branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># tap tap "homebrew/core" tap "homebrew/bundle" tap "homebrew/services" tap "homebrew/cask" tap "homebrew/cask-versions" tap "homebrew/cask-fonts" cask_args appdir: "/Applications" tap "brewsci/science" tap "caskroom/cask" tap "delphinus/sfmono-square" tap "heroku/brew" tap "iyuuya/jimakun" tap "mscharley/homebrew" tap "nektos/tap" tap "neovim/neovim" tap "sanemat/font" tap "tkengo/highway" tap "universal-ctags/universal-ctags" cask "xquartz" brew "mas" brew "readline" brew "libffi" brew "pkg-config" brew "pcre" brew "pcre2" brew "automake" brew "libtool" brew "openssl" brew "curl", args: ["with-openssl"] brew "boost" brew "w3m" brew "universal-ctags" brew "gnu-sed" # for PHP brew "libevent" brew "jpeg" brew "openjpeg" brew "libpng" brew "mcrypt" brew "libxml2" brew "lemon" brew "re2c" brew "git", args: ["with-curl", "with-gettext", "with-openssl", "with-pcre2"] brew "git-cal" brew "git-extras" brew "git-flow" brew "git-lfs" brew "git-now" brew "hub" brew "tig" brew "gibo" brew "gpg" brew "tree" brew "zsh", args: ["without-etcdir"] brew "zsh-completions" brew "reattach-to-user-namespace" brew "tmux" brew "pv" brew "global" brew "nmap" brew "jq" brew "the_silver_searcher" brew "rg" brew "fzf" brew "asciidoc" brew "source-highlight" brew "ccat" brew "colordiff" brew "dfc" brew "direnv" brew "cairo" brew "pango" brew "freetype" brew "fontforge" # brew "graphviz", args: ["with-freetype"] brew "ghostscript" # brew "imagemagick@6", link: true, args: ["with-fontconfig", "with-ghostscript", "with-librsvg", "with-little-cms2", "with-openjpeg", "with-pango", "with-webp"] brew "qt" # brew "qt@5.5", link: true brew "mycli" brew "mysql" brew "postgresql" brew "sqlite" brew "redis" brew "neovim" brew "macvim", args: [ "with-lua", "with-luajit", "with-python3" ] # brew "emacs", args: [ # "with-cocoa", # "with-ctags", # "with-dbus", # "with-gnutls", # "with-imagemagick@6", # "with-librsvg", # "with-mailutils", # "with-modules" # ] # science brew "r" brew "packer" brew "cmatrix" brew "ansible" brew "libyaml" brew "gdbm" brew "docbook" brew "docbook-xsl" brew "bdw-gc" brew "gettext" brew "pixman" brew "cmake" brew "zeromq" brew "czmq" brew "wxmac" brew "erlang" brew "elixir" brew "ffmpeg" brew "gobject-introspection" brew "icu4c" brew "isl" brew "mpfr" brew "libmpc" brew "gcc" brew "geckodriver" brew "heroku" brew "xz" brew "jbig2dec" brew "oniguruma" brew "libgit2" brew "libiconv" brew "libmagic" brew "librsvg" brew "libsodium" brew "libsvg" brew "libsvg-cairo" brew "libxslt" brew "mhash" brew "mono" brew "ncurses" brew "nkf" brew "poppler" brew "pdf2svg" brew "scons" brew "shellcheck" brew "subversion" brew "terminal-notifier" brew "unar" brew "unixodbc" brew "unoconv" brew "watchman" brew "yarn" # tap "sanemat/font" # brew "sanemat/font/ricty" brew "octave" brew "sourcekitten" # cask "iterm2" cask "evernote" cask "firefox" cask "google-chrome" cask "keycastr" cask "licecap" cask "linein" cask "sequel-pro" cask "shoes" cask "virtualbox" cask "virtualbox-extension-pack" cask "vagrant" cask "vlc" cask "wireshark" cask "dropbox" cask "slack" cask "macpass" cask "font-sourcecodepro-nerd-font" cask "font-sourcecodepro-nerd-font-mono" brew "act" brew "adns" brew "aom" brew "apr" brew "apr-util" brew "arpack" brew "aws-shell" brew "awscli" brew "bison" brew "brotli" brew "c-ares" brew "carthage" brew "cscope" brew "csfml" brew "doxygen" brew "editorconfig" brew "eigen" brew "elinks" brew "embulk" brew "epstool" brew "fig2dev" brew "flac" brew "fltk" brew "fontconfig" brew "frei0r" brew "fribidi" brew "fswatch" brew "fx" brew "gd" brew "gdk-pixbuf" brew "ghc" brew "ghostscript" brew "ghq" brew "giflib" brew "gifsicle" brew "git-quick-stats" brew "git-subrepo" brew "gitleaks" brew "gl2ps" brew "glfw" brew "glib" brew "glpk" brew "gmp" brew "gnu-getopt" brew "gnu-tar" brew "gnupg" brew "gnuplot" brew "go" brew "gperftools" brew "graphicsmagick" brew "graphite2" brew "graphviz" brew "grep" brew "gtk-doc" brew "gts" brew "harfbuzz" brew "hdf5" brew "heroku" brew "heroku-node" brew "highlight" brew "highway" brew "htop" brew "httpd" brew "hubflow" brew "hwloc" brew "icu4c" brew "ilmbase" brew "imagemagick" brew "isl" brew "jansson" brew "jasper" brew "jbig2dec" brew "jemalloc" brew "kpcli" brew "lame" brew "ldns" brew "leptonica" brew "lftp" brew "libass" brew "libassuan" brew "libbluray" brew "libcerf" brew "libcroco" brew "libde265" brew "libev" brew "libgcrypt" brew "libgpg-error" brew "libheif" brew "libidn" brew "libidn2" brew "libksba" brew "libmodplug" brew "libogg" brew "libomp" brew "libsamplerate" brew "libsndfile" brew "libsoxr" brew "libspiro" brew "libssh2" brew "libtasn1" brew "libtermkey" brew "libtiff" brew "libuninameslist" brew "libunistring" brew "libusb" brew "libuv" brew "libvorbis" brew "libvpx" brew "libvterm" brew "libxslt" brew "libyaml" brew "little-cms" brew "little-cms2" brew "llvm@4" brew "lua" brew "luajit" brew "lynx" brew "lz4" brew "lzo" brew "make" brew "media-info" brew "metis" brew "mpfr" brew "msgpack" brew "neovim" brew "netpbm" brew "nettle" brew "nghttp2" brew "nginx" brew "node" brew "npth" brew "nspr" brew "nss" brew "numpy" brew "open-mpi" brew "openblas" brew "opencore-amr" brew "openexr" brew "openssh" brew "opus" brew "p11-kit" brew "pdf2svg" brew "perl" brew "pinentry" brew "pixman" brew "plantuml" brew "plotutils" brew "poppler" brew "portaudio" brew "pstoedit" brew "pwgen" brew "python" brew "python3" brew "python@2" brew "qhull" brew "qrupdate" brew "ranger" brew "ricty" brew "ripgrep" brew "rsync" brew "rtmpdump" brew "rubberband" brew "ruby" brew "rust" brew "scons" brew "sdl2" brew "sdl2_gfx" brew "sdl2_image" brew "sdl2_mixer" brew "sdl2_net" brew "sdl2_ttf" brew "sfml" brew "sfmono-square" brew "shared-mime-info" brew "snappy" brew "speex" brew "sslscan" brew "suite-sparse" brew "szip" brew "tbb" brew "terminal-notifier" brew "tesseract" brew "theora" brew "unar" brew "unbound" brew "unibilium" brew "unixodbc" brew "unoconv" brew "utf8proc" brew "veclibfort" brew "vim" brew "webp" brew "x264" brew "x265" brew "xvid" brew "yq" cask "bdash" cask "dash" cask "font-sourcecodepro-nerd-font" cask "font-sourcecodepro-nerd-font-mono" cask "hammerspoon" cask "karabiner-elements" cask "macpass" cask "mono-mdk" cask "sequel-pro" cask "skitch" cask "vagrant" cask "visual-studio-code" cask "jasper" mas 'Things', id: 904280696
7bfe4e78c268a690dbc65f292263a58d1411769e
[ "Ruby" ]
1
Ruby
iyuuya/brew-config
f146c0cb79621581b0319cb5741ae25739b03fb9
65d647c1c6c32d1d61b1d80ce67f8a266354c5ac
refs/heads/main
<repo_name>mjgaylord94/Chirper<file_sep>/src/components/Header.jsx import React from 'react'; const Header = () => { return ( <div id="header-container" className="row"> <div className="col-md-4"></div> <h1 id="header-title" className="col-md-4"> Chirper </h1> <div className="col-md-4"></div> </div> ) }; export default Header;<file_sep>/src/components/Chirp.jsx import React from 'react'; const Chirp = (props) => { return ( <> <div className="chirp"> <img src={props.chirp.image} alt="egg" width="75px" height="75px"/> <h3>@{props.chirp.username}</h3> <p>{props.chirp.chirpText}</p> </div> </> ); }; export default Chirp;
4d92e2a44560fbed0aa48bd7703e5a780ca8af9b
[ "JavaScript" ]
2
JavaScript
mjgaylord94/Chirper
6223278afae04fbe942afeb2900906a69607c40f
6196c3d872f5ee3b909eee002604445d92ffec4e
refs/heads/master
<repo_name>nchaudry/Practice<file_sep>/README.md # Practice Practice to use github, store python and javascript practice files Eyyy, I'm a fat nerd. I am trying to better myself. <file_sep>/complete-javascript-course-master/3-how-JS-works/starter/script.js /////////////////////////////////////// // Lecture: Hoisting // functions and variables are available before the execution of a script starts - this is Hoisting // functions are already defined before execution // variables are undefined before exectuion //functions hoisting /* calculateAge(1965); function calculateAge(year) { console.log(2016 - year); } //retirement(1965); var retirement = function(year) { console.log(65 - (2018 - year)); }; //variables Hoisting console.log(age); var age = 23; console.log(age); function foo() { console.log(age); var age = 65; console.log(age); } foo(); console.log(age); /////////////////////////////////////// // Lecture: Scoping // where can we access a certain variables // each function creates a scope // lexical scoping - lexically(written) in another function, gets access to scope of outer function // First scoping example var a = 'Hello!'; first(); function first() { var b = 'Hi!'; second(); function second() { var c = 'Hey!'; console.log(a + b + c); } } // Example to show the differece between execution stack and scope chain var a = 'Hello!'; first(); function first() { var b = 'Hi!'; second(); function second() { var c = 'Hey!'; third() } } function third() { var d = 'John'; console.log(a + b + c + d); // this function is not in the scope chain of the others, it is out of the execution stack of that chain } /////////////////////////////////////// // Lecture: The this keyword //console.log(this); calculateAge(1985); function calculateAge(year){ console.log(2018-year); console.log(this); } */ var john = { name: "John", yearOfBirth: 1990, calculateAge: function () { console.log(this); console.log(2018 - this.yearOfBirth); /* function innerFunction() { console.log(this); //Since it is not a method it binds to global. Even if it's in a method. } innerFunction(); */ } } john.calculateAge(); var mike = { name: "Mike", yearOfBirth: 1984 } mike.calculateAge = john.calculateAge; mike.calculateAge(); //this variable only called when method is called.
5cd79b42d43e343f8c132e20a8ad4afe0d9ac82b
[ "Markdown", "JavaScript" ]
2
Markdown
nchaudry/Practice
c260b650cbd7eb3247574a0e4f52405a094e4648
a4db5e6821f32da75dd770c40d9dc7d424e3dd8f
refs/heads/master
<file_sep>package com.donkor.deepnight.ui.fragment import android.graphics.Color import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.donkor.deepnight.R import com.donkor.deepnight.adapter.CommonAdapter import com.donkor.deepnight.mvp.model.bean.CommonBean import com.donkor.deepnight.network.ApiService import kotlinx.android.synthetic.main.fragment_common.* import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.select.Elements /** * 黑丝袜 * Created by donkor on 2017/12/14. */ class StockingsFragment : BaseFragment(), SwipeRefreshLayout.OnRefreshListener { private var mList: ArrayList<CommonBean>? = null override fun onRefresh() { mSwipeRefresh.isRefreshing = false stockingsData(mPage) } private var mPage: Int? = 1 override fun loadData() { if (mList!!.isEmpty()) stockingsData(mPage) } override fun initView() { mSwipeRefresh.setColorSchemeColors(Color.rgb(47, 223, 189)) mSwipeRefresh.setOnRefreshListener(this) mRvCommonList.layoutManager = LinearLayoutManager(context) // mRvCommonList.layoutManager = GridLayoutManager(context, 2) mList = ArrayList() mRvCommonList.addOnScrollListener(object : RecyclerView.OnScrollListener() { var lastVisibleItem: Int? = 0 override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem!! + 1 == mCommomAdapter?.itemCount) { mCommomAdapter?.changeMoreStatus(mCommomAdapter?.LOAD_MORE!!) mPage = mPage!! + 1 stockingsData(mPage) } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView?.layoutManager as LinearLayoutManager //最后一个可见的ITEM lastVisibleItem = layoutManager.findLastVisibleItemPosition() } }) } private fun stockingsData(page: Int?) { Thread(Runnable { val doc: Document = Jsoup.connect(ApiService.BASE_URL + ApiService.Stockings + page) .timeout(defaultTimeout).userAgent(defualtUserAgent).get() val imgSingle: Elements? = doc.getElementsByClass("img_single") imgSingle?.map { it.select("img") } ?.forEach { mCommonBean = CommonBean(it.attr("title"), it.attr("src")) mList!!.add(mCommonBean!!) } activity.runOnUiThread({ mCommomAdapter?.changeMoreStatus(mCommomAdapter?.PULLUP_LOAD_MORE!!) if (mPage != 1) { mRvCommonList.adapter.notifyDataSetChanged() } else { mCommomAdapter = CommonAdapter(activity, mList) mRvCommonList.adapter = mCommomAdapter } }) }).start() } override fun getLayoutResources(): Int { return R.layout.fragment_common } }<file_sep>package com.donkor.deepnight.ui import android.graphics.Typeface import android.os.Bundle import android.os.Handler import android.os.Message import android.support.v7.app.AppCompatActivity import android.view.WindowManager import com.donkor.deepnight.R import com.donkor.deepnight.utils.switchActivity import kotlinx.android.synthetic.main.activity_splash.* import java.lang.ref.WeakReference /** * 启动页 */ private val SWITCH_MAINACTIVITY = 1000//跳转到主界面 private val TAG: String? = "SplashActivity" class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //设置全屏 window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_splash) initView() MyHandler(this).sendEmptyMessageDelayed(SWITCH_MAINACTIVITY, 1000) } private class MyHandler(activity: SplashActivity) : Handler() { private val mActivity: WeakReference<SplashActivity> = WeakReference(activity) override fun handleMessage(msg: Message) { if (mActivity.get() == null) { return } val activity = mActivity.get() when (msg.what) { SWITCH_MAINACTIVITY -> { // Log.e(TAG, "SplashActivity --- switch_MainActivity") activity!!.switchActivity<MainActivity>() activity.finish() } else -> { } } } } private fun initView() { val font: Typeface = Typeface.createFromAsset(this.assets, "fonts/Lobster-1.4.otf") tv_splash_instruction.typeface = font tv_splash_instruction.text = getString(R.string.splash_activity_splash_instruction) } override fun onDestroy() { // Remove all Runnable and Message. MyHandler(this).removeCallbacksAndMessages(null) super.onDestroy() } }<file_sep>package com.donkor.deepnight.utils import android.app.Activity import android.content.Context import android.content.Intent import android.view.Gravity import android.widget.Toast //import io.reactivex.Observable //import io.reactivex.android.schedulers.AndroidSchedulers //import io.reactivex.schedulers.Schedulers /** * Created by donkor on 2017/12/11. */ fun Context.showToast(message: String): Toast { var toast: Toast = Toast.makeText(this, message, Toast.LENGTH_SHORT) toast.setGravity(Gravity.CENTER, 0, 0) toast.show() return toast } inline fun <reified T : Activity?> Activity.switchActivity() { val intent = Intent(this, T::class.java) startActivity(intent) } <file_sep>package com.donkor.deepnight.ui.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.donkor.deepnight.adapter.CommonAdapter import com.donkor.deepnight.mvp.model.bean.CommonBean /** * * Created by Donkor on 2017/12/13. */ abstract class BaseFragment : Fragment() { protected val defaultTimeout: Int = 3000 protected val defualtUserAgent = "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52" protected var mCommomAdapter: CommonAdapter? = null protected var mCommonBean: CommonBean? = null var rootView: View? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (rootView == null) { rootView = inflater?.inflate(getLayoutResources(), container, false) } return rootView } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden) loadData() } abstract fun getLayoutResources(): Int abstract fun initView() abstract fun loadData() } <file_sep>package com.donkor.deepnight.ui import android.graphics.Typeface import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.View import com.donkor.deepnight.R import com.donkor.deepnight.ui.fragment.* import com.donkor.deepnight.utils.switchActivity import com.gyf.barlibrary.ImmersionBar import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.toolbar_layout.* /** * 主页面 */ private val TAG: String? = "MainActivity" class MainActivity : AppCompatActivity() { private var allFragment: AllFragment? = null private var bosomFragment: BosomFragment? = null private var stockingFragment: StockingsFragment? = null private var buttocksFragment: ButtocksFragment? = null private var legsFragment: LegsFragment? = null private var prettyFragment: PrettyFragment? = null private var hodgepodgeFragment: HodgepodgeFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ImmersionBar.with(this).transparentBar().barAlpha(0.6f).fitsSystemWindows(true).init() val window = window val params = window.attributes params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION window.attributes = params /*设置ActionBar*/ setActionBar() /*设置Drawerlayout开关*/ setDrawerToggle() /*设置监听器*/ setListener() /*设置ToolBar标题*/ initToolBar() initFragment(savedInstanceState) } private fun initFragment(savedInstanceState: Bundle?) { if (savedInstanceState != null) { //异常情况 val mFragments: List<Fragment> = supportFragmentManager.fragments for (item in mFragments) { if (item is AllFragment) { allFragment = item } if (item is BosomFragment) { bosomFragment = item } if (item is StockingsFragment) { stockingFragment = item } if (item is ButtocksFragment) { buttocksFragment = item } if (item is LegsFragment) { legsFragment = item } if (item is PrettyFragment) { prettyFragment = item } if (item is HodgepodgeFragment) { hodgepodgeFragment = item } } } else { allFragment = AllFragment() bosomFragment = BosomFragment() stockingFragment = StockingsFragment() buttocksFragment = ButtocksFragment() legsFragment = LegsFragment() prettyFragment = PrettyFragment() hodgepodgeFragment = HodgepodgeFragment() val fragmentTrans = supportFragmentManager.beginTransaction() fragmentTrans.add(R.id.fl_content, allFragment) fragmentTrans.add(R.id.fl_content, bosomFragment) fragmentTrans.add(R.id.fl_content, stockingFragment) fragmentTrans.add(R.id.fl_content, buttocksFragment) fragmentTrans.add(R.id.fl_content, legsFragment) fragmentTrans.add(R.id.fl_content, prettyFragment) fragmentTrans.add(R.id.fl_content, hodgepodgeFragment) fragmentTrans.commit() } supportFragmentManager.beginTransaction().show(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } /*设置ActionBar*/ private fun setActionBar() { toolbar.title = "" setSupportActionBar(toolbar) /*显示Home图标*/ supportActionBar!!.setDisplayHomeAsUpEnabled(true) } /*设置Drawerlayout的开关,并且和Home图标联动*/ private fun setDrawerToggle() { val mToggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, 0, 0) drawer_layout.addDrawerListener(mToggle) /*同步drawerlayout的状态*/ mToggle.syncState() } /*设置监听器*/ private fun setListener() { nav_view.setNavigationItemSelectedListener { item -> when (item.itemId) { R.id.nav_item_all -> { //所有 tv_bar_title.text = resources.getString(R.string.main_activity_item_all) supportFragmentManager.beginTransaction().show(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_bosom -> { //大胸妹 tv_bar_title.text = resources.getString(R.string.main_activity_item_bosom) supportFragmentManager.beginTransaction().show(bosomFragment) .hide(allFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_buttocks -> { //小翘臀 tv_bar_title.text = resources.getString(R.string.main_activity_item_buttocks) supportFragmentManager.beginTransaction().show(buttocksFragment) .hide(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(legsFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_stockings -> { //黑丝袜 tv_bar_title.text = resources.getString(R.string.main_activity_item_stockings) supportFragmentManager.beginTransaction().show(stockingFragment) .hide(allFragment) .hide(bosomFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_legs -> { //美腿控 tv_bar_title.text = resources.getString(R.string.main_activity_item_legs) supportFragmentManager.beginTransaction().show(legsFragment) .hide(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(prettyFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_pretty -> { //有颜值 tv_bar_title.text = resources.getString(R.string.main_activity_item_pretty) supportFragmentManager.beginTransaction().show(prettyFragment) .hide(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(hodgepodgeFragment) .commit() } R.id.nav_item_hodgepodge -> { //大杂烩 tv_bar_title.text = resources.getString(R.string.main_activity_item_hodgepodge) supportFragmentManager.beginTransaction().show(hodgepodgeFragment) .hide(allFragment) .hide(bosomFragment) .hide(stockingFragment) .hide(buttocksFragment) .hide(legsFragment) .hide(prettyFragment) .commit() } R.id.nav_item_about -> { switchActivity<AboutActivity>() } } drawer_layout.closeDrawer(GravityCompat.START) true } } /*设置ToolBar标题*/ private fun initToolBar() { tv_bar_title.typeface = Typeface.createFromAsset(this.assets, "fonts/Lobster-1.4.otf") tv_bar_title.text = resources.getString(R.string.main_activity_item_all) } } // private class MyHandler(activity: SplashActivity) : Handler() { // private val mActivity: WeakReference<SplashActivity> = WeakReference(activity) // // override fun handleMessage(msg: Message) { // if (mActivity.get() == null) { // return // } // when (msg.what) { // SWITCH_MAINACTIVITY -> { // Log.e(TAG, "SplashActivity --- switch_MainActivity") // } // else -> { // } // } // } // } // override fun onClick(v: View?) { // clearState() // when (v?.id) { // R.id.rb_home -> { // rb_home.isChecked = true // rb_home.setTextColor(ContextCompat.getColor(applicationContext,R.color.black)) // } // R.id.rb_find -> { // rb_find.isChecked = true // rb_find.setTextColor(ContextCompat.getColor(applicationContext,R.color.black)) // } // R.id.rb_hot -> { // rb_hot.isChecked = true // rb_hot.setTextColor(ContextCompat.getColor(applicationContext,R.color.black)) // } // R.id.rb_mine -> { // rb_mine.isChecked = true // rb_mine.setTextColor(ContextCompat.getColor(applicationContext,R.color.black)) // } // } // } //}<file_sep>package com.donkor.deepnight.ui; import android.animation.Animator; import android.animation.ValueAnimator; import android.os.Build; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DecodeFormat; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.donkor.deepnight.R; import com.wingsofts.dragphotoview.DragPhotoView; import java.util.ArrayList; import java.util.List; public class DragPhotoActivity extends AppCompatActivity { private ViewPager mViewPager; private LinearLayout mLinDownloadPic; private List<String> mList; private DragPhotoView[] mPhotoViews; // int mOriginLeft; // int mOriginTop; int mOriginHeight; int mOriginWidth; int mOriginCenterX; int mOriginCenterY; private float mTargetHeight; private float mTargetWidth; private float mScaleX; private float mScaleY; private float mTranslationX; private float mTranslationY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_drag_photo); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary)); } mViewPager = (ViewPager) findViewById(R.id.viewpager); mList = new ArrayList<>(); mList.add("path"); mPhotoViews = new DragPhotoView[mList.size()]; for (int i = 0; i < mPhotoViews.length; i++) { mPhotoViews[i] = (DragPhotoView) View.inflate(this, R.layout.item_viewpager, null); Glide.with(this).load(getIntent().getStringExtra("picUrl")) .asBitmap() .format(DecodeFormat.PREFER_ARGB_8888) .diskCacheStrategy(DiskCacheStrategy.ALL) .placeholder(R.mipmap.ic_image_loading) .error(R.mipmap.ic_empty_picture) .into(mPhotoViews[i]); // mPhotoViews[i].setImageResource(R.drawable.wugeng); mPhotoViews[i].setOnTapListener(new DragPhotoView.OnTapListener() { @Override public void onTap(DragPhotoView view) { finishWithAnimation(); } }); mPhotoViews[i].setOnExitListener(new DragPhotoView.OnExitListener() { @Override public void onExit(DragPhotoView view, float x, float y, float w, float h) { performExitAnimation(view, x, y, w, h); } }); } mViewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return mList.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mPhotoViews[position]); return mPhotoViews[position]; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mPhotoViews[position]); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }); mViewPager.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this); // mOriginLeft = getIntent().getIntExtra("left", 0); // mOriginTop = getIntent().getIntExtra("top", 0); mOriginHeight = getIntent().getIntExtra("height", 0); mOriginWidth = getIntent().getIntExtra("width", 0); mOriginCenterX = mOriginWidth / 2; mOriginCenterY = mOriginHeight / 2; // mOriginCenterX = mOriginLeft + mOriginWidth / 2; // mOriginCenterY = mOriginTop + mOriginHeight / 2; int[] location = new int[2]; final DragPhotoView photoView = mPhotoViews[0]; photoView.getLocationOnScreen(location); mTargetHeight = (float) photoView.getHeight(); mTargetWidth = (float) photoView.getWidth(); mScaleX = (float) mOriginWidth / mTargetWidth; mScaleY = (float) mOriginHeight / mTargetHeight; float targetCenterX = location[0] + mTargetWidth / 2; float targetCenterY = location[1] + mTargetHeight / 2; mTranslationX = mOriginCenterX - targetCenterX; mTranslationY = mOriginCenterY - targetCenterY; photoView.setTranslationX(mTranslationX); photoView.setTranslationY(mTranslationY); photoView.setScaleX(mScaleX); photoView.setScaleY(mScaleY); performEnterAnimation(); for (int i = 0; i < mPhotoViews.length; i++) { mPhotoViews[i].setMinScale(mScaleX); } } }); } /** * =================================================================================== * <p> * 底下是低版本"共享元素"实现 不需要过分关心 如有需要 可作为参考. * <p> * Code under is shared transitions in all android versions implementation */ private void performExitAnimation(final DragPhotoView view, float x, float y, float w, float h) { view.finishAnimationCallBack(); float viewX = mTargetWidth / 2 + x - mTargetWidth * mScaleX / 2; float viewY = mTargetHeight / 2 + y - mTargetHeight * mScaleY / 2; view.setX(viewX); view.setY(viewY); float centerX = view.getX() + mOriginWidth / 2; float centerY = view.getY() + mOriginHeight / 2; float translateX = mOriginCenterX - centerX; float translateY = mOriginCenterY - centerY; ValueAnimator translateXAnimator = ValueAnimator.ofFloat(view.getX(), view.getX() + translateX); translateXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { view.setX((Float) valueAnimator.getAnimatedValue()); } }); translateXAnimator.setDuration(300); translateXAnimator.start(); ValueAnimator translateYAnimator = ValueAnimator.ofFloat(view.getY(), view.getY() + translateY); translateYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { view.setY((Float) valueAnimator.getAnimatedValue()); } }); translateYAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { animator.removeAllListeners(); finish(); overridePendingTransition(0, 0); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); translateYAnimator.setDuration(300); translateYAnimator.start(); } private void finishWithAnimation() { final DragPhotoView photoView = mPhotoViews[0]; ValueAnimator translateXAnimator = ValueAnimator.ofFloat(0, mTranslationX); translateXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setX((Float) valueAnimator.getAnimatedValue()); } }); translateXAnimator.setDuration(300); translateXAnimator.start(); ValueAnimator translateYAnimator = ValueAnimator.ofFloat(0, mTranslationY); translateYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setY((Float) valueAnimator.getAnimatedValue()); } }); translateYAnimator.setDuration(300); translateYAnimator.start(); ValueAnimator scaleYAnimator = ValueAnimator.ofFloat(1, mScaleY); scaleYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setScaleY((Float) valueAnimator.getAnimatedValue()); } }); scaleYAnimator.setDuration(300); scaleYAnimator.start(); ValueAnimator scaleXAnimator = ValueAnimator.ofFloat(1, mScaleX); scaleXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setScaleX((Float) valueAnimator.getAnimatedValue()); } }); scaleXAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { animator.removeAllListeners(); finish(); overridePendingTransition(0, 0); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); scaleXAnimator.setDuration(300); scaleXAnimator.start(); } private void performEnterAnimation() { final DragPhotoView photoView = mPhotoViews[0]; ValueAnimator translateXAnimator = ValueAnimator.ofFloat(photoView.getX(), 0); translateXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setX((Float) valueAnimator.getAnimatedValue()); } }); translateXAnimator.setDuration(300); translateXAnimator.start(); ValueAnimator translateYAnimator = ValueAnimator.ofFloat(photoView.getY(), 0); translateYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setY((Float) valueAnimator.getAnimatedValue()); } }); translateYAnimator.setDuration(300); translateYAnimator.start(); ValueAnimator scaleYAnimator = ValueAnimator.ofFloat(mScaleY, 1); scaleYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setScaleY((Float) valueAnimator.getAnimatedValue()); } }); scaleYAnimator.setDuration(300); scaleYAnimator.start(); ValueAnimator scaleXAnimator = ValueAnimator.ofFloat(mScaleX, 1); scaleXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { photoView.setScaleX((Float) valueAnimator.getAnimatedValue()); } }); scaleXAnimator.setDuration(300); scaleXAnimator.start(); } @Override public void onBackPressed() { finishWithAnimation(); } } <file_sep>package com.donkor.deepnight.utils import android.content.Context import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.engine.DiskCacheStrategy import com.donkor.deepnight.R /** * Created by donkor on 2017/12/13. */ class ImageLoadUtils{ companion object { fun display(context: Context?, imageView: ImageView?, url: String?) { if (imageView == null) { throw IllegalArgumentException("argument error") } Glide.with(context).load(url) .diskCacheStrategy(DiskCacheStrategy.ALL) .centerCrop() .placeholder(R.mipmap.ic_image_loading) .error(R.mipmap.ic_empty_picture) .crossFade().into(imageView) } fun displayHigh(context: Context?, imageView: ImageView?, url: String?){ if (imageView == null) { throw IllegalArgumentException("argument error") } Glide.with(context).load(url) .asBitmap() .format(DecodeFormat.PREFER_ARGB_8888) .diskCacheStrategy(DiskCacheStrategy.ALL) .centerCrop() .placeholder(R.mipmap.ic_image_loading) .error(R.mipmap.ic_empty_picture) .into(imageView) } } }<file_sep># DeepNight-in-kotlin DeepNight 陪你度过每一个深夜,妹纸看不停<br> 看够了代码家的妹纸,来看看豆瓣的妹纸<br> # Description 妹纸图片来源:<br> - http://www.dbmeinv.com # Screenshot <img src="https://raw.githubusercontent.com/ChenYXin/DeepNight-in-kotlin/master/Screenshot/splash_pic.png" width=25% height=25% /> <img src="https://raw.githubusercontent.com/ChenYXin/DeepNight-in-kotlin/master/Screenshot/md_pic.png" width=25% height=25% /> <img src="https://raw.githubusercontent.com/ChenYXin/DeepNight-in-kotlin/master/Screenshot/all_pic.png" width=25% height=25% /> <img src="https://raw.githubusercontent.com/ChenYXin/DeepNight-in-kotlin/master/Screenshot/drag_pic.jpeg" width=25% height=25% /> # Features - Material Design设计风格 - [Kotlin中SwipeRefreshLayout结合RecyclerView下拉刷新上拉加载](http://blog.csdn.net/donkor_/article/details/78820880) - [Kotlin实现侧滑抽屉菜单(DrawerLayout+NavigationView+Toolbar)](http://blog.csdn.net/donkor_/article/details/78819081) - [Fragment懒加载模式](http://blog.csdn.net/donkor_/article/details/78819081) - [Kotlin中handler避免内存泄漏](http://blog.csdn.net/donkor_/article/details/78796518) - [jsoup 抓取妹纸图片](https://github.com/jhy/jsoup) - [glide 图片缓存,加载缩略图,加载高清原图](https://github.com/bumptech/glide) - [DragPhotoView高仿微信可拖拽返回PhotoView](https://github.com/githubwing/DragPhotoView) # Download [火速下载](http://fir.im/DeepNight)<br> <img src="https://raw.githubusercontent.com/ChenYXin/DeepNight-in-kotlin/master/Screenshot/download_pic.jpg" /> # Platform MacBook Pro (13-inch, 2016, Four Thunderbolt 3 Ports) - macOS High Sierra(10.13.2) Android Studio - gradle 3.0.2 - kotlin 1.1.51 # About me ❤ 我觉得大家一起学习和交流才会更有意思,如果您觉得我的文章还不错,或是对您有过帮助,欢迎Follow、Fork、Star .咱们大家一起学习,一起交流~~❤ Email :<EMAIL> csdn_blog: http://blog.csdn.net/donkor_ jianshu_blog: http://www.jianshu.com/u/10f35b1d7e12 QQ Group : 537891203 <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=99f75bb45aa9c94b8c8f23e8cafbd4317da0e1f77f7e8936ed39e78266d1b5b2"><img src="http://img.blog.csdn.net/20160919114825097" alt="Android开发交流群" title="Android开发交流群" border="0"></a> # License ``` Copyright (C) 2017 <EMAIL> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` <file_sep>package com.donkor.deepnight.mvp.model.bean /** * Created by donkor on 2017/12/13. */ data class CommonBean(var title:String,var src:String)<file_sep>package com.donkor.deepnight.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo /** *网络工具 * Created by Donkor on 2017/12/13. */ object NetworkUtils { fun isNetConnected(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo return if (networkInfo == null) { false } else { networkInfo.isAvailable && networkInfo.isConnected } } }<file_sep>package com.donkor.deepnight.ui import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import com.donkor.deepnight.R import com.gyf.barlibrary.ImmersionBar import kotlinx.android.synthetic.main.activity_about.* /** * Created by donkor on 2017/12/14. */ class AboutActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ImmersionBar.with(this).transparentBar().barAlpha(0.6f).fitsSystemWindows(true).init() val window = window val params = window.attributes params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION window.attributes = params setContentView(R.layout.activity_about) tvVersion.text = getAppVersionName(this) btnBack.setOnClickListener({ finish() }) } /** * 返回当前程序版本名 */ private fun getAppVersionName(context: Context): String { var versionName: String? = "" try { val pm = context.packageManager val pi = pm.getPackageInfo(context.packageName, 0) versionName = pi.versionName if (versionName == null || versionName.isEmpty()) { return "" } } catch (e: Exception) { Log.e("VersionInfo", "Exception", e) } return versionName.toString() } }<file_sep>package com.donkor.deepnight.adapter import android.app.Activity import android.content.Intent import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import com.donkor.deepnight.R import com.donkor.deepnight.mvp.model.bean.CommonBean import com.donkor.deepnight.ui.DragPhotoActivity import com.donkor.deepnight.utils.ImageLoadUtils /** * Created by donkor on 2017/12/13. */ class CommonAdapter(context: Activity?, list: ArrayList<CommonBean>?) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var mContext: Activity? = null private var mList: ArrayList<CommonBean>? = null private var mInflater: LayoutInflater? = null private val TYPE_ITEM: Int? = 0 private val TYPE_FOOTER: Int? = 1 //上拉加载更多 val PULLUP_LOAD_MORE: Int? = 0 //正在加载中 val LOAD_MORE: Int? = 1 //没有加载更多 隐藏 val NO_LOAD_MORE: Int? = 2 //上拉加载更多状态-默认为0 private var mLoadMoreStatus: Int? = 0 init { mContext = context mList = list mInflater = LayoutInflater.from(context) } override fun getItemCount(): Int { return mList?.size ?: 0 } override fun getItemViewType(position: Int): Int { return if (position + 1 == itemCount) { TYPE_FOOTER!! } else { TYPE_ITEM!! } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? { when (viewType) { TYPE_ITEM -> return CommonHolder(mInflater?.inflate(R.layout.item_common, parent, false)) TYPE_FOOTER -> return FooterViewHolder(mInflater?.inflate(R.layout.load_more, parent, false)) } return null } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { val title: String? = mList?.get(position)?.title if (holder is CommonHolder) { holder.tvTitle.text = title ImageLoadUtils.display(mContext, holder.ivPic, mList?.get(position)?.src) holder.ivPic.setOnClickListener({ startPhotoActivity(mContext, holder.ivPic, mList?.get(position)?.src) }) } else if (holder is FooterViewHolder) { when (mLoadMoreStatus) { PULLUP_LOAD_MORE -> holder.tvLoadText?.text = "上拉加载更多" LOAD_MORE -> holder.tvLoadText?.text = "正在加载更多..." NO_LOAD_MORE -> holder.linLoadLayout?.visibility = View.GONE } } } class CommonHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { var ivPic: ImageView = itemView?.findViewById<ImageView>(R.id.iv_pic) as ImageView var tvTitle: TextView = itemView?.findViewById<TextView>(R.id.tv_title) as TextView } class FooterViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { var pbLoad: ProgressBar? = null var tvLoadText: TextView? = null var linLoadLayout: LinearLayout? = null init { pbLoad = itemView?.findViewById(R.id.pb_load) tvLoadText = itemView?.findViewById(R.id.tv_load_text) linLoadLayout = itemView?.findViewById(R.id.lin_load_layout) } } fun changeMoreStatus(status: Int) { mLoadMoreStatus = status notifyDataSetChanged() } private fun startPhotoActivity(context: Activity?, imageView: ImageView?, picUrl: String?) { val intent = Intent(context, DragPhotoActivity::class.java) intent.putExtra("picUrl", picUrl) intent.putExtra("height", imageView?.height) intent.putExtra("width", imageView?.width) context?.startActivity(intent) context?.overridePendingTransition(0, 0) } }<file_sep>package com.donkor.deepnight.mvp /** * Created by donkor on 2017/12/11. */ <file_sep>package com.donkor.deepnight.network /** * Created by donkor on 2017/12/11. */ interface ApiService { companion object { val BASE_URL: String get() = "https://www.dbmeinv.com/dbgroup/" val ALL_URL: String get() = "show.htm?pager_offset=" val BOSOM: String get() = "show.htm?cid=2&pager_offset=" val Buttocks: String get() = "show.htm?cid=6?pager_offset=" val Stockings: String get() = "show.htm?cid=7&pager_offset=" val Legs: String get() = "show.htm?cid=3&pager_offset=" val Pretty: String get() = "show.htm?cid=4&pager_offset=" val Hodgepodge: String get() = "show.htm?cid=5&pager_offset=" } }
d0a1d506f8fd2d52d58c822d545371384a6caf72
[ "Markdown", "Java", "Kotlin" ]
14
Kotlin
ChenYXin/DeepNight-in-kotlin
9751dec05a08292ed87f523b8796352e5ccf91b0
d7f2f5382433055571d4637875c2865dc412672e
refs/heads/master
<file_sep>var Async = require('../lib/async.js'); //Testing series calls var series = function () { var async = new Async(); async.next(function (next) { var count = 0; console.log('doing step 1'); count++; next({value: "new value"}, count); }); async.next(function (next, paramsFromFirstAsyncNext, count) { console.log('doing step 2'); console.log('using passed params: ' + paramsFromFirstAsyncNext.value + " count: " + count); next(); }); async.next.start(function () { console.log('All done.\n\n'); parallel(); }); }; //Testing parallel calls var parallel = function () { var async = new Async(); var path = require('path'), fs = require('fs'); var filesToUpdate = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'./files/file' + (i + 1) + '.txt'), text: 'New Test Data for file: ' + (i + 1)}) } //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { fs.writeFile(file.path,file.text, function(){ console.log('done updating file: ' + file.path); next(); }); }, filesToUpdate[i]); } async.now.start(function(){ console.log('done with nested async.now\n\n'); combined(); }); }; //Using series and parallel combined and nested. var combined = function() { var async = new Async(); async.next(function series1 (next){ //starting a nested async.next will require all nested async calls to complete before the outer async.next will continue; async.next(function series1Nested1(next){ console.log('done with series1Nested1'); next(); }); async.next(function series1Nested2(next){ console.log('done with series1Nested2'); next(); }); async.next(function series1Nested3(next){ console.log('done with series1Nested3'); //calling next() on the last nested async.next will resume the outer async.next next(); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. console.log('done with series1'); //calling the outer async.next after adding nested async.next calls will start them - the outer async.next will continue after the last nested async.next has been called. next(); }); async.next(function series2 (next){ var path = require('path'), fs = require('fs'); var filesToUpdate = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'./files/file' + (i + 1) + '.txt'), text: 'New Test Data for file: ' + (i + 1)}) } //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { fs.writeFile(file.path,file.text, function(){ console.log('done updating file: ' + file.path); next(); }); }, filesToUpdate[i]); } async.now.start(function(){ console.log('done with nested async.now'); //we need to call the outer next callback for the series2 function to continue our outer async.next series. next(); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. console.log('done with series2'); }); async.next(function series3 (next){ console.log('done with series3'); next(); }); async.next.start(function(){ console.log('all done with combined example.\n\n'); }); }; //start tests series();<file_sep>var assert = require('assert'); var Async = require('../lib/async.js'); var currentTime = new Date(); currentTime = currentTime.toLocaleDateString() + ' ' + currentTime.toLocaleTimeString(); describe("Testing required params",function(){ var async = new Async(); it("Should fail if first param isn't a callback function.", function () { assert.throws(function () { async.next("Not a function."); },"async.next requires the first param to be a callback function."); assert.throws(function () { async.next({value: "also not a function."}); },"async.next requires the first param to be a callback function."); assert.doesNotThrow(function () { async.next(function (next) { },"Should be able to use this function.") }); }) }); describe("Testing series calls",function () { var async = new Async(); var expectedOrder = ['series0','series1','series2', 'series3','seriesComplete']; var actualOrder = []; it("Should run in order of: " + expectedOrder, function (done){ async.next(function series0 (next) { assert.equal(0,actualOrder.push('series0') -1,'series0 should be index 0'); next(); }); async.next(function series1 (next) { assert.equal(1,actualOrder.push('series1') -1,'series1 should be index 1'); next(); }); async.next(function series2 (next) { assert.equal(2,actualOrder.push('series2') -1,'series2 should be index 2'); next(); }); async.next(function series3 (next) { assert.equal(3,actualOrder.push('series3') -1,'series3 should be index 3'); next(); }); async.next.start(function seriesComplete () { assert.equal(4,actualOrder.push('seriesComplete') -1,'seriesComplete should be index 4'); assert.deepEqual(actualOrder,expectedOrder,"actualOrder should match") done(); }); }); }); describe("Testing parallel calls", function(){ var async = new Async(); var path = require('path'), fs = require('fs'); var filesToUpdate = [], filesUpdated = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'../examples/files/file' + (i + 1) + '.txt'), text: 'Updating Data for file: ' + (i + 1) + ' at ' + currentTime}); } it("should update all files from filesToUpdate and add path filesUpdated for testing. Order doesn't matter.", function (done) { //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { fs.writeFile(file.path,file.text, function(err){ filesUpdated.push(file) next(); }); }, filesToUpdate[i]); } async.now.start(function(){ var n, found; for (i=0; i < filesToUpdate.length; i++){ for (n=0; n < filesUpdated.length; n++){ if (filesToUpdate[i].path === filesUpdated[n].path) {found = true; break;} } assert.ok(found,"Doesn't look like we have all the files. async.now doesn't seem to work.") } done(); }); }); }); describe("Using series and parallel combined and nested.", function(){ var async = new Async(), i; var expectedOuterSeries = ['series0', 'series1', 'series2']; var actualOuterSeries = []; var expectedInnerSeries = ['series1Nested0', 'series1Nested1', 'series1Nested2']; var actualInnerSeries = []; describe("Building Outer Layer of async.next calls", function (){ async.next(function series0 (next){ it("Should handle nested async.next in order. Then call next outer async.next", function () { //starting a nested async.next will require all nested async calls to complete before the outer async.next will continue; async.next(function series1Nested0(next){ assert.equal(actualOuterSeries[0],'series0',"We shouldn't get to our nested async.next until the outer async.next has called it's next callback") actualInnerSeries.push('series1Nested0'); next(); }); async.next(function series1Nested1(next){ actualInnerSeries.push('series1Nested1'); next(); }); async.next(function series1Nested2(next){ actualInnerSeries.push('series1Nested2'); for (i=0; i < expectedInnerSeries.length;i++){ assert.equal(actualInnerSeries[i], expectedInnerSeries[i],"Our nested async.next should be called in the same order as defined.") } //calling next() on the last nested async.next will resume the outer async.next next(); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. assert.equal(actualOuterSeries.push('series0') -1,0,"Our outer async.next should be called in the same order that it is defined."); //calling the outer async.next after adding nested async.next calls will start them - the outer async.next will continue after the last nested async.next has been called. next(); }); }); async.next(function series1 (next){ describe("Should handle nested async.now and continue to the next outer async.next when all async.now callbacks have finished.", function(){ var path = require('path'), fs = require('fs'); var filesToUpdate = [], filesUpdated = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'../examples/files/file' + (i + 1) + '.txt'), text: 'Updating Data for file: ' + (i + 1) + ' at ' + currentTime}); } it("should update all files from filesToUpdate and add path filesUpdated for testing. Order doesn't matter.", function (done) { //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { assert.equal(actualOuterSeries[1],'series1','The outer async.next should finish before the first async.now is called.'); fs.writeFile(file.path,file.text, function(){ filesUpdated.push(file); next(); }); }, filesToUpdate[i]); } async.now.start(function(){ var n, found; for (i=0; i < filesToUpdate.length; i++){ for (n=0; n < filesUpdated.length; n++){ if (filesToUpdate[i].path === filesUpdated[n].path) {found = true; break;} } assert.ok(found,"Doesn't look like we have all the files. async.now doesn't seem to work.") } done(); //calling next here will continue to the next outer async.next next(); }); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. assert.equal(actualOuterSeries.push('series1') -1,1,"Our outer async.next should be called in the same order that it is defined."); }); }); async.next(function series2 (next){ assert.equal(actualOuterSeries.push('series2') -1,2,"Our outer async.next should be called in the same order that it is defined."); next(); }); async.next.start(function(){ for (i=0; i < expectedOuterSeries.length; i++){ assert.equal(actualOuterSeries[i],expectedOuterSeries[i],"The outer async.next should be called in the order they were defined.") } }); }); }); describe("Using params on callbacks for async.next.", function () { var async = new Async(), myObj = {id: 0, name: 'Kevin'}; async.next(function(next){ next("string value.", 12, myObj); }); async.next(function(next, param1, param2, param3){ it("Should pass params from async.next callback to the next async.next function.", function(){ assert.equal(param1,"string value.","There was a problem getting the first parameter."); assert.equal(param2, 12, "There was a problem getting the second parameter."); assert.deepEqual(param3, {id: 0, name: 'Kevin'}, "There was a problem getting the third parameter."); }); }); async.next.start() }); describe("Using params on callbacks for async.now.", function () { var async = new Async(), params = [{id: 0, name:'Kevin'}, {id: 1, name: 'Barnett'}], i, updatedParams = []; it("Params to async.now callbacks are passed after callback function and are inserted after next.", function (done) { for (i=0; i < params.length;i++){ async.now(function (next, param, index) { updatedParams[index] = param; next(); }, params[i], i); } async.now.start(function () { assert.deepEqual(updatedParams, params,"Params should be in same order and value."); done(); }); }); });<file_sep>async-next ============= Async callback manager. Use async.now to run a set of functions in parallel or async.next to run in series. ## Install ```` npm install async-next ```` ## Series Example ````js var Async = require('async-next'); var async = new Async(); async.next(function (next) { var count = 0; console.log('doing step 1'); count++; next({value: "new value"}, count); }); async.next(function (next, paramsFromFirstAsyncNext, count) { console.log('doing step 2'); console.log('using passed params: ' + paramsFromFirstAsyncNext.value + " count: " + count); next(); }); async.next.start(function () { console.log('All done.'); }); ```` ## Async Example ````js var async = new Async(); var path = require('path'), fs = require('fs'); var filesToUpdate = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'./files/file' + i + 'txt'), text: 'New Test Data for file: ' + i}) } //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { fs.writeFile(file.path,file.text, function(){ console.log('done updating file: ' + file.path); next(); }); }, filesToUpdate[i]); } async.now.start(function(){ console.log('Done with Async'); }); ```` ## Combined async.next and async.now with nesting ````js var async = new Async(); async.next(function series1 (next){ //starting a nested async.next will require all nested async calls to complete before the outer async.next will continue; async.next(function series1Nested1(next){ console.log('done with series1Nested1'); next(); }); async.next(function series1Nested2(next){ console.log('done with series1Nested2'); next(); }); async.next(function series1Nested3(next){ console.log('done with series1Nested3'); //calling next() on the last nested async.next will resume the outer async.next next(); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. console.log('done with series1'); //calling the outer async.next after adding nested async.next calls will start them - the outer async.next will continue after the last nested async.next has been called. next(); });//end async.next series1 async.next(function series2 (next){ var path = require('path'), fs = require('fs'); var filesToUpdate = [], i; //build file array to use as test update for (i=0; i < 3; i++) { filesToUpdate.push({path: path.join(__dirname,'./files/file' + i + 'txt'), text: 'New Test Data for file: ' + i}) } //now run async update for (i=0; i < filesToUpdate.length; i++){ async.now(function (next, file) { fs.writeFile(file.path,file.text, function(){ console.log('done updating file: ' + file.path); next(); }); }, filesToUpdate[i]); } async.now.start(function(){ console.log('done with nested async.now'); //we need to call the outer next callback for the series2 function to continue our outer async.next series. next(); }); //all nested async.next or async.now calls are started on nextTick. That means their parent function will complete before they start. console.log('done with series2'); });//end async.next series2 async.next(function series3 (next){ console.log('done with series3'); next(); });//end async.next series3 async.next.start(function(){ console.log('all done with combined example.\n\n'); }); ```` ## License [MIT](LICENSE)
a19e9dd04fb670c1a5b559448927b37380ee9f54
[ "JavaScript", "Markdown" ]
3
JavaScript
kbscript/async-next
fe81361741dcf3897f5718808c85c0b3ca53139f
cf8716e0e9897d284897397f40c558ae247ce54a
refs/heads/master
<repo_name>rootfs-analytics/gfarm-fs<file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8/contrib/mount.gfarm2fs/umount.hpci #!/bin/sh ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } u=`gfwhoami` [ X"$u" = X ] && ABORT 'Who?' groups=`gfgroup -l | grep $u | awk -F: '{print $1}'` for g in $groups do umount.gfarm2fs /gfarm/$g/$u done <file_sep>/gfarm/tags/gfarm_1_1_0_rc1/lib/libgfarm/gfarm/schedule.c #include <stdio.h> /* sprintf */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <gfarm/gfarm.h> #include "gfevent.h" #include "hash.h" #include "host.h" /* gfarm_host_info_address_get() */ #include "auth.h" /* XXX gfarm_random_initialize() */ #include "config.h" #include "gfs_client.h" char GFARM_ERR_NO_REPLICA[] = "no replica"; char GFARM_ERR_NO_HOST[] = "no filesystem node"; /* * data structure which represents information about a host */ #define HOSTS_HASHTAB_SIZE 3079 /* prime number */ struct search_idle_host_state { struct gfarm_host_info *host_info; float loadavg; int flags; #define HOST_STATE_FLAG_RUNNABLE 0x01 #define HOST_STATE_FLAG_LOADAVG_TRIED 0x02 #define HOST_STATE_FLAG_LOADAVG_AVAIL 0x04 #define HOST_STATE_FLAG_AUTH_TRIED 0x08 #define HOST_STATE_FLAG_AUTH_SUCCEED 0x10 }; static void free_hosts_state(int n_all_hosts, struct gfarm_host_info *all_hosts, struct gfarm_hash_table *hosts_state) { gfarm_hash_table_free(hosts_state); gfarm_host_info_free_all(n_all_hosts, all_hosts); } static char * alloc_hosts_state(int *n_all_hostsp, struct gfarm_host_info **all_hostsp, struct gfarm_hash_table **hosts_statep) { char *e; int i, created, n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct gfarm_hash_entry *entry; struct search_idle_host_state *h; e = gfarm_host_info_get_all(&n_all_hosts, &all_hosts); if (e != NULL) return (e); if (n_all_hosts == 0) { gfarm_host_info_free_all(n_all_hosts, all_hosts); return (GFARM_ERR_NO_HOST); } hosts_state = gfarm_hash_table_alloc(HOSTS_HASHTAB_SIZE, gfarm_hash_casefold, gfarm_hash_key_equal_casefold); if (hosts_state == NULL) { gfarm_host_info_free_all(n_all_hosts, all_hosts); return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < n_all_hosts; i++) { entry = gfarm_hash_enter(hosts_state, all_hosts[i].hostname, strlen(all_hosts[i].hostname) + 1, sizeof(struct search_idle_host_state), &created); if (entry == NULL) { free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (GFARM_ERR_NO_MEMORY); } /* `created' must be always true. */ h = gfarm_hash_entry_data(entry); h->host_info = &all_hosts[i]; h->flags = 0; } *n_all_hostsp = n_all_hosts; *all_hostsp = all_hosts; *hosts_statep = hosts_state; return (NULL); } /* * data structure which represents architectures which can run a program */ #define ARCH_SET_HASHTAB_SIZE 31 /* prime number */ #define IS_IN_ARCH_SET(arch, arch_set) \ (gfarm_hash_lookup(arch_set, arch, strlen(arch) + 1) != NULL) #define free_arch_set(arch_set) gfarm_hash_table_free(arch_set) /* Create a set of architectures that the program is registered for */ static char * program_arch_set(char *program, struct gfarm_hash_table **arch_setp) { char *e, *gfarm_file; struct gfarm_path_info pi; struct gfarm_file_section_info *sections; struct gfarm_hash_table *arch_set; int i, nsections, created; e = gfarm_url_make_path(program, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { if (e == GFARM_ERR_NO_SUCH_OBJECT) e = "such program isn't registered"; free(gfarm_file); return (e); } if (!GFARM_S_IS_PROGRAM(pi.status.st_mode)) { gfarm_path_info_free(&pi); free(gfarm_file); return ("specified command is not an executable"); } e = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); gfarm_path_info_free(&pi); free(gfarm_file); if (e != NULL) return ("no binary is registered as the specified command"); arch_set = gfarm_hash_table_alloc(ARCH_SET_HASHTAB_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (arch_set == NULL) { gfarm_file_section_info_free_all(nsections, sections); return (GFARM_ERR_NO_MEMORY); } /* register architectures of the program to `arch_set' */ for (i = 0; i < nsections; i++) { if (gfarm_hash_enter(arch_set, sections[i].section, strlen(sections[i].section) + 1, sizeof(int), &created) == NULL) { free_arch_set(arch_set); gfarm_file_section_info_free_all(nsections, sections); return (GFARM_ERR_NO_MEMORY); } } gfarm_file_section_info_free_all(nsections, sections); *arch_setp = arch_set; return (NULL); } /* * Record whether the host can run the program or cannot */ static char * hosts_for_program(char *program, int *n_all_hostsp, struct gfarm_host_info **all_hostsp, struct gfarm_hash_table **hosts_statep, int *n_runnable_hostsp) { char *e; int n_all_hosts, n_runnable_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct gfarm_hash_table *arch_set; struct gfarm_hash_iterator it; struct gfarm_hash_entry *entry; struct search_idle_host_state *h; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e == NULL) { e = program_arch_set(program, &arch_set); if (e == NULL) { n_runnable_hosts = 0; for (gfarm_hash_iterator_begin(hosts_state, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { entry = gfarm_hash_iterator_access(&it); h = gfarm_hash_entry_data(entry); if (IS_IN_ARCH_SET(h->host_info->architecture, arch_set)) { h->flags |= HOST_STATE_FLAG_RUNNABLE; ++n_runnable_hosts; } } free_arch_set(arch_set); if (n_runnable_hosts > 0) { *n_all_hostsp = n_all_hosts; *all_hostsp = all_hosts; *hosts_statep = hosts_state; *n_runnable_hostsp = n_runnable_hosts; return (NULL); } e = "there is no host which can run the program"; } free_hosts_state(n_all_hosts, all_hosts, hosts_state); } return (e); } /* * search_idle() callback routines to get next hostname */ /* abstract super class (a.k.a. interface class) to get next hostname */ struct get_next_iterator { char *(*get_next)(struct get_next_iterator *); }; /* for "char *" */ struct string_array_iterator { struct get_next_iterator super; char **current; }; static char * get_next_from_string_array(struct get_next_iterator *self) { struct string_array_iterator *iterator = (struct string_array_iterator *)self; return (*iterator->current++); } static struct get_next_iterator * init_string_array_iterator(struct string_array_iterator *iterator, char **strings) { iterator->super.get_next = get_next_from_string_array; iterator->current = strings; return (&iterator->super); } /* for struct gfarm_host_info */ struct host_info_array_iterator { struct get_next_iterator super; struct gfarm_host_info *current; }; static char * get_next_from_host_info_array(struct get_next_iterator *self) { struct host_info_array_iterator *iterator = (struct host_info_array_iterator *)self; return ((iterator->current++)->hostname); } static struct get_next_iterator * init_host_info_array_iterator(struct host_info_array_iterator *iterator, struct gfarm_host_info *hosts) { iterator->super.get_next = get_next_from_host_info_array; iterator->current = hosts; return (&iterator->super); } /* for struct gfarm_file_section_copy_info */ struct section_copy_info_array_iterator { struct get_next_iterator super; struct gfarm_file_section_copy_info *current; }; static char * get_next_from_section_copy_info_array(struct get_next_iterator *self) { struct section_copy_info_array_iterator *iterator = (struct section_copy_info_array_iterator *)self; return ((iterator->current++)->hostname); } static struct get_next_iterator * init_section_copy_info_array_iterator( struct section_copy_info_array_iterator *iterator, struct gfarm_file_section_copy_info *copies) { iterator->super.get_next = get_next_from_section_copy_info_array; iterator->current = copies; return (&iterator->super); } /* abstract super class (a.k.a. interface class) to restrict host */ struct string_filter { int (*suitable)(struct string_filter *self, const char *); }; /* to not restrict anything */ static int always_suitable(struct string_filter *self, const char *string) { return (1); } static struct string_filter null_filter = { always_suitable }; /* to restrict host by domain */ struct domainname_filter { struct string_filter super; const char *domainname; }; static int is_host_in_domain(struct string_filter *self, const char *hostname) { struct domainname_filter *filter = (struct domainname_filter *)self; return (gfarm_host_is_in_domain(hostname, filter->domainname)); } static struct string_filter * init_domainname_filter(struct domainname_filter *filter, const char *domainname) { filter->super.suitable = is_host_in_domain; filter->domainname = domainname; return (&filter->super); } /* to restrict string by string_set */ struct host_runnable_filter { struct string_filter super; struct gfarm_hash_table *hosts_state; }; static int is_host_runnable(struct string_filter *self, const char *host) { struct host_runnable_filter *filter = (struct host_runnable_filter *)self; struct gfarm_hash_entry *entry = gfarm_hash_lookup(filter->hosts_state, host, strlen(host) + 1); struct search_idle_host_state *h; if (entry == NULL) /* never happen, if metadata is consistent */ return (0); h = gfarm_hash_entry_data(entry); return ((h->flags & HOST_STATE_FLAG_RUNNABLE) != 0); } static struct string_filter * init_host_runnable_filter(struct host_runnable_filter *filter, struct gfarm_hash_table *hosts_state) { filter->super.suitable = is_host_runnable; filter->hosts_state = hosts_state; return (&filter->super); } /* * gfarm_client_*_load_*() callback routine which is provided by search_idle() */ #define VIRTUAL_LOAD_FOR_SCHEDULED_HOST 1.0F #define IDLE_LOAD_AVERAGE 0.1F #define SEMI_IDLE_LOAD_AVERAGE 0.5F struct search_idle_available_host { struct search_idle_host_state *host_state; char *hostname; /* used to hold return value */ }; struct search_idle_state { struct gfarm_eventqueue *q; struct search_idle_available_host *available_hosts; int available_hosts_number; int idle_hosts_number; int semi_idle_hosts_number; int concurrency; }; static void search_idle_record_host(struct search_idle_state *s, struct search_idle_host_state *h, char *hostname) { struct search_idle_available_host *ah = &s->available_hosts[s->available_hosts_number++]; float loadavg = h->loadavg; ah->host_state = h; ah->hostname = hostname; /* * We don't use (loadavg / h->host_info->ncpu) to count * semi_idle_hosts here for now, because it is possible * that there is a process which is consuming 100% of * memory or 100% of I/O bandwidth on the host. */ if (loadavg <= SEMI_IDLE_LOAD_AVERAGE) s->semi_idle_hosts_number++; if (loadavg / h->host_info->ncpu <= IDLE_LOAD_AVERAGE) s->idle_hosts_number++; } struct search_idle_callback_closure { struct search_idle_state *state; struct sockaddr peer_addr; struct search_idle_available_host ah; void *protocol_state; }; static void search_idle_load_callback(void *closure) { struct search_idle_callback_closure *c = closure; char *e; struct gfs_client_load load; e = gfs_client_get_load_result_multiplexed(c->protocol_state, &load); if (e == NULL) { c->ah.host_state->flags |= HOST_STATE_FLAG_LOADAVG_AVAIL; c->ah.host_state->loadavg = load.loadavg_1min; search_idle_record_host(c->state, c->ah.host_state, c->ah.hostname); } c->state->concurrency--; free(c); } static void search_idle_connect_callback(void *closure) { struct search_idle_callback_closure *c = closure; char *e; struct gfs_connection *gfs_server; e = gfs_client_connect_result_multiplexed(c->protocol_state, &gfs_server); if (e == NULL) { c->ah.host_state->flags |= HOST_STATE_FLAG_AUTH_SUCCEED; search_idle_record_host(c->state, c->ah.host_state, c->ah.hostname); gfs_client_disconnect(gfs_server); } c->state->concurrency--; free(c); } static void search_idle_load_and_connect_callback(void *closure) { struct search_idle_callback_closure *c = closure; char *e; struct gfs_client_load load; struct gfs_client_connect_state *cs; e = gfs_client_get_load_result_multiplexed(c->protocol_state, &load); if (e == NULL) { c->ah.host_state->flags |= HOST_STATE_FLAG_LOADAVG_AVAIL | HOST_STATE_FLAG_AUTH_TRIED; c->ah.host_state->loadavg = load.loadavg_1min; e = gfs_client_connect_request_multiplexed(c->state->q, c->ah.hostname, &c->peer_addr, search_idle_connect_callback, c, &cs); if (e == NULL) { c->protocol_state = cs; return; /* request continues */ } } c->state->concurrency--; free(c); } static int loadavg_compare(const void *a, const void *b) { const struct search_idle_available_host *aa = a; const struct search_idle_available_host *bb = b; const struct search_idle_host_state *p = aa->host_state; const struct search_idle_host_state *q = bb->host_state; const float l1 = p->loadavg / p->host_info->ncpu; const float l2 = q->loadavg / q->host_info->ncpu; if (l1 < l2) return (-1); else if (l1 > l2) return (1); else return (0); } /* check authentication success or not? */ enum gfarm_schedule_search_mode { GFARM_SCHEDULE_SEARCH_BY_LOADAVG, GFARM_SCHEDULE_SEARCH_BY_LOADAVG_AND_AUTH }; static enum gfarm_schedule_search_mode default_search_method = GFARM_SCHEDULE_SEARCH_BY_LOADAVG_AND_AUTH; void gfarm_schedule_search_mode_use_loadavg(void) { default_search_method = GFARM_SCHEDULE_SEARCH_BY_LOADAVG; } /* * The search will be stopped, if `enough_number' of semi-idle hosts * are found. * * `*nohostsp' is an IN/OUT parameter. * It means desired number of hosts as an INPUT parameter. * It returns available number of hosts as an OUTPUT parameter. */ static char * search_idle(int concurrency, int enough_number, struct gfarm_hash_table *hosts_state, int nihosts, struct string_filter *ihost_filter, struct get_next_iterator *ihost_iterator, int *nohostsp, char **ohosts) { char *e, *ihost; int i, rv, desired_number = *nohostsp; struct search_idle_state s; struct gfarm_hash_entry *entry; struct search_idle_host_state *h; struct search_idle_callback_closure *c; struct sockaddr addr; struct gfs_client_get_load_state *gls; if (nihosts == 0) return (GFARM_ERR_NO_HOST); s.q = gfarm_eventqueue_alloc(); if (s.q == NULL) return (GFARM_ERR_NO_MEMORY); s.available_hosts_number = s.idle_hosts_number = s.semi_idle_hosts_number = 0; s.available_hosts = malloc(nihosts * sizeof(*s.available_hosts)); if (s.available_hosts == NULL) { gfarm_eventqueue_free(s.q); return (GFARM_ERR_NO_MEMORY); } s.concurrency = 0; for (i = 0; i < nihosts; i++) { do { ihost = (*ihost_iterator->get_next)(ihost_iterator); } while (!(*ihost_filter->suitable)(ihost_filter, ihost)); entry = gfarm_hash_lookup(hosts_state, ihost, strlen(ihost) + 1); if (entry == NULL) continue; /* never happen, if metadata is consistent */ h = gfarm_hash_entry_data(entry); if ((h->flags & HOST_STATE_FLAG_LOADAVG_TRIED) != 0) { if ((h->flags & (default_search_method == GFARM_SCHEDULE_SEARCH_BY_LOADAVG ? HOST_STATE_FLAG_LOADAVG_AVAIL : HOST_STATE_FLAG_AUTH_SUCCEED)) != 0) search_idle_record_host(&s, h, ihost); } else { e = gfarm_host_info_address_get(ihost, gfarm_spool_server_port, h->host_info, &addr, NULL); if (e != NULL) continue; /* We limit concurrency here */ rv = 0; while (s.concurrency >= concurrency) { rv = gfarm_eventqueue_turn(s.q, NULL); /* XXX - how to report this error? */ if (rv != 0 && rv != EAGAIN && rv != EINTR) break; } if (rv != 0 && rv != EAGAIN && rv != EINTR) break; c = malloc(sizeof(*c)); if (c == NULL) break; c->state = &s; c->peer_addr = addr; c->ah.host_state = h; c->ah.hostname = ihost; /* record return value */ h->flags |= HOST_STATE_FLAG_LOADAVG_TRIED; e = gfs_client_get_load_request_multiplexed(s.q, &c->peer_addr, default_search_method == GFARM_SCHEDULE_SEARCH_BY_LOADAVG ? search_idle_load_callback : search_idle_load_and_connect_callback, c, &gls); if (e != NULL) { free(c); } else { c->protocol_state = gls; s.concurrency++; } } if (s.idle_hosts_number >= desired_number || s.semi_idle_hosts_number >= enough_number) break; } /* XXX - how to report this error? */ rv = gfarm_eventqueue_loop(s.q, NULL); gfarm_eventqueue_free(s.q); if (s.available_hosts_number == 0) { free(s.available_hosts); *nohostsp = 0; return (GFARM_ERR_NO_HOST); } /* sort hosts in the order of load average */ qsort(s.available_hosts, s.available_hosts_number, sizeof(*s.available_hosts), loadavg_compare); for (i = 0; i < s.available_hosts_number && i < desired_number; i++) ohosts[i] = s.available_hosts[i].hostname; /* return value */ *nohostsp = i; free(s.available_hosts); return (NULL); } /* * shuffle input-hosts before searching to avoid unbalanced search */ /* #define USE_SHUFFLED */ #ifdef USE_SHUFFLED static void shuffle_strings(int n, char **strings) { int i, j; char *tmp; gfarm_random_initialize(); for (i = n - 1; i > 0; --i) { #ifdef HAVE_RANDOM j = random() % (i + 1); #else j = rand()/(RAND_MAX + 1.0) * (i + 1); #endif tmp = strings[i]; strings[i] = strings[j]; strings[j] = tmp; } } static char * search_idle_shuffled(int concurrency, int enough_number, struct gfarm_hash_table *hosts_state, int nihosts, struct string_filter *ihost_filter, struct get_next_iterator *ihost_iterator, int *nohostsp, char **ohosts) { char *e, *ihost, **shuffled_ihosts; int i; struct string_array_iterator host_iterator; if (nihosts == 0) return (GFARM_ERR_NO_HOST); shuffled_ihosts = malloc(nihosts * sizeof(*shuffled_ihosts)); if (shuffled_ihosts == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < nihosts; i++) { do { ihost = (*ihost_iterator->get_next)(ihost_iterator); } while (!(*ihost_filter->suitable)(ihost_filter, ihost)); shuffled_ihosts[i++] = ihost; } shuffle_strings(nihosts, shuffled_ihosts); e = search_idle(concurrency, enough_number, hosts_state, nihosts, &null_filter, init_string_array_iterator(&host_iterator, shuffled_ihosts), nohostsp, ohosts); free(shuffled_ihosts); return (e); } #endif /* USE_SHUFFLED */ void gfarm_strings_expand_cyclic(int nsrchosts, char **srchosts, int ndsthosts, char **dsthosts) { int i, j; for (i = 0, j = 0; i < ndsthosts; i++, j++) { if (j >= nsrchosts) j = 0; dsthosts[i] = srchosts[j]; } } #define CONCURRENCY 10 #define ENOUGH_RATE 4 static char * search_idle_cyclic(struct gfarm_hash_table *hosts_state, int nihosts, struct string_filter *ihost_filter, struct get_next_iterator *ihost_iterator, int nohosts, char **ohosts) { char *e; int nfound = nohosts; #ifdef USE_SHUFFLED e = search_idle_shuffled(CONCURRENCY, nohosts * ENOUGH_RATE, hosts_state, nihosts, ihost_filter, ihost_iterator, &nfound, ohosts); #else e = search_idle(CONCURRENCY, nohosts * ENOUGH_RATE, hosts_state, nihosts, ihost_filter, ihost_iterator, &nfound, ohosts); #endif if (e != NULL) return (e); if (nfound == 0) { /* Oh, my god */ return (GFARM_ERR_NO_HOST); } if (nohosts > nfound) gfarm_strings_expand_cyclic(nfound, ohosts, nohosts - nfound, &ohosts[nfound]); return (NULL); } /* * Select 'nohosts' hosts among 'nihosts' ihosts in the order of * load average, and return to 'ohosts'. * When enough number of hosts are not available, the available hosts * will be listed in the cyclic manner. * NOTE: all of ihosts[] must be canonical hostnames. */ char * gfarm_schedule_search_idle_hosts( int nihosts, char **ihosts, int nohosts, char **ohosts) { char *e; int n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct string_array_iterator host_iterator; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) return (e); e = search_idle_cyclic(hosts_state, nihosts, &null_filter, init_string_array_iterator(&host_iterator, ihosts), nohosts, ohosts); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } char * gfarm_schedule_search_idle_by_all(int nohosts, char **ohosts) { char *e; int n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_info_array_iterator host_iterator; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) return (e); e = search_idle_cyclic(hosts_state, n_all_hosts, &null_filter, init_host_info_array_iterator(&host_iterator, all_hosts), nohosts, ohosts); if (e == NULL) e = gfarm_fixedstrings_dup(nohosts, ohosts, ohosts); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } /* * lists host names that contains domainname. */ char * gfarm_schedule_search_idle_by_domainname(const char *domainname, int nohosts, char **ohosts) { char *e; int i, nhosts, n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_info_array_iterator host_iterator; struct domainname_filter domain_filter; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) return (e); nhosts = 0; for (i = 0; i < n_all_hosts; i++) { if (gfarm_host_is_in_domain(all_hosts[i].hostname, domainname)) ++nhosts; } e = search_idle_cyclic(hosts_state, nhosts, init_domainname_filter(&domain_filter, domainname), init_host_info_array_iterator(&host_iterator, all_hosts), nohosts, ohosts); if (e == NULL) e = gfarm_fixedstrings_dup(nohosts, ohosts, ohosts); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } char * gfarm_schedule_search_idle_acyclic_by_domainname(const char *domainname, int *niohosts, char **ohosts) { char *e; int i, nhosts, n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_info_array_iterator host_iterator; struct domainname_filter domain_filter; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) return (e); nhosts = 0; for (i = 0; i < n_all_hosts; i++) { if (gfarm_host_is_in_domain(all_hosts[i].hostname, domainname)) ++nhosts; } e = search_idle(CONCURRENCY, *niohosts * ENOUGH_RATE, hosts_state, nhosts, init_domainname_filter(&domain_filter, domainname), init_host_info_array_iterator(&host_iterator, all_hosts), niohosts, ohosts); if (e == NULL) e = gfarm_fixedstrings_dup(*niohosts, ohosts, ohosts); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } char * gfarm_schedule_search_idle_by_program(char *program, int nohosts, char **ohosts) { char *e; int n_all_hosts, n_runnable_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_info_array_iterator host_iterator; struct host_runnable_filter host_filter; if (!gfarm_is_url(program)) return (gfarm_schedule_search_idle_by_all(nohosts, ohosts)); e = hosts_for_program(program, &n_all_hosts, &all_hosts, &hosts_state, &n_runnable_hosts); if (e != NULL) return (e); e = search_idle_cyclic(hosts_state, n_runnable_hosts, init_host_runnable_filter(&host_filter, hosts_state), init_host_info_array_iterator(&host_iterator, all_hosts), nohosts, ohosts); if (e == NULL) e = gfarm_fixedstrings_dup(nohosts, ohosts, ohosts); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } /* * Return GFARM_ERR_NO_HOST, if there is a replica, but there isn't * any host which satisfies the hostname_filter. */ static char * search_idle_by_section_copy_info(struct gfarm_hash_table *hosts_state, int ncopies, struct gfarm_file_section_copy_info *copies, struct string_filter *hostname_filter, int nohosts, char **ohosts) { char *e; int i, nhosts; struct section_copy_info_array_iterator copy_iterator; struct gfarm_hash_entry *entry; struct search_idle_host_state *h; nhosts = 0; for (i = 0; i < ncopies; i++) { if ((*hostname_filter->suitable)(hostname_filter, copies[i].hostname)) nhosts++; } if (nhosts == 0) return (GFARM_ERR_NO_HOST); e = search_idle_cyclic(hosts_state, nhosts, hostname_filter, init_section_copy_info_array_iterator(&copy_iterator, copies), nohosts, ohosts); if (e == NULL) { e = gfarm_fixedstrings_dup(nohosts, ohosts, ohosts); if (e == NULL) { /* increase the load average of scheduled hosts */ for (i = 0; i < nohosts; i++) { entry = gfarm_hash_lookup(hosts_state, ohosts[i], strlen(ohosts[i]) + 1); if (entry == NULL) continue; /* shouldn't happen */ h = gfarm_hash_entry_data(entry); h->loadavg += VIRTUAL_LOAD_FOR_SCHEDULED_HOST; } } } return (e); } /* * Return GFARM_ERR_NO_HOST, if there is a replica, but there isn't * any host which satisfies the hostname_filter. */ static char * schedule_by_file_section(struct gfarm_hash_table *hosts_state, char *gfarm_file, char *section, struct string_filter *hostname_filter, int nohosts, char **ohosts) { char *e; int ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); e = ncopies == 0 ? GFARM_ERR_NO_REPLICA : search_idle_by_section_copy_info(hosts_state, ncopies, copies, hostname_filter, nohosts, ohosts); gfarm_file_section_copy_info_free_all(ncopies, copies); return (e); } char * gfarm_file_section_host_schedule(char *gfarm_file, char *section, char **hostp) { char *e; int n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) return (e); e = schedule_by_file_section(hosts_state, gfarm_file, section, &null_filter, 1, hostp); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } char * gfarm_file_section_host_schedule_by_program(char *gfarm_file, char *section, char *program, char **hostp) { char *e; int n_all_hosts, n_runnable_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_runnable_filter host_filter; struct host_info_array_iterator host_iterator; if (!gfarm_is_url(program)) return (gfarm_file_section_host_schedule(gfarm_file, section, hostp)); e = hosts_for_program(program, &n_all_hosts, &all_hosts, &hosts_state, &n_runnable_hosts); if (e != NULL) return (e); e = schedule_by_file_section(hosts_state, gfarm_file, section, init_host_runnable_filter(&host_filter, hosts_state), 1, hostp); if (e == GFARM_ERR_NO_HOST) { e = search_idle_cyclic(hosts_state, n_runnable_hosts, init_host_runnable_filter(&host_filter, hosts_state), init_host_info_array_iterator(&host_iterator, all_hosts), 1, hostp); if (e == NULL) e = gfarm_fixedstrings_dup(1, hostp, hostp); } free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } char * gfarm_file_section_host_schedule_with_priority_to_local( char *gfarm_file, char *section, char **hostp) { char *e, *host, *self_name; int n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; int i, ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); if (ncopies == 0) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (GFARM_ERR_NO_REPLICA); } /* choose/schedule local one, if possible */ e = gfarm_host_get_canonical_self_name(&self_name); if (e != NULL) { i = ncopies; } else { for (i = 0; i < ncopies; i++) if (strcasecmp(self_name, copies[i].hostname) == 0) break; } if (i < ncopies) { /* * local host is found in a list of 'copies', but it * is necessary to make sure 'gfsd' is running or not. */ e = gfarm_schedule_search_idle_hosts( 1, &copies[i].hostname, 1, &host); if (e != NULL) { /* 'gfsd' is not running. */ i = ncopies; } } if (i == ncopies) { e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) goto free_copies; e = search_idle_by_section_copy_info(hosts_state, ncopies, copies, &null_filter, 1, &host); free_hosts_state(n_all_hosts, all_hosts, hosts_state); if (e != NULL) goto free_copies; } e = gfarm_fixedstrings_dup(1, &host, &host); free_copies: gfarm_file_section_copy_info_free_all(ncopies, copies); if (e == NULL) *hostp = host; return (e); } static char * url_hosts_schedule_filtered(struct gfarm_hash_table *hosts_state, char *gfarm_url, char *option, int nihosts, struct string_filter *ihost_filter, struct get_next_iterator *ihost_iterator, int *nhostsp, char ***hostsp) { char *e, *gfarm_file, **hosts, **residual; int i, nfrags, shortage; char section[GFARM_INT32STRLEN + 1]; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); hosts = malloc(sizeof(char *) * nfrags); if (hosts == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } shortage = 0; for (i = 0; i < nfrags; i++) { sprintf(section, "%d", i); e = schedule_by_file_section(hosts_state, gfarm_file, section, ihost_filter, 1, &hosts[i]); if (e == GFARM_ERR_NO_HOST) { hosts[i] = NULL; shortage++; continue; } if (e != NULL) { gfarm_strings_free_deeply(i, hosts); free(gfarm_file); return (e); } } if (shortage > 0) { residual = malloc(shortage * sizeof(*residual)); if (residual == NULL) { gfarm_strings_free_deeply(nfrags, hosts); free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } e = search_idle_cyclic(hosts_state, nihosts, ihost_filter, ihost_iterator, shortage, residual); if (e == NULL) e = gfarm_fixedstrings_dup(shortage,residual,residual); if (e != NULL) { free(residual); gfarm_strings_free_deeply(nfrags, hosts); free(gfarm_file); return (e); } for (i = 0; i < nfrags; i++) { if (hosts[i] == NULL) { hosts[i] = residual[--shortage]; if (shortage == 0) break; } } free(residual); } *nhostsp = nfrags; *hostsp = hosts; free(gfarm_file); return (e); } char * gfarm_url_hosts_schedule(const char *gfarm_url, char *option, int *nhostsp, char ***hostsp) { char *e, *gfarm_file, **hosts; int i, nfrags, n_all_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; char section[GFARM_INT32STRLEN + 1]; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); hosts = malloc(sizeof(char *) * nfrags); if (hosts == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } e = alloc_hosts_state(&n_all_hosts, &all_hosts, &hosts_state); if (e != NULL) { free(hosts); free(gfarm_file); return (e); } for (i = 0; i < nfrags; i++) { sprintf(section, "%d", i); e = schedule_by_file_section(hosts_state, gfarm_file, section, &null_filter, 1, &hosts[i]); if (e != NULL) { free_hosts_state(n_all_hosts, all_hosts, hosts_state); gfarm_strings_free_deeply(i, hosts); free(gfarm_file); return (e); } } free_hosts_state(n_all_hosts, all_hosts, hosts_state); free(gfarm_file); *nhostsp = nfrags; *hostsp = hosts; return (NULL); } char * gfarm_url_hosts_schedule_by_program( char *gfarm_url, char *program, char *option, int *nhostsp, char ***hostsp) { char *e; int n_all_hosts, n_runnable_hosts; struct gfarm_host_info *all_hosts; struct gfarm_hash_table *hosts_state; struct host_runnable_filter host_filter; struct host_info_array_iterator host_iterator; if (!gfarm_is_url(program)) return (gfarm_url_hosts_schedule(gfarm_url, option, nhostsp, hostsp)); e = hosts_for_program(program, &n_all_hosts, &all_hosts, &hosts_state, &n_runnable_hosts); if (e != NULL) return (e); e = url_hosts_schedule_filtered(hosts_state, gfarm_url, option, n_runnable_hosts, init_host_runnable_filter(&host_filter, hosts_state), init_host_info_array_iterator(&host_iterator, all_hosts), nhostsp, hostsp); free_hosts_state(n_all_hosts, all_hosts, hosts_state); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/server.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <gssapi.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #include "gfutil.h" #include "tcputil.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_auth.h" #include "gfarm_secure_session.h" #include "misc.h" #include "scarg.h" static char *hostname = NULL; static int ParseArgs(argc, argv) int argc; char *argv[]; { int c; while ((c = getopt(argc, argv, "h:" COMMON_OPTIONS)) != -1) { switch (c) { case 'h': hostname = optarg; break; default: if (HandleCommonOptions(c, optarg) != 0) return -1; break; } } if (optind < argc) { fprintf(stderr, "unknown extra argument %s\n", argv[optind]); return -1; } return 0; } void doServer(int fd, char *host, int port, gss_cred_id_t myCred, char *acceptorNameString, gss_OID acceptorNameType); int main(argc, argv) int argc; char *argv[]; { int bindFd = -1; struct sockaddr_in remote; int remLen = sizeof(struct sockaddr_in); int fd = -1; OM_uint32 majStat, minStat; unsigned long int rAddr; char *rHost; char myHostname[4096]; gss_cred_id_t myCred; if (ParseArgs(argc, argv) != 0) { return 1; } if (hostname == NULL) { if (gethostname(myHostname, 4096) < 0) { perror("gethostname"); return 1; } hostname = myHostname; } gflog_auth_set_verbose(1); if (gfarmSecSessionInitializeBoth(NULL, NULL, NULL, &majStat, &minStat) <= 0) { fprintf(stderr, "can't initialize as both role because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); gfarmSecSessionFinalizeBoth(); return 1; } if (!acceptorSpecified) { myCred = GSS_C_NO_CREDENTIAL; acceptorNameString = malloc(sizeof("host@") + strlen(hostname)); if (acceptorNameString == NULL) { fprintf(stderr, "no memory\n"); return 1; } sprintf(acceptorNameString, "host@%s", hostname); acceptorNameType = GSS_C_NT_HOSTBASED_SERVICE; } else { char *credName; if (gfarmGssAcquireCredential(&myCred, acceptorNameString, acceptorNameType, GSS_C_BOTH, &majStat, &minStat, &credName) <= 0) { fprintf(stderr, "can't acquire credential because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return 1; } fprintf(stderr, "Acceptor Credential: '%s'\n", credName); } /* * Create a channel. */ bindFd = gfarmTCPBindPort(port); if (bindFd < 0) { gfarmSecSessionFinalizeBoth(); return 1; } (void)gfarmIPGetNameOfSocket(bindFd, &port); fprintf(stderr, "Accepting port: %d\n", port); /* * Accept-fork loop. */ while (1) { pid_t pid; fd = accept(bindFd, (struct sockaddr *)&remote, &remLen); if (fd < 0) { perror("accept"); (void)close(bindFd); return 1; } rAddr = ntohl(remote.sin_addr.s_addr); rHost = gfarmIPGetHostOfAddress(rAddr); fprintf(stderr, "Connected from %s\n", rHost); (void)free(rHost); pid = fork(); if (pid < 0) { (void)close(fd); (void)close(bindFd); perror("fork"); return 1; } else if (pid == 0) { (void)close(bindFd); doServer(fd, hostname, port, myCred, acceptorNameString, acceptorNameType); (void)close(fd); exit(0); } else { (void)close(fd); } } #if 0 /* never reach here */ gfarmSecSessionFinalizeBoth(); return 0; #endif } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/gftool/gfrun/gfrun.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "host.h" #include "gfj_client.h" #include "schedule.h" char *program_name = "gfrun"; void setsig(int signum, void (*handler)(int)) { struct sigaction act; act.sa_handler = handler; sigemptyset(&act.sa_mask); /* do not set SA_RESTART to make interrupt at waitpid(2) */ act.sa_flags = 0; if (sigaction(signum, &act, NULL) == -1) { fprintf(stderr, "%s: sigaction(%d): %s\n", program_name, signum, strerror(errno)); exit(1); } } void ignore_handler(int signum) { /* do nothing */ } void sig_ignore(int signum) { /* we don't use SIG_IGN to make it possible that child catch singals */ setsig(signum, ignore_handler); } void usage() { fprintf(stderr, "Usage: %s [-n] [-l <login>]\n" "\t[-G <Gfarm file>|-H <hostfile>|-N <number of hosts>]\n" "\t[-o <Gfarm file>] [-e <Gfarm file>]" " command ...\n", program_name); exit(1); } #define ENV_GFRUN_CMD "GFRUN_CMD" #define ENV_GFRUN_FLAGS "GFRUN_FLAGS" char * gfrun(char *rsh_command, gfarm_stringlist *rsh_options, char *stdout_file, char *stderr_file, int nhosts, char **hosts, char *cmd, char **argv) { int i, save_errno, pid, status, command_alist_index; gfarm_stringlist arg_list; char total_nodes[GFARM_INT32STRLEN], node_index[GFARM_INT32STRLEN]; char **delivered_paths = NULL, *e; int is_gfarm_cmd = 0; /* * deliver gfarm:program. */ if (gfarm_is_url(cmd)) { e = gfarm_url_program_deliver( cmd, nhosts, hosts, &delivered_paths); if (e != NULL) return (e); is_gfarm_cmd = 1; } sprintf(total_nodes, "%d", nhosts); gfarm_stringlist_init(&arg_list); gfarm_stringlist_add(&arg_list, rsh_command); gfarm_stringlist_add(&arg_list, "(dummy)"); if (rsh_options != NULL) gfarm_stringlist_add_list(&arg_list, rsh_options); command_alist_index = gfarm_stringlist_length(&arg_list); gfarm_stringlist_add(&arg_list, "(dummy)"); if (is_gfarm_cmd) { gfarm_stringlist_add(&arg_list, "--gfarm_nfrags"); gfarm_stringlist_add(&arg_list, total_nodes); gfarm_stringlist_add(&arg_list, "--gfarm_index"); gfarm_stringlist_add(&arg_list, node_index); if (stdout_file != NULL) { gfarm_stringlist_add(&arg_list, "--gfarm_stdout"); gfarm_stringlist_add(&arg_list, stdout_file); } if (stderr_file != NULL) { gfarm_stringlist_add(&arg_list, "--gfarm_stderr"); gfarm_stringlist_add(&arg_list, stderr_file); } } gfarm_stringlist_cat(&arg_list, argv); gfarm_stringlist_add(&arg_list, NULL); for (i = 0; i < nhosts; i++) { char *if_hostname; struct sockaddr peer_addr; sprintf(node_index, "%d", i); /* reflect "address_use" directive in the `if_hostname' */ e = gfarm_host_address_get(hosts[i], gfarm_spool_server_port, &peer_addr, &if_hostname); GFARM_STRINGLIST_ELEM(arg_list, 1) = e == NULL ? if_hostname : hosts[i]; if (delivered_paths == NULL) { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = cmd; } else { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = delivered_paths[i]; } switch (pid = fork()) { case 0: execvp(rsh_command, GFARM_STRINGLIST_STRARRAY(arg_list)); perror(rsh_command); exit(1); case -1: perror("fork"); exit(1); } if (e == NULL) free(if_hostname); } sig_ignore(SIGHUP); sig_ignore(SIGINT); sig_ignore(SIGQUIT); sig_ignore(SIGTERM); sig_ignore(SIGTSTP); while (waitpid(-1, &status, 0) != -1) ; save_errno = errno; if (delivered_paths != NULL) gfarm_strings_free_deeply(nhosts, delivered_paths); gfarm_stringlist_free(&arg_list); return (save_errno == ECHILD ? NULL : gfarm_errno_to_error(save_errno)); } /* * register files in gfarm spool */ char * register_file(char *rsh_command, gfarm_stringlist *rsh_options, int nhosts, char **hosts, char **gfarm_files) { char *gfsplck_cmd = "gfarm:/bin/gfsplck"; char *e = NULL; struct gfs_stat sb; if (gfarm_files == NULL) return (NULL); e = gfs_stat(gfsplck_cmd, &sb); if (e != NULL) return (e); gfs_stat_free(&sb); e = gfrun(rsh_command, rsh_options, NULL, NULL, nhosts, hosts, gfsplck_cmd, gfarm_files); return (e); } /* * main */ int main(int argc, char *argv[]) { gfarm_stringlist input_list, output_list, option_list; int command_index, i, j, nhosts, job_id, nfrags; char *e, *save_e, **hosts; static char gfarm_prefix[] = "gfarm:"; # define GFARM_PREFIX_LEN (sizeof(gfarm_prefix) - 1) char *rsh_command, *rsh_flags; int have_gfarm_url_prefix = 1, have_redirect_stdio_option = 1; char *hostfile = NULL, *schedfile = NULL, *scheduling_file; int nprocs = 0; char *stdout_file = NULL, *stderr_file = NULL, *command_name; /* * rsh_command */ rsh_command = getenv(ENV_GFRUN_CMD); if (rsh_command == NULL) rsh_command = "gfrcmd"; /* For backward compatibility */ if (argc >= 1) { program_name = basename(argv[0]); if (strcmp(program_name, "gfrsh") == 0) { rsh_command = "rsh"; } else if (strcmp(program_name, "gfssh") == 0) { rsh_command = "ssh"; } else if (strcmp(program_name, "gfrshl") == 0) { rsh_command = "rsh"; have_gfarm_url_prefix = 0; } else if (strcmp(program_name, "gfsshl") == 0) { rsh_command = "ssh"; have_gfarm_url_prefix = 0; } } /* Globus-job-run hack */ if (strcmp(rsh_command, "globus-job-run") == 0) { have_redirect_stdio_option = 0; } /* * rsh_flags * * XXX - Currently, You can specify at most one flag. */ gfarm_stringlist_init(&option_list); rsh_flags = getenv(ENV_GFRUN_FLAGS); if (rsh_flags == NULL) { if (have_redirect_stdio_option == 1) gfarm_stringlist_add(&option_list, "-n"); } else gfarm_stringlist_add(&option_list, rsh_flags); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm initialize: %s\n", program_name, e); exit(1); } e = gfj_initialize(); if (e != NULL) { fprintf(stderr, "%s: job manager: %s\n", program_name, e); exit(1); } /* * parse and skip/record options */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; for (j = 1; argv[i][j] != '\0'; j++) { switch (argv[i][j]) { case 'G': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { schedfile = &argv[i][j + 1]; } else if (++i < argc) { schedfile = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'H': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { hostfile = &argv[i][j + 1]; } else if (++i < argc) { hostfile = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'N': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { nprocs = atoi(&argv[i][j + 1]); } else if (++i < argc) { nprocs = atoi(argv[i]); } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'o': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { stdout_file = &argv[i][j + 1]; } else if (++i < argc) { stdout_file = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'e': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { stderr_file = &argv[i][j + 1]; } else if (++i < argc) { stderr_file = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'K': case 'd': case 'n': case 'x': /* an option which doesn't have an argument */ break; case 'k': case 'l': /* an option which does have an argument */ if (argv[i][j + 1] != '\0') ; else if (++i < argc) { gfarm_stringlist_add(&option_list, argv[i - 1]); } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto record_opt; } } record_opt: gfarm_stringlist_add(&option_list, argv[i]); skip_opt: ; } command_index = i; if (command_index >= argc) /* no command name */ usage(); command_name = argv[command_index]; gfarm_stringlist_init(&input_list); gfarm_stringlist_init(&output_list); for (i = command_index + 1; i < argc; i++) { if (strncmp(argv[i], gfarm_prefix, GFARM_PREFIX_LEN) == 0) { e = gfarm_url_fragment_number(argv[i], &nfrags); if (e == NULL) { gfarm_stringlist_add(&input_list, argv[i]); } else { gfarm_stringlist_add(&output_list, argv[i]); } if (!have_gfarm_url_prefix) argv[i] += GFARM_PREFIX_LEN; } } /* * Process scheduling */ if (schedfile != NULL) { /* File-affinity scheduling */ if (hostfile != NULL) { fprintf(stderr, "%s: -H option is ignored.\n", program_name); } if (nprocs > 0) { fprintf(stderr, "%s: -N option is ignored.\n", program_name); } e = gfarm_url_hosts_schedule(schedfile, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", schedfile, e); exit(1); } scheduling_file = schedfile; } else if (hostfile != NULL) { /* Hostfile scheduling */ int error_line; if (nprocs > 0) { fprintf(stderr, "%s: -N option is ignored.\n", program_name); } /* * Is it necessary to access a Gfarm hostfile? */ e = gfarm_hostlist_read(hostfile, &nhosts, &hosts, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s: line %d: %s\n", program_name, hostfile, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, hostfile, e); exit(1); } scheduling_file = hostfile; } else if (nprocs > 0) { nhosts = nprocs; hosts = malloc(sizeof(char *) * nprocs); if (hosts == NULL) fputs("not enough memory", stderr), exit(1); /* XXX - it is necessary to choose nodes such that user authentication succeeds. */ e = gfarm_schedule_search_idle_by_all(nprocs, hosts); if (e != NULL) fprintf(stderr, "%s: %s\n", program_name, e); scheduling_file = "none"; } else if (gfarm_stringlist_length(&input_list) != 0) { /* The first input file used for file-affinity scheduling. */ scheduling_file = gfarm_stringlist_elem(&input_list, 0); e = gfarm_url_hosts_schedule(scheduling_file, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: schedule: %s\n", program_name, e); exit(1); } } else { /* Serial execution */ char *self_name; nhosts = 1; hosts = malloc(sizeof(char *)); if (hosts == NULL) fputs("not enough memory", stderr), exit(1); e = gfarm_host_get_canonical_self_name(&self_name); if (e == NULL) { *hosts = strdup(self_name); if (*hosts == NULL) fputs("not enough memory", stderr), exit(1); } else { /* XXX - it is necessary to choose nodes such that user authentication succeeds. */ e = gfarm_schedule_search_idle_by_all(1, hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } } scheduling_file = "none"; } /* * register job manager */ e = gfarm_user_job_register(nhosts, hosts, program_name, scheduling_file, argc - command_index, &argv[command_index], &job_id); if (e != NULL) { fprintf(stderr, "%s: job register: %s\n", program_name, e); exit(1); } save_e = gfrun(rsh_command, &option_list, stdout_file, stderr_file, nhosts, hosts, command_name, &argv[command_index + 1]); if (save_e != NULL) { fprintf(stderr, "%s: %s\n", command_name, save_e); goto finish; } /* register a stdout file. */ if (stdout_file != NULL || stderr_file != NULL) { char *files[3]; struct gfs_stat sb; int i = 0; if (stdout_file != NULL) { e = gfs_stat(stdout_file, &sb); if (e != NULL) files[i++] = stdout_file; else gfs_stat_free(&sb); } if (stderr_file != NULL) { e = gfs_stat(stderr_file, &sb); if (e != NULL) files[i++] = stderr_file; else gfs_stat_free(&sb); } files[i] = NULL; if (i > 0) { e = register_file(rsh_command, &option_list, nhosts, hosts, files); if (e != NULL) fprintf(stderr, "%s: cannot register a stdout file: " "%s\n", program_name, e); } } finish: #if 0 /* XXX - temporary solution; it is not necessary for the output file to be the same number of fragments. */ for (i = 0; i < gfarm_stringlist_length(&output_list); i++) gfarm_url_fragment_cleanup( gfarm_stringlist_elem(&output_list, i), nhosts, hosts); #endif gfarm_strings_free_deeply(nhosts, hosts); gfarm_stringlist_free(&output_list); gfarm_stringlist_free(&input_list); gfarm_stringlist_free(&option_list); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (save_e == NULL ? 0 : 1); } <file_sep>/gfarm/tags/gfarm_1_1_0_rc1/gfptool/gfsplck/gfsplck.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <glob.h> #include <gfarm/gfarm.h> #include "config.h" char *progname = "gfsplck"; static int check_all = 0; static int delete_invalid_file = 0; static void print_errmsg(const char *path, char *msg) { fprintf(stderr, "%s on %s: %s\n", path, gfarm_host_get_self_name(), msg); } static void print_errmsg_with_section(const char *path, char *section, char *msg) { fprintf(stderr, "%s (%s) on %s: %s\n", path, section, gfarm_host_get_self_name(), msg); } static int unlink_dir(const char *src) { struct stat sb; if (lstat(src, &sb)) { perror(src); return (1); } if (S_ISDIR(sb.st_mode)) { DIR *dirp; struct dirent *dp; dirp = opendir(src); if (dirp == NULL) { perror(src); return (1); } while ((dp = readdir(dirp)) != NULL) { char *f; if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || dp->d_ino == 0) continue; f = malloc(strlen(src) + 1 + strlen(dp->d_name) + 1); if (f == NULL) { print_errmsg(dp->d_name, "not enough memory"); return (1); } strcpy(f, src); strcat(f, "/"); strcat(f, dp->d_name); (void)unlink_dir(f); free(f); } closedir(dirp); if (rmdir(src)) { perror(src); return (1); } } else if (unlink(src)) { /* if 'src' is not a directory, try to unlink. */ perror(src); return (1); } return (0); } static void delete_invalid_file_or_directory(char *pathname) { if (delete_invalid_file) { if (unlink_dir(pathname) == 0) printf("%s on %s: deleted\n", pathname, gfarm_host_get_self_name()); else print_errmsg(pathname, "cannot delete"); } } static char * append_prefix_pathname(const char *prefix, const char *path) { char *url; url = malloc(strlen(prefix) + strlen(path) + 2); if (url == NULL) return (url); strcpy(url, prefix); switch (url[strlen(url) - 1]) { case '/': case ':': break; default: strcat(url, "/"); } strcat(url, path); return (url); } static char * fixfrag_i(char *pathname, char *gfarm_file, char *sec) { char *hostname, *e; struct gfarm_file_section_copy_info sc_info; /* * XXX - Gfarm v1 uses a special lock file to avoid race * condition during on-demand replication. This file should * not be registered. */ if (strstr(sec, ":::lock")) return ("lock file"); if (check_all == 0) { /* check whether the fragment is already registered. */ e = gfarm_host_get_canonical_self_name(&hostname); if (e == NULL) { e = gfarm_file_section_copy_info_get( gfarm_file, sec, hostname, &sc_info); if (e == NULL) { /* already exist */ gfarm_file_section_copy_info_free(&sc_info); return (GFARM_ERR_ALREADY_EXISTS); } if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); } } /* * If the corresponding metadata does not exist, register it. * Otherwise, check file size and checksum. */ return (gfs_pio_set_fragment_info_local(pathname, gfarm_file, sec)); } static int fixdir(char *dir, const char *gfarm_prefix); static void fixurl(const char *gfarm_url) { char *gfarm_file, *local_path, *e; struct stat sb; int len_path, is_invalid = 0, is_directory = 0; glob_t pglob; char **pathp, *pat; struct gfs_stat gs; e = gfarm_canonical_path(gfarm_url_prefix_skip(gfarm_url), &gfarm_file); if (e != NULL) { /* * no path info, try to delete invalid physical files * or directories */ e = gfarm_canonical_path_for_creation( gfarm_url_prefix_skip(gfarm_url), &gfarm_file); if (e != NULL) { /* in this case, give up searching invalid files */ print_errmsg(gfarm_url, e); return; } is_invalid = 1; } else { /* check it is a directory or not */ e = gfs_stat(gfarm_url, &gs); if (e != NULL) { if (e != GFARM_ERR_NO_FRAGMENT_INFORMATION) { /* maybe permission denied */ print_errmsg(gfarm_url, e); goto error_gfarm_file; } /* no fragment information case */ } else { is_directory = GFARM_S_ISDIR(gs.st_mode); gfs_stat_free(&gs); } } /* * Check local_path; if it is invalid or not a directory, * delete it. Otherwise, check it recursively. */ e = gfarm_path_localize(gfarm_file, &local_path); if (e == NULL && stat(local_path, &sb) == 0) { if (is_invalid || !is_directory || !S_ISDIR(sb.st_mode)) { print_errmsg(local_path, "invalid file or directory"); delete_invalid_file_or_directory(local_path); } else if (chdir(local_path) == 0) (void)fixdir(".", gfarm_url); /* continue */ } if (e != NULL) { print_errmsg(gfarm_url, e); goto error_gfarm_file; } /* investigate file sections */ len_path = strlen(local_path); pat = malloc(len_path + 3); if (pat == NULL) { print_errmsg(gfarm_url, "not enough memory"); free(local_path); goto error_gfarm_file; } strcpy(pat, local_path); strcat(pat, ":*"); free(local_path); pglob.gl_offs = 0; glob(pat, GLOB_DOOFFS, NULL, &pglob); free(pat); pathp = pglob.gl_pathv; while (*pathp) { char *sec = &((*pathp)[len_path + 1]); if (is_invalid || is_directory) { print_errmsg_with_section( gfarm_url, sec, "invalid file"); delete_invalid_file_or_directory(*pathp); ++pathp; continue; } e = fixfrag_i(*pathp, gfarm_file, sec); if (e != NULL) { if (e != GFARM_ERR_ALREADY_EXISTS) { print_errmsg_with_section(gfarm_url, sec, e); delete_invalid_file_or_directory(*pathp); } } else printf("%s (%s) on %s: fixed\n", gfarm_url, sec, gfarm_host_get_self_name()); ++pathp; } globfree(&pglob); error_gfarm_file: free(gfarm_file); return; } static int fixfrag(char *pathname, const char *gfarm_prefix) { char *gfarm_url, *sec, *pname, *gfarm_file, *e; struct gfs_stat gst; int r = 1; gfarm_url = append_prefix_pathname(gfarm_prefix, pathname); if (gfarm_url == NULL) { print_errmsg(pathname, "not enough memory"); return (r); } /* divide into file and section parts. */ sec = &gfarm_url[strlen(gfarm_url) - 1]; pname = sec - strlen(pathname) + 1; while (sec > pname && *sec != '/') { if (*sec == ':') { *sec = '\0'; ++sec; break; } --sec; } if (sec == pname || *sec == '/') { print_errmsg(pathname, "invalid filename"); delete_invalid_file_or_directory(pathname); goto error_gfarm_url; } e = gfs_stat(gfarm_url, &gst); if (e == NULL) { if (!GFARM_S_ISREG(gst.st_mode)) { gfs_stat_free(&gst); print_errmsg(gfarm_url, "not a regular file"); delete_invalid_file_or_directory(pathname); goto error_gfarm_url; } gfs_stat_free(&gst); } else /* permit no fragment case */; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { print_errmsg_with_section(gfarm_url, sec, e); delete_invalid_file_or_directory(pathname); goto error_gfarm_url; } /* check whether the fragment is already registered. */ e = fixfrag_i(pathname, gfarm_file, sec); if (e != NULL) { if (e != GFARM_ERR_ALREADY_EXISTS) { print_errmsg_with_section(pathname, sec, e); delete_invalid_file_or_directory(pathname); goto error_gfarm_file; } else /* no message */; } else printf("%s (%s) on %s: fixed\n", gfarm_url, sec, gfarm_host_get_self_name()); r = 0; error_gfarm_file: free(gfarm_file); error_gfarm_url: free(gfarm_url); return (r); } static int fixdir(char *dir, const char *gfarm_prefix) { DIR* dirp; struct dirent *dp; struct stat sb; char *dir1; char *gfarm_url, *e; int is_directory; struct gfs_stat gs; if (lstat(dir, &sb)) { perror(dir); return (1); } if (S_ISREG(sb.st_mode)) return (fixfrag(dir, gfarm_prefix)); if (!S_ISDIR(sb.st_mode)) { print_errmsg(dir, "neither a regular file nor a directory"); delete_invalid_file_or_directory(dir); return (1); } /* 'dir' is a directory */ gfarm_url = append_prefix_pathname(gfarm_prefix, dir); if (gfarm_url == NULL) { print_errmsg(dir, "not enough memory"); return (1); } e = gfs_stat(gfarm_url, &gs); if (e != NULL) { print_errmsg(gfarm_url, e); delete_invalid_file_or_directory(dir); free(gfarm_url); return (1); } is_directory = GFARM_S_ISDIR(gs.st_mode); gfs_stat_free(&gs); if (!is_directory) { print_errmsg(gfarm_url, "invalid directory"); delete_invalid_file_or_directory(dir); free(gfarm_url); return (1); } free(gfarm_url); dirp = opendir(dir); if (dirp == NULL) { perror(dir); return (1); } if (strcmp(dir, ".") == 0) dir = ""; /* just a trick */ while ((dp = readdir(dirp)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue; dir1 = malloc(strlen(dir) + strlen(dp->d_name) + 2); if (dir1 == NULL) { print_errmsg(dp->d_name, "not enough memory"); closedir(dirp); return (1); } strcpy(dir1, dir); if (strcmp(dir, "")) strcat(dir1, "/"); strcat(dir1, dp->d_name); fixdir(dir1, gfarm_prefix); free(dir1); } return (closedir(dirp)); } /* * */ void usage() { fprintf(stderr, "usage: %s [ -a ] [ -d ] [ Gfarm directory . . . ]\n", progname); fprintf(stderr, "options:\n"); fprintf(stderr, "\t-a\tcheck all files\n"); fprintf(stderr, "\t-d\tdelete invalid files\n"); exit(1); } int main(int argc, char *argv[]) { char *e, *gfarm_prefix; extern int optind; int c; e = gfarm_initialize(&argc, &argv); if (e != NULL) { print_errmsg(progname, e); exit(1); } if (!gfarm_is_active_file_system_node) { print_errmsg(progname, "not a filesystem node"); exit(1); } while ((c = getopt(argc, argv, "ad")) != EOF) { switch (c) { case 'a': check_all = 1; break; case 'd': delete_invalid_file = 1; break; default: usage(); } } argc -= optind; argv += optind; if (*argv) { while (*argv) fixurl(*argv++); goto finish; } /* fix a whole spool directory. */ if (chdir(gfarm_spool_root) == 0) gfarm_prefix = "gfarm:/"; else gfarm_prefix = "gfarm:"; fixdir(".", gfarm_prefix); finish: e = gfarm_terminate(); if (e != NULL) { print_errmsg(progname, e); exit(1); } exit(0); } <file_sep>/gfarm/tags/gfarm_1_0_2/gftool/gfmkdir/gfmkdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <unistd.h> #include <sys/time.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include <gfarm/gfarm_error.h> #include "gfs_client.h" char *program_name = "gfmkdir"; static void usage() { fprintf(stderr, "Usage: %s directory...\n", program_name); exit(1); } int main(int argc, char **argv) { char *e, *canonic_path; int i, c; extern int optind; char *user; if (argc <= 1) usage(); program_name = basename(argv[0]); while ((c = getopt(argc, argv, "h")) != EOF) { switch (c) { case 'h': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } user = gfarm_get_global_username(); if (user == NULL) { fprintf(stderr, "%s:%s%s\n", program_name, "programming error, gfarm library isn't properly ", "initialized"); exit(1); } for (i = 0; i < argc; i++) { struct gfarm_path_info pi; struct timeval now; e = gfarm_url_make_path_for_creation(argv[i], &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path_for_creation(argv[i], &canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } if (gfarm_path_info_get(canonic_path, &pi) == 0) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], GFARM_ERR_ALREADY_EXISTS); gfarm_path_info_free(&pi); continue; } gettimeofday(&now, NULL); pi.pathname = canonic_path; pi.status.st_mode = (GFARM_S_IFDIR | 0755); pi.status.st_user = user; pi.status.st_group = "*"; /* XXX for now */ pi.status.st_atimespec.tv_sec = pi.status.st_mtimespec.tv_sec = pi.status.st_ctimespec.tv_sec = now.tv_sec; pi.status.st_atimespec.tv_nsec = pi.status.st_mtimespec.tv_nsec = pi.status.st_ctimespec.tv_nsec = now.tv_usec * 1000; pi.status.st_size = 0; pi.status.st_nsections = 0; e = gfarm_path_info_set(canonic_path, &pi); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } free(canonic_path); } e = gfarm_terminate(); return (0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_editor/common.php <?php # 'gfarm2.conf' file. $gfarm2_conf_file = 'skeleton/gfarm2.conf'; # file which stores result of 'gfmdhost -l'. $gfmdlist_file = 'gfmdlist/metadataserver_list.log'; # # Read '$gfarm2_conf_file' file. # function read_gfarm2_conf_file() { global $gfarm2_conf_file; $lines = array(); $handle = fopen($gfarm2_conf_file, 'rb'); if ($handle == FALSE) { $line = sprintf("# Error: failed to open the file '%s'", $gfarm2_conf_file); array_push($lines, $line); } else { while (($line = fgets($handle)) != FALSE) { $line = rtrim($line); if (!ereg('^[ \t\f\v\'\"]*metadb_server_list([^A-Za-z0-9_]|$)', $line)) { array_push($lines, $line); } } fclose($handle); } while (count($lines) > 0 && end($lines) == "") { array_pop($lines); } return $lines; } # # Read '$gfmdlist_file' file. # function read_gfmdlist_file() { global $gfmdlist_file; $lines = array(); $handle = fopen($gfmdlist_file, 'rb'); if ($handle == FALSE) { $line = sprintf("# Error: failed to open the file '%s'", $gfmdlist_file); array_push($lines, $line); } else { while (($line = fgets($handle)) != FALSE) { array_push($lines, rtrim($line)); } fclose($handle); } return $lines; } # # Write '$gfarm2_conf_file' file. # function write_gfarm2_conf($conf_data) { global $gfarm2_conf_file; $tmp_file = $gfarm2_conf_file . '.tmp'; $handle = fopen($tmp_file, 'wb'); if (!$handle) { return FALSE; } fwrite($handle, $conf_data); fclose($handle); if (!rename($tmp_file, $gfarm2_conf_file)) { return FALSE; } return TRUE; } ?> <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/gfm_proto.h #ifndef GFMD_DEFAULT_PORT #define GFMD_DEFAULT_PORT 601 #endif enum gfm_proto_command { GFJ_PROTO_LOCK_REGISTER, GFJ_PROTO_UNLOCK_REGISTER, GFJ_PROTO_REGISTER, GFJ_PROTO_UNREGISTER, GFJ_PROTO_REGISTER_NODE, GFJ_PROTO_LIST, GFJ_PROTO_INFO, GFJ_PROTO_HOSTINFO }; enum gfm_proto_error { GFM_ERROR_NOERROR, GFM_ERROR_NO_MEMORY, GFM_ERROR_NO_SUCH_OBJECT, GFJ_ERROR_TOO_MANY_JOBS }; #define GFJ_ERROR_NOERROR GFM_ERROR_NOERROR #define GFJ_ERROR_NO_MEMORY GFM_ERROR_NO_MEMORY #define GFJ_ERROR_NO_SUCH_OBJECT GFM_ERROR_NO_SUCH_OBJECT <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_6/systest/Makefile.am SUBDIRS = testcases common_scripts plugins scenarios noinst_DATA = testcases.xls <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/lib/gfs_hook/hook_test.c /* * Test program for syscall hooking feature. * * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/syscall.h> #include <pwd.h> #include <grp.h> #include <time.h> #include <stdio.h> /* * Display struct stat. * * Known bug: Device is not correctly displayed. */ #ifndef HAVE_GTIME #define gtime(x) asctime(gmtime(x)) #endif #ifndef S_IAMB #define S_IAMB 07777 #endif void display_stat(char *fn, struct stat *st) { printf(" File: \"%s\"\n", fn); printf(" Size: %-12ld Filetype: ", (long)st->st_size); switch (st->st_mode & S_IFMT) { case S_IFSOCK: puts("socket"); break; case S_IFLNK: puts("symbolic link"); break; case S_IFREG: puts("regular file"); break; case S_IFBLK: puts("block device"); break; case S_IFDIR: puts("directory"); break; case S_IFCHR: puts("character device"); break; case S_IFIFO: puts("fifo"); break; default: printf("unknown\n"); } #if 0 printf(" Mode: (%04o) Uid: (%5d/%8s) Gid: (%5d/%8s)\n", st->st_mode & S_IAMB, st->st_uid, getpwuid(st->st_uid)->pw_name, st->st_gid, getgrgid(st->st_gid)->gr_name); printf("Device: %d,%d Inode: %ld Links: %d\n", st->st_dev, st->st_rdev, st->st_ino, st->st_nlink); #endif printf("Access: %s", gtime(&st->st_atime)); printf("Modify: %s", gtime(&st->st_mtime)); printf("Change: %s", gtime(&st->st_ctime)); } /* * test functions */ int test_stat(char *filename) { struct stat s; int r; printf("***** stat(%s)\n", filename); if ((r = stat(filename, &s))) perror(filename); else display_stat(filename, &s); return r; } int test_lstat(char *filename) { struct stat s; int r; printf("***** lstat(%s)\n", filename); if ((r = lstat(filename, &s))) perror(filename); else display_stat(filename, &s); return r; } void test_fstat(int filedes) { struct stat s; printf("***** fstat(%d)\n", filedes); if (fstat(filedes, &s)) perror("fstat"); else display_stat("test_fstat", &s); } int test_access(char *filename) { int r; printf("***** access(%s, %d)\n", filename, R_OK); if ((r = access(filename, R_OK))) perror(filename); return r; } int test_open_create(char *filename) { int fd; printf("***** open(%s, O_WRONLY|O_CREAT|O_TRUNC, 0664)\n", filename); if ((fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0664)) == -1) perror(filename), exit(1); return fd; } int test_open_rdonly(char *filename) { int fd; printf("***** open(%s, O_RDONLY)\n", filename); if ((fd = open(filename, O_RDONLY)) == -1) perror(filename), exit(1); return fd; } void test_write_string(int fd, char *teststring) { printf("***** write(%d, %d)\n", fd, strlen(teststring) + 1); if (write(fd, teststring, strlen(teststring) + 1) == -1) perror("write"), exit(1); } void test_read_string(int fd) { # define BUFSIZE 100 char buf[BUFSIZE]; int n; printf("***** read(%d, %d)\n", fd, sizeof(buf)); while ((n = read(fd, buf, sizeof(buf))) > 0) { int i; for (i = 0; i < n; ++i) if (buf[i]) printf("%c", buf[i]); } } void test_lseek_set(int fd, off_t offset) { printf("***** lseek(%d, %d, SEEK_SET)\n", fd, (int)offset); if (lseek(fd, offset, SEEK_SET) == -1) perror("lseek"), exit(1); } void test_close(int fd) { printf("***** close(%d)\n", fd); if (close(fd)) perror("close"), exit(1); } void test_unlink(char *filename) { printf("***** unlink(%s)\n", filename); if (unlink(filename)) perror(filename), exit(1); } /* * stdio */ FILE *test_fopen(char *filename, char *mode) { FILE *f; printf("***** fopen(%s, \"%s\")\n", filename, mode); if ((f = fopen(filename, mode)) == NULL) perror(filename), exit(1); return f; } void test_fgetc(FILE *f) { int c; printf("***** fgetc(%d)\n", fileno(f)); while ((c = fgetc(f)) != EOF) printf("%c", c); } void test_fseek_set(FILE *f, long offset) { printf("***** fseek(%d, %ld, SEEK_SET)\n", fileno(f), offset); if (fseek(f, offset, SEEK_SET)) perror("fseek"), exit(1); } void test_ftell(FILE *f) { long pos; printf("***** ftell(%d)\n", fileno(f)); pos = ftell(f); if (pos == -1) perror("ftell"), exit(1); printf("pos = %ld\n", pos); } void test_rewind(FILE *f) { printf("***** rewind(%d)\n", fileno(f)); rewind(f); } void test_fseeko_set(FILE *f, off_t offset) { printf("***** fseeko(%d, %ld, SEEK_SET)\n", fileno(f), (long)offset); if (fseeko(f, offset, SEEK_SET)) perror("fseeko"), exit(1); } void test_ftello(FILE *f) { off_t pos; printf("***** ftello(%d)\n", fileno(f)); pos = ftello(f); if (pos == -1) perror("ftello"), exit(1); printf("pos = %ld\n", (long)pos); } void test_fclose(FILE *f) { printf("***** fclose(%d)\n", fileno(f)); if (fclose(f)) perror("fclose"), exit(1); } /* * */ int main(int argc, char *argv[]) { char *filename = "gfarm:gfs_hook_test", *e; static char teststring[] = "Gfarm hook test!\n"; int fd; FILE *f; setvbuf(stdout, NULL, _IONBF, 0); /* to sync with truss/strace output */ if (argc > 1) filename = argv[1]; /* create a file */ if (test_stat(filename) == 0) test_unlink(filename); fd = test_open_create(filename); test_write_string(fd, teststring); test_lseek_set(fd, 0); test_fstat(fd); test_close(fd); test_access(filename); test_stat(filename); test_lstat(filename); /* read the file */ fd = test_open_rdonly(filename); test_read_string(fd); test_lseek_set(fd, 0); test_read_string(fd); test_fstat(fd); test_close(fd); test_stat(filename); test_lstat(filename); /* unlink the file */ test_unlink(filename); f = test_fopen(filename, "w"); fprintf(f, "%s", teststring); test_fclose(f); f = test_fopen(filename, "r"); test_fgetc(f); test_fseek_set(f, 0); test_ftell(f); test_rewind(f); test_fseeko_set(f, 0); test_ftello(f); test_fclose(f); test_unlink(filename); exit(0); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8_1/systest/testcases/Makefile.am testcasesdir = $(datadir)/gfarm/systest/testcases dist_testcases_DATA = read_files \ write_files \ write_files_each_mntpnts \ make_file \ make_dir \ copy_file_local_to_gfarm \ copy_file_gfarm_to_gfarm \ copy_file_gfarm_to_local \ copy_dir_local_to_gfarm \ copy_dir_gfarm_to_gfarm \ copy_dir_gfarm_to_local <file_sep>/gfarm/branches/metadb_dev/Makefile.in top_objdir = @top_objdir@ top_srcdir = @top_srcdir@ srcdir = @srcdir@ VPATH = @srcdir@ SUBDIRS = \ man \ include \ nslib \ lib \ gfarmd \ gfarm \ gfmd \ gfsd \ nstool \ gftool include $(top_srcdir)/makes/subdir.mk post-distclean-hook: rm -f config.log config.status config.cache \ gfarm_config.h Makefile makes/config.mk <file_sep>/gfarm/tags/gfarm_20050822/gftool/config-gfarm/config-gfsd.in #!/bin/sh # # $Id$ [ ${DEBUG:="off"} = off ] || set -xu PROGNAME=`basename $0` usage() { echo 1>&2 "usage: $PROGNAME [--prefix prefix] [-t] [-f]" echo 1>&2 " [-a arch] [-h hostname] [-n ncpu] spool_directory" exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* echo "$PROGNAME failure" exit 1 } display_params() { echo "prefix [--prefix]: $CONFIG_PREFIX" echo "hostname [-h]: $GFSD_HOSTNAME" echo "architecture [-a]: $ARCH" echo "ncpu [-n]: $NCPU" exit 0 } # default value : ${CONFIG_PREFIX:=} : ${FORCE:="0"} : ${DISPLAY_PARAMS:="0"} while [ $# -gt 0 ] ; do case $1 in --prefix) shift; [ $# -ge 1 ] || usage CONFIG_PREFIX=$1 ;; -a) shift; [ $# -ge 1 ] || usage ARCH=$1 ;; -f) FORCE=1 ;; -h) shift; [ $# -ge 1 ] || usage GFSD_HOSTNAME=$1 ;; -n) shift; [ $# -ge 1 ] || usage NCPU=$1 ;; -t) DISPLAY_PARAMS=1 ;; -*) usage ;; *) break ;; esac shift done [ $# -eq 1 ] || usage SPOOL_DIRECTORY=$1 case $SPOOL_DIRECTORY in /*) break ;; *) ABORT "$SPOOL_DIRECTORY: should be absolute path" ;; esac : ${GFARM_CONF_SCRIPT:="/tmp/config-gfsd-$$"} : ${GFARM_CONF:="$CONFIG_PREFIX/etc/gfarm.conf"} : ${ETC_INITD:="$CONFIG_PREFIX/etc/init.d"} : ${VAR_RUND:="$CONFIG_PREFIX/var/run"} : ${VAR_LOCKD:="$CONFIG_PREFIX/var/lock/subsys"} : ${DO_NOT_START_SERVICE:="0"} # Gfarm installation directory prefix=@prefix@ if [ X$ARCH = X ]; then KERNEL=`uname -s` RELEASE=`uname -r` MACHINE=`uname -m` [ X$KERNEL = X -o X$RELEASE = X -o X$MACHINE = X ] && ABORT ARCH=$KERNEL-$RELEASE-$MACHINE fi [ X$GFSD_HOSTNAME = X ] && GFSD_HOSTNAME=`hostname -f` [ X$NCPU = X ] && NCPU=`grep ^processor /proc/cpuinfo | wc | awk '{ print $1 }'` [ X$GFSD_HOSTNAME = X -o X$NCPU = X ] && ABORT # -t option; display parameters [ X$DISPLAY_PARAMS = X1 ] && display_params ######################################################################### mkcnf_config_script() { cat <<EOF s,@config_gfarm_prefix@,@prefix@, s,@config_gfarm_gfarm_config@,$GFARM_CONF, s,@config_gfarm_gfsd_option@,"-f $GFARM_CONF", s,@config_gfarm_run_dir@,$VAR_RUND, s,@config_gfarm_lock_dir@,$VAR_LOCKD, EOF } mkscript_gfsd() { sed -f $GFARM_CONF_SCRIPT @datadir@/gfarm/config/gfsd.in } mkcnf() { [ $# -eq 2 ] && $1 > $2 && echo create $2 } mkscript() { [ $# -eq 2 ] && $1 > $2 && chmod +x $2 && echo create $2 } ######################################################################### delete_file_or_directory() { while [ $# -gt 0 ] ; do [ -e $1 ] && rmdir $1 > /dev/null 2>&1 if [ -e $1 ]; then if [ X$FORCE = X0 ]; then ABORT "$PROGNAME: $1 already exist" else rm -rf $1 fi fi shift done } create_directory() { [ $# -gt 0 ] && mkdir -p $* && echo create $* } [ -f $GFARM_CONF ] || ABORT "$GFARM_CONF: no such file" # spool directory delete_file_or_directory $SPOOL_DIRECTORY create_directory $SPOOL_DIRECTORY && chmod 1777 $SPOOL_DIRECTORY || ABORT "$PROGNAME: mkdir $SPOOL_DIRECTORY, failed" grep -v "^spool " $GFARM_CONF > $GFARM_CONF.tmp && echo spool $SPOOL_DIRECTORY >> $GFARM_CONF.tmp && mv $GFARM_CONF.tmp $GFARM_CONF && echo $GFARM_CONF: updated || ABORT "$GFARM_CONF: cannot append spool statement" # gfhost if [ X$CONFIG_PREFIX = X ]; then if [ X$FORCE = X1 ]; then gfhost -d $GFSD_HOSTNAME > /dev/null 2>&1 fi gfhost -c -a $ARCH -n $NCPU $GFSD_HOSTNAME && echo gfhost $GFSD_HOSTNAME: succeeded || echo 1>&2 "gfhost $GFSD_HOSTNAME: failed" else echo '** 'run \'gfhost -c -a $ARCH -n $NCPU $GFSD_HOSTNAME\' echo '** 'after copying $GFARM_CONF to ~/.gfarmrc fi # if [ X"$DO_NOT_START_SERVICE" = X1 ]; then echo "$PROGNAME success" exit 0 fi if [ X$CONFIG_PREFIX = X -a X`id -u` = X0 ]; then service gfsd restart || ABORT "$PROGNAME: cannot start gfsd" else # create run script for gfsd mkcnf mkcnf_config_script $GFARM_CONF_SCRIPT > /dev/null || ABORT "$PROGNAME: cannot create configuration script" create_directory $ETC_INITD $VAR_RUND $VAR_LOCKD mkscript mkscript_gfsd $ETC_INITD/gfsd || ABORT "$PROGNAME: cannot create $ETC_INITD/gfsd" $ETC_INITD/gfsd restart || ABORT "$PROGNAME: cannot start gfsd" rm -f $GFARM_CONF_SCRIPT fi error=$? [ $error = 0 ] && echo "$PROGNAME success" || echo "$PROGNAME failure" exit $error <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/makes/var.mk VPATH=$(srcdir) include $(top_builddir)/makes/config.mk ja_mandir = $(default_mandir)/ja # example_bindir = $(default_bindir)/example example_bindir = $(default_bindir) metadb_client_includes = $(ldap_includes) metadb_client_libs = $(ldap_libs) SHELL = /bin/sh RM = rm # library to be installed, see lib.mk LIBRARY_RESULT = $(LIBRARY) # libgfarm COMMON_CFLAGS = $(OPTFLAGS) $(largefile_cflags) \ -I$(top_builddir)/include -I$(top_srcdir)/include COMMON_LDFLAGS = $(largefile_ldflags) GFARMLIB = -L$(top_builddir)/lib/libgfarm -lgfarm \ $(metadb_client_libs) $(globus_gssapi_libs) $(openssl_libs) INC_SRCDIR = $(top_srcdir)/include/gfarm INC_BUILDDIR = $(top_builddir)/include/gfarm DEPGFARMLIB = $(top_builddir)/lib/libgfarm/libgfarm.la DEPGFARMINC = $(INC_BUILDDIR)/gfarm_config.h $(INC_SRCDIR)/gfarm.h $(INC_SRCDIR)/gfarm_error.h $(INC_SRCDIR)/gfarm_metadb.h $(INC_SRCDIR)/gfarm_misc.h $(INC_SRCDIR)/gfarm_stringlist.h $(INC_SRCDIR)/gfs.h $(INC_SRCDIR)/gfs_glob.h # ns NS_COMMON_CFLAGS = $(OPTFLAGS) $(largefile_cflags) \ -I$(top_builddir)/include \ -I$(top_builddir)/ns/include -I$(top_srcdir)/ns/include NSLIB = -L$(top_builddir)/ns/nslib -lns NSEXECLIB = -L$(top_builddir)/ns/nslib -lnsexec NSINC_SRCDIR = $(top_srcdir)/ns/include/gfarm NSINC_BUILDDIR = $(top_builddir)/ns/include/gfarm GFD_SRCDIR = $(top_srcdir)/ns/gfarmd DEPNSLIB = $(top_builddir)/ns/nslib/libns.la DEPNSEXECLIB = $(top_builddir)/ns/nslib/libnsexec.la # gfsl GFSL_SRCDIR = $(top_srcdir)/lib/libgfarm/gfsl DEPGFSLINC = $(GFSL_SRCDIR)/gfarm_auth.h $(GFSL_SRCDIR)/gfarm_gsi.h $(GFSL_SRCDIR)/gfarm_secure_session.h # libgfarm internal interface GFUTIL_SRCDIR = $(top_srcdir)/lib/libgfarm/gfutil GFARMLIB_SRCDIR = $(top_srcdir)/lib/libgfarm/gfarm # doc & man DOCBOOK2MAN = jw -b man DOCBOOK2HTML = jw -b html -u srcsubst = dummy dstsubst = dummy # libtool LTFLAGS_SHARELIB_IN = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) -rpath CCLD = $(CC) LTCOMPILE = $(LIBTOOL) --mode=compile $(CC) $(CFLAGS) LTLINK = $(LIBTOOL) --mode=link $(CCLD) $(CFLAGS) $(LDFLAGS) -o $@ LTLINK_SHARELIB_IN = $(LTLINK) $(LTFLAGS_SHARELIB_IN) LTINSTALL_PROGRAM = $(LIBTOOL) --mode=install $(INSTALL_PROGRAM) LTINSTALL_LIBRARY = $(LIBTOOL) --mode=install $(INSTALL_DATA) LTCLEAN = $(LIBTOOL) --mode=clean $(RM) -f .SUFFIXES: .a .la .ln .o .lo .s .S .c .cc .f .y .l .c.lo: $(LTCOMPILE) -c $(srcdir)/$*.c <file_sep>/gfarm/tags/gfarm_1_0_rc2/bench/thput-pvfs/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk CFLAGS = $(COMMON_CFLAGS) -I/usr/local/include -DPVFS_MOUNT=\"/mnt/pvfs\" LDLIBS = $(COMMON_LDFLAGS) $(LIBS) -L/usr/local/lib -lpvfs PROGRAM = thput-pvfs OBJS = thput-pvfs.o all: $(PROGRAM) include $(top_srcdir)/makes/prog.mk <file_sep>/gfarm/tags/gfarm_1_0_beta_5/package/solaris/build #!/bin/sh PATH=/usr/bin:/bin:/usr/ccs/bin:/opt/SUNWspro/bin:/usr/local/bin:/usr/ucb export PATH version=1.0b5 subpkgs='client devel doc fsnode gfptool server gfront' srcdir=`pwd` work=$srcdir/.. buildroot=$work/buildroot-$$ prefix=--prefix=/usr/grid make=/usr/local/bin/make tar=/usr/local/bin/tar with_globus=--with-globus=/usr/grid # XXX "unresolved symbol __eprintf" happens without --with-globus-shared globus_extra_config=--with-globus-shared # XXX --with-mpi needs OPTFLAGS=-O with gcc # otherwise gfs_hook_mpi causes error # XXX tar reports missing `gfwc' without --with-mpi with_mpi= # --with-mpi=/usr/local/mpich vendorcc_pkg=/usr/users/soda/install/SunOS-5.8-SUWspro-6.2 with_vendorcc_openldap=--with-openldap=$vendorcc_pkg/openldap-2.1.17 with_vendorcc_openssl=--with-openssl=$vendorcc_pkg/openssl-0.9.7b with_vendorcc_globus_flavor=--with-globus-flavor=gcc32 gcc_pkg=/usr/users/soda/install/SunOS-5.8-gcc-2.95.2 with_gcc_openldap=--with-openldap=$gcc_pkg/openldap-2.1.17 with_gcc_openssl=--with-openssl=$gcc_pkg/openssl-0.9.7b with_gcc_globus_flavor=--with-globus-flavor=gcc32 case `whoami` in root) ;; # OK *) echo "root privilege is needed to invoke this script" >&2 exit 1;; esac for pkg in gfarm gfarm-gsi do for cc in vendorcc gcc do case ${pkg}-${cc} in gfarm-vendorcc) ./configure $prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl ;; gfarm-gsi-vendorcc) ./configure $prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl \ $with_globus $with_vendorcc_globus_flavor \ $globus_extra_config ;; gfarm-gcc) CC=gcc ./configure $prefix \ $with_gcc_openldap \ $with_gcc_openssl ;; gfarm-gsi-gcc) CC=gcc ./configure $prefix \ $with_gcc_openldap \ $with_gcc_openssl \ $with_globus $with_gcc_globus_flavor \ $globus_extra_config ;; esac $make rm -rf $buildroot mkdir -p $buildroot $buildroot/usr/grid $buildroot/etc $make prefix=$buildroot/usr/grid install mkdir -p $buildroot/etc/rc3.d cp package/solaris/gfmd $buildroot/etc/rc3.d/S98gfmd cp package/solaris/gfsd $buildroot/etc/rc3.d/S99gfsd ln $buildroot/etc/rc3.d/S98gfmd $buildroot/etc/rc3.d/K98gfmd ln $buildroot/etc/rc3.d/S99gfsd $buildroot/etc/rc3.d/K97gfsd chmod +x $buildroot/etc/rc3.d/* cp doc/conf/gfarm.conf $buildroot/etc/gfarm.conf.sample mkdir -p $buildroot/etc/gfarm-ldap cp doc/conf/gfarm.schema $buildroot/etc/gfarm-ldap/ $make distclean ( cd $buildroot && for s in $subpkgs do $tar zcf $work/${pkg}-${s}-${cc}-${version}.tar.gz \ `cat $srcdir/package/solaris/gfarm-${s}.files` done ) rm -rf $buildroot done done <file_sep>/gfarm/tags/gfarm_0_1/lib/gfs_hook/sysdep/linux/kernel_stat.h /* older glibc doesn't have _STAT_VER_KERNEL in /usr/include/bits/stat.h */ #ifndef _STAT_VER_KERNEL #define _STAT_VER_KERNEL 1 #endif /* Definition of `struct stat' used in the kernel.. */ struct kernel_stat { unsigned short int st_dev; unsigned short int __pad1; #define _HAVE___PAD1 unsigned long int st_ino; unsigned short int st_mode; unsigned short int st_nlink; unsigned short int st_uid; unsigned short int st_gid; unsigned short int st_rdev; unsigned short int __pad2; #define _HAVE___PAD2 unsigned long int st_size; unsigned long int st_blksize; unsigned long int st_blocks; unsigned long int st_atime; unsigned long int __unused1; #define _HAVE___UNUSED1 unsigned long int st_mtime; unsigned long int __unused2; #define _HAVE___UNUSED2 unsigned long int st_ctime; unsigned long int __unused3; #define _HAVE___UNUSED3 unsigned long int __unused4; #define _HAVE___UNUSED4 unsigned long int __unused5; #define _HAVE___UNUSED5 }; #define _HAVE_STAT___UNUSED1 #define _HAVE_STAT___UNUSED2 #define _HAVE_STAT___UNUSED3 #define _HAVE_STAT___UNUSED4 #define _HAVE_STAT___UNUSED5 #define _HAVE_STAT___PAD1 #define _HAVE_STAT___PAD2 #define _HAVE_STAT64___UNUSED1 #define _HAVE_STAT64___UNUSED2 #define _HAVE_STAT64___UNUSED3 #define _HAVE_STAT64___PAD1 #define _HAVE_STAT64___PAD2 #define _HAVE_STAT64___ST_INO <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/gfptool/gfrepbe_server/gfrepbe_server.c #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <syslog.h> #include <gfarm/gfarm.h> #include "gfutil.h" #include "xxx_proto.h" #include "io_fd.h" #include "param.h" #include "sockopt.h" #include "auth.h" #include "config.h" #include "gfs_proto.h" #include "gfs_client.h" #ifdef SOMAXCONN #define LISTEN_BACKLOG SOMAXCONN #else #define LISTEN_BACKLOG 5 #endif #define PORT_MINIMUM 11000 #define PORT_MAXIMUM 12000 char *program_name = "gfrepbe_server"; char *my_name; /* == gfarm_host_get_self_name() */ long rate_limit; /* * XXX * The definition of GFREPBE_SERVICE_TAG and gfrepbe_auth_initialize() in * gfrepbe_server.c and gfrepbe_client.c must be factored out. */ #define GFREPBE_SERVICE_TAG "gfarm-replication-backend" char * gfrepbe_auth_initialize(void) { return (gfarm_auth_server_cred_type_set(GFREPBE_SERVICE_TAG, GFARM_AUTH_CRED_TYPE_USER)); } void fatal(void) { exit(EXIT_FAILURE); } char * sequential_transfer(int ifd, file_offset_t size, int file_read_size, struct xxx_connection *conn, struct gfs_client_rep_rate_info *rinfo, gfarm_int32_t *read_resultp) { char *e; int i, len, rv = 0; gfarm_int32_t read_result = GFS_ERROR_NOERROR; file_offset_t transfered = 0; char buffer[GFS_PROTO_MAX_IOSIZE]; if (file_read_size >= sizeof(buffer)) file_read_size = sizeof(buffer); while (transfered < size) { if (read_result == GFS_ERROR_NOERROR) { rv = read(ifd, buffer, file_read_size); if (rv <= 0) { read_result = rv == -1 ? gfs_errno_to_proto_error(errno) : GFS_ERROR_EXPIRED; /* file is truncated */ /* * XXX - we cannot stop here, because * currently there is no way to cancel * on-going transfer. */ memset(buffer, 0, sizeof(buffer)); rv = size - transfered < sizeof(buffer) ? size - transfered : sizeof(buffer); } else if (rv > size - transfered) { /* file changed */ read_result = GFS_ERROR_EXPIRED; rv = size - transfered; } } else { /* buffer is already zero filled above */ rv = size - transfered < sizeof(buffer) ? size - transfered : sizeof(buffer); } for (i = 0; i < rv; i += len) { e = xxx_write_direct(conn, buffer + i, rv - i, &len); if (e != NULL) return (e); if (rinfo != NULL) gfs_client_rep_rate_control(rinfo, len); } transfered += rv; } *read_resultp = read_result; return (NULL); } char * parallel_transfer_with_parallel_diskio(char *file, int ifd, file_offset_t size, int ndivisions, int interleave_factor, int file_read_size, struct xxx_connection **conns, int *socks, struct gfs_client_rep_transfer_state **transfers, struct gfs_client_rep_rate_info **rinfos, gfarm_int32_t *read_resultp) { char *e; int i, to_be_read, len, rv, st, *pids; gfarm_int32_t read_result = GFS_ERROR_NOERROR; char buffer[GFS_PROTO_MAX_IOSIZE]; if (file_read_size >= sizeof(buffer)) file_read_size = sizeof(buffer); pids = malloc(sizeof(*pids) * ndivisions); if (pids == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < ndivisions; i++) { switch (pids[i] = fork()) { case -1: e = gfarm_errno_to_error(errno); fprintf(stderr, "%s: replicating %s fork(%d): %s\n", program_name, file, i, e); return (e); case 0: if (i > 0) /* to unshare file offset */ ifd = open(file, O_RDONLY); if (ifd == -1) { read_result = gfs_errno_to_proto_error(errno); memset(buffer, 0, sizeof(buffer)); } while (!gfs_client_rep_transfer_finished( transfers[i])){ to_be_read = gfs_client_rep_transfer_length( transfers[i], file_read_size); if (read_result != GFS_ERROR_NOERROR) { memset(buffer, 0, to_be_read); } else { #ifndef HAVE_PREAD rv = lseek(ifd, (off_t) gfs_client_rep_transfer_offset( transfers[i]), SEEK_SET); if (rv != -1) rv = read(ifd, buffer, to_be_read); #else rv = pread(ifd, buffer, to_be_read, (off_t) gfs_client_rep_transfer_offset( transfers[i])); #endif /* * XXX - we cannot stop here, * because currently there is * no way to cancel on-going * transfer. */ if (rv == -1) { read_result = gfs_errno_to_proto_error( errno); memset(buffer, 0, to_be_read); } else if (rv < to_be_read) { read_result = GFS_ERROR_EXPIRED; memset(buffer + rv, 0, to_be_read - rv); } } for (i = 0; i < to_be_read; i += len) { e = xxx_write_direct(conns[i], buffer + i, to_be_read - i, &len); if (e != NULL) { _exit(GFS_ERROR_PIPE); } /* * XXX FIXME * Since this process is forked, * rate_control_info isn't maintained * correctly. */ if (rinfos != NULL) gfs_client_rep_rate_control( rinfos[i], len); } gfs_client_rep_transfer_progress(transfers[i], to_be_read); } if (ifd != -1) close(ifd); _exit(read_result); default: break; } } for (i = 0; i < ndivisions; i++) { rv = waitpid(pids[i], &st, 0); if (rv == -1) return (gfarm_errno_to_error(errno)); if (WIFSIGNALED(st)) return ("parallel transfer process dead"); if (WIFEXITED(st)) { st = WEXITSTATUS(st); if (st == GFS_ERROR_PIPE) return ("parallel transfer connection lost"); if (read_result == GFS_ERROR_NOERROR) read_result = st; } } free(pids); *read_resultp = read_result; return (NULL); } char * parallel_transfer_with_sequential_diskio(char *file, int ifd, file_offset_t size, int ndivisions, int interleave_factor, int file_read_size, struct xxx_connection **conns, int *socks, struct gfs_client_rep_transfer_state **transfers, struct gfs_client_rep_rate_info **rinfos, gfarm_int32_t *read_resultp) { char *e = NULL; int full_stripe_size = ndivisions * interleave_factor; int buffer_to_be_read, buffer_read, to_be_read, len, offset; int buffer_cycle, max_fd, nfound, i, rv; gfarm_int32_t read_result = GFS_ERROR_NOERROR; file_offset_t transfered = 0; char *buffers[2]; fd_set writable; if (interleave_factor == 0) return ("interleave_factor == 0 doesn't make sense " "for parallel_transfer_with_sequential_diskio"); if (size == 0) /* nothing to send */ return (NULL); buffers[0] = malloc(full_stripe_size); buffers[1] = malloc(full_stripe_size); if (buffers[0] == NULL || buffers[1] == NULL) { if (buffers[0] != NULL) free(buffers[0]); if (buffers[1] != NULL) free(buffers[1]); return (GFARM_ERR_NO_MEMORY); } to_be_read = size < full_stripe_size ? size : full_stripe_size; rv = read(ifd, buffers[0], to_be_read); /* * XXX - we cannot stop here, because currently there is no * way to cancel on-going transfer. */ if (rv == -1) { read_result = gfs_errno_to_proto_error(errno); memset(buffers[0], 0, to_be_read); } else if (rv < to_be_read) { read_result = GFS_ERROR_EXPIRED; memset(buffers[0] + rv, 0, to_be_read - rv); } buffer_to_be_read = size - to_be_read < full_stripe_size ? size - to_be_read : full_stripe_size; buffer_read = 0; buffer_cycle = 0; /* current active buffer of double buffering */ for (transfered = 0; transfered < size; ) { FD_ZERO(&writable); max_fd = -1; for (i = 0; i < ndivisions; i++) { if (gfs_client_rep_transfer_stripe_finished( transfers[i])) continue; if (socks[i] >= FD_SETSIZE) { /* XXX - use poll? */ fprintf(stderr, "%s: too big fd %d on %s\n", program_name, socks[i], my_name); fatal(); } FD_SET(socks[i], &writable); if (max_fd < socks[i]) max_fd = socks[i]; } if (max_fd == -1) { /* full_stripe finished */ transfered += full_stripe_size; for (i = 0; i < ndivisions; i++) gfs_client_rep_transfer_stripe_next( transfers[i]); if (buffer_read < buffer_to_be_read) { to_be_read = buffer_to_be_read - buffer_read; if (read_result != GFS_ERROR_NOERROR) { memset(buffers[1 - buffer_cycle] + buffer_read, 0, to_be_read); } else { rv = read(ifd, buffers[1 - buffer_cycle] + buffer_read, to_be_read); /* * XXX - we cannot stop here, because * currently there is no way to cancel * on-going transfer. */ if (rv == -1) { read_result = gfs_errno_to_proto_error( errno); memset(buffers[1-buffer_cycle]+ buffer_read, 0,to_be_read); } else if (rv < to_be_read) { read_result = GFS_ERROR_EXPIRED; memset(buffers[1-buffer_cycle]+ buffer_read + rv, 0, to_be_read - rv); } } } buffer_to_be_read = size - transfered - buffer_to_be_read < full_stripe_size ? size - transfered - buffer_to_be_read : full_stripe_size; buffer_read = 0; buffer_cycle = 1 - buffer_cycle; continue; } do { nfound = select(max_fd + 1, NULL, &writable, NULL, NULL); } while (nfound == -1 && errno == EINTR); if (nfound <= 0) { fprintf(stderr, "%s: parallel_transfer select: %s\n", program_name, nfound < 0 ? strerror(errno) : "assertion failed"); fatal(); } for (i = 0, offset = 0; i < ndivisions; i++, offset += interleave_factor) { if (!FD_ISSET(socks[i], &writable)) continue; len = gfs_client_rep_transfer_length(transfers[i], interleave_factor); e = xxx_write_direct(conns[i], buffers[buffer_cycle] + offset + gfs_client_rep_transfer_stripe_offset(transfers[i]), len, &len); if (e != NULL) goto finish; gfs_client_rep_transfer_stripe_progress(transfers[i], len); if (rinfos != NULL) gfs_client_rep_rate_control(rinfos[i], len); } if (buffer_read < buffer_to_be_read) { to_be_read = file_read_size < buffer_to_be_read - buffer_read ? file_read_size : buffer_to_be_read - buffer_read; if (read_result != GFS_ERROR_NOERROR) { memset(buffers[1 - buffer_cycle] + buffer_read, 0, to_be_read); } else { rv = read(ifd, buffers[1 - buffer_cycle] + buffer_read, to_be_read); /* * XXX - we cannot stop here, because * currently there is no way to cancel * on-going transfer. */ if (rv == -1) { read_result = gfs_errno_to_proto_error(errno); memset(buffers[1 - buffer_cycle] + buffer_read, 0, to_be_read); } else { read_result = GFS_ERROR_EXPIRED; memset(buffers[1 - buffer_cycle] + buffer_read + rv, 0, to_be_read - rv); } } buffer_read += to_be_read; } } *read_resultp = read_result; finish: if (ifd != -1) close(ifd); free(buffers[1]); free(buffers[0]); return (e); } char * transfer(char *file, int ifd, file_offset_t size, int algorithm_version, int ndivisions, int interleave_factor, int file_read_size, int send_stripe_sync, struct xxx_connection **conns, int *socks, struct gfs_client_rep_rate_info **rinfos, gfarm_int32_t *read_resultp) { char *e; struct gfs_client_rep_transfer_state **transfers; ndivisions = gfs_client_rep_limit_division( algorithm_version, ndivisions, size); if (ndivisions == -1) return ("unknown algorithm version"); if (ndivisions == 1) return (sequential_transfer(ifd, size, file_read_size, conns[0], rinfos != NULL ? rinfos[0] : NULL, read_resultp)); e = gfs_client_rep_transfer_state_alloc(size, algorithm_version, ndivisions, interleave_factor, &transfers); if (e != NULL) return (e); e = (*(send_stripe_sync ? parallel_transfer_with_parallel_diskio : parallel_transfer_with_sequential_diskio))(file, ifd, size, ndivisions, interleave_factor, file_read_size, conns, socks, transfers, rinfos, read_resultp); gfs_client_rep_transfer_state_free(ndivisions, transfers); return (e); } int open_accepting_socket() { char *e; struct sockaddr_in self_addr; socklen_t self_addr_size; int sock, port; #if 0 int sockopt; #endif sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { fprintf(stderr, "%s: accepting socket: %s\n", program_name, strerror(errno)); fatal(); } #if 0 sockopt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) == -1) { fprintf(stderr, "%s: SO_REUSEADDR: %s\n", program_name, strerror(errno)); } #endif for (port = PORT_MINIMUM; port <= PORT_MAXIMUM; port++) { memset(&self_addr, 0, sizeof(self_addr)); self_addr.sin_family = AF_INET; self_addr.sin_addr.s_addr = INADDR_ANY; self_addr.sin_port = htons(port); self_addr_size = sizeof(self_addr); if (bind(sock, (struct sockaddr *)&self_addr, self_addr_size) == -1) { if (errno == EADDRINUSE) continue; fprintf(stderr, "%s: bind accepting socket: %s\n", program_name, strerror(errno)); fatal(); } break; } if (port > PORT_MAXIMUM) { fprintf(stderr, "%s: bind: port not available between %d and %d\n", program_name, PORT_MINIMUM, PORT_MAXIMUM); fatal(); } e = gfarm_sockopt_apply_listener(sock); if (e != NULL) { fprintf(stderr, "%s: setsockopt: %s\n", program_name, e); } if (listen(sock, LISTEN_BACKLOG) < 0) { fprintf(stderr, "%s: listen: %s\n", program_name, strerror(errno)); fatal(); } return (sock); } void session(struct xxx_connection *from_client, struct xxx_connection *to_client, int algorithm_version, int ndivisions, int interleave_factor, int send_stripe_sync, int n, gfarm_stringlist *files, gfarm_stringlist *sections) { char *e, *pathname; gfarm_int32_t r; int i, listening_sock, *socks, ifd; long file_read_size; struct xxx_connection **conns; struct gfs_client_rep_rate_info **rinfos = NULL; #ifdef __GNUC__ /* shut up stupid warning by gcc */ file_offset_t file_size = 0; #else file_offset_t file_size; #endif struct stat st; struct sockaddr_in listen_addr, client_addr; socklen_t listen_addr_len, client_addr_len; if (rate_limit != 0) { rinfos = malloc(sizeof(*rinfos) * ndivisions); if (rinfos == NULL) { fprintf(stderr, "%s: no memory for %d rate limits " "on gfrebe_server %s\n", program_name, ndivisions, my_name); fatal(); } for (i = 0; i < ndivisions; i++) { rinfos[i] = gfs_client_rep_rate_info_alloc(rate_limit); if (rinfos[i] == NULL) { fprintf(stderr, "%s: no memory for %d/%d rate limit " "on gfrebe_server %s\n", program_name, i, ndivisions, my_name); fatal(); } } } socks = malloc(sizeof(*socks) * ndivisions); conns = malloc(sizeof(*conns) * ndivisions); if (socks == NULL || conns == NULL) { if (socks != NULL) free(socks); if (conns != NULL) free(conns); fprintf(stderr, "%s: no memory for %d connections on gfrebe_server %s\n", program_name, ndivisions, my_name); fatal(); } /* * XXX FIXME: this port may be blocked by firewall. * This should be implemented via gfsd connection passing service. */ listening_sock = open_accepting_socket(); listen_addr_len = sizeof(listen_addr); if (getsockname(listening_sock, (struct sockaddr *)&listen_addr, &listen_addr_len) == -1) { fprintf(stderr, "%s: getsockname: %s\n", program_name, strerror(errno)); fatal(); } e = xxx_proto_send(to_client, "i", htons(listen_addr.sin_port)); if (e == NULL) e = xxx_proto_flush(to_client); if (e != NULL) { fprintf(stderr, "%s: while sending port number on %s: %s\n", program_name, my_name, e); fatal(); } /* XXX FIXME: make connections in parallel */ for (i = 0; i < ndivisions; i++) { client_addr_len = sizeof(client_addr); socks[i] = accept(listening_sock, (struct sockaddr *)&client_addr, &client_addr_len); if (socks[i] == -1) { if (errno == EINTR) { --i; continue; } fprintf(stderr, "%s: while accepting sockets on %s: %s\n", program_name, my_name, strerror(errno)); fatal(); } e = xxx_fd_connection_new(socks[i], &conns[i]); if (e != NULL) { fprintf(stderr, "%s: while allocating connection %d on %s: %s\n", program_name, i, my_name, e); fatal(); } e = gfarm_authorize(conns[i], 1, GFREPBE_SERVICE_TAG, NULL, NULL, NULL); if (e != NULL) { fprintf(stderr, "%s: authorization on %s: %s\n", program_name, my_name, e); fatal(); } e = xxx_proto_send(conns[i], "i", i); if (e == NULL) e = xxx_proto_flush(conns[i]); if (e != NULL) { fprintf(stderr, "%s: sending connection index on %s: %s\n", program_name, my_name, e); fatal(); } } close(listening_sock); e = gfarm_netparam_config_get_long(&gfarm_netparam_file_read_size, NULL, (struct sockaddr *)&client_addr, &file_read_size); if (e != NULL) { /* shouldn't happen */ fprintf(stderr, "%s: get netparam file_read_size on %s: %s\n", program_name, my_name, e); fatal(); } e = gfarm_netparam_config_get_long(&gfarm_netparam_rate_limit, NULL, (struct sockaddr *)&client_addr, &rate_limit); if (e != NULL) { /* shouldn't happen */ fprintf(stderr, "%s: get netparam rate_limit on %s: %s\n", program_name, my_name, e); fatal(); } for (i = 0; i < n; i++) { char *file = gfarm_stringlist_elem(files, i); char *section = gfarm_stringlist_elem(sections, i); /* NOTE: assumes current directory == spool_root */ if (*section == '\0') { pathname = file; } else { pathname = malloc(strlen(file) + strlen(section) + 2); if (pathname == NULL) { fprintf(stderr, "%s: no memory for pathname %s:%s" " to replicate on %s\n", program_name, file, section, my_name); fatal(); } sprintf(pathname, "%s:%s", file, section); } ifd = open(pathname, O_RDONLY); if (ifd == -1) { r = gfs_errno_to_proto_error(errno); } else if (fstat(ifd, &st) == -1) { r = gfs_errno_to_proto_error(errno); } else { r = GFS_ERROR_NOERROR; file_size = st.st_size; } e = xxx_proto_send(conns[0], "i", r); if (e != NULL) { fprintf(stderr, "%s: send reply on %s\n", program_name, my_name); fatal(); } if (r != GFS_ERROR_NOERROR) continue; e = xxx_proto_send(conns[0], "o", file_size); if (e == NULL) e = xxx_proto_flush(conns[0]); if (e != NULL) { fprintf(stderr, "%s: send reply on %s\n", program_name, my_name); fatal(); } e = transfer(pathname, ifd, file_size, algorithm_version, ndivisions, interleave_factor, file_read_size, send_stripe_sync, conns, socks, rinfos, &r); close(ifd); e = xxx_proto_send(conns[0], "i", r); if (e != NULL) { fprintf(stderr, "%s: send reply on %s\n", program_name, my_name); fatal(); } if (*section != '\0') free(pathname); } e = xxx_proto_flush(conns[0]); if (e != NULL) { fprintf(stderr, "%s: send reply on %s\n", program_name, my_name); fatal(); } for (i = 0; i < ndivisions; i++) xxx_connection_free(conns[i]); free(conns); free(socks); if (rinfos != NULL) { for (i = 0; i < ndivisions; i++) gfs_client_rep_rate_info_free(rinfos[i]); free(rinfos); } } void usage(void) { fprintf(stderr, "Usage: %s [-p] " "[-i interleave_factor] [-n <ndivisions>]\n", program_name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int algorithm_version = -1; gfarm_int32_t interleave_factor = 0; gfarm_int32_t ndivisions = 1; int send_stripe_sync = 0; struct xxx_connection *from_client, *to_client; char *e; int c, n; gfarm_stringlist files, sections; /* should be read from /etc/gfarm.conf */ int syslog_facility = GFARM_DEFAULT_FACILITY; while ((c = getopt(argc, argv, "a:i:n:sS:")) != -1) { switch (c) { case 'a': algorithm_version = atoi(optarg); break; case 'i': interleave_factor = atoi(optarg); break; case 'n': ndivisions = atoi(optarg); break; case 's': send_stripe_sync = 1; break; default: fprintf(stderr, "%s: unknown option -%c\n", program_name, c); usage(); /*NOTREACHED*/ } } argc -= optind; argv += optind; my_name = my_name; if (argc != 0) { fprintf(stderr, "%s: too many argument on %s: %s\n", program_name, my_name, argv[0]); usage(); /*NOTREACHED*/ } if (algorithm_version == -1) { fprintf(stderr, "%s: missing mandatory option: -a <version>\n", program_name); usage(); /*NOTREACHED*/ } e = gfarm_server_initialize(); if (e != NULL) { fprintf(stderr, "gfarm_server_initialize: %s\n", e); exit(1); } e = gfrepbe_auth_initialize(); if (e != NULL) { fprintf(stderr, "gfarm_auth_initialize: %s\n", e); exit(1); } /* makes current directory == spool_root */ if (chdir(gfarm_spool_root) == -1) { fprintf(stderr, "%s: chdir(%s) on %s: %s\n", program_name, gfarm_spool_root, my_name, e); fatal(); } /* XXX read-only connection */ e = xxx_fd_connection_new(STDIN_FILENO, &from_client); if (e != NULL) { fprintf(stderr, "%s: %s for stdin\n", program_name, e); fatal(); } /* XXX write-only connection */ e = xxx_fd_connection_new(STDOUT_FILENO, &to_client); if (e != NULL) { fprintf(stderr, "%s: %s for stdout\n", program_name, e); fatal(); } e = gfs_client_rep_filelist_receive(from_client, &n, &files, &sections, program_name); if (e != NULL) fatal(); gflog_set_identifier(program_name); gflog_syslog_open(LOG_PID, syslog_facility); session(from_client, to_client, algorithm_version, ndivisions, interleave_factor, send_stripe_sync, n, &files, &sections); return (0); } <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_utils.inc # Syslog facility SYSLOG_FACILITY=${SYSLOG_FACILITY:-"local0"} # Timeout interval of 'gf*' command. TIMEOUT=${TIMEOUT:-12} # Exit code of 'gfservice-timeout' when timeout occurs. TIMEOUT_EXITCODE=124 # # Output a syslog message of the priority 'err'. # # Arguments: # $@ A log message. # # Return value. # It always returns 0. # log_err() { logger -p $SYSLOG_FACILITY.err -i -t `basename $0` "$@" return 0 } # # Output a syslog message of the priority 'warning'. # # Arguments: # $@ A log message. # # Return value. # It always returns 0. # log_warning() { logger -p $SYSLOG_FACILITY.warning -i -t `basename $0` "$@" return 0 } # # Output a syslog message of the priority 'notice'. # # Arguments: # $@ A log message. # # Return value. # It always returns 0. # log_notice() { logger -p $SYSLOG_FACILITY.notice -i -t `basename $0` "$@" return 0 } # # Output a syslog message of the priority 'info'. # # Arguments: # $@ A log message. # # Return value. # It always returns 0. # log_info() { logger -p $SYSLOG_FACILITY.info -i -t `basename $0` "$@" return 0 } # # Check an authentication error occcurs at execution of gf* command. # # Arguments: # $1 a flie which records error messages of the gf* command. # # Return value. # Return 0 in case of authentication error. # check_auth_error() { test -r "$1" || return 0 grep 'libgfarm: <err> \[1000059\]' "$1" > /dev/null 2>&1 } <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/gftool/gfexec/gfexec.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <gfarm/gfarm.h> static char progname[] = "gfexec"; int main(int argc, char *argv[], char *envp[]) { char *e, *gfarm_url, **saved_argv; int i, saved_argc; --argc, ++argv; if (argc < 1) { printf("usage: %s program args ...\n", progname); exit(2); } /* save argv because it may be modified in gfarm_initialize() */ saved_argc = argc; saved_argv = malloc(argc * sizeof(char *) + 1); if (saved_argv == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } for (i = 0; i < argc; ++i) { saved_argv[i] = strdup(argv[i]); if (saved_argv[i] == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } } saved_argv[i] = '\0'; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); exit(1); } e = gfs_realpath(*saved_argv, &gfarm_url); if (e != NULL) { /* not found in Gfarm file system */ execvp(*saved_argv, saved_argv); perror(*saved_argv); exit(1); } e = gfs_execve(gfarm_url, saved_argv, envp); fprintf(stderr, "%s: %s\n", gfarm_url, e); free(gfarm_url); for (i = 0; i < saved_argc; ++i) free(saved_argv[i]); free(saved_argv); /* * Should not call gfarm_terminate() here, because it has been * already called in gfs_execve(). */ exit(1); } <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/gftool/gfstat/gfstat.c /* * $Id$ */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <libgen.h> #include <gfarm/gfarm.h> /* * Display struct gfs_stat. */ void display_stat(char *fn, struct gfs_stat *st) { printf(" File: \"%s\"\n", fn); printf(" Size: %-12" PR_FILE_OFFSET " Filetype: ", st->st_size); switch (st->st_mode & GFARM_S_IFMT) { case GFARM_S_IFREG: puts("regular file"); break; case GFARM_S_IFDIR: puts("directory"); break; default: printf("unknown\n"); } printf(" Num of sections: %d\n", st->st_nsections); printf(" Mode: (%04o) Uid: (%8s) Gid: (%8s)\n", st->st_mode & GFARM_S_ALLPERM, st->st_user, st->st_group); printf("Access: %s", ctime((time_t *)&st->st_atimespec.tv_sec)); printf("Modify: %s", ctime((time_t *)&st->st_mtimespec.tv_sec)); printf("Change: %s", ctime((time_t *)&st->st_ctimespec.tv_sec)); } void usage(char *prog_name) { fprintf(stderr, "Usage: %s file1 [file2 ...]\n", prog_name); exit(2); } /* * */ int main(int argc, char *argv[]) { char *prog_name = basename(argv[0]); char c, *e; extern int optind; int r = 0; while ((c = getopt(argc, argv, "h")) != -1) { switch (c) { case 'h': case '?': default: usage(prog_name); } } argc -= optind; argv += optind; if (argc < 1) usage(prog_name); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", prog_name, e); exit(1); } while (*argv) { struct gfs_stat st; char *url; e = gfs_realpath(*argv, &url); if (e != NULL) { fprintf(stderr, "%s: %s\n", *argv, e); r = 1; ++argv; continue; } e = gfs_stat(url, &st); if (e != NULL) { fprintf(stderr, "%s: %s\n", url, e); r = 1; free(url); ++argv; continue; } display_stat(url, &st); gfs_stat_free(&st); free(url); ++argv; } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", prog_name, e); exit(1); } exit(r); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_3/id.h /* * $Id$ */ void gfarm2fs_id_init(struct gfarm2fs_param *); gfarm_error_t gfarm2fs_get_uid(const char *, const char *, uid_t *); gfarm_error_t gfarm2fs_get_gid(const char *, const char *, gid_t *); gfarm_error_t gfarm2fs_get_user(const char *, uid_t, char **); gfarm_error_t gfarm2fs_get_group(const char *, gid_t, char **); uid_t gfarm2fs_get_nobody_uid(); gid_t gfarm2fs_get_nogroup_gid(); <file_sep>/gfarm/tags/gfarm_1_0_3_rc1/gfptool/gfcp/gfcp.c /* * $Id$ * * Copy a file */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> char *program_name = "gfcp"; void usage() { fprintf(stderr, "Usage: %s [option] <input_file> <output_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-p\t\t\tpreserve file status\n"); fprintf(stderr, "\t-I fragment-index\tspecify a fragment index\n"); exit(1); } #define BUFSIZE 65536 int main(int argc, char *argv[]) { int flag_preserve = 0; char *e, c, *input, *output, *gfarm_index = NULL; GFS_File igf, ogf; struct gfs_stat gstat; gfarm_mode_t mode; struct gfarm_timespec gtspec[2]; extern char *optarg; extern int optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; while ((c = getopt(argc, argv, "hI:p?")) != -1) { switch (c) { case 'p': flag_preserve = 1; break; case 'I': gfarm_index = optarg; break; case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; if (argc < 2 || argc > 3 /* XXX */) usage(); output = argv[argc - 1]; --argc; e = gfs_stat(output, &gstat); if (e == NULL && GFARM_S_ISDIR(gstat.st_mode)) { fprintf(stderr, "%s: is a directory, not supported yet\n", output); exit(1); } #if 0 /* XXX - gfs_stat() may return a non-null pointer because a process in the same parallel process might create it already. */ else if (e == NULL) { fprintf(stderr, "%s: already exist\n", output); exit(1); } #endif gfs_stat_free(&gstat); e = gfs_realpath(*argv, &input); if (e != NULL) { fprintf(stderr, "%s: %s\n", *argv, e); exit(1); } e = gfs_stat(input, &gstat); if (e != NULL) { fprintf(stderr, "%s: %s\n", input, e); exit(1); } if (flag_preserve) { mode = gstat.st_mode; gtspec[0] = gstat.st_atimespec; gtspec[1] = gstat.st_mtimespec; } else mode = 0666; gfs_stat_free(&gstat); /** **/ e = gfs_pio_open(input, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "%s: %s\n", input, e); exit(1); } if (gfarm_index == NULL) { e = gfs_pio_set_view_local(igf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: set_view_local(%s): %s\n", program_name, input, e); exit(1); } } else { e = gfs_pio_set_view_section( igf, gfarm_index, NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: set_view_section(%s, %s): %s\n", program_name, input, gfarm_index, e); exit(1); } } /** **/ e = gfs_pio_create(output, GFARM_FILE_WRONLY, mode, &ogf); if (e != NULL) { fprintf(stderr, "%s: cannot open %s: %s\n", program_name, output, e); exit(1); } if (gfarm_index == NULL) { e = gfs_pio_set_view_local(ogf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: set_view_local(%s): %s\n", program_name, output, e); exit(1); } } else { e = gfs_pio_set_view_section( ogf, gfarm_index, NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: set_view_section(%s, %s): %s\n", program_name, output, gfarm_index, e); exit(1); } } /* copy this fragment */ for (;;) { int rv, wv; char buffer[BUFSIZE]; e = gfs_pio_read(igf, buffer, sizeof(buffer), &rv); if (e != NULL || rv == 0) break; e = gfs_pio_write(ogf, buffer, rv, &wv); if (e != NULL) break; } if (e != NULL) fprintf(stderr, "%s\n", e); e = gfs_pio_close(igf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", input, e); e = gfs_pio_close(ogf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", output, e); if (flag_preserve) { e = gfs_utimes(output, gtspec); if (e != NULL) fprintf(stderr, "%s: utimes failed: %s\n", output, e); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/gftool/gfarm_agent/agent_ptable.c /* * $Id$ */ #include <stdlib.h> #include <pthread.h> #include "agent_ptable.h" #define PTABLE_LEN 4096 #define PTABLE_OUT_OF_RANGE(p) ((p) < 0 || (p) >= PTABLE_LEN) static pthread_key_t ptable_key; static pthread_key_t ptable_free_ptr_key; static pthread_once_t ptable_key_once = PTHREAD_ONCE_INIT; static void agent_ptable_destroy(void *buf) { free(buf); } static void agent_ptable_key_alloc() { pthread_key_create(&ptable_key, agent_ptable_destroy); pthread_key_create(&ptable_free_ptr_key, NULL); } static void agent_ptable_free_ptr_set(int p) { int *free_ptr; free_ptr = pthread_getspecific(ptable_free_ptr_key); *free_ptr = p; } static int agent_ptable_free_ptr_get(void) { int *free_ptr; free_ptr = pthread_getspecific(ptable_free_ptr_key); return (*free_ptr); } void agent_ptable_alloc(void) { pthread_once(&ptable_key_once, agent_ptable_key_alloc); pthread_setspecific(ptable_key, calloc(PTABLE_LEN, sizeof(void *))); pthread_setspecific(ptable_free_ptr_key, malloc(sizeof(int))); /* free pointer begins with 1 */ agent_ptable_free_ptr_set(1); } static int agent_ptable_entry_set(int p, void *ptr) { void **ptable; /* adjust the range from [1:PTABLE_LEN] to [0:PTABLE_LEN-1] */ p = p - 1; if (PTABLE_OUT_OF_RANGE(p)) return (-1); ptable = pthread_getspecific(ptable_key); ptable[p] = ptr; return (0); } void * agent_ptable_entry_get(int p) { void **ptable; /* adjust the range from [1:PTABLE_LEN] to [0:PTABLE_LEN-1] */ p = p - 1; if (PTABLE_OUT_OF_RANGE(p)) return (0); ptable = pthread_getspecific(ptable_key); return (ptable[p]); } int agent_ptable_entry_add(void *ptr) { int saved_ptr, free_ptr; free_ptr = saved_ptr = agent_ptable_free_ptr_get(); if (agent_ptable_entry_get(free_ptr)) return (-1); agent_ptable_entry_set(free_ptr, ptr); while (agent_ptable_entry_get(++free_ptr)); agent_ptable_free_ptr_set(free_ptr); return (saved_ptr); } int agent_ptable_entry_delete(int p) { int free_ptr; if (agent_ptable_entry_get(p)) agent_ptable_entry_set(p, 0); else return (-1); free_ptr = agent_ptable_free_ptr_get(); if (p < free_ptr) agent_ptable_free_ptr_set(p); return (0); } <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/Makefile top_objdir = .. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk GLOBUS_SUBDIRS = libgfarm/gfsl SUBDIRS = \ libgfarm \ gfs_hook \ $(globus_subdirs) include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/gfarm-zabbix_redundancy/mds_list/scripts/zbx_check_gfarm2_conf.sh #!/bin/sh # # @(#) zbx_check_gfarm2_conf.sh # # Usage: # zbx_check_gfarm2_conf.sh # # Description: # a script for checking gfarm2.conf on the Gfarm2 file system. # ############################################################################### # defines PATH=$PATH:/usr/local/bin GFARM2_PREFIX=/usr/local GFARM2_CONF=$GFARM2_PREFIX/etc/gfarm2.conf LOCK_FILE=/tmp/zbx_check_gfarm2_conf.lock RES_FILE=/tmp/gfls_result.txt ERR_FILE=/tmp/gfls_error.txt CHK_CMD='sudo -u zabbix gfls -ld /' TIMEOUT=10 NEW_GFARM2_CONF=$1 # check arguments. if [ X"$NEW_GFARM2_CONF" = X ]; then echo "Specify file name."; exit 1 fi # check gfarm2.conf for the host. if [ ! -f $GFARM2_CONF ]; then echo "$GFARM2_CONF not found."; exit 1 fi # check upload Gfarm2 config file. if [ ! -f $NEW_GFARM2_CONF ]; then echo "$NEW_GFARM2_CONF not found."; exit 1 fi # check the lock file. if [ -f $LOCK_FILE ]; then echo "Another process is using this checker."; exit 1 fi # create the lock file. touch $LOCK_FILE # execute to heck Gfarm2 configuration. if [ -f $GFARM2_CONF.org ]; then rm -f $GFARM2_CONF.org fi if [ -f $RES_FILE ]; then rm -f $RES_FILE fi if [ -f $ERR_FILE ]; then rm -f $ERR_FILE fi # back up gfarm2.conf for the host. mv -f $GFARM2_CONF $GFARM2_CONF.org cp -f $NEW_GFARM2_CONF $GFARM2_CONF $CHK_CMD > $RES_FILE 2> $ERR_FILE & PID=$! count=0 while [ $count -lt $TIMEOUT ]; do TO_CHK=`ps -ef | awk '{ print $2 }' | grep $PID` if [ X$TO_CHK = X ]; then break fi count=`expr $count + 1` sleep 1 done if [ -f $RES_FILE ]; then RESULT=`cat $RES_FILE` fi # set the return value. if [ $count -ge $TIMEOUT ]; then RESULT="timeout" elif [ X"$RESULT" = X ]; then RESULT="error" else RESULT="success" fi # recover gfarm2.conf for the host. rm -f $GFARM2_CONF mv -f $GFARM2_CONF.org $GFARM2_CONF # remove the lock file. rm -f $LOCK_FILE echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_2_rc2/lib/libgfarm/gfarm/gfs_lock.h /* * $Id$ */ int gfs_lock_local_path_section(char *); int gfs_unlock_local_path_section(char *); <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/iobuffer.h /* * FIFO style input/output buffer * * enqueue functions: * gfarm_iobuffer_read() * gfarm_iobuffer_put() * * dequeue functions: * gfarm_iobuffer_write() * gfarm_iobuffer_get() * gfarm_iobuffer_purge() * gfarm_iobuffer_flush_write() * * enqueue side can notify EOF by either * the read_func() hook function returns 0 * or * calling gfarm_iobuffer_set_read_eof() function * * dequeue side can notice EOF by either * gfarm_iobuffer_is_writable(b) && * gfarm_iobuffer_empty(b) * i.e. * gfarm_iobuffer_is_writable(b) && * gfarm_iobuffer_avail_length(b) == 0 * i.e. * gfarm_iobuffer_is_eof(b) && * !gfarm_iobuffer_is_write_eof(b) * or * the write_close() hook function is called at dequeue operation. * note that the write_close() hook will be called at the dequeue * function call just after the above conditions become true. * * Once a dequeue function is called after the above conditions * (i.e. once a write_close() hook is called), the above conditions becomes * untrue, and the following conditions become true: * gfarm_iobuffer_is_write_eof(b) * and * !gfarm_iobuffer_is_writable(b) * * of course, the following conditions are all true at that time: * gfarm_iobuffer_empty(b) * and * gfarm_iobuffer_avail_length(b) == 0 * and * gfarm_iobuffer_is_read_eof(b) * and * gfarm_iobuffer_is_eof(b) */ struct gfarm_iobuffer; struct gfarm_iobuffer *gfarm_iobuffer_alloc(int); void gfarm_iobuffer_free(struct gfarm_iobuffer *); void gfarm_iobuffer_set_error(struct gfarm_iobuffer *, char *); char *gfarm_iobuffer_get_error(struct gfarm_iobuffer *); int gfarm_iobuffer_empty(struct gfarm_iobuffer *); int gfarm_iobuffer_full(struct gfarm_iobuffer *); int gfarm_iobuffer_avail_length(struct gfarm_iobuffer *); void gfarm_iobuffer_set_read_eof(struct gfarm_iobuffer *); void gfarm_iobuffer_clear_read_eof(struct gfarm_iobuffer *); int gfarm_iobuffer_is_read_eof(struct gfarm_iobuffer *); void gfarm_iobuffer_clear_write_eof(struct gfarm_iobuffer *); int gfarm_iobuffer_is_write_eof(struct gfarm_iobuffer *); int gfarm_iobuffer_is_readable(struct gfarm_iobuffer *); int gfarm_iobuffer_is_writable(struct gfarm_iobuffer *); int gfarm_iobuffer_is_eof(struct gfarm_iobuffer *); /* enqueue */ void gfarm_iobuffer_set_read(struct gfarm_iobuffer *, int (*)(struct gfarm_iobuffer *, void *, int, void *, int), void *, int); void *gfarm_iobuffer_get_read_cookie(struct gfarm_iobuffer *); int gfarm_iobuffer_get_read_fd(struct gfarm_iobuffer *); void gfarm_iobuffer_read(struct gfarm_iobuffer *, int *); int gfarm_iobuffer_put(struct gfarm_iobuffer *, void *, int); /* dequeue */ void gfarm_iobuffer_set_write_close(struct gfarm_iobuffer *, void (*)(struct gfarm_iobuffer *, void *, int)); void gfarm_iobuffer_set_write(struct gfarm_iobuffer *, int (*)(struct gfarm_iobuffer *, void *, int, void *, int), void *, int); void *gfarm_iobuffer_get_write_cookie(struct gfarm_iobuffer *); int gfarm_iobuffer_get_write_fd(struct gfarm_iobuffer *); void gfarm_iobuffer_write(struct gfarm_iobuffer *, int *); int gfarm_iobuffer_purge(struct gfarm_iobuffer *, int *); int gfarm_iobuffer_get(struct gfarm_iobuffer *, void *, int); void gfarm_iobuffer_flush_write(struct gfarm_iobuffer *); /* enqueue by memory copy, dequeue by write */ int gfarm_iobuffer_put_write(struct gfarm_iobuffer *, void *, int); /* enqueue by read, dequeue by purge */ int gfarm_iobuffer_purge_read_x(struct gfarm_iobuffer *, int, int); /* enqueue by read, dequeue by memory copy */ int gfarm_iobuffer_get_read_x(struct gfarm_iobuffer *, void *, int, int); int gfarm_iobuffer_get_read_just(struct gfarm_iobuffer *, void *, int); int gfarm_iobuffer_get_read(struct gfarm_iobuffer *, void *, int); int gfarm_iobuffer_get_read_partial_x(struct gfarm_iobuffer *, void *,int,int); int gfarm_iobuffer_get_read_partial_just(struct gfarm_iobuffer *, void *, int); int gfarm_iobuffer_get_read_partial(struct gfarm_iobuffer *, void *, int); /* * gfarm_iobuffer_get_read{,_partial}_just() functions doesn't perform * read ahead for given stream, so the caller can perform read operation * for the stream without calling iobuffer layer or with another iobuffer * at subsequent the call. * gfarm_iobuffer_{purge_read,get_read{,_partial}}_x() functions take * the `just' flag at its last argument. */ /* default operation for gfarm_iobuffer_set_write_close() */ void gfarm_iobuffer_write_close_nop(struct gfarm_iobuffer *, void *, int); <file_sep>/gfarm/tags/gfarm_1_0_beta_5_fix1/lib/libgfarm/gfsl/session.c #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <ctype.h> #include <pwd.h> #include <gssapi.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/time.h> #include <gfarm/gfarm_config.h> #include "gfevent.h" #include "gfarm_secure_session.h" #include "tcputil.h" #include "misc.h" /* #define SS_DEBUG */ /* * Initial credential and its name. */ static gss_cred_id_t initiatorInitialCred = GSS_C_NO_CREDENTIAL; static gss_cred_id_t acceptorInitialCred = GSS_C_NO_CREDENTIAL; static char *initiatorInitialCredName = NULL; static char *acceptorInitialCredName = NULL; static int initiatorInitialized = 0; static int acceptorInitialized = 0; /* * Communication option read from configuration file. */ static gfarmSecSessionOption acceptorSsOpt = GFARM_SS_DEFAULT_OPTION; static gfarmSecSessionOption initiatorSsOpt = GFARM_SS_DEFAULT_OPTION; static int canonicSecSessionOpt(int which, gfarmSecSessionOption *reqPtr, gfarmSecSessionOption *canPtr); static gfarmSecSession * allocSecSession(int which); static void destroySecSession(gfarmSecSession *ssPtr); static int secSessionReadConfigFile(char *configFile, gfarmSecSessionOption *ssOptPtr); static int negotiateConfigParam(int fd, gss_ctx_id_t sCtx, int which, gfarmSecSessionOption *canPtr, gss_qop_t *qOpPtr, unsigned int *maxTransPtr, unsigned int *configPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); static gfarmSecSession * secSessionInitiate(int fd, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr, int needClose); #ifdef SS_DEBUG static void dumpConfParam(gss_qop_t qOp, unsigned int max, unsigned int conf); static void dumpSsOpt(gfarmSecSessionOption *ssOptPtr); static void dumpConfParam(qOp, max, conf) gss_qop_t qOp; unsigned int max; unsigned int conf; { fprintf(stderr, "\tQOP:\t%d\n", (int)qOp); fprintf(stderr, "\tMAX:\t%d\n", max); fprintf(stderr, "\tOPT:\t(%d)", conf); if (conf & GFARM_SS_USE_ENCRYPTION) { fprintf(stderr, " encrypt"); } if (conf & GFARM_SS_USE_COMPRESSION) { fprintf(stderr, " compress"); } fprintf(stderr, "\n"); } static void dumpSsOpt(ssOptPtr) gfarmSecSessionOption *ssOptPtr; { fprintf(stderr, "\n\tQOP:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_QOP_MASK) { fprintf(stderr, "%d%s\n", (int)ssOptPtr->qOpReq, (ssOptPtr->qOpForce == 1) ? " (force)" : ""); } else { fprintf(stderr, "none\n"); } fprintf(stderr, "\tMAX:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_MAXT_MASK) { fprintf(stderr, "%d%s\n", (int)ssOptPtr->maxTransSizeReq, (ssOptPtr->maxTransSizeForce == 1) ? " (force)" : ""); } else { fprintf(stderr, "none\n"); } fprintf(stderr, "\tOPT:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_CONF_MASK) { fprintf(stderr, "(%d)", ssOptPtr->configReq); if (ssOptPtr->configReq & GFARM_SS_USE_ENCRYPTION) { fprintf(stderr, " encrypt"); } if (ssOptPtr->configReq & GFARM_SS_USE_COMPRESSION) { fprintf(stderr, " compress"); } if (ssOptPtr->configForce == 1) { fprintf(stderr, " (force)"); } fprintf(stderr, "\n\n"); } else { fprintf(stderr, "none\n\n"); } } #endif /* SS_DEBUG */ static int secSessionReadConfigFile(configFile, ssOptPtr) char *configFile; gfarmSecSessionOption *ssOptPtr; { FILE *fd = NULL; char lineBuf[65536]; char *token[64]; int nToken; gfarmSecSessionOption ssTmp = GFARM_SS_DEFAULT_OPTION; int i; if (configFile == NULL || configFile[0] == '\0') { return -1; } if ((fd = fopen(configFile, "r")) == NULL) { /* * use default option. */ goto Done; } while (fgets(lineBuf, 65536, fd) != NULL) { nToken = gfarmGetToken(lineBuf, token, 64); if (nToken <= 0) { continue; } if (token[0][0] == '#') { continue; } if (strcasecmp(token[0], "qop:") == 0) { for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.qOpForce = 1; } else if (strcasecmp(token[i], "default") == 0 || strcasecmp(token[i], "gfarm") == 0) { ssTmp.qOpReq = GFARM_GSS_DEFAULT_QOP; #if defined(USE_GLOBUS) && defined(GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG) } else if (strcasecmp(token[i], "globus") == 0) { ssTmp.qOpReq = GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG; #endif /* USE_GLOBUS */ } else if (strcasecmp(token[i], "gssapi") == 0) { ssTmp.qOpReq = GSS_C_QOP_DEFAULT; } } } else if (strcasecmp(token[0], "maxtrans:") == 0) { for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.maxTransSizeForce = 1; } else if (strcasecmp(token[i], "default") == 0) { ssTmp.maxTransSizeReq = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; } else { int val; if (gfarmGetInt(token[i], &val) == 1) { if (val < 0) { val = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; } ssTmp.maxTransSizeReq = (unsigned int)val; } } } } else if (strcasecmp(token[0], "options:") == 0) { unsigned int opt = GFARM_SS_USE_ENCRYPTION; for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.configForce = 1; } else if (strcasecmp(token[i], "encrypt") == 0) { opt |= GFARM_SS_USE_ENCRYPTION; } else if (strcasecmp(token[i], "compress") == 0) { opt |= GFARM_SS_USE_COMPRESSION; } else if (strcasecmp(token[i], "default") == 0) { opt = GFARM_SS_USE_ENCRYPTION; } } ssTmp.configReq = opt; } } (void)fclose(fd); Done: if (ssOptPtr != NULL) { memcpy((void *)ssOptPtr, (void *)&ssTmp, sizeof(gfarmSecSessionOption)); ssOptPtr->optMask = GFARM_SS_OPT_ALL_MASK; } return 1; } static int canonicSecSessionOpt(which, reqPtr, canPtr) int which; gfarmSecSessionOption *reqPtr; gfarmSecSessionOption *canPtr; { gfarmSecSessionOption *dPtr = (which == GFARM_SS_INITIATOR) ? &initiatorSsOpt : &acceptorSsOpt; if (canPtr == NULL) { return -1; } if (reqPtr == NULL) { (void)memcpy((void *)canPtr, (void *)dPtr, sizeof(gfarmSecSessionOption)); return 1; } #define isMasked(op, msk) ((op)->optMask & msk) == msk #define isUseReq(req, mbr) (req)->mbr == 1 || ((req)->mbr == 0 && dPtr->mbr == 0) #define cpIt(dst, src, mbr) (dst)->mbr = (src)->mbr #define useReq(mbr) cpIt(canPtr, reqPtr, mbr) #define useDef(mbr) cpIt(canPtr, dPtr, mbr) canPtr->optMask |= GFARM_SS_OPT_QOP_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_QOP_MASK)) { if (isUseReq(reqPtr, qOpForce)) { useReq(qOpReq); useReq(qOpForce); } else { goto useQOPDef; } } else { useQOPDef: useDef(qOpReq); useDef(qOpForce); } canPtr->optMask |= GFARM_SS_OPT_MAXT_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_MAXT_MASK)) { if (isUseReq(reqPtr, maxTransSizeForce)) { useReq(maxTransSizeReq); useReq(maxTransSizeForce); } else { goto useMaxTDef; } } else { useMaxTDef: useDef(maxTransSizeReq); useDef(maxTransSizeForce); } canPtr->optMask |= GFARM_SS_OPT_CONF_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_CONF_MASK)) { if (isUseReq(reqPtr, configForce)) { useReq(configReq); useReq(configForce); } else { goto useConfigDef; } } else { useConfigDef: useDef(configReq); useDef(configForce); } return 1; #undef isMasked #undef isUseReq #undef cpIt #undef useReq #undef useDef } static int negotiateConfigParam(fd, sCtx, which, canPtr, qOpPtr, maxTransPtr, configPtr, majStatPtr, minStatPtr) int fd; gss_ctx_id_t sCtx; int which; gfarmSecSessionOption *canPtr; gss_qop_t *qOpPtr; unsigned int *maxTransPtr; unsigned int *configPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = -1; OM_uint32 majStat = GSS_S_FAILURE; OM_uint32 minStat = GFSL_DEFAULT_MINOR_ERROR; gss_qop_t retQOP = GFARM_GSS_DEFAULT_QOP; unsigned int retMaxT = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; unsigned int retConf = GFARM_SS_USE_ENCRYPTION; #define NEGO_PARAM_QOP 0 #define NEGO_PARAM_QOP_FORCE 1 #define NEGO_PARAM_MAX_TRANS_SIZE 2 #define NEGO_PARAM_MAX_TRANS_SIZE_FORCE 3 #define NEGO_PARAM_OTHER_CONFIG 4 #define NEGO_PARAM_OTHER_CONFIG_FORCE 5 #define NUM_NEGO_PARAM 6 if (sCtx == GSS_C_NO_CONTEXT) { goto Done; } switch (which) { long param[NUM_NEGO_PARAM]; case GFARM_SS_ACCEPTOR: { int iQOP, iQOPF; unsigned int iMax; int iMaxF; int iConf, iConfF; if (gfarmReadLongs(fd, param, NUM_NEGO_PARAM) != NUM_NEGO_PARAM) goto Done; iQOP = param[NEGO_PARAM_QOP]; iQOPF = param[NEGO_PARAM_QOP_FORCE]; iMax = param[NEGO_PARAM_MAX_TRANS_SIZE]; iMaxF = param[NEGO_PARAM_MAX_TRANS_SIZE_FORCE]; iConf = param[NEGO_PARAM_OTHER_CONFIG]; iConfF = param[NEGO_PARAM_OTHER_CONFIG_FORCE]; /* * Give precedence to the acceptor on QOP. */ if (canPtr->qOpForce == 0 && iQOPF == 1) { /* * Use the initiator's. */ retQOP = (gss_qop_t)iQOP; } else { /* * Use the acceptor's. */ retQOP = canPtr->qOpReq; } param[NEGO_PARAM_QOP] = retQOP; /* * maximum transmission size */ if (canPtr->maxTransSizeForce == 1) { /* * Use the acceptor's. */ retMaxT = iMax; } else if (iMaxF == 1) { /* * Use the initiator's. */ retMaxT = canPtr->maxTransSizeReq; } else { /* * Both force flags are off. * Use larger one. */ retMaxT = (canPtr->maxTransSizeReq >= iMax) ? canPtr->maxTransSizeReq : iMax; } param[NEGO_PARAM_MAX_TRANS_SIZE] = retMaxT; /* * other configuration flags */ /* compression, systemconf - Give precedence to the acceptor. */ if (canPtr->configForce == 0 && iConfF == 1) { /* * Use the initiator's. */ retConf = canPtr->configReq; } else { /* * Use the acceptor's. */ retConf = iConf; } /* encryption - Take logical or value ignoring both force flags. */ retConf &= ~GFARM_SS_USE_ENCRYPTION; retConf |= (canPtr->configReq | iConf) & GFARM_SS_USE_ENCRYPTION; param[NEGO_PARAM_OTHER_CONFIG] = retConf; if (gfarmWriteLongs(fd, param, NUM_NEGO_PARAM) != NUM_NEGO_PARAM) goto Done; /* End of acceptor side negotiation. */ break; } case GFARM_SS_INITIATOR: { param[NEGO_PARAM_QOP] = canPtr->qOpReq; param[NEGO_PARAM_QOP_FORCE] = canPtr->qOpForce; param[NEGO_PARAM_MAX_TRANS_SIZE] = canPtr->maxTransSizeReq; param[NEGO_PARAM_MAX_TRANS_SIZE_FORCE] = canPtr->maxTransSizeForce; param[NEGO_PARAM_OTHER_CONFIG] = canPtr->configReq; param[NEGO_PARAM_OTHER_CONFIG_FORCE] = canPtr->configForce; if (gfarmWriteLongs(fd, param, NUM_NEGO_PARAM) != NUM_NEGO_PARAM) goto Done; if (gfarmReadLongs(fd, param, NUM_NEGO_PARAM) != NUM_NEGO_PARAM) goto Done; retQOP = param[NEGO_PARAM_QOP]; retMaxT = param[NEGO_PARAM_MAX_TRANS_SIZE]; retConf = param[NEGO_PARAM_OTHER_CONFIG]; /* End of initiator side negotiation. */ break; } } { unsigned int maxMsgSize; int doEncrypt = GFARM_GSS_ENCRYPTION_ENABLED & (isBitSet(retConf, GFARM_SS_USE_ENCRYPTION) ? 1 : 0); if (gfarmGssConfigureMessageSize(sCtx, doEncrypt, retQOP, retMaxT, &maxMsgSize, &majStat, &minStat) >= 0) { if (qOpPtr != NULL) { *qOpPtr = retQOP; } if (maxTransPtr != NULL) { *maxTransPtr = maxMsgSize; } if (configPtr != NULL) { *configPtr = retConf; } ret = 1; } } Done: if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } static gfarmSecSession * allocSecSession(which) int which; { gfarmSecSession *ret = (gfarmSecSession *)malloc(sizeof(gfarmSecSession)); if (ret == NULL) { return NULL; } (void)memset((void *)ret, 0, sizeof(gfarmSecSession)); switch (which) { case GFARM_SS_INITIATOR: { break; } case GFARM_SS_ACCEPTOR: { ret->iOaInfo.acceptor.deleCred = GSS_C_NO_CREDENTIAL; break; } default: { (void)free(ret); ret = NULL; return NULL; } } ret->iOa = which; ret->cred = GSS_C_NO_CREDENTIAL; ret->sCtx = GSS_C_NO_CONTEXT; ret->gssLastStat = GSS_S_COMPLETE; return ret; } static void destroySecSession(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr != NULL) { OM_uint32 minStat; if (ssPtr->peerName != NULL) { (void)free(ssPtr->peerName); } if (ssPtr->credName != NULL) { (void)free(ssPtr->credName); } switch (ssPtr->iOa) { case GFARM_SS_INITIATOR: { if (ssPtr->iOaInfo.initiator.acceptorDistName != NULL) { (void)free(ssPtr->iOaInfo.initiator.acceptorDistName); } break; } case GFARM_SS_ACCEPTOR: { if (ssPtr->iOaInfo.acceptor.deleCred != GSS_C_NO_CREDENTIAL) { (void)gss_release_cred(&minStat, &(ssPtr->iOaInfo.acceptor.deleCred)); } if (ssPtr->iOaInfo.acceptor.mappedUser != NULL) { /* * ssPtr->iOaInfo.acceptor.mappedUser may be NULL, * if gfarmSecSessionAccept() aborts during initialization. */ ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount--; if (ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount < 0) { ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount = 0; } if (ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount == 0 && ssPtr->iOaInfo.acceptor.mappedUser->orphaned == 1) { gfarmAuthDestroyUserEntry(ssPtr->iOaInfo.acceptor.mappedUser); } } break; } default: { break; } } if (ssPtr->sCtx != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat, &(ssPtr->sCtx), GSS_C_NO_BUFFER); } if (ssPtr->needClose == 1) { (void)close(ssPtr->fd); } (void)free(ssPtr); } } char ** gfarmSecSessionCrackStatus(ssPtr) gfarmSecSession *ssPtr; { return gfarmGssCrackMajorStatus(ssPtr->gssLastStat); } void gfarmSecSessionFreeCrackedStatus(strPtr) char **strPtr; { gfarmGssFreeCrackedStatus(strPtr); } void gfarmSecSessionPrintStatus(ssPtr) gfarmSecSession *ssPtr; { gfarmGssPrintMajorStatus(ssPtr->gssLastStat); } int gfarmSecSessionInitializeAcceptor(configFile, usermapFile, majStatPtr, minStatPtr) char *configFile; char *usermapFile; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; OM_uint32 minStat = GSS_S_COMPLETE; if (acceptorInitialized == 0) { char confFile[PATH_MAX]; /* * Get a credential. */ if (acceptorInitialCred == GSS_C_NO_CREDENTIAL && acceptorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&acceptorInitialCred, GSS_C_ACCEPT, &majStat, &minStat, &acceptorInitialCredName) < 0) { ret = -1; goto Done; } } /* * Read config file. */ if (configFile == NULL || configFile[0] == '\0') { char *confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #endif (void)free(confDir); configFile = confFile; } if (secSessionReadConfigFile(configFile, &acceptorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Authorization init. */ if (gfarmAuthInitialize(usermapFile) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (ret == -1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } } else { acceptorInitialized = 1; } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmSecSessionInitializeInitiator(configFile, majStatPtr, minStatPtr) char *configFile; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; OM_uint32 minStat = GSS_S_COMPLETE; if (initiatorInitialized == 0) { char confFile[PATH_MAX]; /* * Get a credential. */ if (initiatorInitialCred == GSS_C_NO_CREDENTIAL && initiatorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&initiatorInitialCred, GSS_C_INITIATE, &majStat, &minStat, &initiatorInitialCredName) < 0) { ret = -1; goto Done; } } /* * Read config file. */ if (configFile == NULL || configFile[0] == '\0') { char *confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #endif (void)free(confDir); configFile = confFile; } if (secSessionReadConfigFile(configFile, &initiatorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (ret == -1) { if (initiatorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &initiatorInitialCred); initiatorInitialCred = GSS_C_NO_CREDENTIAL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } } else { initiatorInitialized = 1; } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmSecSessionInitializeBoth(iConfigFile, aConfigFile, usermapFile, majStatPtr, minStatPtr) char *iConfigFile; char *aConfigFile; char *usermapFile; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; OM_uint32 minStat = GSS_S_COMPLETE; /* * If the process's effective user is root (getuid()==0): * acceptor: host credential (GSS_C_BOTH) * initiator: host credential (GSS_C_BOTH) * * Otherwise (uid!=0): * acceptor: user credential (GSS_C_BOTH) * initiator: user credential (GSS_C_BOTH) * * XXXXX FIXME: * This implementation depends on gssapi_ssleay of Globus. With * other GSSAPI implementation, a major change could be needed. */ if (initiatorInitialized == 0 && acceptorInitialized == 0) { char confFile[PATH_MAX]; char *confDir = NULL; if (acceptorInitialCred == GSS_C_NO_CREDENTIAL && acceptorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&acceptorInitialCred, GSS_C_BOTH, &majStat, &minStat, &acceptorInitialCredName) < 0) { ret = -1; goto Done; } initiatorInitialCred = acceptorInitialCred; initiatorInitialCredName = strdup(acceptorInitialCredName); } /* * Read config file. */ if ((aConfigFile == NULL || aConfigFile[0] == '\0') || (iConfigFile == NULL || iConfigFile[0] == '\0')) { confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } } /* * Acceptor's configuration */ if (aConfigFile == NULL || aConfigFile[0] == '\0') { #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #endif aConfigFile = confFile; } if (secSessionReadConfigFile(aConfigFile, &acceptorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Initiator's configuration */ if (iConfigFile == NULL || iConfigFile[0] == '\0') { #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #endif iConfigFile = confFile; } if (secSessionReadConfigFile(iConfigFile, &initiatorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Authorization init. */ if (gfarmAuthInitialize(usermapFile) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (confDir != NULL) { (void)free(confDir); } if (ret == -1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } initiatorInitialCred = GSS_C_NO_CREDENTIAL; } else { initiatorInitialized = 1; acceptorInitialized = 1; } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } void gfarmSecSessionFinalizeInitiator() { if (initiatorInitialized == 1) { if (initiatorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &initiatorInitialCred); initiatorInitialCred = GSS_C_NO_CREDENTIAL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } initiatorInitialized = 0; } } void gfarmSecSessionFinalizeAcceptor() { if (acceptorInitialized == 1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } gfarmAuthFinalize(); acceptorInitialized = 0; } } void gfarmSecSessionFinalizeBoth() { if (initiatorInitialized == 1 && acceptorInitialized == 1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; initiatorInitialCred = GSS_C_NO_CREDENTIAL; } gfarmAuthFinalize(); acceptorInitialized = 0; initiatorInitialized = 0; } } gfarmSecSession * gfarmSecSessionAccept(fd, cred, ssOptPtr, majStatPtr, minStatPtr) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { gfarmSecSession *ret = NULL; gfarmSecSessionOption canOpt = GFARM_SS_DEFAULT_OPTION; gfarmAuthEntry *entry = NULL; unsigned long int rAddr = INADDR_ANY; int rPort = 0; char *peerName = NULL; OM_uint32 majStat = GSS_S_FAILURE; OM_uint32 minStat = GSS_S_COMPLETE; gss_ctx_id_t sCtx = GSS_C_NO_CONTEXT; char *initiatorDistName = NULL; gss_cred_id_t deleCred = GSS_C_NO_CREDENTIAL; char *credName = NULL; int acknack = GFARM_SS_AUTH_NACK; gss_qop_t qOp; unsigned int maxTransSize; unsigned int config; if (acceptorInitialized == 0) { goto Fail; } ret = allocSecSession(GFARM_SS_ACCEPTOR); if (ret == NULL) { goto Fail; } if (canonicSecSessionOpt(GFARM_SS_ACCEPTOR, ssOptPtr, &canOpt) < 0) { goto Fail; } /* * Get a peer information. */ rAddr = gfarmIPGetPeernameOfSocket(fd, &rPort); if (rAddr != 0 && rPort != 0) { peerName = gfarmIPGetHostOfAddress(rAddr); } /* * Check the credential. */ if (cred == GSS_C_NO_CREDENTIAL) { cred = acceptorInitialCred; credName = strdup(acceptorInitialCredName); } else { credName = gfarmGssGetCredentialName(cred); } /* * Phase 1: Accept a security context. */ if (gfarmGssAcceptSecurityContext(fd, cred, &sCtx, &majStat, &minStat, &initiatorDistName, &deleCred) < 0) { goto Fail; } if (initiatorDistName == NULL || initiatorDistName[0] == '\0') { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 2: Authorization and send ACK/NACK */ entry = gfarmAuthGetUserEntry(initiatorDistName); if (entry == NULL) { majStat = GSS_S_UNAUTHORIZED; /* Send NACK. */ acknack = GFARM_SS_AUTH_NACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); goto Fail; } else { int type = gfarmAuthGetAuthEntryType(entry); if (type == GFARM_AUTH_USER) { /* Send ACK. */ acknack = GFARM_SS_AUTH_ACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); } else if (type == GFARM_AUTH_HOST) { /* check peer name is actually allowed */ if (strcmp(peerName, entry->authData.hostAuth.FQDN) == 0) { /* Send ACK. */ acknack = GFARM_SS_AUTH_ACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); } else { /* Send NACK. */ acknack = GFARM_SS_AUTH_NACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); goto Fail; } } } /* * Phase 3: Negotiate configuration parameters * with the initiator. */ if (negotiateConfigParam(fd, sCtx, GFARM_SS_ACCEPTOR, &canOpt, &qOp, &maxTransSize, &config, &majStat, &minStat) < 0) { goto Fail; } #if 0 fprintf(stderr, "Acceptor config:\n"); dumpConfParam(qOp, maxTransSize, config); #endif /* * Success: Fill all members of session struct out. */ ret->fd = fd; ret->rAddr = rAddr; ret->rPort = rPort; ret->peerName = peerName; ret->cred = cred; ret->credName = credName; ret->sCtx = sCtx; ret->iOa = GFARM_SS_ACCEPTOR; ret->iOaInfo.acceptor.mappedUser = entry; ret->iOaInfo.acceptor.mappedUser->sesRefCount++; ret->iOaInfo.acceptor.deleCred = deleCred; ret->qOp = qOp; ret->maxTransSize = maxTransSize; ret->config = config; ret->gssLastStat = majStat; goto Done; Fail: if (ret != NULL) { destroySecSession(ret); ret = NULL; } Done: if (initiatorDistName != NULL) { (void)free(initiatorDistName); } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } static gfarmSecSession * secSessionInitiate(fd, cred, ssOptPtr, majStatPtr, minStatPtr, needClose) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; int needClose; { gfarmSecSession *ret = NULL; gfarmSecSessionOption canOpt = GFARM_SS_DEFAULT_OPTION; unsigned long int rAddr = INADDR_ANY; int rPort = 0; char *peerName = NULL; OM_uint32 majStat = GSS_S_FAILURE; OM_uint32 minStat = GSS_S_COMPLETE; gss_ctx_id_t sCtx = GSS_C_NO_CONTEXT; char *acceptorDistName = NULL; char *credName = NULL; int acknack = GFARM_SS_AUTH_NACK; gss_qop_t qOp; unsigned int maxTransSize; unsigned int config; if (initiatorInitialized == 0) { goto Fail; } ret = allocSecSession(GFARM_SS_INITIATOR); if (ret == NULL) { goto Fail; } if (canonicSecSessionOpt(GFARM_SS_INITIATOR, ssOptPtr, &canOpt) < 0) { goto Fail; } /* * Get a peer information. */ rAddr = gfarmIPGetPeernameOfSocket(fd, &rPort); if (rAddr != 0 && rPort != 0) { peerName = gfarmIPGetHostOfAddress(rAddr); } /* * Check the credential. */ if (cred == GSS_C_NO_CREDENTIAL) { cred = initiatorInitialCred; credName = strdup(initiatorInitialCredName); } else { credName = gfarmGssGetCredentialName(cred); } /* * Phase 1: Initiate a security context. */ if (gfarmGssInitiateSecurityContext(fd, cred, GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG, &sCtx, &majStat, &minStat, &acceptorDistName) < 0) { goto Fail; } if (acceptorDistName == NULL || acceptorDistName[0] == '\0') { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 2: Receive authorization acknowledgement. */ if (gfarmReadLongs(fd, (long *)&acknack, 1) != 1) { majStat = GSS_S_UNAUTHORIZED; goto Fail; } if (acknack == GFARM_SS_AUTH_NACK) { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 3: Negotiate configuration parameters * with the acceptor. */ if (negotiateConfigParam(fd, sCtx, GFARM_SS_INITIATOR, &canOpt, &qOp, &maxTransSize, &config, &majStat, &minStat) < 0) { goto Fail; } #if 0 fprintf(stderr, "Initiator config:\n"); dumpConfParam(qOp, maxTransSize, config); #endif /* * Success: Fill all members of session struct out. */ ret->fd = fd; ret->needClose = needClose; ret->rAddr = rAddr; ret->rPort = rPort; ret->peerName = peerName; ret->cred = cred; ret->credName = credName; ret->sCtx = sCtx; ret->iOa = GFARM_SS_INITIATOR; ret->iOaInfo.initiator.reqFlag = GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG; ret->iOaInfo.initiator.acceptorDistName = strdup(acceptorDistName); ret->qOp = qOp; ret->maxTransSize = maxTransSize; ret->config = config; ret->gssLastStat = majStat; goto Done; Fail: if (ret != NULL) { destroySecSession(ret); ret = NULL; } Done: if (acceptorDistName != NULL) { (void)free(acceptorDistName); } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } gfarmSecSession * gfarmSecSessionInitiate(fd, cred, ssOptPtr, majStatPtr, minStatPtr) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { return secSessionInitiate(fd, cred, ssOptPtr, majStatPtr, minStatPtr, 0); } gfarmSecSession * gfarmSecSessionInitiateByAddr(rAddr, port, cred, ssOptPtr, majStatPtr, minStatPtr) unsigned long rAddr; int port; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int fd = gfarmTCPConnectPort(rAddr, port); if (fd < 0) { if (majStatPtr != NULL) { *majStatPtr = GSS_S_FAILURE; } return NULL; } return secSessionInitiate(fd, cred, ssOptPtr, majStatPtr, minStatPtr, 1); } gfarmSecSession * gfarmSecSessionInitiateByName(hostname, port, cred, ssOptPtr, majStatPtr, minStatPtr) char *hostname; int port; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { unsigned long rAddr = gfarmIPGetAddressOfHost(hostname); if (rAddr == ~0L || rAddr == 0L) { if (majStatPtr != NULL) { *majStatPtr = GSS_S_FAILURE; *minStatPtr = GSS_S_COMPLETE; } return NULL; } return gfarmSecSessionInitiateByAddr(rAddr, port, cred, ssOptPtr, majStatPtr, minStatPtr); } void gfarmSecSessionTerminate(ssPtr) gfarmSecSession *ssPtr; { destroySecSession(ssPtr); } gss_cred_id_t gfarmSecSessionGetDelegatedCredential(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr->iOa == GFARM_SS_INITIATOR) { return GSS_C_NO_CREDENTIAL; } return ssPtr->iOaInfo.acceptor.deleCred; } gfarmAuthEntry * gfarmSecSessionGetInitiatorInfo(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr->iOa == GFARM_SS_INITIATOR) { return NULL; } return ssPtr->iOaInfo.acceptor.mappedUser; } int gfarmSecSessionDedicate(ssPtr) gfarmSecSession *ssPtr; { int ret = -1; gfarmAuthEntry *aePtr = gfarmSecSessionGetInitiatorInfo(ssPtr); if (aePtr != NULL) { gid_t gid = getgid(); uid_t uid = getuid(); gfarmAuthMakeThisAlone(aePtr); if (uid == 0 && aePtr->authType == GFARM_AUTH_USER) { if (aePtr->authData.userAuth.gid != gid) { if ((ret = setgid(aePtr->authData.userAuth.gid)) < 0) { ssPtr->gssLastStat = GSS_S_FAILURE; goto Done; } } if (aePtr->authData.userAuth.uid != uid) { if ((ret = setuid(aePtr->authData.userAuth.uid)) < 0) { ssPtr->gssLastStat = GSS_S_FAILURE; goto Done; } } } ret = 1; } else { ssPtr->gssLastStat = GSS_S_FAILURE; } Done: return ret; } int gfarmSecSessionSendBytes(ssPtr, buf, n) gfarmSecSession *ssPtr; char *buf; int n; { int doEncrypt = GFARM_GSS_ENCRYPTION_ENABLED & (isBitSet(ssPtr->config, GFARM_SS_USE_ENCRYPTION) ? 1 : 0); return gfarmGssSend(ssPtr->fd, ssPtr->sCtx, doEncrypt, ssPtr->qOp, buf, n, ssPtr->maxTransSize, &(ssPtr->gssLastStat)); } int gfarmSecSessionReceiveBytes(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; char **bufPtr; int *lenPtr; { return gfarmGssReceive(ssPtr->fd, ssPtr->sCtx, bufPtr, lenPtr, &(ssPtr->gssLastStat)); } int gfarmSecSessionSendLongs(ssPtr, buf, n) gfarmSecSession *ssPtr; long *buf; int n; { long *lBuf = (long *)malloc(sizeof(long) * n); int i; int ret = -1; if (lBuf == NULL) { ssPtr->gssLastStat = GSS_S_FAILURE; return ret; } for (i = 0; i < n; i++) { lBuf[i] = htonl(buf[i]); } ret = gfarmSecSessionSendBytes(ssPtr, (char *)lBuf, n * sizeof(long)); (void)free(lBuf); if (ret > 0) { ret /= sizeof(long); } return ret; } int gfarmSecSessionReceiveLongs(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; long **bufPtr; int *lenPtr; { char *lBuf = NULL; char *lbPtr = NULL; long *retBuf = NULL; long tmp; int len = 0; int i; int n; int ret = gfarmSecSessionReceiveBytes(ssPtr, &lBuf, &len); if (ret <= 0) { goto Done; } n = len % sizeof(long); if (n != 0) { goto Done; } n = len / sizeof(long); retBuf = (long *)malloc(sizeof(long) * n); if (retBuf == NULL) { goto Done; } lbPtr = lBuf; for (i = 0; i < n; i++) { memcpy((void *)&tmp, (void *)lbPtr, sizeof(long)); retBuf[i] = ntohl(tmp); lbPtr += sizeof(long); } ret = n; if (lenPtr != NULL) { *lenPtr = n; } if (bufPtr != NULL) { *bufPtr = retBuf; } Done: if (lBuf != NULL) { (void)free(lBuf); } return ret; } int gfarmSecSessionSendShorts(ssPtr, buf, n) gfarmSecSession *ssPtr; short *buf; int n; { short *lBuf = (short *)malloc(sizeof(short) * n); int i; int ret = -1; if (lBuf == NULL) { ssPtr->gssLastStat = GSS_S_FAILURE; return ret; } for (i = 0; i < n; i++) { lBuf[i] = htons(buf[i]); } ret = gfarmSecSessionSendBytes(ssPtr, (char *)lBuf, n * sizeof(short)); (void)free(lBuf); if (ret > 0) { ret /= sizeof(short); } return ret; } int gfarmSecSessionReceiveShorts(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; short **bufPtr; int *lenPtr; { char *lBuf = NULL; char *lbPtr = NULL; short *retBuf = NULL; short tmp; int len = 0; int i; int n; int ret = gfarmSecSessionReceiveBytes(ssPtr, &lBuf, &len); if (ret <= 0) { goto Done; } n = len % sizeof(short); if (n != 0) { goto Done; } n = len / sizeof(short); retBuf = (short *)malloc(sizeof(short) * n); if (retBuf == NULL) { goto Done; } lbPtr = lBuf; for (i = 0; i < n; i++) { memcpy((void *)&tmp, (void *)lbPtr, sizeof(short)); retBuf[i] = ntohs(tmp); lbPtr += sizeof(short); } ret = n; if (lenPtr != NULL) { *lenPtr = n; } if (bufPtr != NULL) { *bufPtr = retBuf; } Done: if (lBuf != NULL) { (void)free(lBuf); } return ret; } int gfarmSecSessionPoll(ssList, n, toPtr) gfarmSecSession *ssList[]; int n; struct timeval *toPtr; { int nFds = -INT_MAX; int i; fd_set rFds; fd_set wFds; fd_set eFds; gfarmSecSession *ssPtr; int fdChk = 0; int ret; FD_ZERO(&rFds); FD_ZERO(&wFds); FD_ZERO(&eFds); for (i = 0; i < n; i++) { fdChk = 0; ssPtr = ssList[i]; if (gfarmSecSessionCheckPollReadable(ssPtr)) { FD_SET(ssPtr->fd, &rFds); fdChk++; } if (gfarmSecSessionCheckPollWritable(ssPtr)) { FD_SET(ssPtr->fd, &wFds); fdChk++; } if (gfarmSecSessionCheckPollError(ssPtr)) { FD_SET(ssPtr->fd, &eFds); fdChk++; } if (fdChk > 0) { if (nFds < ssPtr->fd) { nFds = ssPtr->fd; } } } if (nFds < 0) { return 0; } nFds++; doSel: ret = select(nFds, &rFds, &wFds, &eFds, toPtr); if (ret == 0) { for (i = 0; i < n; i++) { gfarmSecSessionClearPollEvent(ssList[i]); } } else if (ret < 0) { if (errno == EINTR) { goto doSel; } } else { for (i = 0; i < n; i++) { ssPtr = ssList[i]; gfarmSecSessionClearPollEvent(ssPtr); if (FD_ISSET(ssPtr->fd, &rFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_READABLE; } if (FD_ISSET(ssPtr->fd, &wFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_WRITABLE; } if (FD_ISSET(ssPtr->fd, &eFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_ERROR; } } } return ret; } /* * multiplexed version of negotiateConfigParam(,, GFARM_SS_INITIATOR, ...) */ struct negotiateConfigParamInitiatorState { struct gfarm_eventqueue *q; struct gfarm_event *writable, *readable; int fd; gss_ctx_id_t sCtx; gfarmSecSessionOption *canPtr; void (*continuation)(void *); void *closure; gss_qop_t retQOP; unsigned int retMaxT; unsigned int retConf; /* results */ OM_uint32 majStat; OM_uint32 minStat; }; static void negotiateConfigParamInitiatorReceive(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct negotiateConfigParamInitiatorState *state = closure; long param[NUM_NEGO_PARAM]; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->majStat = GSS_S_UNAVAILABLE; /* timeout */ } else { assert(events == GFARM_EVENT_READ); if (gfarmReadLongs(fd, param, NUM_NEGO_PARAM) == NUM_NEGO_PARAM) { state->retQOP = param[NEGO_PARAM_QOP]; state->retMaxT = param[NEGO_PARAM_MAX_TRANS_SIZE]; state->retConf = param[NEGO_PARAM_OTHER_CONFIG]; /* End of initiator side negotiation. */ } else { state->majStat = GSS_S_FAILURE; } } /* finished */ if (state->continuation != NULL) (*state->continuation)(state->closure); } static void negotiateConfigParamInitiatorSend(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct negotiateConfigParamInitiatorState *state = closure; gfarmSecSessionOption *canPtr = state->canPtr; long param[NUM_NEGO_PARAM]; struct timeval timeout; int rv; param[NEGO_PARAM_QOP] = canPtr->qOpReq; param[NEGO_PARAM_QOP_FORCE] = canPtr->qOpForce; param[NEGO_PARAM_MAX_TRANS_SIZE] = canPtr->maxTransSizeReq; param[NEGO_PARAM_MAX_TRANS_SIZE_FORCE] = canPtr->maxTransSizeForce; param[NEGO_PARAM_OTHER_CONFIG] = canPtr->configReq; param[NEGO_PARAM_OTHER_CONFIG_FORCE] = canPtr->configForce; if (gfarmWriteLongs(fd, param, NUM_NEGO_PARAM) == NUM_NEGO_PARAM) { timeout.tv_sec = GFARM_GSS_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); if (rv == 0) { /* go to negotiateConfigParamInitiatorReceive() */ return; } /* XXX convert rv to state->{majStat,minStat} */ state->majStat = GSS_S_FAILURE; } /* failure */ if (state->continuation != NULL) (*state->continuation)(state->closure); } struct negotiateConfigParamInitiatorState * negotiateConfigParamInitiatorRequest(q, fd, sCtx, canPtr, continuation, closure, majStatPtr, minStatPtr) struct gfarm_eventqueue *q; int fd; gss_ctx_id_t sCtx; gfarmSecSessionOption *canPtr; void (*continuation)(void *); void *closure; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { struct negotiateConfigParamInitiatorState *state = NULL; OM_uint32 majStat = GSS_S_FAILURE; OM_uint32 minStat = GFSL_DEFAULT_MINOR_ERROR; int rv; if (sCtx != GSS_C_NO_CONTEXT && (state = malloc(sizeof(*state))) != NULL) { state->writable = gfarm_fd_event_alloc( GFARM_EVENT_WRITE, fd, negotiateConfigParamInitiatorSend, state); if (state->writable != NULL) { /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, fd, negotiateConfigParamInitiatorReceive, state); if (state->readable != NULL) { /* go to negotiateConfigParamInitiatorSend() */ rv = gfarm_eventqueue_add_event(q, state->writable, NULL); if (rv == 0) { state->q = q; state->fd = fd; state->sCtx = sCtx; state->canPtr = canPtr; state->continuation = continuation; state->closure = closure; state->retQOP = GFARM_GSS_DEFAULT_QOP; state->retMaxT = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; state->retConf = GFARM_SS_USE_ENCRYPTION; state->majStat = GSS_S_COMPLETE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; majStat = GSS_S_COMPLETE; goto Done; } /* XXX convert rv to {majStat,minStat} */ gfarm_event_free(state->readable); } gfarm_event_free(state->writable); } free(state); state = NULL; } Done: if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return (state); } int negotiateConfigParamInitiatorResult(state, qOpPtr, maxTransPtr, configPtr, majStatPtr, minStatPtr) struct negotiateConfigParamInitiatorState *state; gss_qop_t *qOpPtr; unsigned int *maxTransPtr; unsigned int *configPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = -1; OM_uint32 majStat = state->majStat; OM_uint32 minStat = state->minStat; if (majStat == GSS_S_COMPLETE) { unsigned int maxMsgSize; int doEncrypt = GFARM_GSS_ENCRYPTION_ENABLED & (isBitSet(state->retConf, GFARM_SS_USE_ENCRYPTION) ? 1 : 0); if (gfarmGssConfigureMessageSize(state->sCtx, doEncrypt, state->retQOP, state->retMaxT, &maxMsgSize, &majStat, &minStat) < 0) { majStat = GSS_S_FAILURE; } else { if (qOpPtr != NULL) { *qOpPtr = state->retQOP; } if (maxTransPtr != NULL) { *maxTransPtr = maxMsgSize; } if (configPtr != NULL) { *configPtr = state->retConf; } ret = 1; } } gfarm_event_free(state->readable); gfarm_event_free(state->writable); free(state); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } /* * multiplexed version of secSessionInitiate() */ struct gfarmSecSessionInitiateState { /* request */ struct gfarm_eventqueue *q; int fd; gss_cred_id_t cred; void (*continuation)(void *); void *closure; int needClose; /* local variables */ gfarmSecSessionOption canOpt; unsigned long int rAddr; int rPort; char *peerName; struct gfarm_event *readable; struct gfarmGssInitiateSecurityContextState *secCtxState; struct negotiateConfigParamInitiatorState *negoCfgState; gss_ctx_id_t sCtx; char *acceptorDistName; char *credName; gss_qop_t qOp; unsigned int maxTransSize; unsigned int config; /* results */ OM_uint32 majStat; OM_uint32 minStat; gfarmSecSession *session; }; static void secSessionInitiateCleanup(closure) void *closure; { struct gfarmSecSessionInitiateState *state = closure; if (negotiateConfigParamInitiatorResult(state->negoCfgState, &state->qOp, &state->maxTransSize, &state->config, &state->majStat, &state->minStat) >= 0) { state->majStat = GSS_S_COMPLETE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void secSessionInitiateReceiveAuthorizationAck(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct gfarmSecSessionInitiateState *state = closure; int acknack; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->majStat = GSS_S_UNAVAILABLE; /* timeout */ } else { assert(events == GFARM_EVENT_READ); /* * Phase 2: Receive authorization acknowledgement. */ if (gfarmReadLongs(fd, (long *)&acknack, 1) != 1) { state->majStat = GSS_S_UNAUTHORIZED; } else if (acknack == GFARM_SS_AUTH_NACK) { state->majStat = GSS_S_UNAUTHORIZED; } else { /* * Phase 3: Negotiate configuration parameters * with the acceptor. */ state->negoCfgState = negotiateConfigParamInitiatorRequest( state->q, fd, state->sCtx, &state->canOpt, secSessionInitiateCleanup, state, &state->majStat, &state->minStat); if (state->negoCfgState != NULL) { /* * call negotiateConfigParamInitiator*(), * then go to secSessionInitiateCleanup() */ return; } } } /* failure */ if (state->continuation != NULL) (*state->continuation)(state->closure); } static void secSessionInitiateWaitAuthorizationAck(closure) void *closure; { struct gfarmSecSessionInitiateState *state = closure; struct timeval timeout; int rv; if (gfarmGssInitiateSecurityContextResult( state->secCtxState, &state->sCtx, &state->majStat, &state->minStat, &state->acceptorDistName) >= 0) { if (state->acceptorDistName == NULL || state->acceptorDistName[0] == '\0') { state->majStat = GSS_S_UNAUTHORIZED; /* failure */ } else { timeout.tv_sec = GFARM_GSS_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); if (rv == 0) { /* go to secSessionInitiateReceiveAuthorizationAck() */ return; } /* XXX convert rv to state->{majStat,minStat} */ state->majStat = GSS_S_FAILURE; } } /* failure */ if (state->continuation != NULL) (*state->continuation)(state->closure); } static struct gfarmSecSessionInitiateState * secSessionInitiateRequest(q, fd, cred, ssOptPtr, continuation, closure, needClose, majStatPtr, minStatPtr) struct gfarm_eventqueue *q; int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; void (*continuation)(void *); void *closure; int needClose; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { struct gfarmSecSessionInitiateState *state = NULL; gfarmSecSession *ret = NULL; gfarmSecSessionOption canOpt = GFARM_SS_DEFAULT_OPTION; OM_uint32 majStat = GSS_S_FAILURE; OM_uint32 minStat = GFSL_DEFAULT_MINOR_ERROR; if (initiatorInitialized == 0) { /* failure */; } else if ((state = malloc(sizeof(*state))) == NULL) { /* failure */; } else if ((ret = allocSecSession(GFARM_SS_INITIATOR)) == NULL) { /* failure */; } else if (canonicSecSessionOpt(GFARM_SS_INITIATOR, ssOptPtr, &canOpt)< 0){ /* failure */; } else { state->q = q; state->fd = fd; state->cred = cred; state->continuation = continuation; state->closure = closure; state->needClose = needClose; state->canOpt = canOpt; state->rAddr = INADDR_ANY; state->rPort = 0; state->peerName = NULL; state->sCtx = GSS_C_NO_CONTEXT; state->acceptorDistName = NULL; state->credName = NULL; state->majStat = GSS_S_COMPLETE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; state->session = ret; /* * Get a peer information. */ state->rAddr = gfarmIPGetPeernameOfSocket(fd, &state->rPort); if (state->rAddr != 0 && state->rPort != 0) { state->peerName = gfarmIPGetHostOfAddress(state->rAddr); } /* * Check the credential. */ if (cred == GSS_C_NO_CREDENTIAL) { state->cred = initiatorInitialCred; state->credName = strdup(initiatorInitialCredName); } else { state->credName = gfarmGssGetCredentialName(cred); } state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, fd, secSessionInitiateReceiveAuthorizationAck, state); if (state->readable != NULL) { /* * Phase 1: Initiate a security context. */ state->secCtxState = gfarmGssInitiateSecurityContextRequest(q, fd, cred, GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG, secSessionInitiateWaitAuthorizationAck, state, majStatPtr, minStatPtr); if (state->secCtxState != NULL) return (state); /* success */ majStat = *majStatPtr; minStat = *minStatPtr; } /* failure */ if (state->readable != NULL) { gfarm_event_free(state->readable); } if (state->peerName != NULL) { free(state->peerName); } if (state->credName != NULL) { free(state->credName); } } if (ret != NULL) { destroySecSession(ret); } if (state != NULL) { free(state); } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return (NULL); /* failure */ } static gfarmSecSession * secSessionInitiateResult(state, majStatPtr, minStatPtr) struct gfarmSecSessionInitiateState *state; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { gfarmSecSession *ret = state->session; if (GSS_ERROR(state->majStat)) { destroySecSession(ret); ret = NULL; } else { #if 0 fprintf(stderr, "Initiator config:\n"); dumpConfParam(state->qOp, state->maxTransSize, state->config); #endif /* * Success: Fill all members of session struct out. */ ret->fd = state->fd; ret->needClose = state->needClose; ret->rAddr = state->rAddr; ret->rPort = state->rPort; ret->peerName = state->peerName; ret->cred = state->cred; ret->credName = state->credName; ret->sCtx = state->sCtx; ret->iOa = GFARM_SS_INITIATOR; ret->iOaInfo.initiator.reqFlag = GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG; ret->iOaInfo.initiator.acceptorDistName = strdup(state->acceptorDistName); ret->qOp = state->qOp; ret->maxTransSize = state->maxTransSize; ret->config = state->config; ret->gssLastStat = state->majStat; } if (state->acceptorDistName != NULL) { (void)free(state->acceptorDistName); } gfarm_event_free(state->readable); if (majStatPtr != NULL) { *majStatPtr = state->majStat; } if (minStatPtr != NULL) { *minStatPtr = state->minStat; } free(state); return (ret); } /* * multiplexed version of gfarmSecSessionInitiate() */ struct gfarmSecSessionInitiateState * gfarmSecSessionInitiateRequest(q, fd, cred, ssOptPtr, continuation, closure, majStatPtr, minStatPtr) struct gfarm_eventqueue *q; int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; void (*continuation)(void *); void *closure; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { return secSessionInitiateRequest(q, fd, cred, ssOptPtr, continuation, closure, majStatPtr, minStatPtr, 0); } gfarmSecSession * gfarmSecSessionInitiateResult(state, majStatPtr, minStatPtr) struct gfarmSecSessionInitiateState *state; OM_uint32 *majStatPtr, *minStatPtr; { return secSessionInitiateResult(state, majStatPtr, minStatPtr); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc1/lib/libgfarm/gfarm/url.c /* * $Id$ */ #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pwd.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> /* * GFarm-URL: * gfarm:path/name * gfarm:~/path/name * = ${gfarm_spool_root}/${USER}/path/name * gfarm:/path/name * = ${gfarm_spool_root}/path/name */ /* * Remove "gfarm:" prefix and expand "~" and current directory. * Return malloc(3)ed string, thus caller should free(3) the memory. * * Do not add ${gfarm_spool_root}, because it is only available on * gfarm pool hosts. * * i.e. * input: gfarm:path/name * output: ${USER}/path/name * * input: gfarm:~/path/name * output: ${USER}/path/name * * input: gfarm:/path/name * output: path/name * * input: gfarm:~user/path/name * output: user/path/name */ char GFARM_URL_PREFIX[] = "gfarm:"; char * gfarm_canonical_path(const char *gfarm_file, char **canonic_pathp) { char *s, *user, *e, *t; *canonic_pathp = NULL; /* cause SEGV, if return value is ignored */ if (gfarm_file[0] == '~' && (gfarm_file[1] == '\0' || gfarm_file[1] == '/')) { user = gfarm_get_global_username(); s = malloc(strlen(user) + strlen(&gfarm_file[1]) + 2); if (s == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(s, "/%s%s", user, &gfarm_file[1]); } else { s = strdup(gfarm_file); if (s == NULL) return (GFARM_ERR_NO_MEMORY); if (gfarm_file[0] == '~') /* ~username/... */ *s = '/'; } e = gfs_realpath(s, &t); free(s); if (e != NULL) return(e); *canonic_pathp = strdup(t + GFARM_URL_PREFIX_LENGTH + 1); free(t); if (*canonic_pathp == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } char * gfarm_canonical_path_for_creation(const char *gfarm_file, char **canonic_pathp) { const char *basename; char *dir, *e, *dir_canonic; *canonic_pathp = NULL; /* cause SEGV, if return value is ignored */ basename = gfarm_path_dir_skip(gfarm_file); dir = NULL; if (basename == gfarm_file) { /* "filename" */ dir = strdup("."); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); } else if (basename == gfarm_file + 1) { /* "/filename" */ dir = strdup("/"); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); } else { /* /.../.../filename */ dir = malloc(basename - 2 - gfarm_file + 2); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); strncpy(dir, gfarm_file, basename - 2 - gfarm_file + 1); dir[basename - 2 - gfarm_file + 1] = '\0'; } e = gfarm_canonical_path(dir, &dir_canonic); if (e != NULL) return(e); free(dir); *canonic_pathp = malloc(strlen(dir_canonic) + 1 + strlen(basename) + 1); if (*canonic_pathp == NULL) return (GFARM_ERR_NO_MEMORY); /* * When the 'dir_canonic' is a null string, *canonic_pathp * will start with '/' incorrectly. */ if (dir_canonic[0] == '\0') strcpy(*canonic_pathp, basename); else sprintf(*canonic_pathp, "%s/%s", dir_canonic, basename); free(dir_canonic); return (NULL); } char * gfarm_url_make_path(const char *gfarm_url, char **canonic_pathp) { *canonic_pathp = NULL; /* cause SEGV, if return value is ignored */ if (!gfarm_is_url(gfarm_url)) return (GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING); gfarm_url += GFARM_URL_PREFIX_LENGTH; return (gfarm_canonical_path(gfarm_url, canonic_pathp)); } char * gfarm_url_make_path_for_creation(const char *gfarm_url, char **canonic_pathp) { *canonic_pathp = NULL; /* cause SEGV, if return value is ignored */ if (!gfarm_is_url(gfarm_url)) return (GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING); gfarm_url += GFARM_URL_PREFIX_LENGTH; return (gfarm_canonical_path_for_creation(gfarm_url, canonic_pathp)); } int gfarm_is_url(const char *gfarm_url) { return (memcmp(gfarm_url, GFARM_URL_PREFIX, GFARM_URL_PREFIX_LENGTH) == 0); } /* * Append section suffix to pathname. * Return malloc(3)ed string, thus caller should free(3) the memory. * i.e. * input1: pathname * input2: section * output: pathname:section */ char * gfarm_path_section(const char *pathname, const char *section, char **section_pathp) { char *s; *section_pathp = NULL; /* cause SEGV, if return value is ignored */ s = malloc(strlen(pathname) + 1 + strlen(section) + 1); if (s == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(s, "%s:%s", pathname, section); *section_pathp = s; return (NULL); } /* * Add spool_root prefix and section suffix to canonic path. * Return malloc(3)ed string, thus caller should free(3) the memory. * * i.e. * input1: /spool_root * input2: path/name * input3: section * output: /spool_root/path/name:section */ char * gfarm_full_path_file_section( char *spool_root, char *canonic_path, char *section, char **abs_pathp) { char *s; *abs_pathp = NULL; /* cause SEGV, if return value is ignored */ s = malloc(strlen(spool_root) + 1 + strlen(canonic_path) + 1 + strlen(section) + 1); if (s == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(s, "%s/%s:%s", spool_root, canonic_path, section); *abs_pathp = s; return (NULL); } /* * Add ${gfarm_spool_root} prefix to canonic path. * Return malloc(3)ed string, thus caller should free(3) the memory. * * Should be called on gfarm pool hosts, because ${gfarm_spool_root} is * only available on pool. * * i.e. * input: path/name * output: ${gfarm_spool_root}/path/name */ char * gfarm_path_localize(char *canonic_path, char **abs_pathp) { char *s; *abs_pathp = NULL; /* cause SEGV, if return value is ignored */ s = malloc(strlen(gfarm_spool_root) + 1 + strlen(canonic_path) + 1); if (s == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(s, "%s/%s", gfarm_spool_root, canonic_path); *abs_pathp = s; return (NULL); } /* * Add ${gfarm_spool_root} prefix and section suffix to canonic path. * Return malloc(3)ed string, thus caller should free(3) the memory. * * Should be called on gfarm pool hosts, because ${gfarm_spool_root} is * only available on pool. * * i.e. * input1: path/name * input2: section * output: ${gfarm_spool_root}/path/name:section */ char * gfarm_path_localize_file_section(char *canonic_path, char *section, char **abs_pathp) { return (gfarm_full_path_file_section(gfarm_spool_root, canonic_path, section, abs_pathp)); } char * gfarm_path_localize_file_fragment(char *canonic_path, int index, char **abs_pathp) { char buffer[GFARM_INT32STRLEN]; sprintf(buffer, "%d", index); return (gfarm_path_localize_file_section(canonic_path, buffer, abs_pathp)); } /* * Strip suffix from pathname. * * It is necessary to free a returned string. */ char * gfarm_url_remove_suffix(char *gfarm_url, char *suffix, char **out_urlp) { char *r; int ulen = strlen(gfarm_url); int slen = strlen(suffix); if (ulen > slen) { if (memcmp(gfarm_url + ulen - slen, suffix, slen) == 0) ulen -= slen; } r = malloc(ulen + 1); if (r == NULL) return (GFARM_ERR_NO_MEMORY); memcpy(r, gfarm_url, ulen); r[ulen] = '\0'; *out_urlp = r; return (NULL); } /* * convenience functions */ char * gfarm_url_prefix_skip(char *gfarm_url) { if (memcmp(gfarm_url, GFARM_URL_PREFIX, GFARM_URL_PREFIX_LENGTH) == 0) gfarm_url += GFARM_URL_PREFIX_LENGTH; return (gfarm_url); } /* * Skip directory in the pathname. * We want traditional basename(3) here, rather than weird XPG one. */ const char * gfarm_path_dir_skip(const char *path) { const char *base; for (base = path; *path != '\0'; path++) { if (*path == '/') base = path + 1; } return (base); } #if 0 char * gfarm_url_make_localized_path(char *gfarm_url, char **abs_pathp) { char *e, *canonic_path; e = gfarm_url_make_path(gfarm_url, &canonic_path); if (e != NULL) return (e); e = gfarm_path_localize(canonic_path, abs_pathp); free(canonic_path); return (e); } char * gfarm_url_make_localized_file_fragment_path(char *gfarm_url, int index, char **abs_pathp) { char *e, *canonic_path; e = gfarm_url_make_path(gfarm_url, &canonic_path); if (e != NULL) return (e); e = gfarm_path_localize_file_fragment(canonic_path, index, abs_pathp); free(canonic_path); return (e); } #endif <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT-set-journal-size #! /bin/sh # # Utility to set journal file size of gfmd servers. # # ./FT-set-journal-size SIZE # # where the unit of SIZE is byte. This script should be executed just # after ./FT-config. # . ./FT-common # # Check command line arguments. # USAGE="Usage: $0 SIZE" if [ $# -eq 0 ]; then echo "$0: journal size not specified" 1>&2 echo $USAGE 1>&2 exit 1 fi JOURNAL_SIZE="$1" expr "X$JOURNAL_SIZE" : '^X[1-9][0-9]*$' > /dev/null 2>&1 || { echo "$0: invalid journal size '$JOURNAL_SIZE'" 1>&2 echo $USAGE 1>&2 exit 1 } # # Stop gfmd servers. # I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice stop-gfmd gfmd$I || { echo "$0: failed to stop gfmd on gfmd$I" 1>&2 exit 1 } I=`expr $I + 1` done # # Set 'metadb_journal_max_size' directive in 'gfmd.conf' to the # specified size. # I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice set-gfmd-conf gfmd$I metadb_journal_max_size $JOURNAL_SIZE I=`expr $I + 1` done # # Backup database of gfmd1 and restore it to other gfmd servers. # TMP_FILE=/tmp/ft-set-journal-size.$$ trap "rm -f $TMP_FILE; exit 1" 1 2 3 15 rm -f $TMP_FILE $gfservice backup-backend-db gfmd1 > $TMP_FILE || { echo "$0: failed to backup database of gfmd1" 1>&2 exit 1 } I=2 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice restore-backend-db gfmd$I < $TMP_FILE || { echo "$0: failed to restore database of gfmd1" 1>&2 exit 1 } I=`expr $I + 1` done rm -f $TMP_FILE # # Start gfmd servers. # I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice start-gfmd gfmd$I || { echo "$0: failed to start gfmd on gfmd$I" 1>&2 } I=`expr $I + 1` done exit 0 <file_sep>/gfarm_gridftp_dsi/tags/gfarm_dsi_1_0_3/Makefile.am FLAVOR = @FLAVOR@ lib_LTLIBRARIES = libglobus_gridftp_server_gfarm_$(FLAVOR).la libglobus_gridftp_server_gfarm___FLAVOR__la_SOURCES = globus_gridftp_server_gfarm.c AM_CFLAGS = -Wall EXTRA_DIST = RELNOTES LICENSE README.en README.ja <file_sep>/gfarm/branches/metadb_dev/gftool/example/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk MPI_SUBDIRS = gfwc SUBDIRS = \ gfimport_fixed \ gfimport_text \ gfgrep \ $(mpi_subdirs) include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfarm/io_fd.h /* iobuffer operation: file descriptor read/write */ /* nonblocking i/o */ void gfarm_iobuffer_set_nonblocking_read_fd(struct gfarm_iobuffer *, int); void gfarm_iobuffer_set_nonblocking_write_fd(struct gfarm_iobuffer *, int); /* blocking i/o */ void gfarm_iobuffer_set_blocking_read_fd(struct gfarm_iobuffer *, int); void gfarm_iobuffer_set_blocking_write_fd(struct gfarm_iobuffer *, int); /* an option for gfarm_iobuffer_set_write_close() */ void gfarm_iobuffer_write_close_fd_op(struct gfarm_iobuffer *, void *, int); /* xxx_connection operation */ struct xxx_connection; char *xxx_fd_connection_new(int, struct xxx_connection **); char *xxx_connection_set_fd(struct xxx_connection *, int); <file_sep>/gfarm/tags/gfarm_1_0_rc1/gfptool/gfrepbe_client/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk bindir = $(default_libexecdir) PROGRAM = gfrepbe_client SRCS = $(PROGRAM).c OBJS = $(PROGRAM).o CFLAGS = $(COMMON_CFLAGS) -I$(GFARMLIB_SRCDIR) LDLIBS = $(COMMON_LDFLAGS) $(GFARMLIB) $(LIBS) DEPLIBS = $(DEPGFARMLIB) all: $(PROGRAM) include $(top_srcdir)/makes/gfptool.mk ### $(OBJS): \ $(GFARMLIB_SRCDIR)/xxx_proto.h \ $(GFARMLIB_SRCDIR)/io_fd.h \ $(GFARMLIB_SRCDIR)/param.h \ $(GFARMLIB_SRCDIR)/sockopt.h \ $(GFARMLIB_SRCDIR)/auth.h \ $(GFARMLIB_SRCDIR)/gfs_proto.h \ $(GFARMLIB_SRCDIR)/gfs_client.h \ $(DEPGFARMINC) <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_6/contrib/mount.gfarm2fs/Makefile.am bin_SCRIPTS = mount.gfarm2fs umount.gfarm2fs mount.hpci umount.hpci EXTRA_DIST = $(bin_SCRIPTS) <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc2/gfptool/gfgrep/gfgrep.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <regex.h> #include <gfarm/gfarm.h> char *program_name = "gfarm_grep"; void usage() { fprintf(stderr, "Usage: %s [option] <regexp> <input_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-o <output_gfarm_file>\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int c, total_nodes = -1, node_index = -1; char *regexp = NULL; char *e, *input, *output = NULL; regex_t re; struct gfs_file *igf; struct gfs_file *ogf; int eof; char line[1024]; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; while ((c = getopt(argc, argv, "e:o:")) != -1) { switch (c) { case 'e': regexp = optarg; break; case 'o': output = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_pio_get_node_size(&total_nodes); if (total_nodes <= 0) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (regexp == NULL) { if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing regular expression\n", program_name); usage(); } exit(1); } regexp = argv[0]; argc--; argv++; } if (output == NULL) { if (node_index == 0) { fprintf(stderr, "%s: \"-o <output gfarm_file>\" is needed\n", program_name); } exit(1); } if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: input file name is mandatory\n", program_name); } exit(1); } input = argv[0]; argc--; argv++; if (argc != 0) { if (node_index == 0) { fprintf(stderr, "%s: currently, " "only one input file is supported\n", program_name); } exit(1); } if (regcomp(&re, regexp, REG_NOSUB) != 0) { if (node_index == 0) { fprintf(stderr, "%s: invalid regular expression\n", program_name); } exit(1); } e = gfs_pio_create(output, GFARM_FILE_WRONLY, 0666, &ogf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_set_view_local(ogf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_open(input, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, input, e); exit(1); } e = gfs_pio_set_view_local(igf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, input, e); exit(1); } for (;;) { e = gfs_pio_getline(igf, line, sizeof line, &eof); if (e != NULL) { fprintf(stderr, "%s: %s\n", input, e); break; } if (eof) break; if (regexec(&re, line, 0, NULL, 0) == 0) gfs_pio_putline(ogf, line); } gfs_pio_close(igf); gfs_pio_close(ogf); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } regfree(&re); return (0); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_2/systest/common_scripts/Makefile.am common_scriptsdir = $(datadir)/gfarm/systest/common_scripts/gfarm2fs dist_common_scripts_DATA = \ calc_checksum \ check_files \ check_files_each_mntpnts \ check_gfsd_connected \ check_metadata_filesize \ exec_on_multiple_clients \ gfwhere_check \ log_view \ make_files \ make_files_each_mntpnts \ make_files_single \ mkdir_n \ mount_n \ remove_files \ remove_files_each_mntpnts \ rmdir_n \ test_read_files_common \ test_write_files_common \ test_write_files_each_mntpnts_common \ umount_n \ wait_for_gfsd_connect \ wait_for_gfsd_disconnect <file_sep>/gfarmfs-fuse/trunk/contrib/mount.gfarmfs/umount.gfarmfs #!/bin/sh # # $Id$ USAGE() { cat <<EOF umount.gfarmfs [ mount_point ] Environment variable: GFS_USERNAME global user name in Gfarm (default: $LOGNAME) GFS_MOUNTDIR mount point (default: /gfs/home/$GFS_USERNAME) EOF exit 1 } UMOUNT_FUSE() { MNTDIR=$1 retry=10 i=0 while true; do fusermount -u $MNTDIR > /dev/null 2>&1 if [ $? -eq 0 ]; then return 0 fi ls -l $MNTDIR > /dev/null 2>&1 if [ $i -ge $retry ]; then return 1 fi i=`expr $i + 1` done } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi : ${GFS_USERNAME:=`gfwhoami 2> /dev/null`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2> /dev/null`} : ${GFS_MOUNTDIR:=/gfs/home/$GFS_USERNAME} UMOUNT_FUSE $GFS_MOUNTDIR exit $? <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8/systest/Makefile.am SUBDIRS = testcases parameters common_scripts plugins <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9/contrib/mount.gfarm2fs/mount.gfarm2fs.in #!/bin/sh # # $Id$ prefix=@prefix@ exec_prefix=@exec_prefix@ export PATH=@bindir@:$PATH USAGE() { cat <<EOF mount.gfarm2fs [ configuration_file mount_point options ] options: username effective local user name to mount Environment variable: GFS_USERNAME global user name in Gfarm GFS_MOUNTDIR mount point GFARMFS_ROOT directory to be mounted in Gfarm GFARMFS_OPTIONS gfarmfs mount options FUSE_OPTIONS fuse mount options When mount.gfarm2fs is installed to /sbin/mount.gfarm2fs, you can mount the Gfarm file system by mount(8) and automount(8). Example of /etc/fstab entries: /etc/gfarm2.conf /gfarm/tatebe gfarm2fs noauto,user,username=tatebe 0 0 Example of /etc/auto.master entries: /gfarm /etc/auto.gfarm Example of /etc/auto.gfarm entries: tatebe -fstype=gfarm2fs,username=tatebe :/etc/gfarm2.conf EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then GFARM_ENV="env GFARM_CONFIG_FILE=$1 PATH=$PATH" shift fi if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi if [ $# -gt 0 ]; then OPTIONS=$* fi getoptvalue() { o=$1 v=`echo $OPTIONS | sed "s/.*$o=\([0-9a-zA-Z_.-]*\).*/\1/"` echo $v } : ${GFARMFS_USERNAME:=`getoptvalue username`} [ -x /sbin/runuser ] && SU=/sbin/runuser || SU=su if [ -w / -a X"$GFARMFS_USERNAME" != X ]; then RUN="$SU -l $GFARMFS_USERNAME" if $RUN --session-command=hostname >/dev/null 2>&1; then RUN="$RUN --session-command=" else RUN="$RUN -c " fi else RUN="/bin/sh -c " fi : ${GFS_USERNAME:=`$RUN"$GFARM_ENV gfwhoami 2>/dev/null"`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2>/dev/null`} : ${GFS_MOUNTDIR:=/tmp/$GFS_USERNAME} : ${GFARMFS_ROOT:=`$RUN"$GFARM_ENV gfuser -l $GFS_USERNAME 2>/dev/null" | awk -F: '{ print $3 }'`} : ${GFARMFS_ROOT:=/} : ${GFARMFS_OPTIONS:=} : ${FUSE_OPTIONS:=} # if already mounted, exit grep $GFS_MOUNTDIR /etc/mtab >/dev/null && ABORT "$GFS_MOUNTDIR: already mounted" DELETE_MOUNTDIR_ON_ERROR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR_ON_ERROR=1 fi [ -w / -o -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME # if username is specified, change the owner of the mount point if [ -w / ]; then if [ X"$GFARMFS_USERNAME" != X ]; then chown $GFARMFS_USERNAME $GFS_MOUNTDIR chmod +w $GFS_MOUNTDIR fi fi # mount $RUN"$GFARM_ENV gfarm2fs -o modules=subdir,subdir=$GFARMFS_ROOT $GFARMFS_OPTIONS $GFS_MOUNTDIR $FUSE_OPTIONS" STATUS=$? if [ $STATUS = 0 ]; then [ -w / ] || echo Mount GfarmFS on $GFS_MOUNTDIR else [ $DELETE_MOUNTDIR_ON_ERROR = 1 ] && rmdir $GFS_MOUNTDIR fi exit $STATUS <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT-run-all #! /bin/sh . ./FT-common rm -f $FT_LOG rm -f $FT_MBOX_BACKUP_FILE_PREFIX.* ft_run_all <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/gfs_hook/hooks_common.c /* * $Id$ */ /* * open */ int FUNC___OPEN(const char *path, int oflag, ...) { GFS_File gf; const char *e; char *url, *sec; va_list ap; mode_t mode; int filedes; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___OPEN) "(%s, 0x%x)\n", path, oflag)); retry: if (!gfs_hook_is_url(path, &url, &sec)) return (SYSCALL_OPEN(path, oflag, mode)); /* XXX - ROOT I/O creates a new file with O_CREAT|O_RDWR mode. */ /* XXX - FIXME */ if ((oflag & O_CREAT) != 0 || (oflag & O_TRUNC) != 0) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) "(%s:%s, 0x%x, 0%o)\n", path, sec != NULL ? sec : "(null)", oflag, mode)); if (oflag & O_TRUNC) { /* * Hooking open syscall does not mean to open * an entire file but a file fragment in local and * index file views. gfs_unlink() should not be * called in both views. */ if (_gfs_hook_default_view == global_view) gfs_unlink(path); /* XXX - FIXME */ e = gfs_pio_create(url, oflag, mode, &gf); } else { e = gfs_pio_open(url, oflag, &gf); if (e == GFARM_ERR_NO_SUCH_OBJECT) /* XXX - FIXME */ e = gfs_pio_create(url, oflag, mode, &gf); } } else { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) "(%s:%s, 0x%x)\n", path, sec != NULL ? sec : "(null)", oflag)); e = gfs_pio_open(url, oflag, &gf); } free(url); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } if (sec != NULL || _gfs_hook_default_view == index_view) { if (sec != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section(%s, %s)\n", path, sec)); e = gfs_pio_set_view_section(gf, sec, NULL, 0); free(sec); } else { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index(%s, %d, %d)\n", path, _gfs_hook_num_fragments, _gfs_hook_index)); e = gfs_pio_set_view_index(gf, _gfs_hook_num_fragments, _gfs_hook_index, NULL, 0); } if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section: %s\n", e)); gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } } else if (_gfs_hook_default_view == local_view) { int nf = -1, np; /* * If the number of fragments is not the same as the * number of parallel processes, or the file is not * fragmented, do not change to the local file view. */ if (gfs_pio_get_nfragment(gf, &nf) == GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE || (gfs_pio_get_node_size(&np) == NULL && nf == np)) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local(%s (%d, %d))\n", path, gfarm_node, gfarm_nnode)); if ((e = gfs_pio_set_view_local(gf, 0)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); gfs_pio_close(gf); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* * corrupted GFarmPath entry, * possibly caused by coredump. */ gfs_unlink(path); /* XXX - FIXME */ goto retry; /* XXX - FIXME */ } errno = gfarm_error_to_errno(e); return (-1); } } } filedes = gfs_hook_insert_gfs_file(gf); _gfs_hook_debug( if (filedes != -1) { fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) " --> %d(%d)\n", filedes, gfs_pio_fileno(gf)); } ); return (filedes); } int FUNC__OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fputs("Hooking " S(FUNC__OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } int FUNC_OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fputs("Hooking " S(FUNC_OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } /* * creat */ int FUNC___CREAT(const char *path, mode_t mode) { const char *e; char *url, *sec; GFS_File gf; int filedes; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___CREAT) "(%s, 0%o)\n", path, mode)); if (!gfs_hook_is_url(path, &url, &sec)) return (SYSCALL_CREAT(path, mode)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___CREAT) "(%s:%s, 0%o)\n", path, sec != NULL ? sec : "(null)", mode)); e = gfs_pio_create(url, GFARM_FILE_WRONLY, mode, &gf); free(url); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___CREAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } if (sec != NULL || _gfs_hook_default_view == index_view) { if (sec != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section(%s, %s)\n", path, sec)); e = gfs_pio_set_view_section(gf, sec, NULL, 0); free(sec); } else { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index(%s, %d, %d)\n", path, _gfs_hook_num_fragments, _gfs_hook_index)); e = gfs_pio_set_view_index(gf, _gfs_hook_num_fragments, _gfs_hook_index, NULL, 0); } if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section: %s\n", e)); gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } } else if (_gfs_hook_default_view == local_view) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local(%s)\n", path)); if ((e = gfs_pio_set_view_local(gf, 0)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } } filedes = gfs_hook_insert_gfs_file(gf); _gfs_hook_debug( if (filedes != -1) { fprintf(stderr, "GFS: Hooking " S(FUNC___CREAT) " --> %d(%d)\n", filedes, gfs_pio_fileno(gf)); } ); return (filedes); } int FUNC__CREAT(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking " S(FUNC__CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } int FUNC_CREAT(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking " S(FUNC_CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } /* * lseek */ OFF_T FUNC___LSEEK(int filedes, OFF_T offset, int whence) { GFS_File gf; const char *e; file_offset_t o; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___LSEEK) "(%d, %" PR_FILE_OFFSET ", %d)\n", filedes, (file_offset_t)offset, whence)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_LSEEK(filedes, offset, whence)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___LSEEK) "(%d(%d), %" PR_FILE_OFFSET ", %d)\n", filedes, gfs_pio_fileno(gf), (file_offset_t)offset, whence)); e = gfs_pio_seek(gf, offset, whence, &o); if (e == NULL) return ((OFF_T)o); _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___LSEEK) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } OFF_T FUNC__LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC__LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } OFF_T FUNC_LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } <file_sep>/gfarm/tags/gfarm_0_1/lib/gfs_hook/hooks_common.c /* * open */ int FUNC___OPEN(const char *path, int oflag, ...) { GFS_File gf; const char *e, *url; va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___OPEN) ": %s\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_OPEN(path, oflag, mode)); if (oflag & O_CREAT) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) " (create): %s\n", path)); e = gfs_pio_create(url, oflag, mode, &gf); } else { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": %s\n", path)); e = gfs_pio_open(url, oflag, &gf); } if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } if ((e = gfs_pio_set_view_local(gf, 0)) != NULL) { gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } return (gfs_hook_insert_gfs_file(gf)); } int FUNC__OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug(fputs("Hooking " S(FUNC__OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } int FUNC_OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug(fputs("Hooking " S(FUNC_OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } /* * creat */ int FUNC___CREAT(const char *path, mode_t mode) { const char *e, *url; GFS_File gf; _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___CREAT) ": %s\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_CREAT(path, mode)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___CREAT) ": %s\n", path)); e = gfs_pio_create(url, GFARM_FILE_WRONLY, mode, &gf); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___CREAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } if ((e = gfs_pio_set_view_local(gf, 0)) != NULL) { gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } return (gfs_hook_insert_gfs_file(gf)); } int FUNC__CREAT(const char *path, mode_t mode) { _gfs_hook_debug(fputs("Hooking " S(FUNC__CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } int FUNC_CREAT(const char *path, mode_t mode) { _gfs_hook_debug(fputs("Hooking " S(FUNC_CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } /* * lseek */ OFF_T FUNC___LSEEK(int filedes, OFF_T offset, int whence) { GFS_File gf; const char *e; file_offset_t o; _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___LSEEK) ": %d\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_LSEEK(filedes, offset, whence)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___LSEEK) ": %d %d\n", filedes, gfs_pio_fileno(gf))); e = gfs_pio_seek(gf, offset, whence, &o); if (e == NULL) return ((OFF_T)o); _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___LSEEK) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } OFF_T FUNC__LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC__LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } OFF_T FUNC_LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC_LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } /* * stat */ #include <stdlib.h> extern int gfarm_node; #ifndef _STAT_VER int FUNC___STAT(const char *path, STRUCT_STAT *buf) { const char *e, *url; #if 1 char *canonic_path, *abs_path; int r, save_errno; #endif _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___STAT) ": %s\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_STAT(path, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___STAT) ": %s\n", path)); #if 0 /* Not yet implemented. */ e = gfs_stat(url, buf); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___STAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); #else /* Temporary code until gfs_stat() will be implemented. */ /* * gfs_stat() may not appropriate here, because: * 1. it doesn't/can't fill all necessary field of struct stat. * 2. it returns information of whole gfarm file, rather than * information of the fragment. */ e = gfarm_url_make_path(url, &canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } e = gfarm_path_localize_file_fragment(canonic_path, gfarm_node, &abs_path); free(canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___STAT) " locally: %s\n", abs_path)); r = SYSCALL_STAT(abs_path, buf); save_errno = errno; free(abs_path); errno = save_errno; return (r); #endif } int FUNC__STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC__STAT) ": %s\n", path)); return (FUNC___STAT(path, buf)); } int FUNC_STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC_STAT) ": %s\n", path)); return (FUNC___STAT(path, buf)); } #else /* defined(_STAT_VER) -- SVR4 or Linux */ /* * SVR4 and Linux do inline stat() and call _xstat/__xstat() with * an additional version argument. */ #ifdef __linux__ /* * unlike SVR4, stat() on linux seems to be compatible with xstat(STAT_VER,...) */ int FUNC___STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___STAT) ": %s\n", path)); return (FUNC___XSTAT(_STAT_VER, path, buf)); } int FUNC_STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC_STAT) ": %s\n", path)); return (FUNC___XSTAT(_STAT_VER, path, buf)); } #else /* * we don't provide stat(), because it is only used for SVR3 compat code. */ #endif int FUNC___XSTAT(int ver, const char *path, STRUCT_STAT *buf) { const char *e, *url; #if 1 char *canonic_path, *abs_path; int r, save_errno; #endif _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC___XSTAT) ": %s\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_XSTAT(ver, path, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___XSTAT) ": %s\n", path)); #if 0 /* Not yet implemented. */ e = gfs_stat(url, buf); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___XSTAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); #else /* Temporary code until gfs_stat() will be implemented. */ e = gfarm_url_make_path(url, &canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } e = gfarm_path_localize_file_fragment(canonic_path, gfarm_node, &abs_path); free(canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___XSTAT) " locally: %s\n", abs_path)); r = SYSCALL_XSTAT(ver, abs_path, buf); save_errno = errno; free(abs_path); errno = save_errno; return (r); #endif } int FUNC__XSTAT(int ver, const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC__XSTAT) ": %s\n", path)); return (FUNC___XSTAT(ver, path, buf)); } int FUNC_XSTAT(int ver, const char *path, STRUCT_STAT *buf) { _gfs_hook_debug(fprintf(stderr, "Hooking " S(FUNC_XSTAT) ": %s\n", path)); return (FUNC___XSTAT(ver, path, buf)); } #endif /* SVR4 or Linux */ <file_sep>/gfarm/tags/gfarm_1_0/gftool/gfexec/gfexec.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gfarm/gfarm.h> static char progname[] = "gfexec"; int main(int argc, char *argv[], char *envp[]) { char *e, *gfarm_url, **saved_argv; int i, saved_argc; --argc, ++argv; if (argc < 1) { printf("usage: %s program args ...\n", progname); exit(2); } /* save argv because it may be modified in gfarm_initialize() */ saved_argc = argc; saved_argv = malloc(argc * sizeof(char *) + 1); if (saved_argv == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } for (i = 0; i < argc; ++i) { saved_argv[i] = strdup(argv[i]); if (saved_argv[i] == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } } saved_argv[i] = '\0'; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); exit(1); } e = gfs_realpath(*argv, &gfarm_url); if (e != NULL) { fprintf(stderr, "%s: %s\n", *argv, e); exit(1); } e = gfs_execve(gfarm_url, saved_argv, envp); fprintf(stderr, "%s: %s\n", gfarm_url, e); free(gfarm_url); for (i = 0; i < saved_argc; ++i) free(saved_argv[i]); free(saved_argv); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); exit(1); } exit(1); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc4/gfptool/gfsplck/gfsplck.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <gfarm/gfarm.h> char *progname = "gfsplck"; static int check_all = 0; static int delete_invalid_file = 0; static char * check_path_info(char *gfarm_file) { struct gfarm_path_info p_info; char *e; /* check whether the path info is already registered. */ e = gfarm_path_info_get(gfarm_file, &p_info); if (e != NULL) return (e); gfarm_path_info_free(&p_info); return (NULL); } static char * fixfrag_i(char *pathname, char *gfarm_file, char *sec) { char *hostname, *e; struct gfarm_file_section_copy_info sc_info; if (check_all == 0) { /* check whether the fragment is already registered. */ e = gfarm_host_get_canonical_self_name(&hostname); if (e == NULL) { e = gfarm_file_section_copy_info_get( gfarm_file, sec, hostname, &sc_info); if (e == NULL) { /* already exist */ gfarm_file_section_copy_info_free(&sc_info); return (GFARM_ERR_ALREADY_EXISTS); } if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); } } /* register the section info */ e = gfs_pio_set_fragment_info_local(pathname, gfarm_file, sec); if (e != NULL) return (e); return (NULL); } static int fixdir(char *dir, char *gfarm_prefix); static int fixurl(char *gfarm_url) { char *gfarm_file, *local_path, *e; char sec[GFARM_INT32STRLEN]; struct stat sb; int rank; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s on %s: %s\n", gfarm_url, gfarm_host_get_self_name(), e); return 1; } /* check whether gfarm_url is directory or not. */ e = gfarm_path_localize(gfarm_file, &local_path); if (e == NULL && stat(local_path, &sb) == 0 && S_ISDIR(sb.st_mode)) { int r = 1; if (chdir(local_path) == 0) r = fixdir(".", gfarm_url); free(gfarm_file); free(local_path); return (r); } if (e != NULL) { fprintf(stderr, "%s on %s: %s\n", gfarm_url, gfarm_host_get_self_name(), e); free(gfarm_file); return (1); } free(local_path); /* XXX - assume gfarm_url is a fragmented file. */ e = gfs_pio_get_node_rank(&rank); if (e != NULL) { fprintf(stderr, "%s on %s: %s\n", gfarm_url, gfarm_host_get_self_name(), e); goto error_gfarm_file; } e = gfarm_path_localize_file_fragment(gfarm_file, rank, &local_path); if (e != NULL) { fprintf(stderr, "%s on %s: %s\n", gfarm_url, gfarm_host_get_self_name(), e); goto error_gfarm_file; } e = check_path_info(gfarm_file); if (e != NULL) { fprintf(stderr, "%s on %s: %s\n", gfarm_url, gfarm_host_get_self_name(), e); if (delete_invalid_file) { if (unlink(local_path) == 0) printf("%s on %s: deleted\n", local_path, gfarm_host_get_self_name()); else perror(local_path); } goto error_local_path; } sprintf(sec, "%d", rank); e = fixfrag_i(local_path, gfarm_file, sec); if (e != NULL && e != GFARM_ERR_ALREADY_EXISTS) { fprintf(stderr, "%s (%s) on %s: %s\n", gfarm_url, sec, gfarm_host_get_self_name(), e); if (delete_invalid_file) { if (unlink(local_path) == 0) printf("%s on %s: deleted\n", local_path, gfarm_host_get_self_name()); else perror(local_path); } goto error_local_path; } /* printf("%s (%s): fixed\n", gfarm_url, sec); */ return (0); error_local_path: free(local_path); error_gfarm_file: free(gfarm_file); return (1); } static int fixfrag(char *pathname, char *gfarm_prefix) { char *gfarm_url, *sec, *gfarm_file, *e; int r = 0; gfarm_url = malloc(strlen(gfarm_prefix) + strlen(pathname) + 2); if (gfarm_url == NULL) { fputs("not enough memory", stderr); return 1; } strcpy(gfarm_url, gfarm_prefix); if (gfarm_url[strlen(gfarm_url) - 1] != '/' && gfarm_url[strlen(gfarm_url) - 1] != ':') strcat(gfarm_url, "/"); strcat(gfarm_url, pathname); /* divide into file and section parts. */ sec = gfarm_url + strlen(gfarm_prefix); while (*sec) { if (*sec == ':') { *sec = '\0'; ++sec; break; } ++sec; } if (*sec == '\0') { fprintf(stderr, "%s on %s: invalid filename\n", pathname, gfarm_host_get_self_name()); free(gfarm_url); return 1; } e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s (%s) on %s: %s\n", gfarm_url, sec, gfarm_host_get_self_name(), e); if (delete_invalid_file) { if (unlink(pathname) == 0) printf("%s on %s: deleted\n", pathname, gfarm_host_get_self_name()); else perror(pathname); } free(gfarm_url); return 1; } /* check whether the fragment is already registered. */ e = fixfrag_i(pathname, gfarm_file, sec); if (e != NULL) { if (e != GFARM_ERR_ALREADY_EXISTS) { fprintf(stderr, "%s on %s: %s\n", pathname, gfarm_host_get_self_name(), e); if (delete_invalid_file) { if (unlink(pathname) == 0) printf("%s on %s: deleted\n", pathname, gfarm_host_get_self_name()); else perror(pathname); } r = 1; } else /* no message */; } else printf("%s (%s) on %s: fixed\n", gfarm_url, sec, gfarm_host_get_self_name()); free(gfarm_file); free(gfarm_url); return (r); } static int fixdir(char *dir, char *gfarm_prefix) { DIR* dirp; struct dirent *dp; struct stat sb; char *dir1; if (stat(dir, &sb)) { perror(dir); return 1; } if (S_ISREG(sb.st_mode)) return fixfrag(dir, gfarm_prefix); dirp = opendir(dir); if (dirp == NULL) { perror(dir); return 1; } if (strcmp(dir, ".") == 0) dir = ""; /* just a trick */ while ((dp = readdir(dirp)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue; dir1 = malloc(strlen(dir) + strlen(dp->d_name) + 2); if (dir1 == NULL) { fputs("not enough memory", stderr); closedir(dirp); return 1; } strcpy(dir1, dir); if (strcmp(dir, "")) strcat(dir1, "/"); strcat(dir1, dp->d_name); fixdir(dir1, gfarm_prefix); free(dir1); } closedir(dirp); if (dirp != NULL) return 1; return 0; } /* * */ void usage() { fprintf(stderr, "usage: %s [ -a ] [ -d ] [ Gfarm directory . . . ]\n", progname); fprintf(stderr, "options:\n"); fprintf(stderr, "\t-a\tcheck all files\n"); fprintf(stderr, "\t-d\tdelete invalid files\n"); exit(1); } int main(int argc, char *argv[]) { char *e, *gfarm_prefix; extern int optind; int c; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); } while ((c = getopt(argc, argv, "ad")) != EOF) { switch (c) { case 'a': check_all = 1; break; case 'd': delete_invalid_file = 1; break; default: usage(); } } argc -= optind; argv += optind; if (argc > 0) { while (argc-- > 0 && fixurl(*argv++) == 0); goto finish; } /* fix a whole spool directory. */ if (chdir(gfarm_spool_root) == 0) gfarm_prefix = "gfarm:/"; else gfarm_prefix = "gfarm:"; fixdir(".", gfarm_prefix); finish: e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); } exit(0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfsched_gfsd.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command if [ X"$MY_HOST" != X ]; then FSN_NAME=$MY_HOST else FSN_NAME=`hostname` fi RESULT=`gfsched $* | grep $FSN_NAME` if [ $? != 0 ]; then RESULT="gfsched $* error." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_1_1_rc3/lib/libgfarm/gfarm/agent_client.c /* * $Id$ */ #include <assert.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #include <stdio.h> /* sprintf() */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <gfarm/gfarm.h> #include "xxx_proto.h" #include "io_fd.h" #include "config.h" #include "agent_proto.h" #include "agent_client.h" struct agent_connection { struct xxx_connection *conn; }; static char * agent_client_connection0( struct sockaddr_un *peer_addr, struct agent_connection *agent_server) { char *e; int sock; sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock == -1) return (gfarm_errno_to_error(errno)); fcntl(sock, F_SETFD, 1); /* automatically close() on exec(2) */ if (connect(sock, peer_addr, sizeof(*peer_addr)) < 0) { e = gfarm_errno_to_error(errno); close(sock); return (e); } e = xxx_fd_connection_new(sock, &agent_server->conn); if (e != NULL) { close(sock); return (e); } return (NULL); } char * agent_client_connect(struct sockaddr_un *peer_addr, struct agent_connection **agent_serverp) { struct agent_connection *agent_server = malloc(sizeof(struct agent_connection)); char *e; if (agent_server == NULL) return (GFARM_ERR_NO_MEMORY); e = agent_client_connection0(peer_addr, agent_server); if (e != NULL) { free(agent_server); return (e); } *agent_serverp = agent_server; return (NULL); } char * agent_client_disconnect(struct agent_connection *agent_server) { char *e = xxx_connection_free(agent_server->conn); free(agent_server); return (e); } /* * agent_client RPC */ char * agent_client_rpc(struct agent_connection *agent_server, int just, int command, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc(agent_server->conn, just, command, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfarm_errno_to_error(error)); return (NULL); } char * agent_client_path_info_get(struct agent_connection *agent_server, const char *path, struct gfarm_path_info *info) { return (agent_client_rpc( agent_server, 0, AGENT_PROTO_PATH_INFO_GET, "s/siissoiiiiiii", path, &info->pathname, &info->status.st_ino, &info->status.st_mode, &info->status.st_user, &info->status.st_group, &info->status.st_size, &info->status.st_nsections, &info->status.st_atimespec.tv_sec, &info->status.st_atimespec.tv_nsec, &info->status.st_mtimespec.tv_sec, &info->status.st_mtimespec.tv_nsec, &info->status.st_ctimespec.tv_sec, &info->status.st_ctimespec.tv_nsec)); } char * agent_client_path_info_set(struct agent_connection *agent_server, char *path, struct gfarm_path_info *info) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_PATH_INFO_SET, "siissoiiiiiii/", path, info->status.st_ino, info->status.st_mode, info->status.st_user, info->status.st_group, info->status.st_size, info->status.st_nsections, info->status.st_atimespec.tv_sec, info->status.st_atimespec.tv_nsec, info->status.st_mtimespec.tv_sec, info->status.st_mtimespec.tv_nsec, info->status.st_ctimespec.tv_sec, info->status.st_ctimespec.tv_nsec)); } char * agent_client_path_info_replace(struct agent_connection *agent_server, char *path, struct gfarm_path_info *info) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_PATH_INFO_REPLACE, "siissoiiiiiii/", path, info->status.st_ino, info->status.st_mode, info->status.st_user, info->status.st_group, info->status.st_size, info->status.st_nsections, info->status.st_atimespec.tv_sec, info->status.st_atimespec.tv_nsec, info->status.st_mtimespec.tv_sec, info->status.st_mtimespec.tv_nsec, info->status.st_ctimespec.tv_sec, info->status.st_ctimespec.tv_nsec)); } char * agent_client_path_info_remove(struct agent_connection *agent_server, const char *path) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_PATH_INFO_REMOVE, "s/", path)); } char * agent_client_realpath_canonical(struct agent_connection *agent_server, const char *path, char **abspathp) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_REALPATH_CANONICAL, "s/s", path, abspathp)); } char * agent_client_get_ino(struct agent_connection *agent_server, const char *path, gfarm_int32_t *inop) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_GET_INO, "s/i", path, inop)); } char * agent_client_opendir(struct agent_connection *agent_server, const char *path, GFS_Dir *dirp) { gfarm_int32_t p; char *e; e = agent_client_rpc(agent_server, 0, AGENT_PROTO_OPENDIR, "s/i", path, &p); if (e == NULL) *dirp = (GFS_Dir)p; return (e); } char * agent_client_readdir(struct agent_connection *agent_server, GFS_Dir dir, struct gfs_dirent **entry) { gfarm_int32_t p = (gfarm_int32_t)dir; char *e, *name; static struct gfs_dirent de; e = agent_client_rpc( agent_server, 0, AGENT_PROTO_READDIR, "i/ihccs", p, &de.d_fileno, &de.d_reclen, &de.d_type, &de.d_namlen, &name); if (strcmp(name, "") == 0) *entry = NULL; else { strcpy(de.d_name, name); *entry = &de; } free(name); return (e); } char * agent_client_closedir(struct agent_connection *agent_server, GFS_Dir dir) { gfarm_int32_t p = (gfarm_int32_t)dir; return (agent_client_rpc( agent_server, 0, AGENT_PROTO_CLOSEDIR, "i/", p)); } char * agent_client_dirname(struct agent_connection *agent_server, GFS_Dir dir) { gfarm_int32_t p = (gfarm_int32_t)dir; char *e, *n; static char name[GFS_MAXNAMLEN]; e = agent_client_rpc( agent_server, 0, AGENT_PROTO_DIRNAME, "i/s", p, &n); if (e == NULL) { strcpy(name, n); free(n); return (name); } else return (NULL); } char * agent_client_uncachedir(struct agent_connection *agent_server) { return (agent_client_rpc(agent_server, 0, AGENT_PROTO_UNCACHEDIR, "/")); } <file_sep>/gfarm/tags/gfarm_1_0_rc3/lib/libgfarm/gfsl/gsi.c #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <ctype.h> #include <pwd.h> #include "gssapi.h" #include "gfutil.h" #include "gfevent.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "tcputil.h" static char * gssName2Str(gss_name_t name); static char * gssName2Str(name) gss_name_t name; { OM_uint32 minStat; char *ret = NULL; gss_name_t nameT = name; if (nameT != GSS_C_NO_NAME) { gss_buffer_desc nameBuf; (void)gss_display_name(&minStat, nameT, &nameBuf, NULL); ret = (char *)malloc(sizeof(char) * (nameBuf.length + 1)); if (ret == NULL) { goto done; } ret[nameBuf.length] = '\0'; (void)memcpy((void *)ret, (void *)nameBuf.value, nameBuf.length); (void)gss_release_buffer(&minStat, (gss_buffer_t)&nameBuf); } done: return ret; } char * gfarmGssGetCredentialName(cred) gss_cred_id_t cred; { char *ret = NULL; OM_uint32 minStat = GSS_S_COMPLETE; gss_name_t credName = GSS_C_NO_NAME; (void)gss_inquire_cred(&minStat, cred, &credName, NULL, /* lifetime */ NULL, /* usage */ NULL /* supported mech */); if (credName != GSS_C_NO_NAME) { ret = gssName2Str(credName); (void)gss_release_name(&minStat, &credName); } return ret; } static char ** gssCrackStatus(statValue, statType) OM_uint32 statValue; int statType; { OM_uint32 msgCtx; OM_uint32 minStat; gss_buffer_desc stStr; char **ret = (char **)malloc(sizeof(char *) * 1); int i = 0; char *dP = NULL; ret[0] = NULL; while (1) { msgCtx = 0; (void)gss_display_status(&minStat, statValue, statType, GSS_C_NO_OID, &msgCtx, &stStr); ret = (char **)realloc(ret, sizeof(char *) * (i + 2)); ret[i] = (char *)malloc(sizeof(char) * ((int)stStr.length + 1)); dP = ret[i]; dP[(int)stStr.length] = '\0'; i++; (void)memcpy((void *)dP, (void *)stStr.value, (int)stStr.length); (void)gss_release_buffer(&minStat, (gss_buffer_t)&stStr); if (msgCtx == 0) { break; } } ret[i] = NULL; return ret; } void gfarmGssFreeCrackedStatus(strPtr) char **strPtr; { char **cpS = strPtr; while (*cpS != NULL) { (void)free(*cpS++); } (void)free(strPtr); } char ** gfarmGssCrackMajorStatus(majStat) OM_uint32 majStat; { return gssCrackStatus(majStat, GSS_C_GSS_CODE); } char ** gfarmGssCrackMinorStatus(minStat) OM_uint32 minStat; { return gssCrackStatus(minStat, GSS_C_MECH_CODE); } void gfarmGssPrintMajorStatus(majStat) OM_uint32 majStat; { char **list = gfarmGssCrackMajorStatus(majStat); char **lP = list; if (*lP != NULL) { while (*lP != NULL) { gflog_error("", *lP++); } } else { gflog_error("GSS Major Status Error:", " UNKNOWN\n"); } gfarmGssFreeCrackedStatus(list); } void gfarmGssPrintMinorStatus(minStat) OM_uint32 minStat; { char **list = gfarmGssCrackMinorStatus(minStat); char **lP = list; if (*lP != NULL) { while (*lP != NULL) gflog_error("", *lP++); } else { gflog_error("GSS Minor Status Error:", " UNKNOWN\n"); } gfarmGssFreeCrackedStatus(list); } int gfarmGssAcquireCredential(credPtr, credUsage, majStatPtr, minStatPtr, credNamePtr) gss_cred_id_t *credPtr; gss_cred_usage_t credUsage; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; char **credNamePtr; { OM_uint32 majStat = 0; OM_uint32 minStat = 0; int ret = -1; *credPtr = GSS_C_NO_CREDENTIAL; majStat = gss_acquire_cred(&minStat, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, credUsage, credPtr, NULL, NULL); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } /* * Check validness. */ if (majStat == GSS_S_COMPLETE) { char *name = gfarmGssGetCredentialName(*credPtr); if (name != NULL) { /* Only valid when the name is got. */ ret = 1; } if (credNamePtr != NULL) { *credNamePtr = name; } else { (void)free(name); } } return ret; } int gfarmGssSendToken(fd, gsBuf) int fd; gss_buffer_t gsBuf; { int iLen = (int)(gsBuf->length); if (gfarmWriteLongs(fd, (long *)&iLen, 1) != 1) { return -1; } if (gfarmWriteBytes(fd, (char *)(gsBuf->value), iLen) != iLen) { return -1; } return iLen; } int gfarmGssReceiveToken(fd, gsBuf) int fd; gss_buffer_t gsBuf; { int iLen; char *buf = NULL; if (gsBuf->value != NULL) { OM_uint32 minStat; (void)gss_release_buffer(&minStat, gsBuf); } gsBuf->length = 0; gsBuf->value = NULL; if (gfarmReadLongs(fd, (long *)&iLen, 1) != 1) { return -1; } /* * XXXXX FIXME: * GSSAPI has no API for allocating a gss_buffer_t. It is not * recommended to allocate it with malloc(). */ buf = (void *)malloc(sizeof(char) * iLen); if (buf == NULL) { return -1; } if (gfarmReadBytes(fd, buf, iLen) != iLen) { (void)free(buf); return -1; } gsBuf->length = (size_t)iLen; gsBuf->value = (void *)buf; return iLen; } int gfarmGssAcceptSecurityContext(fd, cred, scPtr, majStatPtr, minStatPtr, remoteNamePtr, remoteCredPtr) int fd; gss_cred_id_t cred; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; char **remoteNamePtr; gss_cred_id_t *remoteCredPtr; { OM_uint32 majStat; OM_uint32 minStat; OM_uint32 retFlag = 0; gss_name_t initiatorName = GSS_C_NO_NAME; gss_cred_id_t remCred = GSS_C_NO_CREDENTIAL; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; gss_OID mechType = GSS_C_NO_OID; OM_uint32 timeRet; OM_uint32 minStat2; int tknStat; int ret = -1; if (remoteCredPtr != NULL) { *remoteCredPtr = GSS_C_NO_CREDENTIAL; } *scPtr = GSS_C_NO_CONTEXT; do { tknStat = gfarmGssReceiveToken(fd, itPtr); if (tknStat <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; break; } majStat = gss_accept_sec_context(&minStat, scPtr, cred, itPtr, GSS_C_NO_CHANNEL_BINDINGS, &initiatorName, &mechType, otPtr, &retFlag, &timeRet, &remCred); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { tknStat = gfarmGssSendToken(fd, otPtr); (void)gss_release_buffer(&minStat2, otPtr); if (tknStat <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; } } if (GSS_ERROR(majStat)) { if (*scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); break; } } } while (majStat & GSS_S_CONTINUE_NEEDED); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { (void)gss_release_buffer(&minStat2, otPtr); } if (majStat == GSS_S_COMPLETE && (retFlag & GSS_C_ANON_FLAG) == 0) { if (initiatorName != GSS_C_NO_NAME) { char *name = gssName2Str(initiatorName); if (name != NULL) { #if GLOBUS_BUG /* * From the RFC 2744, delegated credential is only * valid when GSS_C_DELEG_FLAG is true, however, this * is not satisfied at least in the Globus-2.2.x * GSSAPI library. * Although this was satisfied in the Globus-1.x once. */ #else /* !GLOBUS_BUG */ if ((retFlag & GSS_C_DELEG_FLAG) == GSS_C_DELEG_FLAG) { #endif /* !GLOBUS_BUG */ /* * If a credential is delegeted from the initiator, * Check a name of the delegated credential. */ if (remCred != GSS_C_NO_CREDENTIAL) { char *cName = gfarmGssGetCredentialName(remCred); if (cName != NULL) { if (strcmp(name, cName) == 0) { /* * Only valid if the name of sec-context and * the name of delegated credential are * identical. */ ret = 1; if (remoteCredPtr != NULL) { *remoteCredPtr = remCred; } } (void)free(cName); } } #if GLOBUS_BUG else { /* * Only valid when the sec-context name is got. */ ret = 1; } #else /* !GLOBUS_BUG */ } else { /* * Only valid when the sec-context name is got. */ ret = 1; } #endif /* !GLOBUS_BUG */ } if (remoteNamePtr != NULL) { *remoteNamePtr = name; } else { (void)free(name); } } if (ret != 1) { majStat = GSS_S_UNAUTHORIZED; } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (initiatorName != GSS_C_NO_NAME) { (void)gss_release_name(&minStat2, &initiatorName); } if (ret == -1) { if (*scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); } } return ret; } int gfarmGssInitiateSecurityContext(fd, cred, reqFlag, scPtr, majStatPtr, minStatPtr,remoteNamePtr) int fd; gss_cred_id_t cred; OM_uint32 reqFlag; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; char **remoteNamePtr; { OM_uint32 majStat; OM_uint32 minStat; OM_uint32 retFlag = 0; gss_name_t acceptorName = GSS_C_NO_NAME; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; gss_OID *actualMechType = NULL; OM_uint32 timeRet; OM_uint32 minStat2; int tknStat; int ret = -1; *scPtr = GSS_C_NO_CONTEXT; /* * Implementation specification: * In gfarm, an initiator must reveal own identity to an acceptor. */ reqFlag &= ~GSS_C_ANON_FLAG; while (1) { majStat = gss_init_sec_context(&minStat, cred, scPtr, acceptorName, GSS_C_NO_OID, reqFlag, 0, GSS_C_NO_CHANNEL_BINDINGS, itPtr, actualMechType, otPtr, &retFlag, &timeRet); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { tknStat = gfarmGssSendToken(fd, otPtr); (void)gss_release_buffer(&minStat2, otPtr); if (tknStat <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; } } if (GSS_ERROR(majStat)) { if (*scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); break; } } if (majStat & GSS_S_CONTINUE_NEEDED) { tknStat = gfarmGssReceiveToken(fd, itPtr); if (tknStat <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; break; } } else { break; } } if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { (void)gss_release_buffer(&minStat2, otPtr); } if (majStat == GSS_S_COMPLETE) { acceptorName = GSS_C_NO_NAME; (void)gss_inquire_context(&minStat2, *scPtr, NULL, &acceptorName, NULL, NULL, NULL, NULL, NULL); if (acceptorName != GSS_C_NO_NAME) { char *name = gssName2Str(acceptorName); if (name != NULL) { /* Only valid when the name is got. */ ret = 1; } if (remoteNamePtr != NULL) { *remoteNamePtr = name; } else { (void)free(name); } (void)gss_release_name(&minStat2, &acceptorName); } if (ret != 1) { majStat = GSS_S_UNAUTHORIZED; } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (ret == -1) { if (*scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); } } return ret; } void gfarmGssDeleteSecurityContext(scPtr) gss_ctx_id_t *scPtr; { OM_uint32 minStat; if (scPtr == NULL || *scPtr == GSS_C_NO_CONTEXT) { return; } (void)gss_delete_sec_context(&minStat, scPtr, GSS_C_NO_BUFFER); } int gfarmGssConfigureMessageSize(sCtx, doEncrypt, qopReq, reqOutSz, maxInSzPtr, majStatPtr, minStatPtr) gss_ctx_id_t sCtx; int doEncrypt; gss_qop_t qopReq; unsigned int reqOutSz; unsigned int *maxInSzPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; OM_uint32 oReqSz = (OM_uint32)reqOutSz; OM_uint32 oMaxSz = oReqSz; majStat = gss_wrap_size_limit(&minStat, sCtx, doEncrypt, qopReq, oReqSz, &oMaxSz); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (majStat == GSS_S_COMPLETE) { ret = 1; if (maxInSzPtr != NULL) { *maxInSzPtr = (int)oMaxSz; } } return ret; } int gfarmGssSend(fd, sCtx, doEncrypt, qopReq, buf, n, chunkSz, statPtr) int fd; gss_ctx_id_t sCtx; int doEncrypt; gss_qop_t qopReq; char *buf; int n; int chunkSz; OM_uint32 *statPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; int sum = 0; int rem = n; int len; /* * Send a length of a PLAIN TEXT. * XXXXX FIX ME: * Generally it is wrong idea sending a plain text length * in plain text communication. Should be encrypted. */ if (buf == NULL || n <= 0) { ret = 0; majStat = GSS_S_COMPLETE; goto Done; } if (gfarmWriteLongs(fd, (long *)&n, 1) != 1) { majStat = GSS_S_CALL_INACCESSIBLE_WRITE; goto Done; } do { inputToken.value = (void *)((char *)(buf + sum)); len = (rem > chunkSz ? chunkSz : rem); inputToken.length = (size_t)len; majStat = gss_wrap(&minStat, sCtx, doEncrypt, qopReq, (const gss_buffer_t)itPtr, NULL, otPtr); if (majStat == GSS_S_COMPLETE) { if (otPtr->length > 0) { if (gfarmGssSendToken(fd, otPtr) <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; goto Done; } (void)gss_release_buffer(&minStat, otPtr); otPtr->length = 0; otPtr->value = NULL; rem -= len; sum += len; } else { majStat = GSS_S_DEFECTIVE_TOKEN; goto Done; } } else { break; } } while (rem > 0); if (rem <= 0) { ret = n; } Done: if (otPtr->length > 0) { (void)gss_release_buffer(&minStat, otPtr); } if (statPtr != NULL) { *statPtr = majStat; } return ret; } int gfarmGssReceive(fd, sCtx, bufPtr, lenPtr, statPtr) int fd; gss_ctx_id_t sCtx; char **bufPtr; int *lenPtr; OM_uint32 *statPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; int n; int sum = 0; int rem; int len; char *buf = NULL; int i; /* * Receive a length of a PLAIN TEXT. * XXXXX FIX ME: * Generally it is wrong idea receiving a plain text * length in plain text communication. Should be * encrypted. */ i = gfarmReadLongs(fd, (long *)&n, 1); if (i == 0) { ret = 0; n = 0; majStat = GSS_S_COMPLETE; goto Done; } else if (i != 1) { majStat = GSS_S_CALL_INACCESSIBLE_READ; goto Done; } buf = (char *)malloc(sizeof(char) * n); if (buf == NULL) { majStat = GSS_S_FAILURE; goto Done; } rem = n; do { if (gfarmGssReceiveToken(fd, itPtr) <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; goto Done; } majStat = gss_unwrap(&minStat, sCtx, (const gss_buffer_t)itPtr, otPtr, NULL, NULL); (void)gss_release_buffer(&minStat, itPtr); itPtr->length = 0; itPtr->value = NULL; if (majStat == GSS_S_COMPLETE) { if (otPtr->length > 0) { (void)memcpy((void *)(buf + sum), (void *)otPtr->value, otPtr->length); len = (int)(otPtr->length); rem -= len; sum += len; (void)gss_release_buffer(&minStat, otPtr); otPtr->length = 0; otPtr->value = NULL; } else { majStat = GSS_S_DEFECTIVE_TOKEN; goto Done; } } else { break; } } while (rem > 0); if (rem <= 0) { ret = n; } Done: if (otPtr->length > 0) { (void)gss_release_buffer(&minStat, otPtr); } if (itPtr->length > 0) { (void)gss_release_buffer(&minStat, itPtr); } if (statPtr != NULL) { *statPtr = majStat; } if (ret == -1) { *bufPtr = NULL; *lenPtr = -1; } else { *bufPtr = buf; *lenPtr = n; } return ret; } #if GFARM_GSS_EXPORT_CRED_ENABLED struct gfarmExportedCredential { char *env; char *filename; }; gfarmExportedCredential * gfarmGssExportCredential(cred, statPtr) gss_cred_id_t cred; OM_uint32 *statPtr; { gfarmExportedCredential *exportedCred = NULL; OM_uint32 majStat = 0; OM_uint32 minStat = 0; gss_buffer_desc buf = GSS_C_EMPTY_BUFFER; char *exported, *filename, *env; static char exported_name[] = "X509_USER_DELEG_PROXY="; static char env_name[] = "X509_USER_PROXY="; static char file_prefix[] = "FILE:"; majStat = gss_export_cred(&minStat, cred, GSS_C_NO_OID, 1, &buf); if (GSS_ERROR(majStat)) goto Done; exported = (char *)buf.value; for (filename = exported; *filename != '\0'; filename++) if (!isalnum(*(unsigned char *)filename) && *filename != '_') break; if (*filename != '=') { /* not an environment variable */ majStat = GSS_S_UNAVAILABLE; goto Done; } filename++; if (memcmp(exported, exported_name, sizeof(exported_name) - 1) == 0) { env = malloc(sizeof(env_name) + strlen(filename)); if (env == NULL) { majStat = GSS_S_FAILURE; goto Done; } memcpy(env, env_name, sizeof(env_name) - 1); strcpy(env + sizeof(env_name) - 1, filename); filename = env + sizeof(env_name) - 1; } else { env = strdup(exported); if (env == NULL) { majStat = GSS_S_FAILURE; goto Done; } filename = env + (filename - exported); } if (memcmp(filename, file_prefix, sizeof(file_prefix) - 1) == 0) filename += sizeof(file_prefix) - 1; exportedCred = malloc(sizeof(*exportedCred)); if (exportedCred == NULL) { free(env); majStat = GSS_S_FAILURE; goto Done; } exportedCred->env = env; exportedCred->filename = access(filename, R_OK) == 0 ? filename : NULL; Done: gss_release_buffer(&minStat, &buf); if (statPtr != NULL) *statPtr = majStat; return exportedCred; } char * gfarmGssEnvForExportedCredential(exportedCred) gfarmExportedCredential *exportedCred; { return exportedCred->env; } void gfarmGssDeleteExportedCredential(exportedCred) gfarmExportedCredential *exportedCred; { if (exportedCred->filename != NULL) unlink(exportedCred->filename); free(exportedCred->env); free(exportedCred); } #endif /* GFARM_GSS_EXPORT_CRED_ENABLED */ /* * multiplexed version of gfarmGssInitiateSecurityContext() */ struct gfarmGssInitiateSecurityContextState { struct gfarm_eventqueue *q; struct gfarm_event *readable, *writable; int fd; gss_cred_id_t cred; OM_uint32 reqFlag; void (*continuation)(void *); void *closure; int completed; OM_uint32 majStat; OM_uint32 minStat; gss_ctx_id_t sc; gss_name_t acceptorName; OM_uint32 retFlag; gss_buffer_desc inputToken; gss_buffer_t itPtr; gss_buffer_desc outputToken; gss_buffer_t otPtr; gss_OID *actualMechType; OM_uint32 timeRet; }; static void gssInitiateSecurityContextSwitch(state) struct gfarmGssInitiateSecurityContextState *state; { OM_uint32 minStat2; struct timeval timeout; if (GSS_ERROR(state->majStat)) { if (state->sc != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, &state->sc, GSS_C_NO_BUFFER); return; } } if (state->majStat & GSS_S_CONTINUE_NEEDED) { timeout.tv_sec = GFARM_GSS_AUTH_TIMEOUT; timeout.tv_usec = 0; if (gfarm_eventqueue_add_event(state->q, state->readable, &timeout) == 0) { /* go to gfarmGssInitiateSecurityContextRecieveToken() */ return; } state->majStat = GSS_S_FAILURE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } else { state->completed = 1; } } static void gssInitiateSecurityContextNext(state) struct gfarmGssInitiateSecurityContextState *state; { OM_uint32 minStat2; state->majStat = gss_init_sec_context(&state->minStat, state->cred, &state->sc, state->acceptorName, GSS_C_NO_OID, state->reqFlag, 0, GSS_C_NO_CHANNEL_BINDINGS, state->itPtr, state->actualMechType, state->otPtr, &state->retFlag, &state->timeRet); if (state->itPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->itPtr); } if (state->otPtr->length > 0) { if (gfarm_eventqueue_add_event(state->q, state->writable, NULL) == 0) { /* go to gfarmGssInitiateSecurityContextSendToken() */ return; } state->majStat = GSS_S_FAILURE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } gssInitiateSecurityContextSwitch(state); } static void gfarmGssInitiateSecurityContextSendToken(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct gfarmGssInitiateSecurityContextState *state = closure; int tknStat; OM_uint32 minStat2; tknStat = gfarmGssSendToken(fd, state->otPtr); (void)gss_release_buffer(&minStat2, state->otPtr); if (tknStat <= 0) { state->majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; } gssInitiateSecurityContextSwitch(state); if (GSS_ERROR(state->majStat) || state->completed) { if (state->continuation != NULL) (*state->continuation)(state->closure); } } static void gfarmGssInitiateSecurityContextReceiveToken(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct gfarmGssInitiateSecurityContextState *state = closure; int tknStat; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->majStat = GSS_S_UNAVAILABLE; /* failure: timeout */ } else { assert(events == GFARM_EVENT_READ); tknStat = gfarmGssReceiveToken(fd, state->itPtr); if (tknStat <= 0) { state->majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; } else { gssInitiateSecurityContextNext(state); if (!GSS_ERROR(state->majStat) && !state->completed) { /* possibly go to gfarmGssInitiateSecurityContextSendToken() */ return; } } } assert(GSS_ERROR(state->majStat) || state->completed); if (state->continuation != NULL) (*state->continuation)(state->closure); } struct gfarmGssInitiateSecurityContextState * gfarmGssInitiateSecurityContextRequest(q, fd, cred, reqFlag, continuation, closure, majStatPtr, minStatPtr) struct gfarm_eventqueue *q; int fd; gss_cred_id_t cred; OM_uint32 reqFlag; void (*continuation)(void *); void *closure; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { struct gfarmGssInitiateSecurityContextState *state; state = malloc(sizeof(*state)); if (state == NULL) { if (majStatPtr != NULL) { *majStatPtr = GSS_S_FAILURE; } if (minStatPtr != NULL) { *minStatPtr = GFSL_DEFAULT_MINOR_ERROR; } return (NULL); } state->completed = 0; state->majStat = GSS_S_COMPLETE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; state->writable = gfarm_fd_event_alloc(GFARM_EVENT_WRITE, fd, gfarmGssInitiateSecurityContextSendToken, state); if (state->writable == NULL) { state->majStat = GSS_S_FAILURE; goto freeState; } /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc(GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, fd, gfarmGssInitiateSecurityContextReceiveToken, state); if (state->readable == NULL) { state->majStat = GSS_S_FAILURE; goto freeWritable; } state->q = q; state->fd = fd; state->cred = cred; state->reqFlag = reqFlag; state->continuation = continuation; state->closure = closure; state->retFlag = 0; state->acceptorName = GSS_C_NO_NAME; /* GSS_C_EMPTY_BUFFER */ state->inputToken.length = 0; state->inputToken.value = NULL; state->itPtr = &state->inputToken; /* GSS_C_EMPTY_BUFFER */ state->outputToken.length = 0; state->outputToken.value = NULL; state->otPtr = &state->outputToken; state->actualMechType = NULL; state->sc = GSS_C_NO_CONTEXT; /* * Implementation specification: * In gfarm, an initiator must reveal own identity to an acceptor. */ state->reqFlag &= ~GSS_C_ANON_FLAG; gssInitiateSecurityContextNext(state); assert(!state->completed); if (!GSS_ERROR(state->majStat)) { if (majStatPtr != NULL) { *majStatPtr = GSS_S_COMPLETE; } if (minStatPtr != NULL) { *minStatPtr = GFSL_DEFAULT_MINOR_ERROR; } return (state); } gfarm_event_free(state->readable); freeWritable: gfarm_event_free(state->writable); freeState: if (majStatPtr != NULL) { *majStatPtr = state->majStat; } if (minStatPtr != NULL) { *minStatPtr = state->minStat; } free(state); return (NULL); } int gfarmGssInitiateSecurityContextResult(state, scPtr, majStatPtr, minStatPtr, remoteNamePtr) struct gfarmGssInitiateSecurityContextState *state; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; char **remoteNamePtr; { int ret = -1; OM_uint32 minStat2; assert(GSS_ERROR(state->majStat) || state->completed); if (state->itPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->itPtr); } if (state->otPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->otPtr); } if (state->majStat == GSS_S_COMPLETE) { state->acceptorName = GSS_C_NO_NAME; (void)gss_inquire_context(&minStat2, state->sc, NULL, &state->acceptorName, NULL, NULL, NULL, NULL, NULL); if (state->acceptorName != GSS_C_NO_NAME) { char *name = gssName2Str(state->acceptorName); if (name != NULL) { /* Only valid when the name is got. */ ret = 1; } if (remoteNamePtr != NULL) { *remoteNamePtr = name; } else { (void)free(name); } (void)gss_release_name(&minStat2, &state->acceptorName); } if (ret != 1) { state->majStat = GSS_S_UNAUTHORIZED; } } gfarm_event_free(state->readable); gfarm_event_free(state->writable); if (majStatPtr != NULL) { *majStatPtr = state->majStat; } if (minStatPtr != NULL) { *minStatPtr = state->minStat; } if (ret == -1) { if (state->sc != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, &state->sc, GSS_C_NO_BUFFER); } } *scPtr = state->sc; free(state); return ret; } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfsl/gfsl_config.h #ifndef _GFARM_CONFIG_H_ #define _GFARM_CONFIG_H_ /* Now, Globus GSSAPI seems to support the encryption feature. */ /*#define USE_GLOBUS*/ #ifdef USE_GLOBUS /* * Globus GSSAPI does not support confidentiality security service. */ #define GFARM_GSS_ENCRYPTION_ENABLED 0 #ifndef GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG #define GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG 1 #endif /* GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG */ #define GFARM_GSS_DEFAULT_QOP GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG #define GFARM_GSS_C_CONF_FLAG 0 #else #define GFARM_GSS_ENCRYPTION_ENABLED 1 #define GFARM_GSS_DEFAULT_QOP GSS_C_QOP_DEFAULT #define GFARM_GSS_C_CONF_FLAG GSS_C_CONF_FLAG #endif /* USE_GLOBUS */ #define GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG \ (OM_uint32)(GSS_C_DELEG_FLAG | /* delegation */ \ GSS_C_MUTUAL_FLAG | /* mutual authentication */ \ GSS_C_REPLAY_FLAG | /* reply message detection */ \ GSS_C_SEQUENCE_FLAG | /* out of sequence detection */ \ GFARM_GSS_C_CONF_FLAG | /* confidentiality service */ \ GSS_C_INTEG_FLAG /* integrity check service */ \ ) #define GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE 8 * 1024 * 1024 #define GFARM_DEFAULT_INITIATOR_CONFIG_FILE "gfarm-initiator.conf" #define GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE "gfarm-acceptor.conf" #define GFARM_DEFAULT_INSTALL_ETC_DIR "etc" #ifndef GFARM_INSTALL_ETC_DIR #define GFARM_INSTALL_ETC_DIR "/etc" #endif /* GFARM_INSTALL_ETC_DIR */ #ifndef GFARM_INSTALL_DIR_ENV #define GFARM_INSTALL_DIR_ENV "GFARM_HOME" #endif /* GFARM_INSTALL_DIR_ENV */ #define GFARM_DEFAULT_USERMAP_FILE "gfarm-usermap" #endif /* _GFARM_CONFIG_H_ */ <file_sep>/gfarm_samba/trunk/configure.ac # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) AC_INIT([gfarm_samba], [1.0.0]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AC_CONFIG_SRCDIR([gfarm.c]) AC_CONFIG_HEADERS([config_gfarm.h]) AC_CONFIG_MACRO_DIR([m4]) # Checks for programs. AC_PROG_CC AC_PROG_LIBTOOL ### --with-gfarm=GFARM AC_MSG_CHECKING([for Gfarm file system]) AC_ARG_WITH([gfarm], AC_HELP_STRING([--with-gfarm=PATH], [path to gfarm file system [[/usr]]])) case x$with_gfarm in x|xyes|xno) GFARM=/usr ;; *) GFARM=$with_gfarm ;; esac if test x"$GFARM" != x/usr; then CPPFLAGS="$CPPFLAGS -I$GFARM/include" LDFLAGS="$LDFLAGS -L$GFARM/lib" fi AC_MSG_RESULT([$GFARM]) ### --with-samba=SAMBA AC_MSG_CHECKING([for Samba]) AC_ARG_WITH([samba], AC_HELP_STRING([--with-samba=PATH], [path to sambe source [[/usr/src/samba/source3]]])) case x$with_samba in x|xyes|xno) SAMBA=/usr/src/samba/source3 ;; *) SAMBA=$with_samba ;; esac if test x"$SAMBA" != x/usr; then CPPFLAGS="$CPPFLAGS -I$SAMBA/include -I$SAMBA/../lib/replace -I$SAMBA -I$SAMBA/.. -I$SAMBA/../lib/talloc -I$SAMBA/../lib/tevent" LDFLAGS="$LDFLAGS -L$SAMBA/lib" fi AC_MSG_RESULT([$SAMBA]) # Checks for libraries. AC_CHECK_LIB([gfarm], [gfarm_initialize],, [AC_MSG_ERROR([libgfarm not found. Use --with-gfarm option])]) AC_CHECK_LIB([gfarm], [gfs_statdir],, [AC_MSG_ERROR([Gfarm-2.5.4 or later is required])]) # Checks for header files. AC_CHECK_HEADERS([fcntl.h unistd.h]) AC_CHECK_HEADERS([gfarm/gfarm.h],, [AC_MSG_ERROR([gfarm/gfarm.h not found])]) # Samba includes.h cannot be checked by AC_CHECK_HEADERS AC_MSG_CHECKING([Samba includes.h]) AC_TRY_COMPILE([#include "includes.h"],[],, [AC_MSG_ERROR([Samba include files not found. Use --with-samba option to specify the samba source directory])]) AC_MSG_RESULT([yes]) # Checks for typedefs, structures, and compiler characteristics. AC_HEADER_STDBOOL AC_TYPE_UID_T AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T # Checks for library functions. AC_CHECK_FUNCS([memset strdup strerror]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfutil/gfutil.h #ifndef HAVE_DAEMON int gfarm_daemon(int, int); #else #define gfarm_daemon daemon #endif void gfarm_unlimit_nofiles(int *); /* logutil */ #ifndef GFARM_DEFAULT_FACILITY #define GFARM_DEFAULT_FACILITY LOG_LOCAL0 #endif void gflog_message(int, char *, char *); void gflog_error(char *, char *); void gflog_warning(char *, char *); void gflog_notice(char *, char *); void gflog_info(char *, char *); void gflog_debug(char *, char *); void gflog_warning_errno(char *); void gflog_fatal(char *, char *); void gflog_fatal_errno(char *); void gflog_set_identifier(char *); void gflog_set_auxiliary_info(char *); char *gflog_get_auxiliary_info(void); void gflog_syslog_open(int, int); int gflog_syslog_name_to_facility(char *); <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/gfptool/util/gfregister.in #!/bin/sh PTOOLS_BIN='gfcombine gfcombine_hook gfcp gfcp_hook gfgrep gfrcmd gfreg gfsplck' PTOOLS_LIBEXEC='gfrepbe_client gfrepbe_server' # gfwc may not be included in a release binary if [ -f @prefix@/bin/gfwc ]; then PTOOLS_BIN="$PTOOLS_BIN gfwc" fi hostname=`hostname` arch=`gfhost -M $hostname | sed 's/ .*//'` status=0 if test x"$arch" = x"" then echo "$0: error: architecture name of $hostname isn't determined" >&2 exit 1 fi cd @prefix@ echo Creating gfarm:/bin gfarm:/libexec ... if gfmkdir gfarm:/bin gfarm:/libexec; then : else status=1 fi # force to register the commands, even if already registered, # because the binaries may be obsolete. echo Registering gfarm commands for $arch ... ( cd bin && gfreg -f $PTOOLS_BIN gfarm:/bin ) ( cd libexec && gfreg -f $PTOOLS_LIBEXEC gfarm:/libexec ) all_commands='' for cmd in $PTOOLS_BIN; do all_commands="$all_commands gfarm:/bin/$cmd" done for cmd in $PTOOLS_LIBEXEC; do all_commands="$all_commands gfarm:/libexec/$cmd" done gfhost -a $arch | while read host; do echo Replicating gfarm commands to $host ... if gfrep -b -I $arch -s $hostname -d $host $all_commands then : else status=1 fi done exit $status <file_sep>/gfarm/tags/gfarm_1_0_beta_2/package/redhat/gfsd.in #!/bin/bash # # Init file for Gfarm filesystem daemon # # chkconfig: 2345 95 05 # description: Gfarm filesystem daemon # # processname: gfsd # config: /etc/gfarm.conf # pidfile: /var/run/gfsd.pid # # $Id$ gfarm_prefix=@prefix@ prog="gfsd" # source function library . /etc/rc.d/init.d/functions # pull in sysconfig settings [ -f /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog RETVAL=0 # Some functions to make the below more readable BINARY=$gfarm_prefix/sbin/$prog PID_FILE=/var/run/${prog}.pid start() { echo -n $"Starting $prog:" initlog -c "$BINARY $OPTIONS" && success || failure RETVAL=$? [ "$RETVAL" = 0 ] && touch /var/lock/subsys/$prog echo } stop() { echo -n $"Stopping $prog:" killproc $BINARY -TERM RETVAL=$? [ "$RETVAL" = 0 ] && rm -f /var/lock/subsys/$prog echo } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) status $BINARY RETVAL=$? ;; *) echo $"Usage: $0 {start|stop|restart|status}" RETVAL=1 esac exit $RETVAL <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT2-2-2-4_master_and_non_candidate_slave_gfmd_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-4" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd and a slave gfmd which is not master candidate down" ###################################################################### . ./FT-common ft_setup() { CANDIDATE=`ft_get_master_candidate` [ $? -ne 0 ] && return $FT_RESULT_FAIL SLAVE="gfmd2" [ "X$CANDIDATE" = "X$SLAVE" ] && SLAVE="gfmd3" return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS gfmdhost -l > /dev/null 2>&1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "gfmdhost -l" $RESULT $gfservice stop-gfmd $SLAVE \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $SLAVE" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_rc1/gftool/gfrep/gfrep.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "gfs_client.h" #define LINELEN 2048 char *program_name = "gfrep"; /* Do not use gfrepbe_client/gfrepbe_server, but use gfsd internal routine */ int bootstrap_method = 0; int verbose = 0; struct replication_job { struct replication_job *next; char *file; char *section; char *src; char *dest; }; struct replication_job_list { struct replication_job *head; struct replication_job **tail; int n; }; struct replication_pair { struct replication_pair *next; gfarm_stringlist files, sections; struct gfs_client_rep_backend_state *state; char *src, *dest; }; struct replication_pair_list { struct replication_pair *head; struct replication_pair **tail; int max_fragments_per_pair; }; void replication_job_list_init(struct replication_job_list *list) { list->head = NULL; list->tail = &list->head; list->n = 0; } int replication_job_list_add(struct replication_job_list *list, char *file, char *section, char *src, char *dest) { char *e, *gfarm_file, *dest_canonical; struct replication_job *job; if (bootstrap_method) { if (src != NULL) { e = gfarm_url_section_replicate_from_to( file, section, src, dest); if (e != NULL) fprintf(stderr, "%s: replicate %s:%s from %s to %s: %s\n", program_name, file, section, src, dest, e); } else { e = gfarm_url_section_replicate_to( file, section, dest); if (e != NULL) fprintf(stderr, "%s: replicate %s:%s to %s: %s\n", program_name, file, section, dest, e); } return (e != NULL ? 1 : 0); } e = gfarm_url_make_path(file, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: parsing pathname %s: %s\n", program_name, file, e); return (1); } e = gfarm_host_get_canonical_name(dest, &dest_canonical); if (e != NULL) { fprintf(stderr, "%s: host %s isn't a filesystem node: %s\n", program_name, dest, e); free(gfarm_file); return (1); } if (gfarm_file_section_copy_info_does_exist(gfarm_file, section, dest_canonical)) { /* already exists, don't have to replicate */ free(dest_canonical); free(gfarm_file); return (0); } job = malloc(sizeof(*job)); if (job == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } job->file = gfarm_file; job->section = strdup(section); if (job->section == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } job->dest = dest_canonical; if (src != NULL) { e = gfarm_host_get_canonical_name(src, &job->src); if (e != NULL) { fprintf(stderr, "%s: checking source host %s for %s:%s: %s", program_name, src, file, section, e); free(job); free(dest_canonical); free(gfarm_file); return (1); } } else { e = gfarm_file_section_host_schedule(job->file, section, &job->src); if (e != NULL) { fprintf(stderr, "%s: searching source host for %s:%s: %s", program_name, file, section, e); free(job); free(dest_canonical); free(gfarm_file); return (1); } } job->next = NULL; *list->tail = job; list->tail = &job->next; list->n++; return (0); } void replication_pair_init(struct replication_pair_list *transfers) { transfers->head = NULL; transfers->tail = &transfers->head; transfers->max_fragments_per_pair = 0; } int replication_pair_entry(struct replication_pair_list *transfers, struct replication_job **list, int n) { char *e; int i; struct replication_pair *pair = malloc(sizeof(*pair)); if (pair == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(&pair->files); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(&pair->sections); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < n; i++) { e = gfarm_stringlist_add(&pair->files, list[i]->file); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(&pair->sections, list[i]->section); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } } pair->src = list[0]->src; pair->dest = list[0]->dest; if (verbose) fprintf(stderr, "%s: scheduling %s -> %s\n", program_name, pair->src, pair->dest); e = gfarm_file_section_replicate_multiple_request( &pair->files, &pair->sections, pair->src, pair->dest, &pair->state); if (e != NULL) { fprintf(stderr, "%s: replication from %s to %s: %s\n", program_name, pair->src, pair->dest, e); gfarm_stringlist_free(&pair->files); gfarm_stringlist_free(&pair->sections); free(pair); return (1); } pair->next = NULL; *transfers->tail = pair; transfers->tail = &pair->next; if (transfers->max_fragments_per_pair < n) transfers->max_fragments_per_pair = n; return (0); } int replication_pair_results(struct replication_pair_list *transfers) { char *e, **results = malloc(sizeof(*results) * transfers->max_fragments_per_pair); struct replication_pair *pair; int i, n, error_happend = 0; if (results == NULL) { fprintf(stderr, "%s: cannot allocate memory for %d results\n", program_name, transfers->max_fragments_per_pair); exit(EXIT_FAILURE); } for (pair = transfers->head; pair != NULL; pair = pair->next) { e = gfarm_file_section_replicate_multiple_result(pair->state, results); if (e != NULL) { fprintf(stderr, "%s: replication from %s to %s: %s\n", program_name, pair->src, pair->dest, e); error_happend = 1; continue; } n = gfarm_stringlist_length(&pair->files); for (i = 0; i < n; i++) { if (results[i] == NULL) continue; fprintf(stderr, "%s: replicate %s:%s from %s to %s: %s\n", program_name, gfarm_stringlist_elem(&pair->files, i), gfarm_stringlist_elem(&pair->sections, i), pair->src, pair->dest, e); error_happend = 1; } } return (error_happend); } /* sort by (src, dest) */ int job_compare(const void *a, const void *b) { struct replication_job *const * jpa = a, *const * jpb = b; struct replication_job *ja = *jpa, *jb = *jpb; int cmp; if ((cmp = strcasecmp(ja->src, jb->src)) < 0) return (-1); else if (cmp > 0) return (1); else if ((cmp = strcasecmp(ja->dest, jb->dest)) < 0) return (-1); else if (cmp > 0) return (1); else if ((cmp = strcmp(ja->file, jb->file)) < 0) return (-1); else if (cmp > 0) return (1); else return (strcmp(ja->section, jb->section)); } int replication_job_list_execute(struct replication_job_list *list) { int i, top; struct replication_job *job, **jobs; int error_happend = 0; struct replication_pair_list transfers; if (bootstrap_method) { /* All jobs are already completed here with bootstrap mode */ return (0); } if (list->n == 0) /* do nothing */ return (0); jobs = malloc(sizeof(*jobs) * list->n); if (jobs == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } for (job = list->head, i = 0; job != NULL; job = job->next, i++) { if (i >= list->n) { /* sanity */ fprintf(stderr, "%s: panic: more than %d jobs\n", program_name, list->n); exit(EXIT_FAILURE); } jobs[i] = job; } qsort(jobs, list->n, sizeof(*jobs), job_compare); replication_pair_init(&transfers); top = 0; for (i = 1; i < list->n; i++) { if (strcasecmp(jobs[top]->src, jobs[i]->src) != 0 || strcasecmp(jobs[top]->dest, jobs[i]->dest) != 0) { if (replication_pair_entry(&transfers, &jobs[top], i - top)) error_happend = 1; top = i; } } if (replication_pair_entry(&transfers, &jobs[top], list->n - top)) error_happend = 1; if (replication_pair_results(&transfers)) error_happend = 1; return (error_happend); } int replicate_by_fragment_dest_list(char *fragment_dest_list, char *src_default) { int error_happend = 0; struct replication_job_list job_list; int n, lineno; char line[LINELEN]; char file[LINELEN], section[LINELEN], dest[LINELEN], src[LINELEN]; FILE *fp; fp = fopen(fragment_dest_list, "r"); if (fp == NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, fragment_dest_list, strerror(errno)); exit(EXIT_FAILURE); } replication_job_list_init(&job_list); for (lineno = 1; fgets(line, sizeof line, fp) != NULL; lineno++) { n = sscanf(line, "%s %s %s %s", file, section, dest, src); if (n == 0) continue; if (n < 3) { fprintf(stderr, "%s: %s line %d: " "gfarm-URL, fragment-name and dest-node " "are required, skip this line\n", program_name, fragment_dest_list, lineno); continue; } else if (n > 4) { fprintf(stderr, "%s: %s line %d: " "there are more than 4 fields, ignore extras\n", program_name, fragment_dest_list, lineno); } if (replication_job_list_add(&job_list, file, section, n > 3 ? src : src_default, dest)) error_happend = 1; } fclose(fp); return (error_happend | replication_job_list_execute(&job_list)); } int jobs_by_pairs(struct replication_job_list *job_list, char *gfarm_url, int npairs, gfarm_stringlist *src_nodes, gfarm_stringlist *dst_nodes) { int i, j, k, error_happend = 0; char *e, *gfarm_file, *src_host, *dst_host; int nfragments, ncopies; struct gfarm_file_section_copy_info *copies; char section[GFARM_INT32STRLEN]; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: cannot determine pathname for %s: %s\n", program_name, gfarm_url, e); return (error_happend); } e = gfarm_url_fragment_number(gfarm_url, &nfragments); if (e != NULL) { fprintf(stderr, "%s: %s: cannot get fragment number: %s\n", program_name, gfarm_url, e); return (error_happend); } for (i = 0; i < nfragments; i++) { sprintf(section, "%d", i); e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) { fprintf(stderr, "%s: %s:%s: cannot get replica location: %s\n", program_name, gfarm_url, section, e); continue; } for (j = 0; j < npairs; j++) { src_host = gfarm_stringlist_elem(src_nodes, j); dst_host = gfarm_stringlist_elem(dst_nodes, j); for (k = 0; k < ncopies; k++) { if(strcasecmp(copies[k].hostname,src_host)==0){ #if 0 printf("%s %s %s %s\n", gfarm_url, section, dst_host, src_host); #else if (replication_job_list_add(job_list, gfarm_url, section, src_host, dst_host)) error_happend = 1; #endif goto found; } } } fprintf(stderr, "%s: error: %s:%s - no replica is found\n", program_name, gfarm_url, section); found: gfarm_file_section_copy_info_free_all(ncopies, copies); } return (error_happend); } void pairlist_read(char *pair_list, int *npairsp, gfarm_stringlist *src_nodes, gfarm_stringlist *dst_nodes) { char *e, *s; int npairs, lineno, n; FILE *fp; char line[LINELEN], src[LINELEN], dst[LINELEN]; e = gfarm_stringlist_init(src_nodes); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(dst_nodes); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } if ((fp = fopen(pair_list, "r")) == NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, pair_list, strerror(errno)); exit(EXIT_FAILURE); } npairs = 0; for (lineno = 1; fgets(line, sizeof line, fp) != NULL; lineno++) { /* remove comment */ s = strchr(line, '#'); if (s != NULL) *s = '\0'; n = sscanf(line, "%s %s\n", src, dst); if (n == 0) continue; if (n != 2) { fprintf(stderr, "%s: %s line %d: field number is not 2\n", program_name, pair_list, lineno); exit(EXIT_FAILURE); } e = gfarm_host_get_canonical_name(src, &s); if (e != NULL) { fprintf(stderr, "%s: %s isn't a filesystem node: %s\n", program_name, src, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(src_nodes, s); if (e != NULL) { fprintf(stderr, "%s: string %s: %s\n", program_name, src, e); exit(EXIT_FAILURE); } e = gfarm_host_get_canonical_name(dst, &s); if (e != NULL) { fprintf(stderr, "%s: %s isn't a filesystem node: %s\n", program_name, dst, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(dst_nodes, s); if (e != NULL) { fprintf(stderr, "%s: string %s: %s\n", program_name, dst, e); exit(EXIT_FAILURE); } npairs++; } fclose(fp); *npairsp = npairs; } void usage() { fprintf(stderr, "Usage: %s [option] <gfarm_url>...\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-b\t\t\tuse bootstrap mode\n"); fprintf(stderr, "\t-v\t\t\tverbose message\n"); fprintf(stderr, "\t-H <hostfile>\t\treplicate a whole file\n"); fprintf(stderr, "\t-D <domainname>\t\treplicate a whole file\n"); fprintf(stderr, "\t-I fragment-index\treplicate a fragment" " with -d option\n"); fprintf(stderr, "\t-s src-node\n"); fprintf(stderr, "\t-d dest-node\n"); fprintf(stderr, "\t-l <fragment-dest-list-file>\n"); fprintf(stderr, "\t-P <host-pair-file>\n"); exit(EXIT_FAILURE); } void conflict_check(int *mode_ch_p, int ch) { if (*mode_ch_p) { fprintf(stderr, "%s: -%c option conflicts with -%c\n", program_name, ch, *mode_ch_p); usage(); } *mode_ch_p = ch; } int main(argc, argv) int argc; char **argv; { char *e, *file; int i, ch, mode_ch = 0; gfarm_stringlist paths; gfs_glob_t types; int error_happened = 1; char *hostfile = NULL, *domainname = NULL, *index = NULL; char *src = NULL, *dest = NULL, *fragment_dest_list = NULL; char *pair_list = NULL; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "bvH:D:I:s:d:l:P:")) != -1) { switch (ch) { case 'b': bootstrap_method = 1; break; case 'v': verbose = 1; break; case 'H': hostfile = optarg; conflict_check(&mode_ch, ch); break; case 'D': domainname = optarg; conflict_check(&mode_ch, ch); break; case 'I': index = optarg; conflict_check(&mode_ch, ch); break; case 's': src = optarg; break; case 'd': dest = optarg; break; case 'l': fragment_dest_list = optarg; conflict_check(&mode_ch, ch); break; case 'P': pair_list = optarg; conflict_check(&mode_ch, ch); break; case '?': default: usage(); } } argc -= optind; argv += optind; if (bootstrap_method) gfarm_replication_set_method( GFARM_REPLICATION_BOOTSTRAP_METHOD); if (src != NULL && (hostfile != NULL || domainname != NULL || pair_list != NULL)) { fprintf(stderr, "%s: warning: -s src option is ignored with -%c option\n", program_name, mode_ch); } if (dest != NULL && mode_ch != 'I' && mode_ch != 0) { fprintf(stderr, "%s: warning: -d dest option is ignored with -%c option\n", program_name, mode_ch); } if (argc == 0 && fragment_dest_list == NULL) usage(); e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); if (hostfile != NULL) { char **hosttab; int nhosts, error_line; /* replicate a whole file */ e = gfarm_hostlist_read(hostfile, &nhosts, &hosttab, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: line %d: %s\n", hostfile, error_line, e); else fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); e = gfarm_url_fragments_replicate(file, nhosts, hosttab); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, file, e); error_happened = 1; } } } else if (domainname != NULL) { /* replicate a whole file */ for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); e= gfarm_url_fragments_replicate_to_domainname( file, domainname); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, file, e); error_happened = 1; } } } else if (fragment_dest_list != NULL) { /* replicate specified fragments */ if (bootstrap_method) { fprintf(stderr, "%s: -l option isn't supported " "on bootstrap mode\n", program_name); /* It's easy to support this, but probably too slow */ usage(); exit(EXIT_FAILURE); } error_happened = replicate_by_fragment_dest_list(fragment_dest_list, src); } else if (pair_list != NULL) { int npairs; gfarm_stringlist src_nodes, dst_nodes; struct replication_job_list job_list; pairlist_read(pair_list, &npairs, &src_nodes, &dst_nodes); replication_job_list_init(&job_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); if (verbose) fprintf(stderr, "%s: scan fragments for %s\n", program_name, file); if (jobs_by_pairs(&job_list, file, npairs, &src_nodes, &dst_nodes)) error_happened = 1; } if (replication_job_list_execute(&job_list)) error_happened = 1; } else { /* -I may be omitted */ struct replication_job_list job_list; /* replicate specified fragments */ if (dest == NULL) { fprintf(stderr, "%s: -d dest-node option is required\n", program_name); usage(); exit(EXIT_FAILURE); } replication_job_list_init(&job_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { char *section = index; file = gfarm_stringlist_elem(&paths, i); if (index == NULL) { /* * Special case for replicating a Gfarm * file having only one fragment */ int nfrags; e = gfarm_url_fragment_number(file, &nfrags); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, file, e); continue; } if (nfrags != 1) { fprintf(stderr, "%s: %s has more than " "one fragments, skipped\n", program_name, file); continue; } /* XXX program case */ section = "0"; /* assume -I 0 */ } if (replication_job_list_add(&job_list, file, section, src, dest)) error_happened = 1; } if (replication_job_list_execute(&job_list)) error_happened = 1; } gfs_glob_free(&types); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } return (error_happened); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfsl/scarg.c #include <stdio.h> #include <string.h> #include <unistd.h> #include <gssapi.h> #include <gfarm/gfarm_misc.h> #include "gfarm_gsi.h" #include "misc.h" #include "scarg.h" int port = 0; int acceptorSpecified = 0; gss_name_t acceptorName = GSS_C_NO_NAME; int HandleCommonOptions(option, arg) int option; char *arg; { int tmp; OM_uint32 majStat; OM_uint32 minStat; switch (option) { case 'p': if (gfarmGetInt(arg, &tmp) < 0) { fprintf(stderr, "illegal port number.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "port number must be > 0.\n"); return -1; } else if (tmp > 65535) { fprintf(stderr, "port number must be < 65536.\n"); return -1; } port = tmp; break; case 'H': if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NT_HOSTBASED_SERVICE, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; case 'M': /* mechanism specific name */ if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NO_OID, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; case 'N': acceptorName = GSS_C_NO_NAME; acceptorSpecified = 1; break; case 'n': if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NT_USER_NAME, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; case 'U': if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NT_STRING_UID_NAME, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; case 'X': /* This isn't guaranteed to work */ if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NT_EXPORT_NAME, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; case 'u': arg = getenv("USER"); if (arg == NULL) arg = getenv("LOGNAME"); if (arg == NULL) { fprintf(stderr, "neither $USER nor $LOGNAME isn't set"); return -1; } if (gfarmGssImportName(&acceptorName, arg, strlen(arg), GSS_C_NT_USER_NAME, &majStat, &minStat) < 0) { gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return -1; } acceptorSpecified = 1; break; default: fprintf(stderr, "error happens at an option\n"); return -1; } return 0; } char * newStringOfName(inputName) const gss_name_t inputName; { OM_uint32 majStat, minStat; char *s = gfarmGssNewDisplayName(inputName, &majStat, &minStat, NULL); if (s != NULL) { return s; } fprintf(stderr, "cannot convert gss_name_t to display string:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return strdup("(invalid gss_name_t)"); } char * newStringOfCredential(cred) gss_cred_id_t cred; { OM_uint32 majStat, minStat; gss_name_t name; char *s; if (gfarmGssNewCredentialName(&name, cred, &majStat, &minStat) > 0) { s = newStringOfName(name); gfarmGssDeleteName(&name, NULL, NULL); return s; } fprintf(stderr, "cannot convert credential to gss_name_t:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return strdup("(invalid credential)"); } <file_sep>/gfarmfs-fuse/trunk/contrib/gfarmfs-exec/Makefile.am bin_SCRIPTS = gfarmfs-exec.sh EXTRA_DIST = $(bin_SCRIPTS) <file_sep>/gfarm_samba/trunk/msgno/msgno.h #define GFARM_MSG_3000001 3000001 #define GFARM_MSG_3000002 3000002 #define GFARM_MSG_3000003 3000003 #define GFARM_MSG_3000004 3000004 #define GFARM_MSG_3000005 3000005 #define GFARM_MSG_3000006 3000006 #define GFARM_MSG_3000007 3000007 #define GFARM_MSG_3000008 3000008 #define GFARM_MSG_3000009 3000009 #define GFARM_MSG_3000010 3000010 #define GFARM_MSG_3000011 3000011 #define GFARM_MSG_3000012 3000012 #define GFARM_MSG_3000013 3000013 #define GFARM_MSG_3000014 3000014 #define GFARM_MSG_3000015 3000015 #define GFARM_MSG_3000016 3000016 #define GFARM_MSG_3000017 3000017 #define GFARM_MSG_3000018 3000018 #define GFARM_MSG_3000019 3000019 #define GFARM_MSG_3000020 3000020 #define GFARM_MSG_3000021 3000021 #define GFARM_MSG_3000022 3000022 #define GFARM_MSG_3000023 3000023 #define GFARM_MSG_3000024 3000024 #define GFARM_MSG_3000025 3000025 #define GFARM_MSG_3000026 3000026 #define GFARM_MSG_3000027 3000027 #define GFARM_MSG_3000028 3000028 #define GFARM_MSG_3000029 3000029 #define GFARM_MSG_3000030 3000030 #define GFARM_MSG_3000031 3000031 #define GFARM_MSG_3000032 3000032 #define GFARM_MSG_3000033 3000033 #define GFARM_MSG_3000034 3000034 #define GFARM_MSG_3000035 3000035 #define GFARM_MSG_3000036 3000036 #define GFARM_MSG_3000037 3000037 #define GFARM_MSG_3000038 3000038 #define GFARM_MSG_3000039 3000039 #define GFARM_MSG_3000040 3000040 #define GFARM_MSG_3000041 3000041 #define GFARM_MSG_3000042 3000042 #define GFARM_MSG_3000043 3000043 #define GFARM_MSG_3000044 3000044 #define GFARM_MSG_3000045 3000045 #define GFARM_MSG_3000046 3000046 #define GFARM_MSG_3000047 3000047 #define GFARM_MSG_3000048 3000048 #define GFARM_MSG_3000049 3000049 #define GFARM_MSG_3000050 3000050 #define GFARM_MSG_3000051 3000051 #define GFARM_MSG_3000052 3000052 #define GFARM_MSG_3000053 3000053 #define GFARM_MSG_3000054 3000054 #define GFARM_MSG_3000055 3000055 #define GFARM_MSG_3000056 3000056 #define GFARM_MSG_3000057 3000057 #define GFARM_MSG_3000058 3000058 #define GFARM_MSG_3000059 3000059 #define GFARM_MSG_3000060 3000060 #define GFARM_MSG_3000061 3000061 #define GFARM_MSG_3000062 3000062 #define GFARM_MSG_3000063 3000063 #define GFARM_MSG_3000064 3000064 #define GFARM_MSG_3000065 3000065 #define GFARM_MSG_3000066 3000066 #define GFARM_MSG_3000067 3000067 #define GFARM_MSG_3000068 3000068 #define GFARM_MSG_3000069 3000069 #define GFARM_MSG_3000070 3000070 #define GFARM_MSG_3000071 3000071 #define GFARM_MSG_3000072 3000072 #define GFARM_MSG_3000073 3000073 #define GFARM_MSG_3000074 3000074 #define GFARM_MSG_3000075 3000075 #define GFARM_MSG_3000076 3000076 #define GFARM_MSG_3000077 3000077 #define GFARM_MSG_3000078 3000078 #define GFARM_MSG_3000079 3000079 #define GFARM_MSG_3000080 3000080 #define GFARM_MSG_3000081 3000081 #define GFARM_MSG_3000082 3000082 #define GFARM_MSG_3000083 3000083 #define GFARM_MSG_3000084 3000084 #define GFARM_MSG_3000085 3000085 #define GFARM_MSG_3000086 3000086 #define GFARM_MSG_3000087 3000087 #define GFARM_MSG_3000088 3000088 #define GFARM_MSG_3000089 3000089 #define GFARM_MSG_3000090 3000090 #define GFARM_MSG_3000091 3000091 #define GFARM_MSG_3000092 3000092 #define GFARM_MSG_3000093 3000093 #define GFARM_MSG_3000094 3000094 #define GFARM_MSG_3000095 3000095 #define GFARM_MSG_3000096 3000096 #define GFARM_MSG_3000097 3000097 #define GFARM_MSG_3000098 3000098 #define GFARM_MSG_3000099 3000099 #define GFARM_MSG_3000100 3000100 #define GFARM_MSG_3000101 3000101 #define GFARM_MSG_3000102 3000102 #define GFARM_MSG_3000103 3000103 #define GFARM_MSG_3000104 3000104 #define GFARM_MSG_3000105 3000105 #define GFARM_MSG_3000106 3000106 #define GFARM_MSG_3000107 3000107 #define GFARM_MSG_3000108 3000108 #define GFARM_MSG_3000109 3000109 #define GFARM_MSG_3000110 3000110 #define GFARM_MSG_3000111 3000111 #define GFARM_MSG_3000112 3000112 #define GFARM_MSG_3000113 3000113 #define GFARM_MSG_3000114 3000114 #define GFARM_MSG_3000115 3000115 #define GFARM_MSG_3000116 3000116 #define GFARM_MSG_3000117 3000117 #define GFARM_MSG_3000118 3000118 #define GFARM_MSG_3000119 3000119 #define GFARM_MSG_3000120 3000120 #define GFARM_MSG_3000121 3000121 #define GFARM_MSG_3000122 3000122 #define GFARM_MSG_3000123 3000123 #define GFARM_MSG_3000124 3000124 #define GFARM_MSG_3000125 3000125 #define GFARM_MSG_3000126 3000126 #define GFARM_MSG_3000127 3000127 #define GFARM_MSG_3000128 3000128 #define GFARM_MSG_3000129 3000129 #define GFARM_MSG_3000130 3000130 #define GFARM_MSG_3000131 3000131 #define GFARM_MSG_3000132 3000132 #define GFARM_MSG_3000133 3000133 #define GFARM_MSG_3000134 3000134 #define GFARM_MSG_3000135 3000135 #define GFARM_MSG_3000136 3000136 #define GFARM_MSG_3000137 3000137 #define GFARM_MSG_3000138 3000138 #define GFARM_MSG_3000139 3000139 #define GFARM_MSG_3000140 3000140 #define GFARM_MSG_3000141 3000141 #define GFARM_MSG_3000142 3000142 #define GFARM_MSG_3000143 3000143 #define GFARM_MSG_3000144 3000144 #define GFARM_MSG_3000145 3000145 #define GFARM_MSG_3000146 3000146 #define GFARM_MSG_3000147 3000147 #define GFARM_MSG_3000148 3000148 #define GFARM_MSG_3000149 3000149 #define GFARM_MSG_3000150 3000150 #define GFARM_MSG_3000151 3000151 #define GFARM_MSG_3000152 3000152 #define GFARM_MSG_3000153 3000153 #define GFARM_MSG_3000154 3000154 #define GFARM_MSG_3000155 3000155 #define GFARM_MSG_3000156 3000156 #define GFARM_MSG_3000157 3000157 #define GFARM_MSG_3000158 3000158 #define GFARM_MSG_3000159 3000159 #define GFARM_MSG_3000160 3000160 #define GFARM_MSG_3000161 3000161 #define GFARM_MSG_3000162 3000162 #define GFARM_MSG_3000163 3000163 #define GFARM_MSG_3000164 3000164 #define GFARM_MSG_3000165 3000165 #define GFARM_MSG_3000166 3000166 #define GFARM_MSG_3000167 3000167 #define GFARM_MSG_3000168 3000168 #define GFARM_MSG_3000169 3000169 #define GFARM_MSG_3000170 3000170 #define GFARM_MSG_3000171 3000171 #define GFARM_MSG_3000172 3000172 #define GFARM_MSG_3000173 3000173 #define GFARM_MSG_3000174 3000174 #define GFARM_MSG_3000175 3000175 #define GFARM_MSG_3000176 3000176 #define GFARM_MSG_3000177 3000177 #define GFARM_MSG_3000178 3000178 #define GFARM_MSG_3000179 3000179 #define GFARM_MSG_3000180 3000180 #define GFARM_MSG_3000181 3000181 #define GFARM_MSG_3000182 3000182 #define GFARM_MSG_3000183 3000183 #define GFARM_MSG_3000184 3000184 #define GFARM_MSG_3000185 3000185 #define GFARM_MSG_3000186 3000186 #define GFARM_MSG_3000187 3000187 #define GFARM_MSG_3000188 3000188 #define GFARM_MSG_3000189 3000189 #define GFARM_MSG_3000190 3000190 #define GFARM_MSG_3000191 3000191 #define GFARM_MSG_3000192 3000192 #define GFARM_MSG_3000193 3000193 #define GFARM_MSG_3000194 3000194 #define GFARM_MSG_3000195 3000195 #define GFARM_MSG_3000196 3000196 #define GFARM_MSG_3000197 3000197 #define GFARM_MSG_3000198 3000198 #define GFARM_MSG_3000199 3000199 #define GFARM_MSG_3000200 3000200 #define GFARM_MSG_3000201 3000201 #define GFARM_MSG_3000202 3000202 #define GFARM_MSG_3000203 3000203 #define GFARM_MSG_3000204 3000204 #define GFARM_MSG_3000205 3000205 #define GFARM_MSG_3000206 3000206 #define GFARM_MSG_3000207 3000207 #define GFARM_MSG_3000208 3000208 #define GFARM_MSG_3000209 3000209 <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_0_rc2/replicate.c /* * $Id$ */ #include "config.h" #ifdef HAVE_PRIVATE_SRCS /* replace replicate.c with replicate_private.c */ #include "replicate_private.c" #else /* ! HAVE_PRIVATE_SRCS */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <libgen.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> /* * fuse.h requres that _FILE_OFFSET_BITS is defined in any case, but * AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 * since it is not necessary. To avoid this problem we define it here. */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #define FUSE_USE_VERSION 25 #include <fuse.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include <gfarm2fs.h> #include "gfarm2fs_msg_enums.h" static char *rep = "gfrep"; static int replicate_ncopy; static int replicate_max_concurrency; volatile sig_atomic_t replicate_concurrency = 0; static int replicate_enabled; #define XATTR_NCOPY "gfarm.ncopy" static void sigchld_handler(int sig) { int pid, status, no; char *msg; for (;;) { pid = waitpid(-1, &status, WNOHANG); if (pid == -1 || pid == 0) break; --replicate_concurrency; if (WIFEXITED(status)) { msg = "exit"; no = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { msg = "killed by signal"; no = WTERMSIG(status); } else { msg = "unknown status"; no = status; } gflog_info(GFARM_MSG_2000041, "replicate [%d]: %s %d", pid, msg, no); } } void gfarm2fs_replicate_init(struct gfarm2fs_param *param) { struct sigaction sa; if (param->ncopy <= 0 || param->copy_limit <= 0) return; replicate_enabled = 1; replicate_ncopy = param->ncopy; replicate_max_concurrency = param->copy_limit; sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_NOCLDSTOP; sigaction(SIGCHLD, &sa, NULL); } void gfarm2fs_replicate_final(void) { /* Do nothing */ } static int gfarm2fs_replicate_ncopy(const char *path) { int ncopy = replicate_ncopy; #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) char *p, *ep, s_ncopy[GFARM_INT32STRLEN]; size_t size_ncopy; gfarm_error_t e; int nc; p = strdup(path); if (p == NULL) return (ncopy); for (;;) { size_ncopy = sizeof(s_ncopy); e = gfs_getxattr(p, XATTR_NCOPY, s_ncopy, &size_ncopy); if (e == GFARM_ERR_NO_ERROR) { s_ncopy[size_ncopy] = '\0'; nc = strtol(s_ncopy, &ep, 10); if (*ep == '\0') { ncopy = nc; break; } } if (p[0] == '/' && p[1] == '\0') break; p = dirname(p); } free(p); #endif return (ncopy); } static int gfarm2fs_replicate_stat_ncopy(const char *path) { struct gfs_stat st; gfarm_error_t e; int ncopy; e = gfs_lstat_cached(path, &st); if (e == GFARM_ERR_NO_ERROR) { ncopy = st.st_ncopy; gfs_stat_free(&st); return (ncopy); } return (0); } void gfarm2fs_replicate(const char *path, struct fuse_file_info *fi) { char str_ncopy[GFARM_INT32STRLEN]; int ncopy; if (!replicate_enabled) return; /* if necessary number of copies is less than 2, return */ ncopy = gfarm2fs_replicate_ncopy(path); if (ncopy < 2) return; /* * if it is opened in read only mode and it has enough number * of copies, return */ if (fi != NULL && (fi->flags & O_ACCMODE) == O_RDONLY && ncopy <= gfarm2fs_replicate_stat_ncopy(path)) return; /* if enough number of replication processes are in process, wait */ while (replicate_concurrency >= replicate_max_concurrency) sleep(1); snprintf(str_ncopy, sizeof(str_ncopy), "%d", ncopy); switch (fork()) { case 0: gflog_info(GFARM_MSG_2000042, "replicate [%d]: path %s ncopy %s", getpid(), path, str_ncopy); execlp(rep, rep, "-q", "-N", str_ncopy, path, NULL); gflog_error_errno(GFARM_MSG_2000043, "failed to exec %s", rep); _exit(1); case -1: gflog_error_errno(GFARM_MSG_2000044, "fork"); break; default: ++replicate_concurrency; break; } } #endif /* HAVE_PRIVATE_SRCS */ <file_sep>/gfarm/branches/metadb_dev/bench/thput-pvfs/thput-pvfs.c /* * $Id$ */ #include <assert.h> #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <pvfs.h> double timerval_calibration; #ifdef i386 typedef unsigned long long timerval_t; unsigned long long get_cycles(void) { unsigned long long rv; __asm __volatile("rdtsc" : "=A" (rv)); return (rv); } #define gettimerval(tp) (*(tp) = get_cycles()) #define timerval_second(tp) (*(tp) * timerval_calibration) #define timerval_sub(t1p, t2p) ((*(t1p) - *(t2p)) * timerval_calibration) void timerval_calibrate(void) { timerval_t t1, t2; struct timeval s1, s2; gettimerval(&t1); gettimeofday(&s1, NULL); sleep(10); gettimerval(&t2); gettimeofday(&s2, NULL); timerval_calibration = (t2 - t1) / ( (s2.tv_sec - s1.tv_sec) + (s2.tv_usec - s1.tv_usec) * .000001); timerval_calibration = 1.0 / timerval_calibration; } #else /* gettimeofday */ typedef struct timeval timerval_t; #define gettimerval(t1) gettimeofday(t1, NULL) #define timerval_second(t1) ((double)(t1)->tv_sec \ + (double)(t1)->tv_usec * .000001) #define timerval_sub(t1, t2) \ (((double)(t1)->tv_sec - (double)(t2)->tv_sec) \ + ((double)(t1)->tv_usec - (double)(t2)->tv_usec) * .000001) void timerval_calibrate(void) { timerval_calibration = 1.0; } #endif int tm_write_write_measured = 0; timerval_t tm_write_open_0, tm_write_open_1; timerval_t tm_write_write_0, tm_write_write_1; timerval_t tm_write_close_0, tm_write_close_1; int tm_read_read_measured = 0; timerval_t tm_read_open_0, tm_read_open_1; timerval_t tm_read_read_0, tm_read_read_1; timerval_t tm_read_close_0, tm_read_close_1; #define ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0])) #define MAX_BUFFER_SIZE_NUMBER 32 #define MAX_BUFFER_SIZE (8*1024*1024) #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 256 #endif char buffer[MAX_BUFFER_SIZE]; static struct pvfs_filestat _pstat; static char _hname[MAXHOSTNAMELEN]; void initbuffer(void) { int i; for (i = 0; i < MAX_BUFFER_SIZE; i++) buffer[i] = i; } void writetest(char *ofile, int buffer_size, off_t file_size) { int fd, rv; off_t residual; gettimerval(&tm_write_open_0); fd = pvfs_open(ofile, O_CREAT|O_TRUNC|O_WRONLY|O_META, 0666, &_pstat); gettimerval(&tm_write_open_1); if (fd == -1) { perror(ofile); exit(1); } pvfs_ioctl(fd, GETMETA, &_pstat); for (residual = file_size; residual > 0; residual -= rv) { if (!tm_write_write_measured) { tm_write_write_measured = 1; gettimerval(&tm_write_write_0); rv = pvfs_write(fd, buffer, buffer_size <= residual ? buffer_size : residual); gettimerval(&tm_write_write_1); } else { rv = pvfs_write(fd, buffer, buffer_size <= residual ? buffer_size : residual); } if (rv == -1) { perror("write test"); break; } assert(rv == (buffer_size <= residual ? buffer_size : residual)); } if (residual > 0) { fprintf(stderr, "write test failed, residual = %ld\n", (long)residual); } gettimerval(&tm_write_close_0); rv = pvfs_close(fd); gettimerval(&tm_write_close_1); if (rv == -1) perror("write test close failed"); } void readtest(char *ifile, int buffer_size, off_t file_size) { int fd, rv; off_t residual; gettimerval(&tm_read_open_0); fd = pvfs_open(ifile, O_RDONLY); gettimerval(&tm_read_open_1); if (fd == -1) { perror(ifile); exit(1); } for (residual = file_size; residual > 0; residual -= rv) { if (!tm_read_read_measured) { tm_read_read_measured = 1; gettimerval(&tm_read_read_0); rv = pvfs_read(fd, buffer, buffer_size <= residual ? buffer_size : residual); gettimerval(&tm_read_read_1); } else { rv = pvfs_read(fd, buffer, buffer_size <= residual ? buffer_size : residual); } if (rv == 0) break; if (rv == -1) { perror("read test"); break; } assert(rv == buffer_size || rv == residual); } if (residual > 0) { fprintf(stderr, "read test failed, residual = %ld\n", (long)residual); } gettimerval(&tm_read_close_0); rv = pvfs_close(fd); gettimerval(&tm_read_close_1); if (rv == -1) perror("read test closed failed"); } void copytest(char *ifile, char *ofile, int buffer_size, off_t file_size) { int ifd, ofd; int rv, osize; off_t residual; ifd = pvfs_open(ifile, O_RDONLY); if (ifd == -1) { perror(ifile); exit(1); } ofd = pvfs_open(ofile, O_CREAT|O_TRUNC|O_WRONLY|O_META, 0666, &_pstat); if (ofd == -1) { perror(ofile); exit(1); } pvfs_ioctl(ofd, GETMETA, &_pstat); for (residual = file_size; residual > 0; residual -= rv) { rv = pvfs_read(ifd, buffer, buffer_size <= residual ? buffer_size : residual); if (rv == 0) break; if (rv == -1) { perror("copytest read"); break; } assert(rv == buffer_size || rv == residual); osize = rv; rv = pvfs_write(ofd, buffer, osize); if (rv == -1) { perror("copytest write"); break; } assert(rv == osize); } if (residual > 0) { fprintf(stderr, "copy test failed, residual = %ld\n", (long)residual); } if (pvfs_close(ofd) == -1) perror("copy test write close failed"); if (pvfs_close(ifd) == -1) perror("copy test read close failed"); } double timeval_sub(struct timeval *t1, struct timeval *t2) { return ((t1->tv_sec + t1->tv_usec * .000001) - (t2->tv_sec + t2->tv_usec * .000001)); } #define TESTMODE_WRITE 1 #define TESTMODE_READ 2 #define TESTMODE_COPY 4 #define FLAG_DONT_REMOVE 1 #define FLAG_MEASURE_PRIMITIVES 2 void test_title(int test_mode, off_t file_size, int flags) { fprintf(stdout, "testing with %d MB file\n", (int)file_size); printf("%-8s ", "hostname"); printf("%-8s", "bufsize"); if (test_mode & TESTMODE_WRITE) printf(" %12s", "write [MB/s]"); if (test_mode & TESTMODE_READ) printf(" %12s", "read [MB/s]"); if (test_mode & TESTMODE_COPY) printf(" %12s", "copy [MB/s]"); printf(" (#iods / base / ssize)"); printf("\n"); fflush(stdout); if ((flags & FLAG_MEASURE_PRIMITIVES) != 0 && (test_mode & (TESTMODE_WRITE|TESTMODE_READ)) != 0) fprintf(stderr, "timer/sec=%g\n", 1.0 / timerval_calibration); } void test(int test_mode, char *file1, char *file2, int buffer_size, off_t file_size, int flags) { struct timeval t1, t2, t3, t4; if ((flags & FLAG_DONT_REMOVE) == 0) { if (test_mode & TESTMODE_WRITE) pvfs_unlink(file1); if (test_mode & TESTMODE_COPY) pvfs_unlink(file2); } gettimeofday(&t1, NULL); if (test_mode & TESTMODE_WRITE) writetest(file1, buffer_size, file_size); gettimeofday(&t2, NULL); if (test_mode & TESTMODE_READ) readtest(file1,buffer_size, file_size); gettimeofday(&t3, NULL); if (test_mode & TESTMODE_COPY) copytest(file1, file2, buffer_size, file_size); gettimeofday(&t4, NULL); printf("%8s ", _hname); printf("%7d ", buffer_size); if (test_mode & TESTMODE_WRITE) printf(" %9.3f%3s", file_size / timeval_sub(&t2, &t1) * .000001, ""); if (test_mode & TESTMODE_READ) printf(" %9.3f%3s", file_size / timeval_sub(&t3, &t2) * .000001, ""); if (test_mode & TESTMODE_COPY) printf(" %9.3f%3s", file_size / timeval_sub(&t4, &t3) * .000001, ""); printf(" (%d / %d / %d)", _pstat.pcount, _pstat.base, _pstat.ssize); printf("\n"); fflush(stdout); if ((flags & FLAG_DONT_REMOVE) == 0) { if (test_mode & TESTMODE_WRITE) pvfs_unlink(file1); if (test_mode & TESTMODE_COPY) pvfs_unlink(file2); } if ((flags & FLAG_MEASURE_PRIMITIVES) != 0 && (test_mode & (TESTMODE_WRITE|TESTMODE_READ)) != 0) { fprintf(stderr, "%7d ", buffer_size); if (test_mode & TESTMODE_WRITE) fprintf(stderr, " %g %g %g", timerval_sub(&tm_write_open_1, &tm_write_open_0), timerval_sub(&tm_write_write_1, &tm_write_write_0), timerval_sub(&tm_write_close_1, &tm_write_close_0) ); if (test_mode & TESTMODE_READ) fprintf(stderr, " %g %g %g", timerval_sub(&tm_read_open_1, &tm_read_open_0), timerval_sub(&tm_read_read_1, &tm_read_read_0), timerval_sub(&tm_read_close_1, &tm_read_close_0) ); fprintf(stderr, "\n"); tm_write_write_measured = tm_read_read_measured = 0; } } /* * */ #ifndef PVFS_MOUNT #define PVFS_MOUNT "/pvfs" #endif /* PVFS_MOUNT */ int main(int argc, char **argv) { # define file_prefix "test.file" char bfile1[MAXHOSTNAMELEN + strlen(PVFS_MOUNT file_prefix) + 4]; char bfile2[MAXHOSTNAMELEN + strlen(PVFS_MOUNT file_prefix) + 4]; char *file1, *file2; int test_mode = 0; int c, i, buffer_sizec = 0, buffer_sizes[MAX_BUFFER_SIZE_NUMBER]; static int buffer_sizes_default[] = { 8 * 1024, 64 * 1024, 512 * 1024, 8 * 1024 * 1024, }; off_t file_size = 1024; int flags = 0; if (gethostname(_hname, MAXHOSTNAMELEN) == -1) { perror("gethostname"); exit(1); } sprintf(bfile1, "%s/%s1.%s", PVFS_MOUNT, file_prefix, _hname); sprintf(bfile2, "%s/%s2.%s", PVFS_MOUNT, file_prefix, _hname); file1 = bfile1; file2 = bfile2; _pstat.base = -1; _pstat.pcount = -1; _pstat.ssize = -1; _pstat.soff = 0; _pstat.bsize = 0; while ((c = getopt(argc, argv, "b:s:n:t:wrcmp")) != -1) { switch (c) { case 'b': if (buffer_sizec >= MAX_BUFFER_SIZE_NUMBER) { fprintf(stderr, "too many -b options (max %d)\n", MAX_BUFFER_SIZE_NUMBER); exit(1); } buffer_sizes[buffer_sizec] = strtol(optarg, NULL, 0); if (buffer_sizes[buffer_sizec] > MAX_BUFFER_SIZE) { fprintf(stderr, "-b: %d is too big\n", buffer_sizes[buffer_sizec]); exit(1); } buffer_sizec++; break; case 's': file_size = strtol(optarg, NULL, 0); break; case 'n': _pstat.pcount = strtol(optarg, NULL, 0); break; case 't': _pstat.ssize = strtol(optarg, NULL, 0); break; case 'w': test_mode |= TESTMODE_WRITE; break; case 'r': test_mode |= TESTMODE_READ; break; case 'c': test_mode |= TESTMODE_COPY; break; case 'm': flags |= FLAG_MEASURE_PRIMITIVES; timerval_calibrate(); break; case 'p': flags |= FLAG_DONT_REMOVE; break; case '?': default: fprintf(stderr, "Usage: thput-pvfs [options]" " [file1 [file2]]\n" "options:\n" "\t-n # of io nodes\n" "\t-t striping-size\n" "\t-b block-size\n" "\t-s file-size\n" "\t-w : write test\n" "\t-r : read test\n" "\t-c : copy test\n" "\t-p : don't remove\n"); exit(1); } } argc -= optind; argv += optind; if (argc > 0) file1 = argv[0]; if (argc > 1) file2 = argv[1]; if (test_mode == 0) test_mode = TESTMODE_WRITE|TESTMODE_READ|TESTMODE_COPY; test_title(test_mode, file_size, flags); file_size *= 1024 * 1024; initbuffer(); if (buffer_sizec == 0) { for (i = 0; i < ARRAY_LENGTH(buffer_sizes_default); i++) test(test_mode, file1, file2, buffer_sizes_default[i], file_size, flags); } else { for (i = 0; i < buffer_sizec; i++) test(test_mode, file1, file2, buffer_sizes[i], file_size, flags); } return (0); } <file_sep>/gfarmfs-fuse/trunk/test/fsystest.c /* * Filesystem tests * * This program is based on test.c from FUSE project. * http://fuse.cvs.sourceforge.net/fuse/fuse/test/ */ #if defined(__linux__) && !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #include <stdio.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <utime.h> #include <errno.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <stdlib.h> #include <signal.h> #ifndef __GNUC__ # define __attribute__(a) #endif #define FILE1 "./__testfile1" #define FILE2 "./__testfile2" #define DIR1 "./__testdir1" #define DIR2 "./__testdir2" static char *testfile; static char *testfile2; static char *testdir; static char *testdir2; static char testname[256]; static char testdata[] = "abcdefghijklmnopqrstuvwxyz"; static char testdata2[] = "1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./"; static const char *testdir_files[] = { "f1", "f2", NULL}; static char zerodata[4096]; static int testdatalen = sizeof(testdata) - 1; static int testdata2len = sizeof(testdata2) - 1; #define MAX_ENTRIES 1024 static void test_perror(const char *func, const char *msg) { fprintf(stdout, "NG [%s] %s(): %s: %s\n", testname, func, msg, strerror(errno)); } static void test_error(const char *func, const char *msg, ...) __attribute__ ((format (printf, 2, 3))); static void start_test(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); static void test_error(const char *func, const char *msg, ...) { va_list ap; fprintf(stdout, "NG [%s] %s(): ", testname, func); va_start(ap, msg); vfprintf(stdout, msg, ap); va_end(ap); fprintf(stdout, "\n"); } static void success(void) { fprintf(stdout, "OK [%s]\n", testname); } static void start_test(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsprintf(testname, fmt, ap); va_end(ap); } #if 0 /* This feature is not supported by Sun Forte Developer 7 C 5.4 */ #define PERROR(msg) test_perror(__func__, msg) #define ERROR(msg, args...) test_error(__func__, msg, ##args) #endif static int check_size(const char *path, int len) { static char func[] = "check_size"; struct stat stbuf; int res = stat(path, &stbuf); if (res == -1) { test_perror(func, "stat"); return -1; } if (stbuf.st_size != len) { test_error(func, "length %u instead of %u", (int) stbuf.st_size, (int) len); return -1; } return 0; } static int check_type(const char *path, mode_t type) { static char func[] = "check_type"; struct stat stbuf; int res = lstat(path, &stbuf); if (res == -1) { test_perror(func, "lstat"); return -1; } if ((stbuf.st_mode & S_IFMT) != type) { test_error(func, "type 0%o instead of 0%o", stbuf.st_mode & S_IFMT, type); return -1; } return 0; } static int check_mode(const char *path, mode_t mode) { static char func[] = "check_mode"; struct stat stbuf; int res = lstat(path, &stbuf); if (res == -1) { test_perror(func, "lstat"); return -1; } if ((stbuf.st_mode & 07777) != mode) { test_error(func, "mode 0%o instead of 0%o", stbuf.st_mode & 07777, mode); return -1; } return 0; } static int check_times(const char *path, time_t atime, time_t mtime) { static char func[] = "check_times"; int err = 0; struct stat stbuf; int res = lstat(path, &stbuf); if (res == -1) { test_perror(func, "lstat"); return -1; } if (stbuf.st_atime != atime) { test_error(func, "different atime"); err--; } if (stbuf.st_mtime != mtime) { test_error(func, "different mtime"); err--; } if (err) return -1; return 0; } static int check_nlink(const char *path, nlink_t nlink) { static char func[] = "check_nlink"; struct stat stbuf; int res = lstat(path, &stbuf); if (res == -1) { test_perror(func, "lstat"); return -1; } if (stbuf.st_nlink != nlink) { test_error(func, "nlink %i instead of %i", stbuf.st_nlink, nlink); return -1; } return 0; } static int check_nonexist(const char *path) { static char func[] = "check_nonexist"; struct stat stbuf; int res = lstat(path, &stbuf); if (res == 0) { test_error(func, "file should not exist"); return -1; } if (errno != ENOENT) { test_error(func, "file should not exist: %s", strerror(errno)); return -1; } return 0; } static int check_buffer(const char *buf, const char *data, unsigned len) { static char func[] = "check_buffer"; if (memcmp(buf, data, len) != 0) { test_error(func, "data mismatch"); return -1; } return 0; } #define check_data(p, d, o, l) do_check_data(p, #p, d, o, l) static int do_check_data(const char *path, const char *path_str, const char *data, int offset, unsigned len) { static char func[] = "do_check_data"; char buf[4096]; int res; int fd = open(path, O_RDONLY); if (fd == -1) { test_perror(func, "open"); return -1; } if (lseek(fd, offset, SEEK_SET) == (off_t) -1) { test_perror(func, "lseek"); close(fd); return -1; } while (len) { int rdlen = len < sizeof(buf) ? len : sizeof(buf); res = read(fd, buf, rdlen); if (res == -1) { test_perror(func, "read"); close(fd); return -1; } if (res != rdlen) { test_error(func, "%s: short read: %u instead of %u", path_str, res, rdlen); close(fd); return -1; } if (check_buffer(buf, data, rdlen) != 0) { close(fd); return -1; } data += rdlen; len -= rdlen; } res = close(fd); if (res == -1) { test_perror(func, "close"); return -1; } return 0; } static int check_dir_contents(const char *path, const char **contents) { static char func[] = "check_dir_contents"; int i; int res; int err = 0; int found[MAX_ENTRIES]; const char *cont[MAX_ENTRIES]; DIR *dp; for (i = 0; contents[i]; i++) { assert(i < MAX_ENTRIES - 3); found[i] = 0; cont[i] = contents[i]; } found[i] = 0; cont[i++] = "."; found[i] = 0; cont[i++] = ".."; cont[i] = NULL; dp = opendir(path); if (dp == NULL) { test_perror(func, "opendir"); return -1; } memset(found, 0, sizeof(found)); while(1) { struct dirent *de; errno = 0; de = readdir(dp); if (de == NULL) { if (errno) { test_perror(func, "readdir"); closedir(dp); return -1; } break; } for (i = 0; cont[i] != NULL; i++) { assert(i < MAX_ENTRIES); if (strcmp(cont[i], de->d_name) == 0) { if (found[i]) { test_error(func, "duplicate entry <%s>", de->d_name); err--; } else found[i] = 1; break; } } if (!cont[i]) { test_error(func, "unexpected entry <%s>", de->d_name); err --; } } for (i = 0; cont[i] != NULL; i++) { if (!found[i]) { test_error(func, "missing entry <%s>", cont[i]); err--; } } res = closedir(dp); if (res == -1) { test_perror(func, "closedir"); return -1; } if (err) return -1; return 0; } static int create_file(const char *path, const char *data, int len) { static char func[] = "create_file"; int res; int fd; unlink(path); fd = creat(path, 0644); if (fd == -1) { test_perror(func, "creat"); return -1; } if (len) { res = write(fd, data, len); if (res == -1) { test_perror(func, "write"); close(fd); return -1; } if (res != len) { test_error(func, "write is short: %u instead of %u", res, len); close(fd); return -1; } } res = close(fd); if (res == -1) { test_perror(func, "close"); return -1; } res = check_type(path, S_IFREG); if (res == -1) return -1; res = check_mode(path, 0644); if (res == -1) return -1; res = check_nlink(path, 1); if (res == -1) return -1; res = check_size(path, len); if (res == -1) return -1; if (len) { res = check_data(path, data, 0, len); if (res == -1) return -1; } return 0; } static int cleanup_dir(const char *path, const char **dir_files, int quiet) { static char func[] = "cleanup_dir"; int i; int err = 0; for (i = 0; dir_files[i]; i++) { int res; char fpath[1024]; sprintf(fpath, "%s/%s", path, dir_files[i]); res = unlink(fpath); if (res == -1 && !quiet) { test_perror(func, "unlink"); err --; } } if (err) return -1; return 0; } static int create_dir(const char *path, const char **dir_files) { static char func[] = "create_dir"; int res; int i; rmdir(path); res = mkdir(path, 0755); if (res == -1) { test_perror(func, "mkdir"); return -1; } res = check_type(path, S_IFDIR); if (res == -1) return -1; res = check_mode(path, 0755); if (res == -1) return -1; for (i = 0; dir_files[i]; i++) { char fpath[1024]; sprintf(fpath, "%s/%s", path, dir_files[i]); res = create_file(fpath, "", 0); if (res == -1) { cleanup_dir(path, dir_files, 1); return -1; } } res = check_dir_contents(path, dir_files); if (res == -1) { cleanup_dir(path, dir_files, 1); return -1; } return 0; } static int test_truncate(int len) { static char func[] = "test_truncate"; const char *data = testdata; int datalen = testdatalen; int res; start_test("truncate(%u)", (int) len); res = create_file(testfile, data, datalen); if (res == -1) return -1; res = truncate(testfile, len); if (res == -1) { test_perror(func, "truncate"); return -1; } res = check_size(testfile, len); if (res == -1) return -1; if (len > 0) { if (len <= datalen) { res = check_data(testfile, data, 0, len); if (res == -1) return -1; } else { res = check_data(testfile, data, 0, datalen); if (res == -1) return -1; res = check_data(testfile, zerodata, datalen, len - datalen); if (res == -1) return -1; } } res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; success(); return 0; } #define test_ftruncate(l, m) test_ftruncate_common(l, m, 0, O_WRONLY, NULL, 0, NULL) #define test_open_truncate(f, m, l, e) test_ftruncate_common(l, m, 1, f, #f, e, #e) static int test_ftruncate_common(int len, int mode, int open_truncate, int flags, const char *flags_str, int err, const char *err_str) { char *func; static char f1[] = "test_ftruncate"; static char f2[] = "test_open_truncate"; const char *data = testdata; int datalen = testdatalen; int res; int fd; if (open_truncate) { start_test("open(%s) fchmod(0%03o) truncate(%u) errno=%s", flags_str, mode, len, err_str); func = f2; } else { start_test("ftruncate(%u) mode=0%03o", len, mode); func = f1; } res = create_file(testfile, data, datalen); if (res == -1) return -1; fd = open(testfile, flags); if (fd == -1) { test_perror(func, "open"); return -1; } res = fchmod(fd, mode); if (res == -1) { test_perror(func, "fchmod"); close(fd); return -1; } res = check_mode(testfile, mode); if (res == -1) { close(fd); return -1; } if (open_truncate) { res = truncate(testfile, len); if (res == -1 && err != errno) { test_perror(func, "truncate"); close(fd); return -1; } else if (res == 0 && err) { test_error(func, "truncate should have failed"); close(fd); return -1; } else if (err) { len = datalen; } } else { res = ftruncate(fd, len); if (res == -1) { test_perror(func, "ftruncate"); close(fd); return -1; } } close(fd); res = check_size(testfile, len); if (res == -1) return -1; if (len > 0) { if (len <= datalen) { res = check_data(testfile, data, 0, len); if (res == -1) return -1; } else { res = check_data(testfile, data, 0, datalen); if (res == -1) return -1; res = check_data(testfile, zerodata, datalen, len - datalen); if (res == -1) return -1; } } res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; success(); return 0; } static int test_utime(void) { static char func[] = "test_utime"; struct utimbuf utm; time_t atime = 987631200; time_t mtime = 123116400; int res; start_test("utime"); res = create_file(testfile, NULL, 0); if (res == -1) return -1; utm.actime = atime; utm.modtime = mtime; res = utime(testfile, &utm); if (res == -1) { test_perror(func, "utime"); return -1; } res = check_times(testfile, atime, mtime); if (res == -1) { return -1; } res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; success(); return 0; } static int test_create(void) { static char func[] = "test_create"; const char *data = testdata; int datalen = testdatalen; int err = 0; int res; int fd; start_test("create"); unlink(testfile); fd = creat(testfile, 0644); if (fd == -1) { test_perror(func, "creat"); return -1; } res = write(fd, data, datalen); if (res == -1) { test_perror(func, "write"); close(fd); return -1; } if (res != datalen) { test_error(func, "write is short: %u instead of %u", res, datalen); close(fd); return -1; } res = close(fd); if (res == -1) { test_perror(func, "close"); return -1; } res = check_type(testfile, S_IFREG); if (res == -1) return -1; err += check_mode(testfile, 0644); err += check_nlink(testfile, 1); err += check_size(testfile, datalen); err += check_data(testfile, data, 0, datalen); res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; if (err) return -1; success(); return 0; } #define test_open(exist, flags, mode) do_test_open(exist, flags, #flags, mode) static int do_test_open(int exist, int flags, const char *flags_str, int mode) { static char func[] = "do_test_open"; char buf[4096]; const char *data = testdata; int datalen = testdatalen; unsigned currlen = 0; int err = 0; int res; int fd; off_t off; start_test("open(%s, %s, 0%03o)", exist ? "+" : "-", flags_str, mode); unlink(testfile); if (exist) { res = create_file(testfile, testdata2, testdata2len); if (res == -1) return -1; currlen = testdata2len; } fd = open(testfile, flags, mode); if ((flags & O_CREAT) && (flags & O_EXCL) && exist) { if (fd != -1) { test_error(func, "open should have failed"); close(fd); return -1; } else if (errno == EEXIST) goto succ; } if (!(flags & O_CREAT) && !exist) { if (fd != -1) { test_error(func, "open should have failed"); close(fd); return -1; } else if (errno == ENOENT) goto succ; } if (fd == -1) { test_perror(func, "open"); return -1; } if (flags & O_TRUNC) currlen = 0; err += check_type(testfile, S_IFREG); if (exist) err += check_mode(testfile, 0644); else err += check_mode(testfile, mode); err += check_nlink(testfile, 1); err += check_size(testfile, currlen); if (exist && !(flags & O_TRUNC) && (mode & 0400)) err += check_data(testfile, testdata2, 0, testdata2len); res = write(fd, data, datalen); if ((flags & O_ACCMODE) != O_RDONLY) { if (res == -1) { test_perror(func, "write"); err --; } else if (res != datalen) { test_error(func, "write is short: %u instead of %u", res, datalen); err --; } else { if (datalen > (int) currlen) currlen = datalen; err += check_size(testfile, currlen); if (mode & 0400) { err += check_data(testfile, data, 0, datalen); if (exist && !(flags & O_TRUNC) && testdata2len > datalen) err += check_data( testfile, testdata2 + datalen, datalen, testdata2len - datalen); } } } else { if (res != -1) { test_error(func, "write should have failed"); err --; } else if (errno != EBADF) { test_perror(func, "write"); err --; } } off = lseek(fd, SEEK_SET, 0); if (off == (off_t) -1) { test_perror(func, "lseek"); err--; } else if (off != 0) { test_error(func, "offset should have returned 0"); err --; } res = read(fd, buf, sizeof(buf)); if ((flags & O_ACCMODE) != O_WRONLY) { if (res == -1) { test_perror(func, "read"); err--; } else { int readsize = currlen < sizeof(buf) ? currlen : sizeof(buf); if (res != readsize) { test_error(func, "read is short: %i instead of %u", res, readsize); err--; } else { if ((flags & O_ACCMODE) != O_RDONLY) { err += check_buffer(buf, data, datalen); if (exist && !(flags & O_TRUNC) && testdata2len > datalen) err += check_buffer( buf + datalen, testdata2 + datalen, testdata2len - datalen ); } else if (exist && !(flags & O_TRUNC)) /* (added) O_RDONLY only */ err += check_buffer( buf, testdata2, testdata2len); } } } else { if (res != -1) { test_error(func, "read should have failed"); err --; } else if (errno != EBADF) { test_perror(func, "read"); err --; } } res = close(fd); if (res == -1) { test_perror(func, "close"); return -1; } res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; if (err) return -1; succ: success(); return 0; } #define test_open_acc(flags, mode, err) do_test_open_acc(flags, #flags, mode, err, #err) static int do_test_open_acc(int flags, const char *flags_str, int mode, int err, const char *err_str) { static char func[] = "do_test_open_acc"; const char *data = testdata; int datalen = testdatalen; int res; int fd; start_test("open_acc(%s) mode=0%03o errno=%s", flags_str, mode, err_str); unlink(testfile); res = create_file(testfile, data, datalen); if (res == -1) return -1; res = chmod(testfile, mode); if (res == -1) { test_perror(func, "chmod"); return -1; } res = check_mode(testfile, mode); if (res == -1) return -1; fd = open(testfile, flags); if (fd == -1) { if (err != errno) { test_perror(func, "open"); return -1; } res = check_size(testfile, datalen); /* added */ if (res == -1) return -1; chmod(testfile, 0400); res = check_data(testfile, data, 0, datalen); /* added */ if (res == -1) return -1; } else { if (err) { test_error(func, "open should have failed"); close(fd); return -1; } close(fd); if (flags & O_TRUNC) { /* added */ res = check_size(testfile, 0); if (res == -1) return -1; } } success(); return 0; } static int test_symlink(void) { static char func[] = "test_symlink"; char buf[1024]; const char *data = testdata; int datalen = testdatalen; int linklen = strlen(testfile); int err = 0; int res; start_test("symlink"); res = create_file(testfile, data, datalen); if (res == -1) return -1; unlink(testfile2); res = symlink(testfile, testfile2); if (res == -1) { test_perror(func, "symlink"); return -1; } res = check_type(testfile2, S_IFLNK); if (res == -1) return -1; err += check_mode(testfile2, 0777); err += check_nlink(testfile2, 1); res = readlink(testfile2, buf, sizeof(buf)); if (res == -1) { test_perror(func, "readlink"); err--; } if (res != linklen) { test_error(func, "short readlink: %u instead of %u", res, linklen); err--; } if (memcmp(buf, testfile, linklen) != 0) { test_error(func, "link mismatch"); err--; } err += check_size(testfile2, datalen); err += check_data(testfile2, data, 0, datalen); res = unlink(testfile2); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile2); if (res == -1) return -1; if (err) return -1; success(); return 0; } static int test_link(void) { static char func[] = "test_link"; const char *data = testdata; int datalen = testdatalen; int err = 0; int res; start_test("link"); res = create_file(testfile, data, datalen); if (res == -1) return -1; unlink(testfile2); res = link(testfile, testfile2); if (res == -1) { test_perror(func, "link"); return -1; } res = check_type(testfile2, S_IFREG); if (res == -1) return -1; err += check_mode(testfile2, 0644); err += check_nlink(testfile2, 2); err += check_size(testfile2, datalen); err += check_data(testfile2, data, 0, datalen); res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; err += check_nlink(testfile2, 1); res = unlink(testfile2); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile2); if (res == -1) return -1; if (err) return -1; success(); return 0; } static int test_rename_file(void) { static char func[] = "test_rename_file"; const char *data = testdata; int datalen = testdatalen; int err = 0; int res; start_test("rename file"); res = create_file(testfile, data, datalen); if (res == -1) return -1; unlink(testfile2); res = rename(testfile, testfile2); if (res == -1) { test_perror(func, "rename"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; res = check_type(testfile2, S_IFREG); if (res == -1) return -1; err += check_mode(testfile2, 0644); err += check_nlink(testfile2, 1); err += check_size(testfile2, datalen); err += check_data(testfile2, data, 0, datalen); res = unlink(testfile2); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile2); if (res == -1) return -1; if (err) return -1; success(); return 0; } static int test_rename_dir(void) { static char func[] = "test_rename_dir"; int err = 0; int res; start_test("rename dir"); res = create_dir(testdir, testdir_files); if (res == -1) return -1; rmdir(testdir2); res = rename(testdir, testdir2); if (res == -1) { test_perror(func, "rename"); cleanup_dir(testdir, testdir_files, 1); return -1; } res = check_nonexist(testdir); if (res == -1) { cleanup_dir(testdir, testdir_files, 1); return -1; } res = check_type(testdir2, S_IFDIR); if (res == -1) { cleanup_dir(testdir2, testdir_files, 1); return -1; } err += check_mode(testdir2, 0755); err += check_dir_contents(testdir2, testdir_files); err += cleanup_dir(testdir2, testdir_files, 0); res = rmdir(testdir2); if (res == -1) { test_perror(func, "rmdir"); return -1; } res = check_nonexist(testdir2); if (res == -1) return -1; if (err) return -1; success(); return 0; } static int test_mkfifo(void) { static char func[] = "test_mkfifo"; int res; int err = 0; start_test("mkfifo"); unlink(testfile); res = mkfifo(testfile, 0644); if (res == -1) { test_perror(func, "mkfifo"); return -1; } res = check_type(testfile, S_IFIFO); if (res == -1) return -1; err += check_mode(testfile, 0644); err += check_nlink(testfile, 1); res = unlink(testfile); if (res == -1) { test_perror(func, "unlink"); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; if (err) return -1; success(); return 0; } static int test_mkdir(void) { static char func[] = "test_mkdir"; int res; int err = 0; const char *dir_contents[] = {NULL}; start_test("mkdir"); rmdir(testdir); res = mkdir(testdir, 0755); if (res == -1) { test_perror(func, "mkdir"); return -1; } res = check_type(testdir, S_IFDIR); if (res == -1) return -1; err += check_mode(testdir, 0755); err += check_nlink(testdir, 2); err += check_dir_contents(testdir, dir_contents); res = rmdir(testdir); if (res == -1) { test_perror(func, "rmdir"); return -1; } res = check_nonexist(testdir); if (res == -1) return -1; if (err) return -1; success(); return 0; } #define test_mmap(prot, flags) do_test_mmap(prot, #prot, flags, #flags) static int do_test_mmap(int prot, const char *prot_str, int flags, const char *flags_str) { static char func[] = "do_test_mmap"; int res; int err = 0; int fd; unsigned currlen = 0; char *m; static char testdata3[] = "_1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,."; start_test("mmap(%s, %s)", prot_str, flags_str); unlink(testfile); res = create_file(testfile, testdata2, testdata2len); if (res == -1) return -1; currlen = testdata2len; fd = open(testfile, O_RDWR); if (fd == -1) { test_perror(func, "open"); return -1; } m = mmap(0, currlen, prot, flags, fd, 0); close(fd); if ((void *) m == MAP_FAILED) { test_perror(func, "mmap"); return -1; } if (prot & PROT_READ) { err += check_buffer(m, testdata2, currlen); } if (prot & PROT_WRITE) { memcpy(m, testdata3, currlen); err += check_buffer(m, testdata3, currlen); } munmap(m, currlen); err += check_nlink(testfile, 1); err += check_size(testfile, currlen); if (err) { return -1; } else { success(); return 0; } } #define BSIZE 1024 static int test_seek_eof(int pos) { static char func[] = "test_seek_eof"; int res; int fd; int i; char b1[BSIZE], b2[BSIZE]; start_test("seek_EOF offset=%d", pos); unlink(testfile); fd = open(testfile, O_CREAT | O_RDWR, 0644); if (fd == -1) { test_perror(func, "open"); return -1; } for (i = 0; i < BSIZE; i++) b1[i] = (char) i; pwrite(fd, b1, 1, pos - 2); pread(fd, b2, 2, pos - 2); /* toward */ pwrite(fd, b1, 1, pos - 1); /* go back */ pwrite(fd, b1, 2, pos); /* Can this write correctly? */ res = pread(fd, b2, BSIZE, pos); /* check */ if (res != 2) { test_error(func, "cannot write correctly"); return -1; } success(); return 0; } static int test_open_size() { static char func[] = "test_open_size"; int res; int fd; char b = '0'; start_test("open size"); unlink(testfile); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; fd = open(testfile, O_RDWR | O_CREAT | O_TRUNC, 0600); if (fd == -1) { test_perror(func, "open"); return -1; } res = check_size(testfile, 0); if (res == -1) return -1; res = write(fd, &b, 1); if (res == -1) { test_perror(func, "write"); return -1; } res = check_size(testfile, 1); if (res == -1) return -1; lseek(fd, 65536, SEEK_SET); res = write(fd, &b, 1); res = check_size(testfile, 65537); if (res == -1) return -1; close(fd); success(); return 0; } static int test_open_rename() { static char func[] = "test_open_rename"; int res, err = 0; int fd1, fd2; struct utimbuf utm; time_t atime = 987631200; time_t mtime = 123116400; start_test("open rename utime close"); unlink(testfile); unlink(testfile2); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; fd1 = open(testfile, O_RDWR); if (fd1 == -1) { test_perror(func, "open_1"); return -1; } res = rename(testfile, testfile2); if (res == -1) { test_perror(func, "rename"); close(fd1); return -1; } res = check_nonexist(testfile); if (res == -1) return -1; fd2 = open(testfile, O_RDWR | O_CREAT | O_EXCL, 0600); if (fd2 == -1) { test_perror(func, "open_2"); close(fd1); return -1; } res = write(fd2, testdata2, testdata2len); if (res == -1) { test_perror(func, "write"); err += -1; } else if (res != testdata2len) { test_error(func, "write is short: %u instead of %u", res, testdata2len); err += -1; } utm.actime = atime; utm.modtime = mtime; res = utime(testfile, &utm); res = 0; if (res == -1) { test_perror(func, "utime_1"); err += -1; } res = utime(testfile2, &utm); if (res == -1) { test_perror(func, "utime_2"); err += -1; } close(fd1); close(fd2); err += check_times(testfile, atime, mtime); err += check_times(testfile2, atime, mtime); err += check_data(testfile, testdata2, 0, testdata2len); err += check_data(testfile2, testdata, 0, testdatalen); if (err) return -1; success(); return 0; } static int test_open_unlink() { static char func[] = "test_open_unlink"; int res; int fd; char b = '0'; start_test("open unlink close"); unlink(testfile); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; fd = open(testfile, O_RDWR); if (fd == -1) { test_perror(func, "open"); return -1; } res = unlink(testfile); /* FUSE: RENAME is called */ if (res == -1) { test_perror(func, "unlink"); close(fd); return -1; } /* for a filesystem which update the metadata at CLOSE only */ write(fd, &b, 1); res = check_nonexist(testfile); if (res == -1) return -1; res = fchmod(fd, 0700); /* FUSE: renamed hidden file. */ if (res == -1) test_perror(func, "fchmod"); close(fd); res = check_nonexist(testfile); if (res == -1) return -1; success(); return 0; } static int test_open_utime() { static char func[] = "test_open_utime"; int res; int fd; char b = '0'; struct utimbuf utm; time_t atime = 987631200; time_t mtime = 123116400; start_test("open utime close"); unlink(testfile); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; fd = open(testfile, O_RDWR); if (fd == -1) { test_perror(func, "open"); return -1; } write(fd, &b, 1); /* update metadata */ utm.actime = atime; utm.modtime = mtime; res = utime(testfile, &utm); if (res == -1) { test_perror(func, "utime"); close(fd); return -1; } res = check_times(testfile, atime, mtime); if (res == -1) return -1; close(fd); res = check_times(testfile, atime, mtime); if (res == -1) return -1; success(); return 0; } static int test_open_chmod(mode_t mode1, mode_t mode2) { static char func[] = "test_open_chmod"; int res; int fd; char b = '0'; start_test("chmod(0%o) open chmod(0%o) close", mode1, mode2); unlink(testfile); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; res = chmod(testfile, mode1); if (res == -1) { test_perror(func, "chmod_1"); return -1; } res = check_mode(testfile, mode1); if (res == -1) return -1; fd = open(testfile, O_RDWR); if (fd == -1) { test_perror(func, "open"); return -1; } write(fd, &b, 1); /* update metadata */ res = chmod(testfile, mode2); if (res == -1) { test_perror(func, "chmod_2"); close(fd); return -1; } res = check_mode(testfile, mode2); close(fd); if (res == -1) return -1; res = check_mode(testfile, mode2); if (res == -1) return -1; success(); return 0; } #define test_open_open(f, s) do_test_open_open(0, f, #f, s, #s) #define test_creat_open(f, s) do_test_open_open(1, f, #f, s, #s) static int do_test_open_open(int creat_mode, int flags_first, const char *str_first, int flags_second, const char *str_second) { static char func[] = "do_test_open_open"; int res; int fd1, fd2; unlink(testfile); if (creat_mode) { start_test("creat(%s) open(%s)", str_first, str_second); fd1 = open(testfile, O_CREAT | flags_first, 0644); if (fd1 == -1) { test_perror(func, "open_1"); return -1; } res = write(fd1, testdata, testdatalen); if (res == -1) { test_perror(func, "write"); close(fd1); return -1; } if (res != testdatalen) { test_error(func, "write is short: %u instead of %u", res, testdatalen); close(fd1); return -1; } } else { start_test("open(%s) open(%s)", str_first, str_second); res = create_file(testfile, testdata, testdatalen); if (res == -1) return -1; fd1 = open(testfile, flags_first); if (fd1 == -1) { test_perror(func, "open_1"); return -1; } } fd2 = open(testfile, flags_second); if (fd2 == -1) { test_perror(func, "open_2"); close(fd1); return -1; } close(fd1); close(fd2); res = check_data(testfile, testdata, 0, testdatalen); if (res == -1) return -1; success(); return 0; } static void filename_set(char **namep, char *prefix, char *hostname, char *pid) { size_t len = (strlen(prefix) + strlen(hostname) + strlen(pid)) * sizeof(char *); *namep = malloc(len); if (*namep == NULL) exit(1); snprintf(*namep, len, "%s_%s_%s", prefix, hostname, pid); } #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 256 #endif static void test_initialize() { char hostname[HOST_NAME_MAX]; char pid[16]; int res; res = gethostname(hostname, HOST_NAME_MAX); if (res == -1) snprintf(hostname, HOST_NAME_MAX, "tmp"); snprintf(pid, 16, "%d", (int)getpid()); filename_set(&testfile, FILE1, hostname, pid); filename_set(&testfile2, FILE2, hostname, pid); filename_set(&testdir, DIR1, hostname, pid); filename_set(&testdir2, DIR2, hostname, pid); } static int test_finalize(int err) { unlink(testfile); unlink(testfile2); rmdir(testdir); rmdir(testdir2); if (err) { fprintf(stdout, "%i tests failed\n", -err); return 1; } return 0; } static void signal_exit(int sig) { int res; (void) sig; res = test_finalize(0); fprintf(stderr, "canceled\n"); exit(res); } static void usage(char *name) { fprintf(stderr, "usage: %s [-m] testdir\n", name); } int main(int argc, char *argv[]) { int err = 0; struct sigaction sa; char c; char *progname = argv[0]; int enable_mmap = 0; while ((c = getopt(argc, argv, "m")) != EOF) { switch(c) { case 'm': enable_mmap = 1; break; default: usage(progname); return 1; } } argc -= optind; argv += optind; if (argc != 1) { usage(progname); return 1; } umask(0); chdir(argv[0]); setvbuf(stdout, NULL, _IOLBF, 0); setvbuf(stderr, NULL, _IOLBF, 0); sa.sa_handler = signal_exit; sigaction(SIGHUP, &sa, NULL); sigaction(SIGINT, &sa, NULL); test_initialize(); #if 1 err += test_create(); err += test_symlink(); err += test_link(); err += test_mkfifo(); err += test_mkdir(); err += test_rename_file(); err += test_rename_dir(); err += test_utime(); err += test_truncate(0); err += test_truncate(testdatalen / 2); err += test_truncate(testdatalen); err += test_truncate(testdatalen + 100); err += test_ftruncate(0, 0600); err += test_ftruncate(testdatalen / 2, 0600); err += test_ftruncate(testdatalen, 0600); err += test_ftruncate(testdatalen + 100, 0600); err += test_ftruncate(0, 0400); err += test_ftruncate(0, 0200); err += test_ftruncate(0, 0000); err += test_open(0, O_RDONLY, 0); err += test_open(1, O_RDONLY, 0); err += test_open(1, O_RDWR, 0); err += test_open(1, O_WRONLY, 0); err += test_open(0, O_RDWR | O_CREAT, 0600); err += test_open(1, O_RDWR | O_CREAT, 0600); err += test_open(0, O_RDWR | O_CREAT | O_TRUNC, 0600); err += test_open(1, O_RDWR | O_CREAT | O_TRUNC, 0600); err += test_open(0, O_RDONLY | O_CREAT, 0600); err += test_open(0, O_RDONLY | O_CREAT, 0400); err += test_open(0, O_RDONLY | O_CREAT, 0200); err += test_open(0, O_RDONLY | O_CREAT, 0000); err += test_open(0, O_WRONLY | O_CREAT, 0600); err += test_open(0, O_WRONLY | O_CREAT, 0400); err += test_open(0, O_WRONLY | O_CREAT, 0200); err += test_open(0, O_WRONLY | O_CREAT, 0000); err += test_open(0, O_RDWR | O_CREAT, 0400); err += test_open(0, O_RDWR | O_CREAT, 0200); err += test_open(0, O_RDWR | O_CREAT, 0000); err += test_open(0, O_RDWR | O_CREAT | O_EXCL, 0600); err += test_open(1, O_RDWR | O_CREAT | O_EXCL, 0600); err += test_open(0, O_RDWR | O_CREAT | O_EXCL, 0000); err += test_open(1, O_RDWR | O_CREAT | O_EXCL, 0000); err += test_open_acc(O_RDONLY, 0600, 0); err += test_open_acc(O_WRONLY, 0600, 0); err += test_open_acc(O_RDWR, 0600, 0); err += test_open_acc(O_RDONLY, 0400, 0); err += test_open_acc(O_RDONLY | O_TRUNC, 0400, EACCES); err += test_open_acc(O_WRONLY, 0400, EACCES); err += test_open_acc(O_RDWR, 0400, EACCES); err += test_open_acc(O_RDONLY, 0200, EACCES); err += test_open_acc(O_WRONLY, 0200, 0); err += test_open_acc(O_RDWR, 0200, EACCES); err += test_open_acc(O_RDONLY, 0000, EACCES); err += test_open_acc(O_WRONLY, 0000, EACCES); err += test_open_acc(O_RDWR, 0000, EACCES); /* ------ additional tests ------ */ err += test_open_acc(O_RDONLY | O_TRUNC, 0600, 0); err += test_open_acc(O_RDONLY | O_TRUNC, 0200, EACCES); err += test_open_acc(O_WRONLY | O_TRUNC, 0200, 0); err += test_open_acc(O_RDWR | O_TRUNC, 0200, EACCES); if (enable_mmap) { err += test_mmap(PROT_READ, MAP_SHARED); err += test_mmap(PROT_WRITE, MAP_SHARED); err += test_mmap(PROT_READ | PROT_WRITE, MAP_SHARED); } err += test_seek_eof(10); err += test_open_size(); err += test_open_rename(); err += test_open_unlink(); err += test_open_utime(); err += test_open_chmod(0600, 0700); err += test_open_chmod(0700, 0600); err += test_open_open(O_RDONLY, O_WRONLY); err += test_open_open(O_RDONLY, O_RDWR); err += test_open_open(O_WRONLY, O_RDONLY); err += test_open_open(O_WRONLY, O_RDWR); err += test_open_open(O_RDWR, O_RDONLY); err += test_open_open(O_RDWR, O_WRONLY); /* err += test_creat_open(O_RDONLY, O_WRONLY); -- EBADF */ /* err += test_creat_open(O_RDONLY, O_RDWR); -- EBADF */ err += test_creat_open(O_WRONLY, O_RDONLY); err += test_creat_open(O_WRONLY, O_RDWR); err += test_creat_open(O_RDWR, O_RDONLY); err += test_creat_open(O_RDWR, O_WRONLY); err += test_open_truncate(O_RDONLY, 0200, 0, 0); /* err += test_open_truncate(O_RDONLY, 0200, 5, 0); -- EBADF */ err += test_open_truncate(O_RDONLY, 0600, 5, 0); err += test_open_truncate(O_RDONLY, 0400, 5, EACCES); err += test_open_truncate(O_WRONLY, 0600, 5, 0); err += test_open_truncate(O_WRONLY, 0400, 5, EACCES); #endif return test_finalize(err); } <file_sep>/gfarm/tags/gfarm_1_0_2/gftool/gfexport/gfexport.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfexport"; void gfprint(GFS_File gf, FILE *ofp) { int c; while ((c = gfs_pio_getc(gf)) != EOF) putc(c, ofp); if (gfs_pio_error(gf) != NULL) fprintf(stderr, "%s: error: %s\n", program_name, gfs_pio_error(gf)); } char * gfexport_section(char *gfarm_url, char *section, FILE *ofp) { char *e; GFS_File gf; e = gfs_pio_open(gfarm_url, GFARM_FILE_RDONLY, &gf); if (e != NULL) return (e); e = gfs_pio_set_view_section(gf, section, NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) { gfs_pio_close(gf); return (e); } gfprint(gf, ofp); gfs_pio_close(gf); return (NULL); } char * gfexport(char *gfarm_url, FILE *ofp, int nhosts, char **hostlist) { char *e; GFS_File gf; int i, nfrags; e = gfs_pio_open(gfarm_url, GFARM_FILE_RDONLY, &gf); if (e != NULL) return (e); e = gfs_pio_get_nfragment(gf, &nfrags); if (e != NULL) { gfs_pio_close(gf); return (e); } if (hostlist != NULL && nhosts != nfrags) { fprintf(stderr, "%s: specified hostlist are ignored, because " "the number of hosts %d doesn't match " "the number of fragments %d.\n", program_name, nhosts, nfrags); hostlist = NULL; } for (i = 0; i < nfrags; i++) { e = gfs_pio_set_view_index(gf, nfrags, i, hostlist != NULL ? hostlist[i] : NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) break; gfprint(gf, ofp); } gfs_pio_close(gf); return (e); } /* just a test routine for global view (and default view) */ char * gfexport_test(char *gfarm_url, FILE *ofp, int explicit) { char *e; GFS_File gf; e = gfs_pio_open(gfarm_url, GFARM_FILE_RDONLY, &gf); if (e != NULL) return (e); if (explicit) { /* * global mode is default, * so, we don't have to specify this explicitly. */ e = gfs_pio_set_view_global(gf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { gfs_pio_close(gf); return (e); } } gfprint(gf, ofp); gfs_pio_close(gf); return (NULL); } void usage() { fprintf(stderr, "Usage: %s [option] <input_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-H <hostfile>\n"); fprintf(stderr, "\t-I <fragment>\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *hostfile = NULL, *section = NULL, *url; int ch, error_line, n = 0, default_view = 0, global_view = 0; char **hostlist = NULL; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "H:I:dg?")) != -1) { switch (ch) { case 'H': hostfile = optarg; break; case 'I': section = optarg; break; case 'd': default_view = 1; break; case 'g': global_view = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc != 1) { fprintf(stderr, "%s: error: only one input file name expected\n", program_name); exit(1); } if (hostfile != NULL && section != NULL) { fprintf(stderr, "%s: error: option -H and option -I are exclusive\n", program_name); exit(1); } e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_realpath(argv[0], &url); if (e != NULL) { fprintf(stderr, "%s: %s\n", argv[0], e); exit(1); } if (section != NULL) { e = gfexport_section(url, section, stdout); } else if (global_view) { e = gfexport_test(url, stdout, 1); } else if (default_view) { e = gfexport_test(url, stdout, 0); } else { if (hostfile != NULL) { e = gfarm_hostlist_read(hostfile, &n, &hostlist, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s: line %d: %s\n", program_name, hostfile, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, hostfile, e); free(url); exit(1); } } e = gfexport(url, stdout, n, hostlist); } if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, url, e); free(url); exit(1); } free(url); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_2/lib/libgfarm/gfarm/gfs_lock.c /* * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <errno.h> #define GFARM_LOCKFILE_SUF ":::lock" #define GFARM_USLEEP_INTERVAL 100 /* 100 msec */ static int gfs_i_lockfile(char *file, char **lockfile) { char *lfile; *lockfile = NULL; if (file == NULL) return (-1); lfile = malloc(strlen(file) + sizeof(GFARM_LOCKFILE_SUF)); if (lfile == NULL) return (-1); sprintf(lfile, "%s%s", file, GFARM_LOCKFILE_SUF); *lockfile = lfile; return (0); } static int gfs_i_lock(char *file) { char *lockfile; int fd; mode_t saved_mask; if (file == NULL) return (-2); if (gfs_i_lockfile(file, &lockfile)) return (-2); saved_mask = umask(0); fd = open(lockfile, O_CREAT | O_EXCL, 0644); umask(saved_mask); free(lockfile); if (fd != -1) { close(fd); return (0); } else if (errno != EEXIST) return (-2); /* other reasons. cannot lock */ return (-1); } int gfs_lock_local_path_section(char *localpath) { int r; while ((r = gfs_i_lock(localpath)) == -1) { usleep(GFARM_USLEEP_INTERVAL); } return (r); } int gfs_unlock_local_path_section(char *localpath) { char *lockfile; if (gfs_i_lockfile(localpath, &lockfile)) return (-1); unlink(lockfile); free(lockfile); return (0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT3-2-1-1_all_gfmd_down #! /bin/sh ###################################################################### TESTID="FT3-2-1-1" CATEGORY="N point accident" SECTION="MDS internal accident" TITLE="all gfmd down" ###################################################################### . ./FT-common ft_setup() { # # This test case is never succeeded. # zabbix-agent executes 'gfmdhost -l' to check whether master # gfmd is alive but it takes about 40sec since all gfmd servers # are down. However, zabbix-agent gives up waiting 'gfmdhost -l' # and it never reports an trouble. # return $FT_RESULT_UNTESTED } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd3 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.3 "stop gfmd on $gfmd3" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd2 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.2 "stop gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "slave gfmd is not running on $gfmd3" \ "slave gfmd is not running on $gfmd2" \ "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2.1 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { $gfservice start-gfmd gfmd1 $gfservice start-gfmd gfmd2 $gfservice start-gfmd gfmd3 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/config.c #include <sys/param.h> #include <sys/wait.h> #include <signal.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> /* ntohs */ #include <netdb.h> #include <time.h> #include <pwd.h> #include <gfarm/gfarm.h> #include "hostspec.h" #include "host.h" #include "param.h" #include "sockopt.h" #include "auth.h" #include "gfm_proto.h" #include "gfs_proto.h" #include "gfs_client.h" #include "gfs_pio.h" /* GFS_FILE_MODE_CALC_DIGEST */ #ifndef GFARM_CONFIG #define GFARM_CONFIG "/etc/gfarm.conf" #endif #ifndef GFARM_CLIENT_RC #define GFARM_CLIENT_RC ".gfarmrc" #endif #ifndef GFARM_SPOOL_ROOT #define GFARM_SPOOL_ROOT "/var/spool/gfarm" #endif int gfarm_initialized = 0; char *gfarm_config_file = GFARM_CONFIG; void gfarm_config_set_filename(char *filename) { gfarm_config_file = filename; } /* * GFarm username handling */ static gfarm_stringlist local_user_map_file_list; static char GFARM_ERR_TOO_MANY_ARGUMENTS[] = "too many arguments"; static char GFARM_ERR_LOCAL_USER_REDEFIEND[] = "local user name redifined"; static char GFARM_ERR_GLOBAL_USER_REDEFIEND[] = "global user name redifined"; /* the return value of the following function should be free(3)ed */ char * gfarm_global_to_local_username(char *global_user ,char **local_user) { FILE *map = NULL; char *mapfile = NULL; int i, list_len; char buffer[1024], *g_user, *l_user, *e; int lineno = 0; static char format[] = "%s: line %d: %s"; static char error[256]; e = NULL; *local_user = NULL; list_len = gfarm_stringlist_length(&local_user_map_file_list); for (i = 0; i < list_len; i++) { mapfile = gfarm_stringlist_elem(&local_user_map_file_list, i); if ((map = fopen(mapfile, "r")) == NULL) { e = "cannot read"; #ifdef HAVE_SNPRINTF snprintf(error, sizeof(error), "%s: %s", mapfile, e); #else if (strlen(format) + strlen(mapfile) + strlen(e) < sizeof(error)) { sprintf(error, "%s: %s", mapfile, e); } else { /* XXX: no file name */ strcpy(error, "user map file cannot read"); } #endif return (error); } lineno = 0; while (fgets(buffer, sizeof buffer, map) != NULL) { char *bp = buffer; lineno++; g_user = gfarm_strtoken(&bp, &e); if (e != NULL) goto finish; if (g_user == NULL) /* blank or comment line */ continue; l_user = gfarm_strtoken(&bp, &e); if (e != NULL) goto finish; if (l_user == NULL) { e = "local user name undefined"; goto finish; } if (strcmp(g_user, global_user) == 0) { if (*local_user != NULL && strcmp(l_user, *local_user) != 0) { e = GFARM_ERR_GLOBAL_USER_REDEFIEND; goto finish; } *local_user = strdup(l_user); if (*local_user == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } } if (gfarm_strtoken(&bp, &e) != NULL) { e = GFARM_ERR_TOO_MANY_ARGUMENTS; goto finish; } } fclose(map); map = NULL; } if (*local_user == NULL) { /* not found */ *local_user = strdup(global_user); if (*local_user == NULL) e = GFARM_ERR_NO_MEMORY; } finish: if (map != NULL) fclose(map); if (e != NULL) { #ifdef HAVE_SNPRINTF snprintf(error, sizeof(error), format, mapfile, lineno, e); #else if (strlen(format) + strlen(mapfile) + GFARM_INT32STRLEN + strlen(e) < sizeof(error)) { sprintf(error, format, mapfile, lineno, e); } else { /* XXX: no file name, no line number */ strcpy(error, "user map file read error"); } #endif e = error; } return (e); } /* the return value of the following function should be free(3)ed */ char * gfarm_local_to_global_username(char *local_user, char **global_user) { FILE *map = NULL; char *mapfile = NULL; int i, list_len; char buffer[1024], *g_user, *l_user, *e; int lineno = 0; static char format[] = "%s: line %d: %s"; static char error[256]; e = NULL; *global_user = NULL; list_len = gfarm_stringlist_length(&local_user_map_file_list); for (i = 0; i < list_len; i++) { mapfile = gfarm_stringlist_elem(&local_user_map_file_list, i); if ((map = fopen(mapfile, "r")) == NULL) { e = "cannot read"; #ifdef HAVE_SNPRINTF snprintf(error, sizeof(error), "%s: %s", mapfile, e); #else if (strlen(format) + strlen(mapfile) + strlen(e) < sizeof(error)) { sprintf(error, "%s: %s", mapfile, e); } else { /* XXX: no file name */ strcpy(error, "user map file cannot read"); } #endif return (error); } lineno = 0; while (fgets(buffer, sizeof buffer, map) != NULL) { char *bp = buffer; lineno++; g_user = gfarm_strtoken(&bp, &e); if (e != NULL) goto finish; if (g_user == NULL) /* blank or comment line */ continue; l_user = gfarm_strtoken(&bp, &e); if (e != NULL) goto finish; if (l_user == NULL) { e = "local user name undefined"; goto finish; } if (strcmp(l_user, local_user) == 0) { if (*global_user != NULL && strcmp(g_user, *global_user) != 0) { e = GFARM_ERR_LOCAL_USER_REDEFIEND; goto finish; } *global_user = strdup(g_user); if (*global_user == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } } if (gfarm_strtoken(&bp, &e) != NULL) { e = GFARM_ERR_TOO_MANY_ARGUMENTS; goto finish; } } fclose(map); map = NULL; } if (*global_user == NULL) { /* not found */ *global_user = strdup(local_user); if (*global_user == NULL) e = GFARM_ERR_NO_MEMORY; } finish: if (map != NULL) fclose(map); if (e != NULL) { #ifdef HAVE_SNPRINTF snprintf(error, sizeof(error), format, mapfile, lineno, e); #else if (strlen(format) + strlen(mapfile) + GFARM_INT32STRLEN + strlen(e) < sizeof(error)) { sprintf(error, format, mapfile, lineno, e); } else { /* XXX: no file name, no line number */ strcpy(error, "user map file read error"); } #endif e = error; } return (e); } static char * set_string(char **var, char *value) { if (*var != NULL) free(*var); *var = strdup(value); if (*var == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } /* * client side variables */ static char *gfarm_global_username = NULL; static char *gfarm_local_username = NULL; static char *gfarm_local_homedir = NULL; char * gfarm_set_global_username(char *global_username) { return (set_string(&gfarm_global_username, global_username)); } char * gfarm_get_global_username(void) { return (gfarm_global_username); } char * gfarm_set_local_username(char *local_username) { return (set_string(&gfarm_local_username, local_username)); } char * gfarm_get_local_username(void) { return (gfarm_local_username); } char * gfarm_set_local_homedir(char *local_homedir) { return (set_string(&gfarm_local_homedir, local_homedir)); } char * gfarm_get_local_homedir(void) { return (gfarm_local_homedir); } /* * We should not trust gfarm_get_*() values as a result of this function * (because it may be forged). */ char * gfarm_set_local_user_for_this_local_account(void) { char *error = NULL; char *user; char *home; struct passwd *pwd; user = getenv("USER"); if (user == NULL) user = getenv("LOGIN"); if (user == NULL) user = getlogin(); home = getenv("HOME"); if (user == NULL || home == NULL) { pwd = NULL; if (user != NULL) pwd = getpwnam(user); if (pwd == NULL) { /*user = NULL;*/ /* maybe getpwnam(user) failed */ pwd = getpwuid(getuid()); } if (pwd != NULL) { if (user == NULL) user = pwd->pw_name; if (home == NULL) home = pwd->pw_dir; } else { /* XXX */ if (user == NULL) user = "nobody"; if (home == NULL) home = "/"; } } error = gfarm_set_local_username(user); if (error != NULL) return (error); error = gfarm_set_local_homedir(home); if (error != NULL) return (error); return (error); } char * gfarm_set_global_user_for_this_local_account(void) { char *e, *local_user, *global_user; local_user = gfarm_get_local_username(); e = gfarm_local_to_global_username(local_user, &global_user); if (e != NULL) return (e); e = gfarm_set_global_username(global_user); gfarm_stringlist_free_deeply(&local_user_map_file_list); return (e); } /* * GFarm Configurations. * * These initial values should be NULL, otherwise the value incorrectly * free(3)ed in the get_one_argument() function below. * If you would like to provide default value other than NULL, set the * value at the end of gfarm_config_read(). */ char *gfarm_spool_root = NULL; static char *gfarm_spool_server_portname = NULL; /* GFM dependent */ char *gfarm_metadb_server_name = NULL; static char *gfarm_metadb_server_portname = NULL; /* LDAP dependent */ char *gfarm_ldap_server_name = NULL; char *gfarm_ldap_server_port = NULL; char *gfarm_ldap_base_dn = NULL; int gfarm_spool_server_port = GFSD_DEFAULT_PORT; int gfarm_metadb_server_port = GFMD_DEFAULT_PORT; /* * get (almost) shell style token. * e.g. * string... * 'string...' (do not interpret escape character `\') * "string..." (interpret escape character `\') * # comment * difference from shell token: * don't allow newline in "..." and '...". * * return value: * string * OR * NULL - if error or end-of-line. * output parameter: * *cursorp: * next character to read * *errorp: * NULL (if success or end-of-line) * OR * error message */ char * gfarm_strtoken(char **cursorp, char **errorp) { char *top, *p, *s = *cursorp; *errorp = NULL; while (*s != '\n' && isspace(*s)) s++; if (*s == '\0' || *s == '\n' || *s == '#') { /* end of line */ *cursorp = s; return (NULL); } top = s; p = s; for (;;) { switch (*s) { case '\'': s++; for (;;) { if (*s == '\'') break; if (*s == '\0' || *s == '\n') { *errorp = "unterminated single quote"; return (NULL); } *p++ = *s++; } s++; break; case '"': s++; for (;;) { if (*s == '"') break; if (*s == '\0' || *s == '\n') { *errorp = "unterminated double quote"; return (NULL); } if (*s == '\\') { if (s[1] == '\0' || s[1] == '\n') { *errorp = "unterminated double quote"; return (NULL); } /* * only interpret `\"' and `\\' * in double quotation. */ if (s[1] == '"' || s[1] == '\\') s++; } *p++ = *s++; } s++; break; case '\\': s++; if (*s == '\0' || *s == '\n') { *errorp = "incomplete escape: \\"; return (NULL); } *p++ = *s++; break; case '\n': case '#': case '\0': *p = '\0'; *cursorp = s; return (top); default: if (isspace(*s)) { *p = '\0'; *cursorp = s + 1; return (top); } *p++ = *s++; break; } } } static char * parse_auth_arguments(char *p, char **op) { char *e, *command, *auth, *host; enum gfarm_auth_method auth_method; struct gfarm_hostspec *hostspecp; /* assert(strcmp(*op, "auth") == 0); */ command = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (command == NULL) return ("missing 1st(auth-command) argument"); auth = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (auth == NULL) return ("missing 2nd(auth-method) argument"); if (strcmp(auth, "ALL") == 0) { auth_method = GFARM_AUTH_METHOD_ALL; } else { e = gfarm_auth_method_parse(auth, &auth_method); if (e != NULL) { *op = "2nd(auth-method) argument"; if (e == GFARM_ERR_NO_SUCH_OBJECT) e = "unknown authentication method"; return (e); } } host = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (host == NULL) return ("missing 3rd(host-spec) argument"); if (gfarm_strtoken(&p, &e) != NULL) return (GFARM_ERR_TOO_MANY_ARGUMENTS); e = gfarm_hostspec_parse(host, &hostspecp); if (e != NULL) { /* * we don't return `host' to *op here, * because it may be too long. */ *op = "3rd(host-spec) argument"; return (e); } if (strcmp(command, "enable") == 0) { e = gfarm_auth_enable(auth_method, hostspecp); } else if (strcmp(command, "disable") == 0) { e = gfarm_auth_disable(auth_method, hostspecp); } else { /* * we don't return `command' to *op here, * because it may be too long. */ *op = "1st(auth-command) argument"; gfarm_hostspec_free(hostspecp); return ("unknown auth subcommand"); } if (e != NULL) gfarm_hostspec_free(hostspecp); return (e); } static char * parse_netparam_arguments(char *p, char **op) { char *e, *option, *host; struct gfarm_hostspec *hostspecp; /* assert(strcmp(*op, "netparam") == 0); */ option = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (option == NULL) return ("missing 1st(netparam-option) argument"); host = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (host == NULL) { /* if 2nd argument is omitted, it is treated as "ALL". */ host = "ALL"; } else if (gfarm_strtoken(&p, &e) != NULL) { return (GFARM_ERR_TOO_MANY_ARGUMENTS); } e = gfarm_hostspec_parse(host, &hostspecp); if (e != NULL) { /* * we don't return `host' to *op here, * because it may be too long. */ *op = "2nd(host-spec) argument"; return (e); } e = gfarm_netparam_config_add_long(option, hostspecp); if (e != NULL) { /* * we don't return `option' to *op here, * because it may be too long. */ *op = "1st(sockopt-option) argument"; gfarm_hostspec_free(hostspecp); return (e); } return (NULL); } static char * parse_sockopt_arguments(char *p, char **op) { char *e, *option, *host; struct gfarm_hostspec *hostspecp; int is_listener; /* assert(strcmp(*op, "sockopt") == 0); */ option = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (option == NULL) return ("missing 1st(sockopt-option) argument"); host = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (host == NULL) { /* * if 2nd argument is omitted, it is treated as: * "LISTENER" + "ALL". */ is_listener = 1; } else { is_listener = strcmp(host, "LISTENER") == 0; if (gfarm_strtoken(&p, &e) != NULL) return (GFARM_ERR_TOO_MANY_ARGUMENTS); } if (is_listener) { e = gfarm_sockopt_listener_config_add(option); if (e != NULL) { /* * we don't return `option' to *op here, * because it may be too long. */ *op = "1st(sockopt-option) argument"; return (e); } } if (host == NULL || !is_listener) { e = gfarm_hostspec_parse(host != NULL ? host : "ALL", &hostspecp); if (e != NULL) { /* * we don't return `host' to *op here, * because it may be too long. */ *op = "2nd(host-spec) argument"; return (e); } e = gfarm_sockopt_config_add(option, hostspecp); if (e != NULL) { /* * we don't return `option' to *op here, * because it may be too long. */ *op = "1st(sockopt-option) argument"; gfarm_hostspec_free(hostspecp); return (e); } } return (NULL); } static char * parse_address_use_arguments(char *p, char **op) { char *e, *address; struct gfarm_hostspec *hostspecp; /* assert(strcmp(*op, "address_use") == 0); */ address = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (address == NULL) return ("missing <address> argument"); if (gfarm_strtoken(&p, &e) != NULL) return (GFARM_ERR_TOO_MANY_ARGUMENTS); e = gfarm_hostspec_parse(address, &hostspecp); if (e != NULL) { /* * we don't return `host' to *op here, * because it may be too long. */ *op = "1st(address) argument"; return (e); } e = gfarm_host_address_use(hostspecp); if (e != NULL) { /* * we don't return `option' to *op here, * because it may be too long. */ *op = "1st(address) argument"; gfarm_hostspec_free(hostspecp); return (e); } return (NULL); } static char * parse_local_user_map(char *p, char **op) { char *e, *mapfile; mapfile = gfarm_strtoken(&p, &e); if (mapfile == NULL) return ("missing <user map file> argument"); if (gfarm_strtoken(&p, &e) != NULL) return (GFARM_ERR_TOO_MANY_ARGUMENTS); mapfile = strdup(mapfile); if (mapfile == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_stringlist_add(&local_user_map_file_list, mapfile); return(e); } static char * get_one_argument(char *p, char **rv) { char *s, *e; s = gfarm_strtoken(&p, &e); if (e != NULL) return (e); if (s == NULL) return ("missing argument"); if (gfarm_strtoken(&p, &e) != NULL) return (GFARM_ERR_TOO_MANY_ARGUMENTS); if (*rv != NULL) /* first line has precedence */ return (NULL); s = strdup(s); if (s == NULL) return (GFARM_ERR_NO_MEMORY); *rv = s; return (NULL); } static char * parse_one_line(char *s, char *p, char **op) { char *e, *o; if (strcmp(s, o = "spool") == 0) { e = get_one_argument(p, &gfarm_spool_root); } else if (strcmp(s, o = "spool_serverport") == 0) { e = get_one_argument(p, &gfarm_spool_server_portname); } else if (strcmp(s, o = "metadb_serverhost") == 0) { e = get_one_argument(p, &gfarm_metadb_server_name); } else if (strcmp(s, o = "metadb_serverport") == 0) { e = get_one_argument(p, &gfarm_metadb_server_portname); } else if (strcmp(s, o = "ldap_serverhost") == 0) { e = get_one_argument(p, &gfarm_ldap_server_name); } else if (strcmp(s, o = "ldap_serverport") == 0) { e = get_one_argument(p, &gfarm_ldap_server_port); } else if (strcmp(s, o = "ldap_base_dn") == 0) { e = get_one_argument(p, &gfarm_ldap_base_dn); } else if (strcmp(s, o = "auth") == 0) { e = parse_auth_arguments(p, &o); } else if (strcmp(s, o = "netparam") == 0) { e = parse_netparam_arguments(p, &o); } else if (strcmp(s, o = "sockopt") == 0) { e = parse_sockopt_arguments(p, &o); } else if (strcmp(s, o = "address_use") == 0) { e = parse_address_use_arguments(p, &o); } else if (strcmp(s, o = "local_user_map") == 0) { e = parse_local_user_map(p, &o); } else { o = s; e = "unknown keyword"; } *op = o; return (e); } static char * gfarm_config_read_file(FILE *config, char *config_file) { int lineno = 0; char *s, *p, *e, *o, buffer[1024]; static char format[] = "%s: line %d: %s: %s\n"; static char error[256]; while (fgets(buffer, sizeof buffer, config) != NULL) { lineno++; p = buffer; s = gfarm_strtoken(&p, &e); if (e == NULL) { if (s == NULL) /* blank or comment line */ continue; e = parse_one_line(s, p, &o); } if (e != NULL) { #ifdef HAVE_SNPRINTF snprintf(error, sizeof(error), format, config_file, lineno, o, e); e = error; #else if (strlen(format) + strlen(config_file) + GFARM_INT32STRLEN + strlen(o) + strlen(e) < sizeof(error)) { sprintf(error, format, config_file, lineno, o, e); e = error; } else { /* XXX: no file name, no line number */ } #endif fclose(config); return (e); } } fclose(config); return (NULL); } /* * set default value of configurations. */ static void gfarm_config_set_default1(void) { if (gfarm_spool_server_portname != NULL) { int p = strtol(gfarm_spool_server_portname, NULL, 0); struct servent *sp = getservbyname(gfarm_spool_server_portname, "tcp"); if (sp != NULL) gfarm_spool_server_port = ntohs(sp->s_port); else if (p != 0) gfarm_spool_server_port = p; } if (gfarm_metadb_server_portname != NULL) { int p = strtol(gfarm_metadb_server_portname, NULL, 0); struct servent *sp = getservbyname(gfarm_metadb_server_portname, "tcp"); if (sp != NULL) gfarm_metadb_server_port = ntohs(sp->s_port); else if (p != 0) gfarm_metadb_server_port = p; } } static void gfarm_config_set_default2(void) { if (gfarm_spool_root == NULL) { /* * When this node is a filesystem node, * gfarm_spool_root should be obtained by gfsd. */ char *host, *e; e = gfarm_host_get_canonical_self_name(&host); if (e == NULL && gfarm_host_is_local(host)) { struct sockaddr peer_addr; struct gfs_connection *gfs_server; e = gfarm_host_address_get(host, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) goto ignore_error; e = gfs_client_connection(host, &peer_addr, &gfs_server); if (e != NULL) goto ignore_error; e = gfs_client_get_spool_root(gfs_server, &gfarm_spool_root); ignore_error: ; } if (gfarm_spool_root == NULL) /* XXX - this case is not recommended. */ gfarm_spool_root = GFARM_SPOOL_ROOT; } } static void gfarm_config_set_default2_server(void) { if (gfarm_spool_root == NULL) { /* XXX - this case is not recommended. */ gfarm_spool_root = GFARM_SPOOL_ROOT; } } static enum { gfarm_config_not_read, gfarm_config_user_read, gfarm_config_server_read } config_read = gfarm_config_not_read; /* * the following function is for client, * server/daemon process shouldn't call it. * Because this function may read incorrect setting from user specified * $USER or $HOME. */ char * gfarm_config_read(void) { char *e, *home; FILE *config; int user_config_errno; static char gfarm_client_rc[] = GFARM_CLIENT_RC; char *rc; switch (config_read) { case gfarm_config_not_read: config_read = gfarm_config_user_read; break; case gfarm_config_user_read: return (NULL); case gfarm_config_server_read: return ("gfarm_config_read() is called " "after gfarm_server_config_read() is called. " "something wrong"); } /* * result of gfarm_get_local_homedir() should not be trusted. * (maybe forged) */ home = gfarm_get_local_homedir(); rc = malloc(strlen(home) + 1 + sizeof(gfarm_client_rc)); if (rc == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(rc, "%s/%s", home, gfarm_client_rc); gfarm_stringlist_init(&local_user_map_file_list); if ((config = fopen(rc, "r")) == NULL) { user_config_errno = errno; } else { user_config_errno = 0; /* * The reason why we don't just pass `rc' as the * second argument of gfarm_config_read_file() is * because `rc' may be too long name to generate error * message. */ e = gfarm_config_read_file(config, "~/" GFARM_CLIENT_RC); if (e != NULL) { free(rc); return (e); } } free(rc); if ((config = fopen(gfarm_config_file, "r")) == NULL) { if (user_config_errno != 0) return ("gfarm.conf: cannot read"); } else { e = gfarm_config_read_file(config, gfarm_config_file); if (e != NULL) return (e); } gfarm_config_set_default1(); return (NULL); } /* the following function is for server. */ char * gfarm_server_config_read(void) { char *e; FILE *config; switch (config_read) { case gfarm_config_not_read: config_read = gfarm_config_server_read; break; case gfarm_config_user_read: return ("gfarm_server_config_read() is called " "after gfarm_config_read() is called. " "something wrong"); case gfarm_config_server_read: return (NULL); } gfarm_stringlist_init(&local_user_map_file_list); if ((config = fopen(gfarm_config_file, "r")) == NULL) { return ("gfarm.conf: cannot read"); } e = gfarm_config_read_file(config, gfarm_config_file); if (e != NULL) return (e); gfarm_config_set_default1(); return (NULL); } #ifdef STRTOKEN_TEST main() { char buffer[1024]; char *cursor, *token, *error; while (fgets(buffer, sizeof buffer, stdin) != NULL) { cursor = buffer; while ((token = strtoken(&cursor, &error)) != NULL) printf("token: <%s>\n", token); if (error == NULL) printf("newline\n"); else printf("error: %s\n", error); } } #endif char *gfarm_debug_command; char gfarm_debug_pid[GFARM_INT32STRLEN]; static int gfarm_call_debugger(void) { int pid; if ((pid = fork()) == 0) { execlp("xterm", "xterm", "-e", "gdb", gfarm_debug_command, gfarm_debug_pid, NULL); perror("xterm"); _exit(1); } return (pid); } int gfarm_attach_debugger(void) { int pid = gfarm_call_debugger(); /* not really correct way to wait until attached, but... */ sleep(5); return (pid); } void gfarm_sig_debug(int sig) { int pid, status; static char message[] = "signal 00 caught\n"; message[7] = sig / 10 + '0'; message[8] = sig % 10 + '0'; write(2, message, sizeof(message) - 1); pid = gfarm_call_debugger(); if (pid == -1) perror("fork"); else waitpid(pid, &status, 0); } void gfarm_debug_initialize(char *command) { gfarm_debug_command = command; sprintf(gfarm_debug_pid, "%d", getpid()); signal(SIGQUIT, gfarm_sig_debug); signal(SIGILL, gfarm_sig_debug); signal(SIGTRAP, gfarm_sig_debug); signal(SIGABRT, gfarm_sig_debug); signal(SIGFPE, gfarm_sig_debug); signal(SIGBUS, gfarm_sig_debug); signal(SIGSEGV, gfarm_sig_debug); } /* * redirect stdout */ static char * gfarm_redirect_file(int fd, char *file, GFS_File *gf) { int nfd; char *e; if (file == NULL) return (NULL); e = gfs_pio_create(file, GFARM_FILE_WRONLY, 0644, gf); if (e != NULL) return (e); e = gfs_pio_set_view_local(*gf, 0); if (e != NULL) return (e); nfd = gfs_pio_fileno(*gf); if (nfd == -1) return (gfarm_errno_to_error(errno)); /* * This assumes the file fragment is created in the local * spool. */ if (dup2(nfd, fd) == -1) e = gfarm_errno_to_error(errno); /* XXX - apparently violate the layer */ ((struct gfs_file_section_context *)(*gf)->view_context)->fd = fd; (*gf)->mode &= ~GFS_FILE_MODE_CALC_DIGEST; close(nfd); return (e); } /* * eliminate arguments added by the gfrun command. */ static GFS_File gf_stdout, gf_stderr; char * gfarm_parse_argv(int *argcp, char ***argvp) { int total_nodes = -1, node_index = -1; int argc = *argcp; char **argv = *argvp; char *argv0 = *argv; int call_set_local = 0; char *stdout_file = NULL, *stderr_file = NULL, *e; --argc; ++argv; while (argc > 0 && argv[0][0] == '-' && argv[0][1] == '-') { if (strcmp(&argv[0][2], "gfarm_index") == 0) { --argc; ++argv; if (argc > 0) node_index = strtol(*argv, NULL, 0); call_set_local |= 1; } else if (strcmp(&argv[0][2], "gfarm_nfrags") == 0) { --argc; ++argv; if (argc > 0) total_nodes = strtol(*argv, NULL, 0); call_set_local |= 2; } else if (strcmp(&argv[0][2], "gfarm_stdout") == 0) { --argc; ++argv; if (argc > 0) stdout_file = *argv; } else if (strcmp(&argv[0][2], "gfarm_stderr") == 0) { --argc; ++argv; if (argc > 0) stderr_file = *argv; } else break; --argc; ++argv; } if (call_set_local == 3) { e = gfs_pio_set_local(node_index, total_nodes); if (e != NULL) return (e); /* redirect stdout and stderr */ if (stdout_file != NULL) { e = gfarm_redirect_file(1, stdout_file, &gf_stdout); if (e != NULL) return (e); } if (stderr_file != NULL) { e = gfarm_redirect_file(2, stderr_file, &gf_stderr); if (e != NULL) return (e); } ++argc; --argv; *argcp = argc; *argv = argv0; *argvp = argv; } return (NULL); } /* * the following function is for client, * server/daemon process shouldn't call it. * Because this function may read incorrect setting from user specified * $USER or $HOME. */ char * gfarm_initialize(int *argcp, char ***argvp) { char *e; gfarm_error_initialize(); e = gfarm_set_local_user_for_this_local_account(); if (e != NULL) return (e); e = gfarm_config_read(); if (e != NULL) return (e); e = gfarm_set_global_user_for_this_local_account(); if (e != NULL) return (e); e = gfarm_metadb_initialize(); if (e != NULL) return (e); gfarm_config_set_default2(); if (argvp != NULL) { gfarm_debug_initialize((*argvp)[0]); e = gfarm_parse_argv(argcp, argvp); if (e != NULL) return (e); } gfarm_initialized = 1; return (NULL); } /* the following function is for server. */ char * gfarm_server_initialize(void) { char *e; gfarm_error_initialize(); e = gfarm_server_config_read(); if (e != NULL) return (e); gfarm_config_set_default2_server(); return (NULL); } /* * the following function is for client, * server/daemon process shouldn't call it. * Because this function may read incorrect setting from user specified * $USER or $HOME. */ char * gfarm_terminate(void) { char *e; if (gf_stdout != NULL) { fflush(stdout); e = gfs_pio_close(gf_stdout); if (e != NULL) return (e); } if (gf_stderr != NULL) { fflush(stderr); e = gfs_pio_close(gf_stderr); if (e != NULL) return (e); } e = gfarm_metadb_terminate(); if (e != NULL) return (e); return (NULL); } /* the following function is for server. */ char * gfarm_server_terminate(void) { /* nothing to do (and also may never be called) */ return (NULL); } #ifdef CONFIG_TEST main() { char *e; gfarm_error_initialize(); e = gfarm_set_local_user_for_this_local_account(); if (e) { fprintf(stderr, "gfarm_set_local_user_for_this_local_account(): %s\n", e); exit(1); } e = gfarm_config_read(); if (e) { fprintf(stderr, "gfarm_config_read(): %s\n", e); exit(1); } printf("gfarm_spool_root = <%s>\n", gfarm_spool_root); printf("gfarm_spool_server_port = <%d>\n", gfarm_spool_server_port); printf("gfarm_metadb_server_name = <%s>\n", gfarm_metadb_server_name); printf("gfarm_metadb_server_port = <%d>\n", gfarm_metadb_server_name); printf("gfarm_ldap_server_name = <%s>\n", gfarm_ldap_server_name); printf("gfarm_ldap_server_port = <%s>\n", gfarm_ldap_server_port); printf("gfarm_ldap_base_dn = <%s>\n", gfarm_ldap_base_dn); return (0); } #endif <file_sep>/gfarm/tags/gfarm_0_1/gftool/example/Makefile.inc bindir = $(default_bindir)/example <file_sep>/gfarm/tags/gfarm_1_0_2_rc1/doc/docbook/en/ref/man3/Makefile.inc DOCBOOK = \ gfarm_initialize.3 \ gfarm_strings_free_deeply.3 \ gfarm_terminate.3 \ gfarm_url_hosts_schedule.3 \ gfs_chdir.3 \ gfs_closedir.3 \ gfs_opendir.3 \ gfs_pio_close.3 \ gfs_pio_create.3 \ gfs_pio_eof.3 \ gfs_pio_error.3 \ gfs_pio_flush.3 \ gfs_pio_getc.3 \ gfs_pio_getline.3 \ gfs_pio_open.3 \ gfs_pio_putc.3 \ gfs_pio_putline.3 \ gfs_pio_puts.3 \ gfs_pio_read.3 \ gfs_pio_seek.3 \ gfs_pio_set_local.3 \ gfs_pio_set_view_index.3 \ gfs_pio_set_view_local.3 \ gfs_pio_ungetc.3 \ gfs_pio_write.3 \ gfs_readdir.3 \ gfs_realpath.3 \ gfs_stat.3 \ gfs_stat_free.3 \ gfs_unlink.3 \ gfs_utimes.3 \ gfs_glob_init.3 \ gfs_glob.3 \ gfs_glob_add.3 \ gfs_glob_free.3 <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_gfmd_postgresql.sh.in #! /bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on gfmd hosts. # It tries executing an SQL statement with 'psql' to check whether PostgreSQL # server is running. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Set path to 'psql' command. # PSQL=${PSQL:-"psql"} # # Export variables about connection to PostgreSQL server. # export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD # # Execute 'psql' command. # @GFARM_BINDIR@/gfservice-timeout $TIMEOUT \ psql -t -w -f - -c "SELECT COUNT(*) FROM seqnum;" > /dev/null 2>&1 PSQL_EXITCODE=$? if [ $PSQL_EXITCODE -ne 0 ]; then echo "not running" exit 0 fi echo "ok" exit 0 <file_sep>/gfarm/tags/gfarm_1_0_beta_5_rc1/snmptool/gmonitor3/gmonitor/app/SimpleGrapherApp.java /* * Created on 2003/07/14 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package gmonitor.app; import gmonitor.gui.DataTimeSpace; import gmonitor.gui.GraphMonitor; import gmonitor.gui.GraphMonitorModel; import gmonitor.gui.RawData; import gmonitor.gui.RawDataElement; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.Timer; import javax.swing.text.Document; /** * @author hkondo * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class SimpleGrapherApp extends SimpleGrapherBaseUI { String currentDirectoryPath = null; String setTargetHostName = null; String setTargetEventName = null; String setTargetUnitName = null; int initialDelay = 0; String[] selectedHostsForTotal = null; DataTimeSpace dtSpace = null; ArrayList rawDataSeries = new ArrayList(); GraphMonitorModel model = new GraphMonitorModel(); private int autoUpdateInterval = 5; // second Timer timer = new Timer(autoUpdateInterval * 1000, new TimerAutoUpdateAction()); private boolean timerInitFlag; private int resampleResolution = 100; // second File selectedDir = null; // for use of Auto updating. JFrame appFrame = new JFrame(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String propDataPathPrefix = null; ArrayList propDataFileList = new ArrayList(); // String[] ArrayList propHostList = new ArrayList(); // String[] String propEvent = null; boolean propTotalMode = false; boolean propDiffMode = false; // direct. boolean propAutoUpdate = false; boolean propLineStyle = true; boolean propBarStyle = true; boolean propPlotStyle = true; double propMultiplier = 1.0; boolean propControllerVisibility = true; boolean propStylePanelVisibility = true; boolean propUnitPanelVisibility = true; boolean propMenuBarVisibility = true; boolean propInformationPanelVisibility = true; private double savedInfoWidth = 0; private double savedInfoHeight = 0; private Dimension savedDimension = null; private Dimension savedDimension2 = null; private boolean repaintFlag = false; private long magnificationY = 1; // Y scale /* private static final String[] UNIT_PREFIX_TABLE = new String[]{ "", //10^0 "K",// 10^3 "M",// 10^6 "G",// 10^9 "T",// 10^12 "P",// 10^15 "E",// 10^18 "Z",// 10^21 "Y",// 10^24 }; */ private static final String[] UNIT_PREFIX_TABLE = new String[]{ "", "x 10^3", "x 10^6", "x 10^9", "x 10^12", "x 10^15", "x 10^18", "x 10^21", "x 10^24" }; private void initializeFromProperty(String pref) { ArrayList propDataFileList = extractCSV(System.getProperty(pref + "DataFileList")); ArrayList propHostList = extractCSV(System.getProperty(pref + "HostList")); propTotalMode = getBooleanWithDefault(pref + "TotalMode", propTotalMode); propDiffMode = getBooleanWithDefault(pref + "DiffMode", propDiffMode); propAutoUpdate= getBooleanWithDefault(pref + "AutoUpdate",propAutoUpdate); propLineStyle = getBooleanWithDefault(pref + "LineStyle", propLineStyle); propBarStyle = getBooleanWithDefault(pref + "BarStyle", propBarStyle); propPlotStyle = getBooleanWithDefault(pref + "PlotStyle", propPlotStyle); propMultiplier =getDoubleWithDefault(pref + "Multiplier",propMultiplier); propControllerVisibility = getBooleanWithDefault(pref + "ControllerVisibility", propControllerVisibility); propStylePanelVisibility = getBooleanWithDefault(pref + "StylePanelVisibility", propStylePanelVisibility); propMenuBarVisibility = getBooleanWithDefault(pref + "MenuBarVisibility", propMenuBarVisibility); } private void initializeEventHandlers() { MenuItemFileOpenAction a = new MenuItemFileOpenAction(); menuItemFileOpen.addActionListener(a); buttonFileOpen.addActionListener(a); menuItemFileAutoUpdate.addActionListener(new FileAutoUpdateAction()); menuItemFileExit.addActionListener(new MenuItemFileExitAction()); buttonUpdateNow.addActionListener(new RepaintRepack()); comboEvent.addActionListener(new ComboEventSelectionAction()); comboHostname.addActionListener(new ComboHostnameSelectionAction()); checkGraphStyleBar.addActionListener(new CheckBoxBarAction()); checkGraphStyleLine.addActionListener(new CheckBoxLineAction()); checkGraphStylePlot.addActionListener(new CheckBoxPlotAction()); checkDifferentialMode.addActionListener(new CheckBoxDifferentialModeAction()); check8times.addActionListener(new CheckBox8timesAction()); check1000times.addActionListener(new CheckBox1000timesAction()); check100div.addActionListener(new CheckBox100divAction()); checkTotal.addActionListener(new CheckBoxTotalAction()); checkAutoUpdate.addActionListener(new CheckBoxAutoUpdateAction()); menuItemGraphStyleBar.addActionListener(new MenuItemGraphStyleBarAction()); menuItemGraphStyleLine.addActionListener(new MenuItemGraphStyleLineAction()); menuItemGraphStylePlot.addActionListener(new MenuItemGraphStylePlotAction()); menuItemDifferentialMode.addActionListener(new MenuItemDifferentialModeAction()); menuItem8times.addActionListener(new MenuItem8timesAction()); menuItem1000times.addActionListener(new MenuItem1000timesAction()); menuItem100div.addActionListener(new MenuItem100divAction()); menuItemTotal.addActionListener(new MenuItemTotalAction()); menuItemAutoUpdate.addActionListener(new MenuItemAutoUpdateAction()); RadioAction ra = new RadioAction(); radioMenuNone.addActionListener(ra); radioMenubps.addActionListener(ra); radioMenuKB.addActionListener(ra); radioMenuLoad.addActionListener(ra); comboUnit.addActionListener(new ComboUnitSelectionAction()); menuItemAutoUpdateInterval.addActionListener(new AutoUpdateIntervalAction()); menuItemAutoUpdateInterval.setText(menuStrAutoUpdateInterval + " ("+String.valueOf(autoUpdateInterval)+")"); menuItemResolution.addActionListener(new ResampleResoAction()); menuItemResolution.setText(menuStrResolution + " ("+String.valueOf(resampleResolution)+")"); menuItemRepaint.addActionListener(new RepaintRepack()); RepaintNow rn = new RepaintNow(); menuItemRaw.addActionListener(rn); ResampleAction resampleAct = new ResampleAction(); menuItemBefore.addActionListener(resampleAct); menuItemInterpolate.addActionListener(resampleAct); // visible menuItemVisInfo.addActionListener(new VisibleInfoAction()); menuItemVisInfo.setSelected(true); menuItemVisGraphStyle.addActionListener(new VisibleStyleAction()); menuItemVisGraphStyle.setSelected(true); menuItemVisUnit.addActionListener(new VisibleUnitAction()); menuItemVisUnit.setSelected(true); menuItemVisController.addActionListener(new VisibleControllerAction()); menuItemVisController.setSelected(true); graphPane.addMouseListener(new GraphMouseAction()); } private void initializeGUIComponents() { appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textBeginTime.setText(dateFormat.format(new Date())); textRange.setText("3600"); checkAutoUpdate.setSelected(propAutoUpdate); checkTotal.setSelected(propTotalMode); checkGraphStyleBar.setSelected(propBarStyle); menuItemGraphStyleBar.setSelected(propBarStyle); checkGraphStylePlot.setSelected(propPlotStyle); menuItemGraphStylePlot.setSelected(propPlotStyle); checkGraphStyleLine.setSelected(propLineStyle); menuItemGraphStyleLine.setSelected(propLineStyle); } class GraphMouseAction implements MouseListener { private boolean rightFlag; int click; public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { click = e.getClickCount(); if (click >= 2){ System.out.println("click = " + click); } rightFlag = false; // Linux event(e); } public void mouseReleased(MouseEvent e) { // Windows event(e); if(rightFlag == false && click >= 2){ System.out.println("x2"); magnificationY *= 2; paintGraphAccordingToCurrentGUIStatus(); } } private void event(MouseEvent e){ if (e.isPopupTrigger() && rightFlag == false) { if (click == 1){ System.out.println("/2"); magnificationY /= 2; if(magnificationY <= 0){ magnificationY = 1; } } else if (click == 2){ System.out.println("Reset"); magnificationY = 1; // reset } paintGraphAccordingToCurrentGUIStatus(); rightFlag = true; } } } class ResampleAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { dtSpace.initResampingMode(); paintGraphAccordingToCurrentGUIStatus(); } } class VisibleInfoAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { panelInformation.setVisible(menuItemVisInfo.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class VisibleStyleAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { panelGraphStyle.setVisible(menuItemVisGraphStyle.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class VisibleUnitAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { panelUnit.setVisible(menuItemVisUnit.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class VisibleControllerAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { panelController.setVisible(menuItemVisController.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class RadioAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { if(((JRadioButtonMenuItem) arg0.getSource()).equals(radioMenubps)){ menuItem8times.setSelected(true); check8times.setSelected(true); menuItemDifferentialMode.setSelected(true); checkDifferentialMode.setSelected(true); } else { menuItem8times.setSelected(false); check8times.setSelected(false); menuItemDifferentialMode.setSelected(false); checkDifferentialMode.setSelected(false); } comboUnit.setSelectedItem((JRadioButtonMenuItem) arg0.getSource()); paintGraphAccordingToCurrentGUIStatus(); } } class AutoUpdateIntervalAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { String interval = JOptionPane.showInputDialog( appFrame, "AutoUpdate Interval (second)", String.valueOf(autoUpdateInterval)); try { if(interval != null){ System.out.println("AutoUpdateInterval " + interval); int tmp = Integer.parseInt(interval); if(tmp <= 0){ return; } autoUpdateInterval = tmp; menuItemAutoUpdateInterval.setText(menuStrAutoUpdateInterval + " ("+interval+")"); timer.setDelay(autoUpdateInterval * 1000); } } catch(Exception e){ } } } class ResampleResoAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { String interval = JOptionPane.showInputDialog( appFrame, "Resampling Resolution (second)", String.valueOf(resampleResolution)); try { if(interval != null){ System.out.println("ResampleResolution " + interval); int tmp = Integer.parseInt(interval); if(tmp <= 0){ return; } resampleResolution = tmp; menuItemResolution.setText(menuStrResolution + " ("+interval+")"); } } catch(Exception e){ } paintGraphAccordingToCurrentGUIStatus(); } } class ComboUnitSelectionAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { ((JRadioButtonMenuItem)comboUnit.getSelectedItem()).setSelected(true); ((JRadioButtonMenuItem)comboUnit.getSelectedItem()).doClick(); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBoxBarAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItemGraphStyleBar.setSelected(checkGraphStyleBar.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBoxLineAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItemGraphStyleLine.setSelected(checkGraphStyleLine.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBoxPlotAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItemGraphStylePlot.setSelected(checkGraphStylePlot.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBoxDifferentialModeAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItemDifferentialMode.setSelected(checkDifferentialMode.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBox8timesAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItem8times.setSelected(check8times.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBox1000timesAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItem1000times.setSelected(check1000times.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class CheckBox100divAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItem100div.setSelected(check100div.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } private JDialog jd; private JList list; private boolean totalOkFlag; private void actionTotal(boolean b){ totalOkFlag = false; boolean timerFlag; if(timer.isRunning()){ timer.stop(); timerFlag = true; } else { timerFlag = false; } if(b == true){ jd = new JDialog(appFrame, "select hosts", true); JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); ArrayList hostList = new ArrayList(); DefaultComboBoxModel cmbmodel = (DefaultComboBoxModel) comboHostname.getModel(); int count = cmbmodel.getSize(); if(count <= 1){ checkTotal.setSelected(false); menuItemTotal.setSelected(false); comboHostname.setEnabled(true); return; } for(int i = 0; i < count; i++){ String host = (String) cmbmodel.getElementAt(i); hostList.add(host); //hostList.add("****************************"); } String[] tmp = new String[hostList.size()]; String[] listData = (String[]) hostList.toArray(tmp); list = new JList(listData); JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] h = list.getSelectedValues(); if(h == null || h.length <= 1){ return; } selectedHostsForTotal = new String[h.length]; System.out.println("--- Total ---"); for(int i=0; i<h.length; i++){ selectedHostsForTotal[i] = (String) h[i]; System.out.println(h[i]); } jd.setVisible(false); jd = null; totalOkFlag = true; } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jd.setVisible(false); jd = null; totalOkFlag = false; } }); jp.add(new JScrollPane(list), BorderLayout.NORTH); jp.add(ok, BorderLayout.CENTER); jp.add(cancel, BorderLayout.EAST); jp.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); jd.setContentPane(jp); jd.pack(); jd.setLocationRelativeTo(appFrame); jd.setVisible(true); } if(totalOkFlag == true){ comboHostname.setEnabled(false); } else{ checkTotal.setSelected(false); menuItemTotal.setSelected(false); comboHostname.setEnabled(true); } if(timerFlag == true){ timer.start(); } else { paintGraphAccordingToCurrentGUIStatus(); } } class CheckBoxTotalAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { JCheckBox c = checkTotal; menuItemTotal.setSelected(c.isSelected()); actionTotal(c.isSelected()); } } private void actionAutoUpdate(boolean check, boolean choice){ if(check == true){ if(choice == true) { initialDelay = -1; dialogDirOpen.setDialogTitle("Choose the directory where .glg files are contained"); if(currentDirectoryPath != null){ String path; try { File f = new File(currentDirectoryPath); if(f.exists()){ path = f.getCanonicalPath(); } else { path = ""; } } catch (IOException e) { path = currentDirectoryPath; } System.out.println(path); dialogDirOpen.setCurrentDirectory(new File(path)); } int ret = dialogDirOpen.showOpenDialog(appFrame); if(ret == JFileChooser.APPROVE_OPTION){ selectedDir = dialogDirOpen.getSelectedFile(); System.out.println(selectedDir.getPath()); } else { menuItemAutoUpdate.setSelected(false); checkAutoUpdate.setSelected(false); return; } } else { selectedDir = new File(currentDirectoryPath); if(selectedDir.exists() == false){ menuItemAutoUpdate.setSelected(false); checkAutoUpdate.setSelected(false); return; } System.out.println(selectedDir.getPath()); } if(selectedDir == null){ // Cannot auto update because no data folder is selected. JOptionPane.showMessageDialog(appFrame, "No logdata is specified. Open logfile first."); //c.setEnabled(false); //c.setSelected(false); //c.setEnabled(true); menuItemAutoUpdate.setSelected(false); checkAutoUpdate.setSelected(false); return; } textBeginTime.setEnabled(false); //textRange.setEnabled(false); if(timer.isRunning()){ timer.stop(); } // schedule the first event in 1 milli-sec future. //if(initialDelay > 0) { // timer.setInitialDelay(initialDelay * 1000); // initialDelay = -1; //} else { timer.setInitialDelay(0); //} // start Swing timer to update. timerInitFlag = false; timer.start(); //paintGraphAccordingToCurrentGUIStatus(); return; }else{ textBeginTime.setEnabled(true); textRange.setEnabled(true); // stop Swing timer. timer.stop(); return; } } class FileAutoUpdateAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkAutoUpdate.setSelected(true); menuItemAutoUpdate.setSelected(true); actionAutoUpdate(true, true); } } class CheckBoxAutoUpdateAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { JCheckBox c = checkAutoUpdate; menuItemAutoUpdate.setSelected(c.isSelected()); actionAutoUpdate(c.isSelected(), true); } } class TimerAutoUpdateAction implements ActionListener { // This listener is invoked when the Swing timer was exceeded // the update interval. synchronized public void actionPerformed(ActionEvent arg0) { //System.out.println("AutoUpdate"); // scan directory contents in selectedDir and rebuild // data-time space. File[] files = selectedDir.listFiles(new FileFilter(){ public boolean accept(File f){ if( (f.isFile() == true) && (f.getName().endsWith(".glg") == true) ){ return true; }else{ return false; } } }); if(files == null){ System.out.println("AutoUpdate: no .glg file"); return; } String[] filenames = new String[files.length]; for(int i = 0; i < files.length; i++){ filenames[i] = files[i].getPath(); } try { dtSpace = new DataTimeSpace(filenames); // hostname, event name, count of them should not be changed. // obtain the latest time from date-time space, and back to past in range seconds. long t = dtSpace.getLatestDateTime(); long r = Long.parseLong(textRange.getText()) * 1000L; String dt = dateFormat.format(new Date(t - r)); textBeginTime.setText(dt); if(timerInitFlag == false){ defineNewComboBox(comboHostname, dtSpace.getHostnames()); defineNewComboBox(comboEvent, dtSpace.getEvents()); setComboTargets(); timerInitFlag = true; } // repaint graph according to GUI switches. paintGraphAccordingToCurrentGUIStatus(); } catch (IOException e) { // cannot create data-time space. String msg = "File open error."; //JOptionPane.showMessageDialog(appFrame, msg); System.out.println(msg); //e.printStackTrace(); } } } class MenuItemGraphStyleBarAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkGraphStyleBar.setSelected(menuItemGraphStyleBar.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItemGraphStyleLineAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkGraphStyleLine.setSelected(menuItemGraphStyleLine.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItemGraphStylePlotAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkGraphStylePlot.setSelected(menuItemGraphStylePlot.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItemDifferentialModeAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkDifferentialMode.setSelected(menuItemDifferentialMode.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItem8timesAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { check8times.setSelected(menuItem8times.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItem1000timesAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { check1000times.setSelected(menuItem1000times.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItem100divAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { check100div.setSelected(menuItem100div.isSelected()); paintGraphAccordingToCurrentGUIStatus(); } } class MenuItemTotalAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkTotal.setSelected(menuItemTotal.isSelected()); actionTotal(menuItemTotal.isSelected()); } } class MenuItemAutoUpdateAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { checkAutoUpdate.setSelected(menuItemAutoUpdate.isSelected()); actionAutoUpdate(menuItemAutoUpdate.isSelected(), true); } } /* * Event selection is changed event handler of ComboBox. * @author hkondo */ class ComboEventSelectionAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { setTargetEventName = (String) comboEvent.getSelectedItem(); paintGraphAccordingToCurrentGUIStatus(); } } /* * Hostname selection is changed event handler of ComboBox. * @author hkondo */ class ComboHostnameSelectionAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { setTargetHostName = (String) comboHostname.getSelectedItem(); paintGraphAccordingToCurrentGUIStatus(); } } /* * "Repaint" Event handler of Button. * @author hkondo */ class RepaintRepack implements ActionListener { public void actionPerformed(ActionEvent arg0) { repaintFlag = true; paintGraphAccordingToCurrentGUIStatus(); repaintFlag = false; } } class RepaintNow implements ActionListener { public void actionPerformed(ActionEvent arg0) { paintGraphAccordingToCurrentGUIStatus(); } } /* * "File" - "Exit" Event handler of Menu item. * @author hkondo */ class MenuItemFileExitAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { System.exit(0); } } private void defineNewComboBox(JComboBox box, String[] items) { DefaultComboBoxModel cmodel = new DefaultComboBoxModel(); for(int i = 0; i < items.length; i++){ cmodel.addElement(items[i]); } if(items.length > 0){ cmodel.setSelectedItem(items[0]); } box.setModel(cmodel); } private long getBeginDate() throws ParseException { Date d = dateFormat.parse(textBeginTime.getText()); return d.getTime(); } private long getTimeRange() throws ParseException { return Long.parseLong(textRange.getText()) * 1000; } private String createTitle(String host, String event) { return host + " " + event; } private String createAxisLabelX(String event) { return "Date and Time"; } private String createAxisLabelY(String event) { String ret = event; String e = event.toLowerCase(); if(e.startsWith("available") == true){ ret = "Available Disk space"; }else if(e.startsWith("used") == true){ ret = "Used Disk space"; }else if(e.startsWith("eth") == true){ if(e.indexOf("out") > 0){ ret = "TX Bandwidth"; }else if(e.indexOf("in") > 0){ ret = "RX Bandwidth"; }else{ ret = "Network bandwidth"; } }else if(e.startsWith("loadavg") == true){ ret = "Load average (x100)"; } return ret; } private String createUnit(String event) { String ret = "."; String e = event.toLowerCase(); if(e.startsWith("available") == true){ ret = "bytes"; }else if(e.startsWith("used") == true){ ret = "bytes"; }else if(e.startsWith("eth") == true){ ret = "bps"; }else if(e.startsWith("loadavg") == true){ ret = ""; } return ret; } protected int prefixIndex(long v) { long factor = 0; int prefix_index = 0; for(int i = 1; i < UNIT_PREFIX_TABLE.length; i++){ factor = (long) Math.pow(10, i * 3); prefix_index = i - 1; if( (v / factor) <= 1 ){ // i - 1 hit. break; } } //System.out.println("prefix_index " + prefix_index + " / " + v); return prefix_index; } private boolean initFlag = true; private void paintGraphAccordingToCurrentGUIStatus() { if(dtSpace == null){ // No data-time space, Nothing to do. return; } String unit = ""; String unitName = ((JRadioButtonMenuItem)comboUnit.getSelectedItem()).getText(); if(unitName.equals(SimpleGrapherBaseUI.unitKB)){ unit += " KB"; } else if(unitName.equals(SimpleGrapherBaseUI.unitNone)){ unit += ""; } else if(unitName.equals(SimpleGrapherBaseUI.unitbps)){ unit += " bps"; } else if(unitName.equals(SimpleGrapherBaseUI.unitLoad)){ unit += " %"; } boolean diffmode = checkDifferentialMode.isSelected(); boolean totalmode= checkTotal.isSelected(); boolean automode = checkAutoUpdate.isSelected(); GraphMonitor gm = SimpleGrapherApp.this.getGraphPane(); String event= (String) comboEvent.getSelectedItem(); ArrayList hostList = new ArrayList(); if(totalmode == true){ for(int i = 0; i < selectedHostsForTotal.length; i++){ hostList.add(selectedHostsForTotal[i]); } // DefaultComboBoxModel cmbmodel = (DefaultComboBoxModel) comboHostname.getModel(); // int count = cmbmodel.getSize(); // for(int i = 0; i < count; i++){ // String host = (String) cmbmodel.getElementAt(i); // hostList.add(host); // } }else{ String host = (String) comboHostname.getSelectedItem(); hostList.add(host); } long begin = 0; long term = 0; rawDataSeries.clear(); try{ begin = getBeginDate(); //System.out.println("getBeginDate() " + begin); term = getTimeRange(); model.setBegin(begin); model.setTerm(term); }catch(ParseException e1) { JOptionPane.showMessageDialog(appFrame, "Invalid date time format, correct Begin Time or Time Range"); return; } for(int h = 0; h < hostList.size(); h++){ String host = (String) hostList.get(h); try { // extract data from data-time space. ArrayList dt = dtSpace.getMeasurementData(host, event, begin, term); if(menuItemBefore.isSelected()){ dt = dtSpace.resampleBeforeDateDataPairListToRawDataElements(dt, resampleResolution); } else if(menuItemInterpolate.isSelected()){ dt = dtSpace.resampleEstimateDateDataPairListToRawDataElements(dt, resampleResolution); } ArrayList rde = dtSpace.convertDateDataPairListToRawDataElements(dt, diffmode); RawData rd = new RawData(); rd.setValid(true); RawDataElement[] rda = new RawDataElement[rde.size()]; rda = (RawDataElement[]) rde.toArray(rda); int magnification = 1; int rate = 1; if(check8times.isSelected() == true){ magnification *= 8; } if(check1000times.isSelected() == true){ magnification *= 1000; } if(check100div.isSelected() == true){ rate *= 100; } if(magnification > 1 || rate > 1){ for(int i=0; i<rda.length; i++){ rda[i].setValue(rda[i].getValue() * magnification / rate); } } rd.setData(rda); rawDataSeries.add(rd); } catch (IOException e) { // cannot create model because specified time is out of range. // null clear. e.printStackTrace(); JOptionPane.showMessageDialog(appFrame, host + " does not exist into the data file."); gm.setModel(null); if(totalmode == true){ // total off checkTotal.setSelected(false); menuItemTotal.setSelected(false); comboHostname.setEnabled(true); } return; } } if(totalmode == true){ rawDataSeries = totalofRawDataSeries(rawDataSeries); } for(int z = 0; z < rawDataSeries.size(); z++){ RawData rd = (RawData) rawDataSeries.get(z); rd.setDiffMode(diffmode); rd.setMax(model.getTopValue()); } model.setRawDataSeries(rawDataSeries, magnificationY); //int prefixIndex = prefixIndex(model.getMaxValue()); int prefixIndex = prefixIndex(model.getTopValue()); int cooked_prefixIndex = cookPrefixIndex(prefixIndex, event); String prefix = UNIT_PREFIX_TABLE[cooked_prefixIndex]; long prefixFactor = (long) Math.pow(1000, prefixIndex); // not cooked. model.setPrefixFactor(prefixFactor); model.setSumMode(totalmode); String labelAxisX = createAxisLabelX(event); String labelAxisY = ""; //String labelAxisY = createAxisLabelY(event); /* String unit = createUnit(event); if(unit.length() > 0){ //labelAxisY += " (" + prefix + createUnit(event) + ")"; } */ if(unit == null || unit.equals("")){ labelAxisY = prefix; } else { labelAxisY = prefix + " (" + unit + ")"; } gm.setStyleFill(checkGraphStyleBar.isSelected()); gm.setStyleJoin(checkGraphStyleLine.isSelected()); gm.setStylePlot(checkGraphStylePlot.isSelected()); String host = ""; if(totalmode == true){ host = "Total of "; }else{ host = (String) comboHostname.getSelectedItem(); } gm.setTitle(createTitle(host, event)); gm.setModel(model); gm.setAxisLabelX(labelAxisX); // set label of x-axis gm.setAxisLabelY(labelAxisY); // set label of y-axis String ls = System.getProperty("line.separator"); DecimalFormat df = new DecimalFormat("###,###,##0"); Document doc = txtInfo.getDocument(); String info = ""; info += "Latest (" + dateString(model.getLatestValueTime()) + "): "+ df.format(model.getLatestValue()) + unit + ls; info += "Max (" + dateString(model.getMaxValueTime()) + "): " + df.format(model.getMaxValue()) + unit + ls; info += "Min (" + dateString(model.getMinValueTime()) + "): " + df.format(model.getMinValue()) + unit + ls; //info += "min (" + dateString(model.getMinValueTime()) + "): " + df.format(Long.MAX_VALUE) + unit + ls; info += "Average: " + df.format((long) Math.rint(model.getAvgValue())) + unit; if(totalmode == true){ info += ls + "Total: " + event + " ("; int i = 0; while(true){ info += selectedHostsForTotal[i]; if( i < selectedHostsForTotal.length - 1){ info += ", "; } else { info += ")"; break; } i++; } } txtInfo.setText(info); txtInfo.repaint(); if(initFlag){ initFlag = false; } if(repaintFlag) { //txtInfoScroll.setMinimumSize(txtInfo.getSize()); Dimension windowSize = appFrame.getSize(); // save appFrame.pack(); appFrame.setSize(windowSize); //System.out.println(windowSize.getWidth() + " " + windowSize.getHeight()); } gm.repaint(); appFrame.repaint(); } public static String dateString(long t){ DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); return df.format(new Date(t)); } private int cookPrefixIndex(int prefixIndex, String event) { int ret = prefixIndex; String e = event.toLowerCase(); if(e.startsWith("available") == true){ //ret++; }else if(e.startsWith("used") == true){ //ret++; }else if(e.startsWith("eth") == true){ // Nothing to do. }else if(e.startsWith("loadavg") == true){ //ret = 0; } return ret; } private ArrayList totalofRawDataSeries(ArrayList rawDataSeries) { RawData[] rda = new RawData[rawDataSeries.size()]; rda = (RawData[]) rawDataSeries.toArray(rda); RawDataElement[] rde = total(rda); ArrayList newList = new ArrayList(); RawData newData = new RawData(); newData.setMax(rda[0].getMax()); newData.setBarColor(rda[0].getBarColor()); newData.setLevelColor(rda[0].getLevelColor()); newData.setLineColor(rda[0].getLineColor()); newData.setPlotColor(rda[0].getPlotColor()); newData.setDiffMode(rda[0].isDiffmode()); newData.setValid(true); newData.setData(rde); newList.add(newData); return newList; } /* * "File" - "Open..." Event handler of Menu item. * @author hkondo */ class MenuItemFileOpenAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { menuItemAutoUpdate.setSelected(false); checkAutoUpdate.setSelected(false); textBeginTime.setEnabled(true); textRange.setEnabled(true); // stop Swing timer. timer.stop(); if(currentDirectoryPath != null){ String path; try { File f = new File(currentDirectoryPath); if(f.exists()){ path = f.getCanonicalPath(); } else { path = ""; } } catch (IOException e) { path = currentDirectoryPath; } System.out.println(path); dialogFileOpen.setCurrentDirectory(new File(path)); } int ret = dialogFileOpen.showOpenDialog(appFrame); if(ret == JFileChooser.APPROVE_OPTION){ // rebuild data-time space because files are specified. // TODO このとき、GUI の開始時刻フィールド値も更新する。時間幅フィールドを参考に、最新n秒がでるように。 File[] files = dialogFileOpen.getSelectedFiles(); selectedDir = files[0].getParentFile(); String[] filenames = new String[files.length]; for(int i = 0; i < files.length; i++){ filenames[i] = files[i].getPath(); } try { dtSpace = new DataTimeSpace(filenames); long begin = dtSpace.getBeginDateTime() - 500; long latest = dtSpace.getLatestDateTime(); String dt = dateFormat.format(new Date(begin)); textBeginTime.setText(dt); long r =(latest-begin)/1000; textRange.setText(""+r); //System.out.println("dtSpace.getBeginDateTime() " + begin); defineNewComboBox(comboHostname, dtSpace.getHostnames()); defineNewComboBox(comboEvent, dtSpace.getEvents()); paintGraphAccordingToCurrentGUIStatus(); } catch (IOException e) { // Cannot create datat-time space. e.printStackTrace(); String msg = "File open error."; JOptionPane.showMessageDialog(appFrame, msg); } } } } public void setOptions2(String args[]) { if(args.length >= 1){ currentDirectoryPath = args[0]; } else { currentDirectoryPath = null; } panelInformation.setVisible(false); menuItemVisInfo.setSelected(false); panelController.setVisible(false); menuItemVisController.setSelected(false); } public void printHelp(){ String ls = System.getProperty("line.separator"); String str = "usage: java -jar gmonitor3.jar [ -d TargetAutoUpdateDirectory ]" + ls; str += " [ -h TargetHostname ] [ -e TargetEventNickName ] " + ls; str += " [ -u UnitName(bps/KB/Load) ] [ --help ]" + ls; str += " [ --line ] [ --bar ] [ --plot ]" + ls; str += " [ --information ] [ --style ] [ --unit ] [ --controller ]"; System.err.println(str); } public void setOptions(String args[]) { int len = args.length; currentDirectoryPath = null; setTargetHostName = null; setTargetEventName = null; setTargetUnitName = null; //initialDelay = 0; // default 3 seconds for(int i = 0; i < len; i++){ String now = args[i]; if(now.startsWith("-")){ String opt = now.substring(1); if(opt.startsWith("d")){ if(++i < len){ currentDirectoryPath = args[i]; } else { System.err.println(""); printHelp(); System.exit(1); } } /* else if(opt.startsWith("d")){ if(++i < len){ try { initialDelay = Integer.parseInt(args[i]); } catch(NumberFormatException e){ // do nothing } } else { System.err.println(""); printHelp(); System.exit(1); } } */ else if(opt.startsWith("h")){ if(++i < len){ setTargetHostName = args[i]; } else { System.err.println(""); printHelp(); System.exit(1); } } else if(opt.startsWith("e")){ if(++i < len){ setTargetEventName = args[i]; } else { System.err.println(""); printHelp(); System.exit(1); } } else if(opt.startsWith("u")){ if(++i < len){ setTargetUnitName = args[i]; } else { System.err.println(""); printHelp(); System.exit(1); } } else if(opt.startsWith("-")){ String longopt = opt.substring(1); if(longopt.equals("line")){ menuItemGraphStyleLine.setSelected(false); checkGraphStyleLine.setSelected(false); } else if(longopt.equals("bar")){ menuItemGraphStyleBar.setSelected(false); checkGraphStyleBar.setSelected(false); } else if(longopt.equals("plot")){ menuItemGraphStylePlot.setSelected(false); checkGraphStylePlot.setSelected(false); } else if(longopt.equals("information")){ panelInformation.setVisible(false); menuItemVisInfo.setSelected(false); } else if(longopt.equals("style")){ panelGraphStyle.setVisible(false); menuItemVisGraphStyle.setSelected(false); } else if(longopt.equals("unit")){ panelUnit.setVisible(false); menuItemVisUnit.setSelected(false); } else if(longopt.equals("controller")){ panelController.setVisible(false); menuItemVisController.setSelected(false); } else if(longopt.equals("help")){ printHelp(); System.exit(1); } else { System.err.println("invalid option -- " + longopt); printHelp(); System.exit(1); } } else { System.err.println("invalid option -- " + opt); printHelp(); System.exit(1); } } } if(currentDirectoryPath != null){ checkAutoUpdate.setSelected(true); menuItemAutoUpdate.setSelected(true); actionAutoUpdate(true, false); } } public void setComboTargets(){ if(setTargetHostName != null){ for(int i=0; i<comboHostname.getItemCount(); i++){ //System.out.println((String)comboHostname.getItemAt(i)); if(setTargetHostName.equals((String)comboHostname.getItemAt(i))){ comboHostname.setSelectedItem(comboHostname.getItemAt(i)); break; } } //System.out.println(setTargetHostName); } if(setTargetEventName != null){ for(int i=0; i<comboEvent.getItemCount(); i++){ //System.out.println((String)comboEvent.getItemAt(i)); if(setTargetEventName.equals((String)comboEvent.getItemAt(i))){ comboEvent.setSelectedItem(comboEvent.getItemAt(i)); break; } } //System.out.println(setTargetEventName); } if(setTargetUnitName != null){ if(setTargetUnitName.equals("bps")){ comboUnit.setSelectedItem(radioMenubps); } else if(setTargetUnitName.equals("KB")){ comboUnit.setSelectedItem(radioMenuKB); } else if(setTargetUnitName.equals("Load")){ comboUnit.setSelectedItem(radioMenuLoad); } setTargetUnitName = null; } } public SimpleGrapherApp(String args[]) { initializeFromProperty("GMonitor."); initializeEventHandlers(); initializeGUIComponents(); JFrame f = appFrame; if(propMenuBarVisibility == true){ f.setJMenuBar(getMenubar()); } Container c = f.getContentPane(); JPanel allPanel = new JPanel(); GridBagConstraints gbc = new GridBagConstraints(); allPanel.setLayout(new GridBagLayout()); gbc.gridwidth = 2; gbc.gridy = 0; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; allPanel.add(getGraphPane(), gbc); gbc.gridy++; gbc.weightx = 0.0; gbc.weighty = 0.0; gbc.fill = GridBagConstraints.HORIZONTAL; if(propInformationPanelVisibility == true){ allPanel.add(getPanelInformation(), gbc); } gbc.gridy++; gbc.gridwidth = 1; if(propStylePanelVisibility == true){ allPanel.add(getPanelGraphStyle(), gbc); } if(propUnitPanelVisibility == true){ allPanel.add(getPanelUnit(), gbc); } gbc.gridy++; gbc.gridwidth = 2; if(propControllerVisibility == true){ allPanel.add(getPanelController(), gbc); } c.add(allPanel); //f.setLocationRelativeTo(null); //Point p = f.getLocation(); //Dimension d = f.getSize(); //f.setLocation(p.x - d.width/2, p.y - d.height/2); // Swing paint debugging with diabling double-bufferring. //RepaintManager rm = RepaintManager.currentManager(getGraphPane()); //rm.setDoubleBufferingEnabled(false); } public static void main(String[] args) { SimpleGrapherApp app = new SimpleGrapherApp(args); //app.setSize(400, 500); app.setTitle("GMonitor"); app.show(); app.pack(); app.setOptions(args); } /** * set frame size. * @param arg0 * @param arg1 */ public void setSize(int arg0, int arg1) { appFrame.setSize(arg0, arg1); } /** * set title of frame. * @param arg0 */ public void setTitle(String arg0) { appFrame.setTitle(arg0); } /** * control visibility of application frame. * @param arg0 */ public void setVisible(boolean arg0) { appFrame.setVisible(arg0); } /** * control visibility of application frame. */ public void show() { appFrame.show(); } public void pack(){ appFrame.pack(); } private RawDataElement[] total(RawData[] rda) { RawData newData = new RawData(); ArrayList newList = new ArrayList(); long time = 0; int series = rda.length; RawDataElement[] totalBuffer = new RawDataElement[series]; int[] scanIndex = new int[series]; long endTime[] = new long[series]; fillEndTime(endTime, rda); while(true){ // scan next element. time = scanNext(time, rda, scanIndex, totalBuffer); // add up values latched in total buffer and create new element. long v = addup(totalBuffer); RawDataElement ne = new RawDataElement(); ne.setTime(time); ne.setValue(v); ne.setValid(true); newList.add(ne); // termination ? if(isFinishedTime(time, endTime) == true){ break; } } RawDataElement[] rde = new RawDataElement[newList.size()]; rde = (RawDataElement[]) newList.toArray(rde); return rde; } private long scanNext(long time, RawData[] rda, int[] si, RawDataElement[] tb) { int series = rda.length; // with all series... long t = Long.MAX_VALUE; for(int s = 0; s < series; s++){ RawDataElement[] rde = rda[s].getData(); // finding the index of element that is exceeded time... int idx = findFirstExceededTime(time, rde); // ... and adopt the oldest element. if(idx < 0){ // not matched in this series. }else{ // temporary keeping. si[s] = idx; long tt = rde[idx].getTime(); if(t > tt){ t = tt; } } } // matched elements are latched in tb. If plural elements are matched, process them all. for(int s = 0; s < series; s++){ RawDataElement[] rde = rda[s].getData(); if(rde[si[s]].getTime() == t){ // should be latched in tb. tb[s] = rde[si[s]]; } } return t; } /** * @param time * @param rde * @return */ private int findFirstExceededTime(long time, RawDataElement[] rde) { for(int i = 0; i < rde.length; i++){ if(rde[i].isValid() == true){ if(rde[i].getTime() > time){ return i; } } } return -1; } private boolean isFinishedTime(long t, long[] endTime) { for(int i = 0; i < endTime.length; i++){ if(t < endTime[i]){ return false; } } // t >= endTime[all of]; return true; } private void fillEndTime(long[] endTime, RawData[] rda) { for(int i = 0; i < rda.length; i++){ RawDataElement[] rde = rda[i].getData(); endTime[i] = rde[rde.length - 1].getTime(); // TODO 有効な最後のデータを参照すること } return; } private long addup(RawDataElement[] rde) { long s = 0; for(int i = 0; i < rde.length; i++){ if(rde[i] != null){ s += rde[i].getValue(); } } return s; } } <file_sep>/gfarm/tags/gfarm_1_0_beta_5_fix1/lib/libgfarm/gfarm/io_gfsl.h struct xxx_connection; struct gfarmSecSession; struct gfarm_iobuffer; char *gfarm_gsi_server_initialize(void); char *xxx_connection_set_secsession(struct xxx_connection *, struct gfarmSecSession *); void xxx_connection_reset_secsession(struct xxx_connection *); void gfarm_iobuffer_write_close_secsession_op(struct gfarm_iobuffer *, void *, int); void xxx_connection_downgrade_to_insecure_session(struct xxx_connection *); <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfsl/tcputil.h extern int gfarmTCPConnectPort(unsigned long addr, int port); extern int gfarmTCPBindPort(int port); extern unsigned long int gfarmIPGetAddressOfHost(char *host); extern char * gfarmIPGetHostOfAddress(unsigned long int addr); extern unsigned long int gfarmIPGetNameOfSocket(int sock, int *portPtr); extern unsigned long int gfarmIPGetPeernameOfSocket(int sock, int *portPtr); extern int gfarmWaitReadable(int fd); extern int gfarmReadBytes(int fd, char *buf, int len); extern int gfarmReadShorts(int fd, short *buf, int len); extern int gfarmReadLongs(int fd, long *buf, int len); extern int gfarmWriteBytes(int fd, char *buf, int len); extern int gfarmWriteShorts(int fd, short *buf, int len); extern int gfarmWriteLongs(int fd, long *buf, int len); <file_sep>/gfarm/tags/gfarm_1_1_0_rc1/lib/libgfarm/gfsl/auth.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <limits.h> #include <sys/stat.h> #include <ctype.h> #include <pwd.h> #include <gfarm/gfarm_config.h> #include "hash.h" #include "gfutil.h" #include "gfsl_config.h" #include "gfarm_auth.h" #include "misc.h" #define AUTH_TABLE_SIZE 139 static struct gfarm_hash_table *authTable = NULL; #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS static struct gfarm_hash_table *userToDNTable = NULL; #endif #if 0 static void dumpAuthEntry(aePtr) gfarmAuthEntry *aePtr; { if (aePtr->authType != GFARM_AUTH_USER && aePtr->authType != GFARM_AUTH_HOST) { fprintf(stderr, "Invalid auth entry.\n"); return; } fprintf(stderr, "Type:\t%s\n", (aePtr->authType == GFARM_AUTH_USER) ? "user" : "host"); fprintf(stderr, "DN:\t%s\n", aePtr->distName); if (aePtr->authType == GFARM_AUTH_USER) { fprintf(stderr, "Local:\t%s\n", aePtr->authData.userAuth.localName); fprintf(stderr, "uid:\t%d\n", aePtr->authData.userAuth.uid); fprintf(stderr, "gid:\t%d\n", aePtr->authData.userAuth.gid); fprintf(stderr, "home:\t%s\n", aePtr->authData.userAuth.homeDir); fprintf(stderr, "shell:\t%s\n", aePtr->authData.userAuth.loginShell); } else { fprintf(stderr, "FQDN:\t%s\n", aePtr->authData.hostAuth.FQDN); } fprintf(stderr, "\n"); } #endif int gfarmAuthInitialize(usermapFile) char *usermapFile; { int ret = 1; if (authTable == NULL) { char mapFile[PATH_MAX]; FILE *mFd = NULL; char lineBuf[65536]; gfarmAuthEntry *aePtr; struct gfarm_hash_entry *ePtr; /* * Read global users -> local users mapping file * and create a translation table. */ if (usermapFile == NULL || usermapFile[0] == '\0') { char *confDir = gfarmGetEtcDir(); if (confDir == NULL) { gflog_auth_error("gfarmAuthInitialize()", "no memory"); ret = -1; goto done; } #ifdef HAVE_SNPRINTF snprintf(mapFile, sizeof mapFile, "%s/%s", confDir, GFARM_DEFAULT_USERMAP_FILE); #else sprintf(mapFile, "%s/%s", confDir, GFARM_DEFAULT_USERMAP_FILE); #endif usermapFile = mapFile; (void)free(confDir); } if ((mFd = fopen(usermapFile, "r")) == NULL) { gflog_auth_error(usermapFile, "cannot open"); ret = -1; goto done; } authTable = gfarm_hash_table_alloc(AUTH_TABLE_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (authTable == NULL) { /* no memory */ gflog_auth_error("gfarmAuthInitialize()", "no memory"); ret = -1; goto done; } #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS userToDNTable = gfarm_hash_table_alloc(AUTH_TABLE_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (userToDNTable == NULL) { /* no memory */ gflog_auth_error("gfarmAuthInitialize()", "no memory"); gfarm_hash_table_free(authTable); ret = -1; goto done; } #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ while (fgets(lineBuf, sizeof lineBuf, mFd) != NULL) { char *token[64]; int nToken = gfarmGetToken(lineBuf, token, sizeof token); char *distName = NULL; char *mode = NULL; char *localName = NULL; struct passwd *pPtr; int isNew; if (nToken <= 1) { continue; } if (*token[0] == '#') { continue; } distName = token[0]; if (nToken == 2) { mode = "@user@"; localName = token[1]; } else if (nToken >= 3) { mode = token[1]; localName = token[2]; } else if (nToken == 0) { continue; } else { gflog_warning(distName, "WARNING: missing local username for DN." " Ignored."); continue; } /* * Unquote distinguished name */ if (distName[0] == '\'' || distName[0] == '"') { int quote = distName[0]; int dLen = strlen(distName); dLen--; if (distName[dLen] == quote) { distName[dLen] = '\0'; distName++; } } if (strcmp(mode, "@user@") == 0) { pPtr = getpwnam(localName); if (pPtr == NULL) { gflog_auth_warning(localName, "WARNING: Account doesn't exist." " Ignored."); continue; } if (pPtr->pw_uid == 0) { gflog_warning(localName, "WARNING: This user is a super user." " Ignored."); continue; } aePtr = (gfarmAuthEntry *)malloc(sizeof(gfarmAuthEntry)); if (aePtr == NULL) { gflog_auth_error("gfarmAuthInitialize()", "no memory"); ret = -1; goto initDone; } (void)memset(aePtr, 0, sizeof(gfarmAuthEntry)); aePtr->sesRefCount = 0; aePtr->orphaned = 0; aePtr->authType = GFARM_AUTH_USER; aePtr->distName = strdup(distName); aePtr->authData.userAuth.localName = strdup(localName); aePtr->authData.userAuth.uid = pPtr->pw_uid; aePtr->authData.userAuth.gid = pPtr->pw_gid; aePtr->authData.userAuth.homeDir = strdup(pPtr->pw_dir); aePtr->authData.userAuth.loginShell = strdup(pPtr->pw_shell); #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS ePtr = gfarm_hash_enter(userToDNTable, localName, strlen(localName) + 1, sizeof(aePtr), &isNew); if (ePtr == NULL) { /* no memory */ gflog_warning(localName, "WARNING: no memory for DN. Ignored."); } else if (!isNew) { gflog_auth_warning(localName, "WARNING: multiple X.509 Distinguish name " "for a UNIX user account. Ignored."); } else { *(gfarmAuthEntry **)gfarm_hash_entry_data(ePtr) = aePtr; } #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ } else if (strcmp(mode, "@host@") == 0) { aePtr = (gfarmAuthEntry *)malloc(sizeof(gfarmAuthEntry)); if (aePtr == NULL) { gflog_auth_error("gfarmAuthInitialize()", "no memory"); ret = -1; goto initDone; } (void)memset(aePtr, 0, sizeof(gfarmAuthEntry)); aePtr->sesRefCount = 0; aePtr->orphaned = 0; aePtr->authType = GFARM_AUTH_HOST; aePtr->distName = strdup(distName); aePtr->authData.hostAuth.FQDN = strdup(localName); } else { gflog_warning(localName, "WARNING: Unknown keyword at second field." " Ignored."); continue; } ePtr = gfarm_hash_enter(authTable, aePtr->distName, strlen(aePtr->distName) + 1, sizeof(aePtr), &isNew); if (ePtr == NULL) { /* no memory */ gflog_warning(distName, "WARNING: no memory for DN. Ignored."); #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS if (aePtr->authType == GFARM_AUTH_USER) gfarm_hash_purge(userToDNTable, localName, strlen(localName) + 1); #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ aePtr->orphaned = 1; gfarmAuthDestroyUserEntry(aePtr); goto initDone; } if (!isNew) { gflog_warning(distName, "WARNING: duplicate DN. Ignored."); #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS if (aePtr->authType == GFARM_AUTH_USER) gfarm_hash_purge(userToDNTable, localName, strlen(localName) + 1); #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ aePtr->orphaned = 1; gfarmAuthDestroyUserEntry(aePtr); continue; } *(gfarmAuthEntry **)gfarm_hash_entry_data(ePtr) = aePtr; #if 0 dumpAuthEntry(aePtr); #endif } initDone: fclose(mFd); if (ret == -1) { /* * Destroy mapping table. */ struct gfarm_hash_iterator it; for (gfarm_hash_iterator_begin(authTable, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { aePtr = *(gfarmAuthEntry **)gfarm_hash_entry_data( gfarm_hash_iterator_access(&it)); aePtr->orphaned = 1; gfarmAuthDestroyUserEntry(aePtr); } gfarm_hash_table_free(authTable); authTable = NULL; #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS gfarm_hash_table_free(userToDNTable); userToDNTable = NULL; #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ } } done: return ret; } void gfarmAuthFinalize() { if (authTable != NULL) { gfarmAuthEntry *aePtr; struct gfarm_hash_iterator it; for (gfarm_hash_iterator_begin(authTable, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { aePtr = *(gfarmAuthEntry **)gfarm_hash_entry_data( gfarm_hash_iterator_access(&it)); if (aePtr->sesRefCount <= 0) { /* * If any sessions reffer this entry, don't free it. */ aePtr->orphaned = 1; gfarmAuthDestroyUserEntry(aePtr); } else { aePtr->orphaned = 1; } } gfarm_hash_table_free(authTable); authTable = NULL; #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS gfarm_hash_table_free(userToDNTable); userToDNTable = NULL; #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ } } gfarmAuthEntry * gfarmAuthGetUserEntry(distUserName) char *distUserName; { gfarmAuthEntry *ret = NULL; if (authTable != NULL) { struct gfarm_hash_entry *ePtr = gfarm_hash_lookup(authTable, distUserName, strlen(distUserName) + 1); if (ePtr != NULL) { ret = *(gfarmAuthEntry **)gfarm_hash_entry_data(ePtr); #if 0 dumpAuthEntry(ret); #endif } } return ret; } #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS gfarmAuthEntry * gfarmAuthGetLocalUserEntry(localUserName) char *localUserName; { gfarmAuthEntry *ret = NULL; if (userToDNTable != NULL) { struct gfarm_hash_entry *ePtr = gfarm_hash_lookup(userToDNTable, localUserName, strlen(localUserName) + 1); if (ePtr != NULL) { ret = *(gfarmAuthEntry **)gfarm_hash_entry_data(ePtr); #if 0 dumpAuthEntry(ret); #endif } } return ret; } #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ int gfarmAuthGetAuthEntryType(aePtr) gfarmAuthEntry *aePtr; { if (aePtr == NULL) { return GFARM_AUTH_UNKNOWN; } else { if (aePtr->authType == GFARM_AUTH_USER || aePtr->authType == GFARM_AUTH_HOST) { return aePtr->authType; } else { return GFARM_AUTH_UNKNOWN; } } } void gfarmAuthDestroyUserEntry(aePtr) gfarmAuthEntry *aePtr; { if (aePtr->sesRefCount == 0 && aePtr->orphaned == 1) { if (aePtr->distName != NULL) { (void)free(aePtr->distName); } switch (aePtr->authType) { case GFARM_AUTH_USER: { if (aePtr->authData.userAuth.localName != NULL) { (void)free(aePtr->authData.userAuth.localName); } if (aePtr->authData.userAuth.homeDir != NULL) { (void)free(aePtr->authData.userAuth.homeDir); } if (aePtr->authData.userAuth.loginShell != NULL) { (void)free(aePtr->authData.userAuth.loginShell); } break; } case GFARM_AUTH_HOST: { if (aePtr->authData.hostAuth.FQDN != NULL) { (void)free(aePtr->authData.hostAuth.FQDN); } break; } } (void)free(aePtr); } } static void cleanString(char *str); static void cleanString(str) char *str; { if (str == NULL || str[0] == '\0') { return; } else { int len = strlen(str); (void)memset(str, 0, len); } } void gfarmAuthMakeThisAlone(laePtr) gfarmAuthEntry *laePtr; { if (laePtr->orphaned == 1) { return; } else { gfarmAuthEntry *aePtr; struct gfarm_hash_iterator it; for (gfarm_hash_iterator_begin(authTable, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { aePtr = *(gfarmAuthEntry **)gfarm_hash_entry_data( gfarm_hash_iterator_access(&it)); if (laePtr == aePtr) { laePtr->orphaned = 1; } else { aePtr->sesRefCount = 0; aePtr->orphaned = 1; cleanString(aePtr->distName); switch (aePtr->authType) { case GFARM_AUTH_USER: { cleanString(aePtr->authData.userAuth.localName); cleanString(aePtr->authData.userAuth.homeDir); cleanString(aePtr->authData.userAuth.loginShell); break; } case GFARM_AUTH_HOST: { cleanString(aePtr->authData.hostAuth.FQDN); break; } } gfarmAuthDestroyUserEntry(aePtr); } } gfarm_hash_table_free(authTable); authTable = NULL; #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS gfarm_hash_table_free(userToDNTable); userToDNTable = NULL; #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ } } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT1-2-5-1_zabbix_child_down #! /bin/sh ###################################################################### TESTID="FT1-2-5-1" CATEGORY="accident causes no failover" SECTION="observer accident" TITLE="zabbix child down" ###################################################################### . ./FT-common ft_setup() { SERVICE_PATH=/sbin/service FT_MAIL_TIMEOUT=900 return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $zabbix1 sudo $SERVICE_PATH zabbix-server stop \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop zabbix child server on $zabbix1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "zabbix_server is not running on $zabbix1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ssh $zabbix1 sudo $SERVICE_PATH zabbix-server start \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "start zabbix child server on $zabbix1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: zabbix_server is not running on $zabbix1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { ssh $zabbix1 sudo $SERVICE_PATH zabbix-server start return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_5_rc1/snmptool/gmonitor3/gmonitor/logdata/HostDefBlock.java package gmonitor.logdata; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /* * Created on 2003/05/14 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ /** * @author hkondo * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class HostDefBlock extends BinaryBlock { protected ArrayList definition = new ArrayList(); public static HostDefBlock newInstance(InputStream is, int sz) throws IOException { HostDefBlock bb = new HostDefBlock(); bb.deserialize(is, sz); return bb; } public int getCount(){ return definition.size(); } /* (non-Javadoc) * @see BinaryBlock#parse_binary_block(java.io.InputStream) * {IPアドレス(文字列)}{NULL}{FQDN}{NULL}{略称}{NULL}{コミュニティストリング}{NULL} */ protected void parse_binary_block(InputStream is) throws IOException { byte[] buf = new byte[STRLEN]; int read_size = 0; while(read_size < size){ HostDefElement e = new HostDefElement(); // Read string represented IP Address. String ipaddr; int cnt = readBytesWithNull(is, buf); e.setIpAddr(UTY.byte2String(buf, 0, cnt)); read_size += (cnt + 1); // '+1' means NULL. // Read Hostname. cnt = readBytesWithNull(is, buf); e.setHostname(UTY.byte2String(buf, 0, cnt)); read_size += (cnt + 1); // '+1' means NULL. // Read Nickname of host. cnt = readBytesWithNull(is, buf); e.setNickname(UTY.byte2String(buf, 0, cnt)); read_size += (cnt + 1); // '+1' means NULL. // Read community string of host. cnt = readBytesWithNull(is, buf); e.setCommunityString(UTY.byte2String(buf, 0, cnt)); read_size += (cnt + 1); // '+1' means NULL. // add definition element. definition.add(e); } } public String toString() { StringBuffer sb = new StringBuffer("# HostDefBlock"); synchronized(definition){ int cnt = definition.size(); for(int i = 0; i < cnt; i++){ HostDefElement e = (HostDefElement) definition.get(i); sb.append('\n'); sb.append(e.toString(i)); } } return sb.toString(); } public int getHostIndex(String host) { int idx = -1; synchronized(definition){ for(int i = 0; i < definition.size(); i++){ HostDefElement e = (HostDefElement) definition.get(i); String h = e.getHostname(); if(h.equals(host) == true){ idx = i; break; } } } return idx; } public HostDefElement getHostDefElement(int idx) { HostDefElement e = null; synchronized(definition){ e = (HostDefElement) definition.get(idx); } return e; } public boolean containsHost(String host) { int idx = getHostIndex(host); if(idx < 0){ return false; }else{ return true; } } } <file_sep>/gfarmfs-fuse/trunk/test/test.sh #! /bin/sh OUTPUTDIR=./output DIFFDIR=./diffs TMP_MNTDIR=./_tmp_mnt FSYSTEST=./fsystest GFARMFS=../gfarmfs TESTSH=./test.sh FUNCSH=./func.sh CONFSH=./conf.sh export GFARM_PATH_INFO_TIMEOUT=1000 ##### check current directory ##### if [ ! -f $TESTSH -o ! -f $FUNCSH -o ! -f $CONFSH ]; then exit 1 fi ##### initialize ##### . $CONFSH . $FUNCSH test_init ##### expected directory ##### if [ x"$FUSE_MODE" = x"FUSE25_Linux" ]; then EXPECTDIR=./expected/default elif [ x"$FUSE_MODE" = x"FUSE25_Linux26_old" ]; then EXPECTDIR=./expected/fuse25_linux26_old elif [ x"$FUSE_MODE" = x"FUSE22_Linux" ]; then EXPECTDIR=./expected/default ### TODO fuse22_linux elif [ x"$FUSE_MODE" = x"FUSE25_FreeBSD" ]; then EXPECTDIR=./expected/freebsd else ### unknown EXPECTDIR=./expected/default fi echo "expected directory: ${EXPECTDIR} (${FUSE_MODE})" ##### test mode ##### TESTMODE=$1 DO_TMP=0 DO_GFARMFS=0 DO_GFARMFS_OLD=0 DO_FUSEXMP=0 if [ x"${TESTMODE}" = x"all" ]; then DO_TMP=1 DO_GFARMFS=1 DO_GFARMFS_OLD=1 DO_FUSEXMP=1 elif [ x"${TESTMODE}" = x"tmp" ]; then DO_TMP=1 elif [ x"${TESTMODE}" = x"gfarmfs" ]; then DO_GFARMFS=1 elif [ x"${TESTMODE}" = x"oldgfarmfs" ]; then DO_GFARMFS_OLD=1 elif [ x"${TESTMODE}" = x"fusexmp" ]; then DO_FUSEXMP=1 else echo "usage: $0 <all|gfarmfs|oldgfarmfs|fusexmp|tmp>" exit 1 fi ##### test on /tmp ##### if [ $DO_TMP -eq 1 ]; then test_common /tmp slashtmp slashtmp "/tmp" fi ##### test on gfarmfs ##### if [ $DO_GFARMFS -eq 1 ]; then test_gfarmfs "" "" gfarmfs_noopt test_gfarmfs "-nlsu" "" gfarmfs_nlsu test_gfarmfs "-nlsu" "-o default_permissions" gfarmfs_defperm test_gfarmfs "-nlsu" "-o attr_timeout=0" gfarmfs_attr0 test_gfarmfs "-nlsu -N2" "" gfarmfs_N2 test_gfarmfs "-nlsu -b" "" gfarmfs_b test_gfarmfs "-nlsu -b" "-o direct_io" gfarmfs_b_direct_io test_gfarmfs "-nlsu" "-o direct_io" gfarmfs_direct_io fi if [ $DO_GFARMFS_OLD -eq 1 ]; then test_gfarmfs "--oldio -nlsu" "-o attr_timeout=0" gfarmfs_oldio test_gfarmfs "--oldio -nlsub" "-o attr_timeout=0" gfarmfs_oldio_b test_gfarmfs "--oldio -nlsuF" "-o attr_timeout=0" gfarmfs_oldio_F fi ##### fusexmp_fh ##### if [ $DO_FUSEXMP -eq 1 ]; then test_fusexmp "fusexmp" "" fusexmp test_fusexmp "fusexmp_fh" "" fusexmp_fh test_fusexmp "fusexmp_fh" "-o direct_io" fusexmp_fh_direct_io test_fusexmp "fusexmp_fh" "-o kernel_cache" fusexmp_fh_kernel_cache test_fusexmp "fusexmp_fh" "-s" fusexmp_fh_s test_fusexmp "fusexmp_fh" "-o default_permissions" fusexmp_fh_defperm fi ##### final ##### exit $err <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/setup-server-mysql.sh #! /bin/sh # # Setup MySQL database for 'gfarm_zabbix'. # Please note that this script assumes MySQL server (mysqld) is running. # . ./install.conf ( echo "create database $DB_NAME;" ) | mysql --user=root \ || { echo "Failed to create the database: $DB_NAME"; exit 1; } echo "Create the database: $DB_NAME" ( echo "grant all on $DB_NAME.* to $DB_USER@localhost " echo " identified by '$DB_PASSWORD';" \ ) | mysql --user=root \ || { echo "Failed to create the user: $DB_USER"; exit 1; } echo "Create the user: $DB_USER" for I in \ $ZABBIX_DOCDIR/schema/mysql.sql \ $ZABBIX_DOCDIR/data/data.sql \ $ZABBIX_DOCDIR/data/images_mysql.sql; do cat $I | mysql --user=$DB_USER --password="$<PASSWORD>" $DB_NAME \ || { echo "Failed to execute the SQL file: $I"; exit 1; } echo "Execute the SQL file: $I" done <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/gfptool/gfcombine/gfcombine.c /* * $Id$ * * Reduce the number of fragments by nth. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gfarm/gfarm.h> char *program_name = "gfarm_combine"; #define default_output "gfarm:combine.out" void usage() { fprintf(stderr, "Usage: %s [option] <input_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-n <combined_frag_number>\tdefault 2\n"); fprintf(stderr, "\t-o <output_gfarm_file>\t\tdefault %s\n", default_output); exit(1); } #define BUFSIZE 65536 int main(int argc, char *argv[]) { extern char *optarg; extern int optind; int c, total_nodes = -1, node_index = -1; int output_nodes, output_index; char *e, *input, *output = default_output; GFS_File igf, ogf; int n = 2, i; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; while ((c = getopt(argc, argv, "o:n:")) != -1) { switch (c) { case 'n': n = atoi(optarg); break; case 'o': output = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_pio_get_node_size(&total_nodes); if (total_nodes <= 0) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing input file name\n", program_name); } exit(1); } input = argv[0]; argc--; argv++; if (argc != 0) { if (node_index == 0) { fprintf(stderr, "%s: currently, " "only one input file is supported\n", program_name); } exit(1); } output_nodes = (total_nodes + n - 1) / n; output_index = node_index / n; if (output_index * n != node_index) goto terminate; /* Only combined nodes run this part. */ e = gfs_pio_create(output, GFARM_FILE_WRONLY, 0666, &ogf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_set_view_index(ogf, output_nodes, output_index, NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_index(%s): %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_open(input, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, input, e); exit(1); } for (i = 0; i < n; ++i) { if (node_index + i < total_nodes) { e = gfs_pio_set_view_index(igf, GFARM_FILE_DONTCARE, node_index + i, NULL, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_index(%s): %s\n", program_name, node_index, input, e); exit(1); } /* copy this fragment */ for (;;) { int rv, wv; char buffer[BUFSIZE]; e = gfs_pio_read(igf, buffer, sizeof(buffer), &rv); if (e != NULL || rv == 0) break; e = gfs_pio_write(ogf, buffer, rv, &wv); if (e != NULL) break; } } } e = gfs_pio_close(igf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", input, e); e = gfs_pio_close(ogf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", output, e); terminate: e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT2-2-1-2_master_gfmd_down_with_master_candidate_network_down #! /bin/sh ###################################################################### TESTID="FT2-2-1-2" CATEGORY="2 point accident" SECTION="internal accident and network down" TITLE="master gfmd down with master candidate network down" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfmd2_CTRL_ADDRESS sudo $IFDOWN_PATH $gfmd2_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfmd2_GFARM_IF on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_wait_failover $gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "gfmd failed over" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4.1 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4.2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd2_CTRL_ADDRESS sudo $IFUP_PATH $gfmd2_GFARM_IF \ ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_0_1/lib/gfs_hook/hooks_64.c #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "hooks_subr.h" #include <sys/syscall.h> /* * The following hooks are not implemented: * * _LFS64_ASYNCHRONOUS_IO APIs * aio_cancel64() * aio_error64() * aio_fsync64() * aio_read64() * aio_return64() * aio_suspend64() * aio_write64() * lio_listio64() * * _LFS64_LARGEFILE APIs * fstat64() * ftruncate64() * lockf64() * lstat64() * mmap64() * readdir64() * truncate64() * */ /* * definitions for "hooks_common.c" */ int gfs_hook_syscall_open64(const char *path, int oflag, mode_t mode) { #ifdef SYS_open64 return (syscall(SYS_open64, path, oflag, mode)); #else return (gfs_hook_syscall_open(path, oflag | O_LARGEFILE, mode)); #endif } int gfs_hook_syscall_creat64(const char *path, mode_t mode) { #ifdef SYS_creat64 return (syscall(SYS_creat64, path, mode)); #else return (gfs_hook_syscall_open64(path, O_CREAT|O_TRUNC|O_WRONLY, mode)); #endif } /* * XXX - not really tested. */ int gfs_hook_syscall_lseek64(int filedes, off64_t offset, int whence) { #if defined(SYS_lseek64) return (syscall(SYS_lseek64, filedes, offset, whence)); #elif defined(SYS_llseek) return (syscall(SYS_llseek, filedes, (int)(offset >> 32), (int)offset, whence)); #elif defined(SYS__llseek) /* linux */ off64_t rv, result; rv = syscall(SYS__llseek, filedes, (int)(offset >>32), (int)offset, &result, whence); return (rv ? rv : result); #else #error do not know how to implement lseek64 #endif } int gfs_hook_syscall_stat64(const char *path, struct stat64 *buf) { #ifndef _STAT_VER return (syscall(SYS_stat64, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_xstat64(_STAT_VER, path, buf)); #endif } /* * for SVR4. * * (see sysdep/linux/xstat64.c about Linux) */ #if defined(_STAT_VER) && defined(SYS_xstat) int gfs_hook_syscall_xstat64(int ver, const char *path, struct stat64 *buf) { #if defined(__sgi) && _MIPS_SIM == _ABIN32 /* ABI N32 */ return (gfs_hook_syscall_xstat(SYS_xstat, _STAT_VER, path, buf)); #else return (gfs_hook_syscall_xstat(SYS_xstat, _STAT64_VER, path, buf)); #endif } #endif #define OFF_T off64_t #define SYSCALL_OPEN(path, oflag, mode) \ gfs_hook_syscall_open64(path, oflag, mode) #define SYSCALL_CREAT(path, mode) \ gfs_hook_syscall_creat64(path, mode) #define SYSCALL_LSEEK(filedes, offset, whence) \ gfs_hook_syscall_lseek64(filedes, offset, whence) #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_stat64(path, buf) #define FUNC___OPEN __open64 #define FUNC__OPEN _open64 #define FUNC_OPEN open64 #define FUNC___CREAT __creat64 #define FUNC__CREAT _creat64 #define FUNC_CREAT creat64 #define FUNC___LSEEK __lseek64 #define FUNC__LSEEK _lseek64 #define FUNC_LSEEK lseek64 #define FUNC___STAT __stat64 #define FUNC__STAT _stat64 #define FUNC_STAT stat64 #define STRUCT_STAT struct stat64 #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_xstat64(ver, path, buf) #define FUNC___XSTAT __xstat64 #define FUNC__XSTAT _xstat64 #define FUNC_XSTAT xstat64 #endif #include "hooks_common.c" <file_sep>/gfarm_mpiio/tags/gfarm_mpiio_0_0_1/ad_gfarm/ad_gfarm.h /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #ifndef AD_GFARM_INCLUDE #define AD_GFARM_INCLUDE #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <fcntl.h> #include <math.h> #include "adio.h" #include <gfarm/gfarm.h> typedef struct { char *filename; int nprocs; int *count; unsigned *filetype_size; MPI_Aint *filetype_extent; ADIO_Offset **blocklens; /* array of contiguous block lengths (bytes)*/ ADIO_Offset **indices; /* array of byte offsets of each block */ int gfp_num; int gfp_index; int *gfp_flag; unsigned long *data_size; double all_time; double access_time; GFS_File *gfp; GFS_File header_gfp; int is_collective; int newfile; int header_flag; int gfarm_view_flag; struct ADIOI_GFARM_col_info *gci; } ADIOI_GFARM_headerInf; typedef struct ADIOI_GFARM_col_info{ int same_rank_count; int head_rank; int head_rank_flag; int *same_rank_arr; GFS_File *gfp; }ADIOI_GFARM_collective_info; void ADIOI_GFARM_Open(ADIO_File fd, int *error_code); void ADIOI_GFARM_Close(ADIO_File fd, int *error_code); void ADIOI_GFARM_ReadContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_WriteContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_IwriteContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Request *request, int *error_code); void ADIOI_GFARM_IreadContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Request *request, int *error_code); int ADIOI_GFARM_ReadDone(ADIO_Request *request, ADIO_Status *status, int *error_code); int ADIOI_GFARM_WriteDone(ADIO_Request *request, ADIO_Status *status, int *error_code); void ADIOI_GFARM_ReadComplete(ADIO_Request *request, ADIO_Status *status, int *error_code); void ADIOI_GFARM_WriteComplete(ADIO_Request *request, ADIO_Status *status, int *error_code); void ADIOI_GFARM_Fcntl(ADIO_File fd, int flag, ADIO_Fcntl_t *fcntl_struct, int *error_code); void ADIOI_GFARM_WriteStrided(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_ReadStrided(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_WriteStridedColl(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_ReadStridedColl(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code); void ADIOI_GFARM_IreadStrided(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Request *request, int *error_code); void ADIOI_GFARM_IwriteStrided(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Request *request, int *error_code); void ADIOI_GFARM_Flush(ADIO_File fd, int *error_code); void ADIOI_GFARM_Resize(ADIO_File fd, ADIO_Offset size, int *error_code); ADIO_Offset ADIOI_GFARM_SeekIndividual(ADIO_File fd, ADIO_Offset offset, int whence, int *error_code); void ADIOI_GFARM_SetInfo(ADIO_File fd, MPI_Info users_info, int *error_code); void ADIOI_GFARM_Get_shared_fp(ADIO_File fd, int size, ADIO_Offset *shared_fp, int *error_code); void ADIOI_GFARM_Set_shared_fp(ADIO_File fd, ADIO_Offset offset, int *error_code); void ADIOI_GFARM_Delete(char *filename, int *error_code); #endif <file_sep>/gfarm/tags/gfarm_1_0_4_rc7/lib/libgfarm/gfarm/gfs_dir.c #include <errno.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <sys/time.h> #include <sys/stat.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "hash.h" #include "gfs_pio.h" /* gfarm_path_expand_home */ #include "gfutil.h" #include "dircache.h" static char *gfarm_current_working_directory; char * gfs_mkdir(const char *pathname, gfarm_mode_t mode) { char *user, *canonic_path, *e; struct gfarm_path_info pi; struct timeval now; mode_t mask; user = gfarm_get_global_username(); if (user == NULL) return ("unknown user"); e = gfarm_url_make_path_for_creation(pathname, &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path_for_creation(pathname, &canonic_path); if (e != NULL) return (e); if (gfarm_path_info_get(canonic_path, &pi) == NULL) { gfarm_path_info_free(&pi); free(canonic_path); return (GFARM_ERR_ALREADY_EXISTS); } mask = umask(0); umask(mask); mode &= ~mask; gettimeofday(&now, NULL); pi.pathname = canonic_path; pi.status.st_mode = (GFARM_S_IFDIR | mode); pi.status.st_user = user; pi.status.st_group = "*"; /* XXX for now */ pi.status.st_atimespec.tv_sec = pi.status.st_mtimespec.tv_sec = pi.status.st_ctimespec.tv_sec = now.tv_sec; pi.status.st_atimespec.tv_nsec = pi.status.st_mtimespec.tv_nsec = pi.status.st_ctimespec.tv_nsec = now.tv_usec * GFARM_MILLISEC_BY_MICROSEC; pi.status.st_size = 0; pi.status.st_nsections = 0; e = gfarm_path_info_set(canonic_path, &pi); free(canonic_path); return (e); } char * gfs_rmdir(const char *pathname) { char *canonic_path, *e, *e_tmp; struct gfarm_path_info pi; GFS_Dir dir; struct gfs_dirent *entry; e = gfarm_url_make_path_for_creation(pathname, &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path_for_creation(pathname, &canonic_path); if (e != NULL) return (e); e = gfarm_path_info_get(canonic_path, &pi); if (e != NULL) goto error_free_canonic_path; if (!GFARM_S_ISDIR(pi.status.st_mode)) { gfarm_path_info_free(&pi); e = GFARM_ERR_NOT_A_DIRECTORY; goto error_free_canonic_path; } gfarm_path_info_free(&pi); e = gfs_opendir(pathname, &dir); if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL) { if (entry == NULL) { /* OK, remove the directory */ e = gfarm_path_info_remove(canonic_path); break; } if ((entry->d_namlen == 1 && entry->d_name[0] == '.') || (entry->d_namlen == 2 && entry->d_name[0] == '.' && entry->d_name[1] == '.')) continue; /* "." or ".." */ /* Not OK */ e = GFARM_ERR_DIRECTORY_NOT_EMPTY; break; } e_tmp = gfs_closedir(dir); if (e == NULL) e = e_tmp; } error_free_canonic_path: free(canonic_path); return (e); } char * gfs_chdir_canonical(const char *canonic_dir) { static char env_name[] = "GFS_PWD="; static char *env = NULL; static int env_len = 0; int len; len = sizeof(env_name) - 1 + GFARM_URL_PREFIX_LENGTH + 1 + strlen(canonic_dir) + 1; if (env_len < len) { char *tmp_env; tmp_env = realloc(env, len); if (tmp_env == NULL) return (GFARM_ERR_NO_MEMORY); env = tmp_env; env_len = len; } sprintf(env, "%s%s/%s", env_name, GFARM_URL_PREFIX, canonic_dir); gfarm_current_working_directory = env + sizeof(env_name) - 1 + GFARM_URL_PREFIX_LENGTH; if (putenv(env) != 0) return (gfarm_errno_to_error(errno)); return (NULL); } char * gfs_chdir(const char *dir) { char *e, *canonic_path; struct gfs_stat st; if ((e = gfs_stat(dir, &st)) != NULL) return (e); if (!GFARM_S_ISDIR(st.st_mode)) { gfs_stat_free(&st); return (GFARM_ERR_NOT_A_DIRECTORY); } gfs_stat_free(&st); e = gfarm_canonical_path(gfarm_url_prefix_skip(dir), &canonic_path); if (e != NULL) return (e); e = gfs_chdir_canonical(canonic_path); free (canonic_path); return (e); } char * gfs_getcwd(char *cwd, int cwdsize) { const char *path; char *default_cwd = NULL, *e, *p; int len; if (gfarm_current_working_directory != NULL) path = gfarm_current_working_directory; else if ((path = getenv("GFS_PWD")) != NULL) path = gfarm_url_prefix_skip(path); else { /* default case, use user's home directory */ char *e; e = gfarm_path_expand_home("~", &default_cwd); if (e != NULL) return (e); path = default_cwd; } /* check the existence */ e = gfarm_canonical_path(path, &p); if (e != NULL) goto finish; free(p); len = strlen(path); if (len < cwdsize) { strcpy(cwd, path); e = NULL; } else { e = GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE; } finish: if (default_cwd != NULL) free(default_cwd); return (e); } /* * directory tree, opendir/readdir/closedir */ struct node { struct node *parent; char *name; int flags; #define NODE_FLAG_IS_DIR 1 #define NODE_FLAG_MARKED 2 #define NODE_FLAG_PURGED 4 /* removed, and to be freed */ union node_u { struct dir { struct gfarm_hash_table *children; struct timeval mtime; } d; } u; }; #define NODE_HASH_SIZE 53 /* prime */ static struct node *root; static struct node * init_node_name(struct node *n, const char *name, int len) { n->name = malloc(len + 1); if (n->name == NULL) return (NULL); memcpy(n->name, name, len); n->name[len] = '\0'; return (n); } #define DIR_NODE_SIZE \ (sizeof(struct node) - sizeof(union node_u) + sizeof(struct dir)) static struct node * init_dir_node(struct node *n, const char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->flags = NODE_FLAG_IS_DIR; n->u.d.children = gfarm_hash_table_alloc(NODE_HASH_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); n->u.d.mtime.tv_sec = n->u.d.mtime.tv_usec = 0; return (n); } #define FILE_NODE_SIZE (sizeof(struct node) - sizeof(union node_u)) static struct node * init_file_node(struct node *n, const char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->flags = 0; #if 1 /* * We hold this even on a file_node, * this field can be non-NULL, if this node is changed from * a dir_node to a file_node. */ n->u.d.children = NULL; #endif return (n); } static void change_file_node_to_dir(struct node *n) { n->flags |= NODE_FLAG_IS_DIR; if (n->u.d.children == NULL) { n->u.d.children = gfarm_hash_table_alloc(NODE_HASH_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); n->u.d.mtime.tv_sec = n->u.d.mtime.tv_usec = 0; } } static void change_dir_node_to_file(struct node *n) { n->flags &= ~NODE_FLAG_IS_DIR; } static void for_each_node(struct node *n, void (*f)(void *, struct node *), void *cookie) { #if 0 if ((n->flags & NODE_FLAG_IS_DIR) != 0) #else if (n->u.d.children != NULL) #endif { struct gfarm_hash_iterator i; struct gfarm_hash_entry *child; for (gfarm_hash_iterator_begin(n->u.d.children, &i); (child = gfarm_hash_iterator_access(&i)) != NULL; gfarm_hash_iterator_next(&i)) { for_each_node(gfarm_hash_entry_data(child), f, cookie); } } (*f)(cookie, n); } static void free_node(void *cookie, struct node *n) { #if 0 if ((n->flags & NODE_FLAG_IS_DIR) != 0) #else if (n->u.d.children != NULL) #endif gfarm_hash_table_free(n->u.d.children); free(n->name); } static void recursive_free_nodes(struct node *n) { for_each_node(n, free_node, NULL); } static void delayed_purge_node(void *cookie, struct node *n) { n->flags |= NODE_FLAG_PURGED; } static void recursive_delayed_purge_nodes(struct node *n) { for_each_node(n, delayed_purge_node, NULL); } static void recursive_free_children(struct node *n) { struct gfarm_hash_iterator i; struct gfarm_hash_entry *child; for (gfarm_hash_iterator_begin(n->u.d.children, &i); (child = gfarm_hash_iterator_access(&i)) != NULL; gfarm_hash_iterator_next(&i)) { recursive_free_nodes(gfarm_hash_entry_data(child)); } gfarm_hash_table_free(n->u.d.children); n->u.d.children = NULL; } enum gfarm_node_lookup_op { GFARM_INODE_LOOKUP, GFARM_INODE_CREATE, GFARM_INODE_REMOVE, GFARM_INODE_MARK }; /* to inhibit dirctory uncaching while some directories are opened */ static int opendir_count = 0; /* * if (op != GFARM_INODE_CREATE), (is_dir) may be -1, * and that means "don't care". */ char * lookup_node(struct node *parent, const char *name, int len, int is_dir, enum gfarm_node_lookup_op op, struct node **np) { struct gfarm_hash_entry *entry; int created, already_purged; struct node *n; if ((parent->flags & NODE_FLAG_IS_DIR) == 0) return (GFARM_ERR_NOT_A_DIRECTORY); if (len == 0) { /* We don't handle GFARM_INODE_MARK for this case */ if (op == GFARM_INODE_REMOVE) return (GFARM_ERR_INVALID_ARGUMENT); *np = parent; return (NULL); } else if (len == 1 && name[0] == '.') { /* We don't handle GFARM_INODE_MARK for this case */ if (op == GFARM_INODE_REMOVE) return (GFARM_ERR_INVALID_ARGUMENT); *np = parent; return (NULL); } else if (len == 2 && name[0] == '.' && name[1] == '.') { /* We don't handle GFARM_INODE_MARK for this case */ if (op == GFARM_INODE_REMOVE) return (GFARM_ERR_DIRECTORY_NOT_EMPTY); *np = parent->parent; return (NULL); } if (len > GFS_MAXNAMLEN) len = GFS_MAXNAMLEN; if (op == GFARM_INODE_MARK) { entry = gfarm_hash_lookup(parent->u.d.children, name, len); /* We should not honor the PURGED flag here */ if (entry != NULL) { n = gfarm_hash_entry_data(entry); if ((n->flags & NODE_FLAG_IS_DIR) == is_dir) { /* abandon the PURGED flag at the mark phase */ n->flags &= ~NODE_FLAG_PURGED; n->flags |= NODE_FLAG_MARKED; *np = n; return (NULL); } if (opendir_count > 0) { if (is_dir) { change_file_node_to_dir(n); } else { recursive_delayed_purge_nodes(n); change_dir_node_to_file(n); } /* abandon the PURGED flag at the mark phase */ n->flags &= ~NODE_FLAG_PURGED; n->flags |= NODE_FLAG_MARKED; *np = n; return (NULL); } recursive_free_nodes(n); gfarm_hash_purge(parent->u.d.children, name, len); } /* do create */ } else if (op != GFARM_INODE_CREATE) { entry = gfarm_hash_lookup(parent->u.d.children, name, len); if (entry == NULL) return (GFARM_ERR_NO_SUCH_OBJECT); n = gfarm_hash_entry_data(entry); already_purged = (n->flags & NODE_FLAG_PURGED) != 0; if (already_purged || op == GFARM_INODE_REMOVE) { if (opendir_count > 0) { recursive_delayed_purge_nodes(n); } else { recursive_free_nodes(n); gfarm_hash_purge(parent->u.d.children, name, len); } if (already_purged) return (GFARM_ERR_NO_SUCH_OBJECT); *np = NULL; return (NULL); } *np = n; return (NULL); } entry = gfarm_hash_enter(parent->u.d.children, name, len, #if 0 is_dir ? DIR_NODE_SIZE : FILE_NODE_SIZE, #else /* * always allocate DIR_NODE_SIZE * to make it possible to change a file to a dir */ DIR_NODE_SIZE, #endif &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); n = gfarm_hash_entry_data(entry); if (!created) { n->flags &= ~NODE_FLAG_PURGED; /* assert(op == GFARM_INODE_CREATE); */ *np = n; return (NULL); } if (is_dir) init_dir_node(n, name, len); else init_file_node(n, name, len); n->parent = parent; if (op == GFARM_INODE_MARK) n->flags |= NODE_FLAG_MARKED; *np = n; return (NULL); } /* * is_dir must be -1 (don't care), 0 (not a dir) or NODE_FLAG_IS_DIR. * * if (op != GFARM_INODE_CREATE), (is_dir) may be -1, * and that means "don't care". */ static char * lookup_relative(struct node *n, const char *path, int is_dir, enum gfarm_node_lookup_op op, struct node **np) { char *e; int len; if ((n->flags & NODE_FLAG_IS_DIR) == 0) return (GFARM_ERR_NOT_A_DIRECTORY); for (;;) { while (*path == '/') path++; for (len = 0; path[len] != '/'; len++) { if (path[len] == '\0') { e = lookup_node(n, path, len, is_dir, op, &n); if (e != NULL) return (e); if (is_dir != -1 && (n->flags & NODE_FLAG_IS_DIR) != is_dir) return ((n->flags & NODE_FLAG_IS_DIR) ? GFARM_ERR_IS_A_DIRECTORY : GFARM_ERR_NOT_A_DIRECTORY); if (np != NULL) *np = n; return (NULL); } } e = lookup_node(n, path, len, NODE_FLAG_IS_DIR, op == GFARM_INODE_MARK ? GFARM_INODE_MARK : GFARM_INODE_LOOKUP, &n); if (e != NULL) return (e); if ((n->flags & NODE_FLAG_IS_DIR) == 0) return (GFARM_ERR_NOT_A_DIRECTORY); path += len; } } /* * if (op != GFARM_INODE_CREATE), (is_dir) may be -1, * and that means "don't care". */ static char * lookup_path(const char *path, int is_dir, enum gfarm_node_lookup_op op, struct node **np) { struct node *n; if (path[0] == '/') { n = root; } else { char *e; char cwd[PATH_MAX + 1]; e = gfs_getcwd(cwd, sizeof(cwd)); if (e != NULL) return (e); e = lookup_relative(root, cwd, NODE_FLAG_IS_DIR, GFARM_INODE_LOOKUP, &n); if (e != NULL) return (e); } return (lookup_relative(n, path, is_dir, op, np)); } static char * root_node(void) { root = malloc(DIR_NODE_SIZE); if (root == NULL) return (GFARM_ERR_NO_MEMORY); init_dir_node(root, "", 0); root->parent = root; return (NULL); } #if 0 /* not used */ static void free_all_nodes(void) { if (root != NULL) { recursive_free_nodes(root); free(root); root = NULL; } } #endif static char * gfs_dircache_modify_parent(const char *pathname) { char *e = NULL; char *parent = strdup(pathname), *b; struct gfarm_path_info pi; struct timeval now; if (parent == NULL) return (GFARM_ERR_NO_MEMORY); /* create parent directory canonic path */ for (b = (char *)gfarm_path_dir_skip(parent); b > parent && b[-1] == '/'; --b) ; *b = '\0'; /* NOTE: We don't have path_info for the root directory */ if (b > parent && (e = gfarm_metadb_path_info_get(parent, &pi)) == NULL) { gettimeofday(&now, NULL); pi.status.st_mtimespec.tv_sec = now.tv_sec; pi.status.st_mtimespec.tv_nsec = now.tv_usec * GFARM_MILLISEC_BY_MICROSEC; /* the following calls gfs_dircache_enter_path() internally */ e = gfarm_path_info_replace(parent, &pi); gfarm_path_info_free(&pi); } free(parent); return (e); } static char * gfs_dircache_enter_path(enum gfarm_node_lookup_op op, const char *pathname, struct gfarm_path_info *info) { struct node *n; char *e = lookup_relative(root, info->pathname, GFARM_S_ISDIR(info->status.st_mode) ? NODE_FLAG_IS_DIR : 0, op, &n); if (e != NULL) return (e); if (GFARM_S_ISDIR(info->status.st_mode)) { n->u.d.mtime.tv_sec = info->status.st_mtimespec.tv_sec; n->u.d.mtime.tv_usec = info->status.st_mtimespec.tv_nsec / GFARM_MILLISEC_BY_MICROSEC; } return (NULL); } static char * gfs_dircache_purge_path(const char *pathname) { return (lookup_relative(root, pathname, -1, GFARM_INODE_REMOVE, NULL)); } static void mark_path(void *closure, struct gfarm_path_info *info) { gfs_dircache_enter_path(GFARM_INODE_MARK, info->pathname, info); } static void sweep_nodes(struct node *n) { struct gfarm_hash_iterator i; struct gfarm_hash_entry *child; /* assert((n->flags & NODE_FLAG_IS_DIR) != 0); */ /* * We don't have to honor the PURGED flag here, * because the mark phase overrides the flag. */ for (gfarm_hash_iterator_begin(n->u.d.children, &i); (child = gfarm_hash_iterator_access(&i)) != NULL; gfarm_hash_iterator_next(&i)) { struct node *c = gfarm_hash_entry_data(child); if ((c->flags & NODE_FLAG_MARKED) == 0) { if (opendir_count > 0) { recursive_delayed_purge_nodes(c); } else { recursive_free_nodes(c); gfarm_hash_iterator_purge(&i); } } else { if ((c->flags & NODE_FLAG_IS_DIR) != 0) sweep_nodes(c); else if (opendir_count == 0 && c->u.d.children != NULL) recursive_free_children(c); c->flags &= ~NODE_FLAG_MARKED; } } } /* refresh directories as soon as possible */ static int need_to_clear_cache = 0; struct timeval gfarm_dircache_timeout = { 60, 0 }; /* default 60sec. */ static struct timeval last_dircache = {0, 0}; static char * gfs_cachedir(struct timeval *now) { /* assert(root != NULL); */ gfarm_path_info_get_all_foreach(mark_path, NULL); sweep_nodes(root); need_to_clear_cache = 0; last_dircache = *now; return (NULL); } void gfs_uncachedir(void) { need_to_clear_cache = 1; } void gfs_dircache_set_timeout(struct gfarm_timespec *timeout) { gfarm_dircache_timeout.tv_sec = timeout->tv_sec; gfarm_dircache_timeout.tv_usec = timeout->tv_nsec / GFARM_MILLISEC_BY_MICROSEC; } static char * gfs_refreshdir(void) { char *e, *s; static int initialized = 0; struct timeval now, elapsed; if (!initialized) { if ((s = getenv("GFARM_DIRCACHE_TIMEOUT")) != NULL) gfarm_dircache_timeout.tv_sec = atoi(s); gfarm_dircache_timeout.tv_usec = 0; initialized = 1; } gettimeofday(&now, NULL); if (root == NULL) { e = root_node(); if (e != NULL) return (e); return (gfs_cachedir(&now)); } if (need_to_clear_cache) return (gfs_cachedir(&now)); elapsed = now; gfarm_timeval_sub(&elapsed, &last_dircache); if (gfarm_timeval_cmp(&elapsed, &gfarm_dircache_timeout) >= 0) return (gfs_cachedir(&now)); return (NULL); } /* * metadatabase interface wrappers provided by dircache layer. */ char * gfarm_path_info_get(const char *pathname, struct gfarm_path_info *info) { char *e = gfs_refreshdir(), *e2; struct node *n; if (e != NULL) return (e); /* real metadata */ e = gfarm_metadb_path_info_get(pathname, info); /* cached metadata */ e2 = lookup_relative(root, pathname, e != NULL ? -1 : GFARM_S_ISDIR(info->status.st_mode) ? NODE_FLAG_IS_DIR : 0, GFARM_INODE_LOOKUP, &n); /* real and cache do agree, and the metadata does not exist */ if ((e == NULL) == (e2 == NULL) && e != NULL) return (e); if ((e == NULL) != (e2 == NULL) || GFARM_S_ISDIR(info->status.st_mode) != ((n->flags & NODE_FLAG_IS_DIR) != 0) || ((n->flags & NODE_FLAG_IS_DIR) != 0 && (n->u.d.mtime.tv_sec != info->status.st_mtimespec.tv_sec || n->u.d.mtime.tv_usec != info->status.st_mtimespec.tv_nsec / GFARM_MILLISEC_BY_MICROSEC))) { /* there is inconsistency, refresh the dircache. */ gfs_uncachedir(); e2 = gfs_refreshdir(); } return (e != NULL ? e : e2); } char * gfarm_path_info_set(char *pathname, struct gfarm_path_info *info) { char *e = gfs_refreshdir(); if (e != NULL) return (e); e = gfarm_metadb_path_info_set(pathname, info); if (e == NULL) { gfs_dircache_enter_path(GFARM_INODE_CREATE, pathname, info); gfs_dircache_modify_parent(pathname); } return (e); } char * gfarm_path_info_replace(char *pathname, struct gfarm_path_info *info) { char *e = gfs_refreshdir(); if (e != NULL) return (e); e = gfarm_metadb_path_info_replace(pathname, info); if (e == NULL) { e = gfs_dircache_enter_path(GFARM_INODE_LOOKUP, pathname, info); if (e != NULL) { gfs_uncachedir(); e = gfs_refreshdir(); } } return (e); } char * gfarm_path_info_remove(const char *pathname) { char *e = gfs_refreshdir(); if (e != NULL) return (e); e = gfarm_metadb_path_info_remove(pathname); if (e == NULL) { gfs_dircache_purge_path(pathname); gfs_dircache_modify_parent(pathname); } return (e); } /* * 'path' is '/' + canonical path, or a relative path. It is not the * same as a canonical path. */ char * gfs_realpath_canonical(const char *path, char **abspathp) { struct node *n, *p; char *e, *abspath; int l, len; e = gfs_refreshdir(); if (e != NULL) return (e); e = lookup_path(path, -1, GFARM_INODE_LOOKUP, &n); if (e != NULL) return (e); len = 0; for (p = n; p != root; p = p->parent) { if (p != n) ++len; /* for '/' */ len += strlen(p->name); } abspath = malloc(len + 1); if (abspath == NULL) return (GFARM_ERR_NO_MEMORY); abspath[len] = '\0'; for (p = n; p != root; p = p->parent) { if (p != n) abspath[--len] = '/'; l = strlen(p->name); len -= l; memcpy(abspath + len, p->name, l); } *abspathp = abspath; return (NULL); } #define INUMBER(node) ((long)(node)) char * gfs_get_ino(const char *canonical_path, long *inop) { struct node *n; char *e; e = gfs_refreshdir(); if (e != NULL) return (e); e = lookup_relative(root, canonical_path, -1, GFARM_INODE_LOOKUP, &n); if (e != NULL) return (e); *inop = INUMBER(n);; return (NULL); } /* * gfs_opendir()/readdir()/closedir() */ struct gfs_dir { struct node *dir; struct gfarm_hash_iterator iterator; struct gfs_dirent buffer; int index; }; char * gfs_opendir(const char *path, GFS_Dir *dirp) { char *e, *canonic_path; struct node *n; struct gfs_dir *dir; struct gfs_stat st; /* gfs_stat() -> gfarm_path_info_get() makes the dircache consistent */ if ((e = gfs_stat(path, &st)) != NULL) return (e); if (!GFARM_S_ISDIR(st.st_mode)) { gfs_stat_free(&st); return (GFARM_ERR_NOT_A_DIRECTORY); } gfs_stat_free(&st); e = gfarm_canonical_path(gfarm_url_prefix_skip(path), &canonic_path); if (e != NULL) return (e); e = lookup_relative(root, canonic_path, NODE_FLAG_IS_DIR, GFARM_INODE_LOOKUP, &n); free(canonic_path); if (e != NULL) return (e); dir = malloc(sizeof(struct gfs_dir)); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); dir->dir = n; gfarm_hash_iterator_begin(n->u.d.children, &dir->iterator); dir->index = 0; *dirp = dir; ++opendir_count; /* XXX if someone removed a path, while opening a directory... */ return (NULL); } char * gfs_readdir(GFS_Dir dir, struct gfs_dirent **entry) { struct gfarm_hash_entry *he; struct node *n; if (dir->index == 0) { n = dir->dir; dir->buffer.d_namlen = 1; dir->buffer.d_name[0] = '.'; dir->index++; } else if (dir->index == 1) { n = dir->dir->parent; dir->buffer.d_namlen = 2; dir->buffer.d_name[0] = dir->buffer.d_name[1] = '.'; dir->index++; } else { for (;;) { he = gfarm_hash_iterator_access(&dir->iterator); if (he == NULL) { *entry = NULL; return (NULL); } n = gfarm_hash_entry_data(he); gfarm_hash_iterator_next(&dir->iterator); dir->index++; if ((n->flags & NODE_FLAG_PURGED) == 0) break; } dir->buffer.d_namlen = gfarm_hash_entry_key_length(he); memcpy(dir->buffer.d_name, gfarm_hash_entry_key(he), dir->buffer.d_namlen); } dir->buffer.d_name[dir->buffer.d_namlen] = '\0'; dir->buffer.d_type = (n->flags & NODE_FLAG_IS_DIR) ? GFS_DT_DIR : GFS_DT_REG; dir->buffer.d_reclen = 0x100; /* XXX */ dir->buffer.d_fileno = INUMBER(n); *entry = &dir->buffer; return (NULL); } char * gfs_closedir(GFS_Dir dir) { free(dir); --opendir_count; return (NULL); } /* * gfs_dirname() */ char * gfs_dirname(GFS_Dir dir) { return (dir->dir->name); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/auth_config.c #include <assert.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "hostspec.h" #include "auth.h" struct gfarm_auth_method_name_value { char *name; enum gfarm_auth_method method; } gfarm_auth_method_name_value_table[] = { { "sharedsecret", GFARM_AUTH_METHOD_SIMPLE }, { "gsi", GFARM_AUTH_METHOD_GSI }, }; enum gfarm_auth_config_command { GFARM_AUTH_ENABLE, GFARM_AUTH_DISABLE }; struct gfarm_auth_config { struct gfarm_auth_config *next; enum gfarm_auth_config_command command; enum gfarm_auth_method method; struct gfarm_hostspec *hostspec; }; struct gfarm_auth_config *gfarm_auth_config_list = NULL; struct gfarm_auth_config **gfarm_auth_config_last = &gfarm_auth_config_list; char * gfarm_auth_method_parse(char *name, enum gfarm_auth_method *methodp) { int i; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_auth_method_name_value_table); i++) { if (strcmp(name, gfarm_auth_method_name_value_table[i].name) == 0) { *methodp = gfarm_auth_method_name_value_table[i].method; return (NULL); } } return (GFARM_ERR_NO_SUCH_OBJECT); } char * gfarm_auth_config_add( enum gfarm_auth_config_command command, enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { struct gfarm_auth_config *acp = malloc(sizeof(struct gfarm_auth_config)); if (acp == NULL) return (GFARM_ERR_NO_MEMORY); acp->next = NULL; acp->command = command; acp->method = method; acp->hostspec = hsp; *gfarm_auth_config_last = acp; gfarm_auth_config_last = &acp->next; return (NULL); } char * gfarm_auth_enable(enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { return (gfarm_auth_config_add(GFARM_AUTH_ENABLE, method, hsp)); } char * gfarm_auth_disable(enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { return (gfarm_auth_config_add(GFARM_AUTH_DISABLE, method, hsp)); } /* this i/f have to be changed, if we support more than 31 auth methods */ gfarm_int32_t gfarm_auth_method_get_enabled_by_name_addr(char *name, struct sockaddr *addr) { struct gfarm_auth_config *acp = gfarm_auth_config_list; gfarm_int32_t enabled = 0, disabled = 0, methods; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); for (; acp != NULL; acp = acp->next) { if (gfarm_hostspec_match(acp->hostspec, name, addr)) { if (acp->method == GFARM_AUTH_METHOD_ALL) { methods = ((1 << GFARM_AUTH_METHOD_NUMBER) - 1) & ~(1 << GFARM_AUTH_METHOD_NONE) & ~(enabled | disabled); } else { methods = 1 << acp->method; if (((enabled | disabled) & methods) != 0) continue; /* already determined */ } switch (acp->command) { case GFARM_AUTH_ENABLE: enabled |= methods; break; case GFARM_AUTH_DISABLE: disabled |= methods; break; } } } return (enabled); } gfarm_int32_t gfarm_auth_method_get_available(void) { int i; gfarm_int32_t methods; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); methods = 0; for (i = GFARM_AUTH_METHOD_NONE + 1; i < GFARM_AUTH_METHOD_NUMBER; i++) { switch (i) { #ifndef HAVE_GSI case GFARM_AUTH_METHOD_GSI: break; #endif default: methods |= 1 << i; break; } } return (methods); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/package/solaris/gfsd.in #!/sbin/sh # # $Id$ GFSD=@prefix@/sbin/gfsd PID_FILE=/var/run/gfsd.pid # workaround a problem that "ld -R" doesn't work with indirectly dependent SOs if [ -n "@globus_location@" ]; then LD_LIBRARY_PATH=@globus_location@/lib export LD_LIBRARY_PATH fi case "$1" in 'start') if [ -x $GFSD -a -f /etc/gfarm.conf ]; then $GFSD -P $PID_FILE fi ;; 'stop') if [ -f $PID_FILE ]; then kill -TERM `cat $PID_FILE` fi ;; *) echo "Usage: $0 { start | stop }" exit 1 ;; esac exit 0 <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfsl/gsi.c #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <ctype.h> #include <pwd.h> #include "gssapi.h" #include "gfevent.h" #include "gfutil.h" #include "tcputil.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS #include "gfarm_auth.h" #endif static char **gssCrackStatus(OM_uint32 statValue, int statType); static int gssInitiateSecurityContextSwitch(struct gfarmGssInitiateSecurityContextState *state); static int gssInitiateSecurityContextNext(struct gfarmGssInitiateSecurityContextState *state); static void gfarmGssInitiateSecurityContextSendToken(int events, int fd, void *closure, const struct timeval *t); static void gfarmGssInitiateSecurityContextReceiveToken(int events, int fd, void *closure, const struct timeval *t); static char ** gssCrackStatus(statValue, statType) OM_uint32 statValue; int statType; { OM_uint32 msgCtx; OM_uint32 minStat; gss_buffer_desc stStr; char **ret = (char **)malloc(sizeof(char *) * 1); int i = 0; char *dP = NULL; ret[0] = NULL; while (1) { msgCtx = 0; (void)gss_display_status(&minStat, statValue, statType, GSS_C_NO_OID, &msgCtx, &stStr); ret = (char **)realloc(ret, sizeof(char *) * (i + 2)); ret[i] = (char *)malloc(sizeof(char) * ((int)stStr.length + 1)); dP = ret[i]; dP[(int)stStr.length] = '\0'; i++; (void)memcpy((void *)dP, (void *)stStr.value, (int)stStr.length); (void)gss_release_buffer(&minStat, (gss_buffer_t)&stStr); if (msgCtx == 0) { break; } } ret[i] = NULL; return ret; } void gfarmGssFreeCrackedStatus(strPtr) char **strPtr; { char **cpS = strPtr; while (*cpS != NULL) { (void)free(*cpS++); } (void)free(strPtr); } char ** gfarmGssCrackMajorStatus(majStat) OM_uint32 majStat; { return gssCrackStatus(majStat, GSS_C_GSS_CODE); } char ** gfarmGssCrackMinorStatus(minStat) OM_uint32 minStat; { return gssCrackStatus(minStat, GSS_C_MECH_CODE); } void gfarmGssPrintMajorStatus(majStat) OM_uint32 majStat; { char **list = gfarmGssCrackMajorStatus(majStat); char **lP = list; if (*lP != NULL) { while (*lP != NULL) { gflog_error("", *lP++); } } else { gflog_error("GSS Major Status Error:", " UNKNOWN\n"); } gfarmGssFreeCrackedStatus(list); } void gfarmGssPrintMinorStatus(minStat) OM_uint32 minStat; { char **list = gfarmGssCrackMinorStatus(minStat); char **lP = list; if (*lP != NULL) { while (*lP != NULL) gflog_error("", *lP++); } else { gflog_error("GSS Minor Status Error:", " UNKNOWN\n"); } gfarmGssFreeCrackedStatus(list); } int gfarmGssImportName(namePtr, nameValue, nameLength, nameType, majStatPtr, minStatPtr) gss_name_t *namePtr; void *nameValue; size_t nameLength; gss_OID nameType; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat = 0; OM_uint32 minStat = 0; int ret = -1; gss_buffer_desc buf; #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS if (nameType == GSS_C_NT_USER_NAME) { char *user; gfarmAuthEntry *aePtr; user = malloc(nameLength + 1); if (user == NULL) { gflog_auth_error("gfarmGssImportName()", "no memory"); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; goto Done; } memcpy(user, nameValue, nameLength); user[nameLength] = '\0'; aePtr = gfarmAuthGetLocalUserEntry(user); if (aePtr == NULL) { gflog_auth_error(user, "ERROR: cannot convert " "this user name to X.509 Distinguish name"); free(user); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; goto Done; } free(user); assert(aePtr->authType == GFARM_AUTH_USER); nameValue = aePtr->distName; nameLength = strlen(aePtr->distName); nameType = GSS_C_NO_OID; /* mechanism specific */ } #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ buf.length = nameLength; buf.value = nameValue; majStat = gss_import_name(&minStat, &buf, nameType, namePtr); if (majStat == GSS_S_COMPLETE) { ret = 1; /* OK */ } Done: if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmGssImportNameOfHostBasedService(namePtr, service, hostname, majStatPtr, minStatPtr) gss_name_t *namePtr; char *service; char *hostname; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat; OM_uint32 minStat; int ret = -1; size_t nameLength = strlen(service) + 1 + strlen(hostname); char *nameString = malloc(nameLength + 1); if (nameString == NULL) { gflog_auth_error("gfarmGssImportNameOfHostBasedService()", "no memory"); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; } else { sprintf(nameString, "%s@%s", service, hostname); if (gfarmGssImportName(namePtr, nameString, nameLength, GSS_C_NT_HOSTBASED_SERVICE, &majStat, &minStat) > 0) { ret = 1; } free(nameString); } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmGssImportNameOfHost(namePtr, hostname, majStatPtr, minStatPtr) gss_name_t *namePtr; char *hostname; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { return gfarmGssImportNameOfHostBasedService(namePtr, "host", hostname, majStatPtr, minStatPtr); } int gfarmGssDeleteName(namePtr, majStatPtr, minStatPtr) gss_name_t *namePtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat; OM_uint32 minStat; majStat = gss_release_name(&minStat, namePtr); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return majStat == GSS_S_COMPLETE ? 1 : -1; } #if 0 /* gss_duplicate_name() is not implemented at least in globus-2 yet. */ int gfarmGssDuplicateName(outputNamePtr, inputName, majStatPtr, minStatPtr) gss_name_t *outputNamePtr; const gss_name_t inputName; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat; OM_uint32 minStat; majStat = gss_duplicate_name(&minStat, inputName, outputNamePtr); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return majStat == GSS_S_COMPLETE ? 1 : -1; } #endif int gfarmGssNewCredentialName(outputNamePtr, cred, majStatPtr, minStatPtr) gss_name_t *outputNamePtr; gss_cred_id_t cred; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat; OM_uint32 minStat; majStat = gss_inquire_cred(&minStat, cred, outputNamePtr, NULL, /* lifetime */ NULL, /* usage */ NULL /* supported mech */); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return majStat == GSS_S_COMPLETE ? 1 : -1; } char * gfarmGssNewDisplayName(inputName, majStatPtr, minStatPtr, outputNameTypePtr) const gss_name_t inputName; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; gss_OID *outputNameTypePtr; { OM_uint32 majStat; OM_uint32 minStat, minStat2; char *ret = NULL; gss_buffer_desc buf; gss_OID outputNameType; if (inputName == GSS_C_NO_NAME) { gflog_auth_error("gfarmGssNewDisplayName()","GSS_C_NO_NAME is passed"); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; } else if ((majStat = gss_display_name(&minStat, inputName, &buf, &outputNameType)) == GSS_S_COMPLETE) { ret = malloc(buf.length + 1); if (ret == NULL) { gflog_auth_error("gfarmGssNewDisplayName()", "no memory"); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; } else { ret[buf.length] = '\0'; memcpy(ret, buf.value, buf.length); (void)gss_release_buffer(&minStat2, &buf); if (outputNameTypePtr != NULL) { *outputNameTypePtr = outputNameType; } } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmGssAcquireCredential(credPtr, desiredName, credUsage, majStatPtr, minStatPtr, credNamePtr) gss_cred_id_t *credPtr; const gss_name_t desiredName; gss_cred_usage_t credUsage; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; gss_name_t *credNamePtr; { OM_uint32 majStat = 0; OM_uint32 minStat = 0; int ret = -1; gss_cred_id_t cred; *credPtr = GSS_C_NO_CREDENTIAL; majStat = gss_acquire_cred(&minStat, desiredName, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, credUsage, &cred, NULL, NULL); #if GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS if (majStat != GSS_S_COMPLETE) { OM_uint32 majStat2, majStat3; OM_uint32 minStat2, minStat3; /* * to workaround a problem that any proxy credential cannot be * acquired by using "/C=.../O=.../CN=<NAME>" as its name. * Globus requires "/C=.../O=.../CN=<NAME>/CN=proxy". */ majStat2 = gss_acquire_cred(&minStat2, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, credUsage, &cred, NULL, NULL); if (majStat2 == GSS_S_COMPLETE) { gss_name_t credName; if (gfarmGssNewCredentialName(&credName, cred, NULL, NULL) > 0) { int equal; majStat3 = gss_compare_name(&minStat3, desiredName, credName, &equal); if (majStat3 == GSS_S_COMPLETE && equal) { majStat = majStat2; minStat = minStat2; } gfarmGssDeleteName(&credName, NULL, NULL); } if (majStat != GSS_S_COMPLETE) { gfarmGssDeleteCredential(&cred, NULL, NULL); } } } #endif /* GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS */ /* * Check validness. */ if (majStat == GSS_S_COMPLETE) { if (credNamePtr == NULL) { ret = 1; } else if (gfarmGssNewCredentialName(credNamePtr, cred, &majStat, &minStat) > 0) { /* Only valid when the name is got. */ ret = 1; } if (ret > 0 && credPtr != NULL) { *credPtr = cred; } else { gfarmGssDeleteCredential(&cred, NULL, NULL); } } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmGssDeleteCredential(credPtr, majStatPtr, minStatPtr) gss_cred_id_t *credPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat = 0; OM_uint32 minStat = 0; int ret = -1; majStat = gss_release_cred(&minStat, credPtr); if (majStat == GSS_S_COMPLETE) { ret = 1; /* valid */ } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return ret; } int gfarmGssSendToken(fd, gsBuf) int fd; gss_buffer_t gsBuf; { gfarm_int32_t iLen = (gfarm_int32_t)(gsBuf->length); if (gfarmWriteInt32(fd, &iLen, 1) != 1) { return -1; } if (gfarmWriteInt8(fd, (gfarm_int8_t *)(gsBuf->value), iLen) != iLen) { return -1; } return iLen; } int gfarmGssReceiveToken(fd, gsBuf) int fd; gss_buffer_t gsBuf; { gfarm_int32_t iLen; gfarm_int8_t *buf = NULL; if (gsBuf->value != NULL) { OM_uint32 minStat; (void)gss_release_buffer(&minStat, gsBuf); } gsBuf->length = 0; gsBuf->value = NULL; if (gfarmReadInt32(fd, &iLen, 1) != 1) { return -1; } /* * XXXXX FIXME: * GSSAPI has no API for allocating a gss_buffer_t. It is not * recommended to allocate it with malloc(). */ buf = (void *)malloc(sizeof(char) * iLen); if (buf == NULL) { return -1; } if (gfarmReadInt8(fd, buf, iLen) != iLen) { (void)free(buf); return -1; } gsBuf->length = (size_t)iLen; gsBuf->value = (void *)buf; return iLen; } int gfarmGssAcceptSecurityContext(fd, cred, scPtr, majStatPtr, minStatPtr, remoteNamePtr, remoteCredPtr) int fd; gss_cred_id_t cred; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; gss_name_t *remoteNamePtr; gss_cred_id_t *remoteCredPtr; { OM_uint32 majStat; OM_uint32 minStat, minStat2; OM_uint32 retFlag = 0; gss_name_t initiatorName = GSS_C_NO_NAME; gss_cred_id_t remCred = GSS_C_NO_CREDENTIAL; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; gss_OID mechType = GSS_C_NO_OID; OM_uint32 timeRet; int tknStat; *scPtr = GSS_C_NO_CONTEXT; do { tknStat = gfarmGssReceiveToken(fd, itPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssAcceptSecurityContext()", "failed to receive response"); majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; minStat = GFSL_DEFAULT_MINOR_ERROR; break; } majStat = gss_accept_sec_context(&minStat, scPtr, cred, itPtr, GSS_C_NO_CHANNEL_BINDINGS, &initiatorName, &mechType, otPtr, &retFlag, &timeRet, &remCred); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { tknStat = gfarmGssSendToken(fd, otPtr); (void)gss_release_buffer(&minStat2, otPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssAcceptSecurityContext()", "failed to send response"); majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; minStat = GFSL_DEFAULT_MINOR_ERROR; } } if (GSS_ERROR(majStat)) { break; } } while (majStat & GSS_S_CONTINUE_NEEDED); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { (void)gss_release_buffer(&minStat2, otPtr); } if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (majStat == GSS_S_COMPLETE && remoteNamePtr != NULL) { *remoteNamePtr = initiatorName; } else if (initiatorName != GSS_C_NO_NAME) { (void)gss_release_name(&minStat2, &initiatorName); } if (majStat == GSS_S_COMPLETE && remoteCredPtr != NULL) { *remoteCredPtr = remCred; } else if (remCred != GSS_C_NO_CREDENTIAL) { (void)gss_release_cred(&minStat2, &remCred); } if (majStat != GSS_S_COMPLETE && *scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); } return majStat == GSS_S_COMPLETE ? 1 : -1; } int gfarmGssInitiateSecurityContext(fd, acceptorName, cred, reqFlag, scPtr, majStatPtr, minStatPtr, remoteNamePtr) int fd; const gss_name_t acceptorName; gss_cred_id_t cred; OM_uint32 reqFlag; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; gss_name_t *remoteNamePtr; { OM_uint32 majStat; OM_uint32 minStat, minStat2; OM_uint32 retFlag = 0; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; gss_OID *actualMechType = NULL; OM_uint32 timeRet; int tknStat; *scPtr = GSS_C_NO_CONTEXT; /* * Implementation specification: * In gfarm, an initiator must reveal own identity to an acceptor. */ if ((reqFlag & GSS_C_ANON_FLAG) == GSS_C_ANON_FLAG) { /* It is a bit safer to deny the request than to silently ignore it */ gflog_auth_error("gfarmGssInitiateSecurityContext()", "GSS_C_ANON_FLAG is not allowed"); majStat = GSS_S_UNAVAILABLE; minStat = GFSL_DEFAULT_MINOR_ERROR; goto Done; } while (1) { majStat = gss_init_sec_context(&minStat, cred, scPtr, acceptorName, GSS_C_NO_OID, reqFlag, 0, GSS_C_NO_CHANNEL_BINDINGS, itPtr, actualMechType, otPtr, &retFlag, &timeRet); if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { tknStat = gfarmGssSendToken(fd, otPtr); (void)gss_release_buffer(&minStat2, otPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssInitiateSecurityContext()", "failed to send response"); majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; minStat = GFSL_DEFAULT_MINOR_ERROR; } } if (GSS_ERROR(majStat)) { break; } if (majStat & GSS_S_CONTINUE_NEEDED) { tknStat = gfarmGssReceiveToken(fd, itPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssInitiateSecurityContext()", "failed to receive response"); majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; minStat = GFSL_DEFAULT_MINOR_ERROR; break; } } else { break; } } if (itPtr->length > 0) { (void)gss_release_buffer(&minStat2, itPtr); } if (otPtr->length > 0) { (void)gss_release_buffer(&minStat2, otPtr); } if (majStat == GSS_S_COMPLETE && remoteNamePtr != NULL) { majStat = gss_inquire_context(&minStat, *scPtr, NULL, remoteNamePtr, NULL, NULL, NULL, NULL, NULL); } Done: if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (majStat != GSS_S_COMPLETE && *scPtr != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, scPtr, GSS_C_NO_BUFFER); } return majStat == GSS_S_COMPLETE ? 1 : -1; } void gfarmGssDeleteSecurityContext(scPtr) gss_ctx_id_t *scPtr; { OM_uint32 minStat; if (scPtr == NULL || *scPtr == GSS_C_NO_CONTEXT) { return; } (void)gss_delete_sec_context(&minStat, scPtr, GSS_C_NO_BUFFER); } int gfarmGssConfigureMessageSize(sCtx, doEncrypt, qopReq, reqOutSz, maxInSzPtr, majStatPtr, minStatPtr) gss_ctx_id_t sCtx; int doEncrypt; gss_qop_t qopReq; unsigned int reqOutSz; unsigned int *maxInSzPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; OM_uint32 oReqSz = (OM_uint32)reqOutSz; OM_uint32 oMaxSz = oReqSz; majStat = gss_wrap_size_limit(&minStat, sCtx, doEncrypt, qopReq, oReqSz, &oMaxSz); if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } if (majStat == GSS_S_COMPLETE) { ret = 1; if (maxInSzPtr != NULL) { *maxInSzPtr = (int)oMaxSz; } } return ret; } int gfarmGssSend(fd, sCtx, doEncrypt, qopReq, buf, n, chunkSz, statPtr) int fd; gss_ctx_id_t sCtx; int doEncrypt; gss_qop_t qopReq; gfarm_int8_t *buf; int n; int chunkSz; OM_uint32 *statPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; int sum = 0; int rem = n; int len; gfarm_int32_t n_buf = n; /* * Send a length of a PLAIN TEXT. * XXXXX FIX ME: * Generally it is wrong idea sending a plain text length * in plain text communication. Should be encrypted. */ if (buf == NULL || n <= 0) { ret = 0; majStat = GSS_S_COMPLETE; goto Done; } if (gfarmWriteInt32(fd, &n_buf, 1) != 1) { majStat = GSS_S_CALL_INACCESSIBLE_WRITE; goto Done; } do { inputToken.value = (void *)((char *)(buf + sum)); len = (rem > chunkSz ? chunkSz : rem); inputToken.length = (size_t)len; majStat = gss_wrap(&minStat, sCtx, doEncrypt, qopReq, (const gss_buffer_t)itPtr, NULL, otPtr); if (majStat == GSS_S_COMPLETE) { if (otPtr->length > 0) { if (gfarmGssSendToken(fd, otPtr) <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; goto Done; } (void)gss_release_buffer(&minStat, otPtr); otPtr->length = 0; otPtr->value = NULL; rem -= len; sum += len; } else { majStat = GSS_S_DEFECTIVE_TOKEN; goto Done; } } else { break; } } while (rem > 0); if (rem <= 0) { ret = n; } Done: if (otPtr->length > 0) { (void)gss_release_buffer(&minStat, otPtr); } if (statPtr != NULL) { *statPtr = majStat; } return ret; } int gfarmGssReceive(fd, sCtx, bufPtr, lenPtr, statPtr) int fd; gss_ctx_id_t sCtx; gfarm_int8_t **bufPtr; int *lenPtr; OM_uint32 *statPtr; { int ret = -1; OM_uint32 majStat; OM_uint32 minStat; gss_buffer_desc inputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t itPtr = &inputToken; gss_buffer_desc outputToken = GSS_C_EMPTY_BUFFER; gss_buffer_t otPtr = &outputToken; gfarm_int32_t n; int sum = 0; int rem; int len; gfarm_int8_t *buf = NULL; int i; /* * Receive a length of a PLAIN TEXT. * XXXXX FIX ME: * Generally it is wrong idea receiving a plain text * length in plain text communication. Should be * encrypted. */ i = gfarmReadInt32(fd, &n, 1); if (i == 0) { ret = 0; n = 0; majStat = GSS_S_COMPLETE; goto Done; } else if (i != 1) { majStat = GSS_S_CALL_INACCESSIBLE_READ; goto Done; } buf = (char *)malloc(sizeof(*buf) * n); if (buf == NULL) { majStat = GSS_S_FAILURE; goto Done; } rem = n; do { if (gfarmGssReceiveToken(fd, itPtr) <= 0) { majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; goto Done; } majStat = gss_unwrap(&minStat, sCtx, (const gss_buffer_t)itPtr, otPtr, NULL, NULL); (void)gss_release_buffer(&minStat, itPtr); itPtr->length = 0; itPtr->value = NULL; if (majStat == GSS_S_COMPLETE) { if (otPtr->length > 0) { (void)memcpy((void *)(buf + sum), (void *)otPtr->value, otPtr->length); len = (int)(otPtr->length); rem -= len; sum += len; (void)gss_release_buffer(&minStat, otPtr); otPtr->length = 0; otPtr->value = NULL; } else { majStat = GSS_S_DEFECTIVE_TOKEN; goto Done; } } else { break; } } while (rem > 0); if (rem <= 0) { ret = n; } Done: if (otPtr->length > 0) { (void)gss_release_buffer(&minStat, otPtr); } if (itPtr->length > 0) { (void)gss_release_buffer(&minStat, itPtr); } if (statPtr != NULL) { *statPtr = majStat; } if (ret == -1) { *bufPtr = NULL; *lenPtr = -1; } else { *bufPtr = buf; *lenPtr = n; } return ret; } #if GFARM_GSS_EXPORT_CRED_ENABLED struct gfarmExportedCredential { char *env; char *filename; }; gfarmExportedCredential * gfarmGssExportCredential(cred, statPtr) gss_cred_id_t cred; OM_uint32 *statPtr; { gfarmExportedCredential *exportedCred = NULL; OM_uint32 majStat = 0; OM_uint32 minStat = 0; gss_buffer_desc buf = GSS_C_EMPTY_BUFFER; char *exported, *filename, *env; static char exported_name[] = "X509_USER_DELEG_PROXY="; static char env_name[] = "X509_USER_PROXY="; static char file_prefix[] = "FILE:"; majStat = gss_export_cred(&minStat, cred, GSS_C_NO_OID, 1, &buf); if (GSS_ERROR(majStat)) goto Done; exported = (char *)buf.value; for (filename = exported; *filename != '\0'; filename++) if (!isalnum(*(unsigned char *)filename) && *filename != '_') break; if (*filename != '=') { /* not an environment variable */ majStat = GSS_S_UNAVAILABLE; goto Done; } filename++; if (memcmp(exported, exported_name, sizeof(exported_name) - 1) == 0) { env = malloc(sizeof(env_name) + strlen(filename)); if (env == NULL) { majStat = GSS_S_FAILURE; goto Done; } memcpy(env, env_name, sizeof(env_name) - 1); strcpy(env + sizeof(env_name) - 1, filename); filename = env + sizeof(env_name) - 1; } else { env = strdup(exported); if (env == NULL) { majStat = GSS_S_FAILURE; goto Done; } filename = env + (filename - exported); } if (memcmp(filename, file_prefix, sizeof(file_prefix) - 1) == 0) filename += sizeof(file_prefix) - 1; exportedCred = malloc(sizeof(*exportedCred)); if (exportedCred == NULL) { free(env); majStat = GSS_S_FAILURE; goto Done; } exportedCred->env = env; exportedCred->filename = access(filename, R_OK) == 0 ? filename : NULL; Done: gss_release_buffer(&minStat, &buf); if (statPtr != NULL) *statPtr = majStat; return exportedCred; } char * gfarmGssEnvForExportedCredential(exportedCred) gfarmExportedCredential *exportedCred; { return exportedCred->env; } void gfarmGssDeleteExportedCredential(exportedCred) gfarmExportedCredential *exportedCred; { if (exportedCred->filename != NULL) unlink(exportedCred->filename); free(exportedCred->env); free(exportedCred); } #endif /* GFARM_GSS_EXPORT_CRED_ENABLED */ /* * multiplexed version of gfarmGssInitiateSecurityContext() */ struct gfarmGssInitiateSecurityContextState { struct gfarm_eventqueue *q; struct gfarm_event *readable, *writable; int fd; gss_cred_id_t cred; OM_uint32 reqFlag; void (*continuation)(void *); void *closure; int completed; OM_uint32 majStat; OM_uint32 minStat; gss_ctx_id_t sc; gss_name_t acceptorName; OM_uint32 retFlag; gss_buffer_desc inputToken; gss_buffer_t itPtr; gss_buffer_desc outputToken; gss_buffer_t otPtr; gss_OID *actualMechType; OM_uint32 timeRet; }; /* this function returns 1, if an event is added */ static int gssInitiateSecurityContextSwitch(state) struct gfarmGssInitiateSecurityContextState *state; { int rv; struct timeval timeout; if (GSS_ERROR(state->majStat)) { return 0; } if (state->majStat & GSS_S_CONTINUE_NEEDED) { timeout.tv_sec = GFARM_GSS_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); if (rv == 0) { /* go to gfarmGssInitiateSecurityContextReceiveToken() */ return 1; } gflog_auth_error("gfarm:gssInitiateSecurityContextSwitch()", strerror(rv)); state->majStat = GSS_S_FAILURE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } else { state->completed = 1; } return 0; } /* this function returns 1, if an event is added */ static int gssInitiateSecurityContextNext(state) struct gfarmGssInitiateSecurityContextState *state; { OM_uint32 minStat2; int rv; state->majStat = gss_init_sec_context(&state->minStat, state->cred, &state->sc, state->acceptorName, GSS_C_NO_OID, state->reqFlag, 0, GSS_C_NO_CHANNEL_BINDINGS, state->itPtr, state->actualMechType, state->otPtr, &state->retFlag, &state->timeRet); if (state->itPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->itPtr); } if (state->otPtr->length > 0) { rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL); if (rv == 0) { /* go to gfarmGssInitiateSecurityContextSendToken() */ return 1; } gflog_auth_error("gfarm:gssInitiateSecurityContextNext()", strerror(rv)); state->majStat = GSS_S_FAILURE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } return gssInitiateSecurityContextSwitch(state); } static void gfarmGssInitiateSecurityContextSendToken(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct gfarmGssInitiateSecurityContextState *state = closure; int tknStat; OM_uint32 minStat2; tknStat = gfarmGssSendToken(fd, state->otPtr); (void)gss_release_buffer(&minStat2, state->otPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssInitiateSecurityContextSendToken()", "failed to send response"); state->majStat = GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_WRITE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; } if (gssInitiateSecurityContextSwitch(state)) { return; } if (state->continuation != NULL) { (*state->continuation)(state->closure); } } static void gfarmGssInitiateSecurityContextReceiveToken(events, fd, closure, t) int events; int fd; void *closure; const struct timeval *t; { struct gfarmGssInitiateSecurityContextState *state = closure; int tknStat; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->majStat = GSS_S_UNAVAILABLE; /* failure: timeout */ } else { assert(events == GFARM_EVENT_READ); tknStat = gfarmGssReceiveToken(fd, state->itPtr); if (tknStat <= 0) { gflog_auth_error("gfarmGssInitiateSecurityContextReceiveToken()", "failed to receive response"); state->majStat= GSS_S_DEFECTIVE_TOKEN|GSS_S_CALL_INACCESSIBLE_READ; state->minStat= GFSL_DEFAULT_MINOR_ERROR; } else if (gssInitiateSecurityContextNext(state)) { return; } } assert(GSS_ERROR(state->majStat) || state->completed); if (state->continuation != NULL) (*state->continuation)(state->closure); } struct gfarmGssInitiateSecurityContextState * gfarmGssInitiateSecurityContextRequest(q, fd, acceptorName, cred, reqFlag, continuation, closure, majStatPtr, minStatPtr) struct gfarm_eventqueue *q; int fd; const gss_name_t acceptorName; gss_cred_id_t cred; OM_uint32 reqFlag; void (*continuation)(void *); void *closure; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; { OM_uint32 majStat; OM_uint32 minStat; struct gfarmGssInitiateSecurityContextState *state; /* * Implementation specification: * In gfarm, an initiator must reveal own identity to an acceptor. */ if ((reqFlag & GSS_C_ANON_FLAG) == GSS_C_ANON_FLAG) { /* It is a bit safer to deny the request than to silently ignore it */ gflog_auth_error("gfarmGssInitiateSecurityContextRequest()", "GSS_C_ANON_FLAG is not allowed"); majStat = GSS_S_UNAVAILABLE; minStat = GFSL_DEFAULT_MINOR_ERROR; goto ReturnStat; } state = malloc(sizeof(*state)); if (state == NULL) { gflog_auth_error("gfarmGssInitiateSecurityContextRequest()", "no memory"); majStat = GSS_S_FAILURE; minStat = GFSL_DEFAULT_MINOR_ERROR; goto ReturnStat; } state->completed = 0; state->majStat = GSS_S_COMPLETE; state->minStat = GFSL_DEFAULT_MINOR_ERROR; state->writable = gfarm_fd_event_alloc(GFARM_EVENT_WRITE, fd, gfarmGssInitiateSecurityContextSendToken, state); if (state->writable == NULL) { gflog_auth_error("gfarmGssInitiateSecurityContextRequest()", "no memory"); state->majStat = GSS_S_FAILURE; goto FreeState; } /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc(GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, fd, gfarmGssInitiateSecurityContextReceiveToken, state); if (state->readable == NULL) { gflog_auth_error("gfarmGssInitiateSecurityContextRequest()", "no memory"); state->majStat = GSS_S_FAILURE; goto FreeWritable; } state->q = q; state->fd = fd; state->acceptorName = acceptorName; state->cred = cred; state->reqFlag = reqFlag; state->continuation = continuation; state->closure = closure; state->retFlag = 0; /* GSS_C_EMPTY_BUFFER */ state->inputToken.length = 0; state->inputToken.value = NULL; state->itPtr = &state->inputToken; /* GSS_C_EMPTY_BUFFER */ state->outputToken.length = 0; state->outputToken.value = NULL; state->otPtr = &state->outputToken; state->actualMechType = NULL; state->sc = GSS_C_NO_CONTEXT; gssInitiateSecurityContextNext(state); assert(!state->completed); if (!GSS_ERROR(state->majStat)) { if (majStatPtr != NULL) { *majStatPtr = GSS_S_COMPLETE; } if (minStatPtr != NULL) { *minStatPtr = GFSL_DEFAULT_MINOR_ERROR; } return (state); } gfarm_event_free(state->readable); FreeWritable: gfarm_event_free(state->writable); FreeState: majStat = state->majStat; minStat = state->minStat; free(state); ReturnStat: if (majStatPtr != NULL) { *majStatPtr = majStat; } if (minStatPtr != NULL) { *minStatPtr = minStat; } return (NULL); } int gfarmGssInitiateSecurityContextResult(state, scPtr, majStatPtr, minStatPtr, remoteNamePtr) struct gfarmGssInitiateSecurityContextState *state; gss_ctx_id_t *scPtr; OM_uint32 *majStatPtr; OM_uint32 *minStatPtr; gss_name_t *remoteNamePtr; { int ret; OM_uint32 minStat2; assert(GSS_ERROR(state->majStat) || state->completed); if (state->itPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->itPtr); } if (state->otPtr->length > 0) { (void)gss_release_buffer(&minStat2, state->otPtr); } if (state->majStat == GSS_S_COMPLETE && remoteNamePtr != NULL) { state->majStat = gss_inquire_context(&state->minStat, state->sc, NULL, remoteNamePtr, NULL, NULL, NULL, NULL, NULL); } gfarm_event_free(state->readable); gfarm_event_free(state->writable); if (majStatPtr != NULL) { *majStatPtr = state->majStat; } if (minStatPtr != NULL) { *minStatPtr = state->minStat; } if (state->majStat == GSS_S_COMPLETE) { *scPtr = state->sc; } else if (state->sc != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat2, &state->sc, GSS_C_NO_BUFFER); } ret = state->majStat == GSS_S_COMPLETE ? 1 : -1; free(state); return ret; } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfutil/logutil.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <syslog.h> #include <string.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" static char *log_identifier = "libgfarm"; static char *log_auxiliary_info = NULL; static int log_use_syslog = 0; void gflog_message(int priority, char *message, char *status) { if (log_auxiliary_info != NULL) { if (status != NULL) { if (log_use_syslog) syslog(priority, "(%s) %s: %s", log_auxiliary_info, message, status); else fprintf(stderr, "%s: (%s) %s: %s\n", log_identifier, log_auxiliary_info, message, status); } else { if (log_use_syslog) syslog(priority, "(%s) %s", log_auxiliary_info, message); else fprintf(stderr, "%s: (%s) %s\n", log_identifier, log_auxiliary_info, message); } } else { if (status != NULL) { if (log_use_syslog) syslog(priority, "%s: %s", message, status); else fprintf(stderr, "%s: %s: %s\n", log_identifier, message, status); } else { if (log_use_syslog) syslog(priority, "%s", message); else fprintf(stderr, "%s: %s\n", log_identifier, message); } } } void gflog_error(char *message, char *status) { gflog_message(LOG_ERR, message, status); } void gflog_warning(char *message, char *status) { gflog_message(LOG_WARNING, message, status); } void gflog_warning_errno(char *message) { gflog_warning(message, strerror(errno)); } void gflog_fatal(char *message, char *status) { gflog_error(message, status); exit(2); } void gflog_fatal_errno(char *message) { gflog_fatal(message, strerror(errno)); } void gflog_set_identifier(char *identifier) { log_identifier = identifier; } void gflog_set_auxiliary_info(char *aux_info) { log_auxiliary_info = aux_info; } void gflog_syslog_open(int syslog_option, int syslog_facility) { openlog(log_identifier, syslog_option, syslog_facility); log_use_syslog = 1; } int gflog_syslog_name_to_facility(char *name) { int i; struct { char *name; int facility; } syslog_facilities[] = { { "kern", LOG_KERN }, { "user", LOG_USER }, { "mail", LOG_MAIL }, { "daemon", LOG_DAEMON }, { "auth", LOG_AUTH }, { "syslog", LOG_SYSLOG }, { "lpr", LOG_LPR }, { "news", LOG_NEWS }, { "uucp", LOG_UUCP }, { "cron", LOG_CRON }, #ifdef LOG_AUTHPRIV { "authpriv", LOG_AUTHPRIV }, #endif #ifdef LOG_FTP { "ftp", LOG_FTP }, #endif { "local0", LOG_LOCAL0 }, { "local1", LOG_LOCAL1 }, { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, { "local6", LOG_LOCAL6 }, { "local7", LOG_LOCAL7 }, }; for (i = 0; i < GFARM_ARRAY_LENGTH(syslog_facilities); i++) { if (strcmp(syslog_facilities[i].name, name) == 0) return (syslog_facilities[i].facility); } return (-1); /* not found */ } <file_sep>/gfarm_hadoop/tags/gfarm_hadoop_1_0_0/GfarmFSNative.cpp #include "org_apache_hadoop_fs_gfarmfs_GfarmFSNative.h" #include "org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel.h" #include "org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel.h" #include <gfarm/gfarm.h> #include <cassert> #include <iostream> #include <string> #include <vector> using namespace std; //----------------------------------------------------------------------------- // Utilities // namespace { inline string jstr2cppstr(JNIEnv *env, jstring src) { string cpps; char const * s = env->GetStringUTFChars(src, 0); cpps.assign(s); env->ReleaseStringUTFChars(src, s); return cpps; } inline void throw_io_exception(JNIEnv *env, const string& s){ jclass clazz = env->FindClass("java/io/IOException"); assert(clazz != 0); env->ThrowNew(clazz, s.c_str()); } inline void throw_file_not_found_exception(JNIEnv *env, const string& s, const string& path){ jclass clazz = env->FindClass("java/io/FileNotFoundException"); assert(clazz != 0); string msg = s + ": " + path; env->ThrowNew(clazz, msg.c_str()); } } //----------------------------------------------------------------------------- // class GfarmFSNative // JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_init (JNIEnv *env, jclass cls) { return gfarm_initialize(0, NULL); } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_terminate (JNIEnv *env, jclass cls) { return gfarm_terminate(); } JNIEXPORT jstring JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_getErrorString (JNIEnv *env, jclass cls, jint e) { return env->NewStringUTF(gfarm_error_string(e)); } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_mkdir (JNIEnv *env, jclass cls, jstring jstrpath) { string path = jstr2cppstr(env, jstrpath); gfarm_error_t e = gfs_mkdir(path.c_str(), 0755); if(e != GFARM_ERR_NO_ERROR && e != GFARM_ERR_ALREADY_EXISTS) goto err; return 0; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_rmdir (JNIEnv *env, jclass cls, jstring jstrpath) { string path = jstr2cppstr(env, jstrpath); return gfs_rmdir(path.c_str()); } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_rename (JNIEnv *env, jclass cls, jstring jstrsrc, jstring jstrdst) { string src = jstr2cppstr(env, jstrsrc); string dst = jstr2cppstr(env, jstrdst); return gfs_rename(src.c_str(), dst.c_str()); } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_remove (JNIEnv *env, jclass cls, jstring jstrpath) { string path = jstr2cppstr(env, jstrpath); return gfs_remove(path.c_str()); } JNIEXPORT jboolean JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_isDirectory (JNIEnv *env, jclass cls, jstring jstrpath) { jboolean r; string path = jstr2cppstr(env, jstrpath); struct gfs_stat s; gfarm_error_t e = gfs_stat(path.c_str(), &s); if(e != GFARM_ERR_NO_ERROR) goto err; r = (GFARM_S_ISDIR(s.st_mode)) ? JNI_TRUE : JNI_FALSE; gfs_stat_free(&s); return r; err: return JNI_FALSE; } JNIEXPORT jboolean JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_isFile (JNIEnv *env, jclass cls, jstring jstrpath) { jboolean r; string path = jstr2cppstr(env, jstrpath); struct gfs_stat s; gfarm_error_t e = gfs_stat(path.c_str(), &s); if(e != GFARM_ERR_NO_ERROR) goto err; r = (GFARM_S_ISREG(s.st_mode)) ? JNI_TRUE : JNI_FALSE; gfs_stat_free(&s); return r; err: return JNI_FALSE; } JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_getFileSize (JNIEnv *env, jclass cls, jstring jstrpath) { jlong r; string path = jstr2cppstr(env, jstrpath); struct gfs_stat s; gfarm_error_t e = gfs_stat(path.c_str(), &s); if(e != GFARM_ERR_NO_ERROR) goto err; r = s.st_size; gfs_stat_free(&s); return r; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_getModificationTime (JNIEnv *env, jclass cls, jstring jstrpath) { jlong r; string path = jstr2cppstr(env, jstrpath); struct gfs_stat s; gfarm_error_t e = gfs_stat(path.c_str(), &s); if(e != GFARM_ERR_NO_ERROR) goto err; r = s.st_mtimespec.tv_sec * 1000; // TODO: Is this ok? gfs_stat_free(&s); return r; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_getReplication (JNIEnv *env, jclass cls, jstring jstrpath) { jlong r; string path = jstr2cppstr(env, jstrpath); struct gfs_stat s; gfarm_error_t e = gfs_stat(path.c_str(), &s); if(e != GFARM_ERR_NO_ERROR) goto err; r = s.st_ncopy; gfs_stat_free(&s); return r; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jobjectArray JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_readdir (JNIEnv *env, jclass cls, jstring jstrpath) { jobjectArray jentries; string path = jstr2cppstr(env, jstrpath); vector<string> v; gfarm_error_t e; GFS_Dir dir; struct gfs_dirent *entry; e = gfs_opendir(path.c_str(), &dir); if(e != GFARM_ERR_NO_ERROR){ if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) goto err_not_found; else goto err; } while ((e = gfs_readdir(dir, &entry)) == GFARM_ERR_NO_ERROR && entry != NULL) v.push_back(entry->d_name); gfs_closedir(dir); if(e != GFARM_ERR_NO_ERROR) goto err; // Construct String[] from vector<string> jentries = env->NewObjectArray(v.size(), env->FindClass("Ljava/lang/String;"), NULL); for(unsigned int i=0; i<v.size(); i++){ jstring s = env->NewStringUTF(v[i].c_str()); env->SetObjectArrayElement(jentries, i, s); env->DeleteLocalRef(s); } return jentries; err: throw_io_exception(env, gfarm_error_string(e)); return NULL; err_not_found: throw_file_not_found_exception(env, gfarm_error_string(e), path); return NULL; } JNIEXPORT jobjectArray JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNative_getDataLocation (JNIEnv *env, jclass cls, jstring jstrpath, jlong start, jlong len) { string path = jstr2cppstr(env, jstrpath); gfarm_error_t e; int n; char **hosts; jclass jstrClass = env->FindClass("Ljava/lang/String;"); jstring s; e = gfs_replica_list_by_name(path.c_str(), &n, &hosts); jobjectArray jentries = env->NewObjectArray(n, jstrClass, NULL); if (e == GFARM_ERR_NO_ERROR) { for (int i = 0; i < n; i++) { s = env->NewStringUTF(hosts[i]); env->SetObjectArrayElement(jentries, i, s); env->DeleteLocalRef(s); } } for (int i = 0; i < n; ++i) free(hosts[i]); free(hosts); return jentries; } //----------------------------------------------------------------------------- // class GfarmFSNativeOutputChannel // JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_open (JNIEnv *env, jclass cls, jstring jstrpath) { string path = jstr2cppstr(env, jstrpath); GFS_File f = NULL; gfarm_error_t e = gfs_pio_create(path.c_str(), GFARM_FILE_WRONLY | GFARM_FILE_TRUNC, 0644, &f); if(e != GFARM_ERR_NO_ERROR) goto err; return (jlong)f; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); if(f != NULL) gfs_pio_close(f); return 0; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_close (JNIEnv *env, jclass cls, jlong jptr) { GFS_File f = (GFS_File)jptr; if(f == NULL) return 0; gfarm_error_t e = gfs_pio_close(f); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_write (JNIEnv *env, jclass cls, jlong jptr, jobject jbuf, jint begin, jint end) { GFS_File f = (GFS_File)jptr; if(jbuf == NULL) return 0; void * addr = env->GetDirectBufferAddress(jbuf); jlong cap = env->GetDirectBufferCapacity(jbuf); if(addr == NULL || cap < 0) return 0; if(begin < 0 || end > cap || begin >= end) return 0; addr = (void *)(uintptr_t(addr) + begin); int ret = 0; gfarm_error_t e = gfs_pio_write(f, addr, (end - begin), &ret); if(e != GFARM_ERR_NO_ERROR) goto err; return ret; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_flush (JNIEnv *env, jclass cls, jlong jptr) { gfarm_error_t e; GFS_File f = (GFS_File)jptr; if(f == NULL) return 0; e = gfs_pio_flush(f); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_sync (JNIEnv *env, jclass cls, jlong jptr) { gfarm_error_t e; GFS_File f = (GFS_File)jptr; if(f == NULL) return 0; e = gfs_pio_flush(f); if(e != GFARM_ERR_NO_ERROR) goto err; e = gfs_pio_sync(f); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_seek (JNIEnv *env, jclass cls, jlong jptr, jlong joffset) { GFS_File f = (GFS_File)jptr; gfarm_error_t e = gfs_pio_seek(f, joffset, GFARM_SEEK_SET /* from beginning */, NULL); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeOutputChannel_tell (JNIEnv *env, jclass cls, jlong jptr) { GFS_File f = (GFS_File)jptr; gfarm_off_t cur; gfarm_error_t e = gfs_pio_seek(f, 0, GFARM_SEEK_CUR /* from current */, &cur); if(e != GFARM_ERR_NO_ERROR) goto err; return cur; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } //----------------------------------------------------------------------------- // class GfarmFSNativeInputChannel // JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel_open (JNIEnv *env, jclass cls, jstring jstrpath) { string path = jstr2cppstr(env, jstrpath); GFS_File f = NULL; gfarm_error_t e = gfs_pio_open(path.c_str(), GFARM_FILE_RDONLY, &f); if(e != GFARM_ERR_NO_ERROR) goto err; return (jlong)f; err: if(e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY) throw_file_not_found_exception(env, gfarm_error_string(e), path); else throw_io_exception(env, gfarm_error_string(e)); if(f != NULL) gfs_pio_close(f); return 0; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel_close (JNIEnv *env, jclass cls, jlong jptr) { GFS_File f = (GFS_File)jptr; if(f == NULL) return 0; gfarm_error_t e = gfs_pio_close(f); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel_read (JNIEnv *env, jclass cls, jlong jptr, jobject jbuf, jint begin, jint end) { GFS_File f = (GFS_File)jptr; if(jbuf == NULL) return 0; void * addr = env->GetDirectBufferAddress(jbuf); jlong cap = env->GetDirectBufferCapacity(jbuf); if(addr == NULL || cap < 0) return 0; if(begin < 0 || end > cap || begin >= end) return 0; addr = (void *)(uintptr_t(addr) + begin); int ret = 0; gfarm_error_t e = gfs_pio_read(f, addr, (end - begin), &ret); if(e != GFARM_ERR_NO_ERROR) goto err; return ret; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jint JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel_seek (JNIEnv *env, jclass cls, jlong jptr, jlong joffset) { GFS_File f = (GFS_File)jptr; gfarm_error_t e = gfs_pio_seek(f, joffset, GFARM_SEEK_SET /* from beginning */, NULL); if(e != GFARM_ERR_NO_ERROR) goto err; return 0; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } JNIEXPORT jlong JNICALL Java_org_apache_hadoop_fs_gfarmfs_GfarmFSNativeInputChannel_tell (JNIEnv *env, jclass cls, jlong jptr) { GFS_File f = (GFS_File)jptr; gfarm_off_t cur; gfarm_error_t e = gfs_pio_seek(f, 0, GFARM_SEEK_CUR /* from current */, &cur); if(e != GFARM_ERR_NO_ERROR) goto err; return cur; err: throw_io_exception(env, gfarm_error_string(e)); return -1; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/include/gfarm/gfarm_error.h /* * address constants which represents error conditions * * $Id$ */ /* classic errno (1..10, 12..34) */ extern char GFARM_ERR_OPERATION_NOT_PERMITTED[]; /* forbidden entirely */ extern char GFARM_ERR_NO_SUCH_OBJECT[]; extern char GFARM_ERR_INTERRUPTED_SYSTEM_CALL[]; extern char GFARM_ERR_INPUT_OUTPUT[]; extern char GFARM_ERR_NO_MEMORY[]; extern char GFARM_ERR_PERMISSION_DENIED[]; /* prohibited by access control */ extern char GFARM_ERR_ALREADY_EXISTS[]; extern char GFARM_ERR_NOT_A_DIRECTORY[]; extern char GFARM_ERR_IS_A_DIRECTORY[]; extern char GFARM_ERR_INVALID_ARGUMENT[]; extern char GFARM_ERR_NO_SPACE[]; extern char GFARM_ERR_READ_ONLY_FILE_SYSTEM[]; /* non classic, non-blocking and interrupt i/o */ extern char GFARM_ERR_RESOURCE_TEMPORARILY_UNAVAILABLE[]; /* non classic, filesystem related errors */ extern char GFARM_ERR_DISK_QUOTA_EXCEEDED[]; extern char GFARM_ERR_DIRECTORY_NOT_EMPTY[]; /* math software */ extern char GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE[]; /* ipc/network errors */ extern char GFARM_ERR_OPERATION_NOT_SUPPORTED[]; extern char GFARM_ERR_AUTHENTICATION[]; extern char GFARM_ERR_EXPIRED[]; extern char GFARM_ERR_PROTOCOL_NOT_SUPPORTED[]; extern char GFARM_ERR_PROTOCOL[]; extern char GFARM_ERR_NETWORK_IS_UNREACHABLE[]; extern char GFARM_ERR_NO_ROUTE_TO_HOST[]; extern char GFARM_ERR_CONNECTION_TIMED_OUT[]; extern char GFARM_ERR_CONNECTION_REFUSED[]; extern char GFARM_ERR_CONNECTION_RESET_BY_PEER[]; extern char GFARM_ERR_UNKNOWN_HOST[]; /* gfarm specific errors */ extern char GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING[]; extern char GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE[]; extern char GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH[]; extern char GFARM_ERR_AMBIGUOUS_RESULT[]; extern char GFARM_ERR_INCONSISTENT_RECOVERABLE[]; extern char GFARM_ERR_NO_FRAGMENT_INFORMATION[]; extern char GFARM_ERR_UNKNOWN[]; int gfarm_error_to_errno(const char *); char *gfarm_errno_to_error(int); void gfarm_error_initialize(void); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_3/gfarm2fs.h #ifndef HAVE_GFS_GETXATTR_CACHED #define gfs_getxattr_cached gfs_getxattr #endif struct gfarm2fs_param { const char *mount_point; int foreground; int debug; double cache_timeout; int use_syslog; char *facility; char *loglevel; int ncopy; int copy_limit; int fix_acl; int disable_acl; int enable_cached_id; int auto_uid_min; int auto_uid_max; int auto_gid_min; int auto_gid_max; }; struct gfarmized_path { int alloced; char *path; }; gfarm_error_t gfarmize_path(const char *, struct gfarmized_path *); void free_gfarmized_path(struct gfarmized_path *); <file_sep>/gfarm/tags/gfarm_1_0_4/doc/docbook/ja/ref/man1/Makefile.inc DOCBOOK = \ digest.1 \ gfcd.1 \ gfdf.1 \ gfexec.1 \ gfexport.1 \ gfgrep.1 \ gfhost.1 \ gfimport_fixed.1 \ gfimport_text.1 \ gfkey.1 \ gfls.1 \ gfmkdir.1 \ gfmpirun_p4.1 \ gfps.1 \ gfpwd.1 \ gfrcmd.1 \ gfreg.1 \ gfrep.1 \ gfrm.1 \ gfrmdir.1 \ gfront.1 \ gfrun.1 \ gfsched.1 \ gfsetdir.1 \ gfstat.1 \ gfwc.1 \ gfwhere.1 \ gfwhoami.1 <file_sep>/gfarm/tags/gfarm_1_0_rc2/lib/libgfarm/gfsl/tcputil.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #ifdef USE_GLOBUS_LIBC_HOOK #include "globus_libc.h" #endif /* USE_GLOBUS_LIBC_HOOK */ #include <gfarm/gfarm_config.h> #include "tcputil.h" #define MAX_BACKLOG 10 static int isNonBlock(int fd); static int isNonBlock(fd) int fd; { int stat = fcntl(fd, F_GETFL, 0); if (stat < 0) { perror("fcntl"); return 0; } else { if (stat & O_NONBLOCK) { return 1; } else { return 0; } } } int gfarmTCPConnectPort(addr, port) unsigned long addr; int port; { struct sockaddr_in sin; int sock; memset((void *)&sin, 0, sizeof(struct sockaddr_in)); if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return -1; } sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = htonl(addr); ReConnect: errno = 0; if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) != 0) { if (errno == EINTR) { goto ReConnect; } else if (errno == EINPROGRESS) { if (isNonBlock(sock) == 0) { goto Error; } else { sleep(1); return sock; } } else { Error: perror("connect"); return -1; } } return sock; } int gfarmTCPBindPort(port) int port; { struct sockaddr_in sin; int sock; int one = 1; memset((void *)&sin, 0, sizeof(struct sockaddr_in)); if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return -1; } sin.sin_family = AF_INET; sin.sin_port = htons((unsigned short)port); sin.sin_addr.s_addr = htonl(INADDR_ANY); if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(int)) != 0) { perror("setsockopt"); close(sock); return -1; } if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) != 0) { perror("bind"); close(sock); return -1; } if (listen(sock, MAX_BACKLOG) != 0) { perror("listen"); close(sock); return -1; } return sock; } unsigned long int gfarmIPGetAddressOfHost(host) char *host; { struct hostent *h = gethostbyname(host); if (h != NULL) { return ntohl(*(unsigned long *)(h->h_addr)); } else { /* * maybe host is XXX.XXX.XXX.XXX format. */ return ntohl(inet_addr(host)); } } char * gfarmIPGetHostOfAddress(addr) unsigned long int addr; { /* * addr must be Host Byte Order. */ char *ret = NULL; unsigned long caddr = htonl(addr); struct hostent *h = NULL; #ifndef USE_GLOBUS_LIBC_HOOK h = gethostbyaddr((void *)&caddr, sizeof(unsigned long int), AF_INET); #else { struct hostent gH; char gBuf[4096]; int gh_errno = 0; h = globus_libc_gethostbyaddr_r((void *)&caddr, sizeof(unsigned long int), AF_INET, &gH, gBuf, 4096, &gh_errno); } #endif /* USE_GLOBUS_LIBC_HOOK */ if (h != NULL) { ret = strdup(h->h_name); } else { char hostBuf[4096]; #ifdef HAVE_SNPRINTF snprintf(hostBuf, sizeof hostBuf, "%d.%d.%d.%d", (int)((addr & 0xff000000) >> 24), (int)((addr & 0x00ff0000) >> 16), (int)((addr & 0x0000ff00) >> 8), (int)(addr & 0x000000ff)); #else sprintf(hostBuf, "%d.%d.%d.%d", (int)((addr & 0xff000000) >> 24), (int)((addr & 0x00ff0000) >> 16), (int)((addr & 0x0000ff00) >> 8), (int)(addr & 0x000000ff)); #endif ret = strdup(hostBuf); } return ret; } unsigned long int gfarmIPGetPeernameOfSocket(sock, portPtr) int sock; int *portPtr; { struct sockaddr_in sin; int slen = sizeof(sin); if (getpeername(sock, (struct sockaddr *)&sin, &slen) != 0) { perror("getpeername"); if (portPtr != NULL) { *portPtr = 0; } return 0; } if (portPtr != NULL) { *portPtr = (int)ntohs(sin.sin_port); } return ntohl(sin.sin_addr.s_addr); } unsigned long int gfarmIPGetNameOfSocket(sock, portPtr) int sock; int *portPtr; { struct sockaddr_in sin; int slen = sizeof(sin); if (getsockname(sock, (struct sockaddr *)&sin, &slen) != 0) { perror("getsockname"); if (portPtr != NULL) { *portPtr = 0; } return 0; } if (portPtr != NULL) { *portPtr = (int)ntohs(sin.sin_port); } return ntohl(sin.sin_addr.s_addr); } int gfarmWaitReadable(fd) int fd; { fd_set rFd; int sel; FD_ZERO(&rFd); FD_SET(fd, &rFd); SelectAgain: errno = 0; sel = select(fd + 1, &rFd, NULL, NULL, NULL); if (sel < 0) { if (errno == EINTR) { goto SelectAgain; } else { perror("select"); return sel; } } return sel; } int gfarmReadBytes(fd, buf, len) int fd; char *buf; int len; { int sum = 0; int cur = 0; int sel; do { sel = gfarmWaitReadable(fd); if (sel <= 0) { return sum; } cur = read(fd, buf + sum, len - sum); if (cur < 0) { perror("read"); return sum; } else if (cur == 0) { break; } sum += cur; } while (sum < len); return sum; } int gfarmReadShorts(fd, buf, len) int fd; short *buf; int len; { int i; int n; short s; for (i = 0; i < len; i++) { n = gfarmReadBytes(fd, (char *)&s, sizeof(short)); if (sizeof(short) != n) { return i; } buf[i] = ntohs(s); } return i; } int gfarmReadLongs(fd, buf, len) int fd; long *buf; int len; { int i; int n; long l; for (i = 0; i < len; i++) { n = gfarmReadBytes(fd, (char *)&l, sizeof(long)); if (sizeof(long) != n) { return i; } buf[i] = ntohl(l); } return i; } int gfarmWriteBytes(fd, buf, len) int fd; char *buf; int len; { int sum = 0; int cur = 0; do { cur = write(fd, buf + sum, len - sum); if (cur < 0) { perror("write"); return sum; } sum += cur; } while (sum < len); return sum; } int gfarmWriteShorts(fd, buf, len) int fd; short *buf; int len; { int i; int n; short s; for (i = 0; i < len; i++) { s = htons(buf[i]); n = gfarmWriteBytes(fd, (char *)&s, sizeof(short)); if (sizeof(short) != n) { return i; } } return i; } int gfarmWriteLongs(fd, buf, len) int fd; long *buf; int len; { int i; int n; long l; for (i = 0; i < len; i++) { l = htonl(buf[i]); n = gfarmWriteBytes(fd, (char *)&l, sizeof(long)); if (sizeof(long) != n) { return i; } } return i; } <file_sep>/gfarm/tags/gfarm_1_0_beta_5_fix1/gfptool/gfcp_hook/gfcp_hook.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gfarm/gfarm.h> #include <gfarm/gfs_hook.h> char *program_name = "gfcp_hook"; void usage() { fprintf(stderr, "Usage: %s [option] <input_file> <output_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\tcurrently no option supported\n"); exit(1); } #define BUFSIZE 65536 int main(int argc, char *argv[]) { extern char *optarg; extern int optind; int node_index = -1; char *e, *input, *output; int ifd, ofd; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; --argc; ++argv; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing input file name\n", program_name); } exit(1); } input = argv[0]; argc--; argv++; if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing output file name\n", program_name); } exit(1); } output = argv[0]; argc--; argv++; if (argc != 0) { if (node_index == 0) { fprintf(stderr, "%s: currently, " "only one input file is supported\n", program_name); } exit(1); } ofd = creat(output, 0666); if (ofd == -1) { perror(output); exit(1); } ifd = open(input, O_RDONLY); if (ifd == -1) { perror(input); exit(1); } /* copy this fragment */ for (;;) { int rv, wv; char buffer[BUFSIZE]; rv = read(ifd, buffer, sizeof(buffer)); if (rv <= 0) break; wv = write(ofd, buffer, rv); if (wv <= 0) break; } if (close(ifd)) perror(input); if (close(ofd)) perror(output); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_4/lib/gfs_hook/sysdep/linux/Makefile # $Id$ top_builddir = ../../../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk # do not use $(COMMON_CFLAGS) here, to avoid symbol renaming by largefile API. CFLAGS = -I$(srcdir) -I$(top_srcdir)/lib/gfs_hook -Doff64_t=__off64_t LIBRARY = libsysdep.la LIBRARY_RESULT = # do not install LARGEFILE64_SRCS = getdents64.c xstat64.c lxstat64.c fxstat64.c LARGEFILE64_OBJS = getdents64.lo xstat64.lo lxstat64.lo fxstat64.lo SRCS = getdents.c xstat.c lxstat.c fxstat.c xstatconv.c \ ${largefile64_srcs} OBJS = getdents.lo xstat.lo lxstat.lo fxstat.lo \ ${largefile64_objs} all: $(LIBRARY) include $(top_srcdir)/makes/lib.mk getdents.lo: getdents.c getdents64.lo: getdents64.c getdents.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -c $(srcdir)/getdents64.c xstat.lo: xstat.c xstatconv.c lxstat.lo: lxstat.c xstatconv.c fxstat.lo: fxstat.c xstatconv.c xstat64.lo: xstat64.c xstatconv.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -c $(srcdir)/xstat64.c lxstat64.lo: lxstat64.c xstatconv.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -c $(srcdir)/lxstat64.c fxstat64.lo: fxstat64.c xstatconv.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -c $(srcdir)/fxstat64.c <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT1-2-5-2_zabbix_master_down #! /bin/sh ###################################################################### TESTID="FT1-2-5-2" CATEGORY="accident causes no failover" SECTION="observer accident" TITLE="zabbix master down" ###################################################################### . ./FT-common ft_setup() { [ `hostname` != $zabbix2 ] || return $FT_RESULT_FAIL SERVICE_PATH=/sbin/service return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $zabbix2 sudo $SERVICE_PATH zabbix-server stop \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop zabbix child server on $zabbix2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "zabbix_server is not running on $zabbix2" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ssh $zabbix2 sudo $SERVICE_PATH zabbix-server start \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "start zabbix child server on $zabbix2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: zabbix_server is not running on $zabbix2" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { ssh $zabbix2 sudo $SERVICE_PATH zabbix-server start return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT3-1-2-1_master_gfmd_and_candidate_gfmd_down #! /bin/sh ######################################################################## TESTID="FT3-1-2-1" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master and master candidate gfmd are down" ######################################################################## . ./FT-common ft_setup() { FT_MAIL_TIMEOUT=900 return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ft_checkpoint 1 "find master candidate gfmd" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop master candidate gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd2 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop master candidate gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "slave gfmd is not running on $gfmd2" \ "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_pgsql.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # database prefixes=$2 # exec check command RESULT=-1 case "$1" in version) RESULT=`psql --version|head -n1` ;; process) SQL="SELECT SUM(numbackends) FROM pg_stat_database" RESULT=`gfarm_pgsql_exec "${prefixes}" "${SQL}" | average_or_error` ;; commit) SQL="SELECT SUM(xact_commit) FROM pg_stat_database" RESULT=`gfarm_pgsql_exec "${prefixes}" "${SQL}" | average_or_error` ;; rollback) SQL="SELECT SUM(xact_rollback) FROM pg_stat_database" RESULT=`gfarm_pgsql_exec "${prefixes}" "${SQL}" | average_or_error` ;; *) RESULT=-1 esac if [ $? != 0 ]; then RESULT=-1 fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/io_gfsl.h struct xxx_connection; struct gfarmSecSession; struct gfarm_iobuffer; char *gfarm_gsi_initialize(void); char *gfarm_auth_request_gsi(struct xxx_connection *); char *gfarm_authorize_gsi(struct xxx_connection *, int, char **); char *xxx_connection_set_secsession(struct xxx_connection *, struct gfarmSecSession *); void xxx_connection_reset_secsession(struct xxx_connection *); void gfarm_iobuffer_write_close_secsession_op(struct gfarm_iobuffer *, void *, int); <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_listenport_gfsd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo "error: ${CONF_FILE} does not exist." exit 0 fi # create the temporary file tmpfile=`mktemp` trap "rm -f $tmpfile >/dev/null 2>&1" EXIT netstat_options="-alnNt" netstat ${netstat_options} > $tmpfile if [ $? != 0 ]; then echo "error: netstat ${netstat_options} error." exit 1 fi c=0 while read prefix gfsdhost port listen_aadress; do if [ "`grep LISTEN ${tmpfile} | awk '{print $4}' | grep -c :${port}$`" -eq 0 ]; then echo "error: ${gfsdhost} does not listen port." c=`expr 1 + $c` fi done<<EOF `parse_gfsd_confs "$1"` EOF if [ $? != 0 ]; then echo "error: something wrong with arguments \'$1\'." 1>&2 fi if [ $c = 0 ]; then echo "ok" fi exit 0 <file_sep>/gfarm/tags/gfarm_1_0_3/gfptool/gfwc/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk CC = $(MPICC) SRCS = gfwc.c OBJS = gfwc.o PROGRAM = gfwc CFLAGS = $(COMMON_CFLAGS) LDLIBS = $(COMMON_LDFLAGS) $(GFARMLIB) $(LIBS) DEPLIBS = $(DEPGFARMLIB) all: $(PROGRAM) include $(top_srcdir)/makes/gfptool.mk ### $(OBJS): $(DEPGFARMINC) <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT2-2-2-2_master_gfmd_down_with_no_synced_slave #! /bin/sh ###################################################################### TESTID="FT2-2-2-2" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd down with no synced slave" ###################################################################### . ./FT-common ft_setup() { JOURNAL_SIZE=50000 N_TRANSACTIONS=`expr $JOURNAL_SIZE / 200` ft_reset_gfmd || return $FT_RESULT_FAIL ./FT-set-journal-size $JOURNAL_SIZE || return $FT_RESULT_FAIL return $FT_RESULT_PASS } ft_main() { R1=$FT_RESULT_PASS gfmdhost -l > /dev/null 2>&1 || R1=$FT_RESULT_FAIL ft_checkpoint 1 "gfmdhost -l" $R1 [ $R1 -eq $FT_RESULT_PASS ] || return $R1 R2=$FT_RESULT_PASS $gfservice stop-gfmd gfmd2 || R2=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd2" $R2 [ $R2 -eq $FT_RESULT_PASS ] || return $R2 I=0 TESTDIR="/$TESTID.$$" while [ $I -lt $N_TRANSACTIONS ]; do gfmkdir $TESTDIR gfrmdir $TESTDIR I=`expr $I + 1` done R3=$FT_RESULT_PASS ft_checkpoint 3 "lap a journal file." $R3 [ $R3 -eq $FT_RESULT_PASS ] || return $R3 R4=$FT_RESULT_PASS $gfservice -t 30 start-gfmd gfmd2 && R4=$FT_RESULT_XPASS ft_checkpoint 4 "start gfmd on gfmd2" $R4 [ $R4 -eq $FT_RESULT_PASS -o $R4 -eq $FT_RESULT_XPASS ] || return $R4 R5=$FT_RESULT_PASS CONN_STATUS=`gfmdhost -l | awk "{if (\\$6 == \"$gfmd2\") print \\$1}"` [ "X$CONN_STATUS" = "Xx" ] || R5=$FT_RESULT_XPASS ft_checkpoint 5 "gfmdhost -l" $R5 [ $R5 -eq $FT_RESULT_PASS -o $R5 -eq $FT_RESULT_XPASS ] || return $R5 R6=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 || R6=$FT_RESULT_FAIL ft_checkpoint 6 "stop gfmd on $gfmd1" $R6 [ $R6 -eq $FT_RESULT_PASS ] || return $R6 R7=$FT_RESULT_PASS ft_check_mail "gfmd does not listen on $gfmd1" \ || R7=$FT_RESULT_FAIL ft_checkpoint 7 "receive a mail" $R7 [ $R7 -eq $FT_RESULT_PASS ] || return $R7 R8=$FT_RESULT_PASS ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || R8=$FT_RESULT_FAIL ft_checkpoint 8 "receive a mail" $R8 [ $R8 -eq $FT_RESULT_PASS ] || return $R8 return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_1/open_file.c /* * $Id$ */ #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <gfarm/gfarm.h> #include "gfarm2fs_msg_enums.h" #include "gfarm2fs.h" #include "hash.h" struct opening { struct opening *next; struct gfarm2fs_file *fp; int writing; }; struct inode_openings { struct opening *openings; struct gfarm2fs_file *fp_cached; }; static struct gfarm_hash_table *open_file_table; #define OPEN_FILE_TABLE_SIZE 256 static int open_file_hash(const void *k, int l) { gfarm_ino_t h = *(gfarm_ino_t *)k; int i = (int)h; return (i); } static int open_file_hash_equal( const void *k1, int k1len, const void *k2, int k2len) { gfarm_ino_t h1 = *(gfarm_ino_t *)k1, h2 = *(gfarm_ino_t *)k2; return (h1 == h2); } void gfarm2fs_open_file_init() { open_file_table = gfarm_hash_table_alloc( OPEN_FILE_TABLE_SIZE, open_file_hash, open_file_hash_equal); if (open_file_table == NULL) gflog_fatal(GFARM_MSG_2000051, "no memory"); } struct gfarm2fs_file * gfarm2fs_open_file_lookup(gfarm_ino_t ino) { struct gfarm_hash_entry *entry; struct inode_openings *ios; struct opening *o; entry = gfarm_hash_lookup(open_file_table, &ino, sizeof(ino)); if (entry == NULL) return (NULL); ios = gfarm_hash_entry_data(entry); if (ios->fp_cached != NULL) return (ios->fp_cached); for (o = ios->openings; o != NULL; o = o->next) { if (o->writing) { ios->fp_cached = o->fp; return (ios->fp_cached); } } ios->fp_cached = ios->openings->fp; return (ios->fp_cached); } void gfarm2fs_open_file_enter(struct gfarm2fs_file *fp, int flags) { gfarm_ino_t ino = fp->inum; struct gfarm_hash_entry *entry; struct inode_openings *ios; struct opening *o; int created; o = malloc(sizeof(*o)); if (o == NULL) { gflog_error(GFARM_MSG_2000053, "no memory to cache an opening for inode %lld", (unsigned long long)ino); return; } entry = gfarm_hash_enter(open_file_table, &ino, sizeof(ino), sizeof(*ios), &created); if (entry == NULL) { gflog_error(GFARM_MSG_2000054, "no memory to insert inode %lld to open file table", (unsigned long long)ino); return; } o->fp = fp; o->writing = ((flags & O_TRUNC) != 0 || (flags & O_ACCMODE) != O_RDONLY); ios = gfarm_hash_entry_data(entry); if (!created) { o->next = ios->openings; } else { o->next = NULL; ios->fp_cached = NULL; } ios->openings = o; if (o->writing) ios->fp_cached = fp; } static int open_file_remove_opening(struct inode_openings *ios, struct gfarm2fs_file *fp) { struct opening *o, **prev; for (prev = &ios->openings; (o = *prev) != NULL; prev = &o->next) { if (o->fp == fp) break; } if (o == NULL) return (1); *prev = o->next; free(o); return (0); } void gfarm2fs_open_file_remove(struct gfarm2fs_file *fp) { gfarm_ino_t ino = fp->inum; struct gfarm_hash_entry *entry; struct inode_openings *ios = NULL; entry = gfarm_hash_lookup(open_file_table, &ino, sizeof(ino)); if (entry == NULL) { gflog_warning(GFARM_MSG_2000056, "inode %lld is not found in open file table", (unsigned long long)ino); return; } ios = gfarm_hash_entry_data(entry); if (open_file_remove_opening(ios, fp) != 0) gflog_warning(GFARM_MSG_2000057, "file %p is not found in the inode %lld openings", fp, (unsigned long long)ino); if (ios->fp_cached == fp) ios->fp_cached = NULL; if (ios->openings == NULL) (void)gfarm_hash_purge(open_file_table, &ino, sizeof(ino)); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc4/lib/libgfarm/gfsl/server.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #include "gssapi.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_auth.h" #include "gfarm_secure_session.h" #include "tcputil.h" #include "misc.h" static int port = 0; static int ParseArgs(argc, argv) int argc; char *argv[]; { while (*argv != NULL) { if (strcmp(*argv, "-p") == 0) { if (argv[1] != NULL && *argv[1] != '\0') { int tmp; argv++; if (gfarmGetInt(*argv, &tmp) < 0) { fprintf(stderr, "illegal port number.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "port number must be > 0.\n"); return -1; } else if (tmp > 65535) { fprintf(stderr, "port number must be < 65536.\n"); return -1; } port = tmp; } else { fprintf(stderr, "a port number must be specified.\n"); return -1; } } argv++; } return 0; } extern void doServer(int fd, char *host, int port); extern void doClient(char *host, int port, gss_cred_id_t sCtx, int deleCheck); int main(argc, argv) int argc; char *argv[]; { int bindFd = -1; struct sockaddr_in remote; int remLen = sizeof(struct sockaddr_in); int fd = -1; OM_uint32 majStat, minStat; unsigned long int rAddr, myAddr; char *rHost; char myHostname[4096]; if (ParseArgs(argc - 1, argv + 1) != 0) { return 1; } if (gethostname(myHostname, 4096) < 0) { return 1; } myAddr = gfarmIPGetAddressOfHost(myHostname); if (gfarmSecSessionInitializeBoth(NULL, NULL, NULL, &majStat, &minStat) <= 0) { fprintf(stderr, "can't initialize as both role because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); gfarmSecSessionFinalizeBoth(); return 1; } /* * Create a channel. */ bindFd = gfarmTCPBindPort(port); if (bindFd < 0) { gfarmSecSessionFinalizeBoth(); return 1; } (void)gfarmIPGetNameOfSocket(bindFd, &port); fprintf(stderr, "Accepting port: %d\n", port); /* * Accept-fork loop. */ while (1) { pid_t pid; fd = accept(bindFd, (struct sockaddr *)&remote, &remLen); if (fd < 0) { perror("accept"); (void)close(bindFd); return 1; } rAddr = ntohl(remote.sin_addr.s_addr); rHost = gfarmIPGetHostOfAddress(rAddr); fprintf(stderr, "Connected from %s\n", rHost); (void)free(rHost); pid = fork(); if (pid < 0) { (void)close(fd); (void)close(bindFd); perror("fork"); return 1; } else if (pid == 0) { (void)close(bindFd); doServer(fd, myHostname, port); (void)close(fd); exit(0); } else { (void)close(fd); } } #if 0 /* never reach here */ gfarmSecSessionFinalizeBoth(); return 0; #endif } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/failure_test_scripts/FT1-2-2-2_slave_network_down #! /bin/sh ###################################################################### TESTID="FT1-2-2-2" CATEGORY="accident causes no failover" SECTION="mds accident" TITLE="network down with slave to master" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfmd2_CTRL_ADDRESS sudo $IFDOWN_PATH $gfmd2_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfmd2_GFARM_IF on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Can't get master metadata server name on $gfmd2" && \ ft_check_mail \ "Gfarm metadata server is not available on $gfmd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ssh $gfmd2_CTRL_ADDRESS sudo $IFUP_PATH $gfmd2_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "ifup $gfmd2_GFARM_IF on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Re: Can't get master metadata server name on $gfmd2" && \ ft_check_mail \ "Re: Gfarm metadata server is not available on $gfmd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { ssh $gfmd2_CTRL_ADDRESS sudo $IFUP_PATH $gfmd2_GFARM_IF return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/schedule.h /* * */ char *gfarm_schedule_search_idle_hosts(int, char **, int, char **); char *gfarm_schedule_search_idle_by_all(int, char **); char *gfarm_host_domain_hosts_schedule(); char *gfarm_hosts_schedule_expand_cyclic(); <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc1/gfptool/util/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk SCRIPTS= gfregister all: install: @for i in / $(SCRIPTS); do \ case $$i in /) continue;; esac; \ ( set -x; $(INSTALL_PROGRAM) $${i} $(bindir)/$${i} ); \ done clean: veryclean: clean distclean: veryclean -rm -f $(SCRIPTS) gfregister: man: html: <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfmdtype_gfmd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # Chekc Config File if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1 exit 0 fi prefix=$1 if [ -z "$prefix" ]; then prefix="/" fi read prefix myhost port<<EOF `read_gfmd_confs "$1"` EOF if [ $? -ne 0 ]; then myhost=`hostname` fi if [ -f $MDS_LIST_PATH ]; then CHK=`grep '^+ master' $MDS_LIST_PATH | awk '{ print $6 }' | grep $myhost` if [ X$CHK != X ]; then RESULT="master" else RESULT="slave" fi else RESULT="error: $MDS_LIST_PATH not found." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/gftool/gfrep/gfrep.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <limits.h> #include <gfarm/gfarm.h> #include "gfs_client.h" #define LINELEN 2048 char *program_name = "gfrep"; /* Do not use gfrepbe_client/gfrepbe_server, but use gfsd internal routine */ #if 0 /* XXX for now */ int bootstrap_method = 0; #else int bootstrap_method = 1; #endif int verbose = 0; struct replication_job { struct replication_job *next; char *file; char *section; char *src; char *dest; }; struct replication_job_list { struct replication_job *head; struct replication_job **tail; int n; }; struct replication_pair { struct replication_pair *next; gfarm_stringlist files, sections; struct gfs_client_rep_backend_state *state; char *src, *dest; }; struct replication_pair_list { struct replication_pair *head; struct replication_pair **tail; int max_fragments_per_pair; }; static void replication_job_list_init(struct replication_job_list *list) { list->head = NULL; list->tail = &list->head; list->n = 0; } static int replication_job_list_add(struct replication_job_list *list, char *file, char *section, char *src, char *dest) { char *e, *gfarm_file, *dest_canonical; struct replication_job *job; if (bootstrap_method) { if (src != NULL) { e = gfarm_url_section_replicate_from_to( file, section, src, dest); if (e != NULL) fprintf(stderr, "%s: replicate %s:%s from %s to %s: %s\n", program_name, file, section, src, dest, e); } else { e = gfarm_url_section_replicate_to( file, section, dest); if (e != NULL) fprintf(stderr, "%s: replicate %s:%s to %s: %s\n", program_name, file, section, dest, e); } return (e != NULL ? 1 : 0); } e = gfarm_url_make_path(file, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: parsing pathname %s: %s\n", program_name, file, e); return (1); } e = gfarm_host_get_canonical_name(dest, &dest_canonical); if (e != NULL) { fprintf(stderr, "%s: host %s isn't a filesystem node: %s\n", program_name, dest, e); free(gfarm_file); return (1); } if (gfarm_file_section_copy_info_does_exist(gfarm_file, section, dest_canonical)) { /* already exists, don't have to replicate */ free(dest_canonical); free(gfarm_file); return (0); } job = malloc(sizeof(*job)); if (job == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } job->file = gfarm_file; job->section = strdup(section); if (job->section == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } job->dest = dest_canonical; if (src != NULL) { e = gfarm_host_get_canonical_name(src, &job->src); if (e != NULL) { fprintf(stderr, "%s: checking source host %s for %s:%s: %s", program_name, src, file, section, e); free(job); free(dest_canonical); free(gfarm_file); return (1); } } else { e = gfarm_file_section_host_schedule(job->file, section, &job->src); if (e != NULL) { fprintf(stderr, "%s: searching source host for %s:%s: %s", program_name, file, section, e); free(job); free(dest_canonical); free(gfarm_file); return (1); } } job->next = NULL; *list->tail = job; list->tail = &job->next; list->n++; return (0); } static void replication_pair_init(struct replication_pair_list *transfers) { transfers->head = NULL; transfers->tail = &transfers->head; transfers->max_fragments_per_pair = 0; } static int replication_pair_entry(struct replication_pair_list *transfers, struct replication_job **list, int n) { char *e; int i; struct replication_pair *pair = malloc(sizeof(*pair)); if (pair == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(&pair->files); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(&pair->sections); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < n; i++) { e = gfarm_stringlist_add(&pair->files, list[i]->file); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(&pair->sections, list[i]->section); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } } pair->src = list[0]->src; pair->dest = list[0]->dest; if (verbose) fprintf(stderr, "%s: scheduling %s -> %s\n", program_name, pair->src, pair->dest); e = gfarm_file_section_replicate_multiple_request( &pair->files, &pair->sections, pair->src, pair->dest, &pair->state); if (e != NULL) { fprintf(stderr, "%s: replication from %s to %s: %s\n", program_name, pair->src, pair->dest, e); gfarm_stringlist_free(&pair->files); gfarm_stringlist_free(&pair->sections); free(pair); return (1); } pair->next = NULL; *transfers->tail = pair; transfers->tail = &pair->next; if (transfers->max_fragments_per_pair < n) transfers->max_fragments_per_pair = n; return (0); } static int replication_pair_results(struct replication_pair_list *transfers) { char *e, **results = malloc(sizeof(*results) * transfers->max_fragments_per_pair); struct replication_pair *pair; int i, n, error_happend = 0; if (results == NULL) { fprintf(stderr, "%s: cannot allocate memory for %d results\n", program_name, transfers->max_fragments_per_pair); exit(EXIT_FAILURE); } for (pair = transfers->head; pair != NULL; pair = pair->next) { e = gfarm_file_section_replicate_multiple_result(pair->state, results); if (e != NULL) { fprintf(stderr, "%s: replication from %s to %s: %s\n", program_name, pair->src, pair->dest, e); error_happend = 1; continue; } n = gfarm_stringlist_length(&pair->files); for (i = 0; i < n; i++) { if (results[i] == NULL) continue; fprintf(stderr, "%s: replicate %s:%s from %s to %s: %s\n", program_name, gfarm_stringlist_elem(&pair->files, i), gfarm_stringlist_elem(&pair->sections, i), pair->src, pair->dest, e); error_happend = 1; } } return (error_happend); } /* sort by (src, dest) */ static int job_compare(const void *a, const void *b) { struct replication_job *const * jpa = a, *const * jpb = b; struct replication_job *ja = *jpa, *jb = *jpb; int cmp; if ((cmp = strcasecmp(ja->src, jb->src)) < 0) return (-1); else if (cmp > 0) return (1); else if ((cmp = strcasecmp(ja->dest, jb->dest)) < 0) return (-1); else if (cmp > 0) return (1); else if ((cmp = strcmp(ja->file, jb->file)) < 0) return (-1); else if (cmp > 0) return (1); else return (strcmp(ja->section, jb->section)); } static int replication_job_list_execute(struct replication_job_list *list) { int i, top; struct replication_job *job, **jobs; int error_happend = 0; struct replication_pair_list transfers; if (bootstrap_method) { /* All jobs are already completed here with bootstrap mode */ return (0); } if (list->n == 0) /* do nothing */ return (0); jobs = malloc(sizeof(*jobs) * list->n); if (jobs == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(EXIT_FAILURE); } for (job = list->head, i = 0; job != NULL; job = job->next, i++) { if (i >= list->n) { /* sanity */ fprintf(stderr, "%s: panic: more than %d jobs\n", program_name, list->n); exit(EXIT_FAILURE); } jobs[i] = job; } qsort(jobs, list->n, sizeof(*jobs), job_compare); replication_pair_init(&transfers); top = 0; for (i = 1; i < list->n; i++) { if (strcasecmp(jobs[top]->src, jobs[i]->src) != 0 || strcasecmp(jobs[top]->dest, jobs[i]->dest) != 0) { if (replication_pair_entry(&transfers, &jobs[top], i - top)) error_happend = 1; top = i; } } if (replication_pair_entry(&transfers, &jobs[top], list->n - top)) error_happend = 1; if (replication_pair_results(&transfers)) error_happend = 1; return (error_happend); } static int replicate_by_fragment_dest_list(char *fragment_dest_list, char *src_default) { int error_happend = 0; struct replication_job_list job_list; int n, lineno; char line[LINELEN]; char file[LINELEN], section[LINELEN], dest[LINELEN], src[LINELEN]; FILE *fp; fp = fopen(fragment_dest_list, "r"); if (fp == NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, fragment_dest_list, strerror(errno)); exit(EXIT_FAILURE); } replication_job_list_init(&job_list); for (lineno = 1; fgets(line, sizeof line, fp) != NULL; lineno++) { n = sscanf(line, "%s %s %s %s", file, section, dest, src); if (n == 0) continue; if (n < 3) { fprintf(stderr, "%s: %s line %d: " "gfarm-URL, fragment-name and dest-node " "are required, skip this line\n", program_name, fragment_dest_list, lineno); continue; } else if (n > 4) { fprintf(stderr, "%s: %s line %d: " "there are more than 4 fields, ignore extras\n", program_name, fragment_dest_list, lineno); } if (replication_job_list_add(&job_list, file, section, n > 3 ? src : src_default, dest)) error_happend = 1; } fclose(fp); return (error_happend | replication_job_list_execute(&job_list)); } static void pairlist_read(char *pair_list, int *npairsp, gfarm_stringlist *src_nodes, gfarm_stringlist *dst_nodes) { char *e, *s; int npairs, lineno, n; FILE *fp; char line[LINELEN], src[LINELEN], dst[LINELEN]; e = gfarm_stringlist_init(src_nodes); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_init(dst_nodes); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } if ((fp = fopen(pair_list, "r")) == NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, pair_list, strerror(errno)); exit(EXIT_FAILURE); } npairs = 0; for (lineno = 1; fgets(line, sizeof line, fp) != NULL; lineno++) { /* remove comment */ s = strchr(line, '#'); if (s != NULL) *s = '\0'; n = sscanf(line, "%s %s\n", src, dst); if (n == 0) continue; if (n != 2) { fprintf(stderr, "%s: %s line %d: field number is not 2\n", program_name, pair_list, lineno); exit(EXIT_FAILURE); } e = gfarm_host_get_canonical_name(src, &s); if (e != NULL) { fprintf(stderr, "%s: %s isn't a filesystem node: %s\n", program_name, src, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(src_nodes, s); if (e != NULL) { fprintf(stderr, "%s: string %s: %s\n", program_name, src, e); exit(EXIT_FAILURE); } e = gfarm_host_get_canonical_name(dst, &s); if (e != NULL) { fprintf(stderr, "%s: %s isn't a filesystem node: %s\n", program_name, dst, e); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(dst_nodes, s); if (e != NULL) { fprintf(stderr, "%s: string %s: %s\n", program_name, dst, e); exit(EXIT_FAILURE); } npairs++; } fclose(fp); *npairsp = npairs; } static char * get_default_section(char *file, char *dest) { char *e; struct gfs_stat gst; e = gfs_stat(file, &gst); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, file, e); return (NULL); } if (GFARM_S_IS_PROGRAM(gst.st_mode)) { /* architecture of dest host (cache) */ static char *architecture = NULL; gfs_stat_free(&gst); if (architecture == NULL) { char *dest_canonical; e = gfarm_host_get_canonical_name(dest, &dest_canonical); if (e != NULL) { fprintf(stderr, "%s: host %s: %s\n", program_name, dest, e); exit(EXIT_FAILURE); } architecture = gfarm_host_info_get_architecture_by_host( dest_canonical); free(dest_canonical); if (architecture == NULL) { fprintf(stderr, "%s: host %s: %s\n", program_name, dest, "cannot get architecture"); exit(EXIT_FAILURE); } } return (architecture); /* assume -a <architecture of dest> */ } else { int nfrags = gst.st_nsections; gfs_stat_free(&gst); /* * Special case for replicating a Gfarm * file having only one fragment */ if (nfrags != 1) { fprintf(stderr, "%s: %s has more than one fragments, skipped\n", program_name, file); return (NULL); } return ("0"); /* assume -I 0 */ } } static char * add_cwd_to_relative_path(char *cwd, const char *path) { char *p; path = gfarm_url_prefix_skip(path); if (*path == '/') { p = strdup(path); if (p == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } } else { p = malloc(strlen(cwd) + strlen(path) + 2); if (p == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } sprintf(p, "%s/%s", cwd, path); } return (p); } static int traverse_file_tree_with_cwd(char *cwd, char *path, int (*file_processor)(char *, char *, void *), void *closure) { char *e; struct gfs_stat gs; GFS_Dir dir; struct gfs_dirent *entry; gfarm_mode_t mode; int error_happend = 0; e = gfs_stat(path, &gs); if (e != NULL) { fprintf(stderr, "%s: gfs_stat: %s in gfarm:%s: %s\n", program_name, path, cwd, e); return (1); } mode = gs.st_mode; gfs_stat_free(&gs); if (GFARM_S_ISREG(mode)) { return ((*file_processor)(cwd, path, closure)); } else if (GFARM_S_ISDIR(mode)) { char *ncwd; e = gfs_chdir(path); if (e != NULL) { fprintf(stderr, "%s: gfs_chdir: %s: %s\n", program_name, path, e); return (1); } e = gfs_opendir(".", &dir); if (e != NULL) { fprintf(stderr, "%s: gfs_opendir: %s: %s\n", program_name, path, e); return (1); } ncwd = add_cwd_to_relative_path(cwd, path); while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { char *url; if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } url = gfarm_url_prefix_add(entry->d_name); if (url == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } if (traverse_file_tree_with_cwd(ncwd, url, file_processor, closure)) { error_happend = 1; } free(url); } free(ncwd); if (e != NULL) { fprintf(stderr, "%s: gfs_readdir: %s: %s\n", program_name, path, e); return (1); } gfs_closedir(dir); e = gfs_chdir(".."); if (e != NULL) { fprintf(stderr, "%s: gfs_chdir: %s/..: %s\n", program_name, path, e); exit(EXIT_FAILURE); } } return (error_happend); } static int traverse_file_tree(char *path, int (*file_processor)(char *, char *, void *), void *closure) { char *e; char cwdbf[PATH_MAX * 2]; e = gfs_getcwd(cwdbf, sizeof(cwdbf)); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); return (1); } return (traverse_file_tree_with_cwd(cwdbf, path, file_processor, closure)); } struct replicate_to_hosts_closure { char *url; int nhosts; char **hosttab; }; static int replicate_to_hosts_callback(char *cwd, char *url, void *closure) { struct replicate_to_hosts_closure *c = closure; char *e; int error_happened = 0; e = gfarm_url_fragments_replicate(url, c->nhosts, c->hosttab); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, url, e); error_happened = 1; } return (error_happened); } static int replicate_files_to_hosts(char *url, int nhosts, char **hosttab) { struct replicate_to_hosts_closure c; c.nhosts = nhosts; c.hosttab = hosttab; return traverse_file_tree(url, replicate_to_hosts_callback, &c); } static int collect_file_paths_callback(char *cwd, char *url, void *closure) { gfarm_stringlist *path_list = closure; char *e, *p; p = add_cwd_to_relative_path(cwd, url); url = gfarm_url_prefix_add(p); free(p); if (url == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } e = gfarm_stringlist_add(path_list, url); if (e != NULL) { fprintf(stderr, "%s: collect_file_path_callback: %s\n", program_name, e); exit(EXIT_FAILURE); } return (0); } static char * get_hosts_have_replica_in_domain( char *url, char *section, char *domainname, int *nrhosts, char ***rhosts) { char *e, *gfarm_file, **hosts; int i, ncinfos, nhosts; struct gfarm_file_section_copy_info *cinfos; e = gfarm_url_make_path(url, &gfarm_file); if (e != NULL) return(e); e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncinfos, &cinfos); free(gfarm_file); if (e != NULL) return(e); hosts = malloc(sizeof(*hosts) * ncinfos); if (hosts == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } nhosts = 0; for (i = 0; i < ncinfos; i++) if (gfarm_host_is_in_domain(cinfos[i].hostname, domainname)) { char *p = strdup(cinfos[i].hostname); if (p == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } hosts[nhosts] = p; nhosts++; } gfarm_file_section_copy_info_free_all(ncinfos, cinfos); *nrhosts = nhosts; *rhosts = hosts; return(NULL); } #define min(a,b) (((a)<(b))?(a):(b)) static int search_not_have_replica_host(int pos, int ndhosts, char **dhosts, int *nrhosts, char ***rhosts) { int i, j, exist_in_rhosts; for (i = 0; i < ndhosts; i++) { exist_in_rhosts = 0; for (j = 0; j < *nrhosts; j++) { if (strcasecmp(dhosts[pos], (*rhosts)[j]) == 0) { exist_in_rhosts = 1; break; } } if (exist_in_rhosts == 0) { /* found a host */ char **p; (*nrhosts)++; p = realloc(*rhosts, sizeof(**rhosts) * (*nrhosts)); if (p == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } p[*nrhosts - 1] = strdup(dhosts[pos]); if (p[*nrhosts - 1] == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } *rhosts = p; return (pos); } pos = (pos + 1) % ndhosts; } return (-1); } static int replicate_files_to_domain(char *path, int min_replicas, char *domainname) { char *e; int i, j, k, k2, m; gfarm_stringlist path_list; int *nfragments, nhosts; char **hosts = NULL; struct gfarm_file_section_info **sinfos; int error_happend = 0; e = gfarm_stringlist_init(&path_list); if (e != NULL) { fprintf(stderr, "%s %s: %s\n", program_name, path, e); exit(EXIT_FAILURE); } if (traverse_file_tree(path, collect_file_paths_callback, &path_list)) error_happend = 1; nfragments = malloc(sizeof(*nfragments) * gfarm_stringlist_length(&path_list)); if (nfragments == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } sinfos = malloc(sizeof(*sinfos) * gfarm_stringlist_length(&path_list)); if (sinfos == NULL) { fprintf(stderr, "%s: %s\n", path, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } nhosts = 0; for (i = 0; i < gfarm_stringlist_length(&path_list); i++) { char *e, *url, *gfarm_file; url = gfarm_stringlist_elem(&path_list, i); e = gfarm_url_make_path(url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, url, e); continue; } e = gfarm_file_section_info_get_all_by_file( gfarm_file, &nfragments[i], &sinfos[i]); free(gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, url, e); nfragments[i] = 0; sinfos[i] = NULL; continue; } nhosts += nfragments[i]; } nhosts *= min_replicas; hosts = malloc(sizeof(*hosts) * nhosts); if (hosts == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } e = gfarm_schedule_search_idle_acyclic_by_domainname( domainname, &nhosts, hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } if (nhosts < min_replicas) fprintf(stderr, "%s: warning: #host in domain(%d) < " "#replica required(%d)\n", program_name, nhosts, min_replicas); k = 0; for (i = 0; i < gfarm_stringlist_length(&path_list); i++) { char *file_path, **rhosts; int nrhosts; file_path = gfarm_stringlist_elem(&path_list, i); for (j = 0; j < nfragments[i]; j++) { e = get_hosts_have_replica_in_domain( file_path, sinfos[i][j].section, domainname, &nrhosts, &rhosts); if (e != NULL) { fprintf(stderr, "%s: get_hosts_replica_in_domain:" " %s: %s: %s\n", program_name, file_path, sinfos[i][j].section, e); continue; } m = min(min_replicas, nhosts) - nrhosts; if (m <= 0) { gfarm_strings_free_deeply(nrhosts, rhosts); continue; } while (m--) { k2 = search_not_have_replica_host( k, nhosts, hosts, &nrhosts, &rhosts); if (k2 == -1) /* not found */ break; k = k2; e = gfarm_url_section_replicate_to( file_path, sinfos[i][j].section, hosts[k]); if (e != NULL) { fprintf(stderr, "%s: gfarm_url_section_" "replicate_to %s: %s: %s\n", program_name, file_path, sinfos[i][j].section, e); continue; } k = (k + 1) % nhosts; } gfarm_strings_free_deeply(nrhosts, rhosts); } } gfarm_strings_free_deeply(nhosts, hosts); for (i = 0; i < gfarm_stringlist_length(&path_list); i++) if (sinfos[i] != NULL) gfarm_file_section_info_free_all(nfragments[i], sinfos[i]); free(sinfos); free(nfragments); gfarm_stringlist_free_deeply(&path_list); return (error_happend); } struct jobs_by_pairs_closure { struct replication_job_list *job_list; int npairs; gfarm_stringlist *src_nodes; gfarm_stringlist *dst_nodes; }; static int jobs_by_pairs_callback(char *cwd, char *gfarm_url, void *closure) { struct jobs_by_pairs_closure *c = closure; int i, j, k, error_happend = 0; char *e, *gfarm_file, *src_host, *dst_host, *p; int nfragments, ncopies; struct gfarm_file_section_copy_info *copies; char section[GFARM_INT32STRLEN]; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: cannot determine pathname for %s: %s\n", program_name, gfarm_url, e); error_happend = 1; goto free_gfarm_file; } e = gfarm_url_fragment_number(gfarm_url, &nfragments); if (e != NULL) { fprintf(stderr, "%s: %s: cannot get fragment number: %s\n", program_name, gfarm_url, e); error_happend = 1; goto free_gfarm_file; } p = add_cwd_to_relative_path(cwd, gfarm_url); gfarm_url = gfarm_url_prefix_add(p); free(p); for (i = 0; i < nfragments; i++) { sprintf(section, "%d", i); e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) { fprintf(stderr, "%s: %s:%s: cannot get replica location: %s\n", program_name, gfarm_url, section, e); continue; } for (j = 0; j < c->npairs; j++) { src_host = gfarm_stringlist_elem(c->src_nodes, j); dst_host = gfarm_stringlist_elem(c->dst_nodes, j); for (k = 0; k < ncopies; k++) { if(strcasecmp(copies[k].hostname,src_host)==0){ if (replication_job_list_add( c->job_list, gfarm_url, section, src_host, dst_host)) error_happend = 1; goto found; } } } fprintf(stderr, "%s: error: %s:%s - no replica is found\n", program_name, gfarm_url, section); found: gfarm_file_section_copy_info_free_all(ncopies, copies); } free_gfarm_file: free(gfarm_file); return (error_happend); } static int jobs_by_pairs(struct replication_job_list *job_list, char *gfarm_url, int npairs, gfarm_stringlist *src_nodes, gfarm_stringlist *dst_nodes) { struct jobs_by_pairs_closure c; c.job_list = job_list; c.npairs = npairs; c.src_nodes = src_nodes; c.dst_nodes = dst_nodes; return traverse_file_tree(gfarm_url, jobs_by_pairs_callback, &c); } struct replicate_to_dest_closure { struct replication_job_list *list; char *index; char *src; char *dest; }; static int replicate_to_dest_callback(char *cwd, char *url, void *closure) { struct replicate_to_dest_closure *c = closure; char *section = c->index; char *p; if (c->index == NULL) { /* special case */ section = get_default_section(url, c->dest); if (section == NULL) { return (1); } } p = add_cwd_to_relative_path(cwd, url); url = gfarm_url_prefix_add(p); free(p); if (url == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } return (replication_job_list_add(c->list, url, section, c-> src, c->dest)); } static int replicate_to_dest(struct replication_job_list *list, char *url, char *index, char *src, char *dest) { struct replicate_to_dest_closure c; c.list = list; c.index = index; c.src = src; c.dest = dest; return traverse_file_tree(url, replicate_to_dest_callback, &c); } static void usage() { fprintf(stderr, "Usage: %s [option] <gfarm_url>...\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-b\t\t\tuse bootstrap mode\n"); fprintf(stderr, "\t-v\t\t\tverbose message\n"); fprintf(stderr, "\t-H <hostfile>\t\treplicate a whole file\n"); fprintf(stderr, "\t-D <domainname>\t\treplicate a whole file\n"); fprintf(stderr, "\t-I fragment-index\treplicate a fragment" " with -d option\n"); fprintf(stderr, "\t-s src-node\n"); fprintf(stderr, "\t-d dest-node\n"); fprintf(stderr, "\t-l <fragment-dest-list-file>\n"); fprintf(stderr, "\t-P <host-pair-file>\n"); fprintf(stderr, "\t-N <number-of-replicas-per-fragment>\n"); exit(EXIT_FAILURE); } static void conflict_check(int *mode_ch_p, int ch) { if (*mode_ch_p) { fprintf(stderr, "%s: -%c option conflicts with -%c\n", program_name, ch, *mode_ch_p); usage(); } *mode_ch_p = ch; } int main(argc, argv) int argc; char **argv; { char *e, *file; int i, ch, mode_ch = 0; gfarm_stringlist paths; gfs_glob_t types; int error_happened = 0, min_replicas = 1; char *hostfile = NULL, *domainname = NULL, *index = NULL; char *src = NULL, *dest = NULL, *fragment_dest_list = NULL; char *pair_list = NULL; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "bXvH:D:I:s:d:l:P:N:?")) != -1) { switch (ch) { case 'b': bootstrap_method = 1; break; case 'X': /* use eXternal command (gfrepbe_*) */ bootstrap_method = 0; break; case 'v': verbose = 1; break; case 'H': hostfile = optarg; conflict_check(&mode_ch, ch); break; case 'D': domainname = optarg; conflict_check(&mode_ch, ch); break; case 'I': index = optarg; break; case 's': src = optarg; break; case 'd': dest = optarg; conflict_check(&mode_ch, ch); break; case 'l': fragment_dest_list = optarg; conflict_check(&mode_ch, ch); break; case 'P': pair_list = optarg; conflict_check(&mode_ch, ch); break; case 'N': min_replicas = strtol(optarg, NULL, 0); break; case '?': default: usage(); } } argc -= optind; argv += optind; if (bootstrap_method) gfarm_replication_set_method( GFARM_REPLICATION_BOOTSTRAP_METHOD); if (src != NULL && dest == NULL && fragment_dest_list == NULL) { fprintf(stderr, "%s: -s <src> option only works with -d or -l option\n", program_name); exit(EXIT_FAILURE); } if (index != NULL && dest == NULL) { fprintf(stderr, "%s: -I <index> option only works with -d option\n", program_name); exit(EXIT_FAILURE); } if (min_replicas > 1 && mode_ch != 0 && mode_ch != 'D') { fprintf(stderr, "%s: error: -N num-replica option is unavailable " "with -%c option\n", program_name, mode_ch); exit(EXIT_FAILURE); } if (argc == 0 && fragment_dest_list == NULL) usage(); if (min_replicas == 1 && mode_ch == 0) { fprintf(stderr, "%s: warning: -N 1 (default) is meaningless " "without another option\n", program_name); exit(EXIT_SUCCESS); } e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); if (hostfile != NULL) { char **hosttab; int nhosts, error_line; /* replicate directories and whole files */ e = gfarm_hostlist_read(hostfile, &nhosts, &hosttab, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: line %d: %s\n", hostfile, error_line, e); else fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); error_happened = replicate_files_to_hosts( file, nhosts, hosttab); } } else if (fragment_dest_list != NULL) { /* replicate specified fragments */ if (bootstrap_method) { fprintf(stderr, "%s: -l option isn't supported " "on bootstrap mode\n", program_name); /* It's easy to support this, but probably too slow */ usage(); exit(EXIT_FAILURE); } error_happened = replicate_by_fragment_dest_list(fragment_dest_list, src); } else if (pair_list != NULL) { int npairs; gfarm_stringlist src_nodes, dst_nodes; struct replication_job_list job_list; pairlist_read(pair_list, &npairs, &src_nodes, &dst_nodes); replication_job_list_init(&job_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); if (verbose) fprintf(stderr, "%s: scan fragments for %s\n", program_name, file); if (jobs_by_pairs(&job_list, file, npairs, &src_nodes, &dst_nodes)) error_happened = 1; } if (replication_job_list_execute(&job_list)) error_happened = 1; } else if (dest != NULL) { /* -I may be omitted */ struct replication_job_list job_list; /* replicate specified fragments */ replication_job_list_init(&job_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); if (replicate_to_dest(&job_list, file, index, src, dest)) error_happened = 1; } if (replication_job_list_execute(&job_list)) error_happened = 1; } else { /* replicate directories and whole files */ if (domainname == NULL) domainname = ""; for (i = 0; i < gfarm_stringlist_length(&paths); i++) { file = gfarm_stringlist_elem(&paths, i); if (replicate_files_to_domain(file, min_replicas, domainname)) error_happened = 1; } } gfs_glob_free(&types); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } return (error_happened); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/gfs_client_rep.c #include <assert.h> #include <sys/time.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <time.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <gfarm/gfarm.h> #include "gfutil.h" #include "xxx_proto.h" #include "io_fd.h" #include "host.h" #include "param.h" #include "auth.h" #include "config.h" #include "gfs_proto.h" #include "gfs_client.h" #define GFRCMD_URL "gfarm:/bin/gfrcmd" static char *gfrcmd_path = "gfrcmd"; /* i.e. search this from $PATH */ static char *gfrep_backend_client_url = "gfarm:/libexec/gfrepbe_client"; /* ********************************************************************** * Really experimental rate limiter. * XXX This doesn't really work well. * XXX RTT is hardcoded. * XXX MTU is hardcoded. * XXX This doesn't work, if any packet is dropepd. * XXX slowstart estimation is too optimistic. * XXX use Web100 to see number of pending packets in SO_SNDBUF??? ********************************************************************** */ #define RATECTL_TICK 100 /* i.e. 1/100seconds */ #define RTT 25 /* XXX - hardcoded 250ms RTT */ #define USEC_RATECTL_TICK (GFARM_SECOND_BY_MICROSEC / RATECTL_TICK) #define DEFAULT_MTU 1500 struct gfs_client_rep_rate_info { long octets_per_tick; long flow_limit; long flow; struct timeval period; int tick; }; struct gfs_client_rep_rate_info * gfs_client_rep_rate_info_alloc(long rate) { struct gfs_client_rep_rate_info *rinfo = malloc(sizeof(*rinfo)); if (rinfo == NULL) return (NULL); rinfo->octets_per_tick = rate / 8 / RATECTL_TICK; rinfo->flow_limit = DEFAULT_MTU; rinfo->flow = 0; gettimeofday(&rinfo->period, NULL); gfarm_timeval_add_microsec(&rinfo->period, USEC_RATECTL_TICK); rinfo->tick++; return (rinfo); } void gfs_client_rep_rate_control(struct gfs_client_rep_rate_info *rinfo, long size) { rinfo->flow += size; /* XXX - it's inefficient to call usleep() multiple times. */ while (rinfo->flow >= rinfo->flow_limit) { struct timeval now, interval; gettimeofday(&now, NULL); if (gfarm_timeval_cmp(&now, &rinfo->period) < 0) { interval = rinfo->period; gfarm_timeval_sub(&interval, &now); usleep(interval.tv_sec * GFARM_SECOND_BY_MICROSEC + interval.tv_usec); #if 1 /* make this slow while slow starting */ rinfo->period = now; #endif } #if 0 /* * We do update rinfo->period by current time here, * because our intention is to limit network flow. */ rinfo->period = now; #endif gfarm_timeval_add_microsec(&rinfo->period, USEC_RATECTL_TICK); rinfo->flow -= rinfo->flow_limit; /* slow start */ if (rinfo->flow_limit < rinfo->octets_per_tick) { if (++rinfo->tick >= RTT) { rinfo->tick = 0; rinfo->flow_limit <<= 1; if (rinfo->flow_limit > rinfo->octets_per_tick) rinfo->flow_limit = rinfo->octets_per_tick; } } } } void gfs_client_rep_rate_info_free(struct gfs_client_rep_rate_info *rinfo) { free(rinfo); } /* ********************************************************************** * Implementation of new replication protocol which uses gfrepbe-client/server ********************************************************************** */ /* * common routines for gfrep and gfrepbe_client: * gfrep uses this to invoke gfrepbe_client. * gfrepbe_client uses this to invoke gfrepbe_server. * other programs/libraries shouldn't use this function. */ struct gfs_client_rep_backend_state { int pid; struct xxx_connection *in; struct xxx_connection *out; int n; }; char * gfs_client_rep_backend_invoke(char *canonical_hostname, char *gfrcmd, char *program, char *arg, int algorithm_version, int ndivisions, int interleave_factor, int file_sync_stripe, int send_stripe_sync, int recv_stripe_sync, char *message_prefix, struct xxx_connection **from_server_p, struct xxx_connection **to_server_p, struct gfs_client_rep_backend_state **statep) { /* * XXX FIXME * This should be done by gfs_client_command() instead of * calling gfrcmd, but it requires a wrapping layer which * converts xxx_connection() presentation to the input * for gfs_client_command_send_stdin(), and the output * of gfs_client_command_recv_stdout() to xxx_connection() * presentation. */ char *e; int i, stdin_pipe[2], stdout_pipe[2]; char interleave[GFARM_INT32STRLEN + 1]; char divisions[GFARM_INT32STRLEN + 1]; char fs_stripe[GFARM_INT32STRLEN + 1]; char version[GFARM_INT32STRLEN + 1]; /* "gfrcmd <dst> gfrepbe_client -i <I> -n <N> -s -r -S 1 <srchost>" */ /* "gfrcmd <src> gfrepbe_server -i <I> -n <N> -s -a <version>" */ char *args[13]; struct gfs_client_rep_backend_state *state; if (algorithm_version >= 0 && (arg != NULL || file_sync_stripe > 0 || recv_stripe_sync)) return ("gfs_client_rep_backend_invoke: argument invalid"); state = malloc(sizeof(*state)); if (state == NULL) return (GFARM_ERR_NO_MEMORY); i = 0; args[i++] = "gfrcmd"; args[i++] = canonical_hostname; args[i++] = program; if (interleave_factor != 0) { sprintf(interleave, "%d", interleave_factor); args[i++] = "-i"; args[i++] = interleave; } if (ndivisions > 1) { sprintf(divisions, "%d", ndivisions); args[i++] = "-n"; args[i++] = divisions; } if (file_sync_stripe > 0) { sprintf(fs_stripe, "%d", file_sync_stripe); args[i++] = "-S"; args[i++] = fs_stripe; } if (send_stripe_sync) args[i++] = "-s"; if (recv_stripe_sync) args[i++] = "-r"; if (algorithm_version >= 0) { sprintf(version, "%d", algorithm_version); args[i++] = "-a"; args[i++] = version; } if (arg != NULL) args[i++] = arg; args[i++] = NULL; if (socketpair(AF_UNIX, SOCK_STREAM, 0, stdin_pipe) == -1) { e = gfarm_errno_to_error(errno); fprintf(stderr, "%s: creating a pipe for stdin to %s: %s\n", message_prefix, canonical_hostname, e); free(state); return (e); } if (socketpair(AF_UNIX, SOCK_STREAM, 0, stdout_pipe) == -1) { e = gfarm_errno_to_error(errno); fprintf(stderr, "%s: creating a pipe for stdout to %s: %s\n", message_prefix, canonical_hostname, e); close(stdin_pipe[0]); close(stdin_pipe[1]); free(state); return (e); } if ((state->pid = fork()) == -1) { e = gfarm_errno_to_error(errno); fprintf(stderr, "%s: fork(2) for %s %s: %s\n", message_prefix, gfrcmd, canonical_hostname, e); close(stdin_pipe[0]); close(stdin_pipe[1]); close(stdout_pipe[0]); close(stdout_pipe[1]); free(state); return (e); } else if (state->pid == 0) { /* child */ dup2(stdin_pipe[0], STDIN_FILENO); dup2(stdout_pipe[1], STDOUT_FILENO); close(stdin_pipe[0]); close(stdin_pipe[1]); close(stdout_pipe[0]); close(stdout_pipe[1]); /* close other streams, if any */ for (i = 3; i < stdout_pipe[1]; i++) close(i); execvp(gfrcmd, args); e = gfarm_errno_to_error(errno); fprintf(stderr, "%s: invoking %s %s: %s\n", message_prefix, gfrcmd, canonical_hostname, e); _exit(EXIT_FAILURE); } /* parent */ close(stdin_pipe[0]); close(stdout_pipe[1]); e = xxx_fd_connection_new(stdin_pipe[1], &state->out); if (e != NULL) { fprintf(stderr, "%s: allocating memory for pipe to %s: %s\n", message_prefix, canonical_hostname, e); close(stdin_pipe[1]); close(stdout_pipe[0]); kill(SIGTERM, state->pid); free(state); return (e); } e = xxx_fd_connection_new(stdout_pipe[0], &state->in); if (e != NULL) { fprintf(stderr, "%s: allocating memory for pipe from %s: %s\n", message_prefix, canonical_hostname, e); xxx_connection_free(state->out); close(stdout_pipe[0]); kill(SIGTERM, state->pid); free(state); return (e); } *from_server_p = state->in; *to_server_p = state->out; *statep = state; return (NULL); } char * gfs_client_rep_backend_wait(struct gfs_client_rep_backend_state *state) { int rv; while ((rv = waitpid(state->pid, NULL, 0)) == -1 && errno == EINTR) ; xxx_connection_free(state->in); xxx_connection_free(state->out); free(state); return (NULL); } char * gfs_client_rep_backend_kill(struct gfs_client_rep_backend_state *state) { kill(SIGTERM, state->pid); xxx_connection_free(state->in); xxx_connection_free(state->out); free(state); return (NULL); } /* * common routine for gfrep and gfrepbe_client. * other programs/libraries shouldn't use this function. */ char * gfs_client_rep_filelist_send( char *server_name, struct xxx_connection *to_server, char *message_prefix, int n, gfarm_stringlist *files, gfarm_stringlist *sections) { char *e; int i; /* * XXX FIXME: This should be done in parallel during replication. */ for (i = 0; i < n; i++) { char *gfarm_file = gfarm_stringlist_elem(files, i); char *section = gfarm_stringlist_elem(sections, i); if (section == NULL) section = ""; e = xxx_proto_send(to_server, "ss", gfarm_file, section); if (e != NULL) { fprintf(stderr, "%s: " "error while sending requests to %s on %s: %s\n", message_prefix, server_name, gfarm_host_get_self_name(), e); return (e); } } /* end of requests mark */ e = xxx_proto_send(to_server, "ss", "", ""); if (e != NULL) { fprintf(stderr, "%s: " "error while sending end of requests to %s on %s: %s\n", message_prefix, server_name, gfarm_host_get_self_name(), e); return (e); } e = xxx_proto_flush(to_server); if (e != NULL) { fprintf(stderr, "%s: " "error while flushing requests to %s on %s: %s\n", message_prefix, server_name, gfarm_host_get_self_name(), e); return (e); } return (NULL); } /* * common routine for gfrepbe_client and gfrepbe_server. * other programs/libraries shouldn't use this function. */ char * gfs_client_rep_filelist_receive(struct xxx_connection *from_client, int *np, gfarm_stringlist *files, gfarm_stringlist *sections, char *message_prefix) { int eof, n; char *e, *file, *section; /* * XXX FIXME: This should be done in parallel during replication. */ e = gfarm_stringlist_init(files); if (e != NULL) { fprintf(stderr, "%s: allocating memory for filenames: %s\n", message_prefix, e); return (e); } e = gfarm_stringlist_init(sections); if (e != NULL) { fprintf(stderr, "%s: allocating memory for sections: %s\n", message_prefix, e); return (e); } n = 0; for (;;) { e = xxx_proto_recv(from_client, 0, &eof, "ss", &file, &section); if (e != NULL) { fprintf(stderr, "%s: error while receiving requests: " "%s\n", message_prefix, e); return (e); } if (eof) { fprintf(stderr, "%s: unexpected EOF " "while receiving file:section lists\n", message_prefix); return (GFARM_ERR_PROTOCOL); } if (*file == '\0') { /* end of list */ if (*section != '\0') { fprintf(stderr, "%s: " "protocol error, unexpected section = <%s>" " at the end of replication list\n", message_prefix, section); return (GFARM_ERR_PROTOCOL); } free(file); free(section); break; } e = gfarm_stringlist_add(files, file); if (e != NULL) { fprintf(stderr, "%s: %s for file %s:%s\n", message_prefix, e, file, section); return (e); } e = gfarm_stringlist_add(sections, section); if (e != NULL) { fprintf(stderr, "%s: %s for section %s:%s\n", message_prefix, e, file, section); return (e); } n++; } *np = n; return (NULL); } char * gfarm_file_section_replicate_multiple_request( gfarm_stringlist *gfarm_file_list, gfarm_stringlist *section_list, char *src_canonical, char *dst_canonical, struct gfs_client_rep_backend_state **statep) { char *e, **gfrep_backend_client_paths; struct sockaddr peer_addr; long parallel_streams, stripe_unit_size; long file_sync_stripe, send_stripe_sync, recv_stripe_sync; struct gfs_client_rep_backend_state *state; struct xxx_connection *from_server, *to_server; int replication_method_save; static char *gfrcmd = NULL; /* cache */ if (gfarm_stringlist_length(gfarm_file_list) != gfarm_stringlist_length(section_list)) return ("number of files isn't equal to number of sections"); /* * netparam is evaluated here rather than in gfsd, * so, settings in user's .gfarmrc can be reflected. * * XXX - but this also means that settings in frontend host * is used, rather than settings in the host which does * actual transfer. */ e = gfarm_host_address_get(src_canonical, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_parallel_streams, src_canonical, (struct sockaddr *)&peer_addr, &parallel_streams); if (e != NULL) /* shouldn't happen */ return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_stripe_unit_size, src_canonical, (struct sockaddr *)&peer_addr, &stripe_unit_size); if (e != NULL) /* shouldn't happen */ return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_file_sync_stripe, src_canonical, (struct sockaddr *)&peer_addr, &file_sync_stripe); if (e != NULL) /* shouldn't happen */ return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_send_stripe_sync, src_canonical, (struct sockaddr *)&peer_addr, &send_stripe_sync); if (e != NULL) /* shouldn't happen */ return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_recv_stripe_sync, src_canonical, (struct sockaddr *)&peer_addr, &recv_stripe_sync); if (e != NULL) /* shouldn't happen */ return (e); if (gfrcmd == NULL) { /* if `gfrcmd' is not cached */ char *self_canonical, **gfrcmd_real_paths; if (gfarm_host_get_canonical_self_name(&self_canonical)!= NULL) gfrcmd = gfrcmd_path; /* not a filesystem node */ else { replication_method_save = gfarm_replication_get_method(); gfarm_replication_set_method( GFARM_REPLICATION_BOOTSTRAP_METHOD); e = gfarm_url_program_deliver(GFRCMD_URL, 1, &self_canonical, &gfrcmd_real_paths); gfarm_replication_set_method( replication_method_save); if (e != NULL) return ("cannot replicate " GFRCMD_URL " to this host"); gfrcmd = strdup(gfrcmd_real_paths[0]); gfarm_strings_free_deeply(1, gfrcmd_real_paths); if (gfrcmd == NULL) return (GFARM_ERR_NO_MEMORY); } } replication_method_save = gfarm_replication_get_method(); gfarm_replication_set_method(GFARM_REPLICATION_BOOTSTRAP_METHOD); e = gfarm_url_program_deliver(gfrep_backend_client_url, 1, &dst_canonical, &gfrep_backend_client_paths); gfarm_replication_set_method(replication_method_save); if (e != NULL) return (e); e = gfs_client_rep_backend_invoke(dst_canonical, gfrcmd, gfrep_backend_client_paths[0], src_canonical, -1, parallel_streams, stripe_unit_size, file_sync_stripe, send_stripe_sync, recv_stripe_sync, "gfarm_file_section_replicate_multiple_request()", &from_server, &to_server, &state); gfarm_strings_free_deeply(1, gfrep_backend_client_paths); if (e != NULL) return (e); state->n = gfarm_stringlist_length(gfarm_file_list); e = gfs_client_rep_filelist_send(src_canonical, state->out, "gfarm_file_section_replicate_multiple_request()", state->n, gfarm_file_list, section_list); if (e != NULL) { gfs_client_rep_backend_kill(state); return (e); } *statep = state; return (NULL); } char * gfarm_file_section_replicate_multiple_result( struct gfs_client_rep_backend_state *state, char **errors) { char *e = NULL; int i, eof; gfarm_int32_t result; for (i = 0; i < state->n; i++) { e = xxx_proto_recv(state->in, 0, &eof, "i", &result); if (e != NULL || eof) { if (e == NULL) e = "unexpected EOF"; fprintf(stderr, "reply from gfrepbe_client is too short: " "%d expected, %d received: %s\n", state->n, i, e); if (i == 0) break; for (; i < state->n; i++) errors[i] = GFARM_ERR_PROTOCOL; e = NULL; break; } errors[i] = result == GFS_ERROR_NOERROR ? NULL : gfs_proto_error_string(result); } gfs_client_rep_backend_wait(state); return (e); } char * gfarm_file_section_replicate_multiple( gfarm_stringlist *gfarm_file_list, gfarm_stringlist *section_list, char *srchost, char *dsthost, char **errors) { char *e; struct gfs_client_rep_backend_state *state; e = gfarm_file_section_replicate_multiple_request( gfarm_file_list, section_list, srchost, dsthost, &state); if (e != NULL) return (e); return (gfarm_file_section_replicate_multiple_result(state, errors)); } /* these constants shoudn't be changed without changing algorithm_version */ #define GFS_CLIENT_IOSIZE_ALIGNMENT 4096 #define GFS_CLIENT_IOSIZE_MINIMUM_DIVISION 65536 int gfs_client_rep_limit_division(int algorithm_version, int ndivisions, file_offset_t file_size) { if (algorithm_version != GFS_CLIENT_REP_ALGORITHM_LATEST) return (-1); /* do not divide too much */ if (ndivisions > file_size / GFS_CLIENT_IOSIZE_MINIMUM_DIVISION) { ndivisions = file_size / GFS_CLIENT_IOSIZE_MINIMUM_DIVISION; if (ndivisions == 0) ndivisions = 1; } return (ndivisions); } struct gfs_client_rep_transfer_state { file_offset_t size; int interleave_factor; /* 0, if it's simple_division case */ file_offset_t full_stripe_size; /* only used for striping case */ file_offset_t offset; file_offset_t chunk_offset; file_offset_t transfered; file_offset_t chunk_residual; }; static void simple_division(file_offset_t file_size, int ndivisions, struct gfs_client_rep_transfer_state **transfers) { file_offset_t offset = 0, residual = file_size; file_offset_t size_per_division = file_offset_floor(file_size / ndivisions); int i; if (file_offset_floor(size_per_division/GFS_CLIENT_IOSIZE_ALIGNMENT) * GFS_CLIENT_IOSIZE_ALIGNMENT != size_per_division) { size_per_division = (file_offset_floor( size_per_division / GFS_CLIENT_IOSIZE_ALIGNMENT) + 1) * GFS_CLIENT_IOSIZE_ALIGNMENT; } for (i = 0; i < ndivisions; i++) { file_offset_t size; /* NOTE: ``residual'' may be 0 here */ size = residual <= size_per_division ? residual : size_per_division; transfers[i]->size = size; transfers[i]->interleave_factor = 0; transfers[i]->full_stripe_size = 0; transfers[i]->offset = offset; transfers[i]->chunk_offset = offset; offset += size_per_division; residual -= size; transfers[i]->transfered = 0; transfers[i]->chunk_residual = size; } } static void striping(file_offset_t file_size, int ndivisions, int interleave_factor, struct gfs_client_rep_transfer_state **transfers) { file_offset_t full_stripe_size = (file_offset_t)interleave_factor * ndivisions; file_offset_t stripe_number = file_offset_floor(file_size / full_stripe_size); file_offset_t size_per_division = interleave_factor * stripe_number; file_offset_t residual = file_size - full_stripe_size * stripe_number; file_offset_t chunk_number_on_last_stripe; file_offset_t last_chunk_size; file_offset_t offset = 0; int i; if (residual == 0) { chunk_number_on_last_stripe = 0; last_chunk_size = 0; } else { chunk_number_on_last_stripe = file_offset_floor( residual / interleave_factor); last_chunk_size = residual - interleave_factor * chunk_number_on_last_stripe; } for (i = 0; i < ndivisions; i++) { file_offset_t size = size_per_division; if (i < chunk_number_on_last_stripe) size += interleave_factor; else if (i == chunk_number_on_last_stripe) size += last_chunk_size; /* NOTE: ``size'' may be 0 here */ transfers[i]->size = size; transfers[i]->interleave_factor = interleave_factor; transfers[i]->full_stripe_size = full_stripe_size; transfers[i]->offset = offset; transfers[i]->chunk_offset = offset; offset += interleave_factor; transfers[i]->transfered = 0; if (stripe_number > 0 || i < chunk_number_on_last_stripe) transfers[i]->chunk_residual = interleave_factor; else if (i == chunk_number_on_last_stripe) transfers[i]->chunk_residual = last_chunk_size; else transfers[i]->chunk_residual = 0; } } char * gfs_client_rep_transfer_state_alloc(file_offset_t file_size, int algorithm_version, int ndivisions, int interleave_factor, struct gfs_client_rep_transfer_state ***transfersp) { int i; struct gfs_client_rep_transfer_state **transfers; if (algorithm_version != GFS_CLIENT_REP_ALGORITHM_LATEST) return ("unknown gfrep algorithm"); transfers = malloc(sizeof(*transfers) * ndivisions); if (transfers == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < ndivisions; i++) { transfers[i] = malloc(sizeof(*transfers[i])); if (transfers[i] == NULL) { while (--i >= 0) free(transfers[i]); free(transfers); return (GFARM_ERR_NO_MEMORY); } } if (interleave_factor == 0) { simple_division(file_size, ndivisions, transfers); } else { striping(file_size, ndivisions, interleave_factor, transfers); } *transfersp = transfers; return (NULL); } void gfs_client_rep_transfer_state_free(int ndivisions, struct gfs_client_rep_transfer_state **transfers) { int i; for (i = 0; i < ndivisions; i++) free(transfers[i]); free(transfers); } int gfs_client_rep_transfer_finished( struct gfs_client_rep_transfer_state *transfer) { return (transfer->transfered >= transfer->size); } int gfs_client_rep_transfer_stripe_finished( struct gfs_client_rep_transfer_state *transfer) { return (transfer->chunk_residual == 0); } size_t gfs_client_rep_transfer_length( struct gfs_client_rep_transfer_state *transfer, size_t limit) { return (transfer->chunk_residual < limit ? (size_t)transfer->chunk_residual : limit); } file_offset_t gfs_client_rep_transfer_offset(struct gfs_client_rep_transfer_state *transfer) { return (transfer->offset); } int gfs_client_rep_transfer_stripe_offset( struct gfs_client_rep_transfer_state *transfer) { return (transfer->offset - transfer->chunk_offset); } void gfs_client_rep_transfer_stripe_progress( struct gfs_client_rep_transfer_state *transfer, size_t length) { /* assert(length <= transfer->chunk_residual); */ transfer->offset += length; transfer->transfered += length; transfer->chunk_residual -= length; } void gfs_client_rep_transfer_stripe_next( struct gfs_client_rep_transfer_state *transfer) { if (transfer->chunk_residual == 0) { /* stripe_finished ? */ if (transfer->transfered < transfer->size) { /* must be striping mode */ /* assert(transfer->interleave_factor != 0) */ transfer->offset += transfer->full_stripe_size - transfer->interleave_factor; transfer->chunk_offset += transfer->full_stripe_size; transfer->chunk_residual = transfer->size - transfer->transfered; if (transfer->chunk_residual > transfer->interleave_factor) transfer->chunk_residual = transfer->interleave_factor; } } } void gfs_client_rep_transfer_progress( struct gfs_client_rep_transfer_state *transfer, size_t length) { gfs_client_rep_transfer_stripe_progress(transfer, length); gfs_client_rep_transfer_stripe_next(transfer); } <file_sep>/gfarm_mpiio/trunk/ad_gfarm/ad_gfarm_open.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" #include "adioi.h" void ADIOI_GFARM_Open(ADIO_File fd, int *error_code) { int myrank, nprocs; size_t size; char *gfarm_dirname, *gfarm_meta_dirname, *gfarm_data_dirname, *gfarm_filename, *getvalue; ADIOI_GFARM_headerInf *ghi; GFS_Dir gfs_dirp; GFS_File gfs_file; gfarm_error_t gerr; fd->fd_sys = 1; fd->fd_direct = -1; *error_code = MPI_SUCCESS; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); #ifdef GFARM_DEBUG FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_Open called on %s\n", myrank, nprocs, fd->filename); #endif gerr = gfarm_initialize(NULL, NULL); if(gerr != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfarm_initialize. gerr = %d\n", myrank, nprocs, gerr); } //MPI_INFO = NULL gerr = gfs_opendir(fd->filename, &gfs_dirp); //create new file if(gerr == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY){ //create dirname gfarm_meta_dirname = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10)); gfarm_data_dirname = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10)); gfarm_filename = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10)); sprintf(gfarm_meta_dirname, "%s/meta", fd->filename); sprintf(gfarm_data_dirname, "%s/data", fd->filename); sprintf(gfarm_filename, "%s/data/0", fd->filename); //create dir if(myrank == 0){ //root dir if(gerr = gfs_mkdir(fd->filename, 0000755) != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfs_mkdir %s. gerr = %d\n", myrank, nprocs, fd->filename, gerr); } //set mpi-io/gfarm flag if(gerr = gfs_setxattr(fd->filename, "user.mpiio", "1", 16, GFS_XATTR_CREATE) != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfs_setxattr %s. gerr = %d\n", myrank, nprocs, fd->filename, gerr); } //meta dir if(gerr = gfs_mkdir(gfarm_meta_dirname, 0000755) != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfs_mkdir %s. gerr = %d\n", myrank, nprocs, gfarm_meta_dirname, gerr); } //data dir if(gerr = gfs_mkdir(gfarm_data_dirname, 0000755) != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfs_mkdir %s. gerr = %d\n", myrank, nprocs, gfarm_data_dirname, gerr); } //create file if(gerr = gfs_pio_create(gfarm_filename,GFARM_FILE_RDWR,0000644,&gfs_file)){ printf("[%d/%d] gfs_pio_create %s. gerr = %d\n", myrank, nprocs, gfarm_filename, gerr); } } ghi = (ADIOI_GFARM_headerInf*)malloc(sizeof(ADIOI_GFARM_headerInf)); ghi->header_flag = 1; ghi->gfarm_view_flag = 0; ghi->header_gfp = gfs_file; fd->fs_ptr = ghi; free(gfarm_meta_dirname); free(gfarm_data_dirname); free(gfarm_filename); //access split file }else if(gerr == GFARM_ERR_NO_ERROR){ gfs_closedir(gfs_dirp); getvalue = (char*)malloc(sizeof(char)*16); size = 16; gerr = gfs_getxattr(fd->filename, "user.mpiio", getvalue, &size); if(gerr != GFARM_ERR_NO_ERROR){ //error_code printf("[%d/%d] gfarm_open. getvalue = %s, size = %d\n", myrank, nprocs, getvalue, size); printf("[%d/%d] gfarm_open %s is directory. but it is not set to mpiio flag. size = %d, gerr = %d\n", myrank, nprocs, fd->filename, size, gerr); //return; } //first open or not if(atoi(getvalue) == 1){ gfarm_filename = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10)); sprintf(gfarm_filename, "%s/data/0", fd->filename); //file open gerr = gfs_pio_open(gfarm_filename, GFARM_FILE_RDWR, &gfs_file); if(gerr != GFARM_ERR_NO_ERROR){ //error_code printf("[%d/%d] gfarm_open. error in open header file. gerr = %d\n", myrank, nprocs, gerr); return; } if(fd->fs_ptr != NULL){ ghi = (ADIOI_GFARM_headerInf*)fd->fs_ptr; }else{ ghi = (ADIOI_GFARM_headerInf*)malloc(sizeof(ADIOI_GFARM_headerInf)); fd->fs_ptr = ghi; } ghi->header_gfp = gfs_file; ghi->header_flag = 1; ghi->gfarm_view_flag = 0; ghi->gfp_num = 0; free(gfarm_filename); }else if(atoi(getvalue) == 2){ printf("[%d/%d] gfarm_open xattr.mpiio = %c. access to a existed file.\n", myrank, nprocs, getvalue); } free(getvalue); //error }else{ //error_code printf("[%d/%d] gerr = %d.\n", myrank, nprocs, gerr); return; } error_code = MPI_SUCCESS; #ifdef GFARM_DEBUG FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_Open end on %s\n", myrank, nprocs, fd->filename); #endif } <file_sep>/gfarm/tags/gfarm_1_0_rc2/lib/libgfarm/gfarm/hostspec.h /* * $Id$ */ struct gfarm_hostspec; struct sockaddr; char *gfarm_hostspec_parse(char *, struct gfarm_hostspec **); void gfarm_hostspec_free(struct gfarm_hostspec *); int gfarm_hostspec_match(struct gfarm_hostspec *, const char *, struct sockaddr *); char *gfarm_sockaddr_to_name(struct sockaddr *, char **); /* "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]" */ #define GFARM_SOCKADDR_STRLEN 42 void gfarm_sockaddr_to_string(struct sockaddr *, char *, size_t); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_0_rc2/gfarm2fs_msg_enums.h #define GFARM_MSG_2000001 2000001 #define GFARM_MSG_2000002 2000002 #define GFARM_MSG_2000003 2000003 #define GFARM_MSG_2000004 2000004 #define GFARM_MSG_2000005 2000005 #define GFARM_MSG_2000006 2000006 #define GFARM_MSG_2000007 2000007 #define GFARM_MSG_2000008 2000008 #define GFARM_MSG_2000009 2000009 #define GFARM_MSG_2000010 2000010 #define GFARM_MSG_2000011 2000011 #define GFARM_MSG_2000012 2000012 #define GFARM_MSG_2000013 2000013 #define GFARM_MSG_2000014 2000014 #define GFARM_MSG_2000015 2000015 #define GFARM_MSG_2000016 2000016 #define GFARM_MSG_2000017 2000017 #define GFARM_MSG_2000018 2000018 #define GFARM_MSG_2000019 2000019 #define GFARM_MSG_2000020 2000020 #define GFARM_MSG_2000021 2000021 #define GFARM_MSG_2000022 2000022 #define GFARM_MSG_2000023 2000023 #define GFARM_MSG_2000024 2000024 #define GFARM_MSG_2000025 2000025 #define GFARM_MSG_2000026 2000026 #define GFARM_MSG_2000027 2000027 #define GFARM_MSG_2000028 2000028 #define GFARM_MSG_2000029 2000029 #define GFARM_MSG_2000030 2000030 #define GFARM_MSG_2000031 2000031 #define GFARM_MSG_2000032 2000032 #define GFARM_MSG_2000033 2000033 #define GFARM_MSG_2000034 2000034 #define GFARM_MSG_2000035 2000035 #define GFARM_MSG_2000036 2000036 #define GFARM_MSG_2000037 2000037 #define GFARM_MSG_2000038 2000038 #define GFARM_MSG_2000039 2000039 #define GFARM_MSG_2000040 2000040 #define GFARM_MSG_2000041 2000041 #define GFARM_MSG_2000042 2000042 #define GFARM_MSG_2000043 2000043 #define GFARM_MSG_2000044 2000044 <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/bench/thput-gfpio/thput-gfpio.c /* * $Id$ */ #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gfarm/gfarm.h> int node_index = -1; #ifdef i386 typedef unsigned long long timerval_t; double timerval_calibration; unsigned long long get_cycles(void) { unsigned long long rv; __asm __volatile("rdtsc" : "=A" (rv)); return (rv); } #define gettimerval(tp) (*(tp) = get_cycles()) #define timerval_second(tp) (*(tp) * timerval_calibration) #define timerval_sub(t1p, t2p) ((*(t1p) - *(t2p)) * timerval_calibration) void timerval_calibrate(void) { timerval_t t1, t2; struct timeval s1, s2; /* warming up */ gettimerval(&t1); gettimeofday(&s1, NULL); gettimerval(&t1); gettimeofday(&s1, NULL); sleep(3); gettimerval(&t2); gettimeofday(&s2, NULL); timerval_calibration = ((s2.tv_sec - s1.tv_sec) + (s2.tv_usec - s1.tv_usec) * .000001) / (t2 - t1); fprintf(stderr, "[%03d] timer/sec=%g %s\n", node_index, 1.0 / timerval_calibration, gfarm_host_get_self_name()); } #else /* gettimeofday */ typedef struct timeval timerval_t; #define gettimerval(t1) gettimeofday(t1, NULL) #define timerval_second(t1) ((double)(t1)->tv_sec \ + (double)(t1)->tv_usec * .000001) #define timerval_sub(t1, t2) \ (((double)(t1)->tv_sec - (double)(t2)->tv_sec) \ + ((double)(t1)->tv_usec - (double)(t2)->tv_usec) * .000001) void timerval_calibrate(void) {} #endif int tm_write_write_measured = 0; timerval_t tm_write_open_0, tm_write_open_1; timerval_t tm_write_write_0, tm_write_write_1; timerval_t tm_write_write_all_0, tm_write_write_all_1; timerval_t tm_write_close_0, tm_write_close_1; int tm_read_read_measured = 0; timerval_t tm_read_open_0, tm_read_open_1; timerval_t tm_read_read_0, tm_read_read_1; timerval_t tm_read_read_all_0, tm_read_read_all_1; timerval_t tm_read_close_0, tm_read_close_1; char *program_name = "thput-gfpio"; #define MAX_BUFFER_SIZE (1024*1024) char buffer[MAX_BUFFER_SIZE]; void initbuffer(void) { int i; for (i = 0; i < MAX_BUFFER_SIZE; i++) buffer[i] = i; } void writetest(char *ofile, int buffer_size, off_t file_size) { GFS_File gf; char *e; int rv; off_t residual; gettimerval(&tm_write_open_0); e = gfs_pio_create(ofile, GFARM_FILE_WRONLY, 0666, &gf); if (e != NULL) { fprintf(stderr, "[%03d] cannot open %s: %s on %s\n", node_index, ofile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_pio_set_view_local(gf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "[%03d] set_view_local(%s): %s on %s\n", node_index, ofile, e, gfarm_host_get_self_name()); exit(1); } gettimerval(&tm_write_open_1); gettimerval(&tm_write_write_all_0); for (residual = file_size; residual > 0; residual -= rv) { if (!tm_write_write_measured) { tm_write_write_measured = 1; gettimerval(&tm_write_write_0); e = gfs_pio_write(gf, buffer, buffer_size <= residual ? buffer_size : residual, &rv); gettimerval(&tm_write_write_1); } else { e = gfs_pio_write(gf, buffer, buffer_size <= residual ? buffer_size : residual, &rv); } if (e != NULL) { fprintf(stderr, "[%03d] write test: %s on %s\n", node_index, e, gfarm_host_get_self_name()); break; } if (rv != (buffer_size <= residual ? buffer_size : residual)) break; } gettimerval(&tm_write_write_all_1); if (residual > 0) { fprintf(stderr, "[%03d] write test failed, residual = %ld on %s\n", node_index, (long)residual, gfarm_host_get_self_name()); } gettimerval(&tm_write_close_0); e = gfs_pio_close(gf); gettimerval(&tm_write_close_1); if (e != NULL) { fprintf(stderr, "[%03d] write test close failed: %s on %s\n", node_index, e, gfarm_host_get_self_name()); } } off_t readtest(char *ifile, int buffer_size, off_t file_size) { GFS_File gf; struct gfs_stat status; char *e; int rv; off_t residual; gettimerval(&tm_read_open_0); e = gfs_pio_open(ifile, GFARM_FILE_RDONLY, &gf); if (e != NULL) { fprintf(stderr, "[%03d] cannot open %s: %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_pio_set_view_local(gf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "[%03d] set_view_local(%s): %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } gettimerval(&tm_read_open_1); e = gfs_fstat(gf, &status); if (e != NULL) { fprintf(stderr, "[%03d] fstat(%s): %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } if (file_size == 0) file_size = status.st_size; if (file_size > status.st_size) file_size = status.st_size; gfs_stat_free(&status); gettimerval(&tm_read_read_all_0); for (residual = file_size; residual > 0; residual -= rv) { if (!tm_read_read_measured) { tm_read_read_measured = 1; gettimerval(&tm_read_read_0); e = gfs_pio_read(gf, buffer, buffer_size <= residual ? buffer_size : residual, &rv); gettimerval(&tm_read_read_1); } else { e = gfs_pio_read(gf, buffer, buffer_size <= residual ? buffer_size : residual, &rv); } if (e != NULL) { fprintf(stderr, "[%03d] read test: %s on %s\n", node_index, e, gfarm_host_get_self_name()); break; } if (rv == 0) break; if (rv != buffer_size && rv != residual) break; } gettimerval(&tm_read_read_all_1); if (residual > 0) { fprintf(stderr, "[%03d] read test failed, residual = %ld on %s\n", node_index, (long)residual, gfarm_host_get_self_name()); } gettimerval(&tm_read_close_0); e = gfs_pio_close(gf); gettimerval(&tm_read_close_1); if (e != NULL) { fprintf(stderr, "[%03d] read test close failed: %s on %s\n", node_index, e, gfarm_host_get_self_name()); } return (file_size - residual); } off_t copytest(char *ifile, char *ofile, int buffer_size, off_t file_size) { GFS_File igf, ogf; struct gfs_stat status; char *e; int rv, osize; off_t residual; e = gfs_pio_open(ifile, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "[%03d] cannot open %s: %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_pio_set_view_local(igf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "[%03d] set_view_local(%s): %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_pio_create(ofile, GFARM_FILE_WRONLY, 0666, &ogf); if (e != NULL) { fprintf(stderr, "[%03d] cannot open %s: %s on %s\n", node_index, ofile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_pio_set_view_local(ogf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "[%03d] set_view_local(%s): %s on %s\n", node_index, ofile, e, gfarm_host_get_self_name()); exit(1); } e = gfs_fstat(igf, &status); if (e != NULL) { fprintf(stderr, "[%03d] fstat(%s): %s on %s\n", node_index, ifile, e, gfarm_host_get_self_name()); exit(1); } if (file_size == 0) file_size = status.st_size; if (file_size > status.st_size) file_size = status.st_size; gfs_stat_free(&status); for (residual = file_size; residual > 0; residual -= rv) { e = gfs_pio_read(igf, buffer, buffer_size, &rv); if (e != NULL) { fprintf(stderr, "[%03d] copytest read: %s on %s\n", node_index, e, gfarm_host_get_self_name()); break; } if (rv == 0) break; if (rv != buffer_size && rv != residual) break; osize = rv; e = gfs_pio_write(ogf, buffer, osize, &rv); if (e != NULL) { fprintf(stderr, "[%03d] copytest write: %s on %s\n", node_index, e, gfarm_host_get_self_name()); break; } if (rv != osize) break; } if (residual > 0) { fprintf(stderr, "[%03d] copy test failed, residual = %ld on %s\n", node_index, (long)residual, gfarm_host_get_self_name()); } e = gfs_pio_close(ogf); if (e != NULL) { fprintf(stderr, "[%03d] copy test write close failed: %s on %s\n", node_index, e, gfarm_host_get_self_name()); } e = gfs_pio_close(igf); if (e != NULL) { fprintf(stderr, "[%03d] copy test read close failed: %s on %s\n", node_index, e, gfarm_host_get_self_name()); } return (file_size - residual); } double timeval_sub(struct timeval *t1, struct timeval *t2) { return ((t1->tv_sec + t1->tv_usec * .000001) - (t2->tv_sec + t2->tv_usec * .000001)); } enum testmode { TESTMODE_WRITE, TESTMODE_READ, TESTMODE_COPY }; #define FLAG_MEASURE_PRIMITIVES 1 void test(enum testmode test_mode, char *file1, char *file2, int buffer_size, off_t file_size, int flags) { struct timeval t1, t2; char *label; gettimeofday(&t1, NULL); switch (test_mode) { case TESTMODE_WRITE: writetest(file1, buffer_size, file_size); label = "write"; break; case TESTMODE_READ: file_size = readtest(file1, buffer_size, file_size); label = "read"; break; case TESTMODE_COPY: file_size = copytest(file1, file2, buffer_size, file_size); label = "copy"; break; default: fprintf(stderr, "[%03d] ??? wrong test_mode: %d\n", node_index, test_mode); exit(1); } gettimeofday(&t2, NULL); printf("[%03d] %" PR_FILE_OFFSET " %7d %-5s %10.0f %s\n", node_index, CAST_PR_FILE_OFFSET (file_offset_t)file_size, buffer_size, label, file_size / timeval_sub(&t2, &t1), gfarm_host_get_self_name()); fflush(stdout); if ((flags & FLAG_MEASURE_PRIMITIVES) != 0) { fprintf(stderr, "[%03d] %" PR_FILE_OFFSET " %7d %-5s", node_index, CAST_PR_FILE_OFFSET (file_offset_t)file_size, buffer_size, label); if (test_mode == TESTMODE_WRITE) fprintf(stderr, " %11g %11g %11g %11g\n", timerval_sub(&tm_write_open_1, &tm_write_open_0), timerval_sub(&tm_write_write_1, &tm_write_write_0), timerval_sub(&tm_write_write_all_1, &tm_write_write_all_0), timerval_sub(&tm_write_close_1, &tm_write_close_0) ); if (test_mode == TESTMODE_READ) fprintf(stderr, " %11g %11g %11g %11g\n", timerval_sub(&tm_read_open_1, &tm_read_open_0), timerval_sub(&tm_read_read_1, &tm_read_read_0), timerval_sub(&tm_read_read_all_1, &tm_read_read_all_0), timerval_sub(&tm_read_close_1, &tm_read_close_0) ); tm_write_write_measured = tm_read_read_measured = 0; } } #define DEFAULT_FILE_SIZE 1024 int main(int argc, char **argv) { char *file1 = "gfarm:test.file1"; char *file2 = "gfarm:test.file2"; int c, buffer_size = 1024 * 1024; off_t file_size = 0; enum testmode test_mode = TESTMODE_WRITE; int flags = 0; char *e; if (argc > 0) program_name = argv[0]; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm_initalize(): %s\n", program_name, e); exit(1); } while ((c = getopt(argc, argv, "b:s:wrcm")) != -1) { switch (c) { case 'b': buffer_size = strtol(optarg, NULL, 0); if (buffer_size > MAX_BUFFER_SIZE) { fprintf(stderr, "%s: \"-b %d\" is too big\n", program_name, buffer_size); exit(1); } break; case 's': file_size = strtol(optarg, NULL, 0); break; case 'w': test_mode = TESTMODE_WRITE; break; case 'r': test_mode = TESTMODE_READ; break; case 'c': test_mode = TESTMODE_COPY; break; case 'm': flags |= FLAG_MEASURE_PRIMITIVES; break; case '?': default: fprintf(stderr, "Usage: gfrun %s [options]" " [gfarm_url1 [gfarm_url2]]\n" "options:\n" "\t-b block-size\n" "\t-s file-size\n" "\t-w : write test\n" "\t-r : read test\n" "\t-c : copy test\n", program_name); exit(1); } } argc -= optind; argv += optind; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: gfs_pio_get_node_rank(): %s\n", program_name, e); exit(1); } if (argc > 0) file1 = argv[0]; if (argc > 1) file2 = argv[1]; if (flags & FLAG_MEASURE_PRIMITIVES) timerval_calibrate(); if (file_size == 0 && test_mode == TESTMODE_WRITE) file_size = DEFAULT_FILE_SIZE; file_size *= 1024 * 1024; initbuffer(); test(test_mode, file1, file2, buffer_size, file_size, flags); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: gfarm_terminiate(): %s on %s\n", program_name, e, gfarm_host_get_self_name()); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1/gftool/gfmkdir/gfmkdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <unistd.h> #include <sys/time.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include <gfarm/gfarm_error.h> #include "gfs_client.h" char *program_name = "gfmkdir"; static void usage() { fprintf(stderr, "Usage: %s directory...\n", program_name); exit(1); } int main(int argc, char **argv) { char *e; int i, c, err = 0; extern int optind; if (argc <= 1) usage(); program_name = basename(argv[0]); while ((c = getopt(argc, argv, "h?")) != EOF) { switch (c) { case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < argc; i++) { e = gfs_mkdir(argv[i], 0755); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); err++; } } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); err++; } return (err > 0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_editor/download.php <?php include('./common.php'); header('Content-Disposition: attachment; filename="gfarm2.conf"'); header('Content-Type: text/plain'); header('Content-Transfer-Encoding: 8bit'); $lines = read_gfarm2_conf_file(); foreach ($lines as $line) { printf("%s\n", $line); } print("\n"); $lines = read_gfmdlist_file(); foreach ($lines as $line) { printf("%s\n", $line); } ?> <file_sep>/gfarm/branches/metadb_dev/lib/Makefile top_objdir = .. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk GLOBUS_SUBDIRS = libgfsl SUBDIRS = \ $(globus_subdirs) \ libgfarm \ gfs_hook include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_represent_client_gfmdhost2.sh.in #!/bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on a representative client host. # It executes 'gfmdhost -1 -N -P ...' for each gfmd server. It checks # which servers are listening on TCP ports and which server are not. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Execute 'gfmdhost' to get a list of gfmd servers. # GFCMD="@GFARM_BINDIR@/gfmdhost -l" GFMDS=`@GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD \ | awk '{print $6 ":" $7}'` # # Execute 'gfmdhost -1 -N -P ...' for each gfmd. # I=1 for GFMD in - $GFMDS; do [ "X$GFMD" = X- ] && continue GFCMD="@GFARM_BINDIR@/gfmdhost -1 -N -P gfarm://$GFMD" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > /dev/null 2>&1 & eval "GFCMD_PID$I=$!" I=`expr $I + 1` done I=1 for GFMD in - $GFMDS; do [ "X$GFMD" = X- ] && continue GFCMD_PID=`eval echo \\$GFCMD_PID$I` [ "X$GFCMD_PID" = X ] && continue wait $GFCMD_PID eval "GFCMD_EXITCODE$I=$?" I=`expr $I + 1` done # # Check whether more than one gfmd servers are listening. # I=1 LISTENING_GFMDS_COUNT=0 LISTENING_GFMDS="" for GFMD in - $GFMDS; do [ "X$GFMD" = X- ] && continue if [ `eval echo \\$GFCMD_EXITCODE$I` -eq 0 ]; then if [ "X$LISTENING_GFMDS" = X ]; then LISTENING_GFMDS=$GFMD else LISTENING_GFMDS="$LISTENING_GFMDS, $GFMD" fi LISTENING_GFMDS_COUNT=`expr $LISTENING_GFMDS_COUNT + 1` fi I=`expr $I + 1` done if [ $LISTENING_GFMDS_COUNT -gt 1 ]; then LISTENING_GFMDS="`echo $LISTENING_GFMDS | sed -e 's/:[0-9]*//g'`" echo "master: $LISTENING_GFMDS" else echo "ok" fi exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT-config #! /bin/sh . ./FT-common $gfservice config-gfarm-master gfmd1 # # Configure gfmd servers. # I=2 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice config-gfarm-slave gfmd$I gfmd1 I=`expr $I + 1` done # # Configure gfsd servers. # I=1 while [ "X`eval echo \\$gfsd$I`" != X ]; do $gfservice config-gfsd gfsd$I I=`expr $I + 1` done # # Configure clients. # I=1 while [ "X`eval echo \\$client$I`" != X ]; do $gfservice config-client client$I I=`expr $I + 1` done # # Create ~/.pgpass for Zabbix agent. # TMP_GFMD_CONF=/tmp/ftconfig.$$ TMP_PGPASS=/tmp/pgpass.$$ rm -f $TMP_GFMD_CONF $TMP_PGPASS trap "rm -f $TMP_GFMD_CONF $TMP_PGPASS; exit 1" 1 2 3 15 I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do rm -f $TMP_GFMD_CONF $TMP_PGPASS gfmd=`eval echo \\$gfmd$I` $gfservice backup-gfmd-conf gfmd$I > $TMP_GFMD_CONF awk '/^postgresql_server_host[ ]/ {host=$2} /^postgresql_server_port[ ]/ {port=$2} /^postgresql_dbname[ ]/ {db=$2} /^postgresql_user[ ]/ {user=$2} /^postgresql_password[ ]/ {gsub(/\"/, "", $2); passwd=$2} END {printf("%s:%s:%s:%s:%s\n", host, port, db, user, passwd)}' \ $TMP_GFMD_CONF > $TMP_PGPASS ssh $gfmd tee .pgpass < $TMP_PGPASS > /dev/null I=`expr $I + 1` done rm -f $TMP_GFMD_CONF $TMP_PGPASS exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_dead_gfmd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo "error: gfmd does not listen ${prefix} port." exit 0 fi c=0 while read prefix host port; do initscript="${prefix}/etc/init.d/gfmd" if [ "`$initscript status | grep -c running`" -ne 1 ]; then echo "error: ${prefix} is dead." c=`expr $c + 1` fi done<<EOF `read_gfmd_confs "$1"` EOF if [ $c = 0 ]; then echo "ok" fi exit 0 <file_sep>/gfarm/branches/metadb_dev/lib/gfs_hook/hooks_subr.h /* convert symbol to string literal */ #define STRING(symbol) #symbol #define S(symbol) STRING(symbol) #ifdef DEBUG #include <stdio.h> #define _gfs_hook_debug(x) x #else #define _gfs_hook_debug(x) #endif int gfs_hook_insert_gfs_file(GFS_File); void gfs_hook_clear_gfs_file(int); GFS_File gfs_hook_is_open(int); int gfs_hook_is_url(const char *, const char **); <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/gftool/addpath/addpath.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <sys/time.h> #include <pwd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gfarm/gfarm.h> /* * */ static char * gfarm_path_info_set_from_file(char *pathname, int nfrags) { struct stat sb; struct passwd *pw; struct gfarm_path_info pi; char *e, *p; if (stat(pathname, &sb)) return "no such file"; /* remove a section part. */ p = pathname; while (*p) { if (*p == ':') { *p = '\0'; break; } ++p; } pw = getpwuid(sb.st_uid); if (pw == NULL) return "no such user"; pi.pathname = pathname; pi.status.st_mode = GFARM_S_IFREG | (sb.st_mode & GFARM_S_ALLPERM); pi.status.st_user = strdup(pw->pw_name); /* XXX NULL check */ pi.status.st_group = strdup("*"); /* XXX for now */ pi.status.st_atimespec.tv_sec = sb.st_atime; pi.status.st_mtimespec.tv_sec = sb.st_mtime; pi.status.st_ctimespec.tv_sec = sb.st_ctime; pi.status.st_atimespec.tv_nsec = pi.status.st_mtimespec.tv_nsec = pi.status.st_ctimespec.tv_nsec = 0; pi.status.st_size = 0; pi.status.st_nsections = nfrags; e = gfarm_path_info_set(pi.pathname, &pi); return (e); } static char * gfarm_path_info_remove_all(char *pathname) { char *e, *e_save = NULL; e = gfarm_file_section_copy_info_remove_all_by_file(pathname); if (e != NULL) e_save = e; e = gfarm_file_section_info_remove_all_by_file(pathname); if (e != NULL) e_save = e; e = gfarm_path_info_remove(pathname); if (e != NULL) e_save = e; return (e_save); } /* * */ static char *progname = "addpath"; void usage() { fprintf(stderr, "usage: %s pathname:sec nfrags\n", progname); fprintf(stderr, " %s -d pathname\n", progname); } int main(int argc, char *argv[]) { char *pathname; int nfrags; char *e; extern int optind; int c; enum { add, delete } mode = add; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); } while ((c = getopt(argc, argv, "d")) != EOF) { switch (c) { case 'd': mode = delete; break; default: usage(); exit(1); } } argc -= optind; argv += optind; if (argc > 0) pathname = argv[0]; else { fprintf(stderr, "%s: too few arguments\n", progname); usage(); exit(1); } --argc; ++argv; switch (mode) { case add: if (argc == 1) nfrags = atoi(argv[0]); else { usage(); exit(1); } e = gfarm_path_info_set_from_file(pathname, nfrags); if (e != NULL) { fprintf(stderr, "%s: %s\n", pathname, e); exit(1); } break; case delete: e = gfarm_path_info_remove_all(pathname); if (e != NULL) { fprintf(stderr, "%s: %s\n", pathname, e); exit(1); } break; } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", pathname, e); } exit(0); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfarm/metadb_ldap.c /* * $Id$ */ #include <assert.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <lber.h> #include <ldap.h> #include <gfarm/gfarm.h> #include "config.h" #include "dircache.h" /* old openldap does not have ldap_memfree. */ #ifndef HAVE_LDAP_MEMFREE #define ldap_memfree(a) #endif /* HAVE_LDAP_MEMFREE */ #define INT32STRLEN GFARM_INT32STRLEN #define INT64STRLEN GFARM_INT64STRLEN #define ARRAY_LENGTH(array) GFARM_ARRAY_LENGTH(array) /**********************************************************************/ static LDAP *gfarm_ldap_server = NULL; static pid_t gfarm_ldap_client_pid; static int gfarm_ldap_shared; void gfarm_metadb_share_connection(void) { gfarm_ldap_shared = 1; } char * gfarm_metadb_initialize(void) { int rv; int port; char *e; if (gfarm_ldap_server_name == NULL) return ("gfarm.conf: ldap_serverhost is missing"); if (gfarm_ldap_server_port == NULL) return ("gfarm.conf: ldap_serverport is missing"); port = strtol(gfarm_ldap_server_port, &e, 0); if (e == gfarm_ldap_server_port || port <= 0 || port >= 65536) return ("gfarm.conf: ldap_serverport: " "illegal value"); if (gfarm_ldap_base_dn == NULL) return ("gfarm.conf: ldap_base_dn is missing"); /* * initialize LDAP */ /* open a connection */ gfarm_ldap_server = ldap_init(gfarm_ldap_server_name, port); if (gfarm_ldap_server == NULL) { switch (errno) { case EHOSTUNREACH: return ("gfarm meta-db ldap_serverhost " "access failed"); case ECONNREFUSED: return ("gfarm meta-db ldap_serverport " "connection refused"); default: return ("gfarm meta-db ldap_server " "access failed"); /*return (strerror(errno));*/ } } /* authenticate as nobody */ rv = ldap_simple_bind_s(gfarm_ldap_server, NULL, NULL); if (rv == LDAP_PROTOCOL_ERROR) { /* Try the version 3 */ int version = LDAP_VERSION3; ldap_set_option(gfarm_ldap_server, LDAP_OPT_PROTOCOL_VERSION, &version); rv = ldap_simple_bind_s(gfarm_ldap_server, NULL, NULL); } if (rv != LDAP_SUCCESS) { (void)gfarm_metadb_terminate(); return (ldap_err2string(rv)); } /* sanity check. base_dn can be accessed? */ e = gfarm_metadb_check(); if (e != NULL) { (void)gfarm_metadb_terminate(); return (e); } gfarm_ldap_client_pid = getpid(); return (NULL); } char * gfarm_metadb_terminate(void) { int rv; char *e = NULL; if (gfarm_ldap_server == NULL) return ("metadb connection already disconnected"); /* close and free connection resources */ if (gfarm_ldap_shared || getpid() == gfarm_ldap_client_pid) { rv = ldap_unbind(gfarm_ldap_server); if (rv != LDAP_SUCCESS) e = ldap_err2string(rv); } gfarm_ldap_server = NULL; gfarm_ldap_client_pid = 0; return (e); } char * gfarm_metadb_check(void) { int rv; LDAPMessage *res; if (gfarm_ldap_server == NULL) return ("metadb connection already disconnected"); rv = ldap_search_s(gfarm_ldap_server, gfarm_ldap_base_dn, LDAP_SCOPE_BASE, "objectclass=top", NULL, 0, &res); if (rv != LDAP_SUCCESS) { if (rv == LDAP_SERVER_DOWN) return ("can't contact gfarm meta-db server"); if (rv == LDAP_NO_SUCH_OBJECT) return ("gfarm meta-db ldap_base_dn not found"); return ("gfarm meta-db ldap_base_dn access failed"); } ldap_msgfree(res); return (NULL); } /* * LDAP connection cannot be used from forked children unless the * connection is ensured to be used exclusively. * This routine guarantees that never happens. */ static char * gfarm_ldap_check(void) { if (gfarm_ldap_shared || getpid() == gfarm_ldap_client_pid) return (NULL); /* XXX close the file descriptor for gfarm_ldap_server */ gfarm_ldap_server = NULL; gfarm_ldap_client_pid = 0; return (gfarm_metadb_initialize()); } /**********************************************************************/ struct ldap_string_modify { LDAPMod mod; char *str[2]; }; static void set_string_mod( LDAPMod **modp, int op, char *type, char *value, struct ldap_string_modify *storage) { storage->str[0] = value; storage->str[1] = NULL; storage->mod.mod_op = op; storage->mod.mod_type = type; storage->mod.mod_vals.modv_strvals = storage->str; *modp = &storage->mod; } #if 0 static void set_delete_mod( LDAPMod **modp, char *type, LDAPMod *storage) { storage->mod_op = LDAP_MOD_DELETE; storage->mod_type = type; storage->mod_vals.modv_strvals = NULL; *modp = storage; } #endif struct gfarm_generic_info_ops { size_t info_size; char *query_type; char *dn_template; char *(*make_dn)(void *key); void (*clear)(void *info); void (*set_field)(void *info, char *attribute, char **vals); int (*validate)(void *info); void (*free)(void *info); }; char * gfarm_generic_info_get( void *key, void *info, const struct gfarm_generic_info_ops *ops) { LDAPMessage *res, *e; int n, rv; char *a; BerElement *ber; char **vals; char *dn = ops->make_dn(key); char *error; if (dn == NULL) return (GFARM_ERR_NO_MEMORY); if ((error = gfarm_ldap_check()) != NULL) return (error); rv = ldap_search_s(gfarm_ldap_server, dn, LDAP_SCOPE_BASE, ops->query_type, NULL, 0, &res); free(dn); if (rv != LDAP_SUCCESS) { if (rv == LDAP_NO_SUCH_OBJECT) return (GFARM_ERR_NO_SUCH_OBJECT); return (ldap_err2string(rv)); } n = ldap_count_entries(gfarm_ldap_server, res); if (n == 0) { /* free the search results */ ldap_msgfree(res); return (GFARM_ERR_NO_SUCH_OBJECT); } ops->clear(info); e = ldap_first_entry(gfarm_ldap_server, res); ber = NULL; for (a = ldap_first_attribute(gfarm_ldap_server, e, &ber); a != NULL; a = ldap_next_attribute(gfarm_ldap_server, e, ber)) { vals = ldap_get_values(gfarm_ldap_server, e, a); if (vals[0] != NULL) ops->set_field(info, a, vals); ldap_value_free(vals); ldap_memfree(a); } if (ber != NULL) ber_free(ber, 0); /* free the search results */ ldap_msgfree(res); /* should check all fields are filled */ if (!ops->validate(info)) { ops->free(info); /* XXX - different error code is better ? */ return (GFARM_ERR_NO_SUCH_OBJECT); } return (NULL); /* success */ } char * gfarm_generic_info_set( void *key, LDAPMod **modv, const struct gfarm_generic_info_ops *ops) { int rv; char *dn = ops->make_dn(key); char *error; if (dn == NULL) return (GFARM_ERR_NO_MEMORY); if ((error = gfarm_ldap_check()) != NULL) return (error); rv = ldap_add_s(gfarm_ldap_server, dn, modv); free(dn); if (rv != LDAP_SUCCESS) { if (rv == LDAP_ALREADY_EXISTS) return (GFARM_ERR_ALREADY_EXISTS); return (ldap_err2string(rv)); } return (NULL); } char * gfarm_generic_info_modify( void *key, LDAPMod **modv, const struct gfarm_generic_info_ops *ops) { int rv; char *dn = ops->make_dn(key); char *error; if (dn == NULL) return (GFARM_ERR_NO_MEMORY); if ((error = gfarm_ldap_check()) != NULL) return (error); rv = ldap_modify_s(gfarm_ldap_server, dn, modv); free(dn); switch (rv) { case LDAP_SUCCESS: return (NULL); case LDAP_NO_SUCH_OBJECT: return (GFARM_ERR_NO_SUCH_OBJECT); case LDAP_ALREADY_EXISTS: return (GFARM_ERR_ALREADY_EXISTS); default: return (ldap_err2string(rv)); } } char * gfarm_generic_info_remove( void *key, const struct gfarm_generic_info_ops *ops) { int rv; char *dn = ops->make_dn(key); char *error; if (dn == NULL) return (GFARM_ERR_NO_MEMORY); if ((error = gfarm_ldap_check()) != NULL) return (error); rv = ldap_delete_s(gfarm_ldap_server, dn); free(dn); if (rv != LDAP_SUCCESS) { if (rv == LDAP_NO_SUCH_OBJECT) return (GFARM_ERR_NO_SUCH_OBJECT); return (ldap_err2string(rv)); } return (NULL); } void gfarm_generic_info_free_all( int n, void *vinfos, const struct gfarm_generic_info_ops *ops) { int i; char *infos = vinfos; for (i = 0; i < n; i++) { ops->free(infos); infos += ops->info_size; } free(vinfos); } char * gfarm_generic_info_get_all( char *dn, int scope, /* LDAP_SCOPE_ONELEVEL or LDAP_SCOPE_SUBTREE */ char *query, int *np, void *infosp, const struct gfarm_generic_info_ops *ops) { LDAPMessage *res, *e; int i, n, rv; char *a; BerElement *ber; char **vals; char *infos, *tmp_info; char *error; if ((error = gfarm_ldap_check()) != NULL) return (error); /* search for entries, return all attrs */ rv = ldap_search_s(gfarm_ldap_server, dn, scope, query, NULL, 0, &res); if (rv != LDAP_SUCCESS) { if (rv == LDAP_NO_SUCH_OBJECT) return (GFARM_ERR_NO_SUCH_OBJECT); return (ldap_err2string(rv)); } n = ldap_count_entries(gfarm_ldap_server, res); if (n == 0) { /* free the search results */ ldap_msgfree(res); return (GFARM_ERR_NO_SUCH_OBJECT); } infos = malloc(ops->info_size * n); if (infos == NULL) { /* free the search results */ ldap_msgfree(res); return (GFARM_ERR_NO_MEMORY); } /* use last element as temporary buffer */ tmp_info = infos + ops->info_size * (n - 1); /* step through each entry returned */ for (i = 0, e = ldap_first_entry(gfarm_ldap_server, res); e != NULL; e = ldap_next_entry(gfarm_ldap_server, e)) { ops->clear(tmp_info); ber = NULL; for (a = ldap_first_attribute(gfarm_ldap_server, e, &ber); a != NULL; a = ldap_next_attribute(gfarm_ldap_server, e, ber)) { vals = ldap_get_values(gfarm_ldap_server, e, a); if (vals[0] != NULL) ops->set_field(tmp_info, a, vals); ldap_value_free(vals); ldap_memfree(a); } if (ber != NULL) ber_free(ber, 0); if (!ops->validate(tmp_info)) { /* invalid record */ ops->free(tmp_info); continue; } if (i < n - 1) { /* if (i == n - 1), do not have to copy */ memcpy(infos + ops->info_size * i, tmp_info, ops->info_size); } i++; } /* free the search results */ ldap_msgfree(res); if (i == 0) { free(infos); /* XXX - data were all invalid */ return (GFARM_ERR_NO_SUCH_OBJECT); } /* XXX - if (i < n), element from (i+1) to (n-1) may be wasted */ *np = i; *(char **)infosp = infos; return (NULL); } /* XXX - this is for a stopgap implementation of gfs_opendir() */ char * gfarm_generic_info_get_foreach( char *dn, int scope, /* LDAP_SCOPE_ONELEVEL or LDAP_SCOPE_SUBTREE */ char *query, void *tmp_info, /* just used as a work area */ void (*callback)(void *, void *), void *closure, const struct gfarm_generic_info_ops *ops) { LDAPMessage *res, *e; int i, msgid, rv; char *a; BerElement *ber; char **vals; char *error; if ((error = gfarm_ldap_check()) != NULL) return (error); /* search for entries asynchronously */ msgid = ldap_search(gfarm_ldap_server, dn, scope, query, NULL, 0); if (msgid == -1) return ("ldap_search: error"); /* step through each entry returned */ i = 0; while ((rv = ldap_result(gfarm_ldap_server, msgid, LDAP_MSG_ONE, NULL, &res)) > 0) { e = ldap_first_entry(gfarm_ldap_server, res); if (e == NULL) { ldap_msgfree(res); break; } for (; e != NULL; e = ldap_next_entry(gfarm_ldap_server, e)) { ops->clear(tmp_info); ber = NULL; for (a = ldap_first_attribute( gfarm_ldap_server, e, &ber); a != NULL; a = ldap_next_attribute( gfarm_ldap_server, e, ber)) { vals = ldap_get_values(gfarm_ldap_server, e, a); if (vals[0] != NULL) ops->set_field(tmp_info, a, vals); ldap_value_free(vals); ldap_memfree(a); } if (ber != NULL) ber_free(ber, 0); if (!ops->validate(tmp_info)) { /* invalid record */ ops->free(tmp_info); continue; } (*callback)(closure, tmp_info); ops->free(tmp_info); i++; } /* free the search results */ ldap_msgfree(res); } if (rv == -1) return ("ldap_result: error"); if (i == 0) return (GFARM_ERR_NO_SUCH_OBJECT); return (NULL); } /**********************************************************************/ static char *gfarm_host_info_make_dn(void *vkey); static void gfarm_host_info_clear(void *info); static void gfarm_host_info_set_field(void *info, char *attribute, char **vals); static int gfarm_host_info_validate(void *info); struct gfarm_host_info_key { const char *hostname; }; static const struct gfarm_generic_info_ops gfarm_host_info_ops = { sizeof(struct gfarm_host_info), "(objectclass=GFarmHost)", "hostname=%s, %s", gfarm_host_info_make_dn, gfarm_host_info_clear, gfarm_host_info_set_field, gfarm_host_info_validate, (void (*)(void *))gfarm_host_info_free, }; static char * gfarm_host_info_make_dn(void *vkey) { struct gfarm_host_info_key *key = vkey; char *dn = malloc(strlen(gfarm_host_info_ops.dn_template) + strlen(key->hostname) + strlen(gfarm_ldap_base_dn) + 1); if (dn == NULL) return (NULL); sprintf(dn, gfarm_host_info_ops.dn_template, key->hostname, gfarm_ldap_base_dn); return (dn); } static void gfarm_host_info_clear(void *vinfo) { struct gfarm_host_info *info = vinfo; memset(info, 0, sizeof(*info)); #if 0 info->ncpu = GFARM_HOST_INFO_NCPU_NOT_SET; #else info->ncpu = 1; /* assume 1 CPU by default */ #endif } static void gfarm_host_info_set_field( void *vinfo, char *attribute, char **vals) { struct gfarm_host_info *info = vinfo; if (strcasecmp(attribute, "hostname") == 0) { info->hostname = strdup(vals[0]); } else if (strcasecmp(attribute, "hostalias") == 0) { info->hostaliases = gfarm_strarray_dup(vals); info->nhostaliases = info->hostaliases == NULL ? 0 : gfarm_strarray_length(info->hostaliases); } else if (strcasecmp(attribute, "architecture") == 0) { info->architecture = strdup(vals[0]); } else if (strcasecmp(attribute, "ncpu") == 0) { info->ncpu = strtol(vals[0], NULL, 0); } } static int gfarm_host_info_validate(void *vinfo) { struct gfarm_host_info *info = vinfo; /* info->hostaliases may be NULL */ return ( info->hostname != NULL && info->architecture != NULL && info->ncpu != GFARM_HOST_INFO_NCPU_NOT_SET ); } void gfarm_host_info_free( struct gfarm_host_info *info) { if (info->hostname != NULL) free(info->hostname); if (info->hostaliases != NULL) { gfarm_strarray_free(info->hostaliases); info->nhostaliases = 0; } if (info->architecture != NULL) free(info->architecture); /* * if implementation of this function is changed, * implementation of gfarm_host_info_get_architecture_by_host() * should be changed, too. */ } char *gfarm_host_info_get( const char *hostname, struct gfarm_host_info *info) { struct gfarm_host_info_key key; key.hostname = hostname; return (gfarm_generic_info_get(&key, info, &gfarm_host_info_ops)); } static char * gfarm_host_info_update( char *hostname, struct gfarm_host_info *info, int mod_op, char *(*update_op)(void *, LDAPMod **, const struct gfarm_generic_info_ops *)) { int i; LDAPMod *modv[6]; struct ldap_string_modify storage[ARRAY_LENGTH(modv) - 1]; char ncpu_string[INT32STRLEN + 1]; LDAPMod hostaliases_mod; struct gfarm_host_info_key key; key.hostname = hostname; /* * `info->hostname' doesn't have to be set, * because this function uses its argument instead. */ sprintf(ncpu_string, "%d", info->ncpu); i = 0; set_string_mod(&modv[i], mod_op, "objectclass", "GFarmHost", &storage[i]); i++; set_string_mod(&modv[i], mod_op, "hostname", hostname, &storage[i]); i++; /* "hostalias" is optional */ if (info->hostaliases != NULL && info->nhostaliases > 0) { hostaliases_mod.mod_type = "hostalias"; hostaliases_mod.mod_op = mod_op; hostaliases_mod.mod_vals.modv_strvals = info->hostaliases; modv[i] = &hostaliases_mod; i++; } set_string_mod(&modv[i], mod_op, "architecture", info->architecture, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "ncpu", ncpu_string, &storage[i]); i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv) || i == ARRAY_LENGTH(modv) - 1); return ((*update_op)(&key, modv, &gfarm_host_info_ops)); } char * gfarm_host_info_remove_hostaliases(const char *hostname) { int i; LDAPMod *modv[2]; LDAPMod hostaliases_mod; struct gfarm_host_info_key key; key.hostname = hostname; i = 0; hostaliases_mod.mod_type = "hostalias"; hostaliases_mod.mod_op = LDAP_MOD_DELETE; hostaliases_mod.mod_vals.modv_strvals = NULL; modv[i] = &hostaliases_mod; i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv)); return (gfarm_generic_info_modify(&key, modv, &gfarm_host_info_ops)); } char * gfarm_host_info_set( char *hostname, struct gfarm_host_info *info) { return (gfarm_host_info_update(hostname, info, LDAP_MOD_ADD, gfarm_generic_info_set)); } char * gfarm_host_info_replace( char *hostname, struct gfarm_host_info *info) { return (gfarm_host_info_update(hostname, info, LDAP_MOD_REPLACE, gfarm_generic_info_modify)); } char * gfarm_host_info_remove(const char *hostname) { struct gfarm_host_info_key key; key.hostname = hostname; return (gfarm_generic_info_remove(&key, &gfarm_host_info_ops)); } void gfarm_host_info_free_all( int n, struct gfarm_host_info *infos) { gfarm_generic_info_free_all(n, infos, &gfarm_host_info_ops); } char * gfarm_host_info_get_all( int *np, struct gfarm_host_info **infosp) { char *error; int n; struct gfarm_host_info *infos; error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, gfarm_host_info_ops.query_type, &n, &infos, &gfarm_host_info_ops); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } char * gfarm_host_info_get_by_name_alias( const char *name_alias, struct gfarm_host_info *info) { char *error; int n; struct gfarm_host_info *infos; static char query_template[] = "(&(objectclass=GFarmHost)(|(hostname=%s)(hostalias=%s)))"; char *query = malloc(sizeof(query_template) + strlen(name_alias) * 2); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, name_alias, name_alias); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, query, &n, &infos, &gfarm_host_info_ops); free(query); if (error != NULL) { if (error == GFARM_ERR_NO_SUCH_OBJECT) return (GFARM_ERR_UNKNOWN_HOST); return (error); } if (n != 1) { gfarm_host_info_free_all(n, infos); return (GFARM_ERR_AMBIGUOUS_RESULT); } *info = infos[0]; return (NULL); } char * gfarm_host_info_get_allhost_by_architecture(const char *architecture, int *np, struct gfarm_host_info **infosp) { char *error; int n; struct gfarm_host_info *infos; static char query_template[] = "(&(objectclass=GFarmHost)(architecture=%s))"; char *query = malloc(sizeof(query_template) + strlen(architecture)); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, architecture); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, query, &n, &infos, &gfarm_host_info_ops); free(query); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } char * gfarm_host_info_get_architecture_by_host(const char *hostname) { char *error; struct gfarm_host_info info; error = gfarm_host_info_get(hostname, &info); if (error != NULL) return (NULL); /* free info except info.architecture */ free(info.hostname); if (info.hostaliases != NULL) { gfarm_strarray_free(info.hostaliases); info.nhostaliases = 0; } return (info.architecture); } /**********************************************************************/ static char *gfarm_path_info_make_dn(void *vkey); static void gfarm_path_info_clear(void *info); static void gfarm_path_info_set_field(void *info, char *attribute, char **vals); static int gfarm_path_info_validate(void *info); struct gfarm_path_info; struct gfarm_path_info_key { const char *pathname; }; static int gfarm_metadb_ldap_need_escape(char c) { switch (c) { case ',': case '+': case '"': case '\\': case '<': case '>': case ';': return (1); } return (0); } static char * gfarm_metadb_ldap_escape_pathname(const char *pathname) { const char *s = pathname; char *escaped_pathname, *d; /* if pathname is a null string, return immediately */ if (*s == '\0') return (NULL); escaped_pathname = malloc(strlen(pathname) * 3); if (escaped_pathname == NULL) return (escaped_pathname); d = escaped_pathname; /* Escape the first character; ' ', '#', and need_escape(). */ if (*s == ' ' || *s == '#' || gfarm_metadb_ldap_need_escape(*s)) *d++ = '\\'; *d++ = *s++; while (*s) { if (gfarm_metadb_ldap_need_escape(*s) || (*s == ' ' && d[-1] == ' ')) *d++ = '\\'; *d++ = *s++; } /* * Escape the last 'space' character. pathname should have a * length of more than 1. If d[-1] == ' ', it should have a * length more than 2. */ if (d[-1] == ' ' && d[-2] != '\\') { d[-1] = '\\'; *d++ = ' '; } *d = '\0'; return (escaped_pathname); } static const struct gfarm_generic_info_ops gfarm_path_info_ops = { sizeof(struct gfarm_path_info), "(objectclass=GFarmPath)", "pathname=%s, %s", gfarm_path_info_make_dn, gfarm_path_info_clear, gfarm_path_info_set_field, gfarm_path_info_validate, (void (*)(void *))gfarm_path_info_free, }; static char * gfarm_path_info_make_dn(void *vkey) { struct gfarm_path_info_key *key = vkey; char *escaped_pathname, *dn; escaped_pathname = gfarm_metadb_ldap_escape_pathname(key->pathname); if (escaped_pathname == NULL) return (NULL); dn = malloc(strlen(gfarm_path_info_ops.dn_template) + strlen(escaped_pathname) + strlen(gfarm_ldap_base_dn) + 1); if (dn == NULL) { free(escaped_pathname); return (NULL); } sprintf(dn, gfarm_path_info_ops.dn_template, escaped_pathname, gfarm_ldap_base_dn); free(escaped_pathname); return (dn); } static void gfarm_path_info_clear(void *vinfo) { struct gfarm_path_info *info = vinfo; memset(info, 0, sizeof(*info)); } static void gfarm_path_info_set_field( void *vinfo, char *attribute, char **vals) { struct gfarm_path_info *info = vinfo; /* XXX - info->status.st_ino is set not here but at upper level */ if (strcasecmp(attribute, "pathname") == 0) { info->pathname = strdup(vals[0]); } else if (strcasecmp(attribute, "mode") == 0) { info->status.st_mode = strtol(vals[0], NULL, 8); } else if (strcasecmp(attribute, "user") == 0) { info->status.st_user = strdup(vals[0]); } else if (strcasecmp(attribute, "group") == 0) { info->status.st_group = strdup(vals[0]); } else if (strcasecmp(attribute, "atimesec") == 0) { info->status.st_atimespec.tv_sec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "atimensec") == 0) { info->status.st_atimespec.tv_nsec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "mtimesec") == 0) { info->status.st_mtimespec.tv_sec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "mtimensec") == 0) { info->status.st_mtimespec.tv_nsec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "ctimesec") == 0) { info->status.st_ctimespec.tv_sec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "ctimensec") == 0) { info->status.st_ctimespec.tv_nsec = strtol(vals[0], NULL, 0); } else if (strcasecmp(attribute, "nsections") == 0) { info->status.st_nsections = strtol(vals[0], NULL, 0); } } static int gfarm_path_info_validate(void *vinfo) { struct gfarm_path_info *info = vinfo; /* XXX - should check all fields are filled */ return ( info->pathname != NULL && info->status.st_user != NULL && info->status.st_group != NULL ); } static char * gfarm_path_info_update( char *pathname, struct gfarm_path_info *info, int mod_op, char *(*update_op)(void *, LDAPMod **, const struct gfarm_generic_info_ops *)) { int i; LDAPMod *modv[13]; struct ldap_string_modify storage[ARRAY_LENGTH(modv) - 1]; char mode_string[INT32STRLEN + 1]; char atimespec_sec_string[INT32STRLEN + 1]; char atimespec_nsec_string[INT32STRLEN + 1]; char mtimespec_sec_string[INT32STRLEN + 1]; char mtimespec_nsec_string[INT32STRLEN + 1]; char ctimespec_sec_string[INT32STRLEN + 1]; char ctimespec_nsec_string[INT32STRLEN + 1]; char nsections_string[INT32STRLEN + 1]; struct gfarm_path_info_key key; key.pathname = pathname; /* * `info->pathname' doesn't have to be set, * because this function uses its argument instead. */ sprintf(mode_string, "%07o", info->status.st_mode); sprintf(atimespec_sec_string, "%d", info->status.st_atimespec.tv_sec); sprintf(atimespec_nsec_string, "%d", info->status.st_atimespec.tv_nsec); sprintf(mtimespec_sec_string, "%d", info->status.st_mtimespec.tv_sec); sprintf(mtimespec_nsec_string, "%d", info->status.st_mtimespec.tv_nsec); sprintf(ctimespec_sec_string, "%d", info->status.st_ctimespec.tv_sec); sprintf(ctimespec_nsec_string, "%d", info->status.st_ctimespec.tv_nsec); sprintf(nsections_string, "%d", info->status.st_nsections); i = 0; set_string_mod(&modv[i], mod_op, "objectclass", "GFarmPath", &storage[i]); i++; set_string_mod(&modv[i], mod_op, "pathname", pathname, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "mode", mode_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "user", info->status.st_user, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "group", info->status.st_group, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "atimesec", atimespec_sec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "atimensec", atimespec_nsec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "mtimesec", mtimespec_sec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "mtimensec", mtimespec_nsec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "ctimesec", ctimespec_sec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "ctimensec", ctimespec_nsec_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "nsections", nsections_string, &storage[i]); i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv)); return ((*update_op)(&key, modv, &gfarm_path_info_ops)); } void gfarm_path_info_free( struct gfarm_path_info *info) { if (info->pathname != NULL) free(info->pathname); if (info->status.st_user != NULL) free(info->status.st_user); if (info->status.st_group != NULL) free(info->status.st_group); } char * gfarm_metadb_path_info_get( const char *pathname, struct gfarm_path_info *info) { struct gfarm_path_info_key key; /* * This case intends to investigate the root directory. Because * Gfarm-1.0.x does not have an entry for the root directory, and * moreover, because OpenLDAP-2.1.X does not accept a dn such as * 'pathname=, dc=xxx', return immediately with an error. */ if (pathname[0] == '\0') return (GFARM_ERR_NO_SUCH_OBJECT); else key.pathname = pathname; return (gfarm_generic_info_get(&key, info, &gfarm_path_info_ops)); } char * gfarm_metadb_path_info_set( char *pathname, struct gfarm_path_info *info) { return (gfarm_path_info_update(pathname, info, LDAP_MOD_ADD, gfarm_generic_info_set)); } char * gfarm_metadb_path_info_replace( char *pathname, struct gfarm_path_info *info) { return (gfarm_path_info_update(pathname, info, LDAP_MOD_REPLACE, gfarm_generic_info_modify)); } char * gfarm_metadb_path_info_remove(const char *pathname) { struct gfarm_path_info_key key; key.pathname = pathname; return (gfarm_generic_info_remove(&key, &gfarm_path_info_ops)); } void gfarm_path_info_free_all( int n, struct gfarm_path_info *infos) { gfarm_generic_info_free_all(n, infos, &gfarm_path_info_ops); } char * gfarm_path_info_get_all( int *np, struct gfarm_path_info **infosp) { char *error; int n; struct gfarm_path_info *infos; error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, gfarm_path_info_ops.query_type, &n, &infos, &gfarm_path_info_ops); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } /* XXX - this is for a stopgap implementation of gfs_opendir() */ char * gfarm_path_info_get_all_foreach( void (*callback)(void *, struct gfarm_path_info *), void *closure) { struct gfarm_path_info tmp_info; return (gfarm_generic_info_get_foreach(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, gfarm_path_info_ops.query_type, &tmp_info, /*XXX*/(void (*)(void *, void *))callback, closure, &gfarm_path_info_ops)); } void gfarm_file_history_free_allfile(int n, char **v) { gfarm_path_info_free_all(n, (struct gfarm_path_info *)v); } /* get GFarmFiles which were created by the program */ char * gfarm_file_history_get_allfile_by_program( char *program, int *np, char ***gfarm_files_p) { char *error; int n; struct gfarm_path_info *infos; static char query_template[] = "(&(objectclass=GFarmFile)(generatorProgram=%s))"; char *query = malloc(sizeof(query_template) + strlen(program)); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, program); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, query, &n, &infos, &gfarm_path_info_ops); free(query); if (error != NULL) return (error); *np = n; *gfarm_files_p = (char **)infos; return (NULL); } /* get GFarmFiles which were created from the file as a input */ char * gfarm_file_history_get_allfile_by_file( char *input_gfarm_file, int *np, char ***gfarm_files_p) { char *error; int n; struct gfarm_path_info *infos; static char query_template[] = "(&(objectclass=GFarmFile)(generatorInputGFarmFiles=%s))"; char *query = malloc(sizeof(query_template) + strlen(input_gfarm_file)); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, input_gfarm_file); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_ONELEVEL, query, &n, &infos, &gfarm_path_info_ops); free(query); if (error != NULL) return (error); *np = n; *gfarm_files_p = (char **)infos; return (NULL); } /**********************************************************************/ static char *gfarm_file_section_info_make_dn(void *vkey); static void gfarm_file_section_info_clear(void *info); static void gfarm_file_section_info_set_field(void *info, char *attribute, char **vals); static int gfarm_file_section_info_validate(void *info); struct gfarm_file_section_info_key { const char *pathname; const char *section; }; static const struct gfarm_generic_info_ops gfarm_file_section_info_ops = { sizeof(struct gfarm_file_section_info), "(objectclass=GFarmFileSection)", "section=%s, pathname=%s, %s", gfarm_file_section_info_make_dn, gfarm_file_section_info_clear, gfarm_file_section_info_set_field, gfarm_file_section_info_validate, (void (*)(void *))gfarm_file_section_info_free, }; static char * gfarm_file_section_info_make_dn(void *vkey) { struct gfarm_file_section_info_key *key = vkey; char *escaped_pathname, *dn; escaped_pathname = gfarm_metadb_ldap_escape_pathname(key->pathname); if (escaped_pathname == NULL) return (NULL); dn = malloc(strlen(gfarm_file_section_info_ops.dn_template) + strlen(key->section) + strlen(escaped_pathname) + strlen(gfarm_ldap_base_dn) + 1); if (dn == NULL) { free(escaped_pathname); return (NULL); } sprintf(dn, gfarm_file_section_info_ops.dn_template, key->section, escaped_pathname, gfarm_ldap_base_dn); free(escaped_pathname); return (dn); } static void gfarm_file_section_info_clear(void *vinfo) { struct gfarm_file_section_info *info = vinfo; memset(info, 0, sizeof(*info)); } static void gfarm_file_section_info_set_field( void *vinfo, char *attribute, char **vals) { struct gfarm_file_section_info *info = vinfo; if (strcasecmp(attribute, "pathname") == 0) { info->pathname = strdup(vals[0]); } else if (strcasecmp(attribute, "section") == 0) { info->section = strdup(vals[0]); } else if (strcasecmp(attribute, "filesize") == 0) { info->filesize = string_to_file_offset(vals[0], NULL); } else if (strcasecmp(attribute, "checksumType") == 0) { info->checksum_type = strdup(vals[0]); } else if (strcasecmp(attribute, "checksum") == 0) { info->checksum = strdup(vals[0]); } } static int gfarm_file_section_info_validate(void *vinfo) { struct gfarm_file_section_info *info = vinfo; /* XXX - should check all fields are filled */ return ( info->section != NULL ); } void gfarm_file_section_info_free(struct gfarm_file_section_info *info) { if (info->pathname != NULL) free(info->pathname); if (info->section != NULL) free(info->section); if (info->checksum_type != NULL) free(info->checksum_type); if (info->checksum != NULL) free(info->checksum); } char *gfarm_file_section_info_get( const char *pathname, const char *section, struct gfarm_file_section_info *info) { struct gfarm_file_section_info_key key; key.pathname = pathname; key.section = section; return (gfarm_generic_info_get(&key, info, &gfarm_file_section_info_ops)); } static char * gfarm_file_section_info_update( char *pathname, char *section, struct gfarm_file_section_info *info, int mod_op, char *(*update_op)(void *, LDAPMod **, const struct gfarm_generic_info_ops *)) { int i; LDAPMod *modv[7]; struct ldap_string_modify storage[ARRAY_LENGTH(modv) - 1]; char filesize_string[INT64STRLEN + 1]; struct gfarm_file_section_info_key key; key.pathname = pathname; key.section = section; /* * `info->section' doesn't have to be set, * because this function uses its argument instead. */ sprintf(filesize_string, "%" PR_FILE_OFFSET, CAST_PR_FILE_OFFSET info->filesize); i = 0; set_string_mod(&modv[i], mod_op, "objectclass", "GFarmFileSection", &storage[i]); i++; set_string_mod(&modv[i], mod_op, "pathname", pathname, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "section", section, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "filesize", filesize_string, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "checksumType", info->checksum_type, &storage[i]); i++; set_string_mod(&modv[i], mod_op, "checksum", info->checksum, &storage[i]); i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv)); return ((*update_op)(&key, modv, &gfarm_file_section_info_ops)); } char * gfarm_file_section_info_set( char *pathname, char *section, struct gfarm_file_section_info *info) { return (gfarm_file_section_info_update(pathname, section, info, LDAP_MOD_ADD, gfarm_generic_info_set)); } char * gfarm_file_section_info_replace( char *pathname, char *section, struct gfarm_file_section_info *info) { return (gfarm_file_section_info_update(pathname, section, info, LDAP_MOD_REPLACE, gfarm_generic_info_modify)); } char * gfarm_file_section_info_remove( const char *pathname, const char *section) { struct gfarm_file_section_info_key key; key.pathname = pathname; key.section = section; return (gfarm_generic_info_remove(&key, &gfarm_file_section_info_ops)); } void gfarm_file_section_info_free_all( int n, struct gfarm_file_section_info *infos) { gfarm_generic_info_free_all(n, infos, &gfarm_file_section_info_ops); } char * gfarm_file_section_info_get_all_by_file( const char *pathname, int *np, struct gfarm_file_section_info **infosp) { char *error; int n; struct gfarm_file_section_info *infos; static char dn_template[] = "pathname=%s, %s"; char *escaped_pathname, *dn; escaped_pathname = gfarm_metadb_ldap_escape_pathname(pathname); if (escaped_pathname == NULL) return (NULL); dn = malloc(sizeof(dn_template) + strlen(escaped_pathname) + strlen(gfarm_ldap_base_dn)); if (dn == NULL) { free(escaped_pathname); return (NULL); } sprintf(dn, dn_template, escaped_pathname, gfarm_ldap_base_dn); free(escaped_pathname); error = gfarm_generic_info_get_all(dn, LDAP_SCOPE_ONELEVEL, gfarm_file_section_info_ops.query_type, &n, &infos, &gfarm_file_section_info_ops); free(dn); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } static int gfarm_file_section_info_compare_serial(const void *d, const void *s) { const struct gfarm_file_section_info *df = d, *sf = s; return (atoi(df->section) - atoi(sf->section)); } char * gfarm_file_section_info_get_sorted_all_serial_by_file( const char *pathname, int *np, struct gfarm_file_section_info **infosp) { int n; struct gfarm_file_section_info *infos; char *error = gfarm_file_section_info_get_all_by_file( pathname, &n, &infos); if (error != NULL) return (error); qsort(infos, n, sizeof(infos[0]), gfarm_file_section_info_compare_serial); *np = n; *infosp = infos; return (NULL); } char * gfarm_file_section_info_remove_all_by_file(const char *pathname) { char *error, *error_save; int i, n; struct gfarm_file_section_info *infos; error = gfarm_file_section_info_get_all_by_file(pathname, &n, &infos); if (error != NULL) { if (error == GFARM_ERR_NO_SUCH_OBJECT) return (NULL); return (error); } /* * remove GfarmFileSection's */ error_save = NULL; for (i = 0; i < n; i++) { error = gfarm_file_section_info_remove(pathname, infos[i].section); if (error != NULL && error != GFARM_ERR_NO_SUCH_OBJECT) error_save = error; } gfarm_file_section_info_free_all(n, infos); /* XXX - do not remove parent GFarmPath here */ return (error_save); } int gfarm_file_section_info_does_exist( const char *pathname, const char *section) { struct gfarm_file_section_info info; if (gfarm_file_section_info_get(pathname, section, &info) != NULL) return (0); gfarm_file_section_info_free(&info); return (1); } /**********************************************************************/ static char *gfarm_file_section_copy_info_make_dn(void *vkey); static void gfarm_file_section_copy_info_clear(void *info); static void gfarm_file_section_copy_info_set_field(void *info, char *attribute, char **vals); static int gfarm_file_section_copy_info_validate(void *info); struct gfarm_file_section_copy_info_key { const char *pathname; const char *section; const char *hostname; }; static const struct gfarm_generic_info_ops gfarm_file_section_copy_info_ops = { sizeof(struct gfarm_file_section_copy_info), "(objectclass=GFarmFileSectionCopy)", "hostname=%s, section=%s, pathname=%s, %s", gfarm_file_section_copy_info_make_dn, gfarm_file_section_copy_info_clear, gfarm_file_section_copy_info_set_field, gfarm_file_section_copy_info_validate, (void (*)(void *))gfarm_file_section_copy_info_free, }; static char * gfarm_file_section_copy_info_make_dn(void *vkey) { struct gfarm_file_section_copy_info_key *key = vkey; char *escaped_pathname, *dn; escaped_pathname = gfarm_metadb_ldap_escape_pathname(key->pathname); if (escaped_pathname == NULL) return (NULL); dn = malloc(strlen(gfarm_file_section_copy_info_ops.dn_template) + strlen(key->hostname) + strlen(key->section) + strlen(escaped_pathname) + strlen(gfarm_ldap_base_dn) + 1); if (dn == NULL) { free(escaped_pathname); return (NULL); } sprintf(dn, gfarm_file_section_copy_info_ops.dn_template, key->hostname, key->section, escaped_pathname, gfarm_ldap_base_dn); free(escaped_pathname); return (dn); } static void gfarm_file_section_copy_info_clear(void *vinfo) { struct gfarm_file_section_copy_info *info = vinfo; memset(info, 0, sizeof(*info)); } static void gfarm_file_section_copy_info_set_field( void *vinfo, char *attribute, char **vals) { struct gfarm_file_section_copy_info *info = vinfo; if (strcasecmp(attribute, "pathname") == 0) { info->pathname = strdup(vals[0]); } else if (strcasecmp(attribute, "section") == 0) { info->section = strdup(vals[0]); } else if (strcasecmp(attribute, "hostname") == 0) { info->hostname = strdup(vals[0]); } } static int gfarm_file_section_copy_info_validate(void *vinfo) { struct gfarm_file_section_copy_info *info = vinfo; return ( info->pathname != NULL && info->section != NULL && info->hostname != NULL ); } void gfarm_file_section_copy_info_free(struct gfarm_file_section_copy_info *info) { if (info->pathname != NULL) free(info->pathname); if (info->section != NULL) free(info->section); if (info->hostname != NULL) free(info->hostname); } char * gfarm_file_section_copy_info_get( const char *pathname, const char *section, const char *hostname, struct gfarm_file_section_copy_info *info) { struct gfarm_file_section_copy_info_key key; key.pathname = pathname; key.section = section; key.hostname = hostname; return (gfarm_generic_info_get(&key, info, &gfarm_file_section_copy_info_ops)); } char * gfarm_file_section_copy_info_set( char *pathname, char *section, char *hostname, struct gfarm_file_section_copy_info *info) { int i; LDAPMod *modv[5]; struct ldap_string_modify storage[ARRAY_LENGTH(modv) - 1]; struct gfarm_file_section_copy_info_key key; key.pathname = pathname; key.section = section; key.hostname = hostname; /* * `info->pathname', `info->section' and `info->hostname' * don't have to be set, * because this function uses its argument instead. */ i = 0; set_string_mod(&modv[i], LDAP_MOD_ADD, "objectclass", "GFarmFileSectionCopy", &storage[i]); i++; set_string_mod(&modv[i], LDAP_MOD_ADD, "pathname", pathname, &storage[i]); i++; set_string_mod(&modv[i], LDAP_MOD_ADD, "section", section, &storage[i]); i++; set_string_mod(&modv[i], LDAP_MOD_ADD, "hostname", hostname, &storage[i]); i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv)); return (gfarm_generic_info_set(&key, modv, &gfarm_file_section_copy_info_ops)); } char * gfarm_file_section_copy_info_remove( const char *pathname, const char *section, const char *hostname) { struct gfarm_file_section_copy_info_key key; key.pathname = pathname; key.section = section; key.hostname = hostname; return (gfarm_generic_info_remove(&key, &gfarm_file_section_copy_info_ops)); } void gfarm_file_section_copy_info_free_all( int n, struct gfarm_file_section_copy_info *infos) { gfarm_generic_info_free_all(n, infos, &gfarm_file_section_copy_info_ops); } char * gfarm_file_section_copy_info_get_all_by_file( const char *pathname, int *np, struct gfarm_file_section_copy_info **infosp) { char *error; int n; struct gfarm_file_section_copy_info *infos; static char query_template[] = "(&(objectclass=GFarmFileSectionCopy)(pathname=%s))"; char *query = malloc(sizeof(query_template) + strlen(pathname)); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, pathname); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_SUBTREE, query, &n, &infos, &gfarm_file_section_copy_info_ops); free(query); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } char * gfarm_file_section_copy_info_remove_all_by_file( const char *pathname) { char *error, *error_save; int i, n; struct gfarm_file_section_copy_info *infos; error = gfarm_file_section_copy_info_get_all_by_file(pathname, &n, &infos); if (error != NULL) { if (error == GFARM_ERR_NO_SUCH_OBJECT) return (NULL); return (error); } /* * remove GFarmFileSectionCopies */ error_save = NULL; for (i = 0; i < n; i++) { error = gfarm_file_section_copy_info_remove(pathname, infos[i].section, infos[i].hostname); if (error != NULL && error != GFARM_ERR_NO_SUCH_OBJECT) error_save = error; } gfarm_file_section_copy_info_free_all(n, infos); return (error_save); } char * gfarm_file_section_copy_info_get_all_by_section( const char *pathname, const char *section, int *np, struct gfarm_file_section_copy_info **infosp) { char *error, *dn; int n; struct gfarm_file_section_info_key frag_info_key; struct gfarm_file_section_copy_info *infos; frag_info_key.pathname = pathname; frag_info_key.section = section; dn = (*gfarm_file_section_info_ops.make_dn)(&frag_info_key); if (dn == NULL) return (GFARM_ERR_NO_MEMORY); error = gfarm_generic_info_get_all(dn, LDAP_SCOPE_ONELEVEL, gfarm_file_section_copy_info_ops.query_type, &n, &infos, &gfarm_file_section_copy_info_ops); free(dn); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } char * gfarm_file_section_copy_info_remove_all_by_section( const char *pathname, const char *section) { char *error, *error_save; int i, n; struct gfarm_file_section_copy_info *infos; error = gfarm_file_section_copy_info_get_all_by_section( pathname, section, &n, &infos); if (error != NULL) { if (error == GFARM_ERR_NO_SUCH_OBJECT) return (NULL); return (error); } /* * remove GfarmFileSectionCopies */ error_save = NULL; for (i = 0; i < n; i++) { error = gfarm_file_section_copy_info_remove(pathname, section, infos[i].hostname); if (error != NULL && error != GFARM_ERR_NO_SUCH_OBJECT) error_save = error; } gfarm_file_section_copy_info_free_all(n, infos); return (error_save); } char * gfarm_file_section_copy_info_get_all_by_host( const char *hostname, int *np, struct gfarm_file_section_copy_info **infosp) { char *error; int n; struct gfarm_file_section_copy_info *infos; static char query_template[] = "(&(objectclass=GFarmFileSectionCopy)(hostname=%s))"; char *query = malloc(sizeof(query_template) + strlen(hostname)); if (query == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(query, query_template, hostname); error = gfarm_generic_info_get_all(gfarm_ldap_base_dn, LDAP_SCOPE_SUBTREE, query, &n, &infos, &gfarm_file_section_copy_info_ops); free(query); if (error != NULL) return (error); *np = n; *infosp = infos; return (NULL); } char * gfarm_file_section_copy_info_remove_all_by_host( const char *hostname) { char *error, *error_save; int i, n; struct gfarm_file_section_copy_info *infos; error = gfarm_file_section_copy_info_get_all_by_host(hostname, &n, &infos); if (error != NULL) { if (error == GFARM_ERR_NO_SUCH_OBJECT) return (NULL); return (error); } /* * remove GfarmFileSectionCopy's */ error_save = NULL; for (i = 0; i < n; i++) { error = gfarm_file_section_copy_info_remove( infos[i].pathname, infos[i].section, hostname); if (error != NULL && error != GFARM_ERR_NO_SUCH_OBJECT) error_save = error; } gfarm_file_section_copy_info_free_all(n, infos); return (error_save); } int gfarm_file_section_copy_info_does_exist( const char *pathname, const char *section, const char *hostname) { struct gfarm_file_section_copy_info info; if (gfarm_file_section_copy_info_get(pathname, section, hostname, &info) != NULL) return (0); gfarm_file_section_copy_info_free(&info); return (1); } /**********************************************************************/ static char *gfarm_file_history_make_dn(void *vkey); static void gfarm_file_history_clear(void *info); static void gfarm_file_history_set_field(void *info, char *attribute, char **vals); static int gfarm_file_history_validate(void *info); struct gfarm_file_history_key { char *gfarm_file; }; static const struct gfarm_generic_info_ops gfarm_file_history_ops = { sizeof(struct gfarm_file_history), "(objectclass=GFarmFile)", "gfarmFile=%s, %s", gfarm_file_history_make_dn, gfarm_file_history_clear, gfarm_file_history_set_field, gfarm_file_history_validate, (void (*)(void *))gfarm_file_history_free, }; static char * gfarm_file_history_make_dn(void *vkey) { struct gfarm_file_history_key *key = vkey; char *dn = malloc(strlen(gfarm_file_history_ops.dn_template) + strlen(key->gfarm_file) + strlen(gfarm_ldap_base_dn) + 1); if (dn == NULL) return (NULL); sprintf(dn, gfarm_file_history_ops.dn_template, key->gfarm_file, gfarm_ldap_base_dn); return (dn); } static void gfarm_file_history_clear(void *vinfo) { struct gfarm_file_history *info = vinfo; memset(info, 0, sizeof(*info)); } static void gfarm_file_history_set_field( void *vinfo, char *attribute, char **vals) { struct gfarm_file_history *info = vinfo; if (strcasecmp(attribute, "generatorProgram") == 0) { info->program = strdup(vals[0]); } else if (strcasecmp(attribute, "generatorInputGFarmFiles") == 0) { info->input_files = gfarm_strarray_dup(vals); } else if (strcasecmp(attribute, "generatorParameter") == 0) { info->parameter = strdup(vals[0]); } } static int gfarm_file_history_validate(void *vinfo) { struct gfarm_file_history *info = vinfo; return ( info->program != NULL && info->input_files != NULL && info->parameter != NULL ); } void gfarm_file_history_free( struct gfarm_file_history *info) { if (info->program != NULL) free(info->program); if (info->input_files != NULL) gfarm_strarray_free(info->input_files); if (info->parameter != NULL) free(info->parameter); } char *gfarm_file_history_get( char *gfarm_file, struct gfarm_file_history *info) { struct gfarm_file_history_key key; key.gfarm_file = gfarm_file; return (gfarm_generic_info_get(&key, info, &gfarm_file_history_ops)); } char * gfarm_file_history_set( char *gfarm_file, struct gfarm_file_history *info) { int i; LDAPMod *modv[4]; struct ldap_string_modify storage[ARRAY_LENGTH(modv) - 1]; LDAPMod input_files_mod; struct gfarm_file_history_key key; key.gfarm_file = gfarm_file; i = 0; #if 0 /* objectclass should be already set */ set_string_mod(&modv[i], LDAP_MOD_ADD, "objectclass", "GFarmFile", &storage[i]); i++; #endif set_string_mod(&modv[i], LDAP_MOD_ADD, "generatorProgram", info->program, &storage[i]); i++; input_files_mod.mod_op = LDAP_MOD_ADD; input_files_mod.mod_type = "generatorInputGFarmFiles"; input_files_mod.mod_vals.modv_strvals = info->input_files; modv[i] = &input_files_mod; i++; set_string_mod(&modv[i], LDAP_MOD_ADD, "generatorParameter", info->parameter, &storage[i]); i++; modv[i++] = NULL; assert(i == ARRAY_LENGTH(modv)); return (gfarm_generic_info_set(&key, modv, &gfarm_file_history_ops)); } char * gfarm_file_history_remove(char *gfarm_file) { struct gfarm_file_history_key key; key.gfarm_file = gfarm_file; return (gfarm_generic_info_remove(&key, &gfarm_file_history_ops)); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT3-1-1-1_master_gfmd_down_with_master_MDS_network_down #! /bin/sh ###################################################################### TESTID="FT3-1-1-1" CATEGORY="2 point accident" SECTION="internal accident and network down" TITLE="master gfmd down with master MDS network down" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd1_CTRL_ADDRESS sudo $IFDOWN_PATH $gfmd1_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "ifdown $gfmd1_GFARM_IF on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "$gfmd1 is unreachable" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd1_CTRL_ADDRESS sudo $IFUP_PATH $gfmd1_GFARM_IF $gfservice start-gfmd gfmd1 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_2_rc2/gftool/gfexec/gfexec.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <gfarm/gfarm.h> static char progname[] = "gfexec"; static void print_usage() { fprintf(stderr, "usage: %s [-u|-h] program args ...\n", progname); exit(2); } int fork_and_execvp(char *path, char *argv[]) { pid_t pid; int status; pid = fork(); if (pid == 0) { execvp(path, argv); perror(path); _exit(1); } else waitpid(pid, &status, 0); return (status); } int main(int argc, char *argv[], char *envp[]) { char *e, *gfarm_url, **saved_argv; int i, saved_argc; int gfarm_program = 1; --argc, ++argv; if (argc < 1) print_usage(); while (argv[0] && argv[0][0] == '-') { i = 1; while (argv[0][i]) { switch (argv[0][i]) { case 'u': gfarm_program = 0; break; case 'h': print_usage(); default: fprintf(stderr, "%s: invalid option -- %c\n", progname, argv[0][i]); print_usage(); } ++i; } --argc, ++argv; } if (argc < 1) print_usage(); /* save argv because it may be modified in gfarm_initialize() */ saved_argc = argc; saved_argv = malloc(argc * sizeof(char *) + 1); if (saved_argv == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } for (i = 0; i < argc; ++i) { saved_argv[i] = strdup(argv[i]); if (saved_argv[i] == NULL) { fprintf(stderr, "not enough memory\n"); exit(1); } } saved_argv[i] = '\0'; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", progname, e); exit(1); } e = gfs_realpath(*saved_argv, &gfarm_url); if (e != NULL) { /* not found in Gfarm file system */ if (gfarm_program) { execvp(*saved_argv, saved_argv); perror(*saved_argv); exit(1); } else { fork_and_execvp(*argv, argv); e = gfarm_terminate(); if (e != NULL) fprintf(stderr, "%s: %s\n", *argv, e); exit(0); } } if (gfarm_program) e = gfs_execve(gfarm_url, saved_argv, envp); else e = gfs_execve_legacy(gfarm_url, argv, envp); fprintf(stderr, "%s: %s\n", gfarm_url, e); free(gfarm_url); for (i = 0; i < saved_argc; ++i) free(saved_argv[i]); free(saved_argv); /* * gfarm_terminate() may fail because it might be already * called in gfs_execve(). */ (void)gfarm_terminate(); exit(1); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4/gftool/gfsetdir/gfsetdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <sys/socket.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "gfs_client.h" char *program_name = "gfsetdir"; void usage() { fprintf(stderr, "Usage: %s [-s|-c] [directory]\n", program_name); fprintf(stderr, "\t-c\t output string for *csh\n"); fprintf(stderr, "\t-s\t otherwise\n"); exit(1); } int main(int argc, char **argv) { extern int optind; char *e, *canonic_path, *gfarm_path, *peer_hostname; int ch; struct sockaddr peer_addr; struct gfs_connection *peer_conn; enum { UNDECIDED, B_SHELL_LIKE, C_SHELL_LIKE } shell_type = UNDECIDED; if (argc > 0) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((ch = getopt(argc, argv, "sc")) != -1) { switch (ch) { case 's': shell_type = B_SHELL_LIKE; break; case 'c': shell_type = C_SHELL_LIKE; break; default: usage(); } } argc -= optind; argv += optind; /* * Get absolute path from the argument directory name. * If no arugument is passed, generate gfarm:/"global username". */ canonic_path = NULL; switch (argc) { case 0: /* home directory */ canonic_path = gfarm_get_global_username(); break; case 1: e = gfarm_url_make_path(argv[0], &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path(argv[0], &canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } break; default: usage(); } /* * Check existence of the absolute path in a host. */ e = gfarm_schedule_search_idle_by_all(1, &peer_hostname); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_host_address_get(peer_hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_client_connect(peer_hostname, &peer_addr, &peer_conn); free(peer_hostname); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_client_chdir(peer_conn, canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_client_disconnect(peer_conn); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } gfarm_path = malloc(strlen(GFARM_URL_PREFIX) + strlen(canonic_path) + 2); if (gfarm_path == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(1); } sprintf(gfarm_path, "%s/%s", GFARM_URL_PREFIX, canonic_path); free(canonic_path); if (shell_type == UNDECIDED) { char *shell; shell = getenv("SHELL"); if (strlen(shell) < 3 || strncmp(shell + strlen(shell) - 3, "csh", 3)) shell_type = B_SHELL_LIKE; else shell_type = C_SHELL_LIKE; } if (shell_type == B_SHELL_LIKE) printf("GFS_PWD=%s; export GFS_PWD", gfarm_path); else printf("setenv GFS_PWD %s", gfarm_path); fflush(stdout); free(gfarm_path); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_rc3/lib/libgfarm/gfarm/host.h char *gfarm_host_get_self_architecture(char **); int gfarm_canonical_hostname_is_local(char *); int gfarm_host_is_local(char *); struct in_addr; char *gfarm_get_ip_addresses(int *, struct in_addr **); struct sockaddr; struct gfarm_hostspec; char *gfarm_host_address_use(struct gfarm_hostspec *); struct gfarm_host_info; char *gfarm_host_info_address_get(const char *, int, struct gfarm_host_info *, struct sockaddr *, char **); <file_sep>/gfarm_zabbix/trunk/src/install-editor.sh #! /bin/sh # # Install 'gfarm2.conf' editor. # . ./install.conf # install(1) command. INSTALL=install # Directory where edited 'gfarm2.conf' will be stored. EDITOR_SKELETON_DIR=$EDITOR_HTMLDIR/skeleton # Directory where 'metadataserver_list.log' will be placed by an external # script of Zabbix. EDITOR_GFMDLIST_DIR=$EDITOR_HTMLDIR/gfmdlist # # Create "$1" file from "$1.in". # create_file() { [ -f "$1".in ] || return 0 [ -f "$1" ] && rm -f "$1" sed \ -e "s|@GFARM_BINDIR@|$GFARM_BINDIR|g" \ -e "s|@ZABBIX_CONFDIR@|$ZABBIX_CONFDIR|g" \ -e "s|@EDITOR_GFMDLIST_DIR@|$EDITOR_GFMDLIST_DIR|g" \ "$1.in" > "$1" } # # Make a directory '$EDITOR_HTMLDIR'. # DIR=$EDITOR_HTMLDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files 'editor/*.php' to $EDITOR_HTMLDIR. # for I in \ common.php \ download.php \ edit.php \ index.php \ save.php; do SRCFILE=editor/$I DSTFILE=$EDITOR_HTMLDIR/$I $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Make a directory '$EDITOR_SKELETON_DIR'. # DIR=$EDITOR_SKELETON_DIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o $EDITOR_HTMLDIR_USER -g $EDITOR_HTMLDIR_GROUP $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Create initial 'gfarm2.conf' file. # SRCFILE=editor/gfarm2.conf DSTFILE=$EDITOR_SKELETON_DIR/gfarm2.conf if [ ! -f $DSTFILE ]; then $INSTALL -c -m 0644 -o $EDITOR_HTMLDIR_USER -g $EDITOR_HTMLDIR_GROUP \ $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" fi # # Make a directory '$EDITOR_GFMDLIST_DIR'. # DIR=$EDITOR_GFMDLIST_DIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o zabbix -g zabbix $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install 'editor/gfmdlist.sh' to '$ZABBIX_CONFDIR'. # SRCFILE=editor/gfmdlist.sh DSTFILE=$ZABBIX_CONFDIR/gfmdlist.sh create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" echo "" echo "Please add the following lines to a crontab file of user 'zabbix':" echo "" echo " # Run 'gfmdhost -l' every five minutes." echo " */5 * * * * $DSTFILE" echo "" echo "or add the following lines to a file under /etc/cron.d/:" echo "" echo " # Run 'gfmdhost -l' every five minutes." echo " */5 * * * * zabbix $DSTFILE" echo "" <file_sep>/gfarm/tags/gfarm_1_0_2/doc/html/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = en/ref ja/ref htmldir=$(default_htmldir) HTML = index.html include $(top_srcdir)/makes/subdir.mk include $(top_srcdir)/makes/html.mk <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/stringlist.c #include <stddef.h> #include <stdlib.h> #include <string.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfarm_stringlist.h> #define GFARM_STRINGLIST_INITIAL 50 #define GFARM_STRINGLIST_DELTA 50 char * gfarm_stringlist_init(gfarm_stringlist *listp) { char **v; v = malloc(sizeof(char *) * GFARM_STRINGLIST_INITIAL); if (v == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = GFARM_STRINGLIST_INITIAL; listp->length = 0; listp->array = v; v[0] = NULL; return (NULL); } void gfarm_stringlist_free(gfarm_stringlist *listp) { free(listp->array); /* the following is not needed, but to make erroneous program abort */ listp->size = 0; listp->length = 0; listp->array = NULL; } void gfarm_stringlist_free_deeply(gfarm_stringlist *listp) { int i, length = gfarm_stringlist_length(listp); for (i = 0; i < length; i++) { if (listp->array[i] != NULL) free(listp->array[i]); } gfarm_stringlist_free(listp); } char * gfarm_stringlist_add_strings(gfarm_stringlist *listp, int al, char **av) { int ll = gfarm_stringlist_length(listp); if (ll + al > listp->size) { int n = listp->size; char **t; do { n += GFARM_STRINGLIST_DELTA; } while (ll + al > n); t = realloc(listp->array, sizeof(char *) * n); if (t == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = n; listp->array = t; } memcpy(&listp->array[ll], av, sizeof(char *) * al); listp->length += al; return (NULL); } char * gfarm_stringlist_add_list(gfarm_stringlist *listp, gfarm_stringlist *addp) { return (gfarm_stringlist_add_strings(listp, gfarm_stringlist_length(addp), addp->array)); } char * gfarm_stringlist_add(gfarm_stringlist *listp, char *s) { int length = gfarm_stringlist_length(listp); if (length >= listp->size) { int n = listp->size + GFARM_STRINGLIST_DELTA; char **t = realloc(listp->array, sizeof(char *) * n); if (t == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = n; listp->array = t; } listp->array[length] = s; listp->length++; return (NULL); } char * gfarm_stringlist_cat(gfarm_stringlist *listp, char **v) { return (gfarm_stringlist_add_strings(listp, gfarm_strarray_length(v), v)); } char ** gfarm_strings_alloc_from_stringlist(gfarm_stringlist *listp) { int n = gfarm_stringlist_length(listp); char **t = malloc(sizeof(char *) * n); if (t == NULL) return (NULL); memcpy(t, listp->array, sizeof(char *) * n); return (t); } int gfarm_strarray_length(char **array) { int i; for (i = 0; array[i] != NULL; i++) ; return (i); } char ** gfarm_strarray_dup(char **array) { int i, n = gfarm_strarray_length(array); char **v = malloc(sizeof(char *) * (n + 1)); if (v == NULL) return (v); for (i = 0; i < n; i++) { v[i] = strdup(array[i]); if (v[i] == NULL) { for (--i; i >= 0; --i) free(v[i]); free(v); return (NULL); } } v[i] = NULL; return (v); } void gfarm_strarray_free(char **array) { int i; for (i = 0; array[i] != NULL; i++) free(array[i]); free(array); } void gfarm_strings_free_deeply(int n, char **strings) { int i; for (i = 0; i < n; i++) { if (strings[i] != NULL) free(strings[i]); } free(strings); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfarm/agent_wrap.h /* * $Id$ */ void gfarm_agent_disable(void); /* for direct access without agent */ char *gfarm_i_path_info_get(const char *, struct gfarm_path_info *); char *gfarm_i_path_info_set(char *, struct gfarm_path_info *); char *gfarm_i_path_info_replace(char *, struct gfarm_path_info *); char *gfarm_i_path_info_remove(const char *); char *gfs_i_realpath_canonical(const char *, char **); char *gfs_i_get_ino(const char *, long *); char *gfs_i_opendir(const char *, GFS_Dir *); char *gfs_i_readdir(GFS_Dir, struct gfs_dirent **); char *gfs_i_closedir(GFS_Dir); char *gfs_i_dirname(GFS_Dir); void gfs_i_uncachedir(void); <file_sep>/gfarm/tags/gfarm_0_1/man/ja/man1/Makefile # $Id$ top_objdir = ../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk include $(srcdir)/../Makefile.inc MAN = digest.1 gfexport.1 gfgrep.1 gfimport_fixed.1 gfimport_text.1 \ gfkey.1 gfls.1 gfmkdir.1 gfmpirun.1 gfps.1 gfrcmd.1 gfreg.1 \ gfrep.1 gfrm.1 gfrmdir.1 gfrsh.1 gfrun.1 gfssh.1 gfwc.1 gfwhere.1 include $(top_srcdir)/makes/man.mk <file_sep>/gfarm/tags/gfarm_1_0_3_1/lib/libgfarm/gfarm/import_help.c #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <math.h> /* file_offset_floor() may be floor() */ #include <time.h> #include <gfarm/gfarm.h> #define TABLE_SIZE_INITIAL 128 #define TABLE_SIZE_DELTA 128 /* * configuration file format: * fragment_size fragment_hostnmae * : */ char * gfarm_import_fragment_config_read(char *config, int *np, char ***hosttabp, file_offset_t **sizetabp, int *error_linep) { char *e, **host_table, line[1024]; int i, table_size = TABLE_SIZE_INITIAL; file_offset_t *size_table = malloc(sizeof(size_table[0]) * table_size); file_offset_t *stab; gfarm_stringlist host_list; FILE *fp; *error_linep = -1; if (size_table == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_stringlist_init(&host_list); if (e != NULL) { free(size_table); return (e); } if (strcmp(config, "-") == 0) { fp = stdin; } else if ((fp = fopen(config, "r")) == NULL) { gfarm_stringlist_free(&host_list); free(size_table); return (GFARM_ERR_NO_SUCH_OBJECT); } for (i = 0; fgets(line, sizeof(line), fp) != NULL; i++) { int l = strlen(line); char *s, *t, *host; file_offset_t size; if (l > 0 && line[l - 1] == '\n') line[--l] = '\0'; size = string_to_file_offset(line, &s); if (s == line) { e = "fragment size expected"; *error_linep = i + 1; goto error; } while (isspace(*(unsigned char *)s)) s++; if (*s == '\0') { e = "fragment hostname expected"; *error_linep = i + 1; goto error; } for (t = s; *t != '\0' && !isspace(*(unsigned char *)t); t++) ; *t = '\0'; host = strdup(s); if (host == NULL) { e = GFARM_ERR_NO_MEMORY; *error_linep = i + 1; goto error; } e = gfarm_stringlist_add(&host_list, host); if (e != NULL) { *error_linep = i + 1; goto error; } if (i >= table_size) { table_size += TABLE_SIZE_DELTA; stab = realloc(size_table, sizeof(size_table[0]) * table_size); if (stab == NULL) { e = GFARM_ERR_NO_MEMORY; *error_linep = i + 1; goto error; } size_table = stab; } size_table[i] = size; } if (i == 0) { e = "empty file"; goto error; } host_table = gfarm_strings_alloc_from_stringlist(&host_list); if (host_table == NULL) { e = GFARM_ERR_NO_MEMORY; goto error; } if (i < table_size) { stab = realloc(size_table, sizeof(size_table[0]) * i); if (stab == NULL) { e = GFARM_ERR_NO_MEMORY; goto error; } memcpy(stab, size_table, sizeof(size_table[0]) * i); size_table = stab; } /* * do not call gfarm_stringlist_free_deeply() here, * because the strings are passed to *host_table. */ gfarm_stringlist_free(&host_list); /* no limit on last fragment */ size_table[i - 1] = FILE_OFFSET_T_MAX; *np = i; *hosttabp = host_table; *sizetabp = size_table; if (strcmp(config, "-") != 0) fclose(fp); return (NULL); error: if (strcmp(config, "-") != 0) fclose(fp); gfarm_stringlist_free_deeply(&host_list); free(size_table); return (e); } file_offset_t * gfarm_import_fragment_size_alloc(file_offset_t total_size, int n) { file_offset_t *sizetab = malloc(sizeof(sizetab[0]) * n); file_offset_t fragment_size; int i; if (sizetab == NULL) return (NULL); fragment_size = file_offset_floor((total_size + n - 1) / n); --n; for (i = 0; i < n; i++) sizetab[i] = fragment_size; /* no limit on last fragment */ sizetab[n] = FILE_OFFSET_T_MAX; return (sizetab); } /* * NOTE: * returned (*linetabp) should be freed by gfarm_strings_free_deeply(). * * configuration file format: * hostname1 * hostname2 * : */ char * gfarm_hostlist_read(char *filename, int *np, char ***host_table_p, int *error_linep) { gfarm_stringlist host_list; FILE *fp; int i; char *e, line[1024]; *error_linep = -1; e = gfarm_stringlist_init(&host_list); if (e != NULL) return (e); if (strcmp(filename, "-") == 0) { fp = stdin; } else if ((fp = fopen(filename, "r")) == NULL) { gfarm_stringlist_free(&host_list); return (GFARM_ERR_NO_SUCH_OBJECT); } for (i = 0; fgets(line, sizeof(line), fp) != NULL; i++) { int l = strlen(line); char *s, *t, *host; if (l > 0 && line[l - 1] == '\n') line[--l] = '\0'; for (s = line; isspace(*(unsigned char *)s); s++) ; if (*s == '\0') { e = "hostname expected"; *error_linep = i + 1; goto error; } for (t = s; *t != '\0' && !isspace(*(unsigned char *)t); t++) ; *t = '\0'; host = strdup(s); if (host == NULL) { e = GFARM_ERR_NO_MEMORY; *error_linep = i + 1; goto error; } e = gfarm_stringlist_add(&host_list, host); if (e != NULL) { free(host); *error_linep = i + 1; goto error; } } if (i == 0) { e = "empty file"; goto error; } *np = gfarm_stringlist_length(&host_list); *host_table_p = gfarm_strings_alloc_from_stringlist(&host_list); if (e != NULL) goto error; /* * do not call gfarm_stringlist_free_deeply() here, * because the strings are passed to *host_table. */ gfarm_stringlist_free(&host_list); if (strcmp(filename, "-") != 0) fclose(fp); return (NULL); error: if (strcmp(filename, "-") != 0) fclose(fp); gfarm_stringlist_free_deeply(&host_list); return (e); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT1-2-1-1_disk_exhausted #! /bin/sh ###################################################################### TESTID="FT1-2-1-1" CATEGORY="accident causes no failover" SECTION="common observed properties" TITLE="disk exhausted" ###################################################################### . ./FT-common get_exhausted_size() { _HOST_=$1 _SIZE_=`ssh $_HOST_ df -Pk | grep ' /$' | awk '{ usize=$3; fsize=$4 } END { print int(((usize + fsize) / 100 * 95) - usize) }'` echo $_SIZE_ } ft_setup() { scp create-random-file $gfsd1: ssh $gfsd1 rm -f tmp.dat return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` SIZE=`get_exhausted_size $gfsd1` ssh $gfsd1 ./create-random-file tmp.dat "${SIZE}K" || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "create a large file on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "Low free disk space on $gfsd1 volume /" \ "High used disk space on $gfsd1 volume /" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive two mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfsd1 rm -f tmp.dat || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "delete the large file on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "Re: Low free disk space on $gfsd1 volume /" \ "Re: High used disk space on $gfsd1 volume /" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive two mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfsd1 rm -f create-random-file tmp.dat return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_mpiio/tags/gfarm_mpiio_0_0_1/ad_gfarm/ad_gfarm.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" /* adioi.h has the ADIOI_Fns_struct define */ #include "adioi.h" #include "adio_extern.h" struct ADIOI_Fns_struct ADIO_GFARM_operations = { ADIOI_GFARM_Open, /* Open */ ADIOI_GEN_OpenColl, /* OpenColl */ ADIOI_GFARM_ReadContig, /* ReadContig */ ADIOI_GFARM_WriteContig, /* WriteContig */ ADIOI_GFARM_ReadStridedColl, /* ReadStridedColl */ ADIOI_GFARM_WriteStridedColl, /* WriteStridedColl */ ADIOI_GFARM_SeekIndividual, /* SeekIndividual */ ADIOI_GFARM_Fcntl, /* Fcntl */ ADIOI_GFARM_SetInfo, /* SetInfo */ ADIOI_GFARM_ReadStrided, /* ReadStrided */ ADIOI_GFARM_WriteStrided, /* WriteStrided */ ADIOI_GFARM_Close, /* Close */ ADIOI_FAKE_IreadContig, /* IreadContig */ ADIOI_FAKE_IwriteContig, /* IwriteContig */ ADIOI_FAKE_IODone, /* ReadDone */ ADIOI_FAKE_IODone, /* ReadDone */ ADIOI_FAKE_IOComplete, /* ReadComplete */ ADIOI_FAKE_IOComplete, /* ReadComplete */ ADIOI_FAKE_IreadStrided, /* IreadStrided */ ADIOI_FAKE_IwriteStrided, /* IwriteStrided */ ADIOI_GFARM_Flush, /* Flush */ ADIOI_GFARM_Resize, /* Resize */ ADIOI_GFARM_Delete, /* Delete */ ADIOI_GEN_Feature, /* Features */ }; void ad_gfarm_set_view(ADIO_File fd, ADIO_Offset disp, MPI_Info info) { int i,j,k; int read_only, write_only, number_of_set_view, overwrap; char tmp_filename[256]; char tmp_dirname[256], tmp_metadirname[256], gfarm_filename[256]; char *gfarm_header_file, *gfarm_file_name; char header_file_str[256], tmp_hfs; int myrank, nprocs; int *flat_file_count, flat_file_maxcount; int header_nprocs, *count_arr, flag; long header_seek_len; ADIO_Offset *header_disps, *disps; MPI_Aint *adds; MPI_Datatype *etypes, *filetypes, *header_etypes, *header_filetypes; MPI_Offset **flat_file_blocklens, **flat_file_indices, *flat_file_disp, tmp_indices; int header_fp; unsigned *filetype_size_arr, filetype_size; MPI_Aint *filetype_extent_arr, filetype_extent; mode_t permisson; ADIOI_Flatlist_node *flat_file; char hostname[256]; int filetype_is_contig; //gfarm param GFS_File gfp, data_gfp; gfarm_off_t result, tail_header_file_offset; gfarm_error_t gerr; int g_np; GFS_Dir dirp; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf*)fd->fs_ptr; MPI_Comm_rank(fd->comm, &myrank); MPI_Comm_size(fd->comm, &nprocs); //gethostname(hostname,256); #ifdef GFARM_DEBUG printf("[%d/%d] ADIO_Set_view\n", myrank, nprocs); #endif ADIOI_Datatype_iscontig(fd->filetype, &filetype_is_contig); if(filetype_is_contig){ #ifdef GFARM_DEBUG printf("[%d/%d] gfarm_set_view filtype_is_contig\n", myrank,nprocs); #endif if(myrank < 10){ gfarm_header_file = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10+1)); }else{ gfarm_header_file = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10+(int)log10(myrank)+1)); } sprintf(gfarm_header_file, "%s/meta/%d", fd->filename, myrank); printf("[%d/%d] gfarm_headr_file = %s.\n", myrank, nprocs, gfarm_header_file); gerr = gfs_pio_open(gfarm_header_file, GFARM_FILE_RDWR, &gfp); printf("[%d/%d] open header_file. gerr = %d.\n", myrank, nprocs, gerr); if(gerr == GFARM_ERR_NO_ERROR){ gerr = gfs_pio_read(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_read(gfp, &tail_header_file_offset, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } number_of_set_view += 1; gerr = gfs_pio_seek(gfp, 0, 0, &result); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_write(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_seek(gfp, tail_header_file_offset, 0, &result); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } }else if(gerr == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY){ number_of_set_view = 0; gerr = gfs_pio_create(gfarm_header_file, GFARM_FILE_RDWR, 0000644, &gfp); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } number_of_set_view += 1; gerr = gfs_pio_write(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } }else{ //error_code return; } int tmp_count; tmp_count = 0; gerr = gfs_pio_write(gfp, &nprocs, sizeof(int), &g_np); gerr = gfs_pio_write(gfp, &tmp_count, sizeof(int), &g_np); gerr = gfs_pio_write(gfp, &disp, sizeof(ADIO_Offset), &g_np); gerr = gfs_pio_seek(gfp, 0, 1, &tail_header_file_offset); gerr = gfs_pio_seek(gfp, 4, 0, &result); gerr = gfs_pio_write(gfp, &tail_header_file_offset, sizeof(int), &g_np); gfs_pio_close(gfp); if(myrank < 10){ gfarm_file_name = (char*)malloc(sizeof(char)* (strlen(fd->filename)+10+1+(int)log10(number_of_set_view+1))); }else{ gfarm_file_name = (char*)malloc(sizeof(char)* (strlen(fd->filename)+10+(int)log10(myrank)+(int)log10(number_of_set_view+1))); } sprintf(gfarm_file_name, "%s/data/0-%d", fd->filename, number_of_set_view-1); if(myrank == 0){ gerr = gfs_pio_create(gfarm_file_name, GFARM_FILE_RDWR, 0000644, &data_gfp); gerr = gfs_pio_close(data_gfp); } MPI_Barrier(fd->comm); gerr = gfs_pio_open(gfarm_file_name, GFARM_FILE_RDWR, &data_gfp); if(ghi->gfp_num > 0){ for(i=0;i<ghi->gfp_num;i++){ gfs_pio_close(ghi->gfp[i]); } free(ghi->gfp); } ghi->gfp_num = 1; ghi->gfp_index = 0; ghi->gfp = (GFS_File*)malloc(sizeof(GFS_File)); ghi->gfp[0] = data_gfp; ghi->nprocs = nprocs; ghi->count = 0; ghi->is_collective = 0; return; }else{ flat_file = ADIOI_Flatlist; while (flat_file->type != fd->filetype) flat_file = flat_file->next; } if((gerr = gfs_opendir(fd->filename, &dirp)) == GFARM_ERR_NO_ERROR){ // gfs_closedir(dirp); if(true){//ghi->header_flag == 1 && ghi->gfarm_view_flag == 0){ if(myrank < 10){ gfarm_header_file = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10+1)); }else{ gfarm_header_file = (char*)malloc(sizeof(char)*(strlen(fd->filename)+10+(int)log10(myrank)+1)); } sprintf(gfarm_header_file, "%s/meta/%d", fd->filename, myrank); gerr = gfs_pio_open(gfarm_header_file, GFARM_FILE_RDWR, &gfp); if(gerr == GFARM_ERR_NO_ERROR){ gerr = gfs_pio_read(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_read(gfp, &tail_header_file_offset, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } number_of_set_view += 1; gerr = gfs_pio_seek(gfp, 0, 0, &result); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_write(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } gerr = gfs_pio_seek(gfp, tail_header_file_offset, 0, &result); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } }else if(gerr == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY){ number_of_set_view = 0; gerr = gfs_pio_create(gfarm_header_file, GFARM_FILE_RDWR, 0000644, &gfp); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } number_of_set_view += 1; gerr = gfs_pio_write(gfp, &number_of_set_view, sizeof(int), &g_np); if(gerr != GFARM_ERR_NO_ERROR){ //error_code return; } }else{ //error_code return; } MPI_Type_extent(fd->filetype, &filetype_extent); MPI_Type_size(fd->filetype, &filetype_size); //check overwrap reagion overwrap = ad_gfarm_check_view(fd, &filetype_extent, &filetype_size); //create new file if(overwrap == 0){ if(myrank < 10){ gfarm_file_name = (char*)malloc(sizeof(char)* (strlen(fd->filename)+10+1+(int)log10(number_of_set_view+1))); }else{ gfarm_file_name = (char*)malloc(sizeof(char)* (strlen(fd->filename)+10+(int)log10(myrank)+(int)log10(number_of_set_view+1))); } sprintf(gfarm_file_name, "%s/data/%d-%d", fd->filename, myrank, number_of_set_view-1); gerr = gfs_pio_create(gfarm_file_name, GFARM_FILE_RDWR, 0000644, &data_gfp); if(gerr != GFARM_ERR_NO_ERROR){ printf("[%d/%d] create error! gfarm_file_name = %s\n", myrank, nprocs, gfarm_file_name); } if(ghi->gfp_num > 0){ for(i=0;i<ghi->gfp_num;i++){ gfs_pio_close(ghi->gfp[i]); } free(ghi->gfp); } ghi->gfp_num = 1; ghi->gfp_index = 0; ghi->gfp = (GFS_File*)malloc(sizeof(GFS_File)); //ghi->gfp_flag = (int*)malloc(sizeof(int)*gfp_num); ghi->gfp[0] = data_gfp; ghi->gfarm_view_flag = 1; ghi->is_collective = 0; }else{ } //MPI_Type_extent(fd->etype, &etype_extent); //MPI_Type_size(fd->etype, &etype_extent); gerr = gfs_pio_write(gfp, &nprocs, sizeof(int), &g_np); gerr = gfs_pio_write(gfp, &(flat_file->count), sizeof(int), &g_np); gerr = gfs_pio_write(gfp, &disp, sizeof(ADIO_Offset), &g_np); gerr = gfs_pio_write(gfp, &filetype_size, sizeof(unsigned), &g_np); gerr = gfs_pio_write(gfp, &filetype_extent, sizeof(MPI_Aint), &g_np); gerr = gfs_pio_write(gfp, flat_file->blocklens, sizeof(ADIO_Offset)*(flat_file->count), &g_np); gerr = gfs_pio_write(gfp, flat_file->indices, sizeof(ADIO_Offset)*(flat_file->count), &g_np); gerr = gfs_pio_seek(gfp, 0, 1, &tail_header_file_offset); gerr = gfs_pio_seek(gfp, 4, 0, &result); gerr = gfs_pio_write(gfp, &tail_header_file_offset, sizeof(int), &g_np); gfs_pio_close(gfp); #ifdef GFARM_DEBUG printf("[%d/%d] end gfarm_set_view\n", myrank,nprocs); #endif }else{ strcpy(tmp_metadirname, tmp_dirname); strcat(tmp_metadirname, "/meta"); sprintf(gfarm_header_file, "%s/%d", tmp_metadirname, myrank); if((gerr = gfs_pio_open(gfarm_header_file, GFARM_FILE_RDWR, &gfp)) != 0){ printf("old open :%d\n", gerr); } //header if((gerr = gfs_pio_read(gfp, &header_nprocs, sizeof(int), &g_np)) != 0){ printf("old header_nprocs :%d\n", gerr); } //fread(&header_nprocs, sizeof(int), 1, header); count_arr = malloc(sizeof(int)*(header_nprocs)); if((gerr = gfs_pio_read(gfp, count_arr+myrank, sizeof(int), &g_np)) != 0){ printf("old count_arr :%d\n", gerr); } //fread(count_arr, sizeof(int), header_nprocs, header); //header flat_file_blocklens = (ADIO_Offset**)malloc(sizeof(ADIO_Offset*)*header_nprocs); flat_file_indices = (ADIO_Offset**)malloc(sizeof(ADIO_Offset*)*header_nprocs); flat_file_disp = (ADIO_Offset*)malloc(sizeof(ADIO_Offset)*header_nprocs); filetype_size_arr = malloc(sizeof(unsigned)*header_nprocs); filetype_extent_arr = malloc(sizeof(MPI_Aint)*header_nprocs); for(i=0;i<header_nprocs;i++){ flat_file_blocklens[i] = (ADIO_Offset*)malloc(sizeof(ADIO_Offset)*count_arr[i]); flat_file_indices[i] =(ADIO_Offset*) malloc(sizeof(ADIO_Offset)*count_arr[i]); } if((gerr = gfs_pio_read(gfp, flat_file_disp+myrank, sizeof(ADIO_Offset), &g_np)) != 0){ printf("old flat_file_disp : %d\n", gerr); } if((gerr = gfs_pio_read(gfp, filetype_size_arr+myrank, sizeof(unsigned), &g_np)) != 0){ printf("old filetype_size_arr : %d\n", gerr); } if((gerr = gfs_pio_read(gfp, filetype_extent_arr+myrank, sizeof(MPI_Aint), &g_np)) != 0){ printf("old filetype_extent_arr : %d\n", gerr); } if((gerr = gfs_pio_read(gfp, flat_file_blocklens[myrank], sizeof(ADIO_Offset)*count_arr[myrank], &g_np)) != 0){ printf("old flat_file_blocklens : %d\n", gerr); } if((gerr = gfs_pio_read(gfp, flat_file_indices[myrank], sizeof(ADIO_Offset)*count_arr[myrank], &g_np)) != 0){ printf("old flat_file_indices : %d\n", gerr); } gfs_pio_close(gfp); // MPI_Allgather(count_arr+myrank, 1, MPI_INT, count_arr, 1, MPI_INT, fd->comm); MPI_Allgather(flat_file_disp+myrank, 1, ADIO_OFFSET, flat_file_disp, 1, ADIO_OFFSET, fd->comm); MPI_Allgather(filetype_size_arr+myrank, 1, MPI_UNSIGNED, filetype_size_arr, 1, MPI_UNSIGNED, fd->comm); MPI_Allgather(filetype_extent_arr+myrank, 1, MPI_AINT, filetype_extent_arr, 1, MPI_AINT, fd->comm); //count_arr_sum = 0; //for(i=0;i<nprocs;i++) count_arr_sum += count_arr[i]; //tmp_blocklens = malloc(sizeof(ADIO_Offset)*count_arr_sum); for(i=0;i<nprocs;i++){ MPI_Bcast(flat_file_blocklens[i], count_arr[i], ADIO_OFFSET, i, fd->comm); MPI_Bcast(flat_file_indices[i], count_arr[i], ADIO_OFFSET, i, fd->comm); } if(header_nprocs > nprocs){ for(i=0;i<header_nprocs/nprocs;i++){ if((header_nprocs-nprocs) > myrank){ sprintf(gfarm_header_file, "%s/%d", tmp_metadirname, nprocs*(i+1)+myrank); if((gerr = gfs_pio_open(gfarm_header_file, GFARM_FILE_RDWR, &gfp)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_seek(gfp, sizeof(int), 0, &result)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, count_arr+(nprocs*(i+1)+myrank), sizeof(int), &g_np)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, flat_file_disp+(nprocs*(i+1)+myrank), sizeof(ADIO_Offset), &g_np)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, filetype_size_arr+(nprocs*(i+1)+myrank), sizeof(unsigned), &g_np)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, filetype_extent_arr+(nprocs*(i+1)+myrank), sizeof(MPI_Aint), &g_np)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, flat_file_blocklens[(nprocs*(i+1)+myrank)], sizeof(ADIO_Offset)*count_arr[(nprocs*(i+1)+myrank)], &g_np)) != 0){ printf("%d\n", gerr); } if((gerr = gfs_pio_read(gfp, flat_file_indices[(nprocs*(i+1)+myrank)], sizeof(ADIO_Offset)*count_arr[(nprocs*(i+1)+myrank)], &g_np)) != 0){ printf("%d\n", gerr); } gfs_pio_close(gfp); } } } //fclose(header); ghi->nprocs = header_nprocs; ghi->count = count_arr; ghi->filetype_size = filetype_size_arr; ghi->filetype_extent = filetype_extent_arr; ghi->blocklens = flat_file_blocklens; ghi->indices = flat_file_indices; ghi->gfp_num = 0; ghi->gfp = malloc(sizeof(GFS_File)*header_nprocs); ghi->gfp_flag = malloc(sizeof(int)*header_nprocs); ghi->data_size = malloc(sizeof(unsigned long)*header_nprocs); ghi->access_time = 0.0; ghi->all_time = 0.0; for(i=0;i<header_nprocs;i++){ ghi->gfp_flag[i] = 0; ghi->data_size[i] = 0; } flag = 0; for(j=0;j<header_nprocs;j++){ for(i=0;i<count_arr[j];i++){ #ifdef GFARM_DEBUG printf("[%d/%d] j:i=%d:%d indices:blocklens=%d:%d\n", myrank, nprocs, j, i, flat_file_indices[j][i], flat_file_blocklens[j][i]); #endif if(flat_file->blocklens[0] == 0){ if(flat_file->indices[1] >= filetype_extent_arr[j]){ tmp_indices = flat_file->indices[1] % filetype_extent_arr[j]; }else{ tmp_indices = flat_file->indices[1]; } if(tmp_indices >= flat_file_indices[j][i] && (tmp_indices < flat_file_indices[j][i] + flat_file_blocklens[j][i]) ){ flag = 1; break; } }else{ if(flat_file->indices[0] >= filetype_extent_arr[j]){ tmp_indices = flat_file->indices[0] % filetype_extent_arr[j]; }else{ tmp_indices = flat_file->indices[0]; } if(tmp_indices >= flat_file_indices[j][i] && (tmp_indices < flat_file_indices[j][i] + flat_file_blocklens[j][i]) ){ flag = 1; break; } } } if(flag == 1) break; } if(flag != 0){ //create file name sprintf(gfarm_filename, "%s/%d", tmp_dirname, j); //open file if((gerr = gfs_pio_open(gfarm_filename, GFARM_FILE_RDWR, &gfp)) != 0){ printf("%d\n", gerr); } ghi->filename = gfarm_filename; ghi->gfp[j] = gfp; ghi->gfp_flag[j] = 1; ghi->gfp_num = j; fd->fs_ptr = ghi; ghi->newfile = 0; ghi->is_collective = 0; ghi->gci = NULL; #ifdef GFARM_DEBUG printf("[%d/%d] ADIO_Set_view:%s\n", myrank, nprocs, gfarm_filename); printf("[%d/%d] open fd=%d\n", myrank, nprocs, ghi->gfp[j]); #endif }else{ #ifdef GFARM_DEBUG printf("[%d/%d] flag=0\n", myrank, nprocs); #endif } } }else{ printf("[%d/%d] gfs_opendir. dir_name = %s. gerr = %d.\n", myrank, nprocs, fd->filename, gerr); } ghi->gfarm_view_flag = 1; } int ad_gfarm_check_view(ADIO_File fd, MPI_Aint *filetype_extent, unsigned *filetype_size) { int i, myrank, nprocs; int *count_arr, overwrap; ADIO_Offset *disps; ADIO_Offset **filetype_blocklens, **filetype_indices; MPI_Aint *filetype_extent_arr; unsigned *filetype_size_arr; ADIOI_Flatlist_node *flat_file; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf*)fd->fs_ptr; //ghi = (ADIOI_GFARM_headerInf *)malloc(sizeof(ADIOI_GFARM_headerInf)); flat_file = ADIOI_Flatlist; while(flat_file->type != fd->filetype) flat_file = flat_file->next; MPI_Comm_rank(fd->comm, &myrank); MPI_Comm_size(fd->comm, &nprocs); //init disps = (ADIO_Offset*)malloc(sizeof(ADIO_Offset)*nprocs); count_arr = (int*)malloc(sizeof(int)*nprocs); filetype_extent_arr = (MPI_Aint*)malloc(sizeof(MPI_Aint)*nprocs); filetype_size_arr = (unsigned*)malloc(sizeof(unsigned)*nprocs); filetype_blocklens = (ADIO_Offset**)malloc(sizeof(ADIO_Offset*)*nprocs); filetype_indices = (ADIO_Offset**)malloc(sizeof(ADIO_Offset*)*nprocs); for(i=0;i<nprocs;i++){ filetype_blocklens[i] = (ADIO_Offset*)malloc(sizeof(ADIO_Offset)*(flat_file->count)); filetype_indices[i] = (ADIO_Offset*)malloc(sizeof(ADIO_Offset)*(flat_file->count)); } //exchange view /* MPI_Allgather(&(flat_file->count),1,MPI_INT,count_arr,1,MPI_INT,fd->comm); MPI_Allgather(filetype_extent,1,MPI_AINT,filetype_extent_arr,1,MPI_AINT,fd->comm); MPI_Allgather(filetype_size,1,MPI_UNSIGNED,filetype_size_arr,1,MPI_UNSIGNED,fd->comm); filetype_blocklens[myrank] = flat_file->blocklens; filetype_indices[myrank] = flat_file->indices; for(i=0;i<nprocs;i++){ MPI_Bcast(filetype_blocklens[i], count_arr[i], ADIO_OFFSET, i, fd->comm); MPI_Bcast(filetype_indices[i], count_arr[i], ADIO_OFFSET, i, fd->comm); } */ //check view overwrap = 0; //store ghi->nprocs = nprocs; ghi->count = count_arr; ghi->filetype_size = filetype_size_arr; ghi->filetype_extent = filetype_extent_arr; ghi->blocklens = filetype_blocklens; ghi->indices = filetype_indices; return overwrap; } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/gfs_hook/hooks_subr.c /* * $Id$ */ #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" #define MAX_GFS_FILE_BUF 2048 static GFS_File _gfs_file_buf[MAX_GFS_FILE_BUF]; static int _gfs_file_refcount[MAX_GFS_FILE_BUF]; void gfs_hook_not_initialized(void) { static int printed = 0; if (!printed) { printed = 1; fprintf(stderr, "fatal error: gfarm_initialize() isn't called\n"); } } /* * gfs_file_buf management */ int gfs_hook_insert_gfs_file(GFS_File gf) { int fd, save_errno; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_file: %p\n", gf)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = dup(gfs_pio_fileno(gf)); if (fd == -1) { save_errno = errno; gfs_pio_close(gf); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_pio_close(gf); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_pio_close(gf); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = gf; return (fd); } int gfs_hook_clear_gfs_file(int fd) { int ref; _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: %d\n", fd)); _gfs_file_buf[fd] = NULL; __syscall_close(fd); ref = _gfs_file_refcount[fd]; if (ref > 0) --_gfs_file_refcount[fd]; return ref; } int gfs_hook_insert_filedes(int fd, GFS_File gf) { _gfs_hook_debug( fprintf(stderr, "GFS: insert_filedes: %d, %p\n", fd, gf)); if (_gfs_file_buf[fd] != NULL) return (-1); _gfs_file_buf[fd] = gf; return (fd); } void gfs_hook_inc_refcount(int fd) { _gfs_hook_debug( fprintf(stderr, "GFS: inc_refcount: %d\n", fd)); ++_gfs_file_refcount[fd]; } /* printf and puts should not be put into the following function. */ GFS_File gfs_hook_is_open(int fd) { if (fd >= 0 && fd < MAX_GFS_FILE_BUF) return (_gfs_file_buf[fd]); return (NULL); } /* * Check whether pathname is gfarm url or not. * * Gfarm URL: gfarm:[:section:]pathname * * It is necessary to free the memory space for *url. * Also, it's necessary to free the memory space for *secp, * if *secp is not NULL. */ int gfs_hook_is_url(const char *path, char **urlp, char **secp) { /* * ROOT patch: * 'gfarm@' is also considered as a Gfarm URL */ char *gfarm_url_prefix_for_root = "gfarm@"; *secp = NULL; /* * Objectivity patch: * '/gfarm:' is also considered as a Gfarm URL */ if (*path == '/') ++path; if (gfarm_is_url(path) || /* ROOT patch */ memcmp(path, gfarm_url_prefix_for_root, sizeof(gfarm_url_prefix_for_root) - 1) == 0) { static char prefix[] = "gfarm:"; if (!gfarm_initialized && gfs_hook_initialize() != NULL) { gfs_hook_not_initialized(); return (0); /* don't perform gfarm operation */ } /* * extension for accessing individual sections * gfarm::section:pathname */ if (path[sizeof(prefix) - 1] == ':') { const char *p = path + sizeof(prefix); int secsize = strcspn(p, "/:"); int urlsize; if (p[secsize] != ':') return (0); /* gfarm::foo/:bar or gfarm::foo */ urlsize = sizeof(prefix) - 1 + strlen(p + secsize + 1); *urlp = malloc(urlsize + 1); *secp = malloc(secsize + 1); if (*urlp == NULL || *secp == NULL) { if (*urlp != NULL) free(*urlp); if (*secp != NULL) free(*secp); return (0); /* XXX - should return ENOMEM */ } memcpy(*urlp, prefix, sizeof(prefix) - 1); strcpy(*urlp + sizeof(prefix) - 1, p + secsize + 1); memcpy(*secp, p, secsize); (*secp)[secsize] = '\0'; /* * This case needs to free memory space of * both *urlp and *secp. */ } else { *urlp = malloc(strlen(path) + 1); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ /* * the reason why we don't just call strcpy(*url, path) * is because the path may be "gfarm@path/name". * (ROOT patch) */ memcpy(*urlp, prefix, sizeof(prefix) - 1); strcpy(*urlp + sizeof(prefix) - 1, path + sizeof(prefix) - 1); } return (1); } return (0); } /* * default file view manipulation */ enum gfs_hook_file_view _gfs_hook_default_view = local_view; int _gfs_hook_index = 0; int _gfs_hook_num_fragments = GFARM_FILE_DONTCARE; void gfs_hook_set_default_view_local() { _gfs_hook_default_view = local_view; } void gfs_hook_set_default_view_index(int index, int nfrags) { _gfs_hook_default_view = index_view; _gfs_hook_index = index; _gfs_hook_num_fragments = nfrags; } void gfs_hook_set_default_view_global() { _gfs_hook_default_view = global_view; } char * gfs_hook_set_view_local(int filedes, int flag) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_local(gf, flag)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_index(int filedes, int nfrags, int index, char *host, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_index(gf, nfrags, index, host, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_global(int filedes, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_global(gf, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_global: %s\n", e)); return e; } return NULL; } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_editor/gfmdlist.sh.in #! /bin/sh GFMDLIST_FILE='@EDITOR_GFMDLIST_DIR@/metadataserver_list.log' TMP_GFMDLIST_FILE="$GFMDLIST_FILE.tmp" trap "rm -f $TMP_GFMDLIST_FILE; exit 1" 1 2 3 15 rm -f $TMP_GFMDLIST_FILE @GFARM_BINDIR@/gfmdhost -l \ | awk 'BEGIN {printf("metadb_server_list");} \ {printf(" %s:%s", $6, $7);} \ END {printf("\n");}' > $TMP_GFMDLIST_FILE if cmp $GFMDLIST_FILE $TMP_GFMDLIST_FILE > /dev/null 2>&1; then rm -f $TMP_GFMDLIST_FILE else mv -f $TMP_GFMDLIST_FILE $GFMDLIST_FILE fi exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_ntp.sh.in #!/bin/sh # defines NTPQ_CMD=/usr/sbin/ntpq # check config file if [ ! -f $NTPQ_CMD ]; then echo -1; exit 0; fi # exec check command RESULT=`$NTPQ_CMD -p| grep ^+ | awk '{ print $9 };' | sed 's/-//'` if [ $? != 0 ]; then RESULT="ntpq error." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/lib/libgfarm/gfarm/gfs_client.c /* * $Id$ */ #include <assert.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <ctype.h> #include <stdio.h> /* sprintf() */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <openssl/evp.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include "gfutil.h" #include "gfevent.h" #include "hash.h" #include "iobuffer.h" #include "xxx_proto.h" #include "io_fd.h" #include "host.h" #include "param.h" #include "sockopt.h" #include "auth.h" #include "gfs_proto.h" #include "gfs_client.h" #define XAUTH_NEXTRACT_MAXLEN 512 static char GFARM_ERR_GFSD_ABORTED[] = "gfsd aborted"; struct gfs_connection { struct xxx_connection *conn; enum gfarm_auth_method auth_method; char *hostname; /* malloc()ed, if created by gfs_client_connect() */ void *context; /* work area for RPC (esp. GFS_PROTO_COMMAND) */ }; #define SERVER_HASHTAB_SIZE 3079 /* prime number */ static struct gfarm_hash_table *gfs_server_hashtab = NULL; void gfs_client_terminate(void) { struct gfarm_hash_iterator it; struct gfs_connection *gfs_server; if (gfs_server_hashtab == NULL) return; for (gfarm_hash_iterator_begin(gfs_server_hashtab, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { gfs_server = gfarm_hash_entry_data( gfarm_hash_iterator_access(&it)); /* * We cannot use gfs_client_disconnect() here, * because gfs_server->hostname and gfs_server aren't * malloc'ed. */ xxx_connection_free(gfs_server->conn); } gfarm_hash_table_free(gfs_server_hashtab); gfs_server_hashtab = NULL; } int gfs_client_connection_fd(struct gfs_connection *gfs_server) { return (xxx_connection_fd(gfs_server->conn)); } enum gfarm_auth_method gfs_client_connection_auth_method(struct gfs_connection *gfs_server) { return (gfs_server->auth_method); } const char * gfs_client_hostname(struct gfs_connection *gfs_server) { return (gfs_server->hostname); } static char * gfs_client_connection0(const char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection *gfs_server) { char *e, *host_fqdn; int sock; sock = socket(PF_INET, SOCK_STREAM, 0); if (sock == -1) return (gfarm_errno_to_error(errno)); fcntl(sock, F_SETFD, 1); /* automatically close() on exec(2) */ /* XXX - how to report setsockopt(2) failure ? */ gfarm_sockopt_apply_by_name_addr(sock, canonical_hostname, peer_addr); if (connect(sock, peer_addr, sizeof(*peer_addr)) < 0) { e = gfarm_errno_to_error(errno); close(sock); return (e); } e = xxx_fd_connection_new(sock, &gfs_server->conn); if (e != NULL) { close(sock); return (e); } gfs_server->context = NULL; /* * the reason why we call strdup() is because * gfarm_auth_request() may break static work area of `*hp'. * XXX - now it's not hp->h_name, but canonical_hostname. */ host_fqdn = strdup(canonical_hostname); if (host_fqdn == NULL) { xxx_connection_free(gfs_server->conn); return (GFARM_ERR_NO_MEMORY); } e = gfarm_auth_request(gfs_server->conn, host_fqdn, peer_addr, &gfs_server->auth_method); free(host_fqdn); if (e != NULL) { xxx_connection_free(gfs_server->conn); return (e); } return (NULL); } /* * `hostname' to `addr' conversion really should be done in this function, * rather than a caller of this function. * but currently gfsd cannot access gfmd, and we need to access gfmd to * resolve hostname. (to check host_alias for "address_use" directive.) */ char * gfs_client_connection(const char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection **gfs_serverp) { char *e; struct gfarm_hash_entry *entry; struct gfs_connection *gfs_server; int created; if (gfs_server_hashtab == NULL) { gfs_server_hashtab = gfarm_hash_table_alloc(SERVER_HASHTAB_SIZE, gfarm_hash_casefold, gfarm_hash_key_equal_casefold); if (gfs_server_hashtab == NULL) return (GFARM_ERR_NO_MEMORY); } entry = gfarm_hash_enter(gfs_server_hashtab, canonical_hostname, strlen(canonical_hostname) + 1, sizeof(struct gfs_connection), &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); gfs_server = gfarm_hash_entry_data(entry); if (created) { e = gfs_client_connection0(canonical_hostname, peer_addr, gfs_server); if (e != NULL) { gfarm_hash_purge(gfs_server_hashtab, canonical_hostname, strlen(canonical_hostname)+1); return (e); } gfs_server->hostname = gfarm_hash_entry_key(entry); } *gfs_serverp = gfs_server; return (NULL); } /* * XXX FIXME * `hostname' to `addr' conversion really should be done in this function, * rather than a caller of this function. * but currently gfsd cannot access gfmd, and we need to access gfmd to * resolve hostname. (to check host_alias for "address_use" directive.) */ char * gfs_client_connect(char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection **gfs_serverp) { struct gfs_connection *gfs_server = malloc(sizeof(struct gfs_connection)); char *e; if (gfs_server == NULL) return (GFARM_ERR_NO_MEMORY); gfs_server->hostname = strdup(canonical_hostname); if (gfs_server->hostname == NULL) { free(gfs_server); return (GFARM_ERR_NO_MEMORY); } e = gfs_client_connection0(canonical_hostname, peer_addr, gfs_server); if (e != NULL) { free(gfs_server->hostname); free(gfs_server); return (e); } *gfs_serverp = gfs_server; return (NULL); } /* * Should be used for the gfs_connection created by gfs_client_connect(). * Shouldn't be used for the gfs_connection created by gfs_client_connection(). */ char * gfs_client_disconnect(struct gfs_connection *gfs_server) { char *e = xxx_connection_free(gfs_server->conn); /* XXX - gfs_server->context should be NULL here */ free(gfs_server->hostname); free(gfs_server); return (e); } /* * multiplexed version of gfs_client_connect() for parallel authentication */ struct gfs_client_connect_state { struct gfarm_eventqueue *q; struct gfarm_event *writable; struct sockaddr peer_addr; void (*continuation)(void *); void *closure; struct gfs_connection *gfs_server; struct gfarm_auth_request_state *auth_state; /* results */ char *error; }; static void gfs_client_connect_end_auth(void *closure) { struct gfs_client_connect_state *state = closure; state->error = gfarm_auth_result_multiplexed( state->auth_state, &state->gfs_server->auth_method); if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfs_client_connect_start_auth(int events, int fd, void *closure, const struct timeval *t) { struct gfs_client_connect_state *state = closure; int error; socklen_t error_size = sizeof(error); int rv = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &error_size); if (rv == -1) { /* Solaris, see UNP by rstevens */ state->error = gfarm_errno_to_error(errno); } else if (error != 0) { state->error = gfarm_errno_to_error(error); } else { /* successfully connected */ state->error = gfarm_auth_request_multiplexed(state->q, state->gfs_server->conn, state->gfs_server->hostname, &state->peer_addr, gfs_client_connect_end_auth, state, &state->auth_state); if (state->error == NULL) { /* * call auth_request, * then go to gfs_client_connect_end_auth() */ return; } } if (state->continuation != NULL) (*state->continuation)(state->closure); } char * gfs_client_connect_request_multiplexed(struct gfarm_eventqueue *q, char *canonical_hostname, struct sockaddr *peer_addr, void (*continuation)(void *), void *closure, struct gfs_client_connect_state **statepp) { char *e; int rv, sock; struct gfs_connection *gfs_server; struct gfs_client_connect_state *state; int connection_in_progress; /* clone of gfs_client_connection0() */ sock = socket(PF_INET, SOCK_STREAM, 0); if (sock == -1) return (gfarm_errno_to_error(errno)); fcntl(sock, F_SETFD, 1); /* automatically close() on exec(2) */ /* XXX - how to report setsockopt(2) failure ? */ gfarm_sockopt_apply_by_name_addr(sock, canonical_hostname, peer_addr); fcntl(sock, F_SETFL, O_NONBLOCK); if (connect(sock, peer_addr, sizeof(*peer_addr)) < 0) { if (errno != EINPROGRESS) { e = gfarm_errno_to_error(errno); close(sock); return (e); } connection_in_progress = 1; } else { connection_in_progress = 0; } fcntl(sock, F_SETFL, 0); /* clear O_NONBLOCK */ gfs_server = malloc(sizeof(*gfs_server)); if (gfs_server == NULL) { close(sock); return (GFARM_ERR_NO_MEMORY); } e = xxx_fd_connection_new(sock, &gfs_server->conn); if (e != NULL) { free(gfs_server); close(sock); return (e); } gfs_server->context = NULL; gfs_server->hostname = strdup(canonical_hostname); if (gfs_server->hostname == NULL) { xxx_connection_free(gfs_server->conn); free(gfs_server); return (GFARM_ERR_NO_MEMORY); } state = malloc(sizeof(*state)); if (state == NULL) { free(gfs_server->hostname); xxx_connection_free(gfs_server->conn); free(gfs_server); return (GFARM_ERR_NO_MEMORY); } state->q = q; state->peer_addr = *peer_addr; state->continuation = continuation; state->closure = closure; state->gfs_server = gfs_server; state->auth_state = NULL; state->error = NULL; if (connection_in_progress) { state->writable = gfarm_fd_event_alloc(GFARM_EVENT_WRITE, sock, gfs_client_connect_start_auth, state); if (state->writable == NULL) { e = GFARM_ERR_NO_MEMORY; } else if ((rv = gfarm_eventqueue_add_event(q, state->writable, NULL)) == 0) { *statepp = state; /* go to gfs_client_connect_start_auth() */ return (0); } else { e = gfarm_errno_to_error(rv); gfarm_event_free(state->writable); } } else { state->writable = NULL; e = gfarm_auth_request_multiplexed(q, gfs_server->conn, gfs_server->hostname, &state->peer_addr, gfs_client_connect_end_auth, state, &state->auth_state); if (e == NULL) { *statepp = state; /* * call gfarm_auth_request, * then go to gfs_client_connect_end_auth() */ return (0); } } free(state); free(gfs_server->hostname); xxx_connection_free(gfs_server->conn); free(gfs_server); return (e); } char * gfs_client_connect_result_multiplexed(struct gfs_client_connect_state *state, struct gfs_connection **gfs_serverp) { char *e = state->error; struct gfs_connection *gfs_server = state->gfs_server; if (state->writable != NULL) gfarm_event_free(state->writable); free(state); if (e != NULL) { gfs_client_disconnect(gfs_server); return (e); } *gfs_serverp = gfs_server; return (NULL); } /* * gfs_client RPC */ char * gfs_client_rpc_request(struct gfs_connection *gfs_server, int command, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_vrpc_request(gfs_server->conn, command, &format, &ap); va_end(ap); return (e); } char * gfs_client_rpc_result(struct gfs_connection *gfs_server, int just, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc_result(gfs_server->conn, just, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfs_proto_error_string(error)); return (NULL); } char * gfs_client_rpc(struct gfs_connection *gfs_server, int just, int command, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc(gfs_server->conn, just, command, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfs_proto_error_string(error)); return (NULL); } char * gfs_client_open(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t flag, gfarm_int32_t mode, gfarm_int32_t *fdp) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_OPEN, "sii/i", gfarm_file, flag, mode, fdp)); } char * gfs_client_close(struct gfs_connection *gfs_server, gfarm_int32_t fd) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CLOSE, "i/", fd)); } char * gfs_client_seek(struct gfs_connection *gfs_server, gfarm_int32_t fd, file_offset_t offset, gfarm_int32_t whence, file_offset_t *resultp) { file_offset_t dummy; if (resultp == NULL) resultp = &dummy; return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_SEEK, "ioi/o", fd, offset, whence, resultp)); } char * gfs_client_read(struct gfs_connection *gfs_server, gfarm_int32_t fd, void *buffer, size_t size, size_t *np) { char *e; e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_READ, "ii/b", fd, (int)size, size, np, buffer); if (e != NULL) return (e); if (*np > size) return ("gfs_pio_read: protocol error"); return (NULL); } char * gfs_client_write(struct gfs_connection *gfs_server, gfarm_int32_t fd, const void *buffer, size_t size, size_t *np) { char *e; gfarm_int32_t n; /* size_t may be 64bit */ e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_WRITE, "ib/i", fd, size, buffer, &n); if (e != NULL) return (e); *np = n; if (n > size) return ("gfs_pio_write: protocol error"); return (NULL); } char * gfs_client_link(struct gfs_connection *gfs_server, char *from, char *to) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_LINK, "ss/", from, to)); } char * gfs_client_unlink(struct gfs_connection *gfs_server, char *path) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_UNLINK, "s/", path)); } char * gfs_client_rename(struct gfs_connection *gfs_server, char *from, char *to) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_RENAME, "ss/", from, to)); } char * gfs_client_chdir(struct gfs_connection *gfs_server, char *dir) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHDIR, "s/", dir)); } char * gfs_client_mkdir(struct gfs_connection *gfs_server, char *dir, gfarm_int32_t mode) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_MKDIR, "si/", dir, mode)); } char * gfs_client_rmdir(struct gfs_connection *gfs_server, char *dir) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_RMDIR, "s/", dir)); } char * gfs_client_chmod(struct gfs_connection *gfs_server, char *path, gfarm_int32_t mode) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHMOD, "si/", path, mode)); } char * gfs_client_chgrp(struct gfs_connection *gfs_server, char *path, char *group) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHGRP, "ss/", path, group)); } char * gfs_client_exist(struct gfs_connection *gfs_server, char *path) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_EXIST, "s/", path)); } char * gfs_client_digest(struct gfs_connection *gfs_server, int fd, char *digest_type, size_t digest_size, size_t *digest_length, unsigned char *digest, file_offset_t *filesize) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_DIGEST, "is/bo", fd, digest_type, digest_size, digest_length, digest, filesize)); } char * gfs_client_get_spool_root(struct gfs_connection *gfs_server, char **spool_rootp) { char *e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_GET_SPOOL_ROOT, "/s", spool_rootp); if (e != NULL) return (e); return (*spool_rootp == NULL ? GFARM_ERR_NO_MEMORY : NULL); } /* ********************************************************************** * Implementation of old (inner gfsd) replication protocol ********************************************************************** */ /* We keep this protocol for protocol compatibility and bootstrapping */ char * gfs_client_copyin(struct gfs_connection *gfs_server, int src_fd, int fd, long sync_rate) { int i, rv, eof; long written; char *e, *e_tmp; char buffer[GFS_PROTO_MAX_IOSIZE]; #ifdef XXX_MEASURE_CKSUM_COST /* XXX: should be passed from caller */ EVP_MD_CTX md_ctx; unsigned int md_len; unsigned char md_value[EVP_MAX_MD_SIZE]; const EVP_MD *md_type = EVP_md5(); /* XXX GFS_DEFAULT_DIGEST_MODE; */ EVP_DigestInit(&md_ctx, md_type); #endif e = xxx_proto_send(gfs_server->conn, "ii", GFS_PROTO_BULKREAD, src_fd); if (e != NULL) return (e); written = 0; for (;;) { #ifdef XXX_SLOW size_t size; e = xxx_proto_recv(gfs_server->conn, 0, &eof, "b", sizeof(buffer), &size, buffer); if (e != NULL) break; if (eof) { e = GFARM_ERR_PROTOCOL; break; } if (size <= 0) break; #ifdef XXX_MEASURE_CKSUM_COST EVP_DigestUpdate(&md_ctx, buffer, size); #endif for (i = 0; i < size; i += rv) { rv = write(fd, buffer + i, size - i); if (rv <= 0) break; if (sync_rate != 0) { written += rv; if (written >= sync_rate) { written -= sync_rate; fdatasync(fd); } } } if (i < size) { /* * write(2) never returns 0, * so the following rv == 0 case is just warm fuzzy. */ e = gfarm_errno_to_error(rv == 0 ? ENOSPC : errno); break; /* * XXX - we should return rest of data, * even if write(2) fails. */ } #else gfarm_int32_t size; /* XXX - FIXME layering violation */ e = xxx_proto_recv(gfs_server->conn, 0, &eof, "i", &size); if (e != NULL) break; if (eof) { e = GFARM_ERR_PROTOCOL; break; } if (size <= 0) break; do { /* XXX - FIXME layering violation */ int partial = xxx_recv_partial(gfs_server->conn, 0, buffer, size); if (partial <= 0) return (GFARM_ERR_PROTOCOL); #ifdef XXX_MEASURE_CKSUM_COST EVP_DigestUpdate(&md_ctx, buffer, partial); #endif size -= partial; #ifdef __GNUC__ /* shut up stupid warning by gcc */ rv = 0; #endif for (i = 0; i < partial; i += rv) { rv = write(fd, buffer + i, partial - i); if (rv <= 0) break; if (sync_rate != 0) { written += rv; if (written >= sync_rate) { written -= sync_rate; fdatasync(fd); } } } if (i < partial) { /* * write(2) never returns 0, * so the following rv == 0 case is * just warm fuzzy. */ return (gfarm_errno_to_error( rv == 0 ? ENOSPC : errno)); /* * XXX - we should return rest of data, * even if write(2) fails. */ } } while (size > 0); #endif } #ifdef XXX_MEASURE_CKSUM_COST /* should be returned to caller */ EVP_DigestFinal(&md_ctx, md_value, &md_len); #endif e_tmp = gfs_client_rpc_result(gfs_server, 0, ""); return (e != NULL ? e : e_tmp); } /* We keep this protocol for protocol compatibility */ struct gfs_client_striping_copyin_context { int ofd; file_offset_t offset; file_offset_t size; int interleave_factor; file_offset_t full_stripe_size; file_offset_t chunk_residual; int io_residual; int flags; #define GCSCC_FINISHED 1 }; /* XXX CKSUM */ char * gfs_client_striping_copyin_request(struct gfs_connection *gfs_server, int src_fd, int ofd, file_offset_t offset, file_offset_t size, int interleave_factor, file_offset_t full_stripe_size) { char *e = gfs_client_rpc_request(gfs_server, GFS_PROTO_STRIPING_READ, "iooio", src_fd, offset, size, interleave_factor, full_stripe_size); struct gfs_client_striping_copyin_context *cc; if (e != NULL) return (e); e = xxx_proto_flush(gfs_server->conn); if (e != NULL) return (e); cc = malloc(sizeof(struct gfs_client_striping_copyin_context)); gfs_server->context = cc; assert(cc != NULL); cc->ofd = ofd; cc->offset = offset; cc->size = size; cc->interleave_factor = interleave_factor; cc->full_stripe_size = full_stripe_size; cc->chunk_residual = cc->interleave_factor == 0 ? cc->size : cc->interleave_factor; cc->io_residual = 0; cc->flags = 0; return (NULL); } char * gfs_client_striping_copyin_partial(struct gfs_connection *gfs_server, int *rvp) { struct gfs_client_striping_copyin_context *cc = gfs_server->context; char *e; int eof, partial, i, rv; gfarm_int32_t size; char buffer[GFS_PROTO_MAX_IOSIZE]; if (cc->flags & GCSCC_FINISHED) { *rvp = 0; return (NULL); } if (cc->chunk_residual == 0) { /* assert(cc->interleave_factor != 0); */ cc->chunk_residual = cc->interleave_factor; cc->io_residual = 0; cc->offset += cc->full_stripe_size - cc->interleave_factor; } if (cc->io_residual == 0) { /* * Because we use select(2)/poll(2) as a subsequent i/o * of this statement, we must read just one int32 data only. * Otherwise the select(2)/poll(2) cannot see that * this stream is readable. */ /* XXX - FIXME layering violation */ e = xxx_proto_recv(gfs_server->conn, 1, &eof, "i", &size); if (e != NULL) { cc->flags |= GCSCC_FINISHED; return (e); } if (eof) { cc->flags |= GCSCC_FINISHED; return (GFARM_ERR_PROTOCOL); } if (size <= 0) { cc->flags |= GCSCC_FINISHED; *rvp = size; return (NULL); } cc->io_residual = size; } /* * Because we use select(2)/poll(2) as a subsequent i/o * of this statement, we must read just `size' bytes only. * Otherwise the select(2)/poll(2) cannot see that * this stream is readable. */ /* XXX - FIXME layering violation */ partial = xxx_recv_partial(gfs_server->conn, 1, buffer, cc->io_residual); if (partial == 0) return (GFARM_ERR_PROTOCOL); #ifdef XXX_MEASURE_CKSUM_COST /* XXX - we cannot calculate checksum on parallel case. */ #endif /* We assume that each block never goes across any chunk. */ cc->io_residual -= partial; cc->chunk_residual -= partial; #ifndef HAVE_PWRITE if (lseek(cc->ofd, (off_t)cc->offset, SEEK_SET) == -1) return (gfarm_errno_to_error(errno)); #endif #ifdef __GNUC__ /* shut up stupid warning by gcc */ rv = 0; #endif for (i = 0; i < partial; i += rv) { #ifndef HAVE_PWRITE rv = write(cc->ofd, buffer + i, partial - i); #else rv = pwrite(cc->ofd, buffer + i, partial - i, (off_t)cc->offset + i); #endif if (rv <= 0) break; } cc->offset += partial; if (i < partial) { /* * write(2) never returns 0, * so the following rv == 0 case is * just warm fuzzy. */ return (gfarm_errno_to_error(rv == 0 ? ENOSPC : errno)); /* * XXX - we should return rest of data, * even if write(2) fails. */ } *rvp = partial; return (NULL); } char * gfs_client_striping_copyin_result(struct gfs_connection *gfs_server) { struct gfs_client_striping_copyin_context *cc = gfs_server->context; char *e, *e_save = NULL; int rv; while ((cc->flags & GCSCC_FINISHED) == 0) { e = gfs_client_striping_copyin_partial(gfs_server, &rv); if (e != NULL && e_save == NULL) e_save = e; } free(gfs_server->context); gfs_server->context = NULL; e = gfs_client_rpc_result(gfs_server, 0, ""); return (e != NULL ? e : e_save); } char * gfs_client_striping_copyin(struct gfs_connection *gfs_server, int src_fd, int ofd, file_offset_t offset, file_offset_t size, int interleave_factor, file_offset_t full_stripe_size) { char *e; e = gfs_client_striping_copyin_request(gfs_server, src_fd, ofd, offset, size, interleave_factor, full_stripe_size); if (e != NULL) return (e); return (gfs_client_striping_copyin_result(gfs_server)); } /* We keep this for bootstrapping */ char * gfs_client_bootstrap_replicate_file_sequential_request( struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, char *srchost) { return (gfs_client_rpc_request(gfs_server, GFS_PROTO_REPLICATE_FILE_SEQUENTIAL, "sis", gfarm_file, mode, srchost)); } /* Perhaps this isn't needed any more, or we can use this for bootstrapping */ char * gfs_client_bootstrap_replicate_file_parallel_request( struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, gfarm_int32_t ndivisions, gfarm_int32_t interleave_factor, char *srchost) { return (gfs_client_rpc_request(gfs_server, GFS_PROTO_REPLICATE_FILE_PARALLEL, "sioiis", gfarm_file, mode, file_size, ndivisions, interleave_factor, srchost)); } char * gfs_client_bootstrap_replicate_file_result(struct gfs_connection *gfs_server) { return (gfs_client_rpc_result(gfs_server, 0, "")); } char * gfs_client_bootstrap_replicate_file_request(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname) { char *e; struct sockaddr peer_addr; long parallel_streams, stripe_unit_size; /* * netparam is evaluated here rather than in gfsd, * so, settings in user's .gfarmrc can be reflected. * * XXX - but this also means that settings in frontend host * is used, rather than settings in the host which does * actual transfer. */ e = gfarm_host_address_get(src_if_hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_parallel_streams, src_canonical_hostname, (struct sockaddr *)&peer_addr, &parallel_streams); if (e != NULL) /* shouldn't happen */ return (e); if (parallel_streams <= 1) return (gfs_client_bootstrap_replicate_file_sequential_request( gfs_server, gfarm_file, mode, src_if_hostname)); e = gfarm_netparam_config_get_long( &gfarm_netparam_stripe_unit_size, src_canonical_hostname, (struct sockaddr *)&peer_addr, &stripe_unit_size); if (e != NULL) /* shouldn't happen */ return (e); return ( gfs_client_bootstrap_replicate_file_parallel_request(gfs_server, gfarm_file, mode, file_size, parallel_streams, stripe_unit_size, src_if_hostname)); } char * gfs_client_bootstrap_replicate_file(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname) { char *e; e = gfs_client_bootstrap_replicate_file_request(gfs_server, gfarm_file, mode, file_size, src_canonical_hostname, src_if_hostname); if (e == NULL) e = gfs_client_bootstrap_replicate_file_result(gfs_server); return (e); } /* ********************************************************************** * Implementation of gfs_client_command() ********************************************************************** */ struct gfs_client_command_context { struct gfarm_iobuffer *iobuffer[NFDESC]; enum { GFS_COMMAND_SERVER_STATE_NEUTRAL, GFS_COMMAND_SERVER_STATE_OUTPUT, GFS_COMMAND_SERVER_STATE_EXITED, GFS_COMMAND_SERVER_STATE_ABORTED } server_state; int server_output_fd; int server_output_residual; enum { GFS_COMMAND_CLIENT_STATE_NEUTRAL, GFS_COMMAND_CLIENT_STATE_OUTPUT } client_state; int client_output_residual; int pid; int pending_signal; }; void gfs_client_command_set_stdin(struct gfs_connection *gfs_server, int (*rf)(struct gfarm_iobuffer *, void *, int, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_read(cc->iobuffer[FDESC_STDIN], rf, cookie, fd); } void gfs_client_command_set_stdout(struct gfs_connection *gfs_server, int (*wf)(struct gfarm_iobuffer *, void *, int, void *, int), void (*wcf)(struct gfarm_iobuffer *, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_write(cc->iobuffer[FDESC_STDOUT], wf, cookie, fd); gfarm_iobuffer_set_write_close(cc->iobuffer[FDESC_STDOUT], wcf); } void gfs_client_command_set_stderr(struct gfs_connection *gfs_server, int (*wf)(struct gfarm_iobuffer *, void *, int, void *, int), void (*wcf)(struct gfarm_iobuffer *, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_write(cc->iobuffer[FDESC_STDERR], wf, cookie, fd); gfarm_iobuffer_set_write_close(cc->iobuffer[FDESC_STDERR], wcf); } char *gfs_client_command_request(struct gfs_connection *gfs_server, char *path, char **argv, char **envp, int flags, int *pidp) { struct gfs_client_command_context *cc; int na = argv == NULL ? 0 : gfarm_strarray_length(argv); int ne = envp == NULL ? 0 : gfarm_strarray_length(envp); int conn_fd = xxx_connection_fd(gfs_server->conn); int i, xenv_copy, xauth_copy; gfarm_int32_t pid; socklen_t siz; char *e; static char *xdisplay_name_cache = NULL; static char *xdisplay_env_cache = NULL; static int xauth_cached = 0; static char *xauth_cache = NULL; char *dpy; if ((dpy = getenv("DISPLAY")) != NULL && xdisplay_name_cache == NULL && (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) != 0) { /* * get $DISPLAY to `xdisplay_name_cache', * and set "DISPLAY=$DISPLAY" to `xdisplay_env_cache'. */ static char xdisplay_env_format[] = "DISPLAY=%s"; static char local_prefix[] = "unix:"; char *prefix; if (*dpy == ':') { prefix = gfarm_host_get_self_name(); } else if (memcmp(dpy, local_prefix, sizeof(local_prefix) - 1) == 0) { prefix = gfarm_host_get_self_name(); dpy += sizeof(local_prefix) - 1 - 1; } else { prefix = ""; } xdisplay_name_cache = malloc(strlen(prefix) + strlen(dpy) + 1); if (xdisplay_name_cache == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(xdisplay_name_cache, "%s%s", prefix, dpy); xdisplay_env_cache = malloc(sizeof(xdisplay_env_format) + strlen(xdisplay_name_cache)); if (xdisplay_env_cache == NULL) { free(xdisplay_name_cache); xdisplay_name_cache = NULL; return (GFARM_ERR_NO_MEMORY); } sprintf(xdisplay_env_cache, xdisplay_env_format, xdisplay_name_cache); } if ((flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) == GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY && xdisplay_name_cache != NULL && !xauth_cached) { /* * get xauth data to `xauth_cache' */ static char xauth_command_format[] = "%s nextract - %s 2>/dev/null"; char *xauth_command; FILE *fp; char *s, line[XAUTH_NEXTRACT_MAXLEN]; xauth_command = malloc(sizeof(xauth_command_format) + strlen(XAUTH_COMMAND) + strlen(xdisplay_name_cache)); if (xauth_command == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(xauth_command, xauth_command_format, XAUTH_COMMAND, xdisplay_name_cache); if ((fp = popen(xauth_command, "r")) == NULL) { free(xauth_command); return (GFARM_ERR_NO_MEMORY); } s = fgets(line, sizeof line, fp); pclose(fp); free(xauth_command); if (s != NULL) { xauth_cache = strdup(line); if (xauth_cache == NULL) { free(xdisplay_name_cache); return (GFARM_ERR_NO_MEMORY); } } xauth_cached = 1; } xenv_copy = (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) != 0 && xdisplay_env_cache != NULL; xauth_copy = (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) == GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY && xauth_cache != NULL; /* * don't pass * GFS_CLIENT_COMMAND_FLAG_STDIN_EOF and * GFS_CLIENT_COMMAND_FLAG_XENV_COPY flag via network */ e = gfs_client_rpc_request(gfs_server, GFS_PROTO_COMMAND, "siii", path, na, ne + (xenv_copy ? 1 : 0), ((flags & GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) ? GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND : 0) | (xauth_copy ? GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY : 0)); if (e != NULL) return (e); /* * argv */ for (i = 0; i < na; i++) { e = xxx_proto_send(gfs_server->conn, "s", argv[i]); if (e != NULL) return (e); } /* * envp */ for (i = 0; i < ne; i++) { e = xxx_proto_send(gfs_server->conn, "s", envp[i]); if (e != NULL) return (e); } if (xenv_copy) { e = xxx_proto_send(gfs_server->conn, "s", xdisplay_env_cache); if (e != NULL) return (e); } if (xauth_copy) { /* * xauth */ e = xxx_proto_send(gfs_server->conn, "s", xauth_cache); if (e != NULL) return (e); } /* we have to set `just' flag here */ e = gfs_client_rpc_result(gfs_server, 1, "i", &pid); if (e != NULL) return (e); cc = gfs_server->context = malloc(sizeof(struct gfs_client_command_context)); if (gfs_server->context == NULL) return (GFARM_ERR_NO_MEMORY); /* * Now, we set the connection file descriptor non-blocking mode. */ if (fcntl(conn_fd, F_SETFL, O_NONBLOCK) == -1) { free(gfs_server->context); gfs_server->context = NULL; return (gfarm_errno_to_error(errno)); } /* * initialize gfs_server->context by default values */ siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_SNDBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDIN] = gfarm_iobuffer_alloc(i); siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_RCVBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDOUT] = gfarm_iobuffer_alloc(i); cc->iobuffer[FDESC_STDERR] = gfarm_iobuffer_alloc(i); gfarm_iobuffer_set_nonblocking_read_fd( cc->iobuffer[FDESC_STDIN], FDESC_STDIN); gfarm_iobuffer_set_nonblocking_write_xxx( cc->iobuffer[FDESC_STDIN], gfs_server->conn); gfarm_iobuffer_set_nonblocking_read_xxx( cc->iobuffer[FDESC_STDOUT], gfs_server->conn); gfarm_iobuffer_set_nonblocking_write_fd( cc->iobuffer[FDESC_STDOUT], FDESC_STDOUT); gfarm_iobuffer_set_nonblocking_read_xxx( cc->iobuffer[FDESC_STDERR], gfs_server->conn); gfarm_iobuffer_set_nonblocking_write_fd( cc->iobuffer[FDESC_STDERR], FDESC_STDERR); if ((flags & GFS_CLIENT_COMMAND_FLAG_STDIN_EOF) != 0) gfarm_iobuffer_set_read_eof(cc->iobuffer[FDESC_STDIN]); cc->server_state = GFS_COMMAND_SERVER_STATE_NEUTRAL; cc->client_state = GFS_COMMAND_CLIENT_STATE_NEUTRAL; cc->pending_signal = 0; *pidp = cc->pid = pid; return (e); } int gfs_client_command_is_running(struct gfs_connection *gfs_server) { struct gfs_client_command_context *cc = gfs_server->context; return (cc->server_state != GFS_COMMAND_SERVER_STATE_EXITED && cc->server_state != GFS_COMMAND_SERVER_STATE_ABORTED); } char * gfs_client_command_fd_set(struct gfs_connection *gfs_server, fd_set *readable, fd_set *writable, int *max_fdp) { struct gfs_client_command_context *cc = gfs_server->context; int conn_fd = xxx_connection_fd(gfs_server->conn); int i, fd; /* * The following test condition should just match with * the i/o condition in gfs_client_command_io_fd_set(), * otherwise unneeded busy wait happens. */ if (cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL || (cc->server_state == GFS_COMMAND_SERVER_STATE_OUTPUT && gfarm_iobuffer_is_readable(cc->iobuffer[cc->server_output_fd]))) { FD_SET(conn_fd, readable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if ((cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL && (cc->pending_signal || gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDIN]))) || cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT) { FD_SET(conn_fd, writable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if (gfarm_iobuffer_is_readable(cc->iobuffer[FDESC_STDIN])) { fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDIN]); if (fd < 0) { gfarm_iobuffer_read(cc->iobuffer[FDESC_STDIN], NULL); /* XXX - if the callback sets an error? */ } else { FD_SET(fd, readable); if (*max_fdp < fd) *max_fdp = fd; } } for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { if (gfarm_iobuffer_is_writable(cc->iobuffer[i])) { fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[i]); if (fd < 0) { gfarm_iobuffer_write(cc->iobuffer[i], NULL); /* XXX - if the callback sets an error? */ } else { FD_SET(fd, writable); if (*max_fdp < fd) *max_fdp = fd; } } } return (NULL); } char * gfs_client_command_io_fd_set(struct gfs_connection *gfs_server, fd_set *readable, fd_set *writable) { char *e; struct gfs_client_command_context *cc = gfs_server->context; int i, fd, conn_fd = xxx_connection_fd(gfs_server->conn); fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDIN]); if (fd >= 0 && FD_ISSET(fd, readable)) { gfarm_iobuffer_read(cc->iobuffer[FDESC_STDIN], NULL); e = gfarm_iobuffer_get_error(cc->iobuffer[FDESC_STDIN]); if (e != NULL) { /* treat this as eof */ gfarm_iobuffer_set_read_eof(cc->iobuffer[FDESC_STDIN]); /* XXX - how to report this error? */ gfarm_iobuffer_set_error(cc->iobuffer[FDESC_STDIN], NULL); } } for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[i]); if (fd < 0 || !FD_ISSET(fd, writable)) continue; gfarm_iobuffer_write(cc->iobuffer[i], NULL); e = gfarm_iobuffer_get_error(cc->iobuffer[i]); if (e == NULL) continue; /* XXX - just purge the content */ gfarm_iobuffer_purge(cc->iobuffer[i], NULL); /* XXX - how to report this error? */ gfarm_iobuffer_set_error(cc->iobuffer[i], NULL); } if (FD_ISSET(conn_fd, readable)) { if (cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL) { gfarm_int32_t cmd, fd, len; int eof; char *e; e = xxx_proto_recv(gfs_server->conn, 1, &eof, "i", &cmd); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_GFSD_ABORTED; cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } switch (cmd) { case GFS_PROTO_COMMAND_EXITED: cc->server_state = GFS_COMMAND_SERVER_STATE_EXITED; break; case GFS_PROTO_COMMAND_FD_OUTPUT: e = xxx_proto_recv(gfs_server->conn, 1, &eof, "ii", &fd, &len); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_GFSD_ABORTED; cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } if (fd != FDESC_STDOUT && fd != FDESC_STDERR) { /* XXX - something wrong */ cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return ("illegal gfsd descriptor"); } if (len <= 0) { /* notify closed */ gfarm_iobuffer_set_read_eof( cc->iobuffer[fd]); } else { cc->server_state = GFS_COMMAND_SERVER_STATE_OUTPUT; cc->server_output_fd = fd; cc->server_output_residual = len; } break; default: /* XXX - something wrong */ cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return ("unknown gfsd reply"); } } else if (cc->server_state==GFS_COMMAND_SERVER_STATE_OUTPUT) { gfarm_iobuffer_read(cc->iobuffer[cc->server_output_fd], &cc->server_output_residual); if (cc->server_output_residual == 0) cc->server_state = GFS_COMMAND_SERVER_STATE_NEUTRAL; e = gfarm_iobuffer_get_error( cc->iobuffer[cc->server_output_fd]); if (e != NULL) { /* treat this as eof */ gfarm_iobuffer_set_read_eof( cc->iobuffer[cc->server_output_fd]); gfarm_iobuffer_set_error( cc->iobuffer[cc->server_output_fd], NULL); cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } if (gfarm_iobuffer_is_read_eof( cc->iobuffer[cc->server_output_fd])) { cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (GFARM_ERR_GFSD_ABORTED); } } } if (FD_ISSET(conn_fd, writable) && gfs_client_command_is_running(gfs_server)) { if (cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL) { if (cc->pending_signal) { e = xxx_proto_send(gfs_server->conn, "ii", GFS_PROTO_COMMAND_SEND_SIGNAL, cc->pending_signal); if (e != NULL || (e = xxx_proto_flush(gfs_server->conn)) != NULL) { cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } } else if (gfarm_iobuffer_is_writable( cc->iobuffer[FDESC_STDIN])) { /* * cc->client_output_residual may be 0, * if stdin reaches EOF. */ cc->client_output_residual = gfarm_iobuffer_avail_length( cc->iobuffer[FDESC_STDIN]); e = xxx_proto_send(gfs_server->conn, "iii", GFS_PROTO_COMMAND_FD_INPUT, FDESC_STDIN, cc->client_output_residual); if (e != NULL || (e = xxx_proto_flush(gfs_server->conn)) != NULL) { cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } cc->client_state = GFS_COMMAND_CLIENT_STATE_OUTPUT; } } else if (cc->client_state==GFS_COMMAND_CLIENT_STATE_OUTPUT) { gfarm_iobuffer_write(cc->iobuffer[FDESC_STDIN], &cc->client_output_residual); if (cc->client_output_residual == 0) cc->client_state = GFS_COMMAND_CLIENT_STATE_NEUTRAL; e = gfarm_iobuffer_get_error( cc->iobuffer[FDESC_STDIN]); if (e != NULL) { cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; gfarm_iobuffer_set_error( cc->iobuffer[FDESC_STDIN], NULL); return (e); } } } return (NULL); } char * gfs_client_command_io(struct gfs_connection *gfs_server, struct timeval *timeout) { int nfound, max_fd; fd_set readable, writable; char *e = NULL; if (!gfs_client_command_is_running(gfs_server)) return (NULL); max_fd = -1; FD_ZERO(&readable); FD_ZERO(&writable); gfs_client_command_fd_set(gfs_server, &readable, &writable, &max_fd); if (max_fd >= 0) { nfound = select(max_fd + 1, &readable, &writable, NULL, timeout); if (nfound > 0) { e = gfs_client_command_io_fd_set(gfs_server, &readable, &writable); } else if (nfound == -1 && errno != EINTR) { e = gfarm_errno_to_error(errno); } } return (e); } int gfs_client_command_send_stdin(struct gfs_connection *gfs_server, void *data, int len) { struct gfs_client_command_context *cc = gfs_server->context; char *p = data; int residual = len, rv; while (residual > 0 && gfs_client_command_is_running(gfs_server)) { rv = gfarm_iobuffer_put(cc->iobuffer[FDESC_STDIN], p, residual); p += rv; residual -= rv; gfs_client_command_io(gfs_server, NULL); /* XXX - how to report this error? */ } return (len - residual); } void gfs_client_command_close_stdin(struct gfs_connection *gfs_server) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_read_eof(cc->iobuffer[FDESC_STDIN]); } char * gfs_client_command_send_signal(struct gfs_connection *gfs_server, int sig) { char *e; struct gfs_client_command_context *cc = gfs_server->context; while (gfs_client_command_is_running(gfs_server) && cc->pending_signal != 0) { e = gfs_client_command_io(gfs_server, NULL); if (e != NULL) return (e); } if (!gfs_client_command_is_running(gfs_server)) return (gfarm_errno_to_error(ESRCH)); cc->pending_signal = sig; /* make a chance to send the signal immediately */ return (gfs_client_command_io(gfs_server, NULL)); } char * gfs_client_command_result(struct gfs_connection *gfs_server, int *term_signal, int *exit_status, int *exit_flag) { struct gfs_client_command_context *cc = gfs_server->context; char *e; while (gfs_client_command_is_running(gfs_server)) { gfs_client_command_io(gfs_server, NULL); /* XXX - how to report this error? */ } /* * flush stdout/stderr */ while (gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDOUT]) || gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDERR])) { int i, nfound, fd, max_fd = -1; fd_set writable; FD_ZERO(&writable); for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { if (gfarm_iobuffer_is_writable(cc->iobuffer[i])) { fd = gfarm_iobuffer_get_write_fd( cc->iobuffer[i]); if (fd < 0) { gfarm_iobuffer_write(cc->iobuffer[i], NULL); /* * XXX - if the callback sets an error? */ } else { FD_SET(fd, &writable); if (max_fd < fd) max_fd = fd; } } } if (max_fd < 0) continue; nfound = select(max_fd + 1, NULL, &writable, NULL, NULL); if (nfound == -1 && errno != EINTR) break; if (nfound > 0) { for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { fd = gfarm_iobuffer_get_write_fd( cc->iobuffer[i]); if (fd < 0 || !FD_ISSET(fd, &writable)) continue; gfarm_iobuffer_write(cc->iobuffer[i], NULL); e = gfarm_iobuffer_get_error(cc->iobuffer[i]); if (e == NULL) continue; /* XXX - just purge the content */ gfarm_iobuffer_purge(cc->iobuffer[i], NULL); /* XXX - how to report this error? */ gfarm_iobuffer_set_error(cc->iobuffer[i],NULL); } } } /* * context isn't needed anymore */ gfarm_iobuffer_free(cc->iobuffer[FDESC_STDIN]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDOUT]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDERR]); free(gfs_server->context); gfs_server->context = NULL; /* * Now, we recover the connection file descriptor blocking mode. */ if (fcntl(xxx_connection_fd(gfs_server->conn), F_SETFL, 0) == -1) { return (gfarm_errno_to_error(errno)); } return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_COMMAND_EXIT_STATUS, "/iii", term_signal, exit_status, exit_flag)); } char * gfs_client_command(struct gfs_connection *gfs_server, char *path, char **argv, char **envp, int flags, int *term_signal, int *exit_status, int *exit_flag) { char *e, *e2; int pid; e = gfs_client_command_request(gfs_server, path, argv, envp, flags, &pid); if (e) return (e); while (gfs_client_command_is_running(gfs_server)) e = gfs_client_command_io(gfs_server, NULL); e2 = gfs_client_command_result(gfs_server, term_signal, exit_status, exit_flag); return (e != NULL ? e : e2); } /* ********************************************************************** * gfsd datagram service ********************************************************************** */ int gfs_client_datagram_timeouts[] = { 10, 100, 1000, 2000 /* milli seconds */ }; int gfs_client_datagram_ntimeouts = GFARM_ARRAY_LENGTH(gfs_client_datagram_timeouts); /* * `server_addr_size' should be socklen_t, but that requires <sys/socket.h> * for all source files which include "gfs_client.h". */ char * gfs_client_get_load_request(int sock, struct sockaddr *server_addr, int server_addr_size) { int rv, command = 0; if (server_addr == NULL || server_addr_size == 0) { /* using connected UDP socket */ rv = write(sock, &command, sizeof(command)); } else { rv = sendto(sock, &command, sizeof(command), 0, server_addr, server_addr_size); } if (rv == -1) return (gfarm_errno_to_error(errno)); return (NULL); } /* * `*server_addr_sizep' is an IN/OUT parameter. * * `*server_addr_sizep' should be socklen_t, but that requires <sys/socket.h> * for all source files which include "gfs_client.h". */ char * gfs_client_get_load_result(int sock, struct sockaddr *server_addr, int *server_addr_sizep, struct gfs_client_load *result) { int rv; double loadavg[3]; #ifndef WORDS_BIGENDIAN struct { char c[8]; } nloadavg[3]; #else # define nloadavg loadavg #endif if (server_addr == NULL || server_addr_sizep == NULL) { /* caller doesn't need server_addr */ rv = read(sock, nloadavg, sizeof(nloadavg)); } else { rv = recvfrom(sock, nloadavg, sizeof(nloadavg), 0, server_addr, server_addr_sizep); } if (rv == -1) return (gfarm_errno_to_error(errno)); #ifndef WORDS_BIGENDIAN swab(&nloadavg[0], &loadavg[0], sizeof(loadavg[0])); swab(&nloadavg[1], &loadavg[1], sizeof(loadavg[1])); swab(&nloadavg[2], &loadavg[2], sizeof(loadavg[2])); #endif result->loadavg_1min = loadavg[0]; result->loadavg_5min = loadavg[1]; result->loadavg_15min = loadavg[2]; return (NULL); } /* * multiplexed version of gfs_client_get_load() */ struct gfs_client_get_load_state { struct gfarm_eventqueue *q; struct gfarm_event *writable, *readable; void (*continuation)(void *); void *closure; int sock; int try; /* results */ char *error; struct gfs_client_load load; }; static void gfs_client_get_load_send(int events, int fd, void *closure, const struct timeval *t) { struct gfs_client_get_load_state *state = closure; int rv; struct timeval timeout; state->error = gfs_client_get_load_request(state->sock, NULL, 0); if (state->error == NULL) { timeout.tv_sec = timeout.tv_usec = 0; gfarm_timeval_add_microsec(&timeout, gfs_client_datagram_timeouts[state->try] * GFARM_MILLISEC_BY_MICROSEC); if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout)) == 0) { /* go to gfs_client_get_load_receive() */ return; } state->error = gfarm_errno_to_error(rv); } close(state->sock); state->sock = -1; if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfs_client_get_load_receive(int events, int fd, void *closure, const struct timeval *t) { struct gfs_client_get_load_state *state = closure; int rv; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); ++state->try; if (state->try >= gfs_client_datagram_ntimeouts) { state->error = GFARM_ERR_CONNECTION_TIMED_OUT; } else if ((rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL)) == 0) { /* go to gfs_client_get_load_send() */ return; } else { state->error = gfarm_errno_to_error(rv); } } else { assert(events == GFARM_EVENT_READ); state->error = gfs_client_get_load_result(state->sock, NULL, NULL, &state->load); } close(state->sock); state->sock = -1; if (state->continuation != NULL) (*state->continuation)(state->closure); } char * gfs_client_get_load_request_multiplexed(struct gfarm_eventqueue *q, struct sockaddr *peer_addr, void (*continuation)(void *), void *closure, struct gfs_client_get_load_state **statepp) { char *e; int rv, sock; struct gfs_client_get_load_state *state; /* use different socket for each peer, to identify error code */ sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock == -1) { e = gfarm_errno_to_error(errno); goto error_return; } fcntl(sock, F_SETFD, 1); /* automatically close() on exec(2) */ /* connect UDP socket, to get error code */ if (connect(sock, peer_addr, sizeof(*peer_addr)) == -1) { e = gfarm_errno_to_error(errno); goto error_close_sock; } state = malloc(sizeof(*state)); if (state == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_close_sock; } state->writable = gfarm_fd_event_alloc( GFARM_EVENT_WRITE, sock, gfs_client_get_load_send, state); if (state->writable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_state; } /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, sock, gfs_client_get_load_receive, state); if (state->readable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_writable; } /* go to gfs_client_get_load_send() */ rv = gfarm_eventqueue_add_event(q, state->writable, NULL); if (rv != 0) { e = gfarm_errno_to_error(rv); goto error_free_readable; } state->q = q; state->continuation = continuation; state->closure = closure; state->sock = sock; state->try = 0; state->error = NULL; *statepp = state; return (NULL); error_free_readable: gfarm_event_free(state->readable); error_free_writable: gfarm_event_free(state->writable); error_free_state: free(state); error_close_sock: close(sock); error_return: return (e); } char * gfs_client_get_load_result_multiplexed( struct gfs_client_get_load_state *state, struct gfs_client_load *loadp) { char *error = state->error; if (state->sock >= 0) { /* sanity */ close(state->sock); state->sock = -1; } if (error == NULL) *loadp = state->load; gfarm_event_free(state->readable); gfarm_event_free(state->writable); free(state); return (error); } /* * gfs_client_apply_all_hosts() */ static int apply_one_host(char *(*op)(struct gfs_connection *, void *), char *hostname, void *args, char *message, int tolerant) { char *e; int pid; struct sockaddr addr; struct gfs_connection *conn; pid = fork(); if (pid) { /* parent or error */ return pid; } /* child */ /* * use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_initialize(); if (e != NULL) { if (message != NULL) fprintf(stderr, "%s: metadb initialization error: %s\n", message, e); _exit(1); } /* reflect "address_use" directive in the `hostname' */ e = gfarm_host_address_get(hostname, gfarm_spool_server_port, &addr, NULL); if (e != NULL) { if (message != NULL) fprintf(stderr, "%s: host %s: %s\n", message, hostname, e); _exit(2); } e = gfs_client_connect(hostname, &addr, &conn); if (e != NULL) { /* if tolerant, we allow failure to connect the host */ if (message != NULL && !tolerant) fprintf(stderr, "%s: connecting to %s: %s\n", message, hostname, e); _exit(tolerant ? 0 : 3); } e = (*op)(conn, args); if (e != NULL) { /* if tolerant, we allow "no such file or directory" */ if (message != NULL && (!tolerant || e != GFARM_ERR_NO_SUCH_OBJECT)) fprintf(stderr, "%s on %s: %s\n", message, hostname, e); _exit(tolerant && e == GFARM_ERR_NO_SUCH_OBJECT ? 0 : 4); } e = gfs_client_disconnect(conn); if (e != NULL) { if (message != NULL) fprintf(stderr, "%s: disconnecting to %s: %s\n", message, hostname, e); _exit(5); } _exit(0); } static char * wait_pid(int pids[], int num, int *nhosts_succeed) { char *e; int rv, s; e = NULL; while (--num >= 0) { while ((rv = waitpid(pids[num], &s, 0)) == -1 && errno == EINTR) ; if (rv == -1) { if (e == NULL) e = gfarm_errno_to_error(errno); } else if (WIFEXITED(s)) { if (WEXITSTATUS(s) == 0) (*nhosts_succeed)++; else e = "error happened on the operation"; } else { e = "operation aborted abnormally"; } } return (e); } #define CONCURRENCY 25 char * gfs_client_apply_all_hosts( char *(*op)(struct gfs_connection *, void *), void *args, char *message, int tolerant, int *nhosts_succeed) { char *e; int i, j, nhosts, pids[CONCURRENCY]; struct gfarm_host_info *hosts; e = gfarm_host_info_get_all(&nhosts, &hosts); if (e != NULL) return (e); /* * To use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_terminate(); if (e != NULL) goto finish_hosts; j = 0; *nhosts_succeed = 0; for (i = 0; i < nhosts; i++) { pids[j] = apply_one_host(op, hosts[i].hostname, args, message, tolerant); if (pids[j] < 0) /* fork error */ break; if (++j == CONCURRENCY) { e = wait_pid(pids, j, nhosts_succeed); j = 0; } } if (j > 0) e = wait_pid(pids, j, nhosts_succeed); /* * recover temporary closed metadb connection * * XXX: FIXME layering violation */ if (e != NULL) { gfarm_metadb_initialize(); } else { e = gfarm_metadb_initialize(); } finish_hosts: gfarm_host_info_free_all(nhosts, hosts); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_4/server/gfsd/gfsd_subr.h int gfsd_statfs(char *, gfarm_int32_t *, file_offset_t *, file_offset_t *, file_offset_t *, file_offset_t *, file_offset_t *, file_offset_t *); <file_sep>/gfarm/tags/gfarm_1_0_2/lib/libgfarm/gfarm/stringlist.c #include <stddef.h> #include <stdlib.h> #include <string.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfarm_stringlist.h> #define GFARM_STRINGLIST_INITIAL 50 #define GFARM_STRINGLIST_DELTA 50 /* gfarm_stringlist: variable size string array */ char * gfarm_stringlist_init(gfarm_stringlist *listp) { char **v; v = malloc(sizeof(char *) * GFARM_STRINGLIST_INITIAL); if (v == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = GFARM_STRINGLIST_INITIAL; listp->length = 0; listp->array = v; v[0] = NULL; return (NULL); } void gfarm_stringlist_free(gfarm_stringlist *listp) { free(listp->array); /* the following is not needed, but to make erroneous program abort */ listp->size = 0; listp->length = 0; listp->array = NULL; } void gfarm_stringlist_free_deeply(gfarm_stringlist *listp) { int i, length = gfarm_stringlist_length(listp); for (i = 0; i < length; i++) { if (listp->array[i] != NULL) free(listp->array[i]); } gfarm_stringlist_free(listp); } char * gfarm_stringlist_add_strings(gfarm_stringlist *listp, int al, char **av) { int ll = gfarm_stringlist_length(listp); if (ll + al > listp->size) { int n = listp->size; char **t; do { n += GFARM_STRINGLIST_DELTA; } while (ll + al > n); t = realloc(listp->array, sizeof(char *) * n); if (t == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = n; listp->array = t; } memcpy(&listp->array[ll], av, sizeof(char *) * al); listp->length += al; return (NULL); } char * gfarm_stringlist_add_list(gfarm_stringlist *listp, gfarm_stringlist *addp) { return (gfarm_stringlist_add_strings(listp, gfarm_stringlist_length(addp), addp->array)); } char * gfarm_stringlist_add(gfarm_stringlist *listp, char *s) { int length = gfarm_stringlist_length(listp); if (length >= listp->size) { int n = listp->size + GFARM_STRINGLIST_DELTA; char **t = realloc(listp->array, sizeof(char *) * n); if (t == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = n; listp->array = t; } listp->array[length] = s; listp->length++; return (NULL); } char * gfarm_stringlist_cat(gfarm_stringlist *listp, char **v) { return (gfarm_stringlist_add_strings(listp, gfarm_strarray_length(v), v)); } /* gfarm_fixedstrings: fixed length array of dynamically allocated strings */ char * gfarm_fixedstrings_dup(int n, char **dst, char **src) { int i; for (i = 0; i < n; i++) { dst[i] = strdup(src[i]); if (dst[i] == NULL) { while (--i >= 0) { free(dst[i]); dst[i] = NULL; } return (GFARM_ERR_NO_MEMORY); } } return (NULL); } /* gfarm_strings: dynamically allocated string array and array contents */ char ** gfarm_strings_alloc_from_stringlist(gfarm_stringlist *listp) { int n = gfarm_stringlist_length(listp); char **t = malloc(sizeof(char *) * n); if (t == NULL) return (NULL); memcpy(t, listp->array, sizeof(char *) * n); return (t); } void gfarm_strings_free_deeply(int n, char **strings) { int i; for (i = 0; i < n; i++) { if (strings[i] != NULL) free(strings[i]); } free(strings); } /* gfarm_array: NULL terminated gfarm_strings */ int gfarm_strarray_length(char **array) { int i; for (i = 0; array[i] != NULL; i++) ; return (i); } char ** gfarm_strarray_dup(char **array) { int n = gfarm_strarray_length(array); char **v = malloc(sizeof(char *) * (n + 1)); if (v == NULL) return (v); if (gfarm_fixedstrings_dup(n, v, array) != NULL) return (NULL); v[n] = NULL; return (v); } void gfarm_strarray_free(char **array) { int i; for (i = 0; array[i] != NULL; i++) free(array[i]); free(array); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/gftool/gfhost/gfhost.c /* * $Id$ */ #include <assert.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <limits.h> #include <errno.h> #include <gfarm/gfarm.h> #include "gfs_client.h" char *program_name = "gfhost"; static char * update_host(char *hostname, int nhostaliases, char **hostaliases, char *architecture, int ncpu, char *(*update_op)(char *, struct gfarm_host_info *)) { struct gfarm_host_info hi; hi.hostname = hostname; hi.nhostaliases = nhostaliases; hi.hostaliases = hostaliases; hi.architecture = architecture; hi.ncpu = ncpu; return ((*update_op)(hostname, &hi)); } static char * check_hostname(char *hostname) { char *e, *n; e = gfarm_host_get_canonical_name(hostname, &n); if (e == NULL || e == GFARM_ERR_AMBIGUOUS_RESULT) { if (e == NULL) free(n); return ("the hostname is already registered"); } return (NULL); } static char * check_hostaliases(int nhostaliases, char **hostaliases) { int i; for (i = 0; i < nhostaliases; i++) { if (check_hostname(hostaliases[i]) != NULL) return ("the hostalias is already registered"); } return (NULL); } char * add_host(char *hostname, char **hostaliases, char *architecture, int ncpu) { int nhostaliases = gfarm_strarray_length(hostaliases); char *e; e = check_hostname(hostname); if (e != NULL) return (e); e = check_hostaliases(nhostaliases, hostaliases); if (e != NULL) return (e); return (update_host(hostname, nhostaliases, hostaliases, architecture, ncpu, gfarm_host_info_set)); } char * gfarm_modify_host(char *hostname, char **hostaliases, char *architecture, int ncpu, int add_aliases) { char *e; struct gfarm_host_info hi; int host_info_needs_free = 0; gfarm_stringlist aliases; if (*hostaliases == NULL || architecture == NULL || ncpu < 1 || add_aliases) { e = gfarm_host_info_get(hostname, &hi); if (e != NULL) return (e); host_info_needs_free = 1; if (!add_aliases) { /* XXX - do check_hostaliases() here, too. */ hostaliases = hostaliases; } else { e = check_hostaliases( gfarm_strarray_length(hostaliases), hostaliases); if (e != NULL) goto free_host_info; e = gfarm_stringlist_init(&aliases); if (e != NULL) goto free_host_info; if (hi.hostaliases != NULL) { e = gfarm_stringlist_cat(&aliases, hi.hostaliases); if (e != NULL) goto free_aliases; } if (hostaliases != NULL) { e = gfarm_stringlist_cat(&aliases, hostaliases); if (e != NULL) goto free_aliases; } e = gfarm_stringlist_add(&aliases, NULL); if (e != NULL) goto free_aliases; hostaliases = GFARM_STRINGLIST_STRARRAY(aliases); } if (architecture == NULL) architecture = hi.architecture; if (ncpu < 1) ncpu = hi.ncpu; } e = update_host(hostname, gfarm_strarray_length(hostaliases), hostaliases, architecture, ncpu, gfarm_host_info_replace); if (e == NULL && !add_aliases && *hostaliases == NULL) e = gfarm_host_info_remove_hostaliases(hostname); free_aliases: if (add_aliases) gfarm_stringlist_free(&aliases); free_host_info: if (host_info_needs_free) gfarm_host_info_free(&hi); return (e); } char * validate_architecture(char *architecture) { unsigned char c, *s = (unsigned char *)architecture; while ((c = *s++) != '\0') { if (!isalnum(c) && c != '-' && c != '_' && c != '.') return ((char *)s - 1); } return (NULL); } char * validate_hostname(char *hostname) { unsigned char c, *s = (unsigned char *)hostname; while ((c = *s++) != '\0') { if (!isalnum(c) && c != '-' && c != '.') return ((char *)s - 1); } return (NULL); } char * invalid_input(int lineno) { fprintf(stderr, "line %d: invalid input format\n", lineno); fprintf(stderr, "%s: input must be " "\"<architecture> <ncpu> <hostname> <hostalias>...\" format\n", program_name); return (GFARM_ERR_INVALID_ARGUMENT); } #define LINE_BUFFER_SIZE 16384 #define MAX_HOSTALIASES 256 char * add_line(char *line, int lineno) { int len, ncpu, nhostaliases; char *e, *hostname, *architecture; char *hostaliases[MAX_HOSTALIASES + 1]; static char space[] = " \t"; /* parse architecture */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0 || line[len] == '\0') return (invalid_input(lineno)); line[len] = '\0'; architecture = line; line += len + 1; e = validate_architecture(architecture); if (e != NULL) { fprintf(stderr, "line %d: invalid character '%c' in architecture \"%s\"\n", lineno, *e, architecture); return (GFARM_ERR_INVALID_ARGUMENT); } /* parse ncpu */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0 || line[len] == '\0') return (invalid_input(lineno)); line[len] = '\0'; errno = 0; ncpu = strtol(line, &e, 0); if (e == line) { return (invalid_input(lineno)); } else if (*e != '\0') { fprintf(stderr, "line %d: garbage \"%s\" in ncpu \"%s\"\n", lineno, e, line); return (GFARM_ERR_INVALID_ARGUMENT); } else if (errno != 0 && (ncpu == LONG_MIN || ncpu == LONG_MAX)) { fprintf(stderr, "line %d: %s on \"%s\"\n", lineno, strerror(errno), line); return (GFARM_ERR_INVALID_ARGUMENT); } line += len + 1; /* parse hostname */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0) return (invalid_input(lineno)); hostname = line; if (line[len] == '\0') { line += len; } else { line[len] = '\0'; line += len + 1; } e = validate_hostname(hostname); if (e != NULL) { fprintf(stderr, "line %d: invalid character '%c' in hostname \"%s\"\n", lineno, *e, hostname); return (GFARM_ERR_INVALID_ARGUMENT); } /* parse hostaliases */ for (nhostaliases = 0;; nhostaliases++) { line += strspn(line, space); /* skip space */ if (*line == '\0') break; len = strcspn(line, space); /* assert(len > 0); */ if (nhostaliases >= MAX_HOSTALIASES) { fprintf(stderr, "line %d: " "number of hostaliases exceeds %d\n", lineno, nhostaliases); return (GFARM_ERR_INVALID_ARGUMENT); } hostaliases[nhostaliases] = line; if (line[len] == '\0') { line += len; } else { line[len] = '\0'; line += len + 1; } e = validate_hostname(hostaliases[nhostaliases]); if (e != NULL) { fprintf(stderr, "line %d: " "invalid character '%c' in hostalias \"%s\"\n", lineno, *e, hostaliases[nhostaliases]); return (GFARM_ERR_INVALID_ARGUMENT); } } hostaliases[nhostaliases] = NULL; e = add_host(hostname, hostaliases, architecture, ncpu); if (e != NULL) fprintf(stderr, "line %d: %s\n", lineno, e); return (e); } char * register_db(void) { char *e, *e_save = NULL; int len, lineno; char line[LINE_BUFFER_SIZE]; if (fgets(line, sizeof line, stdin) == NULL) return (NULL); len = strlen(line); for (lineno = 1;; lineno++) { if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } else { fprintf(stderr, "line %d: too long line\n", lineno); if (e_save == NULL) e_save = GFARM_ERR_INVALID_ARGUMENT; do { if (fgets(line, sizeof line, stdin) == NULL) return (e_save); len = strlen(line); } while (len == 0 || line[len - 1] != '\n'); continue; } e = add_line(line, lineno); if (e_save == NULL) e_save = e; if (fgets(line, sizeof line, stdin) == NULL) break; len = strlen(line); } return (e_save); } /* * handle option "-i" (ignore "address_use" directive in gfarm.conf(5)) */ char * resolv_addr_with_address_use(char *hostname, struct sockaddr *addr, char **if_hostnamep) { return (gfarm_host_address_get(hostname, gfarm_spool_server_port, addr, if_hostnamep)); } char * resolv_addr_without_address_use(char *hostname, struct sockaddr *addr, char **if_hostnamep) { /* sizeof(struct sockaddr_in) == sizeof(struct sockaddr) */ struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; struct hostent *hp; hp = gethostbyname(hostname); if (hp == NULL || hp->h_addrtype != AF_INET) return (GFARM_ERR_UNKNOWN_HOST); memset(addr_in, 0, sizeof(*addr_in)); memcpy(&addr_in->sin_addr, hp->h_addr, sizeof(addr_in->sin_addr)); addr_in->sin_family = hp->h_addrtype; addr_in->sin_port = htons(gfarm_spool_server_port); if (if_hostnamep != NULL) { *if_hostnamep = strdup(hostname); if (*if_hostnamep == NULL) return (GFARM_ERR_NO_MEMORY); } return (NULL); } char *(*opt_resolv_addr)(char *, struct sockaddr *, char **) = resolv_addr_with_address_use; /* * listing options. */ int opt_verbose = 0; #define round_loadavg(l) ((l) < 0.0 ? 0.0 : (l) > 9.99 ? 9.99 : (l)) void callback_loadavg(void *closure, struct sockaddr *addr, struct gfs_client_load *result, char *error) { char *if_hostname = closure; struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; if (error != NULL) { fprintf(stderr, "%s: %s\n", if_hostname, error); } else { printf("%4.2f/%4.2f/%4.2f %s(%s)\n", round_loadavg(result->loadavg_1min), round_loadavg(result->loadavg_5min), round_loadavg(result->loadavg_15min), if_hostname, inet_ntoa(addr_in->sin_addr)); } free(if_hostname); } char * print_loadavg(struct gfarm_host_info *info, struct gfs_client_udp_requests *udp_requests) { char *e; struct sockaddr addr; char *hostname = info->hostname; char *if_hostname; e = (*opt_resolv_addr)(hostname, &addr, &if_hostname); if (e != NULL) { fprintf(stderr, "%s: %s\n", hostname, e); return (e); } gfarm_client_add_load_request(udp_requests, &addr, if_hostname, callback_loadavg); return (NULL); } char * list_loadavg(int nhosts, char **hosts, struct gfs_client_udp_requests *udp_requests) { char *e, *e_save = NULL; int i; struct gfarm_host_info host; for (i = 0; i < nhosts; i++) { host.hostname = hosts[i]; e = print_loadavg(&host, udp_requests); if (e_save == NULL) e_save = e; } return (e_save); } struct closure_for_host_info_and_loadavg { struct gfarm_host_info host_info; char *if_hostname; }; void callback_host_info_and_loadavg(void *closure, struct sockaddr *addr, struct gfs_client_load *result, char *error) { struct closure_for_host_info_and_loadavg *c = closure; /* sizeof(struct sockaddr_in) == sizeof(struct sockaddr) */ struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; struct gfarm_host_info *info = &c->host_info; int i, print_ifaddr = c->if_hostname != NULL; if (error != NULL) { if (opt_verbose) fprintf(stderr, "%s: %s\n", info->hostname, error); if (error == GFARM_ERR_CONNECTION_REFUSED) /* machine is up */ printf("-.--/-.--/-.-- "); else printf("x.xx/x.xx/x.xx "); } else { printf("%4.2f/%4.2f/%4.2f ", round_loadavg(result->loadavg_1min), round_loadavg(result->loadavg_5min), round_loadavg(result->loadavg_15min)); } printf("%s %d %s", info->architecture, info->ncpu, info->hostname); if (print_ifaddr && strcasecmp(info->hostname, c->if_hostname) == 0) { print_ifaddr = 0; printf("(%s)", inet_ntoa(addr_in->sin_addr)); } for (i = 0; i < info->nhostaliases; i++) { printf(" %s", info->hostaliases[i]); if (print_ifaddr && strcasecmp(info->hostaliases[i], c->if_hostname) == 0) { print_ifaddr = 0; printf("(%s)", inet_ntoa(addr_in->sin_addr)); } } if (print_ifaddr) { printf(" [%s(%s)]", c->if_hostname, inet_ntoa(addr_in->sin_addr)); } putchar('\n'); gfarm_host_info_free(&c->host_info); if (c->if_hostname != NULL) free(c->if_hostname); free(c); } char * print_host_info_and_loadavg(struct gfarm_host_info *host_info, struct gfs_client_udp_requests *udp_requests) { char *e; struct sockaddr addr; struct closure_for_host_info_and_loadavg *closure; closure = malloc(sizeof(*closure)); if (closure == NULL) { e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } /* dup `*host_info' -> `closure->host_info' */ closure->host_info.hostname = strdup(host_info->hostname); closure->host_info.nhostaliases = host_info->nhostaliases; if (host_info->nhostaliases == 0) { closure->host_info.hostaliases = NULL; } else { closure->host_info.hostaliases = gfarm_strarray_dup(host_info->hostaliases); if (closure->host_info.hostaliases == NULL) closure->host_info.nhostaliases = 0; } closure->host_info.architecture = strdup(host_info->architecture); closure->host_info.ncpu = host_info->ncpu; if (closure->host_info.hostname == NULL || closure->host_info.architecture == NULL) { gfarm_host_info_free(&closure->host_info); e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } e = (*opt_resolv_addr)(host_info->hostname, &addr, &closure->if_hostname); if (e != NULL) { closure->if_hostname = NULL; callback_host_info_and_loadavg(closure, NULL, NULL, e); return (e); } gfarm_client_add_load_request(udp_requests, &addr, closure, callback_host_info_and_loadavg); return (NULL); } struct closure_for_up { struct gfarm_host_info host_info; char *if_hostname; }; void callback_up(void *closure, struct sockaddr *addr, struct gfs_client_load *result, char *error) { char *hostname = closure; if (error != NULL) { fprintf(stderr, "%s: %s\n", hostname, error); } else { puts(hostname); } free(hostname); } char * print_up(struct gfarm_host_info *host_info, struct gfs_client_udp_requests *udp_requests) { char *e, *hostname; struct sockaddr addr; /* dup `*host_info' -> `closure->host_info' */ hostname = strdup(host_info->hostname); if (hostname == NULL) { e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } e = (*opt_resolv_addr)(hostname, &addr, NULL); if (e != NULL) { callback_up(hostname, NULL, NULL, e); return (e); } gfarm_client_add_load_request(udp_requests, &addr, hostname, callback_up); return (NULL); } char * print_host_info(struct gfarm_host_info *info, struct gfs_client_udp_requests *udp_requests) { int i; printf("%s %d %s", info->architecture, info->ncpu, info->hostname); for (i = 0; i < info->nhostaliases; i++) printf(" %s", info->hostaliases[i]); putchar('\n'); return (NULL); } char * list_all(const char *architecture, const char *domainname, char *(*print_op)(struct gfarm_host_info *, struct gfs_client_udp_requests *), struct gfs_client_udp_requests *udp_requests) { char *e, *e_save = NULL; int i, nhosts; struct gfarm_host_info *hosts; if (architecture != NULL) e = gfarm_host_info_get_allhost_by_architecture( architecture, &nhosts, &hosts); else e = gfarm_host_info_get_all(&nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); return (e); } for (i = 0; i < nhosts; i++) { if (domainname == NULL || strstr(hosts[i].hostname, domainname)) { e = (*print_op)(&hosts[i], udp_requests); if (e_save == NULL) e_save = e; } } gfarm_host_info_free_all(nhosts, hosts); return (e_save); } char * list(int nhosts, char **hosts, char *(*print_op)(struct gfarm_host_info *, struct gfs_client_udp_requests *), struct gfs_client_udp_requests *udp_requests) { char *e, *e_save = NULL; int i; struct gfarm_host_info hi; for (i = 0; i < nhosts; i++) { e = gfarm_host_info_get_by_if_hostname(hosts[i], &hi); if (e != NULL) { fprintf(stderr, "%s: %s\n", hosts[i], e); if (e_save == NULL) e_save = e; } else { e = (*print_op)(&hi, udp_requests); if (e_save == NULL) e_save = e; gfarm_host_info_free(&hi); } } return (e_save); } /* Well, this is really ad hoc manner to sort output... */ int setup_sort(char *sort_arg) { int pid, fds[2]; if (pipe(fds) == -1) return (-1); pid = fork(); switch (pid) { case -1: /* error */ close(fds[0]); close(fds[1]); return (-1); case 0: /* child */ close(fds[1]); dup2(fds[0], 0); close(fds[0]); execlp("sort", "sort", sort_arg, NULL); exit(1); default: /* parent */ close(fds[0]); dup2(fds[1], 1); close(fds[1]); return (pid); } } char * wait_sort(int pid) { char *e; int status; fclose(stdout); if (waitpid(pid, &status, 0) == -1) e = gfarm_errno_to_error(errno); else if (WIFSIGNALED(status)) e = "killed by signal"; else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) e = "failed to invoke"; else e = NULL; if (e != NULL) fprintf(stderr, "%s: sort command: %s\n", program_name, e); return (e); } void usage(void) { fprintf(stderr, "Usage:" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n", program_name, "[-lMH] [-a <architecture>] [-D <domainname>] [-j <concurrency>] [-iprv]", program_name, "-c -a <architecture> [-n <ncpu>] <hostname> [<hostalias>...]", program_name, "-m [-a <architecture>] [-n <ncpu>] [-A] <hostname> [<hostalias>...]", program_name, "-d <hostname>...", program_name, "-R"); exit(EXIT_FAILURE); } #define OP_DEFAULT '\0' #define OP_LIST_LOADAVG 'H' #define OP_LIST_LONG 'l' #define OP_DUMP_METADB 'M' #define OP_REGISTER_DB 'R' /* or, restore db */ #define OP_CREATE_ENTRY 'c' #define OP_DELETE_ENTRY 'd' #define OP_MODIFY_ENTRY 'm' void inconsistent_option(int c1, int c2) { fprintf(stderr, "%s: inconsistent option -%c and -%c\n", program_name, c1, c2); usage(); } void invalid_option(int c) { fprintf(stderr, "%s: option -%c is only available with -%c or -%c\n", program_name, c, OP_CREATE_ENTRY, OP_MODIFY_ENTRY); usage(); } long parse_opt_long(char *option, int option_char, char *argument_name) { long value; char *s; errno = 0; value = strtol(option, &s, 0); if (s == option) { fprintf(stderr, "%s: missing %s after -%c\n", program_name, argument_name, option_char); usage(); } else if (*s != '\0') { fprintf(stderr, "%s: garbage in -%c %s\n", program_name, option_char, option); usage(); } else if (errno != 0 && (value == LONG_MIN || value == LONG_MAX)) { fprintf(stderr, "%s: %s with -%c %s\n", program_name, strerror(errno), option_char, option); usage(); } return (value); } #define DEFAULT_CONCURRENCY 10 int main(int argc, char **argv) { int argc_save = argc; char **argv_save = argv; char *e, *e_save = NULL; char opt_operation = OP_DEFAULT; int opt_concurrency = DEFAULT_CONCURRENCY; int opt_alter_aliases = 0; char *opt_architecture = NULL; char *opt_domainname = NULL; long opt_ncpu = 0; int opt_plain_order = 0; /* i.e. do not sort */ int opt_sort_reverse = 0; int opt_sort_by_loadavg = 0; int i, c, sort_pid, need_metadb = 1; struct gfs_client_udp_requests *udp_requests; #ifdef __GNUC__ /* shut up "warning: `...' might be used uninitialized" */ sort_pid = 0; #endif if (argc > 0) program_name = basename(argv[0]); while ((c = getopt(argc, argv, "AD:HLMRa:cdij:lmn:prv")) != -1) { switch (c) { case 'A': opt_alter_aliases = 1; break; case 'L': opt_sort_by_loadavg = 1; break; case 'M': case 'H': case 'R': case 'c': case 'd': case 'l': case 'm': if (opt_operation != OP_DEFAULT && opt_operation != c) inconsistent_option(opt_operation, c); opt_operation = c; break; case 'a': opt_architecture = optarg; e = validate_architecture(opt_architecture); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in \"-a %s\"\n", program_name, *e, opt_architecture); exit(1); } break; case 'D': opt_domainname = optarg; e = validate_hostname(opt_domainname); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in \"-a %s\"\n", program_name, *e, opt_domainname); exit(1); } break; case 'i': opt_resolv_addr = resolv_addr_without_address_use; break; case 'j': opt_concurrency = parse_opt_long(optarg, c, "<concurrency>"); if (opt_concurrency <= 0) { fprintf(stderr, "%s: invalid value: -%c %d\n", program_name, c, opt_concurrency); usage(); } break; case 'n': opt_ncpu = parse_opt_long(optarg, c, "<ncpu>"); break; case 'p': opt_plain_order = 1; break; case 'r': opt_sort_reverse = 1; break; case 'v': opt_verbose = 1; break; case '?': usage(); } } argc -= optind; argv += optind; switch (opt_operation) { case OP_CREATE_ENTRY: if (opt_architecture == NULL) { fprintf(stderr, "%s: missing -a <architecture>\n", program_name); usage(); } if (opt_ncpu == 0) { opt_ncpu = 1; } /* opt_alter_aliases is meaningless, but allowed */ break; case OP_REGISTER_DB: case OP_DELETE_ENTRY: if (opt_architecture != NULL) invalid_option('a'); if (opt_domainname != NULL) invalid_option('D'); /* fall through */ case OP_DEFAULT: case OP_LIST_LOADAVG: case OP_LIST_LONG: case OP_DUMP_METADB: if (opt_ncpu != 0) invalid_option('n'); if (opt_alter_aliases) invalid_option('A'); break; case OP_MODIFY_ENTRY: if (opt_domainname != NULL) invalid_option('D'); break; default: ; } for (i = 0; i < argc; i++) { e = validate_hostname(argv[i]); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in hostname \"%s\"\n", program_name, *e, argv[i]); exit(1); } } if (opt_operation == OP_LIST_LOADAVG && argc > 0 && opt_resolv_addr == resolv_addr_without_address_use) { /* * We don't have to initialize metadb in this case. * e.g. gfhost -Li <hostname> */ need_metadb = 0; gfarm_error_initialize(); } else { e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } } switch (opt_operation) { case OP_CREATE_ENTRY: if (argc > 0) { e_save = add_host(argv[0], &argv[1], opt_architecture, opt_ncpu); if (e_save != NULL) fprintf(stderr, "%s: %s\n", argv[0], e_save); } break; case OP_MODIFY_ENTRY: if (argc > 0) { e_save = gfarm_modify_host(argv[0], &argv[1], opt_architecture, opt_ncpu, !opt_alter_aliases); if (e_save != NULL) fprintf(stderr, "%s: %s\n", argv[0], e_save); } break; case OP_DELETE_ENTRY: for (i = 0; i < argc; i++) { e = gfarm_host_info_remove(argv[i]); if (e != NULL) { fprintf(stderr, "%s: %s\n", argv[i], e); if (e_save == NULL) e_save = e; } } break; case OP_REGISTER_DB: if (argc > 0) { fprintf(stderr, "%s: too many argument: %s\n", program_name, argv[0]); exit(1); } e_save = register_db(); break; case OP_LIST_LOADAVG: if (!opt_plain_order) { if (opt_sort_by_loadavg) { if (opt_sort_reverse) { sort_pid = setup_sort("+0nr"); } else { sort_pid = setup_sort("+0n"); } } else { if (opt_sort_reverse) { sort_pid = setup_sort("+1r"); } else { sort_pid = setup_sort("+1"); } } } e = gfarm_client_init_load_requests( opt_concurrency, &udp_requests); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_loadavg, udp_requests); } else { e_save = list_loadavg(argc, argv, udp_requests); } e = gfarm_client_wait_all_load_results(udp_requests); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_DEFAULT: if (!opt_plain_order) { if (opt_sort_reverse) { sort_pid = setup_sort("+0r"); } else { sort_pid = setup_sort("+0"); } } e = gfarm_client_init_load_requests( opt_concurrency, &udp_requests); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_up, udp_requests); } else { e_save = list(argc, argv, print_up, udp_requests); } e = gfarm_client_wait_all_load_results(udp_requests); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_LIST_LONG: if (!opt_plain_order) { if (opt_sort_by_loadavg) { if (opt_sort_reverse) { sort_pid = setup_sort("+0nr"); } else { sort_pid = setup_sort("+0n"); } } else { if (opt_sort_reverse) { sort_pid = setup_sort("+3r"); } else { sort_pid = setup_sort("+3"); } } } e = gfarm_client_init_load_requests( opt_concurrency, &udp_requests); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_host_info_and_loadavg, udp_requests); } else { e_save = list(argc, argv, print_host_info_and_loadavg, udp_requests); } e = gfarm_client_wait_all_load_results(udp_requests); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_DUMP_METADB: if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_host_info, NULL); } else { e_save = list(argc, argv, print_host_info, NULL); } break; } if (need_metadb) { e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } } exit(e_save == NULL ? 0 : 1); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_2/gfarm2fs.h #ifndef HAVE_GFS_GETXATTR_CACHED #define gfs_getxattr_cached gfs_getxattr #endif struct gfarm2fs_param { const char *mount_point; int foreground; int debug; double cache_timeout; int use_syslog; char *facility; char *loglevel; int ncopy; int copy_limit; }; struct gfarmized_path { int alloced; char *path; }; gfarm_error_t gfarmize_path(const char *, struct gfarmized_path *); void free_gfarmized_path(struct gfarmized_path *); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_3/open_file.h void gfarm2fs_open_file_init(void); GFS_File gfarm2fs_open_file_lookup(gfarm_ino_t); void gfarm2fs_open_file_enter(GFS_File, int); void gfarm2fs_open_file_remove(GFS_File); <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_represent_client_gfmdhost.sh.in #!/bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on a representative client host. # It tries executing 'gfmdhost -l' to check whether all gfmd servers are # running properly. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile=/tmp/gfarm_represent_client_gfmdhost.out.$$ errfile=/tmp/gfarm_represent_client_gfmdhost.err.$$ trap "rm -f $outfile $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile $errfile # # Execute 'gfmdhost'. # GFCMD="@GFARM_BINDIR@/gfmdhost -l" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > $outfile 2> $errfile GFCMD_EXITCODE=$? if [ $GFCMD_EXITCODE -ne 0 ]; then if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then echo "'$GFCMD' failed, timeout" log_err "'$GFCMD' failed, timeout" else echo "'$GFCMD' failed" log_err "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" fi [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi # # Check whether 'gfmdhost' outputs a list of servers correctly. # if [ ! -s $outfile ]; then echo "ok" log_warning "'$GFCMD' outputs no data" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi # # Check the result data of 'gfmdhost'. # awk ' BEGIN { not_connected_gfmds = "" expired_gfmds = "" error_gfmds = "" } { if ($1 == "-") { if (not_connected_gfmds == "") not_connected_gfmds = $6 else not_connected_gfmds = not_connected_gfmds ", " $6 } else if ($1 == "e") { if (error_gfmds == "") error_gfmds = $6 else error_gfmds = error_gfmds ", " $6 } else if ($1 == "x") { if (expired_gfmds == "") expired_gfmds = $6 else expired_gfmds = expired_gfmds ", " $6 } } END { if (not_connected_gfmds != "") print "not connected: " not_connected_gfmds else if (error_gfmds != "") print "error happened: " error_gfmds else if (expired_gfmds != "") print "expired: " expired_gfmds else print "ok" }' $outfile rm -f $outfile $errfile exit 0 <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8/systest/common_scripts/Makefile.am common_scriptsdir = @gfarm_root@/share/gfarm/systest/common_scripts dist_common_scripts_DATA = calc_checksum \ check_files \ check_files_each_mntpnts \ exec_on_multiple_clients \ gfwhere_check \ log_view \ make_files \ make_files_each_mntpnts \ make_files_single \ mkdir_n \ mount_n \ read_files \ remove_files \ remove_files_each_mntpnts \ rmdir_n \ umount_n <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_6/contrib/mount.gfarm2fs/umount.gfarm2fs #!/bin/sh # # $Id$ USAGE() { cat <<EOF umount.gfarm2fs [ mount_point ] Environment variable: GFS_USERNAME global user name in Gfarm GFS_MOUNTDIR mount point EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } UMOUNT_FUSE() { MNTDIR=$1 retry=10 i=0 while true; do fusermount -u $MNTDIR > /dev/null 2>&1 if [ $? -eq 0 ]; then return 0 fi ls -l $MNTDIR > /dev/null 2>&1 if [ $i -ge $retry ]; then return 1 fi i=`expr $i + 1` done } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi : ${GFS_USERNAME:=`gfwhoami 2> /dev/null`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2> /dev/null`} : ${GFS_MOUNTDIR:=`grep user=$LOGNAME /etc/mtab | grep gfarm | head -1 | awk '{ print $2 }'`} : ${GFS_MOUNTDIR:=`grep user=$LOGNAME /etc/mtab | head -1 | awk '{ print $2 }'`} [ X"$GFS_MOUNTDIR" = X ] && ABORT "It seems GfarmFS is not mounted. Specify the mount directory by GFS_MOUNTDIR environment variable" UMOUNT_FUSE $GFS_MOUNTDIR STATUS=$? if [ $STATUS = 0 ]; then echo Unmount GfarmFS on $GFS_MOUNTDIR else ABORT Error: failed to umount GfarmFS on $GFS_MOUNTDIR fi exit $STATUS <file_sep>/gfarm/tags/gfarm_1_0_3_1/lib/libgfarm/gfarm/gfs_pio.h /* * $Id$ */ #define GFS_FILE_IS_PROGRAM(gf) (GFARM_S_IS_PROGRAM(gf->pi.status.st_mode)) extern char GFS_FILE_ERROR_EOF[]; struct gfs_pio_ops { char *(*view_close)(GFS_File); char *(*view_write)(GFS_File, const char *, size_t, size_t *); char *(*view_read)(GFS_File, char *, size_t, size_t *); char *(*view_seek)(GFS_File, file_offset_t, int, file_offset_t *); int (*view_fd)(GFS_File); char *(*view_stat)(GFS_File, struct gfs_stat *); }; struct gfs_file { struct gfs_pio_ops *ops; void *view_context; int mode; #define GFS_FILE_MODE_READ 0x00000001 #define GFS_FILE_MODE_WRITE 0x00000002 #define GFS_FILE_MODE_NSEGMENTS_FIXED 0x01000000 #define GFS_FILE_MODE_CALC_DIGEST 0x02000000 #define GFS_FILE_MODE_FILE_DIRTY 0x10000000 #define GFS_FILE_MODE_SECTION_DIRTY 0x20000000 #define GFS_FILE_MODE_BUFFER_DIRTY 0x40000000 /* remember parameter of open/set_view */ int open_flags; int view_flags; char *error; /* GFS_FILE_ERROR_EOF, if end of file */ file_offset_t io_offset; #define GFS_FILE_BUFSIZE 65536 char *buffer; int p; int length; file_offset_t offset; struct gfarm_path_info pi; }; char *gfs_unlink_section(const char *, const char *); #define GFS_F_OK 0 #define GFS_X_OK 1 #define GFS_W_OK 2 #define GFS_R_OK 4 char *gfarm_path_info_access(struct gfarm_path_info *, int); char *gfs_pio_set_view_default(GFS_File); char *gfs_pio_set_view_global(GFS_File, int); char *gfs_pio_open_local_section(GFS_File, int); char *gfs_pio_open_remote_section(GFS_File, char *, int); struct gfs_connection; char *gfs_pio_local_mkdir_parent_canonical_path(char *); char *gfs_pio_remote_mkdir_parent_canonical_path( struct gfs_connection *, char *); struct gfs_storage_ops { char *(*storage_close)(GFS_File); char *(*storage_write)(GFS_File, const char *, size_t, size_t *); char *(*storage_read)(GFS_File, char *, size_t, size_t *); char *(*storage_seek)(GFS_File, file_offset_t, int, file_offset_t *); char *(*storage_calculate_digest)(GFS_File, char *, size_t, size_t *, unsigned char *, file_offset_t *); int (*storage_fd)(GFS_File); }; #define GFS_DEFAULT_DIGEST_NAME "md5" #define GFS_DEFAULT_DIGEST_MODE EVP_md5() struct gfs_file_section_context { struct gfs_storage_ops *ops; void *storage_context; char *section; char *canonical_hostname; int fd; /* socket (for remote) or file (for local) descriptor */ /* for checksum, maintained only if GFS_FILE_MODE_CALC_DIGEST */ EVP_MD_CTX md_ctx; }; /* * offset * v * buffer |*******************************---------| * ^ ^ ^ * 0 p length * * on write: * io_offset == offset * on sequential write: * io_offset == offset && p == length * on read: * io_offset == offset + length * * switching from writing to reading: * no problem, flush the buffer if `p' beyonds `length'. * switching from reading to writing: * usually, seek is needed. */ extern GFS_File gf_stdout, gf_stderr; extern int gf_profile; extern int gf_on_demand_replication; #define gfs_profile(x) if (gf_profile == 1) { x; } extern double gfs_pio_set_view_section_time; extern double gfs_unlink_time; extern double gfs_stat_time; void gfs_display_timers(); /* url.c */ char *gfarm_path_expand_home(const char *_file, char **); /* gfs_pio_misc.c */ char *gfs_stat_canonical_path(char *, struct gfs_stat *); /* gfs_dir.c */ char *gfs_realpath_canonical(const char *, char **); char *gfs_get_ino(const char *, long *); <file_sep>/gfarm/tags/gfarm_1_1_1_rc4/makes/prog.mk install: all prog-install post-install-hook clean: prog-clean post-clean-hook veryclean: prog-veryclean post-veryclean-hook distclean: prog-distclean post-distclean-hook gfregister: prog-gfregister post-gfregister-hook man: prog-man post-man-hook html: prog-html post-html-hook post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: $(PROGRAM): $(OBJS) $(DEPLIBS) $(LTLINK) $(OBJS) $(LDLIBS) prog-install: $(LTINSTALL_PROGRAM) $(PROGRAM) $(bindir)/$(PROGRAM) prog-clean: -$(LTCLEAN) $(OBJS) $(EXTRA_CLEAN_TARGETS) prog-veryclean: clean -$(LTCLEAN) $(PROGRAM) $(EXTRA_VERYCLEAN_TARGETS) prog-distclean: veryclean -test ! -f $(srcdir)/Makefile.in || $(RM) -f Makefile prog-gfregister: prog-man: prog-html: <file_sep>/gfarm_mpiio/trunk/ad_gfarm/ad_gfarm_flush.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" #include "adioi.h" #include "adio_extern.h" void ADIOI_GFARM_Flush(ADIO_File fd, int *error_code) { int myrank, nprocs; int i; ADIOI_GFARM_headerInf *ghi; ADIOI_GFARM_collective_info *gci; *error_code = MPI_SUCCESS; ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); if(ghi->gfarm_view_flag == 1){ for(i=0;i<ghi->gfp_num;i++){ gfs_pio_datasync(ghi->gfp[i]); } gfs_pio_datasync(ghi->header_gfp); if(ghi->is_collective == 1){ gci = (ADIOI_GFARM_collective_info *)ghi->gci; if(gci->head_rank_flag == 1 && gci->gfp != NULL){ for(i=0;i<((gci->same_rank_count)-1);i++){ gfs_pio_datasync(gci->gfp[i]); } } } }else if(ghi->gfarm_view_flag == 2){ ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); gfs_pio_datasync(ghi->gfp[0]); }else{ } #ifdef GFARM_DEBUG MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_Flush called on %s\n", myrank, nprocs, fd->filename); #endif } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/gftool/gfhost/gfhost.c /* * $Id$ */ #include <assert.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <limits.h> #include <errno.h> #include <gfarm/gfarm.h> #include "gfevent.h" #include "host.h" /* gfarm_host_info_address_get() */ #include "auth.h" #include "config.h" #include "gfs_client.h" char *program_name = "gfhost"; static char * update_host(char *hostname, int nhostaliases, char **hostaliases, char *architecture, int ncpu, char *(*update_op)(char *, struct gfarm_host_info *)) { struct gfarm_host_info hi; hi.hostname = hostname; hi.nhostaliases = nhostaliases; hi.hostaliases = hostaliases; hi.architecture = architecture; hi.ncpu = ncpu; return ((*update_op)(hostname, &hi)); } static char * check_hostname(char *hostname) { char *e, *n; e = gfarm_host_get_canonical_name(hostname, &n); if (e == NULL || e == GFARM_ERR_AMBIGUOUS_RESULT) { if (e == NULL) free(n); return ("the hostname is already registered"); } return (NULL); } static char * check_hostaliases(int nhostaliases, char **hostaliases) { int i; for (i = 0; i < nhostaliases; i++) { if (check_hostname(hostaliases[i]) != NULL) return ("the hostalias is already registered"); } return (NULL); } char * add_host(char *hostname, char **hostaliases, char *architecture, int ncpu) { int nhostaliases = gfarm_strarray_length(hostaliases); char *e; e = check_hostname(hostname); if (e != NULL) return (e); e = check_hostaliases(nhostaliases, hostaliases); if (e != NULL) return (e); return (update_host(hostname, nhostaliases, hostaliases, architecture, ncpu, gfarm_host_info_set)); } char * gfarm_modify_host(char *hostname, char **hostaliases, char *architecture, int ncpu, int add_aliases) { char *e; struct gfarm_host_info hi; int host_info_needs_free = 0; gfarm_stringlist aliases; if (*hostaliases == NULL || architecture == NULL || ncpu < 1 || add_aliases) { e = gfarm_host_info_get(hostname, &hi); if (e != NULL) return (e); host_info_needs_free = 1; if (!add_aliases) { /* XXX - do check_hostaliases() here, too. */ hostaliases = hostaliases; } else { e = check_hostaliases( gfarm_strarray_length(hostaliases), hostaliases); if (e != NULL) goto free_host_info; e = gfarm_stringlist_init(&aliases); if (e != NULL) goto free_host_info; if (hi.hostaliases != NULL) { e = gfarm_stringlist_cat(&aliases, hi.hostaliases); if (e != NULL) goto free_aliases; } if (hostaliases != NULL) { e = gfarm_stringlist_cat(&aliases, hostaliases); if (e != NULL) goto free_aliases; } e = gfarm_stringlist_add(&aliases, NULL); if (e != NULL) goto free_aliases; hostaliases = GFARM_STRINGLIST_STRARRAY(aliases); } if (architecture == NULL) architecture = hi.architecture; if (ncpu < 1) ncpu = hi.ncpu; } e = update_host(hostname, gfarm_strarray_length(hostaliases), hostaliases, architecture, ncpu, gfarm_host_info_replace); if (e == NULL && !add_aliases && *hostaliases == NULL) e = gfarm_host_info_remove_hostaliases(hostname); free_aliases: if (add_aliases) gfarm_stringlist_free(&aliases); free_host_info: if (host_info_needs_free) gfarm_host_info_free(&hi); return (e); } char * validate_architecture(char *architecture) { unsigned char c, *s = (unsigned char *)architecture; while ((c = *s++) != '\0') { if (!isalnum(c) && c != '-' && c != '_' && c != '.') return ((char *)s - 1); } return (NULL); } char * validate_hostname(char *hostname) { unsigned char c, *s = (unsigned char *)hostname; while ((c = *s++) != '\0') { if (!isalnum(c) && c != '-' && c != '.') return ((char *)s - 1); } return (NULL); } char * invalid_input(int lineno) { fprintf(stderr, "line %d: invalid input format\n", lineno); fprintf(stderr, "%s: input must be " "\"<architecture> <ncpu> <hostname> <hostalias>...\" format\n", program_name); return (GFARM_ERR_INVALID_ARGUMENT); } #define LINE_BUFFER_SIZE 16384 #define MAX_HOSTALIASES 256 char * add_line(char *line, int lineno) { long ncpu; int len, nhostaliases; char *e, *hostname, *architecture; char *hostaliases[MAX_HOSTALIASES + 1]; static char space[] = " \t"; /* parse architecture */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0 || line[len] == '\0') return (invalid_input(lineno)); line[len] = '\0'; architecture = line; line += len + 1; e = validate_architecture(architecture); if (e != NULL) { fprintf(stderr, "line %d: invalid character '%c' in architecture \"%s\"\n", lineno, *e, architecture); return (GFARM_ERR_INVALID_ARGUMENT); } /* parse ncpu */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0 || line[len] == '\0') return (invalid_input(lineno)); line[len] = '\0'; errno = 0; ncpu = strtol(line, &e, 0); if (e == line) { return (invalid_input(lineno)); } else if (*e != '\0') { fprintf(stderr, "line %d: garbage \"%s\" in ncpu \"%s\"\n", lineno, e, line); return (GFARM_ERR_INVALID_ARGUMENT); } else if (errno != 0 && (ncpu == LONG_MIN || ncpu == LONG_MAX)) { fprintf(stderr, "line %d: %s on \"%s\"\n", lineno, strerror(errno), line); return (GFARM_ERR_INVALID_ARGUMENT); } line += len + 1; /* parse hostname */ line += strspn(line, space); /* skip space */ len = strcspn(line, space); if (len == 0) return (invalid_input(lineno)); hostname = line; if (line[len] == '\0') { line += len; } else { line[len] = '\0'; line += len + 1; } e = validate_hostname(hostname); if (e != NULL) { fprintf(stderr, "line %d: invalid character '%c' in hostname \"%s\"\n", lineno, *e, hostname); return (GFARM_ERR_INVALID_ARGUMENT); } /* parse hostaliases */ for (nhostaliases = 0;; nhostaliases++) { line += strspn(line, space); /* skip space */ if (*line == '\0') break; len = strcspn(line, space); /* assert(len > 0); */ if (nhostaliases >= MAX_HOSTALIASES) { fprintf(stderr, "line %d: " "number of hostaliases exceeds %d\n", lineno, nhostaliases); return (GFARM_ERR_INVALID_ARGUMENT); } hostaliases[nhostaliases] = line; if (line[len] == '\0') { line += len; } else { line[len] = '\0'; line += len + 1; } e = validate_hostname(hostaliases[nhostaliases]); if (e != NULL) { fprintf(stderr, "line %d: " "invalid character '%c' in hostalias \"%s\"\n", lineno, *e, hostaliases[nhostaliases]); return (GFARM_ERR_INVALID_ARGUMENT); } } hostaliases[nhostaliases] = NULL; e = add_host(hostname, hostaliases, architecture, ncpu); if (e != NULL) fprintf(stderr, "line %d: %s\n", lineno, e); return (e); } char * register_db(void) { char *e, *e_save = NULL; int len, lineno; char line[LINE_BUFFER_SIZE]; if (fgets(line, sizeof line, stdin) == NULL) return (NULL); len = strlen(line); for (lineno = 1;; lineno++) { if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } else { fprintf(stderr, "line %d: too long line\n", lineno); if (e_save == NULL) e_save = GFARM_ERR_INVALID_ARGUMENT; do { if (fgets(line, sizeof line, stdin) == NULL) return (e_save); len = strlen(line); } while (len == 0 || line[len - 1] != '\n'); continue; } e = add_line(line, lineno); if (e_save == NULL) e_save = e; if (fgets(line, sizeof line, stdin) == NULL) break; len = strlen(line); } return (e_save); } /* * handle option "-i" (ignore "address_use" directive in gfarm.conf(5)) */ char * resolv_addr_with_address_use(char *hostname, struct sockaddr *addr, char **if_hostnamep) { return (gfarm_host_address_get(hostname, gfarm_spool_server_port, addr, if_hostnamep)); } char * resolv_addr_by_host_info_with_address_use( char *hostname, struct gfarm_host_info *info, struct sockaddr *addr, char **if_hostnamep) { return (gfarm_host_info_address_get(hostname, gfarm_spool_server_port, info, addr, if_hostnamep)); } char * resolv_addr_without_address_use(char *hostname, struct sockaddr *addr, char **if_hostnamep) { /* sizeof(struct sockaddr_in) == sizeof(struct sockaddr) */ struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; struct hostent *hp; hp = gethostbyname(hostname); if (hp == NULL || hp->h_addrtype != AF_INET) return (GFARM_ERR_UNKNOWN_HOST); memset(addr_in, 0, sizeof(*addr_in)); memcpy(&addr_in->sin_addr, hp->h_addr, sizeof(addr_in->sin_addr)); addr_in->sin_family = hp->h_addrtype; addr_in->sin_port = htons(gfarm_spool_server_port); if (if_hostnamep != NULL) { *if_hostnamep = strdup(hostname); if (*if_hostnamep == NULL) return (GFARM_ERR_NO_MEMORY); } return (NULL); } char * resolv_addr_by_host_info_without_address_use( char *hostname, struct gfarm_host_info *info, struct sockaddr *addr, char **if_hostnamep) { return (resolv_addr_without_address_use(hostname, addr, if_hostnamep)); } char *(*opt_resolv_addr)(char *, struct sockaddr *, char **) = resolv_addr_with_address_use; char *(*opt_resolv_addr_by_host_info)(char *, struct gfarm_host_info *, struct sockaddr *, char **) = resolv_addr_by_host_info_with_address_use; /* * parallel access wrapper */ struct gfarm_paraccess { struct gfarm_eventqueue *q; int try_auth; struct gfarm_access { void (*callback)(void *, char *, struct sockaddr *, struct gfs_client_load *, struct gfs_connection *, char *); void *closure; char *hostname; struct sockaddr peer_addr; struct gfs_client_load load; void *protocol_state; struct gfarm_paraccess *pa; struct gfarm_access *next; } *access_state; struct gfarm_access *free_list; int concurrency, nfree; }; char * gfarm_paraccess_alloc( int concurrency, int try_auth, struct gfarm_paraccess **pap) { struct gfarm_paraccess *pa; int i; pa = malloc(sizeof(*pa)); if (pa == NULL) return (GFARM_ERR_NO_MEMORY); pa->q = gfarm_eventqueue_alloc(); if (pa->q == NULL) { free(pa); return (GFARM_ERR_NO_MEMORY); } pa->access_state = malloc(sizeof(*pa->access_state) * concurrency); if (pa->access_state == NULL) { gfarm_eventqueue_free(pa->q); free(pa); return (GFARM_ERR_NO_MEMORY); } /* construct free slot list */ i = concurrency - 1; pa->access_state[i].next = NULL; while (--i >= 0) pa->access_state[i].next = &pa->access_state[i + 1]; pa->free_list = &pa->access_state[0]; pa->concurrency = pa->nfree = concurrency; pa->try_auth = try_auth; *pap = pa; return (NULL); } static void gfarm_paraccess_callback(struct gfarm_paraccess *pa, struct gfarm_access *a, struct gfs_client_load *load, struct gfs_connection *gfs_server, char *e) { (*a->callback)(a->closure, a->hostname, &a->peer_addr, load, gfs_server, e); /* bring this back to the free slot list */ a->next = pa->free_list; pa->free_list = a; pa->nfree++; } static void gfarm_paraccess_load_finish(void *closure) { struct gfarm_access *a = closure; char *e; e = gfs_client_get_load_result_multiplexed(a->protocol_state, &a->load); gfarm_paraccess_callback(a->pa, a, e == NULL ? &a->load : NULL, NULL, e); } static void gfarm_paraccess_connect_finish(void *closure) { struct gfarm_access *a = closure; char *e; struct gfs_connection *gfs_server; e = gfs_client_connect_result_multiplexed(a->protocol_state, &gfs_server); if (e != NULL) { gfarm_paraccess_callback(a->pa, a, &a->load, NULL, e); return; } gfarm_paraccess_callback(a->pa, a, &a->load, gfs_server, e); gfs_client_disconnect(gfs_server); } static void gfarm_paraccess_connect_request(void *closure) { struct gfarm_access *a = closure; char *e; struct gfs_client_connect_state *cs; e = gfs_client_get_load_result_multiplexed(a->protocol_state, &a->load); if (e != NULL) { gfarm_paraccess_callback(a->pa, a, NULL, NULL, e); return; } e = gfs_client_connect_request_multiplexed(a->pa->q, a->hostname, &a->peer_addr, gfarm_paraccess_connect_finish, a, &cs); if (e != NULL) { gfarm_paraccess_callback(a->pa, a, &a->load, NULL, e); return; } a->protocol_state = cs; } char * gfarm_paraccess_request(struct gfarm_paraccess *pa, void (*callback)(void *, char *, struct sockaddr *, struct gfs_client_load *, struct gfs_connection *, char *), void *closure, char *hostname, struct sockaddr *peer_addr) { int rv; char *e; struct gfarm_access *a; struct gfs_client_get_load_state *gls; /* * Wait until at least one slot becomes available. * We limit concurrency here. */ while (pa->free_list == NULL) { rv = gfarm_eventqueue_turn(pa->q, NULL); if (rv == EAGAIN || rv == EINTR) { continue; /* not really an error */ } else if (rv != 0) { return (gfarm_errno_to_error(rv)); } } /* acquire free slot */ a = pa->free_list; pa->free_list = a->next; --pa->nfree; a->callback = callback; a->closure = closure; a->hostname = hostname; a->peer_addr = *peer_addr; e = gfs_client_get_load_request_multiplexed(pa->q, &a->peer_addr, pa->try_auth ? gfarm_paraccess_connect_request : gfarm_paraccess_load_finish, a, &gls); if (e != NULL) { gfarm_paraccess_callback(pa, a, NULL, NULL, e); return (e); } a->protocol_state = gls; a->pa = pa; return (NULL); } char * gfarm_paraccess_free(struct gfarm_paraccess *pa) { int rv = gfarm_eventqueue_loop(pa->q, NULL); char *e; free(pa->access_state); gfarm_eventqueue_free(pa->q); free(pa); if (rv == 0) return (NULL); e = gfarm_errno_to_error(rv); fprintf(stderr, "%s: %s\n", program_name, e); return (e); } /* * listing options. */ int opt_verbose = 0; int opt_udp_only = 0; #define round_loadavg(l) ((l) < 0.0 ? 0.0 : (l) > 9.99 ? 9.99 : (l)) #define MNEMONIC_AUTH_FAIL 'x' #define MNEMONIC_NOT_TRIED '-' void print_loadavg_authinfo(struct gfs_client_load *load, struct gfs_connection *gfs_server, char *error) { if (load != NULL) printf("%4.2f/%4.2f/%4.2f ", round_loadavg(load->loadavg_1min), round_loadavg(load->loadavg_5min), round_loadavg(load->loadavg_15min)); else if (error == GFARM_ERR_CONNECTION_REFUSED) /* machine is up */ printf("-.--/-.--/-.-- "); else printf("x.xx/x.xx/x.xx "); if (!opt_udp_only) { printf("%c ", gfs_server != NULL ? gfarm_auth_method_mnemonic( gfs_client_connection_auth_method(gfs_server)) : load == NULL ? MNEMONIC_NOT_TRIED : MNEMONIC_AUTH_FAIL); } } void callback_gfsd_info(void *closure, char *if_hostname, struct sockaddr *peer_addr, struct gfs_client_load *load, struct gfs_connection *gfs_server, char *error) { struct sockaddr_in *addr_in = (struct sockaddr_in *)peer_addr; print_loadavg_authinfo(load, gfs_server, error); printf("%s(%s)\n", if_hostname, inet_ntoa(addr_in->sin_addr)); if (opt_verbose && error != NULL) fprintf(stderr, "%s: %s\n", if_hostname, error); free(if_hostname); } char * print_gfsd_info(struct gfarm_host_info *info, struct gfarm_paraccess *pa) { char *e; struct sockaddr addr; char *if_hostname; if (info->architecture == NULL) { /* XXX faked host_info? */ e = (*opt_resolv_addr)(info->hostname, &addr, &if_hostname); } else { e = (*opt_resolv_addr_by_host_info)(info->hostname, info, &addr, &if_hostname); } if (e != NULL) { fprintf(stderr, "%s: %s\n", info->hostname, e); return (e); } return (gfarm_paraccess_request(pa, callback_gfsd_info, NULL, if_hostname, &addr)); } /* This function is a special case to avoid Meta DB access. */ char * list_gfsd_info(int nhosts, char **hosts, struct gfarm_paraccess *pa) { char *e, *e_save = NULL; int i; struct gfarm_host_info host; for (i = 0; i < nhosts; i++) { host.hostname = hosts[i]; host.architecture = NULL; /* XXX mark as a faked host_info */ e = print_gfsd_info(&host, pa); if (e_save == NULL) e_save = e; } return (e_save); } void callback_long_format( void *closure, char *if_hostname, struct sockaddr *peer_addr, struct gfs_client_load *load, struct gfs_connection *gfs_server, char *error) { struct gfarm_host_info *info = closure; /* sizeof(struct sockaddr_in) == sizeof(struct sockaddr) */ struct sockaddr_in *addr_in = (struct sockaddr_in *)peer_addr; int i, print_ifaddr = if_hostname != NULL; print_loadavg_authinfo(load, gfs_server, error); printf("%s %d %s", info->architecture, info->ncpu, info->hostname); if (print_ifaddr && strcasecmp(info->hostname, if_hostname) == 0) { print_ifaddr = 0; printf("(%s)", inet_ntoa(addr_in->sin_addr)); } for (i = 0; i < info->nhostaliases; i++) { printf(" %s", info->hostaliases[i]); if (print_ifaddr && strcasecmp(info->hostaliases[i], if_hostname) == 0) { print_ifaddr = 0; printf("(%s)", inet_ntoa(addr_in->sin_addr)); } } if (print_ifaddr) { printf(" [%s(%s)]", if_hostname, inet_ntoa(addr_in->sin_addr)); } putchar('\n'); if (opt_verbose && error != NULL) fprintf(stderr, "%s: %s\n", info->hostname, error); gfarm_host_info_free(info); free(info); if (if_hostname != NULL) free(if_hostname); } char * print_long_format(struct gfarm_host_info *host_info, struct gfarm_paraccess *pa) { char *e; struct sockaddr addr; struct gfarm_host_info *info; char *if_hostname; info = malloc(sizeof(*info)); if (info == NULL) { e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } /* dup `*host_info' -> `*info' */ info->hostname = strdup(host_info->hostname); info->nhostaliases = host_info->nhostaliases; if (host_info->nhostaliases == 0) { info->hostaliases = NULL; } else { info->hostaliases = gfarm_strarray_dup(host_info->hostaliases); if (info->hostaliases == NULL) info->nhostaliases = 0; } info->architecture = strdup(host_info->architecture); info->ncpu = host_info->ncpu; if (info->hostname == NULL || info->architecture == NULL) { gfarm_host_info_free(info); free(info); e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } e = (*opt_resolv_addr_by_host_info)(host_info->hostname, host_info, &addr, &if_hostname); if (e != NULL) { callback_long_format(info, NULL, NULL, NULL, NULL, e); return (e); } return (gfarm_paraccess_request(pa, callback_long_format, info, if_hostname, &addr)); } void callback_nodename(void *closure, char *hostname, struct sockaddr *peer_addr, struct gfs_client_load *load, struct gfs_connection *gfs_server, char *error) { if (error == NULL) puts(hostname); else if (opt_verbose) fprintf(stderr, "%s: %s\n", hostname, error); free(hostname); } char * print_nodename(struct gfarm_host_info *host_info, struct gfarm_paraccess *pa) { char *e, *hostname; struct sockaddr addr; /* dup `host_info->hostname' -> `hostname' */ hostname = strdup(host_info->hostname); if (hostname == NULL) { e = GFARM_ERR_NO_MEMORY; fprintf(stderr, "%s: %s\n", program_name, e); return (e); } e = (*opt_resolv_addr_by_host_info)(hostname, host_info, &addr, NULL); if (e != NULL) { callback_nodename(NULL, hostname, NULL, NULL, NULL, e); return (e); } return (gfarm_paraccess_request(pa, callback_nodename, NULL, hostname, &addr)); } char * print_host_info(struct gfarm_host_info *info, struct gfarm_paraccess *pa) { int i; printf("%s %d %s", info->architecture, info->ncpu, info->hostname); for (i = 0; i < info->nhostaliases; i++) printf(" %s", info->hostaliases[i]); putchar('\n'); return (NULL); } char * list_all(const char *architecture, const char *domainname, char *(*print_op)(struct gfarm_host_info *, struct gfarm_paraccess *), struct gfarm_paraccess *pa) { char *e, *e_save = NULL; int i, nhosts; struct gfarm_host_info *hosts; if (architecture != NULL) e = gfarm_host_info_get_allhost_by_architecture( architecture, &nhosts, &hosts); else e = gfarm_host_info_get_all(&nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); return (e); } for (i = 0; i < nhosts; i++) { if (domainname == NULL || gfarm_host_is_in_domain(hosts[i].hostname, domainname)) { e = (*print_op)(&hosts[i], pa); if (e_save == NULL) e_save = e; } } gfarm_host_info_free_all(nhosts, hosts); return (e_save); } char * list(int nhosts, char **hosts, char *(*print_op)(struct gfarm_host_info *, struct gfarm_paraccess *), struct gfarm_paraccess *pa) { char *e, *e_save = NULL; int i; struct gfarm_host_info hi; for (i = 0; i < nhosts; i++) { e = gfarm_host_info_get_by_if_hostname(hosts[i], &hi); if (e != NULL) { fprintf(stderr, "%s: %s\n", hosts[i], e); if (e_save == NULL) e_save = e; } else { e = (*print_op)(&hi, pa); if (e_save == NULL) e_save = e; gfarm_host_info_free(&hi); } } return (e_save); } /* Well, this is really ad hoc manner to sort output... */ int setup_sort(char *sort_arg) { int pid, fds[2]; if (pipe(fds) == -1) return (-1); pid = fork(); switch (pid) { case -1: /* error */ close(fds[0]); close(fds[1]); return (-1); case 0: /* child */ close(fds[1]); dup2(fds[0], 0); close(fds[0]); execlp("sort", "sort", sort_arg, NULL); exit(1); default: /* parent */ close(fds[0]); dup2(fds[1], 1); close(fds[1]); return (pid); } } char * wait_sort(int pid) { char *e; int status; fclose(stdout); if (waitpid(pid, &status, 0) == -1) e = gfarm_errno_to_error(errno); else if (WIFSIGNALED(status)) e = "killed by signal"; else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) e = "failed to invoke"; else e = NULL; if (e != NULL) fprintf(stderr, "%s: sort command: %s\n", program_name, e); return (e); } void usage(void) { fprintf(stderr, "Usage:" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n" "\t%s %s\n", program_name, "[-lMH] [-a <architecture>] [-D <domainname>] [-j <concurrency>] [-iprv]", program_name, "-c -a <architecture> [-n <ncpu>] <hostname> [<hostalias>...]", program_name, "-m [-a <architecture>] [-n <ncpu>] [-A] <hostname> [<hostalias>...]", program_name, "-d <hostname>...", program_name, "-R"); exit(EXIT_FAILURE); } #define OP_NODENAME '\0' /* '\0' means default operation */ #define OP_LIST_GFSD_INFO 'H' #define OP_LIST_LONG 'l' #define OP_DUMP_METADB 'M' #define OP_REGISTER_DB 'R' /* or, restore db */ #define OP_CREATE_ENTRY 'c' #define OP_DELETE_ENTRY 'd' #define OP_MODIFY_ENTRY 'm' void inconsistent_option(int c1, int c2) { fprintf(stderr, "%s: inconsistent option -%c and -%c\n", program_name, c1, c2); usage(); } void invalid_option(int c) { fprintf(stderr, "%s: option -%c is only available with -%c or -%c\n", program_name, c, OP_CREATE_ENTRY, OP_MODIFY_ENTRY); usage(); } long parse_opt_long(char *option, int option_char, char *argument_name) { long value; char *s; errno = 0; value = strtol(option, &s, 0); if (s == option) { fprintf(stderr, "%s: missing %s after -%c\n", program_name, argument_name, option_char); usage(); } else if (*s != '\0') { fprintf(stderr, "%s: garbage in -%c %s\n", program_name, option_char, option); usage(); } else if (errno != 0 && (value == LONG_MIN || value == LONG_MAX)) { fprintf(stderr, "%s: %s with -%c %s\n", program_name, strerror(errno), option_char, option); usage(); } return (value); } #define DEFAULT_CONCURRENCY 10 /* reflect this value to gfhost.1.docbook */ int main(int argc, char **argv) { int argc_save = argc; char **argv_save = argv; char *e, *e_save = NULL; char opt_operation = '\0'; /* default operation */ int opt_concurrency = DEFAULT_CONCURRENCY; int opt_alter_aliases = 0; char *opt_architecture = NULL; char *opt_domainname = NULL; long opt_ncpu = 0; int opt_plain_order = 0; /* i.e. do not sort */ int opt_sort_reverse = 0; int opt_sort_by_loadavg = 0; int i, c, sort_pid, need_metadb = 1; struct gfarm_paraccess *pa; #ifdef __GNUC__ /* shut up "warning: `...' might be used uninitialized" */ sort_pid = 0; #endif if (argc > 0) program_name = basename(argv[0]); while ((c = getopt(argc, argv, "AD:HLMRUa:cdij:lmn:prv?")) != -1) { switch (c) { case 'A': opt_alter_aliases = 1; break; case 'L': opt_sort_by_loadavg = 1; break; case 'M': case 'H': case 'R': case 'c': case 'd': case 'l': case 'm': if (opt_operation != '\0' && opt_operation != c) inconsistent_option(opt_operation, c); opt_operation = c; break; case 'a': opt_architecture = optarg; e = validate_architecture(opt_architecture); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in \"-a %s\"\n", program_name, *e, opt_architecture); exit(1); } break; case 'D': opt_domainname = optarg; e = validate_hostname(opt_domainname); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in \"-a %s\"\n", program_name, *e, opt_domainname); exit(1); } break; case 'i': opt_resolv_addr = resolv_addr_without_address_use; opt_resolv_addr_by_host_info = resolv_addr_by_host_info_without_address_use; break; case 'j': opt_concurrency = parse_opt_long(optarg, c, "<concurrency>"); if (opt_concurrency <= 0) { fprintf(stderr, "%s: invalid value: -%c %d\n", program_name, c, opt_concurrency); usage(); } break; case 'n': opt_ncpu = parse_opt_long(optarg, c, "<ncpu>"); break; case 'p': opt_plain_order = 1; break; case 'r': opt_sort_reverse = 1; break; case 'U': opt_udp_only = 1; break; case 'v': opt_verbose = 1; break; case '?': usage(); } } argc -= optind; argv += optind; switch (opt_operation) { case OP_CREATE_ENTRY: if (opt_architecture == NULL) { fprintf(stderr, "%s: missing -a <architecture>\n", program_name); usage(); } if (opt_ncpu == 0) { opt_ncpu = 1; } /* opt_alter_aliases is meaningless, but allowed */ break; case OP_REGISTER_DB: case OP_DELETE_ENTRY: if (opt_architecture != NULL) invalid_option('a'); if (opt_domainname != NULL) invalid_option('D'); /* fall through */ case OP_NODENAME: case OP_LIST_GFSD_INFO: case OP_LIST_LONG: case OP_DUMP_METADB: if (opt_ncpu != 0) invalid_option('n'); if (opt_alter_aliases) invalid_option('A'); break; case OP_MODIFY_ENTRY: if (opt_domainname != NULL) invalid_option('D'); break; default: ; } for (i = 0; i < argc; i++) { e = validate_hostname(argv[i]); if (e != NULL) { fprintf(stderr, "%s: " "invalid character '%c' in hostname \"%s\"\n", program_name, *e, argv[i]); exit(1); } } if (opt_operation == OP_LIST_GFSD_INFO && argc > 0 && opt_resolv_addr == resolv_addr_without_address_use) { /* * We don't have to initialize metadb in this case. * e.g. gfhost -Li <hostname> */ need_metadb = 0; gfarm_error_initialize(); } else { e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } } switch (opt_operation) { case OP_CREATE_ENTRY: if (argc > 0) { e_save = add_host(argv[0], &argv[1], opt_architecture, opt_ncpu); if (e_save != NULL) fprintf(stderr, "%s: %s\n", argv[0], e_save); } break; case OP_MODIFY_ENTRY: if (argc > 0) { e_save = gfarm_modify_host(argv[0], &argv[1], opt_architecture, opt_ncpu, !opt_alter_aliases); if (e_save != NULL) fprintf(stderr, "%s: %s\n", argv[0], e_save); } break; case OP_DELETE_ENTRY: for (i = 0; i < argc; i++) { e = gfarm_host_info_remove(argv[i]); if (e != NULL) { fprintf(stderr, "%s: %s\n", argv[i], e); if (e_save == NULL) e_save = e; } } break; case OP_REGISTER_DB: if (argc > 0) { fprintf(stderr, "%s: too many argument: %s\n", program_name, argv[0]); exit(1); } e_save = register_db(); break; case OP_LIST_GFSD_INFO: if (!opt_plain_order) { if (opt_sort_by_loadavg) { if (opt_sort_reverse) { sort_pid = setup_sort("+0nr"); } else { sort_pid = setup_sort("+0n"); } } else if (opt_udp_only) { if (opt_sort_reverse) { sort_pid = setup_sort("+1r"); } else { sort_pid = setup_sort("+1"); } } else { if (opt_sort_reverse) { sort_pid = setup_sort("+2r"); } else { sort_pid = setup_sort("+2"); } } } e = gfarm_paraccess_alloc(opt_concurrency, !opt_udp_only, &pa); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_gfsd_info, pa); } else { e_save = list_gfsd_info(argc, argv, pa); } e = gfarm_paraccess_free(pa); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_NODENAME: if (!opt_plain_order) { if (opt_sort_reverse) { sort_pid = setup_sort("+0r"); } else { sort_pid = setup_sort("+0"); } } e = gfarm_paraccess_alloc(opt_concurrency, !opt_udp_only, &pa); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_nodename, pa); } else { e_save = list(argc, argv, print_nodename, pa); } e = gfarm_paraccess_free(pa); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_LIST_LONG: if (!opt_plain_order) { if (opt_sort_by_loadavg) { if (opt_sort_reverse) { sort_pid = setup_sort("+0nr"); } else { sort_pid = setup_sort("+0n"); } } else if (opt_udp_only) { if (opt_sort_reverse) { sort_pid = setup_sort("+3r"); } else { sort_pid = setup_sort("+3"); } } else { if (opt_sort_reverse) { sort_pid = setup_sort("+4r"); } else { sort_pid = setup_sort("+4"); } } } e = gfarm_paraccess_alloc(opt_concurrency, !opt_udp_only, &pa); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_long_format, pa); } else { e_save = list(argc, argv, print_long_format, pa); } e = gfarm_paraccess_free(pa); if (e_save == NULL) e_save = e; if (!opt_plain_order && sort_pid != -1) { e = wait_sort(sort_pid); if (e_save == NULL) e_save = e; } break; case OP_DUMP_METADB: if (argc == 0) { e_save = list_all(opt_architecture, opt_domainname, print_host_info, NULL); } else { e_save = list(argc, argv, print_host_info, NULL); } break; } if (need_metadb) { e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } } exit(e_save == NULL ? 0 : 1); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc5/lib/libgfarm/gfarm/gfs_misc.h char *gfs_unlink_replica_internal(const char *, const char *, const char *); <file_sep>/gfarm/tags/gfarm_1_0_beta_3_rev_2/lib/gfs_hook/hooks_init.c /* * $Id$ */ #include <sys/types.h> #include <unistd.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" char * gfs_hook_initialize(void) { #if 0 return "gfs_hook_initialize: Cannot initialize"; #else char *e; _gfs_hook_debug(fprintf(stderr, "GFS: gfs_hook_initialize: set_local(0, 1)\n")); e = gfarm_initialize(NULL, NULL); if (e != NULL) return e; gfs_pio_set_local(0, 1); return NULL; #endif } <file_sep>/gfarm/tags/gfarm_1_0_beta_5_rc1/gftool/gfrcmd/gfrcmd.c #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "gfs_client.h" char *program_name = "gfrcmd"; void usage() { fprintf(stderr, "Usage: %s [option] host command...\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-n: disable standard input.\n"); fprintf(stderr, "\t-r: execute a remote command directly.\n"); fprintf(stderr, "\t-y: inherits the environment variable DISPLAY.\n"); fprintf(stderr, "\t-X: inherits the authentication info of the " "X Window System.\n"); #ifdef HAVE_GSI fprintf(stderr, "\t-v: display GSS minor status error.\n"); #endif exit(1); } char *opt_username; /* ignored for now */ int opt_no_stdin = 0; int opt_raw_command = 0; int opt_xdpy_env = 0; int opt_xauth_copy = 0; int opt_auth_verbose = 0; void parse_option(int *argcp, char ***argvp) { int argc; char **argv, *s; argc = *argcp; argv = *argvp; for (; argc > 0 && argv[0][0] == '-'; argc--, argv++) { for (s = &argv[0][1]; *s; s++) { switch (*s) { case 'l': /* XXX: FIXME. `opt_username' isn't used yet */ if (s[1]) { opt_username = &s[1]; s += strlen(s) - 1; } else if (argc > 1) { opt_username = argv[1]; argc--, argv++; s = argv[0] + strlen(argv[0]) - 1; } else { usage(); } break; case 'n': opt_no_stdin = 1; break; case 'r': opt_raw_command = 1; break; case 'y': opt_xdpy_env = 1; break; case 'X': opt_xauth_copy = 1; break; case 'v': opt_auth_verbose = 1; break; case '?': default: usage(); } } } *argcp = argc; *argvp = argv; } char * concat(int argc, char **argv) { int i, len = 0; char *s; for (i = 0; i < argc; i++) len += strlen(argv[i]); len += argc + 1; s = malloc(len); if (s == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(1); } strcpy(s, argv[0]); for (i = 1; i < argc; i++) { strcat(s, " "); strcat(s, argv[i]); } return (s); } int passing_signals[] = { SIGINT, SIGQUIT, SIGTERM }; volatile int send_signal = 0; void record_signal(int sig) { send_signal = sig; } int main(argc, argv) int argc; char **argv; { char *e, *user, *hostname, *command; char *args[2]; char *envs[2]; char **argp, **envp = NULL; struct gfs_connection *gfs_server; int i, remote_pid, sig, status, coredump; struct hostent *hp; struct sockaddr_in peer_addr; if (argc <= 0) usage(); program_name = basename(argv[0]); argc--, argv++; parse_option(&argc, &argv); if (argc <= 0) usage(); hostname = argv[0]; argc--, argv++; parse_option(&argc, &argv); if (argc <= 0) usage(); e = getenv("GFARM_DEBUG_MODE"); if (e != NULL && strcmp(e, "gdb") == 0) { opt_xauth_copy = 1; envs[0] = "GFARM_DEBUG_MODE=gdb"; envs[1] = NULL; envp = envs; } if (opt_raw_command) { argp = argv; command = argv[0]; } else { args[0] = concat(argc, argv); args[1] = NULL; argp = args; command = args[0]; } if (opt_auth_verbose) gfarm_authentication_verbose = 1; /* * initialization * * XXX * The reason we don't call gfarm_initialize() here is that * we'd like to avoid overhead to access meta database. * but we may have to access meta database eventually * for GSI DN <-> gfarm global username mapping. */ gfarm_error_initialize(); e = gfarm_set_local_user_for_this_local_account(); if (e == NULL) e = gfarm_config_read(); if (e == NULL) e = gfarm_set_global_user_for_this_local_account(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } #if 0 /* XXX - We cannot do this, because we don't access meta database. */ e = gfarm_host_address_get(hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e == NULL) { char *canonical_name; e = gfarm_host_get_canonical_name(hostname, &canonical_name); if (e == NULL) { e = gfs_client_connect(canonical_name, (struct sockaddr *)&peer_addr, &gfs_server); } } #else hp = gethostbyname(hostname); if (hp == NULL || hp->h_addrtype != AF_INET) { e = GFARM_ERR_UNKNOWN_HOST; } else { memset(&peer_addr, 0, sizeof(peer_addr)); memcpy(&peer_addr.sin_addr, hp->h_addr, sizeof(peer_addr.sin_addr)); peer_addr.sin_family = hp->h_addrtype; peer_addr.sin_port = htons(gfarm_spool_server_port); /* XXX - `hostname' may not be a canonical_hostname. */ e = gfs_client_connect(hostname, (struct sockaddr *)&peer_addr, &gfs_server); } #endif if (e != NULL) { fprintf(stderr, "%s: %s\n", hostname, e); exit(1); } user = gfarm_get_global_username(); /* XXX - kluge */ e = gfs_client_mkdir(gfs_server, user, 0755); e = gfs_client_chdir(gfs_server, user); /* for gfs_client_command_send_signal() */ for (i = 0; i < GFARM_ARRAY_LENGTH(passing_signals); i++) { struct sigaction sa; /* * DO NOT set SA_RESTART here, because we rely on the fact * that select(2) breaks with EINTR. * XXX - This is not so portable. Use siglongjmp() instead? */ sa.sa_handler = record_signal; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(passing_signals[i], &sa, NULL); } e = gfs_client_command_request(gfs_server, command, argp, envp, (opt_raw_command ? 0 : GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) | (opt_no_stdin ? GFS_CLIENT_COMMAND_FLAG_STDIN_EOF : 0) | (opt_xdpy_env ? GFS_CLIENT_COMMAND_FLAG_XENVCOPY : 0) | (opt_xauth_copy ? GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY : 0), &remote_pid); if (e == NULL) { char *e2; while (gfs_client_command_is_running(gfs_server)) { e = gfs_client_command_io(gfs_server, NULL); if (e == NULL && send_signal != 0) { e = gfs_client_command_send_signal( gfs_server, send_signal); send_signal = 0; } } e2 = gfs_client_command_result(gfs_server, &sig, &status, &coredump); if (e == NULL) e = e2; } if (e != NULL) { fprintf(stderr, "%s: %s\n", argv[0], e); exit(1); } if (sig) { fprintf(stderr, "%s: signal %d received%s.\n", hostname, sig, coredump ? " (core dumped)" : ""); exit(255); } exit(status); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfquota_cli.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command USERS=`gfusage 2>/dev/null | grep -v '^#' | awk '{ print $1 };'` RESULT=`for u in $USERS; do \ gfquota -u $u | \ awk ' /UserName/ { user=$3 } /FileSpace / { fs=$3 } /FileSpaceSoftLimit/ { fslimit=$3 } /FileNum / { fn=$3 } /FileNumSoftLimit/ { fnlimit=$3 } END{ if (( fslimit !~ /disable/ && fs >= fslimit ) || ( fnlimit !~ /disable/ && fn >= fnlimit )) { print user } }'; \ done` if [ $? != 0 ]; then RESULT="gfquota $* error." fi if [ X"$RESULT" = X ]; then RESULT="---" fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_3_rc1/gftool/gfsck/gfsck.c /* * $Id$ */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <libgen.h> #include <limits.h> #include <gfarm/gfarm.h> static int option_verbose; static char * gfsck_file(char *gfarm_url) { char *gfarm_file, *e, *e_save = NULL; int i, nsections, valid_nsections = 0; struct gfarm_file_section_info *sections; GFS_File gf; e = gfs_pio_open(gfarm_url, GFARM_FILE_RDONLY, &gf); if (e != NULL) { return (e); } e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { (void)gfs_pio_close(gf); return (e); } e = gfarm_file_section_info_get_all_by_file( gfarm_file, &nsections, &sections); if (e != NULL) { /* no section info, remove path info */ e = gfarm_path_info_remove(gfarm_file); if (e == NULL) printf("%s: invalid metadata deleted\n", gfarm_url); else fprintf(stderr, "%s: %s\n", gfarm_url, e); free(gfarm_file); (void)gfs_pio_close(gf); return (e); } for (i = 0; i < nsections; i++) { int j, ncopies, valid_ncopies = 0; struct gfarm_file_section_copy_info *copies; char *section = sections[i].section; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* no section copy info, remove section info */ e = gfarm_file_section_info_remove( gfarm_file, section); if (e == NULL) { printf("%s (%s): invalid metadata deleted\n", gfarm_url, section); } else { fprintf(stderr, "%s (%s): %s\n", gfarm_url, section, e); if (e_save == NULL) e_save = e; } continue; } if (e != NULL) { fprintf(stderr, "%s (%s): %s\n", gfarm_url, section, e); if (e_save == NULL) e_save = e; continue; } for (j = 0; j < ncopies; ++j) { if (option_verbose) printf("%s (%s) on %s\n", gfarm_url, section, copies[j].hostname); e = gfs_pio_set_view_section(gf, section, copies[j].hostname, GFARM_FILE_NOT_REPLICATE | GFARM_FILE_NOT_RETRY); if (e == GFARM_ERR_INCONSISTENT_RECOVERABLE) { /* invalid section copy info removed */ printf("%s (%s) on %s: " "invalid metadata deleted\n", gfarm_url, section, copies[j].hostname); e = NULL; } else { ++valid_ncopies; if (e != NULL) { fprintf(stderr, "%s (%s) on %s: %s\n", gfarm_url, section, copies[j].hostname, e); if (e_save == NULL) e_save = e; } } } gfarm_file_section_copy_info_free_all(ncopies, copies); if (valid_ncopies == 0) { /* no section copy info, remove section info */ e = gfarm_file_section_info_remove( gfarm_file, section); if (e == NULL) { printf("%s (%s): invalid metadata deleted\n", gfarm_url, section); } else { fprintf(stderr, "%s (%s): %s\n", gfarm_url, section, e); if (e_save == NULL) e_save = e; } } else ++valid_nsections; } if (valid_nsections == 0) { /* no section info, remove path info */ e = gfarm_path_info_remove(gfarm_file); if (e == NULL) { printf("%s: invalid metadata deleted\n", gfarm_url); } else { fprintf(stderr, "%s: %s\n", gfarm_url, e); if (e_save == NULL) e_save = e; } } else if (valid_nsections < nsections) { printf("%s: warning: number of file sections reduced\n", gfarm_url); } gfarm_file_section_info_free_all(nsections, sections); free(gfarm_file); e = gfs_pio_close(gf); if (e != NULL) return (e); return (e_save); } static char * gfsck_dir(char *gfarm_dir, char *file) { char *e, *e_save = NULL, *gfarm_url; struct gfs_stat gsb; GFS_Dir gdir; struct gfs_dirent *gdent; gfarm_url = malloc(strlen(gfarm_dir) + strlen(file) + 2); if (gfarm_url == NULL) return (GFARM_ERR_NO_MEMORY); if (gfarm_dir[0] == '\0') sprintf(gfarm_url, "%s", file); else sprintf(gfarm_url, "%s/%s", gfarm_dir, file); e = gfs_stat(gfarm_url, &gsb); if (e != NULL) { free(gfarm_url); return (e); } if (GFARM_S_ISREG(gsb.st_mode)) { gfs_stat_free(&gsb); e = gfsck_file(gfarm_url); free(gfarm_url); return (e); } if (!GFARM_S_ISDIR(gsb.st_mode)) { gfs_stat_free(&gsb); free(gfarm_url); return ("unknown file type"); } gfs_stat_free(&gsb); e = gfs_opendir(gfarm_url, &gdir); if (e != NULL) { free(gfarm_url); return (e); } while ((e = gfs_readdir(gdir, &gdent)) == NULL && gdent != NULL) { e = gfsck_dir(gfarm_url, gdent->d_name); if (e != NULL) { fprintf(stderr, "%s/%s: %s\n", gfarm_url, gdent->d_name, e); if (e_save == NULL) e_save = e; } } (void)gfs_closedir(gdir); free(gfarm_url); return (e_save); } char *program_name = "gfsck"; static void usage() { fprintf(stderr, "Usage: %s [-vh] path ...\n", program_name); exit(1); } int main(int argc, char *argv[]) { extern int optind; int c, i, error = 0; gfarm_stringlist paths; gfs_glob_t types; char *e; if (argc <= 1) usage(); program_name = basename(argv[0]); while ((c = getopt(argc, argv, "hv?")) != EOF) { switch (c) { case 'v': option_verbose = 1; break; case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { char *url = gfarm_stringlist_elem(&paths, i); e = gfsck_dir("", url); if (e != NULL) { fprintf(stderr, "%s: %s\n", url, e); error = 1; } } gfs_glob_free(&types); gfarm_stringlist_free_deeply(&paths); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(error); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_0_1/gfarm2fs.c /* * GfarmFS-FUSE for Gfarm version 2 * * $Id$ */ #include "config.h" #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <fcntl.h> #include <errno.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif /* * fuse.h requres that _FILE_OFFSET_BITS is defined in any case, but * AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 * since it is not necessary. To avoid this problem we define it here. */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #define FUSE_USE_VERSION 25 #include <fuse.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> /* XXX FIXME */ #define GFS_DEV ((dev_t)-1) #define GFS_BLKSIZE 8192 #define STAT_BLKSIZ 512 /* for st_blocks */ static uid_t get_uid(char *user) { if (strcmp(gfarm_get_global_username(), user) == 0) return getuid(); /* my own file */ /* XXX FIXME - some other's file */ return (0); } static int get_gid(char *group) { /* XXX FIXME */ return (0); } static int get_nlink(struct gfs_stat *st) { /* XXX FIXME */ return (GFARM_S_ISDIR(st->st_mode) ? 32000 : st->st_nlink); } static void copy_gfs_stat(struct stat *dst, struct gfs_stat *src) { memset(dst, 0, sizeof(*dst)); dst->st_dev = GFS_DEV; dst->st_ino = src->st_ino; dst->st_mode = src->st_mode; dst->st_nlink = get_nlink(src); dst->st_uid = get_uid(src->st_user); dst->st_gid = get_gid(src->st_group); dst->st_size = src->st_size; dst->st_blksize = GFS_BLKSIZE; dst->st_blocks = (src->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; dst->st_atime = src->st_atimespec.tv_sec; dst->st_mtime = src->st_mtimespec.tv_sec; dst->st_ctime = src->st_ctimespec.tv_sec; } static int gfarm2fs_getattr(const char *path, struct stat *stbuf) { struct gfs_stat st; gfarm_error_t e; e = gfs_stat(path, &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); copy_gfs_stat(stbuf, &st); gfs_stat_free(&st); return (0); } static inline GFS_File get_filep(struct fuse_file_info *fi) { return (GFS_File) (uintptr_t) fi->fh; } static int gfarm2fs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { struct gfs_stat st; gfarm_error_t e; e = gfs_pio_stat(get_filep(fi), &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); copy_gfs_stat(stbuf, &st); gfs_stat_free(&st); return (0); } static int gfarm2fs_access(const char *path, int mask) { /* XXX FIXME */ return (-ENOSYS); #if 0 gfarm_error_t e; e = gfs_access(path, mask); return (-gfarm_error_to_errno(e)); #endif } static int gfarm2fs_readlink(const char *path, char *buf, size_t size) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res; res = readlink(path, buf, size - 1); if (res == -1) return -errno; buf[res] = '\0'; return 0; #endif } static int gfarm2fs_opendir(const char *path, struct fuse_file_info *fi) { gfarm_error_t e; GFS_Dir dp; e = gfs_opendir(path, &dp); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) dp; return (0); } static inline GFS_Dir get_dirp(struct fuse_file_info *fi) { return (GFS_Dir) (uintptr_t) fi->fh; } static int gfarm2fs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); struct gfs_dirent *de; struct stat st; /* gfarm_off_t off = 0; */ gfarm_error_t e; (void) path; /* XXX gfs_seekdir(dp, offset); */ while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { memset(&st, 0, sizeof(st)); st.st_ino = de->d_fileno; st.st_mode = de->d_type << 12; /* XXX (void)gfs_telldir(dp, &off); */ if (filler(buf, de->d_name, &st, 0)) break; } return (0); } static int gfarm2fs_releasedir(const char *path, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); (void) path; gfs_closedir(dp); return (0); } static int gfarm2fs_mknod(const char *path, mode_t mode, dev_t rdev) { GFS_File gf; gfarm_error_t e; if (!S_ISREG(mode)) return (-ENOSYS); e = gfs_pio_create(path, GFARM_FILE_WRONLY, mode & GFARM_S_ALLPERM, &gf); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_close(gf); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_mkdir(const char *path, mode_t mode) { gfarm_error_t e; e = gfs_mkdir(path, mode & GFARM_S_ALLPERM); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_unlink(const char *path) { gfarm_error_t e; e = gfs_unlink(path); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_rmdir(const char *path) { gfarm_error_t e; e = gfs_rmdir(path); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_symlink(const char *from, const char *to) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res; res = symlink(from, to); if (res == -1) return -errno; return 0; #endif } static int gfarm2fs_rename(const char *from, const char *to) { gfarm_error_t e; e = gfs_rename(from, to); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_link(const char *from, const char *to) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res; res = link(from, to); if (res == -1) return -errno; return 0; #endif } static int gfarm2fs_chmod(const char *path, mode_t mode) { gfarm_error_t e; e = gfs_chmod(path, mode & GFARM_S_ALLPERM); return (-gfarm_error_to_errno(e)); } #if 0 static char * get_user(uid_t uid) { /* XXX FIXME */ return "user"; } static char * get_group(uid_t gid) { /* XXX FIXME */ return "group"; } #endif static int gfarm2fs_chown(const char *path, uid_t uid, gid_t gid) { struct gfs_stat st; gfarm_error_t e; /* XXX FIXME */ if (uid == getuid()) { e = gfs_stat(path, &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); if (strcmp(st.st_user, gfarm_get_global_username()) == 0) { gfs_stat_free(&st); return (0); } gfs_stat_free(&st); } return (-ENOSYS); #if 0 gfarm_error_t e; char *user, *group; user = get_user(uid); group = get_group(gid); e = gfs_chown(path, user, group); return (-gfarm_error_to_errno(e)); #endif } static int gfarm2fs_truncate(const char *path, off_t size) { gfarm_error_t e, e2; GFS_File gf; e = gfs_pio_open(path, GFARM_FILE_WRONLY, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); e = gfs_pio_truncate(gf, size); e2 = gfs_pio_close(gf); return (-gfarm_error_to_errno(e != GFARM_ERR_NO_ERROR ? e : e2)); } static int gfarm2fs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { gfarm_error_t e; (void) path; e = gfs_pio_truncate(get_filep(fi), size); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_utime(const char *path, struct utimbuf *buf) { struct gfarm_timespec gt[2]; gfarm_error_t e; if (buf != NULL) { gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; } e = gfs_utimes(path, gt); return (-gfarm_error_to_errno(e)); } static int gfs_hook_open_flags_gfarmize(int open_flags) { int gfs_flags; switch (open_flags & O_ACCMODE) { case O_RDONLY: gfs_flags = GFARM_FILE_RDONLY; break; case O_WRONLY: gfs_flags = GFARM_FILE_WRONLY; break; case O_RDWR: gfs_flags = GFARM_FILE_RDWR; break; default: return (-1); } #if 0 /* this is unnecessary */ if ((open_flags & O_CREAT) != 0) gfs_flags |= GFARM_FILE_CREATE; #endif if ((open_flags & O_TRUNC) != 0) gfs_flags |= GFARM_FILE_TRUNC; #if 0 /* not yet on Gfarm v2 */ if ((open_flags & O_APPEND) != 0) gfs_flags |= GFARM_FILE_APPEND; if ((open_flags & O_EXCL) != 0) gfs_flags |= GFARM_FILE_EXCLUSIVE; #endif #if 0 /* not yet on Gfarm v2 */ /* open(2) and creat(2) should be unbuffered */ gfs_flags |= GFARM_FILE_UNBUFFERED; #endif return (gfs_flags); } static int gfarm2fs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { gfarm_error_t e; GFS_File gf; int flags; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfs_pio_create(path, flags, mode & GFARM_S_ALLPERM, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) gf; return (0); } static int gfarm2fs_open(const char *path, struct fuse_file_info *fi) { GFS_File gf; int flags; gfarm_error_t e; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfs_pio_open(path, flags, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) gf; return (0); } static int gfarm2fs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; (void) path; e = gfs_pio_seek(get_filep(fi), offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_read(get_filep(fi), buf, size, &rv); if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); return (rv); } static int gfarm2fs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; (void) path; e = gfs_pio_seek(get_filep(fi), offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_write(get_filep(fi), buf, size, &rv); if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); return (rv); } static int gfarm2fs_statfs(const char *path, struct statvfs *stbuf) { gfarm_error_t e; gfarm_off_t used, avail, files; e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); else { stbuf->f_bsize = 1024; /* XXX */ stbuf->f_frsize = 1024; /* XXX */ stbuf->f_blocks = used + avail; stbuf->f_bfree = avail; stbuf->f_bavail = avail; stbuf->f_files = files; stbuf->f_ffree = -1; /* XXX */ stbuf->f_favail = -1; /* XXX */ stbuf->f_fsid = 298; /* XXX */ stbuf->f_flag = 0; /* XXX */ stbuf->f_namemax = GFS_MAXNAMLEN; } return (0); } static int gfarm2fs_release(const char *path, struct fuse_file_info *fi) { (void) path; gfs_pio_close(get_filep(fi)); return (0); } static int gfarm2fs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { gfarm_error_t e; (void) path; if (isdatasync) e = gfs_pio_datasync(get_filep(fi)); else e = gfs_pio_sync(get_filep(fi)); return (-gfarm_error_to_errno(e)); } #ifdef HAVE_SETXATTR /* xattr operations are optional and can safely be left unimplemented */ static int gfarm2fs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res = lsetxattr(path, name, value, size, flags); if (res == -1) return -errno; return 0; #endif } static int gfarm2fs_getxattr(const char *path, const char *name, char *value, size_t size) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res = lgetxattr(path, name, value, size); if (res == -1) return -errno; return res; #endif } static int gfarm2fs_listxattr(const char *path, char *list, size_t size) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res = llistxattr(path, list, size); if (res == -1) return -errno; return res; #endif } static int gfarm2fs_removexattr(const char *path, const char *name) { /* XXX FIXME */ return (-ENOSYS); #if 0 int res = lremovexattr(path, name); if (res == -1) return -errno; return 0; #endif } #endif /* HAVE_SETXATTR */ static struct fuse_operations gfarm2fs_oper = { .getattr = gfarm2fs_getattr, .fgetattr = gfarm2fs_fgetattr, .access = gfarm2fs_access, .readlink = gfarm2fs_readlink, .opendir = gfarm2fs_opendir, .readdir = gfarm2fs_readdir, .releasedir = gfarm2fs_releasedir, .mknod = gfarm2fs_mknod, .mkdir = gfarm2fs_mkdir, .symlink = gfarm2fs_symlink, .unlink = gfarm2fs_unlink, .rmdir = gfarm2fs_rmdir, .rename = gfarm2fs_rename, .link = gfarm2fs_link, .chmod = gfarm2fs_chmod, .chown = gfarm2fs_chown, .truncate = gfarm2fs_truncate, .ftruncate = gfarm2fs_ftruncate, .utime = gfarm2fs_utime, .create = gfarm2fs_create, .open = gfarm2fs_open, .read = gfarm2fs_read, .write = gfarm2fs_write, .statfs = gfarm2fs_statfs, .release = gfarm2fs_release, .fsync = gfarm2fs_fsync, #ifdef HAVE_SETXATTR .setxattr = gfarm2fs_setxattr, .getxattr = gfarm2fs_getxattr, .listxattr = gfarm2fs_listxattr, .removexattr= gfarm2fs_removexattr, #endif }; int main(int argc, char *argv[]) { gfarm_error_t e; char **nargv; umask(0); e = gfarm_initialize(&argc, &argv); if (e != GFARM_ERR_NO_ERROR) { fprintf(stderr, "%s: %s\n", *argv, gfarm_error_string(e)); exit(1); } /* * specify '-s' option to disable multithreaded operations * libgfarm is not thread-safe for now */ ++argc; nargv = malloc(sizeof(*argv) * (argc + 1)); if (nargv == NULL) { fprintf(stderr, "%s: no memory\n", *argv); exit(1); } memcpy(nargv, argv, sizeof(*argv) * (argc - 1)); nargv[argc - 1] = "-s"; nargv[argc] = ""; return (fuse_main(argc, nargv, &gfarm2fs_oper)); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT3-3-1-4_failover_while_syncing_metadata #! /bin/sh ###################################################################### TESTID="FT3-3-1-4" CATEGORY="accident while failover and failure of meta data sync" SECTION="failover in the midst of client accessd" TITLE="failover while syncing metadata" ###################################################################### . ./FT-common ft_setup() { TESTDIR="/$TESTID.$$" INTERVAL=60 RESULT=$FT_RESULT_PASS gfmkdir -p $TESTDIR [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL return $RESULT } ft_main() { R1=$FT_RESULT_PASS $gfservice stop-gfmd gfmd2 \ || R1=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd2" $R1 [ $R1 -eq $FT_RESULT_PASS ] || return $R1 R2=$FT_RESULT_PASS I=0 N_TIMES=4096 while [ $I -lt $N_TIMES ]; do gfmkdir $TESTDIR/$I if [ $? -ne 0 ]; then R2=$FT_RESULT_FAIL break fi I=`expr $I + 1` done ft_checkpoint 2 "create many directories by gfmkdir on $client1" $R2 [ $R2 -eq $FT_RESULT_PASS ] || return $R2 R3=$FT_RESULT_PASS $gfservice start-gfmd gfmd2 \ || R3=$FT_RESULT_FAIL ft_checkpoint 3 "start gfmd on $gfmd2" $R3 [ $R3 -eq $FT_RESULT_PASS ] || return $R3 R4=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || R4=$FT_RESULT_FAIL ft_checkpoint 4 "stop gfmd on $gfmd1" $R4 [ $R4 -eq $FT_RESULT_PASS ] || return $R4 R5=$FT_RESULT_PASS ssh $gfmd3 "sudo kill -USR1 \`cat /var/run/gfmd.pid\`" \ || R5=$FT_RESULT_FAIL ft_checkpoint 5 "upgrade slave gfmd on $gfmd3" $R5 [ $R5 -eq $FT_RESULT_PASS ] || return $R5 R6=$FT_RESULT_FAIL I=0 N_TIMES=10 while [ $I -lt $N_TIMES ]; do CHK_GFMDHOST=`gfmdhost -l | grep $gfmd3 | grep '^+'` if [ "X$CHK_GFMDHOST" != X ]; then R6=$FT_RESULT_PASS break fi I=`expr $I + 1` sleep $INTERVAL done ft_checkpoint 6 "check finish syncing metadata on $gfmd3" $R6 [ $R6 -eq $FT_RESULT_PASS ] || return $R6 return $FT_RESULT_PASS } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8_1/systest/plugins/Makefile.am gfservicedir = $(datadir)/gfarm/gfservice dist_gfservice_DATA = check_files \ check_files_n_each_mntpnts \ log_view \ make_files \ make_files_n \ make_files_n_each_mntpnts \ mkdir_n \ read_files_n \ remove_files \ remove_files_each_mntpnts \ rmdir_n \ exec_ssh \ spool_file_exists <file_sep>/gfarm/tags/gfarm_1_0_beta_5/bench/nconnect/nconnect.c /* * Copyright (C) 1993-2000 by Software Research Associates, Inc. * 1-1-1 Hirakawa-cho, Chiyoda-ku, Tokyo 102-8605, Japan * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE SOFTWARE RESEARCH * ASSOCIATES BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of the Software * Research Associates shall not be used in advertising or otherwise * to promote the sale, use or other dealings in this Software without * prior written authorization from the Software Research Associates. * * Id: nconnect.c,v 1.21 2002/09/19 06:43:57 soda Exp * */ #include <sys/types.h> #include <sys/param.h> /* ntohs(), ... for BSD direct descendant */ #include <sys/socket.h> #include <sys/un.h> /* PF_UNIX */ #include <netinet/in.h> /* PF_INET */ #include <netinet/tcp.h> /* TCP_NODELAY */ #include <arpa/inet.h> /* inet_addr(), inet_ntoa() */ #include <netdb.h> /* gethostbyname(), getservbyname(), ... */ #include <stdio.h> #include <ctype.h> #include <signal.h> /* SIGPIPE */ #include <errno.h> extern int errno; /* some <errno.h> doesn't define `errno' */ #ifdef __STDC__ #include <string.h> /* strlen(), ... & bzero()/bcopy()/bcmp() */ #include <stdlib.h> /* atoi(), ... */ #endif #ifndef NO_UNISTD_H #include <unistd.h> #endif #include <sys/wait.h> /* waitpid()/wait3() */ #ifdef _AIX #include <sys/select.h> /* fd_set, ... */ #endif /* 2nd argument of shutdown(2) */ #define SHUTDOWN_RECV 0 /* shutdown receive */ #define SHUTDOWN_SEND 1 /* shutdown send */ #define SHUTDOWN_SOCK 2 /* shutdown send & receive */ /* 2nd argument of listen(2) */ #define LISTEN_BACKLOG 5 /*** portable ************************************************/ #ifdef POSIX # define NO_BSTRING # define NO_INDEX #endif #ifdef NO_BSTRING #define bcmp(a, b, length) memcmp(a, b, length) #define bcopy(s, d, length) memcpy(d, s, length) #define bzero(b, length) memset(b, 0, length) #endif extern char *index(), *rindex(); #ifdef NO_INDEX extern char *strchr(), *strrchr(); #define index(string, c) strchr(string, c) #define rindex(string, c) strrchr(string, c) #endif #ifdef NO_SIZE_T typedef int size_t; #endif #ifdef __STDC__ typedef void *Pointer; #else typedef char *Pointer; #define const #define volatile #endif extern Pointer malloc(); #ifndef POSIX # if !defined(SIGTSTP) || defined(SV_BSDSIG) || defined(SA_OLDSTYLE) || (defined(SA_NOCLDWAIT) && defined(SIGCLD)) /* SysV3 or earlier || HP-UX || AIX || SVR4 */ # define CAN_IGNORE_ZOMBIE # define SIGNAL signal # else /* guarantee reliable signal */ void (*reliable_signal(sig, handler))() int sig; void (*handler)(); { struct sigvec sv, osv; sv.sv_handler = handler; sv.sv_mask = 0; sv.sv_flags = 0; /* XXX - no singal stack */ if (sigvec(sig, &sv, &osv) < 0) return (void (*)())-1; return osv.sv_handler; } # define SIGNAL reliable_signal # endif #else /* POSIX - don't use undefined behavior */ /* * This function installs reliable signal handler, but not (always) * BSD signal compatible. Because interrupted system call is not * always restarted. * At least, BSD Net/2 or later and SVR4 and AIX (SA_RESTART is not * specified) and HP-UX (struct sigcontext::sc_syscall_action == * SIG_RETURN) are not BSD compatible. On SunOS4, this function is BSD * signal compatible (because SA_INTERRUPT is not specifed). */ void (*reliable_signal(sig, handler))() int sig; void (*handler)(); { struct sigaction sa, osa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(sig, &sa, &osa) < 0) return (void (*)())-1; return osa.sa_handler; } # define SIGNAL reliable_signal #endif /* POSIX */ /*** miscellaneous *******************************************/ #define ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0])) typedef int Bool; #define YES 1 #define NO 0 static char *progname = "nconnect"; static Bool debug_flag = NO; #define debug(statement) \ { \ if (debug_flag) { \ statement; \ } \ } #define EXIT_OK 0 #define EXIT_USAGE 2 #define EXIT_NETERR 1 #define EXIT_SYSERR 3 void fatal(message) char *message; { perror(message); exit(EXIT_NETERR); } Pointer emalloc(size) size_t size; { Pointer p = malloc(size); if (p == NULL) { fprintf(stderr, "%s: no memory\n", progname); exit(EXIT_SYSERR); } return p; } /*** sockaddr ************************************************/ union generic_sockaddr { struct sockaddr address; struct sockaddr_un un; struct sockaddr_in in; }; size_t make_unix_address(address, pathname) struct sockaddr_un *address; char *pathname; { size_t len = strlen(pathname); if (len >= sizeof(address->sun_path)) { fputs(pathname, stderr); fputs(": socket name too long\n", stderr); exit(EXIT_USAGE); } bzero((char *)address, sizeof(*address)); /* needless ? */ bcopy(pathname, address->sun_path, len + 1); address->sun_family = AF_UNIX; #ifdef SUN_LEN /* derived from 4.4BSD */ return SUN_LEN(address); #else return sizeof(*address) - sizeof(address->sun_path) + len; #endif } /* * make Internet address * argument `ip_address' is network byte order IP-address, * or htonl(INADDR_ANY), or htonl(INADDR_BROADCAST). * argument `port' is network byte order port-number or 0. * 0 is for bind(2). bind(2) automagically allocates port number. */ size_t make_inet_address(address, ip_address, port) struct sockaddr_in *address; unsigned long ip_address; int port; { bzero((char *)address, sizeof(*address)); address->sin_addr.s_addr = ip_address; address->sin_family = AF_INET; address->sin_port = port; return sizeof(*address); } size_t make_inet_address_by_string(address, host, port) struct sockaddr_in *address; char *host; int port; { struct hostent *hp; struct in_addr in; if ((in.s_addr = inet_addr(host)) != (unsigned long)-1) return make_inet_address(address, in.s_addr, port); if ((hp = gethostbyname(host)) != NULL) { bzero((char *)address, sizeof(*address)); bcopy(hp->h_addr, (char *)&address->sin_addr, sizeof(address->sin_addr)); address->sin_family = hp->h_addrtype; address->sin_port = port; return sizeof(*address); } /* * BUG: * if (hp == NULL && h_errno == TRY_AGAIN) * we must try again; */ fputs(host, stderr); fputs(": unknown host\n", stderr); exit(EXIT_USAGE); } int make_inet_port_by_string(portname, protocol) char *portname, *protocol; { struct servent *sp; if (isdigit(portname[0])) { return htons(atoi(portname)); } else { if (protocol == NULL) { fprintf(stderr, "%s: need port number\n", portname); exit(EXIT_SYSERR); } if ((sp = getservbyname(portname, protocol)) == NULL) { fprintf(stderr, "%s/%s: unknown service\n", portname, protocol); exit(EXIT_SYSERR); } return sp->s_port; } } size_t make_socket_address(address, name, socket_type) union generic_sockaddr *address; char *name; int socket_type; { int rv; if (bcmp(name, "unix/", (size_t)5) == 0) { /* AF_UNIX */ return make_unix_address(&address->un, name + 5); } else { /* AF_INET */ char *colon = index(name, ':'), *protocol; int port; if (colon == NULL) { port = 0; } else { *colon = '\0'; /* XXX - breaks *name */ switch (socket_type) { case SOCK_STREAM: protocol = "tcp"; break; case SOCK_DGRAM: protocol = "udp"; break; default: protocol = NULL; break; } port = make_inet_port_by_string(colon + 1, protocol); } rv = *name == '\0' ? make_inet_address(&address->in, htonl(INADDR_ANY), port) : make_inet_address_by_string(&address->in, name, port); if (colon != NULL) *colon = ':'; /* XXX - restore *name */ return rv; } } int make_socket_type(name) char *name; { if (strcmp(name, "stream") == 0) return SOCK_STREAM; else if (strcmp(name, "dgram") == 0 || strcmp(name, "datagram") == 0) return SOCK_DGRAM; #ifdef USE_RAW_SOCKET else if (strcmp(name, "raw") == 0) return SOCK_RAW; #endif else if (strcmp(name, "rdm") == 0) /* reliably-delivered message */ return SOCK_RDM; else if (strcmp(name, "seqpacket") == 0) /* sequenced packet stream */ return SOCK_SEQPACKET; else { fprintf(stderr, "%s: unknown socket type \"%s\"\n", progname, name); exit(EXIT_NETERR); } } Bool socket_type_is_stream(socket_type) int socket_type; { switch (socket_type) { case SOCK_STREAM: return YES; default: return NO; } } void print_sockaddr(fp, address, addr_size) FILE *fp; struct sockaddr *address; size_t addr_size; { union generic_sockaddr *p = (union generic_sockaddr *)address; switch (p->address.sa_family) { case AF_UNIX: fputs("AF_UNIX: pathname = \"", fp); fwrite(p->un.sun_path, sizeof(char), addr_size - (sizeof(p->un) - sizeof(p->un.sun_path)), fp); fputs("\"\n", fp); break; case AF_INET: fprintf(fp, "AF_INET: address = %s, port = %d\n", inet_ntoa(p->in.sin_addr), ntohs(p->in.sin_port)); break; default: fprintf(fp,"%s: unknown address family %d\n", progname, p->address.sa_family); break; } } void print_sockname(fd) int fd; { union generic_sockaddr generic; int addr_size = sizeof(generic); if (getsockname(fd, &generic.address, &addr_size) < 0) { perror("getsockname"); /* exit(EXIT_NETERR); */ } else { print_sockaddr(stderr, &generic.address, (size_t)addr_size); } } void print_peername(fd) int fd; { union generic_sockaddr generic; int addr_size = sizeof(generic); if (getpeername(fd, &generic.address, &addr_size) < 0) { perror("getpeername"); /* exit(EXIT_NETERR); */ } else { print_sockaddr(stderr, &generic.address, (size_t)addr_size); } } void print_sockport(fp, fd) FILE *fp; int fd; { union generic_sockaddr generic; int addr_size = sizeof(generic); if (getsockname(fd, &generic.address, &addr_size) < 0) { fatal("getsockname"); } switch (generic.address.sa_family) { case AF_INET: fprintf(fp, "%d\n", ntohs(generic.in.sin_port)); break; default: fprintf(fp,"%s: cannot print port for address family %d\n", progname, generic.address.sa_family); exit(EXIT_SYSERR); } } /*** Queue ***************************************************/ #define QBUFSIZE 4096 typedef struct Queue { char buffer[QBUFSIZE]; int length; int point; char *tag; } Queue; char *session_log = NULL; /* default - do not log session */ FILE *session_log_fp = NULL; /* default - log file is not opened */ void makeQueue(q, tag) Queue *q; char *tag; { q->length = 0; q->point = 0; q->tag = tag; } Bool queueIsEmpty(q) Queue *q; { return q->point >= q->length; } Bool queueIsFull(q) Queue *q; { /* this queue is NOT true queue */ return !queueIsEmpty(q); } Bool enqueue(q, fd) /* if success (not end-of-file) then YES */ Queue *q; int fd; { int done; if (queueIsFull(q)) return YES; done = read(fd, q->buffer, QBUFSIZE); debug(fprintf(stderr, "\tread() - %d\n", done)); if (done < 0) { if (errno == EINTR) return YES; fatal("enqueue"); } q->point = 0; q->length = done; if (session_log != NULL) { switch (session_log_fp == NULL) { case 1: session_log_fp = fopen(session_log, "a"); if (session_log_fp == NULL) { perror(session_log); session_log = NULL; /* give up logging */ break; } /*FALLTHROUGH*/ default: fprintf(session_log_fp, "%s:%d/<%.*s>\n", q->tag, done, done, q->buffer); fflush(session_log_fp); break; } } return done > 0; } void dequeue(q, fd) Queue *q; int fd; { int done; if (queueIsEmpty(q)) return; done = write(fd, q->buffer + q->point, q->length - q->point); debug(fprintf(stderr, "\twrite() - %d\n", done)); if (done < 0) { if (errno == EINTR) return; fatal("dequeue"); } q->point += done; } /*** sockopts ************************************************/ static struct sockopt_table { char *name, *proto; int level, option, default_value; } sockopt_tab[] = { { "debug", NULL, SOL_SOCKET, SO_DEBUG, 1, }, { "reuseaddr", NULL, SOL_SOCKET, SO_REUSEADDR, 1, }, { "keepalive", NULL, SOL_SOCKET, SO_KEEPALIVE, 1, }, { "dontroute", NULL, SOL_SOCKET, SO_DONTROUTE, 1, }, { "broadcast", NULL, SOL_SOCKET, SO_BROADCAST, 1, }, #if defined(SO_USELOOPBACK) { "useloopback",NULL, SOL_SOCKET, SO_USELOOPBACK, 1, }, #endif { "linger", NULL, SOL_SOCKET, SO_LINGER, 1, }, { "oobinline", NULL, SOL_SOCKET, SO_OOBINLINE, 1, }, #if defined(SO_REUSEPORT) { "reuseport", NULL, SOL_SOCKET, SO_REUSEPORT, 1, }, #endif { "sndbuf", NULL, SOL_SOCKET, SO_SNDBUF, 16384, }, { "rcvbuf", NULL, SOL_SOCKET, SO_RCVBUF, 16384, }, { "sndlowat", NULL, SOL_SOCKET, SO_SNDLOWAT, 2048, }, { "rcvlowat", NULL, SOL_SOCKET, SO_RCVLOWAT, 1, }, #if 0 /* typeof(option) == struct timeval */ { "sndtimeo", NULL, SOL_SOCKET, SO_SNDTIMEO, , }, { "rcvtimeo", NULL, SOL_SOCKET, SO_RCVTIMEO, , }, #endif { "tcp_nodelay","tcp", 0, TCP_NODELAY, 1, }, }; #define MAX_SOCKOPTS ARRAY_LENGTH(sockopt_tab) int nsockopts = 0; struct socket_option { char *string; int level, option, value; } sockopts[MAX_SOCKOPTS]; void record_sockopt(option) char *option; { /* * SO_TYPE and SO_ERROR are used for * getsockopt() only. * SO_ACCEPTCONN, ... */ struct sockopt_table *tab; char *equal; struct protoent *proto; equal = strchr(option, '='); if (equal != NULL) *equal = '\0'; for (tab = sockopt_tab; tab < &sockopt_tab[MAX_SOCKOPTS]; tab++) { if (strcmp(option, tab->name) == 0) { if (nsockopts >= MAX_SOCKOPTS) { fprintf(stderr, "%s: too many socket options", progname); exit(EXIT_USAGE); } sockopts[nsockopts].string = option; if (tab->proto == NULL) { sockopts[nsockopts].level = tab->level; } else { proto = getprotobyname(tab->proto); if (proto == NULL) { fprintf(stderr, "%s: getprotobyname(\"%s\") failed\n", progname, tab->proto); exit(EXIT_SYSERR); } sockopts[nsockopts].level = proto->p_proto; } sockopts[nsockopts].option = tab->option; if (equal == NULL) sockopts[nsockopts].value = tab->default_value; else sockopts[nsockopts].value = atol(equal + 1); nsockopts++; if (equal != NULL) *equal = '='; return; } } fprintf(stderr, "%s: unknown socket option \"%s\"\n", progname, option); exit(EXIT_USAGE); } void apply_sockopts(fd) int fd; { int i; for (i = 0; i < nsockopts; i++) { if (setsockopt(fd, sockopts[i].level, sockopts[i].option, &sockopts[i].value, sizeof(sockopts[i].value)) == -1) { fatal(sockopts[i].string); } } } /*** main ***************************************************/ void broken_pipe_handler(sig) int sig; { fprintf(stderr, "%s: Broken pipe or socket\n", progname); exit(EXIT_NETERR); } void set_fd(set, fd, available) fd_set *set; int fd; Bool available; { if (available) FD_SET(fd, set); else FD_CLR(fd, set); } enum SocketMode { sock_sendrecv, sock_send, sock_recv }; void transfer(fd, socket_mode, one_eof_exit) int fd; enum SocketMode socket_mode; Bool one_eof_exit; { fd_set readfds, writefds, exceptfds; int nfds = fd + 1, nfound; Bool eof_stdin = NO, eof_socket = NO; Queue sendq, recvq; debug(SIGNAL(SIGPIPE, broken_pipe_handler)); switch (socket_mode) { case sock_recv: eof_stdin = YES; break; case sock_send: eof_socket = YES; break; } FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); makeQueue(&sendq, "SEND"); makeQueue(&recvq, "RECV"); while (!eof_stdin || !queueIsEmpty(&sendq) || !eof_socket || !queueIsEmpty(&recvq)) { set_fd(&readfds, 0, !queueIsFull(&sendq) && !eof_stdin); set_fd(&readfds, fd, !queueIsFull(&recvq) && !eof_socket); set_fd(&writefds, fd, !queueIsEmpty(&sendq)); set_fd(&writefds, 1, !queueIsEmpty(&recvq)); debug(fprintf(stderr, "\tselect() wait : %d%d%d%d\n", FD_ISSET(0, &readfds)!=0, FD_ISSET(1, &writefds)!=0, FD_ISSET(fd,&readfds)!=0, FD_ISSET(fd,&writefds)!=0)); /* if socket is EOF, select() says "you can read socket." */ nfound = select(nfds, &readfds, &writefds, &exceptfds, NULL); debug(fprintf(stderr, "\tselect() -- %d : %d%d%d%d\n", nfound, FD_ISSET(0, &readfds)!=0, FD_ISSET(1, &writefds)!=0, FD_ISSET(fd,&readfds)!=0, FD_ISSET(fd,&writefds)!=0)); if (nfound < 0) { if (errno == EINTR) continue; fatal("select"); } if (FD_ISSET(0, &readfds)) { if (!enqueue(&sendq, 0)) { if (one_eof_exit) eof_socket = YES; eof_stdin = YES; if (queueIsEmpty(&sendq)) { if (shutdown(fd, SHUTDOWN_SEND) < 0) fatal("shutdown"); } } } if (FD_ISSET(fd, &writefds) && !queueIsEmpty(&sendq)) { dequeue(&sendq, fd); if (eof_stdin && queueIsEmpty(&sendq)) { if (shutdown(fd, SHUTDOWN_SEND) < 0) fatal("shutdown"); } } if (FD_ISSET(fd, &readfds)) { if (!enqueue(&recvq, fd)) { if (one_eof_exit) eof_stdin = YES; eof_socket = YES; } } if (FD_ISSET(1, &writefds)) { dequeue(&recvq, 1); } } if (session_log_fp != NULL) { fprintf(session_log_fp, "CLOSED\n"); fclose(session_log_fp); session_log_fp = NULL; } } void putenv_address(generic, addr_size, prefix) union generic_sockaddr *generic; int addr_size; char *prefix; { struct hostent *hp; char buffer[BUFSIZ]; switch (generic->address.sa_family) { case AF_INET: sprintf(buffer, "%s_ADDR=%s", prefix, inet_ntoa(generic->in.sin_addr)); putenv(strdup(buffer)); sprintf(buffer, "%s_PORT=%d", prefix, ntohs(generic->in.sin_port)); putenv(strdup(buffer)); hp = gethostbyaddr((char *) &generic->in.sin_addr, (int)sizeof(generic->in.sin_addr), AF_INET); if (hp != NULL) { sprintf(buffer, "%s_NAME=%s", prefix, hp->h_name); putenv(strdup(buffer)); } break; } } void env_setup(fd) int fd; { union generic_sockaddr generic; int addr_size = sizeof(generic); if (getsockname(fd, &generic.address, &addr_size) == 0) putenv_address(&generic, addr_size, "SOCK"); if (getpeername(fd, &generic.address, &addr_size) == 0) putenv_address(&generic, addr_size, "PEER"); } void doit(argv, fd, socket_mode, one_eof_exit) int fd; enum SocketMode socket_mode; char **argv; Bool one_eof_exit; { switch (socket_mode) { case sock_recv: if (shutdown(fd, SHUTDOWN_SEND) < 0) fatal("shutdown"); break; case sock_send: /* * This shutdown(2) has no effect, I THINK. */ if (shutdown(fd, SHUTDOWN_RECV) < 0) fatal("shutdown"); break; } if (argv == NULL) { transfer(fd, socket_mode, one_eof_exit); close(fd); exit(EXIT_OK); } else { env_setup(fd); if (socket_mode != sock_send) { close(0); dup2(fd, 0); } if (socket_mode != sock_recv) { close(1); dup2(fd, 1); } close(fd); execvp(argv[0], argv); fatal(argv[0]); } } #ifndef CAN_IGNORE_ZOMBIE void child_exit_handler(sig) int sig; { #ifdef POSIX while (waitpid(-1, NULL, WNOHANG) > 0) ; #else while (wait3(NULL, WNOHANG, NULL) > 0) ; #endif } #endif /* CAN_IGNORE_ZOMBIE */ void usage() { fprintf(stderr, "Usage: %s [-srk] [-b <address>] <address>\n", progname); fprintf(stderr, " %s [-srk] -b <address>\n", progname); fprintf(stderr, "\t\t<address> format is :\n"); fprintf(stderr, "\t\t\tunix/pathname\t- unix domain socket\n"); fprintf(stderr, "\t\t\t[host]:port\t- inet domain socket\n"); exit(EXIT_USAGE); } int main(argc, argv) int argc; char **argv; { union generic_sockaddr peer_addr, self_addr; size_t peer_addr_size, self_addr_size; int fd; int socket_type = SOCK_STREAM; enum SocketMode socket_mode = sock_sendrecv; char *bind_to = NULL; char *connect_to = NULL; char **shell_command = NULL; /* if NULL: only data transfer */ Bool one_eof_exit = YES; Bool accept_one_client = YES; FILE *port_output = stderr; if (argc >= 1) progname = argv[0]; while (--argc > 0) { char *s; if ((s = *++argv)[0] != '-') break; while (*++s) { static char end_loop[] = "."; switch(*s) { case 'd': debug_flag = YES; break; case 'b': /* bind sockname */ if (s[1] != '\0') { bind_to = &s[1]; } else { if (--argc <= 0) usage(); bind_to = *++argv; } s = end_loop; break; case 't': if (s[1] != '\0') { socket_type = make_socket_type(&s[1]); } else { if (--argc <= 0) usage(); socket_type = make_socket_type(*++argv); } s = end_loop; break; case 's': socket_mode = sock_send; break; case 'r': socket_mode = sock_recv; break; case 'k': /* keep */ one_eof_exit = NO; break; case 'i': /* interactive (like `telnet') */ one_eof_exit = YES; break; case 'l': /* log session - not work if shell_command */ if (s[1] != '\0') { session_log = &s[1]; } else { if (--argc <= 0) usage(); session_log = *++argv; } s = end_loop; break; case 'n': /* nowait && accept number of clients */ accept_one_client = NO; break; case 'o': if (s[1] != '\0') { record_sockopt(&s[1]); } else { if (--argc <= 0) usage(); record_sockopt(*++argv); } s = end_loop; break; case 'p': if (s[1] != '\0') { s = &s[1]; } else { if (--argc <= 0) usage(); s = *++argv; } if ((port_output = fopen(s, "w")) == NULL) fatal(s); s = end_loop; break; case 'c': if (s[1] != '\0') { connect_to = &s[1]; } else { if (--argc <= 0) usage(); connect_to = *++argv; } s = end_loop; break; case 'e': case 'f': shell_command = argv - 1; shell_command[0] = "/bin/sh"; shell_command[1] = *s == 'f' ? "-f" : "-c"; argv += argc - 1; argc = 1; /* i.e. argc -= argc - 1; */ break; default: usage(); } } } switch (argc) { case 0: if (bind_to == NULL && connect_to == NULL) usage(); break; case 1: connect_to = argv[0]; break; default: usage(); } if (connect_to != NULL) { peer_addr_size = make_socket_address(&peer_addr,connect_to,socket_type); } if (bind_to == NULL) { fd = socket(peer_addr.address.sa_family, socket_type, 0); if (fd < 0) fatal("socket"); apply_sockopts(fd); } else { Bool print_port; self_addr_size = make_socket_address(&self_addr, bind_to, socket_type); print_port = self_addr.in.sin_family == AF_INET && self_addr.in.sin_port == 0; fd = socket(self_addr.address.sa_family, socket_type, 0); if (fd < 0) fatal("socket"); switch (self_addr.address.sa_family) { case AF_UNIX: unlink(self_addr.un.sun_path); break; case AF_INET: break; } apply_sockopts(fd); if (bind(fd, &self_addr.address, (int)self_addr_size) < 0) fatal("bind"); debug(print_sockname(fd)); if (print_port) print_sockport(port_output, fd); if (port_output != stderr) fclose(port_output); } if (connect_to == NULL && socket_type_is_stream(socket_type)) { int client; #ifdef CAN_IGNORE_ZOMBIE SIGNAL(SIGCLD, SIG_IGN); #else reliable_signal(SIGCHLD, child_exit_handler); #endif if (listen(fd, accept_one_client ? 1 : LISTEN_BACKLOG) < 0) fatal("listen"); for (;;) { union generic_sockaddr client_addr; int client_addr_size = sizeof(client_addr); client = accept(fd, &client_addr.address, &client_addr_size); if (client < 0) { if (errno == EINTR) continue; fatal("accept"); } if (accept_one_client) break; switch (fork()) { case -1: fatal("fork"); case 0: close(fd); debug(print_peername(client)); doit(shell_command, client, socket_mode, one_eof_exit); default: close(client); break; } } close(fd); debug(print_peername(client)); doit(shell_command, client, socket_mode, one_eof_exit); } else if (connect_to == NULL) { doit(shell_command, fd, socket_mode, one_eof_exit); } else { if (connect(fd, &peer_addr.address, (int)peer_addr_size) < 0) fatal("connect"); debug(print_peername(fd)); doit(shell_command, fd, socket_mode, one_eof_exit); } /*NOTREACHED*/ return EXIT_SYSERR; } <file_sep>/gfarm/tags/gfarm_1_0_2/include/gfarm/gfs.h /* * $Id$ */ /* * basic types */ struct gfarm_timespec { unsigned int tv_sec; unsigned int tv_nsec; }; typedef unsigned int gfarm_mode_t; #define GFARM_S_ALLPERM 0007777 /* all access permissions */ #define GFARM_S_IFMT 0170000 /* type of file mask */ #define GFARM_S_IFDIR 0040000 /* directory */ #define GFARM_S_IFREG 0100000 /* regular file */ #if 0 #define GFARM_S_IFLNK 0120000 /* symbolic link */ #endif #define GFARM_S_ISDIR(m) (((m) & GFARM_S_IFMT) == GFARM_S_IFDIR) #define GFARM_S_ISREG(m) (((m) & GFARM_S_IFMT) == GFARM_S_IFREG) #if 0 #define GFARM_S_ISLNK(m) (((m) & GFARM_S_IFMT) == GFARM_S_IFLNK) #endif #define GFARM_S_IS_FRAGMENTED_FILE(m) \ (GFARM_S_ISREG(m) && ((m) & 0111) == 0) #define GFARM_S_IS_PROGRAM(m) \ (GFARM_S_ISREG(m) && ((m) & 0111) != 0) struct gfs_stat { long st_ino; gfarm_mode_t st_mode; char *st_user; char *st_group; struct gfarm_timespec st_atimespec; struct gfarm_timespec st_mtimespec; struct gfarm_timespec st_ctimespec; file_offset_t st_size; int st_nsections; }; /* * gfs_file ops */ typedef struct gfs_file *GFS_File; char *gfs_pio_open(const char *, int, GFS_File *); char *gfs_pio_create(const char *, int, gfarm_mode_t mode, GFS_File *); #define GFARM_FILE_RDONLY 0 #define GFARM_FILE_WRONLY 1 #define GFARM_FILE_RDWR 2 #define GFARM_FILE_ACCMODE 3 /* RD/WR/RDWR mode mask */ #define GFARM_FILE_CREATE 0x00000200 #define GFARM_FILE_TRUNC 0x00000400 /* the followings are just hints */ #define GFARM_FILE_SEQUENTIAL 0x01000000 #define GFARM_FILE_REPLICATE 0x02000000 #define GFARM_FILE_NOT_REPLICATE 0x04000000 #define GFARM_FILE_NOT_RETRY 0x08000000 char *gfs_pio_set_local(int, int); char *gfs_pio_set_local_check(void); char *gfs_pio_get_node_rank(int *); char *gfs_pio_get_node_size(int *); char *gfs_pio_set_view_local(GFS_File, int); char *gfs_pio_set_view_index(GFS_File, int, int, char *, int); char *gfs_pio_set_view_section(GFS_File, const char *, char *, int); char *gfs_pio_set_view_global(GFS_File, int); /* as total fragment number */ #define GFARM_FILE_DONTCARE (-1) char *gfs_pio_close(GFS_File); int gfs_pio_eof(GFS_File); char *gfs_pio_error(GFS_File); void gfs_pio_clearerr(GFS_File); int gfs_pio_fileno(GFS_File); char *gfs_pio_get_nfragment(GFS_File, int *); char *gfs_pio_flush(GFS_File); char *gfs_pio_seek(GFS_File, file_offset_t, int, file_offset_t *); char *gfs_pio_read(GFS_File, void *, int, int *); char *gfs_pio_write(GFS_File, const void *, int, int *); int gfs_pio_getc(GFS_File); int gfs_pio_ungetc(GFS_File, int); char *gfs_pio_putc(GFS_File, int); char *gfs_pio_puts(GFS_File, const char *); char *gfs_pio_getline(GFS_File, char *, size_t, int *); char *gfs_pio_putline(GFS_File, const char *); /* * For legacy code */ char *gfs_pio_set_fragment_info_local(char *, char *, char *); /* * Meta operations */ char *gfs_unlink(const char *); char *gfs_unlink_section_replica(const char *, const char *, int, char **, int); char *gfs_unlink_replicas_on_host(const char *, const char *, int); char *gfs_mkdir(const char *, gfarm_mode_t); char *gfs_rmdir(const char *); char *gfs_chdir(const char *); char *gfs_getcwd(char *, int); char *gfs_chown(const char *, char *, char *); char *gfs_chmod(const char *, gfarm_mode_t); char *gfs_utimes(const char *, const struct gfarm_timespec *); char *gfs_rename(const char *, const char *); char *gfs_stat(const char *, struct gfs_stat *); char *gfs_stat_section(const char *, const char *, struct gfs_stat *); char *gfs_stat_index(char *, int, struct gfs_stat *); char *gfs_fstat(GFS_File, struct gfs_stat *); void gfs_stat_free(struct gfs_stat *); char *gfs_access(const char *, int); #define GFS_MAXNAMLEN 255 struct gfs_dirent { int d_fileno; unsigned char d_type; unsigned char d_namlen; char d_name[GFS_MAXNAMLEN + 1]; }; /* File types */ #define GFS_DT_UNKNOWN 0 /* gfs_hook.c depends on it that this is 0 */ #define GFS_DT_DIR 4 #define GFS_DT_REG 8 typedef struct gfs_dir *GFS_Dir; char *gfs_opendir(const char *, GFS_Dir *); char *gfs_readdir(GFS_Dir, struct gfs_dirent **); char *gfs_closedir(GFS_Dir); char *gfs_realpath(const char *, char **); void gfs_uncachedir(void); /* * execution */ char *gfs_execve(const char *, char *const [], char *const []); /* * meta operations */ enum { GFARM_REPLICATION_BOOTSTRAP_METHOD, GFARM_REPLICATION_NORMAL_METHOD }; int gfarm_replication_get_method(void); void gfarm_replication_set_method(int); char *gfarm_url_section_replicate_from_to(const char *, char *, char *, char *); char *gfarm_url_section_replicate_to(const char *, char *, char *); char *gfarm_url_program_register(const char *, char *, char *, int); char *gfarm_url_program_deliver(const char *, int, char **, char ***); char *gfarm_url_program_get_local_path(const char *, char **); char *gfarm_url_fragments_replicate(const char *, int, char **); char *gfarm_url_fragments_replicate_to_domainname(const char *, const char *); <file_sep>/gfarm_hadoop/tags/gfarm_hadoop_1_0_0/build.sh #!/usr/bin/env bash # Please set these variables export JAVA_HOME=/usr/local/jdk export HADOOP_HOME=/home/mikami/hadoop/hadoop-0.20.2 export GFARM_HOME=/data/local/gfarm_v2 export CPLUS_INCLUDE_PATH=${GFARM_HOME}/include # Include jar files export CLASSPATH=${CLASSPATH} for f in $HADOOP_HOME/hadoop-*-core.jar; do CLASSPATH=${CLASSPATH}:$f; done for f in $HADOOP_HOME/lib/*.jar; do CLASSPATH=${CLASSPATH}:$f; done for f in $HADOOP_HOME/lib/jetty-ext/*.jar; do CLASSPATH=${CLASSPATH}:$f; done make cp hadoop-gfarm.jar ${HADOOP_HOME}/lib/ cp libGfarmFSNative.so ${HADOOP_HOME}/lib/native/Linux-amd64-64/ cp libGfarmFSNative.so ${HADOOP_HOME}/lib/native/Linux-i386-32/<file_sep>/gfarm/tags/gfarm_1_0_2_rc2/util/gfront/build.xml <project name="gfront" default="jar" basedir="."> <!-- Source file directory --> <property name="build.src" value="GFront/gfront"/> <!-- Class file directory --> <property name="build.dest" value="GFront/classes"/> <!-- Jar file directory --> <property name="build.jar" value="gfront.jar"/> <!-- Javadoc file directory --> <property name="javadoc.dest" value="GFront/api"/> <target name="jar" depends="compile"> <jar jarfile="${build.jar}" basedir="${build.dest}" manifest="gfront.mani"> </jar> </target> <target name="compile"> <mkdir dir="${build.dest}" /> <javac srcdir="${build.src}" debug="${debug}" destdir="${build.dest}" /> </target> <target name="javadoc"> <mkdir dir="${javadoc.dest}" /> <javadoc packagenames="*" sourcepath="${build.src}" destdir="${javadoc.dest}"> </javadoc> </target> <target name="clean"> <delete dir="${javadoc.dest}" /> <delete dir="${build.dest}" /> <delete dir="${build.jar}" /> </target> </project> <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/lib/libgfarm/gfarm/gfs_unlink.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <string.h> #include <stdlib.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "config.h" #include "gfs_client.h" #include "gfs_pio.h" /* gfs_profile */ #include "gfs_misc.h" /* gfs_unlink_replica_internal() */ #include "timer.h" char * gfs_unlink_replica_internal(const char *gfarm_file, const char *section, const char *hostname) { char *path_section, *e; struct gfs_connection *gfs_server; struct sockaddr peer_addr; e = gfarm_path_section(gfarm_file, section, &path_section); if (e != NULL) goto finish; e = gfarm_file_section_copy_info_remove(gfarm_file, section, hostname); if (e != NULL) goto finish_path_section; e = gfarm_host_address_get(hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) goto finish_path_section; e = gfs_client_connection(hostname, &peer_addr, &gfs_server); if (e != NULL) goto finish_path_section; e = gfs_client_unlink(gfs_server, path_section); finish_path_section: free(path_section); finish: return (e); } double gfs_unlink_time; char * gfs_unlink(const char *gfarm_url) { char *gfarm_file, *e, *e_save = NULL; int i, j, nsections; struct gfarm_path_info pi; struct gfarm_file_section_info *sections; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { e_save = e; goto finish_unlink; } e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { e_save = e; goto finish_free_gfarm_file; } if (GFARM_S_ISDIR(pi.status.st_mode)) { gfarm_path_info_free(&pi); e_save = GFARM_ERR_IS_A_DIRECTORY; goto finish_free_gfarm_file; } gfarm_path_info_free(&pi); e = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); if (e != NULL) { e_save = e; nsections = 0; sections = NULL; } /* XXX - should unlink in parallel. */ for (i = 0; i < nsections; i++) { int ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, sections[i].section, &ncopies, &copies); if (e != NULL) { if (e_save == NULL) e_save = e; continue; } for (j = 0; j < ncopies; j++) { e = gfs_unlink_replica_internal(gfarm_file, sections[i].section, copies[j].hostname); if (e != NULL) { if (e_save == NULL) e_save = e; continue; } } gfarm_file_section_copy_info_free_all(ncopies, copies); } if (sections != NULL) gfarm_file_section_info_free_all(nsections, sections); e = gfarm_file_section_info_remove_all_by_file(gfarm_file); if (e != NULL) e_save = e; e = gfarm_path_info_remove(gfarm_file); if (e != NULL) e_save = e; finish_free_gfarm_file: free(gfarm_file); finish_unlink: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_unlink_time += gfarm_timerval_sub(&t2, &t1)); return (e_save); } /* internal use in the gfarm library */ char * gfs_unlink_section(const char *gfarm_file, const char *section) { char *e, *e_save = NULL; int j, ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e == GFARM_ERR_NO_SUCH_OBJECT) { e = gfarm_file_section_info_remove(gfarm_file, section); return (e == NULL || e == GFARM_ERR_NO_SUCH_OBJECT ? NULL : e); } if (e != NULL) return (e); for (j = 0; j < ncopies; j++) { e = gfs_unlink_replica_internal(gfarm_file, section, copies[j].hostname); if (e != NULL) { if (e_save == NULL) e_save = e; continue; } } gfarm_file_section_copy_info_free_all(ncopies, copies); (void)gfarm_file_section_copy_info_remove_all_by_section( gfarm_file, section); e = gfarm_file_section_info_remove(gfarm_file, section); if (e != NULL && e != GFARM_ERR_NO_SUCH_OBJECT) { if (e_save == NULL) e_save = e; } return (e_save != NULL ? e_save : e); } char * gfs_unlink_section_replica(const char *gfarm_url, const char *section, int nreplicas, char **replica_hosts, int force) { char *e, *e_save = NULL; char *gfarm_file, **replica_canonical_hostnames; int i, j, ncopies, ndeletes; struct gfarm_file_section_copy_info *copies; char *do_delete; int remove_section_info = 0; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) { if (e == GFARM_ERR_NO_SUCH_OBJECT && force) /* * filesystem metadata should be collapsed. * Ignore the previous error and delete the * section information. */ e = gfarm_file_section_info_remove( gfarm_file, section); goto finish_gfarm_file; } if (ncopies == 0) { /* assert(0); */ e = "gfs_unlink_section_replica: no file replica"; goto finish_copies; } do_delete = malloc(ncopies); if (do_delete == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_copies; } memset(do_delete, 0, ncopies); e = gfarm_host_get_canonical_names(nreplicas, replica_hosts, &replica_canonical_hostnames); if (e != NULL) goto finish_do_delete; ndeletes = 0; for (i = 0; i < nreplicas; i++) { for (j = 0; j < ncopies; j++) { if (strcasecmp(replica_canonical_hostnames[i], copies[j].hostname) == 0) { if (do_delete[j]) { e = "gfs_unlink_section_replica: " "duplicate hostname"; if (e_save == NULL) e_save = e; /* do not finish, but continue */ continue; } do_delete[j] = 1; ndeletes++; break; } } if (j >= ncopies && e_save == NULL) { e_save = GFARM_ERR_NO_REPLICA_ON_HOST; /* do not finish, but continue */ } } if (ndeletes == ncopies) { if (force == 0) { e_save = "cannot remove all replicas"; goto finish_replica_canonical_hostnames; } else remove_section_info = 1; } for (j = 0; j < ncopies; j++) { if (!do_delete[j]) continue; e = gfs_unlink_replica_internal(gfarm_file, section, copies[j].hostname); if (e != NULL) { if (e_save == NULL) e_save = e; continue; } } if (remove_section_info) { int ncps; struct gfarm_file_section_copy_info *cps; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncps, &cps); if (e == GFARM_ERR_NO_SUCH_OBJECT) /* Oh, there is no section copy info. */ /* Some filesystem nodes might be down. */ e = gfarm_file_section_info_remove( gfarm_file, section); else if (e == NULL) gfarm_file_section_copy_info_free_all(ncps, cps); if (e != NULL) { if (e_save == NULL) e_save = e; } } finish_replica_canonical_hostnames: gfarm_strings_free_deeply(nreplicas, replica_canonical_hostnames); finish_do_delete: free(do_delete); finish_copies: gfarm_file_section_copy_info_free_all(ncopies, copies); finish_gfarm_file: free(gfarm_file); finish: return (e_save != NULL ? e_save : e); } /* * Eliminate file replicas of a gfarm_url on a specified node list. */ char * gfs_unlink_replica(const char *gfarm_url, int nreplicas, char **replica_hosts, int force) { char *gfarm_file, *e, *e_save; int i, nsections; struct gfarm_file_section_info *sections; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e_save = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); if (e_save != NULL) { nsections = 0; sections = NULL; } for (i = 0; i < nsections; i++) { e = gfs_unlink_section_replica(gfarm_url, sections[i].section, nreplicas, replica_hosts, force); if (e != NULL && e_save == NULL) e_save = e; } if (sections != NULL) gfarm_file_section_info_free_all(nsections, sections); free(gfarm_file); return (e_save); } /* * internal use - eliminate all file replicas that are not stored on * the specified host. */ char * gfs_unlink_every_other_replicas(const char *gfarm_file, const char *section, const char *canonical_hostname) { char *e, *e_save = NULL; int j, ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); for (j = 0; j < ncopies; j++) { /* skip when the specified node. */ if (strcmp(canonical_hostname, copies[j].hostname) == 0) continue; e = gfs_unlink_replica_internal(gfarm_file, section, copies[j].hostname); if (e_save == NULL) e_save = e; } gfarm_file_section_copy_info_free_all(ncopies, copies); return (e_save); } <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_1_rc1/Makefile.in TARGET = gfarmfs SRCS = gfarmfs.c OBJS = gfarmfs.o DOCS = LICENSE README README.ja CC = @CC@ DEFS = @DEFS@ prefix = @prefix@ exec_prefix = @exec_prefix@ bindir = $(exec_prefix)/bin INSTALL_PROGRAM = ./install-sh CPPFLAGS = -g -Wall -O2 @CPPFLAGS@ -DFUSE_USE_VERSION=22 -D_FILE_OFFSET_BITS=64 LDFLAGS = @LDFLAGS@ LIBS = @LIBS@ VER = $(TARGET)-fuse-`date +%Y%m%d` FILES = $(SRCS) Makefile.in configure.in configure $(DOCS) $(INSTALL_PROGRAM) BINS = $(TARGET) all: $(TARGET) $(TARGET): $(OBJS) $(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) .c.o: $(CC) $(CPPFLAGS) -c -o $@ $< $(OBJS): Makefile install: $(BINS) @for i in -- $(BINS); do \ case $$i in --) continue;; esac; \ ( set -x; $(INSTALL_PROGRAM) $${i} $(bindir)/$${i} ); \ done clean: $(RM) $(OBJS) $(TARGET) distclean: clean rm -f Makefile config.log config.status tar: @echo $(VER) > .package @$(RM) -r `cat .package` @mkdir `cat .package` cp --parents $(FILES) `cat .package` tar cvf - `cat .package` | gzip -9 > `cat .package`.tar.gz @$(RM) -r `cat .package` .package <file_sep>/gfarm/tags/gfarm_1_1_1_rc3/gftool/gfarm_agent/agent_thr.h /* * $Id$ */ void agent_lock(void); void agent_unlock(void); int agent_schedule(int *, void *(*)(void *)); <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfarm/auth.h enum gfarm_auth_error { GFARM_AUTH_ERROR_NO_ERROR, GFARM_AUTH_ERROR_DENIED, GFARM_AUTH_ERROR_NOT_SUPPORTED, GFARM_AUTH_ERROR_INVALID_CREDENTIAL, GFARM_AUTH_ERROR_EXPIRED, GFARM_AUTH_ERROR_RESOURCE_UNAVAILABLE, }; enum gfarm_auth_method { GFARM_AUTH_METHOD_NONE, /* never used */ GFARM_AUTH_METHOD_SHAREDSECRET, GFARM_AUTH_METHOD_GSI, GFARM_AUTH_METHOD_NUMBER }; #define GFARM_AUTH_METHOD_ALL GFARM_AUTH_METHOD_NONE /* * GFARM_AUTH_METHOD_SHAREDSECRET dependent constants. * note that this is too weak authentication for the Internet. */ void gfarm_random_initialize(void); void gfarm_auth_random(void *, size_t); void gfarm_auth_sharedsecret_response_data(char *, char *, char *); char *gfarm_auth_shared_key_get(unsigned int *, char *, char *, int); #define GFARM_AUTH_SHARED_KEY_GET 0 #define GFARM_AUTH_SHARED_KEY_CREATE 1 #define GFARM_AUTH_SHARED_KEY_CREATE_FORCE 2 /* request */ enum gfarm_auth_sharedsecret_request { GFARM_AUTH_SHAREDSECRET_GIVEUP, GFARM_AUTH_SHAREDSECRET_MD5 }; /* key */ #define GFARM_AUTH_RETRY_MAX 2 #define GFARM_AUTH_SHARED_KEY_LEN 32 #define GFARM_AUTH_CHALLENGE_LEN 32 #define GFARM_AUTH_RESPONSE_LEN 16 /* length of MD5 */ struct xxx_connection; struct sockaddr; char *gfarm_authorize_log_connected(struct xxx_connection *, char *, char *); char *gfarm_auth_request(struct xxx_connection *, char *, struct sockaddr *); char *gfarm_authorize(struct xxx_connection *, int, char **, char **); /* auth config */ struct gfarm_hostspec; char *gfarm_auth_method_parse(char *, enum gfarm_auth_method *); char *gfarm_auth_enable(enum gfarm_auth_method, struct gfarm_hostspec *); char *gfarm_auth_disable(enum gfarm_auth_method, struct gfarm_hostspec *); /* this i/f have to be changed, if we support more than 31 auth methods */ gfarm_int32_t gfarm_auth_method_get_enabled_by_name_addr( char *, struct sockaddr *); gfarm_int32_t gfarm_auth_method_get_available(void); <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfsl/server2.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #include "gssapi.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_auth.h" #include "gfarm_secure_session.h" #include "tcputil.h" #include "misc.h" static int port = 0; static int ParseArgs(argc, argv) int argc; char *argv[]; { while (*argv != NULL) { if (strcmp(*argv, "-p") == 0) { if (argv[1] != NULL && *argv[1] != '\0') { int tmp; argv++; if (gfarmGetInt(*argv, &tmp) < 0) { fprintf(stderr, "illegal port number.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "port number must be > 0.\n"); return -1; } else if (tmp > 65535) { fprintf(stderr, "port number must be < 65536.\n"); return -1; } port = tmp; } else { fprintf(stderr, "a port number must be specified.\n"); return -1; } } argv++; } return 0; } int main(argc, argv) int argc; char *argv[]; { int ret = 1; int bindFd = -1; struct sockaddr_in remote; int remLen = sizeof(struct sockaddr_in); int fd0 = -1; int fd1 = -1; OM_uint32 majStat; gfarmSecSession *ss0 = NULL; gfarmSecSession *ss1 = NULL; int sel; char *buf; int n; int i; gfarmSecSession *ssList[2]; if (ParseArgs(argc - 1, argv + 1) != 0) { goto Done; } if (gfarmSecSessionInitializeAcceptor(NULL, NULL, &majStat) <= 0) { fprintf(stderr, "can't initialize as acceptor because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } /* * Create a channel. */ bindFd = gfarmTCPBindPort(port); if (bindFd < 0) { goto Done; } (void)gfarmIPGetNameOfSocket(bindFd, &port); fprintf(stderr, "Accepting port: %d\n", port); fd0 = accept(bindFd, (struct sockaddr *)&remote, &remLen); if (fd0 < 0) { perror("accept"); goto Done; } ss0 = gfarmSecSessionAccept(fd0, GSS_C_NO_CREDENTIAL, NULL, &majStat); if (ss0 == NULL) { fprintf(stderr, "Can't create acceptor session because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } fd1 = accept(bindFd, (struct sockaddr *)&remote, &remLen); if (fd1 < 0) { perror("accept"); goto Done; } ss1 = gfarmSecSessionAccept(fd1, GSS_C_NO_CREDENTIAL, NULL, &majStat); if (ss1 == NULL) { fprintf(stderr, "Can't create acceptor session because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } if (gfarmSecSessionGetInitiatorInfo(ss0) != gfarmSecSessionGetInitiatorInfo(ss1)) { fprintf(stderr, "1st initiator and 2nd initiator differ.\n"); goto Done; } gfarmSecSessionDedicate(ss0); ssList[0] = ss0; ssList[1] = ss1; while (1) { gfarmSecSessionSetPollEvent(ss0, GFARM_SS_POLL_READABLE); gfarmSecSessionSetPollEvent(ss1, GFARM_SS_POLL_READABLE); sel = gfarmSecSessionPoll(ssList, 2, NULL); if (sel == 0) { continue; } else if (sel > 0) { if (gfarmSecSessionCheckPollReadable(ss0)) { i = gfarmSecSessionReceiveBytes(ss0, &buf, &n); if (i == 0) { break; } else if (i < 0) { fprintf(stderr, "1st session receive failed because of:\n"); gfarmSecSessionPrintStatus(stderr, ss0); break; } else { fprintf(stderr, "0: got %5d '", n); write(2, buf, n); fprintf(stderr, "'\n"); (void)free(buf); } } if (gfarmSecSessionCheckPollReadable(ss1)) { i = gfarmSecSessionReceiveBytes(ss1, &buf, &n); if (i == 0) { break; } else if (i < 0) { fprintf(stderr, "2nd session receive failed because of:\n"); gfarmSecSessionPrintStatus(stderr, ss0); break; } else { fprintf(stderr, "1: got %5d '", n); write(2, buf, n); fprintf(stderr, "'\n"); (void)free(buf); } } } else { break; } } ret = 0; Done: (void)close(bindFd); if (ss0 != NULL) { (void)close(fd0); gfarmSecSessionTerminate(ss0); } if (ss1 != NULL) { (void)close(fd1); gfarmSecSessionTerminate(ss1); } gfarmSecSessionFinalizeAcceptor(); return ret; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/gftool/gfrun/Makefile # $Id$ top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk SRCS = gfrun.c OBJS = gfrun.o PROGRAM = gfrun PROGRAM_LINKS = gfrsh gfssh gfrshl gfsshl EXTRA_VERYCLEAN_TARGETS = $(PROGRAM_LINKS) CFLAGS = $(COMMON_CFLAGS) -I$(GFARMLIB_SRCDIR) LDLIBS = $(COMMON_LDFLAGS) $(GFARMLIB) $(LIBS) DEPLIBS = $(DEPGFARMLIB) all: $(PROGRAM) $(PROGRAM_LINKS) include $(top_srcdir)/makes/prog.mk $(PROGRAM_LINKS): $(PROGRAM) rm -f $@ ln $(PROGRAM) $@ post-install-hook: for f in $(PROGRAM_LINKS); do \ rm -f $(bindir)/$$f; ln $(bindir)/$(PROGRAM) $(bindir)/$$f; \ done ### $(OBJS): $(DEPGFARMINC) \ $(GFARMLIB_SRCDIR)/host.h \ $(GFARMLIB_SRCDIR)/gfj_client.h \ $(GFARMLIB_SRCDIR)/schedule.h <file_sep>/gfarm_samba/trunk/gfarm_acl.c /* * $Id$ */ #include "includes.h" #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #undef PACKAGE_BUGREPORT #include <gfarm/gfarm.h> #include "gfarm_id.h" #include "msgno/msgno.h" void gfvfs_acl_id_init() { static int initialized = 0; if (initialized == 0) { gfarm_id_init(70000, 79999, 70000, 79999, 0); initialized = 1; } } static bool acl_gfarm_ace_to_smb_ace( const char *path, gfarm_acl_entry_t g_ace, struct smb_acl_entry *s_ace) { gfarm_error_t e; gfarm_acl_tag_t tag; gfarm_acl_permset_t permset; char *name; uid_t uid; gid_t gid; int b; (void)gfs_acl_get_tag_type(g_ace, &tag); switch (tag) { case GFARM_ACL_USER: s_ace->a_type = SMB_ACL_USER; break; case GFARM_ACL_USER_OBJ: s_ace->a_type = SMB_ACL_USER_OBJ; break; case GFARM_ACL_GROUP: s_ace->a_type = SMB_ACL_GROUP; break; case GFARM_ACL_GROUP_OBJ: s_ace->a_type = SMB_ACL_GROUP_OBJ; break; case GFARM_ACL_OTHER: s_ace->a_type = SMB_ACL_OTHER; break; case GFARM_ACL_MASK: s_ace->a_type = SMB_ACL_MASK; break; default: gflog_error(GFARM_MSG_3000188, "unknown tag: type=%u", (unsigned int)tag); errno = EINVAL; return (False); } switch (s_ace->a_type) { case SMB_ACL_USER: (void)gfs_acl_get_qualifier(g_ace, &name); e = gfarm_id_user_to_uid(path, name, &uid); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000189, "gfarm_id_user_to_uid: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (False); } s_ace->uid = uid; break; case SMB_ACL_GROUP: (void)gfs_acl_get_qualifier(g_ace, &name); e = gfarm_id_group_to_gid(path, name, &gid); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000190, "gfarm_id_group_to_gid: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (False); } s_ace->gid = gid; break; default: break; } (void)gfs_acl_get_permset(g_ace, &permset); s_ace->a_perm = 0; (void)gfs_acl_get_perm(permset, GFARM_ACL_READ, &b); if (b) s_ace->a_perm |= SMB_ACL_READ; (void)gfs_acl_get_perm(permset, GFARM_ACL_WRITE, &b); if (b) s_ace->a_perm |= SMB_ACL_WRITE; (void)gfs_acl_get_perm(permset, GFARM_ACL_EXECUTE, &b); if (b) s_ace->a_perm |= SMB_ACL_EXECUTE; return (True); } SMB_ACL_T gfvfs_gfarm_acl_to_smb_acl(const char *path, gfarm_acl_t acl) { gfarm_error_t e; SMB_ACL_T s_acl = SMB_MALLOC_P(struct smb_acl_t), tmp; gfarm_acl_entry_t ent; int save_errno; if (s_acl == NULL) { gflog_error(GFARM_MSG_3000191, "gfarm_acl_to_smb_acl: no memory"); errno = ENOMEM; return (NULL); } ZERO_STRUCTP(s_acl); e = gfs_acl_get_entry(acl, GFARM_ACL_FIRST_ENTRY, &ent); while (e == GFARM_ERR_NO_ERROR) { tmp = SMB_REALLOC(s_acl, sizeof(struct smb_acl_t) + (sizeof(struct smb_acl_entry) * (s_acl->count + 1))); if (tmp == NULL) { SAFE_FREE(s_acl); gflog_error(GFARM_MSG_3000192, "gfarm_acl_to_smb_acl: no memory"); errno = ENOMEM; return (NULL); } s_acl = tmp; if (!acl_gfarm_ace_to_smb_ace(path, ent, &s_acl->acl[s_acl->count])) { save_errno = errno; SAFE_FREE(s_acl); errno = save_errno; return (NULL); } s_acl->count += 1; e = gfs_acl_get_entry(acl, GFARM_ACL_NEXT_ENTRY, &ent); } if (e == GFARM_ERR_NO_SUCH_OBJECT) e = GFARM_ERR_NO_ERROR; if (e != GFARM_ERR_NO_ERROR) { SAFE_FREE(s_acl); errno = gfarm_error_to_errno(e); return (NULL); } return (s_acl); } static void set_mode_smb_to_gfarm(gfarm_acl_entry_t entry, SMB_ACL_PERM_T perm) { gfarm_acl_permset_t permset; gfs_acl_get_permset(entry, &permset); gfs_acl_clear_perms(permset); if (perm & SMB_ACL_READ) gfs_acl_add_perm(permset, GFARM_ACL_READ); if (perm & SMB_ACL_WRITE) gfs_acl_add_perm(permset, GFARM_ACL_WRITE); if (perm & SMB_ACL_EXECUTE) gfs_acl_add_perm(permset, GFARM_ACL_EXECUTE); gfs_acl_set_permset(entry, permset); } gfarm_acl_t gfvfs_smb_acl_to_gfarm_acl(const char *path, SMB_ACL_T s_acl) { gfarm_error_t e; gfarm_acl_t g_acl; int i; char *name; e = gfs_acl_init(s_acl->count, &g_acl); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000193, "gfs_acl_init: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (NULL); } for (i = 0; i < s_acl->count; i++) { const struct smb_acl_entry *entry = &s_acl->acl[i]; gfarm_acl_entry_t ent; gfarm_acl_tag_t tag; e = gfs_acl_create_entry(&g_acl, &ent); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000194, "gfs_acl_create_entry: %s", gfarm_error_string(e)); goto fail; } switch (entry->a_type) { case SMB_ACL_USER: tag = GFARM_ACL_USER; break; case SMB_ACL_USER_OBJ: tag = GFARM_ACL_USER_OBJ; break; case SMB_ACL_GROUP: tag = GFARM_ACL_GROUP; break; case SMB_ACL_GROUP_OBJ: tag = GFARM_ACL_GROUP_OBJ; break; case SMB_ACL_OTHER: tag = GFARM_ACL_OTHER; break; case SMB_ACL_MASK: tag = GFARM_ACL_MASK; break; default: gflog_error(GFARM_MSG_3000195, "unknown tag value %d", entry->a_type); e = GFARM_ERR_INVALID_ARGUMENT; goto fail; } gfs_acl_set_tag_type(ent, tag); switch (entry->a_type) { case SMB_ACL_USER: e = gfarm_id_uid_to_user(path, entry->uid, &name); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000196, "gfarm_id_uid_to_user: %s", gfarm_error_string(e)); goto fail; } gfs_acl_set_qualifier(ent, name); break; case SMB_ACL_GROUP: e = gfarm_id_gid_to_group(path, entry->gid, &name); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000197, "gfarm_id_gid_to_group: %s", gfarm_error_string(e)); goto fail; } gfs_acl_set_qualifier(ent, name); break; default: gfs_acl_set_qualifier(ent, NULL); break; } set_mode_smb_to_gfarm(ent, entry->a_perm); } gfs_acl_sort(g_acl); e = gfs_acl_valid(g_acl); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000198, "ACL is invalid for set: %s", gfarm_error_string(e)); goto fail; } return (g_acl); fail: gfs_acl_free(g_acl); errno = gfarm_error_to_errno(e); return (NULL); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_4/open_file.h void gfarm2fs_open_file_init(void); struct gfarm2fs_file *gfarm2fs_open_file_lookup(gfarm_ino_t); void gfarm2fs_open_file_enter(struct gfarm2fs_file *, int); void gfarm2fs_open_file_remove(struct gfarm2fs_file *); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_4/gfarm2fs.h #ifndef HAVE_GFS_GETXATTR_CACHED #define gfs_getxattr_cached gfs_getxattr #endif struct gfarm2fs_param { const char *mount_point; char *subdir; int foreground; int debug; double cache_timeout; int use_syslog; char *facility; char *loglevel; int ncopy; int copy_limit; int fix_acl; int disable_acl; int enable_cached_id; int auto_uid_min; int auto_uid_max; int auto_gid_min; int auto_gid_max; int genuine_nlink; }; struct gfarmized_path { int alloced; char *path; }; gfarm_error_t gfarmize_path(const char *, struct gfarmized_path *); void free_gfarmized_path(struct gfarmized_path *); struct gfarm2fs_file { int flags; GFS_File gf; gfarm_ino_t inum; int time_updated; struct gfarm_timespec gt[2]; }; /* support nanosecond */ #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC) #define gfarm2fs_stat_mtime_nsec_set(st, v) ((st)->st_mtim.tv_nsec = (v)) #define gfarm2fs_stat_atime_nsec_set(st, v) ((st)->st_atim.tv_nsec = (v)) #define gfarm2fs_stat_ctime_nsec_set(st, v) ((st)->st_ctim.tv_nsec = (v)) #else #define gfarm2fs_stat_mtime_nsec_set(st, v) do {} while (0) #define gfarm2fs_stat_atime_nsec_set(st, v) do {} while (0) #define gfarm2fs_stat_ctime_nsec_set(st, v) do {} while (0) #endif <file_sep>/gfarm/tags/gfarm_1_0_2_rc1/lib/libgfarm/gfsl/scsub.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <gssapi.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #include "tcputil.h" #include "gfarm_secure_session.h" #include "gfarm_auth.h" gfarm_int32_t testBufSize = 4096; void doServer(int fd, char *host, int port); void doClient(char *host, int port, gss_cred_id_t deleCred, gfarm_int32_t deleCheck); void doServer(fd, hostname, port) int fd; char *hostname; int port; { OM_uint32 majStat, minStat; char *rBuf = NULL; int tBufSz = -1; int n = -1; int rSz = -1; int dCheck = 0; gfarm_int32_t *tmpBuf; gfarmAuthEntry *aePtr = NULL; gfarmSecSession *initialSession = gfarmSecSessionAccept(fd, GSS_C_NO_CREDENTIAL, NULL, &majStat, &minStat); int x; if (initialSession == NULL) { fprintf(stderr, "Can't create acceptor session because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); goto Done; } aePtr = gfarmSecSessionGetInitiatorInfo(initialSession); fprintf(stderr, "Initiator: '%s' -> '%s'\n", aePtr->distName, (aePtr->authType == GFARM_AUTH_USER) ? aePtr->authData.userAuth.localName : aePtr->authData.hostAuth.FQDN); if (gfarmSecSessionDedicate(initialSession) < 0) { fprintf(stderr, "Can't dedicate to '%s'.\n", (aePtr->authType == GFARM_AUTH_USER) ? aePtr->authData.userAuth.localName : aePtr->authData.hostAuth.FQDN); goto Done; } /* * Now, we can communicate securely. */ x = gfarmSecSessionReceiveInt32(initialSession, &tmpBuf, &n); if (x != 1) { fprintf(stderr, "can't receive test buffer size because of:\n"); gfarmSecSessionPrintStatus(initialSession); goto Done; } tBufSz = *tmpBuf; (void)free(tmpBuf); fprintf(stderr, "Receive buffer size: %d\n", tBufSz); if (gfarmSecSessionReceiveInt8(initialSession, &rBuf, &rSz) <= 0) { fprintf(stderr, "test buffer receive failed because of:\n"); gfarmSecSessionPrintStatus(initialSession); goto Done; } if (tBufSz != rSz) { fprintf(stderr, "test buffer size differ.\n" "\tOriginal: %10d\n" "\tReplyed: %10d\n", tBufSz, rSz); goto Done; } if (gfarmSecSessionSendInt8(initialSession, rBuf, rSz) != rSz) { fprintf(stderr, "test buffer send failed because of:\n"); gfarmSecSessionPrintStatus(initialSession); goto Done; } (void)free(rBuf); if (gfarmSecSessionReceiveInt32(initialSession, &tmpBuf, &n) != 1) { fprintf(stderr, "can't receive delegation check flag because of:\n"); gfarmSecSessionPrintStatus(initialSession); goto Done; } dCheck = *tmpBuf; if (dCheck == 1) { gss_cred_id_t deleCred = gfarmSecSessionGetDelegatedCredential(initialSession); if (deleCred != GSS_C_NO_CREDENTIAL) { fprintf(stderr, "\nDelegation check.\n"); doClient(hostname, port, deleCred, 0); } } Done: gfarmSecSessionTerminate(initialSession); if (dCheck == 1) { gfarmSecSessionFinalizeBoth(); } return; } static void randomizeIt(char *buf, int len); static void randomizeIt(buf, len) char *buf; int len; { int i; srand(time(NULL)); for (i = 0; i < len; i++) { buf[i] = rand() % 256; } } void doClient(hostname, port, deleCred, deleCheck) char *hostname; int port; gss_cred_id_t deleCred; gfarm_int32_t deleCheck; { char *sBuf = NULL; char *rBuf = NULL; int rSz = -1; OM_uint32 majStat; OM_uint32 minStat; gfarmSecSession *ss = gfarmSecSessionInitiateByName(hostname, port, deleCred, NULL, &majStat, &minStat); if (ss == NULL) { fprintf(stderr, "Can't create initiator session because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); return; } /* * Now, we can communicate securely. */ sBuf = (char *)malloc(sizeof(char *) * testBufSize); if (sBuf == NULL) { fprintf(stderr, "can't allocate test buffer.\n"); goto Done; } randomizeIt(sBuf, testBufSize); if (gfarmSecSessionSendInt32(ss, &testBufSize, 1) != 1) { fprintf(stderr, "can't send test buffer size because of:\n"); gfarmSecSessionPrintStatus(ss); goto Done; } fprintf(stderr, "Send buffer size: %ld\n", (long)testBufSize); if (gfarmSecSessionSendInt8(ss, sBuf, testBufSize) != testBufSize) { fprintf(stderr, "test buffer send failed because of:\n"); gfarmSecSessionPrintStatus(ss); goto Done; } if (gfarmSecSessionReceiveInt8(ss, &rBuf, &rSz) <= 0) { fprintf(stderr, "test buffer receive failed because of:\n"); gfarmSecSessionPrintStatus(ss); goto Done; } if (testBufSize != rSz) { fprintf(stderr, "test buffer size differ.\n" "\tOriginal: %10ld\n" "\tReplyed: %10d\n", (long)testBufSize, rSz); goto Done; } if (memcmp((void *)sBuf, (void *)rBuf, testBufSize) != 0) { fprintf(stderr, "test buffer check failed.\n"); goto Done; } else { fprintf(stderr, "test buffer check OK.\n"); } if (gfarmSecSessionSendInt32(ss, &deleCheck, 1) != 1) { fprintf(stderr, "can't send delegation check flag.\n"); goto Done; } Done: if (sBuf != NULL) { (void)free(sBuf); } if (rBuf != NULL) { (void)free(rBuf); } gfarmSecSessionTerminate(ss); return; } <file_sep>/gfarm/tags/gfarm_1_0_1/gftool/example/gfimport_text/Makefile # $Id$ top_objdir = ../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk include $(srcdir)/../Makefile.inc SRCS = gfimport_text.c OBJS = gfimport_text.o PROGRAM = gfimport_text CFLAGS = $(COMMON_CFLAGS) LDLIBS = $(COMMON_LDLIBS) $(GFARMLIB) $(LIBS) DEPLIBS = $(DEPGFARMLIB) all: $(PROGRAM) include $(top_srcdir)/makes/prog.mk ### $(OBJS): $(DEPGFARMINC) <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/io_fd.c /* * iobuffer operation: file descriptor read/write */ #include <gfarm/gfarm_config.h> #include <sys/types.h> #ifdef HAVE_POLL #include <poll.h> #else #include <sys/time.h> #endif #include <unistd.h> #include <stdarg.h> #include <stdlib.h> #include <errno.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "iobuffer.h" #include "xxx_proto.h" #include "io_fd.h" /* * nonblocking i/o */ int gfarm_iobuffer_nonblocking_read_fd_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { ssize_t rv = read(fd, data, length); if (rv == -1) gfarm_iobuffer_set_error(b, gfarm_errno_to_error(errno)); return (rv); } int gfarm_iobuffer_nonblocking_write_fd_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { ssize_t rv = write(fd, data, length); if (rv == -1) gfarm_iobuffer_set_error(b, gfarm_errno_to_error(errno)); return (rv); } void gfarm_iobuffer_set_nonblocking_read_fd(struct gfarm_iobuffer *b, int fd) { gfarm_iobuffer_set_read(b, gfarm_iobuffer_nonblocking_read_fd_op, NULL, fd); } void gfarm_iobuffer_set_nonblocking_write_fd(struct gfarm_iobuffer *b, int fd) { gfarm_iobuffer_set_write(b, gfarm_iobuffer_nonblocking_write_fd_op, NULL, fd); } /* * blocking i/o */ int gfarm_iobuffer_blocking_read_fd_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { ssize_t rv; for (;;) { rv = read(fd, data, length); if (rv == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) { #ifdef HAVE_POLL struct pollfd fds[1]; fds[0].fd = fd; fds[0].events = POLLIN; poll(fds, 1, -1); #else fd_set readable; FD_ZERO(&readable); FD_SET(fd, &readable); select(fd + 1, &readable, NULL, NULL, NULL); #endif continue; } gfarm_iobuffer_set_error(b, gfarm_errno_to_error(errno)); } return (rv); } } int gfarm_iobuffer_blocking_write_fd_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { ssize_t rv; for (;;) { rv = write(fd, data, length); if (rv == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) { #ifdef HAVE_POLL struct pollfd fds[1]; fds[0].fd = fd; fds[0].events = POLLOUT; poll(fds, 1, -1); #else fd_set writable; FD_ZERO(&writable); FD_SET(fd, &writable); select(fd + 1, NULL, &writable, NULL, NULL); #endif continue; } gfarm_iobuffer_set_error(b, gfarm_errno_to_error(errno)); } return (rv); } } void gfarm_iobuffer_set_blocking_read_fd(struct gfarm_iobuffer *b, int fd) { gfarm_iobuffer_set_read(b, gfarm_iobuffer_blocking_read_fd_op, NULL, fd); } void gfarm_iobuffer_set_blocking_write_fd(struct gfarm_iobuffer *b, int fd) { gfarm_iobuffer_set_write(b, gfarm_iobuffer_blocking_write_fd_op, NULL, fd); } /* * an option for gfarm_iobuffer_set_write_close() */ void gfarm_iobuffer_write_close_fd_op(struct gfarm_iobuffer *b, void *cookie, int fd) { int rv = close(fd); if (rv == -1 && gfarm_iobuffer_get_error(b) == NULL) gfarm_iobuffer_set_error(b, gfarm_errno_to_error(errno)); } /* * xxx_connection operation */ char * xxx_iobuffer_close_fd_op(void *cookie, int fd) { return (close(fd) == -1 ? gfarm_errno_to_error(errno) : NULL); } char * xxx_iobuffer_export_credential_fd_op(void *cookie) { return (NULL); /* it's already exported, or no way to export it. */ } char * xxx_iobuffer_delete_credential_fd_op(void *cookie) { return (NULL); } char * xxx_iobuffer_env_for_credential_fd_op(void *cookie) { return (NULL); } struct xxx_iobuffer_ops xxx_fd_iobuffer_ops = { xxx_iobuffer_close_fd_op, xxx_iobuffer_export_credential_fd_op, xxx_iobuffer_delete_credential_fd_op, xxx_iobuffer_env_for_credential_fd_op, gfarm_iobuffer_nonblocking_read_fd_op, gfarm_iobuffer_nonblocking_write_fd_op, gfarm_iobuffer_blocking_read_fd_op, gfarm_iobuffer_blocking_write_fd_op }; char * xxx_fd_connection_new(int fd, struct xxx_connection **connp) { return (xxx_connection_new(&xxx_fd_iobuffer_ops, NULL, fd, connp)); } char * xxx_connection_set_fd(struct xxx_connection *conn, int fd) { xxx_connection_set(conn, &xxx_fd_iobuffer_ops, NULL, fd); return (NULL); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_4/xattr.c /* * $Id$ */ #include "config.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm2fs.h" #include "acl.h" #include "xattr.h" #include "gfarm_config.h" struct gfarm2fs_xattr_sw { gfarm_error_t (*set)(const char *path, const char *name, const void *value, size_t size, int flags); gfarm_error_t (*get)(const char *path, const char *name, void *value, size_t *sizep); gfarm_error_t (*remove)(const char *path, const char *name); }; #define XATTR_IS_SUPPORTED(name) \ (strncmp(name, "gfarm.", 6) == 0 || \ strncmp(name, "gfarm_root.", 11) == 0 || \ strncmp(name, "user.", 5) == 0) static const char LOCAL_XATTR_PREFIX[] = "gfarm2fs."; #define LOCAL_XATTR_PREFIX_LENGTH 9 /* sizeof(LOCAL_XATTR_PREFIX) - 1 */ #define XATTR_IS_LOCALLY_SUPPORTED(name) \ (strncmp(name, LOCAL_XATTR_PREFIX, LOCAL_XATTR_PREFIX_LENGTH) == 0) #ifdef ENABLE_ACL /* ------------------------------- */ static gfarm_error_t normal_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_ACCESS, value, size)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_DEFAULT, value, size)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t normal_get(const char *path, const char *name, void *value, size_t *sizep) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_ACCESS, value, sizep)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_DEFAULT, value, sizep)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t normal_remove(const char *path, const char *name) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_ACCESS)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_DEFAULT)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_normal = { normal_set, normal_get, normal_remove, }; /* ------------------------------- */ /* for gfarm2fs_fix_acl command */ const char FIX_ACL_ACCESS[] = "gfarm2fs.fix_acl_access"; const char FIX_ACL_DEFAULT[] = "gfarm2fs.fix_acl_default"; static gfarm_error_t fix_acl_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (strcmp(name, FIX_ACL_ACCESS) == 0 || strcmp(name, FIX_ACL_DEFAULT) == 0) return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_ACCESS, value, size)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_DEFAULT, value, size)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t fix_acl_get(const char *path, const char *name, void *value, size_t *sizep) { if (strcmp(name, FIX_ACL_ACCESS) == 0) return (gfs_lgetxattr_cached(path, ACL_EA_ACCESS, value, sizep)); else if (strcmp(name, FIX_ACL_DEFAULT) == 0) return (gfs_lgetxattr_cached(path, ACL_EA_DEFAULT, value, sizep)); else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_ACCESS, value, sizep)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_DEFAULT, value, sizep)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t fix_acl_remove(const char *path, const char *name) { if (strcmp(name, FIX_ACL_ACCESS) == 0) return (gfs_lremovexattr(path, ACL_EA_ACCESS)); else if (strcmp(name, FIX_ACL_DEFAULT) == 0) return (gfs_lremovexattr(path, ACL_EA_DEFAULT)); else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_ACCESS)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_DEFAULT)); else if (XATTR_IS_SUPPORTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_fix_acl = { fix_acl_set, fix_acl_get, fix_acl_remove, }; #endif /* ENABLE_ACL */ /* ------------------------------- */ static gfarm_error_t disable_acl_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (XATTR_IS_SUPPORTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t disable_acl_get(const char *path, const char *name, void *value, size_t *sizep) { if (XATTR_IS_SUPPORTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t disable_acl_remove(const char *path, const char *name) { if (XATTR_IS_SUPPORTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_disable_acl = { disable_acl_set, disable_acl_get, disable_acl_remove, }; /* ------------------------------- */ static gfarm_error_t gfarm2fs_xattr_copy(const char *src, void *dst, size_t *sizep) { size_t len; len = strlen(src); if (*sizep == 0) { *sizep = len; return (GFARM_ERR_NO_ERROR); } else if (len > *sizep) return (GFARM_ERR_RESULT_OUT_OF_RANGE); *sizep = len; memcpy(dst, src, len); return (GFARM_ERR_NO_ERROR); } static int port_size(int port) { int s; for (s = 0; port > 0; ++s, port /= 10) ; return (s); } static void port_to_string(int port, char *dst) { int s, size = port_size(port); for (s = size - 1; s >= 0; --s) { dst[s] = port % 10 + '0'; port /= 10; } } static gfarm_error_t gfarm2fs_xattr_get_local(const char *path, const char *name, void *value, size_t *sizep) { const char *n, *metadb; char *gsivalue = NULL; size_t len, metadb_len, port_len, path_len; int port; gfarm_error_t e; n = name + LOCAL_XATTR_PREFIX_LENGTH; if (strcmp(n, "path") == 0) return (gfarm2fs_xattr_copy(path, value, sizep)); else if (strcmp(n, "url") == 0) { if (gfarm_is_url(path)) return (gfarm2fs_xattr_copy(path, value, sizep)); e = gfarm_config_metadb_server(path, &metadb, &port); if (e != GFARM_ERR_NO_ERROR) return (e); metadb_len = strlen(metadb); port_len = port_size(port); path_len = strlen(path); len = GFARM_URL_PREFIX_LENGTH + 2 + metadb_len + 1 + port_len + path_len; if (*sizep == 0) { *sizep = len; return (GFARM_ERR_NO_ERROR); } else if (len > *sizep) return (GFARM_ERR_RESULT_OUT_OF_RANGE); *sizep = len; snprintf(value, len, "%s//%s:%d", GFARM_URL_PREFIX, metadb, port); value += GFARM_URL_PREFIX_LENGTH + 2 + metadb_len + 1 + port_len; memcpy(value, path, path_len); return (GFARM_ERR_NO_ERROR); } else if (strcmp(n, "metadb") == 0) { e = gfarm_config_metadb_server(path, &metadb, &port); if (e != GFARM_ERR_NO_ERROR) return (e); metadb_len = strlen(metadb); port_len = port_size(port); len = metadb_len + 1 + port_len; if (*sizep == 0) { *sizep = len; return (GFARM_ERR_NO_ERROR); } else if (len > *sizep) return (GFARM_ERR_RESULT_OUT_OF_RANGE); *sizep = len; snprintf(value, len, "%s:", metadb); value += metadb_len + 1; port_to_string(port, value); return (GFARM_ERR_NO_ERROR); } else if (strcmp(n, "gsiproxyinfo") == 0) { e = gfarm_config_gsi_proxy_info(&gsivalue); if (e == GFARM_ERR_NO_ERROR) { e = gfarm2fs_xattr_copy(gsivalue, value, sizep); free(gsivalue); } return (e); } else if (strcmp(n, "gsipath") == 0) { e = gfarm_config_gsi_path(&gsivalue); if (e == GFARM_ERR_NO_ERROR) { e = gfarm2fs_xattr_copy(gsivalue, value, sizep); free(gsivalue); } return (e); } else if (strcmp(n, "gsitimeleft") == 0) { e = gfarm_config_gsi_timeleft(&gsivalue); if (e == GFARM_ERR_NO_ERROR) { e = gfarm2fs_xattr_copy(gsivalue, value, sizep); free(gsivalue); } return (e); } else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } /* ------------------------------- */ static struct gfarm2fs_xattr_sw *funcs = &sw_disable_acl; gfarm_error_t gfarm2fs_xattr_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (XATTR_IS_LOCALLY_SUPPORTED(name)) return (GFARM_ERR_NO_ERROR); return ((*funcs->set)(path, name, value, size, flags)); } gfarm_error_t gfarm2fs_xattr_get(const char *path, const char *name, void *value, size_t *sizep) { if (XATTR_IS_LOCALLY_SUPPORTED(name)) return (gfarm2fs_xattr_get_local(path, name, value, sizep)); return ((*funcs->get)(path, name, value, sizep)); } gfarm_error_t gfarm2fs_xattr_remove(const char *path, const char *name) { if (XATTR_IS_LOCALLY_SUPPORTED(name)) return (GFARM_ERR_NO_ERROR); return ((*funcs->remove)(path, name)); } void gfarm2fs_xattr_init(struct gfarm2fs_param *params) { #ifdef ENABLE_ACL if (params->disable_acl) funcs = &sw_disable_acl; else if (params->fix_acl) funcs = &sw_fix_acl; else { funcs = &sw_normal; gfarm_xattr_caching_pattern_add(GFARM_ACL_EA_ACCESS); gfarm_xattr_caching_pattern_add(GFARM_ACL_EA_DEFAULT); } #endif } <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/gftool/gfreg/gfreg.c #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <string.h> #include <assert.h> #include <gfarm/gfarm.h> /* * Register a local file to Gfarm filesystem * * gfreg <local_filename> <gfarm_url> * * $Id$ */ /* Don't permit set[ug]id bit for now */ #define FILE_MODE_MASK 0777 /* * This value is only used as a last resort, * when the local file argument is "-" only, * and if `gfarm_url' is a directory or doesn't exist. */ #define DEFAULT_FILE_MODE 0644 char *program_name = "gfreg"; static const char STDIN_FILENAME[] = "-"; void usage() { fprintf(stderr, "Usage: %s [option] <local_filename> ... <gfarm_url>\n", program_name); fprintf(stderr, "Register local file(s) to Gfarm filesystem.\n\n"); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-I fragment-index\tspecify a fragment index\n"); fprintf(stderr, "\t-N number\t\ttotal number of fragments\n"); fprintf(stderr, "\t-a architecture\t\tspecify an architecture\n"); fprintf(stderr, "\t-h hostname\t\tspecify a hostname\n"); fprintf(stderr, "\t-H hostfile\t\tspecify hostnames by a file\n"); fprintf(stderr, "\t-D domainname\t\tspecify a domainname\n"); fprintf(stderr, "\t-f \t\t\tforce to register\n"); exit(EXIT_FAILURE); } static int opt_force = 0; static int error_happened = 0; static int open_file(char *filename, int *fdp, int *fd_needs_close_p) { int fd; if (strcmp(filename, STDIN_FILENAME) == 0) { *fdp = STDIN_FILENO; *fd_needs_close_p = 0; return (1); } if ((fd = open(filename, O_RDONLY)) == -1) { fprintf(stderr, "%s: cannot open %s: %s\n", program_name, filename, strerror(errno)); error_happened = 1; return (0); } *fdp = fd; *fd_needs_close_p = 1; return (1); } static int get_mode(int fd, char *filename, gfarm_mode_t *mode_p) { struct stat s; if (fstat(fd, &s) == -1) { fprintf(stderr, "%s: cannot stat %s: %s\n", program_name, filename, strerror(errno)); error_happened = 1; return (0); } *mode_p = s.st_mode; return (1); } static int get_file_mode(int fd, char *filename, gfarm_mode_t *file_mode_p) { if (!get_mode(fd, filename, file_mode_p)) return (0); *file_mode_p &= FILE_MODE_MASK; return (1); } static int concat_dir_name(const char *gfarm_url, const char *base_name, char **target_url_p) { char *target_url = malloc(strlen(gfarm_url) + 1 + strlen(base_name) + 1); if (target_url == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); error_happened = 1; return (0); } if (*gfarm_path_dir_skip(gfarm_url_prefix_skip(gfarm_url)) != '\0') sprintf(target_url, "%s/%s", gfarm_url, base_name); else sprintf(target_url, "%s%s", gfarm_url, base_name); *target_url_p = target_url; return (1); } static int section_does_not_exists(char *gfarm_url, char *section) { struct gfs_stat s; if (gfs_stat_section(gfarm_url, section, &s) == NULL) { gfs_stat_free(&s); fprintf(stderr, "%s: %s:%s already exists\n", program_name, gfarm_url, section); return (0); } return (1); } #define GFS_FILE_BUFSIZE 65536 static void copy_file(int fd, GFS_File gf, char *gfarm_url, char *section) { char *e; ssize_t rv; int length; /* XXX - should be size_t */ char buffer[GFS_FILE_BUFSIZE]; for (;;) { rv = read(fd, buffer, sizeof(buffer)); if (rv <= 0) break; /* XXX - partial write case ? */ e = gfs_pio_write(gf, buffer, rv, &length); if (e != NULL) { fprintf(stderr, "%s: writing to %s:%s: %s\n", program_name, gfarm_url, section, e); error_happened = 1; break; } } } static int get_nsections(char *gfarm_url, int *nsectionsp) { char *e, *gfarm_file; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: gfarm_url_make_path(%s): %s\n", program_name, gfarm_url, e); error_happened = 1; return (0); } e = gfarm_path_info_get(gfarm_file, &pi); free(gfarm_file); if (e != NULL) { if (e == GFARM_ERR_NO_SUCH_OBJECT) fprintf(stderr, "%s: missing -N <total number of fragments>\n", program_name); else fprintf(stderr, "%s: gfarm_get_path_info(%s): %s\n", program_name, gfarm_url, e); error_happened = 1; return (0); } *nsectionsp = pi.status.st_nsections; gfarm_path_info_free(&pi); return (1); } static void register_program(int is_dir, char *gfarm_url, char *section, char *hostname, char *filename, int use_file_mode, gfarm_mode_t file_mode) { char *e; int fd, fd_needs_close; char *target_url; GFS_File gf; if (!open_file(filename, &fd, &fd_needs_close)) return; if (!use_file_mode && !get_file_mode(fd, filename, &file_mode)) goto finish; if (!is_dir) target_url = gfarm_url; else if (!concat_dir_name(gfarm_url, gfarm_path_dir_skip(filename), &target_url)) goto finish; if (opt_force || section_does_not_exists(target_url, section)) { e = gfs_pio_create(target_url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC, file_mode, &gf); if (e != NULL) { fprintf(stderr, "%s: cannot open %s: %s\n", program_name, target_url, e); error_happened = 1; } else { if ((e = gfs_pio_set_view_section(gf, section, hostname, 0)) != NULL) { fprintf(stderr, "%s: cannot open %s:%s: %s\n", program_name, target_url, section, e); error_happened = 1; } else { copy_file(fd, gf, target_url, section); } gfs_pio_close(gf); } } if (target_url != gfarm_url) free(target_url); finish: if (fd_needs_close) close(fd); } static void register_fragment(int is_dir, char *gfarm_url, int index, int nfragments, char *hostname, char *filename, int use_file_mode, gfarm_mode_t file_mode) { char *e; int fd, fd_needs_close; char *target_url; GFS_File gf; char section[GFARM_INT32STRLEN + 1]; if (!open_file(filename, &fd, &fd_needs_close)) return; if (!use_file_mode && !get_file_mode(fd, filename, &file_mode)) goto finish; if (!is_dir) target_url = gfarm_url; else if (!concat_dir_name(gfarm_url, gfarm_path_dir_skip(filename), &target_url)) goto finish; if (nfragments == GFARM_FILE_DONTCARE && !get_nsections(target_url, &nfragments)) goto finish_url; sprintf(section, "%d", index); if (opt_force || section_does_not_exists(target_url, section)) { e = gfs_pio_create(target_url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC, file_mode, &gf); if (e != NULL) { fprintf(stderr, "%s: cannot open %s: %s\n", program_name, target_url, e); error_happened = 1; } else { if ((e = gfs_pio_set_view_index(gf, nfragments, index, hostname, 0)) != NULL) { fprintf(stderr, "%s: cannot open %s:%d: %s\n", program_name, target_url, index, e); error_happened = 1; } else { copy_file(fd, gf, target_url, section); } gfs_pio_close(gf); } } finish_url: if (target_url != gfarm_url) free(target_url); finish: if (fd_needs_close) close(fd); } int main(int argc, char *argv[]) { /* options */ char *section = NULL; int nfragments = GFARM_FILE_DONTCARE; /* -1, actually */ char *hostname = NULL; char *hostfile = NULL; char *domainname = NULL; char *e, *gfarm_url, *file_mode_arg; gfarm_mode_t file_mode = DEFAULT_FILE_MODE; int c, i, is_dir, index; struct gfs_stat gs; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } /* Command options */ while ((c = getopt(argc, argv, "a:fh:D:I:N:?")) != -1) { switch (c) { case 'I': case 'a': section = optarg; break; case 'N': nfragments = strtol(optarg, NULL, 0); break; case 'h': hostname = optarg; break; case 'D': domainname = optarg; break; case 'f': opt_force = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc == 0) { fprintf(stderr, "%s: missing a local filename\n", program_name); usage(); } if (argc == 1) { fprintf(stderr, "%s: missing a Gfarm URL\n", program_name); usage(); } gfarm_url = argv[argc - 1]; --argc; if (!gfarm_is_url(gfarm_url)) { fprintf(stderr, "%s: %s: %s\n", program_name, gfarm_url, GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING); exit(EXIT_FAILURE); } c = 0; if (hostname != NULL) c++; if (hostfile != NULL) c++; if (domainname != NULL) c++; if (c > 1) { fprintf(stderr, "%s: more than one options are specified " "from -h, -H and -D\n", program_name); usage(); } /* * distinguish which mode is specified: * 1. program mode: * gfreg [-h <hostname>] [-a <architecture>] \ * <local-program>... <gfarm-URL> * 2. auto index mode: * gfreg [-h <hostname>] [-H <hostfile>] [-D <domainname>] \ * <local-file>... <gfarm-URL> * 3. fragment mode: * gfreg [-h <hostname>] [-N <nfragments>] -I <index> \ * <local-file>... <gfarm-URL> */ e = gfs_stat(gfarm_url, &gs); if (e == GFARM_ERR_NO_SUCH_OBJECT) { is_dir = 0; file_mode_arg = NULL; } else if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, gfarm_url, e); exit(EXIT_FAILURE); } else { if (GFARM_S_ISREG(gs.st_mode)) { is_dir = 0; file_mode_arg = gfarm_url; file_mode = gs.st_mode; } else if (GFARM_S_ISDIR(gs.st_mode)) { is_dir = 1; file_mode_arg = NULL; } else { /* defensive programming. this shouldn't happen. */ fprintf(stderr, "%s: %s: unknown file type\n", program_name, gfarm_url); exit(EXIT_FAILURE); } gfs_stat_free(&gs); } c = 0; /* count of "-" in the arguments */ if (hostfile != NULL && strcmp(hostfile, STDIN_FILENAME) == 0) ++c; for (i = 0; i < argc; i++) { int fd, fd_needs_close; gfarm_mode_t m; if (!open_file(argv[i], &fd, &fd_needs_close)) exit(EXIT_FAILURE); if (!get_mode(fd, argv[i], &m)) exit(EXIT_FAILURE); if (S_ISREG(m)) { if (file_mode_arg == NULL) { /* * NOTE: this mode may be used for the mode * to create the gfarm file. */ file_mode_arg = argv[i]; file_mode = m & FILE_MODE_MASK; } if (((m & 0111) != 0) != ((file_mode & 0111) != 0)) { fprintf(stderr, "%s: program and non-program are mixed in " "%s and %s\n", program_name, file_mode_arg, argv[i]); exit(EXIT_FAILURE); } } else if (fd_needs_close) { /* if it's "-", allow non-file (e.g. pipe) */ fprintf(stderr, "%s: %s: not a regular file\n", program_name, argv[i]); exit(EXIT_FAILURE); } if (fd_needs_close) { close(fd); } else if (++c > 1) { fprintf(stderr, "%s: `-' (stdin) is specified " "multiple times\n", program_name); exit(EXIT_FAILURE); } } if ((file_mode & 0111) != 0) { /* * program mode */ int section_alloced = 0; if (!is_dir && argc != 1) { fprintf(stderr, "%s: only one file can be specified to" " register the gfarm program `%s'\n", program_name, gfarm_url); exit(EXIT_FAILURE); } if (hostfile != NULL || domainname != NULL) { fprintf(stderr, "%s: cannot use -%c to register programs\n", program_name, hostfile != NULL ? 'H' : 'D'); exit(EXIT_FAILURE); } if (nfragments != GFARM_FILE_DONTCARE) { /* * XXX - call gfarm_url_replicate() to replicate * `nfragments' copies of gfarm_url:section? */ fprintf(stderr, "%s: warning: option -N is currently ignored\n", program_name); } if (section != NULL) { ; } else if (hostname != NULL) { char *canonical; e = gfarm_host_get_canonical_name(hostname, &canonical); if (e != NULL) { if (e == GFARM_ERR_NO_SUCH_OBJECT) e = "not a filesystem node"; fprintf(stderr, "%s: host %s: %s\n", program_name, hostname, e); exit(EXIT_FAILURE); } section_alloced = 1; section = gfarm_host_info_get_architecture_by_host( canonical); free(canonical); if (section == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } } else if (gfarm_host_get_self_architecture(&section) != NULL){ fprintf(stderr, "%s: missing -a option\n", program_name); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) { register_program(is_dir, gfarm_url, section, hostname, argv[i], file_mode_arg == gfarm_url || file_mode_arg == argv[i], file_mode); } if (section_alloced) free(section); } else if (section != NULL || gfs_pio_get_node_rank(&index) == NULL) { /* * fragment mode */ if (section != NULL) index = strtol(section, NULL, 0); else if (nfragments == GFARM_FILE_DONTCARE) gfs_pio_get_node_size(&nfragments); if (!is_dir && argc != 1) { fprintf(stderr, "%s: only one file can be specified to" " register a fragment %s of the gfarm file `%s'\n", program_name, section, gfarm_url); exit(EXIT_FAILURE); } if (hostfile != NULL || domainname != NULL) { fprintf(stderr, "%s: cannot use -%c with -I\n", program_name, hostfile != NULL ? 'H' : 'D'); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) { register_fragment(is_dir, gfarm_url, index, nfragments, hostname, argv[i], file_mode_arg == gfarm_url || file_mode_arg == argv[i], file_mode); } } else { /* * auto index mode */ char **hosts = NULL; if (nfragments == GFARM_FILE_DONTCARE) nfragments = argc; if (nfragments != argc) { fprintf(stderr, "%s: local file number %d " "doesn't match with -N %d\n", program_name, argc, nfragments); exit(EXIT_FAILURE); } if (is_dir && nfragments > 1) { fprintf(stderr, "%s: cannot determine the file name " "under the directory %s, " "because multiple local file names are specifed\n", program_name, gfarm_url); exit(EXIT_FAILURE); } if (hostname != NULL) { ; } else if (hostfile != NULL) { int nhosts, error_line; e = gfarm_hostlist_read(hostfile, &nhosts, &hosts, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s line %d: %s\n", program_name, hostfile, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, hostfile, e); exit(EXIT_FAILURE); } } else { hosts = malloc(sizeof(*hosts) * nfragments); if (hosts == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(EXIT_FAILURE); } if (domainname != NULL) e = gfarm_schedule_search_idle_by_domainname( domainname, nfragments, hosts); else e = gfarm_schedule_search_idle_by_all( nfragments, hosts); if (e != NULL) { fprintf(stderr, "%s: selecting filesystem nodes: %s\n", program_name, e); exit(EXIT_FAILURE); } } /* XXX - need to register in parallel? */ for (i = 0; i < argc; i++) { register_fragment(is_dir, gfarm_url, i, nfragments, hostname != NULL ? hostname : hosts[i], argv[i], 1, file_mode); } if (hostname == NULL) gfarm_strings_free_deeply(nfragments, hosts); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } exit(error_happened); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/install-agentd.sh #! /bin/sh # # Install the 'gfarm_zabbix' package for Zabbix agent. # . ./install.conf # install(1) command. INSTALL=install # Directory where external scripts for Zabbix reside. ZABBIX_EXTSCRIPTDIR=$ZABBIX_CONFDIR/externalscripts # Directory where configuration files for Zabbix agentd reside. ZABBIX_AGENTD_CONFSUBDIR=$ZABBIX_CONFDIR/zabbix_agentd.d # # Create "$1" file from "$1.in". # create_file() { [ -f "$1".in ] || return 0 [ -f "$1" ] && rm -f "$1" sed \ -e "s|@GFARM_BINDIR@|$GFARM_BINDIR|g" \ -e "s|@GFMD_JOURNALDIR@|$GFMD_JOURNALDIR|g" \ -e "s|@GFMD_PIDFILE@|$GFMD_PIDFILE|g" \ -e "s|@SYSLOG_FILE@|$SYSLOG_FILE|g" \ -e "s|@ZABBIX_CONFDIR@|$ZABBIX_CONFDIR|g" \ -e "s|@ZABBIX_EXTSCRIPTDIR@|$ZABBIX_EXTSCRIPTDIR|g" \ "$1.in" > "$1" } # # Install files in 'gfarm-zabbix_scripts/zabbix_agentd.d/' to # $ZABBIX_AGENTD_CONFSUBDIR. # for I in \ userparameter_postgresql.conf \ userparameter_redundant_gfarm.conf; do SRCFILE=gfarm-zabbix_scripts/zabbix_agentd.d/$I DSTFILE=$ZABBIX_AGENTD_CONFSUBDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Make a directory '$ZABBIX_EXTSCRIPTDIR'. # DIR=$ZABBIX_EXTSCRIPTDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files in 'gfarm-zabbix_scripts/externalscripts/' to # $ZABBIX_EXTSCRIPTDIR. # for I in \ zbx_chk_dead_gfarm_pgsql.sh \ zbx_chk_dead_gfmd.sh \ zbx_chk_dead_gfsd.sh \ zbx_chk_gfarm.conf \ zbx_chk_gfhost_cli.sh \ zbx_chk_gfhost_gfsd.sh \ zbx_chk_gfmdhost_cli.sh \ zbx_chk_gfmdlist_cli.sh \ zbx_chk_gfmdtype_gfmd.sh \ zbx_chk_gfsched_gfmd.sh \ zbx_chk_gfsched_gfsd.sh \ zbx_chk_listenport_gfmd.sh \ zbx_chk_listenport_gfsd.sh \ zbx_chk_mastername_cli.sh \ zbx_chk_pgsql.sh \ zbx_failover.pl \ zbx_gfarm_utils.inc; do SRCFILE=gfarm-zabbix_scripts/externalscripts/$I DSTFILE=$ZABBIX_EXTSCRIPTDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Change mode of $SYSLOG_FILE # chmod 0644 $SYSLOG_FILE \ && echo "Set mode (= 0644) of the file: $SYSLOG_FILE" <file_sep>/gfarm/branches/metadb_dev/bench/thput-fsys/thput-fsys.c #include <assert.h> #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> double timerval_calibration; #ifdef i386 typedef unsigned long long timerval_t; unsigned long long get_cycles(void) { unsigned long long rv; __asm __volatile("rdtsc" : "=A" (rv)); return (rv); } #define gettimerval(tp) (*(tp) = get_cycles()) #define timerval_second(tp) (*(tp) * timerval_calibration) #define timerval_sub(t1p, t2p) ((*(t1p) - *(t2p)) * timerval_calibration) void timerval_calibrate(void) { timerval_t t1, t2; struct timeval s1, s2; gettimerval(&t1); gettimeofday(&s1, NULL); sleep(10); gettimerval(&t2); gettimeofday(&s2, NULL); timerval_calibration = (t2 - t1) / ( (s2.tv_sec - s1.tv_sec) + (s2.tv_usec - s1.tv_usec) * .000001); timerval_calibration = 1.0 / timerval_calibration; } #else /* gettimeofday */ typedef struct timeval timerval_t; #define gettimerval(t1) gettimeofday(t1, NULL) #define timerval_second(t1) ((double)(t1)->tv_sec \ + (double)(t1)->tv_usec * .000001) #define timerval_sub(t1, t2) \ (((double)(t1)->tv_sec - (double)(t2)->tv_sec) \ + ((double)(t1)->tv_usec - (double)(t2)->tv_usec) * .000001) void timerval_calibrate(void) { timerval_calibration = 1.0; } #endif int tm_write_write_measured = 0; timerval_t tm_write_open_0, tm_write_open_1; timerval_t tm_write_write_0, tm_write_write_1; timerval_t tm_write_close_0, tm_write_close_1; int tm_read_read_measured = 0; timerval_t tm_read_open_0, tm_read_open_1; timerval_t tm_read_read_0, tm_read_read_1; timerval_t tm_read_close_0, tm_read_close_1; #define ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0])) /* Linux stupidly requires 512byte aligned buffer for raw device access. */ #define ALIGNMENT 512 #define MAX_BUFFER_SIZE_NUMBER 32 char *buffer; int max_buffer_size = 0; void * alloc_aligned_memory(size_t size, int alignment) { char *p = malloc(size + alignment - 1); if (p == NULL) { fprintf(stderr, "no memory for %ld bytes\n", (long)size + alignment - 1); exit(1); } if (((long)p & (alignment - 1)) != 0) p += alignment - ((long)p & (alignment - 1)); return (p); } void initbuffer(void) { int i; for (i = 0; i < max_buffer_size; i++) buffer[i] = i; } void writetest(char *ofile, int buffer_size, off_t file_size) { int fd, rv; off_t residual; gettimerval(&tm_write_open_0); fd = open(ofile, O_CREAT|O_TRUNC|O_WRONLY, 0666); gettimerval(&tm_write_open_1); if (fd == -1) { perror(ofile); exit(1); } for (residual = file_size; residual > 0; residual -= rv) { if (!tm_write_write_measured) { tm_write_write_measured = 1; gettimerval(&tm_write_write_0); rv = write(fd, buffer, buffer_size <= residual ? buffer_size : residual); gettimerval(&tm_write_write_1); } else { rv = write(fd, buffer, buffer_size <= residual ? buffer_size : residual); } if (rv == -1) { perror("write test"); break; } assert(rv == (buffer_size <= residual ? buffer_size : residual)); } if (residual > 0) { fprintf(stderr, "write test failed, residual = %ld\n", (long)residual); } gettimerval(&tm_write_close_0); rv = close(fd); gettimerval(&tm_write_close_1); if (rv == -1) perror("write test close failed"); } void readtest(char *ifile, int buffer_size, off_t file_size) { int fd, rv; off_t residual; gettimerval(&tm_read_open_0); fd = open(ifile, O_RDONLY); gettimerval(&tm_read_open_1); if (fd == -1) { perror(ifile); exit(1); } for (residual = file_size; residual > 0; residual -= rv) { if (!tm_read_read_measured) { tm_read_read_measured = 1; gettimerval(&tm_read_read_0); rv = read(fd, buffer, buffer_size <= residual ? buffer_size : residual); gettimerval(&tm_read_read_1); } else { rv = read(fd, buffer, buffer_size <= residual ? buffer_size : residual); } if (rv == 0) break; if (rv == -1) { perror("read test"); break; } assert(rv == buffer_size || rv == residual); } if (residual > 0) { fprintf(stderr, "read test failed, residual = %ld\n", (long)residual); } gettimerval(&tm_read_close_0); rv = close(fd); gettimerval(&tm_read_close_1); if (rv == -1) perror("read test closed failed"); } void copytest(char *ifile, char *ofile, int buffer_size, off_t file_size) { int ifd, ofd; int rv, osize; off_t residual; ifd = open(ifile, O_RDONLY); if (ifd == -1) { perror(ifile); exit(1); } ofd = open(ofile, O_CREAT|O_TRUNC|O_WRONLY, 0666); if (ofd == -1) { perror(ofile); exit(1); } for (residual = file_size; residual > 0; residual -= rv) { rv = read(ifd, buffer, buffer_size <= residual ? buffer_size : residual); if (rv == 0) break; if (rv == -1) { perror("copytest read"); break; } assert(rv == buffer_size || rv == residual); osize = rv; rv = write(ofd, buffer, osize); if (rv == -1) { perror("copytest write"); break; } assert(rv == osize); } if (residual > 0) { fprintf(stderr, "copy test failed, residual = %ld\n", (long)residual); } if (close(ofd) == -1) perror("copy test write close failed"); if (close(ifd) == -1) perror("copy test read close failed"); } double timeval_sub(struct timeval *t1, struct timeval *t2) { return ((t1->tv_sec + t1->tv_usec * .000001) - (t2->tv_sec + t2->tv_usec * .000001)); } #define TESTMODE_WRITE 1 #define TESTMODE_READ 2 #define TESTMODE_COPY 4 #define FLAG_DONT_REMOVE 1 #define FLAG_MEASURE_PRIMITIVES 2 void test_title(int test_mode, off_t file_size, int flags) { fprintf(stdout, "testing with %d MB file\n", (int)file_size); printf("%-8s", "bufsize"); if (test_mode & TESTMODE_WRITE) printf(" %20s", "write [bytes/sec]"); if (test_mode & TESTMODE_READ) printf(" %20s", "read [bytes/sec]"); if (test_mode & TESTMODE_COPY) printf(" %20s", "copy [bytes/sec]"); printf("\n"); fflush(stdout); if ((flags & FLAG_MEASURE_PRIMITIVES) != 0 && (test_mode & (TESTMODE_WRITE|TESTMODE_READ)) != 0) fprintf(stderr, "timer/sec=%g\n", 1.0 / timerval_calibration); } void test(int test_mode, char *file1, char *file2, int buffer_size, off_t file_size, int flags) { struct timeval t1, t2, t3, t4; if ((flags & FLAG_DONT_REMOVE) == 0) { if (test_mode & TESTMODE_WRITE) unlink(file1); if (test_mode & TESTMODE_COPY) unlink(file2); } gettimeofday(&t1, NULL); if (test_mode & TESTMODE_WRITE) writetest(file1, buffer_size, file_size); gettimeofday(&t2, NULL); if (test_mode & TESTMODE_READ) readtest(file1,buffer_size, file_size); gettimeofday(&t3, NULL); if (test_mode & TESTMODE_COPY) copytest(file1, file2, buffer_size, file_size); gettimeofday(&t4, NULL); printf("%7d ", buffer_size); if (test_mode & TESTMODE_WRITE) printf(" %10.0f%10s", file_size / timeval_sub(&t2, &t1), ""); if (test_mode & TESTMODE_READ) printf(" %10.0f%10s", file_size / timeval_sub(&t3, &t2), ""); if (test_mode & TESTMODE_COPY) printf(" %10.0f%10s", file_size / timeval_sub(&t4, &t3), ""); printf("\n"); fflush(stdout); if ((flags & FLAG_DONT_REMOVE) == 0) { if (test_mode & TESTMODE_WRITE) unlink(file1); if (test_mode & TESTMODE_COPY) unlink(file2); } if ((flags & FLAG_MEASURE_PRIMITIVES) != 0 && (test_mode & (TESTMODE_WRITE|TESTMODE_READ)) != 0) { fprintf(stderr, "%7d ", buffer_size); if (test_mode & TESTMODE_WRITE) fprintf(stderr, " %g %g %g", timerval_sub(&tm_write_open_1, &tm_write_open_0), timerval_sub(&tm_write_write_1, &tm_write_write_0), timerval_sub(&tm_write_close_1, &tm_write_close_0) ); if (test_mode & TESTMODE_READ) fprintf(stderr, " %g %g %g", timerval_sub(&tm_read_open_1, &tm_read_open_0), timerval_sub(&tm_read_read_1, &tm_read_read_0), timerval_sub(&tm_read_close_1, &tm_read_close_0) ); fprintf(stderr, "\n"); tm_write_write_measured = tm_read_read_measured = 0; } } int main(int argc, char **argv) { char *file1 = "test.file1"; char *file2 = "test.file2"; int test_mode = 0; int c, i, buffer_sizec = 0, buffer_sizes_space[MAX_BUFFER_SIZE_NUMBER]; static int buffer_sizes_default[] = { 512, 1024, 8 * 1024, 64 * 1024, 256 * 1024, 1024 * 1024, }; int *buffer_sizes; off_t file_size = 1024; int flags = 0; while ((c = getopt(argc, argv, "b:s:wrcmp")) != -1) { switch (c) { case 'b': if (buffer_sizec >= MAX_BUFFER_SIZE_NUMBER) { fprintf(stderr, "too many -b options (max %d)\n", MAX_BUFFER_SIZE_NUMBER); exit(1); } buffer_sizes_space[buffer_sizec] = strtol(optarg, NULL, 0); buffer_sizec++; break; case 's': file_size = strtol(optarg, NULL, 0); break; case 'w': test_mode |= TESTMODE_WRITE; break; case 'r': test_mode |= TESTMODE_READ; break; case 'c': test_mode |= TESTMODE_COPY; break; case 'm': flags |= FLAG_MEASURE_PRIMITIVES; timerval_calibrate(); break; case 'p': flags |= FLAG_DONT_REMOVE; break; case '?': default: fprintf(stderr, "Usage: thput-fsys [options]" " [file1 [file2]]\n" "options:\n" "\t-b block-size\n" "\t-s file-size\n" "\t-w : write test\n" "\t-r : read test\n" "\t-c : copy test\n" "\t-p : don't remove\n"); exit(1); } } argc -= optind; argv += optind; if (argc > 0) file1 = argv[0]; if (argc > 1) file2 = argv[1]; if (test_mode == 0) test_mode = TESTMODE_WRITE|TESTMODE_READ|TESTMODE_COPY; if (buffer_sizec == 0) { buffer_sizec = ARRAY_LENGTH(buffer_sizes_default); buffer_sizes = buffer_sizes_default; } else { buffer_sizes = buffer_sizes_space; } for (i = 0; i < buffer_sizec; i++) { if (max_buffer_size < buffer_sizes[i]) max_buffer_size = buffer_sizes[i]; } buffer = alloc_aligned_memory(max_buffer_size, ALIGNMENT); test_title(test_mode, file_size, flags); file_size *= 1024 * 1024; initbuffer(); for (i = 0; i < buffer_sizec; i++) { test(test_mode, file1, file2, buffer_sizes[i], file_size, flags); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/libgfarm/gfarm/gfs_pio_global.c /* * pio operations for global view * * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <string.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "gfs_pio.h" struct gfs_file_global_context { GFS_File fragment_gf; int fragment_index; char *url; file_offset_t *offsets; }; static char * gfs_pio_view_global_close(GFS_File gf) { struct gfs_file_global_context *gc = gf->view_context; char *e; e = gfs_pio_close(gc->fragment_gf); free(gc->url); free(gc->offsets); free(gc); gf->view_context = NULL; gfs_pio_set_view_default(gf); return (e); } /* * Instead of just calling gfs_pio_set_view_index(), * we use another GFS_File to move to another fragment. * This is because we don't want to leave this context inconsistent, * if failure happens at the gfs_pio_set_view_index(). */ static char * gfs_pio_view_global_move_to(GFS_File gf, int fragment_index) { struct gfs_file_global_context *gc = gf->view_context; char *e; GFS_File new_fragment; if ((gf->open_flags & GFARM_FILE_CREATE) != 0) e = gfs_pio_create(gc->url, gf->open_flags, gf->pi.status.st_mode & GFARM_S_ALLPERM, &new_fragment); else e = gfs_pio_open(gc->url, gf->open_flags, &new_fragment); if (e != NULL) return (e); e = gfs_pio_set_view_index(new_fragment, gf->pi.status.st_nsections, fragment_index, NULL, gf->view_flags); if (e != NULL) { gfs_pio_close(new_fragment); return (e); } if (gc->fragment_gf != NULL) { gfs_pio_close(gc->fragment_gf); /* XXX need a way to report error on here */ } gc->fragment_gf = new_fragment; gc->fragment_index = fragment_index; return (NULL); } static char * gfs_pio_view_global_adjust(GFS_File gf, const char *buffer, size_t *sizep) { struct gfs_file_global_context *gc = gf->view_context; size_t size = *sizep; char *e = NULL; if (gc->fragment_index < gf->pi.status.st_nsections - 1 && gf->io_offset >= gc->offsets[gc->fragment_index + 1]) { e = gfs_pio_view_global_move_to(gf, gc->fragment_index + 1); if (e != NULL) return (e); } if (gc->fragment_index < gf->pi.status.st_nsections - 1 && gf->io_offset + size > gc->offsets[gc->fragment_index + 1]) size = gc->offsets[gc->fragment_index + 1] - gf->io_offset; *sizep = size; return (e); } static char * gfs_pio_view_global_write(GFS_File gf, const char *buffer, size_t size, size_t *lengthp) { struct gfs_file_global_context *gc = gf->view_context; char *e = gfs_pio_view_global_adjust(gf, buffer, &size); int length; /* XXX - should be size_t */ if (e != NULL) return (e); e = gfs_pio_write(gc->fragment_gf, buffer, size, &length); if (e != NULL) return (e); /* XXX - should notify this change to all of the parallel process. */ if (gc->fragment_index == gf->pi.status.st_nsections - 1 && gf->io_offset + length > gc->offsets[gf->pi.status.st_nsections]) gc->offsets[gf->pi.status.st_nsections] = gf->io_offset + length; *lengthp = length; return (NULL); } static char * gfs_pio_view_global_read(GFS_File gf, char *buffer, size_t size, size_t *lengthp) { struct gfs_file_global_context *gc = gf->view_context; char *e = gfs_pio_view_global_adjust(gf, buffer, &size); int length; /* XXX - should be size_t */ if (e != NULL) return (e); e = gfs_pio_read(gc->fragment_gf, buffer, size, &length); if (e != NULL) return (e); *lengthp = length; return (NULL); } static int gfs_pio_view_global_bsearch(file_offset_t key, file_offset_t *v, size_t n) { size_t m, l = 0, r = n - 1; while (l < r) { m = (l + r) / 2; if (key < v[m]) r = m - 1; else if (key < v[m + 1]) return (m); else l = m + 1; } return (l); } static char * gfs_pio_view_global_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { struct gfs_file_global_context *gc = gf->view_context; char *e; int fragment; switch (whence) { case SEEK_SET: break; case SEEK_CUR: offset += gf->io_offset + gf->p; break; case SEEK_END: offset += gc->offsets[gf->pi.status.st_nsections]; break; } if (gc->offsets[gc->fragment_index] <= offset && offset <= gc->offsets[gc->fragment_index + 1]) { /* same file fragment */ if (offset == gf->io_offset) return (NULL); } else { if (offset < 0) return (GFARM_ERR_INVALID_ARGUMENT); if (offset >= gc->offsets[gf->pi.status.st_nsections - 1]) fragment = gf->pi.status.st_nsections - 1; else fragment = gfs_pio_view_global_bsearch( offset, gc->offsets, gf->pi.status.st_nsections-1); e = gfs_pio_view_global_move_to(gf, fragment); if (e != NULL) return (e); } offset -= gc->offsets[gc->fragment_index]; e = gfs_pio_seek(gc->fragment_gf, offset, SEEK_SET, &offset); if (e != NULL) return (e); *resultp = gc->offsets[gc->fragment_index] + offset; return (NULL); } static int gfs_pio_view_global_fd(GFS_File gf) { struct gfs_file_global_context *gc = gf->view_context; return (gfs_pio_fileno(gc->fragment_gf)); } static char * gfs_pio_view_global_stat(GFS_File gf, struct gfs_stat *status) { struct gfs_file_global_context *gc = gf->view_context; char *e; e = gfs_stat(gc->url, status); if (e != NULL) return (e); return (NULL); } struct gfs_pio_ops gfs_pio_view_global_ops = { gfs_pio_view_global_close, gfs_pio_view_global_write, gfs_pio_view_global_read, gfs_pio_view_global_seek, gfs_pio_view_global_fd, gfs_pio_view_global_stat }; char * gfs_pio_set_view_global(GFS_File gf, int flags) { struct gfs_file_global_context *gc; char *e, *arch; int i, n; struct gfarm_file_section_info *infos; static char gfarm_url_prefix[] = "gfarm:/"; e = gfs_pio_set_view_default(gf); if (e != NULL) return (e); if (GFS_FILE_IS_PROGRAM(gf)) { e = gfarm_host_get_self_architecture(&arch); if (e != NULL) return (gf->error = e); return (gfs_pio_set_view_section(gf, arch, NULL, flags)); } if ((gf->open_flags & GFARM_FILE_CREATE) != 0) return (gfs_pio_set_view_index(gf, 1, 0, NULL, flags)); gc = malloc(sizeof(struct gfs_file_global_context)); if (gc == NULL) { gf->error = GFARM_ERR_NO_MEMORY; return (gf->error); } e = gfarm_file_section_info_get_sorted_all_serial_by_file( gf->pi.pathname, &n, &infos); if (e != NULL) { free(gc); gf->error = e; return (e); } if (n != gf->pi.status.st_nsections) { gfarm_file_section_info_free_all(n, infos); free(gc); gf->error = "metainfo inconsitency, fragment number mismatch"; return (gf->error); } gc->offsets = malloc(sizeof(file_offset_t) * (n + 1)); gc->url = malloc(sizeof(gfarm_url_prefix) + strlen(gf->pi.pathname)); if (gc->offsets == NULL || gc->url == NULL) { if (gc->offsets != NULL) free(gc->offsets); if (gc->url != NULL) free(gc->url); gfarm_file_section_info_free_all(n, infos); free(gc); gf->error = GFARM_ERR_NO_MEMORY; return (gf->error); } gc->offsets[0] = 0; for (i = 0; i < n; i++) gc->offsets[i + 1] = gc->offsets[i] + infos[i].filesize; gfarm_file_section_info_free_all(n, infos); sprintf(gc->url, "%s%s", gfarm_url_prefix, gf->pi.pathname); gf->view_context = gc; gf->view_flags = flags; gc->fragment_gf = NULL; e = gfs_pio_view_global_move_to(gf, 0); if (e != NULL) { free(gc->url); free(gc->offsets); free(gc); gf->view_context = NULL; gfs_pio_set_view_default(gf); gf->error = e; return (e); } gf->ops = &gfs_pio_view_global_ops; gf->p = gf->length = 0; gf->io_offset = gf->offset = 0; gf->error = NULL; return (NULL); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8/systest/parameters/Makefile.am parametersdir = @gfarm_root@/share/gfarm/systest/parameters dist_parameters_DATA = read_files_1c_100m_1000f_100M \ read_files_1c_100m_1000f_1G \ read_files_1c_100m_1000f_1M \ read_files_1c_1m_1000f_100M \ read_files_1c_1m_1000f_1G \ read_files_1c_1m_1000f_1M \ read_files_4c_100m_1000f_100M \ read_files_4c_100m_1000f_1G \ read_files_4c_100m_1000f_1M \ read_files_4c_100m_1f_1G \ read_files_4c_250m_1000f_100M \ read_files_4c_250m_1000f_1G \ read_files_4c_250m_1000f_1M \ read_files_4c_250m_1f_1G \ write_files_1c_100m_1000f_100M \ write_files_1c_100m_1000f_1G \ write_files_1c_100m_1000f_1M \ write_files_1c_1m_1000f_100M \ write_files_1c_1m_1000f_1G \ write_files_1c_1m_1000f_1M \ write_files_4c_100m_1000f_100M \ write_files_4c_100m_1000f_1G \ write_files_4c_100m_1000f_1M \ write_files_4c_100m_1f_1G \ write_files_4c_250m_1000f_100M \ write_files_4c_250m_1000f_1G \ write_files_4c_250m_1000f_1M \ write_files_4c_250m_1f_1G \ write_files_each_mntpnts_4c_250m_1000f_100M \ write_files_each_mntpnts_4c_250m_1000f_1G \ write_files_each_mntpnts_4c_250m_1000f_1M <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_dead_gfarm_pgsql.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo "error: gfmd does not listen ${prefix} port." exit 0 fi c=0 while read prefix host port; do initscript="${prefix}/etc/init.d/gfarm-pgsql" sudo $initscript status > /dev/null 2> /dev/null if [ $? -ne 0 ]; then echo "error: ${prefix} pgsql is dead." c=`expr $c + 1` fi done<<EOF `read_gfmd_confs "$1"` EOF if [ $c = 0 ]; then echo "ok" fi exit 0 <file_sep>/gfarm_samba/tags/gfarm_samba_0_0_1/gfarm_vfs.c /* * Gfarm Samba VFS module. * v0.0.1 03 Sep 2010 <NAME> <ohtsuji at hpcs.cs.tsukuba.ac.jp> * * * This program is free software; you can redistribute it and/or modify * it 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ //#include <stdio.h> #include "includes.h" #include <gfarm/gfarm.h> /* XXX FIXME */ #define GFS_DEV ((dev_t)-1) #define GFS_BLKSIZE 8192 #define STAT_BLKSIZ 512 /* for st_blocks */ static int gfs_hook_open_flags_gfarmize(int open_flags) { int gfs_flags; switch (open_flags & O_ACCMODE) { case O_RDONLY: gfs_flags = GFARM_FILE_RDONLY; break; case O_WRONLY: gfs_flags = GFARM_FILE_WRONLY; break; case O_RDWR: gfs_flags = GFARM_FILE_RDWR; break; default: return (-1); } #if 0 /* this is unnecessary */ if ((open_flags & O_CREAT) != 0) gfs_flags |= GFARM_FILE_CREATE; #endif if ((open_flags & O_TRUNC) != 0) gfs_flags |= GFARM_FILE_TRUNC; #if 0 /* not yet on Gfarm v2 */ if ((open_flags & O_APPEND) != 0) gfs_flags |= GFARM_FILE_APPEND; if ((open_flags & O_EXCL) != 0) gfs_flags |= GFARM_FILE_EXCLUSIVE; #endif #if 0 /* not yet on Gfarm v2 */ /* open(2) and creat(2) should be unbuffered */ gfs_flags |= GFARM_FILE_UNBUFFERED; #endif return (gfs_flags); } static uid_t get_uid(char *user) { struct passwd *pwd; char *luser; if (strcmp(gfarm_get_global_username(), user) == 0) return (getuid()); /* my own file */ /* * XXX - this interface will be changed soon to support * multiple gfmds. */ if (gfarm_global_to_local_username(user, &luser) == GFARM_ERR_NO_ERROR) { pwd = getpwnam(luser); free(luser); if (pwd != NULL) return (pwd->pw_uid); } /* cannot conver to a local account */ return (0); } static int get_gid(char *group) { struct group *grp; char *lgroup; /* * XXX - this interface will be changed soon to support * multiple gfmds. */ if (gfarm_global_to_local_groupname(group, &lgroup) == GFARM_ERR_NO_ERROR) { grp = getgrnam(lgroup); free(lgroup); if (grp != NULL) return (grp->gr_gid); } /* cannot conver to a local group */ return (0); } static int get_nlink(struct gfs_stat *st) { /* XXX FIXME */ return (GFARM_S_ISDIR(st->st_mode) ? 32000 : st->st_nlink); } static void copy_gfs_stat(/*struct stat*/SMB_STRUCT_STAT *dst, struct gfs_stat *src) { memset(dst, 0, sizeof(*dst)); dst->st_dev = GFS_DEV; dst->st_ino = src->st_ino; dst->st_mode = src->st_mode; dst->st_nlink = get_nlink(src); dst->st_uid = get_uid(src->st_user); dst->st_gid = get_gid(src->st_group); dst->st_size = src->st_size; dst->st_blksize = GFS_BLKSIZE; dst->st_blocks = (src->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; dst->st_atime = src->st_atimespec.tv_sec; dst->st_mtime = src->st_mtimespec.tv_sec; dst->st_ctime = src->st_ctimespec.tv_sec; } static int gfvfs_connect(vfs_handle_struct *handle, const char *service, const char *user) { gfarm_error_t e; (void) handle; (void) service; (void) user; e = gfarm_initialize(0, NULL); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } return 0; } static void gfvfs_disconnect(vfs_handle_struct *handle, connection_struct *conn) { gfarm_error_t e; (void) handle; (void) conn; e = gfarm_terminate(); if(e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return ; } return; } static SMB_BIG_UINT gfvfs_disk_free(vfs_handle_struct *handle, const char *path, BOOL small_query, SMB_BIG_UINT *bsize, SMB_BIG_UINT *dfree, SMB_BIG_UINT *dsize) { (void) handle; (void) path; (void) small_query; (void) bsize; (void) dfree; (void) dsize; return 0; } static int gfvfs_get_quota(vfs_handle_struct *handle, enum SMB_QUOTA_TYPE qtype, unid_t id, SMB_DISK_QUOTA *dq) { (void) handle; (void) qtype; (void) id; (void) dq; return 0; } static int gfvfs_set_quota(vfs_handle_struct *handle, enum SMB_QUOTA_TYPE qtype, unid_t id, SMB_DISK_QUOTA *dq) { (void) handle; (void) qtype; (void) id; (void) dq; return 0; } static int gfvfs_get_shadow_copy_data(vfs_handle_struct *handle, files_struct *fsp, SHADOW_COPY_DATA *shadow_copy_data, BOOL labels) { return 0; } static int gfvfs_statvfs(struct vfs_handle_struct *handle, const char *path, struct vfs_statvfs_struct *statbuf) { (void) handle; (void) path; (void) statbuf; gfarm_error_t e; gfarm_off_t used, avail, files; e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } else { statbuf->BlockSize = 1024; statbuf->TotalBlocks = used + avail; statbuf->BlocksAvail = avail; statbuf->UserBlocksAvail = avail; statbuf->TotalFileNodes = files; statbuf->FreeFileNodes = -1; } return 0; } int dof = 0; static SMB_STRUCT_DIR *gfvfs_opendir(vfs_handle_struct *handle, const char *fname, const char *mask, uint32 attr) { dof = 0; gfarm_error_t e; GFS_Dir dp; e = gfs_opendir_caching(fname, &dp ); if (e != GFARM_ERR_NO_ERROR) { /* gfarm2fs_check_error(2000005, "OPENDIR", "gfs_opendir_caching", fname, e); */ errno = gfarm_error_to_errno(e); return -1; } (void) handle; (void) fname; (void) mask; (void) attr; return (SMB_STRUCT_DIR *)dp; } static SMB_STRUCT_DIRENT *gfvfs_readdir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { GFS_Dir dp = /*get_dirp(fi)*/ (GFS_Dir)dirp; struct gfs_dirent *de; struct stat st; /* gfarm_off_t off = 0; */ gfarm_error_t e; SMB_STRUCT_DIRENT *ssd; ssd = (SMB_STRUCT_DIRENT *)malloc(sizeof(SMB_STRUCT_DIRENT)); if(!ssd){ write(1,"SSD-NULL",strlen("SSD-NULL")); } //(void) path; /* XXX gfs_seekdir(dp, offset); */ e = gfs_readdir(dp, &de); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } if(de!=NULL){ ssd->d_fileno = de->d_fileno; ssd->d_reclen = de->d_reclen; ssd->d_type = de->d_type; ssd->d_off = 0; dof++; strncpy( ssd->d_name, de->d_name, /*256*/sizeof(ssd->d_name)); } else { return(NULL); } return ssd; } static void gfvfs_seekdir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp, long offset) { gfarm_error_t e; GFS_Dir dp = dirp; e = gfs_seekdir(dp, offset); if( e!= GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return ; } static long gfvfs_telldir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { return 0; gfarm_error_t e; long off; e = gfs_telldir(dirp, &off); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return(off); } static void gfvfs_rewinddir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { return 0; } static int gfvfs_mkdir(vfs_handle_struct *handle, const char *path, mode_t mode) { gfarm_error_t e; e = gfs_mkdir(path, mode & GFARM_S_ALLPERM); if( e!= GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_rmdir(vfs_handle_struct *handle, const char *path) { gfarm_error_t e; e = gfs_rmdir(path); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_closedir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dir) { GFS_Dir dp = dir; //DIR = dirp gfarm_error_t e; e = gfs_closedir(dp); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return (0); } static int gfvfs_open(vfs_handle_struct *handle, const char *fname, files_struct *fsp, int flags, mode_t mode) { #ifdef SDEBUG char errtmp[64]; snprintf(errtmp, sizeof(errtmp), "gf2smb: open=%s",fname); write(1, errtmp, strlen(errtmp)); #endif GFS_File gf; int g_flags; char *path; path = fname; gfarm_error_t e; g_flags = gfs_hook_open_flags_gfarmize(flags); if(flags & O_CREAT){ e = gfs_pio_create(fname, g_flags, mode & GFARM_S_ALLPERM, &gf); if( e!= GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } gfs_pio_close(gf); } e = gfs_pio_open(fname, g_flags, &gf); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } fsp->fh->file_id = (unsigned long)gf; return (0); } static int gfvfs_close(vfs_handle_struct *handle, files_struct *fsp, int fd) { gfarm_error_t e; e = gfs_pio_close((GFS_File)fsp->fh->file_id); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return (0); } static ssize_t gfvfs_read(vfs_handle_struct *handle, files_struct *fsp, int fd, void *data, size_t n) { gfarm_error_t e; gfarm_off_t off; int rv; e = gfs_pio_read((GFS_File)fsp->fh->file_id, (char *)data, n, &rv); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return (rv); } static ssize_t gfvfs_pread(vfs_handle_struct *handle, struct files_struct *fsp, int fd, void *data, size_t n, SMB_OFF_T offset) { gfarm_error_t e; gfarm_off_t off; int rv; e = gfs_pio_seek((GFS_File)fsp->fh->file_id, (off_t)offset, GFARM_SEEK_SET, &off); //get_filep(fi) if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } else { e = gfs_pio_read((GFS_File)fsp->fh->file_id, data, n, &rv); } if (e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; rv = 0; } return (rv); } static ssize_t gfvfs_write(vfs_handle_struct *handle, files_struct *fsp, int fd, const void *data, size_t n) { gfarm_error_t e; int rv; e = gfs_pio_write((GFS_File)fsp->fh->file_id, data, n, &rv); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return rv; } ssize_t gfvfs_pwrite(vfs_handle_struct *handle, struct files_struct *fsp, int fd, const void *data, size_t n, SMB_OFF_T offset) { gfarm_error_t e; gfarm_off_t off; int rv; e = gfs_pio_seek((GFS_File)fsp->fh->file_id, offset, GFARM_SEEK_SET, &off); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } else { e = gfs_pio_write((GFS_File)fsp->fh->file_id, data, n, &rv); } if (e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return (rv); } static SMB_OFF_T gfvfs_lseek(vfs_handle_struct *handle, files_struct *fsp, int filedes, SMB_OFF_T offset, int whence) { gfarm_error_t e; gfarm_off_t off; e = gfs_pio_seek((GFS_File)fsp->fh->file_id, offset, GFARM_SEEK_SET, &off); if (e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return off; } static int gfvfs_rename(vfs_handle_struct *handle, const char *oldname, const char *newname) { gfarm_error_t e; e = gfs_rename(oldname, newname); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_fsync(vfs_handle_struct *handle, files_struct *fsp, int fd) { (void) handle; (void) fd; gfarm_error_t e; e = gfs_pio_sync((GFS_File)fsp->fh->file_id); if(e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_stat(vfs_handle_struct *handle, const char *fname, SMB_STRUCT_STAT *sbuf) { struct gfs_stat st; gfarm_error_t e; e = gfs_stat(fname, &st); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } copy_gfs_stat(sbuf, &st); gfs_stat_free(&st); return 0; } static int gfvfs_fstat(vfs_handle_struct *handle, files_struct *fsp, int fd, SMB_STRUCT_STAT *sbuf) { struct gfs_stat st; gfarm_error_t e; e = gfs_pio_stat((GFS_File)fsp->fh->file_id, &st); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } copy_gfs_stat(sbuf, &st); gfs_stat_free(&st); return 0; } static int gfvfs_lstat(vfs_handle_struct *handle, const char *path, SMB_STRUCT_STAT *sbuf) { struct gfs_stat st; gfarm_error_t e; e = gfs_lstat(path, &st); if (e != GFARM_ERR_NO_ERROR) { errno = gfarm_error_to_errno(e); return -1; } copy_gfs_stat(sbuf, &st); gfs_stat_free(&st); return 0; } static int gfvfs_unlink(vfs_handle_struct *handle, const char *path) { gfarm_error_t e; e = gfs_unlink(path); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_chmod(vfs_handle_struct *handle, const char *path, mode_t mode) { gfarm_error_t e;; e = gfs_chmod(path, mode & GFARM_S_ALLPERM); if(e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_fchmod(vfs_handle_struct *handle, files_struct *fsp, int fd, mode_t mode) { return 0; } static int gfvfs_chown(vfs_handle_struct *handle, const char *path, uid_t uid, gid_t gid) { return 0; } static int gfvfs_fchown(vfs_handle_struct *handle, files_struct *fsp, int fd, uid_t uid, gid_t gid) { return 0; } static int gfvfs_chdir(vfs_handle_struct *handle, const char *path) { return 0; } static char *gfvfs_getwd(vfs_handle_struct *handle, char *buf) { return 0; } static int gfvfs_ntimes(vfs_handle_struct *handle, const char *path, const struct timespec ts[2]) { return 0; } static int gfvfs_ftruncate(vfs_handle_struct *handle, files_struct *fsp, int fd, SMB_OFF_T offset) { gfarm_error_t e; e = gfs_pio_truncate((GFS_File)fsp->fh->file_id, /*offset*/0); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static BOOL gfvfs_lock(vfs_handle_struct *handle, files_struct *fsp, int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type) { return 0; } static BOOL gfvfs_getlock(vfs_handle_struct *handle, files_struct *fsp, int fd, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pid_t *ppid) { return 0; } static int gfvfs_symlink(vfs_handle_struct *handle, const char *oldpath, const char *newpath) { gfarm_error_t e; e = gfs_symlink(oldpath, newpath); if( e != GFARM_ERR_NO_ERROR){ errno = gfarm_error_to_errno(e); return -1; } return 0; } static int gfvfs_readlink(vfs_handle_struct *handle, const char *path, char *buf, size_t bufsiz) { return 0; } static int gfvfs_link(vfs_handle_struct *handle, const char *oldpath, const char *newpath) { return 0; } static int gfvfs_mknod(vfs_handle_struct *handle, const char *path, mode_t mode, SMB_DEV_T dev) { return 0; } static char *gfvfs_realpath(vfs_handle_struct *handle, const char *path, char *resolved_path) { return 0; } static NTSTATUS gfvfs_notify_watch(struct vfs_handle_struct *handle, struct sys_notify_context *ctx, struct notify_entry *e, void (*callback)(struct sys_notify_context *ctx, void *private_data, struct notify_event *ev), void *private_data, void *handle_p) { return NT_STATUS_NOT_SUPPORTED; } static int gfvfs_chflags(vfs_handle_struct *handle, const char *path, uint flags) { return 0; } static size_t gfvfs_fget_nt_acl(vfs_handle_struct *handle, files_struct *fsp, int fd, uint32 security_info, SEC_DESC **ppdesc) { return 0; } static size_t gfvfs_get_nt_acl(vfs_handle_struct *handle, files_struct *fsp, const char *name, uint32 security_info, SEC_DESC **ppdesc) { return 0; } static BOOL gfvfs_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, int fd, uint32 security_info_sent, SEC_DESC *psd) { return False; } static BOOL gfvfs_set_nt_acl(vfs_handle_struct *handle, files_struct *fsp, const char *name, uint32 security_info_sent, SEC_DESC *psd) { return False; } static int gfvfs_chmod_acl(vfs_handle_struct *handle, const char *name, mode_t mode) { return 0; } static int gfvfs_fchmod_acl(vfs_handle_struct *handle, files_struct *fsp, int fd, mode_t mode) { return 0; } static int gfvfs_sys_acl_get_entry(vfs_handle_struct *handle, SMB_ACL_T theacl, int entry_id, SMB_ACL_ENTRY_T *entry_p) { return 0; } static int gfvfs_sys_acl_get_tag_type(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d, SMB_ACL_TAG_T *tag_type_p) { return 0; } static int gfvfs_sys_acl_get_permset(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d, SMB_ACL_PERMSET_T *permset_p) { return 0; } static void *gfvfs_sys_acl_get_qualifier(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d) { return NULL; } static SMB_ACL_T gfvfs_sys_acl_get_file(vfs_handle_struct *handle, const char *path_p, SMB_ACL_TYPE_T type) { return NULL; } static SMB_ACL_T gfvfs_sys_acl_get_fd(vfs_handle_struct *handle, files_struct *fsp, int fd) { //errno = ENOSYS; return NULL; } static int gfvfs_sys_acl_clear_perms(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_add_perm(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset, SMB_ACL_PERM_T perm) { //errno = ENOSYS; return 0; } static char *gfvfs_sys_acl_to_text(vfs_handle_struct *handle, SMB_ACL_T theacl, ssize_t *plen) { //errno = ENOSYS; return NULL; } static SMB_ACL_T gfvfs_sys_acl_init(vfs_handle_struct *handle, int count) { //errno = ENOSYS; return NULL; } static int gfvfs_sys_acl_create_entry(vfs_handle_struct *handle, SMB_ACL_T *pacl, SMB_ACL_ENTRY_T *pentry) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_set_tag_type(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, SMB_ACL_TAG_T tagtype) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_set_qualifier(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, void *qual) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_set_permset(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, SMB_ACL_PERMSET_T permset) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_valid(vfs_handle_struct *handle, SMB_ACL_T theacl ) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_set_file(vfs_handle_struct *handle, const char *name, SMB_ACL_TYPE_T acltype, SMB_ACL_T theacl) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_set_fd(vfs_handle_struct *handle, files_struct *fsp, int fd, SMB_ACL_T theacl) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_delete_def_file(vfs_handle_struct *handle, const char *path) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_get_perm(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset, SMB_ACL_PERM_T perm) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_free_text(vfs_handle_struct *handle, char *text) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_free_acl(vfs_handle_struct *handle, SMB_ACL_T posix_acl) { //errno = ENOSYS; return 0; } static int gfvfs_sys_acl_free_qualifier(vfs_handle_struct *handle, void *qualifier, SMB_ACL_TAG_T tagtype) { //errno = ENOSYS; return 0; } static ssize_t gfvfs_getxattr(vfs_handle_struct *handle, const char *path, const char *name, void *value, size_t size) { return 0; } static ssize_t gfvfs_lgetxattr(vfs_handle_struct *handle, const char *path, const char *name, void *value, size_t size) { return 0; } static ssize_t gfvfs_fgetxattr(vfs_handle_struct *handle, struct files_struct *fsp,int fd, const char *name, void *value, size_t size) { return 0; } static ssize_t gfvfs_listxattr(vfs_handle_struct *handle, const char *path, char *list, size_t size) { return 0; } static ssize_t gfvfs_llistxattr(vfs_handle_struct *handle, const char *path, char *list, size_t size) { return 0; } static ssize_t gfvfs_flistxattr(vfs_handle_struct *handle, struct files_struct *fsp,int fd, char *list, size_t size) { return 0; } static int gfvfs_removexattr(vfs_handle_struct *handle, const char *path, const char *name) { return 0; } static int gfvfs_lremovexattr(vfs_handle_struct *handle, const char *path, const char *name) { return 0; } static int gfvfs_fremovexattr(vfs_handle_struct *handle, struct files_struct *fsp,int fd, const char *name) { return 0; } static int gfvfs_setxattr(vfs_handle_struct *handle, const char *path, const char *name, const void *value, size_t size, int flags) { return 0; } static int gfvfs_lsetxattr(vfs_handle_struct *handle, const char *path, const char *name, const void *value, size_t size, int flags) { return 0; } static int gfvfs_fsetxattr(vfs_handle_struct *handle, struct files_struct *fsp,int fd, const char *name, const void *value, size_t size, int flags) { return 0; } static int gfvfs_aio_read(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { return 0; } static int gfvfs_aio_write(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { return 0; } static ssize_t gfvfs_aio_return(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { return 0; } static int gfvfs_aio_cancel(struct vfs_handle_struct *handle, struct files_struct *fsp, int fd, SMB_STRUCT_AIOCB *aiocb) { return 0; } static int gfvfs_aio_error(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { return 0; } static int gfvfs_aio_fsync(struct vfs_handle_struct *handle, struct files_struct *fsp, int op, SMB_STRUCT_AIOCB *aiocb) { return 0; } static int gfvfs_aio_suspend(struct vfs_handle_struct *handle, struct files_struct *fsp, const SMB_STRUCT_AIOCB * const aiocb[], int n, const struct timespec *ts) { return 0; } /* VFS operations structure */ static vfs_op_tuple gfvfs_op_tuples[] = { /* Disk operations */ {SMB_VFS_OP(gfvfs_connect), SMB_VFS_OP_CONNECT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_disconnect), SMB_VFS_OP_DISCONNECT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_disk_free), SMB_VFS_OP_DISK_FREE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_get_quota), SMB_VFS_OP_GET_QUOTA, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_set_quota), SMB_VFS_OP_SET_QUOTA, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_get_shadow_copy_data), SMB_VFS_OP_GET_SHADOW_COPY_DATA,SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_statvfs), SMB_VFS_OP_STATVFS, SMB_VFS_LAYER_OPAQUE}, /* Directory operations */ {SMB_VFS_OP(gfvfs_opendir), SMB_VFS_OP_OPENDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_readdir), SMB_VFS_OP_READDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_seekdir), SMB_VFS_OP_SEEKDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_telldir), SMB_VFS_OP_TELLDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_rewinddir), SMB_VFS_OP_REWINDDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_mkdir), SMB_VFS_OP_MKDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_rmdir), SMB_VFS_OP_RMDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_closedir), SMB_VFS_OP_CLOSEDIR, SMB_VFS_LAYER_OPAQUE}, /* File operations */ {SMB_VFS_OP(gfvfs_open), SMB_VFS_OP_OPEN, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_close), SMB_VFS_OP_CLOSE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_read), SMB_VFS_OP_READ, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_pread), SMB_VFS_OP_PREAD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_write), SMB_VFS_OP_WRITE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_pwrite), SMB_VFS_OP_PWRITE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lseek), SMB_VFS_OP_LSEEK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_rename), SMB_VFS_OP_RENAME, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fsync), SMB_VFS_OP_FSYNC, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_stat), SMB_VFS_OP_STAT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fstat), SMB_VFS_OP_FSTAT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lstat), SMB_VFS_OP_LSTAT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_unlink), SMB_VFS_OP_UNLINK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_chmod), SMB_VFS_OP_CHMOD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fchmod), SMB_VFS_OP_FCHMOD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_chown), SMB_VFS_OP_CHOWN, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fchown), SMB_VFS_OP_FCHOWN, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_chdir), SMB_VFS_OP_CHDIR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_getwd), SMB_VFS_OP_GETWD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_ntimes), SMB_VFS_OP_NTIMES, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_ftruncate), SMB_VFS_OP_FTRUNCATE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lock), SMB_VFS_OP_LOCK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_getlock), SMB_VFS_OP_GETLOCK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_symlink), SMB_VFS_OP_SYMLINK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_readlink), SMB_VFS_OP_READLINK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_link), SMB_VFS_OP_LINK, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_mknod), SMB_VFS_OP_MKNOD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_realpath), SMB_VFS_OP_REALPATH, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_notify_watch), SMB_VFS_OP_NOTIFY_WATCH, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_chflags), SMB_VFS_OP_CHFLAGS, SMB_VFS_LAYER_OPAQUE}, /* NT File ACL operations */ {SMB_VFS_OP(gfvfs_fget_nt_acl), SMB_VFS_OP_FGET_NT_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_get_nt_acl), SMB_VFS_OP_GET_NT_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fset_nt_acl), SMB_VFS_OP_FSET_NT_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_set_nt_acl), SMB_VFS_OP_SET_NT_ACL, SMB_VFS_LAYER_OPAQUE}, /* POSIX ACL operations */ {SMB_VFS_OP(gfvfs_chmod_acl), SMB_VFS_OP_CHMOD_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fchmod_acl), SMB_VFS_OP_FCHMOD_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_entry), SMB_VFS_OP_SYS_ACL_GET_ENTRY, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_tag_type), SMB_VFS_OP_SYS_ACL_GET_TAG_TYPE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_permset), SMB_VFS_OP_SYS_ACL_GET_PERMSET, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_qualifier), SMB_VFS_OP_SYS_ACL_GET_QUALIFIER, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_file), SMB_VFS_OP_SYS_ACL_GET_FILE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_fd), SMB_VFS_OP_SYS_ACL_GET_FD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_clear_perms), SMB_VFS_OP_SYS_ACL_CLEAR_PERMS, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_add_perm), SMB_VFS_OP_SYS_ACL_ADD_PERM, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_to_text), SMB_VFS_OP_SYS_ACL_TO_TEXT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_init), SMB_VFS_OP_SYS_ACL_INIT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_create_entry), SMB_VFS_OP_SYS_ACL_CREATE_ENTRY, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_set_tag_type), SMB_VFS_OP_SYS_ACL_SET_TAG_TYPE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_set_qualifier), SMB_VFS_OP_SYS_ACL_SET_QUALIFIER, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_set_permset), SMB_VFS_OP_SYS_ACL_SET_PERMSET, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_valid), SMB_VFS_OP_SYS_ACL_VALID, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_set_file), SMB_VFS_OP_SYS_ACL_SET_FILE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_set_fd), SMB_VFS_OP_SYS_ACL_SET_FD, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_delete_def_file), SMB_VFS_OP_SYS_ACL_DELETE_DEF_FILE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_get_perm), SMB_VFS_OP_SYS_ACL_GET_PERM, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_free_text), SMB_VFS_OP_SYS_ACL_FREE_TEXT, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_free_acl), SMB_VFS_OP_SYS_ACL_FREE_ACL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_sys_acl_free_qualifier), SMB_VFS_OP_SYS_ACL_FREE_QUALIFIER, SMB_VFS_LAYER_OPAQUE}, /* EA operations. */ {SMB_VFS_OP(gfvfs_getxattr), SMB_VFS_OP_GETXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lgetxattr), SMB_VFS_OP_LGETXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fgetxattr), SMB_VFS_OP_FGETXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_listxattr), SMB_VFS_OP_LISTXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_llistxattr), SMB_VFS_OP_LLISTXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_flistxattr), SMB_VFS_OP_FLISTXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_removexattr), SMB_VFS_OP_REMOVEXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lremovexattr), SMB_VFS_OP_LREMOVEXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fremovexattr), SMB_VFS_OP_FREMOVEXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_setxattr), SMB_VFS_OP_SETXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_lsetxattr), SMB_VFS_OP_LSETXATTR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_fsetxattr), SMB_VFS_OP_FSETXATTR, SMB_VFS_LAYER_OPAQUE}, /* AIO operations. */ {SMB_VFS_OP(gfvfs_aio_read), SMB_VFS_OP_AIO_READ, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_write), SMB_VFS_OP_AIO_WRITE, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_return), SMB_VFS_OP_AIO_RETURN, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_cancel), SMB_VFS_OP_AIO_CANCEL, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_error), SMB_VFS_OP_AIO_ERROR, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_fsync), SMB_VFS_OP_AIO_FSYNC, SMB_VFS_LAYER_OPAQUE}, {SMB_VFS_OP(gfvfs_aio_suspend), SMB_VFS_OP_AIO_SUSPEND, SMB_VFS_LAYER_OPAQUE}, {NULL, SMB_VFS_OP_NOOP, SMB_VFS_LAYER_NOOP} }; NTSTATUS init_module(void) { return smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "gfarm_vfs", gfvfs_op_tuples); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/lib/libgfarm/gfarm/schedule.h /* * */ void gfarm_strings_expand_cyclic(int, char **, int, char **); <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT1-2-3-3_gfsd_warning_and_error #! /bin/sh ###################################################################### TESTID="FT1-2-3-3" CATEGORY="accident causes no failover" SECTION="fsn accident" TITLE="gfsd warning and error" ###################################################################### . ./FT-common ft_setup() { zabbix_sender -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"\sgfsd\[[0-9]+\]:\s+<err>",UTF-8]' -o RECOVERED zabbix_sender -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"\sgfsd\[[0-9]+\]:\s+<warning>",UTF-8]' -o RECOVERED return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfsd1 logger -p $FT_SYSLOG_FACILITY.err \ -t "gfsd[9999]" "\<err\> unknown error" && \ ssh $gfsd1 logger -p $FT_SYSLOG_FACILITY.warning \ -t "gfsd[9999]" "\<warning\> unknown warning" || \ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfsd error message in /var/log/messages on $gfsd1" &&\ ft_check_mail "gfsd warning message in /var/log/messages on $gfsd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT zabbix_sender -v -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"\sgfsd\[[0-9]+\]:\s+<err>",UTF-8]' -o RECOVERED zabbix_sender -v -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"\sgfsd\[[0-9]+\]:\s+<warning>",UTF-8]' -o RECOVERED || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "clear log" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfsd error message in /var/log/messages on $gfsd1" &&\ ft_check_mail "Re: gfsd warning message in /var/log/messages on $gfsd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT3-2-1-2_no_synchronized_slave_and_master_down #! /bin/sh ######################################################################## TESTID="FT3-2-1-2" CATEGORY="N point accident" SECTION="MDS internal accident" TITLE="no synchronized slave gfmd and master gfmd down" ######################################################################## . ./FT-common ft_setup() { JOURNAL_SIZE=50000 N_TRANSACTIONS=`expr $JOURNAL_SIZE / 200` ft_reset_gfmd || return $FT_RESULT_FAIL ./FT-set-journal-size $JOURNAL_SIZE || return $FT_RESULT_FAIL return $FT_RESULT_PASS } ft_main() { GFMD_TIMEOUT=60 R1=$FT_RESULT_PASS $gfservice -t $GFMD_TIMEOUT stop-gfmd gfmd2 \ && $gfservice -t $GFMD_TIMEOUT stop-gfmd gfmd3 \ || R1=$FT_RESULT_FAIL ft_checkpoint 1 "stop all slave gfmd" $R1 [ $R1 -eq $FT_RESULT_PASS ] || return $R1 I=0 TESTDIR="/$TESTID.$$" while [ $I -lt $N_TRANSACTIONS ]; do gfmkdir $TESTDIR gfrmdir $TESTDIR I=`expr $I + 1` done R2=$FT_RESULT_PASS ft_checkpoint 2 "lap a journal file." $R2 [ $R2 -eq $FT_RESULT_PASS ] || return $R2 $gfservice -t $GFMD_TIMEOUT start-gfmd gfmd2 $gfservice -t $GFMD_TIMEOUT start-gfmd gfmd3 R3=$FT_RESULT_PASS ft_checkpoint 3 "start all slave gfmd with timeout $TIMEOUT sec." $R3 [ $R3 -eq $FT_RESULT_PASS ] || return $R3 SLEEP_PERIOD=600 R4=$FT_RESULT_PASS sleep $SLEEP_PERIOD \ || R4=$FT_RESULT_FAIL ft_checkpoint 4 "sleep $SLEEP_PERIOD sec." $R4 [ $R4 -eq $FT_RESULT_PASS ] || return $R4 R5=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || R5=$FT_RESULT_FAIL ft_checkpoint 5 "stop master gfmd on $gfmd1" $R5 [ $R5 -eq $FT_RESULT_PASS ] || return $R5 R6=$FT_RESULT_PASS ft_check_mail "gfmd does not listen on $gfmd1" \ || R6=$FT_RESULT_FAIL ft_checkpoint 6 "receive a mail" $R6 [ $R6 -eq $FT_RESULT_PASS ] || return $R6 return $FT_RESULT_PASS } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/gfarm/gfs_pio_misc.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> /* struct sockaddr */ #include <sys/stat.h> #include <sys/wait.h> #include <sys/time.h> /* for gfs_utime() */ #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "host.h" #include "gfs_proto.h" /* for gfs_digest_calculate_local() */ #include "gfs_client.h" #include "gfs_pio.h" #include "schedule.h" #include "timer.h" #include "gfutil.h" char * gfs_stat_canonical_path(char *gfarm_file, struct gfs_stat *s) { char *e; int i, nsections; struct gfarm_file_section_info *sections; struct gfarm_path_info pi; long ino; e = gfs_get_ino(gfarm_file, &ino); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) return (e); *s = pi.status; s->st_ino = ino; s->st_user = strdup(s->st_user); s->st_group = strdup(s->st_group); gfarm_path_info_free(&pi); if (s->st_user == NULL || s->st_group == NULL) { gfs_stat_free(s); return (GFARM_ERR_NO_MEMORY); } if (!GFARM_S_ISREG(s->st_mode)) return (NULL); /* regular file */ e = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); if (e != NULL) { gfs_stat_free(s); /* * If GFARM_ERR_NO_SUCH_OBJECT is returned here, * gfs_stat() incorrectly assumes that this is a directory, * and reports GFARM_ERR_NOT_A_DIRECTORY. */ return (GFARM_ERR_NO_FRAGMENT_INFORMATION); } s->st_size = 0; for (i = 0; i < nsections; i++) s->st_size += sections[i].filesize; s->st_nsections = nsections; gfarm_file_section_info_free_all(nsections, sections); return (NULL); } double gfs_stat_time; char * gfs_stat(const char *path, struct gfs_stat *s) { char *e, *p; gfarm_timerval_t t1, t2; long ino; gfs_profile(gfarm_gettimerval(&t1)); path = gfarm_url_prefix_skip(path); e = gfarm_canonical_path(path, &p); if (e != NULL) goto finish; e = gfs_stat_canonical_path(p, s); if (e == NULL) goto finish_free_p; if (e != GFARM_ERR_NO_SUCH_OBJECT) goto finish_free_p; /* * XXX - assume that it's a directory that does not have the * path info. */ e = gfs_get_ino(p, &ino); if (e != NULL) goto finish_free_p; s->st_ino = ino; s->st_mode = GFARM_S_IFDIR | 0777; s->st_user = strdup("root"); s->st_group = strdup("gfarm"); s->st_atimespec.tv_sec = 0; s->st_atimespec.tv_nsec = 0; s->st_mtimespec.tv_sec = 0; s->st_mtimespec.tv_nsec = 0; s->st_ctimespec.tv_sec = 0; s->st_ctimespec.tv_nsec = 0; s->st_size = 0; s->st_nsections = 0; e = NULL; finish_free_p: free(p); finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_stat_time += gfarm_timerval_sub(&t2, &t1)); return (e); } void gfs_stat_free(struct gfs_stat *s) { if (s->st_user != NULL) free(s->st_user); if (s->st_group != NULL) free(s->st_group); } char * gfs_stat_section(const char *gfarm_url, const char *section, struct gfs_stat *s) { char *e, *gfarm_file; struct gfarm_file_section_info sinfo; struct gfarm_path_info pi; long ino; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfs_get_ino(gfarm_file, &ino); if (e != NULL) { free(gfarm_file); return (e); } e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } *s = pi.status; s->st_ino = ino; s->st_user = strdup(s->st_user); s->st_group = strdup(s->st_group); gfarm_path_info_free(&pi); if (!GFARM_S_ISREG(s->st_mode)) { free(gfarm_file); return (NULL); } e = gfarm_file_section_info_get(gfarm_file, section, &sinfo); free(gfarm_file); if (e != NULL) return (e); s->st_size = sinfo.filesize; s->st_nsections = 1; gfarm_file_section_info_free(&sinfo); return (NULL); } char * gfs_stat_index(char *gfarm_url, int index, struct gfs_stat *s) { char section[GFARM_INT32STRLEN + 1]; sprintf(section, "%d", index); return (gfs_stat_section(gfarm_url, section, s)); } char * gfs_fstat(GFS_File gf, struct gfs_stat *status) { return ((*gf->ops->view_stat)(gf, status)); } char * gfs_access(const char *gfarm_url, int mode) { char *e, *gfarm_file; struct gfarm_path_info pi; gfarm_mode_t stat_mode; int stat_nsections, nsections; struct gfarm_file_section_info *sections; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } stat_mode = pi.status.st_mode; stat_nsections = pi.status.st_nsections; e = gfarm_path_info_access(&pi, mode); gfarm_path_info_free(&pi); if (e != NULL) { free(gfarm_file); return (e); } if (GFARM_S_ISDIR(stat_mode)) { free(gfarm_file); return (NULL); } /* * Check all fragments are ready or not. * XXX - is this check necessary? */ e = gfarm_file_section_info_get_all_by_file( gfarm_file, &nsections, &sections); free(gfarm_file); if (e != NULL) return (e); gfarm_file_section_info_free_all(nsections, sections); if (!GFARM_S_IS_PROGRAM(stat_mode) && nsections != stat_nsections) e = GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH; return (e); } static char * change_path_info_mode(struct gfarm_path_info *p, gfarm_mode_t mode) { p->status.st_mode &= ~GFARM_S_ALLPERM; p->status.st_mode |= (mode & GFARM_S_ALLPERM); return (gfarm_path_info_replace(p->pathname, p)); } enum exec_change { EXECUTABILITY_NOT_CHANGED, TO_EXECUTABLE, TO_NONEXECUTABLE }; static char * change_path_info_mode_nsections( struct gfarm_path_info *p, gfarm_mode_t mode, enum exec_change change) { switch (change) { case TO_EXECUTABLE: p->status.st_nsections = 0; break; case TO_NONEXECUTABLE: p->status.st_nsections = 1; break; default: break; } return (change_path_info_mode(p, mode)); } static enum exec_change diff_exec(gfarm_mode_t old, gfarm_mode_t new) { gfarm_mode_t xmask = 0111; if ((old & xmask) == 0 && (new & xmask) != 0) return (TO_EXECUTABLE); else if ((old & xmask) != 0 && (new & xmask) == 0) return (TO_NONEXECUTABLE); else return (EXECUTABILITY_NOT_CHANGED); } static char * get_architecture_name(int ncopy, struct gfarm_file_section_copy_info *copies) { /* XXX - this selection of architecture is stopgap. */ char *e, *hostname; int i; e = gfarm_host_get_canonical_self_name(&hostname); if (e != NULL) hostname = copies[0].hostname; for (i = 0; i < ncopy; i++) if (strcmp(copies[i].hostname, hostname) == 0) break; if (i >= ncopy) hostname = copies[0].hostname; return gfarm_host_info_get_architecture_by_host(hostname); } struct gfs_chmod_args { char *path; gfarm_mode_t mode; }; static char * chmod_dir_request_parallel(struct gfs_connection *gfs_server, void *args) { struct gfs_chmod_args *a = args; char *e; /* * XXX - Not to issue a error message "no such object" for directory. * A directory in spool is created on demand, so generally it * does not exist in spool though its meta data exits. */ e = gfs_client_chmod(gfs_server, a->path, a->mode); if (e == GFARM_ERR_NO_SUCH_OBJECT) e = NULL; return (e); } static char * get_new_section_name(enum exec_change change, int ncopy, struct gfarm_file_section_copy_info *copies) { if (change == TO_EXECUTABLE) return get_architecture_name(ncopy, copies); else /* change == TO_NONEXECUTABLE */ return strdup("0"); } static char * gfs_chmod_execfile_metadata( struct gfarm_path_info *pi, gfarm_mode_t mode, struct gfarm_file_section_info *from_section, int ncopy, struct gfarm_file_section_copy_info *copies, enum exec_change change) { struct gfarm_file_section_info to_section; char *e; int i; to_section = *from_section; to_section.section = get_new_section_name(change, ncopy, copies); if (to_section.section == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_file_section_info_set(to_section.pathname, to_section.section, &to_section); if (e != NULL) goto finish_free_to_section_section; e = change_path_info_mode_nsections(pi, mode, change); if (e != NULL) { char *e2; e2 = gfarm_file_section_info_remove( to_section.pathname, to_section.section); gflog_warning("gfs_chmod: gfarm_file_section_info_remove()", e2); goto finish_free_to_section_section; } for (i = 0; i < ncopy; i++) { e = gfarm_file_section_copy_info_remove(copies[i].pathname, copies[i].section, copies[i].hostname); if (e != NULL) gflog_warning( "gfs_chmod:gfarm_file_section_copy_info_remove()", e); } e = gfarm_file_section_info_remove(from_section->pathname, from_section->section); if (e != NULL) gflog_warning("gfs_chmod:gfarm_file_section_info_remove()", e); finish_free_to_section_section: free(to_section.section); return(e); } static char * gfs_chmod_file_spool( gfarm_mode_t mode, int nsection, struct gfarm_file_section_info *sections, int *ncopy, struct gfarm_file_section_copy_info **copies, enum exec_change change) { int i, j; char *e; char *from_path_section, *to_path_section; struct gfarm_file_section_copy_info new_copy; for (i = 0; i < nsection; i++) { char *section; e = gfarm_path_section(sections[i].pathname, sections[i].section, &from_path_section); if (e != NULL) return (e); section = get_new_section_name( change, ncopy[i], copies[i]); if (section == NULL) { free(from_path_section); return (GFARM_ERR_NO_MEMORY); } e = gfarm_path_section(sections[i].pathname, section, &to_path_section); if (e != NULL) { free(section); free(from_path_section); return (e); } for (j = 0; j < ncopy[i]; j++) { struct gfs_connection *gfs_server; struct sockaddr peer_addr; e = gfarm_host_address_get(copies[i][j].hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { gflog_warning( "gfs_chmod:gfarm_host_address_get()", e); continue; } e = gfs_client_connect(copies[i][j].hostname, &peer_addr, &gfs_server); if (e != NULL) { gflog_warning( "gfs_chmod:gfarm_client_connection()", e); continue; } e = gfs_client_chmod(gfs_server, from_path_section, mode); if (e != NULL) { gflog_warning("gfs_chmod:gfs_client_chmod()", e); gfs_client_disconnect(gfs_server); continue; } if (change != EXECUTABILITY_NOT_CHANGED) { e = gfs_client_rename(gfs_server, from_path_section, to_path_section); if (e != NULL) { gflog_warning( "gfs_chmod:gfs_client_rename()", e); gfs_client_disconnect(gfs_server); continue; } new_copy = copies[i][j]; new_copy.section = section; e = gfarm_file_section_copy_info_set( new_copy.pathname, new_copy.section, new_copy.hostname, &new_copy); if (e != NULL) { gflog_warning( "gfs_chmod:" "gfarm_file_section_copy_info_set()", e); } } gfs_client_disconnect(gfs_server); } free(to_path_section); free(section); free(from_path_section); } return (NULL); } static char * gfs_chmod_internal(struct gfarm_path_info *pi, gfarm_mode_t mode) { char *e; int nsection, *ncopy, i; struct gfarm_file_section_info *sections; struct gfarm_file_section_copy_info **copies; enum exec_change change; if (strcmp(pi->status.st_user, gfarm_get_global_username()) != 0) { return (GFARM_ERR_OPERATION_NOT_PERMITTED); } if (GFARM_S_ISDIR(pi->status.st_mode)) { struct gfs_chmod_args a; int nhosts_succeed; e = change_path_info_mode(pi, mode); if (e != NULL) return (e); a.path = pi->pathname; a.mode = mode; e = gfs_client_apply_all_hosts(chmod_dir_request_parallel, &a, "gfs_chmod", 1, &nhosts_succeed); return (e); } e = gfarm_file_section_info_get_all_by_file(pi->pathname, &nsection, &sections); if (e != NULL) return (e); change = diff_exec(pi->status.st_mode, mode); if (change != EXECUTABILITY_NOT_CHANGED && nsection > 1) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto finish_free_section_info; } ncopy = malloc(nsection * sizeof(*ncopy)); if (ncopy == NULL) goto finish_free_section_info; copies = malloc(nsection * sizeof(*copies)); if (copies == NULL) goto finish_free_ncopy; for (i = 0; i < nsection; i++) { e = gfarm_file_section_copy_info_get_all_by_section( sections[i].pathname, sections[i].section, &ncopy[i], &copies[i]); if (e != NULL) { while (i--) gfarm_file_section_copy_info_free_all( ncopy[i], copies[i]); goto finish_free_copies; } } if (change == EXECUTABILITY_NOT_CHANGED) { e = change_path_info_mode(pi, mode); } else { e = gfs_chmod_execfile_metadata(pi, mode, &sections[0], ncopy[0], copies[0], change); } if (e != NULL) goto finish_free_section_copy_info; e = gfs_chmod_file_spool(mode, nsection, sections, ncopy, copies, change); finish_free_section_copy_info: for (i = 0; i < nsection; i++) gfarm_file_section_copy_info_free_all(ncopy[i], copies[i]); finish_free_copies: free(copies); finish_free_ncopy: free(ncopy); finish_free_section_info: gfarm_file_section_info_free_all(nsection, sections); return (e); } char * gfs_chmod(const char *gfarm_url, gfarm_mode_t mode) { char *e, *gfarm_file; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); free(gfarm_file); if (e != NULL) return (e); e = gfs_chmod_internal(&pi, mode); gfarm_path_info_free(&pi); return (e); } char * gfs_fchmod(GFS_File gf, gfarm_mode_t mode) { return (gfs_chmod_internal(&gf->pi, mode)); } char * gfs_utimes(const char *gfarm_url, const struct gfarm_timespec *tsp) { char *e, *gfarm_file; struct gfarm_path_info pi; struct timeval now; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); free(gfarm_file); if (e != NULL) return (e); if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) goto finish_free_path_info; gettimeofday(&now, NULL); if (tsp == NULL) { pi.status.st_atimespec.tv_sec = pi.status.st_mtimespec.tv_sec = now.tv_sec; pi.status.st_atimespec.tv_nsec = pi.status.st_mtimespec.tv_nsec = now.tv_usec * 1000; } else { pi.status.st_atimespec = tsp[0]; pi.status.st_mtimespec = tsp[1]; } pi.status.st_ctimespec.tv_sec = now.tv_sec; pi.status.st_ctimespec.tv_nsec = now.tv_usec * 1000; e = gfarm_path_info_replace(pi.pathname, &pi); finish_free_path_info: gfarm_path_info_free(&pi); return (e); } static char * gfs_rename_clean_spool( char *pathname, int nsection, struct gfarm_file_section_info *sections, int *ncopy, struct gfarm_file_section_copy_info **copies) { char *e, *e2, *path_section; int i, j; struct gfs_connection *gfs_server; struct sockaddr peer_addr; for (i = 0; i < nsection; i++) { e = gfarm_path_section(pathname, sections[i].section, &path_section); if (e != NULL) return (e); for (j = 0; j < ncopy[i]; j++) { e2 = gfarm_host_address_get(copies[i][j].hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e2 != NULL) continue; e2 = gfs_client_connect(copies[i][j].hostname, &peer_addr, &gfs_server); if (e2 != NULL) continue; e2 = gfs_client_unlink(gfs_server, path_section); gfs_client_disconnect(gfs_server); } free(path_section); } return (NULL); } static char * gfs_rename_file_spool( char *from_pathname, char *to_pathname, int nsection, struct gfarm_file_section_info *sections, int *ncopy, struct gfarm_file_section_copy_info **copies) { int i, j, ok; char *e, *e2; char *from_path_section, *to_path_section; struct gfarm_file_section_copy_info new_copy; struct gfs_connection *gfs_server; struct sockaddr peer_addr; e = NULL; ok = 1; for (i = 0; i < nsection; i++) { e = gfarm_path_section(sections[i].pathname, sections[i].section, &from_path_section); if (e != NULL) return (e); /* XXX this leaves inconsistent state */ e = gfarm_path_section(to_pathname, sections[i].section, &to_path_section); if (e != NULL) { free(from_path_section); return (e); /* XXX this leaves inconsistent state */ } ok = 0; for (j = 0; j < ncopy[i]; j++) { e = gfarm_host_address_get(copies[i][j].hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { gflog_warning("gfs_rename_file_spool:" "gfarm_host_address_get()", e); continue; } e = gfs_client_connect(copies[i][j].hostname, &peer_addr, &gfs_server); if (e != NULL) { gflog_warning("gfs_rename_file_spool:" "gfarm_client_connect()", e); continue; } e = gfs_client_link(gfs_server, from_path_section, to_path_section); if (e == GFARM_ERR_NO_SUCH_OBJECT) { if (gfs_pio_remote_mkdir_parent_canonical_path( gfs_server, to_path_section) == NULL) e = gfs_client_link(gfs_server, from_path_section, to_path_section); } gfs_client_disconnect(gfs_server); if (e != NULL) { gflog_warning("gfs_rename_file_spool:" "gfarm_client_link()", e); continue; } new_copy = copies[i][j]; new_copy.pathname = to_pathname; e = gfarm_file_section_copy_info_set(new_copy.pathname, new_copy.section, new_copy.hostname, &new_copy); if (e != NULL) { gflog_warning("gfs_rename_file_spool:" "gfarm_file_section_copy_info_set()", e); continue; } ok = 1; } if (j == 0) /* this section has no section copy info */ ok = 1; free(to_path_section); free(from_path_section); if (!ok) /* none of copies of this section can be renamed */ break; } if (ok) { /* unlink old spool file */ e2 = gfs_rename_clean_spool(from_pathname, nsection, sections, ncopy, copies); if (e2 != NULL) gflog_warning("gfs_rename_file_spool:" "gfs_rename_clean_spool(from_pathname)", e2); } else { /* remove new section copy info and new spool file */ e2 = gfs_rename_clean_spool(to_pathname, nsection, sections, ncopy, copies); } return (e); } static char * gfs_rename_file(struct gfarm_path_info *from_pi, const char *to_url) { char *e, *e2, *gfarm_file; struct gfarm_path_info to_pi; int i, nsection, *ncopy; struct gfarm_file_section_info *sections; struct gfarm_file_section_copy_info **copies; e = gfarm_url_make_path_for_creation(to_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &to_pi); if (e != NULL && e != GFARM_ERR_NO_SUCH_OBJECT) goto finish_free_gfarm_file; if (e == NULL) { /* "to" side file or directory exists */ if (GFARM_S_ISDIR(to_pi.status.st_mode)) { e = GFARM_ERR_IS_A_DIRECTORY; gfarm_path_info_free(&to_pi); goto finish_free_gfarm_file; } gfarm_path_info_free(&to_pi); e = gfs_unlink(to_url); if (e != NULL) goto finish_free_gfarm_file; } /* set "to" path info and section info */ to_pi = *from_pi; to_pi.pathname = gfarm_file; e = gfarm_path_info_set(to_pi.pathname, &to_pi); if (e != NULL) goto finish_free_gfarm_file; e = gfarm_file_section_info_get_all_by_file(from_pi->pathname, &nsection, &sections); if (e != NULL) goto finish_free_gfarm_file; for (i = 0; i < nsection; i++) { struct gfarm_file_section_info to_section; to_section = sections[i]; to_section.pathname = to_pi.pathname; e = gfarm_file_section_info_set(to_section.pathname, to_section.section, &to_section); if (e != NULL) { while (i--) { e2 = gfarm_file_section_info_remove( to_section.pathname, sections[i].section); if (e2 != NULL) gflog_warning("gfs_rename_file" "gfarm_file_section_info_remove()", e); } e2 = gfarm_path_info_remove(to_pi.pathname); if (e2 != NULL) gflog_warning("gfs_rename_file:" "gfarm_path_info_remove()", e); goto finish_free_section_info; } } ncopy = malloc(nsection * sizeof(*ncopy)); if (ncopy == NULL) goto finish_free_section_info; copies = malloc(nsection * sizeof(*copies)); if (copies == NULL) goto finish_free_ncopy; for (i = 0; i < nsection; i++) { e = gfarm_file_section_copy_info_get_all_by_section( sections[i].pathname, sections[i].section, &ncopy[i], &copies[i]); if (e != NULL) { while (i--) gfarm_file_section_copy_info_free_all( ncopy[i], copies[i]); goto finish_free_copies; } } /* change spool file name and set section copy info */ e = gfs_rename_file_spool(from_pi->pathname, to_pi.pathname, nsection, sections, ncopy, copies); if (e != NULL) { e2 = gfarm_file_section_copy_info_remove_all_by_file( to_pi.pathname); for (i = 0; i < nsection; i++) { e2 = gfarm_file_section_info_remove(to_pi.pathname, sections[i].section); if (e2 != NULL) gflog_warning("gfs_rename_file:" "gfarm_file_section_info_remove()", e2); } e2 = gfarm_path_info_remove(to_pi.pathname); if (e2 != NULL) gflog_warning("gfs_rename_file:" "gfarm_path_info_remove()", e2); } else { e = gfarm_file_section_copy_info_remove_all_by_file( from_pi->pathname); for (i = 0; i < nsection; i++) { e2 = gfarm_file_section_info_remove( sections[i].pathname, sections[i].section); if (e2 != NULL) gflog_warning("gfs_rename_file:" "gfarm_file_section_info_remove()", e2); if (e == NULL && e2 != NULL) e = e2; } e2 = gfarm_path_info_remove(from_pi->pathname); if (e2 != NULL) gflog_warning("gfs_rename_file:" "gfarm_file_path_info_remove()", e2); if (e == NULL && e2 != NULL) e = e2; } for (i = 0; i < nsection; i++) gfarm_file_section_copy_info_free_all(ncopy[i], copies[i]); finish_free_copies: free(copies); finish_free_ncopy: free(ncopy); finish_free_section_info: gfarm_file_section_info_free_all(nsection, sections); finish_free_gfarm_file: free(gfarm_file); return (e); } static char * gfs_rename_dir(struct gfarm_path_info *from_pi, const char *to_url) { return (GFARM_ERR_OPERATION_NOT_SUPPORTED); } char * gfs_rename(const char *from_url, const char *to_url) { char *e, *gfarm_file; struct gfarm_path_info from_pi; e = gfarm_url_make_path_for_creation(from_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &from_pi); free(gfarm_file); if (e != NULL) return (e); if (GFARM_S_ISREG(from_pi.status.st_mode)) e = gfs_rename_file(&from_pi, to_url); else if (GFARM_S_ISDIR(from_pi.status.st_mode)) e = gfs_rename_dir(&from_pi, to_url); else e = GFARM_ERR_OPERATION_NOT_SUPPORTED; gfarm_path_info_free(&from_pi); return (e); } /* * */ static char * digest_calculate(char *filename, char **digest_type, char *digest_string, size_t *md_len_p, file_offset_t *filesizep) { int fd, i, rv; EVP_MD_CTX md_ctx; unsigned char md_value[EVP_MAX_MD_SIZE]; char buffer[GFS_FILE_BUFSIZE]; if ((fd = open(filename, O_RDONLY)) == -1) return (gfarm_errno_to_error(errno)); EVP_DigestInit(&md_ctx, GFS_DEFAULT_DIGEST_MODE); rv = gfs_digest_calculate_local( fd, buffer, GFS_FILE_BUFSIZE, GFS_DEFAULT_DIGEST_MODE, &md_ctx, md_len_p, md_value, filesizep); close(fd); if (rv != 0) return (gfarm_errno_to_error(rv)); for (i = 0; i < *md_len_p; i++) sprintf(&digest_string[i + i], "%02x", md_value[i]); *digest_type = GFS_DEFAULT_DIGEST_NAME; return (NULL); } /* * Register a gfarm fragment to a Meta DB. This function is intended * to be used with legacy applications to register a new file. */ char * gfs_pio_set_fragment_info_local(char *filename, char *gfarm_file, char *section) { char *digest_type; char digest_value_string[EVP_MAX_MD_SIZE * 2 + 1]; size_t digest_len; file_offset_t filesize; char *e = NULL; struct gfarm_file_section_info fi; struct gfarm_file_section_copy_info fci; /* Calculate checksum. */ e = digest_calculate(filename, &digest_type, digest_value_string, &digest_len, &filesize); if (e != NULL) return (e); /* Update the filesystem metadata. */ e = gfarm_file_section_info_get(gfarm_file, section, &fi); if (e == GFARM_ERR_NO_SUCH_OBJECT) { fi.filesize = filesize; fi.checksum_type = digest_type; fi.checksum = digest_value_string; e = gfarm_file_section_info_set(gfarm_file, section, &fi); if (e != NULL) return (e); } else if (e == NULL) { if (fi.filesize != filesize) return "file size mismatch"; if (strcasecmp(fi.checksum_type, digest_type) != 0) return "checksum type mismatch"; if (strcasecmp(fi.checksum,digest_value_string) != 0) return "check sum mismatch"; gfarm_file_section_info_free(&fi); } else return (e); e = gfarm_host_get_canonical_self_name(&fci.hostname); if (e == NULL) { e = gfarm_file_section_copy_info_set( gfarm_file, section, fci.hostname, &fci); } return (e); } static char * gfarm_file_section_replicate_from_to_by_gfrepbe( char *gfarm_file, char *section, char *srchost, char *dsthost) { char *e; char *e2; gfarm_stringlist gfarm_file_list; gfarm_stringlist section_list; e = gfarm_stringlist_init(&gfarm_file_list); if (e != NULL) return (e); e = gfarm_stringlist_init(&section_list); if (e != NULL) { gfarm_stringlist_free(&gfarm_file_list); return (e); } e = gfarm_stringlist_add(&gfarm_file_list, gfarm_file); e2 = gfarm_stringlist_add(&section_list, section); if (e == NULL && e2 == NULL) { e = gfarm_file_section_replicate_multiple( &gfarm_file_list, &section_list, srchost, dsthost, &e2); } gfarm_stringlist_free(&gfarm_file_list); gfarm_stringlist_free(&section_list); return (e != NULL ? e : e2); } /* * 0: use gfrepbe_client/gfrepbe_server * 1: use gfs_client_bootstrap_replicate_file() */ #if 0 /* XXX for now */ static int gfarm_replication_method = GFARM_REPLICATION_NORMAL_METHOD; #else static int gfarm_replication_method = GFARM_REPLICATION_BOOTSTRAP_METHOD; #endif int gfarm_replication_get_method(void) { return (gfarm_replication_method); } void gfarm_replication_set_method(int method) { gfarm_replication_method = method; } /* * `srchost' must already reflect "address_use" directive. */ static char * gfarm_file_section_replicate_from_to_internal( char *gfarm_file, char *section, gfarm_mode_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname, char *dsthost) { char *e, *path_section; struct gfarm_file_section_copy_info ci; struct gfs_connection *gfs_server; struct sockaddr peer_addr; e = gfarm_host_get_canonical_name(dsthost, &ci.hostname); if (e != NULL) goto finish; if (gfarm_file_section_copy_info_does_exist(gfarm_file, section, ci.hostname)) /* already exists, don't have to replicate */ goto finish_hostname; if (gfarm_replication_method != GFARM_REPLICATION_BOOTSTRAP_METHOD) { e = gfarm_file_section_replicate_from_to_by_gfrepbe( gfarm_file, section, src_canonical_hostname, ci.hostname); goto finish_hostname; } e = gfarm_path_section(gfarm_file, section, &path_section); if (e != NULL) goto finish_hostname; e = gfarm_host_address_get(dsthost, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) goto finish_path_section; e = gfs_client_connect(ci.hostname, &peer_addr, &gfs_server); if (e != NULL) goto finish_path_section; e = gfs_client_bootstrap_replicate_file(gfs_server, path_section, mode, file_size, src_canonical_hostname, src_if_hostname); /* FT - the parent directory of the destination may be missing */ if (e == GFARM_ERR_NO_SUCH_OBJECT) { if (gfs_pio_remote_mkdir_parent_canonical_path( gfs_server, gfarm_file) == NULL) e = gfs_client_bootstrap_replicate_file( gfs_server, path_section, mode, file_size, src_canonical_hostname, src_if_hostname); } #if 0 /* XXX - not implemented yet */ /* FT - source file should be missing */ if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* XXX - need to check explicitly */ if (gfs_client_exist() == GFARM_ERR_NO_SUCH_OBJECT) /* Delete the section copy info */ if (gfarm_file_section_copy_info_remove(gfarm_file, section, src_canonical_hostname) == NULL) e = GFARM_ERR_INCONSISTENT_RECOVERABLE; } #endif gfs_client_disconnect(gfs_server); if (e != NULL) goto finish_path_section; e = gfarm_file_section_copy_info_set(gfarm_file, section, ci.hostname, &ci); finish_path_section: free(path_section); finish_hostname: free(ci.hostname); finish: return (e); } static char * gfarm_file_section_replicate_to_internal(char *gfarm_file, char *section, gfarm_mode_t mode, file_offset_t file_size, char *dsthost) { char *e, *srchost, *if_hostname; struct sockaddr peer_addr; e = gfarm_file_section_host_schedule(gfarm_file, section, &srchost); if (e != NULL) goto finish; /* reflect "address_use" directive in the `srchost' */ e = gfarm_host_address_get(srchost, gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_srchost; e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section, mode & GFARM_S_ALLPERM, file_size, srchost, if_hostname, dsthost); free(if_hostname); finish_srchost: free(srchost); finish: return (e); } char * gfarm_url_section_replicate_from_to(const char *gfarm_url, char *section, char *srchost, char *dsthost) { char *e, *gfarm_file, *canonical_hostname, *if_hostname; struct sockaddr peer_addr; struct gfarm_path_info pi; struct gfarm_file_section_info si; gfarm_mode_t mode_allowed = 0, mode_mask = GFARM_S_ALLPERM; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish; e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; e = gfarm_file_section_info_get(gfarm_file, section, &si); if (e != NULL) goto finish_path_info; e = gfarm_host_get_canonical_name(srchost, &canonical_hostname); if (e != NULL) goto finish_canonical_hostname; /* reflect "address_use" directive in the `srchost' */ e = gfarm_host_address_get(srchost, gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_section_info; /* * XXX - if the owner of a file is not the same, permit a * group/other write access - This should be fixed in the next * major release. */ if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) { e = gfarm_path_info_access(&pi, GFS_R_OK); if (e != NULL) goto finish_path_info; mode_allowed = 022; mode_mask = 0777; /* don't allow setuid/setgid */ } e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section, (pi.status.st_mode | mode_allowed) & mode_mask, si.filesize, canonical_hostname, if_hostname, dsthost); free(if_hostname); finish_canonical_hostname: free(canonical_hostname); finish_section_info: gfarm_file_section_info_free(&si); finish_path_info: gfarm_path_info_free(&pi); finish_gfarm_file: free(gfarm_file); finish: return (e); } char * gfarm_url_section_replicate_to( const char *gfarm_url, char *section, char *dsthost) { char *e, *gfarm_file; struct gfarm_path_info pi; struct gfarm_file_section_info si; gfarm_mode_t mode_allowed = 0, mode_mask = GFARM_S_ALLPERM; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish; e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; e = gfarm_file_section_info_get(gfarm_file, section, &si); if (e != NULL) goto finish_path_info; /* * XXX - if the owner of a file is not the same, permit a * group/other write access - This should be fixed in the next * major release. */ if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) { e = gfarm_path_info_access(&pi, GFS_R_OK); if (e != NULL) goto finish_path_info; mode_allowed = 022; mode_mask = 0777; /* don't allow setuid/setgid */ } e = gfarm_file_section_replicate_to_internal( gfarm_file, section, (pi.status.st_mode | mode_allowed) & mode_mask, si.filesize, dsthost); gfarm_file_section_info_free(&si); finish_path_info: gfarm_path_info_free(&pi); finish_gfarm_file: free(gfarm_file); finish: return (e); } char * gfarm_url_program_register( const char *gfarm_url, char *architecture, char *filename, int nreplicas) { char *e, *e_save = NULL, *if_hostname, *gfarm_file; int nhosts, fd, i; struct gfarm_host_info *hosts; struct sockaddr peer_addr; size_t rv; int length; /* XXX - should be size_t */ GFS_File gf; struct stat s; char buffer[GFS_FILE_BUFSIZE]; char *self_name; char **hostnames; if (stat(filename, &s) == -1) return (gfarm_errno_to_error(errno)); if (!GFARM_S_IS_PROGRAM(s.st_mode)) return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* XXX - use better strategy for the replication */ e = gfarm_host_info_get_allhost_by_architecture(architecture, &nhosts, &hosts); if (e == GFARM_ERR_NO_SUCH_OBJECT) return ("gfarm_url_program_register(): no such architecture"); if (e != NULL) goto finish; hostnames = malloc(sizeof(char *) * nhosts); if (hostnames == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_host_info; } for (i = 0; i < nhosts; i++) hostnames[i] = hosts[i].hostname; if (nhosts < nreplicas) nreplicas = nhosts; if (gfarm_host_get_canonical_self_name(&self_name) != NULL) { e = gfarm_schedule_search_idle_hosts(nhosts, hostnames, nreplicas, hostnames); } else { /* give the top priority to self host */ char * tmp; for (i = 0; i < nhosts; i++) if (strcmp(hostnames[i], self_name) == 0) break; if (i != 0 && i < nhosts) { tmp = hostnames[0]; hostnames[0] = hostnames[i]; hostnames[i] = tmp; } if (nreplicas > 1) e = gfarm_schedule_search_idle_hosts(nhosts - 1, hostnames + 1, nreplicas - 1, hostnames + 1); } if (e != NULL) goto finish_hostnames; /* reflect "address_use" directive in the `hostnames[0]' */ e = gfarm_host_address_get(hostnames[0], gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_hostnames; /* * register the program */ fd = open(filename, O_RDONLY); if (fd == -1) { e = "gfarm_url_program_register(): can't open program"; goto finish_if_hostname; } /* XXX - overwrite case */ e = gfs_pio_create(gfarm_url, GFARM_FILE_WRONLY, s.st_mode & GFARM_S_ALLPERM, &gf); if (e != NULL) { close(fd); goto finish_if_hostname; } /* XXX - better strategy to select replica */ e = gfs_pio_set_view_section(gf, architecture, if_hostname, 0); if (e != NULL) { /* XXX - take care of the case where node is down */ gfs_pio_close(gf); close(fd); goto finish_if_hostname; } for (;;) { rv = read(fd, buffer, sizeof(buffer)); if (rv <= 0) break; /* XXX - partial write case ? */ e = gfs_pio_write(gf, buffer, rv, &length); if (e != NULL) break; } e_save = e; e = gfs_pio_close(gf); close(fd); if (e_save != NULL) e = e_save; if (e != NULL) goto finish_if_hostname; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish_if_hostname; /* * replicate the program */ for (i = 1; i < nreplicas; i++) { /* XXX - better strategy to select replica */ e = gfarm_file_section_replicate_from_to_internal( gfarm_file, architecture, s.st_mode & GFARM_S_ALLPERM, s.st_size, hostnames[0], if_hostname, hostnames[i]); if (e != NULL) e_save = e; } e = NULL; /* there is at least on copy available. */ /* XXX - partial error case? */ free(gfarm_file); finish_if_hostname: free(if_hostname); finish_hostnames: free(hostnames); finish_host_info: gfarm_host_info_free_all(nhosts, hosts); finish: return (e); } char * gfarm_url_program_deliver(const char *gfarm_url, int nhosts, char **hosts, char ***delivered_paths) { char *e, **dp, *gfarm_file, *root, *arch, **canonical_hostnames; gfarm_mode_t mode, mode_mask = GFARM_S_ALLPERM; int i; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } mode = pi.status.st_mode; if (!GFARM_S_IS_PROGRAM(mode)) { gfarm_path_info_free(&pi); free(gfarm_file); return ("gfarm_url_program_deliver(): not a program"); } /* * XXX - if the owner of a file is not the same, permit a * group/other write access - This should be fixed in the next * major release. */ /* * XXX FIXME * This may be called with GFARM_REPLICATION_BOOTSTRAP_METHOD * to deliver gfrepbe_client/gfrepbe_server. */ if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) { e = gfarm_path_info_access(&pi, GFS_X_OK); if (e != NULL) { gfarm_path_info_free(&pi); free(gfarm_file); return (e); } mode |= 022; mode_mask = 0777; /* don't allow setuid/setgid */ } gfarm_path_info_free(&pi); dp = malloc(sizeof(char *) * (nhosts + 1)); if (dp == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } dp[nhosts] = NULL; e = gfarm_host_get_canonical_names(nhosts, hosts, &canonical_hostnames); if (e != NULL) { free(dp); free(gfarm_file); return (e); } /* XXX - this is too slow */ for (i = 0; i < nhosts; i++) { struct sockaddr peer_addr; struct gfs_connection *gfs_server; struct gfarm_file_section_info si; dp[i] = NULL; /* for error handling */ arch = gfarm_host_info_get_architecture_by_host( canonical_hostnames[i]); if (arch == NULL) { /* architecture of the hosts[i] is not registered */ e = "cannot deliver program to an unregistered host"; goto error; } /* XXX - which to use? `hosts[i]' vs `copies[j].hostname' */ e = gfarm_host_address_get(hosts[i], gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { free(arch); goto error; } e = gfs_client_connection(canonical_hostnames[i], &peer_addr, &gfs_server); if (e != NULL) { free(arch); goto error; } e = gfs_client_get_spool_root(gfs_server, &root); if (e != NULL) { free(arch); goto error; } e = gfarm_full_path_file_section(root, gfarm_file, arch, &dp[i]); free(root); if (e != NULL) { free(arch); goto error; } e = gfarm_file_section_info_get(gfarm_file, arch, &si); if (e != NULL) { free(arch); goto error; } /* * replicate the program */ e = gfarm_file_section_replicate_to_internal(gfarm_file, arch, mode & mode_mask, si.filesize, hosts[i]); gfarm_file_section_info_free(&si); free(arch); if (e != NULL) goto error; } gfarm_strings_free_deeply(nhosts, canonical_hostnames); free(gfarm_file); *delivered_paths = dp; return (NULL); error: gfarm_strings_free_deeply(nhosts, canonical_hostnames); free(gfarm_file); gfarm_strings_free_deeply(i + 1, dp); *delivered_paths = NULL; return (e); } char * gfarm_url_fragments_replicate( const char *gfarm_url, int ndsthosts, char **dsthosts) { char *e, *gfarm_file, **srchosts, **edsthosts; int nsrchosts; gfarm_mode_t mode, mode_mask = GFARM_S_ALLPERM; int i, pid, *pids; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; mode = pi.status.st_mode; if (!GFARM_S_IS_FRAGMENTED_FILE(mode)) { gfarm_path_info_free(&pi); e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto finish_gfarm_file; } /* * XXX - if the owner of a file is not the same, permit a * group/other write access - This should be fixed in the next * major release. */ if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) { e = gfarm_path_info_access(&pi, GFS_R_OK); if (e != NULL) { gfarm_path_info_free(&pi); free(gfarm_file); return (e); } mode |= 022; mode_mask = 0777; /* don't allow setuid/setgid */ } gfarm_path_info_free(&pi); e = gfarm_url_hosts_schedule(gfarm_url, "", &nsrchosts, &srchosts); if (e != NULL) goto finish_gfarm_file; edsthosts = malloc(sizeof(*edsthosts) * nsrchosts); if (edsthosts == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_srchosts; } gfarm_strings_expand_cyclic(ndsthosts, dsthosts, nsrchosts, edsthosts); pids = malloc(sizeof(int) * nsrchosts); if (pids == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_edsthosts; } /* * To use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_terminate(); if (e != NULL) goto finish_pids; for (i = 0; i < nsrchosts; i++) { struct sockaddr peer_addr; char *if_hostname; char section_string[GFARM_INT32STRLEN + 1]; struct gfarm_file_section_info si; pid = fork(); if (pid < 0) break; if (pid) { /* parent */ pids[i] = pid; continue; } /* child */ /* * use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_initialize(); if (e != NULL) _exit(1); /* reflect "address_use" directive in the `srchosts[i]' */ e = gfarm_host_address_get(srchosts[i], gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) _exit(2); sprintf(section_string, "%d", i); e = gfarm_file_section_info_get(gfarm_file, section_string, &si); if (e != NULL) _exit(3); e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section_string, mode & mode_mask, si.filesize, srchosts[i], if_hostname, edsthosts[i]); if (e != NULL) _exit(1); _exit(0); } while (--i >= 0) { int rv, s; while ((rv = waitpid(pids[i], &s, 0)) == -1 && errno == EINTR) ; if (rv == -1) { if (e == NULL) e = gfarm_errno_to_error(errno); } else if (WIFEXITED(s) && WEXITSTATUS(s) != 0) { e = "error happens on replication"; } } /* * recover temporary closed metadb connection * * XXX: FIXME layering violation */ if (e != NULL) { gfarm_metadb_initialize(); } else { e = gfarm_metadb_initialize(); } finish_pids: free(pids); finish_edsthosts: free(edsthosts); finish_srchosts: gfarm_strings_free_deeply(nsrchosts, srchosts); finish_gfarm_file: free(gfarm_file); return (e); } char * gfarm_url_fragments_replicate_to_domainname( const char *gfarm_url, const char *domainname) { char *e, **dsthosts; int nfrags; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); dsthosts = malloc(nfrags * sizeof(char *)); if (dsthosts == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_schedule_search_idle_by_domainname(domainname, nfrags, dsthosts); if (e != NULL) goto free_dsthosts; e = gfarm_url_fragments_replicate(gfarm_url, nfrags, dsthosts); while (--nfrags >= 0) free(dsthosts[nfrags]); free_dsthosts: free(dsthosts); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_beta_3_rev_2/lib/libgfarm/gfarm/param.c /* * $Id$ */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "hostspec.h" #include "param.h" struct gfarm_param_config { struct gfarm_param_config *next; int param_type_index; long value; struct gfarm_hostspec *hostspec; }; char * gfarm_param_config_parse_long(int ntypes, struct gfarm_param_type *type_table, char *config, int *type_indexp, long *valuep) { int i; size_t configlen, namelen; struct gfarm_param_type *type; long value; char *ep; configlen = strlen(config); namelen = strcspn(config, "="); for (i = 0; i < ntypes; i++) { type = &type_table[i]; if (strlen(type->name) != namelen || memcmp(config, type->name, namelen) != 0) continue; if (configlen == namelen) { /* no value specified */ if (!type->boolean) return ("value isn't specified"); value = 1; } else { if (type->boolean) return ("value isn't allowed for boolean"); if (config[namelen + 1] == '\0') return ("value is empty"); errno = 0; value = strtol(&config[namelen + 1], &ep, 0); if (errno != 0) return (gfarm_errno_to_error(errno)); if (*ep != '\0') return ("invalid character in value"); } *type_indexp = i; *valuep = value; return (NULL); } return (GFARM_ERR_NO_SUCH_OBJECT); } char * gfarm_param_config_add_long( struct gfarm_param_config ***config_list_lastp, int param_type_index, long value, struct gfarm_hostspec *hsp) { struct gfarm_param_config *pcp = malloc(sizeof(struct gfarm_param_config)); if (pcp == NULL) return (GFARM_ERR_NO_MEMORY); pcp->next = NULL; pcp->param_type_index = param_type_index; pcp->value = value; pcp->hostspec = hsp; *(*config_list_lastp) = pcp; *config_list_lastp = &pcp->next; return (NULL); } char * gfarm_param_apply_long_by_name_addr(struct gfarm_param_config *list, const char *name, struct sockaddr *addr, char *(*f)(void *, int, long), void *closure) { char *e_save = NULL, *e; long done = 0; for (; list != NULL; list = list->next) { if (gfarm_hostspec_match(list->hostspec, name, addr)) { assert(list->param_type_index < sizeof(long)*CHAR_BIT); if ((done & (1 << list->param_type_index)) != 0) continue; /* use first match only */ done |= (1 << list->param_type_index); e = (*f)(closure, list->param_type_index, list->value); if (e != NULL && e_save == NULL) e_save = e; } } return (e_save); } char * gfarm_param_apply_long(struct gfarm_param_config *list, char *(*f)(void *, int, long), void *closure) { char *e_save = NULL, *e; long done = 0; for (; list != NULL; list = list->next) { assert(list->param_type_index < sizeof(long)*CHAR_BIT); if ((done & (1 << list->param_type_index)) != 0) continue; /* use first match only */ done |= (1 << list->param_type_index); e = (*f)(closure, list->param_type_index, list->value); if (e != NULL && e_save == NULL) e_save = e; } return (e_save); } char * gfarm_param_get_long_by_name_addr(struct gfarm_param_config *list, int param_type_index, char *name, struct sockaddr *addr, long *valuep) { for (; list != NULL; list = list->next) { if (list->param_type_index == param_type_index && gfarm_hostspec_match(list->hostspec, name, addr)) { *valuep = list->value; return (NULL); } } return (GFARM_ERR_NO_SUCH_OBJECT); } char * gfarm_param_get_long(struct gfarm_param_config *list, int param_type_index, long *valuep) { for (; list != NULL; list = list->next) { if (list->param_type_index == param_type_index) { *valuep = list->value; return (NULL); } } return (GFARM_ERR_NO_SUCH_OBJECT); } /* * netparam */ struct gfarm_netparam_info { long minimum, maximum, default_value; struct gfarm_param_config *list; struct gfarm_param_config **last; }; struct gfarm_netparam_info gfarm_netparam_parallel_streams = { /* minimum */ 1, /* maximum */ 1000, /* default */ 1, NULL, &gfarm_netparam_parallel_streams.list, }; struct gfarm_netparam_info gfarm_netparam_stripe_unit_size = { /* minimum */ 0, /* maximum */ INT_MAX, /* default */ 0, NULL, &gfarm_netparam_stripe_unit_size.list, }; struct gfarm_netparam_info gfarm_netparam_rate_limit = { /* minimum */ 0, /* maximum */ INT_MAX, /* default */ 0, NULL, &gfarm_netparam_rate_limit.list, }; struct gfarm_param_type gfarm_netparam_type_table[] = { { "parallel_streams", 0, &gfarm_netparam_parallel_streams }, { "stripe_unit_size", 0, &gfarm_netparam_stripe_unit_size }, { "rate_limit", 0, &gfarm_netparam_rate_limit }, }; #define NNETPARAMS GFARM_ARRAY_LENGTH(gfarm_netparam_type_table) char * gfarm_netparam_config_add_long(char *config, struct gfarm_hostspec *hsp) { char *e; int param_type_index; long value; struct gfarm_netparam_info *info; e = gfarm_param_config_parse_long( NNETPARAMS, gfarm_netparam_type_table, config, &param_type_index, &value); if (e == GFARM_ERR_NO_SUCH_OBJECT) return ("unknown parameter"); if (e != NULL) return (e); info = gfarm_netparam_type_table[param_type_index].extension; if (value < info->minimum || value > info->maximum) return (GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE); return (gfarm_param_config_add_long(&info->last, 0, value, hsp)); } char * gfarm_netparam_config_get_long(struct gfarm_netparam_info *info, char *name, struct sockaddr *addr, long *valuep) { char *e; long value; e = gfarm_param_get_long_by_name_addr(info->list, 0, name, addr, &value); if (e == GFARM_ERR_NO_SUCH_OBJECT) { *valuep = info->default_value; } else if (e != NULL) { return (e); } else { *valuep = value; } return (NULL); } <file_sep>/gfarmfs-fuse/trunk/contrib/gfarmfs-exec/gfarmfs-exec.sh #!/bin/sh # # $Id$ USAGE() { cat <<EOF wrapper script to execute a program in Gfarm file system using GfarmFS-FUSE Usage: gfarmfs-exec.sh [OPTIONS] prog arg ... or GFS_PROG=prog GFS_ARGS="arg ..." gfarmfs-exec.sh Environment variable: GFS_USERNAME global user name in Gfarm (defaut: \$LOGNAME) GFS_MOUNTDIR mount point (defaut: /tmp/\$GFS_USERNAME/\$\$) GFS_WDIR working directory relative to the home directory in Gfarm file system (default: .) GFS_STDOUT Filename for the standard output (default: STDOUT.\$\$) GFS_STDERR Filename for the standard error (default: STDERR.\$\$) Options: -u username -m mountdir -wdir working_directory_from_home -stdout filename -stderr filename EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } PARSE_ARG() { while [ $# -gt 0 ]; do case $1 in -u) shift; GFS_USERNAME=$1 ;; -m) shift; GFS_MOUNTDIR=$1 ;; -wdir) shift; GFS_WDIR=$1 ;; -stdout) shift; GFS_STDOUT=$1 ;; -stderr) shift; GFS_STDERR=$1 ;; -*) USAGE ;; *) break ;; esac shift done [ $# -lt 1 ] && USAGE GFS_PROG=$1 shift GFS_ARGS=$* } UMOUNT_FUSE() { MNTDIR=$1 retry=10 i=0 while true; do fusermount -u $MNTDIR > /dev/null 2>&1 if [ $? -eq 0 ]; then return 0 fi ls -l $MNTDIR > /dev/null 2>&1 if [ $i -ge $retry ]; then return 1 fi i=`expr $i + 1` done } if [ X"$GFS_PROG" = X ]; then PARSE_ARG $* fi : ${GFS_USERNAME:=`gfwhoami 2> /dev/null`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2> /dev/null`} : ${GFS_MOUNTDIR:=/tmp/$GFS_USERNAME/$$} : ${GFS_WDIR:=.} : ${GFS_STDOUT:=STDOUT.$$} : ${GFS_STDERR:=STDERR.$$} DELETE_MOUNTDIR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR=1 fi [ -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME cd / # mount Gfarm file system if ! grep $GFS_MOUNTDIR /etc/mtab > /dev/null; then gfarmfs -lsu $GFS_MOUNTDIR || : fi # change directory and execute $GFS_PROG with $GFS_ARGS cd $GFS_MOUNTDIR/$GFS_USERNAME && cd $GFS_WDIR && $GFS_PROG $GFS_ARGS > $GFS_STDOUT 2> $GFS_STDERR STATUS=$? cd / # unmount Gfarm file system if grep $GFS_MOUNTDIR /etc/mtab > /dev/null; then UMOUNT_FUSE $GFS_MOUNTDIR fi [ $DELETE_MOUNTDIR = 1 ] && rmdir $GFS_MOUNTDIR exit $STATUS <file_sep>/gfarm/tags/gfarm_0_1/gftool/example/gfimport_fixed/gfimport_fixed.c #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfimport_fixed"; void import_fixed(FILE *ifp, char *output, int len, int nfrags, char **hosttab, file_offset_t *sizetab) { int i, c, n, rv; char *e; struct gfs_file *of; char *buffer = malloc(len); file_offset_t size; if (buffer == NULL) { fprintf(stderr, "no memory\n"); return; } e = gfs_pio_create(output, GFARM_FILE_WRONLY, 0666, &of); if (e != NULL) { fprintf(stderr, "%s, %s\n", output, e); free(buffer); return; } for (i = 0; i < nfrags; i++) { c = getc(ifp); if (c == EOF) break; ungetc(c, ifp); e = gfs_pio_set_view_index(of, nfrags, i, hosttab[i], GFARM_FILE_SEQUENTIAL); if (e != NULL) { gfs_pio_close(of); fprintf(stderr, "%s, fragment %d: %s\n", output, i, e); e = gfarm_url_fragment_cleanup(output, nfrags, hosttab); free(buffer); return; } size = 0; for (;;) { if (size >= sizetab[i]) /* wrote enough */ break; n = fread(buffer, 1, len, ifp); if (n == 0) /* EOF */ break; gfs_pio_write(of, buffer, n, &rv); size += n; if (n < len) /* EOF */ break; } } e = gfs_pio_close(of); if (e != NULL) { fprintf(stderr, "%s, %s\n", output, e); e = gfarm_url_fragment_cleanup(output, nfrags, hosttab); } free(buffer); } void usage() { fprintf(stderr, "Usage: %s [option] <input_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-H <hostfile>\n"); fprintf(stderr, "\t-f <configfile>\n"); fprintf(stderr, "\t-l <record length>\n"); fprintf(stderr, "\t-o <output_gfarm_file>\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *config = NULL, *hostfile = NULL, *output = NULL, *iname; int ch, nhosts, error_line, len = 1; FILE *ifp; char **hosttab; file_offset_t *sizetab; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "H:f:l:o:")) != -1) { switch (ch) { case 'H': hostfile = optarg; break; case 'f': config = optarg; break; case 'l': len = strtol(optarg, NULL, 0); break; case 'o': output = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (output == NULL) { fprintf(stderr, "%s: -o <output gfarm file> expected\n", program_name); exit(1); } if (argc == 0) { iname = "stdin"; ifp = stdin; } else if (argc != 1) { fprintf(stderr, "%s: error: multiple input file name specified\n", program_name); exit(1); } else { iname = argv[0]; ifp = fopen(iname, "r"); if (ifp == NULL) { perror(iname); exit(1); } } e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (hostfile != NULL && config != NULL) { fprintf(stderr, "%s: ambiguous. both -H %s and -f %s specified\n", program_name, hostfile, config); exit(1); } else if (config != NULL) { e = gfarm_import_fragment_config_read( config, &nhosts, &hosttab, &sizetab, &error_line); } else if (hostfile != NULL) { struct stat is; if (fstat(fileno(ifp), &is) == -1) { perror(iname); exit(1); } if (!S_ISREG(is.st_mode)) { fprintf(stderr, "%s: size unknown\n", iname); exit(1); } e = gfarm_hostlist_read(hostfile, &nhosts, &hosttab, &error_line); if (e == NULL) { sizetab = gfarm_import_fragment_size_alloc( is.st_size, nhosts); if (sizetab == NULL) { fprintf(stderr, "%s: not enough memory for %d hosts\n", program_name, nhosts); exit(1); } } } else /* if (hostfile == NULL && config == NULL) */ { fprintf(stderr, "%s: either -H <hostfile> or -f <config> expected\n", program_name); exit(1); } if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: line %d: %s\n", config, error_line, e); else fprintf(stderr, "%s: %s\n", program_name, e); return (1); } import_fixed(ifp, output, len, nhosts, hosttab, sizetab); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT1-2-2-3_failed_to_gfsched #! /bin/sh ###################################################################### TESTID="FT1-2-2-3" CATEGORY="accident causes no failover" SECTION="mds accident" TITLE="failed to gfsched" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { SHARED_KEY=~/.gfarm_shared_key RESULT=$FT_RESULT_PASS ssh $gfmd2 mv ${SHARED_KEY} ${SHARED_KEY}.bak [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "replace gfsched on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Gfarm metadata server is not available on $gfmd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd2 mv ${SHARED_KEY}.bak ${SHARED_KEY} [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "restore gfsched on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: Gfarm metadata server is not available on $gfmd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { # if a shared key backup exists, then restore shared key. ssh $gfmd2 test -f ${SHARED_KEY}.bak && \ ssh $gfmd2 mv ${SHARED_KEY}.bak ${SHARED_KEY} return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/server/gfsd/gfsd.c /* * $Id$ */ #include <gfarm/gfarm_config.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/resource.h> #include <netdb.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <stdarg.h> #include <setjmp.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <pwd.h> #include <grp.h> #include <libgen.h> #include <openssl/evp.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "gfutil.h" #include "iobuffer.h" #include "xxx_proto.h" #include "io_fd.h" #include "param.h" #include "sockopt.h" #include "host.h" #include "auth.h" #include "gfs_proto.h" #include "gfs_client.h" #define COMPAT_OLD_GFS_PROTOCOL #ifndef DEFAULT_PATH #define DEFAULT_PATH "PATH=/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin:/usr/openwin/bin" #endif #ifndef PATH_BSHELL #define PATH_BSHELL "/bin/sh" #endif #ifdef SOMAXCONN #define LISTEN_BACKLOG SOMAXCONN #else #define LISTEN_BACKLOG 5 #endif /* limit maximum open files per client, when system limit is very high */ #ifndef FILE_TABLE_LIMIT #define FILE_TABLE_LIMIT 2048 #endif char *program_name = "gfsd"; int debug_mode = 0; int restrict_user = 0; uid_t restricted_user = 0; long rate_limit = 0; struct xxx_connection *credential_exported = NULL; /* this routine should be called before calling exit(). */ void cleanup(void) { if (credential_exported != NULL) xxx_connection_delete_credential(credential_exported); credential_exported = NULL; /* disconnect, do logging */ gflog_notice("disconnected", NULL); } #define fatal_proto(proto, status) fatal(proto, status) void fatal(char *message, char *status) { cleanup(); gflog_fatal(message, status); } void fatal_errno(char *message) { cleanup(); gflog_fatal_errno(message); } void gfs_server_get_request(struct xxx_connection *client, char *diag, char *format, ...) { va_list ap; char *e; int eof; va_start(ap, format); e = xxx_proto_vrecv(client, 0, &eof, &format, &ap); va_end(ap); if (e != NULL) fatal_proto(diag, e); if (eof) fatal_proto(diag, "missing RPC argument"); if (*format != '\0') fatal(diag, "invalid format character to get request"); } void gfs_server_put_reply(struct xxx_connection *client, char *diag, int ecode, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_send(client, "i", (gfarm_int32_t)ecode); if (e != NULL) fatal_proto(diag, e); if (ecode == 0) { e = xxx_proto_vsend(client, &format, &ap); if (e != NULL) fatal_proto(diag, e); } va_end(ap); if (ecode == 0 && *format != '\0') fatal(diag, "invalid format character to put reply"); } int file_table_free = 0; int file_table_size = 0; int *file_table; void file_table_init(int table_size) { int i; file_table = malloc(sizeof(int) * table_size); if (file_table == NULL) { errno = ENOMEM; fatal_errno("file table"); } for (i = 0; i < table_size; i++) file_table[i] = -1; file_table_size = table_size; } int file_table_add(int fd) { if (file_table_free >= file_table_size) { close(fd); errno = EMFILE; return (-1); } file_table[file_table_free] = fd; fd = file_table_free; for (++file_table_free; file_table_free < file_table_size; ++file_table_free) if (file_table[file_table_free] == -1) break; return (fd); } int file_table_close(int fd) { int rv = 0; if (fd >= file_table_size || file_table[fd] == -1) return (EBADF); if (close(file_table[fd]) < 0) rv = errno; file_table[fd] = -1; if (fd < file_table_free) file_table_free = fd; return (rv); } int file_table_get(int fd) { if (0 <= fd && fd < file_table_size) return (file_table[fd]); else return (-1); } void local_path(char *file, char **pathp, char *diag) { char *e; e = gfarm_path_localize(file, pathp); free(file); if (e != NULL) fatal(diag, e); } void gfs_server_open(struct xxx_connection *client) { char *file, *path; gfarm_int32_t netflag, mode; int hostflag, fd = -1, save_errno = 0; gfs_server_get_request(client, "open", "sii", &file, &netflag, &mode); hostflag = gfs_open_flags_localize(netflag); if (hostflag == -1) { gfs_server_put_reply(client, "open", GFS_ERROR_INVAL, ""); return; } local_path(file, &path, "open"); if ((fd = open(path, hostflag, mode)) < 0) { save_errno = errno; } else if ((fd = file_table_add(fd)) < 0) { save_errno = errno; } free(path); gfs_server_put_reply(client, "open", gfs_errno_to_proto_error(save_errno), "i", fd); } void gfs_server_close(struct xxx_connection *client) { int fd, save_errno; gfs_server_get_request(client, "close", "i", &fd); save_errno = file_table_close(fd); gfs_server_put_reply(client, "close", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_seek(struct xxx_connection *client) { int fd, whence, save_errno = 0; file_offset_t offset; off_t rv; gfs_server_get_request(client, "seek", "ioi", &fd, &offset, &whence); rv = lseek(file_table_get(fd), (off_t)offset, whence); if (rv == -1) save_errno = errno; else offset = rv; gfs_server_put_reply(client, "seek", gfs_errno_to_proto_error(save_errno), "o", offset); } void gfs_server_read(struct xxx_connection *client) { ssize_t rv; int fd, size; char buffer[GFS_PROTO_MAX_IOSIZE]; gfs_server_get_request(client, "read", "ii", &fd, &size); /* We truncatef i/o size bigger than GFS_PROTO_MAX_IOSIZE. */ if (size > GFS_PROTO_MAX_IOSIZE) size = GFS_PROTO_MAX_IOSIZE; rv = read(file_table_get(fd), buffer, size); gfs_server_put_reply(client, "read", rv == -1 ? gfs_errno_to_proto_error(errno) : 0, "b", rv, buffer); } void gfs_server_write(struct xxx_connection *client) { ssize_t rv; size_t size; gfarm_int32_t fd; char buffer[GFS_PROTO_MAX_IOSIZE]; gfs_server_get_request(client, "write", "ib", &fd, sizeof(buffer), &size, buffer); /* * We truncate i/o size bigger than GFS_PROTO_MAX_IOSIZE. * This is inefficient because passed extra data are just * abandoned. So client should avoid such situation. */ if (size > GFS_PROTO_MAX_IOSIZE) size = GFS_PROTO_MAX_IOSIZE; rv = write(file_table_get(fd), buffer, size); gfs_server_put_reply(client, "write", rv == -1 ? gfs_errno_to_proto_error(errno) : 0, "i", (gfarm_int32_t)rv); } void gfs_server_unlink(struct xxx_connection *client) { char *file, *path; int save_errno = 0; gfs_server_get_request(client, "unlink", "s", &file); local_path(file, &path, "unlink"); if (unlink(path) == -1) save_errno = errno; free(path); gfs_server_put_reply(client, "unlink", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_mkdir(struct xxx_connection *client) { char *gpath, *path; gfarm_int32_t mode; int save_errno = 0; gfs_server_get_request(client, "mkdir", "si", &gpath, &mode); local_path(gpath, &path, "mkdir"); if (mkdir(path, mode) == -1) save_errno = errno; free(path); gfs_server_put_reply(client, "mkdir", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_rmdir(struct xxx_connection *client) { char *gpath, *path; int save_errno = 0; gfs_server_get_request(client, "rmdir", "s", &gpath); local_path(gpath, &path, "rmdir"); if (rmdir(path) == -1) save_errno = errno; free(path); gfs_server_put_reply(client, "rmdir", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_chmod(struct xxx_connection *client) { char *file, *path; gfarm_int32_t mode; int save_errno = 0; gfs_server_get_request(client, "chmod", "si", &file, &mode); local_path(file, &path, "chmod"); if (chmod(path, mode) == -1) save_errno = errno; free(path); gfs_server_put_reply(client, "chmod", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_chgrp(struct xxx_connection *client) { char *file, *path, *group; int save_errno = 0; struct group *grp; gfs_server_get_request(client, "chgrp", "ss", &file, &group); local_path(file, &path, "chgrp"); grp = getgrnam(group); if (grp == NULL) { save_errno = EPERM; } else if (chown(path, -1, grp->gr_gid) == -1) { save_errno = errno; } free(path); free(group); gfs_server_put_reply(client, "chgrp", gfs_errno_to_proto_error(save_errno), ""); } void gfs_server_digest(struct xxx_connection *client) { char *digest_type; int fd, save_errno = 0; file_offset_t filesize; EVP_MD_CTX md_ctx; const EVP_MD *md_type; unsigned int digest_length; unsigned char digest_value[EVP_MAX_MD_SIZE]; char buffer[GFS_PROTO_MAX_IOSIZE]; gfs_server_get_request(client, "digest", "is", &fd, &digest_type); if ((md_type = EVP_get_digestbyname(digest_type)) == NULL) { save_errno = EINVAL; /* * to avoid loading malformed value to floating register, * if file_offset_t is double */ filesize = 0; } else { save_errno = gfs_digest_calculate_local( file_table_get(fd), buffer, sizeof(buffer), md_type, &md_ctx, &digest_length, digest_value, &filesize); } free(digest_type); gfs_server_put_reply(client, "digest", gfs_errno_to_proto_error(save_errno), "bo", (size_t)digest_length, digest_value, filesize); } void gfs_server_get_spool_root(struct xxx_connection *client) { gfs_server_put_reply(client, "get_spool_root", GFS_ERROR_NOERROR, "s", gfarm_spool_root); } #define USEC_SEC 1000000 #define USEC_MILLISEC 1000 int timeval_cmp(struct timeval *t1, struct timeval *t2) { if (t1->tv_sec > t2->tv_sec) return (1); if (t1->tv_sec < t2->tv_sec) return (-1); if (t1->tv_usec > t2->tv_usec) return (1); if (t1->tv_usec < t2->tv_usec) return (-1); return (0); } void timeval_add_usec(struct timeval *t1, long usec) { t1->tv_usec += usec; if (t1->tv_usec >= USEC_SEC) { t1->tv_usec -= USEC_SEC; ++t1->tv_sec; } } void timeval_sub(struct timeval *t1, struct timeval *t2) { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; if (t1->tv_usec < 0) { t1->tv_usec += USEC_SEC; --t1->tv_sec; } } #define RATECTL_TICK 100 /* i.e. 1/100seconds */ #define RTT 25 /* XXX - hardcoded 250ms RTT */ #define USEC_RATECTL_TICK (USEC_SEC / RATECTL_TICK) #define DEFAULT_MTU 1500 struct rate_info { long octets_per_tick; long flow_limit; long flow; struct timeval period; int tick; }; void rate_init(struct rate_info *rinfo, long rate) { rinfo->octets_per_tick = rate / 8 / RATECTL_TICK; rinfo->flow_limit = DEFAULT_MTU; rinfo->flow = 0; gettimeofday(&rinfo->period, NULL); timeval_add_usec(&rinfo->period, USEC_RATECTL_TICK); rinfo->tick++; } void rate_control(struct rate_info *rinfo, long size) { rinfo->flow += size; /* XXX - it's inefficient to call usleep() multiple times. */ while (rinfo->flow >= rinfo->flow_limit) { struct timeval now, interval; gettimeofday(&now, NULL); if (timeval_cmp(&now, &rinfo->period) < 0) { interval = rinfo->period; timeval_sub(&interval, &now); usleep(interval.tv_sec * USEC_SEC + interval.tv_usec); #if 1 /* make this slow while slow starting */ rinfo->period = now; #endif } #if 0 /* * We do update rinfo->period by current time here, * because our intention is to limit network flow. */ rinfo->period = now; #endif timeval_add_usec(&rinfo->period, USEC_RATECTL_TICK); rinfo->flow -= rinfo->flow_limit; /* slow start */ if (rinfo->flow_limit < rinfo->octets_per_tick) { if (++rinfo->tick >= RTT) { rinfo->tick = 0; rinfo->flow_limit <<= 1; if (rinfo->flow_limit > rinfo->octets_per_tick) rinfo->flow_limit = rinfo->octets_per_tick; } } } } #if 0 #define BULKREAD_SIZE GFS_PROTO_MAX_IOSIZE #else #define BULKREAD_SIZE 4096 #endif void gfs_server_bulkread(struct xxx_connection *client) { char *e; gfarm_int32_t fd; ssize_t rv; enum gfs_proto_error error = GFS_ERROR_NOERROR; char buffer[BULKREAD_SIZE]; struct rate_info rinfo; gfs_server_get_request(client, "bulkread", "i", &fd); fd = file_table_get(fd); if (rate_limit != 0) rate_init(&rinfo, rate_limit); do { rv = read(fd, buffer, BULKREAD_SIZE); if (rv <= 0) { if (rv == -1) error = gfs_errno_to_proto_error(errno); break; } e = xxx_proto_send(client, "b", rv, buffer); if (e != NULL) { error = gfs_string_to_proto_error(e); break; } #if BULKREAD_SIZE < GFS_PROTO_MAX_IOSIZE e = xxx_proto_flush(client); if (e != NULL) { error = gfs_string_to_proto_error(e); break; } #endif if (rate_limit != 0) rate_control(&rinfo, rv); } while (rv > 0); /* send EOF mark */ e = xxx_proto_send(client, "b", 0, buffer); if (e != NULL && error == GFS_ERROR_NOERROR) error = gfs_string_to_proto_error(e); gfs_server_put_reply(client, "bulkread", error, ""); } void gfs_server_striping_read(struct xxx_connection *client) { char *e; gfarm_int32_t fd, interleave_factor; file_offset_t offset, size, full_stripe_size; file_offset_t chunk_size; ssize_t rv; enum gfs_proto_error error = GFS_ERROR_NOERROR; char buffer[BULKREAD_SIZE]; struct rate_info rinfo; gfs_server_get_request(client, "striping_read", "iooio", &fd, &offset, &size, &interleave_factor, &full_stripe_size); fd = file_table_get(fd); if (lseek(fd, (off_t)offset, SEEK_SET) == -1) { error = gfs_errno_to_proto_error(errno); goto finish; } if (rate_limit != 0) rate_init(&rinfo, rate_limit); for (;;) { chunk_size = interleave_factor == 0 || size < interleave_factor ? size : interleave_factor; for (; chunk_size > 0; chunk_size -= rv, size -= rv) { rv = read(fd, buffer, chunk_size < BULKREAD_SIZE ? chunk_size : BULKREAD_SIZE); if (rv <= 0) { if (rv == -1) error = gfs_errno_to_proto_error(errno); goto finish; } e = xxx_proto_send(client, "b", rv, buffer); if (e != NULL) { error = gfs_string_to_proto_error(e); goto finish; } #if BULKREAD_SIZE < GFS_PROTO_MAX_IOSIZE e = xxx_proto_flush(client); if (e != NULL) { error = gfs_string_to_proto_error(e); goto finish; } #endif if (rate_limit != 0) rate_control(&rinfo, rv); } if (size <= 0) break; offset += full_stripe_size; if (lseek(fd, (off_t)offset, SEEK_SET) == -1) { error = gfs_errno_to_proto_error(errno); break; } } finish: /* send EOF mark */ e = xxx_proto_send(client, "b", 0, buffer); if (e != NULL && error == GFS_ERROR_NOERROR) error = gfs_string_to_proto_error(e); gfs_server_put_reply(client, "striping_read", error, ""); } void gfs_server_replicate_file_sequential(struct xxx_connection *client) { char *e, *file, *path, *src_host; gfarm_int32_t mode; struct gfs_connection *src_conn; int fd, src_fd; enum gfs_proto_error error = GFS_ERROR_NOERROR; struct hostent *hp; struct sockaddr_in peer_addr; gfs_server_get_request(client, "replicate_file_seq", "sis", &file, &mode, &src_host); hp = gethostbyname(src_host); if (hp == NULL || hp->h_addrtype != AF_INET) { e = GFARM_ERR_UNKNOWN_HOST; } else { memset(&peer_addr, 0, sizeof(peer_addr)); memcpy(&peer_addr.sin_addr, hp->h_addr, sizeof(peer_addr.sin_addr)); peer_addr.sin_family = hp->h_addrtype; peer_addr.sin_port = htons(gfarm_spool_server_port); /* * the following gfs_client_connect() accesses user & home * information which was set in gfarm_authorize() * with switch_to==1. */ /* XXX - `src_host' should be canonical_hostname. */ e = gfs_client_connect(src_host, (struct sockaddr *)&peer_addr, &src_conn); } free(src_host); if (e != NULL) { error = gfs_string_to_proto_error(e); gflog_warning("replicate_file_seq:remote_connect", e); } else { e = gfs_client_open(src_conn, file, GFARM_FILE_RDONLY, 0, &src_fd); if (e != NULL) { error = gfs_string_to_proto_error(e); gflog_warning("replicate_file_seq:remote_open", e); } else { e = gfarm_path_localize(file, &path); if (e != NULL) fatal("replicate_file_seq:path", e); fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, mode); if (fd < 0) { error = gfs_errno_to_proto_error(errno); gflog_warning_errno( "replicate_file_seq:local_open"); } else { e = gfs_client_copyin(src_conn, src_fd, fd); if (e != NULL) { error = gfs_string_to_proto_error(e); gflog_warning( "replicate_file_seq:copyin", e); } close(fd); } e = gfs_client_close(src_conn, src_fd); free(path); } gfs_client_disconnect(src_conn); } free(file); gfs_server_put_reply(client, "replicate_file_seq", error, ""); } int iosize_alignment = 4096; int iosize_minimum_division = 65536; struct parallel_stream { struct gfs_connection *src_conn; int src_fd; enum { GSRFP_COPYING, GSRFP_FINISH } state; }; char * simple_division(int ofd, struct parallel_stream *divisions, off_t file_size, int n) { char *e, *e_save = NULL; file_offset_t offset = 0, residual = file_size; file_offset_t size_per_division = file_offset_floor(file_size / n); int i; if (file_offset_floor(size_per_division / iosize_alignment) * iosize_alignment != size_per_division) { size_per_division = (file_offset_floor( size_per_division / iosize_alignment) + 1) * iosize_alignment; } for (i = 0; i < n; i++) { file_offset_t size; if (residual <= 0 || e_save != NULL) { divisions[i].state = GSRFP_FINISH; continue; } size = residual <= size_per_division ? residual : size_per_division; e = gfs_client_striping_copyin_request( divisions[i].src_conn, divisions[i].src_fd, ofd, offset, size, 0, 0); offset += size_per_division; residual -= size; if (e != NULL) { if (e_save == NULL) e_save = e; gflog_warning("replicate_file_division:copyin", e); divisions[i].state = GSRFP_FINISH; continue; } divisions[i].state = GSRFP_COPYING; } return (e_save); } char * striping(int ofd, struct parallel_stream *divisions, off_t file_size, int n, int interleave_factor) { char *e, *e_save = NULL; file_offset_t full_stripe_size = (file_offset_t)interleave_factor * n; file_offset_t stripe_number = file_offset_floor(file_size / full_stripe_size); file_offset_t size_per_division = interleave_factor * stripe_number; file_offset_t residual = file_size - full_stripe_size * stripe_number; file_offset_t chunk_number_on_last_stripe; file_offset_t last_chunk_size; file_offset_t offset = 0; int i; if (residual == 0) { chunk_number_on_last_stripe = 0; last_chunk_size = 0; } else { chunk_number_on_last_stripe = file_offset_floor( residual / interleave_factor); last_chunk_size = residual - interleave_factor * chunk_number_on_last_stripe; } for (i = 0; i < n; i++) { file_offset_t size = size_per_division; if (i < chunk_number_on_last_stripe) size += interleave_factor; else if (i == chunk_number_on_last_stripe) size += last_chunk_size; if (size <= 0 || e_save != NULL) { divisions[i].state = GSRFP_FINISH; continue; } e = gfs_client_striping_copyin_request( divisions[i].src_conn, divisions[i].src_fd, ofd, offset, size, interleave_factor, full_stripe_size); offset += interleave_factor; if (e != NULL) { if (e_save == NULL) e_save = e; gflog_warning("replicate_file_stripe:copyin", e); divisions[i].state = GSRFP_FINISH; continue; } divisions[i].state = GSRFP_COPYING; } return (e_save); } void limit_division(int *ndivisionsp, file_offset_t file_size) { int ndivisions = *ndivisionsp; /* do not divide too much */ if (ndivisions > file_size / iosize_minimum_division) { ndivisions = file_size / iosize_minimum_division; if (ndivisions == 0) ndivisions = 1; } *ndivisionsp = ndivisions; } void gfs_server_replicate_file_parallel(struct xxx_connection *client) { struct parallel_stream *divisions; char *e_save = NULL, *e, *file, *path, *src_host; gfarm_int32_t mode; gfarm_int32_t ndivisions; /* parallel_streams */ gfarm_int32_t interleave_factor; /* stripe_unit_size, chuck size */ file_offset_t file_size; int i, j, n, ofd; enum gfs_proto_error error = GFS_ERROR_NOERROR; struct hostent *hp; struct sockaddr_in peer_addr; gfs_server_get_request(client, "replicate_file_par", "sioiis", &file, &mode, &file_size, &ndivisions, &interleave_factor, &src_host); e = gfarm_path_localize(file, &path); if (e != NULL) fatal("replicate_file_par", e); ofd = open(path, O_WRONLY|O_CREAT|O_TRUNC, mode); free(path); if (ofd == -1) { error = gfs_errno_to_proto_error(errno); gflog_warning_errno("replicate_file_par:local_open"); goto finish; } limit_division(&ndivisions, file_size); divisions = malloc(sizeof(*divisions) * ndivisions); if (divisions == NULL) { error = GFS_ERROR_NOMEM; goto finish_ofd; } hp = gethostbyname(src_host); if (hp == NULL || hp->h_addrtype != AF_INET) { error = GFS_ERROR_CONNREFUSED; goto finish_free_divisions; } memset(&peer_addr, 0, sizeof(peer_addr)); memcpy(&peer_addr.sin_addr, hp->h_addr, sizeof(peer_addr.sin_addr)); peer_addr.sin_family = hp->h_addrtype; peer_addr.sin_port = htons(gfarm_spool_server_port); /* XXX - this should be done in parallel rather than sequential */ for (i = 0; i < ndivisions; i++) { e = gfs_client_connect(src_host, (struct sockaddr *)&peer_addr, &divisions[i].src_conn); if (e != NULL) { if (e_save == NULL) e_save = e; gflog_warning("replicate_file_par:remote_connect", e); break; } } n = i; if (n == 0) { error = gfs_string_to_proto_error(e_save); goto finish_free_divisions; } e_save = NULL; /* not fatal */ /* XXX - this should be done in parallel rather than sequential */ for (i = 0; i < n; i++) { e = gfs_client_open(divisions[i].src_conn, file, GFARM_FILE_RDONLY, 0, &divisions[i].src_fd); if (e != NULL) { if (e_save == NULL) e_save = e; gflog_warning("replicate_file_par:remote_open", e); /* * XXX - this should be done in parallel * rather than sequential */ for (j = i; j < n; j++) gfs_client_disconnect(divisions[j].src_conn); n = i; break; } } if (n == 0) { error = gfs_string_to_proto_error(e_save); goto finish_free_divisions; } e_save = NULL; /* not fatal */ if (interleave_factor == 0) { e = simple_division(ofd, divisions, file_size, n); } else { e = striping(ofd, divisions, file_size, n, interleave_factor); } e_save = e; /* * XXX - we cannot stop here, even if e_save != NULL, * because currently there is no way to cancel * striping_copyin request. */ for (;;) { int max_fd, fd, nfound, rv; fd_set readable; FD_ZERO(&readable); max_fd = -1; for (i = 0; i < n; i++) { if (divisions[i].state != GSRFP_COPYING) continue; fd = gfs_client_connection_fd(divisions[i].src_conn); /* XXX - prevent this happens */ if (fd >= FD_SETSIZE) { fatal("replicate_file_par", "too big file descriptor"); } FD_SET(fd, &readable); if (max_fd < fd) max_fd = fd; } if (max_fd == -1) break; nfound = select(max_fd + 1, &readable, NULL, NULL, NULL); if (nfound <= 0) { if (nfound == -1 && errno != EINTR && errno != EAGAIN) gflog_warning_errno( "replicate_file_par:select"); continue; } for (i = 0; i < n; i++) { if (divisions[i].state != GSRFP_COPYING) continue; fd = gfs_client_connection_fd(divisions[i].src_conn); if (!FD_ISSET(fd, &readable)) continue; e = gfs_client_striping_copyin_partial( divisions[i].src_conn, &rv); if (e != NULL) { if (e_save == NULL) e_save = e; divisions[i].state = GSRFP_FINISH; /* XXX */ } else if (rv == 0) { divisions[i].state = GSRFP_FINISH; e = gfs_client_striping_copyin_result( divisions[i].src_conn); if (e != NULL) { if (e_save == NULL) e_save = e; } else { e = gfs_client_close( divisions[i].src_conn, divisions[i].src_fd); if (e_save == NULL) e_save = e; } } if (--nfound <= 0) break; } } /* XXX - this should be done in parallel rather than sequential */ for (i = 0; i < n; i++) { e = gfs_client_disconnect(divisions[i].src_conn); if (e_save == NULL) e_save = e; } if (e_save != NULL) error = gfs_string_to_proto_error(e_save); finish_free_divisions: free(divisions); finish_ofd: close(ofd); finish: free(file); free(src_host); gfs_server_put_reply(client, "replicate_file_par", error, ""); } void gfs_server_chdir(struct xxx_connection *client) { char *gpath, *path; int save_errno = 0; gfs_server_get_request(client, "chdir", "s", &gpath); local_path(gpath, &path, "chdir"); if (chdir(path) == -1) save_errno = errno; free(path); gfs_server_put_reply(client, "chdir", gfs_errno_to_proto_error(save_errno), ""); } struct gfs_server_command_context { struct gfarm_iobuffer *iobuffer[NFDESC]; enum { GFS_COMMAND_SERVER_STATE_NEUTRAL, GFS_COMMAND_SERVER_STATE_OUTPUT, GFS_COMMAND_SERVER_STATE_EXITED } server_state; int server_output_fd; int server_output_residual; enum { GFS_COMMAND_CLIENT_STATE_NEUTRAL, GFS_COMMAND_CLIENT_STATE_OUTPUT } client_state; int client_output_residual; int pid; int exited_pid; int status; } server_command_context; #define COMMAND_IS_RUNNING() (server_command_context.exited_pid == 0) volatile sig_atomic_t sigchld_jmp_needed = 0; sigjmp_buf sigchld_jmp_buf; void sigchld_handler(int sig) { int pid, status; for (;;) { pid = waitpid(-1, &status, WNOHANG); if (pid == -1 || pid == 0) break; server_command_context.exited_pid = pid; server_command_context.status = status; } if (sigchld_jmp_needed) { sigchld_jmp_needed = 0; siglongjmp(sigchld_jmp_buf, 1); } } char * gfs_server_command_fd_set(struct xxx_connection *client, fd_set *readable, fd_set *writable, int *max_fdp) { struct gfs_server_command_context *cc = &server_command_context; int conn_fd = xxx_connection_fd(client); int i, fd; /* * The following test condition should just match with * the i/o condition in gfs_server_command_io_fd_set(), * otherwise unneeded busy wait happens. */ if (cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL || (cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT && gfarm_iobuffer_is_readable(cc->iobuffer[FDESC_STDIN]))) { FD_SET(conn_fd, readable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if ((cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL && (gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDERR]) || gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDOUT]) || !COMMAND_IS_RUNNING())) || cc->server_state == GFS_COMMAND_SERVER_STATE_OUTPUT) { FD_SET(conn_fd, writable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if (COMMAND_IS_RUNNING() && gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDIN])) { fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[FDESC_STDIN]); FD_SET(fd, writable); if (*max_fdp < fd) *max_fdp = fd; } for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { if (gfarm_iobuffer_is_readable(cc->iobuffer[i])) { fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[i]); FD_SET(fd, readable); if (*max_fdp < fd) *max_fdp = fd; } } return (NULL); } char * gfs_server_command_io_fd_set(struct xxx_connection *client, fd_set *readable, fd_set *writable) { struct gfs_server_command_context *cc = &server_command_context; int fd, conn_fd = xxx_connection_fd(client); fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[FDESC_STDIN]); if (FD_ISSET(fd, writable)) { assert(gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDIN])); gfarm_iobuffer_write(cc->iobuffer[FDESC_STDIN], NULL); if (gfarm_iobuffer_is_eof(cc->iobuffer[FDESC_STDIN])) close(fd); } fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDOUT]); if (FD_ISSET(fd, readable)) gfarm_iobuffer_read(cc->iobuffer[FDESC_STDOUT], NULL); fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDERR]); if (FD_ISSET(fd, readable)) gfarm_iobuffer_read(cc->iobuffer[FDESC_STDERR], NULL); if (FD_ISSET(conn_fd, readable) && cc->server_state != GFS_COMMAND_SERVER_STATE_EXITED) { if (cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL) { gfarm_int32_t cmd, fd, len, sig; int eof; char *e; e = xxx_proto_recv(client, 1, &eof, "i", &cmd); if (e != NULL) fatal_proto("command:client subcommand", e); if (eof) fatal_proto("command:client subcommand", "eof"); switch (cmd) { case GFS_PROTO_COMMAND_EXIT_STATUS: fatal_proto("command:client subcommand", "unexpected exit_status"); break; case GFS_PROTO_COMMAND_SEND_SIGNAL: e = xxx_proto_recv(client, 1, &eof, "i", &sig); if (e != NULL) fatal_proto("command_send_signal", e); if (eof) fatal_proto( "command_send_signal", "eof"); /* "-" is to send it to the process group */ kill(-cc->pid, sig); break; case GFS_PROTO_COMMAND_FD_INPUT: e = xxx_proto_recv(client, 1, &eof, "ii", &fd, &len); if (e != NULL) fatal_proto("command_fd_input", e); if (eof) fatal_proto("command_fd_input", "eof"); if (fd != FDESC_STDIN) { /* XXX - something wrong */ fatal_proto("command_fd_input", "fd"); } if (len <= 0) { /* notify closed */ gfarm_iobuffer_set_read_eof( cc->iobuffer[FDESC_STDIN]); } else { cc->client_state = GFS_COMMAND_CLIENT_STATE_OUTPUT; cc->client_output_residual = len; } break; default: /* XXX - something wrong */ fatal_proto("command_io", "unknown subcommand"); break; } } if (cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT) { gfarm_iobuffer_read(cc->iobuffer[FDESC_STDIN], &cc->client_output_residual); if (cc->client_output_residual == 0) cc->client_state = GFS_COMMAND_CLIENT_STATE_NEUTRAL; if (gfarm_iobuffer_is_read_eof( cc->iobuffer[FDESC_STDIN])) { fatal_proto("command_fd_input_content", "eof"); } } } if (FD_ISSET(conn_fd, writable)) { if (cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL) { char *e; if (gfarm_iobuffer_is_writable( cc->iobuffer[FDESC_STDERR]) || gfarm_iobuffer_is_writable( cc->iobuffer[FDESC_STDOUT])) { if (gfarm_iobuffer_is_writable( cc->iobuffer[FDESC_STDERR])) cc->server_output_fd = FDESC_STDERR; else cc->server_output_fd = FDESC_STDOUT; /* * cc->server_output_residual may be 0, * if stdout or stderr is closed. */ cc->server_output_residual = gfarm_iobuffer_avail_length( cc->iobuffer[cc->server_output_fd]); e = xxx_proto_send(client, "iii", GFS_PROTO_COMMAND_FD_OUTPUT, cc->server_output_fd, cc->server_output_residual); xxx_proto_flush(client); cc->server_state = GFS_COMMAND_SERVER_STATE_OUTPUT; } else if (!COMMAND_IS_RUNNING()) { e = xxx_proto_send(client, "i", GFS_PROTO_COMMAND_EXITED); xxx_proto_flush(client); cc->server_state = GFS_COMMAND_SERVER_STATE_EXITED; } } if (cc->server_state == GFS_COMMAND_SERVER_STATE_OUTPUT) { gfarm_iobuffer_write( cc->iobuffer[cc->server_output_fd], &cc->server_output_residual); if (cc->server_output_residual == 0) cc->server_state = GFS_COMMAND_SERVER_STATE_NEUTRAL; } } return (NULL); } char * gfs_server_command_io(struct xxx_connection *client, struct timeval *timeout) { volatile int nfound; int max_fd, conn_fd = xxx_connection_fd(client); fd_set readable, writable; char *e; if (server_command_context.server_state == GFS_COMMAND_SERVER_STATE_EXITED) return (NULL); max_fd = -1; FD_ZERO(&readable); FD_ZERO(&writable); gfs_server_command_fd_set(client, &readable, &writable, &max_fd); /* * We wait for either SIGCHLD or select(2) event here, * and use siglongjmp(3) to avoid a race condition about the signal. * * The race condition happens, if the SIGCHLD signal is delivered * after the if-statement which does FD_SET(conn_fd, writable) in * gfs_server_command_fd_set(), and before the select(2) below. * In that condition, the following select(2) may wait that the * `conn_fd' becomes readable, and because it may never happan, * it waits forever (i.e. both gfrcmd and gfsd wait each other * forever), and hangs, unless there is the sigsetjmp()/siglongjmp() * handling. * * If the SIGCHLD is delivered inside the select(2) system call, * the problem doesn't happen, because select(2) will return * with EINTR. * * Also, if the SIGCHLD is delivered before an EOF from either * cc->iobuffer[FDESC_STDOUT] or cc->iobuffer[FDESC_STDERR], * the problem doesn't happen, either. Because the select(2) * will be woken up by the EOF. But actually the SIGCHLD is * delivered after the EOF (of both FDESC_STDOUT and FDESC_STDERR, * and even after the EOFs are reported to a client) at least * on linux-2.4.21-pre4. */ nfound = -1; errno = EINTR; if (sigsetjmp(sigchld_jmp_buf, 1) == 0) { sigchld_jmp_needed = 1; /* * Here, we have to wait until the `conn_fd' is writable, * if this is !COMMAND_IS_RUNNING() case. */ if (COMMAND_IS_RUNNING() || FD_ISSET(conn_fd, &writable)) { nfound = select(max_fd + 1, &readable, &writable, NULL, timeout); } } sigchld_jmp_needed = 0; if (nfound > 0) e = gfs_server_command_io_fd_set(client, &readable, &writable); else e = NULL; return (e); } char * gfs_server_client_command_result(struct xxx_connection *client) { struct gfs_server_command_context *cc = &server_command_context; gfarm_int32_t cmd, fd, len, sig; int finish, eof; char *e; while (cc->server_state != GFS_COMMAND_SERVER_STATE_EXITED) gfs_server_command_io(client, NULL); /* * Now, we recover the connection file descriptor blocking mode. */ if (fcntl(xxx_connection_fd(client), F_SETFL, 0) == -1) gflog_warning("command-result:block", strerror(errno)); /* make cc->client_state neutral */ if (cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT) { e = xxx_proto_purge(client, 0, cc->client_output_residual); if (e != NULL) fatal_proto("command_fd_input:purge", e); } for (finish = 0; !finish; ) { e = xxx_proto_recv(client, 0, &eof, "i", &cmd); if (e != NULL) fatal_proto("command:client subcommand", e); if (eof) fatal_proto("command:client subcommand", "eof"); switch (cmd) { case GFS_PROTO_COMMAND_EXIT_STATUS: finish = 1; break; case GFS_PROTO_COMMAND_SEND_SIGNAL: e = xxx_proto_recv(client, 0, &eof, "i", &sig); if (e != NULL) fatal_proto("command_send_signal", e); if (eof) fatal_proto("command_send_signal","eof"); break; case GFS_PROTO_COMMAND_FD_INPUT: e = xxx_proto_recv(client, 0, &eof, "ii", &fd, &len); if (e != NULL) fatal_proto("command_fd_input", e); if (eof) fatal_proto("command_fd_input", "eof"); if (fd != FDESC_STDIN) { /* XXX - something wrong */ fatal_proto("command_fd_input", "fd"); } e = xxx_proto_purge(client, 0, len); if (e != NULL) fatal_proto("command_fd_input:purge", e); break; default: /* XXX - something wrong */ fatal_proto("command_io", "unknown subcommand"); break; } } gfs_server_put_reply(client, "command:exit_status", GFS_ERROR_NOERROR, "iii", WIFEXITED(cc->status) ? 0 : WTERMSIG(cc->status), WIFEXITED(cc->status) ? WEXITSTATUS(cc->status) : 0, WIFEXITED(cc->status) ? 0 : WCOREDUMP(cc->status)); return (NULL); } void gfs_server_command(struct xxx_connection *client, char *cred_env) { struct gfs_server_command_context *cc = &server_command_context; gfarm_int32_t argc, nenv, flags, error; char *path, *command, **argv_storage, **argv, **envp, *xauth; int stdin_pipe[2], stdout_pipe[2], stderr_pipe[2]; int conn_fd = xxx_connection_fd(client); int i, eof; socklen_t siz; char *e = NULL; char *user, *home, *shell; char *user_env, *home_env, *shell_env, *xauth_env; /* cred_end */ static char user_format[] = "USER=%s"; static char home_format[] = "HOME=%s"; static char shell_format[] = "SHELL=%s"; static char path_env[] = DEFAULT_PATH; #define N_EXTRA_ENV 4 /* user_env, home_env, shell_env, path_env */ int use_cred_env = cred_env != NULL ? 1 : 0; static char xauth_format[] = "XAUTHORITY=%s"; static char xauth_template[] = "/tmp/.xaXXXXXX"; static char xauth_filename[sizeof(xauth_template)]; int use_xauth_env = 0; #ifdef __GNUC__ /* workaround gcc warning: unused variable */ envp = NULL; xauth_env = NULL; #endif gfs_server_get_request(client, "command", "siii", &path, &argc, &nenv, &flags); if ((flags & GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) != 0) { /* "$SHELL" + "-c" */ argv_storage = malloc(sizeof(char *) * (argc + 3)); argv = argv_storage + 2; } else { argv_storage = malloc(sizeof(char *) * (argc + 1)); argv = argv_storage; } if (argv_storage == NULL) { e = GFARM_ERR_NO_MEMORY; goto rpc_error; } if ((flags & GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY) != 0) use_xauth_env = 1; envp = malloc(sizeof(char *) * (nenv + N_EXTRA_ENV + use_cred_env + use_xauth_env + 1)); if (envp == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_argv; } user = gfarm_get_local_username(); home = gfarm_get_local_homedir(); user_env = malloc(sizeof(user_format) + strlen(user)); if (user_env == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_envp; } sprintf(user_env, user_format, user); home_env = malloc(sizeof(home_format) + strlen(home)); if (home_env == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_user_env; } sprintf(home_env, home_format, home); shell = getpwnam(user)->pw_shell; /* XXX - this shouldn't fail */ if (*shell == '\0') shell = PATH_BSHELL; if ((flags & GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) == 0) { /* * SECURITY. * disallow anyone who doesn't have a standard shell. */ char *s; while ((s = getusershell()) != NULL) if (strcmp(s, shell) == 0) break; endusershell(); if (s == NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto free_home_env; } } shell_env = malloc(sizeof(shell_format) + strlen(shell)); if (shell_env == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_home_env; } sprintf(shell_env, shell_format, shell); argv[argc] = envp[nenv + N_EXTRA_ENV + use_cred_env + use_xauth_env] = NULL; envp[nenv + 0] = user_env; envp[nenv + 1] = home_env; envp[nenv + 2] = shell_env; envp[nenv + 3] = path_env; for (i = 0; i < argc; i++) { e = xxx_proto_recv(client, 0, &eof, "s", &argv[i]); if (e != NULL || eof) { while (--i >= 0) free(argv[i]); goto free_shell_env; } } for (i = 0; i < nenv; i++) { e = xxx_proto_recv(client, 0, &eof, "s", &envp[i]); if (e != NULL || eof) { while (--i >= 0) free(envp[i]); goto free_argv_array; } } if ((flags & GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) != 0) { argv_storage[0] = shell; argv_storage[1] = "-c"; argv[1] = NULL; /* ignore argv[1 ... argc - 1] in this case. */ command = shell; } else { command = path; } if (use_cred_env) envp[nenv + N_EXTRA_ENV] = cred_env; if (use_xauth_env) { static char xauth_command_format[] = "%s %s nmerge - 2>/dev/null"; char *xauth_command; FILE *fp; int xauth_fd; e = xxx_proto_recv(client, 0, &eof, "s", &xauth); if (e != NULL || eof) goto free_envp_array; /* * don't touch $HOME/.Xauthority to avoid lock contention * on NFS home. (Is this really better? XXX) */ xauth_fd = mkstemp(strcpy(xauth_filename, xauth_template)); if (xauth_fd == -1) goto free_xauth; close(xauth_fd); xauth_env = malloc(sizeof(xauth_format) + sizeof(xauth_filename)); if (xauth_env == NULL) goto remove_xauth; sprintf(xauth_env, xauth_format, xauth_filename); envp[nenv + N_EXTRA_ENV + use_cred_env] = xauth_env; xauth_command = malloc(sizeof(xauth_command_format) + strlen(xauth_env) + strlen(XAUTH_COMMAND)); if (xauth_command == NULL) goto free_xauth_env; sprintf(xauth_command, xauth_command_format, xauth_env, XAUTH_COMMAND); if ((fp = popen(xauth_command, "w")) == NULL) goto free_xauth_env; fputs(xauth, fp); pclose(fp); free(xauth_command); } if (pipe(stdin_pipe) == -1) { e = gfarm_errno_to_error(errno); goto free_xauth_env; } if (pipe(stdout_pipe) == -1) { e = gfarm_errno_to_error(errno); goto close_stdin_pipe; } if (pipe(stderr_pipe) == -1) { e = gfarm_errno_to_error(errno); goto close_stdout_pipe; } cc->pid = cc->exited_pid = 0; if ((cc->pid = fork()) == 0) { struct rlimit rlim; /* * XXX - Some Linux distributions set coredump size 0 * by default. */ if (getrlimit(RLIMIT_CORE, &rlim) != -1) { rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_CORE, &rlim); } /* child */ dup2(stdin_pipe[0], 0); dup2(stdout_pipe[1], 1); dup2(stderr_pipe[1], 2); close(stderr_pipe[1]); close(stderr_pipe[0]); close(stdout_pipe[1]); close(stdout_pipe[0]); close(stdin_pipe[1]); close(stdin_pipe[0]); /* close client connection, syslog and other sockets */ for (i = 3; i < stderr_pipe[1]; i++) close(i); /* re-install default signal handler (see main) */ signal(SIGPIPE, SIG_DFL); setpgid(0, getpid()); execve(command, argv_storage, envp); fprintf(stderr, "%s: ", gfarm_host_get_self_name()); perror(path); _exit(1); } else if (cc->pid == -1) { e = gfarm_errno_to_error(errno); goto close_stderr_pipe; } close(stderr_pipe[1]); close(stdout_pipe[1]); close(stdin_pipe[0]); error = GFS_ERROR_NOERROR; goto rpc_reply; close_stderr_pipe: close(stderr_pipe[0]); close(stderr_pipe[1]); close_stdout_pipe: close(stdout_pipe[0]); close(stdout_pipe[1]); close_stdin_pipe: close(stdin_pipe[0]); close(stdin_pipe[1]); free_xauth_env: if (use_xauth_env) free(xauth_env); remove_xauth: if (use_xauth_env) unlink(xauth_filename); free_xauth: if (use_xauth_env) free(xauth); free_envp_array: for (i = 0; i < nenv; i++) free(envp[i]); free_argv_array: for (i = 0; i < argc; i++) free(argv[i]); free_shell_env: free(shell_env); free_home_env: free(home_env); free_user_env: free(user_env); free_envp: free(envp); free_argv: free(argv_storage); rpc_error: free(path); error = gfs_string_to_proto_error(e); rpc_reply: gfs_server_put_reply(client, "command-start", error, "i", cc->pid); xxx_proto_flush(client); if (error != GFS_ERROR_NOERROR) return; /* * Now, we set the connection file descriptor non-blocking mode. */ if (fcntl(conn_fd, F_SETFL, O_NONBLOCK) == -1) /* shouldn't fail */ gflog_warning("command-start:nonblock", strerror(errno)); siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_RCVBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDIN] = gfarm_iobuffer_alloc(i); siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_SNDBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDOUT] = gfarm_iobuffer_alloc(i); cc->iobuffer[FDESC_STDERR] = gfarm_iobuffer_alloc(i); gfarm_iobuffer_set_nonblocking_read_xxx( cc->iobuffer[FDESC_STDIN], client); gfarm_iobuffer_set_nonblocking_write_fd( cc->iobuffer[FDESC_STDIN], stdin_pipe[1]); gfarm_iobuffer_set_nonblocking_read_fd( cc->iobuffer[FDESC_STDOUT], stdout_pipe[0]); gfarm_iobuffer_set_nonblocking_write_xxx( cc->iobuffer[FDESC_STDOUT], client); gfarm_iobuffer_set_nonblocking_read_fd( cc->iobuffer[FDESC_STDERR], stderr_pipe[0]); gfarm_iobuffer_set_nonblocking_write_xxx( cc->iobuffer[FDESC_STDERR], client); while (cc->server_state != GFS_COMMAND_SERVER_STATE_EXITED) gfs_server_command_io(client, NULL); gfs_server_client_command_result(client); /* * clean up */ gfarm_iobuffer_free(cc->iobuffer[FDESC_STDIN]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDOUT]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDERR]); close(stderr_pipe[0]); close(stdout_pipe[0]); close(stdin_pipe[1]); if (use_xauth_env) { free(xauth_env); unlink(xauth_filename); free(xauth); } for (i = 0; i < nenv; i++) free(envp[i]); for (i = 0; i < argc; i++) free(argv[i]); free(envp); free(argv_storage); free(path); } void server(int client_fd) { char *e; struct xxx_connection *client; int eof; gfarm_int32_t request; char buffer[GFARM_INT32STRLEN]; /* XXX - kluge for gfrcmd (to mkdir HOME....) for now */ chdir(gfarm_spool_root); e = xxx_fd_connection_new(client_fd, &client); if (e != NULL) { close(client_fd); gflog_fatal("xxx_connection_new", e); } /* * The following function switches deamon's privilege * to the authenticated user. * This also enables gfarm_get_global_username() and * gfarm_get_local_homedir() which are necessary for * gfs_client_connect() called from gfs_server_replicate_file(). */ e = gfarm_authorize(client, 1, NULL, NULL); if (e != NULL) gflog_fatal("gfarm_authorize", e); for (;;) { e = xxx_proto_recv(client, 0, &eof, "i", &request); if (e != NULL) fatal_proto("request number", e); if (eof) { cleanup(); exit(0); } switch (request) { case GFS_PROTO_OPEN: gfs_server_open(client); break; case GFS_PROTO_CLOSE: gfs_server_close(client); break; case GFS_PROTO_SEEK: gfs_server_seek(client); break; case GFS_PROTO_READ: gfs_server_read(client); break; case GFS_PROTO_WRITE: gfs_server_write(client); break; case GFS_PROTO_UNLINK: gfs_server_unlink(client); break; case GFS_PROTO_MKDIR: gfs_server_mkdir(client); break; case GFS_PROTO_RMDIR: gfs_server_rmdir(client); break; case GFS_PROTO_CHMOD: gfs_server_chmod(client); break; case GFS_PROTO_CHGRP: gfs_server_chgrp(client); break; case GFS_PROTO_DIGEST: gfs_server_digest(client); break; case GFS_PROTO_GET_SPOOL_ROOT: gfs_server_get_spool_root(client); break; case GFS_PROTO_BULKREAD: gfs_server_bulkread(client); break; case GFS_PROTO_STRIPING_READ: gfs_server_striping_read(client); break; case GFS_PROTO_REPLICATE_FILE_SEQUENTIAL: gfs_server_replicate_file_sequential(client); break; case GFS_PROTO_REPLICATE_FILE_PARALLEL: gfs_server_replicate_file_parallel(client); break; case GFS_PROTO_CHDIR: gfs_server_chdir(client); break; case GFS_PROTO_COMMAND: if (credential_exported == NULL) { e = xxx_connection_export_credential(client); if (e == NULL) credential_exported = client; else gflog_warning( "export delegated credential", e); } gfs_server_command(client, credential_exported == NULL ? NULL : xxx_connection_env_for_credential(client)); break; default: sprintf(buffer, "%d", (int)request); gflog_warning("unknown request", buffer); cleanup(); exit(1); } } } void datagram_server(int sock) { int rv; struct sockaddr_in client_addr; socklen_t client_addr_size = sizeof(client_addr); double loadavg[3]; #ifndef WORDS_BIGENDIAN struct { char c[8]; } nloadavg[3]; #else # define nloadavg loadavg #endif char buffer[1024]; rv = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_addr_size); if (rv == -1) return; rv = getloadavg(loadavg, GFARM_ARRAY_LENGTH(loadavg)); if (rv == -1) { gflog_warning("datagram_server", "cannot get load average"); return; } #ifndef WORDS_BIGENDIAN swab(&loadavg[0], &nloadavg[0], sizeof(nloadavg[0])); swab(&loadavg[1], &nloadavg[1], sizeof(nloadavg[1])); swab(&loadavg[2], &nloadavg[2], sizeof(nloadavg[2])); #endif rv = sendto(sock, nloadavg, sizeof(nloadavg), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); } int open_accepting_socket(int port) { char *e; struct sockaddr_in self_addr; socklen_t self_addr_size; int sock, sockopt; memset(&self_addr, 0, sizeof(self_addr)); self_addr.sin_family = AF_INET; self_addr.sin_addr.s_addr = INADDR_ANY; self_addr.sin_port = htons(port); self_addr_size = sizeof(self_addr); sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) gflog_fatal_errno("accepting socket"); sockopt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) == -1) gflog_warning_errno("SO_REUSEADDR"); if (bind(sock, (struct sockaddr *)&self_addr, self_addr_size) < 0) gflog_fatal_errno("bind accepting socket"); e = gfarm_sockopt_apply_listener(sock); if (e != NULL) gflog_warning("setsockopt", e); if (listen(sock, LISTEN_BACKLOG) < 0) gflog_fatal_errno("listen"); return (sock); } void open_datagram_service_sockets(int port, int *countp, int **socketsp) { char *e; int i, self_addresses_count, *sockets, s; struct in_addr *self_addresses; struct sockaddr_in bind_addr; socklen_t bind_addr_size; e = gfarm_get_ip_addresses(&self_addresses_count, &self_addresses); if (e != NULL) gflog_fatal("get_ip_addresses", e); sockets = malloc(sizeof(*sockets) * self_addresses_count); if (sockets == NULL) gflog_fatal_errno("malloc datagram sockets"); for (i = 0; i < self_addresses_count; i++) { memset(&bind_addr, 0, sizeof(bind_addr)); bind_addr.sin_family = AF_INET; bind_addr.sin_addr = self_addresses[i]; bind_addr.sin_port = ntohs(port); bind_addr_size = sizeof(bind_addr); s = socket(PF_INET, SOCK_DGRAM, 0); if (s < 0) gflog_fatal_errno("datagram socket"); if (bind(s, (struct sockaddr *)&bind_addr, bind_addr_size) < 0) gflog_fatal_errno("datagram bind"); sockets[i] = s; } *countp = self_addresses_count; *socketsp = sockets; free(self_addresses); } void usage(void) { fprintf(stderr, "Usage: %s [option]\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-p <port>\n"); fprintf(stderr, "\t-r rsh invocation (not deadmon)\n"); exit(1); } int main(int argc, char **argv) { extern char *optarg; extern int optind; struct sockaddr_in client_addr; socklen_t client_addr_size; char *e, *config_file = NULL, *port_number = NULL; int syslog_facility = GFARM_DEFAULT_FACILITY; int ch, table_size, datagram_socks_count, i, nfound; int accepting_sock, *datagram_socks, client, max_fd; struct sigaction sa; fd_set requests; if (argc >= 1) program_name = basename(argv[0]); gflog_set_identifier(program_name); while ((ch = getopt(argc, argv, "df:p:s:u")) != -1) { switch (ch) { case 'd': debug_mode = 1; break; case 'f': config_file = optarg; break; case 'p': port_number = optarg; break; case 's': syslog_facility = gflog_syslog_name_to_facility(optarg); if (syslog_facility == -1) gflog_fatal(optarg, "unknown syslog facility"); break; case 'u': restrict_user = 1; restricted_user = getuid(); break; case '?': default: usage(); } } argc -= optind; argv += optind; if (config_file != NULL) gfarm_config_set_filename(config_file); e = gfarm_server_initialize(); if (e != NULL) { fprintf(stderr, "gfarm_server_initialize: %s\n", e); exit(1); } if (port_number != NULL) gfarm_spool_server_port = strtol(port_number, NULL, 0); accepting_sock = open_accepting_socket(gfarm_spool_server_port); open_datagram_service_sockets(gfarm_spool_server_port, &datagram_socks_count, &datagram_socks); max_fd = accepting_sock; for (i = 0; i < datagram_socks_count; i++) { if (max_fd < datagram_socks[i]) max_fd = datagram_socks[i]; } if (max_fd > FD_SETSIZE) gflog_fatal("datagram_service", "too big file descriptor"); if (!debug_mode) { gflog_syslog_open(LOG_PID, syslog_facility); gfarm_daemon(0, 0); } table_size = FILE_TABLE_LIMIT; gfarm_unlimit_nofiles(&table_size); if (table_size > FILE_TABLE_LIMIT) table_size = FILE_TABLE_LIMIT; file_table_init(table_size); SSLeay_add_all_algorithms(); /* for EVP_get_digestbyname() */ /* * Because SA_NOCLDWAIT is not implemented on some OS, * we do not rely on the feature. */ sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_NOCLDSTOP; sigaction(SIGCHLD, &sa, NULL); /* * We don't want SIGPIPE, but want EPIPE on write(2)/close(2). */ signal(SIGPIPE, SIG_IGN); for (;;) { FD_ZERO(&requests); FD_SET(accepting_sock, &requests); for (i = 0; i < datagram_socks_count; i++) FD_SET(datagram_socks[i], &requests); nfound = select(max_fd + 1, &requests, NULL, NULL, NULL); if (nfound <= 0) { if (nfound == 0 || errno == EINTR || errno == EAGAIN) continue; gflog_fatal_errno("select"); } if (FD_ISSET(accepting_sock, &requests)) { client_addr_size = sizeof(client_addr); client = accept(accepting_sock, (struct sockaddr *)&client_addr, &client_addr_size); if (client < 0) { if (errno == EINTR) continue; gflog_fatal_errno("accept"); } #ifndef GFSD_DEBUG switch (fork()) { case 0: #endif close(accepting_sock); for (i = 0; i < datagram_socks_count; i++) close(datagram_socks[i]); e = gfarm_netparam_config_get_long( &gfarm_netparam_rate_limit, NULL, (struct sockaddr *)&client_addr, &rate_limit); if (e != NULL) /* shouldn't happen */ gflog_warning("rate_limit", e); server(client); /*NOTREACHED*/ #ifndef GFSD_DEBUG case -1: gflog_warning_errno("fork"); /*FALLTHROUGH*/ default: close(client); break; } #endif } for (i = 0; i < datagram_socks_count; i++) { if (FD_ISSET(datagram_socks[i], &requests)) datagram_server(datagram_socks[i]); } } /*NOTREACHED*/ return (0); /* to shut up warning */ } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_5/xattr.c /* * $Id$ */ #include "config.h" #include <string.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm2fs.h" #include "acl.h" #include "xattr.h" struct gfarm2fs_xattr_sw { gfarm_error_t (*set)(const char *path, const char *name, const void *value, size_t size, int flags); gfarm_error_t (*get)(const char *path, const char *name, void *value, size_t *sizep); gfarm_error_t (*remove)(const char *path, const char *name); }; #define XATTR_IS_SUPPORTTED(name) \ (strncmp(name, "gfarm.", 6) == 0 || \ strncmp(name, "gfarm_root.", 11) == 0 || \ strncmp(name, "user.", 5) == 0) #ifdef ENABLE_GFARM_ACL /* ------------------------------- */ static gfarm_error_t normal_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_ACCESS, value, size)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_DEFAULT, value, size)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t normal_get(const char *path, const char *name, void *value, size_t *sizep) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_ACCESS, value, sizep)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_DEFAULT, value, sizep)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t normal_remove(const char *path, const char *name) { if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_ACCESS)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_DEFAULT)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_normal = { normal_set, normal_get, normal_remove, }; /* ------------------------------- */ /* for gfarm2fs_fix_acl command */ static gfarm_error_t fix_acl_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (strcmp(name, FIX_ACL_ACCESS) == 0 || strcmp(name, FIX_ACL_DEFAULT) == 0) return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_ACCESS, value, size)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_set(path, GFARM_ACL_TYPE_DEFAULT, value, size)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t fix_acl_get(const char *path, const char *name, void *value, size_t *sizep) { if (strcmp(name, FIX_ACL_ACCESS) == 0) return (gfs_lgetxattr_cached(path, ACL_EA_ACCESS, value, sizep)); else if (strcmp(name, FIX_ACL_DEFAULT) == 0) return (gfs_lgetxattr_cached(path, ACL_EA_DEFAULT, value, sizep)); else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_ACCESS, value, sizep)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfarm2fs_acl_get(path, GFARM_ACL_TYPE_DEFAULT, value, sizep)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t fix_acl_remove(const char *path, const char *name) { if (strcmp(name, FIX_ACL_ACCESS) == 0) return (gfs_lremovexattr(path, ACL_EA_ACCESS)); else if (strcmp(name, FIX_ACL_DEFAULT) == 0) return (gfs_lremovexattr(path, ACL_EA_DEFAULT)); else if (strcmp(name, ACL_EA_ACCESS) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_ACCESS)); else if (strcmp(name, ACL_EA_DEFAULT) == 0) return (gfs_lremovexattr(path, GFARM_ACL_EA_DEFAULT)); else if (XATTR_IS_SUPPORTTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_fix_acl = { fix_acl_set, fix_acl_get, fix_acl_remove, }; #endif /* ENABLE_GFARM_ACL */ /* ------------------------------- */ static gfarm_error_t disable_acl_set(const char *path, const char *name, const void *value, size_t size, int flags) { if (XATTR_IS_SUPPORTTED(name)) return (gfs_lsetxattr(path, name, value, size, flags)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static gfarm_error_t disable_acl_get(const char *path, const char *name, void *value, size_t *sizep) { if (XATTR_IS_SUPPORTTED(name)) return (gfs_lgetxattr_cached(path, name, value, sizep)); else return (GFARM_ERR_NO_SUCH_OBJECT); /* ENODATA */ } static gfarm_error_t disable_acl_remove(const char *path, const char *name) { if (XATTR_IS_SUPPORTTED(name)) return (gfs_lremovexattr(path, name)); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); /* EOPNOTSUPP */ } static struct gfarm2fs_xattr_sw sw_disable_acl = { disable_acl_set, disable_acl_get, disable_acl_remove, }; /* ------------------------------- */ static struct gfarm2fs_xattr_sw *funcs = &sw_disable_acl; gfarm_error_t gfarm2fs_xattr_set(const char *path, const char *name, const void *value, size_t size, int flags) { return ((*funcs->set)(path, name, value, size, flags)); } gfarm_error_t gfarm2fs_xattr_get(const char *path, const char *name, void *value, size_t *sizep) { return ((*funcs->get)(path, name, value, sizep)); } gfarm_error_t gfarm2fs_xattr_remove(const char *path, const char *name) { return ((*funcs->remove)(path, name)); } void gfarm2fs_xattr_init(struct gfarm2fs_param *params) { #ifdef ENABLE_GFARM_ACL if (params->disable_acl) funcs = &sw_disable_acl; else if (params->fix_acl) funcs = &sw_fix_acl; else { funcs = &sw_normal; gfarm_xattr_caching_pattern_add(GFARM_ACL_EA_ACCESS); gfarm_xattr_caching_pattern_add(GFARM_ACL_EA_DEFAULT); } #endif } <file_sep>/gfarmfs-fuse/trunk/contrib/Makefile.am SUBDIRS = gfarmfs-exec mount.gfarmfs <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_5/contrib/mount.gfarm2fs/mount.gfarm2fs.in #!/bin/sh # # $Id$ prefix=@prefix@ exec_prefix=@exec_prefix@ export PATH=@bindir@:$PATH USAGE() { cat <<EOF mount.gfarm2fs [ configuration_file mount_point options ] options: username effective local user name to mount gfarmfs_root directory to be mounted in Gfarm allow_root allow root to access allow_other allow everyone to access ro mount the file system read-only Environment variable: GFS_USERNAME global user name in Gfarm GFS_MOUNTDIR mount point GFARMFS_ROOT directory to be mounted in Gfarm GFARMFS_OPTIONS gfarmfs mount options FUSE_OPTIONS fuse mount options When mount.gfarm2fs is installed to /sbin/mount.gfarm2fs, you can mount the Gfarm file system by mount(8) and automount(8). Example of /etc/fstab entries: /etc/gfarm2.conf /gfarm/tatebe gfarm2fs noauto,user,username=tatebe 0 0 Example of /etc/auto.master entries: /gfarm /etc/auto.gfarm Example of /etc/auto.gfarm entries: tatebe -fstype=gfarm2fs,username=tatebe :/home/tatebe/.gfarm2rc * -fstype=gfarm2fs,username=& :/home/&/.gfarm2rc EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then GFARM_ENV="env GFARM_CONFIG_FILE=$1 PATH=$PATH" shift fi if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi if [ $# -gt 0 ]; then [ x"$1" = x"-o" ] && shift OPTIONS=$* fi SAVE_IFS=$IFS IFS=, for o in $OPTIONS do case $o in # mount.gfarm2fs options username=*) : ${GFARMFS_USERNAME:=`echo $o | sed -n 's/username=//p'`} ;; gfarmfs_root=*) : ${GFARMFS_ROOT:=`echo $o | sed -n 's/gfarmfs_root=//p'`} ;; # Gfarm2fs options gfs_stat_timeout=*|\ syslog=*|loglevel=*|\ ncopy=*|copy_limit=*|\ genuine_nlink|disable_genuine_nlink|\ auto_uid_min=*|auto_uid_max=*|\ auto_gid_min=*|auto_gid_max=*) [ x"$GFARMFS_OPTIONS" = x ] && GFARMFS_OPTIONS="-o " || GFARMFS_OPTIONS="$GFARMFS_OPTIONS," GFARMFS_OPTIONS="$GFARMFS_OPTIONS$o" ;; # FUSE options ro|rw|\ debug|allow_other|allow_root|\ nonempty|default_permissions|\ fsname=*|subtype=*|\ large_read|max_read=*|\ hard_remove|use_ino|readdir_ino|\ direct_io|kernel_cache|auto_cache|noauto_cache|\ umask=*|uid=*|gid=*|\ entry_timeout=*|negative_timeout=*|\ attr_timeout=*|ac_attr_timeout=*|\ intr|intr_signal=*|\ modules=*|\ max_write=*|max_readahead=*|async_read|sync_read|\ atomic_o_trunc|\ subdir=*|rellinks|norellinks|\ from_code=*|to_code=*) [ x"$FUSE_OPTIONS" = x ] && FUSE_OPTIONS="-o " || FUSE_OPTIONS="$FUSE_OPTIONS," FUSE_OPTIONS="$FUSE_OPTIONS$o" ;; esac done IFS=$SAVE_IFS [ -x /sbin/runuser ] && SU=/sbin/runuser || SU=su if [ -w / -a X"$GFARMFS_USERNAME" != X ]; then RUN="$SU -l $GFARMFS_USERNAME" if $RUN --session-command=hostname >/dev/null 2>&1; then RUN="$RUN --session-command=" else RUN="$RUN -c " fi else RUN="/bin/sh -c " fi # default value : ${GFS_USERNAME:=`$RUN"$GFARM_ENV gfwhoami 2>/dev/null"`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2>/dev/null`} : ${GFS_MOUNTDIR:=/tmp/$GFS_USERNAME} : ${GFARMFS_ROOT:=`$RUN"$GFARM_ENV gfuser -l $GFS_USERNAME 2>/dev/null" | awk -F: '{ print $3 }'`} : ${GFARMFS_ROOT:=/} : ${GFARMFS_OPTIONS:=} : ${FUSE_OPTIONS:=} # copy proxy cert to default location and unset X509_USER_PROXY : ${UID:=`id -u`} X509_PROXY=/tmp/x509up_u$UID if [ X"$X509_USER_PROXY" != X -a -f "$X509_USER_PROXY" -a "$X509_USER_PROXY" != "$X509_PROXY" ]; then cmp "$X509_USER_PROXY" "$X509_PROXY" > /dev/null 2>&1 || { cp -p "$X509_USER_PROXY" "$X509_PROXY".tmp && mv "$X509_PROXY".tmp "$X509_PROXY" && unset X509_USER_PROXY && echo Update proxy certificate for gfarm2fs } fi # if already mounted, exit awk '{ print $2 }' /etc/mtab | grep "^$GFS_MOUNTDIR$" >/dev/null && ABORT "$GFS_MOUNTDIR: already mounted" DELETE_MOUNTDIR_ON_ERROR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR_ON_ERROR=1 fi [ -w / -o -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME # if username is specified, change the owner of the mount point if [ -w / ]; then if [ X"$GFARMFS_USERNAME" != X ]; then chown $GFARMFS_USERNAME $GFS_MOUNTDIR chmod +w $GFS_MOUNTDIR fi fi # mount $RUN"$GFARM_ENV gfarm2fs -o modules=subdir,subdir=$GFARMFS_ROOT $GFARMFS_OPTIONS $GFS_MOUNTDIR $FUSE_OPTIONS" STATUS=$? if [ $STATUS = 0 ]; then [ -w / ] || echo Mount GfarmFS on $GFS_MOUNTDIR else [ $DELETE_MOUNTDIR_ON_ERROR = 1 ] && rmdir $GFS_MOUNTDIR fi exit $STATUS <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_gfsd_gfsched.sh.in #! /bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on gfsd hosts. # It tries executing 'gfsched' to check the current availability # of 'gfsd' on that host. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # GFSD_HOSTNAMES=$1 if [ "X$GFSD_HOSTNAMES" = X -o "X$GFSD_HOSTNAMES" = X- ]; then GFSD_HOSTNAMES=`hostname -f` fi # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile=/tmp/gfarm_gfsd_gfsched.out.$$ errfile=/tmp/gfarm_gfsd_gfsched.err.$$ trap "rm -f $outfile $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile $errfile for GFSD_HOSTNAME in $GFSD_HOSTNAMES; do # # Execute 'gfsched'. # GFCMD="@GFARM_BINDIR@/gfsched -M -D $GFSD_HOSTNAME" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > $outfile 2> $errfile GFCMD_EXITCODE=$? # # We ignore timeout. The timeout is caused by network trouble or high # load of the gfsd host, but those troubles are also detected by other # monitoring items. # if [ $GFCMD_EXITCODE -ne 0 -a $GFCMD_EXITCODE -ne $TIMEOUT_EXITCODE ]; then echo "'$GFCMD' failed" log_err "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi done echo "ok" rm -f $outfile $errfile exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfmdtype_gfmd.sh #!/bin/sh # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_gfarm.conf # Chekc Config File if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command if [ X"$MY_HOST" = X ]; then MY_HOST=`hostname` fi if [ -f $MDS_LIST_PATH ]; then CHK=`grep '^+ master' $MDS_LIST_PATH | awk '{ print $6 }' | grep $MY_HOST` if [ X$CHK != X ]; then RESULT="master" else RESULT="slave" fi else RESULT="error: $MDS_LIST_PATH not found." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_1_1/util/ptool/Makefile top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk SCRIPTS= $(srcdir)/pcat $(srcdir)/pcp $(srcdir)/pdel $(srcdir)/pdist $(srcdir)/prun include $(top_srcdir)/makes/script.mk <file_sep>/gfarm/tags/gfarm_1_0_beta_3_rev_2/lib/libgfarm/gfsl/Makefile # $Id$ top_objdir = ../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk # PURE = /usr/local/rational/releases/purify.sol.2001a.04.00/purify PROGRAMS = server client server2 client2 SCOBJS = scsub.o CFLAGS = $(COMMON_CFLAGS) -I$(GFSL_SRCDIR) $(globus_includes) \ -DGLOBUS_BUG=1 # see gsi.c LDLIBS = $(COMMON_LDFLAGS) $(GFARMLIB) $(LIBS) all: $(PROGRAMS) server: server.o $(SCOBJS) $(DEPGFARMLIB) rm -f $@ $(PURE) $(CC) $(CFLAGS) -o $@ server.o $(SCOBJS) $(LDLIBS) client: client.o $(SCOBJS) $(DEPGFARMLIB) rm -f $@ $(PURE) $(CC) $(CFLAGS) -o $@ client.o $(SCOBJS) $(LDLIBS) server2: server2.o $(DEPGFARMLIB) rm -f $@ $(PURE) $(CC) $(CFLAGS) -o $@ server2.o $(LDLIBS) client2: client2.o $(DEPGFARMLIB) rm -f $@ $(PURE) $(CC) $(CFLAGS) -o $@ client2.o $(LDLIBS) clean: $(RM) -f $(PROGRAMS) *.o *~ core *.core distclean: clean # don't install anything install: gfregister: man: html: <file_sep>/gfarm/tags/gfarm_1_0_beta_5/lib/libgfarm/gfutil/timeval.c #include <sys/time.h> #include "gfutil.h" int gfarm_timeval_cmp(const struct timeval *t1, const struct timeval *t2) { if (t1->tv_sec > t2->tv_sec) return (1); if (t1->tv_sec < t2->tv_sec) return (-1); if (t1->tv_usec > t2->tv_usec) return (1); if (t1->tv_usec < t2->tv_usec) return (-1); return (0); } static void gfarm_timeval_normalize(struct timeval *t) { long n; if (t->tv_usec >= GFARM_SECOND_BY_MICROSEC) { n = t->tv_usec / GFARM_SECOND_BY_MICROSEC; t->tv_usec -= n * GFARM_SECOND_BY_MICROSEC; t->tv_sec += n; } else if (t->tv_usec < 0) { n = -t->tv_usec / GFARM_SECOND_BY_MICROSEC + 1; t->tv_usec += n * GFARM_SECOND_BY_MICROSEC; t->tv_sec -= n; } } void gfarm_timeval_add(struct timeval *t1, const struct timeval *t2) { t1->tv_sec += t2->tv_sec; t1->tv_usec += t2->tv_usec; gfarm_timeval_normalize(t1); } void gfarm_timeval_sub(struct timeval *t1, const struct timeval *t2) { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; gfarm_timeval_normalize(t1); } void gfarm_timeval_add_microsec(struct timeval *t, long microsec) { t->tv_usec += microsec; gfarm_timeval_normalize(t); } <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT3-1-2-2_master_gfmd_and_master_zabbix_agent_down #! /bin/sh ######################################################################## TESTID="FT3-1-2-2" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="gfmd and zabbix agent on master MDS are down" ######################################################################## . ./FT-common ft_setup() { FT_MAIL_TIMEOUT=900 return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd1 sudo /etc/init.d/zabbix-agent stop \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop zabbix-agent on $gfmd" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "zabbix agent is not running on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd ssh $gfmd1 sudo /etc/init.d/zabbix-agent start return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT1-2-3-2_fsn_network_down #! /bin/sh ###################################################################### TESTID="FT1-2-3-2" CATEGORY="accident causes no failover" SECTION="fsn accident" TITLE="network down with slave to fsn" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfsd2_CTRL_ADDRESS sudo $IFDOWN_PATH $gfsd2_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Can't get metadata server master name on $gfsd2" && \ ft_check_mail \ "Gfarm metadata server list is not available on $gfsd2" && \ ft_check_mail \ "Reachability failed on $gfsd2" && \ ft_check_mail \ "Backchannel failed on $gfsd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ssh $gfsd2_CTRL_ADDRESS sudo $IFUP_PATH $gfsd2_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "ifup $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Re: Can't get metadata server master name on $gfsd2" && \ ft_check_mail \ "Re: Gfarm metadata server list is not available on $gfsd2" && \ ft_check_mail \ "Re: Reachability failed on $gfsd2" && \ ft_check_mail \ "Re: Backchannel failed on $gfsd2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { ssh $gfsd2_CTRL_ADDRESS sudo $IFUP_PATH $gfsd2_GFARM_IF return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/libgfarm/gfarm/gfs_pio_section.c /* * pio operations for file fragments or programs * * $Id$ */ #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include <unistd.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include "gfs_pio.h" #include "host.h" #include "schedule.h" #include "gfs_client.h" #include "gfs_proto.h" #include "timer.h" #include "gfs_lock.h" static char * gfs_pio_view_section_close(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; char *e = NULL, *e_save = NULL; int md_calculated = 1; file_offset_t filesize; size_t md_len; unsigned char md_value[EVP_MAX_MD_SIZE]; /* calculate checksum */ if ((gf->mode & GFS_FILE_MODE_CALC_DIGEST) != 0) { if ((gf->mode & GFS_FILE_MODE_WRITE) == 0 && (gf->error != GFS_FILE_ERROR_EOF)) { /* * sequential and read-only case, but * either error occurred or gf doesn't reach EOF, * we don't confirm checksum in this case. */ md_calculated = 0; } else if ((gf->mode & GFS_FILE_MODE_WRITE) != 0 && (gf->open_flags & GFARM_FILE_TRUNC) == 0) { /* we have to read rest of the file in this case */ char message[] = "gfarm: writing without truncation" " isn't supported yet\n"; write(2, message, sizeof(message) - 1); abort(); /* XXX - not supported for now */ } else { unsigned int len; EVP_DigestFinal(&vc->md_ctx, md_value, &len); md_len = len; filesize = gf->offset + gf->length; } } else { if ((gf->mode & GFS_FILE_MODE_WRITE) == 0) { /* * random-access and read-only case, * we don't confirm checksum for this case, * because of its high overhead. */ md_calculated = 0; } else { /* * re-read whole file to calculate digest value * for writing. * note that this effectively breaks file offset. */ e = (*vc->ops->storage_calculate_digest)(gf, GFS_DEFAULT_DIGEST_NAME, sizeof(md_value), &md_len, md_value, &filesize); if (e != NULL) { md_calculated = 0; if (e_save == NULL) e_save = e; } } } if (md_calculated) { int i; char md_value_string[EVP_MAX_MD_SIZE * 2 + 1]; struct gfarm_file_section_info fi; struct gfarm_file_section_copy_info fci; for (i = 0; i < md_len; i++) sprintf(&md_value_string[i + i], "%02x", md_value[i]); if (gf->mode & GFS_FILE_MODE_WRITE) { fi.filesize = filesize; fi.checksum_type = GFS_DEFAULT_DIGEST_NAME; fi.checksum = md_value_string; e = gfarm_file_section_info_set( gf->pi.pathname, vc->section, &fi); if (e == NULL) { fci.hostname = vc->canonical_hostname; e = gfarm_file_section_copy_info_set( gf->pi.pathname, vc->section, fci.hostname, &fci); } } else { e = gfarm_file_section_info_get( gf->pi.pathname, vc->section, &fi); if (filesize != fi.filesize) e = "filesize mismatch"; else if (strcasecmp(fi.checksum_type, GFS_DEFAULT_DIGEST_NAME) != 0 || strcasecmp(fi.checksum, md_value_string) != 0) e = "checksum mismatch"; } } if (e_save == NULL) e_save = e; e = (*vc->ops->storage_close)(gf); if (e_save == NULL) e_save = e; free(vc->canonical_hostname); free(vc->section); free(vc); gf->view_context = NULL; gfs_pio_set_view_default(gf); return (e_save); } static char * gfs_pio_view_section_write(GFS_File gf, const char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; char *e = (*vc->ops->storage_write)(gf, buffer, size, lengthp); if (e == NULL && *lengthp > 0 && (gf->mode & GFS_FILE_MODE_CALC_DIGEST) != 0) EVP_DigestUpdate(&vc->md_ctx, buffer, *lengthp); return (e); } static char * gfs_pio_view_section_read(GFS_File gf, char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; char *e = (*vc->ops->storage_read)(gf, buffer, size, lengthp); if (e == NULL && *lengthp > 0 && (gf->mode & GFS_FILE_MODE_CALC_DIGEST) != 0) EVP_DigestUpdate(&vc->md_ctx, buffer, *lengthp); return (e); } static char * gfs_pio_view_section_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { struct gfs_file_section_context *vc = gf->view_context; gf->mode &= ~GFS_FILE_MODE_CALC_DIGEST; return ((*vc->ops->storage_seek)(gf, offset, whence, resultp)); } static int gfs_pio_view_section_fd(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; return ((*vc->ops->storage_fd)(gf)); } static char * gfs_pio_view_section_stat(GFS_File gf, struct gfs_stat *status) { struct gfs_file_section_context *vc = gf->view_context; struct gfarm_file_section_info sinfo; long ino; char *e; e = gfs_get_ino(gf->pi.pathname, &ino); if (e != NULL) return (e); *status = gf->pi.status; status->st_ino = ino; status->st_user = strdup(status->st_user); if (status->st_user == NULL) return (GFARM_ERR_NO_MEMORY); status->st_group = strdup(status->st_group); if (status->st_group == NULL) { free(status->st_user); return (GFARM_ERR_NO_MEMORY); } status->st_size = 0; status->st_nsections = 1; e = gfarm_file_section_info_get(gf->pi.pathname, vc->section, &sinfo); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* this section is created but not closed yet. */ return (NULL); } else if (e != NULL) { free(status->st_user); free(status->st_group); return (e); } status->st_size = sinfo.filesize; gfarm_file_section_info_free(&sinfo); return (NULL); } struct gfs_pio_ops gfs_pio_view_section_ops = { gfs_pio_view_section_close, gfs_pio_view_section_write, gfs_pio_view_section_read, gfs_pio_view_section_seek, gfs_pio_view_section_fd, gfs_pio_view_section_stat }; static char * replicate_section_to_local_internal( char *pathname, char *section, gfarm_mode_t st_mode, char *local_path, char *path_section, char *peer_hostname) { struct sockaddr peer_addr; struct gfs_connection *peer_conn; int fd, peer_fd, saved_errno; char *e; e = gfarm_host_address_get(peer_hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) return (e); e = gfs_client_connection(peer_hostname, &peer_addr, &peer_conn); if (e != NULL) return (e); e = gfs_client_open(peer_conn, path_section, GFARM_FILE_RDONLY, 0, &peer_fd); /* FT - source file should be missing */ if (e == GFARM_ERR_NO_SUCH_OBJECT) /* Delete the section copy info */ if (gfarm_file_section_copy_info_remove(pathname, section, peer_hostname) == NULL) e = GFARM_ERR_INCONSISTENT_RECOVERABLE; if (e != NULL) return (e); fd = open(local_path, O_WRONLY|O_CREAT|O_TRUNC, st_mode); saved_errno = errno; /* FT - the parent directory may be missing */ if (fd == -1 && gfs_proto_error_string(saved_errno) == GFARM_ERR_NO_SUCH_OBJECT) { if (gfs_pio_local_mkdir_parent_canonical_path( pathname) == NULL) { fd = open(local_path, O_WRONLY|O_CREAT|O_TRUNC, st_mode); saved_errno = errno; } } if (fd < 0) { e = gfs_proto_error_string(saved_errno); goto finish_peer_close; } /* XXX FIXME: this should honor sync_rate */ e = gfs_client_copyin(peer_conn, peer_fd, fd, 0); /* XXX - copyin() should return the digest value */ if (e == NULL) e = gfs_pio_set_fragment_info_local(local_path, pathname, section); close(fd); finish_peer_close: gfs_client_close(peer_conn, peer_fd); return (e); } static char * replicate_section_to_local(GFS_File gf, char *section, char *peer_hostname) { char *e; char *path_section, *local_path, *my_hostname; int metadata_exist, localfile_exist, replication_needed = 0; struct stat sb; e = gfarm_host_get_canonical_self_name(&my_hostname); if (e != NULL) return (e); e = gfarm_path_section(gf->pi.pathname, section, &path_section); if (e != NULL) return (e); e = gfarm_path_localize(path_section, &local_path); if (e != NULL) goto finish_free_path_section; /* critical section starts */ gfs_lock_local_path_section(local_path); /* FT - check existence of the local file and its metadata */ metadata_exist = gfarm_file_section_copy_info_does_exist( gf->pi.pathname, section, my_hostname); localfile_exist = !stat(local_path, &sb); if (metadata_exist && localfile_exist) { /* already exist */ /* XXX - need integrity check */ } else if (localfile_exist) { /* FT - unknown local file. delete it */ unlink(local_path); replication_needed = 1; } else if (metadata_exist) { /* FT - local file is missing. delete the metadata */ e = gfarm_file_section_copy_info_remove( gf->pi.pathname, section, my_hostname); if (e == NULL) replication_needed = 1; } else replication_needed = 1; if (replication_needed) e = replicate_section_to_local_internal( gf->pi.pathname, section, gf->pi.status.st_mode, local_path, path_section, peer_hostname); gfs_unlock_local_path_section(local_path); /* critical section ends */ free(local_path); finish_free_path_section: free(path_section); return (e); } double gfs_pio_set_view_section_time; char * gfs_pio_set_view_section(GFS_File gf, const char *section, char *if_hostname, int flags) { struct gfs_file_section_context *vc; char *e; int is_local_host; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfs_pio_set_view_default(gf); if (e != NULL) goto profile_finish; vc = malloc(sizeof(struct gfs_file_section_context)); if (vc == NULL) { e = gf->error = GFARM_ERR_NO_MEMORY; goto profile_finish; } vc->section = strdup(section); if (vc->section == NULL) { free(vc); e = gf->error = GFARM_ERR_NO_MEMORY; goto profile_finish; } retry: if (if_hostname != NULL) { e = gfarm_host_get_canonical_name(if_hostname, &vc->canonical_hostname); if (e == GFARM_ERR_UNKNOWN_HOST) { /* FT - invalid hostname, delete section copy info */ if (gfarm_file_section_copy_info_remove( gf->pi.pathname, vc->section, if_hostname) == NULL) e = GFARM_ERR_INCONSISTENT_RECOVERABLE; if (e == GFARM_ERR_INCONSISTENT_RECOVERABLE && (flags & GFARM_FILE_NOT_RETRY) == 0 && (gf->open_flags & GFARM_FILE_NOT_RETRY) == 0) { if_hostname = NULL; goto retry; } goto finish; } else if (e != NULL) goto finish; } else if ((gf->open_flags & GFARM_FILE_CREATE) != 0) { e = gfarm_host_get_canonical_self_name(&if_hostname); if (e == NULL) e = gfarm_schedule_search_idle_hosts( 1, &if_hostname, 1, &vc->canonical_hostname); if (e == NULL) e = gfarm_fixedstrings_dup( 1, &vc->canonical_hostname, &vc->canonical_hostname); if (e != NULL) { /* * local host is not a file system node, or * 'gfsd' on a local host is not running. */ e = gfarm_schedule_search_idle_by_all(1, &if_hostname); if (e != NULL) goto finish; vc->canonical_hostname = if_hostname; } } else { e = gfarm_file_section_host_schedule_with_priority_to_local( gf->pi.pathname, vc->section, &if_hostname); if (e != NULL) goto finish; vc->canonical_hostname = if_hostname; /* must be already canonical */ } is_local_host = gfarm_canonical_hostname_is_local( vc->canonical_hostname); if ((gf->open_flags & GFARM_FILE_CREATE) != 0) { struct gfarm_path_info pi; e = gfarm_path_info_set(gf->pi.pathname, &gf->pi); if (e == GFARM_ERR_ALREADY_EXISTS && (e = gfarm_path_info_get(gf->pi.pathname, &pi)) == NULL) { if (GFS_FILE_IS_PROGRAM(gf) != GFARM_S_IS_PROGRAM(pi.status.st_mode)) e = GFARM_ERR_OPERATION_NOT_PERMITTED; if (e == NULL && !GFS_FILE_IS_PROGRAM(gf)) { if (gf->pi.status.st_nsections != pi.status.st_nsections) { e = GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH; } else { #if 0 assert(gf->pi.status.st_mode & GFS_FILE_MODE_NSEGMENTS_FIXED); #endif } } if (e != NULL) { gfarm_path_info_free(&pi); } else { gfarm_path_info_free(&gf->pi); gf->pi = pi; } /* * XXX should check the follows: * - creator of the metainfo has same job id * - mode is consistent among same job * - nfragments is consistent among same job */ } if (e != NULL) goto free_host; } /* delete the file section when opening with a truncation flag. */ if ((gf->open_flags & GFARM_FILE_TRUNC) != 0) (void)gfs_unlink_section(gf->pi.pathname, vc->section); gf->ops = &gfs_pio_view_section_ops; gf->view_context = vc; gf->view_flags = flags; gf->p = gf->length = 0; gf->io_offset = gf->offset = 0; gf->mode |= GFS_FILE_MODE_CALC_DIGEST; EVP_DigestInit(&vc->md_ctx, GFS_DEFAULT_DIGEST_MODE); if (!is_local_host && ((((gf->open_flags & GFARM_FILE_REPLICATE) != 0 || gf_on_demand_replication ) && (flags & GFARM_FILE_NOT_REPLICATE) == 0) || (flags & GFARM_FILE_REPLICATE) != 0)) { e = replicate_section_to_local(gf, vc->section, if_hostname); /* FT - inconsistent metadata has been fixed. try again. */ if (e == GFARM_ERR_INCONSISTENT_RECOVERABLE && (flags & GFARM_FILE_NOT_RETRY) == 0 && (gf->open_flags & GFARM_FILE_NOT_RETRY) == 0) { if_hostname = NULL; free(vc->canonical_hostname); goto retry; } if (e != NULL) goto free_host; free(vc->canonical_hostname); e = gfarm_host_get_canonical_self_name( &vc->canonical_hostname); if (e != NULL) goto finish; vc->canonical_hostname = strdup(vc->canonical_hostname); if (vc->canonical_hostname == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } is_local_host = 1; } if (is_local_host) e = gfs_pio_open_local_section(gf, flags); else e = gfs_pio_open_remote_section(gf, if_hostname, flags); /* FT - inconsistent metadata has been fixed. try again. */ if (e == GFARM_ERR_INCONSISTENT_RECOVERABLE && (flags & GFARM_FILE_NOT_RETRY) == 0 && (gf->open_flags & GFARM_FILE_NOT_RETRY) == 0) { if_hostname = NULL; free(vc->canonical_hostname); goto retry; } free_host: if (e != NULL) free(vc->canonical_hostname); finish: if (e != NULL) { free(vc->section); free(vc); gf->view_context = NULL; gfs_pio_set_view_default(gf); } gf->error = e; profile_finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_set_view_section_time += gfarm_timerval_sub(&t2, &t1)); return (e); } char * gfs_pio_set_view_index(GFS_File gf, int nfragments, int fragment_index, char *host, int flags) { char section_string[GFARM_INT32STRLEN + 1]; if (GFS_FILE_IS_PROGRAM(gf)) { gf->error = GFARM_ERR_OPERATION_NOT_PERMITTED; return (gf->error); } if (nfragments == GFARM_FILE_DONTCARE) { if ((gf->mode & GFARM_FILE_CREATE) != 0 && !GFARM_S_IS_PROGRAM(gf->pi.status.st_mode)) { /* DONTCARE isn't permitted in this case */ gf->error = GFARM_ERR_INVALID_ARGUMENT; return (gf->error); } } else { if ((gf->mode & GFS_FILE_MODE_NSEGMENTS_FIXED) == 0) { gf->pi.status.st_nsections = nfragments; gf->mode |= GFS_FILE_MODE_NSEGMENTS_FIXED; } else if (nfragments != gf->pi.status.st_nsections) { gf->error = GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH; return (gf->error); } if (fragment_index < 0 || fragment_index >= nfragments) { gf->error = GFARM_ERR_INVALID_ARGUMENT; return (gf->error); } } sprintf(section_string, "%d", fragment_index); return (gfs_pio_set_view_section(gf, section_string, host, flags)); } <file_sep>/gfarm/tags/gfarm_1_0_3/lib/libgfarm/gfarm/gfs_exec.c /* * $Id$ */ #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/wait.h> #include <gfarm/gfarm.h> #include <openssl/evp.h>/* EVP_MD_CTX */ #include "gfs_pio.h" /* gfs_profile */ #include "gfs_lock.h" char * gfarm_url_program_get_local_path(const char *url, char **local_path) { char *hostname, *e; char *arch, *gfarm_file, *localpath; struct gfs_stat gstat; struct stat st; int metadata_exist, localfile_exist, replication_needed = 0; *local_path = NULL; /* check the permission */ e = gfs_access(url, X_OK); if (e != NULL) return (e); /* determine the architecture */ e = gfarm_host_get_canonical_self_name(&hostname); if (e == GFARM_ERR_UNKNOWN_HOST) return ("not file system node"); else if (e != NULL) return (e); arch = gfarm_host_info_get_architecture_by_host(hostname); if (arch == NULL) return ("not file system node"); /* check the metadata */ e = gfs_stat_section(url, arch, &gstat); if (e != NULL) { free(arch); return (e); } if (GFARM_S_ISDIR(gstat.st_mode)) { gfs_stat_free(&gstat); free(arch); return (GFARM_ERR_IS_A_DIRECTORY); } else if (!GFARM_S_ISREG(gstat.st_mode)) { gfs_stat_free(&gstat); free(arch); return ("unknown format"); } gfs_stat_free(&gstat); /* determine the local pathname */ e = gfarm_url_make_path(url, &gfarm_file); if (e != NULL) { free(arch); return (e); } e = gfarm_path_localize_file_section(gfarm_file, arch, &localpath); if (e != NULL) { free(gfarm_file); free(arch); return (e); } /* critical section starts */ gfs_lock_local_path_section(localpath); /* replicate the program if needed */ metadata_exist = gfarm_file_section_copy_info_does_exist( gfarm_file, arch, hostname); localfile_exist = !stat(localpath, &st); /* FT - check existence of the local file and its metadata */ if (metadata_exist && localfile_exist) { /* already exist */ /* XXX - need integrity check */ } else if (localfile_exist) { /* FT - unknown local file. delete it */ unlink(localpath); replication_needed = 1; } else if (metadata_exist) { /* FT - local file is missing. delete the metadata */ e = gfarm_file_section_copy_info_remove( gfarm_file, arch, hostname); if (e == NULL) replication_needed = 1; } else replication_needed = 1; if (replication_needed) e = gfarm_url_section_replicate_to(url, arch, hostname); gfs_unlock_local_path_section(localpath); /* critical section ends */ free(gfarm_file); free(arch); if (e != NULL) { free(localpath); return (e); } *local_path = localpath; return (NULL); } char * gfs_execve(const char *filename, char *const argv[], char *const envp[]) { char *localpath, *url, *e; const char *path; e = gfs_realpath(filename, &url); if (e != NULL) return (e); e = gfarm_url_program_get_local_path(url, &localpath); free(url); if (e != NULL) return (e); path = localpath; /* clean up the client environment */ gfs_profile(gf_profile = 0); /* not to display profile statistics */ (void)gfarm_terminate(); execve(path, argv, envp); return gfarm_errno_to_error(errno); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/include/gfarm/gfarm_stringlist.h /* * stringlist */ typedef struct { char **array; int length, size; } gfarm_stringlist; #define GFARM_STRINGLIST_STRARRAY(stringlist) (stringlist).array #define GFARM_STRINGLIST_ELEM(stringlist, i) (stringlist).array[i] #define gfarm_stringlist_length(stringlist) (stringlist)->length #define gfarm_stringlist_elem(stringlist, i) \ GFARM_STRINGLIST_ELEM(*(stringlist), i) char *gfarm_stringlist_init(gfarm_stringlist *); char *gfarm_stringlist_add_list(gfarm_stringlist *, gfarm_stringlist *); char *gfarm_stringlist_add(gfarm_stringlist *, char *); char *gfarm_stringlist_cat(gfarm_stringlist *, char **); void gfarm_stringlist_free(gfarm_stringlist *); void gfarm_stringlist_free_deeply(gfarm_stringlist *); char **gfarm_strings_alloc_from_stringlist(gfarm_stringlist *); <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/lib/libgfarm/gfarm/gfs_exec.c /* * $Id$ */ #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/stat.h> #include <gfarm/gfarm.h> #include <openssl/evp.h>/* EVP_MD_CTX */ #include "gfs_pio.h" /* gfs_profile */ char * gfs_execve(const char *filename, char *const argv [], char *const envp[]) { char *hostname, *e; char *localpath, *url, *arch, *gfarm_file; struct gfs_stat gstat; e = gfs_realpath(filename, &url); if (e != NULL) { execve(filename, argv, envp); return gfarm_errno_to_error(errno); } /* check the permission */ e = gfs_access(url, X_OK); if (e != NULL) { free(url); return (e); } /* determine the architecture */ e = gfarm_host_get_canonical_self_name(&hostname); if (e != NULL) { free(url); return (e); } arch = gfarm_host_info_get_architecture_by_host(hostname); if (arch == NULL) { free(url); return ("not file system node"); } /* check the metadata */ e = gfs_stat_section(url, arch, &gstat); if (e != NULL) { free(arch); free(url); return (e); } if (GFARM_S_ISDIR(gstat.st_mode)) { gfs_stat_free(&gstat); free(arch); free(url); return (GFARM_ERR_IS_A_DIRECTORY); } else if (!GFARM_S_ISREG(gstat.st_mode)) { gfs_stat_free(&gstat); free(arch); free(url); return ("unknown format"); } gfs_stat_free(&gstat); /* determine the local pathname */ e = gfarm_url_make_path(url, &gfarm_file); if (e != NULL) { free(arch); free(url); return (e); } e = gfarm_path_localize_file_section(gfarm_file, arch, &localpath); if (e != NULL) { free(gfarm_file); free(arch); free(url); return (e); } /* replicate the program if needed */ if (gfarm_file_section_copy_info_does_exist( gfarm_file, arch, hostname)) { struct stat st; /* * FT - already exists in metadata, but need check * whether it really exists or not. */ if (stat(localpath, &st)) { /* not exist. delete the metadata, and try to * replicate the binary */ e = gfarm_file_section_copy_info_remove( gfarm_file, arch, hostname); if (e != NULL) { free(localpath); free(gfarm_file); free(arch); free(url); return (e); } e = gfarm_url_section_replicate_to(url, arch, hostname); } /* the replica of the program already exists */ /* XXX - need integrity check */ } else e = gfarm_url_section_replicate_to(url, arch, hostname); free(gfarm_file); free(arch); free(url); if (e != NULL) { free(localpath); return (e); } /* clean up the client environment */ gfs_profile(gf_profile = 0); /* not to display profile statistics */ (void)gfarm_terminate(); execve(localpath, argv, envp); return gfarm_errno_to_error(errno); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/Makefile # $Id$ top_builddir = ../../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk LIBRARY = libgfarmcore.la LIBRARY_RESULT = # do not install GLOBUS_SRCS = auth_client_gsi.c auth_common_gsi.c auth_server_gsi.c io_gfsl.c GLOBUS_OBJS = auth_client_gsi.lo auth_common_gsi.lo auth_server_gsi.lo \ io_gfsl.lo GLOBUS_CFLAGS = -I$(GFSL_SRCDIR) $(globus_includes) SRCS = \ auth_client.c auth_common.c auth_config.c auth_server.c \ config.c error.c gfm_client.c gfs_client.c gfs_client_rep.c \ gfs_dir.c gfs_pio.c gfs_pio_global.c \ gfs_pio_local.c gfs_pio_remote.c gfs_pio_misc.c gfs_pio_section.c \ gfs_exec.c gfs_unlink.c gfs_lock.c \ gfs_proto.c glob.c host.c hostspec.c iobuffer.c \ import_help.c metadb_ldap.c metadb_misc.c param.c schedule.c \ sockopt.c stringlist.c url.c xxx_proto.c io_fd.c \ $(globus_srcs) OBJS = \ auth_client.lo auth_common.lo auth_config.lo auth_server.lo \ config.lo error.lo gfm_client.lo gfs_client.lo gfs_client_rep.lo \ gfs_dir.lo gfs_pio.lo gfs_pio_global.lo \ gfs_pio_local.lo gfs_pio_remote.lo gfs_pio_misc.lo gfs_pio_section.lo \ gfs_exec.lo gfs_unlink.lo gfs_lock.lo \ gfs_proto.lo glob.lo host.lo hostspec.lo iobuffer.lo \ import_help.lo metadb_ldap.lo metadb_misc.lo param.lo schedule.lo \ sockopt.lo stringlist.lo url.lo xxx_proto.lo io_fd.lo \ $(globus_objs) CFLAGS = $(COMMON_CFLAGS) -I$(GFUTIL_SRCDIR) -I$(GFARMLIB_SRCDIR) \ $(globus_cflags) $(metadb_client_includes) $(openssl_includes) all: $(LIBRARY) include $(top_srcdir)/makes/lib.mk ### $(GFARM_OBJS): $(DEPGFARMINC) $(GFARM_GLOBUS_OBJS): $(DEPGFSLINC) auth_client.lo: $(GFUTIL_SRCDIR)/gfutil.h $(GFUTIL_SRCDIR)/gfevent.h xxx_proto.h auth.h auth_client_gsi.lo: $(GFUTIL_SRCDIR)/gfutil.h $(GFUTIL_SRCDIR)/gfevent.h $(GFSL_SRCDIR)/gfarm_secure_session.h $(GFSL_SRCDIR)/gfarm_auth.h xxx_proto.h io_fd.h io_gfsl.h auth.h auth_gsi.h auth_common.lo: auth.h auth_common_gsi.lo: $(GFUTIL_SRCDIR)/gfutil.h $ $(GFSL_SRCDIR)/gfarm_secure_session.h $(GFSL_SRCDIR)/gfarm_auth.h auth.h auth_gsi.h auth_config.lo: hostspec.h auth.h auth_server.lo: $(GFUTIL_SRCDIR)/gfutil.h xxx_proto.h hostspec.h auth.h auth_server_gsi.lo: $(GFSL_SRCDIR)/gfarm_secure_session.h $(GFSL_SRCDIR)/gfarm_auth.h $(GFUTIL_SRCDIR)/gfutil.h xxx_proto.h io_fd.h io_gfsl.h auth.h auth_gsi.h config.lo: hostspec.h host.h param.h sockopt.h auth.h config.h gfm_proto.h gfs_proto.h gfs_client.h gfs_pio.h $(GFUTIL_SRCDIR)/timer.h error.lo: $(GFUTIL_SRCDIR)/hash.h gfm_client.lo: $(GFUTIL_SRCDIR)/hash.h xxx_proto.h io_fd.h sockopt.h auth.h config.h gfm_proto.h gfj_client.h gfs_client.lo: $(GFUTIL_SRCDIR)/gfutil.h $(GFUTIL_SRCDIR)/gfevent.h $(GFUTIL_SRCDIR)/hash.h iobuffer.h xxx_proto.h io_fd.h host.h param.h sockopt.h auth.h config.h gfs_proto.h gfs_client.h gfs_client_rep.lo: $(GFUTIL_SRCDIR)/gfutil.h xxx_proto.h io_fd.h host.h param.h auth.h config.h gfs_proto.h gfs_client.h gfs_dir.lo: $(GFUTIL_SRCDIR)/hash.h gfs_pio.h dircache.h gfs_exec.lo: gfs_pio.h gfs_lock.h gfs_lock.lo: gfs_pio.lo: gfs_pio.h $(GFUTIL_SRCDIR)/timer.h gfs_pio_global.lo: gfs_pio.h gfs_pio_local.lo: gfs_proto.h gfs_pio.h gfs_pio_misc.lo: host.h config.h gfs_proto.h gfs_client.h gfs_pio.h $(GFUTIL_SRCDIR)/timer.h gfs_pio_remote.lo: host.h config.h gfs_proto.h gfs_client.h gfs_pio.h gfs_pio_section.lo: gfs_pio.h host.h config.h schedule.h gfs_client.h gfs_proto.h $(GFUTIL_SRCDIR)/timer.h gfs_lock.h gfs_proto.lo: gfs_proto.h gfs_unlink.lo: config.h gfs_client.h gfs_pio.h $(GFUTIL_SRCDIR)/timer.h glob.lo: host.lo: hostspec.h host.h hostspec.lo: hostspec.h import_help.lo: io_fd.lo: iobuffer.h xxx_proto.h io_fd.h io_gfsl.lo: $(GFSL_SRCDIR)/gfarm_secure_session.h iobuffer.h xxx_proto.h io_fd.h io_gfsl.h iobuffer.lo: iobuffer.h metadb_ldap.lo: config.h dircache.h metadb_misc.lo: host.h config.h gfs_client.h param.lo: hostspec.h param.h schedule.lo: $(GFUTIL_SRCDIR)/gfevent.h $(GFUTIL_SRCDIR)/hash.h host.h auth.h config.h gfs_client.h sockopt.lo: hostspec.h param.h sockopt.h stringlist.lo: url.lo: config.h gfs_pio.h xxx_proto.lo: iobuffer.h xxx_proto.h <file_sep>/gfarm/branches/metadb_dev/gftool/gfrun/gfrun.c /* * $Id$ */ #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "gfj_client.h" char *program_name = "gfrun"; void setsig(int signum, void (*handler)(int)) { struct sigaction act; act.sa_handler = handler; sigemptyset(&act.sa_mask); /* do not set SA_RESTART to make interrupt at waitpid(2) */ act.sa_flags = 0; if (sigaction(signum, &act, NULL) == -1) { fprintf(stderr, "%s: sigaction(%d): %s\n", program_name, signum, strerror(errno)); exit(1); } } void ignore_handler(int signum) { /* do nothing */ } void sig_ignore(int signum) { /* we don't use SIG_IGN to make it possible that child catch singals */ setsig(signum, ignore_handler); } void usage() { fprintf(stderr, "Usage: %s [-n] [-l <login>]" " [-H <hostfile or Gfarm file>] command...\n", program_name); exit(1); } #define ENV_GFRUN_CMD "GFRUN_CMD" #define ENV_GFRUN_FLAGS "GFRUN_FLAGS" int main(argc, argv) int argc; char **argv; { gfarm_stringlist input_list, output_list, arg_list, option_list; int command_index, command_alist_index; int pid, status; int i, j, nhosts, job_id, nfrags, save_errno; char *e, **hosts; static char gfarm_prefix[] = "gfarm:"; # define GFARM_PREFIX_LEN (sizeof(gfarm_prefix) - 1) char total_nodes[GFARM_INT32STRLEN], node_index[GFARM_INT32STRLEN]; char *rsh_command, *rsh_flags; int have_gfarm_url_prefix = 1; char *hostfile = NULL, *scheduling_file; char *command_name, **delivered_paths = NULL; int have_redirect_stdio_option = 1; /* * rsh_command */ rsh_command = getenv(ENV_GFRUN_CMD); if (rsh_command == NULL) rsh_command = "gfrcmd"; /* For backward compatibility */ if (argc >= 1) { program_name = basename(argv[0]); if (strcmp(program_name, "gfrsh") == 0) { rsh_command = "rsh"; } else if (strcmp(program_name, "gfssh") == 0) { rsh_command = "ssh"; } else if (strcmp(program_name, "gfrshl") == 0) { have_gfarm_url_prefix = 0; } else if (strcmp(program_name, "gfsshl") == 0) { rsh_command = "ssh"; have_gfarm_url_prefix = 0; } } /* Globus-job-run hack */ if (strcmp(rsh_command, "globus-job-run") == 0) { have_redirect_stdio_option = 0; } /* * rsh_flags * * XXX - Currently, You can specify at most one flag. */ rsh_flags = getenv(ENV_GFRUN_FLAGS); if (rsh_flags == NULL) { if (have_redirect_stdio_option == 1) rsh_flags = "-n"; } e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm initialize: %s\n", program_name, e); exit(1); } e = gfj_initialize(); if (e != NULL) { fprintf(stderr, "%s: job manager: %s\n", program_name, e); exit(1); } gfarm_stringlist_init(&option_list); /* * parse and skip/record options */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; for (j = 1; argv[i][j] != '\0'; j++) { switch (argv[i][j]) { case 'H': if (j > 1) { argv[i][j] = '\0'; gfarm_stringlist_add(&option_list, argv[i]); } if (argv[i][j + 1] != '\0') { hostfile = &argv[i][j + 1]; } else if (++i < argc) { hostfile = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto skip_opt; case 'K': case 'd': case 'n': case 'x': /* an option which doesn't have an argument */ break; case 'k': case 'l': /* an option which does have an argument */ if (argv[i][j + 1] != '\0') ; else if (++i < argc) { gfarm_stringlist_add(&option_list, argv[i - 1]); } else { fprintf(stderr, "%s: " "missing argument to -%c\n", program_name, argv[i - 1][j]); usage(); } goto record_opt; } } record_opt: gfarm_stringlist_add(&option_list, argv[i]); skip_opt: ; } command_index = i; if (command_index >= argc) /* no command name */ usage(); command_name = argv[command_index]; gfarm_stringlist_init(&input_list); gfarm_stringlist_init(&output_list); for (i = command_index + 1; i < argc; i++) { if (strncmp(argv[i], gfarm_prefix, GFARM_PREFIX_LEN) == 0) { e = gfarm_url_fragment_number(argv[i], &nfrags); if (e == NULL) { gfarm_stringlist_add(&input_list, argv[i]); } else { gfarm_stringlist_add(&output_list, argv[i]); } if (!have_gfarm_url_prefix) argv[i] += GFARM_PREFIX_LEN; } } if (hostfile == NULL) { if (gfarm_stringlist_length(&input_list) == 0) { fprintf(stderr, "%s: no input file\n", program_name); exit(1); } /* XXX - this is only using first input file for scheduling */ scheduling_file = gfarm_stringlist_elem(&input_list, 0); e = gfarm_url_hosts_schedule(scheduling_file, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: schedule: %s\n", program_name, e); exit(1); } } else if (gfarm_is_url(hostfile)) { /* * If hostfile is a Gfarm file, schedule using the * distribution of the Gfarm file. */ e = gfarm_url_hosts_schedule(hostfile, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", hostfile, e); exit(1); } scheduling_file = hostfile; } else { int error_line; e = gfarm_hostlist_read(hostfile, &nhosts, &hosts, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s: line %d: %s\n", program_name, hostfile, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, hostfile, e); exit(1); } scheduling_file = hostfile; } /* * register job manager */ e = gfarm_user_job_register(nhosts, hosts, program_name, scheduling_file, argc - command_index, &argv[command_index], &job_id); if (e != NULL) { fprintf(stderr, "%s: job register: %s\n", program_name, e); exit(1); } /* * deliver gfarm:program. */ if (strncmp(command_name, gfarm_prefix, GFARM_PREFIX_LEN) == 0) { e = gfarm_url_program_deliver(command_name, nhosts, hosts, &delivered_paths); if (e != NULL) { fprintf(stderr, "%s: deliver %s: %s\n", program_name, command_name, e); exit(1); } } sprintf(total_nodes, "%d", nhosts); gfarm_stringlist_init(&arg_list); gfarm_stringlist_add(&arg_list, rsh_command); gfarm_stringlist_add(&arg_list, "(dummy)"); if (rsh_flags != NULL) gfarm_stringlist_add(&arg_list, rsh_flags); gfarm_stringlist_add_list(&arg_list, &option_list); command_alist_index = gfarm_stringlist_length(&arg_list); gfarm_stringlist_add(&arg_list, "(dummy)"); gfarm_stringlist_add(&arg_list, "-N"); gfarm_stringlist_add(&arg_list, total_nodes); gfarm_stringlist_add(&arg_list, "-I"); gfarm_stringlist_add(&arg_list, node_index); gfarm_stringlist_cat(&arg_list, &argv[command_index + 1]); gfarm_stringlist_add(&arg_list, NULL); for (i = 0; i < nhosts; i++) { sprintf(node_index, "%d", i); GFARM_STRINGLIST_ELEM(arg_list, 1) = hosts[i]; if (delivered_paths == NULL) { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = command_name; } else { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = delivered_paths[i]; } switch (pid = fork()) { case 0: execvp(rsh_command, GFARM_STRINGLIST_STRARRAY(arg_list)); perror(rsh_command); exit(1); case -1: perror("fork"); exit(1); } } sig_ignore(SIGHUP); sig_ignore(SIGINT); sig_ignore(SIGQUIT); sig_ignore(SIGTERM); sig_ignore(SIGTSTP); while (waitpid(-1, &status, 0) != -1) ; save_errno = errno; for (i = 0; i < gfarm_stringlist_length(&output_list); i++) gfarm_url_fragment_cleanup( gfarm_stringlist_elem(&output_list, i), nhosts, hosts); if (delivered_paths != NULL) gfarm_strings_free_deeply(nhosts, delivered_paths); gfarm_strings_free_deeply(nhosts, hosts); gfarm_stringlist_free(&arg_list); gfarm_stringlist_free(&output_list); gfarm_stringlist_free(&input_list); gfarm_stringlist_free(&option_list); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (save_errno == ECHILD ? 0 : 1); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/debian/gfmd.init #! /bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin DAEMON_GFMD=/usr/sbin/gfmd NAME_GFMD=gfmd DESC_GFMD="gfmd" test -f $DAEMON_GFMD || exit 0 set -e case "$1" in start) echo -n "Starting $DESC_GFMD: " start-stop-daemon --start --quiet --exec $DAEMON_GFMD echo "$NAME_GFMD." ;; stop) echo -n "Stopping $DESC_GFMD: " # start-stop-daemon --stop --oknodo --quiet --exec $DAEMON_GFMD # to avoid post-installation script abort on non-zero return value. echo `killall $NAME_GFMD`&>/dev/null echo "$NAME_GFMD." ;; #reload) # # If the daemon can reload its config files on the fly # for example by sending it SIGHUP, do it here. # # If the daemon responds to changes in its config file # directly anyway, make this a do-nothing entry. # # echo "Reloading $DESC_GFARMD configuration files." # start-stop-daemon --stop --signal 1 --quiet --pidfile \ # /var/run/$NAME_GFARMD.pid --exec $DAEMON_GFARMD #;; restart|force-reload) # # If the "reload" option is implemented, move the "force-reload" # option to the "reload" entry above. If not, "force-reload" is # just the same as "restart". # echo -n "Restarting $DESC_GFMD: " # start-stop-daemon --stop --oknodo --quiet --exec $DAEMON_GFMD # to avoid post-installation script abort on non-zero return value. echo `killall $NAME_GFMD`&>/dev/null sleep 1 start-stop-daemon --start --quiet --exec $DAEMON_GFMD echo "$NAME_GFMD." ;; *) N="/etc/init.d/gfmd" # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2 echo "Usage: $N {start|stop|restart|force-reload}" >&2 exit 1 ;; esac exit 0 <file_sep>/gfarm/tags/gfarm_1_0_3_1/lib/gfs_hook/hooks_common.c /* * $Id$ */ /* * open */ int FUNC___OPEN(const char *path, int oflag, ...) { GFS_File gf; const char *e; char *url, *sec; va_list ap; mode_t mode; int filedes; struct gfs_stat gs; int file_exist, file_size = 0, is_directory = 0; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___OPEN) "(%s, 0x%x)\n", path, oflag)); if (!gfs_hook_is_url(path, &url, &sec)) return (SYSCALL_OPEN(path, oflag, mode)); if (sec == NULL) e = gfs_stat(url, &gs); else e = gfs_stat_section(url, sec, &gs); if (e == GFARM_ERR_NO_SUCH_OBJECT) file_exist = 0; else if (e == NULL) { file_exist = 1; file_size = gs.st_size; is_directory = GFARM_S_ISDIR(gs.st_mode); gfs_stat_free(&gs); } else { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": gfs_stat: %s\n", e)); /* XXX - metadata may be incomplete. anyway, continue. */ file_exist = 1; file_size = 0; /* XXX - metadata of a directory should not be imcomplete */ is_directory = 0; } /* * XXX - stopgap implementation of O_WRONLY/O_RDWR, O_CREAT, * O_TRUNC flags */ if (!file_exist && (oflag & O_CREAT) != 0) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) "(%s:%s, 0x%x, 0%o)\n", url, sec != NULL ? sec : "(null)", oflag, mode)); e = gfs_pio_create(url, oflag, mode, &gf); if (e == NULL) gfs_hook_add_creating_file(gf); } else if ((oflag & O_ACCMODE) == O_WRONLY || (oflag & O_ACCMODE) == O_RDWR) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) "(%s:%s, 0x%x, 0%o)\n", url, sec != NULL ? sec : "(null)", oflag, mode)); if (file_exist && (file_size == 0 || (oflag & O_TRUNC) != 0)) { /* * XXX - O_TRUNC is basically supported in * Gfarm v1 except in global file view. * This case needs to be implemented in * gfs_pio_set_view_global() in gfs_pio_global.c. */ if (sec == NULL && _gfs_hook_default_view == global_view) gfs_unlink(url); /* XXX - FIXME */ /* * gfs_pio_create assumes GFARM_FILE_TRUNC. * It is not necessary to set O_TRUNC explicitly. */ e = gfs_pio_create(url, oflag, mode, &gf); if (e == NULL) gfs_hook_add_creating_file(gf); } else if (file_exist) { /* read-write mode: not supported yet */ _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": unsupported flags 0%o\n", oflag)); errno = ENOSYS; free(url); if (sec != NULL) free(sec); return (-1); } else { /* no such file or directory */ _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": no such file or directory\n")); errno = ENOENT; free(url); if (sec != NULL) free(sec); return (-1); } } /* XXX - end of stopgap implementation */ else { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) "(%s:%s, 0x%x)\n", url, sec != NULL ? sec : "(null)", oflag)); if (file_exist && is_directory) { GFS_Dir dir; e = gfs_opendir(url, &dir); if (e == NULL) { filedes = gfs_hook_insert_gfs_dir(dir, url); _gfs_hook_debug( if (filedes != -1) { fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) " --> %d\n", filedes); } ); free(url); if (sec != NULL) free(sec); return (filedes); } } else e = gfs_pio_open(url, oflag, &gf); } free(url); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) ": %s\n", e)); errno = gfarm_error_to_errno(e); if (sec != NULL) free(sec); return (-1); } /* set file view */ if (sec != NULL || _gfs_hook_default_view == index_view) { if (sec != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section(%s, %s)\n", path, sec)); e = gfs_pio_set_view_section(gf, sec, NULL, 0); free(sec); } else { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index(%s, %d, %d)\n", path, _gfs_hook_num_fragments, _gfs_hook_index)); e = gfs_pio_set_view_index(gf, _gfs_hook_num_fragments, _gfs_hook_index, NULL, 0); } } else if (_gfs_hook_default_view == local_view) { int nf = -1, np; /* * If the number of fragments is not the same as the * number of parallel processes, or the file is not * fragmented, do not change to the local file view. */ if (gfs_pio_get_nfragment(gf, &nf) == GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE || (gfs_pio_get_node_size(&np) == NULL && nf == np)) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local(%s (%d, %d))\n", path, gfarm_node, gfarm_nnode)); e = gfs_pio_set_view_local(gf, 0); } else e = gfs_pio_set_view_global(gf, 0); } else e = gfs_pio_set_view_global(gf, 0); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view: %s\n", e)); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } filedes = gfs_hook_insert_gfs_file(gf); _gfs_hook_debug( if (filedes != -1) { fprintf(stderr, "GFS: Hooking " S(FUNC___OPEN) " --> %d(%d)\n", filedes, gfs_pio_fileno(gf)); } ); return (filedes); } int FUNC__OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fputs("Hooking " S(FUNC__OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } int FUNC_OPEN(const char *path, int oflag, ...) { va_list ap; mode_t mode; va_start(ap, oflag); mode = va_arg(ap, mode_t); va_end(ap); _gfs_hook_debug_v(fputs("Hooking " S(FUNC_OPEN) "\n", stderr)); return (FUNC___OPEN(path, oflag, mode)); } /* * creat */ int FUNC___CREAT(const char *path, mode_t mode) { const char *e; char *url, *sec; GFS_File gf; int filedes; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___CREAT) "(%s, 0%o)\n", path, mode)); if (!gfs_hook_is_url(path, &url, &sec)) return (SYSCALL_CREAT(path, mode)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___CREAT) "(%s:%s, 0%o)\n", path, sec != NULL ? sec : "(null)", mode)); e = gfs_pio_create(url, GFARM_FILE_WRONLY, mode, &gf); if (e == NULL) gfs_hook_add_creating_file(gf); free(url); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___CREAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); if (sec != NULL) free(sec); return (-1); } /* set file view */ if (sec != NULL || _gfs_hook_default_view == index_view) { if (sec != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section(%s, %s)\n", path, sec)); e = gfs_pio_set_view_section(gf, sec, NULL, 0); free(sec); } else { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index(%s, %d, %d)\n", path, _gfs_hook_num_fragments, _gfs_hook_index)); e = gfs_pio_set_view_index(gf, _gfs_hook_num_fragments, _gfs_hook_index, NULL, 0); } } else if (_gfs_hook_default_view == local_view) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local(%s)\n", path)); e = gfs_pio_set_view_local(gf, 0); } else e = gfs_pio_set_view_global(gf, 0); if (e != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view: %s\n", e)); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = gfarm_error_to_errno(e); return (-1); } filedes = gfs_hook_insert_gfs_file(gf); _gfs_hook_debug( if (filedes != -1) { fprintf(stderr, "GFS: Hooking " S(FUNC___CREAT) " --> %d(%d)\n", filedes, gfs_pio_fileno(gf)); } ); return (filedes); } int FUNC__CREAT(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking " S(FUNC__CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } int FUNC_CREAT(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking " S(FUNC_CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } int FUNC__LIBC_CREAT(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking " S(FUNC_CREAT) "\n", stderr)); return (FUNC___CREAT(path, mode)); } /* * lseek */ OFF_T FUNC___LSEEK(int filedes, OFF_T offset, int whence) { GFS_File gf; const char *e; file_offset_t o; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___LSEEK) "(%d, %" PR_FILE_OFFSET ", %d)\n", filedes, (file_offset_t)offset, whence)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_LSEEK(filedes, offset, whence)); if (gfs_hook_gfs_file_type(filedes) == GFS_DT_DIR) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___LSEEK) "(%d, %" PR_FILE_OFFSET ", %d)\n", filedes, (file_offset_t)offset, whence)); _gfs_hook_debug(fprintf(stderr, "lseek(2) trapping of Gfarm directory " "not supported yet\n")); e = GFARM_ERR_IS_A_DIRECTORY; goto error; } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___LSEEK) "(%d(%d), %" PR_FILE_OFFSET ", %d)\n", filedes, gfs_pio_fileno(gf), (file_offset_t)offset, whence)); e = gfs_pio_seek(gf, offset, whence, &o); if (e == NULL) return ((OFF_T)o); error: _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___LSEEK) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } OFF_T FUNC__LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC__LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } OFF_T FUNC_LSEEK(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_LSEEK) ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } /* * getdents */ #ifdef __linux__ # define internal_function __attribute__ ((regparm (3), stdcall)) #else # define internal_function /* empty */ #endif int internal_function FUNC___GETDENTS(int filedes, STRUCT_DIRENT *buf, size_t nbyte) { GFS_Dir dir; const char *e; unsigned short reclen; struct gfs_dirent *entry; STRUCT_DIRENT *bp; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___GETDENTS) "(%d, %p, %d)\n", filedes, buf, nbyte)); if ((dir = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_GETDENTS(filedes, buf, nbyte)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___GETDENTS) "(%d, %p, %d)\n", filedes, buf, nbyte)); if (gfs_hook_gfs_file_type(filedes) != GFS_DT_DIR) { e = GFARM_ERR_NOT_A_DIRECTORY; goto error; } bp = buf; if (!gfs_hook_is_read(filedes)) { /* for the first time */ static const char dot[] = "."; static const char dotdot[] = ".."; e = NULL; reclen = ALIGN( offsetof(STRUCT_DIRENT, d_name) + sizeof(dot)); if ((char *)bp + reclen > (char *)buf + nbyte) { e = GFARM_ERR_INVALID_ARGUMENT; goto finish; } memset(bp, 0, offsetof(STRUCT_DIRENT, d_name)); /* XXX */ bp->d_ino = 1; /* XXX */ bp->d_reclen = reclen; strcpy(bp->d_name, dot); memset(bp->d_name + sizeof(dot) - 1, 0, reclen - (offsetof(STRUCT_DIRENT, d_name) + sizeof(dot) - 1)); bp = (STRUCT_DIRENT *) ((char *)bp + reclen); reclen = ALIGN( offsetof(STRUCT_DIRENT, d_name) + sizeof(dotdot)); if ((char *)bp + reclen > (char *)buf + nbyte) { e = GFARM_ERR_INVALID_ARGUMENT; goto finish; } memset(bp, 0, offsetof(STRUCT_DIRENT, d_name)); /* XXX */ bp->d_ino = 1; /* XXX */ bp->d_reclen = reclen; strcpy(bp->d_name, dotdot); memset(bp->d_name + sizeof(dotdot) - 1, 0, reclen - (offsetof(STRUCT_DIRENT, d_name) + sizeof(dotdot) - 1)); bp = (STRUCT_DIRENT *) ((char *)bp + reclen); } if ((entry = gfs_hook_get_suspended_gfs_dirent(filedes)) != NULL) { reclen = ALIGN( offsetof(STRUCT_DIRENT, d_name) + entry->d_namlen + 1); if ((char *)bp + reclen > (char *)buf + nbyte) { e = GFARM_ERR_INVALID_ARGUMENT; goto finish; } gfs_hook_set_suspended_gfs_dirent(filedes, NULL); memset(bp, 0, offsetof(STRUCT_DIRENT, d_name)); /* XXX */ bp->d_ino = 1; /* XXX */ bp->d_reclen = reclen; memcpy(bp->d_name, entry->d_name, entry->d_namlen); memset(bp->d_name + entry->d_namlen, 0, reclen - (offsetof(STRUCT_DIRENT, d_name) + entry->d_namlen)); bp = (STRUCT_DIRENT *) ((char *)bp + reclen); } while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { reclen = ALIGN( offsetof(STRUCT_DIRENT, d_name) + entry->d_namlen + 1); if ((char *)bp + reclen > (char *)buf + nbyte) { gfs_hook_set_suspended_gfs_dirent(filedes, entry); goto finish; } memset(bp, 0, offsetof(STRUCT_DIRENT, d_name)); /* XXX */ bp->d_ino = 1; /* XXX */ bp->d_reclen = reclen; memcpy(bp->d_name, entry->d_name, entry->d_namlen); memset(bp->d_name + entry->d_namlen, 0, reclen - (offsetof(STRUCT_DIRENT, d_name) + entry->d_namlen)); bp = (STRUCT_DIRENT *) ((char *)bp + reclen); } finish: if (e == NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___GETDENTS) " --> %d\n", filedes)); gfs_hook_inc_readcount(filedes); return ((char *)bp - (char *)buf); } error: _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___GETDENTS) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int internal_function FUNC__GETDENTS(int filedes, STRUCT_DIRENT *buf, size_t nbyte) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC__GETDENTS) ": %d\n", filedes)); return (FUNC___GETDENTS(filedes, buf, nbyte)); } int internal_function #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) FUNC_GETDENTS(int filedes, char *buf, size_t nbyte) #else FUNC_GETDENTS(int filedes, STRUCT_DIRENT *buf, size_t nbyte) #endif { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_GETDENTS) ": %d\n", filedes)); return (FUNC___GETDENTS(filedes, (STRUCT_DIRENT *)buf, nbyte)); } <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfarm/schedule.c #include <stdio.h> /* sprintf */ #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <gfarm/gfarm.h> #include "auth.h" /* XXX gfarm_random_initialize() */ #include "gfs_client.h" char GFARM_ERR_NO_REPLICA[] = "no replica"; char GFARM_ERR_NO_HOST[] = "no filesystem node"; #define IDLE_LOAD_AVERAGE 0.1F #define SEMI_IDLE_LOAD_AVERAGE 0.5F struct search_idle_available_host { char *hostname; float loadavg; }; struct search_idle_state { struct search_idle_available_host *available_hosts; int available_hosts_number; int idle_hosts_number; int semi_idle_hosts_number; }; struct search_idle_callback_closure { struct search_idle_state *state; char *hostname; }; static void search_idle_callback(void *closure, struct sockaddr *addr, struct gfs_client_load *load, char *error) { struct search_idle_callback_closure *c = closure; struct search_idle_state *s = c->state; if (error == NULL) { struct search_idle_available_host *h = &s->available_hosts[s->available_hosts_number++]; h->hostname = c->hostname; h->loadavg = load->loadavg_1min; if (h->loadavg <= SEMI_IDLE_LOAD_AVERAGE) { s->semi_idle_hosts_number++; if (h->loadavg <= IDLE_LOAD_AVERAGE) s->idle_hosts_number++; } } free(c); } static int loadavg_compare(const void *a, const void *b) { const struct search_idle_available_host *p = a; const struct search_idle_available_host *q = b; const float l1 = p->loadavg; const float l2 = q->loadavg; if (l1 < l2) return (-1); else if (l1 > l2) return (1); else return (0); } /* * The search will be stopped, if `enough_number' of semi-idle hosts * are found. * * `*nohostsp' is an IN/OUT parameter. * It means desired number of hosts as an INPUT parameter. * It returns available number of hosts as an OUTPUT parameter. */ static char * search_idle(int concurrency, int enough_number, int nihosts, char **ihosts, int *nohostsp, char **ohosts) { char *e; int i, desired_number = *nohostsp; struct gfs_client_udp_requests *udp_requests; struct sockaddr addr; struct search_idle_state s; struct search_idle_callback_closure *c; s.available_hosts_number = s.idle_hosts_number = s.semi_idle_hosts_number = 0; s.available_hosts = malloc(nihosts * sizeof(*s.available_hosts)); if (s.available_hosts == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_client_init_load_requests(concurrency, &udp_requests); if (e != NULL) { free(s.available_hosts); return (e); } for (i = 0; i < nihosts; i++) { e = gfarm_host_address_get(ihosts[i], gfarm_spool_server_port, &addr, NULL); if (e != NULL) continue; c = malloc(sizeof(*c)); if (c == NULL) break; c->state = &s; c->hostname = ihosts[i]; e = gfarm_client_add_load_request(udp_requests, &addr, c, search_idle_callback); if (s.idle_hosts_number >= desired_number || s.semi_idle_hosts_number >= enough_number) break; } e = gfarm_client_wait_all_load_results(udp_requests); if (s.available_hosts_number == 0) { free(s.available_hosts); *nohostsp = 0; return (GFARM_ERR_NO_HOST); } /* sort hosts in the order of load average */ qsort(s.available_hosts, s.available_hosts_number, sizeof(*s.available_hosts), loadavg_compare); for (i = 0; i < s.available_hosts_number && i < desired_number; i++) ohosts[i] = s.available_hosts[i].hostname; *nohostsp = i; free(s.available_hosts); return (NULL); } /* #define USE_SHUFFLED */ #ifdef USE_SHUFFLED static void shuffle_strings(int n, char **strings) { int i, j; char *tmp; gfarm_random_initialize(); for (i = n - 1; i > 0; --i) { #ifdef HAVE_RANDOM j = random() % (i + 1); #else j = rand()/(RAND_MAX + 1.0) * (i + 1); #endif tmp = strings[i]; strings[i] = strings[j]; strings[j] = tmp; } } static char * search_idle_shuffled(int concurrency, int enough_number, int nihosts, char **ihosts, int *nohostsp, char **ohosts) { char *e, **shuffled_ihosts; int i; /* shuffle ihosts[] to avoid unbalanced host selection */ shuffled_ihosts = malloc(nihosts * sizeof(*shuffled_ihosts)); if (shuffled_ihosts == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < nihosts; i++) shuffled_ihosts[i] = ihosts[i]; shuffle_strings(nihosts, shuffled_ihosts); e = search_idle(concurrency, enough_number, nihosts, shuffled_ihosts, nohostsp, ohosts); free(shuffled_ihosts); return (e); } #endif /* USE_SHUFFLED */ #define CONCURRENCY 10 #define ENOUGH_RATE 4 /* * Select 'nohosts' hosts among 'nihosts' ihosts in the order of * load average, and return to 'ohosts'. * When enough number of hosts are not available, the available hosts * will be listed in the cyclic manner. */ char * gfarm_schedule_search_idle_hosts( int nihosts, char **ihosts, int nohosts, char **ohosts) { int i, j, nfound = nohosts; #ifdef USE_SHUFFLED char *e = search_idle_shuffled(CONCURRENCY, nohosts * ENOUGH_RATE, nihosts, ihosts, &nfound, ohosts); #else char *e = search_idle(CONCURRENCY, nohosts * ENOUGH_RATE, nihosts, ihosts, &nfound, ohosts); #endif if (e != NULL) return (e); if (nfound == 0) { /* Oh, my god */ return (GFARM_ERR_NO_HOST); } for (i = nfound, j = 0; i < nohosts; i++, j++) { if (j >= nfound) j = 0; ohosts[i] = ohosts[j]; } return (NULL); } char * gfarm_schedule_search_idle_by_all(int nhosts_req, char **hostnames_found) { char *e, **hostnames; int i, nhosts; struct gfarm_host_info *hosts; e = gfarm_host_info_get_all(&nhosts, &hosts); if (e != NULL) return (e); hostnames = malloc(sizeof(char *) * nhosts); if (hostnames == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } for (i = 0; i < nhosts; i++) hostnames[i] = hosts[i].hostname; e = gfarm_schedule_search_idle_hosts(nhosts, hostnames, nhosts_req, hostnames_found); if (e != NULL) goto free_hostnames; for (i = 0; i < nhosts_req; i++) { hostnames_found[i] = strdup(hostnames_found[i]); if (hostnames_found[i] == NULL) { while (--i >= 0) free(hostnames_found[i]); e = GFARM_ERR_NO_MEMORY; goto free_hostnames; } } free_hostnames: free(hostnames); finish: gfarm_host_info_free_all(nhosts, hosts); return (e); } static char * gfarm_schedule_search_idle_by_section_copy_info( int ncopies, struct gfarm_file_section_copy_info *copies, char **hostp) { char *e, **hostnames; int i; hostnames = malloc(sizeof(char *) * ncopies); if (hostnames == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < ncopies; i++) hostnames[i] = copies[i].hostname; e = gfarm_schedule_search_idle_hosts( ncopies, hostnames, 1, hostp); free(hostnames); return (e); } char * gfarm_file_section_host_schedule(char *gfarm_file, char *section, char **hostp) { char *e; int ncopies; struct gfarm_file_section_copy_info *copies; char *host; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); if (ncopies == 0) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (GFARM_ERR_NO_REPLICA); } e = gfarm_schedule_search_idle_by_section_copy_info( ncopies, copies, &host); *hostp = strdup(host); gfarm_file_section_copy_info_free_all(ncopies, copies); if (*hostp == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } char * gfarm_file_section_host_schedule_with_priority_to_local( char *gfarm_file, char *section, char **hostp) { char *e, *self_name, *host; int i, ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); if (ncopies == 0) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (GFARM_ERR_NO_REPLICA); } /* choose/schedule local one, if possible */ e = gfarm_host_get_canonical_self_name(&self_name); if (e != NULL) { i = ncopies; } else { for (i = 0; i < ncopies; i++) if (strcasecmp(self_name, copies[i].hostname) == 0) break; } if (i < ncopies) /* local */ host = copies[i].hostname; else { e = gfarm_schedule_search_idle_by_section_copy_info( ncopies, copies, &host); if (e != NULL) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (e); } } *hostp = strdup(host); gfarm_file_section_copy_info_free_all(ncopies, copies); if (*hostp == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } char * gfarm_url_hosts_schedule(char *gfarm_url, char *option, int *nhostsp, char ***hostsp) { char *e, *gfarm_file, **hosts; int i, nfrags; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); hosts = malloc(sizeof(char *) * nfrags); if (hosts == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < nfrags; i++) { char section_string[GFARM_INT32STRLEN + 1]; sprintf(section_string, "%d", i); e = gfarm_file_section_host_schedule( gfarm_file, section_string, &hosts[i]); if (e != NULL) { gfarm_strings_free_deeply(i, hosts); free(gfarm_file); return (e); } } free(gfarm_file); *nhostsp = nfrags; *hostsp = hosts; return (NULL); } /* * lists host names that contains domainname. */ char * gfarm_schedule_search_idle_by_domainname(const char *domainname, int nhosts, char **hosts) { char *e; struct gfarm_host_info *hinfos; int i, j, domain_nhosts = 0, nhinfos; char **domain_hosts; e = gfarm_host_info_get_all(&nhinfos, &hinfos); if (e != NULL) return (e); for (i = 0; i < nhinfos; ++i) { if (strstr(hinfos[i].hostname, domainname)) ++domain_nhosts; } if (domain_nhosts == 0) { e = GFARM_ERR_NO_HOST; goto finish; } domain_hosts = malloc(sizeof(char *) * domain_nhosts); if (domain_hosts == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } j = 0; for (i = 0; i < nhinfos; ++i) { if (strstr(hinfos[i].hostname, domainname)) { domain_hosts[j++] = hinfos[i].hostname; } } e = gfarm_schedule_search_idle_hosts(domain_nhosts, domain_hosts, nhosts, hosts); if (e != NULL) goto free_hostnames; for (i = 0; i < nhosts; i++) { hosts[i] = strdup(hosts[i]); if (hosts[i] == NULL) { while (--i >= 0) free(hosts[i]); e = GFARM_ERR_NO_MEMORY; goto free_hostnames; } } free_hostnames: free(domain_hosts); finish: gfarm_host_info_free_all(nhinfos, hinfos); return (e); } /* * expands a host list up to nhosts. This function does not need * gfarm_strings_free_deeply() for hostsp. */ char * gfarm_hosts_schedule_expand_cyclic(int nhosts, char ***hostsp, int nsrchosts, char **srchosts) { int i; char **hosts; hosts = malloc(sizeof(char *) * nhosts); if (hosts == NULL) { return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < nhosts; ++i) { hosts[i] = srchosts[i % nsrchosts]; } *hostsp = hosts; return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_beta_2/lib/libgfarm/gfarm/gfs_dir.c #include <string.h> #include <stdlib.h> #include <limits.h> #include <gfarm/gfarm.h> #include "hash.h" char * gfs_getcwd(char *cwd, int cwdsize) { char *user = gfarm_get_global_username(); int len = strlen(user); if (len < cwdsize) { strcpy(cwd, user); } else { memcpy(cwd, user, cwdsize - 1); cwd[cwdsize - 1] = '\0'; } return (NULL); } /* * directory tree, opendir/readdir/closedir */ struct node { struct node *parent; char *name; int is_dir; union node_u { struct dir { struct gfarm_hash_table *children; } d; } u; }; #define NODE_HASH_SIZE 53 /* prime */ static struct node *root; static struct node * init_node_name(struct node *n, char *name, int len) { n->name = malloc(len + 1); if (n->name == NULL) return (NULL); memcpy(n->name, name, len); n->name[len] = '\0'; return (n); } #define DIR_NODE_SIZE \ (sizeof(struct node) - sizeof(union node_u) + sizeof(struct dir)) static struct node * init_dir_node(struct node *n, char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->is_dir = 1; n->u.d.children = gfarm_hash_table_alloc(NODE_HASH_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); return (n); } #define FILE_NODE_SIZE (sizeof(struct node) - sizeof(union node_u)) static struct node * init_file_node(struct node *n, char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->is_dir = 0; return (n); } static struct node * lookup_node(struct node *parent, char *name, int len, int is_dir, int create) { struct gfarm_hash_entry *entry; int created; struct node *n; if (!parent->is_dir) return (NULL); /* not a directory */ if (len == 0) { return (parent); } else if (len == 1 && name[0] == '.') { return (parent); } else if (len == 2 && name[0] == '.' && name[1] == '.') { return (parent->parent); } if (len > GFS_MAXNAMLEN) len = GFS_MAXNAMLEN; if (!create) { entry = gfarm_hash_lookup(parent->u.d.children, name, len); return (entry == NULL ? NULL : gfarm_hash_entry_data(entry)); } entry = gfarm_hash_enter(parent->u.d.children, name, len, is_dir ? DIR_NODE_SIZE : FILE_NODE_SIZE, &created); n = gfarm_hash_entry_data(entry); if (!created) return (n); if (is_dir) init_dir_node(n, name, len); else init_file_node(n, name, len); if (n == NULL) { gfarm_hash_purge(parent->u.d.children, name, len); return (NULL); } n->parent = parent; return (n); } /* if (!create), (is_dir) may be -1, and that means "don't care". */ static char * lookup_relative(struct node *n, char *path, int is_dir, int create, struct node **np) { int len; if (!n->is_dir) return (GFARM_ERR_NOT_A_DIRECTORY); for (;;) { while (*path == '/') path++; for (len = 0; path[len] != '/'; len++) { if (path[len] == '\0') { n = lookup_node(n, path, len, is_dir, create); if (n == NULL) return (create ? GFARM_ERR_NO_MEMORY : GFARM_ERR_NO_SUCH_OBJECT); if (is_dir != -1 && n->is_dir != is_dir) return (n->is_dir ? GFARM_ERR_IS_A_DIRECTORY : GFARM_ERR_NOT_A_DIRECTORY); if (np != NULL) *np = n; return (NULL); } } n = lookup_node(n, path, len, 1, /* XXX */ create); if (n == NULL) return (create ? GFARM_ERR_NO_MEMORY : GFARM_ERR_NO_SUCH_OBJECT); if (!n->is_dir) return (GFARM_ERR_NOT_A_DIRECTORY); path += len; } } /* if (!create), (is_dir) may be -1, and that means "don't care". */ static char * lookup_path(char *path, int is_dir, int create, struct node **np) { struct node *n; if (path[0] == '/') { n = root; } else { char *e; char cwd[PATH_MAX + 1]; e = gfs_getcwd(cwd, sizeof(cwd)); if (e != NULL) return (e); e = lookup_relative(root, cwd, 1, /* XXX */ 1, &n); if (e != NULL) return (e); } return (lookup_relative(n, path, is_dir, create, np)); } static char * root_node(void) { root = malloc(DIR_NODE_SIZE); if (root == NULL) return (GFARM_ERR_NO_MEMORY); init_dir_node(root, "", 0); root->parent = root; return (NULL); } static void remember_path(void *closure, struct gfarm_path_info *info) { lookup_relative(root, info->pathname, GFARM_S_ISDIR(info->status.st_mode), 1, NULL); } static char * gfs_cachedir(void) { char *e; if (root != NULL) return (NULL); e = root_node(); if (e != NULL) return (e); gfarm_path_info_get_all_foreach(remember_path, NULL); return (NULL); } static void free_node(struct node *n) { if (n->is_dir) { struct gfarm_hash_iterator i; struct gfarm_hash_entry *child; for (gfarm_hash_iterator_begin(n->u.d.children, &i); (child = gfarm_hash_iterator_access(&i)) != NULL; gfarm_hash_iterator_next(&i)) { free_node(gfarm_hash_entry_data(child)); } gfarm_hash_table_free(n->u.d.children); } free(n->name); } void gfs_uncachedir(void) { if (root != NULL) { free_node(root); free(root); root = NULL; } } static char * get_abspath(char *path, char **abspathp) { struct node *n, *p; char *e, *abspath; int l, len; e = lookup_path(path, -1, 0, &n); if (e != NULL) return (e); len = 0; for (p = n; p != root; p = p->parent) len += strlen(p->name) + 1; len += GFARM_URL_PREFIX_LENGTH; abspath = malloc(len + 1); if (abspath == NULL) return (GFARM_ERR_NO_MEMORY); abspath[len] = '\0'; for (p = n; p != root; p = p->parent) { l = strlen(p->name); len -= l; memcpy(abspath + len, p->name, l); abspath[--len] = '/'; } memcpy(abspath, GFARM_URL_PREFIX, GFARM_URL_PREFIX_LENGTH); *abspathp = abspath; return (NULL); } /* * gfs_opendir()/readdir()/closedir() */ struct gfs_dir { struct node *dir; struct gfarm_hash_iterator iterator; struct gfs_dirent buffer; }; char * gfs_opendir(char *path, GFS_Dir *dirp) { char *e; struct node *n; struct gfs_dir *dir; e = gfs_cachedir(); if (e != NULL) return (e); path = gfarm_url_prefix_skip(path); e = lookup_path(path, 1, 0, &n); if (e != NULL) return (e); dir = malloc(sizeof(struct gfs_dir)); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); dir->dir = n; gfarm_hash_iterator_begin(n->u.d.children, &dir->iterator); *dirp = dir; return (NULL); } char * gfs_readdir(GFS_Dir dir, struct gfs_dirent **entry) { struct gfarm_hash_entry *he; struct node *n; he = gfarm_hash_iterator_access(&dir->iterator); if (he == NULL) { *entry = NULL; return (NULL); } n = gfarm_hash_entry_data(he); gfarm_hash_iterator_next(&dir->iterator); dir->buffer.d_fileno = 1; /* XXX */ dir->buffer.d_type = n->is_dir ? GFS_DT_DIR : GFS_DT_REG; dir->buffer.d_namlen = gfarm_hash_entry_key_length(he); memcpy(dir->buffer.d_name, gfarm_hash_entry_key(he), dir->buffer.d_namlen); dir->buffer.d_name[dir->buffer.d_namlen] = '\0'; *entry = &dir->buffer; return (NULL); } char * gfs_closedir(GFS_Dir dir) { free(dir); return (NULL); } static char * gfs_stat_sub(char *gfarm_url, struct gfs_stat *s) { char *e, *gfarm_file; int i, nsections; struct gfarm_file_section_info *sections; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } *s = pi.status; s->st_user = strdup(s->st_user); s->st_group = strdup(s->st_group); gfarm_path_info_free(&pi); if (s->st_user == NULL || s->st_group == NULL) { gfs_stat_free(s); free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } if (!GFARM_S_ISREG(s->st_mode)) { free(gfarm_file); return (NULL); } e = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); free(gfarm_file); if (e != NULL) { gfs_stat_free(s); /* * If GFARM_ERR_NO_SUCH_OBJECT is returned here, * gfs_stat() incorrectly assumes that this is a directory, * and reports GFARM_ERR_NOT_A_DIRECTORY. */ return ("no fragment information"); } s->st_size = 0; for (i = 0; i < nsections; i++) s->st_size += sections[i].filesize; s->st_nsections = nsections; gfarm_file_section_info_free_all(nsections, sections); return (NULL); } char * gfs_stat(char *path, struct gfs_stat *s) { char *e, *p; struct node *n; e = gfs_cachedir(); if (e != NULL) return (e); path = gfarm_url_prefix_skip(path); e = get_abspath(path, &p); if (e != NULL) return (e); e = gfs_stat_sub(p, s); free(p); if (e == NULL) return (NULL); if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); /* XXX - assume that it's a directory. */ e = lookup_path(path, 1, 0, &n); if (e != NULL) return (e); s->st_mode = GFARM_S_IFDIR | 0777; s->st_user = strdup("root"); s->st_group = strdup("gfarm"); s->st_atimespec.tv_sec = 0; s->st_atimespec.tv_nsec = 0; s->st_mtimespec.tv_sec = 0; s->st_mtimespec.tv_nsec = 0; s->st_ctimespec.tv_sec = 0; s->st_ctimespec.tv_nsec = 0; s->st_size = 0; s->st_nsections = 0; return (NULL); } void gfs_stat_free(struct gfs_stat *s) { if (s->st_user != NULL) free(s->st_user); if (s->st_group != NULL) free(s->st_group); } <file_sep>/gfarm_samba/trunk/gfarm_id.c /* * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <string.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm_hash.h" #include "msgno/msgno.h" static struct gfarm_hash_table *hash_uid_to_user; static struct gfarm_hash_table *hash_gid_to_group; static struct gfarm_hash_table *hash_user_to_uid; static struct gfarm_hash_table *hash_group_to_gid; static gfarm_uint32_t next_auto_uid; static gfarm_uint32_t next_auto_gid; static uid_t auto_uid_min; static uid_t auto_uid_max; static gid_t auto_gid_min; static gid_t auto_gid_max; static int use_cached_id = 0; /* for debug */ static int id_hash_index(const void *k, int l) { return (*(int *)k); } static int id_hash_equal(const void *k1, int k1len, const void *k2, int k2len) { return (*(gfarm_uint32_t *)k1 == *(gfarm_uint32_t *)k2); } static int primes[] = { 5, 11, 19, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209, 16411, 32771 }; static int next_prime(int n) { int i, nprimes = sizeof(primes) / sizeof(int); for (i = 0; i < nprimes; i++) if (primes[i] > n) return (primes[i]); return (primes[nprimes - 1]); } gfarm_error_t gfarm_id_init( gfarm_uint32_t uid_min, gfarm_uint32_t uid_max, gfarm_uint32_t gid_min, gfarm_uint32_t gid_max, int use_cache) { gfarm_uint32_t auto_uid_hash_size, auto_gid_hash_size; use_cached_id = use_cache; auto_uid_min = uid_min; auto_uid_max = uid_max; auto_gid_min = gid_min; auto_gid_max = gid_max; if (auto_uid_min >= auto_uid_max) { gflog_error(GFARM_MSG_3000199, "illegal parameter: uid_min(%u) >= uid_max(%u)", auto_uid_min, auto_uid_max); return (GFARM_ERR_INVALID_ARGUMENT); } if (auto_gid_min >= auto_gid_max) { gflog_error(GFARM_MSG_3000200, "illegal parameter: gid_min(%u) >= gid_max(%u)", auto_gid_min, auto_gid_max); return (GFARM_ERR_INVALID_ARGUMENT); } auto_uid_hash_size = next_prime((auto_uid_max - auto_uid_min) / 8); auto_gid_hash_size = next_prime((auto_gid_max - auto_gid_min) / 8); hash_uid_to_user = gfarm_hash_table_alloc( auto_uid_hash_size, id_hash_index, id_hash_equal); hash_gid_to_group = gfarm_hash_table_alloc( auto_gid_hash_size, id_hash_index, id_hash_equal); hash_user_to_uid = gfarm_hash_table_alloc( auto_uid_hash_size, gfarm_hash_strptr, gfarm_hash_key_equal_strptr); hash_group_to_gid = gfarm_hash_table_alloc( auto_gid_hash_size, gfarm_hash_strptr, gfarm_hash_key_equal_strptr); if (hash_uid_to_user == NULL || hash_gid_to_group == NULL || hash_user_to_uid == NULL || hash_group_to_gid == NULL) { gflog_error(GFARM_MSG_3000201, "no memory for id hashtab"); return (GFARM_ERR_NO_MEMORY); } next_auto_uid = auto_uid_min; next_auto_gid = auto_gid_min; return (GFARM_ERR_NO_ERROR); } static gfarm_error_t global_user_to_local_uid( const char *url, const char *user, gfarm_uint32_t *uidp) { gfarm_error_t e; struct passwd *pwd; char *luser, *guser; if ((e = gfarm_get_global_username_by_url(url, &guser)) != GFARM_ERR_NO_ERROR) { gflog_debug(GFARM_MSG_3000202, "gfarm_get_global_username_by_url() failed: %s", gfarm_error_string(e)); return (e); } if (strcmp(guser, user) == 0) { free(guser); *uidp = (gfarm_uint32_t)geteuid(); /* my own file */ return (GFARM_ERR_NO_ERROR); } free(guser); if (gfarm_global_to_local_username_by_url(url, user, &luser) == GFARM_ERR_NO_ERROR) { pwd = getpwnam(luser); free(luser); if (pwd != NULL) { *uidp = (gfarm_uint32_t)pwd->pw_uid; return (GFARM_ERR_NO_ERROR); } } return (GFARM_ERR_NO_SUCH_OBJECT); /* unknown local user */ } static gfarm_error_t global_group_to_local_gid( const char *url, const char *group, gfarm_uint32_t *gidp) { struct group *grp; char *lgroup; if (gfarm_global_to_local_groupname_by_url(url, group, &lgroup) == GFARM_ERR_NO_ERROR) { grp = getgrnam(lgroup); free(lgroup); if (grp != NULL) { *gidp = (gfarm_uint32_t)grp->gr_gid; return (GFARM_ERR_NO_ERROR); } } return (GFARM_ERR_NO_SUCH_OBJECT); /* unknown local group */ } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t local_uid_to_global_user(const char *url, gfarm_uint32_t uid, char **userp) { gfarm_error_t e; struct passwd *pwd; *userp = NULL; if (uid == (gfarm_uint32_t)getuid()) { e = gfarm_get_global_username_by_url(url, userp); if (e != GFARM_ERR_NO_ERROR) gflog_error(GFARM_MSG_3000203, "gfarm_get_global_username_by_url() failed: %s", gfarm_error_string(e)); return (e); } /* use the user map file to identify the global user */ if ((pwd = getpwuid((uid_t)uid)) == NULL) return (GFARM_ERR_NO_SUCH_OBJECT); return (gfarm_local_to_global_username_by_url( url, pwd->pw_name, userp)); } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t local_gid_to_global_group(const char *url, gfarm_uint32_t gid, char **groupp) { struct group *grp; *groupp = NULL; /* use the group map file to identify the global group */ if ((grp = getgrgid((gid_t)gid)) == NULL) return (GFARM_ERR_NO_SUCH_OBJECT); return (gfarm_local_to_global_groupname_by_url( url, grp->gr_name, groupp)); } static gfarm_error_t auto_name_to_id(struct gfarm_hash_table *name_to_id, const char *name, gfarm_uint32_t *idp) { struct gfarm_hash_entry *entry; entry = gfarm_hash_lookup(name_to_id, &name, sizeof(name)); if (entry != NULL) { *idp = *(gfarm_uint32_t *)gfarm_hash_entry_data(entry); return (GFARM_ERR_NO_ERROR); } return (GFARM_ERR_NO_SUCH_OBJECT); } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t auto_id_to_name(struct gfarm_hash_table *id_to_name, gfarm_uint32_t id, char **namep) { struct gfarm_hash_entry *entry; *namep = NULL; entry = gfarm_hash_lookup(id_to_name, &id, sizeof(id)); if (entry != NULL) { *namep = strdup(*(char **)gfarm_hash_entry_data(entry)); if (*namep == NULL) { gflog_error(GFARM_MSG_3000204, "no memory for auto uid/gid"); return (GFARM_ERR_NO_MEMORY); } return (GFARM_ERR_NO_ERROR); } return (GFARM_ERR_NO_SUCH_OBJECT); } static gfarm_error_t auto_id_and_name_enter(gfarm_uint32_t id, const char *name, struct gfarm_hash_table *hash_id_to_name, struct gfarm_hash_table *hash_name_to_id) { struct gfarm_hash_entry *entry1, *entry2; int created; char *str; char *type = (hash_id_to_name == hash_uid_to_user ? "uid" : "gid"); str = strdup(name); if (str == NULL) goto nomem; /* uid to user */ entry1 = gfarm_hash_enter(hash_id_to_name, &id, sizeof(gfarm_uint32_t), sizeof(char *), &created); if (entry1 == NULL) { free(str); goto nomem; } if (!created) { free(str); return (GFARM_ERR_ALREADY_EXISTS); } /* user to uid */ entry2 = gfarm_hash_enter(hash_name_to_id, &str, sizeof(str), sizeof(gfarm_uint32_t), &created); if (entry2 == NULL) { free(str); gfarm_hash_purge(hash_id_to_name, &id, sizeof(gfarm_uint32_t)); goto nomem; } if (!created) { gfarm_hash_purge(hash_id_to_name, &id, sizeof(gfarm_uint32_t)); gfarm_hash_purge(hash_name_to_id, &str, sizeof(str)); free(str); gflog_error(GFARM_MSG_3000205, "unexpected: inconsistent auto %s(name=%s)", type, name); return (GFARM_ERR_ALREADY_EXISTS); } *(char **)gfarm_hash_entry_data(entry1) = str; *(gfarm_uint32_t *)gfarm_hash_entry_data(entry2) = id; #if 0 /* for debug */ { gfarm_uint32_t i; char *s; printf("----- start of debug gfarm_id.c -----\n"); for (i = auto_uid_min; i <= next_auto_uid; i++) { auto_id_to_name(hash_uid_to_user, i, &s); if (s != NULL) { printf("uid[%d]: user=%s\n", i, s); free(s); } } for (i = auto_gid_min; i <= next_auto_gid; i++) { auto_id_to_name(hash_gid_to_group, i, &s); if (s != NULL) { printf("gid[%d]: group=%s\n", i, s); free(s); } } printf("----- end of debug id.c -----\n"); } #endif return (GFARM_ERR_NO_ERROR); nomem: gflog_error(GFARM_MSG_3000206, "no memory for auto %s(name=%s)", type, name); return (GFARM_ERR_NO_MEMORY); } static gfarm_error_t global_name_to_local_id( const char *url, const char *name, struct gfarm_hash_table *hash_id_to_name, struct gfarm_hash_table *hash_name_to_id, gfarm_error_t (*global_name_to_local_id_func)( const char *, const char *, gfarm_uint32_t *), gfarm_error_t (*local_id_to_global_name_func)( const char *, gfarm_uint32_t, char **), gfarm_uint32_t *next_auto_id_p, const gfarm_uint32_t *id_max_p, gfarm_uint32_t *return_id_p) { gfarm_error_t e; int checked_cache = 0; if (use_cached_id) { /* for debug: use cached id any time */ if (auto_name_to_id(hash_name_to_id, name, return_id_p) == GFARM_ERR_NO_ERROR) return (GFARM_ERR_NO_ERROR); checked_cache = 1; } /* * Assuming a new local user/group is added, getpwnam() or * getgrnam() are checked every time. */ if (global_name_to_local_id_func(url, name, return_id_p) == GFARM_ERR_NO_ERROR) { if (use_cached_id) /* for debug: cache all mapping */ auto_id_and_name_enter(*return_id_p, name, hash_id_to_name, hash_name_to_id); return (GFARM_ERR_NO_ERROR); } if (checked_cache == 0 && auto_name_to_id(hash_name_to_id, name, return_id_p) == GFARM_ERR_NO_ERROR) return (GFARM_ERR_NO_ERROR); /* search unused id number */ do { char *str; do { *return_id_p = (gfarm_uint32_t)*next_auto_id_p; (*next_auto_id_p)++; } while (*return_id_p + 1 != *next_auto_id_p); if (*return_id_p >= *id_max_p) { gflog_warning(GFARM_MSG_3000207, "lack of auto_%s: name=%s", (hash_id_to_name == hash_uid_to_user ? "uid" : "gid"), name); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } e = local_id_to_global_name_func(url, *return_id_p, &str); if (e != GFARM_ERR_NO_ERROR && e != GFARM_ERR_NO_SUCH_OBJECT) return (e); if (str == NULL) /* found unused uid/gid */ break; free(str); } while (1); /* * If <PASSWORD> and <PASSWORD> are the same * name, they have the same id. */ e = auto_id_and_name_enter(*return_id_p, name, hash_id_to_name, hash_name_to_id); if (e != GFARM_ERR_NO_ERROR) return (e); return (GFARM_ERR_NO_ERROR); } /* --------------------------------------------------------------------- */ gfarm_error_t gfarm_id_user_to_uid(const char *url, const char *user, uid_t *uidp) { gfarm_uint32_t id; gfarm_error_t e; e = global_name_to_local_id(url, user, hash_uid_to_user, hash_user_to_uid, global_user_to_local_uid, local_uid_to_global_user, &next_auto_uid, &auto_uid_max, &id); if (e == GFARM_ERR_NO_ERROR) *uidp = (uid_t)id; return (e); } gfarm_error_t gfarm_id_group_to_gid(const char *url, const char *group, gid_t *gidp) { gfarm_uint32_t id; gfarm_error_t e; e = global_name_to_local_id(url, group, hash_gid_to_group, hash_group_to_gid, global_group_to_local_gid, local_gid_to_global_group, &next_auto_gid, &auto_gid_max, &id); if (e == GFARM_ERR_NO_ERROR) *gidp = (gid_t)id; return (e); } /* returned string should be free'ed if it is not NULL */ gfarm_error_t gfarm_id_uid_to_user(const char *url, uid_t uid, char **userp) { gfarm_error_t e; /* * Assuming a new local user/group is added, getpwuid() is * checked every time. */ e = local_uid_to_global_user(url, (gfarm_uint32_t)uid, userp); if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); /* success or error */ e = auto_id_to_name(hash_uid_to_user, (gfarm_uint32_t)uid, userp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { gflog_debug(GFARM_MSG_3000208, "cannot convert uid(%d) to gfarm username", uid); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } else return (e); } /* returned string should be free'ed if it is not NULL */ gfarm_error_t gfarm_id_gid_to_group(const char *url, gid_t gid, char **groupp) { gfarm_error_t e; /* * Assuming a new local user/group is added, getgrgid() is * checked every time. */ e = local_gid_to_global_group(url, (gfarm_uint32_t)gid, groupp); if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); /* success or error */ e = auto_id_to_name(hash_gid_to_group, (gfarm_uint32_t)gid, groupp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { gflog_debug(GFARM_MSG_3000209, "cannot convert gid(%d) to gfarm groupname", gid); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } else return (e); } uid_t gfarm_id_nobody_uid() { struct passwd *pwd = getpwnam("<PASSWORD>"); if (pwd != NULL) return (pwd->pw_uid); return (auto_uid_max); } gid_t gfarm_id_nogroup_gid() { struct group *grp = getgrnam("nogroup"); if (grp != NULL) return (grp->gr_gid); return (auto_gid_max); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc3/lib/libgfarm/gfarm/xxx_proto.h /* * private definition. these functions may be merged to nslib. */ struct gfarm_iobuffer; struct xxx_iobuffer_ops { char *(*close)(void *, int); char *(*export_credential)(void *); char *(*delete_credential)(void *); char *(*env_for_credential)(void *); int (*nonblocking_read)(struct gfarm_iobuffer *, void *, int, void *, int); int (*nonblocking_write)(struct gfarm_iobuffer *, void *, int, void *, int); int (*blocking_read)(struct gfarm_iobuffer *, void *, int, void *, int); int (*blocking_write)(struct gfarm_iobuffer *, void *, int, void *, int); }; struct xxx_connection; char *xxx_connection_new(struct xxx_iobuffer_ops *, void *, int, struct xxx_connection **); char *xxx_connection_free(struct xxx_connection *); void *xxx_connection_cookie(struct xxx_connection *); int xxx_connection_fd(struct xxx_connection *); void xxx_connection_set(struct xxx_connection *, struct xxx_iobuffer_ops *, void *, int); char *xxx_connection_export_credential(struct xxx_connection *); char *xxx_connection_delete_credential(struct xxx_connection *); char *xxx_connection_env_for_credential(struct xxx_connection *); void gfarm_iobuffer_set_nonblocking_read_xxx(struct gfarm_iobuffer *, struct xxx_connection *); void gfarm_iobuffer_set_nonblocking_write_xxx(struct gfarm_iobuffer *, struct xxx_connection *); char *xxx_proto_flush(struct xxx_connection *); char *xxx_proto_purge(struct xxx_connection *, int, int); char *xxx_proto_vsend(struct xxx_connection *, char **, va_list *); char *xxx_proto_vrecv(struct xxx_connection *, int, int *, char **, va_list *); char *xxx_proto_send(struct xxx_connection *, char *, ...); char *xxx_proto_recv(struct xxx_connection *, int, int *, char *, ...); char *xxx_proto_vrpc_request(struct xxx_connection *, gfarm_int32_t, char **, va_list *); char *xxx_proto_vrpc_result(struct xxx_connection *, int, gfarm_int32_t *, char **, va_list *); char *xxx_proto_vrpc(struct xxx_connection *, int, gfarm_int32_t, gfarm_int32_t *, char **, va_list *); int xxx_recv_partial(struct xxx_connection *, int, void *, int); /* * rpc format string mnemonic: * * c [u]int8_t * h [u]int16_t * i [u]int32_t * o file_offset_t (on network: int64_t) * s char * (on network: int32_t, int8_t-array) * b fixed size buffer * request: size_t, char * * result: size_t, size_t *, char * * (on network: int32_t, int8_t-array) * * (all integers are transfered as big endian on network) */ <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/package/redhat/gfarm-slapd #! /bin/sh # # gfarm-slapd # # chkconfig: 2345 85 15 # description: LDAP slapd for Gfarm # processname: slapd # pidfile: /var/run/gfarm-slapd.pid # config: /etc/gfarm-ldap/slapd.conf bindir=/usr/sbin config=/etc/gfarm-ldap/slapd.conf port=389 # Source function library. . /etc/rc.d/init.d/functions # Get config. . /etc/sysconfig/network # Check that networking is up. if [ ${NETWORKING} = "no" ] then exit 0 fi [ -f $bindir/slapd ] || exit 0 [ -f $config ] || exit 0 RETVAL=0 # See how we were called. case "$1" in start) echo -n "Starting Gfarm LDAP services: " daemon $bindir/slapd -f $config -h ldap://:$port/ RETVAL=$? echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/gfarm-slapd ;; stop) echo -n "Stopping Gfarm LDAP services: " killproc gfarm-slapd RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/gfarm-slapd ;; status) status slapd RETVAL=$? ;; restart|reload) $0 stop $0 start # is this available?: killall -HUP slapd RETVAL=$? ;; *) echo "Usage: inet {start|stop|status|restart|reload}" exit 1 esac exit $REVAL <file_sep>/gfarm/tags/gfarm_0_1/bench/Makefile top_objdir = .. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = \ bwlat-syscache \ nconnect \ thput-fsys \ thput-gfpio include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/failure_test_scripts/FT3-3-1-1_failover_while_reading #! /bin/sh ###################################################################### TESTID="FT3-3-1-1" CATEGORY="accident while failover and failure of meta data sync" SECTION="failover in the midst of client accessd" TITLE="failover while reading" ###################################################################### . ./FT-common ft_setup() { FILE=a.dat COPY=b.dat DIR=mnt SIZE=1000M ssh $client1 "mkdir -p $DIR" $gfservice unmount client1 $DIR $gfservice mount client1 $DIR -o nonempty ssh $client1 "rm -f $DIR/$FILE" ssh $client1 "rm -f $FILE $COPY create-random-file" scp create-random-file $client1: ssh $client1 "./create-random-file $FILE $SIZE" return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 "cp $FILE $DIR/$FILE" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "copy a large file on Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 "cp $DIR/$FILE $COPY" & [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "read a large file from Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd2 "sudo kill -USR1 \`cat /var/run/gfmd.pid\`" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "upgrade slave gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_wait_remote_process $client1 "cp $DIR/$FILE $COPY" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "wait to copy a large file" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 "cmp $FILE $COPY" || RESULT=$FT_RESULT_FAIL ft_checkpoint 6 "compare the copy with the original" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $client1 "rm -f $DIR/$FILE" ssh $client1 "rm -f $FILE $COPY create-random-file" $gfservice umount client1 $DIR ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/gfarm/glob.c #include <string.h> #include <stdlib.h> #include <limits.h> #include <gfarm/gfarm.h> #define GFS_GLOB_INITIAL 200 #define GFS_GLOB_DELTA 200 char * gfs_glob_init(gfs_glob_t *listp) { unsigned char *v; v = malloc(sizeof(unsigned char) * GFS_GLOB_INITIAL); if (v == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = GFS_GLOB_INITIAL; listp->length = 0; listp->array = v; return (NULL); } void gfs_glob_free(gfs_glob_t *listp) { free(listp->array); /* the following is not needed, but to make erroneous program abort */ listp->size = 0; listp->length = 0; listp->array = NULL; } char * gfs_glob_add(gfs_glob_t *listp, int dtype) { int length = gfs_glob_length(listp); if (length >= listp->size) { int n = listp->size + GFS_GLOB_DELTA; unsigned char *t = realloc(listp->array, sizeof(unsigned char) * n); if (t == NULL) return (GFARM_ERR_NO_MEMORY); listp->size = n; listp->array = t; } listp->array[length] = dtype; listp->length++; return (NULL); } /* * gfs_glob */ static void glob_pattern_to_name(char *name, const char *pattern, int length) { int i, j; for (i = j = 0; j < length; i++, j++) { if (pattern[j] == '\\') { if (pattern[j + 1] != '\0' && pattern[j + 1] != '/') j++; } name[i] = pattern[j]; } name[i] = '\0'; } static int glob_charset_parse(const char *pattern, int index, int *ip) { int i = index; if (pattern[i] == '!') i++; if (pattern[i] != '\0') { if (pattern[i + 1] == '-' && pattern[i + 2] != '\0') i += 3; else i++; } while (pattern[i] != ']') { if (pattern[i] == '\0') { /* end of charset isn't found */ if (ip != NULL) *ip = index; return (0); } if (pattern[i + 1] == '-' && pattern[i + 2] != '\0') i += 3; else i++; } if (ip != NULL) *ip = i; return (1); } static int glob_charset_match(int ch, const char *pattern, int pattern_length) { int i = 0, negate = 0; unsigned char c = ch, *p = (unsigned char *)pattern; if (p[i] == '!') { negate = 1; i++; } while (i < pattern_length) { if (p[i + 1] == '-' && p[i + 2] != '\0') { if (p[i] <= c && c <= p[i + 2]) return (!negate); i += 3; } else { if (c == p[i]) return (!negate); i++; } } return (negate); } static int glob_name_submatch(char *name, const char *pattern, int namelen) { int w; for (; --namelen >= 0; name++, pattern++){ if (*pattern == '?') continue; if (*pattern == '[' && glob_charset_parse(pattern, 1, &w)) { if (glob_charset_match(*(unsigned char *)name, pattern + 1, w - 1)) { pattern += w; continue; } return (0); } if (*pattern == '\\' && pattern[1] != '\0' && pattern[1] != '/') { if (*name == pattern[1]) { pattern++; continue; } } if (*name != *pattern) return (0); } return (1); } static int glob_prefix_length_to_asterisk(const char *pattern, int pattern_length, const char **asterisk) { int i, length = 0; for (i = 0; i < pattern_length; length++, i++) { if (pattern[i] == '\\') { if (i + 1 < pattern_length && pattern[i + 1] != '/') i++; } else if (pattern[i] == '*') { *asterisk = &pattern[i]; return (length); } else if (pattern[i] == '[') { glob_charset_parse(pattern, i + 1, &i); } } *asterisk = &pattern[i]; return (length); } static int glob_name_match(char *name, const char *pattern, int pattern_length) { const char *asterisk; int residual = strlen(name); int sublen = glob_prefix_length_to_asterisk(pattern, pattern_length, &asterisk); if (residual < sublen || !glob_name_submatch(name, pattern, sublen)) return (0); if (*asterisk == '\0') return (residual == sublen); for (;;) { name += sublen; residual -= sublen; pattern_length -= asterisk + 1 - pattern; pattern = asterisk + 1; sublen = glob_prefix_length_to_asterisk(pattern, pattern_length, &asterisk); if (*asterisk == '\0') break; for (;; name++, --residual){ if (residual < sublen) return (0); if (glob_name_submatch(name, pattern, sublen)) break; } } return (residual >= sublen && glob_name_submatch(name + residual - sublen, pattern, sublen)); } static char GFARM_ERR_PATHNAME_TOO_LONG[] = "pathname too long"; #define GLOB_PATH_BUFFER_SIZE (PATH_MAX * 2) static char * gfs_glob_sub(char *path_buffer, char *path_tail, const char *pattern, gfarm_stringlist *paths, gfs_glob_t *types) { char *s, *e, *e_save = NULL; int i, nomagic, dirpos = -1; GFS_Dir dir; struct gfs_dirent *entry; struct gfs_stat st; for (i = 0; pattern[i] != '\0'; i++) { if (pattern[i] == '\\') { if (pattern[i + 1] != '\0' && pattern[i + 1] != '/') i++; } else if (pattern[i] == '/') { dirpos = i; } else if (pattern[i] == '?' || pattern[i] == '*') { break; } else if (pattern[i] == '[') { if (glob_charset_parse(pattern, i + 1, NULL)) break; } } if (pattern[i] == '\0') { /* no magic */ if (path_tail - path_buffer + strlen(pattern) > GLOB_PATH_BUFFER_SIZE) return (GFARM_ERR_PATHNAME_TOO_LONG); glob_pattern_to_name(path_tail, pattern, strlen(pattern)); e = gfs_stat(path_buffer, &st); if (e != NULL) return (e); s = gfarm_url_prefix_add(path_buffer); if (s == NULL) return (GFARM_ERR_NO_MEMORY); gfarm_stringlist_add(paths, s); if (GFARM_S_ISDIR(st.st_mode)) gfs_glob_add(types, GFS_DT_DIR); else gfs_glob_add(types, GFS_DT_REG); return (NULL); } nomagic = i; if (dirpos >= 0) { int dirlen = dirpos == 0 ? 1 : dirpos; if (path_tail - path_buffer + dirlen > GLOB_PATH_BUFFER_SIZE) return (GFARM_ERR_PATHNAME_TOO_LONG); glob_pattern_to_name(path_tail, pattern, dirlen); path_tail += strlen(path_tail); } dirpos++; for (i = nomagic; pattern[i] != '\0'; i++) { if (pattern[i] == '\\') { if (pattern[i + 1] != '\0' && pattern[i + 1] != '/') i++; } else if (pattern[i] == '/') { break; } else if (pattern[i] == '?' || pattern[i] == '*') { } else if (pattern[i] == '[') { glob_charset_parse(pattern, i + 1, &i); } } e = gfs_opendir(path_buffer, &dir); if (e != NULL) return (e); if (path_tail > path_buffer && path_tail[-1] != '/') { if (path_tail - path_buffer + 1 > GLOB_PATH_BUFFER_SIZE) return (GFARM_ERR_PATHNAME_TOO_LONG); *path_tail++ = '/'; } while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { if (entry->d_name[0] == '.' && pattern[dirpos] != '.') continue; /* initial '.' must be literally matched */ if (!glob_name_match(entry->d_name, &pattern[dirpos], i - dirpos)) continue; if (path_tail - path_buffer + strlen(entry->d_name) > GLOB_PATH_BUFFER_SIZE) { if (e_save == NULL) e_save = GFARM_ERR_PATHNAME_TOO_LONG; continue; } strcpy(path_tail, entry->d_name); if (pattern[i] == '\0') { s = gfarm_url_prefix_add(path_buffer); if (s == NULL) return (GFARM_ERR_NO_MEMORY); gfarm_stringlist_add(paths, s); gfs_glob_add(types, entry->d_type); continue; } e = gfs_glob_sub(path_buffer, path_tail + strlen(path_tail), pattern + i, paths, types); if (e_save == NULL) e_save = e; } gfs_closedir(dir); return (e_save); } char * gfs_glob(const char *pattern, gfarm_stringlist *paths, gfs_glob_t *types) { const char *s; char *p = NULL, *e = NULL; int len, n = gfarm_stringlist_length(paths); char path_buffer[GLOB_PATH_BUFFER_SIZE + 1]; pattern = gfarm_url_prefix_skip(pattern); if (*pattern == '~') { if (pattern[1] == '\0' || pattern[1] == '/') { s = gfarm_get_global_username(); len = strlen(s); pattern++; } else { s = pattern + 1; len = strcspn(s, "/"); pattern += 1 + len; } p = malloc(1 + len + strlen(pattern) + 1); if (p == NULL) { e = GFARM_ERR_PATHNAME_TOO_LONG; } else { p[0] = '/'; memcpy(p + 1, s, len); strcpy(p + 1 + len, pattern); pattern = p; } } else { strcpy(path_buffer, "."); } if (e == NULL) { e = gfs_glob_sub(path_buffer, path_buffer, pattern, paths, types); } if (gfarm_stringlist_length(paths) <= n) { gfarm_stringlist_add(paths, gfarm_url_prefix_add(pattern)); gfs_glob_add(types, GFS_DT_UNKNOWN); } if (p != NULL) free(p); return (e); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/debian/gfarm-slapd.init #! /bin/sh # Kill me on all errors set -e # Stop processing if slapd is not there [ -x /usr/sbin/slapd ] || exit 0 # Source the init script configuration if [ -f "/etc/default/gfarm-slapd" ]; then . /etc/default/gfarm-slapd else exit 1 fi # Load the default location of the slapd config file if [ -z "$SLAPD_CONF" ]; then SLAPD_CONF="/etc/ldap/slapd.conf" else SLAPD_OPTIONS="-f $SLAPD_CONF $SLAPD_OPTIONS" SLURPD_OPTIONS="-f $SLAPD_CONF $SLURPD_OPTIONS" fi # Stop processing if the config file is not there if [ ! -r "$SLAPD_CONF" ]; then cat <<EOF >&2 No configuration file was found for slapd at $SLAPD_CONF. If you have moved the slapd configuration file please modify /etc/default/slapd to reflect this. If you chose to not configure slapd during installation then you need to do so prior to attempting to start slapd. An example slapd.conf is in /usr/share/slapd EOF exit 0 # Should this be 1? fi # Figure out some default settings # Check wether slurpd should get started if [ "$SLURPD_START" != "yes" ] && [ "$SLURPD_START" != "no" ]; then if grep -q '^replica' "$SLAPD_CONF" > /dev/null 2>&1 ; then SLURPD_START=yes else SLURPD_START=no fi fi # Find out the name of slapd's pid file if [ -z "$SLAPD_PIDFILE" ]; then SLAPD_PIDFILE=`sed -ne 's/^pidfile[[:space:]]\+\(.\+\)/\1/p' \ "$SLAPD_CONF"` fi # XXX: Breaks upgrading if there is no pidfile (invoke-rc.d stop will fail) # -- Torsten if [ -z "$SLAPD_PIDFILE" ]; then cat <<EOF >&2 The pidfile for slapd is neither specified in "$SLAPD_CONF" nor in /etc/default/slapd. Consequently, slapd will not be started. EOF exit 1 fi # Pass the user and group to run under to slapd if [ "$SLAPD_USER" ]; then SLAPD_OPTIONS="-u $SLAPD_USER $SLAPD_OPTIONS" fi if [ "$SLAPD_GROUP" ]; then SLAPD_OPTIONS="-g $SLAPD_GROUP $SLAPD_OPTIONS" fi # Tell the user that something went wrong and give some hints for # resolving the problem. report_failure() { if [ -n "$reason" ]; then echo " - failed: " echo "$reason" else echo " - failed." cat <<EOF The operation failed but no output was produced. For hints on what went wrong please refer to the system's logfiles (e.g. /var/log/syslog) or try running the daemon in Debug mode like via "slapd -d 16383" (warning: this will create copious output). EOF if [ -n "$SLURPD_OPTIONS" -o \ -n "$SLAPD_OPTIONS" -o \ -n "$SLAPD_SERVICES" ]; then cat << EOF Below, you can find the command line options used by this script to run slapd and slurpd. Do not forget to specify those options if you want to look to debugging output: EOF if [ -z "$SLAPD_SERVICES" ]; then if [ -n "$SLAPD_OPTIONS" ]; then echo " slapd $SLAPD_OPTIONS" fi else echo " slapd -h '$SLAPD_SERVICES' $SLAPD_OPTIONS" fi if [ "$SLURPD" = "yes" -a -n "$SLURPD_OPTIONS" ]; then echo " slurpd $SLURPD_OPTIONS" fi fi fi } # Start the slapd daemon and capture the error message if any to # $reason. start_slapd() { echo -n " slapd" if [ -z "$SLAPD_SERVICES" ]; then reason="`start-stop-daemon --start --quiet --oknodo \ --pidfile "$SLAPD_PIDFILE" \ --exec /usr/sbin/slapd -- $SLAPD_OPTIONS 2>&1`" else reason="`start-stop-daemon --start --quiet --oknodo \ --pidfile "$SLAPD_PIDFILE" \ --exec /usr/sbin/slapd -- -h "$SLAPD_SERVICES" $SLAPD_OPTIONS 2>&1`" fi } # Start the slurpd daemon and capture the error message if any to # $reason. start_slurpd() { if [ "$SLURPD_START" != yes ]; then return 0 fi echo -n " slurpd" reason="`start-stop-daemon --start --quiet --oknodo \ --exec /usr/sbin/slurpd -- $SLURPD_OPTIONS 2>&1`" } # Stop the slapd daemon and capture the error message (if any) to # $reason. stop_slapd() { echo -n " slapd" reason="`start-stop-daemon --stop --quiet --oknodo --retry 10 \ --pidfile "$SLAPD_PIDFILE" \ --exec /usr/sbin/slapd 2>&1`" } # Stop the slurpd daemon and capture the error message (if any) to # $reason. stop_slurpd() { if [ "$SLURPD_START" != yes ]; then return 0 fi echo -n " slurpd" reason="`start-stop-daemon --stop --quiet --oknodo --retry 10 \ --exec /usr/sbin/slurpd 2>&1`" } # Start the OpenLDAP daemons start() { echo -n "Starting OpenLDAP:" trap 'report_failure' 0 start_slapd start_slurpd trap "-" 0 echo . } # Stop the OpenLDAP daemons stop() { echo -n "Stopping OpenLDAP:" trap 'report_failure' 0 stop_slurpd stop_slapd trap "-" 0 echo . } case "$1" in start) start ;; stop) stop ;; restart|force-reload) stop start ;; *) echo "Usage: $0 {start|stop|restart|force-reload}" exit 1 ;; esac <file_sep>/gfarm/tags/gfarm_0_1/gftool/gfsched/gfsched.c #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <gfarm/gfarm.h> /* * Create a hostfile. * * gfsched <gfarm_url> [<hostfile>] * gfsched -f <gfarm_file> [<hostfile>] */ char *program_name = "gfsched"; void usage() { fprintf(stderr, "usage: %s [-f] gfarm_file [hostfile]\n", program_name); fflush(stderr); } int main(int argc, char * argv[]) { int argc_save = argc; char **argv_save = argv; char * gfarm_url = (char *)NULL; char * e = (char *)NULL; FILE * outp = stdout; int errflg = 0; extern int optind; int nhosts; char **hosts; int c, i; while ((c = getopt(argc, argv, "?")) != EOF) { switch (c) { case '?': default: ++errflg; } } if (errflg) { usage(); exit(2); } if (optind < argc) { gfarm_url = argv[optind]; } else { usage(); exit(2); } ++optind; if (optind < argc) { outp = fopen(argv[optind], "w"); if (outp == (FILE *)NULL) { perror(argv[optind]); exit(1); } } e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_url_hosts_schedule(gfarm_url, (char *)NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < nhosts; ++i) fprintf(outp, "%s\n", hosts[i]); fclose(outp); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(0); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/debian/rules #!/usr/bin/make -f # Sample debian/rules that uses debhelper. # GNU copyright 1997 by <NAME>. # # This version is for a hypothetical package that builds an # architecture-dependant package, as well as an architecture-independent # package. # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 # This is the debhelper compatability version to use. export DH_COMPAT=2 # This has to be exported to make some magic below work. export DH_OPTIONS export CC=gcc GFARM_CLIENT_PKG = gfarm-client GFARM_DOC_PKG = gfarm-doc GFARM_PKG = gfarm GFARMD_PKG = gfarmd GFMD_PKG = gfmd GFSD_PKG=gfsd LIBGFARM_DEV_PKG = libgfarm-dev GFARM_MAN1=gfgrep.1 gfhost.1 gfls.1 GFMD_MAN8=gfmd.8 GFARM_CLIENT_MAN1=digest.1 gfexport.1 gfimport_fixed.1 gfimport_text.1 gfkey.1 gfmpirun_p4.1 gfps.1 gfrcmd.1 gfreg.1 gfrep.1 gfrm.1 gfrsh.1 gfrun.1 gfsched.1 gfssh.1 gfwhere.1 GFSD_MAN8=gfsd.8 LIBGFARM_DEV_MAN3=gfarm_initialize.3 gfarm_strings_free_deeply.3 gfarm_terminate.3 gfarm_url_hosts_schedule.3 gfs_closedir.3 gfs_opendir.3 gfs_pio_close.3 gfs_pio_create.3 gfs_pio_eof.3 gfs_pio_error.3 gfs_pio_flush.3 gfs_pio_getc.3 gfs_pio_getline.3 gfs_pio_open.3 gfs_pio_putc.3 gfs_pio_putline.3 gfs_pio_puts.3 gfs_pio_read.3 gfs_pio_seek.3 gfs_pio_set_local.3 gfs_pio_set_view_index.3 gfs_pio_set_view_local.3 gfs_pio_ungetc.3 gfs_pio_write.3 gfs_readdir.3 gfs_stat.3 gfs_stat_free.3 gfs_unlink.3 configure: configure-stamp configure-stamp: dh_testdir # Add here commands to configure the package. -rm -rf ns/ install -d build && cd build && ../configure --srcdir=$(PWD) --with-openldap=/usr --prefix=`pwd`/../debian/tmp/usr --with-mpi=/usr touch configure-stamp build: configure-stamp build-stamp build-stamp: dh_testdir # Add here commands to compile the package. cd build && $(MAKE) touch build-stamp clean: dh_testdir dh_testroot rm -f build-stamp # Add here commands to clean up after the build process. -cd build && $(MAKE) distclean -rm -f configure-stamp -rm -rf build find . -name '*.o' -o -name '_libs' -o -name '*.lo' -o -name '*.a' -o -name '.deps' | xargs rm -rf dh_clean install: DH_OPTIONS= install: build dh_testdir dh_testroot dh_clean -k dh_installdirs # Add here commands to install the package into debian/tmp. cd build && $(MAKE) install DESTDIR=`pwd`/../debian/tmp # hoax gfarm's Makefile. install -d debian/tmp/etc/init.d/ install -m 444 doc/conf/gfarm.conf debian/tmp/etc/ install -d debian/tmp/usr/share/doc/gfarm/ cp debian/gfsd.init debian/tmp/etc/init.d/gfsd cp debian/gfmd.init debian/tmp/etc/init.d/gfmd dh_install --sourcedir=debian/tmp -dh_movefiles # Build architecture-independent files here. # Pass -i to all debhelper commands in this target to reduce clutter. binary-indep: DH_OPTIONS=-i binary-indep: build install # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir dh_testroot # dh_installdebconf dh_installdocs dh_installexamples # dh_installmenu # dh_installemacsen # dh_installpam # dh_installinit # dh_installcron # dh_installmanpages # dh_installinfo # dh_undocumented dh_installchangelogs dh_link dh_compress dh_fixperms # You may want to make some executables suid here. # dh_suidregister dh_installdeb # dh_perl dh_gencontrol dh_md5sums dh_builddeb # Build architecture-dependent files here. # Pass -a to all debhelper commands in this target to reduce clutter. # binary-arch: DH_OPTIONS=-a binary-arch: build install # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir dh_testroot # dh_installdebconf dh_installdocs dh_installexamples # dh_installmenu # dh_installemacsen # dh_installpam # dh_installinit # dh_installcron # manpages for gfarm package for man in $(GFARM_MAN1); do \ dh_installman -p$(GFARM_PKG) man/ja/man1/$$man man/man1/$$man; \ done # manpages for gfmd package for man in $(GFMD_MAN8); do \ dh_installman -p$(GFMD_PKG) man/ja/man8/$$man man/man8/$$man; \ done # manpages for gfarm-client package for man in $(GFARM_CLIENT_MAN1); do \ dh_installman -p$(GFARM_CLIENT_PKG) man/ja/man1/$$man man/man1/$$man; \ done # manpages for gfsd for man in $(GFSD_MAN8); do \ dh_installman -p$(GFSD_PKG) man/ja/man8/$$man man/man8/$$man; \ done # manpages for libgfarm-dev for man in $(LIBGFARM_DEV_MAN3); do \ dh_installman -p$(LIBGFARM_DEV_PKG) man/ja/man3/$$man man/man3/$$man; \ done # dh_installinfo # dh_undocumented dh_installchangelogs dh_strip dh_link dh_compress dh_fixperms # You may want to make some executables suid here. # dh_suidregister dh_installdeb dh_makeshlibs # dh_perl dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb binary: binary-arch binary-indep .PHONY: build clean binary-indep binary-arch binary install configure <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/failure_test_scripts/FT3-2-1-1_all_gfmd_down #! /bin/sh ###################################################################### TESTID="FT3-2-1-1" CATEGORY="N point accident" SECTION="MDS internal accident" TITLE="all gfmd down" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd3 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.3 "stop gfmd on $gfmd3" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd2 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.2 "stop gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 || RESULT=$FT_RESULT_FAIL ft_checkpoint 1.1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "slave gfmd is not running on $gfmd3" \ "slave gfmd is not running on $gfmd2" \ "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2.1 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { $gfservice start-gfmd gfmd1 $gfservice start-gfmd gfmd2 $gfservice start-gfmd gfmd3 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc2/gfptool/util/gfregister.in #!/bin/sh PTOOLS='gfcombine gfcombine_hook gfcp gfcp_hook gfgrep gfreg gfsplck gfwc' hostname=`hostname` arch=`gfhost -M $hostname | sed 's/ .*//'` status=0 if test x"$arch" = x"" then echo "$0: error: architecture name of $hostname isn't determined" >&2 exit 1 fi cd @prefix@/bin echo Creating gfarm:/bin ... if gfmkdir gfarm:/bin; then : else status=1 fi for cmd in $PTOOLS do if test -f $cmd then if gfwhere -I $arch gfarm:/bin/$cmd >/dev/null 2>&1; then : else echo Registering gfarm:/bin/$cmd for $arch ... if gfreg $cmd gfarm:/bin/$cmd; then : else status=1 fi fi gfhost -a $arch | while read host; do echo Replicating gfarm:/bin/${cmd}:${arch} to $host ... if gfrep -I $arch -s $hostname -d $host gfarm:/bin/$cmd then : else status=1 fi done fi done exit $status <file_sep>/gfarm/branches/metadb_dev/lib/libgfarm/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk CFLAGS = $(COMMON_CFLAGS) $(openssl_includes) -I. $(gfsl_includes) LIB = gfarm GLOBUS_SRCS = auth_client_gsi.c auth_server_gsi.c io_gfsl.c GLOBUS_OBJS = auth_client_gsi.o auth_server_gsi.o io_gfsl.o SRCS = auth_client.c auth_common.c auth_config.c auth_server.c \ config.c error.c gfm_client.o gfm_proto.c gfs_client.c \ gfs_pio.c gfs_pio_default.c gfs_pio_global.c \ gfs_pio_local.c gfs_pio_remote.c gfs_pio_misc.c gfs_pio_section.c \ gfs_proto.c hash.c host.c hostspec.c iobuffer.c \ import_help.c logutil.c metadb_gfmd.c metadb_misc.c schedule.c \ stringlist.c url.c xxx_proto.c io_fd.c \ $(globus_srcs) OBJS = auth_client.o auth_common.o auth_config.o auth_server.o \ config.o error.o gfm_client.o gfm_proto.o gfs_client.o \ gfs_pio.o gfs_pio_default.o gfs_pio_global.o \ gfs_pio_local.o gfs_pio_remote.o gfs_pio_misc.o gfs_pio_section.o \ gfs_proto.o hash.o host.o hostspec.o iobuffer.o \ import_help.o logutil.o metadb_gfmd.o metadb_misc.o schedule.o \ stringlist.o url.o xxx_proto.o io_fd.o \ $(globus_objs) all: lib$(LIB).a lib$(LIB).a: $(OBJS) ar rucv lib$(LIB).a $(OBJS) $(RANLIB) lib$(LIB).a install: all $(INSTALL_DATA) lib$(LIB).a $(libdir) clean:; rm -f *.o veryclean: clean rm -f lib$(LIB).a distclean: veryclean ### $(OBJS): $(INCDIR)/gfarm.h $(INCDIR)/gfarm_error.h $(INCDIR)/gfarm_metadb.h $(INCDIR)/gfarm_misc.h $(INCDIR)/gfs.h hash.h iobuffer.h xxx_proto.h gfs_proto.h gfs_client.h $(GLOBUS_OBJS): $(DEPGFSLINC) <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/client2.c #include <sys/types.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <gssapi.h> #include <limits.h> #include "gfutil.h" #include "tcputil.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_secure_session.h" #include "misc.h" #include "scarg.h" static unsigned long int addr = 0L; static char *hostname = NULL; static int ParseArgs(argc, argv) int argc; char *argv[]; { int c, tmp; while ((c = getopt(argc, argv, "h:" COMMON_OPTIONS)) != -1) { switch (c) { case 'h': addr = gfarmIPGetAddressOfHost(optarg); if (addr == ~0L || addr == 0L) { fprintf(stderr, "Invalid hostname.\n"); return -1; } hostname = optarg; break; default: if (HandleCommonOptions(c, optarg) != 0) return -1; break; } } if (optind < argc) { fprintf(stderr, "unknown extra argument %s\n", argv[optind]); return -1; } if (addr == 0L) { fprintf(stderr, "hostname is not specified.\n"); return -1; } if (port == 0) { fprintf(stderr, "port # is not specified.\n"); return -1; } return 0; } int main(argc, argv) int argc; char *argv[]; { OM_uint32 majStat; OM_uint32 minStat; gfarmSecSession *ss0 = NULL; gfarmSecSession *ss1 = NULL; char buf[4096]; int z = 0; int ret = 1; int len; if (ParseArgs(argc, argv) != 0) { goto Done; } gflog_auth_set_verbose(1); if (gfarmSecSessionInitializeInitiator(NULL, NULL, &majStat, &minStat) <= 0) { fprintf(stderr, "can't initialize as initiator because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); goto Done; } if (!acceptorSpecified) { acceptorNameString = malloc(sizeof("host@") + strlen(hostname)); if (acceptorNameString == NULL) { fprintf(stderr, "no memory\n"); goto Done; } sprintf(acceptorNameString, "host@%s", hostname); acceptorNameType = GSS_C_NT_HOSTBASED_SERVICE; } ss0 = gfarmSecSessionInitiateByAddr(addr, port, acceptorNameString, acceptorNameType, GSS_C_NO_CREDENTIAL, NULL, &majStat, &minStat); if (ss0 == NULL) { fprintf(stderr, "Can't initiate session 0 because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); goto Done; } ss1 = gfarmSecSessionInitiateByAddr(addr, port, acceptorNameString, acceptorNameType, GSS_C_NO_CREDENTIAL, NULL, &majStat, &minStat); if (ss1 == NULL) { fprintf(stderr, "Can't initiate session 1 because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); goto Done; } while (fgets(buf, 4096, stdin) != NULL) { len = strlen(buf); if (buf[len - 1] == '\n') { len--; } if (z % 2 == 0) { (void)gfarmSecSessionSendInt8(ss0, buf, len); } else { (void)gfarmSecSessionSendInt8(ss1, buf, len); } z++; } ret = 0; Done: if (ss0 != NULL) { gfarmSecSessionTerminate(ss0); } if (ss1 != NULL) { gfarmSecSessionTerminate(ss1); } gfarmSecSessionFinalizeInitiator(); return ret; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/scarg.c #include <stdio.h> #include <unistd.h> #include <gssapi.h> #include "misc.h" #include "scarg.h" int port = 0; int acceptorSpecified = 0; char *acceptorNameString; gss_OID acceptorNameType; int HandleCommonOptions(option, arg) int option; char *arg; { int tmp; switch (option) { case 'p': if (gfarmGetInt(arg, &tmp) < 0) { fprintf(stderr, "illegal port number.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "port number must be > 0.\n"); return -1; } else if (tmp > 65535) { fprintf(stderr, "port number must be < 65536.\n"); return -1; } port = tmp; break; case 'H': acceptorNameString = arg; acceptorNameType = GSS_C_NT_HOSTBASED_SERVICE; acceptorSpecified = 1; break; case 'M': acceptorNameString = arg; /* mechanism specific name */ acceptorNameType = GSS_C_NO_OID; acceptorSpecified = 1; break; case 'N': acceptorNameString = NULL; /* this feature is GFSL specific */ acceptorNameType = GSS_C_NO_OID; acceptorSpecified = 1; break; case 'n': acceptorNameString = arg; acceptorNameType = GSS_C_NT_USER_NAME; acceptorSpecified = 1; break; case 'U': acceptorNameString = arg; acceptorNameType = GSS_C_NT_STRING_UID_NAME; acceptorSpecified = 1; break; case 'X': acceptorNameString = arg; acceptorNameType = GSS_C_NT_EXPORT_NAME; acceptorSpecified = 1; break; case 'u': acceptorNameString = getenv("USER"); if (acceptorNameString == NULL) acceptorNameString = getenv("LOGNAME"); if (acceptorNameString == NULL) { fprintf(stderr, "neither $USER nor $LOGNAME isn't set"); return -1; } acceptorNameType = GSS_C_NT_USER_NAME; acceptorSpecified = 1; break; default: fprintf(stderr, "error happens at an option\n"); return -1; } return 0; } <file_sep>/gfarm_samba/trunk/gfarm_acl.h /* * $Id$ */ void gfvfs_acl_id_init(); SMB_ACL_T gfvfs_gfarm_acl_to_smb_acl(const char *, gfarm_acl_t); gfarm_acl_t gfvfs_smb_acl_to_gfarm_acl(const char *, SMB_ACL_T); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_4/gfarm2fs_msg_enums.h #define GFARM_MSG_2000001 2000001 #define GFARM_MSG_2000002 2000002 #define GFARM_MSG_2000003 2000003 #define GFARM_MSG_2000004 2000004 #define GFARM_MSG_2000005 2000005 #define GFARM_MSG_2000006 2000006 #define GFARM_MSG_2000007 2000007 #define GFARM_MSG_2000008 2000008 #define GFARM_MSG_2000009 2000009 #define GFARM_MSG_2000010 2000010 #define GFARM_MSG_2000011 2000011 #define GFARM_MSG_2000012 2000012 #define GFARM_MSG_2000013 2000013 #define GFARM_MSG_2000014 2000014 #define GFARM_MSG_2000015 2000015 #define GFARM_MSG_2000016 2000016 #define GFARM_MSG_2000017 2000017 #define GFARM_MSG_2000018 2000018 #define GFARM_MSG_2000019 2000019 #define GFARM_MSG_2000020 2000020 #define GFARM_MSG_2000021 2000021 #define GFARM_MSG_2000022 2000022 #define GFARM_MSG_2000023 2000023 #define GFARM_MSG_2000024 2000024 #define GFARM_MSG_2000025 2000025 #define GFARM_MSG_2000026 2000026 #define GFARM_MSG_2000027 2000027 #define GFARM_MSG_2000028 2000028 #define GFARM_MSG_2000029 2000029 #define GFARM_MSG_2000030 2000030 #define GFARM_MSG_2000031 2000031 #define GFARM_MSG_2000032 2000032 #define GFARM_MSG_2000033 2000033 #define GFARM_MSG_2000034 2000034 #define GFARM_MSG_2000035 2000035 #define GFARM_MSG_2000036 2000036 #define GFARM_MSG_2000037 2000037 #define GFARM_MSG_2000038 2000038 #define GFARM_MSG_2000039 2000039 #define GFARM_MSG_2000040 2000040 #define GFARM_MSG_2000041 2000041 #define GFARM_MSG_2000042 2000042 #define GFARM_MSG_2000043 2000043 #define GFARM_MSG_2000044 2000044 #define GFARM_MSG_2000045 2000045 #define GFARM_MSG_2000046 2000046 #define GFARM_MSG_2000047 2000047 #define GFARM_MSG_2000048 2000048 #define GFARM_MSG_2000049 2000049 #define GFARM_MSG_2000050 2000050 #define GFARM_MSG_2000051 2000051 #define GFARM_MSG_2000052 2000052 #define GFARM_MSG_2000053 2000053 #define GFARM_MSG_2000054 2000054 #define GFARM_MSG_2000055 2000055 #define GFARM_MSG_2000056 2000056 #define GFARM_MSG_2000057 2000057 #define GFARM_MSG_2000058 2000058 #define GFARM_MSG_2000059 2000059 #define GFARM_MSG_2000060 2000060 #define GFARM_MSG_2000061 2000061 #define GFARM_MSG_2000062 2000062 #define GFARM_MSG_2000063 2000063 #define GFARM_MSG_2000064 2000064 #define GFARM_MSG_2000065 2000065 #define GFARM_MSG_2000066 2000066 #define GFARM_MSG_2000067 2000067 #define GFARM_MSG_2000068 2000068 #define GFARM_MSG_2000069 2000069 #define GFARM_MSG_2000070 2000070 #define GFARM_MSG_2000071 2000071 #define GFARM_MSG_2000072 2000072 #define GFARM_MSG_2000073 2000073 #define GFARM_MSG_2000074 2000074 #define GFARM_MSG_2000075 2000075 #define GFARM_MSG_2000076 2000076 #define GFARM_MSG_2000077 2000077 #define GFARM_MSG_2000078 2000078 #define GFARM_MSG_2000079 2000079 #define GFARM_MSG_2000080 2000080 #define GFARM_MSG_2000081 2000081 #define GFARM_MSG_2000082 2000082 #define GFARM_MSG_2000083 2000083 #define GFARM_MSG_2000084 2000084 #define GFARM_MSG_2000085 2000085 #define GFARM_MSG_2000086 2000086 #define GFARM_MSG_2000087 2000087 #define GFARM_MSG_2000088 2000088 #define GFARM_MSG_2000089 2000089 #define GFARM_MSG_2000090 2000090 #define GFARM_MSG_2000091 2000091 #define GFARM_MSG_2000092 2000092 #define GFARM_MSG_2000093 2000093 #define GFARM_MSG_2000094 2000094 #define GFARM_MSG_2000095 2000095 #define GFARM_MSG_2000096 2000096 #define GFARM_MSG_2000097 2000097 #define GFARM_MSG_2000098 2000098 #define GFARM_MSG_2000099 2000099 #define GFARM_MSG_2000100 2000100 #define GFARM_MSG_2000101 2000101 #define GFARM_MSG_2000102 2000102 #define GFARM_MSG_2000103 2000103 #define GFARM_MSG_2000104 2000104 #define GFARM_MSG_2000105 2000105 #define GFARM_MSG_2000106 2000106 #define GFARM_MSG_2000107 2000107 #define GFARM_MSG_2000108 2000108 #define GFARM_MSG_2000109 2000109 #define GFARM_MSG_2000110 2000110 #define GFARM_MSG_2000111 2000111 #define GFARM_MSG_2000112 2000112 #define GFARM_MSG_2000113 2000113 #define GFARM_MSG_2000114 2000114 #define GFARM_MSG_2000115 2000115 #define GFARM_MSG_2000116 2000116 #define GFARM_MSG_2000117 2000117 #define GFARM_MSG_2000118 2000118 #define GFARM_MSG_2000119 2000119 #define GFARM_MSG_2000120 2000120 #define GFARM_MSG_2000121 2000121 #define GFARM_MSG_2000122 2000122 #define GFARM_MSG_2000123 2000123 #define GFARM_MSG_2000124 2000124 <file_sep>/gfarm/tags/gfarm_20050822/gftool/config-gfarm/sysdep/netbsd/gfsd.in #!@RCD_SCRIPTS_SHELL@ # # $NetBSD$ # # Gfarm filesystem node daemon # # PROVIDE: gfsd # REQUIRE: DAEMON if [ -f /etc/rc.subr ]; then . /etc/rc.subr fi name="gfsd" rcvar=${name} command="@PREFIX@/sbin/${name}" required_files="@PKG_SYSCONFDIR@/gfarm.conf" # add more flags through ${${name}_flags} command_args="-P @GFARM_PID_DIR@/${name}.pid" if [ -f /etc/rc.subr ]; then load_rc_config $name run_rc_command "$1" else @ECHO@ -n " ${name}" ${command} ${gfsd_flags} ${command_args} fi <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_3_0/contrib/mount.gfarmfs/mount.gfarmfs #!/bin/sh # # mount.gfarmfs [ username mount_point options ] # # Environment variable: # # GFS_USERNAME global user name in Gfarm (default: $LOGNAME) # GFS_MOUNTDIR mount point (default: /gfs/home/$GFS_USERNAME) # GFARMFS_OPTIONS gfarmfs mount options (default: -lsu) # FUSE_OPTIONS fuse mount options ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } if [ $# -gt 0 ]; then GFS_USERNAME=$1 shift fi if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi if [ $# -gt 0 ]; then FUSE_OPTIONS=$* fi : ${GFS_USERNAME:=$LOGNAME} : ${GFS_MOUNTDIR:=/gfs/home/$GFS_USERNAME} : ${GFARMFS_OPTIONS:=-lsu} : ${FUSE_OPTIONS:=} if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR fi [ -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME gfarmfs -m /$GFS_USERNAME $GFARMFS_OPTIONS $GFS_MOUNTDIR $FUSE_OPTIONS && echo Mount GfarmFS on $GFS_MOUNTDIR exit $? <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/test_zabbix_gfarm_utils.sh #! /bin/sh . ./zbx_gfarm_utils.inc testGfsdConfsDefault () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs "::"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not default!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNotNull "listen address is not empty" ${listen_address} } testGfsdConfsDefault2 () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs ":::"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not default!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNotNull "listen address is not empty" ${listen_address} } testGfsdConfsPrefixSpecifiedFmt1 () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs "/usr/local::"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/usr/local" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNull "listen address is not empty" "${listen_address}" } testGfsdConfsPrefixSpecifiedFmt2 () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs "/usr/local:::"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/usr/local" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNull "listen address is not empty" "${listen_address}" } testGfsdConfsHostSpecified () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs ":gfsd.gfarm.co.jp::"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "gfsd.gfarm.co.jp" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNull "listen address is not empty" "${listen_address}" } testGfsdConfsListenAddressSpecified () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs ":gfsd.gfarm.co.jp:gfsd.gfarm.co.jp:"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "gfsd.gfarm.co.jp" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertEquals "listen addres is not correct!" "gfsd.gfarm.co.jp" "${listen_address}" } testGfsdConfsPortSpecifiedFmt1 () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs "::10600"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "10600" "${port}" assertNull "listen address is not empty" "${listen_address}" } testGfsdConfsPortSpecifiedFmt2 () { read prefix gfsdhost port listen_address <<EOF `parse_gfsd_confs ":::10600"` EOF assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "10600" "${port}" assertNull "listen address is not empty" "${listen_address}" } testGfsdConfsSepareated () { ( read prefix gfsdhost port listen_address assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNull "listen_address is not empty" "${listen_address}" read prefix gfsdhost port listen_address assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "hostname is not correct!" "`hostname -f`" "${gfsdhost}" assertEquals "port is not correct!" "600" "${port}" assertNull "listen_address is not empty" "${listen_address}" )<<EOF `parse_gfsd_confs ":::%:::"` EOF } testGfsdConfsEmptyIsInvalid () { parse_gfsd_confs "" assertEquals "invalid arg should exit with 1" 1 $? } testGfsdConfsTooFewColonIsInvalid () { parse_gfsd_confs ":" assertEquals "invalid arg should exit with 1" 1 $? } testGfsdConfsManyColonIsInvalid () { parse_gfsd_confs "::::" assertEquals "invalid arg should exit with 1" 1 $? } testGfmdConfsDefault () { :<<COMMENTOUT # expects /etc/gfmd.conf as: #========================================== # metadb_server_host dhcp-167-220.sra.co.jp # metadb_server_port 12345 # postgresql_server_host dhcp-167-220.sra.co.jp # postgresql_server_port 5432 # postgresql_dbname gfarm # postgresql_user gfarm # postgresql_password "<PASSWORD>" # admin_user gfadmin # auth enable sharedsecret * # # sockopt keepalive # metadb_replication disable # # mkdir following directory when metadb_replication is set to enable. # metadb_journal_dir /opt/gfarmA/var/gfarm-metadata/journal #========================================== ( read prefix host port assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "host is not correct!" "dhcp-167-220.sra.co.jp" "${host}" assertEquals "port is not correct!" "12345" "${port}" ) <<EOF `read_gfmd_confs` EOF assertEquals "failed to exec" 0 $? COMMENTOUT } testGfmdConfsSeparatedDefaults () { :<<COMMENTOUT # expects /etc/gfmd.conf as: #========================================== # metadb_server_host dhcp-167-220.sra.co.jp # metadb_server_port 12345 # postgresql_server_host dhcp-167-220.sra.co.jp # postgresql_server_port 5432 # postgresql_dbname gfarm # postgresql_user gfarm # postgresql_password "<PASSWORD>" # admin_user gfadmin # auth enable sharedsecret * # # sockopt keepalive # metadb_replication disable # # mkdir following directory when metadb_replication is set to enable. # metadb_journal_dir /opt/gfarmA/var/gfarm-metadata/journal #========================================== ( read prefix host port assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "host is not correct!" "dhcp-167-220.sra.co.jp" "${host}" assertEquals "port is not correct!" "12345" "${port}" read prefix host port assertEquals "failed to read" 0 $? assertEquals "prefix is not correct!" "/" "${prefix}" assertEquals "host is not correct!" "dhcp-167-220.sra.co.jp" "${host}" assertEquals "port is not correct!" "12345" "${port}" ) <<EOF `read_gfmd_confs "%"` EOF assertEquals "failed to exec" 0 $? COMMENTOUT } testGfarmPgsqlConfsDefault () { # expects /etc/gfmd.conf as: #========================================== # metadb_server_host dhcp-167-220.sra.co.jp # metadb_server_port 12345 # postgresql_server_host dhcp-167-220.sra.co.jp # postgresql_server_port 5432 # postgresql_dbname gfarm # postgresql_user gfarm # postgresql_password "<PASSWORD>" # admin_user gfadmin # auth enable sharedsecret * # # sockopt keepalive # metadb_replication disable # # mkdir following directory when metadb_replication is set to enable. # metadb_journal_dir /opt/gfarmA/var/gfarm-metadata/journal #========================================== ( read prefix port db user pass assertEquals "port is not correct!" "5432" "${port}" assertEquals "db is not correct!" "gfarm" "${db}" assertEquals "user is not correct!" "gfarm" "${user}" assertEquals "pass is not correct!" "<PASSWORD>" "${pass}" ) <<EOF `read_gfarm_pgsql_confs ""` EOF assertEquals "failed to exec" 0 $? } testAverage () { result=`echo 5 | average_or_error` assertEquals "failed to exec" 0 $? assertEquals "expect result" 5 $result result=`(echo 1; echo 3) | average_or_error` assertEquals "failed to exec" 0 $? assertEquals "expect result" 2 $result } testAverageWithNegativeValue () { result=`echo -1 | average_or_error` assertEquals "failed to exec" 0 $? assertEquals "expect error" -1 $result result=`(echo 1; echo 3; echo -1; echo 4) | average_or_error` assertEquals "failed to exec" 0 $? assertEquals "expect error" -1 $result } testAverageNoInput () { result=`echo | average_or_error` assertEquals "failed to expect" 0 $? assertEquals "expect error" -1 $result } testPsqlWrapper () { # and database 'gfarm' and table dog as: # id | name # 1 | momo # 2 | pochi result=`psql_wrapper \ localhost \ 5432 \ gfarm \ gfarm \ "02r86NcPiL0IYpt30z3CeVc55PcVpXrkb64=yg1vWhp" \ "SELECT COUNT(*) FROM dog"` assertEquals "failed to exec" 0 $? assertEquals "expect result" "2" ${result} } testGfarmPgsqlExec () { # expect gmfd.conf, and database 'gfarm' and table dog as: # id | name # 1 | momo # 2 | pochi result=`gfarm_pgsql_exec "" 'SELECT COUNT(*) FROM dog'` # assertEquals "failed to exec" 0 $? assertEquals "expect result" "2" ${result} } testGfarmPgsqlExecAndGrouping () { # expect gmfd.conf, and database 'gfarm' and table dog as: # id | name # 1 | momo # 2 | pochi result=`gfarm_pgsql_exec "/%/" 'SELECT COUNT(*) FROM dog' | average_or_error` # assertEquals "failed to exec" 0 $? assertEquals "expect result" "2" ${result} } . shunit2 <file_sep>/gfarm/tags/gfarm_1_0_rc3/lib/libgfarm/gfarm/auth_client.c #include <sys/types.h> /* fd_set */ #include <sys/time.h> #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <limits.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "gfevent.h" #include "xxx_proto.h" #include "auth.h" /* * currently 31 is enough, * but it is possible that future server replies more methods. */ #define GFARM_AUTH_METHODS_BUFFER_SIZE 256 struct gfarm_auth_client_method { enum gfarm_auth_method method; char *(*request)(struct xxx_connection *); char *(*request_multiplexed)(struct gfarm_eventqueue *, struct xxx_connection *, void (*)(void *), void *, void **); char *(*result_multiplexed)(void *); } gfarm_auth_trial_table[] = { /* * This table entry should be prefered order */ { GFARM_AUTH_METHOD_SHAREDSECRET, gfarm_auth_request_sharedsecret, gfarm_auth_request_sharedsecret_multiplexed, gfarm_auth_result_sharedsecret_multiplexed }, #ifdef HAVE_GSI { GFARM_AUTH_METHOD_GSI_AUTH, gfarm_auth_request_gsi_auth, gfarm_auth_request_gsi_auth_multiplexed, gfarm_auth_result_gsi_auth_multiplexed }, { GFARM_AUTH_METHOD_GSI, gfarm_auth_request_gsi, gfarm_auth_request_gsi_multiplexed, gfarm_auth_result_gsi_multiplexed }, #endif { GFARM_AUTH_METHOD_NONE, NULL, NULL, NULL } /* sentinel */ }; char * gfarm_auth_request_sharedsecret(struct xxx_connection *conn) { /* * too weak authentication. * assumes shared home directory. */ char *e, *e_save = NULL, *user, *home; unsigned int expire; char shared_key[GFARM_AUTH_SHARED_KEY_LEN]; char challenge[GFARM_AUTH_CHALLENGE_LEN]; char response[GFARM_AUTH_RESPONSE_LEN]; size_t len; gfarm_int32_t error, error_ignore; /* enum gfarm_auth_error */ int eof, key_create = GFARM_AUTH_SHARED_KEY_CREATE; int try = 0; user = gfarm_get_global_username(); home = gfarm_get_local_homedir(); if (user == NULL || home == NULL) return ( "gfarm_auth_request_sharedsecret(): programming error, " "gfarm library isn't properly initialized"); e = xxx_proto_send(conn, "s", user); if (e != NULL) return (e); do { e = gfarm_auth_shared_key_get(&expire, shared_key, home, key_create); key_create = GFARM_AUTH_SHARED_KEY_CREATE_FORCE; if (e != NULL) { e_save = e; break; } e = xxx_proto_send(conn, "i", GFARM_AUTH_SHAREDSECRET_MD5); if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "i", &error); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (error != GFARM_AUTH_ERROR_NO_ERROR) break; e = xxx_proto_recv(conn, 0, &eof, "b", sizeof(challenge), &len, challenge); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); gfarm_auth_sharedsecret_response_data(shared_key, challenge, response); e = xxx_proto_send(conn, "ib", expire, sizeof(response), response); if (e != NULL) return (e); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (error == GFARM_AUTH_ERROR_NO_ERROR) return (NULL); /* success */ } while (++try < GFARM_AUTH_RETRY_MAX && error == GFARM_AUTH_ERROR_EXPIRED); e = xxx_proto_send(conn, "i", GFARM_AUTH_SHAREDSECRET_GIVEUP); if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "i", &error_ignore); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (e_save != NULL) return (e_save); switch (error) { case GFARM_AUTH_ERROR_NOT_SUPPORTED: return (GFARM_ERR_PROTOCOL_NOT_SUPPORTED); case GFARM_AUTH_ERROR_EXPIRED: return (GFARM_ERR_EXPIRED); default: return (GFARM_ERR_AUTHENTICATION); } } char * gfarm_auth_request(struct xxx_connection *conn, char *name, struct sockaddr *addr, enum gfarm_auth_method *auth_methodp) { char *e, *e_save = NULL; int i, eof; gfarm_int32_t methods, server_methods; /* bitset */ gfarm_int32_t method; /* enum gfarm_auth_method */ gfarm_int32_t error; /* enum gfarm_auth_error */ size_t nmethods; unsigned char methods_buffer[GFARM_AUTH_METHODS_BUFFER_SIZE]; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); methods = gfarm_auth_method_get_enabled_by_name_addr(name, addr); if (methods == 0) return ("gfarm auth method isn't available for the host"); methods &= gfarm_auth_method_get_available(); if (methods == 0) return ("usable auth-method isn't configured"); e = xxx_proto_recv(conn, 0, &eof, "b", sizeof(methods_buffer), &nmethods, methods_buffer); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); server_methods = 0; for (i = 0; i < nmethods; i++) { if (methods_buffer[i] <= GFARM_AUTH_METHOD_NONE || methods_buffer[i] >= GFARM_AUTH_METHOD_NUMBER) continue; server_methods |= 1 << methods_buffer[i]; } for (i = 0;; i++) { method = gfarm_auth_trial_table[i].method; if (method != GFARM_AUTH_METHOD_NONE && (methods & server_methods & (1 << method)) == 0) continue; e = xxx_proto_send(conn, "i", method); if (e != NULL) return (e); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL) return (e); if (eof || error != GFARM_AUTH_ERROR_NO_ERROR) return (GFARM_ERR_PROTOCOL); /* shouldn't happen */ if (method == GFARM_AUTH_METHOD_NONE) { /* give up */ if (server_methods == 0) return (GFARM_ERR_PERMISSION_DENIED); if ((methods & server_methods) == 0) return (GFARM_ERR_PROTOCOL_NOT_SUPPORTED); return (e_save != NULL ? e_save : "gfarm_auth_request: implementation error"); } e = (*gfarm_auth_trial_table[i].request)(conn); if (e == NULL) { if (auth_methodp != NULL) *auth_methodp = method; return (NULL); /* success */ } if (e != GFARM_ERR_PROTOCOL_NOT_SUPPORTED && e != GFARM_ERR_EXPIRED && e != GFARM_ERR_AUTHENTICATION) { /* protocol error */ return (e); } e_save = e; } } /* * multiplexed version of gfarm_auth_request_sharedsecret() * for parallel authentication */ struct gfarm_auth_request_sharedsecret_state { struct gfarm_eventqueue *q; struct gfarm_event *readable, *writable; struct xxx_connection *conn; void (*continuation)(void *); void *closure; char *home; /* for loop */ int try; unsigned int expire; char shared_key[GFARM_AUTH_SHARED_KEY_LEN]; /* results */ char *error, *error_save; gfarm_int32_t proto_error; /* enum gfarm_auth_error */ }; static void gfarm_auth_request_sharedsecret_receive_fin(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int eof; gfarm_int32_t error_ignore; /* enum gfarm_auth_error */ if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 0, &eof, "i", &error_ignore); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error != NULL) ; else if (state->error_save != NULL) { state->error = state->error_save; } else { switch (state->proto_error) { case GFARM_AUTH_ERROR_NOT_SUPPORTED: state->error = GFARM_ERR_PROTOCOL_NOT_SUPPORTED; break; case GFARM_AUTH_ERROR_EXPIRED: state->error = GFARM_ERR_EXPIRED; break; default: state->error = GFARM_ERR_AUTHENTICATION; break; } } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_sharedsecret_send_giveup(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int rv; struct timeval timeout; state->error = xxx_proto_send(state->conn, "i", GFARM_AUTH_SHAREDSECRET_GIVEUP); if (state->error == NULL && (state->error = xxx_proto_flush(state->conn)) == NULL) { gfarm_fd_event_set_callback(state->readable, gfarm_auth_request_sharedsecret_receive_fin, state); timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout)) == 0) { /* go to * gfarm_auth_request_sharedsecret_receive_fin() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_sharedsecret_send_keytype(int events, int fd, void *closure, const struct timeval *t); static void gfarm_auth_request_sharedsecret_receive_result(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int rv, eof; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 1, &eof, "i", &state->proto_error); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL) { if (state->proto_error != GFARM_AUTH_ERROR_NO_ERROR) { gfarm_fd_event_set_callback(state->writable, (++state->try < GFARM_AUTH_RETRY_MAX && state->proto_error == GFARM_AUTH_ERROR_EXPIRED) ? gfarm_auth_request_sharedsecret_send_keytype : gfarm_auth_request_sharedsecret_send_giveup, state); rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL); if (rv == 0) return; state->error = gfarm_errno_to_error(rv); } } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_sharedsecret_receive_challenge(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int rv, eof; char challenge[GFARM_AUTH_CHALLENGE_LEN]; char response[GFARM_AUTH_RESPONSE_LEN]; size_t len; struct timeval timeout; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 0, &eof, "b", sizeof(challenge), &len, challenge); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL) { /* XXX It's better to check writable event here */ gfarm_auth_sharedsecret_response_data( state->shared_key, challenge, response); state->error = xxx_proto_send(state->conn, "ib", state->expire, sizeof(response), response); if (state->error == NULL && (state->error = xxx_proto_flush(state->conn)) == NULL) { gfarm_fd_event_set_callback(state->readable, gfarm_auth_request_sharedsecret_receive_result, state); timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); if (rv == 0) { /* go to gfarm_..._receive_result() */ return; } state->error = gfarm_errno_to_error(rv); } } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_sharedsecret_receive_keytype(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int rv, eof; struct timeval timeout; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); /* We need just==1 here, because we may wait an event next. */ state->error = xxx_proto_recv(state->conn, 1, &eof, "i", &state->proto_error); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL) { if (state->proto_error != GFARM_AUTH_ERROR_NO_ERROR) { gfarm_fd_event_set_callback(state->writable, gfarm_auth_request_sharedsecret_send_giveup, state); rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL); } else { gfarm_fd_event_set_callback(state->readable, gfarm_auth_request_sharedsecret_receive_challenge, state); timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); } if (rv == 0) { /* * go to * gfarm_auth_request_sharedsecret_send_giveup() * or *gfarm_auth_request_sharedsecret_receive_challenge() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_sharedsecret_send_keytype(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_sharedsecret_state *state = closure; int rv; struct timeval timeout; state->error_save = gfarm_auth_shared_key_get( &state->expire, state->shared_key, state->home, state->try == 0 ? GFARM_AUTH_SHARED_KEY_CREATE : GFARM_AUTH_SHARED_KEY_CREATE_FORCE); if (state->error_save != NULL) { gfarm_auth_request_sharedsecret_send_giveup(events, fd, closure, t); return; } state->error = xxx_proto_send(state->conn, "i", GFARM_AUTH_SHAREDSECRET_MD5); if (state->error == NULL && (state->error = xxx_proto_flush(state->conn)) == NULL) { timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout)) == 0) { /* go to gfarm_auth_request_sharedsecret * _receive_keytype() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } char * gfarm_auth_request_sharedsecret_multiplexed(struct gfarm_eventqueue *q, struct xxx_connection *conn, void (*continuation)(void *), void *closure, void **statepp) { char *e, *user, *home; struct gfarm_auth_request_sharedsecret_state *state; int rv, sock = xxx_connection_fd(conn); user = gfarm_get_global_username(); home = gfarm_get_local_homedir(); if (user == NULL || home == NULL) return ( "gfarm_auth_request_sharedsecret(): programming error, " "gfarm library isn't properly initialized"); /* XXX It's better to check writable event here */ e = xxx_proto_send(conn, "s", user); if (e != NULL) return (e); state = malloc(sizeof(*state)); if (state == NULL) return (GFARM_ERR_NO_MEMORY); state->writable = gfarm_fd_event_alloc( GFARM_EVENT_WRITE, sock, gfarm_auth_request_sharedsecret_send_keytype, state); if (state->writable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_state; } /* * We cannt use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, sock, gfarm_auth_request_sharedsecret_receive_keytype, state); if (state->readable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_writable; } /* go to gfarm_auth_request_sharedsecret_send_user() */ rv = gfarm_eventqueue_add_event(q, state->writable, NULL); if (rv != 0) { e = gfarm_errno_to_error(rv); goto error_free_readable; } state->q = q; state->conn = conn; state->continuation = continuation; state->closure = closure; state->home = home; state->try = 0; state->error = state->error_save = NULL; *statepp = state; return (NULL); error_free_readable: gfarm_event_free(state->readable); error_free_writable: gfarm_event_free(state->writable); error_free_state: free(state); return (e); } char * gfarm_auth_result_sharedsecret_multiplexed(void *sp) { struct gfarm_auth_request_sharedsecret_state *state = sp; char *e = state->error; gfarm_event_free(state->readable); gfarm_event_free(state->writable); free(state); return (e); } /* * multiplexed version of gfs_auth_request() for parallel authentication */ struct gfarm_auth_request_state { struct gfarm_eventqueue *q; struct gfarm_event *readable, *writable; struct xxx_connection *conn; char *name; struct sockaddr *addr; void (*continuation)(void *); void *closure; gfarm_int32_t methods, server_methods; /* bitset */ /* loop state */ int auth_method_index; void *method_state; char *last_error; /* results */ char *error; }; static void gfarm_auth_request_next_method(struct gfarm_auth_request_state *state) { int rv; if (state->last_error == NULL || (state->last_error != GFARM_ERR_PROTOCOL_NOT_SUPPORTED && state->last_error != GFARM_ERR_EXPIRED && state->last_error != GFARM_ERR_AUTHENTICATION)) { state->error = state->last_error; } else { if ((rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL)) == 0) { ++state->auth_method_index; /* go to gfarm_auth_request_loop_ask_method() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_dispatch_result(void *closure) { struct gfarm_auth_request_state *state = closure; state->last_error = (*gfarm_auth_trial_table[state->auth_method_index]. result_multiplexed)(state->method_state); gfarm_auth_request_next_method(state); } static void gfarm_auth_request_dispatch_method(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_state *state = closure; int eof; gfarm_int32_t error; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 1, &eof, "i", &error); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL && error != GFARM_AUTH_ERROR_NO_ERROR) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL) { if (gfarm_auth_trial_table[state->auth_method_index].method != GFARM_AUTH_METHOD_NONE) { state->last_error = (*gfarm_auth_trial_table[state->auth_method_index]. request_multiplexed)(state->q, state->conn, gfarm_auth_request_dispatch_result, state, &state->method_state); if (state->last_error == NULL) { /* * call gfarm_auth_request_$method, then * go to gfarm_auth_request_dispatch_result() */ return; } gfarm_auth_request_next_method(state); return; } /* give up */ if (state->server_methods == 0) { state->error = GFARM_ERR_PERMISSION_DENIED; } else if ((state->methods & state->server_methods) == 0) { state->error = GFARM_ERR_PROTOCOL_NOT_SUPPORTED; } else { state->error = state->last_error != NULL ? state->last_error : "gfarm_auth_request_multiplexed: " "implementation error"; } } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_loop_ask_method(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_state *state = closure; gfarm_int32_t method; /* enum gfarm_auth_method */ int rv; struct timeval timeout; method = gfarm_auth_trial_table[state->auth_method_index].method; while (method != GFARM_AUTH_METHOD_NONE && (state->methods & state->server_methods & (1 << method)) == 0) { method = gfarm_auth_trial_table[++state->auth_method_index].method; } state->error = xxx_proto_send(state->conn, "i", method); if (state->error == NULL && (state->error = xxx_proto_flush(state->conn)) == NULL) { gfarm_fd_event_set_callback(state->readable, gfarm_auth_request_dispatch_method, state); timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout)) == 0) { /* go to gfarm_auth_request_dispatch_method() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_receive_server_methods(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_state *state = closure; int rv, i, eof; size_t nmethods; unsigned char methods_buffer[GFARM_AUTH_METHODS_BUFFER_SIZE]; if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 0, &eof, "b", sizeof(methods_buffer), &nmethods, methods_buffer); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL) { state->server_methods = 0; for (i = 0; i < nmethods; i++) { if (methods_buffer[i] <= GFARM_AUTH_METHOD_NONE || methods_buffer[i] >= GFARM_AUTH_METHOD_NUMBER) continue; state->server_methods |= 1 << methods_buffer[i]; } if ((rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL)) == 0) { state->last_error = NULL; state->auth_method_index = 0; /* go to gfarm_auth_request_loop_ask_method() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } char * gfarm_auth_request_multiplexed(struct gfarm_eventqueue *q, struct xxx_connection *conn, char *name, struct sockaddr *addr, void (*continuation)(void *), void *closure, struct gfarm_auth_request_state **statepp) { char *e; int rv, sock = xxx_connection_fd(conn); struct gfarm_auth_request_state *state; gfarm_int32_t methods; /* bitset */ struct timeval timeout; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); methods = gfarm_auth_method_get_enabled_by_name_addr(name, addr); if (methods == 0) return ("gfarm auth method isn't available for the host"); methods &= gfarm_auth_method_get_available(); if (methods == 0) return ("usable auth-method isn't configured"); state = malloc(sizeof(*state)); if (state == NULL) return (GFARM_ERR_NO_MEMORY); state->writable = gfarm_fd_event_alloc( GFARM_EVENT_WRITE, sock, gfarm_auth_request_loop_ask_method, state); if (state->writable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_state; } /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, sock, gfarm_auth_request_receive_server_methods, state); if (state->readable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_writable; } /* go to gfarm_auth_request_receive_server_methods() */ timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(q, state->readable, &timeout); if (rv != 0) { e = gfarm_errno_to_error(rv); goto error_free_readable; } state->q = q; state->conn = conn; state->name = name; state->addr = addr; state->methods = methods; state->continuation = continuation; state->closure = closure; state->error = NULL; *statepp = state; return (NULL); error_free_readable: gfarm_event_free(state->readable); error_free_writable: gfarm_event_free(state->writable); error_free_state: free(state); return (e); } char * gfarm_auth_result_multiplexed(struct gfarm_auth_request_state *state, enum gfarm_auth_method *auth_methodp) { char *e = state->error; if (e == NULL) { if (auth_methodp != NULL) *auth_methodp = gfarm_auth_trial_table[ state->auth_method_index].method; } gfarm_event_free(state->readable); gfarm_event_free(state->writable); free(state); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/gftool/gfrmdir/gfrmdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <unistd.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include <gfarm/gfarm_error.h> #include "gfs_client.h" char *program_name = "gfrmdir"; static void usage() { fprintf(stderr, "Usage: %s directory...\n", program_name); exit(1); } struct args { char *path; }; char * gfrmdir(struct gfs_connection *gfs_server, void *args) { struct args *a = args; char *e = gfs_client_rmdir(gfs_server, a->path); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* * We don't treat this as error to remove path_info in MetaDB */ fprintf(stderr, "%s on %s: %s\n", program_name, gfs_client_hostname(gfs_server), e); return (NULL); } return (e); } int main(int argc, char **argv) { char *e, *canonic_path; int i, c; extern int optind; if (argc <= 1) usage(); program_name = basename(argv[0]); while ((c = getopt(argc, argv, "h")) != EOF) { switch (c) { case 'h': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < argc; i++) { char *e; struct args a; struct gfarm_path_info pi; GFS_Dir dir; struct gfs_dirent *entry; int nhosts_succeed; e = gfarm_url_make_path(argv[i], &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path(argv[i], &canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); continue; } e = gfarm_path_info_get(canonic_path, &pi); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (!GFARM_S_ISDIR(pi.status.st_mode)) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], GFARM_ERR_NOT_A_DIRECTORY); free(canonic_path); gfarm_path_info_free(&pi); continue; } gfarm_path_info_free(&pi); e = gfs_opendir(argv[i], &dir); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } e = gfs_readdir(dir, &entry); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } if (entry != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], "directory not empty"); free(canonic_path); continue; } a.path = canonic_path; e = gfs_client_apply_all_hosts(gfrmdir, &a, program_name, &nhosts_succeed); #if 0 /* XXX - gfrmdir may fail. In the current release, Only problem * is that a new directory cannot be created in the other * owner/permission. */ if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } #endif e = gfarm_path_info_remove(canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } free(canonic_path); } e = gfarm_terminate(); return (0); } <file_sep>/gfarm/tags/gfarm_1_0_beta_5/gftool/gfmkdir/gfmkdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <unistd.h> #include <sys/time.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include <gfarm/gfarm_error.h> #include "gfs_client.h" char *program_name = "gfmkdir"; static void usage() { fprintf(stderr, "Usage: %s directory...\n", program_name); exit(1); } struct args { char *path; gfarm_int32_t mode; int may_exist; }; char * gfmkdir(struct gfs_connection *gfs_server, void *args) { struct args *a = args; char *e; e = gfs_client_mkdir(gfs_server, a->path, a->mode); if (a->may_exist && e == GFARM_ERR_ALREADY_EXISTS) return (NULL); return (e); } int main(int argc, char **argv) { char *e, *canonic_path; int i, c; char *user; if (argc <= 1) usage(); program_name = basename(argv[0]); while ((c = getopt(argc, argv, "h")) != EOF) { switch (c) { case 'h': default: usage(); } } e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } user = gfarm_get_global_username(); if (user == NULL) { fprintf(stderr, "%s:%s%s\n", program_name, "programming error, gfarm library isn't properly ", "initialized"); exit(1); } for (i = 1; i < argc; i++) { struct args a; struct gfarm_path_info pi; struct timeval now; int nhosts_succeed; e = gfarm_url_make_path_for_creation(argv[i], &canonic_path); /* We permit missing gfarm: prefix here as a special case */ if (e == GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING) e = gfarm_canonical_path_for_creation(argv[i], &canonic_path); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } if (gfarm_path_info_get(canonic_path, &pi) == 0) { /* * XXX We should make this error, * even if it's GFARM_S_ISDIR() case. * But We cannot actually do it, * becauase currently we don't record directory * operation failure in anywhere. * Thus, we must permit user to retry the gfmkdir * operation. */ if (!GFARM_S_ISDIR(pi.status.st_mode)) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], GFARM_ERR_ALREADY_EXISTS); gfarm_path_info_free(&pi); continue; } gfarm_path_info_free(&pi); /* * don't report error, * if the directory already exists */ a.may_exist = 1; } else { a.may_exist = 0; } a.path = canonic_path; a.mode = 0755; e = gfs_client_apply_all_hosts(gfmkdir, &a, program_name, &nhosts_succeed); #if 0 /* XXX - gfmkdir may fail. However, it will be created by the * following open operation. */ if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); if (nhosts_succeed == 0) { free(canonic_path); continue; } } #endif gettimeofday(&now, NULL); pi.pathname = canonic_path; pi.status.st_mode = (GFARM_S_IFDIR | a.mode); pi.status.st_user = user; pi.status.st_group = "*"; /* XXX for now */ pi.status.st_atimespec.tv_sec = pi.status.st_mtimespec.tv_sec = pi.status.st_ctimespec.tv_sec = now.tv_sec; pi.status.st_atimespec.tv_nsec = pi.status.st_mtimespec.tv_nsec = pi.status.st_ctimespec.tv_nsec = now.tv_usec * 1000; pi.status.st_size = 0; pi.status.st_nsections = 0; e = gfarm_path_info_set(canonic_path, &pi); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(1); } free(canonic_path); } e = gfarm_terminate(); return (0); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_1/systest/testcases/Makefile.am testcasesdir = $(datadir)/gfarm/systest/testcases dist_testcases_DATA = read_files \ write_files \ write_files_each_mntpnts \ make_file \ make_dir \ copy_file_local_to_gfarm \ copy_file_gfarm_to_gfarm \ copy_file_gfarm_to_local \ copy_dir_local_to_gfarm \ copy_dir_gfarm_to_gfarm \ copy_dir_gfarm_to_local \ gfmd_ifdown_in_write \ gfmd_ifdown_in_read \ operation_in_gfmd_ifdown \ pgsql_down_in_write \ pgsql_down_in_read \ operation_in_pgsql_down \ client_ifdown_in_write \ client_ifdown_in_read \ operation_in_client_ifdown \ gfsd_ifdown_in_write \ gfsd_ifdown_in_read \ gfsd_ifdown_in_rep \ operation_in_gfsd_ifdown \ append_in_gfsd_ifdown \ delete_in_gfsd_ifdown \ rename_in_gfsd_ifdown \ copy_in_gfsd_ifdown \ append_immediately_in_gfsd_ifdown \ two_gfsd_ifdown_in_write \ two_gfsd_ifdown_in_read \ two_gfsd_ifdown_in_rep \ operation_in_two_gfsd_ifdown \ append_in_two_gfsd_ifdown \ delete_in_two_gfsd_ifdown \ rename_in_two_gfsd_ifdown \ copy_in_two_gfsd_ifdown \ gfmd_failover_in_write \ gfmd_failover_in_read \ write_in_gfmd_failover \ read_in_gfmd_failover \ useradd_in_gfmd_failover \ userlist_in_gfmd_failover \ userdel_in_gfmd_failover \ start_gfsd_in_gfmd_failover \ mount_in_gfmd_failover \ rep_in_gfmd_failover \ operation_after_gfmd_failover \ continuous_operation <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/gfarm-zabbix_scripts/externalscripts/zbx_gfarm2_mds_upgrade.sh.in #!/bin/sh # # @(#) zbx_gfarm2_mds_upgrade.sh # # Usage: # zbx_gfarm2_mds_upgrade.sh # # Description: # Upgrade script for a slave metadata server on a redundant Gfarm2 file # system. # ############################################################################### # defines PID_FILE=@GFMD_PIDFILE@ # execute upgrade command PID=`cat $PID_FILE` kill -USR1 $PID if [ $? -eq 0 ]; then echo "success" else echo "error" fi exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT-common #! /bin/sh # # Functions and definitions commonly used by test case scripts. # # Path to 'gfservice' command and its arguments. FT_GFSERVICE_CONF="./gfservice.conf" gfservice="/usr/local/gfarm/bin/gfservice -f $FT_GFSERVICE_CONF" . "$FT_GFSERVICE_CONF" # Install prefix of gf* commands on remote nodes. GFARM_PREFIX="/usr/local/gfarm" # log file. FT_LOG=log FT_TMP_LOG=log.tmp # Timeout interval for receiving an expected alert mail. FT_MAIL_TIMEOUT=600 # Check mails every $FT_MAIL_WAIT_INTERVAL seconds. FT_MAIL_CHECK_INTERVAL=10 # Timeout interval for waiting fail over of gfmd. FT_FAILOVER_TIMEOUT=600 # Check completion of failover every $FT_FAILOVER_CHECK_INTERVAL seconds. FT_FAILOVER_CHECK_INTERVAL=30 # Check completion of a remote command every $FT_PROCESS_CHECK_INTERVAL seconds. FT_PROCESS_CHECK_INTERVAL=30 # Mbox file. FT_MBOX_FILE=/var/spool/mail/$USER FT_MBOX_BACKUP_FILE_PREFIX=mbox FT_MBOX_BACKUP_TMP_FILE=mbox.tmp # Test case scrips. FT_TEST_SCRIPT_PATTERN="FT*_*" # # Result codes. # FT_RESULT_PASS=0 FT_RESULT_FAIL=1 FT_RESULT_XPASS=2 # passed, but it's unexpected. fixed recently? FT_RESULT_XFAIL=3 # failed, but it's expected. i.e. known bug. FT_RESULT_UNRESOLVED=4 # cannot determine whether (X)?PASS or (X)?FAIL FT_RESULT_UNTESTED=5 # not tested, this test haven't written yet. FT_RESULT_UNSUPPORTED=6 # not tested, this environment can't test this. FT_RESULT_TRAP=7 # killed by Control-C or something # # Convert a result code to a string. # # $1 ... result code. # # It prints a result code string corresponding with $1 to standard out. # result_string() { [ $1 -eq $FT_RESULT_PASS ] && { echo "PASS"; return 0; } [ $1 -eq $FT_RESULT_FAIL ] && { echo "FAIL"; return 0; } [ $1 -eq $FT_RESULT_XPASS ] && { echo "XPASS"; return 0; } [ $1 -eq $FT_RESULT_XFAIL ] && { echo "XFAIL"; return 0; } [ $1 -eq $FT_RESULT_UNRESOLVED ] && { echo "UNRESOLVED"; return 0; } [ $1 -eq $FT_RESULT_UNTESTED ] && { echo "UNTESTED"; return 0; } [ $1 -eq $FT_RESULT_UNSUPPORTED ] && { echo "UNSUPPORTED"; return 0; } [ $1 -eq $FT_RESULT_TRAP ] && { echo "TRAP"; return 0; } echo "UNKNOWN"; return 0 } # # Report a checkpoint of the test case. # # $1 ... checkpoint no (1, 2, 3 ...) # $2 ... title # $3 ... result code # ft_checkpoint() { awk "BEGIN {printf(\" checkpoint [%3s] %-40s ... %s\\n\", \"$1\", \"$2\", \""`result_string $3`"\")}" >> $FT_TMP_LOG } # # Wait a mail which has a subject '$1'. # # $1 ... search string. # # The function returns 0 if it finds an expected mail. Otherwise it # returns 1. # ft_check_mail() { _I_=0 while [ $_I_ -le $FT_MAIL_TIMEOUT ]; do ./mbox-search -f $FT_MBOX_FILE -r -t 10 "$1" && return 0 sleep $FT_MAIL_CHECK_INTERVAL _I_=`expr $_I_ + $FT_MAIL_CHECK_INTERVAL` done return 1 } # # Wait mails which have subjects '$1', '$2', ... # # $@ ... search strings # # The function returns 0 if it finds all mails. Otherwise it returns 1. # ft_check_mails() { _I_=0 while [ $# -gt 0 ]; do [ $_I_ -le $FT_MAIL_TIMEOUT ] || return 1 if ./mbox-search -f $FT_MBOX_FILE -r -t 10 "$1"; then shift continue fi sleep $FT_MAIL_CHECK_INTERVAL _I_=`expr $_I_ + $FT_MAIL_CHECK_INTERVAL` done return 0 } # # Truncate an mbox file to size of 0 byte. # ft_truncate_mbox() { ./mbox-search -f $FT_MBOX_FILE -b $FT_MBOX_BACKUP_TMP_FILE return 0 } # # Wait for a failed over of gfmd. # # $1 ... previous master gfmd. # ft_wait_failover() { _I_=0 while [ $_I_ -le $FT_FAILOVER_TIMEOUT ]; do case X`gfmdhost -l 2> /dev/null \ | awk "{if (\\$2 == \"master\") print \\$6}"` in X) true ;; X$1) true ;; *) return 0 ;; esac sleep $FT_FAILOVER_CHECK_INTERVAL _I_=`expr $_I_ + $FT_FAILOVER_CHECK_INTERVAL` done return 1 } # # Wait for a remote command execution. # # $1 ... remote host. # $2 ... command. # ft_wait_remote_process() { _HOST_=$1 _CMD_=$2 while [ "X`ssh $_HOST_ \"ps -ef | grep '$_CMD_' | grep -v grep \"`" != X ]; do sleep $FT_PROCESS_CHECK_INTERVAL; done return 0 } # # It prints a master candidate metadata server name. # ft_get_master_candidate() { _MAX_SEQNUM_FILE_="/var/tmp/seqnum.txt" _SLAVE_LIST_=`ssh $zabbix1 gfmdhost -l 2> /dev/null \ | grep "^+ \+slave \+sync \+c \+" | awk '{ print $6 }'` echo -n > $_MAX_SEQNUM_FILE_ [ -f $_MAX_SEQNUM_FILE_ ] || return 1; for _SLAVE_ in $_SLAVE_LIST_ ; do _MAX_SEQNUM_=`ssh $_SLAVE_ \ sudo /etc/zabbix/externalscripts/zbx_chk_gfjournal_gfmd.sh` if [ $? -ne 0 ] || [ X"$_MAX_SEQNUM_" = X ]; then continue fi echo $_MAX_SEQNUM_ $_SLAVE_ >> $_MAX_SEQNUM_FILE_ done _CANDIDATE_HOST_=`sort -nr $_MAX_SEQNUM_FILE_ | awk '{ print $2 };' | head -1` _I_=1 while [ "X`eval echo \\$gfmd${_I_}`" != X ]; do if [ "X$_CANDIDATE_HOST_" = "X`eval echo \\$gfmd${_I_}`" ] then echo gfmd${_I_} return 0 fi _I_=`expr $_I_ + 1` done return 1 } # # Reset gfmd servers. # At teardown, we have to make gfmd1 to be a master and other gfmd servers # to be slaves for the next test case. # ft_reset_gfmd() { ./FT-unconfig >> $FT_LOG 2>&1 ./FT-config >> $FT_LOG 2>&1 return 0 } # # Signal handler # ft_trap() { echo $FT_RESULT_TRAP cat $FT_TMP_LOG awk "BEGIN {printf(\"@:= %-13s %-43s ... %s\\n\", \"$1\", \"$2\", \"$FT_RESULT_TRAP\")}" >> $FT_LOG cat $FT_TMP_LOG >> $FT_LOG ft_teardown >> $FT_LOG 2>&1 rm -f $FT_TMP_LOG exit $FT_RESULT_TRAP } # # Run a test case. # # $1 ... test ID. # $2 ... title. # ft_run() { # # Setup. # rm -f $FT_TMP_LOG touch $FT_TMP_LOG rm -f $FT_MBOX_BACKUP_TMP_FILE touch $FT_MBOX_BACKUP_TMP_FILE awk "BEGIN {printf(\"--- %-13s %-43s ... \", \"$1\", \"$2\")}" awk "BEGIN {printf(\"--- %-13s %-43s ... BEGIN\\n\", \"$1\", \"$2\")}" >> $FT_LOG date +'@@_ start at %s - %Y-%m-%d %H:%M:%S' >>$FT_LOG trap "ft_trap" 1 2 3 15 _RESULT_=$FT_RESULT_PASS ft_setup >> $FT_LOG 2>&1 _RESULT_=$? if [ $_RESULT_ -ne 0 ]; then echo "failed to setup $1" echo " failed to setup $1" >> $FT_LOG fi # Truncate the mbox file. ./mbox-search -f $FT_MBOX_FILE # # Main. # if [ $_RESULT_ -eq 0 ]; then ft_main >> $FT_LOG 2>&1 _RESULT_=$? _RESULT_STRING_=`result_string $_RESULT_` fi # # Teardown. # echo $_RESULT_STRING_ cat $FT_TMP_LOG awk "BEGIN {printf(\"@:= %-13s %-43s ... %s\\n\", \"$1\", \"$2\", \"$_RESULT_STRING_\")}" >> $FT_LOG cat $FT_TMP_LOG >> $FT_LOG ft_teardown >> $FT_LOG 2>&1 date +'@@~ end at %s - %Y-%m-%d %H:%M:%S' >>$FT_LOG echo "--- ------------------------------------------------------------ ----" >> $FT_LOG rm -f $FT_TMP_LOG ft_truncate_mbox mv -f $FT_MBOX_BACKUP_TMP_FILE "$FT_MBOX_BACKUP_FILE_PREFIX.$1" exit $_RESULT_ } # # Run all test scripts. # ft_run_all() { _N_PASS_=0 _N_FAIL_=0 _N_XPASS_=0 _N_XFAIL_=0 _N_UNRESOLVED_=0 _N_UNTESTED_=0 _N_UNSUPPORTED_=0 _N_TRAP_=0 _N_UNKNOWN_=0 for _FILE_ in `/bin/sh -c "echo $FT_TEST_SCRIPT_PATTERN"`; do [ -x "$_FILE_" ] || continue ./$_FILE_ _RESULT_=$? case $_RESULT_ in $FT_RESULT_PASS) _N_PASS_=`expr $_N_PASS_ + 1` ;; $FT_RESULT_FAIL) _N_FAIL_=`expr $_N_FAIL_ + 1` ;; $FT_RESULT_XPASS) _N_XPASS_=`expr $_N_XPASS_ + 1` ;; $FT_RESULT_XFAIL) _N_XFAIL_=`expr $_N_XFAIL_ + 1` ;; $FT_RESULT_UNRESOLVED) _N_UNRESOLVED_=`expr $_N_UNRESOLVED_ + 1` ;; $FT_RESULT_UNTESTED) _N_UNTESTED_=`expr $_N_UNTESTED_ + 1` ;; $FT_RESULT_UNSUPPORTED) _N_UNSUPPORTED_=`expr $_N_UNSUPPORTED_ + 1` ;; $FT_RESULT_TRAP) _N_TRAP_=`expr $_N_TRAP_ + 1` ;; *) _N_UNKNOWN_=`expr $_N_UNKNOWN_ + 1` ;; esac done echo "Total test: `expr $_N_PASS_ + $_N_FAIL_`" echo " success : $_N_PASS_" echo " failure : $_N_FAIL_" [ $_N_XPASS_ -gt 0 ] \ && echo " unexpected success : $_N_XPASS_" [ $_N_XFAIL_ -gt 0 ] \ && echo " expected failure : $_N_XFAIL_" [ $_N_UNRESOLVED_ -gt 0 ] \ && echo " unresolved : $_N_UNRESOLVED_" [ $_N_UNTESTED_ -gt 0 ] \ && echo " untested : $_N_UNTESTED_" [ $_N_UNSUPPORTED_ -gt 0 ] \ && echo " unsupported : $_N_UNSUPPORTED_" exit 0 } <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT2-2-2-4_master_and_non_candidate_slave_gfmd_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-4" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd and a slave gfmd which is not master candidate down" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd2 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/auth_server_gsi.c #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <grp.h> #include <sys/types.h> #include <time.h> #include <pwd.h> #include <gssapi.h> #include <stdio.h> #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "xxx_proto.h" #include "io_fd.h" #include "io_gfsl.h" #include "auth.h" #include "gfutil.h" /* * Delegated credential */ static gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL; void gfarm_gsi_set_delegated_cred(gss_cred_id_t cred) { delegated_cred = cred; } gss_cred_id_t gfarm_gsi_get_delegated_cred() { return (delegated_cred); } /* * */ char * gfarm_authorize_gsi(struct xxx_connection *conn, int switch_to, char **global_usernamep) { int fd = xxx_connection_fd(conn); char *e, *e2, *global_username; OM_uint32 e_major; gfarmSecSession *session; gfarmAuthEntry *userinfo; e = xxx_proto_flush(conn); if (e != NULL) return (e); e = gfarm_gsi_initialize(); if (e != NULL) return (e); session = gfarmSecSessionAccept(fd, GSS_C_NO_CREDENTIAL, NULL, &e_major); if (session == NULL) { #if 1 /* XXX for debugging */ fprintf(stderr, "Can't accept session because of:\n"); gfarmGssPrintStatus(stderr, e_major); #endif return (GFARM_ERR_AUTHENTICATION); } xxx_connection_set_secsession(conn, session); userinfo = gfarmSecSessionGetInitiatorInfo(session); #if 1 /* XXX - global name should be distinguished by DN (distinguish name) */ e = gfarm_local_to_global_username( userinfo->authData.userAuth.localName, &global_username); if (e != NULL) { e2 = xxx_proto_send(conn, "i", GFARM_AUTH_ERROR_DENIED); if (e2 == NULL) e2 = xxx_proto_flush(conn); gfarmSecSessionTerminate(session); xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); gflog_error("authorize_gsi: " "cannot map global username into local username", userinfo->authData.userAuth.localName); return (e); } #else e = gfarm_DN_to_global_username(userinfo->distName, &global_username); if (e != NULL) { e2 = xxx_proto_send(conn, "i", GFARM_AUTH_ERROR_DENIED); if (e2 == NULL) e2 = xxx_proto_flush(conn); gfarmSecSessionTerminate(session); xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); gflog_error( "authorize_gsi: cannot map DN into global username", userinfo->distName); return (e != NULL ? e : GFARM_ERR_AUTHENTICATION); } #endif e = xxx_proto_send(conn, "i", GFARM_AUTH_ERROR_NO_ERROR); if (e == NULL) e = xxx_proto_flush(conn); if (e != NULL) { gfarmSecSessionTerminate(session); xxx_connection_set_fd(conn, fd); return (e); } if (switch_to) { gflog_set_auxiliary_info(global_username); /* * because the name returned by getlogin() is * an attribute of a session on 4.4BSD derived OSs, * we should create new session before calling * setlogin(). */ setsid(); #ifdef HAVE_SETLOGIN setlogin(userinfo->authData.userAuth.localName); #endif initgroups(userinfo->authData.userAuth.localName, userinfo->authData.userAuth.gid); gfarmSecSessionDedicate(session); gfarm_set_global_username(global_username); gfarm_set_local_username( userinfo->authData.userAuth.localName); gfarm_set_local_homedir( userinfo->authData.userAuth.homeDir); /* set the delegated credential. */ gfarm_gsi_set_delegated_cred( gfarmSecSessionGetDelegatedCredential(session)); } else { if (global_usernamep == NULL) /* see below */ free(global_username); } /* * global_username may continue to be refered, * if (switch_to) as gflog_set_auxiliary_info() * else if (global_usernamep != NULL) as *global_usernamep */ if (global_usernamep != NULL) *global_usernamep = global_username; return (NULL); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT1-2-1-4_high_load_average #! /bin/sh ###################################################################### TESTID="FT1-2-1-4" CATEGORY="accident causes no failover" SECTION="common observed properties" TITLE="common observed properties " ###################################################################### . ./FT-common ft_setup() { STRESS_CMD=bin/cpu-stress STRESS_NPROCS=6 STRESS_PERIOD=$FT_MAIL_TIMEOUT ssh $gfmd1 mkdir -p `dirname $STRESS_CMD` ssh $gfmd1 tee $STRESS_CMD < ./cpu-stress > /dev/null ssh $gfmd1 chmod a+x $STRESS_CMD return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfmd1 $STRESS_CMD -t $STRESS_PERIOD -n $STRESS_NPROCS & [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "start 'cpu-stress'" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Processor load is too high on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd1 pkill `basename $STRESS_CMD` ft_checkpoint 3 "stop 'cpu-stress'" $RESULT ft_check_mail "Re: Processor load is too high on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/debian/gfmd.postinst #!/bin/sh -e . /usr/share/debconf/confmodule echo 'Run /usr/sbin/config-gfarm, if you want to setup gfmd and slapd for Gfarm filesystem metadata server. Please see /usr/share/gfmd/doc/INSTALL.RPM.* for more details.' >&2 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT1-2-1-3_HW_error #! /bin/sh ###################################################################### TESTID="FT1-2-1-3" CATEGORY="accident causes no failover" SECTION="common observed properties" TITLE="HW error" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfsd1 logger -p local7.error -t "kernel" "/dev/sda I/O error" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "H/W error message in /var/log/messages on $gfsd1" || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_checkpoint 3 "sleep $ADDITIONAL_TIME sec." $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: H/W error message in /var/log/messages on $gfsd1" || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/lib/gfs_hook/sysdep/linux/sysdep.h /* Copyright (C) 1993, 1995-2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #define __alloca(size) __builtin_alloca (size) #define __set_errno(val) (errno = (val)) #define internal_function /* empty */ #if defined(__i386__) /* We need some help from the assembler to generate optimal code. We define some macros here which later will be used. */ asm (".L__X'%ebx = 1\n\t" ".L__X'%ecx = 2\n\t" ".L__X'%edx = 2\n\t" ".L__X'%eax = 3\n\t" ".L__X'%esi = 3\n\t" ".L__X'%edi = 3\n\t" ".L__X'%ebp = 3\n\t" ".L__X'%esp = 3\n\t" ".macro bpushl name reg\n\t" ".if 1 - \\name\n\t" ".if 2 - \\name\n\t" "pushl %ebx\n\t" ".else\n\t" "xchgl \\reg, %ebx\n\t" ".endif\n\t" ".endif\n\t" ".endm\n\t" ".macro bpopl name reg\n\t" ".if 1 - \\name\n\t" ".if 2 - \\name\n\t" "popl %ebx\n\t" ".else\n\t" "xchgl \\reg, %ebx\n\t" ".endif\n\t" ".endif\n\t" ".endm\n\t" ".macro bmovl name reg\n\t" ".if 1 - \\name\n\t" ".if 2 - \\name\n\t" "movl \\reg, %ebx\n\t" ".endif\n\t" ".endif\n\t" ".endm\n\t"); /* Define a macro which expands inline into the wrapper code for a system call. */ #undef INLINE_SYSCALL #define INLINE_SYSCALL(name, nr, args...) \ ({ \ unsigned int resultvar; \ asm volatile ( \ LOADARGS_##nr \ "movl %1, %%eax\n\t" \ "int $0x80\n\t" \ RESTOREARGS_##nr \ : "=a" (resultvar) \ : "i" (__NR_##name) ASMFMT_##nr(args) : "memory", "cc"); \ if (resultvar >= 0xfffff001) \ { \ __set_errno (-resultvar); \ resultvar = 0xffffffff; \ } \ (int) resultvar; }) #define LOADARGS_0 #define LOADARGS_1 \ "bpushl .L__X'%k2, %k2\n\t" \ "bmovl .L__X'%k2, %k2\n\t" #define LOADARGS_2 LOADARGS_1 #define LOADARGS_3 LOADARGS_1 #define LOADARGS_4 LOADARGS_1 #define LOADARGS_5 LOADARGS_1 #define RESTOREARGS_0 #define RESTOREARGS_1 \ "bpopl .L__X'%k2, %k2\n\t" #define RESTOREARGS_2 RESTOREARGS_1 #define RESTOREARGS_3 RESTOREARGS_1 #define RESTOREARGS_4 RESTOREARGS_1 #define RESTOREARGS_5 RESTOREARGS_1 #define ASMFMT_0() #define ASMFMT_1(arg1) \ , "acdSD" (arg1) #define ASMFMT_2(arg1, arg2) \ , "adCD" (arg1), "c" (arg2) #define ASMFMT_3(arg1, arg2, arg3) \ , "aCD" (arg1), "c" (arg2), "d" (arg3) #define ASMFMT_4(arg1, arg2, arg3, arg4) \ , "aD" (arg1), "c" (arg2), "d" (arg3), "S" (arg4) #define ASMFMT_5(arg1, arg2, arg3, arg4, arg5) \ , "a" (arg1), "c" (arg2), "d" (arg3), "S" (arg4), "D" (arg5) /* -- end of defined(__i386__) -- */ #elif defined(__x86_64__) /* Define a macro which expands inline into the wrapper code for a system call. */ #undef INLINE_SYSCALL #define INLINE_SYSCALL(name, nr, args...) \ ({ \ unsigned long resultvar; \ LOAD_ARGS_##nr (args) \ asm volatile ( \ "movq %1, %%rax\n\t" \ "syscall\n\t" \ : "=a" (resultvar) \ : "i" (__NR_##name) ASM_ARGS_##nr : "memory", "cc", "r11", "cx"); \ if (resultvar >= (unsigned long) -4095) \ { \ __set_errno (-resultvar); \ resultvar = (unsigned long) -1; \ } \ (long) resultvar; }) #define LOAD_ARGS_0() #define ASM_ARGS_0 #define LOAD_ARGS_1(a1) \ register long int _a1 asm ("rdi") = (long) (a1); \ LOAD_ARGS_0 () #define ASM_ARGS_1 ASM_ARGS_0, "r" (_a1) #define LOAD_ARGS_2(a1, a2) \ register long int _a2 asm ("rsi") = (long) (a2); \ LOAD_ARGS_1 (a1) #define ASM_ARGS_2 ASM_ARGS_1, "r" (_a2) #define LOAD_ARGS_3(a1, a2, a3) \ register long int _a3 asm ("rdx") = (long) (a3); \ LOAD_ARGS_2 (a1, a2) #define ASM_ARGS_3 ASM_ARGS_2, "r" (_a3) #define LOAD_ARGS_4(a1, a2, a3, a4) \ register long int _a4 asm ("r10") = (long) (a4); \ LOAD_ARGS_3 (a1, a2, a3) #define ASM_ARGS_4 ASM_ARGS_3, "r" (_a4) #define LOAD_ARGS_5(a1, a2, a3, a4, a5) \ register long int _a5 asm ("r8") = (long) (a5); \ LOAD_ARGS_4 (a1, a2, a3, a4) #define ASM_ARGS_5 ASM_ARGS_4, "r" (_a5) #define LOAD_ARGS_6(a1, a2, a3, a4, a5, a6) \ register long int _a6 asm ("r9") = (long) (a6); \ LOAD_ARGS_5 (a1, a2, a3, a4, a5) #define ASM_ARGS_6 ASM_ARGS_5, "r" (_a6) /* -- end of defined(__x86_64__) -- */ #else #error sysdep.h - unknown architecture #endif <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT1-2-1-3_HW_error #! /bin/sh ###################################################################### TESTID="FT1-2-1-3" CATEGORY="accident causes no failover" SECTION="common observed properties" TITLE="HW error" ###################################################################### . ./FT-common ft_setup() { zabbix_sender -v -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"kernel:\s.*I\/O\serror",UTF-8]' -o RECOVERED || RESULT=$FT_RESULT_FAIL return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfsd1 logger -p $FT_SYSLOG_FACILITY.error \ -t "kernel" "/dev/sda I/O error" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "H/W error message in /var/log/messages on $gfsd1" || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT zabbix_sender -v -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"kernel:\s.*I\/O\serror",UTF-8]' -o RECOVERED || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "clear log" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: H/W error message in /var/log/messages on $gfsd1" || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { zabbix_sender -v -z $zabbix1 -s $gfsd1 -k 'log[{$GFARM_LOGFILE},"kernel:\s.*I\/O\serror",UTF-8]' -o RECOVERED || RESULT=$FT_RESULT_FAIL return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/schedule.h /* * */ char *gfarm_schedule_search_idle_hosts(int, char **, int, char **); char *gfarm_schedule_search_idle_by_domainname(const char *, int, char **); char *gfarm_hosts_schedule_expand_cyclic(int, char ***, int, char **); <file_sep>/gfarm2fs/branches/1.1.0/configure.ac # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT([gfarm2fs], [0.9]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AM_MAINTAINER_MODE AC_CONFIG_SRCDIR([gfarm2fs.c]) AC_CONFIG_HEADER([config.h]) AC_CONFIG_FILES([Makefile]) AC_SYS_LARGEFILE # Checks for programs. AC_PROG_CC AC_PROG_LIBTOOL ### --with-gfarm=gfarm_ROOT AC_MSG_CHECKING([Gfarm file system package]) AC_ARG_WITH([gfarm], AC_HELP_STRING([--with-gfarm=PATH], [path to gfarm file system [[/usr]]]), [gfarm_prefix=$withval], [gfarm_prefix=no]) if test x"$gfarm_prefix" != xno; then AC_MSG_RESULT([$gfarm_prefix]) CPPFLAGS="$CPPFLAGS -I$gfarm_prefix/include" LDFLAGS="$LDFLAGS -R$gfarm_prefix/lib -L$gfarm_prefix/lib" else AC_MSG_RESULT([/usr]) fi # Checks for header files. AC_CHECK_HEADERS([gfarm/gfarm.h],, [AC_MSG_ERROR([gfarm/gfarm.h not found])]) # fuse.h requres _FILE_OFFSET_BITS is defined in any case, but # AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 # since it is not necessary. To avoid this problem we just skip the check. #AC_CHECK_HEADERS([fuse.h],, [AC_MSG_ERROR([fuse.h not found])]) # Checks for libraries. AC_CHECK_LIB([gfarm], [gfarm_initialize],, [AC_MSG_ERROR([libgfarm not found])]) AC_CHECK_LIB([fuse], [fuse_main],, [AC_MSG_ERROR([libfuse not found])]) # Checks for typedefs, structures, and compiler characteristics. # Checks for library functions. AC_OUTPUT <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc2/gfptool/gfcp/gfcp.c /* * $Id$ * * Copy a file */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gfarm/gfarm.h> char *program_name = "gfcp"; void usage() { fprintf(stderr, "Usage: %s [option] <input_file> <output_file>\n", program_name); exit(1); } #define BUFSIZE 65536 int main(int argc, char *argv[]) { int total_nodes = -1, node_index = -1; char *e, *input, *output; GFS_File igf, ogf; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; argc--; argv++; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_pio_get_node_size(&total_nodes); if (total_nodes <= 0) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing input file name\n", program_name); } exit(1); } input = argv[0]; argc--; argv++; if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing output file name\n", program_name); } exit(1); } output = argv[0]; argc--; argv++; if (argc != 0) { if (node_index == 0) { fprintf(stderr, "%s: currently, " "only one input file is supported\n", program_name); } exit(1); } if (strcmp(input, output) == 0) { fprintf(stderr, "%s: %s and %s are the same file\n", program_name, input, output); exit(1); } e = gfs_pio_create(output, GFARM_FILE_WRONLY, 0666, &ogf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_set_view_local(ogf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_open(input, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, input, e); exit(1); } e = gfs_pio_set_view_local(igf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, input, e); exit(1); } /* copy this fragment */ for (;;) { int rv, wv; char buffer[BUFSIZE]; e = gfs_pio_read(igf, buffer, sizeof(buffer), &rv); if (e != NULL || rv == 0) break; e = gfs_pio_write(ogf, buffer, rv, &wv); if (e != NULL) break; } if (e != NULL) fprintf(stderr, "%s\n", e); e = gfs_pio_close(igf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", input, e); e = gfs_pio_close(ogf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", output, e); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_0_1/lib/Makefile top_objdir = .. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = \ gfs_hook include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/include/gfarm/gfarm_misc.h /* * $Id$ */ #include <gfarm/gfarm_config.h> /* * basic types */ typedef unsigned char gfarm_uint8_t; typedef unsigned short gfarm_uint16_t; typedef unsigned int gfarm_uint32_t; typedef char gfarm_int8_t; typedef short gfarm_int16_t; typedef int gfarm_int32_t; /* * username handling */ /* the return value of the following functions should be free(3)ed */ char *gfarm_global_to_local_username(char *, char **); char *gfarm_local_to_global_username(char *, char **); /* * the return value of the following gfarm_get_*() funtions should not be * trusted (maybe forged) on client side, because any user can forge * the name by simply setting $USER. */ char *gfarm_set_global_username(char *); char *gfarm_get_global_username(void); char *gfarm_set_local_username(char *); char *gfarm_get_local_username(void); char *gfarm_set_local_homedir(char *); char *gfarm_get_local_homedir(void); char *gfarm_set_local_user_for_this_local_account(void); char *gfarm_set_global_user_for_this_local_account(void); /* * gfarm.conf */ /* the following functions are for client, */ /* server/daemon process shouldn't call follows: */ char *gfarm_initialize(int *, char ***); char *gfarm_terminate(void); char *gfarm_config_read(void); /* the following function is for server. */ char *gfarm_server_initialize(void); char *gfarm_server_terminate(void); char *gfarm_server_config_read(void); void gfarm_config_set_filename(char *); char *gfarm_strtoken(char **, char **); /* * GFarm URL and pathname handling */ char *gfarm_canonical_path(const char *, char **); char *gfarm_canonical_path_for_creation(const char *, char **); char *gfarm_url_make_path(const char *, char **); char *gfarm_url_make_path_for_creation(const char *, char **); int gfarm_is_url(const char *); char *gfarm_path_canonical_to_url(const char *, char **); #if 0 char *gfarm_url_make_localized_path(char *, char **); char *gfarm_url_make_localized_file_fragment_path(char *, int, char **); #endif char *gfarm_path_section(const char *, const char *, char **); char *gfarm_full_path_file_section(char *, char *, char *, char **); char *gfarm_path_localize(char *, char **); char *gfarm_path_localize_file_section(char *, char *, char **); char *gfarm_path_localize_file_fragment(char *, int, char **); const char *gfarm_url_prefix_skip(const char *); char *gfarm_url_prefix_add(const char *); const char *gfarm_path_dir_skip(const char *); extern char GFARM_URL_PREFIX[]; #define GFARM_URL_PREFIX_LENGTH 6 /* * Pool Host Scheduling * XXX - will be separated to <gfarm_schedule.h>? */ void gfarm_schedule_search_mode_use_loadavg(void); char *gfarm_schedule_search_idle_hosts(int, char **, int, char **); char *gfarm_schedule_search_idle_by_all(int, char **); char *gfarm_schedule_search_idle_by_domainname(const char *, int, char **); char *gfarm_schedule_search_idle_by_program(char *, int, char **); char *gfarm_url_hosts_schedule(const char *, char *, int *, char ***); char *gfarm_url_hosts_schedule_by_program(char *, char *, char *, int *, char ***); char *gfarm_file_section_host_schedule(char *, char *, char **); char *gfarm_file_section_host_schedule_by_program(char *, char *, char *, char **); char *gfarm_file_section_host_schedule_with_priority_to_local(char *, char *, char **); /* * MetaDB utility */ char *gfarm_url_fragment_cleanup(char *, int, char **); char *gfarm_url_fragment_number(const char *, int *); /* * helper functions for import */ char *gfarm_import_fragment_config_read(char *, int *, char ***, file_offset_t **, int *); file_offset_t *gfarm_import_fragment_size_alloc(file_offset_t, int); char *gfarm_hostlist_read(char *, int *, char ***, int *); /* * hostspec */ int gfarm_host_is_in_domain(const char *, const char *); /* * host */ struct gfarm_host_info; char *gfarm_host_info_get_by_if_hostname(const char *, struct gfarm_host_info *); char *gfarm_host_get_self_name(void); char *gfarm_host_get_canonical_name(const char *, char **); char *gfarm_host_get_canonical_names(int, char **, char ***); char *gfarm_host_get_canonical_self_name(char **); char *gfarm_host_get_self_architecture(char **); struct sockaddr; char *gfarm_host_address_get(const char *, int, struct sockaddr *, char **); /* * Miscellaneous */ #define GFARM_INT32STRLEN 11 /* max strlen(sprintf(s, "%d", int32)) */ #define GFARM_INT64STRLEN 22 /* max strlen(sprintf(s, "%lld", int64)) */ #define GFARM_ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0])) char *gfarm_fixedstrings_dup(int, char **, char **); void gfarm_strings_free_deeply(int, char **); int gfarm_strarray_length(char **); char **gfarm_strarray_dup(char **); void gfarm_strarray_free(char **); int gfarm_attach_debugger(void); <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc2/makes/prog.mk install: all prog-install post-install-hook clean: prog-clean post-clean-hook veryclean: prog-veryclean post-veryclean-hook distclean: prog-distclean post-distclean-hook gfregister: prog-gfregister post-gfregister-hook man: prog-man post-man-hook html: prog-html post-html-hook post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: $(PROGRAM): $(OBJS) $(DEPLIBS) $(CC) -o $(PROGRAM) $(CFLAGS) $(OBJS) $(LDLIBS) prog-install: $(INSTALL_PROGRAM) $(PROGRAM) $(bindir)/$(PROGRAM) prog-clean: -rm -f $(OBJS) $(EXTRA_CLEAN_TARGETS) prog-veryclean: clean -rm -f $(PROGRAM) $(EXTRA_VERYCLEAN_TARGETS) prog-distclean: veryclean if [ -f $(srcdir)/Makefile.in ]; then rm -f Makefile; fi prog-gfregister: prog-man: prog-html: <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT1-2-4-1_network_down_cn_to_master #! /bin/sh ###################################################################### TESTID="FT1-2-4-1" CATEGORY="accident causes no failover" SECTION="cn accident" TITLE="network down with cn to master" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 sudo $IFDOWN_PATH $client1_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Gfarm client node is not available on $client1" && \ ft_check_mail \ "Can't get master metadata server name on $client1" && \ ft_check_mail \ "Gfarm metadata server list is not available on $client1" && \ [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ssh $client1_CTRL_ADDRESS sudo $IFUP_PATH $client1_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "ifup $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Re: Gfarm client node is not available on $client1" && \ ft_check_mail \ "Re: Can't get master metadata server name on $client1" && \ ft_check_mail \ "Re: Gfarm metadata server list is not available on $client1" && \ [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { ssh $client1_CTRL_ADDRESS sudo $IFUP_PATH $client1_GFARM_IF return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/Makefile # $Id$ top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk # shared object version SHARELIB_LTFLAGS= LT_CURRENT=0 LT_REVISION=0 LT_AGE=0 LIBRARY = libgfarm.la LDFLAGS = $(LTFLAGS_SHARELIB_IN) $(libdir) $(SHARELIB_LTFLAGS) LDLIBS = $(metadb_client_libs) $(globus_gssapi_libs) $(openssl_libs) $(LIBS) GLOBUS_TARGETS = gfsl SUBDIRS = gfutil $(globus_targets) gfarm GLOBUS_OBJS = gfsl/libgfsl.la OBJS = gfutil/libgfutil.la $(globus_objs) gfarm/libgfarmcore.la all: subdir-all $(LIBRARY) $(OBJS): subdir-all include $(top_srcdir)/makes/subdir.mk include $(top_srcdir)/makes/lib.mk clean: $(RM) -f hook_test hook_test_mpi <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/gfutil/gfevent.h /* * This interface is a mimic of the libevent library by <NAME>. * * XXX - make this library a wrapper to libevent, if the system has it. */ struct timeval; /* event */ struct gfarm_event; #define GFARM_EVENT_TIMEOUT 1 #define GFARM_EVENT_READ 2 #define GFARM_EVENT_WRITE 4 #define GFARM_EVENT_EXCEPTION 8 struct gfarm_event *gfarm_fd_event_alloc(int, int, void (*)(int, int, void *, const struct timeval *), void *); void gfarm_fd_event_set_callback(struct gfarm_event *, void (*)(int, int, void *, const struct timeval *), void *); /* * NOTE: * timer_event shouldn't be used for timeout handling of * read/write/exception processing, because it's possible that both a * timer_event handler and a read/write/exception handler are called * at once. In other words, if timer_event is used for such timeout * handling, timer_event handler may be called even if timeout doesn't * actually happen. * If fd_event is used with GFARM_EVENT_TIMEOUT, it's guaranteed that * the TIMEOUT event and READ/WRITE/EXCEPTION event never happen at once. */ struct gfarm_event *gfarm_timer_event_alloc( void (*)(void *, const struct timeval *), void *); void gfarm_timer_event_set_callback(struct gfarm_event *, void (*)(void *, const struct timeval *), void *); void gfarm_event_free(struct gfarm_event *); /* event queue */ struct gfarm_eventqueue; struct gfarm_eventqueue *gfarm_eventqueue_alloc(void); void gfarm_eventqueue_free(struct gfarm_eventqueue *); int gfarm_eventqueue_add_event(struct gfarm_eventqueue *, struct gfarm_event *, const struct timeval *); int gfarm_eventqueue_delete_event(struct gfarm_eventqueue *, struct gfarm_event *); int gfarm_eventqueue_turn(struct gfarm_eventqueue *, const struct timeval *); int gfarm_eventqueue_loop(struct gfarm_eventqueue *, const struct timeval *); <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/gfarm_secure_session.h #ifndef _GFARM_SECURE_SESSION_H_ #define _GFARM_SECURE_SESSION_H_ #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_auth.h" /* * Session information struct */ typedef struct gfarmSecSession { /* * Generic TCP transport information. */ int fd; /* File descriptor for the session. */ int needClose; /* Need to close above fd or not when terminate this session. */ unsigned long int rAddr; /* IP address of a peer. */ int rPort; /* Port # of the peer. */ char *peerName; /* FQDN of the peer. Heap alloc'd. */ /* * Credential information. */ gss_cred_id_t cred; /* The credential used for the session. */ char *credName; /* Name of the credential. Heap alloc'd. */ gss_ctx_id_t sCtx; /* A secure context for the session. */ /* * Role specific information. */ int iOa; /* An initiator or an acceptor. */ #define GFARM_SS_INITIATOR 1 #define GFARM_SS_ACCEPTOR 2 union { /* * Initiator side session infomation. */ struct initiatorSessionInfo { OM_uint32 reqFlag; /* Security context initiation flag. */ char *acceptorDistName; /* Acceptor's DN. Heap alloc'd. */ } initiator; /* * Acceptor side session information. */ struct acceptorSessionInfo { gfarmAuthEntry *mappedUser; /* Authenticated user information. */ char *exportedName; /* initiator GSS_C_NT_EXPORT_NAME */ gss_cred_id_t deleCred; /* A credential delegated from the initiator. */ } acceptor; } iOaInfo; /* * Session configuration information. */ gss_qop_t qOp; /* Quality Of Protection * for GSSAPI layer. */ unsigned int maxTransSize; /* Maximum transmission size of the session in bytes. */ unsigned int config; /* Or'd value of belows. */ #define GFARM_SS_USE_ENCRYPTION 0x1 #define GFARM_SS_USE_COMPRESSION 0x2 #define GFARM_SS_USE_SYSTEMCONF 0x80000000 /* * Poll status. */ int pollEvent; /* Or'd value of belows. */ #define GFARM_SS_POLL_NONE 0x0 #define GFARM_SS_POLL_READABLE 0x1 #define GFARM_SS_POLL_WRITABLE 0x2 #define GFARM_SS_POLL_ERROR 0x4 /* * Session status. */ OM_uint32 gssLastStat; /* The last status of GSSAPI invocation. */ } gfarmSecSession; #define isBitSet(A, B) (((A) & (B)) == (B)) /* * GSSAPI and other transmission configuration information struct. */ typedef struct { unsigned int optMask; /* Mask of which options are specified. Or'd belows: */ #define GFARM_SS_OPT_QOP_MASK 0x1 #define GFARM_SS_OPT_MAXT_MASK 0x2 #define GFARM_SS_OPT_CONF_MASK 0x4 #define GFARM_SS_OPT_ALL_MASK 0x7 gss_qop_t qOpReq; /* Requested QOP. */ int qOpForce; /* If 1 use the requested QOP forcible otherwise negothiate with peer and falldown to acceptable level. */ unsigned int maxTransSizeReq; /* Requested maximum transmission size. */ int maxTransSizeForce; /* Force use above or not. */ unsigned int configReq; /* Any other configuration. */ int configForce; /* Force use above or not. */ } gfarmSecSessionOption; #define GFARM_SS_DEFAULT_OPTION \ { \ GFARM_SS_OPT_ALL_MASK, \ GFARM_GSS_DEFAULT_QOP, \ 0, \ GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE, \ 0, \ GFARM_SS_USE_ENCRYPTION, \ 0 \ } /* Authorization ACK/NACK */ #define GFARM_SS_AUTH_ACK 1 #define GFARM_SS_AUTH_NACK 0 /* Prototypes */ extern char ** gfarmSecSessionCrackStatus(gfarmSecSession *ssPtr); extern void gfarmSecSessionFreeCrackedStatus(char **strPtr); extern void gfarmSecSessionPrintStatus(gfarmSecSession *ssPtr); extern int gfarmSecSessionInitializeAcceptor(char *configFile, char *usermapFile, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern int gfarmSecSessionInitializeInitiator(char *configFile, char *usermapFile, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern int gfarmSecSessionInitializeBoth(char *iConfigFile, char *aConfigFile, char *usermapFile, OM_uint32 *majstatPtr, OM_uint32 *minstatPtr); extern void gfarmSecSessionFinalizeAcceptor(void); extern void gfarmSecSessionFinalizeInitiator(void); extern void gfarmSecSessionFinalizeBoth(void); extern char * gfarmSecSessionGetInitiatorCredName(void); extern gfarmSecSession * gfarmSecSessionAccept(int fd, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern gfarmSecSession * gfarmSecSessionInitiate(int fd, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern gfarmSecSession * gfarmSecSessionInitiateByAddr(unsigned long rAddr, int port, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern gfarmSecSession * gfarmSecSessionInitiateByName(char *hostname, int port, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern void gfarmSecSessionTerminate(gfarmSecSession *ssPtr); extern gss_cred_id_t gfarmSecSessionGetDelegatedCredential(gfarmSecSession *ssPtr); extern char * gfarmSecSessionGetInitiatorExportedName(gfarmSecSession *ssPtr); extern gfarmAuthEntry * gfarmSecSessionGetInitiatorInfo(gfarmSecSession *ssPtr); extern int gfarmSecSessionDedicate(gfarmSecSession *ssPtr); extern int gfarmSecSessionSendInt32(gfarmSecSession *ssPtr, gfarm_int32_t *buf, int n); extern int gfarmSecSessionReceiveInt32(gfarmSecSession *ssPtr, gfarm_int32_t **bufPtr, int *lenPtr); extern int gfarmSecSessionSendInt16(gfarmSecSession *ssPtr, gfarm_int16_t *buf, int n); extern int gfarmSecSessionReceiveInt16(gfarmSecSession *ssPtr, gfarm_int16_t **bufPtr, int *lenPtr); extern int gfarmSecSessionSendInt8(gfarmSecSession *ssPtr, gfarm_int8_t *buf, int n); extern int gfarmSecSessionReceiveInt8(gfarmSecSession *ssPtr, gfarm_int8_t **bufPtr, int *lenPtr); extern int gfarmSecSessionPoll(gfarmSecSession *ssList[], int n, struct timeval *toPtr); /* * gfarmSecSessionPoll() convinience macro(s). */ #define gfarmSecSessionCheckPollReadable(s) (isBitSet(s->pollEvent, GFARM_SS_POLL_READABLE)) #define gfarmSecSessionCheckPollWritable(s) (isBitSet(s->pollEvent, GFARM_SS_POLL_WRITABLE)) #define gfarmSecSessionCheckPollError(s) (isBitSet(s->pollEvent, GFARM_SS_POLL_WRITABLE)) #define gfarmSecSessionSetPollEvent(s, e) { s->pollEvent = (e); } #define gfarmSecSessionClearPollEvent(s) gfarmSecSessionSetPollEvent(s, GFARM_SS_POLL_NONE) #define gfarmSecSessionAddPollEvent(s, m) { s->pollEvent |= (m); } #define gfarmSecSessionDeletePollEvent(s, d) { s->pollEvent &= ~(d); } /* * multiplexed version */ struct gfarm_eventqueue; struct gfarmSecSessionInitiateState; extern struct gfarmSecSessionInitiateState *gfarmSecSessionInitiateRequest( struct gfarm_eventqueue *q, int fd, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, void (*continuation)(void *), void *closure, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern gfarmSecSession *gfarmSecSessionInitiateResult(struct gfarmSecSessionInitiateState *state, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); #endif /* _GFARM_SECURE_SESSION_H_ */ <file_sep>/gfarmfs-fuse/trunk/test/Makefile.am noinst_PROGRAMS = fsystest fsystest_SOURCE = fsystest.c noinst_SCRIPTS = test.sh func.sh EXTRA_DIST = $(noinst_SCRIPTS) README KNOWN_ERRORS SUBDIRS = expected clean-local: -rm -rf output diffs top-all: $(MAKE) -C $(top_builddir) all check-all: top-all sh ./test.sh all check-gfarmfs: top-all sh ./test.sh gfarmfs check-fusexmp: top-all sh ./test.sh fusexmp check: check-gfarmfs <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT2-2-2-3_master_gfmd_down_and_master_candidate_MDS_network_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-3" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd down and master candidate MDS network down" ###################################################################### . ./FT-common ft_setup() { IFDOWN=/sbin/ifdown IFUP=/sbin/ifup return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfmd2_CTRL_ADDRESS sudo $IFDOWN $gfmd2_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfmd2_GFARM_IF on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop master gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd2_CTRL_ADDRESS sudo $IFUP $gfmd2_GFARM_IF ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_1/contrib/mount.gfarm2fs/mount.hpci #!/bin/sh # # mount.hpci - mount HPCI shared storage # # this command assumes to be executed by a normal user not root ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } create_link() { LINK=$1 G=$2 U=$3 [ -h $LINK ] || (gfln -s gfarm:///$LINK/$G/$U $LINK && echo create \'$LINK\' symlink) } # check proxy cert grid-proxy-info > /dev/null || ABORT "Invalid proxy certificate" # copy proxy cert to default location and unset X509_USER_PROXY : ${UID:=`id -u`} if [ X"$X509_USER_PROXY" != X -a -f "$X509_USER_PROXY" -a "$X509_USER_PROXY" != /tmp/x509up_u$UID ]; then cmp $X509_USER_PROXY /tmp/x509up_u$UID > /dev/null 2>&1 || { cp -p $X509_USER_PROXY /tmp/x509up_u$UID && unset X509_USER_PROXY && echo Update proxy certificate for gfarm2fs } fi # display timeleft of proxy cert (grid-proxy-info || ABORT "Invalid proxy certificate") | grep timeleft GFUSER=`gfwhoami` [ X"$GFUSER" = X ] && ABORT 'Who?' : ${USER:=`whoami`} USERLIST="$GFUSER" [ X"$GFUSER" != X"$USER" ] && USERLIST="$USERLIST $USER" : ${GFARM_CONFIG_FILE:=`gfstatus 2>/dev/null | grep "user config file" | sed 's/user config file : //'`} : ${GFARM_CONFIG_FILE:="$HOME/.gfarm2rc"} groups=`gfgroup -l | grep $GFUSER | awk -F: '{print $1}'` for g in $groups do for u in $USERLIST do [ -d /gfarm/$g/$u ] && { env GFARMFS_ROOT=/home/$g/$GFUSER mount.gfarm2fs "$GFARM_CONFIG_FILE" /gfarm/$g/$u # create symlinks test $? -eq 0 && (cd /gfarm/$g/$u && { create_link www $g $GFUSER create_link samba $g $GFUSER }) } done done <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_3_0/contrib/mount.gfarmfs/umount.gfarmfs #!/bin/sh # # umount.gfarmfs [ mount_point ] # # Environment variable: # # GFS_USERNAME global user name in Gfarm (default: $LOGNAME) # GFS_MOUNTDIR mount point (default: /gfs/home/$GFS_USERNAME) if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi : ${GFS_USERNAME:=$LOGNAME} : ${GFS_MOUNTDIR:=/gfs/home/$GFS_USERNAME} fusermount -u $GFS_MOUNTDIR <file_sep>/gfarm_gridftp_dsi/tags/gfarm_dsi_1_0_0/configure.ac # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT([gfarm_gridftp_dsi], [1.0.0]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AC_CONFIG_SRCDIR([globus_gridftp_server_gfarm.c]) AC_CONFIG_HEADER([config.h]) # Checks for programs. AC_PROG_AWK AC_PROG_CC AC_PROG_CPP AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_MAKE_SET AC_PROG_LIBTOOL ### --with-gfarm=GFARM AC_MSG_CHECKING([for Gfarm file system]) AC_ARG_WITH([gfarm], AC_HELP_STRING([--with-gfarm=PATH], [path to gfarm file system [[/usr]]])) case x$with_gfarm in x|xyes|xno) GFARM=/usr ;; *) GFARM=$with_gfarm ;; esac if test x"$GFARM" != x/usr; then CPPFLAGS="$CPPFLAGS -I$GFARM/include" LDFLAGS="$LDFLAGS -R$GFARM/lib -L$GFARM/lib" fi AC_MSG_RESULT([$GFARM]) ### --with-globus-flavor=FLAVOR AC_ARG_WITH(globus_flavor, [ --with-globus-flavor=FLAVOR globus flavor name [[default=guessed]]], [FLAVOR="${withval}" ], [FLAVOR= ]) ### --with-globus=GLOBUS_LOCATION AC_MSG_CHECKING([for Globus toolkit]) AC_ARG_WITH([globus], AC_HELP_STRING([--with-globus=PATH], [path to Globus toolkit [[$GLOBUS_LOCATION]]])) case x$with_globus in x|xyes|xno) GLOBUS_LOCATION=$GLOBUS_LOCATION ;; *) GLOBUS_LOCATION=$with_globus ;; esac if test x"$GLOBUS_LOCATION" = x; then AC_MSG_RESULT([no]) AC_MSG_ERROR([Specify GLOBUS_LOCATION using --with-globus option]) fi AC_MSG_RESULT([$GLOBUS_LOCATION]) # guess FLAVOR AC_MSG_CHECKING([for Globus flavor]) if test x"$FLAVOR" = x; then FTPSERVER=$GLOBUS_LOCATION/sbin/globus-gridftp-server FLAVOR=`ldd $FTPSERVER | $AWK '($1 ~ /^libglobus_gridftp_server_control_/){name=gensub(/^libglobus_gridftp_server_control_(.+)\.so.*/,"\\\\1","g",$1);print name}'` fi if test x"$FLAVOR" = x; then AC_MSG_RESULT([no]) AC_MSG_ERROR([Specify Globus flavor using --with-globus-flavor option]) fi AC_MSG_RESULT([$FLAVOR]) AC_SUBST(FLAVOR) if test x"$GLOBUS_LOCATION" != x/usr; then CPPFLAGS="$CPPFLAGS -I$GLOBUS_LOCATION/include/$FLAVOR" LDFLAGS="$LDFLAGS -R$GLOBUS_LOCATION/lib -L$GLOBUS_LOCATION/lib" fi # make sure nonthreaded gridftp server is installed AC_MSG_CHECKING([whether nonthreaded GridFTP server is installed]) f_prefix=`expr "$FLAVOR" : '\(.*\)pthr'` f_pthr=`expr "$FLAVOR" : '.*\(pthr\)'` if test x"$f_pthr" = xpthr; then AC_MSG_RESULT([no]) AC_MSG_ERROR([Copy $GLOBUS_LOCATION/sbin/$f_prefix/shared/globus-gridftp-server to $GLOBUS_LOCATION/sbin/globus-gridftp-server]) fi AC_MSG_RESULT([yes]) # Checks for libraries. AC_CHECK_LIB([gfarm], [gfarm_initialize],, [AC_MSG_ERROR([libgfarm not found. Use --with-gfarm option])]) # Checks for header files. AC_CHECK_HEADERS([gfarm/gfarm.h],, [AC_MSG_ERROR([gfarm/gfarm.h not found])]) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_MODE_T AC_TYPE_UID_T # Checks for library functions. AC_HEADER_STDC AC_CHECK_FUNCS([memset strdup]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT <file_sep>/gfarm_mpiio/trunk/ad_gfarm/ad_gfarm_close.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" void ADIOI_GFARM_Close(ADIO_File fd, int *error_code) { int myrank, nprocs; int i, n; ADIOI_GFARM_headerInf *ghi; ADIOI_GFARM_collective_info *gci; gfarm_error_t gerr; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); fd->fd_sys = -1; *error_code = MPI_SUCCESS; #ifdef GFARM_DEBUG FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_Close called on %s\n", myrank, nprocs, fd->filename); #endif ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); if(ghi->gfarm_view_flag == 1){ for(i=0;i<ghi->gfp_num;i++){ gfs_pio_close(ghi->gfp[i]); } gfs_pio_close(ghi->header_gfp); #ifdef GFARM_DEBUG_TIME ad_gfarm_print_detailaccesstime(fd); #endif #ifdef GFARM_DEBUG_DATA_SIZE ad_gfarm_print_detaildatasize(fd); #endif free(ghi->count); free(ghi->filetype_size); free(ghi->filetype_extent); for(i=0;i<ghi->nprocs;i++){ free(ghi->blocklens[i]); free(ghi->indices[i]); } free(ghi->blocklens); free(ghi->indices); //free(ghi->gfp_flag); if(ghi->gfp_num > 0) free(ghi->gfp); free(ghi); }else if(ghi->header_flag == 1){ gfs_pio_close(ghi->header_gfp); } gerr = gfarm_terminate(); if(gerr != GFARM_ERR_NO_ERROR){ printf("[%d/%d] gfarm_initialize. gerr = %d\n", myrank, nprocs, gerr); } #ifdef GFARM_DEBUG FPRINTF(stdout, "[%d/%d] end ADIOI_GFARM_Close called on %s\n", myrank, nprocs, fd->filename); #endif } void ad_gfarm_print_detailaccesstime(ADIO_File fd) { int i, myrank, nprocs; double *trance_time_arr, *access_time_arr, *all_time_arr; double trance_time; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf*)fd->fs_ptr; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); trance_time_arr = malloc(sizeof(double)*nprocs); access_time_arr = malloc(sizeof(double)*nprocs); all_time_arr = malloc(sizeof(double)*nprocs); trance_time = ghi->all_time - ghi->access_time; MPI_Gather(&trance_time, 1, MPI_DOUBLE, trance_time_arr, 1, MPI_DOUBLE, 0, fd->comm); MPI_Gather(&(ghi->access_time), 1, MPI_DOUBLE, access_time_arr, 1, MPI_DOUBLE, 0, fd->comm); MPI_Gather(&(ghi->all_time), 1, MPI_DOUBLE, all_time_arr, 1, MPI_DOUBLE, 0, fd->comm); if(myrank == 0){ FILE *fp; fp = fopen("result/time_gfarm", "a+"); fprintf(fp, "%d\n", nprocs); for(i=0;i<nprocs;i++){ fprintf(fp, "%f\t", all_time_arr[i]); fprintf(fp, "%f\t", access_time_arr[i]); fprintf(fp, "%f\t", trance_time_arr[i]); fprintf(fp, "%f\t", (trance_time_arr[i]/all_time_arr[i])*100); fprintf(fp, "\n"); } fprintf(fp, "\n"); fclose(fp); } free(trance_time_arr); free(access_time_arr); free(all_time_arr); } void ad_gfarm_print_detaildatasize(ADIO_File fd) { int i, n, myrank, nprocs; unsigned long *data_size_arr; unsigned long data_size_sum; double data_size_rate, *data_size_rate_arr; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf*)fd->fs_ptr; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); data_size_arr = malloc(sizeof(unsigned long)*ghi->nprocs*nprocs); data_size_rate_arr = malloc(sizeof(double)*nprocs); MPI_Gather(ghi->data_size, ghi->nprocs, MPI_UNSIGNED_LONG, data_size_arr, ghi->nprocs, MPI_UNSIGNED_LONG, 0, fd->comm); data_size_sum = 0; for(i=0;i<ghi->nprocs;i++){ data_size_sum += ghi->data_size[i]; } if(data_size_sum!=0){ data_size_rate = ((double)ghi->data_size[myrank])/((double)data_size_sum); }else{ data_size_rate = 0; } MPI_Gather(&data_size_rate, 1, MPI_DOUBLE, data_size_rate_arr, 1, MPI_DOUBLE, 0, fd->comm); if(myrank == 0){ FILE *fp; fp = fopen("result/data_size_gfarm", "a+"); fprintf(fp, "%d\n", nprocs); for(n=0;n<nprocs;n++){ fprintf(fp, "%d\t", n); for(i=0;i<ghi->nprocs;i++){ fprintf(fp, "%d\t", data_size_arr[ghi->nprocs*n+i]); } fprintf(fp, "\n"); } fprintf(fp, "\n"); fclose(fp); fp = fopen("result/data_rate_gfarm", "a+"); fprintf(fp, "%d\n", nprocs); for(n=0;n<nprocs;n++){ fprintf(fp, "%d\t", n); fprintf(fp, "%f\t", data_size_rate_arr[n]); fprintf(fp, "\n"); } fprintf(fp, "\n"); fclose(fp); } } <file_sep>/gfarm/tags/gfarm_1_0_beta_3_rev_2/lib/libgfarm/gfarm/gfs_pio_local.c /* * pio operations for local section * * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "gfs_proto.h" /* for gfs_digest_calculate_local() */ #include "gfs_pio.h" int gfarm_node = -1; int gfarm_nnode = -1; char * gfs_pio_set_local(int node, int nnode) { if (node < 0 || node >= nnode || nnode < 0) return (GFARM_ERR_INVALID_ARGUMENT); gfarm_node = node; gfarm_nnode = nnode; return (NULL); } char * gfs_pio_set_local_check(void) { if (gfarm_node < 0 || gfarm_nnode <= 0) return ("gfs_pio_set_local() is not correctly called"); return (NULL); } char * gfs_pio_get_node_rank(int *node) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); *node = gfarm_node; return (NULL); } char * gfs_pio_get_node_size(int *nnode) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); *nnode = gfarm_nnode; return (NULL); } char * gfs_pio_set_view_local(GFS_File gf, int flags) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); return (gfs_pio_set_view_index(gf, gfarm_nnode, gfarm_node, NULL, flags)); } /***********************************************************************/ static char * gfs_pio_local_storage_close(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; if (close(vc->fd) == -1) return (gfarm_errno_to_error(errno)); return (NULL); } static char * gfs_pio_local_storage_write(GFS_File gf, const char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; int rv = write(vc->fd, buffer, size); if (rv == -1) return (gfarm_errno_to_error(errno)); *lengthp = rv; return (NULL); } static char * gfs_pio_local_storage_read(GFS_File gf, char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; int rv = read(vc->fd, buffer, size); if (rv == -1) return (gfarm_errno_to_error(errno)); *lengthp = rv; return (NULL); } static char * gfs_pio_local_storage_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { struct gfs_file_section_context *vc = gf->view_context; off_t rv = lseek(vc->fd, (off_t)offset, whence); if (rv == -1) return (gfarm_errno_to_error(errno)); if (resultp != NULL) *resultp = rv; return (NULL); } static char * gfs_pio_local_storage_calculate_digest(GFS_File gf, char *digest_type, size_t digest_size, size_t *digest_lengthp, unsigned char *digest, file_offset_t *filesizep) { struct gfs_file_section_context *vc = gf->view_context; const EVP_MD *md_type; int rv; static int openssl_initialized = 0; if (!openssl_initialized) { SSLeay_add_all_algorithms(); /* for EVP_get_digestbyname() */ openssl_initialized = 1; } if ((md_type = EVP_get_digestbyname(digest_type)) == NULL) return (GFARM_ERR_INVALID_ARGUMENT); /* note that this effectively breaks file offset. */ rv = gfs_digest_calculate_local( vc->fd, gf->buffer, GFS_FILE_BUFSIZE, md_type, &vc->md_ctx, digest_lengthp, digest, filesizep); if (rv != 0) return (gfarm_errno_to_error(rv)); return (NULL); } static int gfs_pio_local_storage_fd(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; return (vc->fd); } struct gfs_storage_ops gfs_pio_local_storage_ops = { gfs_pio_local_storage_close, gfs_pio_local_storage_write, gfs_pio_local_storage_read, gfs_pio_local_storage_seek, gfs_pio_local_storage_calculate_digest, gfs_pio_local_storage_fd, }; char * gfs_pio_open_local_section(GFS_File gf, int flags) { struct gfs_file_section_context *vc = gf->view_context; char *e, *local_path; int fd, open_flags = gfs_open_flags_localize(gf->open_flags); if (open_flags == -1) return (GFARM_ERR_INVALID_ARGUMENT); e = gfarm_path_localize_file_section(gf->pi.pathname, vc->section, &local_path); if (e != NULL) return (e); fd = open(local_path, open_flags, gf->pi.status.st_mode & GFARM_S_ALLPERM); free(local_path); if (fd == -1) return (gfarm_errno_to_error(errno)); vc->ops = &gfs_pio_local_storage_ops; vc->storage_context = NULL; /* not needed */ vc->fd = fd; return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/debian/gfmd.postinst #!/bin/sh -e if [ -e /etc/init.d/gfmd ]; then update-rc.d gfmd defaults >/dev/null # /etc/init.d/gfmd restart fi <file_sep>/gfarm/tags/gfarm_0_1/man/ja/Makefile.inc mandir = $(default_mandir)/ja <file_sep>/gfarm2fs/tags/gfarm2fs_1_1_1/Makefile.am bin_PROGRAMS = gfarm2fs gfarm2fs_SOURCES = gfarm2fs.c AM_CFLAGS = -Wall EXTRA_DIST = RELNOTES LICENSE gfarm2fs.spec <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT2-2-1-2_master_gfmd_down_with_master_candidate_network_down #! /bin/sh ###################################################################### TESTID="FT2-2-1-2" CATEGORY="2 point accident" SECTION="internal accident and network down" TITLE="master gfmd down with master candidate network down" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS gfmdhost -l > /dev/null 2>&1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "gfmdhost -l" $RESULT ssh $gfmd2_CTRL_ADDRESS sudo $IFDOWN_PATH $gfmd2_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "ifdown $gfmd2_GFARM_IF on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_wait_failover $gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "gfmd failed over" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5.1 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5.2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd2_CTRL_ADDRESS sudo $IFUP_PATH $gfmd2_GFARM_IF \ ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/gfs_client_udp.c /* * $Id$ */ #include <assert.h> #include <sys/types.h> /* fd_set */ #include <sys/time.h> #include <sys/socket.h> #include <arpa/inet.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <errno.h> #include <gfarm/gfarm.h> #ifdef HAVE_POLL #include <poll.h> #endif #include <unistd.h> #include "gfs_client.h" /* * concurrent processing of * gfs_client_get_load_request()/gfs_client_get_load_result() */ #define MILLISEC_BY_MICROSEC 1000 #define SECOND_BY_MICROSEC 1000000 static int timeval_cmp(struct timeval *t1, struct timeval *t2) { if (t1->tv_sec > t2->tv_sec) return (1); if (t1->tv_sec < t2->tv_sec) return (-1); if (t1->tv_usec > t2->tv_usec) return (1); if (t1->tv_usec < t2->tv_usec) return (-1); return (0); } static void timeval_add_microsec(struct timeval *t, long microsec) { int n; t->tv_usec += microsec; if (t->tv_usec >= SECOND_BY_MICROSEC) { n = t->tv_usec / SECOND_BY_MICROSEC; t->tv_usec -= n * SECOND_BY_MICROSEC; t->tv_sec += n; } } static void timeval_sub(struct timeval *t1, struct timeval *t2) { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; if (t1->tv_usec < 0) { --t1->tv_sec; t1->tv_usec += SECOND_BY_MICROSEC; } } struct gfs_client_udp_requests { char *requests_save_error; int nrequests, requests_free; struct { int sock; void *closure; void (*callback)(void *, struct sockaddr *, struct gfs_client_load *, char *); struct sockaddr addr; int try; struct timeval timeout; } *requests ; #ifdef HAVE_POLL struct pollfd *requests_poll_fds; /* only used on HAVE_POLL case */ #endif }; char * gfarm_client_init_load_requests(int max_requests, struct gfs_client_udp_requests **udp_requestsp) { struct gfs_client_udp_requests *p; int i; p = malloc(sizeof(**udp_requestsp)); if (p == NULL) return (GFARM_ERR_NO_MEMORY); p->requests = malloc(sizeof(*p->requests) * max_requests); if (p->requests == NULL) { free(p); return (GFARM_ERR_NO_MEMORY); } #ifdef HAVE_POLL p->requests_poll_fds = malloc(sizeof(*p->requests_poll_fds) * max_requests); if (p->requests_poll_fds == NULL) { free(p->requests); free(p); return (GFARM_ERR_NO_MEMORY); } #endif for (i = 0; i < max_requests; i++) p->requests[i].sock = -1; p->nrequests = p->requests_free = max_requests; p->requests_save_error = NULL; *udp_requestsp = p; return (NULL); } static void request_callback(int i, struct gfs_client_load *result, char *e, struct gfs_client_udp_requests *p) { if (p->requests_save_error == NULL) p->requests_save_error = e; (*p->requests[i].callback)(p->requests[i].closure, &p->requests[i].addr, result, e); close(p->requests[i].sock); p->requests[i].sock = -1; p->requests_free++; } static char * request_time_tick(struct gfs_client_udp_requests *p) { char *e; int i, rv; struct timeval now, timeout; struct gfs_client_load result; #ifdef HAVE_POLL int to, nfds = 0; #else int max_fd = -1; fd_set readable; FD_ZERO(&readable); #endif timeout.tv_sec = LONG_MAX; timeout.tv_usec = SECOND_BY_MICROSEC - 1; for (i = 0; i < p->nrequests; i++) { if (p->requests[i].sock == -1) continue; if (timeval_cmp(&timeout, &p->requests[i].timeout) > 0) timeout = p->requests[i].timeout; #ifdef HAVE_POLL p->requests_poll_fds[nfds].fd = p->requests[i].sock; p->requests_poll_fds[nfds].events = POLLIN; nfds++; #else if (max_fd < p->requests[i].sock) { max_fd = p->requests[i].sock; if (max_fd >= FD_SETSIZE) return ("gfs_client_udp.c:request_time_tick()" ": FD_SETSIZE is too small"); } FD_SET(p->requests[i].sock, &readable); #endif } gettimeofday(&now, NULL); if (timeval_cmp(&timeout, &now) <= 0) { #ifdef HAVE_POLL to = 0; #else timeout.tv_sec = timeout.tv_usec = 0; #endif } else { timeval_sub(&timeout, &now); #ifdef HAVE_POLL to = timeout.tv_sec * 1000 + timeout.tv_usec / 1000; #endif } #ifdef HAVE_POLL rv = poll(p->requests_poll_fds, nfds, to); #else rv = select(max_fd + 1, &readable, NULL, NULL, &timeout); #endif if (rv == -1) return (gfarm_errno_to_error(errno)); gettimeofday(&now, NULL); #ifdef HAVE_POLL nfds = 0; #endif for (i = 0; i < p->nrequests; i++) { if (p->requests[i].sock == -1) continue; #ifdef HAVE_POLL /* revents shows not only POLLIN, but also POLLERR. */ if (p->requests_poll_fds[nfds++].revents != 0) #else if (FD_ISSET(p->requests[i].sock, &readable)) #endif { e = gfs_client_get_load_result( p->requests[i].sock, NULL, NULL, &result); if (e != NULL) { request_callback(i, NULL, e, p); continue; } request_callback(i, &result, NULL, p); continue; } if (timeval_cmp(&p->requests[i].timeout, &now) > 0) continue; ++p->requests[i].try; if (p->requests[i].try >= gfs_client_datagram_ntimeouts) { request_callback(i, NULL, GFARM_ERR_CONNECTION_TIMED_OUT, p); continue; } timeval_add_microsec(&p->requests[i].timeout, gfs_client_datagram_timeouts[p->requests[i].try] * MILLISEC_BY_MICROSEC); e = gfs_client_get_load_request(p->requests[i].sock, NULL, 0); if (e != NULL) { request_callback(i, NULL, e, p); continue; } } return NULL; } static void wait_request_reply(struct gfs_client_udp_requests *p) { int initial = p->requests_free; if (p->requests_free >= p->nrequests) return; while (p->requests_free <= initial) request_time_tick(p); } char * gfarm_client_wait_all_load_results(struct gfs_client_udp_requests *p) { char *e; while (p->requests_free < p->nrequests) wait_request_reply(p); #ifdef HAVE_POLL free(p->requests_poll_fds); #endif free(p->requests); e = p->requests_save_error; free(p); return (e); } static int free_request(struct gfs_client_udp_requests *p) { int i; if (p->requests_free <= 0) wait_request_reply(p); for (i = 0; i < p->nrequests; i++) if (p->requests[i].sock == -1) return (i); assert(0); /*NOTREACHED*/ return (-1); } char * gfarm_client_add_load_request(struct gfs_client_udp_requests *udp_requests, struct sockaddr *peer_addr, void *closure, void (*callback)(void *, struct sockaddr *, struct gfs_client_load *, char *)) { int i = free_request(udp_requests); /* use different socket each time, to identify error code */ int sock = socket(PF_INET, SOCK_DGRAM, 0); char *e; if (sock == -1) { e = gfarm_errno_to_error(errno); (*callback)(closure, peer_addr, NULL, e); if (udp_requests->requests_save_error == NULL) udp_requests->requests_save_error = e; return e; } fcntl(sock, F_SETFD, 1); /* automatically close() on exec(2) */ /* connect UDP socket, to get error code */ if (connect(sock, peer_addr, sizeof(*peer_addr)) == -1) { e = gfarm_errno_to_error(errno); close(sock); (*callback)(closure, peer_addr, NULL, e); if (udp_requests->requests_save_error == NULL) udp_requests->requests_save_error = e; return e; } e = gfs_client_get_load_request(sock, NULL, 0); if (e != NULL) { close(sock); (*callback)(closure, peer_addr, NULL, e); if (udp_requests->requests_save_error == NULL) udp_requests->requests_save_error = e; return e; } udp_requests->requests[i].sock = sock; udp_requests->requests[i].closure = closure; udp_requests->requests[i].callback = callback; udp_requests->requests[i].addr = *peer_addr; udp_requests->requests[i].try = 0; gettimeofday(&udp_requests->requests[i].timeout, NULL); timeval_add_microsec(&udp_requests->requests[i].timeout, gfs_client_datagram_timeouts[0] * MILLISEC_BY_MICROSEC); --udp_requests->requests_free; return NULL; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/makes/lib.mk install: all lib-install post-install-hook clean: lib-clean post-clean-hook veryclean: lib-veryclean post-veryclean-hook distclean: lib-distclean post-distclean-hook gfregister: lib-gfregister post-gfregister-hook man: lib-man post-man-hook html: lib-html post-html-hook post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: $(LIBRARY): $(OBJS) $(DEPLIBS) $(LTLINK) $(OBJS) $(LDLIBS) lib-install: @set -x; \ for i in -- $(LIBRARY_RESULT); do \ case $$i in --) continue;; esac; \ $(LTINSTALL_LIBRARY) $$i $(libdir)/$$i; \ done lib-clean: -$(LTCLEAN) $(OBJS) $(EXTRA_CLEAN_TARGETS) lib-veryclean: clean -test -z "$(EXTRA_VERYCLEAN_TARGETS)" || $(LTCLEAN) $(EXTRA_VERYCLEAN_TARGETS) -test -z "$(LIBRARY)" || $(LTCLEAN) $(LIBRARY) -test -z "$(LIBRARY_RESULT)" || $(LTCLEAN) $(LIBRARY_RESULT) lib-distclean: veryclean -test ! -f $(srcdir)/Makefile.in || $(RM) -f Makefile lib-gfregister: lib-man: lib-html: <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfmdlist_cli.sh #!/bin/sh # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi OLD_MDS_LIST_PATH=$MDS_LIST_PATH.old # exec check command MDS_LIST=`gfmdhost -l` if [ $? = 0 ]; then if [ -f $MDS_LIST_PATH ]; then mv -f $MDS_LIST_PATH $OLD_MDS_LIST_PATH fi cat << EOF > $MDS_LIST_PATH $MDS_LIST EOF RESULT="gfmdhost -l same." if [ -f $OLD_MDS_LIST_PATH ]; then DIFF=`diff $OLD_MDS_LIST_PATH $MDS_LIST_PATH | head -1` if [ X"$DIFF" != X ]; then RESULT="gfmdhost -l changed." fi fi else RESULT="gfmdhost -l error." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/gfs_hook/hooks.c /* * Hooking system calls to utilize Gfarm file system. * * $Id$ */ #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "hooks_subr.h" #include <sys/syscall.h> #if defined(__osf__) && defined(__alpha) /* Tru64 */ #define SYS_creat SYS_old_creat #endif #ifdef __NetBSD__ #define SYS_creat SYS_compat_43_ocreat #define SYS_stat SYS___stat13 #define SYS_fstat SYS___fstat13 #define SYS_lstat SYS___lstat13 #endif #ifdef SYS_utime #include <sys/types.h> #include <utime.h> #endif /* * XXX - quite naive implementation * * It is necessary to re-implement more cleverly. */ /* * read */ ssize_t __read(int filedes, void *buf, size_t nbyte) { GFS_File gf; char *e; int n; _gfs_hook_debug_v(fprintf(stderr, "Hooking __read(%d, , %lu)\n", filedes, (unsigned long)nbyte)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return syscall(SYS_read, filedes, buf, nbyte); if (gfs_hook_gfs_file_type(filedes) == GFS_DT_DIR) { _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __read(%d, , %lu)\n", filedes, (unsigned long)nbyte)); e = GFARM_ERR_IS_A_DIRECTORY; goto error; } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __read(%d(%d), , %lu)\n", filedes, gfs_pio_fileno(gf), (unsigned long)nbyte)); e = gfs_pio_read(gf, buf, nbyte, &n); if (e == NULL) { _gfs_hook_debug_v(fprintf(stderr, "GFS: Hooking __read --> %d\n", n)); return (n); } error: _gfs_hook_debug(fprintf(stderr, "GFS: __read: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } ssize_t _read(int filedes, void *buf, size_t nbyte) { _gfs_hook_debug_v(fputs("Hooking _read\n", stderr)); return (__read(filedes, buf, nbyte)); } ssize_t read(int filedes, void *buf, size_t nbyte) { _gfs_hook_debug_v(fputs("Hooking read\n", stderr)); return (__read(filedes, buf, nbyte)); } ssize_t _libc_read(int filedes, void *buf, size_t nbyte) { _gfs_hook_debug_v(fputs("Hooking _libc_read\n", stderr)); return (__read(filedes, buf, nbyte)); } /* * write */ /* fprintf and fputs should not be put into the following function. */ ssize_t __write(int filedes, const void *buf, size_t nbyte) { GFS_File gf; char *e; int n; /* * DO NOT put the following line here. This causes infinite loop! * * _gfs_hook_debug_v(fprintf(stderr, "Hooking __write(%d, , %lu)\n", * filedes, (unsigned long)nbyte)); */ if ((gf = gfs_hook_is_open(filedes)) == NULL) return (syscall(SYS_write, filedes, buf, nbyte)); if (gfs_hook_gfs_file_type(filedes) == GFS_DT_DIR) { /* * DO NOT put the following line here, which results * in infinite loop. * * _gfs_hook_debug(fprintf(stderr, * "GFS: Hooking __write(%d, , %d)\n", * filedes, nbyte)); */ e = GFARM_ERR_IS_A_DIRECTORY; goto error; } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __write(%d(%d), , %lu)\n", filedes, gfs_pio_fileno(gf), (unsigned long)nbyte)); e = gfs_pio_write(gf, buf, nbyte, &n); if (e == NULL) { _gfs_hook_debug_v(fprintf(stderr, "GFS: Hooking __write --> %d\n", n)); return (n); } error: /* * DO NOT put the following line here. * * _gfs_hook_debug(fprintf(stderr, "GFS: __write: %s\n", e)); */ errno = gfarm_error_to_errno(e); return (-1); } ssize_t _write(int filedes, const void *buf, size_t nbyte) { return (__write(filedes, buf, nbyte)); } ssize_t write(int filedes, const void *buf, size_t nbyte) { return (__write(filedes, buf, nbyte)); } ssize_t _libc_write(int filedes, const void *buf, size_t nbyte) { return (__write(filedes, buf, nbyte)); } /* * close */ int __syscall_close(int filedes) { return (syscall(SYS_close, filedes)); } int __close(int filedes) { GFS_File gf; char *e; _gfs_hook_debug_v(fprintf(stderr, "Hooking __close(%d)\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (__syscall_close(filedes)); switch (gfs_hook_gfs_file_type(filedes)) { case GFS_DT_REG: _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __close(%d(%d))\n", filedes, gfs_pio_fileno(gf))); break; case GFS_DT_DIR: _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __close(%d)\n", filedes)); break; default: _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __close: couldn't get gf or dir\n")); errno = EBADF; /* XXX - something broken */ return (-1); } e = gfs_hook_clear_gfs_file(filedes); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __close: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _close(int filedes) { _gfs_hook_debug_v(fputs("Hooking _close\n", stderr)); return (__close(filedes)); } int close(int filedes) { _gfs_hook_debug_v(fputs("Hooking close\n", stderr)); return (__close(filedes)); } int _libc_close(int filedes) { _gfs_hook_debug_v(fputs("Hooking close\n", stderr)); return (__close(filedes)); } int _private_close(int filedes) { _gfs_hook_debug_v(fputs("Hooking close\n", stderr)); return (__close(filedes)); } /* * unlink */ int __unlink(const char *path) { const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __unlink(%s)\n", path)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_unlink, path); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __unlink(%s)\n", path)); e = gfs_unlink(url); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __unlink: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _unlink(const char *path) { _gfs_hook_debug_v(fputs("Hooking _unlink\n", stderr)); return (__unlink(path)); } int unlink(const char *path) { _gfs_hook_debug_v(fputs("Hooking unlink\n", stderr)); return (__unlink(path)); } /* * access */ int __access(const char *path, int type) { char *e, *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __access(%s, %d)\n", path, type)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_access, path, type); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __access(%s, %d)\n", path, type)); e = gfs_access(url, type); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __access: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _access(const char *path, int type) { _gfs_hook_debug_v(fputs("Hooking _access\n", stderr)); return (__access(path, type)); } int access(const char *path, int type) { _gfs_hook_debug_v(fputs("Hooking access\n", stderr)); return (__access(path, type)); } /* * mmap * * XXX - just print out the information. */ #if 0 /* XXX - Linux causes a segfault while loading a shared library. Should we call old_map() instead of syscall(SYS_mmap)??? */ void * __mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off) { GFS_File gf; int gfs_fd; _gfs_hook_debug_v(fprintf(stderr, "Hooking __mmap(%p, %lu, %d, %d, %d, %ld)\n", addr, (unsigned long)len, prot, flags, fildes, (long)off)); if ((gf = gfs_hook_is_open(fildes)) == NULL) return (void *)syscall( SYS_mmap, addr, len, prot, flags, fildes, off); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __mmap(%p, %lu, %d, %d, %d, %ld)\n", addr, (unsigned long)len, prot, flags, fildes, (long)off)); gfs_fd = gfs_pio_fileno(gf); return (void *)syscall(SYS_mmap, addr, len, prot, flags, gfs_fd, off); } void * _mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off) { _gfs_hook_debug_v(fputs("Hooking _mmap\n", stderr)); return (__mmap(addr, len, prot, flags, fildes, off)); } void * mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off) { _gfs_hook_debug_v(fputs("Hooking mmap\n", stderr)); return (__mmap(addr, len, prot, flags, fildes, off)); } #endif /* * dup2 and dup */ #ifdef SYS_dup2 int __dup2(int oldfd, int newfd) { struct _gfs_file_descriptor *d; _gfs_hook_debug_v(fprintf(stderr, "Hooking __dup2(%d, %d)\n", oldfd, newfd)); if (gfs_hook_is_open(oldfd) == NULL && gfs_hook_is_open(newfd) == NULL) return syscall(SYS_dup2, oldfd, newfd); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __dup2(%d, %d)\n", oldfd, newfd)); d = gfs_hook_dup_descriptor(oldfd); gfs_hook_set_descriptor(newfd, d); /* * dup2() should be called after gfs_hook_set_descriptor() * because newfd may be a descriptor reserved for a hooking point * of a Gfarm file. */ if (syscall(SYS_dup2, oldfd, newfd) == -1) return (-1); return (newfd); } int _dup2(int oldfd, int newfd) { _gfs_hook_debug_v(fputs("Hooking _dup2\n", stderr)); return (__dup2(oldfd, newfd)); } int dup2(int oldfd, int newfd) { _gfs_hook_debug_v(fputs("Hooking dup2\n", stderr)); return (__dup2(oldfd, newfd)); } #endif /* SYS_dup2 */ int __dup(int oldfd) { struct _gfs_file_descriptor *d; int newfd; _gfs_hook_debug_v(fprintf(stderr, "Hooking __dup(%d)\n", oldfd)); if (gfs_hook_is_open(oldfd) == NULL) return syscall(SYS_dup, oldfd); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __dup(%d)\n", oldfd)); newfd = syscall(SYS_dup, oldfd); if (newfd == -1) return (-1); d = gfs_hook_dup_descriptor(oldfd); gfs_hook_set_descriptor(newfd, d); return (newfd); } int _dup(int oldfd) { _gfs_hook_debug_v(fputs("Hooking _dup\n", stderr)); return (__dup(oldfd)); } int dup(int oldfd) { _gfs_hook_debug_v(fputs("Hooking dup\n", stderr)); return (__dup(oldfd)); } /* * execve */ int __execve(const char *filename, char *const argv [], char *const envp[]) { char *url, *e; _gfs_hook_debug_v(fprintf(stderr, "Hooking __execve(%s)\n", filename)); if (!gfs_hook_is_url(filename, &url)) return syscall(SYS_execve, filename, argv, envp); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __execve(%s)\n", url)); e = gfs_execve(url, argv, envp); free(url); _gfs_hook_debug(fprintf(stderr, "GFS: __execve: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _execve(const char *filename, char *const argv [], char *const envp[]) { _gfs_hook_debug_v(fputs("Hooking _execve\n", stderr)); return (__execve(filename, argv, envp)); } int execve(const char *filename, char *const argv [], char *const envp[]) { _gfs_hook_debug_v(fputs("Hooking execve\n", stderr)); return (__execve(filename, argv, envp)); } int _private_execve(const char *filename, char *const argv [], char *const envp[]) { _gfs_hook_debug_v(fputs("Hooking execve\n", stderr)); return (__execve(filename, argv, envp)); } /* * vfork - this entry is needed for linux to avoid segfault. */ #ifdef SYS_vfork pid_t __vfork(void) { _gfs_hook_debug_v(fprintf(stderr, "Hooking __vfork()\n")); /* SYS_fork is called instead of SYS_vfork. */ return syscall(SYS_fork); } pid_t _vfork(void) { _gfs_hook_debug_v(fputs("Hooking _vfork\n", stderr)); return (__vfork()); } pid_t vfork(void) { _gfs_hook_debug_v(fputs("Hooking vfork\n", stderr)); return (__vfork()); } #endif /* * utimes & utime */ int __utimes(const char *path, const struct timeval *tvp) { char *e, *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __utimes(%s, %p)\n", path, tvp)); if (!gfs_hook_is_url(path, &url)) { #ifdef SYS_utimes return syscall(SYS_utimes, path, tvp); #else /* e.g. linux */ if (tvp == NULL) { return syscall(SYS_utime, path, NULL); } else { struct utimbuf ut; ut.actime = tvp[0].tv_sec; ut.modtime = tvp[1].tv_sec; return syscall(SYS_utime, path, &ut); } #endif } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __utimes(%s)\n", url)); if (tvp == NULL) e = gfs_utimes(url, NULL); else { struct gfarm_timespec gt[2]; gt[0].tv_sec = tvp[0].tv_sec; gt[0].tv_nsec= tvp[0].tv_usec * 1000; gt[1].tv_sec = tvp[1].tv_sec; gt[1].tv_nsec= tvp[1].tv_usec * 1000; e = gfs_utimes(url, gt); } free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __utimes: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _utimes(const char *path, const struct timeval *tvp) { _gfs_hook_debug_v(fputs("Hooking _utimes\n", stderr)); return (__utimes(path, tvp)); } int utimes(const char *path, const struct timeval *tvp) { _gfs_hook_debug_v(fputs("Hooking utimes\n", stderr)); return (__utimes(path, tvp)); } #ifdef SYS_utime int __utime(const char *path, const struct utimbuf *buf) { char *e, *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __utime(%s, %p)\n", path, buf)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_utime, path, buf); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __utime(%s)\n", url)); if (buf == NULL) e = gfs_utimes(url, NULL); else { struct gfarm_timespec gt[2]; gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __utime: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _utime(const char *path, const struct utimbuf *buf) { _gfs_hook_debug_v(fputs("Hooking _utime\n", stderr)); return (__utime(path, buf)); } int utime(const char *path, const struct utimbuf *buf) { _gfs_hook_debug_v(fputs("Hooking utime\n", stderr)); return (__utime(path, buf)); } #endif /* SYS_utime */ /* * mkdir */ int __mkdir(const char *path, mode_t mode) { const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __mkdir(%s, 0%o)\n", path, mode)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_mkdir, path, mode); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __mkdir(%s, 0%o)\n", path, mode)); e = gfs_mkdir(url, mode); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __mkdir: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _mkdir(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking _mkdir\n", stderr)); return (__mkdir(path, mode)); } int mkdir(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking mkdir\n", stderr)); return (__mkdir(path, mode)); } /* * rmdir */ int __rmdir(const char *path) { const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __rmdir(%s)\n", path)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_rmdir, path); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __rmdir(%s)\n", path)); e = gfs_rmdir(url); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __rmdir: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _rmdir(const char *path) { _gfs_hook_debug_v(fputs("Hooking _rmdir\n", stderr)); return (__rmdir(path)); } int rmdir(const char *path) { _gfs_hook_debug_v(fputs("Hooking rmdir\n", stderr)); return (__rmdir(path)); } /* * chdir */ int __chdir(const char *path) { const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __chdir(%s)\n", path)); if (!gfs_hook_set_cwd_is_gfarm(gfs_hook_is_url(path, &url))) return syscall(SYS_chdir, path); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __chdir(%s)\n", path)); e = gfs_chdir(url); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __chdir: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _chdir(const char *path) { _gfs_hook_debug_v(fputs("Hooking _chdir\n", stderr)); return (__chdir(path)); } int chdir(const char *path) { _gfs_hook_debug_v(fputs("Hooking chdir\n", stderr)); return (__chdir(path)); } /* * fchdir */ int __fchdir(int filedes) { GFS_File gf; const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __fchdir(%d)\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return syscall(SYS_fchdir, filedes); if (gfs_hook_gfs_file_type(filedes) != GFS_DT_DIR) { e = GFARM_ERR_NOT_A_DIRECTORY; goto error; } _gfs_hook_debug( fprintf(stderr, "GFS: Hooking __fchdir(%d)\n", filedes)); e = gfarm_path_canonical_to_url( gfs_hook_get_gfs_canonical_path(filedes), &url); if (e != NULL) goto error; e = gfs_chdir(url); free(url); if (e == NULL) return (0); error: _gfs_hook_debug(fprintf(stderr, "GFS: __fchdir: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _fchdir(int filedes) { _gfs_hook_debug_v(fputs("Hooking _fchdir\n", stderr)); return (__fchdir(filedes)); } int fchdir(int filedes) { _gfs_hook_debug_v(fputs("Hooking fchdir\n", stderr)); return (__fchdir(filedes)); } /* * getcwd */ char * __getcwd(char *buf, size_t size) { const char *e; _gfs_hook_debug_v(fprintf(stderr, "Hooking __getcwd(%p, %lu)\n", buf, (unsigned long)size)); if (!gfs_hook_get_cwd_is_gfarm()) return (gfs_hook_syscall_getcwd(buf, size)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __getcwd(%p, %lu)\n" ,buf, (unsigned long)size)); e = gfs_hook_get_prefix(buf, size); if (e != NULL) goto error; e = gfs_getcwd(buf + strlen(buf), size - strlen(buf)); if (e == NULL) return (buf); error: _gfs_hook_debug(fprintf(stderr, "GFS: __getcwd: %s\n", e)); errno = gfarm_error_to_errno(e); return (NULL); } char * _getcwd(char *buf, size_t size) { _gfs_hook_debug_v(fputs("Hooking _getcwd\n", stderr)); return (__getcwd(buf, size)); } char * getcwd(char *buf, size_t size) { _gfs_hook_debug_v(fputs("Hooking getcwd\n", stderr)); return (__getcwd(buf, size)); } /* * chmod */ int __chmod(const char *path, mode_t mode) { const char *e; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __chmod(%s, 0%o)\n", path, mode)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_chmod, path, mode); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __chmod(%s, 0%o)\n", path, mode)); e = gfs_chmod(url, mode); free(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __chmod: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _chmod(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking _chmod\n", stderr)); return (__chmod(path, mode)); } int chmod(const char *path, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking chmod\n", stderr)); return (__chmod(path, mode)); } /* * fchmod */ int __fchmod(int filedes, mode_t mode) { GFS_File gf; char *e, *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __fchmod(%d, 0%o)\n", filedes, mode)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return syscall(SYS_fchmod, filedes, mode); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __fchmod(%d, 0%o)\n", filedes, mode)); switch (gfs_hook_gfs_file_type(filedes)) { case GFS_DT_REG: e = gfs_fchmod(gf, mode); break; case GFS_DT_DIR: url = gfarm_url_prefix_add(gfs_dirname((GFS_Dir)gf)); if (url == NULL) { e = GFARM_ERR_NO_MEMORY; break; } e = gfs_chmod(url, mode); free(url); break; default: _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __fchmod: couldn't get gf or dir\n")); errno = EBADF; /* XXX - something broken */ return (-1); } if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __fchmod: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _fchmod(int filedes, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking _fchmod\n", stderr)); return (__fchmod(filedes, mode)); } int fchmod(int filedes, mode_t mode) { _gfs_hook_debug_v(fputs("Hooking fchmod\n", stderr)); return (__fchmod(filedes, mode)); } /* * rename */ int __rename(const char *oldpath, const char *newpath) { const char *e; char *oldurl, *newurl; int old_is_url, new_is_url; _gfs_hook_debug_v(fprintf(stderr, "Hooking __rename(%s, %s)\n", oldpath, newpath)); old_is_url = gfs_hook_is_url(oldpath, &oldurl); new_is_url = gfs_hook_is_url(newpath, &newurl); if (!old_is_url || !new_is_url) { if (old_is_url) free(oldurl); if (new_is_url) free(newurl); if (old_is_url != new_is_url) { errno = EXDEV; return (-1); } return (syscall(SYS_rename, oldpath, newpath)); } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __rename(%s, %s)\n", oldpath, newpath)); e = gfs_rename(oldurl, newurl); free(oldurl); free(newurl); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __rename: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _rename(const char *oldpath, const char *newpath) { _gfs_hook_debug_v(fputs("Hooking _rename\n", stderr)); return (__rename(oldpath, newpath)); } int rename(const char *oldpath, const char *newpath) { _gfs_hook_debug_v(fputs("Hooking rename\n", stderr)); return (_rename(oldpath, newpath)); } #ifdef __linux__ /* * getxattr */ int getxattr(const char *path, const char *name, void *value, size_t size) { char *e, *gfarm_file; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking getxattr(%s, %s, %p, %lu)\n", path, name, value, (unsigned long)size)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_getxattr, path, name, value, size); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking getxattr(%s, %s, %p, %lu)\n", path, name, value, (unsigned long)size)); e = gfarm_url_make_path(url, &gfarm_file); free(url); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_SUPPORTED; free(gfarm_file); } _gfs_hook_debug(fprintf(stderr, "GFS: getxattr: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } /* * lgetxattr */ int lgetxattr(const char *path, const char *name, void *value, size_t size) { char *e, *gfarm_file; char *url; _gfs_hook_debug_v(fprintf(stderr, "Hooking lgetxattr(%s, %s, %p, %lu)\n", path, name, value, (unsigned long)size)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_lgetxattr, path, name, value, size); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking lgetxattr(%s, %s, %p, %lu)\n", path, name, value, (unsigned long)size)); e = gfarm_url_make_path(url, &gfarm_file); free(url); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_SUPPORTED; free(gfarm_file); } _gfs_hook_debug(fprintf(stderr, "GFS: lgetxattr: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } /* * fgetxattr */ int fgetxattr(int filedes, const char *name, void *value, size_t size) { char *e; _gfs_hook_debug_v(fprintf(stderr, "Hooking fgetxattr(%d, %s, %p, %lu)\n", filedes, name, value, (unsigned long)size)); if (!gfs_hook_is_open(filedes)) return syscall(SYS_fgetxattr, filedes, name, value, size); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking fgetxattr(%d, %s, %p, %lu)\n", filedes, name, value, (unsigned long)size)); e = GFARM_ERR_OPERATION_NOT_SUPPORTED; _gfs_hook_debug(fprintf(stderr, "GFS: fgetxattr: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } #endif /* * definitions for "hooks_common.c" */ int gfs_hook_syscall_open(const char *path, int oflag, mode_t mode) { return (syscall(SYS_open, path, oflag, mode)); } int gfs_hook_syscall_creat(const char *path, mode_t mode) { return (syscall(SYS_creat, path, mode)); } off_t gfs_hook_syscall_lseek(int filedes, off_t offset, int whence) { #if defined(__NetBSD__) return (__syscall((quad_t)SYS_lseek, filedes, 0, offset, whence)); #else return (syscall(SYS_lseek, filedes, offset, whence)); #endif } #ifndef __linux__ int gfs_hook_syscall_getdents(int filedes, struct dirent *buf, size_t nbyte) { return (syscall(SYS_getdents, filedes, buf, nbyte)); } #endif int gfs_hook_syscall_stat(const char *path, struct stat *buf) { #ifndef _STAT_VER return (syscall(SYS_stat, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_xstat(_STAT_VER, path, buf)); #endif } int gfs_hook_syscall_lstat(const char *path, struct stat *buf) { #ifndef _STAT_VER return (syscall(SYS_lstat, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_lxstat(_STAT_VER, path, buf)); #endif } int gfs_hook_syscall_fstat(int filedes, struct stat *buf) { #ifndef _STAT_VER return (syscall(SYS_fstat, filedes, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_fxstat(_STAT_VER, filedes, buf)); #endif } #if defined(_STAT_VER) && defined(SYS_xstat) /* * for SVR4. * * but not for Linux. (see sysdep/linux/xstat.c for Linux version) */ int gfs_hook_syscall_xstat(int ver, const char *path, struct stat *buf) { return (syscall(SYS_xstat, ver, path, buf)); } int gfs_hook_syscall_lxstat(int ver, const char *path, struct stat *buf) { return (syscall(SYS_lxstat, ver, path, buf)); } int gfs_hook_syscall_fxstat(int ver, int filedes, struct stat *buf) { return (syscall(SYS_fxstat, ver, filedes, buf)); } #endif /* defined(_STAT_VER) && defined(SYS_xstat) */ #define OFF_T off_t #define SYSCALL_OPEN(path, oflag, mode) \ gfs_hook_syscall_open(path, oflag, mode) #define SYSCALL_CREAT(path, mode) \ gfs_hook_syscall_creat(path, mode) #define SYSCALL_LSEEK(filedes, offset, whence) \ gfs_hook_syscall_lseek(filedes, offset, whence) #define SYSCALL_GETDENTS(filedes, buf, nbyte) \ gfs_hook_syscall_getdents(filedes, buf, nbyte) #define FUNC___OPEN __open #define FUNC__OPEN _open #define FUNC_OPEN open #define FUNC___CREAT __creat #define FUNC__CREAT _creat #define FUNC_CREAT creat #define FUNC__LIBC_CREAT _libc_creat #define FUNC___LSEEK __lseek #define FUNC__LSEEK _lseek #define FUNC_LSEEK lseek #define FUNC___GETDENTS __getdents #define FUNC__GETDENTS _getdents #define FUNC_GETDENTS getdents #define STRUCT_DIRENT struct dirent #define ALIGNMENT 8 #define ALIGN(p) (((unsigned long)(p) + ALIGNMENT - 1) & ~(ALIGNMENT - 1)) #include "hooks_common.c" #undef ALIGNMENT /* stat */ #define STRUCT_STAT struct stat #define GFS_BLKSIZE 8192 #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_stat(path, buf) #define FUNC___STAT __stat #define FUNC__STAT _stat #define FUNC_STAT stat #define GFS_STAT gfs_stat #define GFS_STAT_SECTION gfs_stat_section #define GFS_STAT_INDEX gfs_stat_index #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_xstat(ver, path, buf) #define FUNC___XSTAT __xstat #define FUNC__XSTAT _xstat #endif #include "hooks_stat.c" #undef SYSCALL_STAT #undef FUNC___STAT #undef FUNC__STAT #undef FUNC_STAT #undef GFS_STAT #ifdef _STAT_VER /* SVR4 or Linux */ #undef SYSCALL_XSTAT #undef FUNC___XSTAT #undef FUNC__XSTAT #endif /* lstat */ #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_lstat(path, buf) #define FUNC___STAT __lstat #define FUNC__STAT _lstat #define FUNC_STAT lstat #define GFS_STAT gfs_stat /* XXX - gfs_lstat is not implemented yet. */ #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_lxstat(ver, path, buf) #define FUNC___XSTAT __lxstat #define FUNC__XSTAT _lxstat #endif #include "hooks_stat.c" /* fstat */ #define SYSCALL_FSTAT(path, buf) \ gfs_hook_syscall_fstat(path, buf) #define FUNC___FSTAT __fstat #define FUNC__FSTAT _fstat #define FUNC_FSTAT fstat #define GFS_FSTAT gfs_fstat #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_FXSTAT(ver, fd, buf) \ gfs_hook_syscall_fxstat(ver, fd, buf) #define FUNC___FXSTAT __fxstat #define FUNC__FXSTAT _fxstat #endif #include "hooks_fstat.c" <file_sep>/gfarm/tags/gfarm_1_0_beta_3/gftool/gfls/gfls.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <libgen.h> #include <limits.h> #include <unistd.h> #include <sys/time.h> #include <time.h> #include <gfarm/gfarm.h> char *program_name = "gfls"; enum output_format { OF_ONE_PER_LINE, OF_MULTI_COLUMN, OF_LONG } option_output_format; /* -1/-C/-l */ enum sort_order { SO_NAME, SO_SIZE, SO_MTIME } option_sort_order = SO_NAME; /* -S/-t */ int option_type_suffix = 0; /* -F */ int option_recursive = 0; /* -R */ int option_complete_time = 0; /* -T */ int option_directory_itself = 0; /* -d */ int option_reverse_sort = 0; /* -r */ int screen_width = 80; /* default */ /* * gfls implementation */ struct ls_entry { char *path; struct gfs_stat *st; }; int compare_name(const void *a, const void *b) { const struct ls_entry *p = a, *q = b; return (strcmp(p->path, q->path)); } int compare_name_r(const void *a, const void *b) { const struct ls_entry *p = a, *q = b; return (-strcmp(p->path, q->path)); } int compare_size(const void *a, const void *b) { const struct ls_entry *p = a, *q = b; if (p->st->st_size > q->st->st_size) return (1); else if (p->st->st_size < q->st->st_size) return (-1); else return (0); } int compare_size_r(const void *a, const void *b) { return (-compare_size(a, b)); } int timespec_cmp(struct gfarm_timespec *t1, struct gfarm_timespec *t2) { if (t1->tv_sec > t2->tv_sec) return (1); if (t1->tv_sec < t2->tv_sec) return (-1); if (t1->tv_nsec > t2->tv_nsec) return (1); if (t1->tv_nsec < t2->tv_nsec) return (-1); return (0); } int compare_mtime(const void *a, const void *b) { const struct ls_entry *p = a, *q = b; return (timespec_cmp(&q->st->st_mtimespec, &p->st->st_mtimespec)); } int compare_mtime_r(const void *a, const void *b) { const struct ls_entry *p = a, *q = b; return (timespec_cmp(&p->st->st_mtimespec, &q->st->st_mtimespec)); } void ls_sort(int n, struct ls_entry *ls) { int (*compare)(const void *, const void *); #ifdef __GNUC__ /* workaround gcc warning: unused variable */ compare = NULL; #endif if (option_reverse_sort) { switch (option_sort_order) { case SO_NAME: compare = compare_name_r; break; case SO_SIZE: compare = compare_size_r; break; case SO_MTIME: compare = compare_mtime_r; break; } } else { switch (option_sort_order) { case SO_NAME: compare = compare_name; break; case SO_SIZE: compare = compare_size; break; case SO_MTIME: compare = compare_mtime; break; } } qsort(ls, n, sizeof(*ls), compare); } char * do_stats(char *prefix, int *np, char **files, struct gfs_stat *stats, struct ls_entry *ls) { int i, n = *np, m, prefix_len, space; char *namep, buffer[PATH_MAX * 2 + 1], *e, *e_save = NULL; prefix_len = strlen(prefix); if (prefix_len > sizeof(buffer) - 1) prefix_len = sizeof(buffer) - 1; memcpy(buffer, prefix, prefix_len); namep = &buffer[prefix_len]; space = sizeof(buffer) - prefix_len - 1; m = 0; for (i = 0; i < n; i++) { if (strlen(files[i]) <= space) { strcpy(namep, files[i]); } else { memcpy(namep, files[i], space); namep[space] = '\0'; } e = gfs_stat(buffer, &stats[i]); if (e != NULL) { fprintf(stderr, "%s: %s\n", buffer, e); if (e_save != NULL) e_save = e; continue; } ls[m].path = files[i]; ls[m].st = &stats[i]; m++; } *np = m; return (e_save); } void put_suffix(struct ls_entry *ls) { struct gfs_stat *st = ls->st; if (GFARM_S_ISDIR(st->st_mode)) putchar('/'); else if (GFARM_S_IS_PROGRAM(st->st_mode)) putchar('*'); } void put_perm(int mode) { if (mode & 04) putchar('r'); else putchar('-'); if (mode & 02) putchar('w'); else putchar('-'); if (mode & 01) putchar('x'); else putchar('-'); } #define HALFYEAR ((365 * 24 * 60 * 60) / 2) void put_time(struct gfarm_timespec *ts) { static struct timeval now; static int initialized = 0; struct tm *tm; time_t sec; char buffer[100]; if (!initialized) { gettimeofday(&now, NULL); initialized = 1; } sec = ts->tv_sec; tm = localtime(&sec); if (option_complete_time) strftime(buffer, sizeof(buffer) - 1, "%b %e %H:%M:%S %Y", tm); else if (ts->tv_sec >= now.tv_sec - HALFYEAR && ts->tv_sec <= now.tv_sec + HALFYEAR) strftime(buffer, sizeof(buffer) - 1, "%b %e %H:%M", tm); else strftime(buffer, sizeof(buffer) - 1, "%b %e %Y", tm); buffer[sizeof(buffer) - 1] = '\0'; fputs(buffer, stdout); } void put_stat(struct gfs_stat *st) { if (GFARM_S_ISDIR(st->st_mode)) putchar('d'); else putchar('-'); put_perm(st->st_mode >> 6); put_perm(st->st_mode >> 3); put_perm(st->st_mode); putchar(' '); printf("%-8s %-8s ", st->st_user, st->st_group); printf("%10" PR_FILE_OFFSET " ", st->st_size); put_time(&st->st_mtimespec); putchar(' '); } char * list_files(char *prefix, int n, char **files, int *need_newline) { int i; struct ls_entry *ls = malloc(sizeof(struct ls_entry) * n); struct gfs_stat *stats = NULL; char *e = NULL; if (ls == NULL) return (GFARM_ERR_NO_MEMORY); if (option_output_format == OF_LONG || option_sort_order != SO_NAME || option_type_suffix) { stats = malloc(sizeof(struct gfs_stat) * n); if (stats == NULL) { free(ls); return (GFARM_ERR_NO_MEMORY); } e = do_stats(prefix, &n, files, stats, ls); } else { for (i = 0; i < n; i++) { ls[i].path = files[i]; ls[i].st = NULL; } } ls_sort(n, ls); if (option_output_format == OF_MULTI_COLUMN) { int j, k, columns, lines, column_width, max_width = 0; for (i = 0; i < n; i++) if (max_width < strlen(ls[i].path)) max_width = strlen(ls[i].path); column_width = option_type_suffix ? max_width + 1 : max_width; columns = screen_width / (column_width + 1); lines = n / columns; if (lines * columns < n) lines++; for (i = 0; i < lines; i++) { for (j = 0; j < columns; j++) { k = i + j * lines; if (k >= n) break; fputs(ls[k].path, stdout); if (option_type_suffix) put_suffix(&ls[k]); printf("%*s", max_width - strlen(ls[k].path) + 1, ""); } putchar('\n'); } } else { for (i = 0; i < n; i++) { if (option_output_format == OF_LONG) put_stat(ls[i].st); fputs(ls[i].path, stdout); if (option_type_suffix) put_suffix(&ls[i]); putchar('\n'); } } if (n > 0 || e != NULL) *need_newline = 1; if (stats != NULL) free(stats); free(ls); return (e); } char *list_dirs(char *, int, char **, int *); char * list_dir(char *prefix, char *dirname, int *need_newline) { char *e, *s, *path, *e_save = NULL; gfarm_stringlist names; gfs_glob_t types; GFS_Dir dir; struct gfs_dirent *entry; int len = strlen(prefix) + strlen(dirname); path = malloc(len + 1 + 1); if (path == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(path, "%s%s", prefix, dirname); e = gfarm_stringlist_init(&names); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); free(path); return (e); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); gfarm_stringlist_free(&names); free(path); return (e); } e = gfs_opendir(path, &dir); if (e != NULL) { fprintf(stderr, "%s: %s\n", path, e); gfs_glob_free(&types); gfarm_stringlist_free(&names); free(path); return (e); } while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { s = strdup(entry->d_name); if (s == NULL) { e = GFARM_ERR_NO_MEMORY; break; } gfarm_stringlist_add(&names, s); gfs_glob_add(&types, entry->d_type); } if (e != NULL) { fprintf(stderr, "%s%s: %s\n", prefix, dirname, e); e_save = e; } gfs_closedir(dir); if (*gfarm_path_dir_skip(gfarm_url_prefix_skip(path)) != '\0') { path[len] = '/'; path[len + 1] = '\0'; } e = list_files(path, gfarm_stringlist_length(&names), GFARM_STRINGLIST_STRARRAY(names), need_newline); if (e_save == NULL) e_save = e; if (option_recursive) { int i; for (i = 0; i < gfarm_stringlist_length(&names); i++) { s = GFARM_STRINGLIST_STRARRAY(names)[i]; if (s[0] == '.' && (s[1] == '\0' || (s[1] == '.' && s[2] == '\0'))) continue; if (gfs_glob_elem(&types, i) == GFS_DT_DIR) { e = list_dirs(path, 1, &s, need_newline); if (e_save == NULL) e_save = e; } } } gfs_glob_free(&types); gfarm_stringlist_free_deeply(&names); free(path); return (e_save); } int string_compare(const void *a, const void *b) { const char *const *p = a, *const *q = b; return (strcmp(*p, *q)); } void string_sort(int n, char **v) { qsort(v, n, sizeof(*v), string_compare); } char * list_dirs(char *prefix, int n, char **dirs, int *need_newline) { char *e, *e_save = NULL; int i; string_sort(n, dirs); for (i = 0; i < n; i++) { if (*need_newline) { printf("\n"); *need_newline = 0; } printf("%s%s:\n", prefix, dirs[i]); e = list_dir(prefix, dirs[i], need_newline); *need_newline = 1; if (e_save == NULL) e_save = e; } return (e_save); } char * list(gfarm_stringlist *paths, gfs_glob_t *types, int *need_newline) { char *e, *e_save = NULL; gfarm_stringlist dirs, files; int i, nfiles, ndirs; if (option_directory_itself) { return (list_files("", gfarm_stringlist_length(paths), GFARM_STRINGLIST_STRARRAY(*paths), need_newline)); } e = gfarm_stringlist_init(&dirs); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); return (e); } e = gfarm_stringlist_init(&files); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); gfarm_stringlist_free(&dirs); return (e); } for (i = 0; i < gfarm_stringlist_length(paths); i++) { char *path = gfarm_stringlist_elem(paths, i); if (gfs_glob_elem(types, i) == GFS_DT_DIR) gfarm_stringlist_add(&dirs, path); else gfarm_stringlist_add(&files, path); } nfiles = gfarm_stringlist_length(&files); ndirs = gfarm_stringlist_length(&dirs); if (nfiles > 0) { e = list_files("", nfiles, GFARM_STRINGLIST_STRARRAY(files), need_newline); /* warning is already printed in list_files() */ if (e_save == NULL) e_save = e; } gfarm_stringlist_free(&files); if (nfiles == 0 && ndirs == 1) { e = list_dir("", gfarm_stringlist_elem(&dirs, 0), need_newline); /* warning is already printed in list_dir() */ } else { e = list_dirs("", ndirs, GFARM_STRINGLIST_STRARRAY(dirs), need_newline); /* warning is already printed in list_dirs() */ } if (e_save == NULL) e_save = e; gfarm_stringlist_free(&dirs); return (e_save); } void usage(void) { fprintf(stderr, "Usage: %s [-1CFRSTdlrt] <path>...\n", program_name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { char *e; gfarm_stringlist paths; gfs_glob_t types; int i, c, exit_code = EXIT_SUCCESS; extern char *optarg; if (argc > 0) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } if (isatty(STDOUT_FILENO)) { char *s = getenv("COLUMNS"); #ifdef TIOCGWINSZ struct winsize win; #endif if (s != NULL) screen_width = strtol(s, NULL, 0); #ifdef TIOCGWINSZ else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 && win.ws_col > 0) screen_width = win.ws_col; #endif option_output_format = OF_MULTI_COLUMN; } else { option_output_format = OF_ONE_PER_LINE; } while ((c = getopt(argc, argv, "1CFRSTdlrt")) != -1) { switch (c) { case '1': option_output_format = OF_ONE_PER_LINE; break; case 'C': option_output_format = OF_MULTI_COLUMN; break; case 'F': option_type_suffix = 1; break; case 'R': option_recursive = 1; break; case 'S': option_sort_order = SO_SIZE; break; case 'T': option_complete_time = 1; break; case 'd': option_directory_itself = 1; break; case 'l': option_output_format = OF_LONG; break; case 'r': option_reverse_sort = 1; break; case 't': option_sort_order = SO_MTIME; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } if (argc < 1) { gfarm_stringlist_add(&paths, "gfarm:."); gfs_glob_add(&types, GFS_DT_DIR); } else { for (i = 0; i < argc; i++) { int last; /* do not treat glob error as an error */ gfs_glob(argv[i], &paths, &types); last = gfs_glob_length(&types) - 1; if (last >= 0 && gfs_glob_elem(&types, last) == GFS_DT_UNKNOWN) { /* * Currently, this only happens if there is * no file which matches with argv[i]. * In such case, the number of entries which * were added by gfs_glob() is 1. * But also please note that GFS_DT_UNKNOWN * may happen on other case in future. */ struct gfs_stat s; char *path = gfarm_stringlist_elem(&paths, last); e = gfs_stat(path, &s); if (e != NULL) { fprintf(stderr, "%s: %s\n", path, e); exit_code = EXIT_FAILURE; /* remove last entry */ /* XXX: FIXME layering violation */ free(paths.array[last]); paths.length--; types.length--; } else { GFS_GLOB_ELEM(types, last) = GFARM_S_ISDIR(s.st_mode) ? GFS_DT_DIR : GFS_DT_REG; gfs_stat_free(&s); } } } } if (gfarm_stringlist_length(&paths) > 0) { int need_newline = 0; #if 1 if (list(&paths, &types, &need_newline) != NULL) { /* warning is already printed in list() */ exit_code = EXIT_FAILURE; } #else for (i = 0; i < gfarm_stringlist_length(&paths); i++) printf("<%s>\n", gfarm_stringlist_elem(&paths, i)); #endif } return (exit_code); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/gfptool/Makefile top_objdir = .. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk MPI_SUBDIRS = gfwc SUBDIRS = \ gfcombine \ gfcombine_hook \ gfcp \ gfcp_hook \ gfgrep \ gfsplck \ $(mpi_subdirs) include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm_mpiio/trunk/mvapich2/Makefile.mk ## -*- Mode: Makefile; -*- ## vim: set ft=automake : if BUILD_AD_GFARM noinst_HEADERS += adio/ad_gfarm/ad_gfarm.h AM_CPPFLAGS += -lgfarm romio_other_sources += \ adio/ad_gfarm/ad_gfarm.c\ adio/ad_gfarm/ad_gfarm_fcntl.c\ adio/ad_gfarm/ad_gfarm_resize.c\ adio/ad_gfarm/ad_gfarm_flush.c\ adio/ad_gfarm/ad_gfarm_open.c\ adio/ad_gfarm/ad_gfarm_delete.c\ adio/ad_gfarm/ad_gfarm_hints.c\ adio/ad_gfarm/ad_gfarm_close.c\ adio/ad_gfarm/ad_gfarm_read.c\ adio/ad_gfarm/ad_gfarm_wrcoll.c\ adio/ad_gfarm/ad_gfarm_rdcoll.c\ adio/ad_gfarm/ad_gfarm_seek.c\ adio/ad_gfarm/ad_gfarm_write.c endif BUILD_AD_GFARM <file_sep>/gfarm/tags/gfarm_1_0_beta_6/lib/libgfarm/gfarm/param.h /* * $Id$ */ struct sockaddr; struct gfarm_hostspec; struct gfarm_param_config; struct gfarm_param_type { char *name; int boolean; void *extension; }; char *gfarm_param_config_parse_long(int, struct gfarm_param_type *, char *, int *, long *); char *gfarm_param_config_add_long(struct gfarm_param_config ***, int, long, struct gfarm_hostspec *); char *gfarm_param_apply_long_by_name_addr(struct gfarm_param_config *, const char *, struct sockaddr *, char *(*)(void *, int, long), void *); char *gfarm_param_apply_long(struct gfarm_param_config *, char *(*)(void *, int, long), void *); char *gfarm_param_get_long_by_name_addr(struct gfarm_param_config *, int, char *, struct sockaddr *, long *); char *gfarm_param_get_long(struct gfarm_param_config *, int, long *); /* * netparam */ struct gfarm_netparam_info; char *gfarm_netparam_config_add_long(char *, struct gfarm_hostspec *); char *gfarm_netparam_config_get_long(struct gfarm_netparam_info *, char *, struct sockaddr *, long *); extern struct gfarm_netparam_info gfarm_netparam_parallel_streams; extern struct gfarm_netparam_info gfarm_netparam_stripe_unit_size; extern struct gfarm_netparam_info gfarm_netparam_rate_limit; extern struct gfarm_netparam_info gfarm_netparam_sync_rate; <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_7/xattr.h /* * $Id$ */ void gfarm2fs_xattr_init(struct gfarm2fs_param *); gfarm_error_t gfarm2fs_xattr_set(const char *, const char *, const void *, size_t, int); gfarm_error_t gfarm2fs_xattr_get(const char *, const char *, void *, size_t *); gfarm_error_t gfarm2fs_xattr_remove(const char *, const char *); static const char FIX_ACL_ACCESS[] = "gfarm2fs.fix_acl_access"; static const char FIX_ACL_DEFAULT[] = "gfarm2fs.fix_acl_default"; <file_sep>/gfarm/tags/gfarm_1_0_3/lib/gfs_hook/hooks_init.c /* * $Id$ */ #include <sys/types.h> #include <unistd.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" char * gfs_hook_initialize(void) { #if 0 return "gfs_hook_initialize: Cannot initialize"; #else char *e; _gfs_hook_debug(fprintf(stderr, "GFS: gfs_hook_initialize\n")); e = gfarm_initialize(NULL, NULL); if (e != NULL) return (e); if (gfs_pio_set_local_check() != NULL) gfs_pio_set_local(0, 1); return (NULL); #endif } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc3/gftool/gfrep/gfrep.c /* * $Id$ */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfrep"; void usage() { fprintf(stderr, "Usage: %s [option] <gfarm_url>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-H <hostfile>\t\treplicate a whole file\n"); fprintf(stderr, "\t-D <domainname>\t\treplicate a whole file\n"); fprintf(stderr, "\t-I fragment-index\treplicate a fragment" " with -d option\n"); fprintf(stderr, "\t-s src-node\n"); fprintf(stderr, "\t-d dest-node\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *hostfile = NULL; int ch, nhosts, error_line; char **hosttab; char *index = NULL, *src = NULL, *dest = NULL, *domainname = NULL; char *gfarm_url; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "H:I:s:d:D:")) != -1) { switch (ch) { case 'H': hostfile = optarg; break; case 'I': index = optarg; break; case 's': src = optarg; break; case 'd': dest = optarg; break; case 'D': domainname = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc != 1) usage(); gfarm_url = argv[0]; e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (index != NULL) { /* replicate a section */ if (hostfile != NULL) fprintf(stderr, "%s: warning: -H option is ignored\n", program_name); if (dest == NULL) { fprintf(stderr, "%s: -d dest-node option is required\n", program_name); exit(1); } if (src == NULL) e = gfarm_url_section_replicate_to(gfarm_url, index, dest); else e = gfarm_url_section_replicate_from_to(gfarm_url, index, src, dest); } else { /* replicate a whole file */ if (hostfile != NULL) { if (domainname != NULL) fprintf(stderr, "%s: warning: -D is ignored\n", program_name); e = gfarm_hostlist_read(hostfile, &nhosts, &hosttab, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: line %d: %s\n", hostfile, error_line, e); else fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_url_fragments_replicate(gfarm_url, nhosts, hosttab); } else if (domainname != NULL) { e = gfarm_url_fragments_replicate_to_domainname( gfarm_url, domainname); } else if (dest != NULL) { /* * Special case for replicating a Gfarm file * having only one fragment */ int nfrags; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_url, e); exit(1); } if (nfrags != 1) usage(); index = "0"; /* assume -I 0 */ if (src == NULL) e = gfarm_url_section_replicate_to( gfarm_url, index, dest); else e = gfarm_url_section_replicate_from_to( gfarm_url, index, src, dest); } else usage(); } if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, gfarm_url, e); exit(1); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT3-3-1-3_failover_while_file_replication #! /bin/sh ###################################################################### TESTID="FT3-3-1-3" CATEGORY="accident while failover and failure of meta data sync" SECTION="failover in the midst of client accessd" TITLE="failover while file replication" ###################################################################### . ./FT-common ft_setup() { DIR=mnt FILE=a.dat SIZE=1000M ssh $client1 "mkdir -p $DIR" $gfservice unmount client1 $DIR $gfservice mount client1 $DIR -o nonempty ssh $client1 "rm -f $FILE create-random-file $DIR/$FILE" scp create-random-file $client1: ssh $client1 "./create-random-file $FILE $SIZE" return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 "cp $FILE $DIR/$FILE" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "copy $FILE to the Gfarm2 filesytem on $client1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 "$client1_GFBINDIR/gfrep -N 2 $FILE" & [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "replicate $FILE on $client1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd2 "sudo kill -USR1 \`cat /var/run/gfmd.pid\`" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "upgrade slave gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_wait_remote_process $client1 "$client1_GFBINDIR/gfrep -N 2 $FILE" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "wait copying $FILE to the Gfarm2 filesytem on $client1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 "cmp $FILE $DIR/$FILE" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 6 "compare the copied $FILE with the original" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT GFWHERE=`ssh $client1 $client1_GFBINDIR/gfwhere $FILE` [ $? -eq 0 ] && [ "X$GFWHERE" != X ] && [ `echo $GFWHERE | awk '{ print NF }'` -eq 2 ] \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 7 "check replication status of $FILE" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $client1 "rm -f $FILE $DIR/$FILE create-random-file" $gfservice umount client1 $DIR ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc4/lib/libgfarm/gfarm/agent_proto.h /* * $Id$ */ enum gfarm_agent_proto_command { AGENT_PROTO_PATH_INFO_GET, AGENT_PROTO_PATH_INFO_SET, AGENT_PROTO_PATH_INFO_REPLACE, AGENT_PROTO_PATH_INFO_REMOVE, AGENT_PROTO_REALPATH_CANONICAL, AGENT_PROTO_GET_INO, AGENT_PROTO_OPENDIR, AGENT_PROTO_READDIR, AGENT_PROTO_CLOSEDIR, AGENT_PROTO_DIRNAME, AGENT_PROTO_UNCACHEDIR }; <file_sep>/gfarm/tags/gfarm_1_0_beta_4/include/gfarm/gfs_hook.h /* * $Id$ */ void gfs_hook_set_default_view_local(); void gfs_hook_set_default_view_index(int index, int nfrags); void gfs_hook_set_default_view_global(); char *gfs_hook_set_view_local(int fd, int flags); char *gfs_hook_set_view_index(int fd, int nfrags, int index, char *host, int flags); char *gfs_hook_set_view_global(int fd, int flags); <file_sep>/gfarm/branches/metadb_dev/lib/gfs_hook/hooks.c /* * Hooking system calls to utilize Gfarm file system. * * $Id$ */ #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "hooks_subr.h" #include <sys/syscall.h> #if defined(__osf__) && defined(__alpha) /* Tru64 */ #define SYS_creat SYS_old_creat #endif #ifdef __NetBSD__ #define SYS_creat SYS_compat_43_ocreat #define SYS_stat SYS___stat13 #endif /* * XXX - quite naive implementation * * It is necessary to re-implement more cleverly. */ /* * read */ ssize_t __read(int filedes, void *buf, size_t nbyte) { GFS_File gf; char *e; int n; _gfs_hook_debug(fprintf(stderr, "Hooking __read: %d\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return syscall(SYS_read, filedes, buf, nbyte); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __read: %d %d\n", filedes, gfs_pio_fileno(gf))); e = gfs_pio_read(gf, buf, nbyte, &n); if (e == NULL) return (n); _gfs_hook_debug(fprintf(stderr, "GFS: __read: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } ssize_t _read(int filedes, void *buf, size_t nbyte) { _gfs_hook_debug(fputs("Hooking _read\n", stderr)); return (__read(filedes, buf, nbyte)); } ssize_t read(int filedes, void *buf, size_t nbyte) { _gfs_hook_debug(fputs("Hooking read\n", stderr)); return (__read(filedes, buf, nbyte)); } /* * write */ /* fprintf and fputs should not be put into the following function. */ ssize_t __write(int filedes, const void *buf, size_t nbyte) { GFS_File gf; char *e; int n; if ((gf = gfs_hook_is_open(filedes)) == NULL) return (syscall(SYS_write, filedes, buf, nbyte)); e = gfs_pio_write(gf, buf, nbyte, &n); if (e == NULL) return (n); errno = gfarm_error_to_errno(e); return (-1); } ssize_t _write(int filedes, const void *buf, size_t nbyte) { return (__write(filedes, buf, nbyte)); } ssize_t write(int filedes, const void *buf, size_t nbyte) { return (__write(filedes, buf, nbyte)); } /* * close */ int __syscall_close(int filedes) { return (syscall(SYS_close, filedes)); } int __close(int filedes) { GFS_File gf; char *e; _gfs_hook_debug(fprintf(stderr, "Hooking __close: %d\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (__syscall_close(filedes)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __close: %d %d\n", filedes, gfs_pio_fileno(gf))); gfs_hook_clear_gfs_file(filedes); e = gfs_pio_close(gf); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __close: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } int _close(int filedes) { _gfs_hook_debug(fputs("Hooking _close\n", stderr)); return (__close(filedes)); } int close(int filedes) { _gfs_hook_debug(fputs("Hooking __close\n", stderr)); return (__close(filedes)); } /* * unlink */ int __unlink(const char *path) { const char *e, *url; _gfs_hook_debug(fprintf(stderr, "Hooking __unlink: %s\n", path)); if (!gfs_hook_is_url(path, &url)) return syscall(SYS_unlink, path); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking __unlink: %s\n", path)); e = gfs_unlink(url); if (e == NULL) return (0); _gfs_hook_debug(fprintf(stderr, "GFS: __unlink: %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); } /* * definitions for "hooks_common.c" */ int gfs_hook_syscall_open(const char *path, int oflag, mode_t mode) { return (syscall(SYS_open, path, oflag, mode)); } int gfs_hook_syscall_creat(const char *path, mode_t mode) { return (syscall(SYS_creat, path, mode)); } int gfs_hook_syscall_lseek(int filedes, off_t offset, int whence) { #if defined(__NetBSD__) return (__syscall((quad_t)SYS_lseek, filedes, 0, offset, whence)); #else return (syscall(SYS_lseek, filedes, offset, whence)); #endif } int gfs_hook_syscall_stat(const char *path, struct stat *buf) { #ifndef _STAT_VER return (syscall(SYS_stat, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_xstat(_STAT_VER, path, buf)); #endif } /* * for SVR4. * * (see sysdep/linux/xstat.c about Linux) */ #if defined(_STAT_VER) && defined(SYS_xstat) int gfs_hook_syscall_xstat(int ver, const char *path, struct stat *buf) { return (syscall(SYS_xstat, ver, path, buf)); } #endif #define OFF_T off_t #define SYSCALL_OPEN(path, oflag, mode) \ gfs_hook_syscall_open(path, oflag, mode) #define SYSCALL_CREAT(path, mode) \ gfs_hook_syscall_creat(path, mode) #define SYSCALL_LSEEK(filedes, offset, whence) \ gfs_hook_syscall_lseek(filedes, offset, whence) #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_stat(path, buf) #define FUNC___OPEN __open #define FUNC__OPEN _open #define FUNC_OPEN open #define FUNC___CREAT __creat #define FUNC__CREAT _creat #define FUNC_CREAT creat #define FUNC___LSEEK __lseek #define FUNC__LSEEK _lseek #define FUNC_LSEEK lseek #define FUNC___STAT __stat #define FUNC__STAT _stat #define FUNC_STAT stat #define STRUCT_STAT struct stat #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_xstat(ver, path, buf) #define FUNC___XSTAT __xstat #define FUNC__XSTAT _xstat #define FUNC_XSTAT xstat #endif #include "hooks_common.c" <file_sep>/gfarm/tags/gfarm_1_0_3/lib/libgfarm/gfarm/metadb_misc.c #include <stdlib.h> /* off_t */ #include <sys/types.h> /* off_t */ #include <sys/socket.h> /* struct sockaddr */ #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <gfarm/gfarm.h> #include "host.h" #include "gfs_client.h" char * gfarm_url_fragment_cleanup(char *gfarm_url, int nhosts, char **hosts) { char *e, *gfarm_file, **canonical_hostnames; int i, j, nfrags, ncopies; struct gfarm_file_section_info *frags; struct gfarm_file_section_copy_info *copies; struct gfs_connection *gfs_server; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_file_section_info_get_all_by_file( gfarm_file, &nfrags, &frags); if (e != NULL) { free(gfarm_file); return (NULL); } gfarm_file_section_info_free_all(nfrags, frags); if (nfrags == nhosts) { free(gfarm_file); return (NULL); /* complete */ } e = gfarm_host_get_canonical_names(nhosts, hosts, &canonical_hostnames); if (e != NULL) { free(gfarm_file); return (e); } /* * do removal */ /* remove gfarm_file_fragment_copy_info and actual copy */ for (i = 0; i < nhosts; i++) { char *path_section; char section_string[GFARM_INT32STRLEN + 1]; struct sockaddr peer_addr; sprintf(section_string, "%d", i); e = gfarm_path_section(gfarm_file, section_string, &path_section); if (e != NULL) continue; e = gfarm_host_address_get(hosts[i], gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { free(path_section); continue; } /* remove copy */ if (gfs_client_connection(canonical_hostnames[i], &peer_addr, &gfs_server) == NULL) gfs_client_unlink(gfs_server, path_section); e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section_string, &ncopies, &copies); if (e != NULL) { free(path_section); continue; } for (j = 0; j < ncopies; j++) { /* * equivalent to * gfarm_file_section_copy_info_remove_all_by_section() */ gfarm_file_section_copy_info_remove(gfarm_file, section_string, copies[j].hostname); /* remove actual copies */ if (strcasecmp(copies[j].hostname, canonical_hostnames[i]) == 0) continue; if (gfarm_host_address_get(copies[j].hostname, gfarm_spool_server_port, &peer_addr, NULL) != NULL) continue; if (gfs_client_connection(copies[j].hostname, &peer_addr, &gfs_server) == NULL) gfs_client_unlink(gfs_server, path_section); } free(path_section); gfarm_file_section_copy_info_free_all(ncopies, copies); } gfarm_file_section_info_remove_all_by_file(gfarm_file); gfarm_path_info_remove(gfarm_file); gfarm_strings_free_deeply(nhosts, canonical_hostnames); free(gfarm_file); return (NULL); } char * gfarm_url_fragment_number(const char *gfarm_url, int *np) { char *e, *gfarm_file; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); free(gfarm_file); if (e != NULL) return (e); if (!GFARM_S_IS_FRAGMENTED_FILE(pi.status.st_mode)) return (GFARM_ERR_OPERATION_NOT_PERMITTED); *np = pi.status.st_nsections; gfarm_path_info_free(&pi); return (NULL); } <file_sep>/gfarm2fs/branches/1.2.1/gfarm2fs_msg_enums.h #define GFARM_MSG_2000001 2000001 #define GFARM_MSG_2000002 2000002 #define GFARM_MSG_2000003 2000003 #define GFARM_MSG_2000004 2000004 #define GFARM_MSG_2000005 2000005 #define GFARM_MSG_2000006 2000006 #define GFARM_MSG_2000007 2000007 #define GFARM_MSG_2000008 2000008 #define GFARM_MSG_2000009 2000009 #define GFARM_MSG_2000010 2000010 #define GFARM_MSG_2000011 2000011 #define GFARM_MSG_2000012 2000012 #define GFARM_MSG_2000013 2000013 #define GFARM_MSG_2000014 2000014 #define GFARM_MSG_2000015 2000015 #define GFARM_MSG_2000016 2000016 #define GFARM_MSG_2000017 2000017 #define GFARM_MSG_2000018 2000018 #define GFARM_MSG_2000019 2000019 #define GFARM_MSG_2000020 2000020 #define GFARM_MSG_2000021 2000021 #define GFARM_MSG_2000022 2000022 #define GFARM_MSG_2000023 2000023 #define GFARM_MSG_2000024 2000024 #define GFARM_MSG_2000025 2000025 #define GFARM_MSG_2000026 2000026 #define GFARM_MSG_2000027 2000027 #define GFARM_MSG_2000028 2000028 #define GFARM_MSG_2000029 2000029 #define GFARM_MSG_2000030 2000030 #define GFARM_MSG_2000031 2000031 #define GFARM_MSG_2000032 2000032 #define GFARM_MSG_2000033 2000033 #define GFARM_MSG_2000034 2000034 #define GFARM_MSG_2000035 2000035 #define GFARM_MSG_2000036 2000036 #define GFARM_MSG_2000037 2000037 #define GFARM_MSG_2000038 2000038 #define GFARM_MSG_2000039 2000039 #define GFARM_MSG_2000040 2000040 #define GFARM_MSG_2000041 2000041 #define GFARM_MSG_2000042 2000042 #define GFARM_MSG_2000043 2000043 #define GFARM_MSG_2000044 2000044 #define GFARM_MSG_2000045 2000045 #define GFARM_MSG_2000046 2000046 #define GFARM_MSG_2000047 2000047 #define GFARM_MSG_2000048 2000048 #define GFARM_MSG_2000049 2000049 #define GFARM_MSG_2000050 2000050 #define GFARM_MSG_2000051 2000051 #define GFARM_MSG_2000052 2000052 #define GFARM_MSG_2000053 2000053 #define GFARM_MSG_2000054 2000054 #define GFARM_MSG_2000055 2000055 #define GFARM_MSG_2000056 2000056 #define GFARM_MSG_2000057 2000057 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT2-2-2-3_master_gfmd_down_and_master_candidate_MDS_network_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-3" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd down and master candidate MDS network down" ###################################################################### . ./FT-common ft_setup() { IFDOWN=/sbin/ifdown IFUP=/sbin/ifup CANDIDATE=`ft_get_master_candidate` [ $? -ne 0 ] && return $FT_RESULT_FAIL [ "X$CANDIDATE" = X ] && return $FT_RESULT_FAIL return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS gfmdhost -l > /dev/null 2>&1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "gfmdhost -l" $RESULT CANDIDATE_CTRL_ADDRESS=`eval echo \\${${CANDIDATE}_CTRL_ADDRESS}` CANDIDATE_GFARM_IF=`eval echo \\${${CANDIDATE}_GFARM_IF}` ssh ${CANDIDATE_CTRL_ADDRESS} sudo $IFDOWN $CANDIDATE_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "ifdown $CANDIDATE_GFARM_IF on $CANDIDATE" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop master gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh ${CANDIDATE_CTRL_ADDRESS} sudo $IFUP $CANDIDATE_GFARM_IF ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc1/server/gfmd/gfmd.c /* * $Id$ */ #include <gfarm/gfarm_config.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/resource.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <stdarg.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <pwd.h> #include <grp.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "xxx_proto.h" #include "io_fd.h" #include "sockopt.h" #include "auth.h" #include "config.h" #include "gfm_proto.h" #include "gfj_client.h" #ifdef SOMAXCONN #define LISTEN_BACKLOG SOMAXCONN #else #define LISTEN_BACKLOG 5 #endif /* limit maximum connections, when system limit is very high */ #ifndef GFMD_CONNECTION_LIMIT #define GFMD_CONNECTION_LIMIT 65536 #endif char *program_name = "gfmd"; int debug_mode = 0; char * gfm_server_get_request(struct xxx_connection *client, char *diag, char *format, ...) { va_list ap; char *e; int eof; va_start(ap, format); e = xxx_proto_vrecv(client, 0, &eof, &format, &ap); va_end(ap); if (e != NULL) { gflog_warning(diag, e); return (e); } if (eof) { gflog_warning(diag, "missing RPC argument"); return (GFARM_ERR_PROTOCOL); } if (*format != '\0') gflog_fatal(diag, "invalid format character to get request"); return (NULL); } char * gfm_server_put_reply(struct xxx_connection *client, char *diag, int ecode, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_send(client, "i", (gfarm_int32_t)ecode); if (e != NULL) { gflog_warning(diag, e); return (e); } if (ecode == GFJ_ERROR_NOERROR) { e = xxx_proto_vsend(client, &format, &ap); if (e != NULL) { gflog_warning(diag, e); return (e); } } va_end(ap); if (ecode == 0 && *format != '\0') gflog_fatal(diag, "invalid format character to put reply"); return (NULL); } #define gfj_server_get_request gfm_server_get_request #define gfj_server_put_reply gfm_server_put_reply void gfarm_job_info_clear(struct gfarm_job_info *infos, int n) { memset(infos, 0, sizeof(struct gfarm_job_info) * n); } void gfarm_job_info_server_free_contents(struct gfarm_job_info *infos, int n) { int i, j; struct gfarm_job_info *info; for (i = 0; i < n; i++) { info = &infos[i]; /* * DO NOT free info->user on gfmd, * because it is shared with file_table[].user. * * if (info->user != NULL) * free(info->user); */ free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); for (j = 0; j < info->argc; j++) free(info->argv[j]); free(info->argv); for (j = 0; j < info->total_nodes; j++) free(info->nodes[j].hostname); free(info->nodes); } } struct job_table_entry { /* linked list of jobs which were registered by same file descriptor */ struct job_table_entry *next; int id; struct gfarm_job_info *info; }; #define JOB_ID_MIN 1 /* we won't use job id 0 */ int job_table_free = JOB_ID_MIN; int job_table_size = 2048; struct job_table_entry **job_table; void job_table_init(int table_size) { int i; job_table = malloc(sizeof(struct job_table_entry *) * table_size); if (job_table == NULL) { errno = ENOMEM; gflog_fatal_errno("job table"); } for (i = 0; i < table_size; i++) job_table[i] = NULL; job_table_size = table_size; } int job_table_add(struct gfarm_job_info *info, struct job_table_entry **listp) { int id; if (job_table_free >= job_table_size) { for (job_table_free = JOB_ID_MIN; job_table_free < job_table_size; job_table_free++) if (job_table[job_table_free] == NULL) break; if (job_table_free >= job_table_size) return (-1); } id = job_table_free; job_table[id] = malloc(sizeof(struct job_table_entry)); if (job_table[id] == NULL) return (-1); job_table[id]->id = id; job_table[id]->info = info; job_table[id]->next = *listp; *listp = job_table[id]; for (++job_table_free; job_table_free < job_table_size; ++job_table_free) if (job_table[job_table_free] == NULL) break; return (id); } int job_table_remove(int id, char *user, struct job_table_entry **listp) { struct job_table_entry **pp = listp; if (id >= job_table_size || job_table[id] == NULL) return (EBADF); if (strcmp(job_table[id]->info->user, user) != 0) return (EPERM); for (; *pp != NULL; pp = &(*pp)->next) if ((*pp)->id == id) break; if (*pp == NULL) /* cannot find the id on the list */ return (EBADF); /* assert(*pp == job_table[id]); */ *pp = job_table[id]->next; gfarm_job_info_server_free_contents(job_table[id]->info, 1); free(job_table[id]); job_table[id] = NULL; return (0); } struct file_table_entry { struct xxx_connection *conn; char *user, *host; struct job_table_entry *jobs; } *file_table; int file_table_size; int file_table_max = -1; void file_table_init(int table_size) { int i; file_table = malloc(sizeof(struct file_table_entry) * table_size); if (file_table == NULL) { errno = ENOMEM; gflog_fatal_errno("job table"); } for (i = 0; i < table_size; i++) { file_table[i].conn = NULL; file_table[i].user = NULL; file_table[i].jobs = NULL; } file_table_size = table_size; } int file_table_add(struct xxx_connection *client, char *username, char *hostname) { int fd = xxx_connection_fd(client); if (fd < 0) return (EINVAL); if (fd >= file_table_size) return (EMFILE); file_table[fd].conn = client; file_table[fd].user = username; file_table[fd].host = hostname; if (fd > file_table_max) file_table_max = fd; return (0); } int file_table_close(int fd) { static char m1[] = "("; static char m2[] = "@"; static char m3[] = ") disconnected"; char *msg; if (fd < 0 || fd >= file_table_size || file_table[fd].conn == NULL) return (EBADF); /* disconnect, do logging */ msg = malloc(sizeof(m1) - 1 + strlen(file_table[fd].user) + sizeof(m2) - 1 + strlen(file_table[fd].host) + sizeof(m3)); if (msg == NULL) { gflog_notice("(:@not enough memory) disconnected", file_table[fd].user); } else { sprintf(msg, "%s%s%s%s%s", m1, file_table[fd].user, m2, file_table[fd].host, m3); gflog_notice(msg, NULL); free(msg); } while (file_table[fd].jobs != NULL) job_table_remove(file_table[fd].jobs->id, file_table[fd].user, &file_table[fd].jobs); file_table[fd].jobs = NULL; free(file_table[fd].user); file_table[fd].user = NULL; free(file_table[fd].host); file_table[fd].host = NULL; xxx_connection_free(file_table[fd].conn); file_table[fd].conn = NULL; if (fd == file_table_max) { while (--file_table_max >= 0) if (file_table[file_table_max].conn != NULL) break; } return (0); } void file_table_fd_set(fd_set *set) { int fd; for (fd = 0; fd <= file_table_max; fd++) { if (file_table[fd].conn != NULL) FD_SET(fd, set); } } char * gfj_server_lock_register(struct xxx_connection *client) { /* XXX - NOT IMPLEMENTED */ return (gfj_server_put_reply(client, "lock_register", GFJ_ERROR_NOERROR, "")); } char * gfj_server_unlock_register(struct xxx_connection *client) { /* XXX - NOT IMPLEMENTED */ return (gfj_server_put_reply(client, "unlock_register", GFJ_ERROR_NOERROR, "")); } char * gfj_server_register(int client_socket) { struct xxx_connection *client = file_table[client_socket].conn; char *user = file_table[client_socket].user; char *e; int i, eof; gfarm_int32_t flags, total_nodes, argc, job_id, error; struct gfarm_job_info *info; info = malloc(sizeof(struct gfarm_job_info)); if (info == NULL) return (GFARM_ERR_NO_MEMORY); gfarm_job_info_clear(info, 1); e = gfj_server_get_request(client, "register", "iisssi", &flags, &total_nodes, &info->job_type, &info->originate_host, &info->gfarm_url_for_scheduling, &argc); if (e != NULL) return (e); /* XXX - currently `flags' is just igored */ info->total_nodes = total_nodes; info->argc = argc; info->argv = malloc(sizeof(char *) * (argc + 1)); info->nodes = malloc(sizeof(struct gfarm_job_node_info) * total_nodes); if (info->argv == NULL || info->nodes == NULL) { free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); if (info->argv != NULL) free(info->argv); if (info->nodes != NULL) free(info->nodes); free(info); return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < argc; i++) { e = xxx_proto_recv(client, 0, &eof, "s", &info->argv[i]); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_PROTOCOL; while (--i >= 0) free(info->argv[i]); free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); free(info->argv); free(info->nodes); return (e); } } info->argv[i] = NULL; info->user = user; /* shared with file_table[].user */ for (i = 0; i < total_nodes; i++) { e = xxx_proto_recv(client, 0, &eof, "s", &info->nodes[i].hostname); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_PROTOCOL; while (--i >= 0) free(info->nodes[i].hostname); for (i = 0; i < argc; i++) free(info->argv[i]); free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); free(info->argv); free(info->nodes); return (e); } info->nodes[i].pid = 0; info->nodes[i].state = GFJ_NODE_NONE; } job_id = job_table_add(info, &file_table[client_socket].jobs); if (job_id < JOB_ID_MIN) { job_id = 0; error = GFJ_ERROR_TOO_MANY_JOBS; } else { error = GFJ_ERROR_NOERROR; } return (gfj_server_put_reply(client, "register", error, "i", job_id)); } char * gfj_server_unregister(int client_socket) { struct xxx_connection *client = file_table[client_socket].conn; char *user = file_table[client_socket].user; char *e; gfarm_int32_t error; gfarm_int32_t job_id; e = gfj_server_get_request(client, "unregister", "i", &job_id); if (e != NULL) return (e); error = job_table_remove(job_id, user, &file_table[client_socket].jobs); return (gfj_server_put_reply(client, "unregister", error, "")); } char * gfj_server_register_node(struct xxx_connection *client) { /* XXX - NOT IMPLEMENTED */ gflog_fatal("register_node", "not implemented"); return (gfj_server_put_reply(client, "register_node", GFJ_ERROR_NOERROR, "")); } char * gfj_server_list(struct xxx_connection *client) { char *e, *user; int i; gfarm_int32_t n; e = gfj_server_get_request(client, "list", "s", &user); if (e != NULL) return (e); n = 0; for (i = 0; i < job_table_size; i++) { if (job_table[i] != NULL && (*user == '\0' || strcmp(user, job_table[i]->info->user) == 0)) n++; } e = gfj_server_put_reply(client, "register", GFJ_ERROR_NOERROR, "i", n); if (e != NULL) return (e); for (i = 0; i < job_table_size; i++) { if (job_table[i] != NULL && (*user == '\0' || strcmp(user, job_table[i]->info->user) == 0)) { e = xxx_proto_send(client, "i", (gfarm_int32_t)i); if (e != NULL) return (e); } } free(user); return (NULL); } char * gfj_server_put_info_entry(struct xxx_connection *client, struct gfarm_job_info *info) { char *e; int i; e = xxx_proto_send(client, "issssi", info->total_nodes, info->user, info->job_type, info->originate_host, info->gfarm_url_for_scheduling, info->argc); if (e != NULL) return (e); for (i = 0; i < info->argc; i++) { e = xxx_proto_send(client, "s", info->argv[i]); if (e != NULL) return (e); } for (i = 0; i < info->total_nodes; i++) { e = xxx_proto_send(client, "sii", info->nodes[i].hostname, info->nodes[i].pid, info->nodes[i].state); if (e != NULL) return (e); } return (NULL); } char * gfj_server_info(struct xxx_connection *client) { char *e; int i, eof; gfarm_int32_t n, *jobs; e = gfj_server_get_request(client, "info", "i", &n); if (e != NULL) return (e); jobs = malloc(sizeof(*jobs) * n); if (jobs == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < n; i++) { e = xxx_proto_recv(client, 0, &eof, "i", &jobs[i]); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_PROTOCOL; free(jobs); return (e); } } for (i = 0; i < n; i++) { if (jobs[i] < 0 || jobs[i] >= job_table_size || job_table[jobs[i]] == NULL) { e = gfj_server_put_reply(client, "info", GFJ_ERROR_NO_SUCH_OBJECT, ""); if (e != NULL) { free(jobs); return (e); } } else { e = gfj_server_put_reply(client, "info", GFJ_ERROR_NOERROR, ""); if (e != NULL) { free(jobs); return (e); } e = gfj_server_put_info_entry(client, job_table[jobs[i]]->info); if (e != NULL) { free(jobs); return (e); } } } free(jobs); return (NULL); } char * gfj_server_hostinfo(struct xxx_connection *client) { /* XXX - NOT IMPLEMENTED */ gflog_fatal("host_info", "not implemented"); return (gfj_server_put_reply(client, "host_info", GFJ_ERROR_NOERROR, "")); } void service(int client_socket) { struct xxx_connection *client; char *e; int eof; gfarm_int32_t request; char buffer[GFARM_INT32STRLEN]; client = file_table[client_socket].conn; e = xxx_proto_recv(client, 0, &eof, "i", &request); if (eof) { file_table_close(client_socket); return; } if (e != NULL) { gflog_warning("request number", e); return; } switch (request) { case GFJ_PROTO_LOCK_REGISTER: e = gfj_server_lock_register(client); break; case GFJ_PROTO_UNLOCK_REGISTER: e = gfj_server_unlock_register(client); break; case GFJ_PROTO_REGISTER: e = gfj_server_register(client_socket); break; case GFJ_PROTO_UNREGISTER: e = gfj_server_unregister(client_socket); break; case GFJ_PROTO_REGISTER_NODE: e = gfj_server_register_node(client); break; case GFJ_PROTO_LIST: e = gfj_server_list(client); break; case GFJ_PROTO_INFO: e = gfj_server_info(client); break; case GFJ_PROTO_HOSTINFO: e = gfj_server_hostinfo(client); break; default: sprintf(buffer, "%d", request); gflog_warning("unknown request", buffer); } if (e == NULL) e = xxx_proto_flush(client); if (e != NULL) file_table_close(client_socket); } void main_loop(int accepting_socket) { char *e, *username, *hostname; int max_fd, nfound, client_socket, fd; struct xxx_connection *client_conn; struct sockaddr_in client_addr; socklen_t client_addr_size; fd_set readable; /* * To deal with race condition which may be caused by RST, * listening socket must be O_NONBLOCK, if the socket will be * used as a file descriptor for select(2) . * See section 15.6 of "UNIX NETWORK PROGRAMMING, Volume1, * Second Edition" by <NAME>, for detail. * We do report such case by gflog_warning_errno("accept"); */ if (fcntl(accepting_socket, F_SETFL, fcntl(accepting_socket, F_GETFL, NULL) | O_NONBLOCK) == -1) gflog_warning_errno("accepting_socket O_NONBLOCK"); for (;;) { FD_ZERO(&readable); FD_SET(accepting_socket, &readable); file_table_fd_set(&readable); max_fd = file_table_max >= accepting_socket ? file_table_max : accepting_socket; nfound = select(max_fd + 1, &readable, NULL, NULL, 0); if (nfound <= 0) continue; if (FD_ISSET(accepting_socket, &readable)) { client_addr_size = sizeof(client_addr); client_socket = accept(accepting_socket, (struct sockaddr *)&client_addr, &client_addr_size); if (client_socket < 0) { if (errno != EINTR) gflog_warning_errno("accept"); } else if ((e = xxx_fd_connection_new(client_socket, &client_conn)) != NULL) { gflog_warning("fd_connection_new", e); close(client_socket); } else if ((e = gfarm_authorize(client_conn, 0, GFM_SERVICE_TAG, &username, &hostname, NULL)) != NULL) { gflog_warning("authorize", e); xxx_connection_free(client_conn); } else if ((errno = file_table_add(client_conn, username, hostname)) != 0) { gflog_warning_errno("file_table_add"); xxx_connection_free(client_conn); free(username); free(hostname); } else { int sockopt = 1; /* deal with reboots or network problems */ if (setsockopt(client_socket, SOL_SOCKET, SO_KEEPALIVE, &sockopt, sizeof(sockopt)) == -1) gflog_warning_errno("SO_KEEPALIVE"); } } for (fd = 0; fd <= file_table_max; fd++) { if (file_table[fd].conn != NULL && FD_ISSET(fd, &readable)) service(fd); } } } int open_accepting_socket(int port) { char *e; struct sockaddr_in self_addr; socklen_t self_addr_size; int sock, sockopt; memset(&self_addr, 0, sizeof(self_addr)); self_addr.sin_family = AF_INET; self_addr.sin_addr.s_addr = INADDR_ANY; self_addr.sin_port = htons(port); self_addr_size = sizeof(self_addr); sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) gflog_fatal_errno("accepting socket"); sockopt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) == -1) gflog_warning_errno("SO_REUSEADDR"); if (bind(sock, (struct sockaddr *)&self_addr, self_addr_size) < 0) gflog_fatal_errno("bind accepting socket"); e = gfarm_sockopt_apply_listener(sock); if (e != NULL) gflog_warning("setsockopt", e); if (listen(sock, LISTEN_BACKLOG) < 0) gflog_fatal_errno("listen"); return (sock); } void usage(void) { fprintf(stderr, "Usage: %s [option]\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-P <pid-file>\n"); fprintf(stderr, "\t-f <gfarm-configuration-file>\n"); fprintf(stderr, "\t-p <port>\n"); fprintf(stderr, "\t-s <syslog-facility>\n"); fprintf(stderr, "\t-v>\n"); exit(1); } int main(int argc, char **argv) { extern char *optarg; extern int optind; char *e, *config_file = NULL, *port_number = NULL, *pid_file = NULL; FILE *pid_fp = NULL; int syslog_facility = GFARM_DEFAULT_FACILITY; int ch, sock, table_size; if (argc >= 1) program_name = basename(argv[0]); gflog_set_identifier(program_name); while ((ch = getopt(argc, argv, "P:df:p:s:v")) != -1) { switch (ch) { case 'P': pid_file = optarg; break; case 'd': debug_mode = 1; break; case 'f': config_file = optarg; break; case 'p': port_number = optarg; break; case 's': syslog_facility = gflog_syslog_name_to_facility(optarg); if (syslog_facility == -1) gflog_fatal(optarg, "unknown syslog facility"); break; case 'v': gflog_auth_set_verbose(1); break; case '?': default: usage(); } } argc -= optind; argv += optind; if (config_file != NULL) gfarm_config_set_filename(config_file); e = gfarm_server_initialize(); if (e != NULL) { fprintf(stderr, "gfarm_server_initialize: %s\n", e); exit(1); } if (port_number != NULL) gfarm_metadb_server_port = strtol(port_number, NULL, 0); sock = open_accepting_socket(gfarm_metadb_server_port); if (pid_file != NULL) { /* * We do this before calling gfarm_daemon() * to print the error message to stderr. */ pid_fp = fopen(pid_file, "w"); if (pid_fp == NULL) gflog_fatal_errno(pid_file); } if (!debug_mode) { gflog_syslog_open(LOG_PID, syslog_facility); gfarm_daemon(0, 0); } if (pid_file != NULL) { /* * We do this after calling gfarm_daemon(), * because it changes pid. */ fprintf(pid_fp, "%ld\n", (long)getpid()); fclose(pid_fp); } table_size = GFMD_CONNECTION_LIMIT; gfarm_unlimit_nofiles(&table_size); if (table_size > GFMD_CONNECTION_LIMIT) table_size = GFMD_CONNECTION_LIMIT; file_table_init(table_size); job_table_init(table_size); /* * We don't want SIGPIPE, but want EPIPE on write(2)/close(2). */ signal(SIGPIPE, SIG_IGN); main_loop(sock); /*NOTREACHED*/ return (0); /* to shut up warning */ } <file_sep>/gfarm_zabbix/trunk/src/clean.sh #! /bin/sh find . -name \*.in -type f -print | while read IN_FILE; do FILE=`echo "X$IN_FILE" | sed -e 's|^X||' -e 's|\.in$||'` [ -f $FILE ] && rm -f $FILE done <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/libgfarm/gfutil/timer.h /* * $Id$ * * TIMER routine */ #ifdef i386 typedef unsigned long long gfarm_timerval_t; extern double gfarm_timerval_calibration; unsigned long long gfarm_get_cycles(void); #define gfarm_gettimerval(tp) (*(tp) = gfarm_get_cycles()) #define gfarm_timerval_second(tp) (*(tp) * gfarm_timerval_calibration) #define gfarm_timerval_sub(t1p, t2p) \ ((*(t1p) - *(t2p)) * gfarm_timerval_calibration) #else /* gettimeofday */ typedef struct timeval gfarm_timerval_t; #define gfarm_gettimerval(t1) gettimeofday(t1, NULL) #define gfarm_timerval_second(t1) \ ((double)(t1)->tv_sec + (double)(t1)->tv_usec * .000001) #define gfarm_timerval_sub(t1, t2) \ (((double)(t1)->tv_sec - (double)(t2)->tv_sec) \ + ((double)(t1)->tv_usec - (double)(t2)->tv_usec) * .000001) #endif void gfarm_timerval_calibrate(void); <file_sep>/gfarm/tags/gfarm_1_0_beta_4/lib/libgfarm/gfutil/gfevent.c #include <stdio.h> /* XXX implement, poll, /dev/poll, kqueue and epoll version */ #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <assert.h> #include <limits.h> /* CHAR_BIT */ #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include "gfutil.h" #include "gfevent.h" /* select(2) */ #ifndef howmany #define howmany(x, y) (((x) + ((y) - 1)) / (y)) #endif #define MIN_FDS_SIZE FD_SETSIZE /* event */ struct gfarm_event { /* doubly linked circular list with a header */ struct gfarm_event *next, *prev; int filter; void *closure; struct timeval timeout; int timeout_specified; enum { GFARM_FD_EVENT, GFARM_TIMER_EVENT } type; union { struct gfarm_fd_event { void (*callback)(int, int, void *, const struct timeval *); int fd; } fd; struct gfarm_timer_event { void (*callback)(void *, const struct timeval *); } timeout; } u; }; struct gfarm_event * gfarm_fd_event_alloc(int filter, int fd, void (*callback)(int, int, void *, const struct timeval *), void *closure) { struct gfarm_event *ev = malloc(sizeof(*ev)); if (ev == NULL) return (NULL); ev->next = ev->prev = NULL; /* to be sure */ ev->type = GFARM_FD_EVENT; ev->filter = filter; ev->closure = closure; ev->u.fd.callback = callback; ev->u.fd.fd = fd; return (ev); } void gfarm_fd_event_set_callback(struct gfarm_event * ev, void (*callback)(int, int, void *, const struct timeval *), void *closure) { ev->closure = closure; ev->u.fd.callback = callback; } struct gfarm_event * gfarm_timer_event_alloc( void (*callback)(void *, const struct timeval *), void *closure) { struct gfarm_event *ev = malloc(sizeof(*ev)); if (ev == NULL) return (NULL); ev->next = ev->prev = NULL; /* to be sure */ ev->type = GFARM_TIMER_EVENT; ev->filter = GFARM_EVENT_TIMEOUT; ev->closure = closure; ev->u.timeout.callback = callback; return (ev); } void gfarm_timer_event_set_callback(struct gfarm_event *ev, void (*callback)(void *, const struct timeval *), void *closure) { ev->closure = closure; ev->u.timeout.callback = callback; } void gfarm_event_free(struct gfarm_event *ev) { free(ev); } /* event queue */ struct gfarm_eventqueue { /* doubly linked circular list with a header */ struct gfarm_event header; int fd_set_size, fd_set_bytes; fd_set *read_fd_set, *write_fd_set, *exception_fd_set; }; struct gfarm_eventqueue * gfarm_eventqueue_alloc(void) { struct gfarm_eventqueue *q = malloc(sizeof(*q)); if (q == NULL) return (NULL); /* make the queue empty */ q->header.next = q->header.prev = &q->header; q->fd_set_size = q->fd_set_bytes = 0; q->read_fd_set = q->write_fd_set = q->exception_fd_set = NULL; return (q); } void gfarm_eventqueue_free(struct gfarm_eventqueue *q) { if (q->read_fd_set != NULL) free(q->read_fd_set); if (q->write_fd_set != NULL) free(q->write_fd_set); if (q->exception_fd_set != NULL) free(q->exception_fd_set); #if 0 /* this may not be true, if gfarm_eventqueue_loop() fails */ /* assert that the queue is empty */ assert(q->header.next == &q->header && q->header.prev == &q->header); #endif free(q); } /* * XXX This is not so portable, * but fixed-size fd_set cannot be used. */ static int gfarm_eventqueue_realloc_fd_set(size_t fds_bytes, fd_set **fd_setpp) { fd_set *fsp; if (*fd_setpp != NULL) { fsp = realloc(*fd_setpp, fds_bytes); if (fsp == NULL) return (0); /* failure */ *fd_setpp = fsp; } return (1); /* success */ } static int gfarm_eventqueue_alloc_fd_set(struct gfarm_eventqueue *q, int fd, fd_set **fd_setpp) { fd_set *fsp; if (fd >= q->fd_set_size) { size_t fds_size, fds_array_length, fds_bytes; fds_size = q->fd_set_size > 0 ? q->fd_set_size : MIN_FDS_SIZE; for (; fd >= fds_size; fds_size += fds_size) ; fds_array_length = howmany(fds_size, sizeof(fsp->fds_bits[0]) * CHAR_BIT); fds_bytes = fds_array_length * sizeof(fsp->fds_bits[0]); if (!gfarm_eventqueue_realloc_fd_set(fds_bytes, &q->read_fd_set)) return (0); /* failure */ if (!gfarm_eventqueue_realloc_fd_set(fds_bytes, &q->write_fd_set)) /* XXX wastes q->read_fd_set_value */ return (0); /* failure */ if (!gfarm_eventqueue_realloc_fd_set(fds_bytes, &q->exception_fd_set))/*XXX wastes q->{r,w}*_fd_set_value*/ return (0); /* failure */ q->fd_set_bytes = fds_bytes; q->fd_set_size = fds_bytes * CHAR_BIT; } if (*fd_setpp == NULL) { /* * XXX This is not so portable, * but fixed-size fd_set cannot be used. */ *fd_setpp = malloc(q->fd_set_bytes); if (*fd_setpp == NULL) return (0); /* failure */ } return (1); /* success */ } int gfarm_eventqueue_add_event(struct gfarm_eventqueue *q, struct gfarm_event *ev, const struct timeval *timeout) { if (ev->next != NULL || ev->prev != NULL) /* shouldn't happen */ return (EINVAL); if (timeout == NULL) { ev->timeout_specified = 0; } else if ((ev->filter & GFARM_EVENT_TIMEOUT) != 0) { ev->timeout_specified = 1; gettimeofday(&ev->timeout, NULL); gfarm_timeval_add(&ev->timeout, timeout); } else { /* * if the event is not allocated with GFARM_EVENT_TIMEOUT, * it's not allowed to specify a timeout. */ return (EINVAL); } switch (ev->type) { case GFARM_FD_EVENT: if ((ev->filter & GFARM_EVENT_READ) != 0) { if (!gfarm_eventqueue_alloc_fd_set(q, ev->u.fd.fd, &q->read_fd_set)) return (ENOMEM); } if ((ev->filter & GFARM_EVENT_WRITE) != 0) { if (!gfarm_eventqueue_alloc_fd_set(q, ev->u.fd.fd, &q->write_fd_set)) return (ENOMEM); } if ((ev->filter & GFARM_EVENT_EXCEPTION) != 0) { if (!gfarm_eventqueue_alloc_fd_set(q, ev->u.fd.fd, &q->exception_fd_set)) return (ENOMEM); } break; case GFARM_TIMER_EVENT: if (timeout == NULL) return (EINVAL); /* not allowed */ break; } /* enqueue - insert at the tail of the circular list */ ev->next = &q->header; ev->prev = q->header.prev; q->header.prev->next = ev; q->header.prev = ev; return (0); } int gfarm_eventqueue_delete_event(struct gfarm_eventqueue *q, struct gfarm_event *ev) { if (ev->next == NULL || ev->prev == NULL) /* shouldn't happen */ return (EINVAL); /* dequeue */ ev->next->prev = ev->prev; ev->prev->next = ev->next; ev->next = ev->prev = NULL; /* to be sure */ return (0); } /* * run one turn of select(2) loop. * this function may return before the timeout. * * RETURN VALUE: * 0: All events are processed, and no event is remaining in the queue. * EAGAIN: There are still pending events. * EDEADLK: no watching file descriptor is requested, and any timer event * isn't specified, either. This means infinite sleep. * otherwise: select(2) failed, return value shows the `errno' of * the select(2). */ int gfarm_eventqueue_turn(struct gfarm_eventqueue *q, const struct timeval *timeo) { int nfound, max_fd = -1; struct gfarm_event *ev, *n; fd_set *read_fd_set, *write_fd_set, *exception_fd_set; struct timeval start_time, end_time, timeout_value, *timeout = NULL; int events; /* queue is empty? */ if (q->header.next == &q->header) return (0); /* finished */ /* * prepare arguments for select(2) */ if (timeo != NULL) { timeout_value = *timeo; timeout = &timeout_value; } /* * XXX This is not so portable, * but usual implementation of FD_ZERO cannot be used. */ if (q->read_fd_set != NULL) memset(q->read_fd_set, 0, q->fd_set_bytes); if (q->write_fd_set != NULL) memset(q->write_fd_set, 0, q->fd_set_bytes); if (q->exception_fd_set != NULL) memset(q->exception_fd_set, 0, q->fd_set_bytes); read_fd_set = write_fd_set = exception_fd_set = NULL; for (ev = q->header.next; ev != &q->header; ev = ev->next) { if (ev->timeout_specified) { if (timeout == NULL) { timeout = &timeout_value; timeout_value = ev->timeout; } else if (gfarm_timeval_cmp(&ev->timeout,timeout) <0){ timeout_value = ev->timeout; } } switch (ev->type) { case GFARM_FD_EVENT: if ((ev->filter & GFARM_EVENT_READ) != 0) { read_fd_set = q->read_fd_set; FD_SET(ev->u.fd.fd, read_fd_set); } if ((ev->filter & GFARM_EVENT_WRITE) != 0) { write_fd_set = q->write_fd_set; FD_SET(ev->u.fd.fd, write_fd_set); } if ((ev->filter & GFARM_EVENT_EXCEPTION) != 0) { exception_fd_set = q->exception_fd_set; FD_SET(ev->u.fd.fd, exception_fd_set); } if (ev->u.fd.fd > max_fd) max_fd = ev->u.fd.fd; break; case GFARM_TIMER_EVENT: break; } } /* * do select(2) */ if (max_fd < 0 && timeout == NULL) return (EDEADLK); /* infinite sleep without any watching fd */ gettimeofday(&start_time, NULL); if (timeout != NULL) { gfarm_timeval_sub(&timeout_value, &start_time); if (timeout_value.tv_sec < 0) timeout_value.tv_sec = timeout_value.tv_usec = 0; } nfound = select(max_fd + 1, read_fd_set, write_fd_set, exception_fd_set, timeout); if (nfound == -1) return (errno); gettimeofday(&end_time, NULL); /* * call event callback routines */ for (ev = q->header.next; ev != &q->header; ev = n) { /* * We shouldn't use "ev = ev->next" in the 3rd clause * of above "for(;;)" statement, because ev may be * deleted in this loop. */ n = ev->next; switch (ev->type) { case GFARM_FD_EVENT: events = 0; if ((ev->filter & GFARM_EVENT_READ) != 0 && FD_ISSET(ev->u.fd.fd, q->read_fd_set)) events |= GFARM_EVENT_READ; if ((ev->filter & GFARM_EVENT_WRITE) != 0 && FD_ISSET(ev->u.fd.fd, q->write_fd_set)) events |= GFARM_EVENT_WRITE; if ((ev->filter & GFARM_EVENT_EXCEPTION) != 0 && FD_ISSET(ev->u.fd.fd, q->exception_fd_set)) events |= GFARM_EVENT_EXCEPTION; if (events != 0) { gfarm_eventqueue_delete_event(q, ev); /* here is a good breakpoint on a debugger */ (*ev->u.fd.callback)(events, ev->u.fd.fd, ev->closure, &end_time); } else if (ev->timeout_specified && gfarm_timeval_cmp(&end_time, &ev->timeout) >= 0) { gfarm_eventqueue_delete_event(q, ev); (*ev->u.fd.callback)( GFARM_EVENT_TIMEOUT, ev->u.fd.fd, ev->closure, &end_time); } break; case GFARM_TIMER_EVENT: if (gfarm_timeval_cmp(&end_time, &ev->timeout) >= 0){ gfarm_eventqueue_delete_event(q, ev); (*ev->u.timeout.callback)( ev->closure, &end_time); } break; } } /* queue is empty? */ if (q->header.next == &q->header) return (0); /* finished */ return (EAGAIN); } /* * run whole select(2) loop. * * RETURN VALUE: * 0: All events are processed, and no event is remaining in the queue. * EDEADLK: no watching file descriptor is requested, and any timer event * isn't specified, either. This means infinite sleep. * ETIMEDOUT: timeout happened. * otherwise: select(2) failed, return value shows the `errno' of * the select(2). */ int gfarm_eventqueue_loop(struct gfarm_eventqueue *q, const struct timeval *timeo) { struct timeval limit, now, timeout_value, *timeout = NULL; int rv; if (timeo != NULL) { gettimeofday(&limit, NULL); gfarm_timeval_add(&limit, timeo); now = limit; timeout = &timeout_value; } for (;;) { if (timeout != NULL) { *timeout = limit; gfarm_timeval_sub(timeout, &now); } rv = gfarm_eventqueue_turn(q, timeout); if (rv == 0) return (0); /* completed */ if (rv != EAGAIN && rv != EINTR) return (rv); /* probably program logic is wrong */ if (timeout != NULL) { gettimeofday(&now, NULL); if (gfarm_timeval_cmp(&now, &limit) >= 0) return (ETIMEDOUT); /* timeout */ } } } #if 0 /* sample usage */ #include <stdio.h> struct proto1_state { struct gfarm_eventqueue *q; int sock; struct gfarm_event *writable, *readable; void (*continuation)(void *); void *closure; /* results */ int error; unsigned char result; }; void proto1_receiving(int events, int fd, void *closure, const struct timeval *t) { struct proto1_state *state = closure; int rv; rv = read(state->sock, &state->result, sizeof(state->result)); if (rv == -1) { if (errno != EINTR && errno != EAGAIN) state->error = errno; else if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, NULL)) != 0) { state->error = rv; } } if (state->continuation != NULL) (*state->continuation)(state->closure); } void proto1_sending(int events, int fd, void *closure, const struct timeval *t) { struct proto1_state *state = closure; unsigned char request_code = 1; int rv; rv = write(state->sock, &request_code, sizeof(request_code)); if (rv == -1) { if (errno != EINTR && errno != EAGAIN) { state->error = errno; } else if ((rv = gfarm_eventqueue_add_event(state->q, state->writable, NULL)) != 0) { state->error = rv; } else { return; /* go to proto1_sending() */ } } else { if ((rv = gfarm_eventqueue_add_event(state->q, state->readable, NULL)) == 0) { return; /* go to proto1_receiving() */ } state->error = rv; } if (state->continuation != NULL) (*state->continuation)(state->closure); } int proto1_request_multiplexed(struct gfarm_eventqueue *q, int peer_socket, void (*continuation)(void *), void *closure, struct proto1_state **statepp) { struct proto1_state *state = malloc(sizeof(*state)); int rv = ENOMEM; if (state == NULL) return (ENOMEM); state->writable = gfarm_fd_event_alloc(GFARM_EVENT_WRITE, peer_socket, proto1_sending, state); if (state->writable != NULL) { state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ, peer_socket, proto1_receiving, state); if (state->readable != NULL) { state->q = q; state->sock = peer_socket; state->continuation = continuation; state->closure = closure; state->error = 0; rv = gfarm_eventqueue_add_event(q, state->writable, NULL); if (rv == 0) { *statepp = state; return (0); /* go to proto1_sending() */ } gfarm_event_free(state->readable); } gfarm_event_free(state->writable); } free(state); return (rv); } int proto1_result_multiplexed(struct proto1_state *state, unsigned char *resultp) { int error = state->error; if (error == 0) *resultp = state->result; gfarm_event_free(state->readable); gfarm_event_free(state->writable); free(state); return (error); } struct p1_finalize_closure { char *name; struct proto1_state *state; }; void p1_finalize(void *closure) { struct p1_finalize_closure *p1 = closure; unsigned char result; int error = proto1_result_multiplexed(p1->state, &result); if (error != 0) fprintf(stderr, "%s: error = %s\n", p1->name, strerror(error)); else printf("%s: result=%c\n", p1->name, result); } void run2(int host1_socket, int host2_socket) { int error; struct gfarm_eventqueue *q; struct p1_finalize_closure fc1, fc2; /* initialize */ if ((q = gfarm_eventqueue_alloc()) == NULL) { fprintf(stderr, "out of memory\n"); return; } fc1.name = "host1"; fc1.state = NULL; error = proto1_request_multiplexed(q, host1_socket, p1_finalize, &fc1, &fc1.state); if (error != 0) fprintf(stderr, "host1: %s\n", strerror(error)); fc2.name = "host2"; fc2.state = NULL; error = proto1_request_multiplexed(q, host2_socket, p1_finalize, &fc2, &fc2.state); if (error != 0) fprintf(stderr, "host2: %s\n", strerror(error)); /* run */ error = gfarm_eventqueue_loop(q, NULL); if (error != 0) fprintf(stderr, "host2: %s\n", strerror(error)); /* terminate */ gfarm_eventqueue_free(q); } #endif /* sample usage */ <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/lib/libgfarm/gfarm/auth_client_gsi.c #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <sys/time.h> #include <gssapi.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "gfevent.h" #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include "xxx_proto.h" #include "io_fd.h" #include "io_gfsl.h" #include "auth.h" #define GFSL_CONF_USERMAP "/etc/grid-security/grid-mapfile" gss_cred_id_t gfarm_gsi_get_delegated_cred(); /* XXX */ static int gsi_initialized; static int gsi_server_initialized; static char *gsi_client_cred_name; char * gfarm_gsi_client_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) return (NULL); rv = gfarmSecSessionInitializeInitiator(NULL, &e_major, &e_minor); if (rv <= 0) { if (gfarm_authentication_verbose) { gflog_error( "can't initialize as initiator because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeInitiator(); return ("GSI credential initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 0; gsi_client_cred_name = gfarmSecSessionGetInitiatorCredName(); return (NULL); } char * gfarm_gsi_client_cred_name(void) { return (gsi_client_cred_name); } char * gfarm_gsi_server_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) { if (gsi_server_initialized) return (NULL); gfarmSecSessionFinalizeInitiator(); gsi_initialized = 0; } rv = gfarmSecSessionInitializeBoth(NULL, NULL, GFSL_CONF_USERMAP, &e_major, &e_minor); if (rv <= 0) { if (gfarm_authentication_verbose) { gflog_error( "can't initialize GSI as both because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeBoth(); return ("GSI initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 1; return (NULL); } char * gfarm_auth_request_gsi(struct xxx_connection *conn) { int fd = xxx_connection_fd(conn); char *e; OM_uint32 e_major; OM_uint32 e_minor; gfarmSecSession *session; gfarm_int32_t error; /* enum gfarm_auth_error */ int eof; e = gfarm_gsi_client_initialize(); if (e != NULL) return (e); session = gfarmSecSessionInitiate(fd, gfarm_gsi_get_delegated_cred(), NULL, &e_major, &e_minor); if (session == NULL) { if (gfarm_authentication_verbose) { gflog_error("Can't initiate session because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } return (GFARM_ERR_AUTHENTICATION); } xxx_connection_set_secsession(conn, session); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL || eof || error != GFARM_AUTH_ERROR_NO_ERROR) { xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); return (e != NULL ? e : eof ? GFARM_ERR_PROTOCOL : GFARM_ERR_AUTHENTICATION); } return (NULL); } /* * multiplexed version of gfarm_auth_request_gsi() for parallel authentication */ struct gfarm_auth_request_gsi_state { struct gfarm_eventqueue *q; struct gfarm_event *readable; struct xxx_connection *conn; void (*continuation)(void *); void *closure; struct gfarmSecSessionInitiateState *gfsl_state; gfarmSecSession *session; /* results */ char *error; }; static void gfarm_auth_request_gsi_receive_result(int events, int fd, void *closure, const struct timeval *t) { struct gfarm_auth_request_gsi_state *state = closure; int eof; gfarm_int32_t error; /* enum gfarm_auth_error */ if ((events & GFARM_EVENT_TIMEOUT) != 0) { assert(events == GFARM_EVENT_TIMEOUT); state->error = GFARM_ERR_CONNECTION_TIMED_OUT; if (state->continuation != NULL) (*state->continuation)(state->closure); return; } assert(events == GFARM_EVENT_READ); state->error = xxx_proto_recv(state->conn, 1, &eof, "i", &error); if (state->error == NULL && eof) state->error = GFARM_ERR_PROTOCOL; if (state->error == NULL && error != GFARM_AUTH_ERROR_NO_ERROR) state->error = GFARM_ERR_AUTHENTICATION; if (state->error != NULL) { xxx_connection_reset_secsession(state->conn); xxx_connection_set_fd(state->conn, fd); } if (state->continuation != NULL) (*state->continuation)(state->closure); } static void gfarm_auth_request_gsi_wait_result(void *closure) { struct gfarm_auth_request_gsi_state *state = closure; OM_uint32 e_major, e_minor; int rv; struct timeval timeout; state->session = gfarmSecSessionInitiateResult(state->gfsl_state, &e_major, &e_minor); if (state->session == NULL) { /* XXX e_major/e_minor should be used */ state->error = GFARM_ERR_AUTHENTICATION; } else { timeout.tv_sec = GFARM_AUTH_TIMEOUT; timeout.tv_usec = 0; rv = gfarm_eventqueue_add_event(state->q, state->readable, &timeout); if (rv == 0) { xxx_connection_set_secsession(state->conn, state->session); /* go to gfarm_auth_request_gsi_receive_result() */ return; } state->error = gfarm_errno_to_error(rv); } if (state->continuation != NULL) (*state->continuation)(state->closure); } char * gfarm_auth_request_gsi_multiplexed(struct gfarm_eventqueue *q, struct xxx_connection *conn, void (*continuation)(void *), void *closure, void **statepp) { char *e; struct gfarm_auth_request_gsi_state *state; OM_uint32 e_major, e_minor; e = gfarm_gsi_client_initialize(); if (e != NULL) return (e); state = malloc(sizeof(*state)); if (state == NULL) return (GFARM_ERR_NO_MEMORY); /* * We cannot use two independent events (i.e. a fd_event with * GFARM_EVENT_READ flag and a timer_event) here, because * it's possible that both event handlers are called at once. */ state->readable = gfarm_fd_event_alloc( GFARM_EVENT_READ|GFARM_EVENT_TIMEOUT, xxx_connection_fd(conn), gfarm_auth_request_gsi_receive_result, state); if (state->readable == NULL) { e = GFARM_ERR_NO_MEMORY; goto error_free_state; } state->gfsl_state = gfarmSecSessionInitiateRequest(q, xxx_connection_fd(conn), gfarm_gsi_get_delegated_cred(), NULL, gfarm_auth_request_gsi_wait_result, state, &e_major, &e_minor); if (state->gfsl_state == NULL) { /* XXX e_major/e_minor should be used */ e = "cannote initiate GSI connection"; goto error_free_readable; } state->q = q; state->conn = conn; state->continuation = continuation; state->closure = closure; state->error = NULL; *statepp = state; return (NULL); error_free_readable: gfarm_event_free(state->readable); error_free_state: free(state); return (e); } char * gfarm_auth_result_gsi_multiplexed(void *sp) { struct gfarm_auth_request_gsi_state *state = sp; char *e = state->error; gfarm_event_free(state->readable); free(state); return (e); } /* * "gsi_auth" method */ char * gfarm_auth_request_gsi_auth(struct xxx_connection *conn) { char *e = gfarm_auth_request_gsi(conn); if (e == NULL) xxx_connection_downgrade_to_insecure_session(conn); return (e); } char * gfarm_auth_request_gsi_auth_multiplexed(struct gfarm_eventqueue *q, struct xxx_connection *conn, void (*continuation)(void *), void *closure, void **statepp) { return (gfarm_auth_request_gsi_multiplexed(q, conn, continuation, closure, statepp)); } char * gfarm_auth_result_gsi_auth_multiplexed(void *sp) { struct gfarm_auth_request_gsi_state *state = sp; /* sp will be free'ed in gfarm_auth_result_gsi_multiplexed(). * state->conn should be saved before calling it. */ struct xxx_connection *conn = state->conn; char *e = gfarm_auth_result_gsi_multiplexed(sp); if (e == NULL) xxx_connection_downgrade_to_insecure_session(conn); return (e); } <file_sep>/gfarmfs-fuse/trunk/test/expected/freebsd/Makefile.am EXTRA_DIST = \ fusexmp_fh_defperm.out \ fusexmp_fh_direct_io.out \ fusexmp_fh_kernel_cache.out \ fusexmp_fh.out \ fusexmp_fh_s.out \ fusexmp.out \ gfarmfs_b_direct_io.out \ gfarmfs_b.out \ gfarmfs_defperm.out \ gfarmfs_direct_io.out \ gfarmfs_N2.out \ gfarmfs_nlsu.out \ gfarmfs_noopt.out \ gfarmfs_attr0.out \ gfarmfs_oldio.out \ gfarmfs_oldio_b.out \ gfarmfs_oldio_F.out \ slashtmp.out <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/debian/rules #!/usr/bin/make -f # Sample debian/rules that uses debhelper. # GNU copyright 1997 by <NAME>. # # This version is for a hypothetical package that builds an # architecture-dependant package, as well as an architecture-independent # package. # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 # This is the debhelper compatability version to use. export DH_COMPAT=2 # This has to be exported to make some magic below work. export DH_OPTIONS export CC=gcc CLIENT_PKG = gfarm-client GFRONT_PKG = gfarm-gfront DOC_PKG = gfarm-doc GFPTOOL_PKG = gfarm-gfptool GFARMD_PKG = gfarmd GFMD_PKG = gfmd GFSD_PKG=gfsd LIBGFARM_DEV_PKG = libgfarm-dev CLIENT_GSI_PKG = gfarm-gsi-client GFPTOOL_GSI_PKG = gfarm-gsi-gfptool GFMD_GSI_PKG = gfmd-gsi GFSD_GSI_PKG=gfsd-gsi DEV_GSI_PKG = libgfarm-gsi-dev GFARM_GFPTOOL_MAN1=gfgrep.1 GFMD_MAN8=gfmd.8 GFARM_CLIENT_MAN1=digest.1 gfexport.1 gfimport_fixed.1 gfimport_text.1 gfkey.1 gfmpirun_p4.1 gfps.1 gfrcmd.1 gfreg.1 gfrep.1 gfrm.1 gfrsh.1 gfrun.1 gfsched.1 gfssh.1 gfstat.1 gfwhere.1 gfwhoami.1 gfhost.1 gfls.1 gfcd.1 gfmkdir.1 gfpwd.1 gfrmdir.1 gfsetdir.1 GFRONT_MAN1=gfront.1 GFSD_MAN1=gfexec.1 GFSD_MAN8=gfsd.8 LIBGFARM_DEV_MAN3=gfarm_initialize.3 gfarm_strings_free_deeply.3 gfarm_terminate.3 gfarm_url_hosts_schedule.3 gfs_chdir.3 gfs_chmod.3 gfs_closedir.3 gfs_opendir.3 gfs_glob.3 gfs_glob_add.3 gfs_glob_free.3 gfs_glob_init.3 gfs_pio_close.3 gfs_pio_create.3 gfs_pio_eof.3 gfs_pio_error.3 gfs_pio_flush.3 gfs_pio_getc.3 gfs_pio_getline.3 gfs_pio_gets.3 gfs_pio_open.3 gfs_pio_putc.3 gfs_pio_putline.3 gfs_pio_puts.3 gfs_pio_read.3 gfs_pio_readdelim.3 gfs_pio_readline.3 gfs_pio_seek.3 gfs_pio_set_local.3 gfs_pio_set_view_index.3 gfs_pio_set_view_local.3 gfs_pio_ungetc.3 gfs_pio_write.3 gfs_readdir.3 gfs_stat.3 gfs_stat_free.3 gfs_unlink.3 gfs_utimes.3 CONFIGURE = ../configure --srcdir=$(PWD) --with-openldap=/usr --with-mpi=/usr --prefix=/usr --libexecdir=/usr/lib/gfarm configure: configure-stamp configure-stamp: dh_testdir # Add here commands to configure the package. -rm -rf ns/ install -d build && cd build && $(CONFIGURE) install -d build_gsi && cd build_gsi && $(CONFIGURE) --with-globus=/usr/grid --with-globus-flavor=gcc32dbg ln -s $(CLIENT_PKG).install debian/$(CLIENT_GSI_PKG).install ln -s $(GFPTOOL_PKG).install debian/$(GFPTOOL_GSI_PKG).install ln -s $(GFMD_PKG).install debian/$(GFMD_GSI_PKG).install ln -s $(GFSD_PKG).install debian/$(GFSD_GSI_PKG).install ln -s $(LIBGFARM_DEV_PKG).install debian/$(DEV_GSI_PKG).install ln -s $(GFMD_PKG).conffiles debian/$(GFMD_GSI_PKG).conffiles ln -s $(GFSD_PKG).conffiles debian/$(GFSD_GSI_PKG).conffiles ln -s $(CLIENT_PKG).manpages debian/$(CLIENT_GSI_PKG).manpages ln -s $(GFPTOOL_PKG).manpages debian/$(GFPTOOL_GSI_PKG).manpages ln -s $(GFMD_PKG).manpages debian/$(GFMD_GSI_PKG).manpages ln -s $(GFSD_PKG).manpages debian/$(GFSD_GSI_PKG).manpages ln -s $(LIBGFARM_DEV_PKG).manpages debian/$(DEV_GSI_PKG).manpages touch configure-stamp build: configure-stamp build-stamp build-stamp: dh_testdir # Add here commands to compile the package. cd build && $(MAKE) cd build_gsi && $(MAKE) touch build-stamp clean: dh_testdir dh_testroot rm -f build-stamp # Add here commands to clean up after the build process. # -cd build && $(MAKE) distclean # -cd build_gsi && $(MAKE) distclean -rm -f configure-stamp -rm -rf build build_gsi find . -name '*.o' -o -name '_libs' -o -name '*.lo' -o -name '*.a' -o -name '.deps' | xargs rm -rf -rm -rf debian/tmp_gsi debian/tmp_nogsi rm -f debian/$(CLIENT_GSI_PKG).install rm -f debian/$(GFPTOOL_GSI_PKG).install rm -f debian/$(GFMD_GSI_PKG).install rm -f debian/$(GFSD_GSI_PKG).install rm -f debian/$(DEV_GSI_PKG).install rm -f debian/$(GFMD_GSI_PKG).conffiles rm -f debian/$(GFSD_GSI_PKG).conffiles rm -f debian/$(CLIENT_GSI_PKG).manpages rm -f debian/$(GFPTOOL_GSI_PKG).manpages rm -f debian/$(GFMD_GSI_PKG).manpages rm -f debian/$(GFSD_GSI_PKG).manpages rm -f debian/$(DEV_GSI_PKG).manpages #### FIEXME rm -f debian/gf{s,m}d-gsi.p* dh_clean install: DH_OPTIONS= install: build dh_testdir dh_testroot dh_clean -k dh_installdirs # Add here commands to install the package into debian/tmp. cd build && $(MAKE) install prefix=`pwd`/../debian/tmp/usr \ default_libexecdir=`pwd`/../debian/tmp/usr/lib/gfarm cd build_gsi && $(MAKE) install prefix=`pwd`/../debian/tmp_gsi/usr \ default_libexecdir=`pwd`/../debian/tmp_gsi/usr/lib/gfarm rm -f debian/tmp/usr/share/doc/gfarm/LICENSE mv debian/tmp/usr/share/doc/gfarm debian/tmp/usr/share/doc/gfarm-doc # for tmp_dir in tmp tmp_gsi; do \ # install -d debian/$$tmp_dir/usr/lib/gfarm/; \ # mv debian/$$tmp_dir/usr/libexec/* debian/$$tmp_dir/usr/lib/gfarm/; \ # done # hoax gfarm's Makefile. for tmp_dir in tmp tmp_gsi; do \ install -d debian/$$tmp_dir/etc/init.d/; \ install -m 444 doc/conf/gfarm.conf debian/$$tmp_dir/etc/; \ install -d debian/$$tmp_dir/usr/share/doc/gfarm/; \ install debian/gfsd.init debian/$$tmp_dir/etc/init.d/; \ mv debian/$$tmp_dir/etc/init.d/gfsd.init debian/$$tmp_dir/etc/init.d/gfsd; \ install debian/gfmd.init debian/$$tmp_dir/etc/init.d/; \ mv debian/$$tmp_dir/etc/init.d/gfmd.init debian/$$tmp_dir/etc/init.d/gfmd; \ done dh_install -p$(CLIENT_PKG) dh_install -p$(GFRONT_PKG) dh_install -p$(DOC_PKG) dh_install -p$(GFPTOOL_PKG) dh_install -p$(GFMD_PKG) dh_install -p$(GFSD_PKG) dh_install -p$(LIBGFARM_DEV_PKG) mv debian/tmp debian/tmp_nogsi mv debian/tmp_gsi debian/tmp dh_install -p$(CLIENT_GSI_PKG) dh_install -p$(GFPTOOL_GSI_PKG) dh_install -p$(GFMD_GSI_PKG) dh_install -p$(GFSD_GSI_PKG) dh_install -p$(DEV_GSI_PKG) # -dh_movefiles # Build architecture-independent files here. # Pass -i to all debhelper commands in this target to reduce clutter. binary-indep: DH_OPTIONS=-i binary-indep: build install # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir dh_testroot # dh_installdebconf dh_installdocs dh_installexamples # dh_installmenu # dh_installemacsen # dh_installpam # dh_installinit # dh_installcron # dh_installmanpages # dh_installinfo # dh_undocumented dh_installchangelogs dh_link dh_compress dh_fixperms # You may want to make some executables suid here. # dh_suidregister dh_installdeb # dh_perl dh_gencontrol dh_md5sums dh_builddeb # Build architecture-dependent files here. # Pass -a to all debhelper commands in this target to reduce clutter. # binary-arch: DH_OPTIONS=-a binary-arch: build install # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir dh_testroot # dh_installdebconf dh_installdocs dh_installexamples -pgfmd # dh_installmenu # dh_installemacsen # dh_installpam dh_installinit # dh_installcron # manpages for gfarm package for pkg in $(GFPTOOL_PKG) $(GFPTOOL_GSI_PKG); do \ dh_installman -p$$pkg; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ for man in $(GFARM_GFPTOOL_MAN1); do \ install -o root -g root -m 644 man/ja/man1/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man1/$$man; \ done; \ done # manpages for gfmd package for pkg in $(GFMD_PKG) $(GFMD_GSI_PKG); do \ dh_installman -p$$pkg; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man8; \ for man in $(GFMD_MAN8); do \ install -o root -g root -m 644 man/ja/man8/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man8; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man8/$$man; \ done; \ done # manpages for gfarm-client package for pkg in $(CLIENT_PKG) $(CLIENT_GSI_PKG); do \ dh_installman -p$$pkg; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ for man in $(GFARM_CLIENT_MAN1); do \ install -o root -g root -m 644 man/ja/man1/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man1/$$man; \ done; \ done # manpages for gfarm-gfront package dh_installman -p$(GFRONT_PKG) install -d `pwd`/debian/$(GFRONT_PKG)/usr/share/man/ja/man1 for man in $(GFRONT_MAN1); do \ install -o root -g root -m 644 man/ja/man1/$$man `pwd`/debian/$(GFRONT_PKG)/usr/share/man/ja/man1; \ gzip -f -9 `pwd`/debian/$(GFRONT_PKG)/usr/share/man/ja/man1/$$man; \ done # manpages for gfsd for pkg in $(GFSD_PKG) $(GFSD_GSI_PKG); do \ dh_installman -p$$pkg; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ for man in $(GFSD_MAN1); do \ install -o root -g root -m 644 man/ja/man1/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man1; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man1/$$man; \ done; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man8; \ for man in $(GFSD_MAN8); do \ install -o root -g root -m 644 man/ja/man8/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man8; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man8/$$man; \ done; \ done # manpages for libgfarm-dev for pkg in $(LIBGFARM_DEV_PKG) $(DEV_GSI_PKG); do \ dh_installman -p$$pkg; \ install -d `pwd`/debian/$$pkg/usr/share/man/ja/man3; \ for man in $(LIBGFARM_DEV_MAN3); do \ install -o root -g root -m 644 man/ja/man3/$$man `pwd`/debian/$$pkg/usr/share/man/ja/man3; \ gzip -f -9 `pwd`/debian/$$pkg/usr/share/man/ja/man3/$$man; \ done; \ done # symlinks (cd ./debian/gfarm-client/usr/share/man/man1/; rm -f gfssh.1 gfsshl.1.gz gfrsh.1 gfrshl.1.gz; \ ln -s gfrun.1.gz gfssh.1.gz; ln -s gfrun.1.gz gfsshl.1.gz; \ ln -s gfrun.1.gz gfrsh.1.gz; ln -s gfrun.1.gz gfrshl.1.gz) (cd ./debian/gfarm-gsi-client/usr/share/man/man1/; rm -f gfssh.1.gz gfsshl.1.gz gfrsh.1.gz gfrshl.1.gz; \ ln -s gfrun.1.gz gfssh.1.gz; ln -s gfrun.1.gz gfsshl.1.gz; \ ln -s gfrun.1.gz gfrsh.1.gz; ln -s gfrun.1.gz gfrshl.1.gz) # others # install -o root -g root -m 644 debian/man/gfregister.1 debian/gfarm-gfptool/usr/share/man/man1/ # gzip -f -9 debian/gfarm-gfptool/usr/share/man/man1/gfregister.1 # install -o root -g root -m 644 debian/man/gfregister.1 debian/gfarm-gsi-gfptool/usr/share/man/man1/ # gzip -f -9 debian/gfarm-gsi-gfptool/usr/share/man/man1/gfregister.1 # install -o root -g root -m 644 debian/man/gfsck.1 debian/gfarm-client/usr/share/man/man1/ # gzip -f -9 debian/gfarm-client/usr/share/man/man1/gfsck.1 # install -o root -g root -m 644 debian/man/gfsck.1 debian/gfarm-gsi-client/usr/share/man/man1/ # gzip -f -9 debian/gfarm-gsi-client/usr/share/man/man1/gfsck.1 # install -o root -g root -m 644 debian/man/ptool.1 debian/gfarm-client/usr/share/man/man1/ # gzip -f -9 debian/gfarm-client/usr/share/man/man1/ptool.1 # install -o root -g root -m 644 debian/man/ptool.1 debian/gfarm-gsi-client/usr/share/man/man1/ # gzip -f -9 debian/gfarm-gsi-client/usr/share/man/man1/ptool.1 # (cd ./debian/gfarm-client/usr/share/man/man1/; \ # ln -s ptool.1.gz prun.1.gz; ln -s ptool.1.gz pcp.1.gz; \ # ln -s ptool.1.gz pcat.1.gz; ln -s ptool.1.gz pdel.1.gz; ln -s ptool.1.gz pdist.1.gz) # (cd ./debian/gfarm-gsi-client/usr/share/man/man1/; \ # ln -s ptool.1.gz prun.1.gz; ln -s ptool.1.gz pcp.1.gz; \ # ln -s ptool.1.gz pcat.1.gz; ln -s ptool.1.gz pdel.1.gz; ln -s ptool.1.gz pdist.1.gz) # dh_installinfo # dh_undocumented dh_installchangelogs dh_strip dh_link dh_compress dh_fixperms # You may want to make some executables suid here. # dh_suidregister dh_installdeb dh_makeshlibs # dh_perl dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb binary: binary-arch binary-indep .PHONY: build clean binary-indep binary-arch binary install configure <file_sep>/gfarmfs-fuse/trunk/Makefile.am bin_PROGRAMS = gfarmfs gfarmfs_SOURCES = gfarmfs.c gfarmfs_LDADD = $(GFARMFS_LIBS) $(gfarm_libs) gfarmfs_CFLAGS = $(GFARMFS_CFLAGS) gfarmfs_CPPFLAGS = -D_REENTRANT -DFUSE_USE_VERSION=$(fuse_interface) EXTRA_DIST = README.ja ChangeLog.ja gfarmfs.spec SUBDIRS = contrib test testurl = 'http://fuse.cvs.sourceforge.net/*checkout*/fuse/fuse/test/test.c' testprog = fusetest testobj = $(testprog).o testsrc = $(testprog).c test-get: wget $(testurl) -O $(testsrc) test-build: $(CC) -Wall -O2 -c -o $(testobj) $(testsrc) $(CC) -o $(testprog) $(testobj) test-clean: -$(RM) $(testprog) $(testobj) <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_1_rc2/gfarmfs.c /* GfarmFS-FUSE Gfarm: http://datafarm.apgrid.org/ FUSE: http://fuse.sourceforge.net/ Mount: $ ./gfarmfs [GfarmFS options] <mountpoint> [FUSE options] Unmount: $ fusermount -u <mountpoint> Copyright (c) 2005 National Institute of Advanced Industrial Science and Technology (AIST). All Rights Reserved. */ #include <fuse.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <sys/statfs.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <libgen.h> #include <stdlib.h> #include <gfarm/gfarm.h> #define GFARMFS_VER "1.1" #define GFARMFS_VER_DATE "12 Oct 2005" #ifndef GFS_DEV #define GFS_DEV ((dev_t)-1); #endif #ifndef GFS_BLKSIZE #define GFS_BLKSIZE 8192 #endif #ifndef STAT_BLKSIZ #define STAT_BLKSIZ 512 #endif #define SYMLINK_MODE #ifdef SYMLINK_MODE #define SYMLINK_SUFFIX ".gfarmfs-symlink" #endif /* #define GFARMFS_EVERYINIT (for test) */ /* ################################################################### */ int gfarmfs_debug = 0; /* 1: error, 2: debug */ int enable_symlink = 0; int enable_linkiscopy = 0; int enable_unlinkall = 0; int enable_gfarm_unbuf = 0; char *archi_name = NULL; /* This is necessary to free the memory space by free(). */ static char * add_gfarm_prefix(const char *path) { char *url; url = malloc(strlen(path) + 7); sprintf(url, "gfarm:%s", path); return url; } #ifdef SYMLINK_MODE /* This is necessary to free the memory space by free(). */ static char * add_gfarm_prefix_symlink_suffix(const char *path) { char *url; url = malloc(strlen(path) + 7 + strlen(SYMLINK_SUFFIX)); sprintf(url, "gfarm:%s%s", path, SYMLINK_SUFFIX); return url; } #endif static char * gfarmfs_init() { #ifdef GFARMFS_EVERYINIT return gfarm_initialize(NULL, NULL); #else return NULL; #endif } static int gfarmfs_final(char *e, int val_noerror, const char *name) { #ifdef GFARMFS_EVERYINIT gfarm_terminate(); #endif if (e == NULL) { return val_noerror; } else { if (gfarmfs_debug >= 1) { if (name != NULL) { fprintf(stderr, "error: %s: %s\n", name, e); } else { fprintf(stderr, "error: %s\n", e); } } return -gfarm_error_to_errno(e); } } static int gfarmfs_dir_nlink(const char *url) { GFS_Dir dir; struct gfs_dirent *entry; char *e; int res = 0; e = gfs_opendir(url, &dir); if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { if (S_ISDIR(DTTOIF(entry->d_type))) { res++; } } gfs_closedir(dir); } if (res == 0) { return 2; } else { return res; } } #ifdef SYMLINK_MODE int ends_with_and_delete(char *str, char *suffix) { int m, n; m = strlen(str) - 1; n = strlen(suffix) - 1; while (n >=0) { if (m <= 0 || str[m] != suffix[n]) { return 0; /* false */ } m--; n--; } str[m + 1] = '\0'; return 1; /* true */ } #endif char * gfarmfs_check_program_and_set_archi_using_url(GFS_File gf, char *url) { char *e; if (archi_name != NULL) { e = gfs_access(url, X_OK); if (e == NULL) { e = gfs_pio_set_view_section(gf, archi_name, NULL, 0); return e; } } return NULL; } char * gfarmfs_check_program_and_set_archi_using_mode(GFS_File gf, mode_t mode) { char *e; if (archi_name != NULL && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0) { e = gfs_pio_set_view_section(gf, archi_name, NULL, 0); return e; } else { return NULL; } } /* ################################################################### */ static int gfarmfs_getattr(const char *path, struct stat *buf) { /* referred to hooks_stat.c */ struct gfs_stat gs; char *e; struct passwd *p; char *url; #ifdef SYMLINK_MODE int symlinkmode = 0; #endif url = add_gfarm_prefix(path); e = gfarmfs_init(); if (e == NULL) { e = gfs_stat(url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e != NULL) { if (gfarm_error_to_errno(e) == ENOENT) { free(url); url = add_gfarm_prefix_symlink_suffix(path); if (gfarmfs_debug >= 2) { printf("check for symlink: %s\n", url); } e = gfs_stat(url, &gs); symlinkmode = 1; } } #endif } if (e == NULL) { memset(buf, 0, sizeof(struct stat)); buf->st_dev = GFS_DEV; buf->st_ino = gs.st_ino; buf->st_mode = gs.st_mode; #ifdef SYMLINK_MODE if (symlinkmode == 1) { buf->st_mode = 0777 | S_IFLNK; } #endif if (GFARM_S_ISDIR(buf->st_mode)) { buf->st_nlink = gfarmfs_dir_nlink(url); } else { buf->st_nlink = 1; } if (gs.st_user != NULL && ((p = getpwnam(gs.st_user)) != NULL)) { buf->st_uid = p->pw_uid; buf->st_gid = p->pw_gid; } else { buf->st_uid = getuid(); buf->st_gid = getgid(); } buf->st_size = gs.st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_blocks = (gs.st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; buf->st_atime = gs.st_atimespec.tv_sec; buf->st_mtime = gs.st_mtimespec.tv_sec; buf->st_ctime = gs.st_ctimespec.tv_sec; gfs_stat_free(&gs); } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_getdir(const char *path, fuse_dirh_t h, fuse_dirfil_t filler) { GFS_Dir dir; struct gfs_dirent *entry; char *e; int res; char *url; e = gfarmfs_init(); if (e == NULL) { url = add_gfarm_prefix(path); e = gfs_opendir(url, &dir); free(url); } if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { #ifdef SYMLINK_MODE if (enable_symlink == 1 && ends_with_and_delete(entry->d_name, SYMLINK_SUFFIX) > 0) { entry->d_type = DT_LNK; } #endif res = filler(h, entry->d_name, entry->d_type, entry->d_ino); if (res != 0) break; } e = gfs_closedir(dir); } return gfarmfs_final(e, 0, path); } static int gfarmfs_mknod(const char *path, mode_t mode, dev_t rdev) { char *e, *ex; GFS_File gf; char *url; if (rdev != 0 && ((rdev & S_IFREG) != S_IFREG)) { if (gfarmfs_debug >= 1) { printf("mknod: not supported: rdev = %d\n", (int)rdev); } return -ENOSYS; /* XXX */ } url = add_gfarm_prefix(path); e = gfarmfs_init(); while (e == NULL) { e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, mode, &gf); if (e != NULL) break; ex = gfarmfs_check_program_and_set_archi_using_mode(gf, mode); e = gfs_pio_close(gf); if (ex != NULL) e = ex; break; } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_mkdir(const char *path, mode_t mode) { char *e; char *url; url = add_gfarm_prefix(path); e = gfarmfs_init(); if (e == NULL) { e = gfs_mkdir(url, mode); } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_unlink(const char *path) { char *e; char *url; e = gfarmfs_init(); if (e == NULL) { if (enable_unlinkall == 1) { /* remove an entry (all architecture) */ url = add_gfarm_prefix(path); e = gfs_unlink(url); free(url); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e != NULL && gfarm_error_to_errno(e) == ENOENT) { url = add_gfarm_prefix_symlink_suffix(path); if (gfarmfs_debug >= 2) { printf("unlink: for symlink: %s\n", path); } e = gfs_unlink(url); free(url); } #endif } else { /* remove a self architecture file */ struct gfs_stat gs; url = add_gfarm_prefix(path); e = gfs_stat(url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e != NULL && gfarm_error_to_errno(e) == ENOENT) { free(url); url = add_gfarm_prefix_symlink_suffix(path); if (gfarmfs_debug >= 2) { printf("unlink: for symlink: %s\n", path); } e = gfs_stat(url, &gs); } #endif if (e == NULL) { /* gfs_stat succeeds */ if (GFARM_S_IS_PROGRAM(gs.st_mode)) { /* executable file */ char *arch; e = gfarm_host_get_self_architecture(&arch); if (e != NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } else { e = gfs_unlink_section(url, arch); } printf("*** %s %s\n", arch, e); } else { /* regular file */ e = gfs_unlink(url); } gfs_stat_free(&gs); } free(url); } } return gfarmfs_final(e, 0, path); } static int gfarmfs_rmdir(const char *path) { char *e; char *url; url = add_gfarm_prefix(path); e = gfarmfs_init(); if (e == NULL) { e = gfs_rmdir(url); } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_readlink(const char *path, char *buf, size_t size) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n = 0; if (enable_symlink == 0) { return -ENOSYS; } url = add_gfarm_prefix_symlink_suffix(path); e = gfarmfs_init(); while (e == NULL) { e = gfs_pio_open(url, GFARM_FILE_RDONLY, &gf); if (e != NULL) break; e = gfs_pio_read(gf, buf, size - 1, &n); gfs_pio_close(gf); break; } free(url); buf[n] = '\0'; return gfarmfs_final(e, 0, path); #else return -ENOSYS; #endif } static int gfarmfs_symlink(const char *from, const char *to) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n, len; if (enable_symlink == 0) { return -ENOSYS; } url = add_gfarm_prefix_symlink_suffix(to); e = gfarmfs_init(); while (e == NULL) { e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, 0644, &gf); if (e != NULL) break; len = strlen(from); e = gfs_pio_write(gf, from, len, &n); gfs_pio_close(gf); if (len != n) { e = gfs_unlink(url); gfarmfs_final(e, 0, to); free(url); return -EIO; } break; } free(url); return gfarmfs_final(e, 0, to); #else return -ENOSYS; #endif } static int gfarmfs_rename(const char *from, const char *to) { char *e; char *from_url; char *to_url; e = gfarmfs_init(); if (e == NULL) { from_url = add_gfarm_prefix(from); to_url = add_gfarm_prefix(to); e = gfs_rename(from_url, to_url); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e != NULL) { if (gfarm_error_to_errno(e) == ENOENT) { free(from_url); free(to_url); from_url = add_gfarm_prefix_symlink_suffix(from); to_url = add_gfarm_prefix_symlink_suffix(to); if (gfarmfs_debug >= 2) { printf("rename: for symlink: %s\n", from); } e = gfs_rename(from_url, to_url); } } #endif free(from_url); free(to_url); } return gfarmfs_final(e, 0, to); } static int gfarmfs_link(const char *from, const char *to) { char *e; char *fromurl, *tourl; GFS_File fromgf, togf; int fromopened, toopened; struct gfs_stat gs; int mode; int m, n; char buf[4096]; int symlinkmode = 0; if (enable_linkiscopy == 0) { return -ENOSYS; } if (gfarmfs_debug >= 2) { printf("hard link is replaced by copy: %s\n", to); } fromopened = toopened = 0; fromurl = add_gfarm_prefix(from); e = gfarmfs_init(); while (e == NULL) { e = gfs_stat(fromurl, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e != NULL) { if (gfarm_error_to_errno(e) == ENOENT) { free(fromurl); fromurl = add_gfarm_prefix_symlink_suffix(from); if (gfarmfs_debug >= 2) { printf("link: for symlink: %s\n", from); } e = gfs_stat(fromurl, &gs); symlinkmode = 1; } } #endif if (e != NULL) break; mode = gs.st_mode; gfs_stat_free(&gs); e = gfs_pio_open(fromurl, GFARM_FILE_RDONLY, &fromgf); if (e != NULL) break; fromopened = 1; e = gfarmfs_check_program_and_set_archi_using_url(fromgf, fromurl); if (e != NULL) break; if (symlinkmode == 1) { tourl = add_gfarm_prefix_symlink_suffix(to); } else { tourl = add_gfarm_prefix(to); } e = gfs_pio_create(tourl, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, mode, &togf); free(tourl); if (e != NULL) break; toopened = 1; e = gfarmfs_check_program_and_set_archi_using_mode(togf, mode); if (e != NULL) break; while(1) { e = gfs_pio_read(fromgf, buf, 4096, &m); if (e != NULL) break; if (m == 0) { /* EOF */ break; } e = gfs_pio_write(togf, buf, m, &n); if (e != NULL) break; if (m != n) { e = GFARM_ERR_INPUT_OUTPUT; break; } } break; } free(fromurl); if (fromopened == 1) { gfs_pio_close(fromgf); } if (toopened == 1) { gfs_pio_close(togf); } return gfarmfs_final(e, 0, to); } static int gfarmfs_chmod(const char *path, mode_t mode) { char *e; char *url; url = add_gfarm_prefix(path); e = gfarmfs_init(); if (e == NULL) { e = gfs_chmod(url, mode); } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_chown(const char *path, uid_t uid, gid_t gid) { /* referred to hooks.c */ char *e; char *url; struct gfs_stat s; e = gfarmfs_init(); if (e == NULL) { url = add_gfarm_prefix(path); e = gfs_stat(url, &s); free(url); if (e == NULL) { if (strcmp(s.st_user, gfarm_get_global_username()) != 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; /* EPERM */ } /* XXX - do nothing */ gfs_stat_free(&s); } } return gfarmfs_final(e, 0, path); } static int gfarmfs_truncate(const char *path, off_t size) { char *e; GFS_File gf; char *url; url = add_gfarm_prefix(path); e = gfarmfs_init(); while (e == NULL) { e = gfs_pio_open(url, GFARM_FILE_WRONLY, &gf); if (e != NULL) break; e = gfarmfs_check_program_and_set_archi_using_url(gf, url); if (e == NULL) { e = gfs_pio_truncate(gf, size); } gfs_pio_close(gf); break; } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_utime(const char *path, struct utimbuf *buf) { char *e; char *url; url = add_gfarm_prefix(path); e = gfarmfs_init(); if (e == NULL) { if (buf == NULL) e = gfs_utimes(url, NULL); else { struct gfarm_timespec gt[2]; gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_open(const char *path, struct fuse_file_info *fi) { char *e; char *url; int flags = 0; GFS_File gf; url = add_gfarm_prefix(path); e = gfarmfs_init(); while (e == NULL) { if ((fi->flags & O_ACCMODE) == O_RDONLY) { flags = GFARM_FILE_RDONLY; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { flags = GFARM_FILE_WRONLY; } else if ((fi->flags & O_ACCMODE) == O_RDWR) { flags = GFARM_FILE_RDWR; } if (enable_gfarm_unbuf == 1) { flags |= GFARM_FILE_UNBUFFERED; } e = gfs_pio_open(url, flags, &gf); if (e != NULL) break; e = gfarmfs_check_program_and_set_archi_using_url(gf, url); if (e != NULL) { gfs_pio_close(gf); break; } fi->fh = (unsigned long) gf; break; } free(url); return gfarmfs_final(e, 0, path); } static int gfarmfs_release(const char *path, struct fuse_file_info *fi) { char *e; GFS_File gf; e = gfarmfs_init(); if (e == NULL) { gf = (GFS_File) fi->fh; e = gfs_pio_close(gf); } return gfarmfs_final(e, 0, path); } static int gfarmfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(); while (e == NULL) { gf = (GFS_File) fi->fh; e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_read(gf, buf, size, &n); break; } return gfarmfs_final(e, n, path); } static int gfarmfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(); while (e == NULL) { gf = (GFS_File) fi->fh; e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_write(gf, buf, size, &n); break; } return gfarmfs_final(e, n, path); } #if 0 static int gfarmfs_statfs(const char *path, struct statfs *stbuf) { return -ENOSYS; } static int gfarmfs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { return 0; } #endif #if 0 /* #ifdef HAVE_SETXATTR */ /* xattr operations are optional and can safely be left unimplemented */ static int gfarmfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return -ENOSYS; } static int gfarmfs_getxattr(const char *path, const char *name, char *value, size_t size) { return -ENOSYS; } static int gfarmfs_listxattr(const char *path, char *list, size_t size) { return -ENOSYS; } static int gfarmfs_removexattr(const char *path, const char *name) { return -ENOSYS; } #endif /* HAVE_SETXATTR */ static struct fuse_operations gfarmfs_oper = { .getattr = gfarmfs_getattr, .readlink = gfarmfs_readlink, .getdir = gfarmfs_getdir, .mknod = gfarmfs_mknod, .mkdir = gfarmfs_mkdir, .symlink = gfarmfs_symlink, .unlink = gfarmfs_unlink, .rmdir = gfarmfs_rmdir, .rename = gfarmfs_rename, .link = gfarmfs_link, .chmod = gfarmfs_chmod, .chown = gfarmfs_chown, .truncate = gfarmfs_truncate, .utime = gfarmfs_utime, .open = gfarmfs_open, .read = gfarmfs_read, .write = gfarmfs_write, .release = gfarmfs_release, #if 0 .fsync = gfarmfs_fsync, .statfs = gfarmfs_statfs, #endif #if 0 /* #ifdef HAVE_SETXATTR */ .setxattr = gfarmfs_setxattr, .getxattr = gfarmfs_getxattr, .listxattr = gfarmfs_listxattr, .removexattr= gfarmfs_removexattr, #endif }; /* ################################################################### */ char *program_name = "gfarmfs"; void gfarmfs_version() { fprintf(stdout, "GfarmFS-FUSE version %s (%s)\n", GFARMFS_VER, GFARMFS_VER_DATE); } void gfarmfs_usage() { const char *fusehelp[] = { program_name, "-ho", NULL }; fprintf(stderr, "Usage: %s [GfarmFS options] <mountpoint> [FUSE options]\n" "\n" "GfarmFS options:\n" #ifdef SYMLINK_MODE " -s, --symlink enable symlink(2) to work (emulation)\n" #endif " -l, --linkiscopy enable link(2) to behave copying a file (emulation)\n" " -a <architecture> for a client not registered by gfhost\n" " -u, --unlinkall enable unlink(2) to remove all architecture files\n" " -v, --version show version and exit\n" "\n", program_name); fuse_main(2, (char **) fusehelp, &gfarmfs_oper); } void check_fuse_options(int *argcp, char ***argvp) { int argc = *argcp; char **argv = *argvp; char **newargv; int i; int ok_s = 0; /* check -s */ static char *opt_s_str = "-s"; for(i = 1; i < argc; i++) { if (strcmp(argv[i], "-s") == 0) { ok_s = 1; } else if (strcmp(argv[i], "-f") == 0) { gfarmfs_debug = 1; } else if (strcmp(argv[i], "-d") == 0) { gfarmfs_debug = 2; } else if (strcmp(argv[i], "-h") == 0) { gfarmfs_usage(); exit(0); } } if (ok_s == 0) { /* add -s option */ newargv = malloc((argc + 1) * sizeof(char *)); for (i = 0; i < argc; i++) { newargv[i] = argv[i]; } argc++; newargv[argc - 1] = opt_s_str; *argcp = argc; *argvp = newargv; } } void check_gfarmfs_options(int *argcp, char ***argvp) { int argc = *argcp; char **argv = *argvp; char *argv0 = *argv; --argc; ++argv; while (argc > 0 && argv[0][0] == '-') { if (strcmp(&argv[0][1], "-symlink") == 0 || strcmp(&argv[0][1], "s") == 0) { printf("enable symlink\n"); enable_symlink = 1; } else if (strcmp(&argv[0][1], "-linkiscopy") == 0 || strcmp(&argv[0][1], "l") == 0) { printf("enable linkiscopy\n"); enable_linkiscopy = 1; } else if (strcmp(&argv[0][1], "-architecture") == 0 || strcmp(&argv[0][1], "a") == 0) { --argc; ++argv; if (argc > 0) { archi_name = *argv; printf("set architecture: `%s'\n", archi_name); } else { gfarmfs_usage(); exit(1); } } else if (strcmp(&argv[0][1], "-unlinkall") == 0 || strcmp(&argv[0][1], "u") == 0) { archi_name = *argv; printf("enable unlinkall\n"); enable_unlinkall = 1; } else if (strcmp(&argv[0][1], "-unbuf") == 0) { printf("enable GFARM_FILE_UNBUFFERED\n"); enable_gfarm_unbuf = 1; } else if (strcmp(&argv[0][1], "-version") == 0 || strcmp(&argv[0][1], "v") == 0) { gfarmfs_version(); exit(0); } else { gfarmfs_usage(); exit(1); } --argc; ++argv; } ++argc; --argv; *argcp = argc; *argv = argv0; *argvp = argv; } int main(int argc, char *argv[]) { #ifndef GFARMFS_EVERYINIT char *e; if (argc > 0) { program_name = basename(argv[0]); } /* e = gfarm_initialize(&argc, &argv); */ e = gfarm_initialize(NULL, NULL); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(-1); } #endif check_gfarmfs_options(&argc, &argv); check_fuse_options(&argc, &argv); return fuse_main(argc, argv, &gfarmfs_oper); } <file_sep>/gfarm/branches/metadb_dev/makes/prog.mk install: all prog-install post-install-hook clean: prog-clean post-clean-hook veryclean: prog-veryclean post-veryclean-hook distclean: prog-distclean post-distclean-hook post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: $(PROGRAM): $(OBJS) $(DEPLIBS) $(CC) -o $(PROGRAM) $(CFLAGS) $(OBJS) $(LDLIBS) prog-install: $(INSTALL_PROGRAM) $(PROGRAM) $(bindir)/$(PROGRAM) prog-clean: -rm -f $(OBJS) $(EXTRA_CLEAN_TARGETS) prog-veryclean: clean -rm -f $(PROGRAM) $(EXTRA_VERYCLEAN_TARGETS) prog-distclean: veryclean if [ -f $(srcdir)/Makefile.in ]; then rm -f Makefile; fi <file_sep>/gfarm/tags/gfarm_1_1_0_rc1/lib/libgfarm/gfarm/auth_common_gsi.c #include <sys/types.h> #include <pwd.h> #include <string.h> #include <gssapi.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include "auth.h" #include "auth_gsi.h" #define GFSL_CONF_USERMAP "/etc/grid-security/grid-mapfile" static int gsi_initialized; static int gsi_server_initialized; char * gfarm_gsi_client_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) return (NULL); rv = gfarmSecSessionInitializeInitiator(NULL, GFSL_CONF_USERMAP, &e_major, &e_minor); if (rv <= 0) { if (gflog_auth_get_verbose()) { gflog_error( "can't initialize as initiator because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeInitiator(); return ("GSI credential initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 0; return (NULL); } char * gfarm_gsi_client_cred_name(void) { gss_cred_id_t cred; gss_name_t name; OM_uint32 e_major, e_minor; static int initialized = 0; static char *dn; if (initialized) return (dn); if (gfarmSecSessionGetInitiatorInitialCredential(&cred) < 0) { dn = NULL; gflog_auth_error("gfarm_gsi_client_cred_name()", "not initialized as an initiator"); } else if (gfarmGssNewCredentialName(&name, cred, &e_major, &e_minor) < 0) { dn = NULL; if (gflog_auth_get_verbose()) { gflog_error("cannot convert initiator credential " "to name", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } } else { dn = gfarmGssNewDisplayName(name, &e_major, &e_minor, NULL); if (dn == NULL && gflog_auth_get_verbose()) { gflog_error("cannot convert initiator credential " "to string", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmGssDeleteName(&name, NULL, NULL); } initialized = 1; return (dn); } char * gfarm_gsi_server_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) { if (gsi_server_initialized) return (NULL); gfarmSecSessionFinalizeInitiator(); gsi_initialized = 0; } rv = gfarmSecSessionInitializeBoth(NULL, NULL, GFSL_CONF_USERMAP, &e_major, &e_minor); if (rv <= 0) { if (gflog_auth_get_verbose()) { gflog_error( "can't initialize GSI as both because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeBoth(); return ("GSI initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 1; return (NULL); } /* * Delegated credential */ static gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL; void gfarm_gsi_set_delegated_cred(gss_cred_id_t cred) { delegated_cred = cred; } gss_cred_id_t gfarm_gsi_get_delegated_cred() { return (delegated_cred); } /* * converter from credential configuration to [GSSNameType, GSSName]. * * The results of * (type, service, name) -> gss_name_t [NameType, Name] -> gss_cred_id_t * are: * (DEFAULT, NULL, NULL) is not allowed. caller must check this at first. * (NO_NAME, NULL, NULL) -> GSS_C_NO_NAME * (MECHANISM_SPECIFIC, NULL, name) -> [GSS_C_NO_OID, name] * (HOST, service, host) ->[GSS_C_NT_HOSTBASED_SERVICE, service + "@" + host] * if (service == NULL) service = "host" * (USER, NULL, username) -> [GSS_C_NT_USER_NAME, username] * if (username == NULL) username = self_local_username * (SELF, NULL, NULL) -> the name of initial initiator credential * * when a server acquires a credential of itself: * (DEFAULT, NULL, NULL) -> N/A -> GSS_C_NO_CREDENTIAL * when a client authenticates a server: * (DEFAULT, NULL, NULL) is equivalent to (HOST, NULL, NULL) * (HOST, service, NULL) is equivalent to (HOST, service, peer_host) */ char * gfarm_gsi_cred_config_convert_to_name( enum gfarm_auth_cred_type type, char *service, char *name, char *hostname, gss_name_t *namep) { int rv; OM_uint32 e_major; OM_uint32 e_minor; gss_cred_id_t cred; switch (type) { case GFARM_AUTH_CRED_TYPE_DEFAULT: /* special. equivalent to GSS_C_NO_CREDENTIAL */ if (name != NULL) return ("cred_type is not set, but cred_name is set"); if (service != NULL) return ("cred_type is not set, but cred_service is set" ); return ("internal error: missing GSS_C_NO_CREDENTIAL check"); case GFARM_AUTH_CRED_TYPE_NO_NAME: if (name != NULL) return ("cred_type is \"no-name\", " "but cred_name is set"); if (service != NULL) return ("cred_type is \"no-name\", " "but cred_service is set"); *namep = GSS_C_NO_NAME; return (NULL); case GFARM_AUTH_CRED_TYPE_MECHANISM_SPECIFIC: if (name == NULL) return ("cred_type is \"mechanism-specific\", " "but cred_name is not set"); if (service != NULL) return ("cred_type is \"mechanism-specific\", " "but cred_service is set"); rv = gfarmGssImportName(namep, name, strlen(name), GSS_C_NO_OID, &e_major, &e_minor); break; case GFARM_AUTH_CRED_TYPE_HOST: if (name == NULL) name = hostname; if (service == NULL) { rv = gfarmGssImportNameOfHost(namep, name, &e_major, &e_minor); } else { rv = gfarmGssImportNameOfHostBasedService(namep, service, name, &e_major, &e_minor); } break; case GFARM_AUTH_CRED_TYPE_USER: if (service != NULL) return ("cred_type is \"user\", " "but cred_service is set"); /* * XXX FIXME: `name' must be converted from global_username * to local_username, but there is no such function for now. */ if (name == NULL) name = gfarm_get_local_username(); rv = gfarmGssImportName(namep, name, strlen(name), GSS_C_NT_USER_NAME, &e_major, &e_minor); break; case GFARM_AUTH_CRED_TYPE_SELF: /* special. there is no corresponding name_type in GSSAPI */ if (name != NULL) return ("cred_type is \"self\", but cred_name is set"); if (service != NULL) return ("cred_type is \"self\", " "but cred_service is set"); if (gfarmSecSessionGetInitiatorInitialCredential(&cred) < 0 || cred == GSS_C_NO_CREDENTIAL) return ("cred_type is \"self\", " "but not initialized as an initiator"); rv = gfarmGssNewCredentialName(namep, cred, &e_major,&e_minor); break; default: return ("internal error - invalid cred_type"); } if (rv < 0) { if (gflog_auth_get_verbose()) { gflog_error("gfarmGssImportName()", "invalid credential configuration:"); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } return ("invalid credential configuration"); } return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/makes/subdir.mk all: subdir-all post-all-hook install: subdir-install post-install-hook clean: subdir-clean post-clean-hook veryclean: subdir-veryclean post-very-clean-hook distclean: subdir-distclean post-distclean-hook gfregister: subdir-gfregister post-gfregister-hook man: subdir-man html: subdir-html post-all-hook: post-install-hook: post-clean-hook: post-very-clean-hook: post-distclean-hook: post-gfregister-hook: subdir-all subdir-install subdir-clean subdir-veryclean subdir-distclean subdir-gfregister subdir-man subdir-html: @target=`expr $@ : 'subdir-\(.*\)'`; \ for dir in / $(SUBDIRS); do \ case $${dir} in /) continue;; esac; \ echo '[' making $${dir} ']'; \ if test -f $(srcdir)/$${dir}/Makefile.in; then \ ( cd $${dir} && \ case "$(srcdir)" in \ .) $(MAKE) $${target};; \ *) $(MAKE) \ top_srcdir=$(top_srcdir) \ top_objdir=$(top_objdir) \ srcdir=$(srcdir)/$${dir} \ $${target};; \ esac; \ ) || exit 1; \ else \ test -d $${dir} || mkdir -p $${dir} || exit 1; \ ( cd $${dir} && \ case "$(srcdir)" in \ .) $(MAKE) $${target};; \ *) $(MAKE) -f $(srcdir)/$${dir}/Makefile \ top_srcdir=$(top_srcdir) \ top_objdir=$(top_objdir) \ srcdir=$(srcdir)/$${dir} \ $${target};; \ esac; \ ) || exit 1; \ fi; \ done <file_sep>/gfarm/tags/gfarm_1_0_1_rc1/lib/libgfarm/gfarm/gfs_dir.c #include <string.h> #include <stdlib.h> #include <limits.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "hash.h" #include "gfs_pio.h" /* gfarm_path_expand_home */ static char *gfarm_current_working_directory; char * gfs_chdir(const char *dir) { char *e, *canonic_path, *new_dir; e = gfarm_canonical_path(gfarm_url_prefix_skip(dir), &canonic_path); if (e != NULL) return (e); if (gfarm_current_working_directory != NULL) { free(gfarm_current_working_directory); gfarm_current_working_directory = NULL; } new_dir = malloc(strlen(canonic_path) + 2); if (new_dir == NULL) { free(canonic_path); return (GFARM_ERR_NO_MEMORY); } sprintf(new_dir, "/%s", canonic_path); free(canonic_path); gfarm_current_working_directory = new_dir; return (NULL); } char * gfs_getcwd(char *cwd, int cwdsize) { const char *path; char *default_cwd = NULL; int len; if (gfarm_current_working_directory != NULL) path = gfarm_current_working_directory; else if ((path = getenv("GFS_PWD")) != NULL) path = gfarm_url_prefix_skip(path); else { /* default case, use user's home directory */ char *e; e = gfarm_path_expand_home("~", &default_cwd); if (e != NULL) return (e); path = default_cwd; } len = strlen(path); if (len < cwdsize) { strcpy(cwd, path); } else { memcpy(cwd, path, cwdsize - 1); cwd[cwdsize - 1] = '\0'; } if (default_cwd != NULL) free(default_cwd); return (NULL); } /* * directory tree, opendir/readdir/closedir */ struct node { struct node *parent; char *name; int is_dir; union node_u { struct dir { struct gfarm_hash_table *children; } d; } u; }; #define NODE_HASH_SIZE 53 /* prime */ static struct node *root; static struct node * init_node_name(struct node *n, const char *name, int len) { n->name = malloc(len + 1); if (n->name == NULL) return (NULL); memcpy(n->name, name, len); n->name[len] = '\0'; return (n); } #define DIR_NODE_SIZE \ (sizeof(struct node) - sizeof(union node_u) + sizeof(struct dir)) static struct node * init_dir_node(struct node *n, const char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->is_dir = 1; n->u.d.children = gfarm_hash_table_alloc(NODE_HASH_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); return (n); } #define FILE_NODE_SIZE (sizeof(struct node) - sizeof(union node_u)) static struct node * init_file_node(struct node *n, const char *name, int len) { if (init_node_name(n, name, len) == NULL) return (NULL); n->is_dir = 0; return (n); } static struct node * lookup_node(struct node *parent, const char *name, int len, int is_dir, int create) { struct gfarm_hash_entry *entry; int created; struct node *n; if (!parent->is_dir) return (NULL); /* not a directory */ if (len == 0) { return (parent); } else if (len == 1 && name[0] == '.') { return (parent); } else if (len == 2 && name[0] == '.' && name[1] == '.') { return (parent->parent); } if (len > GFS_MAXNAMLEN) len = GFS_MAXNAMLEN; if (!create) { entry = gfarm_hash_lookup(parent->u.d.children, name, len); return (entry == NULL ? NULL : gfarm_hash_entry_data(entry)); } entry = gfarm_hash_enter(parent->u.d.children, name, len, is_dir ? DIR_NODE_SIZE : FILE_NODE_SIZE, &created); n = gfarm_hash_entry_data(entry); if (!created) return (n); if (is_dir) init_dir_node(n, name, len); else init_file_node(n, name, len); if (n == NULL) { gfarm_hash_purge(parent->u.d.children, name, len); return (NULL); } n->parent = parent; return (n); } /* if (!create), (is_dir) may be -1, and that means "don't care". */ static char * lookup_relative(struct node *n, const char *path, int is_dir, int create, struct node **np) { int len; if (!n->is_dir) return (GFARM_ERR_NOT_A_DIRECTORY); for (;;) { while (*path == '/') path++; for (len = 0; path[len] != '/'; len++) { if (path[len] == '\0') { n = lookup_node(n, path, len, is_dir, create); if (n == NULL) return (create ? GFARM_ERR_NO_MEMORY : GFARM_ERR_NO_SUCH_OBJECT); if (is_dir != -1 && n->is_dir != is_dir) return (n->is_dir ? GFARM_ERR_IS_A_DIRECTORY : GFARM_ERR_NOT_A_DIRECTORY); if (np != NULL) *np = n; return (NULL); } } n = lookup_node(n, path, len, 1, /* XXX */ create); if (n == NULL) return (create ? GFARM_ERR_NO_MEMORY : GFARM_ERR_NO_SUCH_OBJECT); if (!n->is_dir) return (GFARM_ERR_NOT_A_DIRECTORY); path += len; } } /* if (!create), (is_dir) may be -1, and that means "don't care". */ static char * lookup_path(const char *path, int is_dir, int create, struct node **np) { struct node *n; if (path[0] == '/') { n = root; } else { char *e; char cwd[PATH_MAX + 1]; e = gfs_getcwd(cwd, sizeof(cwd)); if (e != NULL) return (e); e = lookup_relative(root, cwd, 1, 0, &n); if (e != NULL) return (e); } return (lookup_relative(n, path, is_dir, create, np)); } static char * root_node(void) { root = malloc(DIR_NODE_SIZE); if (root == NULL) return (GFARM_ERR_NO_MEMORY); init_dir_node(root, "", 0); root->parent = root; return (NULL); } static void remember_path(void *closure, struct gfarm_path_info *info) { lookup_relative(root, info->pathname, GFARM_S_ISDIR(info->status.st_mode), 1, NULL); } static char * gfs_cachedir(void) { char *e; if (root != NULL) return (NULL); e = root_node(); if (e != NULL) return (e); gfarm_path_info_get_all_foreach(remember_path, NULL); return (NULL); } static void free_node(struct node *n) { if (n->is_dir) { struct gfarm_hash_iterator i; struct gfarm_hash_entry *child; for (gfarm_hash_iterator_begin(n->u.d.children, &i); (child = gfarm_hash_iterator_access(&i)) != NULL; gfarm_hash_iterator_next(&i)) { free_node(gfarm_hash_entry_data(child)); } gfarm_hash_table_free(n->u.d.children); } free(n->name); } void gfs_uncachedir(void) { if (root != NULL) { free_node(root); free(root); root = NULL; } } char * gfs_realpath_canonical(const char *path, char **abspathp) { struct node *n, *p; char *e, *abspath; int l, len; e = gfs_cachedir(); if (e != NULL) return (e); e = lookup_path(path, -1, 0, &n); if (e != NULL) return (e); len = 0; for (p = n; p != root; p = p->parent) { if (p != n) ++len; /* for '/' */ len += strlen(p->name); } abspath = malloc(len + 1); if (abspath == NULL) return (GFARM_ERR_NO_MEMORY); abspath[len] = '\0'; for (p = n; p != root; p = p->parent) { if (p != n) abspath[--len] = '/'; l = strlen(p->name); len -= l; memcpy(abspath + len, p->name, l); } *abspathp = abspath; return (NULL); } /* * gfs_opendir()/readdir()/closedir() */ struct gfs_dir { struct node *dir; struct gfarm_hash_iterator iterator; struct gfs_dirent buffer; }; char * gfs_opendir(const char *path, GFS_Dir *dirp) { char *e, *canonic_path, *abspath; struct node *n; struct gfs_dir *dir; path = gfarm_url_prefix_skip(path); e = gfarm_canonical_path(path, &canonic_path); if (e != NULL) return (e); abspath = malloc(strlen(canonic_path) + 2); if (abspath == NULL) { free(canonic_path); return (GFARM_ERR_NO_MEMORY); } sprintf(abspath, "/%s", canonic_path); free(canonic_path); e = lookup_path(abspath, 1, 0, &n); free(abspath); if (e != NULL) return (e); dir = malloc(sizeof(struct gfs_dir)); if (dir == NULL) return (GFARM_ERR_NO_MEMORY); dir->dir = n; gfarm_hash_iterator_begin(n->u.d.children, &dir->iterator); *dirp = dir; return (NULL); } char * gfs_readdir(GFS_Dir dir, struct gfs_dirent **entry) { struct gfarm_hash_entry *he; struct node *n; he = gfarm_hash_iterator_access(&dir->iterator); if (he == NULL) { *entry = NULL; return (NULL); } n = gfarm_hash_entry_data(he); gfarm_hash_iterator_next(&dir->iterator); dir->buffer.d_fileno = 1; /* XXX */ dir->buffer.d_type = n->is_dir ? GFS_DT_DIR : GFS_DT_REG; dir->buffer.d_namlen = gfarm_hash_entry_key_length(he); memcpy(dir->buffer.d_name, gfarm_hash_entry_key(he), dir->buffer.d_namlen); dir->buffer.d_name[dir->buffer.d_namlen] = '\0'; *entry = &dir->buffer; return (NULL); } char * gfs_closedir(GFS_Dir dir) { free(dir); return (NULL); } <file_sep>/gfarmfs-fuse/trunk/test/func.sh #! /bin/sh err=0 canceled=0 test_cancel() { echo "canceled (test.sh)" canceled=1 } test_init() { if [ -e ${OUTPUTDIR} ]; then rm -rf ${OUTPUTDIR} fi mkdir ${OUTPUTDIR} if [ $? -ne 0 ]; then exit 1 fi if [ -e ${DIFFDIR} ]; then rm -rf ${DIFFDIR} fi mkdir ${DIFFDIR} if [ $? -ne 0 ]; then exit 1 fi err=0 trap test_cancel 1 trap test_cancel 2 } check_result() { RESULT=$1 TESTSTR=$2 IGNORE=$3 if [ $RESULT -ne 0 -a $IGNORE -eq 1 ]; then echo "IGNORE: ${TESTSTR}" elif [ $RESULT -ne 0 ]; then err=`expr $err + 1` echo "NG: ${TESTSTR}" else echo "OK: ${TESTSTR}" fi } test_common() { TESTDIR=$1 OUTPUT=${OUTPUTDIR}/${2}.out DIFFOUT=${DIFFDIR}/${2}.out EXPECTEDOUT=${EXPECTDIR}/${3}.out TESTSTR=$4 if [ $canceled -eq 1 ];then return fi echo "${TESTSTR}" > ${OUTPUT} (${FSYSTEST} ${TESTDIR} 2>&1 | grep -v '^OK' >> ${OUTPUT} 2>&1 ) & testpid=$! wait $testpid if [ $canceled -eq 1 ];then wait $testpid # cat ${OUTPUT} fi diff -u ${EXPECTEDOUT} ${OUTPUT} > ${DIFFOUT} 2>&1 result=$? if [ $result -eq 0 ]; then rm ${DIFFOUT} > /dev/null 2>&1 check_result 0 "${TESTSTR}" 0 else check_result 1 "${TESTSTR}: different results" 0 fi } umount_fuse() { MNTDIR=$1 retry=10 i=0 while true; do if [ x"$FUSE_MODE" = x"FUSE25_FreeBSD" ]; then umount $MNTDIR > /dev/null 2>&1 else fusermount -u $MNTDIR > /dev/null 2>&1 fi if [ $? -eq 0 ]; then return 0 fi # force RELEASE (?) ls -l $MNTDIR > /dev/null 2>&1 if [ $i -ge $retry ]; then return 1 fi i=`expr $i + 1` done } fuse_common_init() { TESTNAME=$1 OUTNAME=$2 MNTDIR=$3 OUTPUT=${OUTPUTDIR}/${OUTNAME}.out umount_fuse ${MNTDIR} > /dev/null 2>&1 rmdir ${MNTDIR} > /dev/null 2>&1 if [ -e ${MNTDIR} ]; then echo "${MNTDIR} exists" > ${OUTPUT} check_result 1 "${TESTNAME}: `cat ${OUTPUT}`" 0 return 1 fi mkdir ${MNTDIR} > /dev/null 2>&1 } wait_mount() { DIR=$1 retry=3 i=0 while ! ls -ld $DIR > /dev/null 2>&1; do if [ $i -ge $retry -o $canceled -eq 1 ]; then return 1 fi i=`expr $i + 1` sleep 1 done return 0 } fuse_common_do_test() { RESULT=$1 TESTDIR=$2 OUTNAME=$3 TESTNAME=$4 EXPECTED=${OUTNAME} OUTPUT=${OUTPUTDIR}/${OUTNAME}.out wait_mount $TESTDIR if [ $? -ne 0 -o $RESULT -ne 0 ]; then check_result 1 "${TESTNAME}: `cat ${OUTPUT}`" 0 return $RESULT fi rm ${OUTPUT} > /dev/null 2>&1 test_common ${TESTDIR} ${OUTNAME} ${EXPECTED} "${TESTNAME}" } fuse_common_final() { MNTDIR=$1 umount_fuse ${MNTDIR} rmdir ${MNTDIR} > /dev/null 2>&1 } test_gfarmfs() { OPTIONS=$1 FUSEOPTIONS=$2 OUTNAME=$3 OUTPUT=${OUTPUTDIR}/${OUTNAME}.out ERRLOGOPT="--errlog ${OUTPUTDIR}/errlog-${OUTNAME}" TESTNAME="gfarmfs: opt=\"${OPTIONS}\", fuse_opt=\"${FUSEOPTIONS}\"" TESTDIR=${TMP_MNTDIR}/${LOGNAME} # need gfmkdir gfarm:~ if [ $canceled -eq 1 ]; then return fi fuse_common_init "${TESTNAME}" ${OUTNAME} ${TMP_MNTDIR} result=$? if [ $result -ne 0 ]; then return $result fi $GFARMFS $OPTIONS $ERRLOGOPT $TMP_MNTDIR $FUSEOPTIONS > $OUTPUT 2>&1 result=$? fuse_common_do_test $result ${TESTDIR} ${OUTNAME} "${TESTNAME}" fuse_common_final ${TMP_MNTDIR} } test_fusexmp() { FUSEXMP=$1 FUSEOPTIONS=$2 OUTNAME=$3 OUTPUT=${OUTPUTDIR}/${OUTNAME}.out TESTNAME="$FUSEXMP: fuse_opt=\"${FUSEOPTIONS}\"" TESTDIR=${TMP_MNTDIR}/tmp if [ $canceled -eq 1 ]; then return fi which $FUSEXMP 2> $OUTPUT 1> /dev/null result=$? if [ $result -ne 0 ]; then check_result 1 "${TESTNAME}: `cat ${OUTPUT}`" 1 # ignore return 0 fi fuse_common_init "${TESTNAME}" ${OUTNAME} ${TMP_MNTDIR} result=$? if [ $result -ne 0 ]; then return $result fi if [ x"$FUSE_MODE" = x"FUSE25_FreeBSD" ]; then FUSEOPTIONS="-s ${FUSEOPTIONS}" # instability ? fi ${FUSEXMP} ${TMP_MNTDIR} ${FUSEOPTIONS} > ${OUTPUT} 2>&1 result=$? fuse_common_do_test $result ${TESTDIR} ${OUTNAME} "${TESTNAME}" fuse_common_final ${TMP_MNTDIR} } <file_sep>/gfarm/tags/gfarm_1_0_beta_6/lib/libgfarm/gfarm/gfs_client.h /* * $Id$ */ struct sockaddr; struct timeval; struct gfarm_eventqueue; struct gfs_connection; struct gfs_stat; enum gfarm_auth_method; struct gfs_client_connect_state; int gfs_client_connection_fd(struct gfs_connection *); enum gfarm_auth_method gfs_client_connection_auth_method( struct gfs_connection *); const char *gfs_client_hostname(struct gfs_connection *); char *gfs_client_connection(const char *, struct sockaddr *, struct gfs_connection **); char *gfs_client_connect(char *, struct sockaddr *, struct gfs_connection **); char *gfs_client_connect_request_multiplexed(struct gfarm_eventqueue *, char *, struct sockaddr *, void (*)(void *), void *, struct gfs_client_connect_state **); char *gfs_client_connect_result_multiplexed(struct gfs_client_connect_state *, struct gfs_connection **); char *gfs_client_disconnect(struct gfs_connection *); char *gfs_client_create(struct gfs_connection *, char *, gfarm_int32_t, int *); char *gfs_client_open(struct gfs_connection *, char *, gfarm_int32_t, gfarm_int32_t, gfarm_int32_t *); char *gfs_client_close(struct gfs_connection *, gfarm_int32_t); char *gfs_client_seek(struct gfs_connection *, gfarm_int32_t, file_offset_t, gfarm_int32_t, file_offset_t *); char *gfs_client_read(struct gfs_connection *, gfarm_int32_t, void *, size_t, size_t *); char *gfs_client_write(struct gfs_connection *, gfarm_int32_t, const void *, size_t, size_t *); char *gfs_client_unlink(struct gfs_connection *, char *); char *gfs_client_chdir(struct gfs_connection *, char *); char *gfs_client_mkdir(struct gfs_connection *, char *, gfarm_int32_t); char *gfs_client_rmdir(struct gfs_connection *, char *); char *gfs_client_chmod(struct gfs_connection *, char *, gfarm_int32_t); char *gfs_client_chgrp(struct gfs_connection *, char *, char *); char *gfs_client_stat(struct gfs_connection *, char *); char *gfs_client_exist(struct gfs_connection *, char *); char *gfs_client_digest(struct gfs_connection *, int, char *, size_t, size_t *, unsigned char *, file_offset_t *); char *gfs_client_get_spool_root(struct gfs_connection *, char **); char *gfs_client_copyin(struct gfs_connection *, int, int, long); char *gfs_client_striping_copyin_request(struct gfs_connection *, int, int, file_offset_t, file_offset_t, int, file_offset_t); char *gfs_client_striping_copyin_partial(struct gfs_connection *, int *); char *gfs_client_striping_copyin_result(struct gfs_connection *); char *gfs_client_striping_copyin(struct gfs_connection *, int, int, file_offset_t, file_offset_t, int, file_offset_t); char *gfs_client_replicate_file(struct gfs_connection *, char *, gfarm_int32_t, file_offset_t, char *, char *); #define GFS_CLIENT_COMMAND_FLAG_STDIN_EOF 0x01 #define GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND 0x02 #define GFS_CLIENT_COMMAND_FLAG_XENVCOPY 0x10 #define GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY 0x20 /* copies env, too */ #define GFS_CLIENT_COMMAND_FLAG_X11MASK 0x30 #define GFS_CLIENT_COMMAND_EXITFLAG_COREDUMP 1 char *gfs_client_command_request(struct gfs_connection *, char *, char **, char **, int, int *); int gfs_client_command_is_running(struct gfs_connection *); char *gfs_client_command_io(struct gfs_connection *, struct timeval *); char *gfs_client_command_send_signal(struct gfs_connection *, int); char *gfs_client_command_result(struct gfs_connection *, int *, int *, int *); char *gfs_client_command(struct gfs_connection *, char *, char **, char **, int, int *, int *, int *); /* * gfsd service on UDP port. */ extern int gfs_client_datagram_timeouts[]; /* milli seconds */ extern int gfs_client_datagram_ntimeouts; struct gfs_client_load { double loadavg_1min, loadavg_5min, loadavg_15min; }; char *gfs_client_get_load_request(int, struct sockaddr *, int); char *gfs_client_get_load_result(int, struct sockaddr *, int *, struct gfs_client_load *); struct gfs_client_get_load_state; char *gfs_client_get_load_request_multiplexed(struct gfarm_eventqueue *, struct sockaddr *, void (*)(void *), void *, struct gfs_client_get_load_state **); char *gfs_client_get_load_result_multiplexed( struct gfs_client_get_load_state *, struct gfs_client_load *); char *gfs_client_apply_all_hosts( char *(*)(struct gfs_connection *, void *), void *, char *, int *); <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/auth_client_gsi.c #include <stddef.h> #include <stdarg.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <gssapi.h> #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "xxx_proto.h" #include "io_fd.h" #include "io_gfsl.h" #include "auth.h" #define GFSL_CONF_USERMAP "/etc/grid-security/grid-mapfile" gss_cred_id_t gfarm_gsi_get_delegated_cred(); /* XXX */ char * gfarm_gsi_initialize(void) { static int initialized; OM_uint32 e_major; int rv; if (initialized) return (NULL); if (geteuid() == 0) { /* XXX - kluge */ rv = gfarmSecSessionInitializeBoth(NULL, NULL, GFSL_CONF_USERMAP, &e_major); } else { rv = gfarmSecSessionInitializeInitiator(NULL, &e_major); } if (rv <= 0) { #if 1 /* XXX for debugging */ fprintf(stderr, "can't initialize as initiator because of:\n"); gfarmGssPrintStatus(stderr, e_major); #endif if (geteuid() == 0) { /* XXX - kluge */ gfarmSecSessionFinalizeBoth(); } else { gfarmSecSessionFinalizeInitiator(); } return (GFARM_ERR_UNKNOWN); /* XXX */ } initialized = 1; return (NULL); } char * gfarm_auth_request_gsi(struct xxx_connection *conn) { int fd = xxx_connection_fd(conn); char *e; OM_uint32 e_major; gfarmSecSession *session; gfarm_int32_t error; /* enum gfarm_auth_error */ int eof; e = gfarm_gsi_initialize(); if (e != NULL) return (e); session = gfarmSecSessionInitiate(fd, gfarm_gsi_get_delegated_cred(), NULL, &e_major); if (session == NULL) { #if 1 /* XXX for debugging */ fprintf(stderr, "Can't initiate session because of:\n"); gfarmGssPrintStatus(stderr, e_major); #endif return (GFARM_ERR_AUTHENTICATION); } xxx_connection_set_secsession(conn, session); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL || error != GFARM_AUTH_ERROR_NO_ERROR) { gfarmSecSessionTerminate(session); xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); if (e != NULL ? e : GFARM_ERR_AUTHENTICATION); } return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/lib/libgfarm/gfutil/Makefile # $Id$ top_builddir = ../../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk LIBRARY = libgfutil.la LIBRARY_RESULT = # do not install SRCS = daemon.c gfevent.c hash.c limit.c logutil.c timer.c timeval.c OBJS = daemon.lo gfevent.lo hash.lo limit.lo logutil.lo timer.lo timeval.lo CFLAGS = $(COMMON_CFLAGS) -I$(GFUTIL_SRCDIR) all: $(LIBRARY) include $(top_srcdir)/makes/lib.mk ### $(GFUTIL_OBJS): $(DEPGFARMINC) daemon.lo: gfutil.h gfevent.lo: gfutil.h gfevent.h hash.lo: hash.h limit.lo: gfutil.h logutil.lo: gfutil.h timer.lo: timer.h timeval.lo: gfutil.h <file_sep>/gfarm/tags/gfarm_1_0_3_1/lib/gfs_hook/hooks_subr.c /* * $Id$ */ #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" /* for creating_file hash -- XXX: Gfarm v2 may make this stuff obsolete */ #include "hash.h" #include <openssl/evp.h> #include "gfs_pio.h" #define MAX_GFS_FILE_BUF 2048 struct _gfs_file_descriptor { int refcount; unsigned char d_type; /* file types in <gfarm/gfs.h> */ union { GFS_File f; struct { GFS_Dir dir; int readcount; struct gfs_dirent *suspended; struct gfs_stat gst; char *canonical_path; /* for __fchdir() hook */ } *d; } u; }; static struct _gfs_file_descriptor *_gfs_file_buf[MAX_GFS_FILE_BUF]; void gfs_hook_not_initialized(void) { static int printed = 0; if (!printed) { printed = 1; fprintf(stderr, "fatal error: gfarm_initialize() isn't called\n"); } } /* * gfs_file_buf management */ int gfs_hook_insert_gfs_file(GFS_File gf) { int fd, save_errno; struct stat st; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_file: %p\n", gf)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = gfs_pio_fileno(gf); if (fstat(fd, &st) == -1) { save_errno = errno; gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = save_errno; return (-1); } if (S_ISREG(st.st_mode)) fd = dup(fd); else /* don't return a socket, to make select(2) work with this fd */ fd = open("/dev/null", O_RDWR); if (fd == -1) { save_errno = errno; gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_REG; _gfs_file_buf[fd]->u.f = gf; return (fd); } int gfs_hook_insert_gfs_dir(GFS_Dir dir, char *url) { int fd, save_errno; char *e; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_dir: %p\n", dir)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = open("/dev/null", O_RDONLY); if (fd == -1) { save_errno = errno; gfs_closedir(dir); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_closedir(dir); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_closedir(dir); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->u.d = malloc(sizeof(*_gfs_file_buf[fd]->u.d)); if (_gfs_file_buf[fd]->u.d == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_DIR; _gfs_file_buf[fd]->u.d->dir = dir; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; e = gfs_stat(url, &_gfs_file_buf[fd]->u.d->gst); if (e != NULL) return (-1); e = gfarm_canonical_path(gfarm_url_prefix_skip(url), &_gfs_file_buf[fd]->u.d->canonical_path); if (e != NULL) return (-1); return (fd); } unsigned char gfs_hook_gfs_file_type(int fd) { return (_gfs_file_buf[fd]->d_type); } char * gfs_hook_clear_gfs_file(int fd) { GFS_File gf; char *e = NULL; _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: %d\n", fd)); gf = gfs_hook_is_open(fd); if (--_gfs_file_buf[fd]->refcount > 0) { /* fd is duplicated, skip closing the file. */ _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: skipped\n")); } else { if (gfs_hook_gfs_file_type(fd) == GFS_DT_REG) { gfs_hook_delete_creating_file(gf); e = gfs_pio_close(gf); } else if (gfs_hook_gfs_file_type(fd) == GFS_DT_DIR) { _gfs_file_buf[fd]->u.d->dir = NULL; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; gfs_stat_free(&_gfs_file_buf[fd]->u.d->gst); free(_gfs_file_buf[fd]->u.d->canonical_path); free(_gfs_file_buf[fd]->u.d); e = gfs_closedir((GFS_Dir)gf); } free(_gfs_file_buf[fd]); } __syscall_close(fd); _gfs_file_buf[fd] = NULL; return (e); } struct _gfs_file_descriptor *gfs_hook_dup_descriptor(int fd) { if (gfs_hook_is_open(fd) == NULL) return (NULL); ++_gfs_file_buf[fd]->refcount; return (_gfs_file_buf[fd]); } void gfs_hook_set_descriptor(int fd, struct _gfs_file_descriptor *d) { if (gfs_hook_is_open(fd) != NULL) gfs_hook_clear_gfs_file(fd); _gfs_file_buf[fd] = d; } #if 0 int gfs_hook_dup_filedes(int oldfd, int newfd) { _gfs_hook_debug( fprintf(stderr, "GFS: dpu_filedes: %d, %d\n", oldfd, newfd)); #if 0 if (_gfs_file_buf[oldfd] == _gfs_file_buf[newfd]) return (newfd); #endif _gfs_file_buf[newfd] = _gfs_file_buf[oldfd]; } return (newfd); } #endif /* printf and puts should not be put into the following function. */ void * gfs_hook_is_open(int fd) { if (fd < 0 || fd >= MAX_GFS_FILE_BUF) return (NULL); if (_gfs_file_buf[fd] == NULL) return (NULL); switch (gfs_hook_gfs_file_type(fd)) { case GFS_DT_REG: return (_gfs_file_buf[fd]->u.f); case GFS_DT_DIR: return (_gfs_file_buf[fd]->u.d->dir); default: return (NULL); } } /* * hash table for files under creation * * This hash maintains a list of filenames that is created by this * process but not closed yet. This hash is needed to 'stat' these * files in Gfarm v1 API. */ #define CREATING_FILE_HASHTAB_SIZE 53 /* prime number */ static struct gfarm_hash_table *creating_file_hashtab = NULL; char * gfs_hook_add_creating_file(GFS_File gf) { struct gfarm_hash_entry *entry; int created; _gfs_hook_debug(fprintf(stderr, "GFS: add_creating_file: %p (%s)\n", gf, gf->pi.pathname)); if (creating_file_hashtab == NULL) { creating_file_hashtab = gfarm_hash_table_alloc(CREATING_FILE_HASHTAB_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (creating_file_hashtab == NULL) return (GFARM_ERR_NO_MEMORY); } entry = gfarm_hash_enter(creating_file_hashtab, gf->pi.pathname, strlen(gf->pi.pathname) + 1, sizeof(GFS_File), &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); /* always update */ *(GFS_File *)gfarm_hash_entry_data(entry) = gf; return (NULL); } GFS_File gfs_hook_is_now_creating(const char *url) { char *pathname, *e; struct gfarm_hash_entry *entry; _gfs_hook_debug(fprintf(stderr, "GFS: is_now_creating: %s\n", url)); if (creating_file_hashtab == NULL) return (NULL); e = gfarm_url_make_path(url, &pathname); if (e != NULL) return (NULL); _gfs_hook_debug(fprintf(stderr, "GFS: is_now_creating: %s\n", pathname)); entry = gfarm_hash_lookup(creating_file_hashtab, pathname, strlen(pathname) + 1); free(pathname); if (entry == NULL) return (NULL); else return *(GFS_File *)gfarm_hash_entry_data(entry); } void gfs_hook_delete_creating_file(GFS_File gf) { _gfs_hook_debug(fprintf(stderr, "GFS: delete_creating_file: %p (%s)\n", gf, gf->pi.pathname)); if (creating_file_hashtab == NULL) return; gfarm_hash_purge(creating_file_hashtab, gf->pi.pathname, strlen(gf->pi.pathname) + 1); return; } void gfs_hook_inc_readcount(int fd) { _gfs_hook_debug( fprintf(stderr, "GFS: inc_readount: %d\n", fd)); ++_gfs_file_buf[fd]->u.d->readcount; } int gfs_hook_is_read(int fd) { return (_gfs_file_buf[fd]->u.d->readcount > 0); } void gfs_hook_set_suspended_gfs_dirent(int fd, struct gfs_dirent *entry) { _gfs_file_buf[fd]->u.d->suspended = entry; } struct gfs_dirent * gfs_hook_get_suspended_gfs_dirent(int fd) { return (_gfs_file_buf[fd]->u.d->suspended); } struct gfs_stat * gfs_hook_get_gfs_stat(int fd) { return (&_gfs_file_buf[fd]->u.d->gst); } char * gfs_hook_get_gfs_canonical_path(int fd) { return (_gfs_file_buf[fd]->u.d->canonical_path); } /* * Check whether pathname is gfarm url or not. * * Gfarm URL: gfarm:[:section:]pathname * * It is necessary to free the memory space for *url. * Also, it's necessary to free the memory space for *secp, * if *secp is not NULL. */ static char gfs_mntdir[] = "/gfarm"; extern int gfs_hook_cwd_is_gfarm; static char *received_prefix = NULL; static int gfs_hook_is_null_or_slash(const char c) { return (c == '\0' || c == '/' || c == ':'); } static int gfs_hook_is_mount_point(const char *path) { return (*path == '/' && memcmp(path, gfs_mntdir, sizeof(gfs_mntdir) - 1) == 0 && gfs_hook_is_null_or_slash(path[sizeof(gfs_mntdir) - 1])); } static int set_received_prefix(const char *path) { char *end, *p; int len; if (received_prefix != NULL) { free(received_prefix); received_prefix = NULL; } if (gfs_hook_is_mount_point(path)) { received_prefix = strdup(gfs_mntdir); if (received_prefix == NULL) return (0); /* XXX - should return ENOMEM */ return (1); } /* path is either 'gfarm:' or 'gfarm@'. */ if ((end = strchr(path, ':')) == NULL) end = strchr(path, '@'); if (end == NULL) return (0); /* XXX */ len = end - path + 1; p = malloc(len + 1); if (p == NULL) return (0); /* XXX - should return ENOMEM */ received_prefix = p; strncpy(received_prefix, path, len); received_prefix[len] = '\0'; return (1); } /* * Gfarm path starts with '<mount_point>', 'gfarm:' or 'gfarm@'. * * When the Gfarm path starts with '<mount_point>', the path is * considered to be an absolute path instead of a relative path. * * '<mount_point>/~username' such as '/gfarm/~tatebe' can be used to * specify a home directory in Gfarm file system. */ int gfs_hook_is_url(const char *path, char **urlp, char **secp) { static char prefix[] = "gfarm:"; int sizeof_gfarm_prefix = sizeof(prefix); int sizeof_prefix = sizeof_gfarm_prefix; const char *path_save; int is_mount_point = 0, remove_slash = 0; /* * ROOT patch: * 'gfarm@' is also considered as a Gfarm URL */ static char gfarm_url_prefix_for_root[] = "gfarm@"; *secp = NULL; path_save = path; if (gfs_hook_is_mount_point(path)) { is_mount_point = 1; sizeof_prefix = sizeof(gfs_mntdir); } if (is_mount_point || gfarm_is_url(path) || /* ROOT patch */ memcmp(path, gfarm_url_prefix_for_root, sizeof(gfarm_url_prefix_for_root) - 1) == 0) { if (!gfarm_initialized && gfs_hook_initialize() != NULL) { gfs_hook_not_initialized(); return (0); /* don't perform gfarm operation */ } /* * extension for accessing individual sections * gfarm::section:pathname */ if (path[sizeof_prefix - 1] == ':') { const char *p = path + sizeof_prefix; int secsize = strcspn(p, "/:"); int urlsize; if (p[secsize] != ':') return (0); /* gfarm::foo/:bar or gfarm::foo */ /* '/gfarm/~' will be translated to 'gfarm:~'. */ if (is_mount_point && p[secsize + 1] == '/' && p[secsize + 2] == '~') remove_slash = 1; urlsize = sizeof_gfarm_prefix - 1 + strlen(p + secsize + remove_slash + 1); *urlp = malloc(urlsize + 1); *secp = malloc(secsize + 1); if (*urlp == NULL || *secp == NULL) { if (*urlp != NULL) free(*urlp); if (*secp != NULL) free(*secp); return (0); /* XXX - should return ENOMEM */ } memcpy(*urlp, prefix, sizeof_gfarm_prefix - 1); strcpy(*urlp + sizeof_gfarm_prefix - 1, p + secsize + remove_slash + 1); memcpy(*secp, p, secsize); (*secp)[secsize] = '\0'; /* * This case needs to free memory space of * both *urlp and *secp. */ } else { /* '/gfarm/~' will be translated to 'gfarm:~'. */ if (is_mount_point && path[sizeof_prefix - 1] == '/' && path[sizeof_prefix] == '~') remove_slash = 1; *urlp = malloc(sizeof_gfarm_prefix - 1 + strlen(path + sizeof_prefix + remove_slash - 1) + 1); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ /* * the reason why we don't just call strcpy(*url, path) * is because the path may be "gfarm@path/name". * (ROOT patch) */ memcpy(*urlp, prefix, sizeof_gfarm_prefix - 1); strcpy(*urlp + sizeof_gfarm_prefix - 1, path + sizeof_prefix + remove_slash - 1); } if (!set_received_prefix(path_save)) return (0); return (1); } if (gfs_hook_cwd_is_gfarm && *path_save != '/') { *urlp = malloc(strlen(prefix) + strlen(path_save) + 1); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ memcpy(*urlp, prefix, sizeof_prefix - 1); strcpy(*urlp + sizeof_prefix - 1, path_save); return (1); } return (0); } char * gfs_hook_get_prefix(char *buf, size_t size) { if (received_prefix == NULL) return GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING; if (size < strlen(received_prefix)) return GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE; strcpy(buf, received_prefix); return (NULL); } /* * default file view manipulation */ enum gfs_hook_file_view _gfs_hook_default_view = local_view; int _gfs_hook_index = 0; int _gfs_hook_num_fragments = GFARM_FILE_DONTCARE; void gfs_hook_set_default_view_local() { _gfs_hook_default_view = local_view; } void gfs_hook_set_default_view_index(int index, int nfrags) { _gfs_hook_default_view = index_view; _gfs_hook_index = index; _gfs_hook_num_fragments = nfrags; } void gfs_hook_set_default_view_global() { _gfs_hook_default_view = global_view; } char * gfs_hook_set_view_local(int filedes, int flag) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_local(gf, flag)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_index(int filedes, int nfrags, int index, char *host, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_index(gf, nfrags, index, host, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_global(int filedes, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_global(gf, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_global: %s\n", e)); return e; } return NULL; } <file_sep>/gfarm/branches/gfarm/gftool/config-gfarm/sysdep/linux/debian/gfmd.in #! /bin/bash # # gfmd Start the gfmd server. # PATH=/sbin:/bin:/usr/sbin:/usr/bin NAME=gfmd DAEMON=/usr/sbin/$NAME PIDFILE=/var/run/$NAME.pid CONF=/etc/gfarm.conf trap "" 1 export LANG=C export PATH test -f $DAEMON || exit 0 test -f $CONF || exit 0 case "$1" in start) echo -n "Starting gfarm server: $NAME" start-stop-daemon --start \ --pidfile $PIDFILE --exec $DAEMON -- -P $PIDFILE echo "." ;; stop) echo -n "Stopping gfarm server: $NAME" start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON echo "." ;; restart|force-reload) $0 stop $0 start ;; *) echo "Usage: /etc/init.d/$NAME {start|stop|restart}" exit 1 ;; esac exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4/makes/script.mk all: script-all post-all-hook install: all script-install post-install-hook clean: script-clean post-clean-hook veryclean: script-veryclean post-veryclean-hook distclean: script-distclean post-distclean-hook gfregister: script-gfregister post-gfregister-hook man: script-man post-man-hook html: script-html post-html-hook post-all-hook: post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: script-all: script-install: @set -x; \ for i in -- $(SCRIPTS); do \ case $$i in --) continue;; esac; \ $(INSTALL_SCRIPT) $$i $(bindir)/`basename $$i`; \ done script-clean: -test -z "$(EXTRA_CLEAN_TARGETS)" || $(RM) -f $(EXTRA_CLEAN_TARGETS) script-veryclean: clean -test -z "$(EXTRA_VERYCLEAN_TARGETS)" || $(RM) -f $(EXTRA_VERYCLEAN_TARGETS) script-distclean: veryclean -test ! -f $(srcdir)/Makefile.in || $(RM) -f Makefile script-gfregister: script-man: script-html: <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/include/gfarm/Makefile top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk includedir=$(default_includedir)/gfarm exec_includedir=$(default_exec_includedir)/gfarm EXEC_INCS= gfarm_config.h INCS= gfarm.h gfarm_error.h gfarm_metadb.h gfarm_misc.h gfarm_stringlist.h \ gfs.h gfs_glob.h \ gfs_hook.h include $(top_srcdir)/makes/include.mk <file_sep>/gfarmfs-fuse/trunk/contrib/mount.gfarmfs/mount.gfarmfs #!/bin/sh # # $Id$ USAGE() { cat <<EOF mount.gfarmfs [ username mount_point options ] Environment variable: GFS_USERNAME global user name in Gfarm (default: $LOGNAME) GFS_MOUNTDIR mount point (default: /gfs/home/$GFS_USERNAME) GFARMFS_ROOT directory to be mounted in Gfarm (default: /$GFS_USERNAME) GFARMFS_OPTIONS gfarmfs mount options (default: -lsu) FUSE_OPTIONS fuse mount options EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then GFS_USERNAME=$1 shift fi if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi if [ $# -gt 0 ]; then FUSE_OPTIONS=$* fi : ${GFS_USERNAME:=`gfwhoami 2> /dev/null`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2> /dev/null`} : ${GFS_MOUNTDIR:=/gfs/home/$GFS_USERNAME} : ${GFARMFS_ROOT:=/$GFS_USERNAME} : ${GFARMFS_OPTIONS:=-lsu} : ${FUSE_OPTIONS:=} # XXX - need sanity check for GFS_USERNAME DELETE_MOUNTDIR_ON_ERROR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR_ON_ERROR=1 fi [ -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME # if already mounted, exit grep $GFS_MOUNTDIR /etc/mtab > /dev/null && exit 0 gfarmfs -m $GFARMFS_ROOT $GFARMFS_OPTIONS $GFS_MOUNTDIR $FUSE_OPTIONS STATUS=$? if [ $STATUS = 0 ]; then echo Mount GfarmFS on $GFS_MOUNTDIR else [ $DELETE_MOUNTDIR_ON_ERROR = 1 ] && rmdir $GFS_MOUNTDIR fi exit $STATUS <file_sep>/gfarm/tags/gfarm_0_1/makes/var.mk include $(top_objdir)/makes/config.mk RM = rm COMMON_CFLAGS = $(OPTFLAGS) $(largefile_cflags) -I$(top_objdir) -I$(INCDIR) COMMON_LDFLAGS = $(largefile_ldflags) INCDIR = $(top_srcdir)/include GFSL_DIR = $(top_srcdir)/lib/libgfsl GFD_DIR = $(top_srcdir)/gfarmd GFSD_DIR = $(top_srcdir)/gfsd GFARMLIB_DIR = $(top_srcdir)/gfarmlib GFSL_INCLUDES = -I$(GFSL_DIR) GFSL_LIBS = -L$(top_objdir)/lib/libgfsl -lgfsl DEPGFSLLIB = $(top_objdir)/lib/libgfsl/libgfsl.a DEPGFSLINC = $(GFSL_DIR)/gfarm_auth.h $(GFSL_DIR)/gfarm_gsi.h $(GFSL_DIR)/gfarm_secure_session.h NSLIB = -L$(top_objdir)/nslib -lns DEPNSLIB = $(top_objdir)/nslib/libns.a GFARMLIB = -L$(top_objdir)/gfarmlib -lgfarm \ $(metadb_client_libs) $(gfsl_libs) $(openssl_libs) DEPGFARMLIB = $(top_objdir)/gfarmlib/libgfarm.a $(depgfsllib) DEPGFARMINC = $(INCDIR)/gfarm.h $(INCDIR)/gfarm_error.h $(INCDIR)/gfarm_metadb.h $(INCDIR)/gfarm_misc.h $(INCDIR)/gfs.h <file_sep>/gfarm/tags/gfarm_1_0_beta_1/gftool/gfrm/gfrm.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfrm"; void usage() { fprintf(stderr, "Usage: %s [ -h <host> ] <gfarm_url>...\n", program_name); fprintf(stderr, " %s -I <fragment> -h <host> <gfarm_url>...\n", program_name); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *section = NULL; int ch, nhosts = 0; char **hosttab; gfarm_stringlist host_list; int o_force = 0; gfarm_stringlist paths; gfs_glob_t types; int i; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_stringlist_init(&host_list); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((ch = getopt(argc, argv, "h:I:fr")) != -1) { switch (ch) { case 'h': e = gfarm_stringlist_add(&host_list, optarg); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } ++nhosts; break; case 'f': o_force = 1; break; case 'I': section = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { fprintf(stderr, "%s: too few arguments\n", program_name); exit(1); } e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); if (section == NULL) { if (nhosts == 0) { /* remove a whole file */ for (i = 0; i < gfarm_stringlist_length(&paths); i++) { e = gfs_unlink(gfarm_stringlist_elem( &paths, i)); if (e != NULL) fprintf(stderr, "%s: %s\n", gfarm_stringlist_elem( &paths, i), e); } } else { /* * remove file replicas of a whole file * on a specified node. */ int i, j; hosttab = gfarm_strings_alloc_from_stringlist( &host_list); gfarm_stringlist_free(&host_list); for (j = 0; j < nhosts; j++) { for (i = 0; i < gfarm_stringlist_length(&paths); i++) { e = gfs_unlink_replicas_on_host( gfarm_stringlist_elem(&paths, i), hosttab[j], o_force); if (e != NULL) fprintf(stderr, "%s: %s\n", gfarm_stringlist_elem( &paths, i), e); } } } } else { int i; /* remove a file fragment */ if (nhosts == 0) { fprintf(stderr, "%s: -h option should be specified\n", program_name); exit(1); } /* assert(nhosts == gfarm_stringlist_length(&host_list)); */ hosttab = gfarm_strings_alloc_from_stringlist(&host_list); gfarm_stringlist_free(&host_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { e = gfs_unlink_section_replica( gfarm_stringlist_elem(&paths,i), section, nhosts, hosttab, o_force); if (e != NULL) fprintf(stderr, "%s: %s\n", gfarm_stringlist_elem(&paths, i), e); } } gfs_glob_free(&types); gfarm_stringlist_free_deeply(&paths); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/branches/metadb_dev/makes/man.mk all: man-all post-all-hook install: man-install post-install-hook clean: man-clean post-clean-hook veryclean: man-veryclean post-very-clean-hook distclean: man-distclean post-distclean-hook post-all-hook: post-install-hook: post-clean-hook: post-very-clean-hook: post-distclean-hook: man-all: man-install: @for i in / $(MAN); do \ case $$i in /) continue;; esac; \ suffix=`expr $$i : '.*\.\([^.]*\)$$'`; \ ( set -x; $(INSTALL_DATA) $$i $(mandir)/man$$suffix/$$i ); \ done man-clean: -rm -f $(EXTRA_CLEAN_TARGETS) man-veryclean: clean -rm -f $(EXTRA_VERYCLEAN_TARGETS) man-distclean: veryclean if [ -f $(srcdir)/Makefile.in ]; then rm -f Makefile; fi <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/gftool/gfpwd/gfpwd.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> char *program_name = "gfpwd"; int main(int argc, char **argv) { char *e, *path; if (argc > 0) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_realpath(".", &path); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } printf("%s\n", path); return (0); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/include/gfarm/gfs_glob.h typedef struct { unsigned char *array; int length, size; } gfs_glob_t; #define GFS_GLOB_ARRAY(glob) (glob).array #define GFS_GLOB_ELEM(glob, i) (glob).array[i] #define gfs_glob_length(glob) (glob)->length #define gfs_glob_elem(glob, i) \ GFS_GLOB_ELEM(*(glob), i) char *gfs_glob(char *, gfarm_stringlist *, gfs_glob_t *); char *gfs_glob_init(gfs_glob_t *); void gfs_glob_free(gfs_glob_t *); char *gfs_glob_add(gfs_glob_t *, int); <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT-unconfig #! /bin/sh . ./FT-common I=1 while [ "X`eval echo \\$client$I`" != X ]; do $gfservice unconfig-client client$I I=`expr $I + 1` done I=1 while [ "X`eval echo \\$gfsd$I`" != X ]; do $gfservice unconfig-gfsd gfsd$I I=`expr $I + 1` done I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice unconfig-gfarm gfmd$I I=`expr $I + 1` done <file_sep>/gfarm/tags/gfarm_0_1/gftool/gfrep/gfrep.c #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfreplicate"; void usage() { fprintf(stderr, "Usage: %s [option] <gfarm_url>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-H <hostfile>\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *hostfile = NULL; int ch, nhosts, error_line; char **hosttab; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "H:")) != -1) { switch (ch) { case 'H': hostfile = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc != 1) usage(); e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (hostfile == NULL) { fprintf(stderr, "%s: -H <hostfile> option is required\n", program_name); exit(1); } e = gfarm_hostlist_read(hostfile, &nhosts, &hosttab, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: line %d: %s\n", hostfile, error_line, e); else fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_url_fragments_replicate(argv[0], nhosts, hosttab); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[0], e); exit(1); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfsl/gfsl_config.h #ifndef _GFARM_GFSL_CONFIG_H_ #define _GFARM_GFSL_CONFIG_H_ #define USE_GLOBUS #if defined(USE_GLOBUS) && GLOBUS_BUG /* currently Globus doesn't actually support GSS_C_NT_USER_NAME */ #define GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS 1 #else #define GFARM_FAKE_GSS_C_NT_USER_NAME_FOR_GLOBUS 0 #endif /* defined(USE_GLOBUS) && GLOBUS_BUG */ #ifdef USE_GLOBUS /* draft-engert-ggf-gss-extensions @ IETF & draft-ggf-gss-extensions @ GGF */ # define GFARM_GSS_EXPORT_CRED_ENABLED 1 #else # define GFARM_GSS_EXPORT_CRED_ENABLED 0 #endif /* USE_GLOBUS */ #if 0 /* defined(USE_GLOBUS) */ /* Now, Globus GSSAPI supports encryption */ /* * Exportable version of Globus GSSAPI did not support confidentiality * security service. */ # define GFARM_GSS_ENCRYPTION_ENABLED 0 #else # define GFARM_GSS_ENCRYPTION_ENABLED 1 #endif /* USE_GLOBUS */ #if GFARM_GSS_ENCRYPTION_ENABLED # define GFARM_GSS_C_CONF_FLAG GSS_C_CONF_FLAG #else # define GFARM_GSS_C_CONF_FLAG 0 # ifdef USE_GLOBUS # ifndef GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG # define GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG 1 # endif /* GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG */ # define GFARM_GSS_DEFAULT_QOP GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG # endif /* USE_GLOBUS */ #endif /* GFARM_GSS_ENCRYPTION_ENABLED */ #ifndef GFARM_GSS_DEFAULT_QOP #define GFARM_GSS_DEFAULT_QOP GSS_C_QOP_DEFAULT #endif #define GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG \ (OM_uint32)(GSS_C_DELEG_FLAG | /* delegation */ \ GSS_C_MUTUAL_FLAG | /* mutual authentication */ \ GSS_C_REPLAY_FLAG | /* reply message detection */ \ GSS_C_SEQUENCE_FLAG | /* out of sequence detection */ \ GFARM_GSS_C_CONF_FLAG | /* confidentiality service */ \ GSS_C_INTEG_FLAG /* integrity check service */ \ ) #define GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE 8 * 1024 * 1024 #define GFARM_DEFAULT_INITIATOR_CONFIG_FILE "gfarm-initiator.conf" #define GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE "gfarm-acceptor.conf" #define GFARM_DEFAULT_INSTALL_ETC_DIR "etc" #ifndef GFARM_INSTALL_ETC_DIR #define GFARM_INSTALL_ETC_DIR "/etc" #endif /* GFARM_INSTALL_ETC_DIR */ #ifndef GFARM_INSTALL_DIR_ENV #define GFARM_INSTALL_DIR_ENV "GFARM_HOME" #endif /* GFARM_INSTALL_DIR_ENV */ #define GFARM_DEFAULT_USERMAP_FILE "gfarm-usermap" /* XXX - This depends on globus implementation - GLOBUS_SUCCESS (== 0) */ #define GFSL_DEFAULT_MINOR_ERROR 0 #define GFARM_GSS_AUTH_TIMEOUT 60 /* seconds */ #endif /* _GFARM_GFSL_CONFIG_H_ */ <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/scarg.h #define COMMON_OPTIONS "p:H:M:Nn:U:u" extern int port; extern int acceptorSpecified; extern char *acceptorNameString; extern gss_OID acceptorNameType; int HandleCommonOptions(int, char *); <file_sep>/gfarm/tags/gfarm_1_0_4/lib/libgfarm/gfutil/limit.c #include <gfarm/gfarm_config.h> #include <sys/types.h> #ifdef HAVE_SETRLIMIT #include <sys/time.h> #include <sys/resource.h> #endif #include "gfutil.h" /* * - Unlimit file descriptors. * - Returns numbers of file descriptors to *file_table_size_p, * if it is available, otherwise do not touch that. */ void gfarm_unlimit_nofiles(int *file_table_size_p) { #ifdef HAVE_SETRLIMIT struct rlimit limit; if (getrlimit(RLIMIT_NOFILE, &limit) == -1) { gflog_warning_errno("getrlimit"); return; } if (limit.rlim_cur != limit.rlim_max) { /* do not use rlim_t here, because rlim_t is not portable */ struct rlimit save_current = limit; limit.rlim_cur = limit.rlim_max; if (setrlimit(RLIMIT_NOFILE, &limit) == -1) { limit = save_current; gflog_warning_errno("setrlimit"); } } if (limit.rlim_cur != RLIM_INFINITY) *file_table_size_p = limit.rlim_cur; #endif } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT1-2-2-5_gfmd_warning_and_error #! /bin/sh ###################################################################### TESTID="FT1-2-2-5" CATEGORY="accident causes no failover" SECTION="mds accident" TITLE="gfmd warning and error" ###################################################################### . ./FT-common ft_setup() { zabbix_sender -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<err>",UTF-8]' -o RECOVERED zabbix_sender -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<warning>",UTF-8]' -o RECOVERED return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfmd1 logger -p $FT_SYSLOG_FACILITY.err -t \ "gfmd[9999]" "\<err\> unknown error" && \ ssh $gfmd1 logger -p $FT_SYSLOG_FACILITY.warning \ -t "gfmd[9999]" "\<warning\> unknown warning" || \ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd error message in /var/log/messages on $gfmd1" &&\ ft_check_mail "gfmd warning message in /var/log/messages on $gfmd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT zabbix_sender -v -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<err>",UTF-8]' -o RECOVERED zabbix_sender -v -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<warning>",UTF-8]' -o RECOVERED || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "clear log" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd error message in /var/log/messages on $gfmd1" &&\ ft_check_mail "Re: gfmd warning message in /var/log/messages on $gfmd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { zabbix_sender -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<err>",UTF-8]' -o RECOVERED zabbix_sender -z $zabbix1 -s $gfmd1 -k 'log[{$GFARM_LOGFILE},"\sgfmd\[[0-9]+\]:\s+<warning>",UTF-8]' -o RECOVERED return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/branches/gfarm/gftool/config-gfarm/config-gfarm.in #!/bin/sh # # $Id$ [ ${DEBUG:="off"} = off ] || set -xu PROGNAME=`basename $0` usage() { echo 1>&2 "usage: $PROGNAME [--prefix prefix] [-t] [-f]" echo 1>&2 " [-d domain_name] [-h hostname]" echo 1>&2 " [-V openldap_version] [-l metadata_directory]" echo 1>&2 " [-p slapd_port] [-s gfsd_port] [-m gfmd_port]" exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* echo "$PROGNAME failure" exit 1 } display_params() { echo "prefix [--prefix]: $CONFIG_PREFIX" echo "domain name [-d]: $DOMAIN_NAME" echo "openldap version [-V]: $OPENLDAP_VERSION" echo "metadata directory [-l]: $LDAP_DATADIRECTORY" echo "metaserver hostname [-h]: $SLAPD_HOSTNAME" echo "slapd port [-p]: $SLAPD_PORT" echo "gfmd port [-m]: $GFMD_PORT" echo "gfsd port [-s]: $GFSD_PORT" echo 'slapd DB type ($SLAPD_DB): ' "$SLAPD_DB" exit 0 } # default value : ${CONFIG_PREFIX:=} : ${DOMAIN_NAME:=`dnsdomainname`} [ X$DOMAIN_NAME = X ] && ABORT : ${OPENLDAP_VERSION:="2.1"} : ${OPENLDAP_LIBEXEC:="/usr/sbin"} : ${OPENLDAP_ETC:="/etc/openldap"} : ${SLAPD_HOSTNAME:="`hostname -f`"} : ${SLAPD_PORT:="389"} [ X$SLAPD_HOSTNAME = X ] && ABORT : ${GFMD_PORT:="601"} : ${GFSD_PORT:="600"} : ${FORCE:="0"} : ${DISPLAY_PARAMS:="0"} while [ $# -gt 0 ] ; do case $1 in --prefix) shift; [ $# -ge 1 ] || usage CONFIG_PREFIX=$1 ;; -d) shift; [ $# -ge 1 ] || usage DOMAIN_NAME=$1 ;; -f) FORCE=1 ;; -l) shift; [ $# -ge 1 ] || usage LDAP_DATADIRECTORY=$1 ;; -m) shift; [ $# -ge 1 ] || usage GFMD_PORT=$1 ;; -h) shift; [ $# -ge 1 ] || usage SLAPD_HOSTNAME=$1 ;; -p) shift; [ $# -ge 1 ] || usage SLAPD_PORT=$1 ;; -s) shift; [ $# -ge 1 ] || usage GFSD_PORT=$1 ;; -t) DISPLAY_PARAMS=1 ;; -V) shift; [ $# -ge 1 ] || usage OPENLDAP_VERSION=$1 ;; *) usage ;; esac shift done if [ $OPENLDAP_VERSION \> 2.1 -o $OPENLDAP_VERSION = 2.1 ]; then : ${SLAPD_DB:="bdb"} else : ${SLAPD_DB:="ldbm"} fi : ${GFARM_LDAP:="$CONFIG_PREFIX/etc/gfarm-ldap"} : ${SLAPD_CONF:="$GFARM_LDAP/slapd.conf"} : ${LDAP_DATADIRECTORY:="$CONFIG_PREFIX/var/gfarm-ldap"} : ${INITIAL_LDIF:="$GFARM_LDAP/initial.ldif"} : ${GFARM_CONF_SCRIPT:="$GFARM_LDAP/config.script"} : ${GFARM_CONF:="$CONFIG_PREFIX/etc/gfarm.conf"} : ${ETC_INITD:="$CONFIG_PREFIX/etc/init.d"} : ${VAR_RUND:="$CONFIG_PREFIX/var/run"} : ${VAR_LOCKD:="$CONFIG_PREFIX/var/lock/subsys"} : ${DO_NOT_START_SERVICE:="0"} # Gfarm installation directory prefix=@prefix@ SUFFIX="dc=`echo ${DOMAIN_NAME} | sed -ne 's/\./, dc=/pg'`" ROOTDN="cn=root, ${SUFFIX}" DC=`echo ${DOMAIN_NAME} | awk -F '.' '{print $1}'` [ X"$SUFFIX" = X -o X"$ROOTDN" = X -o X"$DC" = X ] && ABORT # -t option; display parameters [ X$DISPLAY_PARAMS = X1 ] && display_params ######################################################################### mkcnf_config_script() { cat <<EOF s/@config_gfarm_suffix@/$SUFFIX/ s/@config_gfarm_rootdn@/$ROOTDN/ s/@config_gfarm_dc@/$DC/ s,@config_gfarm_prefix@,@prefix@, s,@config_gfarm_gfarm_config@,$GFARM_CONF, s,@config_gfarm_slapd_hostname@,$SLAPD_HOSTNAME, s,@config_gfarm_slapd_port@,$SLAPD_PORT, s,@config_gfarm_slapd_config@,$SLAPD_CONF, s,@config_gfarm_slapd_database@,$SLAPD_DB, s,@config_gfarm_openldap_libexec@,$OPENLDAP_LIBEXEC, s,@config_gfarm_openldap_etc@,$OPENLDAP_ETC, s,@config_gfarm_ldap_directory@,$LDAP_DATADIRECTORY, s,@config_gfarm_gfmd_port@,$GFMD_PORT, s,@config_gfarm_gfmd_option@,"-f $GFARM_CONF", s,@config_gfarm_gfsd_port@,$GFSD_PORT, s,@config_gfarm_gfsd_option@,"-f $GFARM_CONF", s,@config_gfarm_run_dir@,$VAR_RUND, s,@config_gfarm_lock_dir@,$VAR_LOCKD, EOF } mkcnf_initial_ldif() { cat << initial_ldif_EOF dn: $SUFFIX objectclass: dcObject objectclass: organization objectclass: top dc: $DC o: Gfarm file system initial_ldif_EOF } mkcnf_slapd_conf() { if [ $OPENLDAP_VERSION \> 2.1 -o $OPENLDAP_VERSION = 2.1 ]; then SLAPD_CONF_IN=slapd.conf-2.1.in else SLAPD_CONF_IN=slapd.conf-2.0.in fi sed -f $GFARM_CONF_SCRIPT @datadir@/gfarm/config/$SLAPD_CONF_IN } mkcnf_dbconfig() { cachesize=` awk '$1 == "MemTotal:" {print int($2/2/8)*8*1024}' /proc/meminfo` [ -n "$cachesize" ] && echo "set_cachesize 0 $cachesize 1" echo "set_flags DB_TXN_NOSYNC" } mkcnf_gfarm_conf() { sed -f $GFARM_CONF_SCRIPT @datadir@/gfarm/config/gfarm.conf.in } mkscript_gfarm_slapd() { sed -f $GFARM_CONF_SCRIPT @datadir@/gfarm/config/gfarm-slapd.in } mkscript_gfmd() { sed -f $GFARM_CONF_SCRIPT @datadir@/gfarm/config/gfmd.in } mkcnf() { [ $# -eq 2 ] && $1 > $2 && echo create $2 } mkscript() { [ $# -eq 2 ] && $1 > $2 && chmod +x $2 && echo create $2 } ######################################################################### delete_file_or_directory() { while [ $# -gt 0 ] ; do if [ -e $1 ]; then if [ X$FORCE = X0 ]; then ABORT "$PROGNAME: $1 already exist" else rm -rf $1 fi fi shift done } delete_file_or_directory $LDAP_DATADIRECTORY $GFARM_CONF $ETC_INITD/gfarm-slapd # make directory create_directory() { [ $# -gt 0 ] && mkdir -p $* && echo create $* } create_directory $LDAP_DATADIRECTORY || ABORT "$PROGNAME: mkdir $LDAP_DATADIRECTORY, failed" mkdir_list="" for x in $GFARM_LDAP $ETC_INITD $VAR_RUND $VAR_LOCKD; do if [ ! -d $x ] ; then rm -rf $x > /dev/null 2>&1 mkdir_list="$mkdir_list $x" fi done [ -z "$mkdir_list" ] || create_directory $mkdir_list || ABORT "$PROGNAME: mkdir $mkdir_list, failed" # create configuration file mkcnf mkcnf_config_script $GFARM_CONF_SCRIPT || ABORT "$PROGNAME: cannot create configuration script" mkcnf mkcnf_initial_ldif $INITIAL_LDIF && mkcnf mkcnf_slapd_conf $SLAPD_CONF && mkcnf mkcnf_gfarm_conf $GFARM_CONF || ABORT "$PROGNAME: cannot create configuration file" # add initial data if [ X"$SLAPD_DB" = Xbdb ]; then if [ ! -f $GFARM_LDAP/DB_CONFIG ]; then mkcnf mkcnf_dbconfig $GFARM_LDAP/DB_CONFIG || ABORT "$PROGNAME: cannot create $GFARM_LDAP/DB_CONFIG" fi cp -a $GFARM_LDAP/DB_CONFIG $LDAP_DATADIRECTORY fi slapadd -f $SLAPD_CONF -l $INITIAL_LDIF && echo add initial metadata || ABORT "$PROGNAME: cannot add initial metadata" # create run script for gfarm-slapd mkscript mkscript_gfarm_slapd $ETC_INITD/gfarm-slapd || ABORT "$PROGNAME: cannot create $ETC_INITD/gfarm-slapd" # if [ X"$DO_NOT_START_SERVICE" = X1 ]; then echo "$PROGNAME success" exit 0 fi if [ X`id -u` = X0 -a X$CONFIG_PREFIX = X ]; then chkconfig gfarm-slapd --add && echo add gfarm-slapd service || ABORT "$PROGNAME: cannot add gfarm-slapd service" else echo add gfarm-slapd service: skipped fi if [ X`id -u` = X0 -a X$CONFIG_PREFIX = X ]; then service gfarm-slapd restart || ABORT "$PROGNAME: cannot start gfarm-slapd" else $ETC_INITD/gfarm-slapd restart || ABORT "$PROGNAME: cannot start gfarm-slapd" fi if [ X`id -u` = X0 -a X$CONFIG_PREFIX = X ]; then service gfmd restart || ABORT "$PROGNAME: cannot start gfmd" else # create run script for gfmd mkscript mkscript_gfmd $ETC_INITD/gfmd || ABORT "$PROGNAME: cannot create $ETC_INITD/gfmd" $ETC_INITD/gfmd restart || ABORT "$PROGNAME: cannot start gfmd" fi error=$? [ $error = 0 ] && echo "$PROGNAME success" || echo "$PROGNAME failure" exit $error <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT1-2-3-1_gfsd_down #! /bin/sh ###################################################################### TESTID="FT1-2-3-1" CATEGORY="accident causes no failover" SECTION="fsn accident" TITLE="gfsd down" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfsd gfsd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfsd on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfsd is not running on $gfsd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox $gfservice start-gfsd gfsd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "start gfsd on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfsd is not running on $gfsd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { $gfservice start-gfsd gfsd1 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_represent_client_gfhost.sh.in #! /bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on a representative client host. # It tries executing 'gfhost' to check whether it can connect with # other gfsd servers and succeeds in authentication. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile=/tmp/gfarm_represent_client_gfhost.out.$$ errfile=/tmp/gfarm_represent_client_gfhost.err.$$ trap "rm -f $outfile $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile $errfile # # Execute 'gfhost'. # GFCMD="@GFARM_BINDIR@/gfhost -lv" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > $outfile 2> $errfile GFCMD_EXITCODE=$? if [ $GFCMD_EXITCODE -ne 0 ]; then if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then echo "'$GFCMD' failed, timeout" log_err "'$GFCMD' failed, timeout" else echo "'$GFCMD' failed" log_err "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" fi [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi # # Check whether 'gfhost' outputs a list of servers correctly. # if [ ! -s $outfile ]; then echo "ok" log_warning "'$GFCMD' outputs no data" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi # # Check the result data of 'gfhost'. # awk ' BEGIN { unreachable_gfsds = "" auth_fail_gfsds = "" } { if ($1 == "x.xx/x.xx/x.xx" || $1 == "-.--/-.--/-.--") { if (unreachable_gfsds == "") unreachable_gfsds = $5 else unreachable_gfsds = unreachable_gfsds ", " $5 } else if ($2 == "x") { if (auth_fail_gfsds == "") auth_fail_gfsds = $5 else auth_fail_gfsds = auth_fail_gfsds ", " $5 } } END { if (unreachable_gfsds != "") print "unreachable: " unreachable_gfsds else if (auth_fail_gfsds != "") print "auth failed: " auth_fail_gfsds else print "ok" }' $outfile rm -f $outfile $errfile exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/install-agentd.sh #! /bin/sh # # Install the 'gfarm_zabbix' package for Zabbix agent. # . ./install.conf # install(1) command. INSTALL=install # # Create "$1" file from "$1.in". # create_file() { [ -f "$1" ] && rm -f "$1" sed -e "s|@ZABBIX_CONFDIR@|$ZABBIX_CONFDIR|g" \ -e "s|@ZABBIX_AGENTD_PIDFILE@|$ZABBIX_AGENTD_PIDFILE|g" \ -e "s|@ZABBIX_AGENTD_LOGFILE@|$ZABBIX_AGENTD_LOGFILE|g" \ -e "s|@SYSLOG_FILE@|$SYSLOG_FILE|g" \ -e "s|@ZABBIX_EXTSCRIPTDIR@|$ZABBIX_EXTSCRIPTDIR|g" \ -e "s|@ZABBIX_ALERTSCRIPTDIR@|$ZABBIX_ALERTSCRIPTDIR|g" \ -e "s|@GFARM_BINDIR@|$GFARM_BINDIR|g" \ -e "s|@ZABBIX_AGENTD_CONFSUBDIR@|$ZABBIX_AGENTD_CONFSUBDIR|g" \ -e "s|@ZABBIX_SERVER@|$ZABBIX_SERVER|g" \ -e "s|@ZABBIX_AGENT_HOSTNAME@|$ZABBIX_AGENT_HOSTNAME|g" \ -e "s|@GFMD_PIDFILE@|$GFMD_PIDFILE|g" \ -e "s|@GFMD_JOURNALDIR@|$GFMD_JOURNALDIR|g" \ -e "s|@GFARM_DB_PORT@|$GFARM_DB_PORT|g" \ -e "s|@GFARM_DB_USER@|$GFARM_DB_USER|g" \ -e "s|@GFARM_DB_PASSWORD@|$GFARM_DB_PASSWORD|g" \ -e "s|@IOSTAT_DEVICE@|$IOSTAT_DEVICE|g" \ "$1.in" > "$1" } # # Make a directory '$ZABBIX_AGENTD_CONFSUBDIR'. # DIR=$ZABBIX_AGENTD_CONFSUBDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files in 'gfarm-zabbix_scripts/zabbix_agentd.d/' to # $ZABBIX_AGENTD_CONFSUBDIR. # for I in \ userparameter_postgresql.conf \ userparameter_redundant_gfarm.conf; do SRCFILE=gfarm-zabbix_scripts/zabbix_agentd.d/$I DSTFILE=$ZABBIX_AGENTD_CONFSUBDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Make a directory '$ZABBIX_EXTSCRIPTDIR'. # DIR=$ZABBIX_EXTSCRIPTDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files in 'gfarm-zabbix_scripts/externalscripts/' to # $ZABBIX_EXTSCRIPTDIR. # for I in \ zbx_chk_gfarm.conf \ zbx_chk_gfhost_cli.sh \ zbx_chk_gfhost_gfsd.sh \ zbx_chk_gfjournal_gfmd.sh \ zbx_chk_gfmdhost_cli.sh \ zbx_chk_gfmdlist_cli.sh \ zbx_chk_gfmdtype_gfmd.sh \ zbx_chk_gfquota_cli.sh \ zbx_chk_gfsched_gfmd.sh \ zbx_chk_gfsched_gfsd.sh \ zbx_chk_iostat.sh \ zbx_chk_mastername_cli.sh \ zbx_chk_ntp.sh \ zbx_chk_pgsql.sh \ zbx_chk_redundancy_cli.sh \ zbx_failover.sh \ zbx_gfarm2_mds_upgrade.sh; do SRCFILE=gfarm-zabbix_scripts/externalscripts/$I DSTFILE=$ZABBIX_EXTSCRIPTDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Install 'zabbix_agentd.conf.sample' file to $ZABBIX_CONFDIR. # FILE=zabbix_agentd.conf.sample SRCFILE=gfarm-zabbix_confs/zabbix/$FILE DSTFILE=$ZABBIX_CONFDIR/$FILE create_file $SRCFILE $INSTALL -c -m 0644 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" # # Create the directory of $ZABBIX_AGENTD_PIDFILE. # DIR=`dirname $ZABBIX_AGENTD_PIDFILE` if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o zabbix -g zabbix $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Create the directory of $ZABBIX_AGENTD_LOGFILE. # DIR=`dirname $ZABBIX_AGENTD_LOGFILE` if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o zabbix -g zabbix $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Change mode of $SYSLOG_FILE # chmod 0644 $SYSLOG_FILE \ && echo "Set mode (= 0644) of the file: $SYSLOG_FILE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_editor/save.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>'gfarm2.conf' editor</title> <style type="text/css" media="all"> p.center { text-align: center; } </style> </head> <body> <h1>'gfarm2.conf' editor</h1> <form> <p class="center"> <?php include('./common.php'); $result = TRUE; if (array_key_exists('conf', $_POST)) { if (!write_gfarm2_conf($_POST['conf'])) { print("Failed to update 'gfarm2.conf'."); $result = FALSE; } } else { print("No data.\n"); $result = FALSE; } print("<br><br>\n"); if ($result) { header("HTTP/1.1 303 See Other"); header("Location: index.php"); exit(); } else { print('<input type="button" onClick="history.back();" value="Back">'); print("\n"); } ?> </p> </form> </body> </html> <file_sep>/gfarm/branches/metadb_dev/gftool/gfkey/gfkey.c #include <stdio.h> #include <unistd.h> #include <libgen.h> #include <time.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "auth.h" char *program_name = "gfkey"; static void write_hex(FILE *fp, void *buffer, size_t length) { unsigned char *p = buffer; size_t i; for (i = 0; i < length; i++) fprintf(fp, "%02x", p[i]); } void usage() { fprintf(stderr, "Usage: %s [option]\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-c\tcreate new key, if doesn't exist or expired\n"); fprintf(stderr, "\t-f\tforce to create new key\n"); fprintf(stderr, "\t-l\tlist existing key\n"); fprintf(stderr, "\t-e\treport expire time\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern int optind; int ch, do_list = 0, do_expire_report = 0; char *e, *home; unsigned int expire; char shared_key[GFARM_AUTH_SHARED_KEY_LEN]; int mode = GFARM_AUTH_SHARED_KEY_GET; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "cefl")) != -1) { switch (ch) { case 'c': mode = GFARM_AUTH_SHARED_KEY_CREATE; break; case 'e': do_expire_report = 1; break; case 'f': mode = GFARM_AUTH_SHARED_KEY_CREATE_FORCE; break; case 'l': do_list = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc != 0 || (mode == GFARM_AUTH_SHARED_KEY_GET && !do_list && !do_expire_report)) usage(); gfarm_error_initialize(); e = gfarm_set_user_for_this_local_account(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } home = gfarm_get_local_homedir(); e = gfarm_auth_shared_key_get(&expire, shared_key, home, mode); if (e != NULL) { fprintf(stderr, "%s\n", e); exit(1); } if (do_list) { printf("%08x ", expire); write_hex(stdout, shared_key, GFARM_AUTH_SHARED_KEY_LEN); putc('\n', stdout); } if (do_expire_report) { time_t t = expire; printf("expire time is %s", ctime(&t)); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_rc4/lib/gfs_hook/hooks_subr.h /* convert symbol to string literal */ #define STRING(symbol) #symbol #define S(symbol) STRING(symbol) #ifdef DEBUG #include <stdio.h> extern int gfarm_node, gfarm_nnode; #define _gfs_hook_debug(x) x #define _gfs_hook_debug_v(x) #else #define _gfs_hook_debug(x) #define _gfs_hook_debug_v(x) #endif struct gfs_file; char *gfs_hook_initialize(void); int gfs_hook_insert_gfs_file(struct gfs_file *); int gfs_hook_clear_gfs_file(int); int gfs_hook_insert_filedes(int, struct gfs_file *); void gfs_hook_inc_refcount(int); struct gfs_file *gfs_hook_is_open(int); int gfs_hook_is_url(const char *, char **, char **); int __syscall_close(int); enum gfs_hook_file_view { local_view, index_view, global_view } _gfs_hook_default_view; extern int _gfs_hook_index; extern int _gfs_hook_num_fragments; struct stat; struct stat64; int gfs_hook_syscall_open(const char *, int, mode_t); int gfs_hook_syscall_xstat(int, const char *, struct stat *); int gfs_hook_syscall_lxstat(int, const char *, struct stat *); int gfs_hook_syscall_fxstat(int, int, struct stat *); int gfs_hook_syscall_xstat64(int, const char *, struct stat64 *); int gfs_hook_syscall_lxstat64(int, const char *, struct stat64 *); int gfs_hook_syscall_fxstat64(int, int, struct stat64 *); #ifdef _LARGEFILE64_SOURCE off64_t gfs_hook_syscall_lseek64(int, off64_t, int); #endif <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/lib/libgfarm/gfsl/gfarm_auth.h #ifndef _GFARM_AUTH_H_ #define _GFARM_AUTH_H_ /* * Authentication information struct */ typedef struct { int sesRefCount; /* Reference count (from sessions). */ int orphaned; /* 1 if this entry no longer exists in the * database and should be free'd when the * sesRefCount == 0. */ int authType; /* One of belows. */ #define GFARM_AUTH_HOST 0 #define GFARM_AUTH_USER 1 #define GFARM_AUTH_UNKNOWN -1 char *distName; /* Distinguish name for a user. Heap alloc'd. */ union { struct userAuthData { char *localName; /* Local user account name. Heap alloc'd. */ uid_t uid; gid_t gid; char *homeDir; /* Home directory. Heap alloc'd. */ char *loginShell; /* Login shell. Heap alloc'd. */ } userAuth; struct hostAuthData { char *FQDN; /* FQDN for the host. Heap alloc'd. */ } hostAuth; } authData; } gfarmAuthEntry; /* Prototypes. */ extern int gfarmAuthInitialize(char *usermapFile); extern void gfarmAuthFinalize(void); extern gfarmAuthEntry * gfarmAuthGetUserEntry(char *distUserName); extern void gfarmAuthDestroyUserEntry(gfarmAuthEntry *aePtr); extern void gfarmAuthMakeThisAlone(gfarmAuthEntry *laePtr); extern int gfarmAuthGetAuthEntryType(gfarmAuthEntry *aePtr); #endif /* _GFARM_AUTH_H_ */ <file_sep>/gfarm/tags/gfarm_1_0_3_1/makes/var.mk VPATH=$(srcdir) include $(top_objdir)/makes/config.mk ja_mandir = $(default_mandir)/ja # example_bindir = $(default_bindir)/example example_bindir = $(default_bindir) metadb_client_includes = $(ldap_includes) metadb_client_libs = $(ldap_libs) RM = rm COMMON_CFLAGS = $(OPTFLAGS) $(largefile_cflags) \ -I$(top_objdir)/include -I$(top_srcdir)/include COMMON_LDFLAGS = $(largefile_ldflags) GFARMLIB = -L$(top_objdir)/lib/libgfarm -lgfarm \ $(metadb_client_libs) $(globus_gssapi_libs) $(openssl_libs) INC_SRCDIR = $(top_srcdir)/include/gfarm INC_OBJDIR = $(top_objdir)/include/gfarm DEPGFARMLIB = $(top_objdir)/lib/libgfarm/libgfarm.a DEPGFARMINC = $(INC_OBJDIR)/gfarm_config.h $(INC_SRCDIR)/gfarm.h $(INC_SRCDIR)/gfarm_error.h $(INC_SRCDIR)/gfarm_metadb.h $(INC_SRCDIR)/gfarm_misc.h $(INC_SRCDIR)/gfarm_stringlist.h $(INC_SRCDIR)/gfs.h $(INC_SRCDIR)/gfs_glob.h # ns NS_COMMON_CFLAGS = $(OPTFLAGS) $(largefile_cflags) \ -I$(top_objdir)/include \ -I$(top_objdir)/ns/include -I$(top_srcdir)/ns/include NSLIB = -L$(top_objdir)/ns/nslib -lns NSEXECLIB = -L$(top_objdir)/ns/nslib -lnsexec NSINC_SRCDIR = $(top_srcdir)/ns/include/gfarm NSINC_OBJDIR = $(top_objdir)/ns/include/gfarm GFD_SRCDIR = $(top_srcdir)/ns/gfarmd DEPNSLIB = $(top_objdir)/ns/nslib/libns.a DEPNSEXECLIB = $(top_objdir)/ns/nslib/libnsexec.a # gfsl GFSL_SRCDIR = $(top_srcdir)/lib/libgfarm/gfsl DEPGFSLINC = $(GFSL_SRCDIR)/gfarm_auth.h $(GFSL_SRCDIR)/gfarm_gsi.h $(GFSL_SRCDIR)/gfarm_secure_session.h # libgfarm internal interface GFUTIL_SRCDIR = $(top_srcdir)/lib/libgfarm/gfutil GFARMLIB_SRCDIR = $(top_srcdir)/lib/libgfarm/gfarm # doc & man DOCBOOK2MAN = jw -b man DOCBOOK2HTML = jw -b html -u srcsubst = dummy dstsubst = dummy <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/auth_gsi.h char *gfarm_gsi_cred_config_convert_to_name_and_type( enum gfarm_auth_cred_type, char *, char *, char *, char **, gss_OID *, int *); void gfarm_gsi_set_delegated_cred(gss_cred_id_t); gss_cred_id_t gfarm_gsi_get_delegated_cred(void); <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/gfj_client.h /* * $Id */ struct gfarm_job_info { int total_nodes; char *user; char *job_type; char *originate_host; char *gfarm_url_for_scheduling; int argc; char **argv; /* per node information */ struct gfarm_job_node_info { char *hostname; int pid; enum gfarm_job_node_state { GFJ_NODE_NONE } state; } *nodes; }; void gfarm_job_info_clear(struct gfarm_job_info *, int); void gfarm_job_info_free_contents(struct gfarm_job_info *, int); struct gfm_connection; extern struct gfm_connection *gfarm_metadb_server; #define gfarm_jobmanager_server gfarm_metadb_server char *gfj_initialize(void); char *gfj_client_lock_register(struct gfm_connection *); char *gfj_client_unlock_register(struct gfm_connection *); char *gfj_client_register(struct gfm_connection *, struct gfarm_job_info *, int, int *job_idp); char *gfj_client_unregister(struct gfm_connection *, int); char *gfj_client_list(struct gfm_connection *, char *, int *, int **); char *gfj_client_info(struct gfm_connection *, int, int *, struct gfarm_job_info *); /* convenience function */ char *gfarm_user_job_register(int, char **, char *, char *, int, char **, int *); <file_sep>/gfarm/tags/gfarm_1_0_beta_3/util/gfront/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . javadir = $(prefix)/share/java include $(top_srcdir)/makes/var.mk # NOTE: We use current directory instead of $(srcdir) for the script # to be installed, because the script will be generated by configure. SCRIPTS= gfront JAR= gfront.jar all: install: @for i in / $(SCRIPTS); do \ case $$i in /) continue;; esac; \ ( set -x; $(INSTALL_PROGRAM) $${i} $(bindir)/$${i} ); \ done @for i in / $(JAR); do \ case $$i in /) continue;; esac; \ ( set -x; $(INSTALL_DATA) $(srcdir)/$${i} $(javadir)/$${i} ); \ done clean: veryclean: clean distclean: veryclean -rm -f gfront gfregister: man: html: <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT1-2-4-2_network_down_cn_to_all_fsn #! /bin/sh ###################################################################### TESTID="FT1-2-4-2" CATEGORY="accident causes no failover" SECTION="cn accident" TITLE="network down with cn to all fsn" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 sudo $IFDOWN_PATH $client1_GFARM_IF && \ ssh $client2 sudo $IFDOWN_PATH $client2_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Gfarm client node is not available on $client1" && \ ft_check_mail \ "Gfarm client node is not available on $client2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1_CTRL_ADDRESS sudo $IFUP_PATH $client1_GFARM_IF && \ ssh $client2_CTRL_ADDRESS sudo $IFUP_PATH $client2_GFARM_IF [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "ifup $gfsd2_GFARM_IF on $gfsd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail \ "Re: Gfarm client node is not available on $client1" && \ ft_check_mail \ "Re: Gfarm client node is not available on $client2" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $client1_CTRL_ADDRESS sudo $IFUP_PATH $client1_GFARM_IF ssh $client2_CTRL_ADDRESS sudo $IFUP_PATH $client2_GFARM_IF return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_dead_gfsd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo "error: ${CONF_FILE} does not exist." exit 0 fi c=0 while read prefix gfsdhost port listen_aadress; do initscript="${prefix}/etc/init.d/gfsd" if [ ! -z "${listen_aadress}" ]; then initscript="${prefix}/etc/init.d/gfsd-${listen_aadress}" fi if [ "`$initscript status | grep -c running`" -ne 1 ]; then echo "error: ${gfsdhost} is dead." c=`expr $c + 1` fi done<<EOF `parse_gfsd_confs "$1"` EOF if [ $c = 0 ]; then echo "ok" fi exit 0 <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_6/id.c /* * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <string.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm2fs.h" #include "id.h" #include "hash.h" #include "gfarm2fs_msg_enums.h" static struct gfarm_hash_table *hash_uid_to_user; static struct gfarm_hash_table *hash_gid_to_group; static struct gfarm_hash_table *hash_user_to_uid; static struct gfarm_hash_table *hash_group_to_gid; #include <signal.h> static volatile sig_atomic_t next_auto_uid; static volatile sig_atomic_t next_auto_gid; static uid_t auto_uid_min; static uid_t auto_uid_max; static gid_t auto_gid_min; static gid_t auto_gid_max; static int enable_cached_id = 0; /* for debug */ static int id_hash_index(const void *k, int l) { return (*(int *)k); } static int id_hash_equal(const void *k1, int k1len, const void *k2, int k2len) { return (*(gfarm_uint32_t *)k1 == *(gfarm_uint32_t *)k2); } static int primes[] = { 5, 11, 19, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209, 16411, 32771 }; static int next_prime(int n) { int i, nprimes = sizeof(primes) / sizeof(int); for (i = 0; i < nprimes; i++) if (primes[i] > n) return (primes[i]); return (primes[nprimes - 1]); } void gfarm2fs_id_init(struct gfarm2fs_param *params) { int auto_uid_hash_size, auto_gid_hash_size; enable_cached_id = params->enable_cached_id; /* for debug */ auto_uid_min = params->auto_uid_min; auto_uid_max = params->auto_uid_max; auto_gid_min = params->auto_gid_min; auto_gid_max = params->auto_gid_max; if (auto_uid_min >= auto_uid_max) { gflog_error(GFARM_MSG_2000102, "illegal parameter: " "auto_uid_min(%d) >= auto_uid_max(%d)", auto_uid_min, auto_uid_max); exit(1); } if (auto_gid_min >= auto_gid_max) { gflog_error(GFARM_MSG_2000103, "illegal parameter: " "auto_gid_min(%d) >= auto_gid_max(%d)", auto_gid_min, auto_gid_max); exit(1); } auto_uid_hash_size = next_prime((auto_uid_max - auto_uid_min) / 8); auto_gid_hash_size = next_prime((auto_gid_max - auto_gid_min) / 8); hash_uid_to_user = gfarm_hash_table_alloc( auto_uid_hash_size, id_hash_index, id_hash_equal); hash_gid_to_group = gfarm_hash_table_alloc( auto_gid_hash_size, id_hash_index, id_hash_equal); hash_user_to_uid = gfarm_hash_table_alloc( auto_uid_hash_size, gfarm_hash_strptr, gfarm_hash_key_equal_strptr); hash_group_to_gid = gfarm_hash_table_alloc( auto_gid_hash_size, gfarm_hash_strptr, gfarm_hash_key_equal_strptr); if (hash_uid_to_user == NULL || hash_gid_to_group == NULL || hash_user_to_uid == NULL || hash_group_to_gid == NULL) gflog_fatal(GFARM_MSG_2000104, "no memory for id hashtab"); next_auto_uid = (sig_atomic_t) auto_uid_min; next_auto_gid = (sig_atomic_t) auto_gid_min; } static gfarm_error_t global_user_to_local_uid( const char *url, const char *user, gfarm_uint32_t *uidp) { gfarm_error_t e; struct passwd *pwd; char *luser, *guser; if ((e = gfarm_get_global_username_by_url(url, &guser)) != GFARM_ERR_NO_ERROR) { gflog_debug(GFARM_MSG_2000105, "gfarm_get_global_username_by_url() failed: %s", gfarm_error_string(e)); return (e); } if (strcmp(guser, user) == 0) { free(guser); *uidp = (gfarm_uint32_t) getuid(); /* my own file */ return (GFARM_ERR_NO_ERROR); } free(guser); if (gfarm_global_to_local_username_by_url(url, user, &luser) == GFARM_ERR_NO_ERROR) { pwd = getpwnam(luser); free(luser); if (pwd != NULL) { *uidp = (gfarm_uint32_t) pwd->pw_uid; return (GFARM_ERR_NO_ERROR); } } return (GFARM_ERR_NO_SUCH_OBJECT); /* unknown local user */ } static gfarm_error_t global_group_to_local_gid( const char *url, const char *group, gfarm_uint32_t *gidp) { struct group *grp; char *lgroup; if (gfarm_global_to_local_groupname_by_url(url, group, &lgroup) == GFARM_ERR_NO_ERROR) { grp = getgrnam(lgroup); free(lgroup); if (grp != NULL) { *gidp = (gfarm_uint32_t) grp->gr_gid; return (GFARM_ERR_NO_ERROR); } } return (GFARM_ERR_NO_SUCH_OBJECT); /* unknown local group */ } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t local_uid_to_global_user(const char *url, gfarm_uint32_t uid, char **userp) { gfarm_error_t e; struct passwd *pwd; *userp = NULL; if (uid == (gfarm_uint32_t)getuid()) { e = gfarm_get_global_username_by_url(url, userp); if (e != GFARM_ERR_NO_ERROR) gflog_error(GFARM_MSG_2000106, "gfarm_get_global_username_by_url() failed: %s", gfarm_error_string(e)); return (e); } /* use the user map file to identify the global user */ if ((pwd = getpwuid((uid_t)uid)) == NULL) return (GFARM_ERR_NO_SUCH_OBJECT); return (gfarm_local_to_global_username_by_url( url, pwd->pw_name, userp)); } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t local_gid_to_global_group(const char *url, gfarm_uint32_t gid, char **groupp) { struct group *grp; *groupp = NULL; /* use the group map file to identify the global group */ if ((grp = getgrgid((gid_t)gid)) == NULL) return (GFARM_ERR_NO_SUCH_OBJECT); return (gfarm_local_to_global_groupname_by_url( url, grp->gr_name, groupp)); } static gfarm_error_t auto_name_to_id(struct gfarm_hash_table *name_to_id, const char *name, gfarm_uint32_t *idp) { struct gfarm_hash_entry *entry; entry = gfarm_hash_lookup(name_to_id, &name, sizeof(name)); if (entry != NULL) { *idp = *(gfarm_uint32_t *)gfarm_hash_entry_data(entry); return (GFARM_ERR_NO_ERROR); } return (GFARM_ERR_NO_SUCH_OBJECT); } /* returned string should be free'ed if it is not NULL */ static gfarm_error_t auto_id_to_name(struct gfarm_hash_table *id_to_name, gfarm_uint32_t id, char **namep) { struct gfarm_hash_entry *entry; *namep = NULL; entry = gfarm_hash_lookup(id_to_name, &id, sizeof(id)); if (entry != NULL) { *namep = strdup(*(char **)gfarm_hash_entry_data(entry)); if (*namep == NULL) { gflog_error(GFARM_MSG_2000107, "no memory for auto uid/gid"); return (GFARM_ERR_NO_MEMORY); } return (GFARM_ERR_NO_ERROR); } return (GFARM_ERR_NO_SUCH_OBJECT); } static gfarm_error_t id_and_name_enter(gfarm_uint32_t id, const char *name, struct gfarm_hash_table *hash_id_to_name, struct gfarm_hash_table *hash_name_to_id) { struct gfarm_hash_entry *entry1, *entry2; int created; char *str; char *type = (hash_id_to_name == hash_uid_to_user ? "uid" : "gid"); str = strdup(name); if (str == NULL) goto nomem; /* uid to user */ entry1 = gfarm_hash_enter(hash_id_to_name, &id, sizeof(gfarm_uint32_t), sizeof(char *), &created); if (entry1 == NULL) { free(str); goto nomem; } if (!created) { free(str); return (GFARM_ERR_ALREADY_EXISTS); } /* user to uid */ entry2 = gfarm_hash_enter(hash_name_to_id, &str, sizeof(str), sizeof(gfarm_uint32_t), &created); if (entry2 == NULL) { free(str); gfarm_hash_purge(hash_id_to_name, &id, sizeof(gfarm_uint32_t)); goto nomem; } if (!created) { gfarm_hash_purge(hash_id_to_name, &id, sizeof(gfarm_uint32_t)); gfarm_hash_purge(hash_name_to_id, &str, sizeof(str)); free(str); gflog_error(GFARM_MSG_2000108, "unexpected: inconsistent auto %s(name=%s)", type, name); return (GFARM_ERR_ALREADY_EXISTS); } *(char **)gfarm_hash_entry_data(entry1) = str; *(gfarm_uint32_t *)gfarm_hash_entry_data(entry2) = id; #if 0 /* for debug */ { gfarm_uint32_t i; char *s; printf("----- start of debug id.c -----\n"); for (i = auto_uid_min; i <= next_auto_uid; i++) { auto_id_to_name(hash_uid_to_user, i, &s); if (s != NULL) { printf("uid[%d]: user=%s\n", i, s); free(s); } } for (i = auto_gid_min; i <= next_auto_gid; i++) { auto_id_to_name(hash_gid_to_group, i, &s); if (s != NULL) { printf("gid[%d]: group=%s\n", i, s); free(s); } } printf("----- end of debug id.c -----\n"); } #endif return (GFARM_ERR_NO_ERROR); nomem: gflog_error(GFARM_MSG_2000109, "no memory for auto %s(name=%s)", type, name); return (GFARM_ERR_NO_MEMORY); } static gfarm_error_t global_name_to_local_id( const char *url, const char *name, struct gfarm_hash_table *hash_id_to_name, struct gfarm_hash_table *hash_name_to_id, gfarm_error_t (*global_name_to_local_id_func)( const char *, const char *, gfarm_uint32_t *), gfarm_error_t (*local_id_to_global_name_func)( const char *, gfarm_uint32_t, char **), volatile sig_atomic_t *next_auto_id_p, const gfarm_uint32_t *id_max_p, gfarm_uint32_t *return_id_p) { gfarm_error_t e; int checked_cache = 0; if (enable_cached_id) { /* for debug: use cached id any time */ if (auto_name_to_id(hash_name_to_id, name, return_id_p) == GFARM_ERR_NO_ERROR) return (GFARM_ERR_NO_ERROR); checked_cache = 1; } /* * Assuming a new local user/group is added, getpwnam() or * getgrnam() are checked every time. */ if (global_name_to_local_id_func(url, name, return_id_p) == GFARM_ERR_NO_ERROR) { if (enable_cached_id) /* for debug: cache all mapping */ id_and_name_enter(*return_id_p, name, hash_id_to_name, hash_name_to_id); return (GFARM_ERR_NO_ERROR); } if (checked_cache == 0 && auto_name_to_id(hash_name_to_id, name, return_id_p) == GFARM_ERR_NO_ERROR) return (GFARM_ERR_NO_ERROR); /* search unused id number */ do { char *str; do { *return_id_p = (gfarm_uint32_t) *next_auto_id_p; (*next_auto_id_p)++; } while (*return_id_p + 1 != *next_auto_id_p); if (*return_id_p >= *id_max_p) { char *type = (hash_id_to_name == hash_uid_to_user ? "uid" : "gid"); gflog_warning(GFARM_MSG_2000110, "lack of auto_%s: name=%s", type, name); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } e = local_id_to_global_name_func(url, *return_id_p, &str); if (e != GFARM_ERR_NO_ERROR && e != GFARM_ERR_NO_SUCH_OBJECT) return (e); if (str == NULL) /* found unused uid/gid */ break; free(str); } while (1); /* * If globaluser1@gfmd1 and globaluser2@gfmd2 are the same * name, they have the same id. */ e = id_and_name_enter(*return_id_p, name, hash_id_to_name, hash_name_to_id); if (e != GFARM_ERR_NO_ERROR) return (e); return (GFARM_ERR_NO_ERROR); } /* --------------------------------------------------------------------- */ gfarm_error_t gfarm2fs_get_uid(const char *url, const char *user, uid_t *uidp) { gfarm_uint32_t id; gfarm_error_t e; e = global_name_to_local_id(url, user, hash_uid_to_user, hash_user_to_uid, global_user_to_local_uid, local_uid_to_global_user, &next_auto_uid, &auto_uid_max, &id); if (e == GFARM_ERR_NO_ERROR) *uidp = (uid_t) id; return (e); } gfarm_error_t gfarm2fs_get_gid(const char *url, const char *group, gid_t *gidp) { gfarm_uint32_t id; gfarm_error_t e; e = global_name_to_local_id(url, group, hash_gid_to_group, hash_group_to_gid, global_group_to_local_gid, local_gid_to_global_group, &next_auto_gid, &auto_gid_max, &id); if (e == GFARM_ERR_NO_ERROR) *gidp = (gid_t) id; return (e); } /* returned string should be free'ed if it is not NULL */ gfarm_error_t gfarm2fs_get_user(const char *url, uid_t uid, char **userp) { gfarm_error_t e; /* * Assuming a new local user/group is added, getpwuid() is * checked every time. */ e = local_uid_to_global_user(url, (gfarm_uint32_t)uid, userp); if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); /* success or error */ e = auto_id_to_name(hash_uid_to_user, (gfarm_uint32_t)uid, userp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { gflog_debug(GFARM_MSG_2000111, "cannot convert uid(%d) to gfarm username", uid); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } else return (e); } /* returned string should be free'ed if it is not NULL */ gfarm_error_t gfarm2fs_get_group(const char *url, gid_t gid, char **groupp) { gfarm_error_t e; /* * Assuming a new local user/group is added, getgrgid() is * checked every time. */ e = local_gid_to_global_group(url, (gfarm_uint32_t)gid, groupp); if (e != GFARM_ERR_NO_SUCH_OBJECT) return (e); /* success or error */ e = auto_id_to_name(hash_gid_to_group, (gfarm_uint32_t)gid, groupp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { gflog_debug(GFARM_MSG_2000112, "cannot convert gid(%d) to gfarm groupname", gid); return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* EPERM */ } else return (e); } uid_t gfarm2fs_get_nobody_uid() { struct passwd *pwd = getpwnam("nobody"); if (pwd != NULL) return (pwd->pw_uid); return (auto_uid_max); } gid_t gfarm2fs_get_nogroup_gid() { struct group *grp = getgrnam("nogroup"); if (grp != NULL) return (grp->gr_gid); return (auto_gid_max); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/schedule.c #include <stdio.h> /* sprintf */ #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <time.h> #include <unistd.h> #include <gfarm/gfarm.h> #ifdef HAVE_POLL #include <poll.h> #endif #include "host.h" #include "gfs_client.h" char GFARM_ERR_PANIC_NO_REPLICA_REMAINS[] = "PANIC: no replica remains"; char GFARM_ERR_HOSTS_UNAVAILABLE[] = "available hosts count is less than requested"; struct replied_host_of_search_idle { char *hostname; double loadavg; }; struct state_of_search_idle { int nreplied_hosts; struct replied_host_of_search_idle *replied_hosts; }; struct closure_for_search_idle { struct state_of_search_idle *state; char *hostname; }; static void search_idle_callback(void *closure, struct sockaddr *addr, struct gfs_client_load *result, char *error) { struct closure_for_search_idle *c = closure; struct state_of_search_idle *s = c->state; if (error == NULL) { struct replied_host_of_search_idle *h = &s->replied_hosts[s->nreplied_hosts++]; h->hostname = c->hostname; h->loadavg = result->loadavg_1min; } free(c); } static int loadavg_compare(const void *a, const void *b) { const struct replied_host_of_search_idle *p = a; const struct replied_host_of_search_idle *q = b; const double l1 = p->loadavg; const double l2 = q->loadavg; if (l1 < l2) return (-1); else if (l1 > l2) return (1); else return (0); } #define QUERY_LIMIT 10 /* ask 10 hosts */ /* * Orders host names risingly by load average. * Returns error if the number of active hosts is less than nohosts. */ char * gfarm_schedule_search_idle_hosts( int nihosts, char **ihosts, int nohosts, char **ohosts) { char *e, *e_save = NULL; int i; struct gfs_client_udp_requests *udp_requests; struct sockaddr addr; struct state_of_search_idle s; struct closure_for_search_idle *c; if (nihosts < nohosts) return (GFARM_ERR_HOSTS_UNAVAILABLE); s.nreplied_hosts = 0; s.replied_hosts = malloc( nihosts * sizeof(struct replied_host_of_search_idle)); if (s.replied_hosts == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_client_init_load_requests(QUERY_LIMIT, &udp_requests); if (e != NULL) { free (s.replied_hosts); return (e); } for (i = 0; i < nihosts; i++) { e = gfarm_host_address_get(ihosts[i], gfarm_spool_server_port, &addr, NULL); if (e != NULL) { if (e_save == NULL) e_save = e; continue; } c = malloc(sizeof(*c)); if (c == NULL) { e_save = GFARM_ERR_NO_MEMORY; break; } c->state = &s; c->hostname = ihosts[i]; e = gfarm_client_add_load_request(udp_requests, &addr, c, search_idle_callback); if (s.nreplied_hosts >= nohosts) break; } e = gfarm_client_wait_all_load_results(udp_requests); if (s.nreplied_hosts < nohosts) { free(s.replied_hosts); if (e_save != NULL) return (e_save); else return (GFARM_ERR_HOSTS_UNAVAILABLE); } else if (s.nreplied_hosts > nohosts) { /* to select n minimum load average hosts */ qsort(s.replied_hosts, s.nreplied_hosts, sizeof(*s.replied_hosts), loadavg_compare); } for (i = 0; i < nohosts; i++) ohosts[i] = s.replied_hosts[i].hostname; free(s.replied_hosts); return (NULL); } char * gfarm_schedule_search_idle_by_all(int nhosts_req, char **hostnames_found) { char *e, **hostnames; int i, nhosts; struct gfarm_host_info *hosts; e = gfarm_host_info_get_all(&nhosts, &hosts); if (e != NULL) return (e); if (nhosts < nhosts_req) { e = GFARM_ERR_HOSTS_UNAVAILABLE; goto finish; } if (nhosts == nhosts_req) { /* there is no other choice */ for (i = 0; i < nhosts; i++) { hostnames_found[i] = strdup(hosts[i].hostname); if (hostnames_found[i] == NULL) { while (--i >= 0) free(hostnames_found[i]); e = GFARM_ERR_NO_MEMORY; goto finish; } } goto finish; } hostnames = malloc(sizeof(char *) * nhosts); if (hostnames == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish; } for (i = 0; i < nhosts; i++) hostnames[i] = hosts[i].hostname; e = gfarm_schedule_search_idle_hosts(nhosts, hostnames, nhosts_req, hostnames_found); if (e != NULL) goto free_hostnames; for (i = 0; i < nhosts_req; i++) { hostnames_found[i] = strdup(hostnames_found[i]); if (hostnames_found[i] == NULL) { while (--i >= 0) free(hostnames_found[i]); e = GFARM_ERR_NO_MEMORY; goto free_hostnames; } } free_hostnames: free(hostnames); finish: gfarm_host_info_free_all(nhosts, hosts); return (e); } static char * gfarm_schedule_search_idle_by_section_copy_info( int ncopies, struct gfarm_file_section_copy_info *copies, char **hostp) { char *e, **hostnames; int i; if (ncopies == 1) { /* there is no other choice. */ *hostp = copies[0].hostname; return (NULL); } hostnames = malloc(sizeof(char *) * ncopies); if (hostnames == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < ncopies; i++) hostnames[i] = copies[i].hostname; e = gfarm_schedule_search_idle_hosts( ncopies, hostnames, 1, hostp); free(hostnames); return (e); } char * gfarm_file_section_host_schedule(char *gfarm_file, char *section, char **hostp) { char *e; int ncopies; struct gfarm_file_section_copy_info *copies; char *host; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); if (ncopies == 0) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (GFARM_ERR_PANIC_NO_REPLICA_REMAINS); } e = gfarm_schedule_search_idle_by_section_copy_info( ncopies, copies, &host); *hostp = strdup(host); gfarm_file_section_copy_info_free_all(ncopies, copies); if (*hostp == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } char * gfarm_file_section_host_schedule_with_priority_to_local( char *gfarm_file, char *section, char **hostp) { char *e, *self_name, *host; int i, ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) return (e); if (ncopies == 0) { gfarm_file_section_copy_info_free_all(ncopies, copies); return (GFARM_ERR_PANIC_NO_REPLICA_REMAINS); } /* choose/schedule local one, if possible */ e = gfarm_host_get_canonical_self_name(&self_name); if (e != NULL) { i = ncopies; } else { for (i = 0; i < ncopies; i++) if (strcasecmp(self_name, copies[i].hostname) == 0) break; } if (i < ncopies) /* local */ host = copies[i].hostname; else { e = gfarm_schedule_search_idle_by_section_copy_info( ncopies, copies, &host); if (e != NULL) return (e); } *hostp = strdup(host); gfarm_file_section_copy_info_free_all(ncopies, copies); if (*hostp == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } char * gfarm_url_hosts_schedule(char *gfarm_url, char *option, int *nhostsp, char ***hostsp) { char *e, *gfarm_file, **hosts; int i, nfrags; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); hosts = malloc(sizeof(char *) * nfrags); if (hosts == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < nfrags; i++) { char section_string[GFARM_INT32STRLEN + 1]; sprintf(section_string, "%d", i); e = gfarm_file_section_host_schedule( gfarm_file, section_string, &hosts[i]); if (e != NULL) { gfarm_strings_free_deeply(i, hosts); free(gfarm_file); return (e); } } free(gfarm_file); *nhostsp = nfrags; *hostsp = hosts; return (NULL); } /* * lists host names that contains domainname. */ char * gfarm_host_domain_hosts_schedule(const char *domainname, int *nhostsp, char ***hostsp) { char *e; struct gfarm_host_info *hinfos; int i, j, nhosts = 0, nhinfos; char **hosts; *nhostsp = 0; *hostsp = NULL; e = gfarm_host_info_get_all(&nhinfos, &hinfos); if (e != NULL) return (e); for (i = 0; i < nhinfos; ++i) { if (strstr(hinfos[i].hostname, domainname)) ++nhosts; } if (nhosts == 0) return ("no host"); hosts = malloc(sizeof(char *) * nhosts); if (hosts == NULL) return (GFARM_ERR_NO_MEMORY); j = 0; for (i = 0; i < nhinfos; ++i) { if (strstr(hinfos[i].hostname, domainname)) { hosts[j] = strdup(hinfos[i].hostname); if (hosts[j] == NULL) return (GFARM_ERR_NO_MEMORY); ++j; } } gfarm_host_info_free_all(nhinfos, hinfos); *nhostsp = nhosts; *hostsp = hosts; return (NULL); } /* * expands a host list up to nhosts. This function does not need * gfarm_strings_free_deeply() for hostsp. */ char * gfarm_hosts_schedule_expand_cyclic(int nhosts, char ***hostsp, int nsrchosts, char **srchosts) { int i; char **hosts; hosts = malloc(sizeof(char *) * nhosts); if (hosts == NULL) { return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < nhosts; ++i) { hosts[i] = srchosts[i % nsrchosts]; } *hostsp = hosts; return (NULL); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc5/lib/libgfarm/gfutil/hash.h /* for general memory data (including string) */ int gfarm_hash_default(const void *, int); int gfarm_hash_key_equal_default(const void *, int, const void *, int); /* for string key (casefold) */ int gfarm_hash_casefold(const void *, int); int gfarm_hash_key_equal_casefold(const void *, int, const void *, int); struct gfarm_hash_table; struct gfarm_hash_entry; struct gfarm_hash_table *gfarm_hash_table_alloc(int, int (*)(const void *, int), int (*)(const void *, int, const void *, int)); void gfarm_hash_table_free(struct gfarm_hash_table *); struct gfarm_hash_entry *gfarm_hash_lookup(struct gfarm_hash_table *, const void *, int); struct gfarm_hash_entry *gfarm_hash_enter(struct gfarm_hash_table *, const void *, int, int, int *); int gfarm_hash_purge(struct gfarm_hash_table *, const void *, int); void *gfarm_hash_entry_key(struct gfarm_hash_entry *); int gfarm_hash_entry_key_length(struct gfarm_hash_entry *); void *gfarm_hash_entry_data(struct gfarm_hash_entry *); int gfarm_hash_entry_data_length(struct gfarm_hash_entry *); /* * hash iterator */ struct gfarm_hash_iterator { struct gfarm_hash_table *table; int bucket_index; struct gfarm_hash_entry **pp; }; void gfarm_hash_iterator_begin(struct gfarm_hash_table *, struct gfarm_hash_iterator *); void gfarm_hash_iterator_next(struct gfarm_hash_iterator *); int gfarm_hash_iterator_is_end(struct gfarm_hash_iterator *); struct gfarm_hash_entry *gfarm_hash_iterator_access( struct gfarm_hash_iterator *); int gfarm_hash_iterator_lookup(struct gfarm_hash_table *, const void *, int, struct gfarm_hash_iterator *); int gfarm_hash_iterator_purge(struct gfarm_hash_iterator *); <file_sep>/gfarm2fs/trunk/contrib/mount.gfarm2fs/umount.hpci #!/bin/sh ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } path_exist() { [ -d $1 ] && return 0 for f in `echo $1*` do [ $f = $1 ] && return 0 done return 1 } GFUSER=`gfwhoami` [ X"$GFUSER" = X ] && ABORT 'Who?' : ${USER:=`whoami`} USERLIST="$GFUSER" [ X"$GFUSER" != X"$USER" ] && USERLIST="$USERLIST $USER" groups=`gfgroup -l | grep $GFUSER | awk -F: '{print $1}'` for g in $groups do for u in $USERLIST do d=/gfarm/$g/$u if path_exist $d; then umount.gfarm2fs $d fi done done <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_editor/edit.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>'gfarm2.conf' editor</title> <style type="text/css" media="all"> textarea { font-family: monospace; } td.caption { font-weight: bold; } td.button { text-align: right; } </style> </head> <body> <h1>'gfarm2.conf' editor</h1> <?php include('./common.php'); ?> <form name="save" method="POST" enctype="multipart/form-data" action="save.php"> <table> <thead> <tr> <td class="caption">Edit 'gfarm2.conf' file: <td class="button"><a href="#" onClick="f=history.back()">[cancel]</a> <a href="#" onClick="f=document.save.submit()">[save]</a> </tr> </thead> <tbody> <tr> <td colspan="2"> <textarea name="conf" cols="80" rows="15"> <?php $lines = read_gfarm2_conf_file(); foreach ($lines as $line) { printf("%s\n", htmlspecialchars($line)); } ?> </textarea> </form> </tr> </tbody> </table> </form> <p> Note that 'metadb_server_list' lines are discarded.<br> 'metadb_server_list' line will be added dynamically by the utility. </p> </body> </html> <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/gftool/example/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = \ gfimport_fixed \ gfimport_text include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm/tags/gfarm_0_1/lib/gfs_hook/hooks_subr.c #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" #define MAX_GFS_FILE_BUF 2048 static GFS_File _gfs_file_buf[MAX_GFS_FILE_BUF]; void gfs_hook_not_intialized(void) { fprintf(stderr, "fatal error: gfarm_initialized() isn't called\n"); } int gfs_hook_insert_gfs_file(GFS_File gf) { int fd, save_errno; _gfs_hook_debug(fprintf(stderr, "gfs_hook_insert_gfs_file: %p\n", gf)); fd = dup(gfs_pio_fileno(gf)); if (fd == -1) { save_errno = errno; gfs_pio_close(gf); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_pio_close(gf); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_pio_close(gf); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = gf; return (fd); } void gfs_hook_clear_gfs_file(int fd) { _gfs_hook_debug(fprintf(stderr, "gfs_hook_clear_gfs_file: %d\n", fd)); _gfs_file_buf[fd] = NULL; __syscall_close(fd); } /* printf and puts should not be put into the following function. */ GFS_File gfs_hook_is_open(int fd) { if (!gfarm_initialized) { gfs_hook_not_initialized(); return (NULL); /* don't perform gfarm operation */ } if (fd >= 0 && fd < MAX_GFS_FILE_BUF) return (_gfs_file_buf[fd]); return (NULL); } int gfs_hook_is_url(const char *path, const char **urlp) { /* * Objectivity patch: * '/gfarm:' is also considered as a Gfarm URL */ if (*path == '/') ++path; if (gfarm_is_url(path)) { if (!gfarm_initialized) { gfs_hook_not_initialized(); return (0); /* don't perform gfarm operation */ } *urlp = path; return (1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/lib/libgfarm/gfarm/gfs_proto.h #ifndef GFSD_DEFAULT_PORT #define GFSD_DEFAULT_PORT 600 #endif #ifndef XAUTH_COMMAND #define XAUTH_COMMAND "xauth" #endif enum gfs_proto_command { GFS_PROTO_OPEN, GFS_PROTO_CLOSE, GFS_PROTO_SEEK, GFS_PROTO_READ, GFS_PROTO_WRITE, GFS_PROTO_UNLINK, GFS_PROTO_CHDIR, GFS_PROTO_MKDIR, GFS_PROTO_RMDIR, GFS_PROTO_CHMOD, GFS_PROTO_CHGRP, GFS_PROTO_STAT, GFS_PROTO_DIGEST, GFS_PROTO_GET_SPOOL_ROOT, GFS_PROTO_BULKREAD, GFS_PROTO_BULKWRITE, GFS_PROTO_REPLICATE_FILE_SEQUENTIAL, GFS_PROTO_COMMAND, GFS_PROTO_REPLICATE_FILE_PARALLEL, GFS_PROTO_STRIPING_READ, GFS_PROTO_EXIST, GFS_PROTO_RENAME, GFS_PROTO_LINK }; enum gfs_proto_error { GFS_ERROR_NOERROR, GFS_ERROR_PERM, GFS_ERROR_NOENT, GFS_ERROR_SRCH, GFS_ERROR_INTR, GFS_ERROR_IO, GFS_ERROR_NXIO, GFS_ERROR_E2BIG, GFS_ERROR_NOEXEC, GFS_ERROR_BADF, /* ECHILD, */ GFS_ERROR_DEADLK, GFS_ERROR_NOMEM, GFS_ERROR_ACCES, GFS_ERROR_FAULT, /* ENOTBLK, */ GFS_ERROR_BUSY, GFS_ERROR_EXIST, /* EXDEV, */ /* ENODEV, */ GFS_ERROR_NOTDIR, GFS_ERROR_ISDIR, GFS_ERROR_INVAL, GFS_ERROR_NFILE, GFS_ERROR_MFILE, /* ENOTTY, */ GFS_ERROR_TXTBSY, GFS_ERROR_FBIG, GFS_ERROR_NOSPC, GFS_ERROR_SPIPE, GFS_ERROR_ROFS, /* EMLINK, */ GFS_ERROR_PIPE, /* EDOM, */ /* ERANGE, */ GFS_ERROR_AGAIN, /* : */ GFS_ERROR_OPNOTSUPP, /* : */ GFS_ERROR_CONNREFUSED, GFS_ERROR_LOOP, GFS_ERROR_NAMETOOLONG, /* : */ GFS_ERROR_DQUOT, GFS_ERROR_STALE, /* : */ GFS_ERROR_NOLCK, GFS_ERROR_NOSYS, /* EFTYPE, */ GFS_ERROR_AUTH, /* : */ GFS_ERROR_EXPIRED, GFS_ERROR_PROTO, GFS_ERROR_PROTONOSUPPORT, GFS_ERROR_UNKNOWN, /* : */ GFS_ERROR_NUMBER }; #define GFS_PROTO_MAX_IOSIZE 65536 /* * sub protocols of GFS_PROTO_COMMAND */ enum gfs_proto_command_client { GFS_PROTO_COMMAND_EXIT_STATUS, GFS_PROTO_COMMAND_SEND_SIGNAL, GFS_PROTO_COMMAND_FD_INPUT, }; enum gfs_proto_command_server { GFS_PROTO_COMMAND_EXITED, GFS_PROTO_COMMAND_STOPPED, /* currently not used */ GFS_PROTO_COMMAND_FD_OUTPUT, }; #define GFARM_DEFAULT_COMMAND_IOBUF_SIZE 0x4000 #define FDESC_STDIN 0 #define FDESC_STDOUT 1 #define FDESC_STDERR 2 #define NFDESC 3 char *gfs_proto_error_string(enum gfs_proto_error); enum gfs_proto_error gfs_string_to_proto_error(char *); enum gfs_proto_error gfs_errno_to_proto_error(int); #include <openssl/evp.h> /* for EVP_MD, EVP_MD_CTX */ int gfs_open_flags_localize(int); int gfs_digest_calculate_local(int, char *, size_t, const EVP_MD *, EVP_MD_CTX *, size_t *, unsigned char *, file_offset_t *); <file_sep>/gfarm/tags/gfarm_1_0_rc4/gfptool/util/gfregister.in #!/bin/sh PTOOLS='bin/gfcombine bin/gfcombine_hook bin/gfcp bin/gfcp_hook bin/gfgrep bin/gfrcmd bin/gfreg bin/gfsplck bin/gfwc libexec/gfrepbe_client libexec/gfrepbe_server' hostname=`hostname` arch=`gfhost -M $hostname | sed 's/ .*//'` status=0 if test x"$arch" = x"" then echo "$0: error: architecture name of $hostname isn't determined" >&2 exit 1 fi cd @prefix@ echo Creating gfarm:/bin ... if gfmkdir gfarm:/bin gfarm:/libexec; then : else status=1 fi for cmd in $PTOOLS do if test -f $cmd then if gfwhere -I $arch gfarm:/$cmd >/dev/null 2>&1; then : else echo Registering gfarm:/$cmd for $arch ... if gfreg $cmd gfarm:/$cmd; then : else status=1 fi fi gfhost -a $arch | while read host; do echo Replicating gfarm:/${cmd}:${arch} to $host ... if gfrep -b -I $arch -s $hostname -d $host gfarm:/$cmd then : else status=1 fi done fi done exit $status <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/makes/man.mk all: man-all post-all-hook install: man-install post-install-hook clean: man-clean post-clean-hook veryclean: man-veryclean post-very-clean-hook distclean: man-distclean post-distclean-hook gfregister: man-gfregister post-gfregister-hook man: man-man html: man-html post-all-hook: post-install-hook: post-clean-hook: post-very-clean-hook: post-distclean-hook: post-gfregister-hook: man-all: man-install: @for i in -- $(MAN); do \ case $$i in --) continue;; esac; \ suffix=`expr $$i : '.*\.\([^.]*\)$$'`; \ ( set -x; $(INSTALL_DATA) $(srcdir)/$$i $(mandir)/man$$suffix/$$i ); \ done man-clean: -test -z "$(EXTRA_CLEAN_TARGETS)" || $(RM) -f $(EXTRA_CLEAN_TARGETS) man-veryclean: clean -test -z "$(EXTRA_VERYCLEAN_TARGETS)" || $(RM) -f $(EXTRA_VERYCLEAN_TARGETS) man-distclean: veryclean -test ! -f $(srcdir)/Makefile.in || $(RM) -f Makefile man-gfregister: $(dstsubst): $(srcsubst) $(DOCBOOK2MAN) $(srcsubst) man-man: for i in $(DOCBOOK); do \ $(MAKE) srcsubst=$(DOCBOOK_DIR)/$${i}.docbook \ dstsubst=$$i $$i; \ done man-html: <file_sep>/gfarmfs-fuse/trunk/contrib/mount.gfarmfs/Makefile.am bin_SCRIPTS = mount.gfarmfs umount.gfarmfs EXTRA_DIST = $(bin_SCRIPTS) <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/auth_server.c #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <grp.h> #include <sys/types.h> #include <sys/socket.h> #include <time.h> #include <pwd.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "xxx_proto.h" #include "gfutil.h" #include "hostspec.h" #include "auth.h" #ifdef HAVE_GSI #include "io_gfsl.h" /* XXX - gfarm_authorize_gsi() */ #endif static char *gfarm_authorize_panic(struct xxx_connection *, int, char **); static char *gfarm_authorize_simple(struct xxx_connection *, int, char **); char *(*gfarm_authorization_table[])(struct xxx_connection *, int, char **) = { /* * This table entry should be ordered by enum gfarm_auth_method. */ gfarm_authorize_panic, /* GFARM_AUTH_METHOD_NONE */ gfarm_authorize_simple, /* GFARM_AUTH_METHOD_SIMPLE */ #ifdef HAVE_GSI gfarm_authorize_gsi, /* GFARM_AUTH_METHOD_GSI */ #else gfarm_authorize_panic, /* GFARM_AUTH_METHOD_GSI */ #endif }; static char * gfarm_authorize_panic(struct xxx_connection *conn, int switch_to, char **global_usernamep) { gflog_fatal("gfarm_authorize", "authorization assertion failed"); return (GFARM_ERR_PROTOCOL); } static char * gfarm_auth_simple_response(struct xxx_connection *conn, char *homedir) { char *e; gfarm_uint32_t request, expire, expire_expected; size_t len; gfarm_int32_t error = GFARM_AUTH_ERROR_EXPIRED; /* gfarm_auth_error */ int eof, try = 0; char challenge[GFARM_AUTH_CHALLENGE_LEN]; char response[GFARM_AUTH_RESPONSE_LEN]; char shared_key_expected[GFARM_AUTH_SHARED_KEY_LEN]; char response_expected[GFARM_AUTH_RESPONSE_LEN]; /* NOTE: `homedir' may be NULL, if invalid username is requested. */ for (;;) { ++try; e = xxx_proto_recv(conn, 0, &eof, "i", &request); if (e != NULL) { gflog_error("auth_simple-request", e); return (e); } if (eof) { gflog_error("auth_simple-request", "unexpected EOF"); return (GFARM_ERR_PROTOCOL); } if (request != GFARM_AUTH_SIMPLE_GIVEUP && request != GFARM_AUTH_SIMPLE_MD5) { error = GFARM_AUTH_ERROR_NOT_SUPPORTED; e = xxx_proto_send(conn, "i", error); if (e != NULL) return (e); continue; } e = xxx_proto_send(conn, "i", GFARM_AUTH_ERROR_NO_ERROR); if (e != NULL) return (e); if (request == GFARM_AUTH_SIMPLE_GIVEUP) { e = xxx_proto_flush(conn); if (e != NULL) return (e); if (try > 1) { switch (error) { case GFARM_AUTH_ERROR_EXPIRED: return (GFARM_ERR_EXPIRED); case GFARM_AUTH_ERROR_NOT_SUPPORTED: return ( GFARM_ERR_PROTOCOL_NOT_SUPPORTED); } } return (GFARM_ERR_AUTHENTICATION); } gfarm_auth_random(challenge, sizeof(challenge)); e = xxx_proto_send(conn, "b", sizeof(challenge), challenge); if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "ib", &expire, sizeof(response), &len, response); if (e != NULL) { gflog_error("auth_simple-response", e); return (e); } if (eof) { gflog_error("auth_simple-response", "unexpected EOF"); return (GFARM_ERR_PROTOCOL); } /* * Note that gfarm_auth_shared_key_get() should be called * after the above xxx_proto_recv(), otherwise * client (re)generated shared key may not be accessible. */ if (homedir == NULL) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; } else if ((e = gfarm_auth_shared_key_get(&expire_expected, shared_key_expected, homedir, GFARM_AUTH_SHARED_KEY_GET)) != NULL && e != GFARM_ERR_EXPIRED) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_simple: read-key", e); } else if (time(0) >= expire) { /* may reach here if (e == GFARM_ERR_EXPIRED) */ error = GFARM_AUTH_ERROR_EXPIRED; gflog_warning("auth_simple", "key expired"); } else { /* may also reach here if (e == GFARM_ERR_EXPIRED) */ gfarm_auth_simple_response_data( shared_key_expected, challenge, response_expected); if (expire != expire_expected) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_simple", "expire time mismatch"); } else if (memcmp(response, response_expected, sizeof(response)) != 0) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_simple", "response mismatch"); } else { error = GFARM_AUTH_ERROR_NO_ERROR; } } e = xxx_proto_send(conn, "i", error); if (e != NULL) return (e); if (error == GFARM_AUTH_ERROR_NO_ERROR) { e = xxx_proto_flush(conn); if (e != NULL) return (e); return (NULL); /* success */ } } } static char * gfarm_authorize_simple(struct xxx_connection *conn, int switch_to, char **global_usernamep) { char *e, *global_username, *local_username; int eof; struct passwd *pwd; uid_t o_uid; gid_t o_gid; #ifdef __GNUC__ /* workaround gcc warning: unused variable */ o_uid = o_gid = 0; #endif e = xxx_proto_recv(conn, 0, &eof, "s", &global_username); if (e != NULL) { gflog_error("authorize_simple", "reading username"); return (e); } if (eof) { gflog_error("authorize_simple", "unexpected EOF"); return (GFARM_ERR_PROTOCOL); } gflog_set_auxiliary_info(global_username); e = gfarm_global_to_local_username(global_username, &local_username); if (e != NULL) { pwd = NULL; gflog_error("authorize_simple", "cannot map global username into local username"); } else { pwd = getpwnam(local_username); if (pwd == NULL) gflog_error(local_username, "authorize_simple: " "local account doesn't exist"); } if (pwd != NULL) { /* * first, switch to the user's privilege * to read ~/.gfarm_shared_key. * * NOTE: reading this file with root privilege may not work, * if home directory is NFS mounted and root access for * the home directory partition is not permitted. * * Do not switch the user ID of the current process here * even in the switch_to case, because it is necessary to * switch back to the original user ID when gfarm_auth_simple * fails. */ o_gid = getegid(); o_uid = geteuid(); initgroups(pwd->pw_name, pwd->pw_gid); setegid(pwd->pw_gid); seteuid(pwd->pw_uid); } e = gfarm_auth_simple_response(conn, pwd == NULL ? NULL : pwd->pw_dir); if (pwd != NULL) { setegid(o_gid); seteuid(o_uid); } /* if (pwd == NULL), (e != NULL) must be true */ if (e != NULL) { gflog_set_auxiliary_info(NULL); free(global_username); if (local_username != NULL) free(local_username); return (e); } if (switch_to) { /* * because the name returned by getlogin() is * an attribute of a session on 4.4BSD derived OSs, * we should create new session before calling * setlogin(). */ setsid(); #ifdef HAVE_SETLOGIN setlogin(pwd->pw_name); #endif setgid(pwd->pw_gid); setuid(pwd->pw_uid); /* assert(local_username != NULL); */ gfarm_set_global_username(global_username); gfarm_set_local_username(local_username); gfarm_set_local_homedir(pwd->pw_dir); } else { gflog_set_auxiliary_info(NULL); if (global_usernamep == NULL) /* see below */ free(global_username); } /* * global_username may continue to be refered, * if (switch_to) as gflog_set_auxiliary_info() * else if (global_usernamep != NULL) as *global_usernamep */ free(local_username); if (global_usernamep != NULL) *global_usernamep = global_username; return (NULL); } /* * the `switch_to' flag has the following side effects: * - the privilege of this program will switch to the authenticated user. * - `global_username' will be recorded by gflog_set_auxiliary_info(). * and * - gfarm_get_local_username(), gfarm_get_local_homedir() and * gfarm_get_global_username() become available. * * note that the user's account is not always necessary on this host, * if the `switch_to' flag isn't set. but also note that some * authentication methods (e.g. gfarm-simple-auth) require the user's * local account anyway even if the `switch_to' isn't set. */ char * gfarm_authorize(struct xxx_connection *conn, int switch_to, char **global_usernamep) { char *e, *name, *log_header; gfarm_int32_t methods; /* bitset of enum gfarm_auth_method */ gfarm_int32_t method; /* enum gfarm_auth_method */ gfarm_int32_t error; /* enum gfarm_auth_error */ struct sockaddr addr; socklen_t addrlen = sizeof(addr); int rv = getpeername(xxx_connection_fd(conn), &addr, &addrlen); int i, eof, try = 0; size_t nmethods; unsigned char methods_buffer[CHAR_BIT * sizeof(gfarm_int32_t)]; static char name_header[] = "authorize: "; char namebuf[sizeof(name_header) + GFARM_SOCKADDR_STRLEN]; assert(GFARM_ARRAY_LENGTH(gfarm_authorization_table) == GFARM_AUTH_METHOD_NUMBER); if (rv == -1) return (gfarm_errno_to_error(errno)); e = gfarm_sockaddr_to_name(&addr, &name); if (e == NULL) { log_header = name; } else { strcpy(namebuf, name_header); gfarm_sockaddr_to_string(&addr, namebuf + sizeof(name_header) - 1, GFARM_SOCKADDR_STRLEN); gflog_warning(namebuf, e); log_header = namebuf; name = NULL; } methods = gfarm_auth_method_get_enabled_by_name_addr(name, &addr); if (methods == 0) { gflog_error(log_header, "access refused"); } else { methods &= gfarm_auth_method_get_available(); if (methods == 0) gflog_error(log_header, "auth-method not configured"); } nmethods = 0; for (i = GFARM_AUTH_METHOD_NONE + 1; i < GFARM_AUTH_METHOD_NUMBER && i < CHAR_BIT * sizeof(gfarm_int32_t); i++) { if ((methods & (1 << i)) != 0) methods_buffer[nmethods++] = i; } e = xxx_proto_send(conn, "b", nmethods, methods_buffer); if (e != NULL) return (e); for (;;) { ++try; e = xxx_proto_recv(conn, 0, &eof, "i", &method); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (method == GFARM_AUTH_METHOD_NONE) error = GFARM_AUTH_ERROR_NO_ERROR; else if (method >= GFARM_AUTH_METHOD_NUMBER) error = GFARM_AUTH_ERROR_NOT_SUPPORTED; else if (method <= GFARM_AUTH_METHOD_NONE || ((1 << method) & methods) == 0) error = GFARM_AUTH_ERROR_DENIED; else error = GFARM_AUTH_ERROR_NO_ERROR; e = xxx_proto_send(conn, "i", error); if (e != NULL) return (e); e = xxx_proto_flush(conn); if (e != NULL) return (e); if (method == GFARM_AUTH_METHOD_NONE) { /* client gave up */ if (methods == 0) return (GFARM_ERR_PERMISSION_DENIED); if (try == 1) { /* * there is no usable auth-method * between client and server. */ gflog_error(log_header, "auth-method not match"); return (GFARM_ERR_PROTOCOL_NOT_SUPPORTED); } return (GFARM_ERR_AUTHENTICATION); } if (error != GFARM_AUTH_ERROR_NO_ERROR) { gflog_error(log_header, "incorrect auth-method reply"); return (GFARM_ERR_PROTOCOL); } e = (*gfarm_authorization_table[method])(conn, switch_to, global_usernamep); if (e != GFARM_ERR_PROTOCOL_NOT_SUPPORTED && e != GFARM_ERR_EXPIRED && e != GFARM_ERR_AUTHENTICATION) { /* success if (e == NULL), or protocol error */ return (e); } } } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT1-2-2-1_db_down #! /bin/sh ###################################################################### TESTID="FT1-2-2-1" CATEGORY="accident causes no failover" SECTION="mds accident" TITLE="DB down" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-backend-db gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop backend DB on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "PostgreSQL is not running on $gfmd1" \ "Database access is failed on $gfmd1 numbackends" \ "Database access is failed on $gfmd1 tx_commited" \ "Database access is failed on $gfmd1 tx_rolledback" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox $gfservice start-backend-db gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "start gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "Re: PostgreSQL is not running on $gfmd1" \ "Re: Database access is failed on $gfmd1 numbackends" \ "Re: Database access is failed on $gfmd1 tx_commited" \ "Re: Database access is failed on $gfmd1 tx_rolledback" [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { $gfservice start-gfmd gfmd1 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/branches/1.1.1/gfarm2fs.c /* * GfarmFS-FUSE for Gfarm version 2 * * $Id$ */ #include "config.h" #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <fcntl.h> #include <errno.h> #ifdef HAVE_SYS_XATTR_H #include <sys/xattr.h> #endif /* * fuse.h requres that _FILE_OFFSET_BITS is defined in any case, but * AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 * since it is not necessary. To avoid this problem we define it here. */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #define FUSE_USE_VERSION 25 #include <fuse.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> /* for better scalability */ #define USE_GETDIR /* XXX FIXME */ #define GFS_DEV ((dev_t)-1) #define GFS_BLKSIZE 8192 #define STAT_BLKSIZ 512 /* for st_blocks */ char *program_name = "gfarm2fs"; static uid_t get_uid(char *user) { if (strcmp(gfarm_get_global_username(), user) == 0) return getuid(); /* my own file */ /* XXX FIXME - some other's file */ return (0); } static int get_gid(char *group) { /* XXX FIXME */ return (0); } static int get_nlink(struct gfs_stat *st) { /* XXX FIXME */ return (GFARM_S_ISDIR(st->st_mode) ? 32000 : st->st_nlink); } static void copy_gfs_stat(struct stat *dst, struct gfs_stat *src) { memset(dst, 0, sizeof(*dst)); dst->st_dev = GFS_DEV; dst->st_ino = src->st_ino; dst->st_mode = src->st_mode; dst->st_nlink = get_nlink(src); dst->st_uid = get_uid(src->st_user); dst->st_gid = get_gid(src->st_group); dst->st_size = src->st_size; dst->st_blksize = GFS_BLKSIZE; dst->st_blocks = (src->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; dst->st_atime = src->st_atimespec.tv_sec; dst->st_mtime = src->st_mtimespec.tv_sec; dst->st_ctime = src->st_ctimespec.tv_sec; } static int gfarm2fs_getattr(const char *path, struct stat *stbuf) { struct gfs_stat st; gfarm_error_t e; e = gfs_lstat_cached(path, &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); copy_gfs_stat(stbuf, &st); gfs_stat_free(&st); return (0); } static inline GFS_File get_filep(struct fuse_file_info *fi) { return (GFS_File) (uintptr_t) fi->fh; } static int gfarm2fs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { struct gfs_stat st; gfarm_error_t e; e = gfs_pio_stat(get_filep(fi), &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); copy_gfs_stat(stbuf, &st); gfs_stat_free(&st); return (0); } static int gfarm2fs_access(const char *path, int mask) { /* XXX FIXME */ return (-ENOSYS); #if 0 gfarm_error_t e; e = gfs_access(path, mask); return (-gfarm_error_to_errno(e)); #endif } static int gfarm2fs_readlink(const char *path, char *buf, size_t size) { gfarm_error_t e; char *src; size_t len; e = gfs_readlink(path, &src); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); len = strlen(src); if (len >= size) len = size - 1; memcpy(buf, src, len); buf[len] = '\0'; return (0); } #ifndef USE_GETDIR static int gfarm2fs_opendir(const char *path, struct fuse_file_info *fi) { gfarm_error_t e; GFS_Dir dp; e = gfs_opendir_caching(path, &dp); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) dp; return (0); } static inline GFS_Dir get_dirp(struct fuse_file_info *fi) { return (GFS_Dir) (uintptr_t) fi->fh; } static int gfarm2fs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); struct gfs_dirent *de; struct stat st; /* gfarm_off_t off = 0; */ gfarm_error_t e; (void) path; /* XXX gfs_seekdir(dp, offset); */ while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { memset(&st, 0, sizeof(st)); st.st_ino = de->d_fileno; st.st_mode = de->d_type << 12; /* XXX (void)gfs_telldir(dp, &off); */ if (filler(buf, de->d_name, &st, 0)) break; } return (0); } static int gfarm2fs_releasedir(const char *path, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); (void) path; gfs_closedir(dp); return (0); } #else /* USE_GETDIR */ static int gfarm2fs_getdir(const char *path, fuse_dirh_t h, fuse_dirfil_t filler) { gfarm_error_t e, e2; GFS_Dir dp; struct gfs_dirent *de; e = gfs_opendir_caching(path, &dp); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { if (filler(h, de->d_name, de->d_type << 12, de->d_fileno)) break; } e2 = gfs_closedir(dp); if (e == GFARM_ERR_NO_ERROR) e = e2; return (-gfarm_error_to_errno(e)); } #endif static int gfarm2fs_mknod(const char *path, mode_t mode, dev_t rdev) { GFS_File gf; gfarm_error_t e; if (!S_ISREG(mode)) return (-ENOSYS); e = gfs_pio_create(path, GFARM_FILE_WRONLY, mode & GFARM_S_ALLPERM, &gf); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_close(gf); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_mkdir(const char *path, mode_t mode) { gfarm_error_t e; e = gfs_mkdir(path, mode & GFARM_S_ALLPERM); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_unlink(const char *path) { gfarm_error_t e; e = gfs_unlink(path); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_rmdir(const char *path) { gfarm_error_t e; e = gfs_rmdir(path); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_symlink(const char *from, const char *to) { gfarm_error_t e; e = gfs_symlink(from, to); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_rename(const char *from, const char *to) { gfarm_error_t e; e = gfs_rename(from, to); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_link(const char *from, const char *to) { gfarm_error_t e; e = gfs_link(from, to); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_chmod(const char *path, mode_t mode) { gfarm_error_t e; e = gfs_chmod(path, mode & GFARM_S_ALLPERM); return (-gfarm_error_to_errno(e)); } #if 0 static char * get_user(uid_t uid) { /* XXX FIXME */ return "user"; } static char * get_group(uid_t gid) { /* XXX FIXME */ return "group"; } #endif static int gfarm2fs_chown(const char *path, uid_t uid, gid_t gid) { struct gfs_stat st; gfarm_error_t e; /* XXX FIXME */ if (uid == getuid()) { e = gfs_lstat_cached(path, &st); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); if (strcmp(st.st_user, gfarm_get_global_username()) == 0) { gfs_stat_free(&st); return (0); } gfs_stat_free(&st); } return (-ENOSYS); #if 0 gfarm_error_t e; char *user, *group; user = get_user(uid); group = get_group(gid); e = gfs_chown(path, user, group); return (-gfarm_error_to_errno(e)); #endif } static int gfarm2fs_truncate(const char *path, off_t size) { gfarm_error_t e, e2; GFS_File gf; e = gfs_pio_open(path, GFARM_FILE_WRONLY, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); e = gfs_pio_truncate(gf, size); e2 = gfs_pio_close(gf); return (-gfarm_error_to_errno(e != GFARM_ERR_NO_ERROR ? e : e2)); } static int gfarm2fs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { gfarm_error_t e; (void) path; e = gfs_pio_truncate(get_filep(fi), size); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_utime(const char *path, struct utimbuf *buf) { struct gfarm_timespec gt[2]; gfarm_error_t e; if (buf != NULL) { gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; } e = gfs_utimes(path, gt); return (-gfarm_error_to_errno(e)); } static int gfs_hook_open_flags_gfarmize(int open_flags) { int gfs_flags; switch (open_flags & O_ACCMODE) { case O_RDONLY: gfs_flags = GFARM_FILE_RDONLY; break; case O_WRONLY: gfs_flags = GFARM_FILE_WRONLY; break; case O_RDWR: gfs_flags = GFARM_FILE_RDWR; break; default: return (-1); } #if 0 /* this is unnecessary */ if ((open_flags & O_CREAT) != 0) gfs_flags |= GFARM_FILE_CREATE; #endif if ((open_flags & O_TRUNC) != 0) gfs_flags |= GFARM_FILE_TRUNC; #if 0 /* not yet on Gfarm v2 */ if ((open_flags & O_APPEND) != 0) gfs_flags |= GFARM_FILE_APPEND; if ((open_flags & O_EXCL) != 0) gfs_flags |= GFARM_FILE_EXCLUSIVE; #endif #if 0 /* not yet on Gfarm v2 */ /* open(2) and creat(2) should be unbuffered */ gfs_flags |= GFARM_FILE_UNBUFFERED; #endif return (gfs_flags); } static int gfarm2fs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { gfarm_error_t e; GFS_File gf; int flags; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfs_pio_create(path, flags, mode & GFARM_S_ALLPERM, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) gf; return (0); } static int gfarm2fs_open(const char *path, struct fuse_file_info *fi) { GFS_File gf; int flags; gfarm_error_t e; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfs_pio_open(path, flags, &gf); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); fi->fh = (unsigned long) gf; return (0); } static int gfarm2fs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; (void) path; e = gfs_pio_seek(get_filep(fi), offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_read(get_filep(fi), buf, size, &rv); if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); return (rv); } static int gfarm2fs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; (void) path; e = gfs_pio_seek(get_filep(fi), offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_write(get_filep(fi), buf, size, &rv); if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); return (rv); } static int gfarm2fs_statfs(const char *path, struct statvfs *stbuf) { gfarm_error_t e; gfarm_off_t used, avail, files; e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) return (-gfarm_error_to_errno(e)); else { stbuf->f_bsize = 1024; /* XXX */ stbuf->f_frsize = 1024; /* XXX */ stbuf->f_blocks = used + avail; stbuf->f_bfree = avail; stbuf->f_bavail = avail; stbuf->f_files = files; stbuf->f_ffree = -1; /* XXX */ stbuf->f_favail = -1; /* XXX */ stbuf->f_fsid = 298; /* XXX */ stbuf->f_flag = 0; /* XXX */ stbuf->f_namemax = GFS_MAXNAMLEN; } return (0); } static int gfarm2fs_release(const char *path, struct fuse_file_info *fi) { (void) path; gfs_pio_close(get_filep(fi)); return (0); } static int gfarm2fs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { gfarm_error_t e; (void) path; if (isdatasync) e = gfs_pio_datasync(get_filep(fi)); else e = gfs_pio_sync(get_filep(fi)); return (-gfarm_error_to_errno(e)); } #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) static int gfarm2fs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { gfarm_error_t e; e = gfs_setxattr(path, name, value, size, flags); return -gfarm_error_to_errno(e); } static int gfarm2fs_getxattr(const char *path, const char *name, char *value, size_t size) { gfarm_error_t e; size_t s = size; e = gfs_getxattr(path, name, value, &s); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* * NOTE: man getxattr(2) says that ENOATTR must be returned, * but it's not defined in header files. * We return -ENODATA because "strace ls -l /" is below. * open("/", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY) = 3 * .... * getxattr("/etc", "system.posix_acl_access"..., 0x0, 0) = -1 ENODATA (No data available) * getxattr("/etc", "system.posix_acl_default"..., 0x0, 0) = -1 ENODATA (No data available) * ... */ return -ENODATA; } if (e != GFARM_ERR_NO_ERROR) return -gfarm_error_to_errno(e); else return s; } static int gfarm2fs_listxattr(const char *path, char *list, size_t size) { gfarm_error_t e; size_t s = size; e = gfs_listxattr(path, list, &s); if (e == GFARM_ERR_NO_ERROR) return s; else return -gfarm_error_to_errno(e); } static int gfarm2fs_removexattr(const char *path, const char *name) { gfarm_error_t e; e = gfs_removexattr(path, name); if (e == GFARM_ERR_NO_SUCH_OBJECT) return -ENODATA; else return -gfarm_error_to_errno(e); } #endif /* HAVE_SYS_XATTR_H && ENABLE_XATTR */ static struct fuse_operations gfarm2fs_oper = { .getattr = gfarm2fs_getattr, .fgetattr = gfarm2fs_fgetattr, .access = gfarm2fs_access, .readlink = gfarm2fs_readlink, #ifndef USE_GETDIR .opendir = gfarm2fs_opendir, .readdir = gfarm2fs_readdir, .releasedir = gfarm2fs_releasedir, #else .getdir = gfarm2fs_getdir, #endif .mknod = gfarm2fs_mknod, .mkdir = gfarm2fs_mkdir, .symlink = gfarm2fs_symlink, .unlink = gfarm2fs_unlink, .rmdir = gfarm2fs_rmdir, .rename = gfarm2fs_rename, .link = gfarm2fs_link, .chmod = gfarm2fs_chmod, .chown = gfarm2fs_chown, .truncate = gfarm2fs_truncate, .ftruncate = gfarm2fs_ftruncate, .utime = gfarm2fs_utime, .create = gfarm2fs_create, .open = gfarm2fs_open, .read = gfarm2fs_read, .write = gfarm2fs_write, .statfs = gfarm2fs_statfs, .release = gfarm2fs_release, .fsync = gfarm2fs_fsync, #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) .setxattr = gfarm2fs_setxattr, .getxattr = gfarm2fs_getxattr, .listxattr = gfarm2fs_listxattr, .removexattr= gfarm2fs_removexattr, #endif }; /*** *** for cached mode ***/ static void uncache_parent(const char *path) { char *p = strdup(path), *b; if (p == NULL) /* XXX should report an error */ return; b = (char *)gfarm_path_dir_skip(p); /* UNCONST */ if (b > p && b[-1] == '/') { b[-1] = '\0'; gfs_stat_cache_purge(p); } free(p); } static int gfarm2fs_mknod_cached(const char *path, mode_t mode, dev_t rdev) { int rv = gfarm2fs_mknod(path, mode, rdev); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_mkdir_cached(const char *path, mode_t mode) { int rv = gfarm2fs_mkdir(path, mode); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_unlink_cached(const char *path) { int rv = gfarm2fs_unlink(path); if (rv == 0) { gfs_stat_cache_purge(path); uncache_parent(path); } return (rv); } static int gfarm2fs_rmdir_cached(const char *path) { int rv = gfarm2fs_rmdir(path); if (rv == 0) { gfs_stat_cache_purge(path); uncache_parent(path); } return (rv); } static int gfarm2fs_symlink_cached(const char *from, const char *to) { int rv = gfarm2fs_symlink(from, to); if (rv == 0) uncache_parent(to); return (rv); } static int gfarm2fs_rename_cached(const char *from, const char *to) { int rv = gfarm2fs_rename(from, to); if (rv == 0) { gfs_stat_cache_purge(from); uncache_parent(from); gfs_stat_cache_purge(to); uncache_parent(to); } return (rv); } static int gfarm2fs_link_cached(const char *from, const char *to) { int rv = gfarm2fs_link(from, to); if (rv == 0) uncache_parent(to); return (rv); } static int gfarm2fs_chmod_cached(const char *path, mode_t mode) { int rv = gfarm2fs_chmod(path, mode); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_chown_cached(const char *path, uid_t uid, gid_t gid) { int rv = gfarm2fs_chown(path, uid, gid); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_truncate_cached(const char *path, off_t size) { int rv = gfarm2fs_truncate(path, size); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_ftruncate_cached(const char *path, off_t size, struct fuse_file_info *fi) { int rv = gfarm2fs_ftruncate(path, size, fi); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_utime_cached(const char *path, struct utimbuf *buf) { int rv = gfarm2fs_utime(path, buf); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_create_cached(const char *path, mode_t mode, struct fuse_file_info *fi) { int rv = gfarm2fs_create(path, mode, fi); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_open_cached(const char *path, struct fuse_file_info *fi) { int rv = gfarm2fs_open(path, fi); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_write_cached(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int rv = gfarm2fs_write(path, buf, size, offset, fi); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_release_cached(const char *path, struct fuse_file_info *fi) { int rv = gfarm2fs_release(path, fi); if (rv == 0 && ((fi->flags & O_ACCMODE) == O_WRONLY || (fi->flags & O_ACCMODE) == O_RDWR)) gfs_stat_cache_purge(path); return (rv); } #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) static int gfarm2fs_setxattr_cached(const char *path, const char *name, const char *value, size_t size, int flags) { int rv = gfarm2fs_setxattr(path, name, value, size, flags); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } static int gfarm2fs_removexattr_cached(const char *path, const char *name) { int rv = gfarm2fs_removexattr(path, name); if (rv == 0) gfs_stat_cache_purge(path); return (rv); } #endif /* HAVE_SETXATTR && ENABLE_XATTR */ static struct fuse_operations gfarm2fs_cached_oper = { .getattr = gfarm2fs_getattr, .fgetattr = gfarm2fs_fgetattr, .access = gfarm2fs_access, .readlink = gfarm2fs_readlink, #ifndef USE_GETDIR .opendir = gfarm2fs_opendir, .readdir = gfarm2fs_readdir, .releasedir = gfarm2fs_releasedir, #else .getdir = gfarm2fs_getdir, #endif .mknod = gfarm2fs_mknod_cached, .mkdir = gfarm2fs_mkdir_cached, .symlink = gfarm2fs_symlink_cached, .unlink = gfarm2fs_unlink_cached, .rmdir = gfarm2fs_rmdir_cached, .rename = gfarm2fs_rename_cached, .link = gfarm2fs_link_cached, .chmod = gfarm2fs_chmod_cached, .chown = gfarm2fs_chown_cached, .truncate = gfarm2fs_truncate_cached, .ftruncate = gfarm2fs_ftruncate_cached, .utime = gfarm2fs_utime_cached, .create = gfarm2fs_create_cached, .open = gfarm2fs_open_cached, .read = gfarm2fs_read, .write = gfarm2fs_write_cached, .statfs = gfarm2fs_statfs, .release = gfarm2fs_release_cached, .fsync = gfarm2fs_fsync, #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) .setxattr = gfarm2fs_setxattr_cached, .getxattr = gfarm2fs_getxattr, .listxattr = gfarm2fs_listxattr, .removexattr= gfarm2fs_removexattr_cached, #endif }; /*** *** main ***/ int main(int argc, char *argv[]) { struct fuse_operations *operation_mode = &gfarm2fs_cached_oper; gfarm_error_t e; struct fuse_args args = FUSE_ARGS_INIT(0, NULL); int i; umask(0); e = gfarm_initialize(&argc, &argv); if (e != GFARM_ERR_NO_ERROR) { fprintf(stderr, "%s: %s\n", *argv, gfarm_error_string(e)); exit(1); } if (argc > 0) fuse_opt_add_arg(&args, argv[0]); /* * specify '-s' option to disable multithreaded operations * libgfarm is not thread-safe for now */ fuse_opt_add_arg(&args, "-s"); for (i = 1; i < argc; i++) { if (argv[i][0] == '-' && argv[i][1] == 'E') { double timeout; char *ep; if (i + 1 >= argc) { fprintf(stderr, "%s: -E: missing <seconds>\n", program_name); exit(EXIT_FAILURE); } errno = 0; timeout = strtod(argv[i + 1], &ep); if (ep == optarg || *ep != '\0') { fprintf(stderr, "%s: -E %s: %s\n", program_name, argv[i+1], "invalid argument"); exit(EXIT_FAILURE); } else if (errno != 0) { fprintf(stderr, "%s: -E %s: %s\n", program_name, argv[i+1], strerror(errno)); exit(EXIT_FAILURE); } i++; if (timeout == 0.0) { gfs_stat_cache_enable(0); /* disable cache */ operation_mode = &gfarm2fs_oper; } else { gfs_stat_cache_expiration_set(timeout*1000.0); } } else { fuse_opt_add_arg(&args, argv[i]); } } return (fuse_main(args.argc, args.argv, operation_mode)); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc3/lib/libgfarm/gfutil/daemon.c #include <gfarm/gfarm_config.h> #include <fcntl.h> #include <unistd.h> #include "gfutil.h" #ifndef HAVE_DAEMON int gfarm_daemon(int not_chdir, int not_close) { switch (fork()) { case -1: return (-1); case 0: break; default: exit(0); } setsid(); if (!not_chdir) chdir("/"); if (!not_close) { int fd = open("/dev/null", O_RDWR, 0); if (fd != -1) { dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); } } return (0); } #endif /* !HAVE_DAEMON */ <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfsl/client2.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <limits.h> #include "gssapi.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_secure_session.h" #include "tcputil.h" #include "misc.h" static int port = 0; static unsigned long int addr = 0L; static char *hostname = NULL; static int ParseArgs(argc, argv) int argc; char *argv[]; { while (*argv != NULL) { if (strcmp(*argv, "-p") == 0) { if (*(argv + 1) != NULL) { int tmp; if (gfarmGetInt(*(++argv), &tmp) < 0) { fprintf(stderr, "illegal port number.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "port number must be > 0.\n"); return -1; } else if (tmp > 65535) { fprintf(stderr, "port number must be < 65536.\n"); return -1; } port = tmp; } } else if (strcmp(*argv, "-h") == 0) { if (*(argv + 1) != NULL) { unsigned long int tmp; argv++; tmp = gfarmIPGetAddressOfHost(*argv); if (tmp == ~0L || tmp == 0L) { fprintf(stderr, "Invalid hostname.\n"); return -1; } addr = tmp; hostname = *argv; } } argv++; } if (addr == 0L) { fprintf(stderr, "hostname is not specified.\n"); return -1; } if (port == 0) { fprintf(stderr, "port # is not specified.\n"); return -1; } return 0; } int main(argc, argv) int argc; char *argv[]; { OM_uint32 majStat; gfarmSecSession *ss0 = NULL; gfarmSecSession *ss1 = NULL; char buf[4096]; int z = 0; int ret = 1; int len; if (ParseArgs(argc - 1, argv + 1) != 0) { goto Done; } if (gfarmSecSessionInitializeInitiator(NULL, &majStat) <= 0) { fprintf(stderr, "can't initialize as initiator because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } ss0 = gfarmSecSessionInitiateByAddr(addr, port, GSS_C_NO_CREDENTIAL, NULL, &majStat); if (ss0 == NULL) { fprintf(stderr, "Can't initiate session 0 because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } ss1 = gfarmSecSessionInitiateByAddr(addr, port, GSS_C_NO_CREDENTIAL, NULL, &majStat); if (ss1 == NULL) { fprintf(stderr, "Can't initiate session 1 because of:\n"); gfarmGssPrintStatus(stderr, majStat); goto Done; } while (fgets(buf, 4096, stdin) != NULL) { len = strlen(buf); if (buf[len - 1] == '\n') { len--; } if (z % 2 == 0) { (void)gfarmSecSessionSendBytes(ss0, buf, len); } else { (void)gfarmSecSessionSendBytes(ss1, buf, len); } z++; } ret = 0; Done: if (ss0 != NULL) { gfarmSecSessionTerminate(ss0); } if (ss1 != NULL) { gfarmSecSessionTerminate(ss1); } gfarmSecSessionFinalizeInitiator(); return ret; } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT3-1-2-3_master_and_candidate_zabbix_agent_down #! /bin/sh ######################################################################## TESTID="FT3-1-2-3" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="zabbix agents on master and master candidate are down" ######################################################################## . ./FT-common ft_setup() { FT_MAIL_TIMEOUT=900 return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ft_checkpoint 1 "find master candidate gfmd" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd1 sudo /etc/init.d/zabbix-agent stop \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop zabbix-agent on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd2 sudo /etc/init.d/zabbix-agent stop \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop zabbix-agent on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "zabbix agent is not running on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "zabbix agent is not running on $gfmd2" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd1 sudo /etc/init.d/zabbix-agent start ssh $gfmd2 sudo /etc/init.d/zabbix-agent start ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_templates/format.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # NAME # format.py - Template_Gfarm_exported_all.xml を生成する # # SYNOPSIS # format.py # # DESCRIPTION # format.py は、gfarm-zabbix 用の監視テンプレート XML ファイル # Template_Gfarm_exported_all.xml の生成を行う Python スクリプトです。 # 動作確認は Python 2.7 で行っています。 # # もともと、gfarm-zabbix 用の監視テンプレートは単一の XML ファイルの # 形で提供していたわけではなく、たとえば gfmd の監視であれば # Template_Gfarm_common.xml と Template_Gfarm_redundant_gfmd.xml を # Zabbix にインポートするようになっていました。しかし、この方式では # いくつものテンプレートをインポートする必要があり、手順が煩雑でした。 # # そこで、単一の XML ファイルを用意することにしました。Zabbix には # インポートしたファイルを一括エクスポートして単一の XML ファイルと # して出力する機能があるので、常識的に考えればそれを使えば済む筈です。 # しかし残念なことに、Zabbix から一括エクスポートした XML ファイルを # 再びインポートすると、エラーになります。原因は、Zabbix が監視項目間 # の依存関係を考慮せずにエクスポートを行うため、監視項目の定義順序の # が正しくないからです。 # # 本スクリプトは、Zabbix から一括エクスポートした XML ファイルの定義 # 順序を直し、再度インポートできる形にします。 # # Zabbix から一括エクスポートした XML ファイルをカレントディレクトリ # に Template_Gfarm_exported_all.xml というファイル名で配置した状態で # 本スクリプトを実行して下さい。Template_Gfarm_exported_all.xml は # 定義順序が修正された形のものに上書きされます。 # from xml.etree.ElementTree import ElementTree if __name__ == '__main__': xml = "Template_Gfarm_exported_all.xml" tree = ElementTree() tree.parse(xml) hosts = tree.find('.//hosts') host_list = tree.findall('.//host') for host in host_list: hosts.remove(host) for host in host_list: if host.attrib['name'].endswith('_nodep'): hosts.append(host) for host in host_list: if not host.attrib['name'].endswith('_nodep'): hosts.append(host) tree.write(xml, encoding="UTF-8", xml_declaration=True, method="xml") <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/client.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <gssapi.h> #include <limits.h> #include "gfutil.h" #include "tcputil.h" #include "gfsl_config.h" #include "gfarm_gsi.h" #include "gfarm_secure_session.h" #include "misc.h" #include "scarg.h" extern void doClient(char *host, int port, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t deleCred, int deleCheck); static unsigned long int addr = 0L; static char *hostname = NULL; extern int testBufSize; static int ParseArgs(argc, argv) int argc; char *argv[]; { int c, tmp; while ((c = getopt(argc, argv, "s:h:" COMMON_OPTIONS)) != -1) { switch (c) { case 's': if (gfarmGetInt(optarg, &tmp) < 0) { fprintf(stderr, "illegal buffer size.\n"); return -1; } if (tmp <= 0) { fprintf(stderr, "buffer size must be > 0.\n"); return -1; } testBufSize = tmp; break; case 'h': addr = gfarmIPGetAddressOfHost(optarg); if (addr == ~0L || addr == 0L) { fprintf(stderr, "Invalid hostname.\n"); return -1; } hostname = optarg; break; default: if (HandleCommonOptions(c, optarg) != 0) return -1; break; } } if (optind < argc) { fprintf(stderr, "unknown extra argument %s\n", argv[optind]); return -1; } if (addr == 0L) { fprintf(stderr, "hostname is not specified.\n"); return -1; } if (port == 0) { fprintf(stderr, "port # is not specified.\n"); return -1; } return 0; } int main(argc, argv) int argc; char *argv[]; { OM_uint32 majStat; OM_uint32 minStat; if (ParseArgs(argc, argv) != 0) { return 1; } gflog_auth_set_verbose(1); if (gfarmSecSessionInitializeInitiator(NULL, NULL, &majStat, &minStat) <= 0) { fprintf(stderr, "can't initialize as initiator because of:\n"); gfarmGssPrintMajorStatus(majStat); gfarmGssPrintMinorStatus(minStat); gfarmSecSessionFinalizeInitiator(); return 1; } if (!acceptorSpecified) { acceptorNameString = malloc(sizeof("host@") + strlen(hostname)); if (acceptorNameString == NULL) { fprintf(stderr, "no memory\n"); return 1; } sprintf(acceptorNameString, "host@%s", hostname); acceptorNameType = GSS_C_NT_HOSTBASED_SERVICE; } doClient(hostname, port, acceptorNameString, acceptorNameType, GSS_C_NO_CREDENTIAL, 1); gfarmSecSessionFinalizeInitiator(); return 0; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc5/gftool/gfexec/gfexec.c /* * $Id$ */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <gfarm/gfarm.h> #include <openssl/evp.h> /* "gfs_pio.h" needs this for now */ #include "gfs_pio.h" #define PROGRAM_NAME "gfexec" static char progname[] = PROGRAM_NAME; #define BOURNE_SHELL "/bin/sh" static void print_usage() { fprintf(stderr, "usage: %s <program> [-N <nodes>] [-I <index>] [-s] <args> ...\n", progname); exit(2); } char * search_path(char *command) { int command_len, dir_len; char *result, *path; struct stat st; char buf[PATH_MAX]; if (strchr(command, '/') != NULL) { /* absolute or relative path */ result = command; goto finish; } command_len = strlen(command); path = getenv("PATH"); if (path == NULL) path = "/bin:/usr/bin:/usr/ucb:/usr/local/bin"; do { dir_len = strcspn(path, ":"); if (dir_len == 0) { if (command_len + 1 > sizeof(buf)) { fprintf(stderr, "%s: %s: path too long\n", progname, command); exit(1); } result = command; } else { if (dir_len + command_len + 2 > sizeof(buf)) { fprintf(stderr, "%s: %s: path too long (%s)\n", progname, command, path); exit(1); } memcpy(buf, path, dir_len); buf[dir_len] = '/'; strcpy(buf + dir_len + 1, command); result = buf; } if (access(result, X_OK) == 0 && stat(result, &st) == 0 && (st.st_mode & S_IFMT) == S_IFREG) goto finish; path += dir_len; } while (*path++ == ':'); /* not found in $PATH */ result = command; finish: result = strdup(result); if (result == NULL) { fprintf(stderr, "%s: no memory\n", progname); exit(1); } return (result); } int main(int argc, char *argv[], char *envp[]) { char *e, *gfarm_url, *local_path, **new_env, *cwd_env; int i, j, status, envc, rank = -1, nodes = -1; pid_t pid; static const char env_node_rank[] = "GFARM_NODE_RANK="; static const char env_node_size[] = "GFARM_NODE_SIZE="; static const char env_flags[] = "GFARM_FLAGS="; static const char env_gfs_pwd[] = "GFS_PWD="; char rankbuf[sizeof(env_node_rank) + GFARM_INT64STRLEN]; char nodesbuf[sizeof(env_node_size) + GFARM_INT64STRLEN]; char flagsbuf[sizeof(env_flags) + 3]; char cwdbuf[PATH_MAX * 2]; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm_initialize: %s\n", progname, e); exit(1); } /* * don't use getopt(3) here, because getopt(3) in glibc refers * argv[] passed to main(), instead of argv[] passed to getopt(3). */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; for (j = 1; argv[i][j] != '\0'; j++) { switch (argv[i][j]) { case 'I': if (argv[i][j + 1] != '\0') { rank = strtol(&argv[i][j+1], NULL, 0); j += strlen(&argv[i][j + 1]); } else if (i + 1 < argc) { rank = strtol(argv[++i], NULL, 0); j = strlen(argv[i]) - 1; } else { fprintf(stderr, "%s: -I: missing argument\n", progname); print_usage(); } break; case 'N': if (argv[i][j + 1] != '\0') { nodes = strtol(&argv[i][j+1], NULL, 0); j += strlen(&argv[i][j + 1]); } else if (i + 1 < argc) { nodes = strtol(argv[++i], NULL, 0); j = strlen(argv[i]) - 1; } else { fprintf(stderr, "%s: -N: missing argument\n", progname); print_usage(); } break; case 's': rank = 0; nodes = 1; break; case 'h': case '?': print_usage(); default: fprintf(stderr, "%s: invalid option -- %c\n", progname, argv[i][j]); print_usage(); } } } argc -= i; argv += i; if (argc == 0) print_usage(); e = gfs_realpath(argv[0], &gfarm_url); if (e != NULL) { /* XXX check `e' */ local_path = search_path(argv[0]); } else { e = gfarm_url_program_get_local_path(gfarm_url, &local_path); if (e != NULL) { fprintf(stderr, "%s: replicating %s: %s\n", progname, gfarm_url, e); exit(1); } } /* * the followings are only needed for pid==0 case. * but isn't it better to check errors before fork(2)? * * If gfs_pio_get_node_{rank,size}() fails, continue to * execute as a single process (not parallel processes). */ if (rank == -1) { e = gfs_pio_get_node_rank(&rank); if (e != NULL) rank = 0; } if (nodes == -1) { e = gfs_pio_get_node_size(&nodes); if (e != NULL) nodes = 1; } for (envc = 0; envp[envc] != NULL; envc++) ; new_env = malloc(sizeof(*new_env) * (envc + 4 + 1)); e = gfs_getcwd(cwdbuf, sizeof cwdbuf); if (e != NULL) { fprintf(stderr, "%s: cannot get current directory: %s\n", progname, e); exit(1); } if ((cwd_env = malloc(strlen(cwdbuf) + sizeof(env_gfs_pwd))) == NULL) { fprintf(stderr, "%s: no memory for %s%s\n", progname, env_gfs_pwd, cwdbuf); exit(1); } envc = 0; for (i = 0; (e = envp[i]) != NULL; i++) { if (memcmp(e, env_node_rank, sizeof(env_node_rank) -1 ) != 0 && memcmp(e, env_node_size, sizeof(env_node_size) -1 ) != 0 && memcmp(e, env_flags, sizeof(env_flags) - 1 ) != 0 && memcmp(e, env_gfs_pwd, sizeof(env_gfs_pwd) - 1) != 0) new_env[envc++] = e; } sprintf(rankbuf, "%s%d", env_node_rank, rank); new_env[envc++] = rankbuf; sprintf(nodesbuf, "%s%d", env_node_size, nodes); new_env[envc++] = nodesbuf; sprintf(flagsbuf, "%s%s%s%s", env_flags, gf_profile ? "p" : "", gf_on_demand_replication ? "r" : "", gf_hook_default_global ? "g" : ""); new_env[envc++] = flagsbuf; sprintf(cwd_env, "%s%s", env_gfs_pwd, cwdbuf); new_env[envc++] = cwd_env; new_env[envc++] = NULL; if (gf_stdout == NULL && gf_stderr == NULL) { /* what we need is to call exec(2) */ pid = 0; } else { /* * we have to call fork(2) and exec(2), to close * gf_stdout and gf_stderr by calling gfarm_terminate() * after the child program finished. */ pid = fork(); } switch (pid) { case -1: perror(PROGRAM_NAME ": fork"); status = 255; break; case 0: #if 0 /* * gfarm_terminate() should not be called here * because we need to keep the LDAP connection. */ if (gf_stdout == NULL && gf_stderr == NULL) { /* not to display profile statistics on gfarm_terminate() */ gfs_profile(gf_profile = 0); e = gfarm_terminate(); if (e != NULL) fprintf(stderr, "%s (child): gfarm_terminate: %s\n", progname, e); } else { /* * otherwise don't call gfarm_terminate(), because: * - it closes gf_stdout and gf_stderr. * - it causes: * "gfarm_terminate: Can't contact LDAP server" * on the parent process. */ } #endif execve(local_path, argv, new_env); if (errno != ENOEXEC) { perror(local_path); } else { /* * argv[-1] must be available, * because there should be "gfexec" at least. */ argv[-1] = BOURNE_SHELL; argv[0] = local_path; execve(BOURNE_SHELL, argv - 1, new_env); } _exit(255); default: if (waitpid(pid, &status, 0) == -1) { perror(PROGRAM_NAME ": waitpid"); status = 255; } else if (WIFSIGNALED(status)) { fprintf(stderr, "%s: signal %d received%s.\n", gfarm_host_get_self_name(), WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); status = 255; } else { status = WEXITSTATUS(status); } break; } /* not to display profile statistics on gfarm_terminate() */ gfs_profile(gf_profile = 0); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: gfarm_terminate: %s\n", progname, e); exit(1); } exit(status); } <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_3_0/gfarmfs.c /* GfarmFS-FUSE Gfarm: http://datafarm.apgrid.org/ FUSE: http://fuse.sourceforge.net/ Mount: $ ./gfarmfs [GfarmFS options] <mountpoint> [FUSE options] Unmount: $ fusermount -u <mountpoint> Copyright (c) 2005 National Institute of Advanced Industrial Science and Technology (AIST). All Rights Reserved. */ #define GFARMFS_VER "1.3" #define GFARMFS_VER_DATE "October 12, 2006" #if FUSE_USE_VERSION >= 25 /* # warning FUSE 2.5 compatible mode. */ #elif FUSE_USE_VERSION == 22 /* # warning FUSE 2.2 compatible mode. */ #define ENABLE_FASTCREATE #else # error Please install FUSE 2.2 or later #endif #include <fuse.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #ifdef USE_GFS_STATFSNODE #include <sys/statfs.h> #endif #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <libgen.h> #include <stdlib.h> #include <time.h> #include <gfarm/gfarm.h> #ifndef GFS_DEV #define GFS_DEV ((dev_t)-1); #endif #ifndef GFS_BLKSIZE #define GFS_BLKSIZE 8192 #endif #ifndef STAT_BLKSIZ #define STAT_BLKSIZ 512 #endif #define SYMLINK_MODE #ifdef SYMLINK_MODE #define SYMLINK_SUFFIX ".gfarmfs-symlink" #define SYMLINK_SUFFIX_LEN (sizeof(SYMLINK_SUFFIX)-1) #endif #define GFARM_USE_VERSION 1 #if GFARM_USE_VERSION == 1 #define REVISE_UTIME 1 /* problem of gfarm v1 */ #endif #define REVISE_CHMOD 0 /* limitation in global view of gfarm v1.3.1 or earlier */ #define NOFLAGMENTINFO_AUTO_DELETE 0 /* 1: enable */ /* ################################################################### */ static int gfarmfs_debug = 0; /* 1: error, 2: debug */ static int enable_symlink = 0; static int enable_linkiscopy = 0; static int enable_unlinkall = 0; static char *arch_name = NULL; static int enable_count_dir_nlink = 0; /* default: disable */ static int enable_print_enoent = 0; /* default: do not print ENOENT */ static FILE *enable_trace = NULL; static char *trace_out = "gfarmfs.trace"; /* default filename */ static char *gfarm_mount_point = ""; static int enable_gfarm_iobuf = 0; /* about GFARM_FILE_UNBUFFERED */ static int enable_exact_filesize = 0; /* 0: use gfarmfs_*_share_gf() operations (new) 1: use normal I/O operations (old) */ static int use_old_functions = 0; /* default: enable */ static int enable_fastcreate = 1; /* used on FUSE version 2.2 only */ /* >0: enable, 0: disable, <0: ignore */ #ifdef USE_GFS_STATFSNODE static int enable_statfs = 1; /* default: enable */ static int statfs_nhosts; #endif /* ################################################################### */ static int gmplen = -1; static inline char * add_gfarm_prefix(const char *path, char **urlp) { char *url; int len; if (gmplen == -1) gmplen = strlen(gfarm_mount_point); len = gmplen + strlen(path) + 7; url = malloc(sizeof(char) * len); if (url == NULL) return (GFARM_ERR_NO_MEMORY); snprintf(url, len, "gfarm:%s%s", gfarm_mount_point, path); *urlp = url; return (NULL); } #ifdef SYMLINK_MODE static inline char * add_gfarm_prefix_symlink_suffix(const char *path, char **urlp) { char *url; int len; if (gmplen == -1) gmplen = strlen(gfarm_mount_point); len = gmplen + strlen(path) + 7 + SYMLINK_SUFFIX_LEN; url = malloc(sizeof(char) * len); if (url == NULL) return (GFARM_ERR_NO_MEMORY); snprintf(url, len, "gfarm:%s%s%s", gfarm_mount_point, path, SYMLINK_SUFFIX); *urlp = url; return (NULL); } #endif #define gfarm_url2path(url) (url + 6) /* cut "gfarm:" */ #if 0 static char * gfarmfs_init() { return (NULL); } #else #define gfarmfs_init() (NULL) #endif static inline int gfarmfs_final(char *opname, char *e, int val_noerror, const char *name) { if (e == NULL) { if (enable_trace != NULL) { fprintf(enable_trace, "OK: %s: %s\n", opname, name); } return (val_noerror); } else { if (enable_trace != NULL) { fprintf(enable_trace, "NG: %s: %s: %s\n", opname, name, e); } if (gfarmfs_debug >= 1) { if (enable_print_enoent == 0 && e == GFARM_ERR_NO_SUCH_OBJECT) { /* do not print */ } else if (name != NULL) { fprintf(stderr, "%s: %s: %s\n", opname, name, e); } else { fprintf(stderr, "%s: %s\n", opname, e); } } return -gfarm_error_to_errno(e); } } static int gfarmfs_dir_nlink(const char *url) { GFS_Dir dir; struct gfs_dirent *entry; char *e; int res = 0; if (enable_count_dir_nlink == 0) { return (32000); } e = gfs_opendir(url, &dir); if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { if (S_ISDIR(DTTOIF(entry->d_type))) { res++; } } gfs_closedir(dir); } if (res == 0) { return (2); } else { return (res); } } #ifdef SYMLINK_MODE static int ends_with_and_delete(char *str, char *suffix) { int m, n; m = strlen(str) - 1; n = strlen(suffix) - 1; while (n >=0) { if (m <= 0 || str[m] != suffix[n]) { return (0); /* false */ } m--; n--; } str[m + 1] = '\0'; return (1); /* true */ } #endif #ifdef USE_GFARM_SCRAMBLE /* for scramble version */ #define gfarmfs_set_view_using_url(gf, url) gfs_pio_set_view_scramble(gf, 0) #define gfarmfs_set_view_using_mode(gf, mode) gfs_pio_set_view_scramble(gf, 0) #else /* for normal version */ static char * gfarmfs_set_view(GFS_File gf) { char *e; int nf; e = gfs_pio_get_nfragment(gf, &nf); if (e == NULL && nf <= 1) e = gfs_pio_set_view_index(gf, 1, 0, NULL, 0); else e = gfs_pio_set_view_global(gf, 0); return (e); } static char * gfarmfs_set_view_using_url(GFS_File gf, char *url) { char *e; if (arch_name != NULL) { e = gfs_access(url, X_OK); if (e == NULL) { e = gfs_pio_set_view_section(gf, arch_name, NULL, 0); return (e); } } return gfarmfs_set_view(gf); } static char * gfarmfs_set_view_using_mode(GFS_File gf, mode_t mode) { char *e; if (arch_name != NULL && GFARM_S_IS_PROGRAM(mode)) { e = gfs_pio_set_view_section(gf, arch_name, NULL, 0); return (e); } return gfarmfs_set_view(gf); } #endif static char * gfarmfs_create_empty_file(const char *path, mode_t mode) { char *e, *e2; char *url; GFS_File gf; e = add_gfarm_prefix(path, &url); if (e != NULL) return (e); e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, mode, &gf); if (e == NULL) { e2 = gfarmfs_set_view_using_mode(gf, mode); e = gfs_pio_close(gf); if (e2 != NULL) e = e2; } free(url); return (e); } /* ################################################################### */ /* FUSE version 2.2 only */ #ifdef ENABLE_FASTCREATE struct fastcreate { char *path; mode_t mode; }; static struct fastcreate fc = {NULL, 0}; static void gfarmfs_fastcreate_free() { if (fc.path != NULL) { free(fc.path); fc.path = NULL; } } static char * gfarmfs_fastcreate_flush() { if (fc.path != NULL) { char *e; if (gfarmfs_debug >= 2) { printf("fastcreate flush: %s\n", fc.path); } e = gfarmfs_create_empty_file(fc.path, fc.mode); if (e != NULL) { if (gfarmfs_debug >= 1) { printf("fastcreate flush error: %s: %s\n", fc.path, e); } } gfarmfs_fastcreate_free(); return (e); } else { return (NULL); /* do nothing */ } } static char * gfarmfs_fastcreate_save(const char *path, mode_t mode) { gfarmfs_fastcreate_flush(); fc.path = strdup(path); if (fc.path == NULL) { return (GFARM_ERR_NO_MEMORY); } fc.mode = mode; if (gfarmfs_debug >= 2) { printf("fastcreate add: %s\n", path); } return (NULL); } static char * gfarmfs_fastcreate_open(char *url, int flags, GFS_File *gfp) { char *e; char *path = gfarm_url2path(url); if (fc.path != NULL && strcmp(fc.path, path) == 0) { if (gfarmfs_debug >= 2) { printf("fastcreate open: %s\n", path); } e = gfs_pio_create(url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, fc.mode, gfp); if (e == NULL) { e = gfarmfs_set_view_using_mode( *gfp, fc.mode); if (e != NULL) gfs_pio_close(*gfp); } gfarmfs_fastcreate_free(); } else { gfarmfs_fastcreate_flush(); /* flush previous saved path */ e = gfs_pio_open(url, flags, gfp); if (e == NULL) { e = gfarmfs_set_view_using_url(*gfp, url); if (e != NULL) gfs_pio_close(*gfp); } } return (e); } static int gfarmfs_fastcreate_getattr(const char *path, struct stat *buf) { time_t now; if (fc.path != NULL && strcmp(fc.path, path) == 0) { memset(buf, 0, sizeof(struct stat)); buf->st_dev = GFS_DEV; buf->st_ino = 12345; /* XXX */ buf->st_mode = fc.mode; buf->st_nlink = 1; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = 0; buf->st_blksize = GFS_BLKSIZE; buf->st_blocks = 0; time(&now); buf->st_atime = buf->st_mtime = buf->st_ctime = now; return (1); } else { return (0); } } #define gfarmfs_fastcreate_check() \ (enable_fastcreate > 0 ? (gfarmfs_fastcreate_flush() == NULL ? 1 : -1) : 0) #else #define gfarmfs_fastcreate_check() #endif /* ENABLE_FASTCREATE */ /* ################################################################### */ static char * convert_gfs_stat_to_stat(const char *url, struct gfs_stat *gsp, struct stat *stp, int symlink) { /* referred to hooks_stat.c */ struct passwd *p; static struct passwd *p_save = NULL; static char *username_save = NULL; memset(stp, 0, sizeof(struct stat)); stp->st_dev = GFS_DEV; stp->st_ino = gsp->st_ino; stp->st_mode = gsp->st_mode; #ifdef SYMLINK_MODE if (symlink == 1) { stp->st_mode = 0777 | S_IFLNK; } #endif if (url != NULL && GFARM_S_ISDIR(stp->st_mode)) { stp->st_nlink = gfarmfs_dir_nlink(url); } else { stp->st_nlink = 1; } if (gsp->st_user != NULL && username_save != NULL && strcmp(gsp->st_user, username_save) == 0) { stp->st_uid = p_save->pw_uid; stp->st_gid = p_save->pw_gid; } else if (gsp->st_user != NULL && ((p = getpwnam(gsp->st_user)) != NULL)) { stp->st_uid = p->pw_uid; stp->st_gid = p->pw_gid; if (username_save != NULL) free(username_save); username_save = strdup(gsp->st_user); p_save = p; } else { stp->st_uid = getuid(); stp->st_gid = getgid(); } stp->st_size = gsp->st_size; stp->st_blksize = GFS_BLKSIZE; stp->st_blocks = (gsp->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; stp->st_atime = gsp->st_atimespec.tv_sec; stp->st_mtime = gsp->st_mtimespec.tv_sec; stp->st_ctime = gsp->st_ctimespec.tv_sec; return (NULL); } static char * gfarmfs_exact_filesize(char *url, file_offset_t *sizep, mode_t mode) { /* get st_size using gfs_fstat */ /* On Gfarm version 1.3 (or earlier), gfs_stat cannot get the exact st_size while a file is opened. But gfs_fstat can do it. */ GFS_File gf; int flags; char *e; struct gfs_stat gs; file_offset_t st_size; int change_mode = 0; mode_t save_mode = 0; if (mode & 0444) { flags = GFARM_FILE_RDONLY; #if 0 } else if (mode & 0200) { flags = GFARM_FILE_WRONLY; #endif } else { save_mode = mode; e = gfs_chmod(url, mode|0400); if (e != NULL) { printf("GETATTR: cancel fstat: %s: %s\n", gfarm_url2path(url), e); return (e); /* not my modifiable file */ } change_mode = 1; flags = GFARM_FILE_RDONLY; } e = gfs_pio_open(url, flags, &gf); if (e != NULL) goto revert_mode; #ifdef USE_GFARM_SCRAMBLE e = gfs_pio_set_view_scramble(gf, 0); if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size = gs.st_size; gfs_stat_free(&gs); #else if (GFARM_S_IS_PROGRAM(mode)) { if (arch_name == NULL) { e = gfs_pio_set_view_global(gf, 0); if (e != NULL) goto fstat_close; } else { e = gfs_pio_set_view_section(gf, arch_name, NULL, 0); } if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size = gs.st_size; gfs_stat_free(&gs); } else { int nf, i; e = gfs_pio_get_nfragment(gf, &nf); if (e != NULL) goto fstat_close; st_size = 0; for (i = 0; i < nf; i++) { e = gfs_pio_set_view_index(gf, nf, i, NULL, 0); if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size += gs.st_size; gfs_stat_free(&gs); } } #endif /* success */ *sizep = st_size; fstat_close: gfs_pio_close(gf); if (gfarmfs_debug > 0 && e != NULL && e != GFARM_ERR_NO_SUCH_OBJECT) printf("GETATTR: fstat: %s: %s\n", gfarm_url2path(url), e); revert_mode: if (change_mode == 1) { e = gfs_chmod(url, save_mode); if (e != NULL) printf("GETATTR: revert st_mode...: %s: %s\n", gfarm_url2path(url), e); } return (e); } static int gfarmfs_getattr(const char *path, struct stat *buf) { struct gfs_stat gs; char *e; char *url; int symlinkmode = 0; if ((e = gfarmfs_init()) != NULL) goto end; #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, buf)) { goto end; } #endif e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; if (gfarmfs_debug >= 2) { printf("GETATTR: for symlink: %s\n", gfarm_url2path(url)); } e = gfs_stat(url, &gs); symlinkmode = 1; } #endif if (enable_exact_filesize == 1 && e == NULL && GFARM_S_ISREG(gs.st_mode)) { char *e2; file_offset_t size; e2 = gfarmfs_exact_filesize(url, &size, gs.st_mode); if (e2 == NULL) gs.st_size = size; } #if NOFLAGMENTINFO_AUTO_DELETE == 1 /* to delete invalid path_info */ if (e == NULL && !GFARM_S_ISDIR(gs.st_mode) && !GFARM_S_ISREG(gs.st_mode)) { struct gfarm_path_info pi; char *e2; char *p; printf("GETATTR: invalid entry: %s\n", path); e2 = gfarm_canonical_path(path, &p); if (e2 == NULL) { e2 = gfarm_path_info_get(p, &pi); if (e2 == NULL) { pi.status.st_mode = 0100600; e2 = gfarm_path_info_replace(p, &pi); printf("path_info_replace: %s\n", e2); } free(p); } } if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION) { char *e2; e2 = gfs_unlink(url); printf("GETATTR: unlink: "); if (e2 == NULL) { printf("%s\n", path); } else { printf("%s: %s\n", path, e2); } e = GFARM_ERR_NO_SUCH_OBJECT; } #endif if (e == NULL) { e = convert_gfs_stat_to_stat(url, &gs, buf, symlinkmode); gfs_stat_free(&gs); } free(url); end: return gfarmfs_final("GETATTR", e, 0, path); } static int gfarmfs_getdir(const char *path, fuse_dirh_t h, fuse_dirfil_t filler) { GFS_Dir dir; struct gfs_dirent *entry; char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_opendir(url, &dir); free(url); } } if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { #ifdef SYMLINK_MODE if (enable_symlink == 1 && ends_with_and_delete(entry->d_name, SYMLINK_SUFFIX) > 0) { entry->d_type = DT_LNK; } #endif if (filler(h, entry->d_name, entry->d_type, entry->d_ino) != 0) break; } e = gfs_closedir(dir); } return gfarmfs_final("GETDIR", e, 0, path); } static int gfarmfs_mknod(const char *path, mode_t mode, dev_t rdev) { char *e; if ((e = gfarmfs_init()) != NULL) goto end; if (S_ISREG(mode)) { #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0) { e = gfarmfs_fastcreate_save(path, mode); } else { e = gfarmfs_create_empty_file(path, mode); } #else e = gfarmfs_create_empty_file(path, mode); #endif } else { if (gfarmfs_debug >= 1) { printf("MKNOD: not supported: mode = %o, rdev = %o\n", mode, (int)rdev); } e = GFARM_ERR_OPERATION_NOT_PERMITTED; } end: return gfarmfs_final("MKNOD", e, 0, path); } static int gfarmfs_mkdir(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_mkdir(url, mode); free(url); } } return gfarmfs_final("MKDIR", e, 0, path); } static int gfarmfs_unlink(const char *path) { char *e; char *url; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init()) != NULL) goto end; if (enable_unlinkall == 1) { /* remove an entry (all architecture) */ e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_unlink(url); free(url); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { if (gfarmfs_debug >= 2) { printf("UNLINK: for symlink: %s\n", path); } e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_unlink(url); free(url); } #endif } else { /* remove a self architecture file */ struct gfs_stat gs; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(url); if (gfarmfs_debug >= 2) { printf("UNLINK: for symlink: %s\n", path); } e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs); } #endif if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION) { e = gfs_unlink(url); if (e == GFARM_ERR_NO_SUCH_OBJECT) e = NULL; } else if (e == NULL) { /* gfs_stat succeeds */ if (GFARM_S_IS_PROGRAM(gs.st_mode)) { /* executable file */ char *arch; e = gfarm_host_get_self_architecture(&arch); if (e != NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } else { e = gfs_unlink_section(url, arch); } } else { /* regular file */ e = gfs_unlink(url); } gfs_stat_free(&gs); } free(url); } end: return gfarmfs_final("UNLINK", e, 0, path); } static int gfarmfs_rmdir(const char *path) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_rmdir(url); free(url); } } return gfarmfs_final("RMDIR", e, 0, path); } static int gfarmfs_readlink(const char *path, char *buf, size_t size) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n = 0; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init()) != NULL) goto end; if (enable_symlink == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_pio_open(url, GFARM_FILE_RDONLY, &gf); if (e == NULL) { e = gfs_pio_read(gf, buf, size - 1, &n); gfs_pio_close(gf); } free(url); buf[n] = '\0'; end: return gfarmfs_final("READLINK", e, 0, path); #else char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } return gfarmfs_final("READLINK", e, 0, path); #endif } static int gfarmfs_symlink(const char *from, const char *to) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n, len; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init()) != NULL) goto end; if (enable_symlink == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } e = add_gfarm_prefix_symlink_suffix(to, &url); if (e != NULL) goto end; e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, 0644, &gf); if (e != NULL) goto free_url; len = strlen(from); e = gfs_pio_write(gf, from, len, &n); gfs_pio_close(gf); if (len != n) { e = gfs_unlink(url); e = GFARM_ERR_INPUT_OUTPUT; goto free_url; } free_url: free(url); end: return gfarmfs_final("SYMLINK", e, 0, to); #else char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } return gfarmfs_final("SYMLINK", e, 0, to); #endif } static int gfarmfs_rename(const char *from, const char *to) { char *e; char *from_url; char *to_url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix(to, &to_url); if (e != NULL) goto free_from_url; e = gfs_rename(from_url, to_url); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(from_url); free(to_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix_symlink_suffix(to, &to_url); if (e != NULL) goto free_from_url; if (gfarmfs_debug >= 2) { printf("RENAME: for symlink: %s\n", from); } e = gfs_rename(from_url, to_url); } #endif free(to_url); free_from_url: free(from_url); } end: return gfarmfs_final("RENAME", e, 0, from); } #define COPY_BUFSIZE GFS_BLKSIZE static int gfarmfs_link(const char *from, const char *to) { char *e, *e2; char *from_url, *to_url; GFS_File from_gf, to_gf; struct gfs_stat gs; int m, n; char buf[COPY_BUFSIZE]; struct gfarm_timespec gt[2]; #ifdef SYMLINK_MODE int symlinkmode = 0; #endif int change_mode = 0; mode_t save_mode = 0; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init()) != NULL) goto end; if (enable_linkiscopy == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } if (gfarmfs_debug >= 2) { printf("LINK: hard link is replaced by copy: %s\n", to); } /* get gfs_stat and check symlink mode */ e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; /* need to feee from_url [1] */ e = gfs_stat(from_url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(from_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; if (gfarmfs_debug >= 2) { printf("LINK: for symlink: %s\n", from); } e = gfs_stat(from_url, &gs); symlinkmode = 1; } #endif if (e != NULL) goto free_from_url; /* need to free gfs_stat [2] */ if ((gs.st_mode & 0400) == 0) { save_mode = gs.st_mode; e = gfs_chmod(from_url, gs.st_mode|0400); if (e == NULL) { change_mode = 1; } } /* need to revert mode [3] */ e = gfs_pio_open(from_url, GFARM_FILE_RDONLY, &from_gf); if (e != NULL) goto free_gfs_stat; /* need to close from_gf [4] */ e = gfarmfs_set_view_using_url(from_gf, from_url); if (e != NULL) goto close_from_gf; #ifdef SYMLINK_MODE if (symlinkmode == 1) { e = add_gfarm_prefix_symlink_suffix(to, &to_url); } else { e = add_gfarm_prefix(to, &to_url); } #else e = add_gfarm_prefix(to, &to_url); #endif if (e != NULL) goto close_from_gf; /* need to free to_url [5] */ e = gfs_pio_create(to_url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, gs.st_mode, &to_gf); if (e != NULL) goto free_to_url; /* need to close to_gf [6] */ e = gfarmfs_set_view_using_mode(to_gf, gs.st_mode); if (e != NULL) goto close_to_gf; for (;;) { /* copy */ e = gfs_pio_read(from_gf, buf, COPY_BUFSIZE, &m); if (e != NULL) break; if (m == 0) { /* EOF: success (e == NULL) */ break; } e = gfs_pio_write(to_gf, buf, m, &n); if (e != NULL) break; if (m != n) { e = GFARM_ERR_INPUT_OUTPUT; break; } } close_to_gf: /* [6] */ e2 = gfs_pio_close(to_gf); if (e == NULL && e2 == NULL) { gt[0].tv_sec = gs.st_atimespec.tv_sec; gt[0].tv_nsec= gs.st_atimespec.tv_nsec; gt[1].tv_sec = gs.st_mtimespec.tv_sec; gt[1].tv_nsec= gs.st_mtimespec.tv_nsec; e = gfs_utimes(to_url, gt); } else { (void)gfs_unlink(to_url); if (e == NULL && e2 != NULL) { e = e2; } } free_to_url: /* [5] */ free(to_url); close_from_gf: /* [4] */ gfs_pio_close(from_gf); free_gfs_stat: /* [3] */ gfs_stat_free(&gs); /* revert_mode: [2] */ if (change_mode == 1) { e2 = gfs_chmod(from_url, save_mode); if (e == NULL && e2 != NULL) { e = e2; } } free_from_url: /* [1] */ free(from_url); end: return gfarmfs_final("LINK", e, 0, to); } static int gfarmfs_chmod(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_chmod(url, mode); free(url); } } return gfarmfs_final("CHMOD", e, 0, path); } static int gfarmfs_chown(const char *path, uid_t uid, gid_t gid) { char *e; char *url = NULL; struct gfs_stat s; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_stat(url, &s); free(url); } #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (gfarmfs_debug >= 2) { printf("CHOWN: for symlink: %s\n", gfarm_url2path(url)); } if (e == NULL) { e = gfs_stat(url, &s); free(url); } } #endif if (e == NULL) { if (strcmp(s.st_user, gfarm_get_global_username()) != 0) { /* EPERM */ e = GFARM_ERR_OPERATION_NOT_PERMITTED; } /* XXX - else: do nothing */ gfs_stat_free(&s); } } return gfarmfs_final("CHOWN", e, 0, path); } static int gfarmfs_truncate(const char *path, off_t size) { char *e; GFS_File gf; char *url; gfarmfs_fastcreate_check(); e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_init(); while (e == NULL) { e = gfs_pio_open(url, GFARM_FILE_WRONLY, &gf); if (e != NULL) break; e = gfarmfs_set_view_using_url(gf, url); if (e == NULL) { e = gfs_pio_truncate(gf, size); } gfs_pio_close(gf); break; } free(url); end: return gfarmfs_final("TRUNCATE", e, 0, path); } static int gfarmfs_utime(const char *path, struct utimbuf *buf) { char *e; char *url; gfarmfs_fastcreate_check(); e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_init(); if (e == NULL) { if (buf == NULL) e = gfs_utimes(url, NULL); else { struct gfarm_timespec gt[2]; gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } } free(url); end: return gfarmfs_final("UTIME", e, 0, path); } static inline GFS_File gfarmfs_cast_fh(struct fuse_file_info *fi) { return (GFS_File)(unsigned long) fi->fh; } static int gfarmfs_open(const char *path, struct fuse_file_info *fi) { char *e; char *url; int flags = 0; GFS_File gf; e = gfarmfs_init(); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; if ((fi->flags & O_ACCMODE) == O_RDONLY) { flags = GFARM_FILE_RDONLY; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { flags = GFARM_FILE_WRONLY; } else if ((fi->flags & O_ACCMODE) == O_RDWR) { flags = GFARM_FILE_RDWR; } if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0) { /* check a created file on memory and create/open */ /* with checking program */ e = gfarmfs_fastcreate_open(url, flags, &gf); if (e != NULL) goto free_url; } else { #endif e = gfs_pio_open(url, flags, &gf); if (e != NULL) goto free_url; e = gfarmfs_set_view_using_url(gf, url); if (e != NULL) { gfs_pio_close(gf); goto free_url; } #ifdef ENABLE_FASTCREATE } #endif fi->fh = (unsigned long) gf; free_url: free(url); end: return gfarmfs_final("OPEN", e, 0, path); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { char *e; char *url; int flags = 0; GFS_File gf; e = gfarmfs_init(); while (e == NULL) { if ((fi->flags & O_ACCMODE) == O_RDONLY) { flags = GFARM_FILE_RDONLY; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { flags = GFARM_FILE_WRONLY; } else if ((fi->flags & O_ACCMODE) == O_RDWR) { flags = GFARM_FILE_RDWR; } if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } e = add_gfarm_prefix(path, &url); if (e != NULL) break; e = gfs_pio_create(url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, mode, &gf); if (e != NULL) { free(url); break; } e = gfarmfs_set_view_using_mode(gf, mode); free(url); if (e != NULL) { gfs_pio_close(gf); break; } fi->fh = (unsigned long) gf; break; } return gfarmfs_final("CREATE", e, 0, path); } static int gfarmfs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { char *e; struct gfs_stat gs; e = gfarmfs_init(); if (e == NULL) { e = gfs_fstat(gfarmfs_cast_fh(fi), &gs); if (e == NULL) { e = convert_gfs_stat_to_stat(NULL, &gs, stbuf, 0); gfs_stat_free(&gs); } } return gfarmfs_final("FGETATTR", e, 0, path); } static int gfarmfs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { char *e; GFS_File gf; e = gfarmfs_init(); if (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_truncate(gf, size); } return gfarmfs_final("FTRUNCATE", e, 0, path); } static int gfarmfs_access(const char *path, int mask) { char *e; char *url; e = gfarmfs_init(); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_access(url, mask); free(url); } } return gfarmfs_final("ACCESS", e, 0, path); } #endif /* FUSE_USE_VERSION >= 25 */ static int gfarmfs_release(const char *path, struct fuse_file_info *fi) { char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e == NULL) { e = gfs_pio_close(gfarmfs_cast_fh(fi)); } return gfarmfs_final("RELEASE", e, 0, path); } static int gfarmfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(); while (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_read(gf, buf, size, &n); break; } return gfarmfs_final("READ", e, n, path); } static int gfarmfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(); while (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_write(gf, buf, size, &n); break; } return gfarmfs_final("WRITE", e, n, path); } static int gfarmfs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { char *e; GFS_File gf; if ((e = gfarmfs_init()) != NULL) goto end; gf = gfarmfs_cast_fh(fi); if (isdatasync) { e = gfs_pio_datasync(gf); } else { e = gfs_pio_sync(gf); } end: return gfarmfs_final("FSYNC", e, 0, path); } #ifdef USE_GFS_STATFSNODE static char * gfs_statfsnode_cached_and_retry( char *hostname, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e; e = gfs_statfsnode_cached(hostname, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { e = gfs_statfsnode(hostname, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); } if (e != NULL) { if (gfarmfs_debug > 0) { printf("ERROR: STATFS: %s: %s\n", hostname, e); } if (e == GFARM_ERR_NO_SUCH_OBJECT) { e = GFARM_ERR_CONNECTION_REFUSED; } } return (e); } static char * gfs_statfsnode_total_of_hostlist( char **hosts, int nhosts, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e, *e_save = NULL; int i, ok; gfarm_int32_t bsize; file_offset_t blocks, bfree ,bavail, files, ffree, favail; *bsizep = *blocksp = *bfreep = *bavailp = *filesp = *ffreep = *favailp = 0; ok = 0; for (i = 0; i < nhosts; i++) { e = gfs_statfsnode_cached_and_retry(hosts[i], &bsize, &blocks, &bfree, &bavail, &files, &ffree, &favail); if (e == NULL) { if (*bsizep == 0) { if (bsize == 0) continue; *bsizep = bsize; } ok = 1; if (*bsizep == bsize) { *blocksp += blocks; *bfreep += bfree; *bavailp += bavail; } else { /* revision (rough) */ *blocksp += blocks * bsize / *bsizep; *bfreep += bfree * bsize / *bsizep; *bavailp += bavail * bsize / *bsizep; } *filesp += files; *ffreep += ffree; *favailp += favail; } else { e_save = e; } } if (ok == 1) { return (NULL); } else { return (e_save); } } static inline int gfarmfs_statfs_common( const char *path, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e; int nhosts = statfs_nhosts, i; static char **hosts = NULL; if ((e = gfarmfs_init()) != NULL) goto end; if (hosts == NULL) { hosts = malloc(nhosts * sizeof(char *)); if (hosts == NULL) { e = GFARM_ERR_NO_MEMORY; goto end; } } e = gfarm_schedule_search_idle_acyclic_by_domainname( "", &nhosts, hosts); if (e != NULL) goto end; e = gfs_statfsnode_total_of_hostlist( hosts, nhosts, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); for (i = 0; i < nhosts; i++) { if (hosts[i]) { free(hosts[i]); hosts[i] = NULL; } } end: return gfarmfs_final("STATFS", e, 0, path); } #if FUSE_USE_VERSION == 22 static int gfarmfs_statfs(const char *path, struct statfs *stfs) { file_offset_t favail; return gfarmfs_statfs_common(path, (gfarm_int32_t*)&stfs->f_bsize, (file_offset_t*)&stfs->f_blocks, (file_offset_t*)&stfs->f_bfree, (file_offset_t*)&stfs->f_bavail, (file_offset_t*)&stfs->f_files, (file_offset_t*)&stfs->f_ffree, (file_offset_t*)&favail); } #elif FUSE_USE_VERSION >= 25 static int gfarmfs_statfs(const char *path, struct statvfs *stvfs) { int res; gfarm_int32_t bsize = 0; res = gfarmfs_statfs_common(path, &bsize, (file_offset_t*)&stvfs->f_blocks, (file_offset_t*)&stvfs->f_bfree, (file_offset_t*)&stvfs->f_bavail, (file_offset_t*)&stvfs->f_files, (file_offset_t*)&stvfs->f_ffree, (file_offset_t*)&stvfs->f_favail); stvfs->f_bsize = (unsigned long) bsize; return (res); } #endif /* FUSE_USE_VERSION */ #endif /* USE_GFS_STATFSNODE */ #if 1 static int gfarmfs_flush(const char *path, struct fuse_file_info *fi) { char *e = gfarmfs_init(); #if 0 /* TODO */ GFS_File gf; if (e != NULL) goto end; if ((fi->flags & O_ACCMODE) != O_RDONLY) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_sync(gf); } end: #endif return gfarmfs_final("(FLUSH)", e, 0, path); } #endif #if 0 /* #ifdef HAVE_SETXATTR */ static int gfarmfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return (-ENOSYS); } static int gfarmfs_getxattr(const char *path, const char *name, char *value, size_t size) { return (-ENOSYS); } static int gfarmfs_listxattr(const char *path, char *list, size_t size) { return (-ENOSYS); } static int gfarmfs_removexattr(const char *path, const char *name) { return (-ENOSYS); } #endif /* HAVE_SETXATTR */ static struct fuse_operations gfarmfs_oper_base = { .getattr = gfarmfs_getattr, .readlink = gfarmfs_readlink, .getdir = gfarmfs_getdir, .mknod = gfarmfs_mknod, .mkdir = gfarmfs_mkdir, .symlink = gfarmfs_symlink, .unlink = gfarmfs_unlink, .rmdir = gfarmfs_rmdir, .rename = gfarmfs_rename, .link = gfarmfs_link, .chmod = gfarmfs_chmod, .chown = gfarmfs_chown, .truncate = gfarmfs_truncate, .utime = gfarmfs_utime, .open = gfarmfs_open, .read = gfarmfs_read, .write = gfarmfs_write, .release = gfarmfs_release, .fsync = gfarmfs_fsync, #ifdef USE_GFS_STATFSNODE .statfs = gfarmfs_statfs, #endif #if FUSE_USE_VERSION >= 25 .create = gfarmfs_create, .fgetattr = gfarmfs_fgetattr, .ftruncate = gfarmfs_ftruncate, .access = gfarmfs_access, #endif #if 1 .flush = gfarmfs_flush, #endif #if 0 /* #ifdef HAVE_SETXATTR */ .setxattr = gfarmfs_setxattr, .getxattr = gfarmfs_getxattr, .listxattr = gfarmfs_listxattr, .removexattr = gfarmfs_removexattr, #endif }; /* ################################################################### */ /* new I/O functions (share GFS_File about opening the same file) */ #define FH_LIST_USE_INO 0 /* key: 0=path, 1=ino */ struct gfarmfs_fh { #if FH_LIST_USE_INO == 1 long ino; #else char *path; #endif GFS_File gf; int flags; /* current flag */ int nopen; int nwrite; #if REVISE_CHMOD == 1 int mode_changed; mode_t save_mode; #endif #if REVISE_UTIME == 1 int utime_changed; struct gfarm_timespec save_utime[2]; #endif }; #define FH_LIST_LEN 1024 struct gfarmfs_fh *gfarmfs_fh_list[FH_LIST_LEN]; #if FH_LIST_USE_INO == 1 #define FH_GET1(url) gfarmfs_fh_get_key_url(url) #define FH_GET2(url, ino) gfarmfs_fh_get(ino) #define FH_ADD1(url, fh) gfarmfs_fh_add_key_url(url, fh) #define FH_ADD2(url, ino, fh) gfarmfs_fh_add(ino, fh) #define FH_REMOVE1(url) gfarmfs_fh_remove_key_url(url) #define FH_REMOVE2(url, ino) gfarmfs_fh_remove(ino) #define FH_FREE(fh) free(fh) #else #define FH_GET1(url) gfarmfs_fh_get(url) #define FH_GET2(url, ino) gfarmfs_fh_get(url) #define FH_ADD1(url, fh) gfarmfs_fh_add(url, fh) #define FH_ADD2(url, ino, fh) gfarmfs_fh_add(url, fh) #define FH_REMOVE1(url) gfarmfs_fh_remove(url) #define FH_REMOVE2(url, ino) gfarmfs_fh_remove(url) #define FH_FREE(fh) gfarmfs_fh_free(fh) #endif #if FH_LIST_USE_INO == 1 /* key is ino */ static char * gfarmfs_get_ino(char *url, long *inop) { char *e; struct gfs_stat gs; e = gfs_stat(url, &gs); if (e == NULL) { *inop = gs.st_ino; gfs_stat_free(&gs); return (NULL); } return (e); } static struct gfarmfs_fh * gfarmfs_fh_get(long ino) { int i; if (ino < 0) return (NULL); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && gfarmfs_fh_list[i]->ino == ino) { return gfarmfs_fh_list[i]; } } return (NULL); } static struct gfarmfs_fh * gfarmfs_fh_get_key_url(char *url) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return (NULL); return gfarmfs_fh_get(ino); } static char * gfarmfs_fh_add(long ino, struct gfarmfs_fh *fh) { int i; #if 0 if (gfarmfs_fh_get(ino)) return (GFARM_ERR_ALREADY_EXISTS); #endif for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] == NULL) { fh->ino = ino; gfarmfs_fh_list[i] = fh; return (NULL); } } return (GFARM_ERR_NO_MEMORY); /* EMFILE ? */ } #if 0 static char * gfarmfs_fh_add_key_url(char *url, struct gfarmfs_fh *fh) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return (e); return gfarmfs_fh_add(ino, fh); } #endif static void gfarmfs_fh_remove(long ino) { int i; if (ino < 0) return; for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && gfarmfs_fh_list[i]->ino == ino) { gfarmfs_fh_list[i] = NULL; return; } } return; } #if 0 static void gfarmfs_fh_remove_key_url(char *url) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return; return gfarmfs_fh_remove(ino); } #endif #else /* FH_LIST_USE_INO != 1 */ /* key is url */ static struct gfarmfs_fh * gfarmfs_fh_get(char *url) { int i; char *path; if (url == NULL) return (NULL); path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && strcmp(gfarmfs_fh_list[i]->path, path) == 0) { return gfarmfs_fh_list[i]; } } return (NULL); } static char * gfarmfs_fh_add(char *url, struct gfarmfs_fh *fh) { int i; char *path; #if 0 if (gfarmfs_fh_get(url)) return (GFARM_ERR_ALREADY_EXISTS); #endif path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] == NULL) { if (fh->path != NULL) free(fh->path); fh->path = strdup(path); if (fh->path == NULL) return (GFARM_ERR_NO_MEMORY); gfarmfs_fh_list[i] = fh; return (NULL); } } return (GFARM_ERR_NO_MEMORY); /* EMFILE ? */ } static void gfarmfs_fh_remove(char *url) { int i; char *path; if (url == NULL) return; path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && strcmp(gfarmfs_fh_list[i]->path, path) == 0) { free(gfarmfs_fh_list[i]->path); gfarmfs_fh_list[i]->path = NULL; gfarmfs_fh_list[i] = NULL; return; } } return; } static void gfarmfs_fh_free(struct gfarmfs_fh *fh) { if (fh->path) free(fh->path); free(fh); } #endif /* FH_LIST_USE_INO == 1 */ static char * gfarmfs_fh_alloc(struct gfarmfs_fh **fhp) { struct gfarmfs_fh *fh; fh = malloc(sizeof(struct gfarmfs_fh)); if (fh == NULL) return (GFARM_ERR_NO_MEMORY); fh->gf = NULL; fh->flags = 0; fh->nopen = 0; fh->nwrite = 0; #if FH_LIST_USE_INO == 1 /* fh->ino = -1 */ #else fh->path = NULL; #endif #if REVISE_CHMOD == 1 fh->mode_changed = 0; #endif #if REVISE_UTIME == 1 fh->utime_changed = 0; #endif *fhp = fh; return (NULL); } static inline char * gfs_pio_open_common(char *url, int flags, GFS_File *gfp, mode_t *create_modep) { char *e; if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } #ifdef ENABLE_FASTCREATE /* created a file on MKNOD */ if (enable_fastcreate > 0) { e = gfarmfs_fastcreate_open(url, flags, gfp); } else { e = gfs_pio_open(url, flags, gfp); if (e != NULL) return (e); e = gfarmfs_set_view_using_url(*gfp, url); if (e != NULL) gfs_pio_close(*gfp); } #else if (create_modep) { e = gfs_pio_create( url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, *create_modep, gfp); if (e != NULL) return (e); e = gfarmfs_set_view_using_mode(*gfp, *create_modep); } else { e = gfs_pio_open(url, flags, gfp); if (e != NULL) return (e); e = gfarmfs_set_view_using_url(*gfp, url); } if (e != NULL) gfs_pio_close(*gfp); #endif return (e); } static int gfarmfs_open_common_share_gf(char *opname, const char *path, struct fuse_file_info *fi, mode_t *create_modep) { char *e; char *url; struct gfs_stat gs; struct gfarmfs_fh *fh; long ino = 0; mode_t save_mode = 0; GFS_File gf; #ifdef ENABLE_FASTCREATE struct stat st; #endif if ((e = gfarmfs_init()) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; if (create_modep) { /* normal CREATE */ fh = NULL; #ifdef ENABLE_FASTCREATE } else if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, &st)) { /* fastcreate */ create_modep = &st.st_mode; fh = NULL; #endif } else { /* normal OPEN */ e = gfs_stat(url, &gs); if (e != NULL) goto free_url; ino = gs.st_ino; save_mode = gs.st_mode; gfs_stat_free(&gs); fh = FH_GET2(url, ino); } if (fh == NULL) { /* new gfarmfs_fh */ e = gfarmfs_fh_alloc(&fh); if (e != NULL) goto free_url; if ((fi->flags & O_ACCMODE) == O_RDONLY) { e = gfs_pio_open_common(url, GFARM_FILE_RDONLY, &gf, create_modep); if (e == NULL) { fh->gf = gf; fh->flags = GFARM_FILE_RDONLY; fh->nopen++; } } else { /* WRONLY or RDWR */ e = gfs_pio_open_common(url, GFARM_FILE_RDWR, &gf, create_modep); if (e == NULL) { fh->flags = GFARM_FILE_RDWR; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { /* minor case (mode is 0200) */ e = gfs_pio_open_common( url, GFARM_FILE_WRONLY, &gf, create_modep); if (e == NULL) fh->flags = GFARM_FILE_WRONLY; } if (e == NULL) { fh->gf = gf; fh->nopen++; fh->nwrite++; } } #if FH_LIST_USE_INO != 0 /* key is ino */ if (create_modep && e == NULL) { /* get st_ino */ e = gfs_fstat(gf, &gs); if (e == NULL) { ino = gs.st_ino; gfs_stat_free(&gs); } } #endif if (e == NULL) { struct gfarmfs_fh *fh2 = FH_GET2(url, ino); if (fh2 != NULL) { printf("WARN: This must not happen.\n"); e = GFARM_ERR_ALREADY_EXISTS; } else e = FH_ADD2(url, ino, fh); } if (e != NULL) { if (fh->gf) gfs_pio_close(fh->gf); FH_FREE(fh); } } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDWR) { fh->nopen++; if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite++; } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDONLY && (fi->flags & O_ACCMODE) == O_RDONLY) { fh->nopen++; } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY && (fi->flags & O_ACCMODE) == O_WRONLY) { fh->nopen++; fh->nwrite++; } else { /* RDONLY or WRONLY -> RDWR */ e = gfs_pio_open_common(url, GFARM_FILE_RDWR, &gf, NULL); if (e != NULL) { /* retry */ if ((fi->flags & O_ACCMODE) == O_RDONLY) e = gfs_access(url, R_OK); else if ((fi->flags & O_ACCMODE) == O_WRONLY) e = gfs_access(url, W_OK); if (e == NULL) e = gfs_chmod(url, save_mode|0600); if (e == NULL) { char *e2; e = gfs_pio_open_common( url, GFARM_FILE_RDWR, &gf, NULL); #if REVISE_CHMOD == 1 /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = save_mode; e2 = gfs_chmod(url, save_mode); #else /* gfs_fchmod cannot work in global view (the case of nsection >= 2) on gfarm v1.3.1 or earlier */ e2 = gfs_fchmod(gf, save_mode); #endif if (e2 != NULL) { /* What happen ? */ printf("WARN: chmod failed at OPEN: %o: %s: %s\n", save_mode, path, e2); } } } if (e == NULL) { (void)gfs_pio_close(fh->gf); fh->gf = gf; fh->flags = GFARM_FILE_RDWR; fh->nopen++; if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite++; } } if (e == NULL) fi->fh = (unsigned long) fh; free_url: free(url); end: return gfarmfs_final(opname, e, 0, path); } static int gfarmfs_open_share_gf(const char *path, struct fuse_file_info *fi) { return gfarmfs_open_common_share_gf("OPEN", path, fi, NULL); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_create_share_gf(const char *path, mode_t mode, struct fuse_file_info *fi) { return gfarmfs_open_common_share_gf("CREATE", path, fi, &mode); } #endif #if REVISE_CHMOD == 1 #define IS_EXECUTABLE(mode) ((mode) & 0111 ? 1 : 0) #endif static inline char * gfarmfs_chmod_share_gf_internal(char *url, mode_t mode) { char *e; struct gfs_stat gs; struct gfarmfs_fh *fh; mode_t old_mode; e = gfs_stat(url, &gs); if (e != NULL) goto end; fh = FH_GET2(url, gs.st_ino); #if REVISE_CHMOD == 1 if (fh != NULL) { /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = mode; } #endif old_mode = gs.st_mode; gfs_stat_free(&gs); #if REVISE_CHMOD == 1 if (fh != NULL) { /* somebody opens this open */ if (IS_EXECUTABLE(old_mode) == IS_EXECUTABLE(mode)) { e = gfs_chmod(url, mode); if (e != NULL && fh->mode_changed == 1) fh->mode_changed = 0; } /* (else): somebody opens this file and changes executable bit. -> gfs_chmod on RELEASE only In Gfarm v1, gfs_pio_close fails at replacing section info in this case. */ /* always succeeed ... (e == NULL) */ } else { /* nobody opens this file */ e = gfs_chmod(url, mode); } #else if (fh != NULL) /* somebody opens this open */ /* gfs_fchmod cannot work in global view (the case of nsection >= 2) on gfarm v1.3.1 or earlier */ e = gfs_fchmod(fh->gf, mode); else e = gfs_chmod(url, mode); #endif end: return (e); } static int gfarmfs_chmod_share_gf(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_chmod_share_gf_internal(url, mode); free(url); end: return gfarmfs_final("CHMOD", e, 0, path); } static inline char * gfarmfs_utime_share_gf_internal(char *url, struct utimbuf *buf) { char *e; struct gfarm_timespec gt[2]; if (buf == NULL) e = gfs_utimes(url, NULL); else { gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } #if REVISE_UTIME == 1 if (e == NULL) { struct gfarmfs_fh *fh; fh = FH_GET1(url); if (fh != NULL) { /* must utime on release */ fh->utime_changed = 1; if (buf == NULL) { time_t t; time(&t); fh->save_utime[0].tv_sec = t; fh->save_utime[0].tv_nsec = 0; fh->save_utime[1].tv_sec = t; fh->save_utime[1].tv_nsec = 0; } else { fh->save_utime[0] = gt[0]; fh->save_utime[1] = gt[1]; } } } #endif return (e); } static int gfarmfs_utime_share_gf(const char *path, struct utimbuf *buf) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_utime_share_gf_internal(url, buf); free(url); end: return gfarmfs_final("UTIME", e, 0, path); } static char * gfarmfs_rename_share_gf_check_open(char *from_url, char *to_url, long from_ino, mode_t from_mode) { char *e; struct gfarmfs_fh *fh; #if GFARM_USE_VERSION == 1 /* for Gfarm version 1 */ fh = FH_GET2(from_url, from_ino); if (fh != NULL) { FH_REMOVE2(from_url, from_ino); gfs_pio_close(fh->gf); /* so that gfs_pio_close can set metadata correctly */ } e = gfs_rename(from_url, to_url); if (fh != NULL) { /* somebody opens this file */ char *e2; char *url; GFS_File gf; int retry; if (e == NULL) url = to_url; /* renamed */ else url = from_url; /* recover */ retry = 0; retry: if (retry) { char *e3; e3 = gfs_chmod(url, from_mode|0600); if (e3 == NULL) fh->flags = GFARM_FILE_RDWR; else return (e); } e2 = gfs_pio_open_common(url, fh->flags, &gf, NULL); if (retry) { char *e3; #if REVISE_CHMOD == 1 /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = from_mode; e3 = gfs_chmod(url, from_mode); #else if (e2 == NULL) /* gfs_fchmod cannot work in global view (the case of nsection >= 2) on gfarm v1.3.1 or earlier */ e3 = gfs_fchmod(gf, from_mode); else e3 = gfs_chmod(url, from_mode); #endif if (e3 != NULL) { /* What happen ? */ printf("WARN: RENAME: chmod failed: %o: %s: %s\n", from_mode, gfarm_url2path(url), e3); } } if (e2 == NULL) { /* open succeeeded */ struct gfs_stat gs; fh->gf = gf; e2 = gfs_fstat(gf, &gs); if (e2 == NULL) { e2 = FH_ADD2(url, gs.st_ino, fh); gfs_stat_free(&gs); } else { /* What happen ? */ printf("WARN: RENAME: some problem may happen later: %s\n", gfarm_url2path(url)); FH_FREE(fh); } } else { /* somebody changes st_mode */ if (retry == 0) { retry = 1; goto retry; } /* fatal situation ! */ fh->gf = NULL; printf("FATAL: RENAME: can't read/write more than this: %s: %s\n", gfarm_url2path(url), e2); /* ignore e2 */ } } #else /* for Gfarm version 2 or lator */ fh = FH_GET2(from_url, from_ino); if (fh != NULL) { FH_REMOVE2(from_url, from_ino); } e = gfs_rename(from_url, to_url); if (e == NULL) { e = FH_ADD1(to_url, fh); } else { e = FH_ADD2(from_url, from_ino, fh); } #endif return (e); } static int gfarmfs_rename_share_gf(const char *from, const char *to) { char *e; char *from_url; char *to_url; struct gfs_stat gs; long save_ino; mode_t save_mode; gfarmfs_fastcreate_check(); e = gfarmfs_init(); if (e != NULL) goto end; e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix(to, &to_url); if (e != NULL) goto free_from_url; e = gfs_stat(from_url, &gs); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(from_url); free(to_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix_symlink_suffix(to, &to_url); if (e != NULL) goto free_from_url; if (gfarmfs_debug >= 2) { printf("RENAME: for symlink: %s\n", from); } e = gfs_stat(from_url, &gs); } #endif if (e != NULL) goto free_to_url; save_ino = gs.st_ino; save_mode = gs.st_mode; gfs_stat_free(&gs); e = gfarmfs_rename_share_gf_check_open(from_url, to_url, save_ino, save_mode); free_to_url: free(to_url); free_from_url: free(from_url); end: return gfarmfs_final("RENAME", e, 0, from); } static int gfarmfs_getattr_share_gf(const char *path, struct stat *stbuf) { char *e; struct gfarmfs_fh *fh; struct gfs_stat gs1, gs2; int symlinkmode = 0; char *url; if ((e = gfarmfs_init()) != NULL) goto end; #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, stbuf)) goto end; #endif e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs1); #ifdef SYMLINK_MODE if (enable_symlink == 1 && e == GFARM_ERR_NO_SUCH_OBJECT) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs1); symlinkmode = 1; } #endif if (e != NULL) goto free_url; e = convert_gfs_stat_to_stat(url, &gs1, stbuf, symlinkmode); gfs_stat_free(&gs1); if (e != NULL) goto free_url; fh = FH_GET2(url, gs1.st_ino); /* On Gfarm version 1.3 (or earlier), gfs_stat cannot get the exact st_size while a file is opened. But gfs_fstat can do it. */ if (fh != NULL) { /* somebody opens this file. */ #if REVISE_CHMOD == 1 if (fh->mode_changed) stbuf->st_mode = fh->save_mode; #endif e = gfs_fstat(fh->gf, &gs2); if (e == NULL) { stbuf->st_size = gs2.st_size; gfs_stat_free(&gs2); } /* else: e = NULL (need?) */ } else if (enable_exact_filesize == 1 && S_ISREG(stbuf->st_mode)) { char *e2; file_offset_t size; e2 = gfarmfs_exact_filesize(url, &size, stbuf->st_mode); if (e2 == NULL) stbuf->st_size = size; } free_url: free(url); end: return gfarmfs_final("GETATTR", e, 0, path); } static inline GFS_File gfarmfs_cast_fh_share_gf(struct fuse_file_info *fi) { struct gfarmfs_fh *fh; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; if (fh != NULL) return (fh->gf); else return (NULL); } static int gfarmfs_release_share_gf(const char *path, struct fuse_file_info *fi) { char *e; struct gfarmfs_fh *fh; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init()) != NULL) goto end; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; fh->nopen--; if (fh->nopen <= 0) { char *url; char *e2; if (fh->gf) e = gfs_pio_close(fh->gf); else e = NULL; /* GFARM_ERR_INPUT_OUTPUT ? */ e2 = add_gfarm_prefix(path, &url); if (e2 != NULL) { if (e == NULL) e = e2; goto end; } else { #if REVISE_CHMOD == 1 if (fh->mode_changed) e = gfs_chmod(url, fh->save_mode); #endif #if REVISE_UTIME == 1 if (fh->utime_changed) e = gfs_utimes(url, fh->save_utime); #endif } FH_REMOVE2(url, fh->ino); free(url); FH_FREE(fh); } else { /* nopen > 0 */ if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite--; if (fh->nwrite <= 0 && (fh->flags & GFARM_FILE_ACCMODE) != GFARM_FILE_RDONLY) { /* try to change flags into O_RDONLY */ char *url; GFS_File gf; e = add_gfarm_prefix(path, &url); if (e != NULL) { e = NULL; /* ignore */ goto end; } e = gfs_pio_open(url, GFARM_FILE_RDONLY, &gf); free(url); if (e != NULL) e = NULL; /* use current fh->gf */ else { if (fh->gf) gfs_pio_close(fh->gf); fh->gf = gf; fh->flags = GFARM_FILE_RDONLY; } } } end: return gfarmfs_final("RELEASE", e, 0, path); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_fgetattr_share_gf(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { char *e; struct gfs_stat gs; struct gfarmfs_fh *fh; if ((e = gfarmfs_init()) != NULL) goto end; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_fstat(fh->gf, &gs); if (e == NULL) { e = convert_gfs_stat_to_stat(NULL, &gs, stbuf, 0); gfs_stat_free(&gs); #if REVISE_CHMOD == 1 if (fh->mode_changed) stbuf->st_mode = fh->save_mode; #endif } end: return gfarmfs_final("FGETATTR", e, 0, path); } static int gfarmfs_ftruncate_share_gf(const char *path, off_t size, struct fuse_file_info *fi) { char *e; struct gfarmfs_fh *fh; if ((e = gfarmfs_init()) != NULL) goto end; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_truncate(fh->gf, size); #if REVISE_UTIME == 1 if (e == NULL) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final("FTRUNCATE", e, 0, path); } #endif /* FUSE_USE_VERSION >= 25 */ static int gfarmfs_read_share_gf(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { char *e; file_offset_t off; int n = 0; struct gfarmfs_fh *fh; if ((e = gfarmfs_init()) != NULL) goto end; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_seek(fh->gf, offset, 0, &off); if (e != NULL) goto end; e = gfs_pio_read(fh->gf, buf, size, &n); #if REVISE_UTIME == 1 if (n > 0) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final("READ", e, n, path); } static int gfarmfs_write_share_gf(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { char *e; file_offset_t off; int n = 0; struct gfarmfs_fh *fh; if ((e = gfarmfs_init()) != NULL) goto end; fh = (struct gfarmfs_fh *)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_seek(fh->gf, offset, 0, &off); if (e != NULL) goto end; e = gfs_pio_write(fh->gf, buf, size, &n); #if REVISE_UTIME == 1 if (n > 0) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final("WRITE", e, n, path); } static int gfarmfs_fsync_share_gf(const char *path, int isdatasync, struct fuse_file_info *fi) { char *e; GFS_File gf; if ((e = gfarmfs_init()) != NULL) goto end; gf = gfarmfs_cast_fh_share_gf(fi); if (gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else { if (isdatasync) e = gfs_pio_datasync(gf); else e = gfs_pio_sync(gf); } end: return gfarmfs_final("FSYNC", e, 0, path); } static struct fuse_operations gfarmfs_oper_share_gf = { .getattr = gfarmfs_getattr_share_gf, .readlink = gfarmfs_readlink, .getdir = gfarmfs_getdir, .mknod = gfarmfs_mknod, .mkdir = gfarmfs_mkdir, .symlink = gfarmfs_symlink, .unlink = gfarmfs_unlink, .rmdir = gfarmfs_rmdir, .rename = gfarmfs_rename_share_gf, .link = gfarmfs_link, .chmod = gfarmfs_chmod_share_gf, .chown = gfarmfs_chown, .truncate = gfarmfs_truncate, .utime = gfarmfs_utime_share_gf, .open = gfarmfs_open_share_gf, .read = gfarmfs_read_share_gf, .write = gfarmfs_write_share_gf, .release = gfarmfs_release_share_gf, .fsync = gfarmfs_fsync_share_gf, #ifdef USE_GFS_STATFSNODE .statfs = gfarmfs_statfs, #endif #if FUSE_USE_VERSION >= 25 .create = gfarmfs_create_share_gf, .fgetattr = gfarmfs_fgetattr_share_gf, .ftruncate = gfarmfs_ftruncate_share_gf, .access = gfarmfs_access, #endif #if 1 .flush = gfarmfs_flush, #endif }; /* ################################################################### */ static char *program_name = "gfarmfs"; static struct fuse_operations *gfarmfs_oper_p = &gfarmfs_oper_share_gf; static void gfarmfs_version() { printf("GfarmFS-FUSE version %s (%s)\n", GFARMFS_VER, GFARMFS_VER_DATE); printf("Build: %s %s\n", __DATE__, __TIME__); #if FUSE_USE_VERSION >= 25 printf("FUSE version 2.5 compatible mode\n"); #else printf("FUSE version 2.2 compatible mode\n"); #endif } static void gfarmfs_usage() { const char *fusehelp[] = { program_name, "-ho", NULL }; fprintf(stderr, "Usage: %s [GfarmFS options] <mountpoint> [FUSE options]\n" "\n" "GfarmFS options:\n" " -m <dir on Gfarm> set mount point on Gfarm.\n" " (ex. -m /username cut gfarm:/username)\n" #ifdef SYMLINK_MODE " -s, --symlink enable symlink(2) to work (emulation)\n" #endif " -l, --linkiscopy enable link(2) to behave copying a file (emulation)\n" " -u, --unlinkall enable unlink(2) to remove all architecture files\n" " -b, --buffered enable buffered I/O (unset GFARM_FILE_UNBUFFERED)\n" " -F, --exactfilesize during open(2), exact st_size for other clients\n" " -n, --dirnlink count nlink of a directory precisely\n" #ifdef USE_GFS_STATFSNODE " -S, --disable-statfs disable statfs(2)\n" #endif " -a <architecture> for a client not registered by gfhost\n" " --trace <filename> record FUSE operations called by processes\n" " --print-enoent do not ignore to print ENOENT to stderr\n" " (in -f or -d of FUSE option) (default: ignore)\n" " -v, --version show version and exit\n" "\n", program_name); fuse_main(2, (char **) fusehelp, gfarmfs_oper_p); } static void check_fuse_options(int *argcp, char ***argvp, int *newargcp, char ***newargvp) { int argc = *argcp; char **argv = *argvp; char **newargv; int i; int ok_s = 0; /* check -s */ char *opt_s_str = "-s"; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-s") == 0) { ok_s = 1; } else if (strcmp(argv[i], "-f") == 0) { gfarmfs_debug = 1; } else if (strcmp(argv[i], "-d") == 0) { gfarmfs_debug = 2; } else if (strcmp(argv[i], "-h") == 0) { gfarmfs_usage(); exit(0); } } if (ok_s == 0) { /* add -s option */ newargv = malloc((argc + 1) * sizeof(char *)); if (newargv == NULL) { errno = ENOMEM; perror(""); exit(1); } for (i = 0; i < argc; i++) { newargv[i] = argv[i]; } argc++; newargv[argc - 1] = opt_s_str; *newargcp = argc; *newargvp = newargv; } else { *newargcp = argc; *newargvp = argv; } } static int next_arg_set(char **valp, int *argcp, char ***argvp, int errorexit) { int argc = *argcp; char **argv = *argvp; --argc; ++argv; if (argc <= 0 || (argc > 0 && argv[0][0] == '-' && argv[0][1] != '\0')) { if (errorexit) { gfarmfs_usage(); exit(1); } else { return (0); } } *valp = *argv; *argcp = argc; *argvp = argv; return (1); } static void parse_long_option(int *argcp, char ***argvp) { char **argv = *argvp; if (strcmp(&argv[0][1], "-symlink") == 0) enable_symlink = 1; else if (strcmp(&argv[0][1], "-linkiscopy") == 0) enable_linkiscopy = 1; else if (strcmp(&argv[0][1], "-architecture") == 0) next_arg_set(&arch_name, argcp, argvp, 1); else if (strcmp(&argv[0][1], "-unlinkall") == 0) enable_unlinkall = 1; else if (strcmp(&argv[0][1], "-unbuffered") == 0) enable_gfarm_iobuf = 0; else if (strcmp(&argv[0][1], "-buffered") == 0) enable_gfarm_iobuf = 1; else if (strcmp(&argv[0][1], "-dirnlink") == 0) enable_count_dir_nlink = 1; else if (strcmp(&argv[0][1], "--exactfilesize") == 0) enable_exact_filesize = 1; #ifdef USE_GFS_STATFSNODE else if (strcmp(&argv[0][1], "-disable-statfs") == 0) enable_statfs = 0; #endif else if (strcmp(&argv[0][1], "-oldio") == 0) use_old_functions = 1; else if (strcmp(&argv[0][1], "-print-enoent") == 0) enable_print_enoent = 1; else if (strcmp(&argv[0][1], "-trace") == 0) { next_arg_set(&trace_out, argcp, argvp, 0); if (trace_out == NULL || (strcmp(trace_out, "-") == 0)) enable_trace = stdout; else enable_trace = fopen(trace_out, "w"); if (enable_trace == NULL) { perror(trace_out); exit(1); } } else if (strcmp(&argv[0][1], "-version") == 0) { gfarmfs_version(); exit(0); } else { gfarmfs_usage(); exit(1); } } static int parse_short_option(int *argcp, char ***argvp) { char **argv = *argvp; char *a = &argv[0][1]; while (*a) { switch (*a) { case 's': enable_symlink = 1; break; case 'l': enable_linkiscopy = 1; break; case 'a': return (next_arg_set(&arch_name, argcp, argvp, 1)); case 'u': enable_unlinkall = 1; break; case 'b': enable_gfarm_iobuf = 1; break; case 'F': enable_exact_filesize = 1; break; #ifdef USE_GFS_STATFSNODE case 'S': enable_statfs = 0; /* disable */ break; #endif case 'm': return (next_arg_set( &gfarm_mount_point, argcp, argvp, 1)); case 'n': enable_count_dir_nlink = 1; break; case 'v': gfarmfs_version(); exit(0); default: gfarmfs_usage(); exit(1); } ++a; } return (0); } static void check_gfarmfs_options(int *argcp, char ***argvp) { int argc = *argcp; char **argv = *argvp; char *argv0 = *argv; --argc; ++argv; while (argc > 0 && argv[0][0] == '-') { if (argv[0][1] == '-') parse_long_option(&argc, &argv); else parse_short_option(&argc, &argv); --argc; ++argv; } ++argc; --argv; *argcp = argc; *argv = argv0; *argvp = argv; } static void setup_options() { char *e, *url; struct gfs_stat st; #ifndef ENABLE_FASTCREATE /* not defined */ if (enable_fastcreate > 0) enable_fastcreate = -1; /* ignore on FUSE 2.5 */ #endif /* setup old I/O functions */ if (use_old_functions == 1) { gfarmfs_oper_p = &gfarmfs_oper_base; } /* validate gfarm_mount_point */ e = add_gfarm_prefix("/", &url); if (e == NULL) { e = gfs_stat(url, &st); if (e == NULL) gfs_stat_free(&st); else { fprintf(stderr, "%s: %s\n", gfarm_url2path(url), e); exit(1); } free(url); } else { fprintf(stderr, "add_gfarm_prefix: %s\n", e); exit(1); } #ifdef USE_GFS_STATFSNODE /* count hosts for statfs */ if (enable_statfs == 1) { int nhosts; struct gfarm_host_info *hostinfos; e = gfarm_host_info_get_all(&nhosts, &hostinfos); if (e != NULL) { fprintf(stderr, "gfarm_host_info_get_all: %s\n", e); exit(1); } gfarm_host_info_free_all(nhosts, hostinfos); statfs_nhosts = nhosts; } else { gfarmfs_oper_p->statfs = NULL; /* disable */ } #endif } static void print_options() { if (gfarmfs_debug == 0) return; gfarmfs_version(); if (enable_symlink == 1) { printf("enable symlink\n"); } if (enable_linkiscopy == 1) { printf("enable linkiscopy\n"); } if (arch_name != NULL) { printf("set architecture (%s)\n", arch_name); } if (enable_unlinkall == 1) { printf("enable unlinkall\n"); } #ifdef USE_GFS_STATFSNODE if (enable_statfs == 1) { printf("enable statfs (%d hosts)\n", statfs_nhosts); } #endif if (enable_trace != NULL) { printf("enable trace (output file: %s)\n", trace_out); } if (enable_count_dir_nlink == 1) { printf("enable count_dir_nlink\n"); } if (enable_gfarm_iobuf == 1) { printf("enable buffered I/O (unset GFARM_FILE_UNBUFFERED)\n"); } else { printf("disable buffered I/O (set GFARM_FILE_UNBUFFERED)\n"); } if (enable_exact_filesize == 1) { printf("enable exact filesize\n"); } if (use_old_functions == 1) { printf("use old I/O functions\n"); } if (*gfarm_mount_point != '\0') { printf("mountpoint: gfarm:%s\n", gfarm_mount_point); } } int main(int argc, char *argv[]) { int ret; char *e; char **newargv = NULL; int newargc = 0; if (argc > 0) { program_name = basename(argv[0]); } check_gfarmfs_options(&argc, &argv); check_fuse_options(&argc, &argv, &newargc, &newargv); e = gfarm_initialize(NULL, NULL); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(-1); } setup_options(); print_options(); ret = fuse_main(newargc, newargv, gfarmfs_oper_p); free(newargv); gfarmfs_fastcreate_check(); if (enable_trace != NULL) { fclose(enable_trace); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(-1); } return (ret); } <file_sep>/gfarm/tags/gfarm_1_0_3_1/gftool/gfsched/gfsched.c /* * $Id$ */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <libgen.h> #include <sys/types.h> #include <gfarm/gfarm.h> /* * Create a hostfile. * * gfsched <gfarm_url> [<output_hostfile>] * gfsched -f <gfarm_file> [<output_hostfile>] */ char *program_name = "gfsched"; void usage(void) { fprintf(stderr, "usage:\t%s [options] gfarm_url [output_hostfile]\n", program_name); fprintf(stderr, "\t%s -N <number> [-p <gfarm_url>] [<host>...]\n", program_name); fprintf(stderr, "options:\n"); fprintf(stderr, "\t-I <fragment>\tschedules a node" " using the specified fragment.\n"); fprintf(stderr, "\t-p <gfarm_url>\tprogram URL" " to process the file.\n"); fflush(stderr); } int main(int argc, char * argv[]) { char *gfarm_url = NULL; char *section = NULL; char *program = NULL; char *e = NULL; FILE *outp = stdout; int errflg = 0; extern int optind; int nhosts = -1; char **hosts; char *gfarm_file; char *host; int c, i; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((c = getopt(argc, argv, "I:N:Up:?")) != EOF) { switch (c) { case 'I': section = optarg; break; case 'N': nhosts = atoi(optarg); break; case 'U': gfarm_schedule_search_mode_set(GFARM_SCHEDULE_SEARCH_BY_LOADAVG); break; case 'p': program = optarg; if (!gfarm_is_url(program)) { fprintf(stderr, "%s: only gfarm-URL can be specified" " as a parameter of -p option\n", program_name); exit(2); } break; case '?': default: ++errflg; } } if (errflg) { usage(); exit(2); } if (section != NULL && nhosts != -1) { fprintf(stderr, "%s: -I and -N option cannot be specified at once.\n", program_name); exit(2); } if (nhosts == -1) { if (optind < argc) { gfarm_url = argv[optind]; } else { usage(); exit(2); } ++optind; if (optind < argc) { outp = fopen(argv[optind], "w"); if (outp == NULL) { perror(argv[optind]); exit(1); } } } if (nhosts != -1) { hosts = malloc(sizeof(*hosts) * nhosts); if (hosts == NULL) { fprintf(stderr, "%s: %s\n", program_name, GFARM_ERR_NO_MEMORY); exit(2); } if (optind < argc) { for (i = optind; i < argc; i++) { e = gfarm_host_get_canonical_name(argv[i], &argv[i]); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, argv[i], e); exit(2); } } if (program != NULL) { e = "currently, hosts cannot be specified, " "if both -N and -p option are used."; } else { e = gfarm_schedule_search_idle_hosts( argc - optind, &argv[optind], nhosts, hosts); } } else { if (program != NULL) { e = gfarm_schedule_search_idle_by_program(program, nhosts, hosts); } else { e = gfarm_schedule_search_idle_by_all(nhosts, hosts); } } if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(2); } for (i = 0; i < nhosts; ++i) printf("%s\n", hosts[i]); } else if (section == NULL) { /* file-affinity scheduling */ if (program != NULL) { e = gfarm_url_hosts_schedule_by_program(gfarm_url, program, NULL, &nhosts, &hosts); } else { e = gfarm_url_hosts_schedule(gfarm_url, NULL, &nhosts, &hosts); } if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < nhosts; ++i) fprintf(outp, "%s\n", hosts[i]); } else { /* schedule a node using the specific file fragment. */ e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (program != NULL) { e = gfarm_file_section_host_schedule_by_program(gfarm_file, section, program, &host); } else { e = gfarm_file_section_host_schedule(gfarm_file, section, &host); } if (e != NULL) { fprintf(stderr, "%s: %s:%s: %s\n", program_name, gfarm_url, section, e); exit(1); } fprintf(outp, "%s\n", host); free(host); free(gfarm_file); } fclose(outp); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(0); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_0/gfarm2fs.h struct gfarm2fs_param { const char *mount_point; int foreground; int debug; double cache_timeout; int use_syslog; char *facility; char *loglevel; int ncopy; int copy_limit; }; <file_sep>/gfarm/tags/gfarm_1_1_1_rc4/lib/libgfarm/gfarm/agent_client.h /* * $Id$ */ struct agent_connection; char *agent_client_connect(struct sockaddr_un *, struct agent_connection **); char *agent_client_disconnect(struct agent_connection *); /* agent_client RPC */ char *agent_client_rpc(struct agent_connection *, int, int, char *, ...); char *agent_client_path_info_get( struct agent_connection *, const char *, struct gfarm_path_info *); char *agent_client_path_info_set( struct agent_connection *, char *, struct gfarm_path_info *); char *agent_client_path_info_replace( struct agent_connection *, char *, struct gfarm_path_info *); char *agent_client_path_info_remove(struct agent_connection *, const char *); char *agent_client_realpath_canonical( struct agent_connection *, const char *, char **); char *agent_client_get_ino( struct agent_connection *, const char *, gfarm_int32_t *); char *agent_client_opendir(struct agent_connection *, const char *, GFS_Dir *); char *agent_client_readdir( struct agent_connection *, GFS_Dir, struct gfs_dirent **); char *agent_client_closedir(struct agent_connection *, GFS_Dir); char *agent_client_dirname(struct agent_connection *, GFS_Dir); char *agent_client_uncachedir(struct agent_connection *); <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/lib/libgfarm/gfarm/xxx_proto.c #include <stdio.h> #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> /* ntoh[ls]()/hton[ls]() on glibc */ #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "iobuffer.h" #include "xxx_proto.h" #if FILE_OFFSET_T_IS_FLOAT #include <math.h> #define POWER2_32 4294967296.0 /* 2^32 */ #endif #define XXX_BUFSIZE 16384 struct xxx_connection { struct gfarm_iobuffer *recvbuffer; struct gfarm_iobuffer *sendbuffer; struct xxx_iobuffer_ops *iob_ops; void *cookie; int fd; }; /* * switch to new iobuffer operation, * and (possibly) switch to new cookie/fd */ void xxx_connection_set(struct xxx_connection *conn, struct xxx_iobuffer_ops *ops, void *cookie, int fd) { conn->iob_ops = ops; conn->cookie = cookie; conn->fd = fd; gfarm_iobuffer_set_read(conn->recvbuffer, ops->blocking_read, cookie, fd); gfarm_iobuffer_set_write(conn->sendbuffer, ops->blocking_write, cookie, fd); } char * xxx_connection_new(struct xxx_iobuffer_ops *ops, void *cookie, int fd, struct xxx_connection **connp) { struct xxx_connection *conn; conn = malloc(sizeof(struct xxx_connection)); if (conn == NULL) return (GFARM_ERR_NO_MEMORY); conn->recvbuffer = gfarm_iobuffer_alloc(XXX_BUFSIZE); if (conn->recvbuffer == NULL) { free(conn); return (GFARM_ERR_NO_MEMORY); } conn->sendbuffer = gfarm_iobuffer_alloc(XXX_BUFSIZE); if (conn->sendbuffer == NULL) { gfarm_iobuffer_free(conn->recvbuffer); free(conn); return (GFARM_ERR_NO_MEMORY); } xxx_connection_set(conn, ops, cookie, fd); *connp = conn; return (NULL); } char * xxx_connection_free(struct xxx_connection *conn) { char *e, *e_save; e_save = xxx_proto_flush(conn); gfarm_iobuffer_free(conn->sendbuffer); gfarm_iobuffer_free(conn->recvbuffer); e = (*conn->iob_ops->close)(conn->cookie, conn->fd); if (e_save == NULL) e_save = e; free(conn); return (e); } void * xxx_connection_cookie(struct xxx_connection *conn) { return (conn->cookie); } int xxx_connection_fd(struct xxx_connection *conn) { return (conn->fd); } char * xxx_connection_export_credential(struct xxx_connection *conn) { return ((*conn->iob_ops->export_credential)(conn->cookie)); } char * xxx_connection_delete_credential(struct xxx_connection *conn) { return ((*conn->iob_ops->delete_credential)(conn->cookie)); } char * xxx_connection_env_for_credential(struct xxx_connection *conn) { return ((*conn->iob_ops->env_for_credential)(conn->cookie)); } void gfarm_iobuffer_set_nonblocking_read_xxx(struct gfarm_iobuffer *b, struct xxx_connection *conn) { gfarm_iobuffer_set_read(b, conn->iob_ops->nonblocking_read, conn->cookie, conn->fd); } void gfarm_iobuffer_set_nonblocking_write_xxx(struct gfarm_iobuffer *b, struct xxx_connection *conn) { gfarm_iobuffer_set_write(b, conn->iob_ops->nonblocking_write, conn->cookie, conn->fd); } char * xxx_proto_flush(struct xxx_connection *conn) { gfarm_iobuffer_flush_write(conn->sendbuffer); return (gfarm_iobuffer_get_error(conn->sendbuffer)); } char * xxx_proto_purge(struct xxx_connection *conn, int just, int len) { if (gfarm_iobuffer_purge_read_x(conn->recvbuffer, len, just) != len) return (GFARM_ERR_PROTOCOL); /* unexpected eof */ return (NULL); } char * xxx_proto_vsend(struct xxx_connection *conn, char **formatp, va_list *app) { char *format = *formatp; va_list ap; gfarm_uint8_t c; gfarm_int16_t h; gfarm_int32_t i, n; file_offset_t o; gfarm_uint32_t ov[2]; #if FILE_OFFSET_T_IS_FLOAT int minus; #endif char *s; va_copy(ap, *app); for (; *format; format++) { switch (*format) { case 'c': c = va_arg(ap, int); gfarm_iobuffer_put_write(conn->sendbuffer, &c, sizeof(c)); break; case 'h': h = va_arg(ap, int); h = htons(h); gfarm_iobuffer_put_write(conn->sendbuffer, &h, sizeof(h)); break; case 'i': i = va_arg(ap, gfarm_int32_t); i = htonl(i); gfarm_iobuffer_put_write(conn->sendbuffer, &i, sizeof(i)); break; case 'o': /* * note that because actual type of file_offset_t * may be diffenent (int64_t or double), we must * not pass this as is via network. */ o = va_arg(ap, file_offset_t); #if FILE_OFFSET_T_IS_FLOAT minus = o < 0; if (minus) o = -o; ov[0] = o / POWER2_32; ov[1] = o - ov[0] * POWER2_32; if (minus) { ov[0] = ~ov[0]; ov[1] = ~ov[1]; if (++ov[1] == 0) ++ov[0]; } #else ov[0] = o >> 32; ov[1] = o; #endif ov[0] = htonl(ov[0]); ov[1] = htonl(ov[1]); gfarm_iobuffer_put_write(conn->sendbuffer, ov, sizeof(ov)); break; case 's': s = va_arg(ap, char *); n = strlen(s); i = htonl(n); gfarm_iobuffer_put_write(conn->sendbuffer, &i, sizeof(i)); gfarm_iobuffer_put_write(conn->sendbuffer, s, n); break; case 'b': /* * note that because actual type of size_t may be * diffenent ([u]int32_t or [u]int64_t), we must not * pass this as is via network. */ n = va_arg(ap, size_t); i = htonl(n); s = va_arg(ap, char *); gfarm_iobuffer_put_write(conn->sendbuffer, &i, sizeof(i)); gfarm_iobuffer_put_write(conn->sendbuffer, s, n); break; default: goto finish; } } finish: *formatp = format; va_copy(*app, ap); return (gfarm_iobuffer_get_error(conn->sendbuffer)); } char * xxx_proto_vrecv(struct xxx_connection *conn, int just, int *eofp, char **formatp, va_list *app) { char *format = *formatp; va_list ap; gfarm_int8_t *cp; gfarm_int16_t *hp; gfarm_int32_t *ip, i; file_offset_t *op; gfarm_uint32_t ov[2]; #if FILE_OFFSET_T_IS_FLOAT int minus; #endif char **sp, *s; size_t *szp, sz; char *e; va_copy(ap, *app); e = xxx_proto_flush(conn); if (e != NULL) return (e); *eofp = 1; for (; *format; format++) { switch (*format) { case 'c': cp = va_arg(ap, gfarm_int8_t *); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, cp, sizeof(*cp), just) != sizeof(*cp)) return (NULL); break; case 'h': hp = va_arg(ap, gfarm_int16_t *); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, hp, sizeof(*hp), just) != sizeof(*hp)) return (NULL); *hp = ntohs(*hp); break; case 'i': ip = va_arg(ap, gfarm_int32_t *); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, ip, sizeof(*ip), just) != sizeof(*ip)) return (NULL); *ip = ntohl(*ip); break; case 'o': /* * note that because actual type of file_offset_t * may be diffenent (int64_t or double), we must * not pass this as is via network. */ op = va_arg(ap, file_offset_t *); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, ov, sizeof(ov), just) != sizeof(ov)) return (NULL); ov[0] = ntohl(ov[0]); ov[1] = ntohl(ov[1]); #if FILE_OFFSET_T_IS_FLOAT minus = ov[0] & 0x80000000; if (minus) { ov[0] = ~ov[0]; ov[1] = ~ov[1]; if (++ov[1] == 0) ++ov[0]; } *op = ov[0] * POWER2_32 + ov[1]; if (minus) *op = -*op; #else *op = ((file_offset_t)ov[0] << 32) | ov[1]; #endif break; case 's': sp = va_arg(ap, char **); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, &i, sizeof(i), just) != sizeof(i)) return (NULL); i = ntohl(i); *sp = malloc(i + 1); if (*sp != NULL) { /* caller should check whether *sp == NULL */ if (gfarm_iobuffer_get_read_x(conn->recvbuffer, *sp, i, just) != i) return (NULL); (*sp)[i] = '\0'; } break; case 'b': /* * note that because actual type of size_t may be * diffenent ([u]int32_t or [u]int64_t), we must not * pass this as is via network. */ sz = va_arg(ap, size_t); szp = va_arg(ap, size_t *); s = va_arg(ap, char *); if (gfarm_iobuffer_get_read_x(conn->recvbuffer, &i, sizeof(i), just) != sizeof(i)) return (NULL); i = ntohl(i); *szp = i; if (i <= sz) { if (gfarm_iobuffer_get_read_x(conn->recvbuffer, s, i, just) != i) return (NULL); } else { if (gfarm_iobuffer_get_read_x(conn->recvbuffer, s, sz, just) != sz) return (NULL); /* abandon (i - sz) bytes */ if (gfarm_iobuffer_purge_read_x( conn->recvbuffer, i - sz, just) != i - sz) return (NULL); } break; default: goto finish; } } finish: *formatp = format; va_copy(*app, ap); *eofp = 0; return (gfarm_iobuffer_get_error(conn->recvbuffer)); } char * xxx_proto_send(struct xxx_connection *conn, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_vsend(conn, &format, &ap); va_end(ap); if (e != NULL) return (e); if (*format != '\0') return ("xxx_proto_send: invalid format character"); return (NULL); } char * xxx_proto_recv(struct xxx_connection *conn, int just, int *eofp, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_vrecv(conn, just, eofp, &format, &ap); va_end(ap); if (e != NULL) return (e); if (*eofp) return (NULL); if (*format != '\0') return ("xxx_proto_recv: invalid format character"); return (NULL); } /* * do RPC request */ char * xxx_proto_vrpc_request(struct xxx_connection *conn, gfarm_int32_t command, char **formatp, va_list *app) { char *e; /* * send request */ e = xxx_proto_send(conn, "i", command); if (e != NULL) return (e); e = xxx_proto_vsend(conn, formatp, app); if (e != NULL) return (e); return (NULL); } /* * get RPC result */ char * xxx_proto_vrpc_result(struct xxx_connection *conn, int just, gfarm_int32_t *errorp, char **formatp, va_list *app) { char *e; int eof; /* * receive response */ e = xxx_proto_recv(conn, just, &eof, "i", errorp); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); /* rpc status missing */ if (*errorp != 0) return (NULL); /* should examine error in this case */ e = xxx_proto_vrecv(conn, just, &eof, formatp, app); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); /* rpc return value missing */ return (NULL); } /* * do RPC with "request-args/result-args" format string. */ char * xxx_proto_vrpc(struct xxx_connection *conn, int just, gfarm_int32_t command, gfarm_int32_t *errorp, char **formatp, va_list *app) { char *e; /* * send request */ e = xxx_proto_vrpc_request(conn, command, formatp, app); if (e != NULL) return (e); if (**formatp != '/') return ("xxx_proto_vrpc: missing result in format string"); (*formatp)++; e = xxx_proto_vrpc_result(conn, just, errorp, formatp, app); if (e != NULL) return (e); if (*errorp != 0) return (NULL); /* should examine error in this case */ if (**formatp != '\0') return ("xxx_proto_vrpc: invalid format character"); return (NULL); } /* * low level interface, this does not wait to receive desired length. */ int xxx_recv_partial(struct xxx_connection *conn, int just, void *data, int length) { return (gfarm_iobuffer_get_read_partial_x( conn->recvbuffer, data, length, just)); } /* * lowest level interface, * this does not wait to receive desired length, and * this does not honor iobuffer. */ char * xxx_read_direct(struct xxx_connection *conn, void *data, int length, int *resultp) { int rv = (*conn->iob_ops->blocking_read)(conn->recvbuffer, conn->cookie, conn->fd, data, length); if (rv == -1) { *resultp = 0; return (gfarm_iobuffer_get_error(conn->recvbuffer)); } *resultp = rv; return (NULL); } char * xxx_write_direct(struct xxx_connection *conn, void *data, int length, int *resultp) { int rv = (*conn->iob_ops->blocking_write)(conn->sendbuffer, conn->cookie, conn->fd, data, length); if (rv == -1) { *resultp = 0; return (gfarm_iobuffer_get_error(conn->sendbuffer)); } *resultp = rv; return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_3_1/gftool/gfrun/gfrun.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "host.h" #include "gfj_client.h" #include "schedule.h" #define ENV_GFRUN_CMD "GFRUN_CMD" #define ENV_GFRUN_FLAGS "GFRUN_FLAGS" enum command_type {UNKNOWN_COMMAND = -1, USUAL_COMMAND = 0, GFARM_COMMAND = 1}; char *program_name = "gfrun"; void setsig(int signum, void (*handler)(int)) { struct sigaction act; act.sa_handler = handler; sigemptyset(&act.sa_mask); /* do not set SA_RESTART to make interrupt at waitpid(2) */ act.sa_flags = 0; if (sigaction(signum, &act, NULL) == -1) { fprintf(stderr, "%s: sigaction(%d): %s\n", program_name, signum, strerror(errno)); exit(1); } } void ignore_handler(int signum) { /* do nothing */ } void sig_ignore(int signum) { /* we don't use SIG_IGN to make it possible that child catch singals */ setsig(signum, ignore_handler); } void usage() { fprintf(stderr, #ifdef HAVE_GSI "Usage: %s [-gnuprvS] [-l <login>]\n" #else "Usage: %s [-gnuprS] [-l <login>]\n" #endif "\t[-G <Gfarm file> [ -I <section> ]|-H <hostfile>|" "-N <number of hosts>]\n" "\t[-o <Gfarm file>] [-e <Gfarm file>]" " command ...\n", program_name); exit(1); } struct gfrun_options { char *user_name; char *stdout_file; char *stderr_file; char *sched_file; /* -G <sched_file> */ char *hosts_file; /* -H <hosts_file> */ int nprocs; /* -N <nprocs> */ char *section; /* -I <index> */ enum command_type cmd_type; int authentication_verbose_mode; int profile; int replicate; int use_gfexec; }; static void default_gfrun_options(struct gfrun_options *options) { options->user_name = NULL; options->stdout_file = NULL; options->stderr_file = NULL; options->sched_file = NULL; options->hosts_file = NULL; options->nprocs = 0; options->section = NULL; options->cmd_type = UNKNOWN_COMMAND; options->authentication_verbose_mode = 0; options->profile = 0; options->replicate = 0; options->use_gfexec = 1; } char * gfrun(char *rsh_command, gfarm_stringlist *rsh_options, struct gfrun_options *options, int nhosts, char **hosts, char *cmd, char **argv) { int i, save_errno, pid, status, command_alist_index; gfarm_stringlist arg_list; char total_nodes[GFARM_INT32STRLEN], node_index[GFARM_INT32STRLEN]; char **delivered_paths = NULL, *e; enum command_type cmd_type_guess = USUAL_COMMAND, cmd_type; char *stdout_file = options->stdout_file; char *stderr_file = options->stderr_file; int profile_mode = options->profile; int replication_mode = options->replicate; static char gfexec_command[] = "gfexec"; #ifdef __GNUC__ /* shut up stupid warning by gcc */ command_alist_index = 0; #endif /* * deliver gfarm:program. */ if (gfarm_is_url(cmd)) { if (!options->use_gfexec) { e = gfarm_url_program_deliver(cmd, nhosts, hosts, &delivered_paths); if (e != NULL) { fprintf(stderr, "%s: deliver %s: %s\n", program_name, cmd, e); return (e); } } cmd_type_guess = GFARM_COMMAND; } if (options->cmd_type == UNKNOWN_COMMAND) cmd_type = cmd_type_guess; else cmd_type = options->cmd_type; sprintf(total_nodes, "%d", nhosts); gfarm_stringlist_init(&arg_list); gfarm_stringlist_add(&arg_list, rsh_command); gfarm_stringlist_add(&arg_list, "(dummy)"); if (rsh_options != NULL) gfarm_stringlist_add_list(&arg_list, rsh_options); if (options->use_gfexec) gfarm_stringlist_add(&arg_list, gfexec_command); if (!options->use_gfexec) { command_alist_index = gfarm_stringlist_length(&arg_list); gfarm_stringlist_add(&arg_list, "(dummy)"); } if (options->use_gfexec || cmd_type == GFARM_COMMAND) { char *cwd; gfarm_stringlist_add(&arg_list, "--gfarm_nfrags"); gfarm_stringlist_add(&arg_list, total_nodes); gfarm_stringlist_add(&arg_list, "--gfarm_index"); gfarm_stringlist_add(&arg_list, node_index); if (stdout_file != NULL) { gfarm_stringlist_add(&arg_list, "--gfarm_stdout"); gfarm_stringlist_add(&arg_list, stdout_file); } if (stderr_file != NULL) { gfarm_stringlist_add(&arg_list, "--gfarm_stderr"); gfarm_stringlist_add(&arg_list, stderr_file); } if (profile_mode) gfarm_stringlist_add(&arg_list, "--gfarm_profile"); if (replication_mode) gfarm_stringlist_add(&arg_list, "--gfarm_replicate"); cwd = getenv("GFS_PWD"); if (cwd != NULL) { gfarm_stringlist_add(&arg_list, "--gfarm_cwd"); gfarm_stringlist_add(&arg_list, cwd); } } if (options->use_gfexec) { command_alist_index = gfarm_stringlist_length(&arg_list); gfarm_stringlist_add(&arg_list, "(dummy)"); } gfarm_stringlist_cat(&arg_list, argv); gfarm_stringlist_add(&arg_list, NULL); for (i = 0; i < nhosts; i++) { char *if_hostname; struct sockaddr peer_addr; if (options->section != NULL && nhosts == 1) { /* Serial execution case with section name */ int nfrags; sprintf(node_index, "%d", atoi(options->section)); if (options->sched_file != NULL) { e = gfarm_url_fragment_number( options->sched_file, &nfrags); if (e != NULL) return (e); sprintf(total_nodes, "%d", nfrags); } } else sprintf(node_index, "%d", i); /* reflect "address_use" directive in the `if_hostname' */ e = gfarm_host_address_get(hosts[i], gfarm_spool_server_port, &peer_addr, &if_hostname); GFARM_STRINGLIST_ELEM(arg_list, 1) = e == NULL ? if_hostname : hosts[i]; if (delivered_paths == NULL) { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = cmd; } else { GFARM_STRINGLIST_ELEM(arg_list, command_alist_index) = delivered_paths[i]; } switch (pid = fork()) { case 0: execvp(rsh_command, GFARM_STRINGLIST_STRARRAY(arg_list)); perror(rsh_command); exit(1); case -1: perror("fork"); exit(1); } if (e == NULL) free(if_hostname); } sig_ignore(SIGHUP); sig_ignore(SIGINT); sig_ignore(SIGQUIT); sig_ignore(SIGTERM); while (waitpid(-1, &status, 0) != -1 || errno == EINTR) ; save_errno = errno; if (delivered_paths != NULL) gfarm_strings_free_deeply(nhosts, delivered_paths); gfarm_stringlist_free(&arg_list); if (save_errno != ECHILD) { e = gfarm_errno_to_error(save_errno); fprintf(stderr, "%s: waiting child process: %s\n", program_name, e); return (e); } return (NULL); } /* * register files in gfarm spool */ void register_stdout_stderr(char *stdout_file, char *stderr_file, char *rsh_command, gfarm_stringlist *rsh_options, int nhosts, char **hosts) { char gfsplck_cmd[] = "gfarm:/bin/gfsplck"; struct gfs_stat sb; char *e, *gfarm_files[3]; int i = 0; /* purge the directory-tree cache. */ gfs_uncachedir(); if (stdout_file != NULL) { e = gfs_stat(stdout_file, &sb); if (e != NULL) gfarm_files[i++] = stdout_file; else gfs_stat_free(&sb); } if (stderr_file != NULL) { e = gfs_stat(stderr_file, &sb); if (e != NULL) gfarm_files[i++] = stderr_file; else gfs_stat_free(&sb); } gfarm_files[i] = NULL; if (i > 0) { struct gfrun_options options; e = gfs_stat(gfsplck_cmd, &sb); if (e != NULL) { fprintf(stderr, "%s: cannot register a stdout/stderr file, " "backend program %s: %s\n", program_name, gfsplck_cmd, e); return; } gfs_stat_free(&sb); default_gfrun_options(&options); options.cmd_type = GFARM_COMMAND; e = gfrun(rsh_command, rsh_options, &options, nhosts, hosts, gfsplck_cmd, gfarm_files); if (e != NULL) fprintf(stderr, "%s: cannot register a stdout file: " "%s\n", program_name, e); } } /* Process scheduling */ void schedule(char *command_name, struct gfrun_options *options, gfarm_stringlist *input_list, int *nhostsp, char ***hostsp, char **scheduling_filep) { char *e, *self_name, *scheduling_file, **hosts; int error_line, nhosts; int spooled_command = gfarm_is_url(command_name); int nopts = 0; if (options->sched_file != NULL) nopts++; if (options->hosts_file != NULL) nopts++; if (options->nprocs > 0) nopts++; if (nopts > 1) { fprintf(stderr, "%s: only one of -G/-H/-N option can be used at most.", program_name); usage(); } if (options->hosts_file != NULL) { /* Hostfile scheduling */ if (options->section != NULL) fprintf(stderr, "%s: warning: -I option is ignored\n", program_name); /* * Is it necessary to access a Gfarm hostfile? */ e = gfarm_hostlist_read(options->hosts_file, &nhosts, &hosts, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s: line %d: %s\n", program_name, options->hosts_file, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, options->hosts_file, e); exit(1); } scheduling_file = options->hosts_file; } else if (options->nprocs > 0) { if (options->section != NULL) fprintf(stderr, "%s: warning: -I option is ignored\n", program_name); nhosts = options->nprocs; hosts = malloc(sizeof(*hosts) * nhosts); if (hosts == NULL) { fprintf(stderr, "%s: not enough memory for %d hosts", program_name, nhosts); exit(1); } if (spooled_command) { e = gfarm_schedule_search_idle_by_program( command_name, nhosts, hosts); } else { e = gfarm_schedule_search_idle_by_all(nhosts, hosts); } if (e != NULL) { fprintf(stderr, "%s: scheduling %d nodes: %s\n", program_name, options->nprocs, e); exit(1); } scheduling_file = ""; } else if (options->sched_file != NULL || gfarm_stringlist_length(input_list) != 0) { /* * File-affinity scheduling * * If scheduling file is not explicitly specified, the * first input file used for file-affinity scheduling. */ if (options->sched_file == NULL) options->sched_file = gfarm_stringlist_elem(input_list, 0); scheduling_file = options->sched_file; if (options->section != NULL) { /* schedule a process for specified section */ char *gfarm_file; nhosts = 1; hosts = malloc(sizeof(*hosts)); if (hosts == NULL) { fprintf(stderr, "%s: not enough memory", program_name); exit(1); } e = gfarm_url_make_path(scheduling_file, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s", program_name, e); exit(1); } if (spooled_command) e = gfarm_file_section_host_schedule_by_program( gfarm_file, options->section, command_name, hosts); else e = gfarm_file_section_host_schedule( gfarm_file, options->section, hosts); free(gfarm_file); } else { if (spooled_command) e = gfarm_url_hosts_schedule_by_program( scheduling_file, command_name, NULL, &nhosts, &hosts); else e = gfarm_url_hosts_schedule(scheduling_file, NULL, &nhosts, &hosts); } if (e != NULL) { fprintf(stderr, "%s: scheduling by %s: %s\n", program_name, scheduling_file, e); exit(1); } } else { /* Serial execution */ nhosts = 1; hosts = malloc(sizeof(*hosts)); if (hosts == NULL) { fprintf(stderr, "%s: not enough memory", program_name); exit(1); } e = gfarm_host_get_canonical_self_name(&self_name); if (e == NULL) { hosts[0] = strdup(self_name); if (hosts[0] == NULL) { fprintf(stderr, "%s: not enough memory", program_name); exit(1); } } else { if (spooled_command) { e = gfarm_schedule_search_idle_by_program( command_name, 1, hosts); } else { e= gfarm_schedule_search_idle_by_all(1, hosts); } if (e != NULL) { fprintf(stderr, "%s: scheduling 1 host: %s\n", program_name, e); exit(1); } } scheduling_file = ""; } *nhostsp = nhosts; *hostsp = hosts; *scheduling_filep = scheduling_file; } /* * parse command line */ void decide_rsh_command(char *program_name, char **rsh_commandp, gfarm_stringlist *rsh_options, int *remove_gfarm_url_prefixp) { char *rsh_command, *rsh_flags; int have_redirect_stdin_option = 1, remove_gfarm_url_prefix = 0; rsh_command = getenv(ENV_GFRUN_CMD); if (rsh_command == NULL) rsh_command = "gfrcmd"; /* For backward compatibility */ if (strcmp(program_name, "gfrsh") == 0) { rsh_command = "rsh"; } else if (strcmp(program_name, "gfssh") == 0) { rsh_command = "ssh"; } else if (strcmp(program_name, "gfrshl") == 0) { rsh_command = "rsh"; remove_gfarm_url_prefix = 1; } else if (strcmp(program_name, "gfsshl") == 0) { rsh_command = "ssh"; remove_gfarm_url_prefix = 1; } /* Globus-job-run hack */ if (strcmp(basename(rsh_command), "globus-job-run") == 0) have_redirect_stdin_option = 0; /* $GFRUN_FLAGS: XXX - Currently, You can specify at most one flag */ rsh_flags = getenv(ENV_GFRUN_FLAGS); if (rsh_flags != NULL) gfarm_stringlist_add(rsh_options, rsh_flags); else if (have_redirect_stdin_option) gfarm_stringlist_add(rsh_options, "-n"); *rsh_commandp = rsh_command; *remove_gfarm_url_prefixp = remove_gfarm_url_prefix; } void missing_argument(char option) { fprintf(stderr, "%s: missing argument to -%c\n", program_name, option); usage(); } /* * Parse a gfrun option which does take a parameter. * The option itself will not be added to *rsh_options. * * INPUT: * is_last_arg: Is `arg' last argument of argv[]? * arg: currently looking entry of argv[] * next_arg: next entry of argv[] * char_index: arg[char_index] is the currently looking gfrun option * INPUT/OUTPUT: * *rsh_options: rsh options * OUTPUT: * *parameterp: parameter of the currently looking gfrun option * RETURN: * true, if next argument is spent as the parameter of this option */ int option_param(int is_last_arg, char *arg, char *next_arg, int char_index, gfarm_stringlist *rsh_options, char **parameterp) { char optchar = arg[char_index]; if (char_index > 1) { arg[char_index] = '\0'; gfarm_stringlist_add(rsh_options, arg); } if (arg[char_index + 1] != '\0') { *parameterp = &arg[char_index + 1]; return (0); /* don't skip next arg */ } else if (!is_last_arg) { *parameterp = next_arg; return (1); /* skip next arg */ } else { missing_argument(optchar); /* NOTREACHED */ } return (0); } /* * Parse a rsh option which does take a parameter. * The option will be added to *rsh_options. * * INPUT: * is_last_arg: Is `arg' last argument of argv[]? * arg: currently looking entry of argv[] * next_arg: next entry of argv[] * char_index: arg[char_index] is the currently looking rsh option * INPUT/OUTPUT: * *rsh_options: rsh options * OUTPUT: * *parameterp: parameter of the currently looking rsh option * RETURN: * true, if next argument is spent as the parameter of this option */ int rsh_option_param(int is_last_arg, char *arg, char *next_arg, int char_index, gfarm_stringlist *rsh_options, char **parameterp) { if (arg[char_index + 1] != '\0') { *parameterp = &arg[char_index + 1]; gfarm_stringlist_add(rsh_options, arg); return (0); /* don't skip next arg */ } else if (!is_last_arg) { *parameterp = next_arg; gfarm_stringlist_add(rsh_options, arg); gfarm_stringlist_add(rsh_options, next_arg); return (1); /* skip next arg */ } else { missing_argument(arg[char_index]); /* NOTREACHED */ } return (0); } /* * RETURN: * true, if this is the sole option in the arg, * i.e. this option shouldn't be added to rsh_options */ int remove_option(char *arg, int *char_indexp) { int i = *char_indexp; if (i == 1 && arg[i + 1] == '\0') return (1); /* this is the sole option in the arg */ memmove(&arg[i], &arg[i + 1], strlen(&arg[i])); *char_indexp = i - 1; return (0); } /* * RETURN: * true, if next argument is spent as the parameter of this option. */ int parse_option(int is_last_arg, char *arg, char *next_arg, gfarm_stringlist *rsh_options, struct gfrun_options *options) { int i, skip_next; char *s; for (i = 1; arg[i] != '\0'; i++) { switch (arg[i]) { case 'g': options->cmd_type = GFARM_COMMAND; if (remove_option(arg, &i)) return (0); break; case 'u': options->cmd_type = USUAL_COMMAND; if (remove_option(arg, &i)) return (0); break; case 'v': options->authentication_verbose_mode = 1; if (remove_option(arg, &i)) return (0); break; case 'p': options->profile = 1; if (remove_option(arg, &i)) return (0); break; case 'r': options->replicate = 1; if (remove_option(arg, &i)) return (0); break; case 'S': options->use_gfexec = 0; if (remove_option(arg, &i)) return (0); break; case 'o': return (option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->stdout_file)); case 'e': return (option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->stderr_file)); case 'G': return (option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->sched_file)); case 'H': return (option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->hosts_file)); case 'I': return (option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->section)); case 'N': skip_next = option_param(is_last_arg, arg, next_arg, i, rsh_options, &s); options->nprocs = atoi(s); return (skip_next); case 'K': /* turn off kerberos */ case 'd': /* turn on SO_DEBUG */ case 'n': /* redirect input from /dev/null */ case 'x': /* DES encrypt */ /* an option which doesn't have an argument */ break; case 'k': /* realm of kerberos */ return (rsh_option_param(is_last_arg, arg, next_arg, i, rsh_options, &s)); case 'l': /* user name */ return (rsh_option_param(is_last_arg, arg, next_arg, i, rsh_options, &options->user_name)); } } gfarm_stringlist_add(rsh_options, arg); return (0); /* don't skip next arg */ } int parse_options(int argc, char **argv, gfarm_stringlist *rsh_options, struct gfrun_options *options) { int i; default_gfrun_options(options); for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; /* argv[argc] == NULL, thus this isn't out of bounds. */ if (parse_option(i + 1 == argc, argv[i], argv[i + 1], rsh_options, options)) i++; } return (i); } int main(int argc, char **argv) { char *e, *e_save, *command_url; char **hosts, *rsh_command, *command_name, *scheduling_file; int i, command_index, nhosts, job_id, nfrags; struct gfrun_options options; gfarm_stringlist input_list, output_list, rsh_options; int remove_gfarm_url_prefix = 0; if (argc >= 1) program_name = basename(argv[0]); gfarm_stringlist_init(&rsh_options); decide_rsh_command(program_name, &rsh_command, &rsh_options, &remove_gfarm_url_prefix); command_index = parse_options(argc, argv, &rsh_options, &options); if (command_index >= argc) /* no command name */ usage(); command_name = argv[command_index]; if (options.authentication_verbose_mode) gfarm_authentication_verbose = 1; if ((e = gfarm_initialize(&argc, &argv)) != NULL) { fprintf(stderr, "%s: gfarm initialize: %s\n", program_name, e); exit(1); } if ((e = gfj_initialize()) != NULL) { fprintf(stderr, "%s: job manager: %s\n", program_name, e); exit(1); } gfarm_stringlist_init(&input_list); gfarm_stringlist_init(&output_list); for (i = command_index + 1; i < argc; i++) { if (gfarm_is_url(argv[i])) { e = gfarm_url_fragment_number(argv[i], &nfrags); if (e == NULL) gfarm_stringlist_add(&input_list, argv[i]); else gfarm_stringlist_add(&output_list, argv[i]); if (remove_gfarm_url_prefix) argv[i] += GFARM_URL_PREFIX_LENGTH; } } /* command name */ e = gfs_realpath(command_name, &command_url); if (e == NULL) { struct gfs_stat gsb; e = gfs_stat(command_url, &gsb); if (e == NULL) { if (!GFARM_S_IS_PROGRAM(gsb.st_mode)) { fprintf(stderr, "%s: not an executable\n", command_url); gfs_stat_free(&gsb); free(command_url); exit(1); } gfs_stat_free(&gsb); } else { fprintf(stderr, "%s: %s\n", command_url, e); free(command_url); exit(1); } } else { if (gfarm_is_url(command_name)) { fprintf(stderr, "%s: %s\n", command_name, e); exit(1); } /* not a command in Gfarm file system */ command_url = command_name; } schedule(command_url, &options, &input_list, &nhosts, &hosts, &scheduling_file); /* * register job manager */ e = gfarm_user_job_register(nhosts, hosts, program_name, scheduling_file, argc - command_index, &argv[command_index], &job_id); if (e != NULL) { fprintf(stderr, "%s: job register: %s\n", program_name, e); exit(1); } e_save = gfrun(rsh_command, &rsh_options, &options, nhosts, hosts, command_url, &argv[command_index + 1]); if (e_save == NULL) { register_stdout_stderr( options.stdout_file, options.stderr_file, rsh_command, &rsh_options, nhosts, hosts); } #if 0 /* XXX - temporary solution; it is not necessary for the output file to be the same number of fragments. */ for (i = 0; i < gfarm_stringlist_length(&output_list); i++) gfarm_url_fragment_cleanup( gfarm_stringlist_elem(&output_list, i), nhosts, hosts); #endif gfarm_strings_free_deeply(nhosts, hosts); gfarm_stringlist_free(&output_list); gfarm_stringlist_free(&input_list); gfarm_stringlist_free(&rsh_options); if ((e = gfarm_terminate()) != NULL) { fprintf(stderr, "%s: gfarm terminate: %s\n", program_name, e); exit(1); } return (e_save == NULL ? 0 : 1); } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/auth_common.c #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <netinet/in.h> /* ntoh[ls]()/hton[ls]() on glibc */ #include <errno.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <openssl/evp.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "auth.h" #define GFARM_AUTH_EXPIRE_DEFAULT (24 * 60 * 60) /* 1 day */ #define GFARM_AUTH_SHARED_KEY_BASENAME ".gfarm_shared_key" #define PATH_URANDOM "/dev/urandom" static int skip_space(FILE *fp) { int c; while ((c = getc(fp)) != EOF) { if (c != ' ' && c != '\t') { ungetc(c, fp); return (0); } } return (EOF); } static int read_hex(FILE *fp, void *buffer, size_t length) { char *p = buffer; size_t i; int c1, c2; int x1, x2; for (i = 0; i < length; i++) { c1 = getc(fp); if (!isxdigit(c1)) { if (c1 != EOF) ungetc(c1, fp); return (EOF); } c2 = getc(fp); if (!isxdigit(c2)) { if (c2 != EOF) ungetc(c2, fp); return (EOF); } x1 = isdigit(c1) ? c1 - '0' : tolower(c1) - 'a' + 10; x2 = isdigit(c2) ? c2 - '0' : tolower(c2) - 'a' + 10; p[i] = x1 * 16 + x2; } c1 = getc(fp); if (c1 != EOF) ungetc(c1, fp); return (isxdigit(c1) ? EOF : 0); } static void write_hex(FILE *fp, void *buffer, size_t length) { unsigned char *p = buffer; size_t i; for (i = 0; i < length; i++) fprintf(fp, "%02x", p[i]); } void gfarm_auth_random(void *buffer, size_t length) { unsigned char *p = buffer; size_t i = 0; int fd, rv; struct timeval t; static int rand_initialized = 0; /* * do not use fopen(3) here, * because it wastes entropy and kernel cpu resource by reading BUFSIZ * rather than reading just the length. */ if ((fd = open(PATH_URANDOM, O_RDONLY)) != -1) { for (; i < length; i += rv) { rv = read(fd, p + i, length - i); if (rv == -1) break; } close(fd); if (i >= length) return; } /* XXX - this makes things too weak */ if (!rand_initialized) { rand_initialized = 1; gettimeofday(&t, NULL); #ifdef HAVE_RANDOM srandom(t.tv_sec + t.tv_usec); #else srand(t.tv_sec + t.tv_usec); #endif } for (; i < length; i++) { #ifdef HAVE_RANDOM p[i] = random(); #else p[i] = (double)rand() * 256 / RAND_MAX; #endif } } char * gfarm_auth_shared_key_get(unsigned int *expirep, char *shared_key, char *home, int create) { FILE *fp; static char keyfile_basename[] = "/" GFARM_AUTH_SHARED_KEY_BASENAME; char *keyfilename; unsigned int expire; keyfilename = malloc(strlen(home) + sizeof(keyfile_basename)); if (keyfilename == NULL) return (GFARM_ERR_NO_MEMORY); strcpy(keyfilename, home); strcat(keyfilename, keyfile_basename); if ((fp = fopen(keyfilename, "r+")) != NULL) { if (skip_space(fp) || read_hex(fp, &expire, sizeof(expire))) { fclose(fp); free(keyfilename); return ("~/" GFARM_AUTH_SHARED_KEY_BASENAME ": invalid expire field"); } expire = ntohl(expire); if (skip_space(fp) || read_hex(fp, shared_key, GFARM_AUTH_SHARED_KEY_LEN)) { fclose(fp); free(keyfilename); return ("~/" GFARM_AUTH_SHARED_KEY_BASENAME ": invalid key field"); } } if (fp == NULL) { if (create == GFARM_AUTH_SHARED_KEY_GET) { free(keyfilename); return ("~/" GFARM_AUTH_SHARED_KEY_BASENAME ": not exist"); } fp = fopen(keyfilename, "w+"); if (fp == NULL) { free(keyfilename); return (gfarm_errno_to_error(errno)); } if (chmod(keyfilename, 0600) == -1) { fclose(fp); free(keyfilename); return (gfarm_errno_to_error(errno)); } expire = 0; /* force to regenerate key */ } if (create == GFARM_AUTH_SHARED_KEY_CREATE_FORCE || time(NULL) >= expire) { if (create == GFARM_AUTH_SHARED_KEY_GET) { fclose(fp); free(keyfilename); return (GFARM_ERR_EXPIRED); } if (fseek(fp, 0L, SEEK_SET) == -1) { fclose(fp); free(keyfilename); return (gfarm_errno_to_error(errno)); } gfarm_auth_random(shared_key, GFARM_AUTH_SHARED_KEY_LEN); expire = time(NULL) + GFARM_AUTH_EXPIRE_DEFAULT; expire = htonl(expire); write_hex(fp, &expire, sizeof(expire)); expire = ntohl(expire); fputc(' ', fp); write_hex(fp, shared_key, GFARM_AUTH_SHARED_KEY_LEN); fputc('\n', fp); } fclose(fp); free(keyfilename); *expirep = expire; return (NULL); } void gfarm_auth_simple_response_data(char *shared_key, char *challenge, char *response) { EVP_MD_CTX mdctx; unsigned int md_len; EVP_DigestInit(&mdctx, EVP_md5()); EVP_DigestUpdate(&mdctx, challenge, GFARM_AUTH_CHALLENGE_LEN); EVP_DigestUpdate(&mdctx, shared_key, GFARM_AUTH_SHARED_KEY_LEN); EVP_DigestFinal(&mdctx, (unsigned char *)response, &md_len); if (md_len != GFARM_AUTH_RESPONSE_LEN) { fprintf(stderr, "gfarm_auth_simple_response_data:" "md5 digest length should be %d, but %d\n", GFARM_AUTH_RESPONSE_LEN, md_len); abort(); } } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfsl/scarg.h #define COMMON_OPTIONS "p:H:M:Nn:U:u" extern int port; extern int acceptorSpecified; extern gss_name_t acceptorName; extern int HandleCommonOptions(int, char *); extern char *newStringOfName(const gss_name_t inputName); extern char *newStringOfCredential(gss_cred_id_t cred); <file_sep>/gfarm_samba/trunk/gfarm.c /* * Gfarm Samba VFS module. * v0.0.1 03 Sep 2010 <NAME> <ohtsuji at hpcs.cs.tsukuba.ac.jp> * Copyright (c) 2012 <NAME>. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * $Id$ */ #include "includes.h" #include "smbd/proto.h" #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <pwd.h> #include <grp.h> #include <dirent.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #undef PACKAGE_BUGREPORT #include <gfarm/gfarm.h> #include "gfarm_acl.h" #include "gfarm_id.h" #include "msgno/msgno.h" /* internal interface */ int gfs_pio_fileno(GFS_File); gfarm_error_t gfs_statdir(GFS_Dir, struct gfs_stat *); /* XXX FIXME */ #define GFS_DEV ((dev_t)-1) #define GFS_BLKSIZE 8192 #define STAT_BLKSIZ 512 /* for st_blocks */ static void gfvfs_error(int msgno, const char *func_name, gfarm_error_t e) { if (e == GFARM_ERR_NO_SUCH_FILE_OR_DIRECTORY || e == GFARM_ERR_NO_SUCH_OBJECT || e == GFARM_ERR_IS_A_DIRECTORY || e == GFARM_ERR_ALREADY_EXISTS) gflog_debug(msgno, "%s: %s", func_name, gfarm_error_string(e)); else gflog_error(msgno, "%s: %s", func_name, gfarm_error_string(e)); } static int open_flags_gfarmize(int open_flags) { int gfs_flags; switch (open_flags & O_ACCMODE) { case O_RDONLY: gfs_flags = GFARM_FILE_RDONLY; break; case O_WRONLY: gfs_flags = GFARM_FILE_WRONLY; break; case O_RDWR: gfs_flags = GFARM_FILE_RDWR; break; default: return (-1); } if ((open_flags & O_TRUNC) != 0) gfs_flags |= GFARM_FILE_TRUNC; return (gfs_flags); } static uid_t get_uid(const char *path, const char *user) { gfarm_error_t e; uid_t uid; e = gfarm_id_user_to_uid(path, user, &uid); if (e != GFARM_ERR_NO_ERROR) { gflog_warning(GFARM_MSG_3000001, "get_uid(%s): %s", user, gfarm_error_string(e)); return (gfarm_id_nobody_uid()); } return (uid); } static gid_t get_gid(const char *path, const char *group) { gfarm_error_t e; gid_t gid; e = gfarm_id_group_to_gid(path, group, &gid); if (e != GFARM_ERR_NO_ERROR) { gflog_warning(GFARM_MSG_3000002, "get_gid(%s): %s", group, gfarm_error_string(e)); return (gfarm_id_nogroup_gid()); } return (gid); } static void copy_gfs_stat(const char *path, SMB_STRUCT_STAT *dst, struct gfs_stat *src) { memset(dst, 0, sizeof(*dst)); dst->st_ex_dev = GFS_DEV; dst->st_ex_ino = src->st_ino; dst->st_ex_mode = src->st_mode; dst->st_ex_nlink = src->st_nlink; dst->st_ex_uid = get_uid(path, src->st_user); dst->st_ex_gid = get_gid(path, src->st_group); dst->st_ex_size = src->st_size; dst->st_ex_blksize = GFS_BLKSIZE; dst->st_ex_blocks = (src->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; dst->st_ex_atime.tv_sec = src->st_atimespec.tv_sec; dst->st_ex_atime.tv_nsec = src->st_atimespec.tv_nsec; dst->st_ex_mtime.tv_sec = src->st_mtimespec.tv_sec; dst->st_ex_mtime.tv_nsec = src->st_mtimespec.tv_nsec; dst->st_ex_ctime.tv_sec = src->st_ctimespec.tv_sec; dst->st_ex_ctime.tv_nsec = src->st_ctimespec.tv_nsec; /* XXX dst->st_ex_btime, dst->st_ex_calculated_birthtime */ } static int switch_user(const char *user) { struct passwd *pwd = getpwnam(user); if (pwd != NULL) return (seteuid(pwd->pw_uid)); errno = ENOENT; return (-1); } struct gfvfs_data { char tmp_path[PATH_MAX + 1]; char *cwd; }; static struct gfvfs_data * gfvfs_data_init() { struct gfvfs_data *gdata; GFARM_MALLOC(gdata); if (gdata == NULL) return (NULL); gdata->cwd = NULL; return (gdata); } static void gfvfs_data_free(void **data) { struct gfvfs_data *gdata = *data; free(gdata->cwd); free(gdata); } static const char * gfvfs_fullpath(vfs_handle_struct *handle, const char *path) { struct gfvfs_data *gdata = handle->data; const char *cwd = gdata->cwd; char *buf = gdata->tmp_path; if (cwd == NULL || path[0] == '/') return (path); if (path[0] == '\0') /* "" */ return (cwd); if (path[0] == '.') { if (path[1] == '\0') /* "." */ return (cwd); else if (path[1] == '/') /* "./NAME..." */ path += 2; } if (cwd[0] == '/') { if (cwd[1] == '\0') /* rootdir */ snprintf(buf, PATH_MAX + 1, "/%s", path); else snprintf(buf, PATH_MAX + 1, "%s/%s", cwd, path); } else snprintf(buf, PATH_MAX + 1, "/%s/%s", cwd, path); return (buf); } /* * OPTIONS * gfarm:config = PATH */ static int gfvfs_connect(vfs_handle_struct *handle, const char *service, const char *user) { gfarm_error_t e; struct gfvfs_data *gdata; gfarm_off_t used, avail, files; uid_t uid = getuid(), saved_euid = geteuid(); const char *config = lp_parm_const_string(SNUM(handle->conn), "gfarm", "config", NULL); static const char log_id[] = "gfarm_samba"; gflog_set_identifier(log_id); if (config != NULL) setenv("GFARM_CONFIG_FILE", config, 0); if (uid == 0) { if (switch_user(user) == -1) { int save_errno = errno; gflog_error(GFARM_MSG_3000003, "connect: unknown user=%s: %s", user, strerror(errno)); errno = save_errno; return (-1); } } e = gfarm_initialize(NULL, NULL); gflog_debug(GFARM_MSG_3000004, "connect: %p, service=%s, user=%s, uid=%d/%d, config=%s", handle, service, user, getuid(), geteuid(), config); if (e != GFARM_ERR_NO_ERROR) { if (uid == 0) /* must exit as saved_euid */ seteuid(saved_euid); gflog_error(GFARM_MSG_3000005, "gfarm_initialize: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } /* * Trying gfmd connection is nessessary here. Because some * VFS callbacks by euid==0 will be called after this * SMB_VFS_CONNECT callback. If a Gfarm connection by euid==0 * with GSI authentication succeeds once, the global user is * recognized to be a user corresponding to the host * certificate all the time. * * The callbacks behavior by euid==0 is: * (samba_3.6.x)/source3/smbd/service.c#make_connection_snum() */ e = gfs_statfs(&used, &avail, &files); if (uid == 0) /* must exit as saved_euid */ seteuid(saved_euid); if (e != GFARM_ERR_NO_ERROR) { (void)gfarm_terminate(); gflog_error(GFARM_MSG_3000006, "initial gfs_statfs: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } gfvfs_acl_id_init(); gdata = gfvfs_data_init(); if (gdata == NULL) { (void)gfarm_terminate(); gflog_error(GFARM_MSG_3000007, "connect: no memory"); errno = ENOMEM; return (-1); } handle->data = gdata; handle->free_data = gfvfs_data_free; return (0); } static void gfvfs_disconnect(vfs_handle_struct *handle) { gfarm_error_t e; gflog_debug(GFARM_MSG_3000008, "disconnect: %p", handle); e = gfarm_terminate(); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000009, "gfarm_terminate: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); } } static uint64_t gfvfs_disk_free(vfs_handle_struct *handle, const char *path, bool small_query, uint64_t *bsize, uint64_t *dfree, uint64_t *dsize) { gfarm_off_t used, avail, files; gfarm_error_t e; gflog_debug(GFARM_MSG_3000010, "disk_free: path=%s", path); e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000011, "gfs_statfs: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } *bsize = 1024; *dfree = avail; *dsize = used + avail; return (0); } static int gfvfs_get_quota(vfs_handle_struct *handle, enum SMB_QUOTA_TYPE qtype, unid_t id, SMB_DISK_QUOTA *dq) { gflog_debug(GFARM_MSG_3000012, "get_quota(ENOSYS): qtype=%d", qtype); errno = ENOSYS; return (-1); } static int gfvfs_set_quota(vfs_handle_struct *handle, enum SMB_QUOTA_TYPE qtype, unid_t id, SMB_DISK_QUOTA *dq) { gflog_debug(GFARM_MSG_3000013, "set_quota(ENOSYS): qtype=%d", qtype); errno = ENOSYS; return (-1); } static int gfvfs_get_shadow_copy_data(vfs_handle_struct *handle, files_struct *fsp, struct shadow_copy_data *shadow_copy_data, bool labels) { gflog_debug(GFARM_MSG_3000014, "get_shadow_copy_data(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static int gfvfs_statvfs(struct vfs_handle_struct *handle, const char *path, struct vfs_statvfs_struct *statbuf) { gfarm_off_t used, avail, files; gfarm_error_t e; gflog_debug(GFARM_MSG_3000015, "statvfs: path=%s", path); e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000016, "gfs_statfs: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } statbuf->BlockSize = 1024; statbuf->TotalBlocks = used + avail; statbuf->BlocksAvail = avail; statbuf->UserBlocksAvail = avail; statbuf->TotalFileNodes = files; statbuf->FreeFileNodes = -1; return (0); } static uint32_t gfvfs_fs_capabilities(struct vfs_handle_struct *handle, enum timestamp_set_resolution *p_ts_res) { gflog_debug(GFARM_MSG_3000017, "fs_capabilities: uid=%d/%d", getuid(), geteuid()); return (0); } struct gfvfs_dir { GFS_Dir dp; char *path; }; static SMB_STRUCT_DIR * gfvfs_opendir(vfs_handle_struct *handle, const char *fname, const char *mask, uint32 attr) { GFS_Dir dp; struct gfvfs_dir *gdp; gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000018, "opendir: path=%s, mask=%s", fname, mask); fullpath = gfvfs_fullpath(handle, fname); e = gfs_opendir_caching(fullpath, &dp); if (e == GFARM_ERR_NO_ERROR) { GFARM_MALLOC(gdp); if (gdp != NULL) gdp->path = strdup(fullpath); if (gdp == NULL || gdp->path == NULL) { gflog_error(GFARM_MSG_3000019, "opendir: no memory"); free(gdp->path); free(gdp); gfs_closedir(dp); return (NULL); } gdp->dp = dp; return ((SMB_STRUCT_DIR *)gdp); } gflog_error(GFARM_MSG_3000020, "gfs_opendir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (NULL); } static SMB_STRUCT_DIR * gfvfs_fdopendir(vfs_handle_struct *handle, files_struct *fsp, const char *mask, uint32 attr) { gflog_debug(GFARM_MSG_3000021, "fdopendir: ENOSYS"); errno = ENOSYS; /* use gfvfs_opendir() instead of this */ return (NULL); } /* returns static region */ static SMB_STRUCT_DIRENT * gfvfs_readdir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp, SMB_STRUCT_STAT *sbuf) { struct gfvfs_dir *gdp = (struct gfvfs_dir *)dirp; struct gfs_dirent *de; static SMB_STRUCT_DIRENT ssd; struct gfs_stat st; char *path; size_t len; gfarm_error_t e; gflog_debug(GFARM_MSG_3000022, "readdir: dir=%p", dirp); if (sbuf) SET_STAT_INVALID(*sbuf); e = gfs_readdir(gdp->dp, &de); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000023, "gfs_readdir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (NULL); } if (de == NULL) return (NULL); gflog_debug(GFARM_MSG_3000024, "readdir: name=%s", de->d_name); ssd.d_ino = de->d_fileno; ssd.d_reclen = de->d_reclen; ssd.d_type = de->d_type; ssd.d_off = 0; strncpy(ssd.d_name, de->d_name, sizeof(ssd.d_name)); if (sbuf) { /* gdp->path is fullpath */ len = strlen(gdp->path) + strlen(de->d_name) + 2; GFARM_MALLOC_ARRAY(path, len); if (path == NULL) return (&ssd); snprintf(path, len, "%s/%s", gdp->path, de->d_name); gflog_debug(GFARM_MSG_3000025, "lstat: path=%s", path); e = gfs_lstat_cached(path, &st); if (e == GFARM_ERR_NO_ERROR) { copy_gfs_stat(path, sbuf, &st); gfs_stat_free(&st); } free(path); } return (&ssd); } static void gfvfs_seekdir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp, long offset) { struct gfvfs_dir *gdp = (struct gfvfs_dir *)dirp; gfarm_error_t e; gflog_debug(GFARM_MSG_3000026, "seekdir: dir=%p, offset=%ld", dirp, offset); e = gfs_seekdir(gdp->dp, offset); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000027, "gfs_seekdir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); } return; } static long gfvfs_telldir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { gfarm_off_t off; struct gfvfs_dir *gdp = (struct gfvfs_dir *)dirp; gfarm_error_t e; gflog_debug(GFARM_MSG_3000028, "telldir: dir=%p", dirp); e = gfs_telldir(gdp->dp, &off); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000029, "gfs_telldir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } return ((long)off); } static void gfvfs_rewind_dir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { struct gfvfs_dir *gdp = (struct gfvfs_dir *)dirp; gfarm_error_t e; gflog_debug(GFARM_MSG_3000030, "rewind_dir: dir=%p", dirp); e = gfs_seekdir(gdp->dp, 0); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000031, "gfs_seekdir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); } return; } static void uncache_parent(const char *path) { char *p = gfarm_url_dir(path); if (p == NULL) { gflog_error(GFARM_MSG_3000032, "uncache_parent(%s): no memory", path); return; } gflog_debug(GFARM_MSG_3000033, "uncache_parent: parent=%s, path=%s", p, path); gfs_stat_cache_purge(p); free(p); } static int gfvfs_mkdir(vfs_handle_struct *handle, const char *path, mode_t mode) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000034, "mkdir: path=%s, mode=%o", path, mode); fullpath = gfvfs_fullpath(handle, path); e = gfs_mkdir(fullpath, mode & GFARM_S_ALLPERM); if (e == GFARM_ERR_NO_ERROR) { uncache_parent(fullpath); return (0); } gfvfs_error(GFARM_MSG_3000035, "gfs_mkdir", e); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_rmdir(vfs_handle_struct *handle, const char *path) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000036, "rmdir: path=%s", path); fullpath = gfvfs_fullpath(handle, path); e = gfs_rmdir(fullpath); if (e == GFARM_ERR_NO_ERROR) { gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } gflog_error(GFARM_MSG_3000037, "gfs_rmdir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_closedir(vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { struct gfvfs_dir *gdp = (struct gfvfs_dir *)dirp; gfarm_error_t e; gflog_debug(GFARM_MSG_3000038, "closedir: dir=%p", dirp); e = gfs_closedir(gdp->dp); free(gdp->path); free(gdp); if (e == GFARM_ERR_NO_ERROR) return (0); gflog_error(GFARM_MSG_3000039, "gfs_closedir: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static void gfvfs_init_search_op(struct vfs_handle_struct *handle, SMB_STRUCT_DIR *dirp) { gflog_debug(GFARM_MSG_3000040, "init_search_op: dir=%p", dirp); return; } static int gfvfs_open(vfs_handle_struct *handle, struct smb_filename *smb_fname, files_struct *fsp, int flags, mode_t mode) { int g_flags = open_flags_gfarmize(flags); const char *fname = smb_fname->base_name, *fullpath; const char *stream = smb_fname->stream_name; char *msg; GFS_File gf; GFS_Dir dp; struct gfvfs_dir *gdp; gfarm_error_t e; gflog_debug(GFARM_MSG_3000041, "open: fsp=%p, path=%s%s, flags=%x, mode=%o, is_dir=%d", fsp, fname, stream != NULL ? stream : "", flags, mode, fsp->is_directory); if (stream != NULL) { errno = ENOENT; return (-1); } if (g_flags < 0) { gflog_error(GFARM_MSG_3000042, "open: %s", strerror(EINVAL)); errno = EINVAL; return (-1); } fullpath = gfvfs_fullpath(handle, fname); if (fsp->is_directory && (g_flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDONLY) { msg = "gfs_opendir"; e = gfs_opendir(fullpath, &dp); } else if (flags & O_CREAT) { msg = "gfs_pio_create"; e = gfs_pio_create(fullpath, g_flags, mode & GFARM_S_ALLPERM, &gf); } else { msg = "gfs_pio_open"; e = gfs_pio_open(fullpath, g_flags, &gf); } if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000043, msg, e); errno = gfarm_error_to_errno(e); return (-1); } if (flags & O_CREAT) uncache_parent(fullpath); else gfs_stat_cache_purge(fullpath); /* * XXX - gen_id is assigned in files.c as a unique number * identifying this fsp over the life of this pid. I guess it * is safe to use to store GFS_File. */ if (fsp->is_directory) { GFARM_MALLOC(gdp); if (gdp != NULL) gdp->path = strdup(fullpath); if (gdp == NULL || gdp->path == NULL) { gflog_error(GFARM_MSG_3000044, "open: no memory"); free(gdp->path); free(gdp); gfs_closedir(dp); errno = ENOMEM; return (-1); } gdp->dp = dp; fsp->fh->gen_id = (unsigned long)gdp; return (0); /* dummy */ } else { fsp->fh->gen_id = (unsigned long)gf; return (gfs_pio_fileno(gf)); /* although do not use this */ } } static NTSTATUS gfvfs_create_file(struct vfs_handle_struct *handle, struct smb_request *req, uint16_t root_dir_fid, struct smb_filename *smb_fname, uint32_t access_mask, uint32_t share_access, uint32_t create_disposition, uint32_t create_options, uint32_t file_attributes, uint32_t oplock_request, uint64_t allocation_size, uint32_t private_flags, struct security_descriptor *sd, struct ea_list *ea_list, files_struct **result_fsp, int *pinfo) { NTSTATUS result; const char *str_create_disposition; gflog_debug(GFARM_MSG_3000045, "create_file(VFS_NEXT): %s%s", smb_fname->base_name, smb_fname->stream_name != NULL ? smb_fname->stream_name : ""); *result_fsp = NULL; result = SMB_VFS_NEXT_CREATE_FILE( handle, req, root_dir_fid, smb_fname, access_mask, share_access, create_disposition, create_options, file_attributes, oplock_request, allocation_size, private_flags, sd, ea_list, result_fsp, pinfo); switch (create_disposition) { case FILE_SUPERSEDE: str_create_disposition = "SUPERSEDE"; break; case FILE_OVERWRITE_IF: str_create_disposition = "OVERWRITE_IF"; break; case FILE_OPEN: str_create_disposition = "OPEN"; break; case FILE_OVERWRITE: str_create_disposition = "OVERWRITE"; break; case FILE_CREATE: str_create_disposition = "CREATE"; break; case FILE_OPEN_IF: str_create_disposition = "OPEN_IF"; break; default: str_create_disposition = "UNKNOWN"; } gflog_debug(GFARM_MSG_3000046, "create_file: %p|%s|0x%x|%s|%s|%s%s", *result_fsp, nt_errstr(result), access_mask, create_options & FILE_DIRECTORY_FILE ? "DIR" : "FILE", str_create_disposition, smb_fname->base_name, smb_fname->stream_name != NULL ? smb_fname->stream_name : ""); return (result); } static int gfvfs_close_fn(vfs_handle_struct *handle, files_struct *fsp) { gfarm_error_t e; char *msg; gflog_debug(GFARM_MSG_3000047, "close_fn: fsp=%p", fsp); if (!fsp->is_directory) { msg = "gfs_pio_close"; e = gfs_pio_close((GFS_File)fsp->fh->gen_id); } else { struct gfvfs_dir *gdp = (struct gfvfs_dir *)fsp->fh->gen_id; msg = "gfs_closedir"; e = gfs_closedir(gdp->dp); free(gdp->path); free(gdp); } if (e == GFARM_ERR_NO_ERROR) return (0); gflog_error(GFARM_MSG_3000048, "%s: %s", msg, gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static ssize_t gfvfs_vfs_read(vfs_handle_struct *handle, files_struct *fsp, void *data, size_t n) { gfarm_error_t e; int rv; gflog_debug(GFARM_MSG_3000049, "read: fsp=%p, size=%lu", fsp, (unsigned long)n); e = gfs_pio_read((GFS_File)fsp->fh->gen_id, data, n, &rv); if (e == GFARM_ERR_NO_ERROR) return (rv); gflog_error(GFARM_MSG_3000050, "gfs_pio_read: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static ssize_t gfvfs_pread(vfs_handle_struct *handle, files_struct *fsp, void *data, size_t n, SMB_OFF_T offset) { gfarm_error_t e; gfarm_off_t off; GFS_File gf = (GFS_File)fsp->fh->gen_id; int rv; gflog_debug(GFARM_MSG_3000051, "pread: fsp=%p, size=%lu, offset=%lld", fsp, (unsigned long)n, (long long)offset); e = gfs_pio_seek(gf, (off_t)offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_read(gf, data, n, &rv); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000052, "gfs_pio_pread: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } return (rv); } static ssize_t gfvfs_write(vfs_handle_struct *handle, files_struct *fsp, const void *data, size_t n) { gfarm_error_t e; int rv; gflog_debug(GFARM_MSG_3000053, "write: fsp=%p, size=%lu", fsp, (unsigned long)n); e = gfs_pio_write((GFS_File)fsp->fh->gen_id, data, n, &rv); if (e == GFARM_ERR_NO_ERROR) { const char *fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); gfs_stat_cache_purge(fullpath); return (rv); } gflog_error(GFARM_MSG_3000054, "gfs_pio_write: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static ssize_t gfvfs_pwrite(vfs_handle_struct *handle, files_struct *fsp, const void *data, size_t n, SMB_OFF_T offset) { gfarm_error_t e; gfarm_off_t off; int rv; const char *fullpath; gflog_debug(GFARM_MSG_3000055, "pwrite: fsp=%p, size=%lu, offset=%lld", data, (unsigned long)n, (long long)offset); e = gfs_pio_seek((GFS_File)fsp->fh->gen_id, offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_write((GFS_File)fsp->fh->gen_id, data, n, &rv); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000056, "gfs_pio_pwrite: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); gfs_stat_cache_purge(fullpath); return (rv); } static SMB_OFF_T gfvfs_lseek(vfs_handle_struct *handle, files_struct *fsp, SMB_OFF_T offset, int whence) { gfarm_off_t off; gfarm_error_t e; gflog_debug(GFARM_MSG_3000057, "lseek: fsp=%p, offset=%ld, whence=%d", fsp, (long)offset, whence); e = gfs_pio_seek((GFS_File)fsp->fh->gen_id, offset, GFARM_SEEK_SET, &off); if (e == GFARM_ERR_NO_ERROR) return (off); gflog_error(GFARM_MSG_3000058, "gfs_pio_seek: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static ssize_t gfvfs_sendfile(vfs_handle_struct *handle, int tofd, files_struct *fromfsp, const DATA_BLOB *hdr, SMB_OFF_T offset, size_t n) { gflog_debug(GFARM_MSG_3000059, "sendfile(ENOSYS): to_fd=%d, from_fsp=%p", tofd, fromfsp); errno = ENOSYS; return (-1); } static ssize_t gfvfs_recvfile(vfs_handle_struct *handle, int fromfd, files_struct *tofsp, SMB_OFF_T offset, size_t n) { gflog_debug(GFARM_MSG_3000060, "recvfile(ENOSYS): from_fd=%d, to_fsp=%p", fromfd, tofsp); errno = ENOSYS; return (-1); } static int gfvfs_rename(vfs_handle_struct *handle, const struct smb_filename *smb_fname_src, const struct smb_filename *smb_fname_dst) { const char *oldname = smb_fname_src->base_name; const char *old_stream = smb_fname_src->stream_name; const char *newname = smb_fname_dst->base_name; const char *new_stream = smb_fname_dst->stream_name; char *fullold, *fullnew; gfarm_error_t e; gflog_debug(GFARM_MSG_3000061, "rename: old=%s%s, new=%s%s", oldname, old_stream != NULL ? old_stream : "", newname, new_stream != NULL ? new_stream : ""); if (old_stream != NULL || new_stream != NULL) { errno = ENOENT; return (-1); } fullold = strdup(gfvfs_fullpath(handle, oldname)); fullnew = strdup(gfvfs_fullpath(handle, newname)); if (fullold == NULL || fullnew == NULL) { free(fullold); free(fullnew); gflog_error(GFARM_MSG_3000062, "rename: no memory"); errno = ENOMEM; return (-1); } e = gfs_rename(fullold, fullnew); if (e == GFARM_ERR_NO_ERROR) { gfs_stat_cache_purge(fullold); uncache_parent(fullold); gfs_stat_cache_purge(fullnew); uncache_parent(fullnew); free(fullold); free(fullnew); return (0); } free(fullold); free(fullnew); gflog_error(GFARM_MSG_3000063, "gfs_rename: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_fsync(vfs_handle_struct *handle, files_struct *fsp) { gfarm_error_t e; gflog_debug(GFARM_MSG_3000064, "fsync: fsp=%p", fsp); e = gfs_pio_sync((GFS_File)fsp->fh->gen_id); if (e == GFARM_ERR_NO_ERROR) return (0); gflog_error(GFARM_MSG_3000065, "gfs_pio_sync: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_stat(vfs_handle_struct *handle, struct smb_filename *smb_fname) { struct gfs_stat st; const char *path = smb_fname->base_name, *fullpath; const char *stream = smb_fname->stream_name; gfarm_error_t e; gflog_debug(GFARM_MSG_3000066, "stat: path=%s%s", path, stream != NULL ? stream : ""); if (stream != NULL) { errno = ENOENT; return (-1); } fullpath = gfvfs_fullpath(handle, path); e = gfs_stat_cached(fullpath, &st); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000067, "gfs_stat", e); errno = gfarm_error_to_errno(e); return (-1); } copy_gfs_stat(fullpath, &smb_fname->st, &st); gfs_stat_free(&st); return (0); } static int gfvfs_fstat(vfs_handle_struct *handle, files_struct *fsp, SMB_STRUCT_STAT *sbuf) { struct gfs_stat st; char *msg; gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000068, "fstat: fsp=%p, is_dir=%d", fsp, fsp->is_directory); if (!fsp->is_directory) { msg = "gfs_pio_stat"; e = gfs_pio_stat((GFS_File)fsp->fh->gen_id, &st); } else { msg = "gfs_statdir"; e = gfs_statdir( ((struct gfvfs_dir *)fsp->fh->gen_id)->dp, &st); } if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000069, msg, e); errno = gfarm_error_to_errno(e); return (-1); } fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); copy_gfs_stat(fullpath, sbuf, &st); gfs_stat_free(&st); return (0); } static int gfvfs_lstat(vfs_handle_struct *handle, struct smb_filename *smb_fname) { struct gfs_stat st; const char *path = smb_fname->base_name, *fullpath; const char *stream = smb_fname->stream_name; gfarm_error_t e; gflog_debug(GFARM_MSG_3000070, "lstat: path=%s%s", path, stream != NULL ? stream : ""); if (stream != NULL) { errno = ENOENT; return (-1); } fullpath = gfvfs_fullpath(handle, path); e = gfs_lstat_cached(fullpath, &st); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000071, "gfs_lstat", e); errno = gfarm_error_to_errno(e); return (-1); } copy_gfs_stat(fullpath, &smb_fname->st, &st); gfs_stat_free(&st); return (0); } /* should not be ENOSYS */ static uint64_t gfvfs_get_alloc_size(struct vfs_handle_struct *handle, struct files_struct *fsp, const SMB_STRUCT_STAT *sbuf) { uint64_t result; gflog_debug(GFARM_MSG_3000072, "get_alloc_size: fsp=%p, st_size %lld", fsp, (long long)sbuf->st_ex_size); if (S_ISDIR(sbuf->st_ex_mode)) return (0); result = get_file_size_stat(sbuf); if (fsp && fsp->initial_allocation_size) result = MAX(result, fsp->initial_allocation_size); result = smb_roundup(handle->conn, result); gflog_debug(GFARM_MSG_3000073, "get_alloc_size: result %lld", (long long)result); return (result); } static int gfvfs_unlink(vfs_handle_struct *handle, const struct smb_filename *smb_fname) { const char *path = smb_fname->base_name; const char *stream = smb_fname->stream_name; gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000074, "unlink: path=%s%s", path, stream != NULL ? stream : ""); if (stream != NULL) { errno = ENOENT; return (-1); } fullpath = gfvfs_fullpath(handle, path); e = gfs_unlink(fullpath); if (e == GFARM_ERR_NO_ERROR) { gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } gflog_error(GFARM_MSG_3000075, "gfs_unlink: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_chmod(vfs_handle_struct *handle, const char *path, mode_t mode) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000076, "chmod: path=%s, mode=%o", path, mode); fullpath = gfvfs_fullpath(handle, path); e = gfs_chmod(fullpath, mode & GFARM_S_ALLPERM); if (e == GFARM_ERR_NO_ERROR) { gfs_stat_cache_purge(fullpath); return (0); } gflog_error(GFARM_MSG_3000077, "gfs_chmod: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_fchmod(vfs_handle_struct *handle, files_struct *fsp, mode_t mode) { gflog_debug(GFARM_MSG_3000078, "fchmod(ENOSYS): fsp=%p, mode=%o", fsp, mode); errno = ENOSYS; /* XXX gfs_fchmod() */ return (-1); } static int gfvfs_chown(vfs_handle_struct *handle, const char *path, uid_t uid, gid_t gid) { gflog_debug(GFARM_MSG_3000079, "chown(ENOSYS): path=%s, uid=%d, gid=%d", path, uid, gid); errno = ENOSYS; return (-1); } static int gfvfs_fchown(vfs_handle_struct *handle, files_struct *fsp, uid_t uid, gid_t gid) { gflog_debug(GFARM_MSG_3000080, "fchown(ENOSYS): fsp=%p, uid=%d, gid=%d", fsp, uid, gid); errno = ENOSYS; return (-1); } static int gfvfs_lchown(vfs_handle_struct *handle, const char *path, uid_t uid, gid_t gid) { gflog_debug(GFARM_MSG_3000081, "lchown(ENOSYS): path=%s, uid=%d, gid=%d", path, uid, gid); errno = ENOSYS; return (-1); } static int gfvfs_chdir(vfs_handle_struct *handle, const char *path) { char *fullpath; struct gfvfs_data *gdata = handle->data; gflog_debug(GFARM_MSG_3000082, "chdir: path=%s, uid=%d/%d", path, getuid(), geteuid()); fullpath = strdup(gfvfs_fullpath(handle, path)); if (fullpath == NULL) { gflog_error(GFARM_MSG_3000083, "chdir: no memory"); errno = ENOMEM;; return (-1); } free(gdata->cwd); gdata->cwd = fullpath; return (0); } static char * gfvfs_getwd(vfs_handle_struct *handle, char *buf) { struct gfvfs_data *gdata = handle->data; gflog_debug(GFARM_MSG_3000084, "getwd: cwd=%s", gdata->cwd); return (gdata->cwd); } /* should not be ENOSYS */ static int gfvfs_ntimes(vfs_handle_struct *handle, const struct smb_filename *smb_fname, struct smb_file_time *ft) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000085, "ntimes: path=%s%s", smb_fname->base_name, smb_fname->stream_name != NULL ? smb_fname->stream_name : ""); if (smb_fname->stream_name != NULL) { errno = ENOENT; return (-1); } fullpath = gfvfs_fullpath(handle, smb_fname->base_name); if (ft != NULL) { struct gfarm_timespec gt[2]; if (null_timespec(ft->atime)) ft->atime = smb_fname->st.st_ex_atime; if (null_timespec(ft->mtime)) ft->mtime = smb_fname->st.st_ex_mtime; /* XXX ft->create_time */ if ((timespec_compare(&ft->atime, &smb_fname->st.st_ex_atime) == 0) && (timespec_compare(&ft->mtime, &smb_fname->st.st_ex_mtime) == 0)) return (0); gt[0].tv_sec = ft->atime.tv_sec; gt[0].tv_nsec = ft->atime.tv_nsec; gt[1].tv_sec = ft->mtime.tv_sec; gt[1].tv_nsec = ft->mtime.tv_nsec; e = gfs_lutimes(fullpath, gt); } else e = gfs_lutimes(fullpath, NULL); if (e == GFARM_ERR_NO_ERROR) { gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } gflog_debug(GFARM_MSG_3000086, "gfs_lutimes: %s: %s", fullpath, gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_ftruncate(vfs_handle_struct *handle, files_struct *fsp, SMB_OFF_T offset) { gfarm_error_t e; gflog_debug(GFARM_MSG_3000087, "ftruncate: fsp=%p, offset=%lld", fsp, (long long)offset); e = gfs_pio_truncate((GFS_File)fsp->fh->gen_id, offset); if (e == GFARM_ERR_NO_ERROR) { const char *fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); gfs_stat_cache_purge(fullpath); return (0); } gflog_error(GFARM_MSG_3000088, "gfs_pio_truncate: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_fallocate(vfs_handle_struct *handle, files_struct *fsp, enum vfs_fallocate_mode mode, SMB_OFF_T offset, SMB_OFF_T len) { gflog_debug(GFARM_MSG_3000089, "fallocate(ENOSYS): fsp=%p, off=%lld, len=%lld", fsp, (long long)offset, (long long)len); errno = ENOSYS; return (-1); } static bool gfvfs_lock(vfs_handle_struct *handle, files_struct *fsp, int op, SMB_OFF_T offset, SMB_OFF_T count, int type) { gflog_debug(GFARM_MSG_3000090, "lock(ENOSYS): fsp=%p, op=%o, offset=%lld, count=%lld, type=%o", fsp, op, (long long)offset, (long long)count, type); errno = ENOSYS; return (false); } static int gfvfs_kernel_flock(struct vfs_handle_struct *handle, struct files_struct *fsp, uint32 share_mode, uint32 access_mask) { gflog_debug(GFARM_MSG_3000091, "kernel_flock(ignored): fsp=%p, share_mode=%o, access_mask=%o", fsp, share_mode, access_mask); #if 0 /* should not be ENOSYS */ gflog_info(GFARM_MSG_3000092, "kernel_flock: %s", strerror(ENOSYS)); errno = ENOSYS; return (-1); #else return (0); /* ignore ENOSYS */ #endif } static int gfvfs_linux_setlease(struct vfs_handle_struct *handle, struct files_struct *fsp, int leasetype) { gflog_debug(GFARM_MSG_3000093, "linux_setlease(ENOSYS): fsp=%p, type=%o", fsp, leasetype); errno = ENOSYS; return (-1); } static bool gfvfs_getlock(vfs_handle_struct *handle, files_struct *fsp, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pid_t *ppid) { gflog_debug(GFARM_MSG_3000094, "getlock(ENOSYS): fsp=%p", fsp); #if 1 errno = ENOSYS; return (false); #else *ptype = F_UNLCK; return (0); #endif } static int gfvfs_symlink(vfs_handle_struct *handle, const char *oldpath, const char *newpath) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000095, "symlink: old=%s, new=%s", oldpath, newpath); fullpath = gfvfs_fullpath(handle, newpath); e = gfs_symlink(oldpath, fullpath); if (e == GFARM_ERR_NO_ERROR) { uncache_parent(fullpath); return (0); } gflog_error(GFARM_MSG_3000096, "gfs_symlink: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_vfs_readlink(vfs_handle_struct *handle, const char *path, char *buf, size_t bufsiz) { char *old; size_t len; gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000097, "readlink: path=%s", path); fullpath = gfvfs_fullpath(handle, path); e = gfs_readlink(fullpath, &old); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000098, "gfs_readlink: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } len = strlen(old); if (len >= bufsiz) len = bufsiz - 1; memcpy(buf, old, len); buf[len] = '\0'; free(old); return (len); } static int gfvfs_link(vfs_handle_struct *handle, const char *oldpath, const char *newpath) { gfarm_error_t e; char *fullold, *fullnew; gflog_debug(GFARM_MSG_3000099, "link: old=%s, new=%s", oldpath, newpath); fullold = strdup(gfvfs_fullpath(handle, oldpath)); fullnew = strdup(gfvfs_fullpath(handle, newpath)); if (fullold == NULL || fullnew == NULL) { free(fullold); free(fullnew); gflog_error(GFARM_MSG_3000100, "link: no memory"); errno = ENOMEM; return (-1); } e = gfs_link(fullold, fullnew); if (e == GFARM_ERR_NO_ERROR) { uncache_parent(fullnew); free(fullold); free(fullnew); return (0); } free(fullold); free(fullnew); gflog_error(GFARM_MSG_3000101, "gfs_link: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } static int gfvfs_mknod(vfs_handle_struct *handle, const char *path, mode_t mode, SMB_DEV_T dev) { GFS_File gf; gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000102, "mknod: path=%s, mode=%o", path, mode); if (!S_ISREG(mode)) { gflog_error(GFARM_MSG_3000103, "mknod: %s", strerror(ENOSYS)); errno = ENOSYS; return (-1); } fullpath = gfvfs_fullpath(handle, path); e = gfs_pio_create(fullpath, GFARM_FILE_WRONLY, mode & GFARM_S_ALLPERM, &gf); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_close(gf); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000104, "gfs_pio_mknod: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } uncache_parent(fullpath); return (0); } #define GFARM_PREFIX "gfarm:" #define SLASH_SLASH "//" static char * skip_prefix(char *url) { if (url == NULL) return (NULL); if (strncmp(url, GFARM_PREFIX, strlen(GFARM_PREFIX)) == 0) url += strlen(GFARM_PREFIX); if (strncmp(url, SLASH_SLASH, strlen(SLASH_SLASH)) == 0) url += strlen(SLASH_SLASH); /* skip hostname */ if (isalpha(*url)) while (isalnum(*url) || *url == '.' || *url == '-') ++url; if (*url == ':') ++url; /* skip port */ while (isdigit(*url)) ++url; return (url); } static char * gfvfs_realpath(vfs_handle_struct *handle, const char *path) { const char *fullpath; char *rpath, *skip_path; gfarm_error_t e; gflog_debug(GFARM_MSG_3000105, "realpath: path=%s, uid=%d/%d", path, getuid(), geteuid()); fullpath = gfvfs_fullpath(handle, path); e = gfs_realpath(fullpath, &rpath); /* slow? */ if (e == GFARM_ERR_NO_ERROR) { skip_path = strdup(skip_prefix(rpath)); free(rpath); if (skip_path != NULL) { gflog_debug(GFARM_MSG_3000106, "realpath: result=%s", skip_path); } else { gflog_error(GFARM_MSG_3000107, "realpath: no memory"); errno = ENOMEM; } return (skip_path); } gfvfs_error(GFARM_MSG_3000108, "realpath", e); errno = gfarm_error_to_errno(e); return (NULL); } static NTSTATUS gfvfs_notify_watch(struct vfs_handle_struct *handle, struct sys_notify_context *ctx, struct notify_entry *e, void (*callback)(struct sys_notify_context *ctx, void *private_data, struct notify_event *ev), void *private_data, void *handle_p) { gflog_debug(GFARM_MSG_3000109, "notify_watch(ENOSYS)"); return (NT_STATUS_NOT_IMPLEMENTED); } static int gfvfs_chflags(vfs_handle_struct *handle, const char *path, uint flags) { gflog_debug(GFARM_MSG_3000110, "chflags(ENOSYS): path=%s, flags=%d", path, flags); errno = ENOSYS; return (-1); } static struct file_id gfvfs_file_id_create(vfs_handle_struct *handle, const SMB_STRUCT_STAT *sbuf) { struct file_id id; gflog_debug(GFARM_MSG_3000111, "file_id_create: st_dev=%lld, st_ino=%lld", (long long)sbuf->st_ex_dev, (long long)sbuf->st_ex_ino); ZERO_STRUCT(id); id.devid = sbuf->st_ex_dev; /* XXX not implemented */ id.inode = sbuf->st_ex_ino; /* id.extid is unused by default */ return (id); } static NTSTATUS gfvfs_streaminfo(struct vfs_handle_struct *handle, struct files_struct *fsp, const char *fname, TALLOC_CTX *mem_ctx, unsigned int *num_streams, struct stream_struct **streams) { gflog_debug(GFARM_MSG_3000112, "streaminfo(VFS_NEXT): fsp=%p, path=%s", fsp, fname); return (SMB_VFS_NEXT_STREAMINFO(handle, fsp, fname, mem_ctx, num_streams, streams)); } static int gfvfs_get_real_filename( struct vfs_handle_struct *handle, const char *path, const char *name, TALLOC_CTX *mem_ctx, char **found_name) { gflog_debug(GFARM_MSG_3000113, "get_real_filename(EOPNOTSUPP): path=%s, name=%s", path, name); errno = EOPNOTSUPP; /* should not be ENOSYS */ return (-1); } static const char * gfvfs_connectpath(struct vfs_handle_struct *handle, const char *filename) { const char *result = SMB_VFS_NEXT_CONNECTPATH(handle, filename); gflog_debug(GFARM_MSG_3000114, "connectpath(VFS_NEXT): path=%s, result=%s", filename, result); return (result); } static NTSTATUS gfvfs_brl_lock_windows( struct vfs_handle_struct *handle, struct byte_range_lock *br_lck, struct lock_struct *plock, bool blocking_lock, struct blocking_lock_record *blr) { gflog_debug(GFARM_MSG_3000115, "brl_lock_windows(VFS_NEXT): fsp=%p", br_lck->fsp); return (SMB_VFS_NEXT_BRL_LOCK_WINDOWS(handle, br_lck, plock, blocking_lock, blr)); } static bool gfvfs_brl_unlock_windows( struct vfs_handle_struct *handle, struct messaging_context *msg_ctx, struct byte_range_lock *br_lck, const struct lock_struct *plock) { gflog_debug(GFARM_MSG_3000116, "brl_unlock_windows(VFS_NEXT): fsp=%p", br_lck->fsp); return (SMB_VFS_NEXT_BRL_UNLOCK_WINDOWS(handle, msg_ctx, br_lck, plock)); } static bool gfvfs_brl_cancel_windows( struct vfs_handle_struct *handle, struct byte_range_lock *br_lck, struct lock_struct *plock, struct blocking_lock_record *blr) { gflog_debug(GFARM_MSG_3000117, "brl_cancel_windows(VFS_NEXT): fsp=%p", br_lck->fsp); return (SMB_VFS_NEXT_BRL_CANCEL_WINDOWS(handle, br_lck, plock, blr)); } static bool gfvfs_strict_lock( struct vfs_handle_struct *handle, struct files_struct *fsp, struct lock_struct *plock) { gflog_debug(GFARM_MSG_3000118, "strict_lock(VFS_NEXT): fsp=%p", fsp); /* should not be ENOSYS */ return (SMB_VFS_NEXT_STRICT_LOCK(handle, fsp, plock)); } static void gfvfs_strict_unlock( struct vfs_handle_struct *handle, struct files_struct *fsp, struct lock_struct *plock) { gflog_debug(GFARM_MSG_3000119, "strict_unlock(VFS_NEXT): fsp=%p", fsp); SMB_VFS_NEXT_STRICT_UNLOCK(handle, fsp, plock); } static NTSTATUS gfvfs_translate_name( struct vfs_handle_struct *handle, const char *mapped_name, enum vfs_translate_direction direction, TALLOC_CTX *mem_ctx, char **pmapped_name) { gflog_debug(GFARM_MSG_3000120, "translate_name(none mapped): name=%s", mapped_name); /* should not be NT_STATUS_NOT_IMPLEMENTED */ return (NT_STATUS_NONE_MAPPED); } static NTSTATUS gfvfs_fget_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info, struct security_descriptor **ppdesc) { gflog_debug(GFARM_MSG_3000121, "fget_nt_acl(VFS_NEXT): fsp=%p", fsp); return (SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info, ppdesc)); } static NTSTATUS gfvfs_get_nt_acl(vfs_handle_struct *handle, const char *name, uint32 security_info, struct security_descriptor **ppdesc) { gflog_debug(GFARM_MSG_3000122, "get_nt_acl(VFS_NEXT): path=%s", name); return (SMB_VFS_NEXT_GET_NT_ACL(handle, name, security_info, ppdesc)); } static NTSTATUS gfvfs_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 si_sent, const struct security_descriptor *psd) { gflog_debug(GFARM_MSG_3000123, "fset_nt_acl(VFS_NEXT): fsp=%p", fsp); return (SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, si_sent, psd)); } static int gfvfs_chmod_acl(vfs_handle_struct *handle, const char *path, mode_t mode) { gflog_debug(GFARM_MSG_3000124, "chmod_acl: path=%s, mode=%o", path, mode); return (gfvfs_chmod(handle, path, mode)); } static int gfvfs_fchmod_acl(vfs_handle_struct *handle, files_struct *fsp, mode_t mode) { gflog_debug(GFARM_MSG_3000125, "fchmod_acl: fsp=%p, mode=%o", fsp, mode); return (gfvfs_fchmod(handle, fsp, mode)); } static int smb_acl_type_to_gfarm_acl_type(const char *path, const char *diag, SMB_ACL_TYPE_T s_type, gfarm_acl_type_t *g_typep) { switch (s_type) { case SMB_ACL_TYPE_ACCESS: *g_typep = GFARM_ACL_TYPE_ACCESS; gflog_debug(GFARM_MSG_3000126, "%s[access]: path=%s", diag, path); return (1); case SMB_ACL_TYPE_DEFAULT: *g_typep = GFARM_ACL_TYPE_DEFAULT; gflog_debug(GFARM_MSG_3000127, "%s[default]: path=%s", diag, path); return (1); default: gflog_debug(GFARM_MSG_3000128, "%s[EINVAL]: path=%s", diag, path); return (0); } } static SMB_ACL_T gfvfs_sys_acl_get_file(vfs_handle_struct *handle, const char *path, SMB_ACL_TYPE_T s_type) { SMB_ACL_T s_acl; gfarm_error_t e; gfarm_acl_t g_acl; gfarm_acl_type_t g_type; int save_errno; const char *fullpath; static const char diag[] = "sys_acl_get_file"; fullpath = gfvfs_fullpath(handle, path); if (!smb_acl_type_to_gfarm_acl_type(fullpath, diag, s_type, &g_type)) { errno = EINVAL; return (NULL); } e = gfs_acl_get_file_cached(fullpath, g_type, &g_acl); if (e == GFARM_ERR_NO_SUCH_OBJECT && g_type == GFARM_ACL_TYPE_ACCESS) { struct gfs_stat st; e = gfs_lstat_cached(fullpath, &st); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000129, "gfs_lstat: %s: %s", fullpath, gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (NULL); } e = gfs_acl_from_mode(st.st_mode, &g_acl); gfs_stat_free(&st); } if (e != GFARM_ERR_NO_ERROR) { if (e == GFARM_ERR_NO_SUCH_OBJECT) gflog_debug(GFARM_MSG_3000130, "gfs_acl_get_file_cached[%s]: %s: %s", g_type == GFARM_ACL_TYPE_ACCESS ? "access" : "default", fullpath, gfarm_error_string(e)); else gflog_error(GFARM_MSG_3000131, "gfs_acl_get_file_cached[%s]: %s: %s", g_type == GFARM_ACL_TYPE_ACCESS ? "access" : "default", fullpath, gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (NULL); } s_acl = gfvfs_gfarm_acl_to_smb_acl(fullpath, g_acl); save_errno = errno; gfs_acl_free(g_acl); errno = save_errno; return (s_acl); } static SMB_ACL_T gfvfs_sys_acl_get_fd(vfs_handle_struct *handle, files_struct *fsp) { gflog_debug(GFARM_MSG_3000132, "sys_acl_get_fd(ENOSYS): fsp=%p", fsp); errno = ENOSYS; /* XXX gfs_acl_get_fh() */ return (NULL); } static int gfvfs_sys_acl_set_file(vfs_handle_struct *handle, const char *path, SMB_ACL_TYPE_T s_type, SMB_ACL_T s_acl) { gfarm_error_t e; gfarm_acl_t g_acl; gfarm_acl_type_t g_type; const char *fullpath; static const char diag[] = "sys_acl_set_file"; fullpath = gfvfs_fullpath(handle, path); if (!smb_acl_type_to_gfarm_acl_type(fullpath, diag, s_type, &g_type)) { errno = EINVAL; return (-1); } g_acl = gfvfs_smb_acl_to_gfarm_acl(fullpath, s_acl); if (g_acl == NULL) return (-1); /* with errno */ e = gfs_acl_set_file(fullpath, g_type, g_acl); gfs_acl_free(g_acl); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000133, "gfs_acl_set_file: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_sys_acl_set_fd(vfs_handle_struct *handle, files_struct *fsp, SMB_ACL_T theacl) { gflog_debug(GFARM_MSG_3000134, "sys_acl_set_fd(ENOSYS): fsp=%p", fsp); errno = ENOSYS; /* XXX gfs_acl_set_fh() */ return (-1); } static int gfvfs_sys_acl_delete_def_file(vfs_handle_struct *handle, const char *path) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000135, "sys_acl_delete_def_file: path=%s", path); fullpath = gfvfs_fullpath(handle, path); e = gfs_acl_delete_def_file(fullpath); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_3000136, "gfs_acl_delete_def_file: %s", gfarm_error_string(e)); errno = gfarm_error_to_errno(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } #if 0 /* unnecessary to hook (transparent) */ static int gfvfs_sys_acl_get_entry(vfs_handle_struct *handle, SMB_ACL_T theacl, int entry_id, SMB_ACL_ENTRY_T *entry_p) { gflog_debug(GFARM_MSG_3000137, "sys_acl_get_entry(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_get_tag_type(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d, SMB_ACL_TAG_T *tag_type_p) { gflog_debug(GFARM_MSG_3000138, "sys_acl_get_tag_type(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_get_permset(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d, SMB_ACL_PERMSET_T *permset_p) { gflog_debug(GFARM_MSG_3000139, "sys_acl_get_permset(ENOSYS)"); errno = ENOSYS; return (-1); } static void * gfvfs_sys_acl_get_qualifier(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry_d) { gflog_debug(GFARM_MSG_3000140, "sys_acl_get_qualifier(ENOSYS)"); errno = ENOSYS; return (NULL); } static int gfvfs_sys_acl_clear_perms(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset) { gflog_debug(GFARM_MSG_3000141, "sys_acl_clear_perms(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_add_perm(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset, SMB_ACL_PERM_T perm) { gflog_debug(GFARM_MSG_3000142, "sys_acl_add_perm(ENOSYS)"); errno = ENOSYS; return (-1); } static char * gfvfs_sys_acl_to_text(vfs_handle_struct *handle, SMB_ACL_T theacl, ssize_t *plen) { gflog_debug(GFARM_MSG_3000143, "sys_acl_to_text(ENOSYS)"); errno = ENOSYS; return (NULL); } static SMB_ACL_T gfvfs_sys_acl_init(vfs_handle_struct *handle, int count) { gflog_debug(GFARM_MSG_3000144, "sys_acl_init(ENOSYS): count %d", count); errno = ENOSYS; return (NULL); } static int gfvfs_sys_acl_create_entry(vfs_handle_struct *handle, SMB_ACL_T *pacl, SMB_ACL_ENTRY_T *pentry) { gflog_debug(GFARM_MSG_3000145, "sys_acl_create_entry(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_set_tag_type(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, SMB_ACL_TAG_T tagtype) { gflog_debug(GFARM_MSG_3000146, "sys_acl_set_tag_type(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_set_qualifier(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, void *qual) { gflog_debug(GFARM_MSG_3000147, "sys_acl_set_qualifier(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_set_permset(vfs_handle_struct *handle, SMB_ACL_ENTRY_T entry, SMB_ACL_PERMSET_T permset) { gflog_debug(GFARM_MSG_3000148, "sys_acl_set_permset(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_valid(vfs_handle_struct *handle, SMB_ACL_T theacl) { gflog_debug(GFARM_MSG_3000149, "sys_acl_valid(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_get_perm(vfs_handle_struct *handle, SMB_ACL_PERMSET_T permset, SMB_ACL_PERM_T perm) { gflog_debug(GFARM_MSG_3000150, "sys_acl_get_perm(ENOSYS)"); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_free_text(vfs_handle_struct *handle, char *text) { gflog_debug(GFARM_MSG_3000151, "sys_acl_free_text(ENOSYS): text %s", text); errno = ENOSYS; return (-1); } static int gfvfs_sys_acl_free_acl(vfs_handle_struct *handle, SMB_ACL_T posix_acl) { gflog_debug(GFARM_MSG_3000152, "sys_acl_free_acl"); SAFE_FREE(posix_acl); return (0); } static int gfvfs_sys_acl_free_qualifier(vfs_handle_struct *handle, void *qualifier, SMB_ACL_TAG_T tagtype) { gflog_debug(GFARM_MSG_3000153, "sys_acl_free_qualifier(ENOSYS)"); errno = ENOSYS; return (-1); } #endif /* unnecessary to hook */ static int gfarm_error_to_errno_for_xattr(gfarm_error_t e) { if (e == GFARM_ERR_NO_SUCH_OBJECT) return (ENODATA); else return (gfarm_error_to_errno(e)); } static ssize_t gfvfs_getxattr(vfs_handle_struct *handle, const char *path, const char *name, void *value, size_t size) { gfarm_error_t e; size_t s = size; const char *fullpath; gflog_debug(GFARM_MSG_3000154, "getxattr: path=%s, name=%s, size=%d", path, name, (int)size); fullpath = gfvfs_fullpath(handle, path); e = gfs_getxattr_cached(fullpath, name, value, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000155, "gfs_getxattr_cached", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } return (s); } static ssize_t gfvfs_lgetxattr(vfs_handle_struct *handle, const char *path, const char *name, void *value, size_t size) { gfarm_error_t e; size_t s = size; const char *fullpath; gflog_debug(GFARM_MSG_3000156, "lgetxattr: path=%s, name=%s", path, name); fullpath = gfvfs_fullpath(handle, path); e = gfs_lgetxattr_cached(fullpath, name, value, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000157, "gfs_lgetxattr_cached", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } return (s); } static ssize_t gfvfs_fgetxattr(vfs_handle_struct *handle, struct files_struct *fsp, const char *name, void *value, size_t size) { gfarm_error_t e; size_t s = size; gflog_debug(GFARM_MSG_3000158, "fgetxattr: fsp=%p, name=%s, size=%d", fsp, name, (int)size); e = gfs_fgetxattr((GFS_File)fsp->fh->gen_id, name, value, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000159, "gfs_fgetxattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } return (s); } static ssize_t gfvfs_listxattr(vfs_handle_struct *handle, const char *path, char *list, size_t size) { gfarm_error_t e; size_t s = size; const char *fullpath; gflog_debug(GFARM_MSG_3000160, "listxattr: path=%s, size=%d", path, (int)size); fullpath = gfvfs_fullpath(handle, path); e = gfs_listxattr(fullpath, list, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000161, "gfs_listxattr", e); errno = gfarm_error_to_errno(e); return (-1); } return (s); } static ssize_t gfvfs_llistxattr(vfs_handle_struct *handle, const char *path, char *list, size_t size) { gfarm_error_t e; size_t s = size; const char *fullpath; gflog_debug(GFARM_MSG_3000162, "llistxattr: path=%s, size=%d", path, (int)size); fullpath = gfvfs_fullpath(handle, path); e = gfs_llistxattr(fullpath, list, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000163, "gfs_llistxattr", e); errno = gfarm_error_to_errno(e); return (-1); } return (s); } static ssize_t gfvfs_flistxattr(vfs_handle_struct *handle, struct files_struct *fsp, char *list, size_t size) { gfarm_error_t e; size_t s = size; const char *fullpath; gflog_debug(GFARM_MSG_3000164, "flistxattr: fsp=%p, size=%d", fsp, (int)size); /* XXX gfs_flistxattr() */ fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); e = gfs_llistxattr(fullpath, list, &s); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000165, "gfs_llistxattr", e); errno = gfarm_error_to_errno(e); return (-1); } return (0); } static int gfvfs_removexattr(vfs_handle_struct *handle, const char *path, const char *name) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000166, "removexattr: path=%s, name=%s", path, name); fullpath = gfvfs_fullpath(handle, path); e = gfs_removexattr(fullpath, name); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000167, "gfs_removexattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_lremovexattr(vfs_handle_struct *handle, const char *path, const char *name) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000168, "lremovexattr: path=%s, name=%s", path, name); fullpath = gfvfs_fullpath(handle, path); e = gfs_lremovexattr(fullpath, name); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000169, "gfs_lremovexattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_fremovexattr(vfs_handle_struct *handle, struct files_struct *fsp, const char *name) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000170, "fremovexattr: fsp=%p, name=%s", fsp, name); e = gfs_fremovexattr((GFS_File)fsp->fh->gen_id, name); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000171, "gfs_fremovexattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int xattr_flags_to_gfarm(int flags) { int gflags; switch (flags) { case XATTR_CREATE: gflags = GFS_XATTR_CREATE; break; case XATTR_REPLACE: gflags = GFS_XATTR_REPLACE; break; default: gflags = flags; /* XXX */ break; } return (gflags); } static int gfvfs_setxattr(vfs_handle_struct *handle, const char *path, const char *name, const void *value, size_t size, int flags) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000172, "setxattr: path=%s, name=%s, size=%d, flags=%d", path, name, (int)size, flags); fullpath = gfvfs_fullpath(handle, path); e = gfs_setxattr(fullpath, name, value, size, xattr_flags_to_gfarm(flags)); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000173, "gfs_setxattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_lsetxattr(vfs_handle_struct *handle, const char *path, const char *name, const void *value, size_t size, int flags) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000174, "lsetxattr: path=%s, name=%s, size=%d, flags=%d", path, name, (int)size, flags); fullpath = gfvfs_fullpath(handle, path); e = gfs_lsetxattr(fullpath, name, value, size, xattr_flags_to_gfarm(flags)); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000175, "gfs_lsetxattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_fsetxattr(vfs_handle_struct *handle, struct files_struct *fsp, const char *name, const void *value, size_t size, int flags) { gfarm_error_t e; const char *fullpath; gflog_debug(GFARM_MSG_3000176, "fsetxattr: fsp=%p, name=%s, size=%d, flags=%d", fsp, name, (int)size, flags); e = gfs_fsetxattr((GFS_File)fsp->fh->gen_id, name, value, size, xattr_flags_to_gfarm(flags)); if (e != GFARM_ERR_NO_ERROR) { gfvfs_error(GFARM_MSG_3000177, "gfs_fsetxattr", e); errno = gfarm_error_to_errno_for_xattr(e); return (-1); } fullpath = gfvfs_fullpath(handle, fsp->fsp_name->base_name); gfs_stat_cache_purge(fullpath); uncache_parent(fullpath); return (0); } static int gfvfs_aio_read(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000178, "aio_read(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static int gfvfs_aio_write(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000179, "aio_write(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static ssize_t gfvfs_aio_return_fn(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000180, "aio_return_fn(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static int gfvfs_aio_cancel(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000181, "aio_cancel(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static int gfvfs_aio_error_fn(struct vfs_handle_struct *handle, struct files_struct *fsp, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000182, "aio_error_fn(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (-1); } static int gfvfs_aio_fsync(struct vfs_handle_struct *handle, struct files_struct *fsp, int op, SMB_STRUCT_AIOCB *aiocb) { gflog_debug(GFARM_MSG_3000183, "aio_fsync(ENOSYS): fsp=%p, op=%d", fsp, op); errno = ENOSYS; return (-1); } static int gfvfs_aio_suspend(struct vfs_handle_struct *handle, struct files_struct *fsp, const SMB_STRUCT_AIOCB * const aiocb[], int n, const struct timespec *ts) { gflog_debug(GFARM_MSG_3000184, "aio_suspend(ENOSYS): fsp=%p, n_cb=%d", fsp, n); errno = ENOSYS; return (-1); } static bool gfvfs_aio_force(struct vfs_handle_struct *handle, struct files_struct *fsp) { gflog_debug(GFARM_MSG_3000185, "aio_force(ENOSYS): fsp=%p", fsp); errno = ENOSYS; return (false); } static bool gfvfs_is_offline(struct vfs_handle_struct *handle, const struct smb_filename *fname, SMB_STRUCT_STAT *sbuf) { gflog_debug(GFARM_MSG_3000186, "is_offline(ENOSYS): path=%s%s", fname->base_name, fname->stream_name != NULL ? fname->stream_name : ""); errno = ENOSYS; return (false); } static int gfvfs_set_offline(struct vfs_handle_struct *handle, const struct smb_filename *fname) { gflog_debug(GFARM_MSG_3000187, "set_offline(ENOSYS): path=%s%s", fname->base_name, fname->stream_name != NULL ? fname->stream_name : ""); errno = ENOSYS; return (false); } /* VFS operations structure */ struct vfs_fn_pointers vfs_gfarm_fns = { /* Disk operations */ .connect_fn = gfvfs_connect, .disconnect = gfvfs_disconnect, .disk_free = gfvfs_disk_free, .get_quota = gfvfs_get_quota, /* ENOSYS */ .set_quota = gfvfs_set_quota, /* ENOSYS */ .get_shadow_copy_data = gfvfs_get_shadow_copy_data, /* ENOSYS */ .statvfs = gfvfs_statvfs, .fs_capabilities = gfvfs_fs_capabilities, /* noop */ /* Directory operations */ .opendir = gfvfs_opendir, .fdopendir = gfvfs_fdopendir, /* ENOSYS, it's OK */ .readdir = gfvfs_readdir, .seekdir = gfvfs_seekdir, .telldir = gfvfs_telldir, .rewind_dir = gfvfs_rewind_dir, .mkdir = gfvfs_mkdir, .rmdir = gfvfs_rmdir, .closedir = gfvfs_closedir, .init_search_op = gfvfs_init_search_op, /* noop */ /* File operations */ .open_fn = gfvfs_open, .create_file = gfvfs_create_file, /* transparent */ .close_fn = gfvfs_close_fn, .vfs_read = gfvfs_vfs_read, .pread = gfvfs_pread, .write = gfvfs_write, .pwrite = gfvfs_pwrite, .lseek = gfvfs_lseek, .sendfile = gfvfs_sendfile, /* ENOSYS */ .recvfile = gfvfs_recvfile, /* ENOSYS */ .rename = gfvfs_rename, .fsync = gfvfs_fsync, .stat = gfvfs_stat, .fstat = gfvfs_fstat, .lstat = gfvfs_lstat, .get_alloc_size = gfvfs_get_alloc_size, .unlink = gfvfs_unlink, .chmod = gfvfs_chmod, .fchmod = gfvfs_fchmod, /* ENOSYS */ .chown = gfvfs_chown, /* ENOSYS */ .fchown = gfvfs_fchown, /* ENOSYS */ .lchown = gfvfs_lchown, /* ENOSYS */ .chdir = gfvfs_chdir, .getwd = gfvfs_getwd, .ntimes = gfvfs_ntimes, .ftruncate = gfvfs_ftruncate, .fallocate = gfvfs_fallocate, /* ENOSYS */ .lock = gfvfs_lock, /* ENOSYS */ .kernel_flock = gfvfs_kernel_flock, /* ignored */ .linux_setlease = gfvfs_linux_setlease, /* ENOSYS */ .getlock = gfvfs_getlock, /* ENOSYS */ .symlink = gfvfs_symlink, .vfs_readlink = gfvfs_vfs_readlink, .link = gfvfs_link, .mknod = gfvfs_mknod, /* incomplete */ .realpath = gfvfs_realpath, .notify_watch = gfvfs_notify_watch, /* ENOSYS */ .chflags = gfvfs_chflags, /* ENOSYS */ .file_id_create = gfvfs_file_id_create, .streaminfo = gfvfs_streaminfo, /* transparent */ .get_real_filename = gfvfs_get_real_filename, /* EOPNOTSUPP */ .connectpath = gfvfs_connectpath, /* transparent */ .brl_lock_windows = gfvfs_brl_lock_windows, /* transparent */ .brl_unlock_windows = gfvfs_brl_unlock_windows, /* transparent */ .brl_cancel_windows = gfvfs_brl_cancel_windows, /* transparent */ .strict_lock = gfvfs_strict_lock, /* transparent */ .strict_unlock = gfvfs_strict_unlock, /* transparent */ .translate_name = gfvfs_translate_name, /* NONE_MAPPED */ /* NT ACL operations */ .fget_nt_acl = gfvfs_fget_nt_acl, /* transparent */ .get_nt_acl = gfvfs_get_nt_acl, /* transparent */ .fset_nt_acl = gfvfs_fset_nt_acl, /* transparent */ /* POSIX ACL operations */ .chmod_acl = gfvfs_chmod_acl, .fchmod_acl = gfvfs_fchmod_acl, .sys_acl_get_file = gfvfs_sys_acl_get_file, .sys_acl_get_fd = gfvfs_sys_acl_get_fd, /* ENOSYS */ .sys_acl_set_file = gfvfs_sys_acl_set_file, .sys_acl_set_fd = gfvfs_sys_acl_set_fd, /* ENOSYS */ .sys_acl_delete_def_file = gfvfs_sys_acl_delete_def_file, #if 0 /* unnecessary to hook */ .sys_acl_get_entry = gfvfs_sys_acl_get_entry, .sys_acl_get_tag_type = gfvfs_sys_acl_get_tag_type, .sys_acl_get_permset = gfvfs_sys_acl_get_permset, .sys_acl_get_qualifier = gfvfs_sys_acl_get_qualifier, .sys_acl_clear_perms = gfvfs_sys_acl_clear_perms, .sys_acl_add_perm = gfvfs_sys_acl_add_perm, .sys_acl_to_text = gfvfs_sys_acl_to_text, .sys_acl_init = gfvfs_sys_acl_init, .sys_acl_create_entry = gfvfs_sys_acl_create_entry, .sys_acl_set_tag_type = gfvfs_sys_acl_set_tag_type, .sys_acl_set_qualifier = gfvfs_sys_acl_set_qualifier, .sys_acl_set_permset = gfvfs_sys_acl_set_permset, .sys_acl_valid = gfvfs_sys_acl_valid, .sys_acl_get_perm = gfvfs_sys_acl_get_perm, .sys_acl_free_text = gfvfs_sys_acl_free_text, .sys_acl_free_acl = gfvfs_sys_acl_free_acl, .sys_acl_free_qualifier = gfvfs_sys_acl_free_qualifier, #endif /* unnecessary to hook */ /* EA operations */ .getxattr = gfvfs_getxattr, .lgetxattr = gfvfs_lgetxattr, .fgetxattr = gfvfs_fgetxattr, .listxattr = gfvfs_listxattr, .llistxattr = gfvfs_llistxattr, .flistxattr = gfvfs_flistxattr, .removexattr = gfvfs_removexattr, .lremovexattr = gfvfs_lremovexattr, .fremovexattr = gfvfs_fremovexattr, .setxattr = gfvfs_setxattr, .lsetxattr = gfvfs_lsetxattr, .fsetxattr = gfvfs_fsetxattr, /* aio operations */ /* ENOSYS */ .aio_read = gfvfs_aio_read, .aio_write = gfvfs_aio_write, .aio_return_fn = gfvfs_aio_return_fn, .aio_cancel = gfvfs_aio_cancel, .aio_error_fn = gfvfs_aio_error_fn, .aio_fsync = gfvfs_aio_fsync, .aio_suspend = gfvfs_aio_suspend, .aio_force = gfvfs_aio_force, /* offline operations */ /* ENOSYS */ .is_offline = gfvfs_is_offline, .set_offline = gfvfs_set_offline }; NTSTATUS init_samba_module(void) { return (smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "gfarm", &vfs_gfarm_fns)); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/failure_test_scripts/FT3-2-2-1_observer_network_down #! /bin/sh ###################################################################### TESTID="FT3-2-2-1" CATEGORY="N point accident" SECTION="network accident" TITLE="observer network down" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $zabbix1_CTRL_ADDRESS sudo $IFDOWN_PATH $zabbix1_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "ifdown $zabbix1_GFARM_IF on $zabbix1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "$gfmd1 is unreachable" \ "$gfmd2 is unreachable" \ "$gfmd3 is unreachable" \ "$gfsd1 is unreachable" \ "$gfsd2 is unreachable" \ "$client1 is unreachable" \ "$client2 is unreachable" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $zabbix1_CTRL_ADDRESS sudo $IFUP_PATH $zabbix1_GFARM_IF ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_pgsql.sh.in #!/bin/sh # database DB_HOST=127.0.0.1 DB_NAME=gfarm DB_PORT=@GFARM_DB_PORT@ DB_USER=@GFARM_DB_USER@ PGPASSWORD=@GFARM_DB_PASSWORD@ export PGPASSWORD # exec check command RESULT=-1 case "$1" in version) RESULT=`psql --version|head -n1` ;; process) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -w -c \ "select sum(numbackends) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; commit) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -w -c \ "select sum(xact_commit) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; rollback) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -w -c \ "select sum(xact_rollback) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; *) RESULT=-1 esac if [ $? != 0 ]; then RESULT=-1 fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_3_rc1/lib/gfs_hook/hooks_subr.c /* * $Id$ */ #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" #define MAX_GFS_FILE_BUF 2048 struct _gfs_file_descriptor { int refcount; unsigned char d_type; /* file types in <gfarm/gfs.h> */ union { GFS_File f; struct { GFS_Dir dir; int readcount; struct gfs_dirent *suspended; struct gfs_stat gst; char *canonical_path; /* for __fchdir() hook */ } *d; } u; }; static struct _gfs_file_descriptor *_gfs_file_buf[MAX_GFS_FILE_BUF]; void gfs_hook_not_initialized(void) { static int printed = 0; if (!printed) { printed = 1; fprintf(stderr, "fatal error: gfarm_initialize() isn't called\n"); } } /* * gfs_file_buf management */ int gfs_hook_insert_gfs_file(GFS_File gf) { int fd, save_errno; struct stat st; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_file: %p\n", gf)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = gfs_pio_fileno(gf); if (fstat(fd, &st) == -1) { save_errno = errno; gfs_pio_close(gf); errno = save_errno; return (-1); } if (S_ISREG(st.st_mode)) fd = dup(fd); else /* don't return a socket, to make select(2) work with this fd */ fd = open("/dev/null", O_RDWR); if (fd == -1) { save_errno = errno; gfs_pio_close(gf); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_pio_close(gf); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_pio_close(gf); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_REG; _gfs_file_buf[fd]->u.f = gf; return (fd); } int gfs_hook_insert_gfs_dir(GFS_Dir dir, char *url) { int fd, save_errno; char *e; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_dir: %p\n", dir)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = open("/dev/null", O_RDONLY); if (fd == -1) { save_errno = errno; gfs_closedir(dir); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_closedir(dir); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_closedir(dir); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->u.d = malloc(sizeof(*_gfs_file_buf[fd]->u.d)); if (_gfs_file_buf[fd]->u.d == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_DIR; _gfs_file_buf[fd]->u.d->dir = dir; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; e = gfs_stat(url, &_gfs_file_buf[fd]->u.d->gst); if (e != NULL) return (-1); e = gfarm_canonical_path(gfarm_url_prefix_skip(url), &_gfs_file_buf[fd]->u.d->canonical_path); if (e != NULL) return (-1); return (fd); } unsigned char gfs_hook_gfs_file_type(int fd) { return (_gfs_file_buf[fd]->d_type); } char * gfs_hook_clear_gfs_file(int fd) { GFS_File gf; char *e = NULL; _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: %d\n", fd)); gf = gfs_hook_is_open(fd); if (--_gfs_file_buf[fd]->refcount > 0) { /* fd is duplicated, skip closing the file. */ _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: skipped\n")); } else { if (gfs_hook_gfs_file_type(fd) == GFS_DT_REG) { e = gfs_pio_close(gf); } else if (gfs_hook_gfs_file_type(fd) == GFS_DT_DIR) { _gfs_file_buf[fd]->u.d->dir = NULL; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; gfs_stat_free(&_gfs_file_buf[fd]->u.d->gst); free(_gfs_file_buf[fd]->u.d->canonical_path); free(_gfs_file_buf[fd]->u.d); e = gfs_closedir((GFS_Dir)gf); } free(_gfs_file_buf[fd]); } __syscall_close(fd); _gfs_file_buf[fd] = NULL; return (e); } struct _gfs_file_descriptor *gfs_hook_dup_descriptor(int fd) { if (gfs_hook_is_open(fd) == NULL) return (NULL); ++_gfs_file_buf[fd]->refcount; return (_gfs_file_buf[fd]); } void gfs_hook_set_descriptor(int fd, struct _gfs_file_descriptor *d) { if (gfs_hook_is_open(fd) != NULL) gfs_hook_clear_gfs_file(fd); _gfs_file_buf[fd] = d; } #if 0 int gfs_hook_dup_filedes(int oldfd, int newfd) { _gfs_hook_debug( fprintf(stderr, "GFS: dpu_filedes: %d, %d\n", oldfd, newfd)); #if 0 if (_gfs_file_buf[oldfd] == _gfs_file_buf[newfd]) return (newfd); #endif _gfs_file_buf[newfd] = _gfs_file_buf[oldfd]; } return (newfd); } #endif /* printf and puts should not be put into the following function. */ void * gfs_hook_is_open(int fd) { if (fd < 0 || fd >= MAX_GFS_FILE_BUF) return (NULL); if (_gfs_file_buf[fd] == NULL) return (NULL); switch (gfs_hook_gfs_file_type(fd)) { case GFS_DT_REG: return (_gfs_file_buf[fd]->u.f); case GFS_DT_DIR: return (_gfs_file_buf[fd]->u.d->dir); default: return (NULL); } } void gfs_hook_inc_readcount(int fd) { _gfs_hook_debug( fprintf(stderr, "GFS: inc_readount: %d\n", fd)); ++_gfs_file_buf[fd]->u.d->readcount; } int gfs_hook_is_read(int fd) { return (_gfs_file_buf[fd]->u.d->readcount > 0); } void gfs_hook_set_suspended_gfs_dirent(int fd, struct gfs_dirent *entry) { _gfs_file_buf[fd]->u.d->suspended = entry; } struct gfs_dirent * gfs_hook_get_suspended_gfs_dirent(int fd) { return (_gfs_file_buf[fd]->u.d->suspended); } struct gfs_stat * gfs_hook_get_gfs_stat(int fd) { return (&_gfs_file_buf[fd]->u.d->gst); } char * gfs_hook_get_gfs_canonical_path(int fd) { return (_gfs_file_buf[fd]->u.d->canonical_path); } /* * Check whether pathname is gfarm url or not. * * Gfarm URL: gfarm:[:section:]pathname * * It is necessary to free the memory space for *url. * Also, it's necessary to free the memory space for *secp, * if *secp is not NULL. */ extern int gfs_hook_cwd_is_gfarm; static char *received_prefix = NULL; static int set_received_prefix(const char *path) { char *end, *p; int len; if ((end = strchr(path, ':')) == NULL) end = strchr(path, '@'); len = end - path + 1; p = malloc(len + 1); if (p == NULL) return (0); /* XXX - should return ENOMEM */ if (received_prefix != NULL) free(received_prefix); received_prefix = p; strncpy(received_prefix, path, len); received_prefix[len] = '\0'; return (1); } int gfs_hook_is_url(const char *path, char **urlp, char **secp) { static char prefix[] = "gfarm:"; int sizeof_prefix = sizeof(prefix); const char *path_save; int add_slash = 0; /* * ROOT patch: * 'gfarm@' is also considered as a Gfarm URL */ static char gfarm_url_prefix_for_root[] = "gfarm@"; *secp = NULL; /* * Objectivity patch: * '/gfarm:' is also considered as a Gfarm URL * * In this case, '/gfarm:' is considered to be the root * directory in Gfarm file system instead of a current * working directory. */ path_save = path; if (*path == '/') { ++path; add_slash = 1; } if (gfarm_is_url(path) || /* ROOT patch */ memcmp(path, gfarm_url_prefix_for_root, sizeof(gfarm_url_prefix_for_root) - 1) == 0) { if (!gfarm_initialized && gfs_hook_initialize() != NULL) { gfs_hook_not_initialized(); return (0); /* don't perform gfarm operation */ } /* * extension for accessing individual sections * gfarm::section:pathname */ if (path[sizeof_prefix - 1] == ':') { const char *p = path + sizeof_prefix; int secsize = strcspn(p, "/:"); int urlsize; if (p[secsize] != ':') return (0); /* gfarm::foo/:bar or gfarm::foo */ /* 'path' is an absolute path. */ if (p[secsize + 1] == '/' || p[secsize + 1] == '~') add_slash = 0; urlsize = sizeof_prefix - 1 + strlen(p + secsize + 1); *urlp = malloc(urlsize + 1 + add_slash); *secp = malloc(secsize + 1); if (*urlp == NULL || *secp == NULL) { if (*urlp != NULL) free(*urlp); if (*secp != NULL) free(*secp); return (0); /* XXX - should return ENOMEM */ } memcpy(*urlp, prefix, sizeof_prefix - 1); if (add_slash) (*urlp)[sizeof_prefix - 1] = '/'; strcpy(*urlp + sizeof_prefix - 1 + add_slash, p + secsize + 1); memcpy(*secp, p, secsize); (*secp)[secsize] = '\0'; /* * This case needs to free memory space of * both *urlp and *secp. */ } else { /* 'path' is an absolute path. */ if (path[sizeof_prefix - 1] == '/' || path[sizeof_prefix - 1] == '~') add_slash = 0; *urlp = malloc(strlen(path) + 1 + add_slash); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ /* * the reason why we don't just call strcpy(*url, path) * is because the path may be "gfarm@path/name". * (ROOT patch) */ memcpy(*urlp, prefix, sizeof_prefix - 1); if (add_slash) (*urlp)[sizeof_prefix - 1] = '/'; strcpy(*urlp + sizeof_prefix - 1 + add_slash, path + sizeof_prefix - 1); } if (!set_received_prefix(path_save)) return (0); return (1); } if (gfs_hook_cwd_is_gfarm && *path_save != '/') { *urlp = malloc(strlen(prefix) + strlen(path_save) + 1); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ memcpy(*urlp, prefix, sizeof_prefix - 1); strcpy(*urlp + sizeof_prefix - 1, path_save); return (1); } return (0); } char * gfs_hook_get_prefix(char *buf, size_t size) { if (received_prefix == NULL) return GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING; if (size < strlen(received_prefix)) return GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE; strcpy(buf, received_prefix); return (NULL); } /* * default file view manipulation */ enum gfs_hook_file_view _gfs_hook_default_view = local_view; int _gfs_hook_index = 0; int _gfs_hook_num_fragments = GFARM_FILE_DONTCARE; void gfs_hook_set_default_view_local() { _gfs_hook_default_view = local_view; } void gfs_hook_set_default_view_index(int index, int nfrags) { _gfs_hook_default_view = index_view; _gfs_hook_index = index; _gfs_hook_num_fragments = nfrags; } void gfs_hook_set_default_view_global() { _gfs_hook_default_view = global_view; } char * gfs_hook_set_view_local(int filedes, int flag) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_local(gf, flag)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_index(int filedes, int nfrags, int index, char *host, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_index(gf, nfrags, index, host, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_global(int filedes, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_global(gf, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_global: %s\n", e)); return e; } return NULL; } <file_sep>/gfarm_zabbix/trunk/src/editor/index.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>'gfarm2.conf' editor</title> <style type="text/css" media="all"> textarea { font-family: monospace; border-style: solid; border-color: black; border-width: 1px; padding: 8px; background-color: #c0c0f0; } td.caption { font-weight: bold; } td.button { text-align: right; } td.footer { text-align: right; } </style> </head> <body> <h1>'gfarm2.conf' editor</h1> <?php include('./common.php'); ?> <table> <thead> <tr> <td class="caption">Current 'gfarm2.conf' file: <td class="button"><a href="download.php">[download]</a> <a href="edit.php">[edit]</a> </tr> </thead> <tbody> <tr> <td class="view" colspan="2"> <textarea name="conf" cols="80" rows="15" readonly> <?php $lines = read_gfarm2_conf_file(); if (count($lines) > 0 && !ereg('^# Error:', $lines[0])) { if ($stat = stat($gfarm2_conf_file)) { printf("# This file was edited on: %s\n", strftime("%Y-%m-%d %H:%M:%S", $stat[9])); } } foreach ($lines as $line) { printf("%s\n", htmlspecialchars($line)); } print("\n"); $lines = read_gfmdlist_file(); if (count($lines) > 0 && !ereg('^# Error:', $lines[0])) { if ($stat = stat($gfmdlist_file)) { printf("# The 'metadb_server_list' line was updated on: %s\n", strftime("%Y-%m-%d %H:%M:%S", $stat[9])); } } foreach ($lines as $line) { printf("%s\n", htmlspecialchars($line)); } ?> </textarea> </tr> </tbody> <tr> <td> <td class="footer"> </table> </body> </html> <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_iostat.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command RESULT=-1 case "$1" in read) RESULT=`iostat -m | awk '{if ($1 == "'$DEVICE'") print $3};'` ;; write) RESULT=`iostat -m | awk '{if ($1 == "'$DEVICE'") print $4};'` ;; total_read) RESULT=`iostat -m | awk '{if ($1 == "'$DEVICE'") print $5};'` ;; total_write) RESULT=`iostat -m | awk '{if ($1 == "'$DEVICE'") print $6};'` ;; *) RESULT=-1 esac if [ $? != 0 ]; then RESULT=-1 fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/gfarm/gfs_proto.c #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "gfs_proto.h" int gfs_proto_error_to_errno_map[] = { 0, EPERM, ENOENT, ESRCH, EINTR, EIO, ENXIO, E2BIG, ENOEXEC, EBADF, EDEADLK, ENOMEM, EACCES, EFAULT, EBUSY, EEXIST, ENOTDIR, EISDIR, EINVAL, /* real EINVAL, should be first EINVAL entry for first match */ ENFILE, EMFILE, ETXTBSY, EFBIG, ENOSPC, ESPIPE, EROFS, EPIPE, EAGAIN, EOPNOTSUPP, ECONNREFUSED, ELOOP, ENAMETOOLONG, EDQUOT, ESTALE, ENOLCK, ENOSYS, #ifdef EAUTH /* BSD */ EAUTH, #else EPERM, #endif #ifdef ETIME /* Linux */ ETIME, #else EINVAL, /* as GFS_ERROR_UNKNOWN */ #endif #ifdef EPROTO /* SVR4 and Linux */ EPROTO, #else EPROTONOSUPPORT, #endif EPROTONOSUPPORT, EINVAL /* as GFS_ERROR_UNKNOWN */ }; /* * convert machine independent error number to error string. * (errno may be different between platforms) */ char * gfs_proto_error_string(enum gfs_proto_error err) { /* * The reason we treat somes errors as special cases * is that those errors may not have corresponding errno on some * platforms. * (So gfs_proto_error_to_errno_map[] cannot convert such errors). */ return (err == GFS_ERROR_AUTH ? GFARM_ERR_AUTHENTICATION : err == GFS_ERROR_EXPIRED ? GFARM_ERR_EXPIRED : err == GFS_ERROR_PROTO ? GFARM_ERR_PROTOCOL : err == GFS_ERROR_PROTONOSUPPORT ? GFARM_ERR_PROTOCOL_NOT_SUPPORTED: err >= GFS_ERROR_UNKNOWN ? GFARM_ERR_UNKNOWN : gfarm_errno_to_error(gfs_proto_error_to_errno_map[err])); } /* * convert error string to machine independent error number. * (errno may be different between platforms) * * See also gfarm_errno_error_map[] in error.c. */ enum gfs_proto_error gfs_string_to_proto_error(char *e) { /* * The reason we treat somes errors as special cases * is that those errors may not have corresponding errno on some * platforms. * (So gfs_errno_to_proto_error() cannot convert such errors). */ return (e == GFARM_ERR_AUTHENTICATION ? GFS_ERROR_AUTH : e == GFARM_ERR_EXPIRED ? GFS_ERROR_EXPIRED : e == GFARM_ERR_PROTOCOL ? GFS_ERROR_PROTO : e == GFARM_ERR_PROTOCOL_NOT_SUPPORTED ? GFS_ERROR_PROTONOSUPPORT : e == GFARM_ERR_UNKNOWN ? GFS_ERROR_UNKNOWN : gfs_errno_to_proto_error(gfarm_error_to_errno(e))); } #ifndef ELAST /* sys_nerr isn't constant */ #define ELAST 127 #endif enum gfs_proto_error gfs_errno_to_proto_error_map[ELAST + 1]; int gfs_errno_to_proto_error_initialized; int gfs_errno_to_proto_error_table_overflow; void gfs_errno_to_proto_error_initialize(void) { enum gfs_proto_error err; int unix_errno; if (gfs_errno_to_proto_error_initialized) return; /* sanity */ if (GFARM_ARRAY_LENGTH(gfs_proto_error_to_errno_map) != GFS_ERROR_NUMBER) abort(); gfs_errno_to_proto_error_initialized = 1; for (err = GFS_ERROR_NOERROR; err < GFARM_ARRAY_LENGTH(gfs_proto_error_to_errno_map); err++) { unix_errno = gfs_proto_error_to_errno_map[err]; if (unix_errno > ELAST) { gfs_errno_to_proto_error_table_overflow = 1; } else if (gfs_errno_to_proto_error_map[unix_errno] == 0) { /* make sure to be first match */ gfs_errno_to_proto_error_map[unix_errno] = err; } } } /* * convert errno to machine independent error number, * because errno may be different between platforms. */ enum gfs_proto_error gfs_errno_to_proto_error(int unix_errno) { enum gfs_proto_error err; if (!gfs_errno_to_proto_error_initialized) gfs_errno_to_proto_error_initialize(); if (unix_errno <= ELAST) { err = gfs_errno_to_proto_error_map[unix_errno]; if (err != GFS_ERROR_NOERROR) /* i.e. != 0 */ return (err); else if (unix_errno == 0) return (GFS_ERROR_NOERROR); else return (GFS_ERROR_UNKNOWN); /* errno not mapped */ } if (gfs_errno_to_proto_error_table_overflow) { for (err = GFS_ERROR_NOERROR; err < GFS_ERROR_NUMBER; err++) if (unix_errno == gfs_proto_error_to_errno_map[err]) return (err); } return (GFS_ERROR_UNKNOWN); /* errno not mapped */ } /* * Not really public interface, * but common routine called from both client and server. */ int gfs_open_flags_localize(int open_flags) { int local_flags; switch (open_flags & GFARM_FILE_ACCMODE) { case GFARM_FILE_RDONLY: local_flags = O_RDONLY; break; case GFARM_FILE_WRONLY: local_flags = O_WRONLY; break; case GFARM_FILE_RDWR: local_flags = O_RDWR; break; default: return (-1); } if ((open_flags & GFARM_FILE_CREATE) != 0) local_flags |= O_CREAT; if ((open_flags & GFARM_FILE_TRUNC) != 0) local_flags |= O_TRUNC; if ((open_flags & GFARM_FILE_APPEND) != 0) local_flags |= O_APPEND; return (local_flags); } /* * Not really public interface, * but common routine called from both client and server. */ int gfs_digest_calculate_local(int fd, char *buffer, size_t buffer_size, const EVP_MD *md_type, EVP_MD_CTX *md_ctx, size_t *md_lenp, unsigned char *md_value, file_offset_t *filesizep) { int size; file_offset_t off = 0; unsigned int len; if (lseek(fd, (off_t)0, 0) == -1) return (errno); EVP_DigestInit(md_ctx, md_type); while ((size = read(fd, buffer, buffer_size)) > 0) { EVP_DigestUpdate(md_ctx, buffer, size); off += size; } EVP_DigestFinal(md_ctx, md_value, &len); *md_lenp = len; *filesizep = off; return (size == -1 ? errno : 0); } <file_sep>/gfarm_mpiio/trunk/ad_gfarm/ad_gfarm_write.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" #include "adioi.h" #include "adio_extern.h" void ADIOI_GFARM_Write(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { int myrank, nprocs, datatype_size; int err; ADIO_Offset len; gfarm_off_t result; int g_np; ADIOI_GFARM_headerInf *ghi; GFS_File gfp; MPI_Type_size(datatype, &datatype_size); len = (ADIO_Offset)datatype_size * (ADIO_Offset)count; ADIOI_Assert(len == (unsigned int) len); /* read takes an unsigned int parm */ *error_code = MPI_SUCCESS; MPI_Type_size(datatype, &datatype_size); #ifdef GFARM_DEBUG MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_Write called on %s\n", myrank, nprocs, fd->filename); FPRINTF(stdout, "[%d/%d] writing (buf = %p, loc = %lld, sz = %lld)\n", myrank, nprocs, buf, (long long) offset, (long long)datatype_size * (long long)count); #endif ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); if(ghi->header_flag == 1 && ghi->gfarm_view_flag == 0){ gfarm_write_header(fd, buf, count, datatype, file_ptr_type, offset, status, error_code); return; }else{ gfp = ghi->gfp[ghi->gfp_index]; } if (file_ptr_type == ADIO_INDIVIDUAL) { offset = fd->fp_ind; } if (fd->fp_sys_posn != offset) { if(ghi->gfarm_view_flag != 1 && ghi->gfarm_view_flag != 2){ err = lseek(fd->fd_sys, offset, SEEK_SET); }else{ gfs_pio_seek(gfp, (gfarm_off_t)offset, GFARM_SEEK_SET, &result); #ifdef GFARM_DEBUG printf("[%d/%d] gfs_pio_seek:gfp=%d\n", myrank, nprocs, ghi->gfp[ghi->gfp_index]); printf("[%d/%d] write_contig seek result=%d\n", myrank, nprocs, result); #endif } } if(ghi->gfarm_view_flag != 1 && ghi->gfarm_view_flag != 2){ err = write(fd->fd_sys, buf, (unsigned int)len); }else{ err = gfs_pio_write(gfp, buf, (int)len, &g_np); #ifdef GFARM_DEBUG printf("[%d/%d] gfs_pio_write:gfp=%d\n", myrank, nprocs, ghi->gfp[ghi->gfp_index]); printf("[%d/%d] write_contig write err=%d, g_np=%lld\n", myrank, nprocs, err, g_np); #endif } fd->fp_sys_posn = offset + g_np; if (file_ptr_type == ADIO_INDIVIDUAL) { fd->fp_ind += g_np; } #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, datatype, datatype_size * count); #endif } /*---------------------------------------*/ // // //header file // // /*--------------------------------------*/ void gfarm_write_header(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { int myrank, nprocs, datatype_size; int err; ADIO_Offset len; gfarm_off_t result; int g_np; ADIOI_GFARM_headerInf *ghi; MPI_Type_size(datatype, &datatype_size); len = (ADIO_Offset)datatype_size * (ADIO_Offset)count; ADIOI_Assert(len == (unsigned int) len); /* read takes an unsigned int parm */ *error_code = MPI_SUCCESS; MPI_Type_size(datatype, &datatype_size); #ifdef GFARM_DEBUG MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); FPRINTF(stdout, "[%d/%d] gfarm_write_header called on %s\n", myrank, nprocs, fd->filename); FPRINTF(stdout, "[%d/%d] writing (buf = %p, loc = %lld, sz = %lld)\n", myrank, nprocs, buf, (long long) offset, (long long)datatype_size * (long long)count); #endif ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); if (file_ptr_type == ADIO_INDIVIDUAL) { offset = fd->fp_ind; } if (fd->fp_sys_posn != offset) { err = gfs_pio_seek(ghi->header_gfp, (gfarm_off_t)offset, GFARM_SEEK_SET, &result); #ifdef GFARM_DEBUG printf("[%d/%d] gfs_pio_header:gfp=%d\n", myrank, nprocs, ghi->header_gfp); printf("[%d/%d] write_header seek err=%d, result=%d\n", myrank, nprocs, err, result); #endif } err = gfs_pio_write(ghi->header_gfp, buf, (int)len, &g_np); #ifdef GFARM_DEBUG printf("[%d/%d] gfs_pio_write:gfp=%d\n", myrank, nprocs, ghi->header_gfp); printf("[%d/%d] write_contig write err=%d, g_np=%lld\n", myrank, nprocs, err, g_np); #endif fd->fp_sys_posn = offset + g_np; if (file_ptr_type == ADIO_INDIVIDUAL) { fd->fp_ind += g_np; } #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, datatype, datatype_size * count); #endif } /*---------------------------------------*/ // // // // // /*--------------------------------------*/ void ADIOI_GFARM_WriteContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { ADIOI_Flatlist_node *flat_file; ADIO_Offset blocklen_sum, gfarm_offset; unsigned filetype_size; MPI_Aint filetype_extent; int i, j, nprocs, myrank; int filetype_count; ADIO_Offset **blocklens, **indices; ADIO_Offset tmp_offset; ADIO_Offset tmp_disp; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); #ifdef GFARM_DEBUG MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); printf("[%d/%d] Testfs_WriteContig.ghi->header_flag = %d, ghi->gfarm_view_flag = %d\n", myrank, nprocs, ghi->header_flag, ghi->gfarm_view_flag); #endif if(ghi->header_flag == 1 && ghi->gfarm_view_flag == 0){ #ifdef GFARM_DEBUG printf("[%d/%d] call write header\n", myrank, nprocs); #endif gfarm_write_header(fd, buf, count, datatype, file_ptr_type, offset, status, error_code); return; } if(ghi->count == 0){ #ifdef GFARM_DEBUG printf("[%d/%d] call ADIOI_GFARM_Write\n", myrank, nprocs); #endif ADIOI_GFARM_Write(fd, buf, count, datatype, file_ptr_type, offset, status, error_code); return; } /* printf("[%d/%d] blocklen\n", myrank, nprocs); for(i=0;i<Gfarm_headerlist->count[myrank];i++){ printf("%d, ", Gfarm_headerlist->blocklens[myrank][i]); } printf("\n[%d/%d] indices\n", myrank, nprocs, count); for(i=0;i<Gfarm_headerlist->count[myrank];i++){ printf("%d, ", Gfarm_headerlist->indices[myrank][i]); } printf("\n"); */ MPI_Type_extent(fd->filetype, &filetype_extent); MPI_Type_size(fd->filetype, &filetype_size); flat_file = ADIOI_Flatlist; while (flat_file->type != fd->filetype) flat_file = flat_file->next; tmp_disp = fd->disp; tmp_offset = offset - tmp_disp; filetype_count = tmp_offset/filetype_extent; tmp_offset = tmp_offset - (ADIO_Offset)(filetype_count * filetype_extent); //printf("[%d/%d] filetype extent = %lld \n", myrank, nprocs, filetype_extent); //printf("[%d/%d] buf size = %d \n", myrank, nprocs, count); blocklen_sum = 0; for(j=0;j<flat_file->count;j++){ if(tmp_offset == flat_file->indices[j]){ break; }else if(tmp_offset < flat_file->indices[j] + flat_file->blocklens[j] && tmp_offset > flat_file->indices[j]){ blocklen_sum += tmp_offset - flat_file->indices[j]; break; }else{ blocklen_sum += flat_file->blocklens[j]; } } gfarm_offset = (ADIO_Offset)(filetype_size * filetype_count) + (blocklen_sum); #ifdef GFARM_DEBUG printf("%lld\n", tmp_offset); printf("[%d/%d] global to local offset=%lld -> %lld\n", myrank, nprocs, offset, gfarm_offset); #endif ADIOI_GFARM_Write(fd, buf, count, datatype, file_ptr_type, gfarm_offset, status, error_code); return; } void ADIOI_GFARM_WriteStrided(ADIO_File fd, void *buf, int count, MPI_Datatype buftype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { /* offset is in units of etype relative to the filetype. */ ADIOI_Flatlist_node *flat_buf, *flat_file; /* bwr == buffer write; fwr == file write */ ADIO_Offset bwr_size, fwr_size=0, sum, size_in_filetype; int b_index; unsigned bufsize; int n_etypes_in_filetype; ADIO_Offset size, n_filetypes, etype_in_filetype; ADIO_Offset abs_off_in_filetype=0, req_len; int filetype_size, etype_size, buftype_size; MPI_Aint filetype_extent, buftype_extent; int buf_count, buftype_is_contig, filetype_is_contig; ADIO_Offset userbuf_off; ADIO_Offset off, req_off, disp, end_offset=0, start_off; ADIO_Status status1; int ft_count, gfarm_i, gfarm_j; unsigned rem_size, tmp_rem_size; ADIOI_GFARM_headerInf *ghi; ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); int nprocs, myrank; void* gfarm_tmp_buf; *error_code = MPI_SUCCESS; /* changed below if error */ ADIOI_Datatype_iscontig(buftype, &buftype_is_contig); ADIOI_Datatype_iscontig(fd->filetype, &filetype_is_contig); MPI_Type_size(fd->filetype, &filetype_size); if ( ! filetype_size ) { *error_code = MPI_SUCCESS; return; } MPI_Type_extent(fd->filetype, &filetype_extent); MPI_Type_size(buftype, &buftype_size); MPI_Type_extent(buftype, &buftype_extent); etype_size = fd->etype_size; ADIOI_Assert((buftype_size * count) == ((ADIO_Offset)(unsigned)buftype_size * (ADIO_Offset)count)); bufsize = buftype_size * count; /* contiguous in buftype and filetype is handled elsewhere */ if (!buftype_is_contig && filetype_is_contig) { int b_count; /* noncontiguous in memory, contiguous in file. */ #ifdef GFARM_DEBUG MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); printf("[%d/%d] ADIOI_GFARM_Write_str:nc-c\n", myrank, nprocs); #endif ADIOI_Flatten_datatype(buftype); flat_buf = ADIOI_Flatlist; while (flat_buf->type != buftype) flat_buf = flat_buf->next; off = (file_ptr_type == ADIO_INDIVIDUAL) ? fd->fp_ind : fd->disp + (ADIO_Offset)etype_size * offset; start_off = off; end_offset = off + bufsize - 1; /* if atomicity is true, lock (exclusive) the region to be accessed */ if ((fd->atomicity) && ADIO_Feature(fd, ADIO_LOCKS)) { ADIOI_WRITE_LOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } /* for each region in the buffer, grab the data and put it in * place */ for (b_count=0; b_count < count; b_count++) { for (b_index=0; b_index < flat_buf->count; b_index++) { userbuf_off = (ADIO_Offset)b_count*(ADIO_Offset)buftype_extent + flat_buf->indices[b_index]; req_off = off; req_len = flat_buf->blocklens[b_index]; ADIOI_Assert(req_len == (int) req_len); ADIOI_Assert((((ADIO_Offset)(MPIR_Upint)buf) + userbuf_off) == (ADIO_Offset)(MPIR_Upint)((MPIR_Upint)buf + userbuf_off)); ADIO_WriteContig(fd, (char *) buf + userbuf_off, (int)req_len, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, error_code); if (*error_code != MPI_SUCCESS) return; /* off is (potentially) used to save the final offset later */ off += flat_buf->blocklens[b_index]; } } if ((fd->atomicity) && ADIO_Feature(fd, ADIO_LOCKS)) { ADIOI_UNLOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } if (file_ptr_type == ADIO_INDIVIDUAL) fd->fp_ind = off; } else { /* noncontiguous in file */ int f_index, st_index = 0; ADIO_Offset st_fwr_size, st_n_filetypes; int flag; /* First we're going to calculate a set of values for use in all * the noncontiguous in file cases: * start_off - starting byte position of data in file * end_offset - last byte offset to be acessed in the file * st_n_filetypes - how far into the file we start in terms of * whole filetypes * st_index - index of block in first filetype that we will be * starting in (?) * st_fwr_size - size of the data in the first filetype block * that we will write (accounts for being part-way * into writing this block of the filetype * */ /* filetype already flattened in ADIO_Open */ flat_file = ADIOI_Flatlist; while (flat_file->type != fd->filetype) flat_file = flat_file->next; disp = fd->disp; if (file_ptr_type == ADIO_INDIVIDUAL) { start_off = fd->fp_ind; /* in bytes */ n_filetypes = -1; flag = 0; while (!flag) { n_filetypes++; for (f_index=0; f_index < flat_file->count; f_index++) { if (disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent + flat_file->blocklens[f_index] >= start_off) { /* this block contains our starting position */ st_index = f_index; fwr_size = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent + flat_file->blocklens[f_index] - start_off; flag = 1; break; } } } } else { n_etypes_in_filetype = filetype_size/etype_size; n_filetypes = offset / n_etypes_in_filetype; etype_in_filetype = offset % n_etypes_in_filetype; size_in_filetype = etype_in_filetype * etype_size; sum = 0; for (f_index=0; f_index < flat_file->count; f_index++) { sum += flat_file->blocklens[f_index]; if (sum > size_in_filetype) { st_index = f_index; fwr_size = sum - size_in_filetype; abs_off_in_filetype = flat_file->indices[f_index] + size_in_filetype - (sum - flat_file->blocklens[f_index]); break; } } /* abs. offset in bytes in the file */ start_off = disp + n_filetypes*(ADIO_Offset)filetype_extent + abs_off_in_filetype; } st_fwr_size = fwr_size; st_n_filetypes = n_filetypes; /* start_off, st_n_filetypes, st_index, and st_fwr_size are * all calculated at this point */ /* Calculate end_offset, the last byte-offset that will be accessed. * e.g., if start_off=0 and 100 bytes to be written, end_offset=99 */ userbuf_off = 0; f_index = st_index; off = start_off; fwr_size = ADIOI_MIN(st_fwr_size, bufsize); while (userbuf_off < bufsize) { userbuf_off += fwr_size; end_offset = off + fwr_size - 1; if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; fwr_size = ADIOI_MIN(flat_file->blocklens[f_index], bufsize-(unsigned)userbuf_off); } /* End of calculations. At this point the following values have * been calculated and are ready for use: * - start_off * - end_offset * - st_n_filetypes * - st_index * - st_fwr_size */ /* if atomicity is true, lock (exclusive) the region to be accessed */ if ((fd->atomicity) && ADIO_Feature(fd, ADIO_LOCKS)) { ADIOI_WRITE_LOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } if (buftype_is_contig && !filetype_is_contig) { /* contiguous in memory, noncontiguous in file. should be the * most common case. */ #ifdef GFARM_DEBUG printf("[%d/%d] ADIOI_GFARM_Write_str:c-nc\n", myrank, nprocs); #endif userbuf_off = 0; f_index = st_index; off = start_off; n_filetypes = st_n_filetypes; fwr_size = ADIOI_MIN(st_fwr_size, bufsize); /* while there is still space in the buffer, write more data */ while (userbuf_off < bufsize) { if (fwr_size) { /* TYPE_UB and TYPE_LB can result in fwr_size = 0. save system call in such cases */ req_off = off; req_len = fwr_size; ADIOI_Assert(req_len == (int) req_len); ADIOI_Assert((((ADIO_Offset)(MPIR_Upint)buf) + userbuf_off) == (ADIO_Offset)(MPIR_Upint)((MPIR_Upint)buf + userbuf_off)); if(ghi->newfile == 1){ #ifdef GFARM_WSTR_DEBUG printf("[%d/%d] ADIOI_GFARM_Write_str: bufsize = %d\n", myrank, nprocs, bufsize); #endif ADIO_WriteContig(fd, (char *) buf + userbuf_off, (int)bufsize, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, error_code); }else{ ADIO_WriteContig(fd, (char *) buf + userbuf_off, (int)req_len, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, error_code); if (*error_code != MPI_SUCCESS) return; } } if(ghi->newfile == 1){ userbuf_off += bufsize; ft_count = bufsize/filetype_size; rem_size = bufsize - ft_count*filetype_size; for(gfarm_i = 0; gfarm_i < (flat_file->count - 1);gfarm_i++){ tmp_rem_size = rem_size - flat_file->blocklens[gfarm_i]; if(tmp_rem_size > 0){ rem_size = tmp_rem_size; }else if(tmp_rem_size == 0){ break; }else{ break; } } off += filetype_extent * ft_count + flat_file->indices[gfarm_i] + flat_file->blocklens[gfarm_i]; }else{ userbuf_off += fwr_size; if (off + fwr_size < disp + flat_file->indices[f_index] + flat_file->blocklens[f_index] + n_filetypes*(ADIO_Offset)filetype_extent) { /* important that this value be correct, as it is * used to set the offset in the fd near the end of * this function. */ off += fwr_size; } /* did not reach end of contiguous block in filetype. * no more I/O needed. off is incremented by fwr_size. */ else { if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; fwr_size = ADIOI_MIN(flat_file->blocklens[f_index], bufsize-(unsigned)userbuf_off); } } } } else { #ifdef GFARM_DEBUG printf("[%d/%d] ADIOI_GFARM_Write_str:nc-nc\n", myrank, nprocs); #endif ADIO_Offset i_offset, tmp_bufsize = 0; /* noncontiguous in memory as well as in file */ ADIOI_Flatten_datatype(buftype); flat_buf = ADIOI_Flatlist; while (flat_buf->type != buftype) flat_buf = flat_buf->next; b_index = buf_count = 0; i_offset = flat_buf->indices[0]; f_index = st_index; off = start_off; n_filetypes = st_n_filetypes; fwr_size = st_fwr_size; bwr_size = flat_buf->blocklens[0]; /* while we haven't read size * count bytes, keep going */ while (tmp_bufsize < bufsize) { ADIO_Offset new_bwr_size = bwr_size, new_fwr_size = fwr_size; size = ADIOI_MIN(fwr_size, bwr_size); if (size) { req_off = off; req_len = size; userbuf_off = i_offset; ADIOI_Assert(req_len == (int) req_len); ADIOI_Assert((((ADIO_Offset)(MPIR_Upint)buf) + userbuf_off) == (ADIO_Offset)(MPIR_Upint)((MPIR_Upint)buf + userbuf_off)); if(ghi->newfile == 1){ #ifdef GFARM_WSTR_DEBUG printf("[%d/%d] ADIOI_GFARM_Write_str: bufsize = %d\n", myrank, nprocs, bufsize); #endif gfarm_tmp_buf = (void *)malloc(bufsize); for(gfarm_i=0;gfarm_i<count;gfarm_i++){ for(gfarm_j=0;gfarm_j<flat_buf->count;gfarm_j++){ if(flat_buf->blocklens[gfarm_j] == 0) continue; memcpy(gfarm_tmp_buf, buf+(flat_buf->indices[gfarm_j]+(gfarm_i*buftype_extent)), flat_buf->blocklens[gfarm_j]); } } ADIO_WriteContig(fd, (char *) gfarm_tmp_buf, (int)bufsize, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, error_code); if (*error_code != MPI_SUCCESS) return; }else{ ADIO_WriteContig(fd, (char *) buf + userbuf_off, (int)req_len, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, error_code); if (*error_code != MPI_SUCCESS) return; } } if(ghi->newfile == 1){ tmp_bufsize += bufsize; ft_count = bufsize/filetype_size; rem_size = bufsize - ft_count*filetype_size; for(gfarm_i = 0; gfarm_i < (flat_file->count - 1);gfarm_i++){ tmp_rem_size = rem_size - flat_file->blocklens[gfarm_i]; if(tmp_rem_size > 0){ rem_size = tmp_rem_size; }else if(tmp_rem_size == 0){ break; }else{ break; } } off += filetype_extent * ft_count + flat_file->indices[gfarm_i] + flat_file->blocklens[gfarm_i]; }else{ if (size == fwr_size) { /* reached end of contiguous block in file */ if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; new_fwr_size = flat_file->blocklens[f_index]; if (size != bwr_size) { i_offset += size; new_bwr_size -= size; } } if (size == bwr_size) { /* reached end of contiguous block in memory */ b_index = (b_index + 1)%flat_buf->count; buf_count++; i_offset = (ADIO_Offset)buftype_extent*(ADIO_Offset)(buf_count/flat_buf->count) + flat_buf->indices[b_index]; new_bwr_size = flat_buf->blocklens[b_index]; if (size != fwr_size) { off += size; new_fwr_size -= size; } } tmp_bufsize += size; fwr_size = new_fwr_size; bwr_size = new_bwr_size; } } } /* unlock the file region if we locked it */ if ((fd->atomicity) && ADIO_Feature(fd, ADIO_LOCKS)) { ADIOI_UNLOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } if (file_ptr_type == ADIO_INDIVIDUAL) fd->fp_ind = off; } /* end of (else noncontiguous in file) */ fd->fp_sys_posn = -1; /* mark it as invalid. */ #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, buftype, bufsize); /* This is a temporary way of filling in status. The right way is to * keep track of how much data was actually written and placed in buf */ #endif if (!buftype_is_contig) ADIOI_Delete_flattened(buftype); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfarm/gfs_pio_remote.c /* * pio operations for remote fragment * * $Id$ */ #include <stdlib.h> #include <string.h> #include <libgen.h> #include <sys/socket.h> /* struct sockaddr */ #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "host.h" #include "config.h" #include "gfs_proto.h" #include "gfs_client.h" #include "gfs_pio.h" static char * gfs_pio_remote_storage_close(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; return (gfs_client_close(gfs_server, vc->fd)); } static char * gfs_pio_remote_storage_write(GFS_File gf, const char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; /* * buffer beyond GFS_PROTO_MAX_IOSIZE are just ignored by gfsd, * we don't perform such GFS_PROTO_WRITE request, because it's * inefficient. * Note that upper gfs_pio layer should care this partial write. */ if (size > GFS_PROTO_MAX_IOSIZE) size = GFS_PROTO_MAX_IOSIZE; return (gfs_client_write(gfs_server, vc->fd, buffer, size, lengthp)); } static char * gfs_pio_remote_storage_read(GFS_File gf, char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; /* * Unlike gfs_pio_remote_storage_write(), we don't care * buffer size here, because automatic i/o size truncation * performed by gfsd isn't inefficient for read case. * Note that upper gfs_pio layer should care the partial read. */ return (gfs_client_read(gfs_server, vc->fd, buffer, size, lengthp)); } static char * gfs_pio_remote_storage_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; return (gfs_client_seek(gfs_server, vc->fd, offset, whence, resultp)); } static char * gfs_pio_remote_storage_ftruncate(GFS_File gf, file_offset_t length) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; return (gfs_client_ftruncate(gfs_server, vc->fd, length)); } static char * gfs_pio_remote_storage_calculate_digest(GFS_File gf, char *digest_type, size_t digest_size, size_t *digest_lengthp, unsigned char *digest, file_offset_t *filesizep) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; return (gfs_client_digest(gfs_server, vc->fd, digest_type, digest_size, digest_lengthp, digest, filesizep)); } static int gfs_pio_remote_storage_fd(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; struct gfs_connection *gfs_server = vc->storage_context; return (gfs_client_connection_fd(gfs_server)); } struct gfs_storage_ops gfs_pio_remote_storage_ops = { gfs_pio_remote_storage_close, gfs_pio_remote_storage_write, gfs_pio_remote_storage_read, gfs_pio_remote_storage_seek, gfs_pio_remote_storage_ftruncate, gfs_pio_remote_storage_calculate_digest, gfs_pio_remote_storage_fd, }; char * gfs_pio_open_remote_section(GFS_File gf, char *hostname, int flags) { struct gfs_file_section_context *vc = gf->view_context; char *e, *path_section; struct gfs_connection *gfs_server; /* * We won't use GFARM_FILE_EXCLUSIVE flag for the actual storage * level access (at least for now) to avoid the effect of * remaining junk files. * It's already handled anyway at the metadata level. * * NOTE: Same thing must be done in gfs_pio_local.c. */ int oflags = (gf->open_flags & ~GFARM_FILE_EXCLUSIVE); int fd; struct sockaddr peer_addr; e = gfarm_path_section(gf->pi.pathname, vc->section, &path_section); if (e != NULL) return (e); e = gfarm_host_address_get(hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { free(path_section); return (e); } e = gfs_client_connection(vc->canonical_hostname, &peer_addr, &gfs_server); if (e != NULL) { free(path_section); return (e); } vc->storage_context = gfs_server; e = gfs_client_open(gfs_server, path_section, oflags, gf->pi.status.st_mode & GFARM_S_ALLPERM, &fd); /* FT - the parent directory may be missing */ if (e == GFARM_ERR_NO_SUCH_OBJECT) if (gfs_pio_remote_mkdir_parent_canonical_path( gfs_server, gf->pi.pathname) == NULL) e = gfs_client_open(gfs_server, path_section, oflags, gf->pi.status.st_mode & GFARM_S_ALLPERM, &fd); /* FT - physical file should be missing */ if ((oflags & GFARM_FILE_CREATE) == 0 && e == GFARM_ERR_NO_SUCH_OBJECT) /* Delete the section copy info */ if (gfarm_file_section_copy_info_remove(gf->pi.pathname, vc->section, vc->canonical_hostname) == NULL) e = GFARM_ERR_INCONSISTENT_RECOVERABLE; free(path_section); if (e != NULL) return (e); vc->ops = &gfs_pio_remote_storage_ops; vc->fd = fd; return (NULL); } static char * gfs_pio_remote_mkdir_p( struct gfs_connection *gfs_server, char *canonic_dir) { struct gfs_stat stata; gfarm_mode_t mode; char *e, *user; /* dirname(3) may return '.'. This means the spool root directory. */ if (strcmp(canonic_dir, "/") == 0 || strcmp(canonic_dir, ".") == 0) return (NULL); /* should exist */ e = gfs_stat_canonical_path(canonic_dir, &stata); if (e != NULL) return (e); mode = stata.st_mode; /* * XXX - if the owner of a directory is not the same, create a * directory with permission 0777 - This should be fixed in * the next major release. */ user = gfarm_get_global_username(); if (strcmp(stata.st_user, user) != 0) mode |= 0777; gfs_stat_free(&stata); if (!GFARM_S_ISDIR(mode)) return (GFARM_ERR_NOT_A_DIRECTORY); if (gfs_client_exist(gfs_server, canonic_dir) == GFARM_ERR_NO_SUCH_OBJECT) { char *par_dir, *saved_par_dir; par_dir = saved_par_dir = strdup(canonic_dir); if (par_dir == NULL) return (GFARM_ERR_NO_MEMORY); par_dir = dirname(par_dir); e = gfs_pio_remote_mkdir_p(gfs_server, par_dir); free(saved_par_dir); if (e != NULL) return (e); e = gfs_client_mkdir(gfs_server, canonic_dir, mode); } return (e); } char * gfs_pio_remote_mkdir_parent_canonical_path( struct gfs_connection *gfs_server, char *canonic_dir) { char *par_dir, *saved_par_dir, *e; par_dir = saved_par_dir = strdup(canonic_dir); if (par_dir == NULL) return (GFARM_ERR_NO_MEMORY); par_dir = dirname(par_dir); if (gfs_client_exist(gfs_server, par_dir) == GFARM_ERR_NO_SUCH_OBJECT) e = gfs_pio_remote_mkdir_p(gfs_server, par_dir); else e = GFARM_ERR_ALREADY_EXISTS; free(saved_par_dir); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/package/solaris/build #!/bin/sh PATH=/usr/bin:/bin:/usr/ccs/bin:/opt/SUNWspro/bin:/usr/local/bin:/usr/ucb export PATH version=1.0.1 subpkgs='client devel doc fsnode gfptool server gfront' prefix=/usr/grid srcdir=`pwd` work=$srcdir/.. buildroot=$work/buildroot-$$ make=/usr/local/bin/make tar=/usr/local/bin/tar with_prefix=--prefix=$prefix with_globus=--with-globus=/usr/grid # XXX "unresolved symbol __eprintf" happens without --with-globus-shared. with_globus="$with_globus --with-globus-shared" # XXX --with-mpi needs OPTFLAGS=-O with gcc (an error happens at gfs_hook_mpi). # XXX currently, MPICH isn't installed on the build-host. # XXX tar warns missing `gfwc', because it isn't built without --with-mpi. with_mpi= # --with-mpi=/usr/local/mpich vendorcc_pkg=/usr/users/soda/install/SunOS-5.8-SUWspro-6.2 with_vendorcc_openldap=--with-openldap=$vendorcc_pkg/openldap-2.1.17 with_vendorcc_openssl=--with-openssl=$vendorcc_pkg/openssl-0.9.7c # XXX only gcc32 flavor is installed on the build-host. with_vendorcc_globus_flavor=--with-globus-flavor=gcc32 gcc_pkg=/usr/users/soda/install/SunOS-5.8-gcc-3.3 #with_gcc_openldap=--with-openldap=$gcc_pkg/openldap-2.1.17 # XXX need to update with_gcc_openldap=--with-openldap=/usr/users/soda/install/SunOS-5.8-gcc-2.95.2/openldap-2.1.17 with_gcc_openssl=--with-openssl=$gcc_pkg/openssl-0.9.7c with_gcc_globus_flavor=--with-globus-flavor=gcc32 case `whoami` in root) ;; # OK *) echo "root privilege is needed to invoke this script" >&2 exit 1;; esac for pkg in gfarm gfarm-gsi do for cc in vendorcc gcc do case ${pkg}-${cc} in gfarm-vendorcc) ./configure $with_prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl;; gfarm-gsi-vendorcc) ./configure $with_prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl \ $with_globus $with_vendorcc_globus_flavor;; gfarm-gcc) CC=gcc ./configure $with_prefix \ $with_gcc_openldap \ $with_gcc_openssl;; gfarm-gsi-gcc) CC=gcc ./configure $with_prefix \ $with_gcc_openldap \ $with_gcc_openssl \ $with_globus $with_gcc_globus_flavor;; esac $make rm -rf $buildroot mkdir -p $buildroot $buildroot$prefix $buildroot/etc $make prefix=$buildroot$prefix install mkdir -p $buildroot/etc/rc3.d cp package/solaris/gfmd $buildroot/etc/rc3.d/S98gfmd cp package/solaris/gfsd $buildroot/etc/rc3.d/S99gfsd ln $buildroot/etc/rc3.d/S98gfmd $buildroot/etc/rc3.d/K98gfmd ln $buildroot/etc/rc3.d/S99gfsd $buildroot/etc/rc3.d/K97gfsd chmod +x $buildroot/etc/rc3.d/* cp doc/conf/gfarm.conf $buildroot/etc/gfarm.conf.sample mkdir -p $buildroot/etc/gfarm-ldap cp doc/conf/gfarm.schema $buildroot/etc/gfarm-ldap/ $make distclean ( cd $buildroot && for s in $subpkgs do $tar zcf $work/${pkg}-${s}-${cc}-${version}.tar.gz \ `cat $srcdir/package/solaris/gfarm-${s}.files` done ) rm -rf $buildroot done done # $Id$ <file_sep>/gfarm/tags/gfarm_1_0_3/lib/gfs_hook/hooks_init_mpi.c /* * $Id$ */ #include <sys/types.h> #include <unistd.h> #include <mpi.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" char * gfs_hook_initialize(void) { int rank, size; char *e; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); _gfs_hook_debug(fprintf(stderr, "GFS: gfs_hook_initialize: set_local(%d, %d)\n", rank, size)); e = gfarm_initialize(NULL, NULL); if (e != NULL) return e; gfs_pio_set_local(rank, size); return NULL; } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_4/gfarm2fs.c /* * GfarmFS-FUSE for Gfarm version 2 * * $Id$ */ #include "config.h" #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <syslog.h> #include <sys/stat.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <stddef.h> #include <limits.h> #ifdef HAVE_SYS_XATTR_H #include <sys/xattr.h> #endif #if !defined(S_IFDIR) && defined(__S_IFDIR) /* * XXX Is this really necessary? * At least CentOS 5.0 and all NetBSD releases don't need this #define. */ #define S_IFDIR __S_IFDIR #endif /* * fuse.h requres that _FILE_OFFSET_BITS is defined in any case, but * AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 * since it is not necessary. To avoid this problem we define it here. */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #define FUSE_USE_VERSION 26 #include <fuse.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm2fs.h" #include "replicate.h" #include "open_file.h" #include "xattr.h" #include "id.h" #include "gfarm2fs_msg_enums.h" /* for old interface */ #undef USE_GETDIR /* XXX FIXME */ #define GFS_DEV ((dev_t)-1) #define GFS_BLKSIZE 8192 #define STAT_BLKSIZ 512 /* for st_blocks */ char *program_name = "gfarm2fs"; static const char GFARM2FS_SYSLOG_FACILITY_DEFAULT[] = "local0"; static const char GFARM2FS_SYSLOG_PRIORITY_DEBUG[] = "debug"; static const char *mount_point; #define PATH_LEN_LIMIT 200 static const char syslog_fmt[] = "<%s:%s>[%s]%s%s: %s"; static const char trunc_str[] = "(...)"; static const char empty_str[] = ""; #define gfarm2fs_check_error(msgNo, fuse_opname, gfarm_funcname, \ gfarm_path, gfarm_e) \ { \ if (gfarm_e != GFARM_ERR_NO_ERROR) { \ int ret_errno = gfarm_error_to_errno(gfarm_e); \ int path_len = strlen(gfarm_path); \ int path_offset = 0; \ const char *path_prefix = empty_str; \ if (path_len > PATH_LEN_LIMIT) { \ path_offset = path_len - PATH_LEN_LIMIT; \ path_prefix = trunc_str; \ } \ if (ret_errno == EINVAL || fuse_opname == OP_RELEASE) { \ gflog_error(msgNo, syslog_fmt, fuse_opname, \ gfarm_funcname, mount_point, \ path_prefix, gfarm_path + path_offset, \ gfarm_error_string(gfarm_e)); \ } else if (ret_errno != ENOENT) { \ gflog_info(msgNo, syslog_fmt, fuse_opname, \ gfarm_funcname, mount_point, \ path_prefix, gfarm_path + path_offset, \ gfarm_error_string(gfarm_e)); \ } else { \ gflog_debug(msgNo, syslog_fmt, fuse_opname, \ gfarm_funcname, mount_point, \ path_prefix, gfarm_path + path_offset, \ gfarm_error_string(gfarm_e)); \ } \ } \ } static const char OP_GETATTR[] = "GETATTR"; static const char OP_FGETATTR[] = "FGETATTR"; #if 0 /* XXX Part of invoking gfs_access() is defined "if 0" now */ static const char OP_ACCESS[] = "ACCESS"; #endif static const char OP_READLINK[] = "READLINK"; #ifndef USE_GETDIR static const char OP_OPENDIR[] = "OPENDIR"; static const char OP_READDIR[] = "READDIR"; static const char OP_RELEASEDIR[] = "RELEASEDIR"; #else /* USE_GETDIR */ static const char OP_GETDIR[] = "GETDIR"; #endif /* USE_GETDIR */ static const char OP_MKNOD[] = "MKNOD"; static const char OP_MKDIR[] = "MKDIR"; static const char OP_UNLINK[] = "UNLINK"; static const char OP_RMDIR[] = "RMDIR"; static const char OP_SYMLINK[] = "SYMLINK"; static const char OP_RENAME[] = "RENAME"; static const char OP_LINK[] = "LINK"; static const char OP_CHMOD[] = "CHMOD"; static const char OP_CHOWN[] = "CHOWN"; static const char OP_TRUNCATE[] = "TRUNCATE"; static const char OP_FTRUNCATE[] = "FTRUNCATE"; static const char OP_UTIMENS[] = "UTIMENS"; static const char OP_CREATE[] = "CREATE"; static const char OP_OPEN[] = "OPEN"; static const char OP_READ[] = "READ"; static const char OP_WRITE[] = "WRITE"; static const char OP_STATFS[] = "STATFS"; static const char OP_RELEASE[] = "RELEASE"; static const char OP_FSYNC[] = "FSYNC"; static const char OP_FLUSH[] = "FLUSH"; #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) static const char OP_SETXATTR[] = "SETXATTR"; static const char OP_GETXATTR[] = "GETXATTR"; static const char OP_LISTXATTR[] = "LISTXATTR"; static const char OP_REMOVEXATTR[] = "REMOVEXATTR"; #endif /* HAVE_SYS_XATTR_H && ENABLE_XATTR */ #define GFARM_DIR ".gfarm" static const char gfarm_path_prefix[] = GFARM_DIR "/"; #define GFARM_PATH_PREFIX_LEN (sizeof(gfarm_path_prefix) - 1) static char *gfarm2fs_path_prefix, *gfarm2fs_realpath_prefix; static size_t gfarm2fs_path_prefix_len, gfarm2fs_realpath_prefix_len; const static char *gfarm2fs_subdir; static size_t gfarm2fs_subdir_len; #define IS_SUBDIR(p) (memcmp(p, gfarm2fs_subdir, gfarm2fs_subdir_len) == 0) static void gfarm2fs_record_mount_point(const char *mpoint, const char *subdir) { char buf[PATH_MAX]; if (realpath(mpoint, buf) == NULL) { gflog_error(GFARM_MSG_2000058, "realpath(%s): %s", mpoint, strerror(errno)); exit(1); } if (strcmp(mpoint, buf) == 0) { gfarm2fs_realpath_prefix_len = 0; gfarm2fs_realpath_prefix = NULL; } else { gfarm2fs_realpath_prefix_len = strlen(buf) + 1 + GFARM_PATH_PREFIX_LEN; gfarm2fs_realpath_prefix = malloc(gfarm2fs_realpath_prefix_len + 1); if (gfarm2fs_realpath_prefix == NULL) { gflog_error(GFARM_MSG_2000059, "no memory for \"%s/%s\"", buf, gfarm_path_prefix); exit(1); } sprintf(gfarm2fs_realpath_prefix, "%s/%s", buf, gfarm_path_prefix); } gfarm2fs_path_prefix_len = strlen(mpoint) + 1 + GFARM_PATH_PREFIX_LEN; gfarm2fs_path_prefix = malloc(gfarm2fs_path_prefix_len + 1); if (gfarm2fs_path_prefix == NULL) { gflog_error(GFARM_MSG_2000060, "no memory for \"%s/%s\"", mpoint, gfarm_path_prefix); exit(1); } sprintf(gfarm2fs_path_prefix, "%s/%s", mpoint, gfarm_path_prefix); /* subdir may be modified (free'ed?) when it includes trailing /s */ gfarm2fs_subdir = subdir != NULL ? strdup(subdir) : ""; if (gfarm2fs_subdir == NULL) { gflog_error(GFARM_MSG_2000113, "no memory to allocate subdir \"%s\"", subdir); exit(1); } gfarm2fs_subdir_len = strlen(gfarm2fs_subdir); /* ignore one trailing slash. see gfarm2fs_getattr */ if (gfarm2fs_subdir_len > 0 && gfarm2fs_subdir[gfarm2fs_subdir_len - 1] == '/') --gfarm2fs_subdir_len; } gfarm_error_t gfarmize_path(const char *path, struct gfarmized_path *gfarmized) { const char *p = path; int sz; if (IS_SUBDIR(p)) p += gfarm2fs_subdir_len; if (p[0] == '/') p++; if (memcmp(p, gfarm_path_prefix, GFARM_PATH_PREFIX_LEN) == 0) { sz = strlen(p) - GFARM_PATH_PREFIX_LEN + 2 + GFARM_URL_PREFIX_LENGTH + 1; GFARM_MALLOC_ARRAY(gfarmized->path, sz); if (gfarmized->path == NULL) return (GFARM_ERR_NO_MEMORY); snprintf(gfarmized->path, sz, "%s//%s", GFARM_URL_PREFIX, p + GFARM_PATH_PREFIX_LEN); gfarmized->alloced = 1; return (GFARM_ERR_NO_ERROR); } gfarmized->alloced = 0; gfarmized->path = (char *)path; /* UNCONST */ return (GFARM_ERR_NO_ERROR); } void free_gfarmized_path(struct gfarmized_path *gfarmized) { if (gfarmized->alloced) free(gfarmized->path); } /* NOTE: *pathp must be malloc'ed memory */ static gfarm_error_t ungfarmize_path(char **pathp, const char *c_path) { char *path = *pathp, *p, *metadb = NULL; const static char metadb_xattr[] = "gfarm2fs.metadb"; size_t metadb_size = 0; gfarm_error_t e; if (gfarm_is_url(path) && path[GFARM_URL_PREFIX_LENGTH] == '/' && path[GFARM_URL_PREFIX_LENGTH + 1] == '/') { if (path[GFARM_URL_PREFIX_LENGTH + 2] == '/' && (gfarm2fs_xattr_get(c_path, metadb_xattr, NULL, &metadb_size) == GFARM_ERR_NO_ERROR)) { /* expand metadb and port from the current path */ GFARM_MALLOC_ARRAY(metadb, metadb_size + 1); if (metadb == NULL) /* 1 for '\0' */ return (GFARM_ERR_NO_MEMORY); e = gfarm2fs_xattr_get(c_path, metadb_xattr, metadb, &metadb_size); if (e != GFARM_ERR_NO_ERROR) return (e); metadb[metadb_size] = '\0'; } /* "gfarm://host/path" -> "MOUNT_POINT/.gfarm/host/path" */ p = malloc(gfarm2fs_path_prefix_len + metadb_size + strlen(path) - (GFARM_URL_PREFIX_LENGTH + 2) + 1); if (p == NULL) { /* NOTE: *pathp is not freed in this case */ return (GFARM_ERR_NO_MEMORY); } sprintf(p, "%s%s%s", gfarm2fs_path_prefix, metadb == NULL ? "" : metadb, path + GFARM_URL_PREFIX_LENGTH + 2); free(metadb); free(path); *pathp = p; } return (GFARM_ERR_NO_ERROR); } static gfarm_error_t parent_path(const char *path, struct gfarmized_path *gfarmized) { gfarm_error_t e = gfarmize_path(path, gfarmized); const char *p; if (e != GFARM_ERR_NO_ERROR) return (e); p = gfarm_url_dir(gfarmized->path); if (p == NULL) return (GFARM_ERR_NO_MEMORY); if (gfarmized->alloced) free(gfarmized->path); else gfarmized->alloced = 1; gfarmized->path = (char *)p; /* UNCONST */ return (GFARM_ERR_NO_ERROR); } /* * convert oldpath for symlink(3) to gfarm://-style URL, * but only for the following style: * /MOUNT/POINT/.gfarm/host:port/PATH/NAME */ static gfarm_error_t gfarmize_symlink_old(const char *old, struct gfarmized_path *gfarmized_old) { if (gfarm_is_url(old)) { gfarmized_old->path = (char *)old; /* UNCONST */ gfarmized_old->alloced = 0; return (GFARM_ERR_NO_ERROR); } /* is "/MOUNT/POINT/.gfarm/host:port/PATH/NAME" ? */ if (memcmp(old, gfarm2fs_path_prefix, gfarm2fs_path_prefix_len) == 0) { /* convert to "gfarm://host:/path" */ gfarmized_old->path = malloc(GFARM_URL_PREFIX_LENGTH + 2 + strlen(old) - gfarm2fs_path_prefix_len + 1); if (gfarmized_old->path == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(gfarmized_old->path, "%s//%s", GFARM_URL_PREFIX, old + gfarm2fs_path_prefix_len); gfarmized_old->alloced = 1; } else if (gfarm2fs_realpath_prefix != NULL && memcmp(old, gfarm2fs_realpath_prefix, gfarm2fs_realpath_prefix_len) == 0) { /* convert to "gfarm://host:/path" */ gfarmized_old->path = malloc(GFARM_URL_PREFIX_LENGTH + 2 + strlen(old) - gfarm2fs_realpath_prefix_len + 1); if (gfarmized_old->path == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(gfarmized_old->path, "%s//%s", GFARM_URL_PREFIX, old + gfarm2fs_realpath_prefix_len); gfarmized_old->alloced = 1; } else { gfarmized_old->path = (char *)old; /* UNCONST */ gfarmized_old->alloced = 0; } return (GFARM_ERR_NO_ERROR); } static uid_t get_uid(const char *gpath, char *user) { gfarm_error_t e; uid_t uid; e = gfarm2fs_get_uid(gpath, user, &uid); if (e != GFARM_ERR_NO_ERROR) { gflog_warning(GFARM_MSG_2000089, "get_uid(%s) failed: %s", user, gfarm_error_string(e)); return (gfarm2fs_get_nobody_uid()); } return (uid); } static int get_gid(const char *gpath, char *group) { gfarm_error_t e; gid_t gid; e = gfarm2fs_get_gid(gpath, group, &gid); if (e != GFARM_ERR_NO_ERROR) { gflog_warning(GFARM_MSG_2000090, "get_gid(%s) failed: %s", group, gfarm_error_string(e)); return (gfarm2fs_get_nogroup_gid()); } return (gid); } static int get_faked_nlink(struct gfs_stat *st) { return (GFARM_S_ISDIR(st->st_mode) ? 32000 : st->st_nlink); } static int get_genuine_nlink(struct gfs_stat *st) { return (st->st_nlink); } static int (*get_nlink)(struct gfs_stat *st) = get_faked_nlink; static void copy_gfs_stat(const char *gpath, struct stat *dst, struct gfs_stat *src) { memset(dst, 0, sizeof(*dst)); dst->st_dev = GFS_DEV; dst->st_ino = src->st_ino; dst->st_mode = src->st_mode; dst->st_nlink = get_nlink(src); dst->st_uid = get_uid(gpath, src->st_user); dst->st_gid = get_gid(gpath, src->st_group); dst->st_size = src->st_size; dst->st_blksize = GFS_BLKSIZE; dst->st_blocks = (src->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; dst->st_atime = src->st_atimespec.tv_sec; dst->st_mtime = src->st_mtimespec.tv_sec; dst->st_ctime = src->st_ctimespec.tv_sec; gfarm2fs_stat_atime_nsec_set(dst, src->st_atimespec.tv_nsec); gfarm2fs_stat_mtime_nsec_set(dst, src->st_mtimespec.tv_nsec); gfarm2fs_stat_ctime_nsec_set(dst, src->st_ctimespec.tv_nsec); } /* st_outp needs gfs_stat_free() */ static gfarm_error_t gfarm2fs_fstat( struct gfarm2fs_file *fp, struct gfs_stat *st_inp, struct gfs_stat *st_outp) { gfarm_error_t e; /* assert(st_outp); */ /* get atime, mtime and size from gfsd */ e = gfs_pio_stat(fp->gf, st_outp); /* include gfs_fstat() */ if (e != GFARM_ERR_NO_ERROR) return (e); if (fp->time_updated) { /* use atime and mtime from gfmd */ if (st_inp == NULL) { struct gfs_stat st_gfmd; /* gfs_fstat() again */ e = gfs_fstat(fp->gf, &st_gfmd); /* from gfmd */ if (e != GFARM_ERR_NO_ERROR) { gfs_stat_free(st_outp); return (e); } st_outp->st_atimespec = st_gfmd.st_atimespec; st_outp->st_mtimespec = st_gfmd.st_mtimespec; gfs_stat_free(&st_gfmd); } else { st_outp->st_atimespec = st_inp->st_atimespec; st_outp->st_mtimespec = st_inp->st_mtimespec; } } return (GFARM_ERR_NO_ERROR); } static int gfarm2fs_getattr(const char *path, struct stat *stbuf) { struct gfarmized_path gfarmized; struct gfs_stat st; struct gfarm2fs_file *fp; gfarm_error_t e; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000061, OP_GETATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_lstat_cached(gfarmized.path, &st); if (e != GFARM_ERR_NO_ERROR) { if (IS_SUBDIR(gfarmized.path) && strcmp(gfarmized.path + gfarm2fs_subdir_len, "/" GFARM_DIR) == 0) { memset(stbuf, 0, sizeof(*stbuf)); stbuf->st_dev = GFS_DEV; stbuf->st_ino = 1; stbuf->st_mode = S_IFDIR | 0111; stbuf->st_nlink = 1; /* tell find(1) to ignore nlink */ stbuf->st_uid = 0; stbuf->st_gid = 0; stbuf->st_size = 1024; stbuf->st_blksize = GFS_BLKSIZE; stbuf->st_blocks = (stbuf->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; stbuf->st_atime = 0; stbuf->st_mtime = 0; stbuf->st_ctime = 0; return (GFARM_ERR_NO_ERROR); } gfarm2fs_check_error(GFARM_MSG_2000001, OP_GETATTR, "gfs_lstat_cached", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } if ((fp = gfarm2fs_open_file_lookup(st.st_ino)) != NULL) { struct gfs_stat st2; e = gfarm2fs_fstat(fp, &st, &st2); if (e != GFARM_ERR_NO_ERROR) { gfs_stat_free(&st); gfarm2fs_check_error(GFARM_MSG_2000046, OP_GETATTR, "gfs_pio_stat", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } gfs_stat_free(&st); st = st2; } copy_gfs_stat(gfarmized.path, stbuf, &st); gfs_stat_free(&st); free_gfarmized_path(&gfarmized); return (0); } static inline struct gfarm2fs_file * get_filep(struct fuse_file_info *fi) { return ((struct gfarm2fs_file *)(uintptr_t)fi->fh); } static int gfarm2fs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { struct gfs_stat st; struct gfarmized_path gfarmized; struct gfarm2fs_file *fp = get_filep(fi); gfarm_error_t e; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000091, OP_FGETATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfarm2fs_fstat(fp, NULL, &st); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000002, OP_FGETATTR, "gfs_pio_stat", path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } copy_gfs_stat(path, stbuf, &st); free_gfarmized_path(&gfarmized); gfs_stat_free(&st); return (0); } static int gfarm2fs_access(const char *path, int mask) { /* XXX FIXME */ return (-ENOSYS); #if 0 gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000062, OP_ACCESS, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_access(gfarmized.path, mask); gfarm2fs_check_error(GFARM_MSG_2000003, OP_ACCESS, "gfs_access", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); #endif } static int gfarm2fs_readlink(const char *path, char *buf, size_t size) { gfarm_error_t e; struct gfarmized_path gfarmized; char *old; size_t len; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000063, OP_READLINK, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_readlink(gfarmized.path, &old); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000004, OP_READLINK, "gfs_readlink", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } e = ungfarmize_path(&old, path); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000064, OP_READLINK, "ungfarmize_path", old, GFARM_ERR_NO_MEMORY); free(old); free_gfarmized_path(&gfarmized); return (-ENOMEM); } len = strlen(old); if (len >= size) len = size - 1; memcpy(buf, old, len); buf[len] = '\0'; free(old); free_gfarmized_path(&gfarmized); return (0); } #ifndef USE_GETDIR static int gfarm2fs_opendir(const char *path, struct fuse_file_info *fi) { gfarm_error_t e; struct gfarmized_path gfarmized; GFS_Dir dp; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000065, OP_OPENDIR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_opendir_caching(gfarmized.path, &dp); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000005, OP_OPENDIR, "gfs_opendir_caching", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } fi->fh = (unsigned long) dp; free_gfarmized_path(&gfarmized); return (0); } static inline GFS_Dir get_dirp(struct fuse_file_info *fi) { return (GFS_Dir) (uintptr_t) fi->fh; } static int gfarm2fs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); struct gfs_dirent *de; struct stat st; gfarm_off_t off = 0; int seekdir_works = 0; gfarm_error_t e, e2; (void) path; e2 = gfs_seekdir(dp, offset); if (e2 == GFARM_ERR_NO_ERROR) { seekdir_works = 1; } else if (e2 != GFARM_ERR_FUNCTION_NOT_IMPLEMENTED) { /* was GFARM_ERR_FUNCTION_NOT_IMPLEMENTED until gfarm-2.5.4 */ gfarm2fs_check_error(GFARM_MSG_2000114, OP_READDIR, "gfs_seekdir", path, e2); } while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { memset(&st, 0, sizeof(st)); st.st_ino = de->d_fileno; st.st_mode = de->d_type << 12; if (seekdir_works) { e2 = gfs_telldir(dp, &off); gfarm2fs_check_error(GFARM_MSG_2000115, OP_READDIR, "gfs_telldir", path, e2); } if (filler(buf, de->d_name, &st, off)) break; } gfarm2fs_check_error(GFARM_MSG_2000006, OP_READDIR, "gfs_readdir", path, e); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_releasedir(const char *path, struct fuse_file_info *fi) { GFS_Dir dp = get_dirp(fi); gfarm_error_t e; (void) path; e = gfs_closedir(dp); gfarm2fs_check_error(GFARM_MSG_2000007, OP_RELEASEDIR, "gfs_closedir", path, e); return (-gfarm_error_to_errno(e)); } #else /* USE_GETDIR */ static int gfarm2fs_getdir(const char *path, fuse_dirh_t h, fuse_dirfil_t filler) { gfarm_error_t e, e2; struct gfarmized_path gfarmized; GFS_Dir dp; struct gfs_dirent *de; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000066, OP_GETDIR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_opendir_caching(gfarmized.path, &dp); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000008, OP_GETDIR, "gfs_opendir_caching", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { if (filler(h, de->d_name, de->d_type << 12, de->d_fileno)) break; } gfarm2fs_check_error(GFARM_MSG_2000009, OP_GETDIR, "gfs_readdir", gfarmized.path, e); e2 = gfs_closedir(dp); gfarm2fs_check_error(GFARM_MSG_2000010, OP_GETDIR, "gfs_closedir", gfarmized.path, e2); free_gfarmized_path(&gfarmized); if (e == GFARM_ERR_NO_ERROR) e = e2; return (-gfarm_error_to_errno(e)); } #endif static int gfarm2fs_mknod(const char *path, mode_t mode, dev_t rdev) { struct gfarmized_path gfarmized; GFS_File gf; gfarm_error_t e; if (!S_ISREG(mode)) return (-ENOSYS); e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000067, OP_MKNOD, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_pio_create(gfarmized.path, GFARM_FILE_WRONLY, mode & GFARM_S_ALLPERM, &gf); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000011, OP_MKNOD, "gfs_pio_create", gfarmized.path, e); } else { e = gfs_pio_close(gf); gfarm2fs_check_error(GFARM_MSG_2000012, OP_MKNOD, "gfs_pio_close", gfarmized.path, e); } free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_mkdir(const char *path, mode_t mode) { gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000068, OP_MKDIR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_mkdir(gfarmized.path, mode & GFARM_S_ALLPERM); gfarm2fs_check_error(GFARM_MSG_2000013, OP_MKDIR, "gfs_mkdir", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_unlink(const char *path) { gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000069, OP_UNLINK, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_unlink(gfarmized.path); gfarm2fs_check_error(GFARM_MSG_2000014, OP_UNLINK, "gfs_unlink", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_rmdir(const char *path) { gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000070, OP_RMDIR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_rmdir(gfarmized.path); gfarm2fs_check_error(GFARM_MSG_2000015, OP_RMDIR, "gfs_rmdir", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_symlink(const char *old, const char *new) { gfarm_error_t e; struct gfarmized_path gfarmized_old, gfarmized_new; e = gfarmize_symlink_old(old, &gfarmized_old); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000071, OP_SYMLINK, "gfarmize_symlink_old", old, e); return (-gfarm_error_to_errno(e)); } e = gfarmize_path(new, &gfarmized_new); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000092, OP_SYMLINK, "gfarmize_symlink_new", new, e); free_gfarmized_path(&gfarmized_old); return (-gfarm_error_to_errno(e)); } e = gfs_symlink(gfarmized_old.path, gfarmized_new.path); gfarm2fs_check_error(GFARM_MSG_2000016, OP_SYMLINK, "gfs_symlink", new, e); free_gfarmized_path(&gfarmized_new); free_gfarmized_path(&gfarmized_old); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_rename(const char *from, const char *to) { gfarm_error_t e; struct gfarmized_path gfarmized_from, gfarmized_to; e = gfarmize_path(from, &gfarmized_from); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000072, OP_RENAME, "gfarmize_path", from, e); return (-gfarm_error_to_errno(e)); } e = gfarmize_path(to, &gfarmized_to); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000073, OP_RENAME, "gfarmize_path", to, e); free_gfarmized_path(&gfarmized_from); return (-gfarm_error_to_errno(e)); } e = gfs_rename(gfarmized_from.path, gfarmized_to.path); gfarm2fs_check_error(GFARM_MSG_2000017, OP_RENAME, "gfs_rename", gfarmized_from.path, e); free_gfarmized_path(&gfarmized_to); free_gfarmized_path(&gfarmized_from); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_link(const char *from, const char *to) { gfarm_error_t e; struct gfarmized_path gfarmized_from, gfarmized_to; e = gfarmize_path(from, &gfarmized_from); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000074, OP_LINK, "gfarmize_path", from, e); return (-gfarm_error_to_errno(e)); } e = gfarmize_path(to, &gfarmized_to); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000075, OP_LINK, "gfarmize_path", to, e); free_gfarmized_path(&gfarmized_from); return (-gfarm_error_to_errno(e)); } e = gfs_link(gfarmized_from.path, gfarmized_to.path); gfarm2fs_check_error(GFARM_MSG_2000018, OP_LINK, "gfs_link", gfarmized_to.path, e); free_gfarmized_path(&gfarmized_to); free_gfarmized_path(&gfarmized_from); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_chmod(const char *path, mode_t mode) { gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000076, OP_CHMOD, "gfarmize_path", gfarmized.path, e); return (-gfarm_error_to_errno(e)); } e = gfs_chmod(gfarmized.path, mode & GFARM_S_ALLPERM); gfarm2fs_check_error(GFARM_MSG_2000019, OP_CHMOD, "gfs_chmod", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_chown(const char *path, uid_t uid, gid_t gid) { gfarm_error_t e; char *user = NULL, *group = NULL; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000077, OP_CHOWN, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } if (uid != -1 && ((e = gfarm2fs_get_user(gfarmized.path, uid, &user)) != GFARM_ERR_NO_ERROR)) { gfarm2fs_check_error(GFARM_MSG_2000093, OP_CHOWN, "gfarm2fs_get_user", path, e); goto end; } if (gid != -1 && ((e = gfarm2fs_get_group(gfarmized.path, gid, &group)) != GFARM_ERR_NO_ERROR)) { gfarm2fs_check_error(GFARM_MSG_2000094, OP_CHOWN, "gfarm2fs_get_group", path, e); goto end; } #ifdef HAVE_GFS_LCHOWN e = gfs_lchown(gfarmized.path, user, group); gfarm2fs_check_error(GFARM_MSG_2000020, OP_CHOWN, "gfs_lchown", gfarmized.path, e); #else e = gfs_chown(gfarmized.path, user, group); gfarm2fs_check_error(GFARM_MSG_2000020, OP_CHOWN, "gfs_chown", gfarmized.path, e); #endif end: free_gfarmized_path(&gfarmized); free(user); free(group); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_truncate(const char *path, off_t size) { gfarm_error_t e, e2; struct gfarmized_path gfarmized; GFS_File gf; int flags = GFARM_FILE_WRONLY; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000078, OP_TRUNCATE, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } if (size == 0) flags |= GFARM_FILE_TRUNC; e = gfs_pio_open(gfarmized.path, flags, &gf); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000021, OP_TRUNCATE, "gfs_pio_open", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } e = gfs_pio_truncate(gf, size); gfarm2fs_check_error(GFARM_MSG_2000022, OP_TRUNCATE, "gfs_pio_truncate", gfarmized.path, e); e2 = gfs_pio_close(gf); gfarm2fs_check_error(GFARM_MSG_2000023, OP_TRUNCATE, "gfs_pio_close", gfarmized.path, e2); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e != GFARM_ERR_NO_ERROR ? e : e2)); } static int gfarm2fs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { gfarm_error_t e; struct gfarm2fs_file *fp = get_filep(fi); (void) path; e = gfs_pio_truncate(fp->gf, size); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000024, OP_FTRUNCATE, "gfs_pio_ftruncate", path, e); } else fp->time_updated = 0; return (-gfarm_error_to_errno(e)); } static int gfarm2fs_utimens(const char *path, const struct timespec ts[2]) { struct gfarm_timespec gt[2]; gfarm_error_t e; struct gfarmized_path gfarmized; struct gfarm2fs_file *fp; struct gfs_stat st; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000116, OP_UTIMENS, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_lstat_cached(gfarmized.path, &st); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000117, OP_UTIMENS, "gfs_lstat_cached", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } if ((fp = gfarm2fs_open_file_lookup(st.st_ino)) != NULL) { fp->gt[0].tv_sec = ts[0].tv_sec; fp->gt[0].tv_nsec = ts[0].tv_nsec; fp->gt[1].tv_sec = ts[1].tv_sec; fp->gt[1].tv_nsec = ts[1].tv_nsec; fp->time_updated = 1; } gfs_stat_free(&st); gt[0].tv_sec = ts[0].tv_sec; gt[0].tv_nsec = ts[0].tv_nsec; gt[1].tv_sec = ts[1].tv_sec; gt[1].tv_nsec = ts[1].tv_nsec; #ifdef HAVE_GFS_LUTIMES e = gfs_lutimes(gfarmized.path, gt); #else e = gfs_utimes(gfarmized.path, gt); #endif gfarm2fs_check_error(GFARM_MSG_2000118, OP_UTIMENS, "gfs_lutimes", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } #define IS_WRITABLE(x) (((x) & GFARM_FILE_WRONLY) != 0 || \ ((x) & GFARM_FILE_RDWR) != 0) static int gfs_hook_open_flags_gfarmize(int open_flags) { int gfs_flags; switch (open_flags & O_ACCMODE) { case O_RDONLY: gfs_flags = GFARM_FILE_RDONLY; break; case O_WRONLY: gfs_flags = GFARM_FILE_WRONLY; break; case O_RDWR: gfs_flags = GFARM_FILE_RDWR; break; default: return (-1); } #if 0 /* this is unnecessary */ if ((open_flags & O_CREAT) != 0) gfs_flags |= GFARM_FILE_CREATE; #endif if ((open_flags & O_TRUNC) != 0) gfs_flags |= GFARM_FILE_TRUNC; #ifdef GFARM_FILE_APPEND if ((open_flags & O_APPEND) != 0) gfs_flags |= GFARM_FILE_APPEND; #endif #ifdef GFARM_FILE_EXCLUSIVE if ((open_flags & O_EXCL) != 0) gfs_flags |= GFARM_FILE_EXCLUSIVE; #endif #if 0 /* not yet on Gfarm v2 */ /* open(2) and creat(2) should be unbuffered */ gfs_flags |= GFARM_FILE_UNBUFFERED; #endif return (gfs_flags); } static gfarm_error_t gfarm2fs_file_init( const char *path, GFS_File gf, struct gfarm2fs_file **fpp, int flags) { gfarm_error_t e; struct gfarm2fs_file *fp; struct gfs_stat st; e = gfs_lstat_cached(path, &st); if (e != GFARM_ERR_NO_ERROR) return (e); GFARM_MALLOC(fp); if (fp) { fp->flags = flags; fp->gf = gf; fp->time_updated = 0; fp->inum = st.st_ino; *fpp = fp; gfs_stat_free(&st); return (GFARM_ERR_NO_ERROR); } else { gfs_stat_free(&st); return (GFARM_ERR_NO_MEMORY); } } static int gfarm2fs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { struct gfarm2fs_file *fp; gfarm_error_t e; struct gfarmized_path gfarmized; GFS_File gf; int flags; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000080, OP_CREATE, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_pio_create(gfarmized.path, flags, mode & GFARM_S_ALLPERM, &gf); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000026, OP_CREATE, "gfs_pio_create", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } e = gfarm2fs_file_init(gfarmized.path, gf, &fp, flags); if (e != GFARM_ERR_NO_ERROR) { (void)gfs_pio_close(gf); gfarm2fs_check_error(GFARM_MSG_2000119, OP_CREATE, "gfarm2fs_file_init", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } fi->fh = (unsigned long)fp; gfarm2fs_open_file_enter(fp, fi->flags|O_CREAT); free_gfarmized_path(&gfarmized); return (0); } static int gfarm2fs_open(const char *path, struct fuse_file_info *fi) { struct gfarm2fs_file *fp; GFS_File gf; int flags; gfarm_error_t e; struct gfarmized_path gfarmized; flags = gfs_hook_open_flags_gfarmize(fi->flags); e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000081, OP_OPEN, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_pio_open(gfarmized.path, flags, &gf); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000027, OP_OPEN, "gfs_pio_open", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } e = gfarm2fs_file_init(gfarmized.path, gf, &fp, flags); if (e != GFARM_ERR_NO_ERROR) { (void)gfs_pio_close(gf); gfarm2fs_check_error(GFARM_MSG_2000120, OP_OPEN, "gfarm2fs_file_init", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } fi->fh = (unsigned long)fp; gfarm2fs_open_file_enter(fp, fi->flags); free_gfarmized_path(&gfarmized); return (0); } static int gfarm2fs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; struct gfarm2fs_file *fp = get_filep(fi); (void) path; e = gfs_pio_seek(fp->gf, offset, GFARM_SEEK_SET, &off); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000028, OP_READ, "gfs_pio_seek", path, e); } else { e = gfs_pio_read(fp->gf, buf, size, &rv); gfarm2fs_check_error(GFARM_MSG_2000029, OP_READ, "gfs_pio_read", path, e); } if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); else fp->time_updated = 0; return (rv); } static int gfarm2fs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gfarm_error_t e; gfarm_off_t off; int rv; struct gfarm2fs_file *fp = get_filep(fi); (void) path; e = gfs_pio_seek(fp->gf, offset, GFARM_SEEK_SET, &off); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000030, OP_WRITE, "gfs_pio_seek", path, e); } else { e = gfs_pio_write(fp->gf, buf, size, &rv); gfarm2fs_check_error(GFARM_MSG_2000031, OP_WRITE, "gfs_pio_write", path, e); } if (e != GFARM_ERR_NO_ERROR) rv = -gfarm_error_to_errno(e); else fp->time_updated = 0; return (rv); } static int gfarm2fs_statfs(const char *path, struct statvfs *stbuf) { gfarm_error_t e; gfarm_off_t used, avail, files; /* XXX FIXME - path should be passed to the Gfarm API */ e = gfs_statfs(&used, &avail, &files); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000032, OP_STATFS, "gfs_statfs", path, e); return (-gfarm_error_to_errno(e)); } stbuf->f_bsize = 1024; /* XXX */ stbuf->f_frsize = 1024; /* XXX */ stbuf->f_blocks = used + avail; stbuf->f_bfree = avail; stbuf->f_bavail = avail; stbuf->f_files = files; stbuf->f_ffree = -1; /* XXX */ stbuf->f_favail = -1; /* XXX */ stbuf->f_fsid = 298; /* XXX */ stbuf->f_flag = 0; /* XXX */ stbuf->f_namemax = GFS_MAXNAMLEN; return (0); } static int gfarm2fs_release(const char *path, struct fuse_file_info *fi) { gfarm_error_t e; struct gfarm2fs_file *fp = get_filep(fi); (void) path; gfarm2fs_open_file_remove(fp); e = gfs_pio_close(fp->gf); gfarm2fs_check_error(GFARM_MSG_2000033, OP_RELEASE, "gfs_pio_close", path, e); if (fp->time_updated) { struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000121, OP_RELEASE, "gfarmize_path", path, e); } else { #ifdef HAVE_GFS_LUTIMES e = gfs_lutimes(gfarmized.path, fp->gt); #else e = gfs_utimes(gfarmized.path, fp->gt); #endif gfarm2fs_check_error(GFARM_MSG_2000122, OP_RELEASE, "gfs_lutimes", gfarmized.path, e); free_gfarmized_path(&gfarmized); } } free(fp); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { gfarm_error_t e; (void) path; if (isdatasync) { e = gfs_pio_datasync(get_filep(fi)->gf); gfarm2fs_check_error(GFARM_MSG_2000034, OP_FSYNC, "gfs_pio_datasync", path, e); } else { e = gfs_pio_sync(get_filep(fi)->gf); gfarm2fs_check_error(GFARM_MSG_2000035, OP_FSYNC, "gfs_pio_sync", path, e); } return (-gfarm_error_to_errno(e)); } static int gfarm2fs_flush(const char *path, struct fuse_file_info *fi) { gfarm_error_t e; struct gfarm2fs_file *fp = get_filep(fi); if (IS_WRITABLE(fp->flags)) { e = gfs_pio_flush(fp->gf); gfarm2fs_check_error(GFARM_MSG_2000123, OP_FLUSH, "gfs_pio_flush", path, e); return (-gfarm_error_to_errno(e)); } else return (0); } #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) static int gfarm2fs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { gfarm_error_t e; struct gfarmized_path gfarmized; int gflags; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000082, OP_SETXATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } switch (flags) { case 0: gflags = 0; break; #ifdef GFS_XATTR_CREATE case XATTR_CREATE: gflags = GFS_XATTR_CREATE; break; #endif #ifdef GFS_XATTR_REPLACE case XATTR_REPLACE: gflags = GFS_XATTR_REPLACE; break; #endif default: gflags = flags; /* XXX FIXME */ break; } /* include gfs_lsetxattr() */ e = gfarm2fs_xattr_set(gfarmized.path, name, value, size, gflags); gfarm2fs_check_error(GFARM_MSG_2000036, OP_SETXATTR, "gfs_lsetxattr", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } static int gfarm2fs_getxattr(const char *path, const char *name, char *value, size_t size) { gfarm_error_t e; struct gfarmized_path gfarmized; size_t s = size; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000083, OP_GETXATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } /* include gfs_lgetxattr_cached() */ e = gfarm2fs_xattr_get(gfarmized.path, name, value, &s); if (e == GFARM_ERR_NO_SUCH_OBJECT) { /* * NOTE: man getxattr(2) says that ENOATTR must be returned, * but it's not defined in header files. * We return -ENODATA because "strace ls -l /" is below. * open("/", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY) = 3 * .... * getxattr("/etc", "system.posix_acl_access"..., 0x0, 0) * = -1 ENODATA (No data available) * getxattr("/etc", "system.posix_acl_default"..., 0x0, 0) * = -1 ENODATA (No data available) * ... */ free_gfarmized_path(&gfarmized); return (-ENODATA); } if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000037, OP_GETXATTR, "gfs_lgetxattr_cached", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } free_gfarmized_path(&gfarmized); return (s); } static int gfarm2fs_listxattr(const char *path, char *list, size_t size) { gfarm_error_t e; struct gfarmized_path gfarmized; size_t s = size; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000084, OP_LISTXATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } e = gfs_llistxattr(gfarmized.path, list, &s); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000038, OP_LISTXATTR, "gfs_llistxattr", gfarmized.path, e); free_gfarmized_path(&gfarmized); return (-gfarm_error_to_errno(e)); } free_gfarmized_path(&gfarmized); return (s); } static int gfarm2fs_removexattr(const char *path, const char *name) { gfarm_error_t e; struct gfarmized_path gfarmized; e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gfarm2fs_check_error(GFARM_MSG_2000085, OP_REMOVEXATTR, "gfarmize_path", path, e); return (-gfarm_error_to_errno(e)); } /* include gfs_lremovexattr() */ e = gfarm2fs_xattr_remove(gfarmized.path, name); gfarm2fs_check_error(GFARM_MSG_2000039, OP_REMOVEXATTR, "gfs_lremovexattr", gfarmized.path, e); free_gfarmized_path(&gfarmized); if (e == GFARM_ERR_NO_SUCH_OBJECT) return (-ENODATA); else return (-gfarm_error_to_errno(e)); } #endif /* HAVE_SYS_XATTR_H && ENABLE_XATTR */ static struct fuse_operations gfarm2fs_oper = { .getattr = gfarm2fs_getattr, .fgetattr = gfarm2fs_fgetattr, .access = gfarm2fs_access, .readlink = gfarm2fs_readlink, #ifndef USE_GETDIR .opendir = gfarm2fs_opendir, .readdir = gfarm2fs_readdir, .releasedir = gfarm2fs_releasedir, #else .getdir = gfarm2fs_getdir, #endif .mknod = gfarm2fs_mknod, .mkdir = gfarm2fs_mkdir, .symlink = gfarm2fs_symlink, .unlink = gfarm2fs_unlink, .rmdir = gfarm2fs_rmdir, .rename = gfarm2fs_rename, .link = gfarm2fs_link, .chmod = gfarm2fs_chmod, .chown = gfarm2fs_chown, .truncate = gfarm2fs_truncate, .ftruncate = gfarm2fs_ftruncate, .utimens = gfarm2fs_utimens, .create = gfarm2fs_create, .open = gfarm2fs_open, .read = gfarm2fs_read, .write = gfarm2fs_write, .statfs = gfarm2fs_statfs, .release = gfarm2fs_release, .fsync = gfarm2fs_fsync, .flush = gfarm2fs_flush, #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) .setxattr = gfarm2fs_setxattr, .getxattr = gfarm2fs_getxattr, .listxattr = gfarm2fs_listxattr, .removexattr = gfarm2fs_removexattr, #endif }; /*** *** for cached mode ***/ static void uncache_parent(const char *path) { struct gfarmized_path gfarmized; gfarm_error_t e = parent_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_2000086, "parent_path(%s): %s", path, gfarm_error_string(e)); return; } gfs_stat_cache_purge(gfarmized.path); free_gfarmized_path(&gfarmized); } static void uncache_path(const char *path) { struct gfarmized_path gfarmized; gfarm_error_t e = gfarmize_path(path, &gfarmized); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_2000087, "gfarmize_path(%s): %s", path, gfarm_error_string(e)); return; } gfs_stat_cache_purge(gfarmized.path); free_gfarmized_path(&gfarmized); } static int gfarm2fs_mknod_cached(const char *path, mode_t mode, dev_t rdev) { int rv = gfarm2fs_mknod(path, mode, rdev); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_mkdir_cached(const char *path, mode_t mode) { int rv = gfarm2fs_mkdir(path, mode); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_unlink_cached(const char *path) { int rv = gfarm2fs_unlink(path); if (rv == 0) { uncache_path(path); uncache_parent(path); } return (rv); } static int gfarm2fs_rmdir_cached(const char *path) { int rv = gfarm2fs_rmdir(path); if (rv == 0) { uncache_path(path); uncache_parent(path); } return (rv); } static int gfarm2fs_symlink_cached(const char *old, const char *to) { int rv = gfarm2fs_symlink(old, to); if (rv == 0) uncache_parent(to); return (rv); } static int gfarm2fs_rename_cached(const char *from, const char *to) { int rv = gfarm2fs_rename(from, to); struct gfs_stat st; if (rv == 0) { uncache_path(from); uncache_parent(from); uncache_path(to); uncache_parent(to); /* try to replicate the destination file just in case */ if (gfs_lstat_cached(to, &st) == GFARM_ERR_NO_ERROR) { if (GFARM_S_ISREG(st.st_mode)) gfarm2fs_replicate(to, NULL); gfs_stat_free(&st); } } return (rv); } static int gfarm2fs_link_cached(const char *from, const char *to) { int rv = gfarm2fs_link(from, to); if (rv == 0) uncache_parent(to); return (rv); } static int gfarm2fs_chmod_cached(const char *path, mode_t mode) { int rv = gfarm2fs_chmod(path, mode); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_chown_cached(const char *path, uid_t uid, gid_t gid) { int rv = gfarm2fs_chown(path, uid, gid); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_truncate_cached(const char *path, off_t size) { int rv = gfarm2fs_truncate(path, size); if (rv == 0) uncache_path(path); gfarm2fs_replicate(path, NULL); return (rv); } static int gfarm2fs_ftruncate_cached(const char *path, off_t size, struct fuse_file_info *fi) { int rv = gfarm2fs_ftruncate(path, size, fi); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_utimens_cached(const char *path, const struct timespec ts[2]) { int rv = gfarm2fs_utimens(path, ts); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_create_cached(const char *path, mode_t mode, struct fuse_file_info *fi) { int rv = gfarm2fs_create(path, mode, fi); if (rv == 0) uncache_parent(path); return (rv); } static int gfarm2fs_open_cached(const char *path, struct fuse_file_info *fi) { int rv = gfarm2fs_open(path, fi); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_write_cached(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int rv = gfarm2fs_write(path, buf, size, offset, fi); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_release_cached(const char *path, struct fuse_file_info *fi) { int rv = gfarm2fs_release(path, fi); if (rv == 0 && ((fi->flags & O_ACCMODE) == O_WRONLY || (fi->flags & O_ACCMODE) == O_RDWR || (fi->flags & O_TRUNC) != 0)) uncache_path(path); gfarm2fs_replicate(path, fi); return (rv); } #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) static int gfarm2fs_setxattr_cached(const char *path, const char *name, const char *value, size_t size, int flags) { int rv = gfarm2fs_setxattr(path, name, value, size, flags); if (rv == 0) uncache_path(path); return (rv); } static int gfarm2fs_removexattr_cached(const char *path, const char *name) { int rv = gfarm2fs_removexattr(path, name); if (rv == 0) uncache_path(path); return (rv); } #endif /* HAVE_SETXATTR && ENABLE_XATTR */ static struct fuse_operations gfarm2fs_cached_oper = { .getattr = gfarm2fs_getattr, .fgetattr = gfarm2fs_fgetattr, .access = gfarm2fs_access, .readlink = gfarm2fs_readlink, #ifndef USE_GETDIR .opendir = gfarm2fs_opendir, .readdir = gfarm2fs_readdir, .releasedir = gfarm2fs_releasedir, #else .getdir = gfarm2fs_getdir, #endif .mknod = gfarm2fs_mknod_cached, .mkdir = gfarm2fs_mkdir_cached, .symlink = gfarm2fs_symlink_cached, .unlink = gfarm2fs_unlink_cached, .rmdir = gfarm2fs_rmdir_cached, .rename = gfarm2fs_rename_cached, .link = gfarm2fs_link_cached, .chmod = gfarm2fs_chmod_cached, .chown = gfarm2fs_chown_cached, .truncate = gfarm2fs_truncate_cached, .ftruncate = gfarm2fs_ftruncate_cached, .utimens = gfarm2fs_utimens_cached, .create = gfarm2fs_create_cached, .open = gfarm2fs_open_cached, .read = gfarm2fs_read, .write = gfarm2fs_write_cached, .statfs = gfarm2fs_statfs, .release = gfarm2fs_release_cached, .fsync = gfarm2fs_fsync, .flush = gfarm2fs_flush, #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) .setxattr = gfarm2fs_setxattr_cached, .getxattr = gfarm2fs_getxattr, .listxattr = gfarm2fs_listxattr, .removexattr = gfarm2fs_removexattr_cached, #endif }; /*** *** main ***/ #ifdef HAVE_GFARM_SCHEDULE_CACHE_DUMP void debug_handler(int signo) { /* XXX this function is not really async-signal-safe */ gfarm_schedule_cache_dump(); } #endif static void setup_dumper(void) { #ifdef HAVE_GFARM_SCHEDULE_CACHE_DUMP struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = debug_handler; sa.sa_flags = SA_RESTART; sigaction(SIGUSR2, &sa, NULL); #endif } /* KEY_GFARM2FS_OPT uses in "template has a format" case. * This has no meaning except for just marker. */ enum { KEY_GFARM2FS_OPT, KEY_F, KEY_D, KEY_VERSION, KEY_HELP, KEY_FIX_ACL, KEY_DISABLE_ACL, KEY_ENABLE_CACHED_ID, KEY_GENUINE_NLINK, KEY_DISABLE_GENUINE_NLINK, }; #define GFARM2FS_OPT(t, p, v) \ { t, offsetof(struct gfarm2fs_param, p), v } static struct fuse_opt gfarm2fs_opts[] = { GFARM2FS_OPT("gfs_stat_timeout=%lf", cache_timeout, KEY_GFARM2FS_OPT), GFARM2FS_OPT("-E %lf", cache_timeout, KEY_GFARM2FS_OPT), /* GFARM2FS_OPT("use_stderr", use_syslog, 0), */ GFARM2FS_OPT("syslog=%s", facility, KEY_GFARM2FS_OPT), GFARM2FS_OPT("loglevel=%s", loglevel, KEY_GFARM2FS_OPT), GFARM2FS_OPT("ncopy=%d", ncopy, KEY_GFARM2FS_OPT), GFARM2FS_OPT("copy_limit=%d", copy_limit, KEY_GFARM2FS_OPT), FUSE_OPT_KEY("-f", KEY_F), FUSE_OPT_KEY("-d", KEY_D), FUSE_OPT_KEY("debug", KEY_D), FUSE_OPT_KEY("-V", KEY_VERSION), FUSE_OPT_KEY("--version", KEY_VERSION), FUSE_OPT_KEY("-h", KEY_HELP), FUSE_OPT_KEY("--help", KEY_HELP), FUSE_OPT_KEY("fix_acl", KEY_FIX_ACL), FUSE_OPT_KEY("disable_acl", KEY_DISABLE_ACL), /* for debug */ FUSE_OPT_KEY("enable_cached_id", KEY_ENABLE_CACHED_ID), /* for debug */ FUSE_OPT_KEY("genuine_nlink", KEY_GENUINE_NLINK), FUSE_OPT_KEY("disable_genuine_nlink", KEY_DISABLE_GENUINE_NLINK), GFARM2FS_OPT("auto_uid_min=%d", auto_uid_min, KEY_GFARM2FS_OPT), GFARM2FS_OPT("auto_uid_max=%d", auto_uid_max, KEY_GFARM2FS_OPT), GFARM2FS_OPT("auto_gid_min=%d", auto_gid_min, KEY_GFARM2FS_OPT), GFARM2FS_OPT("auto_gid_max=%d", auto_gid_max, KEY_GFARM2FS_OPT), FUSE_OPT_END }; static void usage(const char *progname, struct gfarm2fs_param *paramsp) { fprintf(stderr, "usage: %s mountpoint [options]\n" "\n" "general options:\n" " -o opt,[opt...] mount options\n" " -h --help print help\n" " -V --version print version\n" "\n" "GFARM2FS options:\n" " -o syslog=facility syslog facility (default: %s)\n" " -o loglevel=priority syslog priority level\n" " (default: log_level directive in gfarm2.conf)\n" " -E T cache timeout for gfs_stat (default: 1.0 sec.)\n" " -o gfs_stat_timeout=T same -E option\n" " -o ncopy=N number of copies\n" " (default: 0 - disable replication)\n" " -o copy_limit=N maximum number of concurrent copy creations\n" " (default: %d)\n" " -o disable_genuine_nlink use faked st_nlink\n" " -o auto_uid_min=N minimum UID automatically assigned (default: %d)\n" " -o auto_uid_max=N maximum UID automatically assigned (default: %d)\n" " -o auto_gid_min=N minimum GID automatically assigned (default: %d)\n" " -o auto_gid_max=N maximum GID automatically assigned (default: %d)\n" "\n", progname, GFARM2FS_SYSLOG_FACILITY_DEFAULT, paramsp->copy_limit, paramsp->auto_uid_min, paramsp->auto_uid_max, paramsp->auto_gid_min, paramsp->auto_gid_max); } static int gfarm2fs_fuse_main(struct fuse_args *args, struct fuse_operations *fo) { #if FUSE_VERSION >= 26 return (fuse_main(args->argc, args->argv, fo, NULL)); #else return (fuse_main(args->argc, args->argv, fo)); #endif } #ifdef HAVE_BUG_OF_FUSE_OPT_PARSE_ON_NETBSD /* NetBSD-5.1 and before */ struct gfarm2fs_param *paramsp; #endif static int gfarm2fs_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { char *s; #ifndef HAVE_BUG_OF_FUSE_OPT_PARSE_ON_NETBSD struct gfarm2fs_param *paramsp = data; #endif switch (key) { case FUSE_OPT_KEY_OPT: /* -?, -o opt, --opt */ if (memcmp(arg, "subdir=", 7) == 0) { s = strdup(arg + 7); if (s != NULL) paramsp->subdir = s; } return (1); /* through */ case FUSE_OPT_KEY_NONOPT: if (!paramsp->mount_point) paramsp->mount_point = arg; return (1); /* through */ case KEY_F: paramsp->foreground = 1; return (1); /* through */ case KEY_D: paramsp->debug = 1; return (1); /* through */ case KEY_FIX_ACL: paramsp->fix_acl = 1; return (0); case KEY_DISABLE_ACL: paramsp->disable_acl = 1; return (0); case KEY_ENABLE_CACHED_ID: paramsp->enable_cached_id = 1; return (0); case KEY_DISABLE_GENUINE_NLINK: paramsp->genuine_nlink = 0; return (0); case KEY_VERSION: fprintf(stderr, "Gfarm2fs version " VERSION "\n"); #ifdef HAVE_GFARM_VERSION fprintf(stderr, "Gfarm version %s\n", gfarm_version()); #endif #if FUSE_VERSION >= 25 fuse_opt_add_arg(outargs, "--version"); gfarm2fs_fuse_main(outargs, &gfarm2fs_oper); #endif exit(0); case KEY_HELP: usage(outargs->argv[0], paramsp); fuse_opt_add_arg(outargs, "-ho"); gfarm2fs_fuse_main(outargs, &gfarm2fs_oper); exit(1); default: return (0); } } int main(int argc, char *argv[]) { struct fuse_operations *operation_mode = &gfarm2fs_cached_oper; gfarm_error_t e; int ret_fuse_main; struct fuse_args args = FUSE_ARGS_INIT(argc, argv); int syslog_priority; int syslog_facility = -1; struct gfarm2fs_param params = { .mount_point = NULL, .subdir = NULL, .foreground = 0, .debug = 0, .cache_timeout = -1.0, .use_syslog = 1, .facility = NULL, .loglevel = NULL, .ncopy = 0, .disable_acl = 0, /* for debug */ .enable_cached_id = 0, /* for debug */ .genuine_nlink = 1, .fix_acl = 0, .auto_uid_min = 70000, .auto_uid_max = 79999, .auto_gid_min = 70000, .auto_gid_max = 79999, #ifdef HAVE_GFS_REPLICATE_FILE_TO .copy_limit = 10 #else /* version 2.3.X */ .copy_limit = 0 #endif }; #ifdef HAVE_BUG_OF_FUSE_OPT_PARSE_ON_NETBSD paramsp = &params; #endif umask(0); e = gfarm_initialize(&argc, &argv); if (e != GFARM_ERR_NO_ERROR) { fprintf(stderr, "%s: %s\n", *argv, gfarm_error_string(e)); exit(1); } if (fuse_opt_parse(&args, &params, gfarm2fs_opts, gfarm2fs_opt_proc) == -1) { fprintf(stderr, "failed to parse option\n"); exit(1); } /* * specify '-s' option to disable multithreaded operations * libgfarm is not thread-safe for now */ fuse_opt_add_arg(&args, "-s"); #if FUSE_VERSION >= 28 /* -o atomic_o_trunc required to overwrite a "lost all replica" file */ fuse_opt_add_arg(&args, "-oatomic_o_trunc"); #endif /* use inum in Gfarm */ fuse_opt_add_arg(&args, "-ouse_ino"); if (params.mount_point == NULL) { fprintf(stderr, "missing mountpoint\n"); fprintf(stderr, "see `%s -h' for usage\n", program_name); exit(1); } mount_point = params.mount_point; gfarm2fs_record_mount_point(mount_point, params.subdir); if (params.foreground || params.debug) { params.use_syslog = 0; /* use stderr */ if (params.loglevel == NULL) { syslog_priority = gflog_syslog_name_to_priority( GFARM2FS_SYSLOG_PRIORITY_DEBUG); gflog_set_priority_level(syslog_priority); } } if (params.loglevel != NULL) { syslog_priority = gflog_syslog_name_to_priority(params.loglevel); if (syslog_priority == -1) { fprintf(stderr, "invalid loglevel: `%s'\n", params.loglevel); fprintf(stderr, "see `%s -h' for usage\n", program_name); exit(1); } gflog_set_priority_level(syslog_priority); } gflog_set_identifier(program_name); gflog_auth_set_verbose(1); if (params.use_syslog) { syslog_facility = gflog_syslog_name_to_facility( params.facility != NULL ? params.facility : GFARM2FS_SYSLOG_FACILITY_DEFAULT); if (syslog_facility == -1) { fprintf(stderr, "invalid facility: `%s'\n", params.facility); fprintf(stderr, "see `%s -h' for usage\n", program_name); exit(1); } } if (params.cache_timeout > 0.0) { gfs_stat_cache_expiration_set(params.cache_timeout*1000.0); } else if (params.cache_timeout == 0.0) { gfs_stat_cache_enable(0); /* disable cache */ operation_mode = &gfarm2fs_oper; } if (params.genuine_nlink) get_nlink = get_genuine_nlink; /* end of setting params */ gfarm2fs_replicate_init(&params); gfarm2fs_open_file_init(); gfarm2fs_xattr_init(&params); gfarm2fs_id_init(&params); setup_dumper(); if (params.use_syslog) /* just before fuse_main */ gflog_syslog_open(LOG_PID, syslog_facility); ret_fuse_main = gfarm2fs_fuse_main(&args, operation_mode); fuse_opt_free_args(&args); gfarm2fs_replicate_final(); e = gfarm_terminate(); if (e != GFARM_ERR_NO_ERROR) gflog_error(GFARM_MSG_2000124, "gfarm_terminate: %s", gfarm_error_string(e)); free(params.subdir); free(params.facility); free(params.loglevel); return (ret_fuse_main); } <file_sep>/gfarm/branches/metadb_dev/gftool/gfreg/gfreg.c #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <gfarm/gfarm.h> /* * Register a local file to the Gfarm Meta DB. * * gfreg <local_filename> <gfarm_url> */ char *program_name = "gfreg"; void usage() { fprintf(stderr, "Usage: %s <local_filename> <gfarm_url>\n", program_name); exit(1); } int main(int argc, char * argv[]) { int argc_save = argc; char **argv_save = argv; char * filename, * gfarm_url; int node_index = -1, total_nodes = -1; char * e = NULL, * architecture = NULL; struct stat s; extern char * optarg; extern int optind; int c; /* Command options */ if (argc >= 1) program_name = argv[0]; while ((c = getopt(argc, argv, "I:N:a:")) != -1) { switch (c) { case 'I': node_index = strtol(optarg, NULL, 0); break; case 'N': total_nodes = strtol(optarg, NULL, 0); break; case 'a': architecture = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc == 0) { fprintf(stderr, "%s: missing a local filename\n", program_name); usage(); exit(1); } filename = argv[0]; argc--; argv++; if (argc == 0) { fprintf(stderr, "%s: missing a Gfarm URL\n", program_name); usage(); exit(1); } gfarm_url = argv[0]; argc--; argv++; /* */ e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (stat(filename, &s) != -1 && S_ISREG(s.st_mode) && (s.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0 && node_index < 0) { if (architecture == NULL) { char *self_hostname; if (gfarm_host_get_canonical_self_name(&self_hostname) == NULL) architecture = gfarm_host_info_get_architecture_by_host(self_hostname); } if (architecture == NULL) { fprintf(stderr, "%s: missing -a <architecture> for %s on %s\n", program_name, filename, gfarm_host_get_self_name()); usage(); exit(1); } if (total_nodes <= 0) total_nodes = 1; e = gfarm_url_program_register(gfarm_url, architecture, filename, total_nodes); } else { if (node_index < 0) { fprintf(stderr, "%s: missing -I <Gfarm index>\n", program_name); usage(); exit(1); } e = gfs_pio_set_fragment_info_local(filename, gfarm_url, node_index); } if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(0); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/lib/gfs_hook/Makefile # $Id$ top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk # shared object version SHARELIB_LTFLAGS= LT_CURRENT=0 LT_REVISION=0 LT_AGE=0 LTLINK_SHARELIB= $(LTLINK_SHARELIB_IN) $(libdir) $(SHARELIB_LTFLAGS) DEBUG_CFLAGS= SUFFIX= DEBUG_MAKEFLAGS= \ DEBUG_CFLAGS=-DDEBUG \ SUFFIX=_debug SUBDIRS= sysdep/$(gfs_hook_sysdep_subdir) SYSDEP_OBJS= sysdep/$(gfs_hook_sysdep_subdir)/libsysdep.la # do not use $(COMMON_CFLAGS) here, to avoid symbol renaming by largefile API. CFLAGS = $(OPTFLAGS) $(DEBUG_CFLAGS) -I$(srcdir) \ -I$(GFUTIL_SRCDIR) -I$(GFARMLIB_SRCDIR) $(openssl_includes) \ -I$(top_builddir)/include -I$(top_srcdir)/include # The reason, why we don't use $(GFARMLIB) and add an inter-library # dependency only on libgfarm here, is because the other dependencies # will be automatically added by libtool. And because using $(GFARMLIB) # automatically adds $(globus_gssapi_libs), and that may add statically # linked globus libraries to the libgfs_hook.a. LDLIBS = $(top_builddir)/lib/libgfarm/libgfarm.la # to not use default $(LIBRARY) target in lib.mk LIBRARY = LIBRARY_RESULT = libgfs_hook$(SUFFIX).la gfs_hook$(SUFFIX).o \ libgfs_hook_no_init$(SUFFIX).la gfs_hook_no_init$(SUFFIX).o \ $(mpi_targets) MPI_TARGETS = libgfs_hook_mpi$(SUFFIX).la gfs_hook_mpi$(SUFFIX).o # need to hook _LFS64_LARGEFILE API? LARGEFILE64_SRCS= hooks_64.c lseek64.c LARGEFILE64_OBJS= hooks_64$(SUFFIX).lo lseek64.lo # build MPI related objects? MPI_SRCS = hooks_init_mpi.c MPI_OBJS = hooks_init_mpi$(SUFFIX).lo SRCS = getcwd.c hooks_subr.c \ hooks.c \ $(largefile64_srcs) \ hooks_common.c hooks_stat.c hooks_fstat.c \ hooks_init.c $(mpi_srcs) OBJS = getcwd.lo hooks_subr$(SUFFIX).lo \ hooks$(SUFFIX).lo \ $(largefile64_objs) \ $(SYSDEP_OBJS) EXTRA_CLEAN_TARGETS= hooks_init$(SUFFIX).lo $(mpi_objs) ### ### settings for test programs ### TEST_LDLIBS = $(GFARMLIB) ### ### main rule ### .SUFFIXES: .a .la .ln .o _debug.lo .lo .s .S .c .cc .f .y .l .c_debug.lo: $(LTCOMPILE) -c $(srcdir)/$*.c -o $*_debug.lo all: subdir-all gfs-hooks debug-gfs-hooks ### ### rules to make $(LIBRARY_RESULT) ### gfs-hooks: $(LIBRARY_RESULT) libgfs_hook$(SUFFIX).la: $(OBJS) hooks_init$(SUFFIX).lo $(LTLINK_SHARELIB) $(OBJS) hooks_init$(SUFFIX).lo $(LDLIBS) gfs_hook$(SUFFIX).o: $(OBJS) hooks_init.lo $(LTLINK) $(OBJS) hooks_init$(SUFFIX).lo libgfs_hook_no_init$(SUFFIX).la: $(OBJS) $(LTLINK_SHARELIB) $(OBJS) $(LDLIBS) gfs_hook_no_init$(SUFFIX).o: $(OBJS) $(LTLINK) $(OBJS) gfs_hook_mpi$(SUFFIX).la: $(OBJS) hooks_init_mpi$(SUFFIX).lo $(LTLINK_SHARELIB) $(OBJS) hooks_init_mpi$(SUFFIX).lo $(LDLIBS) gfs_hook_mpi$(SUFFIX).o: $(OBJS) hooks_init_mpi$(SUFFIX).lo $(LTLINK) $(OBJS) hooks_init_mpi$(SUFFIX).lo ### ### objects needed by $(LIBRARY_TARGET) ### lseek64.lo: lseek64.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -o $@ -c $(srcdir)/lseek64.c hooks_64$(SUFFIX).lo: hooks_64.c hooks_common.c hooks_stat.c hooks_fstat.c $(LTCOMPILE) -D_LARGEFILE64_SOURCE `getconf LFS64_CFLAGS` -o $@ -c $(srcdir)/hooks_64.c hooks$(SUFFIX).lo: hooks.c hooks_common.c hooks_stat.c hooks_fstat.c hooks_init_mpi$(SUFFIX).lo: hooks_init_mpi.c $(LIBTOOL) --mode=compile $(MPICC) $(CFLAGS) -o $@ -c $(srcdir)/hooks_init_mpi.c install: all # XXX this installation directory is WRONG. $(INSTALL_DATA) $(srcdir)/hooks_init_mpi.c $(libdir)/hooks_init_mpi.c ### ### *_debug.{o,a,so*}: libraries compiled with -DDEBUG ### install: debug-lib-install clean: debug-lib-clean veryclean: debug-lib-veryclean debug-gfs-hooks debug-lib-install debug-lib-clean debug-lib-veryclean: @target=`expr $@ : 'debug-\(.*\)'`; \ echo '[' making $@ ']'; set -x; \ $(MAKE) -f $(srcdir)/Makefile $(DEBUG_MAKEFLAGS) $${target} ### ### test programs, these won't be installed. ### veryclean: test-veryclean test: hook_test mpitest: hook_test_mpi hook_test: subdir-all debug-gfs-hooks hook_test.o $(LTLINK) hook_test.o gfs_hook_debug.o $(TEST_LDLIBS) hook_test_mpi: subdir-all debug-gfs-hooks hook_test_mpi.o $(LIBTOOL) --mode=link $(MPICC) $(CFLAGS) -o $@ hook_test_mpi.o gfs_hook_mpi_debug.o $(TEST_LDLIBS) hook_test_mpi.o: hook_test_mpi.c $(MPICC) -c $(CFLAGS) -o $@ $(srcdir)/hook_test_mpi.c test-veryclean: $(LTCLEAN) hook_test hook_test.o hook_test_mpi hook_test_mpi.o ### ### dependencies, etc. ### include $(top_srcdir)/makes/subdir.mk include $(top_srcdir)/makes/lib.mk $(OBJS): $(INC_SRCDIR)/gfarm.h $(INC_SRCDIR)/gfarm_error.h $(INC_SRCDIR)/gfarm_misc.h $(INC_SRCDIR)/gfs.h hooks_subr.h hooks$(SUFFIX).lo hooks_64$(SUFFIX).lo: hooks_subr.h hooks_common.c hooks_stat.c hooks_fstat.c hooks_subr$(SUFFIX).lo: hooks_subr.h <file_sep>/gfarm/tags/gfarm_1_1_1_rc4/makes/include.mk all: include-all post-all-hook install: all include-install post-install-hook clean: include-clean post-clean-hook veryclean: include-veryclean post-veryclean-hook distclean: include-distclean post-distclean-hook gfregister: include-gfregister post-gfregister-hook man: include-man post-man-hook html: include-html post-html-hook post-all-hook: post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: include-all: include-install: all @set -x; \ for i in -- $(INCS); do \ case $$i in --) continue;; esac; \ $(INSTALL_DATA) $(srcdir)/$$i $(includedir)/$$i; \ done @set -x; \ for i in -- $(EXEC_INCS); do \ case $$i in --) continue;; esac; \ $(INSTALL_DATA) $$i $(exec_includedir)/$$i; \ done include-clean: -test -z "$(EXTRA_CLEAN_TARGETS)" || $(RM) -f $(EXTRA_CLEAN_TARGETS) include-veryclean: clean -test -z "$(EXTRA_VERYCLEAN_TARGETS)" || $(RM) -f $(EXTRA_VERYCLEAN_TARGETS) include-distclean: veryclean -test -z "$(EXEC_INCS)" || $(RM) -f $(EXEC_INCS) -test ! -f $(srcdir)/Makefile.in || $(RM) -f Makefile include-gfregister: include-man: include-html: <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_3/src/install-server.sh #! /bin/sh # # Install the 'gfarm_zabbix' package for Zabbix server. # . ./install.conf # install(1) command. INSTALL=install # # Create "$1" file from "$1.in". # create_file() { [ -f "$1" ] && rm -f "$1" sed -e "s|@ZABBIX_CONFDIR@|$ZABBIX_CONFDIR|g" \ -e "s|@SYSLOG_FILE@|$SYSLOG_FILE|g" \ -e "s|@ZABBIX_EXTSCRIPTDIR@|$ZABBIX_EXTSCRIPTDIR|g" \ -e "s|@ZABBIX_ALERTSCRIPTDIR@|$ZABBIX_ALERTSCRIPTDIR|g" \ -e "s|@GFARM_BINDIR@|$GFARM_BINDIR|g" \ -e "s|@ZABBIX_DATADIR@|$ZABBIX_DATADIR|g" \ -e "s|@APACHE_CONDIR@|$APACHE_CONDIR|g" \ -e "s|@ZABBIX_SERVER_PIDFILE@|$ZABBIX_SERVER_PIDFILE|g" \ -e "s|@ZABBIX_SERVER_LOGFILE@|$ZABBIX_SERVER_LOGFILE|g" \ -e "s|@HTMLDIR@|$HTMLDIR|g" \ -e "s|@HTMLDIR_USER@|$HTMLDIR_USER|g" \ -e "s|@HTMLDIR_GROUP@|$HTMLDIR_GROUP|g" \ -e "s|@PHP_TIMEZONE@|$PHP_TIMEZONE|g" \ -e "s|@MYSQL_CONFDIR@|$MYSQL_CONFDIR|g" \ -e "s|@DB_NAME@|$DB_NAME|g" \ -e "s|@DB_USER@|$DB_USER|g" \ -e "s|@DB_PASSWORD@|$DB_PASSWORD|g" \ -e "s|@ZABBIX_NODEID@|$ZABBIX_NODEID|g" \ "$1.in" > "$1" } # # Make a directory '$HTMLDIR'. # DIR=$HTMLDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files in 'gfarm-zabbix_redundancy/mds_list/html' to $HTMLDIR. # for I in download.php regist.php upload.html; do SRCFILE=gfarm-zabbix_redundancy/mds_list/html/$I DSTFILE=$HTMLDIR/$I $INSTALL -c -m 0644 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Make a directory '$HTMLDIR/files'. # DIR=$HTMLDIR/files if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o $HTMLDIR_USER -g $HTMLDIR_GROUP $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Make a directory '$ZABBIX_CONFDIR'. # DIR=$ZABBIX_CONFDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install 'zabbix_server.conf.sample' to $ZABBIX_CONFDIR. # FILE=zabbix_server.conf.sample SRCFILE=gfarm-zabbix_confs/zabbix/$FILE DSTFILE=$ZABBIX_CONFDIR/$FILE create_file $SRCFILE $INSTALL -c -m 0600 -o zabbix -g zabbix $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" # # Make a directory '$MYSQL_CONFDIR'. # DIR=$MYSQL_CONFDIR if [ "X$DIR" != X -a ! -d /.$DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install 'my.cnf.sample' to $MYSQL_CONFDIR. # FILE=my.cnf.sample SRCFILE=gfarm-zabbix_confs/mysql/$FILE DSTFILE=$MYSQL_CONFDIR/$FILE create_file $SRCFILE if [ "X$MYSQL_CONFDIR" != X ]; then $INSTALL -c -m 0644 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" fi # # Make a directory '$APACHE_CONFDIR'. # DIR=$APACHE_CONFDIR if [ "X$DIR" != X -a ! -d /.$DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install 'zabbix.conf.sample' (for Apache HTTPD). # FILE=zabbix.conf.sample SRCFILE=gfarm-zabbix_confs/apache/$FILE DSTFILE=$APACHE_CONFDIR/$FILE create_file $SRCFILE if [ "X$APACHE_CONFDIR" != X ]; then $INSTALL -c -m 0644 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" fi # # Create template files in 'gfarm-zabbix_templates' sub-directory. # for I in \ Template_Gfarm_cli.xml \ Template_Gfarm_common.xml \ Template_Gfarm_gfmd.xml \ Template_Gfarm_gfsd.xml \ Template_Gfarm_redundant_cli.xml \ Template_Gfarm_redundant_gfmd.xml \ Template_Gfarm_redundant_gfsd.xml \ Template_Gfarm_zabbix.xml; do FILE=gfarm-zabbix_templates/$I create_file $FILE \ || { echo "Failed to create the file: $FILE"; exit 1; } echo "Create the file: $FILE" done # # Create the directory of $ZABBIX_SERVER_PIDFILE. # DIR=`dirname $ZABBIX_SERVER_PIDFILE` if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o zabbix -g zabbix $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Create the directory of $ZABBIX_SERVER_LOGFILE. # DIR=`dirname $ZABBIX_SERVER_LOGFILE` if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o zabbix -g zabbix $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8/systest/testcases/Makefile.am testcasesdir = @gfarm_root@/share/gfarm/systest/testcases dist_testcases_DATA = read_files \ write_files \ write_files_each_mntpnts <file_sep>/gfarm/tags/gfarm_1_0_rc2/lib/libgfarm/gfarm/auth_server.c #include <stdio.h> #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <grp.h> #include <sys/types.h> #include <sys/socket.h> #include <time.h> #include <pwd.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "xxx_proto.h" #include "hostspec.h" #include "auth.h" static char *gfarm_authorize_panic(struct xxx_connection *, int, char *, char **); char *(*gfarm_authorization_table[])(struct xxx_connection *, int, char *, char **) = { /* * This table entry should be ordered by enum gfarm_auth_method. */ gfarm_authorize_panic, /* GFARM_AUTH_METHOD_NONE */ gfarm_authorize_sharedsecret, /* GFARM_AUTH_METHOD_SHAREDSECRET */ gfarm_authorize_panic, /* GFARM_AUTH_METHOD_GSI_OLD */ #ifdef HAVE_GSI gfarm_authorize_gsi, /* GFARM_AUTH_METHOD_GSI */ gfarm_authorize_gsi_auth, /* GFARM_AUTH_METHOD_GSI_AUTH */ #else gfarm_authorize_panic, /* GFARM_AUTH_METHOD_GSI */ gfarm_authorize_panic, /* GFARM_AUTH_METHOD_GSI_AUTH */ #endif }; static char * gfarm_authorize_panic(struct xxx_connection *conn, int switch_to, char *hostname, char **global_usernamep) { gflog_fatal("gfarm_authorize", "authorization assertion failed"); return (GFARM_ERR_PROTOCOL); } static char * gfarm_auth_sharedsecret_response(struct xxx_connection *conn, char *homedir) { char *e; gfarm_uint32_t request, expire, expire_expected; size_t len; gfarm_int32_t error = GFARM_AUTH_ERROR_EXPIRED; /* gfarm_auth_error */ int eof, try = 0; char challenge[GFARM_AUTH_CHALLENGE_LEN]; char response[GFARM_AUTH_RESPONSE_LEN]; char shared_key_expected[GFARM_AUTH_SHARED_KEY_LEN]; char response_expected[GFARM_AUTH_RESPONSE_LEN]; /* NOTE: `homedir' may be NULL, if invalid username is requested. */ for (;;) { ++try; e = xxx_proto_recv(conn, 0, &eof, "i", &request); if (e != NULL) { gflog_error("auth_sharedsecret_response", e); return (e); } if (eof) { gflog_error("auth_sharedsecret_response", "unexpected EOF"); return (GFARM_ERR_PROTOCOL); } if (request != GFARM_AUTH_SHAREDSECRET_GIVEUP && request != GFARM_AUTH_SHAREDSECRET_MD5) { error = GFARM_AUTH_ERROR_NOT_SUPPORTED; e = xxx_proto_send(conn, "i", error); if (e != NULL) { gflog_error("auth_sharedsecret: key type", e); return (e); } continue; } e = xxx_proto_send(conn, "i", GFARM_AUTH_ERROR_NO_ERROR); if (e != NULL) { gflog_error("auth_sharedsecret: key query", e); return (e); } if (request == GFARM_AUTH_SHAREDSECRET_GIVEUP) { e = xxx_proto_flush(conn); if (e != NULL) { gflog_error("auth_sharedsecret: cut", e); } else if (try <= 1) { e = GFARM_ERR_AUTHENTICATION; gflog_error("auth_sharedsecret: scaned", e); } else { switch (error) { case GFARM_AUTH_ERROR_EXPIRED: e = GFARM_ERR_EXPIRED; break; case GFARM_AUTH_ERROR_NOT_SUPPORTED: e = GFARM_ERR_PROTOCOL_NOT_SUPPORTED; break; default: e = GFARM_ERR_AUTHENTICATION; break; } gflog_error("auth_sharedsecret: gives up", e); } return (e); } gfarm_auth_random(challenge, sizeof(challenge)); e = xxx_proto_send(conn, "b", sizeof(challenge), challenge); if (e != NULL) { gflog_error("auth_sharedsecret: challenge", e); return (e); } e = xxx_proto_recv(conn, 0, &eof, "ib", &expire, sizeof(response), &len, response); if (e != NULL) { gflog_error("auth_sharedsecret: response", e); return (e); } if (eof) { gflog_error("auth_sharedsecret", "unexpected EOF in response"); return (GFARM_ERR_PROTOCOL); } /* * Note that gfarm_auth_shared_key_get() should be called * after the above xxx_proto_recv(), otherwise * client (re)generated shared key may not be accessible. */ if (homedir == NULL) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; /* already logged at gfarm_authorize_sharedsecret() */ } else if ((e = gfarm_auth_shared_key_get(&expire_expected, shared_key_expected, homedir, GFARM_AUTH_SHARED_KEY_GET)) != NULL && e != GFARM_ERR_EXPIRED) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_sharedsecret: .gfarm_shared_key", e); } else if (time(0) >= expire) { /* may reach here if (e == GFARM_ERR_EXPIRED) */ error = GFARM_AUTH_ERROR_EXPIRED; gflog_warning("auth_sharedsecret", "key expired"); } else { /* may also reach here if (e == GFARM_ERR_EXPIRED) */ gfarm_auth_sharedsecret_response_data( shared_key_expected, challenge, response_expected); if (expire != expire_expected) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_sharedsecret", "expire time mismatch"); } else if (memcmp(response, response_expected, sizeof(response)) != 0) { error = GFARM_AUTH_ERROR_INVALID_CREDENTIAL; gflog_error("auth_sharedsecret", "key mismatch"); } else { /* success */ error = GFARM_AUTH_ERROR_NO_ERROR; } } e = xxx_proto_send(conn, "i", error); if (e != NULL) { gflog_error("auth_sharedsecret: send result", e); return (e); } if (error == GFARM_AUTH_ERROR_NO_ERROR) { e = xxx_proto_flush(conn); if (e != NULL) { gflog_error("auth_sharedsecret: completion",e); return (e); } return (NULL); /* success */ } } } char * gfarm_authorize_sharedsecret(struct xxx_connection *conn, int switch_to, char *hostname, char **global_usernamep) { char *e, *global_username, *local_username, *aux, *msg; int eof; struct passwd *pwd; uid_t o_uid; gid_t o_gid; static char method[] = "auth=sharedsecret local_user="; #ifdef __GNUC__ /* workaround gcc warning: unused variable */ o_uid = o_gid = 0; #endif e = xxx_proto_recv(conn, 0, &eof, "s", &global_username); if (e != NULL) { gflog_error("authorize_sharedsecret", "reading username"); return (e); } if (eof) { gflog_error("authorize_sharedsecret", "unexpected EOF"); return (GFARM_ERR_PROTOCOL); } aux = malloc(strlen(global_username) + 1 + strlen(hostname) + 1); if (aux == NULL) { gflog_error("authorize_sharedsecret", GFARM_ERR_NO_MEMORY); return (GFARM_ERR_NO_MEMORY); } sprintf(aux, "%s@%s", global_username, hostname); gflog_set_auxiliary_info(aux); e = gfarm_global_to_local_username(global_username, &local_username); if (e != NULL) { pwd = NULL; gflog_error("authorize_sharedsecret", "cannot map global username into local username"); } else { pwd = getpwnam(local_username); if (pwd == NULL) gflog_error(local_username, "authorize_sharedsecret: " "local account doesn't exist"); } if (pwd != NULL) { /* * first, switch to the user's privilege * to read ~/.gfarm_shared_key. * * NOTE: reading this file with root privilege may not work, * if home directory is NFS mounted and root access for * the home directory partition is not permitted. * * Do not switch the user ID of the current process here * even in the switch_to case, because it is necessary to * switch back to the original user ID when * gfarm_auth_sharedsecret fails. */ o_gid = getegid(); o_uid = geteuid(); initgroups(pwd->pw_name, pwd->pw_gid); setegid(pwd->pw_gid); seteuid(pwd->pw_uid); } e = gfarm_auth_sharedsecret_response(conn, pwd == NULL ? NULL : pwd->pw_dir); if (pwd != NULL) { setegid(o_gid); seteuid(o_uid); } if (e == NULL) { /* succeed, do logging */ msg = malloc(sizeof(method) + strlen(local_username)); if (msg == NULL) { e = GFARM_ERR_NO_MEMORY; gflog_error("authorize_sharedsecret: ", e); } else { sprintf(msg, "%s%s", method, local_username); gflog_notice("authenticated", msg); free(msg); } } /* if (pwd == NULL), (e != NULL) must be true here */ if (e != NULL) { free(gflog_get_auxiliary_info()); gflog_set_auxiliary_info(NULL); free(global_username); if (local_username != NULL) free(local_username); return (e); } if (switch_to) { /* * because the name returned by getlogin() is * an attribute of a session on 4.4BSD derived OSs, * we should create new session before calling * setlogin(). */ setsid(); #ifdef HAVE_SETLOGIN setlogin(pwd->pw_name); #endif setgid(pwd->pw_gid); setuid(pwd->pw_uid); /* assert(local_username != NULL); */ gfarm_set_global_username(global_username); gfarm_set_local_username(local_username); gfarm_set_local_homedir(pwd->pw_dir); } else { gflog_set_auxiliary_info(NULL); free(aux); } free(local_username); if (global_usernamep != NULL) *global_usernamep = global_username; else free(global_username); return (NULL); } /* * the `switch_to' flag has the following side effects: * - the privilege of this program will switch to the authenticated user. * - gflog_set_auxiliary_info("user@hostname") will be called. * thus, the caller of gfarm_authorize() must call the following later: * char *aux = gflog_get_auxiliary_info(); * gflog_get_auxiliary_info(NULL); * free(aux); * - gfarm_get_local_username(), gfarm_get_local_homedir() and * gfarm_get_global_username() become available. * * note that the user's account is not always necessary on this host, * if the `switch_to' flag isn't set. but also note that some * authentication methods (e.g. "sharedsecret") require the user's * local account anyway even if the `switch_to' isn't set. */ char * gfarm_authorize(struct xxx_connection *conn, int switch_to, char **global_usernamep, char **hostnamep, enum gfarm_auth_method *auth_methodp) { char *e, *hostname; gfarm_int32_t methods; /* bitset of enum gfarm_auth_method */ gfarm_int32_t method; /* enum gfarm_auth_method */ gfarm_int32_t error; /* enum gfarm_auth_error */ struct sockaddr addr; socklen_t addrlen = sizeof(addr); int rv = getpeername(xxx_connection_fd(conn), &addr, &addrlen); int i, eof, try = 0; size_t nmethods; unsigned char methods_buffer[CHAR_BIT * sizeof(gfarm_int32_t)]; char addr_string[GFARM_SOCKADDR_STRLEN]; assert(GFARM_ARRAY_LENGTH(gfarm_authorization_table) == GFARM_AUTH_METHOD_NUMBER); if (rv == -1) { e = gfarm_errno_to_error(errno); gflog_error("authorize: getpeername", e); return (e); } e = gfarm_sockaddr_to_name(&addr, &hostname); if (e != NULL) { gfarm_sockaddr_to_string(&addr, addr_string, GFARM_SOCKADDR_STRLEN); gflog_warning(addr_string, e); hostname = strdup(addr_string); if (hostname == NULL) { gflog_warning(addr_string, GFARM_ERR_NO_MEMORY); return (GFARM_ERR_NO_MEMORY); } } methods = gfarm_auth_method_get_enabled_by_name_addr(hostname, &addr); if (methods == 0) { gflog_error(hostname, "refusing access"); } else { methods &= gfarm_auth_method_get_available(); if (methods == 0) gflog_error(hostname, "auth-method not configured"); } nmethods = 0; for (i = GFARM_AUTH_METHOD_NONE + 1; i < GFARM_AUTH_METHOD_NUMBER && i < CHAR_BIT * sizeof(gfarm_int32_t); i++) { if ((methods & (1 << i)) != 0) methods_buffer[nmethods++] = i; } e = xxx_proto_send(conn, "b", nmethods, methods_buffer); if (e != NULL) { gflog_error(hostname, e); free(hostname); return (e); } for (;;) { ++try; e = xxx_proto_recv(conn, 0, &eof, "i", &method); if (e != NULL) { gflog_error(hostname, e); free(hostname); return (e); } if (eof) { if (try <= 1) gflog_warning(hostname, "port scan"); else gflog_warning(hostname, "client disappeared"); free(hostname); return (GFARM_ERR_PROTOCOL); } if (method == GFARM_AUTH_METHOD_NONE) error = GFARM_AUTH_ERROR_NO_ERROR; else if (method >= GFARM_AUTH_METHOD_NUMBER) error = GFARM_AUTH_ERROR_NOT_SUPPORTED; else if (method <= GFARM_AUTH_METHOD_NONE || ((1 << method) & methods) == 0) error = GFARM_AUTH_ERROR_DENIED; else error = GFARM_AUTH_ERROR_NO_ERROR; e = xxx_proto_send(conn, "i", error); if (e == NULL) e = xxx_proto_flush(conn); if (e != NULL) { gflog_error(hostname, e); free(hostname); return (e); } if (error != GFARM_AUTH_ERROR_NO_ERROR) { gflog_error(hostname, "incorrect auth-method request"); free(hostname); return (GFARM_ERR_PROTOCOL); } if (method == GFARM_AUTH_METHOD_NONE) { /* client gave up */ if (methods == 0) { e = GFARM_ERR_PERMISSION_DENIED; } else if (try <= 1) { /* * there is no usable auth-method * between client and server. */ gflog_notice(hostname, "authentication method " "doesn't match"); e = GFARM_ERR_PROTOCOL_NOT_SUPPORTED; } else { e = GFARM_ERR_AUTHENTICATION; } free(hostname); return (e); } e = (*gfarm_authorization_table[method])(conn, switch_to, hostname, global_usernamep); if (e != GFARM_ERR_PROTOCOL_NOT_SUPPORTED && e != GFARM_ERR_EXPIRED && e != GFARM_ERR_AUTHENTICATION) { /* protocol error, or success */ if (e != NULL || hostnamep == NULL) free(hostname); else *hostnamep = hostname; if (e == NULL) { if (auth_methodp != NULL) *auth_methodp = method; } return (e); } } } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_5/Makefile.am bin_PROGRAMS = gfarm2fs gfarm2fs_fix_acl gfarm2fs_SOURCES = gfarm2fs.c acl.c id.c replicate.c open_file.c xattr.c \ gfarm2fs.h acl.h id.h replicate.h open_file.h gfarm2fs_msg_enums.h \ hash.h xattr.h gfarm2fs_fix_acl_SOURCES = gfarm2fs_fix_acl.c acl.h xattr.h gfarm2fs.h dist_bin_SCRIPTS = gfarm2fs_fix_acl.sh man_MANS = gfarm2fs.1 EXTRA_DIST = RELNOTES LICENSE gfarm2fs.spec $(man_MANS) $(private_srcs) AM_CFLAGS = -Wall ACLOCAL_AMFLAGS = -I m4 # # gflog message number assignment # msgno: assign_msgno ASSIGNMSGNO=$(top_srcdir)/msgno/assign_msgno.pl assign_msgno: GFARM_TOPDIR=$(top_srcdir) $(ASSIGNMSGNO) $(gfarm2fs_SOURCES) # # private sources # private-src-link: @if test "x$(top_private_dir)" != "x"; then \ for i in $(private_srcs); do \ if test ! -r ./$${i} -a \ -r $(top_private_dir)/$${i}; then \ ln -s $(top_private_dir)/$${i} . ; \ fi ; \ done ; \ fi private-src-unlink: @if test "x$(top_private_dir)" != "x"; then \ for i in $(private_srcs); do \ if test -L ./$${i}; then \ $(RM) ./$${i} ; \ fi ; \ done ; \ fi install-private: $(bin_PROGRAMS) if test "x$(top_private_dir)" != "x"; then \ for i in $(bin_PROGRAMS); do \ $(binPROGRAMS_INSTALL) $$i \ $(DESTDIR)$(bindir)/$${i}_private ; \ done ; \ fi gfarm2fs.c: private-src-link distclean-local: private-src-unlink <file_sep>/gfarm/tags/gfarm_1_1_1/debian/gfsd.postinst #!/bin/sh -e . /usr/share/debconf/confmodule echo 'Run /usr/sbin/config-gfsd, if you want to setup gfsd for Gfarm filesystem filesysm node. Please see /usr/share/gfsd/doc/INSTALL.RPM.* for more details.' >&2 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT-config #! /bin/sh . ./FT-common $gfservice -k config-gfarm-master gfmd1 # # Configure gfmd servers. # I=2 while [ "X`eval echo \\$gfmd$I`" != X ]; do $gfservice config-gfarm-slave gfmd$I gfmd1 I=`expr $I + 1` done # # Configure gfsd servers. # I=1 while [ "X`eval echo \\$gfsd$I`" != X ]; do $gfservice config-gfsd gfsd$I I=`expr $I + 1` done # # Configure clients. # I=1 while [ "X`eval echo \\$client$I`" != X ]; do $gfservice config-client client$I I=`expr $I + 1` done # # Create ~/.pgpass for Zabbix agent. # TMP_GFMD_CONF=/tmp/ftconfig.$$ TMP_PGPASS=/tmp/pgpass.$$ rm -f $TMP_GFMD_CONF $TMP_PGPASS trap "rm -f $TMP_GFMD_CONF $TMP_PGPASS; exit 1" 1 2 3 15 I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do rm -f $TMP_GFMD_CONF $TMP_PGPASS gfmd=`eval echo \\$gfmd$I` $gfservice backup-gfmd-conf gfmd$I > $TMP_GFMD_CONF awk '/^postgresql_server_host[ ]/ {host=$2} /^postgresql_server_port[ ]/ {port=$2} /^postgresql_dbname[ ]/ {db=$2} /^postgresql_user[ ]/ {user=$2} /^postgresql_password[ ]/ {gsub(/\"/, "", $2); passwd=$2} END {printf("%s:%s:%s:%s:%s\n", host, port, db, user, passwd)}' \ $TMP_GFMD_CONF > $TMP_PGPASS ssh $gfmd tee .pgpass < $TMP_PGPASS > /dev/null I=`expr $I + 1` done rm -f $TMP_GFMD_CONF $TMP_PGPASS # # Create zbx_failover.conf. # FAILOVER_CONF_DIR=/etc/zabbix/externalscripts FAILOVER_CONF_FILE=zbx_failover.conf rm -f $FAILOVER_CONF_FILE ( echo "#" echo "# This file is created by FT-config." echo "#" I=1 while [ "X`eval echo \\$gfmd$I`" != X ]; do echo "[gfmd$I]" echo "host=`$gfservice get-config-gfarm-param \ gfmd$I BACKEND_HOSTNAME`" echo "gfmd_listen_port=`$gfservice get-config-gfarm-param \ gfmd$I GFMD_PORT`" echo "gfmd_pid_file=`$gfservice get-config-gfarm-param \ gfmd$I GFMD_PID_FILE`" echo "gfmd_journal_file=`$gfservice get-config-gfarm-param \ gfmd$I METADATA_JOURNAL_DIR`/0000000000.gmj" [ "X`eval echo \\$gfmd${I}_GFBINDIR`" != X ] && \ echo "gfarm_bindir=`eval echo \\$gfmd${I}_GFBINDIR`" [ "X`eval echo \\$gfmd${I}_SSH`" != X ] && \ echo "ssh=`eval echo \\$gfmd${I}_SSH`" [ "X`eval echo \\$gfmd${I}_SUDO`" != X ] && \ echo "sudo=`eval echo \\$gfmd${I}_SUDO`" echo I=`expr $I + 1` done ) > $FAILOVER_CONF_FILE if cmp -s $FAILOVER_CONF_DIR/$FAILOVER_CONF_FILE $FAILOVER_CONF_FILE; then true else ( echo "The file '$FAILOVER_CONF_FILE' might have to be updated" echo "To update it, type the following command:" echo " cp $FAILOVER_CONF_FILE $FAILOVER_CONF_DIR/$FAILOVER_CONF_FILE" ) 1>&2 fi exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/gfarm-zabbix_redundancy/mds_list/html/download.php <?php $filepath = "files/gfarm2.conf"; header('Content-Disposition: attachment; filename="'.basename($filepath).'"'); //header('Content-Type: application/octet-stream'); header('Content-Type: text/plain'); //header('Content-Transfer-Encoding: binary'); header('Content-Transfer-Encoding: 8bit'); header('Content-Length: '.filesize($filepath)); readfile($filepath); ?> <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_redundancy/mds_list/html/regist.php <?php /* ** regist.php ** ** A PHP script for checking Gfarm2 client configuration file ** uploaded by upload.html. **/ ?> <?php function get_additional_config() { $cmd = "zbx_generate_mdslist.sh"; $result = shell_exec("$cmd"); return $result; } function edit_config_file($filepath) { $result = get_additional_config(); $fp = fopen($filepath, "a"); $line = "\n" . $result; fwrite($fp, $line); fclose($fp); return 0; } function check_config_file($filepath) { $cmd = "zbx_check_gfarm2_conf.sh"; $result = shell_exec("$cmd $filepath"); return $result; } function display_text_file($filepath, $name) { echo "<textarea name=\"$name\" cols=100 rows=10 readonly>"; readfile($filepath); echo "</textarea>"; } function display_download_button() { echo "<form name=\"filedownload\" method=\"POST\" enctype=\"multipart/form-data\" action=\"download.php\">"; echo "<input type=\"submit\" name=\"download\" value=\"Download\" />"; echo "</form>"; } function display_back_button() { echo "<form name=\"back\" action=\"upload.html\">"; echo "<input type=\"submit\" name=\"back\" value=\"Back\" />"; echo "</form>"; } function download_config_file($filepath) { header('Content-Disposition: attachment; filename="'.basename($filepath).'"'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.filesize($filepath)); readfile($filepath); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>gfarm2.conf sample generator</title> </head> <body> <p><?php $tmp_name = $_FILES["upfile"]["tmp_name"]; $name = $_FILES["upfile"]["name"]; $path = "files/" . "gfarm2.conf"; if (! is_uploaded_file($tmp_name)) { echo "ファイルが選択されていません。"; display_back_button(); return 1; } if (! move_uploaded_file($tmp_name, $path)) { echo "ファイルをアップロードできません。"; display_back_button(); return 1; } /* set permission */ chmod($path, 0644); /* generate configuration file */ edit_config_file($path); /* print the generated file */ echo "以下の Gfarm2 クライアント設定ファイルを生成しました。<br />"; display_text_file($path, "gfarm2.conf"); echo "<br />"; /* check configuration file */ $chk_res = check_config_file($path); if (strncmp($chk_res, "success", 7) == 0) { /* download button */ display_download_button(); } else { if (strncmp($chk_res, "timeout", 7) == 0) { echo "<br />"; echo "Gfarm2 クライアント設定ファイル確認環境に問題があります($chk_res)。<br />"; } else { echo "<br />"; echo "アップロードされた Gfarm2 クライアント設定ファイルが不正です($chk_res)。<br />"; } $errfile="/tmp/gfls_error.txt"; display_text_file($errfile, "error_msg"); } /* back button */ display_back_button(); ?></p> </body> </html> <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfmdlist_cli.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1 exit 0 fi OLD_MDS_LIST_PATH=$MDS_LIST_PATH.old TMP_MDS_LIST_PATH=$MDS_LIST_PATH.tmp rm -f $TMP_MDS_LIST_PATH trap "rm -f $TMP_MDS_LIST_PATH; exit 1" 1 2 3 15 # get a list of gmfd servers. gfmdhost -l > $TMP_MDS_LIST_PATH if [ $? -ne 0 ]; then echo "error: gfmdhost -l error." exit 0 fi # check whether the list is changed. if [ -f $MDS_LIST_PATH ]; then cp -f $MDS_LIST_PATH $OLD_MDS_LIST_PATH if cmp $MDS_LIST_PATH $TMP_MDS_LIST_PATH > /dev/null 2>&1; then CHECK_STATUS=same else CHECK_STATUS=changed fi else CHECK_STATUS=nonexist fi # output a result message and update $MDS_LIST_PATH file if needed. case "$CHECK_STATUS" in same) rm -f $TMP_MDS_LIST_PATH echo "gfmdhost -l same." ;; changed) mv -f $TMP_MDS_LIST_PATH $MDS_LIST_PATH echo "gfmdhost -l changed." ;; nonexist) mv -f $TMP_MDS_LIST_PATH $MDS_LIST_PATH echo "gfmdhost -l same." ;; esac exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc3/lib/libgfarm/gfarm/io_gfsl.c /* * iobuffer operation: GSI communication: GFSL / Globus GSS API / OpenSSL */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <gssapi.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfarm_secure_session.h" #include "iobuffer.h" #include "xxx_proto.h" #include "io_fd.h" #include "io_gfsl.h" /* * for "gsi" method */ struct io_gfsl { gfarmSecSession *session; gfarmExportedCredential *exported_credential; /* for read */ char *buffer; int p, residual; }; /* * only blocking i/o is available. */ int gfarm_iobuffer_read_secsession_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { struct io_gfsl *io = cookie; int rv; if (io->buffer == NULL) { int flag = fcntl(fd, F_GETFL, NULL); /* temporary drop O_NONBLOCK flag to prevent EAGAIN */ if (flag & O_NONBLOCK) fcntl(fd, F_SETFL, flag & ~O_NONBLOCK); rv = gfarmSecSessionReceiveInt8(io->session, &io->buffer, &io->residual); if (flag & O_NONBLOCK) fcntl(fd, F_SETFL, flag); if (rv <= 0) { /* XXX - interpret io->session->gssLastStat */ gfarm_iobuffer_set_error(b, GFARM_ERR_UNKNOWN); return (rv); } io->p = 0; } if (io->residual <= length) { rv = io->residual; memcpy(data, &io->buffer[io->p], rv); free(io->buffer); io->buffer = NULL; io->p = io->residual = 0; } else { rv = length; memcpy(data, &io->buffer[io->p], rv); io->p += rv; io->residual -= rv; } return (rv); } int gfarm_iobuffer_write_secsession_op(struct gfarm_iobuffer *b, void *cookie, int fd, void *data, int length) { struct io_gfsl *io = cookie; int rv, flag = fcntl(fd, F_GETFL, NULL); /* temporary drop O_NONBLOCK flag to prevent EAGAIN */ if (flag & O_NONBLOCK) fcntl(fd, F_SETFL, flag & ~O_NONBLOCK); rv = gfarmSecSessionSendInt8(io->session, data, length); if (flag & O_NONBLOCK) fcntl(fd, F_SETFL, flag); if (rv <= 0) { /* XXX - interpret io->session->gssLastStat */ gfarm_iobuffer_set_error(b, GFARM_ERR_UNKNOWN); } return (rv); } static void free_secsession(struct io_gfsl *io) { gfarmSecSessionTerminate(io->session); if (io->buffer != NULL) free(io->buffer); free(io); } /* * xxx_connection operation */ char * xxx_iobuffer_close_secsession_op(void *cookie, int fd) { int rv; char *e = NULL; free_secsession(cookie); rv = close(fd); if (rv == -1) e = gfarm_errno_to_error(errno); return (e); } char * xxx_iobuffer_export_credential_secsession_op(void *cookie) { struct io_gfsl *io = cookie; OM_uint32 e_major; gss_cred_id_t cred; cred = gfarmSecSessionGetDelegatedCredential(io->session); if (cred == GSS_C_NO_CREDENTIAL) return ("GSI delegated credential doesn't exist"); io->exported_credential = gfarmGssExportCredential(cred, &e_major); if (io->exported_credential == NULL) return ("cannot export GSI delegated credential"); return (NULL); } char * xxx_iobuffer_delete_credential_secsession_op(void *cookie) { struct io_gfsl *io = cookie; if (io->exported_credential == NULL) return (NULL); gfarmGssDeleteExportedCredential(io->exported_credential); io->exported_credential = NULL; return (NULL); } char * xxx_iobuffer_env_for_credential_secsession_op(void *cookie) { struct io_gfsl *io = cookie; if (io->exported_credential == NULL) return (NULL); return (gfarmGssEnvForExportedCredential(io->exported_credential)); } struct xxx_iobuffer_ops xxx_secsession_iobuffer_ops = { xxx_iobuffer_close_secsession_op, xxx_iobuffer_export_credential_secsession_op, xxx_iobuffer_delete_credential_secsession_op, xxx_iobuffer_env_for_credential_secsession_op, gfarm_iobuffer_read_secsession_op, gfarm_iobuffer_write_secsession_op, gfarm_iobuffer_read_secsession_op, gfarm_iobuffer_write_secsession_op }; char * xxx_connection_set_secsession(struct xxx_connection *conn, gfarmSecSession *secsession) { struct io_gfsl *io = malloc(sizeof(struct io_gfsl)); if (io == NULL) return (GFARM_ERR_NO_MEMORY); io->session = secsession; io->exported_credential = NULL; io->buffer = NULL; io->p = io->residual = 0; xxx_connection_set(conn, &xxx_secsession_iobuffer_ops, io, secsession->fd); return (NULL); } /* free resources which were allocated by xxx_connection_set_secsession() */ void xxx_connection_reset_secsession(struct xxx_connection *conn) { struct io_gfsl *io = xxx_connection_cookie(conn); if (io != NULL) free_secsession(io); xxx_connection_set(conn, &xxx_secsession_iobuffer_ops, NULL, -1); } /* * an option for gfarm_iobuffer_set_write_close() */ void gfarm_iobuffer_write_close_secsession_op(struct gfarm_iobuffer *b, void *cookie, int fd) { struct io_gfsl *io = cookie; char *e = xxx_iobuffer_close_secsession_op(io, fd); if (e != NULL && gfarm_iobuffer_get_error(b) == 0) gfarm_iobuffer_set_error(b, e); } /* * for "gsi_auth" method */ struct xxx_iobuffer_ops xxx_insecure_gsi_session_iobuffer_ops = { xxx_iobuffer_close_secsession_op, xxx_iobuffer_export_credential_secsession_op, xxx_iobuffer_delete_credential_secsession_op, xxx_iobuffer_env_for_credential_secsession_op, /* NOTE: the following assumes that these functions don't use cookie */ gfarm_iobuffer_nonblocking_read_fd_op, gfarm_iobuffer_nonblocking_write_fd_op, gfarm_iobuffer_blocking_read_fd_op, gfarm_iobuffer_blocking_write_fd_op }; /* * downgrade * from a "gsi" connection which is created by xxx_connection_set_secsession() * to a "gsi_auth" connection. */ void xxx_connection_downgrade_to_insecure_session(struct xxx_connection *conn) { xxx_connection_set(conn, &xxx_insecure_gsi_session_iobuffer_ops, xxx_connection_cookie(conn), xxx_connection_fd(conn)); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/malloc.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc,char *argv[]) { size_t total, used, buffer, cached, size, i; int period; char *mem; if (argc != 6) { printf("USAGE: malloc total used buffer cached period \n"); printf(" malloc `free | grep Mem | awk '{print $2, $3, $6, $7}'` period\n"); exit(1); } total = atol(argv[1]); printf("total : %8ld\n", total); if (total <= 0) { printf("ERROR: total <= 0\n"); exit(1); } used = atol(argv[2]); printf("used : %8ld\n", used); if (used <= 0) { printf("ERROR: used <= 0\n"); exit(1); } buffer = atol(argv[3]); printf("buffer : %8ld\n", buffer); if (buffer <= 0) { printf("ERROR: buffer <= 0\n"); exit(1); } cached = atol(argv[4]); printf("cached : %8ld\n", cached); if (cached <= 0) { printf("ERROR: cached <= 0\n"); exit(1); } period = atoi(argv[5]); printf("period : %8d\n", period); if (period <= 0) { printf("ERROR: period <= 0\n"); exit(1); } /* sum size */ size = (size_t)((double)(total + buffer + cached) * 0.97) - used; printf("size : %8ld\n", size); /* allocate */ mem = (char *)malloc(size); if(mem == NULL) { printf("ERROR: allocation failed.\n"); exit(1); } printf("success to allocation\n"); /* write something */ for (i = 0; i < size; i++) { mem[i] = 0; } printf("success to write.\n"); /* wait for period */ sleep(period); printf("bye!.\n"); return 0; } <file_sep>/gfarm/tags/gfarm_1_0_beta_1/include/gfarm/gfarm.h #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_stringlist.h> #include <gfarm/gfs_glob.h> #include <gfarm/gfs.h> #include <gfarm/gfarm_metadb.h> #include <gfarm/gfarm_misc.h> <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfarm/auth.h enum gfarm_auth_error { GFARM_AUTH_ERROR_NO_ERROR, GFARM_AUTH_ERROR_DENIED, GFARM_AUTH_ERROR_NOT_SUPPORTED, GFARM_AUTH_ERROR_INVALID_CREDENTIAL, GFARM_AUTH_ERROR_EXPIRED }; enum gfarm_auth_method { GFARM_AUTH_METHOD_NONE, /* never used */ GFARM_AUTH_METHOD_SIMPLE, GFARM_AUTH_METHOD_GSI, GFARM_AUTH_METHOD_NUMBER }; #define GFARM_AUTH_METHOD_ALL GFARM_AUTH_METHOD_NONE /* * GFARM_AUTH_METHOD_SIMPLE dependent constants. * note that this is too weak authentication for the Internet. */ void gfarm_auth_random(void *, size_t); void gfarm_auth_simple_response_data(char *, char *, char *); char *gfarm_auth_shared_key_get(unsigned int *, char *, char *, int); #define GFARM_AUTH_SHARED_KEY_GET 0 #define GFARM_AUTH_SHARED_KEY_CREATE 1 #define GFARM_AUTH_SHARED_KEY_CREATE_FORCE 2 /* request */ enum gfarm_auth_simple_request { GFARM_AUTH_SIMPLE_GIVEUP, GFARM_AUTH_SIMPLE_MD5 }; /* key */ #define GFARM_AUTH_RETRY_MAX 2 #define GFARM_AUTH_SHARED_KEY_LEN 32 #define GFARM_AUTH_CHALLENGE_LEN 32 #define GFARM_AUTH_RESPONSE_LEN 16 /* length of MD5 */ struct xxx_connection; struct sockaddr; char *gfarm_auth_request(struct xxx_connection *, char *, struct sockaddr *); char *gfarm_authorize(struct xxx_connection *, int, char **); /* auth config */ struct gfarm_hostspec; char *gfarm_auth_method_parse(char *, enum gfarm_auth_method *); char *gfarm_auth_enable(enum gfarm_auth_method, struct gfarm_hostspec *); char *gfarm_auth_disable(enum gfarm_auth_method, struct gfarm_hostspec *); /* this i/f have to be changed, if we support more than 31 auth methods */ gfarm_int32_t gfarm_auth_method_get_enabled_by_name_addr( char *, struct sockaddr *); gfarm_int32_t gfarm_auth_method_get_available(void); <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_redundancy_cli.sh #!/bin/sh # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_gfarm.conf # Check Config File if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # Check metadata server list if [ ! -f $MDS_LIST_PATH ]; then echo -1; exit 0; fi # exec check command RESULT=`grep "^+ \+slave \+sync \+c \+" $MDS_LIST_PATH | wc -l` echo $RESULT exit 0 <file_sep>/gfarm/branches/gfarm/gftool/config-gfarm/sysdep/linux/redhat/gfsd.in #!/bin/bash # # Init file for Gfarm filesystem daemon # # chkconfig: 2345 95 05 # description: Gfarm filesystem daemon # # processname: gfsd # config: @config_gfarm_gfarm_config@ # pidfile: @config_gfarm_run_dir@/gfsd.pid # # $Id$ gfarm_prefix=@config_gfarm_prefix@ prog="gfsd" # source function library . /etc/rc.d/init.d/functions OPTIONS=@config_gfarm_gfsd_option@ RETVAL=0 # Some functions to make the below more readable BINARY=$gfarm_prefix/sbin/$prog PID_FILE=@config_gfarm_run_dir@/${prog}.pid start() { echo -n $"Starting $prog:" initlog -c "$BINARY -P $PID_FILE $OPTIONS" && success || failure RETVAL=$? [ "$RETVAL" = 0 ] && touch @config_gfarm_lock_dir@/$prog echo } stop() { echo -n $"Stopping $prog:" if [ -f $PID_FILE ]; then kill -TERM `cat $PID_FILE` && success || failure rm -f $PID_FILE else killproc $prog -TERM fi RETVAL=$? [ "$RETVAL" = 0 ] && rm -f @config_gfarm_lock_dir@/$prog echo } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) status $BINARY RETVAL=$? ;; *) echo $"Usage: $0 {start|stop|restart|status}" RETVAL=1 esac exit $RETVAL <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT2-1-3-1_gfsd_down #! /bin/sh ###################################################################### TESTID="FT2-1-3-1" CATEGORY="1 point accident" SECTION="gfsd accident" TITLE="gfsd down" ###################################################################### . ./FT-common ft_setup() { ssh $client1 mkdir -p mnt $gfservice unmount client1 mnt $gfservice mount client1 mnt -o nonempty ssh $client1 rm -f mnt/a.txt mnt/b.txt return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 sh -c 'echo aaa > mnt/a.txt' \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "create a text file on Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfsd gfsd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfsd on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfsd does not listen on $gfsd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox $gfservice start-gfsd gfsd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "restart gfsd on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfsd does not listen on $gfsd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { $gfservice umount client1 mnt $gfservice start-gfsd gfsd1 return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc2/lib/gfs_hook/hooks_stat.c /* * stat * * $Id$ */ extern int gfarm_node; #ifndef _STAT_VER int FUNC___STAT(const char *path, STRUCT_STAT *buf) { const char *e; char *url; struct gfs_stat gs; int nf = -1, np; #if 0 char *canonic_path, *abs_path; int r, save_errno; #endif _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___STAT) "(%s)\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_STAT(path, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___STAT) "(%s)\n", path)); #if 1 switch (gfs_hook_get_current_view()) { case section_view: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_SECTION) "(%s, %s)\n", url, gfs_hook_get_current_section())); e = GFS_STAT_SECTION(url, gfs_hook_get_current_section(), &gs); break; case index_view: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_INDEX) "(%s, %d)\n", url, gfs_hook_get_current_index())); e = GFS_STAT_INDEX(url, gfs_hook_get_current_index(), &gs); break; case local_view: /* * If the number of fragments is not the same as the * number of parallel processes, or the file is not * fragmented, do not change to the local file view. */ if (gfarm_url_fragment_number(url, &nf) == NULL) { if (gfs_pio_get_node_size(&np) == NULL && nf == np) { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_INDEX) "(%s, %d)\n", url, gfarm_node)); e = GFS_STAT_INDEX(url, gfarm_node, &gs); } else { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } } else { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } if (e != NULL) { /* someone is possibly creating the file right now */ /* * XXX - there is no way to determine other * processes are now creating the * corresponding section or not in Gfarm v1. * However, at least, it is possible to * determine this process is now creating the * section or not. */ GFS_File gf; if ((gf = gfs_hook_is_now_creating(url)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: gfs_fstat(%p (%s))\n", gf, url)); e = gfs_fstat(gf, &gs); } else e = GFARM_ERR_NO_SUCH_OBJECT; } break; default: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } free(url); if (e == NULL) { struct passwd *p; buf->st_dev = GFS_DEV; buf->st_ino = gs.st_ino; buf->st_mode = gs.st_mode; buf->st_nlink = 1; /* XXX FIXME: need to convert gfarm global user to UNIX uid */ p = getpwnam(gfarm_get_local_username()); if (p != NULL) { buf->st_uid = p->pw_uid; buf->st_gid = p->pw_gid; } else { buf->st_uid = getuid(); /* XXX */ buf->st_gid = getgid(); /* XXX */ } buf->st_size = gs.st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = gs.st_atimespec.tv_sec; buf->st_mtime = gs.st_mtimespec.tv_sec; buf->st_ctime = gs.st_ctimespec.tv_sec; gfs_stat_free(&gs); return (0); } _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___STAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); #else /* Temporary code until gfs_stat() will be implemented. */ /* * gfs_stat() may not appropriate here, because: * 1. it doesn't/can't fill all necessary field of struct stat. * 2. it returns information of whole gfarm file, rather than * information of the fragment. */ e = gfarm_url_make_path(url, &canonic_path); free(url); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } e = gfarm_path_localize_file_fragment(canonic_path, gfarm_node, &abs_path); free(canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___STAT) " locally: %s\n", abs_path)); r = SYSCALL_STAT(abs_path, buf); save_errno = errno; free(abs_path); errno = save_errno; return (r); #endif } int FUNC__STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC__STAT) ": %s\n", path)); return (FUNC___STAT(path, buf)); } int FUNC_STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_STAT) ": %s\n", path)); return (FUNC___STAT(path, buf)); } #else /* defined(_STAT_VER) -- SVR4 or Linux */ /* * SVR4 and Linux do inline stat() and call _xstat/__xstat() with * an additional version argument. */ #ifdef __linux__ /* * unlike SVR4, stat() on linux seems to be compatible with xstat(STAT_VER,...) */ int FUNC___STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug_v( fprintf(stderr, "Hooking " S(FUNC___STAT) ": %s\n", path)); return (FUNC___XSTAT(_STAT_VER, path, buf)); } int FUNC_STAT(const char *path, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_STAT) ": %s\n", path)); return (FUNC___XSTAT(_STAT_VER, path, buf)); } #else /* * we don't provide stat(), because it is only used for SVR3 compat code. */ #endif int FUNC___XSTAT(int ver, const char *path, STRUCT_STAT *buf) { const char *e; char *url; struct gfs_stat gs; int nf = -1, np; #if 0 char *canonic_path, *abs_path; int r, save_errno; #endif _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___XSTAT) "(%s)\n", path)); if (!gfs_hook_is_url(path, &url)) return (SYSCALL_XSTAT(ver, path, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___XSTAT) "(%s)\n", path)); #if 1 switch (gfs_hook_get_current_view()) { case section_view: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_SECTION) "(%s, %s)\n", url, gfs_hook_get_current_section())); e = GFS_STAT_SECTION(url, gfs_hook_get_current_section(), &gs); break; case index_view: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_INDEX) "(%s, %d)\n", url, gfs_hook_get_current_index())); e = GFS_STAT_INDEX(url, gfs_hook_get_current_index(), &gs); break; case local_view: /* * If the number of fragments is not the same as the * number of parallel processes, or the file is not * fragmented, do not change to the local file view. */ if (gfarm_url_fragment_number(url, &nf) == NULL) { if (gfs_pio_get_node_size(&np) == NULL && nf == np) { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT_INDEX) "(%s, %d)\n", url, gfarm_node)); e = GFS_STAT_INDEX(url, gfarm_node, &gs); } else { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } } else { _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } if (e != NULL) { /* someone is possibly creating the file right now */ /* * XXX - there is no way to determine other * processes are now creating the corresponding * section or not. However, at least, it is * possible to determine this process is now * creating the section or not. */ GFS_File gf; if ((gf = gfs_hook_is_now_creating(url)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: gfs_fstat(%p (%s))\n", gf, url)); e = gfs_fstat(gf, &gs); } else e = GFARM_ERR_NO_SUCH_OBJECT; } break; default: _gfs_hook_debug(fprintf(stderr, "GFS: " S(GFS_STAT) "(%s)\n", url)); e = GFS_STAT(url, &gs); } free(url); if (e == NULL) { struct passwd *p; buf->st_dev = GFS_DEV; buf->st_ino = gs.st_ino; buf->st_mode = gs.st_mode; buf->st_nlink = 1; /* XXX FIXME: need to convert gfarm global user to UNIX uid */ p = getpwnam(gfarm_get_local_username()); if (p != NULL) { buf->st_uid = p->pw_uid; buf->st_gid = p->pw_gid; } else { buf->st_uid = getuid(); /* XXX */ buf->st_gid = getgid(); /* XXX */ } buf->st_size = gs.st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = gs.st_atimespec.tv_sec; buf->st_mtime = gs.st_mtimespec.tv_sec; buf->st_ctime = gs.st_ctimespec.tv_sec; gfs_stat_free(&gs); return (0); } _gfs_hook_debug(fprintf(stderr, "GFS: " S(FUNC___XSTAT) ": %s\n", e)); errno = gfarm_error_to_errno(e); return (-1); #else /* Temporary code until gfs_stat() will be implemented. */ e = gfarm_url_make_path(url, &canonic_path); free(url); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } e = gfarm_path_localize_file_fragment(canonic_path, gfarm_node, &abs_path); free(canonic_path); if (e != NULL) { errno = gfarm_error_to_errno(e); return (-1); } _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___XSTAT) " locally: %s\n", abs_path)); r = SYSCALL_XSTAT(ver, abs_path, buf); save_errno = errno; free(abs_path); errno = save_errno; return (r); #endif } int FUNC__XSTAT(int ver, const char *path, STRUCT_STAT *buf) { _gfs_hook_debug_v( fprintf(stderr, "Hooking " S(FUNC__XSTAT) ": %s\n", path)); return (FUNC___XSTAT(ver, path, buf)); } #endif /* SVR4 or Linux */ <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_gfsd_gfhost.sh.in #! /bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on gfsd hosts. # It tries executing 'gfhost' to check whether it can connect with # other gfsd servers and succeeds in authentication. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile1=/tmp/gfarm_gfsd_gfhost.out1.$$ outfile2=/tmp/gfarm_gfsd_gfhost.out2.$$ errfile=/tmp/gfarm_gfsd_gfhost.err.$$ trap "rm -f $outfile1 $outfile2 $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile1 $outfile2 $errfile # # Execute 'gfsched' to get a list of running 'gfsd'. # GFCMD="@GFARM_BINDIR@/gfsched -M" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > $outfile1 2> $errfile GFCMD_EXITCODE=$? if [ $GFCMD_EXITCODE -ne 0 ]; then # We ignore the execution failure itself, since too many alerts will # be triggered if each file system node reports the failure. echo "ok" if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then log_warning "'$GFCMD' failed, timeout" else log_warning "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" fi [ -s $errfile ] && head -1 $errfile | log_err rm -f $outfile1 $outfile2 $errfile exit 0 fi # # Check whether 'gfsched' outputs a list of servers correctly. # if [ ! -s $outfile1 ]; then echo "ok" log_warning "'$GFCMD' outputs no data" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile1 $outfile2 $errfile exit 0 fi # # Execute 'gfhost'. # rm -f $errfile GFCMD="@GFARM_BINDIR@/gfhost -lv" sudo -n -u _gfarmfs @GFARM_BINDIR@/gfservice-timeout $TIMEOUT \ $GFCMD `cat $outfile1` > $outfile2 2> $errfile GFCMD_EXITCODE=$? if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then echo "'$GFCMD' failed, timeout" log_err "'$GFCMD' failed, timeout" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile1 $outfile2 $errfile exit 0 elif [ $GFCMD_EXITCODE -ne 0 ]; then # We ignore the execution failure itself, since too many alerts will # be triggered if each file system node reports the failure. echo "ok" log_warning "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile1 $outfile2 $errfile exit 0 fi # # Check whether 'gfhost' outputs a list of servers correctly. # if [ ! -s $outfile2 ]; then echo "ok" log_warning "'$GFCMD' outputs no data" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile1 $outfile2 $errfile exit 0 fi # # Check the result data of 'gfhost'. # awk ' BEGIN { auth_fail_gfsds = "" } { if ($2 == "x") { if (auth_fail_gfsds == "") auth_fail_gfsds = $5 else auth_fail_gfsds = auth_fail_gfsds ", " $5 } } END { if (auth_fail_gfsds != "") print "auth failed: " auth_fail_gfsds else print "ok" }' $outfile2 rm -f $outfile1 $outfile2 $errfile exit 0 <file_sep>/gfarm/tags/gfarm_1_0_2_rc1/server/gfsd/loadavg.c #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <gfarm/gfarm_config.h> /* * getloadavg() function may require root user or kmem group privilege * on some OSes. */ #ifndef HAVE_GETLOADAVG #if defined(__linux__) int getloadavg(double *loadavg, int n) { int i, rv; char buffer[30]; double ldavg[3]; static int fd = -1; if (fd < 0) { if (fd != -2) /* known to be failed */ fd = open("/proc/loadavg", O_RDONLY); } if (fd < 0) { fd = -2; /* known to be failed */ return (-1); } lseek(fd, SEEK_SET, 0L); rv = read(fd, buffer, sizeof(buffer) - 1); if (rv <= 0) return (-1); buffer[rv] = '\0'; ldavg[0] = ldavg[1] = ldavg[2] = 0.0; rv = sscanf(buffer, "%lf %lf %lf", &ldavg[0], &ldavg[1], &ldavg[2]); if (n > rv) n = rv; for (i = 0; i < n; i++) loadavg[i] = ldavg[i]; return (n); } #endif /* __linux__ */ #if defined(__osf__) #include <sys/table.h> int getloadavg(double *loadavg, int n) { int i; struct tbl_loadavg ldavg; if (table(TBL_LOADAVG, 0, &ldavg, 1, sizeof(ldavg)) == -1) return (-1); if (ldavg.tl_lscale == 0) { for (i = 0; i < n; i++) loadavg[i] = ldavg.tl_avenrun.d[i]; } else { for (i = 0; i < n; i++) loadavg[i] = (double)ldavg.tl_avenrun.l[i] / ldavg.tl_lscale; } return (n); } #endif /* __osf__ */ #endif /* !HAVE_GETLOADAVG */ #ifdef LOADAVG_TEST main() { double loadavg[3]; getloadavg(loadavg, 3); printf("%lf %lf %lf\n", loadavg[0], loadavg[1], loadavg[2]); } #endif <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_generic_client_gfmdhost.sh.in #!/bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on generic client hosts. # It tries executing 'gfmdhost' to check whether it can connect with # the master gfmd and succeeds in authentication. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile=/tmp/gfarm_generic_client_gfmdhost.out.$$ errfile=/tmp/gfarm_generic_client_gfmdhost.err.$$ trap "rm -f $outfile $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile $errfile # # Execute 'gfmdhost'. # GFCMD="@GFARM_BINDIR@/gfmdhost -l" @GFARM_BINDIR@/gfservice-timeout $TIMEOUT $GFCMD > $outfile 2> $errfile GFCMD_EXITCODE=$? if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then # We ignore timeout, since too many alerts will be triggered # if each generic clients report it. echo "ok" log_warning "'$GFCMD' failed, timeout" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 elif [ $GFCMD_EXITCODE -ne 0 ]; then echo "'$GFCMD' failed" log_err "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi # # Check whether 'gfmdhost' outputs something. # if [ ! -s $outfile ]; then echo "ok" log_warning "'$GFCMD' outputs no data" [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi echo "ok" rm -f $outfile $errfile exit 0 <file_sep>/gfarm/tags/gfarm_1_0_beta_2/package/solaris/gfsd.in #!/sbin/sh # # $Id$ GFSD=@prefix@/sbin/gfsd # workaround a problem that "ld -R" doesn't work with indirectly dependent SOs if [ -n "@globus_location@" ]; then LD_LIBRARY_PATH=@globus_location@/lib export LD_LIBRARY_PATH fi case "$1" in 'start') if [ -x $GFSD -a -f /etc/gfarm.conf ]; then $GFSD fi ;; 'stop') /usr/bin/pkill -x -u 0 gfsd ;; *) echo "Usage: $0 { start | stop }" exit 1 ;; esac exit 0 <file_sep>/gfarm/tags/gfarm_1_0_rc2/lib/gfs_hook/hooks_64.c #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> #include "hooks_subr.h" #include <sys/syscall.h> /* * The following hooks are not implemented: * * _LFS64_ASYNCHRONOUS_IO APIs * aio_cancel64() * aio_error64() * aio_fsync64() * aio_read64() * aio_return64() * aio_suspend64() * aio_write64() * lio_listio64() * * _LFS64_LARGEFILE APIs * ftruncate64() * lockf64() * mmap64() * readdir64() * truncate64() * */ /* * definitions for "hooks_common.c" */ int gfs_hook_syscall_open64(const char *path, int oflag, mode_t mode) { #ifdef SYS_open64 return (syscall(SYS_open64, path, oflag, mode)); #else return (gfs_hook_syscall_open(path, oflag | O_LARGEFILE, mode)); #endif } int gfs_hook_syscall_creat64(const char *path, mode_t mode) { #ifdef SYS_creat64 return (syscall(SYS_creat64, path, mode)); #else return (gfs_hook_syscall_open64(path, O_CREAT|O_TRUNC|O_WRONLY, mode)); #endif } /* see lseek64.c for gfs_hook_syscall_lseek64() implementation */ int gfs_hook_syscall_stat64(const char *path, struct stat64 *buf) { #ifndef _STAT_VER return (syscall(SYS_stat64, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_xstat64(_STAT_VER, path, buf)); #endif } int gfs_hook_syscall_lstat64(const char *path, struct stat64 *buf) { #ifndef _STAT_VER return (syscall(SYS_lstat64, path, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_lxstat64(_STAT_VER, path, buf)); #endif } int gfs_hook_syscall_fstat64(int filedes, struct stat64 *buf) { #ifndef _STAT_VER return (syscall(SYS_fstat64, filedes, buf)); #else /* SVR4 or Linux */ return (gfs_hook_syscall_fxstat64(_STAT_VER, filedes, buf)); #endif } /* * for SVR4. * * (see sysdep/linux/xstat64.c about Linux) */ #if defined(_STAT_VER) && defined(SYS_xstat) int gfs_hook_syscall_xstat64(int ver, const char *path, struct stat64 *buf) { #if defined(__sgi) && _MIPS_SIM == _ABIN32 /* ABI N32 */ return (gfs_hook_syscall_xstat(SYS_xstat, _STAT_VER, path, buf)); #else return (gfs_hook_syscall_xstat(SYS_xstat, _STAT64_VER, path, buf)); #endif } int gfs_hook_syscall_lxstat64(int ver, const char *path, struct stat64 *buf) { #if defined(__sgi) && _MIPS_SIM == _ABIN32 /* ABI N32 */ return (gfs_hook_syscall_lxstat(SYS_lxstat, _STAT_VER, path, buf)); #else return (gfs_hook_syscall_lxstat(SYS_lxstat, _STAT64_VER, path, buf)); #endif } int gfs_hook_syscall_fxstat64(int ver, int filedes, struct stat64 *buf) { #if defined(__sgi) && _MIPS_SIM == _ABIN32 /* ABI N32 */ return (gfs_hook_syscall_fxstat(SYS_fxstat, _STAT_VER, filedes, buf)); #else return (gfs_hook_syscall_fxstat(SYS_fxstat, _STAT64_VER, filedes, buf)); #endif } #endif #define OFF_T off64_t #define SYSCALL_OPEN(path, oflag, mode) \ gfs_hook_syscall_open64(path, oflag, mode) #define SYSCALL_CREAT(path, mode) \ gfs_hook_syscall_creat64(path, mode) #define SYSCALL_LSEEK(filedes, offset, whence) \ gfs_hook_syscall_lseek64(filedes, offset, whence) #define FUNC___OPEN __open64 #define FUNC__OPEN _open64 #define FUNC_OPEN open64 #define FUNC___CREAT __creat64 #define FUNC__CREAT _creat64 #define FUNC_CREAT creat64 #define FUNC___LSEEK __lseek64 #define FUNC__LSEEK _lseek64 #define FUNC_LSEEK lseek64 #include "hooks_common.c" /* stat */ #define STRUCT_STAT struct stat64 #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_stat64(path, buf) #define FUNC___STAT __stat64 #define FUNC__STAT _stat64 #define FUNC_STAT stat64 #define GFS_STAT gfs_stat #define GFS_STAT_SECTION gfs_stat_section #define GFS_STAT_INDEX gfs_stat_index #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_xstat64(ver, path, buf) #define FUNC___XSTAT __xstat64 #define FUNC__XSTAT _xstat64 #define FUNC_XSTAT xstat64 #endif #include "hooks_stat.c" #undef SYSCALL_STAT #undef FUNC___STAT #undef FUNC__STAT #undef FUNC_STAT #undef GFS_STAT #ifdef _STAT_VER /* SVR4 or Linux */ #undef SYSCALL_XSTAT #undef FUNC___XSTAT #undef FUNC__XSTAT #undef FUNC_XSTAT #endif /* lstat */ #define SYSCALL_STAT(path, buf) \ gfs_hook_syscall_lstat64(path, buf) #define FUNC___STAT __lstat64 #define FUNC__STAT _lstat64 #define FUNC_STAT lstat64 #define GFS_STAT gfs_stat /* XXX - gfs_lstat in not implemented yet */ #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_XSTAT(ver, path, buf) \ gfs_hook_syscall_lxstat64(ver, path, buf) #define FUNC___XSTAT __lxstat64 #define FUNC__XSTAT _lxstat64 #define FUNC_XSTAT lxstat64 #endif #include "hooks_stat.c" /* fstat */ #define SYSCALL_FSTAT(path, buf) \ gfs_hook_syscall_fstat64(path, buf) #define FUNC___FSTAT __fstat64 #define FUNC__FSTAT _fstat64 #define FUNC_FSTAT fstat64 #define GFS_FSTAT gfs_fstat #ifdef _STAT_VER /* SVR4 or Linux */ #define SYSCALL_FXSTAT(ver, fd, buf) \ gfs_hook_syscall_fxstat64(ver, fd, buf) #define FUNC___FXSTAT __fxstat64 #define FUNC__FXSTAT _fxstat64 #define FUNC_FXSTAT fxstat64 #endif #include "hooks_fstat.c" #if defined(SYS_llseek) || defined(SYS__llseek) /* * llseek */ OFF_T __llseek(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " "__llseek" ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } OFF_T _llseek(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " "_llseek" ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } OFF_T llseek(int filedes, OFF_T offset, int whence) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " "llseek" ": %d\n", filedes)); return (FUNC___LSEEK(filedes, offset, whence)); } #endif /* defined(SYS_llseek) || defined(SYS__llseek) */ <file_sep>/gfarm_samba/trunk/gfarm_id.h /* * $Id$ */ gfarm_error_t gfarm_id_init( gfarm_uint32_t, gfarm_uint32_t, gfarm_uint32_t, gfarm_uint32_t, int); gfarm_error_t gfarm_id_user_to_uid(const char *, const char *, uid_t *); gfarm_error_t gfarm_id_group_to_gid(const char *, const char *, gid_t *); gfarm_error_t gfarm_id_uid_to_user(const char *, uid_t, char **); gfarm_error_t gfarm_id_gid_to_group(const char *, gid_t, char **); uid_t gfarm_id_nobody_uid(void); gid_t gfarm_id_nogroup_gid(void); <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/gfs_hook/lseek64.c /* * $Id$ * * The reason that this source file is separated from hooks_64.c is that * llseek/lseek64 needs special syscall() prototype to return 64bit value. */ #define syscall syscall_original /* avoid "int syscall()" function prototype */ #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #undef syscall #include "hooks_subr.h" off64_t syscall(); /* * XXX - not really tested. */ off64_t gfs_hook_syscall_lseek64(int filedes, off64_t offset, int whence) { #if defined(SYS_lseek64) return (syscall(SYS_lseek64, filedes, offset, whence)); #elif defined(SYS_llseek) return (syscall(SYS_llseek, filedes, (int)(offset >> 32), (int)offset, whence)); #elif defined(SYS__llseek) /* linux */ off64_t rv, result; rv = syscall(SYS__llseek, filedes, (int)(offset >>32), (int)offset, &result, whence); return (rv ? rv : result); #else #error do not know how to implement lseek64 #endif } <file_sep>/gfarm/tags/gfarm_1_1_1_rc6/gftool/gfexec/gfexec.c /* * $Id$ */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <libgen.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <gfarm/gfarm.h> #include <openssl/evp.h> /* "gfs_pio.h" needs this for now */ #include "gfs_pio.h" #define PROGRAM_NAME "gfexec" static char progname[] = PROGRAM_NAME; #define BOURNE_SHELL "/bin/sh" static void print_usage() { fprintf(stderr, "usage: %s <program> [-N <nodes>] [-I <index>] [-s] " "<args> ...\n", progname); exit(2); } char * search_path(char *command) { int command_len, dir_len; char *result, *path; struct stat st; char buf[PATH_MAX]; if (strchr(command, '/') != NULL) { /* absolute or relative path */ result = command; goto finish; } command_len = strlen(command); path = getenv("PATH"); if (path == NULL) path = "/bin:/usr/bin:/usr/ucb:/usr/local/bin"; do { dir_len = strcspn(path, ":"); if (dir_len == 0) { if (command_len + 1 > sizeof(buf)) { fprintf(stderr, "%s: %s: path too long\n", progname, command); exit(1); } result = command; } else { if (dir_len + command_len + 2 > sizeof(buf)) { fprintf(stderr, "%s: %s: path too long (%s)\n", progname, command, path); exit(1); } memcpy(buf, path, dir_len); buf[dir_len] = '/'; strcpy(buf + dir_len + 1, command); result = buf; } if (access(result, X_OK) == 0 && stat(result, &st) == 0 && (st.st_mode & S_IFMT) == S_IFREG) goto finish; path += dir_len; } while (*path++ == ':'); /* not found in $PATH */ result = command; finish: result = strdup(result); if (result == NULL) { fprintf(stderr, "%s: no memory\n", progname); exit(1); } return (result); } /* * Shared objects in gfarm file system cannot be dynamically linked * because _dl_*() defined in /lib/ld-linux cannot be hooked. * So, we replicate shared objects to local machine and rewrite paths in * LD_LIBRARY_PATH to local spool directory path, for example, * /gfarm/lib -> /var/spool/gfarm/lib. */ /* XXX - the following two static functions are defined in hooks_subr.c. */ static char gfs_mntdir[] = "/gfarm"; static int is_null_or_slash(const char c) { return (c == '\0' || c == '/' || c == ':'); } static int is_mount_point(const char *path) { return (*path == '/' && memcmp(path, gfs_mntdir, sizeof(gfs_mntdir) - 1) == 0 && is_null_or_slash(path[sizeof(gfs_mntdir) - 1])); } static char * gfarm_url_localize(char *url, char **local_path) { char *e, *canonic_path; *local_path = NULL; e = gfarm_url_make_path(url, &canonic_path); if (e != NULL) return (e); e = gfarm_path_localize(canonic_path, local_path); free(canonic_path); return (e); } /* convert to the canonical path */ static char * gfs_mntpath_canonicalize(char *dir, size_t size, char **canonic_path) { char *e, *gfarm_file; *canonic_path = NULL; dir += sizeof(gfs_mntdir) - 1; size -= sizeof(gfs_mntdir) - 1; /* in '/gfarm/~' case, skip the first '/' */ if (dir[0] == '/' && dir[1] == '~') { ++dir; --size; } /* * in '/gfarm' case, just convert to '\0'. * ':' is a separator of the environment variable. */ else if (dir[0] == '\0' || dir[0] == ':') { *canonic_path = strdup(""); if (*canonic_path == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } gfarm_file = malloc(size + 1); if (gfarm_file == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(gfarm_file, "%.*s", (int)size, dir); e = gfarm_canonical_path(gfarm_file, canonic_path); free(gfarm_file); return (e); } static char * gfs_mntpath_localize(char *dir, size_t size, char **local_path) { char *e, *canonic_path; *local_path = NULL; e = gfs_mntpath_canonicalize(dir, size, &canonic_path); if (e != NULL) return (e); e = gfarm_path_localize(canonic_path, local_path); free(canonic_path); return (e); } static char * replicate_so_and_symlink(char *dir, size_t size) { char *canonic_path, *gfarm_url, *so_pat, *lpath; char *e, *e_save; int i, rv; gfarm_stringlist paths; gfs_glob_t types; static char so_pat_template[] = "/*.so*"; e = gfs_mntpath_canonicalize(dir, size, &canonic_path); if (e != NULL) return (e); e = gfarm_path_canonical_to_url(canonic_path, &gfarm_url); free(canonic_path); if (e != NULL) return (e); so_pat = malloc(strlen(gfarm_url) + sizeof(so_pat_template)); if (so_pat == NULL) { free(gfarm_url); return (GFARM_ERR_NO_MEMORY); } sprintf(so_pat, "%s%s", gfarm_url, so_pat_template); free(gfarm_url); e_save = gfarm_stringlist_init(&paths); if (e_save != NULL) goto free_so_pat; e_save = gfs_glob_init(&types); if (e_save != NULL) goto free_paths; e_save = gfs_glob(so_pat, &paths, &types); if (e_save != NULL) goto free_types; /* XXX - should replicate so files in parallel */ for (i = 0; i < gfarm_stringlist_length(&paths); i++) { char *gfarm_so, *local_so; gfarm_so = gfarm_stringlist_elem(&paths, i); if (strcmp(gfarm_so, so_pat) == 0) /* no "*.so*" file in dir */ break; e = gfarm_url_execfile_replicate_to_local(gfarm_so, &lpath); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_so, e); if (e_save == NULL) e_save = e; if (e == GFARM_ERR_NO_MEMORY) break; continue; } /* create a symlink */ e = gfarm_url_localize(gfarm_so, &local_so); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_so, e); if (e_save == NULL) e_save = e; if (e == GFARM_ERR_NO_MEMORY) break; free(lpath); continue; } unlink(local_so); rv = symlink(lpath, local_so); if (rv == -1) { perror(local_so); if (e_save == NULL) e_save = gfarm_errno_to_error(errno); } free(local_so); free(lpath); } free_types: gfs_glob_free(&types); free_paths: gfarm_stringlist_free_deeply(&paths); free_so_pat: free(so_pat); return (e_save); } static char * alloc_ldpath(size_t size) { static char *ldpath = NULL; static int ldpath_len = 0; if (ldpath_len < size) { char *p; p = realloc(ldpath, size); if (p == NULL) return (NULL); ldpath = p; ldpath_len = size; } return (ldpath); } static char * modify_ld_library_path(void) { char *e, *e_save = NULL, *ldpath, *nldpath; static char env_ldlibpath[] = "LD_LIBRARY_PATH"; size_t len, dirlen; int rv; ldpath = getenv(env_ldlibpath); if (ldpath == NULL) return (NULL); len = sizeof(env_ldlibpath) + 1; nldpath = alloc_ldpath(1024); /* specify bigger size than len */ if (nldpath == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(nldpath, "%s=", env_ldlibpath); while (*ldpath != '\0') { char *local_dir; int is_valid_local_dir = 0; dirlen = strcspn(ldpath, ":"); if (is_mount_point(ldpath)) { e = gfs_mntpath_localize(ldpath, dirlen, &local_dir); if (e != NULL) { if (e != GFARM_ERR_NO_SUCH_OBJECT) { if (e_save == NULL) e_save = e; } goto skip_copying; } e = replicate_so_and_symlink(ldpath, dirlen); if (e != NULL) if (e_save == NULL) e_save = e; len += strlen(local_dir); is_valid_local_dir = 1; } else len += dirlen; nldpath = alloc_ldpath(len); if (nldpath == NULL) { if (is_valid_local_dir) free(local_dir); return (GFARM_ERR_NO_MEMORY); } if (is_valid_local_dir) { strcat(nldpath, local_dir); free(local_dir); } else strncat(nldpath, ldpath, dirlen); skip_copying: ldpath += dirlen; if (*ldpath) { ++len; nldpath = alloc_ldpath(len); if (nldpath == NULL) return (GFARM_ERR_NO_MEMORY); strncat(nldpath, ldpath, 1); ++ldpath; } } rv = putenv(nldpath); if (rv == -1) return (gfarm_errno_to_error(errno)); return (e_save); } static void errmsg(char *func, char *msg) { fprintf(stderr, "%s (%s): %s: %s\n", gfarm_host_get_self_name(), progname, func, msg); } int main(int argc, char *argv[], char *envp[]) { char *e, *gfarm_url, *local_path, **new_env, *cwd_env, *pwd_env; int i, j, status, envc, rank = -1, nodes = -1; pid_t pid; static const char env_node_rank[] = "GFARM_NODE_RANK="; static const char env_node_size[] = "GFARM_NODE_SIZE="; static const char env_flags[] = "GFARM_FLAGS="; static const char env_gfs_pwd[] = "<PASSWORD>="; static const char env_pwd[] = "PWD="; char rankbuf[sizeof(env_node_rank) + GFARM_INT64STRLEN]; char nodesbuf[sizeof(env_node_size) + GFARM_INT64STRLEN]; char flagsbuf[sizeof(env_flags) + 3]; char cwdbuf[PATH_MAX * 2], pwdbuf[PATH_MAX * 2]; e = gfarm_initialize(&argc, &argv); if (e != NULL) { errmsg("gfarm_initialize", e); exit(1); } /* * don't use getopt(3) here, because getopt(3) in glibc refers * argv[] passed to main(), instead of argv[] passed to getopt(3). */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; for (j = 1; argv[i][j] != '\0'; j++) { switch (argv[i][j]) { case 'I': if (argv[i][j + 1] != '\0') { rank = strtol(&argv[i][j+1], NULL, 0); j += strlen(&argv[i][j + 1]); } else if (i + 1 < argc) { rank = strtol(argv[++i], NULL, 0); j = strlen(argv[i]) - 1; } else { errmsg("-I", "missing argument"); print_usage(); } break; case 'N': if (argv[i][j + 1] != '\0') { nodes = strtol(&argv[i][j+1], NULL, 0); j += strlen(&argv[i][j + 1]); } else if (i + 1 < argc) { nodes = strtol(argv[++i], NULL, 0); j = strlen(argv[i]) - 1; } else { errmsg("-N", "missing argument"); print_usage(); } break; case 's': rank = 0; nodes = 1; break; case 'h': case '?': print_usage(); default: fprintf(stderr, "%s: invalid option -- %c\n", progname, argv[i][j]); print_usage(); } } } argc -= i; argv += i; if (argc == 0) print_usage(); e = gfs_realpath(argv[0], &gfarm_url); if (e != NULL) { /* XXX check `e' */ local_path = search_path(argv[0]); } else { e = gfarm_url_program_get_local_path(gfarm_url, &local_path); if (e != NULL) { errmsg(gfarm_url, e); exit(1); } } e = modify_ld_library_path(); if (e != NULL) { errmsg("modify_ld_library_path", e); /* continue */ } /* * the followings are only needed for pid==0 case. * but isn't it better to check errors before fork(2)? * * If gfs_pio_get_node_{rank,size}() fails, continue to * execute as a single process (not parallel processes). */ if (rank == -1) { e = gfs_pio_get_node_rank(&rank); if (e != NULL) rank = 0; } if (nodes == -1) { e = gfs_pio_get_node_size(&nodes); if (e != NULL) nodes = 1; } for (envc = 0; envp[envc] != NULL; envc++) ; new_env = malloc(sizeof(*new_env) * (envc + 5 + 1)); memcpy(cwdbuf, GFARM_URL_PREFIX, GFARM_URL_PREFIX_LENGTH); e = gfs_getcwd(cwdbuf + GFARM_URL_PREFIX_LENGTH, sizeof(cwdbuf) - GFARM_URL_PREFIX_LENGTH); if (e != NULL) { errmsg("cannot get current directory", e); exit(1); } if ((cwd_env = malloc(strlen(cwdbuf) + sizeof(env_gfs_pwd))) == NULL) { fprintf(stderr, "%s: no memory for %s%s\n", progname, env_gfs_pwd, cwdbuf); exit(1); } (void)chdir(cwdbuf); /* rely on syscall hook. it is ok if it fails */ getcwd(pwdbuf, sizeof pwdbuf); pwd_env = malloc(strlen(pwdbuf) + sizeof(env_pwd)); if (pwd_env == NULL) { fprintf(stderr, "%s: no memory for %s%s\n", progname, env_pwd, pwdbuf); exit(1); } envc = 0; for (i = 0; (e = envp[i]) != NULL; i++) { if (memcmp(e, env_node_rank, sizeof(env_node_rank) -1 ) != 0 && memcmp(e, env_node_size, sizeof(env_node_size) -1 ) != 0 && memcmp(e, env_flags, sizeof(env_flags) - 1 ) != 0 && memcmp(e, env_gfs_pwd, sizeof(env_gfs_pwd) - 1) != 0 && memcmp(e, env_pwd, sizeof(env_pwd) - 1 ) != 0) new_env[envc++] = e; } sprintf(rankbuf, "%s%d", env_node_rank, rank); new_env[envc++] = rankbuf; sprintf(nodesbuf, "%s%d", env_node_size, nodes); new_env[envc++] = nodesbuf; sprintf(flagsbuf, "%s%s%s%s", env_flags, gf_profile ? "p" : "", gf_on_demand_replication ? "r" : "", gf_hook_default_global ? "g" : ""); new_env[envc++] = flagsbuf; sprintf(cwd_env, "%s%s", env_gfs_pwd, cwdbuf); new_env[envc++] = cwd_env; sprintf(pwd_env, "%s%s", env_pwd, pwdbuf); new_env[envc++] = pwd_env; new_env[envc++] = NULL; if (gf_stdout == NULL && gf_stderr == NULL) { /* what we need is to call exec(2) */ pid = 0; } else { /* * we have to call fork(2) and exec(2), to close * gf_stdout and gf_stderr by calling gfarm_terminate() * after the child program finished. */ pid = fork(); } switch (pid) { case -1: perror(PROGRAM_NAME ": fork"); status = 255; break; case 0: if (gf_stdout == NULL && gf_stderr == NULL) { /* * not to display profile statistics * on gfarm_terminate() */ gfs_profile(gf_profile = 0); e = gfarm_terminate(); if (e != NULL) errmsg("(child) gfarm_terminate", e); } else { /* * otherwise don't call gfarm_terminate(), because: * - it closes gf_stdout and gf_stderr. * - it causes: * "gfarm_terminate: Can't contact LDAP server" * on the parent process. */ } execve(local_path, argv, new_env); if (errno != ENOEXEC) { perror(local_path); } else { /* * argv[-1] must be available, * because there should be "gfexec" at least. */ argv[-1] = BOURNE_SHELL; argv[0] = local_path; execve(BOURNE_SHELL, argv - 1, new_env); } _exit(255); default: if (waitpid(pid, &status, 0) == -1) { perror(PROGRAM_NAME ": waitpid"); status = 255; } else if (WIFSIGNALED(status)) { fprintf(stderr, "%s: signal %d received%s.\n", gfarm_host_get_self_name(), WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); status = 255; } else { status = WEXITSTATUS(status); } break; } /* not to display profile statistics on gfarm_terminate() */ gfs_profile(gf_profile = 0); e = gfarm_terminate(); if (e != NULL) { errmsg("gfarm_terminate", e); exit(1); } exit(status); } <file_sep>/gfarm/branches/metadb_dev/man/ja/man3/Makefile # $Id$ top_objdir = ../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk include $(srcdir)/../Makefile.inc MAN = \ GFARM_STRINGLIST_ELEM.3 \ GFARM_STRINGLIST_STRARRAY.3 \ gfarm_hostlist_read.3 \ gfarm_import_fragment_config_read.3 \ gfarm_import_fragment_size_alloc.3 \ gfarm_initialize.3 \ gfarm_stringlist_add.3 \ gfarm_stringlist_cat.3 \ gfarm_stringlist_elem.3 \ gfarm_stringlist_free.3 \ gfarm_stringlist_free_deeply.3 \ gfarm_stringlist_init.3 \ gfarm_stringlist_length.3 \ gfarm_strings_free_deeply.3 \ gfarm_terminate.3 \ gfarm_url_hosts_schedule.3 \ gfs_chmod.3 \ gfs_chown.3 \ gfs_closedir.3 \ gfs_mkdir.3 \ gfs_opendir.3 \ gfs_pio_close.3 \ gfs_pio_create.3 \ gfs_pio_eof.3 \ gfs_pio_error.3 \ gfs_pio_flush.3 \ gfs_pio_getc.3 \ gfs_pio_getline.3 \ gfs_pio_open.3 \ gfs_pio_putc.3 \ gfs_pio_putline.3 \ gfs_pio_puts.3 \ gfs_pio_read.3 \ gfs_pio_seek.3 \ gfs_pio_set_local.3 \ gfs_pio_set_view_index.3 \ gfs_pio_set_view_local.3 \ gfs_pio_ungetc.3 \ gfs_pio_write.3 \ gfs_readdir.3 \ gfs_rename.3 \ gfs_rmdir.3 \ gfs_stat.3 \ gfs_stat_free.3 \ gfs_unlink.3 include $(top_srcdir)/makes/man.mk <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT2-2-2-1_master_gfmd_and_master_candidate_gfmd_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-1" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd and master candidate gfmd down" ###################################################################### . ./FT-common ft_setup() { MASTER_CANDIDATE=`ft_get_master_candidate` [ $? -ne 0 ] && return $FT_RESULT_FAIL [ "X$MASTER_CANDIDATE" = X ] && return $FT_RESULT_FAIL MASTER_CANDIDATE_NAME=`eval echo \\$$MASTER_CANDIDATE` return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS gfmdhost -l > /dev/null 2>&1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "gfmdhost -l" $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd $MASTER_CANDIDATE \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "stop gfmd on $MASTER_CANDIDATE_NAME" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "slave gfmd is not running on $MASTER_CANDIDATE_NAME" \ "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/branches/1.2.1/replicate.c /* * $Id$ */ #include "config.h" #ifdef HAVE_PRIVATE_SRCS /* replace replicate.c with replicate_private.c */ #include "replicate_private.c" #else /* ! HAVE_PRIVATE_SRCS */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <libgen.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/time.h> /* * fuse.h requres that _FILE_OFFSET_BITS is defined in any case, but * AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 * since it is not necessary. To avoid this problem we define it here. */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #define FUSE_USE_VERSION 25 #include <fuse.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include <gfarm2fs.h> #include "gfarm2fs_msg_enums.h" #ifdef HAVE_GFS_REPLICATE_FILE_TO #define gfs_replicate_to(file, dsthost, dstport) \ gfs_replicate_file_to(file, dsthost, 0) #endif static int replicate_ncopy; static int replicate_max_concurrency; volatile sig_atomic_t replicate_concurrency = 0; static int replicate_enabled; #define XATTR_NCOPY "gfarm.ncopy" /* * #define UNSAFE_DEBUG * * Since gflog_info() is not async-signal-safe, * UNSAFE_DEBUG shouldn't be defined. */ static void sigchld_handler(int sig) { int pid, status; #ifdef UNSAFE_DEBUG int no; char *msg; #endif for (;;) { pid = waitpid(-1, &status, WNOHANG); if (pid == -1 || pid == 0) break; --replicate_concurrency; #ifdef UNSAFE_DEBUG if (WIFEXITED(status)) { msg = "exit"; no = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { msg = "killed by signal"; no = WTERMSIG(status); } else { msg = "unknown status"; no = status; } gflog_info(GFARM_MSG_2000041, "replicate [%d]: %s %d", pid, msg, no); #endif } } static int available_nhosts; static struct gfarm_host_sched_info *available_hosts; static struct timeval available_host_cache_time; static const char *schedule_path = GFARM_PATH_ROOT; static int is_expired(int expiration) { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec > available_host_cache_time.tv_sec + expiration); } static gfarm_error_t update_schedule_info(const char *domain) { gfarm_error_t e; if (available_hosts != NULL) gfarm_host_sched_info_free(available_nhosts, available_hosts); available_hosts = NULL; e = gfarm_schedule_hosts_domain_all(schedule_path, domain, &available_nhosts, &available_hosts); gettimeofday(&available_host_cache_time, NULL); return (e); } void gfarm2fs_replicate_init(struct gfarm2fs_param *param) { struct sigaction sa; char *domain = ""; gfarm_error_t e; if (param->ncopy < 2 || param->copy_limit < 0) return; e = update_schedule_info(domain); if (e != GFARM_ERR_NO_ERROR) return; replicate_ncopy = param->ncopy; replicate_max_concurrency = param->copy_limit; sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_NOCLDSTOP; sigaction(SIGCHLD, &sa, NULL); replicate_enabled = 1; } void gfarm2fs_replicate_final(void) { if (available_hosts != NULL) gfarm_host_sched_info_free(available_nhosts, available_hosts); } static int get_required_ncopy(const char *path) { int ncopy = replicate_ncopy; #if defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) char *p, *ep, s_ncopy[GFARM_INT32STRLEN]; size_t size_ncopy; gfarm_error_t e; int nc; p = strdup(path); if (p == NULL) return (ncopy); for (;;) { size_ncopy = sizeof(s_ncopy); e = gfs_getxattr(p, XATTR_NCOPY, s_ncopy, &size_ncopy); if (e == GFARM_ERR_NO_ERROR) { s_ncopy[size_ncopy] = '\0'; nc = strtol(s_ncopy, &ep, 10); if (*ep == '\0') { ncopy = nc; break; } } if (p[0] == '/' && p[1] == '\0') break; p = dirname(p); } free(p); #endif return (ncopy); } static int stat_ncopy(const char *path) { struct gfs_stat st; gfarm_error_t e; int ncopy; e = gfs_lstat_cached(path, &st); if (e == GFARM_ERR_NO_ERROR) { ncopy = st.st_ncopy; gfs_stat_free(&st); return (ncopy); } return (0); } static gfarm_error_t select_nhosts(int *nhosts, char ***hostsp, int **portsp) { char **hosts, *domain = ""; int *ports, expiration = 60; /* 60 sec */ gfarm_error_t e; if (is_expired(expiration)) { e = update_schedule_info(domain); if (e != GFARM_ERR_NO_ERROR) return (e); } GFARM_MALLOC_ARRAY(hosts, *nhosts); if (hosts == NULL) return (GFARM_ERR_NO_MEMORY); GFARM_MALLOC_ARRAY(ports, *nhosts); if (ports == NULL) { free(hosts); return (GFARM_ERR_NO_MEMORY); } e = gfarm_schedule_hosts_acyclic_to_write(schedule_path, available_nhosts, available_hosts, nhosts, hosts, ports); if (e != GFARM_ERR_NO_ERROR) { free(hosts); free(ports); } else { *hostsp = hosts; *portsp = ports; } return (e); } static gfarm_error_t replicate_file(const char *path, int ncopy, int ndsts, char **dsts, int *ports) { int i, n = 0; gfarm_error_t e = GFARM_ERR_NO_ERROR; for (i = 0; i < ndsts && n < ncopy; ++i) { e = gfs_replicate_to(path, dsts[i], ports[i]); if (e == GFARM_ERR_NO_ERROR || e == GFARM_ERR_OPERATION_NOW_IN_PROGRESS) ++n; else if (e == GFARM_ERR_ALREADY_EXISTS) /* skip */; else { gflog_error(GFARM_MSG_2000047, "%s: replicataion to %s:%d fails: %s", path, dsts[i], ports[i], gfarm_error_string(e)); break; } } return (n == ncopy ? GFARM_ERR_NO_ERROR : e); } void gfarm2fs_replicate(const char *path, struct fuse_file_info *fi) { int ncopy, cur_ncopy, n, pid, *ports; int wait = 0, max_wait = 10; char **dsts; gfarm_error_t e; if (!replicate_enabled) return; /* if necessary number of copies is less than 2, return */ ncopy = get_required_ncopy(path); if (ncopy < 2) return; /* if it has enough number of copies, return */ cur_ncopy = stat_ncopy(path); if (ncopy <= cur_ncopy) return; /* if enough number of replication processes are in process, wait */ while (replicate_max_concurrency > 0 && replicate_concurrency >= replicate_max_concurrency && wait++ < max_wait) sleep(1); if (wait >= max_wait) { gflog_error(GFARM_MSG_2000045, "%s: too busy to replicate", path); return; } /* at most ncopy hosts required */ n = ncopy; e = select_nhosts(&n, &dsts, &ports); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_2000048, "%s: failed to schedule hosts", path); return; } /* create 'ncopy - cur_ncopy' copies */ if (replicate_max_concurrency == 0) { gflog_info(GFARM_MSG_2000049, "replicate: %s ncopy %d (required %d)", path, n, ncopy); e = replicate_file(path, ncopy - cur_ncopy, n, dsts, ports); free(dsts); free(ports); return; } switch ((pid = fork())) { case 0: e = gfarm_terminate(); if (e == GFARM_ERR_NO_ERROR) e = gfarm_initialize(NULL, NULL); if (e != GFARM_ERR_NO_ERROR) { gflog_error(GFARM_MSG_2000050, "%s: failed to initialize: %s", path, gfarm_error_string(e)); _exit(1); } e = replicate_file(path, ncopy - cur_ncopy, n, dsts, ports); (void)gfarm_terminate(); _exit(e == GFARM_ERR_NO_ERROR ? 0 : 1); case -1: gflog_error_errno(GFARM_MSG_2000044, "fork"); break; default: gflog_info(GFARM_MSG_2000042, "replicate [%d]: %s ncopy %d (required %d)", pid, path, n, ncopy); ++replicate_concurrency; break; } free(dsts); free(ports); } #endif /* HAVE_PRIVATE_SRCS */ <file_sep>/gfarm_zabbix/trunk/src/install-agentd.sh #! /bin/sh # # Install the 'gfarm_zabbix' package for Zabbix agent. # . ./install.conf # install(1) command. INSTALL=install # Directory where external scripts for Zabbix reside. ZABBIX_EXTSCRIPTDIR=$ZABBIX_CONFDIR/externalscripts # Directory where configuration files for Zabbix agentd reside. ZABBIX_AGENTD_CONFSUBDIR=$ZABBIX_CONFDIR/zabbix_agentd.d # User name of Zabbix. ZABBIX_USER=zabbix # Group name of Zabbix. ZABBIX_GROUP=zabbix # # Get value of a particular parameter defined in 'gfmd.conf'. # get_gfmd_conf_value() { [ -f $GFMD_CONF_FILE ] && \ awk '$1 == "'"$1"'" { print $2 }' $GFMD_CONF_FILE } # # Create "$1" file from "$1.in". # create_file() { [ -f "$1".in ] || return 0 [ -f "$1" ] && rm -f "$1" sed \ -e "s|@GFARM_BINDIR@|$GFARM_BINDIR|g" \ -e "s|@PGHOST@|$PGHOST|g" \ -e "s|@PGPORT@|$PGPORT|g" \ -e "s|@PGDATABASE@|$PGDATABASE|g" \ -e "s|@PGUSER@|$PGUSER|g" \ -e "s|@PGPASSWORD@|$PGPASSWORD|g" \ -e "s|@ZABBIX_CONFDIR@|$ZABBIX_CONFDIR|g" \ -e "s|@ZABBIX_EXTSCRIPTDIR@|$ZABBIX_EXTSCRIPTDIR|g" \ -e "s|@ZABBIX_SYSLOG_FACILITY@|$ZABBIX_SYSLOG_FACILITY|g" \ "$1.in" > "$1" } # # Get parameters for accessing PostgreSQL. # PGHOST="`get_gfmd_conf_value postgresql_server_host`" PGPORT="`get_gfmd_conf_value postgresql_server_port`" PGDATABASE="`get_gfmd_conf_value postgresql_dbname`" PGUSER="`get_gfmd_conf_value postgresql_user`" PGPASSWORD="`get_gfmd_conf_value postgresql_password`" # # Install files in 'scripts/zabbix_agentd.d/' to # $ZABBIX_AGENTD_CONFSUBDIR. # for I in \ userparameter_gfarm.conf; do SRCFILE=scripts/zabbix_agentd.d/$I DSTFILE=$ZABBIX_AGENTD_CONFSUBDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o root -g root $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done # # Make a directory '$ZABBIX_EXTSCRIPTDIR'. # DIR=$ZABBIX_EXTSCRIPTDIR if [ ! -d $DIR ]; then $INSTALL -d -m 0755 -o root -g root $DIR \ || { echo "Failed to create the directory: $DIR"; exit 1; } echo "Create the directory: $DIR" fi # # Install files in 'scripts/externalscripts/' to # $ZABBIX_EXTSCRIPTDIR. # for I in \ gfarm_generic_client_gfhost.sh \ gfarm_generic_client_gfmdhost.sh \ gfarm_gfmd_failover.pl \ gfarm_gfmd_gfhost.sh \ gfarm_gfmd_postgresql.sh \ gfarm_gfsd_gfhost.sh \ gfarm_gfsd_gfsched.sh \ gfarm_represent_client_gfhost.sh \ gfarm_represent_client_gfmdhost.sh \ gfarm_represent_client_gfmdhost2.sh \ gfarm_utils.inc; do SRCFILE=scripts/externalscripts/$I DSTFILE=$ZABBIX_EXTSCRIPTDIR/$I create_file $SRCFILE $INSTALL -c -m 0755 -o $ZABBIX_USER -g $ZABBIX_GROUP $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" done SRCFILE=scripts/externalscripts/gfarm_conf.inc DSTFILE=$ZABBIX_EXTSCRIPTDIR/gfarm_conf.inc create_file $SRCFILE $INSTALL -c -m 0700 -o $ZABBIX_USER -g $ZABBIX_GROUP $SRCFILE $DSTFILE \ || { echo "Failed to install the file: $DSTFILE"; exit 1; } echo "Install the file: $DSTFILE" # # Delete or notify obsolete files. # OBSOLETE_FILES= for I in \ zbx_chk_dead_gfarm_pgsql.sh \ zbx_chk_dead_gfmd.sh \ zbx_chk_dead_gfsd.sh \ zbx_chk_gfhost_cli.sh \ zbx_chk_gfhost_gfsd.sh \ zbx_chk_gfmdhost_cli.sh \ zbx_chk_gfmdlist_cli.sh \ zbx_chk_gfmdtype_gfmd.sh \ zbx_chk_gfsched_gfmd.sh \ zbx_chk_gfsched_gfsd.sh \ zbx_chk_listenport_gfmd.sh \ zbx_chk_listenport_gfsd.sh \ zbx_chk_mastername_cli.sh \ zbx_chk_pgsql.sh \ zbx_failover.pl \ zbx_gfarm_utils.inc; do [ -f $ZABBIX_EXTSCRIPTDIR/$I ] && rm -f $ZABBIX_EXTSCRIPTDIR/$I done if [ -f $ZABBIX_EXTSCRIPTDIR/zbx_chk_gfarm.conf ]; then echo "The following file is not used any longer:" echo " $ZABBIX_EXTSCRIPTDIR/zbx_chk_gfarm.conf" echo fi # # Change mode of $GFARM_SYSLOG_FILE # chmod 0644 $GFARM_SYSLOG_FILE \ && echo "Set mode (= 0644) of the file: $GFARM_SYSLOG_FILE" <file_sep>/gfarm/tags/gfarm_0_1/debian/rules #!/usr/bin/make -f # Sample debian/rules that uses debhelper. # GNU copyright 1997 by <NAME>. # # This version is for a hypothetical package that builds an # architecture-dependant package, as well as an architecture-independent # package. # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 # This is the debhelper compatability version to use. export DH_COMPAT=1 # This has to be exported to make some magic below work. export DH_OPTIONS build: build-stamp build-stamp: dh_testdir ./configure --with-openssl=/usr/include/openssl --with-openldap=/usr/lib \ --with-readline="" --prefix=/ --with-default-ns-exec-root=\$${prefix}/var/lib/gfarm \ --mandir=\$${prefix}/usr/share/man --infodir=\$${prefix}/usr/share/info # Add here commands to compile the package. $(MAKE) touch build-stamp clean: dh_testdir dh_testroot rm -f build-stamp # Add here commands to clean up after the build process. -$(MAKE) clean -$(MAKE) distclean find . -name '*.o' -o -name '_libs' -o -name '*.lo' -o -name '*.a' -o -name '.deps' | xargs rm -rf dh_clean install: DH_OPTIONS= install: install-stamp install-stamp: build dh_testdir dh_testroot dh_clean -k # Add here commands to install the package into debian/tmp. # !!FIXME!! there is no install target for gftools. -$(MAKE) install prefix=`pwd`/debian/tmp touch install-stamp # Build architecture-independent files here. # Pass -i to all debhelper commands in this target to reduce clutter. binary-indep: DH_OPTIONS=-i binary-indep: build install gfarm-doc # We have nothing to do by default. # Build architecture-dependent files here. # Pass -a to all debhelper commands in this target to reduce clutter. binary-arch: DH_OPTIONS=-a binary-arch: build install gfarm-pool gfarm-client libgfarm-dev gfarm-server gfarm-server: build # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir -pgfarm-server dh_testroot -pgfarm-server # dh_clean -pgfarm-server -k # Add command to install the files into debian/tmp install -d debian/tmp/usr/sbin mv debian/tmp/bin/gfarmd debian/tmp/usr/sbin install -d debian/tmp/etc/init.d/ install -o root -g root debian/gfarm-server.init debian/tmp/etc/init.d/gfarm-server rm -rf debian/tmp/lib debian/tmp/include debian/tmp/bin # dh_installinit -pgfarm-server dh_installmanpages -pgfarm-server dh_installchangelogs -pgfarm-server dh_strip -pgfarm-server dh_compress -pgfarm-server dh_fixperms -pgfarm-server dh_installdeb -pgfarm-server dh_shlibdeps -pgfarm-server dh_gencontrol -pgfarm-server dh_md5sums -pgfarm-server dh_builddeb -pgfarm-server # dh_installdebconf -pgfarm-server # dh_installdocs -pgfarm-server # dh_installexamples -pgfarm-server # dh_installmenu -pgfarm-server # dh_installpam -pgfarm-server # dh_installinit -pgfarm-server # dh_installcron -pgfarm-server # dh_installinfo -pgfarm-server # dh_undocumented -pgfarm-server # dh_link -pgfarm-server # You may want to make some executables suid here. # dh_suidregister -pgfarm-server # dh_makeshlibs -pgfarm-server # dh_perl -pgfarm-server gfarm-client: build # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir -pgfarm-client dh_testroot -pgfarm-client # dh_clean -pgfarm-client -k # Add command to install the files into debian/tmp install -d debian/gfarm-client/usr/bin cp debian/tmp/bin/gfarm debian/gfarm-client/usr/bin cp nstool/file/put debian/gfarm-client/usr/bin cp nstool/file/get debian/gfarm-client/usr/bin dh_installmanpages -pgfarm-client dh_installchangelogs -pgfarm-client dh_strip -pgfarm-client dh_compress -pgfarm-client dh_fixperms -pgfarm-client dh_installdeb -pgfarm-client dh_shlibdeps -pgfarm-client dh_gencontrol -pgfarm-client dh_md5sums -pgfarm-client # dh_builddeb -pgfarm-client # dh_installdebconf -pgfarm-client # dh_installdocs -pgfarm-client # dh_installexamples -pgfarm-client # dh_installmenu -pgfarm-client # dh_installpam -pgfarm-client # dh_installinit -pgfarm-client # dh_installcron -pgfarm-client # dh_installinfo -pgfarm-client # dh_undocumented -pgfarm-client # dh_link -pgfarm-client # You may want to make some executables suid here. # dh_suidregister -pgfarm-client # dh_makeshlibs -pgfarm-client # dh_perl -pgfarm-client gfarm-pool: build # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir -pgfarm-pool dh_testroot -pgfarm-pool # dh_clean -pgfarm-pool -k # Add command to install the files into debian/tmp install -d debian/gfarm-pool/usr/sbin cp debian/tmp/bin/gfsd debian/gfarm-pool/usr/sbin install -d debian/gfarm-pool/etc/init.d install doc/gfarm.conf debian/gfarm-pool/etc/gfarm.conf install -o root -g root debian/gfarm-pool.init debian/gfarm-pool/etc/init.d/gfarm-pool # dh_installinit -pgfarm-pool dh_installmanpages -pgfarm-pool dh_installchangelogs -pgfarm-pool dh_strip -pgfarm-pool dh_compress -pgfarm-pool dh_fixperms -pgfarm-pool dh_installdeb -pgfarm-pool dh_shlibdeps -pgfarm-pool dh_gencontrol -pgfarm-pool dh_md5sums -pgfarm-pool # dh_builddeb -pgfarm-pool # dh_installdebconf -pgfarm-pool # dh_installdocs -pgfarm-pool # dh_installexamples -pgfarm-pool # dh_installmenu -pgfarm-pool # dh_installpam -pgfarm-pool # dh_installinit -pgfarm-pool # dh_installcron -pgfarm-pool # dh_installinfo -pgfarm-pool # dh_undocumented -pgfarm-pool # dh_link -pgfarm-pool # You may want to make some executables suid here. # dh_suidregister -pgfarm-pool # dh_makeshlibs -pgfarm-pool # dh_perl -pgfarm-pool libgfarm-dev: build # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir -plibgfarm-dev dh_testroot -plibgfarm-dev # dh_clean -plibgfarm-dev -k -V # Add command to install the files into debian/tmp install -d debian/libgfarm-dev/usr/include/gfarm cp debian/tmp/include/gfarm/* debian/libgfarm-dev/usr/include/gfarm # header files install -d debian/libgfarm-dev/usr/lib cp debian/tmp/lib/* debian/libgfarm-dev/usr/lib # *.a files dh_installmanpages -plibgfarm-dev dh_installchangelogs -plibgfarm-dev dh_strip -plibgfarm-dev dh_compress -plibgfarm-dev dh_fixperms -plibgfarm-dev dh_installdeb -plibgfarm-dev dh_shlibdeps -plibgfarm-dev dh_gencontrol -plibgfarm-dev dh_md5sums -plibgfarm-dev # dh_builddeb -plibgfarm-dev # dh_installdebconf -plibgfarm-dev # dh_installdocs -plibgfarm-dev # dh_installexamples -plibgfarm-dev # dh_installmenu -plibgfarm-dev # dh_installpam -plibgfarm-dev # dh_installinit -plibgfarm-dev # dh_installcron -plibgfarm-dev # dh_installinfo -plibgfarm-dev # dh_undocumented -plibgfarm-dev # dh_link -plibgfarm-dev # You may want to make some executables suid here. # dh_suidregister -plibgfarm-dev # dh_makeshlibs -plibgfarm-dev # dh_perl -plibgfarm-dev gfarm-doc: build # Need this version of debhelper for DH_OPTIONS to work. dh_testversion 1.1.17 dh_testdir -pgfarm-doc dh_testroot -pgfarm-doc # dh_clean -pgfarm-doc -k -V # Add command to install the files into debian/tmp install -d debian/gfarm-doc/usr/share/doc/gfarm-doc cp -r doc/* debian/gfarm-doc/usr/share/doc/gfarm-doc # Copy HTML Docs dh_installchangelogs -pgfarm-doc # dh_installdocs -pgfarm-doc dh_installinfo -pgfarm-doc dh_compress -pgfarm-doc dh_fixperms -pgfarm-doc dh_installdeb -pgfarm-doc dh_gencontrol -pgfarm-doc dh_md5sums -pgfarm-doc dh_builddeb -pgfarm-doc binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/FT2-2-2-1_master_gfmd_and_master_candidate_gfmd_down #! /bin/sh ###################################################################### TESTID="FT2-2-2-1" CATEGORY="2 point accident" SECTION="2 internal accident" TITLE="master gfmd and master candidate gfmd down" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd2 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "slave gfmd is not running on $gfmd2" \ "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc1/gftool/gfdf/gfdf.c #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gfarm/gfarm.h> #include "config.h" #include "gfs_client.h" char *program_name = "gfdf"; char * print_space(char *host, int print_inode) { char *e, *canonical_hostname; struct gfs_connection *gfs_server; struct sockaddr peer_addr; gfarm_int32_t bsize; file_offset_t blocks, bfree, bavail, files, ffree, favail; e = gfarm_host_address_get(host, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, host, e); return (e); } e = gfarm_host_get_canonical_name(host, &canonical_hostname); if (e != NULL) canonical_hostname = host; e = gfs_client_connect(canonical_hostname, &peer_addr, &gfs_server); if (e != NULL) { fprintf(stderr, "%s: connect to %s: %s\n", program_name, host, e); if (canonical_hostname != host) free(canonical_hostname); return (e); } e = gfs_client_statfs(gfs_server, ".", &bsize, &blocks, &bfree, &bavail, &files, &ffree, &favail); if (e != NULL) { fprintf(stderr, "%s: df on %s: %s\n", program_name, host, e); } else if (print_inode) { printf("%12.0f%12.0f%12.0f %3.0f%% %s\n", (double)files, (double)files - ffree, (double)favail, (double)(files - ffree)/(files - (ffree - favail))*100.0, host); } else { printf("%12.0f%12.0f%12.0f %3.0f%% %s\n", (double)(blocks * bsize) / 1024.0, (double)(blocks - bfree) * bsize / 1024., (double)bavail * bsize / 1024.0, (double)(blocks - bfree)/(blocks - (bfree - bavail))*100.0, host); } gfs_client_disconnect(gfs_server); if (canonical_hostname != host) free(canonical_hostname); return (e); } #define EXIT_INVALID_ARGUMENT 2 void usage(void) { fprintf(stderr, "Usage:\t%s -h <host>\n", program_name); fprintf(stderr, "\t%s -H <hostfile>\n", program_name); exit(EXIT_INVALID_ARGUMENT); } int main(int argc, char **argv) { char *e, **hosts = NULL; int c, i, lineno, nhosts = 0, opt_print_inode = 0, failed = 0; gfarm_stringlist hostlist; if ((e = gfarm_initialize(&argc, &argv)) != NULL) { fprintf(stderr, "%s: gfarm initialize: %s\n", program_name, e); exit(EXIT_FAILURE); } gfarm_stringlist_init(&hostlist); while ((c = getopt(argc, argv, "H:h:i?")) != -1) { switch (c) { case 'H': e = gfarm_hostlist_read(optarg, &nhosts, &hosts, &lineno); if (e != NULL) { if (lineno != -1) { fprintf(stderr, "%s: %s: line %d: %s\n", program_name, optarg, lineno, e); } else { fprintf(stderr, "%s: %s: %s\n", program_name, optarg, e); } exit(EXIT_INVALID_ARGUMENT); } break; case 'h': gfarm_stringlist_add(&hostlist, optarg); break; case 'i': opt_print_inode = 1; break; case '?': /*FALLTHROUGH*/ default: usage(); } } if (optind < argc || (nhosts == 0 && gfarm_stringlist_length(&hostlist) == 0)) usage(); if (opt_print_inode) { printf("%12s%12s%12s%7s %s\n", "Inodes", "IUsed", "IAvail", "%IUsed", "Host"); } else { printf("%12s%12s%12s%9s %s\n", "1K-blocks", "Used", "Avail", "Capacity", "Host"); } for (i = 0; i < nhosts; i++) { if (print_space(hosts[i], opt_print_inode) != NULL) failed = 1; } for (i = 0; i < gfarm_stringlist_length(&hostlist); i++) { if (print_space(gfarm_stringlist_elem(&hostlist, i), opt_print_inode) != NULL) failed = 1; } if ((e = gfarm_terminate()) != NULL) { fprintf(stderr, "%s: gfarm terminate: %s\n", program_name, e); exit(EXIT_FAILURE); } return (failed ? EXIT_FAILURE : EXIT_SUCCESS); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc4/util/gfront/Makefile top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . javadir = $(prefix)/share/java include $(top_srcdir)/makes/var.mk # NOTE: We use current directory instead of $(srcdir) for the script # to be installed, because the script will be generated by configure. SCRIPTS= gfront JAR= gfront.jar include $(top_srcdir)/makes/script.mk install: @for i in -- $(JAR); do \ case $$i in --) continue;; esac; \ ( set -x; $(INSTALL_DATA) $(srcdir)/$${i} $(javadir)/$${i} ); \ done distclean: -rm -f $(SCRIPTS) <file_sep>/gfarm/branches/gfarm/gftool/config-gfarm/sysdep/freebsd/gfsd.in #!/bin/sh # # $FreeBSD$ # # PROVIDE: gfsd # REQUIRE: NETWORKING SERVERS # BEFORE: DAEMON # KEYWORD: <PASSWORD> # # Add the following lines to /etc/rc.conf to enable gfsd: # gfsd_enable (bool): Set to "NO" by default. # gfsd_flags (str): Set to "" by default. # Extra flags passed to start command # . %%RC_SUBR%% name="gfsd" rcvar=`set_rcvar` command="%%PREFIX%%/sbin/${name}" pidfile="/var/run/${name}.pid" required_files=%%SYSCONFDIR%%/gfarm.conf # add more flags through ${${name}_flags} command_args="-P /var/run/${name}.pid" [ -z "$gfsd_enable" ] && gfsd_enable="NO" [ -z "$gfsd_flags" ] && gfsd_flags="" load_rc_config $name GLOBUS_LOCATION=/usr/local/globus export GLOBUS_LOCATION if [ -f $GLOBUS_LOCATION/etc/globus-user-env.sh ]; then . $GLOBUS_LOCATION/etc/globus-user-env.sh fi run_rc_command "$1" <file_sep>/gfarmfs-fuse/tags/gfarmfs_fuse_1_3_0/contrib/gfarmfs-exec/gfarmfs-exec.sh #!/bin/sh # # wrapper script to execute a program in Gfarm file system using GfarmFS-FUSE # # gfarmfs-exec.sh prog arg ... # or # GFS_PROG=prog GFS_ARGS="arg ..." gfarmfs-exec.sh # # Environment variable: # # GFS_USERNAME global user name in Gfarm (defaut: $LOGNAME) # GFS_MOUNTDIR mount point (defaut: /tmp/$GFS_USERNAME) # GFS_WDIR working directory relative to the home directory # in Gfarm file system (default: .) # GFS_STDOUT Filename for the standard output (default: STDOUT.$$) # GFS_STDERR Filename for the standard error (default: STDERR.$$) # # $Id$ ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } if [ X"$GFS_PROG" = X ]; then [ $# -lt 1 ] && ABORT "no program specified" : ${GFS_PROG:=$1} shift : ${GFS_ARGS:=$*} fi : ${GFS_USERNAME:=$LOGNAME} : ${GFS_MOUNTDIR:=/tmp/$GFS_USERNAME} : ${GFS_WDIR:=.} : ${GFS_STDOUT:=STDOUT.$$} : ${GFS_STDERR:=STDERR.$$} DELETE_MOUNTDIR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR=1 fi [ -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME cd / gfarmfs -lsu $GFS_MOUNTDIR || : cd $GFS_MOUNTDIR/$GFS_USERNAME && cd $GFS_WDIR && $GFS_PROG $GFS_ARGS > $GFS_STDOUT 2> $GFS_STDERR STATUS=$? cd / fusermount -u $GFS_MOUNTDIR || : [ $DELETE_MOUNTDIR = 1 ] && rmdir $GFS_MOUNTDIR exit $STATUS <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8_1/contrib/mount.gfarm2fs/mount.gfarm2fs #!/bin/sh # # $Id$ USAGE() { cat <<EOF mount.gfarm2fs [ configuration_file mount_point options ] Environment variable: GFS_USERNAME global user name in Gfarm GFS_MOUNTDIR mount point GFARMFS_ROOT directory to be mounted in Gfarm GFARMFS_OPTIONS gfarmfs mount options FUSE_OPTIONS fuse mount options When mount.gfarm2fs is installed to /sbin/mount.gfarm2fs, you can mount the Gfarm file system by the mount(8) command. Example of /etc/fstab entries: /etc/gfarm2.conf /gfarm/tatebe gfarm2fs noauto,user 0 0 EOF exit 1 } ABORT() { [ $# -gt 0 ] && echo 1>&2 $* exit 1 } [ x"$1" = x"-h" -o x"$1" = x"--help" ] && USAGE if [ $# -gt 0 ]; then export GFARM_CONFIG_FILE=$1 shift fi if [ $# -gt 0 ]; then GFS_MOUNTDIR=$1 shift fi if [ $# -gt 0 ]; then # abandon OPTIONS=$* fi : ${GFS_USERNAME:=`gfwhoami 2> /dev/null`} : ${GFS_USERNAME:=$USER} : ${GFS_USERNAME:=$LOGNAME} : ${GFS_USERNAME:=`logname 2> /dev/null`} : ${GFS_MOUNTDIR:=/tmp/$GFS_USERNAME} : ${GFARMFS_ROOT:=`gfuser -l $GFS_USERNAME 2> /dev/null | awk -F: '{ print $3 }'`} : ${GFARMFS_ROOT:=/} : ${GFARMFS_OPTIONS:=} : ${FUSE_OPTIONS:=} # if already mounted, exit grep $GFS_MOUNTDIR /etc/mtab > /dev/null && ABORT "$GFS_MOUNTDIR: already mounted" DELETE_MOUNTDIR_ON_ERROR=0 if [ ! -d $GFS_MOUNTDIR ]; then mkdir -p $GFS_MOUNTDIR || ABORT "cannot create a mount point: " $GFS_MOUNTDIR DELETE_MOUNTDIR_ON_ERROR=1 fi [ -O $GFS_MOUNTDIR ] || ABORT "$GFS_MOUNTDIR: not owned by " $LOGNAME # mount gfarm2fs -o modules=subdir,subdir=$GFARMFS_ROOT $GFARMFS_OPTIONS $GFS_MOUNTDIR $FUSE_OPTIONS STATUS=$? if [ $STATUS = 0 ]; then echo Mount GfarmFS on $GFS_MOUNTDIR else [ $DELETE_MOUNTDIR_ON_ERROR = 1 ] && rmdir $GFS_MOUNTDIR fi exit $STATUS <file_sep>/gfarm_gridftp_dsi/trunk/globus_gridftp_server_gfarm.c /* * Globus GridFTP Server DSI for Gfarm File System * * Copyright (c) 1999-2006 University of Chicago * * Copyright (c) 2009 University of Tsukuba. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "globus_gridftp_server.h" #include <libgen.h> #include <pwd.h> #include <grp.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> static globus_version_t local_version = { 1, /* major version number */ 0, /* minor version number */ 1236013521, 0 /* branch ID */ }; typedef struct globus_l_gfs_gfarm_handle_s { int concurrency; globus_size_t block_size; globus_bool_t buffers_initialized; globus_byte_t **buffers; globus_mutex_t mutex; GFS_File gf; globus_off_t offset; globus_bool_t done; globus_bool_t eof; int concurrency_count; globus_off_t read_len; /* not use */ globus_result_t save_result; char *path; } globus_l_gfs_gfarm_handle_t; extern void gfarm_gsi_set_delegated_cred(gss_cred_id_t); extern char *gfarm_gsi_client_cred_name(void); #define DSI_BLOCKSIZE "GFARM_DSI_BLOCKSIZE" #define DSI_CONCURRENCY "GFARM_DSI_CONCURRENCY" /************************************************************************* * start * ----- * This function is called when a new session is initialized, ie a user * connectes to the server. This hook gives the dsi an oppertunity to * set internal state that will be threaded through to all other * function calls associated with this session. And an oppertunity to * reject the user. * * finished_info.info.session.session_arg should be set to an DSI * defined data structure. This pointer will be passed as the void * * user_arg parameter to all other interface functions. * * NOTE: at nice wrapper function should exist that hides the details * of the finished_info structure, but it currently does not. * The DSI developer should jsut follow this template for now ************************************************************************/ static void globus_l_gfs_gfarm_start( globus_gfs_operation_t op, globus_gfs_session_info_t *session_info) { globus_l_gfs_gfarm_handle_t *gfarm_handle; globus_gfs_finished_info_t finished_info; gfarm_error_t e; GlobusGFSName(globus_l_gfs_gfarm_start); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) globus_malloc(sizeof(globus_l_gfs_gfarm_handle_t)); memset(&finished_info, '\0', sizeof(globus_gfs_finished_info_t)); finished_info.type = GLOBUS_GFS_OP_SESSION_START; finished_info.info.session.session_arg = gfarm_handle; finished_info.info.session.username = session_info->username; finished_info.info.session.home_dir = "/"; finished_info.result = GLOBUS_SUCCESS; gfarm_gsi_set_delegated_cred(session_info->del_cred); globus_gfs_log_message( GLOBUS_GFS_LOG_INFO, "[gfarm-dsi] gfarm_gsi_client_cred_name: %s\n", gfarm_gsi_client_cred_name()); globus_mutex_init(&gfarm_handle->mutex, NULL); gfarm_handle->buffers_initialized = GLOBUS_FALSE; gfarm_handle->path = NULL; e = gfarm_initialize(NULL, NULL); if (e != GFARM_ERR_NO_ERROR) { finished_info.result = GlobusGFSErrorSystemError( "gfarm_initialize", gfarm_error_to_errno(e)); } globus_gridftp_server_operation_finished( op, finished_info.result, &finished_info); } /************************************************************************* * destroy * ------- * This is called when a session ends, ie client quits or disconnects. * The dsi should clean up all memory they associated wit the session * here. ************************************************************************/ static void buffers_destroy(globus_l_gfs_gfarm_handle_t *gfarm_handle); static void globus_l_gfs_gfarm_destroy(void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; globus_mutex_destroy(&gfarm_handle->mutex); buffers_destroy(gfarm_handle); globus_free(gfarm_handle); gfarm_terminate(); } /************************************************************************* * stat * ---- * This interface function is called whenever the server needs * information about a given file or resource. It is called then an * LIST is sent by the client, when the server needs to verify that * a file exists and has the proper permissions, etc. ************************************************************************/ #define NOBODY_UID 65535 #define NOBODY_GID 65535 static uid_t get_uid(const char *path, char *user) { struct passwd *pwd; char *luser; if (gfarm_global_to_local_username_by_url(path, user, &luser) == GFARM_ERR_NO_ERROR) { pwd = getpwnam(luser); free(luser); if (pwd != NULL) return (pwd->pw_uid); } /* cannot conver to a local account */ return (NOBODY_UID); } static int get_gid(const char *path, char *group) { struct group *grp; char *lgroup; if (gfarm_global_to_local_groupname_by_url(path, group, &lgroup) == GFARM_ERR_NO_ERROR) { grp = getgrnam(lgroup); free(lgroup); if (grp != NULL) return (grp->gr_gid); } /* cannot conver to a local group */ return (NOBODY_GID); } static int get_nlink(struct gfs_stat *st) { /* XXX FIXME */ return (GFARM_S_ISDIR(st->st_mode) ? 32000 : st->st_nlink); } static void stat_array_copy(const char *path, globus_gfs_stat_t *dst, struct gfs_stat *src) { dst->ino = src->st_ino; dst->mode = src->st_mode; dst->nlink = get_nlink(src); dst->uid = get_uid(path, src->st_user); dst->gid = get_gid(path, src->st_group); dst->size = src->st_size; dst->atime = src->st_atimespec.tv_sec; dst->mtime = src->st_mtimespec.tv_sec; dst->ctime = src->st_ctimespec.tv_sec; } static void stat_array_destroy(globus_gfs_stat_t *stat_array, int stat_count) { int i; if (stat_array == NULL) { return; } for(i = 0; i < stat_count; i++) { if(stat_array[i].name != NULL) { globus_free(stat_array[i].name); } if(stat_array[i].symlink_target != NULL) { globus_free(stat_array[i].symlink_target); } } globus_free(stat_array); } static gfarm_error_t stat_array_set( globus_gfs_stat_t *stat_array, const char *path, const char *name) { struct gfs_stat st; gfarm_error_t e; stat_array->symlink_target = NULL; e = gfs_lstat_cached(path, &st); if (e != GFARM_ERR_NO_ERROR) { stat_array->name = NULL; return (e); } stat_array_copy(path, &stat_array[0], &st); stat_array->name = strdup(name); gfs_stat_free(&st); return (GFARM_ERR_NO_ERROR); } static void globus_l_gfs_gfarm_stat( globus_gfs_operation_t op, globus_gfs_stat_info_t *stat_info, void *user_arg) { globus_gfs_stat_t *stat_array = NULL; int stat_count = 0; globus_l_gfs_gfarm_handle_t *gfarm_handle; globus_result_t result; gfarm_error_t e; struct gfs_stat st; char *path; int is_dir; GFS_Dir dp; struct gfs_dirent *de; gfarm_error_t e2; int array_size = 4; GlobusGFSName(globus_l_gfs_gfarm_stat); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; path = stat_info->pathname; e = gfs_lstat_cached(path, &st); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_lstat", gfarm_error_to_errno(e)); goto error; } #if 0 if (GFARM_S_ISLNK(st.st_mode)) { /* XXX replace st from gfs_stat() */ } #endif is_dir = GFARM_S_ISDIR(st.st_mode); gfs_stat_free(&st); if (!is_dir || stat_info->file_only) { /* stat */ stat_array = (globus_gfs_stat_t *) globus_malloc(sizeof(globus_gfs_stat_t)); if(stat_array == NULL) { result = GlobusGFSErrorMemory("stat_array"); goto error; } stat_count = 1; e = stat_array_set(&stat_array[0], path, basename(path)); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_stat", gfarm_error_to_errno(e)); goto error; } goto end; /* success */ } /* list */ e = gfs_opendir_caching(path, &dp); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_opendir", gfarm_error_to_errno(e)); goto error; } while ((e = gfs_readdir(dp, &de)) == GFARM_ERR_NO_ERROR && de != NULL) { char child[MAXPATHLEN]; stat_count++; if (stat_array == NULL) { stat_array = (globus_gfs_stat_t *) globus_malloc(sizeof(globus_gfs_stat_t) * array_size); } else if (stat_count > array_size) { array_size = array_size * 2; globus_gfs_stat_t *tmp = (globus_gfs_stat_t *) globus_realloc(stat_array, sizeof(globus_gfs_stat_t) * array_size); if (tmp == NULL) { globus_free(stat_array); } stat_array = tmp; } if(stat_array == NULL) { result = GlobusGFSErrorMemory("stat_array"); gfs_closedir(dp); stat_count--; goto error; } snprintf(child, sizeof(child), "%s/%s", path, de->d_name); child[MAXPATHLEN - 1] = '\0'; e = stat_array_set(&stat_array[stat_count-1], child, de->d_name); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_stat", gfarm_error_to_errno(e)); goto error; } } e2 = gfs_closedir(dp); if (e == GFARM_ERR_NO_ERROR) e = e2; if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_readdir", gfarm_error_to_errno(e)); goto error; } end: globus_gridftp_server_finished_stat( op, GLOBUS_SUCCESS, stat_array, stat_count); stat_array_destroy(stat_array, stat_count); return; error: globus_gridftp_server_finished_stat(op, result, NULL, 0); stat_array_destroy(stat_array, stat_count); return; } /************************************************************************* * command * ------- * This interface function is called when the client sends a 'command'. * commands are such things as mkdir, remdir, delete. The complete * enumeration is below. * * To determine which command is being requested look at: * cmd_info->command * * GLOBUS_GFS_CMD_MKD = 1, * GLOBUS_GFS_CMD_RMD, * GLOBUS_GFS_CMD_DELE, * GLOBUS_GFS_CMD_RNTO, * GLOBUS_GFS_CMD_RNFR, * GLOBUS_GFS_CMD_CKSM, * GLOBUS_GFS_CMD_SITE_CHMOD, * GLOBUS_GFS_CMD_SITE_DSI ************************************************************************/ static void uncache(const char *p) { gfs_stat_cache_purge(p); } static void uncache_parent(const char *path) { char *p = strdup(path), *b; if (p == NULL) /* XXX should report an error */ return; b = (char *)gfarm_path_dir_skip(p); /* UNCONST */ if (b > p && b[-1] == '/') { b[-1] = '\0'; uncache(p); } free(p); } static globus_result_t gfarm_mkdir(globus_gfs_operation_t op, const char *pathname) { gfarm_error_t e; mode_t um; GlobusGFSName(gfarm_mkdir); um = umask(0022); umask(um); e = gfs_mkdir(pathname, 0777 & ~um); if (e != GFARM_ERR_NO_ERROR) { return GlobusGFSErrorSystemError( "gfs_mkdir", gfarm_error_to_errno(e)); } uncache_parent(pathname); return (GLOBUS_SUCCESS); } static globus_result_t gfarm_rmdir(globus_gfs_operation_t op, const char *pathname) { gfarm_error_t e; GlobusGFSName(gfarm_rmdir); e = gfs_rmdir(pathname); if (e != GFARM_ERR_NO_ERROR) { return GlobusGFSErrorSystemError( "gfs_rmdir", gfarm_error_to_errno(e)); } uncache(pathname); uncache_parent(pathname); return (GLOBUS_SUCCESS); } static globus_result_t gfarm_delete(globus_gfs_operation_t op, const char *pathname) { gfarm_error_t e; GlobusGFSName(gfarm_delete); e = gfs_unlink(pathname); if (e != GFARM_ERR_NO_ERROR) { return GlobusGFSErrorSystemError( "gfs_unlink", gfarm_error_to_errno(e)); } uncache(pathname); uncache_parent(pathname); return (GLOBUS_SUCCESS); } static globus_result_t gfarm_rename(globus_gfs_operation_t op, const char *from, const char *to) { gfarm_error_t e; GlobusGFSName(gfarm_rename); e = gfs_rename(from, to); if (e != GFARM_ERR_NO_ERROR) { return GlobusGFSErrorSystemError( "gfs_rename", gfarm_error_to_errno(e)); } uncache(from); uncache_parent(from); uncache(to); uncache_parent(to); return (GLOBUS_SUCCESS); } static globus_result_t gfarm_chmod(globus_gfs_operation_t op, const char *pathname, mode_t mode) { gfarm_error_t e; GlobusGFSName(gfarm_chmod); e = gfs_chmod(pathname, mode & 0777); if (e != GFARM_ERR_NO_ERROR) { return GlobusGFSErrorSystemError( "gfs_chmod", gfarm_error_to_errno(e)); } uncache(pathname); return (GLOBUS_SUCCESS); } static void globus_l_gfs_gfarm_command( globus_gfs_operation_t op, globus_gfs_command_info_t *cmd_info, void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; globus_result_t result; GlobusGFSName(globus_l_gfs_gfarm_command); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; switch (cmd_info->command) { case GLOBUS_GFS_CMD_MKD: result = gfarm_mkdir(op, cmd_info->pathname); break; case GLOBUS_GFS_CMD_RMD: result = gfarm_rmdir(op, cmd_info->pathname); break; case GLOBUS_GFS_CMD_DELE: result = gfarm_delete(op, cmd_info->pathname); break; case GLOBUS_GFS_CMD_RNTO: result = gfarm_rename( op, cmd_info->rnfr_pathname, cmd_info->pathname); break; case GLOBUS_GFS_CMD_SITE_CHMOD: result = gfarm_chmod( op, cmd_info->pathname, cmd_info->chmod_mode); break; default: result = GLOBUS_FAILURE; break; } globus_gridftp_server_finished_command(op, result, GLOBUS_NULL); } /************************************************************************* * recv * ---- * This interface function is called when the client requests that a * file be transfered to the server. * * To receive a file the following functions will be used in roughly * the presented order. They are doced in more detail with the * gridftp server documentation. * * globus_gridftp_server_begin_transfer(); * globus_gridftp_server_register_read(); * globus_gridftp_server_finished_transfer(); * ************************************************************************/ static void buffers_destroy(globus_l_gfs_gfarm_handle_t *gfarm_handle) { int i; if (!gfarm_handle->buffers_initialized) return; for (i = 0; i < gfarm_handle->concurrency; i++) { if (gfarm_handle->buffers[i] != NULL) globus_free(gfarm_handle->buffers[i]); } globus_free(gfarm_handle->buffers); gfarm_handle->buffers_initialized = GLOBUS_FALSE; } static globus_result_t buffers_initialize( globus_gfs_operation_t op, globus_l_gfs_gfarm_handle_t *gfarm_handle) { globus_result_t result; int i; char *envstr; GlobusGFSName(buffers_initialize); if (gfarm_handle->buffers_initialized) return (GLOBUS_SUCCESS); envstr = getenv(DSI_BLOCKSIZE); if (envstr != NULL) gfarm_handle->block_size = atoi(envstr); else gfarm_handle->block_size = 0; envstr = getenv(DSI_CONCURRENCY); if (envstr != NULL) gfarm_handle->concurrency = atoi(envstr); else gfarm_handle->concurrency = 0; if (gfarm_handle->block_size <= 0) globus_gridftp_server_get_block_size( op, &gfarm_handle->block_size); if (gfarm_handle->concurrency <= 0) globus_gridftp_server_get_optimal_concurrency( op, &gfarm_handle->concurrency); globus_gfs_log_message( GLOBUS_GFS_LOG_INFO, "[gfarm-dsi] %s=%d\n", DSI_BLOCKSIZE, gfarm_handle->block_size); globus_gfs_log_message( GLOBUS_GFS_LOG_INFO, "[gfarm-dsi] %s=%d\n", DSI_CONCURRENCY, gfarm_handle->concurrency); gfarm_handle->buffers = (globus_byte_t**) globus_calloc( gfarm_handle->concurrency, sizeof(globus_byte_t*)); if (gfarm_handle->buffers == NULL) { result = GlobusGFSErrorMemory("buffers"); goto error; } for (i = 0; i < gfarm_handle->concurrency; i++) { gfarm_handle->buffers[i] = (globus_byte_t*) globus_malloc( sizeof(globus_byte_t) * gfarm_handle->block_size); if (gfarm_handle->buffers[i] == NULL) { result = GlobusGFSErrorMemory("buffer"); i++; for (; i < gfarm_handle->concurrency; i++) { gfarm_handle->buffers[i] = NULL; } gfarm_handle->buffers_initialized = GLOBUS_TRUE; goto error; } } gfarm_handle->buffers_initialized = GLOBUS_TRUE; return (GLOBUS_SUCCESS); error: buffers_destroy(gfarm_handle); return (result); } static void gfarm_import_cb( globus_gfs_operation_t op, globus_result_t result, globus_byte_t *buffer, globus_size_t nbytes, globus_off_t offset, globus_bool_t eof, void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; globus_off_t o; gfarm_error_t e = GFARM_ERR_NO_ERROR; int rv; GlobusGFSName(gfarm_read_cb); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; globus_mutex_lock(&gfarm_handle->mutex); if (gfarm_handle->done) { globus_mutex_unlock(&gfarm_handle->mutex); return; } if (result != GLOBUS_SUCCESS) { gfarm_handle->eof = GLOBUS_TRUE; goto finish; } if (nbytes == 0) goto skip; if (gfarm_handle->offset == 0 || gfarm_handle->offset != offset) e = gfs_pio_seek(gfarm_handle->gf, offset, GFARM_SEEK_SET, &o); if (e == GFARM_ERR_NO_ERROR) e = gfs_pio_write(gfarm_handle->gf, buffer, nbytes, &rv); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_pio_write", gfarm_error_to_errno(e)); gfarm_handle->eof = GLOBUS_TRUE; goto finish; } uncache(gfarm_handle->path); gfarm_handle->offset = offset + rv; skip: if (eof) { result = GLOBUS_SUCCESS; gfarm_handle->eof = GLOBUS_TRUE; goto finish; } /* continue */ globus_mutex_unlock(&gfarm_handle->mutex); globus_gridftp_server_register_read( op, buffer, gfarm_handle->block_size, gfarm_import_cb, gfarm_handle); return; finish: /* end of this thread */ gfarm_handle->concurrency_count--; if (result != GLOBUS_SUCCESS) { gfarm_handle->save_result = result; } if (gfarm_handle->concurrency_count <= 0 && gfarm_handle->eof) { e = gfs_pio_close(gfarm_handle->gf); if (e != GFARM_ERR_NO_ERROR && gfarm_handle->save_result == GLOBUS_SUCCESS) gfarm_handle->save_result = GlobusGFSErrorSystemError( "gfs_pio_close", gfarm_error_to_errno(e)); uncache(gfarm_handle->path); globus_gridftp_server_finished_transfer( op, gfarm_handle->save_result); gfarm_handle->done = GLOBUS_TRUE; } globus_mutex_unlock(&gfarm_handle->mutex); return; } static void globus_l_gfs_gfarm_recv( globus_gfs_operation_t op, globus_gfs_transfer_info_t *transfer_info, void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; int i; mode_t um; globus_result_t result; gfarm_error_t e; GlobusGFSName(globus_l_gfs_gfarm_recv); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; gfarm_handle->done = GLOBUS_FALSE; gfarm_handle->eof = GLOBUS_FALSE; gfarm_handle->concurrency_count = 0; gfarm_handle->offset = 0; gfarm_handle->save_result = GLOBUS_SUCCESS; gfarm_handle->path = transfer_info->pathname; um = umask(0022); umask(um); e = gfs_pio_create(transfer_info->pathname, GFARM_FILE_TRUNC | GFARM_FILE_WRONLY, 0666 & ~um, &gfarm_handle->gf); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError("gfs_pio_create", gfarm_error_to_errno(e)); globus_gridftp_server_finished_transfer(op, result); return; } uncache_parent(transfer_info->pathname); globus_gridftp_server_begin_transfer(op, 0, gfarm_handle); globus_mutex_lock(&gfarm_handle->mutex); result = buffers_initialize(op, gfarm_handle); if (result != GLOBUS_SUCCESS) goto error; for (i = 0; i < gfarm_handle->concurrency; i++) { gfarm_handle->concurrency_count++; result = globus_gridftp_server_register_read( op, gfarm_handle->buffers[i], gfarm_handle->block_size, gfarm_import_cb, gfarm_handle); if (result != GLOBUS_SUCCESS) goto error; } globus_mutex_unlock(&gfarm_handle->mutex); return; error: gfarm_handle->done = GLOBUS_TRUE; globus_mutex_unlock(&gfarm_handle->mutex); gfs_pio_close(gfarm_handle->gf); uncache(transfer_info->pathname); globus_gridftp_server_finished_transfer(op, result); return; } /************************************************************************* * send * ---- * This interface function is called when the client requests to receive * a file from the server. * * To send a file to the client the following functions will be used * in roughly the presented order. They are doced in more detail * with the gridftp server documentation. * * globus_gridftp_server_begin_transfer(); * globus_gridftp_server_register_write(); * globus_gridftp_server_finished_transfer(); * ************************************************************************/ static void gfarm_export_and_register_write( globus_gfs_operation_t op, globus_l_gfs_gfarm_handle_t *gfarm_handle, globus_byte_t *buf); static void gfarm_export_cb( globus_gfs_operation_t op, globus_result_t result, globus_byte_t *buffer, globus_size_t nbytes, void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; GlobusGFSName(gfarm_export_cb); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; /* next */ gfarm_export_and_register_write(op, gfarm_handle, buffer); } static void gfarm_export_and_register_write( globus_gfs_operation_t op, globus_l_gfs_gfarm_handle_t *gfarm_handle, globus_byte_t *buf) { int rv; globus_result_t result; gfarm_error_t e; GlobusGFSName(gfarm_read_and_register_write); globus_mutex_lock(&gfarm_handle->mutex); if (gfarm_handle->done) goto end; e = gfs_pio_read(gfarm_handle->gf, buf, gfarm_handle->block_size, &rv); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError( "gfs_pio_read", gfarm_error_to_errno(e)); goto finish; } if (rv == 0) { /* end */ result = GLOBUS_SUCCESS; goto finish; } /* regist and send */ result = globus_gridftp_server_register_write( op, buf, rv, gfarm_handle->offset, -1, gfarm_export_cb, gfarm_handle); gfarm_handle->offset += rv; if (result == GLOBUS_SUCCESS) goto end; /* next */ finish: e = gfs_pio_close(gfarm_handle->gf); if (e != GFARM_ERR_NO_ERROR && result == GLOBUS_SUCCESS) result = GlobusGFSErrorSystemError("gfs_pio_close", gfarm_error_to_errno(e)); globus_gridftp_server_finished_transfer(op, result); gfarm_handle->done = GLOBUS_TRUE; end: globus_mutex_unlock(&gfarm_handle->mutex); return; } static void globus_l_gfs_gfarm_send( globus_gfs_operation_t op, globus_gfs_transfer_info_t *transfer_info, void *user_arg) { globus_l_gfs_gfarm_handle_t *gfarm_handle; globus_result_t result; globus_off_t o; int i; gfarm_error_t e; GlobusGFSName(globus_l_gfs_gfarm_send); gfarm_handle = (globus_l_gfs_gfarm_handle_t *) user_arg; gfarm_handle->done = GLOBUS_FALSE; gfarm_handle->offset = 0; e = gfs_pio_open(transfer_info->pathname, GFARM_FILE_RDONLY, &gfarm_handle->gf); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError("gfs_pio_open", gfarm_error_to_errno(e)); globus_gridftp_server_finished_transfer(op, result); return; } globus_gridftp_server_get_read_range( op, &gfarm_handle->offset, &gfarm_handle->read_len); globus_gridftp_server_begin_transfer(op, 0, gfarm_handle); e = gfs_pio_seek(gfarm_handle->gf, gfarm_handle->offset, GFARM_SEEK_SET, &o); if (e != GFARM_ERR_NO_ERROR) { result = GlobusGFSErrorSystemError("gfs_pio_seek", gfarm_error_to_errno(e)); goto error; } result = buffers_initialize(op, gfarm_handle); if (result != GLOBUS_SUCCESS) goto error; for (i = 0; i < gfarm_handle->concurrency; i++) { gfarm_export_and_register_write(op, gfarm_handle, gfarm_handle->buffers[i]); } /* start */ return; error: globus_gridftp_server_finished_transfer(op, result); gfs_pio_close(gfarm_handle->gf); return; } static int globus_l_gfs_gfarm_activate(void); static int globus_l_gfs_gfarm_deactivate(void); /* * no need to change this */ static globus_gfs_storage_iface_t globus_l_gfs_gfarm_dsi_iface = { GLOBUS_GFS_DSI_DESCRIPTOR_BLOCKING | GLOBUS_GFS_DSI_DESCRIPTOR_SENDER, globus_l_gfs_gfarm_start, globus_l_gfs_gfarm_destroy, NULL, /* list */ globus_l_gfs_gfarm_send, globus_l_gfs_gfarm_recv, NULL, /* trev */ NULL, /* active */ NULL, /* passive */ NULL, /* data destroy */ globus_l_gfs_gfarm_command, globus_l_gfs_gfarm_stat, NULL, NULL }; /* * no need to change this */ GlobusExtensionDefineModule(globus_gridftp_server_gfarm) = { "globus_gridftp_server_gfarm", globus_l_gfs_gfarm_activate, globus_l_gfs_gfarm_deactivate, NULL, NULL, &local_version }; /* * no need to change this */ static int globus_l_gfs_gfarm_activate(void) { globus_extension_registry_add( GLOBUS_GFS_DSI_REGISTRY, "gfarm", GlobusExtensionMyModule(globus_gridftp_server_gfarm), &globus_l_gfs_gfarm_dsi_iface); return (0); } /* * no need to change this */ static int globus_l_gfs_gfarm_deactivate(void) { globus_extension_registry_remove( GLOBUS_GFS_DSI_REGISTRY, "gfarm"); return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc1/gftool/gfarm_agent/agent_thr.c /* * $Id$ */ #include <string.h> #include <pthread.h> #include "gfutil.h" #include "agent_thr.h" static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void agent_lock() { pthread_mutex_lock(&lock); } void agent_unlock() { pthread_mutex_unlock(&lock); } int agent_schedule(int *fd, void *(*handler)(void *)) { int err; pthread_t thread_id; static int initialized = 0; static pthread_attr_t attr; if (!initialized) { err = pthread_attr_init(&attr); if (err != 0) gflog_fatal("pthread_attr_init()", strerror(err)); err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (err != 0) gflog_fatal("PTHREAD_CREATE_DETACHED", strerror(err)); initialized = 1; } return (pthread_create(&thread_id, &attr, handler, fd)); } <file_sep>/gfarm/tags/gfarm_1_0_rc2/lib/libgfarm/gfutil/hash.c #include <stddef.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "hash.h" #define ALIGNMENT 16 #define ALIGN(p) (((unsigned long)(p) + ALIGNMENT - 1) & ~(ALIGNMENT - 1)) /* string hash function by <NAME> */ int gfarm_hash_default(const void *key, int keylen) { int i; unsigned int hash = 0, g; for (i = 0; i < keylen; i++) { hash = (hash << 4) + ((unsigned char *)key)[i]; /* this assumes size of `int' is 32 bit */ if ((g = hash & 0xf0000000) != 0) { hash ^= g >> 24; hash ^= g; } } return (hash); } int gfarm_hash_casefold(const void *key, int keylen) { int i; unsigned int hash = 0, g; for (i = 0; i < keylen; i++) { hash = (hash << 4) + tolower(((unsigned char *)key)[i]); /* this assumes size of `int' is 32 bit */ if ((g = hash & 0xf0000000) != 0) { hash ^= g >> 24; hash ^= g; } } return (hash); } int gfarm_hash_key_equal_default(const void *key1, int key1len, const void *key2, int key2len) { return (key1len == key2len && memcmp(key1, key2, key1len) == 0); } int gfarm_hash_key_equal_casefold(const void *key1, int key1len, const void *key2, int key2len) { int i; if (key1len != key2len) return (0); for (i = 0; i < key1len; i++) { if (tolower(((unsigned char *)key1)[i]) != tolower(((unsigned char *)key2)[i])) return (0); } return (1); } struct gfarm_hash_entry { struct gfarm_hash_entry *next; int key_length; int data_length; double key_stub; }; #define HASH_KEY(entry) \ (((char *)(entry)) + \ ALIGN(offsetof(struct gfarm_hash_entry, key_stub))) #define HASH_DATA(entry) \ (HASH_KEY(entry) + ALIGN((entry)->key_length)) #define HASH_ENTRY_SIZE(keylen, datalen) \ (ALIGN(offsetof(struct gfarm_hash_entry, key_stub)) + \ ALIGN(keylen) + (datalen)) struct gfarm_hash_table { int table_size; int (*hash)(const void *, int); int (*equal)(const void *, int, const void *, int); struct gfarm_hash_entry *buckets[1]; }; struct gfarm_hash_table * gfarm_hash_table_alloc(int size, int (*hash)(const void *, int), int (*equal)(const void *, int, const void *, int)) { struct gfarm_hash_table *hashtab; hashtab = malloc(sizeof(struct gfarm_hash_table) + sizeof(struct gfarm_hash_entry *) * (size - 1)); if (hashtab == NULL) return (NULL); hashtab->table_size = size; hashtab->hash = hash; hashtab->equal = equal; memset(hashtab->buckets, 0, sizeof(struct gfarm_hash_entry *) * size); return (hashtab); } void gfarm_hash_table_free(struct gfarm_hash_table *hashtab) { int i; struct gfarm_hash_entry *p, *np; for (i = 0; i < hashtab->table_size; i++) { for (p = hashtab->buckets[i]; p != NULL; p = np) { np = p->next; free(p); } } free(hashtab); } static struct gfarm_hash_entry ** gfarm_hash_lookup_internal_search(struct gfarm_hash_table *hashtab, struct gfarm_hash_entry **pp, const void *key, int keylen) { struct gfarm_hash_entry *p; int (*equal)(const void *, int, const void *, int) = hashtab->equal; for (p = *pp; p != NULL; pp = &p->next, p = *pp) { if ((*equal)(HASH_KEY(p), p->key_length, key, keylen)) break; } return (pp); } #define HASH_BUCKET(hashtab, key, keylen) \ ((*hashtab->hash)(key, keylen) % hashtab->table_size) #define GFARM_HASH_LOOKUP_INTERNAL(hashtab, key, keylen) \ gfarm_hash_lookup_internal_search(hashtab, \ &hashtab->buckets[HASH_BUCKET(hashtab, key, keylen)], \ key, keylen) struct gfarm_hash_entry * gfarm_hash_lookup(struct gfarm_hash_table *hashtab, const void *key, int keylen) { struct gfarm_hash_entry **pp = GFARM_HASH_LOOKUP_INTERNAL(hashtab, key, keylen); return (*pp); } struct gfarm_hash_entry * gfarm_hash_enter(struct gfarm_hash_table *hashtab, const void *key, int keylen, int datalen, int *createdp) { struct gfarm_hash_entry *p, **pp = GFARM_HASH_LOOKUP_INTERNAL(hashtab, key, keylen); if (createdp != NULL) *createdp = 0; if (*pp != NULL) return (*pp); /* * create if not found */ p = malloc(HASH_ENTRY_SIZE(keylen, datalen)); if (p == NULL) return (NULL); *pp = p; p->next = NULL; p->key_length = keylen; p->data_length = datalen; memcpy(HASH_KEY(p), key, keylen); if (createdp != NULL) *createdp = 1; return (p); } int gfarm_hash_purge(struct gfarm_hash_table *hashtab, const void *key, int keylen) { struct gfarm_hash_entry *p, **pp = GFARM_HASH_LOOKUP_INTERNAL(hashtab, key, keylen); p = *pp; if (p == NULL) return (0); /* key is not found */ *pp = p->next; free(p); return (1); /* purged */ } void * gfarm_hash_entry_key(struct gfarm_hash_entry *entry) { return (HASH_KEY(entry)); } int gfarm_hash_entry_key_length(struct gfarm_hash_entry *entry) { return (entry->key_length); } void * gfarm_hash_entry_data(struct gfarm_hash_entry *entry) { return (HASH_DATA(entry)); } int gfarm_hash_entry_data_length(struct gfarm_hash_entry *entry) { return (entry->data_length); } /* * hash iterator */ int gfarm_hash_iterator_valid_entry(struct gfarm_hash_iterator *iterator) { struct gfarm_hash_table *hashtab = iterator->table; if (iterator->bucket_index >= hashtab->table_size) return (0); while (*iterator->pp == NULL) { if (++iterator->bucket_index >= hashtab->table_size) return (0); iterator->pp = &hashtab->buckets[iterator->bucket_index]; } return (1); } void gfarm_hash_iterator_begin(struct gfarm_hash_table *hashtab, struct gfarm_hash_iterator *iterator) { iterator->table = hashtab; iterator->bucket_index = 0; iterator->pp = &hashtab->buckets[0 /* == iterator->bucket_index */]; } void gfarm_hash_iterator_next(struct gfarm_hash_iterator *iterator) { if (*iterator->pp == NULL) iterator->bucket_index++; else iterator->pp = &(*iterator->pp)->next; } int gfarm_hash_iterator_is_end(struct gfarm_hash_iterator *iterator) { return (!gfarm_hash_iterator_valid_entry(iterator)); } struct gfarm_hash_entry * gfarm_hash_iterator_access(struct gfarm_hash_iterator *iterator) { if (gfarm_hash_iterator_valid_entry(iterator)) return (*iterator->pp); else return (NULL); } int gfarm_hash_iterator_lookup(struct gfarm_hash_table *hashtab, const void *key, int keylen, struct gfarm_hash_iterator *iterator) { iterator->table = hashtab; iterator->bucket_index = HASH_BUCKET(hashtab, key, keylen); iterator->pp = gfarm_hash_lookup_internal_search(hashtab, &hashtab->buckets[HASH_BUCKET(hashtab, key, keylen)], key, keylen); return (*iterator->pp != NULL); } int gfarm_hash_iterator_purge(struct gfarm_hash_iterator *iterator) { struct gfarm_hash_entry *p; if (!gfarm_hash_iterator_valid_entry(iterator)) return (0); /* not purged */ p = *iterator->pp; *iterator->pp = p->next; free(p); return (1); /* purged */ } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/host.h int gfarm_canonical_hostname_is_local(char *); int gfarm_host_is_local(char *); struct in_addr; char *gfarm_get_ip_addresses(int *, struct in_addr **); struct sockaddr; struct gfarm_hostspec; char *gfarm_host_address_use(struct gfarm_hostspec *); <file_sep>/gfarmfs-fuse/trunk/test/conf.sh.in #! /bin/sh FUSE_MODE=@fuse_mode@ <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/lib/libgfarm/gfarm/gfs_exec.c /* * $Id$ */ #include <unistd.h> #include <errno.h> #include <gfarm/gfarm.h> char * gfs_execve(const char *filename, char *const argv [], char *const envp[]) { char *hostname, *e; char **delivered_paths; if (!gfarm_is_url(filename)) { execve(filename, argv, envp); return gfarm_errno_to_error(errno); } e = gfarm_host_get_canonical_self_name(&hostname); if (e != NULL) return (e); e = gfarm_url_program_deliver(filename, 1, &hostname, &delivered_paths); if (e != NULL) return (e); execve(delivered_paths[0], argv, envp); return gfarm_errno_to_error(errno); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc4/include/gfarm/Makefile top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk EXEC_INCS= gfarm_config.h INCS= gfarm.h gfarm_error.h gfarm_metadb.h gfarm_misc.h gfarm_stringlist.h \ gfs.h gfs_glob.h \ gfs_hook.h include $(top_srcdir)/makes/include.mk <file_sep>/gfarm_zabbix/trunk/src/scripts/externalscripts/gfarm_gfmd_gfhost.sh.in #! /bin/sh # # External script for gfarm-zabbix. # # This script is assumed to be executed on gfmd hosts. # It tries executing 'gfhost' to check whether it can connect with # master gfmd servers and succeeds in authentication. # . @ZABBIX_EXTSCRIPTDIR@/gfarm_utils.inc # # Parse command line arguments. # # # Read a configuration file # CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/gfarm_conf.inc [ -f $CONF_FILE ] && . $CONF_FILE # # Create temporary files # outfile=/tmp/gfarm_gfmd_gfhost.out.$$ errfile=/tmp/gfarm_gfmd_gfhost.err.$$ trap "rm -f $outfile $errfile; log_err 'killed'; exit 1" 1 2 3 15 rm -f $outfile $errfile # # Execute 'gfhost'. # GFCMD="@GFARM_BINDIR@/gfhost -M" sudo -n -u _gfarmmd @GFARM_BINDIR@/gfservice-timeout $TIMEOUT \ $GFCMD > $outfile 2> $errfile GFCMD_EXITCODE=$? if check_auth_error $errfile; then echo "auth request to master gfmd failed" rm -f $outfile $errfile exit 0 elif [ $GFCMD_EXITCODE -ne 0 ]; then # We ignore the execution failure itself, since too many alerts will # be triggered if each file system node reports the failure. echo "ok" if [ $GFCMD_EXITCODE -eq $TIMEOUT_EXITCODE ]; then log_warning "'$GFCMD' failed, timeout" else log_warning "'$GFCMD' failed with the exit code $GFCMD_EXITCODE" fi [ -s $errfile ] && head -1 $errfile | log_warning rm -f $outfile $errfile exit 0 fi echo "ok" rm -f $outfile $errfile exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT1-2-3-3_gfsd_warning_and_error #! /bin/sh ###################################################################### TESTID="FT1-2-3-3" CATEGORY="accident causes no failover" SECTION="fsn accident" TITLE="gfsd warning and error" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfsd1 logger -p local0.err -t "gfsd[9999]" " unknown error" &&\ ssh $gfsd1 logger -p local0.warning -t "gfsd[9999]" " unknown warning" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfsd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfsd error message in /var/log/messages on $gfsd1" &&\ ft_check_mail "gfsd warning message in /var/log/messages on $gfsd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_checkpoint 3 "sleep $ADDITIONAL_TIME sec." $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfsd error message in /var/log/messages on $gfsd1" &&\ ft_check_mail "Re: gfsd warning message in /var/log/messages on $gfsd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_1_1_rc1/lib/libgfarm/gfarm/config.h extern int gfarm_initialized; extern int gfarm_is_active_file_system_node; extern char *gfarm_spool_root; extern int gfarm_spool_server_port; /* GFM dependent */ extern char *gfarm_metadb_server_name; extern int gfarm_metadb_server_port; /* LDAP dependent */ extern char *gfarm_ldap_server_name; extern char *gfarm_ldap_server_port; extern char *gfarm_ldap_base_dn; <file_sep>/gfarm/tags/gfarm_1_0_2_rc1/gftool/gfps/gfps.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfj_client.h" #include "auth.h" char *program_name = "gfps"; void usage() { fprintf(stderr, "Usage: %s [-al] [<job_id>...]\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-a\tlist all user\n"); fprintf(stderr, "\t-l\tdetailed output\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern int optind; int ch, do_all = 0, do_detailed = 0; int n, i, j, *joblist; struct gfarm_job_info *info, *infos; char *e; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "al?")) != -1) { switch (ch) { case 'a': do_all = 1; break; case 'l': do_detailed = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfj_initialize(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc > 0) { n = argc; joblist = malloc(sizeof(int) * n); if (joblist == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(1); } for (i = 0; i < argc; i++) joblist[i] = atoi(argv[i]); } else { e = gfj_client_list(gfarm_jobmanager_server, do_all ? "" : gfarm_get_global_username(), &n, &joblist); } if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } infos = malloc(sizeof(struct gfarm_job_info) * n); if (infos == NULL) { fprintf(stderr, "%s: no memory\n", program_name); exit(1); } e = gfj_client_info(gfarm_jobmanager_server, n, joblist, infos); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < n; i++) { info = &infos[i]; /* * infos[i] may be invalid when there is no process * having the specified process id. */ if (info->user == NULL) continue; printf("%6d %8s@%-10.10s %-8s %4d", joblist[i], info->user, info->originate_host, info->job_type, info->total_nodes); for (j = 0; j < info->argc; j++) printf(" %s", info->argv[j]); printf("\n"); if (do_detailed) { printf("\t"); printf("%s", info->nodes[0].hostname); for (j = 1; j < info->total_nodes; j++) printf(", %s", info->nodes[j].hostname); printf("\n"); } } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_2/configure.ac # -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT([gfarm2fs], [1.2.9.2]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AM_MAINTAINER_MODE AC_CONFIG_SRCDIR([gfarm2fs.c]) AC_CONFIG_HEADER([config.h]) AC_CONFIG_FILES([Makefile contrib/Makefile contrib/mount.gfarm2fs/Makefile contrib/mount.gfarm2fs/mount.gfarm2fs contrib/gfarm2fs-exec/Makefile contrib/gfarm2fs-proxy-info/Makefile systest/Makefile systest/testcases/Makefile systest/scenarios/Makefile systest/common_scripts/Makefile systest/plugins/Makefile]) AC_CONFIG_MACRO_DIR([m4]) AC_SYS_LARGEFILE # Checks for programs. AC_PROG_CC AC_PROG_LIBTOOL ### --with-gfarm=GFARM_ROOT AC_MSG_CHECKING([for Gfarm file system]) AC_ARG_WITH([gfarm], AC_HELP_STRING([--with-gfarm=GFARM_ROOT], [Gfarm root directory [[/usr]]])) case x$with_gfarm in x|xyes|xno) with_gfarm=/usr ;; esac if test x"$with_gfarm" != x/usr; then CPPFLAGS="$CPPFLAGS -I$with_gfarm/include" LDFLAGS="$LDFLAGS -L$with_gfarm/lib" fi AC_MSG_RESULT([$with_gfarm]) ### --with-private-srcdir ### This is provided to replace some functionalities with your private code. AC_MSG_CHECKING([for private source directory]) AC_ARG_WITH([private_srcdir], AC_HELP_STRING([--with-private-srcdir=DIR], [private source directory])) case x$with_private_srcdir in x|xno) top_private_dir="" private_srcs="" AC_MSG_RESULT([no]) ;; *) if test -d "${with_private_srcdir}"; then top_private_dir="`(cd ${with_private_srcdir}; /bin/pwd)`" private_srcs="replicate_private.c private_gfarm2fs_msg_enums.h" AC_MSG_RESULT([${top_private_dir}]) AC_DEFINE(HAVE_PRIVATE_SRCS, [1], [Define to 1 if you have private sources]) else AC_MSG_ERROR([${with_private_srcdir} is not a directory.]) fi esac AC_SUBST(top_private_dir) AC_SUBST(private_srcs) ### --disable-xattr AC_ARG_ENABLE(xattr, AS_HELP_STRING([--disable-xattr], [disable extended attribute]), [], [enable_xattr=yes]) if test "x$enable_xattr" != xno; then AC_DEFINE(ENABLE_XATTR, [1], [support extended attribute]) fi ### --disable-acl AC_ARG_ENABLE(acl, AS_HELP_STRING([--disable-acl], [disable extended ACL]), [], [enable_acl=yes]) if test "x$enable_acl" != xno; then if test "x$enable_xattr" = xno; then AC_MSG_ERROR([extended ACL requires extended attribute. specify --disable-acl]) fi AC_DEFINE(ENABLE_ACL, [1], [support extended ACL]) fi # Checks for header files. AC_CHECK_HEADERS([gfarm/gfarm.h],, [AC_MSG_ERROR([gfarm/gfarm.h not found])]) # fuse.h requres _FILE_OFFSET_BITS is defined in any case, but # AC_SYS_LARGEFILE does not define it on a 64bit platform like x86_64 # since it is not necessary. To avoid this problem we just skip the check. #AC_CHECK_HEADERS([fuse.h],, [AC_MSG_ERROR([fuse.h not found])]) AC_CHECK_HEADERS(sys/xattr.h,, if test "x$enable_xattr" != xno; then AC_MSG_ERROR([sys/xattr.h not found. specify --disable-xattr]) fi) AC_CHECK_HEADERS(sys/acl.h,, if test "x$enable_acl" != xno; then AC_MSG_ERROR([sys/acl.h not found. specify --disable-acl]) fi) # Checks for libraries. AC_CHECK_LIB([gfarm], [gfarm_initialize],, [AC_MSG_ERROR([libgfarm not found])]) AC_CHECK_LIB([gfarm], [gfarm_get_global_username_by_url],, [AC_MSG_ERROR([Gfarm-2.4.2 or later is required])]) AC_SEARCH_LIBS([fuse_opt_parse], [fuse refuse],, [AC_MSG_ERROR([libfuse not found])]) # Checks for typedefs, structures, and compiler characteristics. AC_CHECK_MEMBERS([struct stat.st_mtim.tv_nsec]) # Checks for library functions. AC_CHECK_FUNCS(gfs_replicate_file_to gfarm_schedule_cache_dump gfs_getxattr_cached gfarm_xattr_caching gfarm_xattr_caching_pattern_add gfs_lchown gfs_lutimes gfarm_version) AC_TRY_RUN([ # include <fuse.h> void *data_save; int opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { data_save = data; } int main(int argc, char **argv) { struct fuse_args args = FUSE_ARGS_INIT(argc, argv); int data; fuse_opt_parse(&args, &data, NULL, opt_proc); if (data_save == &data) return 1; return 0; /* have a bug on NetBSD */ } ], [AC_DEFINE(HAVE_BUG_OF_FUSE_OPT_PARSE_ON_NETBSD)], [] ) AH_BOTTOM([ /* fuse_opt_parse() doesn't correctly pass 2nd arg on NetBSD-5.1 and before */ #undef HAVE_BUG_OF_FUSE_OPT_PARSE_ON_NETBSD ]) AC_OUTPUT <file_sep>/gfarm/tags/gfarm_0_1/bench/thput-fsys/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk CFLAGS = $(COMMON_CFLAGS) LDLIBS = $(COMMON_LDFLAGS) $(LIBS) PROGRAM = thput-fsys OBJS = thput-fsys.o all: $(PROGRAM) include $(top_srcdir)/makes/prog.mk <file_sep>/gfarm/tags/gfarm_1_1_1_rc3/gftool/gfarm_agent/gfarm_agent.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <stdio.h> #include <errno.h> #include <syslog.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <signal.h> #include <gfarm/gfarm.h> #include "gfutil.h" #include "xxx_proto.h" #include "io_fd.h" #include "agent_proto.h" #include "agent_wrap.h" #include "agent_thr.h" #include "agent_ptable.h" #ifdef SOMAXCONN #define LISTEN_BACKLOG SOMAXCONN #else #define LISTEN_BACKLOG 5 #endif char *program_name = "gfarm_agent"; int debug_mode = 0; /* this routine should be called before calling exit(). */ static void cleanup(void) { /* disconnect, do logging */ gflog_notice("disconnected", NULL); } static void log_proto(char *proto, char *status) { gflog_notice(proto, status); } static void error_proto(char *proto, char *status) { cleanup(); gflog_error(proto, status); } static char * agent_server_get_request(struct xxx_connection *client, char *diag, char *format, ...) { va_list ap; char *e; int eof; va_start(ap, format); e = xxx_proto_vrecv(client, 0, &eof, &format, &ap); va_end(ap); if (e == NULL) { if (eof) e = "missing RPC argument"; else if (*format != '\0') e = "invalid format character to get request"; } if (e != NULL) error_proto(diag, e); return (e); } static char * agent_server_put_reply_common(struct xxx_connection *client, char *diag, int ecode, char *format, va_list *app) { char *e; e = xxx_proto_send(client, "i", (gfarm_int32_t)ecode); if (e != NULL) { error_proto(diag, e); return (e); } if (ecode == 0) { e = xxx_proto_vsend(client, &format, app); if (e != NULL) error_proto(diag, e); if (*format != '\0') { e = "invalid format character to put reply"; error_proto(diag, e); } } return (e); } static char * agent_server_put_reply(struct xxx_connection *client, char *diag, char *error, char *format, ...) { va_list ap; int eno; char *e; if (error == NULL) eno = 0; else eno = gfarm_error_to_errno(error); va_start(ap, format); e = agent_server_put_reply_common(client, diag, eno, format, &ap); va_end(ap); return (e); } static char * agent_server_path_info_get(struct xxx_connection *client) { char *path, *e, *e_rpc; struct gfarm_path_info pi; e_rpc = agent_server_get_request(client, "path_info_get", "s", &path); if (e_rpc != NULL) return (e_rpc); /* protocol error */ e = gfarm_i_path_info_get(path, &pi); free(path); e_rpc = agent_server_put_reply( client, "path_info_get", e, "siissoiiiiiii", pi.pathname, pi.status.st_ino, pi.status.st_mode, pi.status.st_user, pi.status.st_group, pi.status.st_size, pi.status.st_nsections, pi.status.st_atimespec.tv_sec, pi.status.st_atimespec.tv_nsec, pi.status.st_mtimespec.tv_sec, pi.status.st_mtimespec.tv_nsec, pi.status.st_ctimespec.tv_sec, pi.status.st_ctimespec.tv_nsec); if (e == NULL) gfarm_path_info_free(&pi); if (e != NULL) log_proto("path_info_get", e); return (e_rpc); } static char * agent_server_path_info_set(struct xxx_connection *client) { char *pathname, *e, *e_rpc; struct gfarm_path_info pi; struct gfs_stat *st = &pi.status; e_rpc = agent_server_get_request( client, "path_info_set", "siissoiiiiiii", &pathname, &st->st_ino, &st->st_mode, &st->st_user, &st->st_group, &st->st_size, &st->st_nsections, &st->st_atimespec.tv_sec, &st->st_atimespec.tv_nsec, &st->st_mtimespec.tv_sec, &st->st_mtimespec.tv_nsec, &st->st_ctimespec.tv_sec, &st->st_ctimespec.tv_nsec); if (e_rpc != NULL) return (e_rpc); pi.pathname = pathname; e = gfarm_i_path_info_set(pathname, &pi); /* pathname will be free'ed in gfarm_path_info_free(&pi) */ gfarm_path_info_free(&pi); e_rpc = agent_server_put_reply(client, "path_info_set", e, ""); if (e != NULL) log_proto("path_info_set", e); return (e_rpc); } static char * agent_server_path_info_replace(struct xxx_connection *client) { char *pathname, *e, *e_rpc; struct gfarm_path_info pi; struct gfs_stat *st = &pi.status; e_rpc = agent_server_get_request( client, "path_info_replace", "siissoiiiiiii", &pathname, &st->st_ino, &st->st_mode, &st->st_user, &st->st_group, &st->st_size, &st->st_nsections, &st->st_atimespec.tv_sec, &st->st_atimespec.tv_nsec, &st->st_mtimespec.tv_sec, &st->st_mtimespec.tv_nsec, &st->st_ctimespec.tv_sec, &st->st_ctimespec.tv_nsec); if (e_rpc != NULL) return (e_rpc); pi.pathname = pathname; e = gfarm_i_path_info_replace(pathname, &pi); gfarm_path_info_free(&pi); e_rpc = agent_server_put_reply(client, "path_info_replace", e, ""); if (e != NULL) log_proto("path_info_replace", e); return (e_rpc); } static char * agent_server_path_info_remove(struct xxx_connection *client) { char *pathname, *e, *e_rpc; e_rpc = agent_server_get_request( client, "path_info_remove", "s", &pathname); if (e_rpc != NULL) return (e_rpc); e = gfarm_i_path_info_remove(pathname); free(pathname); e_rpc = agent_server_put_reply(client, "path_info_remove", e, ""); if (e != NULL) log_proto("path_info_remove", e); return (e_rpc); } static char * agent_server_realpath_canonical(struct xxx_connection *client) { char *path, *abspath, *e, *e_rpc; e_rpc = agent_server_get_request( client, "realpath_canonical", "s", &path); if (e_rpc != NULL) return (e_rpc); e = gfs_i_realpath_canonical(path, &abspath); free(path); e_rpc = agent_server_put_reply( client, "realpath_canonical", e, "s", abspath); if (e == NULL) free(abspath); if (e != NULL) log_proto("realpath_canonical", e); return (e_rpc); } static char * agent_server_get_ino(struct xxx_connection *client) { char *path, *e, *e_rpc; long ino; e_rpc = agent_server_get_request(client, "get_ino", "s", &path); if (e_rpc != NULL) return (e_rpc); e = gfs_i_get_ino(path, &ino); free(path); e_rpc = agent_server_put_reply(client, "get_ino", e, "i", ino); if (e != NULL) log_proto("get_ino", e); return (e_rpc); } static char * agent_server_opendir(struct xxx_connection *client) { char *path, *e, *e_rpc; GFS_Dir dir; int dir_index = -1; e_rpc = agent_server_get_request(client, "opendir", "s", &path); if (e_rpc != NULL) return (e_rpc); e = gfs_i_opendir(path, &dir); free(path); if (e == NULL) { dir_index = agent_ptable_entry_add(dir); if (dir_index < 0) { e = GFARM_ERR_NO_SPACE; (void)gfs_i_closedir(dir); } } e_rpc = agent_server_put_reply(client, "opendir", e, "i", dir_index); if (e != NULL) log_proto("opendir", e); return (e_rpc); } static char * agent_server_readdir(struct xxx_connection *client) { char *e, *e_rpc; int dir_index; GFS_Dir dir; struct gfs_dirent *entry; e_rpc = agent_server_get_request(client, "readdir", "i", &dir_index); if (e_rpc != NULL) return (e_rpc); dir = agent_ptable_entry_get(dir_index); if (dir) e = gfs_i_readdir(dir, &entry); else e = GFARM_ERR_NO_SUCH_OBJECT; /* XXX - EBADF */ if (entry) e_rpc = agent_server_put_reply( client, "readdir", e, "ihccs", entry->d_fileno, entry->d_reclen, entry->d_type, entry->d_namlen, entry->d_name); else e_rpc = agent_server_put_reply( client, "readdir", e, "ihccs", 0, 0, 0, 1, ""); if (e != NULL) log_proto("readdir", e); return (e_rpc); } static char * agent_server_closedir(struct xxx_connection *client) { char *e, *e_rpc; int dir_index; GFS_Dir dir; e_rpc = agent_server_get_request(client, "closedir", "i", &dir_index); if (e_rpc != NULL) return (e_rpc); dir = agent_ptable_entry_get(dir_index); if (dir) e = gfs_i_closedir(dir); else e = GFARM_ERR_NO_SUCH_OBJECT; /* XXX - EBADF */ if (e == NULL) agent_ptable_entry_delete(dir_index); e_rpc = agent_server_put_reply(client, "closedir", e, ""); if (e != NULL) log_proto("closedir", e); return (e_rpc); } static char * agent_server_dirname(struct xxx_connection *client) { char *e_rpc, *name = NULL; int dir_index; GFS_Dir dir; e_rpc = agent_server_get_request(client, "dirname", "i", &dir_index); if (e_rpc != NULL) return (e_rpc); dir = agent_ptable_entry_get(dir_index); if (dir) name = gfs_i_dirname(dir); e_rpc = agent_server_put_reply(client, "dirname", NULL, "s", name != NULL ? name : GFARM_ERR_NO_SUCH_OBJECT); if (name == NULL) log_proto("dirname", GFARM_ERR_NO_SUCH_OBJECT); return (e_rpc); } static char * agent_server_uncachedir(struct xxx_connection *client) { char *e_rpc; e_rpc = agent_server_get_request(client, "uncachedir", ""); if (e_rpc != NULL) return (e_rpc); gfs_i_uncachedir(); e_rpc = agent_server_put_reply(client, "uncachedir", NULL, ""); return (e_rpc); } static int gfarm_initialized = 0; void * server(void *arg) { int client_fd = *(int *)arg; char *e; struct xxx_connection *client; int eof; gfarm_int32_t request; char buffer[GFARM_INT32STRLEN]; agent_ptable_alloc(); agent_lock(); if (!gfarm_initialized) { e = gfarm_initialize(NULL, NULL); if (e == NULL) gfarm_initialized = 1; else { (void)gfarm_terminate(); close(client_fd); agent_unlock(); error_proto("gfarm_initialize", e); return (NULL); } } agent_unlock(); agent_lock(); e = gfarm_metadb_check(); if (e != NULL) { log_proto("gfarm_metadb_check", e); e = gfarm_metadb_initialize(); if (e != NULL) { close(client_fd); agent_unlock(); error_proto("gfarm_metadb_initialize", e); return (NULL); } gfs_i_uncachedir(); } agent_unlock(); e = xxx_fd_connection_new(client_fd, &client); if (e != NULL) { close(client_fd); error_proto("xxx_connection_new", e); return (NULL); } for (;;) { char *cmd; e = xxx_proto_recv(client, 0, &eof, "i", &request); if (e != NULL) { error_proto("request number", e); goto exit_free_conn; } if (eof) { cleanup(); goto exit_free_conn; } agent_lock(); switch (request) { case AGENT_PROTO_PATH_INFO_GET: cmd = "path_info_get"; e = agent_server_path_info_get(client); break; case AGENT_PROTO_PATH_INFO_SET: cmd = "path_info_set"; e = agent_server_path_info_set(client); break; case AGENT_PROTO_PATH_INFO_REPLACE: cmd = "path_info_replace"; e = agent_server_path_info_replace(client); break; case AGENT_PROTO_PATH_INFO_REMOVE: cmd = "path_info_remove"; e = agent_server_path_info_remove(client); break; case AGENT_PROTO_REALPATH_CANONICAL: cmd = "realpath_canonical"; e = agent_server_realpath_canonical(client); break; case AGENT_PROTO_GET_INO: cmd = "get_ino"; e = agent_server_get_ino(client); break; case AGENT_PROTO_OPENDIR: cmd = "opendir"; e = agent_server_opendir(client); break; case AGENT_PROTO_READDIR: cmd = "readdir"; e = agent_server_readdir(client); break; case AGENT_PROTO_CLOSEDIR: cmd = "closedir"; e = agent_server_closedir(client); break; case AGENT_PROTO_DIRNAME: cmd = "dirname"; e = agent_server_dirname(client); break; case AGENT_PROTO_UNCACHEDIR: cmd = "uncachedir"; e = agent_server_uncachedir(client); break; default: sprintf(buffer, "%d", (int)request); gflog_warning("unknown request", buffer); agent_unlock(); cleanup(); goto exit_free_conn; } agent_unlock(); if (e != NULL) { /* protocol error */ error_proto(cmd, e); goto exit_free_conn; } } exit_free_conn: /* 'client_fd' will be free'ed in xxx_connection_free() */ e = xxx_connection_free(client); if (e != NULL) error_proto("xxx_connection_free", e); return (NULL); } static char *sock_dir; static char *sock_path; static enum { UNDECIDED, B_SHELL_LIKE, C_SHELL_LIKE } shell_type; static void guess_shell_type(void) { char *shell; if (shell_type == UNDECIDED && (shell = getenv("SHELL")) != NULL) { int shell_len = strlen(shell); if (shell_len < 3 || memcmp(shell + shell_len - 3, "csh", 3) != 0) shell_type = B_SHELL_LIKE; else shell_type = C_SHELL_LIKE; } } static void display_env(int fd) { FILE *f = fdopen(fd, "w"); pid_t pid = getpid(); if (f == NULL) return; guess_shell_type(); switch (shell_type) { case B_SHELL_LIKE: fprintf(f, "GFARM_AGENT_SOCK=%s; export GFARM_AGENT_SOCK;\n", sock_path); fprintf(f, "GFARM_AGENT_PID=%d; export GFARM_AGENT_PID;\n", pid); fprintf(f, "echo Agent pid %d;\n", pid); break; case C_SHELL_LIKE: fprintf(f, "setenv GFARM_AGENT_SOCK %s;\n", sock_path); fprintf(f, "setenv GFARM_AGENT_PID %d;\n", pid); fprintf(f, "echo Agent pid %d;\n", pid); break; default: break; } fclose(f); } void sigterm_handler(int sig) { if (sock_path) unlink(sock_path); if (sock_dir) rmdir(sock_dir); exit(1); } #define AGENT_SOCK_TEMPLATE "/tmp/.gfarm-XXXXXX" int open_accepting_socket(void) { struct sockaddr_un self_addr; socklen_t self_addr_size; int sock, sockopt; char *sdir, sockdir[] = AGENT_SOCK_TEMPLATE; char tmpsoc[7 + GFARM_INT32STRLEN]; sdir = mkdtemp(sockdir); if (sdir == NULL) gflog_fatal_errno("mkdtemp"); sock_dir = strdup(sdir); sprintf(tmpsoc, "/agent.%ld", (long)getpid()); memset(&self_addr, 0, sizeof(self_addr)); self_addr.sun_family = AF_UNIX; strcpy(self_addr.sun_path, sdir); strcat(self_addr.sun_path, tmpsoc); self_addr_size = sizeof(self_addr); sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { (void)rmdir(sdir); gflog_fatal_errno("accepting socket"); } sockopt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) == -1) gflog_warning_errno("SO_REUSEADDR"); if (bind(sock, (struct sockaddr *)&self_addr, self_addr_size) < 0) { (void)unlink(self_addr.sun_path); (void)rmdir(sdir); gflog_fatal_errno("bind accepting socket"); } if (listen(sock, LISTEN_BACKLOG) < 0) { (void)unlink(self_addr.sun_path); (void)rmdir(sdir); gflog_fatal_errno("listen"); } sock_path = strdup(self_addr.sun_path); return (sock); } void usage(void) { fprintf(stderr, "Usage: %s [option]\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-c\t\tGenerate C-shell commands\n"); fprintf(stderr, "\t-s\t\tGenerate Bourne shell commands\n"); fprintf(stderr, "\t-d\t\tdebug mode\n"); fprintf(stderr, "\t-f <gfarm-configuration-file>\n"); fprintf(stderr, "\t-P <pid-file>\n"); fprintf(stderr, "\t-S <syslog-facility>\n"); fprintf(stderr, "\t-v\n"); exit(1); } int main(int argc, char **argv) { extern char *optarg; extern int optind; struct sockaddr_un client_addr; socklen_t client_addr_size; char *e, *config_file = NULL, *pid_file = NULL; FILE *pid_fp = NULL; int syslog_facility = GFARM_DEFAULT_FACILITY; int ch, accepting_sock, client, stdout_fd; if (argc >= 1) program_name = basename(argv[0]); gflog_set_identifier(program_name); while ((ch = getopt(argc, argv, "cdf:P:sS:v")) != -1) { switch (ch) { case 'c': shell_type = C_SHELL_LIKE; break; case 'd': debug_mode = 1; break; case 'f': config_file = optarg; break; case 'P': pid_file = optarg; break; case 's': shell_type = B_SHELL_LIKE; break; case 'S': syslog_facility = gflog_syslog_name_to_facility(optarg); if (syslog_facility == -1) gflog_fatal(optarg, "unknown syslog facility"); break; case 'v': gflog_auth_set_verbose(1); break; case '?': default: usage(); } } argc -= optind; argv += optind; if (config_file != NULL) gfarm_config_set_filename(config_file); /* * Gfarm_initialize() may fail when the metadata server is not * running at start-up time. In this case, retry at connection time. */ gfarm_agent_disable(); gfarm_metadb_share_connection(); e = gfarm_initialize(NULL, NULL); if (e == NULL) gfarm_initialized = 1; else (void)gfarm_terminate(); accepting_sock = open_accepting_socket(); stdout_fd = dup(1); if (pid_file != NULL) { /* * We do this before calling gfarm_daemon() * to print the error message to stderr. */ pid_fp = fopen(pid_file, "w"); if (pid_fp == NULL) gflog_fatal_errno(pid_file); } if (!debug_mode) { gflog_syslog_open(LOG_PID, syslog_facility); gfarm_daemon(0, 0); } if (pid_file != NULL) { /* * We do this after calling gfarm_daemon(), * because it changes pid. */ fprintf(pid_fp, "%ld\n", (long)getpid()); fclose(pid_fp); } display_env(stdout_fd); signal(SIGTERM, sigterm_handler); signal(SIGPIPE, SIG_IGN); for (;;) { client_addr_size = sizeof(client_addr); client = accept(accepting_sock, (struct sockaddr *)&client_addr, &client_addr_size); if (client < 0) { if (errno == EINTR) continue; gflog_fatal_errno("accept"); } agent_schedule(&client, server); } /*NOTREACHED*/ return (0); /* to shut up warning */ } <file_sep>/gfarm_samba/trunk/Makefile.am ACLOCAL_AMFLAGS = -I m4 nobase_lib_LTLIBRARIES = vfs/gfarm.la vfs_gfarm_la_SOURCES = gfarm.c gfarm_acl.c gfarm_acl.h gfarm_id.c gfarm_id.h gfarm_hash.h msgno/msgno.h vfs_gfarm_la_LDFLAGS = -module AM_CFLAGS = -Wall EXTRA_DIST = README # gflog message number assignment ASSIGNMSGNO=$(top_srcdir)/msgno/assign_msgno.pl .PHONY: msgno msgno: GFARM_TOPDIR=$(top_srcdir) $(ASSIGNMSGNO) $(vfs_gfarm_la_SOURCES) <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfjournal_gfmd.sh #!/bin/sh # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command RESULT=`gfjournal -m /var/gfarm-metadata/journal/0000000000.gmj` if [ $? != 0 ]; then echo -1; exit 0; fi echo $RESULT exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_pgsql.sh #!/bin/sh # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_pgsql.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command RESULT=-1 case "$1" in version) RESULT=`psql --version|head -n1` ;; process) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -c \ "select sum(numbackends) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; commit) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -c \ "select sum(xact_commit) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; rollback) RESULT=`psql -U $DB_USER -h $DB_HOST -p $DB_PORT -t -c \ "select sum(xact_rollback) from pg_stat_database" \ $DB_NAME 2> /dev/null` ;; *) RESULT=-1 esac if [ $? != 0 ]; then RESULT=-1 fi echo $RESULT exit 0 <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfsched_gfmd.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1 exit 0 fi # exec check command RESULT=`gfsched $*` if [ $? != 0 ]; then RESULT="error: gfsched $* error." else if [ -z "${RESULT}" ]; then RESULT="gfsched show no fsn." fi fi echo $RESULT exit 0 <file_sep>/gfarmfs-fuse/trunk/test/expected/Makefile.am SUBDIRS = default fuse25_linux26_old freebsd <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_2/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_mastername_cli.sh.in #!/bin/sh # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1; exit 0; fi # exec check command if [ -f $MDS_LIST_PATH ]; then RESULT=`grep '^+ master' $MDS_LIST_PATH | awk '{ print $6 }'` else RESULT="error: $MDS_LIST not found." fi echo $RESULT exit 0 <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfarm/agent_wrap.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <limits.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <gfarm/gfarm.h> #include "agent_client.h" #include "agent_wrap.h" extern char *gfarm_client_initialize(int *, char ***); extern char *gfarm_client_terminate(void); static int gfarm_agent_enabled = 1; static struct agent_connection *agent_server; static pid_t agent_pid; char GFARM_AGENT_ERR_NO_AGENT[] = "no agent connection"; void gfarm_agent_disable(void) { gfarm_agent_enabled = 0; } char *gfarm_agent_connect(char *); char *gfarm_agent_disconnect(void); static char * gfarm_agent_check(void) { if (!gfarm_agent_enabled) return (GFARM_AGENT_ERR_NO_AGENT); if (agent_server != NULL) { if (agent_pid == getpid()) return (NULL); else gfarm_agent_disconnect(); } return (gfarm_agent_connect(NULL)); } char * gfarm_agent_connect(char *path) { struct sockaddr_un peer_addr; if (agent_server != NULL) return ("already connected"); if (path == NULL) path = getenv("GFARM_AGENT_SOCK"); if (path == NULL) return (GFARM_AGENT_ERR_NO_AGENT); memset(&peer_addr, 0, sizeof(peer_addr)); peer_addr.sun_family = AF_UNIX; strcpy(peer_addr.sun_path, path); agent_pid = getpid(); return (agent_client_connect(&peer_addr, &agent_server)); } char * gfarm_agent_disconnect() { char *e; if (agent_server == NULL) return ("already disconnected"); e = agent_client_disconnect(agent_server); if (e == NULL) { agent_server = NULL; agent_pid = 0; } return (e); } char * gfarm_initialize(int *argc, char ***argv) { if (gfarm_agent_enabled) (void)gfarm_agent_connect(NULL); return (gfarm_client_initialize(argc, argv)); } char * gfarm_terminate(void) { gfarm_agent_disconnect(); return (gfarm_client_terminate()); } char * gfarm_path_info_get(const char *path, struct gfarm_path_info *info) { if (gfarm_agent_check() == NULL) return (agent_client_path_info_get(agent_server, path, info)); else return (gfarm_i_path_info_get(path, info)); } char * gfarm_path_info_set(char *path, struct gfarm_path_info *info) { if (gfarm_agent_check() == NULL) return (agent_client_path_info_set(agent_server, path, info)); else return (gfarm_i_path_info_set(path, info)); } char * gfarm_path_info_replace(char *path, struct gfarm_path_info *info) { if (gfarm_agent_check() == NULL) return (agent_client_path_info_replace( agent_server, path, info)); else return (gfarm_i_path_info_replace(path, info)); } char * gfarm_path_info_remove(const char *path) { if (gfarm_agent_check() == NULL) return (agent_client_path_info_remove(agent_server, path)); else return (gfarm_i_path_info_remove(path)); } char * gfs_realpath_canonical(const char *path, char **abspathp) { char *e, cwd[PATH_MAX + 1]; /* cwd is maintained by a client */ if (path[0] != '/') { e = gfs_getcwd(cwd, sizeof(cwd)); if (e != NULL) return (e); if (strlen(cwd) + 1 + strlen(path) + 1 > sizeof(cwd)) return (GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE); strcat(cwd, "/"); strcat(cwd, path); path = cwd; } if (gfarm_agent_check() == NULL) return (agent_client_realpath_canonical( agent_server, path, abspathp)); else return (gfs_i_realpath_canonical(path, abspathp)); } char * gfs_get_ino(const char *canonic_path, long *inop) { char *e; gfarm_int32_t ip; if (gfarm_agent_check() == NULL) { e = agent_client_get_ino(agent_server, canonic_path, &ip); if (e == NULL) *inop = (long)ip; return (e); } else return (gfs_i_get_ino(canonic_path, inop)); } char * gfs_opendir(const char *path, GFS_Dir *dirp) { char *e, cwd[PATH_MAX + 1]; path = gfarm_url_prefix_skip(path); /* cwd is maintained by a client */ if (path[0] != '/') { e = gfs_getcwd(cwd, sizeof(cwd)); if (e != NULL) return (e); if (strlen(cwd) + 1 + strlen(path) + 1 > sizeof(cwd)) return (GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE); strcat(cwd, "/"); strcat(cwd, path); path = cwd; } if (gfarm_agent_check() == NULL) return (agent_client_opendir(agent_server, path, dirp)); else return (gfs_i_opendir(path, dirp)); } char * gfs_readdir(GFS_Dir dir, struct gfs_dirent **entry) { if (gfarm_agent_check() == NULL) return (agent_client_readdir(agent_server, dir, entry)); else return (gfs_i_readdir(dir, entry)); } char * gfs_closedir(GFS_Dir dir) { if (gfarm_agent_check() == NULL) return (agent_client_closedir(agent_server, dir)); else return (gfs_i_closedir(dir)); } char * gfs_dirname(GFS_Dir dir) { if (gfarm_agent_check() == NULL) return (agent_client_dirname(agent_server, dir)); else return (gfs_i_dirname(dir)); } void gfs_uncachedir(void) { if (gfarm_agent_check() == NULL) agent_client_uncachedir(agent_server); else gfs_i_uncachedir(); } <file_sep>/gfarm/tags/gfarm_1_0_beta_6/include/gfarm/gfarm_metadb.h /* * $Id$ */ #include <gfarm/gfarm_config.h> char *gfarm_metadb_initialize(void); char *gfarm_metadb_terminate(void); /* ---------------------------------------- */ /* * GFarm host table: * (hostname) -> (architecture, ncpu) */ struct gfarm_host_info { char *hostname; int nhostaliases; char **hostaliases; char *architecture; int ncpu; }; #define GFARM_HOST_INFO_NCPU_NOT_SET (-1) void gfarm_host_info_free(struct gfarm_host_info *); char *gfarm_host_info_get(char *, struct gfarm_host_info *); char *gfarm_host_info_set(char *, struct gfarm_host_info *); char *gfarm_host_info_replace(char *, struct gfarm_host_info *); char *gfarm_host_info_remove(char *); char *gfarm_host_info_remove_hostaliases(char *); void gfarm_host_info_free_all(int, struct gfarm_host_info *); char *gfarm_host_info_get_all(int *, struct gfarm_host_info **); char *gfarm_host_info_get_by_name_alias(const char *, struct gfarm_host_info *); char *gfarm_host_info_get_allhost_by_architecture(const char *, int *, struct gfarm_host_info **); /* convenience function */ char *gfarm_host_info_get_architecture_by_host(char *); /* ---------------------------------------- */ /* * GFarm filesystem directory / i-node information: * (pathname) -> (status) */ struct gfarm_path_info { char *pathname; /* * In meta DB, the following fields differ from reality: * status.st_size: always 0 * status.st_nsections: 0, if the path is not fragmented file. */ struct gfs_stat status; }; void gfarm_path_info_free(struct gfarm_path_info *); char *gfarm_path_info_get(char *, struct gfarm_path_info *); char *gfarm_path_info_set(char *, struct gfarm_path_info *); char *gfarm_path_info_replace(char *, struct gfarm_path_info *); char *gfarm_path_info_remove(char *); /* XXX - this is for a stopgap implementation of gfs_opendir() */ char *gfarm_path_info_get_all_foreach( void (*)(void *, struct gfarm_path_info *), void *); void gfarm_path_free_all(int, char **); char *gfarm_path_get_all_children(char *, int *, char ***); /* ---------------------------------------- */ /* * GFarmFile section database: * (pathname, section) -> (section_info) * * the `section' means: * serial number for fragments * architecture for programs */ struct gfarm_file_section_info { char *pathname; char *section; file_offset_t filesize; char *checksum_type; char *checksum; }; void gfarm_file_section_info_free(struct gfarm_file_section_info *); char *gfarm_file_section_info_get(char *, char *, struct gfarm_file_section_info *); char *gfarm_file_section_info_set(char *, char *, struct gfarm_file_section_info *); char *gfarm_file_section_info_remove(const char *, const char *); void gfarm_file_section_info_free_all(int, struct gfarm_file_section_info *); char *gfarm_file_section_info_get_all_by_file(char *, int *, struct gfarm_file_section_info **); char *gfarm_file_section_info_get_sorted_all_serial_by_file(char *, int *, struct gfarm_file_section_info **); char *gfarm_file_section_info_remove_all_by_file(char *); /* convenience function */ int gfarm_file_section_info_does_exist(char *, char *); /* ---------------------------------------- */ /* * GFarm file_section delivery map: * (GFarmFile, section, hostname) -> () */ struct gfarm_file_section_copy_info { char *pathname; char *section; char *hostname; }; void gfarm_file_section_copy_info_free(struct gfarm_file_section_copy_info *); char *gfarm_file_section_copy_info_get(char *, char *, char *, struct gfarm_file_section_copy_info *); char *gfarm_file_section_copy_info_set(char *, char *, char *, struct gfarm_file_section_copy_info *); char *gfarm_file_section_copy_info_remove(const char *, const char *, const char *); void gfarm_file_section_copy_info_free_all(int, struct gfarm_file_section_copy_info *); char *gfarm_file_section_copy_info_get_all_by_file(const char *, int *, struct gfarm_file_section_copy_info **); char *gfarm_file_section_copy_info_remove_all_by_file(char *); char *gfarm_file_section_copy_info_get_all_by_section(const char *, const char *, int *, struct gfarm_file_section_copy_info **); char *gfarm_file_section_copy_info_remove_all_by_section( const char *, const char *); char *gfarm_file_section_copy_info_get_all_by_host(char *, int *, struct gfarm_file_section_copy_info **); char *gfarm_file_section_copy_info_remove_all_by_host(char *); /* convenience function */ int gfarm_file_section_copy_info_does_exist(char *, char *, char *); /* ---------------------------------------- */ /* * GFarmFile history database: * (pathname) -> (history) */ struct gfarm_file_history { char *program; /* program which created the file */ char **input_files; /* input_files passed to the program */ char *parameter; /* parameter string passed to the program */ }; void gfarm_file_history_free(struct gfarm_file_history *); char *gfarm_file_history_get(char *, struct gfarm_file_history *); char *gfarm_file_history_set(char *, struct gfarm_file_history *); void gfarm_file_history_free_allfile(int, char **); /* get GFarmFiles which were created by the program */ char *gfarm_file_history_get_allfile_by_program(char *, int *, char ***); /* get GFarmFiles which were created from the file as a input */ char *gfarm_file_history_get_allfile_by_file(char *, int *, char ***); <file_sep>/gfarm/tags/gfarm_1_0_2_rc1/gftool/gfsetdir/gfsetdir.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <sys/socket.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include <gfarm/gfs.h> char *program_name = "gfsetdir"; void usage() { fprintf(stderr, "Usage: %s [-s|-c] [directory]\n", program_name); fprintf(stderr, "\t-c\t output string for *csh\n"); fprintf(stderr, "\t-s\t otherwise\n"); exit(1); } int main(int argc, char **argv) { struct gfs_stat gstat; char *e, *nwdir, *gfarm_path; extern int optind; int ch; enum { UNDECIDED, B_SHELL_LIKE, C_SHELL_LIKE } shell_type = UNDECIDED; if (argc > 0) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((ch = getopt(argc, argv, "sc")) != -1) { switch (ch) { case 's': shell_type = B_SHELL_LIKE; break; case 'c': shell_type = C_SHELL_LIKE; break; default: usage(); } } argc -= optind; argv += optind; /* * Get absolute path from the argument directory name. * If no arugument is passed, generate gfarm:/"global username". */ nwdir = "gfarm:~"; /* home directory */ switch (argc) { case 0: break; case 1: nwdir = argv[0]; break; default: usage(); } /* check whether it is a directory or not. */ e = gfs_stat(nwdir, &gstat); if (e != NULL) { fprintf(stderr, "%s: %s\n", nwdir, e); exit(1); } if (!GFARM_S_ISDIR(gstat.st_mode)) { fprintf(stderr, "%s: not a directory\n", nwdir); gfs_stat_free(&gstat); exit(1); } gfs_stat_free(&gstat); /* expand the path name */ e = gfs_realpath(nwdir, &gfarm_path); if (e != NULL) { fprintf(stderr, "%s: %s\n", nwdir, e); exit(1); } if (shell_type == UNDECIDED) { char *shell; shell = getenv("SHELL"); if (strlen(shell) < 3 || strncmp(shell + strlen(shell) - 3, "csh", 3)) shell_type = B_SHELL_LIKE; else shell_type = C_SHELL_LIKE; } if (shell_type == B_SHELL_LIKE) printf("GFS_PWD=%s; export GFS_PWD", gfarm_path); else printf("setenv GFS_PWD %s", gfarm_path); fflush(stdout); free(gfarm_path); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc7/Makefile.in top_builddir = . top_srcdir = @top_srcdir@ srcdir = @srcdir@ include $(top_srcdir)/makes/var.mk SUBDIRS = \ doc \ man \ include/gfarm \ lib \ `[ -d $(srcdir)/ns ] && echo ns` \ server \ gftool \ gfptool \ util/gfront \ util/ptool \ bench/thput-gfpio all: include $(top_srcdir)/makes/subdir.mk post-distclean-hook: rm -f config.log config.status config.cache \ $(INC_BUILDDIR)/gfarm_config.h \ Makefile makes/config.mk \ package/solaris/gfmd package/solaris/gfsd \ package/redhat/gfmd package/redhat/gfsd \ libtool -rm -rf autom4te.cache <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_9_6/contrib/mount.gfarm2fs/mount.hpci #!/bin/sh # # mount.hpci - mount HPCI shared storage # # usage: mount.hpci [ --root | --home | --group | --user ] # # this command assumes to be executed by a normal user not root PROG=`basename $0` ABORT() { [ $# -gt 0 ] && echo >&2 $PROG: $* exit 1 } ASK() { echo >&2 $PROG: $* echo >&2 $PROG: Please ask the system administrator. exit 1 } USAGE() { echo >&2 "usage: $PROG [ --root | --home | --group | --user ]" exit 1 } create_link() { G=$1 U=$2 H=gfarm:///home/$G/$U if ! gftest -h $H/www; then gfln -s gfarm:///www/$G/$U $H/www && echo create \'www\' symlink fi if ! gftest -h $H/samba; then gfln -s gfarm:///samba/$G/$U $H/samba && echo create \'samba\' symlink fi if ! gftest -h $H/shared; then gfln -s gfarm:///home/$G/shared $H/shared && echo create \'shared\' symlink fi } # option mount_dir=--user while [ $# -gt 0 ] do case $1 in --root|--home|--group|--user) mount_dir=$1 ;; *) USAGE ;; esac shift done # check proxy cert grid-proxy-info > /dev/null || ABORT "Invalid proxy certificate" # check privilege to use FUSE [ -w /dev/fuse ] || ASK "Cannot access /dev/fuse." # display timeleft of proxy cert (grid-proxy-info || ABORT "Invalid proxy certificate") | grep timeleft GFUSER=`gfwhoami` [ X"$GFUSER" = X ] && ABORT 'Who?' : ${USER:=`whoami`} USERLIST="$GFUSER" [ X"$GFUSER" != X"$USER" ] && USERLIST="$USERLIST $USER" : ${GFARM_CONFIG_FILE:=`gfstatus 2>/dev/null | grep "user config file" | sed 's/user config file : //'`} : ${GFARM_CONFIG_FILE:="$HOME/.gfarm2rc"} groups=`gfgroup -l | grep $GFUSER | awk -F: '{print $1}'` if [ -z "$groups" ]; then ASK "The Gfarm user '$GFUSER' doesn't belong to any Gfarm resource group." fi for g in $groups do dir_not_exist=true dir_not_writable=true cannot_mount=true not_writable_dir=XXX not_mountable_dir=XXX for u in $USERLIST do if [ -d /gfarm/$g/$u ]; then dir_not_exist=false if [ ! -w /gfarm/$g/$u ]; then not_writable_dir=/gfarm/$g/$u else dir_not_writable=false case $mount_dir in --root) GFARMFS_ROOT=/ ;; --home) GFARMFS_ROOT=/home ;; --group) GFARMFS_ROOT=/home/$g ;; --user) GFARMFS_ROOT=/home/$g/$GFUSER ;; esac if env GFARMFS_ROOT=$GFARMFS_ROOT mount.gfarm2fs "$GFARM_CONFIG_FILE" /gfarm/$g/$u then cannot_mount=false # create symlinks create_link $g $GFUSER else not_mountable_dir=/gfarm/$g/$u fi fi fi done if $cannot_mount; then if $dir_not_exist; then ASK "Your mount directory is not found/accessible in '/gfarm/$g'." elif $dir_not_writable; then ASK "Your mount directory '$not_writable_dir' is not writable'." else ABORT "failed to mount on $not_mountable_dir." fi fi done <file_sep>/gfarm/tags/gfarm_1_0_beta_5/gftool/gfwhere/gfwhere.c #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfwhere"; static char * display_replica_catalog(char *gfarm_url); static char * display_replica_catalog_section(char *gfarm_url, char *section) { char *gfarm_file, *e; int j, ncopies; struct gfarm_file_section_copy_info *copies; struct gfs_stat st; if (section == NULL) return (display_replica_catalog(gfarm_url)); e = gfs_stat(gfarm_url, &st); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_url, e); return (e); } gfs_stat_free(&st); e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_url, e); return (e); } e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, section, &ncopies, &copies); if (e != NULL) { fprintf(stderr, "%s\n", e); free(gfarm_file); return (e); } j = 0; printf("%s", copies[j].hostname); for (++j; j < ncopies; ++j) printf(" %s", copies[j].hostname); printf("\n"); gfarm_file_section_copy_info_free_all(ncopies, copies); free(gfarm_file); return (NULL); } static char * display_replica_catalog(char *gfarm_url) { char *gfarm_file, *e, *e_save = NULL; int i, j, nsections; struct gfarm_file_section_info *sections; struct gfs_stat st; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_url, e); return (e); } e = gfs_stat(gfarm_url, &st); if (e != NULL) { free(gfarm_file); fprintf(stderr, "%s: %s\n", gfarm_url, e); return (e); } if (!GFARM_S_ISREG(st.st_mode)) { free(gfarm_file); gfs_stat_free(&st); fprintf(stderr, "%s: not a file\n", gfarm_url); return (e); } if ((st.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0) { /* program? */ e = gfarm_file_section_info_get_all_by_file( gfarm_file, &nsections, &sections); } else { e = gfarm_file_section_info_get_sorted_all_serial_by_file( gfarm_file, &nsections, &sections); } gfs_stat_free(&st); if (e != NULL) { free(gfarm_file); fprintf(stderr, "%s: %s\n", gfarm_url, e); return (e); } for (i = 0; i < nsections; i++) { int ncopies; struct gfarm_file_section_copy_info *copies; e = gfarm_file_section_copy_info_get_all_by_section( gfarm_file, sections[i].section, &ncopies, &copies); if (e != NULL) { fprintf(stderr, "%d: %s\n", i, e); if (e_save == NULL) e_save = e; continue; } printf("%s:", sections[i].section); for (j = 0; j < ncopies; j++) printf(" %s", copies[j].hostname); gfarm_file_section_copy_info_free_all(ncopies, copies); printf("\n"); } gfarm_file_section_info_free_all(nsections, sections); free(gfarm_file); return (e_save); } void usage(void) { fprintf(stderr, "Usage: %s [option] <gfarm_url>...\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-I <fragment>\t" "display filesystem nodes specified by <fragment>\n"); exit(1); } int main(int argc, char **argv) { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *section = NULL; int i, ch, error = 0; gfarm_stringlist paths; gfs_glob_t types; int argc_expanded; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "I:")) != -1) { switch (ch) { case 'I': section = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { usage(); } e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); argc_expanded = gfarm_stringlist_length(&paths); for (i = 0; i < argc_expanded; i++) { char *p = gfarm_stringlist_elem(&paths, i); if (argc_expanded > 1) printf("%s:\n", p); if (display_replica_catalog_section(p, section) != NULL) error = 1; if (argc_expanded > 1 && i < argc_expanded - 1) printf("\n"); } gfs_glob_free(&types); gfarm_stringlist_free_deeply(&paths); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (error); } <file_sep>/gfarm/tags/gfarm_1_1_0_rc1/lib/libgfarm/gfarm/gfs_pio.c /* * $Id$ */ #include <sys/types.h> /* mode_t */ #include <sys/stat.h> /* umask() */ #include <sys/time.h> #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "gfs_proto.h" #include "gfs_pio.h" #include "timer.h" char GFS_FILE_ERROR_EOF[] = "end of file"; char * gfs_pio_set_view_default(GFS_File gf) { char *e, *e_save = NULL; if (gf->view_context != NULL) { if ((gf->mode & GFS_FILE_MODE_WRITE) != 0) e_save = gfs_pio_flush(gf); e = (*gf->ops->view_close)(gf); if (e_save == NULL) e_save = e; } gf->ops = NULL; gf->view_context = NULL; gf->view_flags = 0; gf->error = e_save; return (e_save); } static char * gfs_pio_check_view_default(GFS_File gf) { char *e; e = gfs_pio_error(gf); if (e != NULL) return (e); if (gf->view_context == NULL) /* view isn't set yet */ return (gfs_pio_set_view_global(gf, 0)); return (NULL); } int gfs_pio_fileno(GFS_File gf) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) return (-1); return ((*gf->ops->view_fd)(gf)); } static char * gfs_file_alloc(GFS_File *gfp) { GFS_File gf = malloc(sizeof(struct gfs_file)); char *buffer = malloc(GFS_FILE_BUFSIZE); if (buffer == NULL || gf == NULL) { if (buffer != NULL) free(buffer); if (gf != NULL) free(gf); *gfp = NULL; return (GFARM_ERR_NO_MEMORY); } memset(gf, 0, sizeof(struct gfs_file)); gf->mode = 0; gf->open_flags = 0; gf->error = NULL; gf->io_offset = 0; gf->buffer = buffer; gf->p = 0; gf->length = 0; gf->offset = 0; gf->view_context = NULL; gfs_pio_set_view_default(gf); *gfp = gf; return (NULL); } static void gfs_file_free(GFS_File gf) { free(gf->buffer); /* do not touch gf->pi here */ free(gf); } /* * note that unlike access(2), gfarm_path_info_access() doesn't/can't check * access permission of ancestor directories. */ char * gfarm_path_info_access(struct gfarm_path_info *pi, int mode) { gfarm_mode_t mask = 0; if (strcmp(pi->status.st_user, gfarm_get_global_username()) == 0) { if (mode & GFS_X_OK) mask |= 0100; if (mode & GFS_W_OK) mask |= 0200; if (mode & GFS_R_OK) mask |= 0400; #if 0 /* XXX - check against st_group */ } else if (gfarm_is_group_member(pi->status.st_group)) { if (mode & GFS_X_OK) mask |= 0010; if (mode & GFS_W_OK) mask |= 0020; if (mode & GFS_R_OK) mask |= 0040; #endif } else { if (mode & GFS_X_OK) mask |= 0001; if (mode & GFS_W_OK) mask |= 0002; if (mode & GFS_R_OK) mask |= 0004; } return (((pi->status.st_mode & mask) == mask) ? NULL : GFARM_ERR_PERMISSION_DENIED); } static void gfs_pio_open_initialize_mode_flags(GFS_File gf, int flags) { /* * It may be necessary to calculate checksum of the * whole file when closing on either random access case * or even sequential access without truncation, * which requires a read mode. */ if ((flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY && (flags & (GFARM_FILE_TRUNC|GFARM_FILE_SEQUENTIAL)) != (GFARM_FILE_TRUNC|GFARM_FILE_SEQUENTIAL)) flags = (flags & ~GFARM_FILE_ACCMODE) | GFARM_FILE_RDWR; gf->open_flags = flags; if (((flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDWR) || ((flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDONLY)) gf->mode |= GFS_FILE_MODE_READ; if (((flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDWR) || ((flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY)) gf->mode |= GFS_FILE_MODE_WRITE; } static char * gfs_pio_open_check_perm(GFS_File gf) { char *e; int check= 0; if ((gf->mode & GFS_FILE_MODE_READ) != 0) check |= GFS_R_OK; if ((gf->mode & GFS_FILE_MODE_WRITE) != 0 || (gf->open_flags & GFARM_FILE_TRUNC) != 0) check |= GFS_W_OK; e = gfarm_path_info_access(&gf->pi, check); if (e != NULL) return (e); if (!GFARM_S_ISREG(gf->pi.status.st_mode)) { if (GFARM_S_ISDIR(gf->pi.status.st_mode)) return (GFARM_ERR_IS_A_DIRECTORY); else return (GFARM_ERR_OPERATION_NOT_SUPPORTED); } return (NULL); } static double gfs_pio_create_time; static double gfs_pio_open_time; static double gfs_pio_close_time; static double gfs_pio_seek_time; static double gfs_pio_truncate_time; static double gfs_pio_read_time; static double gfs_pio_write_time; static double gfs_pio_getline_time; char * gfs_pio_create(const char *url, int flags, gfarm_mode_t mode, GFS_File *gfp) { char *e, *pathname; GFS_File gf; char *user; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); user = gfarm_get_global_username(); if (user == NULL) { e = "gfs_pio_create(): programming error, " "gfarm library isn't properly initialized"; goto finish; } e = gfarm_url_make_path_for_creation(url, &pathname); if (e != NULL) goto finish; e = gfs_file_alloc(&gf); if (e != NULL) { free(pathname); goto finish; } flags |= GFARM_FILE_CREATE; gfs_pio_open_initialize_mode_flags(gf, flags); e = gfarm_path_info_get(pathname, &gf->pi); if (e != NULL && e != GFARM_ERR_NO_SUCH_OBJECT) { free(pathname); goto free_gf; } if (e == NULL) { free(pathname); if ((flags & GFARM_FILE_EXCLUSIVE) != 0) { e = GFARM_ERR_ALREADY_EXISTS; goto free_gf_pi; } e = gfs_pio_open_check_perm(gf); if (e != NULL) goto free_gf_pi; /* * XXX should check the follows: * - the mode is consistent among same job * - creator of the metainfo has same job id * - O_TRUNC / !O_TRUNC case */ if ((flags & GFARM_FILE_TRUNC) == 0) gf->mode |= GFS_FILE_MODE_NSEGMENTS_FIXED; } else { mode_t mask; struct timeval now; mask = umask(0); umask(mask); gettimeofday(&now, NULL); gf->pi.pathname = pathname; gf->pi.status.st_mode = (GFARM_S_IFREG | (mode & ~mask)); gf->pi.status.st_user = strdup(user); /* XXX NULL check */ gf->pi.status.st_group = strdup("*"); /* XXX for now */ gf->pi.status.st_atimespec.tv_sec = gf->pi.status.st_mtimespec.tv_sec = gf->pi.status.st_ctimespec.tv_sec = now.tv_sec; gf->pi.status.st_atimespec.tv_nsec = gf->pi.status.st_mtimespec.tv_nsec = gf->pi.status.st_ctimespec.tv_nsec = now.tv_usec * 1000; gf->pi.status.st_size = 0; gf->pi.status.st_nsections = 0; gf->mode |= GFS_FILE_MODE_FILE_CREATED; } *gfp = gf; e = NULL; goto finish; free_gf_pi: gfarm_path_info_free(&gf->pi); free_gf: gfs_file_free(gf); finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_create_time += gfarm_timerval_sub(&t2, &t1)); return (e); } char * gfs_pio_open(const char *url, int flags, GFS_File *gfp) { char *e, *pathname; GFS_File gf; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); if (flags & GFARM_FILE_CREATE) { e = GFARM_ERR_OPERATION_NOT_SUPPORTED; goto finish; } e = gfarm_url_make_path(url, &pathname); if (e != NULL) goto finish; e = gfs_file_alloc(&gf); if (e != NULL) { free(pathname); goto finish; } /* GFARM_FILE_EXCLUSIVE is a NOP with gfs_pio_open(). */ flags &= ~GFARM_FILE_EXCLUSIVE; gfs_pio_open_initialize_mode_flags(gf, flags); e = gfarm_path_info_get(pathname, &gf->pi); free(pathname); if (e != NULL) goto free_gf; e = gfs_pio_open_check_perm(gf); if (e != NULL) goto free_gf_pi; if ((flags & GFARM_FILE_TRUNC) == 0) gf->mode |= GFS_FILE_MODE_NSEGMENTS_FIXED; *gfp = gf; e = NULL; goto finish; free_gf_pi: gfarm_path_info_free(&gf->pi); free_gf: gfs_file_free(gf); finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_open_time += gfarm_timerval_sub(&t2, &t1)); return (e); } int gfs_pio_eof(GFS_File gf) { return (gf->error == GFS_FILE_ERROR_EOF); } #define GFS_PIO_ERROR(gf) \ ((gf)->error != GFS_FILE_ERROR_EOF ? (gf)->error : NULL) char * gfs_pio_error(GFS_File gf) { return (GFS_PIO_ERROR(gf)); } void gfs_pio_clearerr(GFS_File gf) { gf->error = NULL; } char * gfs_pio_get_nfragment(GFS_File gf, int *nfragmentsp) { if (GFS_FILE_IS_PROGRAM(gf)) return (GFARM_ERR_OPERATION_NOT_PERMITTED); if ((gf->mode & GFS_FILE_MODE_NSEGMENTS_FIXED) == 0) return (GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE); *nfragmentsp = gf->pi.status.st_nsections; return (NULL); } /* XXX this must be done only if the file was really read or written */ static char * gfs_pio_update_times(GFS_File gf) { struct timeval now; gettimeofday(&now, NULL); if (gf->mode & GFS_FILE_MODE_WRITE) { gf->pi.status.st_mtimespec.tv_sec = now.tv_sec; gf->pi.status.st_mtimespec.tv_nsec = now.tv_usec * 1000; } if (gf->mode & GFS_FILE_MODE_READ) { gf->pi.status.st_atimespec.tv_sec = now.tv_sec; gf->pi.status.st_atimespec.tv_nsec = now.tv_usec * 1000; } return (gfarm_path_info_replace(gf->pi.pathname, &gf->pi)); } char * gfs_pio_close(GFS_File gf) { char *e, *e_save; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e_save = gfs_pio_check_view_default(gf); if (e_save == NULL) { if ((gf->mode & GFS_FILE_MODE_WRITE) != 0) e_save = gfs_pio_flush(gf); e = (*gf->ops->view_close)(gf); if (e_save == NULL) e_save = e; } /* * When there is inconsistency, do not update/overwrite the * metadata. This inconsistency may come from the update by * other process or oneself such as 'nvi'. */ if (e_save == NULL) e = gfs_pio_update_times(gf); if (e_save == NULL) e_save = e; gfarm_path_info_free(&gf->pi); gfs_file_free(gf); gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_close_time += gfarm_timerval_sub(&t2, &t1)); return (e_save); } static char * gfs_pio_purge(GFS_File gf) { gf->p = gf->length = 0; return (NULL); } #define CHECK_WRITABLE(gf) { \ if (((gf)->mode & GFS_FILE_MODE_WRITE) == 0) \ return (gfarm_errno_to_error(EBADF)); \ } /* * we check this against gf->open_flags rather than gf->mode, * because we may set GFARM_FILE_MODE_READ even if write-only case. */ #define CHECK_READABLE(gf) { \ if (((gf)->open_flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY) \ return (gfarm_errno_to_error(EBADF)); \ } #define CHECK_READABLE_EOF(gf) { \ if (((gf)->open_flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY) \ return (EOF); \ } static char * gfs_pio_fillbuf(GFS_File gf) { char *e; size_t len; CHECK_READABLE(gf); if (gf->error != NULL) return (GFS_PIO_ERROR(gf)); if (gf->p < gf->length) return (NULL); if ((gf->mode & GFS_FILE_MODE_BUFFER_DIRTY) != 0) { e = gfs_pio_flush(gf); if (e != NULL) return (e); } else { gf->offset += gf->p; gf->p = gf->length = 0; } assert(gf->io_offset == gf->offset); e = (*gf->ops->view_read)(gf, gf->buffer, GFS_FILE_BUFSIZE, &len); if (e != NULL) { gf->error = e; return (e); } gf->length = len; gf->io_offset += len; if (len == 0) gf->error = GFS_FILE_ERROR_EOF; return (NULL); } /* unlike other functions, this returns `*writtenp' even if an error happens */ static char * do_write(GFS_File gf, const char *buffer, size_t length, size_t *writtenp) { char *e = NULL; size_t written, len; if (length == 0) { *writtenp = 0; return (NULL); } if (gf->io_offset != gf->offset) { /* this happens when switching from reading to writing */ gf->mode &= ~GFS_FILE_MODE_CALC_DIGEST; e = (*gf->ops->view_seek)(gf, gf->offset, SEEK_SET, NULL); if (e != NULL) { gf->error = e; *writtenp = 0; return (e); } gf->io_offset = gf->offset; } for (written = 0; written < length; written += len) { e = (*gf->ops->view_write)( gf, buffer + written, length - written, &len); if (e != NULL) { gf->error = e; break; } } gf->io_offset += written; *writtenp = written; return (e); } char * gfs_pio_flush(GFS_File gf) { char *e = gfs_pio_check_view_default(gf); size_t written; if (e != NULL) return (e); CHECK_WRITABLE(gf); if ((gf->mode & GFS_FILE_MODE_BUFFER_DIRTY) != 0) { e = do_write(gf, gf->buffer, gf->length, &written); if (e != NULL) return (e); gf->mode &= ~GFS_FILE_MODE_BUFFER_DIRTY; } if (gf->p >= gf->length) { gf->offset += gf->p; gf->p = gf->length = 0; } return (NULL); } char * gfs_pio_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { char *e; file_offset_t where; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); if (whence == SEEK_SET || whence == SEEK_CUR) { file_offset_t tmp_offset = offset; /* * This is the case that the file offset will be * repositioned within the current io buffer. */ if (whence == SEEK_CUR) tmp_offset += gf->offset + gf->p; if (gf->offset <= tmp_offset && tmp_offset <= gf->offset + gf->length){ /* * We don't have to clear * GFS_FILE_MODE_CALC_DIGEST bit here, because * this is no problem to calculate checksum * for write-only or read-only case. * This is also ok on switching from writing * to reading. * This is not ok on switching from reading to * writing, but gfs_pio_flush() clears the bit * at that case. */ gf->p = tmp_offset - gf->offset; if (resultp != NULL) *resultp = tmp_offset; e = NULL; goto finish; } } else if (whence != SEEK_END) { e = gf->error = GFARM_ERR_INVALID_ARGUMENT; goto finish; } gf->mode &= ~GFS_FILE_MODE_CALC_DIGEST; if (gf->mode & GFS_FILE_MODE_BUFFER_DIRTY) { e = gfs_pio_flush(gf); if (e != NULL) { gf->error = e; goto finish; } } if (whence == SEEK_CUR) /* modify offset based on io_offset */ offset += gf->offset + gf->p - gf->io_offset; gf->error = NULL; /* purge EOF/error state */ gfs_pio_purge(gf); e = (*gf->ops->view_seek)(gf, offset, whence, &where); if (e != NULL) { gf->error = e; goto finish; } gf->offset = gf->io_offset = where; if (resultp != NULL) *resultp = where; e = NULL; finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_seek_time += gfarm_timerval_sub(&t2, &t1)); return (e); } char * gfs_pio_truncate(GFS_File gf, file_offset_t length) { char *e; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfs_pio_check_view_default(gf); if (e != NULL) goto finish; CHECK_WRITABLE(gf); gf->mode &= ~GFS_FILE_MODE_CALC_DIGEST; if (gf->mode & GFS_FILE_MODE_BUFFER_DIRTY) { e = gfs_pio_flush(gf); if (e != NULL) goto finish; } gf->error = NULL; /* purge EOF/error state */ gfs_pio_purge(gf); e = (*gf->ops->view_ftruncate)(gf, length); if (e != NULL) gf->error = e; finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_truncate_time += gfarm_timerval_sub(&t2, &t1)); return (e); } char * gfs_pio_read(GFS_File gf, void *buffer, int size, int *np) { char *e; char *p = buffer; int n = 0; int length; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); CHECK_READABLE(gf); while (size > 0) { if ((e = gfs_pio_fillbuf(gf)) != NULL) break; if (gf->error != NULL) /* EOF or error */ break; length = gf->length - gf->p; if (length > size) length = size; memcpy(p, gf->buffer + gf->p, length); p += length; n += length; size -= length; gf->p += length; } if (e != NULL && n == 0) goto finish; *np = n; e = NULL; finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_read_time += gfarm_timerval_sub(&t2, &t1)); return (e); } char * gfs_pio_write(GFS_File gf, const void *buffer, int size, int *np) { char *e; size_t written; gfarm_timerval_t t1, t2; gfs_profile(gfarm_gettimerval(&t1)); e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); CHECK_WRITABLE(gf); if (size + gf->p > GFS_FILE_BUFSIZE) { /* * gf->buffer[gf->p .. GFS_FILE_BUFSIZE-1] will be overridden * by buffer. */ gf->length = gf->p; e = gfs_pio_flush(gf); if (e != NULL) goto finish; } if (size >= GFS_FILE_BUFSIZE) { /* shortcut to avoid unnecessary memory copy */ assert(gf->p == 0); /* gfs_pio_flush() was called above */ gf->length = 0; gf->mode &= ~GFS_FILE_MODE_BUFFER_DIRTY; e = do_write(gf, buffer, size, &written); if (e != NULL && written == 0) goto finish; gf->offset += written; *np = written; /* XXX - size_t vs int */ e = NULL; goto finish; } gf->mode |= GFS_FILE_MODE_BUFFER_DIRTY; memcpy(gf->buffer + gf->p, buffer, size); gf->p += size; if (gf->p > gf->length) gf->length = gf->p; *np = size; e = NULL; if (gf->open_flags & GFARM_FILE_UNBUFFERED || gf->p >= GFS_FILE_BUFSIZE) e = gfs_pio_flush(gf); finish: gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_write_time += gfarm_timerval_sub(&t2, &t1)); return (e); } int gfs_pio_getc(GFS_File gf) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) { gf->error = e; return (EOF); } CHECK_READABLE_EOF(gf); if (gf->p >= gf->length) { if (gfs_pio_fillbuf(gf) != NULL) return (EOF); /* can get reason via gfs_pio_error() */ if (gf->error != NULL) return (EOF); } return (((unsigned char *)gf->buffer)[gf->p++]); } int gfs_pio_ungetc(GFS_File gf, int c) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) { gf->error = e; return (EOF); } CHECK_READABLE_EOF(gf); if (c != EOF) { if (gf->p == 0) { /* cannot unget - XXX should permit this? */ gf->error = GFARM_ERR_NO_SPACE; return (EOF); } /* We do not mark this buffer dirty here. */ gf->buffer[--gf->p] = c; } return (c); } char * gfs_pio_putc(GFS_File gf, int c) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); CHECK_WRITABLE(gf); if (gf->p >= GFS_FILE_BUFSIZE) { char *e = gfs_pio_flush(gf); if (e != NULL) return (e); } gf->mode |= GFS_FILE_MODE_BUFFER_DIRTY; gf->buffer[gf->p++] = c; if (gf->p > gf->length) gf->length = gf->p; if (gf->p >= GFS_FILE_BUFSIZE) return (gfs_pio_flush(gf)); return (NULL); } /* mostly compatible with fgets(3) */ char * gfs_pio_puts(GFS_File gf, const char *s) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); CHECK_WRITABLE(gf); while (*s != '\0') { char *e = gfs_pio_putc(gf, *(unsigned char *)s); if (e != NULL) return (e); s++; } return (NULL); } /* mostly compatible with fgets(3), but EOF check is done by *s == '\0' */ char * gfs_pio_gets(GFS_File gf, char *s, size_t size) { char *e = gfs_pio_check_view_default(gf); char *p = s; int c; gfarm_timerval_t t1, t2; if (e != NULL) return (e); gfs_profile(gfarm_gettimerval(&t1)); #ifdef __GNUC__ /* workaround gcc warning: unused variable */ c = EOF; #endif CHECK_READABLE(gf); if (size <= 1) { gf->error = GFARM_ERR_INVALID_ARGUMENT; return (gf->error); } --size; /* for '\0' */ for (; size > 0 && (c = gfs_pio_getc(gf)) != EOF; --size) { *p++ = c; if (c == '\n') break; } *p++ = '\0'; gfs_profile(gfarm_gettimerval(&t2)); /* XXX should introduce gfs_pio_gets_time??? */ gfs_profile(gfs_pio_getline_time += gfarm_timerval_sub(&t2, &t1)); return (NULL); } char * gfs_pio_getline(GFS_File gf, char *s, size_t size, int *eofp) { char *e = gfs_pio_check_view_default(gf); char *p = s; int c; gfarm_timerval_t t1, t2; if (e != NULL) return (e); gfs_profile(gfarm_gettimerval(&t1)); #ifdef __GNUC__ /* workaround gcc warning: unused variable */ c = EOF; #endif CHECK_READABLE(gf); if (size <= 1) { gf->error = GFARM_ERR_INVALID_ARGUMENT; return (gf->error); } --size; /* for '\0' */ for (; size > 0 && (c = gfs_pio_getc(gf)) != EOF; --size) { if (c == '\n') break; *p++ = c; } *p++ = '\0'; if (p == s + 1 && c == EOF) { *eofp = 1; return (GFS_PIO_ERROR(gf)); } *eofp = 0; gfs_profile(gfarm_gettimerval(&t2)); gfs_profile(gfs_pio_getline_time += gfarm_timerval_sub(&t2, &t1)); return (NULL); } char * gfs_pio_putline(GFS_File gf, const char *s) { char *e = gfs_pio_check_view_default(gf); if (e != NULL) return (e); CHECK_WRITABLE(gf); e = gfs_pio_puts(gf, s); if (e != NULL) return (e); return (gfs_pio_putc(gf, '\n')); } #define ALLOC_SIZE_INIT 220 /* * mostly compatible with getline(3) in glibc, * but there are the following differences: * 1. on EOF, *lenp == 0 * 2. on error, *lenp isn't touched. */ char * gfs_pio_readline(GFS_File gf, char **bufp, size_t *sizep, size_t *lenp) { char *e = gfs_pio_check_view_default(gf); char *buf = *bufp, *p; size_t size = *sizep, len = 0; int c; gfarm_timerval_t t1, t2; if (e != NULL) return (e); gfs_profile(gfarm_gettimerval(&t1)); #ifdef __GNUC__ /* workaround gcc warning: unused variable */ c = EOF; #endif CHECK_READABLE(gf); if (buf == NULL || size <= 1) { if (size <= 1) size = ALLOC_SIZE_INIT; buf = realloc(buf, size); if (buf == NULL) return (GFARM_ERR_NO_MEMORY); } for (;;) { c = gfs_pio_getc(gf); if (c == EOF) break; if (size <= len) { p = realloc(buf, size + size); if (p == NULL) { *bufp = buf; *sizep = size; return (GFARM_ERR_NO_MEMORY); } buf = p; size += size; } buf[len++] = c; if (c == '\n') break; } if (size <= len) { p = realloc(buf, size + size); if (p == NULL) { *bufp = buf; *sizep = size; return (GFARM_ERR_NO_MEMORY); } buf = p; size += size; } buf[len] = '\0'; gfs_profile(gfarm_gettimerval(&t2)); /* XXX should introduce gfs_pio_readline_time??? */ gfs_profile(gfs_pio_getline_time += gfarm_timerval_sub(&t2, &t1)); *bufp = buf; *sizep = size; *lenp = len; return (NULL); } /* * mostly compatible with getdelim(3) in glibc, * but there are the following differences: * 1. on EOF, *lenp == 0 * 2. on error, *lenp isn't touched. */ char * gfs_pio_readdelim(GFS_File gf, char **bufp, size_t *sizep, size_t *lenp, const char *delim, size_t delimlen) { char *e = gfs_pio_check_view_default(gf); char *buf = *bufp, *p; size_t size = *sizep, len = 0; int c, delimtail; static const char empty_line[] = "\n\n"; gfarm_timerval_t t1, t2; if (e != NULL) return (e); gfs_profile(gfarm_gettimerval(&t1)); #ifdef __GNUC__ /* workaround gcc warning: unused variable */ c = EOF; #endif CHECK_READABLE(gf); if (delim == NULL) { /* special case 1 */ delimtail = 0; /* workaround gcc warning */ } else { if (delimlen == 0) { /* special case 2 */ delim = empty_line; delimlen = 2; } delimtail = delim[delimlen - 1]; } if (buf == NULL || size <= 1) { if (size <= 1) size = ALLOC_SIZE_INIT; buf = realloc(buf, size); if (buf == NULL) return (GFARM_ERR_NO_MEMORY); } for (;;) { c = gfs_pio_getc(gf); if (c == EOF) break; if (size <= len) { p = realloc(buf, size + size); if (p == NULL) { *bufp = buf; *sizep = size; return (GFARM_ERR_NO_MEMORY); } buf = p; size += size; } buf[len++] = c; if (delim == NULL) /* special case 1: no delimiter */ continue; if (len >= delimlen && c == delimtail && memcmp(&buf[len - delimlen], delim, delimlen) == 0) { if (delim == empty_line) { /* special case 2 */ for (;;) { c = gfs_pio_getc(gf); if (c == EOF) break; if (c != '\n') { gfs_pio_ungetc(gf, c); break; } if (size <= len) { p = realloc(buf, size + size); if (p == NULL) { *bufp = buf; *sizep = size; return ( GFARM_ERR_NO_MEMORY); } buf = p; size += size; } buf[len++] = c; } } break; } } if (size <= len) { p = realloc(buf, size + size); if (p == NULL) { *bufp = buf; *sizep = size; return (GFARM_ERR_NO_MEMORY); } buf = p; size += size; } buf[len] = '\0'; gfs_profile(gfarm_gettimerval(&t2)); /* XXX should introduce gfs_pio_readdelim_time??? */ gfs_profile(gfs_pio_getline_time += gfarm_timerval_sub(&t2, &t1)); *bufp = buf; *sizep = size; *lenp = len; return (NULL); } void gfs_display_timers() { fprintf(stderr, "gfs_pio_create : %g sec\n", gfs_pio_create_time); fprintf(stderr, "gfs_pio_open : %g sec\n", gfs_pio_open_time); fprintf(stderr, "gfs_pio_close : %g sec\n", gfs_pio_close_time); fprintf(stderr, "gfs_pio_seek : %g sec\n", gfs_pio_seek_time); fprintf(stderr, "gfs_pio_truncate : %g sec\n", gfs_pio_truncate_time); fprintf(stderr, "gfs_pio_read : %g sec\n", gfs_pio_read_time); fprintf(stderr, "gfs_pio_write : %g sec\n", gfs_pio_write_time); fprintf(stderr, "gfs_pio_getline : %g sec\n", gfs_pio_getline_time); fprintf(stderr, "gfs_pio_set_view_section : %g sec\n", gfs_pio_set_view_section_time); fprintf(stderr, "gfs_stat : %g sec\n", gfs_stat_time); fprintf(stderr, "gfs_unlink : %g sec\n", gfs_unlink_time); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/gfs_hook/hooks_fstat.c /* * fstat * * $Id$ */ extern int gfarm_node; #ifndef _STAT_VER int FUNC___FSTAT(int filedes, STRUCT_STAT *buf) { GFS_File gf; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___FSTAT) "(%d)\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_FSTAT(filedes, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___FSTAT) "(%d)\n", filedes)); if (gfs_hook_gfs_file_type(filedes) == GFS_DT_REG) { char *e; struct gfs_stat status; e = gfs_fstat(gf, &status); if (e != NULL) return (-1); buf->st_dev = GFS_DEV; buf->st_ino = status.st_ino; buf->st_mode = status.st_mode; buf->st_nlink = 1; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = status.st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = status.st_atimespec.tv_sec; buf->st_mtime = status.st_mtimespec.tv_sec; buf->st_ctime = status.st_ctimespec.tv_sec; gfs_stat_free(&status); } else { struct gfs_stat *gsp; _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___FSTAT) "(%d)\n", filedes)); gsp = gfs_hook_get_gfs_stat(filedes); buf->st_dev = GFS_DEV; buf->st_ino = gsp->st_ino; buf->st_mode = gsp->st_mode; buf->st_nlink = 2; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = gsp->st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = gsp->st_atimespec.tv_sec; buf->st_mtime = gsp->st_mtimespec.tv_sec; buf->st_ctime = gsp->st_ctimespec.tv_sec; } return (0); } int FUNC__FSTAT(int filedes, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC__FSTAT) ": %d\n", filedes)); return (FUNC___FSTAT(filedes, buf)); } int FUNC_FSTAT(int filedes, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_FSTAT) ": %d\n", filedes)); return (FUNC___FSTAT(filedes, buf)); } #else /* defined(_STAT_VER) -- SVR4 or Linux */ /* * SVR4 and Linux do inline stat() and call _xstat/__xstat() with * an additional version argument. */ #ifdef __linux__ /* * unlike SVR4, stat() on linux seems to be compatible with xstat(STAT_VER,...) */ int FUNC___FSTAT(int filedes, STRUCT_STAT *buf) { _gfs_hook_debug_v( fprintf(stderr, "Hooking " S(FUNC___FSTAT) ": %d\n", filedes)); return (FUNC___FXSTAT(_STAT_VER, filedes, buf)); } int FUNC_FSTAT(int filedes, STRUCT_STAT *buf) { _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC_FSTAT) ": %d\n", filedes)); return (FUNC___FXSTAT(_STAT_VER, filedes, buf)); } #else /* * we don't provide stat(), because it is only used for SVR3 compat code. */ #endif int FUNC___FXSTAT(int ver, int filedes, STRUCT_STAT *buf) { GFS_File gf; _gfs_hook_debug_v(fprintf(stderr, "Hooking " S(FUNC___FXSTAT) "(%d)\n", filedes)); if ((gf = gfs_hook_is_open(filedes)) == NULL) return (SYSCALL_FXSTAT(ver, filedes, buf)); _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___FXSTAT) "(%d)\n", filedes)); if (gfs_hook_gfs_file_type(filedes) == GFS_DT_REG) { char *e; struct gfs_stat status; e = gfs_fstat(gf, &status); if (e != NULL) return (-1); buf->st_dev = GFS_DEV; buf->st_ino = status.st_ino; buf->st_mode = status.st_mode; buf->st_nlink = 1; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = status.st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = status.st_atimespec.tv_sec; buf->st_mtime = status.st_mtimespec.tv_sec; buf->st_ctime = status.st_ctimespec.tv_sec; gfs_stat_free(&status); } else { struct gfs_stat *gsp; _gfs_hook_debug(fprintf(stderr, "GFS: Hooking " S(FUNC___FXSTAT) "(%d)\n", filedes)); gsp = gfs_hook_get_gfs_stat(filedes); buf->st_dev = GFS_DEV; buf->st_ino = gsp->st_ino; buf->st_mode = gsp->st_mode; buf->st_nlink = 2; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = gsp->st_size; buf->st_blksize = GFS_BLKSIZE; buf->st_atime = gsp->st_atimespec.tv_sec; buf->st_mtime = gsp->st_mtimespec.tv_sec; buf->st_ctime = gsp->st_ctimespec.tv_sec; } return (0); } int FUNC__FXSTAT(int ver, int filedes, STRUCT_STAT *buf) { _gfs_hook_debug_v( fprintf(stderr, "Hooking " S(FUNC__FXSTAT) ": %d\n", filedes)); return (FUNC___FXSTAT(ver, filedes, buf)); } #endif /* SVR4 or Linux */ <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT1-2-2-5_gfmd_warning_and_error #! /bin/sh ###################################################################### TESTID="FT1-2-2-5" CATEGORY="accident causes no failover" SECTION="mds accident" TITLE="gfmd warning and error" ###################################################################### . ./FT-common ft_setup() { return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ADDITIONAL_TIME=600 FT_MAIL_TIMEOUT=`expr $FT_MAIL_TIMEOUT + $ADDITIONAL_TIME` ssh $gfmd1 logger -p local0.err -t "gfmd[9999]" " unknown error" &&\ ssh $gfmd1 logger -p local0.warning -t "gfmd[9999]" " unknown warning" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "logging error on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd error message in /var/log/messages on $gfmd1" &&\ ft_check_mail "gfmd warning message in /var/log/messages on $gfmd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_checkpoint 3 "sleep $ADDITIONAL_TIME sec." $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd error message in /var/log/messages on $gfmd1" &&\ ft_check_mail "Re: gfmd warning message in /var/log/messages on $gfmd1" ||\ RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive mails" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_1/doc/html/ja/ref/man1/Makefile # $Id$ top_objdir = ../../../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk htmldir=$(default_htmldir)/ja/ref/man1 DOCBOOK_DIR=$(top_srcdir)/doc/docbook/ja/ref/man1 include $(DOCBOOK_DIR)/Makefile.inc HTMLSRC=$(DOCBOOK) include $(top_srcdir)/makes/html.mk <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT2-1-1-2_master_MDS_down #! /bin/sh ###################################################################### TESTID="FT2-1-1-2" CATEGORY="1 point accident" SECTION="mds accident" TITLE="master MDS down" ###################################################################### . ./FT-common ft_setup() { ssh $client1 mkdir -p mnt $gfservice unmount client1 mnt $gfservice mount client1 mnt -o nonempty ssh $client1 rm -f mnt/a.txt mnt/b.txt return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 sh -c 'echo aaa > mnt/a.txt' \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "create a text file on Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfarm gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfarm on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3.1 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox ft_wait_failover $gfmd1 || RESULT=$FT_RESULT_FAIL ft_checkpoint 3.2 "gfmd failed over" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT # Immediately after MDS failover, # it's unable to read/write files on gfarm2fs. SLEEP_PERIOD=$FT_SLEEP_PERIOD_AFTER_FAILOVER RESULT=$FT_RESULT_PASS sleep $SLEEP_PERIOD \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4.1 "sleep $SLEEP_PERIOD sec." $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 cat mnt/a.txt > /dev/null \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4.2 "read data from Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 sh -c 'echo bbb > mnt/b.txt' \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4.3 "write data on Gfarm2 filesytem" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "Re: gfmd does not listen on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_truncate_mbox return $RESULT } ft_teardown() { $gfservice umount client1 mnt ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/gfs_client.c /* * $Id$ */ #include <assert.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <ctype.h> #include <stdio.h> /* sprintf() */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <openssl/evp.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "iobuffer.h" #include "xxx_proto.h" #include "io_fd.h" #include "hash.h" #include "host.h" #include "param.h" #include "sockopt.h" #include "auth.h" #include "gfs_proto.h" #include "gfs_client.h" #define XAUTH_NEXTRACT_MAXLEN 512 static char GFARM_ERR_GFSD_ABORTED[] = "gfsd aborted"; struct gfs_connection { struct xxx_connection *conn; void *context; /* work area for RPC (esp. GFS_PROTO_COMMAND) */ }; #define SERVER_HASHTAB_SIZE 3079 /* prime number */ static struct gfarm_hash_table *gfs_server_hashtab = NULL; int gfs_client_connection_fd(struct gfs_connection *gfs_server) { return (xxx_connection_fd(gfs_server->conn)); } static char * gfs_client_connection0(const char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection *gfs_server) { char *e, *host_fqdn; int sock; sock = socket(PF_INET, SOCK_STREAM, 0); if (sock == -1) return (gfarm_errno_to_error(errno)); /* XXX - how to report setsockopt(2) failure ? */ gfarm_sockopt_apply_by_name_addr(sock, canonical_hostname, peer_addr); if (connect(sock, peer_addr, sizeof(*peer_addr)) < 0) { close(sock); return (gfarm_errno_to_error(errno)); } e = xxx_fd_connection_new(sock, &gfs_server->conn); if (e != NULL) { close(sock); return (e); } gfs_server->context = NULL; /* * the reason why we call strdup() is because * gfarm_auth_request() may break static work area of `*hp'. * XXX - now it's not hp->h_name, but canonical_hostname. */ host_fqdn = strdup(canonical_hostname); if (host_fqdn == NULL) { xxx_connection_free(gfs_server->conn); return (GFARM_ERR_NO_MEMORY); } e = gfarm_auth_request(gfs_server->conn, host_fqdn, peer_addr); free(host_fqdn); if (e != NULL) { xxx_connection_free(gfs_server->conn); return (e); } return (NULL); } /* * `hostname' to `addr' conversion really should be done in this function, * rather than a caller of this function. * but currently gfsd cannot access gfmd, and we need to access gfmd to * resolve hostname. (to check host_alias for "address_use" directive.) */ char * gfs_client_connection(const char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection **gfs_serverp) { char *e; struct gfarm_hash_entry *entry; struct gfs_connection *gfs_server; int created; if (gfs_server_hashtab == NULL) { gfs_server_hashtab = gfarm_hash_table_alloc(SERVER_HASHTAB_SIZE, gfarm_hash_casefold, gfarm_hash_key_equal_casefold); if (gfs_server_hashtab == NULL) return (GFARM_ERR_NO_MEMORY); } entry = gfarm_hash_enter(gfs_server_hashtab, canonical_hostname, strlen(canonical_hostname) + 1, sizeof(struct gfs_connection), &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); gfs_server = gfarm_hash_entry_data(entry); if (created) { e = gfs_client_connection0(canonical_hostname, peer_addr, gfs_server); if (e != NULL) { gfarm_hash_purge(gfs_server_hashtab, canonical_hostname, strlen(canonical_hostname)+1); return (e); } } *gfs_serverp = gfs_server; return (NULL); } /* * `hostname' to `addr' conversion really should be done in this function, * rather than a caller of this function. * but currently gfsd cannot access gfmd, and we need to access gfmd to * resolve hostname. (to check host_alias for "address_use" directive.) */ char * gfs_client_connect(char *canonical_hostname, struct sockaddr *peer_addr, struct gfs_connection **gfs_serverp) { struct gfs_connection *gfs_server = malloc(sizeof(struct gfs_connection)); char *e; if (gfs_server == NULL) return (GFARM_ERR_NO_MEMORY); e = gfs_client_connection0(canonical_hostname, peer_addr, gfs_server); if (e != NULL) { free(gfs_server); return (e); } *gfs_serverp = gfs_server; return (NULL); } /* * Should be used for the gfs_connection created by gfs_client_connect(). * Shouldn't be used for the gfs_connection created by gfs_client_connection(). */ char * gfs_client_disconnect(struct gfs_connection *gfs_server) { char *e = xxx_connection_free(gfs_server->conn); /* XXX - gfs_server->context should be NULL here */ free(gfs_server); return (e); } char * gfs_client_rpc_request(struct gfs_connection *gfs_server, int command, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_vrpc_request(gfs_server->conn, command, &format, &ap); va_end(ap); return (e); } char * gfs_client_rpc_result(struct gfs_connection *gfs_server, int just, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc_result(gfs_server->conn, just, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfs_proto_error_string(error)); return (NULL); } char * gfs_client_rpc(struct gfs_connection *gfs_server, int just, int command, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc(gfs_server->conn, just, command, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfs_proto_error_string(error)); return (NULL); } char * gfs_client_open(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t flag, gfarm_int32_t mode, gfarm_int32_t *fdp) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_OPEN, "sii/i", gfarm_file, flag, mode, fdp)); } char * gfs_client_close(struct gfs_connection *gfs_server, gfarm_int32_t fd) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CLOSE, "i/", fd)); } char * gfs_client_seek(struct gfs_connection *gfs_server, gfarm_int32_t fd, file_offset_t offset, gfarm_int32_t whence, file_offset_t *resultp) { file_offset_t dummy; if (resultp == NULL) resultp = &dummy; return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_SEEK, "ioi/o", fd, offset, whence, resultp)); } char * gfs_client_read(struct gfs_connection *gfs_server, gfarm_int32_t fd, void *buffer, size_t size, size_t *np) { char *e; e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_READ, "ii/b", fd, (int)size, size, np, buffer); if (e != NULL) return (e); if (*np > size) return ("gfs_pio_read: protocol error"); return (NULL); } char * gfs_client_write(struct gfs_connection *gfs_server, gfarm_int32_t fd, const void *buffer, size_t size, size_t *np) { char *e; gfarm_int32_t n; /* size_t may be 64bit */ e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_WRITE, "ib/i", fd, size, buffer, &n); if (e != NULL) return (e); *np = n; if (n > size) return ("gfs_pio_write: protocol error"); return (NULL); } char * gfs_client_unlink(struct gfs_connection *gfs_server, char *path) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_UNLINK, "s/", path)); } char * gfs_client_chdir(struct gfs_connection *gfs_server, char *dir) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHDIR, "s/", dir)); } char * gfs_client_mkdir(struct gfs_connection *gfs_server, char *dir, gfarm_int32_t mode) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_MKDIR, "si/", dir, mode)); } char * gfs_client_rmdir(struct gfs_connection *gfs_server, char *dir) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_RMDIR, "s/", dir)); } char * gfs_client_chmod(struct gfs_connection *gfs_server, char *path, gfarm_int32_t mode) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHMOD, "si/", path, mode)); } char * gfs_client_chgrp(struct gfs_connection *gfs_server, char *path, char *group) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_CHGRP, "ss/", path, group)); } char * gfs_client_digest(struct gfs_connection *gfs_server, int fd, char *digest_type, size_t digest_size, size_t *digest_length, unsigned char *digest, file_offset_t *filesize) { return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_DIGEST, "is/bo", fd, digest_type, digest_size, digest_length, digest, filesize)); } char * gfs_client_get_spool_root(struct gfs_connection *gfs_server, char **spool_rootp) { char *e = gfs_client_rpc(gfs_server, 0, GFS_PROTO_GET_SPOOL_ROOT, "/s", spool_rootp); if (e != NULL) return (e); return (*spool_rootp == NULL ? GFARM_ERR_NO_MEMORY : NULL); } char * gfs_client_copyin(struct gfs_connection *gfs_server, int src_fd, int fd) { int i, rv, eof; char *e; char buffer[GFS_PROTO_MAX_IOSIZE]; #ifdef XXX_MEASURE_CKSUM_COST /* XXX: should be passed from caller */ EVP_MD_CTX md_ctx; unsigned int md_len; unsigned char md_value[EVP_MAX_MD_SIZE]; const EVP_MD *md_type = EVP_md5(); /* XXX GFS_DEFAULT_DIGEST_MODE; */ EVP_DigestInit(&md_ctx, md_type); #endif e = xxx_proto_send(gfs_server->conn, "ii", GFS_PROTO_BULKREAD, src_fd); if (e != NULL) return (e); for (;;) { #ifdef XXX_SLOW size_t size; e = xxx_proto_recv(gfs_server->conn, 0, &eof, "b", sizeof(buffer), &size, buffer); if (e != NULL) break; if (eof) { e = GFARM_ERR_PROTOCOL; break; } if (size <= 0) break; #ifdef XXX_MEASURE_CKSUM_COST EVP_DigestUpdate(&md_ctx, buffer, size); #endif for (i = 0; i < size; i += rv) { rv = write(fd, buffer + i, size - i); if (rv <= 0) break; } if (i < size) { /* * write(2) never returns 0, * so the following rv == 0 case is just warm fuzzy. */ e = gfarm_errno_to_error(rv == 0 ? ENOSPC : errno); break; /* * XXX - we should return rest of data, * even if write(2) fails. */ } #else gfarm_int32_t size; /* XXX - FIXME layering violation */ e = xxx_proto_recv(gfs_server->conn, 0, &eof, "i", &size); if (e != NULL) break; if (eof) { e = GFARM_ERR_PROTOCOL; break; } if (size <= 0) break; do { /* XXX - FIXME layering violation */ int partial = xxx_recv_partial(gfs_server->conn, 0, buffer, size); if (partial <= 0) return (GFARM_ERR_PROTOCOL); #ifdef XXX_MEASURE_CKSUM_COST EVP_DigestUpdate(&md_ctx, buffer, partial); #endif size -= partial; #ifdef __GNUC__ /* shut up stupid warning by gcc */ rv = 0; #endif for (i = 0; i < partial; i += rv) { rv = write(fd, buffer + i, partial - i); if (rv <= 0) break; } if (i < partial) { /* * write(2) never returns 0, * so the following rv == 0 case is * just warm fuzzy. */ return (gfarm_errno_to_error( rv == 0 ? ENOSPC : errno)); /* * XXX - we should return rest of data, * even if write(2) fails. */ } } while (size > 0); #endif } #ifdef XXX_MEASURE_CKSUM_COST /* should be returned to caller */ EVP_DigestFinal(&md_ctx, md_value, &md_len); #endif return (e); } struct gfs_client_striping_copyin_context { int ofd; file_offset_t offset; file_offset_t size; int interleave_factor; file_offset_t full_stripe_size; file_offset_t chunk_residual; int io_residual; int flags; #define GCSCC_FINISHED 1 }; /* XXX CKSUM */ char * gfs_client_striping_copyin_request(struct gfs_connection *gfs_server, int src_fd, int ofd, file_offset_t offset, file_offset_t size, int interleave_factor, file_offset_t full_stripe_size) { char *e = gfs_client_rpc_request(gfs_server, GFS_PROTO_STRIPING_READ, "iooio", src_fd, offset, size, interleave_factor, full_stripe_size); struct gfs_client_striping_copyin_context *cc; if (e != NULL) return (e); e = xxx_proto_flush(gfs_server->conn); if (e != NULL) return (e); cc = malloc(sizeof(struct gfs_client_striping_copyin_context)); gfs_server->context = cc; assert(cc != NULL); cc->ofd = ofd; cc->offset = offset; cc->size = size; cc->interleave_factor = interleave_factor; cc->full_stripe_size = full_stripe_size; cc->chunk_residual = cc->interleave_factor == 0 ? cc->size : cc->interleave_factor; cc->io_residual = 0; cc->flags = 0; return (NULL); } char * gfs_client_striping_copyin_partial(struct gfs_connection *gfs_server, int *rvp) { struct gfs_client_striping_copyin_context *cc = gfs_server->context; char *e; int eof, partial, i, rv; gfarm_int32_t size; char buffer[GFS_PROTO_MAX_IOSIZE]; if (cc->flags & GCSCC_FINISHED) { *rvp = 0; return (NULL); } if (cc->chunk_residual == 0) { /* assert(cc->interleave_factor != 0); */ cc->chunk_residual = cc->interleave_factor; cc->io_residual = 0; cc->offset += cc->full_stripe_size - cc->interleave_factor; } if (cc->io_residual == 0) { /* * Because we use select(2)/poll(2) as a subsequent i/o * of this statement, we must read just one int32 data only. * Otherwise the select(2)/poll(2) cannot see that * this stream is readable. */ /* XXX - FIXME layering violation */ e = xxx_proto_recv(gfs_server->conn, 1, &eof, "i", &size); if (e != NULL) { cc->flags |= GCSCC_FINISHED; return (e); } if (eof) { cc->flags |= GCSCC_FINISHED; return (GFARM_ERR_PROTOCOL); } if (size <= 0) { cc->flags |= GCSCC_FINISHED; *rvp = size; return (NULL); } cc->io_residual = size; } /* * Because we use select(2)/poll(2) as a subsequent i/o * of this statement, we must read just `size' bytes only. * Otherwise the select(2)/poll(2) cannot see that * this stream is readable. */ /* XXX - FIXME layering violation */ partial = xxx_recv_partial(gfs_server->conn, 1, buffer, cc->io_residual); if (partial == 0) return (GFARM_ERR_PROTOCOL); #ifdef XXX_MEASURE_CKSUM_COST /* XXX - we cannot calculate checksum on parallel case. */ #endif /* We assume that each block never goes across any chunk. */ cc->io_residual -= partial; cc->chunk_residual -= partial; #ifndef HAVE_PWRITE if (lseek(cc->ofd, (off_t)cc->offset, SEEK_SET) == -1) return (gfarm_errno_to_error(errno)); #endif #ifdef __GNUC__ /* shut up stupid warning by gcc */ rv = 0; #endif for (i = 0; i < partial; i += rv) { #ifndef HAVE_PWRITE rv = write(cc->ofd, buffer + i, partial - i); #else rv = pwrite(cc->ofd, buffer + i, partial - i, (off_t)cc->offset + i); #endif if (rv <= 0) break; } cc->offset += partial; if (i < partial) { /* * write(2) never returns 0, * so the following rv == 0 case is * just warm fuzzy. */ return (gfarm_errno_to_error(rv == 0 ? ENOSPC : errno)); /* * XXX - we should return rest of data, * even if write(2) fails. */ } *rvp = partial; return (NULL); } char * gfs_client_striping_copyin_result(struct gfs_connection *gfs_server) { struct gfs_client_striping_copyin_context *cc = gfs_server->context; char *e, *e_save = NULL; int rv; while ((cc->flags & GCSCC_FINISHED) == 0) { e = gfs_client_striping_copyin_partial(gfs_server, &rv); if (e != NULL && e_save == NULL) e_save = e; } free(gfs_server->context); gfs_server->context = NULL; e = gfs_client_rpc_result(gfs_server, 0, ""); return (e != NULL ? e : e_save); } char * gfs_client_striping_copyin(struct gfs_connection *gfs_server, int src_fd, int ofd, file_offset_t offset, file_offset_t size, int interleave_factor, file_offset_t full_stripe_size) { char *e; e = gfs_client_striping_copyin_request(gfs_server, src_fd, ofd, offset, size, interleave_factor, full_stripe_size); if (e != NULL) return (e); return (gfs_client_striping_copyin_result(gfs_server)); } char * gfs_client_replicate_file_sequential_request(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, char *srchost) { return (gfs_client_rpc_request(gfs_server, GFS_PROTO_REPLICATE_FILE_SEQUENTIAL, "sis", gfarm_file, mode, srchost)); } char * gfs_client_replicate_file_parallel_request(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, gfarm_int32_t ndivisions, gfarm_int32_t interleave_factor, char *srchost) { return (gfs_client_rpc_request(gfs_server, GFS_PROTO_REPLICATE_FILE_PARALLEL, "sioiis", gfarm_file, mode, file_size, ndivisions, interleave_factor, srchost)); } char * gfs_client_replicate_file_result(struct gfs_connection *gfs_server) { return (gfs_client_rpc_result(gfs_server, 0, "")); } char * gfs_client_replicate_file_request(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname) { char *e; struct sockaddr peer_addr; long parallel_streams, stripe_unit_size; /* * netparam is evaluated here rather than in gfsd, * so, settings in user's .gfarmrc can be reflected. * * XXX - but this also means that settings in frontend host * is used, rather than settings in the host which does * actual transfer. */ e = gfarm_host_address_get(src_if_hostname, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) return (e); e = gfarm_netparam_config_get_long( &gfarm_netparam_parallel_streams, src_canonical_hostname, (struct sockaddr *)&peer_addr, &parallel_streams); if (e != NULL) /* shouldn't happen */ return (e); if (parallel_streams <= 1) return (gfs_client_replicate_file_sequential_request( gfs_server, gfarm_file, mode, src_if_hostname)); e = gfarm_netparam_config_get_long( &gfarm_netparam_stripe_unit_size, src_canonical_hostname, (struct sockaddr *)&peer_addr, &stripe_unit_size); if (e != NULL) /* shouldn't happen */ return (e); return (gfs_client_replicate_file_parallel_request(gfs_server, gfarm_file, mode, file_size, parallel_streams, stripe_unit_size, src_if_hostname)); } char * gfs_client_replicate_file(struct gfs_connection *gfs_server, char *gfarm_file, gfarm_int32_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname) { char *e; e = gfs_client_replicate_file_request(gfs_server, gfarm_file, mode, file_size, src_canonical_hostname, src_if_hostname); if (e == NULL) e = gfs_client_replicate_file_result(gfs_server); return (e); } struct gfs_client_command_context { struct gfarm_iobuffer *iobuffer[NFDESC]; enum { GFS_COMMAND_SERVER_STATE_NEUTRAL, GFS_COMMAND_SERVER_STATE_OUTPUT, GFS_COMMAND_SERVER_STATE_EXITED, GFS_COMMAND_SERVER_STATE_ABORTED } server_state; int server_output_fd; int server_output_residual; enum { GFS_COMMAND_CLIENT_STATE_NEUTRAL, GFS_COMMAND_CLIENT_STATE_OUTPUT } client_state; int client_output_residual; int pid; int pending_signal; }; void gfs_client_command_set_stdin(struct gfs_connection *gfs_server, int (*rf)(struct gfarm_iobuffer *, void *, int, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_read(cc->iobuffer[FDESC_STDIN], rf, cookie, fd); } void gfs_client_command_set_stdout(struct gfs_connection *gfs_server, int (*wf)(struct gfarm_iobuffer *, void *, int, void *, int), void (*wcf)(struct gfarm_iobuffer *, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_write(cc->iobuffer[FDESC_STDOUT], wf, cookie, fd); gfarm_iobuffer_set_write_close(cc->iobuffer[FDESC_STDOUT], wcf); } void gfs_client_command_set_stderr(struct gfs_connection *gfs_server, int (*wf)(struct gfarm_iobuffer *, void *, int, void *, int), void (*wcf)(struct gfarm_iobuffer *, void *, int), void *cookie, int fd) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_write(cc->iobuffer[FDESC_STDERR], wf, cookie, fd); gfarm_iobuffer_set_write_close(cc->iobuffer[FDESC_STDERR], wcf); } char *gfs_client_command_request(struct gfs_connection *gfs_server, char *path, char **argv, char **envp, int flags, int *pidp) { struct gfs_client_command_context *cc; int na = argv == NULL ? 0 : gfarm_strarray_length(argv); int ne = envp == NULL ? 0 : gfarm_strarray_length(envp); int conn_fd = xxx_connection_fd(gfs_server->conn); int i, xenv_copy, xauth_copy; gfarm_int32_t pid; socklen_t siz; char *e; static char *xdisplay_name_cache = NULL; static char *xdisplay_env_cache = NULL; static int xauth_cached = 0; static char *xauth_cache = NULL; char *dpy; if ((dpy = getenv("DISPLAY")) != NULL && xdisplay_name_cache == NULL && (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) != 0) { /* * get $DISPLAY to `xdisplay_name_cache', * and set "DISPLAY=$DISPLAY" to `xdisplay_env_cache'. */ static char xdisplay_env_format[] = "DISPLAY=%s"; static char local_prefix[] = "unix:"; char *prefix; if (*dpy == ':') { prefix = gfarm_host_get_self_name(); } else if (memcmp(dpy, local_prefix, sizeof(local_prefix) - 1) == 0) { prefix = gfarm_host_get_self_name(); dpy += sizeof(local_prefix) - 1 - 1; } else { prefix = ""; } xdisplay_name_cache = malloc(strlen(prefix) + strlen(dpy) + 1); if (xdisplay_name_cache == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(xdisplay_name_cache, "%s%s", prefix, dpy); xdisplay_env_cache = malloc(sizeof(xdisplay_env_format) + strlen(dpy)); if (xdisplay_name_cache == NULL) { free(xdisplay_name_cache); xdisplay_name_cache = NULL; return (GFARM_ERR_NO_MEMORY); } sprintf(xdisplay_env_cache, xdisplay_env_format, xdisplay_name_cache); } if ((flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) == GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY && xdisplay_name_cache != NULL && !xauth_cached) { /* * get xauth data to `xauth_cache' */ static char xauth_command_format[] = "%s nextract - %s 2>/dev/null"; char *xauth_command; FILE *fp; char *s, line[XAUTH_NEXTRACT_MAXLEN]; xauth_command = malloc(sizeof(xauth_command_format) + strlen(XAUTH_COMMAND) + strlen(xdisplay_name_cache)); if (xauth_command == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(xauth_command, xauth_command_format, XAUTH_COMMAND, xdisplay_name_cache); if ((fp = popen(xauth_command, "r")) == NULL) { free(xauth_command); return (GFARM_ERR_NO_MEMORY); } s = fgets(line, sizeof line, fp); pclose(fp); free(xauth_command); if (s != NULL) { xauth_cache = strdup(line); if (xauth_cache == NULL) { free(xdisplay_name_cache); return (GFARM_ERR_NO_MEMORY); } } xauth_cached = 1; } xenv_copy = (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) != 0 && xdisplay_env_cache != NULL; xauth_copy = (flags & GFS_CLIENT_COMMAND_FLAG_X11MASK) == GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY && xauth_cache != NULL; /* * don't pass * GFS_CLIENT_COMMAND_FLAG_STDIN_EOF and * GFS_CLIENT_COMMAND_FLAG_XENV_COPY flag via network */ e = gfs_client_rpc_request(gfs_server, GFS_PROTO_COMMAND, "siii", path, na, ne + (xenv_copy ? 1 : 0), ((flags & GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND) ? GFS_CLIENT_COMMAND_FLAG_SHELL_COMMAND : 0) | (xauth_copy ? GFS_CLIENT_COMMAND_FLAG_XAUTHCOPY : 0)); if (e != NULL) return (e); /* * argv */ for (i = 0; i < na; i++) { e = xxx_proto_send(gfs_server->conn, "s", argv[i]); if (e != NULL) return (e); } /* * envp */ for (i = 0; i < ne; i++) { e = xxx_proto_send(gfs_server->conn, "s", envp[i]); if (e != NULL) return (e); } if (xenv_copy) { e = xxx_proto_send(gfs_server->conn, "s", xdisplay_env_cache); if (e != NULL) return (e); } if (xauth_copy) { /* * xauth */ e = xxx_proto_send(gfs_server->conn, "s", xauth_cache); if (e != NULL) return (e); } /* we have to set `just' flag here */ e = gfs_client_rpc_result(gfs_server, 1, "i", &pid); if (e != NULL) return (e); cc = gfs_server->context = malloc(sizeof(struct gfs_client_command_context)); if (gfs_server->context == NULL) return (GFARM_ERR_NO_MEMORY); /* * Now, we set the connection file descriptor non-blocking mode. */ if (fcntl(conn_fd, F_SETFL, O_NONBLOCK) == -1) { free(gfs_server->context); gfs_server->context = NULL; return (gfarm_errno_to_error(errno)); } /* * initialize gfs_server->context by default values */ siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_SNDBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDIN] = gfarm_iobuffer_alloc(i); siz = sizeof(i); if (getsockopt(conn_fd, SOL_SOCKET, SO_RCVBUF, &i, &siz)) i = GFARM_DEFAULT_COMMAND_IOBUF_SIZE; cc->iobuffer[FDESC_STDOUT] = gfarm_iobuffer_alloc(i); cc->iobuffer[FDESC_STDERR] = gfarm_iobuffer_alloc(i); gfarm_iobuffer_set_nonblocking_read_fd( cc->iobuffer[FDESC_STDIN], FDESC_STDIN); gfarm_iobuffer_set_nonblocking_write_xxx( cc->iobuffer[FDESC_STDIN], gfs_server->conn); gfarm_iobuffer_set_nonblocking_read_xxx( cc->iobuffer[FDESC_STDOUT], gfs_server->conn); gfarm_iobuffer_set_nonblocking_write_fd( cc->iobuffer[FDESC_STDOUT], FDESC_STDOUT); gfarm_iobuffer_set_nonblocking_read_xxx( cc->iobuffer[FDESC_STDERR], gfs_server->conn); gfarm_iobuffer_set_nonblocking_write_fd( cc->iobuffer[FDESC_STDERR], FDESC_STDERR); if ((flags & GFS_CLIENT_COMMAND_FLAG_STDIN_EOF) != 0) gfarm_iobuffer_set_read_eof(cc->iobuffer[FDESC_STDIN]); cc->server_state = GFS_COMMAND_SERVER_STATE_NEUTRAL; cc->client_state = GFS_COMMAND_CLIENT_STATE_NEUTRAL; cc->pending_signal = 0; *pidp = cc->pid = pid; return (e); } int gfs_client_command_is_running(struct gfs_connection *gfs_server) { struct gfs_client_command_context *cc = gfs_server->context; return (cc->server_state != GFS_COMMAND_SERVER_STATE_EXITED && cc->server_state != GFS_COMMAND_SERVER_STATE_ABORTED); } char * gfs_client_command_fd_set(struct gfs_connection *gfs_server, fd_set *readable, fd_set *writable, int *max_fdp) { struct gfs_client_command_context *cc = gfs_server->context; int conn_fd = xxx_connection_fd(gfs_server->conn); int i, fd; /* * The following test condition should just match with * the i/o condition in gfs_client_command_io_fd_set(), * otherwise unneeded busy wait happens. */ if (cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL || (cc->server_state == GFS_COMMAND_SERVER_STATE_OUTPUT && gfarm_iobuffer_is_readable(cc->iobuffer[cc->server_output_fd]))) { FD_SET(conn_fd, readable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if ((cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL && (cc->pending_signal || gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDIN]))) || cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT) { FD_SET(conn_fd, writable); if (*max_fdp < conn_fd) *max_fdp = conn_fd; } if (gfarm_iobuffer_is_readable(cc->iobuffer[FDESC_STDIN])) { fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDIN]); if (fd < 0) { gfarm_iobuffer_read(cc->iobuffer[FDESC_STDIN], NULL); } else { FD_SET(fd, readable); if (*max_fdp < fd) *max_fdp = fd; } } for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { if (gfarm_iobuffer_is_writable(cc->iobuffer[i])) { fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[i]); if (fd < 0) { gfarm_iobuffer_write(cc->iobuffer[i], NULL); } else { FD_SET(fd, writable); if (*max_fdp < fd) *max_fdp = fd; } } } return (NULL); } char * gfs_client_command_io_fd_set(struct gfs_connection *gfs_server, fd_set *readable, fd_set *writable) { struct gfs_client_command_context *cc = gfs_server->context; int fd, conn_fd = xxx_connection_fd(gfs_server->conn); fd = gfarm_iobuffer_get_read_fd(cc->iobuffer[FDESC_STDIN]); if (fd >= 0 && FD_ISSET(fd, readable)) gfarm_iobuffer_read(cc->iobuffer[FDESC_STDIN], NULL); fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[FDESC_STDOUT]); if (fd >= 0 && FD_ISSET(fd, writable)) gfarm_iobuffer_write(cc->iobuffer[FDESC_STDOUT], NULL); fd = gfarm_iobuffer_get_write_fd(cc->iobuffer[FDESC_STDERR]); if (fd >= 0 && FD_ISSET(fd, writable)) gfarm_iobuffer_write(cc->iobuffer[FDESC_STDERR], NULL); if (FD_ISSET(conn_fd, readable)) { if (cc->server_state == GFS_COMMAND_SERVER_STATE_NEUTRAL) { gfarm_int32_t cmd, fd, len; int eof; char *e; e = xxx_proto_recv(gfs_server->conn, 1, &eof, "i", &cmd); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_GFSD_ABORTED; cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } switch (cmd) { case GFS_PROTO_COMMAND_EXITED: cc->server_state = GFS_COMMAND_SERVER_STATE_EXITED; break; case GFS_PROTO_COMMAND_FD_OUTPUT: e = xxx_proto_recv(gfs_server->conn, 1, &eof, "ii", &fd, &len); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_GFSD_ABORTED; cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (e); } if (fd != FDESC_STDOUT && fd != FDESC_STDERR) { /* XXX - something wrong */ cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return ("illegal gfsd descriptor"); } if (len <= 0) { /* notify closed */ gfarm_iobuffer_set_read_eof( cc->iobuffer[fd]); } else { cc->server_state = GFS_COMMAND_SERVER_STATE_OUTPUT; cc->server_output_fd = fd; cc->server_output_residual = len; } break; default: /* XXX - something wrong */ cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return ("unknown gfsd reply"); } } if (cc->server_state == GFS_COMMAND_SERVER_STATE_OUTPUT) { gfarm_iobuffer_read(cc->iobuffer[cc->server_output_fd], &cc->server_output_residual); if (cc->server_output_residual == 0) cc->server_state = GFS_COMMAND_SERVER_STATE_NEUTRAL; if (gfarm_iobuffer_is_read_eof( cc->iobuffer[cc->server_output_fd])) { cc->server_state = GFS_COMMAND_SERVER_STATE_ABORTED; return (GFARM_ERR_GFSD_ABORTED); } } } if (FD_ISSET(conn_fd, writable) && gfs_client_command_is_running(gfs_server)) { if (cc->client_state == GFS_COMMAND_CLIENT_STATE_NEUTRAL) { char *e; if (cc->pending_signal) { e = xxx_proto_send(gfs_server->conn, "ii", GFS_PROTO_COMMAND_SEND_SIGNAL, cc->pending_signal); xxx_proto_flush(gfs_server->conn); } if (gfarm_iobuffer_is_writable( cc->iobuffer[FDESC_STDIN])) { /* * cc->client_output_residual may be 0, * if stdin reaches EOF. */ cc->client_output_residual = gfarm_iobuffer_avail_length( cc->iobuffer[FDESC_STDIN]); e = xxx_proto_send(gfs_server->conn, "iii", GFS_PROTO_COMMAND_FD_INPUT, FDESC_STDIN, cc->client_output_residual); xxx_proto_flush(gfs_server->conn); cc->client_state = GFS_COMMAND_CLIENT_STATE_OUTPUT; } } if (cc->client_state == GFS_COMMAND_CLIENT_STATE_OUTPUT) { gfarm_iobuffer_write(cc->iobuffer[FDESC_STDIN], &cc->client_output_residual); if (cc->client_output_residual == 0) cc->client_state = GFS_COMMAND_CLIENT_STATE_NEUTRAL; } } return (NULL); } char * gfs_client_command_io(struct gfs_connection *gfs_server, struct timeval *timeout) { int nfound, max_fd; fd_set readable, writable; char *e = NULL; if (!gfs_client_command_is_running(gfs_server)) return (NULL); max_fd = -1; FD_ZERO(&readable); FD_ZERO(&writable); gfs_client_command_fd_set(gfs_server, &readable, &writable, &max_fd); if (max_fd >= 0) { nfound = select(max_fd + 1, &readable, &writable, NULL, timeout); if (nfound > 0) e = gfs_client_command_io_fd_set(gfs_server, &readable, &writable); } return (e); } int gfs_client_command_send_stdin(struct gfs_connection *gfs_server, void *data, int len) { struct gfs_client_command_context *cc = gfs_server->context; char *p = data; int residual = len, rv; while (residual > 0 && gfs_client_command_is_running(gfs_server)) { rv = gfarm_iobuffer_put(cc->iobuffer[FDESC_STDIN], p, residual); p += rv; residual -= rv; gfs_client_command_io(gfs_server, NULL); } return (len - residual); } void gfs_client_command_close_stdin(struct gfs_connection *gfs_server) { struct gfs_client_command_context *cc = gfs_server->context; gfarm_iobuffer_set_read_eof(cc->iobuffer[FDESC_STDIN]); } char * gfs_client_command_send_signal(struct gfs_connection *gfs_server, int sig) { struct gfs_client_command_context *cc = gfs_server->context; while (gfs_client_command_is_running(gfs_server) && cc->pending_signal != 0) { gfs_client_command_io(gfs_server, NULL); } if (!gfs_client_command_is_running(gfs_server)) return (gfarm_errno_to_error(ESRCH)); cc->pending_signal = sig; /* make a chance to send the signal immediately */ gfs_client_command_io(gfs_server, NULL); return (NULL); } char * gfs_client_command_result(struct gfs_connection *gfs_server, int *term_signal, int *exit_status, int *exit_flag) { struct gfs_client_command_context *cc = gfs_server->context; while (gfs_client_command_is_running(gfs_server)) gfs_client_command_io(gfs_server, NULL); /* * flush stdout/stderr */ while (gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDOUT]) || gfarm_iobuffer_is_writable(cc->iobuffer[FDESC_STDERR])) { int i, nfound, fd, max_fd = -1; fd_set writable; FD_ZERO(&writable); for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { if (gfarm_iobuffer_is_writable(cc->iobuffer[i])) { fd = gfarm_iobuffer_get_write_fd( cc->iobuffer[i]); if (fd < 0) { gfarm_iobuffer_write(cc->iobuffer[i], NULL); } else { FD_SET(fd, &writable); if (max_fd < fd) max_fd = fd; } } } if (max_fd < 0) continue; nfound = select(max_fd + 1, NULL, &writable, NULL, NULL); if (nfound > 0) { for (i = FDESC_STDOUT; i <= FDESC_STDERR; i++) { fd = gfarm_iobuffer_get_write_fd( cc->iobuffer[i]); if (fd >= 0 && FD_ISSET(fd, &writable)) gfarm_iobuffer_write(cc->iobuffer[i], NULL); } } } /* * context isn't needed anymore */ gfarm_iobuffer_free(cc->iobuffer[FDESC_STDIN]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDOUT]); gfarm_iobuffer_free(cc->iobuffer[FDESC_STDERR]); free(gfs_server->context); gfs_server->context = NULL; /* * Now, we recover the connection file descriptor blocking mode. */ if (fcntl(xxx_connection_fd(gfs_server->conn), F_SETFL, 0) == -1) { return (gfarm_errno_to_error(errno)); } return (gfs_client_rpc(gfs_server, 0, GFS_PROTO_COMMAND_EXIT_STATUS, "/iii", term_signal, exit_status, exit_flag)); } char * gfs_client_command(struct gfs_connection *gfs_server, char *path, char **argv, char **envp, int flags, int *term_signal, int *exit_status, int *exit_flag) { char *e, *e2; int pid; e = gfs_client_command_request(gfs_server, path, argv, envp, flags, &pid); if (e) return (e); while (gfs_client_command_is_running(gfs_server)) e = gfs_client_command_io(gfs_server, NULL); e2 = gfs_client_command_result(gfs_server, term_signal, exit_status, exit_flag); return (e != NULL ? e : e2); } /* * gfsd datagram service */ int gfs_client_datagram_timeouts[] = { 10, 100, 1000, 2000 /* milli seconds */ }; int gfs_client_datagram_ntimeouts = GFARM_ARRAY_LENGTH(gfs_client_datagram_timeouts); /* * `server_addr_size' should be socklen_t, but that requires <sys/socket.h> * for all source files which include "gfs_client.h". */ char * gfs_client_get_load_request(int sock, struct sockaddr *server_addr, int server_addr_size) { int rv, command = 0; if (server_addr == NULL || server_addr_size == 0) { /* using connected UDP socket */ rv = write(sock, &command, sizeof(command)); } else { rv = sendto(sock, &command, sizeof(command), 0, server_addr, server_addr_size); } if (rv == -1) return (gfarm_errno_to_error(errno)); return (NULL); } /* * `*server_addr_sizep' is an IN/OUT parameter. * * `*server_addr_sizep' should be socklen_t, but that requires <sys/socket.h> * for all source files which include "gfs_client.h". */ char * gfs_client_get_load_result(int sock, struct sockaddr *server_addr, int *server_addr_sizep, struct gfs_client_load *result) { int rv; double loadavg[3]; #ifndef WORDS_BIGENDIAN struct { char c[8]; } nloadavg[3]; #else # define nloadavg loadavg #endif if (server_addr == NULL || server_addr_sizep == NULL) { /* using connected UDP socket */ rv = read(sock, nloadavg, sizeof(nloadavg)); } else { rv = recvfrom(sock, nloadavg, sizeof(nloadavg), 0, server_addr, server_addr_sizep); } if (rv == -1) return (gfarm_errno_to_error(errno)); #ifndef WORDS_BIGENDIAN swab(&nloadavg[0], &loadavg[0], sizeof(loadavg[0])); swab(&nloadavg[1], &loadavg[1], sizeof(loadavg[1])); swab(&nloadavg[2], &loadavg[2], sizeof(loadavg[2])); #endif result->loadavg_1min = loadavg[0]; result->loadavg_5min = loadavg[1]; result->loadavg_15min = loadavg[2]; return (NULL); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/failure_test_scripts/FT3-3-1-2_failover_while_writing #! /bin/sh ###################################################################### TESTID="FT3-3-1-2" CATEGORY="accident while failover and failure of meta data sync" SECTION="failover in the midst of client accessd" TITLE="failover while writing" ###################################################################### . ./FT-common ft_setup() { DIR=mnt FILE=a.dat SIZE=1000M ssh $client1 "mkdir -p $DIR" $gfservice unmount client1 $DIR $gfservice mount client1 $DIR -o nonempty ssh $client1 "rm -f $FILE create-random-file $DIR/$FILE" scp create-random-file $client1: ssh $client1 "./create-random-file $FILE $SIZE" return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS ssh $client1 "cp $FILE $DIR/$FILE" & [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "copy $FILE to the Gfarm2 filesytem on $client1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd2 "sudo kill -USR1 \`cat /var/run/gfmd.pid\`" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "upgrade slave gfmd on $gfmd2" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_wait_remote_process $client1 "cp $FILE $DIR/$FILE" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "wait copying $FILE to the Gfarm2 filesytem on $client1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $client1 "cmp $FILE $DIR/$FILE" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 5 "compare the copied $FILE with the original" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT GFWHERE=`ssh $client1 $client1_GFBINDIR/gfwhere $FILE` [ $? -eq 0 ] && [ "X$GFWHERE" != X ] && [ `echo $GFWHERE | awk '{ print NF }'` -eq 1 ] \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 6 "check replication status of $FILE" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $client1 "rm -f $FILE $DIR/$FILE create-random-file" $gfservice umount client1 $DIR ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm/tags/gfarm_1_0_4/configure.ac dnl Process this file with autoconf to produce a configure script. AC_INIT AC_CONFIG_SRCDIR(ChangeLog) AC_CONFIG_AUX_DIR(makes) AC_CONFIG_HEADER(include/gfarm/gfarm_config.h) # Determine target system # This is called "host" on autotools, because its terminology is following: # build system - system which is used to build a tool # host system - system which is used to run a tool # target system - system which is used to run a program generated by a tool AC_CANONICAL_HOST ###### ###### Checks for programs. ###### AC_PROG_CC(cc gcc) # search cc before gcc if test x"$GCC" = x"yes"; then # CFLAGS='-g -O2' CFLAGS="${CFLAGS} -Wall" else # CFLAGS='-g' CFLAGS="-O" # don't use -g, but use -O fi AC_PROG_LEX # the following definition should not be needed. # but there is stupid environment which flex exists but libfl.a doesn't. if test x"$LEX" = x"flex"; then AC_CHECK_LIB(fl, yywrap, [LEXLIB=-lfl], [LEXLIB=-ll]) fi AC_PROG_YACC AC_PROG_INSTALL AC_PROG_LIBTOOL ###### ###### parsing command line options ###### ### --with-openldap is handled later, because it needs AC_CHECK_LIB(nsl, ...) ### ### --with-openssl=OpenSSL_ROOT ### AC_ARG_WITH(openssl, [ --with-openssl=OpenSSL_ROOT openssl root directory [[default=/usr]]], [with_openssl="${withval}" ], [with_openssl=/usr ]) AC_MSG_RESULT([using \"${with_openssl}\" as openssl root directory]) openssl_libs='-lssl -lcrypto' if test x"${with_openssl}" = x"/usr"; then openssl_includes= else openssl_includes="-I${with_openssl}/include" openssl_libs="-R${with_openssl}/lib -L${with_openssl}/lib ${openssl_libs}" fi AC_SUBST(openssl_includes) AC_SUBST(openssl_libs) ### ### --with-globus=GLOBUS_ROOT --with-globus-flavor=FLAVOR -with-globus-static ### AC_ARG_WITH(globus_static, [ --with-globus-static link static version of globus libraries instead of shared version [[default=disable]]], [globus_static="${withval}" ], [globus_static="" ]) AC_ARG_WITH(globus_flavor, [ --with-globus-flavor=FLAVOR globus flavor name [[default=guessed]]], [globus_flavor="${withval}" ], [globus_flavor= ]) AC_SUBST(globus_flavor) AC_ARG_WITH(globus, [ --with-globus=GLOBUS_ROOT globus root directory [[default=disable]]], [globus_location="${withval}" case "${globus_location}" in yes) globus_location=${GLOBUS_LOCATION};; esac AC_MSG_CHECKING([globus]) GLBlocation_candidates=${globus_location:-/usr/grid} if test -n "$globus_flavor"; then GLBflavor_candidates="$globus_flavor" else GLBflavor_candidates= if test x"$GCC" = x"yes"; then tmp='gcc vendorcc' else tmp='vendorcc gcc' fi for GLBbits in 64 32; do for GLBcc in $tmp; do for GLBdebug in "" dbg; do for GLBpthread in "" pthr; do GLBflavor_candidates="$GLBflavor_candidates $GLBcc$GLBbits$GLBdebug$GLBpthread" done done done done fi globus_found= for d in ${GLBlocation_candidates}; do for f in ${GLBflavor_candidates}; do if test -f "$d/include/$f/gssapi.h"; then globus_location=$d globus_flavor=$f globus_found=yes break fi done if test x"$globus_found" = x"yes"; then break; fi done if test x"$globus_found" != x"yes"; then AC_MSG_RESULT([not found]) AC_MSG_RESULT([searched directories are: ${GLBlocation_candidates}]) AC_MSG_RESULT([searched flavors are: ${GLBflavor_candidates}]) AC_MSG_ERROR([aborted]) exit 1 fi AC_MSG_RESULT([found in \"${globus_location}\" with \"${globus_flavor}\" flavor]) globus_includes='-I$(globus_location)/include/$(globus_flavor)' globus_libdir='$(globus_location)/lib' cfgmhtmp=/tmp/cfgmh$$ AC_MSG_CHECKING([globus library names]) if case ${globus_static} in yes) env GLOBUS_LOCATION=${globus_location} ${globus_location}/bin/globus-makefile-header -static -flavor=${globus_flavor} globus_gssapi_gsi;; *) env GLOBUS_LOCATION=${globus_location} ${globus_location}/bin/globus-makefile-header -flavor=${globus_flavor} globus_gssapi_gsi;; esac > $cfgmhtmp then AC_MSG_RESULT([done]) else rm -f $cfgmhtmp AC_MSG_ERROR([failed to call globus-makefile-header, aborted]) fi globus_gssapi_libs=`sed -n '/^GLOBUS_PKG_LIBS *=/s///p' $cfgmhtmp` rm -f $cfgmhtmp case ${globus_static} in yes) :;; *) globus_gssapi_libs="-R${globus_libdir} -L${globus_libdir} $globus_gssapi_libs" esac # for conditional compilation which depends on whether globus is enabled or not globus_srcs='$(GLOBUS_SRCS)' globus_objs='$(GLOBUS_OBJS)' globus_cflags='$(GLOBUS_CFLAGS)' globus_targets='$(GLOBUS_TARGETS)' openssl_includes='$(globus_includes)' case ${globus_static} in yes) openssl_libs="${globus_libdir}"'/libssl_$(globus_flavor).a '"${globus_libdir}"'/libcrypto_$(globus_flavor).a' AC_MSG_RESULT([using globus static library: yes]);; *) openssl_libs="-R${globus_libdir} -L${globus_libdir} "'-lssl_$(globus_flavor) -lcrypto_$(globus_flavor)' AC_MSG_RESULT([using globus static library: no]);; esac AC_DEFINE(HAVE_GSI, 1, [Grid Security Infrastructure exists]) ], [globus_location= globus_includes= globus_gssapi_libs= # for conditional compilation which depends on whether globus is enabled or not globus_srcs= globus_objs= globus_cflags= globus_targets= ]) AC_SUBST(globus_location) AC_SUBST(globus_includes) AC_SUBST(globus_gssapi_libs) # for conditional compilation which depends on whether globus is enabled or not AC_SUBST(globus_srcs) AC_SUBST(globus_objs) AC_SUBST(globus_cflags) AC_SUBST(globus_targets) ### ### --with-mpi=MPI_ROOT ### AC_ARG_WITH(mpi, [ --with-mpi=MPI_ROOT MPI root directory [[default=disable]]], [with_mpi="${withval}" if test x"${withval}" = x'yes'; then mpicc="mpicc" else mpicc="${with_mpi}/bin/mpicc" fi AC_MSG_RESULT([using \"${mpicc}\" to compile MPI programs]) # for conditional compilation which depends on whether MPI is enabled or not mpi_srcs='$(MPI_SRCS)' mpi_objs='$(MPI_OBJS)' mpi_srcs='$(MPI_CFLAGS)' mpi_targets='$(MPI_TARGETS)' ], [with_mpi= mpicc= # for conditional compilation which depends on whether MPI is enabled or not mpi_srcs= mpi_objs= mpi_cflags= mpi_targets= ]) AC_SUBST(mpicc) # for conditional compilation which depends on whether globus is enabled or not AC_SUBST(mpi_srcs) AC_SUBST(mpi_objs) AC_SUBST(mpi_cflags) AC_SUBST(mpi_targets) ### The following options are all "ns" specific ### ### --with-readline=READLINE_ROOT ### AC_ARG_WITH(readline, [ --with-readline=READLINE_ROOT readline root directory [[default=disable]]], [with_readline="${withval}" ], [with_readline= ]) readline_found= if test x"${with_readline}" = x"yes"; then for d in /usr/local /usr/pkg /usr do if test -f $d/include/readline/readline.h; then with_readline=$d AC_MSG_RESULT([using \"${d}\" as readline root directory]) readline_found=yes break fi done if test x"${readline_found}" != x"yes"; then AC_MSG_ERROR([readline is not found, aborted]) fi fi if test -n "${with_readline}"; then readline_includes="-DUSE_READLINE" readline_libs="-lreadline -ltermcap" if test x"${with_readline}" != x"/usr"; then readline_includes="-I${with_readline}/include ${readline_includes}" readline_libs="-R${with_readline}/lib -L${with_readline}/lib ${readline_libs}" fi else readline_includes= readline_libs= fi AC_SUBST(readline_includes) AC_SUBST(readline_libs) ### ### --with-default-ns-server=HOSTNAME ### AC_ARG_WITH(default_ns_server, [ --with-default-ns-server=HOSTNAME default hostname of ns server [[default=localhost]]], [default_ns_server="${withval}"], [default_ns_server='localhost']) AC_SUBST(default_ns_server) ### ### --with-default-ns-port=PORTNUMBER ### AC_ARG_WITH(default_ns_port, [ --with-default-ns-port=PORTNUMBER default port number of ns server [[default=5000]]], [default_ns_port="${withval}"], [default_ns_port='5000']) AC_SUBST(default_ns_port) ### ### --with-default-ns-exec-root=DIR ### AC_ARG_WITH(default_ns_exec_root, [ --with-default-ns-exec-root=DIR default top directory of ns_exec [[default=PREFIX]]], [default_ns_exec_root="${withval}" default_ns_exec_bindir="${default_ns_exec_root}/bin" ], [default_ns_exec_root='$(prefix)' default_ns_exec_bindir='$(bindir)' ]) AC_SUBST(default_ns_exec_root) AC_SUBST(default_ns_exec_bindir) ### ### --with-gfarm-rsh=RSH_COMMAND ### AC_ARG_WITH(gfarm_rsh, [ --with-gfarm-rsh=RSH command name equivalent to rsh [[default=rsh]]], [gfarm_rsh="${withval}"], [gfarm_rsh='rsh']) AC_SUBST(gfarm_rsh) ### ### --with-gfarmd-username=DIR ### AC_ARG_WITH(gfarmd_username, [ --with-gfarmd-username=DIR default username of gfarmd [[default=nobody]]], [gfarmd_username="${withval}"], [gfarmd_username='nobody']) AC_SUBST(gfarmd_username) ###### ###### Checks for libraries. ###### ### check sanity of $CC, $CFLAGS and $CPPFLAGS AC_CHECK_HEADERS(stdio.h) if test x"${ac_cv_header_stdio_h}" != x"yes"; then AC_MSG_RESULT([preprocessor option error on: \"$ac_cpp\"]) #exit 1 fi ### check sanity of $CC, $CFLAGS, $CPPFLAGS and $LDFLAGS setting AC_CHECK_FUNCS(printf) if test x"${ac_cv_func_printf}" != x"yes"; then AC_MSG_RESULT([linker option error on: \"$ac_link\"]) exit 1 fi AC_CHECK_LIB(nsl, gethostname) AC_CHECK_LIB(socket, socket) AC_CHECK_LIB(crypt, crypt) AC_CHECK_LIB(compat, cuserid) AC_CHECK_LIB(gen, basename) AC_CHECK_LIB(rt, fdatasync) ### use 64bit off_t, if possible. AC_MSG_CHECKING([Large File extention for 64bit off_t]) if ( getconf LFS_CFLAGS && getconf LFS_LDFLAGS && getconf LFS_LIBS ) > /dev/null 2>&1; then AC_MSG_RESULT([yes]) largefile_cflags="`getconf LFS_CFLAGS`" largefile_ldflags="`getconf LFS_LDFLAGS`" LIBS="$LIBS `getconf LFS_LIBS`" if test x"$host_os" = x"linux-gnu"; then # glibc requires _GNU_SOURCE for pwrite64(2) largefile_cflags="${largefile_cflags} -D_GNU_SOURCE" fi else AC_MSG_RESULT([no]) largefile_cflags= largefile_ldflags= fi AC_SUBST(largefile_cflags) AC_SUBST(largefile_ldflags) ### is _LARGEFILE64_SOURCE API supported? i.e. can be _LFS64_LARGEFILE=1? AC_MSG_CHECKING([_LARGEFILE64_SOURCE API]) if ( getconf LFS64_CFLAGS && getconf LFS64_LDFLAGS && getconf LFS64_LIBS ) > /dev/null 2>&1; then AC_MSG_RESULT([yes]) largefile64_srcs='$(LARGEFILE64_SRCS)' largefile64_objs='$(LARGEFILE64_OBJS)' largefile64_cflags='$(LARGEFILE64_CFLAGS)' largefile64_targets='$(LARGEFILE64_TARGETS)' else AC_MSG_RESULT([no]) largefile64_srcs= largefile64_objs= largefile64_cflags= largefile64_targets= fi # for conditional compilation which depends on _LARGEFILE64_SOURCE API AC_SUBST(largefile64_srcs) AC_SUBST(largefile64_objs) AC_SUBST(largefile64_cflags) AC_SUBST(largefile64_targets) ### ### --with-openldap=OpenLDAP_ROOT ### AC_ARG_WITH(openldap, [ --with-openldap=OpenLDAP_ROOT openldap root directory [[default=guessed]]], [with_openldap="${withval}" ], [with_openldap= ]) openldap_found= if test x"${with_openldap}" = x -o x"${with_openldap}" = x"yes"; then for d in /usr/local/openldap /usr/local /usr/pkg /usr do if test -f $d/include/ldap.h; then with_openldap=$d openldap_found=yes break fi done if test x"${openldap_found}" != x"yes"; then AC_MSG_ERROR([openldap is not found, aborted]) fi fi AC_MSG_RESULT([using \"${with_openldap}\" as openldap root directory]) if test x"${with_openldap}" = x"/usr"; then ldap_includes="" ldflags="" else ldap_includes="-I${with_openldap}/include" ldflags="-R${with_openldap}/lib -L${with_openldap}/lib" fi # OpenLDAP since 2.x calls res_query() and dn_expand(), if dnssrv is # configured, and DNS resolver library doesn't belongs to libc on some # systems. # But we cannot blindly link libresolv, because it may change behaviour # of gethostbyname() and friends. CPPFLAGS_SAVE="$CPPFLAGS" LIBS_SAVE="$LIBS" openldap_found= for libs in "-lldap -llber" "-lldap"; do for extra_lib in "" "-lresolv" "-lbind"; do CPPFLAGS="$CPPFLAGS_SAVE ${ldap_includes}" LIBS="${ldflags} ${libs} ${extra_lib} $LIBS_SAVE" AC_TRY_LINK([ #include <lber.h> #include <ldap.h>],[ LDAP *ldap_server = ldap_open("example.com", 389); ], [ if test x"${extra_lib}" != x; then AC_MSG_RESULT([using ${extra_lib} for LDAP]) ldap_libs="${ldflags} ${libs} ${extra_lib}" else ldap_libs="${ldflags} ${libs}" fi openldap_found=yes break 2 ], []) done # extra_lib done # libs if test x"${openldap_found}" != x"yes"; then AC_MSG_ERROR([openldap cannot be linked, aborted]) fi AC_MSG_RESULT([using \"${ldap_includes} ${ldap_libs}\" for ldap]) CPPFLAGS="$CPPFLAGS_SAVE" LIBS="$LIBS_SAVE" AC_SUBST(ldap_includes) AC_SUBST(ldap_libs) ###### ###### Checks for header files. ###### AC_CHECK_HEADERS(inttypes.h shadow.h crypt.h machine/endian.h attr/xattr.h) ###### ###### Checks for types. ###### AC_C_BIGENDIAN AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(long long) ### socklen_t is available? AC_TRY_LINK([ #include <sys/types.h> #include <sys/socket.h>],[ int rv, s; struct sockaddr addr; socklen_t len; rv = bind(s, &addr, len); ], [ax_cv_have_socklen_t=yes], [ax_cv_have_socklen_t=no]) if test "$ax_cv_have_socklen_t" = no; then # determine size of socklen_t AC_TRY_RUN([ # include <sys/types.h> # include <sys/socket.h> main() { struct msghdr h; /* h.msg_namelen should be socklen_t */ h.msg_namelen = -1; if (sizeof(h.msg_namelen) == sizeof(int) && h.msg_namelen < 0) return (0); /* int */ else return (1); /* size_t */ } ], [ax_cv_socklen_t=int], [ax_cv_socklen_t=size_t]) AC_DEFINE_UNQUOTED(socklen_t, $ax_cv_socklen_t, [3rd argument type of bind(2)/connect(2), if <sys/socket.h> doesn't define]) fi ###### Checks for structures. # empty for now ###### Checks for compiler characteristics. # empty for now ###### ###### Checks for library functions. ###### AC_CHECK_FUNCS(poll pread pwrite snprintf gethostbyname2 getpassphrase setlogin strtoll strtoq setrlimit daemon getloadavg statvfs statfs) ### SUSv2 getpwnam_r() has 5 args, but Solaris's only has 4. AC_TRY_LINK([ #include <sys/types.h> #include <pwd.h>],[ int rv; struct passwd *pwd; char buffer[1024]; rv = getpwnam_r("root", pwd, buffer, sizeof buffer, &pwd); ], [ax_cv_have_getpwnam_r=yes], [ax_cv_have_getpwnam_r=no]) if test "$ax_cv_have_getpwnam_r" = yes; then AC_DEFINE(HAVE_GETPWNAM_R, 1, [5 arguments getpwnam_r() which is compatible with SUSv2 exists]) fi ### SUSv2 getspnam_r() has 5 args, but Solaris's only has 4. AC_TRY_LINK([ #include <shadow.h>],[ int rv; struct spwd *sp; char buffer[1024]; rv = getspnam_r("root", sp, buffer, sizeof buffer, &sp); ], [ax_cv_have_getspnam_r=yes], [ax_cv_have_getspnam_r=no]) if test "$ax_cv_have_getspnam_r" = yes; then AC_DEFINE(HAVE_GETSPNAM_R, 1, [5 arguments getspnam_r() exists]) fi ### Solaris no longer defines sys_nerr/sys_errlist AC_TRY_LINK([ #include <stdio.h> #include <errno.h>],[ int i = sys_nerr; ], [ax_cv_have_sys_nerr=yes], [ax_cv_have_sys_nerr=no]) if test "$ax_cv_have_sys_nerr" = yes; then AC_DEFINE(HAVE_SYS_NERR, 1, [sys_nerr is defined]) fi ###### Checks for system services. # empty for now ###### ###### miscellaneous ###### ### ### config.h template ### AH_TOP([ #ifndef GFARM_CONFIG_H #define GFARM_CONFIG_H ]) AH_BOTTOM([ #if SIZEOF_LONG == 8 typedef long file_offset_t; # define FILE_OFFSET_T_IS_FLOAT 0 # define FILE_OFFSET_T_MAX 0x7fffffffffffffffL # define file_offset_floor(offset) (offset) # define PR_FILE_OFFSET "ld" # define CAST_PR_FILE_OFFSET # define string_to_file_offset(s, endptr) strtol(s, endptr, 0) #elif SIZEOF_LONG_LONG == 8 typedef long long file_offset_t; # define FILE_OFFSET_T_IS_FLOAT 0 # define FILE_OFFSET_T_MAX 0x7fffffffffffffffLL # define file_offset_floor(offset) (offset) # if defined(HAVE_STRTOLL) || defined(HAVE_STRTOQ) # define PR_FILE_OFFSET "lld" # define CAST_PR_FILE_OFFSET # if defined(HAVE_STRTOLL) # define string_to_file_offset(s, endptr) strtoll(s, endptr, 0) # else # define string_to_file_offset(s, endptr) strtoq(s, endptr, 0) # endif # else # define PR_FILE_OFFSET ".0f" # define CAST_PR_FILE_OFFSET (double) # define string_to_file_offset(s, endptr) (long long)strtod(s, endptr) # endif #else /* * With IEEE floating point, usually double has 53bits fraction, * 10bits biased exponent, and 1 sign bit. * Thus, this can represent -8192T (== -2^53) ... +8192T (== 2^53). */ typedef double file_offset_t; # define FILE_OFFSET_T_IS_FLOAT 1 # define FILE_OFFSET_T_MAX 9007199254740991.0 /* 2^53-1 */ # define file_offset_floor(offset) floor(offset) # define PR_FILE_OFFSET ".0f" # define CAST_PR_FILE_OFFSET # define string_to_file_offset(s, endptr) strtod(s, endptr) #endif #endif /* GFARM_CONFIG_H */ ]) ### ### lib/gfs_hook ### # need to make system dependent source? # "linux-gnu" -> "linux" gfs_hook_sysdep_subdir=`echo $host_os | sed -e 's/-gnu$//' -e 's/[0-9.]*$//' -e 's/^netbsdelf$/netbsd/'` gfs_hook_sysdep=lib/gfs_hook/sysdep/${gfs_hook_sysdep_subdir} if test -f ${srcdir}/${gfs_hook_sysdep}/Makefile; then AC_MSG_RESULT([using ${gfs_hook_sysdep} directory for system dependent objects.]) else gfs_hook_sysdep_subdir=default fi AC_SUBST(gfs_hook_sysdep_subdir) ### ### ns ### if test -d ${srcdir}/ns; then ns_makefiles=' ns/nslib/Makefile ns/gfarmd/Makefile ns/nstool/file/Makefile' # The following is for --srcdir option. # AC_OUTPUT() assumes that parent directory of the Makefile exists test -d ns || mkdir -p ns test -d ns/nstool || mkdir -p ns/nstool fi # The following is for --srcdir option. # AC_OUTPUT() assumes that parent directory of the Makefile exists test -d include || mkdir -p include test -d gfptool || mkdir -p gfptool test -d package || mkdir -p package test -d util || mkdir -p util AC_CONFIG_FILES(Makefile makes/config.mk ${ns_makefiles} gfptool/util/gfregister package/solaris/gfmd package/solaris/gfsd package/redhat/gfmd package/redhat/gfsd util/gfront/gfront ) AC_OUTPUT <file_sep>/gfarm/branches/metadb_dev/gftool/gfrm/gfrm.c #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfrm"; void usage() { fprintf(stderr, "Usage: %s [option] <gfarm_url>...\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\tcurrently no option is supported.\n"); exit(1); } int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e; int i, ch; if (argc >= 1) program_name = basename(argv[0]); while ((ch = getopt(argc, argv, "rf")) != -1) { switch (ch) { case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < argc; i++) { e = gfs_unlink(argv[i]); if (e != NULL) fprintf(stderr, "%s: %s\n", argv[i], e); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc3/lib/libgfarm/gfsl/Makefile # $Id$ top_builddir = ../../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk ### ### variables ### CFLAGS = $(COMMON_CFLAGS) -I$(GFUTIL_SRCDIR) -I$(GFSL_SRCDIR) \ $(globus_includes) \ -DGLOBUS_BUG=1 # see gsi.c ### for library LIBRARY = libgfsl.la LIBRARY_RESULT = # do not install SRCS = gsi.c tcputil.c auth.c session.c misc.c OBJS = gsi.lo tcputil.lo auth.lo session.lo misc.lo ### for programs PURE = /usr/local/rational/releases/purify.sol.2001a.04.00/purify # LINK = $(PURE) $(CC) $(CFLAGS) # PROG_DEPLIBS = ../gfutil/.libs/libgfutil.a .libs/libgfsl.a LINK = $(LTLINK) PROGRAMS = server client server2 client2 SCOBJS = scarg.o scsub.o SCOBJS2 = scarg.o PROG_DEPLIBS = $(LIBRARY) ../gfutil/libgfutil.la PROG_LDLIBS = $(COMMON_LDFLAGS) $(PROG_DEPLIBS) \ $(globus_gssapi_libs) $(openssl_libs) $(LIBS) ### ### rules ### all: $(LIBRARY) $(PROGRAMS) ### for library $(GFSL_OBJS): $(DEPGFSLINC) include $(top_srcdir)/makes/lib.mk # dependencies auth.lo: $(GFUTIL_SRCDIR)/hash.h $(GFUTIL_SRCDIR)/gfutil.h auth.lo: gfsl_config.h gfarm_auth.h misc.h gsi.lo: $(GFUTIL_SRCDIR)/gfevent.h $(GFUTIL_SRCDIR)/gfutil.h gsi.lo: $(INC_SRCDIR)/gfarm_misc.h tcputil.h gsi.lo: gfsl_config.h gfarm_gsi.h gfarm_auth.h misc.lo: gfsl_config.h gfarm_auth.h session.lo: $(GFUTIL_SRCDIR)/gfevent.h $(GFUTIL_SRCDIR)/gfutil.h session.lo: $(INC_SRCDIR)/gfarm_misc.h tcputil.h session.lo: gfarm_secure_session.h misc.h tcputil.lo: $(GFUTIL_SRCDIR)/gfutil.h tcputil.lo: $(INC_SRCDIR)/gfarm_misc.h tcputil.h server.o server2.o client.o client2.o: $(GFUTIL_SRCDIR)/gfutil.h \ $(INC_SRCDIR)/gfarm_misc.h tcputil.h \ gfsl_config.h gfarm_gsi.h gfarm_secure_session.h misc.h scarg.h server.o server2.o: gfarm_auth.h scarg.o: $(INC_SRCDIR)/gfarm_misc.h gfarm_gsi.h misc.h scarg.h scsub.o: gfarm_secure_session.h gfarm_auth.h scarg.h \ $(INC_SRCDIR)/gfarm_misc.h tcputil.h ### for programs server: server.o $(SCOBJS) $(PROG_DEPLIBS) rm -f $@ $(LINK) -o $@ server.o $(SCOBJS) $(PROG_LDLIBS) client: client.o $(SCOBJS) $(PROG_DEPLIBS) rm -f $@ $(LINK) -o $@ client.o $(SCOBJS) $(PROG_LDLIBS) server2: server2.o $(SCOBJS2) $(PROG_DEPLIBS) rm -f $@ $(LINK) -o $@ server2.o $(SCOBJS2) $(PROG_LDLIBS) client2: client2.o $(SCOBJS2) $(PROG_DEPLIBS) rm -f $@ $(LINK) -o $@ client2.o $(SCOBJS2) $(PROG_LDLIBS) clean: $(RM) -f *.o veryclean: $(LTCLEAN) $(PROGRAMS) *~ core *.core <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/gfarm-zabbix_redundancy/mds_list/scripts/zbx_generate_mdslist.sh #!/bin/sh # # @(#) zbx_generate_mdslist.sh # # Usage: # zbx_generate_mdslist.sh # # Description: # genarate a gfarm2.conf line for "metadb_server_list" on the Gfarm2 file # system. # ############################################################################### # defines GFARM2_PREFIX=/usr/local MDS_LIST=/var/tmp/metadataserver_list.log # generate metadata serve list. if [ ! -f $MDS_LIST ]; then echo "$MDS_LIST not found." exit 1; else echo -n 'metadb_server_list ' cat $MDS_LIST | awk '{ print $6":"$7 }' | tr '\n' ' ' echo fi exit 0; <file_sep>/gfarm_zabbix/trunk/src/failure_test_scripts/FT1-2-1-5_memory_usage #! /bin/sh ###################################################################### TESTID="FT1-2-1-5" CATEGORY="accident causes no failover" SECTION="common observed properties" TITLE="memory usage" ###################################################################### . ./FT-common ft_setup() { RESULT=$FT_RESULT_PASS STRESS_CMD=./malloc STRESS_PERIOD=`expr $FT_MAIL_TIMEOUT + $FT_MAIL_TIMEOUT` STRESS_PARAM=`ssh $gfmd1 free -b | grep Mem | awk '{print $2, $3, $6, $7}'` if [ ! -f $STRESS_CMD ]; then cc -o $STRESS_CMD malloc.c fi scp $STRESS_CMD $gfmd1: || RESULT=$FT_RESULT_FAIL return $RESULT } ft_main() { RESULT=$FT_RESULT_PASS ssh $gfmd1 $STRESS_CMD $STRESS_PARAM $STRESS_PERIOD & [ $? -eq 0 ] || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "start 'malloc'" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mail "High memory use on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ssh $gfmd1 pkill `basename $STRESS_CMD` ft_checkpoint 3 "stop 'malloc'" $RESULT ft_check_mail "Re: High memory use on $gfmd1" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 4 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { ssh $gfmd1 "rm -f $STRESS_CMD" ssh $gfmd1 pkill `basename $STRESS_CMD` return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_3/gfarm2fs_fix_acl.c /* * $Id$ */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <libgen.h> #include <sys/types.h> #include <sys/stat.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #if defined(HAVE_SYS_ACL_H) && defined(HAVE_SYS_XATTR_H) #define ENABLE_ACL #endif #ifdef ENABLE_ACL #include <attr/xattr.h> #include <sys/acl.h> #include "gfarm2fs.h" #include "acl.h" #include "xattr.h" static char *progname = "gfarm2fs_fix_acl"; static gfarm_error_t mode_from_posix_acl_xattr(const char *path, const void *posix_xattr_value, size_t size, mode_t *modep) { gfarm_error_t e; const void *p = posix_xattr_value; const void *endp = p + size; gfarm_uint32_t version, id; gfarm_uint16_t tag, perm; mode_t mode = 0; memcpy(&version, p, sizeof(version)); p += sizeof(version); if (p > endp) return (GFARM_ERR_INVALID_ARGUMENT); if (gfarm_ltoh_32(version) != ACL_EA_VERSION) return (GFARM_ERR_INVALID_ARGUMENT); e = GFARM_ERR_NO_ERROR; while (p < endp) { memcpy(&tag, p, sizeof(tag)); p += sizeof(tag); memcpy(&perm, p, sizeof(perm)); p += sizeof(perm); memcpy(&id, p, sizeof(id)); p += sizeof(id); tag = gfarm_ltoh_16(tag); perm = gfarm_ltoh_16(perm); switch (tag) { case ACL_USER_OBJ: mode |= perm << 6; break; case ACL_GROUP_OBJ: mode |= perm << 3; break; case ACL_OTHER: mode |= perm; break; case ACL_USER: case ACL_GROUP: case ACL_MASK: /* do nothing */ break; default: e = GFARM_ERR_INVALID_ARGUMENT; break; } } *modep = mode; return (e); } static int check_acl_access(const char *path, struct stat *stbufp, int do_chmod, int do_remove) { gfarm_error_t e; ssize_t size, size2; void *value; mode_t mode; int res; size = lgetxattr(path, FIX_ACL_ACCESS, NULL, 0); if (size == -1) { if (errno == ENODATA || errno == ENOATTR) return (0); /* ignore */ fprintf(stderr, "%s: lgetxattr(): %s\n", path, strerror(errno)); return (-1); } if (!S_ISLNK(stbufp->st_mode)) { GFARM_MALLOC_ARRAY(value, size); if (value == NULL) { fprintf(stderr, "%s: error: no memory\n", path); return (-1); } size2 = lgetxattr(path, FIX_ACL_ACCESS, value, size); if (size2 == -1) { fprintf(stderr, "%s: lgetxattr(): %s\n", path, strerror(errno)); free(value); return (-1); } else if (size != size2) { fprintf(stderr, "%s: lgetxattr(): unexpected size\n", path); free(value); return (-1); } e = mode_from_posix_acl_xattr(path, value, size, &mode); if (e != GFARM_ERR_NO_ERROR) { fprintf(stderr, "%s: mode_from_posix_acl_xattr(): %s\n", path, gfarm_error_string(e)); free(value); return (-1); } free(value); mode = (stbufp->st_mode & 07000) | mode; printf("%s (%o): %s\n", ACL_EA_ACCESS, mode, path); if (do_chmod) { res = chmod(path, mode); if (res == -1) { fprintf(stderr, "%s: chmod(): %s\n", path, strerror(errno)); return (-1); } printf("change mode: %o -> %o\n", stbufp->st_mode & 07777, mode); } } else printf("%s (symlink): %s\n", ACL_EA_ACCESS, path); if (do_remove) { res = lremovexattr(path, FIX_ACL_ACCESS); if (res == -1) { fprintf(stderr, "%s: lremovexattr(): %s\n", path, strerror(errno)); return (-1); } } return (0); } static int check_acl_default(const char *path, struct stat *stbufp, int do_remove) { ssize_t size; int res; size = lgetxattr(path, FIX_ACL_DEFAULT, NULL, 0); if (size == -1) { if (errno == ENODATA || errno == ENOATTR) return (0); /* ignore */ fprintf(stderr, "%s: lgetxattr(): %s\n", path, strerror(errno)); return (-1); } printf("%s: %s\n", ACL_EA_DEFAULT, path); if (do_remove) { res = lremovexattr(path, FIX_ACL_DEFAULT); if (res == -1) { fprintf(stderr, "%s: lremovexattr(): %s\n", path, strerror(errno)); return (-1); } } return (0); } static void usage(FILE *out) { fprintf(out, "Fix the ACL extended attribute (xattr) problem on gfarm2fs-1.2.2 or older.\n" "The wrong xattr exists if 'cp -p' or 'mv' have been used on gfarm2fs.\n" "Usage: %s [-cr] filename\n" " default: Print paths which have wrong xattrs. (do nothing)\n" " -c: Do chmod() using system.posix_acl_access xattr.\n" " -r: Remove useless system.posix_acl_{access,default} xattrs.\n" " (Not remove gfarm.acl_{access,default} xattrs.)\n" "Example: find . -exec %s -cr {} \\;\n", progname, progname); } int main(int argc, char **argv) { struct stat stbuf; int i, c, res; int do_chmod = 0, do_remove = 0, error = 0; if (argc > 0) progname = basename(argv[0]); while ((c = getopt(argc, argv, "crh?")) != -1) { switch (c) { case 'c': do_chmod = 1; break; case 'r': do_remove = 1; break; case 'h': case '?': usage(stdout); return (0); default: usage(stderr); return (1); } } argc -= optind; argv += optind; if (argc <= 0) { usage(stderr); return (1); } for (i = 0; i < argc; i++) { char *path = argv[i]; res = lstat(path, &stbuf); if (res == -1) { fprintf(stderr, "%s: lstat(): %s\n", path, strerror(errno)); error++; continue; } res = check_acl_access(path, &stbuf, do_chmod, do_remove); if (res == 0) res = check_acl_default(path, &stbuf, do_remove); if (res == -1) error++; } return (error); } #else int main() { return (1); } #endif <file_sep>/gfarm/tags/gfarm_1_1_1_rc2/lib/libgfarm/gfarm/sockopt.h /* * $Id$ */ struct gfarm_hostspec; char *gfarm_sockopt_config_add(char *, struct gfarm_hostspec *); char *gfarm_sockopt_apply_by_name_addr(int, const char *, struct sockaddr *); char *gfarm_sockopt_listener_config_add(char *); char *gfarm_sockopt_apply_listener(int); <file_sep>/gfarm2fs/branches/1.2.1/Makefile.am bin_PROGRAMS = gfarm2fs gfarm2fs_SOURCES = gfarm2fs.c replicate.c open_file.c \ gfarm2fs.h replicate.h open_file.h gfarm2fs_msg_enums.h EXTRA_DIST = RELNOTES LICENSE gfarm2fs.spec $(private_srcs) AM_CFLAGS = -Wall # # gflog message number assignment # msgno: assign_msgno ASSIGNMSGNO=$(top_srcdir)/msgno/assign_msgno.pl assign_msgno: GFARM_TOPDIR=$(top_srcdir) $(ASSIGNMSGNO) $(gfarm2fs_SOURCES) # # private sources # private-src-link: @if test "x$(top_private_dir)" != "x"; then \ for i in $(private_srcs); do \ if test ! -r ./$${i} -a \ -r $(top_private_dir)/$${i}; then \ ln -s $(top_private_dir)/$${i} . ; \ fi ; \ done ; \ fi private-src-unlink: @if test "x$(top_private_dir)" != "x"; then \ for i in $(private_srcs); do \ if test -L ./$${i}; then \ $(RM) ./$${i} ; \ fi ; \ done ; \ fi install-private: $(bin_PROGRAMS) if test "x$(top_private_dir)" != "x"; then \ for i in $(bin_PROGRAMS); do \ $(binPROGRAMS_INSTALL) $$i \ $(DESTDIR)$(bindir)/$${i}_private ; \ done ; \ fi gfarm2fs.c: private-src-link distclean-local: private-src-unlink <file_sep>/gfarm/tags/gfarm_1_0_rc3/gfptool/gfcp/gfcp.c /* * $Id$ * * Copy a file */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> char *program_name = "gfcp"; void usage() { fprintf(stderr, "Usage: %s [option] <input_file> <output_file>\n", program_name); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-p\tpreserve file status\n"); exit(1); } #define BUFSIZE 65536 int main(int argc, char *argv[]) { int total_nodes, node_index; int flag_preserve = 0; char *e, c, *input, *output; GFS_File igf, ogf; struct gfs_stat gstat; gfarm_mode_t mode; struct gfarm_timespec gtspec[2]; extern char *optarg; extern int optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc >= 1) program_name = argv[0]; while ((c = getopt(argc, argv, "ph")) != -1) { switch (c) { case 'p': flag_preserve = 1; break; case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; e = gfs_pio_get_node_rank(&node_index); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfs_pio_get_node_size(&total_nodes); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing input file name\n", program_name); } exit(1); } input = argv[0]; argc--; argv++; if (argc == 0) { if (node_index == 0) { fprintf(stderr, "%s: missing output file name\n", program_name); } exit(1); } output = argv[0]; argc--; argv++; if (argc != 0) { if (node_index == 0) { fprintf(stderr, "%s: currently, " "only one input file is supported\n", program_name); } exit(1); } if (strcmp(input, output) == 0) { fprintf(stderr, "%s: %s and %s are the same file\n", program_name, input, output); exit(1); } e = gfs_stat(input, &gstat); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, input, e); exit(1); } if (flag_preserve) { mode = gstat.st_mode; gtspec[0] = gstat.st_atimespec; gtspec[1] = gstat.st_mtimespec; } else mode = 0666; gfs_stat_free(&gstat); e = gfs_pio_open(input, GFARM_FILE_RDONLY, &igf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, input, e); exit(1); } e = gfs_pio_set_view_local(igf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, input, e); exit(1); } /* check whether the destination is a directory or not */ e = gfs_stat(output, &gstat); if (e == NULL && GFARM_S_ISDIR(gstat.st_mode)) { if (node_index == 0) { fprintf(stderr, "%s: is a directory\n", output); } exit(1); } e = gfs_pio_create(output, GFARM_FILE_WRONLY, mode, &ogf); if (e != NULL) { fprintf(stderr, "%s: node %d, cannot open %s: %s\n", program_name, node_index, output, e); exit(1); } e = gfs_pio_set_view_local(ogf, GFARM_FILE_SEQUENTIAL); if (e != NULL) { fprintf(stderr, "%s: node %d, set_view_local(%s): %s\n", program_name, node_index, output, e); exit(1); } /* copy this fragment */ for (;;) { int rv, wv; char buffer[BUFSIZE]; e = gfs_pio_read(igf, buffer, sizeof(buffer), &rv); if (e != NULL || rv == 0) break; e = gfs_pio_write(ogf, buffer, rv, &wv); if (e != NULL) break; } if (e != NULL) fprintf(stderr, "%s\n", e); e = gfs_pio_close(igf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", input, e); e = gfs_pio_close(ogf); if (e != NULL) fprintf(stderr, "%s: close failed: %s\n", output, e); if (flag_preserve) { e = gfs_utimes(output, gtspec); if (e != NULL) fprintf(stderr, "%s: utimes failed: %s\n", output, e); } e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1/lib/libgfarm/gfarm/error.c /* * $Id$ */ #include <sys/param.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <netdb.h> #if defined(__linux__) #include <features.h> /* __GNUC_PREREQ() */ #endif #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "hash.h" /* * address constants which represents error conditions */ /* classic errno (1..10, 12..34) */ char GFARM_ERR_OPERATION_NOT_PERMITTED[] = "operation not permitted"; char GFARM_ERR_NO_SUCH_OBJECT[] = "no such object"; char GFARM_ERR_INTERRUPTED_SYSTEM_CALL[] = "interrupted system call"; char GFARM_ERR_INPUT_OUTPUT[] = "input/output error"; char GFARM_ERR_NO_MEMORY[] = "not enough memory"; char GFARM_ERR_PERMISSION_DENIED[] = "permission denied"; char GFARM_ERR_ALREADY_EXISTS[] = "already exists"; char GFARM_ERR_NOT_A_DIRECTORY[] = "not a directory"; char GFARM_ERR_IS_A_DIRECTORY[] = "is a directory"; char GFARM_ERR_INVALID_ARGUMENT[] = "invalid argument"; char GFARM_ERR_NO_SPACE[] = "no space"; char GFARM_ERR_READ_ONLY_FILE_SYSTEM[] = "read-only file system"; /* non classic, non-blocking and interrupt i/o */ char GFARM_ERR_RESOURCE_TEMPORARILY_UNAVAILABLE[] = "resource temporarily unavailable"; /* non classic, filesystem related errors */ char GFARM_ERR_DISK_QUOTA_EXCEEDED[] = "disk quota exceeded"; char GFARM_ERR_DIRECTORY_NOT_EMPTY[] = "directory not empty"; /* math software */ char GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE[] = "numerical result out of range"; /* ipc/network errors */ char GFARM_ERR_OPERATION_NOT_SUPPORTED[] = "operation not supported"; char GFARM_ERR_AUTHENTICATION[] = "authentication error"; char GFARM_ERR_EXPIRED[] = "expired"; char GFARM_ERR_PROTOCOL_NOT_SUPPORTED[] = "protocol not supported"; char GFARM_ERR_PROTOCOL[] = "protocol error"; char GFARM_ERR_NETWORK_IS_UNREACHABLE[] = "network is unreachable"; char GFARM_ERR_NO_ROUTE_TO_HOST[] = "no route to host"; char GFARM_ERR_CONNECTION_TIMED_OUT[] = "connection timed out"; char GFARM_ERR_CONNECTION_REFUSED[] = "connection refused"; char GFARM_ERR_CONNECTION_RESET_BY_PEER[] = "connection reset by peer"; char GFARM_ERR_UNKNOWN_HOST[] = "unknown host"; /* gfarm specific errors */ char GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING[] = "\"gfarm:\" URL prefix is missing"; char GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE[] = "fragment index not available"; char GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH[] = "fragment number does not match"; char GFARM_ERR_AMBIGUOUS_RESULT[] = "ambiguous result"; char GFARM_ERR_INCONSISTENT_RECOVERABLE[] = "inconsistent metadata fixed, try again"; char GFARM_ERR_NO_FRAGMENT_INFORMATION[] = "no fragment information"; char GFARM_ERR_NO_REPLICA_ON_HOST[] = "no file replica on the host"; char GFARM_ERR_UNKNOWN[] = "unknown error"; /* * NOTE: The order of the following table is important. * * For cases that multiple GFARM_ERRs are mapped into same UNIX errno. * first map entry will be used to map UNIX errno to GFARM_ERR, * The implementation of gfarm_errno_to_error_initialize() and * gfarm_errno_to_error() ensures this. * * It is ok that different gfarm error strings are mapped into same errno * (because gfarm error string is more detailed than errno), * but it isn't ok that different errno's are mapped into same gfarm string * (because that means errno is more detailed than gfarm error string). */ struct { int unix_errno; char *gfarm_error; } gfarm_errno_error_map[] = { /* * classic errno (1..10, 12..34) */ { EPERM, GFARM_ERR_OPERATION_NOT_PERMITTED }, { ENOENT, GFARM_ERR_NO_SUCH_OBJECT }, { EINTR, GFARM_ERR_INTERRUPTED_SYSTEM_CALL }, { EIO, GFARM_ERR_INPUT_OUTPUT }, { ENOMEM, GFARM_ERR_NO_MEMORY }, { EACCES, GFARM_ERR_PERMISSION_DENIED }, { EEXIST, GFARM_ERR_ALREADY_EXISTS }, { ENOTDIR, GFARM_ERR_NOT_A_DIRECTORY }, { EISDIR, GFARM_ERR_IS_A_DIRECTORY }, { EINVAL, GFARM_ERR_INVALID_ARGUMENT }, { ENOSPC, GFARM_ERR_NO_SPACE }, { EROFS, GFARM_ERR_READ_ONLY_FILE_SYSTEM }, /* * non classic, non-blocking and interrupt i/o */ { EAGAIN, GFARM_ERR_RESOURCE_TEMPORARILY_UNAVAILABLE }, /* * non classic, filesystem related errors */ { EDQUOT, GFARM_ERR_DISK_QUOTA_EXCEEDED }, { ENOTEMPTY, GFARM_ERR_DIRECTORY_NOT_EMPTY }, /* * math software */ { ERANGE, GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE }, /* * ipc/network errors */ { EOPNOTSUPP, GFARM_ERR_OPERATION_NOT_SUPPORTED }, #ifdef EAUTH /* BSD */ { EAUTH, GFARM_ERR_AUTHENTICATION }, #else /* GFARM_ERR_AUTHENTICATION may be mapped into EPERM, */ /* but EPERM will be mapped into GFARM_ERR_OPERATION_NOT_PERMITTED. */ { EPERM, GFARM_ERR_AUTHENTICATION }, #endif #ifdef ETIME /* Linux */ { ETIME, GFARM_ERR_EXPIRED }, #endif { EPROTONOSUPPORT, GFARM_ERR_PROTOCOL_NOT_SUPPORTED }, #ifdef EPROTO /* SVR4 and Linux */ { EPROTO, GFARM_ERR_PROTOCOL }, #else /* GFARM_ERR_PROTOCOL may be mapped into EPROTONOSUPPORT, */ /* but EPROTONOSUPPORT will be mapped into GFARM_ERR_PROTOCOL_NOT_SUPPORTED. */ { EPROTONOSUPPORT, GFARM_ERR_PROTOCOL }, #endif { ENETUNREACH, GFARM_ERR_NETWORK_IS_UNREACHABLE }, { EHOSTUNREACH, GFARM_ERR_NO_ROUTE_TO_HOST }, { ETIMEDOUT, GFARM_ERR_CONNECTION_TIMED_OUT }, { ECONNREFUSED, GFARM_ERR_CONNECTION_REFUSED }, { ECONNRESET, GFARM_ERR_CONNECTION_RESET_BY_PEER }, }; /* prevent infinite loop caused by where IN_ERRNO(i) is always true. */ #ifndef MAX_ERRNO #define MAX_ERRNO 1024 #endif #define ERRLIST_HASHTAB_SIZE 251 /* prime number */ struct gfarm_hash_table *gfarm_errlist_hashtab; #if defined(__linux__) && defined(__GNUC_PREREQ) #if __GNUC_PREREQ(3,2) /* newer glibc warns against sys_errlist and sys_nerr */ # define STRERROR(i) strerror(i) # define IN_ERRNO(i) (strerror(i) != NULL && (i) < MAX_ERRNO) #endif #endif #ifndef STRERROR #if defined(HAVE_SYS_NERR) # define STRERROR(i) sys_errlist[i] # define IN_ERRNO(i) ((i) < sys_nerr) #else /* Solaris doesn't export sys_nerr/sys_errlist, any more */ # define STRERROR(i) strerror(i) # define IN_ERRNO(i) (strerror(i) != NULL && (i) < MAX_ERRNO) #endif #endif /* STRERROR */ void gfarm_errlist_hashtab_initialize(void) { int i, created; struct gfarm_hash_entry *p; gfarm_errlist_hashtab = gfarm_hash_table_alloc(ERRLIST_HASHTAB_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (gfarm_errlist_hashtab == NULL) { fprintf(stderr, "gfarm_errlist_hashtab_initialize(): " "no memory\n"); exit(1); } for (i = 1; IN_ERRNO(i); i++) { if (STRERROR(i) == NULL) continue; p = gfarm_hash_enter(gfarm_errlist_hashtab, STRERROR(i), strlen(STRERROR(i)) + 1, sizeof(int), &created); if (p == NULL) { fprintf(stderr, "gfarm_errlist_hashtab_initialize(): " "no memory for errno %d\n", i); exit(1); } if (created) *(int *)gfarm_hash_entry_data(p) = i; } } int gfarm_error_to_errno(const char *error) { struct gfarm_hash_entry *p; int i; if (gfarm_errlist_hashtab == NULL) gfarm_errlist_hashtab_initialize(); for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_errno_error_map); i++) { if (error == gfarm_errno_error_map[i].gfarm_error) return (gfarm_errno_error_map[i].unix_errno); } /* * The reason why we compare string content rather than string * address here is that strerror(3) may always copy error string * to its internal buffer. * * XXX - If we always use sys_errlist[] rather than strerror(3), * is it ok to just compare string address? */ /* XXX - if locale LC_MESSAGES is changed, this may not work. */ p = gfarm_hash_lookup(gfarm_errlist_hashtab, error, strlen(error) + 1); if (p != NULL) return (*(int *)gfarm_hash_entry_data(p)); return (EINVAL); /* last resort, cannot mapped into errno */ } #ifndef ELAST /* sys_nerr isn't constant */ #define ELAST 257 #endif char *gfarm_errno_to_error_map[ELAST + 1]; int gfarm_errno_to_error_initialized; int gfarm_errno_to_error_table_overflow; void gfarm_errno_to_error_initialize(void) { int i, unix_errno; if (gfarm_errno_to_error_initialized) return; gfarm_errno_to_error_initialized = 1; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_errno_error_map); i++) { unix_errno = gfarm_errno_error_map[i].unix_errno; if (unix_errno > ELAST) { gfarm_errno_to_error_table_overflow = 1; } else if (gfarm_errno_to_error_map[unix_errno] == NULL) { /* make sure to be first match */ gfarm_errno_to_error_map[unix_errno] = gfarm_errno_error_map[i].gfarm_error; } } } char * gfarm_errno_to_error(int unix_errno) { int i; char *e; /* this function is critical, so make sure */ if (!gfarm_errno_to_error_initialized) gfarm_errno_to_error_initialize(); if (unix_errno <= ELAST) { e = gfarm_errno_to_error_map[unix_errno]; if (e != NULL) return (e); else { /* XXX const */ return ((char *)STRERROR(unix_errno)); } } if (gfarm_errno_to_error_table_overflow) { for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_errno_error_map); i++) { if (unix_errno == gfarm_errno_error_map[i].unix_errno) return (gfarm_errno_error_map[i].gfarm_error); } } /* XXX const */ return ((char *)STRERROR(unix_errno)); } void gfarm_error_initialize(void) { gfarm_errlist_hashtab_initialize(); gfarm_errno_to_error_initialize(); } <file_sep>/gfarm/tags/gfarm_1_0_beta_3/lib/libgfarm/gfarm/auth_server_gsi.c #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <grp.h> #include <sys/types.h> #include <time.h> #include <pwd.h> #include <gssapi.h> #include <stdio.h> #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "xxx_proto.h" #include "io_fd.h" #include "io_gfsl.h" #include "auth.h" /* * Delegated credential */ static gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL; void gfarm_gsi_set_delegated_cred(gss_cred_id_t cred) { delegated_cred = cred; } gss_cred_id_t gfarm_gsi_get_delegated_cred() { return (delegated_cred); } /* * */ static char * gfarm_authorize_gsi_common(struct xxx_connection *conn, int switch_to, char *hostname, char *auth_method_name, char **global_usernamep) { int fd = xxx_connection_fd(conn); char *e, *e2, *global_username; OM_uint32 e_major, e_minor; gfarmSecSession *session; gfarmAuthEntry *userinfo; gfarm_int32_t error = GFARM_AUTH_ERROR_NO_ERROR; /* gfarm_auth_error */ e = xxx_proto_flush(conn); if (e != NULL) { gflog_error("authorize_gsi: protocol drain ", e); return (e); } e = gfarm_gsi_initialize(); if (e != NULL) { gflog_error("authorize_gsi: GSI initialize", e); return (e); } session = gfarmSecSessionAccept(fd, GSS_C_NO_CREDENTIAL, NULL, &e_major, &e_minor); if (session == NULL) { if (gfarm_authentication_verbose) { gflog_error("Can't accept session because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); gflog_error("GSI authentication error", hostname); } return (GFARM_ERR_AUTHENTICATION); } userinfo = gfarmSecSessionGetInitiatorInfo(session); #if 1 /* XXX - global name should be distinguished by DN (distinguish name) */ e = gfarm_local_to_global_username( userinfo->authData.userAuth.localName, &global_username); if (e != NULL) { global_username = NULL; error = GFARM_AUTH_ERROR_DENIED; gflog_error("authorize_gsi: " "cannot map global username into local username", userinfo->authData.userAuth.localName); } #else /* * We DO need GSI authentication to access user database in this case, * otherwise GSI authentcation depends on weak protocol. */ e = gfarm_DN_to_global_username(userinfo->distName, &global_username); if (e != NULL) { global_username = NULL; error = GFARM_AUTH_ERROR_DENIED; gflog_error("authorize_gsi: " "cannot map DN into global username", userinfo->distName); } #endif if (e == NULL) { /* assert(error == GFARM_AUTH_ERROR_NO_ERROR); */ /* succeed, do logging */ static char method_prefix[] = "auth="; static char user_prefix[] = " local_user="; static char dnb[] = " DN=\""; static char dne[] = "\""; char *aux = malloc(strlen(global_username) + 1 + strlen(hostname) + 1); char *msg = malloc(sizeof(method_prefix) - 1 + strlen(auth_method_name) + sizeof(user_prefix) - 1 + strlen(userinfo->authData.userAuth.localName) + sizeof(dnb)-1 + strlen(userinfo->distName) + sizeof(dne)); if (aux == NULL || msg == NULL) { e = GFARM_ERR_NO_MEMORY; error = GFARM_AUTH_ERROR_RESOURCE_UNAVAILABLE; if (aux != NULL) free(aux); if (msg != NULL) free(msg); gflog_error("authorize_gsi", e); } else { sprintf(aux, "%s@%s", global_username, hostname); gflog_set_auxiliary_info(aux); sprintf(msg, "%s%s%s%s%s%s%s", method_prefix, auth_method_name, user_prefix, userinfo->authData.userAuth.localName, dnb, userinfo->distName, dne); gflog_notice("authenticated", msg); free(msg); if (!switch_to) { gflog_set_auxiliary_info(NULL); free(aux); } } } xxx_connection_set_secsession(conn, session); e2 = xxx_proto_send(conn, "i", error); if (e2 != NULL) { gflog_error("authorize_gsi: send reply", e2); } else if ((e2 = xxx_proto_flush(conn)) != NULL) { gflog_error("authorize_gsi: completion", e2); } if (e != NULL || e2 != NULL) { if (global_username != NULL) free(global_username); xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); return (e); } if (switch_to) { /* * because the name returned by getlogin() is * an attribute of a session on 4.4BSD derived OSs, * we should create new session before calling * setlogin(). */ setsid(); #ifdef HAVE_SETLOGIN setlogin(userinfo->authData.userAuth.localName); #endif initgroups(userinfo->authData.userAuth.localName, userinfo->authData.userAuth.gid); gfarmSecSessionDedicate(session); gfarm_set_global_username(global_username); gfarm_set_local_username( userinfo->authData.userAuth.localName); gfarm_set_local_homedir( userinfo->authData.userAuth.homeDir); /* set the delegated credential. */ gfarm_gsi_set_delegated_cred( gfarmSecSessionGetDelegatedCredential(session)); } if (global_usernamep != NULL) *global_usernamep = global_username; else free(global_username); return (NULL); } /* * "gsi" method */ char * gfarm_authorize_gsi(struct xxx_connection *conn, int switch_to, char *hostname, char **global_usernamep) { return (gfarm_authorize_gsi_common(conn, switch_to, hostname, "gsi", global_usernamep)); } /* * "gsi_auth" method */ char * gfarm_authorize_gsi_auth(struct xxx_connection *conn, int switch_to, char *hostname, char **global_usernamep) { char *e = gfarm_authorize_gsi_common(conn, switch_to, hostname, "gsi_auth", global_usernamep); int fd = xxx_connection_fd(conn); if (e == NULL) { xxx_connection_reset_secsession(conn); xxx_connection_set_fd(conn, fd); } return (e); } <file_sep>/gfarm/tags/gfarm_1_0_4/gftool/Makefile top_builddir = .. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = \ digest \ gfdf \ gfexec \ gfexport \ gfhost \ gfkey \ gfls \ gfmkdir \ gfpwd \ gfrcmd \ gfreg \ gfrep \ gfrm \ gfrmdir \ gfsched \ gfsck \ gfsetdir \ gfstat \ gfmpirun \ gfps \ gfrun \ gfwhere \ gfwhoami \ example include $(top_srcdir)/makes/subdir.mk <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/auth_client.c #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <limits.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "xxx_proto.h" #ifdef HAVE_GSI #include "io_gfsl.h" /* XXX - gfarm_auth_request_gsi() */ #endif #include "auth.h" /* * currently 31 is enough, * but it is possible that future server replies more methods. */ #define GFARM_AUTH_METHODS_BUFFER_SIZE 256 char *gfarm_auth_request_sharedsecret(struct xxx_connection *); struct { enum gfarm_auth_method method; char *(*request)(struct xxx_connection *); } gfarm_auth_trial_table[] = { /* * This table entry should be prefered order */ { GFARM_AUTH_METHOD_SHAREDSECRET, gfarm_auth_request_sharedsecret }, #ifdef HAVE_GSI { GFARM_AUTH_METHOD_GSI, gfarm_auth_request_gsi }, #endif { GFARM_AUTH_METHOD_NONE, NULL } /* sentinel */ }; char * gfarm_auth_request_sharedsecret(struct xxx_connection *conn) { /* * too weak authentication. * assumes shared home directory. */ char *e, *user, *home; unsigned int expire; char shared_key[GFARM_AUTH_SHARED_KEY_LEN]; char challenge[GFARM_AUTH_CHALLENGE_LEN]; char response[GFARM_AUTH_RESPONSE_LEN]; size_t len; gfarm_int32_t error, error_ignore; /* enum gfarm_auth_error */ int eof, key_create = GFARM_AUTH_SHARED_KEY_CREATE; int try = 0; user = gfarm_get_global_username(); home = gfarm_get_local_homedir(); if (user == NULL || home == NULL) return ( "gfarm_auth_request_sharedsecret(): programming error, " "gfarm library isn't properly initialized"); e = xxx_proto_send(conn, "s", user); if (e != NULL) return (e); do { e = xxx_proto_send(conn, "i", GFARM_AUTH_SHAREDSECRET_MD5); if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "i", &error); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (error != GFARM_AUTH_ERROR_NO_ERROR) break; e = gfarm_auth_shared_key_get(&expire, shared_key, home, key_create); key_create = GFARM_AUTH_SHARED_KEY_CREATE_FORCE; if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "b", sizeof(challenge), &len, challenge); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); gfarm_auth_sharedsecret_response_data(shared_key, challenge, response); e = xxx_proto_send(conn, "ib", expire, sizeof(response), response); if (e != NULL) return (e); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); if (error == GFARM_AUTH_ERROR_NO_ERROR) return (NULL); /* success */ } while (++try < GFARM_AUTH_RETRY_MAX && error == GFARM_AUTH_ERROR_EXPIRED); e = xxx_proto_send(conn, "i", GFARM_AUTH_SHAREDSECRET_GIVEUP); if (e != NULL) return (e); e = xxx_proto_recv(conn, 0, &eof, "i", &error_ignore); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); switch (error) { case GFARM_AUTH_ERROR_NOT_SUPPORTED: return (GFARM_ERR_PROTOCOL_NOT_SUPPORTED); case GFARM_AUTH_ERROR_EXPIRED: return (GFARM_ERR_EXPIRED); default: return (GFARM_ERR_AUTHENTICATION); } } char * gfarm_auth_request(struct xxx_connection *conn, char *name, struct sockaddr *addr) { char *e, *e_save = NULL; int i, eof; gfarm_int32_t methods, server_methods; /* bitset */ gfarm_int32_t method; /* enum gfarm_auth_method */ gfarm_int32_t error; /* enum gfarm_auth_error */ size_t nmethods; unsigned char methods_buffer[GFARM_AUTH_METHODS_BUFFER_SIZE]; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); methods = gfarm_auth_method_get_enabled_by_name_addr(name, addr); if (methods == 0) return ("gfarm auth method isn't available for the host"); methods &= gfarm_auth_method_get_available(); if (methods == 0) return ("usable auth-method isn't configured"); e = xxx_proto_recv(conn, 0, &eof, "b", sizeof(methods_buffer), &nmethods, methods_buffer); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); server_methods = 0; for (i = 0; i < nmethods; i++) { if (methods_buffer[i] <= GFARM_AUTH_METHOD_NONE || methods_buffer[i] >= GFARM_AUTH_METHOD_NUMBER) continue; server_methods |= 1 << methods_buffer[i]; } for (i = 0;; i++) { method = gfarm_auth_trial_table[i].method; if (method != GFARM_AUTH_METHOD_NONE && (methods & server_methods & (1 << method)) == 0) continue; e = xxx_proto_send(conn, "i", method); if (e != NULL) return (e); e = xxx_proto_recv(conn, 1, &eof, "i", &error); if (e != NULL) return (e); if (eof || error != GFARM_AUTH_ERROR_NO_ERROR) return (GFARM_ERR_PROTOCOL); /* shouldn't happen */ if (method == GFARM_AUTH_METHOD_NONE) { /* give up */ if (server_methods == 0) return (GFARM_ERR_PERMISSION_DENIED); if ((methods & server_methods) == 0) return (GFARM_ERR_PROTOCOL_NOT_SUPPORTED); return (e_save != NULL ? e_save : "gfarm_auth_request: implementation error"); } e = (*gfarm_auth_trial_table[i].request)(conn); if (e == NULL) return (NULL); /* success */ if (e != GFARM_ERR_PROTOCOL_NOT_SUPPORTED && e != GFARM_ERR_EXPIRED && e != GFARM_ERR_AUTHENTICATION) { /* protocol error */ return (e); } e_save = e; } } <file_sep>/gfarm/tags/gfarm_1_0_3_rc2/makes/html.mk all: html-all post-all-hook install: html-install post-install-hook clean: html-clean post-clean-hook veryclean: html-veryclean post-very-clean-hook distclean: html-distclean post-distclean-hook gfregister: html-gfregister post-gfregister-hook man: html-man html: html-html post-all-hook: post-install-hook: post-clean-hook: post-very-clean-hook: post-distclean-hook: post-gfregister-hook: html-all: html-install: @for i in / $(HTML); do \ case $$i in /) continue;; esac; \ ( set -x; $(INSTALL_DATA) $(srcdir)/$${i} $(htmldir)/$${i} ); \ done @for i in / $(HTMLSRC); do \ case $$i in /) continue;; esac; \ ( set -x; $(INSTALL_DATA) $(srcdir)/$${i}.html $(htmldir)/$${i}.html ); \ done html-clean: -rm -f $(EXTRA_CLEAN_TARGETS) html-veryclean: clean -rm -f $(EXTRA_VERYCLEAN_TARGETS) html-distclean: veryclean if [ -f $(srcdir)/Makefile.in ]; then rm -f Makefile; fi html-gfregister: html-man: $(dstsubst): $(srcsubst) $(DOCBOOK2HTML) $(srcsubst) html-html: for i in / $(HTMLSRC); do \ case $$i in /) continue;; esac; \ $(MAKE) srcsubst=$(DOCBOOK_DIR)/$${i}.docbook \ dstsubst=$${i}.html $${i}.html; \ done <file_sep>/gfarm/tags/gfarm_1_0_4/package/solaris/build #!/bin/sh # /usr/local/bin must be before /bin, otherwise globus-makefile-header fails. PATH=/opt/SUNWspro/bin:/usr/ccs/bin:/usr/local/bin:/usr/bin:/bin:/usr/ucb export PATH version=1.0.4 subpkgs='client devel doc fsnode gfptool libs server gfront' prefix=usr/local/gfarm pkg_list='gfarm gfarm-gsi' cc_list='vendorcc gcc' # XXX gcc cannot link shared object. what's wrong? cc_list='vendorcc' srcdir=`pwd` work=$srcdir/.. buildrootbase=$work/buildroot-$$ make=/usr/local/bin/make tar=/usr/local/bin/tar with_prefix=--prefix=/$prefix with_globus=--with-globus=/opt/gt-2.4.3 with_globus="$with_globus --with-globus-static" # XXX --with-mpi needs OPTFLAGS=-O with gcc (an error happens at gfs_hook_mpi). # XXX currently, MPICH isn't installed on the build-host. # XXX tar warns missing `gfwc', because it isn't built without --with-mpi. with_mpi= # --with-mpi=/usr/local/mpich vendorcc_pkg=/home/soda/install/SunOS-5.9-SunONEStudio-8 with_vendorcc_openldap=--with-openldap=$vendorcc_pkg/openldap-2.1.30 with_vendorcc_openssl=--with-openssl=$vendorcc_pkg/openssl-0.9.7d with_vendorcc_globus_flavor= # --with-globus-flavor=vendorcc32 # not necessary gcc_pkg=/home/soda/install/SunOS-5.9-gcc-3.3.2 with_gcc_openldap=--with-openldap=$gcc_pkg/openldap-2.1.30 with_gcc_openssl=--with-openssl=$gcc_pkg/openssl-0.9.7d with_gcc_globus_flavor= # --with-globus-flavor=gcc32 # not necessary case `whoami` in root) ;; # OK *) echo "WARNING: root privilege is needed to invoke this script" >&2 # exit 1 ;; esac for pkg in $pkg_list do for cc in $cc_list do case ${pkg}-${cc} in gfarm-vendorcc) ./configure $with_prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl;; gfarm-gsi-vendorcc) ./configure $with_prefix \ $with_vendorcc_openldap \ $with_vendorcc_openssl \ $with_globus $with_vendorcc_globus_flavor;; gfarm-gcc) CC=gcc ./configure $with_prefix \ $with_gcc_openldap \ $with_gcc_openssl;; gfarm-gsi-gcc) CC=gcc ./configure $with_prefix \ $with_gcc_openldap \ $with_gcc_openssl \ $with_globus $with_gcc_globus_flavor;; esac $make buildroot=${buildrootbase}-${pkg}-${cc} rm -rf $buildroot mkdir -p $buildroot $buildroot/$prefix $buildroot/etc $make prefix=$buildroot/$prefix install mkdir -p $buildroot/etc/rc3.d cp package/solaris/gfmd $buildroot/etc/rc3.d/S98gfmd cp package/solaris/gfsd $buildroot/etc/rc3.d/S99gfsd ln $buildroot/etc/rc3.d/S98gfmd $buildroot/etc/rc3.d/K98gfmd ln $buildroot/etc/rc3.d/S99gfsd $buildroot/etc/rc3.d/K97gfsd chmod +x $buildroot/etc/rc3.d/* cp doc/conf/gfarm.conf $buildroot/etc/gfarm.conf.sample mkdir -p $buildroot/etc/gfarm-ldap cp doc/conf/gfarm.schema $buildroot/etc/gfarm-ldap/ $make distclean ( cd $buildroot && for s in $subpkgs do eval \ $tar zcf $work/${pkg}-${s}-${cc}-${version}.tar.gz \ `sed "s:@PREFIX@:$prefix:" \ $srcdir/package/solaris/gfarm-${s}.files` done ) # rm -rf $buildroot done done # $Id$ <file_sep>/gfarm_mpiio/tags/gfarm_mpiio_0_0_1/ad_gfarm/ad_gfarm_read.c /* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * Copyright (C) 2001 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "ad_gfarm.h" #include "adioi.h" #include "adio_extern.h" void ADIOI_GFARM_ReadContig(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { int myrank, nprocs, datatype_size, err=1; ADIO_Offset len; *error_code = MPI_SUCCESS; gfarm_off_t result; int g_np; ADIOI_GFARM_headerInf *ghi; double st_time, fn_time; static char myname[] = "ADIOI_GFARM_READCONTIG"; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); MPI_Type_size(datatype, &datatype_size); #ifdef GFARM_DEBUG_READ FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_ReadContig called on %s\n", myrank, nprocs, fd->filename); #endif MPI_Type_size(datatype, &datatype_size); len = (ADIO_Offset)datatype_size * (ADIO_Offset)count; ADIOI_Assert(len == (unsigned int) len); /* read takes an unsigned int parm */ if (file_ptr_type == ADIO_INDIVIDUAL) { offset = fd->fp_ind; } ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); if(ghi->gfarm_view_flag != 1 && ghi->gfarm_view_flag != 2){ if (fd->fp_sys_posn != offset) { err = lseek(fd->fd_sys, offset, SEEK_SET); /* --BEGIN ERROR HANDLING-- */ if (err == -1) { *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, myname, __LINE__, MPI_ERR_IO, "**io", "**io %s", strerror(errno)); fd->fp_sys_posn = -1; return; } } }else{ gfs_pio_seek(ghi->gfp[ghi->gfp_index], (gfarm_off_t)offset, GFARM_SEEK_SET, &result); #ifdef GFARM_DEBUG_READ printf("[%d/%d] gfs_pio_seek:gfp=%d\n", myrank, nprocs, ghi->gfp[ghi->gfp_index]); printf("[%d/%d] read_contig seek result=%d\n", myrank, nprocs,result); #endif } /* --END ERROR HANDLING-- */ if(ghi->gfarm_view_flag != 1 && ghi->gfarm_view_flag != 2){ err = read(fd->fd_sys, buf, (unsigned int)len); }else{ st_time = MPI_Wtime(); err = gfs_pio_read(ghi->gfp[ghi->gfp_index], buf, (int)len, &g_np); fn_time = MPI_Wtime(); ghi->data_size[ghi->gfp_index] += g_np; ghi->access_time += fn_time -st_time; #ifdef GFARM_DEBUG_READ printf("[%d/%d] read_contig read err=%d, g_np=%d\n", myrank, nprocs,err,g_np); printf("[%d/%d] read len=%d\n", myrank, nprocs, len); #endif } fd->fp_sys_posn = offset + g_np; if (file_ptr_type == ADIO_INDIVIDUAL) { fd->fp_ind += g_np; } if(err == -1){ printf("read error!\n"); } /* if (file_ptr_type != ADIO_EXPLICIT_OFFSET) { offset = fd->fp_ind; fd->fp_ind += datatype_size * count; fd->fp_sys_posn = fd->fp_ind; #if 0 FPRINTF(stdout, "[%d/%d] new file position is %lld\n", myrank, nprocs, (long long) fd->fp_ind); #endif } else { fd->fp_sys_posn = offset + datatype_size * count; } */ #ifdef GFARM_DEBUG_READ FPRINTF(stdout, "[%d/%d] err=%ld\n",myrank, nprocs, err); FPRINTF(stdout, "[%d/%d] reading (buf = %p, loc = %lld, sz = %lld)\n", myrank, nprocs, buf, (long long) offset, (long long) datatype_size * count); #endif #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, datatype, datatype_size * count); #endif } void ADIOI_GFARM_ReadStrided(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { int myrank, nprocs; ADIOI_GFARM_headerInf *ghi; double st_time, fn_time; *error_code = MPI_SUCCESS; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); #ifdef GFARM_DEBUG_READ FPRINTF(stdout, "[%d/%d] ADIOI_GFARM_ReadStrided called on %s\n", myrank, nprocs, fd->filename); FPRINTF(stdout, "[%d/%d] calling ADIOI_GEN_ReadStrided\n", myrank, nprocs); #endif ghi = (ADIOI_GFARM_headerInf *)(fd->fs_ptr); st_time = MPI_Wtime(); ADIOI_GFARM_ReadStrided_naive(fd, buf, count, datatype, file_ptr_type, offset, status, error_code); fn_time = MPI_Wtime(); ghi->all_time += (fn_time - st_time); } void ADIOI_GFARM_ReadStrided_naive(ADIO_File fd, void *buf, int count, MPI_Datatype buftype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int *error_code) { /* offset is in units of etype relative to the filetype. */ ADIOI_Flatlist_node *flat_buf, *flat_file; ADIO_Offset size, brd_size, frd_size=0, req_len, sum; int b_index; int n_etypes_in_filetype; ADIO_Offset n_filetypes, etype_in_filetype; ADIO_Offset abs_off_in_filetype=0; unsigned bufsize, filetype_size, buftype_size, size_in_filetype; int etype_size; MPI_Aint filetype_extent, buftype_extent; int buf_count, buftype_is_contig, filetype_is_contig; ADIO_Offset userbuf_off; ADIO_Offset off, req_off, disp, end_offset=0, start_off; ADIO_Status status1; *error_code = MPI_SUCCESS; /* changed below if error */ ADIOI_Datatype_iscontig(buftype, &buftype_is_contig); ADIOI_Datatype_iscontig(fd->filetype, &filetype_is_contig); MPI_Type_size(fd->filetype, (int*)&filetype_size); if ( ! filetype_size ) { *error_code = MPI_SUCCESS; return; } MPI_Type_extent(fd->filetype, &filetype_extent); MPI_Type_size(buftype,(int*) &buftype_size); MPI_Type_extent(buftype, &buftype_extent); etype_size = fd->etype_size; ADIOI_Assert((buftype_size * count) == ((ADIO_Offset)buftype_size * (ADIO_Offset)count)); bufsize = buftype_size * count; /* contiguous in buftype and filetype is handled elsewhere */ if (!buftype_is_contig && filetype_is_contig) { }else { /* noncontiguous in file */ int f_index, st_index = 0; ADIO_Offset st_n_filetypes; ADIO_Offset st_frd_size; int flag; /* First we're going to calculate a set of values for use in all * the noncontiguous in file cases: * start_off - starting byte position of data in file * end_offset - last byte offset to be acessed in the file * st_n_filetypes - how far into the file we start in terms of * whole filetypes * st_index - index of block in first filetype that we will be * starting in (?) * st_frd_size - size of the data in the first filetype block * that we will read (accounts for being part-way * into reading this block of the filetype * */ /* filetype already flattened in ADIO_Open */ flat_file = ADIOI_Flatlist; while (flat_file->type != fd->filetype) flat_file = flat_file->next; disp = fd->disp; if (file_ptr_type == ADIO_INDIVIDUAL) { start_off = fd->fp_ind; /* in bytes */ n_filetypes = -1; flag = 0; while (!flag) { n_filetypes++; for (f_index=0; f_index < flat_file->count; f_index++) { if (disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent + flat_file->blocklens[f_index] >= start_off) { /* this block contains our starting position */ st_index = f_index; frd_size = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent + flat_file->blocklens[f_index] - start_off; flag = 1; break; } } } } else { n_etypes_in_filetype = filetype_size/etype_size; n_filetypes = offset / n_etypes_in_filetype; etype_in_filetype = (int) (offset % n_etypes_in_filetype); size_in_filetype = (unsigned)etype_in_filetype * (unsigned)etype_size; sum = 0; for (f_index=0; f_index < flat_file->count; f_index++) { sum += flat_file->blocklens[f_index]; if (sum > size_in_filetype) { st_index = f_index; frd_size = sum - size_in_filetype; abs_off_in_filetype = flat_file->indices[f_index] + size_in_filetype - (sum - flat_file->blocklens[f_index]); break; } } /* abs. offset in bytes in the file */ start_off = disp + n_filetypes*(ADIO_Offset)filetype_extent + abs_off_in_filetype; } st_frd_size = frd_size; st_n_filetypes = n_filetypes; /* start_off, st_n_filetypes, st_index, and st_frd_size are * all calculated at this point */ /* Calculate end_offset, the last byte-offset that will be accessed. * e.g., if start_off=0 and 100 bytes to be read, end_offset=99 */ userbuf_off = 0; f_index = st_index; off = start_off; frd_size = ADIOI_MIN(st_frd_size, bufsize); while (userbuf_off < bufsize) { userbuf_off += frd_size; end_offset = off + frd_size - 1; if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; frd_size = ADIOI_MIN(flat_file->blocklens[f_index], bufsize-(unsigned)userbuf_off); } /* End of calculations. At this point the following values have * been calculated and are ready for use: * - start_off * - end_offset * - st_n_filetypes * - st_index * - st_frd_size */ /* if atomicity is true, lock (exclusive) the region to be accessed */ if ((fd->atomicity) && ADIO_Feature(fd, ADIO_LOCKS)) { ADIOI_WRITE_LOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } if (buftype_is_contig && !filetype_is_contig) { /* contiguous in memory, noncontiguous in file. should be the * most common case. */ userbuf_off = 0; f_index = st_index; off = start_off; n_filetypes = st_n_filetypes; frd_size = ADIOI_MIN(st_frd_size, bufsize); /* while there is still space in the buffer, read more data */ while (userbuf_off < bufsize) { if (frd_size) { /* TYPE_UB and TYPE_LB can result in frd_size = 0. save system call in such cases */ req_off = off; req_len = frd_size; ADIOI_Assert((((ADIO_Offset)(MPIR_Upint)buf) + userbuf_off) == (ADIO_Offset)(MPIR_Upint)((MPIR_Upint)buf + userbuf_off)); ADIOI_Assert(req_len == (int) req_len); ADIOI_GFARM_read_gfarm(fd, (char *) buf + userbuf_off, req_len, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, -1, error_code); if (*error_code != MPI_SUCCESS) return; } userbuf_off += frd_size; if (off + frd_size < disp + flat_file->indices[f_index] + flat_file->blocklens[f_index] + n_filetypes*(ADIO_Offset)filetype_extent) { /* important that this value be correct, as it is * used to set the offset in the fd near the end of * this function. */ off += frd_size; } /* did not reach end of contiguous block in filetype. * no more I/O needed. off is incremented by frd_size. */ else { if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; frd_size = ADIOI_MIN(flat_file->blocklens[f_index], bufsize-(unsigned)userbuf_off); } } } else { ADIO_Offset i_offset, tmp_bufsize = 0; /* noncontiguous in memory as well as in file */ ADIOI_Flatten_datatype(buftype); flat_buf = ADIOI_Flatlist; while (flat_buf->type != buftype) flat_buf = flat_buf->next; b_index = buf_count = 0; i_offset = flat_buf->indices[0]; f_index = st_index; off = start_off; n_filetypes = st_n_filetypes; frd_size = st_frd_size; brd_size = flat_buf->blocklens[0]; /* while we haven't read size * count bytes, keep going */ while (tmp_bufsize < bufsize) { ADIO_Offset new_brd_size = brd_size, new_frd_size = frd_size; size = ADIOI_MIN(frd_size, brd_size); if (size) { req_off = off; req_len = size; userbuf_off = i_offset; ADIOI_Assert((((ADIO_Offset)(MPIR_Upint)buf) + userbuf_off) == (ADIO_Offset)(MPIR_Upint)((MPIR_Upint)buf + userbuf_off)); ADIOI_Assert(req_len == (int) req_len); ADIOI_GFARM_read_gfarm(fd, (char *) buf + userbuf_off, req_len, MPI_BYTE, ADIO_EXPLICIT_OFFSET, req_off, &status1, -1, error_code); if (*error_code != MPI_SUCCESS) return; } if (size == frd_size) { /* reached end of contiguous block in file */ if (f_index < (flat_file->count - 1)) f_index++; else { f_index = 0; n_filetypes++; } off = disp + flat_file->indices[f_index] + n_filetypes*(ADIO_Offset)filetype_extent; new_frd_size = flat_file->blocklens[f_index]; if (size != brd_size) { i_offset += size; new_brd_size -= size; } } if (size == brd_size) { /* reached end of contiguous block in memory */ b_index = (b_index + 1)%flat_buf->count; buf_count++; i_offset = buftype_extent*(buf_count/flat_buf->count) + flat_buf->indices[b_index]; new_brd_size = flat_buf->blocklens[b_index]; if (size != frd_size) { off += size; new_frd_size -= size; } } tmp_bufsize += size; frd_size = new_frd_size; brd_size = new_brd_size; } } /* unlock the file region if we locked it */ if ((fd->atomicity) && (fd->file_system != ADIO_PIOFS) && (fd->file_system != ADIO_PVFS) && (fd->file_system != ADIO_PVFS2)) { ADIOI_UNLOCK(fd, start_off, SEEK_SET, end_offset-start_off+1); } if (file_ptr_type == ADIO_INDIVIDUAL) fd->fp_ind = off; } /* end of (else noncontiguous in file) */ fd->fp_sys_posn = -1; /* mark it as invalid. */ #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, buftype, bufsize); /* This is a temporary way of filling in status. The right way is to * keep track of how much data was actually read and placed in buf */ #endif if (!buftype_is_contig) ADIOI_Delete_flattened(buftype); } /*---------------------------------------*/ // // // // // /*---------------------------------------*/ void ADIOI_GFARM_read_gfarm(ADIO_File fd, void *buf, int count, MPI_Datatype datatype, int file_ptr_type, ADIO_Offset offset, ADIO_Status *status, int index, int *error_code) { ADIOI_Flatlist_node *flat_file; ADIO_Offset blocklen_sum, gfarm_offset; unsigned filetype_size; MPI_Aint filetype_extent; int i, j, nprocs, myrank; int filetype_count; ADIO_Offset **blocklens, **indices; ADIO_Offset tmp_offset; char tmpfilename[256]; void *tmp_buf; int gfarm_count; ADIOI_GFARM_headerInf *ghi; GFS_File gfp; gfarm_error_t gerr; ghi = (ADIOI_GFARM_headerInf *)fd->fs_ptr; tmp_buf = buf; MPI_Comm_size(fd->comm, &nprocs); MPI_Comm_rank(fd->comm, &myrank); if(index == -1){ index = ghi->gfp_num; }else{ if(index >= ghi->nprocs){ index = 0; } } if(ghi->gfarm_view_flag == 2){ ADIOI_GFARM_ReadContig(fd, buf, count, datatype, file_ptr_type, offset, status, error_code); return; } /* printf("[%d/%d] blocklen\n", myrank, nprocs); for(i=0;i<Gfarm_headerlist->count[myrank];i++){ printf("%d, ", Gfarm_headerlist->blocklens[myrank][i]); } printf("\n[%d/%d] indices\n", myrank, nprocs, count); for(i=0;i<Gfarm_headerlist->count[myrank];i++){ printf("%d, ", Gfarm_headerlist->indices[myrank][i]); } printf("\n"); */ filetype_count = offset/(ghi->filetype_extent[index]); tmp_offset = offset - (filetype_count * (ghi->filetype_extent[index])); //printf("[%d/%d] filetype extent = %d \n", myrank, nprocs, Gfarm_headerlist->filetype_extent); //printf("[%d/%d] buf size = %d \n", myrank, nprocs, count); for(i=0;i<ghi->count[index];i++){ #ifdef GFARM_DEBUG_READ printf("[%d/%d] check offset.\n", myrank, nprocs); printf("[%d/%d] %d %d, %d, %d\n", myrank, nprocs, index, ghi->blocklens[index][i], ghi->indices[index][i], tmp_offset); #endif if(ghi->blocklens[index][i] == 0) continue; //自分のローカルファイルにあるかどうか if(ghi->indices[index][i] <= tmp_offset && ghi->blocklens[index][i] + ghi->indices[index][i] > tmp_offset){ //他のファイルとまたぐ場合 if(tmp_offset+count > ghi->indices[index][i] + ghi->blocklens[index][i]){ //printf("[%d/%d] 他のファイルとまたぐ offset = %d \n", myrank, nprocs, offset); if(ghi->gfp_flag[index] == 0){ //sprintf(tmpfilename, "./%s_g/%d", ghi->filename, index); sprintf(tmpfilename, "./%s_g/%d", fd->filename, index); #ifdef GFARM_DEBUG_READ printf("[%d/%d] new file open.name = %s\n", myrank, nprocs, tmpfilename); #endif if((gerr = gfs_pio_open(tmpfilename, GFARM_FILE_RDWR, &gfp)) != 0){ printf("%d\n", gerr); } ghi->gfp[index] = gfp; ghi->gfp_flag[index] = 1; ghi->gfp_index = index; }else{ ghi->gfp_index = index; } blocklen_sum = 0; for(j=0;j<i;j++){ blocklen_sum += ghi->blocklens[index][j]; } gfarm_offset = ghi->filetype_size[index] * filetype_count + (blocklen_sum + tmp_offset - ghi->indices[index][i]); gfarm_count = count - (tmp_offset + count -(ghi->indices[index][i] + ghi->blocklens[index][i])); #ifdef GFARM_DEBUG_READ printf("[%d/%d] local and remote.\n", myrank, nprocs); printf("[%d/%d] %d, %d, %d, %d, %d\n", myrank, nprocs, ghi->filetype_size[index], filetype_count, blocklen_sum, tmp_offset, ghi->indices[index][i]); printf("[%d/%d] offset -> gfarm_offset = %d ->%d \n", myrank, nprocs, offset, gfarm_offset); #endif ADIOI_GFARM_ReadContig(fd, tmp_buf, gfarm_count, datatype, file_ptr_type, gfarm_offset, status, error_code); // ADIOI_GFARM_read_gfarm(fd, tmp_buf+gfarm_count, (count-gfarm_count), datatype, file_ptr_type, offset+gfarm_count, status, (index+1), error_code); return; //ローカルファイルのみでいい場合 }else{ if(ghi->gfp_flag[index] == 0){ sprintf(tmpfilename, "./%s_g/%d", fd->filename, index); #ifdef GFARM_DEBUG_READ printf("[%d/%d] new file open.name = %s\n", myrank, nprocs, tmpfilename); #endif if((gerr = gfs_pio_open(tmpfilename, GFARM_FILE_RDWR, &gfp)) != 0){ printf("%d\n", gerr); } ghi->gfp[index] = gfp; ghi->gfp_flag[index] = 1; ghi->gfp_index = index; }else{ ghi->gfp_index = index; } blocklen_sum = 0; for(j=0;j<i;j++){ blocklen_sum += ghi->blocklens[index][j]; } gfarm_offset = ghi->filetype_size[index] * filetype_count + (blocklen_sum + tmp_offset - ghi->indices[index][i]); #ifdef GFARM_DEBUG_READ printf("[%d/%d] local only.\n", myrank, nprocs); printf("[%d/%d] offset -> gfarm_offset = %d ->%d \n", myrank, nprocs, offset, gfarm_offset); #endif ADIOI_GFARM_ReadContig(fd, tmp_buf, count, datatype, file_ptr_type, gfarm_offset, status, error_code); return; } } } //自分のローカルファイルにない #ifdef GFARM_DEBUG_READ printf("[%d/%d] not local.\n", myrank, nprocs); printf("[%d/%d] offset -> tmp_offset = %d -> %d\n", myrank, nprocs, offset, tmp_offset); #endif ADIOI_GFARM_read_gfarm(fd, tmp_buf, count, datatype, file_ptr_type, offset, status, (index+1), error_code); return; } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfsl/gfarm_gsi.h #ifndef _GFARM_GSI_H_ #define _GFARM_GSI_H_ /* only available on GFARM_GSS_EXPORT_CRED_ENABLED case */ typedef struct gfarmExportedCredential gfarmExportedCredential; /* * Prototype */ extern char * gfarmGssGetCredentialName(gss_cred_id_t cred); extern char ** gfarmGssCrackMajorStatus(OM_uint32 majStat); extern char ** gfarmGssCrackMinorStatus(OM_uint32 minStat); extern void gfarmGssFreeCrackedStatus(char **strPtr); extern void gfarmGssPrintMajorStatus(OM_uint32 majStat); extern void gfarmGssPrintMinorStatus(OM_uint32 minStat); extern int gfarmGssSendToken(int fd, gss_buffer_t gsBuf); extern int gfarmGssReceiveToken(int fd, gss_buffer_t gsBuf); extern int gfarmGssAcquireCredential(gss_cred_id_t *credPtr, char *desiredNameString, gss_OID desiredNameType, gss_cred_usage_t credUsage, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr, char **credNamePtr); extern int gfarmGssReleaseCredential(gss_cred_id_t cred, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern int gfarmGssAcceptSecurityContext(int fd, gss_cred_id_t cred, gss_ctx_id_t *scPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr, char **remoteNamePtr, char **exportedNamePtr, gss_cred_id_t *remoteCredPtr); extern int gfarmGssInitiateSecurityContext(int fd, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, OM_uint32 reqFlag, gss_ctx_id_t *scPtr, OM_uint32 *majStatPtr, OM_uint32 *minSstatPtr, char **remoteNamePtr); extern void gfarmGssDeleteSecurityContext(gss_ctx_id_t *scPtr); extern int gfarmGssConfigureMessageSize(gss_ctx_id_t sCtx, int doEncrypt, gss_qop_t qopReq, unsigned int reqOutSz, unsigned int *maxInSzPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern int gfarmGssSend(int fd, gss_ctx_id_t sCtx, int doEncrypt, gss_qop_t qopReq, gfarm_int8_t *buf, int n, int chunkSz, OM_uint32 *statPtr); extern int gfarmGssReceive(int fd, gss_ctx_id_t sCtx, gfarm_int8_t **bufPtr, int *lenPtr, OM_uint32 *statPtr); /* multiplexed version */ struct gfarm_eventqueue; struct gfarmGssInitiateSecurityContextState; extern struct gfarmGssInitiateSecurityContextState *gfarmGssInitiateSecurityContextRequest(struct gfarm_eventqueue *q, int fd, char *acceptorNameString, gss_OID acceptorNameType, gss_cred_id_t cred, OM_uint32 reqFlag, void (*continuation)(void *), void *closure, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr); extern int gfarmGssInitiateSecurityContextResult( struct gfarmGssInitiateSecurityContextState *state, gss_ctx_id_t *scPtr, OM_uint32 *majStatPtr, OM_uint32 *minStatPtr, char **remoteNamePtr); /* only available on GFARM_GSS_EXPORT_CRED_ENABLED case */ extern gfarmExportedCredential * gfarmGssExportCredential(gss_cred_id_t cred, OM_uint32 *statPtr); extern char * gfarmGssEnvForExportedCredential(gfarmExportedCredential *exportedCred); extern void gfarmGssDeleteExportedCredential(gfarmExportedCredential *exportedCred); #endif /* _GFARM_GSI_H_ */ <file_sep>/gfarm/tags/gfarm_1_0_2/lib/libgfarm/gfarm/iobuffer.c #include <stdlib.h> #include <string.h> #include "iobuffer.h" /* XXX - This implementation is somewhat slow, but probably acceptable */ struct gfarm_iobuffer { char *buffer; int bufsize; int head, tail; int (*read_func)(struct gfarm_iobuffer *, void *, int, void *, int); void *read_cookie; int read_fd; /* for file descriptor i/o */ int (*write_func)(struct gfarm_iobuffer *, void *, int, void *, int); void *write_cookie; int write_fd; /* for file descriptor i/o */ void (*write_close_func)(struct gfarm_iobuffer *, void *, int); int read_eof; /* eof is detected on read side */ int write_eof; /* eof reached on write side */ char *error; }; struct gfarm_iobuffer * gfarm_iobuffer_alloc(int bufsize) { struct gfarm_iobuffer *b = malloc(sizeof(struct gfarm_iobuffer)); if (b == NULL) return (NULL); b->buffer = malloc(bufsize); if (b->buffer == NULL) { free(b); return (NULL); } b->bufsize = bufsize; b->head = b->tail = 0; b->read_func = NULL; b->read_cookie = NULL; b->read_fd = -1; b->write_func = NULL; b->write_cookie = NULL; b->write_fd = -1; b->write_close_func = gfarm_iobuffer_write_close_nop; b->read_eof = 0; b->write_eof = 0; b->error = NULL; return (b); } void gfarm_iobuffer_free(struct gfarm_iobuffer *b) { free(b->buffer); free(b); } void gfarm_iobuffer_set_error(struct gfarm_iobuffer *b, char *error) { b->error = error; } char * gfarm_iobuffer_get_error(struct gfarm_iobuffer *b) { return (b->error); } void gfarm_iobuffer_set_read(struct gfarm_iobuffer *b, int (*rf)(struct gfarm_iobuffer *, void *, int, void *, int), void *cookie, int fd) { b->read_func = rf; b->read_cookie = cookie; b->read_fd = fd; } void * gfarm_iobuffer_get_read_cookie(struct gfarm_iobuffer *b) { return (b->read_cookie); } int gfarm_iobuffer_get_read_fd(struct gfarm_iobuffer *b) { return (b->read_fd); } void gfarm_iobuffer_set_write_close(struct gfarm_iobuffer *b, void (*wcf)(struct gfarm_iobuffer *, void *, int)) { b->write_close_func = wcf; } void gfarm_iobuffer_set_write(struct gfarm_iobuffer *b, int (*wf)(struct gfarm_iobuffer *, void *, int, void *, int), void *cookie, int fd) { b->write_func = wf; b->write_cookie = cookie; b->write_fd = fd; } void * gfarm_iobuffer_get_write_cookie(struct gfarm_iobuffer *b) { return (b->write_cookie); } int gfarm_iobuffer_get_write_fd(struct gfarm_iobuffer *b) { return (b->write_fd); } /* * gfarm_iobuffer_empty(b) is a synonym of: * gfarm_iobuffer_avail_length(b) == 0 */ #define IOBUFFER_IS_EMPTY(b) ((b)->head >= (b)->tail) int gfarm_iobuffer_empty(struct gfarm_iobuffer *b) { return (IOBUFFER_IS_EMPTY(b)); } #define IOBUFFER_IS_FULL(b) ((b)->head <= 0 && (b)->tail >= (b)->bufsize) int gfarm_iobuffer_full(struct gfarm_iobuffer *b) { return (IOBUFFER_IS_FULL(b)); } #define IOBUFFER_AVAIL_LENGTH(b) ((b)->tail - (b)->head) int gfarm_iobuffer_avail_length(struct gfarm_iobuffer *b) { return (IOBUFFER_AVAIL_LENGTH(b)); } void gfarm_iobuffer_set_read_eof(struct gfarm_iobuffer *b) { b->read_eof = 1; } void gfarm_iobuffer_clear_read_eof(struct gfarm_iobuffer *b) { b->read_eof = 0; } int gfarm_iobuffer_is_read_eof(struct gfarm_iobuffer *b) { return (b->read_eof); } void gfarm_iobuffer_clear_write_eof(struct gfarm_iobuffer *b) { b->write_eof = 0; } int gfarm_iobuffer_is_write_eof(struct gfarm_iobuffer *b) { return (b->write_eof); } int gfarm_iobuffer_is_readable(struct gfarm_iobuffer *b) { return (!IOBUFFER_IS_FULL(b) && !b->read_eof); } int gfarm_iobuffer_is_writable(struct gfarm_iobuffer *b) { return (!IOBUFFER_IS_EMPTY(b) || (b->read_eof && !b->write_eof)); } /* * gfarm_iobuffer_is_eof(b) is a synonym of: * gfarm_iobuffer_empty(b) && gfarm_iobuffer_is_read_eof(b) */ int gfarm_iobuffer_is_eof(struct gfarm_iobuffer *b) { /* * note that gfarm_iobuffer_is_writable(b) may be TRUE here, * if gfarm_iobuffer_is_write_eof(b) is not TRUE yet. */ return (IOBUFFER_IS_EMPTY(b) && b->read_eof); } void gfarm_iobuffer_read(struct gfarm_iobuffer *b, int *residualp) { int space, rv; if (IOBUFFER_IS_FULL(b)) return; space = b->head + (b->bufsize - b->tail); if (residualp == NULL) /* unlimited */ residualp = &space; if (*residualp <= 0) return; if (*residualp > b->bufsize - b->tail && b->head > 0) { memmove(b->buffer, b->buffer + b->head, IOBUFFER_AVAIL_LENGTH(b)); b->tail -= b->head; b->head = 0; } rv = (*b->read_func)(b, b->read_cookie, b->read_fd, b->buffer + b->tail, *residualp < space ? *residualp : space); if (rv == 0) { b->read_eof = 1; } else if (rv > 0) { b->tail += rv; *residualp -= rv; } return; } int gfarm_iobuffer_put(struct gfarm_iobuffer *b, void *data, int len) { int space, iolen; if (len <= 0) return (0); if (IOBUFFER_IS_FULL(b)) return (0); space = b->head + (b->bufsize - b->tail); if (len > b->bufsize - b->tail && b->head > 0) { memmove(b->buffer, b->buffer + b->head, IOBUFFER_AVAIL_LENGTH(b)); b->tail -= b->head; b->head = 0; } iolen = len < space ? len : space; memcpy(b->buffer + b->tail, data, iolen); b->tail += iolen; return (iolen); } static void gfarm_iobuffer_write_close(struct gfarm_iobuffer *b) { (*b->write_close_func)(b, b->write_cookie, b->write_fd); b->write_eof = 1; } void gfarm_iobuffer_write(struct gfarm_iobuffer *b, int *residualp) { int avail, rv; if (IOBUFFER_IS_EMPTY(b)) { if (b->read_eof) gfarm_iobuffer_write_close(b); return; } avail = IOBUFFER_AVAIL_LENGTH(b); if (residualp == NULL) /* unlimited */ residualp = &avail; if (*residualp <= 0) return; rv = (*b->write_func)(b, b->write_cookie, b->write_fd, b->buffer + b->head, *residualp < avail ? *residualp : avail); if (rv > 0) { b->head += rv; *residualp -= rv; if (IOBUFFER_IS_EMPTY(b)) { b->head = b->tail = 0; /* * We don't do the following here: * if (b->read_eof) * gfarm_iobuffer_write_close(b); * To make sure to produce the following condition * at the EOF: * gfarm_iobuffer_is_writable(b) && * gfarm_iobuffer_empty(b) * i.e. * gfarm_iobuffer_is_eof(b) && * !gfarm_iobuffer_is_write_eof(b) */ } } return; } int gfarm_iobuffer_purge(struct gfarm_iobuffer *b, int *residualp) { int avail, purgelen; if (IOBUFFER_IS_EMPTY(b)) { if (b->read_eof) gfarm_iobuffer_write_close(b); return (0); } avail = IOBUFFER_AVAIL_LENGTH(b); if (residualp == NULL) /* unlimited */ residualp = &avail; if (*residualp <= 0) return (0); purgelen = *residualp < avail ? *residualp : avail; b->head += purgelen; *residualp -= purgelen; if (IOBUFFER_IS_EMPTY(b)) { b->head = b->tail = 0; /* * We don't do the following here: * if (b->read_eof) * gfarm_iobuffer_write_close(b); * To make sure to produce the following condition * at the EOF: * gfarm_iobuffer_is_writable(b) && * gfarm_iobuffer_empty(b) * i.e. * gfarm_iobuffer_is_eof(b) && * !gfarm_iobuffer_is_write_eof(b) */ } return (purgelen); } int gfarm_iobuffer_get(struct gfarm_iobuffer *b, void *data, int len) { int avail, iolen; if (IOBUFFER_IS_EMPTY(b)) { if (b->read_eof) gfarm_iobuffer_write_close(b); return (0); } if (len <= 0) return (0); avail = IOBUFFER_AVAIL_LENGTH(b); iolen = len < avail ? len : avail; memcpy(data, b->buffer + b->head, iolen); b->head += iolen; if (IOBUFFER_IS_EMPTY(b)) { b->head = b->tail = 0; /* * We don't do the following here: * if (b->read_eof) * gfarm_iobuffer_write_close(b); * To make sure to produce the following condition * at the EOF: * gfarm_iobuffer_is_writable(b) && * gfarm_iobuffer_empty(b) * i.e. * gfarm_iobuffer_is_eof(b) && * !gfarm_iobuffer_is_write_eof(b) */ } return (iolen); } void gfarm_iobuffer_flush_write(struct gfarm_iobuffer *b) { while (!IOBUFFER_IS_EMPTY(b) && b->error == NULL) gfarm_iobuffer_write(b, NULL); } int gfarm_iobuffer_put_write(struct gfarm_iobuffer *b, void *data, int len) { char *p; int rv, residual; for (p = data, residual = len; residual > 0; residual -= rv, p += rv) { if (IOBUFFER_IS_FULL(b)) gfarm_iobuffer_write(b, NULL); rv = gfarm_iobuffer_put(b, p, residual); if (rv == 0) /* error */ break; } if (IOBUFFER_IS_FULL(b)) gfarm_iobuffer_write(b, NULL); return (len - residual); } int gfarm_iobuffer_purge_read_x(struct gfarm_iobuffer *b, int len, int just) { int rv, residual, tmp, *justp = just ? &tmp : NULL; for (residual = len; residual > 0; ) { if (IOBUFFER_IS_EMPTY(b)) { tmp = residual; gfarm_iobuffer_read(b, justp); } rv = gfarm_iobuffer_purge(b, &residual); if (rv == 0) /* EOF or error */ break; } return (len - residual); } int gfarm_iobuffer_get_read_x(struct gfarm_iobuffer *b, void *data, int len, int just) { char *p; int rv, residual, tmp, *justp = just ? &tmp : NULL; for (p = data, residual = len; residual > 0; residual -= rv, p += rv) { if (IOBUFFER_IS_EMPTY(b)) { tmp = residual; gfarm_iobuffer_read(b, justp); } rv = gfarm_iobuffer_get(b, p, residual); if (rv == 0) /* EOF or error */ break; } return (len - residual); } int gfarm_iobuffer_get_read_just(struct gfarm_iobuffer *b, void *data, int len) { return (gfarm_iobuffer_get_read_x(b, data, len, 1)); } int gfarm_iobuffer_get_read(struct gfarm_iobuffer *b, void *data, int len) { return (gfarm_iobuffer_get_read_x(b, data, len, 0)); } /* * gfarm_iobuffer_get_read*() wait until desired length of data is * received. * gfarm_iobuffer_get_read_partial*() don't wait like that, but return * the contents of current buffer or the result of (*b->read_func) * if current buffer is empty. */ int gfarm_iobuffer_get_read_partial_x(struct gfarm_iobuffer *b, void *data, int len, int just) { if (IOBUFFER_IS_EMPTY(b)) { int tmp = len; gfarm_iobuffer_read(b, just ? &tmp : NULL); } return (gfarm_iobuffer_get(b, data, len)); } int gfarm_iobuffer_get_read_partial_just(struct gfarm_iobuffer *b, void *data, int len) { return (gfarm_iobuffer_get_read_partial_x(b, data, len, 1)); } int gfarm_iobuffer_get_read_partial(struct gfarm_iobuffer *b, void *data, int len) { return (gfarm_iobuffer_get_read_partial_x(b, data, len, 0)); } /* * default operation for gfarm_iobuffer_set_write_close(): * do nothing at eof on writer side */ void gfarm_iobuffer_write_close_nop(struct gfarm_iobuffer *b, void *cookie, int fd) { /* nop */ } <file_sep>/gfarm/tags/gfarm_1_0_beta_1_rev_2/gftool/gfsched/gfsched.c /* * $Id$ */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <libgen.h> #include <sys/types.h> #include <gfarm/gfarm.h> /* * Create a hostfile. * * gfsched <gfarm_url> [<output_hostfile>] * gfsched -f <gfarm_file> [<output_hostfile>] */ char *program_name = "gfsched"; void usage() { fprintf(stderr, "usage: %s [options] gfarm_url [output_hostfile]\n", program_name); fprintf(stderr, "options:\n"); fprintf(stderr, "\t-I <fragment>\tschedules a node" " using the specified fragment.\n"); fflush(stderr); } int main(int argc, char * argv[]) { char *gfarm_url = NULL; char *section = NULL; char *e = NULL; FILE *outp = stdout; int errflg = 0; extern int optind; int nhosts; char **hosts; char *gfarm_file; char *host; int c, i; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((c = getopt(argc, argv, "I:?")) != EOF) { switch (c) { case 'I': section = optarg; break; case '?': default: ++errflg; } } if (errflg) { usage(); exit(2); } if (optind < argc) { gfarm_url = argv[optind]; } else { usage(); exit(2); } ++optind; if (optind < argc) { outp = fopen(argv[optind], "w"); if (outp == NULL) { perror(argv[optind]); exit(1); } } if (section == NULL) { /* file-affinity scheduling */ e = gfarm_url_hosts_schedule(gfarm_url, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } for (i = 0; i < nhosts; ++i) fprintf(outp, "%s\n", hosts[i]); } else { /* schedule a node using the specific file fragment. */ e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } e = gfarm_file_section_host_schedule(gfarm_file, section, &host); if (e != NULL) { fprintf(stderr, "%s: %s:%s: %s\n", program_name, gfarm_url, section, e); exit(1); } fprintf(outp, "%s\n", host); free(host); free(gfarm_file); } fclose(outp); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(0); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_gfarm_utils.inc GFSD_DEFAULT_PREFIX="/" GFSD_DEFAULT_HOSTNAME="`hostname -f`" GFSD_DEFAULT_PORT="600" if [ -f ./zbx_gfarm_local.inc ]; then . ./zbx_gfarm_local.inc fi parse_gfsd_conf () { arg="$1" # check format seps=`echo "$arg" | sed -s 's/[^:]//g'` argc=0 if [ "::" = "$seps" ]; then argc=3 fi if [ ":::" = "$seps" ]; then argc=4 fi if [ $argc -ne 3 -a $argc -ne 4 ]; then return 1 fi prefix=`echo $arg | cut -d':' -f 1` hostname=`echo $arg | cut -d':' -f 2` if [ $argc -eq 3 ]; then port=`echo $arg | cut -d':' -f 3` listen_address="" else listen_address=`echo $arg | cut -d':' -f 3` port=`echo $arg | cut -d':' -f 4` fi if [ -z "${prefix}" ]; then prefix="${GFSD_DEFAULT_PREFIX}" fi if [ -z "${hostname}" ]; then hostname="${GFSD_DEFAULT_HOSTNAME}" fi if [ -z "${port}" ]; then port="${GFSD_DEFAULT_PORT}" fi echo "${prefix} ${hostname} ${port} ${listen_address}" return 0 } iterate_over_separeted_list () { com=$1; shift 1 list=$1; shift 1 echo $list | sed 's/%/\n/g' |\ while read elm; do $com $elm $* || return 1 done return $? } # # sample: # >> parse_gfsd_confs '::=/usr/local/:gfsd2.gfarm.co.jp:10600' # / gfsd.gfarm.co.jp 600 0 # /usr/local/ gfsd2.gfarm.co.jp 10600 1 # parse_gfsd_confs () { iterate_over_separeted_list parse_gfsd_conf "$1" return $? } read_gfmd_conf () { prefix=$1 if [ -z "${prefix}" ]; then prefix="/" fi host="`sudo grep metadb_server_host ${prefix}/etc/gfmd.conf | awk '{print $2}'`" port="`sudo grep metadb_server_port ${prefix}/etc/gfmd.conf | awk '{print $2}'`" echo "${prefix} ${host} ${port}" return 0 } read_gfmd_confs () { iterate_over_separeted_list read_gfmd_conf "$1" return $? } read_gfarm_pgsql_conf () { prefix=$1 if [ -z "${prefix}" ]; then prefix="/" fi port="`sudo grep postgresql_server_port ${prefix}/etc/gfmd.conf | awk '{print $2}'`" db="`sudo grep postgresql_dbname ${prefix}/etc/gfmd.conf | awk '{print $2}'`" user="`sudo grep postgresql_user ${prefix}/etc/gfmd.conf | awk '{print $2}'`" pass="`sudo grep postgresql_password ${prefix}/etc/gfmd.conf | awk '{print $2}' | sed 's/^\"\(.*\)\"$/\1/g'`" echo "${prefix} ${port} ${db} ${user} ${pass}" return 0 } read_gfarm_pgsql_confs () { iterate_over_separeted_list read_gfarm_pgsql_conf "$1" return $? } average_or_error () { sum=0 c=0 while read val; do if [ -z "${val}" ]; then continue fi if [ "${val}" -lt 0 ]; then break fi sum=`expr $sum + $val` c=`expr $c + 1` done if [ "$c" -eq 0 ] || ( [ ! -z "${val}" ] && [ "${val}" -lt 0 ] ) ; then res="-1" else res=`expr $sum / $c` fi echo $res return 0 } psql_wrapper () { DB_HOST=$1; shift 1 DB_PORT=$1; shift 1 DB_NAME=$1; shift 1 DB_USER=$1; shift 1 DB_PASS=$1; shift 1 SQL="$*" PGPASSWORD=${DB_PASS} export PGPASSWORD result=`echo ${SQL} |\ psql -U ${DB_USER} -h ${DB_HOST} -p ${DB_PORT} ${DB_NAME} -t -w -f - ` ret=$? echo "$result" return $ret } gfarm_pgsql_exec () { confs=$1; shift 1 sql=$* read_gfarm_pgsql_confs $confs |\ while read prefix port db user pass; do psql_wrapper localhost "${port}" "${db}" "${user}" "${pass}" "${sql}" done return 0; } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_0/src/gfarm-zabbix_scripts/externalscripts/zbx_failover.sh #!/bin/sh # # @(#) zbx_failover.sh # # Usage: # zbx_failover.sh # # Description: # Failover script for metadata servers on a redundant Gfarm2 filesystem. # ############################################################################### # defines CONF_FILE=/etc/zabbix/externalscripts/zbx_chk_gfarm.conf FO_EXEC_USER=zabbix SYSLOG=/var/log/messages UPGRADE_CHK_STR="start transforming to the master gfmd" GFMD_STOP_COMMAND='sudo /etc/init.d/gfmd stop' GFJOURNAL_CHK_SCRIPT=/etc/zabbix/externalscripts/zbx_chk_gfjournal_gfmd.sh FO_EXEC_COMMAND='sudo /etc/zabbix/externalscripts/zbx_gfarm2_mds_upgrade.sh' FO_CHK_COMMAND='gfls -ld /' # debug DEBUG=false log_debug() { [ "X$DEBUG" != Xtrue ] && return logger -t "gfmd_failover" "DEBUG: $@" } stop_master_gfmd() { if [ X"$MASTER" != X ]; then # check the master was upgraded or not. _CHK_UPGRADE_RESULT_=`ssh $MASTER -l $FO_EXEC_USER tail -100 $SYSLOG | grep "$UPGRADE_CHK_STR" | tail -1` if [ $? -ne 0 ] || [ X"$_CHK_UPGRADE_RESULT_" != X ]; then log_debug "error: master gfmd was already upgraded." exit 1 fi # stop master gfmd _GFMD_STOP_RESULT_=`ssh $MASTER -l $FO_EXEC_USER $GFMD_STOP_COMMAND` if [ $? -ne 0 ] || [ X"$_GFMD_STOP_RESULT_" = X ]; then log_debug "error: can\'t stop master gfmd." exit 1 fi else log_debug "error: master metadata server not found." exit 1 fi } get_master_candidate_slaves() { _MAX_SEQNUM_FILE_="/var/tmp/seqnum.txt" _CANDIDATE_LIST_=`grep "^+ \+slave \+sync \+c \+" $MDS_LIST_PATH | awk '{ print $6 }'` echo -n > $_MAX_SEQNUM_FILE_ if [ ! -f $_MAX_SEQNUM_FILE_ ]; then log_debug "error: can\'t create a tmp file to search master candidate." exit 1; fi for _CANDIDATE_ in $_CANDIDATE_LIST_; do _MAX_SEQNUM_=`ssh $_CANDIDATE_ sudo $GFJOURNAL_CHK_SCRIPT` if [ $? -ne 0 ] || [ X"$_MAX_SEQNUM_" = X ]; then continue fi echo $_MAX_SEQNUM_ $_CANDIDATE_ >> $_MAX_SEQNUM_FILE_ done sort -nr $_MAX_SEQNUM_FILE_ | awk '{ print $2 };' return 0 } # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else log_debug "error: $CONF_FILE not found."; exit 0; fi # check the metadata server list cache exists. if [ ! -f $MDS_LIST_PATH ]; then log_debug "error: metadata server list cache doesn\'t exist." exit 1 fi # generate the list of candidate slave MDSs for upgrade. MASTER=`grep "^+ \+master \+- \+m \+" $MDS_LIST_PATH | awk '{ print $6 }'` if [ X"$MASTER" = X ]; then log_debug "error: no master metadata server found." exit 1 fi # generate the list of candidate slave MDSs for upgrade. SLAVE_LIST=`get_master_candidate_slaves` if [ X"$SLAVE_LIST" = X ]; then log_debug "error: no slave for upgrading." exit 1 fi # stop gfmd on the master MDS host. stop_master_gfmd # execute upgrade command on slave servers. for SLAVE in $SLAVE_LIST do # Upgrade a slave server. FO_EXEC_RESULT=`ssh $SLAVE -l $FO_EXEC_USER $FO_EXEC_COMMAND` if [ $? -ne 0 ] || [ X"$FO_EXEC_RESULT" = X ]; then continue fi # Check upgrading is success or not. FO_CHK_RESULT=`$FO_CHK_COMMAND` if [ $? -ne 0 ] || [ X"$FO_CHK_RESULT" = X ]; then continue fi # Failover Success and Exit. log_debug "success upgrading $SLAVE" exit 0 done log_debug "error: fail to upgrade all slave server." exit 1 <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_5/open_file.c /* * $Id$ */ #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <gfarm/gfarm.h> #include "gfarm2fs_msg_enums.h" #include "gfarm2fs.h" #include "hash.h" struct opening { struct opening *next; GFS_File gf; int writing; }; struct inode_openings { struct opening *openings; GFS_File gf_cached; }; static struct gfarm_hash_table *open_file_table; #define OPEN_FILE_TABLE_SIZE 256 static int open_file_hash(const void *k, int l) { gfarm_ino_t h = *(gfarm_ino_t *)k; int i = (int)h; return (i); } static int open_file_hash_equal( const void *k1, int k1len, const void *k2, int k2len) { gfarm_ino_t h1 = *(gfarm_ino_t *)k1, h2 = *(gfarm_ino_t *)k2; return (h1 == h2); } void gfarm2fs_open_file_init() { open_file_table = gfarm_hash_table_alloc( OPEN_FILE_TABLE_SIZE, open_file_hash, open_file_hash_equal); if (open_file_table == NULL) gflog_fatal(GFARM_MSG_2000051, "no memory"); } GFS_File gfarm2fs_open_file_lookup(gfarm_ino_t ino) { struct gfarm_hash_entry *entry; struct inode_openings *ios; struct opening *o; entry = gfarm_hash_lookup(open_file_table, &ino, sizeof(ino)); if (entry == NULL) return (NULL); ios = gfarm_hash_entry_data(entry); if (ios->gf_cached != NULL) return (ios->gf_cached); for (o = ios->openings; o != NULL; o = o->next) { if (o->writing) { ios->gf_cached = o->gf; return (ios->gf_cached); } } ios->gf_cached = ios->openings->gf; return (ios->gf_cached); } static int get_ino(GFS_File gf, gfarm_ino_t *ino) { struct gfs_stat st; gfarm_error_t e; e = gfs_pio_stat(gf, &st); if (e == GFARM_ERR_NO_ERROR) { *ino = st.st_ino; gfs_stat_free(&st); return (0); } return (-gfarm_error_to_errno(e)); } void gfarm2fs_open_file_enter(GFS_File gf, int flags) { gfarm_ino_t ino; struct gfarm_hash_entry *entry; struct inode_openings *ios; struct opening *o; int created; if (get_ino(gf, &ino) != 0) { gflog_debug(GFARM_MSG_2000052, "file %p does not exist", gf); return; } o = malloc(sizeof(*o)); if (o == NULL) { gflog_error(GFARM_MSG_2000053, "no memory to cache an opening for inode %lld", (unsigned long long)ino); return; } entry = gfarm_hash_enter(open_file_table, &ino, sizeof(ino), sizeof(*ios), &created); if (entry == NULL) { gflog_error(GFARM_MSG_2000054, "no memory to insert inode %lld to open file table", (unsigned long long)ino); return; } o->gf = gf; o->writing = ((flags & O_TRUNC) != 0 || (flags & O_ACCMODE) != O_RDONLY); ios = gfarm_hash_entry_data(entry); if (!created) { o->next = ios->openings; } else { o->next = NULL; ios->gf_cached = NULL; } ios->openings = o; if (o->writing) ios->gf_cached = gf; } static int open_file_remove_opening(struct inode_openings *ios, GFS_File gf) { struct opening *o, **prev; for (prev = &ios->openings; (o = *prev) != NULL; prev = &o->next) { if (o->gf == gf) break; } if (o == NULL) return (1); *prev = o->next; free(o); return (0); } static int get_ino_and_remove_opening_from_open_table(GFS_File gf, gfarm_ino_t *inop, struct inode_openings **iosp) { struct gfarm_hash_iterator it; struct gfarm_hash_entry *entry = NULL; struct inode_openings *ios = NULL; for (gfarm_hash_iterator_begin(open_file_table, &it); !gfarm_hash_iterator_is_end(&it); gfarm_hash_iterator_next(&it)) { entry = gfarm_hash_iterator_access(&it); ios = gfarm_hash_entry_data(entry); if (open_file_remove_opening(ios, gf) == 0) break; } if (gfarm_hash_iterator_is_end(&it)) return (1); *inop = *(gfarm_ino_t *)gfarm_hash_entry_key(entry); *iosp = ios; return (0); } void gfarm2fs_open_file_remove(GFS_File gf) { gfarm_ino_t ino; struct gfarm_hash_entry *entry; struct inode_openings *ios = NULL; if (get_ino(gf, &ino) != 0) { if (get_ino_and_remove_opening_from_open_table(gf, &ino, &ios) != 0) { gflog_warning(GFARM_MSG_2000055, "file %p does not exist in open file table", gf); return; } /* the opening entry removed */ } else { entry = gfarm_hash_lookup(open_file_table, &ino, sizeof(ino)); if (entry == NULL) { gflog_warning(GFARM_MSG_2000056, "inode %lld is not found in open file table", (unsigned long long)ino); return; } ios = gfarm_hash_entry_data(entry); if (open_file_remove_opening(ios, gf) != 0) gflog_warning(GFARM_MSG_2000057, "file %p is not found in the inode %lld openings", gf, (unsigned long long)ino); } if (ios->gf_cached == gf) ios->gf_cached = NULL; if (ios->openings == NULL) (void)gfarm_hash_purge(open_file_table, &ino, sizeof(ino)); } <file_sep>/gfarm/tags/gfarm_1_0_1_rc2/makes/include.mk all: include-all post-all-hook install: all include-install post-install-hook clean: include-clean post-clean-hook veryclean: include-veryclean post-veryclean-hook distclean: include-distclean post-distclean-hook gfregister: include-gfregister post-gfregister-hook man: include-man post-man-hook html: include-html post-html-hook post-all-hook: post-install-hook: post-clean-hook: post-veryclean-hook: post-distclean-hook: post-gfregister-hook: post-man-hook: post-html-hook: include-all: include-install: all ( cd $(srcdir) && \ for i in *.h; do $(INSTALL_DATA) $$i $(includedir)/$$i; done ) @set -x; \ for i in / $(EXEC_INCS); do \ case $$i in /) continue;; esac; \ $(INSTALL_DATA) $$i $(exec_includedir)/$$i; \ done include-clean: include-veryclean: clean -rm -f $(EXECHEADERS) include-distclean: veryclean include-gfregister: include-man: include-html: <file_sep>/gfarm/tags/gfarm_1_0_beta_3/lib/libgfarm/gfarm/auth.h enum gfarm_auth_error { GFARM_AUTH_ERROR_NO_ERROR, GFARM_AUTH_ERROR_DENIED, GFARM_AUTH_ERROR_NOT_SUPPORTED, GFARM_AUTH_ERROR_INVALID_CREDENTIAL, GFARM_AUTH_ERROR_EXPIRED, GFARM_AUTH_ERROR_RESOURCE_UNAVAILABLE, }; enum gfarm_auth_method { GFARM_AUTH_METHOD_NONE, /* never used */ GFARM_AUTH_METHOD_SHAREDSECRET, GFARM_AUTH_METHOD_GSI_OLD, /* not supported since 2003/07/09 */ GFARM_AUTH_METHOD_GSI, GFARM_AUTH_METHOD_GSI_AUTH, GFARM_AUTH_METHOD_NUMBER }; #define GFARM_AUTH_METHOD_ALL GFARM_AUTH_METHOD_NONE #define GFARM_AUTH_TIMEOUT 60 /* seconds */ /* * GFARM_AUTH_METHOD_SHAREDSECRET dependent constants. * note that this is too weak authentication for the Internet. */ void gfarm_random_initialize(void); void gfarm_auth_random(void *, size_t); void gfarm_auth_sharedsecret_response_data(char *, char *, char *); char *gfarm_auth_shared_key_get(unsigned int *, char *, char *, int); #define GFARM_AUTH_SHARED_KEY_GET 0 #define GFARM_AUTH_SHARED_KEY_CREATE 1 #define GFARM_AUTH_SHARED_KEY_CREATE_FORCE 2 /* request */ enum gfarm_auth_sharedsecret_request { GFARM_AUTH_SHAREDSECRET_GIVEUP, GFARM_AUTH_SHAREDSECRET_MD5 }; /* key */ #define GFARM_AUTH_RETRY_MAX 2 #define GFARM_AUTH_SHARED_KEY_LEN 32 #define GFARM_AUTH_CHALLENGE_LEN 32 #define GFARM_AUTH_RESPONSE_LEN 16 /* length of MD5 */ /* auth_client */ struct xxx_connection; struct sockaddr; struct gfarm_eventqueue; struct gfarm_auth_request_state; char *gfarm_authorize_log_connected(struct xxx_connection *, char *, char *); char *gfarm_auth_request(struct xxx_connection *, char *, struct sockaddr *, enum gfarm_auth_method *); char *gfarm_auth_request_multiplexed(struct gfarm_eventqueue *, struct xxx_connection *, char *, struct sockaddr *, void (*)(void *), void *, struct gfarm_auth_request_state **); char *gfarm_auth_result_multiplexed(struct gfarm_auth_request_state *, enum gfarm_auth_method *); char *gfarm_authorize(struct xxx_connection *, int, char **, char **, enum gfarm_auth_method *); /* auth_config */ struct gfarm_hostspec; char gfarm_auth_method_mnemonic(enum gfarm_auth_method); char *gfarm_auth_method_name(enum gfarm_auth_method); char *gfarm_auth_method_parse(char *, enum gfarm_auth_method *); char *gfarm_auth_enable(enum gfarm_auth_method, struct gfarm_hostspec *); char *gfarm_auth_disable(enum gfarm_auth_method, struct gfarm_hostspec *); /* this i/f have to be changed, if we support more than 31 auth methods */ gfarm_int32_t gfarm_auth_method_get_enabled_by_name_addr( char *, struct sockaddr *); gfarm_int32_t gfarm_auth_method_get_available(void); /* auth_client_sharedsecret */ char *gfarm_auth_request_sharedsecret(struct xxx_connection *); char *gfarm_auth_request_sharedsecret_multiplexed(struct gfarm_eventqueue *, struct xxx_connection *, void (*)(void *), void *, void **); char *gfarm_auth_result_sharedsecret_multiplexed(void *); /* auth_client_gsi */ char *gfarm_auth_request_gsi(struct xxx_connection *); char *gfarm_auth_request_gsi_multiplexed(struct gfarm_eventqueue *, struct xxx_connection *, void (*)(void *), void *, void **); char *gfarm_auth_result_gsi_multiplexed(void *); /* auth_client_gsi_auth */ char *gfarm_auth_request_gsi_auth(struct xxx_connection *); char *gfarm_auth_request_gsi_auth_multiplexed(struct gfarm_eventqueue *, struct xxx_connection *, void (*)(void *), void *, void **); char *gfarm_auth_result_gsi_auth_multiplexed(void *); /* auth_server_sharedsecret */ char *gfarm_authorize_sharedsecret(struct xxx_connection *, int, char *, char **); /* auth_server_gsi */ char *gfarm_authorize_gsi(struct xxx_connection *, int, char *, char **); /* auth_server_gsi_auth */ char *gfarm_authorize_gsi_auth(struct xxx_connection *, int, char *, char **); <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_8_1/contrib/gfarm2fs-proxy-info/gfarm2fs-proxy-info #!/bin/sh PROG=`basename $0` ABORT() { echo >&2 $* exit 1 } usage() { exec >&2 echo "Usage: $PROG MOUNTDIR - display proxy cert information" echo " $PROG -p MOUNTDIR - display path of proxy cert" echo " $PROG -t MOUNTDIR - display timeleft of proxy cert" exit 2 } getxattr() { attr=$1 p=$2 v=`(getfattr -n $attr $p) 2>/dev/null | sed -n s/$attr'="\(.*\)"/\1/p'` echo $v } gsiproxyinfo() { getxattr gfarm2fs.gsiproxyinfo $1 } gsipath() { getxattr gfarm2fs.gsipath $1 } gsitimeleft() { getxattr gfarm2fs.gsitimeleft $1 } MODE=PROXYINFO case $1 in -p) shift MODE=PATH ;; -t) shift MODE=TIMELEFT ;; -*) usage ;; esac [ X"$1" = X ] && usage MOUNTDIR=$1 [ -d $MOUNTDIR ] || ABORT "$MOUNTDIR: not a directory" case $MODE in PROXYINFO) gsiproxyinfo $MOUNTDIR | sed 's/\\012/\n/g' | sed '/^$/d' ;; PATH) gsipath $MOUNTDIR | sed '/^$/d' ;; TIMELEFT) gsitimeleft $MOUNTDIR | sed '/^$/d' ;; esac <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_listenport_gfmd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo "error: ${CONF_FILE} does not exist." exit 0 fi # create the temporary file tmpfile=`mktemp` trap "rm -f $tmpfile >/dev/null 2>&1" EXIT netstat_options="-alnNt" netstat ${netstat_options} > $tmpfile if [ $? != 0 ]; then echo "error: netstat ${netstat_options} error." 1>&2 exit 1 fi c=0 while read prefix host port; do if [ "`grep LISTEN ${tmpfile} | awk '{print $4}' | grep -c :${port}$`" -eq 0 ]; then echo "error: gfmd does not listen ${prefix} port." c=`expr 1 + $c` fi done<<EOF `read_gfmd_confs "$1"` EOF if [ $? -ne 0 ]; then echo "error: something wrong." exit 1 fi if [ $c = 0 ]; then echo "ok" fi exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/auth_config.c #include <assert.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "hostspec.h" #include "auth.h" /* * gfarm_auth_method */ struct gfarm_auth_method_name_value { char mnemonic; char *name; enum gfarm_auth_method method; } gfarm_auth_method_name_value_table[] = { { 's', "sharedsecret", GFARM_AUTH_METHOD_SHAREDSECRET }, { 'G', "gsi", GFARM_AUTH_METHOD_GSI }, { 'g', "gsi_auth", GFARM_AUTH_METHOD_GSI_AUTH }, }; enum gfarm_auth_config_command { GFARM_AUTH_ENABLE, GFARM_AUTH_DISABLE }; struct gfarm_auth_config { struct gfarm_auth_config *next; enum gfarm_auth_config_command command; enum gfarm_auth_method method; struct gfarm_hostspec *hostspec; }; struct gfarm_auth_config *gfarm_auth_config_list = NULL; struct gfarm_auth_config **gfarm_auth_config_last = &gfarm_auth_config_list; char gfarm_auth_method_mnemonic(enum gfarm_auth_method method) { int i; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_auth_method_name_value_table); i++) { struct gfarm_auth_method_name_value *entry = &gfarm_auth_method_name_value_table[i]; if (entry->method == method) return (entry->mnemonic); } return ('-'); } char * gfarm_auth_method_name(enum gfarm_auth_method method) { int i; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_auth_method_name_value_table); i++) { struct gfarm_auth_method_name_value *entry = &gfarm_auth_method_name_value_table[i]; if (entry->method == method) return (entry->name); } return ("unknown auth method"); } char * gfarm_auth_method_parse(char *name, enum gfarm_auth_method *methodp) { int i; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_auth_method_name_value_table); i++) { if (strcmp(name, gfarm_auth_method_name_value_table[i].name) == 0) { *methodp = gfarm_auth_method_name_value_table[i].method; return (NULL); } } return (GFARM_ERR_NO_SUCH_OBJECT); } char * gfarm_auth_config_add( enum gfarm_auth_config_command command, enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { struct gfarm_auth_config *acp = malloc(sizeof(struct gfarm_auth_config)); if (acp == NULL) return (GFARM_ERR_NO_MEMORY); acp->next = NULL; acp->command = command; acp->method = method; acp->hostspec = hsp; *gfarm_auth_config_last = acp; gfarm_auth_config_last = &acp->next; return (NULL); } char * gfarm_auth_enable(enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { return (gfarm_auth_config_add(GFARM_AUTH_ENABLE, method, hsp)); } char * gfarm_auth_disable(enum gfarm_auth_method method, struct gfarm_hostspec *hsp) { return (gfarm_auth_config_add(GFARM_AUTH_DISABLE, method, hsp)); } /* this i/f have to be changed, if we support more than 31 auth methods */ gfarm_int32_t gfarm_auth_method_get_enabled_by_name_addr( char *name, struct sockaddr *addr) { struct gfarm_auth_config *acp = gfarm_auth_config_list; gfarm_int32_t enabled = 0, disabled = 0, methods; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); for (; acp != NULL; acp = acp->next) { if (gfarm_hostspec_match(acp->hostspec, name, addr)) { if (acp->method == GFARM_AUTH_METHOD_ALL) { methods = ((1 << GFARM_AUTH_METHOD_NUMBER) - 1) & ~(1 << GFARM_AUTH_METHOD_NONE) & ~(enabled | disabled); } else { methods = 1 << acp->method; if (((enabled | disabled) & methods) != 0) continue; /* already determined */ } switch (acp->command) { case GFARM_AUTH_ENABLE: enabled |= methods; break; case GFARM_AUTH_DISABLE: disabled |= methods; break; } } } return (enabled); } gfarm_int32_t gfarm_auth_method_get_available(void) { int i; gfarm_int32_t methods; assert(GFARM_AUTH_METHOD_NUMBER <= sizeof(gfarm_int32_t) * CHAR_BIT); methods = 0; for (i = GFARM_AUTH_METHOD_NONE + 1; i < GFARM_AUTH_METHOD_NUMBER; i++) { switch (i) { case GFARM_AUTH_METHOD_GSI_OLD: /* obsolete */ break; #ifndef HAVE_GSI case GFARM_AUTH_METHOD_GSI: break; case GFARM_AUTH_METHOD_GSI_AUTH: break; #endif default: methods |= 1 << i; break; } } return (methods); } /* * gfarm_auth_server_cred */ struct gfarm_auth_cred_type_name_value { char *name; enum gfarm_auth_cred_type type; } gfarm_auth_cred_type_name_value_table[] = { { "", GFARM_AUTH_CRED_TYPE_DEFAULT }, { "no-name", GFARM_AUTH_CRED_TYPE_NO_NAME }, { "mechanism-specific", GFARM_AUTH_CRED_TYPE_MECHANISM_SPECIFIC }, { "host", GFARM_AUTH_CRED_TYPE_HOST }, { "user", GFARM_AUTH_CRED_TYPE_USER }, }; char * gfarm_auth_cred_type_parse(char *type_name, enum gfarm_auth_cred_type *typep) { int i; for (i = 0; i < GFARM_ARRAY_LENGTH(gfarm_auth_cred_type_name_value_table); i++) { struct gfarm_auth_cred_type_name_value *entry = &gfarm_auth_cred_type_name_value_table[i]; if (strcmp(type_name, entry->name) == 0) { *typep = entry->type; return (NULL); } } return ("unknown cred_type"); } struct gfarm_auth_cred_config { struct gfarm_auth_cred_config *next; char *service_tag; enum gfarm_auth_cred_type type; char *service; char *name; }; struct gfarm_auth_cred_config *gfarm_auth_server_cred_config_list = NULL; static struct gfarm_auth_cred_config ** gfarm_auth_server_cred_config_lookup(char *service_tag) { struct gfarm_auth_cred_config *conf, **p; for (p = &gfarm_auth_server_cred_config_list; (conf = *p) != NULL; p = &conf->next) { if (strcmp(service_tag, conf->service_tag) == 0) break; } return (p); } /* service_tag must be statically allocated */ static char * gfarm_auth_server_cred_config_enter(char *service_tag, struct gfarm_auth_cred_config **confp) { struct gfarm_auth_cred_config *conf, **p = gfarm_auth_server_cred_config_lookup(service_tag); if (*p != NULL) { *confp = *p; return (NULL); } *p = conf = malloc(sizeof(*conf)); if (conf == NULL) return (GFARM_ERR_NO_MEMORY); conf->next = NULL; conf->service_tag = service_tag; conf->type = GFARM_AUTH_CRED_TYPE_DEFAULT; conf->service = NULL; conf->name = NULL; *confp = conf; return (NULL); } enum gfarm_auth_cred_type gfarm_auth_server_cred_type_get(char *service_tag) { struct gfarm_auth_cred_config *conf = *gfarm_auth_server_cred_config_lookup(service_tag); if (conf == NULL) return (GFARM_AUTH_CRED_TYPE_DEFAULT); return (conf->type); } char * gfarm_auth_server_cred_service_get(char *service_tag) { struct gfarm_auth_cred_config *conf = *gfarm_auth_server_cred_config_lookup(service_tag); if (conf == NULL) return (NULL); return (conf->service); } char * gfarm_auth_server_cred_name_get(char *service_tag) { struct gfarm_auth_cred_config *conf = *gfarm_auth_server_cred_config_lookup(service_tag); if (conf == NULL) return (NULL); return (conf->name); } /* service_tag must be statically allocated */ char * gfarm_auth_server_cred_type_set_by_string(char *service_tag, char *string) { char *e; enum gfarm_auth_cred_type type; e = gfarm_auth_cred_type_parse(string, &type); if (e != NULL) return (e); return (gfarm_auth_server_cred_type_set(service_tag, type)); } /* service_tag must be statically allocated */ char * gfarm_auth_server_cred_type_set(char *service_tag, enum gfarm_auth_cred_type type) { struct gfarm_auth_cred_config *conf; char *e = gfarm_auth_server_cred_config_enter(service_tag, &conf); if (e != NULL) return (e); /* first line has precedence */ if (conf->type != GFARM_AUTH_CRED_TYPE_DEFAULT) return (NULL); conf->type = type; return (NULL); } /* service_tag must be statically allocated */ char * gfarm_auth_server_cred_service_set(char *service_tag, char *service) { struct gfarm_auth_cred_config *conf; char *e = gfarm_auth_server_cred_config_enter(service_tag, &conf); if (e != NULL) return (e); if (conf->service != NULL) /* first line has precedence */ return (NULL); if ((conf->service = strdup(service)) == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } /* service_tag must be statically allocated */ char * gfarm_auth_server_cred_name_set(char *service_tag, char *name) { struct gfarm_auth_cred_config *conf; char *e = gfarm_auth_server_cred_config_enter(service_tag, &conf); if (e != NULL) return (e); if (conf->name != NULL) /* first line has precedence */ return (NULL); if ((conf->name = strdup(name)) == NULL) return (GFARM_ERR_NO_MEMORY); return (NULL); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/failure_test_scripts/Makefile SHELL = /bin/sh CC = gcc CPPFLAGS = CFLAGS = -Wall -O2 LDFLAGS = CCLD = $(CC) .PHONY: all clean all: malloc malloc: malloc.o $(CCLD) -o $@ $(CFLAGS) malloc.o $(LDFLAGS) malloc.o: malloc.c $(CC) -c -o $@ $(CFLAGS) $(CPPFLAGS) malloc.c clean: rm -f malloc rm -f malloc.o <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc3/lib/libgfarm/gfarm/gfm_client.c /* * $Id$ */ #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "hash.h" #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "xxx_proto.h" #include "io_fd.h" #include "sockopt.h" #include "auth.h" #include "gfm_proto.h" #include "gfj_client.h" struct gfm_connection { struct xxx_connection *conn; enum gfarm_auth_method auth_method; }; #define SERVER_HASHTAB_SIZE 3079 /* prime number */ static struct gfarm_hash_table *gfm_server_hashtab = NULL; static char * gfm_client_connection0(char *hostname, struct gfm_connection *gfm_server) { char *e, *host_fqdn; int sock; struct hostent *hp; struct sockaddr_in peer_addr; hp = gethostbyname(hostname); if (hp == NULL || hp->h_addrtype != AF_INET) return (GFARM_ERR_UNKNOWN_HOST); memset(&peer_addr, 0, sizeof(peer_addr)); memcpy(&peer_addr.sin_addr, hp->h_addr, sizeof(peer_addr.sin_addr)); peer_addr.sin_family = hp->h_addrtype; peer_addr.sin_port = htons(gfarm_metadb_server_port); sock = socket(PF_INET, SOCK_STREAM, 0); if (sock == -1) return (gfarm_errno_to_error(errno)); /* XXX - how to report setsockopt(2) failure ? */ gfarm_sockopt_apply_by_name_addr(sock, hp->h_name, (struct sockaddr *)&peer_addr); if (connect(sock, (struct sockaddr *)&peer_addr, sizeof(peer_addr)) < 0) { close(sock); return (gfarm_errno_to_error(errno)); } e = xxx_fd_connection_new(sock, &gfm_server->conn); if (e != NULL) { close(sock); return (e); } /* * the reason why we call strdup() is because * gfarm_auth_request() may break static work area of `*hp' */ host_fqdn = strdup(hp->h_name); if (host_fqdn == NULL) { xxx_connection_free(gfm_server->conn); return (GFARM_ERR_NO_MEMORY); } e = gfarm_auth_request(gfm_server->conn, host_fqdn, (struct sockaddr *)&peer_addr, &gfm_server->auth_method); free(host_fqdn); if (e != NULL) { xxx_connection_free(gfm_server->conn); return (e); } return (NULL); } char * gfm_client_connection(char *hostname, struct gfm_connection **gfm_serverp) { char *e; struct gfarm_hash_entry *entry; struct gfm_connection *gfm_server; int created; if (gfm_server_hashtab == NULL) { gfm_server_hashtab = gfarm_hash_table_alloc(SERVER_HASHTAB_SIZE, gfarm_hash_casefold, gfarm_hash_key_equal_casefold); if (gfm_server_hashtab == NULL) return (GFARM_ERR_NO_MEMORY); } entry = gfarm_hash_enter(gfm_server_hashtab, hostname, strlen(hostname) + 1, sizeof(struct gfm_connection), &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); gfm_server = gfarm_hash_entry_data(entry); if (created) { e = gfm_client_connection0(hostname, gfm_server); if (e != NULL) { gfarm_hash_purge(gfm_server_hashtab, hostname, strlen(hostname) + 1); return (e); } } *gfm_serverp = gfm_server; return (NULL); } char * gfm_proto_error_string(int error) { switch (error) { case GFM_ERROR_NOERROR: return (NULL); case GFM_ERROR_NO_MEMORY: return (GFARM_ERR_NO_MEMORY); case GFM_ERROR_NO_SUCH_OBJECT: return (GFARM_ERR_NO_SUCH_OBJECT); case GFJ_ERROR_TOO_MANY_JOBS: return ("too many jobs"); default: return (GFARM_ERR_UNKNOWN); } } struct gfm_connection *gfarm_metadb_server = NULL; char * gfj_initialize(void) { char *e; if (gfarm_metadb_server_name == NULL) return ("\"metadb_serverhost\" is missing in configuration"); e = gfm_client_connection(gfarm_metadb_server_name, &gfarm_metadb_server); return (e); } char * gfm_client_rpc_request(struct gfm_connection *gfm_server, int command, char *format, ...) { va_list ap; char *e; va_start(ap, format); e = xxx_proto_vrpc_request(gfm_server->conn, command, &format, &ap); va_end(ap); return (e); } char * gfm_client_rpc_result(struct gfm_connection *gfm_server, int just, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc_result(gfm_server->conn, just, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfm_proto_error_string(error)); return (NULL); } char * gfm_client_rpc(struct gfm_connection *gfm_server, int just, int command, char *format, ...) { va_list ap; char *e; int error; va_start(ap, format); e = xxx_proto_vrpc(gfm_server->conn, just, command, &error, &format, &ap); va_end(ap); if (e != NULL) return (e); if (error != 0) return (gfm_proto_error_string(error)); return (NULL); } char * gfj_client_lock_register(struct gfm_connection *gfm_server) { return (gfm_client_rpc(gfm_server, 0, GFJ_PROTO_LOCK_REGISTER, "/")); } char * gfj_client_unlock_register(struct gfm_connection *gfm_server) { return (gfm_client_rpc(gfm_server, 0, GFJ_PROTO_UNLOCK_REGISTER, "/")); } char * gfj_client_register(struct gfm_connection *gfm_server, struct gfarm_job_info *job, int flags, int *job_idp) { char *e; int i; gfarm_int32_t job_id; e = gfm_client_rpc_request(gfm_server, GFJ_PROTO_REGISTER, "iisssi", (gfarm_int32_t)flags, (gfarm_int32_t)job->total_nodes, job->job_type, job->originate_host, job->gfarm_url_for_scheduling, (gfarm_int32_t)job->argc); if (e != NULL) return (e); for (i = 0; i < job->argc; i++) e = xxx_proto_send(gfm_server->conn, "s", job->argv[i]); for (i = 0; i < job->total_nodes; i++) e = xxx_proto_send(gfm_server->conn, "s", job->nodes[i].hostname); e = gfm_client_rpc_result(gfm_server, 0, "i", &job_id); if (e == NULL) *job_idp = job_id; return (e); } char * gfj_client_unregister(struct gfm_connection *gfm_server, int job_id) { return (gfm_client_rpc(gfm_server, 0, GFJ_PROTO_UNREGISTER, "i/", job_id)); } char * gfj_client_list(struct gfm_connection *gfm_server, char *user, int *np, int **jobsp) { char *e; int i, n, eof, *jobs; gfarm_int32_t job_id; e = gfm_client_rpc(gfm_server, 0, GFJ_PROTO_LIST, "s/i", user, &n); if (e != NULL) return (e); jobs = malloc(sizeof(int) * n); if (jobs == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < n; i++) { e = xxx_proto_recv(gfm_server->conn, 0, &eof, "i", &job_id); if (e != NULL) { free(jobs); return (e); } if (eof) { free(jobs); return (GFARM_ERR_PROTOCOL); } jobs[i] = job_id; } *np = n; *jobsp = jobs; return (NULL); } char * gfj_client_info_entry(struct xxx_connection *conn, struct gfarm_job_info *info) { char *e; int eof, i; gfarm_int32_t total_nodes, argc, node_pid, node_state; e = xxx_proto_recv(conn, 0, &eof, "issssi", &total_nodes, &info->user, &info->job_type, &info->originate_host, &info->gfarm_url_for_scheduling, &argc); if (e != NULL) return (e); if (eof) return (GFARM_ERR_PROTOCOL); info->argv = malloc(sizeof(char *) * (argc + 1)); info->nodes = malloc(sizeof(struct gfarm_job_node_info) * total_nodes); if (info->argv == NULL || info->nodes == NULL) { free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); if (info->argv != NULL) free(info->argv); if (info->nodes != NULL) free(info->nodes); return (GFARM_ERR_NO_MEMORY); } for (i = 0; i < argc; i++) { e = xxx_proto_recv(conn, 0, &eof, "s", &info->argv[i]); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_PROTOCOL; while (--i >= 0) free(info->argv[i]); free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); free(info->argv); free(info->nodes); return (e); } } info->argv[argc] = NULL; for (i = 0; i < total_nodes; i++) { e = xxx_proto_recv(conn, 0, &eof, "sii", &info->nodes[i].hostname, &node_pid, &node_state); if (e != NULL || eof) { if (e == NULL) e = GFARM_ERR_PROTOCOL; while (--i >= 0) free(info->nodes[i].hostname); for (i = 0; i < argc; i++) free(info->argv[i]); free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); free(info->argv); free(info->nodes); return (e); } info->nodes[i].pid = node_pid; info->nodes[i].state = node_state; } info->total_nodes = total_nodes; info->argc = argc; return (NULL); } char * gfj_client_info(struct gfm_connection *gfm_server, int n, int *jobs, struct gfarm_job_info *infos) { char *e; int i; e = gfm_client_rpc_request(gfm_server, GFJ_PROTO_INFO, "i", n); if (e != NULL) return (e); for (i = 0; i < n; i++) { e = xxx_proto_send(gfm_server->conn, "i", (gfarm_int32_t)jobs[i]); if (e != NULL) return (e); } gfarm_job_info_clear(infos, n); for (i = 0; i < n; i++) { e = gfm_client_rpc_result(gfm_server, 0, ""); if (e == GFARM_ERR_NO_SUCH_OBJECT) continue; if (e == NULL) e = gfj_client_info_entry(gfm_server->conn, &infos[i]); if (e != NULL) { gfarm_job_info_free_contents(infos, i - 1); return (e); } } return (NULL); } void gfarm_job_info_clear(struct gfarm_job_info *infos, int n) { memset(infos, 0, sizeof(struct gfarm_job_info) * n); } void gfarm_job_info_free_contents(struct gfarm_job_info *infos, int n) { int i, j; struct gfarm_job_info *info; for (i = 0; i < n; i++) { info = &infos[i]; if (info->user == NULL) /* this entry is not valid */ continue; free(info->user); free(info->job_type); free(info->originate_host); free(info->gfarm_url_for_scheduling); for (j = 0; j < info->argc; j++) free(info->argv[j]); free(info->argv); for (j = 0; j < info->total_nodes; j++) free(info->nodes[j].hostname); free(info->nodes); } } /* * convenience function */ char * gfarm_user_job_register(int nhosts, char **hosts, char *job_type, char *sched_file, int argc, char **argv, int *job_idp) { char *e; int i; struct gfarm_job_info job_info; gfarm_job_info_clear(&job_info, 1); job_info.total_nodes = nhosts; job_info.user = gfarm_get_global_username(); job_info.job_type = job_type; e = gfarm_host_get_canonical_self_name(&job_info.originate_host); if (e == GFARM_ERR_UNKNOWN_HOST || e == GFARM_ERR_AMBIGUOUS_RESULT) { /* * gfarm client doesn't have to be a compute host, * so, we should allow non canonical name here. */ job_info.originate_host = gfarm_host_get_self_name(); } else if (e != NULL) return (e); job_info.gfarm_url_for_scheduling = sched_file; job_info.argc = argc; job_info.argv = argv; job_info.nodes = malloc(sizeof(struct gfarm_job_node_info) * nhosts); if (job_info.nodes == NULL) return (GFARM_ERR_NO_MEMORY); for (i = 0; i < nhosts; i++) { e = gfarm_host_get_canonical_name(hosts[i], &job_info.nodes[i].hostname); if (e != NULL) { while (--i >= 0) free(job_info.nodes[i].hostname); free(job_info.nodes); return (e); } } e = gfj_client_register(gfarm_jobmanager_server, &job_info, 0, job_idp); for (i = 0; i < nhosts; i++) free(job_info.nodes[i].hostname); free(job_info.nodes); return (e); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/gftool/gfrm/gfrm.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <libgen.h> #include <gfarm/gfarm.h> char *program_name = "gfrm"; void usage() { fprintf(stderr, "Usage: %s [-frR] [-h <host>] <gfarm_url>...\n", program_name); fprintf(stderr, " %s [-f] -I <fragment> -h <host> " "<gfarm_url>...\n", program_name); exit(1); } struct unlink_ops { char *(*unlink)(char *, void *); char *(*rmdir)(const char *, void *); }; typedef struct unlink_ops * Unlink_Ops; static void remove_cwd_entries(Unlink_Ops ops, void *closure) { char *e; char cwdbf[PATH_MAX * 2]; int i; GFS_Dir dir; struct gfs_dirent *entry; gfarm_stringlist entry_list; e = gfs_getcwd(cwdbf, sizeof(cwdbf)); if (e != NULL) { fprintf(stderr, "%s\n", e); return; } e = gfs_opendir(".", &dir); if (e != NULL) { fprintf(stderr, "%s: %s\n", cwdbf, e); return; } e = gfarm_stringlist_init(&entry_list); if (e != NULL) { fprintf(stderr, "%s: %s\n", cwdbf, e); gfs_closedir(dir); return; } while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { char *p; if (entry->d_name[0] == '.' && (entry->d_name[1] == '\0' || (entry->d_name[1] == '.' && entry->d_name[2] == '\0'))) continue; /* "." or ".." */ p = strdup(entry->d_name); if (p == NULL) { fprintf(stderr, "%s\n", GFARM_ERR_NO_MEMORY); exit (1); } e = gfarm_stringlist_add(&entry_list, p); if (e != NULL) { fprintf(stderr, "%s/%s: %s\n", cwdbf, entry->d_name, e); } } if (e != NULL) fprintf(stderr, "%s: %s\n", cwdbf, e); gfs_closedir(dir); for (i = 0; i < gfarm_stringlist_length(&entry_list); i++) { struct gfs_stat gs; char *path = gfarm_stringlist_elem(&entry_list, i); gfarm_mode_t mode = 0; e = gfs_stat(path, &gs); if (e != GFARM_ERR_NO_FRAGMENT_INFORMATION && e != NULL) { fprintf(stderr, "%s/%s: %s\n", cwdbf, path, e); continue; } if (e == NULL) { mode = gs.st_mode; gfs_stat_free(&gs); } if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION || GFARM_S_ISREG(mode)) { char *url; url = gfarm_url_prefix_add(path); if (url == NULL) { fprintf(stderr, "%s\n", GFARM_ERR_NO_MEMORY); exit (1); } e = ops->unlink(url, closure); if (e != GFARM_ERR_NO_REPLICA_ON_HOST && e != NULL) fprintf(stderr, "%s/%s: %s\n", cwdbf, path, e); free(url); } else if (GFARM_S_ISDIR(mode)) { e = gfs_chdir(path); if (e != NULL) { fprintf(stderr, "%s/%s: %s\n", cwdbf, path, e); continue; } remove_cwd_entries(ops, closure); e = gfs_chdir(".."); if (e != NULL) { fprintf(stderr, "%s: %s\n", cwdbf, e); exit (1); } e = ops->rmdir(path, closure); if (e != NULL) fprintf(stderr, "%s/%s: %s\n", cwdbf, path, e); } } gfarm_stringlist_free_deeply(&entry_list); } static char * remove_whole_file_or_dir(char *path, Unlink_Ops ops, void *closure, int is_recursive) { struct gfs_stat gs; char *e, cwdbuf[PATH_MAX * 2]; const char *b; gfarm_mode_t mode; b = gfarm_path_dir_skip(gfarm_url_prefix_skip(path)); if (b[0] == '.' && (b[1] == '\0' || (b[1] == '.' && b[2] == '\0'))) return ("cannot remove \'.\' or \'..\'"); e = gfs_stat(path, &gs); if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION) return (ops->unlink(path, closure)); if (e != NULL) return (e); mode = gs.st_mode; gfs_stat_free(&gs); if (GFARM_S_ISREG(mode)) { e = ops->unlink(path, closure); } else if (GFARM_S_ISDIR(mode)) { if (!is_recursive) return (GFARM_ERR_IS_A_DIRECTORY); e = gfs_getcwd(cwdbuf, sizeof(cwdbuf)); if (e != NULL) return (e); e = gfs_chdir(path); if (e != NULL) return (e); remove_cwd_entries(ops, closure); e = gfs_chdir_canonical(cwdbuf); if (e != NULL) return (e); e = ops->rmdir(path, closure); } return (e); } static char * unlink_file(char *path, void *closure) { return (gfs_unlink(path)); } static char * rmdir_file(const char *path, void *closure) { return (gfs_rmdir(path)); } struct unlink_replica_closure { int nhosts; char **hosts; int force; }; static char * unlink_replica_alloc_closure(int nhosts, char **hosts, int force, void **cp) { struct unlink_replica_closure *c; c = malloc(sizeof(struct unlink_replica_closure)); if (c == NULL) return (GFARM_ERR_NO_MEMORY); c->nhosts = nhosts; c->hosts = hosts; c->force = force; *cp = c; return (NULL); } static char * unlink_replica(char *path, void *closure) { struct unlink_replica_closure *a = closure; return (gfs_unlink_replica(path, a->nhosts, a->hosts, a->force)); } static char * rmdir_replica(const char *path, void *closure) { struct unlink_replica_closure *a = closure; if (a->force) return (gfs_rmdir(path)); /* do nothing */ return (NULL); } static struct unlink_ops file_ops = { unlink_file, rmdir_file }; static struct unlink_ops replica_ops = { unlink_replica, rmdir_replica }; int main(argc, argv) int argc; char **argv; { extern char *optarg; extern int optind; int argc_save = argc; char **argv_save = argv; char *e, *section = NULL; int ch, nhosts = 0; char **hosttab; gfarm_stringlist host_list; int o_force = 0; int o_recursive = 0; gfarm_stringlist paths; gfs_glob_t types; int i; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_stringlist_init(&host_list); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } while ((ch = getopt(argc, argv, "h:I:fRr?")) != -1) { switch (ch) { case 'h': e = gfarm_stringlist_add(&host_list, optarg); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } ++nhosts; break; case 'f': o_force = 1; break; case 'I': section = optarg; break; case 'R': case 'r': o_recursive = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; e = gfarm_initialize(&argc_save, &argv_save); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } if (argc == 0) { fprintf(stderr, "%s: too few arguments\n", program_name); exit(1); } e = gfarm_stringlist_init(&paths); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } e = gfs_glob_init(&types); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < argc; i++) gfs_glob(argv[i], &paths, &types); if (section == NULL) { if (nhosts == 0) { /* remove a whole file */ for (i = 0; i < gfarm_stringlist_length(&paths); i++) { char *f = gfarm_stringlist_elem(&paths, i); e = remove_whole_file_or_dir( f, &file_ops, NULL, o_recursive); if (e != NULL) fprintf(stderr, "%s: %s\n", f, e); } } else { /* * remove file replicas of a whole file * on a specified node. */ void *closure; hosttab = gfarm_strings_alloc_from_stringlist( &host_list); gfarm_stringlist_free(&host_list); e = unlink_replica_alloc_closure( nhosts, hosttab, o_force, &closure); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } for (i = 0; i < gfarm_stringlist_length(&paths); i++) { char *f = gfarm_stringlist_elem(&paths, i); e = remove_whole_file_or_dir( f, &replica_ops, closure, o_recursive); if (e != NULL) fprintf(stderr, "%s: %s\n", f, e); } free(closure); free(hosttab); } } else { int i; /* remove a file fragment */ if (nhosts == 0) { fprintf(stderr, "%s: -h option should be specified\n", program_name); exit(1); } /* assert(nhosts == gfarm_stringlist_length(&host_list)); */ hosttab = gfarm_strings_alloc_from_stringlist(&host_list); gfarm_stringlist_free(&host_list); for (i = 0; i < gfarm_stringlist_length(&paths); i++) { e = gfs_unlink_section_replica( gfarm_stringlist_elem(&paths, i), section, nhosts, hosttab, o_force); if (e != NULL) fprintf(stderr, "%s: %s\n", gfarm_stringlist_elem(&paths, i), e); } free(hosttab); } gfs_glob_free(&types); gfarm_stringlist_free_deeply(&paths); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_beta_6/gftool/gfreg/gfreg.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <libgen.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <gfarm/gfarm.h> /* * Register a local file to Gfarm filesystem * * gfreg <local_filename> <gfarm_url> * * $Id$ */ char *program_name = "gfreg"; void usage() { fprintf(stderr, "Usage: %s [option] <local_filename> ... <gfarm_url>\n", program_name); fprintf(stderr, "Register local file(s) to Gfarm filesystem.\n\n"); fprintf(stderr, "option:\n"); fprintf(stderr, "\t-I fragment-index\tspecify a fragment index\n"); fprintf(stderr, "\t-N number\t\ttotal number of fragments\n"); fprintf(stderr, "\t-a architecture\t\tspecify an architecture\n"); fprintf(stderr, "\t-h hostname\t\tspecify a hostname\n"); fprintf(stderr, "\t-D domainname\t\tspecify a domainname\n"); fprintf(stderr, "\t-f \t\t\tforce to register\n"); exit(1); } #define GFS_FILE_BUFSIZE 65536 static char * gfarm_url_fragment_register(char *gfarm_url, char *section, int nfrags, char *hostname, char *filename) { char *e, *e_save = NULL; int fd; size_t rv; int length; /* XXX - should be size_t */ GFS_File gf; struct stat s; char buffer[GFS_FILE_BUFSIZE]; /* * register the fragment */ if (strcmp(filename, "-") == 0) { fd = 0; /* stdin */ s.st_mode = 0664; /* XXX */ } else { if (stat(filename, &s) == -1) return "no such file or directory"; fd = open(filename, O_RDONLY); if (fd == -1) return "cannot open"; } e = gfs_pio_create(gfarm_url, GFARM_FILE_WRONLY, s.st_mode & GFARM_S_ALLPERM, &gf); if (e != NULL) { close(fd); return (e); } if (nfrags == GFARM_FILE_DONTCARE) e = gfs_pio_set_view_section(gf, section, hostname, 0); else e = gfs_pio_set_view_index(gf, nfrags, strtol(section, NULL, 0), hostname, 0); if (e != NULL) { char *gfarm_file; gfs_pio_close(gf); close(fd); /* try to unlink path info when there is no fragment file */ if (gfarm_url_make_path(gfarm_url, &gfarm_file) == NULL) { (void)gfarm_path_info_remove(gfarm_file); free(gfarm_file); } return (e); } for (;;) { rv = read(fd, buffer, sizeof(buffer)); if (rv <= 0) break; /* XXX - partial write case ? */ e = gfs_pio_write(gf, buffer, rv, &length); if (e != NULL) break; } e_save = e; e = gfs_pio_close(gf); close(fd); if (e_save != NULL) return (e_save); return (e); } static int opt_force; static int gfarm_register_file(char *gfarm_url, char *node_index, char *hostname, int total_nodes, char *filename, int auto_index) { struct stat s; struct gfs_stat gs; char *e, *target_url = NULL; int executable_file = 0; if (stat(filename, &s) == 0) { if (!S_ISREG(s.st_mode)) { fprintf(stderr, "%s: not a regular file", filename); return (-1); } if ((s.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0) executable_file = 1; } else if (strcmp(filename, "-")) { perror(filename); return (-1); } e = gfs_stat(gfarm_url, &gs); if (e == NULL && GFARM_S_ISDIR(gs.st_mode)) { char *bname; /* gfarm_url is a directory */ gfs_stat_free(&gs); if (auto_index && total_nodes > 1 && !executable_file) { /* * In the auto index mode, the target Gfarm URL * should be a regular file when two or more local * non-executable files will be registered for * preventing unexpected results. */ fprintf(stderr, "%s: not a regular file. " "The target Gfarm URL should be a " "regular file when registering two or " "more local files.\n", gfarm_url); return (-1); } bname = basename(filename); target_url = malloc(strlen(gfarm_url) + strlen(bname) + 2); if (target_url == NULL) { fprintf(stderr, "not enough memory\n"); return (-1); } strcpy(target_url, gfarm_url); if (*gfarm_path_dir_skip(gfarm_url_prefix_skip(target_url)) != '\0') strcat(target_url, "/"); strcat(target_url, bname); } else if (e == NULL) gfs_stat_free(&gs); if (target_url == NULL) { target_url = strdup(gfarm_url); if (target_url == NULL) { fprintf(stderr, "not enough memory\n"); return (-1); } } if (executable_file) { /* register a binary executable. */ /* * In auto index case, node_index does not stand for * architecture. */ if (auto_index) node_index = NULL; if (node_index == NULL) { if (hostname == NULL) { char *self_name; e = gfarm_host_get_canonical_self_name( &self_name); if (e != NULL) { fprintf(stderr, "%s: %s\n", gfarm_host_get_self_name(), e); return (-1); } node_index = gfarm_host_info_get_architecture_by_host( self_name); } else { char *c_name; e = gfarm_host_get_canonical_name( hostname, &c_name); if (e != NULL) { fprintf(stderr, "%s: %s\n", hostname, e); return (-1); } node_index = gfarm_host_info_get_architecture_by_host( c_name); free(c_name); } } if (node_index == NULL) { fprintf(stderr, "%s: cannot determine the architecture " "of %s.\n", program_name, gfarm_host_get_self_name()); return (-1); } if (total_nodes <= 0) { if (gfs_pio_get_node_size(&total_nodes) != NULL) total_nodes = 1; } if (!opt_force) { struct gfs_stat s; if (gfs_stat_section(target_url, node_index, &s) == NULL) { gfs_stat_free(&s); e = "already exist"; goto finish; } } e = gfarm_url_fragment_register(target_url, node_index, GFARM_FILE_DONTCARE, hostname, filename); /* * XXX - gfarm_url_replicate() to replicate * 'total_nodes' copies of target_url. */ } else { char index_str[GFARM_INT32STRLEN + 1]; /* register a file fragment. */ if (node_index == NULL) { int index; e = gfs_pio_get_node_rank(&index); if (e != NULL) { fprintf(stderr, "%s: missing -I <Gfarm index>\n", program_name); return (-1); } sprintf(index_str, "%d", index); node_index = index_str; } if (total_nodes <= 0) { e = gfs_pio_get_node_size(&total_nodes); if (e != NULL) { fprintf(stderr, "%s: missing -N " "<total num of fragments>\n", program_name); return (-1); } } if (!opt_force) { struct gfs_stat s; if (gfs_stat_section(target_url, node_index, &s) == NULL) { gfs_stat_free(&s); e = "already exist"; goto finish; } } e = gfarm_url_fragment_register(target_url, node_index, total_nodes, hostname, filename); } finish: if (e != NULL) { fprintf(stderr, "%s: %s\n", target_url, e); return (-1); } free(target_url); return (0); } int main(int argc, char *argv[]) { char *gfarm_url, *node_index = NULL; char *hostname = NULL, **auto_hosts = NULL, *domainname = NULL, *e; int total_nodes = -1, c, auto_index = 0; extern char *optarg; extern int optind; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } /* Command options */ while ((c = getopt(argc, argv, "a:fh:D:I:N:")) != -1) { switch (c) { case 'I': case 'a': node_index = optarg; break; case 'N': total_nodes = strtol(optarg, NULL, 0); break; case 'h': hostname = optarg; break; case 'D': domainname = optarg; break; case 'f': opt_force = 1; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc == 0) { fprintf(stderr, "%s: missing a local filename\n", program_name); usage(); } if (argc == 1) { fprintf(stderr, "%s: missing a Gfarm URL\n", program_name); usage(); } if ((argc > 2 || hostname == NULL) && (argc > 1 && total_nodes < 0 && node_index == NULL)) { total_nodes = argc - 1; auto_index = 1; if (hostname != NULL) fprintf(stderr, "%s: warning: -h option is ignored\n", program_name); auto_hosts = malloc(total_nodes * sizeof(char *)); if (auto_hosts != NULL) { if (domainname != NULL) e = gfarm_schedule_search_idle_by_domainname( domainname, total_nodes, auto_hosts); else e = gfarm_schedule_search_idle_by_all( total_nodes, auto_hosts); if (e != NULL) { free(auto_hosts); auto_hosts = NULL; } } } gfarm_url = argv[argc - 1]; while (--argc) { char index_str[GFARM_INT32STRLEN + 1]; /* XXX - need to register in parallel? */ if (auto_index) { sprintf(index_str, "%d", total_nodes - argc); node_index = index_str; if (auto_hosts != NULL) hostname = auto_hosts[total_nodes - argc]; } if (gfarm_register_file(gfarm_url, node_index, hostname, total_nodes, *argv++, auto_index)) break; } if (auto_hosts != NULL) gfarm_strings_free_deeply(total_nodes, auto_hosts); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } exit(0); } <file_sep>/gfarm/tags/gfarm_1_0_3_1/lib/libgfarm/gfarm/gfs_pio_local.c /* * pio operations for local section * * $Id$ */ #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <libgen.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "gfs_proto.h" /* for gfs_digest_calculate_local() */ #include "gfs_pio.h" int gfarm_node = -1; int gfarm_nnode = -1; char * gfs_pio_set_local(int node, int nnode) { if (node < 0 || node >= nnode || nnode < 0) return (GFARM_ERR_INVALID_ARGUMENT); gfarm_node = node; gfarm_nnode = nnode; return (NULL); } char * gfs_pio_set_local_check(void) { if (gfarm_node < 0 || gfarm_nnode <= 0) return ("gfs_pio_set_local() is not correctly called"); return (NULL); } char * gfs_pio_get_node_rank(int *node) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); *node = gfarm_node; return (NULL); } char * gfs_pio_get_node_size(int *nnode) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); *nnode = gfarm_nnode; return (NULL); } char * gfs_pio_set_view_local(GFS_File gf, int flags) { char *e = gfs_pio_set_local_check(); if (e != NULL) return (e); return (gfs_pio_set_view_index(gf, gfarm_nnode, gfarm_node, NULL, flags)); } /***********************************************************************/ static char * gfs_pio_local_storage_close(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; if (close(vc->fd) == -1) return (gfarm_errno_to_error(errno)); return (NULL); } static char * gfs_pio_local_storage_write(GFS_File gf, const char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; int rv = write(vc->fd, buffer, size); if (rv == -1) return (gfarm_errno_to_error(errno)); *lengthp = rv; return (NULL); } static char * gfs_pio_local_storage_read(GFS_File gf, char *buffer, size_t size, size_t *lengthp) { struct gfs_file_section_context *vc = gf->view_context; int rv = read(vc->fd, buffer, size); if (rv == -1) return (gfarm_errno_to_error(errno)); *lengthp = rv; return (NULL); } static char * gfs_pio_local_storage_seek(GFS_File gf, file_offset_t offset, int whence, file_offset_t *resultp) { struct gfs_file_section_context *vc = gf->view_context; off_t rv = lseek(vc->fd, (off_t)offset, whence); if (rv == -1) return (gfarm_errno_to_error(errno)); if (resultp != NULL) *resultp = rv; return (NULL); } static char * gfs_pio_local_storage_calculate_digest(GFS_File gf, char *digest_type, size_t digest_size, size_t *digest_lengthp, unsigned char *digest, file_offset_t *filesizep) { struct gfs_file_section_context *vc = gf->view_context; const EVP_MD *md_type; int rv; static int openssl_initialized = 0; if (!openssl_initialized) { SSLeay_add_all_algorithms(); /* for EVP_get_digestbyname() */ openssl_initialized = 1; } if ((md_type = EVP_get_digestbyname(digest_type)) == NULL) return (GFARM_ERR_INVALID_ARGUMENT); /* note that this effectively breaks file offset. */ rv = gfs_digest_calculate_local( vc->fd, gf->buffer, GFS_FILE_BUFSIZE, md_type, &vc->md_ctx, digest_lengthp, digest, filesizep); if (rv != 0) return (gfarm_errno_to_error(rv)); return (NULL); } static int gfs_pio_local_storage_fd(GFS_File gf) { struct gfs_file_section_context *vc = gf->view_context; return (vc->fd); } struct gfs_storage_ops gfs_pio_local_storage_ops = { gfs_pio_local_storage_close, gfs_pio_local_storage_write, gfs_pio_local_storage_read, gfs_pio_local_storage_seek, gfs_pio_local_storage_calculate_digest, gfs_pio_local_storage_fd, }; char * gfs_pio_open_local_section(GFS_File gf, int flags) { struct gfs_file_section_context *vc = gf->view_context; char *e, *local_path; int fd, open_flags = gfs_open_flags_localize(gf->open_flags); int saved_errno; mode_t saved_umask; if (open_flags == -1) return (GFARM_ERR_INVALID_ARGUMENT); e = gfarm_path_localize_file_section(gf->pi.pathname, vc->section, &local_path); if (e != NULL) return (e); saved_umask = umask(0); fd = open(local_path, open_flags, gf->pi.status.st_mode & GFARM_S_ALLPERM); saved_errno = errno; umask(saved_umask); /* FT - the parent directory may be missing */ if (fd == -1 && (gf->open_flags & GFARM_FILE_CREATE) != 0 && gfarm_errno_to_error(saved_errno) == GFARM_ERR_NO_SUCH_OBJECT) { if (gfs_pio_local_mkdir_parent_canonical_path( gf->pi.pathname) == NULL) { fd = open(local_path, open_flags, gf->pi.status.st_mode & GFARM_S_ALLPERM); saved_errno = errno; } } free(local_path); /* FT - physical file should be missing */ if (fd == -1 && (gf->open_flags & GFARM_FILE_CREATE) == 0 && gfarm_errno_to_error(saved_errno) == GFARM_ERR_NO_SUCH_OBJECT) { /* Delete the section copy info */ char *localhost; if (gfarm_host_get_canonical_self_name(&localhost) == NULL && gfarm_file_section_copy_info_remove( gf->pi.pathname, vc->section, localhost) == NULL) { return (GFARM_ERR_INCONSISTENT_RECOVERABLE); } } if (fd == -1) return (gfarm_errno_to_error(saved_errno)); vc->ops = &gfs_pio_local_storage_ops; vc->storage_context = NULL; /* not needed */ vc->fd = fd; return (NULL); } static char * gfs_pio_local_mkdir_p(char *canonic_dir) { struct gfs_stat stata; struct stat statb; gfarm_mode_t mode; char *e, *local_path, *user; /* dirname(3) may return '.'. This means the spool root directory. */ if (strcmp(canonic_dir, "/") == 0 || strcmp(canonic_dir, ".") == 0) return (NULL); /* should exist */ e = gfs_stat_canonical_path(canonic_dir, &stata); if (e != NULL) return (e); mode = stata.st_mode; /* * XXX - if the owner of a directory is not the same, create a * directory with permission 0777 - This should be fixed in * the next major release. */ user = gfarm_get_global_username(); if (strcmp(stata.st_user, user) != 0) mode |= 0777; gfs_stat_free(&stata); if (!GFARM_S_ISDIR(mode)) return (GFARM_ERR_NOT_A_DIRECTORY); e = gfarm_path_localize(canonic_dir, &local_path); if (e != NULL) return (e); if (stat(local_path, &statb)) { char *par_dir, *saved_par_dir; mode_t saved_umask; int r; par_dir = saved_par_dir = strdup(canonic_dir); if (par_dir == NULL) { free(local_path); return (GFARM_ERR_NO_MEMORY); } par_dir = dirname(par_dir); e = gfs_pio_local_mkdir_p(par_dir); free(saved_par_dir); if (e != NULL) { free(local_path); return (e); } saved_umask = umask(0); r = mkdir(local_path, mode); umask(saved_umask); if (r == -1) { free(local_path); return (gfarm_errno_to_error(errno)); } } free(local_path); return (NULL); } char * gfs_pio_local_mkdir_parent_canonical_path(char *canonic_dir) { char *par_dir, *saved_par_dir, *local_path, *e; struct stat statb; par_dir = saved_par_dir = strdup(canonic_dir); if (par_dir == NULL) return (GFARM_ERR_NO_MEMORY); par_dir = dirname(par_dir); e = gfarm_path_localize(par_dir, &local_path); if (e != NULL) goto finish_free_par_dir; if (stat(local_path, &statb)) e = gfs_pio_local_mkdir_p(par_dir); else e = GFARM_ERR_ALREADY_EXISTS; free(local_path); finish_free_par_dir: free(saved_par_dir); return (e); } <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_1_0/src/gfarm-zabbix_scripts/externalscripts/zbx_chk_gfsched_gfsd.sh.in #!/bin/sh . @ZABBIX_EXTSCRIPTDIR@/zbx_gfarm_utils.inc # defines CONF_FILE=@ZABBIX_EXTSCRIPTDIR@/zbx_chk_gfarm.conf # check config file if [ -f $CONF_FILE ]; then . $CONF_FILE else echo -1 exit 0 fi # create the temporary file tmpfile=`mktemp` trap "rm -f $tmpfile >/dev/null 2>&1" EXIT gfsched_options="-M" gfsched ${gfsched_options} > $tmpfile if [ $? != 0 ]; then echo "error: gfsched ${gfsched_options} error." exit 0 fi while read prefix gfsdhost port listen_aadress; do grep ${gfsdhost} $tmpfile if [ $? != 0 ]; then echo "error: ${gfsdhost} is not shown on gfsched output." fi done<<EOF `parse_gfsd_confs "$1"` EOF exit 0 <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/gfptool/gfrepbe_client/gfrepbe_client.c #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <gfarm/gfarm.h> #include "xxx_proto.h" #include "io_fd.h" #include "param.h" #include "sockopt.h" #include "auth.h" #include "config.h" #include "gfs_proto.h" #include "gfs_client.h" #define HACK_FOR_BWC char *program_name = "gfrepbe_client"; char *my_name; /* == gfarm_host_get_self_name() */ char *gfrcmd_url = "gfarm:/bin/gfrcmd"; char *gfrep_backend_server_url = "gfarm:/libexec/gfrepbe_server"; long file_sync_rate; struct gfs_client_rep_backend_state *backend = NULL; /* * XXX * The definition of GFREPBE_SERVICE_TAG and gfrepbe_auth_initialize() in * gfrepbe_server.c and gfrepbe_client.c must be factored out. */ #define GFREPBE_SERVICE_TAG "gfarm-replication-backend" char * gfrepbe_auth_initialize(void) { return (gfarm_auth_server_cred_type_set(GFREPBE_SERVICE_TAG, GFARM_AUTH_CRED_TYPE_USER)); } void fatal(void) { if (backend != NULL) { gfs_client_rep_backend_kill(backend); backend = NULL; } /* XXX FIXME: register transfered fragments to metadb */ exit(EXIT_FAILURE); } enum gfs_proto_error write_buffer(int fd, char *buffer, int len, int *disksync_cyclep) { int i, rv; for (i = 0; i < len; i += rv) { rv = write(fd, buffer + i, len - i); if (rv <= 0) { /* * write(2) never returns 0, * so the following rv == 0 case is just warm fuzzy. */ return (rv == 0 ? ENOSPC : gfs_errno_to_proto_error(errno)); } if (file_sync_rate != 0) { *disksync_cyclep += rv; if (*disksync_cyclep >= file_sync_rate) { *disksync_cyclep -= file_sync_rate; fdatasync(fd); } } } return (GFS_ERROR_NOERROR); } #ifdef HAVE_PWRITE enum gfs_proto_error pwrite_buffer(int fd, char *buffer, int len, off_t offset, int *disksync_cyclep) { int i, rv; for (i = 0; i < len; i += rv) { rv = pwrite(fd, buffer + i, len - i, offset + i); if (rv <= 0) { /* * pwrite(2) never returns 0, * so the following rv == 0 case is just warm fuzzy. */ return (rv == 0 ? ENOSPC : gfs_errno_to_proto_error(errno)); } if (file_sync_rate != 0) { *disksync_cyclep += rv; if (*disksync_cyclep >= file_sync_rate) { *disksync_cyclep -= file_sync_rate; fdatasync(fd); } } } return (GFS_ERROR_NOERROR); } #endif /* HAVE_PWRITE */ char * sequential_transfer(int ofd, file_offset_t size, struct xxx_connection *conn, int *disksync_cyclep, gfarm_int32_t *write_resultp) { char *e; int to_be_read, len, rv; gfarm_int32_t write_result = GFS_ERROR_NOERROR; file_offset_t transfered = 0; char buffer[GFS_PROTO_MAX_IOSIZE]; while (transfered < size) { to_be_read = size - transfered < sizeof(buffer) ? size - transfered : sizeof(buffer); e = xxx_read_direct(conn, buffer, to_be_read, &len); if (e != NULL) return (e); if (len == 0) return ("unexpected EOF"); transfered += len; rv = write_buffer(ofd, buffer, len, disksync_cyclep); /* * XXX - we cannot stop here, if write(2) failed, because * currently there is no way to cancel on-going transfer. */ if (write_result == GFS_ERROR_NOERROR) write_result = rv; } *write_resultp = write_result; return (NULL); } char * parallel_async_transfer(int ofd, file_offset_t size, int ndivisions, int interleave_factor, int file_sync_stripe, struct xxx_connection **conns, int *socks, struct gfs_client_rep_transfer_state **transfers, int *disksync_cyclep, gfarm_int32_t *write_resultp) { char *e; int i, len, rv, max_fd, nfound; gfarm_int32_t write_result = GFS_ERROR_NOERROR; char buffer[GFS_PROTO_MAX_IOSIZE]; fd_set readable; /* file_sync_stripe is ignored with this function */ for (;;) { /* prepare `readable' */ FD_ZERO(&readable); max_fd = -1; for (i = 0; i < ndivisions; i++) { if (gfs_client_rep_transfer_finished(transfers[i])) continue; if (socks[i] >= FD_SETSIZE) { /* XXX - use poll? */ fprintf(stderr, "%s: too big fd %d on %s\n", program_name, socks[i], my_name); fatal(); } FD_SET(socks[i], &readable); if (max_fd < socks[i]) max_fd = socks[i]; } if (max_fd == -1) /* completed */ break; do { nfound = select(max_fd + 1, &readable, NULL, NULL, NULL); } while (nfound == -1 && errno == EINTR); if (nfound <= 0) { fprintf(stderr, "%s: parallel_transfer select: %s\n", program_name, nfound < 0 ? strerror(errno) : "assertion failed"); fatal(); } for (i = 0; i < ndivisions; i++) { if (!FD_ISSET(socks[i], &readable)) continue; len = gfs_client_rep_transfer_length(transfers[i], sizeof(buffer)); e = xxx_read_direct(conns[i], buffer, len, &len); if (e != NULL) return (e); if (len == 0) return ("unexpected EOF"); #ifndef HAVE_PWRITE if (lseek(ofd, (off_t) gfs_client_rep_transfer_offset(transfers[i]), SEEK_SET) == -1) return (gfarm_errno_to_error(errno)); rv = write_buffer(ofd, buffer, len, disksync_cyclep); #else rv = pwrite_buffer(ofd, buffer, len, (off_t) gfs_client_rep_transfer_offset(transfers[i]), disksync_cyclep); #endif /* * XXX - we cannot stop here, if write(2) * failed, because currently there is no way * to cancel on-going transfer. */ if (write_result == GFS_ERROR_NOERROR) write_result = rv; gfs_client_rep_transfer_progress(transfers[i], len); } } *write_resultp = write_result; return (NULL); } char * parallel_sync_transfer(int ofd, file_offset_t size, int ndivisions, int interleave_factor, int file_sync_stripe, struct xxx_connection **conns, int *socks, struct gfs_client_rep_transfer_state **transfers, int *disksync_cyclep, gfarm_int32_t *write_resultp) { char *e; int full_stripe_size = ndivisions * interleave_factor; int i, k, len, rv, max_fd, nfound; gfarm_int32_t write_result = GFS_ERROR_NOERROR; file_offset_t transfered; char buffer[GFS_PROTO_MAX_IOSIZE]; fd_set readable; if (interleave_factor == 0) return ("interleave_factor == 0 doesn't make sense " "for parallel_sync_transfer"); k = 0; for (transfered = 0; transfered < size; ){ /* prepare `readable' */ FD_ZERO(&readable); max_fd = -1; for (i = 0; i < ndivisions; i++) { if (gfs_client_rep_transfer_stripe_finished( transfers[i])) continue; if (socks[i] >= FD_SETSIZE) { /* XXX - use poll? */ fprintf(stderr, "%s: too big fd %d on %s\n", program_name, socks[i], my_name); fatal(); } FD_SET(socks[i], &readable); if (max_fd < socks[i]) max_fd = socks[i]; } if (max_fd == -1) { /* full_stripe_finished */ transfered += full_stripe_size; for (i = 0; i < ndivisions; i++) gfs_client_rep_transfer_stripe_next( transfers[i]); if (file_sync_stripe > 0) { if (++k >= file_sync_stripe) { fdatasync(ofd); k = 0; } } continue; } do { nfound = select(max_fd + 1, &readable, NULL, NULL, NULL); } while (nfound == -1 && errno == EINTR); if (nfound <= 0) { fprintf(stderr, "%s: parallel_transfer select: %s\n", program_name, nfound < 0 ? strerror(errno) : "assertion failed"); fatal(); } for (i = 0; i < ndivisions; i++) { if (!FD_ISSET(socks[i], &readable)) continue; len = gfs_client_rep_transfer_length(transfers[i], sizeof(buffer)); e = xxx_read_direct(conns[i], buffer, len, &len); if (e != NULL) return (e); if (len == 0) return ("unexpected EOF"); #ifndef HAVE_PWRITE if (lseek(ofd, (off_t) gfs_client_rep_transfer_offset(transfers[i]), SEEK_SET) == -1) return (gfarm_errno_to_error(errno)); rv = write_buffer(ofd, buffer, len, disksync_cyclep); #else rv = pwrite_buffer(ofd, buffer, len, (off_t) gfs_client_rep_transfer_offset(transfers[i]), disksync_cyclep); #endif /* * XXX - we cannot stop here, if write(2) * failed, because currently there is no way * to cancel on-going transfer. */ if (write_result == GFS_ERROR_NOERROR) write_result = rv; gfs_client_rep_transfer_stripe_progress(transfers[i], len); } } *write_resultp = write_result; return (NULL); } char * transfer(int ofd, file_offset_t size, int ndivisions, int interleave_factor, int file_sync_stripe, int recv_stripe_sync, struct xxx_connection **conns, int *socks, int *disksync_cyclep, gfarm_int32_t *write_resultp) { char *e; struct gfs_client_rep_transfer_state **transfers; ndivisions = gfs_client_rep_limit_division( GFS_CLIENT_REP_ALGORITHM_LATEST, ndivisions, size); if (ndivisions == -1) return ("unknown algorithm version"); if (ndivisions == 1) return (sequential_transfer(ofd, size, conns[0], disksync_cyclep, write_resultp)); e = gfs_client_rep_transfer_state_alloc(size, GFS_CLIENT_REP_ALGORITHM_LATEST, ndivisions, interleave_factor, &transfers); if (e != NULL) return (e); e = (*(recv_stripe_sync?parallel_sync_transfer:parallel_async_transfer) )(ofd, size, ndivisions, interleave_factor, file_sync_stripe, conns, socks, transfers, disksync_cyclep, write_resultp); gfs_client_rep_transfer_state_free(ndivisions, transfers); return (e); } int try_to_make_parent_dir(char *pathname) { char *e, *p, *parent, *dirbuf; int rv, dirlen; gfarm_mode_t mode; struct stat st; struct gfarm_path_info pi; parent = strdup(pathname); if (parent == NULL) /* give up */ return (0); /* get parent directory */ p = (char *)gfarm_path_dir_skip(parent); while (p > parent && p[-1] == '/') *--p = '\0'; if (p == parent) { /* no directory part */ free(parent); return (0); } if (stat(parent, &st) == 0) { /* parent directory already exists */ free(parent); return (0); } dirbuf = strdup(parent); if (dirbuf == NULL) { free(parent); return (0); } for (dirlen = 0;;) { dirlen += strcspn(parent + dirlen, "/"); memcpy(dirbuf, parent, dirlen); dirbuf[dirlen] = '\0'; if (stat(dirbuf, &st) == 0) { if (!S_ISDIR(st.st_mode)) { free(dirbuf); free(parent); return (0); } } else { e = gfarm_path_info_get(dirbuf, &pi); mode = pi.status.st_mode; if (e != NULL || !GFARM_S_ISDIR(mode)) { if (e == NULL) gfarm_path_info_free(&pi); free(dirbuf); free(parent); return (0); } mode &= GFARM_S_ALLPERM; if (strcmp(pi.status.st_user, gfarm_get_global_username()) != 0) { mode |= 0777; } gfarm_path_info_free(&pi); rv = mkdir(dirbuf, mode); if (rv == -1) { free(dirbuf); free(parent); return (0); } } dirlen += strspn(parent + dirlen, "/"); if (parent[dirlen] == '\0') { /* OK, made */ free(dirbuf); free(parent); return (1); } } } void session(char *server_name, struct sockaddr *server_addr, struct xxx_connection *from_server, struct xxx_connection *to_server, char *my_canonical_name, int ndivisions, int interleave_factor, int file_sync_stripe, int recv_stripe_sync, int n, gfarm_stringlist *files, gfarm_stringlist *sections, struct gfarm_path_info *path_infos, gfarm_int32_t *results) { char *e, *pathname; int i, eof, ofd, mode; gfarm_int32_t r, port; int *socks, disksync_cycle = 0; struct xxx_connection **conns; struct sockaddr_in *sin = (struct sockaddr_in *)server_addr; file_offset_t size; #ifdef __GNUC__ /* workaround gcc warning: might be used uninitialized */ ofd = -1; #endif socks = malloc(sizeof(*socks) * ndivisions); conns = malloc(sizeof(*conns) * ndivisions); if (socks == NULL || conns == NULL) { fprintf(stderr, "%s: no memory for %d connections to %s on %s\n", program_name, ndivisions, server_name, my_name); fatal(); } /* * XXX FIXME: this port may be blocked by firewall. * This should be implemented via gfsd connection passing service. */ e = xxx_proto_recv(from_server, 0, &eof, "i", &port); if (e != NULL || eof) { fprintf(stderr, "%s: while reading port number from %s on %s: %s\n", program_name, server_name, my_name, e != NULL ? e : "unexpected EOF"); fatal(); } sin->sin_port = htons(port); /* sanity */ for (i = 0; i < ndivisions; i++) socks[i] = -1; /* XXX FIXME: make connections in parallel */ for (i = 0; i < ndivisions; i++) { struct xxx_connection *tmp_conn; int tmp_sock; gfarm_int32_t index; tmp_sock = socket(PF_INET, SOCK_STREAM, 0); if (tmp_sock == -1) { fprintf(stderr, "%s: while opening sockets on %s: %s\n", program_name, my_name, strerror(errno)); fatal(); } /* XXX FIXME canonical_name? */ e = gfarm_sockopt_apply_by_name_addr(tmp_sock, server_name, server_addr); if (e != NULL) { fprintf(stderr, "%s: setsockopt to %s on %s: %s\n", program_name, server_name, my_name, e); } if (connect(tmp_sock, server_addr, sizeof(*server_addr))== -1){ fprintf(stderr, "%s: while connecting to %s on %s: %s\n", program_name, server_name, my_name, e); fatal(); } /* XXX read-only connection */ e = xxx_fd_connection_new(tmp_sock, &tmp_conn); if (e != NULL) { fprintf(stderr, "%s: while allocating memory to %s on %s: %s\n", program_name, server_name, my_name, e); fatal(); } e = gfarm_auth_request(tmp_conn, GFREPBE_SERVICE_TAG, server_name, server_addr, NULL); if (e != NULL) { fprintf(stderr, "%s: authorization request to %s on %s: %s\n", program_name, server_name, my_name, e); fatal(); } /* XXX call shutdown(2) here? */ e = xxx_proto_recv(tmp_conn, 1, &eof, "i", &index); if (e != NULL || eof) { fprintf(stderr, "%s: while reading port index from %s on %s: %s\n", program_name, server_name, my_name, e != NULL ? e : "unexpected EOF"); fatal(); } if (index < 0 || index >= n) { fprintf(stderr, "%s: invalid port index %d from %s on %s\n", program_name, index, server_name, my_name); fatal(); } /* sanity */ if (socks[index] != -1) { fprintf(stderr, "%s: duplicate port index %d from %s on %s\n", program_name, index, server_name, my_name); fatal(); } socks[index] = tmp_sock; conns[index] = tmp_conn; } for (i = 0; i < n; i++) { char *file = gfarm_stringlist_elem(files, i); char *section = gfarm_stringlist_elem(sections, i); /* NOTE: assumes current directory == spool_root */ if (*section == '\0') { pathname = file; } else { pathname = malloc(strlen(file) + strlen(section) + 2); if (pathname == NULL) { fprintf(stderr, "%s: no memory for pathname %s:%s" " to replicate it from %s to %s\n", program_name, file, section, server_name, my_name); fatal(); } sprintf(pathname, "%s:%s", file, section); } /* NOTE: just==TRUE here */ e = xxx_proto_recv(conns[0], 1, &eof, "i", &r); if (e != NULL || eof) { fprintf(stderr, "%s: while reading status " "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, e != NULL ? e : "unexpected EOF"); fatal(); } if (r != GFS_ERROR_NOERROR) { if (results[i] == GFS_ERROR_NOERROR) results[i] = r; fprintf(stderr, "%s: replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, gfs_proto_error_string(r)); if (*section != '\0') free(pathname); continue; } /* NOTE: just==TRUE here */ e = xxx_proto_recv(conns[0], 1, &eof, "o", &size); if (e != NULL || eof) { fprintf(stderr, "%s: while reading file size " "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, e != NULL ? e : "unexpected EOF"); fatal(); } /* XXX FIXME - FT! */ /* XXX FIXME - owner! */ /* XXX FIXME - mode! */ if (results[i] == GFS_ERROR_NOERROR) { mode = (path_infos[i].status.st_mode & GFARM_S_ALLPERM); /* * XXX FIXME * if the owner of a file is not the same, * permit a group/other write access - This * should be fixed in the next major release. */ if (strcmp(path_infos[i].status.st_user, gfarm_get_global_username()) != 0) { /* don't allow setuid/setgid */ mode = (mode | 022) & 0777; } ofd = open(pathname, O_CREAT|O_WRONLY, mode); /* FT */ if (ofd == -1 && try_to_make_parent_dir(pathname)) ofd = open(pathname, O_CREAT|O_WRONLY, mode); if (ofd == -1) { results[i] = gfs_errno_to_proto_error(errno); fprintf(stderr, "%s: cannot create file" "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, strerror(errno)); } } if (results[i] != GFS_ERROR_NOERROR) { /* XXX FIXME: just waste. detect this error before */ ofd = open("/dev/null", O_WRONLY); if (ofd == -1) { fprintf(stderr, "%s: cannot open /dev/null" "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, strerror(errno)); fatal(); } } e = transfer(ofd, size, ndivisions, interleave_factor, file_sync_stripe, recv_stripe_sync, conns, socks, &disksync_cycle, &r); if (e != NULL) { fprintf(stderr, "%s: while replicating %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, e); fatal(); } if (r != GFS_ERROR_NOERROR) { if (results[i] == GFS_ERROR_NOERROR) results[i] = r; fprintf(stderr, "%s: while writing contents " "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, gfs_proto_error_string(r)); } /* NOTE: just==TRUE here */ e = xxx_proto_recv(conns[0], 1, &eof, "i", &r); if (e != NULL || eof) { fprintf(stderr, "%s: while reading status " "to replicate %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, e != NULL ? e : "unexpected EOF"); fatal(); } if (r != GFS_ERROR_NOERROR) { if (results[i] == GFS_ERROR_NOERROR) results[i] = r; fprintf(stderr, "%s: replicated %s from %s to %s: %s\n", program_name, pathname, server_name, my_name, gfs_proto_error_string(r)); } #ifndef HACK_FOR_BWC /* register metadata */ if (results[i] == GFS_ERROR_NOERROR) { struct gfarm_file_section_copy_info fci; e = gfarm_file_section_copy_info_set(file, section, my_canonical_name, &fci); if (e != NULL) results[i] = gfs_string_to_proto_error(e); } #endif if (results[i] != GFS_ERROR_NOERROR) unlink(pathname); close(ofd); if (*section != '\0') free(pathname); } for (i = 0; i < ndivisions; i++) xxx_connection_free(conns[i]); free(conns); free(socks); } void usage(void) { fprintf(stderr, "Usage: %s [-p] " "[-i interleave_factor] [-n <ndivisions>] <server_name>\n", program_name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { gfarm_int32_t interleave_factor = 0; gfarm_int32_t ndivisions = 1; int recv_stripe_sync = 0; int send_stripe_sync = 0; int file_sync_stripe = 0; struct xxx_connection *from_frontend, *to_frontend; struct xxx_connection *from_server, *to_server; char *e, *src_host, *my_canonical_name; char **gfrcmd_paths, **gfrep_backend_server_paths; int c, i, n, replication_method_save; gfarm_stringlist files, sections; struct gfarm_path_info *path_infos; gfarm_int32_t *results; struct sockaddr server_addr; e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm_initialize on %s: %s\n", program_name, my_name, e); fatal(); } e = gfrepbe_auth_initialize(); if (e != NULL) { fprintf(stderr, "gfarm_auth_initialize: %s\n", e); exit(1); } while ((c = getopt(argc, argv, "i:n:rsS:")) != -1) { switch (c) { case 'i': interleave_factor = atoi(optarg); break; case 'n': ndivisions = atoi(optarg); break; case 'r': recv_stripe_sync = 1; break; case 's': send_stripe_sync = 1; break; case 'S': file_sync_stripe = atoi(optarg); break; default: fprintf(stderr, "%s: unknown option -%c\n", program_name, c); usage(); /*NOTREACHED*/ } } argc -= optind; argv += optind; my_name = gfarm_host_get_self_name(); if (argc != 1) { fprintf(stderr, "%s: missing server name argument on %s\n", program_name, my_name); usage(); /*NOTREACHED*/ } src_host = argv[0]; e = gfarm_host_get_canonical_self_name(&my_canonical_name); if (e != NULL) { fprintf(stderr, "%s: host %s isn't a filesystem node: %s\n", program_name, my_name, e); fatal(); } replication_method_save = gfarm_replication_get_method(); gfarm_replication_set_method(GFARM_REPLICATION_BOOTSTRAP_METHOD); e = gfarm_url_program_deliver(gfrcmd_url, 1, &my_canonical_name, &gfrcmd_paths); if (e != NULL) { fprintf(stderr, "%s: cannot deliver %s to host %s on %s: %s\n", program_name, gfrcmd_url, my_canonical_name, my_name, e); fatal(); } e = gfarm_url_program_deliver(gfrep_backend_server_url, 1, &src_host, &gfrep_backend_server_paths); if (e != NULL) { fprintf(stderr, "%s: cannot deliver %s to host %s on %s: %s\n", program_name, gfrep_backend_server_url, src_host, my_name, e); fatal(); } gfarm_replication_set_method(replication_method_save); e = gfs_client_rep_backend_invoke( src_host, gfrcmd_paths[0], gfrep_backend_server_paths[0], NULL, GFS_CLIENT_REP_ALGORITHM_LATEST, ndivisions, interleave_factor, 0, send_stripe_sync, 0, program_name, &from_server, &to_server, &backend); if (e != NULL) fatal(); e = gfarm_host_address_get(src_host, 0, &server_addr, NULL); if (e != NULL) { fprintf(stderr, "%s: %s: %s\n", program_name, src_host, e); fatal(); } e = gfarm_netparam_config_get_long(&gfarm_netparam_file_sync_rate, src_host, (struct sockaddr *)&server_addr, &file_sync_rate); if (e != NULL) {/* shouldn't happen */ fprintf(stderr, "%s: get netparam file_sync_rate on %s (%s): %s\n", program_name, my_name, src_host, e); fatal(); } /* XXX read-only connection */ e = xxx_fd_connection_new(STDIN_FILENO, &from_frontend); if (e != NULL) { fprintf(stderr, "%s: %s for stdin\n", program_name, e); fatal(); } /* XXX write-only connection */ e = xxx_fd_connection_new(STDOUT_FILENO, &to_frontend); if (e != NULL) { fprintf(stderr, "%s: %s for stdout\n", program_name, e); fatal(); } e = gfs_client_rep_filelist_receive(from_frontend, &n, &files, &sections, program_name); if (e != NULL) fatal(); e = gfs_client_rep_filelist_send(src_host, to_server, program_name, n, &files, &sections); if (e != NULL) fatal(); results = malloc(sizeof(*results) * n); if (results == NULL) { fprintf(stderr, "%s: no memory for %d ints on %s\n", program_name, n, my_name); fatal(); } /* make current directory == spool_root */ if (chdir(gfarm_spool_root) == -1) { fprintf(stderr, "%s: chdir(%s) on %s: %s\n", program_name, gfarm_spool_root, my_name, e); fatal(); } path_infos = malloc(sizeof(*path_infos) * n); if (results == NULL) { fprintf(stderr, "%s: no memory for %d path_info on %s\n", program_name, n, my_name); fatal(); } for (i = 0; i < n; i++) { e = gfarm_path_info_get(gfarm_stringlist_elem(&files, i), &path_infos[i]); results[i] = e == NULL ? GFS_ERROR_NOERROR : gfs_string_to_proto_error(e); } umask(0); /* don't mask, just use the 3rd parameter of open(2) */ session(src_host, &server_addr, from_server, to_server, my_canonical_name, ndivisions, interleave_factor, file_sync_stripe, recv_stripe_sync, n, &files, &sections, path_infos, results); #ifdef HACK_FOR_BWC /* * If this program fails with fatal(), or is killed by a signal, * this metadata update isn't executed. (So, #undef HACK_FOR_BWC) */ for (i = 0; i < n; i++) { char *file = gfarm_stringlist_elem(&files, i); char *section = gfarm_stringlist_elem(&sections, i); struct gfarm_file_section_copy_info fci; if (results[i] == GFS_ERROR_NOERROR) { e = gfarm_file_section_copy_info_set(file, section, my_canonical_name, &fci); if (e != NULL) results[i] = gfs_string_to_proto_error(e); } } #endif for (i = 0; i < n; i++) xxx_proto_send(to_frontend, "i", results[i]); xxx_proto_flush(to_frontend); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: gfarm_terminate on %s: %s\n", program_name, my_name, e); fatal(); } return (0); } <file_sep>/gfarm/tags/gfarm_1_0_3_rc3/gftool/gfwhoami/gfwhoami.c /* * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <unistd.h> #include <gfarm/gfarm.h> #include "auth.h" char *program_name = "gfwhoami"; #ifdef HAVE_GSI #define GFWHOAMI_OPTIONS "hv" #else #define GFWHOAMI_OPTIONS "h" #endif void usage(void) { fprintf(stderr, "Usage: %s [-" GFWHOAMI_OPTIONS "]\n", program_name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { char *e; int c; extern char *optarg; #ifdef HAVE_GSI int verbose_flag = 0; #endif if (argc > 0) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(EXIT_FAILURE); } while ((c = getopt(argc, argv, GFWHOAMI_OPTIONS)) != -1) { switch (c) { #ifdef HAVE_GSI case 'v': verbose_flag = 1; break; #endif case 'h': default: usage(); } } if (argc - optind > 0) usage(); printf("%s", gfarm_get_global_username()); #ifdef HAVE_GSI if (verbose_flag == 1) printf(" %s", gfarm_gsi_client_cred_name()); #endif printf("\n"); return (0); } <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/doc/Makefile top_builddir = .. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk SUBDIRS = html DOC = ../INSTALL.en ../INSTALL.ja ../LICENSE ../RELNOTES \ ../INSTALL.RPM.en ../INSTALL.RPM.ja \ GUIDE.ja Gfarm-FAQ.en Gfarm-FAQ.ja README.hook.en include $(top_srcdir)/makes/subdir.mk install: @for i in -- $(DOC); do \ case $$i in --) continue;; esac; \ ( set -x; \ $(INSTALL_DATA) $(srcdir)/$${i} $(docdir)/`basename $${i}` \ ); \ done <file_sep>/gfarm/tags/gfarm_1_0_beta_2_rev_2/lib/libgfarm/gfarm/gfs_pio_misc.c /* * $Id$ */ #include <sys/types.h> #include <sys/socket.h> /* struct sockaddr */ #include <sys/stat.h> #include <sys/wait.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <openssl/evp.h> #include <gfarm/gfarm.h> #include "host.h" #include "gfs_proto.h" /* for gfs_digest_calculate_local() */ #include "gfs_client.h" #include "gfs_pio.h" #include "schedule.h" char * gfs_stat_section(char *gfarm_url, char *section, struct gfs_stat *s) { char *e, *gfarm_file; struct gfarm_file_section_info sinfo; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } *s = pi.status; s->st_user = strdup(s->st_user); s->st_group = strdup(s->st_group); gfarm_path_info_free(&pi); if (!GFARM_S_ISREG(s->st_mode)) { free(gfarm_file); return (NULL); } e = gfarm_file_section_info_get(gfarm_file, section, &sinfo); free(gfarm_file); if (e != NULL) return (e); s->st_size = sinfo.filesize; s->st_nsections = 1; gfarm_file_section_info_free(&sinfo); return (NULL); } char * gfs_stat_index(char *gfarm_url, int index, struct gfs_stat *s) { char section[GFARM_INT32STRLEN + 1]; sprintf(section, "%d", index); return (gfs_stat_section(gfarm_url, section, s)); } char * gfs_fstat(GFS_File gf, struct gfs_stat *status) { return ((*gf->ops->view_stat)(gf, status)); } char * gfs_access(char *gfarm_url, int mode) { char *e, *gfarm_file; struct gfarm_path_info pi; int nsections; struct gfarm_file_section_info *sections; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } /* * Check whether the gfarm_url can be accessible by other * processes or not. * * XXX - temporal solution until file locking will be implemented. */ e = gfarm_file_section_info_get_all_by_file(gfarm_file, &nsections, &sections); free(gfarm_file); if (e != NULL) { return (e); } gfarm_file_section_info_free_all(nsections, sections); if (!GFARM_S_IS_PROGRAM(pi.status.st_mode) && nsections != pi.status.st_nsections) return (GFARM_ERR_FRAGMENT_NUMBER_DOES_NOT_MATCH); e = gfarm_path_info_access(&pi, mode); gfarm_path_info_free(&pi); return (e); } /* * */ static char * digest_calculate(char *filename, char **digest_type, char *digest_string, unsigned *md_len_p, file_offset_t *filesizep) { int fd, i, rv; EVP_MD_CTX md_ctx; unsigned char md_value[EVP_MAX_MD_SIZE]; char buffer[GFS_FILE_BUFSIZE]; if ((fd = open(filename, O_RDONLY)) == -1) return (gfarm_errno_to_error(errno)); EVP_DigestInit(&md_ctx, GFS_DEFAULT_DIGEST_MODE); rv = gfs_digest_calculate_local( fd, buffer, GFS_FILE_BUFSIZE, GFS_DEFAULT_DIGEST_MODE, &md_ctx, md_len_p, md_value, filesizep); close(fd); if (rv != 0) return (gfarm_errno_to_error(rv)); for (i = 0; i < *md_len_p; i++) sprintf(&digest_string[i + i], "%02x", md_value[i]); *digest_type = GFS_DEFAULT_DIGEST_NAME; return (NULL); } /* * Register a gfarm fragment to a Meta DB. This function is intended * to be used with legacy applications to register a new file. */ char * gfs_pio_set_fragment_info_local(char *filename, char *gfarm_file, char *section) { char *digest_type; char digest_value_string[EVP_MAX_MD_SIZE * 2 + 1]; unsigned int digest_len; file_offset_t filesize; char *e = NULL; struct gfarm_file_section_info fi; struct gfarm_file_section_copy_info fci; /* Calculate checksum. */ e = digest_calculate(filename, &digest_type, digest_value_string, &digest_len, &filesize); if (e != NULL) return (e); /* Update the filesystem metadata. */ e = gfarm_file_section_info_get(gfarm_file, section, &fi); if (e == GFARM_ERR_NO_SUCH_OBJECT) { fi.filesize = filesize; fi.checksum_type = digest_type; fi.checksum = digest_value_string; e = gfarm_file_section_info_set(gfarm_file, section, &fi); if (e != NULL) return (e); } else if (e == NULL) { if (fi.filesize != filesize) return "file size mismatch"; if (strcasecmp(fi.checksum_type, digest_type) != 0) return "checksum type mismatch"; if (strcasecmp(fi.checksum,digest_value_string) != 0) return "check sum mismatch"; gfarm_file_section_info_free(&fi); } else return (e); e = gfarm_host_get_canonical_self_name(&fci.hostname); if (e == NULL) { e = gfarm_file_section_copy_info_set( gfarm_file, section, fci.hostname, &fci); } return (e); } /* * `srchost' must already reflect "address_use" directive. */ static char * gfarm_file_section_replicate_from_to_internal( char *gfarm_file, char *section, gfarm_mode_t mode, file_offset_t file_size, char *src_canonical_hostname, char *src_if_hostname, char *dsthost) { char *e, *path_section; struct gfarm_file_section_copy_info ci; struct gfs_connection *gfs_server; struct sockaddr peer_addr; e = gfarm_host_get_canonical_name(dsthost, &ci.hostname); if (e != NULL) goto finish; if (gfarm_file_section_copy_info_does_exist(gfarm_file, section, ci.hostname)) /* already exists, don't have to replicate */ goto finish_hostname; e = gfarm_path_section(gfarm_file, section, &path_section); if (e != NULL) goto finish_hostname; e = gfarm_host_address_get(dsthost, gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) goto finish_path_section; e = gfs_client_connect(ci.hostname, &peer_addr, &gfs_server); if (e != NULL) goto finish_path_section; e = gfs_client_replicate_file(gfs_server, path_section, mode, file_size, src_canonical_hostname, src_if_hostname); gfs_client_disconnect(gfs_server); if (e != NULL) goto finish_path_section; e = gfarm_file_section_copy_info_set(gfarm_file, section, ci.hostname, &ci); finish_path_section: free(path_section); finish_hostname: free(ci.hostname); finish: return (e); } static char * gfarm_file_section_replicate_to_internal(char *gfarm_file, char *section, gfarm_mode_t mode, file_offset_t file_size, char *dsthost) { char *e, *srchost, *if_hostname; struct sockaddr peer_addr; e = gfarm_file_section_host_schedule(gfarm_file, section, &srchost); if (e != NULL) goto finish; /* reflect "address_use" directive in the `srchost' */ e = gfarm_host_address_get(srchost, gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_srchost; e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section, mode & GFARM_S_ALLPERM, file_size, srchost, if_hostname, dsthost); free(if_hostname); finish_srchost: free(srchost); finish: return (e); } char * gfarm_url_section_replicate_from_to(char *gfarm_url, char *section, char *srchost, char *dsthost) { char *e, *gfarm_file, *canonical_hostname, *if_hostname; struct sockaddr peer_addr; struct gfarm_path_info pi; struct gfarm_file_section_info si; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish; e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; e = gfarm_file_section_info_get(gfarm_file, section, &si); if (e != NULL) goto finish_path_info; e = gfarm_host_get_canonical_name(srchost, &canonical_hostname); if (e != NULL) goto finish_canonical_hostname; /* reflect "address_use" directive in the `srchost' */ e = gfarm_host_address_get(srchost, gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_section_info; e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section, pi.status.st_mode & GFARM_S_ALLPERM, si.filesize, canonical_hostname, if_hostname, dsthost); free(if_hostname); finish_canonical_hostname: free(canonical_hostname); finish_section_info: gfarm_file_section_info_free(&si); finish_path_info: gfarm_path_info_free(&pi); finish_gfarm_file: free(gfarm_file); finish: return (e); } char * gfarm_url_section_replicate_to(char *gfarm_url, char *section, char *dsthost) { char *e, *gfarm_file; struct gfarm_path_info pi; struct gfarm_file_section_info si; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish; e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; e = gfarm_file_section_info_get(gfarm_file, section, &si); if (e != NULL) goto finish_path_info; e = gfarm_file_section_replicate_to_internal( gfarm_file, section, pi.status.st_mode & GFARM_S_ALLPERM, si.filesize, dsthost); gfarm_file_section_info_free(&si); finish_path_info: gfarm_path_info_free(&pi); finish_gfarm_file: free(gfarm_file); finish: return (e); } char * gfarm_url_program_register(char *gfarm_url, char *architecture, char *filename, int nreplicas) { char *e, *e_save = NULL, *if_hostname, *gfarm_file; int nhosts, fd, i; struct gfarm_host_info *hosts; struct sockaddr peer_addr; size_t rv; int length; /* XXX - should be size_t */ GFS_File gf; struct stat s; char buffer[GFS_FILE_BUFSIZE]; char *self_name; char **hostnames; if (stat(filename, &s) == -1) return (gfarm_errno_to_error(errno)); if (!GFARM_S_IS_PROGRAM(s.st_mode)) return (GFARM_ERR_OPERATION_NOT_PERMITTED); /* XXX - use better strategy for the replication */ e = gfarm_host_info_get_allhost_by_architecture(architecture, &nhosts, &hosts); if (e == GFARM_ERR_NO_SUCH_OBJECT) return ("gfarm_url_program_register(): no such architecture"); if (e != NULL) goto finish; hostnames = malloc(sizeof(char *) * nhosts); if (hostnames == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_host_info; } for (i = 0; i < nhosts; i++) hostnames[i] = hosts[i].hostname; if (nhosts < nreplicas) nreplicas = nhosts; if (gfarm_host_get_canonical_self_name(&self_name) != NULL) { e = gfarm_schedule_search_idle_hosts(nhosts, hostnames, nreplicas, hostnames); } else { /* give the top priority to self host */ char * tmp; for (i = 0; i < nhosts; i++) if (strcmp(hostnames[i], self_name) == 0) break; if (i != 0 && i < nhosts) { tmp = hostnames[0]; hostnames[0] = hostnames[i]; hostnames[i] = tmp; } if (nreplicas > 1) e = gfarm_schedule_search_idle_hosts(nhosts - 1, hostnames + 1, nreplicas - 1, hostnames + 1); } if (e != NULL) goto finish_hostnames; /* reflect "address_use" directive in the `hostnames[0]' */ e = gfarm_host_address_get(hostnames[0], gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) goto finish_hostnames; /* * register the program */ fd = open(filename, O_RDONLY); if (fd == -1) { e = "gfarm_url_program_register(): can't open program"; goto finish_if_hostname; } /* XXX - overwrite case */ e = gfs_pio_create(gfarm_url, GFARM_FILE_WRONLY, s.st_mode & GFARM_S_ALLPERM, &gf); if (e != NULL) { close(fd); goto finish_if_hostname; } /* XXX - better strategy to select replica */ e = gfs_pio_set_view_section(gf, architecture, if_hostname, 0); if (e != NULL) { /* XXX - take care of the case where node is down */ gfs_pio_close(gf); close(fd); goto finish_if_hostname; } for (;;) { rv = read(fd, buffer, sizeof(buffer)); if (rv <= 0) break; /* XXX - partial write case ? */ e = gfs_pio_write(gf, buffer, rv, &length); if (e != NULL) break; } e_save = e; e = gfs_pio_close(gf); close(fd); if (e_save != NULL) e = e_save; if (e != NULL) goto finish_if_hostname; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) goto finish_if_hostname; /* * replicate the program */ for (i = 1; i < nreplicas; i++) { /* XXX - better strategy to select replica */ e = gfarm_file_section_replicate_from_to_internal( gfarm_file, architecture, s.st_mode & GFARM_S_ALLPERM, s.st_size, hostnames[0], if_hostname, hostnames[i]); if (e != NULL) e_save = e; } e = NULL; /* there is at least on copy available. */ /* XXX - partial error case? */ free(gfarm_file); finish_if_hostname: free(if_hostname); finish_hostnames: free(hostnames); finish_host_info: gfarm_host_info_free_all(nhosts, hosts); finish: return (e); } char * gfarm_url_program_deliver(const char *gfarm_url, int nhosts, char **hosts, char ***delivered_paths) { char *e, **dp, *gfarm_file, *root, *arch, **canonical_hostnames; gfarm_mode_t mode; int i; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) { free(gfarm_file); return (e); } mode = pi.status.st_mode; gfarm_path_info_free(&pi); if (!GFARM_S_IS_PROGRAM(mode)) return ("gfarm_url_program_deliver(): not a program"); dp = malloc(sizeof(char *) * (nhosts + 1)); if (dp == NULL) { free(gfarm_file); return (GFARM_ERR_NO_MEMORY); } dp[nhosts] = NULL; e = gfarm_host_get_canonical_names(nhosts, hosts, &canonical_hostnames); if (e != NULL) { free(dp); free(gfarm_file); return (e); } /* XXX - this is too slow */ for (i = 0; i < nhosts; i++) { struct sockaddr peer_addr; struct gfs_connection *gfs_server; struct gfarm_file_section_info si; dp[i] = NULL; /* for error handling */ arch = gfarm_host_info_get_architecture_by_host( canonical_hostnames[i]); if (arch == NULL) { /* architecture of the hosts[i] is not registered */ e = "cannot deliver program to an unregistered host"; goto error; } /* XXX - which to use? `hosts[i]' vs `copies[j].hostname' */ e = gfarm_host_address_get(hosts[i], gfarm_spool_server_port, &peer_addr, NULL); if (e != NULL) { free(arch); goto error; } e = gfs_client_connection(canonical_hostnames[i], &peer_addr, &gfs_server); if (e != NULL) { free(arch); goto error; } e = gfs_client_get_spool_root(gfs_server, &root); if (e != NULL) { free(arch); goto error; } e = gfarm_full_path_file_section(root, gfarm_file, arch, &dp[i]); free(root); if (e != NULL) { free(arch); goto error; } e = gfarm_file_section_info_get(gfarm_file, arch, &si); if (e != NULL) { free(arch); goto error; } /* * replicate the program */ e = gfarm_file_section_replicate_to_internal(gfarm_file, arch, mode & GFARM_S_ALLPERM, si.filesize, hosts[i]); gfarm_file_section_info_free(&si); free(arch); if (e != NULL) goto error; } gfarm_strings_free_deeply(nhosts, canonical_hostnames); free(gfarm_file); *delivered_paths = dp; return (NULL); error: gfarm_strings_free_deeply(nhosts, canonical_hostnames); free(gfarm_file); gfarm_strings_free_deeply(i + 1, dp); *delivered_paths = NULL; return (e); } char * gfarm_url_fragments_replicate(char *gfarm_url, int ndsthosts, char **dsthosts) { char *e, *gfarm_file, **srchosts, **edsthosts; int nsrchosts; gfarm_mode_t mode; int i, pid, *pids; struct gfarm_path_info pi; e = gfarm_url_make_path(gfarm_url, &gfarm_file); if (e != NULL) return (e); e = gfarm_path_info_get(gfarm_file, &pi); if (e != NULL) goto finish_gfarm_file; mode = pi.status.st_mode; gfarm_path_info_free(&pi); if (!GFARM_S_IS_FRAGMENTED_FILE(mode)) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto finish_gfarm_file; } e = gfarm_url_hosts_schedule(gfarm_url, "", &nsrchosts, &srchosts); if (e != NULL) goto finish_gfarm_file; e = gfarm_hosts_schedule_expand_cyclic(nsrchosts, &edsthosts, ndsthosts, dsthosts); if (e != NULL) goto finish_srchosts; pids = malloc(sizeof(int) * nsrchosts); if (pids == NULL) { e = GFARM_ERR_NO_MEMORY; goto finish_edsthosts; } /* * To use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_terminate(); if (e != NULL) goto finish_pids; for (i = 0; i < nsrchosts; i++) { struct sockaddr peer_addr; char *if_hostname; char section_string[GFARM_INT32STRLEN + 1]; struct gfarm_file_section_info si; pid = fork(); if (pid < 0) break; if (pid) { /* parent */ pids[i] = pid; continue; } /* child */ /* * use different connection for each metadb access. * * XXX: FIXME layering violation */ e = gfarm_metadb_initialize(); if (e != NULL) _exit(1); /* reflect "address_use" directive in the `srchosts[i]' */ e = gfarm_host_address_get(srchosts[i], gfarm_spool_server_port, &peer_addr, &if_hostname); if (e != NULL) _exit(2); sprintf(section_string, "%d", i); e = gfarm_file_section_info_get(gfarm_file, section_string, &si); if (e != NULL) _exit(3); e = gfarm_file_section_replicate_from_to_internal( gfarm_file, section_string, mode & GFARM_S_ALLPERM, si.filesize, srchosts[i], if_hostname, edsthosts[i]); if (e != NULL) _exit(1); _exit(0); } while (--i >= 0) { int rv, s; while ((rv = waitpid(pids[i], &s, 0)) == -1 && errno == EINTR) ; if (rv == -1) { if (e == NULL) e = gfarm_errno_to_error(errno); } else if (WIFEXITED(s) && WEXITSTATUS(s) != 0) { e = "error happens on replication"; } } /* * recover temporary closed metadb connection * * XXX: FIXME layering violation */ if (e != NULL) { gfarm_metadb_initialize(); } else { e = gfarm_metadb_initialize(); } finish_pids: free(pids); finish_edsthosts: free(edsthosts); finish_srchosts: gfarm_strings_free_deeply(nsrchosts, srchosts); finish_gfarm_file: free(gfarm_file); return (e); } char * gfarm_url_fragments_replicate_to_domainname(char *gfarm_url, const char *domainname) { char *e, **dsthosts; int nfrags; e = gfarm_url_fragment_number(gfarm_url, &nfrags); if (e != NULL) return (e); dsthosts = malloc(nfrags * sizeof(char *)); if (dsthosts == NULL) return (GFARM_ERR_NO_MEMORY); e = gfarm_schedule_search_idle_by_domainname(domainname, nfrags, dsthosts); if (e != NULL) goto free_dsthosts; e = gfarm_url_fragments_replicate(gfarm_url, nfrags, dsthosts); while (--nfrags >= 0) free(dsthosts[nfrags]); free_dsthosts: free(dsthosts); return (e); } <file_sep>/gfarm/tags/gfarm_1_0_beta_4_rc2/lib/libgfarm/Makefile # $Id$ top_objdir = ../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk VPATH=$(GFUTIL_SRCDIR):$(GFSL_SRCDIR):$(GFARMLIB_SRCDIR) LIB = gfarm CFLAGS = $(COMMON_CFLAGS) \ -I$(GFUTIL_SRCDIR) -I$(GFARMLIB_SRCDIR) $(globus_cflags) \ $(metadb_client_includes) $(openssl_includes) all: lib$(LIB).a include $(srcdir)/gfutil/Makefile.inc include $(srcdir)/gfsl/Makefile.inc include $(srcdir)/gfarm/Makefile.inc LDAP_SRCS = $(GFARM_LDAP_SRCS) LDAP_OBJS = $(GFARM_LDAP_OBJS) GLOBUS_CFLAGS = -I$(GFSL_SRCDIR) $(globus_includes) \ -DGLOBUS_BUG=1 # see gfsl/gsi.c GLOBUS_SRCS = $(GFSL_SRCS) $(GFARM_GLOBUS_SRCS) GLOBUS_OBJS = $(GFSL_OBJS) $(GFARM_GLOBUS_OBJS) SRCS = $(GFUTIL_SRCS) $(GFARM_SRCS) $(ldap_srcs) $(globus_srcs) OBJS = $(GFUTIL_OBJS) $(GFARM_OBJS) $(ldap_objs) $(globus_objs) lib$(LIB).a: $(OBJS) ar rucv lib$(LIB).a $(OBJS) $(RANLIB) lib$(LIB).a install: all $(INSTALL_DATA) lib$(LIB).a $(libdir)/lib$(LIB).a clean:; rm -f *.o veryclean: clean rm -f lib$(LIB).a distclean: veryclean gfregister: man: html: <file_sep>/gfarm/tags/gfarm_1_0_beta_1/lib/libgfarm/gfsl/session.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <limits.h> #include <sys/stat.h> #include <ctype.h> #include <pwd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/time.h> #include "gssapi.h" #include <gfarm/gfarm_config.h> #include "gfarm_secure_session.h" #include "tcputil.h" #include "misc.h" /* #define SS_DEBUG */ /* * Initial credential and its name. */ static gss_cred_id_t initiatorInitialCred = GSS_C_NO_CREDENTIAL; static gss_cred_id_t acceptorInitialCred = GSS_C_NO_CREDENTIAL; static char *initiatorInitialCredName = NULL; static char *acceptorInitialCredName = NULL; static int initiatorInitialized = 0; static int acceptorInitialized = 0; /* * Communication option read from configuration file. */ static gfarmSecSessionOption acceptorSsOpt = GFARM_SS_DEFAULT_OPTION; static gfarmSecSessionOption initiatorSsOpt = GFARM_SS_DEFAULT_OPTION; static int canonicSecSessionOpt(int which, gfarmSecSessionOption *reqPtr, gfarmSecSessionOption *canPtr); static gfarmSecSession * allocSecSession(int which); static void destroySecSession(gfarmSecSession *ssPtr); static int secSessionReadConfigFile(char *configFile, gfarmSecSessionOption *ssOptPtr); static int negotiateConfigParam(int fd, gss_ctx_id_t sCtx, int which, gfarmSecSessionOption *canPtr, gss_qop_t *qOpPtr, unsigned int *maxTransPtr, unsigned int *configPtr, OM_uint32 *statPtr); static gfarmSecSession * secSessionInitiate(int fd, gss_cred_id_t cred, gfarmSecSessionOption *ssOptPtr, OM_uint32 *statPtr, int needClose); #ifdef SS_DEBUG static void dumpConfParam(gss_qop_t qOp, unsigned int max, unsigned int conf); static void dumpSsOpt(gfarmSecSessionOption *ssOptPtr); static void dumpConfParam(qOp, max, conf) gss_qop_t qOp; unsigned int max; unsigned int conf; { fprintf(stderr, "\tQOP:\t%d\n", (int)qOp); fprintf(stderr, "\tMAX:\t%d\n", max); fprintf(stderr, "\tOPT:\t(%d)", conf); if (conf & GFARM_SS_USE_ENCRYPTION) { fprintf(stderr, " encrypt"); } if (conf & GFARM_SS_USE_COMPRESSION) { fprintf(stderr, " compress"); } fprintf(stderr, "\n"); } static void dumpSsOpt(ssOptPtr) gfarmSecSessionOption *ssOptPtr; { fprintf(stderr, "\n\tQOP:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_QOP_MASK) { fprintf(stderr, "%d%s\n", (int)ssOptPtr->qOpReq, (ssOptPtr->qOpForce == 1) ? " (force)" : ""); } else { fprintf(stderr, "none\n"); } fprintf(stderr, "\tMAX:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_MAXT_MASK) { fprintf(stderr, "%d%s\n", (int)ssOptPtr->maxTransSizeReq, (ssOptPtr->maxTransSizeForce == 1) ? " (force)" : ""); } else { fprintf(stderr, "none\n"); } fprintf(stderr, "\tOPT:\t"); if (ssOptPtr->optMask & GFARM_SS_OPT_CONF_MASK) { fprintf(stderr, "(%d)", ssOptPtr->configReq); if (ssOptPtr->configReq & GFARM_SS_USE_ENCRYPTION) { fprintf(stderr, " encrypt"); } if (ssOptPtr->configReq & GFARM_SS_USE_COMPRESSION) { fprintf(stderr, " compress"); } if (ssOptPtr->configForce == 1) { fprintf(stderr, " (force)"); } fprintf(stderr, "\n\n"); } else { fprintf(stderr, "none\n\n"); } } #endif /* SS_DEBUG */ static int secSessionReadConfigFile(configFile, ssOptPtr) char *configFile; gfarmSecSessionOption *ssOptPtr; { FILE *fd = NULL; char lineBuf[65536]; char *token[64]; int nToken; gfarmSecSessionOption ssTmp = GFARM_SS_DEFAULT_OPTION; int i; if (configFile == NULL || configFile[0] == '\0') { return -1; } if ((fd = fopen(configFile, "r")) == NULL) { /* * use default option. */ goto Done; } while (fgets(lineBuf, 65536, fd) != NULL) { nToken = gfarmGetToken(lineBuf, token, 64); if (nToken <= 0) { continue; } if (token[0][0] == '#') { continue; } if (strcasecmp(token[0], "qop:") == 0) { for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.qOpForce = 1; } else if (strcasecmp(token[i], "default") == 0 || strcasecmp(token[i], "gfarm") == 0) { ssTmp.qOpReq = GFARM_GSS_DEFAULT_QOP; #ifdef USE_GLOBUS } else if (strcasecmp(token[i], "globus") == 0) { ssTmp.qOpReq = GSS_C_QOP_GLOBUS_GSSAPI_SSLEAY_BIG; #endif /* USE_GLOBUS */ } else if (strcasecmp(token[i], "gssapi") == 0) { ssTmp.qOpReq = GSS_C_QOP_DEFAULT; } } } else if (strcasecmp(token[0], "maxtrans:") == 0) { for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.maxTransSizeForce = 1; } else if (strcasecmp(token[i], "default") == 0) { ssTmp.maxTransSizeReq = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; } else { int val; if (gfarmGetInt(token[i], &val) == 1) { if (val < 0) { val = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; } ssTmp.maxTransSizeReq = (unsigned int)val; } } } } else if (strcasecmp(token[0], "options:") == 0) { unsigned int opt = GFARM_SS_USE_ENCRYPTION; for (i = 1; i < nToken; i++) { if (strcasecmp(token[i], "force") == 0) { ssTmp.configForce = 1; } else if (strcasecmp(token[i], "encrypt") == 0) { opt |= GFARM_SS_USE_ENCRYPTION; } else if (strcasecmp(token[i], "compress") == 0) { opt |= GFARM_SS_USE_COMPRESSION; } else if (strcasecmp(token[i], "default") == 0) { opt = GFARM_SS_USE_ENCRYPTION; } } ssTmp.configReq = opt; } } (void)fclose(fd); Done: if (ssOptPtr != NULL) { memcpy((void *)ssOptPtr, (void *)&ssTmp, sizeof(gfarmSecSessionOption)); ssOptPtr->optMask = GFARM_SS_OPT_ALL_MASK; } return 1; } static int canonicSecSessionOpt(which, reqPtr, canPtr) int which; gfarmSecSessionOption *reqPtr; gfarmSecSessionOption *canPtr; { gfarmSecSessionOption *dPtr = (which == GFARM_SS_INITIATOR) ? &initiatorSsOpt : &acceptorSsOpt; if (canPtr == NULL) { return -1; } if (reqPtr == NULL) { (void)memcpy((void *)canPtr, (void *)dPtr, sizeof(gfarmSecSessionOption)); return 1; } #define isMasked(op, msk) ((op)->optMask & msk) == msk #define isUseReq(req, mbr) (req)->mbr == 1 || ((req)->mbr == 0 && dPtr->mbr == 0) #define cpIt(dst, src, mbr) (dst)->mbr = (src)->mbr #define useReq(mbr) cpIt(canPtr, reqPtr, mbr) #define useDef(mbr) cpIt(canPtr, dPtr, mbr) canPtr->optMask |= GFARM_SS_OPT_QOP_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_QOP_MASK)) { if (isUseReq(reqPtr, qOpForce)) { useReq(qOpReq); useReq(qOpForce); } else { goto useQOPDef; } } else { useQOPDef: useDef(qOpReq); useDef(qOpForce); } canPtr->optMask |= GFARM_SS_OPT_MAXT_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_MAXT_MASK)) { if (isUseReq(reqPtr, maxTransSizeForce)) { useReq(maxTransSizeReq); useReq(maxTransSizeForce); } else { goto useMaxTDef; } } else { useMaxTDef: useDef(maxTransSizeReq); useDef(maxTransSizeForce); } canPtr->optMask |= GFARM_SS_OPT_CONF_MASK; if (isMasked(reqPtr, GFARM_SS_OPT_CONF_MASK)) { if (isUseReq(reqPtr, configForce)) { useReq(configReq); useReq(configForce); } else { goto useConfigDef; } } else { useConfigDef: useDef(configReq); useDef(configForce); } return 1; #undef isMasked #undef isUseReq #undef cpIt #undef useReq #undef useDef } static int negotiateConfigParam(fd, sCtx, which, canPtr, qOpPtr, maxTransPtr, configPtr, statPtr) int fd; gss_ctx_id_t sCtx; int which; gfarmSecSessionOption *canPtr; gss_qop_t *qOpPtr; unsigned int *maxTransPtr; unsigned int *configPtr; OM_uint32 *statPtr; { #define SS_CONF_ACK 1 #define SS_CONF_NACK 0 #define SS_CONF_NEGO 2 int ret = -1; gss_qop_t retQOP = GFARM_GSS_DEFAULT_QOP; unsigned int retMaxT = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; unsigned int retConf = GFARM_SS_USE_ENCRYPTION; char NACK = SS_CONF_NACK; char ACK = SS_CONF_ACK; char NEGO = SS_CONF_NEGO; char stat; int negoPhase = 0; int dQOP = (int)(GFARM_GSS_DEFAULT_QOP); unsigned int dMax = GFARM_GSS_DEFAULT_MAX_MESSAGE_REQUEST_SIZE; unsigned int dConf = GFARM_SS_USE_ENCRYPTION; #define SendCmd(p) { if (gfarmWriteBytes(fd, (char *)&(p), 1) != 1) { break; }} #define SendACK(dum) SendCmd(ACK) #define SendNACK(dum) SendCmd(NACK) #define SendNEGO(dum) SendCmd(NEGO) #define ReadCmd(p) { if (gfarmReadBytes(fd, (char *)&(p), 1) != 1) { break; }} #define SendParam(x) {if (gfarmWriteLongs(fd, (long *)&(x), 1) != 1) {break;}} #define ReadParam(x) {if (gfarmReadLongs(fd, (long *)&(x), 1) != 1) {break;}} if (sCtx == GSS_C_NO_CONTEXT) { return ret; } switch (which) { case GFARM_SS_ACCEPTOR: { int iQOP, iQOPF; unsigned int iMax; int iMaxF; int iConf, iConfF; /* QOP negotiation. */ ReadParam(iQOP); ReadParam(iQOPF); if (canPtr->qOpReq != iQOP) { if (canPtr->qOpForce == 1 && iQOPF == 1) { /* * Both sides want to rule the world. * No 2nd thought sigh. */ SendNACK(0); break; } else if (iQOPF == 1) { /* * Use the initiator's QOP */ dQOP = iQOP; goto setQOP; } else { /* * (canPtr->qOpForce == 1 || * Both force flags == 0) * Propose the acceptor's QOP */ SendNEGO(2); SendParam(canPtr->qOpReq); ReadCmd(stat); if (stat != ACK) { break; } else { dQOP = canPtr->qOpReq; goto setQOP; } } } else { dQOP = iQOP; setQOP: SendACK(1); retQOP = (gss_qop_t)dQOP; negoPhase++; } /* Max transmission size negotiation. */ ReadParam(iMax); ReadParam(iMaxF); if (canPtr->maxTransSizeReq != iMax) { if (canPtr->maxTransSizeForce == 1 && iMaxF == 1) { SendNACK(0); break; } else if (iMaxF == 1) { dMax = iMax; goto setMax; } else { int tmpMax; if (canPtr->maxTransSizeForce == 1) { tmpMax = canPtr->maxTransSizeReq; } else { tmpMax = (canPtr->maxTransSizeReq < iMax) ? canPtr->maxTransSizeReq : iMax; } SendNEGO(2); SendParam(tmpMax); ReadCmd(stat); if (stat != ACK) { break; } else { dMax = tmpMax; goto setMax; } } } else { dMax = iMax; setMax: SendACK(1); retMaxT = dMax; negoPhase++; } /* Configuration flag negotiation. */ ReadParam(iConf); ReadParam(iConfF); if (canPtr->configReq != iConf) { if (canPtr->configForce == 1 && iConfF == 1) { SendNACK(0); break; } else if (iConfF == 1) { dConf = iConf; goto setConf; } else { SendNEGO(2); SendParam(canPtr->configReq); ReadCmd(stat); if (stat != ACK) { break; } else { dConf = canPtr->configReq; goto setConf; } } } else { dConf = iConf; setConf: SendACK(1); retConf = dConf; negoPhase++; } /* End of initiator side negotiation. */ break; } case GFARM_SS_INITIATOR: { /* QOP */ SendParam(canPtr->qOpReq); SendParam(canPtr->qOpForce); ReadCmd(stat); switch (stat) { case SS_CONF_ACK: { retQOP = canPtr->qOpReq; break; } case SS_CONF_NACK: { goto Done; } case SS_CONF_NEGO: { ReadParam(retQOP); SendACK(1); break; } } negoPhase++; /* Max transmission size */ SendParam(canPtr->maxTransSizeReq); SendParam(canPtr->maxTransSizeForce); ReadCmd(stat); switch (stat) { case SS_CONF_ACK: { retMaxT = canPtr->maxTransSizeReq; break; } case SS_CONF_NACK: { goto Done; } case SS_CONF_NEGO: { ReadParam(retMaxT); SendACK(1); break; } } negoPhase++; /* Configuration flag */ SendParam(canPtr->configReq); SendParam(canPtr->configForce); ReadCmd(stat); switch (stat) { case SS_CONF_ACK: { retConf = canPtr->configReq; break; } case SS_CONF_NACK: { goto Done; } case SS_CONF_NEGO: { ReadParam(retConf); SendACK(1); break; } } negoPhase++; break; } } Done: if (negoPhase >= 3) { OM_uint32 majStat; unsigned int maxMsgSize; int doEncrypt = GFARM_GSS_ENCRYPTION_ENABLED & (isBitSet(retConf, GFARM_SS_USE_ENCRYPTION) ? 1 : 0); if (gfarmGssConfigureMessageSize(sCtx, doEncrypt, retQOP, retMaxT, &maxMsgSize, &majStat) < 0) { if (statPtr != NULL) { *statPtr = majStat; } return ret; } if (statPtr != NULL) { *statPtr = majStat; } if (qOpPtr != NULL) { *qOpPtr = retQOP; } if (maxTransPtr != NULL) { *maxTransPtr = maxMsgSize; } if (configPtr != NULL) { *configPtr = retConf; } ret = 1; } return ret; #undef SS_CONF_ACK #undef SS_CONF_NACK #undef SS_CONF_NEGO #undef SendCmd #undef SendACK #undef SendNACK #undef SendNEGO #undef ReadCmd #undef SendParam #undef ReadParam } static gfarmSecSession * allocSecSession(which) int which; { gfarmSecSession *ret = (gfarmSecSession *)malloc(sizeof(gfarmSecSession)); if (ret == NULL) { return NULL; } (void)memset((void *)ret, 0, sizeof(gfarmSecSession)); switch (which) { case GFARM_SS_INITIATOR: { break; } case GFARM_SS_ACCEPTOR: { ret->iOaInfo.acceptor.deleCred = GSS_C_NO_CREDENTIAL; break; } default: { (void)free(ret); ret = NULL; return NULL; } } ret->iOa = which; ret->cred = GSS_C_NO_CREDENTIAL; ret->sCtx = GSS_C_NO_CONTEXT; ret->gssLastStat = GSS_S_COMPLETE; return ret; } static void destroySecSession(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr != NULL) { OM_uint32 minStat; if (ssPtr->peerName != NULL) { (void)free(ssPtr->peerName); } if (ssPtr->credName != NULL) { (void)free(ssPtr->credName); } switch (ssPtr->iOa) { case GFARM_SS_INITIATOR: { if (ssPtr->iOaInfo.initiator.acceptorDistName != NULL) { (void)free(ssPtr->iOaInfo.initiator.acceptorDistName); } break; } case GFARM_SS_ACCEPTOR: { if (ssPtr->iOaInfo.acceptor.deleCred != GSS_C_NO_CREDENTIAL) { (void)gss_release_cred(&minStat, &(ssPtr->iOaInfo.acceptor.deleCred)); } if (ssPtr->iOaInfo.acceptor.mappedUser != NULL) { /* * ssPtr->iOaInfo.acceptor.mappedUser may be NULL, * if gfarmSecSessionAccept() aborts during initialization. */ ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount--; if (ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount < 0) { ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount = 0; } if (ssPtr->iOaInfo.acceptor.mappedUser->sesRefCount == 0 && ssPtr->iOaInfo.acceptor.mappedUser->orphaned == 1) { gfarmAuthDestroyUserEntry(ssPtr->iOaInfo.acceptor.mappedUser); } } break; } default: { break; } } if (ssPtr->sCtx != GSS_C_NO_CONTEXT) { (void)gss_delete_sec_context(&minStat, &(ssPtr->sCtx), GSS_C_NO_BUFFER); } if (ssPtr->needClose == 1) { (void)close(ssPtr->fd); } (void)free(ssPtr); } } char ** gfarmSecSessionCrackStatus(ssPtr) gfarmSecSession *ssPtr; { return gfarmGssCrackStatus(ssPtr->gssLastStat); } void gfarmSecSessionFreeCrackedStatus(strPtr) char **strPtr; { gfarmGssFreeCrackedStatus(strPtr); } void gfarmSecSessionPrintStatus(fd, ssPtr) FILE *fd; gfarmSecSession *ssPtr; { gfarmGssPrintStatus(fd, ssPtr->gssLastStat); } int gfarmSecSessionInitializeAcceptor(configFile, usermapFile, statPtr) char *configFile; char *usermapFile; OM_uint32 *statPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; if (acceptorInitialized == 0) { char confFile[PATH_MAX]; /* * Get a credential. */ if (acceptorInitialCred == GSS_C_NO_CREDENTIAL && acceptorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&acceptorInitialCred, GSS_C_ACCEPT, &majStat, &acceptorInitialCredName) < 0) { ret = -1; goto Done; } } /* * Read config file. */ if (configFile == NULL || configFile[0] == '\0') { char *confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #endif (void)free(confDir); configFile = confFile; } if (secSessionReadConfigFile(configFile, &acceptorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Authorization init. */ if (gfarmAuthInitialize(usermapFile) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (ret == -1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } } else { acceptorInitialized = 1; } } if (statPtr != NULL) { *statPtr = majStat; } return ret; } int gfarmSecSessionInitializeInitiator(configFile, statPtr) char *configFile; OM_uint32 *statPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; if (initiatorInitialized == 0) { char confFile[PATH_MAX]; /* * Get a credential. */ if (initiatorInitialCred == GSS_C_NO_CREDENTIAL && initiatorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&initiatorInitialCred, GSS_C_INITIATE, &majStat, &initiatorInitialCredName) < 0) { ret = -1; goto Done; } } /* * Read config file. */ if (configFile == NULL || configFile[0] == '\0') { char *confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #endif (void)free(confDir); configFile = confFile; } if (secSessionReadConfigFile(configFile, &initiatorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (ret == -1) { if (initiatorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &initiatorInitialCred); initiatorInitialCred = GSS_C_NO_CREDENTIAL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } } else { initiatorInitialized = 1; } } if (statPtr != NULL) { *statPtr = majStat; } return ret; } int gfarmSecSessionInitializeBoth(iConfigFile, aConfigFile, usermapFile, statPtr) char *iConfigFile; char *aConfigFile; char *usermapFile; OM_uint32 *statPtr; { int ret = 1; OM_uint32 majStat = GSS_S_COMPLETE; /* * If the process's effective user is root (getuid()==0): * acceptor: host credential (GSS_C_BOTH) * initiator: host credential (GSS_C_BOTH) * * Otherwise (uid!=0): * acceptor: user credential (GSS_C_BOTH) * initiator: user credential (GSS_C_BOTH) * * XXXXX FIXME: * This implementation depends on gssapi_ssleay of Globus. With * other GSSAPI implementation, a major change could be needed. */ if (initiatorInitialized == 0 && acceptorInitialized == 0) { char confFile[PATH_MAX]; char *confDir = NULL; if (acceptorInitialCred == GSS_C_NO_CREDENTIAL && acceptorInitialCredName == NULL) { if (gfarmGssAcquireCredential(&acceptorInitialCred, GSS_C_BOTH, &majStat, &acceptorInitialCredName) < 0) { ret = -1; goto Done; } initiatorInitialCred = acceptorInitialCred; initiatorInitialCredName = strdup(acceptorInitialCredName); } /* * Read config file. */ if ((aConfigFile == NULL || aConfigFile[0] == '\0') || (iConfigFile == NULL || iConfigFile[0] == '\0')) { confDir = gfarmGetEtcDir(); if (confDir == NULL) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } } /* * Acceptor's configuration */ if (aConfigFile == NULL || aConfigFile[0] == '\0') { #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_ACCEPTOR_CONFIG_FILE); #endif aConfigFile = confFile; } if (secSessionReadConfigFile(aConfigFile, &acceptorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Initiator's configuration */ if (iConfigFile == NULL || iConfigFile[0] == '\0') { #ifdef HAVE_SNPRINTF snprintf(confFile, sizeof confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #else sprintf(confFile, "%s/%s", confDir, GFARM_DEFAULT_INITIATOR_CONFIG_FILE); #endif iConfigFile = confFile; } if (secSessionReadConfigFile(iConfigFile, &initiatorSsOpt) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } /* * Authorization init. */ if (gfarmAuthInitialize(usermapFile) < 0) { majStat = GSS_S_FAILURE; ret = -1; goto Done; } Done: if (confDir != NULL) { (void)free(confDir); } if (ret == -1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } initiatorInitialCred = GSS_C_NO_CREDENTIAL; } else { initiatorInitialized = 1; acceptorInitialized = 1; } } if (statPtr != NULL) { *statPtr = majStat; } return ret; } void gfarmSecSessionFinalizeInitiator() { if (initiatorInitialized == 1) { if (initiatorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &initiatorInitialCred); initiatorInitialCred = GSS_C_NO_CREDENTIAL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; } initiatorInitialized = 0; } } void gfarmSecSessionFinalizeAcceptor() { if (acceptorInitialized == 1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } gfarmAuthFinalize(); acceptorInitialized = 0; } } void gfarmSecSessionFinalizeBoth() { if (initiatorInitialized == 1 && acceptorInitialized == 1) { if (acceptorInitialCred != GSS_C_NO_CREDENTIAL) { OM_uint32 minStat; (void)gss_release_cred(&minStat, &acceptorInitialCred); acceptorInitialCred = GSS_C_NO_CREDENTIAL; } if (acceptorInitialCredName != NULL) { (void)free(acceptorInitialCredName); acceptorInitialCredName = NULL; } if (initiatorInitialCredName != NULL) { (void)free(initiatorInitialCredName); initiatorInitialCredName = NULL; initiatorInitialCred = GSS_C_NO_CREDENTIAL; } gfarmAuthFinalize(); acceptorInitialized = 0; initiatorInitialized = 0; } } gfarmSecSession * gfarmSecSessionAccept(fd, cred, ssOptPtr, statPtr) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *statPtr; { gfarmSecSession *ret = NULL; gfarmSecSessionOption canOpt = GFARM_SS_DEFAULT_OPTION; gfarmAuthEntry *entry = NULL; unsigned long int rAddr = INADDR_ANY; int rPort = 0; char *peerName = NULL; OM_uint32 majStat = GSS_S_FAILURE; gss_ctx_id_t sCtx = GSS_C_NO_CONTEXT; char *initiatorDistName = NULL; gss_cred_id_t deleCred = GSS_C_NO_CREDENTIAL; char *credName = NULL; int acknack = GFARM_SS_AUTH_NACK; gss_qop_t qOp; unsigned int maxTransSize; unsigned int config; if (acceptorInitialized == 0) { goto Fail; } ret = allocSecSession(GFARM_SS_ACCEPTOR); if (ret == NULL) { goto Fail; } if (canonicSecSessionOpt(GFARM_SS_ACCEPTOR, ssOptPtr, &canOpt) < 0) { goto Fail; } /* * Get a peer information. */ rAddr = gfarmIPGetPeernameOfSocket(fd, &rPort); if (rAddr != 0 && rPort != 0) { peerName = gfarmIPGetHostOfAddress(rAddr); } /* * Check the credential. */ if (cred == GSS_C_NO_CREDENTIAL) { cred = acceptorInitialCred; credName = strdup(acceptorInitialCredName); } else { credName = gfarmGssGetCredentialName(cred); } /* * Phase 1: Accept a security context. */ if (gfarmGssAcceptSecurityContext(fd, cred, &sCtx, &majStat, &initiatorDistName, &deleCred) < 0) { goto Fail; } if (initiatorDistName == NULL || initiatorDistName[0] == '\0') { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 2: Authorization and send ACK/NACK */ entry = gfarmAuthGetUserEntry(initiatorDistName); if (entry == NULL) { majStat = GSS_S_UNAUTHORIZED; /* Send NACK. */ acknack = GFARM_SS_AUTH_NACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); goto Fail; } else { int type = gfarmAuthGetAuthEntryType(entry); if (type == GFARM_AUTH_USER) { /* Send ACK. */ acknack = GFARM_SS_AUTH_ACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); } else if (type == GFARM_AUTH_HOST) { /* check peer name is actually allowed */ if (strcmp(peerName, entry->authData.hostAuth.FQDN) == 0) { /* Send ACK. */ acknack = GFARM_SS_AUTH_ACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); } else { /* Send NACK. */ acknack = GFARM_SS_AUTH_NACK; (void)gfarmWriteLongs(fd, (long *)&acknack, 1); goto Fail; } } } /* * Phase 3: Negotiate configuration parameters * with the initiator. */ if (negotiateConfigParam(fd, sCtx, GFARM_SS_ACCEPTOR, &canOpt, &qOp, &maxTransSize, &config, &majStat) < 0) { goto Fail; } #if 0 fprintf(stderr, "Acceptor config:\n"); dumpConfParam(qOp, maxTransSize, config); #endif /* * Success: Fill all members of session struct out. */ ret->fd = fd; ret->rAddr = rAddr; ret->rPort = rPort; ret->peerName = peerName; ret->cred = cred; ret->credName = credName; ret->sCtx = sCtx; ret->iOa = GFARM_SS_ACCEPTOR; ret->iOaInfo.acceptor.mappedUser = entry; ret->iOaInfo.acceptor.mappedUser->sesRefCount++; ret->iOaInfo.acceptor.deleCred = deleCred; ret->qOp = qOp; ret->maxTransSize = maxTransSize; ret->config = config; ret->gssLastStat = majStat; goto Done; Fail: if (ret != NULL) { destroySecSession(ret); ret = NULL; } Done: if (initiatorDistName != NULL) { (void)free(initiatorDistName); } if (statPtr != NULL) { *statPtr = majStat; } return ret; } static gfarmSecSession * secSessionInitiate(fd, cred, ssOptPtr, statPtr, needClose) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *statPtr; int needClose; { gfarmSecSession *ret = NULL; gfarmSecSessionOption canOpt = GFARM_SS_DEFAULT_OPTION; unsigned long int rAddr = INADDR_ANY; int rPort = 0; char *peerName = NULL; OM_uint32 majStat = GSS_S_FAILURE; gss_ctx_id_t sCtx = GSS_C_NO_CONTEXT; char *acceptorDistName = NULL; char *credName = NULL; int acknack = GFARM_SS_AUTH_NACK; gss_qop_t qOp; unsigned int maxTransSize; unsigned int config; if (initiatorInitialized == 0) { goto Fail; } ret = allocSecSession(GFARM_SS_INITIATOR); if (ret == NULL) { goto Fail; } if (canonicSecSessionOpt(GFARM_SS_INITIATOR, ssOptPtr, &canOpt) < 0) { goto Fail; } /* * Get a peer information. */ rAddr = gfarmIPGetPeernameOfSocket(fd, &rPort); if (rAddr != 0 && rPort != 0) { peerName = gfarmIPGetHostOfAddress(rAddr); } /* * Check the credential. */ if (cred == GSS_C_NO_CREDENTIAL) { cred = initiatorInitialCred; credName = strdup(initiatorInitialCredName); } else { credName = gfarmGssGetCredentialName(cred); } /* * Phase 1: Initiate a security context. */ if (gfarmGssInitiateSecurityContext(fd, cred, GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG, &sCtx, &majStat, &acceptorDistName) < 0) { goto Fail; } if (acceptorDistName == NULL || acceptorDistName[0] == '\0') { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 2: Receive authorization acknowledgement. */ if (gfarmReadLongs(fd, (long *)&acknack, 1) != 1) { majStat = GSS_S_UNAUTHORIZED; goto Fail; } if (acknack == GFARM_SS_AUTH_NACK) { majStat = GSS_S_UNAUTHORIZED; goto Fail; } /* * Phase 3: Negotiate configuration parameters * with the acceptor. */ if (negotiateConfigParam(fd, sCtx, GFARM_SS_INITIATOR, &canOpt, &qOp, &maxTransSize, &config, &majStat) < 0) { goto Fail; } #if 0 fprintf(stderr, "Initiator config:\n"); dumpConfParam(qOp, maxTransSize, config); #endif /* * Success: Fill all members of session struct out. */ ret->fd = fd; ret->needClose = needClose; ret->rAddr = rAddr; ret->rPort = rPort; ret->peerName = peerName; ret->cred = cred; ret->credName = credName; ret->sCtx = sCtx; ret->iOa = GFARM_SS_INITIATOR; ret->iOaInfo.initiator.reqFlag = GFARM_GSS_DEFAULT_SECURITY_SETUP_FLAG; ret->iOaInfo.initiator.acceptorDistName = strdup(acceptorDistName); ret->qOp = qOp; ret->maxTransSize = maxTransSize; ret->config = config; ret->gssLastStat = majStat; goto Done; Fail: if (ret != NULL) { destroySecSession(ret); ret = NULL; } Done: if (acceptorDistName != NULL) { (void)free(acceptorDistName); } if (statPtr != NULL) { *statPtr = majStat; } return ret; } gfarmSecSession * gfarmSecSessionInitiate(fd, cred, ssOptPtr, statPtr) int fd; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *statPtr; { return secSessionInitiate(fd, cred, ssOptPtr, statPtr, 0); } gfarmSecSession * gfarmSecSessionInitiateByAddr(rAddr, port, cred, ssOptPtr, statPtr) unsigned long rAddr; int port; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *statPtr; { int fd = gfarmTCPConnectPort(rAddr, port); if (fd < 0) { if (statPtr != NULL) { *statPtr = GSS_S_FAILURE; } return NULL; } return secSessionInitiate(fd, cred, ssOptPtr, statPtr, 1); } gfarmSecSession * gfarmSecSessionInitiateByName(hostname, port, cred, ssOptPtr, statPtr) char *hostname; int port; gss_cred_id_t cred; gfarmSecSessionOption *ssOptPtr; OM_uint32 *statPtr; { unsigned long rAddr = gfarmIPGetAddressOfHost(hostname); if (rAddr == ~0L || rAddr == 0L) { if (statPtr != NULL) { *statPtr = GSS_S_FAILURE; } return NULL; } return gfarmSecSessionInitiateByAddr(rAddr, port, cred, ssOptPtr, statPtr); } void gfarmSecSessionTerminate(ssPtr) gfarmSecSession *ssPtr; { destroySecSession(ssPtr); } gss_cred_id_t gfarmSecSessionGetDelegatedCredential(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr->iOa == GFARM_SS_INITIATOR) { return GSS_C_NO_CREDENTIAL; } return ssPtr->iOaInfo.acceptor.deleCred; } gfarmAuthEntry * gfarmSecSessionGetInitiatorInfo(ssPtr) gfarmSecSession *ssPtr; { if (ssPtr->iOa == GFARM_SS_INITIATOR) { return NULL; } return ssPtr->iOaInfo.acceptor.mappedUser; } int gfarmSecSessionDedicate(ssPtr) gfarmSecSession *ssPtr; { int ret = -1; gfarmAuthEntry *aePtr = gfarmSecSessionGetInitiatorInfo(ssPtr); if (aePtr != NULL) { gid_t gid = getgid(); uid_t uid = getuid(); gfarmAuthMakeThisAlone(aePtr); if (uid == 0 && aePtr->authType == GFARM_AUTH_USER) { if (aePtr->authData.userAuth.gid != gid) { if ((ret = setgid(aePtr->authData.userAuth.gid)) < 0) { ssPtr->gssLastStat = GSS_S_FAILURE; goto Done; } } if (aePtr->authData.userAuth.uid != uid) { if ((ret = setuid(aePtr->authData.userAuth.uid)) < 0) { ssPtr->gssLastStat = GSS_S_FAILURE; goto Done; } } } ret = 1; } else { ssPtr->gssLastStat = GSS_S_FAILURE; } Done: return ret; } int gfarmSecSessionSendBytes(ssPtr, buf, n) gfarmSecSession *ssPtr; char *buf; int n; { int doEncrypt = GFARM_GSS_ENCRYPTION_ENABLED & (isBitSet(ssPtr->config, GFARM_SS_USE_ENCRYPTION) ? 1 : 0); return gfarmGssSend(ssPtr->fd, ssPtr->sCtx, doEncrypt, ssPtr->qOp, buf, n, ssPtr->maxTransSize, &(ssPtr->gssLastStat)); } int gfarmSecSessionReceiveBytes(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; char **bufPtr; int *lenPtr; { return gfarmGssReceive(ssPtr->fd, ssPtr->sCtx, bufPtr, lenPtr, &(ssPtr->gssLastStat)); } int gfarmSecSessionSendLongs(ssPtr, buf, n) gfarmSecSession *ssPtr; long *buf; int n; { long *lBuf = (long *)malloc(sizeof(long) * n); int i; int ret = -1; if (lBuf == NULL) { ssPtr->gssLastStat = GSS_S_FAILURE; return ret; } for (i = 0; i < n; i++) { lBuf[i] = htonl(buf[i]); } ret = gfarmSecSessionSendBytes(ssPtr, (char *)lBuf, n * sizeof(long)); (void)free(lBuf); if (ret > 0) { ret /= sizeof(long); } return ret; } int gfarmSecSessionReceiveLongs(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; long **bufPtr; int *lenPtr; { char *lBuf = NULL; char *lbPtr = NULL; long *retBuf = NULL; long tmp; int len = 0; int i; int n; int ret = gfarmSecSessionReceiveBytes(ssPtr, &lBuf, &len); if (ret <= 0) { goto Done; } n = len % sizeof(long); if (n != 0) { goto Done; } n = len / sizeof(long); retBuf = (long *)malloc(sizeof(long) * n); if (retBuf == NULL) { goto Done; } lbPtr = lBuf; for (i = 0; i < n; i++) { memcpy((void *)&tmp, (void *)lbPtr, sizeof(long)); retBuf[i] = ntohl(tmp); lbPtr += sizeof(long); } ret = n; if (lenPtr != NULL) { *lenPtr = n; } if (bufPtr != NULL) { *bufPtr = retBuf; } Done: if (lBuf != NULL) { (void)free(lBuf); } return ret; } int gfarmSecSessionSendShorts(ssPtr, buf, n) gfarmSecSession *ssPtr; short *buf; int n; { short *lBuf = (short *)malloc(sizeof(short) * n); int i; int ret = -1; if (lBuf == NULL) { ssPtr->gssLastStat = GSS_S_FAILURE; return ret; } for (i = 0; i < n; i++) { lBuf[i] = htons(buf[i]); } ret = gfarmSecSessionSendBytes(ssPtr, (char *)lBuf, n * sizeof(short)); (void)free(lBuf); if (ret > 0) { ret /= sizeof(short); } return ret; } int gfarmSecSessionReceiveShorts(ssPtr, bufPtr, lenPtr) gfarmSecSession *ssPtr; short **bufPtr; int *lenPtr; { char *lBuf = NULL; char *lbPtr = NULL; short *retBuf = NULL; short tmp; int len = 0; int i; int n; int ret = gfarmSecSessionReceiveBytes(ssPtr, &lBuf, &len); if (ret <= 0) { goto Done; } n = len % sizeof(short); if (n != 0) { goto Done; } n = len / sizeof(short); retBuf = (short *)malloc(sizeof(short) * n); if (retBuf == NULL) { goto Done; } lbPtr = lBuf; for (i = 0; i < n; i++) { memcpy((void *)&tmp, (void *)lbPtr, sizeof(short)); retBuf[i] = ntohs(tmp); lbPtr += sizeof(short); } ret = n; if (lenPtr != NULL) { *lenPtr = n; } if (bufPtr != NULL) { *bufPtr = retBuf; } Done: if (lBuf != NULL) { (void)free(lBuf); } return ret; } int gfarmSecSessionPoll(ssList, n, toPtr) gfarmSecSession *ssList[]; int n; struct timeval *toPtr; { int nFds = -INT_MAX; int i; fd_set rFds; fd_set wFds; fd_set eFds; gfarmSecSession *ssPtr; int fdChk = 0; int ret; FD_ZERO(&rFds); FD_ZERO(&wFds); FD_ZERO(&eFds); for (i = 0; i < n; i++) { fdChk = 0; ssPtr = ssList[i]; if (gfarmSecSessionCheckPollReadable(ssPtr)) { FD_SET(ssPtr->fd, &rFds); fdChk++; } if (gfarmSecSessionCheckPollWritable(ssPtr)) { FD_SET(ssPtr->fd, &wFds); fdChk++; } if (gfarmSecSessionCheckPollError(ssPtr)) { FD_SET(ssPtr->fd, &eFds); fdChk++; } if (fdChk > 0) { if (nFds < ssPtr->fd) { nFds = ssPtr->fd; } } } if (nFds < 0) { return 0; } nFds++; doSel: ret = select(nFds, &rFds, &wFds, &eFds, toPtr); if (ret == 0) { for (i = 0; i < n; i++) { gfarmSecSessionClearPollEvent(ssList[i]); } } else if (ret < 0) { if (errno == EINTR) { goto doSel; } } else { for (i = 0; i < n; i++) { ssPtr = ssList[i]; gfarmSecSessionClearPollEvent(ssPtr); if (FD_ISSET(ssPtr->fd, &rFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_READABLE; } if (FD_ISSET(ssPtr->fd, &wFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_WRITABLE; } if (FD_ISSET(ssPtr->fd, &eFds)) { ssPtr->pollEvent |= GFARM_SS_POLL_ERROR; } } } return ret; } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_7/acl.h /* * $Id$ */ #if defined(HAVE_SYS_ACL_H) && defined(GFARM_ACL_READ) && \ defined(HAVE_SYS_XATTR_H) && defined(ENABLE_XATTR) && \ defined(HAVE_GFARM_XATTR_CACHING) && \ defined(HAVE_GFARM_XATTR_CACHING_PATTERN_ADD) #define ENABLE_GFARM_ACL gfarm_error_t gfarm2fs_acl_set(const char *, gfarm_acl_type_t type, const void *, size_t); gfarm_error_t gfarm2fs_acl_get(const char *, gfarm_acl_type_t type, void *, size_t *); #endif static const char ACL_EA_ACCESS[] = "system.posix_acl_access"; static const char ACL_EA_DEFAULT[] = "system.posix_acl_default"; #define ACL_EA_VERSION (0x0002) /* Linux ACL Version */ <file_sep>/gfarm/tags/gfarm_1_0_4_rc2/lib/gfs_hook/hooks_subr.c /* * $Id$ */ #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <gfarm/gfarm.h> #include "hooks_subr.h" /* for creating_file hash -- XXX: Gfarm v2 may make this stuff obsolete */ #include "hash.h" #include <openssl/evp.h> #include "gfs_pio.h" #include <gfarm/gfs_hook.h> #define MAX_GFS_FILE_BUF 2048 struct _gfs_file_descriptor { int refcount; unsigned char d_type; /* file types in <gfarm/gfs.h> */ union { GFS_File f; struct { GFS_Dir dir; int readcount; struct gfs_dirent *suspended; struct gfs_stat gst; char *canonical_path; /* for __fchdir() hook */ } *d; } u; }; static struct _gfs_file_descriptor *_gfs_file_buf[MAX_GFS_FILE_BUF]; /* * static function definitions */ static void gfs_hook_set_current_view_local(); static void gfs_hook_set_current_view_index(int, int); static void gfs_hook_set_current_view_global(); static void gfs_hook_set_current_view_section(char *, int); static void gfs_hook_set_current_view_default(); /* * */ void gfs_hook_not_initialized(void) { static int printed = 0; if (!printed) { printed = 1; fprintf(stderr, "fatal error: gfarm_initialize() isn't called\n"); } } /* * gfs_file_buf management */ int gfs_hook_insert_gfs_file(GFS_File gf) { int fd, save_errno; struct stat st; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_file: %p\n", gf)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = gfs_pio_fileno(gf); if (fstat(fd, &st) == -1) { save_errno = errno; gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = save_errno; return (-1); } if (S_ISREG(st.st_mode)) fd = dup(fd); else /* don't return a socket, to make select(2) work with this fd */ fd = open("/dev/null", O_RDWR); if (fd == -1) { save_errno = errno; gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_hook_delete_creating_file(gf); gfs_pio_close(gf); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_REG; _gfs_file_buf[fd]->u.f = gf; return (fd); } int gfs_hook_insert_gfs_dir(GFS_Dir dir, char *url) { int fd, save_errno; char *e; _gfs_hook_debug(fprintf(stderr, "GFS: insert_gfs_dir: %p\n", dir)); /* * A new file descriptor is needed to identify a hooked file * descriptor. */ fd = open("/dev/null", O_RDONLY); if (fd == -1) { save_errno = errno; gfs_closedir(dir); errno = save_errno; return (-1); } if (fd >= MAX_GFS_FILE_BUF) { __syscall_close(fd); gfs_closedir(dir); errno = EMFILE; return (-1); } if (_gfs_file_buf[fd] != NULL) { __syscall_close(fd); gfs_closedir(dir); errno = EBADF; /* XXX - something broken */ return (-1); } _gfs_file_buf[fd] = malloc(sizeof(*_gfs_file_buf[fd])); if (_gfs_file_buf[fd] == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->u.d = malloc(sizeof(*_gfs_file_buf[fd]->u.d)); if (_gfs_file_buf[fd]->u.d == NULL) { __syscall_close(fd); gfs_closedir(dir); errno = ENOMEM; return (-1); } _gfs_file_buf[fd]->refcount = 1; _gfs_file_buf[fd]->d_type = GFS_DT_DIR; _gfs_file_buf[fd]->u.d->dir = dir; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; e = gfs_stat(url, &_gfs_file_buf[fd]->u.d->gst); if (e != NULL) return (-1); e = gfarm_canonical_path(gfarm_url_prefix_skip(url), &_gfs_file_buf[fd]->u.d->canonical_path); if (e != NULL) return (-1); return (fd); } unsigned char gfs_hook_gfs_file_type(int fd) { return (_gfs_file_buf[fd]->d_type); } char * gfs_hook_clear_gfs_file(int fd) { GFS_File gf; char *e = NULL; _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: %d\n", fd)); gf = gfs_hook_is_open(fd); if (--_gfs_file_buf[fd]->refcount > 0) { /* fd is duplicated, skip closing the file. */ _gfs_hook_debug(fprintf(stderr, "GFS: clear_gfs_file: skipped\n")); } else { if (gfs_hook_gfs_file_type(fd) == GFS_DT_REG) { gfs_hook_delete_creating_file(gf); e = gfs_pio_close(gf); } else if (gfs_hook_gfs_file_type(fd) == GFS_DT_DIR) { _gfs_file_buf[fd]->u.d->dir = NULL; _gfs_file_buf[fd]->u.d->readcount = 0; _gfs_file_buf[fd]->u.d->suspended = NULL; gfs_stat_free(&_gfs_file_buf[fd]->u.d->gst); free(_gfs_file_buf[fd]->u.d->canonical_path); free(_gfs_file_buf[fd]->u.d); e = gfs_closedir((GFS_Dir)gf); } free(_gfs_file_buf[fd]); } __syscall_close(fd); _gfs_file_buf[fd] = NULL; return (e); } struct _gfs_file_descriptor *gfs_hook_dup_descriptor(int fd) { if (gfs_hook_is_open(fd) == NULL) return (NULL); ++_gfs_file_buf[fd]->refcount; return (_gfs_file_buf[fd]); } void gfs_hook_set_descriptor(int fd, struct _gfs_file_descriptor *d) { if (gfs_hook_is_open(fd) != NULL) gfs_hook_clear_gfs_file(fd); _gfs_file_buf[fd] = d; } #if 0 int gfs_hook_dup_filedes(int oldfd, int newfd) { _gfs_hook_debug( fprintf(stderr, "GFS: dpu_filedes: %d, %d\n", oldfd, newfd)); #if 0 if (_gfs_file_buf[oldfd] == _gfs_file_buf[newfd]) return (newfd); #endif _gfs_file_buf[newfd] = _gfs_file_buf[oldfd]; } return (newfd); } #endif /* printf and puts should not be put into the following function. */ void * gfs_hook_is_open(int fd) { if (fd < 0 || fd >= MAX_GFS_FILE_BUF) return (NULL); if (_gfs_file_buf[fd] == NULL) return (NULL); switch (gfs_hook_gfs_file_type(fd)) { case GFS_DT_REG: return (_gfs_file_buf[fd]->u.f); case GFS_DT_DIR: return (_gfs_file_buf[fd]->u.d->dir); default: return (NULL); } } /* * hash table for files under creation * * This hash maintains a list of filenames that is created by this * process but not closed yet. This hash is needed to 'stat' these * files in Gfarm v1 API. */ #define CREATING_FILE_HASHTAB_SIZE 53 /* prime number */ static struct gfarm_hash_table *creating_file_hashtab = NULL; char * gfs_hook_add_creating_file(GFS_File gf) { struct gfarm_hash_entry *entry; int created; _gfs_hook_debug(fprintf(stderr, "GFS: add_creating_file: %p (%s)\n", gf, gf->pi.pathname)); if (creating_file_hashtab == NULL) { creating_file_hashtab = gfarm_hash_table_alloc(CREATING_FILE_HASHTAB_SIZE, gfarm_hash_default, gfarm_hash_key_equal_default); if (creating_file_hashtab == NULL) return (GFARM_ERR_NO_MEMORY); } entry = gfarm_hash_enter(creating_file_hashtab, gf->pi.pathname, strlen(gf->pi.pathname) + 1, sizeof(GFS_File), &created); if (entry == NULL) return (GFARM_ERR_NO_MEMORY); /* always update */ *(GFS_File *)gfarm_hash_entry_data(entry) = gf; return (NULL); } GFS_File gfs_hook_is_now_creating(const char *url) { char *pathname, *e; struct gfarm_hash_entry *entry; _gfs_hook_debug(fprintf(stderr, "GFS: is_now_creating: %s\n", url)); if (creating_file_hashtab == NULL) return (NULL); e = gfarm_url_make_path(url, &pathname); if (e != NULL) return (NULL); _gfs_hook_debug(fprintf(stderr, "GFS: is_now_creating: %s\n", pathname)); entry = gfarm_hash_lookup(creating_file_hashtab, pathname, strlen(pathname) + 1); free(pathname); if (entry == NULL) return (NULL); else return *(GFS_File *)gfarm_hash_entry_data(entry); } void gfs_hook_delete_creating_file(GFS_File gf) { _gfs_hook_debug(fprintf(stderr, "GFS: delete_creating_file: %p (%s)\n", gf, gf->pi.pathname)); if (creating_file_hashtab == NULL) return; gfarm_hash_purge(creating_file_hashtab, gf->pi.pathname, strlen(gf->pi.pathname) + 1); return; } void gfs_hook_inc_readcount(int fd) { _gfs_hook_debug( fprintf(stderr, "GFS: inc_readount: %d\n", fd)); ++_gfs_file_buf[fd]->u.d->readcount; } int gfs_hook_is_read(int fd) { return (_gfs_file_buf[fd]->u.d->readcount > 0); } void gfs_hook_set_suspended_gfs_dirent(int fd, struct gfs_dirent *entry) { _gfs_file_buf[fd]->u.d->suspended = entry; } struct gfs_dirent * gfs_hook_get_suspended_gfs_dirent(int fd) { return (_gfs_file_buf[fd]->u.d->suspended); } struct gfs_stat * gfs_hook_get_gfs_stat(int fd) { return (&_gfs_file_buf[fd]->u.d->gst); } char * gfs_hook_get_gfs_canonical_path(int fd) { return (_gfs_file_buf[fd]->u.d->canonical_path); } /* * Check the current working directory is included in Gfarm file system. */ static int _gfs_hook_cwd_is_gfarm = -1; int gfs_hook_set_cwd_is_gfarm(int c) { return (_gfs_hook_cwd_is_gfarm = c); } static void gfs_hook_check_cwd_is_gfarm() { char *cwd; /* * Honor 'PWD', which is set by bash or tcsh with Gfarm * syscall hook library, if it points to a path in Gfarm file * system. */ cwd = getenv("PWD"); if (cwd != NULL) { char *url; if (gfs_hook_is_url(cwd, &url)) { gfs_chdir(url); /* here, cwd is changed. */ gfs_hook_set_cwd_is_gfarm(1); free(url); return; } } gfs_hook_set_cwd_is_gfarm(0); } int gfs_hook_get_cwd_is_gfarm() { if (_gfs_hook_cwd_is_gfarm == -1) gfs_hook_check_cwd_is_gfarm(); return (_gfs_hook_cwd_is_gfarm); } /* * Check whether pathname is gfarm url or not. * * Gfarm URL: gfarm:[:section:]pathname * * It is necessary to free the memory space for *url. */ static char gfs_mntdir[] = "/gfarm"; static char *received_prefix = NULL; static int gfs_hook_is_null_or_slash(const char c) { return (c == '\0' || c == '/' || c == ':'); } static int gfs_hook_is_mount_point(const char *path) { return (*path == '/' && memcmp(path, gfs_mntdir, sizeof(gfs_mntdir) - 1) == 0 && gfs_hook_is_null_or_slash(path[sizeof(gfs_mntdir) - 1])); } static int set_received_prefix(const char *path) { char *end, *p; int len; if (received_prefix != NULL) { free(received_prefix); received_prefix = NULL; } if (gfs_hook_is_mount_point(path)) { received_prefix = strdup(gfs_mntdir); if (received_prefix == NULL) return (0); /* XXX - should return ENOMEM */ return (1); } /* path is either 'gfarm:' or 'gfarm@'. */ if ((end = strchr(path, ':')) == NULL) end = strchr(path, '@'); if (end == NULL) return (0); /* XXX */ len = end - path + 1; p = malloc(len + 1); if (p == NULL) return (0); /* XXX - should return ENOMEM */ received_prefix = p; strncpy(received_prefix, path, len); received_prefix[len] = '\0'; return (1); } /* * Gfarm path starts with '<mount_point>', 'gfarm:' or 'gfarm@'. * * When the Gfarm path starts with '<mount_point>', the path is * considered to be an absolute path instead of a relative path. * * '<mount_point>/~username' such as '/gfarm/~tatebe' can be used to * specify a home directory in Gfarm file system. */ int gfs_hook_is_url(const char *path, char **urlp) { static char prefix[] = "gfarm:"; int sizeof_gfarm_prefix = sizeof(prefix); int sizeof_prefix = sizeof_gfarm_prefix; const char *path_save; int is_mount_point = 0, remove_slash = 0, add_slash = 0; /* * ROOT patch: * 'gfarm@' is also considered as a Gfarm URL */ static char gfarm_url_prefix_for_root[] = "gfarm@"; char *sec = NULL; path_save = path; if (gfs_hook_is_mount_point(path)) { is_mount_point = 1; sizeof_prefix = sizeof(gfs_mntdir); } if (is_mount_point || gfarm_is_url(path) || /* ROOT patch */ memcmp(path, gfarm_url_prefix_for_root, sizeof(gfarm_url_prefix_for_root) - 1) == 0) { if (!gfarm_initialized && gfs_hook_initialize() != NULL) { gfs_hook_not_initialized(); return (0); /* don't perform gfarm operation */ } /* * extension for accessing individual sections * gfarm::section:pathname */ if (path[sizeof_prefix - 1] == ':') { const char *p = path + sizeof_prefix; int secsize = strcspn(p, "/:"); int urlsize; if (p[secsize] != ':') return (0); /* gfarm::foo/:bar or gfarm::foo */ /* * '/gfarm/~' and '/gfarm/.' will be translated * to 'gfarm:~' and 'gfarm:.', respectively. */ if (is_mount_point && p[secsize + 1] == '/' && (p[secsize + 2] == '~' || p[secsize + 2] == '.')) remove_slash = 1; /* '/gfarm' will be translated to 'gfarm:/'. */ if (is_mount_point && path[secsize + 1] == '\0') add_slash = 1; urlsize = sizeof_gfarm_prefix - 1 + add_slash + strlen(p + secsize + remove_slash + 1); *urlp = malloc(urlsize + 1); sec = malloc(secsize + 1); if (*urlp == NULL || sec == NULL) { if (*urlp != NULL) free(*urlp); if (sec != NULL) free(sec); return (0); /* XXX - should return ENOMEM */ } memcpy(*urlp, prefix, sizeof_gfarm_prefix - 1); if (add_slash) strcpy(*urlp + sizeof_gfarm_prefix - 1, "/"); strcpy(*urlp + sizeof_gfarm_prefix - 1 + add_slash, p + secsize + remove_slash + 1); memcpy(sec, p, secsize); sec[secsize] = '\0'; /* It is not necessary to free memory space of 'sec'. */ gfs_hook_set_current_view_section(sec, 1); } else { /* * '/gfarm/~' and '/gfarm/.' will be translated * to 'gfarm:~' and 'gfarm:.', respectively. */ if (is_mount_point && path[sizeof_prefix - 1] == '/' && (path[sizeof_prefix] == '~' || path[sizeof_prefix] == '.')) remove_slash = 1; /* '/gfarm' will be translated to 'gfarm:/'. */ if (is_mount_point && path[sizeof_prefix - 1] == '\0') add_slash = 1; *urlp = malloc(sizeof_gfarm_prefix - 1 + add_slash + strlen(path + sizeof_prefix + remove_slash - 1) + 1); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ /* * the reason why we don't just call strcpy(*url, path) * is because the path may be "gfarm@path/name". * (ROOT patch) */ memcpy(*urlp, prefix, sizeof_gfarm_prefix - 1); if (add_slash) strcpy(*urlp + sizeof_gfarm_prefix - 1, "/"); strcpy(*urlp + sizeof_gfarm_prefix - 1 + add_slash, path + sizeof_prefix + remove_slash - 1); gfs_hook_set_current_view_default(); } if (!set_received_prefix(path_save)) return (0); return (1); } if (*path_save != '/' && gfs_hook_get_cwd_is_gfarm()) { *urlp = malloc(sizeof_gfarm_prefix + strlen(path_save)); if (*urlp == NULL) return (0) ; /* XXX - should return ENOMEM */ memcpy(*urlp, prefix, sizeof_gfarm_prefix - 1); strcpy(*urlp + sizeof_gfarm_prefix - 1, path_save); /* It is not necessary to change the current view. */ return (1); } return (0); } char * gfs_hook_get_prefix(char *buf, size_t size) { if (received_prefix == NULL) return GFARM_ERR_GFARM_URL_PREFIX_IS_MISSING; if (size < strlen(received_prefix)) return GFARM_ERR_NUMERICAL_RESULT_OUT_OF_RANGE; strcpy(buf, received_prefix); return (NULL); } /* * default and current file view manipulation */ static enum gfs_hook_file_view _gfs_hook_default_view = local_view; static int _gfs_hook_default_index = 0; static int _gfs_hook_default_nfrags = GFARM_FILE_DONTCARE; static char *_gfs_hook_default_section = NULL; static enum gfs_hook_file_view _gfs_hook_current_view = local_view; static int _gfs_hook_current_index = 0; static int _gfs_hook_current_nfrags = GFARM_FILE_DONTCARE; static char *_gfs_hook_current_section = NULL; void gfs_hook_set_default_view_local() { _gfs_hook_default_view = local_view; } void gfs_hook_set_default_view_index(int index, int nfrags) { _gfs_hook_default_view = index_view; _gfs_hook_default_index = index; _gfs_hook_default_nfrags = nfrags; } void gfs_hook_set_default_view_global() { _gfs_hook_default_view = global_view; } void gfs_hook_set_default_view_section(char *section) { _gfs_hook_default_view = section_view; if (_gfs_hook_default_section != NULL) free(_gfs_hook_current_section); _gfs_hook_default_section = strdup(section); } static void gfs_hook_set_current_view_local() { _gfs_hook_current_view = local_view; } static void gfs_hook_set_current_view_index(int index, int nfrags) { _gfs_hook_current_view = index_view; _gfs_hook_current_index = index; _gfs_hook_current_nfrags = nfrags; } static void gfs_hook_set_current_view_global() { _gfs_hook_current_view = global_view; } static void gfs_hook_set_current_view_section(char *section, int needfree) { static int space_need_to_be_freeed; _gfs_hook_current_view = section_view; if (_gfs_hook_current_section != NULL && space_need_to_be_freeed) free(_gfs_hook_current_section); space_need_to_be_freeed = needfree; _gfs_hook_current_section = section; } static void gfs_hook_set_current_view_default() { switch (_gfs_hook_default_view) { case local_view: gfs_hook_set_current_view_local(); break; case index_view: gfs_hook_set_current_view_index( _gfs_hook_default_index, _gfs_hook_default_nfrags); break; case global_view: gfs_hook_set_current_view_global(); break; case section_view: gfs_hook_set_current_view_section(_gfs_hook_default_section, 0); break; } } enum gfs_hook_file_view gfs_hook_get_current_view() { return (_gfs_hook_current_view); } int gfs_hook_get_current_index() { return (_gfs_hook_current_index); } int gfs_hook_get_current_nfrags() { return (_gfs_hook_current_nfrags); } char * gfs_hook_get_current_section() { return (_gfs_hook_current_section); } /* * gfs_hook_set_view */ char * gfs_hook_set_view_local(int filedes, int flag) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_local(gf, flag)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_local: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_index(int filedes, int nfrags, int index, char *host, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_index(gf, nfrags, index, host, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_index: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_global(int filedes, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_global(gf, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_global: %s\n", e)); return e; } return NULL; } char * gfs_hook_set_view_section(int filedes, char *section, char *host, int flags) { GFS_File gf; char *e; if ((gf = gfs_hook_is_open(filedes)) == NULL) return "not a Gfarm file"; if ((e = gfs_pio_set_view_section(gf, section, host, flags)) != NULL) { _gfs_hook_debug(fprintf(stderr, "GFS: set_view_section: %s\n", e)); return (e); } return (NULL); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc1/lib/gfs_hook/hooks_subr.h /* convert symbol to string literal */ #define STRING(symbol) #symbol #define S(symbol) STRING(symbol) #ifdef DEBUG #include <stdio.h> extern int gfarm_node, gfarm_nnode; #define _gfs_hook_debug(x) x #define _gfs_hook_debug_v(x) #else #define _gfs_hook_debug(x) #define _gfs_hook_debug_v(x) #endif struct gfs_file; struct gfs_dir; struct gfs_dirent; char *gfs_hook_initialize(void); int gfs_hook_insert_gfs_file(struct gfs_file *); int gfs_hook_insert_gfs_dir(struct gfs_dir *, char *); unsigned char gfs_hook_gfs_file_type(int); char *gfs_hook_clear_gfs_file(int); void *gfs_hook_is_open(int); char *gfs_hook_add_creating_file(struct gfs_file *); struct gfs_file *gfs_hook_is_now_creating(const char *); void gfs_hook_delete_creating_file(struct gfs_file *); void gfs_hook_inc_readcount(int); int gfs_hook_is_read(int); void gfs_hook_set_suspended_gfs_dirent(int, struct gfs_dirent *); struct gfs_dirent *gfs_hook_get_suspended_gfs_dirent(int); struct gfs_stat *gfs_hook_get_gfs_stat(int); char *gfs_hook_get_gfs_canonical_path(int); int gfs_hook_set_cwd_is_gfarm(int); int gfs_hook_get_cwd_is_gfarm(); int gfs_hook_is_url(const char *, char **); char *gfs_hook_get_prefix(char *, size_t); int __syscall_close(int); enum gfs_hook_file_view { local_view, index_view, global_view, section_view }; enum gfs_hook_file_view gfs_hook_get_current_view(); int gfs_hook_get_current_index(); int gfs_hook_get_current_nfrags(); char *gfs_hook_get_current_section(); struct dirent; struct dirent64; struct stat; struct stat64; int gfs_hook_syscall_open(const char *, int, mode_t); int gfs_hook_syscall_getdents(int, struct dirent *, size_t); int gfs_hook_syscall_getdents64(int, struct dirent64 *, size_t); int gfs_hook_syscall_xstat(int, const char *, struct stat *); int gfs_hook_syscall_lxstat(int, const char *, struct stat *); int gfs_hook_syscall_fxstat(int, int, struct stat *); int gfs_hook_syscall_xstat64(int, const char *, struct stat64 *); int gfs_hook_syscall_lxstat64(int, const char *, struct stat64 *); int gfs_hook_syscall_fxstat64(int, int, struct stat64 *); char *gfs_hook_syscall_getcwd(char *, size_t); struct _gfs_file_descriptor; struct _gfs_file_descriptor *gfs_hook_dup_descriptor(int); void gfs_hook_set_descriptor(int, struct _gfs_file_descriptor *); #ifdef _LARGEFILE64_SOURCE off64_t gfs_hook_syscall_lseek64(int, off64_t, int); #endif #define GFS_DEV (dev_t)-1 <file_sep>/gfarm/tags/gfarm_1_0_beta_2/doc/html/ja/ref/index.html <HTML> <HEAD> <TITLE>Gfarm ドキュメント</TITLE> </HEAD> <BODY> <H1>Gfarm 参照マニュアル <HR> <H2>section 1: コマンド</H2> <TABLE> <TR> <TD VALIGN="TOP"> <OL> <LI>クライアント・コマンド <UL> <LI><A HREF="man1/digest.1.html">digest(1)</A> <LI><A HREF="man1/gfexport.1.html">gfexport(1)</A> <LI><A HREF="man1/gfhost.1.html">ghost(1)</A> <LI><A HREF="man1/gfimport_fixed.1.html">gfimport_fixed(1)</A> <LI><A HREF="man1/gfimport_text.1.html">gfimport_text(1)</A> <LI><A HREF="man1/gfkey.1.html">gfkey(1)</A> <LI><A HREF="man1/gfls.1.html">gfls(1)</A> <LI><A HREF="man1/gfmkdir.1.html">gfmkdir(1)</A> <LI><A HREF="man1/gfmpirun_p4.1.html">gfmpirun_p4(1)</A> <LI><A HREF="man1/gfps.1.html">gfps(1)</A> <LI><A HREF="man1/gfrcmd.1.html">gfrcmd(1)</A> <LI><A HREF="man1/gfreg.1.html">gfreg(1)</A> <LI><A HREF="man1/gfrep.1.html">gfrep(1)</A> <LI><A HREF="man1/gfrm.1.html">gfrm(1)</A> <LI><A HREF="man1/gfrmdir.1.html">gfrmdir(1)</A> <LI><A HREF="man1/gfrun.1.html">gfrun(1)</A> <LI><A HREF="man1/gfsched.1.html">gfsched(1)</A> <LI><A HREF="man1/gfwhere.1.html">gfwhere(1)</A> </UL> </OL> </TD> <TD VALIGN="TOP"> <OL START="2"> <LI>並列ツール <UL> <LI><A HREF="man1/gfgrep.1.html">gfgrep(1)</A> <LI><A HREF="man1/gfwc.1.html">gfwc(1)</A> </UL> </OL> </TD> </TR> </TABLE> <HR> <H2>section 3: ライブラリ関数</H2> <TABLE> <TR> <TD VALIGN="TOP"> <OL> <LI>初期化、終了 <UL> <LI><A HREF="man3/gfarm_initialize.3.html">gfarm_initialize.3</A> <LI><A HREF="man3/gfarm_terminate.3.html">gfarm_terminate.3</A> </UL> <LI>並列入出力 <UL> <LI><A HREF="man3/gfs_pio_close.3.html">gfs_pio_close.3</A> <LI><A HREF="man3/gfs_pio_create.3.html">gfs_pio_create.3</A> <LI><A HREF="man3/gfs_pio_eof.3.html">gfs_pio_eof.3</A> <LI><A HREF="man3/gfs_pio_error.3.html">gfs_pio_error.3</A> <LI><A HREF="man3/gfs_pio_flush.3.html">gfs_pio_flush.3</A> <LI><A HREF="man3/gfs_pio_getc.3.html">gfs_pio_getc.3</A> <LI><A HREF="man3/gfs_pio_getline.3.html">gfs_pio_getline.3</A> <LI><A HREF="man3/gfs_pio_open.3.html">gfs_pio_open.3</A> <LI><A HREF="man3/gfs_pio_putc.3.html">gfs_pio_putc.3</A> <LI><A HREF="man3/gfs_pio_putline.3.html">gfs_pio_putline.3</A> <LI><A HREF="man3/gfs_pio_puts.3.html">gfs_pio_puts.3</A> <LI><A HREF="man3/gfs_pio_read.3.html">gfs_pio_read.3</A> <LI><A HREF="man3/gfs_pio_seek.3.html">gfs_pio_seek.3</A> <LI><A HREF="man3/gfs_pio_set_local.3.html">gfs_pio_set_local.3</A> <LI><A HREF="man3/gfs_pio_set_view_index.3.html">gfs_pio_set_view_index.3</A> <LI><A HREF="man3/gfs_pio_set_view_local.3.html">gfs_pio_set_view_local.3</A> <LI><A HREF="man3/gfs_pio_ungetc.3.html">gfs_pio_ungetc.3</A> <LI><A HREF="man3/gfs_pio_write.3.html">gfs_pio_write.3</A> </UL> <LI>ディレクトリ操作 <UL> <LI><A HREF="man3/gfs_closedir.3.html">gfs_closedir.3</A> <LI><A HREF="man3/gfs_opendir.3.html">gfs_opendir.3</A> <LI><A HREF="man3/gfs_readdir.3.html">gfs_readdir.3</A> <LI><A HREF="man3/gfs_stat.3.html">gfs_stat.3</A> <LI><A HREF="man3/gfs_stat_free.3.html">gfs_stat_free.3</A> <LI><A HREF="man3/gfs_unlink.3.html">gfs_unlink.3</A> </UL> </OL> </TD> <TD VALIGN="TOP"> <OL START="4"> <LI>複製・プログラム登録 <UL> <LI><A HREF="man3/gfarm_url_fragments_replicate.3.html">gfarm_url_fragments_replicate.3</A> <LI><A HREF="man3/gfarm_url_program_deliver.3.html">gfarm_url_program_deliver.3</A> <LI><A HREF="man3/gfarm_url_program_register.3.html">gfarm_url_program_register.3</A> <LI><A HREF="man3/gfarm_url_section_replicate_from_to.3.html">gfarm_url_section_replicate_from_to.3</A> <LI><A HREF="man3/gfarm_url_section_replicate_to.3.html">gfarm_url_section_replicate_to.3</A> </UL> <LI>スケジューリング <UL> <LI><A HREF="man3/gfarm_url_hosts_schedule.3.html">gfarm_url_hosts_schedule.3</A> </UL> <LI>gfimport ヘルパー <UL> <LI><A HREF="man3/gfarm_hostlist_read.3.html">gfarm_hostlist_read.3</A> <LI><A HREF="man3/gfarm_import_fragment_config_read.3.html">gfarm_import_fragment_config_read.3</A> <LI><A HREF="man3/gfarm_import_fragment_size_alloc.3.html">gfarm_import_fragment_size_alloc.3</A> </UL> <LI>文字列配列操作 <UL> <LI><A HREF="man3/GFARM_STRINGLIST_ELEM.3.html">GFARM_STRINGLIST_ELEM.3</A> <LI><A HREF="man3/GFARM_STRINGLIST_STRARRAY.3.html">GFARM_STRINGLIST_STRARRAY.3</A> <LI><A HREF="man3/gfarm_stringlist_add.3.html">gfarm_stringlist_add.3</A> <LI><A HREF="man3/gfarm_stringlist_cat.3.html">gfarm_stringlist_cat.3</A> <LI><A HREF="man3/gfarm_stringlist_elem.3.html">gfarm_stringlist_elem.3</A> <LI><A HREF="man3/gfarm_stringlist_free.3.html">gfarm_stringlist_free.3</A> <LI><A HREF="man3/gfarm_stringlist_init.3.html">gfarm_stringlist_init.3</A> <LI><A HREF="man3/gfarm_stringlist_length.3.html">gfarm_stringlist_length.3</A> <LI><A HREF="man3/gfarm_strings_free_deeply.3.html">gfarm_strings_free_deeply.3</A> </UL> </OL> </TD> </TR> </TABLE> <HR> <H2>section 5: ファイル形式</H2> <UL> <LI><A HREF="man5/gfarm.conf.5.html">gfarm.conf.5</A> </UL> <HR> <H2>section 8: デーモン</H2> <UL> <LI><A HREF="man8/gfmd.8.html">gfmd.8</A> <LI><A HREF="man8/gfsd.8.html">gfsd.8</A> </UL> <HR> </BODY> </HTML> <file_sep>/gfarm/branches/soda/man/ja/man8/Makefile # $Id$ top_objdir = ../../.. top_srcdir = $(top_objdir) srcdir = . include $(top_srcdir)/makes/var.mk include $(srcdir)/../Makefile.inc MAN = gfmd.8 gfsd.8 include $(top_srcdir)/makes/man.mk <file_sep>/gfarm_zabbix/tags/gfarm_zabbix_1_0_1/src/failure_test_scripts/FT2-2-1-1_master_gfmd_down_with_observer_network_down #! /bin/sh ###################################################################### TESTID="FT2-2-1-1" CATEGORY="2 point accident" SECTION="internal accident and network down" TITLE="master gfmd down with observer network down" ###################################################################### . ./FT-common ft_setup() { IFUP_PATH=/sbin/ifup IFDOWN_PATH=/sbin/ifdown if [ `hostname` = $zabbix2 ]; then zabbix=$zabbix2 zabbix_GFARM_IF=$zabbix2_GFARM_IF zabbix_CTRL_ADDRESS=$zabbix2_CTRL_ADDRESS else zabbix=$zabbix1 zabbix_GFARM_IF=$zabbix1_GFARM_IF zabbix_CTRL_ADDRESS=$zabbix1_CTRL_ADDRESS fi return $FT_RESULT_PASS } ft_main() { RESULT=$FT_RESULT_PASS $gfservice stop-gfmd gfmd1 \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 1 "stop gfmd on $gfmd1" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT sudo $IFDOWN_PATH $zabbix_GFARM_IF \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 2 "ifdown $zabbix_GFARM_IF on $zabbix" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT ft_check_mails \ "$gfmd1 is unreachable" \ "$gfmd2 is unreachable" \ "$gfmd3 is unreachable" \ "$gfsd1 is unreachable" \ "$gfsd2 is unreachable" \ || RESULT=$FT_RESULT_FAIL ft_checkpoint 3 "receive a mail" $RESULT [ $RESULT -eq $FT_RESULT_PASS ] || return $RESULT return $RESULT } ft_teardown() { sudo $IFUP_PATH $zabbix_GFARM_IF ft_reset_gfmd return $FT_RESULT_PASS } ft_run "$TESTID" "$TITLE" <file_sep>/gfarmfs-fuse/trunk/gfarmfs.c /* * GfarmFS-FUSE * * Gfarm: * http://datafarm.apgrid.org/ * http://sourceforge.net/projects/gfarm/ * * FUSE: * http://fuse.sourceforge.net/ * * Mount: * $ ./gfarmfs [GfarmFS options] <mountpoint> [FUSE options] * * Unmount: * $ fusermount -u <mountpoint> * * Copyright (c) 2005-2007 National Institute of Advanced Industrial * Science and Technology (AIST). * Copyright (c) 2006-2007 <NAME>. */ #include <fuse.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <libgen.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <stdarg.h> #include <sys/sem.h> #include <syslog.h> #include <gfarm/gfarm.h> /* These definitions may conflict with <gfarm/gfarm_config.h> */ #ifdef PACKAGE_NAME #undef PACKAGE_NAME #endif #ifdef PACKAGE_STRING #undef PACKAGE_STRING #endif #ifdef PACKAGE_TARNAME #undef PACKAGE_TARNAME #endif #ifdef PACKAGE_VERSION #undef PACKAGE_VERSION #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #if FUSE_USE_VERSION >= 25 #ifdef USE_KERNEL_2_6_14 /* Linux kernel 2.6.14 or earlier */ #define ENABLE_FASTCREATE 1 #define DISABLE_FUSE_CREATE #define IGNORE_TRUNCATE_EACCES #endif #elif FUSE_USE_VERSION == 22 #define ENABLE_FASTCREATE 1 #else # error Please install FUSE 2.2 or later #endif #define GFARMFS_VERSION PACKAGE_VERSION #define GFARMFS_REVISION "$Revision$" #ifndef GFS_DEV #define GFS_DEV ((dev_t)-1); #endif #ifndef GFS_BLKSIZE #define GFS_BLKSIZE 8192 #endif #ifndef STAT_BLKSIZ #define STAT_BLKSIZ 512 #endif #define SYMLINK_MODE 1 #ifdef SYMLINK_MODE #define SYMLINK_SUFFIX ".gfarmfs-symlink" #define SYMLINK_SUFFIX_LEN (sizeof(SYMLINK_SUFFIX)-1) #endif #ifdef GFARM_MAJOR_VERSION #define GFARM_USE_VERSION GFARM_MAJOR_VERSION #else #define GFARM_USE_VERSION 1 #endif #if GFARM_USE_VERSION == 1 #define REVISE_UTIME 1 /* problem of gfarm v1 */ #endif /* limitation in global view of gfarm v1.3.1 or earlier */ #define REVISE_CHMOD 0 #define ENABLE_ASYNC_REPLICATION 1 #define ENABLE_XATTR 0 /* ################################################################### */ static int gfarmfs_debug = 0; /* 1: error, 2: debug */ static int enable_symlink = 0; static int enable_linkiscopy = 0; static int enable_unlinkall = 0; static char *arch_name = NULL; static int enable_count_dir_nlink = 0; /* default: disable */ static FILE *enable_trace = NULL; static int enable_timer = 0; static char *trace_name = NULL; /* filename */ static FILE *enable_errlog = NULL; static char *errlog_name = NULL; /* filename */ static FILE *errlog_out; static int enable_syslog = 0; static char *gfarm_mount_point = ""; static int gfarm_mount_point_len = 0; static int enable_gfarm_iobuf = 0; /* about GFARM_FILE_UNBUFFERED */ static int enable_exact_filesize = 0; static int path_info_timeout = 0; #if ENABLE_ASYNC_REPLICATION enum repmode { REP_FROMTO_FUNC /* gfarm_url_section_replicate_from_to() */, REP_GFREP_N /* gfrep -N */, #if USE_SCHEDULER REP_GFREP_HN /* gfrep -H -N */, REP_GFREP_d /* gfrep -d */, #endif #if USE_GFARM_SCRAMBLE REP_SCRAMBLE, #endif REP_DISABLE }; enum repmode replication_mode = REP_DISABLE; static char *gfrep_path = NULL; static int replication_num = -1; static char *replication_domain = NULL; #if USE_SCHEDULER static int use_gfrep = 0; static int force_gfrep_N = 0; #endif #endif /* ENABLE_ASYNC_REPLICATION */ /* 0: use gfarmfs_*_share_gf() operations (new) * 1: use normal I/O operations (old) */ static int use_old_functions = 0; /* default: enable */ #ifdef ENABLE_FASTCREATE static int enable_fastcreate = 1; /* used on FUSE version 2.2 only */ /* >0: enable, 0: disable, <0: ignore */ #endif #if USE_GFS_STATFSNODE static int enable_statfs = 1; /* default: enable */ #endif /* ################################################################### */ static char * add_gfarm_prefix(const char *path, char **urlp) { char *url; int len; len = gfarm_mount_point_len + strlen(path) + 7; url = malloc(sizeof(char) * len); if (url == NULL) return (GFARM_ERR_NO_MEMORY); snprintf(url, len, "gfarm:%s%s", gfarm_mount_point, path); *urlp = url; return (NULL); } #ifdef SYMLINK_MODE static char * add_gfarm_prefix_symlink_suffix(const char *path, char **urlp) { char *url; int len; len = gfarm_mount_point_len + strlen(path) + 7 + SYMLINK_SUFFIX_LEN; url = malloc(sizeof(char) * len); if (url == NULL) return (GFARM_ERR_NO_MEMORY); snprintf(url, len, "gfarm:%s%s%s", gfarm_mount_point, path, SYMLINK_SUFFIX); *urlp = url; return (NULL); } #endif /* cut "gfarm:" */ #define gfarm_url2path(url) (url + 6 + gfarm_mount_point_len) static void gfarmfs_errlog(const char *format, ...) { va_list ap; struct timeval tv; struct tm *lt; va_start(ap, format); gettimeofday(&tv, NULL); lt = localtime((time_t*)&tv.tv_sec); fprintf(errlog_out, "[%.2d-%.2d %.2d:%.2d:%.2d] ", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); vfprintf(errlog_out, format, ap); fprintf(errlog_out, "\n"); if (enable_syslog == 1) { char buf[2048]; vsnprintf(buf, sizeof(buf), format, ap); syslog(LOG_ERR, "%s", buf); } va_end(ap); } #define SECOND_BY_MICROSEC 1000000 static void timeval_normalize(struct timeval *t) { long n; if (t->tv_usec >= SECOND_BY_MICROSEC) { n = t->tv_usec / SECOND_BY_MICROSEC; t->tv_usec -= n * SECOND_BY_MICROSEC; t->tv_sec += n; } else if (t->tv_usec < 0) { n = -t->tv_usec / SECOND_BY_MICROSEC + 1; t->tv_usec += n * SECOND_BY_MICROSEC; t->tv_sec -= n; } } static void timeval_add(struct timeval *t1, const struct timeval *t2) { t1->tv_sec += t2->tv_sec; t1->tv_usec += t2->tv_usec; timeval_normalize(t1); } static void timeval_sub(struct timeval *t1, const struct timeval *t2) { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; timeval_normalize(t1); } struct gfarmfs_prof { char *opname; struct timeval timer; struct timeval op_total_time; unsigned long op_count; }; static char OP_GETATTR[] = "GETATTR"; static char OP_READLINK[] = "READLINK"; static char OP_GETDIR[] = "GETDIR"; static char OP_MKNOD[] = "MKNOD"; static char OP_MKDIR[] = "MKDIR"; static char OP_SYMLINK[] = "SYMLINK"; static char OP_UNLINK[] = "UNLINK"; static char OP_RMDIR[] = "RMDIR"; static char OP_RENAME[] = "RENAME"; static char OP_LINK[] = "LINK"; static char OP_CHMOD[] = "CHMOD"; static char OP_CHOWN[] = "CHOWN"; static char OP_TRUNCATE[] = "TRUNCATE"; static char OP_UTIME[] = "UTIME"; static char OP_OPEN[] = "OPEN"; static char OP_READ[] = "READ"; static char OP_WRITE[] = "WRITE"; static char OP_RELEASE[] = "RELEASE"; static char OP_FSYNC[] = "FSYNC"; static char OP_STATFS[] = "STATFS"; static char OP_CREATE[] = "CREATE"; static char OP_FGETATTR[] = "FGETATTR"; static char OP_FTRUNCATE[] = "FTRUNCATE"; static char OP_ACCESS[] = "ACCESS"; static char OP_FLUSH[] = "FLUSH"; static char OP_SETXATTR[] = "SETXATTR"; static char OP_GETXATTR[] = "GETXATTR"; static char OP_LISTXATTR[] = "LISTXATTR"; static char OP_REMOVEXATTR[] = "REMOVEXATTR"; static struct gfarmfs_prof prof_getattr; static struct gfarmfs_prof prof_readlink; static struct gfarmfs_prof prof_getdir; static struct gfarmfs_prof prof_mknod; static struct gfarmfs_prof prof_mkdir; static struct gfarmfs_prof prof_symlink; static struct gfarmfs_prof prof_unlink; static struct gfarmfs_prof prof_rmdir; static struct gfarmfs_prof prof_rename; static struct gfarmfs_prof prof_link; static struct gfarmfs_prof prof_chmod; static struct gfarmfs_prof prof_chown; static struct gfarmfs_prof prof_truncate; static struct gfarmfs_prof prof_utime; static struct gfarmfs_prof prof_open; static struct gfarmfs_prof prof_read; static struct gfarmfs_prof prof_write; static struct gfarmfs_prof prof_release; static struct gfarmfs_prof prof_fsync; static struct gfarmfs_prof prof_statfs; static struct gfarmfs_prof prof_create; static struct gfarmfs_prof prof_fgetattr; static struct gfarmfs_prof prof_ftruncate; static struct gfarmfs_prof prof_access; static struct gfarmfs_prof prof_flush; static struct gfarmfs_prof prof_setxattr; static struct gfarmfs_prof prof_getxattr; static struct gfarmfs_prof prof_listxattr; static struct gfarmfs_prof prof_removexattr; static void prof_set(struct gfarmfs_prof *profp, char *opname) { profp->opname = opname; profp->op_total_time.tv_sec = 0; profp->op_total_time.tv_usec = 0; profp->op_count = 0; } struct timeval total_time; static void gfarmfs_prof_init() { prof_set(&prof_getattr, OP_GETATTR); prof_set(&prof_readlink, OP_READLINK); prof_set(&prof_getdir, OP_GETDIR); prof_set(&prof_mknod, OP_MKNOD); prof_set(&prof_mkdir, OP_MKDIR); prof_set(&prof_symlink, OP_SYMLINK); prof_set(&prof_unlink, OP_UNLINK); prof_set(&prof_rmdir, OP_RMDIR); prof_set(&prof_rename, OP_RENAME); prof_set(&prof_link, OP_LINK); prof_set(&prof_chmod, OP_CHMOD); prof_set(&prof_chown, OP_CHOWN); prof_set(&prof_truncate, OP_TRUNCATE); prof_set(&prof_utime, OP_UTIME); prof_set(&prof_open, OP_OPEN); prof_set(&prof_read, OP_READ); prof_set(&prof_write, OP_WRITE); prof_set(&prof_release, OP_RELEASE); prof_set(&prof_fsync, OP_FSYNC); prof_set(&prof_statfs, OP_STATFS); prof_set(&prof_create, OP_CREATE); prof_set(&prof_fgetattr, OP_FGETATTR); prof_set(&prof_ftruncate, OP_FTRUNCATE); prof_set(&prof_access, OP_ACCESS); prof_set(&prof_flush, OP_FLUSH); prof_set(&prof_setxattr, OP_SETXATTR); prof_set(&prof_getxattr, OP_GETXATTR); prof_set(&prof_listxattr, OP_LISTXATTR); prof_set(&prof_removexattr, OP_REMOVEXATTR); if (enable_timer) { total_time.tv_sec = 0; total_time.tv_usec = 0; } } static void prof_print(struct gfarmfs_prof *profp, double total) { double time = (((double)profp->op_total_time.tv_sec) * SECOND_BY_MICROSEC + profp->op_total_time.tv_usec) / SECOND_BY_MICROSEC; if (time != 0) printf("%13s: %11.6f s (%4.1f %%) = %8.6f * %lu\n", profp->opname, time, time * 100 / total, time / profp->op_count, profp->op_count); } static void gfarmfs_prof_final() { double total; if (!enable_timer) return; total = (((double)total_time.tv_sec) * SECOND_BY_MICROSEC + total_time.tv_usec) / SECOND_BY_MICROSEC; printf("====== gfarmfs profiler (successful operation only) ======\n"); prof_print(&prof_getattr, total); prof_print(&prof_readlink, total); prof_print(&prof_getdir, total); prof_print(&prof_mknod, total); prof_print(&prof_mkdir, total); prof_print(&prof_symlink, total); prof_print(&prof_unlink, total); prof_print(&prof_rmdir, total); prof_print(&prof_rename, total); prof_print(&prof_link, total); prof_print(&prof_chmod, total); prof_print(&prof_chown, total); prof_print(&prof_truncate, total); prof_print(&prof_utime, total); prof_print(&prof_open, total); prof_print(&prof_read, total); prof_print(&prof_write, total); prof_print(&prof_release, total); prof_print(&prof_fsync, total); prof_print(&prof_statfs, total); prof_print(&prof_create, total); prof_print(&prof_fgetattr, total); prof_print(&prof_ftruncate, total); prof_print(&prof_access, total); prof_print(&prof_flush, total); prof_print(&prof_setxattr, total); prof_print(&prof_getxattr, total); prof_print(&prof_listxattr, total); prof_print(&prof_removexattr, total); printf("Total time in gfarmfs (including errors): %10.6f s\n", total); } static char * (*gfarmfs_init)(struct gfarmfs_prof *) = NULL; static int (*gfarmfs_final)(struct gfarmfs_prof *, char *, int, const char *) = NULL; static char * gfarmfs_init_normal(struct gfarmfs_prof *profp) { (void)profp; return (NULL); } static char * gfarmfs_init_prof(struct gfarmfs_prof *profp) { (void)profp; if (enable_timer) gettimeofday(&profp->timer, NULL); return (NULL); } static int gfarmfs_final_normal(struct gfarmfs_prof *profp, char *e, int val_noerror, const char *name) { int return_errno; if (e == NULL) { return (val_noerror); } else { return_errno = gfarm_error_to_errno(e); if (return_errno == EINVAL || profp->opname == OP_RELEASE) gfarmfs_errlog("%s: %s%s: %s", profp->opname, gfarm_mount_point, name, e); return -return_errno; } } static int gfarmfs_final_prof(struct gfarmfs_prof *profp, char *e, int val_noerror, const char *name) { int return_errno; struct timeval now; double time = 0; if (enable_timer) { gettimeofday(&now, NULL); timeval_sub(&now, &profp->timer); if (e == NULL) { timeval_add(&total_time, &now); timeval_add(&profp->op_total_time, &now); profp->op_count++; } /* else if (e != NULL) -- no count */ time = (((double)now.tv_sec) * SECOND_BY_MICROSEC + now.tv_usec) / SECOND_BY_MICROSEC; } if (e == NULL) { if (enable_trace != NULL) { if (enable_timer) fprintf(enable_trace, "OK: %s(%8.6f): %s%s\n", profp->opname, time, gfarm_mount_point, name); else fprintf(enable_trace, "OK: %s: %s%s\n", profp->opname, gfarm_mount_point, name); } return (val_noerror); } else { if (enable_trace != NULL) { if (enable_timer) fprintf(enable_trace, "NG: %s(%8.6f): %s%s: %s\n", profp->opname, time, gfarm_mount_point, name, e); else fprintf(enable_trace, "NG: %s: %s%s: %s\n", profp->opname, gfarm_mount_point, name, e); } return_errno = gfarm_error_to_errno(e); if (return_errno == EINVAL || profp->opname == OP_RELEASE) gfarmfs_errlog("%s: %s%s: %s", profp->opname, gfarm_mount_point, name, e); return -return_errno; } } static int gfarmfs_dir_nlink(const char *url) { GFS_Dir dir; struct gfs_dirent *entry; char *e; int res = 0; if (enable_count_dir_nlink == 0) { return (32000); } e = gfs_opendir(url, &dir); if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { if (S_ISDIR(DTTOIF(entry->d_type))) { res++; } } gfs_closedir(dir); } if (res == 0) { return (2); } else { return (res); } } #ifdef SYMLINK_MODE static int ends_with_and_delete(char *str, char *suffix) { int m, n; m = strlen(str) - 1; n = strlen(suffix) - 1; while (n >=0) { if (m <= 0 || str[m] != suffix[n]) { return (0); /* false */ } m--; n--; } str[m + 1] = '\0'; return (1); /* true */ } #endif #ifdef USE_GFARM_SCRAMBLE /* for scramble version */ #define gfarmfs_set_view(gf) gfs_pio_set_view_scramble(gf, 0) #else /* for normal version */ static char * gfarmfs_set_view(GFS_File gf) { char *e; int nf; e = gfs_pio_get_nfragment(gf, &nf); if (e == NULL && nf <= 1) e = gfs_pio_set_view_index(gf, 1, 0, NULL, 0); else /* GFARM_ERR_FRAGMENT_INDEX_NOT_AVAILABLE -> creating new file */ e = gfs_pio_set_view_global(gf, 0); return (e); } #endif static char * gfarmfs_create_empty_file(const char *path, mode_t mode) { char *e, *e2; char *url; GFS_File gf; e = add_gfarm_prefix(path, &url); if (e != NULL) return (e); e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, mode, &gf); if (e == NULL) { e2 = gfarmfs_set_view(gf); e = gfs_pio_close(gf); if (e2 != NULL) e = e2; } free(url); return (e); } /* ################################################################### */ #ifdef ENABLE_FASTCREATE struct fastcreate { char *path; mode_t mode; }; static struct fastcreate fc = {NULL, 0}; static void gfarmfs_fastcreate_free() { if (fc.path != NULL) { free(fc.path); fc.path = NULL; } } static char * gfarmfs_fastcreate_flush() { if (fc.path != NULL) { char *e; if (gfarmfs_debug >= 2) { printf("FASTCREATE: flush: %s%s\n", gfarm_mount_point, fc.path); } e = gfarmfs_create_empty_file(fc.path, fc.mode); if (e != NULL) { gfarmfs_errlog("FASTCREATE: flush: %s%s: %s", gfarm_mount_point, fc.path, e); } gfarmfs_fastcreate_free(); return (e); } else { return (NULL); /* do nothing */ } } static char * gfarmfs_fastcreate_save(const char *path, mode_t mode) { gfarmfs_fastcreate_flush(); fc.path = strdup(path); if (fc.path == NULL) { return (GFARM_ERR_NO_MEMORY); } fc.mode = mode; if (gfarmfs_debug >= 2) { printf("FASTCREATE: add: %s\n", path); } return (NULL); } static char * gfarmfs_fastcreate_open(char *url, int flags, GFS_File *gfp) { char *e; char *path = gfarm_url2path(url); if (fc.path != NULL && strcmp(fc.path, path) == 0) { if (gfarmfs_debug >= 2) { printf("FASTCREATE: open: %s\n", path); } e = gfs_pio_create(url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, fc.mode, gfp); if (e == NULL) { e = gfarmfs_set_view(*gfp); if (e != NULL) gfs_pio_close(*gfp); } gfarmfs_fastcreate_free(); } else { gfarmfs_fastcreate_flush(); /* flush previous saved path */ e = gfs_pio_open(url, flags, gfp); if (e == NULL) { e = gfarmfs_set_view(*gfp); if (e != NULL) gfs_pio_close(*gfp); } } return (e); } static int gfarmfs_fastcreate_getattr(const char *path, struct stat *buf) { time_t now; if (fc.path != NULL && strcmp(fc.path, path) == 0) { memset(buf, 0, sizeof(struct stat)); buf->st_dev = GFS_DEV; buf->st_ino = 12345; /* XXX */ buf->st_mode = fc.mode; buf->st_nlink = 1; buf->st_uid = getuid(); buf->st_gid = getgid(); buf->st_size = 0; buf->st_blksize = GFS_BLKSIZE; buf->st_blocks = 0; time(&now); buf->st_atime = buf->st_mtime = buf->st_ctime = now; return (1); } else { return (0); } } #define gfarmfs_fastcreate_check() \ (enable_fastcreate > 0 ? (gfarmfs_fastcreate_flush() == NULL ? 1 : -1) : 0) #else #define gfarmfs_fastcreate_check() #endif /* ENABLE_FASTCREATE */ /* ################################################################### */ static char * convert_gfs_stat_to_stat(const char *url, struct gfs_stat *gsp, struct stat *stp, int symlink) { /* referred to hooks_stat.c */ struct passwd *p; static struct passwd *p_save = NULL; static char *username_save = NULL; memset(stp, 0, sizeof(struct stat)); stp->st_dev = GFS_DEV; stp->st_ino = gsp->st_ino; stp->st_mode = gsp->st_mode; #ifdef SYMLINK_MODE if (symlink == 1) { stp->st_mode = 0777 | S_IFLNK; } #endif if (url != NULL && GFARM_S_ISDIR(stp->st_mode)) { stp->st_nlink = gfarmfs_dir_nlink(url); } else { stp->st_nlink = 1; } if (gsp->st_user != NULL && username_save != NULL && strcmp(gsp->st_user, username_save) == 0) { stp->st_uid = p_save->pw_uid; stp->st_gid = p_save->pw_gid; } else if (gsp->st_user != NULL && ((p = getpwnam(gsp->st_user)) != NULL)) { stp->st_uid = p->pw_uid; stp->st_gid = p->pw_gid; if (username_save != NULL) free(username_save); username_save = strdup(gsp->st_user); p_save = p; } else { stp->st_uid = getuid(); stp->st_gid = getgid(); } stp->st_size = gsp->st_size; stp->st_blksize = GFS_BLKSIZE; stp->st_blocks = (gsp->st_size + STAT_BLKSIZ - 1) / STAT_BLKSIZ; stp->st_atime = gsp->st_atimespec.tv_sec; stp->st_mtime = gsp->st_mtimespec.tv_sec; stp->st_ctime = gsp->st_ctimespec.tv_sec; return (NULL); } static char * gfarmfs_exact_filesize(char *url, file_offset_t *sizep, mode_t mode) { /* get st_size using gfs_fstat */ /* gfs_stat cannot get the exact st_size while the file is opened. * But gfs_fstat can do it. */ GFS_File gf; int flags; char *e; struct gfs_stat gs; file_offset_t st_size; int change_mode = 0; mode_t save_mode = 0; if (mode & 0444) { flags = GFARM_FILE_RDONLY; } else { save_mode = mode; e = gfs_chmod(url, mode|0400); if (e != NULL) { gfarmfs_errlog("GETATTR: cancel fstat: %s: %s", gfarm_url2path(url), e); return (e); /* not my modifiable file */ } change_mode = 1; flags = GFARM_FILE_RDONLY; } e = gfs_pio_open(url, flags, &gf); if (e != NULL) goto revert_mode; #ifdef USE_GFARM_SCRAMBLE e = gfs_pio_set_view_scramble(gf, 0); if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size = gs.st_size; gfs_stat_free(&gs); #else if (GFARM_S_IS_PROGRAM(mode)) { e = gfs_pio_set_view_global(gf, 0); if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size = gs.st_size; gfs_stat_free(&gs); } else { int nf, i; e = gfs_pio_get_nfragment(gf, &nf); if (e != NULL) goto fstat_close; st_size = 0; for (i = 0; i < nf; i++) { e = gfs_pio_set_view_index(gf, nf, i, NULL, 0); if (e != NULL) goto fstat_close; e = gfs_fstat(gf, &gs); if (e != NULL) goto fstat_close; st_size += gs.st_size; gfs_stat_free(&gs); } } #endif /* success */ *sizep = st_size; fstat_close: gfs_pio_close(gf); if (e != NULL && e != GFARM_ERR_NO_SUCH_OBJECT) gfarmfs_errlog("exact_filesize: %s: %s", gfarm_url2path(url), e); revert_mode: if (change_mode == 1) { e = gfs_chmod(url, save_mode); if (e != NULL) gfarmfs_errlog("exact_filesize: " "revert st_mode (%o): %s: %s", save_mode, gfarm_url2path(url), e); } return (e); } static char * gfarmfs_gfs_stat_from_pi_only(const char *path, struct gfs_stat *gsp) { char *e; struct gfarm_path_info pi; char *p, *url; e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfarm_url_make_path(url, &p); free(url); } if (e == NULL) { e = gfarm_path_info_get(p, &pi); if (e == NULL) { *gsp = pi.status; gsp->st_user = strdup(pi.status.st_user); gsp->st_group = strdup(pi.status.st_group); gfarm_path_info_free(&pi); gsp->st_size = 0; } free(p); } return (e); } static int gfarmfs_getattr(const char *path, struct stat *buf) { char *e; struct gfs_stat gs; char *url; int symlinkmode = 0; if ((e = gfarmfs_init(&prof_getattr)) != NULL) goto end; #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, buf)) { goto end; } #endif e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; if (gfarmfs_debug >= 2) { printf("GETATTR: for symlink: %s\n", gfarm_url2path(url)); } e = gfs_stat(url, &gs); symlinkmode = 1; } #endif if (enable_exact_filesize == 1 && e == NULL && GFARM_S_ISREG(gs.st_mode)) { char *e2; file_offset_t size; e2 = gfarmfs_exact_filesize(url, &size, gs.st_mode); if (e2 == NULL) gs.st_size = size; } if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION && gfarmfs_gfs_stat_from_pi_only(path, &gs) == NULL) e = NULL; if (e == NULL) { e = convert_gfs_stat_to_stat(url, &gs, buf, symlinkmode); gfs_stat_free(&gs); } free(url); end: return gfarmfs_final(&prof_getattr, e, 0, path); } static int gfarmfs_getdir(const char *path, fuse_dirh_t h, fuse_dirfil_t filler) { GFS_Dir dir; struct gfs_dirent *entry; char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_getdir); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_opendir(url, &dir); free(url); } } if (e == NULL) { while ((e = gfs_readdir(dir, &entry)) == NULL && entry != NULL) { #ifdef SYMLINK_MODE if (enable_symlink == 1 && ends_with_and_delete(entry->d_name, SYMLINK_SUFFIX) > 0) { entry->d_type = DT_LNK; } #endif if (filler(h, entry->d_name, entry->d_type, entry->d_ino) != 0) break; } e = gfs_closedir(dir); } return gfarmfs_final(&prof_getdir, e, 0, path); } static int gfarmfs_mknod(const char *path, mode_t mode, dev_t rdev) { char *e; if ((e = gfarmfs_init(&prof_mknod)) != NULL) goto end; if (S_ISREG(mode)) { #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0) { e = gfarmfs_fastcreate_save(path, mode); } else { e = gfarmfs_create_empty_file(path, mode); } #else e = gfarmfs_create_empty_file(path, mode); #endif } else { gfarmfs_errlog( "MKNOD: not supported: %s%s: mode=%o, rdev=%o", gfarm_mount_point, path, mode, (int)rdev); e = GFARM_ERR_OPERATION_NOT_PERMITTED; } end: return gfarmfs_final(&prof_mknod, e, 0, path); } static int gfarmfs_mkdir(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_mkdir); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_mkdir(url, mode); free(url); } } return gfarmfs_final(&prof_mkdir, e, 0, path); } static char * gfarmfs_unlink_self_arch(const char *url) { char *e; struct gfs_stat gs; e = gfs_stat(url, &gs); if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION) { e = gfs_unlink(url); if (e == GFARM_ERR_NO_SUCH_OBJECT) e = NULL; } else if (e == NULL) { /* gfs_stat succeeds */ if (GFARM_S_IS_PROGRAM(gs.st_mode)) { /* executable file */ char *arch; e = gfarm_host_get_self_architecture(&arch); if (e != NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } else { e = gfs_unlink_section(url, arch); } } else { /* regular file */ e = gfs_unlink(url); } gfs_stat_free(&gs); } return (e); } static char *(*gfarmfs_unlink_op)(const char *) = gfarmfs_unlink_self_arch; static int gfarmfs_unlink(const char *path) { char *e; char *url; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_unlink)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_unlink_op(url); free(url); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { if (gfarmfs_debug >= 2) printf("UNLINK: for symlink: %s\n", path); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfarmfs_unlink_op(url); free(url); } #endif end: return gfarmfs_final(&prof_unlink, e, 0, path); } static int gfarmfs_rmdir(const char *path) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_rmdir); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_rmdir(url); free(url); } } return gfarmfs_final(&prof_rmdir, e, 0, path); } static int gfarmfs_readlink(const char *path, char *buf, size_t size) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n = 0; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_readlink)) != NULL) goto end; if (enable_symlink == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_pio_open(url, GFARM_FILE_RDONLY, &gf); if (e == NULL) { e = gfs_pio_read(gf, buf, size - 1, &n); gfs_pio_close(gf); } free(url); buf[n] = '\0'; end: return gfarmfs_final(&prof_readlink, e, 0, path); #else char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_readlink); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } return gfarmfs_final(&prof_readlink, e, 0, path); #endif } static int gfarmfs_symlink(const char *from, const char *to) { #ifdef SYMLINK_MODE /* This is for exclusive use of GfarmFS-FUSE. */ char *e; char *url; GFS_File gf; int n, len; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_symlink)) != NULL) goto end; if (enable_symlink == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } e = add_gfarm_prefix_symlink_suffix(to, &url); if (e != NULL) goto end; e = gfs_pio_create(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, 0644, &gf); if (e != NULL) goto free_url; len = strlen(from); e = gfs_pio_write(gf, from, len, &n); gfs_pio_close(gf); if (len != n) { e = gfs_unlink(url); e = GFARM_ERR_INPUT_OUTPUT; goto free_url; } free_url: free(url); end: return gfarmfs_final(&prof_symlink, e, 0, to); #else char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_symlink); if (e == NULL) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; } return gfarmfs_final(&prof_symlink, e, 0, to); #endif } static int gfarmfs_rename(const char *from, const char *to) { char *e; char *from_url; char *to_url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_rename); if (e == NULL) { e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix(to, &to_url); if (e != NULL) goto free_from_url; e = gfs_rename(from_url, to_url); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(from_url); free(to_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix_symlink_suffix(to, &to_url); if (e != NULL) goto free_from_url; if (gfarmfs_debug >= 2) { printf("RENAME: for symlink: %s\n", from); } e = gfs_rename(from_url, to_url); } #endif free(to_url); free_from_url: free(from_url); } end: return gfarmfs_final(&prof_rename, e, 0, from); } #define COPY_BUFSIZE GFS_BLKSIZE static int gfarmfs_link(const char *from, const char *to) { char *e, *e2; char *from_url, *to_url; GFS_File from_gf, to_gf; struct gfs_stat gs; int m, n; char buf[COPY_BUFSIZE]; struct gfarm_timespec gt[2]; #ifdef SYMLINK_MODE int symlinkmode = 0; #endif int change_mode = 0; mode_t save_mode = 0; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_link)) != NULL) goto end; if (enable_linkiscopy == 0) { e = GFARM_ERR_OPERATION_NOT_PERMITTED; goto end; } if (gfarmfs_debug >= 2) { printf("LINK: hard link is replaced by copy: %s\n", to); } /* get gfs_stat and check symlink mode */ e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; /* need to feee from_url [1] */ e = gfs_stat(from_url, &gs); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(from_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; if (gfarmfs_debug >= 2) { printf("LINK: for symlink: %s\n", from); } e = gfs_stat(from_url, &gs); symlinkmode = 1; } #endif if (e != NULL) goto free_from_url; /* need to free gfs_stat [2] */ if ((gs.st_mode & 0400) == 0) { save_mode = gs.st_mode; e = gfs_chmod(from_url, gs.st_mode|0400); if (e == NULL) { change_mode = 1; } } /* need to revert mode [3] */ e = gfs_pio_open(from_url, GFARM_FILE_RDONLY, &from_gf); if (e != NULL) goto free_gfs_stat; /* need to close from_gf [4] */ e = gfarmfs_set_view(from_gf); if (e != NULL) goto close_from_gf; #ifdef SYMLINK_MODE if (symlinkmode == 1) { e = add_gfarm_prefix_symlink_suffix(to, &to_url); } else { e = add_gfarm_prefix(to, &to_url); } #else e = add_gfarm_prefix(to, &to_url); #endif if (e != NULL) goto close_from_gf; /* need to free to_url [5] */ e = gfs_pio_create(to_url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC| GFARM_FILE_EXCLUSIVE, gs.st_mode, &to_gf); if (e != NULL) goto free_to_url; /* need to close to_gf [6] */ e = gfarmfs_set_view(to_gf); if (e != NULL) goto close_to_gf; for (;;) { /* copy */ e = gfs_pio_read(from_gf, buf, COPY_BUFSIZE, &m); if (e != NULL) break; if (m == 0) { /* EOF: success (e == NULL) */ break; } e = gfs_pio_write(to_gf, buf, m, &n); if (e != NULL) break; if (m != n) { e = GFARM_ERR_INPUT_OUTPUT; break; } } close_to_gf: /* [6] */ e2 = gfs_pio_close(to_gf); if (e == NULL && e2 == NULL) { gt[0].tv_sec = gs.st_atimespec.tv_sec; gt[0].tv_nsec= gs.st_atimespec.tv_nsec; gt[1].tv_sec = gs.st_mtimespec.tv_sec; gt[1].tv_nsec= gs.st_mtimespec.tv_nsec; e = gfs_utimes(to_url, gt); } else { (void)gfs_unlink(to_url); if (e == NULL && e2 != NULL) { e = e2; } } free_to_url: /* [5] */ free(to_url); close_from_gf: /* [4] */ gfs_pio_close(from_gf); free_gfs_stat: /* [3] */ gfs_stat_free(&gs); /* revert_mode: [2] */ if (change_mode == 1) { e2 = gfs_chmod(from_url, save_mode); if (e == NULL && e2 != NULL) { e = e2; } } free_from_url: /* [1] */ free(from_url); end: return gfarmfs_final(&prof_link, e, 0, to); } static int gfarmfs_chmod(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_chmod); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_chmod(url, mode); free(url); } } return gfarmfs_final(&prof_chmod, e, 0, path); } static int gfarmfs_chown(const char *path, uid_t uid, gid_t gid) { char *e; char *url = NULL; struct gfs_stat s; (void) uid; (void) gid; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_chown)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_stat(url, &s); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (gfarmfs_debug >= 2) { printf("CHOWN: for symlink: %s\n", gfarm_url2path(url)); } if (e == NULL) e = gfs_stat(url, &s); } #endif if (e == NULL) { if (strcmp(s.st_user, gfarm_get_global_username()) != 0) { /* EPERM */ e = GFARM_ERR_OPERATION_NOT_PERMITTED; } /* XXX - else: do nothing */ gfs_stat_free(&s); } free(url); } end: return gfarmfs_final(&prof_chown, e, 0, path); } static char * gfarmfs_truncate_common(char *url, off_t size) { char *e; GFS_File gf; if (size == 0) { e = gfs_pio_open(url, GFARM_FILE_WRONLY|GFARM_FILE_TRUNC, &gf); if (e != NULL) return (e); e = gfarmfs_set_view(gf); gfs_pio_close(gf); } else { e = gfs_pio_open(url, GFARM_FILE_WRONLY, &gf); if (e != NULL) return (e); e = gfarmfs_set_view(gf); if (e == NULL) e = gfs_pio_truncate(gf, size); gfs_pio_close(gf); } return (e); } static int gfarmfs_truncate(const char *path, off_t size) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_truncate); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfarmfs_truncate_common(url, size); free(url); } end: return gfarmfs_final(&prof_truncate, e, 0, path); } static int gfarmfs_utime(const char *path, struct utimbuf *buf) { char *e; char *url; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_utime); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e == NULL) { if (buf == NULL) e = gfs_utimes(url, NULL); else { struct gfarm_timespec gt[2]; gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } free(url); } end: return gfarmfs_final(&prof_utime, e, 0, path); } static inline GFS_File gfarmfs_cast_fh(struct fuse_file_info *fi) { return (GFS_File)(unsigned long) fi->fh; } static int gfarmfs_open(const char *path, struct fuse_file_info *fi) { char *e; char *url; int flags = 0; GFS_File gf; e = gfarmfs_init(&prof_open); if (e != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; if ((fi->flags & O_ACCMODE) == O_RDONLY) { flags = GFARM_FILE_RDONLY; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { flags = GFARM_FILE_WRONLY; } else if ((fi->flags & O_ACCMODE) == O_RDWR) { flags = GFARM_FILE_RDWR; } if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0) { /* check a created file on memory and create/open */ /* with checking program */ e = gfarmfs_fastcreate_open(url, flags, &gf); if (e != NULL) goto free_url; } else { #endif e = gfs_pio_open(url, flags, &gf); if (e != NULL) goto free_url; e = gfarmfs_set_view(gf); if (e != NULL) { gfs_pio_close(gf); goto free_url; } #ifdef ENABLE_FASTCREATE } #endif fi->fh = (unsigned long) gf; free_url: free(url); end: return gfarmfs_final(&prof_open, e, 0, path); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { char *e; char *url; int flags = 0; GFS_File gf; e = gfarmfs_init(&prof_create); while (e == NULL) { if ((fi->flags & O_ACCMODE) == O_RDONLY) { flags = GFARM_FILE_RDONLY; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { flags = GFARM_FILE_WRONLY; } else if ((fi->flags & O_ACCMODE) == O_RDWR) { flags = GFARM_FILE_RDWR; } if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } e = add_gfarm_prefix(path, &url); if (e != NULL) break; e = gfs_pio_create(url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, mode, &gf); if (e != NULL) { free(url); break; } e = gfarmfs_set_view(gf); free(url); if (e != NULL) { gfs_pio_close(gf); break; } fi->fh = (unsigned long) gf; break; } return gfarmfs_final(&prof_create, e, 0, path); } static int gfarmfs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { char *e; struct gfs_stat gs; e = gfarmfs_init(&prof_fgetattr); if (e == NULL) { e = gfs_fstat(gfarmfs_cast_fh(fi), &gs); if (e == NULL) { e = convert_gfs_stat_to_stat(NULL, &gs, stbuf, 0); gfs_stat_free(&gs); } } return gfarmfs_final(&prof_fgetattr, e, 0, path); } static int gfarmfs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { char *e; GFS_File gf; e = gfarmfs_init(&prof_ftruncate); if (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_truncate(gf, size); } return gfarmfs_final(&prof_ftruncate, e, 0, path); } static int gfarmfs_access(const char *path, int mask) { char *e; char *url; e = gfarmfs_init(&prof_access); if (e == NULL) { e = add_gfarm_prefix(path, &url); if (e == NULL) { e = gfs_access(url, mask); free(url); } } return gfarmfs_final(&prof_access, e, 0, path); } #endif /* FUSE_USE_VERSION >= 25 */ static int gfarmfs_release(const char *path, struct fuse_file_info *fi) { char *e; gfarmfs_fastcreate_check(); e = gfarmfs_init(&prof_release); if (e == NULL) { e = gfs_pio_close(gfarmfs_cast_fh(fi)); } return gfarmfs_final(&prof_release, e, 0, path); } #define CLEAR_EOF(gf) (gfs_pio_eof(gf) ? gfs_pio_clearerr(gf) : (void) 0) static int gfarmfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(&prof_read); while (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_read(gf, buf, size, &n); CLEAR_EOF(gf); break; } return gfarmfs_final(&prof_read, e, n, path); } static int gfarmfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int n; file_offset_t off; char *e; GFS_File gf; e = gfarmfs_init(&prof_write); while (e == NULL) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_seek(gf, offset, 0, &off); if (e != NULL) break; e = gfs_pio_write(gf, buf, size, &n); break; } return gfarmfs_final(&prof_write, e, n, path); } static int gfarmfs_fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { char *e; GFS_File gf; if ((e = gfarmfs_init(&prof_fsync)) != NULL) goto end; gf = gfarmfs_cast_fh(fi); if (isdatasync) { e = gfs_pio_datasync(gf); } else { e = gfs_pio_sync(gf); } end: return gfarmfs_final(&prof_fsync, e, 0, path); } #ifdef USE_GFS_STATFSNODE static char * gfs_statfsnode_cached_and_retry( char *hostname, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e; e = gfs_statfsnode_cached(hostname, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); if (e == GFARM_ERR_NO_SUCH_OBJECT) { e = gfs_statfsnode(hostname, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); } if (e != NULL) { gfarmfs_errlog("STATFS: %s: %s", hostname, e); if (e == GFARM_ERR_NO_SUCH_OBJECT) { e = GFARM_ERR_CONNECTION_REFUSED; } } return (e); } static char * gfs_statfsnode_total_of_hostlist( char **hosts, int nhosts, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e, *e_save = NULL; int i, ok; gfarm_int32_t bsize; file_offset_t blocks, bfree ,bavail, files, ffree, favail; *bsizep = *blocksp = *bfreep = *bavailp = *filesp = *ffreep = *favailp = 0; ok = 0; for (i = 0; i < nhosts; i++) { e = gfs_statfsnode_cached_and_retry(hosts[i], &bsize, &blocks, &bfree, &bavail, &files, &ffree, &favail); if (e == NULL) { if (*bsizep == 0) { if (bsize == 0) continue; *bsizep = bsize; } ok = 1; if (*bsizep == bsize) { *blocksp += blocks; *bfreep += bfree; *bavailp += bavail; } else { /* revision (rough) */ *blocksp += blocks * bsize / *bsizep; *bfreep += bfree * bsize / *bsizep; *bavailp += bavail * bsize / *bsizep; } *filesp += files; *ffreep += ffree; *favailp += favail; } else { e_save = e; } } if (ok == 1) { return (NULL); } else { return (e_save); } } static inline int gfarmfs_statfs_common( const char *path, gfarm_int32_t *bsizep, file_offset_t *blocksp, file_offset_t *bfreep, file_offset_t *bavailp, file_offset_t *filesp, file_offset_t *ffreep, file_offset_t *favailp) { char *e; struct gfarm_host_info *hostinfos; int nhosts, i; char **hosts; if ((e = gfarmfs_init(&prof_statfs)) != NULL) goto end; e = gfarm_host_info_get_all(&nhosts, &hostinfos); if (e != NULL) goto end; gfarm_host_info_free_all(nhosts, hostinfos); hosts = malloc(nhosts * sizeof(char *)); if (hosts == NULL) { e = GFARM_ERR_NO_MEMORY; goto end; } e = gfarm_schedule_search_idle_acyclic_by_domainname( "", &nhosts, hosts); if (e != NULL) goto free_hosts; e = gfs_statfsnode_total_of_hostlist( hosts, nhosts, bsizep, blocksp, bfreep, bavailp, filesp, ffreep, favailp); for (i = 0; i < nhosts; i++) if (hosts[i]) free(hosts[i]); free_hosts: free(hosts); end: return gfarmfs_final(&prof_statfs, e, 0, path); } #if FUSE_USE_VERSION == 22 static int gfarmfs_statfs(const char *path, struct statfs *stfs) { file_offset_t favail; stfs->f_namelen = GFS_MAXNAMLEN; return gfarmfs_statfs_common(path, (gfarm_int32_t*)&stfs->f_bsize, (file_offset_t*)&stfs->f_blocks, (file_offset_t*)&stfs->f_bfree, (file_offset_t*)&stfs->f_bavail, (file_offset_t*)&stfs->f_files, (file_offset_t*)&stfs->f_ffree, (file_offset_t*)&favail); } #elif FUSE_USE_VERSION >= 25 static int gfarmfs_statfs(const char *path, struct statvfs *stvfs) { int res; gfarm_int32_t bsize = 0; res = gfarmfs_statfs_common(path, &bsize, (file_offset_t*)&stvfs->f_blocks, (file_offset_t*)&stvfs->f_bfree, (file_offset_t*)&stvfs->f_bavail, (file_offset_t*)&stvfs->f_files, (file_offset_t*)&stvfs->f_ffree, (file_offset_t*)&stvfs->f_favail); stvfs->f_bsize = (unsigned long) bsize; stvfs->f_frsize = (unsigned long) bsize; stvfs->f_namemax = GFS_MAXNAMLEN; return (res); } #endif /* FUSE_USE_VERSION */ #endif /* USE_GFS_STATFSNODE */ #if 1 static int gfarmfs_flush(const char *path, struct fuse_file_info *fi) { char *e = gfarmfs_init(&prof_flush); (void) fi; #if 0 /* XXX TODO */ GFS_File gf; if (e != NULL) goto end; if ((fi->flags & O_ACCMODE) != O_RDONLY) { gf = gfarmfs_cast_fh(fi); e = gfs_pio_sync(gf); } end: #endif return gfarmfs_final(&prof_flush, e, 0, path); } #endif #if ENABLE_XATTR static int gfarmfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return (-ENOSYS); } static int gfarmfs_getxattr(const char *path, const char *name, char *value, size_t size) { return (-ENOSYS); } static int gfarmfs_listxattr(const char *path, char *list, size_t size) { return (-ENOSYS); } static int gfarmfs_removexattr(const char *path, const char *name) { return (-ENOSYS); } #endif /* ENABLE_XATTR */ static struct fuse_operations gfarmfs_oper_base = { .getattr = gfarmfs_getattr, .readlink = gfarmfs_readlink, .getdir = gfarmfs_getdir, .mknod = gfarmfs_mknod, .mkdir = gfarmfs_mkdir, .symlink = gfarmfs_symlink, .unlink = gfarmfs_unlink, .rmdir = gfarmfs_rmdir, .rename = gfarmfs_rename, .link = gfarmfs_link, .chmod = gfarmfs_chmod, .chown = gfarmfs_chown, .truncate = gfarmfs_truncate, .utime = gfarmfs_utime, .open = gfarmfs_open, .read = gfarmfs_read, .write = gfarmfs_write, .release = gfarmfs_release, .fsync = gfarmfs_fsync, #ifdef USE_GFS_STATFSNODE .statfs = gfarmfs_statfs, #endif #if FUSE_USE_VERSION >= 25 .create = gfarmfs_create, .fgetattr = gfarmfs_fgetattr, .ftruncate = gfarmfs_ftruncate, .access = gfarmfs_access, #endif .flush = gfarmfs_flush, #if ENABLE_XATTR .setxattr = gfarmfs_setxattr, .getxattr = gfarmfs_getxattr, .listxattr = gfarmfs_listxattr, .removexattr = gfarmfs_removexattr, #endif }; /* ################################################################### */ /* new I/O functions (share GFS_File during opening the same file) */ #define FH_LIST_USE_INO 0 /* key: 0=path, 1=ino */ #if ENABLE_ASYNC_REPLICATION #include <sys/types.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/shm.h> #define DEFAULT_FORK_MAX (5) #endif struct gfarmfs_fh { #if FH_LIST_USE_INO == 1 long ino; #else char *path; #endif GFS_File gf; int flags; /* current flag */ int nopen; int nwrite; #if REVISE_CHMOD int mode_changed; mode_t save_mode; #endif #if REVISE_UTIME int utime_changed; struct gfarm_timespec save_utime[2]; #endif #if ENABLE_ASYNC_REPLICATION int *shm_child_status; pid_t child_pid; #endif }; typedef struct gfarmfs_fh * FH; /* async replication */ #if ENABLE_ASYNC_REPLICATION #define CHILD_RUNNING 0 #define CHILD_CANCELED 1 #define CHILD_DONE 2 #if 0 /* for child */ static int gfarmfs_async_is_canceled(FH fh) { if (fh->shm_child_status != NULL && *fh->shm_child_status != CHILD_RUNNING) return (1); else return (0); } #endif /* for parent */ static int gfarmfs_async_is_running(FH fh) { if (fh->shm_child_status != NULL && *fh->shm_child_status == CHILD_RUNNING) return (1); else return (0); } #if 0 /* for parent */ static int gfarmfs_async_is_done(FH fh) { if (fh->shm_child_status == NULL) /* no forking */ return (1); else if (*fh->shm_child_status == CHILD_DONE) return (1); else return (0); } #endif #if 0 static void gfarmfs_async_start(FH fh) { if (fh != NULL && fh->shm_child_status != NULL) *fh->shm_child_status = CHILD_RUNNING; } #endif /* cancel is not supported yet */ static void gfarmfs_async_stop(FH fh) { if (fh != NULL && fh->shm_child_status != NULL) *fh->shm_child_status = CHILD_CANCELED; } static void gfarmfs_async_wait(FH fh) { if (fh != NULL && fh->child_pid > 0) { waitpid(fh->child_pid, NULL, 0); fh->child_pid = -1; if (fh->shm_child_status != NULL) *fh->shm_child_status = CHILD_DONE; } } static int gfarmfs_fh_is_opened(FH fh) { if (fh != NULL && fh->nopen > 0) return (1); else return (0); } #endif #define FH_LIST_LEN 1024 FH gfarmfs_fh_list[FH_LIST_LEN]; #if FH_LIST_USE_INO == 1 #define FH_GET1(url) gfarmfs_fh_get_key_url(url) #define FH_GET2(url, ino) gfarmfs_fh_get(ino) #define FH_ADD1(url, fh) gfarmfs_fh_add_key_url(url, fh) #define FH_ADD2(url, ino, fh) gfarmfs_fh_add(ino, fh) #define FH_REMOVE1(url) gfarmfs_fh_remove_key_url(url) #define FH_REMOVE2(url, ino) gfarmfs_fh_remove(ino) #define FH_FREE(fh) gfarmfs_fh_free(fh) #else #define FH_GET1(url) gfarmfs_fh_get(url) #define FH_GET2(url, ino) gfarmfs_fh_get(url) #define FH_ADD1(url, fh) gfarmfs_fh_add(url, fh) #define FH_ADD2(url, ino, fh) gfarmfs_fh_add(url, fh) #define FH_REMOVE1(url) gfarmfs_fh_remove(url) #define FH_REMOVE2(url, ino) gfarmfs_fh_remove(url) #define FH_FREE(fh) gfarmfs_fh_free(fh) #endif static void gfarmfs_fh_free(FH fh) { #if ENABLE_ASYNC_REPLICATION if (fh->child_pid > 0) waitpid(fh->child_pid, NULL, 0); if (fh->shm_child_status) shmdt(fh->shm_child_status); #endif #if FH_LIST_USE_INO == 0 if (fh->path) free(fh->path); #endif free(fh); } #if FH_LIST_USE_INO == 1 /* key is ino */ static char * gfarmfs_get_ino(char *url, long *inop) { char *e; struct gfs_stat gs; e = gfs_stat(url, &gs); if (e == NULL) { *inop = gs.st_ino; gfs_stat_free(&gs); return (NULL); } return (e); } static FH gfarmfs_fh_get(long ino) { int i; for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && gfarmfs_fh_list[i]->ino == ino) { return gfarmfs_fh_list[i]; } } return (NULL); } static FH gfarmfs_fh_get_key_url(char *url) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return (NULL); return gfarmfs_fh_get(ino); } /* must do gfarmfs_fh_remove before this */ static char * gfarmfs_fh_add(long ino, FH fh) { int i; #if 0 /* for debug */ if (gfarmfs_fh_get(ino)) return (GFARM_ERR_ALREADY_EXISTS); #endif for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] == NULL) { fh->ino = ino; gfarmfs_fh_list[i] = fh; return (NULL); } #if ENABLE_ASYNC_REPLICATION else if (replication_mode != REP_DISABLE && gfarmfs_fh_list[i]->nopen <= 0 && !gfarmfs_async_is_running(gfarmfs_fh_list[i])) { FH_FREE(gfarmfs_fh_list[i]); fh->ino = ino; gfarmfs_fh_list[i] = fh; return (NULL); } #endif } return (GFARM_ERR_NO_MEMORY); /* EMFILE ? */ } #if 0 static char * gfarmfs_fh_add_key_url(char *url, FH fh) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return (e); return gfarmfs_fh_add(ino, fh); } #endif static void gfarmfs_fh_remove(long ino) { int i; for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && gfarmfs_fh_list[i]->ino == ino) { gfarmfs_fh_list[i] = NULL; return; } } return; } #if 0 static void gfarmfs_fh_remove_key_url(char *url) { char *e; long ino; e = gfarmfs_get_ino(url, &ino); if (e != NULL) return; return gfarmfs_fh_remove(ino); } #endif #else /* FH_LIST_USE_INO != 0 */ /* key is url */ static FH gfarmfs_fh_get(char *url) { int i; char *path; if (url == NULL) return (NULL); path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && strcmp(gfarmfs_fh_list[i]->path, path) == 0) { return gfarmfs_fh_list[i]; } } return (NULL); } /* must do gfarmfs_fh_remove before this */ static char * gfarmfs_fh_add(char *url, FH fh) { int i; char *path; if (url == NULL) return (NULL); #if 0 /* for debug */ if (gfarmfs_fh_get(url)) return (GFARM_ERR_ALREADY_EXISTS); #endif path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] == NULL) { if (fh->path != NULL) free(fh->path); fh->path = strdup(path); if (fh->path == NULL) return (GFARM_ERR_NO_MEMORY); gfarmfs_fh_list[i] = fh; return (NULL); } #if ENABLE_ASYNC_REPLICATION else if (replication_mode != REP_DISABLE && gfarmfs_fh_list[i]->nopen <= 0 && !gfarmfs_async_is_running(gfarmfs_fh_list[i])) { FH_FREE(gfarmfs_fh_list[i]); if (fh->path != NULL) free(fh->path); fh->path = strdup(path); if (fh->path == NULL) return (GFARM_ERR_NO_MEMORY); gfarmfs_fh_list[i] = fh; return (NULL); } #endif } return (GFARM_ERR_NO_MEMORY); /* EMFILE ? */ } static void gfarmfs_fh_remove(char *url) { int i; char *path; if (url == NULL) return; path = gfarm_url2path(url); for (i = 0; i < FH_LIST_LEN; i++) { if (gfarmfs_fh_list[i] != NULL && strcmp(gfarmfs_fh_list[i]->path, path) == 0) { gfarmfs_fh_list[i] = NULL; return; } } return; } #endif /* FH_LIST_USE_INO == 1 */ #if ENABLE_ASYNC_REPLICATION static void * gfarmfs_shm_alloc(size_t size) { int shmid; void *b; int save_errno; shmid = shmget(IPC_PRIVATE, size, 0600|IPC_CREAT); if (shmid == -1) return (NULL); b = shmat(shmid, NULL, 0); if (b == (void *) -1) return (NULL); if (shmctl(shmid, IPC_RMID, 0) == -1) { save_errno = errno; shmdt(b); errno = save_errno; return (NULL); } return (b); } static int semid; static int sem_initialized = 0; static char * gfarmfs_async_fork_count_initialize() { int save_errno; struct sembuf sb = {0, DEFAULT_FORK_MAX, 0}; if (sem_initialized == 1) return (NULL); sem_initialized = 1; if ((semid = semget(IPC_PRIVATE, 1, 0600|IPC_CREAT)) == -1) { save_errno = errno; gfarmfs_errlog("semget(init): %s", strerror(save_errno)); return (gfarm_errno_to_error(save_errno)); } if (semop(semid, &sb, 1) == -1) { save_errno = errno; gfarmfs_errlog("semop(init): %s", strerror(save_errno)); return (gfarm_errno_to_error(save_errno)); } return (NULL); } static char * gfarmfs_async_fork_count_increment_n(int n) { int save_errno; struct sembuf sb = {0, -n, 0}; if (semop(semid, &sb, 1) == -1) { save_errno = errno; gfarmfs_errlog("semop(+): %s", strerror(save_errno)); return gfarm_errno_to_error(save_errno); } /* printf("semval = %d\n", semctl(semid, 0, GETVAL, 0)); */ return (NULL); } static char * gfarmfs_async_fork_count_decrement_n(int n) { int save_errno; struct sembuf sb = {0, n, 0}; if (semop(semid, &sb, 1) == -1) { save_errno = errno; gfarmfs_errlog("semop(-): %s", strerror(save_errno)); return gfarm_errno_to_error(save_errno); } return (NULL); } static void gfarmfs_async_fork_count_finalize() { sem_initialized = 0; if (semctl(semid, 0, IPC_RMID, 0) == -1) gfarmfs_errlog("semctl(final): %s", strerror(errno)); } #define gfarmfs_async_fork_count_increment() \ gfarmfs_async_fork_count_increment_n(1) #define gfarmfs_async_fork_count_decrement() \ gfarmfs_async_fork_count_decrement_n(1) #ifdef USE_GFARM_SCRAMBLE static void gfarmfs_scramble_replicate(char *url) { char *e; e = gfarm_terminate(); if (e != NULL) goto emsg; e = gfarm_initialize(NULL, NULL); if (e != NULL) goto emsg; e = gfs_scramble_make_replica(url); gfarm_terminate(); emsg: if (e != NULL) gfarmfs_errlog("REPLICATE: %s: %s", gfarm_url2path(url), e); } #endif #ifdef USE_SCHEDULER /* *nhostsp > 0 : OK * *nhostsp == 0: do nothing * *nhostsp = -1: retry (using gfrep -N) * error: undefined */ static char * gfarmfs_gfrep_schedule(char *url, char **srchostp, char **srcsectionp, int nrequire, int *nhostsp, char **hosts) { char *e; int nsections, ncopies, nhostinfos; struct gfarm_file_section_info *sections; struct gfarm_file_section_copy_info *copies; struct gfarm_host_info *hostinfos; int i, nhave, ntmplist; char **have_hosts, **tmplist; char *gfarm_path; char *srcsection = NULL; if (nrequire <= 0) { *nhostsp = 0; /* do nothing */ return (NULL); } e = gfarm_url_make_path(url, &gfarm_path); if (e != NULL) return (e); /* [1] need free_gfarm_path */ e = gfarm_file_section_info_get_all_by_file( gfarm_path, &nsections, &sections); if (e != NULL) goto free_gfarm_path; if (nsections != 1) { /* unexpected */ gfarm_file_section_info_free_all(nsections, sections); e = NULL; *nhostsp = -1; /* gfrep -N */ goto free_gfarm_path; } /* ------ nsections == 1 ------ */ e = gfarm_file_section_copy_info_get_all_by_section( gfarm_path, sections[0].section, &ncopies, &copies); srcsection = strdup(sections[0].section); /* [2] need free_srcsection */ gfarm_file_section_info_free_all(nsections, sections); if (e != NULL) goto free_srcsection; /* ncopies >= 2: unexpected... */ /* [3] need free_copy_info */ have_hosts = malloc(ncopies * sizeof(char *)); if (have_hosts == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_copy_info; } /* [4] need free_have_hosts !!! */ if (replication_domain != NULL) { int j = 0; for (i = 0; i < ncopies; i++) { if (gfarm_host_is_in_domain(copies[i].hostname, replication_domain)) have_hosts[j++] = copies[i].hostname; } nhave = j; } else { for (i = 0; i < ncopies; i++) have_hosts[i] = copies[i].hostname; nhave = ncopies; } if (nhave >= nrequire) { e = NULL; *nhostsp = 0; goto free_have_hosts; } /* ------ nrequire > nhave ------ */ e = gfarm_host_info_get_all(&nhostinfos, &hostinfos); if (e != NULL) { goto free_have_hosts; } /* [5] need free_hostinfos */ /* length of tmplist is the same as hostinfos */ tmplist = calloc(nhostinfos, sizeof(char *)); if (tmplist == NULL) { e = GFARM_ERR_NO_MEMORY; goto free_hostinfos; } /* [6] need free_tmplist */ ntmplist = 0; for (i = 0; i < nhostinfos; i++) { int ignore = 0, j; if (replication_domain != NULL && !gfarm_host_is_in_domain( hostinfos[i].hostname, replication_domain)) { continue; } for (j = 0; j < nhave; j++) { if (strcasecmp(hostinfos[i].hostname, have_hosts[j]) == 0) { ignore = 1; break; } } if (ignore == 0) /* add */ tmplist[ntmplist++] = hostinfos[i].hostname; } if (ntmplist == 0) { *nhostsp = 0; e = NULL; gfarmfs_errlog( "REPLICATE: WARN: " "require(%d) - have(%d) > selected(0)", nrequire, nhave); goto free_tmplist; } /* ntmplist > 0 */ /* schedule the number (nrequire - nhave) of hosts from tmplist */ *nhostsp = nrequire - nhave; if (*nhostsp > ntmplist) *nhostsp = ntmplist; e = gfarm_schedule_search_idle_acyclic_hosts_to_write( ntmplist, tmplist, nhostsp, hosts); if (e == NULL) { for (i = 0; i < *nhostsp; i++) { char *tmp; int j; tmp = strdup(hosts[i]); if (tmp == NULL) { for (j = 0; j < i - 1; j++) if (hosts[j]) free(hosts[j]); e = GFARM_ERR_NO_MEMORY; goto free_tmplist; } hosts[i] = tmp; } if (nrequire - nhave > *nhostsp) gfarmfs_errlog( "REPLICATE: WARN: " "require(%d) - have(%d) > selected(%d)", nrequire, nhave, *nhostsp); } if (e == NULL) { *srchostp = strdup(copies[0].hostname); } free_tmplist: /* [6] */ free(tmplist); free_hostinfos: /* [5] */ gfarm_host_info_free_all(nhostinfos, hostinfos); free_have_hosts: /* [4] */ free(have_hosts); free_copy_info: /* [3] */ gfarm_file_section_copy_info_free_all(ncopies, copies); free_srcsection: /* [2] */ if (e == NULL) { *srcsectionp = srcsection; } else if (e != NULL && srcsection) { free(srcsection); srcsection = NULL; } free_gfarm_path: /* [1] */ free(gfarm_path); return (e); } static int gfarmfs_replicate_from_to(char *url, char *srchost, char *section, int nhosts, char **hosts) { char *e, *e_save = NULL; int i; e = gfarm_terminate(); if (e != NULL) goto end; e = gfarm_initialize(NULL, NULL); if (e != NULL) goto end; for (i = 0; i < nhosts; i++) { e = gfarm_url_section_replicate_from_to(url, section, srchost, hosts[i]); if (e != NULL) { gfarmfs_errlog("REPLICATE: %s -> %s: %s: %s", srchost, hosts[i], gfarm_url2path(url), e); if (e_save == NULL) e_save = e; } } if (e_save != NULL) e = e_save; gfarm_terminate(); end: if (e == NULL) return (0); else return (1); } #define CHANGE_DEV_NULL(fd) dup2(open("/dev/null", O_WRONLY), fd) static int gfarmfs_gfrep_d_exec(char *url, char *srchost, char *section, int nhosts, char **hosts) { int p, i; int status, res = 0; for (i = 0; i < nhosts; i++) { p = fork(); if (p == -1) { gfarmfs_errlog("REPLICATE: fork: %s", strerror(errno)); return (-1); } else if (p == 0) { /* grandchild */ int vl; char *v[10]; static char str_d[] = "-d"; static char str_I[] = "-I"; static char str_s[] = "-s"; vl = 0; v[vl++] = gfrep_path; v[vl++] = str_d; v[vl++] = hosts[i]; if (srchost != NULL) { v[vl++] = str_s; v[vl++] = srchost; } if (section != NULL) { v[vl++] = str_I; v[vl++] = section; } v[vl++] = url; v[vl++] = NULL; CHANGE_DEV_NULL(1); CHANGE_DEV_NULL(2); if (execv(v[0], v) == -1) gfarmfs_errlog("REPLICATE: execvp: %s", strerror(errno)); _exit(1); } waitpid(p, &status, 0); if (WEXITSTATUS(status) != 0 && res == 0) res = WEXITSTATUS(status); } return (res); } static int gfarmfs_gfrep_HN_exec(char *url, int nhosts, char **hosts) { int p, i; int pfds[2]; FILE *f; int status; char numstr[16]; if (pipe(pfds) == -1) gfarmfs_errlog("REPLICATE: pipe: %s", strerror(errno)); p = fork(); if (p == -1) { gfarmfs_errlog("REPLICATE: fork: %s", strerror(errno)); return (-1); } else if (p == 0) { /* grandchild */ close(pfds[1]); if (dup2(pfds[0], 0) == -1) { /* stdin */ gfarmfs_errlog("REPLICATE: dup2(grandchild): %s", strerror(errno)); _exit(1); } close(pfds[0]); snprintf(numstr, sizeof(numstr), "%d", nhosts); CHANGE_DEV_NULL(1); CHANGE_DEV_NULL(2); if (execl(gfrep_path, gfrep_path, "-H", "-", "-N", numstr, url, (char*)NULL) == -1) gfarmfs_errlog("REPLICATE: execvp: %s", strerror(errno)); _exit(1); } close(pfds[0]); f = fdopen(pfds[1], "w"); if (f == NULL) { gfarmfs_errlog("REPLICATE: fdopen: %s", strerror(errno)); close(pfds[1]); return (-1); } for (i = 0; i < nhosts; i++) { if (fprintf(f, "%s\n", hosts[i]) < 0) { gfarmfs_errlog("REPLICATE: fprintf: %s", strerror(errno)); break; } } if (fclose(f) == EOF) gfarmfs_errlog("REPLICATE: fclose: %s", strerror(errno)); waitpid(p, &status, 0); return (WEXITSTATUS(status)); } #endif /* end of USE_SCHEDULER */ static char *gfrep_N_argv[7]; static void gfarmfs_gfrep_N_init() { static char str_N[] = "-N"; static char str_D[] = "-D"; static char gfrep_num[16]; static int initialized = 0; if (initialized) return; snprintf(gfrep_num, 16, "%d", replication_num); if (replication_domain == NULL) { /* gfrep -N 2 */ gfrep_N_argv[0] = gfrep_path; gfrep_N_argv[1] = str_N; gfrep_N_argv[2] = gfrep_num; /* gfrep_N_argv[3] for url */ gfrep_N_argv[4] = NULL; } else { /* gfrep -N 2 -D example.com */ gfrep_N_argv[0] = gfrep_path; gfrep_N_argv[1] = str_N; gfrep_N_argv[2] = gfrep_num; gfrep_N_argv[3] = str_D; gfrep_N_argv[4] = replication_domain; /* gfrep_N_argv[5] for url */ gfrep_N_argv[6] = NULL; } initialized = 1; } static void gfarmfs_gfrep_N_exec(char *url) { int p; gfarmfs_gfrep_N_init(); p = fork(); if (p == -1) { gfarmfs_errlog("REPLICATE: fork: %s", strerror(errno)); return; } else if (p == 0) { /* grandchild */ if (replication_domain == NULL) gfrep_N_argv[3] = url; else gfrep_N_argv[5] = url; if (execv(gfrep_N_argv[0], gfrep_N_argv) == -1) gfarmfs_errlog("REPLICATE: execvp: %s", strerror(errno)); _exit(1); } waitpid(p, NULL, 0); } static char * gfarmfs_async_replicate(char *url, FH fh) { char *e; int do_rep_mode = REP_DISABLE; #ifdef USE_SCHEDULER char *srchost = NULL, *srcsection = NULL; static char **hosts = NULL; int nhosts = 0; #endif /* ----------- prepare ---------- */ if (fh->shm_child_status == NULL) { /* initialize */ fh->shm_child_status = gfarmfs_shm_alloc(sizeof(int)); if (fh->shm_child_status == NULL) return (gfarm_errno_to_error(errno)); } else { gfarmfs_async_stop(fh); /* cancel */ gfarmfs_async_wait(fh); } if (replication_mode == REP_DISABLE) { /* do nothing */ return (NULL); } else if (replication_mode == REP_GFREP_N){ do_rep_mode = REP_GFREP_N; #ifdef USE_GFARM_SCRAMBLE } else if (replication_mode == REP_SCRAMBLE) { do_rep_mode = REP_SCRAMBLE; #endif } else { #ifdef USE_SCHEDULER /* REP_GFREP_d or REP_GFREP_HN */ if (replication_num > 0) { if (hosts == NULL) { /* initialize */ hosts = calloc(replication_num, sizeof(char *)); if (hosts == NULL) return (GFARM_ERR_NO_MEMORY); } } else { /* unexpected: do nothing */ return (NULL); } e = gfarmfs_gfrep_schedule(url, &srchost, &srcsection, replication_num, &nhosts, hosts); if (e != NULL) { nhosts = 0; goto end; /* error */ } if (nhosts == 0) goto end; /* do nothing */ else if (nhosts > 0) do_rep_mode = replication_mode; /* normal */ else /* nhosts == -1 -> using gfrep -N */ do_rep_mode = REP_GFREP_N; #else /* not use scheduler */ /* unexpected: do nothing */ return (NULL); #endif /* USE_SCHEDULER */ } /* ----------- execute ---------- */ e = gfarmfs_async_fork_count_increment(); /* limiter */ if (e != NULL) goto end; *fh->shm_child_status = CHILD_RUNNING; /* gfarmfs_async_start(fh) */ fh->child_pid = fork(); if (fh->child_pid == -1) { /* error */ int save_errno = errno; gfarmfs_errlog("REPLICATE: fork: %s", strerror(save_errno)); (void)gfarmfs_async_fork_count_decrement(); *fh->shm_child_status = CHILD_DONE; e = gfarm_errno_to_error(save_errno); } else if (fh->child_pid == 0) { /* child */ if (do_rep_mode == REP_GFREP_N) gfarmfs_gfrep_N_exec(url); #ifdef USE_SCHEDULER else if (do_rep_mode == REP_FROMTO_FUNC) gfarmfs_replicate_from_to(url, srchost, srcsection, nhosts, hosts); else if (do_rep_mode == REP_GFREP_HN) gfarmfs_gfrep_HN_exec(url, nhosts, hosts); else if (do_rep_mode == REP_GFREP_d) gfarmfs_gfrep_d_exec(url, srchost, srcsection, nhosts, hosts); #endif #ifdef USE_GFARM_SCRAMBLE else if (do_rep_mode == REP_SCRAMBLE) gfarmfs_scramble_replicate(url); #endif /* done */ (void)gfarmfs_async_fork_count_decrement(); *fh->shm_child_status = CHILD_DONE; _exit(0); } /* parent: continue */ end: #ifdef USE_SCHEDULER if (hosts != NULL) { int i; for (i = 0; i < nhosts; i++) if (hosts[i]) { free(hosts[i]); hosts[i] = NULL; /* reuse */ } } if (srchost != NULL) free(srchost); if (srcsection != NULL) free(srcsection); #endif return (e); } #endif static char * gfarmfs_fh_alloc(FH *fhp) { FH fh; fh = malloc(sizeof(*fh)); if (fh == NULL) return (GFARM_ERR_NO_MEMORY); fh->gf = NULL; fh->flags = 0; fh->nopen = 0; fh->nwrite = 0; #if FH_LIST_USE_INO == 1 /* fh->ino = -1 */ #else fh->path = NULL; #endif #if REVISE_CHMOD fh->mode_changed = 0; #endif #if REVISE_UTIME fh->utime_changed = 0; #endif #if ENABLE_ASYNC_REPLICATION fh->shm_child_status = NULL; fh->child_pid = -1; #endif *fhp = fh; return (NULL); } static char * gfs_pio_open_common(char *url, int flags, GFS_File *gfp, mode_t *create_modep) { char *e; if (enable_gfarm_iobuf == 0) { flags |= GFARM_FILE_UNBUFFERED; } #ifdef ENABLE_FASTCREATE (void) create_modep; /* created a file on MKNOD */ if (enable_fastcreate > 0) { e = gfarmfs_fastcreate_open(url, flags, gfp); } else { e = gfs_pio_open(url, flags, gfp); if (e != NULL) return (e); e = gfarmfs_set_view(*gfp); if (e != NULL) gfs_pio_close(*gfp); } #else if (create_modep) { e = gfs_pio_create( url, flags|GFARM_FILE_TRUNC|GFARM_FILE_EXCLUSIVE, *create_modep, gfp); if (e != NULL) return (e); e = gfarmfs_set_view(*gfp); } else { e = gfs_pio_open(url, flags, gfp); if (e != NULL) return (e); e = gfarmfs_set_view(*gfp); } if (e != NULL) gfs_pio_close(*gfp); #endif /* ENABLE_FASTCREATE */ return (e); } static int gfarmfs_open_common_share_gf(struct gfarmfs_prof *profp, const char *path, struct fuse_file_info *fi, mode_t *create_modep) { char *e; char *url; struct gfs_stat gs; FH fh; long ino = 0; mode_t save_mode = 0; GFS_File gf; #ifdef ENABLE_FASTCREATE struct stat st; #endif if ((e = gfarmfs_init(profp)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; if (create_modep) { /* normal CREATE */ fh = NULL; #ifdef ENABLE_FASTCREATE } else if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, &st)) { /* fastcreate */ create_modep = &st.st_mode; fh = NULL; #endif } else { /* normal OPEN */ e = gfs_stat(url, &gs); if (e != NULL) goto free_url; ino = gs.st_ino; save_mode = gs.st_mode; gfs_stat_free(&gs); fh = FH_GET2(url, ino); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_wait(fh); if (fh != NULL && !gfarmfs_fh_is_opened(fh)) { FH_REMOVE2(url, ino); FH_FREE(fh); fh = NULL; } #endif } if (fh == NULL) { /* new gfarmfs_fh */ e = gfarmfs_fh_alloc(&fh); if (e != NULL) goto free_url; if ((fi->flags & O_ACCMODE) == O_RDONLY) { e = gfs_pio_open_common(url, GFARM_FILE_RDONLY, &gf, create_modep); if (e == NULL) { fh->gf = gf; fh->flags = GFARM_FILE_RDONLY; fh->nopen++; } } else { /* WRONLY or RDWR */ e = gfs_pio_open_common(url, GFARM_FILE_RDWR, &gf, create_modep); if (e == NULL) { fh->flags = GFARM_FILE_RDWR; } else if ((fi->flags & O_ACCMODE) == O_WRONLY) { /* minor case (mode is 0200) */ e = gfs_pio_open_common( url, GFARM_FILE_WRONLY, &gf, create_modep); if (e == NULL) fh->flags = GFARM_FILE_WRONLY; } if (e == NULL) { fh->gf = gf; fh->nopen++; fh->nwrite++; } } #if FH_LIST_USE_INO == 1 /* key is ino: cannot use FH_GET1() */ if (create_modep && e == NULL) { /* get st_ino */ e = gfs_fstat(gf, &gs); if (e == NULL) { ino = gs.st_ino; gfs_stat_free(&gs); } } #endif if (e == NULL) { FH fh2 = FH_GET2(url, ino); #if ENABLE_ASYNC_REPLICATION if (fh2 != NULL && !gfarmfs_fh_is_opened(fh2)) { FH_REMOVE2(url, ino); /* for FH_ADD */ FH_FREE(fh2); fh2 = NULL; } #endif if (fh2 != NULL) e = GFARM_ERR_ALREADY_EXISTS; else e = FH_ADD2(url, ino, fh); } if (e != NULL) { if (fh->gf) gfs_pio_close(fh->gf); FH_FREE(fh); } } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDWR) { fh->nopen++; if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite++; } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDONLY && (fi->flags & O_ACCMODE) == O_RDONLY) { fh->nopen++; } else if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_WRONLY && (fi->flags & O_ACCMODE) == O_WRONLY) { fh->nopen++; fh->nwrite++; } else { /* RDONLY or WRONLY -> RDWR */ e = gfs_pio_open_common(url, GFARM_FILE_RDWR, &gf, NULL); if (e != NULL) { /* retry */ if ((fi->flags & O_ACCMODE) == O_RDONLY) e = gfs_access(url, R_OK); else if ((fi->flags & O_ACCMODE) == O_WRONLY) e = gfs_access(url, W_OK); if (e == NULL) e = gfs_chmod(url, save_mode|0600); if (e == NULL) { char *e2; e = gfs_pio_open_common( url, GFARM_FILE_RDWR, &gf, NULL); #if REVISE_CHMOD /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = save_mode; e2 = gfs_chmod(url, save_mode); #else /* gfs_fchmod cannot work in global view * (the case of nsection >= 2) * on gfarm v1.3.1 or earlier */ if (e == NULL) e2 = gfs_fchmod(gf, save_mode); else e2 = gfs_chmod(url, save_mode); #endif if (e2 != NULL) { /* What happen ? */ gfarmfs_errlog("OPEN: WARN: " "chmod failed: " "%o: %s%s: %s", save_mode, gfarm_mount_point, path, e2); } } } if (e == NULL) { (void)gfs_pio_close(fh->gf); fh->gf = gf; fh->flags = GFARM_FILE_RDWR; fh->nopen++; if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite++; } } if (e == NULL) fi->fh = (unsigned long) fh; free_url: free(url); end: return gfarmfs_final(profp, e, 0, path); } static int gfarmfs_open_share_gf(const char *path, struct fuse_file_info *fi) { return gfarmfs_open_common_share_gf(&prof_open, path, fi, NULL); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_create_share_gf(const char *path, mode_t mode, struct fuse_file_info *fi) { return gfarmfs_open_common_share_gf(&prof_create, path, fi, &mode); } #endif #if REVISE_CHMOD #define IS_EXECUTABLE(mode) ((mode) & 0111 ? 1 : 0) #endif static char * gfarmfs_chmod_share_gf_internal(char *url, mode_t mode) { char *e; struct gfs_stat gs; FH fh; e = gfs_stat(url, &gs); if (e != NULL) goto end; if (!GFARM_S_ISREG(gs.st_mode)) { e = gfs_chmod(url, mode); goto free_gfs_stat; } /* regular file */ fh = FH_GET2(url, gs.st_ino); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_wait(fh); if (!gfarmfs_fh_is_opened(fh)) fh = NULL; /* closed */ #endif #if REVISE_CHMOD if (fh != NULL) { /* somebody opens this file */ /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = mode; if (IS_EXECUTABLE(gs.st_mode) == IS_EXECUTABLE(mode)) { e = gfs_chmod(url, mode); if (e != NULL) fh->mode_changed = 0; } /* (else): somebody opens this file and changes executable bit. * -> gfs_chmod on RELEASE only * In Gfarm v1, gfs_pio_close fails at replacing section info * in this case. */ /* always succeeed ... (e == NULL) */ } else { /* nobody opens this file */ e = gfs_chmod(url, mode); } #else if (fh != NULL) /* somebody opens this open */ /* gfs_fchmod cannot work in global view * (the case of nsection >= 2) on gfarm v1.3.1 or earlier */ e = gfs_fchmod(fh->gf, mode); else e = gfs_chmod(url, mode); #endif free_gfs_stat: gfs_stat_free(&gs); end: return (e); } static int gfarmfs_chmod_share_gf(const char *path, mode_t mode) { char *e; char *url; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_chmod)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_chmod_share_gf_internal(url, mode); free(url); end: return gfarmfs_final(&prof_chmod, e, 0, path); } static char * gfarmfs_utime_share_gf_internal(char *url, struct utimbuf *buf) { char *e; struct gfarm_timespec gt[2]; if (buf == NULL) e = gfs_utimes(url, NULL); else { gt[0].tv_sec = buf->actime; gt[0].tv_nsec= 0; gt[1].tv_sec = buf->modtime; gt[1].tv_nsec= 0; e = gfs_utimes(url, gt); } #if REVISE_UTIME if (e == NULL) { FH fh; fh = FH_GET1(url); #if ENABLE_ASYNC_REPLICATION if (!gfarmfs_fh_is_opened(fh)) fh = NULL; #endif if (fh != NULL) { /* must utime on release */ fh->utime_changed = 1; if (buf == NULL) { time_t t; time(&t); fh->save_utime[0].tv_sec = t; fh->save_utime[0].tv_nsec = 0; fh->save_utime[1].tv_sec = t; fh->save_utime[1].tv_nsec = 0; } else { fh->save_utime[0] = gt[0]; fh->save_utime[1] = gt[1]; } } } #endif return (e); } static int gfarmfs_utime_share_gf(const char *path, struct utimbuf *buf) { char *e; char *url; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_utime)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfarmfs_utime_share_gf_internal(url, buf); free(url); end: return gfarmfs_final(&prof_utime, e, 0, path); } static char * gfarmfs_rename_share_gf_check_open(char *from_url, char *to_url, long from_ino, mode_t from_mode) { char *e; FH fh; #if FH_LIST_USE_INO != 1 (void) from_ino; #endif #if GFARM_USE_VERSION == 1 /* for Gfarm version 1 */ fh = FH_GET2(from_url, from_ino); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_wait(fh); if (fh != NULL && !gfarmfs_fh_is_opened(fh)) { FH_REMOVE2(from_url, from_ino); /* for FH_ADD */ FH_FREE(fh); fh = NULL; /* closed */ } #endif if (fh != NULL) { /* opened */ FH_REMOVE2(from_url, from_ino); gfs_pio_close(fh->gf); /* so that gfs_pio_close can set metadata correctly */ } e = gfs_rename(from_url, to_url); if (fh != NULL) { /* somebody opens this file */ char *e2; char *url; GFS_File gf; int retry; if (e == NULL) url = to_url; /* renamed */ else url = from_url; /* recover */ retry = 0; retry: if (retry) { char *e3; e3 = gfs_chmod(url, from_mode|0600); if (e3 == NULL) fh->flags = GFARM_FILE_RDWR; else return (e); } e2 = gfs_pio_open_common(url, fh->flags, &gf, NULL); if (retry) { char *e3; #if REVISE_CHMOD /* must chmod on release */ fh->mode_changed = 1; fh->save_mode = from_mode; e3 = gfs_chmod(url, from_mode); #else if (e2 == NULL) /* gfs_fchmod cannot work in global view * (the case of nsection >= 2) * on gfarm v1.3.1 or earlier */ e3 = gfs_fchmod(gf, from_mode); else e3 = gfs_chmod(url, from_mode); #endif if (e3 != NULL) { /* What happen ? */ gfarmfs_errlog("RENAME: WARN: " "chmod failed: %o: %s: %s", from_mode, gfarm_url2path(url), e3); } } if (e2 == NULL) { /* open succeeeded */ struct gfs_stat gs; fh->gf = gf; e2 = gfs_fstat(gf, &gs); if (e2 == NULL) { e2 = FH_ADD2(url, gs.st_ino, fh); gfs_stat_free(&gs); } else { /* What happen ? */ gfarmfs_errlog("RENAME: FATAL: " "some problem may happen later:" " %s", gfarm_url2path(url)); } } else { /* somebody changes st_mode */ if (retry == 0) { retry = 1; goto retry; } /* fatal situation ! */ fh->gf = NULL; gfarmfs_errlog("RENAME: FATAL: " "can't read/write more than this: " "%s: %s", gfarm_url2path(url), e2); /* ignore e2 */ } } /* (fh != NULL) */ #else /* for Gfarm version 2 or lator */ (void)from_mode; fh = FH_GET2(from_url, from_ino); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_wait(fh); if (fh != NULL && !gfarmfs_fh_is_opened(fh)) { FH_REMOVE2(from_url, from_ino); /* for FH_ADD */ FH_FREE(fh); fh = NULL; } #endif if (fh != NULL) FH_REMOVE2(from_url, from_ino); e = gfs_rename(from_url, to_url); if (fh != NULL) { if (e == NULL) e = FH_ADD1(to_url, fh); else e = FH_ADD2(from_url, from_ino, fh); } #endif return (e); } static int gfarmfs_rename_share_gf(const char *from, const char *to) { char *e; char *from_url; char *to_url; struct gfs_stat gs; long save_ino; mode_t save_mode; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_rename)) != NULL) goto end; e = add_gfarm_prefix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix(to, &to_url); if (e != NULL) goto free_from_url; e = gfs_stat(from_url, &gs); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(from_url); free(to_url); e = add_gfarm_prefix_symlink_suffix(from, &from_url); if (e != NULL) goto end; e = add_gfarm_prefix_symlink_suffix(to, &to_url); if (e != NULL) goto free_from_url; if (gfarmfs_debug >= 2) { printf("RENAME: for symlink: %s\n", from); } e = gfs_stat(from_url, &gs); } #endif if (e != NULL) goto free_to_url; if (GFARM_S_ISDIR(gs.st_mode)) { gfs_stat_free(&gs); /* wait all background processes of replication */ gfarmfs_async_fork_count_increment_n(DEFAULT_FORK_MAX); wait(NULL); e = gfs_rename(from_url, to_url); gfarmfs_async_fork_count_decrement_n(DEFAULT_FORK_MAX); } else if (GFARM_S_ISREG(gs.st_mode)) { save_ino = gs.st_ino; save_mode = gs.st_mode; gfs_stat_free(&gs); e = gfarmfs_rename_share_gf_check_open(from_url, to_url, save_ino, save_mode); } else { e = gfs_rename(from_url, to_url); } free_to_url: free(to_url); free_from_url: free(from_url); end: return gfarmfs_final(&prof_rename, e, 0, from); } static int gfarmfs_getattr_share_gf(const char *path, struct stat *stbuf) { char *e; FH fh; struct gfs_stat gs1; int symlinkmode = 0; char *url; if ((e = gfarmfs_init(&prof_getattr)) != NULL) goto end; #ifdef ENABLE_FASTCREATE if (enable_fastcreate > 0 && gfarmfs_fastcreate_getattr(path, stbuf)) goto end; #endif e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs1); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { free(url); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfs_stat(url, &gs1); symlinkmode = 1; } #endif if (e == GFARM_ERR_NO_FRAGMENT_INFORMATION && gfarmfs_gfs_stat_from_pi_only(path, &gs1) == NULL) e = NULL; if (e != NULL) goto free_url; e = convert_gfs_stat_to_stat(url, &gs1, stbuf, symlinkmode); if (e != NULL) goto free_gfs_stat; if (!S_ISREG(stbuf->st_mode)) /* && e == NULL: skip */ goto free_gfs_stat; fh = FH_GET2(url, gs1.st_ino); #if ENABLE_ASYNC_REPLICATION if (!gfarmfs_fh_is_opened(fh)) fh = NULL; #endif /* gfs_stat cannot get the exact st_size while the file is opened. * But gfs_fstat can do it. */ if (fh != NULL) { /* somebody opens this file. */ struct gfs_stat gs2; #if REVISE_CHMOD if (fh->mode_changed) stbuf->st_mode = fh->save_mode; #endif e = gfs_fstat(fh->gf, &gs2); if (e == NULL) { stbuf->st_size = gs2.st_size; gfs_stat_free(&gs2); } /* else: e = NULL (need?) */ } else if (enable_exact_filesize == 1 && S_ISREG(stbuf->st_mode)) { char *e2; file_offset_t size; e2 = gfarmfs_exact_filesize(url, &size, stbuf->st_mode); if (e2 == NULL) stbuf->st_size = size; } free_gfs_stat: gfs_stat_free(&gs1); free_url: free(url); end: return gfarmfs_final(&prof_getattr, e, 0, path); } static inline GFS_File gfarmfs_cast_fh_share_gf(struct fuse_file_info *fi) { FH fh; fh = (FH)(unsigned long) fi->fh; if (fh != NULL) return (fh->gf); else return (NULL); } static int gfarmfs_release_share_gf(const char *path, struct fuse_file_info *fi) { char *e; FH fh; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_release)) != NULL) goto end; fh = (FH)(unsigned long) fi->fh; fh->nopen--; if (fh->nopen <= 0) { char *url; char *e2; if (fh->gf) e = gfs_pio_close(fh->gf); else e = NULL; /* GFARM_ERR_INPUT_OUTPUT ? */ e2 = add_gfarm_prefix(path, &url); if (e2 != NULL) { if (e == NULL) e = e2; goto end; } else { #if REVISE_CHMOD if (fh->mode_changed) e = gfs_chmod(url, fh->save_mode); #endif #if REVISE_UTIME if (fh->utime_changed) e = gfs_utimes(url, fh->save_utime); #endif } #if ENABLE_ASYNC_REPLICATION if (replication_mode != REP_DISABLE /* enable */ && (fh->flags & GFARM_FILE_ACCMODE) != GFARM_FILE_RDONLY && e == NULL) { e = gfarmfs_async_replicate(url, fh); if (e != NULL) { gfarmfs_errlog("REPLICATE: %s: %s", gfarm_url2path(url), e); e = NULL; } } else { /* disable or read-open or error */ FH_REMOVE2(url, fh->ino); FH_FREE(fh); } #else FH_REMOVE2(url, fh->ino); FH_FREE(fh); #endif /* ENABLE_ASYNC_REPLICATION */ free(url); } else { /* nopen > 0 */ if ((fi->flags & O_ACCMODE) != O_RDONLY) fh->nwrite--; if (fh->nwrite <= 0 && (fh->flags & GFARM_FILE_ACCMODE) != GFARM_FILE_RDONLY) { /* try to change flags into O_RDONLY */ char *url; GFS_File gf; e = add_gfarm_prefix(path, &url); if (e != NULL) { e = NULL; /* ignore */ goto end; } e = gfs_pio_open(url, GFARM_FILE_RDONLY, &gf); free(url); if (e != NULL) e = NULL; /* use current fh->gf */ else { if (fh->gf) gfs_pio_close(fh->gf); fh->gf = gf; fh->flags = GFARM_FILE_RDONLY; } } } end: return gfarmfs_final(&prof_release, e, 0, path); } static int gfarmfs_truncate_share_gf(const char *path, off_t size) { char *e; char *url; FH fh; if ((e = gfarmfs_init(&prof_truncate)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; fh = FH_GET1(url); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_wait(fh); if (!gfarmfs_fh_is_opened(fh)) fh = NULL; #endif if (fh != NULL) { #ifdef IGNORE_TRUNCATE_EACCES /* do not check the permission */ #else e = gfs_access(url, W_OK); if (e != NULL) goto free_url; #endif /* IGNORE_TRUNCATE_EACCES */ if ((fh->flags & GFARM_FILE_ACCMODE) == GFARM_FILE_RDONLY) { char *e2; mode_t save_mode = 0; int is_saved = 0; gfs_pio_close(fh->gf); e = gfarmfs_truncate_common(url, size); e2 = gfs_pio_open(url, GFARM_FILE_RDONLY, &fh->gf); if (e2 != NULL) { /* retry */ struct gfs_stat gs; e2 = gfs_stat(url, &gs); if (e2 == NULL) { save_mode = gs.st_mode; e2 = gfs_chmod(url, save_mode|0400); if (e2 == NULL) is_saved = 1; gfs_stat_free(&gs); } e2 = gfs_pio_open(url, GFARM_FILE_RDONLY, &fh->gf); } if (e2 == NULL) e2 = gfarmfs_set_view(fh->gf); if (e2 != NULL) { fh->gf = NULL; gfarmfs_errlog("TRUNCATE: ERROR: reopen: " "%s%s: %s", gfarm_mount_point, path, e2); } if (is_saved) { e2 = gfs_fchmod(fh->gf, save_mode); if (e2 != NULL) { gfarmfs_errlog("TRUNCATE: WARN: " "can't change mode(%o):" " %s%s: %s", save_mode, gfarm_mount_point, path, e2); } } } else { /* WRONLY or RDWR */ e = gfs_pio_truncate(fh->gf, size); } } else { /* Nobody open this file. */ e = gfarmfs_truncate_common(url, size); } #ifndef IGNORE_TRUNCATE_EACCES free_url: #endif free(url); end: return gfarmfs_final(&prof_truncate, e, 0, path); } #if FUSE_USE_VERSION >= 25 static int gfarmfs_fgetattr_share_gf(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { char *e; struct gfs_stat gs; FH fh; if ((e = gfarmfs_init(&prof_fgetattr)) != NULL) goto end; fh = (FH)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_fstat(fh->gf, &gs); if (e == NULL) { e = convert_gfs_stat_to_stat(NULL, &gs, stbuf, 0); gfs_stat_free(&gs); #if REVISE_CHMOD if (fh->mode_changed) stbuf->st_mode = fh->save_mode; #endif } end: return gfarmfs_final(&prof_fgetattr, e, 0, path); } static int gfarmfs_ftruncate_share_gf(const char *path, off_t size, struct fuse_file_info *fi) { char *e; FH fh; if ((e = gfarmfs_init(&prof_ftruncate)) != NULL) goto end; fh = (FH)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_truncate(fh->gf, size); #if REVISE_UTIME if (e == NULL) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final(&prof_ftruncate, e, 0, path); } #endif /* FUSE_USE_VERSION >= 25 */ static int gfarmfs_read_share_gf(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { char *e; file_offset_t off; int n = 0; FH fh; if ((e = gfarmfs_init(&prof_read)) != NULL) goto end; fh = (FH)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_seek(fh->gf, offset, 0, &off); if (e != NULL) goto end; e = gfs_pio_read(fh->gf, buf, size, &n); CLEAR_EOF(fh->gf); #if REVISE_UTIME if (n > 0) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final(&prof_read, e, n, path); } static int gfarmfs_write_share_gf(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { char *e; file_offset_t off; int n = 0; FH fh; if ((e = gfarmfs_init(&prof_write)) != NULL) goto end; fh = (FH)(unsigned long) fi->fh; if (fh->gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else e = gfs_pio_seek(fh->gf, offset, 0, &off); if (e != NULL) goto end; e = gfs_pio_write(fh->gf, buf, size, &n); #if REVISE_UTIME if (n > 0) fh->utime_changed = 0; /* reset */ #endif end: return gfarmfs_final(&prof_write, e, n, path); } static int gfarmfs_fsync_share_gf(const char *path, int isdatasync, struct fuse_file_info *fi) { char *e; GFS_File gf; if ((e = gfarmfs_init(&prof_fsync)) != NULL) goto end; gf = gfarmfs_cast_fh_share_gf(fi); if (gf == NULL) e = GFARM_ERR_INPUT_OUTPUT; else { if (isdatasync) e = gfs_pio_datasync(gf); else e = gfs_pio_sync(gf); } end: return gfarmfs_final(&prof_fsync, e, 0, path); } static int gfarmfs_unlink_share_gf(const char *path) { char *e; char *url; gfarmfs_fastcreate_check(); if ((e = gfarmfs_init(&prof_unlink)) != NULL) goto end; e = add_gfarm_prefix(path, &url); if (e != NULL) goto end; #if ENABLE_ASYNC_REPLICATION if (replication_mode != REP_DISABLE) { FH fh; fh = FH_GET1(url); gfarmfs_async_stop(fh); /* for cancel... */ gfarmfs_async_wait(fh); } #endif e = gfarmfs_unlink_op(url); free(url); #ifdef SYMLINK_MODE if (e == GFARM_ERR_NO_SUCH_OBJECT && enable_symlink == 1) { if (gfarmfs_debug >= 2) printf("UNLINK: for symlink: %s\n", path); e = add_gfarm_prefix_symlink_suffix(path, &url); if (e != NULL) goto end; e = gfarmfs_unlink_op(url); free(url); } #endif end: return gfarmfs_final(&prof_unlink, e, 0, path); } static struct fuse_operations gfarmfs_oper_share_gf = { .getattr = gfarmfs_getattr_share_gf, .readlink = gfarmfs_readlink, .getdir = gfarmfs_getdir, .mknod = gfarmfs_mknod, .mkdir = gfarmfs_mkdir, .symlink = gfarmfs_symlink, .unlink = gfarmfs_unlink_share_gf, .rmdir = gfarmfs_rmdir, .rename = gfarmfs_rename_share_gf, .link = gfarmfs_link, .chmod = gfarmfs_chmod_share_gf, .chown = gfarmfs_chown, .truncate = gfarmfs_truncate_share_gf, .utime = gfarmfs_utime_share_gf, .open = gfarmfs_open_share_gf, .read = gfarmfs_read_share_gf, .write = gfarmfs_write_share_gf, .release = gfarmfs_release_share_gf, .fsync = gfarmfs_fsync_share_gf, #ifdef USE_GFS_STATFSNODE .statfs = gfarmfs_statfs, #endif #if FUSE_USE_VERSION >= 25 .create = gfarmfs_create_share_gf, .fgetattr = gfarmfs_fgetattr_share_gf, .ftruncate = gfarmfs_ftruncate_share_gf, .access = gfarmfs_access, #endif .flush = gfarmfs_flush, #if ENABLE_XATTR .setxattr = gfarmfs_setxattr, .getxattr = gfarmfs_getxattr, .listxattr = gfarmfs_listxattr, .removexattr = gfarmfs_removexattr, #endif }; /* ################################################################### */ #ifdef HAVE_PATHS_H #include <paths.h> #endif static int iscommand(char *path) { struct stat sb; if (stat(path, &sb) == 0) { if (S_ISREG(sb.st_mode) && /* save time by not calling access() */ (sb.st_mode & (S_IXOTH|S_IXGRP|S_IXUSR)) && access(path, X_OK) == 0) return (1); } return (0); } static char * commandpath(char *command) { static int bufsize = 0; static char *buffer = NULL; char *path; int span, dirlen; if (strchr(command, '/') != NULL) { /* absolute or relative path */ return iscommand(command) ? command : NULL; } if ((path = getenv("PATH")) == NULL) { #ifdef _PATH_DEFPATH path = _PATH_DEFPATH; #else path = "/bin:/usr/bin"; /* XXX */ #endif } if (buffer == NULL) { #ifdef PATH_MAX bufsize = PATH_MAX + 1; #else bufsize = 1025; #endif if ((buffer = malloc(bufsize)) == NULL) { fprintf(stderr, "commandpath(%s): not enough memory\n", command); exit(1); } } for (;;) { span = strcspn(path, ":"); dirlen = span == 0 ? 1 : span; if (bufsize <= dirlen + 1 + (int)strlen(command)) { bufsize = dirlen + 1 + strlen(command) + 1; if ((buffer = realloc(buffer, bufsize)) == NULL) { fprintf(stderr, "commandpath(%s): not enough memory\n", command); exit(1); } } if (span == 0) buffer[0] = '.'; else memcpy(buffer, path, dirlen); buffer[dirlen] = '/'; strcpy(&buffer[dirlen + 1], command); if (iscommand(buffer)) return buffer; if (path[span] == '\0') break; path += span + 1; /* skip ':' */ } return (NULL); /* not found */ } /* ################################################################### */ static char *program_name = "gfarmfs"; static struct fuse_operations *gfarmfs_oper_p = &gfarmfs_oper_share_gf; static void gfarmfs_version(int print_fuse_version) { const char *fusever[] = { program_name, "-V", NULL }; printf("GfarmFS-FUSE version %s (%s)\n", GFARMFS_VERSION, GFARMFS_REVISION); printf("Build: %s %s\n", __DATE__, __TIME__); #ifdef GFARM_VERSION printf("using Gfarm header version %s", GFARM_VERSION); #ifdef GFARM_REVISION printf(" (%s)", GFARM_REVISION); #endif printf("\n"); #endif #ifdef GFARM_VERSION printf("using Gfarm library version %s", gfarm_version_string()); #ifdef GFARM_REVISION printf(" (%s)", gfarm_revision_string()); #endif printf("\n"); #endif #if FUSE_USE_VERSION >= 25 printf("using FUSE version 2.5 interface\n"); #else printf("using FUSE version 2.2 interface\n"); #endif if (print_fuse_version) fuse_main(2, (char **) fusever, gfarmfs_oper_p); } static void gfarmfs_usage() { const char *fusehelp[] = { program_name, "-ho", NULL }; fprintf(stderr, "Usage: %s [GfarmFS options] <mountpoint> [FUSE options]\n" "\n" "GfarmFS options:\n" " -m <dir on Gfarm> set mount point on Gfarm\n" " (ex. -m /username cut gfarm:/username)\n" #ifdef SYMLINK_MODE " -s, --symlink enable symlink(2) to work (emulation)\n" #endif " -l, --linkiscopy enable link(2) to behave copying a file (emulation)\n" " -u, --unlinkall enable unlink(2) to remove all architecture files\n" " -b, --buffered enable buffered I/O (unset GFARM_FILE_UNBUFFERED)\n" " -F, --exactfilesize during open(2), exact st_size for other clients\n" " -n, --dirnlink count nlink of a directory precisely\n" #ifdef USE_GFS_STATFSNODE " -S, --disable-statfs disable statfs(2)\n" #endif #if ENABLE_ASYNC_REPLICATION " -N <num-of-replicas> run gfrep command after write-close\n" " -D <domainname> domainname of destination for -N option\n" #endif " -a <architecture> set the client architecture\n" " --trace <filename> record FUSE operations called by processes\n" " --errlog <filename> record errors of gfarm's own and replication\n" " --syslog record errors in syslog\n" " -v, --version show version and exit\n" "\n", program_name); fuse_main(2, (char **) fusehelp, gfarmfs_oper_p); } static char *opt_str_s = "-s"; static char *opt_str_o = "-o"; static char *opt_str_kopts = ""; static void check_fuse_options(int *argcp, char ***argvp, int *newargcp, char ***newargvp) { int argc = *argcp; char **argv = *argvp; char **newargv; int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-f") == 0) { gfarmfs_debug = 1; } else if (strcmp(argv[i], "-d") == 0) { gfarmfs_debug = 2; } else if (strcmp(argv[i], "-h") == 0) { gfarmfs_usage(); exit(0); } } newargv = malloc((argc + 3) * sizeof(char *)); if (newargv == NULL) { errno = ENOMEM; perror("check_fuse_options"); exit(1); } for (i = 0; i < argc; i++) { newargv[i] = argv[i]; } newargv[argc++] = opt_str_s; if (strlen(opt_str_kopts) > 0) { newargv[argc++] = opt_str_o; newargv[argc++] = opt_str_kopts; } *newargcp = argc; *newargvp = newargv; } static int next_arg_set(char **valp, int *argcp, char ***argvp, int errorexit) { int argc = *argcp; char **argv = *argvp; --argc; ++argv; if (argc <= 0 || (argc > 0 && argv[0][0] == '-' && argv[0][1] != '\0')) { if (errorexit) { gfarmfs_usage(); exit(1); } else { return (0); } } *valp = *argv; *argcp = argc; *argvp = argv; return (1); } static void parse_long_option(int *argcp, char ***argvp) { char **argv = *argvp; if (strcmp(&argv[0][1], "-symlink") == 0) enable_symlink = 1; else if (strcmp(&argv[0][1], "-linkiscopy") == 0) enable_linkiscopy = 1; else if (strcmp(&argv[0][1], "-architecture") == 0) next_arg_set(&arch_name, argcp, argvp, 1); else if (strcmp(&argv[0][1], "-unlinkall") == 0) enable_unlinkall = 1; else if (strcmp(&argv[0][1], "-unbuffered") == 0) enable_gfarm_iobuf = 0; else if (strcmp(&argv[0][1], "-buffered") == 0) enable_gfarm_iobuf = 1; else if (strcmp(&argv[0][1], "-dirnlink") == 0) enable_count_dir_nlink = 1; else if (strcmp(&argv[0][1], "--exactfilesize") == 0) enable_exact_filesize = 1; #ifdef USE_GFS_STATFSNODE else if (strcmp(&argv[0][1], "-disable-statfs") == 0) enable_statfs = 0; #endif else if (strcmp(&argv[0][1], "-oldio") == 0) use_old_functions = 1; #ifdef USE_SCHEDULER else if (strcmp(&argv[0][1], "--gfrep") == 0) use_gfrep = 1; else if (strcmp(&argv[0][1], "--gfrep-N") == 0) { use_gfrep = 1; force_gfrep_N = 1; } else if (strcmp(&argv[0][1], "-gfreppath") == 0) { use_gfrep = 1; next_arg_set(&gfrep_path, argcp, argvp, 0); } #endif else if (strcmp(&argv[0][1], "-trace") == 0) { next_arg_set(&trace_name, argcp, argvp, 0); if (trace_name == NULL || (strcmp(trace_name, "-") == 0)) enable_trace = stdout; else enable_trace = fopen(trace_name, "w"); if (enable_trace == NULL) { perror(trace_name); exit(1); } } else if (strcmp(&argv[0][1], "-errlog") == 0) { int fd; next_arg_set(&errlog_name, argcp, argvp, 0); if (errlog_name == NULL) { gfarmfs_usage(); exit(1); } fd = open(errlog_name, O_WRONLY|O_CREAT|O_APPEND, 0600); if (fd == -1) { fprintf(stderr, "logfile (open): %s: %s\n", errlog_name, strerror(errno)); exit(1); } enable_errlog = fdopen(fd, "a"); if (enable_errlog == NULL) { fprintf(stderr, "logfile (fdopen): %s: %s\n", errlog_name, strerror(errno)); exit(1); } setvbuf(enable_errlog, NULL, _IOLBF, 0); } else if (strcmp(&argv[0][1], "-syslog") == 0) { enable_syslog = 1; } else if (strcmp(&argv[0][1], "-timer") == 0) { enable_timer = 1; } else if (strcmp(&argv[0][1], "-version") == 0) { gfarmfs_version(1); exit(0); } else { gfarmfs_usage(); exit(1); } } static int next_num_get(char **ap, int *argcp, char ***argvp) { char *a = *ap; if (*(a + 1) == '\0') { char *num_str = NULL; next_arg_set(&num_str, argcp, argvp, 0); if (num_str == NULL) return (-1); else return atoi(num_str); } else { long int i; char *endptr; i = strtol(a + 1, &endptr, 10); if (endptr == (a + 1)) return (-1); else { *ap = endptr - 1; return (i); } } } static int parse_short_option(int *argcp, char ***argvp) { char **argv = *argvp; char *a = &argv[0][1]; while (*a) { switch (*a) { case 's': enable_symlink = 1; break; case 'l': enable_linkiscopy = 1; break; case 'a': return (next_arg_set(&arch_name, argcp, argvp, 1)); case 'u': enable_unlinkall = 1; break; case 'b': enable_gfarm_iobuf = 1; break; case 'F': enable_exact_filesize = 1; break; #ifdef USE_GFS_STATFSNODE case 'S': enable_statfs = 0; /* disable */ break; #endif case 'm': return (next_arg_set( &gfarm_mount_point, argcp, argvp, 1)); case 'n': enable_count_dir_nlink = 1; break; #if ENABLE_ASYNC_REPLICATION case 'N': replication_num = next_num_get(&a, argcp, argvp); if (replication_num == -1) replication_num = 2; break; case 'c': path_info_timeout = next_num_get(&a, argcp, argvp); if (path_info_timeout == -1) path_info_timeout = 500; break; case 'D': return (next_arg_set(&replication_domain, argcp, argvp, 1)); #endif case 'v': gfarmfs_version(1); exit(0); default: gfarmfs_usage(); exit(1); } ++a; } return (0); } static void check_gfarmfs_options(int *argcp, char ***argvp) { int argc = *argcp; char **argv = *argvp; char *argv0 = *argv; --argc; ++argv; while (argc > 0 && argv[0][0] == '-') { if (argv[0][1] == '-') parse_long_option(&argc, &argv); else parse_short_option(&argc, &argv); --argc; ++argv; } ++argc; --argv; *argcp = argc; *argv = argv0; *argvp = argv; } #ifdef USE_SCHEDULER static int is_new_gfrep() { int p, status; p = fork(); if (p == -1) { gfarmfs_errlog("gfrep_V_exec: fork: %s", strerror(errno)); return (1); } else if (p == 0) { CHANGE_DEV_NULL(1); CHANGE_DEV_NULL(2); execl(gfrep_path, gfrep_path, "-V", (char*)NULL); _exit(1); } waitpid(p, &status, 0); if (WEXITSTATUS(status) == 0) return (1); /* new */ else return (0); /* old */ } #endif /* USE_SCHEDULER */ static void setup_options() { char *e, *url; struct gfs_stat st; /* environment variables */ if (arch_name != NULL) { setenv("GFARM_ARCHITECTURE", arch_name, 1); } if (path_info_timeout > 0) { char s[16]; snprintf(s, 16, "%d", path_info_timeout); setenv("GFARM_PATH_INFO_TIMEOUT", s, 1); } /* setup old I/O functions */ if (use_old_functions == 1) { gfarmfs_oper_p = &gfarmfs_oper_base; } #ifdef DISABLE_FUSE_CREATE /* disable CREATE for old Linux kernel */ gfarmfs_oper_p->create = NULL; #endif /* validate gfarm_mount_point */ gfarm_mount_point_len = strlen(gfarm_mount_point); e = add_gfarm_prefix("/", &url); if (e == NULL) { e = gfs_stat(url, &st); if (e == NULL) gfs_stat_free(&st); else { fprintf(stderr, "%s: %s\n", gfarm_url2path(url), e); exit(1); } free(url); } else { fprintf(stderr, "add_gfarm_prefix: %s\n", e); exit(1); } /* checks for replication */ #if ENABLE_ASYNC_REPLICATION if (replication_num == 0 || replication_num == 1) { replication_mode = REP_DISABLE; } else if (replication_num <= -1) { /* without -N option */ #ifdef USE_GFARM_SCRAMBLE /* use gfs_scramble_make_replica() in default */ replication_mode = REP_SCRAMBLE; #else replication_mode = REP_DISABLE; #endif /* USE_GFARM_SCRAMBLE */ } else { /* replication_num >= 2 */ #ifdef USE_SCHEDULER if (use_gfrep) { if (force_gfrep_N) replication_mode = REP_GFREP_N; /* force N */ else replication_mode = REP_GFREP_HN; /* normal */ } else { replication_mode = REP_FROMTO_FUNC; } #else replication_mode = REP_GFREP_N; #endif /* USE_SCHEDULER */ } #endif /* ENABLE_ASYNC_REPLICATION */ /* checking the location of grep */ if (gfrep_path == NULL && #ifdef USE_SCHEDULER (replication_mode == REP_GFREP_N || replication_mode == REP_GFREP_HN) #else replication_mode == REP_GFREP_N #endif ) { gfrep_path = commandpath("gfrep"); if (gfrep_path == NULL) { fprintf(stderr, "gfrep: command not found (for -N option)\n"); exit(1); } } #ifdef USE_SCHEDULER /* checking the version of gfrep */ if (replication_mode == REP_GFREP_HN) if (is_new_gfrep() == 0) /* gfarm 1.4 or earlier */ replication_mode = REP_GFREP_d; #endif #ifdef USE_GFS_STATFSNODE /* -S, --disable-statfs */ if (enable_statfs == 0) gfarmfs_oper_p->statfs = NULL; /* disable */ #endif /* unlink operation */ #ifdef USE_GFARM_SCRAMBLE gfarmfs_unlink_op = gfs_unlink; #else if (enable_unlinkall == 1) { gfarmfs_unlink_op = gfs_unlink; } else { gfarmfs_unlink_op = gfarmfs_unlink_self_arch; } #endif /* USE_GFARM_SCRAMBLE */ if (enable_trace != NULL || enable_timer) { gfarmfs_init = gfarmfs_init_prof; gfarmfs_final = gfarmfs_final_prof; } else { gfarmfs_init = gfarmfs_init_normal; gfarmfs_final = gfarmfs_final_normal; } /* ----------------- logging start -------------------------- */ /* error log */ if (enable_errlog != NULL) { errlog_out = enable_errlog; if (dup2(fileno(enable_errlog), fileno(stderr)) == -1) { fprintf(stderr, "dup2: %s\n", strerror(errno)); exit(1); } } else { errlog_out = stderr; } /* syslog */ if (enable_syslog == 1) { openlog("gfarmfs", LOG_PID, LOG_LOCAL0); } } static void print_options() { if (gfarmfs_debug == 0) return; gfarmfs_version(0); #ifdef ENABLE_FASTCREATE if (enable_fastcreate == 1) { printf("enable fastcreate\n"); } #endif if (enable_symlink == 1) { printf("enable symlink\n"); } if (enable_linkiscopy == 1) { printf("enable linkiscopy\n"); } if (arch_name != NULL) { printf("set GFARM_ARCHITECTURE: %s \n", arch_name); } if (enable_unlinkall == 1) { printf("enable unlinkall\n"); } #ifdef USE_GFS_STATFSNODE if (enable_statfs == 0) { printf("disable statfs\n"); } else { printf("enable statfs\n"); } #else printf("disable statfs\n"); #endif if (enable_trace != NULL) { printf("enable trace (output file: %s)\n", trace_name); } if (enable_count_dir_nlink == 1) { printf("enable count_dir_nlink\n"); } if (enable_gfarm_iobuf == 1) { printf("enable buffered I/O (unset GFARM_FILE_UNBUFFERED)\n"); } else { printf("disable buffered I/O (set GFARM_FILE_UNBUFFERED)\n"); } if (enable_exact_filesize == 1) { printf("enable exact filesize\n"); } if (use_old_functions == 1) { printf("use old I/O functions\n"); } if (*gfarm_mount_point != '\0') { printf("mountpoint: gfarm:%s\n", gfarm_mount_point); } #if ENABLE_ASYNC_REPLICATION if (replication_mode != REP_DISABLE #ifdef USE_GFARM_SCRAMBLE && replication_mode != REP_SCRAMBLE #endif ) { printf("auto replication: "); if (replication_mode == REP_GFREP_N) { printf("%s -N %d\n", gfrep_path, replication_num); #ifdef USE_SCHEDULER } else if (replication_mode == REP_FROMTO_FUNC) { printf("using gfarm_url_section_replicate_from_to()" " (%d copies)\n", replication_num); } else if (replication_mode == REP_GFREP_HN) { printf("%s -H hostlist -N %d (%d copies)\n", gfrep_path, replication_num - 1, replication_num); } else if (replication_mode == REP_GFREP_d) { printf("%s -d (%d times) (%d copies)\n", gfrep_path, replication_num - 1, replication_num); #endif } if (replication_domain != NULL) { printf("destination domainname: %s\n", replication_domain); } #ifdef USE_GFARM_SCRAMBLE } else if (replication_mode == REP_SCRAMBLE){ printf("enable 'gfs_scramble_make_replica()' " "to run automatically\n"); #endif } else { printf("disable replication\n"); } #endif/* ENABLE_ASYNC_REPLICATION */ if (path_info_timeout > 0) { printf("set GFARM_PATH_INFO_TIMEOUT: %d (ms)\n", path_info_timeout); } if (enable_errlog) { printf("enable errlog: %s\n", errlog_name); } if (enable_syslog) { printf("enable syslog\n"); } printf("implicit FUSE options: %s", opt_str_s); if (strlen(opt_str_kopts) > 0) printf("-o %s\n", opt_str_kopts); else printf("\n"); } int main(int argc, char *argv[]) { int ret; char *e; char **newargv = NULL; int newargc = 0; if (argc > 0) { program_name = basename(argv[0]); } check_gfarmfs_options(&argc, &argv); check_fuse_options(&argc, &argv, &newargc, &newargv); e = gfarm_initialize(NULL, NULL); if (e != NULL) { fprintf(stderr, "gfarm_initialize: %s\n", e); exit(1); } setup_options(); print_options(); #if ENABLE_ASYNC_REPLICATION e = gfarmfs_async_fork_count_initialize(); if (e != NULL) { fprintf(stderr, "initialize: %s\n", e); exit(1); } #endif gfarmfs_prof_init(); umask(0); ret = fuse_main(newargc, newargv, gfarmfs_oper_p); free(newargv); gfarmfs_fastcreate_check(); gfarmfs_prof_final(); if (enable_trace != NULL) fclose(enable_trace); if (enable_errlog != NULL) fclose(enable_errlog); #if ENABLE_ASYNC_REPLICATION gfarmfs_async_fork_count_finalize(); #endif e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "gfarm_terminate: %s\n", e); exit(1); } return (ret); } <file_sep>/gfarm2fs/tags/gfarm2fs_1_2_5/acl.c /* * $Id$ */ #include "config.h" #include <stdlib.h> #include <string.h> #include <unistd.h> #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include <gfarm/gfarm.h> #include "gfarm2fs.h" #include "id.h" #include "acl.h" #ifdef ENABLE_GFARM_ACL /* with HAVE_SYS_ACL_H */ #include <sys/acl.h> #define ADD_BUF(src, size) \ do { \ if (nowlen + size > bufsize) { \ /* unexpected */ \ gflog_error(GFARM_MSG_2000095, \ "unexpected acl entries size"); \ free(buf); \ return (GFARM_ERR_INVALID_ARGUMENT); \ } \ memcpy(buf + nowlen, src, size); \ nowlen += size; \ } while (0) /* size: version=4 + (tag=2, perm=2, id=4) * num of entries */ #define ACL_BUFSIZE(acl) (4 + gfs_acl_entries(acl) * 8) /* to get ACL */ static gfarm_error_t gfarm2fs_gfarm_acl_to_posix_acl_xattr( const char *url, const gfarm_acl_t acl, void **posix_xattr_value_p, size_t *sizep) { gfarm_error_t e; void *buf; int nowlen = 0, bufsize; gfarm_uint32_t i32; gfarm_uint16_t i16; gfarm_acl_tag_t tag; gfarm_acl_perm_t perm; uid_t uid; gid_t gid; gfarm_acl_entry_t ent; gfarm_acl_permset_t pset; char *s; int bool; if (acl == NULL || posix_xattr_value_p == NULL || sizep == NULL) { gflog_debug(GFARM_MSG_2000096, "invalid argument of " "gfarm2fs_gfarm_acl_to_posix_acl_xattr()"); return (GFARM_ERR_INVALID_ARGUMENT); } bufsize = ACL_BUFSIZE(acl); GFARM_MALLOC_ARRAY(buf, bufsize); if (buf == NULL) { gflog_debug(GFARM_MSG_2000097, "no memory for getting ACL"); return (GFARM_ERR_NO_MEMORY); } i32 = gfarm_htol_32(ACL_EA_VERSION); ADD_BUF(&i32, sizeof(i32)); e = gfs_acl_get_entry(acl, GFARM_ACL_FIRST_ENTRY, &ent); while (e == GFARM_ERR_NO_ERROR) { gfs_acl_get_tag_type(ent, &tag); /* gfarm_acl_tag to posix_acl_tag */ i16 = gfarm_htol_16((gfarm_uint16_t)tag); ADD_BUF(&i16, sizeof(i16)); /* gfarm_acl_perm to posix_acl_perm */ perm = 0; gfs_acl_get_permset(ent, &pset); gfs_acl_get_perm(pset, GFARM_ACL_READ, &bool); if (bool) perm |= ACL_READ; gfs_acl_get_perm(pset, GFARM_ACL_WRITE, &bool); if (bool) perm |= ACL_WRITE; gfs_acl_get_perm(pset, GFARM_ACL_EXECUTE, &bool); if (bool) perm |= ACL_EXECUTE; i16 = gfarm_htol_16((gfarm_uint16_t)perm); ADD_BUF(&i16, sizeof(i16)); gfs_acl_get_qualifier(ent, &s); if (tag == GFARM_ACL_USER) { e = gfarm2fs_get_uid(url, s, &uid); if (e != GFARM_ERR_NO_ERROR) { free(buf); return (e); } i32 = gfarm_htol_32((gfarm_uint32_t)uid); } else if (tag == GFARM_ACL_GROUP) { e = gfarm2fs_get_gid(url, s, &gid); if (e != GFARM_ERR_NO_ERROR) { free(buf); return (e); } i32 = gfarm_htol_32((gfarm_uint32_t)gid); } else i32 = gfarm_htol_32((gfarm_uint32_t)ACL_UNDEFINED_ID); ADD_BUF(&i32, sizeof(i32)); e = gfs_acl_get_entry(acl, GFARM_ACL_NEXT_ENTRY, &ent); } if (e == GFARM_ERR_NO_SUCH_OBJECT) e = GFARM_ERR_NO_ERROR; if (e != GFARM_ERR_NO_ERROR) { free(buf); return (e); } if (nowlen == 0) { free(buf); *posix_xattr_value_p = NULL; *sizep = 0; } else { *posix_xattr_value_p = buf; *sizep = nowlen; } return (GFARM_ERR_NO_ERROR); } /* to set ACL */ static gfarm_error_t gfarm2fs_gfarm_acl_from_posix_acl_xattr( const char *url, const void *posix_xattr_value, size_t size, gfarm_acl_t *acl_p) { gfarm_error_t e; gfarm_acl_t acl; gfarm_acl_entry_t ent; gfarm_acl_permset_t pset; const void *p = posix_xattr_value; const void *endp = p + size; gfarm_uint32_t version, id; gfarm_uint16_t tag, perm; char *qual; gfarm_acl_tag_t tag2; uid_t uid; gid_t gid; memcpy(&version, p, sizeof(version)); p += sizeof(version); if (p > endp) return (GFARM_ERR_INVALID_ARGUMENT); if (gfarm_ltoh_32(version) != ACL_EA_VERSION) return (GFARM_ERR_INVALID_ARGUMENT); e = gfs_acl_init(5, &acl); if (e != GFARM_ERR_NO_ERROR) return (e); while (p < endp) { memcpy(&tag, p, sizeof(tag)); p += sizeof(tag); memcpy(&perm, p, sizeof(perm)); p += sizeof(perm); memcpy(&id, p, sizeof(id)); p += sizeof(id); e = gfs_acl_create_entry(&acl, &ent); if (e != GFARM_ERR_NO_ERROR) goto fail; tag2 = gfarm_ltoh_16(tag); /* posix_acl_tag to gfarm_acl_tag */ gfs_acl_set_tag_type(ent, tag2); gfs_acl_get_permset(ent, &pset); /* posix_acl_perm to gfarm_acl_perm */ gfs_acl_add_perm(pset, gfarm_ltoh_16(perm)); gfs_acl_set_permset(ent, pset); switch (tag2) { case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: qual = NULL; gfs_acl_set_qualifier(ent, NULL); break; case ACL_USER: uid = (uid_t) gfarm_ltoh_32(id); e = gfarm2fs_get_user(url, uid, &qual); if (e != GFARM_ERR_NO_ERROR) goto fail; gfs_acl_set_qualifier(ent, qual); break; case ACL_GROUP: gid = (gid_t) gfarm_ltoh_32(id); e = gfarm2fs_get_group(url, gid, &qual); if (e != GFARM_ERR_NO_ERROR) goto fail; gfs_acl_set_qualifier(ent, qual); break; default: e = GFARM_ERR_INVALID_ARGUMENT; goto fail; } } *acl_p = acl; return (GFARM_ERR_NO_ERROR); fail: gfs_acl_free(acl); return (e); } /* ------------------------------- */ gfarm_error_t gfarm2fs_acl_set(const char *path, gfarm_acl_type_t type, const void *value, size_t size) { gfarm_error_t e; gfarm_acl_t acl; e = gfarm2fs_gfarm_acl_from_posix_acl_xattr(path, value, size, &acl); if (e != GFARM_ERR_NO_ERROR) { gflog_debug(GFARM_MSG_2000098, "gfarm2fs_gfarm_acl_from_posix_acl_xattr(%s) failed" ": %s", path, gfarm_error_string(e)); return (e); } gfs_acl_sort(acl); e = gfs_acl_set_file(path, type, acl); if (e != GFARM_ERR_NO_ERROR) gflog_debug(GFARM_MSG_2000099, "gfs_acl_set_file(%s) failed: %s", path, gfarm_error_string(e)); gfs_acl_free(acl); return (e); } gfarm_error_t gfarm2fs_acl_get(const char *path, gfarm_acl_type_t type, void *value, size_t *sizep) { gfarm_error_t e; gfarm_acl_t acl; size_t size; void *posix; e = gfs_acl_get_file_cached(path, type, &acl); if (e != GFARM_ERR_NO_ERROR) return (e); if (*sizep == 0) { *sizep = ACL_BUFSIZE(acl); goto free_acl; } e = gfarm2fs_gfarm_acl_to_posix_acl_xattr(path, acl, &posix, &size); if (e != GFARM_ERR_NO_ERROR) { gflog_debug(GFARM_MSG_2000100, "gfarm2fs_gfarm_acl_to_posix_acl_xattr() failed: %s", gfarm_error_string(e)); goto free_acl; } if (size > *sizep) { e = GFARM_ERR_RESULT_OUT_OF_RANGE; gflog_error(GFARM_MSG_2000101, "unexpected error: acl size > buf size"); goto free_posix; } if (value != NULL) memcpy(value, posix, size); free_posix: *sizep = size; free(posix); free_acl: gfs_acl_free(acl); return (e); } #endif /* ENABLE_GFARM_ACL */ <file_sep>/gfarm/tags/gfarm_1_1_1_rc7/gftool/gfarm_agent/Makefile # $Id$ top_builddir = ../.. top_srcdir = $(top_builddir) srcdir = . include $(top_srcdir)/makes/var.mk PROGRAM = gfarm_agent SRCS = gfarm_agent.c agent_thr.c agent_ptable.c OBJS = gfarm_agent.o agent_thr.o agent_ptable.o CFLAGS = $(COMMON_CFLAGS) -I$(GFUTIL_SRCDIR) -I$(GFARMLIB_SRCDIR) \ $(openssl_includes) LDLIBS = $(COMMON_LDFLAGS) $(GFARMLIB) $(LIBS) DEPLIBS = $(DEPGFARMLIB) all: $(PROGRAM) include $(top_srcdir)/makes/prog.mk ### gfarm_agent.o: $(DEPGFARMINC) \ $(GFUTIL_SRCDIR)/gfutil.h \ $(GFARMLIB_SRCDIR)/xxx_proto.h \ $(GFARMLIB_SRCDIR)/io_fd.h \ $(GFARMLIB_SRCDIR)/agent_proto.h \ $(GFARMLIB_SRCDIR)/agent_wrap.h \ agent_thr.h \ agent_ptable.h agent_thr.o: $(GFUTIL_SRCDIR)/gfutil.h \ agent_thr.h agent_ptable.o: agent_ptable.h <file_sep>/gfarm/tags/gfarm_0_1/gftool/gfmpirun/gfmpirun.c #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <libgen.h> #include <gfarm/gfarm.h> #include "gfj_client.h" char *program_name = "gfmpirun"; void setsig(int signum, void (*handler)(int)) { struct sigaction act; act.sa_handler = handler; sigemptyset(&act.sa_mask); /* do not set SA_RESTART to make interrupt at waitpid(2) */ act.sa_flags = 0; if (sigaction(signum, &act, NULL) == -1) { fprintf(stderr, "%s: sigaction(%d): %s\n", program_name, signum, strerror(errno)); exit(1); } } void ignore_handler(int signum) { /* do nothing */ } void sig_ignore(int signum) { /* we don't use SIG_IGN to make it possible that child catch singals */ setsig(signum, ignore_handler); } void usage() { fprintf(stderr, "Usage: %s [-H <hostfile>] [<mpirun_options>] command...\n", program_name); exit(1); } int main(argc, argv) int argc; char **argv; { gfarm_stringlist input_list, output_list, arg_list, option_list; int command_index; int pid, status; int i, nhosts, job_id, nfrags, save_errno; char *e, **hosts; static char gfarm_prefix[] = "gfarm:"; # define GFARM_PREFIX_LEN (sizeof(gfarm_prefix) - 1) static char template[] = "/tmp/mpXXXXXX"; char filename[sizeof(template)]; FILE *fp; char total_nodes[GFARM_INT32STRLEN]; char *hostfile = NULL, *scheduling_file; char *command_name, **delivered_paths = NULL; if (argc >= 1) program_name = basename(argv[0]); e = gfarm_initialize(&argc, &argv); if (e != NULL) { fprintf(stderr, "%s: gfarm initialize: %s\n", program_name, e); exit(1); } e = gfj_initialize(); if (e != NULL) { fprintf(stderr, "%s: job manager: %s\n", program_name, e); exit(1); } gfarm_stringlist_init(&option_list); /* * parse and skip/record options */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; if (argv[i][1] == 'H') { if (argv[i][2] != '\0') { hostfile = &argv[i][2]; } else if (++i < argc) { hostfile = argv[i]; } else { fprintf(stderr, "%s: " "missing argument to %s\n", program_name, argv[i - 1]); usage(); } goto skip_opt; } if (strcmp(argv[i], "-arch") == 0 || strcmp(argv[i], "-np") == 0 || strcmp(argv[i], "-stdin") == 0 || strcmp(argv[i], "-stdout") == 0 || strcmp(argv[i], "-stderr") == 0 || strcmp(argv[i], "-nexuspg") == 0 || strcmp(argv[i], "-nexusdb") == 0 || strcmp(argv[i], "-p4pg") == 0 || strcmp(argv[i], "-tcppg") == 0 || strcmp(argv[i], "-p4ssport") == 0 || strcmp(argv[i], "-mvback") == 0 || strcmp(argv[i], "-maxtime") == 0 || strcmp(argv[i], "-mem") == 0 || strcmp(argv[i], "-cpu") == 0) { /* an option which does have an argument */ if (++i >= argc) { fprintf(stderr, "%s: " "missing argument to %s\n", program_name, argv[i - 1]); usage(); } gfarm_stringlist_add(&option_list, argv[i - 1]); } gfarm_stringlist_add(&option_list, argv[i]); skip_opt: ; } command_index = i; if (command_index >= argc) /* no command name */ usage(); command_name = argv[command_index]; gfarm_stringlist_init(&input_list); gfarm_stringlist_init(&output_list); for (i = command_index + 1; i < argc; i++) { if (strncmp(argv[i], gfarm_prefix, GFARM_PREFIX_LEN) == 0) { e = gfarm_url_fragment_number(argv[i], &nfrags); if (e == NULL) { gfarm_stringlist_add(&input_list, argv[i]); } else { gfarm_stringlist_add(&output_list, argv[i]); } } } if (hostfile == NULL) { if (gfarm_stringlist_length(&input_list) == 0) { fprintf(stderr, "%s: no input file\n", program_name); exit(1); } /* XXX - this is only using first input file for scheduling */ scheduling_file = gfarm_stringlist_elem(&input_list, 0); e = gfarm_url_hosts_schedule(scheduling_file, NULL, &nhosts, &hosts); if (e != NULL) { fprintf(stderr, "%s: schedule: %s\n", program_name, e); exit(1); } fp = fdopen(mkstemp(strcpy(filename, template)), "w"); for (i = 0; i < nhosts; i++) fprintf(fp, "%s\n", hosts[i]); fclose(fp); hostfile = filename; } else { int error_line; e = gfarm_hostlist_read(hostfile, &nhosts, &hosts, &error_line); if (e != NULL) { if (error_line != -1) fprintf(stderr, "%s: %s: line %d: %s\n", program_name, hostfile, error_line, e); else fprintf(stderr, "%s: %s: %s\n", program_name, hostfile, e); exit(1); } scheduling_file = hostfile; } /* * register job manager */ e = gfarm_user_job_register(nhosts, hosts, program_name, scheduling_file, argc - command_index, &argv[command_index], &job_id); if (e != NULL) { fprintf(stderr, "%s: job register: %s\n", program_name, e); exit(1); } /* * deliver gfarm:program. */ if (strncmp(command_name, gfarm_prefix, GFARM_PREFIX_LEN) == 0) { e = gfarm_url_program_deliver(command_name, nhosts, hosts, &delivered_paths); if (e != NULL) { fprintf(stderr, "%s: deliver %s: %s\n", program_name, command_name, e); exit(1); } } sprintf(total_nodes, "%d", nhosts); gfarm_stringlist_init(&arg_list); gfarm_stringlist_add(&arg_list, "mpirun"); #if 1 /* * without this option, the machine which is running gfmpirun * always becomes node 0. and total number of nodes becomes * ``1 + total_nodesprocesses'' because this host will be included * regardless whether machine file includes this host or not. * XXX - this option is only available on mpich/p4. */ gfarm_stringlist_add(&arg_list, "-nolocal"); #endif gfarm_stringlist_add(&arg_list, "-machinefile"); gfarm_stringlist_add(&arg_list, hostfile); gfarm_stringlist_add(&arg_list, "-np"); gfarm_stringlist_add(&arg_list, total_nodes); gfarm_stringlist_add_list(&arg_list, &option_list); if (delivered_paths == NULL) { gfarm_stringlist_add(&arg_list, command_name); } else { /* * XXX This assumes that all nodes are same architecture * XXX and all nodes have same gfarm_root! * XXX really broken. */ gfarm_stringlist_add(&arg_list, delivered_paths[0]); } gfarm_stringlist_cat(&arg_list, &argv[command_index + 1]); gfarm_stringlist_add(&arg_list, NULL); switch (pid = fork()) { case 0: execvp("mpirun", GFARM_STRINGLIST_STRARRAY(arg_list)); perror("mpirun"); exit(1); case -1: perror("fork"); exit(1); } sig_ignore(SIGHUP); sig_ignore(SIGINT); sig_ignore(SIGQUIT); sig_ignore(SIGTERM); sig_ignore(SIGTSTP); while (waitpid(-1, &status, 0) != -1) ; save_errno = errno; for (i = 0; i < gfarm_stringlist_length(&output_list); i++) gfarm_url_fragment_cleanup( gfarm_stringlist_elem(&output_list, i), nhosts, hosts); if (hostfile == filename) unlink(filename); if (delivered_paths != NULL) gfarm_strings_free_deeply(nhosts, delivered_paths); gfarm_strings_free_deeply(nhosts, hosts); gfarm_stringlist_free(&arg_list); gfarm_stringlist_free(&output_list); gfarm_stringlist_free(&input_list); gfarm_stringlist_free(&option_list); e = gfarm_terminate(); if (e != NULL) { fprintf(stderr, "%s: %s\n", program_name, e); exit(1); } return (save_errno != ECHILD ? 1 : WIFEXITED(status) ? WEXITSTATUS(status) : 1); } <file_sep>/gfarm/tags/gfarm_1_0_4_rc6/lib/libgfarm/gfarm/auth_common_gsi.c #include <sys/types.h> #include <pwd.h> #include <string.h> #include <gssapi.h> #include <gfarm/gfarm_config.h> #include <gfarm/gfarm_error.h> #include <gfarm/gfarm_misc.h> #include "gfutil.h" #include "gfarm_secure_session.h" #include "gfarm_auth.h" #include "auth.h" #include "auth_gsi.h" #define GFSL_CONF_USERMAP "/etc/grid-security/grid-mapfile" static int gsi_initialized; static int gsi_server_initialized; static char *gsi_client_cred_name; char * gfarm_gsi_client_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) return (NULL); rv = gfarmSecSessionInitializeInitiator(NULL, GFSL_CONF_USERMAP, &e_major, &e_minor); if (rv <= 0) { if (gflog_auth_get_verbose()) { gflog_error( "can't initialize as initiator because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeInitiator(); return ("GSI credential initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 0; gsi_client_cred_name = gfarmSecSessionGetInitiatorCredName(); return (NULL); } char * gfarm_gsi_client_cred_name(void) { return (gsi_client_cred_name); } char * gfarm_gsi_server_initialize(void) { OM_uint32 e_major; OM_uint32 e_minor; int rv; if (gsi_initialized) { if (gsi_server_initialized) return (NULL); gfarmSecSessionFinalizeInitiator(); gsi_initialized = 0; } rv = gfarmSecSessionInitializeBoth(NULL, NULL, GFSL_CONF_USERMAP, &e_major, &e_minor); if (rv <= 0) { if (gflog_auth_get_verbose()) { gflog_error( "can't initialize GSI as both because of:", NULL); gfarmGssPrintMajorStatus(e_major); gfarmGssPrintMinorStatus(e_minor); } gfarmSecSessionFinalizeBoth(); return ("GSI initialization failed"); /* XXX */ } gsi_initialized = 1; gsi_server_initialized = 1; return (NULL); } /* * Delegated credential */ static gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL; void gfarm_gsi_set_delegated_cred(gss_cred_id_t cred) { delegated_cred = cred; } gss_cred_id_t gfarm_gsi_get_delegated_cred() { return (delegated_cred); } /* * converter from credential configuration to [GSSNameType, GSSName]. * * The results of * (type, service, name) -> [NameType, Name] -> gss_name_t -> gss_cred_id_t * are: * (DEFAULT, NULL, NULL) is not allowed. caller must check this at first. * (NO_NAME, NULL, NULL) -> [GSS_C_NO_OID, NULL] -> GSS_C_NO_NAME * (MECHANISM_SPECIFIC, NULL, name) -> [GSS_C_NO_OID, name] * (HOST, service, host) ->[GSS_C_NT_HOSTBASED_SERVICE, service + "@" + host] * if (service == NULL) service = "host" * if (host == NULL) host = canonical_self_name * (USER, NULL, username) -> [GSS_C_NT_USER_NAME, username] * if (username == NULL) username = self_local_username * * when a server acquires a credential of itself: * (DEFAULT, NULL, NULL) -> N/A -> N/A -> GSS_C_NO_CREDENTIAL * when a client authenticates a server: * (DEFAULT, NULL, NULL) is equivalent to (HOST, NULL, NULL) * (HOST, service, NULL) is equivalent to (HOST, service, peer_host) */ char * gfarm_gsi_cred_config_convert_to_name_and_type( enum gfarm_auth_cred_type type, char *service, char *name, char *hostname, char **name_stringp, gss_OID *name_typep, int *need_freep) { char *gss_name_string; switch (type) { case GFARM_AUTH_CRED_TYPE_DEFAULT: if (name != NULL) return ("cred_type is not set, but cred_name is set"); if (service != NULL) return ("cred_type is not set, but cred_service is set" ); return ("internal error: missing GSS_C_NO_CREDENTIAL check"); case GFARM_AUTH_CRED_TYPE_NO_NAME: if (name != NULL) return ("cred_type is \"no-name\", " "but cred_name is set"); if (service != NULL) return ("cred_type is \"no-name\", " "but cred_service is set"); *name_stringp = NULL; *name_typep = GSS_C_NO_OID; *need_freep = 0; break; case GFARM_AUTH_CRED_TYPE_MECHANISM_SPECIFIC: if (name == NULL) return ("cred_type is \"mechanism-specific\", " "but cred_name is not set"); if (service != NULL) return ("cred_type is \"mechanism-specific\", " "but cred_service is set"); *name_stringp = name; *name_typep = GSS_C_NO_OID; *need_freep = 0; break; case GFARM_AUTH_CRED_TYPE_HOST: if (service == NULL) service = "host"; if (name == NULL) name = hostname; if (name == NULL && gfarm_host_get_canonical_self_name(&name) != NULL) name = gfarm_host_get_self_name(); gss_name_string = malloc(strlen(service) + strlen(name) + 2); if (gss_name_string == NULL) return (GFARM_ERR_NO_MEMORY); sprintf(gss_name_string, "%s@%s", service, name); *name_stringp = gss_name_string; *name_typep = GSS_C_NT_HOSTBASED_SERVICE; *need_freep = 1; break; case GFARM_AUTH_CRED_TYPE_USER: if (service != NULL) return ("cred_type is \"user\", " "but cred_service is set"); /* * XXX FIXME: `name' must be converted from global_username * to local_username, but there is no such function for now. */ *name_stringp = name != NULL ? name : gfarm_get_local_username(); *name_typep = GSS_C_NT_USER_NAME; *need_freep = 0; break; default: return ("internal error - invalid cred_type"); } return (NULL); } <file_sep>/gfarm_mpiio/trunk/mpich2/Makefile.in CC = @CC@ AR = @AR@ RANLIB = @RANLIB@ LIBNAME = @LIBNAME@ MPI = @MPI@ srcdir = @srcdir@ CC_SHL = @CC_SHL@ SHLIBNAME = @SHLIBNAME@ #DEFS = @DEFS@ -I. -I${srcdir} CPPFLAGS = @CPPFLAGS@ INCLUDES = -I@MPI_INCLUDE_DIR@ -I${srcdir}/../include -I../include -I../../include -I${srcdir}/../../../../include -I../../../../include #CFLAGS = @CPPFLAGS@ @CFLAGS@ $(INCLUDES) CFLAGS = @CFLAGS@ top_builddir = @master_topbuild_dir@ LIBTOOL = @LIBTOOL@ C_COMPILE = $(CC) $(DEFS) $(INCLUDES) $(CFLAGS) $(CPPFLAGS) C_COMPILE_SHL = $(CC_SHL) $(DEFS) $(INCLUDES) $(CFLAGS) $(CPPFLAGS) #C_COMPILE_SHL = $(CC_SHL) @VPATH@ AD_GFARM_OBJECTS = ad_gfarm_close.o ad_gfarm_read.o ad_gfarm_rdcoll.o \ ad_gfarm_wrcoll.o ad_gfarm_open.o ad_gfarm_write.o \ ad_gfarm_fcntl.o ad_gfarm_flush.o \ ad_gfarm_seek.o ad_gfarm_resize.o ad_gfarm_hints.o \ ad_gfarm_delete.o ad_gfarm.o default: $(LIBNAME) @if [ "@ENABLE_SHLIB@" != "none" ] ; then \ $(MAKE) $(SHLIBNAME).la ;\ fi .SUFFIXES: $(SUFFIXES) .p .lo # $(CC) $(CFLAGS) -c $< .c.o: @if [ "x$(VERBOSE)" != "x1" ] ; then \ echo " CC $<" ; \ else \ echo $(C_COMPILE) -c $< ; \ fi @$(C_COMPILE) -c $< # $(C_COMPILE_SHL) $(CFLAGS) -c $< -o _s$*.o # @mv -f _s$*.o $*.lo .c.lo: @if [ "x$(VERBOSE)" != "x1" ] ; then \ echo " CC $<" ; \ else \ echo $(C_COMPILE_SHL) -c $< -o _s$*.o ; \ echo mv -f _s$*.o $*.lo ; \ fi @$(C_COMPILE_SHL) -c $< -o _s$*.o @mv -f _s$*.o $*.lo $(LIBNAME): $(AD_GFARM_OBJECTS) $(AR) $(LIBNAME) $(AD_GFARM_OBJECTS) $(RANLIB) $(LIBNAME) AD_GFARM_LOOBJECTS = $(AD_GFARM_OBJECTS:.o=.lo) $(SHLIBNAME).la: $(AD_GFARM_LOOBJECTS) $(AR) $(SHLIBNAME).la $(AD_GFARM_LOOBJECTS) clean: @rm -f *.o *.lo *.gcno *.gcda *.bb *.bbg @rm -f ${srcdir}/*.gcno ${srcdir}/*.gcda @rm -f ${srcdir}/*.bb ${srcdir}/*.bbg tags: TAGS SOURCES = ${AD_GFARM_OBJECTS:.o=.c} HEADERS = TAGS:${HEADERS} ${SOURCES} here=`cd ../../../../.. && pwd` ; cd ${srcdir} && etags -o $$here/TAGS --append ${HEADERS} ${SOURCES}
907d80d226b6f0ecaf1d99e32c4d45da2c83fe37
[ "HTML", "Makefile", "Java", "Python", "PHP", "Ant Build System", "C++", "C", "M4Sugar", "Shell" ]
491
Shell
rootfs-analytics/gfarm-fs
3a21bbff37595455259d2931764c4cb338022eac
57f19518a80ae9d8df97b5d7acb4ebd14946fce5
refs/heads/master
<file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; if (isset($_GET['emp_info'])) { $emp_info = $_GET['emp_info']; $show_employee = show_employee($emp_info); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="578" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="578" align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="big_2"><img src="../image/icon/identity_New1.png" width="22" height="22" /><span class="txt_4g"><?php echo $show_employee['emp_titre'] ?></span> <?php echo $show_employee['emp_nom'].' '.$show_employee['emp_prenom']; ?> </td> </tr> </table> <table width="98%" height="468" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="title_1">Document Information </td> <td width="80%" align="left" class="title_1"><span class="txt_4">|</span> <span class="txt_4g">Department</span><span class="txt_1g"> <?php echo $show_employee['emp_groupe']; ?></span> </td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td align="left">&nbsp;</td> </tr> <!--************************--> <table class="sab" width="100%" align="center" cellspacing="1" > <tr class="hhhhhh" > <td>D&eacute;signation</td> <td>E-mail</td> <td>GSM</td> <td>Nationalit&eacute;</td> <td>CIN</td> <td>Copie CIN</td> </tr> <tr align="center" style="background-color:#e2f2fc;" height="40"> <td><?php echo $show_employee['emp_designation']; ?></td> <td><?php echo $show_employee['emp_email']; ?></td> <td><?php echo $show_employee['emp_tel']; ?></td> <td><?php echo $show_employee['nat_design']; ?></td> <td><?php echo $show_employee['emp_num_pass']; ?></td> <td><?php if (!empty($show_employee['emp_attach_pass'])) echo '<a href="#" onclick=" window.open(\'../fichiers/copie_cin/'.$show_employee['emp_attach_pass'].'\',\'List\',\'width=580,height=680\').focus();"><img src="../image/icon/kget_list.png" alt="afficher le fichier" width="22" height="22" align="absmiddle" border="0"/></a>'; ?></td> </tr> </table> <!-- </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" height="30" align="left" class="txt_4">D&eacute;signation</td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['emp_designation'] ?></td> <td width="20%" align="left" class="important_2"><span class="txt_4">E-mail</span></td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['emp_email'] ?></td> </tr> <tr> <!-- <td height="30" align="left" class="txt_4">Company</td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['comp_nom'] ?></td> <td align="left" class="important_2"><span class="txt_4">GSM </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['emp_tel'] ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">Nationalit&eacute;</td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['nat_design'] ?></td> <td align="left" class="important_2"><span class="txt_4">CIN </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_employee['emp_num_pass'] ?></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="txt_4">Passport Copy </td> <td width="80%" align="left" class="txt_2"><span class="important_2"><span class="txt_4">|</span> <?php if (!empty($show_employee['emp_attach_pass'])) echo '<a href="#" onclick=" window.open(\'../fichiers/copie_cin/'.$show_employee['emp_attach_pass'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a>'; ?> </span></td> </tr> </table>--> </td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="detail_1"><NAME> - Doc Manager </td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="507" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="507" align="center" valign="top"><table width="98%" height="680" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="18%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><span class="big_3">Bienvenue, </span> <span class="txt_4g"><?php echo $user ?></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Liens utiles </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=document&amp;show=list">Gestion de documents </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=employee&amp;show=list">Gestion de Ressources </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=user&amp;show=list">Gestion de Utilisateurs </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> </tr> </table></td> <td width="64%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="500" height="350" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top" background="../image/design/img_ppm_gf.png">&nbsp;</td> </tr> </table></td> <td width="18%" align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table></td> </tr> </table></td> </tr> </table> <file_sep><?php session_start(); include_once '../lib/lib_mysql.php'; connexion(); $memePage = $_SERVER["PHP_SELF"]; $message = 'Enter le login et le password'; if (isset($_POST['btnConnexion']) && !empty($_POST['txtUtilisateur']) && !empty($_POST['txtMotdepasse'])) { $user = $_POST['txtUtilisateur']; $motdepasse = $_POST['txtMotdepasse']; if (id_utilisateur($user,$motdepasse)==0) { $message = '<span class="txtRouge12b">Le login ou le mot de passe est incorrect !</span>'; } else { $show_user = show_user($user); $authorization = $show_user['dom_autorisation']; $_SESSION['user'] = $user; $_SESSION['authorization'] = $authorization; header("Location:./"); exit(); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Gestion Documents et Ressources FLO</title> <link rel="icon" type="image/png" href="favicon.png" /> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <link href="../style/menu.css" rel="stylesheet" type="text/css" /> <style> table.Form_sabir{ -webkit-box-shadow: 0px 0px 10px #555050; box-shadow: 0px 0px 10px #555050; margin-top: 200px; background-color: #807372; background-image: -webkit-linear-gradient(top,#5f4d4e,#5f4d4e); background-image: -moz-linear-gradient(top,#5f4d4e,#5f4d4e); background-image: -ms-linear-gradient(top,#5f4d4e,#5f4d4e); background-image: -o-linear-gradient(top,#5f4d4e,#5f4d4e); background-image: linear-gradient(top,#5f4d4e,#5f4d4e); border: 1px solid transparent; text-shadow: 0 1px rgba(0, 0, 0, 0.1); text-transform: uppercase; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; /* padding: 4px 20px ;*/ color: #fff ; font: bold 13px "Trebuchet MS",Arial,sans-serif ; line-height: 1em ; text-align: center ; text-decoration: none ; } </style> </head> <body> <table width="100%" height="759" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="759" align="center" valign="top"><table width="100%" height="751" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="751" align="center" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0" background="../image/design/bg_head_2.png"> <tr> <td width="22%" align="left" valign="top"><img src="../image/design/img_ppm_logo_2.png" width="220" height="80" /></td> <td width="78%" align="right" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="right"><span class="txt_2"><span class="txt_3">Aujourd'huit <?php echo date_fr_2(date("Y-m-d")); ?></span></span>&nbsp;&nbsp;</td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="48" align="right" valign="top">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="1" border="0" cellspacing="0" cellpadding="0" class="bg_menubar"> <tr> <td></td> </tr> </table> <table width="100%" height="565" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="565" align="center" valign="top"><table width="98%" height="30" border="0" cellpadding="0" cellspacing="0" class="bg_submenubar"> <tr> <td width="36%" height="27" align="left">&nbsp;</td> <td width="64%" align="right" class="txt_4"> </td> </tr> </table> <table class="Form_sabir" width="504" height="240" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="middle"><table width="98%" height="121" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="100%" align="center"><table width="100%" height="31" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="100%" align="center" class="message"><?php echo $message ?></td> </tr> </table> <table width="80%" border="0" cellpadding="0" cellspacing="0"> <form id="form1" name="form1" method="post" action=""> <tr> <td width="29%" height="30" align="left" >Login</td> <td width="3%">&nbsp;</td> <td width="68%" align="left"><label> <input name="txtUtilisateur" type="text" id="txtUtilisateur" /> </label></td> </tr> <tr> <td height="30" align="left" >Mot de passe</td> <td>&nbsp;</td> <td align="left"><label> <input name="txtMotdepasse" type="password" id="txtMotdepasse" /> </label></td> </tr> <tr height="40"> <td height="30" align="left" class="token_1">&nbsp;</td> <td>&nbsp;</td> <td align="left"> <label> <input name="btnConnexion" class="sssabir"type="submit" id="btnConnexion" value="Connexion" /> </label></td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="32" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" class="txt_4g"></td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter_0.png"> <tr> <td></td> </tr> </table></td> </tr> </table> <table width="100%" height="32" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td align="center">Ecole Superieur de Technologie</td> </tr> </table> </body> </html> <file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; if (isset($_GET['doc_info'])) { $doc_info = $_GET['doc_info']; $show_document = show_document($doc_info); $folder_id = $_GET['folder_id']; $show_folder = show_folder($folder_id); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="578" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="578" align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="230" height="50" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="69%" align="left" class="txt_4g">Documents - Folder Opened : <?php echo $show_folder['folder_name']; ?></td> <td width="31%" align="right" class="txt_4g"><span class="txt_4"><<&nbsp;<span class="txt_1g"><a href="folder_documents.php?folder_id=<?php echo $folder_id; ?>">Return to the Folder Opened </a></span></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="big_3">Document opened : <span class="big_2"><?php echo $show_document['doc_title']; ?></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="txt_4g">Deatail : <span class="title_2"><?php echo '<span class="txt_4g">'.$show_document['doc_detail'].'</span>'; ?></span> </td> </tr> </table> <table width="98%" height="468" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td align="left">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="title_1"><span class="txt_1g"><span class="txt_4g">Type Document </span></span></td> <td width="80%" align="left" class="txt_1g"><span class="txt_4g"><span class="txt_4">|</span></span> <?php echo $show_document['typdoc_title'] ?> </td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" height="30" align="left" class="txt_4">Proprietaire</td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_owner'] ?></td> <td width="20%" align="left" class="important_2"><span class="txt_4"> Date de creation </span></td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo date_fr_2($show_document['doc_creat_date']) ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">Prepared By </td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_prepared_by'] ?></td> <td align="left" class="important_2"><span class="txt_4">Sign. Date </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo date_fr_2($show_document['doc_sign_date']) ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">Reviewed By </td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_reviewed_by'] ?></td> <td align="left" class="important_2"><span class="txt_4">Number of Page </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_nbr_page'] ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="txt_4">Nom du Dossier </td> <td width="80%" align="left" class="txt_4">Fichier Attach&eacute; </td> </tr> </table> <?php echo show_document_folder($doc_info) ?> </td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" class="token_1"><NAME> - Doc Manager </td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep><?php function connexion() { $srv = "localhost"; $usr = "root"; $pwd = ""; $db = "gestion"; $id_connex = mysql_connect($srv, $usr, $pwd) or die("Could not connect"); mysql_select_db($db) or die("Could not select database"); } function deconnexion() { mysql_close(); } function requete_SQL($strSQL) { $result = mysql_query($strSQL) or die ("ggggggg".mysql_error()); if (!$result) { $message = 'Une erreur s\'est produite, repartez sur menu principal ou contactez l\'administrateur'; //die($message); } return $result; } //date function date_fr($date) { $date_en = substr($date,0,10); $aa = substr($date,0,4); $mm = substr($date,5,2); $jj = substr($date,8,2); $date_fr = $jj."-".$mm."-".$aa; return $date_fr; } function date_en($date) { $date_fr = substr($date,0,10); $aa = substr($date,6,4); $mm = substr($date,3,2); $jj = substr($date,0,2); $date_en = $aa."-".$mm."-".$jj; return $date_en; } function date_fr_2($date) { $date_en = substr($date,0,10); $jj = substr($date,8,2); $mm = substr($date,5,2); $aa = substr($date,0,4); //mois en lettre switch ($mm) { case "01": $mm = "Jan"; break; case "02": $mm = "Feb"; break; case "03": $mm = "Mar"; break; case "04": $mm = "Apr"; break; case "05": $mm = "May"; break; case "06": $mm = "Jun"; break; case "07": $mm = "Jul"; break; case "08": $mm = "Aug"; break; case "09": $mm = "Sept"; break; case "10": $mm = "Oct"; break; case "11": $mm = "Nov"; break; case "12": $mm = "Dec"; break; } //////////////// $date_fr = $jj."-".$mm."-".$aa; return $date_fr; } //table nationalite function insert_nationality($design,$country) { $strSQL = 'INSERT INTO `enationalite` ( `nat_design`, `nat_country` ) '; $strSQL .= 'VALUES ("'.$design.'", "'.$country.'") '; $resultat = requete_SQL($strSQL); return $resultat; } function update_nationality($id,$design,$country) { $strSQL = 'UPDATE `enationalite` SET `nat_design` = "'.$design.'", `nat_country` = "'.$country.'" WHERE CONVERT( `nat_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_nationality($id) { $strSQL = 'DELETE FROM `enationalite` WHERE CONVERT( `nat_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_nationality($id) { $strSQL = 'SELECT `nat_statut` FROM `enationalite` WHERE `nat_id` = '.$id.' '; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); if ($table_result['nat_statut'] == 1) { $strSQL = 'UPDATE `enationalite` SET `nat_statut` = 0 WHERE CONVERT( `nat_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); } else { $strSQL = 'UPDATE `enationalite` SET `nat_statut` = 1 WHERE CONVERT( `nat_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); } return $resultat; } function numberof_nationality($keyword) { $strSQL = 'SELECT * FROM `enationalite` WHERE `nat_design` LIKE "%'.$keyword.'%" ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_nationality($keyword) { $strSQL = 'SELECT * FROM `enationalite` WHERE `nat_design` LIKE "%'.$keyword.'%" ORDER BY `nat_design` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['nat_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" class="sab"height="30" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="6%" align="center">'.$rg.'</td> <td width="48%" align="left" class="'.$important.'">'.$table_result['nat_design'].'</td> <td width="34%" align="left">'.$table_result['nat_country'].'</td> <td width="12%" align="center"> <a href="#"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; <a href="./gestion_nationnalite.php?nat_del='.$table_result['nat_id'].'" onclick="return(confirm(\'Voulez-vous supprimer cette nationalité : '.$table_result['nat_design'].' ?\'));"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; </td> </tr> </table>'; } } return $retour; } function show_nationality($id) { $strSQL = 'SELECT * FROM `enationalite` WHERE CONVERT( `nat_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function select_nationality($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $nationality = show_nationality($id); $design = $nationality['nat_design']; } else $design = ''; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; $strSQL = 'SELECT `nat_id`, `nat_design` FROM `enationalite` WHERE `nat_statut` = 1 AND `nat_id` <> "'.$id.'" ORDER BY `nat_design`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['nat_id'].'">'.$table_result['nat_design'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } //table companie function insert_company($nom,$contact,$mail,$tel) { $strSQL = 'INSERT INTO `ecompanie` ( `comp_nom`, `comp_contact`, `comp_contact_email`, `comp_contact_tel` ) '; $strSQL .= 'VALUES ("'.$nom.'", "'.$contact.'", "'.$mail.'", "'.$tel.'") '; $resultat = requete_SQL($strSQL); return $resultat; } function update_company($id,$nom,$contact,$mail,$tel) { $strSQL = 'UPDATE `ecompanie` SET `comp_nom` = "'.$nom.'", `comp_contact` = "'.$contact.'", `comp_contact_email` = "'.$mail.'", `comp_contact_tel` = "'.$tel.'" WHERE CONVERT( `comp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_company($id) { $strSQL = 'DELETE FROM `ecompanie` WHERE CONVERT( `comp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_company($id) { $strSQL = 'SELECT `comp_statut` FROM `ecompanie` WHERE `comp_id` = '.$id.' '; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); if ($table_result['comp_statut'] == 1) { $strSQL = 'UPDATE `ecompanie` SET `comp_statut` = 0 WHERE CONVERT( `comp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); } else { $strSQL = 'UPDATE `ecompanie` SET `comp_statut` = 1 WHERE CONVERT( `comp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); } return $resultat; } function numberof_company($keyword) { $strSQL = 'SELECT * FROM `ecompanie` WHERE `comp_nom` LIKE "%'.$keyword.'%" ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_company($keyword) { $strSQL = 'SELECT * FROM `ecompanie` WHERE `comp_nom` LIKE "%'.$keyword.'%" ORDER BY `comp_nom` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['comp_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" class="sab" height="30" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="6%" align="center">'.$rg.'</td> <td width="48%" align="left" class="'.$important.'">'.$table_result['comp_nom'].'</td> <td width="34%" align="left">'.$table_result['comp_contact'].'</td> <td width="12%" align="center"> <a href="#"><img src="../image/icon/button_accept.png" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; <a href="#"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; <a href="#" onclick="return(confirm(\'Voulez-vous supprimer cette company : '.$table_result['comp_name'].' ?\'));"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; </td> </tr> </table>'; } } return $retour; } function show_company($id) { $strSQL = 'SELECT * FROM `ecompanie` WHERE CONVERT( `comp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function select_company($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $company = show_company($id); $design = $company['comp_nom']; } else $design = 'Tous les Companies'; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; if ($sub==1 && !empty($id)) $select_retour .= '<option value="">Tous les Companies</option>'; $strSQL = 'SELECT `comp_id`, `comp_nom` FROM `ecompanie` WHERE `comp_statut` = 1 AND `comp_id` <> "'.$id.'" ORDER BY `comp_nom`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['comp_id'].'">'.$table_result['comp_nom'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } //table employee function insert_employee($firstname,$lastname,$title,$designation,$email,$tel,$nationality/*,$company*/,$group,$pass_num,$pass_file) { $strSQL = 'INSERT INTO `eemploye` ( `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `nat_id`, `emp_groupe`, `emp_num_pass`, `emp_attach_pass` ) '; $strSQL .= 'VALUES ("'.$lastname.'", "'.$firstname.'", "'.$title.'", "'.$designation.'", "'.$email.'", "'.$tel.'", '.$nationality.', "'.$group.'", "'.$pass_num.'", "'.$pass_file.'") '; $resultat = requete_SQL($strSQL); return $resultat; } function show_employee($id) { $strSQL = 'SELECT `emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, E.`nat_id`, `nat_design`, `emp_num_pass`, `emp_attach_pass`, `emp_groupe`, `emp_statut` FROM `eemploye` E, `enationalite` N WHERE (E.`nat_id` = N.`nat_id`) AND CONVERT( `emp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL) ; $table_result = mysql_fetch_array($resultat)or die ("ssssssssssssssssssss".mysql_error()); return $table_result; } function update_employee($id,$firstname,$lastname,$title,$designation,$email,$tel,$nationality/*,$company*/,$group,$pass_num,$pass_file) { //echo $group; $strSQL = 'UPDATE `eemploye` SET `emp_nom` = "'.$lastname.'", `emp_prenom` = "'.$firstname.'", `emp_titre` = "'.$title.'", `emp_designation` = "'.$designation.'", `emp_email` = "'.$email.'", `emp_tel` = "'.$tel.'", `nat_id` = "'.$nationality.'",`emp_groupe` = "'.$group.'", `emp_num_pass` = "'.$pass_num.'", `emp_attach_pass` = "'.$pass_file.'" WHERE CONVERT( `emp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_employee($id) { $strSQL = 'DELETE FROM `eemploye` WHERE CONVERT( `emp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_employee($id) { $show_employee = show_employee($id); if ($show_employee['emp_statut'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `eemploye` SET `emp_statut` = '.$set_statut.' WHERE CONVERT( `emp_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function numberof_employee($keyword) { $strSQL = 'SELECT `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `nat_design`, `comp_nom` FROM `eemployee` E, `enationality` N, `ecompany` C WHERE (`emp_nom` LIKE "%'.$keyword.'%" OR `emp_prenom` LIKE "%'.$keyword.'%") AND (E.`nat_id` = N.`nat_id`) AND (E.`comp_id` = C.`comp_id`) ORDER BY `emp_nom`, `emp_prenom` ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_employee($keyword,$edit=0,$del=0) { //if (!empty($company)) $comp_condition = 'AND E.`comp_id` = '.$company.' '; else $comp_condition = ''; $strSQL = 'SELECT `emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `nat_design`, `emp_statut` FROM `eemploye` E, `enationalite` N WHERE (`emp_nom` LIKE "%'.$keyword.'%" OR `emp_prenom` LIKE "%'.$keyword.'%") AND (E.`nat_id` = N.`nat_id`) ORDER BY `emp_nom`, `emp_prenom` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['emp_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%"class="sab" height="30" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr ondblclick="window.open(\'./employee_information.php?emp_info='.$table_result['emp_id'].'\',\'Info\',\'width=800,height=580,scrollbars=1\').focus();"> <td width="6%" align="center">'.$rg.'</td> <td width="45%" align="left" class="'.$important.'"><span class="txt_4">, '.$table_result['emp_titre'].'</span> '.$table_result['emp_nom'].' '.$table_result['emp_prenom'].' </td> <td width="34%" align="left"></td> <td width="15%" align="center">'; if ($edit==1) $retour .= ' <a href="./?page_id=employee&show=add&emp_edit='.$table_result['emp_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; if ($del==1) $retour .= ' <a href="./?page_id=employee&show=list&emp_del='.$table_result['emp_id'].'"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; $retour .= ' <a href=" ./employee_information.php?emp_info='.$table_result['emp_id'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkdfkdclick"window.open(\'./employee_information.php?emp_info='.$table_result['emp_id'].'\',\'Info\',\'width=800,height=480,scrollbars=0\').focus();"> <img src="../image/icon/info.png" alt="Detail" width="22" height="22" align="absmiddle" border="0" /> </a> </td> </tr> </table>'; } } return $retour; } function list_employee_2($keyword) { //if (!empty($company)) $comp_condition = 'AND E.`comp_id` = '.$company.' '; else $comp_condition = ''; $strSQL = 'SELECT `emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `nat_design`, `emp_statut` FROM `eemploye` E, `enationalite` N WHERE (`emp_nom` LIKE "%'.$keyword.'%" OR `emp_prenom` LIKE "%'.$keyword.'%") AND (E.`nat_id` = N.`nat_id`) AND (E.`emp_statut` = 1) ORDER BY `emp_nom`, `emp_prenom` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['emp_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="100%" class="sab" height="30" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="6%" align="center">'.$rg.'</td> <td width="36%" align="left" class="'.$important.'"> <a href="./employee_list.php?show=list&emp_id='.$table_result['emp_id'].'&emp_name='.$table_result['emp_nom'].' '.$table_result['emp_prenom'].'&emp_design='.$table_result['emp_designation'].'"> <span class="txt_4">, '.$table_result['emp_titre'].'</span>'.$table_result['emp_nom'].' '.$table_result['emp_prenom'].' </a> </td> <td width="32%" align="left">'.$table_result['emp_designation'].' </td> <td width="26%" align="left"></td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table>'; } } return $retour; } function select_employee($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $nationality = show_nationality($id); $design = $nationality['nat_design']; } else $design = ''; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; $strSQL = 'SELECT `nat_id`, `nat_design` FROM `enationalite` WHERE `nat_statut` = 1 AND `nat_id` <> "'.$id.'" ORDER BY `nat_design`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['nat_id'].'">'.$table_result['nat_design'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } //table user function id_utilisateur($nom,$motdepasse) { $strSQL2 = 'SELECT * FROM `eutilisateur` WHERE `util_statut` = 1 AND `util_id` = "'.$nom.'" AND `util_pwd` = "'.$<PASSWORD>.'" ;'; $resultat2 = requete_SQL($strSQL2); $retour = mysql_num_rows($resultat2); return $retour; } function insert_user($employee,$login,$password,$group) { $strSQL = 'INSERT INTO `eutilisateur` ( `emp_id`, `util_id`, `util_pwd`, `dom_id` ) '; $strSQL .= 'VALUES (\''.$employee.'\', \''.$login.'\', \''.$password.'\', \''.$group.'\' ) '; $resultat = requete_SQL($strSQL); return $resultat; } function show_user($id) { $strSQL = 'SELECT U.`emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `util_id`, `util_pwd`, `util_statut`, U.`dom_id`, `dom_nom`, `dom_autorisation`, `dom_niveau` FROM `eemploye` E, `eutilisateur` U, `edomaine` D WHERE (U.`emp_id` = E.`emp_id`) AND (U.`dom_id` = D.`dom_id`) AND CONVERT( `util_id` USING utf8 ) = \''.$id.'\' ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function update_user($id,$employee,$login,$password,$group) { $strSQL = 'UPDATE `eutilisateur` SET `emp_id` = \''.$employee.'\', `util_id` = \''.$login.'\', `util_pwd` = \''.$password.'\', `dom_id` = \''.$group.'\' WHERE CONVERT( `util_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_user($id) { $strSQL = 'DELETE FROM `eutilisateur` WHERE CONVERT( `util_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_user($id) { $show_user = show_user($id); if ($show_user['util_statut'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `eutilisateur` SET `util_statut` = '.$set_statut.' WHERE CONVERT( `util_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function numberof_user($keyword) { $strSQL = 'SELECT `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `nat_design`, `comp_nom` FROM `eemployee` E, `enationality` N, `ecompany` C WHERE (`emp_nom` LIKE "%'.$keyword.'%" OR `emp_prenom` LIKE "%'.$keyword.'%") AND (E.`nat_id` = N.`nat_id`) AND (E.`comp_id` = C.`comp_id`) ORDER BY `emp_nom`, `emp_prenom` ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_user($keyword,$group='',$edit=0,$del=0) { if (!empty($group)) $comp_condition = 'AND U.`dom_id` = '.$group.' '; else $comp_condition = ''; if (!empty($keyword)) $key_condition = 'AND (`emp_nom` LIKE \'%'.$keyword.'%\' OR `emp_prenom` LIKE \'%'.$keyword.'%\' OR `util_id` LIKE \'%'.$keyword.'%\') '; else $key_condition = ''; $strSQL = 'SELECT U.`emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `util_id`, `util_pwd`, `util_statut`, U.`dom_id`, `dom_nom`, `dom_autorisation`, `dom_niveau` FROM `eemploye` E, `eutilisateur` U, `edomaine` D WHERE (U.`emp_id` = E.`emp_id`) AND (U.`dom_id` = D.`dom_id`) '.$comp_condition.' '.$key_condition.' ORDER BY `util_id` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['util_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="100%" height="30" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr ondblclick="window.open(\'./user_information.php?user_info='.$table_result['util_id'].'\',\'List\',\'width=800,height=580,scrollbars=1\').focus();"> <td width="4%" align="center">'.$rg.'</td> <td width="22%" align="left" class="'.$important.'">'.$table_result['util_id'].' </td> <td width="40%" align="left">'.$table_result['emp_nom'].' '.$table_result['emp_prenom'].'</td> <td width="23%" align="left">'.$table_result['dom_nom'].'</td> <td width="11%" align="center">'; if ($edit==1) $retour .= ' <a href="./?page_id=user&show=add&user_edit='.$table_result['util_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; if ($del==1) $retour .= ' <a href="./?page_id=user&show=list&user_del='.$table_result['util_id'].'"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; $retour .= ' <a href="./user_information.php?user_info='.$table_result['util_id'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkjkclick="window.open(\'./user_information.php?user_info='.$table_result['util_id'].'&KeepThis=true&TB_iframe=true&height=400&width=650\',\'Info\',\'width=800,height=380,scrollbars=0\').focus();"> <img src="../image/icon/info.png" alt="Detail" width="22" height="22" align="absmiddle" border="0" /> </a> </td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table>'; } } return $retour; } function list_user_of_domain($group='') { if (!empty($group)) $comp_condition = 'AND U.`dom_id` = '.$group.' '; else $comp_condition = ''; $strSQL = 'SELECT U.`emp_id`, `emp_nom`, `emp_prenom`, `emp_titre`, `emp_designation`, `emp_email`, `emp_tel`, `util_id`, `util_pwd`, `util_statut`, U.`dom_id`, `dom_nom`, `dom_autorisation`, `dom_niveau` FROM `eemploye` E, `eutilisateur` U, `edomaine` D WHERE (U.`emp_id` = E.`emp_id`) AND (U.`dom_id` = D.`dom_id`) '.$comp_condition.' ORDER BY `util_id` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['util_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="100%" height="28" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_4"> <tr> <td width="4%" align="center">-</td> <td width="96%" align="left"><span class="'.$important.'">'.$table_result['util_id'].'</span> <span class="txt_1">('.$table_result['emp_prenom'].' '.$table_result['emp_nom'].') </span> </td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table>'; } } return $retour; } function show_domaine($id) { $strSQL = 'SELECT * FROM `edomaine` WHERE CONVERT( `dom_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function select_domaine($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $show_domaine = show_domaine($id); $design = $show_domaine['dom_nom']; } else $design = 'Tous les Groupes'; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; if ($sub==1 && !empty($id)) $select_retour .= '<option value="">Tous les Groupes</option>'; $strSQL = 'SELECT `dom_id`, `dom_nom` FROM `edomaine` WHERE `dom_statut` = 1 AND `dom_id` <> "'.$id.'" ORDER BY `dom_nom`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['dom_id'].'">'.$table_result['dom_nom'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } function insert_group($name,$description,$status,$authorization) { $strSQL = 'INSERT INTO `edomaine` ( `dom_nom`, `dom_description`, `dom_statut`, `dom_autorisation` ) '; $strSQL .= 'VALUES (\''.$name.'\', \''.$description.'\', \''.$status.'\', \''.$authorization.'\' ) '; $resultat = requete_SQL($strSQL); return $resultat; } function update_group($id,$name,$description,$status,$authorization) { $strSQL = 'UPDATE `edomaine` SET `dom_nom` = \''.$name.'\', `dom_description` = \''.$description.'\', `dom_statut` = \''.$status.'\', `dom_autorisation` = \''.$authorization.'\' WHERE CONVERT( `dom_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_group($id) { $strSQL = 'DELETE FROM `edomaine` WHERE CONVERT( `dom_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_group($id) { $show_domaine = show_domaine($id); if ($show_domaine['dom_statut'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `edomaine` SET `dom_statut` = '.$set_statut.' WHERE CONVERT( `dom_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function list_group($keyword='',$edit=0,$del=0) { $strSQL = 'SELECT * FROM `edomaine` WHERE (`dom_nom` LIKE \'%'.$keyword.'%\' OR `dom_description` LIKE \'%'.$keyword.'%\') ORDER BY `dom_nom` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['dom_statut'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="100%" height="30" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="4%" align="center"> <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"><tr><td> <div id="img_'.$table_result['dom_id'].'" style="background:url(../image/icon/treeview_p.png)" onclick="javascript:change_icone(\'a_'.$table_result['dom_id'].'\',\'img_'.$table_result['dom_id'].'\');visibilite(\'a_'.$table_result['dom_id'].'\');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div> </td></tr></table> </td> <td width="22%" align="left" class="'.$important.'">'.$table_result['dom_nom'].' </td> <td align="left">'.$table_result['dom_description'].' </td> <td width="11%" align="center">'; if ($edit==1) $retour .= ' <a href="./?page_id=group&show=add&group_edit='.$table_result['dom_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; if ($del==1) $retour .= ' <a href="./?page_id=group&show=list&group_del='.$table_result['dom_id'].'"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; $retour .= ' </td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table>'; $retour .= '<div id="a_'.$table_result['dom_id'].'" style="display:none">'.list_user_of_domain($table_result['dom_id']).'</div>'; } } return $retour; } //typedoc function show_typdoc($id) { $strSQL = 'SELECT * FROM `etypdoc` WHERE CONVERT( `typdoc_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function insert_typdoc($nom,$descript,$statut) { $strSQL = 'INSERT INTO `etypdoc` ( `typdoc_title`, `typdoc_descript`, `typdoc_status` ) '; $strSQL .= 'VALUES ("'.$nom.'", "'.$descript.'", "'.$statut.'") '; $resultat = requete_SQL($strSQL); return $resultat; } function update_typdoc($id,$nom,$descript,$statut) { $strSQL = 'UPDATE `etypdoc` SET `typdoc_title` = "'.$nom.'", `typdoc_descript` = "'.$descript.'", `typdoc_status` = "'.$statut.'" WHERE CONVERT( `typdoc_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_typdoc($id) { $strSQL = 'DELETE FROM `etypdoc` WHERE CONVERT( `typdoc_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_typdoc($id) { $show_typdoc = show_typdoc($id); if ($show_typdoc['typdoc_status'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `etypdoc` SET `typdoc_status` = '.$set_statut.' WHERE CONVERT( `typdoc_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function numberof_typdoc($keyword) { $strSQL = 'SELECT * FROM `etypdoc` WHERE `typdoc_title` LIKE "%'.$keyword.'%" ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_typdoc($keyword) { $strSQL = 'SELECT * FROM `etypdoc` WHERE `typdoc_title` LIKE "%'.$keyword.'%" ORDER BY `typdoc_title` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['typdoc_status'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" height="30" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="4%" align="center">'.$rg.'</td> <td width="28%" align="left" class="'.$important.'">'.$table_result['typdoc_title'].'</td> <td width="56%" align="left">'.$table_result['typdoc_descript'].'</td> <td width="12%" align="center"> <a href="gestion_doctype.php?show=add&typdoc_edit='.$table_result['typdoc_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; <a href="gestion_doctype.php?show=lis&typdoc_del='.$table_result['typdoc_id'].'" onclick="return(confirm(\'Voulez-vous supprimer ce type de document : '.$table_result['typdoc_title'].' ?\'));"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; </td> </tr> </table>'; } } return $retour; } function select_typedoc($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $typdoc = show_typdoc($id); $design = $typdoc['typdoc_title']; } else $design = 'Tous les Types'; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; if ($sub==1 && !empty($id)) $select_retour .= '<option value="">Tous les Types</option>'; $strSQL = 'SELECT `typdoc_id`, `typdoc_title` FROM `etypdoc` WHERE `typdoc_status` = 1 AND `typdoc_id` <> "'.$id.'" ORDER BY `typdoc_title`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['typdoc_id'].'">'.$table_result['typdoc_title'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } //Dossier function show_folder($id) { $strSQL = 'SELECT * FROM `efolder` WHERE CONVERT( `folder_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function insert_folder($nom,$descript,$statut) { $strSQL = 'INSERT INTO `efolder` ( `folder_name`, `folder_descript`, `folder_status` ) '; $strSQL .= 'VALUES ("'.$nom.'", "'.$descript.'", "'.$statut.'") '; $resultat = requete_SQL($strSQL); return $resultat; } function update_folder($id,$nom,$descript,$statut) { $strSQL = 'UPDATE `efolder` SET `folder_name` = "'.$nom.'", `folder_descript` = "'.$descript.'", `folder_status` = "'.$statut.'" WHERE CONVERT( `folder_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_folder($id) { $strSQL = 'DELETE FROM `efolder` WHERE CONVERT( `folder_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_folder($id) { $show_folder = show_folder($id); if ($show_folder['folder_status'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `efolder` SET `folder_status` = '.$set_statut.' WHERE CONVERT( `folder_id` USING utf8 ) = '.$id.' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function numberof_folder($keyword) { $strSQL = 'SELECT * FROM `efolder` WHERE `comp_nom` LIKE "%'.$keyword.'%" ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour ; } function list_folder($keyword) { $strSQL = 'SELECT * FROM `efolder` WHERE `folder_name` LIKE "%'.$keyword.'%" ORDER BY `folder_name` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['folder_status'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" height="30" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td width="4%" align="center">'.$rg.'</td> <td width="28%" align="left" class="'.$important.'">'.$table_result['folder_name'].'</td> <td width="56%" align="left">'.$table_result['folder_descript'].'</td> <td width="12%" align="center"> <a href="gestion_dossier.php?show=add&folder_edit='.$table_result['folder_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; <a href="gestion_dossier.php?show=lis&folder_del='.$table_result['folder_id'].'" onclick="return(confirm(\'Voulez-vous supprimer ce Dossier : '.$table_result['folder_name'].' ?\'));"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" border="0" align="absmiddle" /></a>&nbsp; </td> </tr> </table>'; } } return $retour; } function select_folder($name,$id='',$sub=0, $class='line_4') { if ($sub==1) $onchange = 'onchange="javascript:submit();"'; else $onchange = ''; if (!empty($id)) { $folder = show_folder($id); $design = $folder['folder_name']; } else $design = 'Tous les Dossiers'; $select_retour = '<select name="'.$name.'" class="'.$class.'" id="'.$name.'" '.$onchange.' >'; $select_retour .= '<option value="'.$id.'" selected="selected">'.$design.'</option>'; if ($sub==1 && !empty($id)) $select_retour .= '<option value="">Tous les Folder</option>'; $strSQL = 'SELECT `folder_id`, `folder_name` FROM `efolder` WHERE `folder_status` = 1 AND `folder_id` <> "'.$id.'" ORDER BY `folder_name`'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $select_retour .= ''; } else { while ($table_result = mysql_fetch_array($resultat)) { $select_retour .= '<option value="'.$table_result['folder_id'].'">'.$table_result['folder_name'].'</option>'; } } $select_retour .= '</select>'; return $select_retour; } //document function insert_document($id,$title,$detail=NULL,$keyword=NULL,$owner=NULL,$preparedby=NULL,$reviewedby=NULL,$approvedby=NULL,$creat_date=NULL,$sign_date=NULL,$nbr_page=NULL,$status=1,$typdoc=NULL) { $strSQL = 'INSERT INTO `edocument` (`doc_id`, `doc_title`, `doc_detail`, `doc_keyword`, `doc_owner`, `doc_prepared_by`, `doc_reviewed_by`, `doc_approved_by`, `doc_creat_date`, `doc_sign_date`, `doc_nbr_page`, `doc_status`, `typdoc_id`) VALUES (\''.$id.'\', \''.$title.'\', \''.$detail.'\', \''.$keyword.'\', \''.$owner.'\', \''.$preparedby.'\', \''.$reviewedby.'\', \''.$approvedby.'\', \''.$creat_date.'\', \''.$sign_date.'\', \''.$nbr_page.'\', \''.$status.'\', \''.$typdoc.'\');'; $resultat = requete_SQL($strSQL); return $resultat; } function show_document($id) { $strSQL = 'SELECT `doc_id`, `doc_title`, `doc_detail`, `doc_owner`, `doc_prepared_by`, `doc_reviewed_by`, `doc_approved_by`, `doc_creat_date`, `doc_sign_date`, `doc_nbr_page`, `doc_status`, `typdoc_title`, D.`typdoc_id` FROM `edocument` D, `etypdoc` T WHERE (D.`typdoc_id` = T.`typdoc_id`) AND CONVERT( `doc_id` USING utf8 ) = "'.$id.'" LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $table_result = mysql_fetch_array($resultat); return $table_result; } function update_document($id,$title,$detail,$keyword,$owner,$preparedby,$reviewedby,$approvedby,$creat_date,$sign_date,$nbr_page,$status,$typdoc) { $strSQL = 'UPDATE `edocument` SET `doc_title` = \''.$title.'\', `doc_detail` = \''.$detail.'\', `doc_keyword` = \''.$keyword.'\', `doc_owner` = \''.$owner.'\', `doc_prepared_by` = \''.$preparedby.'\', `doc_reviewed_by` = \''.$reviewedby.'\', `doc_approved_by` = \''.$approvedby.'\', `doc_creat_date` = \''.$creat_date.'\', `doc_sign_date` = \''.$sign_date.'\', `doc_nbr_page` = \''.$nbr_page.'\', `doc_status` = \''.$status.'\', `typdoc_id` = \''.$typdoc.'\' WHERE CONVERT( `doc_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function delete_document($id) { $strSQL = 'DELETE FROM `edocument` WHERE CONVERT( `doc_id` USING utf8 ) = "'.$id.'" LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function desable_document($id) { $show_document = show_document($id); if ($show_document['doc_status'] == 1) $set_statut = 0; else $set_statut = 1; $strSQL = 'UPDATE `edocument` SET `doc_status` = '.$set_statut.' WHERE CONVERT( `doc_id` USING utf8 ) = "'.$id.'" LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function numberof_document($keyword,$document='') { if (!empty($document)) $doc_condition = 'AND E.`typdoc_id` = '.$document.' '; else $doc_condition = ''; $strSQL = 'SELECT `doc_id`, `doc_title`, `doc_detail`, `doc_creat_date`, `doc_sign_date`, `doc_status`, `typdoc_title` FROM `edoc` D, `etypdoc` T WHERE (`doc_title` LIKE "%'.$keyword.'%" OR `doc_detail` LIKE "%'.$keyword.'%") AND (D.`typdoc_id` = T.`typdoc_id`) '.$doc_condition.' ORDER BY `doc_creat_date` ;'; $resultat = requete_SQL($strSQL); $retour = mysql_num_rows($resultat); return $retour; } function list_document($keyword,$typdoc='',$edit=0,$del=0) { if (!empty($typdoc)) $doc_condition = 'AND D.`typdoc_id` = '.$typdoc.' '; else $doc_condition = ''; $strSQL = 'SELECT D.`doc_id`, `doc_title`, `doc_detail`, `doc_creat_date`, `doc_sign_date`, `doc_status`, `typdoc_title` FROM `edocument` D, `etypdoc` T WHERE (`doc_title` LIKE "%'.$keyword.'%" OR `doc_detail` LIKE "%'.$keyword.'%") AND (D.`typdoc_id` = T.`typdoc_id`) '.$doc_condition.' ORDER BY `doc_creat_date` DESC ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['doc_status'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" height="40"class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr ondblclick="window.open(\'./document_information.php?doc_info='.$table_result['doc_id'].'\',\'Info\',\'width=800,height=380,scrollbars=0\').focus();"> <td width="4%" align="center">'.$rg.'</td> <td width="44%" align="left" class="'.$important.'">'.$table_result['doc_title'].' <br /><span class="txt_4">'.$table_result['doc_detail'].'</span></td> <td width="16%" align="left">'.date_fr_2($table_result['doc_creat_date']).'</td> <td width="24%" align="left">'.$table_result['typdoc_title'].'</td> <td width="10%" align="center">'; if ($edit==1) $retour .= ' <a href="./?page_id=document&show=add&doc_edit='.$table_result['doc_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; if ($del==1) $retour .= ' <a href="./?page_id=document&show=list&doc_del='.$table_result['doc_id'].'"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; $retour .= ' <a href=" ./document_information.php?doc_info='.$table_result['doc_id'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkdfkdclick"window.open(\'./document_information.php?doc_info='.$table_result['doc_id'].'\',\'Info\',\'width=800,height=380,scrollbars=0\').focus();"> <img src="../image/icon/info.png" alt="Detail" width="22" height="22" align="absmiddle" border="0" /> </a>'; $retour .= ' </td> </tr> </table>'; } } return $retour; } function nbr_document_folder($id) { $strSQL = 'SELECT `folder_id` FROM `adocumentfolder` WHERE CONVERT( `doc_id` USING utf8 ) = \''.$id.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); $nbr = mysql_num_rows($resultat); return $nbr; } function insert_document_folder($id_doc,$id_folder,$precision=NULL,$file_attached=NULL) { $strSQL = 'INSERT INTO `adocumentfolder` (`doc_id`, `folder_id`, `precision`, `file_attached`) VALUES (\''.$id_doc.'\', \''.$id_folder.'\', \''.$precision.'\', \''.$file_attached.'\');'; $resultat = requete_SQL($strSQL); return $resultat; } function update_document_folder($hid_doc,$hid_folder,$id_doc,$id_folder,$precision=NULL,$file_attached=NULL) { if (!empty($file_attached)) $edit_file = ', `file_attached` = \''.$file_attached.'\''; else $edit_file = ''; $strSQL = 'UPDATE `adocumentfolder` SET `doc_id` = \''.$id_doc.'\', `folder_id` = \''.$id_folder.'\', `precision` = \''.$precision.'\' '.$edit_file.' WHERE CONVERT( `doc_id` USING utf8 ) = \''.$hid_doc.'\' AND CONVERT( `folder_id` USING utf8 ) = \''.$hid_folder.'\' LIMIT 1 ;'; $resultat = requete_SQL($strSQL); return $resultat; } function show_document_folder($id) { $strSQL = 'SELECT D.`doc_id`, D.`folder_id`, `folder_name`, `precision`, `file_attached` FROM `adocumentfolder` D, `efolder` F WHERE (D.`folder_id` = F.`folder_id`) AND CONVERT( D.`doc_id` USING utf8 ) = "'.$id.'" ORDER BY `precision` ;'; $resultat = requete_SQL($strSQL); $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $retour .= ' <table width="100%" class="sab" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="txt_4">Nom du Dossier </td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span>'.$table_result['folder_name'].'</td> <td width="20%" align="left" class="txt_4">Fichier Attaché</td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span>'; if (!empty($table_result['file_attached'])) $retour .= ' <a href="#" onclick="window.open(\'../fichiers/document/'.$table_result['file_attached'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a> ('.$table_result['precision'].')'; $retour .= ' </td> </tr> </table>'; /* <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="txt_1g">'.$table_result['folder_name'].'</td> <td width="80%" align="left" class="txt_1">'; if (!empty($table_result['file_attached'])) $retour .= ' <a href=" ../fichiers/document/'.$table_result['file_attached'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkdfkdclick" window.open(\'../file/document/'.$table_result['file_attached'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a> ('.$table_result['precision'].')'; $retour .= ' </td> </tr> </table> */ } return $retour; } function show_document_folder_edit($id) { $strSQL = 'SELECT D.`doc_id`, D.`folder_id`, `folder_name`, `precision`, `file_attached` FROM `adocumentfolder` D, `efolder` F WHERE (D.`folder_id` = F.`folder_id`) AND CONVERT( D.`doc_id` USING utf8 ) = "'.$id.'" ORDER BY `precision` ;'; $resultat = requete_SQL($strSQL); $retour = ' <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table>'; $rg = 0; while ($table_result = mysql_fetch_array($resultat)) { $rg++; $retour .= ' <table width="100%" class="sab" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td height="31" align="left" class="txt_1">Folder </td> <td align="left"> <label>'.select_folder($name='select_folder'.$rg,$table_result['folder_id'],$sub=0, 'line_4').'</label> <input name="htxt_folder'.$rg.'" type="hidden" id="htxt_folder'.$rg.'" size="45" value="'.$table_result['folder_id'].'"/> </td> </tr> <tr> <td height="31" align="left" class="txt_1">Detail</td> <td align="left"> <label> <input name="htxt_precision'.$rg.'" type="hidden" id="htxt_precision'.$rg.'" size="45" value="'.$table_result['precision'].'"/> </label> <input name="txt_precision'.$rg.'" type="text" id="txt_precision'.$rg.'" size="45" value="'.$table_result['precision'].'"/> </td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Fichier Attach&eacute; </td> <td width="86%" align="left"><label>'; if (!empty($table_result['file_attached'])) $retour .= '<a href=" ../fichiers/document/'.$table_result['file_attached'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkdfkdclick" window.open(\'../fichiers/document/'.$table_result['file_attached'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Afficher le fichier" width="22" height="22" align="absmiddle" border="0"/></a> -- Update &gt;&gt;'; $retour .= ' <input name="fichier'.$rg.'" type="file" class="line_4" id="fichier'.$rg.'" size="50"/> </label> </td> </tr> </table>'; } $retour .= ' <input name="txt_nbr_folder" type="hidden" id="txt_nbr_folder" size="10" value="'.$rg.'"/>'; return $retour; } function list_folder_docs($keyword) { $strSQL = 'SELECT * FROM `efolder` WHERE `folder_name` LIKE "%'.$keyword.'%" ORDER BY `folder_name` ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['folder_status'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" class="sab" height="30" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr ondblclick="window.open(\'./folder_documents.php?folder_id='.$table_result['folder_id'].'\',\'Info\',\'width=920,height=710,scrollbars=1\').focus();"> <td width="4%" align="center">'.$rg.'</td> <td width="28%" align="left" class="'.$important.'">'.$table_result['folder_name'].'</td> <td width="56%" align="left">'.$table_result['folder_descript'].'</td> <td width="12%" align="center">'; $retour .= ' <a href=" ./folder_documents.php?folder_id='.$table_result['folder_id'].'&KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkdfkdclick"window.open(\'./folder_documents.php?folder_id='.$table_result['folder_id'].'\',\'Info\',\'width=920,height=710,scrollbars=1\').focus();"> <img src="../image/icon/folder_open.png" alt="Open folder" width="22" height="22" align="absmiddle" border="0" /> </a>'; $retour .= ' </td> </tr> </table>'; } } return $retour; } function list_documents_of_folder($keyword,$folder='',$edit=0,$del=0) { if (!empty($folder)) $folder_condition = 'AND (D.`doc_id` = F.`doc_id`) AND F.`folder_id` = '.$folder.' '; else $folder_condition = ''; $strSQL = 'SELECT D.`doc_id`, `doc_title`, `doc_detail`, `doc_creat_date`, `doc_sign_date`, `doc_status`, `typdoc_title` FROM `edocument` D, `etypdoc` T, `adocumentfolder` F WHERE (`doc_title` LIKE "%'.$keyword.'%" OR `doc_detail` LIKE "%'.$keyword.'%") AND (D.`typdoc_id` = T.`typdoc_id`) '.$folder_condition.' ORDER BY `doc_creat_date` DESC ;'; $resultat = requete_SQL($strSQL); if (mysql_num_rows($resultat) == 0) { $retour = '<span class="warning">Aucun enregistrement !</span>'; } else { $rg = 0; $retour = ''; while ($table_result = mysql_fetch_array($resultat)) { $rg ++; if ($table_result['doc_status'] == 1) { $important = 'important_2'; } else { $important = 'txt_4'; } $retour .= ' <table width="98%" class="sab" height="40" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr ondblclick="window.open(\'./folder_documents_details.php?doc_info='.$table_result['doc_id'].'&folder_id='.$folder.'\',\'Info\',\'width=800,height=580,scrollbars=1\').focus();"> <td width="4%" align="center">'.$rg.'</td> <td width="44%" align="left" class="'.$important.'">'.$table_result['doc_title'].' <br /><span class="txt_4">'.$table_result['doc_detail'].'</span></td> <td width="16%" align="left">'.date_fr_2($table_result['doc_creat_date']).'</td> <td width="24%" align="left">'.$table_result['typdoc_title'].'</td> <td width="10%" align="center">'; if ($edit==1) $retour .= ' <a href="./?page_id=document&show=add&doc_edit='.$table_result['doc_id'].'"><img src="../image/icon/color_line.png" alt="Edit" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; if ($del==1) $retour .= ' <a href="./?page_id=document&show=list&doc_del='.$table_result['doc_id'].'"><img src="../image/icon/cancel.png" alt="supprimer" width="22" height="22" align="absmiddle" border="0" /></a> &nbsp;'; $retour .= ' <a href="folder_documents_details.php?doc_info='.$table_result['doc_id'].'&folder_id='.$folder.'"> <img src="../image/icon/info.png" alt="Detail" width="22" height="22" align="absmiddle" border="0" /> </a>'; $retour .= ' </td> </tr> </table>'; } } return $retour; } ?> <file_sep><?php if(isset($_POST['CNE']) && !empty($_POST['CNE'])){ $CNE=$_POST['CNE']; mysql_pconnect("localhost","root","")or die (mysql_error()); mysql_select_db("reinscr")or die (mysql_error()); $acad=mysql_query("SELECT * FROM academie where CNE_etud_acad='".$CNE."'")or die (mysql_error()); $num=mysql_num_rows($acad); $requete=mysql_fetch_assoc($acad); if($num!=0) { $nom=$requete['Nom_etud_acad']; $prenom=$requete['prenom_etud_acad']; $CNE_etud=$requete['CNE_etud_acad']; $Filiere=$requete['filiere_bac_acad']; $Province=$requete['province']; $Date_nais=$requete['date_nais_etud']; } } if(isset($_POST['INSERER']) ){ $nom=$_Post['Nom_etud_acad']; $prenom=$_Post['prenom_etud_acad']; $CNE_etud=$_Post['CNE_etud_acad']; $Filiere=$_Post['filiere_bac_acad']; $Province=$_Post['province']; $Date_nais=$_Post['date_nais_etud']; $lieu=$_Post['lieu']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; $CIN=$_Post['CIN']; ?> <style> table.tablform{ font: bold 14px ubuntu; color:#696969; background-color:white; margin-left: 30px; } span.bismillah{ background-position: 8px 8px; /* LTR */ background-image: url(../../misc/message-24-ok.png); background-repeat: no-repeat; border: 0px solid; margin: 6px 0; padding: 10px 10px 10px 50px; /* LTR */ color:green; } span.bismillahe{ background-position: 8px 8px; /* LTR */ background-image: url(../../misc/message-24-error.png); background-repeat: no-repeat; border: 0px solid; margin: 6px 0; padding: 10px 10px 10px 50px; /* LTR */ color:red; } input.sssabir { cursor:pointer; background-color: #D14836; background-image: -webkit-linear-gradient(top,#DD4B39,#D14836); background-image: -moz-linear-gradient(top,#DD4B39,#D14836); background-image: -ms-linear-gradient(top,#DD4B39,#D14836); background-image: -o-linear-gradient(top,#DD4B39,#D14836); background-image: linear-gradient(top,#DD4B39,#D14836); border: 1px solid transparent; text-shadow: 0 1px rgba(0, 0, 0, 0.1); text-transform: uppercase; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding: 4px 20px ; color: #fff ; font: bold 1em "Trebuchet MS",Arial,sans-serif ; line-height: 1em ; text-align: center ; text-decoration: none ; } input.sssabir:hover, input.sssabir:focus, input.sssabir:active { background: #900 ; text-decoration: underline ; } </style> <script type="text/javascript" > function id_hh(CNE) { var sabiro; if (window.XMLHttpRequest) sabiro = new XMLHttpRequest(); else if (window.ActiveXObject) sabiro = new ActiveXObject('Microsoft.XMLHTTP'); sabiro.open('POST',"/sabir/id.php",true); sabiro.onreadystatechange = function() { if (sabiro.readyState == 4 && sabiro.status==200) { if (document.getElementById) { if (sabiro.responseText =='OK') { /* OK */ document.getElementById('CNE1').innerHTML='<span class="bismillah" > '+sabiro.responseText+' </span>'; }else{ /* PAS OK */ document.getElementById('CNE1').innerHTML='<span class="bismillahe" > '+sabiro.responseText+' </span>'; } } } } sabiro.setRequestHeader('Content-type','application/x-www-form-urlencoded'); sabiro.send('CNE='+CNE); } </script> <form method="post" action=""> <fieldset width="200"> <legend align="center"> Inscription </legend> <table class="tablform" border="0" width="200"cellspacing="0"> <tr align="center" style="background-color:#fff;"> <td colspan=2 id="msg"></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Vous êtes :</td> <td> <select name="etre" id="etre" onChange="javascript:submit();" > <option value="M"> Marocain </option> <option value="E"> Étrangère </option> <option selected="selected"> ------------------ </option> </select> </td> </tr> </table></fieldset> </form> <?php if (isset($_POST['etre']) && ($_POST['etre']=='M') && !isset($_POST['CNE'])){?> <!-- <form method="post" action="">--> <form name="forme"method="post" action=""> <fieldset width="200"> <legend align="center"> CNE </legend> <tr align="center" style="background-color:#fff;"> <td width="90">CNE :</td> <td> <input name="CNE" id="CNE" type="text" onBlur="id_hh(forme.CNE.value);" > <span id="CNE1" ></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td colspan="2" ><input class="sssabir" type="button" onClick="id_hh(forme.CNE.value);return false" value="Verifier" /></td> </tr> <tr align="center" style="background-color:#fff;"> <td colspan="2" ><input class="sssabir" type="submit" value="Envoyer" /></td> </tr> </table></fieldset> </form> <!-- <tr align="center" style="background-color:#fff;"> <td colspan="2" ><input class="sssabir" type="submit" value="envoyer" /></td> </tr> </form> --> <?php }?> <!-- *************************************** FORM2 ***********************---> <?php if ((isset($_POST['etre']) && $_POST['etre']=='E') || isset($_POST['CNE']) ){?> <form name="forme2"method="post" action="" enctype="multipart/form-data"> <fieldset width="200"> <legend align="center"> Informations personnelle </legend> <table class="tablform" border="0" width="200"cellspacing="0"> <tr align="center" style="background-color:#fff;"> <td width="90">Nom : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$nom.'" readonly="readonly"';?> name="nom" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Prenom : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$prenom.'" readonly="readonly"';?>name="prenom" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> CNE : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$CNE_etud.'" readonly="readonly"';?> name="cne" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Date de naissence : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$Date_nais.'" readonly="readonly"';?>name="date_nais" type="text" > </td> </tr> <?php if (isset($_POST['etre']) && $_POST['etre']=='M'){?> <tr align="center" style="background-color:#fff;"> <td> Province : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$Province.'" readonly="readonly"';?> name="province" type="text" > </td> </tr> <?php }?> <!--<tr id="CNE1"></tr>--> <tr align="center" style="background-color:#fff;"> <td width="90">CIN :</td> <td> <input name="CIN" id="CIN" type="text" onBlur="id_hh(forme.CIN1.value);" ></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Lieu de naissance :</td> <td> <input name="lieu" id="lieu" type="text" onBlur="id_hh(forme.lieu.value);" ><span id="lieu1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Adresse actuelle :</td> <td> <input name="adr1" id="adr1" type="text" onBlur="id_hh(forme.adr1.value);" ><span id="adr1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Ville :</td> <td> <input name="ville" id="ville" type="text" onBlur="id_hh(forme.ville.value);" ><span id="ville1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Pays :</td> <td> <input name="paye" id="paye" type="text" onBlur="id_hh(forme.paye.value);" ><span id="paye1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Nationalité :</td> <td> <input name="nat" id="adr1" type="nat" onBlur="id_hh(forme.nat.value);" ><span id="nat1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Sexe :</td> <td> <input name="sexe" id="sexe" type="radio" value="M" onBlur="id_hh(forme.sexe.value);" > Masculin <input name="sexe" id="sexe" type="radio" value="F" onBlur="id_hh(forme.sexe.value);" > Feminin <span id="sexe1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Telephone :</td> <td> <input name="tel" id="tel" type="tel" onBlur="id_hh(forme.tel.value);" ><span id="tel1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">GSM :</td> <td> <input name="GSM" id="GSM" type="text" onBlur="id_hh(forme.GSM.value);" ><span id="GSM1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">E-mail :</td> <td> <input name="email" id="email" type="text" onBlur="id_hh(forme.email.value);" ><span id="email1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Mot de passe :</td> <td> <input name="pass" id="pass" value="" type="password" onBlur="id_hh(forme.pass.value);" ><span id="pass1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Photo :</td> <td> <input name="photo" id="photo" value="" type="file" onBlur="id_hh(forme.photo.value);" ><span id="photo1"></span></td> </tr> </table></fieldset> <!--**************************** Informations Bac ***************--> <fieldset width="200"> <legend align="center"> Informations Bac </legend> <table class="tablform" border="0" width="200"cellspacing="0"> <tr align="center" style="background-color:#fff;"> <td> Filiere : </td><td><input <?php if(isset($_POST['CNE'])) echo 'value="'.$Filiere.'" readonly="readonly"';?> name="filiere" type="text" > </td> </tr> <?php if (isset($_POST['etre']) && $_POST['etre']='E'){?> <tr align="center" style="background-color:#fff;"> <td width="90">Pays : </td><td><input name="pays_bac" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> N&deg; d'Autorisation : </td><td><input name="numauto" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Date de délivrance : </td><td><input name="date_deliv" type="text" > </td> </tr> <?php } else {?> <tr align="center" style="background-color:#fff;"> <td width="90">Année d'Obtention :</td> <select name="annob" id="annob" onChange="fonction_etre(forme.annob.value);" > <?php for($i=1980;$i<2012;$i++){ ?> <option value="<?php echo $i; ?>"> <?php echo $i; ?> </option> <?php }?> </select> </tr> <tr align="center" style="background-color:#fff;"> <td width="90">Lycee :</td> <td> <input name="Lycee" id="Lycee" value="" type="text" onBlur="id_hh(forme.Lycee.value);" ><span id="Lycee1"></span></td> </tr> <tr align="center" style="background-color:#fff;"> <select name="montion" id="montion" onChange="fonction_etre(forme.montion.value);" > <option value="P"> Passable </option> <option value="A"> Assez Bien </option> <option value="B"> Bien </option> <option value="T"> Trés Bien </option> </select> </tr> <?php } ?> </table></fieldset> <!--**************************** Informations Parents ***************--> <fieldset width="200"> <legend align="center"> Informations Parents </legend> <table class="tablform" border="0" width="200"cellspacing="0"> <tr align="center" style="background-color:#fff;"> <td width="90">Nom et Prénom du Père : </td><td><input name="pere" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Nom et Prénom de la Mère : </td><td><input name="mere" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Nom et Prénom du tuteur : </td><td><input name="numauto" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> CIN du tuteur : </td><td><input name="CIN_tut" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Adresse des parents : </td><td><input name="adr2" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Province ou Préfecture : </td><td><input name="prov_pre" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Telephone Parents : </td><td><input name="tel_parent" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Profession Pere : </td><td><input name="prof_pere" type="text" > </td> </tr> <tr align="center" style="background-color:#fff;"> <td> Profession Mere : </td><td><input name="prof_mere" type="text" > </td> </tr> </table> </fieldset> <!--**************************** Informations Departement ***************--> <fieldset width="200"> <legend align="center"> Choix de Filiere </legend> <table class="tablform" border="0" width="200"cellspacing="0"> <tr align="center" style="background-color:#fff;"> <select name="filiere2" id="filiere2"> <?php $acadf=mysql_query("SELECT * FROM filieres ")or die (mysql_error()); $requetef=mysql_fetch_assoc($acadf); do{ ?> <option value="<?php echo $requetef['id_filiere']; ?>"> <?php echo $requetef['lib_filiere']; ?></option> <?php }while($requetef=mysql_fetch_assoc($acadf))?> </select> </table> </fieldset> <input class="sssabir" type="hidden" value="<?php if (isset($_POST['etre']) echo $_POST['etre'];){?>" /> <input class="sssabir" type="hidden" value="INSERER" /> <div> <input class="sssabir" type="submit" value="envoyer" /></div> <?php }?> </form> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Document sans titre</title> <link href="../style/default.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="98%" height="680" border="0" cellpadding="0" cellspacing="25"> <tr> <td width="18%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><span class="title_1"><span class="big_3"><h2>Gestion des Ressources </h2></span></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Liens utile</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Liste des ressources..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=employee&amp;show=list">Liste des ressources </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="ajouter nouveau..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"> <a href="./?page_id=employee&amp;show=add">Nouveau ressource</a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Autre lien</td> </tr> </table> <!-- <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Add new..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="#" onclick="window.open('./company_management.php','List','width=800,height=580,scrollbars=1').focus();">Company</a> </td> </tr> </table>--> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Nationalit&eacute;..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="gestion_nationnalite.php?KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onnjclick="window.open('./gestion_nationnalite.php','List','width=800,height=580,scrollbars=1').focus();">Nationalit&eacute;</a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> </tr> </table> </td> <td width="82%" align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr height="40"> <td align="left" class="title_1"><span class="important_2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=employee&amp;show=list"> Liste des Employ&eacute;s</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=employee&amp;show=add"> Ajouter un nouveau Employ&eacute;</a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <?php if ($show=='add') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="88%" align="left" class="big_3">Ajouter un nouveau Employ&eacute;</td> <td width="12%" align="right" class="txt_1g">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <form id="form_add" name="form_add" method="post" action="" enctype="multipart/form-data"> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left"><input name="htxt_id" type="hidden" id="htxt_id" value="<?php if (isset($show_employee)) echo $show_employee['emp_id']; ?>" /></td> <td width="86%" align="left"><?php echo $message; ?></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td height="30" align="left" class="txt_1">Titre</td> <td align="left"> <label> <select name="select_title" class="line_3" id="select_title"> <?php if (isset($show_employee)) echo '<option value="'.$show_employee['emp_titre'].'" selected="selected">'.$show_employee['emp_titre'].'</option>'; ?> <option value="Mr." <?php if (!isset($show_employee)) echo 'selected="selected"'; ?> >Mr.</option> <option value="Mrs.">Mrs.</option> <option value="Miss">Miss</option> </select> </label> </td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Nom </td> <td width="86%" align="left"><label> <input name="txt_firstname" type="text" class="line_3" id="txt_firstname" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_prenom']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Prenom </td> <td align="left"><label> <input name="txt_lastname" type="text" class="line_3" id="txt_lastname" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_nom']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Nationalit&eacute;</td> <td align="left"><label><?php if (isset($show_employee)) $id = $show_employee['nat_id']; else $id=''; echo select_nationality($name='select_nationality',$id,$sub=0); ?></label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">D&eacute;signation </td> <td width="86%" align="left"><label> <input name="txt_designation" type="text" class="line_4" id="txt_designation" size="45" value="<?php if (isset($show_employee)) echo $show_employee['emp_designation']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">E-mail </td> <td align="left"><label> <input name="txt_email" type="text" class="line_4" id="txt_email" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_email']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">GSM </td> <td align="left"><label> <input name="txt_phone" type="text" class="line_4" id="txt_phone" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_tel']; ?>"/> </label></td> </tr> <!-- <tr> <td height="30" align="left" class="txt_1">Company</td> <td align="left"><label><?php if (isset($show_employee)) $id = $show_employee['comp_id']; else $id=''; echo select_company($name='select_company',$id,$sub=0, 'line_3'); ?></label></td> </tr> --> <tr style="display:none"> <td height="30" align="left" class="txt_1">Department</td> <td align="left"><label> <select name="select_group" id="select_group"> <?php if (isset($show_employee)) echo '<option value="'.$show_employee['emp_groupe'].'" selected="selected">'.$show_employee['emp_groupe'].'</option>'; ?> <option value="Commercial" <?php if (!isset($show_employee)) echo 'selected="selected"'; ?>>Commercial</option> <option value="Finance">Finance</option> <option value="HRA">HRA</option> <option value="Ingineering">Ingineering</option> <option value="IT" <?php if (!isset($show_employee)) echo 'selected="selected"'; ?>>IT</option> </select> </label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td height="30" align="left" class="txt_1">N&deg; CIN </td> <td align="left"><label> <input name="txt_num_pass" type="text" class="line_4" id="txt_num_pass" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_num_pass']; ?>"/> </label></td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1"> Copie de CIN </td> <td width="86%" align="left"><?php if (isset($show_employee) && !empty($show_employee['emp_attach_pass'])) echo '<a href="../fichiers/copie_cin/'.$show_employee['emp_attach_pass'].'?KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onvhclick=" window.open(\'../fichiers/copie_cin/'.$show_employee['emp_attach_pass'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Afficher le fichier" width="22" height="22" align="absmiddle" border="0"/></a> -- Update &gt;&gt; '; ?> <input name="fichier" type="file" class="line_4" id="fichier" size="50"/> <input name="htxt_file" type="hidden" id="htxt_file" value="<?php if (isset($show_employee)) echo $show_employee['emp_attach_pass']; ?>"/></td> </tr> </table> <?php if (isset($message_up)) { ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="line_1"> <tr> <td width="14%">&nbsp;</td> <td width="86%" align="left" class="important_3"><?php echo $message_up; ?></td> </tr> </table> <?php } ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left" class="token_1">Verifiez que tous les champs sont bien remplis avant d'envoyer </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><label> <input name="sub_employee" type="submit" class="sssabir" id="sub_employee" value="Envoyer" /> </label></td> </tr> </table></td> </tr> </form> </table></td> </tr> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr height="63"> <td width="50%" align="left" class="big_3">Liste des Ressources</td> <td width="50%" align="right" class="txt_1g"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <form id="form_search_emp" name="form_search_emp" method="get" action=""> <tr> <td height="28" align="right"><span class="txt_2">Chercher :<span class="txt_1"> par Nom </span> <label> <input class="chercheee"name="txt_search_emp" type="text" id="txt_search_emp" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search_emp" type="submit" id="sub_search_emp" class="sssabir" value="Search" /> </label> </span> </td> </tr> </form> </table> </td> </tr> </table> <table width="100%" height="5" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="6%" align="center">N&deg;</td> <td width="45%" align="left">Nom complet </td> <td width="34%" align="left"> <!-- <table width="100%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form2" name="form2" method="post" action=""> <tr> <td align="left"><?php echo select_company($name='sortby_company',$sortby,$sub=1, 'line_4'); ?></td> </tr> </form> </table>--> </td> <td width="15%" align="center">Options</td> </tr> </table> <table width="100%" height="10" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <div id="zone_list"><?php echo list_employee($keyword,$authorization[3],$authorization[4]); ?></div> </td> </tr> </table> <?php } ?></td> </tr> </table></td> </tr> </table> </body> </html> <file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; if (isset($_GET['doc_info'])) { $doc_info = $_GET['doc_info']; $show_document = show_document($doc_info); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="578" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="578" align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="big_2"><img src="../image/icon/folder_open.png" width="22" height="22" /> <?php echo $show_document['doc_title'].' <br /> <span class="txt_4g">'.$show_document['doc_detail'].'</span>'; ?> </td> </tr> </table> <table width="98%" height="468" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td align="left">&nbsp;</td> </tr> </table> <!-- ********************************************-------> <table class="sab" width="100%" align="center" cellspacing="1" > <tr class="hhhhhh" > <td>Type du Document</td> <td>Propri&eacute;taire</td> <td>Date de creation</td> <td>Prepar&eacute; par</td> <td>Date de signature</td> <td>Approuvé par</td> <td>Nombre de pages</td> </tr> <tr align="center" style="background-color:#e2f2fc;" height="40"> <td><?php echo $show_document['typdoc_title']; ?></td> <td><?php echo $show_document['doc_owner']; ?></td> <td><?php echo $show_document['doc_creat_date']; ?></td> <td><?php echo $show_document['doc_prepared_by']; ?></td> <td><?php echo $show_document['doc_sign_date']; ?></td> <td><?php echo $show_document['doc_reviewed_by']; ?></td> <td><?php echo $show_document['doc_nbr_page']; ?></td> </tr> </table> <p>&nbsp;</p> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr > <!-- ********************************************----- <td align="center" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" height="30" align="left" class="txt_4">Owner</td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_owner'] ?></td> <td width="20%" align="left" class="important_2"><span class="txt_4">Creat. Date </span></td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span> <?php echo date_fr_2($show_document['doc_creat_date']) ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">Prepared By </td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_prepared_by'] ?></td> <td align="left" class="important_2"><span class="txt_4">Sign. Date </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo date_fr_2($show_document['doc_sign_date']) ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">Reviewed By </td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_reviewed_by'] ?></td> <td align="left" class="important_2"><span class="txt_4">Number of Page </span></td> <td align="left" class="important_2"><span class="txt_4">|</span> <?php echo $show_document['doc_nbr_page'] ?></td> </tr> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> <td align="left" class="important_2">&nbsp;</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table>--> <b><?php echo show_document_folder($doc_info) ?></b> </td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="token_1"><NAME> - Doc Manager </td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $keyword=''; $page = $_SERVER["PHP_SELF"]; if (isset($_GET['folder_id'])) { $folder_id = $_GET['folder_id']; $show_folder = show_folder($folder_id); } if (isset($_GET['sub_search_folder']) or isset($_GET['txt_search_folder'])) { $keyword = $_GET['txt_search_folder']; $folder_id = $_GET['folder_id']; $show_folder = show_folder($folder_id); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="578" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="578" align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="txt_4g">Le Dossier ouvert : </td> </tr> </table> <table width="98%" height="468" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="30%" align="left" class="big_3"><?php echo $show_folder['folder_name']; ?></td> <td width="50%" align="right" class="title_1"> <table width="99%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form1" name="form1" method="get" action=""> <tr> <td align="right" class="txt_2"> <input name="folder_id" type="hidden" id="folder_id" value="<?php echo $folder_id; ?>"/> Chercher dans le dossier : <label id="search1"> <input name="txt_search_folder" type="text" id="txt_search_folder" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> </label> <label id="search2"> <input name="sub_search_folder" type="submit" class="sssabir" id="sub_search_folder" value="Chercher"/> </label> &nbsp;&nbsp; <span class="txt_1g"><a href="<?php echo $page ?>?folder_id=<?php echo $folder_id; ?>">Afficher tous les Documents</a></span> </td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="4%" align="center">N&deg;</td> <td width="44%" align="left">Titre (Description) </td> <td width="16%" align="left">Date de creation </td> <td width="24%" align="left">&nbsp;</td> <td width="10%" align="center">Options</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <div id="zone_list_2"><?php echo list_documents_of_folder($keyword,$folder_id,$edit=0,$del=0); ?></div></td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" class="token_1">Ecole superieure de Technologie,MEKNES </td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep> CREATE TABLE `adocumentfolder` ( `doc_id` varchar(50) NOT NULL, `folder_id` int(11) NOT NULL, `file_attached` varchar(150) default NULL, `precision` varchar(250) default NULL, PRIMARY KEY (`doc_id`,`folder_id`), KEY `folder_id` (`folder_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `ecompanie` ( `comp_id` int(11) NOT NULL auto_increment, `comp_nom` varchar(150) default NULL, `comp_contact` varchar(250) default NULL, `comp_contact_email` varchar(150) default NULL, `comp_contact_tel` varchar(100) default NULL, `comp_statut` binary(1) default '1', PRIMARY KEY (`comp_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Contenu de la table `ecompanie` -- INSERT INTO `ecompanie` VALUES (1, 'AC WebSolution', '00', '<EMAIL>', '', 0x31); -- -------------------------------------------------------- -- -- Structure de la table `edocument` -- CREATE TABLE `edocument` ( `doc_id` varchar(50) NOT NULL default '', `doc_title` varchar(250) NOT NULL, `doc_detail` text, `doc_keyword` varchar(250) default NULL, `doc_owner` varchar(150) default NULL, `doc_prepared_by` varchar(100) default NULL, `doc_reviewed_by` varchar(100) default NULL, `doc_approved_by` varchar(100) default NULL, `doc_creat_date` date default NULL, `doc_sign_date` date default NULL, `doc_nbr_page` int(11) default NULL, `doc_status` binary(1) default NULL, `typdoc_id` int(11) default NULL, PRIMARY KEY (`doc_id`), KEY `doc_id` (`doc_id`), KEY `typdoc_id` (`typdoc_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `edocument` -- -- -------------------------------------------------------- -- -- Structure de la table `edomaine` -- CREATE TABLE `edomaine` ( `dom_id` int(11) NOT NULL auto_increment, `dom_nom` varchar(50) default NULL, `dom_description` text, `dom_autorisation` varchar(250) default NULL, `dom_niveau` varchar(25) default NULL, `dom_statut` binary(1) default NULL, PRIMARY KEY (`dom_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Contenu de la table `edomaine` -- INSERT INTO `edomaine` VALUES (1, 'SA', 'Super Admin', '0111100001111111111111111', NULL, 0x31); INSERT INTO `edomaine` VALUES (2, 'UserAdmin', 'UserAdmin', '0111100000000111110001000', NULL, 0x31); -- -------------------------------------------------------- -- -- Structure de la table `eemploye` -- CREATE TABLE `eemploye` ( `emp_id` int(11) NOT NULL auto_increment, `emp_nom` varchar(100) default NULL, `emp_prenom` varchar(100) default NULL, `emp_titre` varchar(10) default NULL, `emp_designation` varchar(250) default NULL, `emp_email` varchar(150) default NULL, `emp_tel` varchar(50) default NULL, `emp_num_pass` varchar(25) default NULL, `emp_attach_pass` varchar(150) default NULL, `emp_groupe` varchar(25) default NULL, `emp_statut` binary(1) default '1', `nat_id` int(11) default NULL, `comp_id` int(11) default NULL, PRIMARY KEY (`emp_id`), KEY `nat_id` (`nat_id`), KEY `comp_id` (`comp_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Contenu de la table `eemploye` -- INSERT INTO `eemploye` VALUES (1, 'Awa', 'Clid', 'Mr.', 'PM', '<EMAIL>', '', '', '', 'IT', 0x31, 1, 1); -- -------------------------------------------------------- -- -- Structure de la table `efolder` -- CREATE TABLE `efolder` ( `folder_id` int(11) NOT NULL auto_increment, `folder_name` varchar(50) NOT NULL, `folder_descript` text, `folder_status` binary(1) default '1', PRIMARY KEY (`folder_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Contenu de la table `efolder` -- INSERT INTO `efolder` VALUES (1, 'Licence', 'Toutes les licence', 0x31); INSERT INTO `efolder` VALUES (2, 'Certificat', 'Tous les certifs', 0x31); -- -------------------------------------------------------- -- -- Structure de la table `enationalite` -- CREATE TABLE `enationalite` ( `nat_id` int(11) NOT NULL auto_increment, `nat_design` varchar(150) default NULL, `nat_country` varchar(150) default NULL, `nat_statut` binary(1) default '1', PRIMARY KEY (`nat_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Contenu de la table `enationalite` -- INSERT INTO `enationalite` VALUES (1, 'Congolaise', 'Congo', 0x31); -- -------------------------------------------------------- -- -- Structure de la table `etypdoc` -- CREATE TABLE `etypdoc` ( `typdoc_id` int(11) NOT NULL auto_increment, `typdoc_title` varchar(150) NOT NULL, `typdoc_descript` text, `typdoc_status` binary(1) default '1', PRIMARY KEY (`typdoc_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Contenu de la table `etypdoc` -- INSERT INTO `etypdoc` VALUES (1, 'Licence Windows', 'Licence Windows', 0x31); INSERT INTO `etypdoc` VALUES (2, 'Certif Oracle', 'Certif Oracle', 0x31); -- -------------------------------------------------------- -- -- Structure de la table `eutilisateur` -- CREATE TABLE `eutilisateur` ( `util_id` varchar(100) NOT NULL, `util_pwd` varchar(100) default NULL, `util_statut` binary(1) default '1', `dom_id` int(11) default NULL, `emp_id` int(11) default NULL, PRIMARY KEY (`util_id`), KEY `dom_id` (`dom_id`), KEY `emp_id` (`emp_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `eutilisateur` -- INSERT INTO `eutilisateur` VALUES ('admin', 'admin', 0x31, 1, 1); INSERT INTO `eutilisateur` VALUES ('user', 'user', 0x31, 2, 1); -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `adocumentfolder` -- ALTER TABLE `adocumentfolder` ADD CONSTRAINT `adocumentfolder_ibfk_1` FOREIGN KEY (`doc_id`) REFERENCES `edocument` (`doc_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `adocumentfolder_ibfk_2` FOREIGN KEY (`folder_id`) REFERENCES `efolder` (`folder_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Contraintes pour la table `edocument` -- ALTER TABLE `edocument` ADD CONSTRAINT `edocument_ibfk_1` FOREIGN KEY (`typdoc_id`) REFERENCES `etypdoc` (`typdoc_id`) ON DELETE SET NULL ON UPDATE CASCADE; -- -- Contraintes pour la table `eemploye` -- ALTER TABLE `eemploye` ADD CONSTRAINT `eemploye_ibfk_1` FOREIGN KEY (`nat_id`) REFERENCES `enationalite` (`nat_id`) ON DELETE SET NULL ON UPDATE CASCADE, ADD CONSTRAINT `eemploye_ibfk_2` FOREIGN KEY (`comp_id`) REFERENCES `ecompanie` (`comp_id`) ON DELETE SET NULL ON UPDATE CASCADE; -- -- Contraintes pour la table `eutilisateur` -- ALTER TABLE `eutilisateur` ADD CONSTRAINT `eutilisateur_ibfk_2` FOREIGN KEY (`emp_id`) REFERENCES `eemploye` (`emp_id`) ON DELETE SET NULL ON UPDATE CASCADE, ADD CONSTRAINT `eutilisateur_ibfk_3` FOREIGN KEY (`dom_id`) REFERENCES `edomaine` (`dom_id`) ON DELETE SET NULL ON UPDATE CASCADE; <file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; $show = 'list'; if (isset($_GET['show'])) { $show = $_GET['show']; } $keyword=''; $message = '<span class="txt_4">Enter fodler name and decription</span>'; if (isset($_POST['sub_folder'])) { $folder_name = $_POST['txt_name']; $folder_descrip = $_POST['txt_description']; if (!empty($folder_name) && !empty($folder_descrip)) { if (isset($_POST['hfield_id']) && !empty($_POST['hfield_id'])) { update_folder($_POST['hfield_id'],$folder_name,$folder_descrip,$folder_status=1); } else { insert_folder($folder_name,$folder_descrip,$folder_status=1); } } else { $message = '<span class="warning_1">Veuillez remplir tous les champs !</span>'; } } if (isset($_GET['sub_search']) or isset($_GET['txt_search'])) { $keyword = $_GET['txt_search']; $show = 'list'; } if (isset($_GET['folder_edit'])) { $folder_edit = $_GET['folder_edit']; $show_folder = show_folder($folder_edit); } if (isset($_GET['folder_del'])) { $folder_del = $_GET['folder_del']; delete_folder($folder_del); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <title>AwaClid - DOC Manager</title> <table width="100%" height="420" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table></td> <td width="50%" align="right"><span class="txt_4"> </td> </tr> </table></td> </tr> </table> <table width="98%" height="680" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"> <?php if ($show=='add') { ?> <table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <form id="form_add" name="form_add" method="post" action=""> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3"><span class="txt_4g">G&egrave;rer les Dossiers | </span>Ajouter un dossier </td> <td width="50%" align="right"><span class="txt_4"> |</span> <span class="important_2"><a href="<?php echo $page ?>?show=add">Ajouter un dossier </a>&nbsp;&nbsp; <a href="<?php echo $page ?>?show=list">Lister les Dossiers </a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><?php echo $message; ?></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%" height="30" align="left" class="txt_1">Nom du Dossier <span class="txt_2g">*</span> </td> <td width="65%" align="left"><label> <input name="txt_name" type="text" class="line_3" id="txt_name" size="35" value="<?php if (isset($show_folder)) echo $show_folder['folder_name']; ?>"/> <input name="hfield_id" type="hidden" id="hfield_id" value="<?php if (isset($show_folder)) echo $show_folder['folder_id']; ?>"/> </label></td> <td width="5%" align="left" class="txt_1">&nbsp;</td> <td width="16%" align="left"><label></label></td> </tr> <tr> <td height="54" align="left" class="txt_1">Description <span class="txt_2g">*</span></td> <td align="left"><textarea name="txt_description" cols="45" rows="3" class="line_3" id="txt_description"><?php if (isset($show_folder)) echo $show_folder['folder_descript']; ?></textarea></td> <td align="left" class="txt_1">&nbsp;</td> <td align="left">&nbsp;</td> </tr> <tr> <td height="30" align="left">&nbsp;</td> <td align="left"><label> <input name="sub_folder" type="submit" class="sssabir" id="sub_folder" value="Mettre à jour" /> </label></td> <td align="left">&nbsp;</td> <td align="left">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%">&nbsp;</td> <td width="86%" align="left" class="txt_2"></td> </tr> </table></td> </tr> </table> </td> </tr> </form> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3"><span class="txt_4g">G&egrave;rer les Dossiers | </span>Liste des Dossiers </td> <td width="50%" align="right"><span class="txt_4"> |</span> <span class="important_2"><a href="<?php echo $page ?>?show=add">Ajouter un dossier </a>&nbsp;&nbsp; <a href="<?php echo $page ?>?show=list">Lister les Dossiers </a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="important_2"> <form id="form_search" name="form_search" method="get" action=""> <tr> <td align="left" class="txt_2">Chercher :<span class="txt_1"> Par Nom </span> <label> <input name="txt_search" type="text" id="txt_search" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search" type="submit" class="sssabir" id="sub_search" value="Chercher" /> </label> </td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="4%" align="center">N&deg;</td> <td width="28%" align="left">Nom du Dossier </td> <td width="56%" align="left">Description</td> <td width="12%" align="center">Options</td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table></td> </tr> </table> <?php echo list_folder($keyword); ?> <?php } ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" class="bg_menubar">Ecole Superieure de Technologie,MEKNES</td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep><?php session_start(); if(!isset($_SESSION["user"]) || !isset($_SESSION["authorization"])) { header("location:./login.php"); } else { $user = $_SESSION['user']; $authorization = $_SESSION['authorization']; include_once '../lib/lib_mysql.php'; } ?> <?php if (isset($_GET["delog"])) { session_unset(); session_destroy(); header("location:./login.php"); exit; } connexion(); $same_page = $_SERVER["PHP_SELF"]; $page_inc = './home.php'; $message = '<span class="warning_1">Veuillez remplir tous les champs</span>'; if (isset($_GET['page_id'])) { switch ($_GET['page_id']) { case 'employee': $page_inc = './gestion_employee.php'; if ($authorization[1]==0) $page_inc = './access_denied.php'; break; case 'document': $page_inc = './gestion_document.php'; if ($authorization[13]==0) $page_inc = './access_denied.php'; break; case 'user': $page_inc = './gestion_user.php'; if ($authorization[17]==0) $page_inc = './access_denied.php'; break; case 'group': $page_inc = './gestion_groupe.php'; if ($authorization[21]==0) $page_inc = './access_denied.php'; break; default: $page_inc = './home.php'; } } $show = 'list'; if (isset($_GET['show'])) { $show = $_GET['show']; if (($_GET['page_id']=='employee') && ($authorization[2]==0) && ($show=='add')) $page_inc = './access_denied.php'; if (($_GET['page_id']=='document') && ($authorization[14]==0) && ($show=='add')) $page_inc = './access_denied.php'; if (($_GET['page_id']=='user') && ($authorization[18]==0) && ($show=='add')) $page_inc = './access_denied.php'; if (($_GET['page_id']=='group') && ($authorization[22]==0) && ($show=='add')) $page_inc = './access_denied.php'; } if (isset($_GET['emp_edit'])) { if ($authorization[3]==0) $page_inc = './access_denied.php'; else { $emp_edit = $_GET['emp_edit']; $show_employee = show_employee($emp_edit); } } if (isset($_GET['emp_del'])) { if ($authorization[4]==0) $page_inc = './access_denied.php'; else { $emp_del = $_GET['emp_del']; delete_employee($emp_del); } } if (isset($_GET['doc_del'])) { if ($authorization[4]==0) $page_inc = './access_denied.php'; else { $doc_del = $_GET['doc_del']; delete_document($doc_del); } } if (isset($_POST['sub_employee'])) { $title = $_POST['select_title']; $firstname = $_POST['txt_firstname']; $lastname = $_POST['txt_lastname']; $nationality = $_POST['select_nationality']; $designation = $_POST['txt_designation']; $email = $_POST['txt_email']; $tel = $_POST['txt_phone']; //$company = $_POST['select_company']; $group = $_POST['select_group']; $pass_num = $_POST['txt_num_pass']; $pass_file = $_POST['htxt_file']; if (!empty($firstname) && !empty($lastname) /*&& !empty($company)*/) { //////////////////////////////////upload $repertoire = '../fichiers/copie_cin/'; if (isset($_FILES['fichier'])) { //$nom_fichier = $_FILES['fichier']['name']; $extension = substr(strrchr($_FILES['fichier']['name'], "."), 0); // On v&eacute;rifit si le r&eacute;pertoire d'upload existe if (!file_exists($repertoire)) { $erreur = 'Erreur, le dossier d\'upload n\'existe pas.'; } // Si il y a une erreur on l'affiche sinon on peut uploader if(isset($erreur)) { $message_up = $erreur ; } else { $nom_emp = strtr($firstname," ","_").strtr($lastname," ","_"); $nom_fichier = 'cin_'.$nom_emp.$extension; // On upload le fichier sur le serveur. if (move_uploaded_file($_FILES['fichier']['tmp_name'], $repertoire.$nom_fichier)) { $message_up = 'Le fichier a &eacute;t&eacute; ajout&eacute; avec succes !'; $pass_file = $nom_fichier; } else { $message_up = 'Le fichier ne peut pas etre ajout&eacute; !'; } } } /////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['htxt_id']) && !empty($_POST['htxt_id'])) { //update $show = 'add'; if (update_employee($_POST['htxt_id'],$firstname,$lastname,$title,$designation,$email,$tel,$nationality/*,$company*/,$group,$pass_num,$pass_file)) { $message = '<span class="txt_44">Les don&eacute;es ont &eacute;t&eacute; mis à jour avec succ&egrave;s</span>'; $emp_edit = $_POST['htxt_id']; $show_employee = show_employee($emp_edit); } else { $message = '<span class="warning_1">Erreur de mis à jour</span>'; } } else { // 'insertion'; if (insert_employee($firstname,$lastname,$title,$designation,$email,$tel,$nationality/*,$company*/,$group,$pass_num,$pass_file)) { $message = '<span class="txt_44">Les donn&eacute;es ont &eacute;t&eacute; ajout&eacute;s avec succ&egrave;s</span>'; } else { $message = '<span class="warning_1">Erreur d\'ajout</span>'; } } } } $keyword=''; if (isset($_POST['sub_search']) or isset($_POST['txt_search'])) { $keyword = $_POST['txt_search']; } if (isset($_GET['sub_search_emp']) or isset($_GET['txt_search_emp'])) { $keyword = $_GET['txt_search_emp']; $show = 'list'; $page_inc = './gestion_employee.php'; if ($authorization[1]==0) $page_inc = './access_denied.php'; } if (isset($_GET['sub_search_doc']) or isset($_GET['txt_search_doc'])) { $keyword = $_GET['txt_search_doc']; $show = 'list'; $page_inc = './gestion_document.php'; if ($authorization[13]==0) $page_inc = './access_denied.php'; } if (isset($_GET['sub_search_folder']) or isset($_GET['txt_search_folder'])) { $keyword = $_GET['txt_search_folder']; $show = 'folder'; $page_inc = './gestion_document.php'; if ($authorization[13]==0) $page_inc = './access_denied.php'; } $sortby = ''; /* if (isset($_POST['sortby_company']) && !empty($_POST['sortby_company'])) { $sortby = $_POST['sortby_company']; }*/ if (isset($_POST['sortby_typdoc']) && !empty($_POST['sortby_typdoc'])) { $sortby = $_POST['sortby_typdoc']; } if (isset($_POST['sortby_group']) && !empty($_POST['sortby_group'])) { $sortby = $_POST['sortby_group']; } if (isset($_POST['sub_document'])) { $id = $_POST['htxt_id']; $typdoc = $_POST['select_typdoc']; $title = $_POST['txt_title']; $detail = $_POST['txt_descript']; $keyword = $_POST['txt_keyword']; $owner = $_POST['txt_owner']; $preparedby = $_POST['txt_preparedby']; $reviewedby = $_POST['txt_reviewedby']; $approvedby = $_POST['txt_approvedby']; $creat_date = date_en($_POST['txt_datecreat']); $sign_date = date_en($_POST['txt_datesign']); //$department = $_POST['select_department']; $nbr_page = $_POST['txt_nbr_page']; $folder = $_POST['select_folder']; $status = 1; if (!empty($typdoc) && !empty($title)) { if ((isset($_POST['htxt_op'])) && ($_POST['htxt_op'] == 'upd')) { //update $id_edit = $_POST['htxt_id']; $show = 'add'; if (update_document($id_edit,$title,$detail,$keyword,$owner,$preparedby,$reviewedby,$approvedby,$creat_date,$sign_date,$nbr_page,$status,$typdoc)) { $message = '<span class="txt_44">Process done successfully</span>'; $show_document = show_document($id_edit); if (isset($_POST['txt_nbr_folder'])) { $nbr_folder = $_POST['txt_nbr_folder']; for ($f=1; $f<=$nbr_folder; $f++) { $selec_folder = 'select_folder'.$f; $txt_precision = 'txt_precision'.$f; $htxt_folder = 'htxt_folder'.$f; $htxt_precision = 'htxt_precision'.$f; $fichier = 'fichier'.$f; if (isset($_POST[$selec_folder]) && !empty($_POST[$selec_folder])) { //////////////////////////////////upload $folder_id1 = $_POST[$selec_folder]; $precision1 = $_POST[$txt_precision]; $doc_file1 = NULL; $hfolder_id = $_POST[$htxt_folder]; $hprecision = $_POST[$htxt_precision]; $repertoire = '../fichiers/document/'; if (isset($_FILES[$fichier])) { $extension = substr(strrchr($_FILES[$fichier]['name'], "."), 0); // On v&eacute;rifit si le r&eacute;pertoire d'upload existe if (!file_exists($repertoire)) { $erreur = '<span class="warning_1">Erreur, le dossier d\'upload n\'existe pas.</span>'; } // Si il y a une erreur on l'affiche sinon on peut uploader if(isset($erreur)) { $message_up = $erreur ; } else { $typ_doc = strtr($typdoc," ","_"); $nom_fichier = $typ_doc.'_'.$id.'_'.$f.$extension; // On upload le fichier sur le serveur. if (move_uploaded_file($_FILES[$fichier]['tmp_name'], $repertoire.$nom_fichier)) { $message_up = '<span class="txt_44">Votre fichier à &eacute;t&eacute; attach&eacute; avec succ&egrave;s !</span>'; $doc_file1 = $nom_fichier; } else { $message_up = '<span class="warning_1">Le fichier n\'a pas pu etre attach&eacute; !</span>'; } } } update_document_folder($id_edit,$hfolder_id,$id_edit,$folder_id1,$precision1,$doc_file1); /////////////////////////////////////////////////////////////////////////////////// } } } //////////////////////////ajout de fichier attach&eacute; if (isset($_POST['select_folder']) && !empty($_POST['select_folder'])) { //////////////////////////////////upload $folder_id = $_POST['select_folder']; $precision = $_POST['txt_precision']; $doc_file = NULL; $repertoire = '../fichiers/document/'; //sur le web if (isset($_FILES['fichier'])) { $extension = substr(strrchr($_FILES['fichier']['name'], "."), 0); // On v&eacute;rifit si le r&eacute;pertoire d'upload existe if (!file_exists($repertoire)) { $erreur = '<span class="warning_1">Erreur, le dossier d\'upload n\'existe pas.</span>'; } // Si il y a une erreur on l'affiche sinon on peut uploader if(isset($erreur)) { $message_up = $erreur ; } else { $nbr_folder = nbr_document_folder($id_edit); $nbr_folder +=1; $typ_doc = strtr($typdoc," ","_"); $nom_fichier = $typ_doc.'_'.$id_edit.'_'.$nbr_folder.$extension; // On upload le fichier sur le serveur. if (move_uploaded_file($_FILES['fichier']['tmp_name'], $repertoire.$nom_fichier)) { $message_up = '<span class="txt_44">Votre fichier à &eacute;t&eacute; attach&eacute; avec succ&egrave;s !</span>'; $doc_file = $nom_fichier; } else { $message_up = '<span class="warning_1">Le fichier n\'a pas pu etre attach&eacute; !</span>'; } } } insert_document_folder($id_edit,$folder_id,$precision,$doc_file); /////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////// } else { $message = '<span class="warning_1">Erreur de l\'envoi </span>'; } } else { if (insert_document($id,$title,$detail,$keyword,$owner,$preparedby,$reviewedby,$approvedby,$creat_date,$sign_date,$nbr_page,$status,$typdoc)) { //insert_document_folder($id,$folder,$precision=NULL); $message = '<span class="txt_44">Process done successfully</span>'; if (isset($_POST['select_folder']) && !empty($_POST['select_folder'])) { //////////////////////////////////upload $folder_id = $_POST['select_folder']; $precision = $_POST['txt_precision']; $doc_file = NULL; $repertoire = '../fichiers/document/'; if (isset($_FILES['fichier'])) { $extension = substr(strrchr($_FILES['fichier']['name'], "."), 0); // On v&eacute;rifit si le r&eacute;pertoire d'upload existe if (!file_exists($repertoire)) { $erreur = '<span class="warning_1">Erreur, le dossier d\'upload n\'existe pas.</span>'; } // Si il y a une erreur on l'affiche sinon on peut uploader if(isset($erreur)) { $message_up = $erreur ; } else { $typ_doc = strtr($typdoc," ","_"); $nom_fichier = $typ_doc.'_'.$id.'_1'.$extension; // On upload le fichier sur le serveur. if (move_uploaded_file($_FILES['fichier']['tmp_name'], $repertoire.$nom_fichier)) { $message_up = '<span class="txt_44">Votre fichier à &eacute;t&eacute; attach&eacute; avec succ&egrave;s !</span>'; $doc_file = $nom_fichier; } else { $message_up = '<span class="warning_1">Le fichier n\'a pas pu etre attach&eacute; !</span>'; } } } insert_document_folder($id,$folder_id,$precision,$doc_file); /////////////////////////////////////////////////////////////////////////////////// } } else { $message = '<span class="warning_1">Erreur de l\'envoi</span>'; } } } } if (isset($_GET['user_edit'])) { if ($authorization[19]==0) $page_inc = './access_denied.php'; else { $user_edit = $_GET['user_edit']; $show_user = show_user($user_edit); } } if (isset($_GET['user_del'])) { if ($authorization[20]==0) $page_inc = './access_denied.php'; else { $user_del = $_GET['user_del']; delete_user($user_del); } } if (isset($_POST['sub_user'])) { $employee = $_POST['htxt_employee']; $login = $_POST['txt_login']; $password = $_POST['txt_password']; $confirmation = $_POST['txt_confirm']; $group = $_POST['select_group']; if (!empty($employee) && !empty($login) && !empty($password) && ($password == $confirmation)) { if (isset($_POST['htxt_id']) && !empty($_POST['htxt_id'])) { //update if (update_user($_POST['htxt_id'],$employee,$login,$password,$group)) { $message = '<span class="txt_44">Process done successfully</span>'; $user_edit = $_POST['htxt_id']; $show_user = show_user($user_edit); } else { $message = '<span class="warning_1">Erreur de l\'envoi</span>'; } } else { // 'insertion'; if (insert_user($employee,$login,$password_c,$group)) { $message = '<span class="txt_44">Process done successfully</span>'; } else { $message = '<span class="warning_1">Erreur de l\'envoi</span>'; } } } } if (isset($_GET['group_edit'])) { if ($authorization[23]==0) $page_inc = './access_denied.php'; else { $group_edit = $_GET['group_edit']; $show_domaine = show_domaine($group_edit); } } if (isset($_GET['group_del'])) { if ($authorization[24]==0) $page_inc = './access_denied.php'; else { $group_del = $_GET['group_del']; delete_group($group_del); } } if (isset($_POST['sub_group'])) { $name = $_POST['txt_name']; $description = $_POST['txt_description']; $status = $_POST['check_status']; $authorization = 0; for ($i=1; $i<=24; $i++) { $auth_check = "c$i"; if (isset($_POST[$auth_check])) $auth_val = 1; else $auth_val = 0; $authorization .= $auth_val; } //echo $authorization; if (!empty($name)) { if (isset($_POST['htxt_id']) && !empty($_POST['htxt_id'])) { //update if (update_group($_POST['htxt_id'],$name,$description,$status,$authorization)) { $message = '<span class="txt_44">Process done successfully</span>'; $group_edit = $_POST['htxt_id']; $show_domaine = show_domaine($group_edit); } else { $message = '<span class="warning_1">Erreur de l\'envoi</span>'; } } else { // 'insertion'; if (insert_group($name,$description,$status,$authorization)) { $message = '<span class="txt_44">Process done successfully</span>'; } else { $message = '<span class="warning_1">Erreur de l\'envoi</span>'; } } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>Gestion Documents et Ressources FLO</title> <link rel="icon" type="image/png" href="favicon.png" /> <script type="text/javascript" src="../script/jquery.js"></script> <script type="text/javascript" src="../script/thickbox.js"></script> <link href="../style/thickbox.css" rel="stylesheet" type="text/css" /> <link href="../style/default.css" rel="stylesheet" type="text/css" /> </head> <body> <table width="100%" height="670" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="670" align="center" valign="top"> <table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="180" border="0" cellpadding="0" cellspacing="0" background="../image/design/bg_head_2.png"> <tr> <td width="22%" align="left" valign="top"><img src="../image/design/img_ppm_logo_2.png" width="220" height="80" /></td> <td width="78%" align="right" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="right"><span class="txt_3">Bienvenue <span class="txt_3g"><?php echo $user ?></span>, Aujourd'huit <?php echo date_fr_2(date("Y-m-d")); ?>&nbsp;&nbsp;|</span>&nbsp;&nbsp;<span ><a class="sssabir" href="./?delog=1">D&eacute;connexion</a></span>&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="150" align="right" valign="bottom"> <table width="100%" height="36" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="72%" align="left" valign="middle" ><a class="sssabir1" href="./">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="sssabir1" href="./?page_id=document">Gestion de Documents</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="sssabir1" href="./?page_id=employee">Gestion de Ressources</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="sssabir1" href="./?page_id=user">Gestions des utilisateurs</a></td> <!-- <td align="left" valign="middle"><span class="txt_4g"></span><span ><a class="sssabir" href="./?page_id=user">Gestions des utilisateurs</a></span>&nbsp;&nbsp;&nbsp;&nbsp;</td>--> </tr> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter_0.png"> <tr> <td></td> </tr> </table> <table width="100%" height="1" border="0" cellspacing="0" cellpadding="0" class="bg_menubar"> <tr> <td></td> </tr> </table> <table width="100%" height="583" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="583" align="center" valign="top"><?php include($page_inc); ?></td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter_0.png"> <tr> <td></td> </tr> </table> <table width="100%" height="32" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="32" align="center" valign="middle"><table width="98%" height="32" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="32" align="center">Ecole Superieur de Technologie,MEKNES</td> </tr> </table></td> </tr> </table> </body> </html> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Document sans titre</title> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <script language="Javascript" type="text/javascript" src="../script/visible.js"></script> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"> <table width="98%" height="680" border="0" cellpadding="0" cellspacing="25"> <tr> <td width="18%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><span class="title_1"><span class="big_3">Admin</span></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Liens utiles</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Ajouter..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=group&amp;show=list">Liste des Groupes </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Ajouter..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=group&amp;show=add">Ajouter un Groupe </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Autres liens </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Ajouter..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=user&amp;show=list">Liste des Utilisateurs </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> </tr> </table> </td> <td width="82%" align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><span class="important_2"><span class="txt_4">Administration | </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=group&amp;show=list"> Liste des Groupes</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=group&amp;show=add"> Ajouter un groupe</a>&nbsp;</span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <?php if ($show=='add') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3">Ajouter un Groupe </td> <td width="50%" align="right" class="txt_1g">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <form id="form_add" name="form_add" method="post" action="" enctype="multipart/form-data"> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left"><input name="htxt_id" type="hidden" id="htxt_id" value="<?php if (isset($show_domaine)) echo $show_domaine['dom_id']; ?>" /></td> <td width="86%" align="left"><?php echo $message; ?></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">Nom du Groupe </td> <td width="86%" align="left"><label> <input name="txt_name" type="text" class="line_3" id="txt_name" size="35" value="<?php if (isset($show_domaine)) echo $show_domaine['dom_nom']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Description </td> <td align="left"><label> <input name="txt_description" type="text" class="line_3" id="txt_description" value="<?php if (isset($show_domaine)) echo $show_domaine['dom_description']; ?>" size="45"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Statut</td> <td align="left" class="txt_1"><label> <input name="check_status" type="checkbox" id="check_status" value="1" <?php if (isset($show_domaine) && $show_domaine['dom_statut']==1) echo 'checked="checked"'; ?> /> Activer </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Les Permissions </td> <td align="left"><label></label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left" class="token_1"> <table width="300" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22" align="center"> <div id="img_employee" style="background:url(../image/icon/treeview_p.png)" onClick="javascript:change_icone('a_employee','img_employee');visibilite('a_employee');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div> </td> <td width="278" align="left" class="subtitle_3">&nbsp;Employ&eacute;</td> </tr> </table> <div id="a_employee" style="display:none"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="7%" align="left" class="txt_1">&nbsp;</td> <td width="93%" height="28" align="left" class="txt_1"><label> <input name="c1" type="checkbox" id="c1" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][1]==1)) echo 'checked="checked"'; ?>/> Consulter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c2" type="checkbox" id="c2" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][2]==1)) echo 'checked="checked"'; ?>/> Ajouter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c3" type="checkbox" id="c3" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][3]==1)) echo 'checked="checked"'; ?>/> Modifier </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c4" type="checkbox" id="c4" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][4]==1)) echo 'checked="checked"'; ?>/> Supprimer </label></td> </tr> </table> </div> <div id="a_arrdep" style="display:none"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="7%" align="left" class="txt_1">&nbsp;</td> <td width="93%" height="28" align="left" class="txt_1"><label> <input name="c9" type="checkbox" id="c9" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][9]==1)) echo 'checked="checked"'; ?>/> Consulter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c10" type="checkbox" id="c10" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][10]==1)) echo 'checked="checked"'; ?>/> Ajouter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c11" type="checkbox" id="c11" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][11]==1)) echo 'checked="checked"'; ?>/> Modifier </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c12" type="checkbox" id="c12" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][12]==1)) echo 'checked="checked"'; ?>/> Supprimer </label></td> </tr> </table> </div> <table width="300" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22" align="center"> <div id="img_documents" style="background:url(../image/icon/treeview_p.png)" onclick="javascript:change_icone('a_documents','img_documents');visibilite('a_documents');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div></td> <td width="278" align="left" class="subtitle_3">&nbsp;Documents</td> </tr> </table> <div id="a_documents" style="display:none"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="7%" align="left" class="txt_1">&nbsp;</td> <td width="93%" height="28" align="left" class="txt_1"><label> <input name="c13" type="checkbox" id="c13" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][13]==1)) echo 'checked="checked"'; ?>/> Consulter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c14" type="checkbox" id="c14" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][14]==1)) echo 'checked="checked"'; ?>/> Ajouter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c15" type="checkbox" id="c15" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][15]==1)) echo 'checked="checked"'; ?>/> Modifier </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c16" type="checkbox" id="c16" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][16]==1)) echo 'checked="checked"'; ?>/> Supprimer </label></td> </tr> </table> </div> <table width="300" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22" align="center"><div id="img_setting" style="background:url(../image/icon/treeview_p.png)" onclick="javascript:change_icone('a_setting','img_setting');visibilite('a_setting');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div></td> <td width="278" align="left" class="subtitle_3">&nbsp;Param&egrave;tres</td> </tr> </table> <div id="a_setting" style="display:none"> <table width="335" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="21">&nbsp;</td> <td width="314" align="left"><table width="300" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22" align="center"><div id="img_setting_user" style="background:url(../image/icon/treeview_p.png)" onclick="javascript:change_icone('a_setting_user','img_setting_user');visibilite('a_setting_user');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div></td> <td width="278" align="left" class="subtitle_3">&nbsp;Utilisateurs</td> </tr> </table> <div id="a_setting_user" style="display:none"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="7%" align="left" class="txt_1">&nbsp;</td> <td width="93%" height="28" align="left" class="txt_1"><label> <input name="c17" type="checkbox" id="c17" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][17]==1)) echo 'checked="checked"'; ?>/> Consulter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c18" type="checkbox" id="c18" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][18]==1)) echo 'checked="checked"'; ?>/> Ajouter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c19" type="checkbox" id="c19" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][19]==1)) echo 'checked="checked"'; ?>/> Modifier </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c20" type="checkbox" id="c20" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][20]==1)) echo 'checked="checked"'; ?>/> Supprimer </label></td> </tr> </table> </div> <table width="300" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="22" align="center"><div id="img_setting_dom" style="background:url(../image/icon/treeview_p.png)" onclick="javascript:change_icone('a_setting_dom','img_setting_dom');visibilite('a_setting_dom');" > <table width="22" height="22" border="0" cellpadding="0" cellspacing="0"> <tr> <td>&nbsp;</td> </tr> </table> </div></td> <td width="278" align="left" class="subtitle_3">&nbsp;Groupes utilisateurs </td> </tr> </table> <div id="a_setting_dom" style="display:none"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="7%" align="left" class="txt_1">&nbsp;</td> <td width="93%" height="28" align="left" class="txt_1"><label> <input name="c21" type="checkbox" id="c21" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][21]==1)) echo 'checked="checked"'; ?>/> Consulter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c22" type="checkbox" id="c22" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][22]==1)) echo 'checked="checked"'; ?>/> Ajouter </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c23" type="checkbox" id="c23" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][23]==1)) echo 'checked="checked"'; ?>/> Modifier </label></td> </tr> <tr> <td align="left" class="txt_1">&nbsp;</td> <td height="28" align="left" class="txt_1"><label> <input name="c24" type="checkbox" id="c24" value="1" <?php if ((isset($show_domaine)) && ($show_domaine['dom_autorisation'][24]==1)) echo 'checked="checked"'; ?>/> Supprimer </label></td> </tr> </table> </div> </td> </tr> </table> </div> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <!-- <td width="86%" align="left" class="token_1">Be sure that all important fields are filled before to submit </td>--> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><label> <input name="sub_group" type="submit" class="sssabir" id="sub_group" value="Envoyer" /> </label></td> </tr> </table></td> </tr> </form> </table></td> </tr> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3">Liste des Groupes </td> <td width="50%" align="right" class="txt_1g"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="important_2"> <form id="form1" name="form1" method="post" action=""> <tr> <td align="right" class="txt_2">Chercher :<span class="txt_1"> Par Nom </span> <label> <input name="txt_search" type="text" id="txt_search" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search" type="submit" class="sssabir"id="sub_search" value="Chercher" /> </label> </td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr > <td width="4%" align="center">N&deg;</td> <td width="22%" align="left">Nom du Groupe </td> <td align="left">Description </td> <td width="11%" align="center">OPTIONS</td> </tr> </table> <?php echo list_group($keyword,$authorization[23],$authorization[24]); ?> </td> </tr> </table> <?php } ?></td> </tr> </table></td> </tr> </table> </body> </html> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Document sans titre</title> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <script language="Javascript" type="text/javascript" src="../script/visible.js"></script> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="98%" height="680" border="0" cellpadding="0" cellspacing="25"> <tr> <td width="18%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><span class="title_1"><span class="big_3">Gestion de Documents</span></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Liens utiles </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="16%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="84%" align="left" class="subtitle_3"><a href="./?page_id=document&amp;show=list">Lister des Documents </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="16%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="84%" align="left" class="subtitle_3"> <a href="./?page_id=document&amp;show=add">Ajouter un Document </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="16%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="84%" align="left" class="subtitle_3"><a href="./?page_id=document&amp;show=folder">Lister les Dossiers </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Autres Liens </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="gestion_doctype.php?KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onjkclick="window.open('./gestion_doctype.php','List','width=800,height=580,scrollbars=1').focus();">Type du Document </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="left" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./gestion_dossier.php?KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onljlclick="window.open('./gestion_dossier.php','List','width=800,height=580,scrollbars=1').focus();">Gestion des Dossiers</a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> </tr> </table> </td> <td width="82%" align="left" valign="top"> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><span class="important_2"><span class="txt_4">G&egrave;rer les Documents | </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=document&amp;show=list"> Lister des Documents</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=document&amp;show=add"> Ajouter un Document</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=document&amp;show=folder"> Lister les Dossiers </a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <?php switch ($show) { case 'add': //if ($show=='add') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="51%" align="left" class="big_3">Ajouter un Document</td> <td width="49%" align="right" class="txt_1g">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <form id="form_add" name="form_add" method="post" action="" enctype="multipart/form-data"> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><?php echo $message; ?> <input name="htxt_op" type="hidden" id="htxt_op" value="<?php if (isset($show_document)) echo 'upd'; else echo 'ins'; ?>"/> <input name="htxt_id" type="hidden" id="htxt_id" value="<?php if (isset($show_document)) echo $show_document['doc_id']; else echo 'DOC'.date("YmdHis"); ?>" /></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td height="30" align="left" class="txt_1">Type du Document </td> <td align="left"> <label><?php if (isset($show_document)) $sortby = $show_document['typdoc_id']; echo select_typedoc($name='select_typdoc',$sortby,$sub=0, 'line_3'); ?></label> </td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Titre </td> <td width="86%" align="left"><label> <input name="txt_title" type="text" class="line_3" id="txt_title" size="45" value="<?php if (isset($show_document)) echo $show_document['doc_title']; ?>"/> </label></td> </tr> <tr> <td height="61" align="left" class="txt_1">Description </td> <td align="left"><label> <textarea name="txt_descript" cols="45" rows="3" class="line_4" id="txt_descript"><?php if (isset($show_document)) echo $show_document['doc_detail']; ?></textarea> </label></td> </tr> <tr style="display: none"> <td height="30" align="left" class="txt_1">Mots cl&eacute;s </td> <td align="left"><label> <input name="txt_keyword" type="text" class="line_4" id="txt_keyword" size="35" value="<?php if (isset($show_document)) echo $show_document['doc_detail']; ?>"/> </label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">Proprietaire </td> <td width="86%" align="left"><label> <input name="txt_owner" type="text" class="line_4" id="txt_owner" size="45" value="<?php if (isset($show_document)) echo $show_document['doc_owner']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Prepar&eacute; par </td> <td align="left"><label> <input name="txt_preparedby" type="text" class="line_4" id="txt_preparedby" size="35" value="<?php if (isset($show_document)) echo $show_document['doc_prepared_by']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Révisé Par </td> <td align="left"><label> <input name="txt_reviewedby" type="text" class="line_4" id="txt_reviewedby" size="35" value="<?php if (isset($show_document)) echo $show_document['doc_reviewed_by']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Approuvé Par </td> <td align="left"><label> <input name="txt_approvedby" type="text" class="line_4" id="txt_approvedby" size="35" value="<?php if (isset($show_document)) echo $show_document['doc_approved_by']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Date de Creation </td> <td align="left"><label> <input name="txt_datecreat" type="text" class="line_4" id="txt_datecreat" <?php if (isset($show_document)) echo 'value="'.date_fr($show_document['doc_creat_date']).'"'; else echo 'value="'.$date = date("d-m-Y").'"'; ?> readonly="readonly"/> <a href="#" onclick=" window.open('../lib/calendar/calendar.php?frm=form_add&amp;ch=txt_datecreat','calendrier','width=350,height=160,scrollbars=0').focus();"> <img src="../image/icon/date.png" width="22" height="22" border="0" align="absmiddle" /> </a></label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Date de Signature </td> <td align="left"><input name="txt_datesign" type="text" class="line_4" id="txt_datesign" <?php if (isset($show_document)) echo 'value="'.date_fr($show_document['doc_sign_date']).'"'; else echo 'value="'.$date = date("d-m-Y").'"'; ?> readonly="readonly"/> <a href="#" onclick=" window.open('../lib/calendar/calendar.php?frm=form_add&amp;ch=txt_datesign','calendrier','width=350,height=160,scrollbars=0').focus();"> <img src="../image/icon/date.png" width="22" height="22" border="0" align="absmiddle" /> </a></td> </tr> <tr> <td height="30" align="left" class="txt_1">Nombre de Pages</td> <td align="left"><input name="txt_nbr_page" type="text" class="line_4" id="txt_nbr_page" size="35" value="<?php if (isset($show_document)) echo $show_document['doc_nbr_page']; ?>"/></td> </tr> </table> <?php if (isset($show_document)) echo show_document_folder_edit($show_document['doc_id']); ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" height="28" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%" align="left" class="txt_1">&nbsp;</td> <td width="86%" align="left" class="txt_4"> <label><span class="txt_1"><a href="#" onclick="javascript:visibilite('attach_file');">[Dossier]</a></span></label></td> </tr> </table> <div id="attach_file" style="display:"> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <?php if (isset($message_up)) { ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><?php echo $message_up; ?></td> </tr> </table> <?php } ?> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="line_2"> <tr> <td height="31" align="left" class="txt_1">Dossier </td> <td align="left"><label><?php echo select_folder($name='select_folder',$sortby='',$sub=0, 'line_4'); ?></label> </td> </tr> <tr style="display:none"> <td height="31" align="left" class="txt_1">Detail</td> <td align="left"><label> <input name="txt_precision" type="text" id="txt_precision" size="45" /> </label></td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Fichier </td> <td width="86%" align="left"><label> <?php if (isset($show_document) && !empty($show_document['doc_attach_file'])) echo '<a href="../fichiers/document/'.$show_document['doc_attach_file'].'?KeepThis=true&TB_iframe=true&height=400&width=890" class="thickbox" onkhkclick=" window.open(\'../fichiers/document/'.$show_document['doc_attach_file'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a> -- Update &gt;&gt; '; ?> <input name="fichier" type="file" class="line_4" id="fichier" size="50"/> </label></td> </tr> </table> </div> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left" class="txt_2"> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><label> <input name="sub_document" type="submit" class="sssabir" class="btn_link_2" id="sub_document" value="Envoyer" /> </label></td> </tr> </table></td> </tr> </form> </table></td> </tr> </table> <?php break; case 'list': //} elseif ($show=='list') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="46%" align="left" class="big_3">Liste de Documents</td> <td width="54%" align="right" class="title_1"><table width="99%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form1" name="form1" method="get" action=""> <tr> <td align="right"> Chercher : <label id="search1"> <input name="txt_search_doc" type="text" id="txt_search_doc" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> </label> <label id="search2"> <input name="sub_search_doc" type="submit"class="sssabir" id="sub_search_doc" value="chercher"/> </label> &nbsp;&nbsp;&nbsp;</td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="4%" align="center">N&deg;</td> <td width="44%" align="left">Titre (Description) </td> <td width="16%" align="left">Date de creation </td> <td width="24%" align="left"> <table width="100%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form2" name="form2" method="post" action=""> <tr> <td align="left"><?php echo select_typedoc($name='sortby_typdoc',$sortby,$sub=1, 'line_4'); ?></td> </tr> </form> </table> </td> <td width="10%" align="center">Options</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <div id="zone_list"><?php echo list_document($keyword,$sortby,$authorization[15],$authorization[16]); ?></div> </td> </tr> </table> <?php break; case 'folder': //} elseif ($show=='folder') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3">Liste des Dossiers</td> <td width="50%" align="right" class="title_1"><table width="99%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form1" name="form1" method="get" action=""> <tr> <td align="right"> Chercher : <label id="search1"> <input name="txt_search_folder" type="text" id="txt_search_folder" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> </label> <label id="search2"> <input name="sub_search_folder" type="submit" id="sub_search_folder" value="Chercher"/> </label> </td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="4%" align="center">N&deg;</td> <td width="28%" align="left">Nom du dossier </td> <td width="56%" align="left">Description</td> <td width="12%" align="center">Options</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <div id="zone_list"><?php echo list_folder_docs($keyword); ?></div> </td> </tr> </table> <?php break; } ?> </td> </tr> </table></td> </tr> </table> </body> </html> <file_sep><?php include_once '../lib/lib_mysql.php'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; if (isset($_GET['user_info'])) { $user_info = $_GET['user_info']; $show_user = show_user($user_info); } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="578" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="578" align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="80" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table> </td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="big_2"><img src="../image/icon/identity_New1.png" width="22" height="22" /> <?php echo $show_user['util_id'].' <span class="txt_4g"> - '.$show_user['emp_prenom'].' '.$show_user['emp_nom']; ?> ,<span class="txt_4"><?php echo $show_user['emp_titre'] ?></span></span> </td> </tr> </table> <table width="98%" height="468" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"><table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="title_1"> Informations d'utilisateur </td> <td width="80%" align="left" class="title_1"><span class="txt_4"></span></td> </tr> </table> <table class="sab" width="100%" align="center" cellspacing="1" > <tr class="hhhhhh" > <td>D&eacute;signation</td> <td>E-mail</td> <td>GSM</td> <td>Groupe</td> <td>Autorisation Groupe</td> <td>Copie CIN</td> </tr> <tr align="center" style="background-color:#e2f2fc;" height="40"> <td><?php echo $show_user['emp_designation']; ?></td> <td><?php echo $show_user['emp_email']; ?></td> <td><?php echo $show_user['emp_tel']; ?></td> <td><?php echo $show_user['dom_nom']; ?></td> <td><?php echo $show_user['dom_autorisation']; ?></td> <td><?php if (!empty($show_user['emp_attach_pass'])) echo '<a href="#" onclick=" window.open(\'../fichiers/copie_cin/'.$show_user['emp_attach_pass'].'\',\'List\',\'width=580,height=680\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a>'; ?></td> </tr> </table> <!-- <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" height="30" align="left" class="txt_4">D&eacute;signation</td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span></td> <td width="20%" align="left" class="important_2"><span class="txt_4">Email</span></td> <td width="30%" align="left" class="important_2"><span class="txt_4">|</span></td> </tr> <tr> <td height="30" align="left" class="txt_4">Company</td> <td align="left" class="important_2"><span class="txt_4">|</span></td> <td align="left" class="important_2"><span class="txt_4">Mobile Phone </span></td> <td align="left" class="important_2"><span class="txt_4">|</span></td> </tr> <tr> <td height="30" align="left" class="txt_4">Nationality</td> <td align="left" class="important_2"><span class="txt_4">|</span></td> <td align="left" class="important_2"><span class="txt_4">Passport Number </span></td> <td align="left" class="important_2"><span class="txt_4">|</span></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" align="left" class="txt_4">Passport Copy </td> <td width="80%" align="left" class="txt_2"><span class="important_2"><span class="txt_4">|</span></span></td> </tr> </table> --> </td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="detail_1">Awa Clid - Doc Manager </td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep><?php session_start(); if(!isset($_SESSION["user"]) || !isset($_SESSION["authorization"])) { header("location:./login.php"); } else { $user = $_SESSION['user']; $authorization = $_SESSION['authorization']; include_once '../lib/lib_mysql.php'; } ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; $show = 'list'; if (isset($_GET['show'])) { $show = $_GET['show']; } $keyword=''; $message = '<span class="txt_4">Enter the nationality and the country</span>'; if (isset($_POST['sub_nationality'])) { $nat_design = $_POST['txt_design']; $nat_country = $_POST['txt_country']; if (!empty($nat_design) && !empty($nat_country)) { insert_nationality($nat_design,$nat_country); } else { $message = '<span class="warning_1">You must fill all field !</span>'; } } if (isset($_GET['sub_search']) or isset($_GET['txt_search'])) { $keyword = $_GET['txt_search']; $show = 'list'; } if (isset($_GET['nat_del'])) { if ($authorization[4]==0) header('location: access_denied.php'); else { $nat_del = $_GET['nat_del']; delete_nationality($nat_del); } } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <title>AwaClid - DOC Manager</title> <table width="100%" height="420" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table></td> <td width="50%" align="right"></td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="680" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"> <?php if ($show=='add') { ?> <table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <form id="form_add" name="form_add" method="post" action=""> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3"><span class="txt_4g">G&egrave;rer Ressources | </span>Ajouter une nouvelle nationalit&eacute; </td> <td width="50%" align="right"><span class="txt_4">|</span> <span class="important_2"><a href="<?php echo $page ?>?show=add">Ajouter une nouvelle nationalit&eacute; </a>&nbsp;&nbsp; <a href="<?php echo $page ?>?show=list"><span class="txt_4">|&nbsp;&nbsp; </span> List of Nationalities </a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td align="left">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><?php //echo $message; ?></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%" height="30" align="left" class="txt_1">Nationalit&eacute; <span class="txt_2g">*</span> </td> <td width="36%" align="left"><label> <input name="txt_design" type="text" class="line_3" id="txt_design" size="35" /> </label></td> <td width="12%" align="left" class="txt_1">Pays <span class="txt_2g">*</span></td> <td width="38%" align="left"><label> <input name="txt_country" type="text" class="line_3" id="txt_country" size="30" /> </label></td> </tr> <tr> <td height="30" align="left">&nbsp;</td> <td align="left"><label> <input name="sub_nationality" type="submit" class="sssabir" id="sub_nationality" value="Envoyer" /> </label></td> <td align="left">&nbsp;</td> <td align="left">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%">&nbsp;</td> <td width="86%" align="left" class="txt_2"> </td> </tr> </table></td> </tr> </table> </td> </tr> </form> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3"><span class="txt_4g">G&egrave;rer Ressources | </span>List of Nationalities </td> <td width="50%" align="right"><span class="txt_4"> |</span> <span class="important_2"><a href="<?php echo $page ?>?show=add">Ajouter une nouvelle nationalit&eacute; </a>&nbsp;&nbsp; <a href="<?php echo $page ?>?show=list">Lister les Nationalit&eacute;s </a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="important_2"> <form id="form_search" name="form_search" method="get" action=""> <tr> <td align="left" class="txt_2">Chercher :<span class="txt_1"> Par Nom </span> <label> <input name="txt_search" type="text" id="txt_search" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search" type="submit" class="sssabir" id="sub_search" value="Chercher" /> </label> </td> </tr> </form> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="6%" align="center">N&deg;</td> <td width="48%" align="left">Nationalit&eacute;</td> <td width="34%" align="left">Pays</td> <td width="12%" align="center">Options</td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table></td> </tr> </table> <?php echo list_nationality($keyword); ?> <?php } ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="detail_1">Ecole Superieure de Technologie,MEKNES</td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep>// JavaScript Document function visibilite(thingId) { var targetElement; targetElement = document.getElementById(thingId) ; if (targetElement.style.display == "none") { targetElement.style.display = "" ; } else { targetElement.style.display = "none"; } } function change_icone(thingId,imgId) { var targetElement; var targetImg; targetElement = document.getElementById(thingId) ; targetImg = document.getElementById(imgId) ; if (targetElement.style.display == "none") { targetImg.style.background = "url(../image/icon/treeview_m.png)"; } else { targetImg.style.background = "url(../image/icon/treeview_p.png)"; } } function display(calque) { document.getElementById('calque').style.display=document.getElementById('calque').style.display=="none"?"block":"none"; } function visibleReset() { var target1; target1 = document.getElementById('tab_1') ; target1.style.background = "url(../design/pic/tab_a.png)"; var target2; target2 = document.getElementById('tab_2') ; target2.style.background = "url(../design/pic/tab_d.png)"; var show1; show1 = document.getElementById('field_1') ; show1.style.display = ""; var show2; show2 = document.getElementById('field_2') ; show2.style.display = "none"; } function visible1() { var target1; target1 = document.getElementById('tab_1') ; target1.style.background = "url(../design/pic/tab_a.png)"; var show1; show1 = document.getElementById('field_1') ; show1.style.display = ""; var target2; target2 = document.getElementById('tab_2') ; target2.style.background = "url(../design/pic/tab_d.png)"; var show2; show2 = document.getElementById('field_2') ; show2.style.display = "none"; } function visible2() { var target1; target1 = document.getElementById('tab_1') ; target1.style.background = "url(../design/pic/tab_d.png)"; var show1; show1 = document.getElementById('field_1') ; show1.style.display = "none"; var target2; target2 = document.getElementById('tab_2') ; target2.style.background = "url(../design/pic/tab_a.png)"; var show2; show2 = document.getElementById('field_2') ; show2.style.display = ""; }<file_sep><?php include_once '../lib/lib_mysql.php'; $user = 'Clid'; ?> <?php connexion(); $page = $_SERVER["PHP_SELF"]; $list = 'all'; if (isset($_GET['list'])) { $list = $_GET['list']; } $show = 'list'; if (isset($_GET['show'])) { $show = $_GET['show']; } $keyword=''; $message = '<span class="txt_4">Enter the company and the contact</span>'; if (isset($_POST['sub_employee'])) { $title = $_POST['select_title']; $firstname = $_POST['txt_firstname']; $lastname = $_POST['txt_lastname']; $nationality = $_POST['select_nationality']; $designation = $_POST['txt_designation']; $email = $_POST['txt_email']; $tel = $_POST['txt_phone']; $company = $_POST['select_company']; $group = $_POST['select_group']; $pass_num = $_POST['txt_num_pass']; $pass_file = NULL; if (!empty($firstname) && !empty($lastname) && !empty($company)) { //////////////////////////////////upload $up_image = 0; $poids_max = 51200000; // Poids max de l'image en octets (1Ko = 1024 octets) //$repertoire = '../web/fr/img/puce/'; // Repertoire d'upload en local $repertoire = '../fichiers/'; //sur le web if (isset($_FILES['fichier'])) { //$nom_fichier = $_FILES['fichier']['name']; $extension = substr(strrchr($_FILES['fichier']['name'], "."), 0); // On vérifit si le répertoire d'upload existe if (!file_exists($repertoire)) { $erreur = 'Erreur, le dossier d\'upload n\'existe pas.'; } // Si il y a une erreur on l'affiche sinon on peut uploader if(isset($erreur)) { $message_up = $erreur ; } else { $nom_emp = strtr($firstname," ","_").strtr($lastname," ","_"); $nom_fichier = 'Pass_'.$nom_emp.$extension; // On upload le fichier sur le serveur. if (move_uploaded_file($_FILES['fichier']['tmp_name'], $repertoire.$nom_fichier)) { $message_up = 'Votre fichier à été attaché avec succès !'; $pass_file = $nom_fichier; } else { $message_up = 'Le fichier n\'a pas pu etre attaché !'; } } } /////////////////////////////////////////////////////////////////////////////////// if (insert_employee($firstname,$lastname,$title,$designation,$email,$tel,$nationality,$company,$group,$pass_num,$pass_file)) { $message = '<span class="txt_4">Process done successfully</span>'; } else { $message = '<span class="warning_1">Process failed</span>'; } } } if (isset($_POST['sub_search']) && !empty($_POST['txt_search'])) { $keyword = $_POST['txt_search']; } $sortby = ''; if (isset($_POST['sortby_company']) && !empty($_POST['sortby_company'])) { $sortby = $_POST['sortby_company']; } if ((isset($_GET["emp_id"])) /*&& (isset($_GET["emp_name"]))*/) { $id = $_GET["emp_id"]; $name = $_GET["emp_name"]; $designation = $_GET["emp_design"]; //$company = $_GET["emp_comp"]; echo '<script type="text/javascript">'; echo 'window.opener.document.form_add.reset();'; echo 'window.opener.document.form_add.elements[\'htxt_employee\'].value=\''.$id.'\';'; echo 'window.opener.document.form_add.elements[\'txt_employee\'].value=\''.$name.'\';'; echo 'window.opener.document.form_add.elements[\'txt_designation\'].value=\''.$designation.'\';'; // echo 'window.opener.document.form_add.elements[\'txt_company\'].value=\''.$company.'\';'; echo 'window.close();'; echo '</script>'; } ?> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <table width="100%" height="420" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"><table width="100%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><table width="98%" height="50" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_1"><img src="../image/design/img_ppm_logo_mini.png" width="500" height="60" /></td> <td width="50%" align="right">&nbsp;</td> </tr> </table></td> <td width="50%" align="right">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table> <table width="98%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">G&egrave;rer le Employ&eacute;s</td> </tr> </table> <table width="98%" height="680" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="82%" align="left" valign="top"> <?php if ($show=='add') { ?> <table width="100%" height="80" border="0" cellpadding="0" cellspacing="0"> <form id="form_add" name="form_add" method="post" action=""> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="title_1">Ajout des Employ&eacute; | <span class="txt_4">Action :</span> <span class="txt_1g">&nbsp;&nbsp;<img src="../image/design/puce_list.png" width="22" height="22" align="absmiddle" /> <a href="<?php echo $page ?>?show=list">List of Employee </a> </span></td> <td width="50%" align="right" class="txt_1g">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left"><input name="htxt_id" type="hidden" id="htxt_id" value="<?php if (isset($show_employee)) echo $show_employee['emp_id']; ?>" /></td> <td width="86%" align="left"><?php echo $message; ?></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td height="30" align="left" class="txt_1">Titre</td> <td align="left"><label> <select name="select_title" class="line_3" id="select_title"> <?php if (isset($show_employee)) echo '<option value="'.$show_employee['emp_titre'].'" selected="selected">'.$show_employee['emp_titre'].'</option>'; ?> <option value="Mr." <?php if (!isset($show_employee)) echo 'selected="selected"'; ?> >Mr.</option> <option value="Mrs.">Mrs.</option> <option value="Miss">Miss</option> </select> </label> </td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Nom </td> <td width="86%" align="left"><label> <input name="txt_firstname" type="text" class="line_3" id="txt_firstname" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_prenom']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Prenom </td> <td align="left"><label> <input name="txt_lastname" type="text" class="line_3" id="txt_lastname" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_nom']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Nationalit&eacute;</td> <td align="left"><label> <?php if (isset($show_employee)) $id = $show_employee['nat_id']; else $id=''; echo select_nationality($name='select_nationality',$id,$sub=0); ?> </label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">D&eacute;signation </td> <td width="86%" align="left"><label> <input name="txt_designation" type="text" class="line_4" id="txt_designation" size="45" value="<?php if (isset($show_employee)) echo $show_employee['emp_designation']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">E-mail </td> <td align="left"><label> <input name="txt_email" type="text" class="line_4" id="txt_email" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_email']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">GSM </td> <td align="left"><label> <input name="txt_phone" type="text" class="line_4" id="txt_phone" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_tel']; ?>"/> </label></td> </tr> <tr> <!--<td height="30" align="left" class="txt_1">Company</td>--> <td align="left"><label> <?php if (isset($show_employee)) $id = $show_employee['comp_id']; else $id=''; echo select_company($name='select_company',$id,$sub=0, 'line_3'); ?> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Department</td> <td align="left"><select name="select_group" id="select_group"> <?php if (isset($show_employee)) echo '<option value="'.$show_employee['emp_groupe'].'" selected="selected">'.$show_employee['emp_groupe'].'</option>'; ?> <option value="Commercial" selected="selected">Commercial</option> <option value="Finance">Finance</option> <option value="HRA">HRA</option> <option value="Ingineering">Ingineering</option> <option value="IT" <?php if (!isset($show_employee)) echo 'selected="selected"'; ?>>IT</option> </select></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td height="30" align="left" class="txt_1">N&deg; CIN </td> <td align="left"><label> <input name="txt_num_pass" type="text" class="line_4" id="txt_num_pass" size="35" value="<?php if (isset($show_employee)) echo $show_employee['emp_num_pass']; ?>"/> </label></td> </tr> <tr> <td width="14%" height="30" align="left" class="txt_1">Copie CIN </td> <td width="86%" align="left"><?php if (isset($show_employee) && !empty($show_employee['emp_attach_pass'])) echo '<a href="#" onclick=" window.open(\'../fichiers/copie_cin/'.$show_employee['emp_attach_pass'].'\',\'List\',\'width=580,height=680,scrollbars=1\').focus();"><img src="../image/icon/kget_list.png" alt="Show the file" width="22" height="22" align="absmiddle" border="0"/></a> -- Update &gt;&gt; '; ?> <input name="fichier" type="file" class="line_4" id="fichier" size="50"/></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left" class="token_1"> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><label> <input name="sub_employee" type="submit" class="btn_link_2" id="sub_employee" value="Submit Employee" /> </label></td> </tr> </table></td> </tr> </table></td> </tr> </form> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="title_1">Liste des Employés | <span class="txt_4">Action :</span> <span class="txt_1g"><img src="../image/design/puce_add.png" width="22" height="22" align="absmiddle" /> <a href="<?php echo $page ?>?show=add">Ajouter un nouveau Employe </a></span></td> <td width="50%" align="right" class="title_1">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="important_2"> <form id="form_search" name="form_search" method="post" action=""> <tr> <td align="left" class="txt_2">Chercher :<span class="txt_1"> Par Nom </span> <label> <input name="txt_search" type="text" id="txt_search" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search" type="submit" class="sssabir"id="sub_search" value="Chercher" /> </label> </td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="6%" align="center">N&deg;</td> <td width="36%" align="left">Nom</td> <td width="32%" align="left">Designation </td> <td width="26%" align="left"><table width="100%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form2" name="form2" method="post" action=""> <tr> <td align="left"><?php //echo select_company($name='sortby_company',$sortby,$sub=1, 'line_4'); ?></td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td></td> </tr> </table></td> </tr> </table> <?php echo list_employee_2($keyword,$sortby); ?> <?php } ?> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1">&nbsp;</td> </tr> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="50" border="0" cellpadding="0" cellspacing="0" class="bg_menubar"> <tr> <td height="43" align="center" valign="middle"><table width="98%" height="40" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="detail_1">Ecole Superieure de Technologie Meknes</td> </tr> </table></td> </tr> </table></td> </tr> </table> <?php deconnexion(); ?> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Document sans titre</title> <link href="../style/default.css" rel="stylesheet" type="text/css" /> <style type="text/css"> <!-- .Style1 {font-weight: bold} --> </style> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="98%" height="680" border="0" cellpadding="0" cellspacing="25"> <tr> <td width="18%" align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left"><span class="title_1"><span class="big_3">Gestion des Utilisateurs</span></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Liens utiles </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Add new..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=user&amp;show=list">Lister les utilisateurs </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Add new..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=user&amp;show=add">Ajouter un nouveau user </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_444">Autres Liens </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="17%" height="30" align="center" class="subtitle_3"><span class="txt_1g"><img src="../image/design/puce_1.png" alt="Add new..." width="18" height="18" /></span></td> <td width="83%" align="left" class="subtitle_3"><a href="./?page_id=group&amp;show=list">Gestion des Groupes </a> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_2">&nbsp;</td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="left" class="txt_4">&nbsp;</td> </tr> </table> </td> <td width="82%" align="left" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="left" class="title_1"><span class="important_2"><span class="txt_4">Administration | </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=user&amp;show=list"> Lister les Utilisateurs </a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=user&amp;show=add"> Ajouter un nouveau User</a>&nbsp;<a href="./?page_id=user&amp;show=list"> </a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./?page_id=group&amp;show=list"> Gestion des Groupes</a></span></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <?php if ($show=='add') { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <!-- <td width="50%" align="left" class="big_3">Ajouter des nouveaux users </td>--> <td width="50%" align="right" class="txt_1g">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <form id="form_add" name="form_add" method="post" action="" enctype="multipart/form-data"> <tr> <td align="left" valign="top"><table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left"><input name="htxt_id" type="hidden" id="htxt_id" value="<?php if (isset($show_user)) echo $show_user['util_id']; ?>" /></td> <td width="86%" align="left"><?php echo $message; ?></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">Employee</td> <td width="86%" align="left"><label> <input name="txt_employee" type="text" class="line_2" id="txt_employee" size="45" readonly="readonly" value="<?php if (isset($show_user)) echo $show_user['emp_nom'].' '.$show_user['emp_prenom']; ?>"/> <input name="htxt_employee" type="hidden" id="htxt_employee" value="<?php if (isset($show_user)) echo $show_user['emp_id']; ?>"/> <a href="#" onclick="window.open('./employee_list.php','List','width=720,height=580,scrollbars=1').focus();"> <img src="../image/icon/kget_list.png" alt="Select Employee ..." width="22" height="22" border="0" align="absmiddle" /> </a> </label> </td> </tr> <tr> <td height="30" align="left" class="txt_1">Designation</td> <td align="left"><label> <input name="txt_designation" type="text" class="line_2" id="txt_designation" size="45" readonly="readonly" value="<?php if (isset($show_user)) echo $show_user['emp_designation']; ?>"/> </label></td> </tr> <!-- <tr> <td height="30" align="left" class="txt_1">Company</td> <td align="left"><input name="txt_company" type="text" class="line_2" id="txt_company" size="45" readonly="readonly" value="<?php if (isset($show_user)) echo $show_user['comp_nom']; ?>"/></td> </tr>--> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left">&nbsp;</td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" height="30" align="left" class="txt_1">Login </td> <td width="86%" align="left"><label> <input name="txt_login" type="text" class="line_3" id="txt_login" size="35" value="<?php if (isset($show_user)) echo $show_user['util_id']; ?>"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Mot de passe </td> <td align="left"><label> <input name="txt_password" type="password" class="line_3" id="txt_password" value="<?php if (isset($show_user)) echo $show_user['util_pwd']; ?>" size="35"/> </label></td> </tr> <tr> <td height="30" align="left" class="txt_1">Confirmer Mot de passe </td> <td align="left"><input name="txt_confirm" type="password" class="line_3" id="txt_confirm" value="<?php if (isset($show_user)) echo $show_user['util_pwd']; ?>" size="35"/></td> </tr> <tr> <td height="30" align="left" class="txt_1"> Groupe User </td> <td align="left"><label><?php if (isset($show_user)) $id = $show_user['dom_id']; else $id=''; echo select_domaine($name='select_group',$id,$sub=0, 'line_4'); ?></label></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left" class="token_1"> </td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_4"> <tr> <td width="14%" align="left">&nbsp;</td> <td width="86%" align="left"><label> <input name="sub_user" type="submit" class="sssabir" id="sub_user" value="Envoyer" /> </label></td> </tr> </table></td> </tr> </form> </table></td> </tr> </table> <?php } else { ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="50%" align="left" class="big_3">Liste des Utilisateurs </td> <td width="50%" align="right" class="txt_1g"><table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="important_2"> <form id="form1" name="form1" method="post" action=""> <tr> <td align="right" class="txt_2">Chercher :<span class="txt_1"> Par Nom </span> <label> <input name="txt_search" type="text" id="txt_search" value="<?php if (!empty($keyword)) echo $keyword; ?>" onclick="this.value=''"/> <input name="sub_search" type="submit" id="sub_search" class="sssabir" value="Chercher" /> </label></td> </tr> </form> </table></td> </tr> </table> <table width="100%" height="6" border="0" cellspacing="0" cellpadding="0" background="../image/design/fond_inter.png"> <tr> <td></td> </tr> </table> <table width="100%" height="30" border="0" cellpadding="0" cellspacing="0" class="txt_444"> <tr> <td width="4%" align="center">N&deg;</td> <td width="22%" align="left">Login </td> <td width="40%" align="left">Nom user </td> <td width="23%" align="left"> <table width="100%" height="28" border="0" cellpadding="0" cellspacing="0"> <form id="form2" name="form2" method="post" action=""> <tr> <td align="left"><?php echo select_domaine($name='sortby_group',$sortby,$sub=1, 'line_4'); ?></td> </tr> </form> </table> </td> <td width="11%" align="center">Options</td> </tr> </table> <div id="zone_list"><?php echo list_user($keyword,$sortby,$authorization[19],$authorization[20]); ?></div> </td> </tr> </table> <?php } ?></td> </tr> </table></td> </tr> </table> </body> </html>
27c0024c99d7ecd75059100a4963bad8ca845534
[ "JavaScript", "SQL", "PHP" ]
19
PHP
FERTAHISAAD/Test
5993db80ea85a4d088e79ae207778a2bb0b8533c
20bfc50eba9b3ae5d5398c260dcfe7a9949b9d14
refs/heads/main
<file_sep>Fast Campus Data Science School 17th <b> Regression project </b> # Regression for factors affecting Life Expectancy🧬 <img src="https://img.shields.io/badge/Python-3766AB?style=flat-square&logo=Python&logoColor=white"/></a> <img src="https://img.shields.io/apm/l/vim-mode"/> ## :pencil: 개요 ### 1️⃣ 주제 선정 동기 - Covid 19로 건강에 대한 관심 ↑ - 100세 시대를 코 앞에 두고 있는 요즘, 어떤 요인이 장수에 영향을 미치는지 탐구해보자 <!-- - ※ 기대 수명이란? - 특정 시기에 태어난 인구의 예상되는 수명 --> ### 2️⃣ 프로젝트 목적 - 기대 수명과 연관된 요인 분석 - 다중 선형 회귀 기반 회귀 모델 공식화 - 개발도상국 등 기대 수명이 낮은 국가 대상, 기대 수명이 낮은 이유 및 수명 제고 방안 분석 ### 3️⃣ Dataset - [Kaggle "Life-Expextancy (WHO)](https://www.kaggle.com/kumarajarshi/life-expectancy-who) - 2000~2015년 193개국의 기대수명 및 관련 요인 데이터셋 - 종속변수(Target): Life expactancy - 독립변수(Features): 경제, 사회 (예방접종, 교육 등), 사망률 등 19개 요인 - [THE WORLD BANK](https://www.worldbank.org/en/home) - GDP per capita, Death rates, Population 등 결측치 처리 및 추가용 자료 수집 ## 📈 Modeling - Pipeline & GridSearchCV <div> <img width="345" src="https://user-images.githubusercontent.com/71582831/119071725-4e96e400-ba25-11eb-9de2-a8ed4f6249d9.png"> <img width="490" alt="model_result" src="https://user-images.githubusercontent.com/71582831/118845152-7e9b9580-b906-11eb-8448-e5f4bd538049.png"></div> - Predict - 2019년 한국 기대수명: 83세 - Linear Regression Predicted: 81.35세 - Results visualization <div> <img width="500" alt="linear_results" src="https://user-images.githubusercontent.com/71582831/118846047-49437780-b907-11eb-9a6c-7ff9043aeffa.png"> <img width="500" alt="randomforest_results" src="https://user-images.githubusercontent.com/71582831/118846172-69733680-b907-11eb-9c73-82941920e573.png"></div> <br> ## 🔎 EDA #### Life expectancy와 높은 상관관계를 가지는 Features - 양의 상관관계: 교육 정도(Schooling) 0.8, 자원의 소득 구성(Income composition of resources) 0.8 - 음의 상관관계: 영아 사망률(Infant deaths) -0.9, 성인 사망률(Adult mortality) -0.7 <img width="500" alt="heatmap_new" src="https://user-images.githubusercontent.com/71582831/118845035-63308a80-b906-11eb-97e3-f1ae3ca98d77.png"> #### Status에 따른 국가별 Features 분포 - Developed(Status 1 - Deep color) / Developing (Status 0 - Light color) - Life expectancy <div><img width="700" src= "https://user-images.githubusercontent.com/71582831/119067183-76357e80-ba1c-11eb-839d-3c90f263789c.png"></div> - Life expectancy 상위/하위 10% 국가들 비교 - Life expectancy와 양의 상관관계를 가진 Features: Developed 국가가 상위권을 차지 - Life expectancy와 음의 상관관계를 가진 Features: Developing 국가가 상위권을 차지 <div><img width="350" src= "https://user-images.githubusercontent.com/71582831/119073677-b4389f80-ba28-11eb-98d1-ca33de326c9d.png"> <img width="350" src= "https://user-images.githubusercontent.com/71582831/119073681-b569cc80-ba28-11eb-9379-59c6d370a605.png"> <img width="350" src= "https://user-images.githubusercontent.com/71582831/119073836-ecd87900-ba28-11eb-80ec-eee1a54efb41.png"> <img width="350" src= "https://user-images.githubusercontent.com/71582831/119073841-ee09a600-ba28-11eb-9dc5-d38908014a92.png"></div> ## 👩🏻‍🤝‍🧑🏻 Contributors - [Se<NAME>](https://github.com/SeyoungKo) & [<NAME>](https://github.com/HyunjinKIM-Chloe) <img width="300" src="https://user-images.githubusercontent.com/71582831/118420774-aae2c680-b6fa-11eb-87c9-9b14e002eced.gif"> <file_sep># 데이터 저장 경로 PATH = '../datas/' # 대분류 카테고리별 컬럼 구분 CAT = {'economy': ['PERCENTAGE_EXPENDITURE', 'TOTAL_EXPENDITURE', 'GDP', 'POPULATION', 'INCOME_COMPOSITION_OF_RESOURCES'], 'death_rate': ['INFANT_DEATHS', "ADULT_MORTALITY", 'UNDER_FIVE_DEATHS'], 'illness_rate': ['THINNESS_1_19_YEARS', 'THINNESS_5_9_YEARS', 'MEASLES', 'HIV/AIDS'], 'vaccine': ['HEPATITIS_B', 'POLIO', 'DIPHTHERIA'], 'others': ['SCHOOLING', 'BMI', 'ALCOHOL']} # Region to Integer REGION = {'South Asia': 0, 'Europe & Central Asia': 1, 'Middle East & North Africa': 2, 'Sub-Saharan Africa': 3, 'Latin America & Caribbean': 4, 'East Asia & Pacific': 5, 'North America': 6} # Grid params GRID_DICT = { 0: 'Linear Regression', 1: 'Decison Tree Regressor', 2: 'Lasso', 3: 'Ridge', 4: 'PCA Regression', 5: 'PLS Regression', 6: "Gradient Boosting Regressor", 7: "XGBoost Regressor", 8: "Random Forest Regressor", 9: "Support Vector Regressor", 10: "Kernel Ridge Regression" }<file_sep>absl-py==0.12.0 appnope==0.1.2 argon2-cffi==20.1.0 arviz @ file:///tmp/build/80754af9/arviz_1614019183254/work astunparse==1.6.3 async-generator==1.10 attrs==20.3.0 Automat==20.2.0 backcall==0.2.0 beautifulsoup4 @ file:///home/linux1/recipes/ci/beautifulsoup4_1610988766420/work bleach==3.3.0 bokeh @ file:///opt/concourse/worker/volumes/live/5a312fdd-9516-439e-63a9-67fcf2e3dee8/volume/bokeh_1617827440191/work branca==0.4.2 brotlipy==0.7.0 cachetools==4.2.1 certifi==2020.12.5 cffi @ file:///opt/concourse/worker/volumes/live/ca3c0fea-9d0f-4489-6889-89b42078ed37/volume/cffi_1613246931142/work cftime @ file:///opt/concourse/worker/volumes/live/19aa8553-ef83-4f8e-40da-167f8acd0344/volume/cftime_1613248241482/work chardet @ file:///opt/concourse/worker/volumes/live/9efbf151-b45b-463d-6340-a5c399bf00b7/volume/chardet_1607706825988/work click @ file:///home/linux1/recipes/ci/click_1610990599742/work click-plugins==1.1.1 cligj==0.7.1 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1598884132938/work colourmap==0.1.1 constantly==15.1.0 convertdate @ file:///home/conda/feedstock_root/build_artifacts/convertdate_1615678826465/work cryptography @ file:///opt/concourse/worker/volumes/live/cdf8ff17-b0bf-4081-524c-b5a0afe929ba/volume/cryptography_1616769280208/work cssselect==1.1.0 cycler==0.10.0 Cython @ file:///opt/concourse/worker/volumes/live/203a63af-5d69-4f3f-44a3-6968eb710a6a/volume/cython_1618435144870/work cytoolz==0.11.0 dask @ file:///tmp/build/80754af9/dask-core_1615055117017/work decorator==4.4.2 defusedxml==0.7.1 distributed @ file:///opt/concourse/worker/volumes/live/82f02f52-d725-4053-413b-163900425318/volume/distributed_1617384070915/work entrypoints==0.3 ephem @ file:///opt/concourse/worker/volumes/live/5288f9c0-a149-4319-62bf-67fcb07432b3/volume/ephem_1600355405696/work et-xmlfile==1.0.1 fbprophet @ file:///Users/runner/miniforge3/conda-bld/fbprophet_1599365544983/work Fiona==1.8.19 Flask @ file:///home/ktietz/src/ci/flask_1611932660458/work flatbuffers==1.12 folium==0.12.1 fsspec @ file:///tmp/build/80754af9/fsspec_1617959894824/work gast==0.3.3 geopandas @ git+git://github.com/geopandas/geopandas.git@<PASSWORD> gmpy2==2.0.8 google-auth==1.29.0 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 graphviz==0.16 grpcio==1.32.0 h2==3.2.0 h5py==2.10.0 HeapDict==1.0.1 hijri-converter @ file:///home/conda/feedstock_root/build_artifacts/hijri-converter_1612531902526/work holidays @ file:///home/conda/feedstock_root/build_artifacts/holidays_1612548464349/work hpack==3.0.0 hyperframe==5.2.0 hyperlink==21.0.0 idna @ file:///home/linux1/recipes/ci/idna_1610986105248/work imageio==2.9.0 imbalanced-learn==0.8.0 importlib-metadata==3.7.3 incremental==21.3.0 ipykernel==5.5.0 ipython==7.21.0 ipython-genutils==0.2.0 ipywidgets==7.6.3 itemadapter==0.2.0 itemloaders==1.0.4 itsdangerous @ file:///tmp/build/80754af9/itsdangerous_1621432558163/work jdcal==1.4.1 jedi==0.18.0 Jinja2 @ file:///tmp/build/80754af9/jinja2_1612213139570/work jmespath==0.10.0 joblib @ file:///tmp/build/80754af9/joblib_1613502643832/work JPype1==1.2.1 jsonschema==3.2.0 jupyter==1.0.0 jupyter-client==6.1.12 jupyter-console==6.2.0 jupyter-core==4.7.1 jupyterlab-pygments==0.1.2 jupyterlab-widgets==1.0.0 Keras==2.4.3 Keras-Preprocessing==1.1.2 kiwisolver @ file:///opt/concourse/worker/volumes/live/1e6d28e8-da14-4365-7344-567a05db7efc/volume/kiwisolver_1612282399491/work korean-lunar-calendar @ file:///home/conda/feedstock_root/build_artifacts/korean_lunar_calendar_1589354365811/work lightgbm==3.2.0 locket==0.2.1 LunarCalendar==0.0.9 lxml==4.6.3 macropy3==1.1.0b2 Markdown==3.3.4 MarkupSafe==1.1.1 matplotlib @ file:///opt/concourse/worker/volumes/live/41e8cd50-031f-4dda-5787-dd3c4f4e0f08/volume/matplotlib-suite_1613407855571/work missingno @ file:///tmp/build/80754af9/missingno_1605824147679/work mistune==0.8.4 mkl-fft==1.3.0 mkl-random @ file:///opt/concourse/worker/volumes/live/45391dab-1d51-4226-600a-9065613b835f/volume/mkl_random_1618853975662/work mkl-service==2.3.0 mlxtend==0.18.0 mpmath==1.2.1 msgpack @ file:///opt/concourse/worker/volumes/live/790199ef-c7e3-451c-7ad3-97c9dd52a04d/volume/msgpack-python_1612287158473/work munch==2.5.0 nbclient==0.5.3 nbconvert==6.0.7 nbformat==5.1.2 nest-asyncio==1.5.1 netCDF4 @ file:///opt/concourse/worker/volumes/live/036bf26e-3598-4e54-730a-657eff007636/volume/netcdf4_1613684171674/work networkx==2.5.1 nltk @ file:///home/conda/feedstock_root/build_artifacts/nltk_1616505766995/work notebook==6.2.0 numpy @ file:///opt/concourse/worker/volumes/live/13cc042b-807c-4cce-4706-4129165bc64e/volume/numpy_and_numpy_base_1618497232858/work oauthlib==3.1.0 olefile==0.46 openpyxl @ file:///tmp/build/80754af9/openpyxl_1615411699337/work opt-einsum==3.3.0 packaging @ file:///tmp/build/80754af9/packaging_1611952188834/work pandas==1.2.4 pandocfilters==1.4.3 parsel==1.6.0 parso==0.8.1 partd @ file:///tmp/build/80754af9/partd_1618000087440/work patsy==0.5.1 pca==1.5.0 pexpect==4.8.0 pickleshare==0.7.5 Pillow @ file:///opt/concourse/worker/volumes/live/0aff898a-aba9-4321-76c2-58d629e96356/volume/pillow_1617386155885/work plotly==4.14.3 plotly-express==0.4.1 prettytable==2.1.0 priority==1.3.0 prometheus-client==0.9.0 prompt-toolkit==3.0.17 Protego==0.1.16 protobuf==3.15.8 psutil @ file:///opt/concourse/worker/volumes/live/8e01e0e9-ea07-4efa-7afb-fae37c1b9faa/volume/psutil_1612298009056/work ptyprocess==0.7.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser @ file:///tmp/build/80754af9/pycparser_1594388511720/work PyDispatcher==2.0.5 pyecharts==1.9.0 Pygments==2.8.1 PyMeeus @ file:///home/conda/feedstock_root/build_artifacts/pymeeus_1615809745702/work pyOpenSSL @ file:///tmp/build/80754af9/pyopenssl_1608057966937/work pyparsing @ file:///home/linux1/recipes/ci/pyparsing_1610983426697/work pyproj==2.6.1.post1 pyrsistent==0.17.3 PySocks @ file:///opt/concourse/worker/volumes/live/ef943889-94fc-4539-798d-461c60b77804/volume/pysocks_1605305801690/work pystan @ file:///opt/concourse/worker/volumes/live/229217d9-d181-4bb6-603d-ab129f3eb1da/volume/pystan_1613565291325/work python-dateutil @ file:///home/ktietz/src/ci/python-dateutil_1611928101742/work pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work PyWavelets==1.1.1 PyYAML==5.4.1 pyzmq==22.0.3 qtconsole==5.0.2 QtPy==1.9.0 queuelib==1.6.1 regex @ file:///opt/concourse/worker/volumes/live/e6eeb005-ec8b-451a-7c56-1e24b2d15761/volume/regex_1617569708726/work requests @ file:///tmp/build/80754af9/requests_1608241421344/work requests-oauthlib==1.3.0 retrying==1.3.3 rise==5.7.1 rsa==4.7.2 scikit-image==0.18.1 scikit-learn==0.24.1 scipy @ file:///opt/concourse/worker/volumes/live/a038d231-fbb5-4cf5-6b71-513b1c94ddce/volume/scipy_1618855950518/work Scrapy==2.5.0 seaborn @ file:///tmp/build/80754af9/seaborn_1608578541026/work selenium @ file:///opt/concourse/worker/volumes/live/ce617773-1849-4851-6e61-21e69dc5e189/volume/selenium_1614267784770/work Send2Trash==1.5.0 service-identity==21.1.0 Shapely==1.7.1 simplejson==3.17.2 six @ file:///opt/concourse/worker/volumes/live/f983ba11-c9fe-4dff-7ce7-d89b95b09771/volume/six_1605205318156/work sklearn==0.0 sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1606865132123/work soupsieve @ file:///tmp/build/80754af9/soupsieve_1616183228191/work statsmodels==0.12.2 sympy @ file:///opt/concourse/worker/volumes/live/347e855c-d365-447b-5b46-aa042092978f/volume/sympy_1608137682049/work tblib @ file:///tmp/build/80754af9/tblib_1597928476713/work tensorboard==2.4.1 tensorboard-plugin-wit==1.8.0 tensorflow==2.4.1 tensorflow-estimator==2.4.0 termcolor==1.1.0 terminado==0.9.2 testpath==0.4.4 threadpoolctl==2.1.0 tifffile==2021.4.8 toolz @ file:///home/linux1/recipes/ci/toolz_1610987900194/work tornado @ file:///opt/concourse/worker/volumes/live/d531d395-893c-4ca1-6a5f-717b318eb08c/volume/tornado_1606942307627/work tqdm @ file:///tmp/build/80754af9/tqdm_1615925068909/work traitlets==5.0.5 Twisted==21.2.0 typing-extensions @ file:///home/ktietz/src/ci_mi/typing_extensions_1612808209620/work urllib3 @ file:///tmp/build/80754af9/urllib3_1615837158687/work w3lib==1.22.0 wcwidth==0.2.5 webencodings==0.5.1 Werkzeug @ file:///home/ktietz/src/ci/werkzeug_1611932622770/work wget==3.2 widgetsnbextension==3.5.1 wrapt==1.12.1 xarray @ file:///tmp/build/80754af9/xarray_1614625053385/work xgboost==1.3.3 xlrd==2.0.1 XlsxWriter @ file:///home/ktietz/src/ci_ipy2/xlsxwriter_1612556818988/work zict==2.0.0 zipp==3.4.1 zope.interface==5.4.0 <file_sep>from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet from sklearn.linear_model import LassoCV , ElasticNetCV , RidgeCV from sklearn.pipeline import Pipeline, FeatureUnion import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import r2_score as r2 from sklearn.model_selection import cross_val_score, KFold, ShuffleSplit, GridSearchCV from sklearn.ensemble import GradientBoostingRegressor as GBR from xgboost import XGBRegressor as XGBR from sklearn.tree import DecisionTreeRegressor as DTR from sklearn.ensemble import RandomForestRegressor as RFR from sklearn.preprocessing import PolynomialFeatures from sklearn.decomposition import PCA from sklearn.cross_decomposition import PLSRegression as PLS from sklearn.svm import SVR from sklearn.kernel_ridge import KernelRidge from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler from plotly.offline import plot, iplot, init_notebook_mode import plotly.io as pio init_notebook_mode(connected=True) pio.renderers.default = "notebook_connected" import pandas as pd import numpy as np import time import pickle import joblib import constant original = pd.read_csv(constant.PATH + 'life_expectancy_data_fillna.csv') class ModelPipeline: def pipe_model(self): pipe_linear = Pipeline([ ('scl', StandardScaler()), ('poly', PolynomialFeatures()), ('fit', LinearRegression())]) pipe_tree = Pipeline([ ('scl', StandardScaler()), ('fit', DTR())]) pipe_lasso = Pipeline([ ('scl', StandardScaler()), ('poly', PolynomialFeatures()), ('fit', Lasso(random_state=13))]) pipe_ridge = Pipeline([ ('scl', StandardScaler()), ('poly', PolynomialFeatures()), ('fit', Ridge(random_state=13))]) pipe_pca = Pipeline([ ('scl', StandardScaler()), ('pca', PCA()), ('fit', LinearRegression())]) pipe_pls = Pipeline([ ('scl', StandardScaler()), ('fit', PLS())]) pipe_gbr = Pipeline([ ('scl', StandardScaler()), ('fit', GBR())]) pipe_xgbr = Pipeline([ ('scl', StandardScaler()), ('fit', XGBR(random_state=13))]) pipe_rfr = Pipeline([ ('scl', StandardScaler()), ('fit', RFR(random_state=13))]) pipe_svr = Pipeline([ ('scl', StandardScaler()), ('fit', SVR())]) pipe_KR = Pipeline([ ('scl', StandardScaler()), ('fit', KernelRidge())]) return [pipe_linear, pipe_tree, pipe_lasso, pipe_ridge, pipe_pca, pipe_pls, pipe_gbr, pipe_xgbr, pipe_rfr, pipe_svr, pipe_KR] def grid_params(self, max_depth, split_range): max_depth = max_depth min_samples_split_range = split_range grid_params_linear = [{ "poly__degree": np.arange(1, 3), "fit__fit_intercept": [True, False] }] grid_params_tree = [{ }] grid_params_lasso = [{ "poly__degree": np.arange(1, 3), "fit__tol": np.logspace(-5, 0, 10), "fit__alpha": np.logspace(-5, 1, 10) }] grid_params_ridge = [{ "poly__degree": np.arange(1, 3), "fit__alpha": np.linspace(2, 5, 10), "fit__solver": ["cholesky", "lsqr", "sparse_cg"], "fit__tol": np.logspace(-5, 0, 10) }] grid_params_pca = [{ "pca__n_components": np.arange(2, 8) }] grid_params_pls = [{ "fit__n_components": np.arange(2, 8) }] grid_params_gbr = [{ "fit__max_features": ["sqrt", "log2"], "fit__loss": ["ls", "lad", "huber", "quantile"], "fit__max_depth": max_depth, "fit__min_samples_split": min_samples_split_range }] grid_params_xgbr = [{ "fit__max_features": ["sqrt", "log2"], "fit__loss": ["ls", "lad", "huber", "quantile"], "fit__max_depth": max_depth, "fit__min_samples_split": min_samples_split_range }] grid_params_rfr = [{ }] grid_params_svr = [{ "fit__kernel": ["rbf", "linear"], "fit__degree": [2, 3, 5], "fit__gamma": np.logspace(-5, 1, 10) }] grid_params_KR = [{ "fit__kernel": ["rbf", "linear"], "fit__gamma": np.logspace(-5, 1, 10) }] return [grid_params_linear, grid_params_tree, grid_params_lasso, grid_params_ridge, grid_params_pca, grid_params_pls, grid_params_gbr, grid_params_xgbr, grid_params_rfr, grid_params_svr, grid_params_KR] def grid_cv(self, pipe, params): jobs = -1 cv = KFold(n_splits=5, shuffle=True, random_state=13) grid_dict = constant.GRID_DICT return jobs, cv, grid_dict def model_save(self, pipe, params, jobs, cv, grid_dict): model_rmse, model_r2, model_best_params, model_fit_times, model_res = {}, {}, {}, {}, {} for idx, (param, model) in enumerate(zip(params, pipe)): start_time = time.time() search = GridSearchCV(model, param, scoring="neg_mean_squared_error", cv=cv, n_jobs=jobs, verbose=-1) search.fit(X_train, y_train) y_pred = search.predict(X_test) model_rmse[grid_dict.get(idx)] = np.sqrt(mse(y_test, y_pred)) model_r2[grid_dict.get(idx)] = r2(y_test, y_pred) model_best_params[grid_dict.get(idx)] = search.best_params_ model_fit_times[grid_dict.get(idx)] = time.time() - start_time joblib.dump(search, f'../models/{grid_dict.get(idx)}.pkl') print("------- all Model Saved -------") return model_rmse, model_r2, model_best_params, model_fit_times # Modeling 결과 시각화 def model_res_barchart(self, res_df): fig, ax = plt.subplots(figsize=(20, 10)) sns.set(font_scale=2) ax = sns.barplot(y="Model", x="R2", data=res_df) return plt.show() # Modeling 결과 데이터프레임 저장 def model_res_df(self, model_r2, model_rmse, model_fit_times): output = pd.DataFrame([model_r2.keys(), model_r2.values(), model_rmse.values(), model_fit_times.values()], index=["Model", "R2", "RMSE", "Fit_times"]).T output.sort_values(["R2"], ascending=False, inplace=True) output['R2'] = [float(_) for _ in output['R2']] output['RMSE'] = [float(_) for _ in output['RMSE']] return output class Preprocessing: # 컬럼 추가 def add_feature(self, original, filename=None): path = constant.PATH + "worldbank_" original.columns = [cols.upper() for cols in original.columns.tolist()] if not filename == None: df = pd.read_csv(f"{path}{filename}.csv").groupby('Country Code').mean() df.drop(columns=['2016', '2017', '2018', '2019', '2020'], axis=1, inplace=True) col_name = filename.upper() original[col_name] = [df.loc[original['COUNTRYCODE'][i]][str(original['YEAR'][i])] for i in range(len(original))] return original def preprocessing(self, data): # GDP per capita 데이터 추가 data = self.add_feature(data, "gdppercap") # Nan값 GDP/POP으로 대체 data["GDPPERCAP"].fillna(data["GDP"] / data["POPULATION"], inplace=True) data.columns = [cols.upper() for cols in data.columns.tolist()] if 'STATUS' in data.columns.tolist(): data = pd.get_dummies(data, columns=['STATUS'], drop_first=True) return data # corr def get_top_features(self, data, drop_n=None): if drop_n is None: drop_n = len(data.columns) # LIFE_EXPECTANCY와 대한 나머지 feature들의 상관관계 corr_matrix = data.drop(['COUNTRYCODE', 'ISO3166', 'COUNTRY', 'YEAR', 'REGION', 'INCOMEGROUP'], axis=1).corr() corr_matrix['LIFE_EXPECTANCY'].sort_values(ascending=False) # LIFE_EXPECTANCY와 높은 상관관계를 가지는 피처 순 정렬 top_corr = abs(corr_matrix['LIFE_EXPECTANCY']).sort_values(ascending=False)[1:drop_n] top_features = top_corr.index.tolist() return top_features # lower fence, upper fence def get_fence(self, data, top_features): region = data['REGION'].unique().tolist() fence = {} for r in region: fence[r] = {} for i, f in enumerate(top_features): q1 = np.percentile(data[data['REGION'] == r][top_features[i]].values, 25) q3 = np.percentile(data[data['REGION'] == r][top_features[i]].values, 75) iqr = q3 - q1 upper_fence = ((iqr * 1.5) + q3).round(3) lower_fence = (q1 - (iqr * 1.5)).round(3) fence[r][f] = [lower_fence, upper_fence] return fence # outlier processing def drop_outlier(self, data, fence, top_features): region = data['REGION'].unique().tolist() drop_list, target_idx = [], [] for r in region: target_df = data[data['REGION'] == r] for f in top_features: drop_idx = target_df[(target_df[f] < fence[r][f][0]) | (target_df[f] > fence[r][f][1])].index.tolist() drop_list.append(drop_idx) # 제거 대상 인덱스 target_idx = set([idx for lst in drop_list for idx in lst]) data = data.drop(target_idx, axis=0) return data if __name__ == '__main__': # 데이터 전처리 p = Preprocessing() data = p.preprocessing(original) top_features = p.get_top_features(data, 5) fence = p.get_fence(data, top_features) prep_data = p.drop_outlier(data, fence, top_features) prep_data.reset_index(inplace=True, drop=True) # ======= Model Predict ======= # 모델 파이프라인 m = ModelPipeline() X = prep_data.drop(['COUNTRYCODE', 'ISO3166', 'COUNTRY', 'YEAR', 'LIFE_EXPECTANCY', 'REGION', 'INCOMEGROUP'], axis=1) y = prep_data['LIFE_EXPECTANCY'] X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, test_size=0.2, random_state=13) split_range = [0.5, 0.7, 0.9] max_depth = [2, 4, 6, 8] pipe = m.pipe_model() params = m.grid_params(max_depth, split_range) jobs, cv, grid_dict = m.grid_cv(pipe, params) model_rmse, model_r2, model_best_params, model_fit_times = m.model_save(pipe, params, jobs, cv, grid_dict) # ====== Model Predict Result ====== res_df = m.model_res_df(model_r2, model_rmse, model_fit_times) # 모델링 결과 데이터프레임 m.model_res_barchart(res_df) # 모델링 결과 시각화<file_sep>import matplotlib.pyplot as plt import plotly.express as px from sklearn import preprocessing from plotly.subplots import make_subplots import plotly.graph_objects as go import plotly.io as pio import pandas as pd import constant pd.options.plotting.backend = 'plotly' pio.renderers.default = "browser" pio.renderers.default = "notebook_connected" pd.set_option('display.max_row', 500) pd.set_option('display.max_columns', 100) class Preprocessing: def __init__(self, original): self.original = original def add_feature(self, filename=None): path = "../datas/worldbank_" original.columns = [cols.upper() for cols in original.columns.tolist()] # GDP per capita 데이터 추가 gdp_percap = pd.read_csv("../datas/worldbank_gdppercap.csv") gdp_percap = gdp_percap.groupby('Country Code').mean() gdp_percap.drop(columns=['2016', '2017', '2018', '2019', '2020'], axis=1, inplace=True) # life_df에 GDP per capita 컬럼 추가 original["GDP_PERCAP"] = [gdp_percap.loc[original['COUNTRYCODE'][i]][str(original['YEAR'][i])] for i in range(len(original))] original["GDP_PERCAP"].fillna(original["GDP"] / original["POPULATION"], inplace=True) if not filename == None: df = pd.read_csv(f"{path}{filename}.csv").groupby('Country Code').mean() df.drop(columns=['2016', '2017', '2018', '2019', '2020'], axis=1, inplace=True) col_name = filename.upper() original[col_name] = [df.loc[original['COUNTRYCODE'][i]][str(original['YEAR'][i])] for i in range(len(original))] return original def processing(self, data): # Nan값 GDP/POP으로 대체 data["GDPPERCAP"].fillna(data["GDP"] / data["POPULATION"], inplace=True) # Developing: 0, developed: 1 data["STATUS"] = [row.replace("Developing", "0") for row in data["STATUS"].tolist()] data["STATUS"] = [row.replace("Developed", "1") for row in data["STATUS"].tolist()] data["STATUS"] = [int(row) for row in data["STATUS"].tolist()] return data def corr_matrix(self, data): # 기대수명에 대한 나머지 feature들의 상관관계 corr_matrix = data.drop(['COUNTRYCODE', 'ISO3166', 'COUNTRY', 'YEAR', 'ISO3166', 'REGION', 'INCOMEGROUP'], axis=1).corr() corr_matrix['LIFE_EXPECTANCY'].sort_values(ascending=False) # LIFE_EXPECTANCY와 높은 상관관계를 가지는 피처 순 정렬 top_corr = abs(corr_matrix['LIFE_EXPECTANCY']).sort_values(ascending=False)[:6] top_features = top_corr.index.tolist() return top_features def minmax_scaling(self, data): # mix-max scaling scaled_data = pd.DataFrame(preprocessing.minmax_scale(data)) scaled_data.index = data.index scaled_data.columns = data.columns.tolist() return scaled_data def set_region_df(self, data, region): data = data.drop(['COUNTRYCODE'], axis=1) data = data.replace({'REGION': region}) # region별 dataframe 선언 regions_df = [pd.DataFrame(data=data[data['REGION'] == i]) for i in range(len(region))] # region별 연도에 따라 groupby year_merge_df = [regions_df[i].groupby('YEAR').mean().drop(['REGION', 'ISO3166'], axis=1) for i in range(len(region))] scaled_region_datas = [pd.DataFrame(data=self.minmax_scaling(year_merge_df[i])) for i in range(len(region))] return year_merge_df, scaled_region_datas def set_category(self, year_merge_df): # 리전별 대분류 카테고리로 구분한 데이터프레임 생성 cat_region_df, regions_df = [], [] for i in range(len(year_merge_df)): economy_df = year_merge_df[i][constant.CAT['economy']] death_df = year_merge_df[i][constant.CAT['death_rate']] illness_df = year_merge_df[i][constant.CAT['illness_rate']] vaccine_df = year_merge_df[i][constant.CAT['vaccine']] others_df = year_merge_df[i][constant.CAT['others']] regions_df.append(economy_df) regions_df.append(death_df) regions_df.append(illness_df) regions_df.append(vaccine_df) regions_df.append(others_df) cat_region_df.append(regions_df) regions_df = [] return cat_region_df class Visualization: def __init__(self, original): self.original = original # 전체 컬럼별 평균값에 대한 전체 연도 추이 그래프 def show_year_cols(self, year_df): plt.figure(figsize=(20, 5)) plt.title("Yearly Features Fluctuation", fontsize=15) for a in year_df.columns.tolist(): plt.plot(year_data.index, preprocessing.minmax_scale(year_df[a]), label=a) plt.xlabel("Year") plt.legend() return plt.show() # 대분류 카테고리별로 나눠본 전체 연도별 추이 plotly 그래프 def show_px_lines(self, scaled_data, category): plt.interactive(False) px.line(scaled_data[constant.CAT[category]]) return plt.show() # 각 컬럼별 전체 국가 연도별 평균 추이 plotly 그래프 def show_year_sep(self, scaled_data): # raw data의 연도별 feature 추이 lower_titles = [scaled_data.columns.tolist()[i].lower().capitalize().replace('_', ' ') for i in range(len(scaled_data.columns))] fig = make_subplots(rows=7, cols=3, subplot_titles=lower_titles) count = 0 for i in range(7): for j in range(3): if count == 19: break fig.add_trace(go.Scatter(x=scaled_data.index, y=scaled_data[scaled_data.columns[count]], name=scaled_data.columns[count], line=dict(width=3.5)), row=i + 1, col=j + 1) count += 1 fig.update_layout(title='Life Expectancy Feautre 연도별 추이', font_size=14, width=2500, height=2000, template="plotly_white") fig.update_annotations(font_size=18) return fig.show() # 전체 리전에 대한 컬럼 연도별 추이 plotly 그래프 def show_year_regions(self, target_region, rows, cols, regions_df): category = [] target_region_idx = constant.REGION[target_region] # 타겟 리전 데이터프레임 인덱스 for i in range(len(constant.REGION)): category.append(regions_df[i][target_region_idx]) lower_titles = [category[target_region_idx].columns.tolist()[i].lower().capitalize().replace('_', ' ') for i in range(len(category[target_region_idx].columns))] fig = make_subplots(rows=rows, cols=cols, subplot_titles=lower_titles) count = 0 colors = ['lightsteelblue', 'cornflowerblue', 'slateblue', 'darkviolet', 'plum', 'limegreen', 'mediumturquoise'] for i in range(rows): for j in range(cols): if count == len(category[target_region_idx].columns): break for k in range(len(constant.REGION)): flag = True if count == 0 else False fig.add_trace(go.Scatter(x=category[target_region_idx].index, y=category[k][category[k].columns[count]], name=list(constant.REGION.items())[k][0], showlegend=flag, marker=dict(color=colors[k]), line=dict(width=3)), row=i + 1, col=j + 1) count += 1 fig.update_layout(font_size=14, width=2800, height=900, template="plotly_white") fig.update_annotations(font_size=19) # return fig.show() # 기대수명과 1인당 GDP scatter plotly 그래프 def show_moving_scatter(self, data, size_target, animation_target, facet_col=None): px.scatter(data, x="GDP_PERCAP", y="LIFE_EXPECTANCY", animation_frame=animation_target, animation_group="COUNTRY", size=size_target, color="REGION", hover_name="COUNTRY", facet_col=facet_col, log_x=True, size_max=60, range_y=[40, 100]) # return fig.show() # 선진국 / 개발도상국으로 나라별 상관관계 높은 컬럼들의 수치 비교 plotly 그래프 def show_status_barchart(self, data): mean_df = data.groupby(['COUNTRY']).mean().round(3).drop(['YEAR'], axis=1) # top corr columns cols = ['LIFE_EXPECTANCY', 'INCOME_COMPOSITION_OF_RESOURCES', 'SCHOOLING', 'INFANT_DEATHS', 'ADULT_MORTALITY'] lower_cols = [col.lower().capitalize().replace('_', ' ') for col in cols] colors = ['Burg', 'Darkmint', 'Purp', 'Teal', 'Magenta'] for i in range(5): hdi_df = mean_df.sort_values(by=cols[i], ascending=False) fig = px.bar(hdi_df, x=hdi_df.index, y=hdi_df[cols[i]], color=hdi_df['STATUS'], barmode='group', color_continuous_scale=colors[i]) fig.update_layout( title_text=lower_cols[i], height=500, width=1000, template='plotly_white', font_color='grey' ) # return fig.show() if __name__ == '__main__': original = pd.read_csv(constant.PATH + 'life_expectancy_data_fillna.csv') original.columns = [cols.upper() for cols in original.columns.tolist()] p = Preprocessing(original) add_data = p.add_feature("gdppercap") pc_data = p.processing(original) top_features = p.corr_matrix(pc_data) year_merge_df, scaled_region_datas = p.set_region_df(pc_data, constant.REGION) cat_regions_df = p.set_category(year_merge_df) # 연도별로 groupby year_data = pc_data.groupby("YEAR").mean() v = Visualization(pc_data) v.show_year_cols(year_data) year_df = p.minmax_scaling(year_data) v.show_year_regions('South Asia', 2, 3, cat_regions_df) v.show_moving_scatter(pc_data, 'POPULATION', 'YEAR') v.show_status_barchart(pc_data) <file_sep>from sklearn.metrics import r2_score as r2 from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error as mse import pandas as pd import numpy as np import constant import joblib import model_pipeline import plotly.express as px original = pd.read_csv(constant.PATH + 'life_expectancy_data_fillna.csv') class ModelPredict: # 2019년 한국 데이터셋 def set_testset(self, data): testset = pd.DataFrame(columns=data.columns) new_dict = {'COUNTRYCODE': 'KOR', 'YEAR': 2019, 'STATUS_Developing': 0, 'LIFE_EXPECTANCY': 83, 'GDP': 1646739.22, 'GDPPERCAP': 31846.2, 'SCHOOLING': 14, 'INFANT_DEATHS': 3, 'ADULT_MORTALITY': 110, 'INCOME_COMPOSITION_OF_RESOURCES': 0.916, 'POPULATION': 51709000, } testset = testset.append(new_dict, ignore_index=True) testset.fillna(data.mean(), inplace=True) return testset # 컬럼 추가 def add_feature(self, original, filename=None): path = constant.PATH + "worldbank_" original.columns = [cols.upper() for cols in original.columns.tolist()] if not filename == None: df = pd.read_csv(f"{path}{filename}.csv").groupby('Country Code').mean() df.drop(columns=['2016', '2017', '2018', '2019', '2020'], axis=1, inplace=True) col_name = filename.upper() original[col_name] = [df.loc[original['COUNTRYCODE'][i]][str(original['YEAR'][i])] for i in range(len(original))] return original def preprocessing(self, data): # GDP per capita 데이터 추가 data = self.add_feature(data, "gdppercap") # Nan값 GDP/POP으로 대체 data["GDPPERCAP"].fillna(data["GDP"] / data["POPULATION"], inplace=True) data.columns = [cols.upper() for cols in original.columns.tolist()] if 'STATUS' in data.columns.tolist(): data = pd.get_dummies(original, columns=['STATUS'], drop_first=True) return data # 저장한 모델을 불러와 predict하는 함수 def model_predict(self, prep_data, model_idx, test_df): saved_model = joblib.load(f"../models/{constant.GRID_DICT.get(model_idx)}.pkl") X = prep_data.drop(['COUNTRYCODE', 'ISO3166', 'COUNTRY', 'YEAR', 'LIFE_EXPECTANCY', 'REGION', 'INCOMEGROUP'], axis=1) y = prep_data['LIFE_EXPECTANCY'] X_pr = test_df[X.columns] y_pr = test_df['LIFE_EXPECTANCY'] y_pred = saved_model.predict(X_pr) # r2_score = r2(y_pr, y_pred) print(f"{constant.GRID_DICT.get(model_idx)} | 예측 기대 수명:{y_pred.mean().round(2)} / RMSE:, {np.sqrt(mse(y_pr, y_pred)).round(2)}") # if r2_score is True: # print("저장된 모델들의 R2:", r2_score) return X # 추가 데이터 예측 결과 def extra_predict(self, extra_df): for idx, model_idx in enumerate(range(len(constant.GRID_DICT))): X = self.model_predict(prep_data, model_idx, extra_df) return X class Visualization(): def split_data(self, prep_data, X): data_df = pd.concat([prep_data[X.columns], prep_data['LIFE_EXPECTANCY']], axis=1) X = data_df[X.columns] y = data_df['LIFE_EXPECTANCY'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13) data_df['split'] = 'train' data_df.loc[X_test.index, 'split'] = 'test' return (X_train, X_test), (y_train, y_test), data_df # reg plot 함수 def reg_plotly(self, prep_data, X, model_idx): model = joblib.load(f"../models/{constant.GRID_DICT.get(model_idx)}.pkl") X, y, data_df = self.split_data(prep_data, X) model.fit(X[0], y[0]) y_pred = model.predict(X) data_df['prediction'], data_df['y_test'], data_df['y_train'] = y_pred, y[1], y_pred fig = px.scatter( data_df, x=data_df['LIFE_EXPECTANCY'], y=data_df['prediction'], marginal_y='histogram', color='split', title=f"{constant.GRID_DICT.get(model_idx)} Model", color_discrete_sequence=['red', 'cornflowerblue']) fig.update_traces(histnorm='probability', selector={'type': 'histogram'}) fig.add_shape(type='line', line=dict(dash='dash'), x0=y.min(), y0=y.min(), x1=y.max(), y1=y.max() ) fig.update_layout(font_size=14, width=1000, height=600, template='plotly_white') # return fig.show() if __name__ == '__main__': pp = model_pipeline.Preprocessing() pipe = model_pipeline.ModelPipeline() mp = ModelPredict() data = pp.preprocessing(original) top_features = pp.get_top_features(data, 5) fence = pp.get_fence(data, top_features) prep_data = pp.drop_outlier(data, fence, top_features) prep_data.reset_index(inplace=True, drop=True) kor_df = mp.set_testset(original) X = mp.extra_predict(kor_df) v = Visualization() # v.reg_plotly(prep_data, X, model_idx=0)
d62e0bb18cc322aa88c68a7222cbce11ce1ddaa2
[ "Markdown", "Python", "Text" ]
6
Markdown
HyunjinKIM-Chloe/Regression_LifeExpectancy
d11169f729c4525d905cf2c158f20938dfb449a0
0be9aa7e155e65e8c720b50562b9a5783f511cf9
refs/heads/master
<file_sep>package Ister6; public abstract class ImageProcessing { public abstract void doImageProcessing(); } <file_sep>package Ister6; public class ImageProcessingAdapter extends ImageProcessing{ private final ImageProcessingAlgorithm2 imageProcessingAlgorithm2 = new ImageProcessingAlgorithm2(); @Override public void doImageProcessing() { imageProcessingAlgorithm2.performImageProcessing(); } } <file_sep>package Ister4; public class Client { public static void main(String[] args) { CommandManager commandManager = new ConcreteCommandManager(); IPlugin1 plugin1 = new IPlugin1(); IPlugin2 plugin2 = new IPlugin2(); plugin1.performAction(); plugin2.performAction(); commandManager.attach(plugin1, commandManager); System.out.println("\n> IPlugin1 is activated"); commandManager.setMRIState("HEAD_SCAN"); commandManager.attach(plugin2, commandManager); System.out.println("\n> IPlugin2 is activated"); commandManager.setMRIState("FOOT_SCAN"); commandManager.detach(plugin1); System.out.println("\n> IPlugin1 is now an deactivated."); commandManager.setMRIState("HEAD_SCAN"); } } <file_sep>package Ister11; abstract public class AbstractStatementBuilderFactory { public abstract StatementBuilder createStatementBuilder(); public abstract PreparedStatementBuilder createPreparedStatementBuilder(); } <file_sep>package Ister3; public class Processing extends ImageProcessing{ @Override public void doImageProcessing() { System.out.println("doImageProcessing is called in Processing"); } } <file_sep>package Ister1; abstract class ImageProcessing { abstract void doImageProcessing(IpluginContext ipluginContext); } <file_sep>package Ister1; public class ImageProcessingStrategy1 extends ImageProcessing { @Override void doImageProcessing(IpluginContext ipluginContext) { System.out.println("The context is: "+ ipluginContext + " and currently running ImageProcessingStrategy1"); } } <file_sep>package Ister11; public class MySqlPreparedStatementBuilder extends PreparedStatementBuilder{ @Override public String find(int index) { return "MySql find Query"; } @Override public String delete(int index) { return "MySql delete Query"; } @Override public String update(int index) { return "MySql update Query"; } @Override public String insert(int index) { return "MySql insert Query"; } } <file_sep>package Ister4; import java.util.ArrayList; public abstract class CommandManager { private final ArrayList<CommandReceiver> Plugins = new ArrayList<>(); public void attach(CommandReceiver commandReceiver, CommandManager commandManager){ commandReceiver.setCommandManager(commandManager); this.Plugins.add(commandReceiver); } public void detach(CommandReceiver commandReceiver){ this.Plugins.remove(commandReceiver); commandReceiver.setCommandManager(null); } public void notifyPlugins(){ for(CommandReceiver plugin : Plugins){ plugin.performAction(); } } public abstract String getMRIState(); public abstract void setMRIState(String newState); } <file_sep>package Ister11; public class MongoDbPreparedStatementBuilder extends PreparedStatementBuilder{ @Override public String find(int index) { return "MongoDB find Query"; } @Override public String delete(int index) { return "MongoDB delete Query"; } @Override public String update(int index) { return "MongoDB update Query"; } @Override public String insert(int index) { return "MongoDB insert Query"; } } <file_sep>package Ister1; public class CommandReceiver { public static void main(String[] args) { IPlugin plugin = new IPlugin(null); plugin.performAction(IpluginContext.HEAD_SCAN); plugin.performAction(IpluginContext.FOOT_SCAN); } } <file_sep>package Ister6; public class CommandReceiver { public static void main(String[] args) { IPlugin iPlugin = new IPlugin(); System.out.println("Calling perfromAction1:"); iPlugin.perfromAction1(); System.out.println("Calling perfromAction2:"); iPlugin.perfromAction2(); } } <file_sep>package Ister4; public abstract class CommandReceiver { public abstract void performAction(); abstract void setCommandManager(CommandManager commandManager); } <file_sep>package Ister11; public class DatabaseManager { private static int index = 0; public static String getDatabaseType(){ String[] supportedDatabaseTypes = {"MongoDB", "MySql"}; return supportedDatabaseTypes[index++]; } public static void main(String[] args) { System.out.println("> Changing the database to MongoDB and running client code."); clientCode(); System.out.println("> Changing the database to MySql and running the client code again"); clientCode(); } public static void clientCode(){ String currentDatabaseType = getDatabaseType(); AbstractStatementBuilderFactory abstractStatementBuilderFactory; if (currentDatabaseType.equals("MongoDB")){ abstractStatementBuilderFactory = new MongoDbStatementBuilderFactory(); }else if(currentDatabaseType.equals("MySql")){ abstractStatementBuilderFactory = new MySqlStatementBuilderFactory(); }else{ System.out.println("Unsupported Database type"); return; } StatementBuilder statementBuilder = abstractStatementBuilderFactory.createStatementBuilder(); PreparedStatementBuilder preparedStatementBuilder = abstractStatementBuilderFactory.createPreparedStatementBuilder(); System.out.println(statementBuilder.createStatement()); System.out.println(preparedStatementBuilder.insert(1)); System.out.println(preparedStatementBuilder.find(1)); System.out.println(preparedStatementBuilder.update(1)); System.out.println(preparedStatementBuilder.delete(1)); } }
6e24602883fd944616640cebaab7b96daf9d2b4a
[ "Java" ]
14
Java
Lumpus99/Bil401ProjectDemo
a8bb25202786457c9809f403f5a79db7ce9aa83e
7c316b9d562b886ed2b14da175fb3ccf0c4f276e
refs/heads/master
<file_sep>import pytest import requests import json from myapi import config import myapi.api.modules.product as product @pytest.mark.usefixtures('client', 'auth_header', 'example_product_json') class TestProductAPI: def test_get_non_existing_product(self, client): example_id = 0 r = client.get('/product/{}'.format(example_id)) json_data = r.get_json() assert r.status_code == 200 assert json_data == {} def test_no_product_id_supplied(self, client): r = client.get('/product') assert r.status_code == 400 def test_create_new_product(self, client, auth_header, example_product_json): r = client.put( '/product', data=json.dumps(example_product_json), headers=auth_header ) new_product_json_data = r.get_json() new_product_id = new_product_json_data['product_id'] # Check that the record in the db matches what we supplied r = client.get('/product/{}'.format(new_product_id)) json_data = r.get_json() assert r.status_code == 200 assert json_data['product_id'] == new_product_json_data['product_id'] assert json_data['name'] == new_product_json_data['name'] assert json_data['value'] == new_product_json_data['value'] # def test_product_id_field_in_get_response(self, client): # r = client.get('/product/{}'.format(example_id)) # json_data = r.get_json() # assert r.status_code == 200 # assert bool(json_data['product_id']) # def test_product_name_field_in_get_response(self, client): # example_id = 13860428 # r = client.get('/product/{}'.format(example_id)) # json_data = r.get_json() # assert r.status_code == 200 # assert bool(json_data['name']) # def test_product_value_field_in_get_response(self, client): # example_id = 13860428 # r = client.get('/product/{}'.format(example_id)) # json_data = r.get_json() # assert r.status_code == 200 # assert bool(json_data['value']) def test_response_for_non_numeric_product_id(self, client): """Used <int:product_id> when assigning the route to the api so giving string makes it think you're trying to find a diff url""" example_id = 'word' r = client.get('/product/{}'.format(example_id)) json_data = r.get_json() assert r.status_code == 404 def test_cannot_update_product_without_auth(self, client, example_product_json): r = client.put( '/product', data=json.dumps(example_product_json) ) assert r.status_code == 401 # def test_create_product_record_using_put(self, client, auth_header, example_product_json): # r = client.put( # '/product/{}'.format(example_product_json['id']), # data=json.dumps(example_product_json), # headers=auth_header # ) # # Check that the record in the db matches what we supplied # r = client.get('/product/{}'.format(example_product_json['id'])) # json_data = r.get_json() # assert r.status_code == 200 # assert int(json_data['id']) == example_product_json['id'] # assert json_data['name'] == example_product_json['name'] # assert float(json_data['current_price']['value']) == example_product_json['current_price']['value'] # assert json_data['current_price']['currency_code'] == example_product_json['current_price']['currency_code'] # def test_update_product_record_using_put(self, client, auth_header, example_product_json): # r = client.put( # '/product/{}'.format(example_product_json['id']), # data=json.dumps(example_product_json), # headers=auth_header # ) # # Change the record we just made # new_product_data = { # "id": 123456789, # "name": "<NAME>", # "current_price": { # "value": -10000, # "currency_code": "CAD" # } # } # r = client.put( # '/product/{}'.format(new_product_data['id']), # data=json.dumps(new_product_data), # headers=auth_header # ) # # Check that the record in the db matches what we supplied # r = client.get('/product/{}'.format(new_product_data['id'])) # json_data = r.get_json() # assert r.status_code == 200 # assert int(json_data['id']) == new_product_data['id'] # assert json_data['name'] == new_product_data['name'] # assert float(json_data['current_price']['value']) == new_product_data['current_price']['value'] # assert json_data['current_price']['currency_code'] == new_product_data['current_price']['currency_code'] # def test_delete_non_existing_product_record(self, client, example_product_json, auth_header): # r = client.delete( # '/product/{}'.format(example_product_json['id']), # data=json.dumps(example_product_json), # headers=auth_header # ) # assert r.status_code == 200 # assert r.get_json() == product.ProductAPIResponseMessages.no_product_to_delete(example_product_json['id']) # def test_delete_product_record(self, client, example_product_json, auth_header): # r = client.put( # '/product/{}'.format(example_product_json['id']), # data=json.dumps(example_product_json), # headers=auth_header # ) # r = client.delete( # '/product/{}'.format(example_product_json['id']), # data=json.dumps(example_product_json), # headers=auth_header # ) # assert r.status_code == 200 # assert r.get_json() == product.ProductAPIResponseMessages.product_deleted(example_product_json['id']) <file_sep>import pytest @pytest.mark.usefixtures('client') class TestHelloAPI: def test_get(self, client): r = client.get('/hello') assert r.status_code == 200 assert r.get_json() == {'hello': 'world'} def test_post(self, client): r = client.post('/hello') assert r.status_code == 200 assert r.get_json() == {'hello': 'world'} def test_put(self, client): r = client.put('/hello') assert r.status_code == 200 assert r.get_json() == {'hello': 'world'} def test_delete(self, client): r = client.delete('/hello') assert r.status_code == 200 assert r.get_json() == {'hello': 'world'} <file_sep>CREATE TABLE "public"."products" ( "product_id" INTEGER NOT NULL PRIMARY KEY, "name" VARCHAR(80) NOT NULL, "value" DECIMAL NOT NULL, "created_at" TIMESTAMPTZ NOT NULL );<file_sep>pytest pytest-flask pytest-runner pytest-factoryboy factory_boy pytest-cov requests<file_sep>from setuptools import setup, find_packages __version__ = '0.1' setup( name='myapi', version=__version__, packages=find_packages(exclude=['tests', 'sql', 'venv', 'docker-testing']), install_requires=[ 'flask', 'flask-sqlalchemy', 'flask-restful', 'flask-migrate', 'flask-jwt-extended', 'flask-marshmallow', 'flask-caching', 'flask-cors', 'flasgger', 'prometheus-flask-exporter', 'marshmallow-sqlalchemy', 'psycopg2', 'gunicorn' ] ) <file_sep>import json import pytest from myapi.app import create_app from myapi.extensions import db as _db from myapi import config @pytest.fixture def app(): _app = create_app(testing=True) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop() @pytest.fixture def client(): _app = create_app(testing=True) _client = _app.test_client() yield _client @pytest.fixture def db(app): _db.app = app with app.app_context(): _db.create_all() yield _db _db.session.close() _db.drop_all() @pytest.fixture def auth_header(client): data = { 'username': 'Us3rnam3', 'password': '<PASSWORD>' } r = client.post( '/auth', data=json.dumps(data), headers={'content-type': 'application/json'} ) token = r.get_json()['access_token'] return { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(token) } @pytest.fixture def example_product_json(): return { "name": "The Greatest Showman (Blu-ray + DVD + Digital)", "value": 19.99 } <file_sep>gunicorn --reload --config myapi/gunicorn_config.py "myapi.app:create_app()"<file_sep>[tox] envlis = py36 [testenv] deps= -r requirements/testing_requirements.txt -r requirements/requirements.txt commands= pytest tests --verbose --junitxml=pytest-results.xml --cov-report html --cov-report xml --cov-report term-missing --cov=myapi --color=yes<file_sep>import json from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from myapi.models import Product, ProductSchema from myapi import config from myapi.commons.log import log from myapi.commons.paginate import paginate from myapi.extensions import ma, db class ProductAPI(Resource): def __init__(self): # Json parser for creating/updating a product record product_parser = reqparse.RequestParser() product_parser.add_argument('name', type=str, required=True, help='No `name` supplied.', location='json') product_parser.add_argument('value', type=float, required=True, help='No `value` supplied.', location='json') self.product_parser = product_parser def get(self, product_id=None): """Handles GET requets""" if product_id == None: return ProductAPIResponseMessages.no_product_id_supplied(), 400 # Check our storage for the product product = Product.query.filter_by(product_id=product_id).first() log('got product {} from database'.format(product), 'debug') if product: return ProductAPIResponseMessages.product_record_info_json(product) return ProductAPIResponseMessages.no_product_with_id() @jwt_required def put(self, product_id=None): """Handles PUT requests""" # Gets the supplied args args = self.product_parser.parse_args() log('got arguments: {}'.format(args)) name = args.get('name') value = args.get('value') product = Product( product_id=product_id, name=name, value=value ).save() return ProductAPIResponseMessages.product_record_info_json(product) @jwt_required def delete(self, product_id): """Handles delete""" product = Product.query.filter_by(product_id=product_id).first() log('Got product to delete: {}'.format(product), 'debug') if product: product.delete() return ProductAPIResponseMessages.product_deleted(product_id) return ProductAPIResponseMessages.no_product_to_delete(product_id) class ProductsAPI(Resource): def get(self): product_list_schema = ProductSchema(many=True) query = Product.query return paginate(query, product_list_schema) # def post(self): # pass # def put(self): # pass # def delete(self): # pass class ProductAPIResponseMessages(object): """Common product api response messages.""" @staticmethod def product_record_info_json(product): product_schema = ProductSchema() return product_schema.dump(product).data @staticmethod def no_product_id_supplied(): return {'message': 'No product id supplied'} @staticmethod def no_product_with_id(): return {} @staticmethod def no_product_to_delete(product_id): return {'message': 'No product to delete with id: {}'.format(product_id)} @staticmethod def product_deleted(product_id): return {'message': 'Deleted product with id: {}'.format(product_id)} @staticmethod def not_implemented(): return {'message': 'Method not implemented'}<file_sep>from myapi.commons.log import log from myapi.commons.paginate import paginate __all__ = [ 'log', 'paginate' ] <file_sep>from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager from flask_marshmallow import Marshmallow from flask_migrate import Migrate from flask_caching import Cache from flask_cors import CORS from flasgger import Swagger from prometheus_flask_exporter import PrometheusMetrics db = SQLAlchemy() jwt = JWTManager() ma = Marshmallow() migrate = Migrate() cache = Cache() cors = CORS() swagger = Swagger() metrics = PrometheusMetrics(app=None) <file_sep>from flask import Flask from myapi import api, config from myapi.extensions import db, jwt, migrate, ma, cache, cors, swagger, metrics from myapi.api import api from myapi.commons.log import log def create_app(testing=False): app = Flask('myapi') log('Using base config: {}'.format(config.BaseConfig.__dict__), 'debug') if testing: _config = config.TestConfig else: _config = config.ProdConfig app.config.from_object(_config) log('Set app config using `{}` with values: {}'.format(_config.__name__, _config.__dict__), 'debug') register_extensions(app, testing) return app def register_extensions(app, testing=False): jwt.init_app(app) ma.init_app(app) cache.init_app(app) cors.init_app(app) swagger.init_app(app) api.init_app(app) # Getting: ValueError: Duplicated timeseries in CollectorRegistry: {'flask_http_request_duration_seconds_sum', 'flask_http_request_duration_seconds_count', 'flask_http_request_duration_seconds_bucket', 'flask_http_request_duration_seconds_created'} # Seems to be from virtualenv? if not testing: metrics.init_app(app) with app.app_context(): db.init_app(app) db.create_all() <file_sep>import datetime as dt from myapi.database import db, Model, SurrogatePK from myapi.extensions import ma class Product(Model): """Model for a product record""" __tablename__ = 'products' product_id = db.Column(db.Integer, unique=True, nullable=True, primary_key=True) name = db.Column(db.String(80), nullable=False) value = db.Column(db.Float, nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) def __init__(self, product_id=product_id, name=name, value=value, **kwargs): """Create instance.""" db.Model.__init__(self, product_id=product_id, name=name, value=value, **kwargs) def __repr__(self): return ( '<Product(' '{product_id},' '{name},' '{value},' '{created_at})>'.format( product_id=self.product_id, name=self.name, value=self.value, created_at=self.created_at ) ) class ProductSchema(ma.ModelSchema): class Meta: model = Product sqla_session = db.session <file_sep>Flask Flask-JWT-Extended flask-marshmallow Flask-Migrate Flask-RESTful Flask-SQLAlchemy flask-caching flask-cors flasgger prometheus-flask-exporter gunicorn marshmallow marshmallow-sqlalchemy psycopg2 SQLAlchemy tox <file_sep># Flask api template A small template to use as a starting point for a Flask api. # Table of Contents - [Flask api template](#flask-api-template) - [Table of Contents](#table-of-contents) - [Myapi Directory Structure](#myapi-directory-structure) - [Running the Application](#running-the-application) - [Deployment](#deployment) - [Testing](#testing) - [Credits](#credits) ## Myapi Directory Structure myapi ├── __init__.py ├── app.py : Main entrypoint for the app ├── config.py : Flask application configuration settings ├── gunicorn_config.py : Gunicorn configuration settings ├── database.py : Database convenience functions ├── extensions.py : Flask extensions and middleware ├── api : Main flask-restful api │   ├── endpoints.py : Different api classes mapped to http endpoints │   ├── __init__.py │   └── modules : Flask-restful api classes │   ├── __init__.py │   ├── auth.py │   ├── hello.py │   └── product.py ├── commons : Any common modules │   ├── __init__.py │   ├── log.py : Logging thats strapped to the gunicorn logger │   └── paginate.py : Pagination for querying └── models : Any database models ├── __init__.py └── product.py ## Running the Application The app can be run using either the Dockerfile, docker-compose file, or by intsalling the packages locally and using the run.sh file. The application will be running on port `8000`. Below is some basic information about the pre-configured url endpoints. | url | description | |:- |:- | | /hello | The hello api. | | /auth | Authorization api for JWT. | | /product | Product api for getting/updating/deleting a single product. | | /products | Products api for getting many products. | | /metrics | Exported application metridcs. | | /apidocs | Swagger api documentation. | ## Deployment The application can be deployed using a self hosting service with the `Dockerfile`. As an example this code was deployed using Heroku at the url `https://myapi-flask-template.herokuapp.com`. ## Testing Tests are run using the `tox` testing framework along with pytest. First install `tox`: ```sh pip install tox ``` Next run tox: ```sh tox ``` ### Credits Code inspired by some of the cookiecutter python projects out there like cookiecutter-flask and cookiecutter-flask-restful. <file_sep>from flask import Blueprint from flask_restful import Api from myapi.api.modules import ( HelloAPI, AuthAPI, ProductAPI, ProductsAPI ) api = Api() api.add_resource(HelloAPI, '/hello') api.add_resource(AuthAPI, '/auth') api.add_resource(ProductAPI, '/product', '/product/<int:product_id>') api.add_resource(ProductsAPI, '/products') <file_sep>SHELL := /bin/bash .PHONY: help help: @echo " clean" @echo " Cleans local files/dirs made when running code/testing/etc." @echo " test" @echo " Tests the app locally using tox." @echo " directory-tree" @echo " Creates a new tree representation of the myapi directory." .PHONY: clean clean: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + rm -rf htmlcov || true; rm -f coverage.xml || true; rm -f .coverage || true; rm -f pytest-results.xml || true; .PHONY: test test: clean tox .PNONY: directory-tree directory-tree: clean cd myapi;\ tree --prune;<file_sep>version: '3' services: myapi: build: context: . dockerfile: ./Dockerfile environment: LOG_LEVEL: debug PROCESSES: 1 SQLALCHEMY_DATABASE_URI: postgresql+psycopg2://user:password@postgres:5432/myapi_db ports: - 8000:8000 # Use postgres:password user:password credentials # https://hub.docker.com/_/postgres/ postgres: image: postgres restart: always environment: POSTGRES_USER: user POSTGRES_PASSWORD: <PASSWORD> POSTGRES_DB: myapi_db volumes: - ./sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql ports: - 5432:5432 # https://hub.docker.com/_/adminer/ adminer: image: adminer restart: always ports: - 8080:8080<file_sep>from myapi.models.product import ( Product, ProductSchema ) __all__ = [ 'Product', 'ProductSchema' ] <file_sep>FROM python:3.6-alpine # https://github.com/psycopg/psycopg2/issues/684 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev COPY myapi /app/myapi WORKDIR /app COPY requirements/requirements.txt /app RUN pip install -r requirements.txt CMD [ "gunicorn", "--config", "myapi/gunicorn_config.py", "myapi.app:create_app()" ]<file_sep>from flask_restful import Resource from flasgger.utils import swag_from class HelloAPI(Resource): @swag_from('../docs/hello.yml') def get(self): return {'hello': 'world'} @swag_from('../docs/hello.yml') def post(self): return {'hello': 'world'} @swag_from('../docs/hello.yml') def put(self): return {'hello': 'world'} @swag_from('../docs/hello.yml') def delete(self): return {'hello': 'world'} <file_sep>from .hello import HelloAPI from .auth import AuthAPI from .product import ProductAPI, ProductsAPI __all__ = [ 'HelloAPI', 'AuthAPI', 'ProductAPI', 'ProductsAPI' ] <file_sep>import json import pytest @pytest.mark.usefixtures('client') class TestAuthAPI: def test_post_to_auth_api_with_no_username(self, client): r = client.post('/auth') assert r.status_code == 400 def test_post_to_auth_api_with_no_password(self, client): creds = {'username': 'test'} headers = {'content-type': 'application/json'} r = client.post( '/auth', data=json.dumps(creds), headers=headers) assert r.status_code == 400 def test_post_to_auth_api_with_bad_username(self, client): creds = {'username': 'test', 'password': '<PASSWORD>'} headers = {'content-type': 'application/json'} r = client.post( '/auth', data=json.dumps(creds), headers=headers) assert r.status_code == 401 def test_post_to_auth_api_with_bad_password(self, client): creds = {'username': 'Us3rnam3', 'password': '<PASSWORD>'} headers = {'content-type': 'application/json'} r = client.post( '/auth', data=json.dumps(creds), headers=headers) assert r.status_code == 401 def test_post_to_auth_api_successful(self, client): creds = {'username': 'Us3rnam3', 'password': '<PASSWORD>'} headers = {'content-type': 'application/json'} r = client.post( '/auth', data=json.dumps(creds), headers=headers) assert r.status_code == 200 assert 'access_token' in r.get_json().keys() def test_get_to_auth_api_using_token(self, client): creds = {'username': 'Us3rnam3', 'password': '<PASSWORD>'} headers = {'content-type': 'application/json'} r = client.post( '/auth', data=json.dumps(creds), headers=headers) json_data = r.get_json() assert r.status_code == 200 assert 'access_token' in r.get_json().keys() headers['Authorization'] = 'Bearer {}'.format(json_data['access_token']) r = client.get( '/auth', headers=headers) json_data = r.get_json() assert r.status_code == 200 assert json_data == {'message': 'Hello, Us3rnam3'}
17ef422d3c446b5f5a71bc1607566840a54dd01e
[ "SQL", "YAML", "Markdown", "Makefile", "INI", "Python", "Text", "Dockerfile", "Shell" ]
23
Python
scott-mcnulty/flask-api-template
00f017b15dd7a37b157b9828911ee5ddb4bac24b
be458dc0214933c5b44ca30f8c5fbdf365b4b1f0
refs/heads/master
<file_sep>using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI; namespace TR.BIDSDispWeb { public partial class TopPage : Page { static public event EventHandler LightChanged; public TopPage() { InitializeComponent(); } Grid showingGrid; Grid ShowingGrid { get { return showingGrid; } set { if (ShowingGrid != null) { ShowingGrid.Visibility = Visibility.Collapsed; value.Visibility = Visibility.Visible; showingGrid = value; } else { value.Visibility = Visibility.Visible; showingGrid = value; } if (value == TopGrid && dt.IsEnabled) dt.Stop(); } } string IPAddr = string.Empty; bool _IsSkyWayConnected = false; bool IsSkyWayConnected { get { return _IsSkyWayConnected; } set { _IsSkyWayConnected = value; TopGrid_SelectGrid.IsEnabled = value; if (value) { IsSkyWayConnectedBlock.Text = "接続成功"; IsSkyWayConnectedBlock.Background = new SolidColorBrush(Colors.Black); IsSkyWayConnectedBlock.Foreground = new SolidColorBrush(Colors.White); } else { IsSkyWayConnectedBlock.Text = "未接続"; IsSkyWayConnectedBlock.Background = new SolidColorBrush(Colors.Red); IsSkyWayConnectedBlock.Foreground = new SolidColorBrush(Colors.Black); } } } class HandleClass { /// <summary> /// ブレーキハンドル位置 /// </summary> public int B; /// <summary> /// ノッチハンドル位置 /// </summary> public int P; /// <summary> /// レバーサーハンドル位置 /// </summary> public int R; /// <summary> /// 定速制御状態 /// </summary> public int C; } class StateClass { /// <summary> /// 列車位置[m] /// </summary> public double Z; /// <summary> /// 列車速度[km/h] /// </summary> public float V; /// <summary> /// 0時からの経過時間[ms] /// </summary> public int T; /// <summary> /// BC圧力[kPa] /// </summary> public float BC; /// <summary> /// MR圧力[kPa] /// </summary> public float MR; /// <summary> /// ER圧力[kPa] /// </summary> public float ER; /// <summary> /// BP圧力[kPa] /// </summary> public float BP; /// <summary> /// SAP圧力[kPa] /// </summary> public float SAP; /// <summary> /// 電流[A] /// </summary> public float I; public int Hour; public int Minute; public int Second; public int MSecond; } StateClass STC = new StateClass(); HandleClass HDC = new HandleClass(); private void CheckConnect(object sender, RoutedEventArgs e) { Console.WriteLine(AddrBox.Text); IsSkyWayConnected = true; } enum ObjInfo { ThatsNULL, ThatsBOOL, ThatsINT, ThatsFLOAT, ThatsDOUBLE, ThatsSTRING, ThatsERROR }; private void SelectPage(object sender, RoutedEventArgs e) { ShowingGrid = PageSelectGrid; } DispatcherTimer dt = new DispatcherTimer(); private void OnLoad(object sender, RoutedEventArgs e) { ErrorGridShow("abc", "def", 0); dt.Interval = new TimeSpan(0, 0, 0, 0, WaitTime); OldWaitTime = WaitTime; dt.Tick += LoopDoingVOID; ShowingGrid = TopGrid; IsSkyWayConnected = false; dt.Start(); } int OldWaitTime = 0; StateClass OSTC = new StateClass(); HandleClass OHDC = new HandleClass(); bool IsDoorClosed = false; bool oIsDoorClosed = false; private void StateSet(double TrainLocation, float Speed, float BC, float MR, float ER, float BP, float SAP, float Current, int PNotch, int BNotch, int Reverser, int Door, int TimeHH, int TimeMM, int TimeSS, int TimeMS) { STC = new StateClass() { Z = TrainLocation, BC = BC, BP = BP, ER = ER, Hour = TimeHH, I = Current, Minute = TimeMM, MR = MR, MSecond = TimeMS, SAP = SAP, Second = TimeSS, V = Speed }; HDC = new HandleClass() { B = BNotch, P = PNotch, R = Reverser }; if (Door == 1) IsDoorClosed = true; else IsDoorClosed = false; } private void ErrorGridShow(string Title,string Content,int ButtonMode) { if (!string.IsNullOrWhiteSpace(Title) || !string.IsNullOrWhiteSpace(Content)) { ErrorShowGrid_Title.Text = Title; ErrorShowGrid_Content.Text = Content; ErrorShowGrid.Visibility = Visibility.Visible; } switch (ButtonMode) { case 1://「閉じる」ボタン ErrorShowGrid_Button.Content = "閉じる"; ErrorShowGrid_Button.Click += ErrorShowGrid_Close; break; default: ErrorShowGrid_Button.Content = "トップへ"; ErrorShowGrid_Button.Click += ErrorShowGrid_GoTop; break;//「トップへ」ボタン } } private void ErrorShowGrid_Close(object s, object e) { ErrorShowGrid.Visibility = Visibility.Collapsed; } private void ErrorShowGrid_GoTop(object s, object e) { ShowingGrid = TopGrid; ErrorShowGrid.Visibility = Visibility.Collapsed; } private void LoopDoingVOID(object sender, object e) { if (OldWaitTime != WaitTime) { OldWaitTime = WaitTime; dt.Interval = new TimeSpan(0, 0, 0, 0, WaitTime); } StateSet(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (!Equals(OSTC, STC)) { SPGrid_TR01_SPSet = STC.V; SPGrid_TR01_PressSet(STC.MR, STC.ER, STC.BC, STC.BP); SPGrid_TR01_TimeSet((byte)STC.Hour, (byte)STC.Minute, (byte)STC.Second); SPGrid_TR01_CurrentSet = STC.I; SPGrid_TR01_LocationSet = STC.Z; OSTC = STC; } if (!Equals(OHDC, HDC)) { SPGrid_TR01_ReverserSet = HDC.R; SPGrid_TR01_HandleSet(HDC.B, HDC.P); OHDC = HDC; } if (!Equals(oIsDoorClosed, IsDoorClosed)) { SPGrid_TR01_IsDoorClosed = IsDoorClosed; oIsDoorClosed = IsDoorClosed; } } private void OnUnLoad(object sender, RoutedEventArgs e) { dt.Stop(); } //Grobal private void LightChagne(object sender, RoutedEventArgs e) => LightChanged?.Invoke(null, null); private void GridSelected(object sender, RoutedEventArgs e) { switch (((Button)sender).Content.ToString()) { case "TR01型速度計": ShowingGrid = SPGrid_TR01; break; } } int WaitTime = 200; private void fpsChange(object sender, RoutedEventArgs e) { WaitTime += 50; if (WaitTime > 550) WaitTime = 50; switch (WaitTime) { case 50: ((Button)sender).Content = "🕐"; break; case 100: ((Button)sender).Content = "🕑"; break; case 150: ((Button)sender).Content = "🕒"; break; case 200: ((Button)sender).Content = "🕓"; break; case 250: ((Button)sender).Content = "🕔"; break; case 300: ((Button)sender).Content = "🕕"; break; case 350: ((Button)sender).Content = "🕖"; break; case 400: ((Button)sender).Content = "🕗"; break; case 450: ((Button)sender).Content = "🕘"; break; case 500: ((Button)sender).Content = "🕙"; break; case 550: ((Button)sender).Content = "🕚"; break; } } ////////////////////////////////////////////////////////////////////////// // //SPGrid ////////////////////////////////////////////////////////////////////////// //// ////TR01 ////////////////////////////////////////////////////////////////////////// readonly Thickness[] SPGrid_TR01_SP90Thick = { new Thickness(890,570,0,0), new Thickness(850,450,0,0), new Thickness(920,360,0,0), new Thickness(1040,360,0,0), new Thickness(1110,450,0,0), new Thickness(1110,520,0,0) }; readonly string[] SPGrid_TR01_SP90MemNumStr = { "0","20","40","60","80","90" }; readonly Thickness[] SPGrid_TR01_SP120Thick = { new Thickness(870,560,0,0), new Thickness(850,460,0,0), new Thickness(890,380,0,0), new Thickness(980,350,0,0), new Thickness(1070,380,0,0), new Thickness(1095,460,0,0), new Thickness(1075,560,0,0) }; readonly Thickness[] SPGrid_TR01_SP140Thick = { new Thickness(875,570,0,0), new Thickness(850,480,0,0), new Thickness(875,400,0,0), new Thickness(940,355,0,0), new Thickness(1025,355,0,0), new Thickness(1070,400,0,0), new Thickness(1095,480,0,0), new Thickness(1070,570,0,0) }; readonly Thickness[] SPGrid_TR01_SP160Thick = { new Thickness(870,560,0,0), new Thickness(850,480,0,0), new Thickness(870,415,0,0), new Thickness(910,370,0,0), new Thickness(980,350,0,0), new Thickness(1035,370,0,0), new Thickness(1075,415,0,0), new Thickness(1095,480,0,0), new Thickness(1075,560,0,0) }; readonly Thickness[] SPGrid_TR01_SP240Thick = { new Thickness(870,560,0,0), new Thickness(850,460,0,0), new Thickness(890,380,0,0), new Thickness(975,350,0,0), new Thickness(1055,380,0,0), new Thickness(1095,460,0,0), new Thickness(1075,560,0,0) }; readonly Thickness[] SPGrid_TR01_SP360Thick = { new Thickness(870,560,0,0), new Thickness(850,460,0,0), new Thickness(890,380,0,0), new Thickness(980,350,0,0), new Thickness(1070,380,0,0), new Thickness(1095,460,0,0), new Thickness(1095,460,0,0), new Thickness(1095,460,0,0), new Thickness(1075,560,0,0), new Thickness(1075,560,0,0) }; private bool SPGrid_TR01_IsTickDefault = true; private int SPGrid_TR01_maxSP = 160; private Windows.UI.Xaml.Shapes.Path SPGrid_TR01_nowShowingSPMem = null; private Windows.UI.Xaml.Shapes.Path SPGrid_TR01_NowShowingSPMem { get { if (SPGrid_TR01_nowShowingSPMem == null) return SPGrid_TR01_SP160Memori; else return SPGrid_TR01_nowShowingSPMem; } set { if (SPGrid_TR01_nowShowingSPMem != null) SPGrid_TR01_nowShowingSPMem.Visibility = Visibility.Collapsed; else SPGrid_TR01_SP160Memori.Visibility = Visibility.Collapsed; value.Visibility = Visibility.Visible; SPGrid_TR01_nowShowingSPMem = value; SPGrid_TR01_SPSet = SPGrid_TR01_SPSet; } } private void SPGrid_TR01_MaxSPChangeEv(object sender, RoutedEventArgs e) { switch (SPGrid_TR01_MaxSP) { case 90: SPGrid_TR01_MaxSP = 120; return; case 120: SPGrid_TR01_MaxSP = 140; return; case 140: SPGrid_TR01_MaxSP = 160; return; case 160: SPGrid_TR01_MaxSP = 240; return; case 240: SPGrid_TR01_MaxSP = 320; return; case 320: //MaxSP = 360; SPGrid_TR01_MaxSP = 90;//Max360km/hモードは未実装 return; case 360: SPGrid_TR01_MaxSP = 90; return; default: SPGrid_TR01_MaxSP = 160; return; } } private int SPGrid_TR01_MaxSP { get { return SPGrid_TR01_maxSP; } set { if (SPGrid_TR01_NowShowingSPMem == null) SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP90Memori; SPGrid_TR01_maxSP = value; Thickness[] tkns = new Thickness[10]; string[] numstr = new string[10]; for (int i = 0; i < 10; i++) { tkns[i] = new Thickness(0, 0, 0, 0); numstr[i] = string.Empty; } switch (value) { case 90: for (int i = 0; i < 6; i++) { tkns[i] = SPGrid_TR01_SP90Thick[i]; numstr[i] = SPGrid_TR01_SP90MemNumStr[i]; } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP90Memori; break; case 120: for (int i = 0; i < 7; i++) { tkns[i] = SPGrid_TR01_SP120Thick[i]; numstr[i] = (i * 20).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP120Memori; break; case 140: for (int i = 0; i < 8; i++) { tkns[i] = SPGrid_TR01_SP140Thick[i]; numstr[i] = (i * 20).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP140Memori; break; case 160: for (int i = 0; i < 9; i++) { tkns[i] = SPGrid_TR01_SP160Thick[i]; numstr[i] = (i * 20).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP160Memori; break; case 240://120と共通 for (int i = 0; i < 7; i++) { tkns[i] = SPGrid_TR01_SP240Thick[i]; numstr[i] = (i * 40).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP120Memori; break; case 320://160と共通 for (int i = 0; i < 9; i++) { tkns[i] = SPGrid_TR01_SP160Thick[i]; numstr[i] = (i * 40).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP160Memori; break; case 360://未実装 for (int i = 0; i < 10; i++) { tkns[i] = SPGrid_TR01_SP360Thick[i]; numstr[i] = (i * 40).ToString(); } break; default: SPGrid_TR01_maxSP = 160; for (int i = 0; i < 9; i++) { tkns[i] = SPGrid_TR01_SP160Thick[i]; numstr[i] = (i * 20).ToString(); } SPGrid_TR01_NowShowingSPMem = SPGrid_TR01_SP160Memori; break; } TextBlock[] tb = { SPGrid_TR01_SPMemNum0, SPGrid_TR01_SPMemNum1, SPGrid_TR01_SPMemNum2, SPGrid_TR01_SPMemNum3, SPGrid_TR01_SPMemNum4, SPGrid_TR01_SPMemNum5, SPGrid_TR01_SPMemNum6, SPGrid_TR01_SPMemNum7, SPGrid_TR01_SPMemNum8, SPGrid_TR01_SPMemNum9, }; for (int i = 0; i < 10; i++) { if (numstr[i] != string.Empty) tb[i].Visibility = Visibility.Visible; else tb[i].Visibility = Visibility.Collapsed; tb[i].Text = numstr[i]; tb[i].Margin = tkns[i]; } } } private byte[] SPGrid_TR01_NowTime = new byte[3] { 0, 0, 0 }; private void SPGrid_TR01_TimeSet(byte Hour, byte Minute, byte Second) { if (SPGrid_TR01_NowTime[0] != Hour) SPGrid_TR01_HourNum.Text = Hour.ToString("D"); if (SPGrid_TR01_NowTime[1] != Minute) SPGrid_TR01_MinuteNum.Text = Minute.ToString("D2");//10進数2桁 if (SPGrid_TR01_NowTime[2] != Second) SPGrid_TR01_SecondNum.Text = Second.ToString("D2");//10進数2桁 SPGrid_TR01_NowTime = new byte[3] { Hour, Minute, Second }; } double NowSP = 0; private double SPGrid_TR01_SPSet { get { return NowSP; } set { NowSP = Math.Abs(value); double UrGosa = NowSP - Math.Floor(NowSP);//11.9-11 double LrGosa = Math.Ceiling(NowSP) - NowSP;//12-11.9 //測定誤差を、数値との離れ具合でランダムに決定する。 Random rdm = new Random(); if (UrGosa < 0.15 && rdm.Next((int)Math.Floor(UrGosa * 10)) == 0) { NowSP -= 1; } if(LrGosa < 0.15 && rdm.Next((int)Math.Floor(LrGosa * 10)) == 0) { NowSP += 1; } NowSP = Math.Ceiling(NowSP); SPGrid_TR01_SpeedNumBlock.Text = NowSP.ToString(); if (NowSP >= SPGrid_TR01_MaxSP && NowSP < 360) SPGrid_TR01_MaxSPChangeEv(null, null); double Angle = 0; switch (SPGrid_TR01_MaxSP) { case 90: Angle = -40; Angle += 2.6 * NowSP; break; case 120: Angle = -30; Angle += 2 * NowSP; break; case 140: Angle = -36; Angle += 1.8 * NowSP; break; case 160: Angle = -30; Angle += 1.5 * NowSP; break; case 240: Angle = -30; Angle += 2 * Math.Round(NowSP / 2); break; case 320: Angle = -30; Angle += 1.5 * Math.Round(NowSP / 2); break; case 360: Angle = -36; Angle += 2.8 * Math.Round(NowSP / 4); break; } SPGrid_TR01_SPHari.Angle = Angle; } } //RWRW private void SPGrid_TR01_PressSet(double MR, double ER, double BC, double BP) { if (!SPGrid_TR01_IsTickDefault) { MR = Math.Ceiling(MR / 100) * 100; ER = Math.Ceiling(ER / 100) * 100; BC = Math.Ceiling(BC / 100) * 100; BP = Math.Ceiling(BP / 100) * 100; } //*2.6 / 10kPa SPGrid_TR01_MRHari.Angle = MR * 0.26 - 40; SPGrid_TR01_ERHari.Angle = ER * 0.26 - 40; SPGrid_TR01_BCHari.Angle = BC * 0.26 - 40; SPGrid_TR01_BPHari.Angle = BP * 0.26 - 40; } private double SPGrid_TR01_CurrentSet { set { double I = value; double PlusW = 0; double MinusW = 0; if (!SPGrid_TR01_IsTickDefault) I = Math.Ceiling(I / 10) * 10; if (I >= 0) { PlusW = I * 0.3; MinusW = 0; } if (I < 0) { MinusW = Math.Abs(I) * 0.3; PlusW = 0; } //SPGrid_TR01_PlusCurrentBar.Width = PlusW; //SPGrid_TR01_MinusCurrentBar.Width = MinusW; SPGrid_TR01_PlusCurrentBar.Margin = new Thickness(50 + PlusW, 130, 0, 0); SPGrid_TR01_MinusCurrentBar.Margin = new Thickness(50 + MinusW, 230, 0, 0); } } private double SPGrid_TR01_LocationSet { set => SPGrid_TR01_LocationTextBlock.Text = value.ToString("F1"); } private int SPGrid_TR01_ReverserSet { set { int num = value; Visibility[] vs = new Visibility[3] { Visibility.Collapsed, Visibility.Collapsed, Visibility.Collapsed }; if (num < 0) vs[2] = Visibility.Visible; else if (num > 0) vs[0] = Visibility.Visible; else vs[1] = Visibility.Visible; SPGrid_TR01_RHandF.Visibility = vs[0]; SPGrid_TR01_RHandN.Visibility = vs[1]; SPGrid_TR01_RHandR.Visibility = vs[2]; } } private void SPGrid_TR01_HandleSet(int B, int P) { SPGrid_TR01_BHandNum.Text = B.ToString("D"); SPGrid_TR01_PHandNum.Text = P.ToString("D"); } private bool SPGrid_TR01_IsDoorClosed { set { if (value) SPGrid_TR01_IsDoorClosedPath.Visibility = Visibility.Visible; else SPGrid_TR01_IsDoorClosedPath.Visibility = Visibility.Collapsed; } } } } <file_sep>--- name: バグ報告 about: バグの修正のために、再現方法などを送信する。 title: タイトル labels: bug assignees: '' --- **バグについて** どのようなバグかを、明確かつ簡潔に記載 **再現手順** バグを発生させる手順を記す 1. ABCを表示する 2. DEFをクリックする 3. バグが発生する **何を修正するべきか(任意)** 何をすることを期待するかを明確かつ簡潔に記載。 **スクリーンショット(任意)** あったほうが役立つと判断される場合、可能であればSSを掲載する **使用環境** - OS: [e.g. iOS] - デバイス名: [e.g. iPhone6, Xperia XZ2 Premium](スマートフォン以外の場合は不要) - ブラウザ: [e.g. chrome, safari] - ブラウザバージョン [e.g. 22] - アプリバージョン [e.g. v002] **追加情報** この問題に関して、何か他の情報があれば、ここに記載 <file_sep>using System; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace TR.BIDSDispWeb { public partial class MainPage : Page { public MainPage() { InitializeComponent(); // Enter construction logic here... } readonly double OrigH = 800; readonly double OrigW = 1280; bool IsDebug = false; private void OnSizeChange(object sender, SizeChangedEventArgs e) { double NowHeight; double NowWidth; NowHeight = e.NewSize.Height; NowWidth = e.NewSize.Width; if (IsDebug || e.NewSize.IsEmpty) return; double ScaleX = NowWidth / OrigW; double ScaleY = NowHeight / OrigH; double scale = Math.Min(ScaleX, ScaleY); double MarX = 0; double MarY = 0; if (ScaleX == scale) MarY = (NowHeight - OrigH * ScaleX) / 2; if (ScaleY == scale) MarX = (NowWidth - OrigW * ScaleY) / 2; FrontFrame.Margin = new Thickness(MarX, MarY, MarX, MarY); ScaleTransform scl = new ScaleTransform { ScaleX = scale, ScaleY = scale }; double Origin = 0; if (scale >= 1) Origin = 0.5; FrontFrame.RenderTransformOrigin = new Point(Origin, Origin); FrontFrame.RenderTransform = scl; } private void OnUnLoad(object sender, RoutedEventArgs e) { } private void OnLoad(object sender, RoutedEventArgs e) { TopPage.LightChanged += TopPage_LightChanged; FrontFrame.Source = new Uri("/", UriKind.Relative); OnSizeChange(null, new SizeChangedEventArgs(new Size(Width, Height))); } private void TopPage_LightChanged(object sender, EventArgs e) { double opt = 0; switch (LightAdjusterRec.Opacity) { case 0: opt = 0.2; break; case 0.2: opt = 0.3; break; case 0.3: opt = 0.4; break; case 0.4: opt = 0.6; break; case 0.6: opt = 0; break; } LightAdjusterRec.Opacity = opt; } } } <file_sep># BIDSDispWeb BIDS表示ソフトのHTML/JavaScript版サンプル C#/XAML for HTML5を用いて開発を行っています。 <file_sep>--- name: 機能追加要望 about: 機能の追加を提案する title: タイトル labels: enhancement assignees: '' --- **提案に関連する問題/不満点** この提案をするに至った原因があれば記載 **どのような機能を望むか** 機能についての簡潔な説明を記載 **機能についての詳細** Add any other context or screenshots about the feature request here.
b01cbe200430f984a41890b16106edaf10000a89
[ "Markdown", "C#" ]
5
C#
Tralsys/BIDSDispWeb
5a8b8665b3de74e061f4291a5c62e19777278e1f
61b5a8a792dd109c9cd3a2e6f9072572629f25fb
refs/heads/master
<repo_name>dsc-sits/DSC-APP-API<file_sep>/apis/serializers.py from rest_framework import serializers from .models import Apis #Serializing all the Fields in the Models class ApisSerializer(serializers.ModelSerializer): class Meta: model = Apis fields = '__all__'<file_sep>/README.md # DSC-APP-API RESTful API backing DSC's Mobile APP <file_sep>/apis/urls.py from rest_framework import routers from .api import ApisViewSets router = routers.DefaultRouter() router.register('api', ApisViewSets, 'api') urlpatterns = router.urls<file_sep>/apis/api.py from apis.models import Apis from rest_framework import viewsets, permissions from .serializers import ApisSerializer # ViewSets are similar to views # which gets rendered with respect to a specific API call(GET, POST, etc.) class ApisViewSets(viewsets.ModelViewSet): queryset = Apis.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ApisSerializer<file_sep>/apis/models.py from django.db import models # Create your models here. class Apis(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True)
ba2ad3ea32b8e269d0107ae6b740548c004882d6
[ "Markdown", "Python" ]
5
Python
dsc-sits/DSC-APP-API
b222c79860daf5737a91d9835370b795f2a2cd77
0231420f542f8b7fd956d207c6d1b2cd43777355
refs/heads/master
<repo_name>staketechnologies/ethereum-lockdrop<file_sep>/src/data/affiliationProgram.ts // the default introducer address when none is provided by the user export const defaultAddress = '0x0000000000000000000000000000000000000000'; export const affiliationRate = 0.01; const firstEthIntroducer = [ '0xd8de1f6764e442b8763d313722e9eaee3779707e', '0x1d32750e8a03443f008236f7c344fc84821cf690', '0xa<KEY>', '0xd<KEY>', '0x4<KEY>', '0xd419d53817e1daa7b2f72e51707774f3ff0a54a3', '0x1080355c93a1b4c0dd3c340eed4f7e514c583077', '0x0013aa2fb5ec916660b38f1d53d4fc9bf8ef8a84', '0x7<KEY>', '0x60dc4b3d8e8d2c5449186270f385a56a21bb82c3', '0x380566185c87ab93ca4edd474cf6<KEY>3e', '0x6a61dc52015945dfc6cd0c42f94a722d5022e3d1', '0x5<KEY>0<KEY>', '0x27c72e4bd23<KEY>06c4a1742e06657c874', '0xd<KEY>', '0x9498db340a3ecab7bb0973ee36e95e58c8e58a41', '0xe552821ee85284249c71d4abfc4437992ed2fb93', '0xc<KEY>', '0x20edd77ea8582f4a2400d3c0d53154a74a1ca887', '0xeef2e4a5f6a01d5fb89f38211fb4e6a8702d33b6', '0x<KEY>', '0<KEY>', '0xb35e0bfec9facd8f2dcc0e43e68350d5e7baa82f', '0x7b4d4ba1070c4562c568fed6280c800a68fa5427', '0x81042f7f99a86d3981308e72feb36bd791c31920', '0xb98df9f7cdc3a983081cefa1cd94aed4e936f1a9', '<KEY>', '<KEY>', '0x8e7fcc7a17f00f0f5f85f2d5964a581d0813c8a6', '<KEY>', '<KEY>', '<KEY>', '0<KEY>', '0x0def9b4811e4c4e9da5acf82d421c97b5e9c152f', ]; const secondEthIntroducer = [ // first lockdrop participent. '0x0def9b4811e4c4e9da5acf82d421c97b5e9c152f', '0xd8068f813c45c88cebb02cbc0f91f95626ec9a34', '0x00eea078f8fbfc5d62458584e95306e60c4a638e', '0x116fd435e3b2e57598353089ba95e6a0febdb2f3', '0xd307ff28710b7a4587200c5ba4c67648c1f24045', '0x8e7fcc7a17f00f0f5f85f2d5964a581d0813c8a6', '0xe552821ee85284249c71d4abfc4437992ed2fb93', '0x<KEY>', '0x1<KEY>', '0xe0e0b97949687e5cdc9ca843c0428bd0437e176d', '0xd419d53817e1daa7b2f72e51707774f3ff0a54a3', '0xdc1f0c07202629be59e1f5396e7d78803423650e', '0xdbfce5f51e67be01ce77b54766f3770992878263', '0x9999999ccd21cf1517e907b535dc8507f79bce09', '0xc55022673882d57ad13358567e62025467f5a57f', '<KEY>', '0xaf1b057a6011583171fb1ea6e627babd6ba0cab4', '0xc8145caf71b4af6c6cc682fc7e1a41c8769c6e86', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '0xc8e99360d5b672d66610b0db0807611fe954ccf9', '0<KEY>', '0x7ba00c82c5b19b2ec77836b23a2289fb32558e88', '0xd5aa581ee5d9033b2e36811869781043b1d571a6', '<KEY>', '<KEY>', '0x1fef0f8a5ac51790de232f0ae3e1bfa47eadbacd', '0xaec05c2a88f2b7896005086adbaba3cfd81b63be', '<KEY>', '<KEY>', '<KEY>', '0xd8de1f6764e442b8763d313722e9eaee3779707e', '0x9a72b97137065b3816d091310e483811baa1be0f', '<KEY>', '0xd997ca66e558aa3d8d2ec39f3c5196fe5f31fede', '0<KEY>25b5a742d2<KEY>', '0<KEY>', '0x50873df6f51369746638a4df373aef4b9e053fee', '0x81042f7f99a86d3981308e72feb36bd791c31920', '0xe81ff5a7f528c660cb41facedd53485e20ea2758', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '0xe32c5673b152571e57976bf3a75068917da2da9c', '<KEY>', '<KEY>', '0<KEY>', '0x0fbb89875a0cb7324<KEY>', '0x08fde66bf84c45fe0ca982425882abe7168c1c2c', '0x<KEY>', '0<KEY>', '0x39d76f41cc6c17e21017dad9abc6609cacd5af67', '0<KEY>', '0<KEY>', '0x900a30257db838d82130980497bd403adaf5e441', '0x<KEY>', '0xdb422897f0f0d3f33845545f691eac4501799a4d', '0x2411605a576fe058483382c1db691318056ebaad', '0xe98407caac216cebe793e577930b8b4ca7a6ad61', '0xb<KEY>', '0x296f0063bdd07be8cba2f5183592574e0d62efca', '0xaad9a85cc1df4e36ed208420cd81a5b3acf984b6', '0<KEY>', '0x5a24f5764fc0a5fd7d74856ac25084bec0916f7c', '0x11a7c436365766b4a1500219529bb94a36c3f6f4', '0x46808e14ada3d28e0a09ce365b281254c6b8c6fa', '0x91715128a71c9c734cdc20e5edeeea02e72e428e', '0x0c4ca96d4e63af64fb7896ab41e0aa871a59fabb', '0x<KEY>', '0x8284048672d74d8165f7e38c5c0e6f8fde18c98c', '0<KEY>', '0x05a0fa3b8f65c62a77e388dabaf2ec7176c3635e', '0x90fdff26419fb9550a6a55c792b14122e72714da', '0x<KEY>', '0<KEY>', '0x9628be77fb3dcd890fd93a5d039092fca855d3cc', '0xaadb9ed84fe0812b87ca98341aef5599b47ea60f', '0x2f0c01465d38fc4a31c95b7e74a4c80be6d87bbe', '0x5023732c23c04bbccce4c75ae9da307a74478dc3', '0<KEY>', '0xe4bb14f0c5e772896ffa5007ea24a5109d910c8e', '0x3<KEY>', '0x06608f5ad0101bdf2786a6a4<KEY>3', '0x17e35b700e6d014d9cc4cc093d6eff6e66d9f117', '0xb16ee2a981cce4c4c075b2bd9406d5074da02727', '0xbd8152fc7f060c6555809f6eada3ce64cba4d723', '0xaf95c1022817a47d23ac90da77be788d66ccfa69', '0x24f94fcd6bfe7a8ca2f9a0730dab0e91590c9147', '0xc1c7f7169b6c3022d172302a32d59c90a33230aa', '0xe5fdedd718bdf40904d67658fa4b9629a7a8b515', '0x4<KEY>', '0x574319e245428c9f064006e49ad5f83947f763ec', '0x2589b11029bd58ca8d917e2ba9f062dec946b463', '0x0a338782562e1740b9468f0855dd4c51f29defde', '0x38bc00ea43ebb5ef5150593a0ba6c381803717e2', '0xe91aee4906c8635bf15962a639436f40780233a0', '0x3385dc8e3ea5a0b077678a7ffdddb2bbed7142b8', '0x2f6f830e90baaf06575d7102f9cd83cf7880e101', '0x19ee7696d2a71548a7f1fc9cef644460d7e73297', '0x198a123599e65140bfefa0966<KEY>07', '0x943d56d95613984e4972ae0c4edf1471502a248e', '0x9a94771e7e73f9d8d6e880cfb12cab4e9573c45e', '0xff3fc772434505abff38eecde3c689d4b0254528', '0x6f9393ebeb1eae46417b915bec7849d270d44d57', '0<KEY>', '0x<KEY>', '0x<KEY>', '0x0c1633e0ba164a9def56d86d7c46afcbe4d28a77', '0x9ed176365cc9928d4922<KEY>08019f1f465', '0x184cca7d9e77d07fe76450019b0df461cf83f316', '0xe5ee62d72a8b26cc1c6c8c2aa0d9697c3f766893', '0x057dc43af6187a931e78a56b3293912a5b42e5ec', '0<KEY>', '0x9cc30a6b421c4e6be8547b8d694a46adf45e8f87', '0xbc3639460ec1e13024c87011a169db2dd07e0d7e', '0x157d9ff7ddd8d426a0013c682dd1567f074f6ec7', '0<KEY>', '0x30086c39930c0708b83e2c31ee080505d843ac8c', '0x762bb60be9460754dff50275d23e742e33844491', '0x381150118f049e8970e57b06a6e880b10769e745', '0x34c3a5ea06a3a67229fb21a7043243b0eb3e853f', '0<KEY>', '0<KEY>', '0xcc<KEY>287a5', '0xab38a0d96586c0f536b09339daa61c4e6981d3fd', '<KEY>', '0xcddc876165579bddbebf2ea6ddacaa54896b2b6a', '0x3fd1ddf28f604cfe5fefa3adc38e38be2f7208d6', '0x6f04ee370184c6ed094f85a0132358f6352fb7db', '<KEY>', '<KEY>', '0x33f3341d95adefed3a51358b04b599862f0f2b8c', '0xbd7c0a61406df33a22eb055643316adce6145198', '0x757058fa2a6261ce0834782152413609ca86c9be', '0<KEY>', '0<KEY>', '0<KEY>', '0<KEY>', '0xde45ac1ddb50d0c7ddb7ce66b3af6a696aec6035', '0xaf<KEY>', '0xf3b02c6df19e6d1fad2ce2b5a463c3cb253194e1', '0xe2e4f2a725e42d0f0ef6291f46c430f963482001', '0x376e21b6eab3ad3623e4002612c5196c4edfef2a', '0<KEY>', '0x4af013afbadb22d8a88c92d68fc96b033b9ebb8a', '0<KEY>', '0x974a3cb54d84b22a6dbeb1bf4e9546eddd825003', '0x6a9f813fb3e6a8f7013dabd1695bae1d49ae8481', '0x3a5444d841f540fc23c9fae2b5d1fb7ee0838a06', '0x04e6839909b7330dc28bf<KEY>', '0x32057597286efed4d8833de4d7b57907e1cd4012', '0<KEY>', '0<KEY>', '0xcbf111366e51ca8e90180d0ee2c7fed9d2bd62dc', '0<KEY>', '<KEY>', '<KEY>', '0<KEY>', '0x1391bec69fa33ae796dce01fa12d194e449db65f', '0<KEY>', '0<KEY>', '0x38567f34e6154f923a96f1eca2cf42be9db1ef4d', '0xc<KEY>', '0<KEY>', '0<KEY>', '0<KEY>', '0<KEY>', '0<KEY>', '0<KEY>', '0x71232ead3bec1ac03ecfe2556acd6c7d0bd349c7', '0x<KEY>', '0x67468a31b888f631b520db2299c4ccead4eed18f', '0x0ab57e2507efc52c1cf65fd829f638e82287638b', '0x<KEY>', '0x<KEY>', '0x7d04227808dd38f649fe272fe0<KEY>', '0<KEY>', '0xaa3d5ab57060e32546e45e7fdddbf482879a3609', '0x1ee0950a899d327e1041728a66fc140d859be81c', '0x<KEY>', '0<KEY>', '0x95340b69162d21a931da57cb9759b671ef57ee7f', '0xfaf55d4daf9e5377eb33a9eadde86d3a455f6c6d', '0xce57992a5a760ff983bfa5cc15415a18a50b3ecd', '0x798121bef71dafcff3d046e4c29893675f4ed503', '0x44a8<KEY>edfee04231077f990d291735c3', '0x951ed2323ad203e490353ab2ac8ee142fe4b771e', '0xbd<KEY>', '0x462cc75caee4d0be283eeddbc2cd569<KEY>', '<KEY>', '<KEY>', '0<KEY>', '0x9406a41d8d845a2fca05f860d33f50c9195bdce3', '0x75b07e64161ace39d6eab54d25f25410ffd3d458', '<KEY>', '<KEY>', '0xa4ad15c9ee1bce28dec3fad031fc3b56e45928a0', '<KEY>', '0<KEY>', '0x6130a038b17f7ee8d28abd54415f2066c0e81b0b', '0xe7d52be2217cc6178b661e4fe0e9e371ee18b630', '0xea8dd9381571d618119912af553ce81<KEY>', '0x98a581c72d4b5b47bd6348ea52d17963f68af33e', '0x<KEY>', '0<KEY>', '0xee<KEY>', '0xc5c510ae135b70a12a6be47d0e8ec072e9c62610', '0x787659052e92862f225b139060569083d6dff695', '0<KEY>', '0x2298718f8c34adb143bdcc017feae24de4a62653', '0x58ffe60904be609b4af1b42ce7bfaadfd0030cea', '0x6de754c<KEY>d2ff55ad6ea7d00ab6e131', '0x5f9f19434824cc539ef0d3c0a386a9707cf2a2ec', '0<KEY>', '0xe1478cbf115c2d6bec1572e0e6a43a2dfadca15a', '<KEY>', '<KEY>', '0x4e65a036fa1df22e6f108ecf256a25d3e6f6ea1d', '0xcdceff3dcf24d6286f8accab295abd5bd5f2ef11', '0xb87d9edb23e88bc7c1e6f2cd3aa65fae6397670f', '<KEY>', '<KEY>', '0x70aecbb415372151c47e4d82a3263b6cc8ea1995', '0x6a6d6d904812b6d559c18eca37ffe366a6c29d9d', '0<KEY>', '<KEY>', '0x33d30dc6eae66f5a5f9ea54f6b54e3ab9cd9ba38', '0x<KEY>', '<KEY>', '0x84609c7176b18487a2b09a2bc4e6db9f5b8e8e0e', '0x926132c52a4a050eabe0bc034b6233a2b37a96b3', '<KEY>', '0x67f40170bf81d44017be25e6596d1df7e67538f8', '0xea3c39496c2868741ff8a32b49a2943309ead303', '<KEY>', '0xebda2d5559eec2fcd86a001a99955fdb75e206e4', '0x90755a465d1b711a6b68e81deb3e3e5fbcdc3d0c', '<KEY>', '0x9fe7a3ed1f3734604c365e3d461e4c1644b1e8e2', '0xe6410ecbaa041a5dcde79164ca66de42a8d72bee', '0x552ec58ec4aa8b5374b042f2995fa857167c99af', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '0xc49b6c714feaf22b12eb02a01521dab6edd1fcbd', '<KEY>', '0x504361604c519a16cc19a628f3de1993996f2a7c', '<KEY>', '0<KEY>', '0x028ced475400006<KEY>', '0xf0a355a5ab3d96a4347e9fe3052ef39357df90d0', '0x215a2a56984df578603f6f9f5a46750efb356894', '0x95f1872c2c63f54072bd42f68beee71e0d6f67d3', ]; const specialCommunityCommitter = [ '0x6c7e7fbfa69f4b5a5ade1c27bc74fa4290a3b8a3', // Chinese ambassador '0xf5d7d97b33c4090a8cace5f7c5a1cc54c5740930', // Russian lockdrop movie introducer. ]; const secondBtcIntroducer = ['add Bitcoin addresses']; export const validEthAddressList = [ ...firstEthIntroducer, ...secondEthIntroducer, ...specialCommunityCommitter, defaultAddress, ]; export const validBtcAddressList = [...secondBtcIntroducer]; /** * Checks if the given introducer address is listed as a valid introducer for the lockdrop * @param introducer a bitcoin or ethereum address */ export function isValidIntroducerAddress(introducer: string) { return ( validEthAddressList.includes(introducer.toLowerCase()) || validBtcAddressList.includes(introducer.toLowerCase()) ); } <file_sep>/src/data/links.ts export const Links = { docs: 'https://docs.plasmnet.io', blog: 'https://medium.com/stake-technologies', twitter: 'https://twitter.com/Plasm_Network', github: 'https://github.com/staketechnologies/Plasm', telegram: 'https://t.me/PlasmOfficial', discord: 'https://discordapp.com/invite/Dnfn5eT', email: '<EMAIL>', home: 'https://stake.co.jp/', plasmHome: 'https://plasmnet.io/', }; export const SponsorLinks = { cryptoEconomicsLab: 'https://www.cryptoeconomicslab.com/', parityTechnologies: 'https://www.parity.io/', web3Foundation: 'https://web3.foundation/', longhash: 'https://longhash.co.jp/en/', universityOfTokyo: 'https://www.u-tokyo.ac.jp/en/index.html', connect: 'https://www.blockchain.t.u-tokyo.ac.jp/', parityBuilders: 'https://builders.parity.io/', acala: 'https://acala.network/', }; export const BlogLinks = { lockdropIntroduction: 'https://medium.com/stake-technologies/plasm-lockdrop-introduction-54614592a13', }; export const AppLinks = { plasmnetIo: 'https://apps.plasmnet.io/', polkadotNetwork: 'https://telemetry.polkadot.io/#list/Plasm%20Testnet%20v3', joinLockdrop: 'https://lockdrop.plasmnet.io', inkPlayground: 'https://ink-playground.com/', }; export const Whitepaper = [ { description: 'English', link: 'https://github.com/stakedtechnologies/plasmdocs/blob/master/wp/en.pdf', icon: `sticky note outline`, }, { description: 'Japanese', link: 'https://github.com/stakedtechnologies/plasmdocs/blob/master/wp/jp.pdf', icon: `sticky note outline`, }, ]; export const Community = [ { description: 'Discord', link: Links.discord, icon: 'discord', }, { description: 'Telegram', link: Links.telegram, icon: 'telegram', }, ]; export const Company = [ { description: 'Home', link: Links.home, }, { description: 'Contact us', link: `mailto:${Links.email}`, }, ]; export const Products = [ { description: 'Plasm', link: 'https://github.com/staketechnologies/Plasm', }, { description: 'Plasm Portal Sites', link: 'https://github.com/staketechnologies/apps', }, { description: 'Plasm Lockdrop', link: 'https://github.com/staketechnologies/lockdrop-ui', }, { description: 'Plasm documentations', link: 'https://github.com/staketechnologies/plasmdocs', }, { description: 'Plasm homepage', link: 'https://github.com/staketechnologies/plasmnet.io', }, ]; export const Collaboration = [ { description: 'Substrate Builders Program', link: 'https://builders.parity.io/', }, { description: 'Web3 foundation grants program', link: 'https://web3.foundation/', }, ]; export const Blogs = [ { description: 'Medium', link: Links.blog, }, ]; export const Discussions = [ { link: Links.discord, className: 'discord', }, { link: Links.telegram, className: 'telegram', }, { link: Links.twitter, className: 'twitter', }, { link: Links.github, className: 'github', }, ]; <file_sep>/src/helpers/getWeb3.ts /* eslint-disable @typescript-eslint/no-explicit-any */ import Web3 from 'web3'; async function web3Listener() { // Modern dapp browsers... if ((window as any).ethereum) { const web3 = new Web3((window as any).ethereum); try { // Request account access if needed await (window as any).ethereum.enable(); console.log('Dapp browser detected'); // Accounts now exposed return web3; } catch (error) { return error; } } // Legacy dapp browsers... else if ((window as any).web3) { // Use Mist/MetaMask's provider. const web3 = (window as any).web3; console.log('Injected web3 detected.'); return web3; } // Fallback to localhost; use dev console port by default... else { const provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545'); const web3 = new Web3(provider); console.log('No web3 instance injected, using Local web3.'); return web3; } } export const removeWeb3Event = () => { new Promise((resolve, reject) => { try { window.removeEventListener('load', () => resolve(web3Listener())); } catch (error) { reject(error); } }); }; const getWeb3 = () => new Promise((resolve, reject) => { // check if the event was already fired if (document.readyState === 'complete') { // reload page to reset the event window.location.reload(); } // Wait for loading completion to avoid race conditions with web3 injection timing. try { window.addEventListener('load', () => resolve(web3Listener())); } catch (error) { reject(error); } }); export default getWeb3; <file_sep>/src/helpers/plasmUtils.ts /* eslint-disable @typescript-eslint/camelcase */ import BigNumber from 'bignumber.js'; import { ApiPromise, WsProvider } from '@polkadot/api'; import { Hash, H256 } from '@polkadot/types/interfaces'; import * as polkadotUtilCrypto from '@polkadot/util-crypto'; import * as polkadotUtils from '@polkadot/util'; import { u8aConcat } from '@polkadot/util'; import { Struct, TypeRegistry, u64, u128, U8aFixed, u8 } from '@polkadot/types'; import * as plasmDefinitions from '@plasm/types/interfaces/definitions'; import { LockdropType, Claim, Lockdrop, LockEvent } from 'src/types/LockdropModels'; /** * Plasm network enum */ export enum PlasmNetwork { Local, Dusty, Main, } /** * converts the plasm network minimum denominator to PLM * @param femto minimum token value */ export function femtoToPlm(femto: BigNumber) { if (femto.isLessThanOrEqualTo(new BigNumber(0))) { return new BigNumber(0); } const plmDenominator = new BigNumber(10).pow(new BigNumber(15)); return femto.dividedBy(plmDenominator); } /** * a Proof-of-Work function that hashes the lockdrop claim ID and the nonce * together to verify the unsigned transaction. * this will return the correct nonce in hex string * @param claimId the real-time lockdrop claim ID (blake2 hashed lock parameter) */ export function claimPowNonce(claimId: Uint8Array | H256): Uint8Array { let nonce = polkadotUtilCrypto.randomAsU8a(); while (true) { const hash = polkadotUtilCrypto.blake2AsU8a(u8aConcat(claimId, nonce)); //console.log('PoW hash: ' + u8aToHex(hash)); if (hash[0] > 0) { nonce = polkadotUtilCrypto.randomAsU8a(); //console.log('Next nonce: ' + u8aToHex(nonce)); } else { return nonce; } } } /** * used for adding new polkadot-js api types for communicating with plasm node */ export const plasmTypeReg = new TypeRegistry(); /** * establishes a connection between the client and the plasm node with the given endpoint. * this will default to the main net node * @param network end point for the client to connect to */ export async function createPlasmInstance(network?: PlasmNetwork) { let endpoint = ''; const types = Object.values(plasmDefinitions).reduce((res, { types }): object => ({ ...res, ...types }), {}); switch (network) { case PlasmNetwork.Local: endpoint = 'ws://127.0.0.1:9944'; break; case PlasmNetwork.Dusty: endpoint = 'wss://rpc.dusty.plasmnet.io/'; break; case PlasmNetwork.Main: // main net endpoint will be the default value default: endpoint = 'wss://rpc.plasmnet.io'; break; } const wsProvider = new WsProvider(endpoint); const api = await ApiPromise.create({ provider: wsProvider, types: { ...types, // aliases that don't do well as part of interfaces 'voting::VoteType': 'VoteType', 'voting::TallyType': 'TallyType', // chain-specific overrides Address: 'GenericAddress', Keys: 'SessionKeys4', StakingLedger: 'StakingLedgerTo223', Votes: 'VotesTo230', ReferendumInfo: 'ReferendumInfoTo239', }, // override duplicate type name typesAlias: { voting: { Tally: 'VotingTally' } }, }); return await api.isReady; } /** * convert the given lock duration in to PLM issue bonus rate * @param duration token lock duration */ export function lockDurationToRate(duration: number) { if (duration < 30) { return 0; } else if (duration < 100) { return 24; } else if (duration < 300) { return 100; } else if (duration < 1000) { return 360; } else { return 1600; } } /** * Create a lock parameter object with the given lock information. * This is used for the real-time lockdrop module in Plasm for both ETH and BTC locks * @param network the lockdrop network type * @param transactionHash the lock transaction hash in hex string * @param publicKey locker's public key in hex string * @param duration lock duration in Unix epoch (seconds) * @param value lock value in the minimum denominator (Wei or Satoshi) */ export function createLockParam( network: LockdropType, transactionHash: string, publicKey: string, duration: string, value: string, ) { const lockParam = new Struct( plasmTypeReg, { type: u8, transactionHash: 'H256', publicKey: U8aFixed, // [u8; 33] duration: u64, value: u128, }, { type: network, // enum is converted to number transactionHash: transactionHash, publicKey: new U8aFixed(plasmTypeReg, publicKey, 264), duration: new u64(plasmTypeReg, duration), value: new u128(plasmTypeReg, value), }, ); return lockParam; } /** * signature message that is used for the claim_to() function. * sign this message with a ECDSA private key to generate the correct signature. * the 0x prefix will be automatically removed * @param claimId lockdrop claim ID in hex string * @param plasmAddress plasm network public address in ss58 encoding. This is the receiving address */ export const claimToMessage = (claimId: string, plasmAddress: string) => { const addressHex = polkadotUtils.u8aToHex(polkadotUtilCrypto.decodeAddress(plasmAddress)).replace('0x', ''); return `I declare to claim lockdrop reward with ID ${claimId.replace('0x', '')} to AccountId ${addressHex}`; }; /** * sends the unclaimed lockdrop reward to the given plasm address. * the signature must derive from the public key that made the lock. * @param api plasm network API instance * @param claimId lockdrop claim ID hash in raw byte stream * @param recipient plasm address in decoded form * @param signature hex string without the 0x for the ECDSA signature from the user */ export async function claimTo( api: ApiPromise, claimId: Uint8Array, recipient: Uint8Array | string, signature: Uint8Array, ) { const encodedAddr = recipient instanceof Uint8Array ? polkadotUtilCrypto.encodeAddress(recipient) : recipient; const addrCheck = polkadotUtilCrypto.checkAddress(encodedAddr, 5); if (!addrCheck[0]) { throw new Error('Plasm address check error: ' + addrCheck[1]); } const claimToTx = api.tx.plasmLockdrop.claimTo(claimId, encodedAddr, signature); const txHash = await claimToTx.send(); return txHash; } /** * submits a real-time lockdrop claim request to plasm node and returns the transaction hash. * this is a unsigned transaction that is only authenticated by a simple PoW to prevent spamming * @param api plasm node api instance (polkadot-js api) * @param lockParam lockdrop parameter that contains the lock data * @param nonce nonce for PoW authentication with the node */ export async function sendLockClaimRequest(api: ApiPromise, lockParam: Struct, nonce: Uint8Array): Promise<Hash> { if (typeof api.tx.plasmLockdrop === 'undefined') { throw new Error('Plasm node cannot find lockdrop module'); } const claimRequestTx = api.tx.plasmLockdrop.request(lockParam.toU8a(), nonce); const txHash = await claimRequestTx.send(); return txHash; } /** * generates a Plasm public address with the given ethereum public key * @param ethPubKey an compressed ECDSA public key. With or without the 0x prefix */ export function generatePlmAddress(publicKey: string) { // converts a given hex string into Uint8Array const toByteArray = (hexString: string) => { const result = []; for (let i = 0; i < hexString.length; i += 2) { result.push(parseInt(hexString.substr(i, 2), 16)); } return new Uint8Array(result); }; // hash to blake2 const plasmPubKey = polkadotUtilCrypto.blake2AsU8a(toByteArray(publicKey.replace('0x', '')), 256); // encode address const plasmAddress = polkadotUtilCrypto.encodeAddress(plasmPubKey, 5); return plasmAddress; } /** * Fetches the number of free balance for the given address in femto. * @param api polkadot-js api instance * @param plasmAddress Plasm network address * @param asPlm if the output value should be in PLM. Default denominator is in femto */ export async function getAddressBalance(api: ApiPromise, plasmAddress: string | Uint8Array, asPlm?: boolean) { const encodedAddr = plasmAddress instanceof Uint8Array ? polkadotUtilCrypto.encodeAddress(plasmAddress) : plasmAddress; const addrCheck = polkadotUtilCrypto.checkAddress(encodedAddr, 5); if (!addrCheck[0]) { throw new Error('Plasm address check error: ' + addrCheck[1]); } const { data: balance } = await api.query.system.account(plasmAddress); let _bal = new BigNumber(balance.free.toString()); if (asPlm) { _bal = femtoToPlm(new BigNumber(balance.free.toString())); } return _bal; } /** * Fetches Plasm real-time lockdrop vote threshold and positive vote values. * @param api polkadot-js api instance */ export async function getLockdropVoteRequirements(api: ApiPromise) { // number of minium votes required for a claim request to be accepted const _voteThreshold = Number.parseInt((await api.query.plasmLockdrop.voteThreshold()).toString()); // number of outstanding votes (approve votes - decline votes) required for a claim request to be accepted const _positiveVotes = Number.parseInt((await api.query.plasmLockdrop.positiveVotes()).toString()); return { voteThreshold: _voteThreshold, positiveVotes: _positiveVotes, }; } /** * sends a lockdrop claim request to Plasm net node. This will fund the ECDSA address. * @param api polkadot API instance * @param claimId real-time lockdrop claim ID */ export async function sendLockdropClaim(api: ApiPromise, claimId: Uint8Array | H256) { if (typeof api.tx.plasmLockdrop === 'undefined') { throw new Error('Plasm node cannot find lockdrop module'); } const claimRequestTx = api.tx.plasmLockdrop.claim(claimId); const txHash = await claimRequestTx.send(); return txHash; } /** * Plasm network real-time lockdrop claim data query wrapper. * This will query the node with the given claim ID and wrap the data to a readable interface. * This function will return undefined if the claim data does not exists on the chain. * @param api Polkadot-js API instance * @param claimId real-time lockdrop claim ID */ export async function getClaimStatus(api: ApiPromise, claimId: Uint8Array | H256) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const claim = (await api.query.plasmLockdrop.claims(claimId)) as any; // wrap block query data to TypeScript interface const data: Claim = { params: { // we use snake case here because this data is directly parsed from the node type: claim.get('params').get('type'), transactionHash: claim.get('params').get('transaction_hash'), publicKey: claim.get('params').get('public_key'), duration: claim.get('params').get('duration'), value: claim.get('params').get('value'), }, approve: claim.get('approve'), decline: claim.get('decline'), amount: claim.get('amount'), complete: claim.get('complete'), }; // eslint-disable-next-line @typescript-eslint/no-unused-vars for (const [_key, value] of Object.entries(data.params)) { // check if data exists on chain if ( typeof value === 'undefined' || value.toHex() === '0x000000000000000000000000000000000000000000000000000000000000000000' || // pub key value.toHex() === '0x0000000000000000000000000000000000000000000000000000000000000000' // tx hash ) { return undefined; } } return data; } export async function getLockdropAlpha(api: ApiPromise) { const alpha = await api.query.plasmLockdrop.alpha(); // the queried data will always be a whole number, but the calculated data is between 0 ~ 1. // so we need to manually convert them return parseFloat('0.' + alpha.toString()); } export function subscribeCoinRate(api: ApiPromise, subscribeCallback: (rate: [number, number]) => void) { //const rate = ((await api.query.plasmLockdrop.dollarRate()) as unknown) as [number, number]; const unsub = api.query.plasmLockdrop.dollarRate(data => { const _rate = (data as unknown) as [number, number]; subscribeCallback(_rate); }); return unsub; } export async function getCoinRate(api: ApiPromise) { const rate = ((await api.query.plasmLockdrop.dollarRate()) as unknown) as [number, number]; return rate; } /** * converts lockdrop parameter into a Lockdrop type * @param lockdropParam lockdrop parameter type in polakdot-js structure */ export function structToLockdrop(lockdropParam: Struct) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const claim = lockdropParam as any; const param: Lockdrop = { type: claim.get('type'), transactionHash: claim.get('transactionHash'), publicKey: claim.get('publicKey'), duration: claim.get('duration'), value: claim.get('value'), }; return param; } const durationToEpoch = (duration: number) => { const epochDays = 60 * 60 * 24; return duration * epochDays; }; /** * converts all lockdrops on ethereum into plasm lockdrop claim parameter * @param pubKey the public key of the locker * @param locks the lock event that has been parsed from the chain * @param latestBlock the current highest ethereum block number */ export const getClaimParamsFromEth = (pubKey: string, locks: LockEvent[], latestBlock: number) => { if (typeof pubKey === 'undefined' || pubKey === '') { throw new Error('No public key was provided'); } if (locks.length === 0) { throw new Error('No lock events found'); } const claimableLocks = locks.filter(i => { // check if the lock as been confirmed for at least 5 blocks const blockPassed = i.blockNo + 5 < latestBlock; return blockPassed; }); const claimIDs = claimableLocks.map(lock => { const _param = createLockParam( LockdropType.Ethereum, lock.transactionHash, pubKey, durationToEpoch(lock.duration).toString(), lock.eth.toString(), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any return structToLockdrop(_param as any); }); return claimIDs; }; <file_sep>/src/tests/plasmLock.test.ts /* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/camelcase */ import EthCrypto from 'eth-crypto'; import * as polkadotCryptoUtil from '@polkadot/util-crypto'; import * as polkadotUtil from '@polkadot/util'; import * as plasmUtils from '../helpers/plasmUtils'; import { ApiPromise, Keyring } from '@polkadot/api'; import BN from 'bn.js'; import { LockdropType } from 'src/types/LockdropModels'; const ethPubKey = '<KEY>'; const plasmPubKey = '215a9a3e38ba3dcaf8120046e3f4b385b25016575ab8564973edfdb64528493b'; const sampleClaimId = '0xa94710e9db798a7d1e977b9f748ae802031eee<KEY>'; const sampleLock = plasmUtils.createLockParam( LockdropType.Ethereum, '<KEY>', '0x039360c9cbbede9ee771a55581d4a53cbcc4640953169549993a3b0e6ec7984061', '2592000', '100000000000000000', ); const ropstenLock = plasmUtils.createLockParam( LockdropType.Ethereum, '0x896d1cbe07c0207b714d87bcde04a535fec049a62c4e279dc2a6b71108afa523', '0x039360c9cbbede9ee771a55581d4a53cbcc4640953169549993a3b0e6ec7984061', '2592000', '100000000000000000', ); const btcTestnet3Lock = plasmUtils.createLockParam( LockdropType.Bitcoin, '0xfd97647c573e2cde683992780c4bad2046ebbe9f90c1a44dfe4a152f3203016c', '0x02d9956c1c39d8c1e67e57de7310757b59102225839343f71d808ef5365b9803db', '2592000', '100000', ); // converts a given hex string into Uint8Array const toByteArray = (hexString: string) => { const result = []; for (let i = 0; i < hexString.length; i += 2) { result.push(parseInt(hexString.substr(i, 2), 16)); } return new Uint8Array(result); }; describe('Plasm ECDSA address tests', () => { it('checks compressed ETH pub key length', () => { expect(EthCrypto.publicKey.compress(ethPubKey).length).toEqual(66); }); it('checks blake hashed pub key', () => { const compressedPubKey = EthCrypto.publicKey.compress(ethPubKey); const blakeHashed = polkadotCryptoUtil.blake2AsU8a(toByteArray(compressedPubKey), 256); expect(polkadotUtil.u8aToHex(blakeHashed)).toEqual('0x' + plasmPubKey); }); }); describe('Plasm lockdrop RPC tests', () => { // initialize a connection with the blockchain // change this to either local or dusty to switch networks and tests const plasmEndpoint = plasmUtils.PlasmNetwork.Dusty; let api: ApiPromise; const keyring = new Keyring({ type: 'sr25519', }); beforeEach(async () => { api = await plasmUtils.createPlasmInstance(plasmEndpoint); }); it('checks plasm constants', async () => { const sessionDuration = api.consts.babe.epochDuration.toNumber(); const plasmRewards = (api.consts.plasmRewards.sessionsPerEra as any).toNumber(); const maxBlockLength = api.consts.system.maximumBlockLength.toNumber(); expect(sessionDuration).toEqual(1440); expect(plasmRewards).toEqual(6); expect(maxBlockLength).toEqual(5242880); }); it('queries plasm account balance', async () => { // the alice wallet from a dev chain const alice = keyring.addFromUri('//Alice', { name: '<NAME>', }); // account that has tokens both on main net and dusty const bob = (plasmEndpoint as plasmUtils.PlasmNetwork) === plasmUtils.PlasmNetwork.Dusty ? 'Wh2nf6F5ZNJguoQu22Z361xo6VFqX1Y2BuQMcJBSJxERh5E' : '5FHne<KEY>'; // only make a transfer if it's connected to a local node if ((plasmEndpoint as plasmUtils.PlasmNetwork) === plasmUtils.PlasmNetwork.Local) { // Create a extrinsic, transferring 12345 units to Bob const transfer = api.tx.balances.transfer(bob, '100000000000'); // Sign and send the transaction using our account await transfer.signAndSend(alice, ({ status }) => { console.log('tx status', status.toHuman()); }); } const { data: balance } = await api.query.system.account(bob); console.log(`has balance of ${balance.free}`); expect(new BN('100000000000').lte(balance.free.toBn())).toBeTruthy(); }); it('checks lockdrop parameter conversion', () => { const param = plasmUtils.structToLockdrop(ropstenLock as any); expect(param.duration.toString()).toEqual(ropstenLock.get('duration')?.toString()); const param2 = plasmUtils.structToLockdrop(btcTestnet3Lock as any); expect(param2.transactionHash.toString()).toEqual(btcTestnet3Lock.get('transactionHash')?.toString()); }); it( 'lock/claim Ropsten transactions', async () => { const nonce = plasmUtils.claimPowNonce(ropstenLock.hash); console.log('claim nonce: ' + polkadotUtil.u8aToHex(nonce)); console.log('claim ID: ' + ropstenLock.hash.toString()); const claimRequestTx = api.tx.plasmLockdrop.request(ropstenLock.toU8a(), nonce); await claimRequestTx.send(); //const claimData = await api.query.plasmLockdrop.claims(ropstenLock.hash); const claimData = await plasmUtils.getClaimStatus(api, ropstenLock.hash); const claimAmount = new BN(claimData!.amount.toString()); console.log('Receiving amount: ' + claimAmount.toString()); expect(claimData!.params.value.toString()).toEqual(ropstenLock.get('value')?.toString()); }, 200 * 1000, ); it( 'lock/claim Ropsten transactions with plasm utils', async () => { const nonce = plasmUtils.claimPowNonce(sampleLock.hash); console.log('claim nonce: ' + polkadotUtil.u8aToHex(nonce)); console.log('claim ID: ' + sampleLock.hash.toString()); await plasmUtils.sendLockClaimRequest(api, sampleLock as any, nonce); const claimData = await plasmUtils.getClaimStatus(api, sampleLock.hash); const claimAmount = new BN(claimData!.amount.toString()); console.log('Receiving amount: ' + claimAmount.toString()); expect(claimData!.params.value.toString()).toEqual(sampleLock.get('value')?.toString()); }, 200 * 1000, ); // it( // 'lock/claim BTC testnet3 transactions', // async () => { // // const nonce = plasmUtils.claimPowNonce(btcTestnet3Lock.hash); // // console.log('claim nonce: ' + polkadotUtil.u8aToHex(nonce)); // // console.log('claim ID: ' + ropstenLock.hash.toString()); // // const claimRequestTx = api.tx.plasmLockdrop.request(btcTestnet3Lock.toU8a(), nonce); // // await claimRequestTx.send(); // //const claimData = await api.query.plasmLockdrop.claims(btcTestnet3Lock.hash); // const claimData = await plasmUtils.getClaimStatus(api, btcTestnet3Lock.hash); // const claimAmount = new BN(claimData!.amount.toString()); // console.log('Receiving amount: ' + claimAmount.toString()); // expect(claimData!.params.value.toString()).toEqual(btcTestnet3Lock.get('value')?.toString()); // }, // 200 * 1000, // ); it('checks lockdrop voting requirements', async () => { const _voteThreshold = Number.parseInt((await api.query.plasmLockdrop.voteThreshold()).toString()); const _positiveVotes = Number.parseInt((await api.query.plasmLockdrop.positiveVotes()).toString()); expect(_voteThreshold).toEqual(5); expect(_positiveVotes).toEqual(4); }); }); describe('real-time lockdrop claim hash tests', () => { it('checks claim request hashing', () => { expect(sampleLock.hash.toHex() === sampleClaimId).toEqual(true); }); it('performs a simple PoW security check', () => { const nonce = plasmUtils.claimPowNonce(sampleLock.hash); const powData = polkadotUtil.u8aConcat(sampleClaimId, nonce); const powHash = polkadotCryptoUtil.blake2AsU8a(powData); expect(powHash[0]).toEqual(0); }); // it('checks claim_to() function request from an Ethereum address', () => { // const unclaimedId = '0x7fc5a41bf6765bc018fbe70e794df6d6c29f6f4e5850bd2a50c1309bcfd18a6f'; // }); }); <file_sep>/src/data/pages.ts import ethLogo from '../resources/ethereum_logo.svg'; import btcLogo from '../resources/bitcoin_logo.svg'; import { LockMenu } from '../types/LockdropModels'; import { firstLockdropStart, firstLockdropEnd, secondLockdropStart, secondLockdropEnd } from './lockInfo'; export const firstLock: LockMenu[] = [ { title: 'ETH Lock', uri: '/lock-form/first', icon: ethLogo, startDate: firstLockdropStart, endDate: firstLockdropEnd, }, ]; export const secondLock: LockMenu[] = [ { title: 'ETH Lock', uri: '/lock-form/second-eth', icon: ethLogo, startDate: secondLockdropStart, endDate: secondLockdropEnd, }, // { // title: 'BTC Lock', // uri: '/lock-form/first', // icon: btcLogo, // startDate: secondLockdropStart, // endDate: secondLockdropEnd, // disabled: true, // }, ]; export const dustyLock: LockMenu[] = [ { title: 'ETH Lock', uri: '/lock-form/dusty-eth', icon: ethLogo, startDate: firstLockdropStart, endDate: firstLockdropEnd, }, { title: 'BTC Lock', uri: '/lock-form/dusty-btc', icon: btcLogo, startDate: firstLockdropStart, endDate: firstLockdropEnd, }, ]; <file_sep>/src/helpers/lockdrop/EthereumLockdrop.ts /* eslint-disable @typescript-eslint/no-explicit-any */ // This module is used for communicating with the Ethereum smart contract import Lockdrop from '../../contracts/Lockdrop.json'; import getWeb3 from '../getWeb3'; import Web3 from 'web3'; import { Contract } from 'web3-eth-contract'; import { LockEvent, LockInput } from '../../types/LockdropModels'; import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { isValidIntroducerAddress, defaultAddress, affiliationRate } from '../../data/affiliationProgram'; import { lockDurationToRate } from '../plasmUtils'; import { PlmDrop } from '../../types/PlasmDrop'; import Web3Utils from 'web3-utils'; import * as ethereumUtils from 'ethereumjs-util'; import EthCrypto from 'eth-crypto'; import { firstLockContract, secondLockContract } from 'src/data/lockInfo'; /** * exchange rate at the start of April 14 UTC (at the end of the first lockdrop) * this is only used for the first lockdrop */ export const ethFinalExRate = 205.56; // the total amount of issueing PLMs at 1st Lockdrop. const totalAmountOfPLMs = new BigNumber('500000000.000000000000000'); const totalAmountOfPLMsForLockdrop = totalAmountOfPLMs.times(new BigNumber('17').div(new BigNumber('20'))); /** * retrieves the ECDSA signature from the given message via Web3js client call. * this will either return the v, r, s values, or the full sig in hex string * @param web3 web3js api instance * @param message message string to sign * @param asSigParam return ECDSA sig param if true (i.e. only v, r, s values) */ export async function getMessageSignature<T extends boolean>( web3: Web3, message: string, asSigParam: T, ): Promise<T extends true ? ethereumUtils.ECDSASignature : string>; export async function getMessageSignature(web3: Web3, message: string, asSigParam: boolean) { const addresses = await web3.eth.getAccounts(); // ask the user to sign the message // the password parameter is only used for specific wallets (most wallets will prompt the user to provide it) const sig = '0x' + (await web3.eth.personal.sign(message, addresses[0], 'SecureP4ssW0rd')).slice(2); const res = ethereumUtils.fromRpcSig(sig); if (!ethereumUtils.isValidSignature(res.v, res.r, res.s)) { throw new Error('Invalid signature'); } if (asSigParam) { return res; } else { return sig; } } /** * asks the user to sign a hashed message from their dApp browser to recover the user's public key. * This will return a compressed public key. * @param web3 a web3.js instance to access the user's wallet information * @param message an optional message that the user should sign */ export async function getPubKey(web3: Web3, message?: string) { // default message let msg = 'Please Sign this message to generate Plasm Network address'; // change message if the function provides one if (message) { msg = message; } const hash = web3.eth.accounts.hashMessage(msg); const res = (await getMessageSignature(web3, msg, true)) as ethereumUtils.ECDSASignature; const publicKey = ethereumUtils.bufferToHex( ethereumUtils.ecrecover(ethereumUtils.toBuffer(hash), res.v, res.r, res.s), ); const compressedPubKey = '0x' + EthCrypto.publicKey.compress(publicKey.replace('0x', '')); return compressedPubKey; } export async function fetchAllAddresses(web3: Web3) { // get user account from injected web3 const ethAddr = await web3.eth.getAccounts(); // throw if the address is still 0 if (ethAddr.length === 0) throw new Error('Could not fetch address from wallet'); return ethAddr; } /** * returns an array of locked events for the lock contract * this function searches from the genesis block * @param web3 a web3.js instance to interact with the blockchain * @param instance a contract instance to parse the contract events */ export async function getAllLockEvents(web3: Web3, instance: Contract): Promise<LockEvent[]> { const contractAddr = instance.options.address; const allContractList = [...firstLockContract, ...secondLockContract]; // set the correct block number const mainnetStartBlock = allContractList.find(i => i.address.toLowerCase() === contractAddr.toLowerCase()) ?.blockHeight; const ev = await instance.getPastEvents('Locked', { fromBlock: mainnetStartBlock }); const eventHashes = await Promise.all( ev.map(async e => { return Promise.all([Promise.resolve(e.returnValues), web3.eth.getTransaction(e.transactionHash)]); }), ); return Promise.all( eventHashes.map(async e => { // e[0] is lock event and e[1] is block hash const blockHash = e[1]; const lockEvent = e[0]; const transactionString = await Promise.resolve(web3.eth.getBlock(blockHash.blockNumber as number)); const time = transactionString.timestamp.toString(); return { eth: lockEvent.eth as BN, duration: lockEvent.duration as number, lock: lockEvent.lock as string, introducer: lockEvent.introducer as string, blockNo: blockHash.blockNumber, timestamp: time, lockOwner: blockHash.from, transactionHash: blockHash.hash, } as LockEvent; }), ); } /** * returns a 0 ethereum address if an empty string was provided. * this function is used for lockers with no introducers * @param aff a valid introducer ETH address */ export function defaultAffiliation(aff: string) { // check if affiliation address is not empty and is not themselves if (aff) { // return itself when it is a valid address return aff; } else { // if it is an invalid address, return the default affiliation address return defaultAddress; } } function plmBaseIssueRatio(lockData: LockEvent, ethExchangeRate: BigNumber): BigNumber { // get lockTimeBonus * ethExRate const bonusRate = new BigNumber(lockDurationToRate(lockData.duration)).times(ethExchangeRate); // calculate issuingPLMRate = lockedEth([ETH]) * lockBonusRate * ethExRate const issuingRatio: BigNumber = new BigNumber(Web3Utils.fromWei(lockData.eth.toString(), 'ether')).times( new BigNumber(bonusRate), ); return issuingRatio; } function totalPlmBaseIssuingRate(allLocks: LockEvent[], ethExchangeRate: BigNumber): BigNumber { return allLocks.reduce( (sum: BigNumber, value: LockEvent): BigNumber => sum.plus(plmBaseIssueRatio(value, ethExchangeRate)), new BigNumber(0), ); } function plmBaseIssueAmountInLock(lock: LockEvent, totalPlmsRate: BigNumber, ethExchangeRate: BigNumber): BigNumber { const currentIssue = plmBaseIssueRatio(lock, ethExchangeRate); return totalAmountOfPLMsForLockdrop.times(currentIssue).div(totalPlmsRate); } /** * returns an array of addresses that referenced the given address for the affiliation program * @param address ETH address * @param lockData list of contract lock event */ function getAllAffReferences(address: string, lockData: LockEvent[]) { // check if there is const results: LockEvent[] = []; const refEvents = lockData.filter(e => e.introducer.toLowerCase() === address.toLowerCase()); for (let i = 0; i < refEvents.length; i++) { results.push(refEvents[i]); } return results; } export function calculateNetworkAlpha(allLocks: LockEvent[]): BigNumber { const ethExchangeRate = new BigNumber(ethFinalExRate); const totalPlmRate = totalPlmBaseIssuingRate(allLocks, ethExchangeRate); // alpha_1 = totalAmountOfPLMsForLockdrop /totalPlmRate const alpha1 = totalAmountOfPLMsForLockdrop.div(totalPlmRate); return alpha1; } /** * calculate the total receiving PLMs from the lockdrop including the affiliation program bonus * in this function, affiliation means the current address being referenced by others * and introducer means this address referencing other affiliated addresses * @param address the lockdrop participant's ETH address * @param lockData a list of lockdrop contract events */ export function calculateTotalPlm(address: string, lockData: LockEvent[]): PlmDrop { const receivingPlm = new PlmDrop(address, new BigNumber(0), [], [], []); const currentAddressLocks = lockData.filter(i => i.lockOwner.toLowerCase() === address.toLowerCase()); receivingPlm.locks = currentAddressLocks; const ethExchangeRate = new BigNumber(ethFinalExRate); // get total plm rate for calculating actual issuing PLMs. const totalPlmRate = totalPlmBaseIssuingRate(lockData, ethExchangeRate); for (let i = 0; i < currentAddressLocks.length; i++) { // calculate total base issuing PLM tokens const issuingPlm = plmBaseIssueAmountInLock(currentAddressLocks[i], totalPlmRate, ethExchangeRate); // add value to the total amount receivingPlm.basePlm = receivingPlm.basePlm.plus(issuingPlm); // self -> introducer : bonus getting PLMs. // check if this address has an introducer if ( isValidIntroducerAddress(currentAddressLocks[i].introducer) && currentAddressLocks[i].introducer !== defaultAddress ) { receivingPlm.introducerAndBonuses.push([ currentAddressLocks[i].introducer, issuingPlm.times(new BigNumber(affiliationRate)), ]); } } // someone -> self(introducer) : bonus getting PLMs. // calculate affiliation bonus for this address if (isValidIntroducerAddress(address)) { const allRefs = getAllAffReferences(address, lockData); for (let i = 0; i < allRefs.length; i++) { // reference amount * 0.01 receivingPlm.affiliationRefsBonuses.push([ allRefs[i].lock, plmBaseIssueAmountInLock(allRefs[i], totalPlmRate, ethExchangeRate).times( new BigNumber(affiliationRate), ), ]); } } return receivingPlm; } /** * parses through the given lock events to calculate the total amount of locked ETH * @param locks a list of lockdrop contract events */ export function getTotalLockVal(locks: LockEvent[]): string { let totalVal = new BigNumber(0); if (locks.length > 0) { for (let i = 0; i < locks.length; i++) { const currentEth = new BigNumber(locks[i].eth.toString()); totalVal = totalVal.plus(currentEth); } } return Web3Utils.fromWei(totalVal.toFixed(), 'ether'); } /** * creates a smart contract instance based on the contract address * @param web3 web3js API instance * @param contractAddress smart contract address */ export async function createContractInstance(web3: Web3, contractAddress: string) { const lockdropAbi = Lockdrop.abi as Web3Utils.AbiItem[]; // create an empty contract instance first return new web3.eth.Contract(lockdropAbi, contractAddress); } /** * returns the unlock date of the given ethereum lock event. * this will return the unlock date in unix time (seconds) * @param lockInfo */ export const getUnlockDate = (lockInfo: LockEvent) => { // 24 hours in epoch const epochDay = 60 * 60 * 24; // Ethereum lock timestamp is in integers const lockedDay = parseInt(lockInfo.timestamp); // locked date + lock duration in days to epoch const unlockDate = lockedDay + lockInfo.duration * epochDay; return unlockDate; }; /** * authenticate if the client has web3 enabled wallet installed and can communicate with the blockchain * returns the web3.js instance, list of active accounts and the contract instance * @param contractAddress the contract address that it should look for */ export async function connectWeb3() { // Get network provider and web3 instance. const web3 = await getWeb3(); if (web3 instanceof Web3) { return web3; } else { throw new Error('Cannot get Web3 instance from the client'); } } /** * returns the UTC (in seconds) epoch string of when the lockdrop smart contract will end * @param contract the lockdrop contract instance */ export async function getContractEndDate(contract: Contract) { const _lockdropEndDate = await contract.methods.LOCK_END_TIME().call(); return _lockdropEndDate as string; } /** * returns the UTC (in seconds) epoch string of when the lockdrop smart contract will start * @param contract the lockdrop contract instance */ export async function getContractStartDate(contract: Contract) { const _lockdropStartDate = await contract.methods.LOCK_START_TIME().call(); return _lockdropStartDate as string; } /** * validate and create a transaction to the lock contract with the given parameter. * This will return the transaction hash * @param txInput the lock parameter for the contract * @param address the address of the locker * @param contract smart contract instance used to invoke the contract method */ export async function submitLockTx(txInput: LockInput, address: string, contract: Contract) { // checks user input if (txInput.amount <= new BN(0) || txInput.duration <= 0) { throw new Error('You are missing an input!'); } // return a default address if user input is empty const introducer = defaultAffiliation(txInput.affiliation).toLowerCase(); // check user input if (introducer === address) { throw new Error('You cannot affiliate yourself'); } if (introducer && !Web3.utils.isAddress(introducer)) { throw new Error('Please input a valid Ethereum address'); } if (!isValidIntroducerAddress(introducer)) { throw new Error('Please input a valid introducer address.'); } // convert user input to Wei const amountToSend = Web3.utils.toWei(txInput.amount, 'ether'); let hash = ''; // communicate with the smart contract await contract.methods .lock(txInput.duration, introducer) .send({ from: address, value: amountToSend, }) .on('transactionHash', (res: any) => { hash = res; }); if (hash === '') { throw new Error('An error has occurred while trying to send transaction'); } return hash; } <file_sep>/src/helpers/lockdrop/BitcoinLockdrop.ts /* eslint-disable @typescript-eslint/no-non-null-assertion */ import * as bitcoinjs from 'bitcoinjs-lib'; import bip68 from 'bip68'; import { LockdropType, HwSigner } from '../../types/LockdropModels'; import { Network } from 'bitcoinjs-lib'; import BigNumber from 'bignumber.js'; import * as plasmUtils from '../plasmUtils'; import { BlockStreamApi } from 'src/types/BlockStreamTypes'; import { SoChainApi } from 'src/types/SoChainTypes'; import AppBtc from '@ledgerhq/hw-app-btc'; import * as LedgerTypes from '../../types/LedgerTypes'; import * as bitcoinjsMessage from 'bitcoinjs-message'; // https://www.blockchain.com/api/api_websocket export const BLOCKCHAIN_WS = 'wss://ws.blockchain.info/inv'; /** * the message that will be hashed and signed by the client */ export const MESSAGE = 'plasm network btc lock'; //todo: add nonce for security /** * returns a blob url for the qr encoded bitcoin address * @param btcAddress bitcoin address */ export async function qrEncodeUri(btcAddress: string, size = 300) { const qrCode = URL.createObjectURL( await fetch(`https://chart.googleapis.com/chart?chs=${size}x${size}&cht=qr&chl=${btcAddress}`).then(res => res.blob(), ), ); return qrCode; } /** * Returns a list of transactions from the given address. * This data is fetched from BlockStream * @param address BTC address to look for * @param network BTC network token (mainnet or testnet) */ export async function getBtcTxsFromAddress(address: string, network: 'mainnet' | 'testnet') { const api = `https://blockstream.info/${network === 'mainnet' ? '' : 'testnet/'}api/address/${address}/txs`; const res = await (await fetch(api)).text(); if (res.includes('Invalid Bitcoin address')) { throw new Error('Invalid Bitcoin address'); } const txs: BlockStreamApi.Transaction[] = JSON.parse(res); return txs; } /** * Returns the transaction information from the given transaction hash/TXID. * This data is fetched from BlockStream * @param txid transaction hash or TXID in hex string * @param network BTC network token (mainnet or testnet) */ export async function getBtcTxFromTxId(txid: string, network: 'mainnet' | 'testnet') { const api = `https://blockstream.info/${network === 'mainnet' ? '' : 'testnet/'}api/tx/${txid.replace('0x', '')}`; const res = await (await fetch(api)).text(); if (res.includes('Invalid hex string')) { throw new Error('Invalid hex string'); } const tx: BlockStreamApi.Transaction = JSON.parse(res); return tx; } /** * returns the transaction information including the inputs and outputs from ledger node API. * @param txId bitcoin transaction hash * @param isTestnet check if looking for BTC testnet */ export async function getTransactionEndpoint(txId: string, isTestnet?: boolean) { const network = isTestnet ? 'btc_testnet' : 'btc'; const api = `https://api.ledgerwallet.com/blockchain/v2/${network}/transactions/${txId}`; const res = await (await fetch(api)).text(); if (res.includes('error')) { throw new Error(res); } const hashEndpoint: LedgerTypes.Transaction = JSON.parse(res); return hashEndpoint; } /** * returns a raw transaction in hex strings from SoChain REST API. * @param txId transaction ID or transaction hash * @param network BTC network to choose from */ export async function getTransactionHex(txId: string, network: 'BTC' | 'BTCTEST') { const api = `https://sochain.com/api/v2/get_tx/${network}/${txId}`; const res = await (await fetch(api)).text(); if (res.includes('fail')) { throw new Error(res); } const txHex: SoChainApi.Transaction = JSON.parse(res); return txHex.data.tx_hex; } /** * Broadcasts the given transaction hex through BlockStream REST API * @param txHex raw transaction in hex string * @param network bitcoin network to broadcast for */ export async function broadcastTransaction(txHex: string, network: 'mainnet' | 'testnet') { const api = `https://blockstream.info/${network === 'mainnet' ? '' : 'testnet/'}api/tx`; const res = await fetch(api, { method: 'POST', body: txHex, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }, }); const responseText = await res.text(); if (!res.ok || responseText.includes('error')) { throw new Error('Failed to broadcast the transaction:\n' + responseText); } console.log(responseText); // returns a tx ID if everything went well return responseText; } /** * Validates the given BTC address by checking if it's in the correct format. * The default network is set to mainnet, byt anything else will require you to explicitly * pass it as the parameter. * @param address Bitcoin public address * @param network bitcoin network type (bitcoinjs-lib) */ export function validateBtcAddress(address: string, network?: bitcoinjs.networks.Network) { try { bitcoinjs.address.toOutputScript(address, network); return true; } catch (e) { return false; } } /** * Validates the given public key hex by importing it through bitcoinjs ECPair. * Returns true if it's valid, and false if it's invalid * @param publicKey Bitcoin public key hex string * @param network bitcoin network to check from. Defaults to mainnet */ export function validatePublicKey(publicKey: string, network?: bitcoinjs.networks.Network) { try { bitcoinjs.ECPair.fromPublicKey(Buffer.from(publicKey, 'hex'), { network: network }); const { address } = bitcoinjs.payments.p2pkh({ pubkey: Buffer.from(publicKey, 'hex'), network: network }); if (typeof address === 'string' && !validateBtcAddress(address, network)) { throw new Error('Invalid public key'); } return true; } catch (e) { return false; } } /** * returns the network type that the given address belongs to. * this will also validate the address before returning a value. * @param address bitcoin address */ export function getNetworkFromAddress(address: string) { // sources: https://en.bitcoin.it/wiki/List_of_address_prefixes // main net public key hash prefixes const mainNetPref = ['1', '3', 'bc1']; // test net public key hash prefixes const testNetPref = ['m', 'n', 'tb1', '2']; let addressNetwork: bitcoinjs.networks.Network; if (new RegExp(`^(${mainNetPref.join('|')})`).test(address)) { // check for regex match from the given address and array addressNetwork = bitcoinjs.networks.bitcoin; //return bitcoinjs.networks.bitcoin; } else if (new RegExp(`^(${testNetPref.join('|')})`).test(address)) { addressNetwork = bitcoinjs.networks.testnet; //return bitcoinjs.networks.testnet; } else { throw new Error('Invalid Bitcoin address'); } if (!validateBtcAddress(address, addressNetwork)) { throw new Error('Invalid Bitcoin address'); } return addressNetwork; } /** * converts satoshi to bitcoin * @param satoshi number of satoshi */ export function satoshiToBitcoin(satoshi: BigNumber | number | string) { // 1 bitcoin = 100,000,000 satoshi const denominator = new BigNumber(10).pow(new BigNumber(8)); if (typeof satoshi === 'string' || typeof satoshi === 'number') { const _satNum = typeof satoshi === 'string' ? parseInt(satoshi) : satoshi; if (isNaN(_satNum)) { throw new Error('Provided value is not a number'); } if (_satNum < 0) { throw new Error('Provided value cannot be negative'); } } return new BigNumber(satoshi).div(denominator); } /** * converts bitcoin into satoshi * @param bitcoin number of bitcoin */ export function bitcoinToSatoshi(bitcoin: BigNumber | number | string) { // 1 bitcoin = 100,000,000 satoshis const denominator = new BigNumber('100000000'); if (typeof bitcoin === 'number' || typeof bitcoin === 'string') { const _btcNum = typeof bitcoin === 'string' ? parseFloat(bitcoin) : bitcoin; if (isNaN(_btcNum)) { throw new Error('Provided value is not a number'); } if (_btcNum < 0) { throw new Error('Provided value cannot be negative'); } } return new BigNumber(bitcoin).multipliedBy(denominator).integerValue(); } /** * converts an compressed public key to a uncompressed public key * @param publicKey compressed BTC public key */ export function decompressPubKey(publicKey: string, network: bitcoinjs.Network) { const pubKeyPair = bitcoinjs.ECPair.fromPublicKey(Buffer.from(publicKey, 'hex'), { compressed: false, network: network, }); return pubKeyPair.publicKey.toString('hex'); } /** * compresses the given BTC public key * @param publicKey uncompressed BTC public key * @param network bitcoin network the public key will encode for */ export function compressPubKey(publicKey: string, network: bitcoinjs.Network) { const pubKeyPair = bitcoinjs.ECPair.fromPublicKey(Buffer.from(publicKey, 'hex'), { compressed: true, network: network, }); return pubKeyPair.publicKey.toString('hex'); } /** * returns a compressed public key from the given address and signature. * this function will only work with BIP44 encoded address. BIP49 or BIP84 will return * an error. * @param address bitcoin address in base58 string * @param signature the signature in base64 string or buffer * @param msg message that was used to sign excluding the prefix in string * @param network bitcoin network this belongs to. If none is given, the function will guess one */ export function getPublicKey(address: string, signature: string | Buffer, msg: string, network?: bitcoinjs.Network) { const _net = network ? network : getNetworkFromAddress(address); // returns a compressed public key by default const _pubKey = bitcoinjsMessage.recover(msg, address, signature); const recoveredAddress = bitcoinjs.payments.p2pkh({ pubkey: Buffer.from(_pubKey, 'hex'), network: _net, }).address!; if (recoveredAddress !== address) { throw new Error('Could not recover public key for ' + address); } return _pubKey; } /** * used for CHECKSEQUENCEVERIFY relative time lock. * this converts days to bip68 encoded block number. * @param days number of days to be converted to sequence number */ export function daysToBlockSequence(days: number) { // verify lock days value if (!Number.isInteger(days) || !Number.isFinite(days)) { throw new Error('Lock days must be a valid integer, but received: ' + days); } const blocksPerDay = 144; //10 min per block. day = 6 * 24 const blockSequence = bip68.encode({ blocks: days * blocksPerDay }); if (blockSequence >= 65535) { // maximum lock time https://en.bitcoin.it/wiki/Timelock throw new Error('Block sequence cannot be more than 65535'); } return blockSequence; } /** * create a bitcoin lock script buffer with the given public key. * this will lock the token for the given number of block sequence. * if the given public key is not compressed, this function will compress it. * @param publicKeyHex compressed BTC public key in hex string * @param blockSequence bip68 encoded block sequence * @param network bitcoin network the public key belongs to */ export function btcLockScript(publicKeyHex: string, blockSequence: number, network: bitcoinjs.Network): Buffer { // verify block sequence value if (blockSequence < 0) { throw new Error('Block sequence cannot be a negative number'); } if (!Number.isInteger(blockSequence) || !Number.isFinite(blockSequence)) { throw new Error('Block sequence must be a valid integer, but received: ' + blockSequence); } if (blockSequence >= 65535) { // maximum lock time https://en.bitcoin.it/wiki/Timelock throw new Error('Block sequence cannot be more than 65535'); } // verify public key by converting to an address if (!validatePublicKey(publicKeyHex, network)) { throw new Error('Invalid public key'); } const pubKeyBuffer = Buffer.from(compressPubKey(publicKeyHex, network), 'hex'); return bitcoinjs.script.fromASM( ` ${bitcoinjs.script.number.encode(blockSequence).toString('hex')} OP_CHECKSEQUENCEVERIFY OP_DROP ${pubKeyBuffer.toString('hex')} OP_CHECKSIG ` .trim() .replace(/\s+/g, ' '), ); } /** * creates a P2SH instance that locks the sent token for the given duration. * the locked tokens can only be claimed by the provided public key * @param lockDays the lock duration in days * @param publicKey public key of the locker. This can be both compressed or uncompressed * @param network bitcoin network the script will generate for */ export function getLockP2SH(lockDays: number, publicKey: string, network: bitcoinjs.Network) { // only check lock duration boundaries for main net if (network === bitcoinjs.networks.bitcoin) { if (lockDays > 300 || lockDays < 30) { throw new Error('Lock duration must be between 30 days to 300 days'); } } return bitcoinjs.payments.p2sh({ network: network, redeem: { output: btcLockScript(publicKey, daysToBlockSequence(lockDays), network), }, }); } /** * creates a lock redeem UTXO * @param signer the signer for signing the transaction hash * @param network network type (bitcoinjs-lib) * @param lockTx the transaction that locks the value to P2SH address * @param lockScript the lock script (P2SH) * @param blockSequence block sequence to lock the funds, should be the same value used in the lock script * @param recipient recipient for the transaction output * @param fee transaction fee for the lock transaction */ export async function btcUnlockTx( signer: HwSigner, network: Network, lockTx: bitcoinjs.Transaction, lockScript: Buffer, blockSequence: number, recipientAddress: string, fee: number, // satoshis ) { function idToHash(txid: string): Buffer { return Buffer.from(txid, 'hex').reverse(); } function toOutputScript(address: string): Buffer { return bitcoinjs.address.toOutputScript(address, network); } if (blockSequence < 0) { throw new Error('Block sequence cannot be less than zeo'); } if (fee < 0) { throw new Error('Transaction fee cannot be less than zero'); } if (!Number.isInteger(blockSequence) || !Number.isFinite(blockSequence)) { throw new Error('Block sequence must be a valid integer, but received: ' + blockSequence); } if (!Number.isInteger(fee) || !Number.isFinite(fee)) { throw new Error('Fee must be a valid integer, but received: ' + fee); } const txIndex = 0; if (lockTx.outs[txIndex].value - fee < 0) { throw new Error(`Transaction fee cannot be larger than ${lockTx.outs[txIndex].value} Satoshi`); } //const sequence = bip68.encode({ blocks: lockBlocks }); const tx = new bitcoinjs.Transaction(); tx.version = 2; tx.addInput(idToHash(lockTx.getId()), txIndex, blockSequence); tx.addOutput(toOutputScript(recipientAddress), lockTx.outs[txIndex].value - fee); const hashType = bitcoinjs.Transaction.SIGHASH_ALL; const signatureHash = tx.hashForSignature(0, lockScript, hashType); const signature = bitcoinjs.script.signature.encode(await signer.sign(signatureHash), hashType); const redeemScriptSig = bitcoinjs.payments.p2sh({ network, redeem: { network, output: lockScript, input: bitcoinjs.script.compile([signature]), }, }).input; if (redeemScriptSig instanceof Buffer) { tx.setInputScript(0, redeemScriptSig); } else { throw new Error('Transaction is invalid'); } return tx; } /** * create a unsigned unlock transaction. This function will return a signature hash for the transaction that the user will sign, * the unsigned transaction instance and the lock P2SH payment instance that this will be unlocking for. * @param lockTransaction the lock UTXO that is already in the blockchain * @param publicKey public key of the user in string hex (compression is done within the function) * @param lockDuration script token locking duration in days (converted to relative block sequence within the function) * @param network the bitcoin network the transaction is for * @param txFee the transaction fee for the UTXO in Satoshi */ export function unsignedUnlockTx( lockTransaction: BlockStreamApi.Transaction, publicKey: string, lockDuration: number, network: bitcoinjs.Network, txFee: number, ) { const lockP2sh = getLockP2SH(lockDuration, publicKey, network); const { address } = bitcoinjs.payments.p2pkh({ pubkey: Buffer.from(publicKey, 'hex'), network }); if (typeof address === 'undefined') { throw new Error('could not get P2PKH address from the given public key'); } const lockVout = lockTransaction.vout.find(locked => locked.scriptpubkey_address === lockP2sh.address!); if (typeof lockVout === 'undefined') { throw new Error('Invalid public key provided'); } if (lockVout.value - txFee < 0) { throw new Error(`Transaction fee cannot be larger than ${lockVout.value} Satoshi`); } if (txFee <= 0) { throw new Error('Transaction fee cannot be 0 or less'); } const lockScript = btcLockScript(publicKey, daysToBlockSequence(lockDuration), network); const sequence = 0; const output = bitcoinjs.address.toOutputScript(address, network); const tx = new bitcoinjs.Transaction(); tx.version = 2; tx.addInput(Buffer.from(lockTransaction.txid, 'hex').reverse(), 0, sequence); tx.addOutput(output, lockVout.value - txFee); const hashType = bitcoinjs.Transaction.SIGHASH_ALL; const signatureHash = tx.hashForSignature(0, lockScript, hashType).toString('hex'); return { signatureHash, unsignedUnlockTx: tx, lockP2sh, }; } /** * Signs the given transaction and returns it as a raw transaction hex that is ready for being broadcasted. * The signature should be provided by the user. * @param unsignedTx transaction instance that isn't signed * @param userUnlockSig signature for the transaction signed by the sender's wallet * @param lockScript the lock script used for the lock transaction * @param network bitcoin network the transaction will be propagating for */ export function signTransactionRaw( unsignedTx: bitcoinjs.Transaction, userUnlockSig: string, lockScript: Buffer, network: bitcoinjs.Network, ) { if (userUnlockSig === '') { throw new Error('Please paste the unlock signature'); } const rawSignature = Buffer.from(userUnlockSig.replace(' ', ''), 'hex'); const signature = bitcoinjs.script.signature.encode(rawSignature, bitcoinjs.Transaction.SIGHASH_ALL); const redeemScriptSig = bitcoinjs.payments.p2sh({ network: network, redeem: { network: network, output: lockScript, input: bitcoinjs.script.compile([signature]), }, }).input; unsignedTx.setInputScript(0, redeemScriptSig!); const signedTxHex = unsignedTx.toHex(); return signedTxHex; } /** * creates a lockdrop parameter from the given lock script address and values * by fetching all transactions in the lock script address from block stream * @param scriptAddress the P2SH lock address * @param lockDuration duration of the lock in days * @param publicKey compressed BTC public key of the locker * @param network bitcoin network */ export async function getLockParameter( scriptAddress: string, lockDurationDays: number, publicKey: string, network: 'mainnet' | 'testnet', ) { const btcNetwork = network === 'mainnet' ? bitcoinjs.networks.bitcoin : bitcoinjs.networks.testnet; const p2sh = bitcoinjs.payments.p2sh({ network: btcNetwork, redeem: { output: btcLockScript(publicKey, daysToBlockSequence(lockDurationDays), btcNetwork), }, }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (p2sh.address && p2sh.address !== scriptAddress) { throw new Error('Lock script information does not match P2SH'); } if (!validatePublicKey(publicKey, btcNetwork)) { throw new Error('Invalid Public Key'); } if (lockDurationDays < 0 || !Number.isInteger(lockDurationDays)) { throw new Error('Invalid lock duration'); } const locks = await getBtcTxsFromAddress(scriptAddress, network); const daysToEpoch = 60 * 60 * 24 * lockDurationDays; const lockParams = locks.map(i => { const lockVal = i.vout.find(locked => locked.scriptpubkey_address === scriptAddress); if (typeof lockVal === 'undefined') { throw new Error('Cannot find lock transaction for ' + scriptAddress); } return plasmUtils.createLockParam( LockdropType.Bitcoin, '0x' + i.txid, '0x' + publicKey, daysToEpoch.toString(), lockVal.value.toString(), ); }); return lockParams; } /** * Creates a signer instance for signing transactions made with bitcoinjs-lib * from Ledger BTC App. * @param ledgerApi * @param path HD address path * @param network bitcoin network the transaction will belong * @param lockTxHex raw lock UTXO in hex string * @param lockScript lock script used to generate the P2SH * @param publicKey compressed public key in string format */ export const generateSigner = async ( ledgerApi: AppBtc, path: string, network: bitcoinjs.Network, lockTxHex: string, lockScript: bitcoinjs.payments.Payment, publicKey: string, ) => { const isSegWit = bitcoinjs.Transaction.fromHex(lockTxHex).hasWitnesses(); const ledgerTx = ledgerApi.splitTransaction(lockTxHex, isSegWit); const txIndex = 0; //temp value return { network, publicKey: Buffer.from(publicKey, 'hex'), sign: async (hash: Buffer, lowR?: boolean) => { console.log('signing with ledger\n' + hash.toString('hex')); const ledgerTxSignatures = await ledgerApi.signP2SHTransaction({ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion inputs: [[ledgerTx, txIndex, lockScript.redeem!.output!.toString('hex'), null]], associatedKeysets: [path], // eslint-disable-next-line @typescript-eslint/no-non-null-assertion outputScriptHex: lockScript.output!.toString('hex'), segwit: isSegWit, transactionVersion: 2, sigHashType: bitcoinjs.Transaction.SIGHASH_ALL, }); console.log(ledgerTxSignatures); console.log(hash.toString('hex') + lowR); const [ledgerSignature] = ledgerTxSignatures; const encodedSignature = (() => { if (isSegWit) { return Buffer.from(ledgerSignature, 'hex'); } return Buffer.concat([ Buffer.from(ledgerSignature, 'hex'), Buffer.from('01', 'hex'), // SIGHASH_ALL ]); })(); const decoded = bitcoinjs.script.signature.decode(encodedSignature); return decoded.signature; }, } as HwSigner; }; <file_sep>/src/types/LedgerTypes.ts export interface Block { hash: string; height: number; time: Date; } export interface Input { input_index: number; output_hash: string; output_index: number; value: number; address: string; script_signature: string; sequence: number; txinwitness: string[]; } export interface Output { output_index: number; value: number; address: string; script_hex: string; } export interface Transaction { hash: string; received_at: Date; lock_time: number; block: Block; inputs: Input[]; outputs: Output[]; fees: number; amount: number; confirmations: number; } <file_sep>/src/types/SoChainTypes.ts /* eslint-disable @typescript-eslint/no-namespace */ export declare namespace SoChainApi { export interface FromOutput { txid: string; output_no: number; } export interface Input { input_no: number; value: string; address: string; type: string; script: string; witness: string[]; from_output: FromOutput; } export interface Output { output_no: number; value: string; address: string; type: string; script: string; } export interface Data { network: string; txid: string; blockhash: string; confirmations: number; time: number; inputs: Input[]; outputs: Output[]; tx_hex: string; size: number; version: number; locktime: number; } export interface Transaction { status: string; data: Data; } } <file_sep>/src/helpers/lockdrop/PolkadotLockdrop.ts export function lockDots() { console.log('implement this!'); } <file_sep>/src/data/lockInfo.ts import { OptionItem } from '../types/LockdropModels'; import moment from 'moment'; import Lockdrop from '../contracts/Lockdrop.json'; const LOCKDROP_DURATION = 30; // days /** * the time zone is set to UTC as default * lockdrop starts from 1584230400 epoch time */ export const firstLockdropStart = moment.unix(1584230400); export const firstLockdropEnd = firstLockdropStart.clone().add(LOCKDROP_DURATION, 'days'); /** * the time zone is set to UTC as default * lockdrop starts from 1598832000 epoch time */ export const secondLockdropStart = moment.unix(1598832000); export const secondLockdropEnd = secondLockdropStart.clone().add(LOCKDROP_DURATION, 'days'); export interface LockdropContract { type: 'main' | 'ropsten' | 'private'; address: string; blockHeight: number; } export const firstLockContract: LockdropContract[] = [ { type: 'main', address: '0x458DaBf1Eff8fCdfbF0896A6Bd1F457c01E2FfD6', blockHeight: 9662816, }, { type: 'ropsten', address: '0xEEd84A89675342fB04faFE06F7BB176fE35Cb168', blockHeight: 7941301 }, { type: 'private', address: Lockdrop.networks[5777].address, blockHeight: 0 }, ]; export const secondLockContract: LockdropContract[] = [ { type: 'main', address: '0xa4803f17607B7cDC3dC579083d9a14089E87502b', blockHeight: 10714638, }, { type: 'ropsten', address: '0x69e7eb3ab94a10e4f408d842b287c70aa0d11649', blockHeight: 8257718, }, { type: 'ropsten', address: '0xa91E04a6ECF202A7628e0c9191676407015F5AF9', blockHeight: 8474518, }, { type: 'private', address: Lockdrop.networks[5777].address, blockHeight: 0 }, ]; //todo: add other contract addresses when ready export const lockdropContracts = { firstLock: { main: { address: '0x458DaBf1Eff8fCdfbF0896A6Bd1F457c01E2FfD6', blockHeight: 9662816 }, ropsten: { address: '0xEEd84A89675342fB04faFE06F7BB176fE35Cb168', blockHeight: 7941301 }, private: { address: Lockdrop.networks[5777].address, blockHeight: 0 }, }, secondLock: { main: { address: '0xa4803f17607B7cDC3dC579083d9a14089E87502b', blockHeight: 10714638 }, ropsten: [ { address: '0x69e7eb3ab94a10e4f408d842b287c70aa0d11649', blockHeight: 8257718 }, { address: '0xa91E04a6ECF202A7628e0c9191676407015F5AF9', blockHeight: 8474518 }, ], private: Lockdrop.networks[5777].address, }, thirdLock: { main: { address: '0x', blockHeight: 0 }, ropsten: { address: '0x', blockHeight: 0 }, private: { address: Lockdrop.networks[5777].address, blockHeight: 0 }, }, }; /** * used to define the content of the dropdown menu */ export const ethDurations: OptionItem[] = [ { label: '30 Days', value: 30, rate: 24 }, { label: '100 Days', value: 100, rate: 100 }, { label: '300 Days', value: 300, rate: 360 }, { label: '1000 Days', value: 1000, rate: 1600 }, ]; /** * used to define the content of the dropdown menu */ export const ethDustyDurations: OptionItem[] = [ { label: '3 Days', value: 3, rate: 24 }, { label: '10 Days', value: 10, rate: 100 }, { label: '30 Days', value: 30, rate: 360 }, { label: '100 Days', value: 100, rate: 1600 }, ]; /** * BTC lockdrop does not support 1000 days lock due to CSV lock scheme */ export const btcDurations: OptionItem[] = [ { label: '30 Days', value: 30, rate: 24 }, { label: '100 Days', value: 100, rate: 100 }, { label: '300 Days', value: 300, rate: 360 }, ]; /** * BTC lockdrop for Dusty network. The lock days are much shorter */ export const btcDustyDurations: OptionItem[] = [ { label: '3 Days', value: 3, rate: 24 }, { label: '10 Days', value: 10, rate: 100 }, { label: '30 Days', value: 30, rate: 360 }, ]; <file_sep>/src/tests/btcLock.test.ts /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { PrivateKey, Message } from 'bitcore-lib'; import wif from 'wif'; import * as bitcoin from 'bitcoinjs-lib'; import * as assert from 'assert'; import { regtestUtils } from './_regtest'; import * as btcLockdrop from '../helpers/lockdrop/BitcoinLockdrop'; import bip68 from 'bip68'; import * as plasmUtils from '../helpers/plasmUtils'; import * as polkadotCrypto from '@polkadot/util-crypto'; import * as bitcoinjsMessage from 'bitcoinjs-message'; // we use a lot of API calls in this test, it's good to extend the timeout jest.setTimeout(60000); const regtest = regtestUtils.network; const testSet1 = { address: '17L3qWGDUBGN5V8d9yqXgJqiwwnEugL1UJ', signature: '<KEY> privateKey: '<KEY>', // WIF publicKey: '<KEY>', }; const testSet2 = { address: '1F3sAm6ZtwLAUnj7d38pGFxtP3RVEvtsbV', signature: 'GwigiVdN7WRlrzksnCz8oC+GzgETW8YCxCZ+xcIerGZIL7MClCgHMqc07bkd736ynPCTuWyPPlSXLY+z5JNUDgc=', privateKey: '<KEY>', // WIF publicKey: '04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235', }; // testnet address information const testSet3 = { address: 'mzUQaN6vnYDYNNYJVpRz2ipxLcWsQg6b8z', signature: 'IJDLVVK3kEMZwC7pvHlSkT2TBFo0LSmvcJwqAbjW+OPtdq5umACvI2RkbZUjBO7CKMrJMNLqPFVNYGqVGwOxRds=', privateKey: '<KEY>', publicKey: '<KEY>', }; describe('BTC signature and key validation tests', () => { it('verifies the signature from address', () => { //verify the first set of signature expect( new Message('aas').verify( '1En7wYxwUiuFfma1Pu3N6d5gopRPvWoj4q', 'IAqCpjxYFTl/OtYzLYb8VVYgyspmiEj43GQoG8R10hLKVOWF6YNXdBlx2U08HEG+oyyu3eZGoYoAfFcRFcQ+dBM=', ), ).toBeTruthy(); // verify the second set of signature expect( new Message('Hello World').verify( '16R2kAxaUNM4xj6ykKbxEugpJdYyJzTP13', 'H0b22gIQIfutUzm7Z9qchdfhUtaO52alhNPK3emrkGOfbOzGHVPuWD9rMIphxniwBNgF/YN4c5C/dMwXz3yJz5k=', ), ).toBeTruthy(); expect(new Message(btcLockdrop.MESSAGE).verify(testSet1.address, testSet2.signature)).toBeFalsy(); expect( new Message(btcLockdrop.MESSAGE).verify('16R2kAxaUNM4xj6ykKbxEugpJdYyJzTP13', testSet3.signature), ).toBeFalsy(); }); it('verifies public key recovery from message with nonce and recover pub key', () => { const _net = bitcoin.networks.bitcoin; // mainnet version number is 128(0x08) while testnet is 239 (0xEF) // details from here https://en.bitcoin.it/wiki/List_of_address_prefixes const priv = bitcoin.ECPair.fromPrivateKey(wif.decode(testSet1.privateKey, 128).privateKey); const addr = bitcoin.payments.p2pkh({ pubkey: priv.publicKey, network: _net, }).address!; const nonces = []; for (let i = 0; i <= 20; i++) { nonces.push(i); } const recoveredData = nonces.map(nonce => { // using bitcoinjs message const msg = 'sign this with nonce: ' + polkadotCrypto.randomAsHex(nonce); const sig = bitcoinjsMessage.sign(msg, priv.privateKey!, true); const recoveredPub = bitcoinjsMessage.recover(msg, addr, sig); // using btc Lockdrop method const msg2 = 'sign this with nonce: ' + polkadotCrypto.randomAsHex(nonce); const sig2 = bitcoinjsMessage.sign(msg2, priv.privateKey!, true); const recoveredPub2 = btcLockdrop.getPublicKey(addr, sig2, msg2); return { recoveredPub, recoveredPub2 }; }); recoveredData.forEach(dat => { expect(dat.recoveredPub).toEqual(priv.publicKey.toString('hex')); expect(dat.recoveredPub2).toEqual(dat.recoveredPub); }); }); it('sign message with private key', () => { const signature = new Message(btcLockdrop.MESSAGE).sign(new PrivateKey(testSet1.privateKey)); expect(new Message(btcLockdrop.MESSAGE).verify(testSet1.address, signature)).toEqual(true); }); it('validates the given Bitcoin address', () => { expect(btcLockdrop.getNetworkFromAddress(testSet1.address)).toEqual(bitcoin.networks.bitcoin); expect(btcLockdrop.getNetworkFromAddress(testSet3.address)).toEqual(bitcoin.networks.testnet); expect(btcLockdrop.validateBtcAddress(testSet2.address)).toBeTruthy(); // invalid address expect(btcLockdrop.validateBtcAddress('26R2kAxaUNb4xj6ykKbxEuGpJaYyJzTP13')).toBeFalsy(); }); it('compresses public key', () => { expect(btcLockdrop.compressPubKey(testSet1.publicKey, bitcoin.networks.bitcoin)).toEqual( '<KEY>', ); expect(btcLockdrop.compressPubKey(testSet3.publicKey, bitcoin.networks.testnet)).toEqual( '<KEY>', ); expect( btcLockdrop.decompressPubKey( '<KEY>', bitcoin.networks.bitcoin, ), ).toEqual(testSet1.publicKey); expect( btcLockdrop.decompressPubKey( '<KEY>', bitcoin.networks.testnet, ), ).toEqual(testSet3.publicKey); const compressedKey = btcLockdrop.compressPubKey(testSet3.publicKey, bitcoin.networks.testnet); // checks if double compression will return the first compressed value expect(btcLockdrop.compressPubKey(compressedKey, bitcoin.networks.testnet)).toEqual(compressedKey); }); }); describe('Bitcoin lockdrop helper tests', () => { it('converts bitcoin to satoshi and back', () => { expect(btcLockdrop.satoshiToBitcoin('65462605489').toFixed()).toEqual('654.62605489'); expect(btcLockdrop.bitcoinToSatoshi(156).toFixed()).toEqual('15600000000'); expect(btcLockdrop.bitcoinToSatoshi(btcLockdrop.satoshiToBitcoin('95')).toNumber()).toEqual(95); expect(btcLockdrop.satoshiToBitcoin(btcLockdrop.bitcoinToSatoshi(10)).toNumber()).toEqual(10); }); }); describe('Bitcoin API fetch tests', () => { it('fetches transaction data from BlockStream', async () => { const allTxFromAddr = await btcLockdrop.getBtcTxsFromAddress('13XXaBufpMvqRqLkyDty1AXqueZHVe6iyy', 'mainnet'); const allTxFromAddrTest = await btcLockdrop.getBtcTxsFromAddress( '2Mubm96PDzLyzcXJvfqX8kdyn2WHa7ssJ67', 'testnet', ); expect(allTxFromAddr.length).toEqual(2); expect(allTxFromAddr[0].txid).toEqual('f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449'); expect(allTxFromAddrTest.length).toEqual(2); expect(allTxFromAddrTest[0].txid).toEqual('f02a3881823238cd4290a8e18bf45db5dd7d9f23a6a8e3d64e307f68085e0929'); const txInfo = await btcLockdrop.getBtcTxFromTxId( 'f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449', 'mainnet', ); const txInfoTestnet = await btcLockdrop.getBtcTxFromTxId( '2336a60b02f69a892b797b21aedafa128779338e9f69650fc87373a4f8036611', 'testnet', ); expect(txInfo.status.block_height).toEqual(293000); expect(txInfo.vout[0].value).toEqual(70320221545); expect(txInfoTestnet.status.block_height).toEqual(1770515); expect(txInfoTestnet.vout[0].value).toEqual(284780111); }); it('fetches a transaction hahs from SoChain', async () => { const txId = '01cec976192e2f39ff57fdba5cba5d03094a7cf696f3f5ab89379e389ef77412'; const txHex = '0100000000010219c88926f3113a8d5fb1801cd55429bd6269d229c7cbf50ac530233857fa9c3d0000000000ffffffff7fce5cf913125ce5bbb93829d819d56e461e39dcadb02ccc33298710fc6f15b40100000000ffffffff02d29e09000000000017a914d550b302301e25bf8f2c5115a31f8511bdbfdd948722c2050000000000160014aeda84ee9434c2259966b95298323b989ec4809502483045022100f6dbf811dc959f6f626da873ce54193efa5b28d81b14c6c0cf7c9237728993fb02206ff5d41e10b000867d345ec183e1<KEY>00000'; const res = await btcLockdrop.getTransactionHex(txId, 'BTCTEST'); expect(res).toEqual(txHex); }); }); describe('BTC lock script tests', () => { // force update MTP beforeEach(async () => { await regtestUtils.mine(11); }); it( 'signs a BTC transaction', () => { const privkey = '<KEY>'; const txhex = '0100000001f7e6430096cd2790bac115aaab22c0a50fb0a1794305302e1a399e81d8d354f4020000006a47304402205793a862d193264afc32713e2e14541e1ff9ebb647dd7e7e6a0051d0faa87de302205216653741ecbbed573ea2fc053209dd6980616701c27be5b958a159fc97f45a012103e877e7deb32d19250dcfe534ea82c99ad739800295cd5429a7f69e2896c36fcdfeffffff0340420f00000000001976a9145c7b8d623fba952d2387703d051d8e931a6aa0a188ac8bda2702000000001976a9145a0ef60784137d03e7868d063b05424f2f43799f88ac40420f00000000001976a9145c7b8d623fba952d2387703d051d8e931a6aa0a188ac2fcc0e00'; const privkeypair = bitcoin.ECPair.fromWIF(privkey, bitcoin.networks.testnet); const transaction = bitcoin.Transaction.fromHex(txhex); const builder = new bitcoin.TransactionBuilder(bitcoin.networks.testnet); builder.addInput(transaction, 0, 0); builder.addOutput('n4pSwWQZm8Wter1wD6n8RDhEwgCqtQgpcY', 6000); builder.sign(0, privkeypair); }, 200 * 1000, ); it('validates block sequence inputs', () => { expect(btcLockdrop.daysToBlockSequence(4)).toEqual(576); expect(() => btcLockdrop.daysToBlockSequence(3.4)).toThrowError( 'Lock days must be a valid integer, but received: 3.4', ); expect(() => btcLockdrop.btcLockScript(testSet2.publicKey, 655356, bitcoin.networks.bitcoin)).toThrowError( 'Block sequence cannot be more than 65535', ); }); it('validates generating lock script', () => { expect(() => btcLockdrop.btcLockScript( testSet2.privateKey, btcLockdrop.daysToBlockSequence(3), bitcoin.networks.bitcoin, ), ).toThrowError('Invalid public key'); expect(() => btcLockdrop.getLockP2SH(-1, testSet3.publicKey, bitcoin.networks.testnet)).toThrowError( 'Block sequence cannot be a negative number', ); expect(() => btcLockdrop.getLockP2SH(301, testSet1.publicKey, bitcoin.networks.bitcoin)).toThrowError( 'Lock duration must be between 30 days to 300 days', ); expect(() => { btcLockdrop.getLockP2SH( 30, 'cScfkGjbzzoeewVWmU2hYPUHeVGJRDdFt7WhmrVVGkxpmPP8BHWe', bitcoin.networks.testnet, ); }).toThrowError('Invalid public key'); expect(() => { btcLockdrop.btcLockScript( testSet3.publicKey, btcLockdrop.daysToBlockSequence(-10), bitcoin.networks.testnet, ); }).toThrowError('Block sequence cannot be a negative number'); }); it('generates BTC lockdrop parameter', async () => { // lock script locking for 3 days on testnet const scriptAddr = '2N1MH1ikVDSh3wyqvGHaG9pKfFHC6mUiDiZ'; // known lock TX hash (https://api.blockcypher.com/v1/btc/test3/txs/384f54793b753e4acd9a9aca1da3ef7609931800d0a86de8c4ae6dc8ab7a96fd) const lockTXHash = '0x384f54793b753e4acd9a9aca1da3ef7609931800d0a86de8c4ae6dc8ab7a96fd'; const locks = await btcLockdrop.getLockParameter( scriptAddr, 3, btcLockdrop.compressPubKey(testSet3.publicKey, bitcoin.networks.testnet), 'testnet', ); const lockParams = locks.map(i => { return plasmUtils.structToLockdrop(i as any); }); expect(lockParams[lockParams.length - 1].transactionHash.toHex()).toEqual(lockTXHash); }); it( 'lock BTC on script and redeem', async () => { const DURATION = 10; // Lock duration in blocks const VALUE = 2000000; // Lock value in Satoshi const FEE = 200; // Relay fee const alice = bitcoin.ECPair.fromWIF('cScfkGjbzzoeew<KEY>', regtest); const pubkey = alice.publicKey.toString('hex'); // create a P2SH from the given data const p2sh = bitcoin.payments.p2sh({ network: regtest, redeem: { output: btcLockdrop.btcLockScript(pubkey, bip68.encode({ blocks: DURATION }), regtest), }, }); // fund the P2SH(CSV) address (this will lock the token with VALUE + FEE) const unspent = await regtestUtils.faucet(p2sh.address!, VALUE + FEE); const lockTx = (await regtestUtils.fetch(unspent.txId)).txHex; // create the redeem UTXO const tx = await btcLockdrop.btcUnlockTx( alice, regtest, bitcoin.Transaction.fromHex(lockTx), p2sh.redeem!.output!, bip68.encode({ blocks: DURATION }), regtestUtils.RANDOM_ADDRESS, FEE, ); // Try to redeem at lock time await regtestUtils.broadcast(tx.toHex()).catch(err => { assert.throws(() => { if (err) throw err; }, /Error: non-BIP68-final \(code 64\)/); }); // Try to redeem for few blocks before unlocking await regtestUtils.mine(DURATION - 5); await regtestUtils.broadcast(tx.toHex()).catch(err => { assert.throws(() => { if (err) throw err; }, /Error: non-BIP68-final \(code 64\)/); }); // mine the number of blocks needed for unlocking await regtestUtils.mine(10); // Try to redeem at unlocking time await regtestUtils.broadcast(tx.toHex()); // this method should work without throwing an error await regtestUtils.verify({ txId: tx.getId(), address: regtestUtils.RANDOM_ADDRESS, vout: 0, value: VALUE, }); }, 200 * 1000, ); // extend jest async resolve timeout it( 'tries to lock with Alice and redeem it with Bob', async () => { const DURATION = 5; // Lock duration in days const VALUE = 2000000; // Lock value in Satoshi const FEE = 200; // Relay fee const alice = bitcoin.ECPair.fromWIF('cScfkGjbzzoeewVWmU2hYPUHeVGJRDdFt7WhmrVVGkxpmPP8BHWe', regtest); const bob = bitcoin.ECPair.makeRandom({ network: regtest }); const pubkey = alice.publicKey.toString('hex'); // create a P2SH from the given data const p2sh = bitcoin.payments.p2sh({ network: regtest, redeem: { output: btcLockdrop.btcLockScript(pubkey, bip68.encode({ blocks: DURATION }), regtest), }, }); // fund the P2SH(CSV) address (this will lock the token with VALUE + FEE) const unspent = await regtestUtils.faucet(p2sh.address!, VALUE + FEE); const lockTx = (await regtestUtils.fetch(unspent.txId)).txHex; // create the redeem UTXO const tx = await btcLockdrop.btcUnlockTx( bob, regtest, bitcoin.Transaction.fromHex(lockTx), p2sh.redeem!.output!, bip68.encode({ blocks: DURATION }), regtestUtils.RANDOM_ADDRESS, FEE, ); // mine the number of blocks needed for unlocking await regtestUtils.mine(DURATION * 2); // Try to redeem at unlocking time // note: sometimes this throws "mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation) (code 16)" // or "mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element) (code 16)" // so instead of checking the exact error message, we just check if it throws or not await expect(regtestUtils.broadcast(tx.toHex())).rejects.toThrowError(); }, 200 * 1000, // extend jest async resolve timeout ); }); <file_sep>/src/types/PlasmDrop.ts import BigNumber from 'bignumber.js'; import { LockEvent } from './LockdropModels'; export class PlmDrop { receiver: string; basePlm: BigNumber; introducerAndBonuses: [string, BigNumber][]; affiliationRefsBonuses: [string, BigNumber][]; locks: LockEvent[]; constructor( receiver: string, basePlm: BigNumber, introducerAndBonuses: [string, BigNumber][], affiliationRefsBonuses: [string, BigNumber][], locks: LockEvent[], ) { this.receiver = receiver; this.basePlm = basePlm; this.introducerAndBonuses = introducerAndBonuses; this.affiliationRefsBonuses = affiliationRefsBonuses; this.locks = locks; } getTotal() { let totalIntroBonuses = new BigNumber(0); for (let i = 0; i < this.introducerAndBonuses.length; i++) { totalIntroBonuses = totalIntroBonuses.plus(this.introducerAndBonuses[i][1]); } const affBonus = this.calculateAffBonus(); return this.basePlm .plus(totalIntroBonuses) .plus(affBonus) .toFixed(); } getTotalPlm() { return new BigNumber(this.getTotal()).toFixed(); } getAffBonus() { return new BigNumber(this.calculateAffBonus()).toFormat(2); } getIntroBonus() { return new BigNumber(this.calculateIntroBonus()).toFormat(2); } // calculate the number of PLM you get for being affiliated calculateAffBonus() { return this.affiliationRefsBonuses.reduce( (sum: BigNumber, bonus: [string, BigNumber]): BigNumber => sum.plus(bonus[1]), new BigNumber(0), ); } // the number of PLM you get for referencing an affiliate calculateIntroBonus() { return this.introducerAndBonuses.reduce( (sum: BigNumber, bonus: [string, BigNumber]): BigNumber => sum.plus(bonus[1]), new BigNumber(0), ); } } <file_sep>/src/types/LockdropModels.ts import BN from 'bn.js'; import { Moment } from 'moment'; import { u64, u128, U8aFixed, BTreeSet } from '@polkadot/types'; import { H256, AuthorityId } from '@polkadot/types/interfaces'; /** * lock contract parameter */ export interface LockInput { duration: number; // in days amount: BN; // in ETH affiliation: string; // Ethereum address rate: number; } /** * defines the method for creating a BTC transaction */ export enum BtcWalletType { Trezor, Ledger, Raw, None, } export interface UnspentTx { value: number; txId: string; vout: number; address?: string; height?: number; } export interface LockMenu { uri?: string; icon?: string; title: string; startDate: Moment; endDate: Moment; disabled?: boolean; } export interface TimeFormat { days: number; hours: number; minutes: number; seconds: number; } export enum LockSeason { First, Second, Dusty, Third, } /** * The lockdrop lock token type. This is used for the real-time lockdrop module */ export enum LockdropType { Bitcoin, Ethereum, } export interface LockEvent { eth: BN; // this uses BN.js instead of BigNumber.js because that is what eth helper uses duration: number; // in Unix epoch seconds lock: string; // lock address introducer: string; blockNo: number; timestamp: string; // in Unix epoch seconds lockOwner: string; // locker's address transactionHash: string; } // option data is the type that is going to be passed to the component export interface OptionData { dataSets: OptionItem[]; onChoose: Function; } // option item type is used to provide the data for dropdown items export interface OptionItem { label: string; // the dropdown display label value: number; // dropdown select return value rate: number; } /** * used for real-time lockdrop parameter * this data is used to communicate with Substrate */ export interface Lockdrop { type: LockdropType; transactionHash: H256; //H256 publicKey: U8aFixed; // [u8; 33] duration: u64; // u64 value: u128; // u128 } export interface Claim { params: Lockdrop; approve: BTreeSet<AuthorityId>; decline: BTreeSet<AuthorityId>; amount: u128; // u128 complete: boolean; } export interface HwSigner { publicKey: Buffer; // eslint-disable-next-line @typescript-eslint/no-explicit-any network?: any; sign(hash: Buffer, lowR?: boolean): Buffer | Promise<Buffer>; getPublicKey?(): Buffer; } <file_sep>/src/types/BlockStreamTypes.ts /* eslint-disable @typescript-eslint/no-namespace */ // types generated from http://json2ts.com/ export declare namespace BlockStreamApi { export interface Prevout { scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; } export interface Vin { txid: string; vout: number; prevout: Prevout; scriptsig?: string; scriptsig_asm?: string; is_coinbase: boolean; sequence: number; } export interface Vout { scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; } export interface Status { confirmed: boolean; block_height: number; block_hash: string; block_time: number; } export interface Transaction { txid: string; version: number; locktime: number; vin: Vin[]; vout: Vout[]; size: number; weight: number; fee: number; status: Status; } }
498843aab53a672e4a6770d778cd3c6327e64c98
[ "TypeScript" ]
16
TypeScript
staketechnologies/ethereum-lockdrop
2d1c159525ec1906972e66e693a279d8c9f7758d
22696dd54f9475a04d4b7fbabba56dc649c0f2aa
refs/heads/master
<file_sep>import { SharedPO } from '../../page-objects/Shared/shared.po'; import { browser, ExpectedConditions } from 'protractor'; const sharedPO = new SharedPO(); export class SharedLogic { public async checkSharedToastMassageAppearence(): Promise<void> { await browser.wait(ExpectedConditions.presenceOf(sharedPO.getToastMassageShared()), browser.params.waitTime * 3); } public async checkSharedToastMassageDisappearence(): Promise<void> { await browser.wait(ExpectedConditions.stalenessOf(sharedPO.getToastMassageShared()), browser.params.waitTime * 2); } public async checkSharedToastMessage(): Promise<void> { await this.checkSharedToastMassageAppearence(); await this.checkSharedToastMassageDisappearence(); } public async inteactWithSharedDeletedialog(): Promise<void> { await browser.wait(ExpectedConditions.invisibilityOf(await sharedPO.getOverlayPanelShared())); await browser.wait(ExpectedConditions.visibilityOf(await sharedPO.getDialogContainerShared())); await browser.wait(ExpectedConditions.visibilityOf(await sharedPO.getDialogContainerMessageShared())); expect(await sharedPO.getDialogContainerMessageShared().getText()).toBe('Are you sure you want to delete this category?'); await browser.wait(ExpectedConditions.visibilityOf(await sharedPO.getDialogContainerCancelButtonShared())); expect(await sharedPO.getDialogContainerCancelButtonShared().getText()).toBe('Cancel'); await browser.wait(ExpectedConditions.visibilityOf(await sharedPO.getDialogContainerDeleteButtonShared())); await browser.wait(ExpectedConditions.textToBePresentInElement(await sharedPO.getDialogContainerDeleteButtonShared(), 'Delete')); expect(await sharedPO.getDialogContainerDeleteButtonShared().getText()).toBe('Delete'); await browser.wait(ExpectedConditions.elementToBeClickable(await sharedPO.getDialogContainerDeleteButtonShared())); await sharedPO.getDialogContainerDeleteButtonShared().click(); } }<file_sep>import { SettingsPO } from '../../page-objects/Settings/settings.po'; import { browser, ExpectedConditions } from 'protractor'; import { SharedPO } from '../../page-objects/Shared/shared.PO'; const settingsPO = new SettingsPO(); const sharedPO = new SharedPO(); export class SettingsLogic { public async checkSettingsHeader(): Promise<void> { await browser.driver.wait(ExpectedConditions.presenceOf(sharedPO.getDrawerContainerShared()), browser.params.waitTime) expect(await settingsPO.getHeaderSettings().getText()).toBe("Settings"); } public async closeSettingsTextCheck(): Promise<void> { await browser.driver.wait(ExpectedConditions.visibilityOf(settingsPO.getCloseSettings()), browser.params.waitTime); await browser.driver.wait(ExpectedConditions.textToBePresentInElement(settingsPO.getCloseSettings(), "Close Settings"), browser.params.waitTime); expect(await settingsPO.getCloseSettings().getText()).toBe("Close Settings"); } public async checkSettingsTiles(): Promise<void> { await browser.driver.wait(ExpectedConditions.visibilityOf(settingsPO.getCategoryTileSettings()), browser.params.waitTime) await browser.driver.wait(ExpectedConditions.elementToBeClickable(settingsPO.getCategoryTileSettings()), browser.params.waitTime) expect(await settingsPO.getCategoryTileSettings().getText()).toBe("Equipment Categories"); await browser.driver.wait(ExpectedConditions.visibilityOf(settingsPO.getStatusTileSettings()), browser.params.waitTime) await browser.driver.wait(ExpectedConditions.elementToBeClickable(settingsPO.getStatusTileSettings()), browser.params.waitTime) expect(await settingsPO.getStatusTileSettings().getText()).toBe("Statuses"); } public async checkSettingsForm(): Promise<void> { await this.closeSettingsTextCheck() await this.checkSettingsHeader(); await this.checkSettingsTiles(); } public async clickSettingsCategoryTile(): Promise<void> { await this.checkSettingsForm(); await browser.driver.wait(ExpectedConditions.elementToBeClickable(settingsPO.getCategoryTileSettings()), 10000) await settingsPO.getCategoryTileSettings().click(); } public async closeSettingsDrawer(): Promise<void> { await this.checkSettingsForm(); await browser.driver.wait(ExpectedConditions.stalenessOf(settingsPO.getNextDrawerSettings(2)), browser.params.waitTime); await browser.driver.wait(ExpectedConditions.elementToBeClickable(settingsPO.getCloseSettings()), browser.params.waitTime * 3); await settingsPO.getCloseSettings().click(); await browser.driver.wait(ExpectedConditions.stalenessOf(settingsPO.getNextDrawerSettings(1)), browser.params.waitTime); } }<file_sep>import { CategoryListPO } from '../../../page-objects/Settings/Category/categoryList.po'; import { browser, ExpectedConditions } from 'protractor'; import { SharedLogic } from '../../Shared/shared.service'; import { SettingsPO } from '../../../page-objects/Settings/settings.po'; const categoryListPO = new CategoryListPO(); const shared = new SharedLogic(); const settingsPO = new SettingsPO(); export class CategoryListLogic { public async checkCategoryListHeader(): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(categoryListPO.getDrawerContainerHeaderOnCatList())); expect(await categoryListPO.getDrawerContainerHeaderOnCatList().getText()).toBe("Equipment Categories"); } public async checkCategoryListHeaderTotalCount(): Promise<number> { let categoryTotalCountText = await categoryListPO.getDrawerContainerHeaderTotalCountOnCatList().getText(); let categoryTotalCountArray = categoryTotalCountText.split(" "); let categoryTotalCount = +categoryTotalCountArray[0]; return categoryTotalCount; } public async clickCategoryListBackToSettings(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getBackToSettingsOnCatList())); await categoryListPO.getBackToSettingsOnCatList().click(); } public async clickCategoryListCreateButton(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getCreateButtonOnCatList()), browser.params.waitTime); await categoryListPO.getCreateButtonOnCatList().click(); } public async searchCategoryListwithName(eqCatName: string, eqCategoryCount: number): Promise<void> { await this.checkCategoryListHeader(); let countAfterCategoryCreation = this.checkCategoryListHeaderTotalCount(); expect(countAfterCategoryCreation).toBe(eqCategoryCount + 1) await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getSearchBarOnCatList())); let searchText = eqCatName.substring(0, 1); await categoryListPO.getSearchBarOnCatList().sendKeys(searchText); await browser.wait(ExpectedConditions.presenceOf(categoryListPO.getSearchIconClearOnCatList())); await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getSearchIconClearOnCatList())); searchText = eqCatName.substring(1, eqCatName.length); await categoryListPO.getSearchBarOnCatList().sendKeys(searchText); await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getSearchIconOnCatList())); await categoryListPO.getSearchIconOnCatList().click(); await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getSearchResultNameCheckOnCatList()), browser.params.waitTime); expect(await categoryListPO.getSearchResultNameCheckOnCatList().getText()).toContain(eqCatName); } public async checkCategoryListHeaderInfo(): Promise<number> { await this.checkCategoryListHeader(); let countCategory = await this.checkCategoryListHeaderTotalCount(); return countCategory; } public async deleteCategoryList(): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(categoryListPO.getActionDropDownDeleteOnCatList())); await browser.wait(ExpectedConditions.textToBePresentInElement(categoryListPO.getActionDropDownDeleteOnCatList(), "Delete")); await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getActionDropDownDeleteOnCatList())); await categoryListPO.getActionDropDownDeleteOnCatList().click(); await shared.inteactWithSharedDeletedialog(); await this.clickCategoryListBackToSettings(); await browser.driver.wait(ExpectedConditions.stalenessOf(settingsPO.getNextDrawerSettings(2)), browser.params.waitTime); } public async clickCategoryListOnActtion1stRecord(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryListPO.getSearchResult1stRecordActionOnCatList())); await categoryListPO.getSearchResult1stRecordActionOnCatList().click(); await this.deleteCategoryList(); } }<file_sep>import { EquipmentListPO } from '../../page-objects/Equipment/equipmentList.po'; import { browser, ExpectedConditions } from 'protractor'; const equipmentListPO = new EquipmentListPO(); export class EquipmentListLogic { public async getListViewHeader(): Promise<string> { return await equipmentListPO.getHeadingOnListView().getText(); } public async getListViewHeaderTotalEquipmentRecord(): Promise<number> { let equipmentTotalCountText = await equipmentListPO.getHeadingTotalCountOnListView().getText(); let equipmentTotalCountArray = equipmentTotalCountText.split(" "); let equipmentHeaderTotalCount = +equipmentTotalCountArray[0]; return equipmentHeaderTotalCount; } public async getListViewFooter(): Promise<void> { expect(await equipmentListPO.getCopyRightFooterOnListView().getText()).toBe('Copyright Fiix © 2020. All Rights Reserved'); expect(await equipmentListPO.getPrivacyPolicyFooterOnListView().isDisplayed()).toBe(true); } public async checkListViewColumnHeaders(): Promise<void> { let columnHeaders: any = await equipmentListPO.getColumnHeadersOnListView() for (let columnNumber = 1; columnNumber < columnHeaders.length; columnNumber++) { if (columnNumber == 1) { expect(await columnHeaders[1].getText()).toBe('NAME'); } else if (columnNumber == 2) { expect(await columnHeaders[2].getText()).toBe('CODE'); } else if (columnNumber == 3) { expect(await columnHeaders[3].getText()).toBe('CATEGORY'); } else if (columnNumber == 4) { expect(await columnHeaders[4].getText()).toBe('STATUS'); } else if (columnNumber == 5) { expect(await columnHeaders[5].getText()).toBe('REASON'); } else if (columnNumber == 6) { expect(await columnHeaders[6].getText()).toBe('MAKE'); } else if (columnNumber == 7) { expect(await columnHeaders[7].getText()).toBe('SERIAL NUMBER'); } else if (columnNumber == 8) { expect(await columnHeaders[8].getText()).toBe('BARCODE'); } else if (columnNumber == 9) { expect(await columnHeaders[9].getText()).toBe('DATE CREATED'); } else if (columnNumber == 10) { expect(await columnHeaders[10].getText()).toBe('ACTIONS'); } } } public async checkListViewButtonNames(): Promise<void> { expect(await equipmentListPO.getCreateButtonOnListView().getText()).toBe('Create'); expect(await equipmentListPO.getSettingButtonOnListView().getText()).toBe('Settings'); } public async checkListViewSearchBarPresence(): Promise<void> { await browser.wait(ExpectedConditions.presenceOf(equipmentListPO.getSearchbarInputOnListView())); expect(await equipmentListPO.getSearchbarInputOnListView().isPresent()).toBe(true); } public async searchListViewForCreatedEq(eqName: string): Promise<void> { await browser.wait(ExpectedConditions.presenceOf(equipmentListPO.getSearchbarInputOnListView())); await equipmentListPO.getSearchbarInputOnListView().sendKeys(eqName); await browser.wait(ExpectedConditions.elementToBeClickable(equipmentListPO.getSearchIconOnListView())); await equipmentListPO.getSearchIconOnListView().click(); expect(await equipmentListPO.getSearchResultNameCheckOnListView().getText()).toBe(eqName); await browser.wait(ExpectedConditions.elementToBeClickable(equipmentListPO.getSearchIconClearOnListView())); await equipmentListPO.getSearchIconClearOnListView().click(); } public async checkTotalRecordCount(): Promise<void> { await browser.wait(ExpectedConditions.presenceOf(equipmentListPO.getTotalRecordHeadingOnListView())); var totalInHeading = await equipmentListPO.getTotalRecordHeadingOnListView().getText(); var totalInHeadingNumber = totalInHeading.split(" ") await browser.wait(ExpectedConditions.presenceOf(equipmentListPO.getTotalRecordPaginationOnListView())); var totalInPaginaion = await equipmentListPO.getTotalRecordPaginationOnListView().getText(); var totalInPaginationNumber = totalInPaginaion.split(" ") expect(totalInHeadingNumber[0]).toEqual(totalInPaginationNumber[totalInPaginationNumber.length - 1]); } public async openSettings(): Promise<void> { await equipmentListPO.getSettingButtonOnListView().click(); } public async get_ListView_recordsNumberShown(): Promise<string> { let equipmentRangeFullText = await equipmentListPO.getPageRangeOnListView().getText(); let equipmentRangeText = equipmentRangeFullText.split("/"); let equipmentRangeTextRecordNumbers = equipmentRangeText[0]; return equipmentRangeTextRecordNumbers; } public async get_ListView_FooterTotalEquipmentRecord(): Promise<number> { let equipmentTotalCountText = await equipmentListPO.getPageRangeOnListView().getText(); let equipmentTotalCountArray = equipmentTotalCountText.split("/"); let equipmentFooterTotalCount = +equipmentTotalCountArray[1]; return equipmentFooterTotalCount; } public async totalEqRecordNumber(): Promise<number> { let countOnTop = await this.getListViewHeaderTotalEquipmentRecord(); let countOnBottom = await this.get_ListView_FooterTotalEquipmentRecord(); expect(countOnTop).toBe(countOnBottom); return countOnBottom; } public async compare2Pages_EqRecordNumber(recordRange1stPage: string): Promise<void> { await this.checkListViewColumnHeaders(); let recordRangelastPage: string = await this.get_ListView_recordsNumberShown(); expect(recordRange1stPage).not.toBe(recordRangelastPage); } public async moveToNextPage(): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(equipmentListPO.getNextPageArrowOnListView())); await browser.wait(ExpectedConditions.elementToBeClickable(equipmentListPO.getNextPageArrowOnListView())); await equipmentListPO.getNextPageArrowOnListView().click(); } public async moveToPreviousPage(): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(equipmentListPO.getPreviousPageArrowOnListView())); await browser.wait(ExpectedConditions.elementToBeClickable(equipmentListPO.getPreviousPageArrowOnListView())); await equipmentListPO.getPreviousPageArrowOnListView().click(); } public async checkDefaultPageSize(defaultPageSize: string): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(equipmentListPO.getPageSizeOnListView())); expect(await equipmentListPO.getPageSizeOnListView().getText()).toBe(defaultPageSize); } public async findLastPageRecordCount(totalEquipmentCount: number, defaultPageSizeNumber: number): Promise<number> { let numberOfRecordOnLastPage = totalEquipmentCount % defaultPageSizeNumber; let lastPageNumber: number; if (numberOfRecordOnLastPage > 0) { lastPageNumber = Math.floor(totalEquipmentCount / defaultPageSizeNumber) + 1; } else { lastPageNumber = Math.floor(totalEquipmentCount / defaultPageSizeNumber); } return lastPageNumber; } public async jumpToDifferentPage(pageNumber: number): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(equipmentListPO.getPageJumpToLabelOnListView())); expect(await equipmentListPO.getPageJumpToLabelOnListView().getText()).toBe("Jump to page"); await browser.wait(ExpectedConditions.visibilityOf(equipmentListPO.getPageJumpToLabelOnListView())); await browser.wait(ExpectedConditions.elementToBeClickable(equipmentListPO.getPageJumpToInputOnListView())); await equipmentListPO.getPageJumpToInputOnListView().sendKeys(pageNumber); } public async paginationCheck(defaultPageSize: string): Promise<void> { // check Default page size await this.checkDefaultPageSize(defaultPageSize); // finding last page number let totalEquipmentCount = await this.totalEqRecordNumber(); let defaultPageSizeNumber = +defaultPageSize; // move pages only if there is more than 1 if (totalEquipmentCount > defaultPageSizeNumber) { let numberOfRecordOnLastPage = totalEquipmentCount % defaultPageSizeNumber; let lastPageNumber = await this.findLastPageRecordCount(totalEquipmentCount, defaultPageSizeNumber) let recordRange1stPage: string = await this.get_ListView_recordsNumberShown(); // jump to last page await this.jumpToDifferentPage(lastPageNumber); // compare page range between 1st and last page to ensure the move await this.compare2Pages_EqRecordNumber(recordRange1stPage); let rows: any = await equipmentListPO.getRowsOnListView(); // compare last page record number if (numberOfRecordOnLastPage > 0) { expect(numberOfRecordOnLastPage).toEqual(rows.length); } let recordRangeLastPage: string = await this.get_ListView_recordsNumberShown(); // move to 2nd last page await this.moveToPreviousPage(); // compare page range between last and 2nd last page to ensure the move await this.compare2Pages_EqRecordNumber(recordRangeLastPage); let recordRange2ndLastPage: string = await this.get_ListView_recordsNumberShown(); // move 1 page forward await this.moveToNextPage(); // compare page range between last and 2nd last page to ensure the move await this.compare2Pages_EqRecordNumber(recordRange2ndLastPage); } } }<file_sep>import { by, element, ElementFinder, $, $$, ElementArrayFinder } from 'protractor'; export class EquipmentListPO { private _heading_EqListView: ElementFinder = $('fiix-heading > h1.ng-star-inserted'); private _headingoTotalCount_EqListView: ElementFinder = $('fiix-heading > span[class~=heading-total]'); private _columnHeaders_EqListView: ElementArrayFinder = $$('th[role="columnheader"] > div'); private _createButton_EqListView: ElementFinder = element(by.buttonText('Create')); private _settingButton_EqListView: ElementFinder = $('button.settings-button.fiix-secondary-button'); private _searchBarInput_EqListView: ElementFinder = element(by.css('fiix-search-bar input')); private _searchIconStartSearch_EqListView: ElementFinder = $('fiix-search-bar fiix-icon[name="search"]'); private _searchIconClear_EqListView: ElementFinder = $('fiix-search-bar fiix-icon[name="cross"]'); private _totaRecord_Heading_EqListView: ElementFinder = $('span.heading-total.ng-star-inserted'); private _totalRecord_Pagination_EqListView: ElementFinder = $('div.mat-paginator-range-label'); private _footer_CopyRight_EqListView: ElementFinder = $('span.fiix-footer-copyright'); private _footer_PrivacyPolicy_EqListView: ElementFinder = $('span.fiix-footer-agreements'); private _pageSize_EqListView: ElementFinder = $('fiix-paginator mat-form-field mat-select div[class~=mat-select-value] span[class~=mat-select-value-text]'); private _pageSizeDropDown_EqListView: ElementFinder = $('fiix-paginator mat-form-field mat-select div[class~=mat-select-arrow]'); private _pageSizeLabel_EqListView: ElementFinder = $('fiix-paginator div.mat-paginator-container div.mat-paginator-page-size-label'); // private _pageSizeDropDownOptions_EqListView: ElementArrayFinder = $$('div.cdk-overlay-container span.mat-option-text'); private _pageSizeDropDownOptions_EqListView: ElementArrayFinder = $$('div.cdk-overlay-container mat-option'); private _pageRange_EqListView: ElementFinder = $('fiix-paginator div.mat-paginator-range-actions div.mat-paginator-range-label'); private _pagePreviousPageArrow_EqListView: ElementFinder = $('fiix-paginator div.mat-paginator-range-actions button[class~=mat-paginator-navigation-previous]'); private _pageNextPageArrow_EqListView: ElementFinder = $('fiix-paginator div.mat-paginator-range-actions button[class~=mat-paginator-navigation-next]'); private _pageJumptoInput_EqListView: ElementFinder = $('fiix-paginator div#pageInput input[class~=pageNumberField]'); private _pageJumptoLabel_EqListView: ElementFinder = $('fiix-paginator div#pageInput label'); private _numberOfRow_EqListView: ElementArrayFinder=$$('fiix-table tbody[role=rowgroup] tr'); private getValueFromRowColumn(row:number, column: number): ElementFinder { let _value_fromCell: ElementFinder = $('fiix-table tbody tr:nth-of-type('+row+') > td:nth-of-type('+column+')'); return _value_fromCell; } public getHeadingOnListView(): ElementFinder { return this._heading_EqListView; } public getHeadingTotalCountOnListView(): ElementFinder { return this._headingoTotalCount_EqListView; } public getColumnHeadersOnListView(): ElementArrayFinder { return this._columnHeaders_EqListView; } public getCreateButtonOnListView(): ElementFinder { return this._createButton_EqListView; } public getSettingButtonOnListView(): ElementFinder { return this._settingButton_EqListView; } public getSearchbarInputOnListView(): ElementFinder { return this._searchBarInput_EqListView; } public getSearchIconOnListView(): ElementFinder { return this._searchIconStartSearch_EqListView; } public getSearchIconClearOnListView(): ElementFinder { return this._searchIconClear_EqListView; } public getSearchResultNameCheckOnListView(): ElementFinder { return this.getValueFromRowColumn(1,2); } public getTotalRecordHeadingOnListView(): ElementFinder { return this._totaRecord_Heading_EqListView; } public getTotalRecordPaginationOnListView(): ElementFinder { return this._totalRecord_Pagination_EqListView; } public getCopyRightFooterOnListView(): ElementFinder { return this._footer_CopyRight_EqListView; } public getPrivacyPolicyFooterOnListView(): ElementFinder { return this._footer_PrivacyPolicy_EqListView; } public getPageSizeOnListView(): ElementFinder { return this._pageSize_EqListView; } public getPageSizeDropDownOnListView(): ElementFinder { return this._pageSizeDropDown_EqListView; } public getPageSizeLabelOnListView(): ElementFinder { return this._pageSizeLabel_EqListView; } public getPageSizeDropDownOptions_ListView(): ElementArrayFinder { return this._pageSizeDropDownOptions_EqListView; } public getPageRangeOnListView(): ElementFinder { return this._pageRange_EqListView; } public getNextPageArrowOnListView(): ElementFinder { return this._pageNextPageArrow_EqListView; } public getPreviousPageArrowOnListView(): ElementFinder { return this._pagePreviousPageArrow_EqListView; } public getPageJumpToLabelOnListView(): ElementFinder { return this._pageJumptoLabel_EqListView; } public getPageJumpToInputOnListView(): ElementFinder { return this._pageJumptoInput_EqListView; } public getRowsOnListView(): ElementArrayFinder { return this._numberOfRow_EqListView; } }<file_sep>import { by, element, ElementFinder, $, $$, ElementArrayFinder } from 'protractor'; export class EquipmentPO { private _formLabels_CreatEqForm: ElementArrayFinder = $$('label.equipment-label'); private _equipmentNameInput_CreatEqForm: ElementFinder = $('input#name'); private _saveButton_CreatEqForm: ElementFinder = element(by.buttonText('Save')); private _cancelButton_CreatEqForm: ElementFinder = element(by.buttonText('Cancel')); private _requiredField_CreatEqForm: ElementFinder = $('span.required.required-fields'); private _make_CreatEqForm: ElementFinder = $('input#make'); private _serialNumber_CreatEqForm: ElementFinder = $('input#serial-number'); private _barcode_CreatEqForm: ElementFinder = $('input#barcode'); private _categoryAdd_CreatEqForm: ElementFinder = $('input#category + div > button'); private _Category_1stRecord_CategoryListView: ElementFinder = $('mat-drawer div.drawer-content-body fiix-table table tbody tr:nth-of-type(1) > td:nth-of-type(1) fiix-radio-button'); private _SaveButton_CategoryListView: ElementFinder = element(by.css('mat-drawer eq-category-picker div.button-container button.save-button.fiix-primary-button')); public getEquipmentLabelsOnCreateEqForm(): ElementArrayFinder { return this._formLabels_CreatEqForm; } public getNameInputOnCreatEqForm(): ElementFinder { return this._equipmentNameInput_CreatEqForm; } public getSaveButtonOnCreatEqForm(): ElementFinder { return this._saveButton_CreatEqForm; } public getCancelButtonOnCreatEqForm(): ElementFinder { return this._cancelButton_CreatEqForm; } public getRequiredFieldOnCreatEqForm(): ElementFinder { return this._requiredField_CreatEqForm; } public getMakeOnCreateEqForm(): ElementFinder { return this._make_CreatEqForm; } public getSerialNumberOnCreateEqForm(): ElementFinder { return this._serialNumber_CreatEqForm; } public getBarcodeOnCreateEqForm(): ElementFinder { return this._barcode_CreatEqForm; } public getAddButtonForCategoryOnCreateEqForm(): ElementFinder { return this._categoryAdd_CreatEqForm; } public getFirstRecordOnCategoryDrawer(): ElementFinder { return this._Category_1stRecord_CategoryListView; } public getSaveButtonOnCategoryDrawer(): ElementFinder { return this._SaveButton_CategoryListView; } }<file_sep>import { ElementFinder, $} from 'protractor'; export class CategoryPO { private _name_CreateCategoryFrom: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form input#name'); private _nameLabel_CreateCategoryFrom: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form label[for=name]'); private _drawerContainer_Header_CreateCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form fiix-heading h1'); private _parentNameLabel_CreatCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form label[for=parent]'); private _save_Button__CreatCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form div.button-container button.save-button.fiix-primary-button'); private _cancel_Button__CreatCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form div.button-container button.button.transparent-button.fiix-button'); private _drawerContainer_backToCatList_CreateCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) div.drawer-content-header-clickable') private _drawerContainer_1stBarcode_CreateCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form div.barcodes-wrapper div[class~=barcode-selection]:nth-of-type(1) div.barcode-outline') private _drawerContainer_BarcodeSectionHeader_CreateCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form div.form-controls-container.barcode-details-container > h2') private _drawerContainer_BarcodeSectionDescription_CreateCategoryForm: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(3) eq-equipment-category-form form div.form-controls-container.barcode-details-container > p') public getDrawerContainerHeaderOnCreateCategoryForm() { return this._drawerContainer_Header_CreateCategoryForm; } public getNameLabelOnCreateCategoryForm(): ElementFinder { return this._nameLabel_CreateCategoryFrom; } public getParentLabelOnCreateCategoryForm(): ElementFinder { return this._parentNameLabel_CreatCategoryForm; } public getNameOnCreateCategoryForm(): ElementFinder { return this._name_CreateCategoryFrom; } public getSaveButtonOnCreateCategoryForm(): ElementFinder { return this._save_Button__CreatCategoryForm; } public getCancelButtonOnCreateCategoryForm(): ElementFinder { return this._cancel_Button__CreatCategoryForm; } public getReturnToListOnCreateCategroyForm(): ElementFinder { return this._drawerContainer_backToCatList_CreateCategoryForm; } public get1stBarcodeOnCreateCategoryForm(): ElementFinder { return this._drawerContainer_1stBarcode_CreateCategoryForm; } public getBarcodeHeaderOnCreateCategoryForm(): ElementFinder { return this._drawerContainer_BarcodeSectionHeader_CreateCategoryForm; } public getBarcodeDescriptionOnCreateCategoryForm(): ElementFinder { return this._drawerContainer_BarcodeSectionDescription_CreateCategoryForm; } }<file_sep>// @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); // var shared = require('./shared'); /** * @type { import("protractor").Config } */ exports.config = { allScriptsTimeout: 11000, specs: [ '**/*.e2e-spec.ts' ], chromeDriver: '/usr/local/bin/chromedriver', capabilities: { 'browserName': 'chrome', args: [ '--window-size=2500,1600', '--disable-notifications', '--disable-infobars', // '--headless', ], 'loggingPrefs': { 'driver': 'ALL', 'server': 'ALL', 'browser': 'ALL' } }, directConnect: true, jasmineNodeOpts: { isVerbose: true, showColors: true, defaultTimeoutInterval: 40000, // longer timeout for debugging includeStackTrace: true, stopSpecOnExpectationFailure: true, }, params: { baseURL: 'https://fiixcmms-devserver.com/equipment', waitTime: 10000, defaultPageSize: "5", equipment:{ equipmentName: 'UI Automation Equipment', equipmentMake: 'Audi', equipmentSerialNumber: '1234567890', equipmentBarcode:'AI 01 SSC US' }, category:{ categoryName: 'AutoCategory' } }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } }; <file_sep>import { EquipmentPO } from '../../page-objects/Equipment/equipment.po'; import { browser, ExpectedConditions } from 'protractor'; import { EquipmentListPO } from '../../page-objects/Equipment/equipmentList.po'; import { SharedPO } from '../../page-objects/Shared/shared.po'; const equipmentPO = new EquipmentPO(); const equipmentListPO = new EquipmentListPO(); const sharedPO = new SharedPO(); export class EquipmentLogic { public async checkCreateEqFormLabels(): Promise<void> { let labels: any = await equipmentPO.getEquipmentLabelsOnCreateEqForm(); for (let labelNumber = 0; labelNumber < labels.length; labelNumber++) { if (labelNumber == 0) { expect(await labels[0].getText()).toBe('Name*'); } else if (labelNumber == 1) { expect(await labels[1].getText()).toBe('Code'); } else if (labelNumber == 2) { expect(await labels[2].getText()).toBe('Criticality'); } else if (labelNumber == 3) { expect(await labels[3].getText()).toBe('Description'); } else if (labelNumber == 4) { expect(await labels[4].getText()).toBe('Category'); } else if (labelNumber == 5) { expect(await labels[5].getText()).toBe('Equipment Location'); } else if (labelNumber == 6) { expect(await labels[6].getText()).toBe('Address'); } else if (labelNumber == 7) { expect(await labels[7].getText()).toBe('Longitude'); } else if (labelNumber == 8) { expect(await labels[8].getText()).toBe('Latitude'); } else if (labelNumber == 9) { expect(await labels[9].getText()).toBe('Account'); } else if (labelNumber == 10) { expect(await labels[10].getText()).toBe('Charge Department'); } else if (labelNumber == 11) { expect(await labels[11].getText()).toBe('Make'); } else if (labelNumber == 12) { expect(await labels[12].getText()).toBe('Model'); } else if (labelNumber == 13) { expect(await labels[13].getText()).toBe('Serial Number'); } else if (labelNumber == 14) { expect(await labels[14].getText()).toBe('UNSPC Code'); } else if (labelNumber == 15) { expect(await labels[15].getText()).toBe('Barcode'); } else if (labelNumber == 16) { expect(await labels[16].getText()).toBe('Notes'); } } } public async addCreateEqFormCategory(): Promise<void> { await browser.driver.wait(ExpectedConditions.elementToBeClickable(equipmentPO.getAddButtonForCategoryOnCreateEqForm()), browser.params.waitTime) await equipmentPO.getAddButtonForCategoryOnCreateEqForm().click(); await browser.driver.wait(ExpectedConditions.presenceOf(sharedPO.getDrawerContainerShared()), browser.params.waitTime) expect(await sharedPO.getDrawerContainerHeaderShared().getText()).toBe("Equipment Categories"); await browser.driver.wait(ExpectedConditions.elementToBeClickable(equipmentPO.getFirstRecordOnCategoryDrawer()), browser.params.waitTime) await equipmentPO.getFirstRecordOnCategoryDrawer().click(); await browser.driver.wait(ExpectedConditions.elementToBeClickable(equipmentPO.getSaveButtonOnCategoryDrawer()), browser.params.waitTime) await equipmentPO.getSaveButtonOnCategoryDrawer().click(); } public async clickCreateEqFormCancelButton(): Promise<void> { await browser.driver.wait(ExpectedConditions.elementToBeClickable(equipmentPO.getCancelButtonOnCreatEqForm()), browser.params.waitTime) await equipmentPO.getCancelButtonOnCreatEqForm().click(); } public async setAndSaveCreateEqFormNameEq(eqName: string, eqMake: string, eqSerialNumber: string, eqBarcode: string): Promise<void> { await equipmentPO.getNameInputOnCreatEqForm().sendKeys(eqName); await equipmentPO.getMakeOnCreateEqForm().sendKeys(eqMake); await equipmentPO.getSerialNumberOnCreateEqForm().sendKeys(eqSerialNumber); await equipmentPO.getBarcodeOnCreateEqForm().sendKeys(eqBarcode); await this.addCreateEqFormCategory(); await equipmentPO.getSaveButtonOnCreatEqForm().click(); } public async createAndCancelEq(): Promise<void> { await equipmentListPO.getCreateButtonOnListView().click(); expect(await equipmentPO.getRequiredFieldOnCreatEqForm().getText()).toBe('*Required Fields') await this.checkCreateEqFormLabels(); await this.clickCreateEqFormCancelButton(); } public async createAndSaveEq(eqName: string, eqMake: string, eqSerialNumber: string, eqBarcode: string): Promise<void> { await equipmentListPO.getCreateButtonOnListView().click(); expect((await equipmentPO.getRequiredFieldOnCreatEqForm()).getText()).toBe('*Required Fields') await this.checkCreateEqFormLabels(); await this.setAndSaveCreateEqFormNameEq(eqName, eqMake, eqSerialNumber, eqBarcode); } }<file_sep>import { ElementFinder, $ } from 'protractor'; export class SharedPO { private _drawerContainer: ElementFinder = $('mat-drawer'); private _drawerContainer_Header: ElementFinder = $('mat-drawer[class~=drawer] fiix-heading h1'); private _drawerContainer_close: ElementFinder = $('div.drawer-header-close-text'); private _toastMessageText: ElementFinder = $('span.fiix-msgbar-text'); private _toastMessageText_drawer: ElementFinder = $('snack-bar-container > fiix-message-bar') private _overlayPane: ElementFinder = $('div#cdk-overlay-4'); private _dialogContainer: ElementFinder = $('div.cdk-overlay-pane.fiix-dialog-panel mat-dialog-container'); private _dialogContainer_Message: ElementFinder = $('div.cdk-overlay-pane.fiix-dialog-panel mat-dialog-container fiix-dialog-content p'); private _dialogContainer_CancelButton: ElementFinder = $('div.cdk-overlay-pane.fiix-dialog-panel mat-dialog-container fiix-dialog-actions button#cancel-button'); private _dialogContainer_DeletelButton: ElementFinder = $('div.cdk-overlay-pane.fiix-dialog-panel mat-dialog-container fiix-dialog-actions button#delete-dialog-button'); public getToastMassageShared(): ElementFinder { return this._toastMessageText_drawer; } public getToastMassageTextShared(): ElementFinder { return this._toastMessageText; } public getDrawerContainerShared(): ElementFinder { return this._drawerContainer; } public getDrawerContainerHeaderShared(): ElementFinder { return this._drawerContainer_Header; } public getDrawerContainerClosedShared(): ElementFinder { return this._drawerContainer_close; } public getDialogContainerShared(): ElementFinder { return this._dialogContainer; } public getDialogContainerMessageShared(): ElementFinder { return this._dialogContainer_Message; } public getDialogContainerCancelButtonShared(): ElementFinder { return this._dialogContainer_CancelButton; } public getDialogContainerDeleteButtonShared(): ElementFinder { return this._dialogContainer_DeletelButton; } public getOverlayPanelShared(): ElementFinder { return this._overlayPane; } }<file_sep>import { ElementFinder, $ } from 'protractor'; export class SettingsPO { private _settings_EqCategoryTile: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(1) eq-equipment-settings fiix-settings-tile#categories-tile'); private _settings_EqStatusTile: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(1) eq-equipment-settings fiix-settings-tile#statuses-tile'); private _setting_CloseSetting: ElementFinder = $('div.drawer-header-close-text') private _settings_Header: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(1) mat-drawer div.drawer-content-body fiix-heading h1'); private nextDrawer(drawerNumber: number): ElementFinder { let _nextDrawerElement = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(' + drawerNumber + ')'); return _nextDrawerElement; } public getCategoryTileSettings(): ElementFinder { return this._settings_EqCategoryTile; } public getStatusTileSettings(): ElementFinder { return this._settings_EqStatusTile; } public getCloseSettings(): ElementFinder { return this._setting_CloseSetting; } public getNextDrawerSettings(drawerNumber: number): ElementFinder { return this.nextDrawer(drawerNumber); } public getHeaderSettings(): ElementFinder { return this._settings_Header; } }<file_sep>import { by, element, ElementFinder, $ } from 'protractor'; export class CategoryListPO { private _drawerContainer_Header_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-heading h1'); private _drawerContainer_HeaderTotalCount_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-heading span.heading-total.ng-star-inserted'); private _drawerContainer_CreateButton_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list button.create-button.fiix-button'); private _drawerContainer_searchBox_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-search-bar input[id^="mat-input-"]'); private _drawerContainer_searchIconStartSearch_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-search-bar fiix-icon[name="search"]'); private _drawerContainer_searchIconClear_CategoryList: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-search-bar fiix-icon[name="cross"]'); private _drawerContainer_actionDropDown_Delete: ElementFinder = $("div.cdk-overlay-connected-position-bounding-box button[class~=delete-button]"); private _drawerContainer_categoryList_close: ElementFinder = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) div.drawer-content-header div.drawer-header-close-text'); private getCellForActionOnCatList(row:number, column: number): ElementFinder { let _actionCell = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-table table tbody tr:nth-of-type('+row+') > td:nth-of-type('+column+') fiix-icon[class~=ellipses]'); return _actionCell; } private getCellForNameOnCatList(row:number, column: number): ElementFinder { let _nameCell = $('div[class=cdk-global-overlay-wrapper]:nth-of-type(2) eq-category-list fiix-table table tbody tr:nth-of-type('+row+') > td:nth-of-type('+column+')'); return _nameCell; } public getDrawerContainerHeaderOnCatList(): ElementFinder { return this._drawerContainer_Header_CategoryList; } public getDrawerContainerHeaderTotalCountOnCatList(): ElementFinder { return this._drawerContainer_HeaderTotalCount_CategoryList; } public getCreateButtonOnCatList(): ElementFinder { return this._drawerContainer_CreateButton_CategoryList; } public getSearchBarOnCatList(): ElementFinder { return this._drawerContainer_searchBox_CategoryList; } public getSearchIconOnCatList(): ElementFinder { return this._drawerContainer_searchIconStartSearch_CategoryList; } public getSearchIconClearOnCatList(): ElementFinder { return this._drawerContainer_searchIconClear_CategoryList; } public getSearchResultNameCheckOnCatList(): ElementFinder { return this.getCellForNameOnCatList(1,2); } public getSearchResult1stRecordActionOnCatList(): ElementFinder { return this.getCellForActionOnCatList(1,5); } public getActionDropDownDeleteOnCatList(): ElementFinder { return this._drawerContainer_actionDropDown_Delete; } public getBackToSettingsOnCatList(): ElementFinder { return this._drawerContainer_categoryList_close; } }<file_sep>import { CategoryPO } from '../../../page-objects/Settings/Category/category.po'; import { browser, ExpectedConditions } from 'protractor'; import { SharedLogic } from '../../../page-logic/Shared/shared.service'; const categoryPO = new CategoryPO(); const shared = new SharedLogic(); export class CategoryLogic { public async checkCategoryCreateFormHeader(): Promise<void> { await browser.wait(ExpectedConditions.visibilityOf(categoryPO.getDrawerContainerHeaderOnCreateCategoryForm()), browser.params.waitTime); expect(await categoryPO.getDrawerContainerHeaderOnCreateCategoryForm().getText()).toBe("Create Equipment Category"); } public async clickCaregoryCreateForm1stBarcode(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryPO.get1stBarcodeOnCreateCategoryForm()), browser.params.waitTime); await categoryPO.get1stBarcodeOnCreateCategoryForm().click(); } public async checkCategoryCreateFormLabels(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryPO.getNameOnCreateCategoryForm())); expect(await categoryPO.getNameLabelOnCreateCategoryForm().getText()).toBe("Name*"); expect(await categoryPO.getParentLabelOnCreateCategoryForm().getText()).toBe("Parent"); expect(await categoryPO.getBarcodeHeaderOnCreateCategoryForm().getText()).toBe("Barcode Details"); expect(await categoryPO.getBarcodeDescriptionOnCreateCategoryForm().getText()).toBe("Select Barcode\n(Support on both Android and IOS devices)"); await browser.wait(ExpectedConditions.visibilityOf(categoryPO.getSaveButtonOnCreateCategoryForm()), browser.params.waitTime); expect(await categoryPO.getSaveButtonOnCreateCategoryForm().getText()).toBe("Save"); await browser.wait(ExpectedConditions.visibilityOf(categoryPO.getCancelButtonOnCreateCategoryForm()), browser.params.waitTime); expect(await categoryPO.getCancelButtonOnCreateCategoryForm().getText()).toBe("Cancel"); } public async clickCategoryCreateFormSaveButton(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryPO.getSaveButtonOnCreateCategoryForm())); await categoryPO.getSaveButtonOnCreateCategoryForm().click(); } public async enterCategoryCreateFormCategoryName(eqCatName: string): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryPO.getNameOnCreateCategoryForm()), browser.params.waitTime); await (categoryPO.getNameOnCreateCategoryForm().sendKeys(eqCatName)); } public async setCategoryFormName(eqCatName: string): Promise<void> { await this.checkCategoryCreateFormLabels(); await this.enterCategoryCreateFormCategoryName(eqCatName); await this.clickCategoryCreateFormSaveButton(); } public async setCategoryCreateFormCategoryWithNameAndBarCode(eqCatName: string): Promise<void> { await this.checkCategoryCreateFormLabels(); await this.enterCategoryCreateFormCategoryName(eqCatName); await this.clickCaregoryCreateForm1stBarcode(); await this.clickCategoryCreateFormSaveButton(); } public async gobackFromCategoryCreateFormToCategoryList(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(categoryPO.getReturnToListOnCreateCategroyForm()), browser.params.waitTime); await categoryPO.getReturnToListOnCreateCategroyForm().click(); } public async createCategoryFormCategoryWithName(eqCatName: string): Promise<void> { await this.checkCategoryCreateFormHeader(); await this.setCategoryFormName(eqCatName); await shared.checkSharedToastMessage(); await this.gobackFromCategoryCreateFormToCategoryList(); } public async createCategoryFormCategoryNameAndBarCode(eqCatName: string): Promise<void> { await this.checkCategoryCreateFormHeader(); await this.setCategoryCreateFormCategoryWithNameAndBarCode(eqCatName); await shared.checkSharedToastMessage(); await this.gobackFromCategoryCreateFormToCategoryList(); } }<file_sep>import { browser } from 'protractor'; import { EquipmentLogic } from '../logics/page-logic/Equipment/equipment.service'; import { SharedLogic } from '../logics/page-logic/Shared/shared.service'; import { EquipmentListLogic } from '../logics/page-logic/Equipment/equipmentList.service'; import { SettingsLogic } from '../logics/page-logic/Settings/settings.service'; import { CategoryListLogic } from '../logics/page-logic/Settings/Category/categoryList.service'; import { CategoryLogic } from '../logics/page-logic/Settings/Category/category.service'; describe('V6 Equipment : ', async () => { const equipment = new EquipmentLogic(); const equipmentList = new EquipmentListLogic(); const shared = new SharedLogic(); const settings = new SettingsLogic(); const categoryList = new CategoryListLogic(); const category = new CategoryLogic(); let categoryTotalCount: number = 0; beforeAll(async () => { await browser.waitForAngularEnabled(false); await browser.driver.manage().window().maximize(); await browser.waitForAngularEnabled(true); await browser.get(browser.params.baseURL); }); describe('on Equipment List View', () => { it('Test case1: Open equipment page', async () => { expect(await equipmentList.getListViewHeader()).toBe('Equipment'); }); it('Test case2: Check button, column headers, total record count, search bar and pagination, footer in List View', async () => { await equipmentList.checkListViewButtonNames(); await equipmentList.checkListViewColumnHeaders(); await equipmentList.checkTotalRecordCount(); await equipmentList.checkListViewSearchBarPresence(); await equipmentList.getListViewFooter(); }); it('Test case 3: Equipment List Pagination', async () => { await equipmentList.paginationCheck(browser.params.defaultPageSize); } ); }); describe('on Equipment Category', () => { it('Test case4: Create and Delete Category with Name and barcode', async () => { await equipmentList.openSettings(); await settings.checkSettingsHeader(); await settings.clickSettingsCategoryTile(); categoryTotalCount = await categoryList.checkCategoryListHeaderInfo(); await categoryList.clickCategoryListCreateButton(); await category.createCategoryFormCategoryNameAndBarCode(browser.params.category.categoryName); await categoryList.searchCategoryListwithName(browser.params.category.categoryName, categoryTotalCount); await categoryList.clickCategoryListOnActtion1stRecord(); await settings.closeSettingsDrawer(); }); }); describe('on Equipment', () => { it('Test case5: Create and cancel Equipment', async () => { await equipment.createAndCancelEq(); }); it('Test case6: Create and search for Equipment', async () => { let equipmentName: string = browser.params.equipment.equipmentName; await equipment.createAndSaveEq(equipmentName, browser.params.equipment.equipmentMake, browser.params.equipment.equipmentSerialNumber, browser.params.equipment.equipmentBarcode); await shared.checkSharedToastMessage(); await equipmentList.searchListViewForCreatedEq(browser.params.equipment.equipmentName) }); }); });
2008b8a0aa71758e84b2ad7bdcf0efa54df23708
[ "JavaScript", "TypeScript" ]
14
TypeScript
KhadijaRasul/gitTest4
7043bd3918523e86c103a444a766cf24183144d2
3487abf6f1e0b7eeed003ff8731a17e0272d88d8
refs/heads/main
<file_sep>from pynput.mouse import Listener, Button # ----------------------------------------------------------- # Gets the cursor position when the left mouse button is clicked # # Author: <NAME> (tjm8975) # ----------------------------------------------------------- def on_click(x, y, button, pressed): """Print the cursor position when the left mouse button is clicked""" if pressed and button == Button.left: print("Mouse Clicked: (%d, %d)" %(x, y)) listener.stop() # Create the Listener with Listener(on_click=on_click) as listener: listener.join()<file_sep># TargetPractices ## Contributors * <NAME> (tjm8975) * <NAME> (Jake-Stokes) ## Description target practice game for the boys made with python
3fbbec74ebb0c19b9b9490968fd9583d14a56266
[ "Markdown", "Python" ]
2
Python
tjm8975/TargetPractice
4d6b85f8432bf5f7c7e5e40dfcdc73beb6b51a88
d6bb4ded4f488a763ddd20b3cef51a2fd881c7c9
refs/heads/master
<repo_name>zyfdoudou/openui5<file_sep>/src/sap.ui.fl/test/sap/ui/fl/qunit/write/_internal/appVariant/AppVariantFactory.qunit.js /*global QUnit*/ sap.ui.define([ "sap/ui/thirdparty/jquery", "sap/ui/fl/descriptorRelated/api/DescriptorInlineChangeFactory", "sap/ui/fl/write/_internal/appVariant/AppVariantFactory", "sap/ui/fl/write/_internal/connectors/Utils", "sap/ui/fl/write/_internal/transport/TransportSelection", "sap/ui/fl/registry/Settings", "sap/ui/fl/Layer", "sap/ui/thirdparty/sinon-4" ], function( jQuery, DescriptorInlineChangeFactory, AppVariantFactory, WriteUtils, TransportSelection, Settings, Layer, sinon ) { "use strict"; var sandbox = sinon.sandbox.create(); // TODO: This test module will go to DescriptorInlineChangeFactory tests with a followup change QUnit.module("Given a DescriptorInlineChangeFactory for S4/Hana onPremise systems", { beforeEach : function() { sandbox.stub(Settings, "getInstance").resolves( new Settings({ isKeyUser:false, isAtoAvailable:false, isAtoEnabled:false, isProductiveSystem:false }) ); }, afterEach : function() { sandbox.restore(); } }, function() { QUnit.test("create_app_setTitle", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { type : "XTIT", maxLength : 20, comment : "a comment", value : { "" : "Default Title", en:"English Title", de:"Deutscher Titel", en_US:"English Title in en_US" } }; return DescriptorInlineChangeFactory.create_app_setTitle(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_app_setTitle"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].texts['a.id_sap.app.title'], 'Initial empty text key replaced'); assert.ok(!_oVariant.getDefinition().content[0].texts[''], 'Initial empty text key removed '); assert.deepEqual(_oVariant.getDefinition().content[0].texts['a.id_sap.app.title'], mParameter, 'Text in "texts"-node equals parameters set in factory method'); }); }); QUnit.test("create_app_setSubTitle", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { type : "XTIT", maxLength : 30, comment : "comment on subtitle", value : { "": "Default Subtitle", en: "English Subtitle", de: "Deutscher Untertitel", en_US: "English Subtitle in en_US" } }; return DescriptorInlineChangeFactory.create_app_setSubTitle(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_app_setSubTitle"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].texts['a.id_sap.app.subTitle'], 'Initial empty text key replaced'); assert.ok(!_oVariant.getDefinition().content[0].texts[''], 'Initial empty text key removed '); assert.deepEqual(_oVariant.getDefinition().content[0].texts['a.id_sap.app.subTitle'], mParameter, 'Text in "texts"-node equals parameters set in factory method'); }); }); QUnit.test("create_ui5_addLibraries", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { libraries: { "descriptor.mocha133": { minVersion: "1.44", lazy: false } } }; return DescriptorInlineChangeFactory.create_ui5_addLibraries(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_ui5_addLibraries"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].content.libraries['descriptor.mocha133'], 'Library is added'); assert.deepEqual(_oVariant.getDefinition().content[0].content, mParameter, 'Added library properties are equal to parameters set in factory method'); }); }); QUnit.test("create_app_setShortTitle", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { type : "XTIT", maxLength : 30, comment : "comment on shorttitle", value : { "" : "Default Shorttitle", en:"English Shorttitle", de:"Deutscher Kurztitel", en_US:"English Shorttitle in en_US" } }; return DescriptorInlineChangeFactory.create_app_setShortTitle(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_app_setShortTitle"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].texts['a.id_sap.app.shortTitle'], 'Initial empty text key replaced'); assert.ok(!_oVariant.getDefinition().content[0].texts[''], 'Initial empty text key removed '); assert.deepEqual(_oVariant.getDefinition().content[0].texts['a.id_sap.app.shortTitle'], mParameter, 'Text in "texts"-node equals parameters set in factory method'); }); }); QUnit.test("create_app_setDescription", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { type : "XTXT", maxLength : 50, comment : "comment on description", value : { "" : "Default Description", en:"English Description", de:"Deutsche Beschreibung", en_US:"English Description in en_US" } }; return DescriptorInlineChangeFactory.create_app_setDescription(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_app_setDescription"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].texts['a.id_sap.app.description'], 'Initial empty text key replaced'); assert.ok(!_oVariant.getDefinition().content[0].texts[''], 'Initial empty text key removed '); assert.deepEqual(_oVariant.getDefinition().content[0].texts['a.id_sap.app.description'], mParameter, 'Text in "texts"-node equals parameters set in factory method'); }); }); QUnit.test("create_app_setInfo", function(assert) { var _oDescriptorInlineChange; var _oVariant; var mParameter = { maxLength : 70, comment : "comment on info", value : { "" : "Default Info", en:"English Info", de:"Deutsche Info", en_US:"English Info in en_US" } }; return DescriptorInlineChangeFactory.create_app_setInfo(mParameter).then(function(oDescriptorInlineChange) { assert.ok(oDescriptorInlineChange, "Descriptor Inline Change created"); _oDescriptorInlineChange = oDescriptorInlineChange; assert.equal(oDescriptorInlineChange.getMap().changeType, "appdescr_app_setInfo"); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }); }).then(function(oVariant) { _oVariant = oVariant; return oVariant.addDescriptorInlineChange(_oDescriptorInlineChange); }).then(function() { assert.ok(_oVariant.getDefinition().content[0].texts['a.id_sap.app.info'], 'Initial empty text key replaced'); assert.ok(!_oVariant.getDefinition().content[0].texts[''], 'Initial empty text key removed '); assert.deepEqual(_oVariant.getDefinition().content[0].texts['a.id_sap.app.info'], mParameter, 'Text in "texts"-node equals parameters set in factory method'); }); }); QUnit.test("addDescriptorInlineChange", function(assert) { var _oVariant; return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { _oVariant = oVariant; return DescriptorInlineChangeFactory.createNew("changeType", {param:"value"}, {a: "b"}); }).then(function(oDescriptorInlineChange) { return _oVariant.addDescriptorInlineChange(oDescriptorInlineChange); }).then(function() { assert.notEqual(_oVariant.getDefinition().content, null); assert.equal(_oVariant.getDefinition().content.length, 1); assert.equal(_oVariant.getDefinition().content[0].changeType, "changeType"); assert.deepEqual(_oVariant.getDefinition().content[0].content, {param:"value"}); assert.deepEqual(_oVariant.getDefinition().content[0].texts, {a: "b"}); }); }); }); QUnit.module("Given a AppVariantFactory for S4/Hana onPremise systems", { beforeEach : function() { sandbox.stub(Settings, "getInstance").resolves( new Settings({ isKeyUser:false, isAtoAvailable:false, isAtoEnabled:false, isProductiveSystem:false }) ); }, afterEach : function() { sandbox.restore(); } }, function() { QUnit.test("When prepareUpdate is called one after another and backend responses are simulated differently", function(assert) { var fnNewConnectorCall = sandbox.stub(WriteUtils, "sendRequest"); fnNewConnectorCall.onFirstCall().resolves({response: '{ "id": "id.string", "reference":"base.id", "content": [] }'}); fnNewConnectorCall.onSecondCall().resolves({response: '{ "id": "id.json", "reference":"base.id", "content": [] }'}); fnNewConnectorCall.onThirdCall().resolves({response: '{ "id": "id.refVer", "reference":"base.id", "referenceVersion":"1.1", "content": [] }'}); return AppVariantFactory.prepareUpdate({ id: "id.string" }).then(function(oVariant) { assert.equal(oVariant.getDefinition().id, "id.string"); assert.equal(oVariant.getDefinition().reference, "base.id"); assert.ok(!oVariant.getDefinition().referenceVersion); }).then(function() { return AppVariantFactory.prepareUpdate({ id: "id.json" }); }).then(function(oVariant) { assert.equal(oVariant.getDefinition().id, "id.json"); assert.equal(oVariant.getDefinition().reference, "base.id"); assert.ok(!oVariant.getDefinition().referenceVersion); }).then(function() { return AppVariantFactory.prepareUpdate({ id: "id.refVer" }); }).then(function(oVariant) { assert.equal(oVariant.getDefinition().id, "id.refVer"); assert.equal(oVariant.getDefinition().reference, "base.id"); assert.equal(oVariant.getDefinition().referenceVersion, "1.1"); }); }); QUnit.test("When prepareUpdate is called only once", function(assert) { sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference" }) }); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function(oVariant) { assert.notEqual(oVariant, null); assert.equal(oVariant.getDefinition().id, "a.id"); assert.equal(oVariant.getDefinition().reference, "a.reference"); assert.equal(oVariant.getMode(), "EXISTING"); }); }); QUnit.test("When prepareUpdate is called and failure happens", function(assert) { sandbox.stub(WriteUtils, "sendRequest").rejects({message: "lalala"}); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function() { assert.notOk("Should never succeed"); }).catch(function(oError) { assert.ok(oError.message, "lalala"); }); }); QUnit.test("When prepareUpdate is called and variant was saved as a local object", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "$TMP" }) }); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""}); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.calledOnce); assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.callCount, 2); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).packageName, "$TMP"); assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).reference, "a.reference"); assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).id, "a.id"); assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).layer, "CUSTOMER"); assert.equal(oNewConnectorStub.getCall(1).args[1], "PUT"); }); }); QUnit.test("When prepareUpdate is called and variant was already published", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER" }) }); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"}); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.calledOnce); assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.callCount, 2); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport"); assert.equal(oNewConnectorStub.getCall(1).args[1], "PUT"); }); }); QUnit.test("When prepareDelete is called", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER" }) }); return AppVariantFactory.prepareDelete({ id: "a.id" }).then(function(oVariant) { assert.notEqual(oVariant, null); assert.equal(oVariant.getDefinition().id, "a.id"); assert.equal(oVariant.getDefinition().reference, "a.reference"); assert.equal(oNewConnectorStub.callCount, 1); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oVariant.getMode(), "DELETION"); }); }); QUnit.test("Smart Business: When prepareDelete is called", function(assert) { return AppVariantFactory.prepareDelete({ id: "a.id", isForSmartBusiness: true }).then(function(oVariant) { assert.notEqual(oVariant, null); assert.equal(oVariant.getDefinition().id, "a.id"); assert.equal(oVariant.getMode(), "DELETION"); }); }); QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete an app variant saved as local object", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "" }) }); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""}); return AppVariantFactory.prepareDelete({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.calledOnce); assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.callCount, 2); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(1).args[1], "DELETE"); }); }); QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete a published app variant", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "" }) }); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"}); return AppVariantFactory.prepareDelete({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.calledOnce); assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.callCount, 2); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport"); assert.equal(oNewConnectorStub.getCall(1).args[1], "DELETE"); }); }); QUnit.test("Smart Business: When prepareDelete is called to prepare a delete app variant config and submit is called to delete a published app variant", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves(); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection"); return AppVariantFactory.prepareDelete({ id: "a.id", transport: "aTransport", isForSmartBusiness: true }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.notCalled); assert.equal(oResponse, undefined); assert.equal(oNewConnectorStub.callCount, 1); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport"); assert.equal(oNewConnectorStub.getCall(0).args[1], "DELETE"); }); }); QUnit.test("When prepareCreate is called and getting id of app variant is checked", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.strictEqual(oVariant.getId(), "a.id"); }); }); QUnit.test("When prepareCreate is called and setting id of app variant is cross checked", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.strictEqual(oVariant.getReference(), "a.reference"); oVariant.setReference("new.reference"); assert.strictEqual(oVariant.getReference(), "new.reference"); }); }); QUnit.test("When prepareCreate is called and setting incorrect id of app variant failed", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.strictEqual(oVariant.getReference(), "a.reference"); oVariant.setReference(); // Setting reference with undefined value }).catch(function(sError) { assert.ok(sError); }); }); QUnit.test("When prepareCreate is called and getting id of reference app is checked", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.strictEqual(oVariant.getReference(), "a.reference"); }); }); QUnit.test("When prepareCreate is called and getting version of an app variant is checked", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", version: "1.0.0" }).then(function(oVariant) { assert.strictEqual(oVariant.getVersion(), "1.0.0"); }); }); QUnit.test("When prepareCreate is called and namespace of an app variant is checked", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.strictEqual(oVariant.getNamespace(), "apps/a.reference/appVariants/a.id/"); }); }); QUnit.test("When prepareCreate is called and setting transport is checked", function(assert) { var _oVariant; return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { _oVariant = oVariant; return oVariant.setTransportRequest("TR12345"); }).then(function() { assert.equal(_oVariant.getTransportRequest(), "TR12345"); }); }); QUnit.test("When prepareCreate is called and setting transport has wrong format", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { return oVariant.setTransportRequest("WRONG_FORMAT"); }).then(function() { assert.notOk("Should never succeed!"); }).catch(function(sError) { assert.ok(sError); }); }); QUnit.test("When prepareCreate is called and setting package is checked", function(assert) { var _oVariant; return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { _oVariant = oVariant; return oVariant.setPackage("/ABC/DEFGH_IJKL12345"); }).then(function() { assert.equal(_oVariant.getPackage(), "/ABC/DEFGH_IJKL12345"); }); }); QUnit.test("When prepareCreate is called and setting package has wrong format", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { return oVariant.setPackage("SomePackage_WrongFormat"); }).then(function() { assert.notOk("Should never succeed!"); }).catch(function(sError) { assert.ok(sError); }); }); QUnit.test("When prepareCreate is called and setting layer to customer", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", layer: Layer.CUSTOMER }).then(function(oVariant) { assert.equal(oVariant._getMap().layer, "CUSTOMER"); }); }); QUnit.test("When prepareCreate is called and setting layer to customer", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", layer: Layer.CUSTOMER_BASE }).then(function(oVariant) { assert.equal(oVariant._getMap().layer, "CUSTOMER_BASE"); }); }); QUnit.test("When prepareCreate is called and setting layer to partner", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", layer: Layer.PARTNER }).then(function(oVariant) { assert.equal(oVariant._getMap().layer, "PARTNER"); }); }); QUnit.test("When prepareCreate is called and setting layer to vendor", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", layer: Layer.VENDOR }).then(function(oVariant) { assert.equal(oVariant._getMap().layer, "VENDOR"); }); }); QUnit.test("When prepareCreate is called, variant saved into backend and checking app variant properties", function(assert) { return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { assert.notEqual(oVariant, null); assert.equal(oVariant.getId(), "a.id"); assert.equal(oVariant.getReference(), "a.reference"); assert.equal(oVariant.getMode(), "NEW"); assert.equal(oVariant._getMap().layer, Layer.CUSTOMER); assert.equal(oVariant._getMap().fileType, "appdescr_variant"); }); }); QUnit.test("When prepareCreate is called and failed with different possible failure options", function(assert) { return AppVariantFactory.prepareCreate({}) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.prepareCreate({ id : "a.id" }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.prepareCreate({ reference : "a.reference" }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.createNew({ id : 1, reference: "a.reference" }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.createNew({ id : "a.id", reference: 1 }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.createNew({ id : "a.id", reference: "a.reference", version: 2 }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }) .then(function() { return AppVariantFactory.createNew({ id : "a.id", reference: "a.reference", layer: true }); }) .then(function() { assert.notOk("Should never succeed!"); }) .catch(function(sError) { assert.ok(sError); }); }); }); QUnit.module("Given a AppVariantFactory for S4/Hana Cloud systems", { beforeEach : function() { //define sandboxes and stubs explicitly for each modules sandbox.stub(Settings, "getInstance").resolves( new Settings({ isKeyUser:false, isAtoAvailable:true, isAtoEnabled:true, isProductiveSystem:false }) ); }, afterEach : function() { sandbox.restore(); } }, function() { QUnit.test("When prepareCreate is called and variant is saved into the backend", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "YY1_DEFAULT_123" }) }); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.getCall(0).args[0], '/sap/bc/lrep/appdescr_variants/'); }); }); QUnit.test("SmartBusiness: When prepareCreate is called and variant is saved into the backend", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "YY1_DEFAULT_123" }) }); return AppVariantFactory.prepareCreate({ id : "a.id", reference: "a.reference", transport: "ATO_NOTIFICATION" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.getCall(0).args[0], '/sap/bc/lrep/appdescr_variants/?changelist=ATO_NOTIFICATION'); }); }); QUnit.test("Smart Business: When prepareUpdate is called and variant was already published", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "YY1_DEFAULT_123" }) }); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.getCall(1).args[0], '/sap/bc/lrep/appdescr_variants/a.id?changelist=ATO_NOTIFICATION'); }); }); QUnit.test("Smart Business: When prepareUpdate is called and variant was already published", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER", packageName: "YY1_DEFAULT_123" }) }); return AppVariantFactory.prepareUpdate({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.getCall(1).args[0], '/sap/bc/lrep/appdescr_variants/a.id?changelist=ATO_NOTIFICATION'); }); }); QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete an app variant saved as local object", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({ response: JSON.stringify({ id : "a.id", reference: "a.reference", layer: "CUSTOMER" }) }); var oSpyOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""}); return AppVariantFactory.prepareDelete({ id: "a.id" }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oSpyOpenTransportSelection.calledOnce); assert.notEqual(oResponse, null); assert.equal(oNewConnectorStub.callCount, 2); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(0).args[1], "GET"); assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id"); assert.equal(oNewConnectorStub.getCall(1).args[1], "DELETE"); }); }); QUnit.test("Smart Business: When prepareDelete is called to prepare a delete app variant config and submit is called to delete a published app variant", function(assert) { var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves(); var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection"); return AppVariantFactory.prepareDelete({ id: "a.id", transport: "ATO_NOTIFICATION", skipIam: true, isForSmartBusiness: true }).then(function(oVariant) { return oVariant.submit(); }).then(function(oResponse) { assert.ok(oStubOpenTransportSelection.notCalled); assert.equal(oResponse, undefined); assert.equal(oNewConnectorStub.callCount, 1); assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=ATO_NOTIFICATION"); assert.equal(oNewConnectorStub.getCall(0).args[1], "DELETE"); }); }); }); QUnit.done(function () { jQuery("#qunit-fixture").hide(); }); });
4f3d2fb2c5711f7bebbbd4a42a3e20e4e8a38a8c
[ "JavaScript" ]
1
JavaScript
zyfdoudou/openui5
1ae08c937bae519b5acd4867e228733369e2ad53
b91c872ae4b5aa1c567fcd7a31579990edb48231
refs/heads/master
<file_sep>package com.example.myapplication; import android.annotation.SuppressLint; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; @SuppressLint("Registered") public class LoginActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); } }
434d0cd10a188e8e21853cee6c61909e8edfabf5
[ "Java" ]
1
Java
Giselle-G/GE
39f7ac89c95ec28e5ce540972b37d40ac58657a7
b7543b0df5d0c6e1be2bc8be781e663748152552
refs/heads/master
<repo_name>tdrhq/bark<file_sep>/source_control.py #!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import getopt import logging import subprocess import os import sys class BadRev(BaseException): pass class NotARepo(BaseException): pass class SourceControl: def __init__(self, master="origin/master"): self._master = master def add_branch(self, name, parent=None): cmd = ["git", "checkout", "-b", name] if parent: cmd.append(parent) subprocess.check_call(cmd) def master(self): return self._master def get_root(self): curdir = os.getcwd() while not os.path.exists(os.path.join(curdir, ".git")): curdir = os.path.abspath(curdir + "/..") if curdir == "/": raise NotARepo() return curdir def checkout(self, name): subprocess.check_call(["git", "checkout", name]) def delete_branch(self, name): print("Deleting branch %s which was at rev: %s" % (name, self.rev_parse(name))) subprocess.check_call(["git", "branch", "-D", name]) def rebase(self, onto, base=None): if not base: subprocess.check_call(["git", "rebase", onto]) else: subprocess.check_call(["git", "rebase", "--onto", onto, base]) def current_branch(self): return subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip() def rev_parse(self, rev="HEAD"): try: return subprocess.check_output(["git", "rev-parse", rev]).strip() except subprocess.CalledProcessError: raise BadRev() def get_master_merge_point(self, rev): return subprocess.check_output(["git", "merge-base", rev, self._master]).strip() def is_clean(self): return subprocess.call(["git", "diff-index", "--quiet", "HEAD"]) == 0 def merge(self, other_rev): subprocess.check_call(["git", "merge", "--quiet", "-m", "merge point", other_rev]) def multi_merge(self, revs): assert self.is_clean() return self._rec_merge(revs) def _rec_merge(self, revs): if len(revs) == 1: return self.rev_parse(revs[0]) if len(revs) == 2: self.checkout(self.rev_parse(revs[0])) self.merge(revs[1]) return self.rev_parse() return self._rec_merge([self._rec_merge(revs[0:-1]), revs[-1]]) <file_sep>/test_bark.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import tempfile import shutil import os import subprocess import bark from bark import Bark from source_control import SourceControl, BadRev from subprocess import * from os.path import exists class TestBark(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.olddir = os.getcwd() os.chdir(self.tmpdir) subprocess.check_output(["git", "init"]) self.add_commit(a="foobar") self.source_control = SourceControl(master="master") self.bark = Bark(source_control=self.source_control) def tearDown(self): os.chdir(self.olddir) shutil.rmtree(self.tmpdir) def test_setup(self): pass def add_commit(self, **files): for k, v in files.iteritems(): f = open(str(k), "w") f.write(v) f.close() subprocess.check_output(["git", "add", k]) subprocess.check_output(["git", "commit", "-a", "-m", "stuff"]) return subprocess.check_output(["git", 'rev-parse', 'HEAD']).strip() def test_add_commit(self): h1 = self.add_commit(a="foo") h2 = self.add_commit(a="bar") self.assertNotEquals(h1, h2) def checkout(self, branch_name, parent="HEAD"): check_output(["git", "checkout", "-b", branch_name, parent]) def checkout_old(self, branch_name, parent="HEAD"): check_output(["git", "checkout", branch_name]) def test_list_managed(self): self.checkout("foo-branch") self.bark.manage_feature("foo-branch") self.assertEquals(["foo-branch"], self.bark.list_features()) def test_non_existent_feature(self): try: self.bark.manage_feature("doesnotexist") self.fail("expected exception") except BadRev: pass # expected def _build_tree(self): self.source_control.checkout("master") self.add_commit(a="foo") self.checkout("parent") self.add_commit(b="bar") self.checkout("child", "parent") self.add_commit(c="car") self.checkout("otherchild", "parent") self.add_commit(c="car2") self.bark.manage_feature("parent") self.bark.manage_feature("child") self.bark.manage_feature("otherchild") self.bark._add_dep("otherchild", "parent") self.bark._add_dep("child", "parent") def test_rebase(self): self._build_tree() self.checkout_old("parent") self.add_commit(z="blah") self.bark.rebase_all("child") self.checkout_old("child") self.assertTrue(exists("z")) def test_linear_dep_finder(self): self._build_tree() self.assertEquals(["parent"], self.bark.get_deps("child")) def test_command_line_manage(self): self.checkout("foo") bark.main(["./a.out", "manage", "foo"]) self.assertEquals(["foo"], Bark(source_control=self.source_control).list_features()) def test_command_line_add_dep(self): self.checkout("foo") self.checkout("bar") Bark(source_control=self.source_control).manage_feature("foo") Bark(source_control=self.source_control).manage_feature("bar") old_bark = bark.instance try: bark.instance = self.bark bark.main(["./a.out", "add_dep", "bar", "foo"]) finally: bark.instance = old_bark self.assertEquals(["foo"], Bark(source_control=self.source_control).get_deps("bar")) def test_stores_base_rev(self): hash = self.source_control.rev_parse() self.bark.create_feature("foobar") f = self.bark.feature_db.get_feature_by_name("foobar") self.assertEquals(hash, f.base_rev) def test_create_feature_with_base(self): hash = self.source_control.rev_parse() self.add_commit(z="blah") self.bark.create_feature("foobar", hash) f = self.bark.feature_db.get_feature_by_name("foobar") self.assertEquals(hash, f.base_rev) def test_create_feature_with_parent(self): self.bark.create_feature("foo") self.bark.create_feature("bar", parent="foo") f = self.bark.feature_db.get_feature_by_name("bar") self.assertEquals(["foo"], f.deps) def test_doesnt_allow_me_to_add_dep_when_base_commit_is_differentt(self): self.bark.create_feature("foo") self.add_commit(y="bsdfdsf") self.source_control.checkout("master") self.add_commit(z="boo") self.bark.create_feature("bar") self.add_commit(zz="dfsdfds") self.source_control.checkout("master") self.bark.create_feature("booboo") self.add_commit(dfd="dfsfs") try: self.bark.add_dep("booboo", "bar") self.fail("expected exception") except SystemExit: pass # expected def test_rebase_all_rebases_single_branch_onto_master(self): self.bark.create_feature("foo") self.add_commit(d="foobar") self.source_control.checkout("master") new_master = self.add_commit(b="blahblah") self.source_control.checkout("foo") self.bark.rebase_all("foo") self.source_control.checkout("foo") self.assertTrue(exists("b")) self.assertEquals(new_master, self.bark.feature_db.get_feature_by_name("foo").base_rev) def test_create_feature_with_feature_should_create_over_master(self): master = self.add_commit(c="fdfd") self.bark.create_feature("foo") self.add_commit(d="dfdfds") self.bark.create_feature("bar") self.assertEquals(master, self.source_control.rev_parse()) def test_delete_feature(self): self.bark.create_feature("foo") self.source_control.checkout("master") self.bark.delete_feature("foo") self.assertEquals([], self.bark.list_features()) def test_delete_feature_when_more_features_exist(self): self.bark.create_feature("bar") self.bark.create_feature("foo") self.source_control.checkout("master") self.bark.delete_feature("foo") self.assertEquals(["bar"], self.bark.list_features()) def test_delete_feature_when_more_features_different_order(self): self.bark.create_feature("foo") self.bark.create_feature("bar") self.source_control.checkout("master") self.bark.delete_feature("foo") self.assertEquals(["bar"], self.bark.list_features()) def test_delete_current_feature(self): master = self.add_commit(b="cdf") self.bark.create_feature("foo") foo = self.add_commit(c="dfsdf") self.bark.delete_feature("foo") self.assertEquals([], self.bark.list_features()) self.assertEquals(master, self.source_control.rev_parse()) def test_complete_linear_feature(self): master = self.add_commit(bb="boo") self.bark.create_feature("foo") self.add_commit(dd="blah") self.bark.create_feature("bar") self.add_commit(ee="sdfdsf") self.source_control.checkout("master") self.bark.complete_feature("foo") self.assertEquals([], self.bark.feature_db.get_feature_by_name("bar").deps) self.source_control.checkout("bar") self.assertTrue(os.path.exists("ee")) self.assertFalse(os.path.exists("dd")) try: self.source_control.rev_parse("foo") self.fail("expected foo to not exist") except BadRev: pass # expected def test_complete_current_feature(self): master = self.add_commit(bb="boo") self.bark.create_feature("foo") self.add_commit(cc="ddd") self.bark.complete_feature("foo") self.assertFalse(os.path.exists("cc")) try: self.source_control.rev_parse("foo") self.fail("expected foo to not exist") except BadRev: pass # expected def test_rebase2(self): self.bark.create_feature("foo") self.add_commit(cc="dd") self.bark.create_feature("bar", parent="foo") self.add_commit(dd="boo") self.assertTrue(os.path.exists("cc")) self.source_control.checkout("foo") self.add_commit(ff="dfdfd") self.source_control.checkout("bar") self.bark.rebase("bar") self.assertTrue(os.path.exists("dd")) self.assertTrue(os.path.exists("cc")) self.assertTrue(os.path.exists("ff")) if __name__ == '__main__': unittest.main() <file_sep>/README.md [WORK IN PROGRESS] == Manage your branches in git == This is especially useful if you use arcanist or some such tool which squashes your commit. The model: we track one "trunk" or "master" branch. By default this is "origin/master". Every feature branch either starts from this branch or from another feature branch. Create a feature branch using the "feature" command: bark feature foo-bar Every feature branch can have multiple dependencies on other feature branches. bark feature foo-bar2 bark add_dep foo-bar2 foo-bar at this point you can continue working on both foo-bar and foo-bar2 branches. When you want to sync everything call: bark rebaseall In particular this will rebase foo-bar2 onto the update foo-bar. It will also rebase foo-bar onto the latest version of origin/master (as retrieved from last fetch) Now, if you have multiple features and you call add_dep, we'll enforce that *all managed features start from the same commit on origin/master*. This is a simplication to make it easy to think about what's going on behind the scenes. If we see that you don't meet this constraint we'll suggest you run "rebaseall" which will bring everything to speed. Once we have this database of dependencies, it's easy to write programmatic things to handle dependencies. For example using arcanist a common pattern is to diff against the parent diff, which can be automated as: arc diff `bark get-root-diff` (TODO: implement get-root-diff) You might also want to automatically list all the dependencies in your arcanist message. As a first step you can get the list of all dependencies using `bark get-deps` (TODO: implement), and then parse the branches to find out what the phabricator diff is. <file_sep>/bark.py #!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import getopt import logging import os import sys from source_control import BadRev from source_control import SourceControl from feature_db import FeatureDb, Feature class BadArgs(BaseException): pass class Bark: def __init__(self, source_control): self.source_control = source_control self.feature_db = FeatureDb() def init(self): os.chdir(self.source_control.get_root()) def manage_feature(self, feature, base_rev=None): self.source_control.rev_parse(feature) f = Feature() f.name = feature f.base_rev = base_rev self.feature_db.add_feature(f) def create_feature(self, name, parent=None): add_dep = True if not parent: parent = self.source_control.master() add_dep = False self.source_control.add_branch(name, parent) self.manage_feature(name, base_rev=source_control.rev_parse()) f = self.feature_db.get_feature_by_name(name) if add_dep: f.deps.append(parent) self.feature_db.update_feature(f) def _validate_mergeable(self): features = self.list_features() merge_bases = [self.source_control.get_master_merge_point(f) for f in features] print("stuff %s" % merge_bases) if len(set(merge_bases)) > 1: print('All branches need to have the same merge point with maser, run "bark rebaseall"') exit(1) def add_dep(self, name, parent): self._validate_mergeable() self._add_dep(name, parent) feature = self.feature_db.get_feature_by_name(name) merge_point = self.source_control.multi_merge(feature.deps) self.source_control.checkout(feature.name) self.source_control.rebase(merge_point, feature.base_rev) feature.base_rev = merge_point self.feature_db.update_feature(feature) def delete_feature(self, feature_name): # verify feature is not referenced from another feature features = self.feature_db.list_features() for feature in features: for f in feature.deps: if f == feature.name: raise RuntimeError("Dep in use") # move to master if we're on the deleted branch if self.source_control.current_branch() == feature_name: self.source_control.checkout(self.source_control.master()) self.feature_db.delete_feature_by_name(feature_name) source_control.delete_branch(feature_name) def list_features(self): return [f.name for f in self.feature_db.list_features()] def _get_feature_for(self, name): features = self.feature_db.list_features() for f in features: if f.name == name: return f def _add_dep(self, child, parent): f = self.feature_db.get_feature_by_name(child) f.deps += [parent] self.feature_db.update_feature(f) def get_deps(self, feature): return self._get_feature_for(feature).deps def rebase_all(self, feature): f = self.feature_db.get_feature_by_name(feature) deps = self.get_deps(feature) # make sure all children are up-to-date before doing anything for d in deps: print("first updating " + d) self.rebase_all(d) merge_point = self._get_merge_point(deps) self.source_control.checkout(feature) self.source_control.rebase(merge_point, base=f.base_rev) f.base_rev = merge_point self.feature_db.update_feature(f) def rebase(self, feature=None): feature = feature or self.source_control.current_branch() f = self.feature_db.get_feature_by_name(feature) self.source_control.checkout(feature) # todo: toposort and only use direct deps print(f.deps) merge_point = self._get_merge_point(f.deps) self.source_control.rebase(merge_point, base=f.base_rev) f.base_rev = merge_point self.feature_db.update_feature(f) def complete_feature(self, feature_name): if not self.feature_db.get_feature_by_name(feature_name): print("Could not find feature: ", feature_name) return features = self.feature_db.list_features() # the ones before feature won't be affected while features[0].name != feature_name: print("stripping off %s" % features[0].name) features.pop(0) # make sure all dependent features are rebased before deleting # the feature for f in features[1:]: if feature_name in f.deps: f.deps.remove(feature_name) merge_point = self._get_merge_point(f.deps) if merge_point == f.base_rev: continue self.source_control.checkout(f.name) self.source_control.rebase(merge_point, base=f.base_rev) f.base_rev = merge_point self.feature_db.update_feature(f) self.feature_db.delete_feature_by_name(feature_name) if self.source_control.current_branch() == feature_name: self.source_control.checkout(self.source_control.master()) self.source_control.delete_branch(feature_name) def _get_merge_point(self, deps): merge_point = self.source_control.rev_parse(self.source_control.master()) if len(deps) > 0: merge_point = self.source_control.multi_merge(deps) return merge_point def print_features(self): for f in self.feature_db.list_features(): print(f.name) def print_base(self): f = self.feature_db.get_feature_by_name(self.source_control.current_branch()) print(f.base_rev) def print_deps(self): f = self.feature_db.get_feature_by_name(self.source_control.current_branch()) for x in f.deps: print(x) def usage(): print("unimplemented") sys.exit(1) def cmd_feature(args): options, rest_args = getopt.gnu_getopt( args[1:], "", [ "continue", ] ) print(rest_args) print(options) feature_name = rest_args[0] dep = (rest_args[1] if len(rest_args) == 2 else None) if "--continue" in dict(options): dep = source_control.current_branch() instance.create_feature(feature_name, parent=dep) def delete_feature(args): feature_name = args[1] instance.delete_feature(feature_name) source_control = SourceControl() instance = Bark(source_control=source_control) def manage(rest_args, root_options): branch = rest_args instance.manage_feature(rest_args[1]) def main(argv): instance.init() try: options, rest_args = getopt.getopt( argv[1:], "", [ ] ) except getopt.GetoptError as e: print(e.msg + "\n") usage() return 1 command = rest_args[0] if command == "manage": manage(rest_args, options) elif command == "rebaseall": instance.rebase_all(rest_args[1]) elif command == "add_dep": instance.add_dep(rest_args[1], rest_args[2]) elif command =="feature": cmd_feature(rest_args) elif command == "delete-feature": delete_feature(rest_args) elif command == "complete": instance.complete_feature(argv[2]) elif command == "list": instance.print_features() elif command == "rebase": instance.rebase() elif command == "print-base": instance.print_base() elif command == "print-deps": instance.print_deps() else: raise RuntimeError("unsupported") return 0 if __name__ == '__main__': main(sys.argv) <file_sep>/feature_db.py #!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import getopt import logging import os import sys import json sys.path.append(os.path.dirname(__file__) + "/toposort-1.4") from toposort import toposort_flatten FEATURE_FILE = '.bark_features' class Feature: def __init__(self): self.name = None self.deps = [] self.base_rev = None def _sort_features(features): graph = {} for f in features: graph[f.name] = set(f.deps) order = toposort_flatten(graph, sort=True) ret = [] for name in order: for f in features: if f.name == name: ret.append(f) return ret class FeatureDb: def __init__(self, filename=FEATURE_FILE): self.filename = filename def _to_json_array(self, features): ret = [] for f in features: ret.append({ "name": f.name, "deps": f.deps, "base_rev": f.base_rev, }) return {"features": ret} def _from_json_array(self, array): ret = [] for f in array["features"]: ff = Feature() ff.name = f["name"] ff.deps = f["deps"] ff.base_rev = f["base_rev"] ret.append(ff) return ret def _read_features(self): ret = [] if not os.path.exists(self.filename): return [] with open(self.filename, "r") as f: return self._from_json_array(json.load(f)) def list_features(self): return _sort_features(self._read_features()) def _write_features(self, features): with open(self.filename, "w") as f: json.dump(self._to_json_array(features), f) def add_feature(self, feature): features = self._read_features() features.append(feature) self._write_features(features) def delete_feature_by_name(self, feature_name): features = self._read_features() features = [x for x in features if x.name != feature_name] self._write_features(features) def get_feature_by_name(self, feature_name): for x in self._read_features(): if x.name == feature_name: return x def update_feature(self, feature): self.delete_feature_by_name(feature.name) self.add_feature(feature) <file_sep>/toposort-1.4/setup.py from __future__ import print_function from distutils.core import setup, Command import sys # This is a hack in order to get the package name to be different when # building an RPM file. When 'setup.py bdist_rpm' is called, it invokes # setup.py twice more, with these command lines: # ['setup.py', 'build'] # ['setup.py', 'install', '-O1', '--root=/home/eric/local/toposort/build/bdist.linux-i686/rpm/BUILDROOT/python-toposort-0.1-1.i386', '--record=INSTALLED_FILES'] # It's only on the original call (when bdist_rpm is in sys.argv) that # I adjust the package name. With Python 2.7, that's enough. I'm not # sure about 3.x. name = 'toposort' if 'bdist_rpm' in sys.argv: name = 'python{0}-{1}'.format('' if sys.version_info.major == 2 else '3', name) # run our tests class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess tests = [('test suite', ['-m', 'test.test_toposort']), ] if sys.hexversion >= 0x03000000: # Skip doctests for python < 3.0. They use set literal reprs, which # are different in 2.7. Testing under 3.x is good enough. tests.append(('doctests', ['-m' 'doctest', 'README.txt'])) for name, cmds in tests: print(name) errno = subprocess.call([sys.executable] + cmds) if errno != 0: raise SystemExit(errno) print('test complete') setup(name=name, version='1.4', url='https://bitbucket.org/ericvsmith/toposort', author='<NAME>', author_email='<EMAIL>', description='Implements a topological sort algorithm.', long_description=open('README.txt').read() + '\n' + open('CHANGES.txt').read(), classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], license='Apache License Version 2.0', py_modules=['toposort'], cmdclass = {'test': PyTest}, ) <file_sep>/test_source_control.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import tempfile import shutil import os import subprocess import bark from source_control import SourceControl, NotARepo from subprocess import * from os.path import exists class TestSourceControl(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.olddir = os.getcwd() os.chdir(self.tmpdir) subprocess.check_output(["git", "init"]) self.add_commit(a="foobar") self.sc = SourceControl() def add_commit(self, **files): for k, v in files.iteritems(): f = open(str(k), "w") f.write(v) f.close() subprocess.check_output(["git", "add", k]) subprocess.check_output(["git", "commit", "-a", "-m", "stuff"]) return subprocess.check_output(["git", 'rev-parse', 'HEAD']) def tearDown(self): os.chdir(self.olddir) shutil.rmtree(self.tmpdir) def test_add_branch(self): self.sc.add_branch("foobar") self.assertEquals("foobar", self.sc.current_branch()) def test_delete_branch(self): self.sc.add_branch("foobar") self.sc.add_branch("foobar3") self.sc.delete_branch("foobar") self.assertNotEquals( 0, subprocess.call(["git", 'rev-parse', "foobar"])) self.assertEquals( 0, subprocess.call(["git", 'rev-parse', "foobar3"])) def test_delete_unmerged_branch(self): self.sc.add_branch("foobar") self.add_commit(a="sdfdf") self.sc.checkout("master") self.sc.delete_branch("foobar") def test_get_hash(self): self.sc.add_branch("blah") hash1 = self.sc.rev_parse("blah") self.add_commit(b="boo") hash2 = self.sc.rev_parse("blah") self.assertEquals(40, len(hash1)) self.assertNotEquals(hash1, hash2) def test_checkout(self): self.sc.add_branch("blah") self.sc.add_branch("blah2") self.sc.checkout("blah") self.assertEquals("blah", self.sc.current_branch()) def test_master_merge_point(self): self.sc.add_branch("blah") self.add_commit(b="boo") merge_point = self.sc.rev_parse() self.sc.add_branch("blah2") self.add_commit(d="dfsfdsf") self.sc.checkout("blah") self.add_commit(c="gah") sc = SourceControl(master="blah") self.assertEquals(merge_point, sc.get_master_merge_point("blah2")) def test_is_clean(self): self.assertTrue(self.sc.is_clean()) with open("a", "w") as f: f.write("blah2") self.assertFalse(self.sc.is_clean()) def test_merge(self): self.sc.add_branch("blah") self.add_commit(b="woo") self.sc.checkout("master") self.sc.add_branch("blah2") self.add_commit(d="blahhh") self.sc.merge("blah") self.assertTrue(exists("b")) self.assertTrue(exists("d")) self.assertTrue(self.sc.is_clean()) def test_multi_merge_with_two(self): self.test_merge() self.sc.checkout("master") self.sc.add_branch("blah3") self.add_commit(f="sdfdsfdsf") self.sc.checkout("master") rev = self.sc.multi_merge(["blah", "blah2", "blah3"]) self.assertNotEquals(None, rev) self.sc.checkout(rev) self.assertTrue(exists("b")) self.assertTrue(exists("d")) self.assertTrue(exists("f")) def test_get_root_dir(self): root = os.getcwd() self.assertEquals(root, self.sc.get_root()) os.mkdir("foo") os.chdir("foo") self.assertEquals(root, self.sc.get_root()) def test_no_git_dir(self): shutil.rmtree(".git") try: self.sc.get_root() except NotARepo: pass # expected if __name__ == '__main__': unittest.main() <file_sep>/test_feature_db.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import tempfile import shutil import os import subprocess import bark from feature_db import FeatureDb, Feature from subprocess import * from os.path import exists class TestFeatureDb(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() self.feature_db = FeatureDb(filename=self.filename) def tearDown(self): if exists(self.filename): os.remove(self.filename) def test_stuff(self): pass def test_stores_stuff(self): f = Feature() f.name = "boo" f.deps = ["ab", "c"] f.base_rev = "blah" self.feature_db.add_feature(f) ff = self.feature_db.get_feature_by_name("boo") self.assertEquals("boo", ff.name) self.assertEquals(["ab", "c"], ff.deps) self.assertEquals("blah", ff.base_rev) def test_toposorts(self): f = Feature() f.name = "boo" f.deps = "blah" self.feature_db.add_feature(f) f2 = Feature() f2.name = "blah" self.feature_db.add_feature(f2) self.assertEquals(["blah", "boo"], [x.name for x in self.feature_db.list_features()])
a05398ca7f1b8c90cd9678adb8b0dcd800c5a16e
[ "Markdown", "Python" ]
8
Python
tdrhq/bark
cb18b337a16270e5be815627366d51efd3392fae
9fdd9f84f4c7e592b93e35953aa25481a5453778
refs/heads/master
<file_sep>//<NAME> //1er <NAME> //Este programa obtiene el mejor tiempo y ruta para transferir un archivo de un origen a un destino en una red de computadora; //tomando como base el concepto de latencia. public class Enlace { private int noOrigen; private int noDestino; private int tasaTransfer; private int distancia; private int DC; private int DU; public Enlace(int noOrigen, int noDestino, int velEnlace, int distancia, int DC, int DU) { this.noOrigen = noOrigen; this.noDestino = noDestino; this.tasaTransfer = velEnlace; this.distancia = distancia; this.DC = DC; this.DU = DU; } public int getNoOrigen() { return noOrigen; } public int getNoDestino() { return noDestino; } public int getTasaTransfer() { return tasaTransfer; } public int getDistancia() { return distancia; } public int getDC() { return DC; } public int getDU() { return DU; } } <file_sep> import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; //<NAME> //1er Par<NAME> //Este programa obtiene el mejor tiempo y ruta para transferir un archivo de un origen a un destino en una red de computadora; //tomando como base el concepto de latencia. public class Archivo { public ArrayList<String> leerArchivo() throws FileNotFoundException, IOException { String cadena; ArrayList<String> lineas = new ArrayList<>(); BufferedReader bf = new BufferedReader(new FileReader("src/datos.txt")); while ( ( cadena = bf.readLine() ) != null ) { lineas.add(cadena); } bf.close(); return lineas; } } <file_sep>//<NAME> //1er Parcial Modelo de Redes //Este programa obtiene el mejor tiempo y ruta para transferir un archivo de un origen a un destino en una red de computadora; //tomando como base el concepto de latencia. public class Nodo { private int noNodo; private double TC; public Nodo(int noNodo, double TC) { this.noNodo = noNodo; this.TC = TC; } public int getNoNodo() { return noNodo; } public double getTC() { return TC; } public void setTC(float TC) { this.TC = TC; } } <file_sep># latency_calculation Network - Latency Calculation (Transfer time) The file: Examen1.pdf contains the explanation of the program and the UML Diagram.
010fe8519a28a87cdf80534ef8c769d4ccd23e27
[ "Markdown", "Java" ]
4
Java
alondraSanchezM/latency_calculation
3cd90eb409785505ad246ac8404881b00cb2c6a6
c943ea97a0c42a14d15c0317c9fe1318e17dd1dc
refs/heads/main
<file_sep>import React, { useEffect } from "react"; import axios from "axios"; import { useSelector, useDispatch } from "react-redux"; import ProductComponent from "./ProductComponent"; import {setProducts, setProviders} from '../redux/actions/commonActions'; const ProductListing = () => { const products = useSelector((state) => state); const dispatch = useDispatch(); //console.log(products); const fetchProducts = async () => { const response = await axios .get( "https://api.inquickerstaging.com/v3/winter.inquickerstaging.com/services" ) .catch((err) => { console.log(err); }); console.log("response"); dispatch(setProducts(response?.data?.data)); }; const fetchProviders = async () => { const response = await axios .get( "https://api.inquickerstaging.com/v3/winter.inquickerstaging.com/providers?include=locations%2Cschedules.location&page%5Bnumber%5D=1&page%5Bsize%5D=1000" ) .catch((err) => { console.log(err); }); console.log("response"); dispatch(setProviders(response?.data?.data)); }; useEffect(() => { fetchProducts(); fetchProviders(); }, []); return ( <div className="ui grid container"> <ProductComponent /> </div> ); }; export default ProductListing; <file_sep>import React, { useState } from "react"; import { useSelector } from "react-redux"; import ProductDetail from "./ProductDetail"; const ProductComponent = (props) => { const products = useSelector((state) => state.reducer.products); const [showDetail, setShowDetail] = useState(false); const [prodName, setProdName] = useState(); const setProducts = (name) => { setProdName(name); console.log(name); if (name != prodName) { setShowDetail(true); } else { setShowDetail(false); } }; const list = products.map((product) => { return ( <li className="four column wide width" key={product.id}> <div className="ui link cards link"> <div className="card"> <div className="content" onClick={() => setProducts(product?.attributes?.name)} > <div className="header">{product?.attributes?.name}</div> <div className="header">{product?.id}</div> </div> </div> </div> </li> ); }); return ( <div className="flex"> <div> <div>Control Section</div> <ul>{list}</ul> </div> <div className="card p-l"> <div>Result Section</div> {showDetail && <ProductDetail name={prodName} />} </div> </div> ); }; export default ProductComponent;
81ad50bf4e1ac78c6ed32feb11ba74d8debea365
[ "JavaScript" ]
2
JavaScript
pawan2726/react-redux
8dd9f31239bdedf0de6fd24e2f22c72ed0632f3e
3ae0e34b00e85df8eb6a520d6a90dc1718a0159e
refs/heads/master
<file_sep>/** * */ /** * @author Chapito * */ package Resources;<file_sep>package Main; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import Resources.AStar; import Resources.AStar.RouteNode; import Resources.Graph; import Resources.Triple; import Resources.Graph.Edge; import Resources.Graph.Node; import Resources.RandomWalk; public class main { public static void main(String[] args) { Graph g = new Graph(); Node Aguadilla = new Node("Aguadilla", 15.66f, false); Node Isabela = new Node("Isabela", 22.14f, false); Node Quebradillas = new Node("Quebradillas", 23.22f, false); Node Camuy = new Node("Camuy", 27.74f, false); Node Hatillo = new Node("Hatillo", 28.77f, false); Node Arecibo = new Node("Arecibo", 33.85f, false); Node Rincon = new Node("Rincon", 11.85f, false); Node Aguada = new Node("Aguada", 12.67f, false); Node Moca = new Node("Moca", 13.55f, false); Node SanSebastian = new Node("San Sebastian", 13.55f, false); Node Lares = new Node("Lares", 18.73f, false); Node Utuado = new Node("Utuado", 29.5f, false); Node Anasco = new Node("Anasco", 5.86f, false); Node Mayaguez = new Node("Mayaguez", 0, true); Node LasMarias = new Node("LasMarias", 11.12f, false); Node Maricao = new Node("Maricao", 10.93f, false); Node Adjuntas = new Node("Adjuntas", 27.9f, false); Node Jayuya = new Node("Jayuya", 36.35f, false); Node CaboRojo = new Node("CaboRojo", 7.96f, false); Node Hormigueros = new Node("Hormigueros", 4.43f, false); Node SanGerman = new Node("San German", 10.81f, false); Node SabanaGrande = new Node("S<NAME>", 14.86f, false); Node Lajas = new Node("Lajas", 11.92f, false); Node Guanica = new Node("Guanica", 22.19f, false); Node Yauco = new Node("Yauco", 22.58f, false); Node Guayanilla = new Node("Guayanilla", 26.42f, false); Node Penuelas = new Node("Penuelas", 29.60f, false); Node Ponce = new Node("Ponce", 37.28f, false); g.addVertex(Aguadilla); g.addVertex(Isabela); g.addVertex(Quebradillas); g.addVertex(Camuy); g.addVertex(Hatillo); g.addVertex(Arecibo); g.addVertex(Rincon); g.addVertex(Aguada); g.addVertex(Moca); g.addVertex(SanSebastian); g.addVertex(Lares); g.addVertex(Utuado); g.addVertex(Anasco); g.addVertex(Mayaguez); g.addVertex(LasMarias); g.addVertex(Maricao); g.addVertex(Adjuntas); g.addVertex(Jayuya); g.addVertex(CaboRojo); g.addVertex(Hormigueros); g.addVertex(SanGerman); g.addVertex(SabanaGrande); g.addVertex(Lajas); g.addVertex(Guanica); g.addVertex(Yauco); g.addVertex(Guayanilla); g.addVertex(Penuelas); g.addVertex(Ponce); g.addEdge(Aguadilla, Aguada, 4.01f, 45, 0.8f); g.addEdge(Aguadilla, Isabela, 9.88f, 45, 0.9f); g.addEdge(Aguadilla, Moca, 3.51f, 35, 0.9f); g.addEdge(Isabela, Moca, 9.38f, 35, 0.9f); g.addEdge(Isabela, Quebradillas, 5.94f, 45, 1f); g.addEdge(Isabela, SanSebastian, 11.79f, 35, 1f); g.addEdge(Quebradillas, Camuy, 5.92f, 45, 0.9f); g.addEdge(Camuy, Lares, 13.27f, 35, 1f); g.addEdge(Camuy, Hatillo, 1.31f, 45, 0.8f); g.addEdge(Hatillo, Arecibo, 7.28f, 45, 0.9f); g.addEdge(Rincon, Aguada, 4.9f, 35, 1f); g.addEdge(Aguada, Moca, 5.05f, 35, 1f); g.addEdge(Aguada, Anasco, 7.21f, 45, 0.8f); g.addEdge(Moca, Anasco, 7.76f, 35, 0.9f); g.addEdge(Moca, SanSebastian, 8.8f, 35, 0.9f); g.addEdge(SanSebastian, LasMarias, 5.44f, 35, 0.8f); g.addEdge(SanSebastian, Lares, 8.22f, 45, 0.8f); g.addEdge(Lares, LasMarias, 7.61f, 35, 0.8f); g.addEdge(Lares, Utuado, 11.75f, 35, 0.9f); g.addEdge(Lares, Adjuntas, 13.68f, 35, 0.8f); g.addEdge(Utuado, Adjuntas, 7.24f, 35, 1f); g.addEdge(Utuado, Jayuya, 7.86f, 35, 0.9f); g.addEdge(Anasco, Mayaguez, 5.81f, 45, 0.9f); g.addEdge(Anasco, LasMarias, 10.37f, 35, 0.8f); g.addEdge(Mayaguez, Hormigueros, 4.42f, 45, 0.8f); g.addEdge(Mayaguez, LasMarias, 16.7f, 35, 0.8f); g.addEdge(LasMarias, Maricao, 7.6f, 35, 0.9f); g.addEdge(Maricao, SanGerman, 7.99f, 35, 0.8f); g.addEdge(Maricao, SabanaGrande, 7.28f, 35, 0.8f); g.addEdge(Adjuntas, Penuelas, 7.33f, 35, 0.8f); g.addEdge(Jayuya, Ponce, 14.41f, 35, 1f); g.addEdge(Hormigueros, CaboRojo, 3.92f, 45, 0.9f); g.addEdge(Hormigueros, SanGerman, 6.97f, 45, 1f); g.addEdge(CaboRojo, SanGerman, 6.89f, 45, 1f); g.addEdge(CaboRojo, Lajas, 6.21f, 45, 0.9f); g.addEdge(SanGerman, Lajas, 2.44f, 35, 0.9f); g.addEdge(SanGerman, SabanaGrande, 5.30f, 45, 1f); g.addEdge(SabanaGrande, Guanica, 8.02f, 45, 0.9f); g.addEdge(SabanaGrande, Yauco, 7.81f, 45, 1f); g.addEdge(Lajas, Guanica, 11.27f, 35, 0.9f); g.addEdge(Guanica, Yauco, 5.81f, 45, 0.9f); g.addEdge(Yauco, Guayanilla, 4.02f, 45, 1f); g.addEdge(Guayanilla, Penuelas, 5.30f, 45, 1f); g.addEdge(Penuelas, Ponce, 8.21f, 45, 1f); ArrayList<Triple<String, Float, Float>> Explored = new ArrayList<Triple<String, Float, Float>>(); RandomWalk random = new RandomWalk(); float pathSum = 0; float costSum = 0; float dist = 0; // total cost of travel // distance/(speedLimit*traffic) float totalCost = 0; // Sets start time for the algorithm's runtime long startTime = System.nanoTime(); Explored = random.RandomWalk(Camuy, g.getMap(), Explored, dist, totalCost); // How long the algorithm took to run long duration = System.nanoTime() - startTime; // Prints all locations visited in Explored for Randomwalk // Except the last one for(int i = 0; i < Explored.size() - 1; i++) { System.out.println(Explored.get(i).toStringFirst()); System.out.println(Explored.get(i).toStringSecond()); System.out.println(Explored.get(i).toStringThird()); pathSum += Explored.get(i).getSecond(); costSum += Explored.get(i).getThird(); } // Prints only the last node visited System.out.println(Explored.get(Explored.size()-1).toStringFirst()); System.out.println("\nPath Cost to goal: " + pathSum); System.out.println("Total Travel Cost to goal: " + costSum); System.out.println("RandomWalk Total Runtime: " + duration + " nanoseconds\n"); startTime = System.nanoTime(); RouteNode pathAStar = new AStar().aStarSearch(g, Camuy); float pathCost = pathAStar.getPathCost(); while(pathAStar!=null) { System.out.println(pathAStar.getCurrentNode().getName() + " : " + pathAStar.getPathCost()); pathAStar = pathAStar.getPreviousNode(); } duration = System.nanoTime() - startTime; System.out.println("\nTotal cost to goal: " + pathCost); System.out.println("A* Total Runtime: " + duration + " nanoseconds"); } private static void makeGraph(Graph g) { Node Aguadilla = new Node("Aguadilla", 15.66f, false); Node Isabela = new Node("Isabela", 22.14f, false); Node Quebradillas = new Node("Quebradillas", 23.22f, false); Node Camuy = new Node("Camuy", 27.74f, false); Node Hatillo = new Node("Hatillo", 28.77f, false); Node Arecibo = new Node("Arecibo", 33.85f, false); Node Rincon = new Node("Rincon", 11.85f, false); Node Aguada = new Node("Aguada", 12.67f, false); Node Moca = new Node("Moca", 13.55f, false); Node SanSebastian = new Node("<NAME>", 13.55f, false); Node Lares = new Node("Lares", 18.73f, false); Node Utuado = new Node("Utuado", 29.5f, false); Node Anasco = new Node("Anasco", 5.86f, false); Node Mayaguez = new Node("Mayaguez", 0, true); Node LasMarias = new Node("LasMarias", 11.12f, false); Node Maricao = new Node("Maricao", 10.93f, false); Node Adjuntas = new Node("Adjuntas", 27.9f, false); Node Jayuya = new Node("Jayuya", 36.35f, false); Node CaboRojo = new Node("CaboRojo", 7.96f, false); Node Hormigueros = new Node("Hormigueros", 4.43f, false); Node SanGerman = new Node("San German", 10.81f, false); Node SabanaGrande = new Node("S<NAME>", 14.86f, false); Node Lajas = new Node("Lajas", 11.92f, false); Node Guanica = new Node("Guanica", 22.19f, false); Node Yauco = new Node("Yauco", 22.58f, false); Node Guayanilla = new Node("Guayanilla", 26.42f, false); Node Penuelas = new Node("Penuelas", 29.60f, false); Node Ponce = new Node("Ponce", 37.28f, false); g.addVertex(Aguadilla); g.addVertex(Isabela); g.addVertex(Quebradillas); g.addVertex(Camuy); g.addVertex(Hatillo); g.addVertex(Arecibo); g.addVertex(Rincon); g.addVertex(Aguada); g.addVertex(Moca); g.addVertex(SanSebastian); g.addVertex(Lares); g.addVertex(Utuado); g.addVertex(Anasco); g.addVertex(Mayaguez); g.addVertex(LasMarias); g.addVertex(Maricao); g.addVertex(Adjuntas); g.addVertex(Jayuya); g.addVertex(CaboRojo); g.addVertex(Hormigueros); g.addVertex(SanGerman); g.addVertex(SabanaGrande); g.addVertex(Lajas); g.addVertex(Guanica); g.addVertex(Yauco); g.addVertex(Guayanilla); g.addVertex(Penuelas); g.addVertex(Ponce); g.addEdge(Aguadilla, Aguada, 4.01f, 45, 0.8f); g.addEdge(Aguadilla, Isabela, 9.88f, 45, 0.9f); g.addEdge(Aguadilla, Moca, 3.51f, 35, 0.9f); g.addEdge(Isabela, Moca, 9.38f, 35, 0.9f); g.addEdge(Isabela, Quebradillas, 5.94f, 45, 1f); g.addEdge(Isabela, SanSebastian, 11.79f, 35, 1f); g.addEdge(Quebradillas, Camuy, 5.92f, 45, 0.9f); g.addEdge(Camuy, Lares, 13.27f, 35, 1f); g.addEdge(Camuy, Hatillo, 1.31f, 45, 0.8f); g.addEdge(Hatillo, Arecibo, 7.28f, 45, 0.9f); g.addEdge(Rincon, Aguada, 4.9f, 35, 1f); g.addEdge(Aguada, Moca, 5.05f, 35, 1f); g.addEdge(Aguada, Anasco, 7.21f, 45, 0.8f); g.addEdge(Moca, Anasco, 7.76f, 35, 0.9f); g.addEdge(Moca, SanSebastian, 8.8f, 35, 0.9f); g.addEdge(SanSebastian, LasMarias, 5.44f, 35, 0.8f); g.addEdge(SanSebastian, Lares, 8.22f, 45, 0.8f); g.addEdge(Lares, LasMarias, 7.61f, 35, 0.8f); g.addEdge(Lares, Utuado, 11.75f, 35, 0.9f); g.addEdge(Lares, Adjuntas, 13.68f, 35, 0.8f); g.addEdge(Utuado, Adjuntas, 7.24f, 35, 1f); g.addEdge(Utuado, Jayuya, 7.86f, 35, 0.9f); g.addEdge(Anasco, Mayaguez, 5.81f, 45, 0.9f); g.addEdge(Anasco, LasMarias, 10.37f, 35, 0.8f); g.addEdge(Mayaguez, Hormigueros, 4.42f, 45, 0.8f); g.addEdge(Mayaguez, LasMarias, 16.7f, 35, 0.8f); g.addEdge(LasMarias, Maricao, 7.6f, 35, 0.9f); g.addEdge(LasMarias, Lares, 7.65f, 35, 0.8f); g.addEdge(Maricao, SanGerman, 7.99f, 35, 0.8f); g.addEdge(Maricao, SabanaGrande, 7.28f, 35, 0.8f); g.addEdge(Adjuntas, Penuelas, 7.33f, 35, 0.8f); g.addEdge(Jayuya, Ponce, 14.41f, 35, 1f); g.addEdge(Hormigueros, CaboRojo, 3.92f, 45, 0.9f); g.addEdge(Hormigueros, SanGerman, 6.97f, 45, 1f); g.addEdge(CaboRojo, SanGerman, 6.89f, 45, 1f); g.addEdge(CaboRojo, Lajas, 6.21f, 45, 0.9f); g.addEdge(SanGerman, Lajas, 2.44f, 35, 0.9f); g.addEdge(SanGerman, SabanaGrande, 5.30f, 45, 1f); g.addEdge(SabanaGrande, Guanica, 8.02f, 45, 0.9f); g.addEdge(SabanaGrande, Yauco, 7.81f, 45, 1f); g.addEdge(Lajas, Guanica, 11.27f, 35, 0.9f); g.addEdge(Guanica, Yauco, 5.81f, 45, 0.9f); g.addEdge(Yauco, Guayanilla, 4.02f, 45, 1f); g.addEdge(Guayanilla, Penuelas, 5.30f, 45, 1f); g.addEdge(Penuelas, Ponce, 8.21f, 45, 1f); } } <file_sep>package Resources; import java.util.ArrayList; import java.util.LinkedList; import java.util.Map; import Resources.Graph.Edge; import Resources.Graph.Node; public class RandomWalk { /* * Recursively accepts a node and a map of a graph and returns a Map of * the names of the Nodes in the path and their distances. It uses the distance between * Nodes as a weight for the randomization. * Backtracking is allowed. */ public ArrayList<Triple<String, Float, Float>> RandomWalk(Node current, Map<Node, LinkedList<Edge>> map, ArrayList<Triple<String, Float, Float>> Result, float goalDist, float totalCost) { // List used to hold weights and results for randomization RandomCollection<Node> randomList = new RandomCollection<>(); // List to hold the Edges connected to the selected node LinkedList<Edge> Frontier = map.get(current); // Refers to the node to be visited next Node nextNode; // Pair where the current node and the distance needed to reach it are saved Triple<String, Float, Float> triple = new Triple<String, Float, Float>(null, null, null); // Checks if the current Node is the goal or not // Returns Result if it is if(current.isGoal == true) { triple.setFirst(current.name); triple.setSecond(goalDist); triple.setThird(totalCost); Result.add(triple); return Result; } else { // Iterates through the map's edges to set the weights for randomList // Weight depends on the distance to the next node // That weight is used to determine the probability of being chosen for(int i = 0; i < Frontier.size(); i++) { randomList.add(Frontier.get(i).distance/(Frontier.get(i).speedLimit*Frontier.get(i).traffic), Frontier.get(i).destination); } // Rolls for the node to be visited next nextNode = randomList.next(); // Once a node has been chosen by the randomization, finds which path was chosen // and gets the distance traveled and then adds it to Result for(int k = 0; k < Frontier.size(); k++) { if(Frontier.get(k).destination == nextNode) { triple.setFirst(current.name); triple.setSecond(Frontier.get(k).distance); goalDist = triple.getSecond(); totalCost = goalDist/(Frontier.get(k).speedLimit*Frontier.get(k).traffic); triple.setThird(totalCost); Result.add(triple); } } } return RandomWalk(nextNode, map, Result, goalDist, totalCost); } } <file_sep>package Resources; public class Triple<F, S, T> { private F first; //first member of triple private S second; //second member of triple private T third; //third member of triple public Triple(F first, S second, T third) { this.first = first; this.second = second; this.third = third; } public void setFirst(F first) { this.first = first; } public void setSecond(S second) { this.second = second; } public void setThird(T third) { this.third = third; } public F getFirst() { return first; } public S getSecond() { return second; } public T getThird() { return third; } public boolean isEmpty() { if(first == null && second == null && third == null) { return true; } else { return false; } } public String toStringFirst() { return "Currently at: " + first; } public String toStringSecond() { return "\nPath Cost to Next: " + second; } public String toStringThird() { return "Total Travel Cost to Next: " + third; } }
39a813eb50d9f30100cfc69820589551a87914c7
[ "Java" ]
4
Java
HRiivera/AIProject
f4f03216687d2be56b482e3b3dafc31e80d7fc81
f786086d54e11901e554ad57992979bc4d0ddb40
refs/heads/master
<repo_name>mlpatt23/atw<file_sep>/functions.php <?php // Register stylesheets function atw_styles() { // Add stylesheets wp_register_style('googlefonts', 'https://fonts.googleapis.com/css?family=PT+Sans:400,700', array(), '1.0.0'); wp_register_style('normalize', get_template_directory_uri() . '/css/normalize.css', array(), '6.0.0'); wp_register_style('style', get_template_directory_uri() . '/style.css', array('normalize'), '1.0'); // Enqueue stylesheets wp_enqueue_style('normalize'); wp_enqueue_style('style'); } add_action('wp_enqueue_scripts', 'atw_styles'); // Add menus to theme function atw_menus() { register_nav_menus(array( 'header-menu' => __('Header Menu', 'atw') )); } add_action('init', 'atw_menus'); // Add featured image support add_theme_support('post-thumbnails'); ?><file_sep>/header.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Around the World</title> <!-- Make Title dynamic --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?> <header style="background:url('<?php echo $backgroundImg[0]; ?>')"> <div class="header-content"> <div class="wrapper"> <div class="logo"> <a href="<?php echo esc_url( home_url('/') ); ?>"> <img src="<?php echo get_template_directory_uri(); ?>/img/logo.svg" alt="Around the World Logo"> </a> </div> <!-- logo --> <nav> <?php wp_nav_menu(array('theme_location' => 'header-menu')); ?> </nav> </div> <!-- wrapper --> </div> <!-- header-content --> </header> <div class="wrapper">
4c6163c4f730b6320f710a195dae644e0fc03227
[ "PHP" ]
2
PHP
mlpatt23/atw
2f7ecf43cdfcf62bb77a56e0a6b857328e6e8cc6
173fd511e3a1e3487764e4cdf885c981a56c5b0b
refs/heads/master
<file_sep>/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uwemlivesore; /** * {@link Uwemlivescore} represents a single Android platform release. * Each object has 3 properties: name, version number, and image resource ID. */ public class Uwemlivescore { /** * Magnitude of the earthquake */ private String mLeaguename; // Location of the earthquake private String mtime; // Location of the earthquake private String mhomename; // Location of the earthquake private String mScore; // Date of the earthquake private String mawayname; /** * Constructs a new {@link Uwemlivescore} object. * * @param leaguename is the magnitude (size) of the earthquake * @param time is the location where the earthquake happened * @param homename is the time in milliseconds (from the Epoch) when the * earthquake happened */ public Uwemlivescore(String leaguename, String time, String homename, String score, String awayname) { mLeaguename = leaguename; mtime = time; mhomename = homename; mScore = score; mawayname = awayname; } /** * Get the Magnitude */ public String getLeaguename() { return mLeaguename; } /** * Get the Location */ public String getTime() { return mtime; } /** * Get the Location */ public String getHomename() { return mhomename; } /** * Get the Location */ public String getScores() { return mScore; } /** * Get the date */ public String getAwayname() { return mawayname; } }<file_sep># UwemLiveScore_V1 This is the version 1 of the app. Its has no fragments and view pager.
b9c5de2f7082505c2848d1bb87f28f9df40b1e6b
[ "Markdown", "Java" ]
2
Java
vidadex/UwemLiveScore_V1_1
398a4b5b959afab65df2265f342d9e3c4c202b35
a13893fc1d7fecb3de7e28b92f1c22920e3661a6
refs/heads/master
<file_sep>Code for my web site. <file_sep>#!/bin/bash set -x mkdir -p public/css node_modules/stylus/bin/stylus \ --compress \ --out public/css \ --include node_modules/nib/lib \ assets/css
6b673fa724f4a34cf67447bd3ad39065185aeaba
[ "Markdown", "Shell" ]
2
Markdown
lmjohns3/leifjohnson.net
3973fa2df259df0eaf79fddeed81f280f75dbd8c
f39ba42d4b165888e2d7c160427eb90aa96052bc
refs/heads/master
<repo_name>MakotoNinja/circle-point<file_sep>/script.py #!/usr/bin/env python ''' ' Moisture sensing and watering routine for Farmbot ''' import os, sys, json, Qualify from random import randint from farmware_tools import device, app, get_config_value from Coordinate import Coordinate def take_readings(): plants_chosen = [] device.execute(moisture_tool_retrieve_sequence_id) #coord = Coordinate(device.get_current_position('x'), device.get_current_position('y'), Z_TRANSLATE) #device.log('Creating Coordinate') bot = Coordinate(device.get_current_position('x'), device.get_current_position('y')) bot.set_offset(OFFSET_X, OFFSET_Y, move_abs=False) # sets the offset, auto-move disabled #device.log('BOT: {}'.format(bot)) for i in range(NUM_SITES): rand_plant_num = randint(0, len(target_plants) - 1) while rand_plant_num in plants_chosen: rand_plant_num = randint(0, len(target_plants) - 1) plants_chosen.append(rand_plant_num) rand_plant = target_plants[rand_plant_num] device.log('Random Plant: {}'.format(json.dumps(rand_plant))) bot.set_axis_position('z', Z_TRANSLATE) # sets the z axis to translate height, auto-move enabled bot.set_coordinate(rand_plant['x'], rand_plant['y']) # set the plant coordinate, auto-move enabled bot.set_axis_position('z', SENSOR_Z_DEPTH) # plunge sensor into soil, auto-move enabled # take reading(s) site_readings = [] for j in range(NUM_SAMPLES): device.read_pin(PIN_SENSOR, 'Sensor', 1) site_readings.append(device.get_pin_value(PIN_SENSOR)) device.wait(100) average = 0 for reading in site_readings: average += reading average /= NUM_SAMPLES moisture_readings.append(average) device.log('Site Reading #{}: {}'.format(i, average), 'success') bot.set_axis_position('z', Z_TRANSLATE) device.log('Readings: {}'.format(json.dumps(moisture_readings)), 'success') device.execute(moisture_tool_return_sequence_id) def response(): average = 0 for i in moisture_readings: average += i average /= len(moisture_readings) device.log('Total Moisture Average: {}'.format(average), 'info') if average < THRESHOLD: device.execute(water_tool_retrieve_sequence_id) device.execute(water_sequence_id) device.execute(water_tool_return_sequence_id) PIN_LIGHTS = 7 PIN_SENSOR = 59 PIN_WATER = 8 PKG = 'Water Routine' input_errors = [] device.log('INIT') PLANT_TYPES = Qualify.get_csv(PKG, 'plant_types') #device.log('CSVs Qualified') SENSOR_Z_DEPTH = Qualify.integer(PKG, 'sensor_z_depth') Z_TRANSLATE = Qualify.integer(PKG,'z_translate') OFFSET_X = Qualify.integer(PKG,'offset_x') OFFSET_Y = Qualify.integer(PKG,'offset_y') THRESHOLD = Qualify.integer(PKG,'threshold') NUM_SITES = Qualify.integer(PKG,'num_sites') NUM_SAMPLES = Qualify.integer(PKG,'num_samples') #device.log('Integers Qualified') moisture_tool_retrieve_sequence_id = Qualify.sequence(PKG, 'tool_moisture_retrieve') moisture_tool_return_sequence_id = Qualify.sequence(PKG, 'tool_moisture_return') water_tool_retrieve_sequence_id = Qualify.sequence(PKG, 'tool_water_retrieve') water_tool_return_sequence_id = Qualify.sequence(PKG, 'tool_water_return') water_sequence_id = Qualify.sequence(PKG, 'water_sequence') #device.log('Sequences Qualified') moisture_readings = [] if len(input_errors): for err in input_errors: device.log(err, 'warn') device.log('Fatal config errors occured, farmware exiting.', 'warn') sys.exit() else: device.log('No config errors were detected.', 'success') if device.get_current_position('x') > 10 or device.get_current_position('y') > 10 or device.get_current_position('z') < -10: device.home('all') device.write_pin(PIN_LIGHTS, 1, 0) target_plants = [] all_plants = app.get_plants() for plant in all_plants: if plant['name'].lower() in PLANT_TYPES: target_plants.append(plant) take_readings() response(); device.home('all') device.write_pin(PIN_LIGHTS, 0, 0)
0be434eafcbf3d22039e7aed772013057d1e6959
[ "Python" ]
1
Python
MakotoNinja/circle-point
3e1f8c5d6f3a2960863d4a7f120d2419949724a4
2094e5c855c1e9d3220c0acde946056b71ea8a31
refs/heads/master
<file_sep>const fi = (function() { return { libraryMethod: function() { return 'Start by reading https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0' }, each: function(collection, callback) { const newArray = Object.values(collection) // Create a var and set it equal to an 'Object.value', which accepts our original array and returns the values in a new array. for (let i = 0; i < newArray.length; i++) { // We then use a 'for' loop to print out our messages callback(newArray[i]) // Using 'Object.values' ensures that we return the values if the collection is an object or an array } return collection // Finally, we return our original array after the messages have finished printing }, map: function(collection, callback) { const emptyArray = []; // First, initialize a variable equal to an empty array. This will help keep our original array unmodified. const newArray = Object.values(collection) // Second, use 'Object.values' to again extract the values from the array for (let i = 0; i < newArray.length; i++){ // Third, use a 'for' loop to take each value from the array... emptyArray.push(callback(newArray[i])) // ...pass it into the callback AND pass the result of that callback into our empty array! } return emptyArray; // Once all values are accounted for, return the array with the modified values. }, reduce: function(collection, callback, acc) { let total = (acc) ? acc : collection[0] // First, we check to see if an acc was entered. If so, we set it equal to our var total. Otherwise, we set total equal to the first element in our array. let i = (acc) ? 0 : 1 // Second, if we had an acc, we want the value of 'i' to equal 0 so that we are adding the acc to the first element of our array using the callback function. If not, we set it equal to 1 so we can add the first 2 elements of the array together. for (; i < collection.length; i++) { // Again, another for loop to go through each element in the collection total = callback(total, collection[i]) // We set our total equal to the result generated by the function, so we can keep a running tally until all elements are accounted for. } return total // Once all the elements have been added together, we return the total now equal to their sum. }, find: function(collection, predicate){ for (let i = 0; i < collection.length; i++){ // We run through our array and plug the current element into our predicate function if(predicate(collection[i])) { return collection[i] // If the predicate returns a true value, we return that element of the collection and the for loop stops } } return undefined // If no element from the array returns a true value from our predicate, when the for loop ends we return 'undefined' }, filter: function(collection, predicate){ const valuesArray = [] // Set var equal to an empty array for(let i = 0; i < collection.length; i++){ // Run a for loop for each element if(predicate(collection[i])){ // If the element produces 'true' from our predicate function... valuesArray.push(collection[i]) //...push that element into the new array } } return valuesArray // return the array after all elements have been inspected }, size: function(collection){ const newCollection = Object.values(collection) // Again, we account for arrays and objects with 'Object.values' return newCollection.length // Returns the size of the array }, first: function(collection, n){ if (n){ // If the user entered a value for 'n'... return collection.slice(0, n) //... we take our array and slice out the first 'n' elements and return the new array } return collection[0] // Otherwise, we simply return the first element of the array (easy right? :D) }, last: function(collection, n){ if (n){ // If a 'n' was provided... return collection.slice(-n) // We take slice and enter in the negative value of 'n' to return the final 'n' elements } return collection[(collection.length)-1] // Otherwise, we find the last element of our array using 'length' and return it }, compact: function(array){ const newArray = []; // Create our new array to leave the original array unmodified for (let i = 0; i < array.length; i++){ // For look to check each element if (array[i]){ // If the element is a truthy value... newArray.push(array[i]) // Push that element into our new array } } return newArray // After all elements have been inspected, return the new array }, sortBy: function(array, callback){ const newArray = [...array] // Takes the original array passed in and puts it in a new array defined as 'newArray' we can now modify newArray.sort(function(a, b) { // We call the sort method on this array and use a function that takes two values of the array... return callback(a) - callback(b) //...and pass them into our callback, subtracting the values from each other and ordering them accordingly }) return newArray // Finally, we return our new array with the sorted values }, flatten: function(array, shallow){ if (shallow){ // If our shallow argument has a value return array.flat() // We only flatten our deep array by 1 level } return array.flat(Infinity) // Otherwise, we use 'Infinity' in our flat method to flatten the array on all levels. }, uniq: function(array, isSorted, callback){ const newArray = [...array] // Takes our original array and makes a new one with the same values. if(callback) { // First we check to see if we have a callback function present... const modifiedArray = new Set() // Create vars that are equal to objects ready to hold values const originalArray = new Set() for(let value of newArray) { // For each value of our newArray... const newValue = callback(value) // we set newValue equal to the result of passing the array value into our callback function if(!modifiedArray.has(newValue)) { // If our modified array object does not have this callback value... modifiedArray.add(newValue) // We add this new value to the to the modified array object... originalArray.add(value) // and add the original value passed into our original array object. } } return(Array.from(originalArray)) // After all the values that were the same have been removed, be return our values. } else if(isSorted) { // If the array is already sorted... return newArray.filter((value, index, array) => array.indexOf(value) === index) // we perform a filter to see if there are any duplicates } else { return newArray.filter((value, index, array) => array.indexOf(value) === index) // same here, only for unsorted arrays } }, keys: function(object){ return Object.keys(object) // I mean, I would explain more, but since this is so straighforward I won't ;) }, values: function(object){ return Object.values(object) // Same story here ;D }, functions: function(object){ const newArray = [] // We have our empty array defined for (const key in object) { // if(typeof object[key] === "function") newArray.push(object[key]) } return newArray } } })() fi.libraryMethod()
6be952ad3c1b61dee5904db789b81f72788f9651
[ "JavaScript" ]
1
JavaScript
Andrew-J-Williams/js-advanced-functions-functional-library-project-online-web-sp-000
60484379ea3945449694045153f27de8a3bb4e96
44c8a22adbdf9f44879826404ad39d7609ce248d
refs/heads/master
<repo_name>bc-jasond/twitter-markov-chain<file_sep>/markov-twitter-bot.js /** * this library's methods are all coupled together, I pulled it into the project and slightly modified it for this exercise but, wouldn't use it otherwise * */ const Twitter = require('twitter') const MarkovGen = require('markov-generator') const tipots = require('this-is-probably-ok-to-say') const schedule = require('node-schedule') const unescape = require('lodash.unescape') class TwitterBot { constructor (options) { this.arrayOfTweets = [] this.options = { hour: 4, minute: 0, account: '', db: null, twitter: { consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET }, bannedWords: [], includeAts: true, includeHashtags: true, replyTo: '' } Object.assign(this.options, options) if (!this.options.account) { throw new Error('No twitter account handle was assigned in options') } this.twitterClient = this.createTwitterClient() } createTwitterClient () { let noMissingKeys = true let missingKey let expectedStructure = { consumer_key: '', consumer_secret: '', access_token_key: '', access_token_secret: '' } // make sure api keys are not false for (let key in this.options.twitter) { if (!this.options.twitter[key]) { noMissingKeys = false } } // make sure all 4 expected keys are present for (let key in expectedStructure) { if (!this.options.twitter[key]) { noMissingKeys = false missingKey = key } } // set this.twitterClient to a new instance of the twitter api object if (noMissingKeys) { return new Twitter({ consumer_key: this.options.twitter.consumer_key, consumer_secret: this.options.twitter.consumer_secret, access_token_key: this.options.twitter.access_token_key, access_token_secret: this.options.twitter.access_token_secret }) // otherwise return an error } else { if (missingKey) { throw new Error('Missing twitter API key: ' + missingKey) } throw new Error('Missing twitter API keys!') } } checkForBannedWords (tweet) { let lower = tweet.toLowerCase() this.options.bannedWords.forEach((e) => { if (lower.includes(e.toLowerCase)) { return true } }) return false } checkForAts (tweet) { if (!this.options.includeAts) { return tweet.includes('@') } else { return false } } checkForHashtags (tweet) { if (!this.options.includeHashtags) { return tweet.includes('#') } else { return false } } getTweets(cb) { let lastID let count = 0 let get = (max_id) => { this.twitterClient.get('statuses/user_timeline', {screen_name: this.options.account, max_id: max_id, count: 200, exclude_replies: true, include_rts: false}, (error, timeline, response) => { if (error) throw new Error(error[0].message) timeline.forEach((e, i, a) => { const tweetText = unescape(e.text) if (!this.arrayOfTweets.includes(tweetText)) { this.arrayOfTweets.push(tweetText) } if (i === a.length - 1) { lastID = e.id } }) count++ if (count <= 15) { get(lastID) } if (count === 16) { if (cb) { return cb(null, this.arrayOfTweets) } else { return this.arrayOfTweets } } }) } get() } generateTweet (callback) { if (!this.arrayOfTweets.length) { console.log('arrayOfTweets was empty!') this.getTweets() } let markov = new MarkovGen({ input: this.arrayOfTweets, minLength: 6 }) let tweet = markov.makeChain() while (tweet.length > 140 || !tipots(tweet) || this.checkForBannedWords(tweet) || this.checkForAts(tweet) || this.checkForHashtags(tweet)) { tweet = markov.makeChain() } if (callback) { return callback(null, tweet) } return tweet } generateReply (replyToUser, callback) { if (!this.arrayOfTweets.length) { console.log('arrayOfTweets was empty!') this.getTweets() } let markov = new MarkovGen({ input: this.arrayOfTweets, minLength: 4 }) let tweet = markov.makeChain() let replyString = '@' + replyToUser + ' ' let length = 140 - replyString.length while (tweet.length > length || !tipots(tweet) || this.checkForBannedWords(tweet) || this.checkForHashtags(tweet) || this.checkForAts(tweet)) { tweet = markov.makeChain() } if (callback) { return callback(replyString + tweet) } return replyString + tweet } postTweet (callback) { this.generateTweet((tweet) => { this.twitterClient.post('statuses/update', {status: tweet}, function (error, postedTweet, response) { if (error) { console.log(error) throw error } if (callback) { callback() } }) }) } setTimedFunctions () { let updateRule = new schedule.RecurrenceRule() updateRule.hour = 1 updateRule.minute = 55 schedule.scheduleJob('50 */1 * * *', () => { this.getTweets((array) => { this.arrayOfTweets = array console.log('updated tweets at ' + Date.now()) }) }) let cronString = this.options.minute + ' */' + this.options.hour + ' * * *' schedule.scheduleJob(cronString, () => { this.postTweet() }) } setReplyFunction () { this.twitterClient.stream('statuses/filter', {track: '@' + this.options.replyTo}, (stream) => { stream.on('data', (tweet) => { this.generateReply(tweet.user.screen_name, (replyTweet) => { this.twitterClient.post('statuses/update', { status: replyTweet, in_reply_to_status_id: tweet.id_str }, (err, postedReply, res) => { if (err) throw err console.log(res) }) }) }) }) } } module.exports = TwitterBot <file_sep>/app/welcome/welcome.component.js import html from './welcome.html'; class Controller { constructor($rootScope) { 'ngInject'; this.$rootScope = $rootScope; } $onInit() {} } export default { template: html, controllerAs: 'welcome', controller: Controller, }; <file_sep>/README.md Markov Chain Tweet Generator ============================= this was scaffolded using `angular-es6-webpack-starter` ##### Quick start Make sure you have Node version >= 6.0 and NPM >= 3 ``` # install the repo with npm npm install # set env variables for twitter client export TWITTER_ACCESS_TOKEN_SECRET=foo export TWITTER_CONSUMER_KEY=bar export TWITTER_CONSUMER_SECRET=baz export TWITTER_ACCESS_TOKEN_KEY=qux # start the 'backend' server node server.js # start the 'frontend' server npm start ``` go to [http://localhost:9000](http://localhost:9000) in your browser note: this generates tweets from David Mamet quotes because they're fun and they're text only<file_sep>/app/welcome/welcome.module.js import angular from 'angular'; import component from './welcome.component'; /* @ngInject */ export default angular .module('welcome', []) .component('welcome', component); <file_sep>/server.js const TwitterBot = require('./markov-twitter-bot'); const http = require('http'); const url = require('url'); const {promisify} = require('util'); const hostname = '127.0.0.1'; const port = 3000; const defaultAccount = 'DailyMamet'; const tweetsCache = {}; const markovChainCache = {}; const server = http.createServer(async (req, res) => { const queryParams = url.parse(req.url, true).query; const account = queryParams.account ? queryParams.account : defaultAccount; const shouldUseCache = queryParams.cache !== '0'; // use 'cache=0' to disable cache const payload = {account}; const bot = new TwitterBot({account}); const getTweets = promisify(bot.getTweets).bind(bot); const generateTweet = promisify(bot.generateTweet).bind(bot); // every request is a success! res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // conditionally cache the generated tweet if (shouldUseCache && markovChainCache.hasOwnProperty(account)) { payload.text = markovChainCache[account]; res.end(JSON.stringify(payload)); return; } try { // always cache the source tweets if (tweetsCache.hasOwnProperty(account)) { bot.arrayOfTweets = tweetsCache[account]; } else { bot.arrayOfTweets = tweetsCache[account] = await getTweets(); } const tweet = await generateTweet(); if (shouldUseCache) markovChainCache[account] = tweet; payload.text = tweet; res.end(JSON.stringify(payload)); } catch (err) { res.end(JSON.stringify(err)); } }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
e873e4d954ae4e565381d1759e26b20d85410e51
[ "JavaScript", "Markdown" ]
5
JavaScript
bc-jasond/twitter-markov-chain
a56daff8d3f7b65c98a7e3a4815f5ba3c1d20984
264fe46c1ac0da05107d7f12f19f0cd8eeb28ebd
refs/heads/master
<file_sep>About WorkWithDataURLs = It's a demo project in order to see how to convert an _Image_ to _Data URL_, and vice versa. Furthermore I tried to reduce the overhead (~30%) of _base64 encoding_, so I implemented GZIP compress/decompress functions too. Unfortunately it hasn't brought the expected results yet. Although the size reduction succeeded. Test results = | File | Original size | Data URL size | Overhead | Compressed Data URL size | Overhead | | :-------------- | ---------------: | --------------: | -------: | -----------------------: | -------: | | Koala.jpg | 780,831 bytes | 1,041,087 bytes | 33.33% | 785,325 bytes | 0.58% | | Penguins.jpg | 777,835 bytes | 1,037,095 bytes | 33.33% | 782,824 bytes | 0.64% | <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace WorkWithDataURLs { class Program { static readonly List<string> ImageExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".gif", ".bmp" }; [STAThreadAttribute] static void Main(string[] args) { try { string input = args[0]; string output = args[1]; bool isImage = ImageExtensions.Contains(Path.GetExtension(input).ToLowerInvariant()); bool compress = (args.Length > 2 && (args[2] == "/c" || args[2] == "/d")); if (isImage) ToDataURL(input, output, compress); else FromDataURL(input, output, compress); } catch (Exception e) { Console.WriteLine(e.Message); } } static void ToDataURL(string input, string output, bool compress) { Image image = Image.FromFile(input, true); string dataURL = ImageToDataURL(image); if (compress) File.WriteAllBytes(output, Compress(dataURL)); else File.WriteAllText(output, dataURL); System.Windows.Forms.Clipboard.SetText(dataURL); Console.WriteLine("Data URL's saved to file '{0}' and copied to clipboard.", output); } static void FromDataURL(string input, string output, bool compress) { string dataURL = compress ? Decompress(File.ReadAllBytes(input)) : File.ReadAllText(input); ImageCodecInfo codec; Image image = DataURLToImage(dataURL, out codec); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); Bitmap bmp = new Bitmap(image); bmp.Save(output, codec, encoderParams); Console.WriteLine("Image's saved to file '{0}'.", output); } #region Image <-> Base64 static Image Base64ToImage(string base64String) { byte[] imageBytes = Convert.FromBase64String(base64String); using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { ms.Write(imageBytes, 0, imageBytes.Length); return Image.FromStream(ms, true); } } static string ImageToBase64(Image image, ImageFormat format) { using (MemoryStream ms = new MemoryStream()) { image.Save(ms, format); byte[] imageBytes = ms.ToArray(); return Convert.ToBase64String(imageBytes); } } #endregion #region Image <-> Data URL static ImageCodecInfo MimeTypeToImageCodecInfo(string mimeType) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) if (encoders[j].MimeType == mimeType) return encoders[j]; return null; } static Image DataURLToImage(string dataURL, out ImageCodecInfo codec) { Match match = Regex.Match(dataURL, @"data:(.+);base64,(.+)"); string mimeType = match.Groups[1].ToString(); codec = MimeTypeToImageCodecInfo(mimeType); string base64String = match.Groups[2].ToString(); return Base64ToImage(base64String); } static string ImageToDataURL(Image image) { ImageFormat format = image.RawFormat; ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == format.Guid); string mimeType = codec.MimeType; string base64String = ImageToBase64(image, format); return String.Format(@"data:{0};base64,{1}", mimeType, base64String); } #endregion #region (De)compress static byte[] Compress(string data) { using (var msi = new MemoryStream(Encoding.UTF8.GetBytes(data))) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(mso, CompressionMode.Compress)) msi.CopyTo(gs); return mso.ToArray(); } } static string Decompress(byte[] data) { using (var msi = new MemoryStream(data)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) gs.CopyTo(mso); return Encoding.UTF8.GetString(mso.ToArray()); } } #endregion } }
96fa3ba6acd2e99ec743c813d98c158a39ce08c7
[ "Markdown", "C#" ]
2
Markdown
rolandrajko/WorkWithDataURLs
a341e40236587df872f8d686febe30a601584217
23eee6220e1d4760c11e92448059e32a6d962b3f
refs/heads/master
<repo_name>deaackben/MoneyExchanger<file_sep>/src/test/java/com/example/demo/Log4jTest.java package com.example.demo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4jTest { public static Logger logger = LogManager.getLogger(Log4jTest.class); } <file_sep>/src/test/java/com/example/demo/DemoApplicationTests.java package com.example.demo; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; @SpringBootTest public class DemoApplicationTests { @BeforeClass public static void setUpTests() { System.setProperty("log4j.xml","src/test/log4j.xml"); } @Before public void testThirdPartyAPI() throws IOException { String url = PropertyReader.getProperty(Controller.getAPI()); System.out.println("Third party API: " + url); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); Assert.assertNotNull(con); } @Test public void contextLoads() throws IOException { try { String url = PropertyReader.getProperty(Controller.getAPI()); System.out.println(url); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); Assert.assertNotNull(con); Log4jTest.logger.info("Test passed"); } catch (IOException e) { Log4jTest.logger.error("Test failed"); e.printStackTrace(); } } @Test public void get200() throws IOException { String url = "http://localhost:8080/"; System.out.println(url); SpringApplication.run(DemoApplication.class); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); int responseCode = con.getResponseCode(); Assert.assertEquals(responseCode, 200); Assert.assertNotNull(con); } } <file_sep>/src/main/java/com/example/demo/Record.java package com.example.demo; import java.io.Serializable; public class Record implements Serializable { String bank; String date; String currency; float sell; float buy; public String getBank() { return bank; } public void setBank(String bank) { this.bank = bank; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public float getSell() { return sell; } public void setSell(Float sell) { this.sell = sell; } public float getBuy() { return buy; } public void setBuy(float buy) { this.buy = buy; } }
e0f2c8b9e7f06fd42c798cbf22a12f22f507c8fd
[ "Java" ]
3
Java
deaackben/MoneyExchanger
1817f11ad2e85923748695b39e500c30b2759be0
be541518d2c9f48b432b7babb22ea469dc91ea9e
refs/heads/master
<repo_name>IamBc/PerlJournal<file_sep>/install.sh echo 'Creating directory...'; eval 'sudo mkdir /opt/prnl/'; echo 'Creating log...'; eval 'sudo touch /opt/prnl/log.txt'; echo 'Installing modules...'; eval 'sudo cp PerlJournal.pm /opt/prnl/PerlJournal.pm'; echo 'Installing scripts...'; eval 'sudo cp perl-journal.pl /opt/prnl/perl-journal.pl'; echo 'Creating alias'; echo 'alias prnl="perl /opt/prnl/perl-journal.pl"' >> ~/.bashrc; echo 'Done'; <file_sep>/README.md PerlJournal =========== Small perl based journal / logger. <h1>Installation</h1> use "install.sh" to install <h1>List of commands:</h1> <h2>add</h2> <p>Creates a new entry in the journal.</p> <p> Sample usage: <br/> add 'Today I learned how to bake cake'<br/> add Today I learned how to bake cake<br/> <b>Note:</b> If you chose the second approach, additional spaces will be ignored. I recommend using the first one. </p> <h2>get</h2> <p>Lists all lines where one of the keywords / substrings is found</p> <p> Sample usage: <br/> get Alice<br/> add <NAME><br/> <b>Note:</b> It will print all entries where either one of them is written.</b> </p> <h2>getn</h2> <p>Lists all lines where all of the keywords / substrings are found</p> <p> Sample usage: <br/> get Alice<br/> add <NAME><br/> </p> <h2>rmv</h2> <p>Removes all lines where all of the keywords / substrings are found</p> <p> Sample usage: <br/> get Alice<br/> add <NAME><br/> <b>Note:</b> Can't be undone.</b> </p> <h2>rmvn</h2> <p>Removes all lines where all of the keywords / substrings are found</p> <p> Sample usage: <br/> get Alice<br/> add <NAME><br/> <b>Note:</b> Can't be undone.</b> </p> <h2>list</h2> <p>Lists all words starting with @</p> <p> Sample usage: <br/> list <br/> </p> <p> Consider all the words starting with @ Special in the sense that you can retrieve them at any point, so I highly recommend that all entries contain at least one word starting with @. This will ease searching for information about specific topics. </p> <h1>Additional information </h1> <p>An Alias is created which is prnl, so when you want to use the journal simply use:<br/> prnl <command> <arguments> <br/> Note: You have to restart your terminal or reload the bashrc in order for the alias to appear. </p> <p> Every entry starts with a timestamp in miliseconds. </p>
b16b2e04eeaf31f52d1852fb2e4645779b9bb335
[ "Markdown", "Shell" ]
2
Shell
IamBc/PerlJournal
759b6de7670aeddfcfe92f6b346acd745824dde4
31e50fbc4777b7af285ba951ad1f7b8e4da905b2
refs/heads/master
<file_sep>#include <time.h> #include <systemc.h> #include "router.h" #include "pe.h" int clk_cycle = 1; SC_MODULE(top) { public: enum {N = 3}; //horizontally enum {M = 3}; //vertically router *routers[N][M]; //REVISED BY LLK PE_base *pes[N][M]; //REVISED BY LLK sc_signal<packet> router_to_pe[N][M], pe_to_router[N][M]; sc_signal<packet> router_to_router_east[N][M-1], router_to_router_west[N][M-1]; sc_signal<packet> router_to_router_north[N-1][M], router_to_router_south[N-1][M]; sc_signal<packet> terminal_loop_east[N], terminal_loop_west[N]; sc_signal<packet> terminal_loop_north[M], terminal_loop_south[M]; sc_signal<bool> clock; SC_CTOR(top) { create_pes(); create_network(); } protected: void create_pes() { pes[1][0] = new PE_P1("P1"); pes[1][0]->clock(clock); pes[1][0]->set_xy(0, 1); pes[1][2] = new PE_P2("P2"); pes[1][2]->clock(clock); pes[1][2]->set_xy(2, 1); pes[0][0] = new PE_P3("P3"); pes[0][0]->clock(clock); pes[0][0]->set_xy(0, 0); pes[2][2] = new PE_P4("P4"); pes[2][2]->clock(clock); pes[2][2]->set_xy(2, 2); pes[0][1] = new PE_P5("P5"); pes[0][1]->clock(clock); pes[0][1]->set_xy(1, 0); pes[2][1] = new PE_P6("P6"); pes[2][1]->clock(clock); pes[2][1]->set_xy(1, 2); pes[0][2] = new PE_P7("P7"); pes[0][2]->clock(clock); pes[0][2]->set_xy(2, 0); pes[2][0] = new PE_P8("P8"); pes[2][0]->clock(clock); pes[2][0]->set_xy(0, 2); pes[1][1] = new PE_IO("PI/PO"); pes[1][1]->clock(clock); pes[1][1]->set_xy(1, 1); } void create_network() { for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { char name[100]; sprintf(name, "router(%d,%d)", i,j); // create router routers[j][i] = new router(name); routers[j][i]->set_xy(i,j); routers[j][i]->clock(clock); if(j!=0) // connect router->north routers { routers[j][i]->port_out[router::NORTH]( router_to_router_north[j-1][i]); routers[j][i]->port_in[router::NORTH]( router_to_router_south[j-1][i]); } else //or make a loop { routers[j][i]->port_out[router::NORTH]( terminal_loop_north[i]); routers[j][i]->port_in[router::NORTH]( terminal_loop_north[i]); } if(j !=N-1) // connect router->south routers { routers[j][i]->port_out[router::SOUTH]( router_to_router_south[j][i]); routers[j][i]->port_in[router::SOUTH]( router_to_router_north[j][i]); } else // or make a loop { routers[j][i]->port_out[router::SOUTH]( terminal_loop_south[i]); routers[j][i]->port_in[router::SOUTH]( terminal_loop_south[i]); } // connect router->west routers if (i != 0) { routers[j][i]->port_out[router::WEST]( router_to_router_west[j][i-1]); routers[j][i]->port_in[router::WEST]( router_to_router_east[j][i-1]); } else // or make a loop { routers[j][i]->port_out[router::WEST]( terminal_loop_west[j]); routers[j][i]->port_in[router::WEST]( terminal_loop_west[j]); } if (i != M-1) // connect router->east routers { routers[j][i]->port_out[router::EAST]( router_to_router_east[j][i]); routers[j][i]->port_in[router::EAST]( router_to_router_west[j][i]); } else // or make a loop { routers[j][i]->port_out[router::EAST]( terminal_loop_east[j]); routers[j][i]->port_in[router::EAST]( terminal_loop_east[j]); } // connect router->PE routers[j][i]->port_out[router::PE](router_to_pe[j][i]); routers[j][i]->port_in[router::PE](pe_to_router[j][i]); pes[j][i]->data_in(router_to_pe[j][i]); pes[j][i]->data_out(pe_to_router[j][i]); } } } }; // top int sc_main(int argc , char *argv[]) { srand(0); top top_module("top"); printf("cycle 0 ================================\n"); sc_start(0, SC_NS); for(; clk_cycle < 500; clk_cycle++){ printf("cycle %2d ================================\n", clk_cycle); top_module.clock.write(1); sc_start(10, SC_NS); top_module.clock.write(0); sc_start(10, SC_NS); } extern int round_cycle; //printf("The minimum computation latency is %d.\n",round_cycle); extern int PE00_R,PE10_R,PE20_R,PE01_R,PE11_R,PE21_R,PE02_R,PE12_R,PE22_R; printf("The queue size from pe(1,1) to router(1,1) is %d.\n",PE11_R); printf("The queue size from pe(1,0) to router(1,0) is %d.\n",PE10_R); printf("The queue size from pe(2,1) to router(2,1) is %d.\n",PE21_R); printf("The queue size from pe(1,2) to router(1,2) is %d.\n",PE12_R); printf("The queue size from pe(0,1) to router(0,1) is %d.\n",PE01_R); printf("The queue size from pe(2,0) to router(2,0) is %d.\n",PE20_R); printf("The queue size from pe(0,2) to router(0,2) is %d.\n",PE02_R); printf("The queue size from pe(2,2) to router(2,2) is %d.\n",PE22_R); printf("The queue size from pe(0,0) to router(0,0) is %d.\n",PE00_R); extern int R00_PE,R00_East,R00_South; extern int R01_North,R01_East,R01_South,R01_PE; extern int R02_North,R02_East,R02_PE; extern int R10_West,R10_PE,R10_East,R10_South; extern int R11_North,R11_East,R11_South,R11_West,R11_PE; extern int R12_North,R12_East,R12_West,R12_PE; extern int R20_West,R20_South,R20_PE; extern int R21_North,R21_South,R21_West,R21_PE; extern int R22_North,R22_West,R22_PE; printf("The queue size from router(0,0) to router(1,0) is %d.\n",R00_East); printf("The queue size from router(0,0) to router(0,1) is %d.\n",R00_South); printf("The queue size from router(0,0) to pe(0,0) is %d.\n",R00_PE); printf("The queue size from router(1,0) to router(2,0) is %d.\n",R10_East); printf("The queue size from router(1,0) to router(1,1) is %d.\n",R10_South); printf("The queue size from router(1,0) to router(0,0) is %d.\n",R10_West); printf("The queue size from router(1,0) to pe(1,0) is %d.\n",R10_PE); printf("The queue size from router(2,0) to router(2,1) is %d.\n",R20_South); printf("The queue size from router(2,0) to router(1,0) is %d.\n",R20_West); printf("The queue size from router(2,0) to pe(2,0) is %d.\n",R20_PE); printf("The queue size from router(0,1) to router(0,0) is %d.\n",R01_North); printf("The queue size from router(0,1) to router(0,2) is %d.\n",R01_South); printf("The queue size from router(0,1) to router(1,1) is %d.\n",R01_East); printf("The queue size from router(0,1) to pe(0,1) is %d.\n",R01_PE); printf("The queue size from router(1,1) to router(0,1) is %d.\n",R11_West); printf("The queue size from router(1,1) to router(1,0) is %d.\n",R11_North); printf("The queue size from router(1,1) to router(2,1) is %d.\n",R11_East); printf("The queue size from router(1,1) to router(1,2) is %d.\n",R11_South); printf("The queue size from router(1,1) to pe(1,1) is %d.\n",R11_PE); printf("The queue size from router(2,1) to router(1,1) is %d.\n",R21_West); printf("The queue size from router(2,1) to router(2,0) is %d.\n",R21_North); printf("The queue size from router(2,1) to router(2,2) is %d.\n",R21_South); printf("The queue size from router(2,1) to pe(2,1) is %d.\n",R21_PE); printf("The queue size from router(0,2) to router(0,1) is %d.\n",R02_North); printf("The queue size from router(0,2) to router(1,2) is %d.\n",R02_East); printf("The queue size from router(0,2) to pe(0,2) is %d.\n",R02_PE); printf("The queue size from router(1,2) to router(1,1) is %d.\n",R12_North); printf("The queue size from router(1,2) to router(0,2) is %d.\n",R12_West); printf("The queue size from router(1,2) to router(2,2) is %d.\n",R12_East); printf("The queue size from router(1,2) to pe(1,2) is %d.\n",R12_PE); printf("The queue size from router(2,2) to router(1,2) is %d.\n",R22_West); printf("The queue size from router(2,2) to router(2,1) is %d.\n",R22_North); printf("The queue size from router(2,2) to pe(2,2) is %d.\n",R22_PE); extern int pofire; extern int clk_in; extern int clk_out; return 0; } <file_sep>#include "router.h" int R00_PE=0,R00_East=0,R00_South=0; int R10_West=0,R10_PE=0,R10_East=0,R10_South=0; int R20_West=0,R20_South=0,R20_PE=0; int R01_North=0,R01_East=0,R01_South=0,R01_PE=0; int R11_North=0,R11_East=0,R11_South=0,R11_West=0,R11_PE=0; int R21_North=0,R21_South=0,R21_West=0,R21_PE=0; int R02_North=0,R02_East=0,R02_PE=0; int R12_North=0,R12_East=0,R12_West=0,R12_PE=0; int R22_North=0,R22_West=0,R22_PE=0; std::ostream &operator<<(std::ostream &o, const packet &p) { char buf[100]; sprintf(buf, "(%d,%d)->(%d,%d)", p.src_x, p.src_y, p.dest_x, p.dest_y); return o << buf << ", " << p.token.real<<p.token.imag; } void sc_trace(sc_trace_file *tf, const packet &p, const std::string &name) { sc_trace(tf, p.src_x, name+".src.x"); sc_trace(tf, p.src_y, name+".src.y"); sc_trace(tf, p.dest_x, name+".dest.x"); sc_trace(tf, p.dest_y, name+".dest.y"); sc_trace(tf, p.token.real, name+".token.real"); sc_trace(tf, p.token.imag, name+".token.imag"); } void router::main() { assert((x_ != -1) && (y_ != -1)); // to identify _PE for (int iport = 0; iport < PORTS; ++iport) read_packet(iport); for (int iport = 0; iport < PORTS; ++iport) write_packet(iport); } void router::set_xy(int x, int y) { assert((x_ == -1) && (y_ == -1)); // set once only assert((x != -1) && (y != -1)); // must use a legal location x_ = x; y_ = y; } void router::read_packet(int iport) { assert(iport < PORTS); packet p = port_in[iport].read(); if ((p.src_x == -1) && (p.src_y == -1)) return; // empty packet route_packet_xy(p); } void router::write_packet(int iport) { assert(iport < PORTS); if (out_queue_[iport].empty()) { port_out[iport].write(packet()); // write an empty packet } else { port_out[iport].write(out_queue_[iport].front()); out_queue_[iport].pop_front(); } } void router::route_packet_xy(packet p) { if ((p.dest_x == -1) || (p.dest_y == -1)) { printf("router (%d,%d): drop packet with invalid destination" " (%d,%d)->(%d,%d)\n", p.src_x, p.src_y, p.dest_x, p.dest_y); return; } if ((p.dest_x == x_) && (p.dest_y ==y_)) // to _PE { out_queue_[PE].push_back(p); if(x_==0&&y_==0&&R00_PE<(int)out_queue_[PE].size()) R00_PE=(int)out_queue_[PE].size(); if(x_==1&&y_==0&&R10_PE<(int)out_queue_[PE].size()) R10_PE=(int)out_queue_[PE].size(); if(x_==2&&y_==0&&R20_PE<(int)out_queue_[PE].size()) R20_PE=(int)out_queue_[PE].size(); if(x_==0&&y_==1&&R01_PE<(int)out_queue_[PE].size()) R01_PE=(int)out_queue_[PE].size(); if(x_==1&&y_==1&&R11_PE<(int)out_queue_[PE].size()) R11_PE=(int)out_queue_[PE].size(); if(x_==2&&y_==1&&R21_PE<(int)out_queue_[PE].size()) R21_PE=(int)out_queue_[PE].size(); if(x_==0&&y_==2&&R02_PE<(int)out_queue_[PE].size()) R02_PE=(int)out_queue_[PE].size(); if(x_==1&&y_==2&&R12_PE<(int)out_queue_[PE].size()) R12_PE=(int)out_queue_[PE].size(); if(x_==2&&y_==2&&R22_PE<(int)out_queue_[PE].size()) R22_PE=(int)out_queue_[PE].size(); } if (p.dest_x > x_) // right to EAST { out_queue_[EAST].push_back(p); if(x_==0&&y_==0&&R00_East<(int)out_queue_[EAST].size()) R00_East=(int)out_queue_[EAST].size(); if(x_==0&&y_==1&&R01_East<(int)out_queue_[EAST].size()) R01_East=(int)out_queue_[EAST].size(); if(x_==0&&y_==2&&R02_East<(int)out_queue_[EAST].size()) R02_East=(int)out_queue_[EAST].size(); if(x_==1&&y_==0&&R10_East<(int)out_queue_[EAST].size()) R10_East=(int)out_queue_[EAST].size(); if(x_==1&&y_==1&&R11_East<(int)out_queue_[EAST].size()) R11_East=(int)out_queue_[EAST].size(); if(x_==1&&y_==2&&R12_East<(int)out_queue_[EAST].size()) R12_East=(int)out_queue_[EAST].size(); } else if (p.dest_y > y_) // down to SOUTH { out_queue_[SOUTH].push_back(p); if(x_==0&&y_==0&&R00_South<(int)out_queue_[SOUTH].size()) R00_South=(int)out_queue_[SOUTH].size(); if(x_==1&&y_==0&&R10_South<(int)out_queue_[SOUTH].size()) R10_South=(int)out_queue_[SOUTH].size(); if(x_==2&&y_==0&&R20_South<(int)out_queue_[SOUTH].size()) R20_South=(int)out_queue_[SOUTH].size(); if(x_==0&&y_==1&&R01_South<(int)out_queue_[SOUTH].size()) R01_South=(int)out_queue_[SOUTH].size(); if(x_==1&&y_==1&&R11_South<(int)out_queue_[SOUTH].size()) R11_South=(int)out_queue_[SOUTH].size(); if(x_==2&&y_==1&&R21_South<(int)out_queue_[SOUTH].size()) R21_South=(int)out_queue_[SOUTH].size(); } else if (p.dest_x < x_) // left to WEST { out_queue_[WEST].push_back(p); if(x_==1&&y_==0&&R10_West<(int)out_queue_[WEST].size()) R10_West=(int)out_queue_[WEST].size(); if(x_==1&&y_==1&&R11_West<(int)out_queue_[WEST].size()) R11_West=(int)out_queue_[WEST].size(); if(x_==1&&y_==2&&R12_West<(int)out_queue_[WEST].size()) R12_West=(int)out_queue_[WEST].size(); if(x_==2&&y_==0&&R20_West<(int)out_queue_[WEST].size()) R20_West=(int)out_queue_[WEST].size(); if(x_==2&&y_==1&&R21_West<(int)out_queue_[WEST].size()) R21_West=(int)out_queue_[WEST].size(); if(x_==2&&y_==2&&R22_West<(int)out_queue_[WEST].size()) R22_West=(int)out_queue_[WEST].size(); } else if (p.dest_y < y_) // up to NORTH { out_queue_[NORTH].push_back(p); if(x_==0&&y_==1&&R01_North<(int)out_queue_[NORTH].size()) R01_North=(int)out_queue_[NORTH].size(); if(x_==1&&y_==1&&R11_North<(int)out_queue_[NORTH].size()) R11_North=(int)out_queue_[NORTH].size(); if(x_==2&&y_==1&&R21_North<(int)out_queue_[NORTH].size()) R21_North=(int)out_queue_[NORTH].size(); if(x_==0&&y_==2&&R02_North<(int)out_queue_[NORTH].size()) R02_North=(int)out_queue_[NORTH].size(); if(x_==1&&y_==2&&R12_North<(int)out_queue_[NORTH].size()) R12_North=(int)out_queue_[NORTH].size(); if(x_==2&&y_==2&&R22_North<(int)out_queue_[NORTH].size()) R22_North=(int)out_queue_[NORTH].size(); } } <file_sep>#include "pe.h" #include <math.h> extern int clk_cycle; token_type x0in,x1in,x2in,x3in,x4in,x5in,x6in,x7in, y0in,y1in,y2in,y3in,y4in,y5in,y6in,y7in, y0out,y1out,y2out,y3out,y4out,y5out,y6out,y7out, z0in,z1in,z2in,z3in,z4in,z5in,z6in,z7in, z0out,z1out,z2out,z3out,z4out,z5out,z6out,z7out, X0in,X1in,X2in,X3in,X4in,X5in,X6in,X7in, X0out,X1out,X2out,X3out,X4out,X5out,X6out,X7out; struct wstruct w1,w2,w3; int pifire=1,pofire=0; int round_cycle=-1; int clk_in=0; int clk_out=0; int PE00_R=0,PE10_R=0,PE20_R=0,PE01_R=0,PE11_R=0,PE21_R=0,PE02_R=0,PE12_R=0,PE22_R=0; void PE_base::set_xy(int x, int y) { assert((x_ == -1) && (y_ == -1)); // set once only assert((x != -1) && (y != -1)); // must use a legal location x_ = x; y_ = y; w1.w_real=sqrt(2.0000)/2.0000; w1.w_imag=-sqrt(2.0000)/2.0000; w2.w_real=0.0000; w2.w_imag=-1.0000; w3.w_real=-sqrt(2.0000)/2.0000; w3.w_imag=-sqrt(2.0000)/2.0000; } void PE_base::read_input() { packet_in_ = data_in.read(); } void PE_base::write_output() { if (out_queue_.empty()) { data_out.write(packet()); } else { data_out.write(out_queue_.front()); out_queue_.pop_front(); } } void PE_IO::execute() { //if(pifire<=1) //fire_PI(); int r = rand()%100; if (r < 11) fire_PI(); // fire PO if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire_PO(); } void PE_IO::fire_PI() { token_type x0,x1,x2,x3,x4,x5,x6,x7; x0.real=(rand()%10000)/10000.0000; x0.imag=(rand()%10000)/10000.0000; x1.real=(rand()%10000)/10000.0000; x1.imag=(rand()%10000)/10000.0000; x2.real=(rand()%10000)/10000.0000; x2.imag=(rand()%10000)/10000.0000; x3.real=(rand()%10000)/10000.0000; x3.imag=(rand()%10000)/10000.0000; x4.real=(rand()%10000)/10000.0000; x4.imag=(rand()%10000)/10000.0000; x5.real=(rand()%10000)/10000.0000; x5.imag=(rand()%10000)/10000.0000; x6.real=(rand()%10000)/10000.0000; x6.imag=(rand()%10000)/10000.0000; x7.real=(rand()%10000)/10000.0000; x7.imag=(rand()%10000)/10000.0000; packet p0(x_, y_, 1, 0,pifire, "x0",x0); printf("Round %d:PI: send x0 %.4f+%.4fi to (%d,%d)\n", pifire,x0.real,x0.imag, p0.dest_x, p0.dest_y); packet p1(x_, y_, 1, 2,pifire, "x1",x1); printf("Round %d:PI: send x1 %.4f+%.4fi to (%d,%d)\n", pifire,x1.real,x1.imag, p1.dest_x, p1.dest_y); packet p2(x_, y_, 2, 1, pifire,"x2",x2); printf("Round %d:PI: send x2 %.4f+%.4fi to (%d,%d)\n", pifire,x2.real,x2.imag, p2.dest_x, p2.dest_y); packet p3(x_, y_, 0, 1,pifire,"x3", x3); printf("Round %d:PI: send x3 %.4f+%.4fi to (%d,%d)\n", pifire,x3.real,x3.imag, p3.dest_x, p3.dest_y); packet p4(x_, y_, 1, 0,pifire, "x4",x4); printf("Round %d:PI: send x4 %.4f+%.4fi to (%d,%d)\n", pifire,x4.real,x4.imag, p4.dest_x, p4.dest_y); packet p5(x_, y_, 1, 2,pifire,"x5", x5); printf("Round %d:PI: send x5 %.4f+%.4fi to (%d,%d)\n", pifire,x5.real,x5.imag, p5.dest_x, p5.dest_y); packet p6(x_, y_, 2, 1,pifire, "x6",x6); printf("Round %d:PI: send x6 %.4f+%.4fi to (%d,%d)\n", pifire,x6.real,x6.imag, p6.dest_x, p6.dest_y); packet p7(x_, y_, 0, 1,pifire, "x7",x7); printf("Round %d:PI: send x7 %.4f+%.4fi to (%d,%d)\n", pifire,x7.real,x7.imag, p7.dest_x, p7.dest_y); out_queue_.push_back(p0); out_queue_.push_back(p1); //++r11_south; out_queue_.push_back(p2); //++r11_east; out_queue_.push_back(p3); //++r11_west; out_queue_.push_back(p4); //++r11_north; out_queue_.push_back(p5); //++r11_south; out_queue_.push_back(p6); //++r11_east; out_queue_.push_back(p7); //++r11_west; if(pifire<529) clk_in=clk_in+clk_cycle; if(PE11_R<(int)out_queue_.size()) PE11_R=(int)out_queue_.size(); pifire++; } void PE_IO::fire_PO() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); //pofire=poc/8+1; printf("Round %d:PO: receive %s = %.4f+%.4fi from (%d,%d)\n", packet_in_.round,packet_in_.content,packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x,packet_in_.src_y); if(packet_in_.content=="X(7)") { pofire++; //round_cycle=clk_cycle; clk_out=clk_out+clk_cycle; } } void PE_P5::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P5::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); //token_type x0in,x4in,y0out,y1out; if(packet_in_.content=="x0") { printf("P5(%d,%d): receive x0 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); x0in.real=packet_in_.token.real; x0in.imag=packet_in_.token.imag; } if(packet_in_.content=="x4") { x4in.real=packet_in_.token.real; x4in.imag=packet_in_.token.imag; printf("P5(%d,%d): receive x4 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y0out.real=x0in.real+x4in.real; y0out.imag=x0in.imag+x4in.imag; y1out.real=x0in.real-x4in.real; y1out.imag=x0in.imag-x4in.imag; packet py0(x_, y_, 0, 0,packet_in_.round, "y0",y0out); printf("P5 send y0=%.4f+%.4fi to (%d,%d)\n", py0.token.real,py0.token.imag, 0, 0); out_queue_.push_back(py0); packet py1(x_, y_, 2, 0,packet_in_.round,"y1", y1out); printf("P5 send y1=%.4f+%.4fi to (%d,%d)\n", py1.token.real,py1.token.imag, 2, 0); out_queue_.push_back(py1); if(PE10_R<(int)out_queue_.size()) PE10_R=(int)out_queue_.size(); } if(packet_in_.content=="z1") { printf("P3(%d,%d): receive z1 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z1in.real=packet_in_.token.real; z1in.imag=packet_in_.token.imag; } if(packet_in_.content=="z5") { printf("P7 (%d,%d): receive z5 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z5in.real=packet_in_.token.real; z5in.imag=packet_in_.token.imag; X2out.real=z1in.real+z5in.imag; X2out.imag=z1in.imag-z5in.real; X6out.real=z1in.real-z5in.imag; X6out.imag=z1in.imag+z5in.real; packet pX2(x_, y_, 1, 1,packet_in_.round, "X(2)",X2out); printf("P5 send X2=%.4f+%.4fi to (%d,%d)\n", pX2.token.real,pX2.token.imag, 1, 1); out_queue_.push_back(pX2); packet pX6(x_, y_, 1, 1,packet_in_.round,"X(6)", X6out); printf("P5 send X6=%.4f+%.4fi to (%d,%d)\n", pX6.token.real,pX6.token.imag, 1, 1); out_queue_.push_back(pX6); if(PE10_R<(int)out_queue_.size()) PE10_R=(int)out_queue_.size(); } } void PE_P2::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P2::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="x2") { x2in.real=packet_in_.token.real; x2in.imag=packet_in_.token.imag; printf("P2(%d,%d): receive x2 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); } if(packet_in_.content=="x6") { x6in.real=packet_in_.token.real; x6in.imag=packet_in_.token.imag; printf("P2(%d,%d): receive x6 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); printf("x2=%.4f+%.4fi,x6=%.4f+%.4fi\n",x2in.real,x2in.imag,x6in.real,x6in.imag); y2out.real=x2in.real+x6in.real; y2out.imag=x2in.imag+x6in.imag; y3out.real=x2in.real-x6in.real; y3out.imag=x2in.imag-x6in.imag; printf("y2=%.4f+%.4fi,y3=%.4f+%.4fi\n",y2out.real,y2out.imag,y3out.real,y3out.imag); packet py2(x_, y_, 0, 0, packet_in_.round,"y2",y2out); printf("P2 send y2=%.4f+%.4fi to (%d,%d)\n", py2.token.real,py2.token.imag, 0, 0); out_queue_.push_back(py2); packet py3(x_, y_, 2, 0, packet_in_.round,"y3",y3out); printf("P2 send y3=%.4f+%.4fi to (%d,%d)\n", py3.token.real,py3.token.imag, 2, 0); out_queue_.push_back(py3); if(PE21_R<(int)out_queue_.size()) PE21_R=(int)out_queue_.size(); } if(packet_in_.content=="z2") { printf("P2(%d,%d): receive z2 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z2in.real=packet_in_.token.real; z2in.imag=packet_in_.token.imag; } if(packet_in_.content=="z6") { z6in.real=packet_in_.token.real; z6in.imag=packet_in_.token.imag; printf("P2(%d,%d): receive z6 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); X1out.real=z2in.real+(z6in.real*w1.w_real-z6in.imag*w1.w_imag); X1out.imag=z2in.imag+(z6in.real*w1.w_imag+z6in.imag*w1.w_real); X5out.real=z2in.real-(z6in.real*w1.w_real-z6in.imag*w1.w_imag); X5out.imag=z2in.imag-(z6in.real*w1.w_imag+z6in.imag*w1.w_real); packet pX1(x_, y_, 1, 1,packet_in_.round, "X(1)",X1out); printf("P2 send X1=%.4f+%.4fi to (%d,%d)\n", pX1.token.real,pX1.token.imag, 1, 1); out_queue_.push_back(pX1); packet pX5(x_, y_, 1, 1,packet_in_.round, "X(5)",X5out); printf("P2 send X5=%.4f+%.4fi to (%d,%d)\n", pX5.token.real,pX5.token.imag, 1, 1); out_queue_.push_back(pX5); if(PE21_R<(int)out_queue_.size()) PE21_R=(int)out_queue_.size(); } } void PE_P6::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P6::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="x1") { printf("P6(%d,%d): receive x1 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); x1in.real=packet_in_.token.real; x1in.imag=packet_in_.token.imag; } if(packet_in_.content=="x5") { x5in.real=packet_in_.token.real; x5in.imag=packet_in_.token.imag; printf("P6(%d,%d): receive x5 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); printf("x1=%.4f+%.4fi,x5=%.4f+%.4fi\n",x1in.real,x1in.imag,x5in.real,x5in.imag); y4out.real=x1in.real+x5in.real; y4out.imag=x1in.imag+x5in.imag; y5out.real=x1in.real-x5in.real; y5out.imag=x1in.imag-x5in.imag; packet py4(x_, y_, 0, 2,packet_in_.round, "y4",y4out); printf("P6 send y4=%.4f+%.4fi to (%d,%d)\n", py4.token.real,py4.token.imag, 0, 2); out_queue_.push_back(py4); packet py5(x_, y_, 2, 2,packet_in_.round,"y5", y5out); printf("P6 send y5=%.4f+%.4fi to (%d,%d)\n", py5.token.real,py5.token.imag, 2, 2); out_queue_.push_back(py5); if(PE12_R<(int)out_queue_.size()) PE12_R=(int)out_queue_.size(); } if(packet_in_.content=="z3") { printf("P6(%d,%d): receive z3 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z3in.real=packet_in_.token.real; z3in.imag=packet_in_.token.imag; } if(packet_in_.content=="z7") { z7in.real=packet_in_.token.real; z7in.imag=packet_in_.token.imag; printf("P6(%d,%d): receive z7 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); X3out.real=z3in.real+(z7in.real*w3.w_real-z7in.imag*w3.w_imag); X3out.imag=z3in.imag+(z7in.real*w3.w_imag+z7in.imag*w3.w_real); X7out.real=z3in.real-(z7in.real*w3.w_real-z7in.imag*w3.w_imag); X7out.imag=z3in.imag-(z7in.real*w3.w_imag+z7in.imag*w3.w_real); packet pX3(x_, y_, 1, 1,packet_in_.round,"X(3)", X3out); printf("P6 send x3=%.4f+%.4fi to (%d,%d)\n", pX3.token.real,pX3.token.imag, 1, 1); out_queue_.push_back(pX3); packet pX7(x_, y_, 1, 1,packet_in_.round, "X(7)",X7out); printf("P6 send x7=%.4f+%.4fi to (%d,%d)\n", pX7.token.real,pX7.token.imag, 1, 1); out_queue_.push_back(pX7); if(PE12_R<(int)out_queue_.size()) PE12_R=(int)out_queue_.size(); } } void PE_P1::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P1::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="x3") { printf("P1(%d,%d): receive x3 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); x3in.real=packet_in_.token.real; x3in.imag=packet_in_.token.imag; } if(packet_in_.content=="x7") { x7in.real=packet_in_.token.real; x7in.imag=packet_in_.token.imag; printf("P1(%d,%d): receive x7 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y6out.real=x3in.real+x7in.real; y6out.imag=x3in.imag+x7in.imag; y7out.real=x3in.real-x7in.real; y7out.imag=x3in.imag-x7in.imag; packet py6(x_, y_, 0, 2, packet_in_.round,"y6",y6out); printf("P1 send y6=%.4f+%.4fi to (%d,%d)\n", py6.token.real,py6.token.imag, 0, 2); out_queue_.push_back(py6); packet py7(x_, y_, 2, 2,packet_in_.round,"y7", y7out); printf("P1 send y7=%.4f+%.4fi to (%d,%d)\n", py7.token.real,py7.token.imag, 2, 2); out_queue_.push_back(py7); if(PE01_R<(int)out_queue_.size()) PE01_R=(int)out_queue_.size(); } if(packet_in_.content=="z0") { printf("P1(%d,%d): receive z0 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z0in.real=packet_in_.token.real; z0in.imag=packet_in_.token.imag; } if(packet_in_.content=="z4") { printf("P1(%d,%d): receive z4 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z4in.real=packet_in_.token.real; z4in.imag=packet_in_.token.imag; X0out.real=z0in.real+z4in.real; X0out.imag=z0in.imag+z4in.imag; X4out.real=z0in.real-z4in.real; X4out.imag=z0in.imag-z4in.imag; packet pX0(x_, y_, 1, 1,packet_in_.round,"X(0)", X0out); printf("P1 send X0=%.4f+%.4fi to (%d,%d)\n", pX0.token.real,pX0.token.imag, 1, 1); out_queue_.push_back(pX0); packet pX4(x_, y_, 1, 1,packet_in_.round, "X(4)",X4out); printf("P1 send X4=%.4f+%.4fi to (%d,%d)\n", pX4.token.real,pX4.token.imag, 1, 1); out_queue_.push_back(pX4); if(PE01_R<(int)out_queue_.size()) PE01_R=(int)out_queue_.size(); } } void PE_P7::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P7::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="y1") { printf("P7(%d,%d): receive y1 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y1in.real=packet_in_.token.real; y1in.imag=packet_in_.token.imag; } if(packet_in_.content=="y3") { y3in.real=packet_in_.token.real; y3in.imag=packet_in_.token.imag; printf("P7(%d,%d): receive y3 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z2out.real=y1in.real+y3in.imag; z2out.imag=y1in.imag-y3in.real; z3out.real=y1in.real-y3in.imag; z3out.imag=y1in.imag+y3in.real; packet pz2(x_, y_, 2, 1,packet_in_.round, "z2",z2out); printf("P7 send z2=%.4f+%.4fi to (%d,%d)\n", pz2.token.real,pz2.token.imag, 2, 1); out_queue_.push_back(pz2); packet pz3(x_, y_, 1, 2,packet_in_.round, "z3",z3out); printf("P7 send z3=%.4f+%.4fi to (%d,%d)\n", pz3.token.real,pz3.token.imag, 1, 2); out_queue_.push_back(pz3); if(PE20_R<(int)out_queue_.size()) PE20_R=(int)out_queue_.size(); } } void PE_P8::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P8::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="y4") { printf("P8(%d,%d): receive y4 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y4in.real=packet_in_.token.real; y4in.imag=packet_in_.token.imag; } if(packet_in_.content=="y6") { printf("P8(%d,%d): receive y6 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y6in.real=packet_in_.token.real; y6in.imag=packet_in_.token.imag; z4out.real=y4in.real+y6in.real; z4out.imag=y4in.imag+y6in.imag; z5out.real=y4in.real-y6in.real; z5out.imag=y4in.imag-y6in.imag; packet pz4(x_, y_, 0, 1,packet_in_.round,"z4", z4out); printf("P8 send z4=%.4f+%.4fi to (%d,%d)\n", pz4.token.real,pz4.token.imag, 0, 1); out_queue_.push_back(pz4); packet pz5(x_, y_, 1, 0,packet_in_.round, "z5",z5out); printf("P8 send z5=%.4f+%.4fi to (%d,%d)\n", pz5.token.real,pz5.token.imag, 1, 0); out_queue_.push_back(pz5); if(PE02_R<(int)out_queue_.size()) PE02_R=(int)out_queue_.size(); } } void PE_P4::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P4::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="y5") { printf("P4(%d,%d): receive y5 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y5in.real=packet_in_.token.real; y5in.imag=packet_in_.token.imag; } if(packet_in_.content=="y7") { y7in.real=packet_in_.token.real; y7in.imag=packet_in_.token.imag; printf("P4(%d,%d): receive y7 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); z6out.real=y5in.real+y7in.imag; z6out.imag=y5in.imag-y7in.real; z7out.real=y5in.real-y7in.imag; z7out.imag=y5in.imag+y7in.real; packet pz6(x_, y_, 2, 1,packet_in_.round, "z6",z6out); printf("P4 send z6=%.4f+%.4fi to (%d,%d)\n", pz6.token.real,pz6.token.imag, 2, 1); out_queue_.push_back(pz6); packet pz7(x_, y_, 1, 2,packet_in_.round, "z7",z7out); printf("P4 send z7=%.4f+%.4fi to (%d,%d)\n", pz7.token.real,pz7.token.imag, 1, 2); out_queue_.push_back(pz7); if(PE22_R<(int)out_queue_.size()) PE22_R=(int)out_queue_.size(); } } void PE_P3::execute() { // fire the actor if the incoming packet is valid if ((packet_in_.src_x != -1) && (packet_in_.src_y != -1)) fire(); } void PE_P3::fire() { assert((packet_in_.src_x != -1) && (packet_in_.src_y != -1)); if(packet_in_.content=="y0") { printf("P3(%d,%d): receive y0 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y0in.real=packet_in_.token.real; y0in.imag=packet_in_.token.imag; } if(packet_in_.content=="y2") { printf("P3(%d,%d): receive y2 %.4f+%.4fi from (%d,%d)\n", x_, y_, packet_in_.token.real,packet_in_.token.imag,packet_in_.src_x, packet_in_.src_y ); y2in.real=packet_in_.token.real; y2in.imag=packet_in_.token.imag; z0out.real=y0in.real+y2in.real; z0out.imag=y0in.imag+y2in.imag; z1out.real=y0in.real-y2in.real; z1out.imag=y0in.imag-y2in.imag; packet pz0(x_, y_, 0, 1,packet_in_.round, "z0",z0out); printf("P3 send z0=%.4f+%.4fi to (%d,%d)\n", pz0.token.real,pz0.token.imag, 0, 1); out_queue_.push_back(pz0); packet pz1(x_, y_, 1, 0,packet_in_.round,"z1", z1out); printf("P3 send z1=%.4f+%.4fi to (%d,%d)\n", pz1.token.real,pz1.token.imag, 1, 0); out_queue_.push_back(pz1); if(PE00_R<(int)out_queue_.size()) PE00_R=(int)out_queue_.size(); } }
e44bb271f807bb6bf6ed8f39f5ec1ad8318f5573
[ "C++" ]
3
C++
kobejamesgt/Noc-Architecture
c90db6852104eac63c2763303fb02ed5e3b47ae7
4b6b0f55d90fde16188e1226b8272197c0e7321d
refs/heads/master
<file_sep> # Jasper Node Client A module providing a simple Jasper Server Client ___ # Install ```bash npm install jasper-node-client --save ``` # Configuration An object with the following structure is require (you can put it in your application config file): ```javascript jasperRestService: { /** * Base Url of your JasperServer * @type {String} */ baseUrl: '', /** * User Name * @type {String} */ userName: '', /** * User passworj * @type {String} */ password: '', /** * Request headers * @type {Object} */ headers: { authorization: '', accept: 'application/json' } } ``` __ # Example ```javascript 'use strict' var config = { baseUrl: '', userName: '', password: '', headers: { authorization: '', accept: 'application/json' } } const Jasper = require('jasper-node-client')(config) var jasper = new Jasper() var reportPath = '' var reportName = 'ExampleName' var fileFormat = 'pdf' var params = { fec_ini: '2016-11-01%2000:00:00', fec_fin: '2016-11-14%2000:00:00', telefono: '0414', conditions: '', auxiliarconditions: '', query: '' } jasper.requestReport(reportPath, reportName, fileFormat, params, (err, response, headers) => { if (err != null) { console.log(err) } else { res.writeHead(200, headers) //res is express response object res.end(response) //response (this is Jasper Client response object passed to the callback) contains the buffer returned by Jasper Server. //I used res.end because the response has already been sent by using writeHead method } }); ``` A way to force the file download without page reloading (Asuming you got a webservice that uses jasper-node-client): ```html <script> window.location.href = "[web service url]" </script> ```<file_sep>'use strict' /** * Class RestClient Esta clase es un adaptador generico para un cliente REST, solo se usa el metodo get que es el necesario para hacer la peticion * @class RestClient * @author <NAME> <<EMAIL>> */ /** Forma de uso var headers = { accept: 'application/json', authorization: 'Bearer 0bd1b7385e90634bc9d9c92b84380722fa00f8f4' } var rest = new restClient("http://webserver2a-local:9201/", headers) var success = function (data, response) { // parsed response body as js object console.log(data, "parsed response body as js object") // raw response //console.log(response) } var params = { idFleet: '', idSubFleet: '', idVehicle: '', iniDate: '2015-10-16', endDate: '2016-11-07' } rest.get('odometer', params, success) **/ class RestClient { /** * Constructor de la clase RestClient. * @method constructor * @param {String} url La URL base de la peticion * @param {String} headers Las cabeceras a enviar en la respuesta hacia el navegador */ constructor (url, headers) { var Client = require('node-rest-client').Client this.client = new Client() this.url = url this.endpoint = '' this.headers = headers } /** * Metodo que envia una peticion GET con los parametros pasados * @method get * @param {String} path Ruta hacia la ubicacion del archivo * @param {String} endpoint El endpoint que representa al reporte en si * @param {Object} params Objeto que contiene los parametros que se le pasaran al reporte * @param {Function} callback Callback que maneja el exito de la respuesta contiene la data y las cabeceras * @param {Function} errorHandler Calback qque devuelve los error al realizar la peticion * @return void */ get (path, endpoint, fileFormat, params, callback, errorHandler) { this.endpoint = endpoint var args = { headers: this.headers } var requestParams = [] for (var property in params) { var value = params[property] requestParams.push(`${property}=${value}`) } var fullUrl = this.url + path + this.endpoint + '.' + fileFormat + '?' + requestParams.join('&') this.client.get(fullUrl, args, callback).on('error', errorHandler) } } module.exports = RestClient <file_sep> 'use strict' var config = { baseUrl: '', userName: '', password: '', headers: { authorization: '', accept: 'application/json' } } const Jasper = require('jasper-node-client')(config) var jasper = new Jasper() var reportPath = '' var reportName = 'ExampleName' var fileFormat = 'pdf' var params = { fec_ini: '2016-11-01%2000:00:00', fec_fin: '2016-11-14%2000:00:00', telefono: '0414', conditions: '', auxiliarconditions: '', query: '' } jasper.requestReport(reportPath, reportName, fileFormat, params, (err, response, headers) => { if (err != null) { console.log(err) } else { res.writeHead(200, headers) //res es el objeto response de express res.end(response) } }); <file_sep>'use strict' /** * Modulo que envuelve la clase JasperClient. Recibe por parametro un objeto obj = {baseUrl: '', userName: '', password: '', headers: {}} * @module JasperClient * @param {Object} config Los parametros basicos para el consumo del servicio. obj = {baseUrl: '', userName: '', password: '', headers: {}} * @return {Object} Retorna el objeto instanciable de la clase JasperClient * @todo DUcktyping para validar que existan los atributos baseUrl, userName, password y headers y que sean del tipo adecuado. * @todo Mejorar el manejo de errores * @author <NAME> <<EMAIL>> */ module.exports = function (config) { const RestClient = require('./RestClient/RestClient.js') var globalConf = config /** * Esta clase es un cliente que permite consumir la API RESTful de Jasper Reports. * * @class JasperClient * @author <NAME> <<EMAIL>> */ /* *Modo de uso const Jasper = require("[PATH HACIA LE MODULO]/JasperClient/src/js/JasperClient.js")({baseUrl: '', userName: '', password: '', headers: { authorization: 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=', accept: 'application/json'}}; var jasper = new Jasper(null, 'jasperadmin', 'jasperadmin'); var reportPath = 'reports/PatrullajeInteligente/Informes/'; var reportName = 'BitacoraTelefono'; var fileFormat = 'pdf'; var params = { fec_ini: '2016-11-01%2000:00:00', fec_fin: '2016-11-14%2000:00:00', telefono: '0414', conditions: '', auxiliarconditions: '', query: '' }; jasper.requestReport(reportPath, reportName, fileFormat, params, (err, response, headers) => { if(err != null){ console.log(err); }else{ res.writeHead(200, headers); res.end(response); } }); */ class JasperClient { /** * Constructor de la clase. * @method constructor * @return {void} */ constructor () { this._baseUrl = globalConf.baseUrl this._username = globalConf.userName this._password = <PASSWORD> this._exportHeaders = { 'pdf': 'application/pdf', 'xls': 'application/ms-excel', 'xml': 'application/xml', 'csv': 'text/csv', 'rtf': 'application/octet-stream', 'html': 'text/html' } this._requestHeaders = globalConf.headers this._apiClient = new RestClient(this._baseUrl, this._requestHeaders) } /** * Metodo que genera el reporte * @method requestReport * @param {String} reportPath La ruta hacia el reporte * @param {String} reportName El nombre del reporte deseado * @param {String} fileFormat El formato requerido (ej, HTML, PDF,...) * @param {Object} params Los parametros requeridos por el reporte * @param {function} callback Un callback que devuelve errores si existen, la data del reporte y los headers a enviar con el archivo * @return {void} Se provee de un callback al que se le pasa la data de salida */ requestReport (reportPath, reportName, fileFormat, params, callback) { var respuesta = '' var self = this var _callback = function (data, response) { respuesta = data var headers = self.getResponseHeaders(fileFormat, reportName, data.length) callback(null, data, headers, response) } var _errorHandler = function (err) { callback(err.request.options, null, null) } this._apiClient.get(reportPath, reportName, fileFormat, params, _callback, _errorHandler) return respuesta } /** * Metodo que construye las cabezeras a ser enviadas con el archivo * @method getResponseHeaders * @param {String} fileFormat Formato del archivo: pdf, html, txt, etc * @param {String} reportName Nombre del reporte a imprimir * @param {Integer} dataLength Longitud del buffer * @return {Object} Retorna un objecto que contiene las cabeceras */ getResponseHeaders (fileFormat, reportName, dataLength) { var headers = { 'Content-Disposition': 'attachment;filename=' + reportName + '.' + fileFormat.toLowerCase(), 'Content-Type': this._exportHeaders[fileFormat.toLowerCase()], 'Content-Length': dataLength } return headers } } return JasperClient }
96932129bfa914366241c98d2c87ceeab2836bf3
[ "Markdown", "JavaScript" ]
4
Markdown
puricamaykol/jasper-node-client
6b8b0be6dfb50bc1a9326be2f318e9bfd0923f2d
1b8accc02e0eb45f803355f34c468eeb760d1dbf
refs/heads/master
<repo_name>kennytm/parse-size<file_sep>/src/lib.rs //! `parse-size` is an accurate, customizable, allocation-free library for //! parsing byte size into integer. //! //! ```rust //! use parse_size::parse_size; //! //! assert_eq!(parse_size("0.2 MiB"), Ok(209715)); //! assert_eq!(parse_size("14.2e+8"), Ok(14_2000_0000)); //! ``` //! //! # Features //! //! Supports both binary and decimal based prefix up to exabytes. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("1 B"), Ok(1)); //! assert_eq!(parse_size("1 KiB"), Ok(1 << 10)); //! assert_eq!(parse_size("1 MiB"), Ok(1 << 20)); //! assert_eq!(parse_size("1 GiB"), Ok(1 << 30)); //! assert_eq!(parse_size("1 TiB"), Ok(1 << 40)); //! assert_eq!(parse_size("1 PiB"), Ok(1 << 50)); //! assert_eq!(parse_size("1 EiB"), Ok(1 << 60)); //! assert_eq!(parse_size("1 KB"), Ok(1_000)); //! assert_eq!(parse_size("1 MB"), Ok(1_000_000)); //! assert_eq!(parse_size("1 GB"), Ok(1_000_000_000)); //! assert_eq!(parse_size("1 TB"), Ok(1_000_000_000_000)); //! assert_eq!(parse_size("1 PB"), Ok(1_000_000_000_000_000)); //! assert_eq!(parse_size("1 EB"), Ok(1_000_000_000_000_000_000)); //! ``` //! //! Numbers can be fractional and/or in scientific notation. //! `parse-size` can accurately parse the input using the full 64-bit precision. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("2.999999999999999999e18"), Ok(2999999999999999999)); //! assert_eq!(parse_size("3.000000000000000001 EB"), Ok(3000000000000000001)); //! ``` //! //! The unit is case-insensitive. The "B" suffix is also optional. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("5gb"), Ok(5_000_000_000)); //! assert_eq!(parse_size("2ki"), Ok(2048)); //! ``` //! //! Fractional bytes are allowed, and rounded to nearest integer. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("0.333333 KB"), Ok(333)); //! assert_eq!(parse_size("2.666666 KB"), Ok(2667)); //! ``` //! //! Underscores and spaces in the numbers are ignored to support digit grouping. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size(" 69_420_000"), Ok(69_420_000)); //! ``` //! //! Conventional units (KB, GB, ...) can be configured to use the binary system. //! //! ```rust //! use parse_size::Config; //! //! let cfg = Config::new().with_binary(); //! assert_eq!(cfg.parse_size("1 KB"), Ok(1024)); //! assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); //! assert_eq!(cfg.parse_size("1 MB"), Ok(1048576)); //! assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); //! ``` //! //! # Integration examples //! //! Use with `structopt` v0.3: //! //! ```rust,ignore //! use structopt::StructOpt; //! use parse_size::parse_size; //! //! #[derive(StructOpt)] //! pub struct Opt { //! #[structopt(long, parse(try_from_str = parse_size))] //! pub size: u64, //! } //! //! let opt = Opt::from_iter(&["./app", "--size", "2.5 K"]); //! assert_eq!(opt.size, 2500); //! ``` #![cfg_attr(not(feature = "std"), no_std)] use core::{convert::TryFrom, fmt}; /// The system to use when parsing prefixes like "KB" and "GB". #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum UnitSystem { /// Use powers of 1000 for prefixes. Parsing "1 KB" returns 1000. Decimal, /// Use powers of 1024 for prefixes. Parsing "1 KB" returns 1024. Binary, } impl UnitSystem { /// Obtains the power factor for the given prefix character. /// /// Returns None if the input is not a valid prefix. /// /// The only valid prefixes are K, M, G, T, P and E. The higher powers Z and /// Y exceed the `u64` range and thus considered invalid. fn factor(self, prefix: u8) -> Option<u64> { Some(match (self, prefix) { (Self::Decimal, b'k') | (Self::Decimal, b'K') => 1_000, (Self::Decimal, b'm') | (Self::Decimal, b'M') => 1_000_000, (Self::Decimal, b'g') | (Self::Decimal, b'G') => 1_000_000_000, (Self::Decimal, b't') | (Self::Decimal, b'T') => 1_000_000_000_000, (Self::Decimal, b'p') | (Self::Decimal, b'P') => 1_000_000_000_000_000, (Self::Decimal, b'e') | (Self::Decimal, b'E') => 1_000_000_000_000_000_000, (Self::Binary, b'k') | (Self::Binary, b'K') => 1_u64 << 10, (Self::Binary, b'm') | (Self::Binary, b'M') => 1_u64 << 20, (Self::Binary, b'g') | (Self::Binary, b'G') => 1_u64 << 30, (Self::Binary, b't') | (Self::Binary, b'T') => 1_u64 << 40, (Self::Binary, b'p') | (Self::Binary, b'P') => 1_u64 << 50, (Self::Binary, b'e') | (Self::Binary, b'E') => 1_u64 << 60, _ => return None, }) } } /// How to deal with the "B" suffix. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum ByteSuffix { /// The "B" suffix must never appear. Parsing a string with the "B" suffix /// causes [`Error::InvalidDigit`] error. Deny, /// The "B" suffix is optional. Allow, /// The "B" suffix is required. Parsing a string without the "B" suffix /// causes [`Error::InvalidDigit`] error. Require, } /// Configuration of the parser. #[derive(Clone, Debug)] pub struct Config { unit_system: UnitSystem, default_factor: u64, byte_suffix: ByteSuffix, } impl Config { /// Creates a new parser configuration. pub const fn new() -> Self { Self { unit_system: UnitSystem::Decimal, default_factor: 1, byte_suffix: ByteSuffix::Allow, } } /// Changes the configuration's unit system. /// /// The default system is decimal (powers of 1000). pub const fn with_unit_system(mut self, unit_system: UnitSystem) -> Self { self.unit_system = unit_system; self } /// Changes the configuration to use the binary unit system, which are /// defined to be powers of 1024. /// /// # Examples /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_binary(); /// assert_eq!(cfg.parse_size("1 KB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 MB"), Ok(1048576)); /// assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); /// ``` pub const fn with_binary(self) -> Self { self.with_unit_system(UnitSystem::Binary) } /// Changes the configuration to use the decimal unit system, which are /// defined to be powers of 1000. This is the default setting. /// /// # Examples /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_decimal(); /// assert_eq!(cfg.parse_size("1 KB"), Ok(1000)); /// assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 MB"), Ok(1000000)); /// assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); /// ``` pub const fn with_decimal(self) -> Self { self.with_unit_system(UnitSystem::Decimal) } /// Changes the default factor when a byte unit is not provided. /// /// This is useful for keeping backward compatibility when migrating from an /// old user interface expecting non-byte input. /// /// The default value is 1. /// /// # Examples /// /// If the input is a pure number, we treat that as mebibytes. /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_default_factor(1048576); /// assert_eq!(cfg.parse_size("10"), Ok(10485760)); /// assert_eq!(cfg.parse_size("0.5"), Ok(524288)); /// assert_eq!(cfg.parse_size("128 B"), Ok(128)); // explicit units overrides the default /// assert_eq!(cfg.parse_size("16 KiB"), Ok(16384)); /// ``` pub const fn with_default_factor(mut self, factor: u64) -> Self { self.default_factor = factor; self } /// Changes the handling of the "B" suffix. /// /// Normally, the character "B" at the end of the input is optional. This /// can be changed to deny or require such suffix. /// /// Power prefixes (K, Ki, M, Mi, ...) are not affected. /// /// # Examples /// /// Deny the suffix. /// /// ```rust /// use parse_size::{ByteSuffix, Config, Error}; /// /// let cfg = Config::new().with_byte_suffix(ByteSuffix::Deny); /// assert_eq!(cfg.parse_size("123"), Ok(123)); /// assert_eq!(cfg.parse_size("123k"), Ok(123000)); /// assert_eq!(cfg.parse_size("123B"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123KB"), Err(Error::InvalidDigit)); /// ``` /// /// Require the suffix. /// /// ```rust /// use parse_size::{ByteSuffix, Config, Error}; /// /// let cfg = Config::new().with_byte_suffix(ByteSuffix::Require); /// assert_eq!(cfg.parse_size("123"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123k"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123B"), Ok(123)); /// assert_eq!(cfg.parse_size("123KB"), Ok(123000)); /// ``` pub const fn with_byte_suffix(mut self, byte_suffix: ByteSuffix) -> Self { self.byte_suffix = byte_suffix; self } /// Parses the string input into the number of bytes it represents. /// /// # Examples /// /// ```rust /// use parse_size::{Config, Error}; /// /// let cfg = Config::new().with_binary(); /// assert_eq!(cfg.parse_size("10 KB"), Ok(10240)); /// assert_eq!(cfg.parse_size("20000"), Ok(20000)); /// assert_eq!(cfg.parse_size("^_^"), Err(Error::InvalidDigit)); /// ``` pub fn parse_size<T: AsRef<[u8]>>(&self, src: T) -> Result<u64, Error> { parse_size_inner(self, src.as_ref()) } } impl Default for Config { fn default() -> Self { Self::new() } } // TODO: Switch to IntErrorKind once it is stable. /// The error returned when parse failed. #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[non_exhaustive] pub enum Error { /// The input contains no numbers. Empty, /// An invalid character is encountered while parsing. InvalidDigit, /// The resulting number is too large to fit into a `u64`. PosOverflow, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::Empty => "cannot parse integer from empty string", Self::InvalidDigit => "invalid digit found in string", Self::PosOverflow => "number too large to fit in target type", }) } } #[cfg(feature = "std")] impl std::error::Error for Error {} /// Parses the string input into the number of bytes it represents using the /// default configuration. /// /// Equivalent to calling [`Config::parse_size()`] with the default /// configuration ([`Config::new()`]). /// /// # Examples /// /// ```rust /// use parse_size::{parse_size, Error}; /// /// assert_eq!(parse_size("10 KB"), Ok(10000)); /// assert_eq!(parse_size("20000"), Ok(20000)); /// assert_eq!(parse_size("0.2 MiB"), Ok(209715)); /// assert_eq!(parse_size("^_^"), Err(Error::InvalidDigit)); /// ``` pub fn parse_size<T: AsRef<[u8]>>(src: T) -> Result<u64, Error> { parse_size_inner(&Config::new(), src.as_ref()) } fn parse_size_inner(cfg: &Config, mut src: &[u8]) -> Result<u64, Error> { // if it ends with 'B' the default factor is always 1. let mut multiply = cfg.default_factor; match src { [init @ .., b'b'] | [init @ .., b'B'] => { if cfg.byte_suffix == ByteSuffix::Deny { return Err(Error::InvalidDigit); } src = init; multiply = 1; } _ => { if cfg.byte_suffix == ByteSuffix::Require { return Err(Error::InvalidDigit); } } } // if it ends with an 'i' we always use binary prefix. let mut unit_system = cfg.unit_system; match src { [init @ .., b'i'] | [init @ .., b'I'] => { src = init; unit_system = UnitSystem::Binary; } _ => {} } if let [init @ .., prefix] = src { if let Some(f) = unit_system.factor(*prefix) { multiply = f; src = init; } } #[derive(Copy, Clone, PartialEq)] enum Ps { Empty, Integer, IntegerOverflow, Fraction, FractionOverflow, PosExponent, NegExponent, } macro_rules! append_digit { ($before:expr, $method:ident, $digit_char:expr) => { $before .checked_mul(10) .and_then(|v| v.$method(($digit_char - b'0').into())) }; } let mut mantissa = 0_u64; let mut fractional_exponent = 0; let mut exponent = 0_i32; let mut state = Ps::Empty; for b in src { match (state, *b) { (Ps::Integer, b'0'..=b'9') | (Ps::Empty, b'0'..=b'9') => { if let Some(m) = append_digit!(mantissa, checked_add, *b) { mantissa = m; state = Ps::Integer; } else { if *b >= b'5' { mantissa += 1; } state = Ps::IntegerOverflow; fractional_exponent += 1; } } (Ps::IntegerOverflow, b'0'..=b'9') => { fractional_exponent += 1; } (Ps::Fraction, b'0'..=b'9') => { if let Some(m) = append_digit!(mantissa, checked_add, *b) { mantissa = m; fractional_exponent -= 1; } else { if *b >= b'5' { mantissa += 1; } state = Ps::FractionOverflow; } } (Ps::FractionOverflow, b'0'..=b'9') => {} (Ps::PosExponent, b'0'..=b'9') => { if let Some(e) = append_digit!(exponent, checked_add, *b) { exponent = e; } else { return Err(Error::PosOverflow); } } (Ps::NegExponent, b'0'..=b'9') => { if let Some(e) = append_digit!(exponent, checked_sub, *b) { exponent = e; } } (_, b'_') | (_, b' ') | (Ps::PosExponent, b'+') => {} (Ps::Integer, b'e') | (Ps::Integer, b'E') | (Ps::Fraction, b'e') | (Ps::Fraction, b'E') | (Ps::IntegerOverflow, b'e') | (Ps::IntegerOverflow, b'E') | (Ps::FractionOverflow, b'e') | (Ps::FractionOverflow, b'E') => state = Ps::PosExponent, (Ps::PosExponent, b'-') => state = Ps::NegExponent, (Ps::Integer, b'.') => state = Ps::Fraction, (Ps::IntegerOverflow, b'.') => state = Ps::FractionOverflow, _ => return Err(Error::InvalidDigit), } } if state == Ps::Empty { return Err(Error::Empty); } let exponent = exponent.saturating_add(fractional_exponent); if exponent >= 0 { let power = 10_u64 .checked_pow(exponent as u32) .ok_or(Error::PosOverflow)?; let multiply = multiply.checked_mul(power).ok_or(Error::PosOverflow)?; mantissa.checked_mul(multiply).ok_or(Error::PosOverflow) } else if exponent >= -38 { let power = 10_u128.pow(-exponent as u32); let result = (u128::from(mantissa) * u128::from(multiply) + power / 2) / power; u64::try_from(result).map_err(|_| Error::PosOverflow) } else { // (2^128) * 1e-39 < 1, always, and thus saturate to 0. Ok(0) } } #[test] fn test_passes() { assert_eq!(parse_size("0"), Ok(0)); assert_eq!(parse_size("3"), Ok(3)); assert_eq!(parse_size("30"), Ok(30)); assert_eq!(parse_size("32"), Ok(32)); assert_eq!(parse_size("_5_"), Ok(5)); assert_eq!(parse_size("1 234 567"), Ok(1_234_567)); assert_eq!( parse_size("18_446_744_073_709_551_581"), Ok(18_446_744_073_709_551_581) ); assert_eq!( parse_size("18_446_744_073_709_551_615"), Ok(18_446_744_073_709_551_615) ); assert_eq!( parse_size("18_446_744_073_709_551_616"), Err(Error::PosOverflow) ); assert_eq!( parse_size("18_446_744_073_709_551_620"), Err(Error::PosOverflow) ); assert_eq!(parse_size("1kB"), Ok(1_000)); assert_eq!(parse_size("2MB"), Ok(2_000_000)); assert_eq!(parse_size("3GB"), Ok(3_000_000_000)); assert_eq!(parse_size("4TB"), Ok(4_000_000_000_000)); assert_eq!(parse_size("5PB"), Ok(5_000_000_000_000_000)); assert_eq!(parse_size("6EB"), Ok(6_000_000_000_000_000_000)); assert_eq!(parse_size("7 KiB"), Ok(7 << 10)); assert_eq!(parse_size("8 MiB"), Ok(8 << 20)); assert_eq!(parse_size("9 GiB"), Ok(9 << 30)); assert_eq!(parse_size("10 TiB"), Ok(10 << 40)); assert_eq!(parse_size("11 PiB"), Ok(11 << 50)); assert_eq!(parse_size("12 EiB"), Ok(12 << 60)); assert_eq!(parse_size("1mib"), Ok(1_048_576)); assert_eq!(parse_size("5k"), Ok(5000)); assert_eq!(parse_size("1.1 K"), Ok(1100)); assert_eq!(parse_size("1.2345 K"), Ok(1235)); assert_eq!(parse_size("1.2345m"), Ok(1_234_500)); assert_eq!(parse_size("5.k"), Ok(5000)); assert_eq!(parse_size("0.0025KB"), Ok(3)); assert_eq!( parse_size("3.141_592_653_589_793_238e"), Ok(3_141_592_653_589_793_238) ); assert_eq!( parse_size("18.446_744_073_709_551_615 EB"), Ok(18_446_744_073_709_551_615) ); assert_eq!( parse_size("18.446_744_073_709_551_616 EB"), Err(Error::PosOverflow) ); assert_eq!( parse_size("1.000_000_000_000_000_001 EB"), Ok(1_000_000_000_000_000_001) ); assert_eq!(parse_size("1e2 KIB"), Ok(102_400)); assert_eq!(parse_size("1E+6"), Ok(1_000_000)); assert_eq!(parse_size("1e-4 MiB"), Ok(105)); assert_eq!(parse_size("1.1e2"), Ok(110)); assert_eq!(parse_size("5.7E3"), Ok(5700)); assert_eq!(parse_size("20_000_000_000_000_000_000e-18"), Ok(20)); assert_eq!(parse_size("98_765_432_109_876_543_210e-16"), Ok(9877)); assert_eq!(parse_size("1e21"), Err(Error::PosOverflow)); assert_eq!(parse_size("0.01e21"), Ok(10_000_000_000_000_000_000)); assert_eq!( parse_size("3.333_333_333_333_333_333_333_333_333_333_333_333_333_333_333_333 EB"), Ok(3_333_333_333_333_333_333) ); assert_eq!(parse_size("2e+0_9"), Ok(2_000_000_000)); assert_eq!( parse_size("3e+66666666666666666666"), Err(Error::PosOverflow) ); assert_eq!(parse_size("4e-77777777777777777777"), Ok(0)); assert_eq!(parse_size("5e-88888888888888888888 EiB"), Ok(0)); assert_eq!( parse_size("123_456_789_012_345_678_901_234_567.890e-16"), Ok(12_345_678_901) ); assert_eq!(parse_size("0.1e-2147483648"), Ok(0)); assert_eq!(parse_size("184467440737095516150e-38EiB"), Ok(2)); } #[test] fn test_parse_errors() { assert_eq!(parse_size(""), Err(Error::Empty)); assert_eq!(parse_size("."), Err(Error::InvalidDigit)); assert_eq!(parse_size(".5k"), Err(Error::InvalidDigit)); assert_eq!(parse_size("k"), Err(Error::Empty)); assert_eq!(parse_size("kb"), Err(Error::Empty)); assert_eq!(parse_size("kib"), Err(Error::Empty)); assert_eq!(parse_size(" "), Err(Error::Empty)); assert_eq!(parse_size("__"), Err(Error::Empty)); assert_eq!(parse_size("a"), Err(Error::InvalidDigit)); assert_eq!(parse_size("-1"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1,5"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1e+f"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1e0.5"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1 ZiB"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1 YiB"), Err(Error::InvalidDigit)); } #[test] fn test_config() { let cfg = Config::new().with_binary().with_default_factor(1_048_576); assert_eq!(cfg.parse_size("3.5"), Ok(3_670_016)); assert_eq!(cfg.parse_size("35 B"), Ok(35)); assert_eq!(cfg.parse_size("5K"), Ok(5120)); } <file_sep>/Cargo.toml [package] name = "parse-size" version = "1.0.0" authors = ["kennytm <<EMAIL>>"] edition = "2018" description = "Parse byte size into integer accurately." keywords = ["bytes", "size", "humanize", "human", "parser"] repository = "https://github.com/kennytm/parse-size" license = "MIT" [features] # The `std` feature is provided if you need `parse_size::Error` to implement # `std::error::Error`. This feature will become no-op once the Error trait is # moved into libcore (https://github.com/rust-lang/rust/issues/53487) or the # type `core::num::IntErrorKind` is stabilized. std = [] <file_sep>/README.md parse-size ========== [![Crates.io](https://img.shields.io/crates/v/parse-size.svg)](https://crates.io/crates/parse-size) [![docs.rs](https://docs.rs/parse-size/badge.svg)](https://docs.rs/parse-size) [![Build status](https://github.com/kennytm/parse-size/workflows/Rust/badge.svg)](https://github.com/kennytm/parse-size/actions?query=workflow%3ARust) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.txt) `parse-size` is an accurate, customizable, allocation-free library for parsing byte size into integer. ```rust use parse_size::parse_size; assert_eq!(parse_size("0.2 MiB"), Ok(209715)); assert_eq!(parse_size("14.2e+8"), Ok(14_2000_0000)); ``` ## Features * Supports both binary and decimal based prefix up to exabytes. * Numbers can be fractional and/or in scientific notation. `parse-size` can accurately parse the input using the full 64-bit precision. * The unit is case-insensitive. The "B" suffix is also optional (`1 KiB` = `1 kib` = `1Ki`). * Fractional bytes are allowed, and rounded to nearest integer (`2.5B` = `3`). * Underscores and spaces in the numbers are ignored to support digit grouping (`123_456` = `123456`). * Conventional units (KB, GB, ...) can be configured to use the binary system. * `#![no_std]`-capable, no dependencies, and uses no heap allocation.
8f4a2c39578e96f8decf3fc379f3c51fc0fce031
[ "TOML", "Rust", "Markdown" ]
3
Rust
kennytm/parse-size
69866cc5800b678ee48aa57ed113a0220ec39fb5
66efd600e313d9b3e95adbc8ef9ad493c1f524f7
refs/heads/master
<file_sep>#!/bin/sh dirs="bin etc usr lib" for d in $dirs; do if ! [ -d /initrd/$d ]; then continue fi mkdir -p $d for x in /initrd/$d/*; do if [ -f $x ]; then ln -s $x $d/ elif [ -d $x ]; then dname=$(basename $x) mkdir -p /$d/$dname for y in /initrd/$d/$dname/*; do if [ "$y" = "/initrd/$d/$dname/*" ]; then break fi ln -s $y /$d/$dname/ done fi done done <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/fs/vfs_base.h> #define KOBJ_BASE_FIELDS \ REF_COUNTED_OBJECT; \ void (*on_handle_close)(fs_handle h); \ void (*on_handle_dup)(fs_handle h); \ void (*destory_obj)(struct kobj_base *); struct kobj_base { KOBJ_BASE_FIELDS }; struct kfs_handle { FS_HANDLE_BASE_FIELDS struct kobj_base *kobj; }; STATIC_ASSERT(sizeof(struct kfs_handle) <= MAX_FS_HANDLE_SIZE); void init_kernelfs(void); void kfs_destroy_handle(struct kfs_handle *h); struct kfs_handle * kfs_create_new_handle(const struct file_ops *fops, struct kobj_base *kobj, int fl_flags); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck_gen_headers/config_kmalloc.h> #include <tilck/kernel/kmalloc.h> #include <kernel/kmalloc/kmalloc_heap_struct.h> // kmalloc private header #include <kernel/kmalloc/kmalloc_block_node.h> // kmalloc private header u32 spur_irq_count; u32 unhandled_irq_count[256]; bool suppress_printk; volatile bool __in_panic; volatile bool __in_kernel_shutdown; volatile bool __in_panic_debugger; void *__kernel_pdir; bool mock_kmalloc = false; /* see the comments above __wrap_general_kmalloc() */ void *__real_general_kmalloc(size_t *size, u32 flags); void __real_general_kfree(void *ptr, size_t *size, u32 flags); void panic(const char *fmt, ...) { printf("\n--- KERNEL PANIC ---\n"); va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); printf("\n--- END PANIC MESSAGE ---\n"); abort(); } void __wrap_tilck_vprintk(u32 flags, const char *fmt, va_list args) { if (suppress_printk) return; vprintf(fmt, args); } void __wrap_assert_failed(const char *expr, const char *file, int line) { printf("Kernel assertion '%s' FAILED in %s:%d\n", expr, file, line); abort(); } void __wrap_not_reached(const char *file, int line) { printf("Kernel NOT_REACHED statement in %s:%d\n", file, line); abort(); } void __wrap_not_implemented(const char *file, int line) { printf("Kernel NOT_IMPLEMENTED at %s:%d\n", file, line); abort(); } int __wrap_fat_ramdisk_prepare_for_mmap(void *hdr, size_t rd_size) { return -1; } int __wrap_wth_create_thread_for(void *t) { return 0; } void __wrap_wth_wakeup() { /* do nothing */ } void __wrap_check_in_irq_handler() { /* do nothing */ } void __wrap_kmutex_lock(struct kmutex *m) { ASSERT(m->owner_task == NULL); m->owner_task = get_curr_task(); } void __wrap_kmutex_unlock(struct kmutex *m) { ASSERT(m->owner_task == get_curr_task()); m->owner_task = NULL; } /* * Decide with just a global flag whether to use glibc's malloc() or Tilck's * kmalloc() implementation, instead of using a proper GMock in kmalloc_test.cpp * with ON_CALL(mock, general_kmalloc).WillByDefault([&mock](...) { ... }), * simply because that is too slow for performance measurements. Otherwise, the * mocking mechanism with GMock is great. */ void *__wrap_general_kmalloc(size_t *size, u32 flags) { if (mock_kmalloc) return malloc(*size); return __real_general_kmalloc(size, 0); } void __wrap_general_kfree(void *ptr, size_t *size, u32 flags) { if (mock_kmalloc) return free(ptr); return __real_general_kfree(ptr, size, 0); } void *__wrap_kmalloc_get_first_heap(size_t *size) { static void *buf; if (!buf) { buf = aligned_alloc(KMALLOC_MAX_ALIGN, KMALLOC_FIRST_HEAP_SIZE); VERIFY(buf); VERIFY( ((ulong)buf & (KMALLOC_MAX_ALIGN - 1)) == 0 ); } if (size) *size = KMALLOC_FIRST_HEAP_SIZE; return buf; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/debug/termios_debug.c.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/term.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/process.h> #include <tilck/kernel/sys_types.h> #include "tty_int.h" const struct termios default_termios = { .c_iflag = ICRNL | IXON, .c_oflag = OPOST | ONLCR, .c_cflag = CREAD | B38400 | CS8, .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN, .c_line = 0, .c_cc = { [VINTR] = 0x03, /* typical value for TERM=linux, Ctrl+C */ [VQUIT] = 0x1c, /* typical value for TERM=linux, Ctrl+\ */ [VERASE] = 0x7f, /* typical value for TERM=linux */ [VKILL] = 0x15, /* typical value for TERM=linux, Ctrl+7 */ [VEOF] = 0x04, /* typical value for TERM=linux, Ctrl+D */ [VTIME] = 0, /* typical value for TERM=linux (unset) */ [VMIN] = 0x01, /* typical value for TERM=linux */ [VSWTC] = 0, /* typical value for TERM=linux (unsupported)*/ [VSTART] = 0x11, /* typical value for TERM=linux, Ctrl+Q */ [VSTOP] = 0x13, /* typical value for TERM=linux, Ctrl+S */ [VSUSP] = 0x1a, /* typical value for TERM=linux, Ctrl+Z */ [VEOL] = 0, /* typical value for TERM=linux (unset) */ [VREPRINT] = 0x12, /* typical value for TERM=linux, Ctrl+R */ [VDISCARD] = 0x0f, /* typical value for TERM=linux, Ctrl+O */ [VWERASE] = 0x17, /* typical value for TERM=linux, Ctrl+W */ [VLNEXT] = 0x16, /* typical value for TERM=linux, Ctrl+V */ [VEOL2] = 0, /* typical value for TERM=linux (unset) */ }, }; void tty_set_raw_mode(struct tty *t) { disable_preemption(); { tty_reset_termios(t); t->c_term.c_iflag = 0; t->c_term.c_oflag = 0; t->c_term.c_cflag = CREAD | B38400 | CS8; t->c_term.c_lflag = 0; } enable_preemption(); } void tty_set_medium_raw_mode(struct tty *t, bool enabled) { disable_preemption(); { if (enabled) tty_set_raw_mode(t); else tty_reset_termios(t); t->mediumraw_mode = enabled; } enable_preemption(); } void tty_reset_termios(struct tty *t) { disable_preemption(); { t->c_term = default_termios; t->mediumraw_mode = false; } enable_preemption(); } static int tty_ioctl_tcgets(struct tty *t, void *argp) { int rc = copy_to_user(argp, &t->c_term, sizeof(struct termios)); if (rc < 0) return -EFAULT; return 0; } static int tty_ioctl_tcsets(struct tty *t, void *argp) { struct termios saved = t->c_term; int rc = copy_from_user(&t->c_term, argp, sizeof(struct termios)); if (rc < 0) { t->c_term = saved; return -EFAULT; } if ((t->c_term.c_lflag & ICANON) != (saved.c_lflag & ICANON)) t->end_line_delim_count = 0; tty_update_ctrl_handlers(t); tty_update_default_state_tables(t); return 0; } static int tty_ioctl_tiocgwinsz(struct tty *t, void *argp) { struct winsize sz = { .ws_row = t->tparams.rows, .ws_col = t->tparams.cols, .ws_xpixel = 0, .ws_ypixel = 0, }; int rc = copy_to_user(argp, &sz, sizeof(struct winsize)); if (rc < 0) return -EFAULT; return 0; } void tty_setup_for_panic(struct tty *t) { if (t->kd_gfx_mode != KD_TEXT) { /* * NOTE: don't try to always fully restart the video output * because it might trigger a nested panic. When kd_gfx_mode != KD_TEXT, * we have no other choice, if we wanna see something on the screen. * * TODO: investigate whether it is possible to make * term_restart_output() safer in panic scenarios. */ t->tintf->restart_output(t->tstate); t->kd_gfx_mode = KD_TEXT; } tty_reset_termios(t); } void tty_restore_kd_text_mode(struct tty *t) { if (t->kd_gfx_mode == KD_TEXT) return; t->tintf->restart_output(t->tstate); t->kd_gfx_mode = KD_TEXT; } static int tty_ioctl_kdsetmode(struct tty *t, void *argp) { ulong opt = (ulong) argp; if (opt == KD_TEXT) { tty_restore_kd_text_mode(t); return 0; } if (opt == KD_GRAPHICS) { t->tintf->pause_output(t->tstate); t->kd_gfx_mode = KD_GRAPHICS; return 0; } return -EINVAL; } static int tty_ioctl_KDGKBMODE(struct tty *t, void *argp) { int mode = t->mediumraw_mode ? K_MEDIUMRAW : K_XLATE; if (!copy_to_user(argp, &mode, sizeof(int))) return 0; return -EFAULT; } static int tty_ioctl_KDSKBMODE(struct tty *t, void *argp) { struct process *pi = get_curr_proc(); if (t != pi->proc_tty) return -EPERM; /* don't allow setting mode of other TTYs */ ulong mode = (ulong) argp; switch (mode) { case K_XLATE: t->mediumraw_mode = false; pi->did_set_tty_medium_raw = false; break; case K_MEDIUMRAW: t->mediumraw_mode = true; pi->did_set_tty_medium_raw = true; break; default: return -EINVAL; } return 0; } static int tty_ioctl_KDGKBTYPE(struct tty *t, void *argp) { const int kb_type = KB_101; if (copy_to_user(argp, &kb_type, sizeof(kb_type))) return -EFAULT; return 0; } static int tty_ioctl_TIOCNOTTY(struct tty *t, void *argp) { struct process *pi = get_curr_proc(); if (pi->proc_tty != t) return -EPERM; /* that's not our controlling terminal */ if (pi->sid == pi->pid) { /* * The session leader gives up his controlling terminal. * * TODO: send SIGHUP to all the processes in the foreground process group * and make all the processes in the current session to lose their * controlling terminal. */ } pi->proc_tty = NULL; return 0; } static int tty_ioctl_TIOCSCTTY(struct tty *t, void *argp) { struct process *pi = get_curr_proc(); if (pi->proc_tty) { /* * The current process has already a controlling terminal. * * On Linux, if the caller process has the CAP_SYS_ADMIN capability and * arg equals 1, the terminal is stolen, and all processes that had it as * controlling terminal lose it. * * On Tilck, at least for the moment, that won't be supported. */ return -EPERM; } if (pi->sid != pi->pid) return -EPERM; /* not a session leader */ pi->proc_tty = t; return 0; } /* get foreground process group */ static int tty_ioctl_TIOCGPGRP(struct tty *t, int *user_pgrp) { int rc; disable_preemption(); { rc = t->fg_pgid; } enable_preemption(); return rc; } /* set foregroup process group */ static int tty_ioctl_TIOCSPGRP(struct tty *t, const int *user_pgrp) { struct process *pi = get_curr_proc(); int pgid; int sid; if (pi->proc_tty != t) return -ENOTTY; if (copy_from_user(&pgid, user_pgrp, sizeof(int))) return -EFAULT; if (pgid < 0) return -EINVAL; sid = sched_get_session_of_group(pgid); if (sid < 0) return -EPERM; /* no such process group */ if (sid != pi->sid) return -EPERM; /* progress group in a different session */ disable_preemption(); { t->fg_pgid = pgid; } enable_preemption(); return 0; } int tty_ioctl_int(struct tty *t, struct devfs_handle *h, ulong request, void *argp) { switch (request) { case TCGETS: return tty_ioctl_tcgets(t, argp); case TCSETS: // equivalent to: tcsetattr(fd, TCSANOW, argp) return tty_ioctl_tcsets(t, argp); case TCSETSW: // equivalent to: tcsetattr(fd, TCSADRAIN, argp) return tty_ioctl_tcsets(t, argp); case TCSETSF: // equivalent to: tcsetattr(fd, TCSAFLUSH, argp) tty_inbuf_reset(t); return tty_ioctl_tcsets(t, argp); case TIOCGWINSZ: return tty_ioctl_tiocgwinsz(t, argp); case KDSETMODE: return tty_ioctl_kdsetmode(t, argp); case KDGKBMODE: return tty_ioctl_KDGKBMODE(t, argp); case KDSKBMODE: return tty_ioctl_KDSKBMODE(t, argp); case KDGKBTYPE: return tty_ioctl_KDGKBTYPE(t, argp); case TIOCSCTTY: return tty_ioctl_TIOCSCTTY(t, argp); case TIOCNOTTY: return tty_ioctl_TIOCNOTTY(t, argp); case TIOCGPGRP: return tty_ioctl_TIOCGPGRP(t, argp); case TIOCSPGRP: return tty_ioctl_TIOCSPGRP(t, argp); default: printk("WARNING: unknown tty_ioctl() request: %p\n", TO_PTR(request)); return -EINVAL; } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <errno.h> #include <elf.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <tilck/common/basic_defs.h> #include <tilck/common/elf_types.h> #include <tilck/common/elf_calc_mem_size.c.h> #include <tilck/common/elf_get_section.c.h> struct elf_file_info { const char *path; size_t mmap_size; void *vaddr; int fd; }; struct elfhack_cmd { const char *opt; const char *help; int nargs; int (*func)(struct elf_file_info *, ...); }; int show_help(struct elf_file_info *nfo, ...); /* --- Low-level ELF utility functions --- */ Elf_Phdr * get_phdr_for_section(Elf_Ehdr *h, Elf_Shdr *section) { Elf_Phdr *phdrs = (Elf_Phdr *)((char*)h + h->e_phoff); Elf_Addr sh_begin = section->sh_addr; Elf_Addr sh_end = section->sh_addr + section->sh_size; for (uint32_t i = 0; i < h->e_phnum; i++) { Elf_Phdr *p = phdrs + i; Elf_Addr pend = p->p_vaddr + p->p_memsz; if (p->p_vaddr <= sh_begin && sh_end <= pend) return p; } return NULL; } Elf_Sym * get_symbol(Elf_Ehdr *h, const char *sym_name) { Elf_Shdr *symtab; Elf_Shdr *strtab; Elf_Sym *syms; unsigned sym_count; symtab = elf_get_section(h, ".symtab"); strtab = elf_get_section(h, ".strtab"); if (!symtab || !strtab) return NULL; syms = (Elf_Sym *)((char *)h + symtab->sh_offset); sym_count = symtab->sh_size / sizeof(Elf_Sym); for (unsigned i = 0; i < sym_count; i++) { Elf_Sym *s = syms + i; const char *s_name = (char *)h + strtab->sh_offset + s->st_name; if (!strcmp(s_name, sym_name)) return s; } return NULL; } /* --- Actual commands --- */ int section_dump(struct elf_file_info *nfo, const char *section_name, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *s = elf_get_section(nfo->vaddr, section_name); if (!s) { fprintf(stderr, "No section '%s'\n", section_name); return 1; } fwrite((char*)h + s->sh_offset, 1, s->sh_size, stdout); return 0; } int copy_section(struct elf_file_info *nfo, const char *src, const char *dst, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *s_src, *s_dst; if (!src) { fprintf(stderr, "Missing <source section> argument\n"); return 1; } if (!dst) { fprintf(stderr, "Missing <dest section> argument\n"); return 1; } s_src = elf_get_section(nfo->vaddr, src); if (!s_src) { fprintf(stderr, "No section '%s'\n", src); return 1; } s_dst = elf_get_section(nfo->vaddr, dst); if (!s_dst) { fprintf(stderr, "No section '%s'\n", dst); return 1; } if (s_src->sh_size > s_dst->sh_size) { fprintf(stderr, "The source section '%s' is too big " "[%lu bytes] to fit in the dest section '%s' [%lu bytes]\n", src, (unsigned long)s_src->sh_size, dst, (unsigned long)s_dst->sh_size); return 1; } memcpy((char*)h + s_dst->sh_offset, (char*)h + s_src->sh_offset, s_src->sh_size); s_dst->sh_info = s_src->sh_info; s_dst->sh_flags = s_src->sh_flags; s_dst->sh_type = s_src->sh_type; s_dst->sh_entsize = s_src->sh_entsize; s_dst->sh_size = s_src->sh_size; return 0; } int rename_section(struct elf_file_info *nfo, const char *section_name, const char *new_name, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; char *hc = (char *)h; Elf_Shdr *sections = (Elf_Shdr *)(hc + h->e_shoff); Elf_Shdr *shstrtab = sections + h->e_shstrndx; if (!new_name) { fprintf(stderr, "Missing <new_name> argument\n"); return 1; } if (strlen(new_name) > strlen(section_name)) { fprintf(stderr, "Section rename with length > old one NOT supported.\n"); return 1; } Elf_Shdr *s = elf_get_section(nfo->vaddr, section_name); if (!s) { fprintf(stderr, "No section '%s'\n", section_name); return 1; } strcpy(hc + shstrtab->sh_offset + s->sh_name, new_name); return 0; } int link_sections(struct elf_file_info *nfo, const char *section_name, const char *linked, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; char *hc = (char *)h; Elf_Shdr *sections = (Elf_Shdr *)(hc + h->e_shoff); if (!linked) { fprintf(stderr, "Missing <linked section> argument\n"); return 1; } Elf_Shdr *a = elf_get_section(nfo->vaddr, section_name); Elf_Shdr *b = elf_get_section(nfo->vaddr, linked); if (!a) { fprintf(stderr, "No section '%s'\n", section_name); return 1; } if (!b) { fprintf(stderr, "No section '%s'\n", linked); return 1; } unsigned bidx = (b - sections); a->sh_link = bidx; return 0; } int move_metadata(struct elf_file_info *nfo, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; char *hc = (char *)h; size_t off = h->e_ehsize; memcpy(hc + off, hc + h->e_phoff, h->e_phentsize*h->e_phnum); h->e_phoff = off; off += h->e_phentsize*h->e_phnum; memcpy(hc + off, hc + h->e_shoff, h->e_shentsize*h->e_shnum); h->e_shoff = off; off += h->e_shentsize*h->e_shnum; Elf_Shdr *sections = (Elf_Shdr *) (hc + h->e_shoff); Elf_Shdr *shstrtab = sections + h->e_shstrndx; memcpy(hc + off, hc + shstrtab->sh_offset, shstrtab->sh_size); shstrtab->sh_offset = off; Elf_Phdr *phdrs = (Elf_Phdr *)(hc + h->e_phoff); shstrtab->sh_addr = phdrs[0].p_vaddr + shstrtab->sh_offset; shstrtab->sh_flags |= SHF_ALLOC; for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; /* Make sure that all the sections with a vaddr != 0 are 'alloc' */ if (s->sh_addr) s->sh_flags |= SHF_ALLOC; } return 0; } int drop_last_section(struct elf_file_info *nfo, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; char *hc = (char *)h; Elf_Shdr *sections = (Elf_Shdr *)(hc + h->e_shoff); Elf_Shdr *shstrtab = sections + h->e_shstrndx; Elf_Shdr *last_section = sections; int last_section_index = 0; off_t last_offset = 0; if (!h->e_shnum) { fprintf(stderr, "ERROR: the ELF file has no sections!\n"); return 1; } for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; if (s->sh_offset > last_offset) { last_section = s; last_offset = s->sh_offset; last_section_index = i; } } if (last_section == shstrtab) { fprintf(stderr, "The last section is .shstrtab and it cannot be removed!\n"); return 1; } if (last_section_index != h->e_shnum - 1) { /* * If the last section physically on file is not the last section in * the table, we cannot just decrease h->e_shnum, otherwise we'll remove * from the table an useful section. Therefore, in that case we just * use the slot of the last_section to store the section metainfo of the * section with the biggest index in the section table (last section in * another sense). */ *last_section = sections[h->e_shnum - 1]; /* * If we're so unlucky that the section with the biggest index in the * section table is also the special .shstrtab, we have to update its * index in the ELF header as well. */ if (h->e_shstrndx == h->e_shnum - 1) { h->e_shstrndx = last_section_index; } } /* Drop the last section from the section table */ h->e_shnum--; /* * Unlink all the sections depending on this one. Yes, this is rough, * but it's fine. Users of this script MUST know exactly what they're doing. * In particular, for the main use of this feature (drop of the old symtab * and strtab), it is expected this function to be just used twice. */ for (uint32_t i = 0; i < h->e_shnum; i++) if (sections[i].sh_link == last_section_index) sections[i].sh_link = 0; /* * Unfortunately, the "bash for Windows" subsystem does not support * ftruncate on memory-mapped files. Even if having the Tilck to work there * is _not_ a must (users are supposed to use Linux), it is a nice-to-have * feature. Therefore, here we first unmap the memory-mapped ELF file and * then we truncate it. */ if (munmap(nfo->vaddr, nfo->mmap_size) < 0) { perror("munmap() failed"); return 1; } nfo->vaddr = NULL; /* Physically remove the last section from the file, by truncating it */ if (ftruncate(nfo->fd, last_offset) < 0) { fprintf(stderr, "ftruncate(%i, %li) failed with '%s'\n", nfo->fd, last_offset, strerror(errno)); return 1; } return 0; } int set_phdr_rwx_flags(struct elf_file_info *nfo, const char *phdr_index, const char *flags, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; errno = 0; char *endptr = NULL; unsigned long phindex = strtoul(phdr_index, &endptr, 10); if (errno || *endptr != '\0') { fprintf(stderr, "Invalid phdr index '%s'\n", phdr_index); return 1; } if (phindex >= h->e_phnum) { fprintf(stderr, "Phdr index %lu out-of-range [0, %u].\n", phindex, h->e_phnum - 1); return 1; } if (!flags) { fprintf(stderr, "Missing <rwx flags> argument.\n"); return 1; } char *hc = (char *)h; Elf_Phdr *phdrs = (Elf_Phdr *)(hc + h->e_phoff); Elf_Phdr *phdr = phdrs + phindex; unsigned f = 0; while (*flags) { switch (*flags) { case 'r': f |= PF_R; break; case 'w': f |= PF_W; break; case 'x': f |= PF_X; break; default: fprintf(stderr, "Invalid flag '%c'. Allowed: r,w,x.\n", *flags); return 1; } flags++; } // First, clear the already set RWX flags (be keep the others!) phdr->p_flags &= ~(PF_R | PF_W | PF_X); // Then, set the new RWX flags. phdr->p_flags |= f; return 0; } int verify_flat_elf_file(struct elf_file_info *nfo, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *sections = (Elf_Shdr *)((char*)h + h->e_shoff); Elf_Shdr *shstrtab = sections + h->e_shstrndx; Elf_Addr lowest_addr = (Elf_Addr) -1; Elf_Addr base_addr = lowest_addr; bool failed = false; if (!h->e_shnum) { fprintf(stderr, "ERROR: the ELF file has no sections!\n"); return 1; } for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; Elf_Phdr *phdr = get_phdr_for_section(h, s); if (!phdr || phdr->p_type != PT_LOAD) continue; if (s->sh_addr < lowest_addr) { base_addr = s->sh_addr - s->sh_offset; lowest_addr = s->sh_addr; } } for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; Elf_Phdr *phdr = get_phdr_for_section(h, s); char *name = (char *)h + shstrtab->sh_offset + s->sh_name; if (!phdr || phdr->p_type != PT_LOAD) continue; Elf_Addr mem_offset = s->sh_addr - base_addr; if (mem_offset != s->sh_offset) { fprintf(stderr, "ERROR: section[%d] '%s' has " "memory_offset (%p) != file_offset (%p)\n", i, name, (void *)(size_t)mem_offset, (void *)(size_t)s->sh_offset); failed = true; } } if (h->e_entry != lowest_addr) { fprintf(stderr, "ERROR: entry point (%p) != lowest load addr (%p)\n", (void *)(size_t)h->e_entry, (void *)(size_t)lowest_addr); failed = true; } if (failed) { fprintf(stderr, "ERROR: flat ELF check FAILED for file: %s\n", nfo->path); return 1; } return 0; } int check_entry_point(struct elf_file_info *nfo, const char *exp, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; uintptr_t exp_val; char *endptr; if (!exp) { printf("%p\n", TO_PTR(h->e_entry)); return 0; } errno = 0; exp_val = strtoul(exp, &endptr, 16); if (errno || endptr == exp) { fprintf(stderr, "Invalid value '%s' for expected entry point.\n", exp); fprintf(stderr, "It must be a hex string like 0xc0101000.\n"); return 1; } if (h->e_entry != exp_val) { fprintf(stderr, "ERROR: entry point (%#lx) != expected (%#lx) for file %s\n", (uintptr_t)h->e_entry, exp_val, nfo->path); return 1; } return 0; } int check_mem_size(struct elf_file_info *nfo, const char *exp, const char *kb, ...) { size_t sz = elf_calc_mem_size(nfo->vaddr); size_t exp_val; char *endptr; int base = 10; if (!exp || !strcmp(exp, "kb")) { printf("%zu\n", exp ? sz / KB : sz); return 0; } if (exp[0] == '0' && exp[1] == 'x') base = 16; errno = 0; exp_val = strtoul(exp, &endptr, base); if (errno || endptr == exp) { fprintf(stderr, "Invalid value '%s' for expected_max.\n", exp); return 1; } if (kb && !strcmp(kb, "kb")) exp_val *= KB; if (sz > exp_val) { fprintf(stderr, "ELF's max in-memory size (%zu) > expected_max (%zu).\n", sz, exp_val); return 1; } return 0; } int set_sym_strval(struct elf_file_info *nfo, const char *section_name, const char *sym_name, const char *val, ...) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *section; Elf_Sym *sym; size_t len; if (!sym_name || !val) { fprintf(stderr, "Missing arguments\n"); return 1; } section = elf_get_section(h, section_name); if (!section) { fprintf(stderr, "No section '%s'\n", section_name); return 1; } sym = get_symbol(h, sym_name); if (!sym) { fprintf(stderr, "Unable to find the symbol '%s'\n", sym_name); return 1; } if (sym->st_value < section->sh_addr || sym->st_value + sym->st_size > section->sh_addr + section->sh_size) { fprintf(stderr, "Symbol '%s' not in section '%s'\n", sym_name, section_name); return 1; } len = strlen(val) + 1; if (sym->st_size < len) { fprintf(stderr, "Symbol '%s' [%u bytes] not big enough for value\n", sym_name, (unsigned)sym->st_size); return 1; } const long sym_sec_off = sym->st_value - section->sh_addr; const long sym_file_off = section->sh_offset + sym_sec_off; memcpy((char *)h + sym_file_off, val, len); return 0; } int dump_sym(struct elf_file_info *nfo, const char *sym_name) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *sections = (Elf_Shdr *) ((char *)h + h->e_shoff); Elf_Sym *sym = get_symbol(h, sym_name); if (!sym) { fprintf(stderr, "Symbol '%s' not found\n", sym_name); return 1; } Elf_Shdr *section = sections + sym->st_shndx; const long sym_sec_off = sym->st_value - section->sh_addr; const long sym_file_off = section->sh_offset + sym_sec_off; for (u32 i = 0; i < sym->st_size; i++) printf("%02x ", *((unsigned char *)h + sym_file_off + i)); printf("\n"); return 0; } int get_sym(struct elf_file_info *nfo, const char *sym_name) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Sym *sym = get_symbol(h, sym_name); if (!sym) { fprintf(stderr, "Symbol '%s' not found\n", sym_name); return 1; } printf("0x%08lx\n", (unsigned long)sym->st_value); return 0; } int get_text_sym(struct elf_file_info *nfo, const char *sym_name) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *sections = (Elf_Shdr *) ((char *)h + h->e_shoff); Elf_Shdr *section_header_strtab = sections + h->e_shstrndx; Elf_Sym *sym = get_symbol(h, sym_name); if (!sym) { fprintf(stderr, "Symbol '%s' not found\n", sym_name); return 1; } if (sym->st_shndx > h->e_shnum) { fprintf(stderr, "ERROR: unknown section for symbol %s\n", sym_name); return 1; } Elf_Shdr *s = sections + sym->st_shndx; char *name = (char *)h + section_header_strtab->sh_offset + s->sh_name; if (strcmp(name, ".text")) { fprintf(stderr, "ERROR: the symbol belongs to section: %s\n", name); return 1; } printf("0x%08lx\n", (unsigned long)sym->st_value); return 0; } int list_text_syms(struct elf_file_info *nfo) { Elf_Ehdr *h = (Elf_Ehdr*)nfo->vaddr; Elf_Shdr *sections = (Elf_Shdr *) ((char *)h + h->e_shoff); Elf_Shdr *text = elf_get_section(h, ".text"); Elf_Shdr *symtab; Elf_Shdr *strtab; Elf_Sym *syms; unsigned sym_count; unsigned text_sh_index; if (!text) { fprintf(stderr, "ERROR: cannot find the .text section\n"); return 1; } text_sh_index = text - sections; symtab = elf_get_section(h, ".symtab"); strtab = elf_get_section(h, ".strtab"); if (!symtab || !strtab) { fprintf(stderr, "ERROR: no .symtab or .strtab in the binary\n"); return 1; } syms = (Elf_Sym *)((char *)h + symtab->sh_offset); sym_count = symtab->sh_size / sizeof(Elf_Sym); for (unsigned i = 0; i < sym_count; i++) { Elf_Sym *s = syms + i; const char *s_name = (char *)h + strtab->sh_offset + s->st_name; if (s->st_shndx != text_sh_index) continue; printf("%s\n", s_name); } return 0; } static struct elfhack_cmd cmds_list[] = { { .opt = "--help", .help = "", .nargs = 0, .func = (void *)&show_help, }, { .opt = "--dump", .help = "<section name>", .nargs = 1, .func = (void *)&section_dump, }, { .opt = "--move-metadata", .help = "", .nargs = 0, .func = (void *)&move_metadata, }, { .opt = "--copy", .help = "<src section> <dest section>", .nargs = 2, .func = (void *)&copy_section, }, { .opt = "--rename", .help = "<section> <new_name>", .nargs = 2, .func = (void *)&rename_section, }, { .opt = "--link", .help = "<section> <linked_section>", .nargs = 2, .func = (void *)&link_sections, }, { .opt = "--drop-last-section", .help = "", .nargs = 0, .func = (void *)&drop_last_section, }, { .opt = "--set-phdr-rwx-flags", .help = "<phdr index> <rwx flags>", .nargs = 2, .func = (void *)&set_phdr_rwx_flags, }, { .opt = "--verify-flat-elf", .help = "", .nargs = 0, .func = (void *)&verify_flat_elf_file, }, { .opt = "--check-entry-point", .help = "[<expected>]", .nargs = 0, /* note: the `expected` param is optional */ .func = (void *)&check_entry_point, }, { .opt = "--check-mem-size", .help = "[expected_max] [kb]", .nargs = 0, /* note: both the params are optional */ .func = (void *)&check_mem_size, }, { .opt = "--set-sym-strval", .help = "<section> <sym> <string value>", .nargs = 3, .func = (void *)&set_sym_strval, }, { .opt = "--dump-sym", .help = "<sym_name>", .nargs = 1, .func = (void *)&dump_sym, }, { .opt = "--get-sym", .help = "<sym_name>", .nargs = 1, .func = (void *)&get_sym, }, { .opt = "--get-text-sym", .help = "<sym_name>", .nargs = 1, .func = (void *)&get_text_sym, }, { .opt = "--list-text-syms", .help = "", .nargs = 0, .func = (void *)&list_text_syms, }, }; #define printerr(...) fprintf(stderr, __VA_ARGS__) #define print_help_line(...) printerr(" elfhack <file> " __VA_ARGS__) int show_help(struct elf_file_info *nfo, ...) { printerr("Usage:\n"); for (int i = 0; i < ARRAY_SIZE(cmds_list); i++) { struct elfhack_cmd *c = &cmds_list[i]; fprintf(stderr, " elfhack <file> %s %s\n", c->opt, c->help); } return 0; } int elf_header_type_check(struct elf_file_info *nfo) { Elf32_Ehdr *h = nfo->vaddr; if (h->e_ident[EI_MAG0] != ELFMAG0 || h->e_ident[EI_MAG1] != ELFMAG1 || h->e_ident[EI_MAG2] != ELFMAG2 || h->e_ident[EI_MAG3] != ELFMAG3) { fprintf(stderr, "Not a valid ELF binary (magic doesn't match)\n"); return 1; } if (sizeof(Elf_Addr) == 4) { if (h->e_ident[EI_CLASS] != ELFCLASS32) { fprintf(stderr, "ERROR: expected 32-bit binary\n"); return 1; } } else { if (h->e_ident[EI_CLASS] != ELFCLASS64) { fprintf(stderr, "ERROR: expected 64-bit binary\n"); return 1; } } return 0; } int main(int argc, char **argv) { struct elf_file_info nfo = {0}; struct stat statbuf; size_t page_size; const char *opt = NULL; const char *opt_arg1 = NULL; const char *opt_arg2 = NULL; const char *opt_arg3 = NULL; struct elfhack_cmd *cmd = NULL; int rc; if (argc > 2) { nfo.path = argv[1]; opt = argv[2]; if (argc > 3) { opt_arg1 = argv[3]; if (argc > 4) { opt_arg2 = argv[4]; if (argc > 5) opt_arg3 = argv[5]; } } } else { show_help(NULL, NULL, NULL); return 1; } nfo.fd = open(nfo.path, O_RDWR); if (nfo.fd < 0) { perror("open failed"); return 1; } if (fstat(nfo.fd, &statbuf) < 0) { perror("fstat failed"); close(nfo.fd); return 1; } page_size = sysconf(_SC_PAGESIZE); if (page_size <= 0) { fprintf(stderr, "Unable to get page size. Got: %ld\n", (long)page_size); close(nfo.fd); return 1; } nfo.mmap_size = pow2_round_up_at((size_t)statbuf.st_size, page_size); errno = 0; nfo.vaddr = mmap(NULL, /* addr */ nfo.mmap_size, /* length */ PROT_READ | PROT_WRITE, /* prot */ MAP_SHARED, /* flags */ nfo.fd, /* fd */ 0); /* offset */ if (errno) { perror(NULL); return 1; } if (elf_header_type_check(&nfo)) { rc = 1; goto end; } for (int i = 0; i < ARRAY_SIZE(cmds_list); i++) { if (!strcmp(opt, cmds_list[i].opt)) { cmd = &cmds_list[i]; break; } } if (cmd && argc-3 < cmd->nargs) { fprintf(stderr, "ERROR: Invalid number of arguments for %s.\n\n", opt); cmd = NULL; } if (!cmd) cmd = &cmds_list[0]; /* help */ rc = cmd->func(&nfo, opt_arg1, opt_arg2, opt_arg3); end: /* * Do munmap() only if vaddr != NULL. * Reason: some functions (at the moment only drop_last_section()) may * have their reasons for calling munmap() earlier. Do avoid double-calling * it and getting an error, such functions will just set vaddr to NULL. */ if (nfo.vaddr && munmap(nfo.vaddr, nfo.mmap_size) < 0) { perror("munmap() failed"); } close(nfo.fd); return rc; } <file_sep>/****************************************************************************** * * Name: amlcode.h - Definitions for AML, as included in "definition blocks" * Declarations and definitions contained herein are derived * directly from the ACPI specification. * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __AMLCODE_H__ #define __AMLCODE_H__ /* primary opcodes */ #define AML_ZERO_OP (UINT16) 0x00 #define AML_ONE_OP (UINT16) 0x01 #define AML_ALIAS_OP (UINT16) 0x06 #define AML_NAME_OP (UINT16) 0x08 #define AML_BYTE_OP (UINT16) 0x0a #define AML_WORD_OP (UINT16) 0x0b #define AML_DWORD_OP (UINT16) 0x0c #define AML_STRING_OP (UINT16) 0x0d #define AML_QWORD_OP (UINT16) 0x0e /* ACPI 2.0 */ #define AML_SCOPE_OP (UINT16) 0x10 #define AML_BUFFER_OP (UINT16) 0x11 #define AML_PACKAGE_OP (UINT16) 0x12 #define AML_VARIABLE_PACKAGE_OP (UINT16) 0x13 /* ACPI 2.0 */ #define AML_METHOD_OP (UINT16) 0x14 #define AML_EXTERNAL_OP (UINT16) 0x15 /* ACPI 6.0 */ #define AML_DUAL_NAME_PREFIX (UINT16) 0x2e #define AML_MULTI_NAME_PREFIX (UINT16) 0x2f #define AML_EXTENDED_PREFIX (UINT16) 0x5b #define AML_ROOT_PREFIX (UINT16) 0x5c #define AML_PARENT_PREFIX (UINT16) 0x5e #define AML_FIRST_LOCAL_OP (UINT16) 0x60 /* Used for Local op # calculations */ #define AML_LOCAL0 (UINT16) 0x60 #define AML_LOCAL1 (UINT16) 0x61 #define AML_LOCAL2 (UINT16) 0x62 #define AML_LOCAL3 (UINT16) 0x63 #define AML_LOCAL4 (UINT16) 0x64 #define AML_LOCAL5 (UINT16) 0x65 #define AML_LOCAL6 (UINT16) 0x66 #define AML_LOCAL7 (UINT16) 0x67 #define AML_FIRST_ARG_OP (UINT16) 0x68 /* Used for Arg op # calculations */ #define AML_ARG0 (UINT16) 0x68 #define AML_ARG1 (UINT16) 0x69 #define AML_ARG2 (UINT16) 0x6a #define AML_ARG3 (UINT16) 0x6b #define AML_ARG4 (UINT16) 0x6c #define AML_ARG5 (UINT16) 0x6d #define AML_ARG6 (UINT16) 0x6e #define AML_STORE_OP (UINT16) 0x70 #define AML_REF_OF_OP (UINT16) 0x71 #define AML_ADD_OP (UINT16) 0x72 #define AML_CONCATENATE_OP (UINT16) 0x73 #define AML_SUBTRACT_OP (UINT16) 0x74 #define AML_INCREMENT_OP (UINT16) 0x75 #define AML_DECREMENT_OP (UINT16) 0x76 #define AML_MULTIPLY_OP (UINT16) 0x77 #define AML_DIVIDE_OP (UINT16) 0x78 #define AML_SHIFT_LEFT_OP (UINT16) 0x79 #define AML_SHIFT_RIGHT_OP (UINT16) 0x7a #define AML_BIT_AND_OP (UINT16) 0x7b #define AML_BIT_NAND_OP (UINT16) 0x7c #define AML_BIT_OR_OP (UINT16) 0x7d #define AML_BIT_NOR_OP (UINT16) 0x7e #define AML_BIT_XOR_OP (UINT16) 0x7f #define AML_BIT_NOT_OP (UINT16) 0x80 #define AML_FIND_SET_LEFT_BIT_OP (UINT16) 0x81 #define AML_FIND_SET_RIGHT_BIT_OP (UINT16) 0x82 #define AML_DEREF_OF_OP (UINT16) 0x83 #define AML_CONCATENATE_TEMPLATE_OP (UINT16) 0x84 /* ACPI 2.0 */ #define AML_MOD_OP (UINT16) 0x85 /* ACPI 2.0 */ #define AML_NOTIFY_OP (UINT16) 0x86 #define AML_SIZE_OF_OP (UINT16) 0x87 #define AML_INDEX_OP (UINT16) 0x88 #define AML_MATCH_OP (UINT16) 0x89 #define AML_CREATE_DWORD_FIELD_OP (UINT16) 0x8a #define AML_CREATE_WORD_FIELD_OP (UINT16) 0x8b #define AML_CREATE_BYTE_FIELD_OP (UINT16) 0x8c #define AML_CREATE_BIT_FIELD_OP (UINT16) 0x8d #define AML_OBJECT_TYPE_OP (UINT16) 0x8e #define AML_CREATE_QWORD_FIELD_OP (UINT16) 0x8f /* ACPI 2.0 */ #define AML_LOGICAL_AND_OP (UINT16) 0x90 #define AML_LOGICAL_OR_OP (UINT16) 0x91 #define AML_LOGICAL_NOT_OP (UINT16) 0x92 #define AML_LOGICAL_EQUAL_OP (UINT16) 0x93 #define AML_LOGICAL_GREATER_OP (UINT16) 0x94 #define AML_LOGICAL_LESS_OP (UINT16) 0x95 #define AML_TO_BUFFER_OP (UINT16) 0x96 /* ACPI 2.0 */ #define AML_TO_DECIMAL_STRING_OP (UINT16) 0x97 /* ACPI 2.0 */ #define AML_TO_HEX_STRING_OP (UINT16) 0x98 /* ACPI 2.0 */ #define AML_TO_INTEGER_OP (UINT16) 0x99 /* ACPI 2.0 */ #define AML_TO_STRING_OP (UINT16) 0x9c /* ACPI 2.0 */ #define AML_COPY_OBJECT_OP (UINT16) 0x9d /* ACPI 2.0 */ #define AML_MID_OP (UINT16) 0x9e /* ACPI 2.0 */ #define AML_CONTINUE_OP (UINT16) 0x9f /* ACPI 2.0 */ #define AML_IF_OP (UINT16) 0xa0 #define AML_ELSE_OP (UINT16) 0xa1 #define AML_WHILE_OP (UINT16) 0xa2 #define AML_NOOP_OP (UINT16) 0xa3 #define AML_RETURN_OP (UINT16) 0xa4 #define AML_BREAK_OP (UINT16) 0xa5 #define AML_COMMENT_OP (UINT16) 0xa9 #define AML_BREAKPOINT_OP (UINT16) 0xcc #define AML_ONES_OP (UINT16) 0xff /* * Combination opcodes (actually two one-byte opcodes) * Used by the disassembler and iASL compiler */ #define AML_LOGICAL_GREATER_EQUAL_OP (UINT16) 0x9295 /* LNot (LLess) */ #define AML_LOGICAL_LESS_EQUAL_OP (UINT16) 0x9294 /* LNot (LGreater) */ #define AML_LOGICAL_NOT_EQUAL_OP (UINT16) 0x9293 /* LNot (LEqual) */ /* Prefixed (2-byte) opcodes (with AML_EXTENDED_PREFIX) */ #define AML_EXTENDED_OPCODE (UINT16) 0x5b00 /* Prefix for 2-byte opcodes */ #define AML_MUTEX_OP (UINT16) 0x5b01 #define AML_EVENT_OP (UINT16) 0x5b02 #define AML_SHIFT_RIGHT_BIT_OP (UINT16) 0x5b10 /* Obsolete, not in ACPI spec */ #define AML_SHIFT_LEFT_BIT_OP (UINT16) 0x5b11 /* Obsolete, not in ACPI spec */ #define AML_CONDITIONAL_REF_OF_OP (UINT16) 0x5b12 #define AML_CREATE_FIELD_OP (UINT16) 0x5b13 #define AML_LOAD_TABLE_OP (UINT16) 0x5b1f /* ACPI 2.0 */ #define AML_LOAD_OP (UINT16) 0x5b20 #define AML_STALL_OP (UINT16) 0x5b21 #define AML_SLEEP_OP (UINT16) 0x5b22 #define AML_ACQUIRE_OP (UINT16) 0x5b23 #define AML_SIGNAL_OP (UINT16) 0x5b24 #define AML_WAIT_OP (UINT16) 0x5b25 #define AML_RESET_OP (UINT16) 0x5b26 #define AML_RELEASE_OP (UINT16) 0x5b27 #define AML_FROM_BCD_OP (UINT16) 0x5b28 #define AML_TO_BCD_OP (UINT16) 0x5b29 #define AML_UNLOAD_OP (UINT16) 0x5b2a #define AML_REVISION_OP (UINT16) 0x5b30 #define AML_DEBUG_OP (UINT16) 0x5b31 #define AML_FATAL_OP (UINT16) 0x5b32 #define AML_TIMER_OP (UINT16) 0x5b33 /* ACPI 3.0 */ #define AML_REGION_OP (UINT16) 0x5b80 #define AML_FIELD_OP (UINT16) 0x5b81 #define AML_DEVICE_OP (UINT16) 0x5b82 #define AML_PROCESSOR_OP (UINT16) 0x5b83 #define AML_POWER_RESOURCE_OP (UINT16) 0x5b84 #define AML_THERMAL_ZONE_OP (UINT16) 0x5b85 #define AML_INDEX_FIELD_OP (UINT16) 0x5b86 #define AML_BANK_FIELD_OP (UINT16) 0x5b87 #define AML_DATA_REGION_OP (UINT16) 0x5b88 /* ACPI 2.0 */ /* * Opcodes for "Field" operators */ #define AML_FIELD_OFFSET_OP (UINT8) 0x00 #define AML_FIELD_ACCESS_OP (UINT8) 0x01 #define AML_FIELD_CONNECTION_OP (UINT8) 0x02 /* ACPI 5.0 */ #define AML_FIELD_EXT_ACCESS_OP (UINT8) 0x03 /* ACPI 5.0 */ /* * Internal opcodes * Use only "Unknown" AML opcodes, don't attempt to use * any valid ACPI ASCII values (A-Z, 0-9, '-') */ #define AML_INT_NAMEPATH_OP (UINT16) 0x002d #define AML_INT_NAMEDFIELD_OP (UINT16) 0x0030 #define AML_INT_RESERVEDFIELD_OP (UINT16) 0x0031 #define AML_INT_ACCESSFIELD_OP (UINT16) 0x0032 #define AML_INT_BYTELIST_OP (UINT16) 0x0033 #define AML_INT_METHODCALL_OP (UINT16) 0x0035 #define AML_INT_RETURN_VALUE_OP (UINT16) 0x0036 #define AML_INT_EVAL_SUBTREE_OP (UINT16) 0x0037 #define AML_INT_CONNECTION_OP (UINT16) 0x0038 #define AML_INT_EXTACCESSFIELD_OP (UINT16) 0x0039 #define ARG_NONE 0x0 /* * Argument types for the AML Parser * Each field in the ArgTypes UINT32 is 5 bits, allowing for a maximum of 6 arguments. * There can be up to 31 unique argument types * Zero is reserved as end-of-list indicator */ #define ARGP_BYTEDATA 0x01 #define ARGP_BYTELIST 0x02 #define ARGP_CHARLIST 0x03 #define ARGP_DATAOBJ 0x04 #define ARGP_DATAOBJLIST 0x05 #define ARGP_DWORDDATA 0x06 #define ARGP_FIELDLIST 0x07 #define ARGP_NAME 0x08 #define ARGP_NAMESTRING 0x09 #define ARGP_OBJLIST 0x0A #define ARGP_PKGLENGTH 0x0B #define ARGP_SUPERNAME 0x0C #define ARGP_TARGET 0x0D #define ARGP_TERMARG 0x0E #define ARGP_TERMLIST 0x0F #define ARGP_WORDDATA 0x10 #define ARGP_QWORDDATA 0x11 #define ARGP_SIMPLENAME 0x12 /* NameString | LocalTerm | ArgTerm */ #define ARGP_NAME_OR_REF 0x13 /* For ObjectType only */ #define ARGP_MAX 0x13 #define ARGP_COMMENT 0x14 /* * Resolved argument types for the AML Interpreter * Each field in the ArgTypes UINT32 is 5 bits, allowing for a maximum of 6 arguments. * There can be up to 31 unique argument types (0 is end-of-arg-list indicator) * * Note1: These values are completely independent from the ACPI_TYPEs * i.e., ARGI_INTEGER != ACPI_TYPE_INTEGER * * Note2: If and when 5 bits becomes insufficient, it would probably be best * to convert to a 6-byte array of argument types, allowing 8 bits per argument. */ /* Single, simple types */ #define ARGI_ANYTYPE 0x01 /* Don't care */ #define ARGI_PACKAGE 0x02 #define ARGI_EVENT 0x03 #define ARGI_MUTEX 0x04 #define ARGI_DDBHANDLE 0x05 /* Interchangeable types (via implicit conversion) */ #define ARGI_INTEGER 0x06 #define ARGI_STRING 0x07 #define ARGI_BUFFER 0x08 #define ARGI_BUFFER_OR_STRING 0x09 /* Used by MID op only */ #define ARGI_COMPUTEDATA 0x0A /* Buffer, String, or Integer */ /* Reference objects */ #define ARGI_INTEGER_REF 0x0B #define ARGI_OBJECT_REF 0x0C #define ARGI_DEVICE_REF 0x0D #define ARGI_REFERENCE 0x0E #define ARGI_TARGETREF 0x0F /* Target, subject to implicit conversion */ #define ARGI_FIXED_TARGET 0x10 /* Target, no implicit conversion */ #define ARGI_SIMPLE_TARGET 0x11 /* Name, Local, Arg -- no implicit conversion */ #define ARGI_STORE_TARGET 0x12 /* Target for store is TARGETREF + package objects */ /* Multiple/complex types */ #define ARGI_DATAOBJECT 0x13 /* Buffer, String, package or reference to a Node - Used only by SizeOf operator*/ #define ARGI_COMPLEXOBJ 0x14 /* Buffer, String, or package (Used by INDEX op only) */ #define ARGI_REF_OR_STRING 0x15 /* Reference or String (Used by DEREFOF op only) */ #define ARGI_REGION_OR_BUFFER 0x16 /* Used by LOAD op only */ #define ARGI_DATAREFOBJ 0x17 /* Note: types above can expand to 0x1F maximum */ #define ARGI_INVALID_OPCODE 0xFFFFFFFF /* * Some of the flags and types below are of the form: * * AML_FLAGS_EXEC_#A_#T,#R, or * AML_TYPE_EXEC_#A_#T,#R where: * * #A is the number of required arguments * #T is the number of target operands * #R indicates whether there is a return value * * These types are used for the top-level dispatch of the AML * opcode. They group similar operators that can share common * front-end code before dispatch to the final code that implements * the operator. */ /* * Opcode information flags */ #define AML_LOGICAL 0x0001 #define AML_LOGICAL_NUMERIC 0x0002 #define AML_MATH 0x0004 #define AML_CREATE 0x0008 #define AML_FIELD 0x0010 #define AML_DEFER 0x0020 #define AML_NAMED 0x0040 #define AML_NSNODE 0x0080 #define AML_NSOPCODE 0x0100 #define AML_NSOBJECT 0x0200 #define AML_HAS_RETVAL 0x0400 #define AML_HAS_TARGET 0x0800 #define AML_HAS_ARGS 0x1000 #define AML_CONSTANT 0x2000 #define AML_NO_OPERAND_RESOLVE 0x4000 /* Convenient flag groupings of the flags above */ #define AML_FLAGS_EXEC_0A_0T_1R AML_HAS_RETVAL #define AML_FLAGS_EXEC_1A_0T_0R AML_HAS_ARGS /* Monadic1 */ #define AML_FLAGS_EXEC_1A_0T_1R AML_HAS_ARGS | AML_HAS_RETVAL /* Monadic2 */ #define AML_FLAGS_EXEC_1A_1T_0R AML_HAS_ARGS | AML_HAS_TARGET #define AML_FLAGS_EXEC_1A_1T_1R AML_HAS_ARGS | AML_HAS_TARGET | AML_HAS_RETVAL /* Monadic2R */ #define AML_FLAGS_EXEC_2A_0T_0R AML_HAS_ARGS /* Dyadic1 */ #define AML_FLAGS_EXEC_2A_0T_1R AML_HAS_ARGS | AML_HAS_RETVAL /* Dyadic2 */ #define AML_FLAGS_EXEC_2A_1T_1R AML_HAS_ARGS | AML_HAS_TARGET | AML_HAS_RETVAL /* Dyadic2R */ #define AML_FLAGS_EXEC_2A_2T_1R AML_HAS_ARGS | AML_HAS_TARGET | AML_HAS_RETVAL #define AML_FLAGS_EXEC_3A_0T_0R AML_HAS_ARGS #define AML_FLAGS_EXEC_3A_1T_1R AML_HAS_ARGS | AML_HAS_TARGET | AML_HAS_RETVAL #define AML_FLAGS_EXEC_6A_0T_1R AML_HAS_ARGS | AML_HAS_RETVAL /* * The opcode Type is used in a dispatch table, do not change * or add anything new without updating the table. */ #define AML_TYPE_EXEC_0A_0T_1R 0x00 /* 0 Args, 0 Target, 1 RetVal */ #define AML_TYPE_EXEC_1A_0T_0R 0x01 /* 1 Args, 0 Target, 0 RetVal */ #define AML_TYPE_EXEC_1A_0T_1R 0x02 /* 1 Args, 0 Target, 1 RetVal */ #define AML_TYPE_EXEC_1A_1T_0R 0x03 /* 1 Args, 1 Target, 0 RetVal */ #define AML_TYPE_EXEC_1A_1T_1R 0x04 /* 1 Args, 1 Target, 1 RetVal */ #define AML_TYPE_EXEC_2A_0T_0R 0x05 /* 2 Args, 0 Target, 0 RetVal */ #define AML_TYPE_EXEC_2A_0T_1R 0x06 /* 2 Args, 0 Target, 1 RetVal */ #define AML_TYPE_EXEC_2A_1T_1R 0x07 /* 2 Args, 1 Target, 1 RetVal */ #define AML_TYPE_EXEC_2A_2T_1R 0x08 /* 2 Args, 2 Target, 1 RetVal */ #define AML_TYPE_EXEC_3A_0T_0R 0x09 /* 3 Args, 0 Target, 0 RetVal */ #define AML_TYPE_EXEC_3A_1T_1R 0x0A /* 3 Args, 1 Target, 1 RetVal */ #define AML_TYPE_EXEC_6A_0T_1R 0x0B /* 6 Args, 0 Target, 1 RetVal */ /* End of types used in dispatch table */ #define AML_TYPE_LITERAL 0x0C #define AML_TYPE_CONSTANT 0x0D #define AML_TYPE_METHOD_ARGUMENT 0x0E #define AML_TYPE_LOCAL_VARIABLE 0x0F #define AML_TYPE_DATA_TERM 0x10 /* Generic for an op that returns a value */ #define AML_TYPE_METHOD_CALL 0x11 /* Miscellaneous types */ #define AML_TYPE_CREATE_FIELD 0x12 #define AML_TYPE_CREATE_OBJECT 0x13 #define AML_TYPE_CONTROL 0x14 #define AML_TYPE_NAMED_NO_OBJ 0x15 #define AML_TYPE_NAMED_FIELD 0x16 #define AML_TYPE_NAMED_SIMPLE 0x17 #define AML_TYPE_NAMED_COMPLEX 0x18 #define AML_TYPE_RETURN 0x19 #define AML_TYPE_UNDEFINED 0x1A #define AML_TYPE_BOGUS 0x1B /* AML Package Length encodings */ #define ACPI_AML_PACKAGE_TYPE1 0x40 #define ACPI_AML_PACKAGE_TYPE2 0x4000 #define ACPI_AML_PACKAGE_TYPE3 0x400000 #define ACPI_AML_PACKAGE_TYPE4 0x40000000 /* * Opcode classes */ #define AML_CLASS_EXECUTE 0x00 #define AML_CLASS_CREATE 0x01 #define AML_CLASS_ARGUMENT 0x02 #define AML_CLASS_NAMED_OBJECT 0x03 #define AML_CLASS_CONTROL 0x04 #define AML_CLASS_ASCII 0x05 #define AML_CLASS_PREFIX 0x06 #define AML_CLASS_INTERNAL 0x07 #define AML_CLASS_RETURN_VALUE 0x08 #define AML_CLASS_METHOD_CALL 0x09 #define AML_CLASS_UNKNOWN 0x0A /* Comparison operation codes for MatchOp operator */ typedef enum { MATCH_MTR = 0, MATCH_MEQ = 1, MATCH_MLE = 2, MATCH_MLT = 3, MATCH_MGE = 4, MATCH_MGT = 5 } AML_MATCH_OPERATOR; #define MAX_MATCH_OPERATOR 5 /* * FieldFlags * * This byte is extracted from the AML and includes three separate * pieces of information about the field: * 1) The field access type * 2) The field update rule * 3) The lock rule for the field * * Bits 00 - 03 : AccessType (AnyAcc, ByteAcc, etc.) * 04 : LockRule (1 == Lock) * 05 - 06 : UpdateRule */ #define AML_FIELD_ACCESS_TYPE_MASK 0x0F #define AML_FIELD_LOCK_RULE_MASK 0x10 #define AML_FIELD_UPDATE_RULE_MASK 0x60 /* 1) Field Access Types */ typedef enum { AML_FIELD_ACCESS_ANY = 0x00, AML_FIELD_ACCESS_BYTE = 0x01, AML_FIELD_ACCESS_WORD = 0x02, AML_FIELD_ACCESS_DWORD = 0x03, AML_FIELD_ACCESS_QWORD = 0x04, /* ACPI 2.0 */ AML_FIELD_ACCESS_BUFFER = 0x05 /* ACPI 2.0 */ } AML_ACCESS_TYPE; /* 2) Field Lock Rules */ typedef enum { AML_FIELD_LOCK_NEVER = 0x00, AML_FIELD_LOCK_ALWAYS = 0x10 } AML_LOCK_RULE; /* 3) Field Update Rules */ typedef enum { AML_FIELD_UPDATE_PRESERVE = 0x00, AML_FIELD_UPDATE_WRITE_AS_ONES = 0x20, AML_FIELD_UPDATE_WRITE_AS_ZEROS = 0x40 } AML_UPDATE_RULE; /* * Field Access Attributes. * This byte is extracted from the AML via the * AccessAs keyword */ typedef enum { AML_FIELD_ATTRIB_QUICK = 0x02, AML_FIELD_ATTRIB_SEND_RECEIVE = 0x04, AML_FIELD_ATTRIB_BYTE = 0x06, AML_FIELD_ATTRIB_WORD = 0x08, AML_FIELD_ATTRIB_BLOCK = 0x0A, AML_FIELD_ATTRIB_BYTES = 0x0B, AML_FIELD_ATTRIB_PROCESS_CALL = 0x0C, AML_FIELD_ATTRIB_BLOCK_PROCESS_CALL = 0x0D, AML_FIELD_ATTRIB_RAW_BYTES = 0x0E, AML_FIELD_ATTRIB_RAW_PROCESS_BYTES = 0x0F } AML_ACCESS_ATTRIBUTE; /* Bit fields in the AML MethodFlags byte */ #define AML_METHOD_ARG_COUNT 0x07 #define AML_METHOD_SERIALIZED 0x08 #define AML_METHOD_SYNC_LEVEL 0xF0 #endif /* __AMLCODE_H__ */ <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ############################### # LCOV (front end for GCOV) ############################### LCOV_VER="1.15" function download_lcov { local tarname="lcov-${LCOV_VER}.tgz" local url="https://github.com/linux-test-project/lcov.git" download_git_repo_in_cache "$url" v${LCOV_VER} $tarname lcov-${LCOV_VER} extract_cachefile_tar_gz $tarname -- } all_funcs_list+=(build_lcov) function build_lcov { pushd noarch if ! [ -d lcov-${LCOV_VER} ]; then show_work_on_component_msg "LCOV" if [ -d lcov ]; then # Older versions of this script called this package just `lcov`. # Rename `lcov` to `lcov-1.13`. mv lcov lcov-1.13 ln -s lcov-1.13 lcov fi download_lcov cd lcov-${LCOV_VER} else show_skip_component_msg "LCOV" fi popd } function build_lcov_installed_status { if [ -d $TC/noarch/lcov-${LCOV_VER} ]; then echo "installed noarch" fi } <file_sep>/******************************************************************************* * * Module Name: nsaccess - Top-level functions for accessing ACPI namespace * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "amlcode.h" #include "acnamesp.h" #include "acdispat.h" #ifdef ACPI_ASL_COMPILER #include "acdisasm.h" #endif #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsaccess") /******************************************************************************* * * FUNCTION: AcpiNsRootInitialize * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Allocate and initialize the default root named objects * * MUTEX: Locks namespace for entire execution * ******************************************************************************/ ACPI_STATUS AcpiNsRootInitialize ( void) { ACPI_STATUS Status; const ACPI_PREDEFINED_NAMES *InitVal = NULL; ACPI_NAMESPACE_NODE *NewNode; ACPI_NAMESPACE_NODE *PrevNode = NULL; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STRING Val = NULL; ACPI_FUNCTION_TRACE (NsRootInitialize); Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * The global root ptr is initially NULL, so a non-NULL value indicates * that AcpiNsRootInitialize() has already been called; just return. */ if (AcpiGbl_RootNode) { Status = AE_OK; goto UnlockAndExit; } /* * Tell the rest of the subsystem that the root is initialized * (This is OK because the namespace is locked) */ AcpiGbl_RootNode = &AcpiGbl_RootNodeStruct; /* Enter the predefined names in the name table */ ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Entering predefined entries into namespace\n")); /* * Create the initial (default) namespace. * This namespace looks like something similar to this: * * ACPI Namespace (from Namespace Root): * 0 _GPE Scope 00203160 00 * 0 _PR_ Scope 002031D0 00 * 0 _SB_ Device 00203240 00 Notify Object: 0020ADD8 * 0 _SI_ Scope 002032B0 00 * 0 _TZ_ Device 00203320 00 * 0 _REV Integer 00203390 00 = 0000000000000002 * 0 _OS_ String 00203488 00 Len 14 "Microsoft Windows NT" * 0 _GL_ Mutex 00203580 00 Object 002035F0 * 0 _OSI Method 00203678 00 Args 1 Len 0000 Aml 00000000 */ for (InitVal = AcpiGbl_PreDefinedNames; InitVal->Name; InitVal++) { Status = AE_OK; /* _OSI is optional for now, will be permanent later */ if (!strcmp (InitVal->Name, "_OSI") && !AcpiGbl_CreateOsiMethod) { continue; } /* * Create, init, and link the new predefined name * Note: No need to use AcpiNsLookup here because all the * predefined names are at the root level. It is much easier to * just create and link the new node(s) here. */ NewNode = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_NAMESPACE_NODE)); if (!NewNode) { Status = AE_NO_MEMORY; goto UnlockAndExit; } ACPI_COPY_NAMESEG (NewNode->Name.Ascii, InitVal->Name); NewNode->DescriptorType = ACPI_DESC_TYPE_NAMED; NewNode->Type = InitVal->Type; if (!PrevNode) { AcpiGbl_RootNodeStruct.Child = NewNode; } else { PrevNode->Peer = NewNode; } NewNode->Parent = &AcpiGbl_RootNodeStruct; PrevNode = NewNode; /* * Name entered successfully. If entry in PreDefinedNames[] specifies * an initial value, create the initial value. */ if (InitVal->Val) { Status = AcpiOsPredefinedOverride (InitVal, &Val); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Could not override predefined %s", InitVal->Name)); } if (!Val) { Val = InitVal->Val; } /* * Entry requests an initial value, allocate a * descriptor for it. */ ObjDesc = AcpiUtCreateInternalObject (InitVal->Type); if (!ObjDesc) { Status = AE_NO_MEMORY; goto UnlockAndExit; } /* * Convert value string from table entry to * internal representation. Only types actually * used for initial values are implemented here. */ switch (InitVal->Type) { case ACPI_TYPE_METHOD: ObjDesc->Method.ParamCount = (UINT8) ACPI_TO_INTEGER (Val); ObjDesc->Common.Flags |= AOPOBJ_DATA_VALID; #if defined (ACPI_ASL_COMPILER) /* Save the parameter count for the iASL compiler */ NewNode->Value = ObjDesc->Method.ParamCount; #else /* Mark this as a very SPECIAL method (_OSI) */ ObjDesc->Method.InfoFlags = ACPI_METHOD_INTERNAL_ONLY; ObjDesc->Method.Dispatch.Implementation = AcpiUtOsiImplementation; #endif break; case ACPI_TYPE_INTEGER: ObjDesc->Integer.Value = ACPI_TO_INTEGER (Val); break; case ACPI_TYPE_STRING: /* Build an object around the static string */ ObjDesc->String.Length = (UINT32) strlen (Val); ObjDesc->String.Pointer = Val; ObjDesc->Common.Flags |= AOPOBJ_STATIC_POINTER; break; case ACPI_TYPE_MUTEX: ObjDesc->Mutex.Node = NewNode; ObjDesc->Mutex.SyncLevel = (UINT8) (ACPI_TO_INTEGER (Val) - 1); /* Create a mutex */ Status = AcpiOsCreateMutex (&ObjDesc->Mutex.OsMutex); if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ObjDesc); goto UnlockAndExit; } /* Special case for ACPI Global Lock */ if (strcmp (InitVal->Name, "_GL_") == 0) { AcpiGbl_GlobalLockMutex = ObjDesc; /* Create additional counting semaphore for global lock */ Status = AcpiOsCreateSemaphore ( 1, 0, &AcpiGbl_GlobalLockSemaphore); if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ObjDesc); goto UnlockAndExit; } } break; default: ACPI_ERROR ((AE_INFO, "Unsupported initial type value 0x%X", InitVal->Type)); AcpiUtRemoveReference (ObjDesc); ObjDesc = NULL; continue; } /* Store pointer to value descriptor in the Node */ Status = AcpiNsAttachObject (NewNode, ObjDesc, ObjDesc->Common.Type); /* Remove local reference to the object */ AcpiUtRemoveReference (ObjDesc); } } UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); /* Save a handle to "_GPE", it is always present */ if (ACPI_SUCCESS (Status)) { Status = AcpiNsGetNode (NULL, "\\_GPE", ACPI_NS_NO_UPSEARCH, &AcpiGbl_FadtGpeDevice); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiNsLookup * * PARAMETERS: ScopeInfo - Current scope info block * Pathname - Search pathname, in internal format * (as represented in the AML stream) * Type - Type associated with name * InterpreterMode - IMODE_LOAD_PASS2 => add name if not found * Flags - Flags describing the search restrictions * WalkState - Current state of the walk * ReturnNode - Where the Node is placed (if found * or created successfully) * * RETURN: Status * * DESCRIPTION: Find or enter the passed name in the name space. * Log an error if name not found in Exec mode. * * MUTEX: Assumes namespace is locked. * ******************************************************************************/ ACPI_STATUS AcpiNsLookup ( ACPI_GENERIC_STATE *ScopeInfo, char *Pathname, ACPI_OBJECT_TYPE Type, ACPI_INTERPRETER_MODE InterpreterMode, UINT32 Flags, ACPI_WALK_STATE *WalkState, ACPI_NAMESPACE_NODE **ReturnNode) { ACPI_STATUS Status; char *Path = Pathname; char *ExternalPath; ACPI_NAMESPACE_NODE *PrefixNode; ACPI_NAMESPACE_NODE *CurrentNode = NULL; ACPI_NAMESPACE_NODE *ThisNode = NULL; UINT32 NumSegments; UINT32 NumCarats; ACPI_NAME SimpleName; ACPI_OBJECT_TYPE TypeToCheckFor; ACPI_OBJECT_TYPE ThisSearchType; UINT32 SearchParentFlag = ACPI_NS_SEARCH_PARENT; UINT32 LocalFlags; ACPI_INTERPRETER_MODE LocalInterpreterMode; ACPI_FUNCTION_TRACE (NsLookup); if (!ReturnNode) { return_ACPI_STATUS (AE_BAD_PARAMETER); } LocalFlags = Flags & ~(ACPI_NS_ERROR_IF_FOUND | ACPI_NS_OVERRIDE_IF_FOUND | ACPI_NS_SEARCH_PARENT); *ReturnNode = ACPI_ENTRY_NOT_FOUND; AcpiGbl_NsLookupCount++; if (!AcpiGbl_RootNode) { return_ACPI_STATUS (AE_NO_NAMESPACE); } /* Get the prefix scope. A null scope means use the root scope */ if ((!ScopeInfo) || (!ScopeInfo->Scope.Node)) { ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Null scope prefix, using root node (%p)\n", AcpiGbl_RootNode)); PrefixNode = AcpiGbl_RootNode; } else { PrefixNode = ScopeInfo->Scope.Node; if (ACPI_GET_DESCRIPTOR_TYPE (PrefixNode) != ACPI_DESC_TYPE_NAMED) { ACPI_ERROR ((AE_INFO, "%p is not a namespace node [%s]", PrefixNode, AcpiUtGetDescriptorName (PrefixNode))); return_ACPI_STATUS (AE_AML_INTERNAL); } if (!(Flags & ACPI_NS_PREFIX_IS_SCOPE)) { /* * This node might not be a actual "scope" node (such as a * Device/Method, etc.) It could be a Package or other object * node. Backup up the tree to find the containing scope node. */ while (!AcpiNsOpensScope (PrefixNode->Type) && PrefixNode->Type != ACPI_TYPE_ANY) { PrefixNode = PrefixNode->Parent; } } } /* Save type. TBD: may be no longer necessary */ TypeToCheckFor = Type; /* * Begin examination of the actual pathname */ if (!Pathname) { /* A Null NamePath is allowed and refers to the root */ NumSegments = 0; ThisNode = AcpiGbl_RootNode; Path = ""; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Null Pathname (Zero segments), Flags=%X\n", Flags)); } else { /* * Name pointer is valid (and must be in internal name format) * * Check for scope prefixes: * * As represented in the AML stream, a namepath consists of an * optional scope prefix followed by a name segment part. * * If present, the scope prefix is either a Root Prefix (in * which case the name is fully qualified), or one or more * Parent Prefixes (in which case the name's scope is relative * to the current scope). */ if (*Path == (UINT8) AML_ROOT_PREFIX) { /* Pathname is fully qualified, start from the root */ ThisNode = AcpiGbl_RootNode; SearchParentFlag = ACPI_NS_NO_UPSEARCH; /* Point to name segment part */ Path++; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Path is absolute from root [%p]\n", ThisNode)); } else { /* Pathname is relative to current scope, start there */ ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Searching relative to prefix scope [%4.4s] (%p)\n", AcpiUtGetNodeName (PrefixNode), PrefixNode)); /* * Handle multiple Parent Prefixes (carat) by just getting * the parent node for each prefix instance. */ ThisNode = PrefixNode; NumCarats = 0; while (*Path == (UINT8) AML_PARENT_PREFIX) { /* Name is fully qualified, no search rules apply */ SearchParentFlag = ACPI_NS_NO_UPSEARCH; /* * Point past this prefix to the name segment * part or the next Parent Prefix */ Path++; /* Backup to the parent node */ NumCarats++; ThisNode = ThisNode->Parent; if (!ThisNode) { /* * Current scope has no parent scope. Externalize * the internal path for error message. */ Status = AcpiNsExternalizeName (ACPI_UINT32_MAX, Pathname, NULL, &ExternalPath); if (ACPI_SUCCESS (Status)) { ACPI_ERROR ((AE_INFO, "%s: Path has too many parent prefixes (^)", ExternalPath)); ACPI_FREE (ExternalPath); } return_ACPI_STATUS (AE_NOT_FOUND); } } if (SearchParentFlag == ACPI_NS_NO_UPSEARCH) { ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Search scope is [%4.4s], path has %u carat(s)\n", AcpiUtGetNodeName (ThisNode), NumCarats)); } } /* * Determine the number of ACPI name segments in this pathname. * * The segment part consists of either: * - A Null name segment (0) * - A DualNamePrefix followed by two 4-byte name segments * - A MultiNamePrefix followed by a byte indicating the * number of segments and the segments themselves. * - A single 4-byte name segment * * Examine the name prefix opcode, if any, to determine the number of * segments. */ switch (*Path) { case 0: /* * Null name after a root or parent prefixes. We already * have the correct target node and there are no name segments. */ NumSegments = 0; Type = ThisNode->Type; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Prefix-only Pathname (Zero name segments), Flags=%X\n", Flags)); break; case AML_DUAL_NAME_PREFIX: /* More than one NameSeg, search rules do not apply */ SearchParentFlag = ACPI_NS_NO_UPSEARCH; /* Two segments, point to first name segment */ NumSegments = 2; Path++; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Dual Pathname (2 segments, Flags=%X)\n", Flags)); break; case AML_MULTI_NAME_PREFIX: /* More than one NameSeg, search rules do not apply */ SearchParentFlag = ACPI_NS_NO_UPSEARCH; /* Extract segment count, point to first name segment */ Path++; NumSegments = (UINT32) (UINT8) *Path; Path++; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Multi Pathname (%u Segments, Flags=%X)\n", NumSegments, Flags)); break; default: /* * Not a Null name, no Dual or Multi prefix, hence there is * only one name segment and Pathname is already pointing to it. */ NumSegments = 1; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Simple Pathname (1 segment, Flags=%X)\n", Flags)); break; } ACPI_DEBUG_EXEC (AcpiNsPrintPathname (NumSegments, Path)); } /* * Search namespace for each segment of the name. Loop through and * verify (or add to the namespace) each name segment. * * The object type is significant only at the last name * segment. (We don't care about the types along the path, only * the type of the final target object.) */ ThisSearchType = ACPI_TYPE_ANY; CurrentNode = ThisNode; while (NumSegments && CurrentNode) { NumSegments--; if (!NumSegments) { /* This is the last segment, enable typechecking */ ThisSearchType = Type; /* * Only allow automatic parent search (search rules) if the caller * requested it AND we have a single, non-fully-qualified NameSeg */ if ((SearchParentFlag != ACPI_NS_NO_UPSEARCH) && (Flags & ACPI_NS_SEARCH_PARENT)) { LocalFlags |= ACPI_NS_SEARCH_PARENT; } /* Set error flag according to caller */ if (Flags & ACPI_NS_ERROR_IF_FOUND) { LocalFlags |= ACPI_NS_ERROR_IF_FOUND; } /* Set override flag according to caller */ if (Flags & ACPI_NS_OVERRIDE_IF_FOUND) { LocalFlags |= ACPI_NS_OVERRIDE_IF_FOUND; } } /* Handle opcodes that create a new NameSeg via a full NamePath */ LocalInterpreterMode = InterpreterMode; if ((Flags & ACPI_NS_PREFIX_MUST_EXIST) && (NumSegments > 0)) { /* Every element of the path must exist (except for the final NameSeg) */ LocalInterpreterMode = ACPI_IMODE_EXECUTE; } /* Extract one ACPI name from the front of the pathname */ ACPI_MOVE_32_TO_32 (&SimpleName, Path); /* Try to find the single (4 character) ACPI name */ Status = AcpiNsSearchAndEnter (SimpleName, WalkState, CurrentNode, LocalInterpreterMode, ThisSearchType, LocalFlags, &ThisNode); if (ACPI_FAILURE (Status)) { if (Status == AE_NOT_FOUND) { #if !defined ACPI_ASL_COMPILER /* Note: iASL reports this error by itself, not needed here */ if (Flags & ACPI_NS_PREFIX_MUST_EXIST) { AcpiOsPrintf (ACPI_MSG_BIOS_ERROR "Object does not exist: %4.4s\n", (char *) &SimpleName); } #endif /* Name not found in ACPI namespace */ ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Name [%4.4s] not found in scope [%4.4s] %p\n", (char *) &SimpleName, (char *) &CurrentNode->Name, CurrentNode)); } #ifdef ACPI_EXEC_APP if ((Status == AE_ALREADY_EXISTS) && (ThisNode->Flags & ANOBJ_NODE_EARLY_INIT)) { ThisNode->Flags &= ~ANOBJ_NODE_EARLY_INIT; Status = AE_OK; } #endif #ifdef ACPI_ASL_COMPILER /* * If this ACPI name already exists within the namespace as an * external declaration, then mark the external as a conflicting * declaration and proceed to process the current node as if it did * not exist in the namespace. If this node is not processed as * normal, then it could cause improper namespace resolution * by failing to open a new scope. */ if (AcpiGbl_DisasmFlag && (Status == AE_ALREADY_EXISTS) && ((ThisNode->Flags & ANOBJ_IS_EXTERNAL) || (WalkState && WalkState->Opcode == AML_EXTERNAL_OP))) { ThisNode->Flags &= ~ANOBJ_IS_EXTERNAL; ThisNode->Type = (UINT8)ThisSearchType; if (WalkState->Opcode != AML_EXTERNAL_OP) { AcpiDmMarkExternalConflict (ThisNode); } break; } #endif *ReturnNode = ThisNode; return_ACPI_STATUS (Status); } /* More segments to follow? */ if (NumSegments > 0) { /* * If we have an alias to an object that opens a scope (such as a * device or processor), we need to dereference the alias here so * that we can access any children of the original node (via the * remaining segments). */ if (ThisNode->Type == ACPI_TYPE_LOCAL_ALIAS) { if (!ThisNode->Object) { return_ACPI_STATUS (AE_NOT_EXIST); } if (AcpiNsOpensScope (((ACPI_NAMESPACE_NODE *) ThisNode->Object)->Type)) { ThisNode = (ACPI_NAMESPACE_NODE *) ThisNode->Object; } } } /* Special handling for the last segment (NumSegments == 0) */ else { /* * Sanity typecheck of the target object: * * If 1) This is the last segment (NumSegments == 0) * 2) And we are looking for a specific type * (Not checking for TYPE_ANY) * 3) Which is not an alias * 4) Which is not a local type (TYPE_SCOPE) * 5) And the type of target object is known (not TYPE_ANY) * 6) And target object does not match what we are looking for * * Then we have a type mismatch. Just warn and ignore it. */ if ((TypeToCheckFor != ACPI_TYPE_ANY) && (TypeToCheckFor != ACPI_TYPE_LOCAL_ALIAS) && (TypeToCheckFor != ACPI_TYPE_LOCAL_METHOD_ALIAS) && (TypeToCheckFor != ACPI_TYPE_LOCAL_SCOPE) && (ThisNode->Type != ACPI_TYPE_ANY) && (ThisNode->Type != TypeToCheckFor)) { /* Complain about a type mismatch */ ACPI_WARNING ((AE_INFO, "NsLookup: Type mismatch on %4.4s (%s), searching for (%s)", ACPI_CAST_PTR (char, &SimpleName), AcpiUtGetTypeName (ThisNode->Type), AcpiUtGetTypeName (TypeToCheckFor))); } /* * If this is the last name segment and we are not looking for a * specific type, but the type of found object is known, use that * type to (later) see if it opens a scope. */ if (Type == ACPI_TYPE_ANY) { Type = ThisNode->Type; } } /* Point to next name segment and make this node current */ Path += ACPI_NAMESEG_SIZE; CurrentNode = ThisNode; } /* Always check if we need to open a new scope */ if (!(Flags & ACPI_NS_DONT_OPEN_SCOPE) && (WalkState)) { /* * If entry is a type which opens a scope, push the new scope on the * scope stack. */ if (AcpiNsOpensScope (Type)) { Status = AcpiDsScopeStackPush (ThisNode, Type, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } #ifdef ACPI_EXEC_APP if (Flags & ACPI_NS_EARLY_INIT) { ThisNode->Flags |= ANOBJ_NODE_EARLY_INIT; } #endif *ReturnNode = ThisNode; return_ACPI_STATUS (AE_OK); } <file_sep>#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause import os import sys import subprocess from typing import List, Optional, Dict, Tuple, Any # Constants fileTypes = [ "C (source)", "C/C++ (header)", "C++ (source)", "Assembly", "Python", "CMake", "Shell script" ] extToType = { ".c": "C (source)", ".h": "C/C++ (header)", ".cpp": "C++ (source)", ".cc": "C++ (source)", ".cxx": "C++ (source)", ".py": "Python", ".asm": "Assembly", ".S": "Assembly", ".cmake": "CMake", ".sh": "Shell script" } excludedDirs = [ "docs", "3rd_party", "build", "other_builds", "tcci_builds", "sysroot", "toolchain", "system_headers", "vim_text_files", "/acpica/", ".git", ".vscode", ] excludedFiles = [ "pci_classes.c.h", "pci_vendors.c.h", ] PREFIX = " " * 3 FLEN = [ 15, 8, 8, 8 ] # fields length LINE_MAX_COLS = 80 ##################################################### # Global variables optPrintFileNames = False optShowLongLines = False optCheckLineEnding = False longLines: Dict[str, List[Tuple[int, int]]] = {} # file -> list of (line#, cols) nonUnixLeFiles = set() ##################################################### def GetNoExtFileType(fpath: str) -> Optional[str]: out = subprocess.check_output(['file', fpath]).decode('utf-8') if out.find("shell script") != -1: return "Shell script" if out.find("Python script") != -1: return "Python" return None def GetFileType(f: str, folder: str) -> Optional[str]: if f == "CMakeLists.txt": return "CMake" #pylint: disable=unused-variable fname, fext = os.path.splitext(f) if fext == "": return GetNoExtFileType(os.path.join(folder, f)) if not fext in extToType: return None return extToType[fext] def CountLinesInFile(f: str, ft: str) -> List[int]: global longLines global nonUnixLeFiles res = [0, 0] # tot lines, empty lines if optPrintFileNames: print(("file: {0} -> {1}".format(f, ft))) with open(f, 'r') as fd: for i, line in enumerate(fd): le = line[-2:] if len(le) == 2 and (le == '\r\n' or le == '\n\r'): nonUnixLeFiles.add(f) elif len(le) == 1 and le[0] != '\n': nonUnixLeFiles.add(f) rsline = line.rstrip() # right strip sline = rsline.strip() # full strip if len(rsline) > LINE_MAX_COLS: if not f in longLines: longLines[f] = [] longLines[f].append( (i+1, len(rsline)) ) res[0] += 1 if not sline: res[1] += 1 return res def IsDirExcluded(path: str) -> bool: if os.path.basename(path) == 'build_apps': return False for e in excludedDirs: if path.find(e) != -1: return True return False def IsFileExcluded(fname: str) -> bool: return fname in excludedFiles def AccumulateCounters(destArr: Dict[str, int], arr: Dict[str, int]): for ft in fileTypes: destArr[ft] += arr[ft] def PrintRow(cols: List[Any]) -> None: s = PREFIX for i, val in enumerate(cols): if i == 0: s += str(val).ljust(FLEN[i]) + " " else: s += str(val).rjust(FLEN[i]) + " " print(s) def GetEmptyPercStr(t: int, e: int) -> str: return str(round(100.0 * e/t, 1)) + "%" def PrintCounters(arr, eArr, total: int, eTot: int) -> None: PrintRow(["File type", "Tot", "Empty", "Empty%"]) for ft in fileTypes: vals = [ arr[ft], eArr[ft] ] if vals[0] > 0: PrintRow([ft] + vals + [GetEmptyPercStr(vals[0], vals[1])]) print(("-" * 50)) PrintRow(["Total:", total, eTot, GetEmptyPercStr(total, eTot)]) print("") def main(): global optPrintFileNames global optShowLongLines global optCheckLineEnding if len(sys.argv) > 1 and sys.argv[1] == '-v': optPrintFileNames = True del sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] == '-l': optShowLongLines = True del sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] == '-e': optCheckLineEnding = True del sys.argv[1] if len(sys.argv) > 1: destDirs = sys.argv[1:] else: destDirs = ["."] gLinesCount = {ft: 0 for ft in fileTypes} gEmptyLinesCount = {ft: 0 for ft in fileTypes} gTotal = 0 gEmptyTotal = 0 print("") # print an empty line for destDir in destDirs: if not os.path.isdir(destDir) or IsDirExcluded(destDir): continue linesByType = {t: 0 for t in fileTypes} emptyLinesByType = {t: 0 for t in fileTypes} total = 0 emptyTotal = 0 for folder, subfolders, files in os.walk(destDir): if IsDirExcluded(folder): continue for f in files: if IsFileExcluded(f): continue ft = GetFileType(f, folder) if ft is not None: c = CountLinesInFile(os.path.join(folder, f), ft) linesByType[ft] += c[0] emptyLinesByType[ft] += c[1] total += c[0] emptyTotal += c[1] gTotal += c[0] gEmptyTotal += c[1] print(("Number of lines in '{0}':".format(destDir))) AccumulateCounters(gLinesCount, linesByType) AccumulateCounters(gEmptyLinesCount, emptyLinesByType) PrintCounters(linesByType, emptyLinesByType, total, emptyTotal) if len(destDirs) > 1: print("\nCumulative number of lines:") PrintCounters(gLinesCount, gEmptyLinesCount, gTotal, gEmptyTotal) if optShowLongLines: if longLines: print("\nLong lines") print(("-" * 80)) for f in longLines: for lines in longLines[f]: print(("{0: <69} [{1: >3} cols]".\ format(f + ":" + str(lines[0]), lines[1]))) else: print("\nLong lines: NONE") if optCheckLineEnding: if nonUnixLeFiles: print("\nFiles with non-UNIX line ending:") for f in nonUnixLeFiles: print((" - {0}".format(f))) print("") else: print("\nFiles with non-UNIX line ending: NONE") ######################################################### if __name__ == "__main__": main() <file_sep>/****************************************************************************** * * Module Name: utdecode - Utility decoding routines (value-to-string) * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "amlcode.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utdecode") /* * Properties of the ACPI Object Types, both internal and external. * The table is indexed by values of ACPI_OBJECT_TYPE */ const UINT8 AcpiGbl_NsProperties[ACPI_NUM_NS_TYPES] = { ACPI_NS_NORMAL, /* 00 Any */ ACPI_NS_NORMAL, /* 01 Number */ ACPI_NS_NORMAL, /* 02 String */ ACPI_NS_NORMAL, /* 03 Buffer */ ACPI_NS_NORMAL, /* 04 Package */ ACPI_NS_NORMAL, /* 05 FieldUnit */ ACPI_NS_NEWSCOPE, /* 06 Device */ ACPI_NS_NORMAL, /* 07 Event */ ACPI_NS_NEWSCOPE, /* 08 Method */ ACPI_NS_NORMAL, /* 09 Mutex */ ACPI_NS_NORMAL, /* 10 Region */ ACPI_NS_NEWSCOPE, /* 11 Power */ ACPI_NS_NEWSCOPE, /* 12 Processor */ ACPI_NS_NEWSCOPE, /* 13 Thermal */ ACPI_NS_NORMAL, /* 14 BufferField */ ACPI_NS_NORMAL, /* 15 DdbHandle */ ACPI_NS_NORMAL, /* 16 Debug Object */ ACPI_NS_NORMAL, /* 17 DefField */ ACPI_NS_NORMAL, /* 18 BankField */ ACPI_NS_NORMAL, /* 19 IndexField */ ACPI_NS_NORMAL, /* 20 Reference */ ACPI_NS_NORMAL, /* 21 Alias */ ACPI_NS_NORMAL, /* 22 MethodAlias */ ACPI_NS_NORMAL, /* 23 Notify */ ACPI_NS_NORMAL, /* 24 Address Handler */ ACPI_NS_NEWSCOPE | ACPI_NS_LOCAL, /* 25 Resource Desc */ ACPI_NS_NEWSCOPE | ACPI_NS_LOCAL, /* 26 Resource Field */ ACPI_NS_NEWSCOPE, /* 27 Scope */ ACPI_NS_NORMAL, /* 28 Extra */ ACPI_NS_NORMAL, /* 29 Data */ ACPI_NS_NORMAL /* 30 Invalid */ }; /******************************************************************************* * * FUNCTION: AcpiUtGetRegionName * * PARAMETERS: Space ID - ID for the region * * RETURN: Decoded region SpaceId name * * DESCRIPTION: Translate a Space ID into a name string (Debug only) * ******************************************************************************/ /* Region type decoding */ const char *AcpiGbl_RegionTypes[ACPI_NUM_PREDEFINED_REGIONS] = { "SystemMemory", /* 0x00 */ "SystemIO", /* 0x01 */ "PCI_Config", /* 0x02 */ "EmbeddedControl", /* 0x03 */ "SMBus", /* 0x04 */ "SystemCMOS", /* 0x05 */ "PCIBARTarget", /* 0x06 */ "IPMI", /* 0x07 */ "GeneralPurposeIo", /* 0x08 */ "GenericSerialBus", /* 0x09 */ "PCC", /* 0x0A */ "PlatformRtMechanism" /* 0x0B */ }; const char * AcpiUtGetRegionName ( UINT8 SpaceId) { if (SpaceId >= ACPI_USER_REGION_BEGIN) { return ("UserDefinedRegion"); } else if (SpaceId == ACPI_ADR_SPACE_DATA_TABLE) { return ("DataTable"); } else if (SpaceId == ACPI_ADR_SPACE_FIXED_HARDWARE) { return ("FunctionalFixedHW"); } else if (SpaceId >= ACPI_NUM_PREDEFINED_REGIONS) { return ("InvalidSpaceId"); } return (AcpiGbl_RegionTypes[SpaceId]); } /******************************************************************************* * * FUNCTION: AcpiUtGetEventName * * PARAMETERS: EventId - Fixed event ID * * RETURN: Decoded event ID name * * DESCRIPTION: Translate a Event ID into a name string (Debug only) * ******************************************************************************/ /* Event type decoding */ static const char *AcpiGbl_EventTypes[ACPI_NUM_FIXED_EVENTS] = { "PM_Timer", "GlobalLock", "PowerButton", "SleepButton", "RealTimeClock", }; const char * AcpiUtGetEventName ( UINT32 EventId) { if (EventId > ACPI_EVENT_MAX) { return ("InvalidEventID"); } return (AcpiGbl_EventTypes[EventId]); } /******************************************************************************* * * FUNCTION: AcpiUtGetTypeName * * PARAMETERS: Type - An ACPI object type * * RETURN: Decoded ACPI object type name * * DESCRIPTION: Translate a Type ID into a name string (Debug only) * ******************************************************************************/ /* * Elements of AcpiGbl_NsTypeNames below must match * one-to-one with values of ACPI_OBJECT_TYPE * * The type ACPI_TYPE_ANY (Untyped) is used as a "don't care" when searching; * when stored in a table it really means that we have thus far seen no * evidence to indicate what type is actually going to be stored for this & entry. */ static const char AcpiGbl_BadType[] = "UNDEFINED"; /* Printable names of the ACPI object types */ static const char *AcpiGbl_NsTypeNames[] = { /* 00 */ "Untyped", /* 01 */ "Integer", /* 02 */ "String", /* 03 */ "Buffer", /* 04 */ "Package", /* 05 */ "FieldUnit", /* 06 */ "Device", /* 07 */ "Event", /* 08 */ "Method", /* 09 */ "Mutex", /* 10 */ "Region", /* 11 */ "Power", /* 12 */ "Processor", /* 13 */ "Thermal", /* 14 */ "BufferField", /* 15 */ "DdbHandle", /* 16 */ "DebugObject", /* 17 */ "RegionField", /* 18 */ "BankField", /* 19 */ "IndexField", /* 20 */ "Reference", /* 21 */ "Alias", /* 22 */ "MethodAlias", /* 23 */ "Notify", /* 24 */ "AddrHandler", /* 25 */ "ResourceDesc", /* 26 */ "ResourceFld", /* 27 */ "Scope", /* 28 */ "Extra", /* 29 */ "Data", /* 30 */ "Invalid" }; const char * AcpiUtGetTypeName ( ACPI_OBJECT_TYPE Type) { if (Type > ACPI_TYPE_INVALID) { return (AcpiGbl_BadType); } return (AcpiGbl_NsTypeNames[Type]); } const char * AcpiUtGetObjectTypeName ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_FUNCTION_TRACE (UtGetObjectTypeName); if (!ObjDesc) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Null Object Descriptor\n")); return_STR ("[NULL Object Descriptor]"); } /* These descriptor types share a common area */ if ((ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) && (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_NAMED)) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Invalid object descriptor type: 0x%2.2X [%s] (%p)\n", ACPI_GET_DESCRIPTOR_TYPE (ObjDesc), AcpiUtGetDescriptorName (ObjDesc), ObjDesc)); return_STR ("Invalid object"); } return_STR (AcpiUtGetTypeName (ObjDesc->Common.Type)); } /******************************************************************************* * * FUNCTION: AcpiUtGetNodeName * * PARAMETERS: Object - A namespace node * * RETURN: ASCII name of the node * * DESCRIPTION: Validate the node and return the node's ACPI name. * ******************************************************************************/ const char * AcpiUtGetNodeName ( void *Object) { ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) Object; /* Must return a string of exactly 4 characters == ACPI_NAMESEG_SIZE */ if (!Object) { return ("NULL"); } /* Check for Root node */ if ((Object == ACPI_ROOT_OBJECT) || (Object == AcpiGbl_RootNode)) { return ("\"\\\" "); } /* Descriptor must be a namespace node */ if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED) { return ("####"); } /* * Ensure name is valid. The name was validated/repaired when the node * was created, but make sure it has not been corrupted. */ AcpiUtRepairName (Node->Name.Ascii); /* Return the name */ return (Node->Name.Ascii); } /******************************************************************************* * * FUNCTION: AcpiUtGetDescriptorName * * PARAMETERS: Object - An ACPI object * * RETURN: Decoded name of the descriptor type * * DESCRIPTION: Validate object and return the descriptor type * ******************************************************************************/ /* Printable names of object descriptor types */ static const char *AcpiGbl_DescTypeNames[] = { /* 00 */ "Not a Descriptor", /* 01 */ "Cached Object", /* 02 */ "State-Generic", /* 03 */ "State-Update", /* 04 */ "State-Package", /* 05 */ "State-Control", /* 06 */ "State-RootParseScope", /* 07 */ "State-ParseScope", /* 08 */ "State-WalkScope", /* 09 */ "State-Result", /* 10 */ "State-Notify", /* 11 */ "State-Thread", /* 12 */ "Tree Walk State", /* 13 */ "Parse Tree Op", /* 14 */ "Operand Object", /* 15 */ "Namespace Node" }; const char * AcpiUtGetDescriptorName ( void *Object) { if (!Object) { return ("NULL OBJECT"); } if (ACPI_GET_DESCRIPTOR_TYPE (Object) > ACPI_DESC_TYPE_MAX) { return ("Not a Descriptor"); } return (AcpiGbl_DescTypeNames[ACPI_GET_DESCRIPTOR_TYPE (Object)]); } /******************************************************************************* * * FUNCTION: AcpiUtGetReferenceName * * PARAMETERS: Object - An ACPI reference object * * RETURN: Decoded name of the type of reference * * DESCRIPTION: Decode a reference object sub-type to a string. * ******************************************************************************/ /* Printable names of reference object sub-types */ static const char *AcpiGbl_RefClassNames[] = { /* 00 */ "Local", /* 01 */ "Argument", /* 02 */ "RefOf", /* 03 */ "Index", /* 04 */ "DdbHandle", /* 05 */ "Named Object", /* 06 */ "Debug" }; const char * AcpiUtGetReferenceName ( ACPI_OPERAND_OBJECT *Object) { if (!Object) { return ("NULL Object"); } if (ACPI_GET_DESCRIPTOR_TYPE (Object) != ACPI_DESC_TYPE_OPERAND) { return ("Not an Operand object"); } if (Object->Common.Type != ACPI_TYPE_LOCAL_REFERENCE) { return ("Not a Reference object"); } if (Object->Reference.Class > ACPI_REFCLASS_MAX) { return ("Unknown Reference class"); } return (AcpiGbl_RefClassNames[Object->Reference.Class]); } /******************************************************************************* * * FUNCTION: AcpiUtGetMutexName * * PARAMETERS: MutexId - The predefined ID for this mutex. * * RETURN: Decoded name of the internal mutex * * DESCRIPTION: Translate a mutex ID into a name string (Debug only) * ******************************************************************************/ /* Names for internal mutex objects, used for debug output */ static const char *AcpiGbl_MutexNames[ACPI_NUM_MUTEX] = { "ACPI_MTX_Interpreter", "ACPI_MTX_Namespace", "ACPI_MTX_Tables", "ACPI_MTX_Events", "ACPI_MTX_Caches", "ACPI_MTX_Memory", }; const char * AcpiUtGetMutexName ( UINT32 MutexId) { if (MutexId > ACPI_MAX_MUTEX) { return ("Invalid Mutex ID"); } return (AcpiGbl_MutexNames[MutexId]); } #if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER) /* * Strings and procedures used for debug only */ /******************************************************************************* * * FUNCTION: AcpiUtGetNotifyName * * PARAMETERS: NotifyValue - Value from the Notify() request * * RETURN: Decoded name for the notify value * * DESCRIPTION: Translate a Notify Value to a notify namestring. * ******************************************************************************/ /* Names for Notify() values, used for debug output */ static const char *AcpiGbl_GenericNotify[ACPI_GENERIC_NOTIFY_MAX + 1] = { /* 00 */ "Bus Check", /* 01 */ "Device Check", /* 02 */ "Device Wake", /* 03 */ "Eject Request", /* 04 */ "Device Check Light", /* 05 */ "Frequency Mismatch", /* 06 */ "Bus Mode Mismatch", /* 07 */ "Power Fault", /* 08 */ "Capabilities Check", /* 09 */ "Device PLD Check", /* 0A */ "Reserved", /* 0B */ "System Locality Update", /* 0C */ "Reserved (was previously Shutdown Request)", /* Reserved in ACPI 6.0 */ /* 0D */ "System Resource Affinity Update", /* 0E */ "Heterogeneous Memory Attributes Update", /* ACPI 6.2 */ /* 0F */ "Error Disconnect Recover" /* ACPI 6.3 */ }; static const char *AcpiGbl_DeviceNotify[5] = { /* 80 */ "Status Change", /* 81 */ "Information Change", /* 82 */ "Device-Specific Change", /* 83 */ "Device-Specific Change", /* 84 */ "Reserved" }; static const char *AcpiGbl_ProcessorNotify[5] = { /* 80 */ "Performance Capability Change", /* 81 */ "C-State Change", /* 82 */ "Throttling Capability Change", /* 83 */ "Guaranteed Change", /* 84 */ "Minimum Excursion" }; static const char *AcpiGbl_ThermalNotify[5] = { /* 80 */ "Thermal Status Change", /* 81 */ "Thermal Trip Point Change", /* 82 */ "Thermal Device List Change", /* 83 */ "Thermal Relationship Change", /* 84 */ "Reserved" }; const char * AcpiUtGetNotifyName ( UINT32 NotifyValue, ACPI_OBJECT_TYPE Type) { /* 00 - 0F are "common to all object types" (from ACPI Spec) */ if (NotifyValue <= ACPI_GENERIC_NOTIFY_MAX) { return (AcpiGbl_GenericNotify[NotifyValue]); } /* 10 - 7F are reserved */ if (NotifyValue <= ACPI_MAX_SYS_NOTIFY) { return ("Reserved"); } /* 80 - 84 are per-object-type */ if (NotifyValue <= ACPI_SPECIFIC_NOTIFY_MAX) { switch (Type) { case ACPI_TYPE_ANY: case ACPI_TYPE_DEVICE: return (AcpiGbl_DeviceNotify [NotifyValue - 0x80]); case ACPI_TYPE_PROCESSOR: return (AcpiGbl_ProcessorNotify [NotifyValue - 0x80]); case ACPI_TYPE_THERMAL: return (AcpiGbl_ThermalNotify [NotifyValue - 0x80]); default: return ("Target object type does not support notifies"); } } /* 84 - BF are device-specific */ if (NotifyValue <= ACPI_MAX_DEVICE_SPECIFIC_NOTIFY) { return ("Device-Specific"); } /* C0 and above are hardware-specific */ return ("Hardware-Specific"); } /******************************************************************************* * * FUNCTION: AcpiUtGetArgumentTypeName * * PARAMETERS: ArgType - an ARGP_* parser argument type * * RETURN: Decoded ARGP_* type * * DESCRIPTION: Decode an ARGP_* parser type, as defined in the amlcode.h file, * and used in the acopcode.h file. For example, ARGP_TERMARG. * Used for debug only. * ******************************************************************************/ static const char *AcpiGbl_ArgumentType[20] = { /* 00 */ "Unknown ARGP", /* 01 */ "ByteData", /* 02 */ "ByteList", /* 03 */ "CharList", /* 04 */ "DataObject", /* 05 */ "DataObjectList", /* 06 */ "DWordData", /* 07 */ "FieldList", /* 08 */ "Name", /* 09 */ "NameString", /* 0A */ "ObjectList", /* 0B */ "PackageLength", /* 0C */ "SuperName", /* 0D */ "Target", /* 0E */ "TermArg", /* 0F */ "TermList", /* 10 */ "WordData", /* 11 */ "QWordData", /* 12 */ "SimpleName", /* 13 */ "NameOrRef" }; const char * AcpiUtGetArgumentTypeName ( UINT32 ArgType) { if (ArgType > ARGP_MAX) { return ("Unknown ARGP"); } return (AcpiGbl_ArgumentType[ArgType]); } #endif /******************************************************************************* * * FUNCTION: AcpiUtValidObjectType * * PARAMETERS: Type - Object type to be validated * * RETURN: TRUE if valid object type, FALSE otherwise * * DESCRIPTION: Validate an object type * ******************************************************************************/ BOOLEAN AcpiUtValidObjectType ( ACPI_OBJECT_TYPE Type) { if (Type > ACPI_TYPE_LOCAL_MAX) { /* Note: Assumes all TYPEs are contiguous (external/local) */ return (FALSE); } return (TRUE); } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) # # Project name and base version. # # Note: the version here is the one currently *under development*. For released # versions, checkout GIT tags like "release-0.1.1". # project(tilck VERSION 0.1.4 LANGUAGES C CXX ASM) include(CheckCCompilerFlag) include(other/cmake/utils.cmake) include(other/cmake/errors.cmake) set(CMAKE_VERBOSE_MAKEFILE off) set(BUILD_SHARED_LIBRARIES off) # disable shared libs globally set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS) # disable -rdynamic globally set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) # disable -rdynamic globally if (NOT ${CMAKE_VERSION} VERSION_LESS "3.12.0") set(GLOB_CONF_DEP CONFIGURE_DEPENDS) endif() set(DEFAULT_TARGET_ARCH "i386") if ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") set(HOST_ARCH "x86_64") set(HOST_ARCH_BITS 64) set(HOST_ARCH_FAMILY "generic_x86") elseif ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64") set(HOST_ARCH "x86_64") set(HOST_ARCH_BITS 64) set(HOST_ARCH_FAMILY "generic_x86") elseif ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686") set(HOST_ARCH "i386") set(HOST_ARCH_BITS 32) set(HOST_ARCH_FAMILY "generic_x86") elseif ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i386") set(HOST_ARCH "i386") set(HOST_ARCH_BITS 32) set(HOST_ARCH_FAMILY "generic_x86") elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64") set(HOST_ARCH "aarch64") set(HOST_ARCH_BITS 64) set(HOST_ARCH_FAMILY "arm") endif() # BEGIN [Environment-controlled "sticky" cache variables] # Main variables define_env_cache_str_var(TCROOT_PARENT ${CMAKE_SOURCE_DIR}) define_env_cache_str_var(TCROOT ${TCROOT_PARENT}/toolchain2) define_env_cache_str_var(ARCH ${DEFAULT_TARGET_ARCH}) define_env_cache_bool_var(TEST_GCOV) define_env_cache_bool_var(KERNEL_GCOV) # USE_SYSCC-related variables define_env_cache_bool_var(USE_SYSCC) define_env_cache_str_var(GCOV "gcov") # Debug cache variables # We don't really need to cache the values of CC/CXX, but is useful to that # in order to prevent user errors. Since CC/CXX affect the build only the first # time CMake is run, it makes sense to check for the next runs whether the env # vars CC/CXX changed (if set) by the user or an incorrect script. In case # they are, we have to stop the build because their new value will be otherwise # completely ignored. In order words, fail *early*. define_env_cache_str_var(CC "<unset>") define_env_cache_str_var(CXX "<unset>") # END [Environment-controlled "sticky" cache variables] # BEGIN [Setup of toolchain-related variables] set(BUILD_SCRIPTS ${CMAKE_SOURCE_DIR}/scripts/build_scripts) set(BUILD_APPS ${CMAKE_BINARY_DIR}/scripts/build_apps) set(BTC_SCRIPT ${CMAKE_SOURCE_DIR}/scripts/build_toolchain) set(COVERAGE_HTML_DIR ${CMAKE_BINARY_DIR}/coverage_html) set(TCROOT_BA ${TCROOT}/host) set(LCOV_VER "1.15") file(RELATIVE_PATH BTC_SCRIPT_REL ${CMAKE_SOURCE_DIR} ${BTC_SCRIPT}) file(RELATIVE_PATH TCROOT_REL ${CMAKE_SOURCE_DIR} ${TCROOT}) if (NOT EXISTS ${TCROOT}) message(FATAL_ERROR "Toolchain not found: run ${BTC_SCRIPT_REL} first.") endif() # # Use as default value for GCC_TC_VER, the contents of: # ${TCROOT}/.gcc_tc_ver_${ARCH} # That file has been generated by the `build_toolchain` script which used # the GCC_TC_VER environment variable or the default value if it was unset. # if (EXISTS ${TCROOT}/.gcc_tc_ver) if (NOT "$ENV{CI}") # Small hack to support older toolchains (and upgrade them) # TODO: drop this once we upgrade to toolchain3 file(RENAME ${TCROOT}/.gcc_tc_ver ${TCROOT}/.gcc_tc_ver_i386) endif() endif() if (EXISTS ${TCROOT}/.gcc_tc_ver_${ARCH}) file(READ ${TCROOT}/.gcc_tc_ver_${ARCH} SAVED_GCC_TC_VAR) else() if (NOT "$ENV{CI}") message(FATAL_ERROR "${TCROOT}/.gcc_tc_ver_${ARCH} not found: run ${BTC_SCRIPT_REL}") else() if (EXISTS ${TCROOT}/.gcc_tc_ver) # Support older pre-built toolchains in docker images used by CI # TODO: drop this once we upgrade to toolchain3 file(READ ${TCROOT}/.gcc_tc_ver SAVED_GCC_TC_VAR) endif() # Small hack to make older container builds to work set(SAVED_GCC_TC_VAR "6.4.0") endif() endif() # Define our special "sticky" env. variable GCC_TC_VER define_env_cache_str_var(GCC_TC_VER "${SAVED_GCC_TC_VAR}") # END [Setup of toolchain-related variables] if (USE_SYSCC) set(SYS_CC "${CMAKE_C_COMPILER}") set(SYS_CXX "${CMAKE_CXX_COMPILER}") endif() if ("${ARCH}" STREQUAL "i386") if ("${HOST_ARCH}" STREQUAL "${ARCH}") if (USE_SYSCC) show_same_arch_build_warning() else() show_missing_use_syscc_error() endif() endif() endif() # Reset the default flags set(CMAKE_C_FLAGS "") set(CMAKE_C_FLAGS_INT "") set(CMAKE_C_FLAGS_DEBUG "") set(CMAKE_C_FLAGS_MINSIZEREL "") set(CMAKE_C_FLAGS_RELWITHDEBINFO "") set(CMAKE_C_FLAGS_RELEASE "") set(CMAKE_CXX_FLAGS "") set(CMAKE_CXX_FLAGS_INT "") set(CMAKE_CXX_FLAGS_DEBUG "") set(CMAKE_CXX_FLAGS_MINSIZEREL "") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "") set(CMAKE_CXX_FLAGS_RELEASE "") # Compile options set(ARCH_GTESTS OFF CACHE BOOL "Build unit tests for the target arch") # Non-boolean kernel options set(TIMER_HZ 250 CACHE STRING "System timer HZ") set(USER_STACK_PAGES 16 CACHE STRING "User apps stack size in pages") set(TTY_COUNT 2 CACHE STRING "Number of TTYs (default)") set(MAX_HANDLES 16 CACHE STRING "Max handles/process (keep small)") set(FBCON_BIGFONT_THR 160 CACHE STRING "Max term cols with 8x16 font. After that, a 16x32 font will be used") # Other non-boolean options set(FATPART_CLUSTER_SIZE 8 CACHE STRING "Cluster size (in sectors) of the FAT ramdisk") set(TERM_SCROLL_LINES 5 CACHE STRING "Number of lines to scroll on Shift+PgUp/PgDown") set( USERAPPS_CFLAGS "-ggdb -Os -Wall -Wno-unused-parameter" CACHE STRING "Build flags for C/C++ user programs" ) # Kernel options (enabled by default) set(KRN_TRACK_NESTED_INTERR ON CACHE BOOL "Track the nested interrupts") set(PANIC_SHOW_STACKTRACE ON CACHE BOOL "Show the stacktrace in case of a kernel panic") set(DEBUG_CHECKS ON CACHE BOOL "Keep checking ASSERTs and other debug checks even in release builds") set(KERNEL_SELFTESTS ON CACHE BOOL "Compile-in self-tests in the kernel") set(KERNEL_STACK_ISOLATION ON CACHE BOOL "Put the kernel stack in hi the vmem in isolated pages") set(FB_CONSOLE_BANNER ON CACHE BOOL "Show a top banner when using fb_console") set(FB_CONSOLE_CURSOR_BLINK ON CACHE BOOL "Support cursor blinking in the fb_console") if ($ENV{TILCK_NO_LOGO}) set(KERNEL_SHOW_LOGO OFF CACHE BOOL "Show Tilck's logo after boot") else() set(KERNEL_SHOW_LOGO ON CACHE BOOL "Show Tilck's logo after boot") endif() set(KERNEL_SYMBOLS ON CACHE BOOL "Keep symbol tables loaded in the kernel for backtraces and self tests") set(BOOTLOADER_LEGACY ON CACHE BOOL "Build the legacy bootloader") set(BOOTLOADER_EFI ON CACHE BOOL "Build the EFI bootloader") set(SERIAL_CON_IN_VIDEO_MODE ON CACHE BOOL "Always open a console on /dev/ttyS0 even in video mode (w/o -sercon)") set(KRN_PRINTK_ON_CURR_TTY ON CACHE BOOL "Make printk() always flush on the current TTY") set(TYPICAL_DEVEL_USERAPPS ON CACHE BOOL "Include in Tilck's ramdisk some apps for testing the kernel") set(BOOT_INTERACTIVE ON CACHE BOOL "Have user-interactive commands in the bootloaders") set(KERNEL_64BIT_OFFT ON CACHE BOOL "Make offt be 64-bit even on 32-bit systems") set(KRN_CLOCK_DRIFT_COMP ON CACHE BOOL "Compensate periodically for the clock drift in the system time") # Kernel options (disabled by default) set(KRN_PAGE_FAULT_PRINTK OFF CACHE BOOL "Use printk() to display info when a process is killed due to page fault") set(KRN_NO_SYS_WARN OFF CACHE BOOL "Show a warning when a not-implemented syscall is called") set(KERNEL_UBSAN OFF CACHE BOOL "Turn on the UBSAN for the kernel") set(KERNEL_BIG_IO_BUF OFF CACHE BOOL "Use a much-bigger buffer for I/O") set(TERM_BIG_SCROLL_BUF OFF CACHE BOOL "Use a 4x bigger scrollback buffer for the terminal") set(KERNEL_SYSCC OFF CACHE BOOL "Use system's compiler for the kernel instead of toolchain's one") set(KERNEL_FORCE_TC_ISYSTEM OFF CACHE BOOL "\ DANGEROUS. Do NOT use for other than static analysis builds. \ BRUTALLY forces the build system to use tc's sysroot \ for system headers even when a system compiler is used.\ ") set(FORK_NO_COW OFF CACHE BOOL "Make fork() to perform a full-copy instead of using copy-on-write") set(MMAP_NO_COW OFF CACHE BOOL "Make mmap() to allocate real memory instead mapping the zero-page + COW") set(PANIC_SHOW_REGS OFF CACHE BOOL "Show the content of the main registers in case of kernel panic") set(KMALLOC_HEAVY_STATS OFF CACHE BOOL "Count the number of allocations for each distinct size") set(KMALLOC_FREE_MEM_POISONING OFF CACHE BOOL "Make kfree() to poison the memory") set(KMALLOC_SUPPORT_DEBUG_LOG OFF CACHE BOOL "Compile-in kmalloc debug messages") set(KMALLOC_SUPPORT_LEAK_DETECTOR OFF CACHE BOOL "Compile-in kmalloc's leak detector") set(BOOTLOADER_POISON_MEMORY OFF CACHE BOOL "Make the bootloader to poison all the available memory") set(WCONV OFF CACHE BOOL "Compile with -Wconversion when clang is used") set(FAT_TEST_DIR OFF CACHE BOOL "Create a test dir with many files in the FAT32 init ramdisk") set(PS2_DO_SELFTEST OFF CACHE BOOL "Do PS/2 controller selftests in init_kb()") set(PS2_VERBOSE_DEBUG_LOG OFF CACHE BOOL "Enable developer-only verbose logging") set(FB_CONSOLE_USE_ALT_FONTS OFF CACHE BOOL "Use the fonts in other/alt_fonts instead of the default ones") set(KRN_RESCHED_ENABLE_PREEMPT OFF CACHE BOOL "Check for need_resched and yield in enable_preemption()") set(TINY_KERNEL OFF CACHE BOOL "\ Advanced option, use carefully. Forces the Tilck kernel \ to be as small as possible. Incompatibile with many modules \ like console, fb, tracing and several kernel options like \ KERNEL_SELFTESTS") set(INIT_REPORT_PROC_EXIT OFF CACHE BOOL "Make init to report on TTY when children (often acquired) exit") set(PREFERRED_GFX_MODE_W "800" CACHE STRING "Preferred video mode (width)") set(PREFERRED_GFX_MODE_H "600" CACHE STRING "Preferred video mode (height)") set(KMALLOC_FIRST_HEAP_SIZE_KB "auto" CACHE STRING "Size in KB of kmalloc's first heap. Must be multiple of 64.") set(PCI_VENDORS_LIST OFF CACHE BOOL "Compile-in the list of all known PCI vendors") set(EFI_BOOTLOADER_DEBUG OFF CACHE BOOL "Enable an early DEBUG dialog (see docs/debugging.md)") set(FB_CONSOLE_FAILSAFE_OPT OFF CACHE BOOL "Optimize fb_console's failsafe mode for older machines") list( APPEND no_arch_modules_whitelist console tracing sysfs ) list( APPEND tiny_kernel_modules_blacklist fb console tracing kb8042 acpi ) list( APPEND disabled_modules_list # No modules in this list, at the moment ) file(GLOB modules ${GLOB_CONF_DEP} "${CMAKE_SOURCE_DIR}/modules/*") foreach(modpath ${modules}) get_filename_component(modname ${modpath} NAME_WE) if (NOT IS_DIRECTORY ${modpath}) continue() endif() if (TINY_KERNEL) list(FIND tiny_kernel_modules_blacklist ${modname} _index) if (${_index} GREATER -1) if (MOD_${modname}) message(WARNING "TINY_KERNEL=1, force-setting MOD_${modname}=0") set(MOD_${modname} OFF) endif() endif() unset(_index) endif(TINY_KERNEL) list(APPEND modules_list ${modname}) list(FIND disabled_modules_list ${modname} _index) if (${_index} GREATER -1) set(MOD_${modname} OFF CACHE BOOL "Compile-in the ${modname} module") else() set(MOD_${modname} ON CACHE BOOL "Compile-in the ${modname} module") endif() endforeach() if (TINY_KERNEL) if (NOT ${CMAKE_BUILD_TYPE} STREQUAL "MinSizeRel") message(FATAL_ERROR "TINY_KERNEL=1 requires CMAKE_BUILD_TYPE=MinSizeRel") endif() if (KERNEL_GCOV) message(FATAL_ERROR "TINY_KERNEL=1 requires KERNEL_GCOV=0") endif() if (KERNEL_SELFTESTS) message(WARNING "TINY_KERNEL=1, force-setting KERNEL_SELFTESTS=0") set(KERNEL_SELFTESTS OFF) endif() if (KERNEL_SYMBOLS) message(WARNING "TINY_KERNEL=1, force-setting KERNEL_SYMBOLS=0") set(KERNEL_SYMBOLS OFF) endif() if (KERNEL_SHOW_LOGO) message(WARNING "TINY_KERNEL=1, force-setting KERNEL_SHOW_LOGO=0") set(KERNEL_SHOW_LOGO OFF) endif() if (PCI_VENDORS_LIST) message(WARNING "TINY_KERNEL=1, force-setting PCI_VENDORS_LIST=0") set(PCI_VENDORS_LIST OFF) endif() endif() if (KMALLOC_FIRST_HEAP_SIZE_KB STREQUAL "auto") if (TINY_KERNEL) set(KMALLOC_FIRST_HEAP_SIZE_KB_VAL 64) else() set(KMALLOC_FIRST_HEAP_SIZE_KB_VAL 128) endif() else() set(KMALLOC_FIRST_HEAP_SIZE_KB_VAL ${KMALLOC_FIRST_HEAP_SIZE_KB}) endif() # Create a list with all the kernel opts, in order to dump it later # ------------------------------------------------------------------- list( APPEND kernel_opts_list # Various options ARCH USE_SYSCC ARCH_GTESTS # Non-boolean options TIMER_HZ USER_STACK_PAGES FATPART_CLUSTER_SIZE PREFERRED_GFX_MODE_W PREFERRED_GFX_MODE_H KMALLOC_FIRST_HEAP_SIZE_KB KMALLOC_FIRST_HEAP_SIZE_KB_VAL # Boolean options ENABLED by default KRN_TRACK_NESTED_INTERR PANIC_SHOW_STACKTRACE DEBUG_CHECKS KERNEL_SELFTESTS KERNEL_STACK_ISOLATION FB_CONSOLE_BANNER KRN_PRINTK_ON_CURR_TTY KERNEL_SHOW_LOGO KERNEL_SYMBOLS BOOTLOADER_LEGACY BOOTLOADER_EFI BOOT_INTERACTIVE KRN_NO_SYS_WARN KERNEL_64BIT_OFFT KRN_CLOCK_DRIFT_COMP # Boolean options DISABLED by default KERNEL_UBSAN KERNEL_BIG_IO_BUF KRN_RESCHED_ENABLE_PREEMPT TERM_BIG_SCROLL_BUF TEST_GCOV KERNEL_GCOV KERNEL_SYSCC KERNEL_FORCE_TC_ISYSTEM FORK_NO_COW MMAP_NO_COW PANIC_SHOW_REGS KMALLOC_HEAVY_STATS KMALLOC_FREE_MEM_POISONING KMALLOC_SUPPORT_DEBUG_LOG KMALLOC_SUPPORT_LEAK_DETECTOR BOOTLOADER_POISON_MEMORY WCONV FAT_TEST_DIR PS2_DO_SELFTEST PS2_VERBOSE_DEBUG_LOG FB_CONSOLE_USE_ALT_FONTS TINY_KERNEL INIT_REPORT_PROC_EXIT PCI_VENDORS_LIST EFI_BOOTLOADER_DEBUG FB_CONSOLE_FAILSAFE_OPT ) ########################################################### if (${ARCH} STREQUAL "i386") set(ARCH_SHORT "x86") set(ARCH_FAMILY "generic_x86") set(ARCH_ELF_NAME "elf32-i386") set(ARCH_LD_OUTPUT "elf_i386") set(ARCH_BFD "i386") set(ARCH_GCC_TC "i686") set(ARCH_GCC_FLAGS "-m32 -march=${ARCH_GCC_TC}") set(ARCH_BITS 32) # Fundamental kernel MM constants set(KERNEL_BASE_VA 0xC0000000) # Better not touch! set(KERNEL_PADDR 0x00100000) # Better not touch! set(LINEAR_MAPPING_MB 896) # Better not touch! elseif(${ARCH} STREQUAL "x86_64") set(ARCH_SHORT "x86_64") set(ARCH_FAMILY "generic_x86") set(ARCH_ELF_NAME "elf64-x86-64") set(ARCH_LD_OUTPUT "elf_x86_64") set(ARCH_BFD "i386:x86-64") set(ARCH_GCC_TC "x86_64") set(ARCH_GCC_FLAGS "") set(ARCH_BITS 64) # Fundamental kernel MM constants set(KERNEL_BASE_VA 0x100000000000) # +16 TB set(KERNEL_PADDR 0x00100000) # Better not touch! set(LINEAR_MAPPING_MB 4096) # Might be updated. else() message(FATAL_ERROR "Architecture '${ARCH}' not supported.") endif() message(STATUS "TCROOT: ${TCROOT}") message(STATUS "GCC_TC_VER: ${GCC_TC_VER}") set(BUSYBOX_CONFIG ${TCROOT}/${ARCH}/busybox/.config) set(NCURSES_INST ${TCROOT}/${ARCH}/ncurses/install) string(REPLACE "." "_" GCC_TC_VER_ "${GCC_TC_VER}") set(GCC_NAME_PFX gcc_${GCC_TC_VER_}_${ARCH}) # BEGIN [ARCH-dependent paths] # Main toolchain (musl) set(GCC_TC_ROOT ${TCROOT_BA}/${GCC_NAME_PFX}_musl) set(GCC_TC_LIBC_DIRNAME ${ARCH_GCC_TC}-buildroot-linux-musl) set(GCC_TC_SYSROOT ${GCC_TC_ROOT}/${GCC_TC_LIBC_DIRNAME}/sysroot) set(GCC_TC_ISYSTEM ${GCC_TC_SYSROOT}/usr/include) set(GCC_TOOLCHAIN ${GCC_TC_ROOT}/bin) # Glibc toolchain set(GCC_TC_GLIBC_ROOT ${TCROOT_BA}/${GCC_NAME_PFX}_glibc) set(GCC_TOOLCHAIN_GLIBC ${GCC_TC_GLIBC_ROOT}/bin) # END [ARCH-dependent paths] if (USE_SYSCC) if (NOT EXISTS ${TCROOT}/${ARCH}/musl/install/bin/musl-gcc) show_no_musl_syscc_error() endif() endif() set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) message(STATUS "SYS CC compiler name: ${CMAKE_C_COMPILER_ID}") message(STATUS "SYS CXX compiler name: ${CMAKE_CXX_COMPILER_ID}") # Include the main lists of compiler flags used in the project include(other/cmake/compiler_flags.cmake) # Include the funcs for building the kernel modules, used both by the kernel # and the gtests targets. include(other/cmake/wrapped_syms.cmake) include(other/cmake/build_modules.cmake) foreach (opt ${kernel_opts_list}) message(STATUS "${opt} = ${${opt}}") endforeach() message(STATUS "****************** KERNEL MODULES *******************") foreach (mod ${modules_list}) message(STATUS "Module ${mod} = ${MOD_${mod}}") endforeach() message(STATUS "**************** END KERNEL MODULES *****************") # Config validation checks # ----------------------------------- if (NOT ${MOD_console} AND NOT ${MOD_serial}) message(FATAL_ERROR "Cannot disable both the `console` and `serial` mods") endif() foreach (mod ${modules_list}) set(deps_file "${CMAKE_SOURCE_DIR}/modules/${mod}/module_deps") if (NOT ${MOD_${mod}}) continue() # Module not compiled-in: skip it. endif() list(APPEND enabled_modules_list ${mod}) if (NOT EXISTS ${deps_file}) continue() # No dependencies. Great! endif() # Read the dependencies in the `deps` list file(STRINGS ${deps_file} deps) foreach (d ${deps}) if (NOT ${MOD_${d}}) message(FATAL_ERROR "The module '${mod}' requires the module '${d}'") endif() endforeach() unset(deps) unset(deps_file) endforeach() JOIN("${enabled_modules_list}" ${SPACE} ENABLED_MODULES_LIST) unset(enabled_modules_list) ################################################################################ set(BOOTLOADER_BIN_FILE ${CMAKE_BINARY_DIR}/boot/legacy/bootloader.bin) if ("${HOST_ARCH}" STREQUAL "x86_64") set(EFI_x86_64_FILE ${CMAKE_BINARY_DIR}/boot/efi/BOOTX64.EFI) endif() set(EFI_ia32_FILE ${CMAKE_BINARY_DIR}/boot/efi/BOOTIA32.EFI) set(KERNEL_UNSTRIPPED ${CMAKE_BINARY_DIR}/tilck_unstripped) set(KERNEL_FILE ${CMAKE_BINARY_DIR}/tilck) set(IMG_FILE ${CMAKE_BINARY_DIR}/tilck.img) set(TILCK_DEVSHELL_PATH "/initrd/usr/bin/devshell") if (${BOOTLOADER_LEGACY} OR ${BOOTLOADER_EFI}) set(KERNEL_BOOTPART_PATH "tilck") endif() ################################################################################ # Bootloaders, build-scripts and link-scripts config set(SECTOR_SIZE 512) # CHS Logic sector size. Do *not* touch! set(CHS_HPC 16) # CHS heads per cylinder. Do *not* touch! set(CHS_SPT 63) # CHS sectors per track. Do *not* touch! set(BL_ST2_DATA_SEG 0x2000) # Better not touch! set(EARLY_BOOT_SZ 4096) # Better not touch! set(STAGE3_ENTRY_OFF 4096) # Better not touch! set(DISK_UUID 0x4906062b) # UUID of Tilck's disk image ${IMG_FILE} set(MAX_BOOTLOADER_BIN_SZ_KB 64) # Max size of bootloader.bin (keep updated!) set(IMG_SZ_MB 36) # Total size of tilck.img if (KERNEL_UBSAN) set(INITRD_SZ_MB 30) # Size of the initrd RAMDISK in MB set(BOOTPART_SZ_SEC 10240) # Size of the boot partition in sectors else() set(INITRD_SZ_MB 32) # Size of the initrd RAMDISK in MB set(BOOTPART_SZ_SEC 6144) # Size of the boot partition in sectors endif() math(EXPR IMG_SZ_SEC "${IMG_SZ_MB} * 1024 * 1024 / ${SECTOR_SIZE}") math(EXPR BOOT_SECTORS "${MAX_BOOTLOADER_BIN_SZ_KB}*1024/${SECTOR_SIZE}") math(EXPR BOOTPART_SEC "${BOOT_SECTORS}") math(EXPR BOOTPART_LAST_SEC "${BOOTPART_SEC} + ${BOOTPART_SZ_SEC} - 1") math(EXPR INITRD_SECTOR "${BOOTPART_LAST_SEC} + 1") math(EXPR INITRD_SZ_SEC "${INITRD_SZ_MB} * 1048576 / ${SECTOR_SIZE}") math(EXPR INITRD_LAST_SEC "${INITRD_SECTOR} + ${INITRD_SZ_SEC} - 1") math(EXPR SEC_PER_CYL "${CHS_HPC} * ${CHS_SPT}") math(EXPR CHS_CYLS "(${IMG_SZ_SEC} + ${SEC_PER_CYL} - 1) / ${SEC_PER_CYL}") unset(SEC_PER_CYL) # For qemu run scripts set(QEMU_CHS_GEOM "cyls=${CHS_CYLS},heads=${CHS_HPC},secs=${CHS_SPT}") set(QEMU_RAM_OPT "") # use qemu's default: 128 MB set(QEMU_COMMON_OPTS "-rtc base=localtime") execute_process(COMMAND uname -r OUTPUT_VARIABLE UNAME_R) string(TOLOWER ${UNAME_R} UNAME_R) string(FIND ${UNAME_R} "microsoft" _index) if (${_index} EQUAL -1) set(QEMU_COMMON_OPTS "${QEMU_COMMON_OPTS} -device sb16") endif() # Set kernel's stack size in number of pages. set(KERNEL_STACK_PAGES 2) set(FATHACK ${BUILD_APPS}/fathack) if (${ARCH_BITS} EQUAL 32) set(ELFHACK ${BUILD_APPS}/elfhack32) else() set(ELFHACK ${BUILD_APPS}/elfhack64) endif() # Options for extra apps include(other/cmake/extra_apps.cmake) # Generate config files & build scripts (before including sub-dirs) include(other/cmake/gen_config_pre.cmake) # Include kernel's noarch sources include(kernel/sources.cmake) ################################################################################ # Include sub-directories if (BOOTLOADER_LEGACY) add_subdirectory(boot/legacy) endif() if (BOOTLOADER_EFI) add_subdirectory(boot/efi) endif() add_subdirectory(userapps) add_subdirectory(kernel) add_subdirectory(scripts/build_apps) ################################################################################ # Generate config files & build scripts (after including sub-dirs) include(other/cmake/gen_config_post.cmake) set(BUILD_SCRIPTS_FILES_LIST "") file(GLOB files ${GLOB_CONF_DEP} "${BUILD_SCRIPTS}/*") foreach (f ${files}) list(APPEND BUILD_SCRIPTS_FILES_LIST "${file}") endforeach() unset(files) set(dd_opts "status=none" "conv=notrunc") set( mbr_img_deps # We MUST depend on BOTH each wrapper-target AND its OUTPUT in order to # our image file to be re-built when the *.bin files are re-built. kernel ${KERNEL_FILE} userapps ${USERAPPS_FILES_LIST} ${EXTRA_APPS_LIST} fathack mbrhack ${CMAKE_BINARY_DIR}/scripts/build_apps/fathack ${CMAKE_BINARY_DIR}/scripts/build_apps/mbrhack ${CMAKE_SOURCE_DIR}/sysroot/etc/start ${CMAKE_BINARY_DIR}/config_fatpart ${BUILD_SCRIPTS_FILES_LIST} ) if (BOOTLOADER_LEGACY) list( APPEND mbr_img_deps bootloader ${BOOTLOADER_BIN_FILE} ) endif() if (BOOTLOADER_EFI) list( APPEND mbr_img_deps efi_bootloader ${EFI_x86_64_FILE} ) if (${ARCH} STREQUAL "i386") list(APPEND mbr_img_deps ${EFI_ia32_FILE}) endif() endif() # [begin] Set some convenience variables set(MBRHACK ${BUILD_APPS}/mbrhack -q ${IMG_FILE}) set(PARTED parted ${IMG_FILE} -s -a minimal) set(CREATE_EMPTY_IMG ${BUILD_SCRIPTS}/create_empty_img_if_necessary) # [begin] Setting one long variable, MBRHACK_BPB set(MBRHACK_BPB ${SECTOR_SIZE} ${CHS_HPC}) set(MBRHACK_BPB ${MBRHACK_BPB} ${CHS_SPT} ${IMG_SZ_SEC} ${BOOT_SECTORS}) set(MBRHACK_BPB ${MBRHACK_BPB} ${BOOT_SECTORS} ${DISK_UUID}) # [end] # [end] if (BOOTLOADER_LEGACY) add_custom_command( OUTPUT ${IMG_FILE} COMMAND ${CREATE_EMPTY_IMG} ${IMG_FILE} ${IMG_SZ_MB} COMMAND dd ${dd_opts} if=${BOOTLOADER_BIN_FILE} of=${IMG_FILE} COMMAND ${MBRHACK} bpb ${MBRHACK_BPB} COMMAND ${MBRHACK} add 0x0e ${BOOTPART_SEC} +${BOOTPART_SZ_SEC} COMMAND ${MBRHACK} add 0x0e ${INITRD_SECTOR} +${INITRD_SZ_MB}M COMMAND ${BUILD_BOOTPART} COMMAND ${BUILD_FATPART} COMMAND ${FATHACK} --truncate fatpart COMMAND ${FATHACK} --align_first_data_sector fatpart COMMAND dd ${dd_opts} if=bootpart of=${IMG_FILE} seek=${BOOTPART_SEC} COMMAND dd ${dd_opts} if=fatpart of=${IMG_FILE} seek=${INITRD_SECTOR} DEPENDS ${mbr_img_deps} COMMENT "Creating a dual-bootable (legacy+efi) image file (MBR)" VERBATIM ) else() add_custom_command( OUTPUT ${IMG_FILE} COMMAND ${CREATE_EMPTY_IMG} ${IMG_FILE} ${IMG_SZ_MB} COMMAND ${PARTED} mklabel msdos COMMAND ${PARTED} mkpart primary FAT16 ${BOOTPART_SEC}s ${BOOTPART_LAST_SEC}s COMMAND ${PARTED} mkpart primary FAT16 ${INITRD_SECTOR}s ${INITRD_LAST_SEC}s COMMAND ${BUILD_BOOTPART} COMMAND ${BUILD_FATPART} COMMAND ${FATHACK} --truncate fatpart COMMAND ${FATHACK} --align_first_data_sector fatpart COMMAND dd ${dd_opts} if=bootpart of=${IMG_FILE} seek=${BOOTPART_SEC} COMMAND dd ${dd_opts} if=fatpart of=${IMG_FILE} seek=${INITRD_SECTOR} DEPENDS ${mbr_img_deps} COMMENT "Creating a EFI-only bootable image file (MBR)" VERBATIM ) endif() # [begin] Unset the convenience variables unset(MBRHACK_BPB) unset(CREATE_EMPTY_IMG) unset(PARTED) unset(MBRHACK) # [end] add_custom_target( tilck_image ALL DEPENDS ${IMG_FILE} ) set(GTEST_VER "1.12.1") set(GTEST_SOURCE_DIR ${TCROOT}/noarch/gtest-${GTEST_VER}/googletest) set(GMOCK_SOURCE_DIR ${TCROOT}/noarch/gtest-${GTEST_VER}/googlemock) if (ARCH_GTESTS) if (NOT ${HOST_ARCH_FAMILY} STREQUAL ${ARCH_FAMILY}) show_arch_gtests_require_same_target_family_error() endif() set(GTEST_TC_BUILD_DIR ${TCROOT}/host_${ARCH}/gtest-${GTEST_VER}) set(GMOCK_TC_BUILD_DIR ${TCROOT}/host_${ARCH}/gmock-${GTEST_VER}) set(GTEST_BTC_COMMAND "build_gtest_arch build_gmock_arch") else() set(GTEST_TC_BUILD_DIR ${TCROOT}/host_${HOST_ARCH}/gtest-${GTEST_VER}) set(GMOCK_TC_BUILD_DIR ${TCROOT}/host_${HOST_ARCH}/gmock-${GTEST_VER}) set(GTEST_BTC_COMMAND "build_gtest build_gmock") endif() add_custom_command( OUTPUT test_fatpart COMMAND ${BUILD_TEST_FATPART} COMMAND ${BUILD_APPS}/fathack --truncate test_fatpart DEPENDS fathack ${CMAKE_BINARY_DIR}/scripts/build_apps/fathack ) add_custom_target( test_fatpart_target DEPENDS test_fatpart ) if (EXISTS ${GTEST_TC_BUILD_DIR} AND EXISTS ${GMOCK_TC_BUILD_DIR}) add_subdirectory(tests/unit) add_dependencies(gtests test_fatpart_target) else() no_googletest_lib_fake_error_target() endif() <file_sep>/****************************************************************************** * * Module Name: dswstate - Dispatcher parse tree walk management routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "acdispat.h" #include "acnamesp.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dswstate") /* Local prototypes */ static ACPI_STATUS AcpiDsResultStackPush ( ACPI_WALK_STATE *WalkState); static ACPI_STATUS AcpiDsResultStackPop ( ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiDsResultPop * * PARAMETERS: Object - Where to return the popped object * WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Pop an object off the top of this walk's result stack * ******************************************************************************/ ACPI_STATUS AcpiDsResultPop ( ACPI_OPERAND_OBJECT **Object, ACPI_WALK_STATE *WalkState) { UINT32 Index; ACPI_GENERIC_STATE *State; ACPI_STATUS Status; ACPI_FUNCTION_NAME (DsResultPop); State = WalkState->Results; /* Incorrect state of result stack */ if (State && !WalkState->ResultCount) { ACPI_ERROR ((AE_INFO, "No results on result stack")); return (AE_AML_INTERNAL); } if (!State && WalkState->ResultCount) { ACPI_ERROR ((AE_INFO, "No result state for result stack")); return (AE_AML_INTERNAL); } /* Empty result stack */ if (!State) { ACPI_ERROR ((AE_INFO, "Result stack is empty! State=%p", WalkState)); return (AE_AML_NO_RETURN_VALUE); } /* Return object of the top element and clean that top element result stack */ WalkState->ResultCount--; Index = (UINT32) WalkState->ResultCount % ACPI_RESULTS_FRAME_OBJ_NUM; *Object = State->Results.ObjDesc [Index]; if (!*Object) { ACPI_ERROR ((AE_INFO, "No result objects on result stack, State=%p", WalkState)); return (AE_AML_NO_RETURN_VALUE); } State->Results.ObjDesc [Index] = NULL; if (Index == 0) { Status = AcpiDsResultStackPop (WalkState); if (ACPI_FAILURE (Status)) { return (Status); } } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Obj=%p [%s] Index=%X State=%p Num=%X\n", *Object, AcpiUtGetObjectTypeName (*Object), Index, WalkState, WalkState->ResultCount)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsResultPush * * PARAMETERS: Object - Where to return the popped object * WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Push an object onto the current result stack * ******************************************************************************/ ACPI_STATUS AcpiDsResultPush ( ACPI_OPERAND_OBJECT *Object, ACPI_WALK_STATE *WalkState) { ACPI_GENERIC_STATE *State; ACPI_STATUS Status; UINT32 Index; ACPI_FUNCTION_NAME (DsResultPush); if (WalkState->ResultCount > WalkState->ResultSize) { ACPI_ERROR ((AE_INFO, "Result stack is full")); return (AE_AML_INTERNAL); } else if (WalkState->ResultCount == WalkState->ResultSize) { /* Extend the result stack */ Status = AcpiDsResultStackPush (WalkState); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Failed to extend the result stack")); return (Status); } } if (!(WalkState->ResultCount < WalkState->ResultSize)) { ACPI_ERROR ((AE_INFO, "No free elements in result stack")); return (AE_AML_INTERNAL); } State = WalkState->Results; if (!State) { ACPI_ERROR ((AE_INFO, "No result stack frame during push")); return (AE_AML_INTERNAL); } if (!Object) { ACPI_ERROR ((AE_INFO, "Null Object! Obj=%p State=%p Num=%u", Object, WalkState, WalkState->ResultCount)); return (AE_BAD_PARAMETER); } /* Assign the address of object to the top free element of result stack */ Index = (UINT32) WalkState->ResultCount % ACPI_RESULTS_FRAME_OBJ_NUM; State->Results.ObjDesc [Index] = Object; WalkState->ResultCount++; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Obj=%p [%s] State=%p Num=%X Cur=%X\n", Object, AcpiUtGetObjectTypeName ((ACPI_OPERAND_OBJECT *) Object), WalkState, WalkState->ResultCount, WalkState->CurrentResult)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsResultStackPush * * PARAMETERS: WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Push an object onto the WalkState result stack * ******************************************************************************/ static ACPI_STATUS AcpiDsResultStackPush ( ACPI_WALK_STATE *WalkState) { ACPI_GENERIC_STATE *State; ACPI_FUNCTION_NAME (DsResultStackPush); /* Check for stack overflow */ if (((UINT32) WalkState->ResultSize + ACPI_RESULTS_FRAME_OBJ_NUM) > ACPI_RESULTS_OBJ_NUM_MAX) { ACPI_ERROR ((AE_INFO, "Result stack overflow: State=%p Num=%u", WalkState, WalkState->ResultSize)); return (AE_STACK_OVERFLOW); } State = AcpiUtCreateGenericState (); if (!State) { return (AE_NO_MEMORY); } State->Common.DescriptorType = ACPI_DESC_TYPE_STATE_RESULT; AcpiUtPushGenericState (&WalkState->Results, State); /* Increase the length of the result stack by the length of frame */ WalkState->ResultSize += ACPI_RESULTS_FRAME_OBJ_NUM; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Results=%p State=%p\n", State, WalkState)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsResultStackPop * * PARAMETERS: WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Pop an object off of the WalkState result stack * ******************************************************************************/ static ACPI_STATUS AcpiDsResultStackPop ( ACPI_WALK_STATE *WalkState) { ACPI_GENERIC_STATE *State; ACPI_FUNCTION_NAME (DsResultStackPop); /* Check for stack underflow */ if (WalkState->Results == NULL) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Result stack underflow - State=%p\n", WalkState)); return (AE_AML_NO_OPERAND); } if (WalkState->ResultSize < ACPI_RESULTS_FRAME_OBJ_NUM) { ACPI_ERROR ((AE_INFO, "Insufficient result stack size")); return (AE_AML_INTERNAL); } State = AcpiUtPopGenericState (&WalkState->Results); AcpiUtDeleteGenericState (State); /* Decrease the length of result stack by the length of frame */ WalkState->ResultSize -= ACPI_RESULTS_FRAME_OBJ_NUM; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Result=%p RemainingResults=%X State=%p\n", State, WalkState->ResultCount, WalkState)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsObjStackPush * * PARAMETERS: Object - Object to push * WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Push an object onto this walk's object/operand stack * ******************************************************************************/ ACPI_STATUS AcpiDsObjStackPush ( void *Object, ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_NAME (DsObjStackPush); /* Check for stack overflow */ if (WalkState->NumOperands >= ACPI_OBJ_NUM_OPERANDS) { ACPI_ERROR ((AE_INFO, "Object stack overflow! Obj=%p State=%p #Ops=%u", Object, WalkState, WalkState->NumOperands)); return (AE_STACK_OVERFLOW); } /* Put the object onto the stack */ WalkState->Operands [WalkState->OperandIndex] = Object; WalkState->NumOperands++; /* For the usual order of filling the operand stack */ WalkState->OperandIndex++; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Obj=%p [%s] State=%p #Ops=%X\n", Object, AcpiUtGetObjectTypeName ((ACPI_OPERAND_OBJECT *) Object), WalkState, WalkState->NumOperands)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsObjStackPop * * PARAMETERS: PopCount - Number of objects/entries to pop * WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Pop this walk's object stack. Objects on the stack are NOT * deleted by this routine. * ******************************************************************************/ ACPI_STATUS AcpiDsObjStackPop ( UINT32 PopCount, ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_NAME (DsObjStackPop); for (i = 0; i < PopCount; i++) { /* Check for stack underflow */ if (WalkState->NumOperands == 0) { ACPI_ERROR ((AE_INFO, "Object stack underflow! Count=%X State=%p #Ops=%u", PopCount, WalkState, WalkState->NumOperands)); return (AE_STACK_UNDERFLOW); } /* Just set the stack entry to null */ WalkState->NumOperands--; WalkState->Operands [WalkState->NumOperands] = NULL; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Count=%X State=%p #Ops=%u\n", PopCount, WalkState, WalkState->NumOperands)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsObjStackPopAndDelete * * PARAMETERS: PopCount - Number of objects/entries to pop * WalkState - Current Walk state * * RETURN: Status * * DESCRIPTION: Pop this walk's object stack and delete each object that is * popped off. * ******************************************************************************/ void AcpiDsObjStackPopAndDelete ( UINT32 PopCount, ACPI_WALK_STATE *WalkState) { INT32 i; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_FUNCTION_NAME (DsObjStackPopAndDelete); if (PopCount == 0) { return; } for (i = (INT32) PopCount - 1; i >= 0; i--) { if (WalkState->NumOperands == 0) { return; } /* Pop the stack and delete an object if present in this stack entry */ WalkState->NumOperands--; ObjDesc = WalkState->Operands [i]; if (ObjDesc) { AcpiUtRemoveReference (WalkState->Operands [i]); WalkState->Operands [i] = NULL; } } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Count=%X State=%p #Ops=%X\n", PopCount, WalkState, WalkState->NumOperands)); } /******************************************************************************* * * FUNCTION: AcpiDsGetCurrentWalkState * * PARAMETERS: Thread - Get current active state for this Thread * * RETURN: Pointer to the current walk state * * DESCRIPTION: Get the walk state that is at the head of the list (the "current" * walk state.) * ******************************************************************************/ ACPI_WALK_STATE * AcpiDsGetCurrentWalkState ( ACPI_THREAD_STATE *Thread) { ACPI_FUNCTION_NAME (DsGetCurrentWalkState); if (!Thread) { return (NULL); } ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Current WalkState %p\n", Thread->WalkStateList)); return (Thread->WalkStateList); } /******************************************************************************* * * FUNCTION: AcpiDsPushWalkState * * PARAMETERS: WalkState - State to push * Thread - Thread state object * * RETURN: None * * DESCRIPTION: Place the Thread state at the head of the state list * ******************************************************************************/ void AcpiDsPushWalkState ( ACPI_WALK_STATE *WalkState, ACPI_THREAD_STATE *Thread) { ACPI_FUNCTION_TRACE (DsPushWalkState); WalkState->Next = Thread->WalkStateList; Thread->WalkStateList = WalkState; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsPopWalkState * * PARAMETERS: Thread - Current thread state * * RETURN: A WalkState object popped from the thread's stack * * DESCRIPTION: Remove and return the walkstate object that is at the head of * the walk stack for the given walk list. NULL indicates that * the list is empty. * ******************************************************************************/ ACPI_WALK_STATE * AcpiDsPopWalkState ( ACPI_THREAD_STATE *Thread) { ACPI_WALK_STATE *WalkState; ACPI_FUNCTION_TRACE (DsPopWalkState); WalkState = Thread->WalkStateList; if (WalkState) { /* Next walk state becomes the current walk state */ Thread->WalkStateList = WalkState->Next; /* * Don't clear the NEXT field, this serves as an indicator * that there is a parent WALK STATE * Do Not: WalkState->Next = NULL; */ } return_PTR (WalkState); } /******************************************************************************* * * FUNCTION: AcpiDsCreateWalkState * * PARAMETERS: OwnerId - ID for object creation * Origin - Starting point for this walk * MethodDesc - Method object * Thread - Current thread state * * RETURN: Pointer to the new walk state. * * DESCRIPTION: Allocate and initialize a new walk state. The current walk * state is set to this new state. * ******************************************************************************/ ACPI_WALK_STATE * AcpiDsCreateWalkState ( ACPI_OWNER_ID OwnerId, ACPI_PARSE_OBJECT *Origin, ACPI_OPERAND_OBJECT *MethodDesc, ACPI_THREAD_STATE *Thread) { ACPI_WALK_STATE *WalkState; ACPI_FUNCTION_TRACE (DsCreateWalkState); WalkState = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_WALK_STATE)); if (!WalkState) { return_PTR (NULL); } WalkState->DescriptorType = ACPI_DESC_TYPE_WALK; WalkState->MethodDesc = MethodDesc; WalkState->OwnerId = OwnerId; WalkState->Origin = Origin; WalkState->Thread = Thread; WalkState->ParserState.StartOp = Origin; /* Init the method args/local */ #ifndef ACPI_CONSTANT_EVAL_ONLY AcpiDsMethodDataInit (WalkState); #endif /* Put the new state at the head of the walk list */ if (Thread) { AcpiDsPushWalkState (WalkState, Thread); } return_PTR (WalkState); } /******************************************************************************* * * FUNCTION: AcpiDsInitAmlWalk * * PARAMETERS: WalkState - New state to be initialized * Op - Current parse op * MethodNode - Control method NS node, if any * AmlStart - Start of AML * AmlLength - Length of AML * Info - Method info block (params, etc.) * PassNumber - 1, 2, or 3 * * RETURN: Status * * DESCRIPTION: Initialize a walk state for a pass 1 or 2 parse tree walk * ******************************************************************************/ ACPI_STATUS AcpiDsInitAmlWalk ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_NAMESPACE_NODE *MethodNode, UINT8 *AmlStart, UINT32 AmlLength, ACPI_EVALUATE_INFO *Info, UINT8 PassNumber) { ACPI_STATUS Status; ACPI_PARSE_STATE *ParserState = &WalkState->ParserState; ACPI_PARSE_OBJECT *ExtraOp; ACPI_FUNCTION_TRACE (DsInitAmlWalk); WalkState->ParserState.Aml = WalkState->ParserState.AmlStart = AmlStart; WalkState->ParserState.AmlEnd = WalkState->ParserState.PkgEnd = AmlStart + AmlLength; /* The NextOp of the NextWalk will be the beginning of the method */ WalkState->NextOp = NULL; WalkState->PassNumber = PassNumber; if (Info) { WalkState->Params = Info->Parameters; WalkState->CallerReturnDesc = &Info->ReturnObject; } Status = AcpiPsInitScope (&WalkState->ParserState, Op); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (MethodNode) { WalkState->ParserState.StartNode = MethodNode; WalkState->WalkType = ACPI_WALK_METHOD; WalkState->MethodNode = MethodNode; WalkState->MethodDesc = AcpiNsGetAttachedObject (MethodNode); /* Push start scope on scope stack and make it current */ Status = AcpiDsScopeStackPush ( MethodNode, ACPI_TYPE_METHOD, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Init the method arguments */ Status = AcpiDsMethodDataInitArgs (WalkState->Params, ACPI_METHOD_NUM_ARGS, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } else { /* * Setup the current scope. * Find a Named Op that has a namespace node associated with it. * search upwards from this Op. Current scope is the first * Op with a namespace node. */ ExtraOp = ParserState->StartOp; while (ExtraOp && !ExtraOp->Common.Node) { ExtraOp = ExtraOp->Common.Parent; } if (!ExtraOp) { ParserState->StartNode = NULL; } else { ParserState->StartNode = ExtraOp->Common.Node; } if (ParserState->StartNode) { /* Push start scope on scope stack and make it current */ Status = AcpiDsScopeStackPush (ParserState->StartNode, ParserState->StartNode->Type, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } Status = AcpiDsInitCallbacks (WalkState, PassNumber); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsDeleteWalkState * * PARAMETERS: WalkState - State to delete * * RETURN: Status * * DESCRIPTION: Delete a walk state including all internal data structures * ******************************************************************************/ void AcpiDsDeleteWalkState ( ACPI_WALK_STATE *WalkState) { ACPI_GENERIC_STATE *State; ACPI_FUNCTION_TRACE_PTR (DsDeleteWalkState, WalkState); if (!WalkState) { return_VOID; } if (WalkState->DescriptorType != ACPI_DESC_TYPE_WALK) { ACPI_ERROR ((AE_INFO, "%p is not a valid walk state", WalkState)); return_VOID; } /* There should not be any open scopes */ if (WalkState->ParserState.Scope) { ACPI_ERROR ((AE_INFO, "%p walk still has a scope list", WalkState)); AcpiPsCleanupScope (&WalkState->ParserState); } /* Always must free any linked control states */ while (WalkState->ControlState) { State = WalkState->ControlState; WalkState->ControlState = State->Common.Next; AcpiUtDeleteGenericState (State); } /* Always must free any linked parse states */ while (WalkState->ScopeInfo) { State = WalkState->ScopeInfo; WalkState->ScopeInfo = State->Common.Next; AcpiUtDeleteGenericState (State); } /* Always must free any stacked result states */ while (WalkState->Results) { State = WalkState->Results; WalkState->Results = State->Common.Next; AcpiUtDeleteGenericState (State); } ACPI_FREE (WalkState); return_VOID; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # GLOBAL VARIABLES # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/../.. && pwd)" # Include files source $MAIN_DIR/scripts/bash_includes/script_utils # CONSTANTS CM=$MAIN_DIR/scripts/cmake_run ############################################################## $CM "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <signal.h> // system header #include <asm-generic/signal-defs.h> // system header #define SIG_FL_PROCESS (1 << 0) #define SIG_FL_FAULT (1 << 1) enum sig_state { sig_none = 0, sig_pre_syscall = 1, sig_in_syscall = 2, sig_in_usermode = 3, sig_in_return = 4, sig_in_fault = 5, } PACKED; int send_signal_to_group(int pgid, int sig); int send_signal_to_session(int sid, int sig); int send_signal2(int pid, int tid, int signum, int flags); bool process_signals(void *curr, enum sig_state new_sig_state, void *regs); void drop_all_pending_signals(void *curr); void reset_all_custom_signal_handlers(void *curr); static inline int send_signal(int tid, int signum, int flags) { return send_signal2(tid, tid, signum, flags); } #define K_SIGACTION_MASK_WORDS 2 <file_sep>import re from enum import Enum, auto from cmake_var import cmake_var, build_cmake_var from typing import List class row_type(Enum): """ The various types a cmake_row can have. Cmake_row is always one and only one of these types. """ EMPTY = auto() SLASH_COMMENT = auto() POUND_COMMENT = auto() VARIABLE = auto() class cmake_row: """ Simple utility class that abstracts away some details from the parsing process from a single CMakeCache.txt row. Assumes that different comments are concatenated to each other using a newline. This is needed to distinguish between the actual comment and metadata. """ _variable_expr = re.compile(r"^([A-Za-z_0-9]+?):([A-Za-z]+?)=(.*)$") def __init__(self, raw_row: str, row_number: int, comment: List[str]=[]): """ Strips variable and assigns its correct type by matching the regex and verifying if it's a comment. Assumes that a variable has maximum one line of comments, and the rest is metadata used by the parser to determine other properties of cmake_var. """ row = raw_row.strip() variable_match = self._variable_expr.match(row) self.val: str | cmake_var | None = None self.name: str = "" self._cmake_type: str # used to serialize back the value self.row_number = row_number self.comment = comment[0].strip() if comment else "" self.row_type: row_type if not len(row): self.row_type = row_type.EMPTY self.val = "" elif self.is_slash_comment(row): self.row_type = row_type.SLASH_COMMENT self.val = row[2:] elif self.is_pound_comment(row): self.row_type = row_type.POUND_COMMENT self.val = row[1:] elif variable_match: groups = variable_match.groups() self.name = groups[0] self.row_type = row_type.VARIABLE val = groups[2] self._cmake_type = groups[1] self.val = build_cmake_var(self._cmake_type, val, comment) else: raise ValueError("Could not parse variable") def is_comment(self, row: str) -> bool: "checks if string is either // comment or # comment" return self.is_slash_comment(row) or self.is_pound_comment(row) def is_slash_comment(self, row: str) -> bool: return row[:2] == "//" def is_pound_comment(self, row: str) -> bool: return row[0] == "#" def serialize(self) -> str: if self.row_type == row_type.VARIABLE: return self.name + ":" + self._cmake_type + "=" + self.val.serialize() elif self.row_type == row_type.POUND_COMMENT: return "#" + str(self.val) elif self.row_type == row_type.SLASH_COMMENT: return "//" + str(self.val) elif self.row_type == row_type.EMPTY: return "" else: raise ValueError("Row does not have a defined type") def get_val(self) -> str: if self.row_type == row_type.VARIABLE: return self.val.serialize() else: return str(self.val) <file_sep>/******************************************************************************* * * Module Name: utstrtoul64 - String-to-integer conversion support for both * 64-bit and 32-bit integers * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utstrtoul64") /******************************************************************************* * * This module contains the top-level string to 64/32-bit unsigned integer * conversion functions: * * 1) A standard strtoul() function that supports 64-bit integers, base * 8/10/16, with integer overflow support. This is used mainly by the * iASL compiler, which implements tighter constraints on integer * constants than the runtime (interpreter) integer-to-string conversions. * 2) Runtime "Explicit conversion" as defined in the ACPI specification. * 3) Runtime "Implicit conversion" as defined in the ACPI specification. * * Current users of this module: * * iASL - Preprocessor (constants and math expressions) * iASL - Main parser, conversion of constants to integers * iASL - Data Table Compiler parser (constants and math expressions) * Interpreter - Implicit and explicit conversions, GPE method names * Interpreter - Repair code for return values from predefined names * Debugger - Command line input string conversion * AcpiDump - ACPI table physical addresses * AcpiExec - Support for namespace overrides * * Notes concerning users of these interfaces: * * AcpiGbl_IntegerByteWidth is used to set the 32/64 bit limit for explicit * and implicit conversions. This global must be set to the proper width. * For the core ACPICA code, the width depends on the DSDT version. For the * AcpiUtStrtoul64 interface, all conversions are 64 bits. This interface is * used primarily for iASL, where the default width is 64 bits for all parsers, * but error checking is performed later to flag cases where a 64-bit constant * is wrongly defined in a 32-bit DSDT/SSDT. * * In ACPI, the only place where octal numbers are supported is within * the ASL language itself. This is implemented via the main AcpiUtStrtoul64 * interface. According the ACPI specification, there is no ACPI runtime * support (explicit/implicit) for octal string conversions. * ******************************************************************************/ /******************************************************************************* * * FUNCTION: AcpiUtStrtoul64 * * PARAMETERS: String - Null terminated input string, * must be a valid pointer * ReturnValue - Where the converted integer is * returned. Must be a valid pointer * * RETURN: Status and converted integer. Returns an exception on a * 64-bit numeric overflow * * DESCRIPTION: Convert a string into an unsigned integer. Always performs a * full 64-bit conversion, regardless of the current global * integer width. Supports Decimal, Hex, and Octal strings. * * Current users of this function: * * iASL - Preprocessor (constants and math expressions) * iASL - Main ASL parser, conversion of ASL constants to integers * iASL - Data Table Compiler parser (constants and math expressions) * Interpreter - Repair code for return values from predefined names * AcpiDump - ACPI table physical addresses * AcpiExec - Support for namespace overrides * ******************************************************************************/ ACPI_STATUS AcpiUtStrtoul64 ( char *String, UINT64 *ReturnValue) { ACPI_STATUS Status = AE_OK; UINT8 OriginalBitWidth; UINT32 Base = 10; /* Default is decimal */ ACPI_FUNCTION_TRACE_STR (UtStrtoul64, String); *ReturnValue = 0; /* A NULL return string returns a value of zero */ if (*String == 0) { return_ACPI_STATUS (AE_OK); } if (!AcpiUtRemoveWhitespace (&String)) { return_ACPI_STATUS (AE_OK); } /* * 1) Check for a hex constant. A "0x" prefix indicates base 16. */ if (AcpiUtDetectHexPrefix (&String)) { Base = 16; } /* * 2) Check for an octal constant, defined to be a leading zero * followed by sequence of octal digits (0-7) */ else if (AcpiUtDetectOctalPrefix (&String)) { Base = 8; } if (!AcpiUtRemoveLeadingZeros (&String)) { return_ACPI_STATUS (AE_OK); /* Return value 0 */ } /* * Force a full 64-bit conversion. The caller (usually iASL) must * check for a 32-bit overflow later as necessary (If current mode * is 32-bit, meaning a 32-bit DSDT). */ OriginalBitWidth = AcpiGbl_IntegerBitWidth; AcpiGbl_IntegerBitWidth = 64; /* * Perform the base 8, 10, or 16 conversion. A 64-bit numeric overflow * will return an exception (to allow iASL to flag the statement). */ switch (Base) { case 8: Status = AcpiUtConvertOctalString (String, ReturnValue); break; case 10: Status = AcpiUtConvertDecimalString (String, ReturnValue); break; case 16: default: Status = AcpiUtConvertHexString (String, ReturnValue); break; } /* Only possible exception from above is a 64-bit overflow */ AcpiGbl_IntegerBitWidth = OriginalBitWidth; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtImplicitStrtoul64 * * PARAMETERS: String - Null terminated input string, * must be a valid pointer * * RETURN: Converted integer * * DESCRIPTION: Perform a 64-bit conversion with restrictions placed upon * an "implicit conversion" by the ACPI specification. Used by * many ASL operators that require an integer operand, and support * an automatic (implicit) conversion from a string operand * to the final integer operand. The major restriction is that * only hex strings are supported. * * ----------------------------------------------------------------------------- * * Base is always 16, either with or without the 0x prefix. Decimal and * Octal strings are not supported, as per the ACPI specification. * * Examples (both are hex values): * Add ("BA98", Arg0, Local0) * Subtract ("0x12345678", Arg1, Local1) * * Conversion rules as extracted from the ACPI specification: * * The converted integer is initialized to the value zero. * The ASCII string is always interpreted as a hexadecimal constant. * * 1) According to the ACPI specification, a "0x" prefix is not allowed. * However, ACPICA allows this as an ACPI extension on general * principle. (NO ERROR) * * 2) The conversion terminates when the size of an integer is reached * (32 or 64 bits). There are no numeric overflow conditions. (NO ERROR) * * 3) The first non-hex character terminates the conversion and returns * the current accumulated value of the converted integer (NO ERROR). * * 4) Conversion of a null (zero-length) string to an integer is * technically not allowed. However, ACPICA allows this as an ACPI * extension. The conversion returns the value 0. (NO ERROR) * * NOTE: There are no error conditions returned by this function. At * the minimum, a value of zero is returned. * * Current users of this function: * * Interpreter - All runtime implicit conversions, as per ACPI specification * iASL - Data Table Compiler parser (constants and math expressions) * ******************************************************************************/ UINT64 AcpiUtImplicitStrtoul64 ( char *String) { UINT64 ConvertedInteger = 0; ACPI_FUNCTION_TRACE_STR (UtImplicitStrtoul64, String); if (!AcpiUtRemoveWhitespace (&String)) { return_VALUE (0); } /* * Per the ACPI specification, only hexadecimal is supported for * implicit conversions, and the "0x" prefix is "not allowed". * However, allow a "0x" prefix as an ACPI extension. */ AcpiUtRemoveHexPrefix (&String); if (!AcpiUtRemoveLeadingZeros (&String)) { return_VALUE (0); } /* * Ignore overflow as per the ACPI specification. This is implemented by * ignoring the return status from the conversion function called below. * On overflow, the input string is simply truncated. */ AcpiUtConvertHexString (String, &ConvertedInteger); return_VALUE (ConvertedInteger); } /******************************************************************************* * * FUNCTION: AcpiUtExplicitStrtoul64 * * PARAMETERS: String - Null terminated input string, * must be a valid pointer * * RETURN: Converted integer * * DESCRIPTION: Perform a 64-bit conversion with the restrictions placed upon * an "explicit conversion" by the ACPI specification. The * main restriction is that only hex and decimal are supported. * * ----------------------------------------------------------------------------- * * Base is either 10 (default) or 16 (with 0x prefix). Octal (base 8) strings * are not supported, as per the ACPI specification. * * Examples: * ToInteger ("1000") Decimal * ToInteger ("0xABCD") Hex * * Conversion rules as extracted from the ACPI specification: * * 1) The input string is either a decimal or hexadecimal numeric string. * A hex value must be prefixed by "0x" or it is interpreted as decimal. * * 2) The value must not exceed the maximum of an integer value * (32 or 64 bits). The ACPI specification states the behavior is * "unpredictable", so ACPICA matches the behavior of the implicit * conversion case. There are no numeric overflow conditions. (NO ERROR) * * 3) Behavior on the first non-hex character is not defined by the ACPI * specification (for the ToInteger operator), so ACPICA matches the * behavior of the implicit conversion case. It terminates the * conversion and returns the current accumulated value of the converted * integer. (NO ERROR) * * 4) Conversion of a null (zero-length) string to an integer is * technically not allowed. However, ACPICA allows this as an ACPI * extension. The conversion returns the value 0. (NO ERROR) * * NOTE: There are no error conditions returned by this function. At the * minimum, a value of zero is returned. * * Current users of this function: * * Interpreter - Runtime ASL ToInteger operator, as per the ACPI specification * ******************************************************************************/ UINT64 AcpiUtExplicitStrtoul64 ( char *String) { UINT64 ConvertedInteger = 0; UINT32 Base = 10; /* Default is decimal */ ACPI_FUNCTION_TRACE_STR (UtExplicitStrtoul64, String); if (!AcpiUtRemoveWhitespace (&String)) { return_VALUE (0); } /* * Only Hex and Decimal are supported, as per the ACPI specification. * A "0x" prefix indicates hex; otherwise decimal is assumed. */ if (AcpiUtDetectHexPrefix (&String)) { Base = 16; } if (!AcpiUtRemoveLeadingZeros (&String)) { return_VALUE (0); } /* * Ignore overflow as per the ACPI specification. This is implemented by * ignoring the return status from the conversion functions called below. * On overflow, the input string is simply truncated. */ switch (Base) { case 10: default: AcpiUtConvertDecimalString (String, &ConvertedInteger); break; case 16: AcpiUtConvertHexString (String, &ConvertedInteger); break; } return_VALUE (ConvertedInteger); } <file_sep>from unittest import TestCase from unittest.mock import patch from cmake_parser import parse_rows, row_type, write_file test_file1 = """ # KEY:TYPE=VALUE # KEY is the name of a variable in the cache. # TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. # VALUE is the current value for the KEY. ######################## # EXTERNAL cache entries ######################## //Build unit tests for the target arch ARCH_GTESTS:BOOL=OFF //Build the EFI bootloader BOOTLOADER_EFI:BOOL=ON //Build the legacy bootloader BOOTLOADER_LEGACY:BOOL=ON //Make the bootloader to poison all the available memory BOOTLOADER_POISON_MEMORY:BOOL=OFF //Have user-interactive commands in the bootloaders BOOT_INTERACTIVE:BOOL=ON //Path to a program. CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line //Example Internal variable CMAKE_AR:INTERNAL=/usr/bin/ar //Path to a program.Example Internal variable CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line """ test_file1_lines = test_file1.splitlines() expected_comments_file1 = [ "Build unit tests for the target arch", "Build the EFI bootloader", "Build the legacy bootloader", "Make the bootloader to poison all the available memory", "Have user-interactive commands in the bootloaders", "Path to a program.", "Example Internal variable", "Path to a program.Example Internal variable", "" ] class test_cmake_parser_lines(TestCase): def test_serialization(self): rows = parse_rows(test_file1_lines) for row, line in zip(rows, test_file1_lines): self.assertEqual(row.serialize(), line) def test_variable_comments(self): rows = parse_rows(test_file1_lines) var_rows = [row for row in rows if row.row_type == row_type.VARIABLE] for row, comment in zip(var_rows, expected_comments_file1): self.assertEqual(row.comment, comment) class test_cmake_parser_io(TestCase): def test_write_file(self): filebuf = "" class fake_file_handle: def write(self, data): nonlocal filebuf filebuf += data class fake_open: def __init__(self, filepath, mode): pass def __enter__(self): return fake_file_handle() def __exit__(self, type, value, traceback): pass rows = parse_rows(test_file1_lines) with patch('builtins.open', new = fake_open): write_file(None, rows) self.assertEqual(filebuf, test_file1) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/fat32.h> int fat_ramdisk_prepare_for_mmap(struct fat_fs_device_data *d, size_t rd_size) { struct fat_hdr *hdr = d->hdr; if (system_mmap_check_for_extra_ramdisk_region(hdr)) { /* * Typical case: the extra 4k region after our ramdisk, survived the * overlap handling, meaning that the was at least 4k of usable (regular) * memory just after our ramdisk. This will help in the corner case below. */ rd_size += PAGE_SIZE; } if (d->cluster_size < PAGE_SIZE || !IS_PAGE_ALIGNED(d->cluster_size)) { /* We cannot support our implementation of mmap in this case */ return -1; } retain_pageframes_mapped_at(get_kernel_pdir(), hdr, rd_size); if (fat_is_first_data_sector_aligned(hdr, PAGE_SIZE)) return 0; /* Typical case: nothing to do */ /* * The code here below will almost never be triggered as it handles a very * ugly use case. Let me explain. * * In order to fat_mmap() work in the simple and direct way as implemented * in Tilck, the FAT clusters must be aligned at page boundary. That is true * when just the first data sector is aligned. In our build system, the * fathack build app is used to make that happen. Fathack substantially calls * fat_align_first_data_sector() which adds more reserved sectors to the * partition by shifting all the data by the necessary amount of bytes. * * Now, when our FAT ramdisk is build by our build system, because of fathack * we never have to worry about such alignment. That is true even if the * fat ramdisk is later modified by an external tool to add/remove files from * it: the number of reserved sectors won't changed. BUT, in the unlikely * case when the external tools reformats the whole partition, we'll loose * that alignment and it would be nice if Tilck itself could handle that case * too. That's what the following code does. * * Note: in order to the code below to work (corner case, like explained) we * need at least one of the following conditions to be true: * * - boot the OS using one of Tilck's bootloaders OR * - have 1 page avail at the end of the ramdisk mem region (very likely) * * In summary, the code below won't work only in the 1 in billion case where * all of the following statements are true: * * - the fatpart was NOT generated by our build system (why doing that?) * - the OS was NOT booted using Tilck's bootloaders (e.g. using GRUB) * - according to the firmware, the next 4k after the ramdisk belong * to a reserved memory region (extremely unlucky case) */ const u32 used = fat_calculate_used_bytes(hdr); pdir_t *const pdir = get_kernel_pdir(); char *const va_begin = (char *)hdr; char *const va_end = va_begin + rd_size; VERIFY(rd_size >= used); if (rd_size - used < PAGE_SIZE) { printk("WARNING: [fat ramdisk] cannot align first data sector\n"); return -1; } for (char *va = va_begin; va < va_end; va += PAGE_SIZE) set_page_rw(pdir, va, true); fat_align_first_data_sector(hdr, PAGE_SIZE); for (char *va = va_begin; va < va_end; va += PAGE_SIZE) set_page_rw(pdir, va, false); printk("fat ramdisk: align of ramdisk was necessary\n"); return 0; } int fat_mmap(struct user_mapping *um, pdir_t *pdir, int flags) { struct fatfs_handle *fh = um->h; struct fat_fs_device_data *d = fh->fs->device_data; const size_t off_begin = um->off; const size_t off_end = off_begin + um->len; ulong vaddr = um->vaddr, off = 0; size_t mapped_cnt, tot_mapped_cnt = 0; u32 clu; if (!d->mmap_support) return -ENODEV; /* We do NOT support mmap for this "superblock" */ if (fh->e->directory) return -EACCES; if (flags & VFS_MM_DONT_MMAP) return 0; clu = fat_get_first_cluster(fh->e); do { char *data; const ulong clu_end_off = off + d->cluster_size; // Are we past the end of the mapped region? if (off >= off_end) break; // Does this cluster belong to the mapped region? if (clu_end_off > off_begin) { // The cluster ends *after* the beginning of our region data = fat_get_pointer_to_cluster_data(d->hdr, clu); if (off < off_begin) { // Our region begins somewhere in the middle of this cluster. // This can happen only with cluster_size > PAGE_SIZE. off = off_begin; data += off_begin - off; } /* * Calculate the number of pages to mmap, considering that: * - we cannot mmap in this iteration further than clu_end_off * - we must not mmap further than off_end */ size_t pg_count = (MIN(clu_end_off, off_end) - off) >> PAGE_SHIFT; mapped_cnt = map_pages(pdir, (void *)vaddr, KERNEL_VA_TO_PA(data), pg_count, PAGING_FL_US | PAGING_FL_SHARED); if (mapped_cnt != pg_count) { unmap_pages_permissive(pdir, (void *)um->vaddr, tot_mapped_cnt, false); return -ENOMEM; } vaddr += pg_count << PAGE_SHIFT; off += pg_count << PAGE_SHIFT; tot_mapped_cnt += mapped_cnt; // After each iteration, `off` must always be aligned at `cluster_size` ASSERT((off % d->cluster_size) == 0); } else { // We skipped the whole cluster off += d->cluster_size; } // Get the next cluster# from the File Allocation Table clu = fat_read_fat_entry(d->hdr, d->type, 0, clu); // We do not expect BAD CLUSTERS ASSERT(!fat_is_bad_cluster(d->type, clu)); } while (!fat_is_end_of_clusterchain(d->type, clu)); return 0; } int fat_munmap(struct user_mapping *um, void *vaddrp, size_t len) { struct fatfs_handle *fh = um->h; struct fat_fs_device_data *d = fh->fs->device_data; if (!d->mmap_support) return -ENODEV; /* We do NOT support mmap for this "superblock" */ return generic_fs_munmap(um, vaddrp, len); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/common/string_util.h> #include <tilck/common/utils.h> #include <tilck/kernel/elf_loader.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/fs/flock.h> #include <sys/mman.h> // system header #if defined(__x86_64__) #define ELF_CURR_ARCH EM_X86_64 #define ELF_CURR_CLASS ELFCLASS64 #elif defined(__i386__) #define ELF_CURR_ARCH EM_386 #define ELF_CURR_CLASS ELFCLASS32 #elif defined(__aarch64__) #define ELF_CURR_ARCH EM_AARCH64 #define ELF_CURR_CLASS ELFCLASS64 #else #error Architecture not supported. #endif typedef int (*load_segment_func)(fs_handle *, pdir_t *, Elf_Phdr *, ulong *); static int load_segment_by_copy(fs_handle *elf_h, pdir_t *pdir, Elf_Phdr *phdr, ulong *end_vaddr_ref) { offt rc; ulong va = phdr->p_vaddr; size_t filesz_rem = phdr->p_filesz; char *vaddr = (char *) (phdr->p_vaddr & PAGE_MASK); const size_t memsz = phdr->p_vaddr + phdr->p_memsz - (ulong)vaddr; const size_t page_count = (memsz + PAGE_SIZE - 1) / PAGE_SIZE; DEBUG_ONLY(size_t tot_read = 0); if (UNLIKELY(phdr->p_memsz == 0)) return 0; /* very weird (because the phdr has type LOAD) */ *end_vaddr_ref = (ulong)vaddr + (page_count << PAGE_SHIFT); rc = vfs_seek(elf_h, (offt)phdr->p_offset, SEEK_SET); if (rc < 0) return (int)rc; /* I/O error during seek */ if (rc != (ssize_t)phdr->p_offset) return -ENOEXEC; for (u32 j = 0; j < page_count; j++, vaddr += PAGE_SIZE) { void *p; if (!is_mapped(pdir, vaddr)) { if (!(p = kzmalloc(PAGE_SIZE))) return -ENOMEM; if ((rc = map_page(pdir, vaddr, KERNEL_VA_TO_PA(p), PAGING_FL_RWUS))) { kfree2(p, PAGE_SIZE); return (int)rc; } } else { /* Get user's vaddr as a kernel vaddr */ p = KERNEL_PA_TO_VA(get_mapping(pdir, vaddr)); } if (filesz_rem) { const size_t off = (va & OFFSET_IN_PAGE_MASK); const size_t to_read = MIN(filesz_rem, (PAGE_SIZE - off)); rc = vfs_read(elf_h, p + off, to_read); if (rc < 0) return (int)rc; /* I/O error during read */ if (rc < (ssize_t)to_read) return -ENOEXEC; /* The ELF file is corrupted */ va += to_read; filesz_rem -= to_read; DEBUG_ONLY(tot_read += to_read); } } ASSERT(tot_read == phdr->p_filesz); if (!(phdr->p_flags & PF_W)) { /* Make the read-only pages to be read-only */ vaddr = (char *) (phdr->p_vaddr & PAGE_MASK); for (size_t j = 0; j < page_count; j++, vaddr += PAGE_SIZE) set_page_rw(pdir, vaddr, false); } return 0; } static inline int check_segment_alignment(Elf_Phdr *phdr) { const ulong file_page_off = phdr->p_offset & OFFSET_IN_PAGE_MASK; const ulong mem_page_off = phdr->p_vaddr & OFFSET_IN_PAGE_MASK; if (phdr->p_align != PAGE_SIZE) { /* * We simply cannot possibly support such a scenario. It would imply * having cases like: * * file_offset = 0x0000a001 * memory_offset = 0x0800b002 * * While we can only map 4k pages, like mapping the whole 4k chunk of * the ELF file at 0x0000a000 to the virtual memory address 0x800b000. * If the two offsets are not equal, the whole mapping in the memory would * have to shift by a given amount in the range [1, 4095] and that could * possibily happen only after copying the whole file in memory. * * NOTE: while it might seem that p_align == PAGE_SIZE means that both * file_page_off and mem_page_off must always be zero, that's NOT correct. * In reality, it's typical for them to have values != 0 as long as their * value is the same, like 0x123, that's absolutely fine. Just, during * the mapping, that offset will be simply ignored. * * See the case below. */ return -ENOEXEC; } if (file_page_off != mem_page_off) { /* * The ELF header states that this segment is aligned at PAGE_SIZE but * the in-page offset of the file position and the one of the vaddr * differ: therefore, the header is lying. The segment is NOT aligned at * PAGE_SIZE. We cannot possibly accept that. */ return -ENOEXEC; } return 0; } static int load_segment_by_mmap(fs_handle *elf_h, pdir_t *pdir, Elf_Phdr *phdr, ulong *end_vaddr_ref) { if (phdr->p_flags & PF_W) return load_segment_by_copy(elf_h, pdir, phdr, end_vaddr_ref); if (UNLIKELY(phdr->p_memsz == 0)) return 0; /* very weird (because the phdr has type LOAD) */ /* * Logic behind the calculation of `um.len`. * * First of all, phdr->p_memsz is NOT page aligned; it could have any value. * Because we have to map a number of pages, not bytes, the least we can do * is to round-up the value of `p_memsz` at PAGE_SIZE. That would do a great * job for many cases like: * * vaddr: 0x08001000 * length: 800 bytes -> 4096 bytes (1 page) * => range [0x08001000, 0x08002000) * * BUT, because `p_vaddr` is NOT required to be divisible by PAGE_SIZE, see * check_segment_alignment(), we will end with a wrong range in some cases. * For example: * * vaddr: 0x08001c00 (in-page offset: 0xc00 = 3072) * length: 2048 bytes -> 4096 bytes (1 page) * => range [0x08001000, 0x08002000) <---- WRONG!! * * The correct way of calculating `length` requires to consider the in-page * offset of `vaddr` as part of it. In other words: * * 0x08001c00 (vaddr) - 0x08001000 (vaddr & PAGE_MASK) + 2048 (p_memsz) = * 0xc00 + 2048 = 5120 -> 8192 (2 pages) * => range [0x08001000, 0x08003000) <---- CORRECT!! */ struct user_mapping um = {0}; um.pi = NULL; um.h = elf_h; um.off = phdr->p_offset & PAGE_MASK; um.vaddr = phdr->p_vaddr & PAGE_MASK; um.len = round_up_at(phdr->p_vaddr + phdr->p_memsz - um.vaddr, PAGE_SIZE); um.prot = PROT_READ; *end_vaddr_ref = um.vaddr + um.len; return vfs_mmap(&um, pdir, VFS_MM_DONT_REGISTER); } struct elf_headers { char *header_buf; Elf_Ehdr *header; Elf_Phdr *phdrs; size_t total_phdrs_size; }; static void free_elf_headers(struct elf_headers *eh) { ASSERT(eh != NULL); if (eh->total_phdrs_size) kfree2(eh->phdrs, eh->total_phdrs_size); } static int load_elf_headers(fs_handle elf_h, char *hdr_buf, struct elf_headers *eh, bool *wrong_arch) { offt rc; bzero(eh, sizeof(*eh)); if ((rc = vfs_seek(elf_h, 0, SEEK_SET))) return -EIO; rc = vfs_read(elf_h, hdr_buf, ELF_RAW_HEADER_SIZE); if (rc < (int)sizeof(*eh->header)) return -ENOEXEC; eh->header = (void *)hdr_buf; if (strncmp((const char *)eh->header->e_ident, ELFMAG, 4)) return -ENOEXEC; if (eh->header->e_type != ET_EXEC) return -ENOEXEC; if (eh->header->e_ident[EI_CLASS] != ELF_CURR_CLASS || eh->header->e_machine != ELF_CURR_ARCH) { *wrong_arch = true; return -ENOEXEC; } if (eh->header->e_ehsize < sizeof(eh->header)) return -ENOEXEC; eh->total_phdrs_size = eh->header->e_phnum * sizeof(Elf_Phdr); eh->phdrs = kmalloc(eh->total_phdrs_size); if (!eh->phdrs) return -ENOMEM; rc = vfs_seek(elf_h, (offt)eh->header->e_phoff, SEEK_SET); if (rc != (ssize_t)eh->header->e_phoff) { rc = -ENOEXEC; goto errend; } rc = vfs_read(elf_h, eh->phdrs, eh->total_phdrs_size); if (rc != (ssize_t)eh->total_phdrs_size) { rc = -ENOEXEC; goto errend; } return 0; errend: free_elf_headers(eh); return (int) rc; } static int alloc_and_map_stack_page(pdir_t *pdir, void *stack_top, u32 i) { int rc; void *p = kzmalloc(PAGE_SIZE); if (!p) return -ENOMEM; rc = map_page(pdir, (void *)stack_top + (i << PAGE_SHIFT), KERNEL_VA_TO_PA(p), PAGING_FL_RW | PAGING_FL_US); return rc; } static int open_elf_file(const char *filepath, fs_handle *elf_file_ref) { struct k_stat64 statbuf; fs_handle h; int rc; if ((rc = vfs_open(filepath, &h, O_RDONLY, 0))) return rc; /* The file does not exist (typical case) */ if ((rc = vfs_fstat64(h, &statbuf))) { vfs_close(h); return rc; /* Cannot stat() the file */ } if ((statbuf.st_mode & S_IFREG) != S_IFREG) { vfs_close(h); if ((statbuf.st_mode & S_IFDIR) == S_IFDIR) return -EISDIR; /* Cannot execute a directory! */ return -EACCES; /* Not a regular file */ } if ((statbuf.st_mode & S_IXUSR) != S_IXUSR) { vfs_close(h); return -EACCES; /* Doesn't have exec permission */ } *elf_file_ref = h; return 0; } static bool is_dyn_exec(struct elf_headers *eh) { Elf_Ehdr *hdr = eh->header; for (int i = 0; i < hdr->e_phnum; i++) { Elf_Phdr *phdr = eh->phdrs + i; if (phdr->p_type == PT_INTERP) return true; } return false; } int load_elf_program(const char *filepath, char *header_buf, struct elf_program_info *pinfo) { load_segment_func load_seg = NULL; fs_handle elf_h = NULL; struct elf_headers eh; ulong brk = 0; size_t count; int rc; pinfo->wrong_arch = false; pinfo->dyn_exec = false; if ((rc = open_elf_file(filepath, &elf_h))) return rc; if ((rc = acquire_subsys_flock_h(elf_h, SUBSYS_PROCMGNT, &pinfo->lf))) { vfs_close(elf_h); return rc == -EBADF ? -ENOEXEC : rc; } if ((rc = load_elf_headers(elf_h, header_buf, &eh, &pinfo->wrong_arch))) { vfs_close(elf_h); return rc; } if (is_dyn_exec(&eh)) { pinfo->dyn_exec = true; rc = -ENOEXEC; goto out; } load_seg = is_mmap_supported(elf_h) ? &load_segment_by_mmap : &load_segment_by_copy; ASSERT(pinfo->pdir == NULL); if (!(pinfo->pdir = pdir_clone(get_kernel_pdir()))) { rc = -ENOMEM; goto out; } for (int i = 0; i < eh.header->e_phnum; i++) { ulong end_vaddr = 0; Elf_Phdr *phdr = eh.phdrs + i; if (phdr->p_type != PT_LOAD) continue; rc = check_segment_alignment(phdr); if (rc < 0) goto out; rc = load_seg(elf_h, pinfo->pdir, phdr, &end_vaddr); if (rc < 0) goto out; if (end_vaddr > brk) brk = end_vaddr; } /* * Mapping the user stack. * * In the "NOCOW" case, all the pages are pre-allocated. * In the default case instead, most of the pages are zero-mapped and so, * therefore, allocated on-demand. But, `USER_ARGS_PAGE_COUNT` pages are * pre-allocated anyway. */ const size_t pre_allocated_pages = MMAP_NO_COW ? USER_STACK_PAGES : USER_ARGS_PAGE_COUNT; const size_t zero_mapped_pages = USER_STACK_PAGES - pre_allocated_pages; const ulong stack_top = (USERMODE_VADDR_END - USER_STACK_PAGES * PAGE_SIZE); count = map_zero_pages(pinfo->pdir, (void *)stack_top, zero_mapped_pages, PAGING_FL_US | PAGING_FL_RW); if (count != zero_mapped_pages) { unmap_pages(pinfo->pdir, (void *)stack_top, count, true); rc = -ENOMEM; goto out; } for (u32 i = zero_mapped_pages; i < USER_STACK_PAGES; i++) { if ((rc = alloc_and_map_stack_page(pinfo->pdir, (void *)stack_top, i))) goto out; } // Finally setting the output-params. pinfo->stack = (void *) USERMODE_STACK_MAX; pinfo->entry = (void *) eh.header->e_entry; pinfo->brk = (void *) brk; out: vfs_close(elf_h); free_elf_headers(&eh); if (UNLIKELY(rc != 0)) { if (pinfo->pdir) { pdir_destroy(pinfo->pdir); pinfo->pdir = NULL; } if (pinfo->lf) release_subsys_flock(pinfo->lf); } return rc; } void get_symtab_and_strtab(Elf_Shdr **symtab, Elf_Shdr **strtab) { Elf_Ehdr *h = (Elf_Ehdr*)(KERNEL_PA_TO_VA(KERNEL_PADDR)); *symtab = NULL; *strtab = NULL; if (!KERNEL_SYMBOLS) return; VERIFY(h->e_shentsize == sizeof(Elf_Shdr)); Elf_Shdr *sections = (Elf_Shdr *)((void *)h + h->e_shoff); for (u32 i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; if (s->sh_type == SHT_SYMTAB) { ASSERT(!*symtab); *symtab = s; } else if (s->sh_type == SHT_STRTAB && i != h->e_shstrndx) { ASSERT(!*strtab); *strtab = s; } } VERIFY(*symtab != NULL); VERIFY(*strtab != NULL); } const char *find_sym_at_addr(ulong vaddr, long *offset, u32 *sym_size) { Elf_Shdr *symtab; Elf_Shdr *strtab; if (!KERNEL_SYMBOLS) return NULL; get_symtab_and_strtab(&symtab, &strtab); Elf_Sym *syms = (Elf_Sym *) symtab->sh_addr; const ulong sym_count = symtab->sh_size / sizeof(Elf_Sym); for (ulong i = 0; i < sym_count; i++) { Elf_Sym *s = syms + i; if (IN_RANGE(vaddr, s->st_value, s->st_value + s->st_size)) { if (offset) *offset = (long)(vaddr - s->st_value); if (sym_size) *sym_size = (u32) s->st_size; return (char *)strtab->sh_addr + s->st_name; } } return NULL; } ulong find_addr_of_symbol(const char *searched_sym) { Elf_Shdr *symtab; Elf_Shdr *strtab; if (!KERNEL_SYMBOLS) return 0; get_symtab_and_strtab(&symtab, &strtab); Elf_Sym *syms = (Elf_Sym *) symtab->sh_addr; const ulong sym_count = symtab->sh_size / sizeof(Elf_Sym); for (ulong i = 0; i < sym_count; i++) { if (!strcmp((char *)strtab->sh_addr + syms[i].st_name, searched_sym)) return syms[i].st_value; } return 0; } int foreach_symbol(int (*cb)(struct elf_symbol_info *, void *), void *arg) { Elf_Shdr *symtab; Elf_Shdr *strtab; int ret = 0; if (!KERNEL_SYMBOLS) return 0; get_symtab_and_strtab(&symtab, &strtab); Elf_Sym *syms = (Elf_Sym *) symtab->sh_addr; const ulong sym_count = symtab->sh_size / sizeof(Elf_Sym); for (ulong i = 0; i < sym_count; i++) { Elf_Sym *s = syms + i; struct elf_symbol_info info = { .vaddr = TO_PTR(s->st_value), .size = (u32) s->st_size, .name = (char *)strtab->sh_addr + syms[i].st_name, }; if ((ret = cb(&info, arg))) break; } return ret; } static void find_sym_at_addr_no_ret(ulong vaddr, long *offset, u32 *sym_size, const char **sym_name_ref) { *sym_name_ref = find_sym_at_addr(vaddr, offset, sym_size); } const char * find_sym_at_addr_safe(ulong vaddr, long *offset, u32 *sym_size) { const char *sym_name = NULL; fault_resumable_call(ALL_FAULTS_MASK, &find_sym_at_addr_no_ret, 4, vaddr, offset, sym_size, &sym_name); return sym_name; } static Elf_Shdr *kernel_elf_get_section(const char *section_name) { Elf_Ehdr *h = (Elf_Ehdr*)(KERNEL_PA_TO_VA(KERNEL_PADDR)); Elf_Shdr *sections = (Elf_Shdr *)((void *)h + h->e_shoff); Elf_Shdr *section_header_strtab = sections + h->e_shstrndx; for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; char *name = (char *)h + section_header_strtab->sh_offset + s->sh_name; if (!strcmp(name, section_name)) return s; } return NULL; } void call_kernel_global_ctors(void) { void (*ctor)(void); Elf_Shdr *ctors = kernel_elf_get_section(".ctors"); if (!ctors) { ctors = kernel_elf_get_section(".init_array"); if (!ctors) return; } void **ctors_begin = (void **)ctors->sh_addr; void **ctors_end = (void **)(ctors->sh_addr + ctors->sh_size); for (void **p = ctors_begin; p < ctors_end; p++) { /* * The C99 standard leaves casting from "void *" to a function pointer * undefined, that's why we assign write a value at &ctor instead of * just casing *p to void (*)(void). */ *(void **)(&ctor) = *p; ctor(); } } <file_sep>/****************************************************************************** * * Module Name: nswalk - Functions for walking the ACPI namespace * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nswalk") /******************************************************************************* * * FUNCTION: AcpiNsGetNextNode * * PARAMETERS: ParentNode - Parent node whose children we are * getting * ChildNode - Previous child that was found. * The NEXT child will be returned * * RETURN: ACPI_NAMESPACE_NODE - Pointer to the NEXT child or NULL if * none is found. * * DESCRIPTION: Return the next peer node within the namespace. If Handle * is valid, Scope is ignored. Otherwise, the first node * within Scope is returned. * ******************************************************************************/ ACPI_NAMESPACE_NODE * AcpiNsGetNextNode ( ACPI_NAMESPACE_NODE *ParentNode, ACPI_NAMESPACE_NODE *ChildNode) { ACPI_FUNCTION_ENTRY (); if (!ChildNode) { /* It's really the parent's _scope_ that we want */ return (ParentNode->Child); } /* Otherwise just return the next peer */ return (ChildNode->Peer); } /******************************************************************************* * * FUNCTION: AcpiNsGetNextNodeTyped * * PARAMETERS: Type - Type of node to be searched for * ParentNode - Parent node whose children we are * getting * ChildNode - Previous child that was found. * The NEXT child will be returned * * RETURN: ACPI_NAMESPACE_NODE - Pointer to the NEXT child or NULL if * none is found. * * DESCRIPTION: Return the next peer node within the namespace. If Handle * is valid, Scope is ignored. Otherwise, the first node * within Scope is returned. * ******************************************************************************/ ACPI_NAMESPACE_NODE * AcpiNsGetNextNodeTyped ( ACPI_OBJECT_TYPE Type, ACPI_NAMESPACE_NODE *ParentNode, ACPI_NAMESPACE_NODE *ChildNode) { ACPI_NAMESPACE_NODE *NextNode = NULL; ACPI_FUNCTION_ENTRY (); NextNode = AcpiNsGetNextNode (ParentNode, ChildNode); /* If any type is OK, we are done */ if (Type == ACPI_TYPE_ANY) { /* NextNode is NULL if we are at the end-of-list */ return (NextNode); } /* Must search for the node -- but within this scope only */ while (NextNode) { /* If type matches, we are done */ if (NextNode->Type == Type) { return (NextNode); } /* Otherwise, move on to the next peer node */ NextNode = NextNode->Peer; } /* Not found */ return (NULL); } /******************************************************************************* * * FUNCTION: AcpiNsWalkNamespace * * PARAMETERS: Type - ACPI_OBJECT_TYPE to search for * StartNode - Handle in namespace where search begins * MaxDepth - Depth to which search is to reach * Flags - Whether to unlock the NS before invoking * the callback routine * DescendingCallback - Called during tree descent * when an object of "Type" is found * AscendingCallback - Called during tree ascent * when an object of "Type" is found * Context - Passed to user function(s) above * ReturnValue - from the UserFunction if terminated * early. Otherwise, returns NULL. * RETURNS: Status * * DESCRIPTION: Performs a modified depth-first walk of the namespace tree, * starting (and ending) at the node specified by StartHandle. * The callback function is called whenever a node that matches * the type parameter is found. If the callback function returns * a non-zero value, the search is terminated immediately and * this value is returned to the caller. * * The point of this procedure is to provide a generic namespace * walk routine that can be called from multiple places to * provide multiple services; the callback function(s) can be * tailored to each task, whether it is a print function, * a compare function, etc. * ******************************************************************************/ ACPI_STATUS AcpiNsWalkNamespace ( ACPI_OBJECT_TYPE Type, ACPI_HANDLE StartNode, UINT32 MaxDepth, UINT32 Flags, ACPI_WALK_CALLBACK DescendingCallback, ACPI_WALK_CALLBACK AscendingCallback, void *Context, void **ReturnValue) { ACPI_STATUS Status; ACPI_STATUS MutexStatus; ACPI_NAMESPACE_NODE *ChildNode; ACPI_NAMESPACE_NODE *ParentNode; ACPI_OBJECT_TYPE ChildType; UINT32 Level; BOOLEAN NodePreviouslyVisited = FALSE; ACPI_FUNCTION_TRACE (NsWalkNamespace); /* Special case for the namespace Root Node */ if (StartNode == ACPI_ROOT_OBJECT) { StartNode = AcpiGbl_RootNode; } /* Null child means "get first node" */ ParentNode = StartNode; ChildNode = AcpiNsGetNextNode (ParentNode, NULL); ChildType = ACPI_TYPE_ANY; Level = 1; /* * Traverse the tree of nodes until we bubble back up to where we * started. When Level is zero, the loop is done because we have * bubbled up to (and passed) the original parent handle (StartEntry) */ while (Level > 0 && ChildNode) { Status = AE_OK; /* Found next child, get the type if we are not searching for ANY */ if (Type != ACPI_TYPE_ANY) { ChildType = ChildNode->Type; } /* * Ignore all temporary namespace nodes (created during control * method execution) unless told otherwise. These temporary nodes * can cause a race condition because they can be deleted during * the execution of the user function (if the namespace is * unlocked before invocation of the user function.) Only the * debugger namespace dump will examine the temporary nodes. */ if ((ChildNode->Flags & ANOBJ_TEMPORARY) && !(Flags & ACPI_NS_WALK_TEMP_NODES)) { Status = AE_CTRL_DEPTH; } /* Type must match requested type */ else if (ChildType == Type) { /* * Found a matching node, invoke the user callback function. * Unlock the namespace if flag is set. */ if (Flags & ACPI_NS_WALK_UNLOCK) { MutexStatus = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (MutexStatus)) { return_ACPI_STATUS (MutexStatus); } } /* * Invoke the user function, either descending, ascending, * or both. */ if (!NodePreviouslyVisited) { if (DescendingCallback) { Status = DescendingCallback (ChildNode, Level, Context, ReturnValue); } } else { if (AscendingCallback) { Status = AscendingCallback (ChildNode, Level, Context, ReturnValue); } } if (Flags & ACPI_NS_WALK_UNLOCK) { MutexStatus = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (MutexStatus)) { return_ACPI_STATUS (MutexStatus); } } switch (Status) { case AE_OK: case AE_CTRL_DEPTH: /* Just keep going */ break; case AE_CTRL_TERMINATE: /* Exit now, with OK status */ return_ACPI_STATUS (AE_OK); default: /* All others are valid exceptions */ return_ACPI_STATUS (Status); } } /* * Depth first search: Attempt to go down another level in the * namespace if we are allowed to. Don't go any further if we have * reached the caller specified maximum depth or if the user * function has specified that the maximum depth has been reached. */ if (!NodePreviouslyVisited && (Level < MaxDepth) && (Status != AE_CTRL_DEPTH)) { if (ChildNode->Child) { /* There is at least one child of this node, visit it */ Level++; ParentNode = ChildNode; ChildNode = AcpiNsGetNextNode (ParentNode, NULL); continue; } } /* No more children, re-visit this node */ if (!NodePreviouslyVisited) { NodePreviouslyVisited = TRUE; continue; } /* No more children, visit peers */ ChildNode = AcpiNsGetNextNode (ParentNode, ChildNode); if (ChildNode) { NodePreviouslyVisited = FALSE; } /* No peers, re-visit parent */ else { /* * No more children of this node (AcpiNsGetNextNode failed), go * back upwards in the namespace tree to the node's parent. */ Level--; ChildNode = ParentNode; ParentNode = ParentNode->Parent; NodePreviouslyVisited = TRUE; } } /* Complete walk, not terminated by user function */ return_ACPI_STATUS (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/fs/vfs_base.h> struct sysfs_inode; struct sysfs_entry; struct sysobj; struct sysobj_prop_type { /* * Get the size of a buffer able to contain all the data returned by load(). * This function can return values in the whole domain of `offt` (long). * * > 0: means simply "buffer_size". In this case, the file backed by this * property type will support seek(), but the contents of the file * will be loaded only once, during open() and will be stored only * once, during close(). This is suitable for big blobs of MUTABLE * data. Example application: kernel coverage files. * * = 0: means there's no buffer. In this case, read() and write(0 on the * file backed by this property type will call directly load() and * store(), every time. No seek() support whatsoever. This is the * typical case for small properties like boolean or integer config * options. Very common. Example application: kernel config flags. * * < 0: means "- buffer_size", but does NOT require the allocation of a * dedicated buffer during open(). It allows seek() though, because * the backing data is assumed to be completely IMMUTABLE, once the * sysobj is created. Example application: kernel symbol table. */ offt (*get_buf_sz)(struct sysobj *obj, void *data); /* * Load the property data at offset `off` into the `buf` buffer, assumed to * be at least `sz` bytes large. Note: the `off` argument can be > 0 * only when get_buf_sz() returned a value < 0. In all the other cases, it * must be 0. * * Returns the number of bytes loaded into `buf` or an error in case the * value is < 0. */ offt (*load)(struct sysobj *obj, void *data, void *buf, offt sz, offt off); /* * Store data into `buf` into the property rappresented by `prop_data`. * The `buf` buffer is assumed to be at least `sz` large. * * Returns the number of bytes actually read from `buf` or an error in case * the value is < 0. */ offt (*store)(struct sysobj *obj, void *data, void *buf, offt sz); /* * Get the underlying data pointer (allows mmap to work). * At the moment, that is supported only when get_buf_sz() returns < 0. */ void *(*get_data_ptr)(struct sysobj *obj, void *data); }; struct sysobj_prop { const char *name; /* actual name of a file in sysfs */ const struct sysobj_prop_type *type; }; struct sysobj_type { const char *name; /* internal name, not visible in sysfs */ struct sysobj_prop **properties; /* pointer to a NULL-terminated array of pointers to sysobj_prop objects */ }; struct sysobj_hooks { offt (*pre_load)(struct sysobj *, struct sysobj_prop *, void *); void (*post_load)(struct sysobj *, struct sysobj_prop *, void *); offt (*pre_store)(struct sysobj *, struct sysobj_prop *, void *); void (*post_store)(struct sysobj *, struct sysobj_prop *, void *); }; struct sysobj { /* Sysfs public fields */ struct list_node node; struct list children_list; struct sysobj_type *type; struct sysobj_hooks *hooks; void **prop_data; /* Fields completely managed by the upper layers */ void *extra; /* Sysfs internal fields */ bool prop_data_owned; bool type_owned; bool object_owned; /* sysfs allocated the object */ struct sysfs_inode *inode; struct sysfs_entry *entry; struct sysobj *parent; }; /* * Default objects of the main sysfs instance, the one created by init_sysfs(). * See the comments above create_sysfs(). */ extern struct sysobj sysfs_root_obj; extern struct sysobj sysfs_hw_obj; extern struct sysobj sysfs_power_obj; extern struct sysobj sysfs_storage_obj; extern struct sysobj sysfs_network_obj; extern struct sysobj sysfs_display_obj; extern struct sysobj sysfs_media_obj; extern struct sysobj sysfs_bridge_obj; extern struct sysobj sysfs_comm_obj; extern struct sysobj sysfs_genp_obj; extern struct sysobj sysfs_input_obj; extern struct sysobj sysfs_serbus_obj; extern struct sysobj sysfs_wifi_obj; extern struct sysobj sysfs_sigproc_obj; extern struct sysobj sysfs_other_obj; /* * Create a sysfs instance. * * Note: Tilck's sysfs is DIFFERENT from Linux kernel's sysfs. Indeed, it can * and will be used for several different purposes: * * - Provide a Tilck specific /syst * - Provide a minimal Linux-compatibile /proc (future) * - Provide a minimal Linux-compatibile /sys (future) * - Maybe replace Tilck's devfs (future) */ struct mnt_fs * create_sysfs(void); /* * Basic function for initializing a caller-allocated sysobj. * * NOTE: when the sysobj is destroyed, the caller is responsible for freeing * the `type` and the `prop_data` objects. In other words, the ownership is not * transferred to the sysfs layer. */ void sysobj_init(struct sysobj *obj, struct sysobj_type *type, struct sysobj_hooks *hooks, void **prop_data); /* * Dynamically create a sysobj of type `type` having the values of its * properties specified as varargs. Uses dynamic property data. * * Note[1]: the number of varargs (after `hooks`) must be exactly as the number * of properties of `type`. * * Note[2]: the ownership of `type`, `hooks` and `prop_data` is NOT transferred * to sysfs. */ struct sysobj * sysfs_create_obj(struct sysobj_type *type, struct sysobj_hooks *hooks, ...); /* * va_list variant of sysfs_create_obj(), used mostly internally. * Note: the ownership of `type` and `hooks` is NOT transferred to sysfs. */ struct sysobj * sysfs_create_obj_va(struct sysobj_type *type, struct sysobj_hooks *hooks, va_list args); /* * Base variant of sysfs_create_obj(). * * Note: the ownership of `type`, `hooks` and `prop_data` is NOT transferred * to sysfs. */ struct sysobj * sysfs_create_obj_va_arr(struct sysobj_type *type, struct sysobj_hooks *hooks, void **prop_data); /* * Create a sys object with a dedicated type, created on the fly. * * This function is very useful to create unique objects that don't share their * type with any other sys object. The first argument is the name of the obj's * type (internal-only field, not visible from userland). Then, it follows a * list of pairs <property, property data> and the whole thing ends up with a * trailing NULL. In case the properties are static config properties defined * with the DEF_STATIC_CONF_* macros, using SYSOBJ_CONF_PROP_PAIR() will make * this function even simpler to use. See config.c. * * Note: the ownership of `hooks` is NOT transferred to sysfs. */ struct sysobj * sysfs_create_custom_obj(const char *type_name, struct sysobj_hooks *hooks, ...); /* * va_list variant of sysfs_create_custom_obj(), used mostly internally. * Note: the ownership of `hooks` is NOT transferred to sysfs. */ struct sysobj * sysfs_create_custom_obj_va(const char *type_name, struct sysobj_hooks *hooks, u32 args_cnt, va_list args); /* * Create an empty sys object. Basically, just a directory in sysfs. */ struct sysobj * sysfs_create_empty_obj(void); /* * Destroy a not-yet-registered sys object. * * It's supposed to be used in error code-paths. The destruction of registered * objects is NOT supported. * * Details: this function might also free the type object (along with its * `properties` array of pointers) AND the `prop_data` array as well, depending * on how the object has been created. * * The general rule (always valid) * --------------------------------- * * If the caller of the function used to create the object passed to it a type * pointer, that type WILL NOT be freed. Otherwise, if the type has been created * by the create function (e.g. sysfs_create_custom_obj()), then it will be * freed. * * The same rule applies to `prop_data` array: often, it's allocated by the * create function and there will be freed by this function. In the special * cases (e.g. sysfs_create_obj_va_arr) where the caller passed the `prop_data` * array to the sysfs create function, the `prop_data` will not be freed. * * In the most generic case where the sys object has been created outside of * sysfs and it has been initialized with sysobj_init(), clearly the caller owns * everything and MUST NOT call sysfs_destroy_unregistered_obj(). */ void sysfs_destroy_unregistered_obj(struct sysobj *obj); /* * Register a sys object in the `fs` sysfs instance, under the object `parent`. * * Notes: * * 1. In order to register an object into the main sysfs instance, pass * NULL to `fs`. * * 2. In order to register the root object, pass NULL to parent. * * 3. The main sysfs instace has always a root object and it's called: * sysfs_root_obj (see below). * * 4. The contents of `name` are copied into sysfs. The buffer is NOT * required to exist after this call. */ int sysfs_register_obj(struct mnt_fs *fs, struct sysobj *parent, const char *name, struct sysobj *obj); /* * Sym-link a sysobj under a different parent with a different name. */ int sysfs_symlink_obj(struct mnt_fs *fs, struct sysobj *new_parent, const char *new_name, struct sysobj *obj); /* * Create and initialize Tilck's main sysfs instance, /syst. */ void init_sysfs(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal_types.h> #include <tilck/kernel/interrupts.h> struct irq_handler_node { struct list_node node; irq_handler_t handler; void *context; /* device-specific context, passed to the handler */ }; #define DEFINE_IRQ_HANDLER_NODE(node_name, func, ctx) \ static struct irq_handler_node node_name = { \ .node = STATIC_LIST_NODE_INIT(node_name.node), \ .handler = (func), \ .context = (ctx), \ }; void init_irq_handling(); void irq_install_handler(u8 irq, struct irq_handler_node *n); void irq_uninstall_handler(u8 irq, struct irq_handler_node *n); void irq_set_mask(int irq); void irq_clear_mask(int irq); bool irq_is_masked(int irq); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <iostream> #include <random> #include "vfs_test.h" using namespace std; using namespace testing; class vfs_fat32 : public vfs_test_base { protected: struct mnt_fs *fat_fs; size_t fatpart_size; void SetUp() override { vfs_test_base::SetUp(); const char *buf = load_once_file(TEST_FATPART_FILE, &fatpart_size); fat_fs = fat_mount_ramdisk((void *) buf, fatpart_size, 0); ASSERT_TRUE(fat_fs != NULL); mp_init(fat_fs); } void TearDown() override { fat_umount_ramdisk(fat_fs); vfs_test_base::TearDown(); } }; TEST_F(vfs_fat32, read_content_of_longname_file) { int r; char data[128] = {0}; const char *file_path = "/testdir/This_is_a_file_with_a_veeeery_long_name.txt"; fs_handle h = NULL; r = vfs_open(file_path, &h, 0, O_RDONLY); ASSERT_TRUE(r == 0); ASSERT_TRUE(h != NULL); ssize_t res = vfs_read(h, data, sizeof(data)); vfs_close(h); EXPECT_GT(res, 0); ASSERT_STREQ("Content of file with a long name\n", data); } TEST_F(vfs_fat32, fseek) { random_device rdev; const auto seed = rdev(); default_random_engine engine(seed); lognormal_distribution<> dist(4.0, 3); off_t linux_lseek; off_t tilck_fseek; off_t linux_pos; off_t tilck_pos; cout << "[ INFO ] random seed: " << seed << endl; int r; const char *fatpart_file_path = "/bigfile"; const char *real_file_path = PROJ_BUILD_DIR "/test_sysroot/bigfile"; int fd = open(real_file_path, O_RDONLY); size_t file_size = lseek(fd, 0, SEEK_END); fs_handle h = NULL; r = vfs_open(fatpart_file_path, &h, 0, O_RDONLY); ASSERT_TRUE(r == 0); ASSERT_TRUE(h != NULL); char buf_tilck[64]; char buf_linux[64]; linux_lseek = lseek(fd, file_size / 2, SEEK_SET); tilck_fseek = vfs_seek(h, file_size / 2, SEEK_SET); ASSERT_EQ(linux_lseek, tilck_fseek); off_t last_pos = lseek(fd, 0, SEEK_CUR); linux_pos = last_pos; tilck_pos = vfs_seek(h, 0, SEEK_CUR); ASSERT_EQ(linux_pos, tilck_pos); (void)last_pos; const int iters = 10000; for (int i = 0; i < iters; i++) { int saved_errno = 0; /* random file offset where to seek */ off_t offset = (off_t) ( dist(engine) - dist(engine)/1.3 ); linux_lseek = lseek(fd, offset, SEEK_CUR); if (linux_lseek < 0) saved_errno = errno; tilck_fseek = vfs_seek(h, offset, SEEK_CUR); linux_pos = lseek(fd, 0, SEEK_CUR); tilck_pos = vfs_seek(h, 0, SEEK_CUR); if (linux_lseek < 0) { /* * Linux syscalls return -ERRNO_VALUE in case something goes wrong, * while the glibc wrappers return -1 and set errno. Since we're * testing the value returned by the syscall in Tilck, we need to * revert that. */ linux_lseek = -saved_errno; } ASSERT_EQ(tilck_fseek, linux_lseek) << "Offset: " << offset << endl << "Curr pos (glibc): " << linux_pos << endl << "Curr pos (tilck): " << tilck_pos << endl; ASSERT_EQ(tilck_pos, linux_pos); memset(buf_linux, 0, sizeof(buf_linux)); memset(buf_tilck, 0, sizeof(buf_tilck)); ssize_t linux_read = read(fd, buf_linux, sizeof(buf_linux)); ssize_t tilck_read = vfs_read(h, buf_tilck, sizeof(buf_tilck)); ASSERT_EQ(tilck_read, linux_read); linux_pos = lseek(fd, 0, SEEK_CUR); tilck_pos = vfs_seek(h, 0, SEEK_CUR); ASSERT_EQ(tilck_pos, linux_pos); if (memcmp(buf_tilck, buf_linux, sizeof(buf_linux)) != 0) { cout << "Buffers differ. " << endl; cout << "Last offset: " << offset << endl; cout << "Curr pos: " << linux_pos << endl; cout << "read ret: " << linux_read << endl; test_dump_buf(buf_linux, "Linux buf: ", 0, sizeof(buf_linux)); test_dump_buf(buf_linux, "Tilck buf: ", 0, sizeof(buf_linux)); FAIL() << "memcmp failed"; } last_pos = linux_pos; } vfs_close(h); close(fd); } TEST_F(vfs_fat32, pread_not_supported) { const char *fatpart_file_path = "/bigfile"; fs_handle h = NULL; char buf[32]; int rc; rc = vfs_open(fatpart_file_path, &h, 0, O_RDONLY); ASSERT_TRUE(rc == 0); ASSERT_TRUE(h != NULL); rc = vfs_pread(h, buf, sizeof(buf), 0 /* offset */); EXPECT_EQ(rc, -EPERM); rc = vfs_pread(h, buf, sizeof(buf), 10 /* offset */); EXPECT_EQ(rc, -EPERM); vfs_close(h); } class vfs_ramfs : public vfs_test_base { protected: struct mnt_fs *mnt_fs; void SetUp() override { vfs_test_base::SetUp(); mnt_fs = ramfs_create(); ASSERT_TRUE(mnt_fs != NULL); mp_init(mnt_fs); } void TearDown() override { // TODO: destroy ramfs vfs_test_base::TearDown(); } /* Custom test helper functions */ void test_pread_pwrite_seek(bool fseek); }; TEST_F(vfs_ramfs, create_and_unlink_file) { static const char my_data[] = "hello world"; fs_handle h; int rc; char buf[32]; rc = vfs_open("/file1", &h, O_CREAT | O_RDWR, 0644); ASSERT_EQ(rc, 0); rc = vfs_write(h, (void *)my_data, sizeof(my_data)); ASSERT_EQ(rc, (int)sizeof(my_data)); vfs_close(h); rc = vfs_open("/file1", &h, O_RDWR, 0644); ASSERT_EQ(rc, 0); rc = vfs_read(h, buf, sizeof(buf)); ASSERT_EQ(rc, (int)sizeof(my_data)); ASSERT_STREQ(buf, my_data); vfs_close(h); rc = vfs_unlink("/file1"); ASSERT_EQ(rc, 0); rc = vfs_open("/file1", &h, O_RDWR, 0); ASSERT_EQ(rc, -ENOENT); } void vfs_ramfs::test_pread_pwrite_seek(bool fseek) { const off_t data_size = 2 * MB; const int iters = 10000; const char *const path = "/bigfile_random_data"; constexpr size_t buf_size = 64; random_device rdev; const auto seed = rdev(); default_random_engine engine(seed); lognormal_distribution<> off_dist(4.0, 3); uniform_int_distribution<uint8_t> data_dist(0, 255); uniform_int_distribution<uint8_t> op_dist(0, 1); fs_handle h; char buf[buf_size] = {0}; vector<uint8_t> data; char *data_buf; off_t rc, curr_pos = 0; data.reserve(data_size); cout << "[ INFO ] random seed: " << seed << endl; for (int i = 0; i < data_size; i++) { data.push_back(data_dist(engine)); } ASSERT_EQ(data.size(), (size_t)data_size); data_buf = (char *)&data[0]; rc = vfs_open(path, &h, O_CREAT | O_RDWR, 0644); ASSERT_EQ(rc, 0); auto clean_up = [&]() { if (h) { vfs_close(h); rc = vfs_unlink(path); ASSERT_EQ(rc, 0); rc = vfs_open(path, &h, O_RDWR, 0); ASSERT_EQ(rc, -ENOENT); } }; { off_t written = 0; while (written < data_size) { rc = vfs_write(h, data_buf + written, data_size - written); if (rc <= 0) { clean_up(); FAIL() << "initial vfs_write() failed with: " << rc; } written += rc; } } vfs_close(h); rc = vfs_open(path, &h, O_RDWR, 0644); ASSERT_EQ(rc, 0); for (int i = 0; i < iters; i++) { const uint8_t op = op_dist(engine); const off_t off = (off_t) ( off_dist(engine) - off_dist(engine)/1.3 ); const off_t target_pos = off + curr_pos; if (target_pos < 0 || target_pos >= data_size) { i--; continue; /* invalid offset, re-try the iteration */ } const off_t rem = data_size - target_pos; if (fseek) { /* Change the offset with a seek operation */ off_t res = vfs_seek(h, off, SEEK_CUR); if (res < 0) { clean_up(); FAIL() << "vfs_seek() failed with: " << res; } if (res != target_pos) { clean_up(); ASSERT_EQ(res, target_pos); } if ((res = vfs_seek(h, 0, SEEK_CUR)) != target_pos) { clean_up(); FAIL() << "pos(" << res << ") != target_pos(" << target_pos << ")"; } if ((res = vfs_seek(h, target_pos, SEEK_SET)) != target_pos) { clean_up(); FAIL() << "pos(" << res << ") != target_pos(" << target_pos << ")"; } curr_pos = target_pos; } if (op == 0) { /* read */ off_t to_read = min((off_t)sizeof(buf), rem); if (fseek) { rc = vfs_read(h, buf, to_read); } else { rc = vfs_pread(h, buf, to_read, target_pos); } if (rc < 0) { clean_up(); FAIL() << "vfs_read() failed with: " << rc; } if (rc != to_read) { clean_up(); ASSERT_EQ(rc, to_read); } /* Compare the data in the mem buffer with what we read from VFS */ if (memcmp(data_buf + target_pos, buf, to_read) != 0) { clean_up(); test_dump_buf(data_buf, "Expected: ", target_pos, to_read); test_dump_buf(buf, "Read: ", 0, to_read); FAIL() << "memcmp failed"; } if (fseek) curr_pos += rc; } else { /* write */ off_t to_write = min((off_t)sizeof(buf), rem); if (fseek) { rc = vfs_write(h, buf, to_write); } else { rc = vfs_pwrite(h, buf, to_write, target_pos); } if (rc < 0) { clean_up(); FAIL() << "vfs_write() failed with: " << rc; } if (rc != to_write) { clean_up(); ASSERT_EQ(rc, to_write); } /* Write the new data on the curr_pos in our mem buffer */ memmove(data_buf + target_pos, buf, to_write); if (fseek) curr_pos += rc; } } clean_up(); } TEST_F(vfs_ramfs, pread_pwrite) { ASSERT_NO_FATAL_FAILURE({ test_pread_pwrite_seek(false); }); } TEST_F(vfs_ramfs, seek) { ASSERT_NO_FATAL_FAILURE({ test_pread_pwrite_seek(true); }); } class compute_abs_path_test : public TestWithParam< tuple<const char *, const char *, const char *> > { }; TEST_P(compute_abs_path_test, check) { const auto &t = GetParam(); const char *cwd = get<0>(t); const char *path = get<1>(t); const char *expected = get<2>(t); char output[256]; int rc = compute_abs_path(path, cwd, output, sizeof(output)); if (rc < 0) FAIL() << "Errno: " << rc; ASSERT_STREQ(output, expected); } INSTANTIATE_TEST_SUITE_P( abs_path, compute_abs_path_test, Values( make_tuple("/", "/a/b/c", "/a/b/c"), make_tuple("/", "/a/b/c/", "/a/b/c/"), make_tuple("/", "/a/b/c/..", "/a/b"), make_tuple("/", "/a/b/c/../", "/a/b/") ) ); INSTANTIATE_TEST_SUITE_P( rel_path, compute_abs_path_test, Values( make_tuple("/", "a/b/c", "/a/b/c"), make_tuple("/", "a/b/c/", "/a/b/c/"), make_tuple("/", "a/b/c/..", "/a/b"), make_tuple("/", "a/b/c/../", "/a/b/") ) ); INSTANTIATE_TEST_SUITE_P( rel_dot_slash_path, compute_abs_path_test, Values( make_tuple("/", "./a/b/c", "/a/b/c"), make_tuple("/", "./a/b/c/", "/a/b/c/"), make_tuple("/", "./a/b/c/..", "/a/b"), make_tuple("/", "./a/b/c/../", "/a/b/") ) ); INSTANTIATE_TEST_SUITE_P( rel_path_cwd_not_root, compute_abs_path_test, Values( make_tuple("/a/b/c/", "a", "/a/b/c/a"), make_tuple("/a/b/c/", "a/", "/a/b/c/a/"), make_tuple("/a/b/c/", "..", "/a/b"), make_tuple("/a/b/c/", "../", "/a/b/"), make_tuple("/a/b/c/", "../..", "/a"), make_tuple("/a/b/c/", "../../", "/a/"), make_tuple("/a/b/c/", "../../.", "/a"), make_tuple("/a/b/c/", "../.././", "/a/"), make_tuple("/a/b/c/", "../../..", "/"), make_tuple("/a/b/c/", "../../../", "/") ) ); INSTANTIATE_TEST_SUITE_P( try_go_beyond_root, compute_abs_path_test, Values( make_tuple("/a/b/c/", "../../../..", "/"), make_tuple("/a/b/c/", "../../../../", "/") ) ); INSTANTIATE_TEST_SUITE_P( multiple_slashes, compute_abs_path_test, Values( make_tuple("/a/b/c/", "d//e", "/a/b/c/d/e"), make_tuple("/a/b/c/", "d///e", "/a/b/c/d/e") ) ); INSTANTIATE_TEST_SUITE_P( other, compute_abs_path_test, Values( make_tuple("/a/b/c/", ".a", "/a/b/c/.a"), make_tuple("/a/b/c/", "..a", "/a/b/c/..a"), make_tuple("/", "something..", "/something.."), make_tuple("/", "something.", "/something.") ) ); <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). send_to_vm_and_find_text(r"dp{ret}", True, [ "TilckDebugPanel", "TERM_ROWS", "DEBUG_CHECKS", ]) send_to_vm_and_find_text(r"2", True, [ "START", "END", "usable physical mem", ]) send_to_vm_and_find_text(r"3", True, [ "Usable", "Used", "vaddr", ]) send_to_vm_and_find_text(r"4", True, [ "pid", "tty", "cmdline", ]) send_to_vm_and_find_text(r"5", True, [ "counters", ]) send_to_vm_and_find_text(r"6", True, []) send_string_to_vm(r"q") <file_sep> # Debugging ## Contents * [Debugging the kernel with GDB](#debugging-the-kernel-with-gdb) - [Custom GDB commands](#custom-gdb-commands) * [list-tasks](#list-tasks) * [list-procs](#list-procs) * [get-task](#get-task-tid) * [get-proc](#get-proc-pid) * [get-handle2](#get-handle2-pid-handle) * [get-handle](#get-handle-handle) * [get-curr](#get-curr) * [get-currp](#get-currp) * [Tilck's debug panel](#tilcks-debug-panel) * [Debugging Tilck's bootloader](#debugging-tilcks-bootloader) - [Debugging the legacy bootloader](#debugging-the-legacy-bootloader) - [Debugging the UEFI bootloader](#debugging-the-uefi-bootloader) * [Details about BaseAddr](#details-about-baseAddr) ## Debugging the kernel with GDB As explained in the README.md file, it's easy to debug Tilck's kernel while it's running inside a QEMU virtual machine. By default, the `run_nokvm_qemu` script runs `QEMU` with the `-s` option, a shorthand for `-gdb tcp::1234`. Therefore, once Tilck has booted we can connect with GDB as if we'd do for any other process debugged remotely: ``` $ gdb ./build/tilck_unstripped Reading symbols from ./build/tilck_unstripped... (gdb) target remote :1234 Remote debugging using :1234 need_reschedule () at /home/vlad/dev/tilck/include/tilck/kernel/sched.h:154 154 return atomic_load_explicit(&__need_resched, mo_relaxed); (gdb) ``` Or, we can set a breakpoint to `kmain()` during the boot stage and then allow the VM to run, in order to debug the kernel during its initialization. One detail omitted in README.md is that we can change the port number used by QEMU's GDB server using the GDB_PORT environment variable: ``` GDB_PORT=9999 ./build/run_qemu ``` Another detail omitted in the README.md is that running `run_nokvm_qemu` is necessary, even if we have `KVM` installed on the machine. That's because QEMU has *limited* support for debugging VMs using hardware-virtualization. For example, it happens that breakpoints are missed. ### Custom GDB commands One "detail" omitted until now is that running GDB like explained, triggers a warning about the auto-loading of GDB scripts found in *unsafe* locations like: ``` Reading symbols from ./build/tilck_unstripped... warning: File "/home/vlad/dev/tilck/build/tilck_unstripped-gdb.py" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load". To enable execution of this file add add-auto-load-safe-path /home/vlad/dev/tilck/build/tilck_unstripped-gdb.py line to your configuration file "/home/vlad/.gdbinit". To completely disable this security protection add set auto-load safe-path / line to your configuration file "/home/vlad/.gdbinit". For more information about this security protection see the "Auto-loading safe path" section in the GDB manual. E.g., run from the shell: info "(gdb)Auto-loading safe path" ``` To allow GDB to load our custom script, add the following line in your `~/.gdbinit` file: ``` add-auto-load-safe-path <ABSOLUTE-PATH-OF-TILCK-BUILD-DIRECTORY> ``` Also, for a better debug experience add also: ``` set print pretty on ``` After that, GDB won't complain anymore and it will load Tilck's custom GDB script, as expected and the `tilck_unstripped-gdb.py` GDB script will import other scripts from the `other/gdb_scripts` directory. The scripts will add both custom pretty printers and custom commands. Plus, there's a special command called `list-tilck-cmds` to list all the custom commands: ``` Reading symbols from ./build/tilck_unstripped... (gdb) list-tilck-cmds list-tasks list-procs list-tilck-cmds get-task get-proc get-handle2 get-handle get-curr get-currp (gdb) ``` #### list-tasks This command will enlist all the tasks on the system: ``` (gdb) list-tasks $14 = (struct task *) 0xc0062c00 {tid = 1, pid = 1, SLEEPING, cmdline = /initrd/bin/init} $15 = (struct task *) 0xc7b82400 {tid = 36, pid = 36, SLEEPING, cmdline = /bin/ash} $16 = (struct task *) 0xc7b83000 {tid = 37, pid = 37, SLEEPING, cmdline = /initrd/bin/init} $17 = (struct task *) 0xc7b83400 {tid = 38, pid = 38, SLEEPING, cmdline = /initrd/bin/init} ------------------ Kernel threads ------------------ $18 = (struct task *) 0xc01f8d00 <buf+36096> {tid = 10001, RUNNABLE, kthread_name = wth_run} $19 = (struct task *) 0xc01f9200 <buf+37376> {tid = 10002, RUNNABLE, kthread_name = wth_run} $20 = (struct task *) 0xc01f9900 <buf+39168> {tid = 10004, SLEEPING, kthread_name = fb_blink_thread} $21 = (struct task *) 0xc01f9a00 <buf+39424> {tid = 10005, SLEEPING, kthread_name = fb_update_banner} $22 = (struct task *) 0xc01f9b00 <buf+39680> {tid = 10006, RUNNING, kthread_name = idle} $23 = (struct task *) 0xc01f9e00 <buf+40448> {tid = 10007, SLEEPING, kthread_name = wth_run} $24 = (struct task *) 0xc01f9f00 <buf+40704> {tid = 10008, SLEEPING, kthread_name = clock_drift_adj} $25 = (struct task *) 0xc002bd00 {tid = 10010, SLEEPING, kthread_name = wth_run} $26 = (struct task *) 0xc0062100 {tid = 10011, SLEEPING, kthread_name = wth_run} (gdb) ``` #### list-procs Similar to `list-tasks`, but it will show just the user processes. Note: while for the moment there's no multi-threading support, in the future there might be and, each user process might be associated to more than 1 task (thread). ``` (gdb) list-procs $27 = (struct process *) 0xc0062cb0 { pid = 1, cmdline = '/initrd/bin/init' } $28 = (struct process *) 0xc7b824b0 { pid = 36, cmdline = '/bin/ash' } $29 = (struct process *) 0xc7b830b0 { pid = 37, cmdline = '/initrd/bin/init' } $30 = (struct process *) 0xc7b834b0 { pid = 38, cmdline = '/initrd/bin/init' } (gdb) ``` #### get-task TID Dump the `struct task` for the task `TID`. ``` (gdb) get-task 1 $33 = *(struct task *) 0xc0062c00 = { tid = 1, pi = (struct process *) 0xc0062cb0, state = TASK_STATE_SLEEPING, kthread_name = 0x0, is_main_thread = true, running_in_kernel = true, stopped = false, was_stopped = false, vfork_stopped = false, traced = false, kernel_stack = 0xf802e000, args_copybuf = 0xc0073000, io_copybuf = 0xc0070000, wstatus = 0, timeslice_ticks = 1, total_ticks = 3, total_kernel_ticks = 2, ticks_before_wake_up = 0, timer_ready = false, wobj = *(struct wait_obj *) 0xc0062c84 = { type = WOBJ_TASK, extra = 0, tid = <any child> }, state_regs = *(struct x86_regs *) 0xf802fd34 = { resume_eip = 0xc010321d <asm_save_regs_and_schedule+45>, custom_flags = 0x00000000, gs = 0x0010, es = 0x0010, ds = 0x0010, fs = 0x0010, edi = 0xf802fef4, esi = 0x00000000, ebp = 0xf802fdcc, esp = 0xf802fd6c, ebx = 0x00000000, edx = 0xc0062c38, ecx = 0x00000000, eax = 0xc0135748, int_num = -1, err_code = 0x00000206, eip = 0x00000002, cs = 0x0002, eflags = 0x00000296, useresp = 0xc012a0a7, [true_eip] = 0xc0135748 <sys_waitpid+592> } } (gdb) ``` #### get-proc PID Dump the `struct process` for the process `PID`. ``` (gdb) get-proc 1 $34 = *(struct process *) 0xc0062cb0 = { pid = 1, cmdline = "/initrd/bin/init", parent_pid = 0, pgid = 1, sid = 1, brk = 0x8051000, initial_brk = 0x8050000, children = {36, 37, 38}, did_call_execve = true, vforked = false, inherited_mmap_heap = false, str_cwd = "/", handles = {0, 1, 2, 3}, mi = (null) } (gdb) ``` #### get-handle2 PID HANDLE Dump the base handle struct for the given handle. ``` (gdb) get-handle2 1 0 $35 = *(struct fs_handle_base *) 0xc00615c0 = { pi = 1, fs = 0xc01f9ce0 <buf+40160>, fs_type = devfs, fd_flags = 0, fl_flags = 32768, spec_flags = (none), pos = 0 } ``` #### get-handle HANDLE Exactly like `get-handle2`, but assumes as PID the current one. #### get-curr Dump the `struct task` of the current task. ``` (gdb) get-curr $39 = *(struct task *) 0xc01f9b00 = { tid = 10006, pi = <kernel_process_pi>, state = TASK_STATE_RUNNING, kthread_name = 0xc01a2d44 "idle", is_main_thread = false, running_in_kernel = true, stopped = false, was_stopped = false, vfork_stopped = false, traced = false, kernel_stack = 0xf801a000, args_copybuf = 0x0, io_copybuf = 0x0, wstatus = 0, timeslice_ticks = 3, total_ticks = 342, total_kernel_ticks = 342, ticks_before_wake_up = 0, timer_ready = false, wobj = *(struct wait_obj *) 0xc01f9b84, state_regs = *(struct x86_regs *) 0xf801bf8c = { resume_eip = 0xc0103115 <asm_irq_entry+58>, custom_flags = 0x00000000, gs = 0x0010, es = 0x0010, ds = 0x0010, fs = 0x0010, edi = 0x00000000, esi = 0x00000000, ebp = 0xf801bff0, esp = 0xf801bfc4, ebx = 0x00000000, edx = 0x00000000, ecx = 0x00000000, eax = 0x00000157, int_num = 32, err_code = 0x00000000, eip = 0xc012a6ac <idle+91>, cs = 0x0008, eflags = 0x00000246, useresp = 0x00000000, useresp = 0x00000000, ss = 0x0000 } } (gdb) ``` #### get-currp Like `get-curr`, but dumps the `struct process`. Note: in this case, pid is 0 because the current task is a kernel thread, therefore `get-currp` dumps the special `kernel_process_pi` object. ``` (gdb) get-currp $38 = *(struct process *) 0xc0212290 = { pid = 0, cmdline = (null), parent_pid = 0, pgid = 0, sid = 0, brk = 0x0, initial_brk = 0x0, children = {1}, did_call_execve = false, vforked = false, inherited_mmap_heap = false, str_cwd = "/", handles = {}, mi = (null) } ``` ## Tilck's debug panel As mentioned in the README.md file, Tilck has a nice developer-only feature called **debug panel** or **dp**. To open it, just run the `dp` *wrapper* program. ![Tilck's debug panel](http://vvaltchev.github.io/tilck_imgs/v2/screenshots/dp01.png) Using it is trivial: just switch tabs using the digits and scroll up and down their content using the `PAGE_UP` and `PAGE_DOWN` keys. Its most interesting feature is probably its embedded **syscall tracer**. To use it, first go to the `tasks` tab. ![Tilck's debug panel](http://vvaltchev.github.io/tilck_imgs/v2/screenshots/dp04.png) Then, enter in *select mode* by pressing ENTER and select a user process. After that, mark it as *traced* by pressing `t`. Finally, enter in *tracing mode* by pressing `Ctrl+T`. In alternative, it's possible to enter in tracing mode directly by running `tracer`. Once there, press `h` for the help menu. ![Tilck's debug panel](http://vvaltchev.github.io/tilck_imgs/v2/screenshots/tracing01.png) Once there, press `ENTER` to start/stop the syscall tracing. This whole feature is particularly useful if the debug panel is run on a serial console: this way its possibile to see at the same time the traced program *and* its syscall trace. To do that, run the `qemu` VM this way: ./build/run_qemu -serial pty In addition to the VM window, you'll see on the terminal something like: char device redirected to /dev/pts/4 (label serial0) Open another virtual terminal, install `screen` if you don't have it, and run: screen /dev/pts/4 You'll just connect to a Tilck serial console. Just press ENTER there and run `dp` as previously explained. ![Tilck's debug panel](http://vvaltchev.github.io/tilck_imgs/v2/screenshots/tracing02.png) Note: recent versions of QEMU (>= 4.0) have a built-in serial console that can be opened by using its GUI, without special command-line options and without using the `screen` application. ## Debugging Tilck's bootloader While Tilck's bootloader looks and behaves the same way no matter if we did a classic BIOS boot or a UEFI boot, internally there are two bootloaders with fundamentally different implementations, compiled in a completely different way which just share the main logic (see `common_bootloader_logic()`) using a an interface implemented by the two variants (see `struct bootloader_intf`). Therefore, from now on, we should talk either about the *legacy* bootloader or about the *UEFI* bootloader. ### Debugging the legacy bootloader The legacy bootloader has 3 stages. Initially, the BIOS loads its first stage (512 bytes) at a predefined address and jumps into it in x86 [real mode]. There, we relocate to a different segment and load both the 2nd and the 3rd stages at once in a way that's AS IF everything were loaded at once in a contiguous chunk of memory. After that, we jump to the 2nd stage. In the 2nd stage, we enter in [protected mode] and jump into the 3rd stage. [real mode]: https://en.wikipedia.org/wiki/Real_mode [protected mode]: https://en.wikipedia.org/wiki/Protected_mode With GDB we cannot really debug code running in [real mode], but the good thing is that the 1st and the 2nd stages are small part of the legacy bootloader and should never really need to be touched. Therefore, we'll talk only about debugging the 3rd stage, which runs in 32-bit [protected mode] like the whole Tilck kernel and it's also mostly written in C. Steps: * Run: `./build/run_nokvm_qemu -S`. The `-S` option will force QEMU to stop before the boot stage. * In a different console, run GDB with: `gdb ./build/boot/legacy/stage3/elf_stage3_unstripped` * Connect to remote GDB server with: `target remote :1234` * Place a breakpoint in the early entry code (`_start`) or in the C main function (`bootloader_main()`). * Allow the VM to run with the `continue` GDB command. * Debug as usual. Note: avoid stepping inside `realmode_call()` because it makes the CPU to enter in (un)real mode (mostly undebuggable with GDB) and then to re-enter in [protected mode]. ### Debugging the UEFI bootloader The setup for debugging the UEFI bootloader is quite different from anything we've seen so far. First of all, since UEFI applications are shared libraries that can be loaded by the firmware anywhere in system's memory, we need to get from the bootloader itself its *base address* in order to debug the application. To do that, we need first to enable the `EFI_BOOTLOADER_DEBUG` CMake config option (see the [building] doc to learn how to do that). After that, we'll run GDB and pass that *BaseAddr* to it, while loading the shared library using the `add-symbol-file` command: * Enable the `EFI_BOOTLOADER_DEBUG` config option * Run QEMU: `./build/run_efi_qemu32`. The bootloader will stop early displaying a similar to the following: ``` ------------ EFI BOOTLOADER DEBUG ------------ Pointer size: 4 JumpToKernel: 0x61392F3 BaseAddr: 0x6137000 Press ANY key to continue... ``` * Run GDB without arguments: `gdb` * Connect to QEMU's gdb server with: `target remote :1234` * Add the EFI's app `.so` file at the right address: `add-symbol-file build/boot/efi/ia32/libefi_app_ia32.so <BaseAddr>` * Set your breakpoints and say GDB to continue the execution * Press a key in QEMU's window * Enjoy debugging with GDB! To debug the 64-bit EFI bootloader, run `run_efi_qemu64` and use the file `build/boot/efi/x86_64/libefi_app_x86_64.so` for symbols. It's worth noticing that, virtually there should be no reason to do that and that it won't be possible to debug with GDB the i386 kernel when running on a x86_64 QEMU virtual machine. See [bug 1686170] on launchpad.net. #### Details about BaseAddr By looking at the body of the `if (EFI_BOOTLOADER_DEBUG)` statement, some readers might notice that `BaseAddr` has a `0x1000` (4 KB) offset from EFI's ImageBase. That's because the first load segment starts at that offset n the ELF file: ``` $ readelf -l ./build/boot/efi/ia32/libefi_app_ia32.so Elf file type is DYN (Shared object file) Entry point 0x8200 There are 4 program headers, starting at offset 52 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align LOAD 0x001000 0x00000000 0x00000000 0x0dd60 0x0dd60 R E 0x1000 LOAD 0x00f000 0x0000e000 0x0000e000 0x0e7bb 0x0e7bb RW 0x1000 DYNAMIC 0x019000 0x00018000 0x00018000 0x000a0 0x000a0 RW 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RWE 0x10 Section to Segment mapping: Segment Sections... 00 .hash .text .plt 01 .sdata .data .dynamic .rel .rel.plt .dynsym .dynstr 02 .dynamic 03 ``` And GDB expects the address of the first load segment (anything before that isn't supposed to be loaded in memory). While in theory that offset might change if the ELF headers get bigger, in practice that will never happen as long as we don't add new sections and segments in the binary (and we don't have a reason to do that). Therefore, it's reasonable fine to just hard-code that +0x1000 offset for the sake of simplicity instead of having to add it manually or to implement any sort of tricky solutions supporting it to change. [building]: building.md [bug 1686170]: https://bugs.launchpad.net/qemu/+bug/1686170 <file_sep>/******************************************************************************* * * Module Name: hwpci - Obtain PCI bus, device, and function numbers * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("hwpci") /* PCI configuration space values */ #define PCI_CFG_HEADER_TYPE_REG 0x0E #define PCI_CFG_PRIMARY_BUS_NUMBER_REG 0x18 #define PCI_CFG_SECONDARY_BUS_NUMBER_REG 0x19 /* PCI header values */ #define PCI_HEADER_TYPE_MASK 0x7F #define PCI_TYPE_BRIDGE 0x01 #define PCI_TYPE_CARDBUS_BRIDGE 0x02 typedef struct acpi_pci_device { ACPI_HANDLE Device; struct acpi_pci_device *Next; } ACPI_PCI_DEVICE; /* Local prototypes */ static ACPI_STATUS AcpiHwBuildPciList ( ACPI_HANDLE RootPciDevice, ACPI_HANDLE PciRegion, ACPI_PCI_DEVICE **ReturnListHead); static ACPI_STATUS AcpiHwProcessPciList ( ACPI_PCI_ID *PciId, ACPI_PCI_DEVICE *ListHead); static void AcpiHwDeletePciList ( ACPI_PCI_DEVICE *ListHead); static ACPI_STATUS AcpiHwGetPciDeviceInfo ( ACPI_PCI_ID *PciId, ACPI_HANDLE PciDevice, UINT16 *BusNumber, BOOLEAN *IsBridge); /******************************************************************************* * * FUNCTION: AcpiHwDerivePciId * * PARAMETERS: PciId - Initial values for the PCI ID. May be * modified by this function. * RootPciDevice - A handle to a PCI device object. This * object must be a PCI Root Bridge having a * _HID value of either PNP0A03 or PNP0A08 * PciRegion - A handle to a PCI configuration space * Operation Region being initialized * * RETURN: Status * * DESCRIPTION: This function derives a full PCI ID for a PCI device, * consisting of a Segment number, Bus number, Device number, * and function code. * * The PCI hardware dynamically configures PCI bus numbers * depending on the bus topology discovered during system * initialization. This function is invoked during configuration * of a PCI_Config Operation Region in order to (possibly) update * the Bus/Device/Function numbers in the PciId with the actual * values as determined by the hardware and operating system * configuration. * * The PciId parameter is initially populated during the Operation * Region initialization. This function is then called, and is * will make any necessary modifications to the Bus, Device, or * Function number PCI ID subfields as appropriate for the * current hardware and OS configuration. * * NOTE: Created 08/2010. Replaces the previous OSL AcpiOsDerivePciId * interface since this feature is OS-independent. This module * specifically avoids any use of recursion by building a local * temporary device list. * ******************************************************************************/ ACPI_STATUS AcpiHwDerivePciId ( ACPI_PCI_ID *PciId, ACPI_HANDLE RootPciDevice, ACPI_HANDLE PciRegion) { ACPI_STATUS Status; ACPI_PCI_DEVICE *ListHead; ACPI_FUNCTION_TRACE (HwDerivePciId); if (!PciId) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Build a list of PCI devices, from PciRegion up to RootPciDevice */ Status = AcpiHwBuildPciList (RootPciDevice, PciRegion, &ListHead); if (ACPI_SUCCESS (Status)) { /* Walk the list, updating the PCI device/function/bus numbers */ Status = AcpiHwProcessPciList (PciId, ListHead); /* Delete the list */ AcpiHwDeletePciList (ListHead); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiHwBuildPciList * * PARAMETERS: RootPciDevice - A handle to a PCI device object. This * object is guaranteed to be a PCI Root * Bridge having a _HID value of either * PNP0A03 or PNP0A08 * PciRegion - A handle to the PCI configuration space * Operation Region * ReturnListHead - Where the PCI device list is returned * * RETURN: Status * * DESCRIPTION: Builds a list of devices from the input PCI region up to the * Root PCI device for this namespace subtree. * ******************************************************************************/ static ACPI_STATUS AcpiHwBuildPciList ( ACPI_HANDLE RootPciDevice, ACPI_HANDLE PciRegion, ACPI_PCI_DEVICE **ReturnListHead) { ACPI_HANDLE CurrentDevice; ACPI_HANDLE ParentDevice; ACPI_STATUS Status; ACPI_PCI_DEVICE *ListElement; /* * Ascend namespace branch until the RootPciDevice is reached, building * a list of device nodes. Loop will exit when either the PCI device is * found, or the root of the namespace is reached. */ *ReturnListHead = NULL; CurrentDevice = PciRegion; while (1) { Status = AcpiGetParent (CurrentDevice, &ParentDevice); if (ACPI_FAILURE (Status)) { /* Must delete the list before exit */ AcpiHwDeletePciList (*ReturnListHead); return (Status); } /* Finished when we reach the PCI root device (PNP0A03 or PNP0A08) */ if (ParentDevice == RootPciDevice) { return (AE_OK); } ListElement = ACPI_ALLOCATE (sizeof (ACPI_PCI_DEVICE)); if (!ListElement) { /* Must delete the list before exit */ AcpiHwDeletePciList (*ReturnListHead); return (AE_NO_MEMORY); } /* Put new element at the head of the list */ ListElement->Next = *ReturnListHead; ListElement->Device = ParentDevice; *ReturnListHead = ListElement; CurrentDevice = ParentDevice; } } /******************************************************************************* * * FUNCTION: AcpiHwProcessPciList * * PARAMETERS: PciId - Initial values for the PCI ID. May be * modified by this function. * ListHead - Device list created by * AcpiHwBuildPciList * * RETURN: Status * * DESCRIPTION: Walk downward through the PCI device list, getting the device * info for each, via the PCI configuration space and updating * the PCI ID as necessary. Deletes the list during traversal. * ******************************************************************************/ static ACPI_STATUS AcpiHwProcessPciList ( ACPI_PCI_ID *PciId, ACPI_PCI_DEVICE *ListHead) { ACPI_STATUS Status = AE_OK; ACPI_PCI_DEVICE *Info; UINT16 BusNumber; BOOLEAN IsBridge = TRUE; ACPI_FUNCTION_NAME (HwProcessPciList); ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION, "Input PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X\n", PciId->Segment, PciId->Bus, PciId->Device, PciId->Function)); BusNumber = PciId->Bus; /* * Descend down the namespace tree, collecting PCI device, function, * and bus numbers. BusNumber is only important for PCI bridges. * Algorithm: As we descend the tree, use the last valid PCI device, * function, and bus numbers that are discovered, and assign them * to the PCI ID for the target device. */ Info = ListHead; while (Info) { Status = AcpiHwGetPciDeviceInfo (PciId, Info->Device, &BusNumber, &IsBridge); if (ACPI_FAILURE (Status)) { return (Status); } Info = Info->Next; } ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION, "Output PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X " "Status %X BusNumber %X IsBridge %X\n", PciId->Segment, PciId->Bus, PciId->Device, PciId->Function, Status, BusNumber, IsBridge)); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiHwDeletePciList * * PARAMETERS: ListHead - Device list created by * AcpiHwBuildPciList * * RETURN: None * * DESCRIPTION: Free the entire PCI list. * ******************************************************************************/ static void AcpiHwDeletePciList ( ACPI_PCI_DEVICE *ListHead) { ACPI_PCI_DEVICE *Next; ACPI_PCI_DEVICE *Previous; Next = ListHead; while (Next) { Previous = Next; Next = Previous->Next; ACPI_FREE (Previous); } } /******************************************************************************* * * FUNCTION: AcpiHwGetPciDeviceInfo * * PARAMETERS: PciId - Initial values for the PCI ID. May be * modified by this function. * PciDevice - Handle for the PCI device object * BusNumber - Where a PCI bridge bus number is returned * IsBridge - Return value, indicates if this PCI * device is a PCI bridge * * RETURN: Status * * DESCRIPTION: Get the device info for a single PCI device object. Get the * _ADR (contains PCI device and function numbers), and for PCI * bridge devices, get the bus number from PCI configuration * space. * ******************************************************************************/ static ACPI_STATUS AcpiHwGetPciDeviceInfo ( ACPI_PCI_ID *PciId, ACPI_HANDLE PciDevice, UINT16 *BusNumber, BOOLEAN *IsBridge) { ACPI_STATUS Status; ACPI_OBJECT_TYPE ObjectType; UINT64 ReturnValue; UINT64 PciValue; /* We only care about objects of type Device */ Status = AcpiGetType (PciDevice, &ObjectType); if (ACPI_FAILURE (Status)) { return (Status); } if (ObjectType != ACPI_TYPE_DEVICE) { return (AE_OK); } /* We need an _ADR. Ignore device if not present */ Status = AcpiUtEvaluateNumericObject (METHOD_NAME__ADR, PciDevice, &ReturnValue); if (ACPI_FAILURE (Status)) { return (AE_OK); } /* * From _ADR, get the PCI Device and Function and * update the PCI ID. */ PciId->Device = ACPI_HIWORD (ACPI_LODWORD (ReturnValue)); PciId->Function = ACPI_LOWORD (ACPI_LODWORD (ReturnValue)); /* * If the previous device was a bridge, use the previous * device bus number */ if (*IsBridge) { PciId->Bus = *BusNumber; } /* * Get the bus numbers from PCI Config space: * * First, get the PCI HeaderType */ *IsBridge = FALSE; Status = AcpiOsReadPciConfiguration (PciId, PCI_CFG_HEADER_TYPE_REG, &PciValue, 8); if (ACPI_FAILURE (Status)) { return (Status); } /* We only care about bridges (1=PciBridge, 2=CardBusBridge) */ PciValue &= PCI_HEADER_TYPE_MASK; if ((PciValue != PCI_TYPE_BRIDGE) && (PciValue != PCI_TYPE_CARDBUS_BRIDGE)) { return (AE_OK); } /* Bridge: Get the Primary BusNumber */ Status = AcpiOsReadPciConfiguration (PciId, PCI_CFG_PRIMARY_BUS_NUMBER_REG, &PciValue, 8); if (ACPI_FAILURE (Status)) { return (Status); } *IsBridge = TRUE; PciId->Bus = (UINT16) PciValue; /* Bridge: Get the Secondary BusNumber */ Status = AcpiOsReadPciConfiguration (PciId, PCI_CFG_SECONDARY_BUS_NUMBER_REG, &PciValue, 8); if (ACPI_FAILURE (Status)) { return (Status); } *BusNumber = (UINT16) PciValue; return (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/process.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/datetime.h> #include <tilck/mods/tracing.h> #include "termutil.h" #define MAX_EXEC_PATH_LEN 34 void init_dp_tracing(void); /* Gfx state */ static int row; /* State */ static int sel_index; static int curr_idx; static int max_idx; static int sel_tid; static bool sel_tid_found; static enum { dp_tasks_mode_default, dp_tasks_mode_sel, } mode; static void debug_get_state_name(char *s, enum task_state state, bool stopped, bool traced) { char *ptr = s; switch (state) { case TASK_STATE_INVALID: *ptr++ = '?'; break; case TASK_STATE_RUNNABLE: *ptr++ = 'r'; break; case TASK_STATE_RUNNING: *ptr++ = 'R'; break; case TASK_STATE_SLEEPING: *ptr++ = 's'; break; case TASK_STATE_ZOMBIE: *ptr++ = 'Z'; break; default: NOT_REACHED(); } if (stopped) *ptr++ = 'S'; if (traced) *ptr++ = 't'; *ptr = 0; } enum task_dump_util_str { HEADER, ROW_FMT, HLINE }; static const char * debug_get_task_dump_util_str(enum task_dump_util_str t) { static bool initialized; static char fmt[120]; static char hfmt[120]; static char header[120]; static char hline_sep[120] = "qqqqqqqnqqqqqqnqqqqqqnqqqqqqnqqqqqnqqqqqn"; static char *hline_sep_end = &hline_sep[sizeof(hline_sep)]; if (!initialized) { int path_field_len = (DP_W - 80) + MAX_EXEC_PATH_LEN; snprintk(fmt, sizeof(fmt), " %%-5d " TERM_VLINE " %%-4d " TERM_VLINE " %%-4d " TERM_VLINE " %%-4d " TERM_VLINE " %%-3s " TERM_VLINE " %%-2d " TERM_VLINE " %%-%ds", dp_start_col+1, path_field_len); snprintk(hfmt, sizeof(hfmt), " %%-5s " TERM_VLINE " %%-4s " TERM_VLINE " %%-4s " TERM_VLINE " %%-4s " TERM_VLINE " %%-3s " TERM_VLINE " %%-3s " TERM_VLINE " %%-%ds", path_field_len); snprintk(header, sizeof(header), hfmt, "pid", "pgid", "sid", "ppid", "S", "tty", "cmdline"); char *p = hline_sep + strlen(hline_sep); for (int i = 0; i < path_field_len + 2 && p < hline_sep_end; i++, p++) { *p = 'q'; } initialized = true; } switch (t) { case HEADER: return header; case ROW_FMT: return fmt; case HLINE: return hline_sep; default: NOT_REACHED(); } } struct per_task_cb_opts { bool kernel_tasks; bool plain_text; }; static int debug_per_task_cb(void *obj, void *arg) { const char *fmt = debug_get_task_dump_util_str(ROW_FMT); struct task *ti = obj; struct process *pi = ti->pi; char buf[128] = {0}; char state_str[4]; char *path = buf; char *path2 = buf + MAX_EXEC_PATH_LEN + 1; const char *orig_path = pi->debug_cmdline ? pi->debug_cmdline : "<n/a>"; struct per_task_cb_opts *opts = arg; const bool kernel_tasks = opts->kernel_tasks; const bool plain_text = opts->plain_text; STATIC_ASSERT(sizeof(buf) >= (2 * MAX_EXEC_PATH_LEN + 2)); if (ti->tid == KERNEL_TID_START) return 0; /* skip the main kernel task */ if (strlen(orig_path) < MAX_EXEC_PATH_LEN - 2) { snprintk(path, MAX_EXEC_PATH_LEN + 1, "%s", orig_path); } else { snprintk(path2, MAX_EXEC_PATH_LEN + 1 - 6, "%s", orig_path); snprintk(path, MAX_EXEC_PATH_LEN + 1, "%s...", path2); } debug_get_state_name(state_str, ti->state, ti->stopped, ti->traced); int ttynum = tty_get_num(ti->pi->proc_tty); if (is_kernel_thread(ti)) { if (!kernel_tasks) return 0; const char *name = ti->kthread_name; ttynum = 0; if (is_worker_thread(ti)) { int p = wth_get_priority(ti->worker_thread); const char *wth_name = wth_get_name(ti->worker_thread); name = wth_name ? wth_name : "generic"; snprintk(buf, sizeof(buf), "<wth:%s(%d)>", name, p); } else { snprintk(buf, sizeof(buf), "<%s>", name); } } if (!plain_text) { bool sel = false; if (mode == dp_tasks_mode_sel) { if (sel_tid > 0) { if (ti->tid == sel_tid) { sel_index = curr_idx; dp_reverse_colors(); sel = true; } } else if (sel_index >= 0) { if (curr_idx == sel_index) { sel_tid = ti->tid; dp_reverse_colors(); sel = true; } } } dp_writeln(fmt, ti->tid, pi->pgid, pi->sid, pi->parent_pid, state_str, ttynum, buf); if (sel) dp_reset_attrs(); } else { dp_write_raw(fmt, ti->tid, pi->pgid, pi->sid, pi->parent_pid, state_str, ttynum, buf); dp_write_raw("\r\n"); } curr_idx++; return 0; } static void debug_dump_task_table_hr(bool plain_text) { if (plain_text) dp_write_raw(GFX_ON "%s" GFX_OFF "\r\n", debug_get_task_dump_util_str(HLINE)); else dp_writeln(GFX_ON "%s" GFX_OFF, debug_get_task_dump_util_str(HLINE)); } static bool is_tid_off_limits(int tid) { if (tid == get_curr_tid()) return true; if (tid >= KERNEL_TID_START) return true; return false; } static enum kb_handler_action dp_no_tracing_module_action(void) { modal_msg = "The tracing module is NOT built-in"; return kb_handler_ok_and_continue; } static enum kb_handler_action dp_enter_tracing_mode(void) { return MOD_tracing ? dp_tracing_screen() : dp_no_tracing_module_action(); } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_special(u32 key) { if (key == KEY_UP) { sel_tid = -1; sel_index = MAX(0, sel_index - 1); ui_need_update = true; return kb_handler_ok_and_continue; } if (key == KEY_DOWN) { sel_tid = -1; sel_index = MIN(max_idx, sel_index + 1); ui_need_update = true; return kb_handler_ok_and_continue; } return kb_handler_nak; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_k(void) { if (is_tid_off_limits(sel_tid) || sel_tid == 1) { if (sel_tid != get_curr_tid()) modal_msg = "Killing kernel threads or pid 1 is not allowed"; else modal_msg = "Killing the debug panel's process is not allowed"; return kb_handler_ok_and_continue; } ui_need_update = true; send_signal(sel_tid, SIGKILL, false); return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_s(void) { if (is_tid_off_limits(sel_tid)) { if (sel_tid != get_curr_tid()) modal_msg = "Stopping kernel threads is not allowed"; else modal_msg = "Stopping the debug panel's process is not allowed"; return kb_handler_ok_and_continue; } ui_need_update = true; send_signal(sel_tid, SIGSTOP, false); return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_c(void) { if (is_tid_off_limits(sel_tid)) return kb_handler_ok_and_continue; ui_need_update = true; send_signal(sel_tid, SIGCONT, false); return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_t(void) { if (is_tid_off_limits(sel_tid)) { if (sel_tid != get_curr_tid()) modal_msg = "Cannot trace kernel threads for syscalls"; else modal_msg = "Cannot trace the debug panel process"; return kb_handler_ok_and_continue; } ui_need_update = true; { disable_preemption(); struct task *ti = get_task(sel_tid); if (ti) ti->traced = !ti->traced; enable_preemption(); } return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_esc(void) { mode = dp_tasks_mode_default; ui_need_update = true; return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress_r(void) { ui_need_update = true; return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_sel_mode_keypress(struct key_event ke) { if (!ke.print_char) return dp_tasks_handle_sel_mode_keypress_special(ke.key); switch (ke.print_char) { case DP_KEY_ESC: return dp_tasks_handle_sel_mode_keypress_esc(); case DP_KEY_CTRL_T: return dp_enter_tracing_mode(); case 'r': return dp_tasks_handle_sel_mode_keypress_r(); case 'k': return dp_tasks_handle_sel_mode_keypress_k(); case 's': return dp_tasks_handle_sel_mode_keypress_s(); case 'c': return dp_tasks_handle_sel_mode_keypress_c(); case 't': if (MOD_tracing) return dp_tasks_handle_sel_mode_keypress_t(); return dp_no_tracing_module_action(); } return kb_handler_nak; } static enum kb_handler_action dp_tasks_handle_default_mode_enter(void) { mode = dp_tasks_mode_sel; ui_need_update = true; return kb_handler_ok_and_continue; } static enum kb_handler_action dp_tasks_handle_default_mode_keypress(struct key_event ke) { switch (ke.print_char) { case 'r': return dp_tasks_handle_sel_mode_keypress_r(); case DP_KEY_ENTER: return dp_tasks_handle_default_mode_enter(); case DP_KEY_CTRL_T: return dp_enter_tracing_mode(); } return kb_handler_nak; } static enum kb_handler_action dp_tasks_keypress(struct key_event ke) { switch (mode) { case dp_tasks_mode_default: return dp_tasks_handle_default_mode_keypress(ke); case dp_tasks_mode_sel: return dp_tasks_handle_sel_mode_keypress(ke); } return kb_handler_nak; } static int dp_count_tasks(void *obj, void *arg) { struct task *ti = obj; if (ti->tid == KERNEL_TID_START) return 0; /* skip the main kernel task */ if (mode == dp_tasks_mode_sel) { if (sel_tid > 0 && ti->tid == sel_tid) sel_tid_found = true; } max_idx++; return 0; } static void show_actions_menu(void) { if (mode == dp_tasks_mode_default) { dp_writeln( E_COLOR_BR_WHITE "<ENTER>" RESET_ATTRS ": select mode " TERM_VLINE " " E_COLOR_BR_WHITE "r" RESET_ATTRS ": refresh " TERM_VLINE " " E_COLOR_BR_WHITE "Ctrl+T" RESET_ATTRS ": tracing mode" ); dp_writeln(""); } else if (mode == dp_tasks_mode_sel) { dp_writeln( E_COLOR_BR_WHITE "ESC" RESET_ATTRS ": exit select mode " TERM_VLINE " " E_COLOR_BR_WHITE "r" RESET_ATTRS ": refresh " TERM_VLINE " " E_COLOR_BR_WHITE "Ctrl+T" RESET_ATTRS ": tracing mode " TERM_VLINE " " E_COLOR_BR_WHITE "t" RESET_ATTRS ": trace task " ); dp_writeln( E_COLOR_BR_WHITE "k" RESET_ATTRS ": kill " TERM_VLINE " " E_COLOR_BR_WHITE "s" RESET_ATTRS ": stop " TERM_VLINE " " E_COLOR_BR_WHITE "c" RESET_ATTRS ": continue " ); } dp_writeln(""); } void dp_dump_task_list(bool kernel_tasks, bool plain_text) { struct per_task_cb_opts opts = { .kernel_tasks = kernel_tasks, .plain_text = plain_text, }; if (plain_text) dp_write_raw("\r\n%s\r\n", debug_get_task_dump_util_str(HEADER)); else dp_writeln("%s", debug_get_task_dump_util_str(HEADER)); debug_dump_task_table_hr(plain_text); disable_preemption(); { curr_idx = 0; max_idx = -1; sel_tid_found = false; iterate_over_tasks(dp_count_tasks, NULL); if (mode == dp_tasks_mode_sel && sel_tid > 0 && !sel_tid_found) { /* * The task with the selected tid does not exist anymore: invalidate * the selected TID, but leave sel_index as it is: this will make * the cursor to stay at the same position and select the next task. */ sel_tid = -1; } if (sel_index >= 0) sel_index = MIN(sel_index, max_idx); iterate_over_tasks(debug_per_task_cb, &opts); } enable_preemption(); if (!plain_text) dp_writeln(""); } static void dp_show_tasks(void) { row = dp_screen_start_row; show_actions_menu(); dp_dump_task_list(true, false); } static void dp_tasks_enter(void) { sel_index = 0; sel_tid = -1; mode = dp_tasks_mode_default; } static void dp_tasks_exit(void) { /* do nothing, for the moment */ } static void dp_tasks_first_setup(void) { if (MOD_tracing) init_dp_tracing(); } static struct dp_screen dp_tasks_screen = { .index = 3, .label = "Tasks", .first_setup = dp_tasks_first_setup, .on_dp_enter = dp_tasks_enter, .on_dp_exit = dp_tasks_exit, .draw_func = dp_show_tasks, .on_keypress_func = dp_tasks_keypress, }; __attribute__((constructor)) static void dp_tasks_init(void) { dp_register_screen(&dp_tasks_screen); } <file_sep>/******************************************************************************* * * Module Name: dbnames - Debugger commands for the acpi namespace * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acdebug.h" #include "acpredef.h" #include "acinterp.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbnames") /* Local prototypes */ static ACPI_STATUS AcpiDbWalkAndMatchName ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbWalkForPredefinedNames ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbWalkForSpecificObjects ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbWalkForObjectCounts ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbIntegrityWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbWalkForReferences ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbBusWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); /* * Arguments for the Objects command * These object types map directly to the ACPI_TYPES */ static ACPI_DB_ARGUMENT_INFO AcpiDbObjectTypes [] = { {"ANY"}, {"INTEGERS"}, {"STRINGS"}, {"BUFFERS"}, {"PACKAGES"}, {"FIELDS"}, {"DEVICES"}, {"EVENTS"}, {"METHODS"}, {"MUTEXES"}, {"REGIONS"}, {"POWERRESOURCES"}, {"PROCESSORS"}, {"THERMALZONES"}, {"BUFFERFIELDS"}, {"DDBHANDLES"}, {"DEBUG"}, {"REGIONFIELDS"}, {"BANKFIELDS"}, {"INDEXFIELDS"}, {"REFERENCES"}, {"ALIASES"}, {"METHODALIASES"}, {"NOTIFY"}, {"ADDRESSHANDLER"}, {"RESOURCE"}, {"RESOURCEFIELD"}, {"SCOPES"}, {NULL} /* Must be null terminated */ }; /******************************************************************************* * * FUNCTION: AcpiDbSetScope * * PARAMETERS: Name - New scope path * * RETURN: Status * * DESCRIPTION: Set the "current scope" as maintained by this utility. * The scope is used as a prefix to ACPI paths. * ******************************************************************************/ void AcpiDbSetScope ( char *Name) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; if (!Name || Name[0] == 0) { AcpiOsPrintf ("Current scope: %s\n", AcpiGbl_DbScopeBuf); return; } AcpiDbPrepNamestring (Name); if (ACPI_IS_ROOT_PREFIX (Name[0])) { /* Validate new scope from the root */ Status = AcpiNsGetNode (AcpiGbl_RootNode, Name, ACPI_NS_NO_UPSEARCH, &Node); if (ACPI_FAILURE (Status)) { goto ErrorExit; } AcpiGbl_DbScopeBuf[0] = 0; } else { /* Validate new scope relative to old scope */ Status = AcpiNsGetNode (AcpiGbl_DbScopeNode, Name, ACPI_NS_NO_UPSEARCH, &Node); if (ACPI_FAILURE (Status)) { goto ErrorExit; } } /* Build the final pathname */ if (AcpiUtSafeStrcat (AcpiGbl_DbScopeBuf, sizeof (AcpiGbl_DbScopeBuf), Name)) { Status = AE_BUFFER_OVERFLOW; goto ErrorExit; } if (AcpiUtSafeStrcat (AcpiGbl_DbScopeBuf, sizeof (AcpiGbl_DbScopeBuf), "\\")) { Status = AE_BUFFER_OVERFLOW; goto ErrorExit; } AcpiGbl_DbScopeNode = Node; AcpiOsPrintf ("New scope: %s\n", AcpiGbl_DbScopeBuf); return; ErrorExit: AcpiOsPrintf ("Could not attach scope: %s, %s\n", Name, AcpiFormatException (Status)); } /******************************************************************************* * * FUNCTION: AcpiDbDumpNamespace * * PARAMETERS: StartArg - Node to begin namespace dump * DepthArg - Maximum tree depth to be dumped * * RETURN: None * * DESCRIPTION: Dump entire namespace or a subtree. Each node is displayed * with type and other information. * ******************************************************************************/ void AcpiDbDumpNamespace ( char *StartArg, char *DepthArg) { ACPI_HANDLE SubtreeEntry = AcpiGbl_RootNode; UINT32 MaxDepth = ACPI_UINT32_MAX; /* No argument given, just start at the root and dump entire namespace */ if (StartArg) { SubtreeEntry = AcpiDbConvertToNode (StartArg); if (!SubtreeEntry) { return; } /* Now we can check for the depth argument */ if (DepthArg) { MaxDepth = strtoul (DepthArg, NULL, 0); } } AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); if (((ACPI_NAMESPACE_NODE *) SubtreeEntry)->Parent) { AcpiOsPrintf ("ACPI Namespace (from %4.4s (%p) subtree):\n", ((ACPI_NAMESPACE_NODE *) SubtreeEntry)->Name.Ascii, SubtreeEntry); } else { AcpiOsPrintf ("ACPI Namespace (from %s):\n", ACPI_NAMESPACE_ROOT); } /* Display the subtree */ AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiNsDumpObjects (ACPI_TYPE_ANY, ACPI_DISPLAY_SUMMARY, MaxDepth, ACPI_OWNER_ID_MAX, SubtreeEntry); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } /******************************************************************************* * * FUNCTION: AcpiDbDumpNamespacePaths * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Dump entire namespace with full object pathnames and object * type information. Alternative to "namespace" command. * ******************************************************************************/ void AcpiDbDumpNamespacePaths ( void) { AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); AcpiOsPrintf ("ACPI Namespace (from root):\n"); /* Display the entire namespace */ AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiNsDumpObjectPaths (ACPI_TYPE_ANY, ACPI_DISPLAY_SUMMARY, ACPI_UINT32_MAX, ACPI_OWNER_ID_MAX, AcpiGbl_RootNode); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } /******************************************************************************* * * FUNCTION: AcpiDbDumpNamespaceByOwner * * PARAMETERS: OwnerArg - Owner ID whose nodes will be displayed * DepthArg - Maximum tree depth to be dumped * * RETURN: None * * DESCRIPTION: Dump elements of the namespace that are owned by the OwnerId. * ******************************************************************************/ void AcpiDbDumpNamespaceByOwner ( char *OwnerArg, char *DepthArg) { ACPI_HANDLE SubtreeEntry = AcpiGbl_RootNode; UINT32 MaxDepth = ACPI_UINT32_MAX; ACPI_OWNER_ID OwnerId; OwnerId = (ACPI_OWNER_ID) strtoul (OwnerArg, NULL, 0); /* Now we can check for the depth argument */ if (DepthArg) { MaxDepth = strtoul (DepthArg, NULL, 0); } AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); AcpiOsPrintf ("ACPI Namespace by owner %X:\n", OwnerId); /* Display the subtree */ AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiNsDumpObjects (ACPI_TYPE_ANY, ACPI_DISPLAY_SUMMARY, MaxDepth, OwnerId, SubtreeEntry); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } /******************************************************************************* * * FUNCTION: AcpiDbWalkAndMatchName * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Find a particular name/names within the namespace. Wildcards * are supported -- '?' matches any character. * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkAndMatchName ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_STATUS Status; char *RequestedName = (char *) Context; UINT32 i; ACPI_BUFFER Buffer; ACPI_WALK_INFO Info; /* Check for a name match */ for (i = 0; i < 4; i++) { /* Wildcard support */ if ((RequestedName[i] != '?') && (RequestedName[i] != ((ACPI_NAMESPACE_NODE *) ObjHandle)->Name.Ascii[i])) { /* No match, just exit */ return (AE_OK); } } /* Get the full pathname to this object */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (ObjHandle, &Buffer, TRUE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could Not get pathname for object %p\n", ObjHandle); } else { Info.Count = 0; Info.OwnerId = ACPI_OWNER_ID_MAX; Info.DebugLevel = ACPI_UINT32_MAX; Info.DisplayType = ACPI_DISPLAY_SUMMARY | ACPI_DISPLAY_SHORT; AcpiOsPrintf ("%32s", (char *) Buffer.Pointer); (void) AcpiNsDumpOneObject (ObjHandle, NestingLevel, &Info, NULL); ACPI_FREE (Buffer.Pointer); } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbFindNameInNamespace * * PARAMETERS: NameArg - The 4-character ACPI name to find. * wildcards are supported. * * RETURN: None * * DESCRIPTION: Search the namespace for a given name (with wildcards) * ******************************************************************************/ ACPI_STATUS AcpiDbFindNameInNamespace ( char *NameArg) { char AcpiName[5] = "____"; char *AcpiNamePtr = AcpiName; if (strlen (NameArg) > ACPI_NAMESEG_SIZE) { AcpiOsPrintf ("Name must be no longer than 4 characters\n"); return (AE_OK); } /* Pad out name with underscores as necessary to create a 4-char name */ AcpiUtStrupr (NameArg); while (*NameArg) { *AcpiNamePtr = *NameArg; AcpiNamePtr++; NameArg++; } /* Walk the namespace from the root */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkAndMatchName, NULL, AcpiName, NULL); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbWalkForPredefinedNames * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Detect and display predefined ACPI names (names that start with * an underscore) * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkForPredefinedNames ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; UINT32 *Count = (UINT32 *) Context; const ACPI_PREDEFINED_INFO *Predefined; const ACPI_PREDEFINED_INFO *Package = NULL; char *Pathname; char StringBuffer[48]; Predefined = AcpiUtMatchPredefinedMethod (Node->Name.Ascii); if (!Predefined) { return (AE_OK); } Pathname = AcpiNsGetNormalizedPathname (Node, TRUE); if (!Pathname) { return (AE_OK); } /* If method returns a package, the info is in the next table entry */ if (Predefined->Info.ExpectedBtypes & ACPI_RTYPE_PACKAGE) { Package = Predefined + 1; } AcpiUtGetExpectedReturnTypes (StringBuffer, Predefined->Info.ExpectedBtypes); AcpiOsPrintf ("%-32s Arguments %X, Return Types: %s", Pathname, METHOD_GET_ARG_COUNT (Predefined->Info.ArgumentList), StringBuffer); if (Package) { AcpiOsPrintf (" (PkgType %2.2X, ObjType %2.2X, Count %2.2X)", Package->RetInfo.Type, Package->RetInfo.ObjectType1, Package->RetInfo.Count1); } AcpiOsPrintf("\n"); /* Check that the declared argument count matches the ACPI spec */ AcpiNsCheckAcpiCompliance (Pathname, Node, Predefined); ACPI_FREE (Pathname); (*Count)++; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbCheckPredefinedNames * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Validate all predefined names in the namespace * ******************************************************************************/ void AcpiDbCheckPredefinedNames ( void) { UINT32 Count = 0; /* Search all nodes in namespace */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkForPredefinedNames, NULL, (void *) &Count, NULL); AcpiOsPrintf ("Found %u predefined names in the namespace\n", Count); } /******************************************************************************* * * FUNCTION: AcpiDbWalkForObjectCounts * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Display short info about objects in the namespace * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkForObjectCounts ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_OBJECT_INFO *Info = (ACPI_OBJECT_INFO *) Context; ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; if (Node->Type > ACPI_TYPE_NS_NODE_MAX) { AcpiOsPrintf ("[%4.4s]: Unknown object type %X\n", Node->Name.Ascii, Node->Type); } else { Info->Types[Node->Type]++; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbWalkForFields * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Display short info about objects in the namespace * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkForFields ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_OBJECT *RetValue; ACPI_REGION_WALK_INFO *Info = (ACPI_REGION_WALK_INFO *) Context; ACPI_BUFFER Buffer; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node = AcpiNsValidateHandle (ObjHandle); if (!Node) { return (AE_OK); } if (Node->Object->Field.RegionObj->Region.SpaceId != Info->AddressSpaceId) { return (AE_OK); } Info->Count++; /* Get and display the full pathname to this object */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (ObjHandle, &Buffer, TRUE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could Not get pathname for object %p\n", ObjHandle); return (AE_OK); } AcpiOsPrintf ("%s ", (char *) Buffer.Pointer); ACPI_FREE (Buffer.Pointer); Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; AcpiEvaluateObject (ObjHandle, NULL, NULL, &Buffer); /* * Since this is a field unit, surround the output in braces */ AcpiOsPrintf ("{"); RetValue = (ACPI_OBJECT *) Buffer.Pointer; switch (RetValue->Type) { case ACPI_TYPE_INTEGER: AcpiOsPrintf ("%8.8X%8.8X", ACPI_FORMAT_UINT64 (RetValue->Integer.Value)); break; case ACPI_TYPE_BUFFER: AcpiUtDumpBuffer (RetValue->Buffer.Pointer, RetValue->Buffer.Length, DB_DISPLAY_DATA_ONLY | DB_BYTE_DISPLAY, 0); break; default: break; } AcpiOsPrintf ("}\n"); ACPI_FREE (Buffer.Pointer); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbWalkForSpecificObjects * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Display short info about objects in the namespace * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkForSpecificObjects ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_WALK_INFO *Info = (ACPI_WALK_INFO *) Context; ACPI_BUFFER Buffer; ACPI_STATUS Status; Info->Count++; /* Get and display the full pathname to this object */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (ObjHandle, &Buffer, TRUE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could Not get pathname for object %p\n", ObjHandle); return (AE_OK); } AcpiOsPrintf ("%32s", (char *) Buffer.Pointer); ACPI_FREE (Buffer.Pointer); /* Dump short info about the object */ (void) AcpiNsDumpOneObject (ObjHandle, NestingLevel, Info, NULL); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayObjects * * PARAMETERS: ObjTypeArg - Type of object to display * DisplayCountArg - Max depth to display * * RETURN: None * * DESCRIPTION: Display objects in the namespace of the requested type * ******************************************************************************/ ACPI_STATUS AcpiDbDisplayObjects ( char *ObjTypeArg, char *DisplayCountArg) { ACPI_WALK_INFO Info; ACPI_OBJECT_TYPE Type; ACPI_OBJECT_INFO *ObjectInfo; UINT32 i; UINT32 TotalObjects = 0; /* No argument means display summary/count of all object types */ if (!ObjTypeArg) { ObjectInfo = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_OBJECT_INFO)); /* Walk the namespace from the root */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkForObjectCounts, NULL, (void *) ObjectInfo, NULL); AcpiOsPrintf ("\nSummary of namespace objects:\n\n"); for (i = 0; i < ACPI_TOTAL_TYPES; i++) { AcpiOsPrintf ("%8u %s\n", ObjectInfo->Types[i], AcpiUtGetTypeName (i)); TotalObjects += ObjectInfo->Types[i]; } AcpiOsPrintf ("\n%8u Total namespace objects\n\n", TotalObjects); ACPI_FREE (ObjectInfo); return (AE_OK); } /* Get the object type */ Type = AcpiDbMatchArgument (ObjTypeArg, AcpiDbObjectTypes); if (Type == ACPI_TYPE_NOT_FOUND) { AcpiOsPrintf ("Invalid or unsupported argument\n"); return (AE_OK); } AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); AcpiOsPrintf ( "Objects of type [%s] defined in the current ACPI Namespace:\n", AcpiUtGetTypeName (Type)); AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); Info.Count = 0; Info.OwnerId = ACPI_OWNER_ID_MAX; Info.DebugLevel = ACPI_UINT32_MAX; Info.DisplayType = ACPI_DISPLAY_SUMMARY | ACPI_DISPLAY_SHORT; /* Walk the namespace from the root */ (void) AcpiWalkNamespace (Type, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkForSpecificObjects, NULL, (void *) &Info, NULL); AcpiOsPrintf ( "\nFound %u objects of type [%s] in the current ACPI Namespace\n", Info.Count, AcpiUtGetTypeName (Type)); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayFields * * PARAMETERS: ObjTypeArg - Type of object to display * DisplayCountArg - Max depth to display * * RETURN: None * * DESCRIPTION: Display objects in the namespace of the requested type * ******************************************************************************/ ACPI_STATUS AcpiDbDisplayFields ( UINT32 AddressSpaceId) { ACPI_REGION_WALK_INFO Info; Info.Count = 0; Info.OwnerId = ACPI_OWNER_ID_MAX; Info.DebugLevel = ACPI_UINT32_MAX; Info.DisplayType = ACPI_DISPLAY_SUMMARY | ACPI_DISPLAY_SHORT; Info.AddressSpaceId = AddressSpaceId; /* Walk the namespace from the root */ (void) AcpiWalkNamespace (ACPI_TYPE_LOCAL_REGION_FIELD, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkForFields, NULL, (void *) &Info, NULL); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbIntegrityWalk * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Examine one NS node for valid values. * ******************************************************************************/ static ACPI_STATUS AcpiDbIntegrityWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_INTEGRITY_INFO *Info = (ACPI_INTEGRITY_INFO *) Context; ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; ACPI_OPERAND_OBJECT *Object; BOOLEAN Alias = TRUE; Info->Nodes++; /* Verify the NS node, and dereference aliases */ while (Alias) { if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED) { AcpiOsPrintf ( "Invalid Descriptor Type for Node %p [%s] - " "is %2.2X should be %2.2X\n", Node, AcpiUtGetDescriptorName (Node), ACPI_GET_DESCRIPTOR_TYPE (Node), ACPI_DESC_TYPE_NAMED); return (AE_OK); } if ((Node->Type == ACPI_TYPE_LOCAL_ALIAS) || (Node->Type == ACPI_TYPE_LOCAL_METHOD_ALIAS)) { Node = (ACPI_NAMESPACE_NODE *) Node->Object; } else { Alias = FALSE; } } if (Node->Type > ACPI_TYPE_LOCAL_MAX) { AcpiOsPrintf ("Invalid Object Type for Node %p, Type = %X\n", Node, Node->Type); return (AE_OK); } if (!AcpiUtValidNameseg (Node->Name.Ascii)) { AcpiOsPrintf ("Invalid AcpiName for Node %p\n", Node); return (AE_OK); } Object = AcpiNsGetAttachedObject (Node); if (Object) { Info->Objects++; if (ACPI_GET_DESCRIPTOR_TYPE (Object) != ACPI_DESC_TYPE_OPERAND) { AcpiOsPrintf ("Invalid Descriptor Type for Object %p [%s]\n", Object, AcpiUtGetDescriptorName (Object)); } } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbCheckIntegrity * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Check entire namespace for data structure integrity * ******************************************************************************/ void AcpiDbCheckIntegrity ( void) { ACPI_INTEGRITY_INFO Info = {0,0}; /* Search all nodes in namespace */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbIntegrityWalk, NULL, (void *) &Info, NULL); AcpiOsPrintf ("Verified %u namespace nodes with %u Objects\n", Info.Nodes, Info.Objects); } /******************************************************************************* * * FUNCTION: AcpiDbWalkForReferences * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Check if this namespace object refers to the target object * that is passed in as the context value. * * Note: Currently doesn't check subobjects within the Node's object * ******************************************************************************/ static ACPI_STATUS AcpiDbWalkForReferences ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_OPERAND_OBJECT *ObjDesc = (ACPI_OPERAND_OBJECT *) Context; ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; /* Check for match against the namespace node itself */ if (Node == (void *) ObjDesc) { AcpiOsPrintf ("Object is a Node [%4.4s]\n", AcpiUtGetNodeName (Node)); } /* Check for match against the object attached to the node */ if (AcpiNsGetAttachedObject (Node) == ObjDesc) { AcpiOsPrintf ("Reference at Node->Object %p [%4.4s]\n", Node, AcpiUtGetNodeName (Node)); } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbFindReferences * * PARAMETERS: ObjectArg - String with hex value of the object * * RETURN: None * * DESCRIPTION: Search namespace for all references to the input object * ******************************************************************************/ void AcpiDbFindReferences ( char *ObjectArg) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_SIZE Address; /* Convert string to object pointer */ Address = strtoul (ObjectArg, NULL, 16); ObjDesc = ACPI_TO_POINTER (Address); /* Search all nodes in namespace */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbWalkForReferences, NULL, (void *) ObjDesc, NULL); } /******************************************************************************* * * FUNCTION: AcpiDbBusWalk * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Display info about device objects that have a corresponding * _PRT method. * ******************************************************************************/ static ACPI_STATUS AcpiDbBusWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; ACPI_STATUS Status; ACPI_BUFFER Buffer; ACPI_NAMESPACE_NODE *TempNode; ACPI_DEVICE_INFO *Info; UINT32 i; if ((Node->Type != ACPI_TYPE_DEVICE) && (Node->Type != ACPI_TYPE_PROCESSOR)) { return (AE_OK); } /* Exit if there is no _PRT under this device */ Status = AcpiGetHandle (Node, METHOD_NAME__PRT, ACPI_CAST_PTR (ACPI_HANDLE, &TempNode)); if (ACPI_FAILURE (Status)) { return (AE_OK); } /* Get the full path to this device object */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (ObjHandle, &Buffer, TRUE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could Not get pathname for object %p\n", ObjHandle); return (AE_OK); } Status = AcpiGetObjectInfo (ObjHandle, &Info); if (ACPI_FAILURE (Status)) { return (AE_OK); } /* Display the full path */ AcpiOsPrintf ("%-32s Type %X", (char *) Buffer.Pointer, Node->Type); ACPI_FREE (Buffer.Pointer); if (Info->Flags & ACPI_PCI_ROOT_BRIDGE) { AcpiOsPrintf (" - Is PCI Root Bridge"); } AcpiOsPrintf ("\n"); /* _PRT info */ AcpiOsPrintf ("_PRT: %p\n", TempNode); /* Dump _ADR, _HID, _UID, _CID */ if (Info->Valid & ACPI_VALID_ADR) { AcpiOsPrintf ("_ADR: %8.8X%8.8X\n", ACPI_FORMAT_UINT64 (Info->Address)); } else { AcpiOsPrintf ("_ADR: <Not Present>\n"); } if (Info->Valid & ACPI_VALID_HID) { AcpiOsPrintf ("_HID: %s\n", Info->HardwareId.String); } else { AcpiOsPrintf ("_HID: <Not Present>\n"); } if (Info->Valid & ACPI_VALID_UID) { AcpiOsPrintf ("_UID: %s\n", Info->UniqueId.String); } else { AcpiOsPrintf ("_UID: <Not Present>\n"); } if (Info->Valid & ACPI_VALID_CID) { for (i = 0; i < Info->CompatibleIdList.Count; i++) { AcpiOsPrintf ("_CID: %s\n", Info->CompatibleIdList.Ids[i].String); } } else { AcpiOsPrintf ("_CID: <Not Present>\n"); } ACPI_FREE (Info); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbGetBusInfo * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display info about system buses. * ******************************************************************************/ void AcpiDbGetBusInfo ( void) { /* Search all nodes in namespace */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbBusWalk, NULL, NULL, NULL); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #define ENABLED_MODULES_LIST "@ENABLED_MODULES_LIST@" <file_sep>/****************************************************************************** * * Module Name: exdump - Interpreter debug output routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlcode.h" #include "acnamesp.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exdump") /* * The following routines are used for debug output only */ #if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER) /* Local prototypes */ static void AcpiExOutString ( const char *Title, const char *Value); static void AcpiExOutPointer ( const char *Title, const void *Value); static void AcpiExDumpObject ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_EXDUMP_INFO *Info); static void AcpiExDumpReferenceObj ( ACPI_OPERAND_OBJECT *ObjDesc); static void AcpiExDumpPackageObj ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Level, UINT32 Index); /******************************************************************************* * * Object Descriptor info tables * * Note: The first table entry must be an INIT opcode and must contain * the table length (number of table entries) * ******************************************************************************/ static ACPI_EXDUMP_INFO AcpiExDumpInteger[2] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpInteger), NULL}, {ACPI_EXD_UINT64, ACPI_EXD_OFFSET (Integer.Value), "Value"} }; static ACPI_EXDUMP_INFO AcpiExDumpString[4] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpString), NULL}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (String.Length), "Length"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (String.Pointer), "Pointer"}, {ACPI_EXD_STRING, 0, NULL} }; static ACPI_EXDUMP_INFO AcpiExDumpBuffer[5] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpBuffer), NULL}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Buffer.Length), "Length"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Buffer.Pointer), "Pointer"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Buffer.Node), "Parent Node"}, {ACPI_EXD_BUFFER, 0, NULL} }; static ACPI_EXDUMP_INFO AcpiExDumpPackage[6] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpPackage), NULL}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Package.Node), "Parent Node"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Package.Flags), "Flags"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Package.Count), "Element Count"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Package.Elements), "Element List"}, {ACPI_EXD_PACKAGE, 0, NULL} }; static ACPI_EXDUMP_INFO AcpiExDumpDevice[4] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpDevice), NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Device.NotifyList[0]), "System Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Device.NotifyList[1]), "Device Notify"}, {ACPI_EXD_HDLR_LIST,ACPI_EXD_OFFSET (Device.Handler), "Handler"} }; static ACPI_EXDUMP_INFO AcpiExDumpEvent[2] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpEvent), NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Event.OsSemaphore), "OsSemaphore"} }; static ACPI_EXDUMP_INFO AcpiExDumpMethod[9] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpMethod), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Method.InfoFlags), "Info Flags"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Method.ParamCount), "Parameter Count"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Method.SyncLevel), "Sync Level"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Method.Mutex), "Mutex"}, {ACPI_EXD_UINT16, ACPI_EXD_OFFSET (Method.OwnerId), "Owner Id"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Method.ThreadCount), "Thread Count"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Method.AmlLength), "Aml Length"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Method.AmlStart), "Aml Start"} }; static ACPI_EXDUMP_INFO AcpiExDumpMutex[6] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpMutex), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Mutex.SyncLevel), "Sync Level"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Mutex.OriginalSyncLevel), "Original Sync Level"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Mutex.OwnerThread), "Owner Thread"}, {ACPI_EXD_UINT16, ACPI_EXD_OFFSET (Mutex.AcquisitionDepth), "Acquire Depth"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Mutex.OsMutex), "OsMutex"} }; static ACPI_EXDUMP_INFO AcpiExDumpRegion[8] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpRegion), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Region.SpaceId), "Space Id"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Region.Flags), "Flags"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Region.Node), "Parent Node"}, {ACPI_EXD_ADDRESS, ACPI_EXD_OFFSET (Region.Address), "Address"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Region.Length), "Length"}, {ACPI_EXD_HDLR_LIST,ACPI_EXD_OFFSET (Region.Handler), "Handler"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Region.Next), "Next"} }; static ACPI_EXDUMP_INFO AcpiExDumpPower[6] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpPower), NULL}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (PowerResource.SystemLevel), "System Level"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (PowerResource.ResourceOrder), "Resource Order"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (PowerResource.NotifyList[0]), "System Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (PowerResource.NotifyList[1]), "Device Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (PowerResource.Handler), "Handler"} }; static ACPI_EXDUMP_INFO AcpiExDumpProcessor[7] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpProcessor), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Processor.ProcId), "Processor ID"}, {ACPI_EXD_UINT8 , ACPI_EXD_OFFSET (Processor.Length), "Length"}, {ACPI_EXD_ADDRESS, ACPI_EXD_OFFSET (Processor.Address), "Address"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Processor.NotifyList[0]), "System Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Processor.NotifyList[1]), "Device Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Processor.Handler), "Handler"} }; static ACPI_EXDUMP_INFO AcpiExDumpThermal[4] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpThermal), NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (ThermalZone.NotifyList[0]), "System Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (ThermalZone.NotifyList[1]), "Device Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (ThermalZone.Handler), "Handler"} }; static ACPI_EXDUMP_INFO AcpiExDumpBufferField[3] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpBufferField), NULL}, {ACPI_EXD_FIELD, 0, NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (BufferField.BufferObj), "Buffer Object"} }; static ACPI_EXDUMP_INFO AcpiExDumpRegionField[5] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpRegionField), NULL}, {ACPI_EXD_FIELD, 0, NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Field.AccessLength), "AccessLength"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Field.RegionObj), "Region Object"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Field.ResourceBuffer), "ResourceBuffer"} }; static ACPI_EXDUMP_INFO AcpiExDumpBankField[5] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpBankField), NULL}, {ACPI_EXD_FIELD, 0, NULL}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (BankField.Value), "Value"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (BankField.RegionObj), "Region Object"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (BankField.BankObj), "Bank Object"} }; static ACPI_EXDUMP_INFO AcpiExDumpIndexField[5] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpBankField), NULL}, {ACPI_EXD_FIELD, 0, NULL}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (IndexField.Value), "Value"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (IndexField.IndexObj), "Index Object"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (IndexField.DataObj), "Data Object"} }; static ACPI_EXDUMP_INFO AcpiExDumpReference[9] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpReference), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Reference.Class), "Class"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Reference.TargetType), "Target Type"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Reference.Value), "Value"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Reference.Object), "Object Desc"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Reference.Node), "Node"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Reference.Where), "Where"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Reference.IndexPointer), "Index Pointer"}, {ACPI_EXD_REFERENCE,0, NULL} }; static ACPI_EXDUMP_INFO AcpiExDumpAddressHandler[6] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpAddressHandler), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (AddressSpace.SpaceId), "Space Id"}, {ACPI_EXD_HDLR_LIST,ACPI_EXD_OFFSET (AddressSpace.Next), "Next"}, {ACPI_EXD_RGN_LIST, ACPI_EXD_OFFSET (AddressSpace.RegionList), "Region List"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (AddressSpace.Node), "Node"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (AddressSpace.Context), "Context"} }; static ACPI_EXDUMP_INFO AcpiExDumpNotify[7] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpNotify), NULL}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Notify.Node), "Node"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Notify.HandlerType), "Handler Type"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Notify.Handler), "Handler"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Notify.Context), "Context"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Notify.Next[0]), "Next System Notify"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Notify.Next[1]), "Next Device Notify"} }; static ACPI_EXDUMP_INFO AcpiExDumpExtra[6] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpExtra), NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Extra.Method_REG), "_REG Method"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (Extra.ScopeNode), "Scope Node"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Extra.RegionContext), "Region Context"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Extra.AmlStart), "Aml Start"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (Extra.AmlLength), "Aml Length"} }; static ACPI_EXDUMP_INFO AcpiExDumpData[3] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpData), NULL}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Data.Handler), "Handler"}, {ACPI_EXD_POINTER, ACPI_EXD_OFFSET (Data.Pointer), "Raw Data"} }; /* Miscellaneous tables */ static ACPI_EXDUMP_INFO AcpiExDumpCommon[5] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpCommon), NULL}, {ACPI_EXD_TYPE , 0, NULL}, {ACPI_EXD_UINT16, ACPI_EXD_OFFSET (Common.ReferenceCount), "Reference Count"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (Common.Flags), "Flags"}, {ACPI_EXD_LIST, ACPI_EXD_OFFSET (Common.NextObject), "Object List"} }; static ACPI_EXDUMP_INFO AcpiExDumpFieldCommon[7] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpFieldCommon), NULL}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (CommonField.FieldFlags), "Field Flags"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (CommonField.AccessByteWidth), "Access Byte Width"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (CommonField.BitLength), "Bit Length"}, {ACPI_EXD_UINT8, ACPI_EXD_OFFSET (CommonField.StartFieldBitOffset),"Field Bit Offset"}, {ACPI_EXD_UINT32, ACPI_EXD_OFFSET (CommonField.BaseByteOffset), "Base Byte Offset"}, {ACPI_EXD_NODE, ACPI_EXD_OFFSET (CommonField.Node), "Parent Node"} }; static ACPI_EXDUMP_INFO AcpiExDumpNode[7] = { {ACPI_EXD_INIT, ACPI_EXD_TABLE_SIZE (AcpiExDumpNode), NULL}, {ACPI_EXD_UINT16, ACPI_EXD_NSOFFSET (Flags), "Flags"}, {ACPI_EXD_UINT16, ACPI_EXD_NSOFFSET (OwnerId), "Owner Id"}, {ACPI_EXD_LIST, ACPI_EXD_NSOFFSET (Object), "Object List"}, {ACPI_EXD_NODE, ACPI_EXD_NSOFFSET (Parent), "Parent"}, {ACPI_EXD_NODE, ACPI_EXD_NSOFFSET (Child), "Child"}, {ACPI_EXD_NODE, ACPI_EXD_NSOFFSET (Peer), "Peer"} }; /* Dispatch table, indexed by object type */ static ACPI_EXDUMP_INFO *AcpiExDumpInfo[] = { NULL, AcpiExDumpInteger, AcpiExDumpString, AcpiExDumpBuffer, AcpiExDumpPackage, NULL, AcpiExDumpDevice, AcpiExDumpEvent, AcpiExDumpMethod, AcpiExDumpMutex, AcpiExDumpRegion, AcpiExDumpPower, AcpiExDumpProcessor, AcpiExDumpThermal, AcpiExDumpBufferField, NULL, NULL, AcpiExDumpRegionField, AcpiExDumpBankField, AcpiExDumpIndexField, AcpiExDumpReference, NULL, NULL, AcpiExDumpNotify, AcpiExDumpAddressHandler, NULL, NULL, NULL, AcpiExDumpExtra, AcpiExDumpData }; /******************************************************************************* * * FUNCTION: AcpiExDumpObject * * PARAMETERS: ObjDesc - Descriptor to dump * Info - Info table corresponding to this object * type * * RETURN: None * * DESCRIPTION: Walk the info table for this object * ******************************************************************************/ static void AcpiExDumpObject ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_EXDUMP_INFO *Info) { UINT8 *Target; const char *Name; UINT8 Count; ACPI_OPERAND_OBJECT *Start; ACPI_OPERAND_OBJECT *Data = NULL; ACPI_OPERAND_OBJECT *Next; ACPI_NAMESPACE_NODE *Node; if (!Info) { AcpiOsPrintf ( "ExDumpObject: Display not implemented for object type %s\n", AcpiUtGetObjectTypeName (ObjDesc)); return; } /* First table entry must contain the table length (# of table entries) */ Count = Info->Offset; while (Count) { if (!ObjDesc) { return; } Target = ACPI_ADD_PTR (UINT8, ObjDesc, Info->Offset); Name = Info->Name; switch (Info->Opcode) { case ACPI_EXD_INIT: break; case ACPI_EXD_TYPE: AcpiOsPrintf ("%20s : %2.2X [%s]\n", "Type", ObjDesc->Common.Type, AcpiUtGetObjectTypeName (ObjDesc)); break; case ACPI_EXD_UINT8: AcpiOsPrintf ("%20s : %2.2X\n", Name, *Target); break; case ACPI_EXD_UINT16: AcpiOsPrintf ("%20s : %4.4X\n", Name, ACPI_GET16 (Target)); break; case ACPI_EXD_UINT32: AcpiOsPrintf ("%20s : %8.8X\n", Name, ACPI_GET32 (Target)); break; case ACPI_EXD_UINT64: AcpiOsPrintf ("%20s : %8.8X%8.8X\n", "Value", ACPI_FORMAT_UINT64 (ACPI_GET64 (Target))); break; case ACPI_EXD_POINTER: case ACPI_EXD_ADDRESS: AcpiExOutPointer (Name, *ACPI_CAST_PTR (void *, Target)); break; case ACPI_EXD_STRING: AcpiUtPrintString (ObjDesc->String.Pointer, ACPI_UINT8_MAX); AcpiOsPrintf ("\n"); break; case ACPI_EXD_BUFFER: ACPI_DUMP_BUFFER ( ObjDesc->Buffer.Pointer, ObjDesc->Buffer.Length); break; case ACPI_EXD_PACKAGE: /* Dump the package contents */ AcpiOsPrintf ("\nPackage Contents:\n"); AcpiExDumpPackageObj (ObjDesc, 0, 0); break; case ACPI_EXD_FIELD: AcpiExDumpObject (ObjDesc, AcpiExDumpFieldCommon); break; case ACPI_EXD_REFERENCE: AcpiExOutString ("Class Name", AcpiUtGetReferenceName (ObjDesc)); AcpiExDumpReferenceObj (ObjDesc); break; case ACPI_EXD_LIST: Start = *ACPI_CAST_PTR (void *, Target); Next = Start; AcpiOsPrintf ("%20s : %p ", Name, Next); if (Next) { AcpiOsPrintf ("%s (Type %2.2X)", AcpiUtGetObjectTypeName (Next), Next->Common.Type); while (Next->Common.NextObject) { if ((Next->Common.Type == ACPI_TYPE_LOCAL_DATA) && !Data) { Data = Next; } Next = Next->Common.NextObject; AcpiOsPrintf ("->%p(%s %2.2X)", Next, AcpiUtGetObjectTypeName (Next), Next->Common.Type); if ((Next == Start) || (Next == Data)) { AcpiOsPrintf ( "\n**** Error: Object list appears to be circular linked"); break; } } } else { AcpiOsPrintf ("- No attached objects"); } AcpiOsPrintf ("\n"); break; case ACPI_EXD_HDLR_LIST: Start = *ACPI_CAST_PTR (void *, Target); Next = Start; AcpiOsPrintf ("%20s : %p", Name, Next); if (Next) { AcpiOsPrintf ("(%s %2.2X)", AcpiUtGetObjectTypeName (Next), Next->AddressSpace.SpaceId); while (Next->AddressSpace.Next) { if ((Next->Common.Type == ACPI_TYPE_LOCAL_DATA) && !Data) { Data = Next; } Next = Next->AddressSpace.Next; AcpiOsPrintf ("->%p(%s %2.2X)", Next, AcpiUtGetObjectTypeName (Next), Next->AddressSpace.SpaceId); if ((Next == Start) || (Next == Data)) { AcpiOsPrintf ( "\n**** Error: Handler list appears to be circular linked"); break; } } } AcpiOsPrintf ("\n"); break; case ACPI_EXD_RGN_LIST: Start = *ACPI_CAST_PTR (void *, Target); Next = Start; AcpiOsPrintf ("%20s : %p", Name, Next); if (Next) { AcpiOsPrintf ("(%s %2.2X)", AcpiUtGetObjectTypeName (Next), Next->Common.Type); while (Next->Region.Next) { if ((Next->Common.Type == ACPI_TYPE_LOCAL_DATA) && !Data) { Data = Next; } Next = Next->Region.Next; AcpiOsPrintf ("->%p(%s %2.2X)", Next, AcpiUtGetObjectTypeName (Next), Next->Common.Type); if ((Next == Start) || (Next == Data)) { AcpiOsPrintf ( "\n**** Error: Region list appears to be circular linked"); break; } } } AcpiOsPrintf ("\n"); break; case ACPI_EXD_NODE: Node = *ACPI_CAST_PTR (ACPI_NAMESPACE_NODE *, Target); AcpiOsPrintf ("%20s : %p", Name, Node); if (Node) { AcpiOsPrintf (" [%4.4s]", Node->Name.Ascii); } AcpiOsPrintf ("\n"); break; default: AcpiOsPrintf ("**** Invalid table opcode [%X] ****\n", Info->Opcode); return; } Info++; Count--; } } /******************************************************************************* * * FUNCTION: AcpiExDumpOperand * * PARAMETERS: *ObjDesc - Pointer to entry to be dumped * Depth - Current nesting depth * * RETURN: None * * DESCRIPTION: Dump an operand object * ******************************************************************************/ void AcpiExDumpOperand ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Depth) { UINT32 Length; UINT32 Index; ACPI_FUNCTION_NAME (ExDumpOperand); /* Check if debug output enabled */ if (!ACPI_IS_DEBUG_ENABLED (ACPI_LV_EXEC, _COMPONENT)) { return; } if (!ObjDesc) { /* This could be a null element of a package */ ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Null Object Descriptor\n")); return; } if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_NAMED) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%p Namespace Node: ", ObjDesc)); ACPI_DUMP_ENTRY (ObjDesc, ACPI_LV_EXEC); return; } if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%p is not a node or operand object: [%s]\n", ObjDesc, AcpiUtGetDescriptorName (ObjDesc))); ACPI_DUMP_BUFFER (ObjDesc, sizeof (ACPI_OPERAND_OBJECT)); return; } /* ObjDesc is a valid object */ if (Depth > 0) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%*s[%u] %p Refs=%u ", Depth, " ", Depth, ObjDesc, ObjDesc->Common.ReferenceCount)); } else { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%p Refs=%u ", ObjDesc, ObjDesc->Common.ReferenceCount)); } /* Decode object type */ switch (ObjDesc->Common.Type) { case ACPI_TYPE_LOCAL_REFERENCE: AcpiOsPrintf ("Reference: [%s] ", AcpiUtGetReferenceName (ObjDesc)); switch (ObjDesc->Reference.Class) { case ACPI_REFCLASS_DEBUG: AcpiOsPrintf ("\n"); break; case ACPI_REFCLASS_INDEX: AcpiOsPrintf ("%p\n", ObjDesc->Reference.Object); break; case ACPI_REFCLASS_TABLE: AcpiOsPrintf ("Table Index %X\n", ObjDesc->Reference.Value); break; case ACPI_REFCLASS_REFOF: AcpiOsPrintf ("%p [%s]\n", ObjDesc->Reference.Object, AcpiUtGetTypeName (((ACPI_OPERAND_OBJECT *) ObjDesc->Reference.Object)->Common.Type)); break; case ACPI_REFCLASS_NAME: AcpiUtRepairName (ObjDesc->Reference.Node->Name.Ascii); AcpiOsPrintf ("- [%4.4s] (Node %p)\n", ObjDesc->Reference.Node->Name.Ascii, ObjDesc->Reference.Node); break; case ACPI_REFCLASS_ARG: case ACPI_REFCLASS_LOCAL: AcpiOsPrintf ("%X\n", ObjDesc->Reference.Value); break; default: /* Unknown reference class */ AcpiOsPrintf ("%2.2X\n", ObjDesc->Reference.Class); break; } break; case ACPI_TYPE_BUFFER: AcpiOsPrintf ("Buffer length %.2X @ %p\n", ObjDesc->Buffer.Length, ObjDesc->Buffer.Pointer); /* Debug only -- dump the buffer contents */ if (ObjDesc->Buffer.Pointer) { Length = ObjDesc->Buffer.Length; if (Length > 128) { Length = 128; } AcpiOsPrintf ( "Buffer Contents: (displaying length 0x%.2X)\n", Length); ACPI_DUMP_BUFFER (ObjDesc->Buffer.Pointer, Length); } break; case ACPI_TYPE_INTEGER: AcpiOsPrintf ("Integer %8.8X%8.8X\n", ACPI_FORMAT_UINT64 (ObjDesc->Integer.Value)); break; case ACPI_TYPE_PACKAGE: AcpiOsPrintf ("Package [Len %X] ElementArray %p\n", ObjDesc->Package.Count, ObjDesc->Package.Elements); /* * If elements exist, package element pointer is valid, * and debug_level exceeds 1, dump package's elements. */ if (ObjDesc->Package.Count && ObjDesc->Package.Elements && AcpiDbgLevel > 1) { for (Index = 0; Index < ObjDesc->Package.Count; Index++) { AcpiExDumpOperand ( ObjDesc->Package.Elements[Index], Depth + 1); } } break; case ACPI_TYPE_REGION: AcpiOsPrintf ("Region %s (%X)", AcpiUtGetRegionName (ObjDesc->Region.SpaceId), ObjDesc->Region.SpaceId); /* * If the address and length have not been evaluated, * don't print them. */ if (!(ObjDesc->Region.Flags & AOPOBJ_DATA_VALID)) { AcpiOsPrintf ("\n"); } else { AcpiOsPrintf (" base %8.8X%8.8X Length %X\n", ACPI_FORMAT_UINT64 (ObjDesc->Region.Address), ObjDesc->Region.Length); } break; case ACPI_TYPE_STRING: AcpiOsPrintf ("String length %X @ %p ", ObjDesc->String.Length, ObjDesc->String.Pointer); AcpiUtPrintString (ObjDesc->String.Pointer, ACPI_UINT8_MAX); AcpiOsPrintf ("\n"); break; case ACPI_TYPE_LOCAL_BANK_FIELD: AcpiOsPrintf ("BankField\n"); break; case ACPI_TYPE_LOCAL_REGION_FIELD: AcpiOsPrintf ("RegionField: Bits=%X AccWidth=%X Lock=%X Update=%X at " "byte=%X bit=%X of below:\n", ObjDesc->Field.BitLength, ObjDesc->Field.AccessByteWidth, ObjDesc->Field.FieldFlags & AML_FIELD_LOCK_RULE_MASK, ObjDesc->Field.FieldFlags & AML_FIELD_UPDATE_RULE_MASK, ObjDesc->Field.BaseByteOffset, ObjDesc->Field.StartFieldBitOffset); AcpiExDumpOperand (ObjDesc->Field.RegionObj, Depth + 1); break; case ACPI_TYPE_LOCAL_INDEX_FIELD: AcpiOsPrintf ("IndexField\n"); break; case ACPI_TYPE_BUFFER_FIELD: AcpiOsPrintf ("BufferField: %X bits at byte %X bit %X of\n", ObjDesc->BufferField.BitLength, ObjDesc->BufferField.BaseByteOffset, ObjDesc->BufferField.StartFieldBitOffset); if (!ObjDesc->BufferField.BufferObj) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "*NULL*\n")); } else if ((ObjDesc->BufferField.BufferObj)->Common.Type != ACPI_TYPE_BUFFER) { AcpiOsPrintf ("*not a Buffer*\n"); } else { AcpiExDumpOperand (ObjDesc->BufferField.BufferObj, Depth + 1); } break; case ACPI_TYPE_EVENT: AcpiOsPrintf ("Event\n"); break; case ACPI_TYPE_METHOD: AcpiOsPrintf ("Method(%X) @ %p:%X\n", ObjDesc->Method.ParamCount, ObjDesc->Method.AmlStart, ObjDesc->Method.AmlLength); break; case ACPI_TYPE_MUTEX: AcpiOsPrintf ("Mutex\n"); break; case ACPI_TYPE_DEVICE: AcpiOsPrintf ("Device\n"); break; case ACPI_TYPE_POWER: AcpiOsPrintf ("Power\n"); break; case ACPI_TYPE_PROCESSOR: AcpiOsPrintf ("Processor\n"); break; case ACPI_TYPE_THERMAL: AcpiOsPrintf ("Thermal\n"); break; default: /* Unknown Type */ AcpiOsPrintf ("Unknown Type %X\n", ObjDesc->Common.Type); break; } return; } /******************************************************************************* * * FUNCTION: AcpiExDumpOperands * * PARAMETERS: Operands - A list of Operand objects * OpcodeName - AML opcode name * NumOperands - Operand count for this opcode * * DESCRIPTION: Dump the operands associated with the opcode * ******************************************************************************/ void AcpiExDumpOperands ( ACPI_OPERAND_OBJECT **Operands, const char *OpcodeName, UINT32 NumOperands) { ACPI_FUNCTION_TRACE (ExDumpOperands); if (!OpcodeName) { OpcodeName = "UNKNOWN"; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "**** Start operand dump for opcode [%s], %u operands\n", OpcodeName, NumOperands)); if (NumOperands == 0) { NumOperands = 1; } /* Dump the individual operands */ while (NumOperands) { AcpiExDumpOperand (*Operands, 0); Operands++; NumOperands--; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "**** End operand dump for [%s]\n", OpcodeName)); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiExOut* functions * * PARAMETERS: Title - Descriptive text * Value - Value to be displayed * * DESCRIPTION: Object dump output formatting functions. These functions * reduce the number of format strings required and keeps them * all in one place for easy modification. * ******************************************************************************/ static void AcpiExOutString ( const char *Title, const char *Value) { AcpiOsPrintf ("%20s : %s\n", Title, Value); } static void AcpiExOutPointer ( const char *Title, const void *Value) { AcpiOsPrintf ("%20s : %p\n", Title, Value); } /******************************************************************************* * * FUNCTION: AcpiExDumpNamespaceNode * * PARAMETERS: Node - Descriptor to dump * Flags - Force display if TRUE * * DESCRIPTION: Dumps the members of the given.Node * ******************************************************************************/ void AcpiExDumpNamespaceNode ( ACPI_NAMESPACE_NODE *Node, UINT32 Flags) { ACPI_FUNCTION_ENTRY (); if (!Flags) { /* Check if debug output enabled */ if (!ACPI_IS_DEBUG_ENABLED (ACPI_LV_OBJECTS, _COMPONENT)) { return; } } AcpiOsPrintf ("%20s : %4.4s\n", "Name", AcpiUtGetNodeName (Node)); AcpiOsPrintf ("%20s : %2.2X [%s]\n", "Type", Node->Type, AcpiUtGetTypeName (Node->Type)); AcpiExDumpObject (ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Node), AcpiExDumpNode); } /******************************************************************************* * * FUNCTION: AcpiExDumpReferenceObj * * PARAMETERS: Object - Descriptor to dump * * DESCRIPTION: Dumps a reference object * ******************************************************************************/ static void AcpiExDumpReferenceObj ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_BUFFER RetBuf; ACPI_STATUS Status; RetBuf.Length = ACPI_ALLOCATE_LOCAL_BUFFER; if (ObjDesc->Reference.Class == ACPI_REFCLASS_NAME) { AcpiOsPrintf (" %p ", ObjDesc->Reference.Node); Status = AcpiNsHandleToPathname (ObjDesc->Reference.Node, &RetBuf, TRUE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf (" Could not convert name to pathname: %s\n", AcpiFormatException (Status)); } else { AcpiOsPrintf ("%s: %s\n", AcpiUtGetTypeName (ObjDesc->Reference.Node->Type), (char *) RetBuf.Pointer); ACPI_FREE (RetBuf.Pointer); } } else if (ObjDesc->Reference.Object) { if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_OPERAND) { AcpiOsPrintf ("%22s %p", "Target :", ObjDesc->Reference.Object); if (ObjDesc->Reference.Class == ACPI_REFCLASS_TABLE) { AcpiOsPrintf (" Table Index: %X\n", ObjDesc->Reference.Value); } else { AcpiOsPrintf (" [%s]\n", AcpiUtGetTypeName (((ACPI_OPERAND_OBJECT *) ObjDesc->Reference.Object)->Common.Type)); } } else { AcpiOsPrintf (" Target: %p\n", ObjDesc->Reference.Object); } } } /******************************************************************************* * * FUNCTION: AcpiExDumpPackageObj * * PARAMETERS: ObjDesc - Descriptor to dump * Level - Indentation Level * Index - Package index for this object * * DESCRIPTION: Dumps the elements of the package * ******************************************************************************/ static void AcpiExDumpPackageObj ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Level, UINT32 Index) { UINT32 i; /* Indentation and index output */ if (Level > 0) { for (i = 0; i < Level; i++) { AcpiOsPrintf (" "); } AcpiOsPrintf ("[%.2d] ", Index); } AcpiOsPrintf ("%p ", ObjDesc); /* Null package elements are allowed */ if (!ObjDesc) { AcpiOsPrintf ("[Null Object]\n"); return; } /* Packages may only contain a few object types */ switch (ObjDesc->Common.Type) { case ACPI_TYPE_INTEGER: AcpiOsPrintf ("[Integer] = %8.8X%8.8X\n", ACPI_FORMAT_UINT64 (ObjDesc->Integer.Value)); break; case ACPI_TYPE_STRING: AcpiOsPrintf ("[String] Value: "); AcpiUtPrintString (ObjDesc->String.Pointer, ACPI_UINT8_MAX); AcpiOsPrintf ("\n"); break; case ACPI_TYPE_BUFFER: AcpiOsPrintf ("[Buffer] Length %.2X = ", ObjDesc->Buffer.Length); if (ObjDesc->Buffer.Length) { AcpiUtDebugDumpBuffer ( ACPI_CAST_PTR (UINT8, ObjDesc->Buffer.Pointer), ObjDesc->Buffer.Length, DB_DWORD_DISPLAY, _COMPONENT); } else { AcpiOsPrintf ("\n"); } break; case ACPI_TYPE_PACKAGE: AcpiOsPrintf ("[Package] Contains %u Elements:\n", ObjDesc->Package.Count); for (i = 0; i < ObjDesc->Package.Count; i++) { AcpiExDumpPackageObj ( ObjDesc->Package.Elements[i], Level + 1, i); } break; case ACPI_TYPE_LOCAL_REFERENCE: AcpiOsPrintf ("[Object Reference] Class [%s]", AcpiUtGetReferenceName (ObjDesc)); AcpiExDumpReferenceObj (ObjDesc); break; default: AcpiOsPrintf ("[%s] Type: %2.2X\n", AcpiUtGetTypeName (ObjDesc->Common.Type), ObjDesc->Common.Type); break; } } /******************************************************************************* * * FUNCTION: AcpiExDumpObjectDescriptor * * PARAMETERS: ObjDesc - Descriptor to dump * Flags - Force display if TRUE * * DESCRIPTION: Dumps the members of the object descriptor given. * ******************************************************************************/ void AcpiExDumpObjectDescriptor ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Flags) { ACPI_FUNCTION_TRACE (ExDumpObjectDescriptor); if (!ObjDesc) { return_VOID; } if (!Flags) { /* Check if debug output enabled */ if (!ACPI_IS_DEBUG_ENABLED (ACPI_LV_OBJECTS, _COMPONENT)) { return_VOID; } } if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_NAMED) { AcpiExDumpNamespaceNode ((ACPI_NAMESPACE_NODE *) ObjDesc, Flags); ObjDesc = ((ACPI_NAMESPACE_NODE *) ObjDesc)->Object; if (!ObjDesc) { return_VOID; } AcpiOsPrintf ("\nAttached Object %p", ObjDesc); if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_NAMED) { AcpiOsPrintf (" - Namespace Node"); } AcpiOsPrintf (":\n"); goto DumpObject; } if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) { AcpiOsPrintf ( "%p is not an ACPI operand object: [%s]\n", ObjDesc, AcpiUtGetDescriptorName (ObjDesc)); return_VOID; } /* Validate the object type */ if (ObjDesc->Common.Type > ACPI_TYPE_LOCAL_MAX) { AcpiOsPrintf ("Not a known object type: %2.2X\n", ObjDesc->Common.Type); return_VOID; } DumpObject: if (!ObjDesc) { return_VOID; } /* Common Fields */ AcpiExDumpObject (ObjDesc, AcpiExDumpCommon); /* Object-specific fields */ AcpiExDumpObject (ObjDesc, AcpiExDumpInfo[ObjDesc->Common.Type]); if (ObjDesc->Common.Type == ACPI_TYPE_REGION) { ObjDesc = ObjDesc->Common.NextObject; if (ObjDesc->Common.Type > ACPI_TYPE_LOCAL_MAX) { AcpiOsPrintf ( "Secondary object is not a known object type: %2.2X\n", ObjDesc->Common.Type); return_VOID; } AcpiOsPrintf ("\nExtra attached Object (%p):\n", ObjDesc); AcpiExDumpObject (ObjDesc, AcpiExDumpInfo[ObjDesc->Common.Type]); } return_VOID; } #endif <file_sep>/****************************************************************************** * * Module Name: actbinfo - Table disassembly info for non-AML tables * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* * Macros used to generate offsets to specific table fields */ #define ACPI_FACS_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_FACS,f) #define ACPI_GAS_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GENERIC_ADDRESS,f) #define ACPI_HDR_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_HEADER,f) #define ACPI_RSDP_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_RSDP,f) #define ACPI_BERT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_BERT,f) #define ACPI_BGRT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_BGRT,f) #define ACPI_BOOT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_BOOT,f) #define ACPI_CPEP_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_CPEP,f) #define ACPI_DBG2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_DBG2,f) #define ACPI_DBGP_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_DBGP,f) #define ACPI_DMAR_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_DMAR,f) #define ACPI_DRTM_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_DRTM,f) #define ACPI_ECDT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_ECDT,f) #define ACPI_EINJ_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_EINJ,f) #define ACPI_ERST_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_ERST,f) #define ACPI_GTDT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_GTDT,f) #define ACPI_HEST_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_HEST,f) #define ACPI_HPET_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_HPET,f) #define ACPI_HMAT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_HMAT,f) #define ACPI_IORT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_IORT,f) #define ACPI_IVRS_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_IVRS,f) #define ACPI_MADT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_MADT,f) #define ACPI_MCFG_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_MCFG,f) #define ACPI_MCHI_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_MCHI,f) #define ACPI_MPST_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_MPST,f) #define ACPI_MSCT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_MSCT,f) #define ACPI_NFIT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_NFIT,f) #define ACPI_PCCT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_PCCT,f) #define ACPI_PDTT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_PDTT,f) #define ACPI_PMTT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_PMTT,f) #define ACPI_RASF_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_RASF,f) #define ACPI_S3PT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_S3PT,f) #define ACPI_SBST_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SBST,f) #define ACPI_SDEI_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SDEI,f) #define ACPI_SDEV_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SDEV,f) #define ACPI_SLIT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SLIT,f) #define ACPI_SPCR_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SPCR,f) #define ACPI_SPMI_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SPMI,f) #define ACPI_SRAT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SRAT,f) #define ACPI_STAO_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_STAO,f) #define ACPI_TCPA_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_TCPA_HDR,f) #define ACPI_TPM2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_TPM2,f) #define ACPI_TPM23_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_TPM23,f) #define ACPI_UEFI_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_UEFI,f) #define ACPI_WAET_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WAET,f) #define ACPI_WDAT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WDAT,f) #define ACPI_WDDT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WDDT,f) #define ACPI_WDRT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WDRT,f) #define ACPI_WPBT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WPBT,f) #define ACPI_WSMT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_WSMT,f) #define ACPI_XENV_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_XENV,f) /* Subtables */ #define ACPI_ASF0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_INFO,f) #define ACPI_ASF1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_ALERT,f) #define ACPI_ASF1a_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_ALERT_DATA,f) #define ACPI_ASF2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_REMOTE,f) #define ACPI_ASF2a_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_CONTROL_DATA,f) #define ACPI_ASF3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_RMCP,f) #define ACPI_ASF4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_ASF_ADDRESS,f) #define ACPI_CPEP0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_CPEP_POLLING,f) #define ACPI_CSRT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_CSRT_GROUP,f) #define ACPI_CSRT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_CSRT_SHARED_INFO,f) #define ACPI_CSRT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_CSRT_DESCRIPTOR,f) #define ACPI_DBG20_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DBG2_DEVICE,f) #define ACPI_DMARS_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_DEVICE_SCOPE,f) #define ACPI_DMAR0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_HARDWARE_UNIT,f) #define ACPI_DMAR1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_RESERVED_MEMORY,f) #define ACPI_DMAR2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_ATSR,f) #define ACPI_DMAR3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_RHSA,f) #define ACPI_DMAR4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DMAR_ANDD,f) #define ACPI_DRTM0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DRTM_VTABLE_LIST,f) #define ACPI_DRTM1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DRTM_RESOURCE_LIST,f) #define ACPI_DRTM1a_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DRTM_RESOURCE,f) #define ACPI_DRTM2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_DRTM_DPS_ID,f) #define ACPI_EINJ0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_WHEA_HEADER,f) #define ACPI_ERST0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_WHEA_HEADER,f) #define ACPI_FPDTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_FPDT_HEADER,f) #define ACPI_FPDT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_FPDT_BOOT_POINTER,f) #define ACPI_FPDT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_FPDT_S3PT_POINTER,f) #define ACPI_GTDT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GTDT_TIMER_BLOCK,f) #define ACPI_GTDT0a_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GTDT_TIMER_ENTRY,f) #define ACPI_GTDT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GTDT_WATCHDOG,f) #define ACPI_GTDTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GTDT_HEADER,f) #define ACPI_GTDT_EL2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_GTDT_EL2,f) #define ACPI_HEST0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_IA_MACHINE_CHECK,f) #define ACPI_HEST1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_IA_CORRECTED,f) #define ACPI_HEST2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_IA_NMI,f) #define ACPI_HEST6_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_AER_ROOT,f) #define ACPI_HEST7_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_AER,f) #define ACPI_HEST8_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_AER_BRIDGE,f) #define ACPI_HEST9_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_GENERIC,f) #define ACPI_HEST10_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_GENERIC_V2,f) #define ACPI_HEST11_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_IA_DEFERRED_CHECK,f) #define ACPI_HESTN_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_NOTIFY,f) #define ACPI_HESTB_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HEST_IA_ERROR_BANK,f) #define ACPI_HMAT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HMAT_PROXIMITY_DOMAIN,f) #define ACPI_HMAT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HMAT_LOCALITY,f) #define ACPI_HMAT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HMAT_CACHE,f) #define ACPI_HMATH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_HMAT_STRUCTURE,f) #define ACPI_IORT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_ITS_GROUP,f) #define ACPI_IORT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_NAMED_COMPONENT,f) #define ACPI_IORT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_ROOT_COMPLEX,f) #define ACPI_IORT3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_SMMU,f) #define ACPI_IORT3A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_SMMU_GSI,f) #define ACPI_IORT4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_SMMU_V3,f) #define ACPI_IORT5_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_PMCG,f) #define ACPI_IORTA_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_MEMORY_ACCESS,f) #define ACPI_IORTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_NODE,f) #define ACPI_IORTM_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IORT_ID_MAPPING,f) #define ACPI_IVRSH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_HEADER,f) #define ACPI_IVRS0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_HARDWARE1,f) #define ACPI_IVRS01_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_HARDWARE2,f) #define ACPI_IVRS1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_MEMORY,f) #define ACPI_IVRSD_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_DE_HEADER,f) #define ACPI_IVRS8A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_DEVICE8A,f) #define ACPI_IVRS8B_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_DEVICE8B,f) #define ACPI_IVRS8C_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_IVRS_DEVICE8C,f) #define ACPI_LPITH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_LPIT_HEADER,f) #define ACPI_LPIT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_LPIT_NATIVE,f) #define ACPI_MADT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_APIC,f) #define ACPI_MADT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_IO_APIC,f) #define ACPI_MADT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_INTERRUPT_OVERRIDE,f) #define ACPI_MADT3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_NMI_SOURCE,f) #define ACPI_MADT4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_APIC_NMI,f) #define ACPI_MADT5_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_APIC_OVERRIDE,f) #define ACPI_MADT6_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_IO_SAPIC,f) #define ACPI_MADT7_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_SAPIC,f) #define ACPI_MADT8_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_INTERRUPT_SOURCE,f) #define ACPI_MADT9_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_X2APIC,f) #define ACPI_MADT10_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_LOCAL_X2APIC_NMI,f) #define ACPI_MADT11_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_GENERIC_INTERRUPT,f) #define ACPI_MADT12_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_GENERIC_DISTRIBUTOR,f) #define ACPI_MADT13_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_GENERIC_MSI_FRAME,f) #define ACPI_MADT14_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_GENERIC_REDISTRIBUTOR,f) #define ACPI_MADT15_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MADT_GENERIC_TRANSLATOR,f) #define ACPI_MADTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SUBTABLE_HEADER,f) #define ACPI_MCFG0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MCFG_ALLOCATION,f) #define ACPI_MPST0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MPST_POWER_NODE,f) #define ACPI_MPST0A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MPST_POWER_STATE,f) #define ACPI_MPST0B_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MPST_COMPONENT,f) #define ACPI_MPST1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MPST_DATA_HDR,f) #define ACPI_MPST2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MPST_POWER_DATA,f) #define ACPI_MSCT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MSCT_PROXIMITY,f) #define ACPI_MTMR0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_MTMR_ENTRY,f) #define ACPI_NFITH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_HEADER,f) #define ACPI_NFIT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_SYSTEM_ADDRESS,f) #define ACPI_NFIT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_MEMORY_MAP,f) #define ACPI_NFIT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_INTERLEAVE,f) #define ACPI_NFIT3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_SMBIOS,f) #define ACPI_NFIT4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_CONTROL_REGION,f) #define ACPI_NFIT5_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_DATA_REGION,f) #define ACPI_NFIT6_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_FLUSH_ADDRESS,f) #define ACPI_NFIT7_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_NFIT_CAPABILITIES,f) #define ACPI_PCCT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PCCT_SUBSPACE,f) #define ACPI_PCCT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PCCT_HW_REDUCED,f) #define ACPI_PCCT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PCCT_HW_REDUCED_TYPE2,f) #define ACPI_PCCT3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PCCT_EXT_PCC_MASTER,f) #define ACPI_PCCT4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PCCT_EXT_PCC_SLAVE,f) #define ACPI_PDTT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PDTT_CHANNEL,f) #define ACPI_PMTT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PMTT_SOCKET,f) #define ACPI_PMTT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PMTT_CONTROLLER,f) #define ACPI_PMTT1A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PMTT_DOMAIN,f) #define ACPI_PMTT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PMTT_PHYSICAL_COMPONENT,f) #define ACPI_PMTTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PMTT_HEADER,f) #define ACPI_PPTTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SUBTABLE_HEADER,f) #define ACPI_PPTT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PPTT_PROCESSOR,f) #define ACPI_PPTT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PPTT_CACHE,f) #define ACPI_PPTT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_PPTT_ID,f) #define ACPI_S3PTH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_FPDT_HEADER,f) #define ACPI_S3PT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_S3PT_RESUME,f) #define ACPI_S3PT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_S3PT_SUSPEND,f) #define ACPI_SDEVH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SDEV_HEADER,f) #define ACPI_SDEV0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SDEV_NAMESPACE,f) #define ACPI_SDEV1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SDEV_PCIE,f) #define ACPI_SDEV1A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SDEV_PCIE_PATH,f) #define ACPI_SLIC_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_SLIC,f) #define ACPI_SRATH_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SUBTABLE_HEADER,f) #define ACPI_SRAT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_CPU_AFFINITY,f) #define ACPI_SRAT1_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_MEM_AFFINITY,f) #define ACPI_SRAT2_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_X2APIC_CPU_AFFINITY,f) #define ACPI_SRAT3_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_GICC_AFFINITY,f) #define ACPI_SRAT4_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_GIC_ITS_AFFINITY,f) #define ACPI_SRAT5_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_SRAT_GENERIC_AFFINITY,f) #define ACPI_TCPA_CLIENT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_TCPA_CLIENT,f) #define ACPI_TCPA_SERVER_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_TCPA_SERVER,f) #define ACPI_TPM2A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TPM2_TRAILER,f) #define ACPI_TPM211_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TPM2_ARM_SMC,f) #define ACPI_TPM23A_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TPM23_TRAILER,f) #define ACPI_VRTC0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_VRTC_ENTRY,f) #define ACPI_WDAT0_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_WDAT_ENTRY,f) /* * Simplify access to flag fields by breaking them up into bytes */ #define ACPI_FLAG_OFFSET(d,f,o) (UINT16) (ACPI_OFFSET (d,f) + o) /* Flags */ #define ACPI_BGRT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_BGRT,f,o) #define ACPI_DRTM_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_DRTM,f,o) #define ACPI_DRTM1a_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_DRTM_RESOURCE,f,o) #define ACPI_FADT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_FADT,f,o) #define ACPI_FACS_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_FACS,f,o) #define ACPI_HPET_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_HPET,f,o) #define ACPI_PPTT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PPTT_PROCESSOR,f,o) #define ACPI_PPTT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PPTT_CACHE,f,o) #define ACPI_SRAT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SRAT_CPU_AFFINITY,f,o) #define ACPI_SRAT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SRAT_MEM_AFFINITY,f,o) #define ACPI_SRAT2_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SRAT_X2APIC_CPU_AFFINITY,f,o) #define ACPI_SRAT3_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SRAT_GICC_AFFINITY,f,o) #define ACPI_SRAT5_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SRAT_GENERIC_AFFINITY,f,o) #define ACPI_GTDT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_GTDT,f,o) #define ACPI_GTDT0a_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_GTDT_TIMER_ENTRY,f,o) #define ACPI_GTDT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_GTDT_WATCHDOG,f,o) #define ACPI_HMAT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HMAT_PROXIMITY_DOMAIN,f,o) #define ACPI_HMAT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HMAT_LOCALITY,f,o) #define ACPI_HMAT2_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HMAT_CACHE,f,o) #define ACPI_IORT3_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_IORT_SMMU,f,o) #define ACPI_IORT3a_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_IORT_SMMU_GSI,f,o) #define ACPI_IORT4_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_IORT_SMMU_V3,f,o) #define ACPI_IORTA_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_IORT_MEMORY_ACCESS,f,o) #define ACPI_IORTM_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_IORT_ID_MAPPING,f,o) #define ACPI_LPITH_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_LPIT_HEADER,f,o) #define ACPI_MADT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_MADT,f,o) #define ACPI_MADT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_APIC,f,o) #define ACPI_MADT2_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_INTERRUPT_OVERRIDE,f,o) #define ACPI_MADT3_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_NMI_SOURCE,f,o) #define ACPI_MADT4_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_APIC_NMI,f,o) #define ACPI_MADT7_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_SAPIC,f,o) #define ACPI_MADT8_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_INTERRUPT_SOURCE,f,o) #define ACPI_MADT9_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_X2APIC,f,o) #define ACPI_MADT10_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_X2APIC_NMI,f,o) #define ACPI_MADT11_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_GENERIC_INTERRUPT,f,o) #define ACPI_MADT13_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MADT_GENERIC_MSI_FRAME,f,o) #define ACPI_MPST0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MPST_POWER_NODE,f,o) #define ACPI_MPST2_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_MPST_POWER_DATA,f,o) #define ACPI_NFIT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_NFIT_SYSTEM_ADDRESS,f,o) #define ACPI_NFIT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_NFIT_MEMORY_MAP,f,o) #define ACPI_NFIT4_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_NFIT_CONTROL_REGION,f,o) #define ACPI_NFIT7_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_NFIT_CAPABILITIES,f,o) #define ACPI_PCCT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_PCCT,f,o) #define ACPI_PCCT1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PCCT_HW_REDUCED,f,o) #define ACPI_PCCT2_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PCCT_HW_REDUCED_TYPE2,f,o) #define ACPI_PCCT3_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PCCT_EXT_PCC_MASTER,f,o) #define ACPI_PCCT4_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PCCT_EXT_PCC_SLAVE,f,o) #define ACPI_PDTT0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PDTT_CHANNEL,f,o) #define ACPI_PMTTH_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_PMTT_HEADER,f,o) #define ACPI_SDEVH_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_SDEV_HEADER,f,o) #define ACPI_WDDT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_WDDT,f,o) #define ACPI_WSMT_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_TABLE_WSMT,f,o) #define ACPI_EINJ0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_WHEA_HEADER,f,o) #define ACPI_ERST0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_WHEA_HEADER,f,o) #define ACPI_HEST0_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HEST_IA_MACHINE_CHECK,f,o) #define ACPI_HEST1_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HEST_IA_CORRECTED,f,o) #define ACPI_HEST6_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HEST_AER_ROOT,f,o) #define ACPI_HEST11_FLAG_OFFSET(f,o) ACPI_FLAG_OFFSET (ACPI_HEST_IA_DEFERRED_CHECK,f,o) /* * Required terminator for all tables below */ #define ACPI_DMT_TERMINATOR {ACPI_DMT_EXIT, 0, NULL, 0} #define ACPI_DMT_NEW_LINE {ACPI_DMT_EXTRA_TEXT, 0, "\n", 0} <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/fault_resumable.h> typedef u64 gcov_type; typedef u32 gcov_unsigned_t; /* * Unfortunately, GCOV_COUNTERS changes with GCC's versions. Hopefully, the * following logic is correct and we've missed no cases. * * Q: How the value of GCOV_COUNTERS for each GCC version has been found? * A: Short story: using GCC's git history. * * Long story: the value of GCOV_COUNTERS depends on the number of * DEF_GCOV_COUNTER() instances in gcc/gcov-counter.def * * List of changes (excluding updates of copyright years) affecting * gcov-counter.def (from git://gcc.gnu.org/git/gcc.git) * * 596341c741a Rename SINGE_VALUE to TOPN_VALUES counters. * BASE-VER: 10.0.0 * GCOV_COUNTERS: 8 * * e37333bad7b Remove indirect call top N counter type. * BASE-VER: 10.0.0 * GCOV_COUNTERS: 8 * * 571e95ccc90 Merged to ToT dated 13th Feb 2017. * BASE-VER: 7.0.1 * GCOV_COUNTERS: 9 * * 56b653f1a37 Remove __gcov_merge_delta (PR bootstrap/77749) * BASE-VER: 7.0.0 * GCOV_COUNTERS: 9 * * afe0c5ee91a Makefile.in: Fix dependence. * BASE-VER: 5.0.0 * GCOV_COUNTERS: 10 * Notes: in basepoints/gcc-5 GCOV_COUNTERS is still 9, but there has never * been a gcc 5.0 release. The project jumped from 4.9.4 to 5.1.0. * * c77556a5d1e Add gcov-tool: an offline gcda profile processing tool Support. * BASE-VER: 4.10.0 * GCOV_COUNTERS: 9 * * Before that, the value was explicitly defined in gcc/gcov-io.h and commit * that made GCOV_COUNTERS=9 was: * * 86ce5d2fc19 Time profiler introduced * BASE-VER: 4.9.0 * GCOV_COUNTERS: 9 * Before that, the value of GCOV_COUNTERS was 8, but it doesn't make sense to * go further back, because older GCC versions than 4.9.0 are not supported * anyway. * * As a double-check, the following bash script checked the value of * GCOV_COUNTERS for each released version after gcc 4.0: * * for x in `git tag | grep -E '^releases/gcc-(4|5|6|7|8|9|10).' | sort -V`; * do * git reset --hard &> /dev/null; * git clean -fd &> /dev/null; * git checkout "$x" &> /dev/null; * echo -n "$x -> "; * if [ -f gcc/gcov-counter.def ]; then * grep 'DEF_GCOV_COUNTER(GCOV_' gcc/gcov-counter.def | wc -l; * else * grep -Eo '#define GCOV_COUNTERS[^_]+[0-9]+' gcc/gcov-io.h | * grep -Eo '[0-9]+'; * fi; * done * * Its output was: * * releases/gcc-4.0.0 -> 5 * releases/gcc-4.0.1 -> 5 * releases/gcc-4.0.2 -> 5 * releases/gcc-4.0.3 -> 5 * releases/gcc-4.0.4 -> 5 * releases/gcc-4.1.0 -> 5 * releases/gcc-4.1.1 -> 5 * releases/gcc-4.1.2 -> 5 * releases/gcc-4.2.0 -> 5 * releases/gcc-4.2.1 -> 5 * releases/gcc-4.2.2 -> 5 * releases/gcc-4.2.3 -> 5 * releases/gcc-4.2.4 -> 5 * releases/gcc-4.3.0 -> 8 * releases/gcc-4.3.1 -> 8 * releases/gcc-4.3.2 -> 8 * releases/gcc-4.3.3 -> 8 * releases/gcc-4.3.4 -> 8 * releases/gcc-4.3.5 -> 8 * releases/gcc-4.3.6 -> 8 * releases/gcc-4.4.0 -> 8 * releases/gcc-4.4.1 -> 8 * releases/gcc-4.4.2 -> 8 * releases/gcc-4.4.3 -> 8 * releases/gcc-4.4.4 -> 8 * releases/gcc-4.4.5 -> 8 * releases/gcc-4.4.6 -> 8 * releases/gcc-4.4.7 -> 8 * releases/gcc-4.5.0 -> 8 * releases/gcc-4.5.1 -> 8 * releases/gcc-4.5.2 -> 8 * releases/gcc-4.5.3 -> 8 * releases/gcc-4.5.4 -> 8 * releases/gcc-4.6.0 -> 8 * releases/gcc-4.6.1 -> 8 * releases/gcc-4.6.2 -> 8 * releases/gcc-4.6.3 -> 8 * releases/gcc-4.6.4 -> 8 * releases/gcc-4.7.0 -> 8 * releases/gcc-4.7.1 -> 8 * releases/gcc-4.7.2 -> 8 * releases/gcc-4.7.3 -> 8 * releases/gcc-4.7.4 -> 8 * releases/gcc-4.8.0 -> 8 * releases/gcc-4.8.1 -> 8 * releases/gcc-4.8.2 -> 8 * releases/gcc-4.8.3 -> 8 * releases/gcc-4.8.4 -> 8 * releases/gcc-4.8.5 -> 8 * releases/gcc-4.9.0 -> 9 * releases/gcc-4.9.1 -> 9 * releases/gcc-4.9.2 -> 9 * releases/gcc-4.9.3 -> 9 * releases/gcc-4.9.4 -> 9 * releases/gcc-5.1.0 -> 10 * releases/gcc-5.2.0 -> 10 * releases/gcc-5.3.0 -> 10 * releases/gcc-5.4.0 -> 10 * releases/gcc-5.5.0 -> 10 * releases/gcc-6.1.0 -> 10 * releases/gcc-6.2.0 -> 10 * releases/gcc-6.3.0 -> 10 * releases/gcc-6.4.0 -> 10 * releases/gcc-6.5.0 -> 10 * releases/gcc-7.1.0 -> 9 * releases/gcc-7.2.0 -> 9 * releases/gcc-7.3.0 -> 9 * releases/gcc-7.4.0 -> 9 * releases/gcc-7.5.0 -> 9 * releases/gcc-8.1.0 -> 9 * releases/gcc-8.2.0 -> 9 * releases/gcc-8.3.0 -> 9 * releases/gcc-8.4.0 -> 9 * releases/gcc-9.1.0 -> 9 * releases/gcc-9.2.0 -> 9 * releases/gcc-9.3.0 -> 9 * releases/gcc-10.1.0 -> 8 * releases/gcc-10.2.0 -> 8 */ #if __GNUC__ >= 10 #define GCOV_COUNTERS 8 #elif __GNUC__ >= 7 #define GCOV_COUNTERS 9 #elif __GNUC__ >= 5 #define GCOV_COUNTERS 10 #elif __GNUC__ == 4 && __GNUC_MINOR__ >= 9 #define GCOV_COUNTERS 9 #else #define GCOV_COUNTERS 8 #endif /* * -------------------------------------------------------------------------- * Data structures (w/ comments) copied from GCC's source: libgcc/libgcov.h * -------------------------------------------------------------------------- */ /* Information about counters for a single function. */ struct gcov_ctr_info { gcov_unsigned_t num; /* number of counters. */ gcov_type *values; /* their values. */ }; /* Information about a single function. This uses the trailing array idiom. The number of counters is determined from the merge pointer array in gcov_info. The key is used to detect which of a set of comdat functions was selected -- it points to the gcov_info object of the object file containing the selected comdat function. */ struct gcov_fn_info { const struct gcov_info *key; /* comdat key */ gcov_unsigned_t ident; /* unique ident of function */ gcov_unsigned_t lineno_checksum; /* function lineo_checksum */ gcov_unsigned_t cfg_checksum; /* function cfg checksum */ struct gcov_ctr_info ctrs[1]; /* instrumented counters */ }; /* Type of function used to merge counters. */ typedef void (*gcov_merge_fn) (gcov_type *, gcov_unsigned_t); /* Information about a single object file. */ struct gcov_info { gcov_unsigned_t version; /* expected version number */ struct gcov_info *next; /* link to next, used by libgcov */ gcov_unsigned_t stamp; /* uniquifying time stamp */ const char *filename; /* output file name */ gcov_merge_fn merge[GCOV_COUNTERS]; /* merge functions (null for unused) */ unsigned n_functions; /* number of functions */ const struct gcov_fn_info *const *functions; /* pointer to pointers to function information */ }; /* * -------------------------------------------------------------------------- * END * -------------------------------------------------------------------------- */ static int files_count; #if KERNEL_GCOV || defined(KERNEL_TEST) #define FILE_ARRAY_SIZE 1024 #else #define FILE_ARRAY_SIZE 1 #endif static struct gcov_info *files_array[FILE_ARRAY_SIZE]; static void gcov_reset_counters(struct gcov_info *gi); #if !defined(KERNEL_TEST) static struct gcov_info *gi_list; void __gcov_merge_add(gcov_type *counters, u32 n) { } void __gcov_exit(void) { } void __gcov_init(struct gcov_info *info) { if (!gi_list) { gi_list = info; } else { info->next = gi_list; gi_list = info; } files_array[files_count++] = info; gcov_reset_counters(info); } #endif /* * Dump counters to a GCDA file. * Definitions taken from GCC's source: gcc/gcov-io.h. */ /* File magic. Must not be palindromes. */ #define GCOV_DATA_MAGIC ((gcov_unsigned_t)0x67636461) /* "gcda" */ #define GCOV_TAG_FUNCTION ((gcov_unsigned_t)0x01000000) #define GCOV_TAG_FUNCTION_LENGTH (3) #define GCOV_TAG_COUNTER_BASE ((gcov_unsigned_t)0x01a10000) #define GCOV_TAG_COUNTER_LENGTH(NUM) ((NUM) * 2) /* Convert a counter index to a tag. */ #define GCOV_TAG_FOR_COUNTER(COUNT) \ (GCOV_TAG_COUNTER_BASE + ((gcov_unsigned_t)(COUNT) << 17)) // ---------------------------------------------------------------- static u32 compute_gcda_file_size(const struct gcov_info *info) { const struct gcov_ctr_info *counters; u32 size = 0; // header size += 3 * sizeof(u32); for (u32 i = 0; i < info->n_functions; i++) { // function tag & checksums size += 5 * sizeof(u32); counters = info->functions[i]->ctrs; for (u32 j = 0; j < GCOV_COUNTERS; j++) { if (!info->merge[j]) continue; /* no merge func -> the counter is NOT used */ size += 2 * sizeof(u32); size += counters->num * sizeof(u64); counters++; } } return size; } // ---------------------------------------------------------------- int sys_gcov_get_file_count(void) { return files_count; } int sys_gcov_get_file_info(int fn, char *user_fname_buf, u32 fname_buf_size, u32 *user_fsize) { if (fn < 0 || fn >= files_count) return -EINVAL; int rc; const struct gcov_info *gi = files_array[fn]; const u32 fname_len = (u32)strlen(gi->filename); if (fname_buf_size < fname_len + 1) { return -ENOBUFS; } rc = copy_to_user(user_fname_buf, gi->filename, fname_len + 1); if (rc != 0) return -EFAULT; if (user_fsize != NULL) { u32 s = compute_gcda_file_size(gi); rc = copy_to_user(user_fsize, &s, sizeof(s)); if (rc != 0) return -EFAULT; } return 0; } static void gcov_reset_counters(struct gcov_info *gi) { const struct gcov_ctr_info *counters; for (u32 i = 0; i < gi->n_functions; i++) { counters = gi->functions[i]->ctrs; for (u32 j = 0; j < GCOV_COUNTERS; j++) { if (!gi->merge[j]) continue; /* no merge func -> the counter is NOT used */ bzero(&counters->values[0], counters->num * sizeof(gcov_type)); counters++; } } } static void gcov_dump_file_to_buf(const struct gcov_info *gi, void *buf) { const struct gcov_fn_info *func; const struct gcov_ctr_info *counters; u32 *ptr = buf; // Header *ptr++ = GCOV_DATA_MAGIC; *ptr++ = gi->version; *ptr++ = gi->stamp; for (u32 i = 0; i < gi->n_functions; i++) { func = gi->functions[i]; *ptr++ = GCOV_TAG_FUNCTION; *ptr++ = GCOV_TAG_FUNCTION_LENGTH; *ptr++ = func->ident; *ptr++ = func->lineno_checksum; *ptr++ = func->cfg_checksum; counters = func->ctrs; for (u32 j = 0; j < GCOV_COUNTERS; j++) { if (!gi->merge[j]) continue; /* no merge func -> the counter is NOT used */ *ptr++ = GCOV_TAG_FOR_COUNTER(j); *ptr++ = GCOV_TAG_COUNTER_LENGTH(counters->num); for (u32 k = 0; k < counters->num; k++) { u64 val = counters->values[k]; *ptr++ = val & 0xffffffffull; *ptr++ = val >> 32; } counters++; } // for (u32 j = 0; j < GCOV_COUNTERS; j++) } // for (u32 i = 0; i < info->n_functions; i++) } int sys_gcov_get_file(int fn, char *user_buf) { if (fn < 0 || fn >= files_count) return -EINVAL; u32 rc; const struct gcov_info *gi = files_array[fn]; rc = fault_resumable_call(ALL_FAULTS_MASK, // mask &gcov_dump_file_to_buf, // func 2, // #args gi, // arg1 user_buf); // arg2 if (rc != 0) return -EFAULT; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int ramfs_ioctl(fs_handle h, ulong cmd, void *argp) { return -EINVAL; } static offt ramfs_dir_seek(struct ramfs_handle *rh, offt target_off) { struct ramfs_inode *i = rh->inode; struct ramfs_entry *dpos; offt off = 0; list_for_each_ro(dpos, &i->entries_list, lnode) { if (off == target_off) { rh->dir_pos = off; rh->dpos = dpos; break; } off++; } return rh->dir_pos; } static offt ramfs_seek_nolock(struct ramfs_handle *rh, offt off, int whence) { struct ramfs_inode *i = rh->inode; if (i->type == VFS_DIR) { if (whence != SEEK_SET || off < 0) { /* * Dirents offsets are NOT regular offsets having an actual scalar * value. They have to be treated as *opaque* values. Therefore, it * does not make ANY sense to accept values of `whence` other than * just SEEK_SET. */ return -EINVAL; } return ramfs_dir_seek(rh, off); } switch (whence) { case SEEK_SET: rh->h_fpos = off; break; case SEEK_CUR: rh->h_fpos += off; break; case SEEK_END: rh->h_fpos = (offt)i->fsize + off; break; default: return -EINVAL; } if (rh->h_fpos < 0) { rh->h_fpos = 0; return -EINVAL; } return rh->h_fpos; } static offt ramfs_seek(fs_handle h, offt off, int whence) { struct ramfs_handle *rh = h; offt ret; ramfs_file_shlock(h); { ret = ramfs_seek_nolock(rh, off, whence); } ramfs_file_shunlock(h); return ret; } /* * ramfs_unmap_past_eof_mappings() * * While reducing the size of a file with truncate(), there could be processes * where the part of the file now becoming "past-EOF" is memory-mapped. * In order to be consistent with Linux, we have to un-map, from all the virtual * space of all of these processes, the "past-EOF" pages. This way, when the * processes try to access these pages, they'll receive a SIGBUS signal, exactly * the same way as if they mapped in memory content past EOF. * * How this is done * ---------------------- * * Each inode has a `mappings_list` with all the user_mappings referring to it. * Assuming that `rlen` is the new length of the file after truncate, rounded-up * to PAGE_SIZE, for each `struct user_mapping` there are 3 cases: * * 1) The mapping remains is in a safe zone, even after the truncate() call: * * 0 KB 4 KB 8 KB 12 KB 16 KB 20 KB * +-----------+-----------+-----------+-----------+-----------+-----------+ * |###########|###########|###########|###########| | | * | | mapped | mapped | | | | * +-----------+-----------+-----------+-----------+-----------+-----------+ * ^ ^ ^ * um->off um->off+um->len rlen * * 2) The part of the mapping remains in a safe zone, part of it doesn't. * * 0 KB 4 KB 8 KB 12 KB 16 KB 20 KB * +-----------+-----------+-----------+-----------+-----------+-----------+ * |###########|###########| | | | | * | | mapped | mapped | mapped | mapped | | * +-----------+-----------+-----------+-----------+-----------+-----------+ * ^ ^ ^ * um->off rlen um->off + um->len * * 3) The whole mapping is outside of the safe zone: * * 0 KB 4 KB 8 KB 12 KB 16 KB 20 KB * +-----------+-----------+-----------+-----------+-----------+-----------+ * |###########| | | | | | * | | | mapped | mapped | mapped | | * +-----------+-----------+-----------+-----------+-----------+-----------+ * ^ ^ ^ * rlen um->off off + um->len * * Case 1) must be checked and completely ignored, as the mapping cannot be * affected by the truncate() call. * * Case 2) requires us to unmap 3 pages, outside of the safe zone. In order to * do that, we need to calculate the starting address as: * * um->vaddr + (rlen - um->off) * \_____________/ * voff * * After that, we just have to calculate `vend` as: * * um->vaddr + um->len * * No matter where we started, the ending address of the mapping will be the * same and it will always be > `rlen`, because we're not in case 1). * * Case 3) is the same as case 2) with the exception that `voff` is just 0. */ static void ramfs_unmap_past_eof_mappings(struct ramfs_inode *i, size_t len) { const size_t rlen = pow2_round_up_at(len, PAGE_SIZE); struct user_mapping *um; ulong va; ASSERT(!is_preemption_enabled()); list_for_each_ro(um, &i->mappings_list, inode_node) { if (um->off + um->len <= rlen) continue; const ulong voff = rlen >= um->off ? rlen - um->off : 0; const ulong vend = um->vaddr + um->len; for (va = um->vaddr + voff; va < vend; va += PAGE_SIZE) { unmap_page_permissive(um->pi->pdir, (void *)va, false); invalidate_page(va); } } } static int ramfs_inode_truncate(struct ramfs_inode *i, offt len) { ASSERT(rwlock_wp_holding_exlock(&i->rwlock)); if (len < 0 || len >= i->fsize) return -EINVAL; if (i->type == VFS_DIR) return -EISDIR; /* * Truncate syscalls cannot get here unless the inode is a file or a * directory. In case of a symlink, we'll get here the corresponding file. * In case of special files instead, the VFS layer should have already * redirected the truncate call to a different layer. */ ASSERT(i->type == VFS_FILE); disable_preemption(); { ramfs_unmap_past_eof_mappings(i, (size_t) len); } enable_preemption(); while (true) { struct ramfs_block *b = bintree_get_last_obj(i->blocks_tree_root, struct ramfs_block, node); if (!b || b->offset < len) break; /* Remove the block object from the tree */ bintree_remove_ptr(&i->blocks_tree_root, b, struct ramfs_block, node, offset); ramfs_destroy_block(b); } i->fsize = len; i->blocks_count = pow2_round_up_at((ulong) len, PAGE_SIZE); return 0; } static int ramfs_inode_truncate_safe(struct ramfs_inode *i, offt len, bool no_perm_check) { int rc; rwlock_wp_exlock(&i->rwlock); { if ((i->mode & 0200) == 0200 || no_perm_check) { /* write permission */ if (len < i->fsize) rc = ramfs_inode_truncate(i, len); else if (len > i->fsize) rc = ramfs_inode_extend(i, len); else rc = 0; /* len == i->fsize */ } else { rc = -EACCES; } } rwlock_wp_exunlock(&i->rwlock); return rc; } static int ramfs_truncate(struct mnt_fs *fs, vfs_inode_ptr_t i, offt len) { return ramfs_inode_truncate_safe(i, len, false); } static ssize_t ramfs_read_nolock(struct ramfs_handle *rh, char *buf, size_t len, offt *pos) { struct ramfs_inode *inode = rh->inode; offt tot_read = 0; offt buf_rem = (offt) len; if (inode->type == VFS_DIR) return -EISDIR; ASSERT(inode->type == VFS_FILE); while (buf_rem > 0) { struct ramfs_block *block; const offt page = *pos & (offt)PAGE_MASK; const offt page_off = *pos & (offt)OFFSET_IN_PAGE_MASK; const offt page_rem = (offt)PAGE_SIZE - page_off; const offt file_rem = inode->fsize - *pos; const offt to_read = MIN3(page_rem, buf_rem, file_rem); if (*pos >= inode->fsize) break; ASSERT(to_read >= 0); if (!to_read) break; block = bintree_find_ptr(inode->blocks_tree_root, page, struct ramfs_block, node, offset); if (block) { /* reading a regular block */ memcpy(buf + tot_read, block->vaddr + page_off, (size_t)to_read); } else { /* reading a hole */ memset(buf + tot_read, 0, (size_t)to_read); } tot_read += to_read; *pos += to_read; buf_rem -= to_read; } return (ssize_t) tot_read; } static ssize_t ramfs_read(fs_handle h, char *buf, size_t len, offt *pos) { struct ramfs_handle *rh = h; ssize_t ret; ramfs_file_shlock(h); { ret = ramfs_read_nolock(rh, buf, len, pos); } ramfs_file_shunlock(h); return ret; } static ssize_t ramfs_write_nolock(struct ramfs_handle *rh, char *buf, size_t len, offt *pos) { struct ramfs_inode *inode = rh->inode; offt tot_written = 0; offt buf_rem = (offt)len; /* We can be sure it's a file because dirs cannot be open for writing */ ASSERT(inode->type == VFS_FILE); if (rh->fl_flags & O_APPEND) *pos = inode->fsize; while (buf_rem > 0) { struct ramfs_block *block; const offt page = *pos & (offt)PAGE_MASK; const offt page_off = *pos & (offt)OFFSET_IN_PAGE_MASK; const offt page_rem = (offt)PAGE_SIZE - page_off; const offt to_write = MIN(page_rem, buf_rem); ASSERT(to_write > 0); block = bintree_find_ptr(inode->blocks_tree_root, page, struct ramfs_block, node, offset); /* Assert that if page_off > 0, the block is present */ ASSERT(!page_off || block); if (!block) { if (!(block = ramfs_new_block(page))) break; ramfs_append_new_block(inode, block); } memcpy(block->vaddr + page_off, buf + tot_written, (size_t)to_write); tot_written += to_write; buf_rem -= to_write; *pos += to_write; if (*pos > inode->fsize) inode->fsize = *pos; } if (len > 0 && !tot_written) return -ENOSPC; return (ssize_t)tot_written; } static ssize_t ramfs_write(fs_handle h, char *buf, size_t len, offt *pos) { struct ramfs_handle *rh = h; ssize_t ret; ramfs_file_exlock(h); { ret = ramfs_write_nolock(rh, buf, len, pos); } ramfs_file_exunlock(h); return ret; } static ssize_t ramfs_readv_nolock(struct ramfs_handle *rh, const struct iovec *iov, int iovcnt) { struct task *curr = get_curr_task(); ssize_t ret = 0; ssize_t rc; size_t len; for (int i = 0; i < iovcnt; i++) { len = MIN(iov[i].iov_len, IO_COPYBUF_SIZE); rc = ramfs_read_nolock(rh, curr->io_copybuf, len, &rh->h_fpos); if (rc < 0) { ret = rc; break; } if (copy_to_user(iov[i].iov_base, curr->io_copybuf, len)) return -EFAULT; ret += rc; if (rc < (ssize_t)iov[i].iov_len) break; // Not enough data to fill all the user buffers. } return ret; } static ssize_t ramfs_readv(fs_handle h, const struct iovec *iov, int iovcnt) { struct ramfs_handle *rh = h; ssize_t ret; ramfs_file_shlock(h); { ret = ramfs_readv_nolock(rh, iov, iovcnt); } ramfs_file_shunlock(h); return ret; } static ssize_t ramfs_writev_nolock(struct ramfs_handle *h, const struct iovec *iov, int iovcnt) { struct task *curr = get_curr_task(); ssize_t ret = 0; ssize_t rc; size_t len; for (int i = 0; i < iovcnt; i++) { len = MIN(iov[i].iov_len, IO_COPYBUF_SIZE); if (copy_from_user(curr->io_copybuf, iov[i].iov_base, len)) return -EFAULT; rc = ramfs_write_nolock(h, curr->io_copybuf, len, &h->h_fpos); if (rc < 0) { ret = rc; break; } ret += rc; if (rc < (ssize_t)iov[i].iov_len) break; } return ret; } static ssize_t ramfs_writev(fs_handle h, const struct iovec *iov, int iovcnt) { struct ramfs_handle *rh = h; ssize_t ret; ramfs_file_exlock(h); { ret = ramfs_writev_nolock(rh, iov, iovcnt); } ramfs_file_exunlock(h); return ret; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/term.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/tty_struct.h> term *__curr_term; const struct term_interface *__curr_term_intf; const struct term_interface *video_term_intf; const struct term_interface *serial_term_intf; void set_curr_video_term(term *t) { ASSERT(!is_preemption_enabled()); ASSERT(__curr_term_intf != NULL); ASSERT(__curr_term_intf->get_type() == term_type_video); __curr_term_intf->pause_output(__curr_term); __curr_term = t; __curr_term_intf->restart_output(__curr_term); } void register_term_intf(const struct term_interface *intf) { switch (intf->get_type()) { case term_type_video: ASSERT(video_term_intf == NULL); video_term_intf = intf; break; case term_type_serial: ASSERT(serial_term_intf == NULL); serial_term_intf = intf; break; default: NOT_REACHED(); } } void init_first_video_term(const struct video_interface *vi, u16 rows, u16 cols, int rows_buf) { ASSERT(!term_is_initialized()); __curr_term_intf = video_term_intf; __curr_term = __curr_term_intf->get_first_term(); __curr_term_intf->video_term_init(__curr_term, vi, rows, cols, rows_buf); } void init_first_serial_term(u16 port) { ASSERT(!term_is_initialized()); __curr_term_intf = serial_term_intf; __curr_term = __curr_term_intf->get_first_term(); __curr_term_intf->serial_term_init(__curr_term, port); } void init_first_term_null(void) { init_first_video_term(NULL, 0, 0, 0); } void process_term_read_info(struct term_params *out) { struct tty *t = get_curr_process_tty(); ASSERT(__curr_term_intf); if (t) *out = t->tparams; else __curr_term_intf->get_params(__curr_term, out); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include "devshell.h" #include "sysenter.h" static int sysenter_fork(void) { return sysenter_call0(2 /* fork */); } static int fork_test(int (*fork_func)(void)) { printf("Running infinite loop..\n"); unsigned n = 1; int FORK_TEST_ITERS_hits_count = 0; bool inchild = false; bool exit_on_next_FORK_TEST_ITERS_hit = false; while (true) { if (!(n % FORK_TEST_ITERS)) { printf("[PID: %i] FORK_TEST_ITERS hit!\n", getpid()); if (exit_on_next_FORK_TEST_ITERS_hit) { break; } FORK_TEST_ITERS_hits_count++; if (FORK_TEST_ITERS_hits_count == 1) { printf("forking..\n"); int pid = fork_func(); printf("Fork returned %i\n", pid); if (pid == 0) { printf("############## I'm the child!\n"); inchild = true; } else { printf("############## I'm the parent, child's pid = %i\n", pid); printf(STR_PARENT "waiting the child to exit...\n"); int wstatus=0; int p = waitpid(pid, &wstatus, 0); printf(STR_PARENT "child (pid: %i) exited with status: %i!\n", p, WEXITSTATUS(wstatus)); exit_on_next_FORK_TEST_ITERS_hit = true; } } if (FORK_TEST_ITERS_hits_count == 2 && inchild) { printf("child: 2 iter hits, exit!\n"); exit(123); // exit from the child } } n++; } return 0; } int cmd_fork0(int argc, char **argv) { return fork_test(&fork); } static int do_fork_perf(int (*fork_func)(void)) { const int iters = 150000; int rc, wstatus, child_pid; ull_t start, duration; start = RDTSC(); for (int i = 0; i < iters; i++) { child_pid = fork_func(); if (child_pid < 0) { perror("fork() failed"); return 1; } if (!child_pid) exit(0); // exit from the child rc = waitpid(child_pid, &wstatus, 0); if (rc < 0) { perror("waitpid() failed"); return 1; } if (rc != child_pid) { printf("waitpid() returned %d [expected: %d]\n", rc, child_pid); return 1; } } duration = RDTSC() - start; printf("duration: %llu\n", duration/iters); return 0; } int cmd_fork_se(int argc, char **argv) { return fork_test(&sysenter_fork); } int cmd_fork_perf(int argc, char **argv) { return do_fork_perf(&fork); } int cmd_vfork_perf(int argc, char **argv) { return do_fork_perf(&vfork); } int cmd_execve0(int argc, char **argv) { int rc, pid, wstatus; char buf[32]; const char *devshell_path = get_devshell_path(); if (argc >= 2 && !strcmp(argv[0], "--test1")) { printf("[execve child] Trying to access mapped mem before fork\n"); ulong val = strtoul(argv[1], NULL, 16); void *ptr = (void *)val; strcpy(ptr, "hello world\n"); printf("[execve child] Something's wrong: I succeeded!\n"); return 0; } printf(STR_PARENT "Calling fork()...\n"); pid = fork(); DEVSHELL_CMD_ASSERT(pid >= 0); if (!pid) { printf(STR_CHILD "alloc 1 MB with mmap()\n"); void *res = mmap(NULL, 1 * MB, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); DEVSHELL_CMD_ASSERT(res != (void *)-1); strcpy(res, "I can write here, for sure!"); sprintf(buf, "%p", res); printf(STR_CHILD "call execve(devshell)\n"); execl(devshell_path, "devshell", "-c", "execve0", "--test1", buf, NULL); perror("execl"); exit(123); } printf(STR_PARENT "Wait for child, expecting it killed by SIGSEGV\n"); rc = waitpid(pid, &wstatus, 0); DEVSHELL_CMD_ASSERT(rc == pid); print_waitpid_change(pid, wstatus); DEVSHELL_CMD_ASSERT(WIFSIGNALED(wstatus)); DEVSHELL_CMD_ASSERT(WTERMSIG(wstatus) == SIGSEGV); return 0; } int cmd_fork1(int argc, char **argv) { int rc, pid, wstatus; void *mmap_addr; printf(STR_CHILD "alloc 1 MB with mmap()\n"); mmap_addr = mmap(NULL, 1 * MB, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); DEVSHELL_CMD_ASSERT(mmap_addr != (void *)-1); strcpy(mmap_addr, "hello from parent"); printf(STR_PARENT "Calling fork()...\n"); pid = fork(); DEVSHELL_CMD_ASSERT(pid >= 0); if (!pid) { printf(STR_CHILD "hello from the child\n"); printf(STR_CHILD "mmap_addr: '%s'\n", (char *)mmap_addr); printf(STR_CHILD "Calling munmap()..\n"); if ((rc = munmap(mmap_addr, 1 * MB))) { perror("munmap failed in the child"); exit(1); } printf(STR_CHILD "clean exit\n"); exit(0); } printf(STR_PARENT "Wait for the child\n"); rc = waitpid(pid, &wstatus, 0); DEVSHELL_CMD_ASSERT(rc == pid); print_waitpid_change(pid, wstatus); DEVSHELL_CMD_ASSERT(!WIFSIGNALED(wstatus)); DEVSHELL_CMD_ASSERT(WEXITSTATUS(wstatus) == 0); if ((rc = munmap(mmap_addr, 1 * MB))) perror("munmap failed in the parent"); printf(STR_PARENT "clean exit\n"); return 0; } int cmd_vfork0(int argc, char **argv) { static const char child_hello[] = "Hello from the child!!"; static const char parent_hello[] = "Hello from the parent!!"; int rc, pid, wstatus, failed = 0; volatile int stack_var = 0; /* changed by child: must be volatile */ void *volatile mmap_addr = NULL; /* changed by child: must be volatile */ printf(STR_PARENT "Call vfork()..\n"); pid = vfork(); DEVSHELL_CMD_ASSERT(pid >= 0); if (!pid) { printf(STR_CHILD "In vfork-ed child..\n"); printf(STR_CHILD "mmap(1 MB)...\n"); mmap_addr = mmap(NULL, 1 * MB, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); printf(STR_CHILD "mmap_addr: %p\n", mmap_addr); DEVSHELL_CMD_ASSERT(mmap_addr != (void *)-1); forced_memcpy(mmap_addr, child_hello, sizeof(child_hello)); printf(STR_CHILD "Sleep a little\n"); usleep(70 * 1000); printf(STR_CHILD "Setting stack_var\n"); stack_var = 12345; printf(STR_CHILD "Call _exit(0)\n"); _exit(0); } if (stack_var != 12345) { printf(STR_PARENT "ERROR: stack_var not set by vforked-child!\n"); failed = 1; } printf(STR_PARENT "Read from mmap_addr:\n"); printf(STR_PARENT "'%s'\n", (char *)mmap_addr); printf(STR_PARENT "Write to mmap_addr...\n"); forced_memcpy(mmap_addr, parent_hello, sizeof(parent_hello)); rc = waitpid(pid, &wstatus, 0); DEVSHELL_CMD_ASSERT(rc == pid); print_waitpid_change(pid, wstatus); return failed; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # This is the latest version of vim that works correctly. Version > v8.2.5057 # uses unsupported kernel features related to timers. # # See https://github.com/vim/vim/issues/10647 # # TODO: check what exactly needs to be implemented in Tilck to support the # latest version of vim and consider if it's worth the effort for Tilck in # general. Hint: it looks like implementing sys_getitimer() and sys_setitimer() # might be enough. VIM_VER="v8.2.5056" function download_vim { local tarname="vim-$VIM_VER.tgz" local url="https://github.com/vim/vim.git" local tag="" if [[ "$VIM_VER" != "latest" ]]; then tag="$VIM_VER" fi download_git_repo_in_cache "$url" "$tag" $tarname vim extract_cachefile_tar_gz $tarname -- } all_funcs_list+=(build_vim) function build_vim { pushd $ARCH if ! [ -d vim ]; then show_work_on_component_msg "VIM" reset_cc_vars local ncurses="$TC/$ARCH/ncurses/install" if ! [ -d "$ncurses" ]; then echo "ERROR: ncurses is needed to build vim" echo "How to fix: run this script with -s build_ncurses first" exit 1 fi download_vim cd vim local curr="$PWD" if [[ "$HOST_ARCH" == "$ARCH" ]]; then # Remember: this scenario (building on $ARCH) is _not_ officially # supported. export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" export CC="$MAIN_DIR/scripts/build_scripts/${ARCH}-gcc" export CXX="$MAIN_DIR/scripts/build_scripts/${ARCH}-g++" else # Default case set_cc_vars_to_tc fi export CFLAGS="-ggdb -Os" export LDFLAGS="-static -L$ncurses/lib" export CPPFLAGS="-I$ncurses/include/ncurses" local c_opts="--with-features=normal" run_command2 "./configure --prefix=$curr/install $c_opts" configure.log run_command2 "make -j$BUILD_PAR" build.log run_command2 "make install" install.log pushd install cp -r ../runtime . pushd runtime rm -rf doc lang tutor spell popd tar cfz vr.tgz runtime rm -rf runtime gzip -c --best ./bin/vim > vim.gz chmod 644 vim.gz popd export CFLAGS="" export LDFLAGS="" export CPPFLAGS="" else show_skip_component_msg "VIM" fi reset_cc_vars popd } function build_vim_installed_status { if [ -d $TC/$ARCH/vim ]; then if [ -f $TC/$ARCH/vim/install/vim.gz ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/****************************************************************************** * * Module Name: psloop - Main AML parse loop * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* * Parse the AML and build an operation tree as most interpreters, (such as * Perl) do. Parsing is done by hand rather than with a YACC generated parser * to tightly constrain stack and dynamic memory usage. Parsing is kept * flexible and the code fairly compact by parsing based on a list of AML * opcode templates in AmlOpInfo[]. */ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "acparser.h" #include "acdispat.h" #include "amlcode.h" #include "acconvert.h" #include "acnamesp.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psloop") /* Local prototypes */ static ACPI_STATUS AcpiPsGetArguments ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT *Op); /******************************************************************************* * * FUNCTION: AcpiPsGetArguments * * PARAMETERS: WalkState - Current state * AmlOpStart - Op start in AML * Op - Current Op * * RETURN: Status * * DESCRIPTION: Get arguments for passed Op. * ******************************************************************************/ static ACPI_STATUS AcpiPsGetArguments ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg = NULL; ACPI_FUNCTION_TRACE_PTR (PsGetArguments, WalkState); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Get arguments for opcode [%s]\n", Op->Common.AmlOpName)); switch (Op->Common.AmlOpcode) { case AML_BYTE_OP: /* AML_BYTEDATA_ARG */ case AML_WORD_OP: /* AML_WORDDATA_ARG */ case AML_DWORD_OP: /* AML_DWORDATA_ARG */ case AML_QWORD_OP: /* AML_QWORDATA_ARG */ case AML_STRING_OP: /* AML_ASCIICHARLIST_ARG */ /* Fill in constant or string argument directly */ AcpiPsGetNextSimpleArg (&(WalkState->ParserState), GET_CURRENT_ARG_TYPE (WalkState->ArgTypes), Op); break; case AML_INT_NAMEPATH_OP: /* AML_NAMESTRING_ARG */ Status = AcpiPsGetNextNamepath (WalkState, &(WalkState->ParserState), Op, ACPI_POSSIBLE_METHOD_CALL); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } WalkState->ArgTypes = 0; break; default: /* * Op is not a constant or string, append each argument to the Op */ while (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) && !WalkState->ArgCount) { WalkState->Aml = WalkState->ParserState.Aml; switch (Op->Common.AmlOpcode) { case AML_METHOD_OP: case AML_BUFFER_OP: case AML_PACKAGE_OP: case AML_VARIABLE_PACKAGE_OP: case AML_WHILE_OP: break; default: ASL_CV_CAPTURE_COMMENTS (WalkState); break; } Status = AcpiPsGetNextArg (WalkState, &(WalkState->ParserState), GET_CURRENT_ARG_TYPE (WalkState->ArgTypes), &Arg); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (Arg) { AcpiPsAppendArg (Op, Arg); } INCREMENT_ARG_LIST (WalkState->ArgTypes); } ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Final argument count: %8.8X pass %u\n", WalkState->ArgCount, WalkState->PassNumber)); /* Special processing for certain opcodes */ switch (Op->Common.AmlOpcode) { case AML_METHOD_OP: /* * Skip parsing of control method because we don't have enough * info in the first pass to parse it correctly. * * Save the length and address of the body */ Op->Named.Data = WalkState->ParserState.Aml; Op->Named.Length = (UINT32) (WalkState->ParserState.PkgEnd - WalkState->ParserState.Aml); /* Skip body of method */ WalkState->ParserState.Aml = WalkState->ParserState.PkgEnd; WalkState->ArgCount = 0; break; case AML_BUFFER_OP: case AML_PACKAGE_OP: case AML_VARIABLE_PACKAGE_OP: if ((Op->Common.Parent) && (Op->Common.Parent->Common.AmlOpcode == AML_NAME_OP) && (WalkState->PassNumber <= ACPI_IMODE_LOAD_PASS2)) { ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Setup Package/Buffer: Pass %u, AML Ptr: %p\n", WalkState->PassNumber, AmlOpStart)); /* * Skip parsing of Buffers and Packages because we don't have * enough info in the first pass to parse them correctly. */ Op->Named.Data = AmlOpStart; Op->Named.Length = (UINT32) (WalkState->ParserState.PkgEnd - AmlOpStart); /* Skip body */ WalkState->ParserState.Aml = WalkState->ParserState.PkgEnd; WalkState->ArgCount = 0; } break; case AML_WHILE_OP: if (WalkState->ControlState) { WalkState->ControlState->Control.PackageEnd = WalkState->ParserState.PkgEnd; } break; default: /* No action for all other opcodes */ break; } break; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsParseLoop * * PARAMETERS: WalkState - Current state * * RETURN: Status * * DESCRIPTION: Parse AML (pointed to by the current parser state) and return * a tree of ops. * ******************************************************************************/ ACPI_STATUS AcpiPsParseLoop ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op = NULL; /* current op */ ACPI_PARSE_STATE *ParserState; UINT8 *AmlOpStart = NULL; UINT8 OpcodeLength; ACPI_FUNCTION_TRACE_PTR (PsParseLoop, WalkState); if (WalkState->DescendingCallback == NULL) { return_ACPI_STATUS (AE_BAD_PARAMETER); } ParserState = &WalkState->ParserState; WalkState->ArgTypes = 0; #ifndef ACPI_CONSTANT_EVAL_ONLY if (WalkState->WalkType & ACPI_WALK_METHOD_RESTART) { /* We are restarting a preempted control method */ if (AcpiPsHasCompletedScope (ParserState)) { /* * We must check if a predicate to an IF or WHILE statement * was just completed */ if ((ParserState->Scope->ParseScope.Op) && ((ParserState->Scope->ParseScope.Op->Common.AmlOpcode == AML_IF_OP) || (ParserState->Scope->ParseScope.Op->Common.AmlOpcode == AML_WHILE_OP)) && (WalkState->ControlState) && (WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING)) { /* * A predicate was just completed, get the value of the * predicate and branch based on that value */ WalkState->Op = NULL; Status = AcpiDsGetPredicateValue (WalkState, ACPI_TO_POINTER (TRUE)); if (ACPI_FAILURE (Status) && ((Status & AE_CODE_MASK) != AE_CODE_CONTROL)) { if (Status == AE_AML_NO_RETURN_VALUE) { ACPI_EXCEPTION ((AE_INFO, Status, "Invoked method did not return a value")); } ACPI_EXCEPTION ((AE_INFO, Status, "GetPredicate Failed")); return_ACPI_STATUS (Status); } Status = AcpiPsNextParseState (WalkState, Op, Status); } AcpiPsPopScope (ParserState, &Op, &WalkState->ArgTypes, &WalkState->ArgCount); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Popped scope, Op=%p\n", Op)); } else if (WalkState->PrevOp) { /* We were in the middle of an op */ Op = WalkState->PrevOp; WalkState->ArgTypes = WalkState->PrevArgTypes; } } #endif /* Iterative parsing loop, while there is more AML to process: */ while ((ParserState->Aml < ParserState->AmlEnd) || (Op)) { ASL_CV_CAPTURE_COMMENTS (WalkState); AmlOpStart = ParserState->Aml; if (!Op) { Status = AcpiPsCreateOp (WalkState, AmlOpStart, &Op); if (ACPI_FAILURE (Status)) { /* * ACPI_PARSE_MODULE_LEVEL means that we are loading a table by * executing it as a control method. However, if we encounter * an error while loading the table, we need to keep trying to * load the table rather than aborting the table load. Set the * status to AE_OK to proceed with the table load. */ if ((WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL) && ((Status == AE_ALREADY_EXISTS) || (Status == AE_NOT_FOUND))) { Status = AE_OK; } if (Status == AE_CTRL_PARSE_CONTINUE) { continue; } if (Status == AE_CTRL_PARSE_PENDING) { Status = AE_OK; } if (Status == AE_CTRL_TERMINATE) { return_ACPI_STATUS (Status); } Status = AcpiPsCompleteOp (WalkState, &Op, Status); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (AcpiNsOpensScope ( AcpiPsGetOpcodeInfo (WalkState->Opcode)->ObjectType)) { /* * If the scope/device op fails to parse, skip the body of * the scope op because the parse failure indicates that * the device may not exist. */ ACPI_INFO (("Skipping parse of AML opcode: %s (0x%4.4X)", AcpiPsGetOpcodeName (WalkState->Opcode), WalkState->Opcode)); /* * Determine the opcode length before skipping the opcode. * An opcode can be 1 byte or 2 bytes in length. */ OpcodeLength = 1; if ((WalkState->Opcode & 0xFF00) == AML_EXTENDED_OPCODE) { OpcodeLength = 2; } WalkState->ParserState.Aml = WalkState->Aml + OpcodeLength; WalkState->ParserState.Aml = AcpiPsGetNextPackageEnd(&WalkState->ParserState); WalkState->Aml = WalkState->ParserState.Aml; } continue; } AcpiExStartTraceOpcode (Op, WalkState); } /* * Start ArgCount at zero because we don't know if there are * any args yet */ WalkState->ArgCount = 0; switch (Op->Common.AmlOpcode) { case AML_BYTE_OP: case AML_WORD_OP: case AML_DWORD_OP: case AML_QWORD_OP: break; default: ASL_CV_CAPTURE_COMMENTS (WalkState); break; } /* Are there any arguments that must be processed? */ if (WalkState->ArgTypes) { /* Get arguments */ Status = AcpiPsGetArguments (WalkState, AmlOpStart, Op); if (ACPI_FAILURE (Status)) { Status = AcpiPsCompleteOp (WalkState, &Op, Status); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if ((WalkState->ControlState) && ((WalkState->ControlState->Control.Opcode == AML_IF_OP) || (WalkState->ControlState->Control.Opcode == AML_WHILE_OP))) { /* * If the if/while op fails to parse, we will skip parsing * the body of the op. */ ParserState->Aml = WalkState->ControlState->Control.AmlPredicateStart + 1; ParserState->Aml = AcpiPsGetNextPackageEnd (ParserState); WalkState->Aml = ParserState->Aml; ACPI_ERROR ((AE_INFO, "Skipping While/If block")); if (*WalkState->Aml == AML_ELSE_OP) { ACPI_ERROR ((AE_INFO, "Skipping Else block")); WalkState->ParserState.Aml = WalkState->Aml + 1; WalkState->ParserState.Aml = AcpiPsGetNextPackageEnd (ParserState); WalkState->Aml = ParserState->Aml; } ACPI_FREE(AcpiUtPopGenericState (&WalkState->ControlState)); } Op = NULL; continue; } } /* Check for arguments that need to be processed */ ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Parseloop: argument count: %8.8X\n", WalkState->ArgCount)); if (WalkState->ArgCount) { /* * There are arguments (complex ones), push Op and * prepare for argument */ Status = AcpiPsPushScope (ParserState, Op, WalkState->ArgTypes, WalkState->ArgCount); if (ACPI_FAILURE (Status)) { Status = AcpiPsCompleteOp (WalkState, &Op, Status); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } continue; } Op = NULL; continue; } /* * All arguments have been processed -- Op is complete, * prepare for next */ WalkState->OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); if (WalkState->OpInfo->Flags & AML_NAMED) { if (Op->Common.AmlOpcode == AML_REGION_OP || Op->Common.AmlOpcode == AML_DATA_REGION_OP) { /* * Skip parsing of control method or opregion body, * because we don't have enough info in the first pass * to parse them correctly. * * Completed parsing an OpRegion declaration, we now * know the length. */ Op->Named.Length = (UINT32) (ParserState->Aml - Op->Named.Data); } } if (WalkState->OpInfo->Flags & AML_CREATE) { /* * Backup to beginning of CreateXXXfield declaration (1 for * Opcode) * * BodyLength is unknown until we parse the body */ Op->Named.Length = (UINT32) (ParserState->Aml - Op->Named.Data); } if (Op->Common.AmlOpcode == AML_BANK_FIELD_OP) { /* * Backup to beginning of BankField declaration * * BodyLength is unknown until we parse the body */ Op->Named.Length = (UINT32) (ParserState->Aml - Op->Named.Data); } /* This op complete, notify the dispatcher */ if (WalkState->AscendingCallback != NULL) { WalkState->Op = Op; WalkState->Opcode = Op->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); Status = AcpiPsNextParseState (WalkState, Op, Status); if (Status == AE_CTRL_PENDING) { Status = AE_OK; } else if ((WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL) && (ACPI_AML_EXCEPTION(Status) || Status == AE_ALREADY_EXISTS || Status == AE_NOT_FOUND)) { /* * ACPI_PARSE_MODULE_LEVEL flag means that we are currently * loading a table by executing it as a control method. * However, if we encounter an error while loading the table, * we need to keep trying to load the table rather than * aborting the table load (setting the status to AE_OK * continues the table load). If we get a failure at this * point, it means that the dispatcher got an error while * trying to execute the Op. */ Status = AE_OK; } } Status = AcpiPsCompleteOp (WalkState, &Op, Status); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* while ParserState->Aml */ Status = AcpiPsCompleteFinalOp (WalkState, Op, Status); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <sys/time.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/select.h> #include "devshell.h" void regular_poll_or_select_on_pipe_child(int rfd, int wfd); /* Regular comunication with child via pipe, before poll timeout */ int cmd_select1(int argc, char **argv) { struct timeval tv; fd_set readfds, writefds; int nfds, pipefd[2]; int wstatus; int rc, fl, tot; int failed = 0; char buf[64]; pid_t childpid; signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE */ printf(STR_PARENT "Calling pipe()\n"); rc = pipe(pipefd); if (rc < 0) { printf(STR_PARENT "pipe() failed. Error: %s\n", strerror(errno)); exit(1); } printf(STR_PARENT "fork()..\n"); childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) regular_poll_or_select_on_pipe_child(pipefd[0], pipefd[1]); /* Wait on the read end of the pipe */ FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(pipefd[0], &readfds); tv.tv_sec = 3; tv.tv_usec = 0; nfds = pipefd[0] + 1; /* Now, wait for the child to start and write something to the pipe */ do { rc = select(nfds, &readfds, &writefds, NULL, &tv); } while (rc < 0 && errno == EINTR); if (rc < 0) { printf(STR_PARENT "ERROR: select() failed with: %s\n", strerror(errno)); failed = 1; goto wait_child_and_return; } if (rc == 0) { printf(STR_PARENT "ERROR: select() timed out (unexpected)\n"); failed = 1; goto wait_child_and_return; } if (rc != 1) { printf(STR_PARENT "ERROR: select() returned %d (expected: 1)\n", rc); failed = 1; goto wait_child_and_return; } if (!FD_ISSET(pipefd[0], &readfds)) { printf(STR_PARENT "ERROR: pipefd[0] is NOT set in readfds\n"); failed = 1; goto wait_child_and_return; } rc = read(pipefd[0], buf, sizeof(buf)); if (rc < 0) { printf(STR_PARENT "ERROR: read(rfd]) failed with: %s\n", strerror(errno)); failed = 1; goto wait_child_and_return; } buf[rc] = 0; printf(STR_PARENT "Got: '%s' from child\n", buf); printf(STR_PARENT "Now make wfd nonblock and fill the buffer\n"); fl = fcntl(pipefd[1], F_GETFL, 0); if (fl < 0) { printf(STR_PARENT "fcntl(pipefd[1]) failed with: %s\n", strerror(errno)); goto wait_child_and_return; } fl |= O_NONBLOCK; rc = fcntl(pipefd[1], F_SETFL, fl); DEVSHELL_CMD_ASSERT(rc == 0); tot = 0; do { if ((rc = write(pipefd[1], &buf[0], 1)) > 0) tot += rc; } while (rc > 0); printf(STR_PARENT "Restore the blocking mode on wfd\n"); rc = fcntl(pipefd[1], F_SETFL, fl & ~O_NONBLOCK); DEVSHELL_CMD_ASSERT(rc == 0); printf(STR_PARENT "The pipe buffer is full after writing %d bytes\n", tot); printf(STR_PARENT "Now select() wfd with writefds\n"); FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(pipefd[1], &writefds); tv.tv_sec = 3; tv.tv_usec = 0; nfds = pipefd[1] + 1; do { rc = select(nfds, &readfds, &writefds, NULL, &tv); } while (rc < 0 && errno == EINTR); if (rc < 0) { printf(STR_PARENT "ERROR: select() failed with: %s\n", strerror(errno)); failed = 1; goto wait_child_and_return; } if (rc == 0) { printf(STR_PARENT "ERROR: select() timed out (unexpected)\n"); failed = 1; goto wait_child_and_return; } if (rc != 1) { printf(STR_PARENT "ERROR: select() returned %d (expected: 1)\n", rc); failed = 1; goto wait_child_and_return; } if (!FD_ISSET(pipefd[1], &writefds)) { printf(STR_PARENT "ERROR: pipefd[1] is NOT set in writefds\n"); failed = 1; goto wait_child_and_return; } printf(STR_PARENT "select() completed as expected\n"); wait_child_and_return: printf(STR_PARENT "waitpid()..\n"); rc = waitpid(childpid, &wstatus, 0); if (rc < 0) { printf(STR_PARENT "waitpid() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "waitpid() done\n"); close(pipefd[0]); close(pipefd[1]); return failed; } /* Test select() with tv != NULL, but tv_sec = tv_usec = 0 */ int cmd_select2(int argc, char **argv) { struct timeval tv; fd_set readfds; int nfds, pipefd[2]; char buf[64]; int rc; printf("Creating a pipe...\n"); rc = pipe(pipefd); if (rc < 0) { printf("pipe() failed. Error: %s\n", strerror(errno)); return 1; } FD_ZERO(&readfds); FD_SET(pipefd[0], &readfds); tv.tv_sec = 0; tv.tv_usec = 0; nfds = pipefd[0] + 1; printf("Running select()...\n"); rc = select(nfds, &readfds, NULL, NULL, &tv); if (rc < 0) { perror("select"); return 1; } printf("select() returned (immediately): %d\n", rc); if (rc != 0) { printf("select() did *not* return 0 as expected\n"); return 1; } printf("Write something on the pipe\n"); rc = write(pipefd[1], "hello", 5); DEVSHELL_CMD_ASSERT(rc == 5); FD_ZERO(&readfds); FD_SET(pipefd[0], &readfds); tv.tv_sec = 0; tv.tv_usec = 0; nfds = pipefd[0] + 1; printf("Running select()\n"); rc = select(nfds, &readfds, NULL, NULL, &tv); if (rc < 0) { perror("select"); return 1; } printf("select() returned (immediately): %d\n", rc); if (rc != 1) { printf("select() did return 1 as expected\n"); return 1; } if (!FD_ISSET(pipefd[0], &readfds)) { printf(STR_PARENT "ERROR: pipefd[0] is NOT set in readfds\n"); return 1; } printf("Everything is alright, pipefd[0] is set in readfds\n"); rc = read(pipefd[0], buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc > 0); buf[rc] = 0; printf("Got from the pipe: '%s'\n", buf); close(pipefd[0]); close(pipefd[1]); return 0; } /* Trigger the timeout case */ int cmd_select3(int argc, char **argv) { struct timeval tv; fd_set readfds; int rc; FD_ZERO(&readfds); FD_SET(0 /* stdin */, &readfds); tv.tv_sec = 0; tv.tv_usec = 100 * 1000; printf("Running select()\n"); rc = select(1, &readfds, NULL, NULL, &tv); if (rc < 0) { perror("select"); return 1; } if (rc > 0) { printf("ERROR: unexpected return value %d > 0\n", rc); return 1; } printf("select() returned 0 (timeout), as expected\n"); return 0; } /* Select as nanosleep() */ int cmd_select4(int argc, char **argv) { struct timeval tv, rtv1, rtv2; u64 ts1, ts2, elapsed; int rc, attempts_cnt = 1; int sleep_ms = 100; const int max_attempts = 5; again: printf("Running select(0, NULL, NULL, NULL, &tv /* %d ms */)\n", sleep_ms); gettimeofday(&rtv1, NULL); { tv.tv_sec = 0; tv.tv_usec = sleep_ms * 1000; rc = select(0, NULL, NULL, NULL, &tv); if (rc != 0) { printf("ERROR: selected returned %d instead of 0 [err: %s]\n", rc, strerror(errno)); return 1; } } gettimeofday(&rtv2, NULL); ts1 = (u64)rtv1.tv_sec * 1000 + rtv1.tv_usec / 1000; ts2 = (u64)rtv2.tv_sec * 1000 + rtv2.tv_usec / 1000; elapsed = ts2 - ts1; printf("Elapsed: %" PRIu64 " ms\n", elapsed); if ((elapsed < 90 * sleep_ms / 100) || (elapsed > 110 * sleep_ms / 100)) { printf("Elapsed was more than expected (%d <= t <= %d ms)\n", 90 * sleep_ms / 100, 110 * sleep_ms / 100); if (attempts_cnt >= max_attempts) { printf("We failed already %d times. STOP\n", max_attempts); return 1; } printf("Probably that was caused by the load of the host machine\n"); printf("Re-running the test again...\n"); attempts_cnt++; sleep_ms *= 2; printf("\n\n[attempt %d of %d] ...\n", attempts_cnt, max_attempts); goto again; } return 0; } <file_sep>/****************************************************************************** * * Module Name: nsdump - table dumping routines for debug * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acoutput.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsdump") /* Local prototypes */ #ifdef ACPI_OBSOLETE_FUNCTIONS void AcpiNsDumpRootDevices ( void); static ACPI_STATUS AcpiNsDumpOneDevice ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue); #endif #if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER) static ACPI_STATUS AcpiNsDumpOneObjectPath ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue); static ACPI_STATUS AcpiNsGetMaxDepth ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue); /******************************************************************************* * * FUNCTION: AcpiNsPrintPathname * * PARAMETERS: NumSegments - Number of ACPI name segments * Pathname - The compressed (internal) path * * RETURN: None * * DESCRIPTION: Print an object's full namespace pathname * ******************************************************************************/ void AcpiNsPrintPathname ( UINT32 NumSegments, const char *Pathname) { UINT32 i; ACPI_FUNCTION_NAME (NsPrintPathname); /* Check if debug output enabled */ if (!ACPI_IS_DEBUG_ENABLED (ACPI_LV_NAMES, ACPI_NAMESPACE)) { return; } /* Print the entire name */ ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "[")); while (NumSegments) { for (i = 0; i < 4; i++) { isprint ((int) Pathname[i]) ? AcpiOsPrintf ("%c", Pathname[i]) : AcpiOsPrintf ("?"); } Pathname += ACPI_NAMESEG_SIZE; NumSegments--; if (NumSegments) { AcpiOsPrintf ("."); } } AcpiOsPrintf ("]\n"); } #ifdef ACPI_OBSOLETE_FUNCTIONS /* Not used at this time, perhaps later */ /******************************************************************************* * * FUNCTION: AcpiNsDumpPathname * * PARAMETERS: Handle - Object * Msg - Prefix message * Level - Desired debug level * Component - Caller's component ID * * RETURN: None * * DESCRIPTION: Print an object's full namespace pathname * Manages allocation/freeing of a pathname buffer * ******************************************************************************/ void AcpiNsDumpPathname ( ACPI_HANDLE Handle, const char *Msg, UINT32 Level, UINT32 Component) { ACPI_FUNCTION_TRACE (NsDumpPathname); /* Do this only if the requested debug level and component are enabled */ if (!ACPI_IS_DEBUG_ENABLED (Level, Component)) { return_VOID; } /* Convert handle to a full pathname and print it (with supplied message) */ AcpiNsPrintNodePathname (Handle, Msg); AcpiOsPrintf ("\n"); return_VOID; } #endif /******************************************************************************* * * FUNCTION: AcpiNsDumpOneObject * * PARAMETERS: ObjHandle - Node to be dumped * Level - Nesting level of the handle * Context - Passed into WalkNamespace * ReturnValue - Not used * * RETURN: Status * * DESCRIPTION: Dump a single Node * This procedure is a UserFunction called by AcpiNsWalkNamespace. * ******************************************************************************/ ACPI_STATUS AcpiNsDumpOneObject ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue) { ACPI_WALK_INFO *Info = (ACPI_WALK_INFO *) Context; ACPI_NAMESPACE_NODE *ThisNode; ACPI_OPERAND_OBJECT *ObjDesc = NULL; ACPI_OBJECT_TYPE ObjType; ACPI_OBJECT_TYPE Type; UINT32 BytesToDump; UINT32 DbgLevel; UINT32 i; ACPI_FUNCTION_NAME (NsDumpOneObject); /* Is output enabled? */ if (!(AcpiDbgLevel & Info->DebugLevel)) { return (AE_OK); } if (!ObjHandle) { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Null object handle\n")); return (AE_OK); } ThisNode = AcpiNsValidateHandle (ObjHandle); if (!ThisNode) { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Invalid object handle %p\n", ObjHandle)); return (AE_OK); } Type = ThisNode->Type; Info->Count++; /* Check if the owner matches */ if ((Info->OwnerId != ACPI_OWNER_ID_MAX) && (Info->OwnerId != ThisNode->OwnerId)) { return (AE_OK); } if (!(Info->DisplayType & ACPI_DISPLAY_SHORT)) { /* Indent the object according to the level */ AcpiOsPrintf ("%2d%*s", (UINT32) Level - 1, (int) Level * 2, " "); /* Check the node type and name */ if (Type > ACPI_TYPE_LOCAL_MAX) { ACPI_WARNING ((AE_INFO, "Invalid ACPI Object Type 0x%08X", Type)); } AcpiOsPrintf ("%4.4s", AcpiUtGetNodeName (ThisNode)); } /* Now we can print out the pertinent information */ AcpiOsPrintf (" %-12s %p %3.3X ", AcpiUtGetTypeName (Type), ThisNode, ThisNode->OwnerId); DbgLevel = AcpiDbgLevel; AcpiDbgLevel = 0; ObjDesc = AcpiNsGetAttachedObject (ThisNode); AcpiDbgLevel = DbgLevel; /* Temp nodes are those nodes created by a control method */ if (ThisNode->Flags & ANOBJ_TEMPORARY) { AcpiOsPrintf ("(T) "); } switch (Info->DisplayType & ACPI_DISPLAY_MASK) { case ACPI_DISPLAY_SUMMARY: if (!ObjDesc) { /* No attached object. Some types should always have an object */ switch (Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_PACKAGE: case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: case ACPI_TYPE_METHOD: AcpiOsPrintf ("<No attached object>"); break; default: break; } AcpiOsPrintf ("\n"); return (AE_OK); } switch (Type) { case ACPI_TYPE_PROCESSOR: AcpiOsPrintf ("ID %02X Len %02X Addr %8.8X%8.8X\n", ObjDesc->Processor.ProcId, ObjDesc->Processor.Length, ACPI_FORMAT_UINT64 (ObjDesc->Processor.Address)); break; case ACPI_TYPE_DEVICE: AcpiOsPrintf ("Notify Object: %p\n", ObjDesc); break; case ACPI_TYPE_METHOD: AcpiOsPrintf ("Args %X Len %.4X Aml %p\n", (UINT32) ObjDesc->Method.ParamCount, ObjDesc->Method.AmlLength, ObjDesc->Method.AmlStart); break; case ACPI_TYPE_INTEGER: AcpiOsPrintf ("= %8.8X%8.8X\n", ACPI_FORMAT_UINT64 (ObjDesc->Integer.Value)); break; case ACPI_TYPE_PACKAGE: if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { AcpiOsPrintf ("Elements %.2X\n", ObjDesc->Package.Count); } else { AcpiOsPrintf ("[Length not yet evaluated]\n"); } break; case ACPI_TYPE_BUFFER: if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { AcpiOsPrintf ("Len %.2X", ObjDesc->Buffer.Length); /* Dump some of the buffer */ if (ObjDesc->Buffer.Length > 0) { AcpiOsPrintf (" ="); for (i = 0; (i < ObjDesc->Buffer.Length && i < 12); i++) { AcpiOsPrintf (" %2.2X", ObjDesc->Buffer.Pointer[i]); } } AcpiOsPrintf ("\n"); } else { AcpiOsPrintf ("[Length not yet evaluated]\n"); } break; case ACPI_TYPE_STRING: AcpiOsPrintf ("Len %.2X ", ObjDesc->String.Length); AcpiUtPrintString (ObjDesc->String.Pointer, 80); AcpiOsPrintf ("\n"); break; case ACPI_TYPE_REGION: AcpiOsPrintf ("[%s]", AcpiUtGetRegionName (ObjDesc->Region.SpaceId)); if (ObjDesc->Region.Flags & AOPOBJ_DATA_VALID) { AcpiOsPrintf (" Addr %8.8X%8.8X Len %.4X\n", ACPI_FORMAT_UINT64 (ObjDesc->Region.Address), ObjDesc->Region.Length); } else { AcpiOsPrintf (" [Address/Length not yet evaluated]\n"); } break; case ACPI_TYPE_LOCAL_REFERENCE: AcpiOsPrintf ("[%s]\n", AcpiUtGetReferenceName (ObjDesc)); break; case ACPI_TYPE_BUFFER_FIELD: if (ObjDesc->BufferField.BufferObj && ObjDesc->BufferField.BufferObj->Buffer.Node) { AcpiOsPrintf ("Buf [%4.4s]", AcpiUtGetNodeName ( ObjDesc->BufferField.BufferObj->Buffer.Node)); } break; case ACPI_TYPE_LOCAL_REGION_FIELD: AcpiOsPrintf ("Rgn [%4.4s]", AcpiUtGetNodeName ( ObjDesc->CommonField.RegionObj->Region.Node)); break; case ACPI_TYPE_LOCAL_BANK_FIELD: AcpiOsPrintf ("Rgn [%4.4s] Bnk [%4.4s]", AcpiUtGetNodeName ( ObjDesc->CommonField.RegionObj->Region.Node), AcpiUtGetNodeName ( ObjDesc->BankField.BankObj->CommonField.Node)); break; case ACPI_TYPE_LOCAL_INDEX_FIELD: AcpiOsPrintf ("Idx [%4.4s] Dat [%4.4s]", AcpiUtGetNodeName ( ObjDesc->IndexField.IndexObj->CommonField.Node), AcpiUtGetNodeName ( ObjDesc->IndexField.DataObj->CommonField.Node)); break; case ACPI_TYPE_LOCAL_ALIAS: case ACPI_TYPE_LOCAL_METHOD_ALIAS: AcpiOsPrintf ("Target %4.4s (%p)\n", AcpiUtGetNodeName (ObjDesc), ObjDesc); break; default: AcpiOsPrintf ("Object %p\n", ObjDesc); break; } /* Common field handling */ switch (Type) { case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: AcpiOsPrintf (" Off %.3X Len %.2X Acc %.2X\n", (ObjDesc->CommonField.BaseByteOffset * 8) + ObjDesc->CommonField.StartFieldBitOffset, ObjDesc->CommonField.BitLength, ObjDesc->CommonField.AccessByteWidth); break; default: break; } break; case ACPI_DISPLAY_OBJECTS: AcpiOsPrintf ("O:%p", ObjDesc); if (!ObjDesc) { /* No attached object, we are done */ AcpiOsPrintf ("\n"); return (AE_OK); } AcpiOsPrintf ("(R%u)", ObjDesc->Common.ReferenceCount); switch (Type) { case ACPI_TYPE_METHOD: /* Name is a Method and its AML offset/length are set */ AcpiOsPrintf (" M:%p-%X\n", ObjDesc->Method.AmlStart, ObjDesc->Method.AmlLength); break; case ACPI_TYPE_INTEGER: AcpiOsPrintf (" I:%8.8X8.8%X\n", ACPI_FORMAT_UINT64 (ObjDesc->Integer.Value)); break; case ACPI_TYPE_STRING: AcpiOsPrintf (" S:%p-%X\n", ObjDesc->String.Pointer, ObjDesc->String.Length); break; case ACPI_TYPE_BUFFER: AcpiOsPrintf (" B:%p-%X\n", ObjDesc->Buffer.Pointer, ObjDesc->Buffer.Length); break; default: AcpiOsPrintf ("\n"); break; } break; default: AcpiOsPrintf ("\n"); break; } /* If debug turned off, done */ if (!(AcpiDbgLevel & ACPI_LV_VALUES)) { return (AE_OK); } /* If there is an attached object, display it */ DbgLevel = AcpiDbgLevel; AcpiDbgLevel = 0; ObjDesc = AcpiNsGetAttachedObject (ThisNode); AcpiDbgLevel = DbgLevel; /* Dump attached objects */ while (ObjDesc) { ObjType = ACPI_TYPE_INVALID; AcpiOsPrintf ("Attached Object %p: ", ObjDesc); /* Decode the type of attached object and dump the contents */ switch (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc)) { case ACPI_DESC_TYPE_NAMED: AcpiOsPrintf ("(Ptr to Node)\n"); BytesToDump = sizeof (ACPI_NAMESPACE_NODE); ACPI_DUMP_BUFFER (ObjDesc, BytesToDump); break; case ACPI_DESC_TYPE_OPERAND: ObjType = ObjDesc->Common.Type; if (ObjType > ACPI_TYPE_LOCAL_MAX) { AcpiOsPrintf ( "(Pointer to ACPI Object type %.2X [UNKNOWN])\n", ObjType); BytesToDump = 32; } else { AcpiOsPrintf ( "(Pointer to ACPI Object type %.2X [%s])\n", ObjType, AcpiUtGetTypeName (ObjType)); BytesToDump = sizeof (ACPI_OPERAND_OBJECT); } ACPI_DUMP_BUFFER (ObjDesc, BytesToDump); break; default: break; } /* If value is NOT an internal object, we are done */ if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) { goto Cleanup; } /* Valid object, get the pointer to next level, if any */ switch (ObjType) { case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: /* * NOTE: takes advantage of common fields between string/buffer */ BytesToDump = ObjDesc->String.Length; ObjDesc = (void *) ObjDesc->String.Pointer; AcpiOsPrintf ("(Buffer/String pointer %p length %X)\n", ObjDesc, BytesToDump); ACPI_DUMP_BUFFER (ObjDesc, BytesToDump); goto Cleanup; case ACPI_TYPE_BUFFER_FIELD: ObjDesc = (ACPI_OPERAND_OBJECT *) ObjDesc->BufferField.BufferObj; break; case ACPI_TYPE_PACKAGE: ObjDesc = (void *) ObjDesc->Package.Elements; break; case ACPI_TYPE_METHOD: ObjDesc = (void *) ObjDesc->Method.AmlStart; break; case ACPI_TYPE_LOCAL_REGION_FIELD: ObjDesc = (void *) ObjDesc->Field.RegionObj; break; case ACPI_TYPE_LOCAL_BANK_FIELD: ObjDesc = (void *) ObjDesc->BankField.RegionObj; break; case ACPI_TYPE_LOCAL_INDEX_FIELD: ObjDesc = (void *) ObjDesc->IndexField.IndexObj; break; default: goto Cleanup; } } Cleanup: AcpiOsPrintf ("\n"); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsDumpObjects * * PARAMETERS: Type - Object type to be dumped * DisplayType - 0 or ACPI_DISPLAY_SUMMARY * MaxDepth - Maximum depth of dump. Use ACPI_UINT32_MAX * for an effectively unlimited depth. * OwnerId - Dump only objects owned by this ID. Use * ACPI_UINT32_MAX to match all owners. * StartHandle - Where in namespace to start/end search * * RETURN: None * * DESCRIPTION: Dump typed objects within the loaded namespace. Uses * AcpiNsWalkNamespace in conjunction with AcpiNsDumpOneObject. * ******************************************************************************/ void AcpiNsDumpObjects ( ACPI_OBJECT_TYPE Type, UINT8 DisplayType, UINT32 MaxDepth, ACPI_OWNER_ID OwnerId, ACPI_HANDLE StartHandle) { ACPI_WALK_INFO Info; ACPI_STATUS Status; ACPI_FUNCTION_ENTRY (); /* * Just lock the entire namespace for the duration of the dump. * We don't want any changes to the namespace during this time, * especially the temporary nodes since we are going to display * them also. */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not acquire namespace mutex\n"); return; } Info.Count = 0; Info.DebugLevel = ACPI_LV_TABLES; Info.OwnerId = OwnerId; Info.DisplayType = DisplayType; (void) AcpiNsWalkNamespace (Type, StartHandle, MaxDepth, ACPI_NS_WALK_NO_UNLOCK | ACPI_NS_WALK_TEMP_NODES, AcpiNsDumpOneObject, NULL, (void *) &Info, NULL); AcpiOsPrintf ("\nNamespace node count: %u\n\n", Info.Count); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); } /******************************************************************************* * * FUNCTION: AcpiNsDumpOneObjectPath, AcpiNsGetMaxDepth * * PARAMETERS: ObjHandle - Node to be dumped * Level - Nesting level of the handle * Context - Passed into WalkNamespace * ReturnValue - Not used * * RETURN: Status * * DESCRIPTION: Dump the full pathname to a namespace object. AcpNsGetMaxDepth * computes the maximum nesting depth in the namespace tree, in * order to simplify formatting in AcpiNsDumpOneObjectPath. * These procedures are UserFunctions called by AcpiNsWalkNamespace. * ******************************************************************************/ static ACPI_STATUS AcpiNsDumpOneObjectPath ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue) { UINT32 MaxLevel = *((UINT32 *) Context); char *Pathname; ACPI_NAMESPACE_NODE *Node; int PathIndent; if (!ObjHandle) { return (AE_OK); } Node = AcpiNsValidateHandle (ObjHandle); if (!Node) { /* Ignore bad node during namespace walk */ return (AE_OK); } Pathname = AcpiNsGetNormalizedPathname (Node, TRUE); PathIndent = 1; if (Level <= MaxLevel) { PathIndent = MaxLevel - Level + 1; } AcpiOsPrintf ("%2d%*s%-12s%*s", Level, Level, " ", AcpiUtGetTypeName (Node->Type), PathIndent, " "); AcpiOsPrintf ("%s\n", &Pathname[1]); ACPI_FREE (Pathname); return (AE_OK); } static ACPI_STATUS AcpiNsGetMaxDepth ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue) { UINT32 *MaxLevel = (UINT32 *) Context; if (Level > *MaxLevel) { *MaxLevel = Level; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsDumpObjectPaths * * PARAMETERS: Type - Object type to be dumped * DisplayType - 0 or ACPI_DISPLAY_SUMMARY * MaxDepth - Maximum depth of dump. Use ACPI_UINT32_MAX * for an effectively unlimited depth. * OwnerId - Dump only objects owned by this ID. Use * ACPI_UINT32_MAX to match all owners. * StartHandle - Where in namespace to start/end search * * RETURN: None * * DESCRIPTION: Dump full object pathnames within the loaded namespace. Uses * AcpiNsWalkNamespace in conjunction with AcpiNsDumpOneObjectPath. * ******************************************************************************/ void AcpiNsDumpObjectPaths ( ACPI_OBJECT_TYPE Type, UINT8 DisplayType, UINT32 MaxDepth, ACPI_OWNER_ID OwnerId, ACPI_HANDLE StartHandle) { ACPI_STATUS Status; UINT32 MaxLevel = 0; ACPI_FUNCTION_ENTRY (); /* * Just lock the entire namespace for the duration of the dump. * We don't want any changes to the namespace during this time, * especially the temporary nodes since we are going to display * them also. */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not acquire namespace mutex\n"); return; } /* Get the max depth of the namespace tree, for formatting later */ (void) AcpiNsWalkNamespace (Type, StartHandle, MaxDepth, ACPI_NS_WALK_NO_UNLOCK | ACPI_NS_WALK_TEMP_NODES, AcpiNsGetMaxDepth, NULL, (void *) &MaxLevel, NULL); /* Now dump the entire namespace */ (void) AcpiNsWalkNamespace (Type, StartHandle, MaxDepth, ACPI_NS_WALK_NO_UNLOCK | ACPI_NS_WALK_TEMP_NODES, AcpiNsDumpOneObjectPath, NULL, (void *) &MaxLevel, NULL); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); } /******************************************************************************* * * FUNCTION: AcpiNsDumpEntry * * PARAMETERS: Handle - Node to be dumped * DebugLevel - Output level * * RETURN: None * * DESCRIPTION: Dump a single Node * ******************************************************************************/ void AcpiNsDumpEntry ( ACPI_HANDLE Handle, UINT32 DebugLevel) { ACPI_WALK_INFO Info; ACPI_FUNCTION_ENTRY (); Info.DebugLevel = DebugLevel; Info.OwnerId = ACPI_OWNER_ID_MAX; Info.DisplayType = ACPI_DISPLAY_SUMMARY; (void) AcpiNsDumpOneObject (Handle, 1, &Info, NULL); } #ifdef ACPI_ASL_COMPILER /******************************************************************************* * * FUNCTION: AcpiNsDumpTables * * PARAMETERS: SearchBase - Root of subtree to be dumped, or * NS_ALL to dump the entire namespace * MaxDepth - Maximum depth of dump. Use INT_MAX * for an effectively unlimited depth. * * RETURN: None * * DESCRIPTION: Dump the name space, or a portion of it. * ******************************************************************************/ void AcpiNsDumpTables ( ACPI_HANDLE SearchBase, UINT32 MaxDepth) { ACPI_HANDLE SearchHandle = SearchBase; ACPI_FUNCTION_TRACE (NsDumpTables); if (!AcpiGbl_RootNode) { /* * If the name space has not been initialized, * there is nothing to dump. */ ACPI_DEBUG_PRINT ((ACPI_DB_TABLES, "namespace not initialized!\n")); return_VOID; } if (ACPI_NS_ALL == SearchBase) { /* Entire namespace */ SearchHandle = AcpiGbl_RootNode; ACPI_DEBUG_PRINT ((ACPI_DB_TABLES, "\\\n")); } AcpiNsDumpObjects (ACPI_TYPE_ANY, ACPI_DISPLAY_OBJECTS, MaxDepth, ACPI_OWNER_ID_MAX, SearchHandle); return_VOID; } #endif #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_kmalloc.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/kmalloc_debug.h> #include <tilck/kernel/sort.h> #include "termutil.h" #include "dp_int.h" #define CHUNKS_ARR_BUF_SIZE (16 * KB) struct chunk_info { size_t size; size_t count; u64 max_waste; u32 max_waste_p; }; static struct debug_kmalloc_stats stats; static u64 lf_allocs; static u64 lf_waste; static size_t chunks_count; static struct chunk_info *chunks_arr; static size_t chunks_max_count; static char chunks_order_by; static long dp_chunks_cmpf_size(const void *a, const void *b) { const struct chunk_info *x = a; const struct chunk_info *y = b; return (long)y->size - (long)x->size; } static long dp_chunks_cmpf_count(const void *a, const void *b) { const struct chunk_info *x = a; const struct chunk_info *y = b; return (long)y->count - (long)x->count; } static long dp_chunks_cmpf_waste(const void *a, const void *b) { const struct chunk_info *x = a; const struct chunk_info *y = b; return (long)y->max_waste - (long)x->max_waste; } static long dp_chunks_cmpf_waste_p(const void *a, const void *b) { const struct chunk_info *x = a; const struct chunk_info *y = b; return (long)y->max_waste_p - (long)x->max_waste_p; } static void dp_chunks_enter(void) { struct debug_kmalloc_chunks_ctx ctx; size_t s, c; if (!KMALLOC_HEAVY_STATS) return; if (!chunks_arr) { size_t chunks_buf_sz = CHUNKS_ARR_BUF_SIZE; for (int i = 0; i < 4; i++) { if ((chunks_arr = kzmalloc(chunks_buf_sz))) break; chunks_buf_sz /= 2; } if (!chunks_arr) panic("Unable to alloc memory for chunks_arr"); chunks_max_count = chunks_buf_sz / sizeof(struct chunk_info); } debug_kmalloc_get_stats(&stats); lf_allocs = 0; lf_waste = 0; chunks_count = 0; chunks_order_by = 's'; disable_preemption(); { debug_kmalloc_chunks_stats_start_read(&ctx); while (debug_kmalloc_chunks_stats_next(&ctx, &s, &c)) { if (chunks_count == chunks_max_count) break; const u64 waste = (u64)( UNSAFE_MAX(SMALL_HEAP_MBS, roundup_next_power_of_2(s)) - s ) * c; chunks_arr[chunks_count++] = (struct chunk_info) { .size = s, .count = c, .max_waste = waste, .max_waste_p = (u32)(waste * 1000 / (waste + (u64)s * (u64)c)), }; lf_allocs += (u64)s * c; lf_waste += waste; } } enable_preemption(); } static void dp_chunks_exit(void) { if (!KMALLOC_HEAVY_STATS) return; } static int dp_chunks_keypress(struct key_event ke) { const char c = ke.print_char; switch (c) { case 's': insertion_sort_generic(chunks_arr, sizeof(chunks_arr[0]), (u32)chunks_count, dp_chunks_cmpf_size); ui_need_update = true; chunks_order_by = c; return kb_handler_ok_and_continue; case 'c': insertion_sort_generic(chunks_arr, sizeof(chunks_arr[0]), (u32)chunks_count, dp_chunks_cmpf_count); ui_need_update = true; chunks_order_by = c; return kb_handler_ok_and_continue; case 'w': insertion_sort_generic(chunks_arr, sizeof(chunks_arr[0]), (u32)chunks_count, dp_chunks_cmpf_waste); ui_need_update = true; chunks_order_by = c; return kb_handler_ok_and_continue; case 't': insertion_sort_generic(chunks_arr, sizeof(chunks_arr[0]), (u32)chunks_count, dp_chunks_cmpf_waste_p); ui_need_update = true; chunks_order_by = c; return kb_handler_ok_and_continue; default: return kb_handler_nak; } } static void dp_show_chunks(void) { int row = dp_screen_start_row; const u64 lf_tot = lf_allocs + lf_waste; if (!KMALLOC_HEAVY_STATS) { dp_writeln("Not available: recompile with KMALLOC_HEAVY_STATS=1"); return; } dp_writeln("Chunk sizes count: %5u sizes", chunks_count); dp_writeln("Lifetime data allocated: %5llu %s [actual: %llu %s]", lf_allocs < 32*MB ? lf_allocs/KB : lf_allocs/MB, lf_allocs < 32*MB ? "KB" : "MB", lf_tot < 32*MB ? lf_tot/KB : lf_tot/MB, lf_tot < 32*MB ? "KB" : "MB"); dp_writeln("Lifetime max data waste: %5llu %s (%llu.%llu%%)", lf_waste < 32*MB ? lf_waste/KB : lf_waste/MB, lf_waste < 32*MB ? "KB" : "MB", lf_waste * 100 / lf_tot, (lf_waste * 1000 / lf_tot) % 10); dp_writeln( "Order by: " E_COLOR_BR_WHITE "s" RESET_ATTRS "ize, " E_COLOR_BR_WHITE "c" RESET_ATTRS "ount, " E_COLOR_BR_WHITE "w" RESET_ATTRS "aste, " "was" E_COLOR_BR_WHITE "t" RESET_ATTRS "e (%%)" ); dp_writeln(""); dp_writeln( "%s" " Size " RESET_ATTRS TERM_VLINE "%s" " Count " RESET_ATTRS TERM_VLINE "%s" " Max waste " RESET_ATTRS TERM_VLINE "%s" " Max waste (%%)" RESET_ATTRS, chunks_order_by == 's' ? E_COLOR_BR_WHITE REVERSE_VIDEO : "", chunks_order_by == 'c' ? E_COLOR_BR_WHITE REVERSE_VIDEO : "", chunks_order_by == 'w' ? E_COLOR_BR_WHITE REVERSE_VIDEO : "", chunks_order_by == 't' ? E_COLOR_BR_WHITE REVERSE_VIDEO : "" ); dp_writeln( GFX_ON "qqqqqqqqqqnqqqqqqqqqnqqqqqqqqqqqnqqqqqqqqqqqqqqqqqq" GFX_OFF ); for (size_t i = 0; i < chunks_count; i++) { const u64 waste = chunks_arr[i].max_waste; dp_writeln("%9u " TERM_VLINE " %7u " TERM_VLINE " %6llu %s " TERM_VLINE " %6u.%u%%", chunks_arr[i].size, chunks_arr[i].count, waste < KB ? waste : waste / KB, waste < KB ? "B " : "KB", chunks_arr[i].max_waste_p / 10, chunks_arr[i].max_waste_p % 10); } dp_writeln(""); } static struct dp_screen dp_chunks_screen = { .index = 5, .label = "MemChunks", .draw_func = dp_show_chunks, .on_dp_enter = dp_chunks_enter, .on_dp_exit = dp_chunks_exit, .on_keypress_func = dp_chunks_keypress, }; __attribute__((constructor)) static void dp_chunks_init(void) { dp_register_screen(&dp_chunks_screen); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/printk.h> #include <tilck/kernel/user.h> #include <tilck/mods/tracing.h> bool buf_append(char *dest, int *used, int *rem, char *str); static bool save_param_iov(void *data, long iovcnt, char *dest_buf, size_t dest_bs) { struct iovec *u_iovec = data; struct iovec iovec[4]; bool ok; ASSERT(dest_bs >= 128); if (iovcnt <= 0) return false; iovcnt = MIN(iovcnt, 4); if (copy_from_user(iovec, u_iovec, sizeof(iovec[0]) * (size_t)iovcnt)) return false; for (int i = 0; i < iovcnt; i++) { ((long *)(void *)(dest_buf + 0))[i] = (long)iovec[i].iov_len; ((ulong *)(void *)(dest_buf + 32))[i] = (ulong)iovec[i].iov_base; ok = ptype_buffer.save(iovec[i].iov_base, (long)iovec[i].iov_len, dest_buf + 64 + 16 * i, 16); if (!ok) return false; } return false; } static bool __dump_param_iov(ulong orig, char *data, long u_iovcnt, long maybe_tot_data_size, char *dest, size_t dest_bs) { int used = 0, rem = (int) dest_bs; long iovcnt = MIN(u_iovcnt, 4); long tot_rem = maybe_tot_data_size >= 0 ? maybe_tot_data_size : 16; char buf[32]; bool ok; ASSERT(dest_bs >= 128); snprintk(buf, sizeof(buf), "(struct iovec[%d]) {\r\n", u_iovcnt); if (!buf_append(dest, &used, &rem, buf)) return false; for (int i = 0; i < iovcnt; i++) { const long len = ((long *)(void *)(data + 0))[i]; const ulong base = ((ulong *)(void *)(data + 32))[i]; if (!buf_append(dest, &used, &rem, " {base: ")) return false; ok = ptype_buffer.dump( base, data + 64 + i * 16, MIN(len, 16), maybe_tot_data_size >= 0 ? MIN(tot_rem, len) : len, buf, sizeof(buf) ); if (!ok) return false; if (maybe_tot_data_size >= 0) tot_rem -= len; if (!buf_append(dest, &used, &rem, buf)) return false; if (!buf_append(dest, &used, &rem, ", len: ")) return false; snprintk(buf, sizeof(buf), "%d", len); if (!buf_append(dest, &used, &rem, buf)) return false; if (!buf_append(dest, &used, &rem, i < u_iovcnt-1 ? "}, \r\n" : "}")) return false; } if (u_iovcnt > iovcnt) { if (!buf_append(dest, &used, &rem, "... ")) return false; } if (!buf_append(dest, &used, &rem, "\r\n}")) return false; return true; } static bool dump_param_iov_in(ulong orig, char *data, long u_iovcnt, long unused, char *dest, size_t dest_bs) { return __dump_param_iov(orig, data, u_iovcnt, -1, dest, dest_bs); } static bool dump_param_iov_out(ulong orig, char *data, long u_iovcnt, long real_sz, char *dest, size_t dest_bs) { return __dump_param_iov(orig, data, u_iovcnt, real_sz, dest, dest_bs); } const struct sys_param_type ptype_iov_in = { .name = "iov", .slot_size = 128, .save = save_param_iov, .dump = dump_param_iov_in, .dump_from_val = NULL, }; const struct sys_param_type ptype_iov_out = { .name = "iov", .slot_size = 128, .save = save_param_iov, .dump = dump_param_iov_out, .dump_from_val = NULL, }; <file_sep># SPDX-License-Identifier: BSD-2-Clause # Some constants STABLE_SCREENSHOT_DELAY = 0.25 STABLE_SCREENSHOT_TIMEOUT = 3.00 class InvalidSystemConfig(Exception): def __init__(self, msg): super(InvalidSystemConfig, self).__init__(msg) class NoTilckHelloMessage(Exception): def __init__(self, screen_text = None): super(NoTilckHelloMessage, self).__init__("NoTilckHelloMessage") self.screen_text = screen_text class KernelPanicFailure(Exception): def __init__(self, screen_text = None): super(KernelPanicFailure, self).__init__("KernelPanicFailure") self.screen_text = screen_text class StableScreenshotFailure(Exception): def __init__(self): msg = "Unable to take a stable screenshot in {}s" msg = msg.format(STABLE_SCREENSHOT_TIMEOUT) super(StableScreenshotFailure, self).__init__(msg) class ConvertFailure(Exception): def __init__(self, msg): super(ConvertFailure, self).__init__(msg) class Pnm2TextFailure(Exception): def __init__(self, ret): super(Pnm2TextFailure, self).__init__("Return code: {}".format(ret)) class IntTestScreenTextCheckFailure(Exception): def __init__(self, screen_text, searched_text): super(IntTestScreenTextCheckFailure, self) \ .__init__( "IntTestScreenTextCheckFailure: '{}' not found" \ .format(searched_text) ) self.screen_text = screen_text class IntTestScreenshotNoMatchFailure(Exception): def __init__(self, screen_text, expected_text): super(IntTestScreenshotNoMatchFailure, self) \ .__init__("IntTestScreenshotNoMatchFailure") self.screen_text = screen_text self.expected_text = expected_text <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #if defined(__TILCK_KERNEL__) && !defined(__TILCK_HAL__) #error Never include this header directly. Do #include <tilck/kernel/hal.h>. #endif #include <tilck_gen_headers/config_kernel.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/kernel/arch/i386/asm_defs.h> struct x86_regs { u32 kernel_resume_eip; u32 custom_flags; /* custom Tilck flags */ u32 gs, fs, es, ds; u32 edi, esi, ebp, esp, ebx, edx, ecx, eax; /* pushed by 'pusha' */ s32 int_num; /* our 'push byte #' do this */ u32 err_code; /* pushed by CPU in some cases, by us in others */ u32 eip, cs, eflags, useresp, ss; /* pushed by the CPU automatically */ }; STATIC_ASSERT(SIZEOF_REGS == sizeof(regs_t)); STATIC_ASSERT(REGS_EIP_OFF == OFFSET_OF(regs_t, eip)); STATIC_ASSERT(REGS_USERESP_OFF == OFFSET_OF(regs_t, useresp)); STATIC_ASSERT(X86_KERNEL_CODE_SEL == X86_SELECTOR(1, TABLE_GDT, 0)); STATIC_ASSERT(X86_KERNEL_DATA_SEL == X86_SELECTOR(2, TABLE_GDT, 0)); STATIC_ASSERT(X86_USER_CODE_SEL == X86_SELECTOR(3, TABLE_GDT, 3)); STATIC_ASSERT(X86_USER_DATA_SEL == X86_SELECTOR(4, TABLE_GDT, 3)); struct x86_arch_proc_members { void *ldt; u16 ldt_size; /* Number of entries. Valid only if ldt != NULL. */ u16 ldt_index_in_gdt; /* Index in gdt, valid only if ldt != NULL. */ u16 gdt_entries[3]; /* Array of indexes in gdt, valid if > 0 */ }; struct x86_arch_task_members { u16 fpu_regs_size; void *aligned_fpu_regs; }; NORETURN void context_switch(regs_t *r); static ALWAYS_INLINE int regs_intnum(regs_t *r) { return r->int_num; } static ALWAYS_INLINE void set_return_register(regs_t *r, ulong value) { r->eax = value; } static ALWAYS_INLINE ulong get_rem_stack(void) { return (get_stack_ptr() & ((ulong)KERNEL_STACK_SIZE - 1)); } static ALWAYS_INLINE void *regs_get_stack_ptr(regs_t *r) { return TO_PTR(r->esp); } static ALWAYS_INLINE void *regs_get_frame_ptr(regs_t *r) { return TO_PTR(r->ebp); } static ALWAYS_INLINE void *regs_get_ip(regs_t *r) { return TO_PTR(r->eip); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/hal.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/list.h> #include <tilck/kernel/kb_scancode_set1_keys.h> struct kb_dev; struct key_event { bool pressed : 1; u32 key : 23; char print_char : 8; }; STATIC_ASSERT(sizeof(struct key_event) == sizeof(u32)); enum kb_handler_action { kb_handler_ok_and_stop = 1, kb_handler_ok_and_continue = 0, kb_handler_nak = -1, }; typedef enum kb_handler_action (*keypress_func)(struct kb_dev *, struct key_event); struct keypress_handler_elem { struct list_node node; keypress_func handler; }; struct kb_dev { struct list_node node; const char *driver_name; bool (*is_pressed)(u32 key); void (*register_handler)(struct keypress_handler_elem *e); bool (*scancode_to_ansi_seq)(u32 key, u8 modifiers, char *seq); u8 (*translate_to_mediumraw)(struct key_event ke); }; void register_keyboard_device(struct kb_dev *kbdev); void register_keypress_handler(struct keypress_handler_elem *e); u8 kb_get_current_modifiers(struct kb_dev *kb); int kb_get_fn_key_pressed(u32 key); static ALWAYS_INLINE struct key_event make_key_event(u32 key, char print_char, bool pressed) { return (struct key_event) { .pressed = pressed, .key = key, .print_char = print_char, }; } static inline bool kb_is_ctrl_pressed(struct kb_dev *kb) { return kb->is_pressed(KEY_LEFT_CTRL) || kb->is_pressed(KEY_RIGHT_CTRL); } static inline bool kb_is_alt_pressed(struct kb_dev *kb) { return kb->is_pressed(KEY_LEFT_ALT) || kb->is_pressed(KEY_RIGHT_ALT); } static inline bool kb_is_shift_pressed(struct kb_dev *kb) { return kb->is_pressed(KEY_L_SHIFT) || kb->is_pressed(KEY_R_SHIFT); } #define KB_MOD_NONE 0 #define KB_MOD_ALT 1 #define KB_MOD_SHIFT 2 #define KB_MOD_CTRL 4 /* * Match is made by OR-ing the four defines above. */ static inline bool kb_exact_match_modifiers(struct kb_dev *kb, u8 match) { return kb_get_current_modifiers(kb) == match; } static inline bool kb_partial_match_modifiers(struct kb_dev *kb, u8 match_mask) { ASSERT(match_mask != 0); return !!(kb_get_current_modifiers(kb) & match_mask); } <file_sep>#!/bin/sh exec $SYS_CC "$@" $CC_POST_FLAGS <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/term.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/tty_struct.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/devfs.h> #define TTY_READ_BS 4096 struct tty_handle_extra { offt read_pos; offt read_buf_used; char *read_buf; bool read_allowed_to_return; }; STATIC_ASSERT(sizeof(struct tty_handle_extra) <= DEVFS_EXTRA_SIZE); void tty_input_init(struct tty *t); enum kb_handler_action tty_keypress_handler(struct kb_dev *, struct key_event ke); void tty_update_ctrl_handlers(struct tty *t); void tty_update_default_state_tables(struct tty *t); ssize_t tty_read_int(struct tty *t, struct devfs_handle *h, char *buf, size_t size); ssize_t tty_write_int(struct tty *t, struct devfs_handle *h, const char *buf, size_t size); int tty_ioctl_int(struct tty *t, struct devfs_handle *h, ulong request, void *argp); bool tty_read_ready_int(struct tty *t, struct devfs_handle *h); int tty_create_extra(int minor, void *extra); void tty_destroy_extra(int minor, void *extra); int tty_on_dup_extra(int minor, void *extra); void init_ttyaux(void); void tty_create_devfile_or_panic(const char *filename, u16 major, u16 minor, void **devfile); extern const struct termios default_termios; extern struct tty *ttys[128]; /* tty0 is not a real tty */ extern int tty_worker_thread; extern struct tty *__curr_tty; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included #endif /* * NOTE: the trick to make the small heap to work well without the number of * small heaps to explode is to allow it to allocate just a small fraction of * its actual size, like 1/16th. */ #define SMALL_HEAP_MAX_ALLOC (SMALL_HEAP_SIZE / 16 - 1) #define SMALL_HEAP_NODE_ALLOC_SZ \ MAX(sizeof(struct small_heap_node), SMALL_HEAP_MAX_ALLOC + 1) /* * Be careful with this: incrementing its value to 2 does not reduce with any of * the current tests the value of shs.lifetime_created_heaps_count: this means * just wasting memory. While, setting it to 0, increases that by +1. It's a * good parameter to have and evaluate it's effects in the long term, with more * and more complex uses cases. */ #if !KERNEL_TEST_INT #define MAX_EMPTY_SMALL_HEAPS 1 #else #define MAX_EMPTY_SMALL_HEAPS 0 #endif struct small_heap_node { struct list_node node; /* all nodes */ struct list_node avail_node; /* non-full nodes, including empty ones */ struct kmalloc_heap heap; }; static struct kmalloc_small_heaps_stats shs; static struct list small_heaps_list; static struct list avail_small_heaps_list; static inline struct small_heap_node *alloc_small_heap_node(void) { return kzmalloc(SMALL_HEAP_NODE_ALLOC_SZ); } static inline void free_small_heap_node(struct small_heap_node *obj) { kfree2(obj, SMALL_HEAP_NODE_ALLOC_SZ); } static inline void add_in_avail_list(struct small_heap_node *node) { ASSERT(node->heap.mem_allocated < node->heap.size); shs.not_full_count++; if (shs.not_full_count > shs.peak_not_full_count) shs.peak_not_full_count = shs.not_full_count; list_add_tail(&avail_small_heaps_list, &node->avail_node); } static inline void remove_from_avail_list(struct small_heap_node *node) { ASSERT(!list_node_is_empty(&node->avail_node)); ASSERT( node->heap.mem_allocated == node->heap.size || node->heap.mem_allocated == SMALL_HEAP_MD_SIZE ); ASSERT(shs.not_full_count > 0); list_remove(&node->avail_node); shs.not_full_count--; DEBUG_ONLY(list_node_init(&node->avail_node)); } static inline void register_small_heap_node(struct small_heap_node *node) { ASSERT(node->heap.mem_allocated < node->heap.size); list_add_tail(&small_heaps_list, &node->node); shs.tot_count++; if (shs.tot_count > shs.peak_count) shs.peak_count = shs.tot_count; ASSERT(list_node_is_empty(&node->avail_node)); add_in_avail_list(node); } static inline void unregister_small_heap_node(struct small_heap_node *node) { ASSERT(!list_node_is_empty(&node->avail_node)); remove_from_avail_list(node); ASSERT(shs.tot_count > 0); list_remove(&node->node); shs.tot_count--; ASSERT(node->heap.mem_allocated == SMALL_HEAP_MD_SIZE); ASSERT(list_node_is_empty(&node->avail_node)); } static struct small_heap_node * alloc_new_small_heap_unsafe(void) { struct small_heap_node *new_node; void *heap_data, *metadata; size_t actual_metadata_size; size_t small_heap_sz = SMALL_HEAP_SIZE; /* * NOTE: here KMALLOC_FL_DONT_ACCOUNT is used in other to avoid the "heavy" * kmalloc stats (when enabled) to account this allocation, as it's not * really a proper allocation: it's the creation of a small heap. Instead, * the allocation for its metadata is explicitly accounted (see below) since * some memory was actually consumed. */ if (!(heap_data = general_kmalloc(&small_heap_sz, KMALLOC_FL_DONT_ACCOUNT))) return NULL; ASSERT(small_heap_sz == SMALL_HEAP_SIZE); metadata = heap_data; new_node = alloc_small_heap_node(); if (!new_node) { kfree2(heap_data, SMALL_HEAP_SIZE); return NULL; } DEBUG_ONLY(list_node_init(&new_node->node)); DEBUG_ONLY(list_node_init(&new_node->avail_node)); bool success = kmalloc_create_heap(&new_node->heap, (ulong)heap_data, SMALL_HEAP_SIZE, SMALL_HEAP_MBS, 0, true, metadata, NULL, NULL); if (!success) { free_small_heap_node(new_node); kfree2(heap_data, SMALL_HEAP_SIZE); return NULL; } // Allocate heap's metadata inside the heap itself actual_metadata_size = new_node->heap.metadata_size; DEBUG_ONLY_UNSAFE(void *actual_metadata =) per_heap_kmalloc(&new_node->heap, &actual_metadata_size, 0); ASSERT(actual_metadata == metadata); if (KMALLOC_HEAVY_STATS) kmalloc_account_alloc(actual_metadata_size); shs.lifetime_created_heaps_count++; register_small_heap_node(new_node); return new_node; } static struct small_heap_node * alloc_new_small_heap(void) { static ATOMIC(bool) in_use; struct small_heap_node *res; bool exp = false; if (!atomic_cas_strong(&in_use, &exp, true, mo_relaxed, mo_relaxed)) return NULL; res = alloc_new_small_heap_unsafe(); atomic_store_explicit(&in_use, false, mo_relaxed); return res; } static void destroy_small_heap(struct small_heap_node *node) { unregister_small_heap_node(node); kfree2((void *)node->heap.vaddr, SMALL_HEAP_SIZE); free_small_heap_node(node); } static void *small_heaps_kmalloc(size_t *size, u32 flags) { struct small_heap_node *new_node; struct small_heap_node *pos; void *ret; bool was_empty; ASSERT(!is_preemption_enabled()); ASSERT(*size <= (SMALL_HEAP_SIZE - SMALL_HEAP_MBS)); list_for_each_ro(pos, &avail_small_heaps_list, avail_node) { if (pos->heap.size - pos->heap.mem_allocated < *size) continue; was_empty = pos->heap.mem_allocated == SMALL_HEAP_MD_SIZE; /* We've found a heap with (potentially) enough space */ if ((ret = per_heap_kmalloc(&pos->heap, size, flags))) { /* * The alloc succeeded. If now the heap is full, remove it from the * 'avail' struct list. */ if (was_empty) { shs.empty_count--; ASSERT(shs.empty_count >= 0); } if (pos->heap.mem_allocated == pos->heap.size) remove_from_avail_list(pos); return ret; } } if (!(new_node = alloc_new_small_heap())) return NULL; // Now finally do the user allocation in the new heap ret = per_heap_kmalloc(&new_node->heap, size, flags); ASSERT(ret != NULL); // We've just created the node, if should be almost // empty (expect for the metadata). There is no reason // the allocation to fail. return ret; } static int small_heaps_kfree(void *ptr, size_t *size, u32 flags) { ASSERT(!is_preemption_enabled()); struct small_heap_node *pos, *node = NULL; const ulong vaddr = (ulong) ptr; bool was_full; list_for_each_ro(pos, &small_heaps_list, node) { const ulong hva = pos->heap.vaddr; const ulong hend = pos->heap.heap_last_byte-pos->heap.min_block_size+1; if (IN_RANGE_INC(vaddr, hva, hend)) { node = pos; break; } } if (!node) return -ENOENT; was_full = node->heap.mem_allocated == node->heap.size; per_heap_kfree(&node->heap, ptr, size, flags); if (was_full) { /* If the heap was full before the free, now it isn't anymore */ add_in_avail_list(node); /* * Because of the metadata, it's impossible with one single chunk to free * all the available space in the small heap: that would require having * a chunk with size different than a power of 2. */ ASSERT(node->heap.mem_allocated > SMALL_HEAP_MD_SIZE); } else { /* The chunk wasn't full: we have to check if it's "empty" now. */ if (node->heap.mem_allocated == SMALL_HEAP_MD_SIZE) { if (MAX_EMPTY_SMALL_HEAPS && shs.empty_count < MAX_EMPTY_SMALL_HEAPS) { shs.empty_count++; } else { destroy_small_heap(node); } } } return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct tty; void *alloc_console_data(void); void free_console_data(void *data); void reset_console_data(struct tty *t); void init_textmode_console(void); <file_sep>#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause import os import sys import urllib.request PCI_IDS_URL = r'https://github.com/pciutils/pciids/blob/master/pci.ids?raw=true' FIXED_COMMENTS = ''' /* * List of PCI IDs generated by scripts/dev/generate_pci_ids, part of the * Tilck project. * * Source data fetched from the `pciids` project: * {} * * Follows the original comments from the top of the `pci.ids` file. *'''.format(PCI_IDS_URL) textdata = '' def download_pci_ids_from_github(): response = urllib.request.urlopen(PCI_IDS_URL) return response.read().decode('utf-8') def show_help_and_exit(): print("Options:") print(" -v [pci_ids_file] Generate vendors C file") print(" -c [pci_ids_file] Generate device classes C file") sys.exit(1) def dump_initial_comments(): print(FIXED_COMMENTS) for line in textdata: if not line or line[0] != '#': break text = line[1:].strip() if text: print(" * {}".format(text)) else: print(" *") print(" */") print("") print(r"#include <tilck/kernel/pci.h>") print("") def generate_vendors(): # Minimal escape strings for C. Yes, there's a vendor with "" in the name. transl = str.maketrans({r'"': r'\"'}) print("const struct pci_vendor pci_vendors_list[] =") print("{") for line in textdata: if not line or line[0] == '#': continue if line[0].isspace(): continue # That's a device (1 tab) or sub-vendor + subdevice (2 tabs) if line[0] == 'C': break # That's a device class: we have to stop devid = int(line[0:4], base=16) name = line[4:].strip().translate(transl).replace("???", "?") print(" {{ 0x{:04x}, \"{}\" }},".format(devid, name)) print("};") print("") def str_or_NULL(val): return '"{}"'.format(val) if val else "NULL" class device_class_ctx: def __init__(self, class_id = 0, subclass_id = 0, progif_id = 0, class_name = "", subclass_name = "", progif_name = ""): self.class_id = class_id self.subclass_id = subclass_id self.progif_id = progif_id self.class_name = class_name self.subclass_name = subclass_name self.progif_name = progif_name def set_class(self, class_id, class_name): self.class_id = class_id self.class_name = class_name # Reset the subclass and progid fields self.subclass_id = 0 self.progif_id = 0 self.subclass_name = "" self.progif_name = "" def set_subclass(self, subclass_id, subclass_name): self.subclass_id = subclass_id self.subclass_name = subclass_name # Reset the progif fields self.progif_id = 0 self.progif_name = "" def set_progif(self, progif_id, progif_name): self.progif_id = progif_id self.progif_name = progif_name def dump(self): print(" {{ 0x{:02x}, 0x{:02x}, 0x{:02x}, {}, {}, {} }}," .format(self.class_id, self.subclass_id, self.progif_id, str_or_NULL(self.class_name), str_or_NULL(self.subclass_name), str_or_NULL(self.progif_name))) def generate_device_classes(): dev_classes = False print("const struct pci_device_class pci_device_classes_list[] =") print("{") devclass = device_class_ctx() class_dumped = True subclass_dumped = True for line in textdata: if not line or line[0] == '#': continue if not dev_classes: if line[0] != 'C': continue # Device classes haven't started yet # This is the first device class in the file dev_classes = True # We're for sure parsing the "device classes" part of the file if line[0] == 'C': # New device class new_class_id = int(line[2:4], base=16) new_class_name = line[4:].strip() if not class_dumped or not subclass_dumped: # The previous class was not dumped and it had no subclass devclass.dump() devclass.set_class(new_class_id, new_class_name) # We just hit a new class. Of course, we haven't dumped it yet: # set class_dumped to False and reset subclass_dumped. # Note: resetting the *_dumped vars means setting them to True class_dumped = False subclass_dumped = True elif line[0].isspace() and not line[1].isspace(): # New device sub-class new_subclass_id = int(line[1:3], base=16) new_subclass_name = line[4:].strip() if not subclass_dumped: # The previous sub-class was not dumped and it had no progif devclass.dump() class_dumped = True devclass.set_subclass(new_subclass_id, new_subclass_name) subclass_dumped = False else: # Device programming interface (sub-sub-class) new_progif_id = int(line[2:4], base=16) new_progif_name = line[5:].strip() devclass.set_progif(new_progif_id, new_progif_name) devclass.dump() class_dumped = True subclass_dumped = True if not class_dumped or not subclass_dumped: devclass.dump() print("};") print("") def main(): global textdata if len(sys.argv) < 2: show_help_and_exit() if sys.argv[1] not in ["-v", "-c"]: show_help_and_exit() if len(sys.argv) > 2: with open(sys.argv[2], 'r') as fh: blob = fh.read() else: blob = download_pci_ids_from_github() textdata = blob.splitlines() dump_initial_comments() if sys.argv[1] == '-v': generate_vendors() elif sys.argv[1] == '-c': generate_device_classes() if __name__ == '__main__': main() <file_sep> # This is a commodity fake Makefile that allows people to run the build from the # project's root directory, instead of entering in the build/ directory first. MAKEFLAGS += --no-print-directory TCROOT_PARENT ?= ./ TCROOT ?= $(TCROOT_PARENT)/toolchain2 PREREQUISITES := $(TCROOT) build/CMakeCache.txt all: $(PREREQUISITES) @$(MAKE) -C build gtests: $(PREREQUISITES) @$(MAKE) -C build gtests clean: $(PREREQUISITES) @$(MAKE) -C build clean # Rem is a shortcut for rebuild_img rem: $(PREREQUISITES) @rm -rf ./build/fatpart ./build/tilck.img @$(MAKE) -C build rebuild_img: $(PREREQUISITES) @rm -rf ./build/fatpart ./build/tilck.img @$(MAKE) -C build config: $(PREREQUISITES) @./scripts/run_config menuconfig: $(PREREQUISITES) @./scripts/run_config $(TCROOT): $(error Before building Tilck, you need to build the toolchain by running ./scripts/build_toolchain) build/CMakeCache.txt: @echo No CMakeCache.txt found: running CMake first. @./scripts/cmake_run .PHONY: all gtests clean <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/string_util.h> #include <tilck/kernel/user.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fault_resumable.h> int copy_from_user(void *dest, const void *user_ptr, size_t n) { if (user_out_of_range(user_ptr, n)) return -1; u32 r = fault_resumable_call(PAGE_FAULT_MASK, memcpy, 3, dest, user_ptr, n); return !r ? 0 : -1; } int copy_to_user(void *user_ptr, const void *src, size_t n) { if (user_out_of_range(user_ptr, n)) return -1; u32 r = fault_resumable_call(PAGE_FAULT_MASK, memcpy, 3, user_ptr, src, n); return !r ? 0 : -1; } static void internal_copy_user_str(void *dest, const void *user_ptr, void *dest_end, size_t *written_ptr, int *rc) { ASSERT(in_fault_resumable_code()); const char *ptr = user_ptr; char *d = dest; *written_ptr = 0; *rc = 0; do { if (d >= (char *)dest_end) { *rc = 1; return; } if (user_out_of_range(ptr, 1)) { *rc = -1; return; } *d++ = *ptr; /* NOTE: `ptr` is NOT increased here */ } while (*ptr++); *written_ptr = (size_t)(d - (char *)dest); /* NOTE: counting the final \0 */ } /* * Copy an user-space NUL-terminated string into 'dest'. Destination's buffer * size is 'max_size'. Returns: * 0 if everything is alright * -1 if the read from the user pointer causes a page fault * 1 if max_size is not enough */ int copy_str_from_user(void *dest, const void *user_ptr, size_t max_size, size_t *written_ptr) { int rc; u32 faults; size_t written; faults = fault_resumable_call(PAGE_FAULT_MASK, internal_copy_user_str, 5, dest, user_ptr, (char *)dest + max_size, &written, &rc); if (written_ptr) *written_ptr = written; if (faults) return -1; return rc; } static void internal_copy_str_array_from_user(void *dest, const char *const *user_arr, size_t max_size, size_t *written_ptr, int *rc) { int argc; char **dest_arr = (char **)dest; char *dest_end = (char *)dest + max_size; char *after_ptrs_arr; size_t written = 0; *rc = 0; ASSERT(in_fault_resumable_code()); for (argc = 0; ; argc++) { const char *const *ptr_ptr = user_arr + argc; if (user_out_of_range(ptr_ptr, sizeof(void *))) { *rc = -1; goto out; } /* * OK, the double-pointer is in range, so we can de-reference it to * read the single (char *) pointer. We don't care at the moment if the * single pointer is valid, but we have to check whether it is NULL in * order to calculate 'argc'. */ if (!*ptr_ptr) break; } if ((char *)&dest_arr[argc] > dest_end - sizeof(void *)) { *rc = 1; goto out; } /* this is safe, we've just checked that */ WRITE_PTR(&dest_arr[argc], NULL); after_ptrs_arr = (char *) &dest_arr[argc + 1]; written += (u32)(after_ptrs_arr - (char *)dest_arr); for (int i = 0; i < argc; i++) { size_t local_written = 0; WRITE_PTR(&dest_arr[i], after_ptrs_arr); internal_copy_user_str(after_ptrs_arr, user_arr[i], dest_end, &local_written, rc); if (*rc != 0) break; written += local_written; after_ptrs_arr += local_written; } out: *written_ptr = written; } int copy_str_array_from_user(void *dest, const char *const *user_arr, size_t max_size, size_t *written_ptr) { int rc; u32 faults; faults = fault_resumable_call(PAGE_FAULT_MASK, internal_copy_str_array_from_user, 5, dest, user_arr, max_size, written_ptr, &rc); if (faults) return -1; return rc; } int duplicate_user_path(char *dest, const char *user_path, size_t dest_size, size_t *written_ptr /* IN/OUT */) { int rc; size_t curr_written = 0; if (!user_path) return -EINVAL; if (*written_ptr >= dest_size) return -ENAMETOOLONG; rc = copy_str_from_user(dest + *written_ptr, user_path, dest_size - *written_ptr, &curr_written); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; *written_ptr += curr_written; return 0; } int duplicate_user_argv(char *dest, const char *const *user_argv, size_t dest_size, size_t *written_ptr /* IN/OUT */) { int rc; size_t curr_written = 0; if (*written_ptr >= dest_size) return -E2BIG; rc = copy_str_array_from_user(dest + *written_ptr, user_argv, dest_size - *written_ptr, &curr_written); if (rc < 0) return -EFAULT; if (rc > 0) return -E2BIG; *written_ptr += curr_written; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include "video_term_int.h" #include <termios.h> // system header #define NPAR 16 /* maximum number of CSI parameters */ #define TTY_ATTR_BOLD (1 << 0) #define TTY_ATTR_REVERSE (1 << 1) struct console_data; struct twfilter_ctx { struct tty *t; struct console_data *cd; char param_bytes[64]; char interm_bytes[64]; char tmpbuf[16]; bool non_default_state; u8 pbc; /* param bytes count */ u8 ibc; /* intermediate bytes count */ }; struct console_data { u16 saved_cur_row; u16 saved_cur_col; u32 attrs; u8 user_color; /* color before attrs */ u8 c_set; /* 0 = G0, 1 = G1 */ const s16 *c_sets_tables[2]; struct twfilter_ctx filter_ctx; term_filter *def_state_funcs; }; static int tty_pre_filter(struct twfilter_ctx *ctx, u8 *c); static void tty_set_state(struct twfilter_ctx *ctx, term_filter new_state); static enum term_fret tty_state_default(u8*, u8*, struct term_action*, void*); static enum term_fret tty_state_esc1(u8*, u8*, struct term_action*, void*); static enum term_fret tty_state_esc2_par0(u8*, u8*, struct term_action*, void*); static enum term_fret tty_state_esc2_par1(u8*, u8*, struct term_action*, void*); static enum term_fret tty_state_esc2_csi(u8*, u8*, struct term_action*, void*); static enum term_fret tty_state_esc2_unknown(u8*,u8*,struct term_action*,void*); extern const u8 fg_csi_to_vga[256]; extern const s16 tty_default_trans_table[256]; extern const s16 tty_gfx_trans_table[256]; <file_sep>/****************************************************************************** * * Module Name: utids - support for device IDs - HID, UID, CID, SUB, CLS * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utids") /******************************************************************************* * * FUNCTION: AcpiUtExecute_HID * * PARAMETERS: DeviceNode - Node for the device * ReturnId - Where the string HID is returned * * RETURN: Status * * DESCRIPTION: Executes the _HID control method that returns the hardware * ID of the device. The HID is either an 32-bit encoded EISAID * Integer or a String. A string is always returned. An EISAID * is converted to a string. * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtExecute_HID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PNP_DEVICE_ID *Hid; UINT32 Length; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtExecute_HID); Status = AcpiUtEvaluateObject (DeviceNode, METHOD_NAME__HID, ACPI_BTYPE_INTEGER | ACPI_BTYPE_STRING, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Get the size of the String to be returned, includes null terminator */ if (ObjDesc->Common.Type == ACPI_TYPE_INTEGER) { Length = ACPI_EISAID_STRING_SIZE; } else { Length = ObjDesc->String.Length + 1; } /* Allocate a buffer for the HID */ Hid = ACPI_ALLOCATE_ZEROED ( sizeof (ACPI_PNP_DEVICE_ID) + (ACPI_SIZE) Length); if (!Hid) { Status = AE_NO_MEMORY; goto Cleanup; } /* Area for the string starts after PNP_DEVICE_ID struct */ Hid->String = ACPI_ADD_PTR (char, Hid, sizeof (ACPI_PNP_DEVICE_ID)); /* Convert EISAID to a string or simply copy existing string */ if (ObjDesc->Common.Type == ACPI_TYPE_INTEGER) { AcpiExEisaIdToString (Hid->String, ObjDesc->Integer.Value); } else { strcpy (Hid->String, ObjDesc->String.Pointer); } Hid->Length = Length; *ReturnId = Hid; Cleanup: /* On exit, we must delete the return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtExecute_UID * * PARAMETERS: DeviceNode - Node for the device * ReturnId - Where the string UID is returned * * RETURN: Status * * DESCRIPTION: Executes the _UID control method that returns the unique * ID of the device. The UID is either a 64-bit Integer (NOT an * EISAID) or a string. Always returns a string. A 64-bit integer * is converted to a decimal string. * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtExecute_UID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PNP_DEVICE_ID *Uid; UINT32 Length; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtExecute_UID); Status = AcpiUtEvaluateObject (DeviceNode, METHOD_NAME__UID, ACPI_BTYPE_INTEGER | ACPI_BTYPE_STRING, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Get the size of the String to be returned, includes null terminator */ if (ObjDesc->Common.Type == ACPI_TYPE_INTEGER) { Length = ACPI_MAX64_DECIMAL_DIGITS + 1; } else { Length = ObjDesc->String.Length + 1; } /* Allocate a buffer for the UID */ Uid = ACPI_ALLOCATE_ZEROED ( sizeof (ACPI_PNP_DEVICE_ID) + (ACPI_SIZE) Length); if (!Uid) { Status = AE_NO_MEMORY; goto Cleanup; } /* Area for the string starts after PNP_DEVICE_ID struct */ Uid->String = ACPI_ADD_PTR (char, Uid, sizeof (ACPI_PNP_DEVICE_ID)); /* Convert an Integer to string, or just copy an existing string */ if (ObjDesc->Common.Type == ACPI_TYPE_INTEGER) { AcpiExIntegerToString (Uid->String, ObjDesc->Integer.Value); } else { strcpy (Uid->String, ObjDesc->String.Pointer); } Uid->Length = Length; *ReturnId = Uid; Cleanup: /* On exit, we must delete the return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtExecute_CID * * PARAMETERS: DeviceNode - Node for the device * ReturnCidList - Where the CID list is returned * * RETURN: Status, list of CID strings * * DESCRIPTION: Executes the _CID control method that returns one or more * compatible hardware IDs for the device. * * NOTE: Internal function, no parameter validation * * A _CID method can return either a single compatible ID or a package of * compatible IDs. Each compatible ID can be one of the following: * 1) Integer (32 bit compressed EISA ID) or * 2) String (PCI ID format, e.g. "PCI\VEN_vvvv&DEV_dddd&SUBSYS_ssssssss") * * The Integer CIDs are converted to string format by this function. * ******************************************************************************/ ACPI_STATUS AcpiUtExecute_CID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID_LIST **ReturnCidList) { ACPI_OPERAND_OBJECT **CidObjects; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PNP_DEVICE_ID_LIST *CidList; char *NextIdString; UINT32 StringAreaSize; UINT32 Length; UINT32 CidListSize; ACPI_STATUS Status; UINT32 Count; UINT32 i; ACPI_FUNCTION_TRACE (UtExecute_CID); /* Evaluate the _CID method for this device */ Status = AcpiUtEvaluateObject (DeviceNode, METHOD_NAME__CID, ACPI_BTYPE_INTEGER | ACPI_BTYPE_STRING | ACPI_BTYPE_PACKAGE, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Get the count and size of the returned _CIDs. _CID can return either * a Package of Integers/Strings or a single Integer or String. * Note: This section also validates that all CID elements are of the * correct type (Integer or String). */ if (ObjDesc->Common.Type == ACPI_TYPE_PACKAGE) { Count = ObjDesc->Package.Count; CidObjects = ObjDesc->Package.Elements; } else /* Single Integer or String CID */ { Count = 1; CidObjects = &ObjDesc; } StringAreaSize = 0; for (i = 0; i < Count; i++) { /* String lengths include null terminator */ switch (CidObjects[i]->Common.Type) { case ACPI_TYPE_INTEGER: StringAreaSize += ACPI_EISAID_STRING_SIZE; break; case ACPI_TYPE_STRING: StringAreaSize += CidObjects[i]->String.Length + 1; break; default: Status = AE_TYPE; goto Cleanup; } } /* * Now that we know the length of the CIDs, allocate return buffer: * 1) Size of the base structure + * 2) Size of the CID PNP_DEVICE_ID array + * 3) Size of the actual CID strings */ CidListSize = sizeof (ACPI_PNP_DEVICE_ID_LIST) + (Count * sizeof (ACPI_PNP_DEVICE_ID)) + StringAreaSize; CidList = ACPI_ALLOCATE_ZEROED (CidListSize); if (!CidList) { Status = AE_NO_MEMORY; goto Cleanup; } /* Area for CID strings starts after the CID PNP_DEVICE_ID array */ NextIdString = ACPI_CAST_PTR (char, CidList->Ids) + ((ACPI_SIZE) Count * sizeof (ACPI_PNP_DEVICE_ID)); /* Copy/convert the CIDs to the return buffer */ for (i = 0; i < Count; i++) { if (CidObjects[i]->Common.Type == ACPI_TYPE_INTEGER) { /* Convert the Integer (EISAID) CID to a string */ AcpiExEisaIdToString ( NextIdString, CidObjects[i]->Integer.Value); Length = ACPI_EISAID_STRING_SIZE; } else /* ACPI_TYPE_STRING */ { /* Copy the String CID from the returned object */ strcpy (NextIdString, CidObjects[i]->String.Pointer); Length = CidObjects[i]->String.Length + 1; } CidList->Ids[i].String = NextIdString; CidList->Ids[i].Length = Length; NextIdString += Length; } /* Finish the CID list */ CidList->Count = Count; CidList->ListSize = CidListSize; *ReturnCidList = CidList; Cleanup: /* On exit, we must delete the _CID return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtExecute_CLS * * PARAMETERS: DeviceNode - Node for the device * ReturnId - Where the _CLS is returned * * RETURN: Status * * DESCRIPTION: Executes the _CLS control method that returns PCI-defined * class code of the device. The _CLS value is always a package * containing PCI class information as a list of integers. * The returned string has format "BBSSPP", where: * BB = Base-class code * SS = Sub-class code * PP = Programming Interface code * ******************************************************************************/ ACPI_STATUS AcpiUtExecute_CLS ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT **ClsObjects; UINT32 Count; ACPI_PNP_DEVICE_ID *Cls; UINT32 Length; ACPI_STATUS Status; UINT8 ClassCode[3] = {0, 0, 0}; ACPI_FUNCTION_TRACE (UtExecute_CLS); Status = AcpiUtEvaluateObject (DeviceNode, METHOD_NAME__CLS, ACPI_BTYPE_PACKAGE, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Get the size of the String to be returned, includes null terminator */ Length = ACPI_PCICLS_STRING_SIZE; ClsObjects = ObjDesc->Package.Elements; Count = ObjDesc->Package.Count; if (ObjDesc->Common.Type == ACPI_TYPE_PACKAGE) { if (Count > 0 && ClsObjects[0]->Common.Type == ACPI_TYPE_INTEGER) { ClassCode[0] = (UINT8) ClsObjects[0]->Integer.Value; } if (Count > 1 && ClsObjects[1]->Common.Type == ACPI_TYPE_INTEGER) { ClassCode[1] = (UINT8) ClsObjects[1]->Integer.Value; } if (Count > 2 && ClsObjects[2]->Common.Type == ACPI_TYPE_INTEGER) { ClassCode[2] = (UINT8) ClsObjects[2]->Integer.Value; } } /* Allocate a buffer for the CLS */ Cls = ACPI_ALLOCATE_ZEROED ( sizeof (ACPI_PNP_DEVICE_ID) + (ACPI_SIZE) Length); if (!Cls) { Status = AE_NO_MEMORY; goto Cleanup; } /* Area for the string starts after PNP_DEVICE_ID struct */ Cls->String = ACPI_ADD_PTR (char, Cls, sizeof (ACPI_PNP_DEVICE_ID)); /* Simply copy existing string */ AcpiExPciClsToString (Cls->String, ClassCode); Cls->Length = Length; *ReturnId = Cls; Cleanup: /* On exit, we must delete the return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # GLOBAL VARIABLES # Reset any forced env-based CFLAGS export CFLAGS="" export FFLAGS="" export CXXFLAGS="" export CFFLAGS="" if [[ "$ARCH" == "" ]]; then export ARCH="i386" # default target arch fi # Default GCC toolchain version to use. Unfortunately, it depends on the target # architecture, because the list of available pre-built toolchains on # https://toolchains.bootlin.com depends on the architecture. if [[ "$ARCH" == "i386" ]]; then DEFAULT_GCC_TC_VERSION="8.4.0" elif [[ "$ARCH" == "x86_64" ]]; then DEFAULT_GCC_TC_VERSION="8.4.0" else echo "Architecture '$ARCH' not supported." exit 1 fi # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/.. && pwd)" # Global toolchain directory if [ -z "$TCROOT_PARENT" ]; then TCROOT_PARENT="$MAIN_DIR" fi if [ -z "$TCROOT" ]; then TCROOT="$TCROOT_PARENT/toolchain2" fi TC="$TCROOT" # Constants BUILD_ARCH="x86_64" # the only arch accepted for the build machine # Arch-variables HOST_ARCH="`uname -m`" if [[ "$HOST_ARCH" == "x86_64" ]]; then : # Great, that's what we expect: do nothing elif [[ "$HOST_ARCH" == "amd64" ]]; then # An alias for x86_64: fix our variable HOST_ARCH="x86_64" elif [[ "$HOST_ARCH" == "i686" ]]; then # Special case, not "officially" supported. # We need to set HOST_ARCH to "i386", to match the convention # used by ARCH and ld. HOST_ARCH="i386" fi # ARCH and ARCH_* variables are all about the TARGET architecture if [ -z "$GCC_TC_VER" ]; then if [ -f $TC/.gcc_tc_ver_$ARCH ]; then GCC_TC_VER=$(cat $TC/.gcc_tc_ver_$ARCH) else if [ -f $TC/.gcc_tc_ver ]; then # TODO: drop this once we upgrade to toolchain3 if [[ "$ARCH" == "i386" ]]; then # Small hack to support older toolchains GCC_TC_VER=$(cat $TC/.gcc_tc_ver) fi # Upgrade the toolchain to the latest format if [[ "$RUNNING_IN_CI" != "1" ]]; then # Keep the old .gcc_tc_ver file to support building older commits cp $TC/.gcc_tc_ver $TC/.gcc_tc_ver_i386 fi fi fi fi if [ -z "$GCC_TC_VER" ]; then GCC_TC_VER="$DEFAULT_GCC_TC_VERSION" fi if [[ "$ARCH" == "i386" ]]; then ARCH_SHORT="x86" ARCH_FAMILY="generic_x86" ARCH_ELF_NAME="elf32-i386" ARCH_LD_OUTPUT="elf_i386" ARCH_EFI="ia32" ARCH_GCC_TC="i686" ARCH_GCC_FLAGS="-m32 -march=$ARCH_GCC_TC" ARCH_GCC_TC_CODENAME="x86-i686" if [[ "$ARCH_GCC_TC_VER" == "" ]] && [[ "$HOST_ARCH" != "aarch64" ]]; then if [ "$GCC_TC_VER" = "6.4.0" ]; then ARCH_GCC_TC_VER="stable-2018.02-2" elif [ "$GCC_TC_VER" = "7.3.0" ]; then ARCH_GCC_TC_VER="stable-2018.11-1" elif [ "$GCC_TC_VER" = "8.4.0" ]; then ARCH_GCC_TC_VER="stable-2020.02-2" elif [ "$GCC_TC_VER" = "9.3.0" ]; then ARCH_GCC_TC_VER="stable-2020.08-1" elif [ "$GCC_TC_VER" = "10.3.0" ]; then ARCH_GCC_TC_VER="stable-2021.11-1" else echo "ERROR: unknown value of ARCH_GCC_TC_VER for GCC $GCC_TC_VER" exit 1 fi fi elif [[ "$ARCH" == "x86_64" ]]; then ARCH_SHORT="x86_64" ARCH_FAMILY="generic_x86" ARCH_ELF_NAME="elf64-x86-64" ARCH_LD_OUTPUT="elf_x86_64" ARCH_EFI="x86_64" ARCH_GCC_TC="x86_64" ARCH_GCC_FLAGS="-m64" ARCH_GCC_TC_CODENAME="x86-64-core-i7" if [[ "$ARCH_GCC_TC_VER" == "" ]] && [[ "$HOST_ARCH" != "aarch64" ]]; then if [ "$GCC_TC_VER" = "6.4.0" ]; then ARCH_GCC_TC_VER="stable-2018.02-2" elif [ "$GCC_TC_VER" = "7.3.0" ]; then ARCH_GCC_TC_VER="stable-2018.11-1" elif [ "$GCC_TC_VER" = "8.4.0" ]; then ARCH_GCC_TC_VER="stable-2020.02-2" elif [ "$GCC_TC_VER" = "9.3.0" ]; then ARCH_GCC_TC_VER="stable-2020.08-1" elif [ "$GCC_TC_VER" = "10.3.0" ]; then ARCH_GCC_TC_VER="stable-2021.11-1" else echo "ERROR: unknown value of ARCH_GCC_TC_VER for GCC $GCC_TC_VER" exit 1 fi fi else echo "Architecture '$ARCH' not supported." exit 1 fi # # Support for AARCH64 as build machine (limited) # if [[ "$HOST_ARCH" == "aarch64" ]]; then GCC_TC_VER="9.4.0" ARCH_GCC_TC_VER="" fi if ! [ -f $TC/.gcc_tc_ver_$ARCH ]; then mkdir -p $TC echo -n $GCC_TC_VER > $TC/.gcc_tc_ver_$ARCH else saved=$(cat $TC/.gcc_tc_ver_$ARCH) v=$GCC_TC_VER if ! [ "$GCC_TC_VER" = "$saved" ]; then echo "WARNING: GCC_TC_VER ($v) does not match with saved one ($saved)" echo "WARNING: This is NOT a supported scenario. Please delete:" echo " $TC/$ARCH" echo " $TC/.gcc_tc_ver_$ARCH" echo "And run this script again to use the new toolchain." exit 1 fi fi GCC_TC_VER_=$(echo $GCC_TC_VER | sed -E 's/[.]/_/g') GCC_NAME_PFX="gcc_${GCC_TC_VER_}_${ARCH}" MUSL_INSTALL=$TC/$ARCH/musl/install echo echo "ARCH=$ARCH" echo "HOST_ARCH=$HOST_ARCH" echo "GCC_TC_VER=$GCC_TC_VER" echo "ARCH_GCC_TC_VER=$ARCH_GCC_TC_VER" echo function save_cc_vars { if [[ "$HOST_ARCH" == "$ARCH" ]]; then if [ -z "$AR" ]; then export AR="ar" fi if [ -z "$NM" ]; then export NM="nm" fi if [ -z "$RANLIB" ]; then export RANLIB="ranlib" fi fi saved_CC=$CC saved_CXX=$CXX saved_AR=$AR saved_NM=$NM saved_RANLIB=$RANLIB } function set_cc_vars_to_tc { if [[ "$HOST_ARCH" != "$ARCH" ]]; then # Default case export CC="${ARCH_GCC_TC}-linux-gcc" export CXX="${ARCH_GCC_TC}-linux-g++" export AR="${ARCH_GCC_TC}-linux-ar" export NM="${ARCH_GCC_TC}-linux-nm" export RANLIB="${ARCH_GCC_TC}-linux-ranlib" fi } function reset_cc_vars_to_null { export CC="" export CXX="" export AR="" export NM="" export RANLIB="" } function reset_cc_vars { export CC=$saved_CC export CXX=$saved_CXX export AR=$saved_AR export NM=$saved_NM export RANLIB=$saved_RANLIB } all_funcs_list=() # Source files to include source $MAIN_DIR/scripts/bash_includes/script_utils function arch_checks { if [[ "$HOST_ARCH" != *"$BUILD_ARCH"* ]]; then echo "WARNING: Tilck is designed to be built only on $BUILD_ARCH host " echo "machines no matter which target architecture has been chosen. " echo "Reason: the build system uses a toolchain pre-compiled for " echo "$BUILD_ARCH hosts." echo echo "Detected HOST_ARCH (uname -m): $HOST_ARCH" echo echo "However, there is *unofficial* support for the following" echo "alternative scenarios: " echo echo " 1. HOST_ARCH == ARCH" echo " 2. HOST_ARCH == aarch64" echo echo "Scenario 1. requires the environment variables USE_SYSCC, CC and " echo "CXX to be set correctly. Scenario 2 is will download and build" echo "a whole cross-gcc toolchain for the selected ARCH". echo if [[ "$HOST_ARCH" == "$ARCH" ]]; then if [[ "$USE_SYSCC" != "" && "$USE_SYSCC" != 0 ]]; then echo "In this case, HOST_ARCH == ARCH and USE_SYSCC is set." echo "The script can continue, but WARNING: this scenario is not " echo "tested as often as the main one (building on $BUILD_ARCH)." echo "" echo -n "Proceed [Y/n] ? " read ans if [[ "$ans" == "" || "$ans" == "y" || "$ans" == "Y" ]]; then echo "OK." else echo "Aborted." exit 1 fi else echo "In this case USE_SYSCC, CC and CXX are NOT set." echo "Unable to continue." exit 1 fi elif [[ "$HOST_ARCH" == "aarch64" ]]; then echo "This scenario is absolutely EXPERIMENTAL and will require" echo "the download and the build of a custom cross GCC toolchain" echo "" echo -n "Proceed [Y/n] ? " read ans if [[ "$ans" == "" || "$ans" == "y" || "$ans" == "Y" ]]; then echo "OK." else echo "Aborted." exit 1 fi else echo "In this case, HOST_ARCH ($HOST_ARCH) != ARCH ($ARCH)" echo "Unable to continue." exit 1 fi fi } function compiler_checks { if [[ "$USE_SYSCC" != "" && "$USE_SYSCC" != 0 ]]; then if [[ "$CC" == "" || "$CXX" == "" ]]; then echo "WARNING: CC and CXX should both be set when USE_SYSCC=1." echo -n "Do you want just to use gcc and g++? [Y/n] " read ans if [[ "$ans" == "" || "$ans" == "y" || "$ans" == "Y" ]]; then echo "----------------------------------------------------------" echo "Setting:" echo " CC=gcc" echo " CXX=g++" echo "" export CC="gcc" export CXX="g++" else echo "Aborted." exit 1 fi fi local cc_compiler="`$CC --version | cut -d ' ' -f 1 | head -1`" local cxx_compiler="`$CXX --version | cut -d ' ' -f 1 | head -1`" if [ -z "$cc_compiler" ]; then echo "ERROR: $CC compiler NOT FOUND" exit 1 fi if [ -z "$cxx_compiler" ]; then echo "ERROR: $CXX compiler NOT FOUND" exit 1 fi if [ "$cc_compiler" != "gcc" ]; then echo "ERROR: USE_SYSCC=1 is NOT supported with compilers != GCC." exit 1 fi fi } function print_func { local fname="$1" local has_printf="$2" local is_default="$3" local def="" if [[ $is_default = 1 ]]; then def=" (*)" fi if [[ $has_printf = 1 ]]; then local attrs="" local extra_info="" local installed_func="${fname}_installed_status" if [[ "$(type -t $installed_func)" == 'function' ]]; then local status="$(eval $installed_func)" if [[ -n "$status" ]]; then if [[ "$status" =~ installed* ]]; then if ! [[ "$status" = "installed" ]]; then extra_info=$(echo "$status" | cut -d ' ' -f 2-) status="installed" fi fi status=$(printf "%-9s" "$status") fi case "$status" in installed*) status="$GREEN${status}$RATTRS" ;; error*) status="$RED${status}$RATTRS" ;; skipped*) status="$YELLOW${status}$RATTRS" ;; esac if [[ -n "$status" ]]; then attrs="$attrs[ $status ]" fi if [[ -n "$extra_info" ]]; then attrs="$attrs[ $extra_info ]" fi fi printf "%-35s $attrs\n" "$fname$def" else echo " - $1 $def" fi } function show_help { echo "" echo "Syntax:" echo " $0 [-n] run default functions" echo " $0 -s func1 [func2 [func3 [...]]] run specific functions" echo "" echo " -n Do not check nor install system packages (advanced)" echo " Even if many packages are downloaded & built by this" echo " script without touching the system, some packages are" echo " required to be installed in the system. For example: " echo " wget, git, make, binutils, bzip2, rpmextract and " echo " others similar. When -n is NOT passed, the script " echo " first tries to detect the current Linux distribution " echo " and then it checks if all the required packages are " echo " already installed. In case some packages need to be " echo " installed, this script will show a list and run: " echo " sudo <package manager> install [pkg1 [pkg2 ...]]" echo " In case the user does not want this script to install " echo " the necessary packages he/she could just interrupt " echo " this script with Ctrl+C, without affecting the " echo " system." echo echo " --clean Remove everything from the toolchain, except the cache" echo "" echo "Functions supported by this script (with -s):" echo "" local has_printf=0 local all_def_funcs=" ${default_funcs[*]} " if printf "" &> /dev/null; then has_printf=1 fi for x in ${default_funcs[@]}; do print_func "$x" $has_printf 1 done for x in ${all_funcs_list[@]}; do if [[ "$all_def_funcs" =~ " ${x} " ]]; then continue 2 fi # Skip the config_* functions, in order to print them last if [[ "$x" =~ config_* ]]; then continue 2 fi print_func "$x" $has_printf 0 done # Now print all the config_* funcs for x in ${all_funcs_list[@]}; do if [[ "$x" =~ config_* ]]; then print_func "$x" $has_printf 0 fi done echo "" echo -e "(*) Functions ran by default\n" } function show_error_no_func { echo "ERROR: The function '$1' does not exist. Re-run with --help." } function execute_func { if [ -n "$(type -t $1)" ] && [ "$(type -t $1)" = function ]; then echo "[build_toolchain] Executing single function '$1'" $1 echo "[build_toolchain] Executing single function: DONE" return 0 else return 1 # No such function fi } function check_func { local func="$1" for x in ${all_funcs_list[@]}; do if [[ "$x" == "$func" || "$x" == "build_$func" || "$x" == "download_$func" ]] then return 0 fi done return 1 # Function not found } function perform_full_clean { echo "*** TOOLCHAIN CLEAN ***" if ! [ -d "$TC" ]; then exit 0 fi cd "$TC" for x in *; do if [[ "$x" != "cache" ]]; then echo "Deleting '$x'..." rm -rf "$x" fi done rm -f .gcc_tc_ver_* echo "DONE" exit 0 } ########################################################## # # MAIN # ########################################################## function main { if [[ "$1" == "--clean" ]]; then perform_full_clean fi default_funcs=() if [[ "$HOST_ARCH" == "$BUILD_ARCH" ]]; then # Default case: we're building on a x86-64 machine default_funcs+=(download_gcc_toolchain) elif [[ "$HOST_ARCH" == "$ARCH" ]]; then # We don't have our pre-build gcc-musl toolchains for HOST_ARCH, therefore # we *must* build also libmusl, in order to link with musl programs # compiled with the system compiler. default_funcs+=(build_libmusl) elif [[ "$HOST_ARCH" == "aarch64" ]]; then default_funcs+=(custom_gcc_cross_tc) fi if [[ "$HOST_ARCH" == "x86_64" ]]; then default_funcs+=(download_cmake) fi default_funcs+=(build_gnuefi) default_funcs+=(build_mtools) default_funcs+=(build_zlib) if [ -z "$NO_BUSYBOX" ]; then default_funcs+=(build_busybox) fi if [[ "$1" == "--help" || "$1" == "-h" ]]; then show_help exit 0 fi # Compiler-related checks compiler_checks # Arch-related checks arch_checks # Save the current values of CC, CXX and related save_cc_vars # Exit on the first failure set -e export PATH="$MAIN_DIR/scripts/build_scripts:$PATH" if [[ "$HOST_ARCH" != "$ARCH" ]]; then local ha=$TC/host_${HOST_ARCH} GCC_TOOLCHAIN=$ha/${GCC_NAME_PFX}_musl/bin # Default cross-compiler GCC_TOOLCHAIN_GLIBC=$ha/${GCC_NAME_PFX}_glibc/bin # NOTE: not in $PATH! unset ha # NOTE: GCC's musl pre-built toolchain overrides build_scripts/* in PATH. # This means that, when HOST_ARCH == BUILD_ARCH, i686-linux-gcc will use # its version and NOT the wrapper script in build_scripts which simulates # its behavior using -m32 and -specs. export PATH="$GCC_TOOLCHAIN:$PATH" fi if [ "$1" == "-s" ] && ! [ -d $TC/$ARCH ]; then echo echo "ERROR: directory $TC/$ARCH not found." echo echo "It is necessary to run this script *without* options first to " echo "download and build a minimum toolchain. Then, it will be possible" echo "to download and build the extra packages." echo echo "For more info: " echo " https://github.com/vvaltchev/tilck/blob/master/docs/building.md" exit 1 fi mkdir -p $TC mkdir -p $TC/cache mkdir -p $TC/noarch mkdir -p $TC/i386 mkdir -p $TC/x86_64 if [[ "$HOST_ARCH" == "aarch64" ]]; then mkdir -p $TC/host_aarch64 else mkdir -p $TC/host_i386 mkdir -p $TC/host_x86_64 fi cd $TC if ! [ -L host ]; then ln -s host_${HOST_ARCH} host fi # Set the CMAKE variable in order to single functions to be able to use it if [ -f $TC/host_$HOST_ARCH/cmake/bin/cmake ]; then CMAKE=$TC/host_$HOST_ARCH/cmake/bin/cmake else CMAKE=cmake fi if [ "$1" == "-s" ]; then if [ $# -lt 2 ]; then echo "Expected the name of the function to call after the $1 option" fi shift # Drop the first argument, $1 for func in "$@"; do if ! check_func "$func"; then show_error_no_func "$func" exit 1 fi if ! execute_func $func; then if ! execute_func "build_$func"; then if ! execute_func "download_$func"; then show_error_no_func "$func" exit 1 fi fi fi done exit 0 fi # Single-option parsing if [ "$1" == "-n" ] || [ "$1" == "--skip-install-pkgs" ]; then local skip_install=1 fi # Do the actual job if [ -z "$skip_install" ]; then install_packages else echo "*** SKIPPING installation of packages" fi echo echo "*** Building the custom toolchain ***" echo for x in ${default_funcs[@]}; do $x done echo echo "*** Building custom toolchain COMPLETED ***" echo } ########################################################## # Entry point: load package funcs and run main() ########################################################## for x in $MAIN_DIR/scripts/tc/pkgs/*; do source $x done if command -v sort &> /dev/null 2>&1; then IFS=$'\n' all_funcs_list=($(sort <<<"${all_funcs_list[*]}")) unset IFS fi main "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "realmode_call.h" #include "mm.h" /* * Struct defines taken from: * * VESA BIOS EXTENSION (VBE) * Core Functions * Standard * * Version: 3.0 * Date: September 16, 1998 */ struct VbeInfoBlock { char VbeSignature[4]; u16 VbeVersion; struct VbeFarPtr OemStringPtr; u8 Capabilities[4]; struct VbeFarPtr VideoModePtr; u16 TotalMemory; /* in number of 64KB blocks */ /* VBE 2.0+ */ u16 OemSoftwareRev; u32 OemVendorNamePtr; u32 OemProductNamePtr; u32 OemProductRevPtr; u8 reserved[222]; u8 OemData[256]; } PACKED; struct ModeInfoBlock { u16 ModeAttributes; u8 WinAAttributes; u8 WinBAttributes; u16 WinGranularity; u16 WinSize; u16 WinASegment; u16 WinBSegment; struct VbeFarPtr WinFuncPtr; u16 BytesPerScanLine; /* VBE 1.2+ */ u16 XResolution; u16 YResolution; u8 XCharSize; u8 YCharSize; u8 NumberOfPlanes; u8 BitsPerPixel; u8 NumberOfBanks; u8 MemoryModel; u8 BankSize; u8 NumberOfImagePages; u8 Reserved0; /* Direct Color fields (required for direct/6 and YUV/7 memory models) */ u8 RedMaskSize, RedFieldPosition; u8 GreenMaskSize, GreenFieldPosition; u8 BlueMaskSize, BlueFieldPosition; u8 RsvdMaskSize, RsvdFieldPosition; u8 DirectColorModeInfo; /* VBE 2.0+ */ u32 PhysBasePtr; u32 Reserved1; u16 Reserved2; /* VBE 3.0+ */ u16 LinBytesPerScanLine; } PACKED; /* * NOTE: the VGA standard modes (0x00 .. 0x13) are reliable, BUT the old * VESA 1.2 modes are NOT. Therefore, for the typical VGA text mode, we can just * hard-code it, while for the graphical VESA modes, we cannot (we must query * the BIOS for the available modes). */ #define VGA_COLOR_TEXT_MODE_80x25 (0x03) #define VBE_MODE_ATTRS_SUPPORTED (1 << 0) #define VBE_MODE_ATTRS_TTY_OUTPUT (1 << 2) #define VBE_MODE_ATTRS_COLOR_MODE (1 << 3) #define VBE_MODE_ATTRS_GFX_MODE (1 << 4) #define VBE_MODE_ATTRS_VGA_COMPAT_WINDOWED_MODE_AVAIL (1 << 6) #define VBE_MODE_ATTRS_LINEAR_FB (1 << 7) #define VBE_SET_MODE_FLAG_USE_LINEAR_FB (1 << 14) #define VB_MEM_MODEL_TEXT_MODE (0x0) #define VB_MEM_MODEL_PACKED_PIXEL (0x4) #define VB_MEM_MODEL_DIRECT_COLOR (0x6) void vga_set_video_mode(u8 mode); bool vbe_get_info_block(struct VbeInfoBlock *vb); bool vbe_get_mode_info(u16 mode, struct ModeInfoBlock *mi); bool vbe_set_video_mode(u16 mode); bool vbe_get_current_mode(u16 *mode); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #if defined(__GNUC__) && (__GNUC__ >= 12) /* * In the following tricky macros, we store the address of a labels in our * stack using the GCC extension &&label. On newer compilers this triggers * the dangling-pointer warning, because the compiler is not able to prove * that is safe to do so (false positive). * * Therefore, we're suppressing this warning for all the files that include * this header. */ #pragma GCC diagnostic ignored "-Wdangling-pointer" #endif #ifndef STACK_VAR #define STACK_VAR stack #endif #ifndef STACK_SIZE_VAR #define STACK_SIZE_VAR stack_size #endif #ifndef NO_REC_INCLUDED /* Make sure we define this structures only once */ struct explicit_stack_elem1 { void *ret_addr, *arg1; }; struct explicit_stack_elem2 { void *ret_addr, *arg1, *arg2; }; #define NO_REC_INCLUDED #endif #define NOREC_LOOP_BEGIN while (STACK_SIZE_VAR) { #define NOREC_LOOP_END loop_end:; } #define LOAD_ARG_FROM_STACK(n, t) \ ((t)(ulong)STACK_VAR[STACK_SIZE_VAR-1].arg##n) #define DECLARE_SHADOW_STACK(size, nargs) \ struct explicit_stack_elem##nargs STACK_VAR[size]; \ int STACK_SIZE_VAR; /* * Init our stack. * * NOTE: it's mandatory to zero it because HANDLE_SIMULATED_RETURN() * relies on that. It checks `ret_addr` at position `stack_size` expecting * to find NULL or a valid value. Each time a "simulated call" occurrs * during the first call-chain (= before any return) the stack_size moves * forward, but the last written element is always stack[stack_size-1], * therefore stack[stack_size] is always dirty. * * The whole reason for that is that SIMULATE_RETURN_NULL() decrements * stack_size: HANDLE_SIMULATED_RETURN() has no other choice than reading * "beyond" stack's limit by 1 element in order to jump to the return addr * left by the last SIMULATE_CALL(), which has now been just dropped * "off-stack" by HANDLE_SIMULATED_RETURN(). Of course, there's always the * case where no such call existed. That's why we zero the stack and * HANDLE_SIMULATED_RETURN() checks if the address is != NULL before jumping. */ #define INIT_SHADOW_STACK() \ do { \ STACK_SIZE_VAR = 0; \ bzero(STACK_VAR, sizeof(STACK_VAR)); \ } while (0) #define CREATE_SHADOW_STACK(size, nargs) \ DECLARE_SHADOW_STACK(size, nargs) \ INIT_SHADOW_STACK() #define SIMULATE_RETURN_NULL() \ { \ STACK_SIZE_VAR--; \ ASSERT(STACK_VAR[STACK_SIZE_VAR].ret_addr || !STACK_SIZE_VAR); \ continue; \ } #define SIMULATE_YIELD(val) \ { \ STACK_VAR[STACK_SIZE_VAR].ret_addr = \ &&CONCAT(after_, __LINE__); \ return val; \ CONCAT(after_, __LINE__):; \ } #define HANDLE_SIMULATED_RETURN() \ { \ void *addr = STACK_VAR[STACK_SIZE_VAR].ret_addr; \ if (addr != NULL) \ goto *addr; \ } #define SIMULATE_CALL1(a1) \ { \ VERIFY(STACK_SIZE_VAR < (int)ARRAY_SIZE(STACK_VAR)); \ STACK_VAR[STACK_SIZE_VAR++] = (typeof(STACK_VAR[0])) { \ &&CONCAT(after_, __LINE__), \ TO_PTR(a1) \ }; \ STACK_VAR[STACK_SIZE_VAR].ret_addr = NULL; \ goto loop_end; \ CONCAT(after_, __LINE__):; \ } #define SIMULATE_CALL2(a1, a2) \ { \ VERIFY(STACK_SIZE_VAR < (int)ARRAY_SIZE(STACK_VAR)); \ STACK_VAR[STACK_SIZE_VAR++] = (typeof(STACK_VAR[0])) { \ &&CONCAT(after_, __LINE__), \ TO_PTR(a1), \ TO_PTR(a2) \ }; \ STACK_VAR[STACK_SIZE_VAR].ret_addr = NULL; \ goto loop_end; \ CONCAT(after_, __LINE__):; \ } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/paging.h> /* * Special selftest that cannot be run by the system test runner. * It has to be run manually. */ void selftest_panic(void) { printk("[panic selftest] I'll panic now\n"); panic("test panic [str: '%s'][num: %d]", "test string", -123); } REGISTER_SELF_TEST(panic, se_manual, &selftest_panic) void selftest_panic2(void) { printk("[panic selftest] I'll panic with bad pointers\n"); panic("test panic [str: '%s'][num: %d]", (char *)1234, -123); } REGISTER_SELF_TEST(panic2, se_manual, &selftest_panic2) /* This works as expected when the KERNEL_STACK_ISOLATION is enabled */ void selftest_so1(void) { char buf[16]; /* * Hack needed to avoid the compiler detecting that we're accessing the * array out-of-bounds, which is generally a terrible bug. But here we're * looking exactly for this. */ char *volatile ptr = buf; printk("Causing intentionally a stack overflow: expect panic\n"); memset(ptr, 'x', KERNEL_STACK_SIZE); } REGISTER_SELF_TEST(so1, se_manual, &selftest_so1) /* This works as expected when the KERNEL_STACK_ISOLATION is enabled */ void selftest_so2(void) { char buf[16]; /* * Hack needed to avoid the compiler detecting that we're accessing the * array below bounds, which is generally a terrible bug. But here we're * looking exactly for this. */ char *volatile ptr = buf; printk("Causing intentionally a stack underflow: expect panic\n"); memset(ptr - KERNEL_STACK_SIZE, 'y', KERNEL_STACK_SIZE); } REGISTER_SELF_TEST(so2, se_manual, &selftest_so2) static void NO_INLINE do_cause_double_fault(void) { char buf[KERNEL_STACK_SIZE]; memset(buf, 'z', KERNEL_STACK_SIZE); } void selftest_so3(void) { printk("Causing intentionally a double fault: expect panic\n"); do_cause_double_fault(); } REGISTER_SELF_TEST(so3, se_manual, &selftest_so3) <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) function (show_missing_use_syscc_error) set(msg "") string(CONCAT msg "In order to build Tilck on this host architecture " "the env variables USE_SYSCC, CC and CXX *must be* set. " "WARNING: this scenario is *not* supported in an official" " way, even if it should work.") message(FATAL_ERROR "\n${msg}") endfunction() function (show_same_arch_build_warning) set(msg "") string(CONCAT msg "Building with HOST_ARCH == ARCH and USE_SYSCC=1 is not" " supported in an official way") message(WARNING "\n${msg}") endfunction() function (show_no_musl_syscc_error) set(msg "") string(CONCAT msg "In order to build with USE_SYSCC=1 libmusl *must be* " "in the toolchain. " "Run: ${BTC_SCRIPT_REL} -s build_libmusl first.") message(FATAL_ERROR "\n${msg}") endfunction() function (show_wconv_warning) set(msg "") string(CONCAT msg "WCONV (-Wconversion) is supported ONLY when the " "kernel is built with Clang: " "(CC=clang and CMAKE_ARGS='-DKERNEL_SYSCC=1')") message(WARNING "${msg}") endfunction() function (show_clang_and_syscc_error) set(msg "") string(CONCAT msg "USE_SYSCC=1 is not supported with Clang. " "Please use GCC. Note[1]: it is possible to build just " "the kernel with Clang by setting CC=clang the CMake " "variable KERNEL_SYSCC=1. However, the i686 gcc " "toolchain will still be used for assembly files and " "other targets. Note[2]: if you're using " "./scripts/cmake_run, you can set CMake variables by " "setting the CMAKE_ARGS environment variable this way: " "\nCMAKE_ARGS='-DCMAKE_VAR1=0 -DVAR2=blabla' " "./scripts/cmake_run") message(FATAL_ERROR "${msg}") endfunction() macro (show_missing_lcov_error) message(FATAL_ERROR "TEST_GCOV/KERNEL_GCOV set but no lcov-${LCOV_VER} in " "toolchain. Run ${BTC_SCRIPT_REL} -s build_lcov first.") endmacro() macro (no_googletest_lib_fake_error_target) add_custom_target( gtests COMMAND echo COMMAND echo "==== ERROR: No googletest in toolchain ====" COMMAND echo COMMAND echo "Instructions:" COMMAND echo " - Run ${BTC_SCRIPT_REL} -s ${GTEST_BTC_COMMAND}" COMMAND echo " - ./scripts/cmake_run ${CMAKE_BINARY_DIR}" COMMAND echo " - Run this command again" COMMAND echo ) endmacro() function (show_no_ms_abi_support_warning relPath) set(msg "") string(CONCAT msg "Unable to build `${relPath}`: " "the system compiler does not support MS_ABI. " "If you need to use EFI boot on x86_64 machines " "please use a non-ancient GCC compiler.") message(WARNING "\n${msg}\n") endfunction() function (show_arch_gtests_require_same_target_family_error) set(msg "") string(CONCAT msg "Building the arch gtests requires the host to have " "the same arch of the target, or be in the same family. " "ARCH_FAMILY: ${ARCH_FAMILY} vs " "HOST_ARCH_FAMILY: ${HOST_ARCH_FAMILY}") message(FATAL_ERROR "\n${msg}\n") endfunction() <file_sep>/****************************************************************************** * * Module Name: psargs - Parse AML opcode arguments * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acnamesp.h" #include "acdispat.h" #include "acconvert.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psargs") /* Local prototypes */ static UINT32 AcpiPsGetNextPackageLength ( ACPI_PARSE_STATE *ParserState); static ACPI_PARSE_OBJECT * AcpiPsGetNextField ( ACPI_PARSE_STATE *ParserState); /******************************************************************************* * * FUNCTION: AcpiPsGetNextPackageLength * * PARAMETERS: ParserState - Current parser state object * * RETURN: Decoded package length. On completion, the AML pointer points * past the length byte or bytes. * * DESCRIPTION: Decode and return a package length field. * Note: Largest package length is 28 bits, from ACPI specification * ******************************************************************************/ static UINT32 AcpiPsGetNextPackageLength ( ACPI_PARSE_STATE *ParserState) { UINT8 *Aml = ParserState->Aml; UINT32 PackageLength = 0; UINT32 ByteCount; UINT8 ByteZeroMask = 0x3F; /* Default [0:5] */ ACPI_FUNCTION_TRACE (PsGetNextPackageLength); /* * Byte 0 bits [6:7] contain the number of additional bytes * used to encode the package length, either 0,1,2, or 3 */ ByteCount = (Aml[0] >> 6); ParserState->Aml += ((ACPI_SIZE) ByteCount + 1); /* Get bytes 3, 2, 1 as needed */ while (ByteCount) { /* * Final bit positions for the package length bytes: * Byte3->[20:27] * Byte2->[12:19] * Byte1->[04:11] * Byte0->[00:03] */ PackageLength |= (Aml[ByteCount] << ((ByteCount << 3) - 4)); ByteZeroMask = 0x0F; /* Use bits [0:3] of byte 0 */ ByteCount--; } /* Byte 0 is a special case, either bits [0:3] or [0:5] are used */ PackageLength |= (Aml[0] & ByteZeroMask); return_UINT32 (PackageLength); } /******************************************************************************* * * FUNCTION: AcpiPsGetNextPackageEnd * * PARAMETERS: ParserState - Current parser state object * * RETURN: Pointer to end-of-package +1 * * DESCRIPTION: Get next package length and return a pointer past the end of * the package. Consumes the package length field * ******************************************************************************/ UINT8 * AcpiPsGetNextPackageEnd ( ACPI_PARSE_STATE *ParserState) { UINT8 *Start = ParserState->Aml; UINT32 PackageLength; ACPI_FUNCTION_TRACE (PsGetNextPackageEnd); /* Function below updates ParserState->Aml */ PackageLength = AcpiPsGetNextPackageLength (ParserState); return_PTR (Start + PackageLength); /* end of package */ } /******************************************************************************* * * FUNCTION: AcpiPsGetNextNamestring * * PARAMETERS: ParserState - Current parser state object * * RETURN: Pointer to the start of the name string (pointer points into * the AML. * * DESCRIPTION: Get next raw namestring within the AML stream. Handles all name * prefix characters. Set parser state to point past the string. * (Name is consumed from the AML.) * ******************************************************************************/ char * AcpiPsGetNextNamestring ( ACPI_PARSE_STATE *ParserState) { UINT8 *Start = ParserState->Aml; UINT8 *End = ParserState->Aml; ACPI_FUNCTION_TRACE (PsGetNextNamestring); /* Point past any namestring prefix characters (backslash or carat) */ while (ACPI_IS_ROOT_PREFIX (*End) || ACPI_IS_PARENT_PREFIX (*End)) { End++; } /* Decode the path prefix character */ switch (*End) { case 0: /* NullName */ if (End == Start) { Start = NULL; } End++; break; case AML_DUAL_NAME_PREFIX: /* Two name segments */ End += 1 + (2 * ACPI_NAMESEG_SIZE); break; case AML_MULTI_NAME_PREFIX: /* Multiple name segments, 4 chars each, count in next byte */ End += 2 + (*(End + 1) * ACPI_NAMESEG_SIZE); break; default: /* Single name segment */ End += ACPI_NAMESEG_SIZE; break; } ParserState->Aml = End; return_PTR ((char *) Start); } /******************************************************************************* * * FUNCTION: AcpiPsGetNextNamepath * * PARAMETERS: ParserState - Current parser state object * Arg - Where the namepath will be stored * ArgCount - If the namepath points to a control method * the method's argument is returned here. * PossibleMethodCall - Whether the namepath can possibly be the * start of a method call * * RETURN: Status * * DESCRIPTION: Get next name (if method call, return # of required args). * Names are looked up in the internal namespace to determine * if the name represents a control method. If a method * is found, the number of arguments to the method is returned. * This information is critical for parsing to continue correctly. * ******************************************************************************/ ACPI_STATUS AcpiPsGetNextNamepath ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_STATE *ParserState, ACPI_PARSE_OBJECT *Arg, BOOLEAN PossibleMethodCall) { ACPI_STATUS Status; char *Path; ACPI_PARSE_OBJECT *NameOp; ACPI_OPERAND_OBJECT *MethodDesc; ACPI_NAMESPACE_NODE *Node; UINT8 *Start = ParserState->Aml; ACPI_FUNCTION_TRACE (PsGetNextNamepath); Path = AcpiPsGetNextNamestring (ParserState); AcpiPsInitOp (Arg, AML_INT_NAMEPATH_OP); /* Null path case is allowed, just exit */ if (!Path) { Arg->Common.Value.Name = Path; return_ACPI_STATUS (AE_OK); } /* * Lookup the name in the internal namespace, starting with the current * scope. We don't want to add anything new to the namespace here, * however, so we use MODE_EXECUTE. * Allow searching of the parent tree, but don't open a new scope - * we just want to lookup the object (must be mode EXECUTE to perform * the upsearch) */ Status = AcpiNsLookup (WalkState->ScopeInfo, Path, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, NULL, &Node); /* * If this name is a control method invocation, we must * setup the method call */ if (ACPI_SUCCESS (Status) && PossibleMethodCall && (Node->Type == ACPI_TYPE_METHOD)) { if ((GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) == ARGP_SUPERNAME) || (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) == ARGP_TARGET)) { /* * AcpiPsGetNextNamestring has increased the AML pointer past * the method invocation namestring, so we need to restore the * saved AML pointer back to the original method invocation * namestring. */ WalkState->ParserState.Aml = Start; WalkState->ArgCount = 1; AcpiPsInitOp (Arg, AML_INT_METHODCALL_OP); } /* This name is actually a control method invocation */ MethodDesc = AcpiNsGetAttachedObject (Node); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Control Method invocation %4.4s - %p Desc %p Path=%p\n", Node->Name.Ascii, Node, MethodDesc, Path)); NameOp = AcpiPsAllocOp (AML_INT_NAMEPATH_OP, Start); if (!NameOp) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Change Arg into a METHOD CALL and attach name to it */ AcpiPsInitOp (Arg, AML_INT_METHODCALL_OP); NameOp->Common.Value.Name = Path; /* Point METHODCALL/NAME to the METHOD Node */ NameOp->Common.Node = Node; AcpiPsAppendArg (Arg, NameOp); if (!MethodDesc) { ACPI_ERROR ((AE_INFO, "Control Method %p has no attached object", Node)); return_ACPI_STATUS (AE_AML_INTERNAL); } ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Control Method - %p Args %X\n", Node, MethodDesc->Method.ParamCount)); /* Get the number of arguments to expect */ WalkState->ArgCount = MethodDesc->Method.ParamCount; return_ACPI_STATUS (AE_OK); } /* * Special handling if the name was not found during the lookup - * some NotFound cases are allowed */ if (Status == AE_NOT_FOUND) { /* 1) NotFound is ok during load pass 1/2 (allow forward references) */ if ((WalkState->ParseFlags & ACPI_PARSE_MODE_MASK) != ACPI_PARSE_EXECUTE) { Status = AE_OK; } /* 2) NotFound during a CondRefOf(x) is ok by definition */ else if (WalkState->Op->Common.AmlOpcode == AML_CONDITIONAL_REF_OF_OP) { Status = AE_OK; } /* * 3) NotFound while building a Package is ok at this point, we * may flag as an error later if slack mode is not enabled. * (Some ASL code depends on allowing this behavior) */ else if ((Arg->Common.Parent) && ((Arg->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Arg->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP))) { Status = AE_OK; } } /* Final exception check (may have been changed from code above) */ if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, Path, Status); if ((WalkState->ParseFlags & ACPI_PARSE_MODE_MASK) == ACPI_PARSE_EXECUTE) { /* Report a control method execution error */ Status = AcpiDsMethodError (Status, WalkState); } } /* Save the namepath */ Arg->Common.Value.Name = Path; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiPsGetNextSimpleArg * * PARAMETERS: ParserState - Current parser state object * ArgType - The argument type (AML_*_ARG) * Arg - Where the argument is returned * * RETURN: None * * DESCRIPTION: Get the next simple argument (constant, string, or namestring) * ******************************************************************************/ void AcpiPsGetNextSimpleArg ( ACPI_PARSE_STATE *ParserState, UINT32 ArgType, ACPI_PARSE_OBJECT *Arg) { UINT32 Length; UINT16 Opcode; UINT8 *Aml = ParserState->Aml; ACPI_FUNCTION_TRACE_U32 (PsGetNextSimpleArg, ArgType); switch (ArgType) { case ARGP_BYTEDATA: /* Get 1 byte from the AML stream */ Opcode = AML_BYTE_OP; Arg->Common.Value.Integer = (UINT64) *Aml; Length = 1; break; case ARGP_WORDDATA: /* Get 2 bytes from the AML stream */ Opcode = AML_WORD_OP; ACPI_MOVE_16_TO_64 (&Arg->Common.Value.Integer, Aml); Length = 2; break; case ARGP_DWORDDATA: /* Get 4 bytes from the AML stream */ Opcode = AML_DWORD_OP; ACPI_MOVE_32_TO_64 (&Arg->Common.Value.Integer, Aml); Length = 4; break; case ARGP_QWORDDATA: /* Get 8 bytes from the AML stream */ Opcode = AML_QWORD_OP; ACPI_MOVE_64_TO_64 (&Arg->Common.Value.Integer, Aml); Length = 8; break; case ARGP_CHARLIST: /* Get a pointer to the string, point past the string */ Opcode = AML_STRING_OP; Arg->Common.Value.String = ACPI_CAST_PTR (char, Aml); /* Find the null terminator */ Length = 0; while (Aml[Length]) { Length++; } Length++; break; case ARGP_NAME: case ARGP_NAMESTRING: AcpiPsInitOp (Arg, AML_INT_NAMEPATH_OP); Arg->Common.Value.Name = AcpiPsGetNextNamestring (ParserState); return_VOID; default: ACPI_ERROR ((AE_INFO, "Invalid ArgType 0x%X", ArgType)); return_VOID; } AcpiPsInitOp (Arg, Opcode); ParserState->Aml += Length; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiPsGetNextField * * PARAMETERS: ParserState - Current parser state object * * RETURN: A newly allocated FIELD op * * DESCRIPTION: Get next field (NamedField, ReservedField, or AccessField) * ******************************************************************************/ static ACPI_PARSE_OBJECT * AcpiPsGetNextField ( ACPI_PARSE_STATE *ParserState) { UINT8 *Aml; ACPI_PARSE_OBJECT *Field; ACPI_PARSE_OBJECT *Arg = NULL; UINT16 Opcode; UINT32 Name; UINT8 AccessType; UINT8 AccessAttribute; UINT8 AccessLength; UINT32 PkgLength; UINT8 *PkgEnd; UINT32 BufferLength; ACPI_FUNCTION_TRACE (PsGetNextField); ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); Aml = ParserState->Aml; /* Determine field type */ switch (ACPI_GET8 (ParserState->Aml)) { case AML_FIELD_OFFSET_OP: Opcode = AML_INT_RESERVEDFIELD_OP; ParserState->Aml++; break; case AML_FIELD_ACCESS_OP: Opcode = AML_INT_ACCESSFIELD_OP; ParserState->Aml++; break; case AML_FIELD_CONNECTION_OP: Opcode = AML_INT_CONNECTION_OP; ParserState->Aml++; break; case AML_FIELD_EXT_ACCESS_OP: Opcode = AML_INT_EXTACCESSFIELD_OP; ParserState->Aml++; break; default: Opcode = AML_INT_NAMEDFIELD_OP; break; } /* Allocate a new field op */ Field = AcpiPsAllocOp (Opcode, Aml); if (!Field) { return_PTR (NULL); } /* Decode the field type */ ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); switch (Opcode) { case AML_INT_NAMEDFIELD_OP: /* Get the 4-character name */ ACPI_MOVE_32_TO_32 (&Name, ParserState->Aml); AcpiPsSetName (Field, Name); ParserState->Aml += ACPI_NAMESEG_SIZE; ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); #ifdef ACPI_ASL_COMPILER /* * Because the package length isn't represented as a parse tree object, * take comments surrounding this and add to the previously created * parse node. */ if (Field->Common.InlineComment) { Field->Common.NameComment = Field->Common.InlineComment; } Field->Common.InlineComment = AcpiGbl_CurrentInlineComment; AcpiGbl_CurrentInlineComment = NULL; #endif /* Get the length which is encoded as a package length */ Field->Common.Value.Size = AcpiPsGetNextPackageLength (ParserState); break; case AML_INT_RESERVEDFIELD_OP: /* Get the length which is encoded as a package length */ Field->Common.Value.Size = AcpiPsGetNextPackageLength (ParserState); break; case AML_INT_ACCESSFIELD_OP: case AML_INT_EXTACCESSFIELD_OP: /* * Get AccessType and AccessAttrib and merge into the field Op * AccessType is first operand, AccessAttribute is second. stuff * these bytes into the node integer value for convenience. */ /* Get the two bytes (Type/Attribute) */ AccessType = ACPI_GET8 (ParserState->Aml); ParserState->Aml++; AccessAttribute = ACPI_GET8 (ParserState->Aml); ParserState->Aml++; Field->Common.Value.Integer = (UINT8) AccessType; Field->Common.Value.Integer |= (UINT16) (AccessAttribute << 8); /* This opcode has a third byte, AccessLength */ if (Opcode == AML_INT_EXTACCESSFIELD_OP) { AccessLength = ACPI_GET8 (ParserState->Aml); ParserState->Aml++; Field->Common.Value.Integer |= (UINT32) (AccessLength << 16); } break; case AML_INT_CONNECTION_OP: /* * Argument for Connection operator can be either a Buffer * (resource descriptor), or a NameString. */ Aml = ParserState->Aml; if (ACPI_GET8 (ParserState->Aml) == AML_BUFFER_OP) { ParserState->Aml++; ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); PkgEnd = ParserState->Aml; PkgLength = AcpiPsGetNextPackageLength (ParserState); PkgEnd += PkgLength; ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); if (ParserState->Aml < PkgEnd) { /* Non-empty list */ Arg = AcpiPsAllocOp (AML_INT_BYTELIST_OP, Aml); if (!Arg) { AcpiPsFreeOp (Field); return_PTR (NULL); } /* Get the actual buffer length argument */ Opcode = ACPI_GET8 (ParserState->Aml); ParserState->Aml++; ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); switch (Opcode) { case AML_BYTE_OP: /* AML_BYTEDATA_ARG */ BufferLength = ACPI_GET8 (ParserState->Aml); ParserState->Aml += 1; break; case AML_WORD_OP: /* AML_WORDDATA_ARG */ BufferLength = ACPI_GET16 (ParserState->Aml); ParserState->Aml += 2; break; case AML_DWORD_OP: /* AML_DWORDATA_ARG */ BufferLength = ACPI_GET32 (ParserState->Aml); ParserState->Aml += 4; break; default: BufferLength = 0; break; } /* Fill in bytelist data */ ASL_CV_CAPTURE_COMMENTS_ONLY (ParserState); Arg->Named.Value.Size = BufferLength; Arg->Named.Data = ParserState->Aml; } /* Skip to End of byte data */ ParserState->Aml = PkgEnd; } else { Arg = AcpiPsAllocOp (AML_INT_NAMEPATH_OP, Aml); if (!Arg) { AcpiPsFreeOp (Field); return_PTR (NULL); } /* Get the Namestring argument */ Arg->Common.Value.Name = AcpiPsGetNextNamestring (ParserState); } /* Link the buffer/namestring to parent (CONNECTION_OP) */ AcpiPsAppendArg (Field, Arg); break; default: /* Opcode was set in previous switch */ break; } return_PTR (Field); } /******************************************************************************* * * FUNCTION: AcpiPsGetNextArg * * PARAMETERS: WalkState - Current state * ParserState - Current parser state object * ArgType - The argument type (AML_*_ARG) * ReturnArg - Where the next arg is returned * * RETURN: Status, and an op object containing the next argument. * * DESCRIPTION: Get next argument (including complex list arguments that require * pushing the parser stack) * ******************************************************************************/ ACPI_STATUS AcpiPsGetNextArg ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_STATE *ParserState, UINT32 ArgType, ACPI_PARSE_OBJECT **ReturnArg) { ACPI_PARSE_OBJECT *Arg = NULL; ACPI_PARSE_OBJECT *Prev = NULL; ACPI_PARSE_OBJECT *Field; UINT32 Subop; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (PsGetNextArg, ParserState); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Expected argument type ARGP: %s (%2.2X)\n", AcpiUtGetArgumentTypeName (ArgType), ArgType)); switch (ArgType) { case ARGP_BYTEDATA: case ARGP_WORDDATA: case ARGP_DWORDDATA: case ARGP_CHARLIST: case ARGP_NAME: case ARGP_NAMESTRING: /* Constants, strings, and namestrings are all the same size */ Arg = AcpiPsAllocOp (AML_BYTE_OP, ParserState->Aml); if (!Arg) { return_ACPI_STATUS (AE_NO_MEMORY); } AcpiPsGetNextSimpleArg (ParserState, ArgType, Arg); break; case ARGP_PKGLENGTH: /* Package length, nothing returned */ ParserState->PkgEnd = AcpiPsGetNextPackageEnd (ParserState); break; case ARGP_FIELDLIST: if (ParserState->Aml < ParserState->PkgEnd) { /* Non-empty list */ while (ParserState->Aml < ParserState->PkgEnd) { Field = AcpiPsGetNextField (ParserState); if (!Field) { return_ACPI_STATUS (AE_NO_MEMORY); } if (Prev) { Prev->Common.Next = Field; } else { Arg = Field; } Prev = Field; } /* Skip to End of byte data */ ParserState->Aml = ParserState->PkgEnd; } break; case ARGP_BYTELIST: if (ParserState->Aml < ParserState->PkgEnd) { /* Non-empty list */ Arg = AcpiPsAllocOp (AML_INT_BYTELIST_OP, ParserState->Aml); if (!Arg) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Fill in bytelist data */ Arg->Common.Value.Size = (UINT32) ACPI_PTR_DIFF (ParserState->PkgEnd, ParserState->Aml); Arg->Named.Data = ParserState->Aml; /* Skip to End of byte data */ ParserState->Aml = ParserState->PkgEnd; } break; case ARGP_SIMPLENAME: case ARGP_NAME_OR_REF: ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "**** SimpleName/NameOrRef: %s (%2.2X)\n", AcpiUtGetArgumentTypeName (ArgType), ArgType)); Subop = AcpiPsPeekOpcode (ParserState); if (Subop == 0 || AcpiPsIsLeadingChar (Subop) || ACPI_IS_ROOT_PREFIX (Subop) || ACPI_IS_PARENT_PREFIX (Subop)) { /* NullName or NameString */ Arg = AcpiPsAllocOp (AML_INT_NAMEPATH_OP, ParserState->Aml); if (!Arg) { return_ACPI_STATUS (AE_NO_MEMORY); } Status = AcpiPsGetNextNamepath (WalkState, ParserState, Arg, ACPI_NOT_METHOD_CALL); } else { /* Single complex argument, nothing returned */ WalkState->ArgCount = 1; } break; case ARGP_TARGET: case ARGP_SUPERNAME: ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "**** Target/Supername: %s (%2.2X)\n", AcpiUtGetArgumentTypeName (ArgType), ArgType)); Subop = AcpiPsPeekOpcode (ParserState); if (Subop == 0 || AcpiPsIsLeadingChar (Subop) || ACPI_IS_ROOT_PREFIX (Subop) || ACPI_IS_PARENT_PREFIX (Subop)) { /* NULL target (zero). Convert to a NULL namepath */ Arg = AcpiPsAllocOp (AML_INT_NAMEPATH_OP, ParserState->Aml); if (!Arg) { return_ACPI_STATUS (AE_NO_MEMORY); } Status = AcpiPsGetNextNamepath (WalkState, ParserState, Arg, ACPI_POSSIBLE_METHOD_CALL); if (Arg->Common.AmlOpcode == AML_INT_METHODCALL_OP) { /* Free method call op and corresponding namestring sub-ob */ AcpiPsFreeOp (Arg->Common.Value.Arg); AcpiPsFreeOp (Arg); Arg = NULL; WalkState->ArgCount = 1; } } else { /* Single complex argument, nothing returned */ WalkState->ArgCount = 1; } break; case ARGP_DATAOBJ: case ARGP_TERMARG: ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "**** TermArg/DataObj: %s (%2.2X)\n", AcpiUtGetArgumentTypeName (ArgType), ArgType)); /* Single complex argument, nothing returned */ WalkState->ArgCount = 1; break; case ARGP_DATAOBJLIST: case ARGP_TERMLIST: case ARGP_OBJLIST: if (ParserState->Aml < ParserState->PkgEnd) { /* Non-empty list of variable arguments, nothing returned */ WalkState->ArgCount = ACPI_VAR_ARGS; } break; default: ACPI_ERROR ((AE_INFO, "Invalid ArgType: 0x%X", ArgType)); Status = AE_AML_OPERAND_TYPE; break; } *ReturnArg = Arg; return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/hal_types.h> #include <tilck/kernel/list.h> #include <tilck/kernel/bintree.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/signal.h> #include <tilck_gen_headers/config_sched.h> #define TIME_SLICE_TICKS (TIMER_HZ / 25) enum task_state { TASK_STATE_INVALID = 0, TASK_STATE_RUNNABLE = 1, TASK_STATE_RUNNING = 2, TASK_STATE_SLEEPING = 3, TASK_STATE_ZOMBIE = 4 }; enum wakeup_reason { task_died, task_stopped, task_continued, }; struct misc_buf { char path_buf[MAX_PATH]; char unused[1024 - MAX_PATH]; char execve_ctx[1024]; char resolve_ctx[2048]; }; struct sched_ticks { u32 timeslice; /* ticks counter for the current time slice */ u64 total; /* total life-time ticks */ u64 total_kernel; /* total life-time ticks spent in kernel */ u64 vruntime; /* a brutal approx. of Linux's vruntime */ }; STATIC_ASSERT(sizeof(enum sig_state) == 1); struct task { union { int tid; /* User/kernel task ID (pid in the Linux kernel) */ /* * For the moment, `tid` has everywhere `int` as type, while the field is * used as key with the bintree_*_int functions which use pointer-sized * integers. Therefore, in case sizeof(long) > sizeof(int), we need some * padding. */ ulong padding_0; }; struct process *pi; bool is_main_thread; /* value of `tid == pi->pid` */ bool running_in_kernel; bool stopped; bool was_stopped; volatile ATOMIC(enum task_state) state; /* see docs/atomics.md */ regs_t *state_regs; regs_t *fault_resume_regs; u32 faults_resume_mask; void *worker_thread; /* only for worker threads */ struct bintree_node tree_by_tid_node; struct list_node runnable_node; struct list_node wakeup_timer_node; struct list_node siblings_node; /* nodes in parent's pi's children list */ struct list tasks_waiting_list; /* tasks waiting this task to end */ s32 wstatus; /* waitpid's wstatus */ struct sched_ticks ticks; /* scheduler counters */ void *kernel_stack; void *args_copybuf; union { void *io_copybuf; struct misc_buf *misc_buf; }; struct wait_obj wobj; u32 ticks_before_wake_up; /* List of callbacks to call on exit */ struct list on_exit; /* Temp kernel allocations for user requests */ struct kernel_alloc *kallocs_tree_root; /* This task is stopped because of its vfork-ed child */ bool vfork_stopped; /* Trace the syscalls of this task (requires debugpanel) */ bool traced; /* The task was sleeping on a timer and has just been woken up */ bool timer_ready; /* The current sa_mask has been altered by sigsuspend() */ bool in_sigsuspend; /* Number of nested custom signal handlers (at most 1, at the moment). */ int nested_sig_handlers; /* Kernel thread name, NULL for user tasks */ const char *kthread_name; /* Pending signals bitset */ ulong sa_pending[K_SIGACTION_MASK_WORDS]; /* Pending signals bitset generated by HW faults */ ulong sa_fault_pending[K_SIGACTION_MASK_WORDS]; /* Blocked signals mask, updated by sigprocmask() and sigsuspend() */ ulong sa_mask[K_SIGACTION_MASK_WORDS]; /* Old blocked signals mask, saved by sys_rt_sigsuspend() */ ulong sa_old_mask[K_SIGACTION_MASK_WORDS]; /* See the comment above struct process' pi_arch */ char ti_arch[ARCH_TASK_MEMBERS_SIZE] ALIGNED_AT(ARCH_TASK_MEMBERS_ALIGN); }; extern struct task *kernel_process; extern struct process *kernel_process_pi; extern struct task *idle_task; extern struct list runnable_tasks_list; extern const char *const task_state_str[5]; #define KTH_ALLOC_BUFS (1 << 0) #define KTH_WORKER_THREAD (1 << 1) #define KERNEL_TID_START 10000 #define KERNEL_MAX_TID 1024 /* + KERNEL_TID_START */ STATIC_ASSERT(MAX_PID < KERNEL_TID_START); void init_sched(void); struct task *get_task(int tid); struct process *get_process(int pid); void task_change_state(struct task *ti, enum task_state new_state); void task_change_state_idempotent(struct task *ti, enum task_state new_state); bool save_regs_and_schedule(bool skip_disable_preempt); static ALWAYS_INLINE void sched_set_need_resched(void) { extern ATOMIC(int) __need_resched; /* see docs/atomics.md */ atomic_store_explicit(&__need_resched, 1, mo_relaxed); } static ALWAYS_INLINE void sched_clear_need_resched(void) { extern ATOMIC(int) __need_resched; /* see docs/atomics.md */ atomic_store_explicit(&__need_resched, 0, mo_relaxed); } static ALWAYS_INLINE bool need_reschedule(void) { extern ATOMIC(int) __need_resched; /* see docs/atomics.md */ return (bool) atomic_load_explicit(&__need_resched, mo_relaxed); } static ALWAYS_INLINE void disable_preemption(void) { extern ATOMIC(int) __disable_preempt; /* see docs/atomics.md */ atomic_fetch_add_explicit(&__disable_preempt, 1, mo_relaxed); } static ALWAYS_INLINE void enable_preemption_nosched(void) { extern ATOMIC(int) __disable_preempt; /* see docs/atomics.md */ atomic_fetch_sub_explicit(&__disable_preempt, 1, mo_relaxed); } void enable_preemption(void); /* * WARNING: this function is dangerous and should NEVER be used it for anything * other than special self-test code paths. See selftest_kmutex_ord_med(). */ static ALWAYS_INLINE void force_enable_preemption(void) { extern ATOMIC(int) __disable_preempt; /* see docs/atomics.md */ atomic_store_explicit(&__disable_preempt, 0, mo_relaxed); } static ALWAYS_INLINE int get_preempt_disable_count(void) { extern ATOMIC(int) __disable_preempt; /* see docs/atomics.md */ return atomic_load_explicit(&__disable_preempt, mo_relaxed); } static ALWAYS_INLINE bool is_preemption_enabled(void) { return !get_preempt_disable_count(); } static ALWAYS_INLINE bool running_in_kernel(struct task *t) { return t->running_in_kernel; } static ALWAYS_INLINE bool is_kernel_thread(struct task *ti) { return ti->pi == kernel_process_pi; } static ALWAYS_INLINE bool is_main_thread(struct task *ti) { return ti->is_main_thread; } static ALWAYS_INLINE bool is_worker_thread(struct task *ti) { return ti->worker_thread != NULL; } /* * Default yield function * * Saves the current state and calls the scheduler. Expects the preemption to be * enabled. Returns true if a context switch occurred, false otherwise. */ static ALWAYS_INLINE bool kernel_yield(void) { sched_set_need_resched(); return save_regs_and_schedule(false); } /* * Special yield function to use when we disabled the preemption just *ONCE* * and want to yield without wasting a whole enable/disable preemption cycle. * * WARNING: this function excepts to be called with __disable_preempt == 1 while * it will always return with __disable_preempt == 0. It is asymmetric but * that's the same as do_schedule(): we want to call it with preemption disabled * in order to safely do stuff before calling it, but we EXPECT that calling it * WILL very likely "preempt" us and do a context switch, so we clearly expect * preemption to be enabled when it returns. */ static ALWAYS_INLINE bool kernel_yield_preempt_disabled(void) { sched_set_need_resched(); return save_regs_and_schedule(true); } /* * Just save the state and call the scheduler, without forcing a yield. */ static ALWAYS_INLINE bool schedule(void) { return save_regs_and_schedule(false); } /* * Just save the state and call the scheduler, without forcing a yield. * Expects the preemption to be already disabled. */ static ALWAYS_INLINE bool schedule_preempt_disabled(void) { return save_regs_and_schedule(true); } static ALWAYS_INLINE struct task *get_curr_task(void) { extern struct task *__current; /* * Access to `__current` DOES NOT need to be atomic (not even relaxed) even * on architectures (!= x86) where loading/storing a pointer-size integer * requires more than one instruction, for the following reasons: * * - While ANY given task is running, `__current` is always set and valid. * That is true even if the task is preempted after reading for example * only half of its value and than its execution resumed back, because * during the task switch the older value of `__current` will be * restored. * * - The `__current` variable is set only in three cases: * - during initialization [create_kernel_process()] * - in switch_to_task() [with interrupts disabled] * - in kthread_exit() [with interrupts disabled] */ return __current; } /* Hack: it works only if the C file includes process.h, but that's fine. */ #define get_curr_proc() (get_curr_task()->pi) static ALWAYS_INLINE enum task_state get_curr_task_state(void) { STATIC_ASSERT(sizeof(get_curr_task()->state) == 4); /* * Casting `state` to u32 and back to `enum task_state` to avoid compiler * errors in some weird configurations. */ return (enum task_state) atomic_load_explicit( (ATOMIC(u32)*)&get_curr_task()->state, mo_relaxed ); } #if DEBUG_CHECKS #define ASSERT_CURR_TASK_STATE(exp) \ do { \ if (get_curr_task_state() != (exp)) \ panic("Curr task state (%s) != expected (%s)", \ task_state_str[get_curr_task_state()], \ task_state_str[exp]); \ } while (0) #define ASSERT_TASK_STATE(s, exp) \ do { \ if ((s) != (exp)) \ panic("Task state (%s) != expected (%s)", \ task_state_str[s], \ task_state_str[exp]); \ } while (0) #else #define ASSERT_CURR_TASK_STATE(exp) #define ASSERT_TASK_STATE(s, exp) #endif static ALWAYS_INLINE void enter_sleep_wait_state(void) { ASSERT(!is_preemption_enabled()); /* Cannot call enter_sleep_wait_state() before setting a wait obj */ ASSERT(get_curr_task()->wobj.type != WOBJ_NONE); if (get_curr_task_state() != TASK_STATE_SLEEPING) { /* * Corner case: we set a timer, then we called prepare_to_wait_on() which * set task's wobj and changed task's state to SLEEPING, but the timer * fired before we called this function. Timer_ready MUST BE set. * * Otherwise, that's simply a logic error: we called this function without * calling first prepare_to_wait_on(). */ ASSERT(get_curr_task()->timer_ready); } schedule_preempt_disabled(); } NORETURN void switch_to_task(struct task *ti); /* * Run the scheduler directly without saving the current state. * Expects preemption to be disabled. */ void do_schedule(void); bool pending_signals(void); int get_curr_tid(void); int get_curr_pid(void); void save_current_task_state(regs_t *); void sched_account_ticks(void); int create_new_pid(void); int create_new_kernel_tid(void); void task_info_reset_kernel_stack(struct task *ti); void add_task(struct task *ti); void remove_task(struct task *ti); void init_task_lists(struct task *ti); // It is called when each kernel thread returns. May be called explicitly too. void kthread_exit(void); int kthread_join(int tid, bool ignore_signals); int kthread_join_all(const int *tids, size_t n, bool ignore_signals); void task_set_wakeup_timer(struct task *task, u32 ticks); void task_update_wakeup_timer_if_any(struct task *ti, u32 new_ticks); u32 task_cancel_wakeup_timer(struct task *ti); typedef void (*kthread_func_ptr)(); NODISCARD int kthread_create2(kthread_func_ptr func, const char *name, int fl, void *arg); #define kthread_create(func, fl, arg) \ kthread_create2(func, #func, (fl), (arg)) int iterate_over_tasks(bintree_visit_cb func, void *arg); int sched_count_proc_in_group(int pgid); int sched_get_session_of_group(int pgid); struct process *task_get_pi_opaque(struct task *ti); void process_set_tty(struct process *pi, void *t); bool in_currently_dying_task(void); void set_current_task_in_kernel(void); void set_current_task_in_user_mode(void); void *task_temp_kernel_alloc(size_t size); void task_temp_kernel_free(void *ptr); int register_on_task_exit_cb(void (*cb)(struct task *)); int unregister_on_task_exit_cb(void (*cb)(struct task *)); void yield_until_last(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include "acpi_int.h" static ACPI_STATUS acpi_fix_power_button_handler(void *ctx) { poweroff(); return 0; /* MUST return 0 in ANY case. Other values are reserved */ } static ACPI_STATUS powerbtn_reg_fix_handlers(void *__ctx) { ACPI_STATUS rc; rc = AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON, &acpi_fix_power_button_handler, NULL); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInstallFixedEventHandler", NULL, rc); /* NOTE: Don't consider it as a fatal failure */ } return AE_OK; } static void powerbtn_notify_handler(ACPI_HANDLE Device, UINT32 Value, void *Context) { printk("ACPI: power button notify event, device: %p, val: %#x\n", Device, Value); } static void lidswitch_notify_handler(ACPI_HANDLE Device, UINT32 Value, void *Context) { printk("ACPI: lid switch notify event, device: %p, val: %#x\n", Device, Value); } static ACPI_STATUS powerbtn_reg_notify_cb(void *obj_handle, void *__device_info, void *ctx) { ACPI_STATUS rc = AE_OK; ACPI_NOTIFY_HANDLER handler = ctx; ASSERT(handler != NULL); rc = AcpiInstallNotifyHandler(obj_handle, ACPI_ALL_NOTIFY, handler, NULL); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInstallNotifyHandler", NULL, rc); /* NOTE: Don't consider it as a fatal failure */ } return AE_OK; } __attribute__((constructor)) static void __reg_callbacks(void) { static struct acpi_reg_callback_node fixh = { .cb = &powerbtn_reg_fix_handlers, .ctx = NULL }; list_node_init(&fixh.node); acpi_reg_on_subsys_enabled_cb(&fixh); static struct acpi_reg_per_object_cb_node pwbtn_notf = { .cb = &powerbtn_reg_notify_cb, .ctx = &powerbtn_notify_handler, .hid = "PNP0C0C", .uid = NULL, .cls = NULL, }; list_node_init(&pwbtn_notf.node); acpi_reg_per_object_cb(&pwbtn_notf); static struct acpi_reg_per_object_cb_node lid_notf = { .cb = &powerbtn_reg_notify_cb, .ctx = &lidswitch_notify_handler, .hid = "PNP0C0D", .uid = NULL, .cls = NULL, }; list_node_init(&lid_notf.node); acpi_reg_per_object_cb(&lid_notf); } <file_sep>FROM opensuse/leap RUN zypper --non-interactive in sudo <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ DEF_3(wrap, assert_failed, void, const char *, const char *, int) DEF_2(wrap, not_reached, void, const char *, int) DEF_2(wrap, not_implemented, void, const char *, int) DEF_3(wrap, tilck_vprintk, void, u32, const char *, va_list) DEF_1(wrap, kmutex_lock, void, struct kmutex *) DEF_1(wrap, kmutex_unlock, void, struct kmutex *) DEF_2(wrap, fat_ramdisk_prepare_for_mmap, int, void *, size_t) DEF_1(wrap, wth_create_thread_for, int, void *) DEF_1(wrap, wth_wakeup, void, void *) DEF_0(wrap, check_in_irq_handler, void) DEF_2(wrap, general_kmalloc, void *, size_t *, u32) DEF_3(wrap, general_kfree, void, void *, size_t *, u32) DEF_1(wrap, kmalloc_get_first_heap, void *, size_t *) DEF_0(real, experiment_bar, bool) DEF_1(real, experiment_foo, int, int) DEF_2(real, vfs_dup, int, fs_handle, fs_handle *) DEF_1(real, vfs_close, void, fs_handle) DEF_1(real, handle_sys_trace_arg, int , const char *); DEF_4(real, copy_str_from_user, int, void *, const void *, size_t, size_t *); DEF_3(real, copy_from_user, int, void *, const void *, size_t); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> static ALWAYS_INLINE void set_curr_pdir(pdir_t *pdir) { __set_curr_pdir(KERNEL_VA_TO_PA(pdir)); } static ALWAYS_INLINE pdir_t *get_curr_pdir() { return (pdir_t *)KERNEL_PA_TO_VA(__get_curr_pdir()); } /* * Tilck's entry point is in `_start` where the so-called "original" * page directory is set, using the `page_size_buf` as buffer. The original * page directory just linearly maps the first 4 MB of the physical memory to * KERNEL_BASE_VA. This function returns true if we're still using that page * directory (-> early_init_paging() has not been called yet). */ static ALWAYS_INLINE bool still_using_orig_pdir(void) { #ifndef UNIT_TEST_ENVIRONMENT return get_curr_pdir() == (void *)page_size_buf; #else return false; #endif } <file_sep>/****************************************************************************** * * Module Name: nsutils - Utilities for accessing ACPI namespace, accessing * parents and siblings and Scope manipulation * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "amlcode.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsutils") /* Local prototypes */ #ifdef ACPI_OBSOLETE_FUNCTIONS ACPI_NAME AcpiNsFindParentName ( ACPI_NAMESPACE_NODE *NodeToSearch); #endif /******************************************************************************* * * FUNCTION: AcpiNsPrintNodePathname * * PARAMETERS: Node - Object * Message - Prefix message * * DESCRIPTION: Print an object's full namespace pathname * Manages allocation/freeing of a pathname buffer * ******************************************************************************/ void AcpiNsPrintNodePathname ( ACPI_NAMESPACE_NODE *Node, const char *Message) { ACPI_BUFFER Buffer; ACPI_STATUS Status; if (!Node) { AcpiOsPrintf ("[NULL NAME]"); return; } /* Convert handle to full pathname and print it (with supplied message) */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (Node, &Buffer, TRUE); if (ACPI_SUCCESS (Status)) { if (Message) { AcpiOsPrintf ("%s ", Message); } AcpiOsPrintf ("%s", (char *) Buffer.Pointer); ACPI_FREE (Buffer.Pointer); } } /******************************************************************************* * * FUNCTION: AcpiNsGetType * * PARAMETERS: Node - Parent Node to be examined * * RETURN: Type field from Node whose handle is passed * * DESCRIPTION: Return the type of a Namespace node * ******************************************************************************/ ACPI_OBJECT_TYPE AcpiNsGetType ( ACPI_NAMESPACE_NODE *Node) { ACPI_FUNCTION_TRACE (NsGetType); if (!Node) { ACPI_WARNING ((AE_INFO, "Null Node parameter")); return_UINT8 (ACPI_TYPE_ANY); } return_UINT8 (Node->Type); } /******************************************************************************* * * FUNCTION: AcpiNsLocal * * PARAMETERS: Type - A namespace object type * * RETURN: LOCAL if names must be found locally in objects of the * passed type, 0 if enclosing scopes should be searched * * DESCRIPTION: Returns scope rule for the given object type. * ******************************************************************************/ UINT32 AcpiNsLocal ( ACPI_OBJECT_TYPE Type) { ACPI_FUNCTION_TRACE (NsLocal); if (!AcpiUtValidObjectType (Type)) { /* Type code out of range */ ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type)); return_UINT32 (ACPI_NS_NORMAL); } return_UINT32 (AcpiGbl_NsProperties[Type] & ACPI_NS_LOCAL); } /******************************************************************************* * * FUNCTION: AcpiNsGetInternalNameLength * * PARAMETERS: Info - Info struct initialized with the * external name pointer. * * RETURN: None * * DESCRIPTION: Calculate the length of the internal (AML) namestring * corresponding to the external (ASL) namestring. * ******************************************************************************/ void AcpiNsGetInternalNameLength ( ACPI_NAMESTRING_INFO *Info) { const char *NextExternalChar; UINT32 i; ACPI_FUNCTION_ENTRY (); NextExternalChar = Info->ExternalName; Info->NumCarats = 0; Info->NumSegments = 0; Info->FullyQualified = FALSE; /* * For the internal name, the required length is 4 bytes per segment, * plus 1 each for RootPrefix, MultiNamePrefixOp, segment count, * trailing null (which is not really needed, but no there's harm in * putting it there) * * strlen() + 1 covers the first NameSeg, which has no path separator */ if (ACPI_IS_ROOT_PREFIX (*NextExternalChar)) { Info->FullyQualified = TRUE; NextExternalChar++; /* Skip redundant RootPrefix, like \\_SB.PCI0.SBRG.EC0 */ while (ACPI_IS_ROOT_PREFIX (*NextExternalChar)) { NextExternalChar++; } } else { /* Handle Carat prefixes */ while (ACPI_IS_PARENT_PREFIX (*NextExternalChar)) { Info->NumCarats++; NextExternalChar++; } } /* * Determine the number of ACPI name "segments" by counting the number of * path separators within the string. Start with one segment since the * segment count is [(# separators) + 1], and zero separators is ok. */ if (*NextExternalChar) { Info->NumSegments = 1; for (i = 0; NextExternalChar[i]; i++) { if (ACPI_IS_PATH_SEPARATOR (NextExternalChar[i])) { Info->NumSegments++; } } } Info->Length = (ACPI_NAMESEG_SIZE * Info->NumSegments) + 4 + Info->NumCarats; Info->NextExternalChar = NextExternalChar; } /******************************************************************************* * * FUNCTION: AcpiNsBuildInternalName * * PARAMETERS: Info - Info struct fully initialized * * RETURN: Status * * DESCRIPTION: Construct the internal (AML) namestring * corresponding to the external (ASL) namestring. * ******************************************************************************/ ACPI_STATUS AcpiNsBuildInternalName ( ACPI_NAMESTRING_INFO *Info) { UINT32 NumSegments = Info->NumSegments; char *InternalName = Info->InternalName; const char *ExternalName = Info->NextExternalChar; char *Result = NULL; UINT32 i; ACPI_FUNCTION_TRACE (NsBuildInternalName); /* Setup the correct prefixes, counts, and pointers */ if (Info->FullyQualified) { InternalName[0] = AML_ROOT_PREFIX; if (NumSegments <= 1) { Result = &InternalName[1]; } else if (NumSegments == 2) { InternalName[1] = AML_DUAL_NAME_PREFIX; Result = &InternalName[2]; } else { InternalName[1] = AML_MULTI_NAME_PREFIX; InternalName[2] = (char) NumSegments; Result = &InternalName[3]; } } else { /* * Not fully qualified. * Handle Carats first, then append the name segments */ i = 0; if (Info->NumCarats) { for (i = 0; i < Info->NumCarats; i++) { InternalName[i] = AML_PARENT_PREFIX; } } if (NumSegments <= 1) { Result = &InternalName[i]; } else if (NumSegments == 2) { InternalName[i] = AML_DUAL_NAME_PREFIX; Result = &InternalName[(ACPI_SIZE) i+1]; } else { InternalName[i] = AML_MULTI_NAME_PREFIX; InternalName[(ACPI_SIZE) i+1] = (char) NumSegments; Result = &InternalName[(ACPI_SIZE) i+2]; } } /* Build the name (minus path separators) */ for (; NumSegments; NumSegments--) { for (i = 0; i < ACPI_NAMESEG_SIZE; i++) { if (ACPI_IS_PATH_SEPARATOR (*ExternalName) || (*ExternalName == 0)) { /* Pad the segment with underscore(s) if segment is short */ Result[i] = '_'; } else { /* Convert the character to uppercase and save it */ Result[i] = (char) toupper ((int) *ExternalName); ExternalName++; } } /* Now we must have a path separator, or the pathname is bad */ if (!ACPI_IS_PATH_SEPARATOR (*ExternalName) && (*ExternalName != 0)) { return_ACPI_STATUS (AE_BAD_PATHNAME); } /* Move on the next segment */ ExternalName++; Result += ACPI_NAMESEG_SIZE; } /* Terminate the string */ *Result = 0; if (Info->FullyQualified) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (abs) \"\\%s\"\n", InternalName, InternalName)); } else { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (rel) \"%s\"\n", InternalName, InternalName)); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsInternalizeName * * PARAMETERS: *ExternalName - External representation of name * **Converted Name - Where to return the resulting * internal represention of the name * * RETURN: Status * * DESCRIPTION: Convert an external representation (e.g. "\_PR_.CPU0") * to internal form (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30) * *******************************************************************************/ ACPI_STATUS AcpiNsInternalizeName ( const char *ExternalName, char **ConvertedName) { char *InternalName; ACPI_NAMESTRING_INFO Info; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsInternalizeName); if ((!ExternalName) || (*ExternalName == 0) || (!ConvertedName)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Get the length of the new internal name */ Info.ExternalName = ExternalName; AcpiNsGetInternalNameLength (&Info); /* We need a segment to store the internal name */ InternalName = ACPI_ALLOCATE_ZEROED (Info.Length); if (!InternalName) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Build the name */ Info.InternalName = InternalName; Status = AcpiNsBuildInternalName (&Info); if (ACPI_FAILURE (Status)) { ACPI_FREE (InternalName); return_ACPI_STATUS (Status); } *ConvertedName = InternalName; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsExternalizeName * * PARAMETERS: InternalNameLength - Length of the internal name below * InternalName - Internal representation of name * ConvertedNameLength - Where the length is returned * ConvertedName - Where the resulting external name * is returned * * RETURN: Status * * DESCRIPTION: Convert internal name (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30) * to its external (printable) form (e.g. "\_PR_.CPU0") * ******************************************************************************/ ACPI_STATUS AcpiNsExternalizeName ( UINT32 InternalNameLength, const char *InternalName, UINT32 *ConvertedNameLength, char **ConvertedName) { UINT32 NamesIndex = 0; UINT32 NumSegments = 0; UINT32 RequiredLength; UINT32 PrefixLength = 0; UINT32 i = 0; UINT32 j = 0; ACPI_FUNCTION_TRACE (NsExternalizeName); if (!InternalNameLength || !InternalName || !ConvertedName) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Check for a prefix (one '\' | one or more '^') */ switch (InternalName[0]) { case AML_ROOT_PREFIX: PrefixLength = 1; break; case AML_PARENT_PREFIX: for (i = 0; i < InternalNameLength; i++) { if (ACPI_IS_PARENT_PREFIX (InternalName[i])) { PrefixLength = i + 1; } else { break; } } if (i == InternalNameLength) { PrefixLength = i; } break; default: break; } /* * Check for object names. Note that there could be 0-255 of these * 4-byte elements. */ if (PrefixLength < InternalNameLength) { switch (InternalName[PrefixLength]) { case AML_MULTI_NAME_PREFIX: /* <count> 4-byte names */ NamesIndex = PrefixLength + 2; NumSegments = (UINT8) InternalName[(ACPI_SIZE) PrefixLength + 1]; break; case AML_DUAL_NAME_PREFIX: /* Two 4-byte names */ NamesIndex = PrefixLength + 1; NumSegments = 2; break; case 0: /* NullName */ NamesIndex = 0; NumSegments = 0; break; default: /* one 4-byte name */ NamesIndex = PrefixLength; NumSegments = 1; break; } } /* * Calculate the length of ConvertedName, which equals the length * of the prefix, length of all object names, length of any required * punctuation ('.') between object names, plus the NULL terminator. */ RequiredLength = PrefixLength + (4 * NumSegments) + ((NumSegments > 0) ? (NumSegments - 1) : 0) + 1; /* * Check to see if we're still in bounds. If not, there's a problem * with InternalName (invalid format). */ if (RequiredLength > InternalNameLength) { ACPI_ERROR ((AE_INFO, "Invalid internal name")); return_ACPI_STATUS (AE_BAD_PATHNAME); } /* Build the ConvertedName */ *ConvertedName = ACPI_ALLOCATE_ZEROED (RequiredLength); if (!(*ConvertedName)) { return_ACPI_STATUS (AE_NO_MEMORY); } j = 0; for (i = 0; i < PrefixLength; i++) { (*ConvertedName)[j++] = InternalName[i]; } if (NumSegments > 0) { for (i = 0; i < NumSegments; i++) { if (i > 0) { (*ConvertedName)[j++] = '.'; } /* Copy and validate the 4-char name segment */ ACPI_COPY_NAMESEG (&(*ConvertedName)[j], &InternalName[NamesIndex]); AcpiUtRepairName (&(*ConvertedName)[j]); j += ACPI_NAMESEG_SIZE; NamesIndex += ACPI_NAMESEG_SIZE; } } if (ConvertedNameLength) { *ConvertedNameLength = (UINT32) RequiredLength; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsValidateHandle * * PARAMETERS: Handle - Handle to be validated and typecast to a * namespace node. * * RETURN: A pointer to a namespace node * * DESCRIPTION: Convert a namespace handle to a namespace node. Handles special * cases for the root node. * * NOTE: Real integer handles would allow for more verification * and keep all pointers within this subsystem - however this introduces * more overhead and has not been necessary to this point. Drivers * holding handles are typically notified before a node becomes invalid * due to a table unload. * ******************************************************************************/ ACPI_NAMESPACE_NODE * AcpiNsValidateHandle ( ACPI_HANDLE Handle) { ACPI_FUNCTION_ENTRY (); /* Parameter validation */ if ((!Handle) || (Handle == ACPI_ROOT_OBJECT)) { return (AcpiGbl_RootNode); } /* We can at least attempt to verify the handle */ if (ACPI_GET_DESCRIPTOR_TYPE (Handle) != ACPI_DESC_TYPE_NAMED) { return (NULL); } return (ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Handle)); } /******************************************************************************* * * FUNCTION: AcpiNsTerminate * * PARAMETERS: none * * RETURN: none * * DESCRIPTION: free memory allocated for namespace and ACPI table storage. * ******************************************************************************/ void AcpiNsTerminate ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsTerminate); /* * Free the entire namespace -- all nodes and all objects * attached to the nodes */ AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode); /* Delete any objects attached to the root node */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_VOID; } AcpiNsDeleteNode (AcpiGbl_RootNode); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n")); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsOpensScope * * PARAMETERS: Type - A valid namespace type * * RETURN: NEWSCOPE if the passed type "opens a name scope" according * to the ACPI specification, else 0 * ******************************************************************************/ UINT32 AcpiNsOpensScope ( ACPI_OBJECT_TYPE Type) { ACPI_FUNCTION_ENTRY (); if (Type > ACPI_TYPE_LOCAL_MAX) { /* type code out of range */ ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type)); return (ACPI_NS_NORMAL); } return (((UINT32) AcpiGbl_NsProperties[Type]) & ACPI_NS_NEWSCOPE); } /******************************************************************************* * * FUNCTION: AcpiNsGetNodeUnlocked * * PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The * \ (backslash) and ^ (carat) prefixes, and the * . (period) to separate segments are supported. * PrefixNode - Root of subtree to be searched, or NS_ALL for the * root of the name space. If Name is fully * qualified (first INT8 is '\'), the passed value * of Scope will not be accessed. * Flags - Used to indicate whether to perform upsearch or * not. * ReturnNode - Where the Node is returned * * DESCRIPTION: Look up a name relative to a given scope and return the * corresponding Node. NOTE: Scope can be null. * * MUTEX: Doesn't locks namespace * ******************************************************************************/ ACPI_STATUS AcpiNsGetNodeUnlocked ( ACPI_NAMESPACE_NODE *PrefixNode, const char *Pathname, UINT32 Flags, ACPI_NAMESPACE_NODE **ReturnNode) { ACPI_GENERIC_STATE ScopeInfo; ACPI_STATUS Status; char *InternalPath; ACPI_FUNCTION_TRACE_PTR (NsGetNodeUnlocked, ACPI_CAST_PTR (char, Pathname)); /* Simplest case is a null pathname */ if (!Pathname) { *ReturnNode = PrefixNode; if (!PrefixNode) { *ReturnNode = AcpiGbl_RootNode; } return_ACPI_STATUS (AE_OK); } /* Quick check for a reference to the root */ if (ACPI_IS_ROOT_PREFIX (Pathname[0]) && (!Pathname[1])) { *ReturnNode = AcpiGbl_RootNode; return_ACPI_STATUS (AE_OK); } /* Convert path to internal representation */ Status = AcpiNsInternalizeName (Pathname, &InternalPath); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Setup lookup scope (search starting point) */ ScopeInfo.Scope.Node = PrefixNode; /* Lookup the name in the namespace */ Status = AcpiNsLookup (&ScopeInfo, InternalPath, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE, (Flags | ACPI_NS_DONT_OPEN_SCOPE), NULL, ReturnNode); if (ACPI_FAILURE (Status)) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%s, %s\n", Pathname, AcpiFormatException (Status))); } ACPI_FREE (InternalPath); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiNsGetNode * * PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The * \ (backslash) and ^ (carat) prefixes, and the * . (period) to separate segments are supported. * PrefixNode - Root of subtree to be searched, or NS_ALL for the * root of the name space. If Name is fully * qualified (first INT8 is '\'), the passed value * of Scope will not be accessed. * Flags - Used to indicate whether to perform upsearch or * not. * ReturnNode - Where the Node is returned * * DESCRIPTION: Look up a name relative to a given scope and return the * corresponding Node. NOTE: Scope can be null. * * MUTEX: Locks namespace * ******************************************************************************/ ACPI_STATUS AcpiNsGetNode ( ACPI_NAMESPACE_NODE *PrefixNode, const char *Pathname, UINT32 Flags, ACPI_NAMESPACE_NODE **ReturnNode) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (NsGetNode, ACPI_CAST_PTR (char, Pathname)); Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiNsGetNodeUnlocked (PrefixNode, Pathname, Flags, ReturnNode); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/term.h> #include <tilck/kernel/term_aux.h> void term_handle_full_ringbuf(term *t, struct term_rb_data *rb_data, struct term_action *a, bool *was_empty, exec_action_func exec) { extern bool __in_printk; /* defined in printk.c */ bool written; /* We got here because the ringbuf was full in the first place */ ASSERT(!*was_empty); if (__in_printk) { if (in_panic()) { /* Stop caring about IRQs and stuff: execute everything */ term_exec_everything(t, rb_data, exec); return; } /* * OK, this is pretty weird: it's maybe (?) the absurd case of many nested * IRQs each one of them calling printk(), which at some point, finished * its own ring buffer and ended up flushing directly the messages to * this layer. The whole thing is more theoretical than practical: it * should never happen, but if it does, it's better to not pass unnoticed. */ panic("Term ringbuf full while in printk()"); } else { /* * We CANNOT possibly be in an IRQ context: we're likely in tty_write() * and we can be preempted. */ do { kmutex_lock(&rb_data->lock); { written = safe_ringbuf_write_elem(&rb_data->rb, a, was_empty); } kmutex_unlock(&rb_data->lock); } while (!written); } } void init_term_rb_data(struct term_rb_data *d, u16 max_elems, u16 elem_size, void *buf) { kmutex_init(&d->lock, 0); safe_ringbuf_init(&d->rb, max_elems, elem_size, buf); } void dispose_term_rb_data(struct term_rb_data *d) { safe_ringbuf_destory(&d->rb); kmutex_destroy(&d->lock); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define MAX_CMD_ARGS 16 #define MAX_CMD_ARG_LEN 255 extern const char *cmd_args[MAX_CMD_ARGS]; extern void (*self_test_to_run)(void); extern long kopt_ttys; extern bool kopt_sercon; extern bool kopt_sched_alive_thread; extern bool kopt_noacpi; extern bool kopt_fb_no_opt; extern bool kopt_fb_no_wc; extern bool kopt_no_fpu_memcpy; extern bool kopt_panic_kb; extern bool kopt_panic_nobt; extern bool kopt_panic_regs; extern bool kopt_panic_mmap; extern bool kopt_big_scroll_buf; extern bool kopt_ps2_log; extern bool kopt_ps2_selftest; void parse_kernel_cmdline(const char *cmdline); <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). send_to_vm_and_find_text(r"ls -l /{ret}", False, ["bin", "dev", "usr"]) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define LOADING_INITRD_STR "Loading ramdisk... " #define LOADING_BOOTPART_STR "Loading bootpart... " #ifdef __TILCK_EFI_BOOTLOADER__ typedef ulong video_mode_t; #define LOADING_INITRD_STR_U CONCAT(L, LOADING_INITRD_STR) #else typedef u16 video_mode_t; #endif #define INVALID_VIDEO_MODE ((video_mode_t)~0) #define CMDLINE_BUF_SZ 80 struct generic_video_mode_info { u16 xres; u16 yres; u8 bpp; bool is_text_mode; bool is_usable; }; struct bootloader_intf { /* Methods that must be implemented by each bootloader */ int (*read_key)(void); void (*write_char)(char c); void (*clear_screen)(void); void (*set_color)(u8 color); video_mode_t (*get_curr_video_mode)(void); bool (*set_curr_video_mode)(video_mode_t); void (*get_all_video_modes)(video_mode_t **modes, int *count); bool (*get_mode_info)(video_mode_t m, struct generic_video_mode_info *gi); bool (*load_kernel_file)(const char *path, void **paddr); bool (*load_initrd)(void); char *(*get_cmdline_buf)(u32 *buf_sz); /* Const configuration values that must be provided */ video_mode_t text_mode; bool efi; }; void init_common_bootloader_code(const struct bootloader_intf *); bool common_bootloader_logic(void); video_mode_t find_default_video_mode(void); void *load_kernel_image(void); size_t get_loaded_kernel_mem_sz(void); void write_bootloader_hello_msg(void); void write_ok_msg(void); void write_fail_msg(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/self_tests.h> static int no_deadlock_set_elems; static int no_deadlock_set[MAX_NO_DEADLOCK_SET_ELEMS]; static u64 no_deadlock_set_progress[MAX_NO_DEADLOCK_SET_ELEMS]; static u64 no_deadlock_set_progress_old[MAX_NO_DEADLOCK_SET_ELEMS]; void debug_reset_no_deadlock_set(void) { disable_preemption(); { no_deadlock_set_elems = 0; bzero(no_deadlock_set, sizeof(no_deadlock_set)); bzero(no_deadlock_set_progress, sizeof(no_deadlock_set_progress)); bzero(no_deadlock_set_progress_old, sizeof(no_deadlock_set_progress_old)); } enable_preemption(); } void debug_add_task_to_no_deadlock_set(int tid) { disable_preemption(); { for (int i = 0; i < no_deadlock_set_elems; i++) { VERIFY(no_deadlock_set[i] != tid); } VERIFY(no_deadlock_set_elems < (int)ARRAY_SIZE(no_deadlock_set)); no_deadlock_set[no_deadlock_set_elems++] = tid; } enable_preemption(); } static int nds_find_pos(int tid) { ASSERT(!is_preemption_enabled()); for (int i = 0; i < no_deadlock_set_elems; i++) { if (no_deadlock_set[i] == tid) return i; } return -1; } void debug_remove_task_from_no_deadlock_set(int tid) { int pos; disable_preemption(); { pos = nds_find_pos(tid); if (pos < 0) panic("Task %d not found in no_deadlock_set", tid); no_deadlock_set[pos] = 0; } enable_preemption(); } void debug_no_deadlock_set_report_progress(void) { int tid = get_curr_tid(); int pos; disable_preemption(); { pos = nds_find_pos(tid); VERIFY(pos >= 0); no_deadlock_set_progress[pos]++; } enable_preemption(); } void debug_check_for_deadlock(void) { bool found_runnable = false; struct task *ti; int tid, candidates = 0; disable_preemption(); { for (int i = 0; i < no_deadlock_set_elems; i++) { if (!(tid = no_deadlock_set[i])) continue; if (!(ti = get_task(tid))) continue; candidates++; if (ti->state == TASK_STATE_RUNNABLE) { found_runnable = true; break; } } } enable_preemption(); if (candidates > 0 && !found_runnable) { panic("No runnable task found in no_deadlock_set [%d elems]", candidates); } } static bool nds_should_skip_progress_check(int i, int *tid_ref) { int tid; struct task *ti; ASSERT(!is_preemption_enabled()); if (!no_deadlock_set_progress[i]) return true; if (!(tid = no_deadlock_set[i])) return true; if (!(ti = get_task(tid))) return true; if (ti->state == TASK_STATE_ZOMBIE) return true; if (tid_ref) *tid_ref = tid; return false; } static void nds_dump_progress_of_first_tasks(void) { int counter = 0; ASSERT(!is_preemption_enabled()); printk("Progress of the first tasks: [\n"); for (int i = 0; i < no_deadlock_set_elems && counter < 4; i++) { if (nds_should_skip_progress_check(i, NULL)) continue; if (i == 0) printk("%" PRIu64 " ", no_deadlock_set_progress[i]); else printk(NO_PREFIX "%" PRIu64 " ", no_deadlock_set_progress[i]); counter++; } printk(NO_PREFIX "\n"); printk("]\n\n"); } void debug_check_for_any_progress(void) { int tid; int candidates = 0; disable_preemption(); { for (int i = 0; i < no_deadlock_set_elems; i++) { if (nds_should_skip_progress_check(i, &tid)) continue; if (no_deadlock_set_progress[i] == no_deadlock_set_progress_old[i]) panic("[deadlock?] No progress for tid %d", tid); candidates++; } if (candidates) nds_dump_progress_of_first_tasks(); memcpy(no_deadlock_set_progress_old, no_deadlock_set_progress, sizeof(no_deadlock_set_progress)); } enable_preemption(); } <file_sep>#!/bin/sh exec $SYS_CC -m32 -march=i686 "$@" $CC_POST_FLAGS <file_sep>#!/usr/bin/env sh if [ -z "$1" ]; then echo echo "dump_all_funcs: a script for listing all the functions in a binary " echo "along with their size. Designed to be used in combination with the" echo "'cmp_funcs_size' script. Requires: nm, grep, cut, sort." echo echo "Syntax:" echo " dump_all_funcs <binary>" exit 1 fi if ! [ -f "$1" ]; then echo "The file '$1' does not exist" exit 1 fi nm_opts='--radix=d --print-size' exec nm $nm_opts "$1" | grep -E ' [Tt] ' | cut -d ' ' -f 2,4 | sort -t ' ' -k 2 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static inline void vfs_smart_fs_lock(struct mnt_fs *fs, bool exlock) { /* See the comment in vfs.h about the "fs-lock" funcs */ exlock ? vfs_fs_exlock(fs) : vfs_fs_shlock(fs); } static inline void vfs_smart_fs_unlock(struct mnt_fs *fs, bool exlock) { /* See the comment in vfs.h about the "fs-lock" funcs */ exlock ? vfs_fs_exunlock(fs) : vfs_fs_shunlock(fs); } static inline void vfs_resolve_stack_pop(struct vfs_resolve_int_ctx *ctx) { ASSERT(ctx->ss > 0); ctx->ss--; } static inline struct vfs_path * vfs_resolve_stack_top(struct vfs_resolve_int_ctx *ctx) { return &ctx->paths[ctx->ss - 1]; } static int vfs_resolve_stack_push(struct vfs_resolve_int_ctx *ctx, const char *path, struct vfs_path *p) { const int ss = ctx->ss; if (ss == ARRAY_SIZE(ctx->paths)) return -ELOOP; if (p->fs_path.inode) vfs_retain_inode_at(p); ctx->orig_paths[ss] = path; ctx->paths[ss] = *p; ctx->paths[ss].last_comp = path; ctx->ss++; return 0; } static void vfs_resolve_stack_replace_top(struct vfs_resolve_int_ctx *ctx, const char *path, struct vfs_path *p) { struct vfs_path *cp; ASSERT(ctx->ss > 0); cp = &ctx->paths[--ctx->ss]; if (cp->fs_path.inode) vfs_release_inode_at(cp); /* push cannot fail here because we've just dropped one frame */ vfs_resolve_stack_push(ctx, path, p); } static void __vfs_resolve_get_entry(vfs_inode_ptr_t idir, const char *pc, const char *path, struct vfs_path *rp, bool exlock) { vfs_get_entry(rp->fs, idir, pc, path - pc, &rp->fs_path); rp->last_comp = pc; struct mnt_fs *target_fs = mp_get_retained_at(rp->fs, rp->fs_path.inode); if (target_fs) { /* unlock and release the current (host) struct mnt_fs */ vfs_smart_fs_unlock(rp->fs, exlock); release_obj(rp->fs); rp->fs = target_fs; /* lock the new (target) struct mnt_fs. NOTE: it's already retained */ vfs_smart_fs_lock(rp->fs, exlock); /* Get root's entry */ vfs_get_root_entry(target_fs, &rp->fs_path); } } static void get_locked_retained_root(struct vfs_path *rp, bool exlock) { rp->fs = mp_get_root(); retain_obj(rp->fs); vfs_smart_fs_lock(rp->fs, exlock); vfs_get_root_entry(rp->fs, &rp->fs_path); } /* See the code below */ static int __vfs_resolve(struct vfs_resolve_int_ctx *ctx, bool res_last_sl); static int vfs_resolve_symlink(struct vfs_resolve_int_ctx *ctx, struct vfs_path *np) { int rc; const char *lc = np->last_comp; char *symlink = ctx->sym_paths[ctx->ss - 1]; struct vfs_path *rp = vfs_resolve_stack_top(ctx); struct vfs_path np2; DEBUG_ONLY_UNSAFE(int saved_ss = ctx->ss); ASSERT(np->fs_path.type == VFS_SYMLINK); if ((rc = rp->fs->fsops->readlink(np, symlink)) < 0) return rc; /* readlink() does not zero-terminate the buffer */ symlink[rc] = 0; if (*symlink == '/') { vfs_smart_fs_unlock(rp->fs, ctx->exlock); release_obj(rp->fs); rp = &np2; get_locked_retained_root(rp, ctx->exlock); } /* Push the current vfs path on the stack and call __vfs_resolve() */ if ((rc = vfs_resolve_stack_push(ctx, symlink, rp)) < 0) return rc; rc = __vfs_resolve(ctx, true); /* At the end, resolve() must use exactly 1 stack frame */ ASSERT(ctx->ss == saved_ss + 1); /* * Now replace our new path with stack's top (the result of __vfs_resolve). * Note: we have to override the value of `last_comp` with the older one * because its value does make any sense from the caller's point of view. * Example: * * resolve('/a/b'), where 'b' is a symlink to /x/y/z. * * We expect the last_comp to be 'b', not 'z'. */ *np = *vfs_resolve_stack_top(ctx); np->last_comp = lc; /* * __vfs_resolve() always retains the resolved inode. It might seem unsafe * to release the inode here as its ref-count could drop to 0 until we get * to stack_replace_top(), but actually it's safe because we're holding * *at least* a shared lock on the FS owning this inode. What it matters is * that we retained the inode before releasing the lock (fs change case). */ if (np->fs_path.inode) vfs_release_inode_at(np); if (np->fs && np->fs != rp->fs) vfs_smart_fs_unlock(np->fs, ctx->exlock); vfs_resolve_stack_pop(ctx); return rc; } static inline bool vfs_is_path_dotdot(const char *path) { return path[0] == '.' && path[1] == '.' && slash_or_nul(path[2]); } /* Returns true if the function completely handled the current component */ static bool vfs_handle_cross_fs_dotdot(struct vfs_resolve_int_ctx *ctx, const char *path, struct vfs_path *np) { struct fs_path root_fsp; struct mountpoint *mp; if (!vfs_is_path_dotdot(path)) return false; *np = *vfs_resolve_stack_top(ctx); /* Get the root inode of the current file system */ vfs_get_root_entry(np->fs, &root_fsp); if (root_fsp.inode != np->fs_path.inode) return false; /* we can go further up: no need for special handling */ if (np->fs == mp_get_root()) return true; /* there's nowhere to go further */ /* * Here we've at the root of a FS mounted somewhere other than the absolute * root. Going to '..' from here means going beyond its mount-point. */ mp = mp_get_retained_mp_of(np->fs); ASSERT(mp != NULL); ASSERT(mp->host_fs != np->fs); ASSERT(mp->target_fs == np->fs); ASSERT(mp->host_fs_inode != NULL); /* * Here it's tricky: we have to switch the FS we're using for the * resolving. Current state: * * 1. The current FS is pointed by np->fs * 2. The current FS is locked (exlock or shlock) * 3. The current FS is retained * 4. The current dir in the current FS is retained * 5. The mountpoint where the current FS is retained * * Therefore, we need to (the order matters): * * 1. retain the new FS * 2. unlock the current FS * 3. lock the new FS * 4. release the current FS (now unlocked) * 5. release the mountpoint * * NOTE: the current dir in the current FS won't be released here. That * will happen in vfs_resolve_stack_replace_top(). */ retain_obj(mp->host_fs); vfs_smart_fs_unlock(np->fs, ctx->exlock); vfs_smart_fs_lock(mp->host_fs, ctx->exlock); release_obj(np->fs); release_obj(mp); np->fs = mp->host_fs; vfs_get_entry(np->fs, mp->host_fs_inode, path, 2, &np->fs_path); ASSERT(np->fs_path.inode != NULL); ASSERT(np->fs_path.type == VFS_DIR); return true; } static int vfs_resolve_get_entry(struct vfs_resolve_int_ctx *ctx, const char *path, struct vfs_path *np, bool res_symlinks) { struct vfs_path *rp = vfs_resolve_stack_top(ctx); const char *const lc = rp->last_comp; if (vfs_handle_cross_fs_dotdot(ctx, lc, np)) return 0; *np = *rp; /* * If the path component is empty (e.g. in 2nd component in 'a//b'), just * return keeping the same VFS path. */ if (lc == path) return 0; __vfs_resolve_get_entry(rp->fs_path.inode, lc, path, np, ctx->exlock); if (np->fs_path.type == VFS_SYMLINK && res_symlinks) return vfs_resolve_symlink(ctx, np); return 0; } static inline bool vfs_resolve_have_to_stop(const char *path, struct vfs_path *rp, int *rc) { if (!rp->fs_path.inode) { *rc = path[1] ? -ENOENT /* the path does NOT end here: no such entity */ : 0; /* the path just ends with a trailing slash */ return true; } /* We've found an entity for this path component (pc) */ if (!path[1]) { /* The path ends here, with a trailing slash */ *rc = rp->fs_path.type != VFS_DIR ? -ENOTDIR /* if the entry is not a dir, that's a problem */ : 0; return true; } return false; } static int __vfs_resolve(struct vfs_resolve_int_ctx *ctx, bool res_last_sl) { int rc = 0; const char *path = ctx->orig_paths[ctx->ss - 1]; struct vfs_path *rp = vfs_resolve_stack_top(ctx); struct vfs_path np = *rp; if (!*path) return -ENOENT; /* the struct vfs_path `rp` is assumed to be valid */ ASSERT(rp->fs != NULL); ASSERT(rp->fs_path.inode != NULL); for (; *path; path++) { if (*path != '/') continue; if ((rc = vfs_resolve_get_entry(ctx, path, &np, true))) return rc; if (vfs_resolve_have_to_stop(path, &np, &rc)) break; vfs_resolve_stack_replace_top(ctx, path + 1, &np); } if (*path == 0) { /* path ended without '/': we have to resolve the last component now */ rc = vfs_resolve_get_entry(ctx, path, &np, res_last_sl); } vfs_resolve_stack_replace_top(ctx, np.last_comp, &np); return rc; } static void get_locked_retained_cwd(struct vfs_path *rp, bool exlock) { struct process *pi = get_curr_proc(); kmutex_lock(&pi->fslock); { ASSERT(pi->cwd.fs != NULL); /* Just copy `cwd` into the address pointed by `rp` */ *rp = pi->cwd; retain_obj(rp->fs); } kmutex_unlock(&pi->fslock); vfs_smart_fs_lock(rp->fs, exlock); } /* * Resolves the path, locking the last struct mnt_fs with an exclusive or a * shared lock depending on `exlock`. The last component of the path, if a * symlink, is resolved only with `res_last_sl` is true. * * NOTE: when the function succeedes (-> return 0), the struct mnt_fs is * returned as `rp->fs` RETAINED and LOCKED. The caller is supposed to first * release the right lock with vfs_shunlock() or with vfs_exunlock() and then * to release the FS with release_obj(). */ int vfs_resolve(const char *path, struct vfs_path *rp, bool exlock, bool res_last_sl) { int rc; #ifndef KERNEL_TEST struct task *curr = get_curr_task(); struct vfs_resolve_int_ctx *ctx = (void *)curr->misc_buf->resolve_ctx; STATIC_ASSERT(sizeof(*ctx) <= sizeof(curr->misc_buf->resolve_ctx)); #else /* For the unit tests, just allocate the ctx on the stack */ struct vfs_resolve_int_ctx __stack_allocated_ctx; struct vfs_resolve_int_ctx *ctx = &__stack_allocated_ctx; #endif bzero(rp, sizeof(*rp)); ctx->ss = 0; ctx->exlock = exlock; if (*path == '/') get_locked_retained_root(rp, exlock); else get_locked_retained_cwd(rp, exlock); rc = vfs_resolve_stack_push(ctx, path, rp); ASSERT(rc == 0); rc = __vfs_resolve(ctx, res_last_sl); /* At the end, resolve() must use exactly 1 stack frame */ ASSERT(ctx->ss == 1); /* Store out the last frame in the caller-provided vfs_path */ *rp = ctx->paths[0]; if (rp->fs_path.inode) vfs_release_inode_at(rp); if (rc == 0) { /* * Resolve succeeded. Handle corner cases like 'a/b/c//'. * The last_comp must be 'c//' instead of '/', as returned by * __vfs_resolve(). */ if (*rp->last_comp == '/') { for (; rp->last_comp > path && *--rp->last_comp == '/'; ) { } } } else { /* resolve failed: release the lock and the fs */ vfs_smart_fs_unlock(rp->fs, exlock); release_obj(rp->fs); bzero(rp, sizeof(struct vfs_path)); } return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mocking.h" using namespace testing; extern "C" { #include <tilck/kernel/process.h> #include <tilck/kernel/test/fork.h> } class vfs_mock : public KernelSingleton { public: MOCK_METHOD(int, vfs_dup, (fs_handle h, fs_handle *dup_h), (override)); MOCK_METHOD(void, vfs_close, (fs_handle h), (override)); }; TEST(fork_dup_all_handles, trigger_inside_path) { vfs_mock mock; process pi = {}; fs_handle_base handles[3] = {}, dup_handles[2] = {}; pi.handles[0] = &handles[0]; pi.handles[1] = &handles[1]; pi.handles[2] = &handles[2]; EXPECT_CALL(mock, vfs_dup(&handles[0], _)) .WillOnce( DoAll( SetArgPointee<1>(&dup_handles[0]), Return(0) ) ); EXPECT_CALL(mock, vfs_dup(&handles[1], _)) .WillOnce( DoAll( SetArgPointee<1>(&dup_handles[1]), Return(0) ) ); EXPECT_CALL(mock, vfs_dup(&handles[2], _)) .WillOnce(Return(-1)); EXPECT_CALL(mock, vfs_close(&dup_handles[0])); EXPECT_CALL(mock, vfs_close(&dup_handles[1])); ASSERT_EQ(fork_dup_all_handles(&pi), -ENOMEM); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <sys/wait.h> #include "devshell.h" #include "sysenter.h" extern struct test_cmd_entry *cmds_table; static const char *tt_str[] = { [TT_SHORT] = "tt_short", [TT_MED] = "tt_med", [TT_LONG] = "tt_long", }; static int get_cmds_count(void) { static int value; struct test_cmd_entry *e; if (value) return value; for (e = cmds_table; e->name != NULL; e++) { value++; } return value; } int cmd_selftest(int argc, char **argv) { int rc; if (argc < 1) { fprintf(stderr, PFX "Expected a <selftest> argument.\n"); return 1; } rc = sysenter_call3(TILCK_CMD_SYSCALL, TILCK_CMD_RUN_SELFTEST, argv[0], /* self test name */ NULL); if (rc != 0) { fprintf(stderr, PFX "Invalid selftest '%s'\n", argv[0]); return 1; } return 0; } static u64 get_monotonic_time_ms(void) { int rc; struct timespec tp; rc = clock_gettime(CLOCK_MONOTONIC, &tp); if (rc < 0) { perror("clock_gettime(CLOCK_MONOTONIC) failed"); exit(1); } return (u64)tp.tv_sec * 1000 + (u64)tp.tv_nsec / 1000000; } static bool run_child(int argc, char **argv, cmd_func_type func, const char *name) { static const char *pass_fail_strings[2] = { COLOR_RED STR_FAIL RESET_ATTRS, COLOR_GREEN STR_PASS RESET_ATTRS, }; int child_pid, wstatus, rc; u64 start_ms, end_ms; bool pass; start_ms = get_monotonic_time_ms(); printf(COLOR_YELLOW PFX); printf(COLOR_GREEN STR_RUN RESET_ATTRS "%s" "\n", name); child_pid = fork(); if (child_pid < -1) { perror("fork failed"); exit(1); } if (!child_pid) { exit(func(argc, argv)); } rc = waitpid(child_pid, &wstatus, 0); if (rc < 0) { perror("waitpid() failed"); return false; } if (rc != child_pid) { fprintf(stderr, "waitpid() returned value [%d] " "!= child_pid [%d]\n", rc, child_pid); return false; } end_ms = get_monotonic_time_ms(); pass = WIFEXITED(wstatus) && (WEXITSTATUS(wstatus) == 0); printf(COLOR_YELLOW PFX "%s", pass_fail_strings[pass]); printf("%s (%" PRIu64 " ms)\n\n", name, end_ms - start_ms); return pass; } int cmd_runall(int argc, char **argv) { bool any_failure = false; int to_run = 0, passed = 0; u64 start_ms, end_ms; start_ms = get_monotonic_time_ms(); for (int i = 1; i < get_cmds_count(); i++) { if (!cmds_table[i].enabled_in_st || cmds_table[i].tt == TT_LONG) continue; to_run++; if (!run_child(argc, argv, cmds_table[i].func, cmds_table[i].name)) { any_failure = true; continue; } passed++; } end_ms = get_monotonic_time_ms(); printf(COLOR_YELLOW PFX); printf("------------------------------------------------------------\n"); printf(COLOR_YELLOW PFX); printf(passed == to_run ? COLOR_GREEN : COLOR_RED); printf("Tests passed %d/%d" RESET_ATTRS " ", passed, to_run); printf("(%" PRIu64 " ms)\n\n", end_ms - start_ms); if (dump_coverage) { dump_coverage_files(); } exit(any_failure); } void dump_list_of_commands_and_exit(void) { for (int i = 1; i < get_cmds_count(); i++) { if (cmds_table[i].enabled_in_st) printf("%s %s\n", cmds_table[i].name, tt_str[cmds_table[i].tt]); } exit(0); } void show_common_help_intro(void) { printf("\n"); printf(COLOR_RED "Tilck development shell\n" RESET_ATTRS); printf("This application is a small dev-only utility originally written "); printf("in order to \nallow running simple programs, while proper shells "); printf("like ASH couldn't run on \nTilck yet. Today, " COLOR_YELLOW); printf("ASH works on Tilck" RESET_ATTRS " and this "); printf(COLOR_YELLOW "devshell" RESET_ATTRS " is used as a runner \n"); printf("for system tests (often called 'shellcmds' for this reason).\n\n"); } int cmd_help(int argc, char **argv) { size_t n, row_len; char buf[64]; show_common_help_intro(); printf(COLOR_RED "Built-in commands\n" RESET_ATTRS); printf(" help shows this help\n"); printf(" cd <DIR> change the current working directory\n"); printf(" runall run all the shellcmd tests\n\n"); printf(COLOR_RED "Kernel test commands\n" RESET_ATTRS); row_len = printf(" "); for (int i = 1 /* skip help */; i < get_cmds_count(); i++) { n = sprintf(buf, "%s%s", cmds_table[i].name, i != get_cmds_count()-1 ? "," : ""); if (row_len + n >= 80) { printf("\n"); row_len = printf(" "); } else if (i > 1) { row_len += printf(" "); } row_len += printf("%s", buf); } printf("\n\n"); return 0; } void do_cmd_exit(int code) { if (!dump_coverage && code != 0) { printf(COLOR_YELLOW PFX RESET_ATTRS); printf("The command %sFAILED%s with %s%d%s\n", COLOR_RED, RESET_ATTRS, COLOR_YELLOW, code, RESET_ATTRS); } exit(code); } static void run_cmd(cmd_func_type func, int argc, char **argv) { int exit_code = func(argc, argv); if (dump_coverage) dump_coverage_files(); do_cmd_exit(exit_code); } void run_if_known_command(const char *cmd, int argc, char **argv) { /* Reset all the signal handlers to their default behavior */ for (int i = 1; i < _NSIG; i++) signal(i, SIG_DFL); for (int i = 0; i < get_cmds_count(); i++) if (!strcmp(cmds_table[i].name, cmd)) run_cmd(cmds_table[i].func, argc, argv); } /* * When the tests are compiled with optimizations like -Os or higher, some * memcpy() are optimized out (e.g. fmmap4 test) because the compiler see no * point in performing the memcpy (while we expect to get killed a signal). * * Therefore, we need a simple "forced" memcpy that will always do what we * expect, even with -O3. */ void forced_memcpy(void *dest, const void *src, size_t n) { for (size_t i = 0; i < n / 4; i++) ((volatile u32 *)dest)[i] = ((const volatile u32 *)src)[i]; for (size_t i = 0; i < n % 4; i++) ((volatile u8 *)dest)[i] = ((const volatile u8 *)src)[i]; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/cmdline.h> struct arg_parse_ctx; STATIC void use_kernel_arg(struct arg_parse_ctx *ctx, int arg_num, const char *arg); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/fat32_base.h> #include <tilck/common/utils.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <multiboot.h> #include "basic_term.h" #include "realmode_call.h" #include "vbe.h" #include "mm.h" #include "common.h" video_mode_t selected_mode = VGA_COLOR_TEXT_MODE_80x25; u8 current_device; u32 sectors_per_track; u32 heads_per_cylinder; u32 cylinders_count; ulong initrd_paddr; /* initrd's physical address */ u32 initrd_size; /* initrd's size (used bytes in the fat partition) */ ulong bp_paddr; /* bootpart's physical address */ u32 bp_size; /* bootpart's size (used bytes in the fat partition) */ ulong kernel_file_pa; u32 kernel_file_sz; static struct mem_area ma_buf[64]; struct mem_info g_meminfo; bool load_kernel_file(const char *filepath) { struct fat_hdr *hdr = (struct fat_hdr *)bp_paddr; struct fat_entry *e; ulong free_space; size_t len; if (!(e = fat_search_entry(hdr, fat_get_type(hdr), filepath, NULL))) { printk("ERROR: Unable to open '%s'\n", filepath); return false; } free_space = get_high_usable_mem(&g_meminfo, e->DIR_FileSize); if (IN_RANGE(free_space, bp_paddr, bp_size)) free_space = 0; /* The kernel would overlap with the bootpart */ if (!free_space) { printk("ERROR: No free memory for the kernel file\n"); return false; } kernel_file_pa = 0; kernel_file_sz = 0; len = fat_read_whole_file(hdr, e, (void *)free_space, e->DIR_FileSize); if (len != e->DIR_FileSize) { printk("ERROR: Couldn't read the whole file\n"); return false; } kernel_file_pa = free_space; kernel_file_sz = e->DIR_FileSize; return true; } static void check_cpu_features(void) { get_cpu_features(); if (!x86_cpu_features.edx1.pse) panic("Sorry, but your CPU is too old: no PSE (page size extension)"); } void bootloader_main(void) { multiboot_info_t *mbi; void *entry; bool success; init_common_bootloader_code(&legacy_boot_intf); vga_set_video_mode(VGA_COLOR_TEXT_MODE_80x25); init_bt(); /* Sanity check: the variables in BSS should be zero-filled */ ASSERT(!sectors_per_track); ASSERT(!heads_per_cylinder); ASSERT(!cylinders_count); write_bootloader_hello_msg(); /* Sanity check: realmode_call should be able to return all reg values */ test_rm_call_working(); /* Check if the CPU has the minimum set of features we need */ check_cpu_features(); read_memory_map(ma_buf, sizeof(ma_buf), &g_meminfo); if (BOOTLOADER_POISON_MEMORY) poison_usable_memory(&g_meminfo); alloc_mbi(); success = read_drive_params(current_device, &sectors_per_track, &heads_per_cylinder, &cylinders_count); if (!success) panic("read_write_params failed"); /* Load the BOOTPART from which we'll load the kernel */ success = load_fat_ramdisk(LOADING_BOOTPART_STR, BOOTPART_SEC, KERNEL_PADDR, &bp_paddr, &bp_size, false); /* alloc_extra_page */ if (!success) goto boot_aborted; success = common_bootloader_logic(); if (!success) goto boot_aborted; entry = load_kernel_image(); mbi = setup_multiboot_info(initrd_paddr, initrd_size); /* Jump to the kernel */ asmVolatile("jmp *%%ecx" : /* no output */ : "a" (MULTIBOOT_BOOTLOADER_MAGIC), "b" (mbi), "c" (entry) : /* no clobber */); boot_aborted: panic("Boot aborted"); } <file_sep>/****************************************************************************** * * Module Name: psopcode - Parser/Interpreter opcode information table * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acopcode.h" #include "amlcode.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psopcode") /******************************************************************************* * * NAME: AcpiGbl_AmlOpInfo * * DESCRIPTION: Opcode table. Each entry contains <opcode, type, name, operands> * The name is a simple ascii string, the operand specifier is an * ascii string with one letter per operand. The letter specifies * the operand type. * ******************************************************************************/ /* * Summary of opcode types/flags * Opcodes that have associated namespace objects (AML_NSOBJECT flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_INT_NAMEDFIELD_OP AML_INT_METHODCALL_OP AML_INT_NAMEPATH_OP Opcodes that are "namespace" opcodes (AML_NSOPCODE flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_INT_NAMEDFIELD_OP Opcodes that have an associated namespace node (AML_NSNODE flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_INT_NAMEDFIELD_OP AML_INT_METHODCALL_OP AML_INT_NAMEPATH_OP Opcodes that define named ACPI objects (AML_NAMED flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_INT_NAMEDFIELD_OP Opcodes that contain executable AML as part of the definition that must be deferred until needed AML_METHOD_OP AML_VARIABLE_PACKAGE_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_REGION_OP AML_BUFFER_OP Field opcodes AML_CREATE_FIELD_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP Field "Create" opcodes AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP ******************************************************************************/ /* * Master Opcode information table. A summary of everything we know about each * opcode, all in one place. */ const ACPI_OPCODE_INFO AcpiGbl_AmlOpInfo[AML_NUM_OPCODES] = { /*! [Begin] no source code translation */ /* Index Name Parser Args Interpreter Args ObjectType Class Type Flags */ /* 00 */ ACPI_OP ("Zero", ARGP_ZERO_OP, ARGI_ZERO_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* 01 */ ACPI_OP ("One", ARGP_ONE_OP, ARGI_ONE_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* 02 */ ACPI_OP ("Alias", ARGP_ALIAS_OP, ARGI_ALIAS_OP, ACPI_TYPE_LOCAL_ALIAS, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 03 */ ACPI_OP ("Name", ARGP_NAME_OP, ARGI_NAME_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 04 */ ACPI_OP ("ByteConst", ARGP_BYTE_OP, ARGI_BYTE_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 05 */ ACPI_OP ("WordConst", ARGP_WORD_OP, ARGI_WORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 06 */ ACPI_OP ("DwordConst", ARGP_DWORD_OP, ARGI_DWORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 07 */ ACPI_OP ("String", ARGP_STRING_OP, ARGI_STRING_OP, ACPI_TYPE_STRING, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 08 */ ACPI_OP ("Scope", ARGP_SCOPE_OP, ARGI_SCOPE_OP, ACPI_TYPE_LOCAL_SCOPE, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 09 */ ACPI_OP ("Buffer", ARGP_BUFFER_OP, ARGI_BUFFER_OP, ACPI_TYPE_BUFFER, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER | AML_CONSTANT), /* 0A */ ACPI_OP ("Package", ARGP_PACKAGE_OP, ARGI_PACKAGE_OP, ACPI_TYPE_PACKAGE, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER | AML_CONSTANT), /* 0B */ ACPI_OP ("Method", ARGP_METHOD_OP, ARGI_METHOD_OP, ACPI_TYPE_METHOD, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 0C */ ACPI_OP ("Local0", ARGP_LOCAL0, ARGI_LOCAL0, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0D */ ACPI_OP ("Local1", ARGP_LOCAL1, ARGI_LOCAL1, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0E */ ACPI_OP ("Local2", ARGP_LOCAL2, ARGI_LOCAL2, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0F */ ACPI_OP ("Local3", ARGP_LOCAL3, ARGI_LOCAL3, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 10 */ ACPI_OP ("Local4", ARGP_LOCAL4, ARGI_LOCAL4, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 11 */ ACPI_OP ("Local5", ARGP_LOCAL5, ARGI_LOCAL5, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 12 */ ACPI_OP ("Local6", ARGP_LOCAL6, ARGI_LOCAL6, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 13 */ ACPI_OP ("Local7", ARGP_LOCAL7, ARGI_LOCAL7, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 14 */ ACPI_OP ("Arg0", ARGP_ARG0, ARGI_ARG0, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 15 */ ACPI_OP ("Arg1", ARGP_ARG1, ARGI_ARG1, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 16 */ ACPI_OP ("Arg2", ARGP_ARG2, ARGI_ARG2, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 17 */ ACPI_OP ("Arg3", ARGP_ARG3, ARGI_ARG3, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 18 */ ACPI_OP ("Arg4", ARGP_ARG4, ARGI_ARG4, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 19 */ ACPI_OP ("Arg5", ARGP_ARG5, ARGI_ARG5, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 1A */ ACPI_OP ("Arg6", ARGP_ARG6, ARGI_ARG6, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 1B */ ACPI_OP ("Store", ARGP_STORE_OP, ARGI_STORE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 1C */ ACPI_OP ("RefOf", ARGP_REF_OF_OP, ARGI_REF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R), /* 1D */ ACPI_OP ("Add", ARGP_ADD_OP, ARGI_ADD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 1E */ ACPI_OP ("Concatenate", ARGP_CONCAT_OP, ARGI_CONCAT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 1F */ ACPI_OP ("Subtract", ARGP_SUBTRACT_OP, ARGI_SUBTRACT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 20 */ ACPI_OP ("Increment", ARGP_INCREMENT_OP, ARGI_INCREMENT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 21 */ ACPI_OP ("Decrement", ARGP_DECREMENT_OP, ARGI_DECREMENT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 22 */ ACPI_OP ("Multiply", ARGP_MULTIPLY_OP, ARGI_MULTIPLY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 23 */ ACPI_OP ("Divide", ARGP_DIVIDE_OP, ARGI_DIVIDE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_2T_1R, AML_FLAGS_EXEC_2A_2T_1R | AML_CONSTANT), /* 24 */ ACPI_OP ("ShiftLeft", ARGP_SHIFT_LEFT_OP, ARGI_SHIFT_LEFT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 25 */ ACPI_OP ("ShiftRight", ARGP_SHIFT_RIGHT_OP, ARGI_SHIFT_RIGHT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 26 */ ACPI_OP ("And", ARGP_BIT_AND_OP, ARGI_BIT_AND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 27 */ ACPI_OP ("NAnd", ARGP_BIT_NAND_OP, ARGI_BIT_NAND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 28 */ ACPI_OP ("Or", ARGP_BIT_OR_OP, ARGI_BIT_OR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 29 */ ACPI_OP ("NOr", ARGP_BIT_NOR_OP, ARGI_BIT_NOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 2A */ ACPI_OP ("XOr", ARGP_BIT_XOR_OP, ARGI_BIT_XOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 2B */ ACPI_OP ("Not", ARGP_BIT_NOT_OP, ARGI_BIT_NOT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2C */ ACPI_OP ("FindSetLeftBit", ARGP_FIND_SET_LEFT_BIT_OP, ARGI_FIND_SET_LEFT_BIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2D */ ACPI_OP ("FindSetRightBit", ARGP_FIND_SET_RIGHT_BIT_OP,ARGI_FIND_SET_RIGHT_BIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2E */ ACPI_OP ("DerefOf", ARGP_DEREF_OF_OP, ARGI_DEREF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R), /* 2F */ ACPI_OP ("Notify", ARGP_NOTIFY_OP, ARGI_NOTIFY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_0R, AML_FLAGS_EXEC_2A_0T_0R), /* 30 */ ACPI_OP ("SizeOf", ARGP_SIZE_OF_OP, ARGI_SIZE_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_NO_OPERAND_RESOLVE), /* 31 */ ACPI_OP ("Index", ARGP_INDEX_OP, ARGI_INDEX_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R), /* 32 */ ACPI_OP ("Match", ARGP_MATCH_OP, ARGI_MATCH_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_6A_0T_1R, AML_FLAGS_EXEC_6A_0T_1R | AML_CONSTANT), /* 33 */ ACPI_OP ("CreateDWordField", ARGP_CREATE_DWORD_FIELD_OP,ARGI_CREATE_DWORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 34 */ ACPI_OP ("CreateWordField", ARGP_CREATE_WORD_FIELD_OP, ARGI_CREATE_WORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 35 */ ACPI_OP ("CreateByteField", ARGP_CREATE_BYTE_FIELD_OP, ARGI_CREATE_BYTE_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 36 */ ACPI_OP ("CreateBitField", ARGP_CREATE_BIT_FIELD_OP, ARGI_CREATE_BIT_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 37 */ ACPI_OP ("ObjectType", ARGP_OBJECT_TYPE_OP, ARGI_OBJECT_TYPE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_NO_OPERAND_RESOLVE), /* 38 */ ACPI_OP ("LAnd", ARGP_LAND_OP, ARGI_LAND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL_NUMERIC | AML_CONSTANT), /* 39 */ ACPI_OP ("LOr", ARGP_LOR_OP, ARGI_LOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL_NUMERIC | AML_CONSTANT), /* 3A */ ACPI_OP ("LNot", ARGP_LNOT_OP, ARGI_LNOT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 3B */ ACPI_OP ("LEqual", ARGP_LEQUAL_OP, ARGI_LEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3C */ ACPI_OP ("LGreater", ARGP_LGREATER_OP, ARGI_LGREATER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3D */ ACPI_OP ("LLess", ARGP_LLESS_OP, ARGI_LLESS_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3E */ ACPI_OP ("If", ARGP_IF_OP, ARGI_IF_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 3F */ ACPI_OP ("Else", ARGP_ELSE_OP, ARGI_ELSE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 40 */ ACPI_OP ("While", ARGP_WHILE_OP, ARGI_WHILE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 41 */ ACPI_OP ("Noop", ARGP_NOOP_OP, ARGI_NOOP_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 42 */ ACPI_OP ("Return", ARGP_RETURN_OP, ARGI_RETURN_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 43 */ ACPI_OP ("Break", ARGP_BREAK_OP, ARGI_BREAK_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 44 */ ACPI_OP ("BreakPoint", ARGP_BREAK_POINT_OP, ARGI_BREAK_POINT_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 45 */ ACPI_OP ("Ones", ARGP_ONES_OP, ARGI_ONES_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* Prefixed opcodes (Two-byte opcodes with a prefix op) */ /* 46 */ ACPI_OP ("Mutex", ARGP_MUTEX_OP, ARGI_MUTEX_OP, ACPI_TYPE_MUTEX, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 47 */ ACPI_OP ("Event", ARGP_EVENT_OP, ARGI_EVENT_OP, ACPI_TYPE_EVENT, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED ), /* 48 */ ACPI_OP ("CondRefOf", ARGP_COND_REF_OF_OP, ARGI_COND_REF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 49 */ ACPI_OP ("CreateField", ARGP_CREATE_FIELD_OP, ARGI_CREATE_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_FIELD | AML_CREATE), /* 4A */ ACPI_OP ("Load", ARGP_LOAD_OP, ARGI_LOAD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_0R, AML_FLAGS_EXEC_1A_1T_0R), /* 4B */ ACPI_OP ("Stall", ARGP_STALL_OP, ARGI_STALL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4C */ ACPI_OP ("Sleep", ARGP_SLEEP_OP, ARGI_SLEEP_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4D */ ACPI_OP ("Acquire", ARGP_ACQUIRE_OP, ARGI_ACQUIRE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R), /* 4E */ ACPI_OP ("Signal", ARGP_SIGNAL_OP, ARGI_SIGNAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4F */ ACPI_OP ("Wait", ARGP_WAIT_OP, ARGI_WAIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R), /* 50 */ ACPI_OP ("Reset", ARGP_RESET_OP, ARGI_RESET_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 51 */ ACPI_OP ("Release", ARGP_RELEASE_OP, ARGI_RELEASE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 52 */ ACPI_OP ("FromBCD", ARGP_FROM_BCD_OP, ARGI_FROM_BCD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 53 */ ACPI_OP ("ToBCD", ARGP_TO_BCD_OP, ARGI_TO_BCD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 54 */ ACPI_OP ("Unload", ARGP_UNLOAD_OP, ARGI_UNLOAD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 55 */ ACPI_OP ("Revision", ARGP_REVISION_OP, ARGI_REVISION_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, 0), /* 56 */ ACPI_OP ("Debug", ARGP_DEBUG_OP, ARGI_DEBUG_OP, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, 0), /* 57 */ ACPI_OP ("Fatal", ARGP_FATAL_OP, ARGI_FATAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_3A_0T_0R, AML_FLAGS_EXEC_3A_0T_0R), /* 58 */ ACPI_OP ("OperationRegion", ARGP_REGION_OP, ARGI_REGION_OP, ACPI_TYPE_REGION, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 59 */ ACPI_OP ("Field", ARGP_FIELD_OP, ARGI_FIELD_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD), /* 5A */ ACPI_OP ("Device", ARGP_DEVICE_OP, ARGI_DEVICE_OP, ACPI_TYPE_DEVICE, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5B */ ACPI_OP ("Processor", ARGP_PROCESSOR_OP, ARGI_PROCESSOR_OP, ACPI_TYPE_PROCESSOR, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5C */ ACPI_OP ("PowerResource", ARGP_POWER_RES_OP, ARGI_POWER_RES_OP, ACPI_TYPE_POWER, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5D */ ACPI_OP ("ThermalZone", ARGP_THERMAL_ZONE_OP, ARGI_THERMAL_ZONE_OP, ACPI_TYPE_THERMAL, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5E */ ACPI_OP ("IndexField", ARGP_INDEX_FIELD_OP, ARGI_INDEX_FIELD_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD), /* 5F */ ACPI_OP ("BankField", ARGP_BANK_FIELD_OP, ARGI_BANK_FIELD_OP, ACPI_TYPE_LOCAL_BANK_FIELD, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD | AML_DEFER), /* Internal opcodes that map to invalid AML opcodes */ /* 60 */ ACPI_OP ("LNotEqual", ARGP_LNOTEQUAL_OP, ARGI_LNOTEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 61 */ ACPI_OP ("LLessEqual", ARGP_LLESSEQUAL_OP, ARGI_LLESSEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 62 */ ACPI_OP ("LGreaterEqual", ARGP_LGREATEREQUAL_OP, ARGI_LGREATEREQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 63 */ ACPI_OP ("-NamePath-", ARGP_NAMEPATH_OP, ARGI_NAMEPATH_OP, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_NSOBJECT | AML_NSNODE ), /* 64 */ ACPI_OP ("-MethodCall-", ARGP_METHODCALL_OP, ARGI_METHODCALL_OP, ACPI_TYPE_METHOD, AML_CLASS_METHOD_CALL, AML_TYPE_METHOD_CALL, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE), /* 65 */ ACPI_OP ("-ByteList-", ARGP_BYTELIST_OP, ARGI_BYTELIST_OP, ACPI_TYPE_ANY, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, 0), /* 66 */ ACPI_OP ("-ReservedField-", ARGP_RESERVEDFIELD_OP, ARGI_RESERVEDFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 67 */ ACPI_OP ("-NamedField-", ARGP_NAMEDFIELD_OP, ARGI_NAMEDFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED ), /* 68 */ ACPI_OP ("-AccessField-", ARGP_ACCESSFIELD_OP, ARGI_ACCESSFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 69 */ ACPI_OP ("-StaticString", ARGP_STATICSTRING_OP, ARGI_STATICSTRING_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 6A */ ACPI_OP ("-Return Value-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_RETURN_VALUE, AML_TYPE_RETURN, AML_HAS_ARGS | AML_HAS_RETVAL), /* 6B */ ACPI_OP ("-UNKNOWN_OP-", ARG_NONE, ARG_NONE, ACPI_TYPE_INVALID, AML_CLASS_UNKNOWN, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 6C */ ACPI_OP ("-ASCII_ONLY-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_ASCII, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 6D */ ACPI_OP ("-PREFIX_ONLY-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_PREFIX, AML_TYPE_BOGUS, AML_HAS_ARGS), /* ACPI 2.0 opcodes */ /* 6E */ ACPI_OP ("QwordConst", ARGP_QWORD_OP, ARGI_QWORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 6F */ ACPI_OP ("Package", /* Var */ ARGP_VAR_PACKAGE_OP, ARGI_VAR_PACKAGE_OP, ACPI_TYPE_PACKAGE, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER), /* 70 */ ACPI_OP ("ConcatenateResTemplate", ARGP_CONCAT_RES_OP, ARGI_CONCAT_RES_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 71 */ ACPI_OP ("Mod", ARGP_MOD_OP, ARGI_MOD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 72 */ ACPI_OP ("CreateQWordField", ARGP_CREATE_QWORD_FIELD_OP,ARGI_CREATE_QWORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 73 */ ACPI_OP ("ToBuffer", ARGP_TO_BUFFER_OP, ARGI_TO_BUFFER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 74 */ ACPI_OP ("ToDecimalString", ARGP_TO_DEC_STR_OP, ARGI_TO_DEC_STR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 75 */ ACPI_OP ("ToHexString", ARGP_TO_HEX_STR_OP, ARGI_TO_HEX_STR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 76 */ ACPI_OP ("ToInteger", ARGP_TO_INTEGER_OP, ARGI_TO_INTEGER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 77 */ ACPI_OP ("ToString", ARGP_TO_STRING_OP, ARGI_TO_STRING_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 78 */ ACPI_OP ("CopyObject", ARGP_COPY_OP, ARGI_COPY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 79 */ ACPI_OP ("Mid", ARGP_MID_OP, ARGI_MID_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_3A_1T_1R, AML_FLAGS_EXEC_3A_1T_1R | AML_CONSTANT), /* 7A */ ACPI_OP ("Continue", ARGP_CONTINUE_OP, ARGI_CONTINUE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 7B */ ACPI_OP ("LoadTable", ARGP_LOAD_TABLE_OP, ARGI_LOAD_TABLE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_6A_0T_1R, AML_FLAGS_EXEC_6A_0T_1R), /* 7C */ ACPI_OP ("DataTableRegion", ARGP_DATA_REGION_OP, ARGI_DATA_REGION_OP, ACPI_TYPE_REGION, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 7D */ ACPI_OP ("[EvalSubTree]", ARGP_SCOPE_OP, ARGI_SCOPE_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE), /* ACPI 3.0 opcodes */ /* 7E */ ACPI_OP ("Timer", ARGP_TIMER_OP, ARGI_TIMER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_0A_0T_1R, AML_FLAGS_EXEC_0A_0T_1R), /* ACPI 5.0 opcodes */ /* 7F */ ACPI_OP ("-ConnectField-", ARGP_CONNECTFIELD_OP, ARGI_CONNECTFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 80 */ ACPI_OP ("-ExtAccessField-", ARGP_CONNECTFIELD_OP, ARGI_CONNECTFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* ACPI 6.0 opcodes */ /* 81 */ ACPI_OP ("External", ARGP_EXTERNAL_OP, ARGI_EXTERNAL_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 82 */ ACPI_OP ("Comment", ARGP_COMMENT_OP, ARGI_COMMENT_OP, ACPI_TYPE_STRING, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT) /*! [End] no source code translation !*/ }; <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error task = gdb.lookup_type("struct task") task_p = task.pointer() process = gdb.lookup_type("struct process") process_p = process.pointer() list_node = gdb.lookup_type("struct list_node") list_node_p = list_node.pointer() fs_handle_base = gdb.lookup_type("struct fs_handle_base") fs_handle_base_p = fs_handle_base.pointer() user_mapping = gdb.lookup_type("struct user_mapping") user_mapping_p = user_mapping.pointer() multi_obj_waiter = gdb.lookup_type("struct multi_obj_waiter") multi_obj_waiter_p = multi_obj_waiter.pointer() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/ringbuf.h> #include <tilck/kernel/kmalloc.h> extern inline void ringbuf_reset(struct ringbuf *rb); extern inline bool ringbuf_write_elem1(struct ringbuf *rb, u8 val); extern inline bool ringbuf_read_elem1(struct ringbuf *rb, u8 *elem_ptr); extern inline bool ringbuf_is_empty(struct ringbuf *rb); extern inline bool ringbuf_is_full(struct ringbuf *rb); extern inline size_t ringbuf_get_elems(struct ringbuf *rb); void ringbuf_init(struct ringbuf *rb, size_t max_elems, size_t elem_size, void *buf) { *rb = (struct ringbuf) { .read_pos = 0, .write_pos = 0, .elems = 0, .max_elems = (u32) max_elems, .elem_size = (u32) elem_size, .buf = buf, }; } void ringbuf_destory(struct ringbuf *rb) { bzero(rb, sizeof(struct ringbuf)); } bool ringbuf_write_elem(struct ringbuf *rb, void *elem_ptr) { if (ringbuf_is_full(rb)) return false; memcpy(rb->buf + rb->write_pos * rb->elem_size, elem_ptr, rb->elem_size); rb->write_pos = (rb->write_pos + 1) % rb->max_elems; rb->elems++; return true; } size_t ringbuf_write_bytes(struct ringbuf *rb, u8 *buf, size_t len) { size_t actual_len; size_t actual_len2; ASSERT(rb->elem_size == 1); if (ringbuf_is_full(rb)) return 0; /* * Three cases: * * 1) +-----------------------------------------------------------+ * ^ ^ * write_pos read_pos * * 2) +-----------------------------------------------------------+ * ^ ^ * read_pos write_pos * * 3) +-----------------------------------------------------------+ * ^ * read_pos == write_pos * * Case 1: * We can write at most (read_pos - write_pos) bytes and set at the end * write_pos == read_pos. * * Case 2: * We can write the data in two chunks. * First, write (max_elems - write_pos) bytes, moving write_pos to the * end of the buffer. Second, we can start from the beginning of the buf * and write `read_pos` bytes, until write_pos == read_pos. * * Case 3: * Because we checked that the ringbuffer is *not* full, it is just a * special variant of case 2. * */ if (rb->write_pos < rb->read_pos) { actual_len = MIN(len, rb->read_pos - rb->write_pos); memcpy(rb->buf + rb->write_pos, buf, actual_len); rb->write_pos += actual_len; rb->elems += actual_len; return actual_len; } /* Part one */ actual_len = MIN(len, rb->max_elems - rb->write_pos); memcpy(rb->buf + rb->write_pos, buf, actual_len); rb->write_pos = (rb->write_pos + actual_len) % rb->max_elems; rb->elems += actual_len; /* `actual_len` can be either less than or equal to `len` */ if (actual_len == len) return actual_len; /* it's equal to, we're done */ /* `actual_len` was less than `len`, we have to continue */ /* Part two */ ASSERT(rb->write_pos == 0); actual_len2 = MIN(len - actual_len, rb->read_pos); memcpy(rb->buf, buf + actual_len, actual_len2); rb->write_pos += actual_len2; rb->elems += actual_len2; return actual_len + actual_len2; } size_t ringbuf_read_bytes(struct ringbuf *rb, u8 *buf, size_t len) { size_t actual_len; size_t actual_len2; ASSERT(rb->elem_size == 1); if (ringbuf_is_empty(rb)) return 0; /* * Three cases: * * 1) +-----------------------------------------------------------+ * ^ ^ * read_pos write_pos * * 2) +-----------------------------------------------------------+ * ^ ^ * write_pos read_pos * * 3) +-----------------------------------------------------------+ * ^ * read_pos == write_pos * * Case 1: * We can read at most (write_pos - read_pos) bytes. * * Case 2: * We can read at first (max_elems - read_pos) and then `write_pos` * bytes. * * Case 3: * Because we checked that the ringbug is *not* empty, it is just a * special variant of case 2. */ if (rb->read_pos < rb->write_pos) { actual_len = MIN(len, rb->write_pos - rb->read_pos); memcpy(buf, rb->buf + rb->read_pos, actual_len); rb->read_pos += actual_len; rb->elems -= actual_len; return actual_len; } /* Part one */ actual_len = MIN(len, rb->max_elems - rb->read_pos); memcpy(buf, rb->buf + rb->read_pos, actual_len); rb->read_pos = (rb->read_pos + actual_len) % rb->max_elems; rb->elems -= actual_len; /* `actual_len` can be either less than or equal to `len` */ if (actual_len == len) return actual_len; /* it's equal to, we're done */ /* `actual_len` was less than `len`, we have to continue */ /* Part two */ ASSERT(rb->read_pos == 0); actual_len2 = MIN(len - actual_len, rb->write_pos); memcpy(buf + actual_len, rb->buf, actual_len2); rb->read_pos += actual_len2; rb->elems -= actual_len2; return actual_len + actual_len2; } bool ringbuf_read_elem(struct ringbuf *rb, void *elem_ptr /* out */) { if (ringbuf_is_empty(rb)) return false; memcpy(elem_ptr, rb->buf + rb->read_pos * rb->elem_size, rb->elem_size); rb->read_pos = (rb->read_pos + 1) % rb->max_elems; rb->elems--; return true; } bool ringbuf_unwrite_elem(struct ringbuf *rb, void *elem_ptr /* out */) { if (ringbuf_is_empty(rb)) return false; rb->write_pos = (rb->max_elems + rb->write_pos - 1) % rb->max_elems; rb->elems--; if (elem_ptr) memcpy(elem_ptr, rb->buf + rb->write_pos * rb->elem_size, rb->elem_size); return true; } <file_sep>/****************************************************************************** * * Module Name: nsprepkg - Validation of package objects for predefined names * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acpredef.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsprepkg") /* Local prototypes */ static ACPI_STATUS AcpiNsCheckPackageList ( ACPI_EVALUATE_INFO *Info, const ACPI_PREDEFINED_INFO *Package, ACPI_OPERAND_OBJECT **Elements, UINT32 Count); static ACPI_STATUS AcpiNsCheckPackageElements ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **Elements, UINT8 Type1, UINT32 Count1, UINT8 Type2, UINT32 Count2, UINT32 StartIndex); static ACPI_STATUS AcpiNsCustomPackage ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **Elements, UINT32 Count); /******************************************************************************* * * FUNCTION: AcpiNsCheckPackage * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status * * DESCRIPTION: Check a returned package object for the correct count and * correct type of all sub-objects. * ******************************************************************************/ ACPI_STATUS AcpiNsCheckPackage ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; const ACPI_PREDEFINED_INFO *Package; ACPI_OPERAND_OBJECT **Elements; ACPI_STATUS Status = AE_OK; UINT32 ExpectedCount; UINT32 Count; UINT32 i; ACPI_FUNCTION_NAME (NsCheckPackage); /* The package info for this name is in the next table entry */ Package = Info->Predefined + 1; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s Validating return Package of Type %X, Count %X\n", Info->FullPathname, Package->RetInfo.Type, ReturnObject->Package.Count)); /* * For variable-length Packages, we can safely remove all embedded * and trailing NULL package elements */ AcpiNsRemoveNullElements (Info, Package->RetInfo.Type, ReturnObject); /* Extract package count and elements array */ Elements = ReturnObject->Package.Elements; Count = ReturnObject->Package.Count; /* * Most packages must have at least one element. The only exception * is the variable-length package (ACPI_PTYPE1_VAR). */ if (!Count) { if (Package->RetInfo.Type == ACPI_PTYPE1_VAR) { return (AE_OK); } ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return Package has no elements (empty)")); return (AE_AML_OPERAND_VALUE); } /* * Decode the type of the expected package contents * * PTYPE1 packages contain no subpackages * PTYPE2 packages contain subpackages */ switch (Package->RetInfo.Type) { case ACPI_PTYPE_CUSTOM: Status = AcpiNsCustomPackage (Info, Elements, Count); break; case ACPI_PTYPE1_FIXED: /* * The package count is fixed and there are no subpackages * * If package is too small, exit. * If package is larger than expected, issue warning but continue */ ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2; if (Count < ExpectedCount) { goto PackageTooSmall; } else if (Count > ExpectedCount) { ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Return Package is larger than needed - " "found %u, expected %u\n", Info->FullPathname, Count, ExpectedCount)); } /* Validate all elements of the returned package */ Status = AcpiNsCheckPackageElements (Info, Elements, Package->RetInfo.ObjectType1, Package->RetInfo.Count1, Package->RetInfo.ObjectType2, Package->RetInfo.Count2, 0); break; case ACPI_PTYPE1_VAR: /* * The package count is variable, there are no subpackages, and all * elements must be of the same type */ for (i = 0; i < Count; i++) { Status = AcpiNsCheckObjectType (Info, Elements, Package->RetInfo.ObjectType1, i); if (ACPI_FAILURE (Status)) { return (Status); } Elements++; } break; case ACPI_PTYPE1_OPTION: /* * The package count is variable, there are no subpackages. There are * a fixed number of required elements, and a variable number of * optional elements. * * Check if package is at least as large as the minimum required */ ExpectedCount = Package->RetInfo3.Count; if (Count < ExpectedCount) { goto PackageTooSmall; } /* Variable number of sub-objects */ for (i = 0; i < Count; i++) { if (i < Package->RetInfo3.Count) { /* These are the required package elements (0, 1, or 2) */ Status = AcpiNsCheckObjectType (Info, Elements, Package->RetInfo3.ObjectType[i], i); if (ACPI_FAILURE (Status)) { return (Status); } } else { /* These are the optional package elements */ Status = AcpiNsCheckObjectType (Info, Elements, Package->RetInfo3.TailObjectType, i); if (ACPI_FAILURE (Status)) { return (Status); } } Elements++; } break; case ACPI_PTYPE2_REV_FIXED: /* First element is the (Integer) revision */ Status = AcpiNsCheckObjectType ( Info, Elements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE (Status)) { return (Status); } Elements++; Count--; /* Examine the subpackages */ Status = AcpiNsCheckPackageList (Info, Package, Elements, Count); break; case ACPI_PTYPE2_PKG_COUNT: /* First element is the (Integer) count of subpackages to follow */ Status = AcpiNsCheckObjectType ( Info, Elements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE (Status)) { return (Status); } /* * Count cannot be larger than the parent package length, but allow it * to be smaller. The >= accounts for the Integer above. */ ExpectedCount = (UINT32) (*Elements)->Integer.Value; if (ExpectedCount >= Count) { goto PackageTooSmall; } Count = ExpectedCount; Elements++; /* Examine the subpackages */ Status = AcpiNsCheckPackageList (Info, Package, Elements, Count); break; case ACPI_PTYPE2: case ACPI_PTYPE2_FIXED: case ACPI_PTYPE2_MIN: case ACPI_PTYPE2_COUNT: case ACPI_PTYPE2_FIX_VAR: /* * These types all return a single Package that consists of a * variable number of subpackages. * * First, ensure that the first element is a subpackage. If not, * the BIOS may have incorrectly returned the object as a single * package instead of a Package of Packages (a common error if * there is only one entry). We may be able to repair this by * wrapping the returned Package with a new outer Package. */ if (*Elements && ((*Elements)->Common.Type != ACPI_TYPE_PACKAGE)) { /* Create the new outer package and populate it */ Status = AcpiNsWrapWithPackage ( Info, ReturnObject, ReturnObjectPtr); if (ACPI_FAILURE (Status)) { return (Status); } /* Update locals to point to the new package (of 1 element) */ ReturnObject = *ReturnObjectPtr; Elements = ReturnObject->Package.Elements; Count = 1; } /* Examine the subpackages */ Status = AcpiNsCheckPackageList (Info, Package, Elements, Count); break; case ACPI_PTYPE2_VAR_VAR: /* * Returns a variable list of packages, each with a variable list * of objects. */ break; case ACPI_PTYPE2_UUID_PAIR: /* The package must contain pairs of (UUID + type) */ if (Count & 1) { ExpectedCount = Count + 1; goto PackageTooSmall; } while (Count > 0) { Status = AcpiNsCheckObjectType(Info, Elements, Package->RetInfo.ObjectType1, 0); if (ACPI_FAILURE(Status)) { return (Status); } /* Validate length of the UUID buffer */ if ((*Elements)->Buffer.Length != 16) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Invalid length for UUID Buffer")); return (AE_AML_OPERAND_VALUE); } Status = AcpiNsCheckObjectType(Info, Elements + 1, Package->RetInfo.ObjectType2, 0); if (ACPI_FAILURE(Status)) { return (Status); } Elements += 2; Count -= 2; } break; default: /* Should not get here if predefined info table is correct */ ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Invalid internal return type in table entry: %X", Package->RetInfo.Type)); return (AE_AML_INTERNAL); } return (Status); PackageTooSmall: /* Error exit for the case with an incorrect package count */ ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return Package is too small - found %u elements, expected %u", Count, ExpectedCount)); return (AE_AML_OPERAND_VALUE); } /******************************************************************************* * * FUNCTION: AcpiNsCheckPackageList * * PARAMETERS: Info - Method execution information block * Package - Pointer to package-specific info for method * Elements - Element list of parent package. All elements * of this list should be of type Package. * Count - Count of subpackages * * RETURN: Status * * DESCRIPTION: Examine a list of subpackages * ******************************************************************************/ static ACPI_STATUS AcpiNsCheckPackageList ( ACPI_EVALUATE_INFO *Info, const ACPI_PREDEFINED_INFO *Package, ACPI_OPERAND_OBJECT **Elements, UINT32 Count) { ACPI_OPERAND_OBJECT *SubPackage; ACPI_OPERAND_OBJECT **SubElements; ACPI_STATUS Status; UINT32 ExpectedCount; UINT32 i; UINT32 j; /* * Validate each subpackage in the parent Package * * NOTE: assumes list of subpackages contains no NULL elements. * Any NULL elements should have been removed by earlier call * to AcpiNsRemoveNullElements. */ for (i = 0; i < Count; i++) { SubPackage = *Elements; SubElements = SubPackage->Package.Elements; Info->ParentPackage = SubPackage; /* Each sub-object must be of type Package */ Status = AcpiNsCheckObjectType (Info, &SubPackage, ACPI_RTYPE_PACKAGE, i); if (ACPI_FAILURE (Status)) { return (Status); } /* Examine the different types of expected subpackages */ Info->ParentPackage = SubPackage; switch (Package->RetInfo.Type) { case ACPI_PTYPE2: case ACPI_PTYPE2_PKG_COUNT: case ACPI_PTYPE2_REV_FIXED: /* Each subpackage has a fixed number of elements */ ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2; if (SubPackage->Package.Count < ExpectedCount) { goto PackageTooSmall; } Status = AcpiNsCheckPackageElements (Info, SubElements, Package->RetInfo.ObjectType1, Package->RetInfo.Count1, Package->RetInfo.ObjectType2, Package->RetInfo.Count2, 0); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_PTYPE2_FIX_VAR: /* * Each subpackage has a fixed number of elements and an * optional element */ ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2; if (SubPackage->Package.Count < ExpectedCount) { goto PackageTooSmall; } Status = AcpiNsCheckPackageElements (Info, SubElements, Package->RetInfo.ObjectType1, Package->RetInfo.Count1, Package->RetInfo.ObjectType2, SubPackage->Package.Count - Package->RetInfo.Count1, 0); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_PTYPE2_VAR_VAR: /* * Each subpackage has a fixed or variable number of elements */ break; case ACPI_PTYPE2_FIXED: /* Each subpackage has a fixed length */ ExpectedCount = Package->RetInfo2.Count; if (SubPackage->Package.Count < ExpectedCount) { goto PackageTooSmall; } /* Check the type of each subpackage element */ for (j = 0; j < ExpectedCount; j++) { Status = AcpiNsCheckObjectType (Info, &SubElements[j], Package->RetInfo2.ObjectType[j], j); if (ACPI_FAILURE (Status)) { return (Status); } } break; case ACPI_PTYPE2_MIN: /* Each subpackage has a variable but minimum length */ ExpectedCount = Package->RetInfo.Count1; if (SubPackage->Package.Count < ExpectedCount) { goto PackageTooSmall; } /* Check the type of each subpackage element */ Status = AcpiNsCheckPackageElements (Info, SubElements, Package->RetInfo.ObjectType1, SubPackage->Package.Count, 0, 0, 0); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_PTYPE2_COUNT: /* * First element is the (Integer) count of elements, including * the count field (the ACPI name is NumElements) */ Status = AcpiNsCheckObjectType (Info, SubElements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE (Status)) { return (Status); } /* * Make sure package is large enough for the Count and is * is as large as the minimum size */ ExpectedCount = (UINT32) (*SubElements)->Integer.Value; if (SubPackage->Package.Count < ExpectedCount) { goto PackageTooSmall; } if (SubPackage->Package.Count < Package->RetInfo.Count1) { ExpectedCount = Package->RetInfo.Count1; goto PackageTooSmall; } if (ExpectedCount == 0) { /* * Either the NumEntries element was originally zero or it was * a NULL element and repaired to an Integer of value zero. * In either case, repair it by setting NumEntries to be the * actual size of the subpackage. */ ExpectedCount = SubPackage->Package.Count; (*SubElements)->Integer.Value = ExpectedCount; } /* Check the type of each subpackage element */ Status = AcpiNsCheckPackageElements (Info, (SubElements + 1), Package->RetInfo.ObjectType1, (ExpectedCount - 1), 0, 0, 1); if (ACPI_FAILURE (Status)) { return (Status); } break; default: /* Should not get here, type was validated by caller */ ACPI_ERROR ((AE_INFO, "Invalid Package type: %X", Package->RetInfo.Type)); return (AE_AML_INTERNAL); } Elements++; } return (AE_OK); PackageTooSmall: /* The subpackage count was smaller than required */ ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return SubPackage[%u] is too small - found %u elements, expected %u", i, SubPackage->Package.Count, ExpectedCount)); return (AE_AML_OPERAND_VALUE); } /******************************************************************************* * * FUNCTION: AcpiNsCustomPackage * * PARAMETERS: Info - Method execution information block * Elements - Pointer to the package elements array * Count - Element count for the package * * RETURN: Status * * DESCRIPTION: Check a returned package object for the correct count and * correct type of all sub-objects. * * NOTE: Currently used for the _BIX method only. When needed for two or more * methods, probably a detect/dispatch mechanism will be required. * ******************************************************************************/ static ACPI_STATUS AcpiNsCustomPackage ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **Elements, UINT32 Count) { UINT32 ExpectedCount; UINT32 Version; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_NAME (NsCustomPackage); /* Get version number, must be Integer */ if ((*Elements)->Common.Type != ACPI_TYPE_INTEGER) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return Package has invalid object type for version number")); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } Version = (UINT32) (*Elements)->Integer.Value; ExpectedCount = 21; /* Version 1 */ if (Version == 0) { ExpectedCount = 20; /* Version 0 */ } if (Count < ExpectedCount) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return Package is too small - found %u elements, expected %u", Count, ExpectedCount)); return_ACPI_STATUS (AE_AML_OPERAND_VALUE); } else if (Count > ExpectedCount) { ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Return Package is larger than needed - " "found %u, expected %u\n", Info->FullPathname, Count, ExpectedCount)); } /* Validate all elements of the returned package */ Status = AcpiNsCheckPackageElements (Info, Elements, ACPI_RTYPE_INTEGER, 16, ACPI_RTYPE_STRING, 4, 0); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Version 1 has a single trailing integer */ if (Version > 0) { Status = AcpiNsCheckPackageElements (Info, Elements + 20, ACPI_RTYPE_INTEGER, 1, 0, 0, 20); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiNsCheckPackageElements * * PARAMETERS: Info - Method execution information block * Elements - Pointer to the package elements array * Type1 - Object type for first group * Count1 - Count for first group * Type2 - Object type for second group * Count2 - Count for second group * StartIndex - Start of the first group of elements * * RETURN: Status * * DESCRIPTION: Check that all elements of a package are of the correct object * type. Supports up to two groups of different object types. * ******************************************************************************/ static ACPI_STATUS AcpiNsCheckPackageElements ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **Elements, UINT8 Type1, UINT32 Count1, UINT8 Type2, UINT32 Count2, UINT32 StartIndex) { ACPI_OPERAND_OBJECT **ThisElement = Elements; ACPI_STATUS Status; UINT32 i; /* * Up to two groups of package elements are supported by the data * structure. All elements in each group must be of the same type. * The second group can have a count of zero. */ for (i = 0; i < Count1; i++) { Status = AcpiNsCheckObjectType (Info, ThisElement, Type1, i + StartIndex); if (ACPI_FAILURE (Status)) { return (Status); } ThisElement++; } for (i = 0; i < Count2; i++) { Status = AcpiNsCheckObjectType (Info, ThisElement, Type2, (i + Count1 + StartIndex)); if (ACPI_FAILURE (Status)) { return (Status); } ThisElement++; } return (AE_OK); } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ################################## # Build GNU EFI ################################## # Note: using a gnu-efi's fork on GitHub instead of the official SF repo: # # git://git.code.sf.net/p/gnu-efi/code # # exclusively for performance reasons: SF sometimes is too slow for # CI builds. GNU_EFI_VER="3.0.14" function download_gnu_efi { local ver="$GNU_EFI_VER" local tarname="gnu-efi-$ver.tgz" local url="https://github.com/vvaltchev/gnu-efi-fork.git" download_git_repo_in_cache "$url" $ver $tarname gnu-efi extract_cachefile_tar_gz $tarname -- } function build_gnuefi_arch { echo build_gnuefi_arch pushd $ARCH if ! [ -d gnu-efi ]; then show_work_on_component_msg "GNU-EFI (arch: $ARCH)" reset_cc_vars download_gnu_efi cd gnu-efi if [[ "$HOST_ARCH" != "$ARCH" ]]; then local arch_flags="ARCH=${ARCH_EFI} prefix=${ARCH_GCC_TC}-linux-" else local arch_flags="ARCH=${ARCH_EFI}" fi run_command2 "make $arch_flags -j$BUILD_PAR" build_${ARCH_EFI}.log else show_skip_component_msg "GNU-EFI (arch: $ARCH)" fi popd } function build_gnuefi_build_arch { echo build_gnuefi_build_arch pushd $BUILD_ARCH if ! [ -d gnu-efi ]; then show_work_on_component_msg "GNU-EFI (arch: $BUILD_ARCH)" reset_cc_vars download_gnu_efi cd gnu-efi run_command2 \ "make ARCH=${BUILD_ARCH} -j$BUILD_PAR" build_${BUILD_ARCH}.log else show_skip_component_msg "GNU-EFI (arch: $BUILD_ARCH)" fi popd } all_funcs_list+=(build_gnuefi) function build_gnuefi { build_gnuefi_arch if [[ "$HOST_ARCH" == "$BUILD_ARCH" ]]; then build_gnuefi_build_arch fi } function build_gnuefi_installed_status { if [ -d $TC/$ARCH/gnu-efi ]; then local ret="" if [ -f $TC/$ARCH/gnu-efi/$ARCH_EFI/gnuefi/libgnuefi.a ]; then ret="$ret $ARCH" fi if [[ "$ARCH" != "$BUILD_ARCH" ]]; then if [ -f $TC/$BUILD_ARCH/gnu-efi/$BUILD_ARCH/gnuefi/libgnuefi.a ]; then ret="$ret $BUILD_ARCH" fi fi if [ -n "ret" ]; then echo "installed$ret" else echo "error" fi fi } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # Exit on any error set -e maindir="@CMAKE_SOURCE_DIR@" bdir="@CMAKE_BINARY_DIR@" dest="@CMAKE_BINARY_DIR@/fatpart" tc="@TCROOT@" archgcc="@ARCH_GCC_TC@" strip="@STRIP@" gcctc="@GCC_TOOLCHAIN@" host_arch="@HOST_ARCH@" arch="@ARCH@" spc="@FATPART_CLUSTER_SIZE@" # sectors per cluster if [[ "@HOST_ARCH@" != "i386" ]]; then if [ -f "$gcctc/$archgcc-linux-strip" ]; then strip="$gcctc/$archgcc-linux-strip" fi else if [ ! -f "$strip" ]; then strip="/usr/bin/env strip" fi fi mtoolsdir=$tc/host_${host_arch}/mtools mformat=$mtoolsdir/mformat mlabel=$mtoolsdir/mlabel mmd=$mtoolsdir/mmd mcopy=$mtoolsdir/mcopy mdel=$mtoolsdir/mdel function strip_binary { $strip -s "$1" } function pushd { command pushd "$@" > /dev/null } function popd { command popd "$@" > /dev/null } function link_or_copy { if [ -n "$AZURE_HTTP_USER_AGENT" ]; then cp $1 $2 else ln $1 $2 fi } function create_fatpart_if_necessary { if [ ! -f $dest ]; then # If the 'fatpart' file does not already exist dd status=none if=/dev/zero of=$dest bs=1M count=@INITRD_SZ_MB@ fi } function format_fatpart { # mformat options # -d <N> ; num of FAT copies # -F ; force FAT32 to be used # -c <N> ; sectors per cluster # -T <N> ; total sectors local force_fat32="" if [[ "$spc" == "1" ]]; then force_fat32="-F" fi $mformat -i $dest -d 1 $force_fat32 -c $spc -T @INITRD_SZ_SEC@ :: $mlabel -i $dest ::TILCK } function create_sysroot_skeleton { rm -rf $bdir/sysroot cp -r $maindir/sysroot $bdir/ cd $bdir/sysroot # Remove the README file that is not supposed to be in the actual sysroot rm README } # Copy the shell-script extra system tests in <SYSROOT>/usr/local/tests function add_script_tests { mkdir -p usr/local/tests cp $maindir/tests/system/scripts/* ./usr/local/tests } function add_apps { IFS=";" local all_apps="@USERAPPS_FILES_LIST@;@EXTRA_APPS_LIST@" for x in ${all_apps[@]}; do local name=$(basename -- $x) local dest_dir="usr/bin" if [[ "$name" == "init" ]]; then dest_dir="bin" elif [[ "$name" == "devshell" ]]; then add_script_tests fi cp "$x" $dest_dir strip_binary "$dest_dir/$name" done unset IFS } function add_busybox { if [ -d $tc/$arch/busybox ]; then link_or_copy $tc/$arch/busybox/busybox bin/ fi } function add_fat_test_dir { if [[ "@FAT_TEST_DIR@" == "0" || "@FAT_TEST_DIR@" == "off" || "@FAT_TEST_DIR@" == "OFF" || "@FAT_TEST_DIR@" == "false" ]] then return fi mkdir -p tdir pushd tdir for i in {0..99}; do if [ $i -lt 10 ]; then n="0" else n="" fi echo > test_$n$i done popd } function add_tcc { if [ -z "@EXTRA_TCC_ENABLED@" ]; then return fi local musl=@GCC_TC_SYSROOT@/lib/ mkdir -p lib/tcc cp -r $tc/$arch/tcc/include lib/tcc link_or_copy $tc/$arch/tcc/tcclib.h lib/tcc/include link_or_copy $tc/$arch/tcc/@ARCH@-libtcc1.a lib/tcc link_or_copy $tc/$arch/tcc/@ARCH@-tcc bin/tcc cp -r $tc/$arch/tcc/examples lib/tcc-examples cp -r $musl lib/@ARCH_GCC_TC@-tilck-musl } function add_micropython { if [ -z "@EXTRA_MICROPYTHON_ENABLED@" ]; then return fi link_or_copy $tc/$arch/micropython/ports/unix/micropython usr/bin } function add_fbdoom { if [ -z "@EXTRA_FBDOOM_ENABLED@" ]; then return fi mkdir -p usr/lib/fbDOOM link_or_copy $tc/$arch/fbDOOM/fbdoom/fbdoom.gz usr/lib/fbDOOM if [ -f $tc/$arch/fbDOOM/Doom1.WAD ]; then local wadfile="$tc/$arch/fbDOOM/Doom1.WAD" else local wadfile="$tc/$arch/fbDOOM/freedoom/freedoom1.wad.gz" fi link_or_copy "$wadfile" usr/lib/fbDOOM # Here document ( cat <<'EOF' #!/bin/sh # Exit on failure set -e fbdoomgz="/usr/lib/fbDOOM/fbdoom.gz" wadgz="/usr/lib/fbDOOM/freedoom1.wad.gz" fbdoom="/tmp/fbdoom" if [ -f /usr/lib/fbDOOM/Doom1.WAD ]; then wad="/usr/lib/fbDOOM/Doom1.WAD" else wad="/tmp/freedom1.wad" fi if ! [ -f $fbdoomgz ]; then echo "ERROR: fbDOOM binary $fbdoomgz not found." exit 1 fi if ! [ -f $fbdoom ]; then echo -n "Uncompressing ${fbdoomgz}... " cp $fbdoomgz /tmp gunzip -c /tmp/fbdoom.gz > $fbdoom chmod 755 $fbdoom rm /tmp/fbdoom.gz echo "[ OK ]" fi if ! [ -f $wad ]; then if ! [ -f $wadgz ]; then echo "ERROR: Wad file $wadgz not found." exit 1 fi echo -n "Uncompressing ${wadgz}... " cp $wadgz /tmp gunzip -c /tmp/freedoom1.wad.gz > $wad rm /tmp/freedoom1.wad.gz echo "[ OK ]" fi echo "Running $fbdoom -iwad $wad" exec $fbdoom -iwad $wad EOF ) > usr/bin/fbdoom chmod 755 usr/bin/fbdoom } function add_vim { if [ -z "@EXTRA_VIM_ENABLED@" ]; then return fi mkdir -p usr/lib/vim link_or_copy $tc/$arch/vim/install/vim.gz usr/lib/vim link_or_copy $tc/$arch/vim/install/vr.tgz usr/lib/vim mkdir -p usr/lib/vim/samples cp $maindir/tests/interactive/vim_text_files/* usr/lib/vim/samples/ } function add_tree_cmd { if [ -z "@EXTRA_TREE_CMD_ENABLED@" ]; then return fi link_or_copy $tc/$arch/tree_cmd/tree usr/bin } function add_lua { if [ -z "@EXTRA_LUA_ENABLED@" ]; then return fi if [ -f $tc/$arch/lua/src/lua ]; then link_or_copy $tc/$arch/lua/src/lua bin/ fi if [ -f $tc/$arch/lua/src/luac ]; then link_or_copy $tc/$arch/lua/src/luac bin/ fi } function make_fatpart { create_fatpart_if_necessary format_fatpart # first, create the directories for f in $(find * -type d); do $mmd -i $dest $f done # [debug] Create a hole (file that will be deleted later) in the fatpart. # [debug] This forces the bootloaders to run fat_compact_clusters() and do # [debug] some real work. Otherwise, fat_calculate_used_bytes() will return # [debug] the same as fat_get_first_free_cluster_off() and we won't test # [debug] that fat_compact_clusters() really works. if ! [ -f hole ]; then dd status=none if=/dev/zero of=hole bs=1K count=16 fi $mcopy -i $dest hole ::/hole # [end debug] # then, copy all the files in sysroot for f in $(find * -type f); do if [[ "$(basename -- $f)" == ".gitignore" ]]; then continue; fi # [debug] Skip our hole file if [[ "$(basename -- $f)" == "hole" ]]; then continue; fi # [end debug] $mcopy -i $dest $f ::/$f done # [debug] Delete our hole file $mdel -i $dest ::/hole } # ----------------------------------------------------------------------------- # MAIN # ----------------------------------------------------------------------------- create_sysroot_skeleton add_apps add_fat_test_dir add_busybox add_tcc add_micropython add_fbdoom add_vim add_tree_cmd add_lua make_fatpart <file_sep>/******************************************************************************* * * Module Name: dsutils - Dispatcher utilities * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acdebug.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsutils") /******************************************************************************* * * FUNCTION: AcpiDsClearImplicitReturn * * PARAMETERS: WalkState - Current State * * RETURN: None. * * DESCRIPTION: Clear and remove a reference on an implicit return value. Used * to delete "stale" return values (if enabled, the return value * from every operator is saved at least momentarily, in case the * parent method exits.) * ******************************************************************************/ void AcpiDsClearImplicitReturn ( ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_NAME (DsClearImplicitReturn); /* * Slack must be enabled for this feature */ if (!AcpiGbl_EnableInterpreterSlack) { return; } if (WalkState->ImplicitReturnObj) { /* * Delete any "stale" implicit return. However, in * complex statements, the implicit return value can be * bubbled up several levels. */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Removing reference on stale implicit return obj %p\n", WalkState->ImplicitReturnObj)); AcpiUtRemoveReference (WalkState->ImplicitReturnObj); WalkState->ImplicitReturnObj = NULL; } } /******************************************************************************* * * FUNCTION: AcpiDsDoImplicitReturn * * PARAMETERS: ReturnDesc - The return value * WalkState - Current State * AddReference - True if a reference should be added to the * return object * * RETURN: TRUE if implicit return enabled, FALSE otherwise * * DESCRIPTION: Implements the optional "implicit return". We save the result * of every ASL operator and control method invocation in case the * parent method exit. Before storing a new return value, we * delete the previous return value. * ******************************************************************************/ BOOLEAN AcpiDsDoImplicitReturn ( ACPI_OPERAND_OBJECT *ReturnDesc, ACPI_WALK_STATE *WalkState, BOOLEAN AddReference) { ACPI_FUNCTION_NAME (DsDoImplicitReturn); /* * Slack must be enabled for this feature, and we must * have a valid return object */ if ((!AcpiGbl_EnableInterpreterSlack) || (!ReturnDesc)) { return (FALSE); } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result %p will be implicitly returned; Prev=%p\n", ReturnDesc, WalkState->ImplicitReturnObj)); /* * Delete any "stale" implicit return value first. However, in * complex statements, the implicit return value can be * bubbled up several levels, so we don't clear the value if it * is the same as the ReturnDesc. */ if (WalkState->ImplicitReturnObj) { if (WalkState->ImplicitReturnObj == ReturnDesc) { return (TRUE); } AcpiDsClearImplicitReturn (WalkState); } /* Save the implicit return value, add a reference if requested */ WalkState->ImplicitReturnObj = ReturnDesc; if (AddReference) { AcpiUtAddReference (ReturnDesc); } return (TRUE); } /******************************************************************************* * * FUNCTION: AcpiDsIsResultUsed * * PARAMETERS: Op - Current Op * WalkState - Current State * * RETURN: TRUE if result is used, FALSE otherwise * * DESCRIPTION: Check if a result object will be used by the parent * ******************************************************************************/ BOOLEAN AcpiDsIsResultUsed ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState) { const ACPI_OPCODE_INFO *ParentInfo; ACPI_FUNCTION_TRACE_PTR (DsIsResultUsed, Op); /* Must have both an Op and a Result Object */ if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_UINT8 (TRUE); } /* * We know that this operator is not a * Return() operator (would not come here.) The following code is the * optional support for a so-called "implicit return". Some AML code * assumes that the last value of the method is "implicitly" returned * to the caller. Just save the last result as the return value. * NOTE: this is optional because the ASL language does not actually * support this behavior. */ (void) AcpiDsDoImplicitReturn (WalkState->ResultObj, WalkState, TRUE); /* * Now determine if the parent will use the result * * If there is no parent, or the parent is a ScopeOp, we are executing * at the method level. An executing method typically has no parent, * since each method is parsed separately. A method invoked externally * via ExecuteControlMethod has a ScopeOp as the parent. */ if ((!Op->Common.Parent) || (Op->Common.Parent->Common.AmlOpcode == AML_SCOPE_OP)) { /* No parent, the return value cannot possibly be used */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "At Method level, result of [%s] not used\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode))); return_UINT8 (FALSE); } /* Get info on the parent. The RootOp is AML_SCOPE */ ParentInfo = AcpiPsGetOpcodeInfo (Op->Common.Parent->Common.AmlOpcode); if (ParentInfo->Class == AML_CLASS_UNKNOWN) { ACPI_ERROR ((AE_INFO, "Unknown parent opcode Op=%p", Op)); return_UINT8 (FALSE); } /* * Decide what to do with the result based on the parent. If * the parent opcode will not use the result, delete the object. * Otherwise leave it as is, it will be deleted when it is used * as an operand later. */ switch (ParentInfo->Class) { case AML_CLASS_CONTROL: switch (Op->Common.Parent->Common.AmlOpcode) { case AML_RETURN_OP: /* Never delete the return value associated with a return opcode */ goto ResultUsed; case AML_IF_OP: case AML_WHILE_OP: /* * If we are executing the predicate AND this is the predicate op, * we will use the return value */ if ((WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING) && (WalkState->ControlState->Control.PredicateOp == Op)) { goto ResultUsed; } break; default: /* Ignore other control opcodes */ break; } /* The general control opcode returns no result */ goto ResultNotUsed; case AML_CLASS_CREATE: /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; case AML_CLASS_NAMED_OBJECT: if ((Op->Common.Parent->Common.AmlOpcode == AML_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_DATA_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_INT_EVAL_SUBTREE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BANK_FIELD_OP)) { /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; } goto ResultNotUsed; default: /* * In all other cases. the parent will actually use the return * object, so keep it. */ goto ResultUsed; } ResultUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (TRUE); ResultNotUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] not used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (FALSE); } /******************************************************************************* * * FUNCTION: AcpiDsDeleteResultIfNotUsed * * PARAMETERS: Op - Current parse Op * ResultObj - Result of the operation * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Used after interpretation of an opcode. If there is an internal * result descriptor, check if the parent opcode will actually use * this result. If not, delete the result now so that it will * not become orphaned. * ******************************************************************************/ void AcpiDsDeleteResultIfNotUsed ( ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT *ResultObj, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsDeleteResultIfNotUsed, ResultObj); if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_VOID; } if (!ResultObj) { return_VOID; } if (!AcpiDsIsResultUsed (Op, WalkState)) { /* Must pop the result stack (ObjDesc should be equal to ResultObj) */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_SUCCESS (Status)) { AcpiUtRemoveReference (ResultObj); } } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsResolveOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: Status * * DESCRIPTION: Resolve all operands to their values. Used to prepare * arguments to a control method invocation (a call from one * method to another.) * ******************************************************************************/ ACPI_STATUS AcpiDsResolveOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (DsResolveOperands, WalkState); /* * Attempt to resolve each of the valid operands * Method arguments are passed by reference, not by value. This means * that the actual objects are passed, not copies of the objects. */ for (i = 0; i < WalkState->NumOperands; i++) { Status = AcpiExResolveToValue (&WalkState->Operands[i], WalkState); if (ACPI_FAILURE (Status)) { break; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsClearOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: None * * DESCRIPTION: Clear all operands on the current walk state operand stack. * ******************************************************************************/ void AcpiDsClearOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsClearOperands, WalkState); /* Remove a reference on each operand on the stack */ for (i = 0; i < WalkState->NumOperands; i++) { /* * Remove a reference to all operands, including both * "Arguments" and "Targets". */ AcpiUtRemoveReference (WalkState->Operands[i]); WalkState->Operands[i] = NULL; } WalkState->NumOperands = 0; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperand * * PARAMETERS: WalkState - Current walk state * Arg - Parse object for the argument * ArgIndex - Which argument (zero based) * * RETURN: Status * * DESCRIPTION: Translate a parse tree object that is an argument to an AML * opcode to the equivalent interpreter object. This may include * looking up a name or entering a new name into the internal * namespace. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Arg, UINT32 ArgIndex) { ACPI_STATUS Status = AE_OK; char *NameString; UINT32 NameLength; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PARSE_OBJECT *ParentOp; UINT16 Opcode; ACPI_INTERPRETER_MODE InterpreterMode; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (DsCreateOperand, Arg); /* A valid name must be looked up in the namespace */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && (Arg->Common.Value.String) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Getting a name: Arg=%p\n", Arg)); /* Get the entire name string from the AML stream */ Status = AcpiExGetNameString (ACPI_TYPE_ANY, Arg->Common.Value.Buffer, &NameString, &NameLength); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* All prefixes have been handled, and the name is in NameString */ /* * Special handling for BufferField declarations. This is a deferred * opcode that unfortunately defines the field name as the last * parameter instead of the first. We get here when we are performing * the deferred execution, so the actual name of the field is already * in the namespace. We don't want to attempt to look it up again * because we may be executing in a different scope than where the * actual opcode exists. */ if ((WalkState->DeferredNode) && (WalkState->DeferredNode->Type == ACPI_TYPE_BUFFER_FIELD) && (ArgIndex == (UINT32) ((WalkState->Opcode == AML_CREATE_FIELD_OP) ? 3 : 2))) { ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, WalkState->DeferredNode); Status = AE_OK; } else /* All other opcodes */ { /* * Differentiate between a namespace "create" operation * versus a "lookup" operation (IMODE_LOAD_PASS2 vs. * IMODE_EXECUTE) in order to support the creation of * namespace objects during the execution of control methods. */ ParentOp = Arg->Common.Parent; OpInfo = AcpiPsGetOpcodeInfo (ParentOp->Common.AmlOpcode); if ((OpInfo->Flags & AML_NSNODE) && (ParentOp->Common.AmlOpcode != AML_INT_METHODCALL_OP) && (ParentOp->Common.AmlOpcode != AML_REGION_OP) && (ParentOp->Common.AmlOpcode != AML_INT_NAMEPATH_OP)) { /* Enter name into namespace if not found */ InterpreterMode = ACPI_IMODE_LOAD_PASS2; } else { /* Return a failure if name not found */ InterpreterMode = ACPI_IMODE_EXECUTE; } Status = AcpiNsLookup (WalkState->ScopeInfo, NameString, ACPI_TYPE_ANY, InterpreterMode, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc)); /* * The only case where we pass through (ignore) a NOT_FOUND * error is for the CondRefOf opcode. */ if (Status == AE_NOT_FOUND) { if (ParentOp->Common.AmlOpcode == AML_CONDITIONAL_REF_OF_OP) { /* * For the Conditional Reference op, it's OK if * the name is not found; We just need a way to * indicate this to the interpreter, set the * object to the root */ ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, AcpiGbl_RootNode); Status = AE_OK; } else if (ParentOp->Common.AmlOpcode == AML_EXTERNAL_OP) { /* * This opcode should never appear here. It is used only * by AML disassemblers and is surrounded by an If(0) * by the ASL compiler. * * Therefore, if we see it here, it is a serious error. */ Status = AE_AML_BAD_OPCODE; } else { /* * We just plain didn't find it -- which is a * very serious error at this point */ Status = AE_AML_NAME_NOT_FOUND; } } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, NameString, Status); } } /* Free the namestring created above */ ACPI_FREE (NameString); /* Check status from the lookup */ if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Put the resulting object onto the current object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } else { /* Check for null name case */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * If the name is null, this means that this is an * optional result parameter that was not specified * in the original ASL. Create a Zero Constant for a * placeholder. (Store to a constant is a Noop.) */ Opcode = AML_ZERO_OP; /* Has no arguments! */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Null namepath: Arg=%p\n", Arg)); } else { Opcode = Arg->Common.AmlOpcode; } /* Get the object type of the argument */ OpInfo = AcpiPsGetOpcodeInfo (Opcode); if (OpInfo->ObjectType == ACPI_TYPE_INVALID) { return_ACPI_STATUS (AE_NOT_IMPLEMENTED); } if ((OpInfo->Flags & AML_HAS_RETVAL) || (Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * Use value that was already previously returned * by the evaluation of this argument */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { /* * Only error is underflow, and this indicates * a missing or null operand! */ ACPI_EXCEPTION ((AE_INFO, Status, "Missing or null operand")); return_ACPI_STATUS (Status); } } else { /* Create an ACPI_INTERNAL_OBJECT for the argument */ ObjDesc = AcpiUtCreateInternalObject (OpInfo->ObjectType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize the new object */ Status = AcpiDsInitObjectFromOp ( WalkState, Arg, Opcode, &ObjDesc); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } } /* Put the operand object on the object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperands * * PARAMETERS: WalkState - Current state * FirstArg - First argument of a parser argument tree * * RETURN: Status * * DESCRIPTION: Convert an operator's arguments from a parse tree format to * namespace objects and place those argument object on the object * stack in preparation for evaluation by the interpreter. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsEvaluateNamePath * * PARAMETERS: WalkState - Current state of the parse tree walk, * the opcode of current operation should be * AML_INT_NAMEPATH_OP * * RETURN: Status * * DESCRIPTION: Translate the -NamePath- parse tree object to the equivalent * interpreter object, convert it to value, if needed, duplicate * it, if needed, and push it onto the current result stack. * ****************************************************************************/ ACPI_STATUS AcpiDsEvaluateNamePath ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op = WalkState->Op; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *NewObjDesc; UINT8 Type; ACPI_FUNCTION_TRACE_PTR (DsEvaluateNamePath, WalkState); if (!Op->Common.Parent) { /* This happens after certain exception processing */ goto Exit; } if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_REF_OF_OP)) { /* TBD: Should we specify this feature as a bit of OpInfo->Flags of these opcodes? */ goto Exit; } Status = AcpiDsCreateOperand (WalkState, Op, 0); if (ACPI_FAILURE (Status)) { goto Exit; } if (Op->Common.Flags & ACPI_PARSEOP_TARGET) { NewObjDesc = *Operand; goto PushResult; } Type = (*Operand)->Common.Type; Status = AcpiExResolveToValue (Operand, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } if (Type == ACPI_TYPE_INTEGER) { /* It was incremented by AcpiExResolveToValue */ AcpiUtRemoveReference (*Operand); Status = AcpiUtCopyIobjectToIobject ( *Operand, &NewObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } } else { /* * The object either was anew created or is * a Namespace node - don't decrement it. */ NewObjDesc = *Operand; } /* Cleanup for name-path operand */ Status = AcpiDsObjStackPop (1, WalkState); if (ACPI_FAILURE (Status)) { WalkState->ResultObj = NewObjDesc; goto Exit; } PushResult: WalkState->ResultObj = NewObjDesc; Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); if (ACPI_SUCCESS (Status)) { /* Force to take it from stack */ Op->Common.Flags |= ACPI_PARSEOP_IN_STACK; } Exit: return_ACPI_STATUS (Status); } <file_sep>/****************************************************************************** * * Module Name: dspkginit - Completion of deferred package initialization * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acparser.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("dspkginit") /* Local prototypes */ static void AcpiDsResolvePackageElement ( ACPI_OPERAND_OBJECT **Element); /******************************************************************************* * * FUNCTION: AcpiDsBuildInternalPackageObj * * PARAMETERS: WalkState - Current walk state * Op - Parser object to be translated * ElementCount - Number of elements in the package - this is * the NumElements argument to Package() * ObjDescPtr - Where the ACPI internal object is returned * * RETURN: Status * * DESCRIPTION: Translate a parser Op package object to the equivalent * namespace object * * NOTE: The number of elements in the package will be always be the NumElements * count, regardless of the number of elements in the package list. If * NumElements is smaller, only that many package list elements are used. * if NumElements is larger, the Package object is padded out with * objects of type Uninitialized (as per ACPI spec.) * * Even though the ASL compilers do not allow NumElements to be smaller * than the Package list length (for the fixed length package opcode), some * BIOS code modifies the AML on the fly to adjust the NumElements, and * this code compensates for that. This also provides compatibility with * other AML interpreters. * ******************************************************************************/ ACPI_STATUS AcpiDsBuildInternalPackageObj ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, UINT32 ElementCount, ACPI_OPERAND_OBJECT **ObjDescPtr) { ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Parent; ACPI_OPERAND_OBJECT *ObjDesc = NULL; ACPI_STATUS Status = AE_OK; BOOLEAN ModuleLevelCode = FALSE; UINT16 ReferenceCount; UINT32 Index; UINT32 i; ACPI_FUNCTION_TRACE (DsBuildInternalPackageObj); /* Check if we are executing module level code */ if (WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL) { ModuleLevelCode = TRUE; } /* Find the parent of a possibly nested package */ Parent = Op->Common.Parent; while ((Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP)) { Parent = Parent->Common.Parent; } /* * If we are evaluating a Named package object of the form: * Name (xxxx, Package) * the package object already exists, otherwise it must be created. */ ObjDesc = *ObjDescPtr; if (!ObjDesc) { ObjDesc = AcpiUtCreateInternalObject (ACPI_TYPE_PACKAGE); *ObjDescPtr = ObjDesc; if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } ObjDesc->Package.Node = Parent->Common.Node; } if (ObjDesc->Package.Flags & AOPOBJ_DATA_VALID) /* Just in case */ { return_ACPI_STATUS (AE_OK); } /* * Allocate the element array (array of pointers to the individual * objects) if necessary. the count is based on the NumElements * parameter. Add an extra pointer slot so that the list is always * null terminated. */ if (!ObjDesc->Package.Elements) { ObjDesc->Package.Elements = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) ElementCount + 1) * sizeof (void *)); if (!ObjDesc->Package.Elements) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (AE_NO_MEMORY); } ObjDesc->Package.Count = ElementCount; } /* First arg is element count. Second arg begins the initializer list */ Arg = Op->Common.Value.Arg; Arg = Arg->Common.Next; /* * If we are executing module-level code, we will defer the * full resolution of the package elements in order to support * forward references from the elements. This provides * compatibility with other ACPI implementations. */ if (ModuleLevelCode) { ObjDesc->Package.AmlStart = WalkState->Aml; ObjDesc->Package.AmlLength = 0; ACPI_DEBUG_PRINT_RAW ((ACPI_DB_PARSE, "%s: Deferring resolution of Package elements\n", ACPI_GET_FUNCTION_NAME)); } /* * Initialize the elements of the package, up to the NumElements count. * Package is automatically padded with uninitialized (NULL) elements * if NumElements is greater than the package list length. Likewise, * Package is truncated if NumElements is less than the list length. */ for (i = 0; Arg && (i < ElementCount); i++) { if (Arg->Common.AmlOpcode == AML_INT_RETURN_VALUE_OP) { if (!Arg->Common.Node) { /* * This is the case where an expression has returned a value. * The use of expressions (TermArgs) within individual * package elements is not supported by the AML interpreter, * even though the ASL grammar supports it. Example: * * Name (INT1, 0x1234) * * Name (PKG3, Package () { * Add (INT1, 0xAAAA0000) * }) * * 1) No known AML interpreter supports this type of construct * 2) This fixes a fault if the construct is encountered */ ACPI_EXCEPTION ((AE_INFO, AE_SUPPORT, "Expressions within package elements are not supported")); /* Cleanup the return object, it is not needed */ AcpiUtRemoveReference (WalkState->Results->Results.ObjDesc[0]); return_ACPI_STATUS (AE_SUPPORT); } if (Arg->Common.Node->Type == ACPI_TYPE_METHOD) { /* * A method reference "looks" to the parser to be a method * invocation, so we special case it here */ Arg->Common.AmlOpcode = AML_INT_NAMEPATH_OP; Status = AcpiDsBuildInternalObject ( WalkState, Arg, &ObjDesc->Package.Elements[i]); } else { /* This package element is already built, just get it */ ObjDesc->Package.Elements[i] = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Arg->Common.Node); } } else { Status = AcpiDsBuildInternalObject ( WalkState, Arg, &ObjDesc->Package.Elements[i]); if (Status == AE_NOT_FOUND) { ACPI_ERROR ((AE_INFO, "%-48s", "****DS namepath not found")); } if (!ModuleLevelCode) { /* * Initialize this package element. This function handles the * resolution of named references within the package. * Forward references from module-level code are deferred * until all ACPI tables are loaded. */ AcpiDsInitPackageElement (0, ObjDesc->Package.Elements[i], NULL, &ObjDesc->Package.Elements[i]); } } if (*ObjDescPtr) { /* Existing package, get existing reference count */ ReferenceCount = (*ObjDescPtr)->Common.ReferenceCount; if (ReferenceCount > 1) { /* Make new element ref count match original ref count */ /* TBD: Probably need an AcpiUtAddReferences function */ for (Index = 0; Index < ((UINT32) ReferenceCount - 1); Index++) { AcpiUtAddReference ((ObjDesc->Package.Elements[i])); } } } Arg = Arg->Common.Next; } /* Check for match between NumElements and actual length of PackageList */ if (Arg) { /* * NumElements was exhausted, but there are remaining elements in * the PackageList. Truncate the package to NumElements. * * Note: technically, this is an error, from ACPI spec: "It is an * error for NumElements to be less than the number of elements in * the PackageList". However, we just print a message and no * exception is returned. This provides compatibility with other * ACPI implementations. Some firmware implementations will alter * the NumElements on the fly, possibly creating this type of * ill-formed package object. */ while (Arg) { /* * We must delete any package elements that were created earlier * and are not going to be used because of the package truncation. */ if (Arg->Common.Node) { AcpiUtRemoveReference ( ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Arg->Common.Node)); Arg->Common.Node = NULL; } /* Find out how many elements there really are */ i++; Arg = Arg->Common.Next; } ACPI_INFO (( "Actual Package length (%u) is larger than " "NumElements field (%u), truncated", i, ElementCount)); } else if (i < ElementCount) { /* * Arg list (elements) was exhausted, but we did not reach * NumElements count. * * Note: this is not an error, the package is padded out * with NULLs as per the ACPI specification. */ ACPI_DEBUG_PRINT_RAW ((ACPI_DB_INFO, "%s: Package List length (%u) smaller than NumElements " "count (%u), padded with null elements\n", ACPI_GET_FUNCTION_NAME, i, ElementCount)); } /* Module-level packages will be resolved later */ if (!ModuleLevelCode) { ObjDesc->Package.Flags |= AOPOBJ_DATA_VALID; } Op->Common.Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsInitPackageElement * * PARAMETERS: ACPI_PKG_CALLBACK * * RETURN: Status * * DESCRIPTION: Resolve a named reference element within a package object * ******************************************************************************/ ACPI_STATUS AcpiDsInitPackageElement ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context) { ACPI_OPERAND_OBJECT **ElementPtr; ACPI_FUNCTION_TRACE (DsInitPackageElement); if (!SourceObject) { return_ACPI_STATUS (AE_OK); } /* * The following code is a bit of a hack to workaround a (current) * limitation of the ACPI_PKG_CALLBACK interface. We need a pointer * to the location within the element array because a new object * may be created and stored there. */ if (Context) { /* A direct call was made to this function */ ElementPtr = (ACPI_OPERAND_OBJECT **) Context; } else { /* Call came from AcpiUtWalkPackageTree */ ElementPtr = State->Pkg.ThisTargetObj; } /* We are only interested in reference objects/elements */ if (SourceObject->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) { /* Attempt to resolve the (named) reference to a namespace node */ AcpiDsResolvePackageElement (ElementPtr); } else if (SourceObject->Common.Type == ACPI_TYPE_PACKAGE) { SourceObject->Package.Flags |= AOPOBJ_DATA_VALID; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsResolvePackageElement * * PARAMETERS: ElementPtr - Pointer to a reference object * * RETURN: Possible new element is stored to the indirect ElementPtr * * DESCRIPTION: Resolve a package element that is a reference to a named * object. * ******************************************************************************/ static void AcpiDsResolvePackageElement ( ACPI_OPERAND_OBJECT **ElementPtr) { ACPI_STATUS Status; ACPI_STATUS Status2; ACPI_GENERIC_STATE ScopeInfo; ACPI_OPERAND_OBJECT *Element = *ElementPtr; ACPI_NAMESPACE_NODE *ResolvedNode; ACPI_NAMESPACE_NODE *OriginalNode; char *ExternalPath = ""; ACPI_OBJECT_TYPE Type; ACPI_FUNCTION_TRACE (DsResolvePackageElement); /* Check if reference element is already resolved */ if (Element->Reference.Resolved) { ACPI_DEBUG_PRINT_RAW ((ACPI_DB_PARSE, "%s: Package element is already resolved\n", ACPI_GET_FUNCTION_NAME)); return_VOID; } /* Element must be a reference object of correct type */ ScopeInfo.Scope.Node = Element->Reference.Node; /* Prefix node */ Status = AcpiNsLookup (&ScopeInfo, (char *) Element->Reference.Aml, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, NULL, &ResolvedNode); if (ACPI_FAILURE (Status)) { if ((Status == AE_NOT_FOUND) && AcpiGbl_IgnorePackageResolutionErrors) { /* * Optionally be silent about the NOT_FOUND case for the referenced * name. Although this is potentially a serious problem, * it can generate a lot of noise/errors on platforms whose * firmware carries around a bunch of unused Package objects. * To disable these errors, set this global to TRUE: * AcpiGbl_IgnorePackageResolutionErrors * * If the AML actually tries to use such a package, the unresolved * element(s) will be replaced with NULL elements. */ /* Referenced name not found, set the element to NULL */ AcpiUtRemoveReference (*ElementPtr); *ElementPtr = NULL; return_VOID; } Status2 = AcpiNsExternalizeName (ACPI_UINT32_MAX, (char *) Element->Reference.Aml, NULL, &ExternalPath); ACPI_EXCEPTION ((AE_INFO, Status, "While resolving a named reference package element - %s", ExternalPath)); if (ACPI_SUCCESS (Status2)) { ACPI_FREE (ExternalPath); } /* Could not resolve name, set the element to NULL */ AcpiUtRemoveReference (*ElementPtr); *ElementPtr = NULL; return_VOID; } else if (ResolvedNode->Type == ACPI_TYPE_ANY) { /* Named reference not resolved, return a NULL package element */ ACPI_ERROR ((AE_INFO, "Could not resolve named package element [%4.4s] in [%4.4s]", ResolvedNode->Name.Ascii, ScopeInfo.Scope.Node->Name.Ascii)); *ElementPtr = NULL; return_VOID; } /* * Special handling for Alias objects. We need ResolvedNode to point * to the Alias target. This effectively "resolves" the alias. */ if (ResolvedNode->Type == ACPI_TYPE_LOCAL_ALIAS) { ResolvedNode = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ResolvedNode->Object); } /* Update the reference object */ Element->Reference.Resolved = TRUE; Element->Reference.Node = ResolvedNode; Type = Element->Reference.Node->Type; /* * Attempt to resolve the node to a value before we insert it into * the package. If this is a reference to a common data type, * resolve it immediately. According to the ACPI spec, package * elements can only be "data objects" or method references. * Attempt to resolve to an Integer, Buffer, String or Package. * If cannot, return the named reference (for things like Devices, * Methods, etc.) Buffer Fields and Fields will resolve to simple * objects (int/buf/str/pkg). * * NOTE: References to things like Devices, Methods, Mutexes, etc. * will remain as named references. This behavior is not described * in the ACPI spec, but it appears to be an oversight. */ OriginalNode = ResolvedNode; Status = AcpiExResolveNodeToValue (&ResolvedNode, NULL); if (ACPI_FAILURE (Status)) { return_VOID; } switch (Type) { /* * These object types are a result of named references, so we will * leave them as reference objects. In other words, these types * have no intrinsic "value". */ case ACPI_TYPE_DEVICE: case ACPI_TYPE_THERMAL: case ACPI_TYPE_METHOD: break; case ACPI_TYPE_MUTEX: case ACPI_TYPE_POWER: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_EVENT: case ACPI_TYPE_REGION: /* AcpiExResolveNodeToValue gave these an extra reference */ AcpiUtRemoveReference (OriginalNode->Object); break; default: /* * For all other types - the node was resolved to an actual * operand object with a value, return the object. Remove * a reference on the existing object. */ AcpiUtRemoveReference (Element); *ElementPtr = (ACPI_OPERAND_OBJECT *) ResolvedNode; break; } return_VOID; } <file_sep>#pragma once #include <tilck/common/basic_defs.h> /* * From: http://graphics.stanford.edu/~seander/bithacks.html * with custom adaptions by <NAME>. * * * Original description in the page * ---------------------------------- * * Bit Twiddling Hacks * * By <NAME> * <EMAIL> * * * Individually, the code snippets here are in the public domain * (unless otherwise noted) — feel free to use them however you please. * The aggregate collection and descriptions are (C) 1997-2005 <NAME> * Anderson. The code and descriptions are distributed in the hope that they * will be useful, but WITHOUT ANY WARRANTY and without even the implied * warranty of merchantability or fitness for a particular purpose. * As of May 5, 2005, all the code has been tested thoroughly. Thousands of * people have read it. Moreover, Professor <NAME>, the Dean of Computer * Science at Carnegie Mellon University, has personally tested almost * everything with his Uclid code verification system. What he hasn't tested, * I have checked against all possible inputs on a 32-bit machine. To the * first person to inform me of a legitimate bug in the code, I'll pay a bounty * of US$10 (by check or Paypal). If directed to a charity, I'll pay US$20. */ CONSTEXPR static ALWAYS_INLINE ulong log2_for_power_of_2(ulong v) { ulong r; r = (v & 0xAAAAAAAA) != 0; #ifdef BITS64 r |= (ulong)((v & 0xFFFFFFFF00000000ULL) != 0) << 5; #endif r |= (ulong)((v & 0xFFFF0000) != 0) << 4; r |= (ulong)((v & 0xFF00FF00) != 0) << 3; r |= (ulong)((v & 0xF0F0F0F0) != 0) << 2; r |= (ulong)((v & 0xCCCCCCCC) != 0) << 1; return r; } CONSTEXPR static inline ulong roundup_next_power_of_2(ulong v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; #ifdef BITS64 v |= v >> 32; #endif v++; return v; } /* * Sign extend the `w`-bits wide value in `val` */ CONSTEXPR static ALWAYS_INLINE long sign_extend(long val, ulong w) { ulong m = (sizeof(long) * 8) - w; return (val << m) >> m; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/time.h> #include "devshell.h" #include "sysenter.h" bool running_on_tilck(void) { return getenv("TILCK") != NULL; } void not_on_tilck_message(void) { fprintf(stderr, "[SKIP]: Test designed to run exclusively on Tilck\n"); } int cmd_loop(int argc, char **argv) { printf(PFX "Do a long NOP loop\n"); for (int i = 0; i < (2 * 1000 * 1000 * 1000); i++) { asmVolatile("nop"); } return 0; } int cmd_bad_read(int argc, char **argv) { int ret, err; void *addr = (void *) 0xB0000000; printf("[cmd] req. kernel to read unaccessibile user addr: %p\n", addr); /* write to stdout a buffer unaccessibile for the user */ errno = 0; ret = write(1, addr, 16); err = errno; printf("ret: %i, errno: %i: %s\n", ret, err, strerror(err)); DEVSHELL_CMD_ASSERT(err == EFAULT); addr = (void *) 0xC0000000; printf("[cmd] req. kernel to read unaccessible user addr: %p\n", addr); /* write to stdout a buffer unaccessibile for the user */ errno = 0; ret = write(1, addr, 16); err = errno; printf("ret: %i, errno: %i: %s\n", ret, err, strerror(err)); DEVSHELL_CMD_ASSERT(err == EFAULT); printf("Open with filename invalid ptr\n"); errno = 0; ret = open((char*)0xB0000000, 0); err = errno; printf("ret: %i, errno: %i: %s\n", ret, errno, strerror(errno)); DEVSHELL_CMD_ASSERT(err == EFAULT); return 0; } int cmd_bad_write(int argc, char **argv) { int ret, err; void *addr = (void *) 0xB0000000; errno = 0; ret = syscall(SYS_gettimeofday, addr, NULL); err = errno; printf("ret: %i, errno: %i: %s\n", ret, err, strerror(err)); DEVSHELL_CMD_ASSERT(err == EFAULT); return 0; } int cmd_sysenter(int argc, char **argv) { const char *str = "hello from a sysenter call!\n"; size_t len = strlen(str); int ret = sysenter_call3(4 /* write */, 1 /* stdout */, str, len); printf("The syscall returned: %i\n", ret); printf("sleep (int 0x80)..\n"); usleep(100*1000); printf("after sleep, everything is fine.\n"); printf("same sleep, but with sysenter:\n"); struct timespec req = { .tv_sec = 0, .tv_nsec = 100*1000*1000 }; sysenter_call3(162 /* nanosleep_time32 */, &req, NULL, NULL); printf("after sleep, everything is fine. Prev ret: %i\n", ret); return 0; } int cmd_syscall_perf(int argc, char **argv) { const int major_iters = 100; const int iters = 1000; ull_t start, duration; ull_t best = (ull_t) -1; for (int j = 0; j < major_iters; j++) { start = RDTSC(); for (int i = 0; i < iters; i++) syscall(SYS_getuid); duration = RDTSC() - start; if (duration < best) best = duration; } printf("int 0x80 getuid(): %llu cycles\n", best/iters); best = (ull_t) -1; for (int j = 0; j < major_iters; j++) { start = RDTSC(); for (int i = 0; i < iters; i++) sysenter_call0(SYS_getuid); duration = RDTSC() - start; if (duration < best) best = duration; } printf("sysenter getuid(): %llu cycles\n", best/iters); return 0; } int cmd_fpu(int argc, char **argv) { long double e = 1.0; long double f = 1.0; for (unsigned i = 1; i < 40; i++) { f *= i; e += (1.0 / f); } printf("e(1): %.10Lf\n", e); return 0; } int cmd_fpu_loop(int argc, char **argv) { register double num = 0; for (unsigned i = 0; i < 1000*1000*1000; i++) { if (!(i % 1000000)) printf("%f\n", num); num += 1e-6; } return 0; } /* * Test the scenario where a user copy-on-write happens in the kernel because * of a syscall. */ int cmd_kcow(int argc, char **argv) { static char cow_buf[4096]; int wstatus; int child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { int rc = stat("/", (void *)cow_buf); if (rc != 0) { printf("stat() failed with %d: %s [%d]\n", rc, strerror(errno), errno); exit(1); } exit(0); // exit from the child } waitpid(child_pid, &wstatus, 0); return 0; } static int cloexec_do_exec(int argc, char **argv) { int rc = fprintf(stderr, COLOR_RED "[execve-proc] stderr works [it should NOT!]" RESET_ATTRS "\n"); if (rc < 0) { printf("[execve-proc] write to stderr failed, AS EXPECTED\n"); return 0; } return 1; } int cmd_cloexec(int argc, char **argv) { int pid; int wstatus; const char *devshell_path = get_devshell_path(); if (argc > 0) { if (!strcmp(argv[0], "do_exec")) return cloexec_do_exec(argc, argv); printf(PFX "[cloexec] Invalid sub-command '%s'\n", argv[0]); return 1; } pid = fork(); if (pid < 0) { perror("fork() failed"); exit(1); } if (!pid) { char *argv[] = { "devshell", "-c", "cloexec", "do_exec", NULL }; int flags = fcntl(2 /* stderr */, F_GETFD); int rc = fcntl(2 /* stderr */, F_SETFD, flags | FD_CLOEXEC); if (rc < 0) { perror("fcntl() failed"); exit(1); } fprintf(stderr, "[forked-child] Stderr works [expected to work]\n"); execvpe(devshell_path, argv, shell_env); fprintf(stderr, "execvpe('%s') failed\n", devshell_path); exit(1); } waitpid(pid, &wstatus, 0); if (!WIFEXITED(wstatus)) { printf("Test child killed by signal: %s\n", strsignal(WTERMSIG(wstatus))); exit(1); } return WEXITSTATUS(wstatus); } /* Test scripts testing EXTRA components running on Tilck */ static const char *extra_test_scripts[] = { "tcc", "tar", "sysfs", }; static int run_extra_test(const char *name) { int rc, pid, wstatus; char buf[64]; if (!getenv("TILCK")) { printf(PFX "[SKIP] because we're not running on Tilck\n"); return 0; } printf("%s Extra: %s\n", STR_RUN, name); sprintf(buf, "/initrd/usr/local/tests/%s", name); pid = vfork(); DEVSHELL_CMD_ASSERT(pid >= 0); if (!pid) { rc = execl(buf, buf, NULL); perror("Execve failed"); _exit(1); } rc = waitpid(pid, &wstatus, 0); DEVSHELL_CMD_ASSERT(rc == pid); rc = WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0; printf("%s Extra: %s\n", rc ? STR_PASS : STR_FAIL, name); return !rc; } int cmd_extra(int argc, char **argv) { int rc = 0; for (int i = 0; i < ARRAY_SIZE(extra_test_scripts); i++) { if ((rc = run_extra_test(extra_test_scripts[i]))) break; } return rc; } int cmd_getuids(void) { DEVSHELL_CMD_ASSERT(syscall(SYS_getuid) == 0); DEVSHELL_CMD_ASSERT(syscall(SYS_getgid) == 0); DEVSHELL_CMD_ASSERT(syscall(SYS_geteuid) == 0); #ifdef __i386__ DEVSHELL_CMD_ASSERT(syscall(SYS_getuid16) == 0); DEVSHELL_CMD_ASSERT(syscall(SYS_getgid16) == 0); DEVSHELL_CMD_ASSERT(syscall(SYS_geteuid16) == 0); DEVSHELL_CMD_ASSERT(syscall(SYS_getegid16) == 0); #endif return 0; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) CHECK_C_COMPILER_FLAG( -Wno-unused-but-set-variable FLAG_WNO_UNUSED_BUT_SET_VAR ) unset(acpica_sources_glob) unset(osl_sources_glob) list( APPEND acpica_sources_glob # ACPICA source files "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/dispatcher/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/events/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/executer/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/hardware/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/namespace/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/parser/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/resources/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/tables/*.c" "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/utilities/*.c" ) # Note: for the moment there's no support in Tilck for ACPI's debugger because # some debugger functions are not implemented yet in the OS services layer. # Still, it makes sense to be prepared and check for ACPI_DEBUGGER_ENABLED. if (ACPI_DEBUGGER_ENABLED) list( APPEND acpica_sources_glob "${CMAKE_SOURCE_DIR}/modules/${mod}/acpica/debugger/*.c" ) endif() list( APPEND osl_sources_glob # Our source files (OS Services Layer) "${CMAKE_SOURCE_DIR}/modules/${mod}/*.c" ) file(GLOB acpica_sources ${GLOB_CONF_DEP} ${acpica_sources_glob}) file(GLOB osl_sources ${GLOB_CONF_DEP} ${osl_sources_glob}) add_library( acpica STATIC EXCLUDE_FROM_ALL ${acpica_sources} ) add_library( acpi_osl STATIC EXCLUDE_FROM_ALL ${osl_sources} ) target_include_directories( acpica PUBLIC "${CMAKE_SOURCE_DIR}/include/3rd_party/acpi" ) set( COMMON_ACPI_FLAGS_LIST -DACPI_DEBUG_OUTPUT=1 -Wno-conversion ) if (ACPI_DEBUGGER_ENABLED) list( APPEND COMMON_ACPI_FLAGS_LIST -DACPI_DEBUGGER=1 ) endif() set( ACPICA_FLAGS_LIST -include tilck/common/basic_defs.h -include tilck/common/string_util.h -Wno-unused-variable -fno-sanitize=all ) if (FLAG_WNO_UNUSED_BUT_SET_VAR) list(APPEND ACPICA_FLAGS_LIST -Wno-unused-but-set-variable) endif() JOIN("${COMMON_ACPI_FLAGS_LIST}" ${SPACE} COMMON_ACPI_FLAGS) JOIN("${ACPICA_FLAGS_LIST}" ${SPACE} ACPICA_FLAGS) set(krn_flags "${KERNEL_FLAGS} ${ACTUAL_KERNEL_ONLY_FLAGS}") set(flags "${krn_flags} ${COMMON_ACPI_FLAGS}") set_target_properties( acpica PROPERTIES COMPILE_FLAGS "-D__MOD_ACPICA__ ${flags} ${ACPICA_FLAGS}" ) set_target_properties( acpi_osl PROPERTIES COMPILE_FLAGS "${flags} -D_COMPONENT=ACPI_OS_SERVICES" ) unset(flags) unset(krn_flags) target_link_libraries(${TARGET_NAME} acpica) target_link_libraries(${TARGET_NAME} acpi_osl) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <3rd_party/acpi/acpi.h> ACPI_STATUS osl_init_malloc(void); ACPI_STATUS osl_init_tasks(void); ACPI_STATUS osl_init_irqs(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #if BINTREE_PTR_FUNCS #define CMP(a, b) bintree_insrem_ptr_cmp(a, b, field_off) #else #define CMP(a, b) objval_cmpfun(a, b) #endif #if BINTREE_PTR_FUNCS void * bintree_remove_ptr_internal(void **root_obj_ref, void *obj_or_value, long bintree_offset, long field_off) #else void * bintree_remove_internal(void **root_obj_ref, void *obj_or_value, cmpfun_ptr objval_cmpfun, long bintree_offset) #endif { void **stack[MAX_TREE_HEIGHT]; int stack_size = 0; void *deleted_obj; AVL_BUILD_PATH_TO_OBJ(); deleted_obj = *STACK_TOP(); if (!deleted_obj) return NULL; /* element not found */ bintree_remove_internal_aux(STACK_TOP(), stack, stack_size, bintree_offset); return deleted_obj; } #undef CMP <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/fs/vfs.h> struct mountpoint { REF_COUNTED_OBJECT; vfs_inode_ptr_t host_fs_inode; struct mnt_fs *host_fs; struct mnt_fs *target_fs; }; #define RESOLVE_STACK_SIZE 4 struct vfs_resolve_int_ctx { int ss; /* stack size */ bool exlock; /* true -> use exlock, false -> use shlock */ const char *orig_paths[RESOLVE_STACK_SIZE]; /* original paths stack */ struct vfs_path paths[RESOLVE_STACK_SIZE]; /* vfs paths stack */ char sym_paths[RESOLVE_STACK_SIZE][MAX_PATH]; /* symlinks paths stack */ }; <file_sep>#!/usr/bin/env bash pkg="$1" ci= if [ "$1" == "-ci" ]; then pkg="$2" ci=1 fi if [ "$ci" == 1 ]; then cmd="apt update" else if ! which sudo &> /dev/null; then cmd="su -c \"apt update\"" else cmd="sudo apt update" fi fi echo "Running the command: $cmd" eval $cmd <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <multiboot.h> #include "realmode_call.h" #include "common.h" #include "mm.h" #define BIOS_INT15h_READ_MEMORY_MAP 0xE820 #define BIOS_INT15h_READ_MEMORY_MAP_MAGIC 0x534D4150 static u64 calculate_tot_usable_mem(struct mem_info *mi) { u64 tot_usable = 0; for (u32 i = 0; i < mi->count; i++) { if (mi->mem_areas[i].type == MEM_USABLE) tot_usable += mi->mem_areas[i].len; } return tot_usable; } static void e820_mmap(void *buf, size_t buf_size, struct mem_info *mi) { struct PACKED { u32 base_low; u32 base_hi; u32 len_low; u32 len_hi; u32 type; u32 acpi; } *bios_mem_area = (void *)BIOS_MEM_AREA_BUF; u32 eax, ebx, ecx, edx, esi, edi, flags; struct mem_area *mem_areas = buf; ulong buf_end = (ulong) buf + buf_size; u32 mem_areas_count = 0; /* * NOTE: ES = 0. This means that `bios_mem_area` MUST BE a pointer in the * first 64 KB. In order to support pointers in the 1st MB, realmode_call() * has to be extended to support passing a value for the ES segment register * as well. */ edi = (u32)bios_mem_area; ebx = 0; while (true) { mem_areas->acpi = 1; eax = BIOS_INT15h_READ_MEMORY_MAP; edx = BIOS_INT15h_READ_MEMORY_MAP_MAGIC; ecx = sizeof(*bios_mem_area); realmode_call(&realmode_int_15h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (!ebx) break; if (flags & EFLAGS_CF) { if (mem_areas_count > 0) break; panic("Error while reading memory map: CF set"); } if (eax != BIOS_INT15h_READ_MEMORY_MAP_MAGIC) panic("Error while reading memory map: eax != magic"); struct mem_area m = { .base = bios_mem_area->base_low | ((u64)bios_mem_area->base_hi << 32), .len = bios_mem_area->len_low | ((u64)bios_mem_area->len_hi << 32), .type = bios_mem_area->type, .acpi = bios_mem_area->acpi, }; if (m.base == 0 && m.len == 0) { /* * Hack: on some emulators, like PCem, while emulating an Intel VC440FX * machine, E820 seems to exist and behave well, but in reality it * doesn't report EBX=0 as "end", nor it sets the carry in EFLAGS. * This might be caused by a corrupted firmware. This needs testing on * real hardware. */ break; } if ((ulong)(mem_areas + mem_areas_count) >= buf_end) panic("No enough memory for the memory map"); memcpy(mem_areas + mem_areas_count, &m, sizeof(struct mem_area)); mem_areas_count++; } mi->mem_areas = mem_areas; mi->count = mem_areas_count; } static void legacy_88h_mmap(void *buf, size_t buf_size, struct mem_info *mi) { /* * INT 15h, AH=88h - Get Extended Memory Size * For more, see: http://www.uruk.org/orig-grub/mem64mb.html */ u32 eax = 0x88; u32 ebx = 0; u32 ecx = 0; u32 edx = 0; u32 esi = 0; u32 edi = 0; u32 flags = 0; realmode_call(&realmode_int_15h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (flags & EFLAGS_CF) panic("INT 15h, AH=88h failed"); /* * Now in AX we should get the number of contiguous KB above 1 MB. * For the memory below 1 MB, we can use a conservative hard-coded * configuration. */ mi->mem_areas = buf; mi->mem_areas[0].base = 0x500; mi->mem_areas[0].len = 0x80000 - 0x500; mi->mem_areas[0].type = MEM_USABLE; mi->mem_areas[1].base = 1 * MB; // + 1 MB mi->mem_areas[1].len = (eax & 0xffff) * KB; mi->mem_areas[1].type = MEM_USABLE; mi->count = 2; } void read_memory_map(void *buf, size_t buf_size, struct mem_info *mi) { /* Try first with the most reliable method for machines made after 2002 */ e820_mmap(buf, buf_size, mi); if (calculate_tot_usable_mem(mi) >= 1 * MB) { /* * E820 succeeded. * * Why checking for success in this weird way? On older machines, at * least on emulators like PCem, E820 might appear to work, but reporting * only 640 KB of available memory, despite the VM having more than 16 MB. * So, to detect such weird cases, we just check if E820 detected more * than 1 MB of usable memory. If it didn't, something went seriously * wrong. * * Q: What if E820 legitimately returned a memory map with less than 1 MB * of usable memory? * * A: Tilck cannot boot nor run in any case on x86 with less than 1 MB of * memory. On other architectures, it might be able to, but it won't use * this x86-specific bootloader. */ return; } /* E820 explicitly failed or didn't work properly */ bzero(buf, buf_size); mi->count = 0; /* Try with INT 15h, AX=88h, which should work on any PC */ legacy_88h_mmap(buf, buf_size, mi); } void poison_usable_memory(struct mem_info *mi) { if (!in_hypervisor()) return; /* it's better to use this feature only in VMs */ for (u32 i = 0; i < mi->count; i++) { struct mem_area *ma = mi->mem_areas + i; if (ma->type == MEM_USABLE && ma->base >= MB) { /* Poison only memory regions above the 1st MB */ memset32(TO_PTR(ma->base), FREE_MEM_POISON_VAL, (u32)ma->len / 4); } } } ulong get_usable_mem(struct mem_info *mi, ulong min_paddr, ulong size) { struct mem_area *ma; u64 mbase, mend; for (u32 i = 0; i < mi->count; i++) { ma = mi->mem_areas + i; mbase = ma->base; mend = ma->base + ma->len; if (ma->type != MEM_USABLE) continue; if (mend <= min_paddr) continue; if (mbase < min_paddr) { /* * The memory area starts before the lowest address we can use, * therefore, for our purposes it's as if it just started at min_addr. */ mbase = min_paddr; } if (mbase + size >= (1ull << 32)) continue; if (mend - mbase >= size) { /* Great, we have enough space in this area. */ return mbase; } } return 0; } ulong get_high_usable_mem(struct mem_info *mi, ulong size) { struct mem_area *ma; u64 mbase, mend; u64 candidate = 0; for (u32 i = 0; i < mi->count; i++) { ma = mi->mem_areas + i; mbase = ma->base; mend = ma->base + ma->len; if (ma->type != MEM_USABLE) continue; if (ma->len < size) continue; if (mend - size >= (1ull << 32)) { if ((1ull << 32) - size >= mbase) { /* * This is, by definition, the highest possible addr in the 32-bit * address space. Since it belongs to this free mem area, it's the * ultimate candidate addr. */ candidate = (1ull << 32) - size; break; } /* * The mem area goes beyond the 32-bit limit, but it cannot contain * a chunk of our size within the 32-bit limit. */ continue; } /* If the end of this area is higher than the candidate, take it */ if (mend - size > candidate) candidate = mend - size; } return (ulong)candidate; } <file_sep>from collections import namedtuple from typing import Dict, Any, Optional, Type, Mapping, List import re from sys import stderr class metadata: """By convention, first row is considered a user comment and is not considered in the metadata parsing process. Raises a ValueError if a keyword definition is repeated twice, or if an invalid keyword is provided.""" keyword_expr = re.compile(r"^([A-Z_]+) (.*)") def __init__(self, comment: List[str]) -> None: kw_tuple = namedtuple("kw_tuple", ["parser", "setter", "getter"]) """ If we wanted to use typehinting on kw_tuple, we should derive a new class from namedtuple and set arguments directly from there""" self.depends_on: Optional[List[str]] = None self.group: Optional[str] = None self.realtype: Optional[str] = None self.kw = { "REALTYPE": kw_tuple(self.parse_realtype, self.get_setter("realtype"), self.get_getter("realtype")), "DEPENDS_ON": kw_tuple(self.parse_depends_on, self.get_setter("depends_on"), self.get_getter("depends_on")), "GROUP": kw_tuple(self.parse_group, self.get_setter("group"), self.get_getter("group")), } for i, line in enumerate(comment): match = self.keyword_expr.match(line) if not match: continue key = match.group(1) if i == 0: if key in self.kw: msg = """WARNING: First line uses a reserved keyword: {}. This will be ignored.""" stderr.write(msg.format(key)) continue elif key not in self.kw: msg = "{} is not a valid metadata keyword." raise ValueError(msg.format(key)) elif self.kw[key].getter() is not None: msg = "Key {} has already a value associated to itself." raise ValueError(msg.format(key)) setter = self.kw[key].setter parsed_value = self.kw[key].parser(match.group(2)) setter(parsed_value) assert(self.kw[key].getter() is not None) def get_setter(self, var_name: str): def setter(val) -> None: nonlocal self self.__dict__[var_name] = val return setter def get_getter(self, var_name: str): def getter(): nonlocal self return self.__dict__[var_name] return getter def parse_realtype(self, string: str) -> str: return string def parse_group(self, string: str) -> str: return string def parse_depends_on(self, string: str) -> List[str]: return [s.strip() for s in string.split(",")] class cmake_var: """ General class used when we don't need particular conversions or validation. When either more validation or special serialization is needed, this class can be used as base. """ def __init__(self, value: str) -> None: self.value: Any = value self.metadata: Optional[metadata] = None def serialize(self) -> str: return self.value class cmake_var_bool(cmake_var): NORMALIZED_BOOLS: Dict[str, bool] = { "ON" : True, "OFF": False, "1" : True, "0" : False, "TRUE": True, "FALSE": False, } def __init__(self, value: str) -> None: self.value: bool = self.NORMALIZED_BOOLS[value] self.metadata: Optional[metadata] = None def serialize(self) -> str: return "ON" if self.value else "OFF" def build_cmake_var(type: str, cmake_var_str: str, comment: List[str] ) -> cmake_var: """ Factory function that associates the correct type of variable and handles metadata, provided by the row's associated comments. """ cmake_type_str_to_class: Mapping[str, Type[cmake_var]] = { "BOOL" : cmake_var_bool, "INTERNAL" : cmake_var, "FILEPATH": cmake_var, "STRING" : cmake_var, } loaded_metadata = metadata(comment) if loaded_metadata.realtype is not None: type = loaded_metadata.realtype class_obj = cmake_type_str_to_class[type] obj = class_obj(cmake_var_str) obj.metadata = loaded_metadata return obj <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct term_action; struct term_interface; typedef void term; extern const struct term_interface *video_term_intf; extern const struct term_interface *serial_term_intf; #define MAX_TERM_WRITE_LEN ((u32)(64 * KB - 1)) struct video_interface { /* Main functions */ void (*set_char_at)(u16 row, u16 col, u16 entry); void (*set_row)(u16 row, u16 *data, bool fpu_allowed); void (*clear_row)(u16 row_num, u8 color); /* Cursor management */ void (*move_cursor)(u16 row, u16 col, int color); void (*enable_cursor)(void); void (*disable_cursor)(void); /* Other (optional) */ void (*scroll_one_line_up)(void); void (*redraw_static_elements)(void); void (*disable_static_elems_refresh)(void); void (*enable_static_elems_refresh)(void); }; enum term_type { term_type_video, term_type_serial, }; struct term_params { u16 rows; u16 cols; enum term_type type; const struct video_interface *vi; }; enum term_fret { TERM_FILTER_WRITE_BLANK, TERM_FILTER_WRITE_C, }; typedef enum term_fret (*term_filter)(u8 *c, /* in/out */ u8 *color, /* in/out */ struct term_action *a, /* out */ void *ctx); /* in */ struct term_interface { enum term_type (*get_type)(void); bool (*is_initialized)(term *t); void (*get_params)(term *t, struct term_params *out); void (*write)(term *t, const char *buf, size_t len, u8 color); void (*scroll_up)(term *t, u32 lines); void (*scroll_down)(term *t, u32 lines); void (*set_col_offset)(term *t, int off); void (*pause_output)(term *t); void (*restart_output)(term *t); void (*set_filter)(term *t, term_filter func, void *ctx); /* * The first term must be pre-allocated but _not_ pre-initialized. * It is expected to require init() to be called on it before use. */ term *(*get_first_term)(void); int (*video_term_init)(term *t, const struct video_interface *vi, u16 rows, u16 cols, int rows_buf); /* note: < 0 means default value */ int (*serial_term_init)(term *t, u16 serial_port_fwd); term *(*alloc)(void); void (*free)(term *t); void (*dispose)(term *t); /* --- debug funcs --- */ void (*debug_dump_font_table)(term *t); }; void set_curr_video_term(term *t); void register_term_intf(const struct term_interface *intf); void init_first_video_term(const struct video_interface *vi, u16 rows, u16 cols, int rows_buf); void init_first_serial_term(u16 port); void init_first_term_null(void); void process_term_read_info(struct term_params *out); static ALWAYS_INLINE term *get_curr_term(void) { extern term *__curr_term; return __curr_term; } static ALWAYS_INLINE const struct term_interface *get_curr_term_intf(void) { extern const struct term_interface *__curr_term_intf; return __curr_term_intf; } static ALWAYS_INLINE bool term_is_initialized(void) { extern term *__curr_term; extern const struct term_interface *__curr_term_intf; if (!__curr_term_intf) return false; return __curr_term_intf->is_initialized(__curr_term); } static ALWAYS_INLINE void term_write(const char *buf, size_t len, u8 color) { extern term *__curr_term; extern const struct term_interface *__curr_term_intf; __curr_term_intf->write(__curr_term, buf, len, color); } static ALWAYS_INLINE void term_pause_output(void) { extern term *__curr_term; extern const struct term_interface *__curr_term_intf; __curr_term_intf->pause_output(__curr_term); } static ALWAYS_INLINE void term_restart_output(void) { extern term *__curr_term; extern const struct term_interface *__curr_term_intf; __curr_term_intf->restart_output(__curr_term); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/list.h> struct task; enum wo_type { WOBJ_NONE = 0, WOBJ_KMUTEX, WOBJ_KCOND, WOBJ_TASK, WOBJ_SEM, /* Special "meta-object" types */ WOBJ_MWO_WAITER, /* struct multi_obj_waiter */ WOBJ_MWO_ELEM /* a pointer to this wobj is castable to mwobj_elem */ }; #define NO_EXTRA 0 #define WEXTRA_TASK_STOPPED 1 #define WEXTRA_TASK_CONTINUED 2 /* * wait_obj is used internally in struct task for referring to an object that * is blocking that task (keeping it in a sleep state). */ struct wait_obj { union { ATOMIC(void *) __ptr; /* ptr to the object we're waiting for */ long __data; /* data field (id) describing the obj */ }; u32 extra; /* extra info about the waiting reason */ enum wo_type type; /* type of the object we're waiting for */ struct list_node wait_list_node; /* node in waited object's waiting list */ }; /* * Struct used as element in `multi_obj_waiter` using `wait_obj` through * composition. */ struct mwobj_elem { struct wait_obj wobj; struct task *ti; /* Task owning this wait obj */ enum wo_type type; /* Actual object type. NOTE: wobj.type cannot be * used because it have to be equal to * WOBJ_MULTI_ELEM. */ }; /* * Heap-allocated object on which struct task->wobj "waits" when the task is * waiting on multiple objects. * * How it works * --------------- * */ struct multi_obj_waiter { int count; /* number of `struct mwobj_elem` elements */ struct mwobj_elem elems[]; /* variable-size array */ }; void wait_obj_set(struct wait_obj *wo, enum wo_type type, void *ptr_or_data, u32 extra, struct list *wait_list); void *wait_obj_reset(struct wait_obj *wo); static ALWAYS_INLINE void * wait_obj_get_ptr(struct wait_obj *wo) { return atomic_load_explicit(&wo->__ptr, mo_relaxed); } static ALWAYS_INLINE long wait_obj_get_data(struct wait_obj *wo) { return wo->__data; } void prepare_to_wait_on(enum wo_type type, void *ptr_or_data, u32 extra, struct list *wait_list); void *wake_up(struct task *ti); struct multi_obj_waiter *allocate_mobj_waiter(int elems); void free_mobj_waiter(struct multi_obj_waiter *w); void mobj_waiter_reset(struct mwobj_elem *e); void mobj_waiter_reset2(struct multi_obj_waiter *w, int index); void mobj_waiter_set(struct multi_obj_waiter *w, int index, enum wo_type type, void *ptr, struct list *wait_list); void prepare_to_wait_on_multi_obj(struct multi_obj_waiter *w); /* * The semaphore implementation used for locking in kernel mode. */ struct ksem { int max; volatile int counter; struct list wait_list; }; #define KSEM_NO_MAX -1 #define KSEM_WAIT_FOREVER -1 #define KSEM_NO_WAIT 0 #define STATIC_KSEM_INIT(s, val, max) \ { \ .max = (max), \ .counter = (val), \ .wait_list = STATIC_LIST_INIT(s.wait_list),\ } void ksem_init(struct ksem *s, int val, int max); void ksem_destroy(struct ksem *s); int ksem_wait(struct ksem *s, int units, int timeout_ticks); int ksem_signal(struct ksem *s, int units); /* * The mutex implementation used for locking in kernel mode. */ struct kmutex { struct task *owner_task; u32 flags; u32 lock_count; // Valid when the mutex is recursive struct list wait_list; #if KMUTEX_STATS_ENABLED u32 num_waiters; u32 max_num_waiters; #endif }; #define STATIC_KMUTEX_INIT(m, fl) \ { \ .owner_task = NULL, \ .flags = 0, \ .lock_count = 0, \ .wait_list = STATIC_LIST_INIT(m.wait_list), \ } #define KMUTEX_FL_RECURSIVE (1 << 0) #if KERNEL_SELFTESTS /* * Magic kmutex flag, existing only when self tests are compiled-in and * designed specifically for selftest_kmutex_ord_med(). See the comments * in se_kmutex.c for more about it. */ #define KMUTEX_FL_ALLOW_LOCK_WITH_PREEMPT_DISABLED (1 << 1) #endif void kmutex_init(struct kmutex *m, u32 flags); void kmutex_lock(struct kmutex *m); bool kmutex_trylock(struct kmutex *m); void kmutex_unlock(struct kmutex *m); void kmutex_destroy(struct kmutex *m); #if DEBUG_CHECKS bool kmutex_is_curr_task_holding_lock(struct kmutex *m); #endif /* * A basic implementation of condition variables similar to the pthread ones. */ struct kcond { struct list wait_list; }; #define STATIC_KCOND_INIT(s) \ { \ .wait_list = STATIC_LIST_INIT(s.wait_list),\ } #define KCOND_WAIT_FOREVER 0 void kcond_init(struct kcond *c); void kcond_destory(struct kcond *c); void kcond_signal_one(struct kcond *c); void kcond_signal_all(struct kcond *c); bool kcond_wait(struct kcond *c, struct kmutex *m, u32 timeout_ticks); bool kcond_is_anyone_waiting(struct kcond *c); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/common/arch/generic_x86/cpu_features.h> volatile struct x86_cpu_features x86_cpu_features; void get_cpu_features(void) { STATIC_ASSERT(sizeof(x86_cpu_features.edx1) == 32); STATIC_ASSERT(sizeof(x86_cpu_features.ecx1) == 32); u32 a = 0, b = 0, c = 0, d = 0; struct x86_cpu_features *f = (void *)&x86_cpu_features; cpuid(0, &a, &b, &c, &d); f->max_basic_cpuid_cmd = a; memcpy(f->vendor_id, &b, 4); memcpy(f->vendor_id + 4, &d, 4); memcpy(f->vendor_id + 8, &c, 4); /* If CPUID is supported, CPUID[1] is always supported */ cpuid(1, &a, &b, &c, &d); for (u32 bit = 0; bit < 32; bit++) ((bool *)&f->edx1)[bit] = !!(d & (1u << bit)); for (u32 bit = 0; bit < 32; bit++) ((bool *)&f->ecx1)[bit] = !!(c & (1u << bit)); if (f->max_basic_cpuid_cmd < 7) goto ext_features; /* CPUID[7] supported */ if (f->ecx1.avx) { cpuid(7, &a, &b, &c, &d); f->avx2 = !!(b & (1 << 5)) && !!(b & (1 << 3)) && !!(b & (1 << 8)); } ext_features: cpuid(0x80000000, &a, &b, &c, &d); f->max_ext_cpuid_cmd = a; if (f->max_ext_cpuid_cmd < 0x80000007) return; /* CPUID[0x80000007] supported */ cpuid(0x80000007, &a, &b, &c, &d); f->invariant_TSC = !!(d & (1 << 8)); if (f->max_ext_cpuid_cmd < 0x80000008) return; /* CPUID[0x80000008] supported */ cpuid(0x80000008, &a, &b, &c, &d); f->phys_addr_bits = a & 0xff; f->virt_addr_bits = (a >> 8) & 0xff; } #ifdef __TILCK_KERNEL__ static const char *edx1_features[] = { "fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mse", "cx8", "apic", NULL, "sep", "mtrr", "pge", "mca", "cmov", "pat", "pse36", "psn", "clfsh", NULL, "ds", "acpi", "mmx", "fxsr", "sse", "sse2", "ss", "htt", "tm", "ia64", "pbe", }; static const char *ecx1_features[] = { "sse3", "pclmulqdq", "dtes64", "monitor", "ds_cpl", "vmx", "smx", "est", "tm2", "ssse3", "cnxt_id", "sdbg", "fma", "cx16", "xtpr", "pdcm", NULL, "pcid", "dca", "sse41", "sse42", "x2apic", "movbe", "popcnt", "tsc_deadline", "aes", "xsave", "osxsave", "avx", "f16c", "rdrnd", "hypervisor", }; void dump_x86_features(void) { char buf[256]; u32 w = 0; printk("CPU: %s\n", x86_cpu_features.vendor_id); bool *flags[] = { (bool *)&x86_cpu_features.edx1, (bool *)&x86_cpu_features.ecx1, }; const char **strings[] = {edx1_features, ecx1_features}; for (u32 j = 0; j < 2; j++) { for (u32 i = 0; i < 32; i++) { if (!strings[j][i]) continue; if (flags[j][i]) w += (u32)snprintk(buf + w, sizeof(buf) - w, "%s ", strings[j][i]); if (w >= 60) { printk("%s\n", buf); w = 0; buf[0] = 0; } } } if (x86_cpu_features.avx2) w += (u32)snprintk(buf + w, sizeof(buf) - w, "avx2 "); if (w) printk("%s\n", buf); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/datetime.h> #include <tilck/kernel/sys_types.h> #define MILLION (1000 * 1000) #define BILLION (1000 * 1000 * 1000) #define TS_SCALE BILLION extern const char *weekdays[7]; extern const char *months3[12]; struct clock_resync_stats { u32 full_resync_count; u32 full_resync_fail_count; u32 full_resync_success_count; u32 full_resync_abs_drift_gt_1; u32 multi_second_resync_count; }; static inline bool is_leap_year(u32 year) { return (!(year % 4) && (year % 100)) || !(year % 400); } u64 get_sys_time(void); s64 get_timestamp(void); void init_system_time(void); int clock_get_second_drift(void); bool clock_in_resync(void); bool clock_in_full_resync(void); void ticks_to_timespec(u64 ticks, struct k_timespec64 *tp); u64 timespec_to_ticks(const struct k_timespec64 *tp); void real_time_get_timespec(struct k_timespec64 *tp); void monotonic_time_get_timespec(struct k_timespec64 *tp); void clock_get_resync_stats(struct clock_resync_stats *s); static ALWAYS_INLINE struct k_timespec32 to_k_timespec32(struct k_timespec64 tp) { struct k_timespec32 res; STATIC_ASSERT(sizeof(res.tv_nsec) == sizeof(tp.tv_nsec)); res = (struct k_timespec32) { .tv_sec = (s32)tp.tv_sec, // NOTE: truncation .tv_nsec = tp.tv_nsec, }; return res; } #ifdef BITS32 #define to_stat_timespec(tp) to_k_timespec32(tp) #else #define to_stat_timespec(tp) (tp) #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/datetime.h> #include "osl.h" #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_misc") static ulong boot_acpi_root_ptr; void acpi_set_root_pointer(ulong ptr) { boot_acpi_root_ptr = ptr; } ACPI_STATUS AcpiOsInitialize(void) { ACPI_STATUS rc; ACPI_FUNCTION_TRACE(__FUNC__); if ((rc = osl_init_malloc()) != AE_OK) return_ACPI_STATUS(rc); if ((rc = osl_init_tasks()) != AE_OK) return_ACPI_STATUS(rc); if ((rc = osl_init_irqs()) != AE_OK) return_ACPI_STATUS(rc); return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsTerminate(void) { ACPI_FUNCTION_TRACE(__FUNC__); return_ACPI_STATUS(AE_OK); } ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(void) { if (boot_acpi_root_ptr) return boot_acpi_root_ptr; ACPI_PHYSICAL_ADDRESS ptr = 0; AcpiFindRootPointer(&ptr); return ptr; } ACPI_STATUS AcpiOsPredefinedOverride( const ACPI_PREDEFINED_NAMES *InitVal, ACPI_STRING *NewVal) { *NewVal = NULL; return AE_OK; } ACPI_STATUS AcpiOsTableOverride( ACPI_TABLE_HEADER *ExistingTable, ACPI_TABLE_HEADER **NewTable) { *NewTable = NULL; return AE_OK; } ACPI_STATUS AcpiOsPhysicalTableOverride( ACPI_TABLE_HEADER *ExistingTable, ACPI_PHYSICAL_ADDRESS *NewAddress, UINT32 *NewTableLength) { *NewAddress = 0; return AE_OK; } void AcpiOsSleep(UINT64 Milliseconds) { kernel_sleep_ms(Milliseconds); } void AcpiOsStall(UINT32 Microseconds) { disable_preemption(); { UINT32 n = Microseconds / 100000; UINT32 rem = Microseconds % 100000; for (UINT32 i = 0; i < n; i++) delay_us(100000); delay_us(rem); } enable_preemption_nosched(); } UINT64 AcpiOsGetTimer(void) { /* system time in 100-ns units */ return get_sys_time() / 100; } ACPI_THREAD_ID AcpiOsGetThreadId(void) { return get_curr_tid(); } ACPI_STATUS AcpiOsSignal ( UINT32 Function, void *Info) { if (Function == ACPI_SIGNAL_FATAL) { ACPI_SIGNAL_FATAL_INFO *i = Info; panic("ACPI: fatal signal. Type: 0x%x, Code: 0x%x, Arg: 0x%x\n", i->Type, i->Code, i->Argument); } else if (Function == ACPI_SIGNAL_BREAKPOINT) { printk("ACPI: breakpoint: %s\n", (char *)Info); printk("ACPI: ignoring the breakpoint\n"); return AE_OK; } else { panic("ACPI: unknown signal: %u\n", Function); } } ACPI_STATUS AcpiOsEnterSleep( UINT8 SleepState, UINT32 RegaValue, UINT32 RegbValue) { ACPI_FUNCTION_TRACE(__FUNC__); printk("ACPI sleep: %u, 0x%x, 0x%x\n", SleepState, RegaValue, RegbValue); return_ACPI_STATUS(AE_OK); } ACPI_PRINTF_LIKE (1) void ACPI_INTERNAL_VAR_XFACE AcpiOsPrintf(const char *Format, ...) { va_list args; va_start(args, Format); vprintk(Format, args); va_end(args); } void AcpiOsVprintf( const char *Format, va_list Args) { vprintk(Format, Args); } /* ACPI DEBUGGER funcs: keep not implemented for the moment */ void AcpiOsRedirectOutput(void *Destination) { printk("AcpiOsRedirectOutput ignored\n"); } ACPI_STATUS AcpiOsGetLine ( char *Buffer, UINT32 BufferLength, UINT32 *BytesRead) { NOT_IMPLEMENTED(); } ACPI_STATUS AcpiOsInitializeDebugger(void) { /* do nothing */ return AE_OK; } void AcpiOsTerminateDebugger(void) { /* do nothing */ } ACPI_STATUS AcpiOsWaitCommandReady(void) { NOT_IMPLEMENTED(); } ACPI_STATUS AcpiOsNotifyCommandComplete(void) { NOT_IMPLEMENTED(); } void AcpiOsTracePoint( ACPI_TRACE_EVENT_TYPE Type, BOOLEAN Begin, UINT8 *Aml, char *Pathname) { /* do nothing */ } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #include <tilck_gen_headers/config_global.h> #include <tilck/common/page_size.h> #define KERNEL_FILE_PATH "/@KERNEL_BOOTPART_PATH@" #define SECTOR_SIZE @SECTOR_SIZE@ #define BL_ST2_DATA_SEG @BL_ST2_DATA_SEG@ #define BL_BASE_ADDR @BL_BASE_ADDR@ #define BL_BASE_SEG (@BL_BASE_ADDR@ / 16) #define DISK_UUID @DISK_UUID@ #define IMG_SZ_SEC @IMG_SZ_SEC@ /* size of the whole image */ #define BOOT_SECTORS @BOOT_SECTORS@ /* bootloader sectors */ #define BOOTPART_SEC @BOOTPART_SEC@ /* start of the bootpart */ #define BOOTPART_SZ_SEC @BOOTPART_SZ_SEC@ /* size of the bootpart */ #define INITRD_SECTOR @INITRD_SECTOR@ /* start of the initrd */ #define INITRD_SZ_SEC @INITRD_SZ_SEC@ /* size of the initrd */ #define PREFERRED_GFX_MODE_W @PREFERRED_GFX_MODE_W@ #define PREFERRED_GFX_MODE_H @PREFERRED_GFX_MODE_H@ /* Boolean config variables */ #cmakedefine01 BOOTLOADER_POISON_MEMORY #cmakedefine01 BOOT_INTERACTIVE #cmakedefine01 EFI_BOOTLOADER_DEBUG <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #include <tilck_gen_headers/config_global.h> #define KMALLOC_FIRST_HEAP_SIZE (@KMALLOC_FIRST_HEAP_SIZE_KB_VAL@ * KB) /* --------- Boolean config variables --------- */ #cmakedefine01 KMALLOC_FREE_MEM_POISONING #cmakedefine01 KMALLOC_HEAVY_STATS #cmakedefine01 KMALLOC_SUPPORT_DEBUG_LOG #cmakedefine01 KMALLOC_SUPPORT_LEAK_DETECTOR /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are many dervied constants and convenience constants not * designed to be easily changed because of the code makes assumptions about * them. Because of that, those constants are hard-coded and not available as * CMake variables. With time, some of those constants get "promoted" and moved * in CMake, others remain here. See the comments and think about the potential * implications before promoting a hard-coded constant to a configurable CMake * variable. */ /* --- NOTHING HERE at the moment --- */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct vterm; enum term_scroll_type { term_scroll_up = 0, term_scroll_down = 1, }; enum term_action_type { a_none, a_write, a_direct_write, // [1] a_del_generic, a_scroll, // [2] a_set_col_offset, a_move_cur, a_move_cur_rel, a_reset, a_pause_output, a_restart_output, a_enable_cursor, a_use_alt_buffer, a_non_buf_scroll, // [3] a_insert_blank_lines, a_delete_lines, a_set_scroll_region, a_insert_blank_chars, a_simple_del_chars, a_simple_erase_chars, }; /* * NOTES [enum term_action_type]. * * [1] direct write without filters/move_cursor/flush * * [2] arg1 = rows, arg2 = direction (0 = up, 1 = down) * WARNING: up => text moves down, down => text moves up. * * [3] non_buf scroll: (arg1: rows, arg2: direction (term_scroll_type)) * WARNING: up and down are inverted if compared to a_scroll. * up => text moves up => new blank lines at the bottom * down => text moves down => new blank lines at the top * * REASON: because the `CSI n S` sequence is called SU (Scroll Up) and * the `CSI n T` sequence is called SD (Scroll Down), despite what * traditionally up and down mean when it's about scrolling. */ enum term_del_type { TERM_DEL_PREV_CHAR, TERM_DEL_PREV_WORD, TERM_DEL_ERASE_IN_DISPLAY, TERM_DEL_ERASE_IN_LINE, }; /* --- interface exposed to the term filter func --- */ struct term_action { union { struct { u32 type1 : 8; u32 arg : 24; }; struct { u32 type2 : 8; u32 arg1 : 12; u32 arg2 : 12; }; struct { u32 type3 : 8; u32 len : 16; u32 col : 8; void *ptr; }; struct { u32 type4 : 8; u32 unused: 24; u16 arg16_1; u16 arg16_2; }; }; }; STATIC_ASSERT(sizeof(struct term_action) == (2 * sizeof(ulong))); u16 vterm_get_curr_row(struct vterm *t); u16 vterm_get_curr_col(struct vterm *t); static ALWAYS_INLINE void term_make_action_write(struct term_action *a, const char *buf, size_t len, u8 color) { *a = (struct term_action) { .type3 = a_write, .len = UNSAFE_MIN((u32)len, MAX_TERM_WRITE_LEN), .col = color, .ptr = (void *)buf, }; } static ALWAYS_INLINE void term_make_action_direct_write(struct term_action *a, const char *buf, size_t len, u8 color) { *a = (struct term_action) { .type3 = a_direct_write, .len = UNSAFE_MIN((u32)len, MAX_TERM_WRITE_LEN), .col = color, .ptr = (void *)buf, }; } static ALWAYS_INLINE void term_make_action_del_prev_char(struct term_action *a) { *a = (struct term_action) { .type1 = a_del_generic, .arg = TERM_DEL_PREV_CHAR, }; } static ALWAYS_INLINE void term_make_action_del_prev_word(struct term_action *a) { *a = (struct term_action) { .type1 = a_del_generic, .arg = TERM_DEL_PREV_WORD, }; } static ALWAYS_INLINE void term_make_action_erase_in_display(struct term_action *a, u32 mode) { *a = (struct term_action) { .type2 = a_del_generic, .arg1 = TERM_DEL_ERASE_IN_DISPLAY, .arg2 = mode, }; } static ALWAYS_INLINE void term_make_action_erase_in_line(struct term_action *a, u32 mode) { *a = (struct term_action) { .type2 = a_del_generic, .arg1 = TERM_DEL_ERASE_IN_LINE, .arg2 = mode, }; } static ALWAYS_INLINE void term_make_action_scroll(struct term_action *a, enum term_scroll_type st, u32 rows) { *a = (struct term_action) { .type2 = a_scroll, .arg1 = rows, .arg2 = st, }; } static ALWAYS_INLINE void term_make_action_set_col_off(struct term_action *a, u32 off) { *a = (struct term_action) { .type1 = a_set_col_offset, .arg = off, }; } static ALWAYS_INLINE void term_make_action_move_cursor(struct term_action *a, u32 row, u32 col) { *a = (struct term_action) { .type4 = a_move_cur, .arg16_1 = LO_BITS(row, 16, u16), .arg16_2 = LO_BITS(col, 16, u16), }; } static ALWAYS_INLINE void term_make_action_move_cursor_rel(struct term_action *a, int dr, int dc) { *a = (struct term_action) { .type4 = a_move_cur_rel, .arg16_1 = LO_BITS((u32)dr, 16, u16), .arg16_2 = LO_BITS((u32)dc, 16, u16), }; } static ALWAYS_INLINE void term_make_action_reset(struct term_action *a) { *a = (struct term_action) { .type1 = a_reset, }; } static ALWAYS_INLINE void term_make_action_pause_output(struct term_action *a) { *a = (struct term_action) { .type1 = a_pause_output, .arg = 0, }; } static ALWAYS_INLINE void term_make_action_restart_output(struct term_action *a) { *a = (struct term_action) { .type1 = a_restart_output, .arg = 0, }; } static ALWAYS_INLINE void term_make_action_set_cursor_enabled(struct term_action *a, bool value) { *a = (struct term_action) { .type1 = a_enable_cursor, .arg = value, }; } static ALWAYS_INLINE void term_make_action_use_alt_buffer(struct term_action *a, bool value) { *a = (struct term_action) { .type1 = a_use_alt_buffer, .arg = value, }; } static ALWAYS_INLINE void term_make_action_non_buf_scroll(struct term_action *a, enum term_scroll_type st, u32 rows) { *a = (struct term_action) { .type2 = a_non_buf_scroll, .arg1 = rows, .arg2 = st, }; } static ALWAYS_INLINE void term_make_action_ins_blank_lines(struct term_action *a, u32 n) { *a = (struct term_action) { .type1 = a_insert_blank_lines, .arg = n, }; } static ALWAYS_INLINE void term_make_action_del_lines(struct term_action *a, u32 n) { *a = (struct term_action) { .type1 = a_delete_lines, .arg = n, }; } static ALWAYS_INLINE void term_make_action_set_scroll_region(struct term_action *a, u32 start, u32 end) { *a = (struct term_action) { .type2 = a_set_scroll_region, .arg1 = start, .arg2 = end, }; } static ALWAYS_INLINE void term_make_action_ins_blank_chars(struct term_action *a, u16 num) { *a = (struct term_action) { .type1 = a_insert_blank_chars, .arg = num, }; } static ALWAYS_INLINE void term_make_action_simple_del_chars(struct term_action *a, u16 num) { *a = (struct term_action) { .type1 = a_simple_del_chars, .arg = num, }; } static ALWAYS_INLINE void term_make_action_simple_erase_chars(struct term_action *a, u16 num) { *a = (struct term_action) { .type1 = a_simple_erase_chars, .arg = num, }; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define PIPE_BUF_SIZE 4096 struct pipe; struct pipe *create_pipe(void); void destroy_pipe(struct pipe *p); fs_handle pipe_create_read_handle(struct pipe *p); fs_handle pipe_create_write_handle(struct pipe *p); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once /* ------ Value-based config variables -------- */ #define MAX_HANDLES @MAX_HANDLES@ /* --------- Boolean config variables --------- */ #cmakedefine01 KERNEL_BIG_IO_BUF /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are some pseudo-constants not designed to be easily changed * because of the code makes assumptions about them. Because of that, those * constants are hard-coded and not available as CMake variables. With time, * some of those constants get "promoted" and moved in CMake, others remain * here. See the comments and think about the potential implications before * promoting a hard-coded constant to a configurable CMake variable. */ #define USERAPP_MAX_ARGS_COUNT 32 /* * execve recursion limit with #!/path/to/executable scripts * WARNING: cannot be increase without increasing KERNEL_STACK_PAGES. */ #define MAX_SCRIPT_REC 2 /* * Per-task I/O buffer size (pages). * Note it is linked with USER_ARGS_PAGE_COUNT. * * Requirement: IO_COPYBUF_PAGE_COUNT + USER_ARGS_PAGE_COUNT must be * a power of 2 smaller than 64. */ #if KERNEL_BIG_IO_BUF #define IO_COPYBUF_PAGE_COUNT 63 #else #define IO_COPYBUF_PAGE_COUNT 3 #endif #define IO_COPYBUF_SIZE (IO_COPYBUF_PAGE_COUNT * PAGE_SIZE) #define ARGS_COPYBUF_SIZE (USER_ARGS_PAGE_COUNT * PAGE_SIZE) <file_sep>/****************************************************************************** * * Name: actypes.h - Common data types for the entire ACPI subsystem * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACTYPES_H__ #define __ACTYPES_H__ /* acpisrc:StructDefs -- for acpisrc conversion */ /* * ACPI_MACHINE_WIDTH must be specified in an OS- or compiler-dependent * header and must be either 32 or 64. 16-bit ACPICA is no longer * supported, as of 12/2006. */ #ifndef ACPI_MACHINE_WIDTH #error ACPI_MACHINE_WIDTH not defined #endif /* * Data type ranges * Note: These macros are designed to be compiler independent as well as * working around problems that some 32-bit compilers have with 64-bit * constants. */ #define ACPI_UINT8_MAX (UINT8) (~((UINT8) 0)) /* 0xFF */ #define ACPI_UINT16_MAX (UINT16)(~((UINT16) 0)) /* 0xFFFF */ #define ACPI_UINT32_MAX (UINT32)(~((UINT32) 0)) /* 0xFFFFFFFF */ #define ACPI_UINT64_MAX (UINT64)(~((UINT64) 0)) /* 0xFFFFFFFFFFFFFFFF */ #define ACPI_ASCII_MAX 0x7F /* * Architecture-specific ACPICA Subsystem Data Types * * The goal of these types is to provide source code portability across * 16-bit, 32-bit, and 64-bit targets. * * 1) The following types are of fixed size for all targets (16/32/64): * * BOOLEAN Logical boolean * * UINT8 8-bit (1 byte) unsigned value * UINT16 16-bit (2 byte) unsigned value * UINT32 32-bit (4 byte) unsigned value * UINT64 64-bit (8 byte) unsigned value * * INT16 16-bit (2 byte) signed value * INT32 32-bit (4 byte) signed value * INT64 64-bit (8 byte) signed value * * COMPILER_DEPENDENT_UINT64/INT64 - These types are defined in the * compiler-dependent header(s) and were introduced because there is no * common 64-bit integer type across the various compilation models, as * shown in the table below. * * Datatype LP64 ILP64 LLP64 ILP32 LP32 16bit * char 8 8 8 8 8 8 * short 16 16 16 16 16 16 * _int32 32 * int 32 64 32 32 16 16 * long 64 64 32 32 32 32 * long long 64 64 * pointer 64 64 64 32 32 32 * * Note: ILP64 and LP32 are currently not supported. * * * 2) These types represent the native word size of the target mode of the * processor, and may be 16-bit, 32-bit, or 64-bit as required. They are * usually used for memory allocation, efficient loop counters, and array * indexes. The types are similar to the size_t type in the C library and * are required because there is no C type that consistently represents the * native data width. ACPI_SIZE is needed because there is no guarantee * that a kernel-level C library is present. * * ACPI_SIZE 16/32/64-bit unsigned value * ACPI_NATIVE_INT 16/32/64-bit signed value */ /******************************************************************************* * * Common types for all compilers, all targets * ******************************************************************************/ #ifndef ACPI_USE_SYSTEM_INTTYPES typedef unsigned char BOOLEAN; typedef unsigned char UINT8; typedef unsigned short UINT16; typedef short INT16; typedef COMPILER_DEPENDENT_UINT64 UINT64; typedef COMPILER_DEPENDENT_INT64 INT64; #endif /* ACPI_USE_SYSTEM_INTTYPES */ /* * Value returned by AcpiOsGetThreadId. There is no standard "thread_id" * across operating systems or even the various UNIX systems. Since ACPICA * only needs the thread ID as a unique thread identifier, we use a UINT64 * as the only common data type - it will accommodate any type of pointer or * any type of integer. It is up to the host-dependent OSL to cast the * native thread ID type to a UINT64 (in AcpiOsGetThreadId). */ #define ACPI_THREAD_ID UINT64 /******************************************************************************* * * Types specific to 64-bit targets * ******************************************************************************/ #if ACPI_MACHINE_WIDTH == 64 #ifndef ACPI_USE_SYSTEM_INTTYPES typedef unsigned int UINT32; typedef int INT32; #endif /* ACPI_USE_SYSTEM_INTTYPES */ typedef INT64 ACPI_NATIVE_INT; typedef UINT64 ACPI_SIZE; typedef UINT64 ACPI_IO_ADDRESS; typedef UINT64 ACPI_PHYSICAL_ADDRESS; #define ACPI_MAX_PTR ACPI_UINT64_MAX #define ACPI_SIZE_MAX ACPI_UINT64_MAX #define ACPI_USE_NATIVE_DIVIDE /* Has native 64-bit integer support */ #define ACPI_USE_NATIVE_MATH64 /* Has native 64-bit integer support */ /* * In the case of the Itanium Processor Family (IPF), the hardware does not * support misaligned memory transfers. Set the MISALIGNMENT_NOT_SUPPORTED * flag to indicate that special precautions must be taken to avoid alignment * faults. (IA64 or ia64 is currently used by existing compilers to indicate * IPF.) * * Note: EM64T and other X86-64 processors support misaligned transfers, * so there is no need to define this flag. */ #if defined (__IA64__) || defined (__ia64__) #define ACPI_MISALIGNMENT_NOT_SUPPORTED #endif /******************************************************************************* * * Types specific to 32-bit targets * ******************************************************************************/ #elif ACPI_MACHINE_WIDTH == 32 #ifndef ACPI_USE_SYSTEM_INTTYPES typedef unsigned int UINT32; typedef int INT32; #endif /* ACPI_USE_SYSTEM_INTTYPES */ typedef INT32 ACPI_NATIVE_INT; typedef UINT32 ACPI_SIZE; #ifdef ACPI_32BIT_PHYSICAL_ADDRESS /* * OSPMs can define this to shrink the size of the structures for 32-bit * none PAE environment. ASL compiler may always define this to generate * 32-bit OSPM compliant tables. */ typedef UINT32 ACPI_IO_ADDRESS; typedef UINT32 ACPI_PHYSICAL_ADDRESS; #else /* ACPI_32BIT_PHYSICAL_ADDRESS */ /* * It is reported that, after some calculations, the physical addresses can * wrap over the 32-bit boundary on 32-bit PAE environment. * https://bugzilla.kernel.org/show_bug.cgi?id=87971 */ typedef UINT64 ACPI_IO_ADDRESS; typedef UINT64 ACPI_PHYSICAL_ADDRESS; #endif /* ACPI_32BIT_PHYSICAL_ADDRESS */ #define ACPI_MAX_PTR ACPI_UINT32_MAX #define ACPI_SIZE_MAX ACPI_UINT32_MAX #else /* ACPI_MACHINE_WIDTH must be either 64 or 32 */ #error unknown ACPI_MACHINE_WIDTH #endif /******************************************************************************* * * OS-dependent types * * If the defaults below are not appropriate for the host system, they can * be defined in the OS-specific header, and this will take precedence. * ******************************************************************************/ /* Flags for AcpiOsAcquireLock/AcpiOsReleaseLock */ #ifndef ACPI_CPU_FLAGS #define ACPI_CPU_FLAGS ACPI_SIZE #endif /* Object returned from AcpiOsCreateCache */ #ifndef ACPI_CACHE_T #ifdef ACPI_USE_LOCAL_CACHE #define ACPI_CACHE_T ACPI_MEMORY_LIST #else #define ACPI_CACHE_T void * #endif #endif /* * Synchronization objects - Mutexes, Semaphores, and SpinLocks */ #if (ACPI_MUTEX_TYPE == ACPI_BINARY_SEMAPHORE) /* * These macros are used if the host OS does not support a mutex object. * Map the OSL Mutex interfaces to binary semaphores. */ #define ACPI_MUTEX ACPI_SEMAPHORE #define AcpiOsCreateMutex(OutHandle) AcpiOsCreateSemaphore (1, 1, OutHandle) #define AcpiOsDeleteMutex(Handle) (void) AcpiOsDeleteSemaphore (Handle) #define AcpiOsAcquireMutex(Handle,Time) AcpiOsWaitSemaphore (Handle, 1, Time) #define AcpiOsReleaseMutex(Handle) (void) AcpiOsSignalSemaphore (Handle, 1) #endif /* Configurable types for synchronization objects */ #ifndef ACPI_SPINLOCK #define ACPI_SPINLOCK void * #endif #ifndef ACPI_SEMAPHORE #define ACPI_SEMAPHORE void * #endif #ifndef ACPI_MUTEX #define ACPI_MUTEX void * #endif /******************************************************************************* * * Compiler-dependent types * * If the defaults below are not appropriate for the host compiler, they can * be defined in the compiler-specific header, and this will take precedence. * ******************************************************************************/ /* Use C99 uintptr_t for pointer casting if available, "void *" otherwise */ #ifndef ACPI_UINTPTR_T #define ACPI_UINTPTR_T void * #endif /* * ACPI_PRINTF_LIKE is used to tag functions as "printf-like" because * some compilers can catch printf format string problems */ #ifndef ACPI_PRINTF_LIKE #define ACPI_PRINTF_LIKE(c) #endif /* * Some compilers complain about unused variables. Sometimes we don't want * to use all the variables (for example, _AcpiModuleName). This allows us * to tell the compiler in a per-variable manner that a variable * is unused */ #ifndef ACPI_UNUSED_VAR #define ACPI_UNUSED_VAR #endif /* * All ACPICA external functions that are available to the rest of the * kernel are tagged with these macros which can be defined as appropriate * for the host. * * Notes: * ACPI_EXPORT_SYMBOL_INIT is used for initialization and termination * interfaces that may need special processing. * ACPI_EXPORT_SYMBOL is used for all other public external functions. */ #ifndef ACPI_EXPORT_SYMBOL_INIT #define ACPI_EXPORT_SYMBOL_INIT(Symbol) #endif #ifndef ACPI_EXPORT_SYMBOL #define ACPI_EXPORT_SYMBOL(Symbol) #endif /* * Compiler/Clibrary-dependent debug initialization. Used for ACPICA * utilities only. */ #ifndef ACPI_DEBUG_INITIALIZE #define ACPI_DEBUG_INITIALIZE() #endif /******************************************************************************* * * Configuration * ******************************************************************************/ #ifdef ACPI_NO_MEM_ALLOCATIONS #define ACPI_ALLOCATE(a) NULL #define ACPI_ALLOCATE_ZEROED(a) NULL #define ACPI_FREE(a) #define ACPI_MEM_TRACKING(a) #else /* ACPI_NO_MEM_ALLOCATIONS */ #ifdef ACPI_DBG_TRACK_ALLOCATIONS /* * Memory allocation tracking (used by AcpiExec to detect memory leaks) */ #define ACPI_MEM_PARAMETERS _COMPONENT, _AcpiModuleName, __LINE__ #define ACPI_ALLOCATE(a) AcpiUtAllocateAndTrack ((ACPI_SIZE) (a), ACPI_MEM_PARAMETERS) #define ACPI_ALLOCATE_ZEROED(a) AcpiUtAllocateZeroedAndTrack ((ACPI_SIZE) (a), ACPI_MEM_PARAMETERS) #define ACPI_FREE(a) AcpiUtFreeAndTrack (a, ACPI_MEM_PARAMETERS) #define ACPI_MEM_TRACKING(a) a #else /* * Normal memory allocation directly via the OS services layer */ #define ACPI_ALLOCATE(a) AcpiOsAllocate ((ACPI_SIZE) (a)) #define ACPI_ALLOCATE_ZEROED(a) AcpiOsAllocateZeroed ((ACPI_SIZE) (a)) #define ACPI_FREE(a) AcpiOsFree (a) #define ACPI_MEM_TRACKING(a) #endif /* ACPI_DBG_TRACK_ALLOCATIONS */ #endif /* ACPI_NO_MEM_ALLOCATIONS */ /****************************************************************************** * * ACPI Specification constants (Do not change unless the specification * changes) * *****************************************************************************/ /* Number of distinct FADT-based GPE register blocks (GPE0 and GPE1) */ #define ACPI_MAX_GPE_BLOCKS 2 /* Default ACPI register widths */ #define ACPI_GPE_REGISTER_WIDTH 8 #define ACPI_PM1_REGISTER_WIDTH 16 #define ACPI_PM2_REGISTER_WIDTH 8 #define ACPI_PM_TIMER_WIDTH 32 #define ACPI_RESET_REGISTER_WIDTH 8 /* Names within the namespace are 4 bytes long */ #define ACPI_NAMESEG_SIZE 4 /* Fixed by ACPI spec */ #define ACPI_PATH_SEGMENT_LENGTH 5 /* 4 chars for name + 1 char for separator */ #define ACPI_PATH_SEPARATOR '.' /* Sizes for ACPI table headers */ #define ACPI_OEM_ID_SIZE 6 #define ACPI_OEM_TABLE_ID_SIZE 8 /* ACPI/PNP hardware IDs */ #define PCI_ROOT_HID_STRING "PNP0A03" #define PCI_EXPRESS_ROOT_HID_STRING "PNP0A08" /* PM Timer ticks per second (HZ) */ #define ACPI_PM_TIMER_FREQUENCY 3579545 /******************************************************************************* * * Independent types * ******************************************************************************/ /* Logical defines and NULL */ #ifdef FALSE #undef FALSE #endif #define FALSE (1 == 0) #ifdef TRUE #undef TRUE #endif #define TRUE (1 == 1) #ifndef NULL #define NULL (void *) 0 #endif /* * Miscellaneous types */ typedef UINT32 ACPI_STATUS; /* All ACPI Exceptions */ typedef UINT32 ACPI_NAME; /* 4-byte ACPI name */ typedef char * ACPI_STRING; /* Null terminated ASCII string */ typedef void * ACPI_HANDLE; /* Actually a ptr to a NS Node */ /* Time constants for timer calculations */ #define ACPI_MSEC_PER_SEC 1000L #define ACPI_USEC_PER_MSEC 1000L #define ACPI_USEC_PER_SEC 1000000L #define ACPI_100NSEC_PER_USEC 10L #define ACPI_100NSEC_PER_MSEC 10000L #define ACPI_100NSEC_PER_SEC 10000000L #define ACPI_NSEC_PER_USEC 1000L #define ACPI_NSEC_PER_MSEC 1000000L #define ACPI_NSEC_PER_SEC 1000000000L #define ACPI_TIME_AFTER(a, b) ((INT64)((b) - (a)) < 0) /* Owner IDs are used to track namespace nodes for selective deletion */ typedef UINT16 ACPI_OWNER_ID; #define ACPI_OWNER_ID_MAX 0xFFF /* 4095 possible owner IDs */ #define ACPI_INTEGER_BIT_SIZE 64 #define ACPI_MAX_DECIMAL_DIGITS 20 /* 2^64 = 18,446,744,073,709,551,616 */ #define ACPI_MAX64_DECIMAL_DIGITS 20 #define ACPI_MAX32_DECIMAL_DIGITS 10 #define ACPI_MAX16_DECIMAL_DIGITS 5 #define ACPI_MAX8_DECIMAL_DIGITS 3 /* * Constants with special meanings */ #define ACPI_ROOT_OBJECT ((ACPI_HANDLE) ACPI_TO_POINTER (ACPI_MAX_PTR)) #define ACPI_WAIT_FOREVER 0xFFFF /* UINT16, as per ACPI spec */ #define ACPI_DO_NOT_WAIT 0 /* * Obsolete: Acpi integer width. In ACPI version 1 (1996), integers are * 32 bits. In ACPI version 2 (2000) and later, integers are max 64 bits. * Note that this pertains to the ACPI integer type only, not to other * integers used in the implementation of the ACPICA subsystem. * * 01/2010: This type is obsolete and has been removed from the entire ACPICA * code base. It remains here for compatibility with device drivers that use * the type. However, it will be removed in the future. */ typedef UINT64 ACPI_INTEGER; #define ACPI_INTEGER_MAX ACPI_UINT64_MAX /******************************************************************************* * * Commonly used macros * ******************************************************************************/ /* Data manipulation */ #define ACPI_LOBYTE(Integer) ((UINT8) (UINT16)(Integer)) #define ACPI_HIBYTE(Integer) ((UINT8) (((UINT16)(Integer)) >> 8)) #define ACPI_LOWORD(Integer) ((UINT16) (UINT32)(Integer)) #define ACPI_HIWORD(Integer) ((UINT16)(((UINT32)(Integer)) >> 16)) #define ACPI_LODWORD(Integer64) ((UINT32) (UINT64)(Integer64)) #define ACPI_HIDWORD(Integer64) ((UINT32)(((UINT64)(Integer64)) >> 32)) #define ACPI_SET_BIT(target,bit) ((target) |= (bit)) #define ACPI_CLEAR_BIT(target,bit) ((target) &= ~(bit)) #define ACPI_MIN(a,b) (((a)<(b))?(a):(b)) #define ACPI_MAX(a,b) (((a)>(b))?(a):(b)) /* Size calculation */ #define ACPI_ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0])) /* Pointer manipulation */ #define ACPI_CAST_PTR(t, p) ((t *) (ACPI_UINTPTR_T) (p)) #define ACPI_CAST_INDIRECT_PTR(t, p) ((t **) (ACPI_UINTPTR_T) (p)) #define ACPI_ADD_PTR(t, a, b) ACPI_CAST_PTR (t, (ACPI_CAST_PTR (UINT8, (a)) + (ACPI_SIZE)(b))) #define ACPI_SUB_PTR(t, a, b) ACPI_CAST_PTR (t, (ACPI_CAST_PTR (UINT8, (a)) - (ACPI_SIZE)(b))) #define ACPI_PTR_DIFF(a, b) ((ACPI_SIZE) (ACPI_CAST_PTR (UINT8, (a)) - ACPI_CAST_PTR (UINT8, (b)))) /* Pointer/Integer type conversions */ #define ACPI_TO_POINTER(i) ACPI_CAST_PTR (void, (ACPI_SIZE) (i)) #define ACPI_TO_INTEGER(p) ACPI_PTR_DIFF (p, (void *) 0) #define ACPI_OFFSET(d, f) ACPI_PTR_DIFF (&(((d *) 0)->f), (void *) 0) #define ACPI_PHYSADDR_TO_PTR(i) ACPI_TO_POINTER(i) #define ACPI_PTR_TO_PHYSADDR(i) ACPI_TO_INTEGER(i) /* Optimizations for 4-character (32-bit) ACPI_NAME manipulation */ #ifndef ACPI_MISALIGNMENT_NOT_SUPPORTED #define ACPI_COMPARE_NAMESEG(a,b) (*ACPI_CAST_PTR (UINT32, (a)) == *ACPI_CAST_PTR (UINT32, (b))) #define ACPI_COPY_NAMESEG(dest,src) (*ACPI_CAST_PTR (UINT32, (dest)) = *ACPI_CAST_PTR (UINT32, (src))) #else #define ACPI_COMPARE_NAMESEG(a,b) (!strncmp (ACPI_CAST_PTR (char, (a)), ACPI_CAST_PTR (char, (b)), ACPI_NAMESEG_SIZE)) #define ACPI_COPY_NAMESEG(dest,src) (strncpy (ACPI_CAST_PTR (char, (dest)), ACPI_CAST_PTR (char, (src)), ACPI_NAMESEG_SIZE)) #endif /* Support for the special RSDP signature (8 characters) */ #define ACPI_VALIDATE_RSDP_SIG(a) (!strncmp (ACPI_CAST_PTR (char, (a)), ACPI_SIG_RSDP, 8)) #define ACPI_MAKE_RSDP_SIG(dest) (memcpy (ACPI_CAST_PTR (char, (dest)), ACPI_SIG_RSDP, 8)) /* Support for OEMx signature (x can be any character) */ #define ACPI_IS_OEM_SIG(a) (!strncmp (ACPI_CAST_PTR (char, (a)), ACPI_OEM_NAME, 3) &&\ strnlen (a, ACPI_NAMESEG_SIZE) == ACPI_NAMESEG_SIZE) /* * Algorithm to obtain access bit or byte width. * Can be used with AccessSize field of ACPI_GENERIC_ADDRESS and * ACPI_RESOURCE_GENERIC_REGISTER. */ #define ACPI_ACCESS_BIT_WIDTH(AccessSize) (1 << ((AccessSize) + 2)) #define ACPI_ACCESS_BYTE_WIDTH(AccessSize) (1 << ((AccessSize) - 1)) /******************************************************************************* * * Miscellaneous constants * ******************************************************************************/ /* * Initialization sequence options */ #define ACPI_FULL_INITIALIZATION 0x0000 #define ACPI_NO_FACS_INIT 0x0001 #define ACPI_NO_ACPI_ENABLE 0x0002 #define ACPI_NO_HARDWARE_INIT 0x0004 #define ACPI_NO_EVENT_INIT 0x0008 #define ACPI_NO_HANDLER_INIT 0x0010 #define ACPI_NO_OBJECT_INIT 0x0020 #define ACPI_NO_DEVICE_INIT 0x0040 #define ACPI_NO_ADDRESS_SPACE_INIT 0x0080 /* * Initialization state */ #define ACPI_SUBSYSTEM_INITIALIZE 0x01 #define ACPI_INITIALIZED_OK 0x02 /* * Power state values */ #define ACPI_STATE_UNKNOWN (UINT8) 0xFF #define ACPI_STATE_S0 (UINT8) 0 #define ACPI_STATE_S1 (UINT8) 1 #define ACPI_STATE_S2 (UINT8) 2 #define ACPI_STATE_S3 (UINT8) 3 #define ACPI_STATE_S4 (UINT8) 4 #define ACPI_STATE_S5 (UINT8) 5 #define ACPI_S_STATES_MAX ACPI_STATE_S5 #define ACPI_S_STATE_COUNT 6 #define ACPI_STATE_D0 (UINT8) 0 #define ACPI_STATE_D1 (UINT8) 1 #define ACPI_STATE_D2 (UINT8) 2 #define ACPI_STATE_D3 (UINT8) 3 #define ACPI_D_STATES_MAX ACPI_STATE_D3 #define ACPI_D_STATE_COUNT 4 #define ACPI_STATE_C0 (UINT8) 0 #define ACPI_STATE_C1 (UINT8) 1 #define ACPI_STATE_C2 (UINT8) 2 #define ACPI_STATE_C3 (UINT8) 3 #define ACPI_C_STATES_MAX ACPI_STATE_C3 #define ACPI_C_STATE_COUNT 4 /* * Sleep type invalid value */ #define ACPI_SLEEP_TYPE_MAX 0x7 #define ACPI_SLEEP_TYPE_INVALID 0xFF /* * Standard notify values */ #define ACPI_NOTIFY_BUS_CHECK (UINT8) 0x00 #define ACPI_NOTIFY_DEVICE_CHECK (UINT8) 0x01 #define ACPI_NOTIFY_DEVICE_WAKE (UINT8) 0x02 #define ACPI_NOTIFY_EJECT_REQUEST (UINT8) 0x03 #define ACPI_NOTIFY_DEVICE_CHECK_LIGHT (UINT8) 0x04 #define ACPI_NOTIFY_FREQUENCY_MISMATCH (UINT8) 0x05 #define ACPI_NOTIFY_BUS_MODE_MISMATCH (UINT8) 0x06 #define ACPI_NOTIFY_POWER_FAULT (UINT8) 0x07 #define ACPI_NOTIFY_CAPABILITIES_CHECK (UINT8) 0x08 #define ACPI_NOTIFY_DEVICE_PLD_CHECK (UINT8) 0x09 #define ACPI_NOTIFY_RESERVED (UINT8) 0x0A #define ACPI_NOTIFY_LOCALITY_UPDATE (UINT8) 0x0B #define ACPI_NOTIFY_SHUTDOWN_REQUEST (UINT8) 0x0C #define ACPI_NOTIFY_AFFINITY_UPDATE (UINT8) 0x0D #define ACPI_NOTIFY_MEMORY_UPDATE (UINT8) 0x0E #define ACPI_NOTIFY_DISCONNECT_RECOVER (UINT8) 0x0F #define ACPI_GENERIC_NOTIFY_MAX 0x0F #define ACPI_SPECIFIC_NOTIFY_MAX 0x84 /* * Types associated with ACPI names and objects. The first group of * values (up to ACPI_TYPE_EXTERNAL_MAX) correspond to the definition * of the ACPI ObjectType() operator (See the ACPI Spec). Therefore, * only add to the first group if the spec changes. * * NOTE: Types must be kept in sync with the global AcpiNsProperties * and AcpiNsTypeNames arrays. */ typedef UINT32 ACPI_OBJECT_TYPE; #define ACPI_TYPE_ANY 0x00 #define ACPI_TYPE_INTEGER 0x01 /* Byte/Word/Dword/Zero/One/Ones */ #define ACPI_TYPE_STRING 0x02 #define ACPI_TYPE_BUFFER 0x03 #define ACPI_TYPE_PACKAGE 0x04 /* ByteConst, multiple DataTerm/Constant/SuperName */ #define ACPI_TYPE_FIELD_UNIT 0x05 #define ACPI_TYPE_DEVICE 0x06 /* Name, multiple Node */ #define ACPI_TYPE_EVENT 0x07 #define ACPI_TYPE_METHOD 0x08 /* Name, ByteConst, multiple Code */ #define ACPI_TYPE_MUTEX 0x09 #define ACPI_TYPE_REGION 0x0A #define ACPI_TYPE_POWER 0x0B /* Name,ByteConst,WordConst,multi Node */ #define ACPI_TYPE_PROCESSOR 0x0C /* Name,ByteConst,DWordConst,ByteConst,multi NmO */ #define ACPI_TYPE_THERMAL 0x0D /* Name, multiple Node */ #define ACPI_TYPE_BUFFER_FIELD 0x0E #define ACPI_TYPE_DDB_HANDLE 0x0F #define ACPI_TYPE_DEBUG_OBJECT 0x10 #define ACPI_TYPE_EXTERNAL_MAX 0x10 #define ACPI_NUM_TYPES (ACPI_TYPE_EXTERNAL_MAX + 1) /* * These are object types that do not map directly to the ACPI * ObjectType() operator. They are used for various internal purposes * only. If new predefined ACPI_TYPEs are added (via the ACPI * specification), these internal types must move upwards. (There * is code that depends on these values being contiguous with the * external types above.) */ #define ACPI_TYPE_LOCAL_REGION_FIELD 0x11 #define ACPI_TYPE_LOCAL_BANK_FIELD 0x12 #define ACPI_TYPE_LOCAL_INDEX_FIELD 0x13 #define ACPI_TYPE_LOCAL_REFERENCE 0x14 /* Arg#, Local#, Name, Debug, RefOf, Index */ #define ACPI_TYPE_LOCAL_ALIAS 0x15 #define ACPI_TYPE_LOCAL_METHOD_ALIAS 0x16 #define ACPI_TYPE_LOCAL_NOTIFY 0x17 #define ACPI_TYPE_LOCAL_ADDRESS_HANDLER 0x18 #define ACPI_TYPE_LOCAL_RESOURCE 0x19 #define ACPI_TYPE_LOCAL_RESOURCE_FIELD 0x1A #define ACPI_TYPE_LOCAL_SCOPE 0x1B /* 1 Name, multiple ObjectList Nodes */ #define ACPI_TYPE_NS_NODE_MAX 0x1B /* Last typecode used within a NS Node */ #define ACPI_TOTAL_TYPES (ACPI_TYPE_NS_NODE_MAX + 1) /* * These are special object types that never appear in * a Namespace node, only in an object of ACPI_OPERAND_OBJECT */ #define ACPI_TYPE_LOCAL_EXTRA 0x1C #define ACPI_TYPE_LOCAL_DATA 0x1D #define ACPI_TYPE_LOCAL_MAX 0x1D /* All types above here are invalid */ #define ACPI_TYPE_INVALID 0x1E #define ACPI_TYPE_NOT_FOUND 0xFF #define ACPI_NUM_NS_TYPES (ACPI_TYPE_INVALID + 1) /* * All I/O */ #define ACPI_READ 0 #define ACPI_WRITE 1 #define ACPI_IO_MASK 1 /* * Event Types: Fixed & General Purpose */ typedef UINT32 ACPI_EVENT_TYPE; /* * Fixed events */ #define ACPI_EVENT_PMTIMER 0 #define ACPI_EVENT_GLOBAL 1 #define ACPI_EVENT_POWER_BUTTON 2 #define ACPI_EVENT_SLEEP_BUTTON 3 #define ACPI_EVENT_RTC 4 #define ACPI_EVENT_MAX 4 #define ACPI_NUM_FIXED_EVENTS ACPI_EVENT_MAX + 1 /* * Event Status - Per event * ------------- * The encoding of ACPI_EVENT_STATUS is illustrated below. * Note that a set bit (1) indicates the property is TRUE * (e.g. if bit 0 is set then the event is enabled). * +-------------+-+-+-+-+-+-+ * | Bits 31:6 |5|4|3|2|1|0| * +-------------+-+-+-+-+-+-+ * | | | | | | | * | | | | | | +- Enabled? * | | | | | +--- Enabled for wake? * | | | | +----- Status bit set? * | | | +------- Enable bit set? * | | +--------- Has a handler? * | +----------- Masked? * +----------------- <Reserved> */ typedef UINT32 ACPI_EVENT_STATUS; #define ACPI_EVENT_FLAG_DISABLED (ACPI_EVENT_STATUS) 0x00 #define ACPI_EVENT_FLAG_ENABLED (ACPI_EVENT_STATUS) 0x01 #define ACPI_EVENT_FLAG_WAKE_ENABLED (ACPI_EVENT_STATUS) 0x02 #define ACPI_EVENT_FLAG_STATUS_SET (ACPI_EVENT_STATUS) 0x04 #define ACPI_EVENT_FLAG_ENABLE_SET (ACPI_EVENT_STATUS) 0x08 #define ACPI_EVENT_FLAG_HAS_HANDLER (ACPI_EVENT_STATUS) 0x10 #define ACPI_EVENT_FLAG_MASKED (ACPI_EVENT_STATUS) 0x20 #define ACPI_EVENT_FLAG_SET ACPI_EVENT_FLAG_STATUS_SET /* Actions for AcpiSetGpe, AcpiGpeWakeup, AcpiHwLowSetGpe */ #define ACPI_GPE_ENABLE 0 #define ACPI_GPE_DISABLE 1 #define ACPI_GPE_CONDITIONAL_ENABLE 2 /* * GPE info flags - Per GPE * +---+-+-+-+---+ * |7:6|5|4|3|2:0| * +---+-+-+-+---+ * | | | | | * | | | | +-- Type of dispatch:to method, handler, notify, or none * | | | +----- Interrupt type: edge or level triggered * | | +------- Is a Wake GPE * | +--------- Has been enabled automatically at init time * +------------ <Reserved> */ #define ACPI_GPE_DISPATCH_NONE (UINT8) 0x00 #define ACPI_GPE_DISPATCH_METHOD (UINT8) 0x01 #define ACPI_GPE_DISPATCH_HANDLER (UINT8) 0x02 #define ACPI_GPE_DISPATCH_NOTIFY (UINT8) 0x03 #define ACPI_GPE_DISPATCH_RAW_HANDLER (UINT8) 0x04 #define ACPI_GPE_DISPATCH_MASK (UINT8) 0x07 #define ACPI_GPE_DISPATCH_TYPE(flags) ((UINT8) ((flags) & ACPI_GPE_DISPATCH_MASK)) #define ACPI_GPE_LEVEL_TRIGGERED (UINT8) 0x08 #define ACPI_GPE_EDGE_TRIGGERED (UINT8) 0x00 #define ACPI_GPE_XRUPT_TYPE_MASK (UINT8) 0x08 #define ACPI_GPE_CAN_WAKE (UINT8) 0x10 #define ACPI_GPE_AUTO_ENABLED (UINT8) 0x20 #define ACPI_GPE_INITIALIZED (UINT8) 0x40 /* * Flags for GPE and Lock interfaces */ #define ACPI_NOT_ISR 0x1 #define ACPI_ISR 0x0 /* Notify types */ #define ACPI_SYSTEM_NOTIFY 0x1 #define ACPI_DEVICE_NOTIFY 0x2 #define ACPI_ALL_NOTIFY (ACPI_SYSTEM_NOTIFY | ACPI_DEVICE_NOTIFY) #define ACPI_MAX_NOTIFY_HANDLER_TYPE 0x3 #define ACPI_NUM_NOTIFY_TYPES 2 #define ACPI_MAX_SYS_NOTIFY 0x7F #define ACPI_MAX_DEVICE_SPECIFIC_NOTIFY 0xBF #define ACPI_SYSTEM_HANDLER_LIST 0 /* Used as index, must be SYSTEM_NOTIFY -1 */ #define ACPI_DEVICE_HANDLER_LIST 1 /* Used as index, must be DEVICE_NOTIFY -1 */ /* Address Space (Operation Region) Types */ typedef UINT8 ACPI_ADR_SPACE_TYPE; #define ACPI_ADR_SPACE_SYSTEM_MEMORY (ACPI_ADR_SPACE_TYPE) 0 #define ACPI_ADR_SPACE_SYSTEM_IO (ACPI_ADR_SPACE_TYPE) 1 #define ACPI_ADR_SPACE_PCI_CONFIG (ACPI_ADR_SPACE_TYPE) 2 #define ACPI_ADR_SPACE_EC (ACPI_ADR_SPACE_TYPE) 3 #define ACPI_ADR_SPACE_SMBUS (ACPI_ADR_SPACE_TYPE) 4 #define ACPI_ADR_SPACE_CMOS (ACPI_ADR_SPACE_TYPE) 5 #define ACPI_ADR_SPACE_PCI_BAR_TARGET (ACPI_ADR_SPACE_TYPE) 6 #define ACPI_ADR_SPACE_IPMI (ACPI_ADR_SPACE_TYPE) 7 #define ACPI_ADR_SPACE_GPIO (ACPI_ADR_SPACE_TYPE) 8 #define ACPI_ADR_SPACE_GSBUS (ACPI_ADR_SPACE_TYPE) 9 #define ACPI_ADR_SPACE_PLATFORM_COMM (ACPI_ADR_SPACE_TYPE) 10 #define ACPI_ADR_SPACE_PLATFORM_RT (ACPI_ADR_SPACE_TYPE) 11 #define ACPI_NUM_PREDEFINED_REGIONS 12 /* * Special Address Spaces * * Note: A Data Table region is a special type of operation region * that has its own AML opcode. However, internally, the AML * interpreter simply creates an operation region with an an address * space type of ACPI_ADR_SPACE_DATA_TABLE. */ #define ACPI_ADR_SPACE_DATA_TABLE (ACPI_ADR_SPACE_TYPE) 0x7E /* Internal to ACPICA only */ #define ACPI_ADR_SPACE_FIXED_HARDWARE (ACPI_ADR_SPACE_TYPE) 0x7F /* Values for _REG connection code */ #define ACPI_REG_DISCONNECT 0 #define ACPI_REG_CONNECT 1 /* * BitRegister IDs * * These values are intended to be used by the hardware interfaces * and are mapped to individual bitfields defined within the ACPI * registers. See the AcpiGbl_BitRegisterInfo global table in utglobal.c * for this mapping. */ /* PM1 Status register */ #define ACPI_BITREG_TIMER_STATUS 0x00 #define ACPI_BITREG_BUS_MASTER_STATUS 0x01 #define ACPI_BITREG_GLOBAL_LOCK_STATUS 0x02 #define ACPI_BITREG_POWER_BUTTON_STATUS 0x03 #define ACPI_BITREG_SLEEP_BUTTON_STATUS 0x04 #define ACPI_BITREG_RT_CLOCK_STATUS 0x05 #define ACPI_BITREG_WAKE_STATUS 0x06 #define ACPI_BITREG_PCIEXP_WAKE_STATUS 0x07 /* PM1 Enable register */ #define ACPI_BITREG_TIMER_ENABLE 0x08 #define ACPI_BITREG_GLOBAL_LOCK_ENABLE 0x09 #define ACPI_BITREG_POWER_BUTTON_ENABLE 0x0A #define ACPI_BITREG_SLEEP_BUTTON_ENABLE 0x0B #define ACPI_BITREG_RT_CLOCK_ENABLE 0x0C #define ACPI_BITREG_PCIEXP_WAKE_DISABLE 0x0D /* PM1 Control register */ #define ACPI_BITREG_SCI_ENABLE 0x0E #define ACPI_BITREG_BUS_MASTER_RLD 0x0F #define ACPI_BITREG_GLOBAL_LOCK_RELEASE 0x10 #define ACPI_BITREG_SLEEP_TYPE 0x11 #define ACPI_BITREG_SLEEP_ENABLE 0x12 /* PM2 Control register */ #define ACPI_BITREG_ARB_DISABLE 0x13 #define ACPI_BITREG_MAX 0x13 #define ACPI_NUM_BITREG ACPI_BITREG_MAX + 1 /* Status register values. A 1 clears a status bit. 0 = no effect */ #define ACPI_CLEAR_STATUS 1 /* Enable and Control register values */ #define ACPI_ENABLE_EVENT 1 #define ACPI_DISABLE_EVENT 0 /* Sleep function dispatch */ typedef ACPI_STATUS (*ACPI_SLEEP_FUNCTION) ( UINT8 SleepState); typedef struct acpi_sleep_functions { ACPI_SLEEP_FUNCTION LegacyFunction; ACPI_SLEEP_FUNCTION ExtendedFunction; } ACPI_SLEEP_FUNCTIONS; /* * External ACPI object definition */ /* * Note: Type == ACPI_TYPE_ANY (0) is used to indicate a NULL package * element or an unresolved named reference. */ typedef union acpi_object { ACPI_OBJECT_TYPE Type; /* See definition of AcpiNsType for values */ struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_INTEGER */ UINT64 Value; /* The actual number */ } Integer; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_STRING */ UINT32 Length; /* # of bytes in string, excluding trailing null */ char *Pointer; /* points to the string value */ } String; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_BUFFER */ UINT32 Length; /* # of bytes in buffer */ UINT8 *Pointer; /* points to the buffer */ } Buffer; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_PACKAGE */ UINT32 Count; /* # of elements in package */ union acpi_object *Elements; /* Pointer to an array of ACPI_OBJECTs */ } Package; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_LOCAL_REFERENCE */ ACPI_OBJECT_TYPE ActualType; /* Type associated with the Handle */ ACPI_HANDLE Handle; /* object reference */ } Reference; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_PROCESSOR */ UINT32 ProcId; ACPI_IO_ADDRESS PblkAddress; UINT32 PblkLength; } Processor; struct { ACPI_OBJECT_TYPE Type; /* ACPI_TYPE_POWER */ UINT32 SystemLevel; UINT32 ResourceOrder; } PowerResource; } ACPI_OBJECT; /* * List of objects, used as a parameter list for control method evaluation */ typedef struct acpi_object_list { UINT32 Count; ACPI_OBJECT *Pointer; } ACPI_OBJECT_LIST; /* * Miscellaneous common Data Structures used by the interfaces */ #define ACPI_NO_BUFFER 0 #ifdef ACPI_NO_MEM_ALLOCATIONS #define ACPI_ALLOCATE_BUFFER (ACPI_SIZE) (0) #define ACPI_ALLOCATE_LOCAL_BUFFER (ACPI_SIZE) (0) #else /* ACPI_NO_MEM_ALLOCATIONS */ #define ACPI_ALLOCATE_BUFFER (ACPI_SIZE) (-1) /* Let ACPICA allocate buffer */ #define ACPI_ALLOCATE_LOCAL_BUFFER (ACPI_SIZE) (-2) /* For internal use only (enables tracking) */ #endif /* ACPI_NO_MEM_ALLOCATIONS */ typedef struct acpi_buffer { ACPI_SIZE Length; /* Length in bytes of the buffer */ void *Pointer; /* pointer to buffer */ } ACPI_BUFFER; /* * NameType for AcpiGetName */ #define ACPI_FULL_PATHNAME 0 #define ACPI_SINGLE_NAME 1 #define ACPI_FULL_PATHNAME_NO_TRAILING 2 #define ACPI_NAME_TYPE_MAX 2 /* * Predefined Namespace items */ typedef struct acpi_predefined_names { const char *Name; UINT8 Type; char *Val; } ACPI_PREDEFINED_NAMES; /* * Structure and flags for AcpiGetSystemInfo */ #define ACPI_SYS_MODE_UNKNOWN 0x0000 #define ACPI_SYS_MODE_ACPI 0x0001 #define ACPI_SYS_MODE_LEGACY 0x0002 #define ACPI_SYS_MODES_MASK 0x0003 /* * System info returned by AcpiGetSystemInfo() */ typedef struct acpi_system_info { UINT32 AcpiCaVersion; UINT32 Flags; UINT32 TimerResolution; UINT32 Reserved1; UINT32 Reserved2; UINT32 DebugLevel; UINT32 DebugLayer; } ACPI_SYSTEM_INFO; /* * System statistics returned by AcpiGetStatistics() */ typedef struct acpi_statistics { UINT32 SciCount; UINT32 GpeCount; UINT32 FixedEventCount[ACPI_NUM_FIXED_EVENTS]; UINT32 MethodCount; } ACPI_STATISTICS; /* * Types specific to the OS service interfaces */ typedef UINT32 (ACPI_SYSTEM_XFACE *ACPI_OSD_HANDLER) ( void *Context); typedef void (ACPI_SYSTEM_XFACE *ACPI_OSD_EXEC_CALLBACK) ( void *Context); /* * Various handlers and callback procedures */ typedef UINT32 (*ACPI_SCI_HANDLER) ( void *Context); typedef void (*ACPI_GBL_EVENT_HANDLER) ( UINT32 EventType, ACPI_HANDLE Device, UINT32 EventNumber, void *Context); #define ACPI_EVENT_TYPE_GPE 0 #define ACPI_EVENT_TYPE_FIXED 1 typedef UINT32 (*ACPI_EVENT_HANDLER) ( void *Context); typedef UINT32 (*ACPI_GPE_HANDLER) ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, void *Context); typedef void (*ACPI_NOTIFY_HANDLER) ( ACPI_HANDLE Device, UINT32 Value, void *Context); typedef void (*ACPI_OBJECT_HANDLER) ( ACPI_HANDLE Object, void *Data); typedef ACPI_STATUS (*ACPI_INIT_HANDLER) ( ACPI_HANDLE Object, UINT32 Function); #define ACPI_INIT_DEVICE_INI 1 typedef ACPI_STATUS (*ACPI_EXCEPTION_HANDLER) ( ACPI_STATUS AmlStatus, ACPI_NAME Name, UINT16 Opcode, UINT32 AmlOffset, void *Context); /* Table Event handler (Load, LoadTable, etc.) and types */ typedef ACPI_STATUS (*ACPI_TABLE_HANDLER) ( UINT32 Event, void *Table, void *Context); /* Table Event Types */ #define ACPI_TABLE_EVENT_LOAD 0x0 #define ACPI_TABLE_EVENT_UNLOAD 0x1 #define ACPI_TABLE_EVENT_INSTALL 0x2 #define ACPI_TABLE_EVENT_UNINSTALL 0x3 #define ACPI_NUM_TABLE_EVENTS 4 /* Address Spaces (For Operation Regions) */ typedef ACPI_STATUS (*ACPI_ADR_SPACE_HANDLER) ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); #define ACPI_DEFAULT_HANDLER NULL /* Special Context data for GenericSerialBus/GeneralPurposeIo (ACPI 5.0) */ typedef struct acpi_connection_info { UINT8 *Connection; UINT16 Length; UINT8 AccessLength; } ACPI_CONNECTION_INFO; typedef ACPI_STATUS (*ACPI_ADR_SPACE_SETUP) ( ACPI_HANDLE RegionHandle, UINT32 Function, void *HandlerContext, void **RegionContext); #define ACPI_REGION_ACTIVATE 0 #define ACPI_REGION_DEACTIVATE 1 typedef ACPI_STATUS (*ACPI_WALK_CALLBACK) ( ACPI_HANDLE Object, UINT32 NestingLevel, void *Context, void **ReturnValue); typedef UINT32 (*ACPI_INTERFACE_HANDLER) ( ACPI_STRING InterfaceName, UINT32 Supported); /* Interrupt handler return values */ #define ACPI_INTERRUPT_NOT_HANDLED 0x00 #define ACPI_INTERRUPT_HANDLED 0x01 /* GPE handler return values */ #define ACPI_REENABLE_GPE 0x80 /* Length of 32-bit EISAID values when converted back to a string */ #define ACPI_EISAID_STRING_SIZE 8 /* Includes null terminator */ /* Length of UUID (string) values */ #define ACPI_UUID_LENGTH 16 /* Length of 3-byte PCI class code values when converted back to a string */ #define ACPI_PCICLS_STRING_SIZE 7 /* Includes null terminator */ /* Structures used for device/processor HID, UID, CID */ typedef struct acpi_pnp_device_id { UINT32 Length; /* Length of string + null */ char *String; } ACPI_PNP_DEVICE_ID; typedef struct acpi_pnp_device_id_list { UINT32 Count; /* Number of IDs in Ids array */ UINT32 ListSize; /* Size of list, including ID strings */ ACPI_PNP_DEVICE_ID Ids[]; /* ID array */ } ACPI_PNP_DEVICE_ID_LIST; /* * Structure returned from AcpiGetObjectInfo. * Optimized for both 32-bit and 64-bit builds. */ typedef struct acpi_device_info { UINT32 InfoSize; /* Size of info, including ID strings */ UINT32 Name; /* ACPI object Name */ ACPI_OBJECT_TYPE Type; /* ACPI object Type */ UINT8 ParamCount; /* If a method, required parameter count */ UINT16 Valid; /* Indicates which optional fields are valid */ UINT8 Flags; /* Miscellaneous info */ UINT8 HighestDstates[4]; /* _SxD values: 0xFF indicates not valid */ UINT8 LowestDstates[5]; /* _SxW values: 0xFF indicates not valid */ UINT64 Address; /* _ADR value */ ACPI_PNP_DEVICE_ID HardwareId; /* _HID value */ ACPI_PNP_DEVICE_ID UniqueId; /* _UID value */ ACPI_PNP_DEVICE_ID ClassCode; /* _CLS value */ ACPI_PNP_DEVICE_ID_LIST CompatibleIdList; /* _CID list <must be last> */ } ACPI_DEVICE_INFO; /* Values for Flags field above (AcpiGetObjectInfo) */ #define ACPI_PCI_ROOT_BRIDGE 0x01 /* Flags for Valid field above (AcpiGetObjectInfo) */ #define ACPI_VALID_ADR 0x0002 #define ACPI_VALID_HID 0x0004 #define ACPI_VALID_UID 0x0008 #define ACPI_VALID_CID 0x0020 #define ACPI_VALID_CLS 0x0040 #define ACPI_VALID_SXDS 0x0100 #define ACPI_VALID_SXWS 0x0200 /* Flags for _STA method */ #define ACPI_STA_DEVICE_PRESENT 0x01 #define ACPI_STA_DEVICE_ENABLED 0x02 #define ACPI_STA_DEVICE_UI 0x04 #define ACPI_STA_DEVICE_FUNCTIONING 0x08 #define ACPI_STA_DEVICE_OK 0x08 /* Synonym */ #define ACPI_STA_BATTERY_PRESENT 0x10 /* Context structs for address space handlers */ typedef struct acpi_pci_id { UINT16 Segment; UINT16 Bus; UINT16 Device; UINT16 Function; } ACPI_PCI_ID; typedef struct acpi_mem_space_context { UINT32 Length; ACPI_PHYSICAL_ADDRESS Address; ACPI_PHYSICAL_ADDRESS MappedPhysicalAddress; UINT8 *MappedLogicalAddress; ACPI_SIZE MappedLength; } ACPI_MEM_SPACE_CONTEXT; /* * ACPI_MEMORY_LIST is used only if the ACPICA local cache is enabled */ typedef struct acpi_memory_list { const char *ListName; void *ListHead; UINT16 ObjectSize; UINT16 MaxDepth; UINT16 CurrentDepth; #ifdef ACPI_DBG_TRACK_ALLOCATIONS /* Statistics for debug memory tracking only */ UINT32 TotalAllocated; UINT32 TotalFreed; UINT32 MaxOccupied; UINT32 TotalSize; UINT32 CurrentTotalSize; UINT32 Requests; UINT32 Hits; #endif } ACPI_MEMORY_LIST; /* Definitions of trace event types */ typedef enum { ACPI_TRACE_AML_METHOD, ACPI_TRACE_AML_OPCODE, ACPI_TRACE_AML_REGION } ACPI_TRACE_EVENT_TYPE; /* Definitions of _OSI support */ #define ACPI_VENDOR_STRINGS 0x01 #define ACPI_FEATURE_STRINGS 0x02 #define ACPI_ENABLE_INTERFACES 0x00 #define ACPI_DISABLE_INTERFACES 0x04 #define ACPI_DISABLE_ALL_VENDOR_STRINGS (ACPI_DISABLE_INTERFACES | ACPI_VENDOR_STRINGS) #define ACPI_DISABLE_ALL_FEATURE_STRINGS (ACPI_DISABLE_INTERFACES | ACPI_FEATURE_STRINGS) #define ACPI_DISABLE_ALL_STRINGS (ACPI_DISABLE_INTERFACES | ACPI_VENDOR_STRINGS | ACPI_FEATURE_STRINGS) #define ACPI_ENABLE_ALL_VENDOR_STRINGS (ACPI_ENABLE_INTERFACES | ACPI_VENDOR_STRINGS) #define ACPI_ENABLE_ALL_FEATURE_STRINGS (ACPI_ENABLE_INTERFACES | ACPI_FEATURE_STRINGS) #define ACPI_ENABLE_ALL_STRINGS (ACPI_ENABLE_INTERFACES | ACPI_VENDOR_STRINGS | ACPI_FEATURE_STRINGS) #define ACPI_OSI_WIN_2000 0x01 #define ACPI_OSI_WIN_XP 0x02 #define ACPI_OSI_WIN_XP_SP1 0x03 #define ACPI_OSI_WINSRV_2003 0x04 #define ACPI_OSI_WIN_XP_SP2 0x05 #define ACPI_OSI_WINSRV_2003_SP1 0x06 #define ACPI_OSI_WIN_VISTA 0x07 #define ACPI_OSI_WINSRV_2008 0x08 #define ACPI_OSI_WIN_VISTA_SP1 0x09 #define ACPI_OSI_WIN_VISTA_SP2 0x0A #define ACPI_OSI_WIN_7 0x0B #define ACPI_OSI_WIN_8 0x0C #define ACPI_OSI_WIN_8_1 0x0D #define ACPI_OSI_WIN_10 0x0E #define ACPI_OSI_WIN_10_RS1 0x0F #define ACPI_OSI_WIN_10_RS2 0x10 #define ACPI_OSI_WIN_10_RS3 0x11 #define ACPI_OSI_WIN_10_RS4 0x12 #define ACPI_OSI_WIN_10_RS5 0x13 #define ACPI_OSI_WIN_10_19H1 0x14 /* Definitions of getopt */ #define ACPI_OPT_END -1 #endif /* __ACTYPES_H__ */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/syscalls.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/sys_types.h> #include <tilck/mods/tracing.h> #ifdef __SYSCALLS_C__ #define CREATE_STUB_SYSCALL_IMPL(name) \ int name() \ { \ if (KRN_NO_SYS_WARN) { \ printk("[TID: %d] NOT IMPLEMENTED: %s()\n", \ get_curr_tid(), #name); \ } \ trace_printk(5, "Syscall NOT IMPLEMENTED: %s()", #name); \ return -ENOSYS; \ } #else #define CREATE_STUB_SYSCALL_IMPL(name) long name(); #endif CREATE_STUB_SYSCALL_IMPL(sys_restart_syscall); int sys_exit(int code); int sys_fork(void); int sys_read(int fd, void *buf, size_t count); int sys_write(int fd, const void *buf, size_t count); int sys_open(const char *u_path, int flags, mode_t mode); int sys_close(int fd); int sys_waitpid(int pid, int *u_wstatus, int options); int sys_creat(const char *u_path, mode_t mode); int sys_link(const char *u_oldpath, const char *u_newpath); int sys_unlink(const char *u_path); int sys_execve(const char *u_path, const char *const *argv, const char *const *env); int sys_chdir(const char *path); CREATE_STUB_SYSCALL_IMPL(sys_time) CREATE_STUB_SYSCALL_IMPL(sys_mknod) int sys_chmod(const char *u_path, mode_t mode); CREATE_STUB_SYSCALL_IMPL(sys_lchown16) CREATE_STUB_SYSCALL_IMPL(sys_break) CREATE_STUB_SYSCALL_IMPL(sys_oldstat) CREATE_STUB_SYSCALL_IMPL(sys_lseek) int sys_getpid(void); int sys_mount(const char *u_source, const char *u_target, const char *u_fstype, unsigned long mountflags, const void *u_data); CREATE_STUB_SYSCALL_IMPL(sys_oldumount) int sys_setuid16(ulong uid); int sys_getuid16(void); CREATE_STUB_SYSCALL_IMPL(sys_stime32) CREATE_STUB_SYSCALL_IMPL(sys_ptrace) CREATE_STUB_SYSCALL_IMPL(sys_alarm) CREATE_STUB_SYSCALL_IMPL(sys_oldfstat) int sys_pause(void); int sys_utime32(const char *u_path, const struct k_utimbuf *u_times); int sys_access(const char *u_path, mode_t mode); CREATE_STUB_SYSCALL_IMPL(sys_nice) int sys_sync(void); int sys_kill(int pid, int sig); int sys_rename(const char *u_oldpath, const char *u_newpath); int sys_mkdir(const char *u_path, mode_t mode); int sys_rmdir(const char *u_path); int sys_dup(int oldfd); int sys_pipe(int u_pipefd[2]); ulong sys_times(struct tms *u_buf); void *sys_brk(void *vaddr); int sys_setgid16(ulong gid); int sys_getgid16(void); __sighandler_t sys_signal(int signum, __sighandler_t handler); // deprecated int sys_geteuid16(void); int sys_getegid16(void); CREATE_STUB_SYSCALL_IMPL(sys_acct) int sys_umount(const char *target, int flags); int sys_ioctl(int fd, ulong request, void *argp); CREATE_STUB_SYSCALL_IMPL(sys_fcntl) int sys_setpgid(int pid, int pgid); CREATE_STUB_SYSCALL_IMPL(sys_olduname) mode_t sys_umask(mode_t mask); CREATE_STUB_SYSCALL_IMPL(sys_chroot) CREATE_STUB_SYSCALL_IMPL(sys_ustat) int sys_dup2(int oldfd, int newfd); int sys_getppid(void); int sys_getpgrp(void); int sys_setsid(void); int sys_sigaction(ulong a1, ulong a2, ulong a3); // deprecated interface CREATE_STUB_SYSCALL_IMPL(sys_sgetmask) CREATE_STUB_SYSCALL_IMPL(sys_ssetmask) CREATE_STUB_SYSCALL_IMPL(sys_setreuid16) CREATE_STUB_SYSCALL_IMPL(sys_setregid16) CREATE_STUB_SYSCALL_IMPL(sys_sigsuspend) CREATE_STUB_SYSCALL_IMPL(sys_sigpending) CREATE_STUB_SYSCALL_IMPL(sys_sethostname) CREATE_STUB_SYSCALL_IMPL(sys_setrlimit) CREATE_STUB_SYSCALL_IMPL(sys_old_getrlimit) CREATE_STUB_SYSCALL_IMPL(sys_getrusage) int sys_gettimeofday(struct k_timeval *tv, struct timezone *tz); CREATE_STUB_SYSCALL_IMPL(sys_settimeofday) CREATE_STUB_SYSCALL_IMPL(sys_getgroups16) CREATE_STUB_SYSCALL_IMPL(sys_setgroups16) CREATE_STUB_SYSCALL_IMPL(sys_old_select) int sys_symlink(const char *u_target, const char *u_linkpath); CREATE_STUB_SYSCALL_IMPL(sys_lstat) int sys_readlink(const char *u_pathname, char *u_buf, size_t bufsize); CREATE_STUB_SYSCALL_IMPL(sys_uselib) CREATE_STUB_SYSCALL_IMPL(sys_swapon) int sys_reboot(u32 magic, u32 magic2, u32 cmd, void *arg); CREATE_STUB_SYSCALL_IMPL(sys_old_readdir) CREATE_STUB_SYSCALL_IMPL(sys_old_mmap) int sys_munmap(void *vaddr, size_t len); CREATE_STUB_SYSCALL_IMPL(sys_truncate) CREATE_STUB_SYSCALL_IMPL(sys_ftruncate) int sys_fchmod(int fd, mode_t mode); CREATE_STUB_SYSCALL_IMPL(sys_fchown16) CREATE_STUB_SYSCALL_IMPL(sys_getpriority) CREATE_STUB_SYSCALL_IMPL(sys_setpriority) CREATE_STUB_SYSCALL_IMPL(sys_statfs) CREATE_STUB_SYSCALL_IMPL(sys_fstatfs) CREATE_STUB_SYSCALL_IMPL(sys_ioperm) int sys_socketcall(int call, ulong *args); CREATE_STUB_SYSCALL_IMPL(sys_syslog) CREATE_STUB_SYSCALL_IMPL(sys_setitimer) CREATE_STUB_SYSCALL_IMPL(sys_getitimer) CREATE_STUB_SYSCALL_IMPL(sys_newstat) CREATE_STUB_SYSCALL_IMPL(sys_newlstat) CREATE_STUB_SYSCALL_IMPL(sys_newfstat) CREATE_STUB_SYSCALL_IMPL(sys_uname) CREATE_STUB_SYSCALL_IMPL(sys_iopl) CREATE_STUB_SYSCALL_IMPL(sys_vhangup) CREATE_STUB_SYSCALL_IMPL(sys_vm86old) int sys_wait4(int pid, int *u_wstatus, int options, void *u_rusage); CREATE_STUB_SYSCALL_IMPL(sys_swapoff) CREATE_STUB_SYSCALL_IMPL(sys_sysinfo) CREATE_STUB_SYSCALL_IMPL(sys_ipc) int sys_fsync(int fd); CREATE_STUB_SYSCALL_IMPL(sys_sigreturn); CREATE_STUB_SYSCALL_IMPL(sys_clone) CREATE_STUB_SYSCALL_IMPL(sys_setdomainname) int sys_newuname(struct utsname *buf); CREATE_STUB_SYSCALL_IMPL(sys_modify_ldt) CREATE_STUB_SYSCALL_IMPL(sys_adjtimex_time32) CREATE_STUB_SYSCALL_IMPL(sys_mprotect) int sys_sigprocmask(ulong a1, ulong a2, ulong a3); // deprecated interface CREATE_STUB_SYSCALL_IMPL(sys_init_module) CREATE_STUB_SYSCALL_IMPL(sys_delete_module) CREATE_STUB_SYSCALL_IMPL(sys_quotactl) int sys_getpgid(int pid); CREATE_STUB_SYSCALL_IMPL(sys_fchdir) CREATE_STUB_SYSCALL_IMPL(sys_bdflush) CREATE_STUB_SYSCALL_IMPL(sys_sysfs) CREATE_STUB_SYSCALL_IMPL(sys_personality) CREATE_STUB_SYSCALL_IMPL(sys_setfsuid16) CREATE_STUB_SYSCALL_IMPL(sys_setfsgid16) int sys_llseek(int fd, size_t off_hi, size_t off_low, u64 *result, u32 whence); CREATE_STUB_SYSCALL_IMPL(sys_getdents) int sys_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct k_timeval *timeout); CREATE_STUB_SYSCALL_IMPL(sys_flock) CREATE_STUB_SYSCALL_IMPL(sys_msync) int sys_readv(int fd, const struct iovec *iov, int iovcnt); int sys_writev(int fd, const struct iovec *iov, int iovcnt); int sys_getsid(int pid); int sys_fdatasync(int fd); CREATE_STUB_SYSCALL_IMPL(sys_sysctl) CREATE_STUB_SYSCALL_IMPL(sys_mlock) CREATE_STUB_SYSCALL_IMPL(sys_munlock) CREATE_STUB_SYSCALL_IMPL(sys_mlockall) CREATE_STUB_SYSCALL_IMPL(sys_munlockall) CREATE_STUB_SYSCALL_IMPL(sys_sched_setparam) CREATE_STUB_SYSCALL_IMPL(sys_sched_getparam) CREATE_STUB_SYSCALL_IMPL(sys_sched_setscheduler) CREATE_STUB_SYSCALL_IMPL(sys_sched_getscheduler) int sys_sched_yield(void); CREATE_STUB_SYSCALL_IMPL(sys_sched_get_priority_max) CREATE_STUB_SYSCALL_IMPL(sys_sched_set_priority_min) CREATE_STUB_SYSCALL_IMPL(sys_sched_rr_get_interval_time32) int sys_nanosleep_time32(const struct k_timespec32 *req, struct k_timespec32 *rem); CREATE_STUB_SYSCALL_IMPL(sys_mremap) CREATE_STUB_SYSCALL_IMPL(sys_setresuid16) CREATE_STUB_SYSCALL_IMPL(sys_getresuid16) CREATE_STUB_SYSCALL_IMPL(sys_vm86) int sys_poll(struct pollfd *fds, nfds_t nfds, int timeout); CREATE_STUB_SYSCALL_IMPL(sys_nfsservctl) CREATE_STUB_SYSCALL_IMPL(sys_setresgid16) CREATE_STUB_SYSCALL_IMPL(sys_getresgid16) int sys_prctl(int option, ulong a2, ulong a3, ulong a4, ulong a5); ulong sys_rt_sigreturn(void); int sys_rt_sigaction(int signum, const struct k_sigaction *act, struct k_sigaction *oldact, size_t sigsetsize); int sys_rt_sigprocmask(int how, sigset_t *u_set, sigset_t *u_oldset, size_t sigsetsize); int sys_rt_sigpending(sigset_t *u_set, size_t sigsetsize); CREATE_STUB_SYSCALL_IMPL(sys_rt_sigtimedwait_time32) CREATE_STUB_SYSCALL_IMPL(sys_rt_sigqueueinfo) int sys_rt_sigsuspend(sigset_t *u_mask, size_t sigsetsize); int sys_pread64(int fd, void *buf, size_t count, s64 off); int sys_pwrite64(int fd, const void *buf, size_t count, s64 off); CREATE_STUB_SYSCALL_IMPL(sys_chown16) int sys_getcwd(char *buf, size_t size); CREATE_STUB_SYSCALL_IMPL(sys_capget) CREATE_STUB_SYSCALL_IMPL(sys_capset) CREATE_STUB_SYSCALL_IMPL(sys_sigaltstack) CREATE_STUB_SYSCALL_IMPL(sys_sendfile) int sys_vfork(void); CREATE_STUB_SYSCALL_IMPL(sys_getrlimit) long sys_mmap_pgoff(void *addr, size_t length, int prot, int flags, int fd, size_t pgoffset); int sys_ia32_truncate64(const char *u_path, s64 length); int sys_ia32_ftruncate64(int fd, s64 length); int sys_stat64(const char *u_path, struct k_stat64 *u_statbuf); int sys_lstat64(const char *u_path, struct k_stat64 *u_statbuf); int sys_fstat64(int fd, struct k_stat64 *u_statbuf); int sys_lchown(const char *u_path, int owner, int group); int sys_getuid(void); int sys_getgid(void); int sys_geteuid(void); int sys_getegid(void); CREATE_STUB_SYSCALL_IMPL(sys_setreuid) CREATE_STUB_SYSCALL_IMPL(sys_setregid) CREATE_STUB_SYSCALL_IMPL(sys_getgroups) CREATE_STUB_SYSCALL_IMPL(sys_setgroups) int sys_fchown(int fd, uid_t owner, gid_t group); CREATE_STUB_SYSCALL_IMPL(sys_setresuid) CREATE_STUB_SYSCALL_IMPL(sys_getresuid) CREATE_STUB_SYSCALL_IMPL(sys_setresgid) CREATE_STUB_SYSCALL_IMPL(sys_getresgid) int sys_chown(const char *u_path, int owner, int group); int sys_setuid(ulong uid); int sys_setgid(ulong gid); CREATE_STUB_SYSCALL_IMPL(sys_setfsuid) CREATE_STUB_SYSCALL_IMPL(sys_setfsgid) CREATE_STUB_SYSCALL_IMPL(sys_pivot_root) CREATE_STUB_SYSCALL_IMPL(sys_mincore) int sys_madvise(void *addr, size_t len, int advice); int sys_getdents64(int fd, struct linux_dirent64 *dirp, u32 buf_size); int sys_fcntl64(int fd, int cmd, int arg); int sys_gettid(void); CREATE_STUB_SYSCALL_IMPL(sys_ia32_readahead) CREATE_STUB_SYSCALL_IMPL(sys_setxattr) CREATE_STUB_SYSCALL_IMPL(sys_lsetxattr) CREATE_STUB_SYSCALL_IMPL(sys_fsetxattr) CREATE_STUB_SYSCALL_IMPL(sys_getxattr) CREATE_STUB_SYSCALL_IMPL(sys_lgetxattr) CREATE_STUB_SYSCALL_IMPL(sys_fgetxattr) CREATE_STUB_SYSCALL_IMPL(sys_listxattr) CREATE_STUB_SYSCALL_IMPL(sys_llistxattr) CREATE_STUB_SYSCALL_IMPL(sys_flistxattr) CREATE_STUB_SYSCALL_IMPL(sys_removexattr) CREATE_STUB_SYSCALL_IMPL(sys_lremovexattr) CREATE_STUB_SYSCALL_IMPL(sys_fremovexattr) int sys_tkill(int tid, int sig); CREATE_STUB_SYSCALL_IMPL(sys_sendfile64) CREATE_STUB_SYSCALL_IMPL(sys_futex_time32) CREATE_STUB_SYSCALL_IMPL(sys_sched_setaffinity) CREATE_STUB_SYSCALL_IMPL(sys_sched_getaffinity) int sys_set_thread_area(void *u_info); CREATE_STUB_SYSCALL_IMPL(sys_get_thread_area) CREATE_STUB_SYSCALL_IMPL(sys_io_setup) CREATE_STUB_SYSCALL_IMPL(sys_io_destroy) CREATE_STUB_SYSCALL_IMPL(sys_io_getevents_time32) CREATE_STUB_SYSCALL_IMPL(sys_io_submit) CREATE_STUB_SYSCALL_IMPL(sys_io_cancel) CREATE_STUB_SYSCALL_IMPL(sys_ia32_fadvise64) NORETURN int sys_exit_group(int status); CREATE_STUB_SYSCALL_IMPL(sys_lookup_dcookie) CREATE_STUB_SYSCALL_IMPL(sys_epoll_create) CREATE_STUB_SYSCALL_IMPL(sys_epoll_ctl) CREATE_STUB_SYSCALL_IMPL(sys_epoll_wait) CREATE_STUB_SYSCALL_IMPL(sys_remap_file_pages) // TODO: complete the implementation when thread creation is implemented. int sys_set_tid_address(int *tidptr); CREATE_STUB_SYSCALL_IMPL(sys_timer_create) CREATE_STUB_SYSCALL_IMPL(sys_timer_settime32) CREATE_STUB_SYSCALL_IMPL(sys_timer_gettime32) CREATE_STUB_SYSCALL_IMPL(sys_timer_getoverrun) CREATE_STUB_SYSCALL_IMPL(sys_timer_delete) CREATE_STUB_SYSCALL_IMPL(sys_clock_settime32) int sys_clock_gettime32(clockid_t clk_id, struct k_timespec32 *tp); int sys_clock_getres_time32(clockid_t clk_id, struct k_timespec32 *res); CREATE_STUB_SYSCALL_IMPL(sys_clock_nanosleep_time32) CREATE_STUB_SYSCALL_IMPL(sys_statfs64) CREATE_STUB_SYSCALL_IMPL(sys_fstatfs64) int sys_tgkill(int pid /* linux: tgid */, int tid, int sig); int sys_utimes(const char *u_path, const struct k_timeval u_times[2]); CREATE_STUB_SYSCALL_IMPL(sys_ia32_fadvise64_64) CREATE_STUB_SYSCALL_IMPL(sys_mbind) CREATE_STUB_SYSCALL_IMPL(sys_get_mempolicy) CREATE_STUB_SYSCALL_IMPL(sys_set_mempolicy) CREATE_STUB_SYSCALL_IMPL(sys_mq_open) CREATE_STUB_SYSCALL_IMPL(sys_mq_unlink) CREATE_STUB_SYSCALL_IMPL(sys_mq_timedsend_time32) CREATE_STUB_SYSCALL_IMPL(sys_mq_timedreceive_time32) CREATE_STUB_SYSCALL_IMPL(sys_mq_notify) CREATE_STUB_SYSCALL_IMPL(sys_mq_getsetattr) CREATE_STUB_SYSCALL_IMPL(sys_kexec_load) CREATE_STUB_SYSCALL_IMPL(sys_waitid) CREATE_STUB_SYSCALL_IMPL(sys_add_key) CREATE_STUB_SYSCALL_IMPL(sys_request_key) CREATE_STUB_SYSCALL_IMPL(sys_keyctl) CREATE_STUB_SYSCALL_IMPL(sys_ioprio_set) CREATE_STUB_SYSCALL_IMPL(sys_ioprio_get) CREATE_STUB_SYSCALL_IMPL(sys_inotify_init) CREATE_STUB_SYSCALL_IMPL(sys_inotify_add_watch) CREATE_STUB_SYSCALL_IMPL(sys_inotify_rm_watch) CREATE_STUB_SYSCALL_IMPL(sys_migrate_pages) CREATE_STUB_SYSCALL_IMPL(sys_openat) CREATE_STUB_SYSCALL_IMPL(sys_mkdirat) CREATE_STUB_SYSCALL_IMPL(sys_mknodat) CREATE_STUB_SYSCALL_IMPL(sys_fchownat) int sys_futimesat_time32(int dirfd, const char *u_path, const struct k_timeval times[2]); CREATE_STUB_SYSCALL_IMPL(sys_fstatat64) CREATE_STUB_SYSCALL_IMPL(sys_unlinkat) CREATE_STUB_SYSCALL_IMPL(sys_renameat) CREATE_STUB_SYSCALL_IMPL(sys_linkat) CREATE_STUB_SYSCALL_IMPL(sys_symlinkat) CREATE_STUB_SYSCALL_IMPL(sys_readlinkat) CREATE_STUB_SYSCALL_IMPL(sys_fchmodat) CREATE_STUB_SYSCALL_IMPL(sys_faccessat) CREATE_STUB_SYSCALL_IMPL(sys_pselect6) CREATE_STUB_SYSCALL_IMPL(sys_ppoll) CREATE_STUB_SYSCALL_IMPL(sys_unshare) CREATE_STUB_SYSCALL_IMPL(sys_set_robust_list) CREATE_STUB_SYSCALL_IMPL(sys_get_robust_list) CREATE_STUB_SYSCALL_IMPL(sys_splice) CREATE_STUB_SYSCALL_IMPL(sys_ia32_sync_file_range) CREATE_STUB_SYSCALL_IMPL(sys_tee) CREATE_STUB_SYSCALL_IMPL(sys_vmsplice) CREATE_STUB_SYSCALL_IMPL(sys_move_pages) CREATE_STUB_SYSCALL_IMPL(sys_getcpu) CREATE_STUB_SYSCALL_IMPL(sys_epoll_pwait) int sys_utimensat_time32(int dirfd, const char *u_path, const struct k_timespec32 times[2], int flags); CREATE_STUB_SYSCALL_IMPL(sys_signalfd) CREATE_STUB_SYSCALL_IMPL(sys_timerfd_create) CREATE_STUB_SYSCALL_IMPL(sys_eventfd) CREATE_STUB_SYSCALL_IMPL(sys_fallocate) CREATE_STUB_SYSCALL_IMPL(sys_timerfd_settime32) CREATE_STUB_SYSCALL_IMPL(sys_timerfd_gettime32) CREATE_STUB_SYSCALL_IMPL(sys_signalfd4) CREATE_STUB_SYSCALL_IMPL(sys_eventfd2) CREATE_STUB_SYSCALL_IMPL(sys_epoll_create1) CREATE_STUB_SYSCALL_IMPL(sys_dup3) int sys_pipe2(int u_pipefd[2], int flags); CREATE_STUB_SYSCALL_IMPL(sys_inotify_init1) CREATE_STUB_SYSCALL_IMPL(sys_preadv) CREATE_STUB_SYSCALL_IMPL(sys_pwritev) CREATE_STUB_SYSCALL_IMPL(sys_rt_tgsigqueueinfo) CREATE_STUB_SYSCALL_IMPL(sys_perf_event_open) CREATE_STUB_SYSCALL_IMPL(sys_recvmmsg_time32) CREATE_STUB_SYSCALL_IMPL(sys_fanotify_init) CREATE_STUB_SYSCALL_IMPL(sys_fanotify_mark) CREATE_STUB_SYSCALL_IMPL(sys_prlimit64) CREATE_STUB_SYSCALL_IMPL(sys_name_to_handle_at) CREATE_STUB_SYSCALL_IMPL(sys_open_by_handle_at) CREATE_STUB_SYSCALL_IMPL(sys_clock_adjtime32) int sys_syncfs(int fd); CREATE_STUB_SYSCALL_IMPL(sys_sendmmsg) CREATE_STUB_SYSCALL_IMPL(sys_setns) CREATE_STUB_SYSCALL_IMPL(sys_process_vm_readv) CREATE_STUB_SYSCALL_IMPL(sys_process_vm_writev) CREATE_STUB_SYSCALL_IMPL(sys_kcmp) CREATE_STUB_SYSCALL_IMPL(sys_finit_module) CREATE_STUB_SYSCALL_IMPL(sys_sched_setattr) CREATE_STUB_SYSCALL_IMPL(sys_sched_getattr) CREATE_STUB_SYSCALL_IMPL(sys_renameat2) CREATE_STUB_SYSCALL_IMPL(sys_seccomp) CREATE_STUB_SYSCALL_IMPL(sys_getrandom) CREATE_STUB_SYSCALL_IMPL(sys_memfd_create) CREATE_STUB_SYSCALL_IMPL(sys_bpf) CREATE_STUB_SYSCALL_IMPL(sys_execveat) CREATE_STUB_SYSCALL_IMPL(sys_socket) CREATE_STUB_SYSCALL_IMPL(sys_socketpair) CREATE_STUB_SYSCALL_IMPL(sys_bind) CREATE_STUB_SYSCALL_IMPL(sys_connect) CREATE_STUB_SYSCALL_IMPL(sys_listen) CREATE_STUB_SYSCALL_IMPL(sys_accept4) CREATE_STUB_SYSCALL_IMPL(sys_getsockopt) CREATE_STUB_SYSCALL_IMPL(sys_setsockopt) CREATE_STUB_SYSCALL_IMPL(sys_getsockname) CREATE_STUB_SYSCALL_IMPL(sys_getpeername) CREATE_STUB_SYSCALL_IMPL(sys_sendto) CREATE_STUB_SYSCALL_IMPL(sys_sendmsg) CREATE_STUB_SYSCALL_IMPL(sys_recvfrom) CREATE_STUB_SYSCALL_IMPL(sys_recvmsg) CREATE_STUB_SYSCALL_IMPL(sys_shutdown) CREATE_STUB_SYSCALL_IMPL(sys_userfaultfd) CREATE_STUB_SYSCALL_IMPL(sys_membarrier) CREATE_STUB_SYSCALL_IMPL(sys_mlock2) CREATE_STUB_SYSCALL_IMPL(sys_copy_file_range) CREATE_STUB_SYSCALL_IMPL(sys_preadv2) CREATE_STUB_SYSCALL_IMPL(sys_pwritev2) CREATE_STUB_SYSCALL_IMPL(sys_pkey_mprotect) CREATE_STUB_SYSCALL_IMPL(sys_pkey_alloc) CREATE_STUB_SYSCALL_IMPL(sys_pkey_free) CREATE_STUB_SYSCALL_IMPL(sys_statx) CREATE_STUB_SYSCALL_IMPL(sys_arch_prctl) CREATE_STUB_SYSCALL_IMPL(sys_io_pgetevents_time32) CREATE_STUB_SYSCALL_IMPL(sys_rseq) CREATE_STUB_SYSCALL_IMPL(sys_semget) CREATE_STUB_SYSCALL_IMPL(sys_semctl) CREATE_STUB_SYSCALL_IMPL(sys_shmget) CREATE_STUB_SYSCALL_IMPL(sys_shmctl) CREATE_STUB_SYSCALL_IMPL(sys_shmat) CREATE_STUB_SYSCALL_IMPL(sys_shmdt) CREATE_STUB_SYSCALL_IMPL(sys_msgget) CREATE_STUB_SYSCALL_IMPL(sys_msgsnd) CREATE_STUB_SYSCALL_IMPL(sys_msgrcv) CREATE_STUB_SYSCALL_IMPL(sys_msgctl) int sys_clock_gettime(clockid_t clk_id, struct k_timespec64 *user_tp); CREATE_STUB_SYSCALL_IMPL(sys_clock_settime) CREATE_STUB_SYSCALL_IMPL(sys_clock_adjtime) int sys_clock_getres(clockid_t clk_id, struct k_timespec64 *user_res); CREATE_STUB_SYSCALL_IMPL(sys_clock_nanosleep) CREATE_STUB_SYSCALL_IMPL(sys_timer_gettime) CREATE_STUB_SYSCALL_IMPL(sys_timer_settime) CREATE_STUB_SYSCALL_IMPL(sys_timerfd_gettime) CREATE_STUB_SYSCALL_IMPL(sys_timerfd_settime) CREATE_STUB_SYSCALL_IMPL(sys_utimensat) CREATE_STUB_SYSCALL_IMPL(sys_pselect6_time32) CREATE_STUB_SYSCALL_IMPL(sys_ppoll_time32) CREATE_STUB_SYSCALL_IMPL(sys_io_pgetevents) CREATE_STUB_SYSCALL_IMPL(sys_recvmmsg) CREATE_STUB_SYSCALL_IMPL(sys_mq_timedsend) CREATE_STUB_SYSCALL_IMPL(sys_mq_timedreceive) CREATE_STUB_SYSCALL_IMPL(sys_semtimedop) CREATE_STUB_SYSCALL_IMPL(sys_rt_sigtimedwait) CREATE_STUB_SYSCALL_IMPL(sys_futex) CREATE_STUB_SYSCALL_IMPL(sys_sched_rr_get_interval) CREATE_STUB_SYSCALL_IMPL(sys_pidfd_send_signal) CREATE_STUB_SYSCALL_IMPL(sys_io_uring_setup) CREATE_STUB_SYSCALL_IMPL(sys_io_uring_enter) CREATE_STUB_SYSCALL_IMPL(sys_io_uring_register) CREATE_STUB_SYSCALL_IMPL(sys_open_tree) CREATE_STUB_SYSCALL_IMPL(sys_move_mount) CREATE_STUB_SYSCALL_IMPL(sys_fsopen) CREATE_STUB_SYSCALL_IMPL(sys_fsconfig) CREATE_STUB_SYSCALL_IMPL(sys_fsmount) CREATE_STUB_SYSCALL_IMPL(sys_fspick) CREATE_STUB_SYSCALL_IMPL(sys_pidfd_open) CREATE_STUB_SYSCALL_IMPL(sys_clone3) CREATE_STUB_SYSCALL_IMPL(sys_close_range) CREATE_STUB_SYSCALL_IMPL(sys_openat2) CREATE_STUB_SYSCALL_IMPL(sys_pidfd_getfd) CREATE_STUB_SYSCALL_IMPL(sys_faccessat2) CREATE_STUB_SYSCALL_IMPL(sys_process_madvise) CREATE_STUB_SYSCALL_IMPL(sys_epoll_pwait2) CREATE_STUB_SYSCALL_IMPL(sys_mount_setattr) CREATE_STUB_SYSCALL_IMPL(sys_quotactl_fd) CREATE_STUB_SYSCALL_IMPL(sys_landlock_create_ruleset) CREATE_STUB_SYSCALL_IMPL(sys_landlock_add_rule) CREATE_STUB_SYSCALL_IMPL(sys_landlock_restrict_self) CREATE_STUB_SYSCALL_IMPL(sys_memfd_secret) CREATE_STUB_SYSCALL_IMPL(sys_process_mrelease) int sys_tilck_cmd(int cmd_n, ulong a1, ulong a2, ulong a3, ulong a4); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include "common_int.h" static void print_string(const char *s) { while (*s) intf->write_char(*s++); } static void print_ll(char fmtX, char *buf, u64 val) { switch (fmtX) { case 'i': case 'd': itoa64((s64)val, buf); break; case 'u': uitoa64(val, buf, 10); break; case 'x': uitoa64_hex_fixed(val, buf); break; default: buf[0] = 0; } if (buf[0]) print_string(buf); } void vprintk(const char *fmt, va_list args) { char buf[64]; for (const char *ptr = fmt; *ptr; ptr++) { if (*ptr != '%') { intf->write_char(*ptr); continue; } /* OK, we read '%', forward by one */ ptr++; switch (*ptr) { case '%': intf->write_char(*ptr); break; case 'l': ptr++; if (!*ptr) return; if (*ptr == 'l') { /* OK, we've got %ll */ ptr++; if (!*ptr) return; print_ll(*ptr, buf, va_arg(args, u64)); } else { if (sizeof(long) > sizeof(int)) { print_ll(*ptr, buf, va_arg(args, u64)); } else { /* Just ignore %l and treat %ld as %d */ } } break; case 'd': case 'i': itoa32(va_arg(args, s32), buf); print_string(buf); break; case 'u': uitoa32(va_arg(args, u32), buf, 10); print_string(buf); break; case 'x': uitoa32(va_arg(args, u32), buf, 16); print_string(buf); break; case 'c': intf->write_char((char)va_arg(args, int)); break; case 's': print_string(va_arg(args, const char *)); break; case 'p': uitoaN_hex_fixed(va_arg(args, ulong), buf); print_string("0x"); print_string(buf); break; default: intf->write_char('%'); intf->write_char(*ptr); } } } void printk(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintk(fmt, args); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define FL_NODE_SPLIT (1 << 0) #define FL_NODE_FULL (1 << 1) #define FL_NODE_ALLOCATED (1 << 2) #define FL_NODE_SPLIT_AND_FULL (FL_NODE_SPLIT | FL_NODE_FULL) #define FL_NODE_ALLOCATED_AND_FULL (FL_NODE_ALLOCATED | FL_NODE_FULL) #define FL_NODE_ALLOCATED_AND_SPLIT (FL_NODE_ALLOCATED | FL_NODE_SPLIT) struct block_node { union { struct { // 1 if the block has been split. Check its children. u8 split : 1; // 1 means obviously completely full // 0 means completely empty if split=0, or partially empty if split=1 u8 full : 1; u8 allocated : 1; // only for nodes with size = alloc_block_size u8 alloc_failed : 1; // only for nodes with size = alloc_block_size u8 unused : 4; // Free unused (for now) bits. }; u8 raw; }; }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/sys_types.h> #include <tilck/kernel/list.h> typedef int (*func_create_per_handle_extra)(int minor, void *extra); typedef int (*func_on_dup_per_handle_extra)(int minor, void *extra); typedef void (*func_destroy_per_handle_extra)(int minor, void *extra); #define DEVFS_EXTRA_SIZE (7 * sizeof(void *)) struct devfs_file_info { const struct file_ops *fops; u16 spec_flags; func_create_per_handle_extra create_extra; func_on_dup_per_handle_extra on_dup_extra; func_destroy_per_handle_extra destroy_extra; }; struct devfs_file { enum vfs_entry_type type; /* Must be FIRST, because of devfs_dir */ struct list_node dir_node; struct devfs_file_info nfo; u16 dev_major; u16 dev_minor; const char *name; tilck_ino_t inode; }; struct devfs_handle { /* struct fs_handle_base */ FS_HANDLE_BASE_FIELDS /* devfs-specific fields */ enum vfs_entry_type type; union { struct devfs_file *dpos; /* valid only if type == VFS_DIR */ struct { struct devfs_file *file; /* valid only if type != VFS_DIR */ char extra[DEVFS_EXTRA_SIZE] ALIGNED_AT(sizeof(void *)); }; }; }; STATIC_ASSERT(sizeof(struct devfs_handle) <= MAX_FS_HANDLE_SIZE); typedef int (*func_create_device_file)(int minor, enum vfs_entry_type *type, struct devfs_file_info *nfo); struct driver_info { u16 major; const char *name; func_create_device_file create_dev_file; }; struct mnt_fs *create_devfs(void); void init_devfs(void); int register_driver(struct driver_info *info, int major); int create_dev_file(const char *filename, u16 major, u16 minor, void **devfile); struct mnt_fs *get_devfs(void); struct driver_info *get_driver_info(u16 major); /* Special interface for in-kernel use of devfs handles */ int devfs_kernel_create_handle_for(void *devfile, fs_handle *out); void devfs_kernel_destory_handle(fs_handle h); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/list.h> #define PCI_CLASS_NONE 0x00 #define PCI_CLASS_MASS_STORAGE 0x01 #define PCI_CLASS_NETWORK 0x02 #define PCI_CLASS_DISPLAY 0x03 #define PCI_CLASS_MULTIMEDIA 0x04 #define PCI_CLASS_MEMORY 0x05 #define PCI_CLASS_BRIDGE 0x06 #define PCI_CLASS_COMMUNICATION 0x07 #define PCI_CLASS_GENERIC_PERIPHERAL 0x08 #define PCI_CLASS_INPUT 0x09 #define PCI_CLASS_DOCKING_STATION 0x0a #define PCI_CLASS_PROCESSOR 0x0b #define PCI_CLASS_SERIAL_BUS 0x0c #define PCI_CLASS_WIRELESS 0x0d #define PCI_CLASS_INTELLIGENT 0x0e #define PCI_CLASS_SATELLITE_COMM 0x0f #define PCI_CLASS_ENCRYPTION 0x10 #define PCI_CLASS_SIGNAL_PROCESSING 0x11 #define PCI_CLASS_PROC_ACC 0x12 #define PCI_CLASS_NON_ESSENTIAL_INST 0x13 #define PCI_CLASS_COPROC 0x40 #define PCI_CLASS_UNASSIGNED 0xff #define PCI_SUBCLASS_PCI_BRIDGE 0x04 struct pci_vendor { u16 vendor_id; const char *name; }; struct pci_device_class { u8 class_id; u8 subclass_id; u8 progif_id; const char *class_name; const char *subclass_name; const char *progif_name; }; struct pci_device_loc { union { struct { u16 seg; /* PCI Segment Group Number */ u8 bus; /* PCI Bus */ u8 dev : 5; /* PCI Device Number */ u8 func : 3; /* PCI Function Number */ }; u32 raw; }; }; struct pci_device_basic_info { union { struct { u16 vendor_id; u16 device_id; }; u32 __dev_vendr; }; union { struct { u8 rev_id; u8 progif_id; u8 subclass_id; u8 class_id; }; u32 __class_info; }; union { struct { u8 header_type : 7; u8 multi_func : 1; }; u8 __header_type; }; }; /* * PCI leaf node: a PCI device function. * * It's called just `device` and not `device_function` because it represents * a logical device, not a physical one. Also, `pci_device` is just shorter * and feels more natural than `pci_device_function` or `pci_device_node`. */ struct pci_device { struct list_node node; struct pci_device_loc loc; struct pci_device_basic_info nfo; void *ext_config; }; static ALWAYS_INLINE struct pci_device_loc pci_make_loc(u16 seg, u8 bus, u8 dev, u8 func) { struct pci_device_loc ret; ret.seg = seg; ret.bus = bus; ret.dev = dev & 0b11111; ret.func = func & 0b00111; return ret; } const char * pci_find_vendor_name(u16 id); void pci_find_device_class_name(struct pci_device_class *dev_class); static inline int pci_config_read(struct pci_device_loc loc, u32 off, u32 width, u32 *val) { extern int (*__pci_config_read_func)(struct pci_device_loc, u32, u32, u32 *); return __pci_config_read_func(loc, off, width, val); } static inline int pci_config_write(struct pci_device_loc loc, u32 off, u32 width, u32 val) { extern int (*__pci_config_write_func)(struct pci_device_loc, u32, u32, u32); return __pci_config_write_func(loc, off, width, val); } struct pci_device * pci_get_object(struct pci_device_loc loc); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* Key definitions (partial) for PS/2 scancode set 1 */ #define KEY_L_SHIFT 0x2A #define KEY_R_SHIFT 0x36 #define KEY_NUM_LOCK 0x45 #define KEY_CAPS_LOCK 0x3A #define KEY_F1 0x3B #define KEY_F2 (KEY_F1 + 1) #define KEY_F3 (KEY_F1 + 2) #define KEY_F4 (KEY_F1 + 3) #define KEY_F5 (KEY_F1 + 4) #define KEY_F6 (KEY_F1 + 5) #define KEY_F7 (KEY_F1 + 6) #define KEY_F8 (KEY_F1 + 7) #define KEY_F9 (KEY_F1 + 8) #define KEY_F10 (KEY_F1 + 9) #define KEY_F11 0x57 #define KEY_F12 0x58 #define KEY_UP 0xE048 #define KEY_DOWN 0xE050 #define KEY_RIGHT 0xE04d #define KEY_LEFT 0xE04b #define KEY_NUMPAD_UP 0x48 #define KEY_NUMPAD_DOWN 0x50 #define KEY_NUMPAD_RIGHT 0x4d #define KEY_NUMPAD_LEFT 0x4b #define KEY_LEFT_CTRL 0x1d #define KEY_RIGHT_CTRL 0xE01d #define KEY_LEFT_ALT 0x38 #define KEY_RIGHT_ALT 0xE038 #define KEY_INS 0xE052 #define KEY_NUMPAD_INS 0x52 #define KEY_HOME 0xE047 #define KEY_NUMPAD_HOME 0x47 #define KEY_DEL 0xE053 #define KEY_NUMPAD_DEL 0x53 #define KEY_END 0xE04f #define KEY_NUMPAD_END 0x4f #define KEY_PAGE_UP 0xE049 #define KEY_NUMPAD_PAGE_UP 0x49 #define KEY_PAGE_DOWN 0xE051 #define KEY_NUMPAD_PAGE_DOWN 0x51 #define KEY_NUMPAD_ENTER 0xE01c #define KEY_NUMPAD_SLASH 0xE035 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #include <tilck_gen_headers/config_kernel.h> /* --------- Boolean config variables --------- */ /* enabled by default */ #cmakedefine01 KRN_TRACK_NESTED_INTERR #cmakedefine01 PANIC_SHOW_STACKTRACE #cmakedefine01 KERNEL_SELFTESTS #cmakedefine01 KERNEL_STACK_ISOLATION #cmakedefine01 KERNEL_SYMBOLS /* disabled by default */ #cmakedefine01 PANIC_SHOW_REGS /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are many dervied constants and convenience constants like * COMPILER_NAME along with some pseudo-constants like USERMODE_VADDR_END not * designed to be easily changed because of the code makes assumptions about * them. Because of that, those constants are hard-coded and not available as * CMake variables. With time, some of those constants get "promoted" and moved * in CMake, others remain here. See the comments and think about the potential * implications before promoting a hard-coded constant to a configurable CMake * variable. */ /* Special advanced developer-only debug utils */ #define KMUTEX_STATS_ENABLED 0 #define SLOW_DEBUG_REF_COUNT 0 /* ------------------------------- */ #if !KERNEL_GCOV #if ARCH_BITS == 32 #define SYMTAB_MAX_SIZE ( 96 * KB) #else #define SYMTAB_MAX_SIZE ( 128 * KB) #endif #define STRTAB_MAX_SIZE ( 96 * KB) #else #define SYMTAB_MAX_SIZE ( 224 * KB) #define STRTAB_MAX_SIZE ( 224 * KB) #endif /* * QEMU-specific debug constants. For the moment, keep those defines always * defined. Unless qemu is run with: * * -device isa-debug-exit,iobase=0xf4,iosize=0x04 * * debug_qemu_turn_off_machine() won't turn off the VM. Also it's worth * remarking debug_qemu_turn_off_machine() does *nothing* if we're running on * real HW (because it checks x86_cpu_features.ecx1.hypervisor). */ #define DEBUG_QEMU_EXIT_ON_INIT_EXIT 1 #define DEBUG_QEMU_EXIT_ON_PANIC 1 <file_sep>#!/usr/bin/env bash BUILD_DIR="@CMAKE_BINARY_DIR@" $BUILD_DIR/run_multiboot_nokvm_qemu -S "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/user.h> #include <tilck/kernel/sys_types.h> #include <tilck/mods/tracing.h> static bool dump_param_int(ulong __val, long hlp, char *dest, size_t dest_buf_size) { const long val = (long)__val; int rc; rc = snprintk(dest, dest_buf_size, NBITS == 32 ? "%d" : "%lld", val); return rc < (int)dest_buf_size; } static bool dump_param_voidp(ulong val, long hlp, char *dest, size_t dest_buf_size) { const int rc = (val != 0) ? snprintk(dest, dest_buf_size, "%p", val) : snprintk(dest, dest_buf_size, "NULL"); return rc < (int)dest_buf_size; } static bool dump_param_oct(ulong __val, long hlp, char *dest, size_t dest_buf_size) { int val = (int)__val; int rc; rc = snprintk(dest, dest_buf_size, "0%03o", val); return rc < (int)dest_buf_size; } static bool dump_param_errno_or_val(ulong __val, long hlp, char *dest, size_t dest_buf_size) { int val = (int)__val; int rc; rc = (val >= 0) ? snprintk(dest, dest_buf_size, "%d", val) : snprintk(dest, dest_buf_size, "-%s", get_errno_name(-val)); return rc < (int)dest_buf_size; } static bool dump_param_errno_or_ptr(ulong __val, long hlp, char *dest, size_t dest_buf_size) { long val = (long)__val; int rc; rc = (val >= 0 || val < -500 /* the smallest errno */) ? snprintk(dest, dest_buf_size, "%p", val) : snprintk(dest, dest_buf_size, "-%s", get_errno_name((int)-val)); return rc < (int)dest_buf_size; } bool buf_append(char *dest, int *used, int *rem, char *str) { int rc; ASSERT(*rem >= 0); if (*rem == 0) return false; rc = snprintk(dest + *used, (size_t) *rem, "%s", str); if (rc >= *rem) return false; *used += rc; *rem -= rc; return true; } static ALWAYS_INLINE bool is_flag_on(ulong var, ulong fl) { return (var & fl) == fl; } #define OPEN_CHECK_FLAG(x) \ if (is_flag_on(fl, x)) \ if (!buf_append(dest, &used, &rem, #x "|")) \ return false; static bool dump_param_open_flags(ulong fl, long hlp, char *dest, size_t dest_buf_size) { int rem = (int) dest_buf_size; int used = 0; if (fl == 0) { memcpy(dest, "0", 2); return true; } OPEN_CHECK_FLAG(O_APPEND) OPEN_CHECK_FLAG(O_ASYNC) OPEN_CHECK_FLAG(O_CLOEXEC) OPEN_CHECK_FLAG(O_CREAT) OPEN_CHECK_FLAG(O_DIRECT) OPEN_CHECK_FLAG(O_DIRECTORY) OPEN_CHECK_FLAG(O_DSYNC) OPEN_CHECK_FLAG(O_EXCL) OPEN_CHECK_FLAG(O_LARGEFILE) OPEN_CHECK_FLAG(O_NOATIME) OPEN_CHECK_FLAG(O_NOCTTY) OPEN_CHECK_FLAG(O_NOFOLLOW) OPEN_CHECK_FLAG(O_NONBLOCK) OPEN_CHECK_FLAG(O_NDELAY) OPEN_CHECK_FLAG(O_PATH) OPEN_CHECK_FLAG(O_SYNC) OPEN_CHECK_FLAG(O_TMPFILE) OPEN_CHECK_FLAG(O_TRUNC) ASSERT(dest[used - 1] == '|'); dest[used - 1] = 0; return true; } static bool dump_param_doff64(ulong hi, long hlp, char *dest, size_t dest_bs) { const ulong low = (ulong)hlp; const u64 val = ((u64)hi) << 32 | (u64)low; const int rc = snprintk(dest, dest_bs, "%llu", val); return rc < (int)dest_bs; } static bool dump_param_whence(ulong val, long hlp, char *dest, size_t dest_bs) { int rc; switch (val) { case SEEK_SET: rc = snprintk(dest, dest_bs, "SEEK_SET"); break; case SEEK_CUR: rc = snprintk(dest, dest_bs, "SEEK_CUR"); break; case SEEK_END: rc = snprintk(dest, dest_bs, "SEEK_END"); break; default: rc = snprintk(dest, dest_bs, "unknown: %d", (int)val); } return rc < (int)dest_bs; } const struct sys_param_type ptype_int = { .name = "int", .slot_size = 0, .ui_type = ui_type_integer, .save = NULL, .dump = NULL, .dump_from_val = dump_param_int, }; const struct sys_param_type ptype_voidp = { .name = "void *", .slot_size = 0, .save = NULL, .dump = NULL, .dump_from_val = dump_param_voidp, }; const struct sys_param_type ptype_oct = { .name = "oct", .slot_size = 0, .ui_type = ui_type_integer, .save = NULL, .dump = NULL, .dump_from_val = dump_param_oct, }; const struct sys_param_type ptype_errno_or_val = { .name = "errno_or_val", .slot_size = 0, .ui_type = ui_type_integer, .save = NULL, .dump = NULL, .dump_from_val = dump_param_errno_or_val, }; const struct sys_param_type ptype_errno_or_ptr = { .name = "errno_or_ptr", .slot_size = 0, .save = NULL, .dump = NULL, .dump_from_val = dump_param_errno_or_ptr, }; const struct sys_param_type ptype_open_flags = { .name = "int", .slot_size = 0, .save = NULL, .dump = NULL, .dump_from_val = dump_param_open_flags, }; const struct sys_param_type ptype_doff64 = { .name = "ulong", .slot_size = 0, .ui_type = ui_type_integer, .save = NULL, .dump = NULL, .dump_from_val = dump_param_doff64, }; const struct sys_param_type ptype_whence = { .name = "char *", .slot_size = 0, .save = NULL, .dump = NULL, .dump_from_val = dump_param_whence, }; struct saved_int_pair_data { bool valid; int pair[2]; }; static bool save_param_int_pair(void *data, long unused, char *dest_buf, size_t dest_bs) { struct saved_int_pair_data *saved_data = (void *)dest_buf; ASSERT(dest_bs >= sizeof(struct saved_int_pair_data)); if (copy_from_user(saved_data->pair, data, sizeof(int) * 2)) saved_data->valid = false; else saved_data->valid = true; return true; } static bool dump_param_int_pair(ulong orig, char *__data, long unused1, long unused2, char *dest, size_t dest_bs) { int rc; struct saved_int_pair_data *data = (void *)__data; if (!data->valid) { snprintk(dest, dest_bs, "<fault>"); return true; } rc = snprintk(dest, dest_bs, "{%d, %d}", data->pair[0], data->pair[1]); return rc <= (int) dest_bs; } const struct sys_param_type ptype_int32_pair = { .name = "int[2]", .slot_size = 32, .save = save_param_int_pair, .dump = dump_param_int_pair, .dump_from_val = NULL, }; static bool save_param_u64_ptr(void *data, long unused, char *dest_buf, size_t dest_bs) { ASSERT(dest_bs >= 8); u64 val; if (copy_from_user(&val, data, 8)) { snprintk(dest_buf, dest_bs, "<fault>"); return true; } snprintk(dest_buf, dest_bs, "%llu", val); return true; } static bool dump_param_u64_ptr(ulong orig, char *data, long unused1, long unused2, char *dest, size_t dest_bs) { memcpy(dest, data, strlen(data) + 1); return true; } const struct sys_param_type ptype_u64_ptr = { .name = "u64", .slot_size = 32, .ui_type = ui_type_integer, .save = save_param_u64_ptr, .dump = dump_param_u64_ptr, .dump_from_val = NULL, }; static bool dump_signum_param(ulong val, long hlp, char *dest, size_t dest_buf_size) { int signum = (int)val; int written = snprintk( dest, dest_buf_size, "%d [%s]", signum, get_signal_name(signum) ); if (written <= 0 || written == (int)dest_buf_size) return false; return true; } const struct sys_param_type ptype_signum = { .name = "signum", .slot_size = 0, .save = NULL, .dump = NULL, .dump_from_val = dump_signum_param, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/utils.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/syscalls.h> #include <sys/mman.h> // system header char page_size_buf[PAGE_SIZE] ALIGNED_AT(PAGE_SIZE); static inline void sys_brk_internal(struct process *pi, void *new_brk) { ASSERT(!is_preemption_enabled()); if (new_brk < pi->brk) { /* we have to free pages */ for (void *vaddr = new_brk; vaddr < pi->brk; vaddr += PAGE_SIZE) { unmap_page(pi->pdir, vaddr, true); } pi->brk = new_brk; return; } void *vaddr = pi->brk; while (vaddr < new_brk) { if (is_mapped(pi->pdir, vaddr)) return; // error: vaddr is already mapped! vaddr += PAGE_SIZE; } /* OK, everything looks good here */ vaddr = pi->brk; while (vaddr < new_brk) { void *kernel_vaddr = kmalloc(PAGE_SIZE); if (!kernel_vaddr) break; /* we've allocated as much as possible */ const ulong paddr = KERNEL_VA_TO_PA(kernel_vaddr); if (map_page(pi->pdir, vaddr, paddr, PAGING_FL_RWUS) != 0) { kfree2(kernel_vaddr, PAGE_SIZE); break; } vaddr += PAGE_SIZE; } /* We're done. */ pi->brk = vaddr; } void *sys_brk(void *new_brk) { struct task *ti = get_curr_task(); struct process *pi = ti->pi; if (!new_brk) return pi->brk; // TODO: check if Linux accepts non-page aligned addresses. // If yes, what to do? how to approx? truncation, round-up/round-down? if ((ulong)new_brk & OFFSET_IN_PAGE_MASK) return pi->brk; if (new_brk < pi->initial_brk) return pi->brk; if ((ulong)new_brk >= MAX_BRK) return pi->brk; if (new_brk == pi->brk) return pi->brk; /* * Disable preemption to avoid any threads to mess-up with the address space * of the current process (i.e. they might call brk(), mmap() etc.) */ disable_preemption(); { sys_brk_internal(pi, new_brk); } enable_preemption(); return pi->brk; } static int create_process_mmap_heap(struct process *pi) { struct kmalloc_heap *mmap_heap; ASSERT(!pi->mi); if (!(pi->mi = kalloc_obj(struct mappings_info))) return -ENOMEM; if (!(mmap_heap = kzmalloc(kmalloc_get_heap_struct_size()))) { kfree_obj(pi->mi, struct mappings_info); return -ENOMEM; } list_init(&pi->mi->mappings); pi->mi->mmap_heap = mmap_heap; pi->mi->mmap_heap_size = USER_MMAP_MIN_SZ; bool success = kmalloc_create_heap(mmap_heap, USER_MMAP_BEGIN, pi->mi->mmap_heap_size, PAGE_SIZE, PAGE_SIZE, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ #if MMAP_NO_COW user_valloc_and_map, user_vfree_and_unmap); #else user_map_zero_page, user_unmap_zero_page); #endif if (!success) return -ENOMEM; return 0; } static inline void mmap_err_case_free(struct process *pi, void *ptr, size_t actual_len) { per_heap_kfree(pi->mi->mmap_heap, ptr, &actual_len, KFREE_FL_ALLOW_SPLIT | KFREE_FL_MULTI_STEP | KFREE_FL_NO_ACTUAL_FREE); } static struct user_mapping * mmap_on_user_heap(struct process *pi, size_t *actual_len_ref, fs_handle handle, u32 per_heap_kmalloc_flags, size_t off, int prot) { void *res; struct user_mapping *um; while (true) { struct kmalloc_heap *new_heap; struct kmalloc_heap *h = pi->mi->mmap_heap; size_t heap_sz = pi->mi->mmap_heap_size; res = per_heap_kmalloc(h, actual_len_ref, per_heap_kmalloc_flags); if (LIKELY(res != NULL)) break; /* great! */ if (heap_sz == USER_MMAP_MAX_SZ) return NULL; /* cannot expand the heap more than that */ new_heap = kmalloc_heap_dup_expanded(h, heap_sz * 2); if (!new_heap) return NULL; /* no enough memory */ pi->mi->mmap_heap_size = heap_sz * 2; pi->mi->mmap_heap = new_heap; kmalloc_destroy_heap(h); } /* NOTE: here `handle` might be NULL (zero-map case) and that's OK */ um = process_add_user_mapping(handle, res, *actual_len_ref, off, prot); if (!um) { mmap_err_case_free(pi, res, *actual_len_ref); return NULL; } return um; } long sys_mmap_pgoff(void *addr, size_t len, int prot, int flags, int fd, size_t pgoffset) { u32 per_heap_kmalloc_flags = KMALLOC_FL_MULTI_STEP | PAGE_SIZE; struct task *curr = get_curr_task(); struct process *pi = curr->pi; struct fs_handle_base *handle = NULL; struct user_mapping *um = NULL; size_t actual_len; int rc, fl; if ((flags & MAP_PRIVATE) && (flags & MAP_SHARED)) return -EINVAL; /* non-sense parameters */ if (!len) return -EINVAL; if (addr) return -EINVAL; /* addr != NULL not supported */ if (!(prot & PROT_READ)) return -EINVAL; actual_len = pow2_round_up_at(len, PAGE_SIZE); if (fd == -1) { if (!(flags & MAP_ANONYMOUS)) return -EINVAL; if (flags & MAP_SHARED) return -EINVAL; /* MAP_SHARED not supported for anonymous mappings */ if (!(flags & MAP_PRIVATE)) return -EINVAL; if ((prot & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) return -EINVAL; if (pgoffset != 0) return -EINVAL; /* pgoffset != 0 does not make sense here */ } else { if (!(flags & MAP_SHARED)) return -EINVAL; handle = get_fs_handle(fd); if (!handle) return -EBADF; fl = handle->fl_flags; if ((prot & (PROT_READ | PROT_WRITE)) == 0) return -EINVAL; /* nor read nor write prot */ if ((prot & (PROT_READ | PROT_WRITE)) == PROT_WRITE) return -EINVAL; /* disallow write-only mappings */ if (prot & PROT_WRITE) { if (!(fl & O_WRONLY) && (fl & O_RDWR) != O_RDWR) return -EACCES; } per_heap_kmalloc_flags |= KMALLOC_FL_NO_ACTUAL_ALLOC; } if (!pi->mi) { if ((rc = create_process_mmap_heap(pi))) { return rc; } } disable_preemption(); { um = mmap_on_user_heap(pi, &actual_len, handle, per_heap_kmalloc_flags, pgoffset << PAGE_SHIFT, prot); } enable_preemption(); if (!um) return -ENOMEM; ASSERT(actual_len == pow2_round_up_at(len, PAGE_SIZE)); if (handle) { if ((rc = vfs_mmap(um, pi->pdir, 0))) { /* * Everything was apparently OK and the allocation in the user virtual * address space succeeded, but for some reason the actual mapping of * the device to the user vaddr failed. */ disable_preemption(); { mmap_err_case_free(pi, um->vaddrp, actual_len); process_remove_user_mapping(um); } enable_preemption(); return rc; } } else { if (MMAP_NO_COW) bzero(um->vaddrp, actual_len); } return (long)um->vaddr; } static int munmap_int(struct process *pi, void *vaddrp, size_t len) { u32 kfree_flags = KFREE_FL_ALLOW_SPLIT | KFREE_FL_MULTI_STEP; struct user_mapping *um = NULL, *um2 = NULL; ulong vaddr = (ulong) vaddrp; size_t actual_len; int rc; ASSERT(!is_preemption_enabled()); actual_len = pow2_round_up_at(len, PAGE_SIZE); um = process_get_user_mapping(vaddrp); if (!um) { /* * We just don't have any user_mappings containing [vaddrp, vaddrp+len). * Just ignore that and return 0 [linux behavior]. */ printk("[%d] Un-map unknown chunk at [%p, %p)\n", pi->pid, TO_PTR(vaddr), TO_PTR(vaddr + actual_len)); return 0; } const ulong um_vend = um->vaddr + um->len; if (actual_len == um->len) { process_remove_user_mapping(um); } else { /* partial un-map */ if (vaddr == um->vaddr) { /* unmap the beginning of the chunk */ um->vaddr += actual_len; um->off += actual_len; um->len -= actual_len; } else if (vaddr + actual_len == um_vend) { /* unmap the end of the chunk */ um->len -= actual_len; } else { /* Unmap something at the middle of the chunk */ /* Shrink the current struct user_mapping */ um->len = vaddr - um->vaddr; /* Create a new struct user_mapping for its 2nd part */ um2 = process_add_user_mapping( um->h, (void *)(vaddr + actual_len), (um_vend - (vaddr + actual_len)), um->off + um->len + actual_len, um->prot ); if (!um2) { /* * Oops, we're out-of-memory! No problem, revert um->page_count * and return -ENOMEM. Linux is allowed to do that. */ um->len = um_vend - um->vaddr; return -ENOMEM; } } } if (um->h) { kfree_flags |= KFREE_FL_NO_ACTUAL_FREE; rc = vfs_munmap(um, vaddrp, actual_len); /* * If there's an actual user_mapping entry, it means um->h's fops MUST * HAVE mmap() implemented. Therefore, we MUST REQUIRE munmap() to be * present as well. */ ASSERT(rc != -ENODEV); (void) rc; /* prevent the "unused variable" Werror in release */ if (um2) vfs_mmap(um2, pi->pdir, VFS_MM_DONT_MMAP); } per_heap_kfree(pi->mi->mmap_heap, vaddrp, &actual_len, kfree_flags); ASSERT(actual_len == pow2_round_up_at(len, PAGE_SIZE)); return 0; } int sys_munmap(void *vaddrp, size_t len) { struct task *curr = get_curr_task(); struct process *pi = curr->pi; ulong vaddr = (ulong) vaddrp; int rc; if (!len || !pi->mi->mmap_heap) return -EINVAL; if (!IN_RANGE(vaddr, USER_MMAP_BEGIN, USER_MMAP_BEGIN + pi->mi->mmap_heap_size)) { return -EINVAL; } disable_preemption(); { rc = munmap_int(pi, vaddrp, len); } enable_preemption(); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> void init_irq_handling(void) { NOT_IMPLEMENTED(); } <file_sep>#!/usr/bin/env bash BUILD_DIR="@CMAKE_BINARY_DIR@" f="@IMG_FILE@" tc="@TCROOT@" tc_bios="$tc/x86_64/ovmf/OVMF-pure-efi.fd" if [ -z "$QEMU_BIOS" ]; then QEMU_BIOS="/usr/share/qemu/OVMF.fd" if ! [ -f "$QEMU_BIOS" ]; then QEMU_BIOS="$tc_bios" fi elif [ "$QEMU_BIOS" = "tc" ]; then QEMU_BIOS="$tc_bios" fi if ! [ -f "$QEMU_BIOS" ]; then echo "In order to boot with EFI, you need to download OVMF first." echo "To do that, just run in project's main directory:" echo " ./scripts/build_toolchain -s download_ovmf" exit 1 fi if [ -z "$GDB_PORT" ]; then GDB_PORT=1234 fi echo "Run QEMU with -bios $QEMU_BIOS -gdb tcp::$GDB_PORT" qemu-system-x86_64 \ @QEMU_COMMON_OPTS@ \ @QEMU_RAM_OPT@ \ -gdb tcp::$GDB_PORT \ -bios "$QEMU_BIOS" \ -drive index=0,media=disk,format=raw,file=$f "$@" <file_sep>#!/usr/bin/python3 # SPDX-License-Identifier: BSD-2-Clause import os import sys def help(): print("cmp_funcs_size: a tool for comparing the size of functions inside") print("a translation unit between two builds.") print() print("How to use") print("-----------------------------") print("1. Generate functions list with:") print(" dump_all_funcs EXECUTABLE-before > before") print(" dump_all_funcs EXECUTABLE-after > after") print() print("2. Compare the two lists by running this script:") print(" cmp_funcs_size <funcs_before> <funcs_after>") print() def read_syms_dict(fname): with open(fname, 'r') as fh: syms = [] while True: ln = fh.readline() if not ln: break ln = ln.strip() sz, name = ln.split(" ") syms.append([name, int(sz)]) return dict(syms) def main(): if len(sys.argv) < 3: help() return f1, f2 = sys.argv[1], sys.argv[2] before = read_syms_dict(f1) after = read_syms_dict(f2) diffs = {} # func -> [size before, size after] for f in before: sz_before = before.get(f, 0) sz_after = after.get(f, 0) if sz_after != sz_before: diffs[f] = [sz_before, sz_after] for f in after: if not f in before: diffs[f] = [0, after[f]] darr = list(diffs.items()) darr.sort(key = lambda p: p[1][1] - p[1][0]) before_funcs = 0 after_funcs = 0 print("Differences for common symbols (size after vs before)") print("-" * 60) for p in darr: bsz, asz = p[1] if bsz and asz: before_funcs += 1 after_funcs += 1 print("{:<60} {:>10}".format(p[0], asz - bsz)) elif bsz: before_funcs += 1 else: after_funcs += 1 if before_funcs > after_funcs: print() print("Symbols existing only in <before>: {}".format(f1)) print("-" * 60) for p in darr: bsz, asz = p[1] if bsz and not asz: print("{:<60} {:>10}".format(p[0], bsz)) if after_funcs > before_funcs: print() print("Symbols existing only in <after>: {}".format(f2)) print("-" * 60) for p in darr: bsz, asz = p[1] if not bsz and asz: print("{:<110} {:>10}".format(p[0], asz)) if __name__ == '__main__': main() <file_sep>/****************************************************************************** * * Module Name: amlresrc.h - AML resource descriptors * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* acpisrc:StructDefs -- for acpisrc conversion */ #ifndef __AMLRESRC_H #define __AMLRESRC_H /* * Resource descriptor tags, as defined in the ACPI specification. * Used to symbolically reference fields within a descriptor. */ #define ACPI_RESTAG_ADDRESS "_ADR" #define ACPI_RESTAG_ALIGNMENT "_ALN" #define ACPI_RESTAG_ADDRESSSPACE "_ASI" #define ACPI_RESTAG_ACCESSSIZE "_ASZ" #define ACPI_RESTAG_TYPESPECIFICATTRIBUTES "_ATT" #define ACPI_RESTAG_BASEADDRESS "_BAS" #define ACPI_RESTAG_BUSMASTER "_BM_" /* Master(1), Slave(0) */ #define ACPI_RESTAG_DEBOUNCETIME "_DBT" #define ACPI_RESTAG_DECODE "_DEC" #define ACPI_RESTAG_DEVICEPOLARITY "_DPL" #define ACPI_RESTAG_DMA "_DMA" #define ACPI_RESTAG_DMATYPE "_TYP" /* Compatible(0), A(1), B(2), F(3) */ #define ACPI_RESTAG_DRIVESTRENGTH "_DRS" #define ACPI_RESTAG_ENDIANNESS "_END" #define ACPI_RESTAG_FLOWCONTROL "_FLC" #define ACPI_RESTAG_FUNCTION "_FUN" #define ACPI_RESTAG_GRANULARITY "_GRA" #define ACPI_RESTAG_INTERRUPT "_INT" #define ACPI_RESTAG_INTERRUPTLEVEL "_LL_" /* ActiveLo(1), ActiveHi(0) */ #define ACPI_RESTAG_INTERRUPTSHARE "_SHR" /* Shareable(1), NoShare(0) */ #define ACPI_RESTAG_INTERRUPTTYPE "_HE_" /* Edge(1), Level(0) */ #define ACPI_RESTAG_IORESTRICTION "_IOR" #define ACPI_RESTAG_LENGTH "_LEN" #define ACPI_RESTAG_LINE "_LIN" #define ACPI_RESTAG_MEMATTRIBUTES "_MTP" /* Memory(0), Reserved(1), ACPI(2), NVS(3) */ #define ACPI_RESTAG_MEMTYPE "_MEM" /* NonCache(0), Cacheable(1) Cache+combine(2), Cache+prefetch(3) */ #define ACPI_RESTAG_MAXADDR "_MAX" #define ACPI_RESTAG_MINADDR "_MIN" #define ACPI_RESTAG_MAXTYPE "_MAF" #define ACPI_RESTAG_MINTYPE "_MIF" #define ACPI_RESTAG_MODE "_MOD" #define ACPI_RESTAG_PARITY "_PAR" #define ACPI_RESTAG_PHASE "_PHA" #define ACPI_RESTAG_PIN "_PIN" #define ACPI_RESTAG_PINCONFIG "_PPI" #define ACPI_RESTAG_PINCONFIG_TYPE "_TYP" #define ACPI_RESTAG_PINCONFIG_VALUE "_VAL" #define ACPI_RESTAG_POLARITY "_POL" #define ACPI_RESTAG_REGISTERBITOFFSET "_RBO" #define ACPI_RESTAG_REGISTERBITWIDTH "_RBW" #define ACPI_RESTAG_RANGETYPE "_RNG" #define ACPI_RESTAG_READWRITETYPE "_RW_" /* ReadOnly(0), Writeable (1) */ #define ACPI_RESTAG_LENGTH_RX "_RXL" #define ACPI_RESTAG_LENGTH_TX "_TXL" #define ACPI_RESTAG_SLAVEMODE "_SLV" #define ACPI_RESTAG_SPEED "_SPE" #define ACPI_RESTAG_STOPBITS "_STB" #define ACPI_RESTAG_TRANSLATION "_TRA" #define ACPI_RESTAG_TRANSTYPE "_TRS" /* Sparse(1), Dense(0) */ #define ACPI_RESTAG_TYPE "_TTP" /* Translation(1), Static (0) */ #define ACPI_RESTAG_XFERTYPE "_SIZ" /* 8(0), 8And16(1), 16(2) */ #define ACPI_RESTAG_VENDORDATA "_VEN" /* Default sizes for "small" resource descriptors */ #define ASL_RDESC_IRQ_SIZE 0x02 #define ASL_RDESC_DMA_SIZE 0x02 #define ASL_RDESC_ST_DEPEND_SIZE 0x00 #define ASL_RDESC_END_DEPEND_SIZE 0x00 #define ASL_RDESC_IO_SIZE 0x07 #define ASL_RDESC_FIXED_IO_SIZE 0x03 #define ASL_RDESC_FIXED_DMA_SIZE 0x05 #define ASL_RDESC_END_TAG_SIZE 0x01 typedef struct asl_resource_node { UINT32 BufferLength; void *Buffer; struct asl_resource_node *Next; } ASL_RESOURCE_NODE; typedef struct asl_resource_info { ACPI_PARSE_OBJECT *DescriptorTypeOp; /* Resource descriptor parse node */ ACPI_PARSE_OBJECT *MappingOp; /* Used for mapfile support */ UINT32 CurrentByteOffset; /* Offset in resource template */ } ASL_RESOURCE_INFO; /* Macros used to generate AML resource length fields */ #define ACPI_AML_SIZE_LARGE(r) (sizeof (r) - sizeof (AML_RESOURCE_LARGE_HEADER)) #define ACPI_AML_SIZE_SMALL(r) (sizeof (r) - sizeof (AML_RESOURCE_SMALL_HEADER)) /* * Resource descriptors defined in the ACPI specification. * * Packing/alignment must be BYTE because these descriptors * are used to overlay the raw AML byte stream. */ #pragma pack(1) /* * SMALL descriptors */ #define AML_RESOURCE_SMALL_HEADER_COMMON \ UINT8 DescriptorType; typedef struct aml_resource_small_header { AML_RESOURCE_SMALL_HEADER_COMMON } AML_RESOURCE_SMALL_HEADER; typedef struct aml_resource_irq { AML_RESOURCE_SMALL_HEADER_COMMON UINT16 IrqMask; UINT8 Flags; } AML_RESOURCE_IRQ; typedef struct aml_resource_irq_noflags { AML_RESOURCE_SMALL_HEADER_COMMON UINT16 IrqMask; } AML_RESOURCE_IRQ_NOFLAGS; typedef struct aml_resource_dma { AML_RESOURCE_SMALL_HEADER_COMMON UINT8 DmaChannelMask; UINT8 Flags; } AML_RESOURCE_DMA; typedef struct aml_resource_start_dependent { AML_RESOURCE_SMALL_HEADER_COMMON UINT8 Flags; } AML_RESOURCE_START_DEPENDENT; typedef struct aml_resource_start_dependent_noprio { AML_RESOURCE_SMALL_HEADER_COMMON } AML_RESOURCE_START_DEPENDENT_NOPRIO; typedef struct aml_resource_end_dependent { AML_RESOURCE_SMALL_HEADER_COMMON } AML_RESOURCE_END_DEPENDENT; typedef struct aml_resource_io { AML_RESOURCE_SMALL_HEADER_COMMON UINT8 Flags; UINT16 Minimum; UINT16 Maximum; UINT8 Alignment; UINT8 AddressLength; } AML_RESOURCE_IO; typedef struct aml_resource_fixed_io { AML_RESOURCE_SMALL_HEADER_COMMON UINT16 Address; UINT8 AddressLength; } AML_RESOURCE_FIXED_IO; typedef struct aml_resource_vendor_small { AML_RESOURCE_SMALL_HEADER_COMMON } AML_RESOURCE_VENDOR_SMALL; typedef struct aml_resource_end_tag { AML_RESOURCE_SMALL_HEADER_COMMON UINT8 Checksum; } AML_RESOURCE_END_TAG; typedef struct aml_resource_fixed_dma { AML_RESOURCE_SMALL_HEADER_COMMON UINT16 RequestLines; UINT16 Channels; UINT8 Width; } AML_RESOURCE_FIXED_DMA; /* * LARGE descriptors */ #define AML_RESOURCE_LARGE_HEADER_COMMON \ UINT8 DescriptorType;\ UINT16 ResourceLength; typedef struct aml_resource_large_header { AML_RESOURCE_LARGE_HEADER_COMMON } AML_RESOURCE_LARGE_HEADER; /* General Flags for address space resource descriptors */ #define ACPI_RESOURCE_FLAG_DEC 2 #define ACPI_RESOURCE_FLAG_MIF 4 #define ACPI_RESOURCE_FLAG_MAF 8 typedef struct aml_resource_memory24 { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 Flags; UINT16 Minimum; UINT16 Maximum; UINT16 Alignment; UINT16 AddressLength; } AML_RESOURCE_MEMORY24; typedef struct aml_resource_vendor_large { AML_RESOURCE_LARGE_HEADER_COMMON } AML_RESOURCE_VENDOR_LARGE; typedef struct aml_resource_memory32 { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 Flags; UINT32 Minimum; UINT32 Maximum; UINT32 Alignment; UINT32 AddressLength; } AML_RESOURCE_MEMORY32; typedef struct aml_resource_fixed_memory32 { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 Flags; UINT32 Address; UINT32 AddressLength; } AML_RESOURCE_FIXED_MEMORY32; #define AML_RESOURCE_ADDRESS_COMMON \ UINT8 ResourceType; \ UINT8 Flags; \ UINT8 SpecificFlags; typedef struct aml_resource_address { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_ADDRESS_COMMON } AML_RESOURCE_ADDRESS; typedef struct aml_resource_extended_address64 { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_ADDRESS_COMMON UINT8 RevisionID; UINT8 Reserved; UINT64 Granularity; UINT64 Minimum; UINT64 Maximum; UINT64 TranslationOffset; UINT64 AddressLength; UINT64 TypeSpecific; } AML_RESOURCE_EXTENDED_ADDRESS64; #define AML_RESOURCE_EXTENDED_ADDRESS_REVISION 1 /* ACPI 3.0 */ typedef struct aml_resource_address64 { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_ADDRESS_COMMON UINT64 Granularity; UINT64 Minimum; UINT64 Maximum; UINT64 TranslationOffset; UINT64 AddressLength; } AML_RESOURCE_ADDRESS64; typedef struct aml_resource_address32 { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_ADDRESS_COMMON UINT32 Granularity; UINT32 Minimum; UINT32 Maximum; UINT32 TranslationOffset; UINT32 AddressLength; } AML_RESOURCE_ADDRESS32; typedef struct aml_resource_address16 { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_ADDRESS_COMMON UINT16 Granularity; UINT16 Minimum; UINT16 Maximum; UINT16 TranslationOffset; UINT16 AddressLength; } AML_RESOURCE_ADDRESS16; typedef struct aml_resource_extended_irq { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 Flags; UINT8 InterruptCount; UINT32 Interrupts[1]; /* ResSourceIndex, ResSource optional fields follow */ } AML_RESOURCE_EXTENDED_IRQ; typedef struct aml_resource_generic_register { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 AddressSpaceId; UINT8 BitWidth; UINT8 BitOffset; UINT8 AccessSize; /* ACPI 3.0, was previously Reserved */ UINT64 Address; } AML_RESOURCE_GENERIC_REGISTER; /* Common descriptor for GpioInt and GpioIo (ACPI 5.0) */ typedef struct aml_resource_gpio { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT8 ConnectionType; UINT16 Flags; UINT16 IntFlags; UINT8 PinConfig; UINT16 DriveStrength; UINT16 DebounceTimeout; UINT16 PinTableOffset; UINT8 ResSourceIndex; UINT16 ResSourceOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) PIN list (Words) * 2) Resource Source String * 3) Vendor Data bytes */ } AML_RESOURCE_GPIO; #define AML_RESOURCE_GPIO_REVISION 1 /* ACPI 5.0 */ /* Values for ConnectionType above */ #define AML_RESOURCE_GPIO_TYPE_INT 0 #define AML_RESOURCE_GPIO_TYPE_IO 1 #define AML_RESOURCE_MAX_GPIOTYPE 1 /* Common preamble for all serial descriptors (ACPI 5.0) */ #define AML_RESOURCE_SERIAL_COMMON \ UINT8 RevisionId; \ UINT8 ResSourceIndex; \ UINT8 Type; \ UINT8 Flags; \ UINT16 TypeSpecificFlags; \ UINT8 TypeRevisionId; \ UINT16 TypeDataLength; \ /* Values for the type field above */ #define AML_RESOURCE_I2C_SERIALBUSTYPE 1 #define AML_RESOURCE_SPI_SERIALBUSTYPE 2 #define AML_RESOURCE_UART_SERIALBUSTYPE 3 #define AML_RESOURCE_MAX_SERIALBUSTYPE 3 #define AML_RESOURCE_VENDOR_SERIALBUSTYPE 192 /* Vendor defined is 0xC0-0xFF (NOT SUPPORTED) */ typedef struct aml_resource_common_serialbus { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_SERIAL_COMMON } AML_RESOURCE_COMMON_SERIALBUS; typedef struct aml_resource_i2c_serialbus { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_SERIAL_COMMON UINT32 ConnectionSpeed; UINT16 SlaveAddress; /* * Optional fields follow immediately: * 1) Vendor Data bytes * 2) Resource Source String */ } AML_RESOURCE_I2C_SERIALBUS; #define AML_RESOURCE_I2C_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_I2C_TYPE_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_I2C_MIN_DATA_LEN 6 typedef struct aml_resource_spi_serialbus { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_SERIAL_COMMON UINT32 ConnectionSpeed; UINT8 DataBitLength; UINT8 ClockPhase; UINT8 ClockPolarity; UINT16 DeviceSelection; /* * Optional fields follow immediately: * 1) Vendor Data bytes * 2) Resource Source String */ } AML_RESOURCE_SPI_SERIALBUS; #define AML_RESOURCE_SPI_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_SPI_TYPE_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_SPI_MIN_DATA_LEN 9 typedef struct aml_resource_uart_serialbus { AML_RESOURCE_LARGE_HEADER_COMMON AML_RESOURCE_SERIAL_COMMON UINT32 DefaultBaudRate; UINT16 RxFifoSize; UINT16 TxFifoSize; UINT8 Parity; UINT8 LinesEnabled; /* * Optional fields follow immediately: * 1) Vendor Data bytes * 2) Resource Source String */ } AML_RESOURCE_UART_SERIALBUS; #define AML_RESOURCE_UART_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_UART_TYPE_REVISION 1 /* ACPI 5.0 */ #define AML_RESOURCE_UART_MIN_DATA_LEN 10 typedef struct aml_resource_pin_function { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT16 Flags; UINT8 PinConfig; UINT16 FunctionNumber; UINT16 PinTableOffset; UINT8 ResSourceIndex; UINT16 ResSourceOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) PIN list (Words) * 2) Resource Source String * 3) Vendor Data bytes */ } AML_RESOURCE_PIN_FUNCTION; #define AML_RESOURCE_PIN_FUNCTION_REVISION 1 /* ACPI 6.2 */ typedef struct aml_resource_pin_config { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT16 Flags; UINT8 PinConfigType; UINT32 PinConfigValue; UINT16 PinTableOffset; UINT8 ResSourceIndex; UINT16 ResSourceOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) PIN list (Words) * 2) Resource Source String * 3) Vendor Data bytes */ } AML_RESOURCE_PIN_CONFIG; #define AML_RESOURCE_PIN_CONFIG_REVISION 1 /* ACPI 6.2 */ typedef struct aml_resource_pin_group { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT16 Flags; UINT16 PinTableOffset; UINT16 LabelOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) PIN list (Words) * 2) Resource Label String * 3) Vendor Data bytes */ } AML_RESOURCE_PIN_GROUP; #define AML_RESOURCE_PIN_GROUP_REVISION 1 /* ACPI 6.2 */ typedef struct aml_resource_pin_group_function { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT16 Flags; UINT16 FunctionNumber; UINT8 ResSourceIndex; UINT16 ResSourceOffset; UINT16 ResSourceLabelOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) Resource Source String * 2) Resource Source Label String * 3) Vendor Data bytes */ } AML_RESOURCE_PIN_GROUP_FUNCTION; #define AML_RESOURCE_PIN_GROUP_FUNCTION_REVISION 1 /* ACPI 6.2 */ typedef struct aml_resource_pin_group_config { AML_RESOURCE_LARGE_HEADER_COMMON UINT8 RevisionId; UINT16 Flags; UINT8 PinConfigType; UINT32 PinConfigValue; UINT8 ResSourceIndex; UINT16 ResSourceOffset; UINT16 ResSourceLabelOffset; UINT16 VendorOffset; UINT16 VendorLength; /* * Optional fields follow immediately: * 1) Resource Source String * 2) Resource Source Label String * 3) Vendor Data bytes */ } AML_RESOURCE_PIN_GROUP_CONFIG; #define AML_RESOURCE_PIN_GROUP_CONFIG_REVISION 1 /* ACPI 6.2 */ /* restore default alignment */ #pragma pack() /* Union of all resource descriptors, so we can allocate the worst case */ typedef union aml_resource { /* Descriptor headers */ UINT8 DescriptorType; AML_RESOURCE_SMALL_HEADER SmallHeader; AML_RESOURCE_LARGE_HEADER LargeHeader; /* Small resource descriptors */ AML_RESOURCE_IRQ Irq; AML_RESOURCE_DMA Dma; AML_RESOURCE_START_DEPENDENT StartDpf; AML_RESOURCE_END_DEPENDENT EndDpf; AML_RESOURCE_IO Io; AML_RESOURCE_FIXED_IO FixedIo; AML_RESOURCE_FIXED_DMA FixedDma; AML_RESOURCE_VENDOR_SMALL VendorSmall; AML_RESOURCE_END_TAG EndTag; /* Large resource descriptors */ AML_RESOURCE_MEMORY24 Memory24; AML_RESOURCE_GENERIC_REGISTER GenericReg; AML_RESOURCE_VENDOR_LARGE VendorLarge; AML_RESOURCE_MEMORY32 Memory32; AML_RESOURCE_FIXED_MEMORY32 FixedMemory32; AML_RESOURCE_ADDRESS16 Address16; AML_RESOURCE_ADDRESS32 Address32; AML_RESOURCE_ADDRESS64 Address64; AML_RESOURCE_EXTENDED_ADDRESS64 ExtAddress64; AML_RESOURCE_EXTENDED_IRQ ExtendedIrq; AML_RESOURCE_GPIO Gpio; AML_RESOURCE_I2C_SERIALBUS I2cSerialBus; AML_RESOURCE_SPI_SERIALBUS SpiSerialBus; AML_RESOURCE_UART_SERIALBUS UartSerialBus; AML_RESOURCE_COMMON_SERIALBUS CommonSerialBus; AML_RESOURCE_PIN_FUNCTION PinFunction; AML_RESOURCE_PIN_CONFIG PinConfig; AML_RESOURCE_PIN_GROUP PinGroup; AML_RESOURCE_PIN_GROUP_FUNCTION PinGroupFunction; AML_RESOURCE_PIN_GROUP_CONFIG PinGroupConfig; /* Utility overlays */ AML_RESOURCE_ADDRESS Address; UINT32 DwordItem; UINT16 WordItem; UINT8 ByteItem; } AML_RESOURCE; /* Interfaces used by both the disassembler and compiler */ void MpSaveGpioInfo ( ACPI_PARSE_OBJECT *Op, AML_RESOURCE *Resource, UINT32 PinCount, UINT16 *PinList, char *DeviceName); void MpSaveSerialInfo ( ACPI_PARSE_OBJECT *Op, AML_RESOURCE *Resource, char *DeviceName); char * MpGetHidFromParseTree ( ACPI_NAMESPACE_NODE *HidNode); char * MpGetHidViaNamestring ( char *DeviceName); char * MpGetConnectionInfo ( ACPI_PARSE_OBJECT *Op, UINT32 PinIndex, ACPI_NAMESPACE_NODE **TargetNode, char **TargetName); char * MpGetParentDeviceHid ( ACPI_PARSE_OBJECT *Op, ACPI_NAMESPACE_NODE **TargetNode, char **ParentDeviceName); char * MpGetDdnValue ( char *DeviceName); char * MpGetHidValue ( ACPI_NAMESPACE_NODE *DeviceNode); #endif <file_sep>/******************************************************************************* * * Module Name: utdelete - object deletion and reference count utilities * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "acnamesp.h" #include "acevents.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utdelete") /* Local prototypes */ static void AcpiUtDeleteInternalObj ( ACPI_OPERAND_OBJECT *Object); static void AcpiUtUpdateRefCount ( ACPI_OPERAND_OBJECT *Object, UINT32 Action); /******************************************************************************* * * FUNCTION: AcpiUtDeleteInternalObj * * PARAMETERS: Object - Object to be deleted * * RETURN: None * * DESCRIPTION: Low level object deletion, after reference counts have been * updated (All reference counts, including sub-objects!) * ******************************************************************************/ static void AcpiUtDeleteInternalObj ( ACPI_OPERAND_OBJECT *Object) { void *ObjPointer = NULL; ACPI_OPERAND_OBJECT *HandlerDesc; ACPI_OPERAND_OBJECT *SecondDesc; ACPI_OPERAND_OBJECT *NextDesc; ACPI_OPERAND_OBJECT *StartDesc; ACPI_OPERAND_OBJECT **LastObjPtr; ACPI_FUNCTION_TRACE_PTR (UtDeleteInternalObj, Object); if (!Object) { return_VOID; } /* * Must delete or free any pointers within the object that are not * actual ACPI objects (for example, a raw buffer pointer). */ switch (Object->Common.Type) { case ACPI_TYPE_STRING: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "**** String %p, ptr %p\n", Object, Object->String.Pointer)); /* Free the actual string buffer */ if (!(Object->Common.Flags & AOPOBJ_STATIC_POINTER)) { /* But only if it is NOT a pointer into an ACPI table */ ObjPointer = Object->String.Pointer; } break; case ACPI_TYPE_BUFFER: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "**** Buffer %p, ptr %p\n", Object, Object->Buffer.Pointer)); /* Free the actual buffer */ if (!(Object->Common.Flags & AOPOBJ_STATIC_POINTER)) { /* But only if it is NOT a pointer into an ACPI table */ ObjPointer = Object->Buffer.Pointer; } break; case ACPI_TYPE_PACKAGE: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, " **** Package of count %X\n", Object->Package.Count)); /* * Elements of the package are not handled here, they are deleted * separately */ /* Free the (variable length) element pointer array */ ObjPointer = Object->Package.Elements; break; /* * These objects have a possible list of notify handlers. * Device object also may have a GPE block. */ case ACPI_TYPE_DEVICE: if (Object->Device.GpeBlock) { (void) AcpiEvDeleteGpeBlock (Object->Device.GpeBlock); } /*lint -fallthrough */ case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_THERMAL: /* Walk the address handler list for this object */ HandlerDesc = Object->CommonNotify.Handler; while (HandlerDesc) { NextDesc = HandlerDesc->AddressSpace.Next; AcpiUtRemoveReference (HandlerDesc); HandlerDesc = NextDesc; } break; case ACPI_TYPE_MUTEX: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Mutex %p, OS Mutex %p\n", Object, Object->Mutex.OsMutex)); if (Object == AcpiGbl_GlobalLockMutex) { /* Global Lock has extra semaphore */ (void) AcpiOsDeleteSemaphore (AcpiGbl_GlobalLockSemaphore); AcpiGbl_GlobalLockSemaphore = NULL; AcpiOsDeleteMutex (Object->Mutex.OsMutex); AcpiGbl_GlobalLockMutex = NULL; } else { AcpiExUnlinkMutex (Object); AcpiOsDeleteMutex (Object->Mutex.OsMutex); } break; case ACPI_TYPE_EVENT: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Event %p, OS Semaphore %p\n", Object, Object->Event.OsSemaphore)); (void) AcpiOsDeleteSemaphore (Object->Event.OsSemaphore); Object->Event.OsSemaphore = NULL; break; case ACPI_TYPE_METHOD: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Method %p\n", Object)); /* Delete the method mutex if it exists */ if (Object->Method.Mutex) { AcpiOsDeleteMutex (Object->Method.Mutex->Mutex.OsMutex); AcpiUtDeleteObjectDesc (Object->Method.Mutex); Object->Method.Mutex = NULL; } if (Object->Method.Node) { Object->Method.Node = NULL; } break; case ACPI_TYPE_REGION: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Region %p\n", Object)); /* * Update AddressRange list. However, only permanent regions * are installed in this list. (Not created within a method) */ if (!(Object->Region.Node->Flags & ANOBJ_TEMPORARY)) { AcpiUtRemoveAddressRange (Object->Region.SpaceId, Object->Region.Node); } SecondDesc = AcpiNsGetSecondaryObject (Object); if (SecondDesc) { /* * Free the RegionContext if and only if the handler is one of the * default handlers -- and therefore, we created the context object * locally, it was not created by an external caller. */ HandlerDesc = Object->Region.Handler; if (HandlerDesc) { NextDesc = HandlerDesc->AddressSpace.RegionList; StartDesc = NextDesc; LastObjPtr = &HandlerDesc->AddressSpace.RegionList; /* Remove the region object from the handler list */ while (NextDesc) { if (NextDesc == Object) { *LastObjPtr = NextDesc->Region.Next; break; } /* Walk the linked list of handlers */ LastObjPtr = &NextDesc->Region.Next; NextDesc = NextDesc->Region.Next; /* Prevent infinite loop if list is corrupted */ if (NextDesc == StartDesc) { ACPI_ERROR ((AE_INFO, "Circular region list in address handler object %p", HandlerDesc)); return_VOID; } } if (HandlerDesc->AddressSpace.HandlerFlags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) { /* Deactivate region and free region context */ if (HandlerDesc->AddressSpace.Setup) { (void) HandlerDesc->AddressSpace.Setup (Object, ACPI_REGION_DEACTIVATE, HandlerDesc->AddressSpace.Context, &SecondDesc->Extra.RegionContext); } } AcpiUtRemoveReference (HandlerDesc); } /* Now we can free the Extra object */ AcpiUtDeleteObjectDesc (SecondDesc); } if (Object->Field.InternalPccBuffer) { ACPI_FREE(Object->Field.InternalPccBuffer); } break; case ACPI_TYPE_BUFFER_FIELD: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Buffer Field %p\n", Object)); SecondDesc = AcpiNsGetSecondaryObject (Object); if (SecondDesc) { AcpiUtDeleteObjectDesc (SecondDesc); } break; case ACPI_TYPE_LOCAL_BANK_FIELD: ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "***** Bank Field %p\n", Object)); SecondDesc = AcpiNsGetSecondaryObject (Object); if (SecondDesc) { AcpiUtDeleteObjectDesc (SecondDesc); } break; default: break; } /* Free any allocated memory (pointer within the object) found above */ if (ObjPointer) { ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Deleting Object Subptr %p\n", ObjPointer)); ACPI_FREE (ObjPointer); } /* Now the object can be safely deleted */ ACPI_DEBUG_PRINT_RAW ((ACPI_DB_ALLOCATIONS, "%s: Deleting Object %p [%s]\n", ACPI_GET_FUNCTION_NAME, Object, AcpiUtGetObjectTypeName (Object))); AcpiUtDeleteObjectDesc (Object); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiUtDeleteInternalObjectList * * PARAMETERS: ObjList - Pointer to the list to be deleted * * RETURN: None * * DESCRIPTION: This function deletes an internal object list, including both * simple objects and package objects * ******************************************************************************/ void AcpiUtDeleteInternalObjectList ( ACPI_OPERAND_OBJECT **ObjList) { ACPI_OPERAND_OBJECT **InternalObj; ACPI_FUNCTION_ENTRY (); /* Walk the null-terminated internal list */ for (InternalObj = ObjList; *InternalObj; InternalObj++) { AcpiUtRemoveReference (*InternalObj); } /* Free the combined parameter pointer list and object array */ ACPI_FREE (ObjList); return; } /******************************************************************************* * * FUNCTION: AcpiUtUpdateRefCount * * PARAMETERS: Object - Object whose ref count is to be updated * Action - What to do (REF_INCREMENT or REF_DECREMENT) * * RETURN: None. Sets new reference count within the object * * DESCRIPTION: Modify the reference count for an internal acpi object * ******************************************************************************/ static void AcpiUtUpdateRefCount ( ACPI_OPERAND_OBJECT *Object, UINT32 Action) { UINT16 OriginalCount; UINT16 NewCount = 0; ACPI_CPU_FLAGS LockFlags; char *Message; ACPI_FUNCTION_NAME (UtUpdateRefCount); if (!Object) { return; } /* * Always get the reference count lock. Note: Interpreter and/or * Namespace is not always locked when this function is called. */ LockFlags = AcpiOsAcquireLock (AcpiGbl_ReferenceCountLock); OriginalCount = Object->Common.ReferenceCount; /* Perform the reference count action (increment, decrement) */ switch (Action) { case REF_INCREMENT: NewCount = OriginalCount + 1; Object->Common.ReferenceCount = NewCount; AcpiOsReleaseLock (AcpiGbl_ReferenceCountLock, LockFlags); /* The current reference count should never be zero here */ if (!OriginalCount) { ACPI_WARNING ((AE_INFO, "Obj %p, Reference Count was zero before increment\n", Object)); } ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Obj %p Type %.2X [%s] Refs %.2X [Incremented]\n", Object, Object->Common.Type, AcpiUtGetObjectTypeName (Object), NewCount)); Message = "Incremement"; break; case REF_DECREMENT: /* The current reference count must be non-zero */ if (OriginalCount) { NewCount = OriginalCount - 1; Object->Common.ReferenceCount = NewCount; } AcpiOsReleaseLock (AcpiGbl_ReferenceCountLock, LockFlags); if (!OriginalCount) { ACPI_WARNING ((AE_INFO, "Obj %p, Reference Count is already zero, cannot decrement\n", Object)); } ACPI_DEBUG_PRINT_RAW ((ACPI_DB_ALLOCATIONS, "%s: Obj %p Type %.2X Refs %.2X [Decremented]\n", ACPI_GET_FUNCTION_NAME, Object, Object->Common.Type, NewCount)); /* Actually delete the object on a reference count of zero */ if (NewCount == 0) { AcpiUtDeleteInternalObj (Object); } Message = "Decrement"; break; default: AcpiOsReleaseLock (AcpiGbl_ReferenceCountLock, LockFlags); ACPI_ERROR ((AE_INFO, "Unknown Reference Count action (0x%X)", Action)); return; } /* * Sanity check the reference count, for debug purposes only. * (A deleted object will have a huge reference count) */ if (NewCount > ACPI_MAX_REFERENCE_COUNT) { ACPI_WARNING ((AE_INFO, "Large Reference Count (0x%X) in object %p, Type=0x%.2X Operation=%s", NewCount, Object, Object->Common.Type, Message)); } } /******************************************************************************* * * FUNCTION: AcpiUtUpdateObjectReference * * PARAMETERS: Object - Increment or decrement the ref count for * this object and all sub-objects * Action - Either REF_INCREMENT or REF_DECREMENT * * RETURN: Status * * DESCRIPTION: Increment or decrement the object reference count * * Object references are incremented when: * 1) An object is attached to a Node (namespace object) * 2) An object is copied (all subobjects must be incremented) * * Object references are decremented when: * 1) An object is detached from an Node * ******************************************************************************/ ACPI_STATUS AcpiUtUpdateObjectReference ( ACPI_OPERAND_OBJECT *Object, UINT16 Action) { ACPI_STATUS Status = AE_OK; ACPI_GENERIC_STATE *StateList = NULL; ACPI_OPERAND_OBJECT *NextObject = NULL; ACPI_OPERAND_OBJECT *PrevObject; ACPI_GENERIC_STATE *State; UINT32 i; ACPI_FUNCTION_NAME (UtUpdateObjectReference); while (Object) { /* Make sure that this isn't a namespace handle */ if (ACPI_GET_DESCRIPTOR_TYPE (Object) == ACPI_DESC_TYPE_NAMED) { ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Object %p is NS handle\n", Object)); return (AE_OK); } /* * All sub-objects must have their reference count updated * also. Different object types have different subobjects. */ switch (Object->Common.Type) { case ACPI_TYPE_DEVICE: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_POWER: case ACPI_TYPE_THERMAL: /* * Update the notify objects for these types (if present) * Two lists, system and device notify handlers. */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { PrevObject = Object->CommonNotify.NotifyList[i]; while (PrevObject) { NextObject = PrevObject->Notify.Next[i]; AcpiUtUpdateRefCount (PrevObject, Action); PrevObject = NextObject; } } break; case ACPI_TYPE_PACKAGE: /* * We must update all the sub-objects of the package, * each of whom may have their own sub-objects. */ for (i = 0; i < Object->Package.Count; i++) { /* * Null package elements are legal and can be simply * ignored. */ NextObject = Object->Package.Elements[i]; if (!NextObject) { continue; } switch (NextObject->Common.Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: /* * For these very simple sub-objects, we can just * update the reference count here and continue. * Greatly increases performance of this operation. */ AcpiUtUpdateRefCount (NextObject, Action); break; default: /* * For complex sub-objects, push them onto the stack * for later processing (this eliminates recursion.) */ Status = AcpiUtCreateUpdateStateAndPush ( NextObject, Action, &StateList); if (ACPI_FAILURE (Status)) { goto ErrorExit; } break; } } NextObject = NULL; break; case ACPI_TYPE_BUFFER_FIELD: NextObject = Object->BufferField.BufferObj; break; case ACPI_TYPE_LOCAL_BANK_FIELD: NextObject = Object->BankField.BankObj; Status = AcpiUtCreateUpdateStateAndPush ( Object->BankField.RegionObj, Action, &StateList); if (ACPI_FAILURE (Status)) { goto ErrorExit; } break; case ACPI_TYPE_LOCAL_INDEX_FIELD: NextObject = Object->IndexField.IndexObj; Status = AcpiUtCreateUpdateStateAndPush ( Object->IndexField.DataObj, Action, &StateList); if (ACPI_FAILURE (Status)) { goto ErrorExit; } break; case ACPI_TYPE_LOCAL_REFERENCE: /* * The target of an Index (a package, string, or buffer) or a named * reference must track changes to the ref count of the index or * target object. */ if ((Object->Reference.Class == ACPI_REFCLASS_INDEX) || (Object->Reference.Class== ACPI_REFCLASS_NAME)) { NextObject = Object->Reference.Object; } break; case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_REGION: default: break; /* No subobjects for all other types */ } /* * Now we can update the count in the main object. This can only * happen after we update the sub-objects in case this causes the * main object to be deleted. */ AcpiUtUpdateRefCount (Object, Action); Object = NULL; /* Move on to the next object to be updated */ if (NextObject) { Object = NextObject; NextObject = NULL; } else if (StateList) { State = AcpiUtPopGenericState (&StateList); Object = State->Update.Object; AcpiUtDeleteGenericState (State); } } return (AE_OK); ErrorExit: ACPI_EXCEPTION ((AE_INFO, Status, "Could not update object reference count")); /* Free any stacked Update State objects */ while (StateList) { State = AcpiUtPopGenericState (&StateList); AcpiUtDeleteGenericState (State); } return (Status); } /******************************************************************************* * * FUNCTION: AcpiUtAddReference * * PARAMETERS: Object - Object whose reference count is to be * incremented * * RETURN: None * * DESCRIPTION: Add one reference to an ACPI object * ******************************************************************************/ void AcpiUtAddReference ( ACPI_OPERAND_OBJECT *Object) { ACPI_FUNCTION_NAME (UtAddReference); /* Ensure that we have a valid object */ if (!AcpiUtValidInternalObject (Object)) { return; } ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Obj %p Current Refs=%X [To Be Incremented]\n", Object, Object->Common.ReferenceCount)); /* Increment the reference count */ (void) AcpiUtUpdateObjectReference (Object, REF_INCREMENT); return; } /******************************************************************************* * * FUNCTION: AcpiUtRemoveReference * * PARAMETERS: Object - Object whose ref count will be decremented * * RETURN: None * * DESCRIPTION: Decrement the reference count of an ACPI internal object * ******************************************************************************/ void AcpiUtRemoveReference ( ACPI_OPERAND_OBJECT *Object) { ACPI_FUNCTION_NAME (UtRemoveReference); /* * Allow a NULL pointer to be passed in, just ignore it. This saves * each caller from having to check. Also, ignore NS nodes. */ if (!Object || (ACPI_GET_DESCRIPTOR_TYPE (Object) == ACPI_DESC_TYPE_NAMED)) { return; } /* Ensure that we have a valid object */ if (!AcpiUtValidInternalObject (Object)) { return; } ACPI_DEBUG_PRINT_RAW ((ACPI_DB_ALLOCATIONS, "%s: Obj %p Current Refs=%X [To Be Decremented]\n", ACPI_GET_FUNCTION_NAME, Object, Object->Common.ReferenceCount)); /* * Decrement the reference count, and only actually delete the object * if the reference count becomes 0. (Must also decrement the ref count * of all subobjects!) */ (void) AcpiUtUpdateObjectReference (Object, REF_DECREMENT); return; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause LIBMUSL_VER="1.1.24" function download_libmusl { local ver="$LIBMUSL_VER" local tarname="libmusl-$ver.tgz" local url="git://git.musl-libc.org/musl" download_git_repo_in_cache "$url" v$ver $tarname musl extract_cachefile_tar_gz $tarname -- } if [[ $HOST_ARCH == "i386" ]] || [[ $HOST_ARCH == "x86_64" ]]; then all_funcs_list+=(build_libmusl) fi function build_libmusl { pushd $ARCH local saved_path="$PATH" export SYS_CC="$CC" export SYS_CXX="$CXX" if ! [ -d musl ]; then if [[ "$USE_SYSCC" == "" || "$USE_SYSCC" == 0 ]]; then # The glibc gcc toolchain is necessary in order to build libmusl and # make its build system generate the musl-gcc script. Attempting to # build libmusl with the musl gcc toolchain succeeds BUT the musl-gcc # script and the lib/musl-gcc.specs file ARE NOT generated, because the # build system detected that the toolchain is already using libmusl. In # our case having the ability to build libmusl and compile programs # with musl-gcc is essential since it allows debugging libmusl itself # (the pre-compiled toolchain uses an optimized non-debug version of # libmusl). download_gcc_glibc_toolchain export PATH="$GCC_TOOLCHAIN_GLIBC:$PATH" # Force use the our cross-compiler when when $ARCH == $HOST_ARCH export CC="$ARCH-linux-gcc" else export CC="$MAIN_DIR/scripts/build_scripts/${ARCH}-gcc" export CXX="$MAIN_DIR/scripts/build_scripts/${ARCH}-g++" fi show_work_on_component_msg "LIBMUSL" download_libmusl cd musl local opts1="--target=${ARCH} --build=${HOST_ARCH}" local opts2="--disable-shared --prefix=$MUSL_INSTALL" local opts3="--exec-prefix=$MUSL_INSTALL --enable-debug" local opts4="--syslibdir=$MUSL_INSTALL/lib" run_command2 "./configure $opts1 $opts2 $opts3 $opts4" configure.log # Unfortunately, musl's build system does not support reliably parallel # builds with make -j. That does not mean that make -j will usually fail. # It means that *sometimes* make -j will fail OR produce corrupted objects # (without failing the build!) leading to weird link errors in user apps. # For that reason, it's just much more convenient to NOT use parallel # builds. run_command2 "make" build.log run_command2 "make install" make_install.log cd $MUSL_INSTALL/bin cp musl-gcc musl-g++ sed -i 's/-${ARCH}-gcc/-${ARCH}-g++/' musl-g++ cd $MUSL_INSTALL/include ln -s /usr/include/linux . ln -s /usr/include/asm-generic . if [ -d /usr/include/asm ]; then ln -s /usr/include/asm . elif [ -d /usr/include/${HOST_ARCH}-linux-gnu/asm ]; then ln -s /usr/include/${HOST_ARCH}-linux-gnu/asm . else msg="WARNING: unable to find the linux include asm directory" echo msg >> make_install.log echo msg fi else show_skip_component_msg "LIBMUSL" fi reset_cc_vars export PATH="$saved_path" popd } function build_libmusl_installed_status { if [ -d $TC/$ARCH/musl ]; then if [ -f $TC/$ARCH/musl/install/lib/libc.a ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/******************************************************************************* * * Module Name: dbtest - Various debug-related tests * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdebug.h" #include "acnamesp.h" #include "acpredef.h" #include "acinterp.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbtest") /* Local prototypes */ static void AcpiDbTestAllObjects ( void); static ACPI_STATUS AcpiDbTestOneObject ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static ACPI_STATUS AcpiDbTestIntegerType ( ACPI_NAMESPACE_NODE *Node, UINT32 BitLength); static ACPI_STATUS AcpiDbTestBufferType ( ACPI_NAMESPACE_NODE *Node, UINT32 BitLength); static ACPI_STATUS AcpiDbTestStringType ( ACPI_NAMESPACE_NODE *Node, UINT32 ByteLength); static ACPI_STATUS AcpiDbTestPackageType ( ACPI_NAMESPACE_NODE *Node); static ACPI_STATUS AcpiDbTestFieldUnitType ( ACPI_OPERAND_OBJECT *ObjDesc); static ACPI_STATUS AcpiDbReadFromObject ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT_TYPE ExpectedType, ACPI_OBJECT **Value); static ACPI_STATUS AcpiDbWriteToObject ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT *Value); static void AcpiDbEvaluateAllPredefinedNames ( char *CountArg); static ACPI_STATUS AcpiDbEvaluateOnePredefinedName ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); /* * Test subcommands */ static ACPI_DB_ARGUMENT_INFO AcpiDbTestTypes [] = { {"OBJECTS"}, {"PREDEFINED"}, {NULL} /* Must be null terminated */ }; #define CMD_TEST_OBJECTS 0 #define CMD_TEST_PREDEFINED 1 #define BUFFER_FILL_VALUE 0xFF /* * Support for the special debugger read/write control methods. * These methods are installed into the current namespace and are * used to read and write the various namespace objects. The point * is to force the AML interpreter do all of the work. */ #define ACPI_DB_READ_METHOD "\\_T98" #define ACPI_DB_WRITE_METHOD "\\_T99" static ACPI_HANDLE ReadHandle = NULL; static ACPI_HANDLE WriteHandle = NULL; /* ASL Definitions of the debugger read/write control methods. AML below. */ #if 0 DefinitionBlock ("ssdt.aml", "SSDT", 2, "Intel", "DEBUG", 0x00000001) { Method (_T98, 1, NotSerialized) /* Read */ { Return (DeRefOf (Arg0)) } } DefinitionBlock ("ssdt2.aml", "SSDT", 2, "Intel", "DEBUG", 0x00000001) { Method (_T99, 2, NotSerialized) /* Write */ { Store (Arg1, Arg0) } } #endif static unsigned char ReadMethodCode[] = { 0x53,0x53,0x44,0x54,0x2E,0x00,0x00,0x00, /* 00000000 "SSDT...." */ 0x02,0xC9,0x49,0x6E,0x74,0x65,0x6C,0x00, /* 00000008 "..Intel." */ 0x44,0x45,0x42,0x55,0x47,0x00,0x00,0x00, /* 00000010 "DEBUG..." */ 0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C, /* 00000018 "....INTL" */ 0x18,0x12,0x13,0x20,0x14,0x09,0x5F,0x54, /* 00000020 "... .._T" */ 0x39,0x38,0x01,0xA4,0x83,0x68 /* 00000028 "98...h" */ }; static unsigned char WriteMethodCode[] = { 0x53,0x53,0x44,0x54,0x2E,0x00,0x00,0x00, /* 00000000 "SSDT...." */ 0x02,0x15,0x49,0x6E,0x74,0x65,0x6C,0x00, /* 00000008 "..Intel." */ 0x44,0x45,0x42,0x55,0x47,0x00,0x00,0x00, /* 00000010 "DEBUG..." */ 0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C, /* 00000018 "....INTL" */ 0x18,0x12,0x13,0x20,0x14,0x09,0x5F,0x54, /* 00000020 "... .._T" */ 0x39,0x39,0x02,0x70,0x69,0x68 /* 00000028 "99.pih" */ }; /******************************************************************************* * * FUNCTION: AcpiDbExecuteTest * * PARAMETERS: TypeArg - Subcommand * * RETURN: None * * DESCRIPTION: Execute various debug tests. * * Note: Code is prepared for future expansion of the TEST command. * ******************************************************************************/ void AcpiDbExecuteTest ( char *TypeArg) { UINT32 Temp; AcpiUtStrupr (TypeArg); Temp = AcpiDbMatchArgument (TypeArg, AcpiDbTestTypes); if (Temp == ACPI_TYPE_NOT_FOUND) { AcpiOsPrintf ("Invalid or unsupported argument\n"); return; } switch (Temp) { case CMD_TEST_OBJECTS: AcpiDbTestAllObjects (); break; case CMD_TEST_PREDEFINED: AcpiDbEvaluateAllPredefinedNames (NULL); break; default: break; } } /******************************************************************************* * * FUNCTION: AcpiDbTestAllObjects * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: This test implements the OBJECTS subcommand. It exercises the * namespace by reading/writing/comparing all data objects such * as integers, strings, buffers, fields, buffer fields, etc. * ******************************************************************************/ static void AcpiDbTestAllObjects ( void) { ACPI_STATUS Status; /* Install the debugger read-object control method if necessary */ if (!ReadHandle) { Status = AcpiInstallMethod (ReadMethodCode); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s, Could not install debugger read method\n", AcpiFormatException (Status)); return; } Status = AcpiGetHandle (NULL, ACPI_DB_READ_METHOD, &ReadHandle); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not obtain handle for debug method %s\n", ACPI_DB_READ_METHOD); return; } } /* Install the debugger write-object control method if necessary */ if (!WriteHandle) { Status = AcpiInstallMethod (WriteMethodCode); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s, Could not install debugger write method\n", AcpiFormatException (Status)); return; } Status = AcpiGetHandle (NULL, ACPI_DB_WRITE_METHOD, &WriteHandle); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not obtain handle for debug method %s\n", ACPI_DB_WRITE_METHOD); return; } } /* Walk the entire namespace, testing each supported named data object */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbTestOneObject, NULL, NULL, NULL); } /******************************************************************************* * * FUNCTION: AcpiDbTestOneObject * * PARAMETERS: ACPI_WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Test one namespace object. Supported types are Integer, * String, Buffer, Package, BufferField, and FieldUnit. * All other object types are simply ignored. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestOneObject ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OBJECT_TYPE LocalType; UINT32 BitLength = 0; UINT32 ByteLength = 0; ACPI_STATUS Status = AE_OK; Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjHandle); ObjDesc = Node->Object; /* * For the supported types, get the actual bit length or * byte length. Map the type to one of Integer/String/Buffer. */ switch (Node->Type) { case ACPI_TYPE_INTEGER: /* Integer width is either 32 or 64 */ LocalType = ACPI_TYPE_INTEGER; BitLength = AcpiGbl_IntegerBitWidth; break; case ACPI_TYPE_STRING: LocalType = ACPI_TYPE_STRING; ByteLength = ObjDesc->String.Length; break; case ACPI_TYPE_BUFFER: LocalType = ACPI_TYPE_BUFFER; ByteLength = ObjDesc->Buffer.Length; BitLength = ByteLength * 8; break; case ACPI_TYPE_PACKAGE: LocalType = ACPI_TYPE_PACKAGE; break; case ACPI_TYPE_FIELD_UNIT: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: LocalType = ACPI_TYPE_FIELD_UNIT; break; case ACPI_TYPE_BUFFER_FIELD: /* * The returned object will be a Buffer if the field length * is larger than the size of an Integer (32 or 64 bits * depending on the DSDT version). */ LocalType = ACPI_TYPE_INTEGER; if (ObjDesc) { BitLength = ObjDesc->CommonField.BitLength; ByteLength = ACPI_ROUND_BITS_UP_TO_BYTES (BitLength); if (BitLength > AcpiGbl_IntegerBitWidth) { LocalType = ACPI_TYPE_BUFFER; } } break; default: /* Ignore all non-data types - Methods, Devices, Scopes, etc. */ return (AE_OK); } /* Emit the common prefix: Type:Name */ AcpiOsPrintf ("%14s: %4.4s", AcpiUtGetTypeName (Node->Type), Node->Name.Ascii); if (!ObjDesc) { AcpiOsPrintf (" No attached sub-object, ignoring\n"); return (AE_OK); } /* At this point, we have resolved the object to one of the major types */ switch (LocalType) { case ACPI_TYPE_INTEGER: Status = AcpiDbTestIntegerType (Node, BitLength); break; case ACPI_TYPE_STRING: Status = AcpiDbTestStringType (Node, ByteLength); break; case ACPI_TYPE_BUFFER: Status = AcpiDbTestBufferType (Node, BitLength); break; case ACPI_TYPE_PACKAGE: Status = AcpiDbTestPackageType (Node); break; case ACPI_TYPE_FIELD_UNIT: Status = AcpiDbTestFieldUnitType (ObjDesc); break; default: AcpiOsPrintf (" Ignoring, type not implemented (%2.2X)", LocalType); break; } /* Exit on error, but don't abort the namespace walk */ if (ACPI_FAILURE (Status)) { Status = AE_OK; } AcpiOsPrintf ("\n"); return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbTestIntegerType * * PARAMETERS: Node - Parent NS node for the object * BitLength - Actual length of the object. Used for * support of arbitrary length FieldUnit * and BufferField objects. * * RETURN: Status * * DESCRIPTION: Test read/write for an Integer-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestIntegerType ( ACPI_NAMESPACE_NODE *Node, UINT32 BitLength) { ACPI_OBJECT *Temp1 = NULL; ACPI_OBJECT *Temp2 = NULL; ACPI_OBJECT *Temp3 = NULL; ACPI_OBJECT WriteValue; UINT64 ValueToWrite; ACPI_STATUS Status; if (BitLength > 64) { AcpiOsPrintf (" Invalid length for an Integer: %u", BitLength); return (AE_OK); } /* Read the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_INTEGER, &Temp1); if (ACPI_FAILURE (Status)) { return (Status); } AcpiOsPrintf (ACPI_DEBUG_LENGTH_FORMAT " %8.8X%8.8X", BitLength, ACPI_ROUND_BITS_UP_TO_BYTES (BitLength), ACPI_FORMAT_UINT64 (Temp1->Integer.Value)); ValueToWrite = ACPI_UINT64_MAX >> (64 - BitLength); if (Temp1->Integer.Value == ValueToWrite) { ValueToWrite = 0; } /* Write a new value */ WriteValue.Type = ACPI_TYPE_INTEGER; WriteValue.Integer.Value = ValueToWrite; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the new value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_INTEGER, &Temp2); if (ACPI_FAILURE (Status)) { goto Exit; } if (Temp2->Integer.Value != ValueToWrite) { AcpiOsPrintf (" MISMATCH 2: %8.8X%8.8X, expecting %8.8X%8.8X", ACPI_FORMAT_UINT64 (Temp2->Integer.Value), ACPI_FORMAT_UINT64 (ValueToWrite)); } /* Write back the original value */ WriteValue.Integer.Value = Temp1->Integer.Value; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_INTEGER, &Temp3); if (ACPI_FAILURE (Status)) { goto Exit; } if (Temp3->Integer.Value != Temp1->Integer.Value) { AcpiOsPrintf (" MISMATCH 3: %8.8X%8.8X, expecting %8.8X%8.8X", ACPI_FORMAT_UINT64 (Temp3->Integer.Value), ACPI_FORMAT_UINT64 (Temp1->Integer.Value)); } Exit: if (Temp1) {AcpiOsFree (Temp1);} if (Temp2) {AcpiOsFree (Temp2);} if (Temp3) {AcpiOsFree (Temp3);} return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbTestBufferType * * PARAMETERS: Node - Parent NS node for the object * BitLength - Actual length of the object. * * RETURN: Status * * DESCRIPTION: Test read/write for an Buffer-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestBufferType ( ACPI_NAMESPACE_NODE *Node, UINT32 BitLength) { ACPI_OBJECT *Temp1 = NULL; ACPI_OBJECT *Temp2 = NULL; ACPI_OBJECT *Temp3 = NULL; UINT8 *Buffer; ACPI_OBJECT WriteValue; ACPI_STATUS Status; UINT32 ByteLength; UINT32 i; UINT8 ExtraBits; ByteLength = ACPI_ROUND_BITS_UP_TO_BYTES (BitLength); if (ByteLength == 0) { AcpiOsPrintf (" Ignoring zero length buffer"); return (AE_OK); } /* Allocate a local buffer */ Buffer = ACPI_ALLOCATE_ZEROED (ByteLength); if (!Buffer) { return (AE_NO_MEMORY); } /* Read the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_BUFFER, &Temp1); if (ACPI_FAILURE (Status)) { goto Exit; } /* Emit a few bytes of the buffer */ AcpiOsPrintf (ACPI_DEBUG_LENGTH_FORMAT, BitLength, Temp1->Buffer.Length); for (i = 0; ((i < 8) && (i < ByteLength)); i++) { AcpiOsPrintf (" %2.2X", Temp1->Buffer.Pointer[i]); } AcpiOsPrintf ("... "); /* * Write a new value. * * Handle possible extra bits at the end of the buffer. Can * happen for FieldUnits larger than an integer, but the bit * count is not an integral number of bytes. Zero out the * unused bits. */ memset (Buffer, BUFFER_FILL_VALUE, ByteLength); ExtraBits = BitLength % 8; if (ExtraBits) { Buffer [ByteLength - 1] = ACPI_MASK_BITS_ABOVE (ExtraBits); } WriteValue.Type = ACPI_TYPE_BUFFER; WriteValue.Buffer.Length = ByteLength; WriteValue.Buffer.Pointer = Buffer; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the new value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_BUFFER, &Temp2); if (ACPI_FAILURE (Status)) { goto Exit; } if (memcmp (Temp2->Buffer.Pointer, Buffer, ByteLength)) { AcpiOsPrintf (" MISMATCH 2: New buffer value"); } /* Write back the original value */ WriteValue.Buffer.Length = ByteLength; WriteValue.Buffer.Pointer = Temp1->Buffer.Pointer; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_BUFFER, &Temp3); if (ACPI_FAILURE (Status)) { goto Exit; } if (memcmp (Temp1->Buffer.Pointer, Temp3->Buffer.Pointer, ByteLength)) { AcpiOsPrintf (" MISMATCH 3: While restoring original buffer"); } Exit: ACPI_FREE (Buffer); if (Temp1) {AcpiOsFree (Temp1);} if (Temp2) {AcpiOsFree (Temp2);} if (Temp3) {AcpiOsFree (Temp3);} return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbTestStringType * * PARAMETERS: Node - Parent NS node for the object * ByteLength - Actual length of the object. * * RETURN: Status * * DESCRIPTION: Test read/write for an String-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestStringType ( ACPI_NAMESPACE_NODE *Node, UINT32 ByteLength) { ACPI_OBJECT *Temp1 = NULL; ACPI_OBJECT *Temp2 = NULL; ACPI_OBJECT *Temp3 = NULL; char *ValueToWrite = "Test String from AML Debugger"; ACPI_OBJECT WriteValue; ACPI_STATUS Status; /* Read the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_STRING, &Temp1); if (ACPI_FAILURE (Status)) { return (Status); } AcpiOsPrintf (ACPI_DEBUG_LENGTH_FORMAT " \"%s\"", (Temp1->String.Length * 8), Temp1->String.Length, Temp1->String.Pointer); /* Write a new value */ WriteValue.Type = ACPI_TYPE_STRING; WriteValue.String.Length = strlen (ValueToWrite); WriteValue.String.Pointer = ValueToWrite; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the new value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_STRING, &Temp2); if (ACPI_FAILURE (Status)) { goto Exit; } if (strcmp (Temp2->String.Pointer, ValueToWrite)) { AcpiOsPrintf (" MISMATCH 2: %s, expecting %s", Temp2->String.Pointer, ValueToWrite); } /* Write back the original value */ WriteValue.String.Length = strlen (Temp1->String.Pointer); WriteValue.String.Pointer = Temp1->String.Pointer; Status = AcpiDbWriteToObject (Node, &WriteValue); if (ACPI_FAILURE (Status)) { goto Exit; } /* Ensure that we can read back the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_STRING, &Temp3); if (ACPI_FAILURE (Status)) { goto Exit; } if (strcmp (Temp1->String.Pointer, Temp3->String.Pointer)) { AcpiOsPrintf (" MISMATCH 3: %s, expecting %s", Temp3->String.Pointer, Temp1->String.Pointer); } Exit: if (Temp1) {AcpiOsFree (Temp1);} if (Temp2) {AcpiOsFree (Temp2);} if (Temp3) {AcpiOsFree (Temp3);} return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbTestPackageType * * PARAMETERS: Node - Parent NS node for the object * * RETURN: Status * * DESCRIPTION: Test read for a Package object. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestPackageType ( ACPI_NAMESPACE_NODE *Node) { ACPI_OBJECT *Temp1 = NULL; ACPI_STATUS Status; /* Read the original value */ Status = AcpiDbReadFromObject (Node, ACPI_TYPE_PACKAGE, &Temp1); if (ACPI_FAILURE (Status)) { return (Status); } AcpiOsPrintf (" %.2X Elements", Temp1->Package.Count); AcpiOsFree (Temp1); return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbTestFieldUnitType * * PARAMETERS: ObjDesc - A field unit object * * RETURN: Status * * DESCRIPTION: Test read/write on a named field unit. * ******************************************************************************/ static ACPI_STATUS AcpiDbTestFieldUnitType ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_OPERAND_OBJECT *RegionObj; UINT32 BitLength = 0; UINT32 ByteLength = 0; ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *RetBufferDesc; /* Supported spaces are memory/io/pci_config */ RegionObj = ObjDesc->Field.RegionObj; switch (RegionObj->Region.SpaceId) { case ACPI_ADR_SPACE_SYSTEM_MEMORY: case ACPI_ADR_SPACE_SYSTEM_IO: case ACPI_ADR_SPACE_PCI_CONFIG: /* Need the interpreter to execute */ AcpiUtAcquireMutex (ACPI_MTX_INTERPRETER); AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); /* Exercise read-then-write */ Status = AcpiExReadDataFromField (NULL, ObjDesc, &RetBufferDesc); if (Status == AE_OK) { AcpiExWriteDataToField (RetBufferDesc, ObjDesc, NULL); AcpiUtRemoveReference (RetBufferDesc); } AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); AcpiUtReleaseMutex (ACPI_MTX_INTERPRETER); BitLength = ObjDesc->CommonField.BitLength; ByteLength = ACPI_ROUND_BITS_UP_TO_BYTES (BitLength); AcpiOsPrintf (ACPI_DEBUG_LENGTH_FORMAT " [%s]", BitLength, ByteLength, AcpiUtGetRegionName (RegionObj->Region.SpaceId)); return (Status); default: AcpiOsPrintf ( " %s address space is not supported in this command [%4.4s]", AcpiUtGetRegionName (RegionObj->Region.SpaceId), RegionObj->Region.Node->Name.Ascii); return (AE_OK); } } /******************************************************************************* * * FUNCTION: AcpiDbReadFromObject * * PARAMETERS: Node - Parent NS node for the object * ExpectedType - Object type expected from the read * Value - Where the value read is returned * * RETURN: Status * * DESCRIPTION: Performs a read from the specified object by invoking the * special debugger control method that reads the object. Thus, * the AML interpreter is doing all of the work, increasing the * validity of the test. * ******************************************************************************/ static ACPI_STATUS AcpiDbReadFromObject ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT_TYPE ExpectedType, ACPI_OBJECT **Value) { ACPI_OBJECT *RetValue; ACPI_OBJECT_LIST ParamObjects; ACPI_OBJECT Params[2]; ACPI_BUFFER ReturnObj; ACPI_STATUS Status; Params[0].Type = ACPI_TYPE_LOCAL_REFERENCE; Params[0].Reference.ActualType = Node->Type; Params[0].Reference.Handle = ACPI_CAST_PTR (ACPI_HANDLE, Node); ParamObjects.Count = 1; ParamObjects.Pointer = Params; ReturnObj.Length = ACPI_ALLOCATE_BUFFER; AcpiGbl_MethodExecuting = TRUE; Status = AcpiEvaluateObject (ReadHandle, NULL, &ParamObjects, &ReturnObj); AcpiGbl_MethodExecuting = FALSE; if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not read from object, %s", AcpiFormatException (Status)); return (Status); } RetValue = (ACPI_OBJECT *) ReturnObj.Pointer; switch (RetValue->Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: case ACPI_TYPE_PACKAGE: /* * Did we receive the type we wanted? Most important for the * Integer/Buffer case (when a field is larger than an Integer, * it should return a Buffer). */ if (RetValue->Type != ExpectedType) { AcpiOsPrintf (" Type mismatch: Expected %s, Received %s", AcpiUtGetTypeName (ExpectedType), AcpiUtGetTypeName (RetValue->Type)); AcpiOsFree (ReturnObj.Pointer); return (AE_TYPE); } *Value = RetValue; break; default: AcpiOsPrintf (" Unsupported return object type, %s", AcpiUtGetTypeName (RetValue->Type)); AcpiOsFree (ReturnObj.Pointer); return (AE_TYPE); } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbWriteToObject * * PARAMETERS: Node - Parent NS node for the object * Value - Value to be written * * RETURN: Status * * DESCRIPTION: Performs a write to the specified object by invoking the * special debugger control method that writes the object. Thus, * the AML interpreter is doing all of the work, increasing the * validity of the test. * ******************************************************************************/ static ACPI_STATUS AcpiDbWriteToObject ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT *Value) { ACPI_OBJECT_LIST ParamObjects; ACPI_OBJECT Params[2]; ACPI_STATUS Status; Params[0].Type = ACPI_TYPE_LOCAL_REFERENCE; Params[0].Reference.ActualType = Node->Type; Params[0].Reference.Handle = ACPI_CAST_PTR (ACPI_HANDLE, Node); /* Copy the incoming user parameter */ memcpy (&Params[1], Value, sizeof (ACPI_OBJECT)); ParamObjects.Count = 2; ParamObjects.Pointer = Params; AcpiGbl_MethodExecuting = TRUE; Status = AcpiEvaluateObject (WriteHandle, NULL, &ParamObjects, NULL); AcpiGbl_MethodExecuting = FALSE; if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not write to object, %s", AcpiFormatException (Status)); } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbEvaluateAllPredefinedNames * * PARAMETERS: CountArg - Max number of methods to execute * * RETURN: None * * DESCRIPTION: Namespace batch execution. Execute predefined names in the * namespace, up to the max count, if specified. * ******************************************************************************/ static void AcpiDbEvaluateAllPredefinedNames ( char *CountArg) { ACPI_DB_EXECUTE_WALK Info; Info.Count = 0; Info.MaxCount = ACPI_UINT32_MAX; if (CountArg) { Info.MaxCount = strtoul (CountArg, NULL, 0); } /* Search all nodes in namespace */ (void) AcpiWalkNamespace (ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbEvaluateOnePredefinedName, NULL, (void *) &Info, NULL); AcpiOsPrintf ( "Evaluated %u predefined names in the namespace\n", Info.Count); } /******************************************************************************* * * FUNCTION: AcpiDbEvaluateOnePredefinedName * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Batch execution module. Currently only executes predefined * ACPI names. * ******************************************************************************/ static ACPI_STATUS AcpiDbEvaluateOnePredefinedName ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; ACPI_DB_EXECUTE_WALK *Info = (ACPI_DB_EXECUTE_WALK *) Context; char *Pathname; const ACPI_PREDEFINED_INFO *Predefined; ACPI_DEVICE_INFO *ObjInfo; ACPI_OBJECT_LIST ParamObjects; ACPI_OBJECT Params[ACPI_METHOD_NUM_ARGS]; ACPI_OBJECT *ThisParam; ACPI_BUFFER ReturnObj; ACPI_STATUS Status; UINT16 ArgTypeList; UINT8 ArgCount; UINT8 ArgType; UINT32 i; /* The name must be a predefined ACPI name */ Predefined = AcpiUtMatchPredefinedMethod (Node->Name.Ascii); if (!Predefined) { return (AE_OK); } if (Node->Type == ACPI_TYPE_LOCAL_SCOPE) { return (AE_OK); } Pathname = AcpiNsGetNormalizedPathname (Node, TRUE); if (!Pathname) { return (AE_OK); } /* Get the object info for number of method parameters */ Status = AcpiGetObjectInfo (ObjHandle, &ObjInfo); if (ACPI_FAILURE (Status)) { ACPI_FREE (Pathname); return (Status); } ParamObjects.Count = 0; ParamObjects.Pointer = NULL; if (ObjInfo->Type == ACPI_TYPE_METHOD) { /* Setup default parameters (with proper types) */ ArgTypeList = Predefined->Info.ArgumentList; ArgCount = METHOD_GET_ARG_COUNT (ArgTypeList); /* * Setup the ACPI-required number of arguments, regardless of what * the actual method defines. If there is a difference, then the * method is wrong and a warning will be issued during execution. */ ThisParam = Params; for (i = 0; i < ArgCount; i++) { ArgType = METHOD_GET_NEXT_TYPE (ArgTypeList); ThisParam->Type = ArgType; switch (ArgType) { case ACPI_TYPE_INTEGER: ThisParam->Integer.Value = 1; break; case ACPI_TYPE_STRING: ThisParam->String.Pointer = "This is the default argument string"; ThisParam->String.Length = strlen (ThisParam->String.Pointer); break; case ACPI_TYPE_BUFFER: ThisParam->Buffer.Pointer = (UINT8 *) Params; /* just a garbage buffer */ ThisParam->Buffer.Length = 48; break; case ACPI_TYPE_PACKAGE: ThisParam->Package.Elements = NULL; ThisParam->Package.Count = 0; break; default: AcpiOsPrintf ("%s: Unsupported argument type: %u\n", Pathname, ArgType); break; } ThisParam++; } ParamObjects.Count = ArgCount; ParamObjects.Pointer = Params; } ACPI_FREE (ObjInfo); ReturnObj.Pointer = NULL; ReturnObj.Length = ACPI_ALLOCATE_BUFFER; /* Do the actual method execution */ AcpiGbl_MethodExecuting = TRUE; Status = AcpiEvaluateObject (Node, NULL, &ParamObjects, &ReturnObj); AcpiOsPrintf ("%-32s returned %s\n", Pathname, AcpiFormatException (Status)); AcpiGbl_MethodExecuting = FALSE; ACPI_FREE (Pathname); /* Ignore status from method execution */ Status = AE_OK; /* Update count, check if we have executed enough methods */ Info->Count++; if (Info->Count >= Info->MaxCount) { Status = AE_CTRL_TERMINATE; } return (Status); } <file_sep> /* * The following is a Tilck adaptation of the following libmusl (v1.1.19) files: * * - src/time/__secs_to_tm.c. * - src/time/__tm_to_secs.c * - src/time/__year_to_secs.c * - src/time/__month_to_secs.c * * Original license [from the "COPYRIGHT" file]: * * musl as a whole is licensed under the following standard MIT license: * * ---------------------------------------------------------------------- * Copyright © 2005-2014 <NAME>, et al. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <tilck/common/basic_defs.h> #include <tilck/common/datetime.h> /* 2000-03-01 (mod 400 year, immediately after feb29 */ #define LEAPOCH (946684800LL + 86400*(31+29)) #define DAYS_PER_400Y (365*400 + 97) #define DAYS_PER_100Y (365*100 + 24) #define DAYS_PER_4Y (365*4 + 1) int timestamp_to_datetime(int64_t t, struct datetime *d) { int64_t days, secs, years; int remdays, remsecs, remyears; int qc_cycles, c_cycles, q_cycles; int months; int wday, yday, leap; static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29}; /* Reject time_t values whose year would overflow int */ if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL) return -1; secs = t - LEAPOCH; days = secs / 86400; remsecs = secs % 86400; if (remsecs < 0) { remsecs += 86400; days--; } wday = (3 + days) % 7; if (wday < 0) wday += 7; qc_cycles = (int)(days / (s64)DAYS_PER_400Y); remdays = days % DAYS_PER_400Y; if (remdays < 0) { remdays += DAYS_PER_400Y; qc_cycles--; } c_cycles = remdays / DAYS_PER_100Y; if (c_cycles == 4) c_cycles--; remdays -= c_cycles * DAYS_PER_100Y; q_cycles = remdays / DAYS_PER_4Y; if (q_cycles == 25) q_cycles--; remdays -= q_cycles * DAYS_PER_4Y; remyears = remdays / 365; if (remyears == 4) remyears--; remdays -= remyears * 365; leap = !remyears && (q_cycles || !c_cycles); yday = remdays + 31 + 28 + leap; if (yday >= 365+leap) yday -= 365+leap; years = remyears + 4*q_cycles + 100*c_cycles + 400LL*qc_cycles; for (months=0; days_in_month[months] <= remdays; months++) remdays -= days_in_month[months]; if (months >= 10) { months -= 12; years++; } if (years+100 > INT_MAX || years+100 < INT_MIN) return -1; d->year = (u16)(years + 2000); d->month = ( u8)(months + 3); d->day = ( u8)(remdays + 1); d->weekday = ( u8)(wday); d->hour = ( u8)(remsecs / 3600); d->min = ( u8)((remsecs / 60) % 60); d->sec = ( u8)(remsecs % 60); return 0; } static int64_t __year_to_secs(int64_t year, int *is_leap) { int is_leap_ignored = 0; if ((uint64_t)year-2ULL <= 136) { int y = (int)year; int leaps = (y-68)>>2; if (!((y-68)&3)) { leaps--; if (is_leap) *is_leap = 1; } else if (is_leap) { *is_leap = 0; } return 31536000*(y-70) + 86400*leaps; } int cycles, centuries, leaps, rem; if (!is_leap) is_leap = &is_leap_ignored; cycles = (int)((year-100) / 400); rem = (year-100) % 400; if (rem < 0) { cycles--; rem += 400; } if (!rem) { *is_leap = 1; centuries = 0; leaps = 0; } else { if (rem >= 200) { if (rem >= 300) centuries = 3, rem -= 300; else centuries = 2, rem -= 200; } else { if (rem >= 100) centuries = 1, rem -= 100; else centuries = 0; } if (!rem) { *is_leap = 0; leaps = 0; } else { leaps = (unsigned)rem / 4U; rem %= 4U; *is_leap = !rem; } } leaps += 97*cycles + 24*centuries - *is_leap; return (year-100) * 31536000LL + leaps * 86400LL + 946684800 + 86400; } static int __month_to_secs(int month, int is_leap) { static const int secs_through_month[] = { 0, 31*86400, 59*86400, 90*86400, 120*86400, 151*86400, 181*86400, 212*86400, 243*86400, 273*86400, 304*86400, 334*86400 }; int t = secs_through_month[month]; if (is_leap && month >= 2) t+=86400; return t; } int64_t datetime_to_timestamp(struct datetime d) { int is_leap; int64_t year = d.year - 1900; int month = d.month-1; if (month >= 12 || month < 0) { int adj = month / 12; month %= 12; if (month < 0) { adj--; month += 12; } year += adj; } int64_t t = __year_to_secs(year, &is_leap); t += __month_to_secs(month, is_leap); t += 86400LL * (d.day-1); t += 3600LL * d.hour; t += 60LL * d.min; t += d.sec; return t; } <file_sep>/****************************************************************************** * * Module Name: exconvrt - Object conversion routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlcode.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exconvrt") /* Local prototypes */ static UINT32 AcpiExConvertToAscii ( UINT64 Integer, UINT16 Base, UINT8 *String, UINT8 MaxLength); /******************************************************************************* * * FUNCTION: AcpiExConvertToInteger * * PARAMETERS: ObjDesc - Object to be converted. Must be an * Integer, Buffer, or String * ResultDesc - Where the new Integer object is returned * ImplicitConversion - Used for string conversion * * RETURN: Status * * DESCRIPTION: Convert an ACPI Object to an integer. * ******************************************************************************/ ACPI_STATUS AcpiExConvertToInteger ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc, UINT32 ImplicitConversion) { ACPI_OPERAND_OBJECT *ReturnDesc; UINT8 *Pointer; UINT64 Result; UINT32 i; UINT32 Count; ACPI_FUNCTION_TRACE_PTR (ExConvertToInteger, ObjDesc); switch (ObjDesc->Common.Type) { case ACPI_TYPE_INTEGER: /* No conversion necessary */ *ResultDesc = ObjDesc; return_ACPI_STATUS (AE_OK); case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: /* Note: Takes advantage of common buffer/string fields */ Pointer = ObjDesc->Buffer.Pointer; Count = ObjDesc->Buffer.Length; break; default: return_ACPI_STATUS (AE_TYPE); } /* * Convert the buffer/string to an integer. Note that both buffers and * strings are treated as raw data - we don't convert ascii to hex for * strings. * * There are two terminating conditions for the loop: * 1) The size of an integer has been reached, or * 2) The end of the buffer or string has been reached */ Result = 0; /* String conversion is different than Buffer conversion */ switch (ObjDesc->Common.Type) { case ACPI_TYPE_STRING: /* * Convert string to an integer - for most cases, the string must be * hexadecimal as per the ACPI specification. The only exception (as * of ACPI 3.0) is that the ToInteger() operator allows both decimal * and hexadecimal strings (hex prefixed with "0x"). * * Explicit conversion is used only by ToInteger. * All other string-to-integer conversions are implicit conversions. */ if (ImplicitConversion) { Result = AcpiUtImplicitStrtoul64 (ACPI_CAST_PTR (char, Pointer)); } else { Result = AcpiUtExplicitStrtoul64 (ACPI_CAST_PTR (char, Pointer)); } break; case ACPI_TYPE_BUFFER: /* Check for zero-length buffer */ if (!Count) { return_ACPI_STATUS (AE_AML_BUFFER_LIMIT); } /* Transfer no more than an integer's worth of data */ if (Count > AcpiGbl_IntegerByteWidth) { Count = AcpiGbl_IntegerByteWidth; } /* * Convert buffer to an integer - we simply grab enough raw data * from the buffer to fill an integer */ for (i = 0; i < Count; i++) { /* * Get next byte and shift it into the Result. * Little endian is used, meaning that the first byte of the buffer * is the LSB of the integer */ Result |= (((UINT64) Pointer[i]) << (i * 8)); } break; default: /* No other types can get here */ break; } /* Create a new integer */ ReturnDesc = AcpiUtCreateIntegerObject (Result); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Converted value: %8.8X%8.8X\n", ACPI_FORMAT_UINT64 (Result))); /* Save the Result */ (void) AcpiExTruncateFor32bitTable (ReturnDesc); *ResultDesc = ReturnDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExConvertToBuffer * * PARAMETERS: ObjDesc - Object to be converted. Must be an * Integer, Buffer, or String * ResultDesc - Where the new buffer object is returned * * RETURN: Status * * DESCRIPTION: Convert an ACPI Object to a Buffer * ******************************************************************************/ ACPI_STATUS AcpiExConvertToBuffer ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc) { ACPI_OPERAND_OBJECT *ReturnDesc; UINT8 *NewBuf; ACPI_FUNCTION_TRACE_PTR (ExConvertToBuffer, ObjDesc); switch (ObjDesc->Common.Type) { case ACPI_TYPE_BUFFER: /* No conversion necessary */ *ResultDesc = ObjDesc; return_ACPI_STATUS (AE_OK); case ACPI_TYPE_INTEGER: /* * Create a new Buffer object. * Need enough space for one integer */ ReturnDesc = AcpiUtCreateBufferObject (AcpiGbl_IntegerByteWidth); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Copy the integer to the buffer, LSB first */ NewBuf = ReturnDesc->Buffer.Pointer; memcpy (NewBuf, &ObjDesc->Integer.Value, AcpiGbl_IntegerByteWidth); break; case ACPI_TYPE_STRING: /* * Create a new Buffer object * Size will be the string length * * NOTE: Add one to the string length to include the null terminator. * The ACPI spec is unclear on this subject, but there is existing * ASL/AML code that depends on the null being transferred to the new * buffer. */ ReturnDesc = AcpiUtCreateBufferObject ((ACPI_SIZE) ObjDesc->String.Length + 1); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Copy the string to the buffer */ NewBuf = ReturnDesc->Buffer.Pointer; strncpy ((char *) NewBuf, (char *) ObjDesc->String.Pointer, ObjDesc->String.Length); break; default: return_ACPI_STATUS (AE_TYPE); } /* Mark buffer initialized */ ReturnDesc->Common.Flags |= AOPOBJ_DATA_VALID; *ResultDesc = ReturnDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExConvertToAscii * * PARAMETERS: Integer - Value to be converted * Base - ACPI_STRING_DECIMAL or ACPI_STRING_HEX * String - Where the string is returned * DataWidth - Size of data item to be converted, in bytes * * RETURN: Actual string length * * DESCRIPTION: Convert an ACPI Integer to a hex or decimal string * ******************************************************************************/ static UINT32 AcpiExConvertToAscii ( UINT64 Integer, UINT16 Base, UINT8 *String, UINT8 DataWidth) { UINT64 Digit; UINT32 i; UINT32 j; UINT32 k = 0; UINT32 HexLength; UINT32 DecimalLength; UINT32 Remainder; BOOLEAN SupressZeros; ACPI_FUNCTION_ENTRY (); switch (Base) { case 10: /* Setup max length for the decimal number */ switch (DataWidth) { case 1: DecimalLength = ACPI_MAX8_DECIMAL_DIGITS; break; case 4: DecimalLength = ACPI_MAX32_DECIMAL_DIGITS; break; case 8: default: DecimalLength = ACPI_MAX64_DECIMAL_DIGITS; break; } SupressZeros = TRUE; /* No leading zeros */ Remainder = 0; for (i = DecimalLength; i > 0; i--) { /* Divide by nth factor of 10 */ Digit = Integer; for (j = 0; j < i; j++) { (void) AcpiUtShortDivide (Digit, 10, &Digit, &Remainder); } /* Handle leading zeros */ if (Remainder != 0) { SupressZeros = FALSE; } if (!SupressZeros) { String[k] = (UINT8) (ACPI_ASCII_ZERO + Remainder); k++; } } break; case 16: /* HexLength: 2 ascii hex chars per data byte */ HexLength = (DataWidth * 2); for (i = 0, j = (HexLength-1); i < HexLength; i++, j--) { /* Get one hex digit, most significant digits first */ String[k] = (UINT8) AcpiUtHexToAsciiChar (Integer, ACPI_MUL_4 (j)); k++; } break; default: return (0); } /* * Since leading zeros are suppressed, we must check for the case where * the integer equals 0 * * Finally, null terminate the string and return the length */ if (!k) { String [0] = ACPI_ASCII_ZERO; k = 1; } String [k] = 0; return ((UINT32) k); } /******************************************************************************* * * FUNCTION: AcpiExConvertToString * * PARAMETERS: ObjDesc - Object to be converted. Must be an * Integer, Buffer, or String * ResultDesc - Where the string object is returned * Type - String flags (base and conversion type) * * RETURN: Status * * DESCRIPTION: Convert an ACPI Object to a string. Supports both implicit * and explicit conversions and related rules. * ******************************************************************************/ ACPI_STATUS AcpiExConvertToString ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc, UINT32 Type) { ACPI_OPERAND_OBJECT *ReturnDesc; UINT8 *NewBuf; UINT32 i; UINT32 StringLength = 0; UINT16 Base = 16; UINT8 Separator = ','; ACPI_FUNCTION_TRACE_PTR (ExConvertToString, ObjDesc); switch (ObjDesc->Common.Type) { case ACPI_TYPE_STRING: /* No conversion necessary */ *ResultDesc = ObjDesc; return_ACPI_STATUS (AE_OK); case ACPI_TYPE_INTEGER: switch (Type) { case ACPI_EXPLICIT_CONVERT_DECIMAL: /* * From ToDecimalString, integer source. * * Make room for the maximum decimal number size */ StringLength = ACPI_MAX_DECIMAL_DIGITS; Base = 10; break; default: /* Two hex string characters for each integer byte */ StringLength = ACPI_MUL_2 (AcpiGbl_IntegerByteWidth); break; } /* * Create a new String * Need enough space for one ASCII integer (plus null terminator) */ ReturnDesc = AcpiUtCreateStringObject ((ACPI_SIZE) StringLength); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } NewBuf = ReturnDesc->Buffer.Pointer; /* Convert integer to string */ StringLength = AcpiExConvertToAscii ( ObjDesc->Integer.Value, Base, NewBuf, AcpiGbl_IntegerByteWidth); /* Null terminate at the correct place */ ReturnDesc->String.Length = StringLength; NewBuf [StringLength] = 0; break; case ACPI_TYPE_BUFFER: /* Setup string length, base, and separator */ switch (Type) { case ACPI_EXPLICIT_CONVERT_DECIMAL: /* Used by ToDecimalString */ /* * Explicit conversion from the ToDecimalString ASL operator. * * From ACPI: "If the input is a buffer, it is converted to a * a string of decimal values separated by commas." */ Base = 10; /* * Calculate the final string length. Individual string values * are variable length (include separator for each) */ for (i = 0; i < ObjDesc->Buffer.Length; i++) { if (ObjDesc->Buffer.Pointer[i] >= 100) { StringLength += 4; } else if (ObjDesc->Buffer.Pointer[i] >= 10) { StringLength += 3; } else { StringLength += 2; } } break; case ACPI_IMPLICIT_CONVERT_HEX: /* * Implicit buffer-to-string conversion * * From the ACPI spec: * "The entire contents of the buffer are converted to a string of * two-character hexadecimal numbers, each separated by a space." * * Each hex number is prefixed with 0x (11/2018) */ Separator = ' '; StringLength = (ObjDesc->Buffer.Length * 5); break; case ACPI_EXPLICIT_CONVERT_HEX: /* * Explicit conversion from the ToHexString ASL operator. * * From ACPI: "If Data is a buffer, it is converted to a string of * hexadecimal values separated by commas." * * Each hex number is prefixed with 0x (11/2018) */ Separator = ','; StringLength = (ObjDesc->Buffer.Length * 5); break; default: return_ACPI_STATUS (AE_BAD_PARAMETER); } /* * Create a new string object and string buffer * (-1 because of extra separator included in StringLength from above) * Allow creation of zero-length strings from zero-length buffers. */ if (StringLength) { StringLength--; } ReturnDesc = AcpiUtCreateStringObject ((ACPI_SIZE) StringLength); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } NewBuf = ReturnDesc->Buffer.Pointer; /* * Convert buffer bytes to hex or decimal values * (separated by commas or spaces) */ for (i = 0; i < ObjDesc->Buffer.Length; i++) { if (Base == 16) { /* Emit 0x prefix for explicit/implicit hex conversion */ *NewBuf++ = '0'; *NewBuf++ = 'x'; } NewBuf += AcpiExConvertToAscii ( (UINT64) ObjDesc->Buffer.Pointer[i], Base, NewBuf, 1); /* Each digit is separated by either a comma or space */ *NewBuf++ = Separator; } /* * Null terminate the string * (overwrites final comma/space from above) */ if (ObjDesc->Buffer.Length) { NewBuf--; } *NewBuf = 0; break; default: return_ACPI_STATUS (AE_TYPE); } *ResultDesc = ReturnDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExConvertToTargetType * * PARAMETERS: DestinationType - Current type of the destination * SourceDesc - Source object to be converted. * ResultDesc - Where the converted object is returned * WalkState - Current method state * * RETURN: Status * * DESCRIPTION: Implements "implicit conversion" rules for storing an object. * ******************************************************************************/ ACPI_STATUS AcpiExConvertToTargetType ( ACPI_OBJECT_TYPE DestinationType, ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT **ResultDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (ExConvertToTargetType); /* Default behavior */ *ResultDesc = SourceDesc; /* * If required by the target, * perform implicit conversion on the source before we store it. */ switch (GET_CURRENT_ARG_TYPE (WalkState->OpInfo->RuntimeArgs)) { case ARGI_SIMPLE_TARGET: case ARGI_FIXED_TARGET: case ARGI_INTEGER_REF: /* Handles Increment, Decrement cases */ switch (DestinationType) { case ACPI_TYPE_LOCAL_REGION_FIELD: /* * Named field can always handle conversions */ break; default: /* No conversion allowed for these types */ if (DestinationType != SourceDesc->Common.Type) { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Explicit operator, will store (%s) over existing type (%s)\n", AcpiUtGetObjectTypeName (SourceDesc), AcpiUtGetTypeName (DestinationType))); Status = AE_TYPE; } } break; case ARGI_TARGETREF: case ARGI_STORE_TARGET: switch (DestinationType) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: /* * These types require an Integer operand. We can convert * a Buffer or a String to an Integer if necessary. */ Status = AcpiExConvertToInteger (SourceDesc, ResultDesc, ACPI_IMPLICIT_CONVERSION); break; case ACPI_TYPE_STRING: /* * The operand must be a String. We can convert an * Integer or Buffer if necessary */ Status = AcpiExConvertToString (SourceDesc, ResultDesc, ACPI_IMPLICIT_CONVERT_HEX); break; case ACPI_TYPE_BUFFER: /* * The operand must be a Buffer. We can convert an * Integer or String if necessary */ Status = AcpiExConvertToBuffer (SourceDesc, ResultDesc); break; default: ACPI_ERROR ((AE_INFO, "Bad destination type during conversion: 0x%X", DestinationType)); Status = AE_AML_INTERNAL; break; } break; case ARGI_REFERENCE: /* * CreateXxxxField cases - we are storing the field object into the name */ break; default: ACPI_ERROR ((AE_INFO, "Unknown Target type ID 0x%X AmlOpcode 0x%X DestType %s", GET_CURRENT_ARG_TYPE (WalkState->OpInfo->RuntimeArgs), WalkState->Opcode, AcpiUtGetTypeName (DestinationType))); Status = AE_AML_INTERNAL; } /* * Source-to-Target conversion semantics: * * If conversion to the target type cannot be performed, then simply * overwrite the target with the new object and type. */ if (Status == AE_TYPE) { Status = AE_OK; } return_ACPI_STATUS (Status); } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(EFI_ARCH x86_64) set(GNUEFI_DIR ${TCROOT}/x86_64/gnu-efi) file(GLOB SOURCES ${GLOB_CONF_DEP} "../*.c" "*.S") file(RELATIVE_PATH relPath ${CMAKE_BINARY_DIR} ${EFI_${EFI_ARCH}_FILE}) CHECK_C_COMPILER_FLAG(-maccumulate-outgoing-args ACC_OUTGOING_ARGS_SUPPORTED) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") if (ACC_OUTGOING_ARGS_SUPPORTED) include (../GenericBuild.cmake) else() show_no_ms_abi_support_warning(${relPath}) endif() elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") # Building the BOOTX64.EFI file with Clang is tricky, in particular using # gnu-efi. Even if recent clang versions support MS ABI, the GenericBuild # used above doesn't work out-of-the-box. It requires a serious effort. # Since Tilck's official toolchain is based on GCC and Clang is partially # supported just for static analysis and devel builds with the -Wconversion # option, making the EFI bootloaders build with Clang is *not* a must. # Until now, this x86_64 target just created a fake empty file to make the # build pass, after displaying a warning during run of CMake. That's the # typical case of devel (contrib) builds (./scripts/cmake_run --contrib). # # Because this warning is annoying and it would be convenient to just behave # as in the GCC case, here a small hack will be used. We'll use (assuming it # exists) the system's GCC to build the 64-bit EFI bootloader. That's exactly # what happens with the OFFICIAL (default) Tilck builds (just, there CC and # CXX and not defined by the user). Because the build host must be a x86_64 # linux system and we have to build a 64-bit EFI bootloader, using the system # compiler is perfectly fine. Again, even in this case where CC=clang. # The CC=clang option has anyway meaning just for the C files in the kernel; # the rest of the files and targets will be built anyway with the custom # GCC-based toolchain. set(CMAKE_C_COMPILER gcc) set(CMAKE_CXX_COMPILER g++) set(CMAKE_ASM_COMPILER gcc) include (../GenericBuild.cmake) else() message(FATAL_ERROR "Compiler ${CMAKE_C_COMPILER_ID} NOT supported") endif() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/datetime.h> #define PIT_FREQ 1193182 #define PIT_CMD_PORT 0x43 #define PIT_CH0_PORT 0x40 #define PIT_CH1_PORT 0x41 #define PIT_CH2_PORT 0x42 #define PIT_MODE_BIN 0b00000000 #define PIT_MODE_BCD 0b00000001 #define PIT_MODE_0 0b00000000 // interrupt on terminal count #define PIT_MODE_1 0b00000010 // hardware re-triggerable one-shot #define PIT_MODE_2 0b00000100 // rate generator #define PIT_MODE_3 0b00000110 // square wave generator #define PIT_MODE_4 0b00001000 // software triggered strobe #define PIT_MODE_5 0b00001010 // hardware triggered strobe #define PIT_ACC_LO 0b00010000 // access mode: lobyte only #define PIT_ACC_HI 0b00100000 // access mode: hibyte only #define PIT_ACC_LOHI 0b00110000 // access mode: lobyte/hibyte #define PIT_CH0 0b00000000 // select channel 0 #define PIT_CH1 0b01000000 // select channel 1 #define PIT_CH2 0b10000000 // select channel 2 #define PIT_READ_BACK 0b11000000 // read-back command (8254 only) /* * Set the time between ticks to be `interval`, where 1 means 1/TS_SCALE sec. * Typically, TS_SCALE = 1,000,000,000 which means `interval` is expected to be * in nanoseconds. * * Returns the _real_ interval between ticks, which is hw-specific. */ u32 hw_timer_setup(u32 interval) { const u32 hz = TS_SCALE / interval; const u32 divisor = PIT_FREQ / hz; u64 actual_interval; ASSERT(IN_RANGE_INC(hz, 18, 1000)); /* * Actual interval calculation. * * Let's define F = PIT_FREQ. * We want `hz`, but at most we can get: * * F * HZ = ------------- * ceil(F/hz) * * Therefore, our actual interval (I) will be: 1/HZ seconds. * Now, if we scale everything with TS_SCALE (S) we get: * * S * I = ----------------------- units (typically nanoseconds) * F * -------------- * ceil(F/hz) * * which is equivalent to: * * S * ceil(F/hz) * I = ---------------------------- units * F */ actual_interval = TS_SCALE; actual_interval *= PIT_FREQ / hz; actual_interval /= PIT_FREQ; ASSERT(actual_interval < UINT32_MAX); outb(PIT_CMD_PORT, PIT_MODE_BIN | PIT_MODE_2 | PIT_ACC_LOHI | PIT_CH0); outb(PIT_CH0_PORT, divisor & 0xff); /* Set low byte of divisor */ outb(PIT_CH0_PORT, (divisor >> 8) & 0xff); /* Set high byte of divisor */ return (u32)actual_interval; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include "devshell.h" #include "sysenter.h" /* * Call waitpid() after the child exited. */ int cmd_wpid1(int argc, char **argv) { int wstatus; pid_t pid; int child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { // This is the child, just exit printf("child: exit\n"); exit(23); } printf("Created child with pid: %d\n", child_pid); /* Wait for the child to exit */ usleep(100*1000); /* Now, let's see call waitpid() after the child exited */ pid = waitpid(child_pid, &wstatus, 0); if (!WIFEXITED(wstatus)) { printf("[pid: %d] PARENT: the child %d did NOT exited normally\n", getpid(), pid); return 1; } int exit_code = WEXITSTATUS(wstatus); printf("waitpid() returned %d, exit code: %d\n", pid, exit_code); if (pid != child_pid) { printf("Expected waitpid() to return child's pid (got: %d)\n", pid); return 1; } if (exit_code != 23) { printf("Expected the exit code to be 23 (got: %d)\n", exit_code); return 1; } return 0; } /* waitpid(-1): wait any child to exit */ int cmd_wpid2(int argc, char **argv) { const int child_count = 3; int pids[child_count]; int wstatus; pid_t pid; for (int i = 0; i < child_count; i++) { int child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { printf("[pid: %d] child: exit (%d)\n", getpid(), 10 + i); usleep((child_count - i) * 100*1000); exit(10 + i); // exit from the child } pids[i] = child_pid; } usleep(120 * 1000); for (int i = child_count-1; i >= 0; i--) { printf("[pid: %d] PARENT: waitpid(-1)\n", getpid()); pid = waitpid(-1, &wstatus, 0); if (!WIFEXITED(wstatus)) { printf("[pid: %d] PARENT: the child %d did NOT exited normally\n", getpid(), pid); return 1; } int exit_code = WEXITSTATUS(wstatus); printf("[pid: %d] PARENT: waitpid() returned %d, exit code: %d\n", getpid(), pid, exit_code); if (pid != pids[i]) { printf("Expected waitpid() to return %d (got: %d)\n", pids[i], pid); return 1; } if (exit_code != 10+i) { printf("Expected the exit code to be %d (got: %d)\n", 10+i, exit_code); return 1; } } return 0; } /* wait on any child after they exit */ int cmd_wpid3(int argc, char **argv) { int wstatus; pid_t pid; int child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { /* This is the child, just exit with a special code */ printf("child: exit\n"); exit(23); } printf("Created child with pid: %d\n", child_pid); /* Wait for the child to exit */ usleep(100*1000); /* Now, let's see call waitpid() after the child exited */ pid = waitpid(-1, &wstatus, 0); if (!WIFEXITED(wstatus)) { printf("[pid: %d] PARENT: the child %d did NOT exited normally\n", getpid(), pid); return 1; } int exit_code = WEXITSTATUS(wstatus); printf("waitpid() returned %d, exit code: %d\n", pid, exit_code); if (pid != child_pid) { printf("Expected waitpid() to return child's pid (got: %d)\n", pid); return 1; } if (exit_code != 23) { printf("Expected the exit code to be 23 (got: %d)\n", exit_code); return 1; } return 0; } /* * Test the case of a parent dying before its children. */ int cmd_wpid4(int argc, char **argv) { pid_t pid; int wstatus; int child_pid; bool failed = false; printf("[grandparent] my pid: %d\n", getpid()); child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { /* in the child: now create other children and die before them */ int grand_child1, grand_child2; grand_child1 = fork(); if (grand_child1 < 0) { printf("fork() failed\n"); exit(1); } if (!grand_child1) { usleep(50*1000); exit(10); } printf(STR_PARENT "child 1: %d\n", grand_child1); grand_child2 = fork(); if (grand_child2 < 0) { printf("fork() failed\n"); exit(1); } if (!grand_child2) { usleep(100*1000); exit(11); } printf(STR_PARENT "child 2: %d\n", grand_child2); printf(STR_PARENT "exit\n"); exit(0); } /* in the grandparent: wait for any child */ printf("[grandparent] child pid: %d\n", child_pid); while ((pid = waitpid(-1, &wstatus, 0)) > 0) { int code = WEXITSTATUS(wstatus); printf("[grandparent] waitpid(): child %d exited with %d\n", pid, code); if (code != 0) failed = true; } printf("[grandparent] exit (failed: %d)\n", failed); return failed ? 1 : 0; } void print_waitpid_change(int child, int wstatus) { int code = WEXITSTATUS(wstatus); int sig = WTERMSIG(wstatus); if (WIFSTOPPED(wstatus)) printf(STR_PARENT "child %d: STOPPED\n", child); else if (WIFCONTINUED(wstatus)) printf(STR_PARENT "child %d: CONTINUED\n", child); else if (WIFEXITED(wstatus)) printf(STR_PARENT "child %d: EXITED with %d\n", child, code); else if (WIFSIGNALED(wstatus)) printf(STR_PARENT "child %d: KILLED by sig: %d\n", child, sig); else printf(STR_PARENT "child %d: UNKNOWN status change!\n", child); fflush(stdout); } static int call_waitpid(int wait_pid, int *wstatus, int *children, int n) { int pid = waitpid(wait_pid, wstatus, WUNTRACED | WCONTINUED); if (pid > 0) { int child_index = -1; for (int i = 0; i < n && child_index < 0; i++) if (children[i] == pid) child_index = i; print_waitpid_change(child_index, *wstatus); } return pid; } /* * Wait on children getting SIGSTOP and SIGCONT */ int cmd_wpid5(int argc, char **argv) { pid_t children[2]; int pid, wstatus; children[0] = fork(); if (children[0] < 0) { printf(STR_PARENT "fork() failed\n"); return 1; } if (!children[0]) { /* child 0's body */ printf("[child 0] Hello from pid %d\n", getpid()); for (int i = 0; i < 10; i++) { printf("[child 0] i = %d\n", i); usleep(100 * 1000); } printf("[child 0] exit\n"); exit(0); } printf(STR_PARENT "children[0] pid: %d\n", children[0]); children[1] = fork(); if (children[1] < 0) { printf(STR_PARENT "fork() failed\n"); kill(children[0], SIGKILL); return 1; } if (!children[1]) { /* child 1's body */ printf("[child 1] Hello from pid %d\n", getpid()); printf("[child 1] Wait some time...\n"); usleep(250 * 1000); printf("[child 1] Send SIGSTOP to child 0\n"); kill(children[0], SIGSTOP); printf("[child 1] Wait some time...\n"); usleep(250 * 1000); printf("[child 1] Send SIGCONT to child 0\n"); kill(children[0], SIGCONT); printf("[child 1] Wait some time...\n"); usleep(50 * 1000); printf("[child 1] exit\n"); exit(0); } /* Expect child 0 stopped */ pid = call_waitpid(-1, &wstatus, children, 2); DEVSHELL_CMD_ASSERT(pid == children[0]); DEVSHELL_CMD_ASSERT(WIFSTOPPED(wstatus)); /* Expect child 0 continued */ pid = call_waitpid(-1, &wstatus, children, 2); DEVSHELL_CMD_ASSERT(pid == children[0]); DEVSHELL_CMD_ASSERT(WIFCONTINUED(wstatus)); /* Expect that child 1 exited */ pid = call_waitpid(-1, &wstatus, children, 2); DEVSHELL_CMD_ASSERT(pid == children[1]); DEVSHELL_CMD_ASSERT(WIFEXITED(wstatus)); /* Expect that child 0 exited */ pid = call_waitpid(-1, &wstatus, children, 2); DEVSHELL_CMD_ASSERT(pid == children[0]); DEVSHELL_CMD_ASSERT(WIFEXITED(wstatus)); return 0; } static void wpid6_test_child(int n, int pgid) { printf("[child %d] Hello from pid %d\n", n, getpid()); printf("[child %d] curr pgid: %d\n", n, getpgid(0)); setpgid(0, pgid); printf("[child %d] new pgid: %d\n", n, getpgid(0)); for (int i = 0; i < 10; i++) { printf("[child %d] i = %d\n", n, i); usleep(100 * 1000); } printf("[child %d] exit\n", n); exit(0); } static void wpid6_test_active_child(int n, int pgid1, int pgid2) { printf("[active child %d] Hello from pid %d\n", n, getpid()); usleep(500 * 1000); printf("[active child %d] Send SIGKILL to the pgid %d\n", n, pgid1); kill(-pgid1, SIGKILL); usleep(100 * 1000); printf("[active child %d] Send SIGKILL to the pgid %d\n", n, pgid2); kill(-pgid2, SIGKILL); printf("[active child %d] exit\n", n); exit(0); } /* * Wait on a process group + send a signal to a process group */ int cmd_wpid6(int argc, char **argv) { int cld[7] = {0}; int pid, wstatus; int g1_killed = 0; int g2_killed = 0; printf(STR_PARENT "Hello, pid: %d, pgid: %d\n", getpid(), getpgid(0)); printf(STR_PARENT "Start children..\n"); for (int i = 0; i < ARRAY_SIZE(cld) - 1; i++) { cld[i] = fork(); DEVSHELL_CMD_ASSERT(cld[i] >= 0); if (!cld[i]) { int pgid = i < 3 ? cld[0] : cld[3]; wpid6_test_child(i, pgid); } } cld[6] = fork(); DEVSHELL_CMD_ASSERT(cld[6] >= 0); if (!cld[6]) wpid6_test_active_child(6, cld[0], cld[3]); printf(STR_PARENT "Wait for children to change their pgid\n"); usleep(100 * 1000); printf(STR_PARENT "Wait on the 1st process group\n"); while ((pid = call_waitpid(-cld[0], &wstatus, cld, ARRAY_SIZE(cld))) > 0) { if (pid == cld[0] || pid == cld[1] || pid == cld[2]) g1_killed++; } DEVSHELL_CMD_ASSERT(g1_killed == 3); printf(STR_PARENT "Wait on the 2st process group\n"); while ((pid = call_waitpid(-cld[3], &wstatus, cld, ARRAY_SIZE(cld))) > 0) { if (pid == cld[3] || pid == cld[4] || pid == cld[5]) g2_killed++; } DEVSHELL_CMD_ASSERT(g2_killed == 3); printf(STR_PARENT "Wait on any other child\n"); pid = call_waitpid(-1, &wstatus, cld, ARRAY_SIZE(cld)); DEVSHELL_CMD_ASSERT(pid == cld[6]); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <random> #include <limits> #include <ctime> #include <gtest/gtest.h> extern "C" { #include <tilck/common/basic_defs.h> #include <tilck/common/datetime.h> } using namespace std; using namespace testing; static void biconv_test(int64_t min, int64_t max) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); uniform_int_distribution<int64_t> dist(min, max); cout << "[ INFO ] random seed: " << seed << endl; for (int i = 0; i < 100000; i++) { const int64_t t = dist(e); datetime d; const int rc = timestamp_to_datetime(t, &d); ASSERT_EQ(rc, 0); const int64_t convT = datetime_to_timestamp(d); ASSERT_EQ(convT, t); } } TEST(datetime, biconv_32bit) { biconv_test(numeric_limits<int>::min(), numeric_limits<int>::max()); } TEST(datetime, biconv_ext) { biconv_test( -59011459200ull, /* Friday, January 1, 0100 00:00:00 */ 253402300799ull /* Friday, December 31, 9999 23:59:59 */ ); } TEST(datetime, timestamp_to_datetime) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); uniform_int_distribution<> dist( numeric_limits<int>::min(), numeric_limits<int>::max() ); cout << "[ INFO ] random seed: " << seed << endl; for (int i = 0; i < 30000; i++) { datetime d; struct tm tm; const time_t t = dist(e); const int rc = timestamp_to_datetime((int64_t)t, &d); ASSERT_EQ(rc, 0); gmtime_r(&t, &tm); ASSERT_EQ(tm.tm_sec, d.sec) << "T: " << t; ASSERT_EQ(tm.tm_min, d.min) << "T: " << t; ASSERT_EQ(tm.tm_hour, d.hour) << "T: " << t; ASSERT_EQ(tm.tm_wday, d.weekday) << "T: " << t; ASSERT_EQ(tm.tm_mday, d.day) << "T: " << t; ASSERT_EQ(tm.tm_mon+1, d.month) << "T: " << t; ASSERT_EQ(tm.tm_year+1900, d.year) << "T: " << t; } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/process.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/datetime.h> #include <sys/prctl.h> // system header #include <sys/wait.h> // system header static bool waitpid_should_skip_child(struct task *waiting_task, struct task *pos, int tid) { /* * tid has several special values: * * > 0 meaning wait for the child whose tid is equal to `tid`. * * < -1 meaning wait for any child process whose process * group ID is equal to the absolute value of pid. * * -1 meaning wait for any child process. * * 0 meaning wait for any child process whose process * group ID is equal to that of the calling process. * * NOTE: Tilck's tid is called `pid` in the Linux kernel. What Tilck calls * `pid` is called in Linux `tgid` (thread ground id). */ if (tid > 0) return pos->tid != tid; if (tid < -1) { /* * -pid is a process group id: skip children which don't belong to * that specific process group. */ return pos->pi->pgid != -tid; } if (tid == 0) { /* We have to skip children belonging to a different group */ return pos->pi->pgid != waiting_task->pi->pgid; } ASSERT(tid == -1); /* We're going to wait on any children */ return false; } static struct task * get_task_if_changed(struct task *ti, int opts) { enum task_state s = atomic_load_explicit(&ti->state, mo_relaxed); if (s == TASK_STATE_ZOMBIE) return ti; if (ti->stopped && !ti->was_stopped && (opts & WUNTRACED)) { ti->was_stopped = true; return ti; } if (!ti->stopped && ti->was_stopped && (opts & WCONTINUED)) { ti->was_stopped = false; return ti; } return NULL; } static struct task * get_child_with_changed_status(struct process *pi, int tid, int opts, u32 *child_cnt_ref) { struct task *curr = get_curr_task(); struct task *chtask = NULL; struct task *pos; u32 cnt = 0; list_for_each_ro(pos, &pi->children, siblings_node) { if (waitpid_should_skip_child(curr, pos, tid)) continue; cnt++; if ((chtask = get_task_if_changed(pos, opts))) break; } *child_cnt_ref = cnt; return chtask; } static bool is_waiting_on_multiple_children(struct task *ti, int *tid) { struct wait_obj *wobj = &ti->wobj; if (ti->state != TASK_STATE_SLEEPING) return false; if (wobj->type != WOBJ_TASK) return false; *tid = (int)wait_obj_get_data(wobj); return *tid < 0; } static bool is_good_reason_to_wake_up_task(struct wait_obj *wo, enum wakeup_reason r) { return r == task_died || (r == task_stopped && (wo->extra & WEXTRA_TASK_STOPPED)) || (r == task_continued && (wo->extra & WEXTRA_TASK_CONTINUED)); } void wake_up_tasks_waiting_on(struct task *ti, enum wakeup_reason r) { struct wait_obj *wo, *wo_temp; struct process *pi = ti->pi; ASSERT(!is_preemption_enabled()); list_for_each(wo, wo_temp, &ti->tasks_waiting_list, wait_list_node) { ASSERT(wo->type == WOBJ_TASK); struct task *task_to_wake_up = CONTAINER_OF(wo, struct task, wobj); if (task_to_wake_up->state != TASK_STATE_SLEEPING) { /* * The task MUST be in waitpid(), but it's not sleeping. Because of * the implementation of waitpid(), it's safe to just skip this task * here as it will notice the event before going to sleep again. */ continue; } if (is_good_reason_to_wake_up_task(wo, r)) wake_up(task_to_wake_up); } if (LIKELY(pi->parent_pid > 0)) { struct task *parent_task = get_task(pi->parent_pid); int tid; if (is_waiting_on_multiple_children(parent_task, &tid) && !waitpid_should_skip_child(parent_task, ti, tid) && is_good_reason_to_wake_up_task(&parent_task->wobj, r)) { wake_up(parent_task); } send_signal(pi->parent_pid, SIGCHLD, true); } } /* * *************************************************************** * * SYSCALLS * * *************************************************************** */ int sys_wait4(int tid, int *user_wstatus, int options, void *user_rusage) { struct task *curr = get_curr_task(); struct task *chtask = NULL; int chtask_tid = -1; u16 wobj_extra = NO_EXTRA; if (options & WUNTRACED) wobj_extra |= WEXTRA_TASK_STOPPED; if (options & WCONTINUED) wobj_extra |= WEXTRA_TASK_CONTINUED; ASSERT(are_interrupts_enabled()); while (true) { struct list *wait_list = NULL; u32 child_count = 0; disable_preemption(); if (tid > 0) { struct task *waited_task = get_task(tid); if (!waited_task || !task_is_parent(curr, waited_task)) { enable_preemption(); return -ECHILD; } wait_list = &waited_task->tasks_waiting_list; child_count = 1; chtask = get_task_if_changed(waited_task, options); } else { chtask = get_child_with_changed_status(curr->pi, tid, options, &child_count); } if (chtask) { chtask_tid = chtask->tid; break; /* note: leave the preemption disabled */ } /* No chtask has been found */ if (!child_count) { /* No children to wait for */ enable_preemption(); return -ECHILD; } if (options & WNOHANG) { /* With WNOHANG we must not hang until a child changes state */ enable_preemption(); return 0; } /* Hang until a child changes state */ prepare_to_wait_on(WOBJ_TASK, TO_PTR(tid), wobj_extra, wait_list); enter_sleep_wait_state(); if (pending_signals()) return -EINTR; } // while (true) /* * The only way to get here is a positive branch in `if (chtask)`: this mean * that we have a valid `chtask` and that preemption is disabled. */ ASSERT(!is_preemption_enabled()); if (user_wstatus) { if (copy_to_user(user_wstatus, &chtask->wstatus, sizeof(s32)) < 0) chtask_tid = -EFAULT; } if (user_rusage) { struct k_rusage ru = {0}; struct k_timespec64 tp; u64 user_ticks = chtask->ticks.total - chtask->ticks.total_kernel; ticks_to_timespec(user_ticks, &tp); ru.ru_utime.tv_sec = (long) tp.tv_sec; ru.ru_utime.tv_usec = tp.tv_nsec / 1000; ticks_to_timespec(chtask->ticks.total_kernel, &tp); ru.ru_stime.tv_sec = (long) tp.tv_sec; ru.ru_stime.tv_usec = tp.tv_nsec / 1000; if (copy_to_user(user_rusage, &ru, sizeof(ru)) < 0) chtask_tid = -EFAULT; } if (chtask->state == TASK_STATE_ZOMBIE) remove_task(chtask); enable_preemption(); return chtask_tid; } int sys_waitpid(int tid, int *user_wstatus, int options) { return sys_wait4(tid, user_wstatus, options, NULL); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/page_size.h> #if defined(__i386__) && !defined(__x86_64__) typedef union x86_page page_t; typedef struct x86_page_table page_table_t; typedef union x86_page_dir_entry page_dir_entry_t; typedef struct x86_pdir pdir_t; typedef struct x86_regs regs_t; typedef struct x86_arch_task_members arch_task_members_t; typedef struct x86_arch_proc_members arch_proc_members_t; #define ARCH_TASK_MEMBERS_SIZE 8 #define ARCH_TASK_MEMBERS_ALIGN 4 #define ARCH_PROC_MEMBERS_SIZE 16 #define ARCH_PROC_MEMBERS_ALIGN 4 #elif defined(__x86_64__) typedef void *pdir_t; typedef struct x86_64_regs regs_t; typedef struct x86_64_arch_task_members arch_task_members_t; typedef struct x86_64_arch_proc_members arch_proc_members_t; #define ARCH_TASK_MEMBERS_SIZE 16 #define ARCH_TASK_MEMBERS_ALIGN 8 #define ARCH_PROC_MEMBERS_SIZE 8 #define ARCH_PROC_MEMBERS_ALIGN 8 #elif defined(__aarch64__) typedef void *pdir_t; typedef u64 regs_t; typedef u64 arch_task_members_t; typedef u64 arch_proc_members_t; #define ARCH_TASK_MEMBERS_SIZE 8 #define ARCH_TASK_MEMBERS_ALIGN 8 #define ARCH_PROC_MEMBERS_SIZE 8 #define ARCH_PROC_MEMBERS_ALIGN 8 #else #error Unsupported architecture. #endif enum irq_action { IRQ_NOT_HANDLED = 0, IRQ_HANDLED = 1, }; typedef void (*soft_int_handler_t)(regs_t *); typedef enum irq_action (*irq_handler_t)(void *ctx); STATIC_ASSERT(PAGE_SIZE == (1u << PAGE_SHIFT)); STATIC_ASSERT( KERNEL_STACK_PAGES == 1 || KERNEL_STACK_PAGES == 2 || KERNEL_STACK_PAGES == 4 ); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/color_defs.h> #include "dp_int.h" #define ERASE_DISPLAY "\033[2J" #define REVERSE_VIDEO "\033[7m" #define E_COLOR_WHITE "\033[37m" #define E_COLOR_BR_WHITE "\033[97m" #define E_COLOR_RED "\033[31m" #define E_COLOR_BR_RED "\033[91m" #define E_COLOR_GREEN "\033[32m" #define E_COLOR_BR_GREEN "\033[92m" #define E_COLOR_BROWN "\033[33m" #define E_COLOR_YELLOW "\033[93m" #define E_COLOR_BLUE "\033[34m" #define E_COLOR_BR_BLUE "\033[94m" #define E_COLOR_MAGENTA "\033[35m" #define E_COLOR_CYAN "\033[36m" #define E_COLOR_BR_CYAN "\033[96m" #define E_COLOR_WHITE_ON_RED "\033[97;41m" #define RESET_ATTRS "\033[0m" #define GFX_ON "\033(0" #define GFX_OFF "\033(B" #define HIDE_CURSOR "\033[?25l" #define SHOW_CURSOR "\033[?25h" #define USE_ALT_BUF "\033[?1049h" #define USE_DEF_BUF "\033[?1049l" #define TERM_VLINE GFX_ON "x" GFX_OFF #define DP_COLOR make_color(DEFAULT_FG_COLOR, DEFAULT_BG_COLOR) #define DP_REV_COLOR make_color(DEFAULT_BG_COLOR, DEFAULT_FG_COLOR) #define DP_ESC_COLOR E_COLOR_WHITE #define DP_KEY_BACKSPACE 0x7f #define DP_KEY_ESC 0x1b #define DP_KEY_ENTER 0x0d #define DP_KEY_CTRL_C 0x03 #define DP_KEY_CTRL_T 0x14 void dp_write(int row, int col, const char *fmt, ...); void dp_draw_rect(const char *label, const char *esc_label_color, int row, int col, int h, int w); /* WARNING: dirty macro expecting a local `row` variable to be defined */ #define dp_writeln(...) dp_write(row++, 0, __VA_ARGS__) /* WARNING: dirty macro expecting both `row` and `col` to be defined */ #define dp_writeln2(...) dp_write(row++, col, __VA_ARGS__) void dp_reverse_colors(void); void dp_reset_attrs(void); void dp_move_right(int n); void dp_move_left(int n); void dp_move_to_col(int n); void dp_clear(void); void dp_move_cursor(int row, int col); void dp_set_cursor_enabled(bool enabled); void dp_switch_to_alt_buffer(void); void dp_switch_to_default_buffer(void); void dp_show_modal_msg(const char *msg); static inline const char * dp_sign_value_esc_color(long val) { return val > 0 ? E_COLOR_GREEN : val < 0 ? E_COLOR_BR_RED : DP_ESC_COLOR; } /* raw functions, avoid using when possible */ void dp_write_raw(const char *fmt, ...); void dp_draw_rect_raw(int row, int col, int h, int w); void dp_write_raw_int(const char *buf, int len); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int ramfs_mkdir(struct vfs_path *p, mode_t mode) { struct ramfs_path *rp = (struct ramfs_path *) &p->fs_path; struct ramfs_data *d = p->fs->device_data; struct ramfs_inode *new_dir; int rc; if (rp->inode) return -EEXIST; if ((rp->dir_inode->mode & 0300) != 0300) /* write + execute */ return -EACCES; if (!(new_dir = ramfs_create_inode_dir(d, mode, rp->dir_inode))) return -ENOSPC; if ((rc = ramfs_dir_add_entry(rp->dir_inode, p->last_comp, new_dir))) { ramfs_destroy_inode(d, new_dir); return rc; } return rc; } static int ramfs_rmdir(struct vfs_path *p) { struct ramfs_path *rp = (struct ramfs_path *) &p->fs_path; struct ramfs_data *d = p->fs->device_data; struct ramfs_inode *i = rp->inode; ASSERT(rwlock_wp_holding_exlock(&d->rwlock)); if (rp->type != VFS_DIR) return -ENOTDIR; if ((rp->dir_inode->mode & 0200) != 0200) /* write permission */ return -EACCES; if (!rp->dir_entry) return -EINVAL; /* root dir case */ if (p->last_comp[0] == '.' && !p->last_comp[1]) return -EINVAL; /* trying to delete /a/b/c/. */ if (i->num_entries > 2) return -ENOTEMPTY; /* empty dirs have two entries: '.' and '..' */ if (get_ref_count(i) > 0) { /* * For the moment, we won't support deleting a directory opened somewhere * as this is allowed by POSIX. Linux typically allowed that, both for * files and for directories. On Tilck let's try to keep that allowed only * for files. TODO: consider supporting removal of in-use directories. */ return -EBUSY; } ASSERT(i->entries_tree_root != NULL); ramfs_dir_remove_entry(i, i->entries_tree_root); // drop . ASSERT(i->entries_tree_root != NULL); ramfs_dir_remove_entry(i, i->entries_tree_root); // drop .. ASSERT(i->num_entries == 0); ASSERT(i->entries_tree_root == NULL); /* Remove the dir entry */ ramfs_dir_remove_entry(rp->dir_inode, rp->dir_entry); /* Destroy the inode */ ramfs_destroy_inode(d, i); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #ifndef __x86_64__ #error This header can be used only when building for x86_64. #endif static ALWAYS_INLINE ulong get_stack_ptr(void) { ulong sp; asmVolatile("mov %%rsp, %0" : "=r" (sp) : /* no input */ : /* no clobber */); return sp; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #if BINTREE_PTR_FUNCS #define CMP(a, b) bintree_find_ptr_cmp(a, b, field_off) #else #define CMP(a, b) objval_cmpfun(a, b) #endif #if BINTREE_PTR_FUNCS void * bintree_find_ptr_internal(void *root_obj, const void *value_ptr, long bintree_offset, long field_off) #else void * bintree_find_internal(void *root_obj, const void *value_ptr, cmpfun_ptr objval_cmpfun, long bintree_offset) #endif { long c; while (root_obj) { if (!(c = CMP(root_obj, value_ptr))) return root_obj; // root_obj is smaller then val => val is bigger => go right. root_obj = c < 0 ? RIGHT_OF(root_obj) : LEFT_OF(root_obj); } return NULL; } #undef CMP <file_sep># SPDX-License-Identifier: BSD-2-Clause import re import os import sys import fcntl import base64 import zlib import subprocess from enum import Enum from .stdio import msg_print, raw_print, direct_print # Constants TEST_TYPES = ['selftest', 'shellcmd', 'interactive'] TEST_TYPES_PRETTY = ['Self tests', 'Shell cmd tests', 'Interactive tests'] KERNEL_DUMP_GCDA_STR = '** GCOV gcda files **' KERNEL_DUMP_GCDA_END_STR = '** GCOV gcda files END **' # Classes class Fail(Enum): success = 0 invalid_args = 1 reboot = 2 timeout = 3 panic = 4 shell_no_zero_exit = 5 gcov_error = 6 shell_unknown_exit_code = 7 invalid_build_config = 8 invalid_system_config = 9 no_hello_message = 10 user_interruption = 11 qemu_msg_parsing_fail = 12 qemu_died_unexpectedly = 13 some_tests_failed = 14 no_tests_matching = 15 other = 16 # Globals __g_fail_reason = Fail.success # Functions def set_once_fail_reason(reason: Fail): global __g_fail_reason if __g_fail_reason == Fail.success: __g_fail_reason = reason def get_fail_reason(): return __g_fail_reason def no_failures(): return __g_fail_reason == Fail.success def any_failures(): return __g_fail_reason != Fail.success def reset_fail_reason(): global __g_fail_reason __g_fail_reason = Fail.success def get_fail_by_code(err_code): for f in Fail: if f.value == err_code: return f return None def is_cmake_opt_enabled(opt): return opt.lower() in ["on", "1", "true", "yes", "y"] def fh_set_blocking_mode(fh, blocking): sys_fd = fh.fileno() fl = fcntl.fcntl(sys_fd, fcntl.F_GETFL) if not blocking: fcntl.fcntl(sys_fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) else: fcntl.fcntl(sys_fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK) def run_gen_coverage_report_tool(gen_cov_tool): try: subprocess.check_output([gen_cov_tool, '--acc']) except Exception as e: msg_print( "{} generated the exception: {}".format(gen_cov_tool, str(e)) ) msg_print("Output of {} --acc:".format(gen_cov_tool)) direct_print(getattr(e, 'output', '<no output>')) msg_print("--- end output ---") return False return True def write_gcda_file(file, b64data): try: data_compressed = base64.b64decode(b64data) data = zlib.decompress(data_compressed) with open(file, 'wb') as fh: fh.write(data) except Exception as e: msg_print("") msg_print( "While writing gcda file '{}', " "got exception: {}".format(file, str(e)) ) raw_print("b64data:\n<<{}>>\n".format(b64data)) set_once_fail_reason(Fail.gcov_error) return False return True def unrunnable_build_graceful_exit(): msg_print("This build was NOT meant to be run") msg_print("Just exiting with 0") sys.exit(0) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <stdbool.h> #include <unistd.h> #include <sys/syscall.h> #include <x86intrin.h> /* for __rdtsc() */ #include <tilck/common/basic_defs.h> #include <tilck/common/syscalls.h> #include "sysenter.h" typedef unsigned long long ull_t; /* configuration */ #define MAX_ARGS 16 #define FORK_TEST_ITERS (250 * MB) /* constants */ #define COLOR_RED "\033[31m" #define COLOR_GREEN "\033[32m" #define COLOR_YELLOW "\033[93m" #define RESET_ATTRS "\033[0m" #define PFX "[devshell] " #define STR_PARENT "[ parent ] " #define STR_CHILD "[child] " #define STR_RUN "[RUN ] " #define STR_PASS "[PASSED] " #define STR_FAIL "[FAILED] " /* utils */ #define RDTSC() __rdtsc() #define DEBUG_BREAK() asmVolatile("int $3") #define DEVSHELL_CMD_ASSERT(x) \ do { \ if (!(x)) { \ fprintf(stderr, PFX "ASSERT '%s' FAILED.\n\t" \ "On:\t%s:%d\n\tERRNO:\t%s\n", \ #x, __FILE__, __LINE__, strerror(errno)); \ do_cmd_exit(1); \ } \ } while(0) /* --- */ extern bool dump_coverage; extern char **shell_argv; extern char **shell_env; typedef int (*cmd_func_type)(int argc, char **argv); enum timeout_type { TT_SHORT = 0, TT_MED = 1, TT_LONG = 2, }; struct test_cmd_entry { const char *name; cmd_func_type func; enum timeout_type tt; bool enabled_in_st; }; void run_if_known_command(const char *cmd, int argc, char **argv); void dump_list_of_commands_and_exit(void); int read_command(char *buf, int buf_size); void dump_coverage_files(void); void show_common_help_intro(void); const char *get_devshell_path(void); void print_waitpid_change(int child, int wstatus); void forced_memcpy(void *dest, const void *src, size_t n); void do_mm_read(void *ptr); void do_cmd_exit(int code); bool is_stack_aligned_16(void); void execute_illegal_instruction(void); size_t mm_estimate_usable_mem(void); /* From the man page of getdents64() */ struct linux_dirent64 { u64 d_ino; /* 64-bit inode number */ u64 d_off; /* 64-bit offset to next structure */ unsigned short d_reclen; /* Size of this dirent */ unsigned char d_type; /* File type */ char d_name[]; /* Filename (null-terminated) */ }; static inline int getdents64(unsigned fd, struct linux_dirent64 *dirp, unsigned count) { return sysenter_call3(220, fd, dirp, count); } static inline int tilck_get_num_gcov_files(void) { return sysenter_call1(TILCK_CMD_SYSCALL, TILCK_CMD_GCOV_GET_NUM_FILES); } static inline int tilck_get_gcov_file_info(int fn, char *fname, unsigned fname_size, unsigned *fsize) { return sysenter_call5(TILCK_CMD_SYSCALL, TILCK_CMD_GCOV_FILE_INFO, fn, fname, fname_size, fsize); } static inline int tilck_get_gcov_file(int fn, char *buf) { return sysenter_call3(TILCK_CMD_SYSCALL, TILCK_CMD_GCOV_GET_FILE, fn, buf); } static inline int tilck_debug_qemu_poweroff(void) { return sysenter_call1(TILCK_CMD_SYSCALL, TILCK_CMD_QEMU_POWEROFF); } static inline int tilck_set_sched_alive_thread_enabled(bool enabled) { return sysenter_call2(TILCK_CMD_SYSCALL, TILCK_CMD_SET_SAT_ENABLED, enabled); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/page_size.h> #include <tilck/kernel/hal_types.h> #ifdef __i386__ #define PAGE_DIR_SIZE (PAGE_SIZE) #endif #define OFFSET_IN_PAGE_MASK (PAGE_SIZE - 1) #define PAGE_MASK (~OFFSET_IN_PAGE_MASK) #define IS_PAGE_ALIGNED(x) (!((ulong)x & OFFSET_IN_PAGE_MASK)) #define IS_PTR_ALIGNED(x) (!((ulong)x & (sizeof(ulong)-1))) #define INVALID_PADDR ((ulong)-1) /* Paging flags (pg_flags) */ #define PAGING_FL_RW (1 << 0) #define PAGING_FL_US (1 << 1) #define PAGING_FL_BIG_PAGES_ALLOWED (1 << 2) #define PAGING_FL_SHARED (1 << 3) #define PAGING_FL_DO_ALLOC (1 << 4) #define PAGING_FL_ZERO_PG (1 << 5) /* Combo values */ #define PAGING_FL_RWUS (PAGING_FL_RW | PAGING_FL_US) /* * These MACROs can be used for the linear mapping region in the kernel space. */ #define KERNEL_PA_TO_VA(pa) ((void *) ((ulong)(pa) + KERNEL_BASE_VA)) #define KERNEL_VA_TO_PA(va) ((ulong)(va) - KERNEL_BASE_VA) extern char page_size_buf[PAGE_SIZE] ALIGNED_AT(PAGE_SIZE); extern char zero_page[PAGE_SIZE] ALIGNED_AT(PAGE_SIZE); void early_init_paging(); bool handle_potential_cow(void *r); /* * Map a pageframe at `paddr` at the virtual address `vaddr` in the page * directory `pdir`, using the arch-independent `pg_flags`. This last param * is made by ORing the flags defined above such as PAGING_FL_RO etc. */ NODISCARD int map_page(pdir_t *pdir, void *vaddr, ulong paddr, u32 pg_flags); NODISCARD int map_page_int(pdir_t *pdir, void *vaddr, ulong paddr, u32 hw_flags); NODISCARD int map_zero_page(pdir_t *pdir, void *vaddrp, u32 pg_flags); NODISCARD size_t map_pages(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, u32 pg_flags); NODISCARD size_t map_pages_int(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, bool big_pages_allowed, u32 hw_flags); NODISCARD size_t map_zero_pages(pdir_t *pdir, void *vaddrp, size_t page_count, u32 pg_flags); void init_paging(void); bool is_mapped(pdir_t *pdir, void *vaddr); bool is_rw_mapped(pdir_t *pdir, void *vaddrp); void unmap_page(pdir_t *pdir, void *vaddr, bool do_free); int unmap_page_permissive(pdir_t *pdir, void *vaddrp, bool do_free); void unmap_pages(pdir_t *pdir, void *vaddr, size_t count, bool do_free); size_t unmap_pages_permissive(pdir_t *pd, void *va, size_t count, bool do_free); ulong get_mapping(pdir_t *pdir, void *vaddr); int get_mapping2(pdir_t *pdir, void *vaddrp, ulong *pa_ref); pdir_t *pdir_clone(pdir_t *pdir); pdir_t *pdir_deep_clone(pdir_t *pdir); void pdir_destroy(pdir_t *pdir); void invalidate_page(ulong vaddr); void set_page_rw(pdir_t *pdir, void *vaddr, bool rw); void retain_pageframes_mapped_at(pdir_t *pdir, void *vaddr, size_t len); void release_pageframes_mapped_at(pdir_t *pdir, void *vaddr, size_t len); static ALWAYS_INLINE pdir_t *get_kernel_pdir(void) { extern pdir_t *__kernel_pdir; return __kernel_pdir; } NODISCARD static ALWAYS_INLINE int map_kernel_page(void *vaddr, ulong paddr, u32 pg_flags) { extern pdir_t *__kernel_pdir; return map_page(__kernel_pdir, vaddr, paddr, pg_flags); } static ALWAYS_INLINE void unmap_kernel_page(void *vaddr, bool do_free) { extern pdir_t *__kernel_pdir; unmap_page(__kernel_pdir, vaddr, do_free); } NODISCARD static ALWAYS_INLINE size_t map_kernel_pages(void *vaddr, ulong paddr, size_t page_count, u32 pg_flags) { extern pdir_t *__kernel_pdir; return map_pages(__kernel_pdir, vaddr, paddr, page_count, pg_flags); } static ALWAYS_INLINE void unmap_kernel_pages(void *vaddr, size_t count, bool do_free) { extern pdir_t *__kernel_pdir; unmap_pages(__kernel_pdir, vaddr, count, do_free); } void * map_framebuffer(pdir_t *pdir, ulong paddr, ulong vaddr, ulong size, bool user_mmap); void set_pages_pat_wc(pdir_t *pdir, void *vaddr, size_t size); /* * Reserve anywhere in the hi virtual mem area (from LINEAR_MAPPING_END to * +4 GB on 32-bit systems) a block. Note: no actual mapping is done here, * just virtual memory is reserved in order to avoid conflicts between multiple * sub-systems trying reserve some virtual space here. * * Callers are expected to do the actual mapping of the virtual memory area * returned (if not NULL) to an actual physical address. */ void *hi_vmem_reserve(size_t size); /* * Counter-part of hi_vmem_reserve(). * * As above: this function *does not* do any kind of ummap. It's all up to the * callers. The function just releases the allocated block in the virtual space. */ void hi_vmem_release(void *ptr, size_t size); /* Returns true if the hi_vmem_heap has been initialized */ bool hi_vmem_avail(void); int virtual_read(pdir_t *pdir, void *extern_va, void *dest, size_t len); int virtual_write(pdir_t *pdir, void *extern_va, void *src, size_t len); static ALWAYS_INLINE void debug_checked_virtual_read(pdir_t *pdir, void *ext_va, void *dest, size_t len) { DEBUG_ONLY_UNSAFE(int rc =) virtual_read(pdir, ext_va, dest, len); ASSERT((size_t)rc == len); } static ALWAYS_INLINE void debug_checked_virtual_write(pdir_t *pdir, void *ext_va, void *src, size_t len) { DEBUG_ONLY_UNSAFE(int rc =) virtual_write(pdir, ext_va, src, len); ASSERT((size_t)rc == len); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/atomics.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/process.h> #include <tilck/kernel/term.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/system_mmap.h> volatile bool __in_panic; volatile bool __in_double_fault; volatile bool __in_kernel_shutdown; volatile bool __in_panic_debugger; void init_console(void); /* defined in main.c */ void panic_save_current_state(); /* defined in kernel_yield.S */ regs_t panic_state_regs; /* Called by the assembly function panic_save_current_state() */ void panic_save_current_task_state(regs_t *r) { /* * Clear the higher (unused) bits of the segment registers for a nicer * panic regs_t dump. */ #if NBITS == 32 r->ss &= 0xffff; r->cs &= 0xffff; r->ds &= 0xffff; r->es &= 0xffff; r->fs &= 0xffff; r->gs &= 0xffff; #else // TODO: add code here #endif /* * Since in panic we need just to save the state without doing a context * switch, just saving the ESP in state_regs won't work, because * we'll going to continue using the same stack. In this particular corner * case, just store the regs in a static regs_t instance. */ memcpy(&panic_state_regs, r, sizeof(regs_t)); struct task *curr = get_curr_task(); if (curr) curr->state_regs = &panic_state_regs; } static void disable_fpu_features(void) { x86_cpu_features.can_use_sse = false; x86_cpu_features.can_use_sse2 = false; x86_cpu_features.can_use_avx = false; x86_cpu_features.can_use_avx2 = false; } static void panic_print_task_info(struct task *curr) { const char *str; if (curr && curr != kernel_process && curr->tid != -1) { if (!is_kernel_thread(curr)) { printk("Current task [USER]: tid: %i, pid: %i\n", curr->tid, curr->pi->pid); } else { str = curr->kthread_name; printk("Current task [KERNEL]: tid: %i [%s]\n", curr->tid, str ? str : "???"); } } else { printk("Current task: NONE\n"); } } static int stop_all_other_tasks(void *task, void *unused) { struct task *ti = task; if (ti != get_curr_task()) { ti->stopped = true; } return 0; } NORETURN void panic(const char *fmt, ...) { static bool first_printk_ok; static bool first_in_panic_double_fault; static const char *saved_fmt; static va_list saved_args; ulong rc; va_list args; struct task *curr; bool panic_triggered_df = false; if (!kopt_panic_kb) { /* No interrupts: we're in a panic state */ disable_interrupts_forced(); } else { /* * While it's a good idea to disable ALL the interrupts during panic(), * sometimes the panic code path does not affect screen scrolling nor * the console, nor the PS/2 driver. Therefore, in those cases, it's * great to reproduce the bug and being able to scroll. * * Therefore, let's mask all the IRQs except the IRQ for the PS/2 * keyboard. */ int keep = kopt_sercon ? X86_PC_COM1_COM3_IRQ : X86_PC_KEYBOARD_IRQ; disable_interrupts_forced(); for (int irq = 0; irq < 16; irq++) { if (irq != keep) irq_set_mask(irq); } disable_preemption(); iterate_over_tasks(&stop_all_other_tasks, NULL); enable_interrupts_forced(); } force_enable_preemption(); /* Set a predefined and sane state */ if (__in_panic) { /* Ouch, nested panic! */ if (!__in_double_fault || first_in_panic_double_fault) { /* * If we're NOT in double fault or we're in a double fault occurred * BEFORE the first call to panic(), we're in a pathologic panic loop * and there's nothing more we can do. */ if (first_printk_ok) printk("[panic] Got panic while in panic state. Halt.\n"); goto end; } /* * In this case we're in double fault caused by panic() itself because of * stack overflow. Since the double fault handler uses a separate stack, * we can continue. */ panic_triggered_df = true; } __in_panic = true; first_in_panic_double_fault = __in_double_fault; va_start(args, fmt); if (!saved_fmt) { saved_fmt = fmt; va_copy(saved_args, args); } disable_fpu_features(); if (!__in_double_fault) panic_save_current_state(); curr = get_curr_task(); if (term_is_initialized()) { if (get_curr_tty() != NULL) tty_setup_for_panic(get_curr_tty()); /* In case the video output has been paused, we MUST restart it */ term_restart_output(); } else { init_console(); } /* Hopefully, we can show something on the screen */ printk("\n********************** KERNEL PANIC **********************\n"); /* * Register the fact that the first printk() succeeded: in case of panic * in panic, at least we know that we can show something on the screen. */ first_printk_ok = true; /* print the arguments in a fault-safe way */ rc = fault_resumable_call(ALL_FAULTS_MASK, vprintk, 2, fmt, args); if (rc != 0) { printk("[panic] Got fault %d while trying to print " "the panic message.", get_fault_num(rc)); } va_end(args); printk("\n"); if (panic_triggered_df) { printk("[panic] The double fault occurred in panic (stack overflow)\n"); printk("[panic] Original panic message: <<\n"); /* print the arguments in a fault-safe way */ rc = fault_resumable_call(ALL_FAULTS_MASK, vprintk, 2, saved_fmt, saved_args); if (rc != 0) { printk("[panic] Got fault %d while trying to print " "the panic message.", get_fault_num(rc)); } printk(">>\n"); } panic_print_task_info(curr); panic_dump_nested_interrupts(); if (__in_double_fault) { copy_main_tss_on_regs(&panic_state_regs); if (!kopt_panic_regs) printk("SP: %p\n", regs_get_stack_ptr(&panic_state_regs)); } if (kopt_panic_regs) dump_regs(&panic_state_regs); if (!kopt_panic_nobt) { dump_stacktrace( __in_double_fault ? regs_get_frame_ptr(&panic_state_regs) : NULL, curr->pi->pdir ); } if (kopt_panic_mmap) dump_memory_map(); if (DEBUG_QEMU_EXIT_ON_PANIC) debug_qemu_turn_off_machine(); if (kopt_panic_kb) { __in_panic_debugger = true; sys_tilck_cmd(TILCK_CMD_DEBUGGER_TOOL, 0, 0, 0, 0); } end: /* Halt the CPU forever */ disable_interrupts_forced(); while (true) { halt(); } } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) if (EXISTS ${TCROOT}/${ARCH}/vim) set(EXTRA_VIM OFF CACHE BOOL "Load the real VIM in Tilck") message(STATUS "EXTRA_VIM: ${EXTRA_VIM}") endif() if (EXISTS ${TCROOT}/${ARCH}/tcc) set(EXTRA_TCC OFF CACHE BOOL "Load the TinyCC compiler in Tilck") message(STATUS "EXTRA_TCC: ${EXTRA_TCC}") endif() if (EXISTS ${TCROOT}/${ARCH}/fbDOOM) set(EXTRA_FBDOOM OFF CACHE BOOL "Load fbDOOM in Tilck") message(STATUS "EXTRA_FBDOOM: ${EXTRA_FBDOOM}") endif() if (EXISTS ${TCROOT}/${ARCH}/micropython) set(EXTRA_MICROPYTHON OFF CACHE BOOL "Load micropython in Tilck") message(STATUS "EXTRA_MICROPYTHON: ${EXTRA_MICROPYTHON}") endif() if (EXISTS ${TCROOT}/${ARCH}/tree_cmd) set(EXTRA_TREE_CMD OFF CACHE BOOL "Load the tree command Tilck") message(STATUS "EXTRA_TREE_CMD: ${EXTRA_TREE_CMD}") endif() if (EXISTS ${TCROOT}/${ARCH}/lua) set(EXTRA_LUA OFF CACHE BOOL "Load LUA in Tilck") message(STATUS "EXTRA_LUA: ${EXTRA_LUA}") endif() if (EXTRA_VIM) set(EXTRA_VIM_ENABLED "1") endif() if (EXTRA_TCC) set(msg "") string(CONCAT msg "The TinyCC compiler works on Tilck, but can be used " "only for generatic static binaries, as the kernel does " "not support dynamic linking, at the moment.") message(WARNING "${msg}") set(EXTRA_TCC_ENABLED "1") endif() if (EXTRA_FBDOOM) set(EXTRA_FBDOOM_ENABLED "1") endif() if (EXTRA_MICROPYTHON) set(EXTRA_MICROPYTHON_ENABLED "1") endif() if (EXTRA_TREE_CMD) set(EXTRA_TREE_CMD_ENABLED "1") endif() if (EXTRA_LUA) set(EXTRA_LUA_ENABLED "1") endif() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * List with all the system tests (shellcmds). DO NOT INCLUDE THIS FILE! * This is a PRIVATE header for cmds_table.c. To list all of the tests, * access the `cmds_table` array. Example: see userapps/devshell/commands.c. */ /* name, timeout, enabled */ CMD_ENTRY(help, TT_SHORT, false) CMD_ENTRY(selftest, TT_LONG, false) CMD_ENTRY(runall, TT_LONG, false) CMD_ENTRY(loop, TT_MED, false) CMD_ENTRY(fpu_loop, TT_LONG, false) CMD_ENTRY(fork0, TT_MED, true) CMD_ENTRY(fork1, TT_SHORT, true) CMD_ENTRY(sysenter, TT_SHORT, true) CMD_ENTRY(fork_se, TT_MED, true) CMD_ENTRY(bad_read, TT_SHORT, true) CMD_ENTRY(bad_write, TT_SHORT, true) CMD_ENTRY(fork_perf, TT_LONG, true) CMD_ENTRY(vfork_perf, TT_LONG, true) CMD_ENTRY(syscall_perf, TT_MED, true) CMD_ENTRY(fpu, TT_SHORT, true) CMD_ENTRY(brk, TT_SHORT, true) CMD_ENTRY(mmap, TT_MED, true) CMD_ENTRY(mmap2, TT_SHORT, true) CMD_ENTRY(kcow, TT_SHORT, true) CMD_ENTRY(wpid1, TT_SHORT, true) CMD_ENTRY(wpid2, TT_SHORT, true) CMD_ENTRY(wpid3, TT_SHORT, true) CMD_ENTRY(wpid4, TT_SHORT, true) CMD_ENTRY(wpid5, TT_SHORT, true) CMD_ENTRY(wpid6, TT_SHORT, true) CMD_ENTRY(sigsegv0, TT_SHORT, true) CMD_ENTRY(sigsegv1, TT_SHORT, true) CMD_ENTRY(sigsegv2, TT_SHORT, true) CMD_ENTRY(sigill, TT_SHORT, true) CMD_ENTRY(sigfpe, TT_SHORT, true) CMD_ENTRY(sigabrt, TT_SHORT, true) CMD_ENTRY(sig_ignore, TT_SHORT, true) CMD_ENTRY(bigargv, TT_SHORT, true) CMD_ENTRY(cloexec, TT_SHORT, true) CMD_ENTRY(fs1, TT_SHORT, true) CMD_ENTRY(fs2, TT_SHORT, true) CMD_ENTRY(fs3, TT_SHORT, true) CMD_ENTRY(fs4, TT_SHORT, true) CMD_ENTRY(fs5, TT_SHORT, true) CMD_ENTRY(fs6, TT_SHORT, true) CMD_ENTRY(fs7, TT_SHORT, true) CMD_ENTRY(fs_perf1, TT_SHORT, true) CMD_ENTRY(fs_perf2, TT_SHORT, true) CMD_ENTRY(fmmap1, TT_SHORT, true) CMD_ENTRY(fmmap2, TT_SHORT, true) CMD_ENTRY(fmmap3, TT_SHORT, true) CMD_ENTRY(fmmap4, TT_SHORT, true) CMD_ENTRY(fmmap5, TT_SHORT, true) CMD_ENTRY(fmmap6, TT_SHORT, true) CMD_ENTRY(fmmap7, TT_SHORT, true) CMD_ENTRY(pipe1, TT_SHORT, true) CMD_ENTRY(pipe2, TT_SHORT, true) CMD_ENTRY(pipe3, TT_SHORT, true) CMD_ENTRY(pipe4, TT_SHORT, true) CMD_ENTRY(pipe5, TT_SHORT, true) CMD_ENTRY(pollerr, TT_SHORT, true) CMD_ENTRY(pollhup, TT_SHORT, true) CMD_ENTRY(poll1, TT_SHORT, true) CMD_ENTRY(poll2, TT_SHORT, true) CMD_ENTRY(poll3, TT_SHORT, true) CMD_ENTRY(select1, TT_SHORT, true) CMD_ENTRY(select2, TT_SHORT, true) CMD_ENTRY(select3, TT_SHORT, true) CMD_ENTRY(select4, TT_SHORT, true) CMD_ENTRY(execve0, TT_SHORT, true) CMD_ENTRY(vfork0, TT_SHORT, true) CMD_ENTRY(extra, TT_MED, true) CMD_ENTRY(fatmm1, TT_SHORT, true) CMD_ENTRY(sigmask, TT_SHORT, true) CMD_ENTRY(sig1, TT_SHORT, true) CMD_ENTRY(sig2, TT_SHORT, true) CMD_ENTRY(sig3, TT_SHORT, true) CMD_ENTRY(sig4, TT_SHORT, true) CMD_ENTRY(sig5, TT_SHORT, true) CMD_ENTRY(sig6, TT_SHORT, true) CMD_ENTRY(sig7, TT_SHORT, true) CMD_ENTRY(sig8, TT_SHORT, true) CMD_ENTRY(sig9, TT_SHORT, true) CMD_ENTRY(sig10, TT_SHORT, true) CMD_ENTRY(sig11, TT_SHORT, true) CMD_ENTRY(sig12, TT_SHORT, true) CMD_ENTRY(sig13, TT_SHORT, true) CMD_ENTRY(fork_oom, TT_MED, true) CMD_ENTRY(sigsegv3, TT_SHORT, true) CMD_ENTRY(sigsegv4, TT_SHORT, true) CMD_ENTRY(sigsegv5, TT_SHORT, true) CMD_ENTRY(getuids, TT_SHORT, true) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/mod_console.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/ringbuf.h> #include <tilck/kernel/term.h> #include <tilck/kernel/sync.h> #include <termios.h> // system header #include <linux/kd.h> // system header struct tty; typedef bool (*tty_ctrl_sig_func)(struct tty *, bool); void tty_reset_filter_ctx(struct tty *t); void tty_inbuf_reset(struct tty *t); struct tty { term *tstate; const struct term_interface *tintf; struct term_params tparams; void *console_data; void *devfile; char dev_filename[16]; int minor; int fg_pgid; struct ringbuf input_ringbuf; struct kcond input_cond; /* signal when we can read from input_rb */ struct kcond output_cond; /* signal when we can write to input_rb */ int end_line_delim_count; bool mediumraw_mode; u8 curr_color; u16 serial_port_fwd; char *input_buf; u32 kd_gfx_mode; tty_ctrl_sig_func *ctrl_handlers; struct termios c_term; }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mocking.h" using namespace testing; extern "C" { #include <tilck/kernel/test/tracing.h> } class tracing_mock : public KernelSingleton { public: MOCK_METHOD(int, handle_sys_trace_arg, (const char *arg), (override)); }; TEST(simple_wildcard_match, basic) { ASSERT_TRUE(simple_wildcard_match("test string", "test string")); ASSERT_TRUE(simple_wildcard_match("test string", "test string*")); ASSERT_TRUE(simple_wildcard_match("test string", "tes? string")); ASSERT_TRUE(simple_wildcard_match("test string", "test *")); ASSERT_FALSE(simple_wildcard_match("test string", "?")); ASSERT_FALSE(simple_wildcard_match("test string", "test strin1")); ASSERT_FALSE(simple_wildcard_match("test string", "te*t")); ASSERT_FALSE(simple_wildcard_match("test string", "test string1")); ASSERT_TRUE(simple_wildcard_match("", "")); } TEST(simple_wildcard_match, questionmark) { ASSERT_TRUE(simple_wildcard_match("abc", "a?c")); ASSERT_TRUE(simple_wildcard_match("abc", "??c")); ASSERT_FALSE(simple_wildcard_match("abc", "abc?")); ASSERT_TRUE(simple_wildcard_match("a,c", "a?c")); ASSERT_FALSE(simple_wildcard_match("abc", "abc??")); ASSERT_FALSE(simple_wildcard_match("abc", "?")); ASSERT_FALSE(simple_wildcard_match("abc", "?")); ASSERT_FALSE(simple_wildcard_match("abc", "??")); ASSERT_TRUE(simple_wildcard_match("abc", "???")); ASSERT_FALSE(simple_wildcard_match("abc", "????")); ASSERT_FALSE(simple_wildcard_match("", "?")); } TEST(simple_wildcard_match, star) { ASSERT_TRUE(simple_wildcard_match("abc", "*")); ASSERT_TRUE(simple_wildcard_match("abc", "ab*")); ASSERT_TRUE(simple_wildcard_match("abc", "a*")); ASSERT_TRUE(simple_wildcard_match("abc", "abc*")); ASSERT_FALSE(simple_wildcard_match("abc", "*b")); ASSERT_FALSE(simple_wildcard_match("abc", "*abc")); ASSERT_TRUE(simple_wildcard_match("", "*")); ASSERT_FALSE(simple_wildcard_match("", "**")); ASSERT_FALSE(simple_wildcard_match("ab", "**")); } TEST(set_traced_syscalls_int, basic) { tracing_mock mock; char tracing_str[TRACED_SYSCALLS_STR_LEN+1]; bool traced_syscalls_mock[MAX_SYSCALLS] = {1}; memset((void *) tracing_str, 'a', TRACED_SYSCALLS_STR_LEN); tracing_str[TRACED_SYSCALLS_STR_LEN] = '\0'; traced_syscalls = traced_syscalls_mock; traced_syscalls_str = tracing_str; ASSERT_EQ(set_traced_syscalls_int(tracing_str), -ENAMETOOLONG); tracing_str[TRACED_SYSCALLS_STR_LEN-1] = '\0'; ASSERT_EQ(set_traced_syscalls_int(tracing_str), -ENAMETOOLONG); EXPECT_CALL(mock, handle_sys_trace_arg(_)) .WillOnce(Return(1)); ASSERT_EQ(set_traced_syscalls_int(",,,"), 1); EXPECT_CALL(mock, handle_sys_trace_arg(_)) .WillOnce(Return(1)); ASSERT_EQ(set_traced_syscalls_int("abc"), 1); EXPECT_CALL(mock, handle_sys_trace_arg(_)) .WillOnce(Return(0)); ASSERT_EQ(set_traced_syscalls_int("abc"), 0); EXPECT_CALL(mock, handle_sys_trace_arg(_)) .WillRepeatedly(Return(0)); ASSERT_EQ(set_traced_syscalls_int("a, b, c"), 0); traced_syscalls = NULL; traced_syscalls_str = NULL; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck_gen_headers/config_debug.h> #define __TILCK_ATOMICS__ #ifndef __cplusplus #if defined(UNIT_TEST_ENVIRONMENT) && \ !defined(__clang__) && \ defined(__GNUC__) && \ __GNUC__ <= 4 && \ __GNUC_MINOR__ <= 8 /* * This is NOT a real kernel build, it's OK to use the fake atomics for * unit tests if the compiler is too old and does not support C11 atomics. */ #include <tilck/common/fake_atomics.h> #else /* DEFAULT case: the Tilck kernel, compiled with a modern C compiler. */ #include <stdatomic.h> // system header STATIC_ASSERT(ATOMIC_BOOL_LOCK_FREE == 2); STATIC_ASSERT(ATOMIC_CHAR_LOCK_FREE == 2); STATIC_ASSERT(ATOMIC_SHORT_LOCK_FREE == 2); STATIC_ASSERT(ATOMIC_INT_LOCK_FREE == 2); STATIC_ASSERT(ATOMIC_LONG_LOCK_FREE == 2); STATIC_ASSERT(ATOMIC_POINTER_LOCK_FREE == 2); #define ATOMIC(x) _Atomic(x) /* Convenience macros */ #define mo_relaxed memory_order_relaxed #define mo_consume memory_order_consume #define mo_acquire memory_order_acquire #define mo_release memory_order_release #define mo_acq_rel memory_order_acq_rel #define mo_seq_cst memory_order_seq_cst #endif // #if defined(UNIT_TEST_ENVIRONMENT) && ... #else #if KERNEL_FORCE_TC_ISYSTEM /* * This is NOT a real kernel build. It's a static analysis build only. * It's OK to use the fake atomics to make the build pass. */ #include <tilck/common/fake_atomics.h> #else /* * If __cplusplus is defined, we're likely in a extern "C" { } context * here. In order to include C++11's atomic header, we have to put it in * an extern "C++" { } block, because templates cannot have "C" linkage. */ extern "C++" { #include <atomic> } #define ATOMIC(x) std::atomic<x> #define mo_relaxed std::memory_order_relaxed #define mo_consume std::memory_order_consume #define mo_acquire std::memory_order_acquire #define mo_release std::memory_order_release #define mo_acq_rel std::memory_order_acq_rel #define mo_seq_cst std::memory_order_seq_cst #endif // #if KERNEL_FORCE_TC_ISYSTEM #endif // #ifndef __cplusplus /* ---- Convenience macros ---- */ #define atomic_cas_weak(p, ep, nv, m1, m2) \ atomic_compare_exchange_weak_explicit((p), (ep), (nv), (m1), (m2)) #define atomic_cas_strong(p, ep, nv, m1, m2) \ atomic_compare_exchange_strong_explicit((p), (ep), (nv), (m1), (m2)) /* ---- Basic reference counting ---- */ #define REF_COUNTED_OBJECT int ref_count #if !SLOW_DEBUG_REF_COUNT /* Return the new value */ static ALWAYS_INLINE int __retain_obj(int *ref_count) { ATOMIC(int) *atomic = (ATOMIC(int) *)ref_count; return atomic_fetch_add_explicit(atomic, 1, mo_relaxed) + 1; } /* Return the new value */ static ALWAYS_INLINE int __release_obj(int *ref_count) { int old; ATOMIC(int) *atomic = (ATOMIC(int) *)ref_count; old = atomic_fetch_sub_explicit(atomic, 1, mo_relaxed); ASSERT(old > 0); return old - 1; } #else int __retain_obj(int *ref_count); int __release_obj(int *ref_count); #endif static ALWAYS_INLINE int __get_ref_count(int *ref_count) { ATOMIC(int) *atomic = (ATOMIC(int) *)ref_count; return atomic_load_explicit(atomic, mo_relaxed); } #define retain_obj(p) (__retain_obj(&(p)->ref_count)) #define release_obj(p) (__release_obj(&(p)->ref_count)) #define get_ref_count(p) (__get_ref_count(&(p)->ref_count)) <file_sep>/****************************************************************************** * * Name: acinterp.h - Interpreter subcomponent prototypes and defines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACINTERP_H__ #define __ACINTERP_H__ #define ACPI_WALK_OPERANDS (&(WalkState->Operands [WalkState->NumOperands -1])) /* Macros for tables used for debug output */ #define ACPI_EXD_OFFSET(f) (UINT8) ACPI_OFFSET (ACPI_OPERAND_OBJECT,f) #define ACPI_EXD_NSOFFSET(f) (UINT8) ACPI_OFFSET (ACPI_NAMESPACE_NODE,f) #define ACPI_EXD_TABLE_SIZE(name) (sizeof(name) / sizeof (ACPI_EXDUMP_INFO)) /* * If possible, pack the following structures to byte alignment, since we * don't care about performance for debug output. Two cases where we cannot * pack the structures: * * 1) Hardware does not support misaligned memory transfers * 2) Compiler does not support pointers within packed structures */ #if (!defined(ACPI_MISALIGNMENT_NOT_SUPPORTED) && !defined(ACPI_PACKED_POINTERS_NOT_SUPPORTED)) #pragma pack(1) #endif typedef const struct acpi_exdump_info { UINT8 Opcode; UINT8 Offset; const char *Name; } ACPI_EXDUMP_INFO; /* Values for the Opcode field above */ #define ACPI_EXD_INIT 0 #define ACPI_EXD_TYPE 1 #define ACPI_EXD_UINT8 2 #define ACPI_EXD_UINT16 3 #define ACPI_EXD_UINT32 4 #define ACPI_EXD_UINT64 5 #define ACPI_EXD_LITERAL 6 #define ACPI_EXD_POINTER 7 #define ACPI_EXD_ADDRESS 8 #define ACPI_EXD_STRING 9 #define ACPI_EXD_BUFFER 10 #define ACPI_EXD_PACKAGE 11 #define ACPI_EXD_FIELD 12 #define ACPI_EXD_REFERENCE 13 #define ACPI_EXD_LIST 14 /* Operand object list */ #define ACPI_EXD_HDLR_LIST 15 /* Address Handler list */ #define ACPI_EXD_RGN_LIST 16 /* Region list */ #define ACPI_EXD_NODE 17 /* Namespace Node */ /* restore default alignment */ #pragma pack() /* * exconvrt - object conversion */ ACPI_STATUS AcpiExConvertToInteger ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc, UINT32 ImplicitConversion); ACPI_STATUS AcpiExConvertToBuffer ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc); ACPI_STATUS AcpiExConvertToString ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc, UINT32 Type); /* Types for ->String conversion */ #define ACPI_EXPLICIT_BYTE_COPY 0x00000000 #define ACPI_EXPLICIT_CONVERT_HEX 0x00000001 #define ACPI_IMPLICIT_CONVERT_HEX 0x00000002 #define ACPI_EXPLICIT_CONVERT_DECIMAL 0x00000003 ACPI_STATUS AcpiExConvertToTargetType ( ACPI_OBJECT_TYPE DestinationType, ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT **ResultDesc, ACPI_WALK_STATE *WalkState); /* * exdebug - AML debug object */ void AcpiExDoDebugObject ( ACPI_OPERAND_OBJECT *SourceDesc, UINT32 Level, UINT32 Index); void AcpiExStartTraceMethod ( ACPI_NAMESPACE_NODE *MethodNode, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState); void AcpiExStopTraceMethod ( ACPI_NAMESPACE_NODE *MethodNode, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState); void AcpiExStartTraceOpcode ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState); void AcpiExStopTraceOpcode ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState); void AcpiExTracePoint ( ACPI_TRACE_EVENT_TYPE Type, BOOLEAN Begin, UINT8 *Aml, char *Pathname); /* * exfield - ACPI AML (p-code) execution - field manipulation */ ACPI_STATUS AcpiExGetProtocolBufferLength ( UINT32 ProtocolId, UINT32 *ReturnLength); ACPI_STATUS AcpiExCommonBufferSetup ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 BufferLength, UINT32 *DatumCount); ACPI_STATUS AcpiExWriteWithUpdateRule ( ACPI_OPERAND_OBJECT *ObjDesc, UINT64 Mask, UINT64 FieldValue, UINT32 FieldDatumByteOffset); void AcpiExGetBufferDatum( UINT64 *Datum, void *Buffer, UINT32 BufferLength, UINT32 ByteGranularity, UINT32 BufferOffset); void AcpiExSetBufferDatum ( UINT64 MergedDatum, void *Buffer, UINT32 BufferLength, UINT32 ByteGranularity, UINT32 BufferOffset); ACPI_STATUS AcpiExReadDataFromField ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **RetBufferDesc); ACPI_STATUS AcpiExWriteDataToField ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc); /* * exfldio - low level field I/O */ ACPI_STATUS AcpiExExtractFromField ( ACPI_OPERAND_OBJECT *ObjDesc, void *Buffer, UINT32 BufferLength); ACPI_STATUS AcpiExInsertIntoField ( ACPI_OPERAND_OBJECT *ObjDesc, void *Buffer, UINT32 BufferLength); ACPI_STATUS AcpiExAccessRegion ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 FieldDatumByteOffset, UINT64 *Value, UINT32 ReadWrite); /* * exmisc - misc support routines */ ACPI_STATUS AcpiExGetObjectReference ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ReturnDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExConcatTemplate ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *ObjDesc2, ACPI_OPERAND_OBJECT **ActualReturnDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExDoConcatenate ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *ObjDesc2, ACPI_OPERAND_OBJECT **ActualReturnDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExDoLogicalNumericOp ( UINT16 Opcode, UINT64 Integer0, UINT64 Integer1, BOOLEAN *LogicalResult); ACPI_STATUS AcpiExDoLogicalOp ( UINT16 Opcode, ACPI_OPERAND_OBJECT *Operand0, ACPI_OPERAND_OBJECT *Operand1, BOOLEAN *LogicalResult); UINT64 AcpiExDoMathOp ( UINT16 Opcode, UINT64 Operand0, UINT64 Operand1); ACPI_STATUS AcpiExCreateMutex ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreateProcessor ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreatePowerResource ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreateRegion ( UINT8 *AmlStart, UINT32 AmlLength, UINT8 RegionSpace, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreateEvent ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreateAlias ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExCreateMethod ( UINT8 *AmlStart, UINT32 AmlLength, ACPI_WALK_STATE *WalkState); /* * exconfig - dynamic table load/unload */ ACPI_STATUS AcpiExLoadOp ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *Target, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExLoadTableOp ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT **ReturnDesc); ACPI_STATUS AcpiExUnloadTable ( ACPI_OPERAND_OBJECT *DdbHandle); /* * exmutex - mutex support */ ACPI_STATUS AcpiExAcquireMutex ( ACPI_OPERAND_OBJECT *TimeDesc, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExAcquireMutexObject ( UINT16 Timeout, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_THREAD_ID ThreadId); ACPI_STATUS AcpiExReleaseMutex ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExReleaseMutexObject ( ACPI_OPERAND_OBJECT *ObjDesc); void AcpiExReleaseAllMutexes ( ACPI_THREAD_STATE *Thread); void AcpiExUnlinkMutex ( ACPI_OPERAND_OBJECT *ObjDesc); /* * exprep - ACPI AML execution - prep utilities */ ACPI_STATUS AcpiExPrepCommonFieldObject ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 FieldFlags, UINT8 FieldAttribute, UINT32 FieldBitPosition, UINT32 FieldBitLength); ACPI_STATUS AcpiExPrepFieldValue ( ACPI_CREATE_FIELD_INFO *Info); /* * exserial - FieldUnit support for serial address spaces */ ACPI_STATUS AcpiExReadSerialBus ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ReturnBuffer); ACPI_STATUS AcpiExWriteSerialBus ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ReturnBuffer); ACPI_STATUS AcpiExReadGpio ( ACPI_OPERAND_OBJECT *ObjDesc, void *Buffer); ACPI_STATUS AcpiExWriteGpio ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ReturnBuffer); /* * exsystem - Interface to OS services */ ACPI_STATUS AcpiExSystemDoNotifyOp ( ACPI_OPERAND_OBJECT *Value, ACPI_OPERAND_OBJECT *ObjDesc); ACPI_STATUS AcpiExSystemDoSleep( UINT64 Time); ACPI_STATUS AcpiExSystemDoStall ( UINT32 Time); ACPI_STATUS AcpiExSystemSignalEvent( ACPI_OPERAND_OBJECT *ObjDesc); ACPI_STATUS AcpiExSystemWaitEvent( ACPI_OPERAND_OBJECT *Time, ACPI_OPERAND_OBJECT *ObjDesc); ACPI_STATUS AcpiExSystemResetEvent( ACPI_OPERAND_OBJECT *ObjDesc); ACPI_STATUS AcpiExSystemWaitSemaphore ( ACPI_SEMAPHORE Semaphore, UINT16 Timeout); ACPI_STATUS AcpiExSystemWaitMutex ( ACPI_MUTEX Mutex, UINT16 Timeout); /* * exoparg1 - ACPI AML execution, 1 operand */ ACPI_STATUS AcpiExOpcode_0A_0T_1R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_1A_0T_0R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_1A_0T_1R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_1A_1T_1R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_1A_1T_0R ( ACPI_WALK_STATE *WalkState); /* * exoparg2 - ACPI AML execution, 2 operands */ ACPI_STATUS AcpiExOpcode_2A_0T_0R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_2A_0T_1R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_2A_1T_1R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_2A_2T_1R ( ACPI_WALK_STATE *WalkState); /* * exoparg3 - ACPI AML execution, 3 operands */ ACPI_STATUS AcpiExOpcode_3A_0T_0R ( ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExOpcode_3A_1T_1R ( ACPI_WALK_STATE *WalkState); /* * exoparg6 - ACPI AML execution, 6 operands */ ACPI_STATUS AcpiExOpcode_6A_0T_1R ( ACPI_WALK_STATE *WalkState); /* * exresolv - Object resolution and get value functions */ ACPI_STATUS AcpiExResolveToValue ( ACPI_OPERAND_OBJECT **StackPtr, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExResolveMultiple ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT *Operand, ACPI_OBJECT_TYPE *ReturnType, ACPI_OPERAND_OBJECT **ReturnDesc); /* * exresnte - resolve namespace node */ ACPI_STATUS AcpiExResolveNodeToValue ( ACPI_NAMESPACE_NODE **StackPtr, ACPI_WALK_STATE *WalkState); /* * exresop - resolve operand to value */ ACPI_STATUS AcpiExResolveOperands ( UINT16 Opcode, ACPI_OPERAND_OBJECT **StackPtr, ACPI_WALK_STATE *WalkState); /* * exdump - Interpreter debug output routines */ void AcpiExDumpOperand ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Depth); void AcpiExDumpOperands ( ACPI_OPERAND_OBJECT **Operands, const char *OpcodeName, UINT32 NumOpcodes); void AcpiExDumpObjectDescriptor ( ACPI_OPERAND_OBJECT *Object, UINT32 Flags); void AcpiExDumpNamespaceNode ( ACPI_NAMESPACE_NODE *Node, UINT32 Flags); /* * exnames - AML namestring support */ ACPI_STATUS AcpiExGetNameString ( ACPI_OBJECT_TYPE DataType, UINT8 *InAmlAddress, char **OutNameString, UINT32 *OutNameLength); /* * exstore - Object store support */ ACPI_STATUS AcpiExStore ( ACPI_OPERAND_OBJECT *ValDesc, ACPI_OPERAND_OBJECT *DestDesc, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExStoreObjectToNode ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_NAMESPACE_NODE *Node, ACPI_WALK_STATE *WalkState, UINT8 ImplicitConversion); /* * exstoren - resolve/store object */ ACPI_STATUS AcpiExResolveObject ( ACPI_OPERAND_OBJECT **SourceDescPtr, ACPI_OBJECT_TYPE TargetType, ACPI_WALK_STATE *WalkState); ACPI_STATUS AcpiExStoreObjectToObject ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *DestDesc, ACPI_OPERAND_OBJECT **NewDesc, ACPI_WALK_STATE *WalkState); /* * exstorob - store object - buffer/string */ ACPI_STATUS AcpiExStoreBufferToBuffer ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *TargetDesc); ACPI_STATUS AcpiExStoreStringToString ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *TargetDesc); /* * excopy - object copy */ ACPI_STATUS AcpiExCopyIntegerToIndexField ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *TargetDesc); ACPI_STATUS AcpiExCopyIntegerToBankField ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *TargetDesc); ACPI_STATUS AcpiExCopyDataToNamedField ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_NAMESPACE_NODE *Node); ACPI_STATUS AcpiExCopyIntegerToBufferField ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *TargetDesc); /* * exutils - interpreter/scanner utilities */ void AcpiExEnterInterpreter ( void); void AcpiExExitInterpreter ( void); BOOLEAN AcpiExTruncateFor32bitTable ( ACPI_OPERAND_OBJECT *ObjDesc); void AcpiExAcquireGlobalLock ( UINT32 Rule); void AcpiExReleaseGlobalLock ( UINT32 Rule); void AcpiExEisaIdToString ( char *Dest, UINT64 CompressedId); void AcpiExIntegerToString ( char *Dest, UINT64 Value); void AcpiExPciClsToString ( char *Dest, UINT8 ClassCode[3]); BOOLEAN AcpiIsValidSpaceId ( UINT8 SpaceId); /* * exregion - default OpRegion handlers */ ACPI_STATUS AcpiExSystemMemorySpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExSystemIoSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExPciConfigSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExCmosSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExPciBarSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExEmbeddedControllerSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExSmBusSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); ACPI_STATUS AcpiExDataTableSpaceHandler ( UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64 *Value, void *HandlerContext, void *RegionContext); #endif /* __INTERP_H__ */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <math.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <tilck/common/tilck_sound.h> static char opt_device[64] = "/dev/sb16"; static char opt_file[64]; static bool opt_test; static bool opt_file_passed; static u8 opt_test_short; static u8 opt_test_bits = 8; static u8 opt_test_channels = 1; static void show_help(void) { printf("syntax:\n"); printf(" play [-d device] --test [-b 8|16] [-ch 1|2] [-s]\n"); printf(" play [-d device] <WAVE FILE>\n"); } static void show_help_and_exit(void) { show_help(); exit(1); } static void parse_args(int argc, char **argv) { while (argc) { char *arg = argv[0]; if (!strcmp(arg, "-d")) { if (argc < 2) show_help_and_exit(); argc--; argv++; strncpy(opt_device, argv[0], sizeof(opt_device)-1); } else if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) { show_help_and_exit(); } else if (!strcmp(arg, "--test") || !strcmp(arg, "-t")) { opt_test = true; } else if (!strcmp(arg, "-s")) { if (!opt_test) show_help_and_exit(); opt_test_short = true; } else if (!strcmp(arg, "-b")) { if (!opt_test) show_help_and_exit(); if (argc < 2) show_help_and_exit(); argc--; argv++; int bits = atoi(argv[0]); if (bits != 8 && bits != 16) show_help_and_exit(); opt_test_bits = (u8)bits; } else if (!strcmp(arg, "-ch")) { if (!opt_test) show_help_and_exit(); if (argc < 2) show_help_and_exit(); argc--; argv++; int channels = atoi(argv[0]); if (channels != 1 && channels != 2) show_help_and_exit(); opt_test_channels = (u8)channels; } else { if (opt_test) show_help_and_exit(); opt_file_passed = true; strncpy(opt_file, argv[0], sizeof(opt_file)-1); break; } argc--; argv++; } if (!opt_test && !opt_file_passed) show_help_and_exit(); } static u32 time_to_samples(u32 rate, u32 time_ms) { if (time_ms == 0) return 0; return time_ms < 1000 ? 1000 * rate / (1000000 / time_ms) : rate * time_ms / 1000; } static void tone_ll(void *raw_buf, u32 rate, float freq, u32 start, u32 cnt, u8 bits, u8 channels, u8 channel_n) { const u32 u = (1 << (bits - 1)) - 1; const double volume = 0.75; const u32 end = start + cnt; s8 *buf8 = raw_buf; s16 *buf16 = raw_buf; s32 *buf32 = raw_buf; for (u32 i = start; i < end; i++) { double t = (double)(i - start) / ((double)rate / freq); int val = (int)(sin(t * 2.0 * M_PI) * volume * u); if (channels == 1) { if (bits == 8) buf8[i] = (u8)val; else buf16[i] = (u16)val; } else { if (bits == 8) { if (channel_n != 255) buf16[i] = ((u16)val << 8 * channel_n); else buf16[i] = ((u16)val | val << 8); } else { if (channel_n != 255) buf32[i] = ((u16)val << 16 * channel_n); else buf32[i] = ((u16)val | val << 16); } } } } static void tone(void *raw_buf, u32 rate, float freq, u32 start_ms, u32 duration_ms, u8 bits, u8 channels, u8 channel_n) { const u32 start = time_to_samples(rate, start_ms); const u32 cnt = time_to_samples(rate, duration_ms); tone_ll(raw_buf, rate, freq, start, cnt, bits, channels, channel_n); } static u32 gen_test_sound(void *buf, u32 max_samples, u8 bits, u8 channels, u32 rate) { const float freq = 326.0; u32 ms = 0; /* Fill the whole buffer with "mute" sound */ memset(buf, 0, max_samples * (bits >> 3) * channels); if (!opt_test_short) { tone(buf, rate, freq , ms, 1486, bits, channels, 0); ms += 1486; tone(buf, rate, freq/2, ms, 1486, bits, channels, 1); ms += 1486; } else { tone(buf, rate, freq , ms, 100, bits, channels, 0); ms += 100; } return time_to_samples(rate, ms); } static int test_sound(int devfd) { const u32 max_samples = 64 * KB; u32 tot_sz = max_samples * (opt_test_bits >> 3) * opt_test_channels; void *raw_buf = malloc(tot_sz); int rc, written = 0; if (!raw_buf) { printf("Out of memory\n"); return 1; } printf("Playing test sound: %u bits, %u channels at 22050 Hz\n", opt_test_bits, opt_test_channels); struct tilck_sound_params p = { .sample_rate = 22050, .bits = opt_test_bits, .channels = opt_test_channels, .sign = 1, }; tot_sz = gen_test_sound( raw_buf, max_samples, p.bits, p.channels, p.sample_rate ); tot_sz *= (opt_test_bits >> 3) * opt_test_channels; rc = ioctl(devfd, TILCK_IOCTL_SOUND_SETUP, &p); if (rc < 0) { printf("Sound device setup ioctl() failed: %s\n", strerror(errno)); return 1; } if (!opt_test_short) { do { rc = write(devfd, (char *)raw_buf + written, tot_sz - written); if (rc < 0) { printf("write() on sound device failed: %s\n", strerror(errno)); break; } written += rc; } while (written < tot_sz); } else { write(devfd, (char *)raw_buf, tot_sz); } free(raw_buf); return 0; } #define CHUNK_ID_RIFF 0x52494646 #define FORMAT_WAV 0x57415645 #define SUBCHUNK1_ID_FMT 0x666d7420 #define SUBCHUNK2_ID_DATA 0x64617461 #define AUDIO_FORMAT_PCM 0x00000001 struct wav_header { u32 ChunkID; u32 ChunkSize; u32 Format; u32 Subchunk1ID; u32 Subchunk1Size; u16 AudioFormat; u16 NumChannels; u32 SampleRate; u32 ByteRate; u16 BlockAlign; u16 BitsPerSample; u32 Subchunk2ID; u32 Subchunk2Size; }; static u32 be32(u32 x) { return ((x >> 24) & 0x000000ff) | ((x << 8) & 0x00ff0000) | ((x >> 8) & 0x0000ff00) | ((x << 24) & 0xff000000); } static int check_wav_header(struct wav_header *hdr) { if (be32(hdr->ChunkID) != CHUNK_ID_RIFF) { printf("Not a WAV file: wrong ChunkID\n"); return -1; } if (be32(hdr->Format) != FORMAT_WAV) { printf("Not a WAV file: wrong Format\n"); return -1; } if (be32(hdr->Subchunk1ID) != SUBCHUNK1_ID_FMT) { printf("Not a WAV file: wrong Subchunk1ID\n"); return -1; } if (be32(hdr->Subchunk2ID) != SUBCHUNK2_ID_DATA) { printf("Not a WAV file: wrongSubchunk2ID\n"); return -1; } if (hdr->AudioFormat != AUDIO_FORMAT_PCM || hdr->Subchunk1Size != 16) { printf("Audio format not supported\n"); return -1; } if (hdr->NumChannels != 1 && hdr->NumChannels != 2) { printf("Unsupported number of channels: %u\n", hdr->NumChannels); return -1; } if (hdr->BitsPerSample != 8 && hdr->BitsPerSample != 16) { printf("Unsupported bits per sample: %u\n", hdr->BitsPerSample); return -1; } if (hdr->ChunkSize - 36 > hdr->Subchunk2Size) { printf("Multiple subchunks in the WAV file are not supported\n"); return -1; } u32 exp_br = hdr->SampleRate * hdr->NumChannels * hdr->BitsPerSample / 8; if (hdr->ByteRate != exp_br) { printf("ByteRate %u != expected value %u\n", hdr->ByteRate, exp_br); return -1; } return 0; } static int play_wav_file(int devfd) { int fd = open(opt_file, O_RDONLY); u32 tot_read = 0, data_read; u32 last_sec = (u32) -1; struct wav_header hdr; u8 *buf = NULL; int rc = 0; if (fd < 0) { printf("Unable to open WAV file '%s': %s\n", opt_file, strerror(errno)); return 1; } rc = read(fd, &hdr, sizeof(hdr)); if (rc < sizeof(hdr)) { printf("Invalid file header\n"); goto out; } if ((rc = check_wav_header(&hdr)) < 0) goto out; printf("Playing file '%s'...\n", opt_file); printf("%u bits/sample, %u channels at %u Hz\n", hdr.BitsPerSample, hdr.NumChannels, hdr.SampleRate); buf = malloc(32 * KB); if (!buf) { printf("Out of memory\n"); rc = 1; goto out; } struct tilck_sound_params params = { .sample_rate = hdr.SampleRate, .bits = hdr.BitsPerSample, .channels = hdr.NumChannels, .sign = 1, }; rc = ioctl(devfd, TILCK_IOCTL_SOUND_SETUP, &params); if (rc < 0) { printf("Unable to setup sound device: %s\n", strerror(errno)); goto out; } do { const u32 sec = tot_read / hdr.ByteRate; const u32 tot_sec = hdr.Subchunk2Size / hdr.ByteRate; u32 written = 0; data_read = 0; if (sec != last_sec) { printf("\033[2K\033[G"); printf("Time: %02u:%02u / %02u:%02u", sec / 60, sec % 60, tot_sec / 60, tot_sec % 60); fflush(stdout); last_sec = sec; } /* Read 32 KB */ while ((rc = read(fd, buf + data_read, 32 * KB - data_read)) > 0) { data_read += rc; } if (rc < 0) { printf("\nread() on WAV file failed with: %s\n", strerror(errno)); goto out; } while (written < data_read) { rc = write(devfd, buf + written, data_read - written); if (rc < 0) { printf("\nwrite() on sound device failed: %s\n", strerror(errno)); goto out; } written += rc; } tot_read += data_read; } while (data_read == 32 * KB); printf("\n"); rc = 0; out: free(buf); close(fd); return !!rc; } static int do_run_cmd(int devfd) { if (opt_test) { return test_sound(devfd); } else if (opt_file_passed) { return play_wav_file(devfd); } show_help(); return 1; } static void show_sb16_message_warning(void) { printf("-------------------------- WARNING --------------------------\n"); printf("The regular QEMU GTK UI doesn't work well with the emulation\n"); printf("of the SoundBlaster 16 sound card: while the sound is playing\n"); printf("you'll observe the whole QEMU window freezing AND flicker\n"); printf("in the sound as well.\n\n"); printf("QEMU bug: https://bugs.launchpad.net/qemu/+bug/1873769\n"); printf("\n"); printf("Workarounds (alternatives):\n\n"); printf(" 1. Best: use virt-manager and create a Tilck VM with the sb16\n"); printf(" sound card. To do that it's necessary to manually edit\n"); printf(" the XML config for the sound device. Make it be:\n"); printf(" <sound model=\"sb16\"/>\n"); printf(" Note: in this case it's possible to use the framebuffer\n"); printf(" console while playing sound, without anything freezing.\n\n"); printf(" 2. Use an older QEMU like 2.11. As good as solution 1.\n\n"); printf(" 3. Run QEMU with -curses and boot in text mode (some flicker,\n"); printf(" but no freezing).\n\n"); printf(" 4. Run QEMU in nographic mode (as solution 3):\n"); printf(" ./build/run_multiboot_qemu -nographic -append -sercon\n"); printf("-------------------------------------------------------------\n"); } int main(int argc, char **argv) { int rc, cmd_rc, devfd; struct tilck_sound_card_info nfo; parse_args(argc-1, argv+1); /* Initialization */ devfd = open(opt_device, O_WRONLY); if (devfd < 0) { printf("Failed to open device: %s\n", opt_device); return 1; } rc = ioctl(devfd, TILCK_IOCTL_SOUND_ACQUIRE, NULL); if (rc < 0) { printf("Failed to acquire the sound device\n"); return 1; } rc = ioctl(devfd, TILCK_IOCTL_SOUND_GET_INFO, &nfo); if (rc < 0) { printf("Failed to get info for the sound device\n"); return 1; } if (!strcmp(nfo.name, "sb16")) { /* QEMU >= 4.0 has a nasty bug affecting this sound card */ show_sb16_message_warning(); /* Give QEMU some time to refresh the video, before start playing */ usleep(200 * 1000); } /* Run the main program logic */ cmd_rc = do_run_cmd(devfd); /* Finalization */ rc = ioctl(devfd, TILCK_IOCTL_SOUND_WAIT_COMPLETION, NULL); if (rc < 0) { printf("Failed to wait for completion\n"); return 1; } rc = ioctl(devfd, TILCK_IOCTL_SOUND_RELEASE, NULL); if (rc < 0) { printf("Failed to release the sound device\n"); return 1; } close(devfd); return cmd_rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_kb8042.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/list.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/safe_ringbuf.h> #include <tilck/mods/acpi.h> #include "i8042.h" #include "kb_layouts.c.h" #include "kb_ansi_seq.c.h" enum kb_state { KB_DEFAULT_STATE = 0, KB_READ_E0_SCANCODE_STATE, KB_READ_E1_SCANCODE_STATE, KB_READ_FIRST_SCANCODE_AFTER_E1_STATE, }; static struct worker_thread *kb_worker_thread; static enum kb_state kb_curr_state; static bool key_pressed_state[2][128]; static bool numLock; static bool capsLock; static struct list keypress_handlers = STATIC_LIST_INIT(keypress_handlers); static struct kb_dev ps2_keyboard; static struct safe_ringbuf kb_input_rb; static bool kb_is_pressed(u32 key) { bool e0 = (key >> 8) == 0xE0; return key_pressed_state[e0][key & 0xFF]; } static inline void kb_led_update(void) { kb_led_set((u8)(capsLock << 2 | numLock << 1)); } static char translate_printable_key(u32 key) { if (key >= 256) { switch (key) { case KEY_NUMPAD_ENTER: return '\r'; case KEY_NUMPAD_SLASH: return '/'; default: return 0; } } char *layout = us_kb_layouts[kb_is_pressed(KEY_L_SHIFT) || kb_is_pressed(KEY_R_SHIFT)]; char c = layout[key]; if (numLock) c |= numkey[key]; if (capsLock) c = (char)toupper(c); return c; } static void kb_register_keypress_handler(struct keypress_handler_elem *e) { list_add_tail(&keypress_handlers, &e->node); } static int kb_call_keypress_handlers(struct key_event ke) { int count = 0; struct keypress_handler_elem *pos; list_for_each_ro(pos, &keypress_handlers, node) { enum kb_handler_action a = pos->handler(&ps2_keyboard, ke); switch (a) { case kb_handler_ok_and_stop: count++; return count; case kb_handler_ok_and_continue: count++; break; case kb_handler_nak: break; default: NOT_REACHED(); } } return count; } static bool handle_special_keys_pressed(u32 key) { switch (key) { case KEY_DEL: if (kb_is_pressed(KEY_LEFT_CTRL) && kb_is_pressed(KEY_LEFT_ALT)) { printk("Ctrl + Alt + Del: Reboot!\n"); reboot(); NOT_REACHED(); } break; case KEY_NUM_LOCK: numLock = !numLock; kb_led_update(); return true; case KEY_CAPS_LOCK: capsLock = !capsLock; kb_led_update(); return true; } return false; } void handle_key_pressed(u32 key, bool pressed) { if (pressed) if (handle_special_keys_pressed(key)) return; kb_call_keypress_handlers( make_key_event(key, translate_printable_key(key), pressed) ); } static void key_int_handler(u32 key, bool kb_is_pressed) { bool e0 = (key >> 8) == 0xE0; key_pressed_state[e0][key & 0xFF] = kb_is_pressed; handle_key_pressed(key, kb_is_pressed); } static void kb_handle_default_state(u8 scancode) { switch (scancode) { case 0xE0: kb_curr_state = KB_READ_E0_SCANCODE_STATE; break; case 0xE1: kb_curr_state = KB_READ_E1_SCANCODE_STATE; break; default: key_int_handler(scancode & ~0x80u, !(scancode & 0x80)); } } static void kb_process_scancode(u8 scancode) { bool kb_is_pressed; switch (kb_curr_state) { case KB_READ_FIRST_SCANCODE_AFTER_E1_STATE: /* We ignore 0xE1 sequences at the moment (scancode 2/2) */ kb_curr_state = KB_DEFAULT_STATE; break; case KB_READ_E1_SCANCODE_STATE: /* We ignore 0xE1 sequences at the moment (scancode 1/2) */ kb_curr_state = KB_READ_FIRST_SCANCODE_AFTER_E1_STATE; break; case KB_READ_E0_SCANCODE_STATE: kb_curr_state = KB_DEFAULT_STATE; // Fake lshift pressed (2A) or released (AA) if (scancode == 0x2A || scancode == 0xAA) break; kb_is_pressed = !(scancode & 0x80); scancode &= (u8) ~0x80; key_int_handler(scancode | (0xE0u << 8u), kb_is_pressed); break; case KB_DEFAULT_STATE: kb_handle_default_state(scancode); break; } } static void kb_dump_regs(u8 ctr, u8 cto, u8 status) { bool masked = irq_is_masked(X86_PC_KEYBOARD_IRQ); printk("KB: IRQ masked: %u\n", masked); printk("KB: Ctrl Config. Byte (CTR): 0x%02x\n", ctr); printk("KB: Ctrl Output Port (CTO): 0x%02x\n", cto); printk("KB: Status register: 0x%02x\n", status); } static void kb_irq_bottom_half(void *arg) { u8 scancode; disable_preemption(); { while (safe_ringbuf_read_1(&kb_input_rb, &scancode)) { kb_process_scancode(scancode); } } enable_preemption(); } static int kb_irq_handler_read_scancodes(void) { int count = 0; while (i8042_has_pending_data()) { u8 scancode = i8042_read_data(); bool was_empty; if (!safe_ringbuf_write_1(&kb_input_rb, &scancode, &was_empty)) { /* We have no other choice than to just drain the data */ printk("KB: Warning: hit input limit. Drain the data!\n"); i8042_drain_any_data(); } count++; } return count; } static enum irq_action keyboard_irq_handler(void *ctx) { ASSERT(are_interrupts_enabled()); ASSERT(!is_preemption_enabled()); if (!i8042_is_ready_for_cmd()) { printk("KB: Warning: got IRQ with pending command\n"); return IRQ_HANDLED; } if (!kb_irq_handler_read_scancodes()) { /* Got IRQ *without* output buffer full set in the status register */ if (kopt_ps2_log) { printk("KB: Got IRQ#1 with OBF=0 in status register\n"); } i8042_force_drain_data(); return IRQ_HANDLED; } if (UNLIKELY(in_panic())) { /* * During panic() typically IRQs are completely disabled BUT, when the * the -panic_kb is passed to the kernel cmdline, we allow just PS/2 KB * IRQs to run, so that we can scroll the term buffer. Because we don't * have the timer IRQ, we have to process everything in the IRQ handler * itself. For the panic case, that's totally fine. * * When kopt_sercon is enabled, we allow IRQ 4 instead of IRQ 1. */ ulong val; disable_interrupts(&val); { kb_irq_bottom_half(NULL); } enable_interrupts(&val); return IRQ_HANDLED; } /* Everything is fine: we read at least one scancode */ if (!wth_enqueue_on(kb_worker_thread, &kb_irq_bottom_half, NULL)) { /* * While on real hardware this should NEVER happen, on some slow emulators * that's totally possible. For example, on this pure browser emulator: * https://copy.sh/v86/ * * If we scroll fast up and down immediately after boot while the * fb_pre_render_char_scanlines() function has not completed yet, * the scroll will be so slow that sometimes the queue of tasks for this * bottom half will fill up. */ printk("WARNING: KB: unable to enqueue job\n"); } return IRQ_HANDLED; } static u8 kb_translate_to_mediumraw(struct key_event ke) { const u32 key = ke.key; if ((key & 0xff) == key) return (u8)(key | (u8)(!ke.pressed << 7)); return mediumraw_e0_keys[key & 0xff] | (u8)(!ke.pressed << 7); } static void create_kb_worker_thread(void) { u8 *kb_input_buf = kmalloc(512); if (!kb_input_buf) panic("KB: unable to alloc kb_input_buf"); safe_ringbuf_init(&kb_input_rb, 512, 1, kb_input_buf); kb_worker_thread = wth_create_thread("kb", 1 /* priority */, WTH_KB_QUEUE_SIZE); if (!kb_worker_thread) panic("KB: Unable to create a worker thread for IRQs"); } static struct kb_dev ps2_keyboard = { .driver_name = "ps2", .is_pressed = kb_is_pressed, .register_handler = kb_register_keypress_handler, .scancode_to_ansi_seq = kb_scancode_to_ansi_seq, .translate_to_mediumraw = kb_translate_to_mediumraw, }; DEFINE_IRQ_HANDLER_NODE(keyboard, keyboard_irq_handler, &ps2_keyboard); static bool hw_8042_init_first_steps(void) { u8 status, ctr = 0, cto = 0; bool dump_regs = kopt_ps2_log; status = i8042_read_status(); if (!i8042_read_ctr_unsafe(&ctr)) { printk("KB: read CTR failed\n"); return false; } if (!in_hypervisor() && !(ctr & I8042_CTR_SYS_FLAG)) { printk("KB: Warning: unset system flag in CTR\n"); dump_regs = true; } if (dump_regs) { if (!i8042_read_cto_unsafe(&cto)) { printk("KB: read CTO failed\n"); return false; } kb_dump_regs(ctr, cto, status); } return true; } static bool hw_8042_init(void) { bool ok; ASSERT(!is_preemption_enabled()); if (!i8042_disable_ports()) return false; ok = hw_8042_init_first_steps(); if (!i8042_enable_ports()) return false; if (!ok) return false; if (!kopt_ps2_selftest) return true; if (i8042_self_test()) return true; printk("KB: PS/2 controller self-test failed, trying a reset\n"); if (i8042_reset()) { printk("KB: PS/2 controller: reset successful\n"); return true; } printk("KB: Unable to initialize the PS/2 controller\n"); return false; } static void init_kb_internal(void) { const bool acpi_ok = get_acpi_init_status() == ais_fully_initialized; /* * While it would be great to not even try initializing the i8042 controller * if ACPI says it's not present on the system, apparently that's not a good * idea because the value of the ACPI_FADT_8042 flag in FADT's IAPC_BOOT_ARCH * is not reliable. E.g.: I have a (pure UEFI) machine that has FADT v6 which * has ACPI_FADT_8042 unset, even if a i8042 controller exists and Linux * confirms that. * if (MOD_acpi && acpi_ok) { if (acpi_is_8042_present() == tri_no) { printk("KB: no 8042 controller (PS/2) detected\n"); return; } } */ if (!hw_8042_init()) { if (acpi_ok) printk("KB: no 8042 controller (PS/2) detected\n"); else printk("KB: hw_8042_init() failed\n"); return; } if (in_hypervisor()) { /* * In case of real HW, we can assume numLock is off on boot, while * when running inside a VM, the numLock can still be off in the VM * itself while being (typically) turned on in the host. Because we * cannot control the `numLock` state in the host and we're not even * guarateed to be able to catch the `numLock` key press, assuming it as * turned on when running in a VM, is typically the best choice. */ numLock = true; } kb_led_update(); kb_set_typematic_byte(0); create_kb_worker_thread(); irq_install_handler(X86_PC_KEYBOARD_IRQ, &keyboard); register_keyboard_device(&ps2_keyboard); } /* This will be executed in a kernel thread */ void init_kb(void) { if (kopt_sercon) return; disable_preemption(); { init_kb_internal(); } enable_preemption(); } static struct module kb_ps2_module = { .name = "kb8042", .priority = MOD_kb_prio, .init = &init_kb, }; REGISTER_MODULE(&kb_ps2_module); <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ############################################ # CONSTANTS VERSION_REGEX='[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)*' if [ -t 1 ]; then # We're running on a terminal, so we can use colors RED='\033[0;31m' GREEN='\033[0;32m' BROWN='\033[0;33m' BLUE='\033[0;34m' MAGENTA='\033[0;35m' CYAN='\033[0;36m' LGRAY='\033[0;37m' DGRAY='\033[1;37m' LRED='\033[1;31m' LGREEN='\033[1;32m' YELLOW='\033[1;33m' LBLUE='\033[1;34m' LMAGENTA='\033[1;35m' LCYAN='\033[1;36m' WHITE='\033[1;37m' RATTRS='\033[0m' else RED='' GREEN='' BROWN='' BLUE='' MAGENTA='' CYAN='' LGRAY='' DGRAY='' LRED='' LGREEN='' YELLOW='' LBLUE='' LMAGENTA='' LCYAN='' WHITE='' RATTRS='' fi if [ -n "$TRAVIS" ]; then if [[ $QUIET != 1 ]]; then echo "CI Detected: TRAVIS" fi export RUNNING_IN_CI=1 elif [ -n "$CIRCLECI" ]; then if [[ $QUIET != 1 ]]; then echo "CI Detected: CIRCLE" fi export RUNNING_IN_CI=1 elif [ -n "$AZURE_HTTP_USER_AGENT" ]; then if [[ $QUIET != 1 ]]; then echo "CI Detected: AZURE PIPELINES" fi export RUNNING_IN_CI=1 else if [[ $QUIET != 1 ]]; then if [[ "$RUNNING_IN_CI" == "1" ]]; then echo "CI Detected: UNKNOWN" else echo "CI Detected: None [Assuming user machine]" fi fi fi ############################################ # FUNCTIONS # $1 version in the format "major.minor.patchlevel" # $2 component number to get (1 => major, 2 => minor, 3 => patchlevel) function get_version_comp { echo -ne $1 | grep -Eo '[0-9]+' | head -$2 | tail -1 } # $1 = program name function generic_get_version_str { $1 --version | head -1 | grep -Eo "${VERSION_REGEX}[ ]*$" | head -1 } # $1 = command function run_command { echo "Running command: $1" eval "$1" } # $1 = command # $2 = output file function run_command2 { echo "Running command: $1 &> $2" eval "$1 &> $2" } pushd () { command pushd "$@" > /dev/null } popd () { command popd "$@" > /dev/null } function show_work_on_component_msg { echo echo "*** $1 ***" echo } function show_skip_component_msg { echo "NOTE: Skipping $1" } # $1 = program name # $2 = min version string function show_too_old_and_exit { echo "System's $1 is too old. Version >= $2 is required." exit 1 } # $1 = program name # $2 = current version string (i.e. "1.2.3") # $3 = min version string (i.e. "1.2.3") function fail_if_too_old { major=$(get_version_comp $2 1) minor=$(get_version_comp $2 2) echo "[cmake_run] $1 version (parsed): $major.$minor" min_major=$(get_version_comp $3 1) min_minor=$(get_version_comp $3 2) if [ $major -lt $min_major ]; then show_too_old_and_exit $1 $3 elif [ $major -eq $min_major ] && [ $minor -lt $min_minor ]; then show_too_old_and_exit $1 $3 fi } function download_file_in_cache { local url="$1" local filename="$2" if ! [ -f $TC/cache/$filename ]; then (cd $TC/cache && wget $url/$filename) else echo "NOTE: Skipping the download of $filename" fi } function extract_cachefile_tar_gz { local tarfile="$1" local internalDirName="$2" local newDirName="$3" echo "Extracting $tarfile..." tar xfz $TC/cache/$tarfile if ! [ "$internalDirName" = "--" ]; then if ! [ "$internalDirName" = "$newDirName" ]; then if ! [ -d "$internalDirName" ]; then echo "ERROR: internal dir: '$internalDirName' not found" exit 1 fi if [ -d "$newDirName" ]; then echo "ERROR: new dir: '$newDirName' exists" exit 1 fi mv "$internalDirName" "$newDirName" fi fi echo "Extracting completed." } function extract_cachefile_tar_bz { local tarfile="$1" local internalDirName="$2" local newDirName="$3" echo "Extracting $tarfile..." tar xfj $TC/cache/$tarfile if ! [ "$internalDirName" = "--" ]; then if ! [ "$internalDirName" = "$newDirName" ]; then if ! [ -d "$internalDirName" ]; then echo "ERROR: internal dir: '$internalDirName' not found" exit 1 fi if [ -d "$newDirName" ]; then echo "ERROR: new dir: '$newDirName' exists" exit 1 fi mv "$internalDirName" "$newDirName" fi fi echo "Extracting completed." } function download_git_repo_in_cache { local url="$1" local tag="$2" local tarname="$3" local dirname="$4" if [ -f $TC/cache/$tarname ]; then return fi if [ -z "$tag" ]; then git clone --depth 1 "$url" $dirname else if ! git clone --branch "$tag" --depth 1 "$url" $dirname; then # Git clone failed. There could be several reasons for that: # # - The remote git server is down # # - The pointed branch/tag/commit does not exist anymore because # the ref has been deleted or the history has been rewritten. # # - In some corner cases, like BitBucket, fetching individual # untagged commits is not allowed. This is the only case for # which an actual workaround is possible. # See: https://stackoverflow.com/a/51002078/2077198 # if echo "$tag" | grep -E "^[0-9a-z]+$"; then # It's worth trying this approach only if the tag looks like a # commit SHA. if git clone "$url" $dirname; then cd $dirname if ! git checkout "$tag"; then echo "ERROR: the git ref $tag does not exist anymore!" exit 1 fi # Save the git commit info before deleting the .git directory git rev-parse --abbrev-ref HEAD > .ref_name git rev-parse --short HEAD > .ref_short git rev-parse HEAD > .ref echo "$tag" > .our_tag # Delete the .git directory which is not needed anymore and takes # quite some space. We just need one commit, not the whole # git history. rm -rf .git # Go back to the parent directory cd .. fi fi fi fi if ! [ -d "$dirname" ]; then echo "ERROR: git clone failed for: $url" exit 1 fi tar cfz $tarname $dirname if ! [ -f $tarname ]; then echo "ERROR: tar failed" exit 1 fi mv $tarname $TC/cache || exit 1 rm -rf $dirname } function get_32bit_libs_pkg { if ! [ -f $TC/.distro ]; then echo "Linux distribution not fully supported by this script." exit 1 fi local distro=`cat $TC/.distro` case $distro in debian) echo gcc-multilib ;; fedora) echo glibc-devel.i686 ;; arch) echo lib32-glibc ;; opensuse) echo glibc-devel-32bit ;; *) echo "Unknown Linux distribution" exit 1 ;; esac } function get_rpm2cpio_pkg { if ! [ -f $TC/.distro ]; then echo "Linux distribution not fully supported by this script." exit 1 fi local distro=`cat $TC/.distro` case $distro in debian) echo rpm2cpio ;; fedora) echo "" ;; arch) echo rpm-tools ;; opensuse) echo "" ;; *) echo "Unknown Linux distribution" exit 1 ;; esac } function get_cpio_pkg { if ! [ -f $TC/.distro ]; then echo "Linux distribution not fully supported by this script." exit 1 fi local distro=`cat $TC/.distro` case $distro in debian) echo cpio ;; fedora) echo cpio ;; arch) echo cpio ;; opensuse) echo cpio ;; *) echo "Unknown Linux distribution" exit 1 ;; esac } function install_pkg_on_demand { local pkg="$1" local distro=`cat $TC/.distro` local install_pkg="$MAIN_DIR/scripts/tc/$distro/install_pkg" if [[ "$pkg" != "" ]]; then if [ "$RUNNING_IN_CI" == 1 ]; then $install_pkg -ci $pkg else $install_pkg $pkg fi fi } function install_32bit_libs { if ! [ -f $TC/.distro ]; then echo "Unable to check the presence of 32-bit glibc on this system: " echo "Linux distribution not fully supported by this script." echo "WARNING: the current operation might fail." return fi install_pkg_on_demand $(get_32bit_libs_pkg) } function install_rpm2cpio { if ! [ -f $TC/.distro ]; then echo "Linux distribution not fully supported by this script." echo "Please make sure that \"rpm2cpio\" is installed on the system." echo "WARNING: the current operation might fail." return fi install_pkg_on_demand $(get_cpio_pkg) install_pkg_on_demand $(get_rpm2cpio_pkg) } <file_sep>/****************************************************************************** * * Module Name: nsrepair2 - Repair for objects returned by specific * predefined methods * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsrepair2") /* * Information structure and handler for ACPI predefined names that can * be repaired on a per-name basis. */ typedef ACPI_STATUS (*ACPI_REPAIR_FUNCTION) ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); typedef struct acpi_repair_info { char Name[ACPI_NAMESEG_SIZE]; ACPI_REPAIR_FUNCTION RepairFunction; } ACPI_REPAIR_INFO; /* Local prototypes */ static const ACPI_REPAIR_INFO * AcpiNsMatchComplexRepair ( ACPI_NAMESPACE_NODE *Node); static ACPI_STATUS AcpiNsRepair_ALR ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_CID ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_CST ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_FDE ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_HID ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_PRT ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_PSS ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsRepair_TSS ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr); static ACPI_STATUS AcpiNsCheckSortedList ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT *ReturnObject, UINT32 StartIndex, UINT32 ExpectedCount, UINT32 SortIndex, UINT8 SortDirection, char *SortKeyName); /* Values for SortDirection above */ #define ACPI_SORT_ASCENDING 0 #define ACPI_SORT_DESCENDING 1 static void AcpiNsRemoveElement ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Index); static void AcpiNsSortList ( ACPI_OPERAND_OBJECT **Elements, UINT32 Count, UINT32 Index, UINT8 SortDirection); /* * This table contains the names of the predefined methods for which we can * perform more complex repairs. * * As necessary: * * _ALR: Sort the list ascending by AmbientIlluminance * _CID: Strings: uppercase all, remove any leading asterisk * _CST: Sort the list ascending by C state type * _FDE: Convert Buffer of BYTEs to a Buffer of DWORDs * _GTM: Convert Buffer of BYTEs to a Buffer of DWORDs * _HID: Strings: uppercase all, remove any leading asterisk * _PRT: Fix reversed SourceName and SourceIndex * _PSS: Sort the list descending by Power * _TSS: Sort the list descending by Power * * Names that must be packages, but cannot be sorted: * * _BCL: Values are tied to the Package index where they appear, and cannot * be moved or sorted. These index values are used for _BQC and _BCM. * However, we can fix the case where a buffer is returned, by converting * it to a Package of integers. */ static const ACPI_REPAIR_INFO AcpiNsRepairableNames[] = { {"_ALR", AcpiNsRepair_ALR}, {"_CID", AcpiNsRepair_CID}, {"_CST", AcpiNsRepair_CST}, {"_FDE", AcpiNsRepair_FDE}, {"_GTM", AcpiNsRepair_FDE}, /* _GTM has same repair as _FDE */ {"_HID", AcpiNsRepair_HID}, {"_PRT", AcpiNsRepair_PRT}, {"_PSS", AcpiNsRepair_PSS}, {"_TSS", AcpiNsRepair_TSS}, {{0,0,0,0}, NULL} /* Table terminator */ }; #define ACPI_FDE_FIELD_COUNT 5 #define ACPI_FDE_BYTE_BUFFER_SIZE 5 #define ACPI_FDE_DWORD_BUFFER_SIZE (ACPI_FDE_FIELD_COUNT * (UINT32) sizeof (UINT32)) /****************************************************************************** * * FUNCTION: AcpiNsComplexRepairs * * PARAMETERS: Info - Method execution information block * Node - Namespace node for the method/object * ValidateStatus - Original status of earlier validation * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if repair was successful. If name is not * matched, ValidateStatus is returned. * * DESCRIPTION: Attempt to repair/convert a return object of a type that was * not expected. * *****************************************************************************/ ACPI_STATUS AcpiNsComplexRepairs ( ACPI_EVALUATE_INFO *Info, ACPI_NAMESPACE_NODE *Node, ACPI_STATUS ValidateStatus, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { const ACPI_REPAIR_INFO *Predefined; ACPI_STATUS Status; /* Check if this name is in the list of repairable names */ Predefined = AcpiNsMatchComplexRepair (Node); if (!Predefined) { return (ValidateStatus); } Status = Predefined->RepairFunction (Info, ReturnObjectPtr); return (Status); } /****************************************************************************** * * FUNCTION: AcpiNsMatchComplexRepair * * PARAMETERS: Node - Namespace node for the method/object * * RETURN: Pointer to entry in repair table. NULL indicates not found. * * DESCRIPTION: Check an object name against the repairable object list. * *****************************************************************************/ static const ACPI_REPAIR_INFO * AcpiNsMatchComplexRepair ( ACPI_NAMESPACE_NODE *Node) { const ACPI_REPAIR_INFO *ThisName; /* Search info table for a repairable predefined method/object name */ ThisName = AcpiNsRepairableNames; while (ThisName->RepairFunction) { if (ACPI_COMPARE_NAMESEG (Node->Name.Ascii, ThisName->Name)) { return (ThisName); } ThisName++; } return (NULL); /* Not found */ } /****************************************************************************** * * FUNCTION: AcpiNsRepair_ALR * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _ALR object. If necessary, sort the object list * ascending by the ambient illuminance values. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_ALR ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_STATUS Status; Status = AcpiNsCheckSortedList (Info, ReturnObject, 0, 2, 1, ACPI_SORT_ASCENDING, "AmbientIlluminance"); return (Status); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_FDE * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _FDE and _GTM objects. The expected return * value is a Buffer of 5 DWORDs. This function repairs a common * problem where the return value is a Buffer of BYTEs, not * DWORDs. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_FDE ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT *BufferObject; UINT8 *ByteBuffer; UINT32 *DwordBuffer; UINT32 i; ACPI_FUNCTION_NAME (NsRepair_FDE); switch (ReturnObject->Common.Type) { case ACPI_TYPE_BUFFER: /* This is the expected type. Length should be (at least) 5 DWORDs */ if (ReturnObject->Buffer.Length >= ACPI_FDE_DWORD_BUFFER_SIZE) { return (AE_OK); } /* We can only repair if we have exactly 5 BYTEs */ if (ReturnObject->Buffer.Length != ACPI_FDE_BYTE_BUFFER_SIZE) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Incorrect return buffer length %u, expected %u", ReturnObject->Buffer.Length, ACPI_FDE_DWORD_BUFFER_SIZE)); return (AE_AML_OPERAND_TYPE); } /* Create the new (larger) buffer object */ BufferObject = AcpiUtCreateBufferObject ( ACPI_FDE_DWORD_BUFFER_SIZE); if (!BufferObject) { return (AE_NO_MEMORY); } /* Expand each byte to a DWORD */ ByteBuffer = ReturnObject->Buffer.Pointer; DwordBuffer = ACPI_CAST_PTR (UINT32, BufferObject->Buffer.Pointer); for (i = 0; i < ACPI_FDE_FIELD_COUNT; i++) { *DwordBuffer = (UINT32) *ByteBuffer; DwordBuffer++; ByteBuffer++; } ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s Expanded Byte Buffer to expected DWord Buffer\n", Info->FullPathname)); break; default: return (AE_AML_OPERAND_TYPE); } /* Delete the original return object, return the new buffer object */ AcpiUtRemoveReference (ReturnObject); *ReturnObjectPtr = BufferObject; Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_CID * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _CID object. If a string, ensure that all * letters are uppercase and that there is no leading asterisk. * If a Package, ensure same for all string elements. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_CID ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT **ElementPtr; ACPI_OPERAND_OBJECT *OriginalElement; UINT16 OriginalRefCount; UINT32 i; /* Check for _CID as a simple string */ if (ReturnObject->Common.Type == ACPI_TYPE_STRING) { Status = AcpiNsRepair_HID (Info, ReturnObjectPtr); return (Status); } /* Exit if not a Package */ if (ReturnObject->Common.Type != ACPI_TYPE_PACKAGE) { return (AE_OK); } /* Examine each element of the _CID package */ ElementPtr = ReturnObject->Package.Elements; for (i = 0; i < ReturnObject->Package.Count; i++) { OriginalElement = *ElementPtr; OriginalRefCount = OriginalElement->Common.ReferenceCount; Status = AcpiNsRepair_HID (Info, ElementPtr); if (ACPI_FAILURE (Status)) { return (Status); } if (OriginalElement != *ElementPtr) { /* Update reference count of new object */ (*ElementPtr)->Common.ReferenceCount = OriginalRefCount; } ElementPtr++; } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_CST * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _CST object: * 1. Sort the list ascending by C state type * 2. Ensure type cannot be zero * 3. A subpackage count of zero means _CST is meaningless * 4. Count must match the number of C state subpackages * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_CST ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT **OuterElements; UINT32 OuterElementCount; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; BOOLEAN Removing; UINT32 i; ACPI_FUNCTION_NAME (NsRepair_CST); /* * Check if the C-state type values are proportional. */ OuterElementCount = ReturnObject->Package.Count - 1; i = 0; while (i < OuterElementCount) { OuterElements = &ReturnObject->Package.Elements[i + 1]; Removing = FALSE; if ((*OuterElements)->Package.Count == 0) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "SubPackage[%u] - removing entry due to zero count", i)); Removing = TRUE; goto RemoveElement; } ObjDesc = (*OuterElements)->Package.Elements[1]; /* Index1 = Type */ if ((UINT32) ObjDesc->Integer.Value == 0) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "SubPackage[%u] - removing entry due to invalid Type(0)", i)); Removing = TRUE; } RemoveElement: if (Removing) { AcpiNsRemoveElement (ReturnObject, i + 1); OuterElementCount--; } else { i++; } } /* Update top-level package count, Type "Integer" checked elsewhere */ ObjDesc = ReturnObject->Package.Elements[0]; ObjDesc->Integer.Value = OuterElementCount; /* * Entries (subpackages) in the _CST Package must be sorted by the * C-state type, in ascending order. */ Status = AcpiNsCheckSortedList (Info, ReturnObject, 1, 4, 1, ACPI_SORT_ASCENDING, "C-State Type"); if (ACPI_FAILURE (Status)) { return (Status); } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_HID * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _HID object. If a string, ensure that all * letters are uppercase and that there is no leading asterisk. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_HID ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT *NewString; char *Source; char *Dest; ACPI_FUNCTION_NAME (NsRepair_HID); /* We only care about string _HID objects (not integers) */ if (ReturnObject->Common.Type != ACPI_TYPE_STRING) { return (AE_OK); } if (ReturnObject->String.Length == 0) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Invalid zero-length _HID or _CID string")); /* Return AE_OK anyway, let driver handle it */ Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; return (AE_OK); } /* It is simplest to always create a new string object */ NewString = AcpiUtCreateStringObject (ReturnObject->String.Length); if (!NewString) { return (AE_NO_MEMORY); } /* * Remove a leading asterisk if present. For some unknown reason, there * are many machines in the field that contains IDs like this. * * Examples: "*PNP0C03", "*ACPI0003" */ Source = ReturnObject->String.Pointer; if (*Source == '*') { Source++; NewString->String.Length--; ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Removed invalid leading asterisk\n", Info->FullPathname)); } /* * Copy and uppercase the string. From the ACPI 5.0 specification: * * A valid PNP ID must be of the form "AAA####" where A is an uppercase * letter and # is a hex digit. A valid ACPI ID must be of the form * "NNNN####" where N is an uppercase letter or decimal digit, and * # is a hex digit. */ for (Dest = NewString->String.Pointer; *Source; Dest++, Source++) { *Dest = (char) toupper ((int) *Source); } AcpiUtRemoveReference (ReturnObject); *ReturnObjectPtr = NewString; return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_PRT * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _PRT object. If necessary, fix reversed * SourceName and SourceIndex field, a common BIOS bug. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_PRT ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *PackageObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT **TopObjectList; ACPI_OPERAND_OBJECT **SubObjectList; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *SubPackage; UINT32 ElementCount; UINT32 Index; /* Each element in the _PRT package is a subpackage */ TopObjectList = PackageObject->Package.Elements; ElementCount = PackageObject->Package.Count; /* Examine each subpackage */ for (Index = 0; Index < ElementCount; Index++, TopObjectList++) { SubPackage = *TopObjectList; SubObjectList = SubPackage->Package.Elements; /* Check for minimum required element count */ if (SubPackage->Package.Count < 4) { continue; } /* * If the BIOS has erroneously reversed the _PRT SourceName (index 2) * and the SourceIndex (index 3), fix it. _PRT is important enough to * workaround this BIOS error. This also provides compatibility with * other ACPI implementations. */ ObjDesc = SubObjectList[3]; if (!ObjDesc || (ObjDesc->Common.Type != ACPI_TYPE_INTEGER)) { SubObjectList[3] = SubObjectList[2]; SubObjectList[2] = ObjDesc; Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "PRT[%X]: Fixed reversed SourceName and SourceIndex", Index)); } } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_PSS * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _PSS object. If necessary, sort the object list * by the CPU frequencies. Check that the power dissipation values * are all proportional to CPU frequency (i.e., sorting by * frequency should be the same as sorting by power.) * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_PSS ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT **OuterElements; UINT32 OuterElementCount; ACPI_OPERAND_OBJECT **Elements; ACPI_OPERAND_OBJECT *ObjDesc; UINT32 PreviousValue; ACPI_STATUS Status; UINT32 i; /* * Entries (subpackages) in the _PSS Package must be sorted by power * dissipation, in descending order. If it appears that the list is * incorrectly sorted, sort it. We sort by CpuFrequency, since this * should be proportional to the power. */ Status = AcpiNsCheckSortedList (Info, ReturnObject, 0, 6, 0, ACPI_SORT_DESCENDING, "CpuFrequency"); if (ACPI_FAILURE (Status)) { return (Status); } /* * We now know the list is correctly sorted by CPU frequency. Check if * the power dissipation values are proportional. */ PreviousValue = ACPI_UINT32_MAX; OuterElements = ReturnObject->Package.Elements; OuterElementCount = ReturnObject->Package.Count; for (i = 0; i < OuterElementCount; i++) { Elements = (*OuterElements)->Package.Elements; ObjDesc = Elements[1]; /* Index1 = PowerDissipation */ if ((UINT32) ObjDesc->Integer.Value > PreviousValue) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "SubPackage[%u,%u] - suspicious power dissipation values", i-1, i)); } PreviousValue = (UINT32) ObjDesc->Integer.Value; OuterElements++; } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRepair_TSS * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if object is OK or was repaired successfully * * DESCRIPTION: Repair for the _TSS object. If necessary, sort the object list * descending by the power dissipation values. * *****************************************************************************/ static ACPI_STATUS AcpiNsRepair_TSS ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; /* * We can only sort the _TSS return package if there is no _PSS in the * same scope. This is because if _PSS is present, the ACPI specification * dictates that the _TSS Power Dissipation field is to be ignored, and * therefore some BIOSs leave garbage values in the _TSS Power field(s). * In this case, it is best to just return the _TSS package as-is. * (May, 2011) */ Status = AcpiNsGetNode (Info->Node, "^_PSS", ACPI_NS_NO_UPSEARCH, &Node); if (ACPI_SUCCESS (Status)) { return (AE_OK); } Status = AcpiNsCheckSortedList (Info, ReturnObject, 0, 5, 1, ACPI_SORT_DESCENDING, "PowerDissipation"); return (Status); } /****************************************************************************** * * FUNCTION: AcpiNsCheckSortedList * * PARAMETERS: Info - Method execution information block * ReturnObject - Pointer to the top-level returned object * StartIndex - Index of the first subpackage * ExpectedCount - Minimum length of each subpackage * SortIndex - Subpackage entry to sort on * SortDirection - Ascending or descending * SortKeyName - Name of the SortIndex field * * RETURN: Status. AE_OK if the list is valid and is sorted correctly or * has been repaired by sorting the list. * * DESCRIPTION: Check if the package list is valid and sorted correctly by the * SortIndex. If not, then sort the list. * *****************************************************************************/ static ACPI_STATUS AcpiNsCheckSortedList ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT *ReturnObject, UINT32 StartIndex, UINT32 ExpectedCount, UINT32 SortIndex, UINT8 SortDirection, char *SortKeyName) { UINT32 OuterElementCount; ACPI_OPERAND_OBJECT **OuterElements; ACPI_OPERAND_OBJECT **Elements; ACPI_OPERAND_OBJECT *ObjDesc; UINT32 i; UINT32 PreviousValue; ACPI_FUNCTION_NAME (NsCheckSortedList); /* The top-level object must be a package */ if (ReturnObject->Common.Type != ACPI_TYPE_PACKAGE) { return (AE_AML_OPERAND_TYPE); } /* * NOTE: assumes list of subpackages contains no NULL elements. * Any NULL elements should have been removed by earlier call * to AcpiNsRemoveNullElements. */ OuterElementCount = ReturnObject->Package.Count; if (!OuterElementCount || StartIndex >= OuterElementCount) { return (AE_AML_PACKAGE_LIMIT); } OuterElements = &ReturnObject->Package.Elements[StartIndex]; OuterElementCount -= StartIndex; PreviousValue = 0; if (SortDirection == ACPI_SORT_DESCENDING) { PreviousValue = ACPI_UINT32_MAX; } /* Examine each subpackage */ for (i = 0; i < OuterElementCount; i++) { /* Each element of the top-level package must also be a package */ if ((*OuterElements)->Common.Type != ACPI_TYPE_PACKAGE) { return (AE_AML_OPERAND_TYPE); } /* Each subpackage must have the minimum length */ if ((*OuterElements)->Package.Count < ExpectedCount) { return (AE_AML_PACKAGE_LIMIT); } Elements = (*OuterElements)->Package.Elements; ObjDesc = Elements[SortIndex]; if (ObjDesc->Common.Type != ACPI_TYPE_INTEGER) { return (AE_AML_OPERAND_TYPE); } /* * The list must be sorted in the specified order. If we detect a * discrepancy, sort the entire list. */ if (((SortDirection == ACPI_SORT_ASCENDING) && (ObjDesc->Integer.Value < PreviousValue)) || ((SortDirection == ACPI_SORT_DESCENDING) && (ObjDesc->Integer.Value > PreviousValue))) { AcpiNsSortList (&ReturnObject->Package.Elements[StartIndex], OuterElementCount, SortIndex, SortDirection); Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Repaired unsorted list - now sorted by %s\n", Info->FullPathname, SortKeyName)); return (AE_OK); } PreviousValue = (UINT32) ObjDesc->Integer.Value; OuterElements++; } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsSortList * * PARAMETERS: Elements - Package object element list * Count - Element count for above * Index - Sort by which package element * SortDirection - Ascending or Descending sort * * RETURN: None * * DESCRIPTION: Sort the objects that are in a package element list. * * NOTE: Assumes that all NULL elements have been removed from the package, * and that all elements have been verified to be of type Integer. * *****************************************************************************/ static void AcpiNsSortList ( ACPI_OPERAND_OBJECT **Elements, UINT32 Count, UINT32 Index, UINT8 SortDirection) { ACPI_OPERAND_OBJECT *ObjDesc1; ACPI_OPERAND_OBJECT *ObjDesc2; ACPI_OPERAND_OBJECT *TempObj; UINT32 i; UINT32 j; /* Simple bubble sort */ for (i = 1; i < Count; i++) { for (j = (Count - 1); j >= i; j--) { ObjDesc1 = Elements[j-1]->Package.Elements[Index]; ObjDesc2 = Elements[j]->Package.Elements[Index]; if (((SortDirection == ACPI_SORT_ASCENDING) && (ObjDesc1->Integer.Value > ObjDesc2->Integer.Value)) || ((SortDirection == ACPI_SORT_DESCENDING) && (ObjDesc1->Integer.Value < ObjDesc2->Integer.Value))) { TempObj = Elements[j-1]; Elements[j-1] = Elements[j]; Elements[j] = TempObj; } } } } /****************************************************************************** * * FUNCTION: AcpiNsRemoveElement * * PARAMETERS: ObjDesc - Package object element list * Index - Index of element to remove * * RETURN: None * * DESCRIPTION: Remove the requested element of a package and delete it. * *****************************************************************************/ static void AcpiNsRemoveElement ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Index) { ACPI_OPERAND_OBJECT **Source; ACPI_OPERAND_OBJECT **Dest; UINT32 Count; UINT32 NewCount; UINT32 i; ACPI_FUNCTION_NAME (NsRemoveElement); Count = ObjDesc->Package.Count; NewCount = Count - 1; Source = ObjDesc->Package.Elements; Dest = Source; /* Examine all elements of the package object, remove matched index */ for (i = 0; i < Count; i++) { if (i == Index) { AcpiUtRemoveReference (*Source); /* Remove one ref for being in pkg */ AcpiUtRemoveReference (*Source); } else { *Dest = *Source; Dest++; } Source++; } /* NULL terminate list and update the package count */ *Dest = NULL; ObjDesc->Package.Count = NewCount; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) include_directories(${CMAKE_SOURCE_DIR}/include) add_definitions(-DUSERMODE_APP) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -ggdb") file( GLOB FATHACK_SRC "fathack.c" "${CMAKE_SOURCE_DIR}/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.cpp" ) add_executable(fathack ${FATHACK_SRC}) add_executable(pnm2text "pnm2text.c") add_executable(mbrhack "mbrhack.c") add_executable(elfhack32 "elfhack.c") set_target_properties( elfhack32 PROPERTIES COMPILE_DEFINITIONS "USE_ELF32" ) add_executable(elfhack64 "elfhack.c") set_target_properties( elfhack64 PROPERTIES COMPILE_DEFINITIONS "USE_ELF64" ) <file_sep># SPDX-License-Identifier: BSD-2-Clause # Remove -rdynamic SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS) file(GLOB COMMON_SOURCES ${GLOB_CONF_DEP} "${CMAKE_SOURCE_DIR}/boot/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.cpp" ) add_library( efi_app_${EFI_ARCH} SHARED EXCLUDE_FROM_ALL ${SOURCES} ${COMMON_SOURCES} ) set( COMPILE_FLAGS_LIST -maccumulate-outgoing-args # necessary for MS_ABI with older GCC compilers -fPIC ) set( LINK_FLAGS_LIST -nostdlib -Wl,--script=${GNUEFI_DIR}/gnuefi/elf_${EFI_ARCH}_efi.lds -Wl,-znocombreloc -Wl,-Bsymbolic ) JOIN("${COMPILE_FLAGS_LIST}" ${SPACE} COMPILE_FLAGS) JOIN("${LINK_FLAGS_LIST}" ${SPACE} LINK_FLAGS) set_target_properties( efi_app_${EFI_ARCH} PROPERTIES COMPILE_FLAGS "${EFI_BUILD_BASE_FLAGS} ${COMPILE_FLAGS}" LINK_FLAGS ${LINK_FLAGS} ) target_include_directories( efi_app_${EFI_ARCH} PRIVATE ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/include/system_headers ${GNUEFI_DIR}/inc ${GNUEFI_DIR}/inc/${EFI_ARCH} ) target_compile_definitions( efi_app_${EFI_ARCH} PRIVATE STATIC_TILCK_ASM_STRING EFI_FUNCTION_WRAPPER NO_TILCK_ASSERT NO_TILCK_STATIC_WRAPPER GNU_EFI_USE_MS_ABI # allows to call UEFI funcs without the wrapper ) target_link_libraries( efi_app_${EFI_ARCH} ${GNUEFI_DIR}/${EFI_ARCH}/gnuefi/crt0-efi-${EFI_ARCH}.o ${GNUEFI_DIR}/${EFI_ARCH}/lib/libefi.a ${GNUEFI_DIR}/${EFI_ARCH}/gnuefi/libgnuefi.a ) add_dependencies(efi_app_${EFI_ARCH} kernel) set( OBJCOPY_OPTS -j .text -j .sdata -j .data -j .dynamic -j .dynsym -j .rel -j .rela -j .reloc --target=efi-app-${EFI_ARCH} ) add_custom_command( OUTPUT ${EFI_${EFI_ARCH}_FILE} COMMAND ${CMAKE_OBJCOPY} ${OBJCOPY_OPTS} libefi_app_${EFI_ARCH}.so ${EFI_${EFI_ARCH}_FILE} DEPENDS ${SWITCHMODE_BIN} efi_app_${EFI_ARCH} COMMENT "Creating the final EFI file for ${EFI_ARCH}" ) add_custom_target( efi_${EFI_ARCH}_bootloader DEPENDS ${EFI_${EFI_ARCH}_FILE} ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_kmalloc.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/kmalloc_debug.h> #include "termutil.h" #include "dp_int.h" static int row; static void dp_dump_mmap(void) { struct mem_region ma; dp_writeln(" START END (T, Extr)"); for (int i = 0; i < get_mem_regions_count(); i++) { get_mem_region(i, &ma); dp_writeln("%02d) %#018llx - %#018llx (%d, %s) [%8u KB]", i, ma.addr, ma.addr + ma.len - 1, ma.type, mem_region_extra_to_str(ma.extra), ma.len / KB); } dp_writeln(""); } #ifdef arch_x86_family static const char *mtrr_mem_type_str[8] = { [MEM_TYPE_UC] = "UC", [MEM_TYPE_WC] = "WC", [MEM_TYPE_R1] = "??", [MEM_TYPE_R2] = "??", [MEM_TYPE_WT] = "WT", [MEM_TYPE_WP] = "WP", [MEM_TYPE_WB] = "WB", [MEM_TYPE_UC_] = "UC-", }; static void dump_var_mtrrs(void) { if (!get_var_mttrs_count()) { dp_writeln("MTRRs: not supported on this CPU"); return; } u64 mtrr_dt = rdmsr(MSR_IA32_MTRR_DEF_TYPE); dp_writeln("MTRRs (default type: %s):", mtrr_mem_type_str[mtrr_dt & 0xff]); for (u32 i = 0; i < get_var_mttrs_count(); i++) { u64 physBaseVal = rdmsr(MSR_MTRRphysBase0 + 2 * i); u64 physMaskVal = rdmsr(MSR_MTRRphysBase0 + 2 * i + 1); u8 mem_type = physBaseVal & 0xff; if (!(physMaskVal & (1 << 11))) continue; physBaseVal &= ~0xffu; physMaskVal &= ~((u64)PAGE_SIZE - 1); u32 first_set_bit = get_first_set_bit_index64(physMaskVal); u64 sz = (1ull << first_set_bit) / KB; bool one_block = true; for (u32 b = first_set_bit; b < x86_cpu_features.phys_addr_bits; b++) { if (!(physMaskVal & (1ull << b))) { one_block = false; break; } } if (one_block) { dp_writeln("%02d) 0x%llx %s [%8llu KB]", i, physBaseVal, mtrr_mem_type_str[mem_type], sz); } else { dp_writeln("%02d) 0x%llx %s [%8s]", i, physBaseVal, mtrr_mem_type_str[mem_type], "???"); } } } #endif static void dump_global_mem_stats(void) { static struct debug_kmalloc_heap_info hi; struct mem_region ma; u64 tot_usable = 0; u64 kernel_mem = 0; u64 ramdisk_mem = 0; u64 kmalloc_mem = 0; u64 tot_used = 0; ASSERT(!is_preemption_enabled()); for (int i = 0; i < KMALLOC_HEAPS_COUNT; i++) { if (!debug_kmalloc_get_heap_info(i, &hi)) break; kmalloc_mem += hi.mem_allocated; } for (int i = 0; i < get_mem_regions_count(); i++) { get_mem_region(i, &ma); if (ma.type == MULTIBOOT_MEMORY_AVAILABLE || (ma.extra & (MEM_REG_EXTRA_RAMDISK | MEM_REG_EXTRA_KERNEL))) { tot_usable += ma.len; if (ma.extra & MEM_REG_EXTRA_KERNEL) kernel_mem += ma.len; if (ma.extra & MEM_REG_EXTRA_RAMDISK) ramdisk_mem += ma.len; } } kernel_mem -= KMALLOC_FIRST_HEAP_SIZE; tot_used = kmalloc_mem + ramdisk_mem + kernel_mem; dp_writeln( "Total usable physical mem: %8llu KB [ %s%llu MB ]", tot_usable / KB, "\033(0g\033(B", /* plus/minus sign */ tot_usable / MB ); dp_writeln( "Used by kmalloc: %8llu KB", kmalloc_mem / KB ); dp_writeln( "Used by initrd: %8llu KB", ramdisk_mem / KB ); dp_writeln( "Used by kernel text + data: %8llu KB", kernel_mem / KB ); dp_writeln( "Tot used: %8llu KB", tot_used / KB ); dp_writeln(""); } static void dp_show_sys_mmap(void) { row = dp_screen_start_row; disable_preemption(); { dump_global_mem_stats(); } enable_preemption(); dp_dump_mmap(); #ifdef arch_x86_family dump_var_mtrrs(); #endif dp_writeln(""); } static struct dp_screen dp_memmap_screen = { .index = 1, .label = "MemMap", .draw_func = dp_show_sys_mmap, .on_keypress_func = NULL, }; __attribute__((constructor)) static void dp_memmap_init(void) { dp_register_screen(&dp_memmap_screen); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include "defs.h" #include "utils.h" #include <multiboot.h> static void PrintModeInfo(EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *mi) { Print(L"Resolution: %u x %u\n", mi->HorizontalResolution, mi->VerticalResolution); if (mi->PixelFormat == PixelRedGreenBlueReserved8BitPerColor) Print(L"PixelFormat: RGB + reserved\n"); else if (mi->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) Print(L"PixelFormat: BGR + reserved\n"); else Print(L"PixelFormat: other\n"); Print(L"PixelsPerScanLine: %u\n", mi->PixelsPerScanLine); } static void PrintModeFullInfo(EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *mode) { Print(L"Framebuffer addr: 0x%x\n", mode->FrameBufferBase); Print(L"Framebuffer size: %u\n", mode->FrameBufferSize); PrintModeInfo(mode->Info); } EFI_STATUS EarlySetDefaultResolution(void) { static EFI_HANDLE handles[32]; /* static: reduce stack usage */ EFI_STATUS status; UINTN handles_buf_size; UINTN handles_count; video_mode_t origMode; video_mode_t chosenMode = INVALID_VIDEO_MODE; ST->ConOut->ClearScreen(ST->ConOut); handles_buf_size = sizeof(handles); status = BS->LocateHandle(ByProtocol, &GraphicsOutputProtocol, NULL, &handles_buf_size, handles); HANDLE_EFI_ERROR("LocateHandle() failed"); handles_count = handles_buf_size / sizeof(EFI_HANDLE); CHECK(handles_count > 0); status = BS->HandleProtocol(handles[0], &GraphicsOutputProtocol, (void **)&gProt); HANDLE_EFI_ERROR("HandleProtocol() failed"); origMode = gProt->Mode->Mode; chosenMode = find_default_video_mode(); if (chosenMode != origMode) { status = gProt->SetMode(gProt, chosenMode); if (EFI_ERROR(status)) { /* Something went wrong: just restore the previous video mode */ status = gProt->SetMode(gProt, origMode); HANDLE_EFI_ERROR("SetMode() failed"); } } end: return status; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(EFI_ARCH ia32) set(GNUEFI_DIR ${TCROOT}/i386/gnu-efi) set_cross_compiler() file(GLOB SOURCES ${GLOB_CONF_DEP} "../*.c") include (../GenericBuild.cmake) <file_sep>/****************************************************************************** * * Module Name: nsconvert - Object conversions for objects returned by * predefined methods * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acinterp.h" #include "acpredef.h" #include "amlresrc.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsconvert") /******************************************************************************* * * FUNCTION: AcpiNsConvertToInteger * * PARAMETERS: OriginalObject - Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful. * * DESCRIPTION: Attempt to convert a String/Buffer object to an Integer. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToInteger ( ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject; ACPI_STATUS Status; UINT64 Value = 0; UINT32 i; switch (OriginalObject->Common.Type) { case ACPI_TYPE_STRING: /* String-to-Integer conversion */ Status = AcpiUtStrtoul64 (OriginalObject->String.Pointer, &Value); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_TYPE_BUFFER: /* Buffer-to-Integer conversion. Max buffer size is 64 bits. */ if (OriginalObject->Buffer.Length > 8) { return (AE_AML_OPERAND_TYPE); } /* Extract each buffer byte to create the integer */ for (i = 0; i < OriginalObject->Buffer.Length; i++) { Value |= ((UINT64) OriginalObject->Buffer.Pointer[i] << (i * 8)); } break; default: return (AE_AML_OPERAND_TYPE); } NewObject = AcpiUtCreateIntegerObject (Value); if (!NewObject) { return (AE_NO_MEMORY); } *ReturnObject = NewObject; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsConvertToString * * PARAMETERS: OriginalObject - Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful. * * DESCRIPTION: Attempt to convert a Integer/Buffer object to a String. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToString ( ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject; ACPI_SIZE Length; ACPI_STATUS Status; switch (OriginalObject->Common.Type) { case ACPI_TYPE_INTEGER: /* * Integer-to-String conversion. Commonly, convert * an integer of value 0 to a NULL string. The last element of * _BIF and _BIX packages occasionally need this fix. */ if (OriginalObject->Integer.Value == 0) { /* Allocate a new NULL string object */ NewObject = AcpiUtCreateStringObject (0); if (!NewObject) { return (AE_NO_MEMORY); } } else { Status = AcpiExConvertToString (OriginalObject, &NewObject, ACPI_IMPLICIT_CONVERT_HEX); if (ACPI_FAILURE (Status)) { return (Status); } } break; case ACPI_TYPE_BUFFER: /* * Buffer-to-String conversion. Use a ToString * conversion, no transform performed on the buffer data. The best * example of this is the _BIF method, where the string data from * the battery is often (incorrectly) returned as buffer object(s). */ Length = 0; while ((Length < OriginalObject->Buffer.Length) && (OriginalObject->Buffer.Pointer[Length])) { Length++; } /* Allocate a new string object */ NewObject = AcpiUtCreateStringObject (Length); if (!NewObject) { return (AE_NO_MEMORY); } /* * Copy the raw buffer data with no transform. String is already NULL * terminated at Length+1. */ memcpy (NewObject->String.Pointer, OriginalObject->Buffer.Pointer, Length); break; default: return (AE_AML_OPERAND_TYPE); } *ReturnObject = NewObject; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsConvertToBuffer * * PARAMETERS: OriginalObject - Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful. * * DESCRIPTION: Attempt to convert a Integer/String/Package object to a Buffer. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToBuffer ( ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject; ACPI_STATUS Status; ACPI_OPERAND_OBJECT **Elements; UINT32 *DwordBuffer; UINT32 Count; UINT32 i; switch (OriginalObject->Common.Type) { case ACPI_TYPE_INTEGER: /* * Integer-to-Buffer conversion. * Convert the Integer to a packed-byte buffer. _MAT and other * objects need this sometimes, if a read has been performed on a * Field object that is less than or equal to the global integer * size (32 or 64 bits). */ Status = AcpiExConvertToBuffer (OriginalObject, &NewObject); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_TYPE_STRING: /* String-to-Buffer conversion. Simple data copy */ NewObject = AcpiUtCreateBufferObject (OriginalObject->String.Length); if (!NewObject) { return (AE_NO_MEMORY); } memcpy (NewObject->Buffer.Pointer, OriginalObject->String.Pointer, OriginalObject->String.Length); break; case ACPI_TYPE_PACKAGE: /* * This case is often seen for predefined names that must return a * Buffer object with multiple DWORD integers within. For example, * _FDE and _GTM. The Package can be converted to a Buffer. */ /* All elements of the Package must be integers */ Elements = OriginalObject->Package.Elements; Count = OriginalObject->Package.Count; for (i = 0; i < Count; i++) { if ((!*Elements) || ((*Elements)->Common.Type != ACPI_TYPE_INTEGER)) { return (AE_AML_OPERAND_TYPE); } Elements++; } /* Create the new buffer object to replace the Package */ NewObject = AcpiUtCreateBufferObject (ACPI_MUL_4 (Count)); if (!NewObject) { return (AE_NO_MEMORY); } /* Copy the package elements (integers) to the buffer as DWORDs */ Elements = OriginalObject->Package.Elements; DwordBuffer = ACPI_CAST_PTR (UINT32, NewObject->Buffer.Pointer); for (i = 0; i < Count; i++) { *DwordBuffer = (UINT32) (*Elements)->Integer.Value; DwordBuffer++; Elements++; } break; default: return (AE_AML_OPERAND_TYPE); } *ReturnObject = NewObject; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsConvertToUnicode * * PARAMETERS: Scope - Namespace node for the method/object * OriginalObject - ASCII String Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful. * * DESCRIPTION: Attempt to convert a String object to a Unicode string Buffer. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToUnicode ( ACPI_NAMESPACE_NODE *Scope, ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject; char *AsciiString; UINT16 *UnicodeBuffer; UINT32 UnicodeLength; UINT32 i; if (!OriginalObject) { return (AE_OK); } /* If a Buffer was returned, it must be at least two bytes long */ if (OriginalObject->Common.Type == ACPI_TYPE_BUFFER) { if (OriginalObject->Buffer.Length < 2) { return (AE_AML_OPERAND_VALUE); } *ReturnObject = NULL; return (AE_OK); } /* * The original object is an ASCII string. Convert this string to * a unicode buffer. */ AsciiString = OriginalObject->String.Pointer; UnicodeLength = (OriginalObject->String.Length * 2) + 2; /* Create a new buffer object for the Unicode data */ NewObject = AcpiUtCreateBufferObject (UnicodeLength); if (!NewObject) { return (AE_NO_MEMORY); } UnicodeBuffer = ACPI_CAST_PTR (UINT16, NewObject->Buffer.Pointer); /* Convert ASCII to Unicode */ for (i = 0; i < OriginalObject->String.Length; i++) { UnicodeBuffer[i] = (UINT16) AsciiString[i]; } *ReturnObject = NewObject; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsConvertToResource * * PARAMETERS: Scope - Namespace node for the method/object * OriginalObject - Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful * * DESCRIPTION: Attempt to convert a Integer object to a ResourceTemplate * Buffer. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToResource ( ACPI_NAMESPACE_NODE *Scope, ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject; UINT8 *Buffer; /* * We can fix the following cases for an expected resource template: * 1. No return value (interpreter slack mode is disabled) * 2. A "Return (Zero)" statement * 3. A "Return empty buffer" statement * * We will return a buffer containing a single EndTag * resource descriptor. */ if (OriginalObject) { switch (OriginalObject->Common.Type) { case ACPI_TYPE_INTEGER: /* We can only repair an Integer==0 */ if (OriginalObject->Integer.Value) { return (AE_AML_OPERAND_TYPE); } break; case ACPI_TYPE_BUFFER: if (OriginalObject->Buffer.Length) { /* Additional checks can be added in the future */ *ReturnObject = NULL; return (AE_OK); } break; case ACPI_TYPE_STRING: default: return (AE_AML_OPERAND_TYPE); } } /* Create the new buffer object for the resource descriptor */ NewObject = AcpiUtCreateBufferObject (2); if (!NewObject) { return (AE_NO_MEMORY); } Buffer = ACPI_CAST_PTR (UINT8, NewObject->Buffer.Pointer); /* Initialize the Buffer with a single EndTag descriptor */ Buffer[0] = (ACPI_RESOURCE_NAME_END_TAG | ASL_RDESC_END_TAG_SIZE); Buffer[1] = 0x00; *ReturnObject = NewObject; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsConvertToReference * * PARAMETERS: Scope - Namespace node for the method/object * OriginalObject - Object to be converted * ReturnObject - Where the new converted object is returned * * RETURN: Status. AE_OK if conversion was successful * * DESCRIPTION: Attempt to convert a Integer object to a ObjectReference. * Buffer. * ******************************************************************************/ ACPI_STATUS AcpiNsConvertToReference ( ACPI_NAMESPACE_NODE *Scope, ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ReturnObject) { ACPI_OPERAND_OBJECT *NewObject = NULL; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_GENERIC_STATE ScopeInfo; char *Name; ACPI_FUNCTION_NAME (NsConvertToReference); /* Convert path into internal presentation */ Status = AcpiNsInternalizeName (OriginalObject->String.Pointer, &Name); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Find the namespace node */ ScopeInfo.Scope.Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Scope); Status = AcpiNsLookup (&ScopeInfo, Name, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, NULL, &Node); if (ACPI_FAILURE (Status)) { /* Check if we are resolving a named reference within a package */ ACPI_ERROR_NAMESPACE (&ScopeInfo, OriginalObject->String.Pointer, Status); goto ErrorExit; } /* Create and init a new internal ACPI object */ NewObject = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_REFERENCE); if (!NewObject) { Status = AE_NO_MEMORY; goto ErrorExit; } NewObject->Reference.Node = Node; NewObject->Reference.Object = Node->Object; NewObject->Reference.Class = ACPI_REFCLASS_NAME; /* * Increase reference of the object if needed (the object is likely a * null for device nodes). */ AcpiUtAddReference (Node->Object); ErrorExit: ACPI_FREE (Name); *ReturnObject = NewObject; return (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* literal string */ static offt sys_str_literal_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); if (data) return snprintk(buf, (size_t)buf_sz, "%s\n", data); return 0; } const struct sysobj_prop_type sysobj_ptype_ro_string_literal = { .load = &sys_str_literal_load }; /* literal ulong */ static offt sys_ulong_literal_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); return snprintk(buf, (size_t)buf_sz, "%lu\n", (ulong)data); } const struct sysobj_prop_type sysobj_ptype_ro_ulong_literal = { .load = &sys_ulong_literal_load }; /* literal ulong_hex */ static offt sys_ulong_hex_literal_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); return snprintk(buf, (size_t)buf_sz, "%#lx\n", (ulong)data); } const struct sysobj_prop_type sysobj_ptype_ro_ulong_hex_literal = { .load = &sys_ulong_hex_literal_load }; /* ulong */ static offt sys_ulong_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); const ulong val = *(ulong *)data; return snprintk(buf, (size_t)buf_sz, "%lu\n", val); } static offt sys_ulong_store(struct sysobj *obj, void *data, void *buf, offt buf_sz) { int err = 0; ulong val; char tmp[32] = {0}; memcpy(tmp, buf, (size_t)MAX(buf_sz, 31)); val = tilck_strtoul(tmp, NULL, 10, &err); if (!err) *(ulong *)data = val; /* * We MUST always return `buf_sz` to make sure userland code believes the * whole buffer was consumed. Otherwise, it will get stuck re-trying forever * to write to this property (which from userland is just a regular file). */ return buf_sz; } const struct sysobj_prop_type sysobj_ptype_rw_ulong = { .load = &sys_ulong_load, .store = &sys_ulong_store, }; const struct sysobj_prop_type sysobj_ptype_ro_ulong = { .load = &sys_ulong_load, }; /* long */ static offt sys_long_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); const long val = *(long *)data; return snprintk(buf, (size_t)buf_sz, "%ld\n", val); } static offt sys_long_store(struct sysobj *obj, void *data, void *buf, offt buf_sz) { int err = 0; long val; char tmp[32] = {0}; memcpy(tmp, buf, (size_t)MAX(buf_sz, (offt)sizeof(tmp) - 1)); val = tilck_strtol(tmp, NULL, 10, &err); if (!err) *(long *)data = val; /* * We MUST always return `buf_sz` to make sure userland code believes the * whole buffer was consumed. Otherwise, it will get stuck re-trying forever * to write to this property (which from userland is just a regular file). */ return buf_sz; } const struct sysobj_prop_type sysobj_ptype_rw_long = { .load = &sys_long_load, .store = &sys_long_store, }; const struct sysobj_prop_type sysobj_ptype_ro_long = { .load = &sys_long_load, .store = NULL, }; /* bool */ static offt sys_bool_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); return snprintk(buf, (size_t)buf_sz, "%u\n", *(bool *)data); } static offt sys_bool_store(struct sysobj *obj, void *data, void *buf, offt buf_sz) { char *s = buf; if (s[0] == '0' || s[1] == '1') { if (!s[1] || s[1] == '\n' || s[1] == '\r') { *(bool *)data = s[0] - '0'; } } return buf_sz; } const struct sysobj_prop_type sysobj_ptype_rw_bool = { .load = &sys_bool_load, .store = &sys_bool_store, }; const struct sysobj_prop_type sysobj_ptype_ro_bool = { .load = &sys_bool_load, }; /* config string */ static offt sys_config_str_load(struct sysobj *obj, void *data, void *buf, offt buf_sz, offt off) { ASSERT(off == 0); struct sysfs_buffer *str = data; return (offt)snprintk(buf, (size_t)buf_sz, "%s\n", str->buf); } static offt sys_config_str_store(struct sysobj *obj, void *data, void *buf, offt buf_sz) { struct sysfs_buffer *str = data; offt len = 0, lim = MIN(buf_sz, (offt)str->buf_sz - 1); char *dest = str->buf; for (char *p = buf; *p && *p != '\n' && len < lim; p++, len++) { *dest++ = *p; } *dest = 0; return buf_sz; } const struct sysobj_prop_type sysobj_ptype_rw_config_str = { .load = &sys_config_str_load, .store = &sys_config_str_store, }; const struct sysobj_prop_type sysobj_ptype_ro_config_str = { .load = &sys_config_str_load, }; /* immutable data */ offt sysobj_imm_data_get_buf_sz(struct sysobj *obj, void *prop_data) { struct sysfs_buffer *buf = prop_data; return -(offt)buf->buf_sz; } void * sysobj_imm_data_get_data_ptr(struct sysobj *obj, void *prop_data) { struct sysfs_buffer *databuf = prop_data; return databuf->buf; } static offt sys_imm_data_load(struct sysobj *obj, void *prop_data, void *buf, offt buf_sz, offt off) { struct sysfs_buffer *databuf = prop_data; offt to_read; /* * This is the only case where `off` is allowed to be > 0. * Note: we're returning -size in our get_buf_sz() func. */ off = CLAMP(off, 0, (offt)databuf->buf_sz); to_read = MIN((offt)databuf->buf_sz - off, buf_sz); memcpy(buf, databuf->buf + off, (size_t)to_read); return to_read; } const struct sysobj_prop_type sysobj_ptype_imm_data = { .get_buf_sz = &sysobj_imm_data_get_buf_sz, .load = &sys_imm_data_load, .get_data_ptr = &sysobj_imm_data_get_data_ptr, }; /* mutable data buffer */ offt sysobj_databuf_get_buf_sz(struct sysobj *obj, void *prop_data) { struct sysfs_buffer *buf = prop_data; return (offt)buf->buf_sz; } static offt sys_databuf_load(struct sysobj *obj, void *prop_data, void *dest, offt dest_buf_sz, offt off) { ASSERT(off == 0); struct sysfs_buffer *databuf = prop_data; offt to_read = MIN(dest_buf_sz, (offt)databuf->used); memcpy(dest, databuf->buf, (size_t)to_read); return to_read; } static offt sys_databuf_store(struct sysobj *obj, void *prop_data, void *src, offt src_buf_sz) { struct sysfs_buffer *databuf = prop_data; offt to_write = MIN(src_buf_sz, (offt)databuf->buf_sz); memcpy(databuf->buf, src, (size_t)to_write); databuf->used = (u32)to_write; return src_buf_sz; } const struct sysobj_prop_type sysobj_ptype_databuf = { .get_buf_sz = &sysobj_databuf_get_buf_sz, .load = &sys_databuf_load, .store = &sys_databuf_store, }; <file_sep>/******************************************************************************* * * Module Name: dbcmds - Miscellaneous debug commands and output routines * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acevents.h" #include "acdebug.h" #include "acnamesp.h" #include "acresrc.h" #include "actables.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbcmds") /* Local prototypes */ static void AcpiDmCompareAmlResources ( UINT8 *Aml1Buffer, ACPI_RSDESC_SIZE Aml1BufferLength, UINT8 *Aml2Buffer, ACPI_RSDESC_SIZE Aml2BufferLength); static ACPI_STATUS AcpiDmTestResourceConversion ( ACPI_NAMESPACE_NODE *Node, char *Name); static ACPI_STATUS AcpiDbResourceCallback ( ACPI_RESOURCE *Resource, void *Context); static ACPI_STATUS AcpiDbDeviceResources ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static void AcpiDbDoOneSleepState ( UINT8 SleepState); static char *AcpiDbTraceMethodName = NULL; /******************************************************************************* * * FUNCTION: AcpiDbConvertToNode * * PARAMETERS: InString - String to convert * * RETURN: Pointer to a NS node * * DESCRIPTION: Convert a string to a valid NS pointer. Handles numeric or * alphanumeric strings. * ******************************************************************************/ ACPI_NAMESPACE_NODE * AcpiDbConvertToNode ( char *InString) { ACPI_NAMESPACE_NODE *Node; ACPI_SIZE Address; if ((*InString >= 0x30) && (*InString <= 0x39)) { /* Numeric argument, convert */ Address = strtoul (InString, NULL, 16); Node = ACPI_TO_POINTER (Address); if (!AcpiOsReadable (Node, sizeof (ACPI_NAMESPACE_NODE))) { AcpiOsPrintf ("Address %p is invalid", Node); return (NULL); } /* Make sure pointer is valid NS node */ if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED) { AcpiOsPrintf ("Address %p is not a valid namespace node [%s]\n", Node, AcpiUtGetDescriptorName (Node)); return (NULL); } } else { /* * Alpha argument: The parameter is a name string that must be * resolved to a Namespace object. */ Node = AcpiDbLocalNsLookup (InString); if (!Node) { AcpiOsPrintf ( "Could not find [%s] in namespace, defaulting to root node\n", InString); Node = AcpiGbl_RootNode; } } return (Node); } /******************************************************************************* * * FUNCTION: AcpiDbSleep * * PARAMETERS: ObjectArg - Desired sleep state (0-5). NULL means * invoke all possible sleep states. * * RETURN: Status * * DESCRIPTION: Simulate sleep/wake sequences * ******************************************************************************/ ACPI_STATUS AcpiDbSleep ( char *ObjectArg) { UINT8 SleepState; UINT32 i; ACPI_FUNCTION_TRACE (AcpiDbSleep); /* Null input (no arguments) means to invoke all sleep states */ if (!ObjectArg) { AcpiOsPrintf ("Invoking all possible sleep states, 0-%d\n", ACPI_S_STATES_MAX); for (i = 0; i <= ACPI_S_STATES_MAX; i++) { AcpiDbDoOneSleepState ((UINT8) i); } return_ACPI_STATUS (AE_OK); } /* Convert argument to binary and invoke the sleep state */ SleepState = (UINT8) strtoul (ObjectArg, NULL, 0); AcpiDbDoOneSleepState (SleepState); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbDoOneSleepState * * PARAMETERS: SleepState - Desired sleep state (0-5) * * RETURN: None * * DESCRIPTION: Simulate a sleep/wake sequence * ******************************************************************************/ static void AcpiDbDoOneSleepState ( UINT8 SleepState) { ACPI_STATUS Status; UINT8 SleepTypeA; UINT8 SleepTypeB; /* Validate parameter */ if (SleepState > ACPI_S_STATES_MAX) { AcpiOsPrintf ("Sleep state %d out of range (%d max)\n", SleepState, ACPI_S_STATES_MAX); return; } AcpiOsPrintf ("\n---- Invoking sleep state S%d (%s):\n", SleepState, AcpiGbl_SleepStateNames[SleepState]); /* Get the values for the sleep type registers (for display only) */ Status = AcpiGetSleepTypeData (SleepState, &SleepTypeA, &SleepTypeB); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not evaluate [%s] method, %s\n", AcpiGbl_SleepStateNames[SleepState], AcpiFormatException (Status)); return; } AcpiOsPrintf ( "Register values for sleep state S%d: Sleep-A: %.2X, Sleep-B: %.2X\n", SleepState, SleepTypeA, SleepTypeB); /* Invoke the various sleep/wake interfaces */ AcpiOsPrintf ("**** Sleep: Prepare to sleep (S%d) ****\n", SleepState); Status = AcpiEnterSleepStatePrep (SleepState); if (ACPI_FAILURE (Status)) { goto ErrorExit; } AcpiOsPrintf ("**** Sleep: Going to sleep (S%d) ****\n", SleepState); Status = AcpiEnterSleepState (SleepState); if (ACPI_FAILURE (Status)) { goto ErrorExit; } AcpiOsPrintf ("**** Wake: Prepare to return from sleep (S%d) ****\n", SleepState); Status = AcpiLeaveSleepStatePrep (SleepState); if (ACPI_FAILURE (Status)) { goto ErrorExit; } AcpiOsPrintf ("**** Wake: Return from sleep (S%d) ****\n", SleepState); Status = AcpiLeaveSleepState (SleepState); if (ACPI_FAILURE (Status)) { goto ErrorExit; } return; ErrorExit: ACPI_EXCEPTION ((AE_INFO, Status, "During invocation of sleep state S%d", SleepState)); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayLocks * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display information about internal mutexes. * ******************************************************************************/ void AcpiDbDisplayLocks ( void) { UINT32 i; for (i = 0; i < ACPI_MAX_MUTEX; i++) { AcpiOsPrintf ("%26s : %s\n", AcpiUtGetMutexName (i), AcpiGbl_MutexInfo[i].ThreadId == ACPI_MUTEX_NOT_ACQUIRED ? "Locked" : "Unlocked"); } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayTableInfo * * PARAMETERS: TableArg - Name of table to be displayed * * RETURN: None * * DESCRIPTION: Display information about loaded tables. Current * implementation displays all loaded tables. * ******************************************************************************/ void AcpiDbDisplayTableInfo ( char *TableArg) { UINT32 i; ACPI_TABLE_DESC *TableDesc; ACPI_STATUS Status; /* Header */ AcpiOsPrintf ("Idx ID Status Type " "TableHeader (Sig, Address, Length, Misc)\n"); /* Walk the entire root table list */ for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; i++) { TableDesc = &AcpiGbl_RootTableList.Tables[i]; /* Index and Table ID */ AcpiOsPrintf ("%3u %.2u ", i, TableDesc->OwnerId); /* Decode the table flags */ if (!(TableDesc->Flags & ACPI_TABLE_IS_LOADED)) { AcpiOsPrintf ("NotLoaded "); } else { AcpiOsPrintf (" Loaded "); } switch (TableDesc->Flags & ACPI_TABLE_ORIGIN_MASK) { case ACPI_TABLE_ORIGIN_EXTERNAL_VIRTUAL: AcpiOsPrintf ("External/virtual "); break; case ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL: AcpiOsPrintf ("Internal/physical "); break; case ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL: AcpiOsPrintf ("Internal/virtual "); break; default: AcpiOsPrintf ("INVALID TYPE "); break; } /* Make sure that the table is mapped */ Status = AcpiTbValidateTable (TableDesc); if (ACPI_FAILURE (Status)) { return; } /* Dump the table header */ if (TableDesc->Pointer) { AcpiTbPrintTableHeader (TableDesc->Address, TableDesc->Pointer); } else { /* If the pointer is null, the table has been unloaded */ ACPI_INFO (("%4.4s - Table has been unloaded", TableDesc->Signature.Ascii)); } } } /******************************************************************************* * * FUNCTION: AcpiDbUnloadAcpiTable * * PARAMETERS: ObjectName - Namespace pathname for an object that * is owned by the table to be unloaded * * RETURN: None * * DESCRIPTION: Unload an ACPI table, via any namespace node that is owned * by the table. * ******************************************************************************/ void AcpiDbUnloadAcpiTable ( char *ObjectName) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; /* Translate name to an Named object */ Node = AcpiDbConvertToNode (ObjectName); if (!Node) { return; } Status = AcpiUnloadParentTable (ACPI_CAST_PTR (ACPI_HANDLE, Node)); if (ACPI_SUCCESS (Status)) { AcpiOsPrintf ("Parent of [%s] (%p) unloaded and uninstalled\n", ObjectName, Node); } else { AcpiOsPrintf ("%s, while unloading parent table of [%s]\n", AcpiFormatException (Status), ObjectName); } } /******************************************************************************* * * FUNCTION: AcpiDbSendNotify * * PARAMETERS: Name - Name of ACPI object where to send notify * Value - Value of the notify to send. * * RETURN: None * * DESCRIPTION: Send an ACPI notification. The value specified is sent to the * named object as an ACPI notify. * ******************************************************************************/ void AcpiDbSendNotify ( char *Name, UINT32 Value) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; /* Translate name to an Named object */ Node = AcpiDbConvertToNode (Name); if (!Node) { return; } /* Dispatch the notify if legal */ if (AcpiEvIsNotifyObject (Node)) { Status = AcpiEvQueueNotifyRequest (Node, Value); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not queue notify\n"); } } else { AcpiOsPrintf ( "Named object [%4.4s] Type %s, " "must be Device/Thermal/Processor type\n", AcpiUtGetNodeName (Node), AcpiUtGetTypeName (Node->Type)); } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayInterfaces * * PARAMETERS: ActionArg - Null, "install", or "remove" * InterfaceNameArg - Name for install/remove options * * RETURN: None * * DESCRIPTION: Display or modify the global _OSI interface list * ******************************************************************************/ void AcpiDbDisplayInterfaces ( char *ActionArg, char *InterfaceNameArg) { ACPI_INTERFACE_INFO *NextInterface; char *SubString; ACPI_STATUS Status; /* If no arguments, just display current interface list */ if (!ActionArg) { (void) AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); NextInterface = AcpiGbl_SupportedInterfaces; while (NextInterface) { if (!(NextInterface->Flags & ACPI_OSI_INVALID)) { AcpiOsPrintf ("%s\n", NextInterface->Name); } NextInterface = NextInterface->Next; } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return; } /* If ActionArg exists, so must InterfaceNameArg */ if (!InterfaceNameArg) { AcpiOsPrintf ("Missing Interface Name argument\n"); return; } /* Uppercase the action for match below */ AcpiUtStrupr (ActionArg); /* Install - install an interface */ SubString = strstr ("INSTALL", ActionArg); if (SubString) { Status = AcpiInstallInterface (InterfaceNameArg); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s, while installing \"%s\"\n", AcpiFormatException (Status), InterfaceNameArg); } return; } /* Remove - remove an interface */ SubString = strstr ("REMOVE", ActionArg); if (SubString) { Status = AcpiRemoveInterface (InterfaceNameArg); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s, while removing \"%s\"\n", AcpiFormatException (Status), InterfaceNameArg); } return; } /* Invalid ActionArg */ AcpiOsPrintf ("Invalid action argument: %s\n", ActionArg); return; } /******************************************************************************* * * FUNCTION: AcpiDbDisplayTemplate * * PARAMETERS: BufferArg - Buffer name or address * * RETURN: None * * DESCRIPTION: Dump a buffer that contains a resource template * ******************************************************************************/ void AcpiDbDisplayTemplate ( char *BufferArg) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_BUFFER ReturnBuffer; /* Translate BufferArg to an Named object */ Node = AcpiDbConvertToNode (BufferArg); if (!Node || (Node == AcpiGbl_RootNode)) { AcpiOsPrintf ("Invalid argument: %s\n", BufferArg); return; } /* We must have a buffer object */ if (Node->Type != ACPI_TYPE_BUFFER) { AcpiOsPrintf ("Not a Buffer object, cannot be a template: %s\n", BufferArg); return; } ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; ReturnBuffer.Pointer = AcpiGbl_DbBuffer; /* Attempt to convert the raw buffer to a resource list */ Status = AcpiRsCreateResourceList (Node->Object, &ReturnBuffer); AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiDbgLevel |= ACPI_LV_RESOURCES; if (ACPI_FAILURE (Status)) { AcpiOsPrintf ( "Could not convert Buffer to a resource list: %s, %s\n", BufferArg, AcpiFormatException (Status)); goto DumpBuffer; } /* Now we can dump the resource list */ AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE, ReturnBuffer.Pointer)); DumpBuffer: AcpiOsPrintf ("\nRaw data buffer:\n"); AcpiUtDebugDumpBuffer ((UINT8 *) Node->Object->Buffer.Pointer, Node->Object->Buffer.Length, DB_BYTE_DISPLAY, ACPI_UINT32_MAX); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); return; } /******************************************************************************* * * FUNCTION: AcpiDmCompareAmlResources * * PARAMETERS: Aml1Buffer - Contains first resource list * Aml1BufferLength - Length of first resource list * Aml2Buffer - Contains second resource list * Aml2BufferLength - Length of second resource list * * RETURN: None * * DESCRIPTION: Compare two AML resource lists, descriptor by descriptor (in * order to isolate a miscompare to an individual resource) * ******************************************************************************/ static void AcpiDmCompareAmlResources ( UINT8 *Aml1Buffer, ACPI_RSDESC_SIZE Aml1BufferLength, UINT8 *Aml2Buffer, ACPI_RSDESC_SIZE Aml2BufferLength) { UINT8 *Aml1; UINT8 *Aml2; UINT8 *Aml1End; UINT8 *Aml2End; ACPI_RSDESC_SIZE Aml1Length; ACPI_RSDESC_SIZE Aml2Length; ACPI_RSDESC_SIZE Offset = 0; UINT8 ResourceType; UINT32 Count = 0; UINT32 i; /* Compare overall buffer sizes (may be different due to size rounding) */ if (Aml1BufferLength != Aml2BufferLength) { AcpiOsPrintf ( "**** Buffer length mismatch in converted " "AML: Original %X, New %X ****\n", Aml1BufferLength, Aml2BufferLength); } Aml1 = Aml1Buffer; Aml2 = Aml2Buffer; Aml1End = Aml1Buffer + Aml1BufferLength; Aml2End = Aml2Buffer + Aml2BufferLength; /* Walk the descriptor lists, comparing each descriptor */ while ((Aml1 < Aml1End) && (Aml2 < Aml2End)) { /* Get the lengths of each descriptor */ Aml1Length = AcpiUtGetDescriptorLength (Aml1); Aml2Length = AcpiUtGetDescriptorLength (Aml2); ResourceType = AcpiUtGetResourceType (Aml1); /* Check for descriptor length match */ if (Aml1Length != Aml2Length) { AcpiOsPrintf ( "**** Length mismatch in descriptor [%.2X] type %2.2X, " "Offset %8.8X Len1 %X, Len2 %X ****\n", Count, ResourceType, Offset, Aml1Length, Aml2Length); } /* Check for descriptor byte match */ else if (memcmp (Aml1, Aml2, Aml1Length)) { AcpiOsPrintf ( "**** Data mismatch in descriptor [%.2X] type %2.2X, " "Offset %8.8X ****\n", Count, ResourceType, Offset); for (i = 0; i < Aml1Length; i++) { if (Aml1[i] != Aml2[i]) { AcpiOsPrintf ( "Mismatch at byte offset %.2X: is %2.2X, " "should be %2.2X\n", i, Aml2[i], Aml1[i]); } } } /* Exit on EndTag descriptor */ if (ResourceType == ACPI_RESOURCE_NAME_END_TAG) { return; } /* Point to next descriptor in each buffer */ Count++; Offset += Aml1Length; Aml1 += Aml1Length; Aml2 += Aml2Length; } } /******************************************************************************* * * FUNCTION: AcpiDmTestResourceConversion * * PARAMETERS: Node - Parent device node * Name - resource method name (_CRS) * * RETURN: Status * * DESCRIPTION: Compare the original AML with a conversion of the AML to * internal resource list, then back to AML. * ******************************************************************************/ static ACPI_STATUS AcpiDmTestResourceConversion ( ACPI_NAMESPACE_NODE *Node, char *Name) { ACPI_STATUS Status; ACPI_BUFFER ReturnBuffer; ACPI_BUFFER ResourceBuffer; ACPI_BUFFER NewAml; ACPI_OBJECT *OriginalAml; AcpiOsPrintf ("Resource Conversion Comparison:\n"); NewAml.Length = ACPI_ALLOCATE_LOCAL_BUFFER; ReturnBuffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; ResourceBuffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; /* Get the original _CRS AML resource template */ Status = AcpiEvaluateObject (Node, Name, NULL, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not obtain %s: %s\n", Name, AcpiFormatException (Status)); return (Status); } /* Get the AML resource template, converted to internal resource structs */ Status = AcpiGetCurrentResources (Node, &ResourceBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiGetCurrentResources failed: %s\n", AcpiFormatException (Status)); goto Exit1; } /* Convert internal resource list to external AML resource template */ Status = AcpiRsCreateAmlResources (&ResourceBuffer, &NewAml); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiRsCreateAmlResources failed: %s\n", AcpiFormatException (Status)); goto Exit2; } /* Compare original AML to the newly created AML resource list */ OriginalAml = ReturnBuffer.Pointer; AcpiDmCompareAmlResources (OriginalAml->Buffer.Pointer, (ACPI_RSDESC_SIZE) OriginalAml->Buffer.Length, NewAml.Pointer, (ACPI_RSDESC_SIZE) NewAml.Length); /* Cleanup and exit */ ACPI_FREE (NewAml.Pointer); Exit2: ACPI_FREE (ResourceBuffer.Pointer); Exit1: ACPI_FREE (ReturnBuffer.Pointer); return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbResourceCallback * * PARAMETERS: ACPI_WALK_RESOURCE_CALLBACK * * RETURN: Status * * DESCRIPTION: Simple callback to exercise AcpiWalkResources and * AcpiWalkResourceBuffer. * ******************************************************************************/ static ACPI_STATUS AcpiDbResourceCallback ( ACPI_RESOURCE *Resource, void *Context) { return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbDeviceResources * * PARAMETERS: ACPI_WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Display the _PRT/_CRS/_PRS resources for a device object. * ******************************************************************************/ static ACPI_STATUS AcpiDbDeviceResources ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node; ACPI_NAMESPACE_NODE *PrtNode = NULL; ACPI_NAMESPACE_NODE *CrsNode = NULL; ACPI_NAMESPACE_NODE *PrsNode = NULL; ACPI_NAMESPACE_NODE *AeiNode = NULL; char *ParentPath; ACPI_BUFFER ReturnBuffer; ACPI_STATUS Status; Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjHandle); ParentPath = AcpiNsGetNormalizedPathname (Node, TRUE); if (!ParentPath) { return (AE_NO_MEMORY); } /* Get handles to the resource methods for this device */ (void) AcpiGetHandle (Node, METHOD_NAME__PRT, ACPI_CAST_PTR (ACPI_HANDLE, &PrtNode)); (void) AcpiGetHandle (Node, METHOD_NAME__CRS, ACPI_CAST_PTR (ACPI_HANDLE, &CrsNode)); (void) AcpiGetHandle (Node, METHOD_NAME__PRS, ACPI_CAST_PTR (ACPI_HANDLE, &PrsNode)); (void) AcpiGetHandle (Node, METHOD_NAME__AEI, ACPI_CAST_PTR (ACPI_HANDLE, &AeiNode)); if (!PrtNode && !CrsNode && !PrsNode && !AeiNode) { goto Cleanup; /* Nothing to do */ } AcpiOsPrintf ("\nDevice: %s\n", ParentPath); /* Prepare for a return object of arbitrary size */ ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; /* _PRT */ if (PrtNode) { AcpiOsPrintf ("Evaluating _PRT\n"); Status = AcpiEvaluateObject (PrtNode, NULL, NULL, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not evaluate _PRT: %s\n", AcpiFormatException (Status)); goto GetCrs; } ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiGetIrqRoutingTable (Node, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("GetIrqRoutingTable failed: %s\n", AcpiFormatException (Status)); goto GetCrs; } AcpiRsDumpIrqList (ACPI_CAST_PTR (UINT8, AcpiGbl_DbBuffer)); } /* _CRS */ GetCrs: if (CrsNode) { AcpiOsPrintf ("Evaluating _CRS\n"); ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiEvaluateObject (CrsNode, NULL, NULL, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not evaluate _CRS: %s\n", AcpiFormatException (Status)); goto GetPrs; } /* This code exercises the AcpiWalkResources interface */ Status = AcpiWalkResources (Node, METHOD_NAME__CRS, AcpiDbResourceCallback, NULL); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiWalkResources failed: %s\n", AcpiFormatException (Status)); goto GetPrs; } /* Get the _CRS resource list (test ALLOCATE buffer) */ ReturnBuffer.Pointer = NULL; ReturnBuffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiGetCurrentResources (Node, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiGetCurrentResources failed: %s\n", AcpiFormatException (Status)); goto GetPrs; } /* This code exercises the AcpiWalkResourceBuffer interface */ Status = AcpiWalkResourceBuffer (&ReturnBuffer, AcpiDbResourceCallback, NULL); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiWalkResourceBuffer failed: %s\n", AcpiFormatException (Status)); goto EndCrs; } /* Dump the _CRS resource list */ AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE, ReturnBuffer.Pointer)); /* * Perform comparison of original AML to newly created AML. This * tests both the AML->Resource conversion and the Resource->AML * conversion. */ (void) AcpiDmTestResourceConversion (Node, METHOD_NAME__CRS); /* Execute _SRS with the resource list */ AcpiOsPrintf ("Evaluating _SRS\n"); Status = AcpiSetCurrentResources (Node, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiSetCurrentResources failed: %s\n", AcpiFormatException (Status)); goto EndCrs; } EndCrs: ACPI_FREE (ReturnBuffer.Pointer); } /* _PRS */ GetPrs: if (PrsNode) { AcpiOsPrintf ("Evaluating _PRS\n"); ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiEvaluateObject (PrsNode, NULL, NULL, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not evaluate _PRS: %s\n", AcpiFormatException (Status)); goto GetAei; } ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiGetPossibleResources (Node, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiGetPossibleResources failed: %s\n", AcpiFormatException (Status)); goto GetAei; } AcpiRsDumpResourceList (ACPI_CAST_PTR ( ACPI_RESOURCE, AcpiGbl_DbBuffer)); } /* _AEI */ GetAei: if (AeiNode) { AcpiOsPrintf ("Evaluating _AEI\n"); ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiEvaluateObject (AeiNode, NULL, NULL, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not evaluate _AEI: %s\n", AcpiFormatException (Status)); goto Cleanup; } ReturnBuffer.Pointer = AcpiGbl_DbBuffer; ReturnBuffer.Length = ACPI_DEBUG_BUFFER_SIZE; Status = AcpiGetEventResources (Node, &ReturnBuffer); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("AcpiGetEventResources failed: %s\n", AcpiFormatException (Status)); goto Cleanup; } AcpiRsDumpResourceList (ACPI_CAST_PTR ( ACPI_RESOURCE, AcpiGbl_DbBuffer)); } Cleanup: ACPI_FREE (ParentPath); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayResources * * PARAMETERS: ObjectArg - String object name or object pointer. * NULL or "*" means "display resources for * all devices" * * RETURN: None * * DESCRIPTION: Display the resource objects associated with a device. * ******************************************************************************/ void AcpiDbDisplayResources ( char *ObjectArg) { ACPI_NAMESPACE_NODE *Node; AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiDbgLevel |= ACPI_LV_RESOURCES; /* Asterisk means "display resources for all devices" */ if (!ObjectArg || (!strcmp (ObjectArg, "*"))) { (void) AcpiWalkNamespace (ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbDeviceResources, NULL, NULL, NULL); } else { /* Convert string to object pointer */ Node = AcpiDbConvertToNode (ObjectArg); if (Node) { if (Node->Type != ACPI_TYPE_DEVICE) { AcpiOsPrintf ( "%4.4s: Name is not a device object (%s)\n", Node->Name.Ascii, AcpiUtGetTypeName (Node->Type)); } else { (void) AcpiDbDeviceResources (Node, 0, NULL, NULL); } } } AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiDbGenerateGpe * * PARAMETERS: GpeArg - Raw GPE number, ascii string * BlockArg - GPE block number, ascii string * 0 or 1 for FADT GPE blocks * * RETURN: None * * DESCRIPTION: Simulate firing of a GPE * ******************************************************************************/ void AcpiDbGenerateGpe ( char *GpeArg, char *BlockArg) { UINT32 BlockNumber = 0; UINT32 GpeNumber; ACPI_GPE_EVENT_INFO *GpeEventInfo; GpeNumber = strtoul (GpeArg, NULL, 0); /* * If no block arg, or block arg == 0 or 1, use the FADT-defined * GPE blocks. */ if (BlockArg) { BlockNumber = strtoul (BlockArg, NULL, 0); if (BlockNumber == 1) { BlockNumber = 0; } } GpeEventInfo = AcpiEvGetGpeEventInfo ( ACPI_TO_POINTER (BlockNumber), GpeNumber); if (!GpeEventInfo) { AcpiOsPrintf ("Invalid GPE\n"); return; } (void) AcpiEvGpeDispatch (NULL, GpeEventInfo, GpeNumber); } /******************************************************************************* * * FUNCTION: AcpiDbGenerateSci * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Simulate an SCI -- just call the SCI dispatch. * ******************************************************************************/ void AcpiDbGenerateSci ( void) { AcpiEvSciDispatch (); } #endif /* !ACPI_REDUCED_HARDWARE */ /******************************************************************************* * * FUNCTION: AcpiDbTrace * * PARAMETERS: EnableArg - ENABLE/AML to enable tracer * DISABLE to disable tracer * MethodArg - Method to trace * OnceArg - Whether trace once * * RETURN: None * * DESCRIPTION: Control method tracing facility * ******************************************************************************/ void AcpiDbTrace ( char *EnableArg, char *MethodArg, char *OnceArg) { UINT32 DebugLevel = 0; UINT32 DebugLayer = 0; UINT32 Flags = 0; AcpiUtStrupr (EnableArg); AcpiUtStrupr (OnceArg); if (MethodArg) { if (AcpiDbTraceMethodName) { ACPI_FREE (AcpiDbTraceMethodName); AcpiDbTraceMethodName = NULL; } AcpiDbTraceMethodName = ACPI_ALLOCATE (strlen (MethodArg) + 1); if (!AcpiDbTraceMethodName) { AcpiOsPrintf ("Failed to allocate method name (%s)\n", MethodArg); return; } strcpy (AcpiDbTraceMethodName, MethodArg); } if (!strcmp (EnableArg, "ENABLE") || !strcmp (EnableArg, "METHOD") || !strcmp (EnableArg, "OPCODE")) { if (!strcmp (EnableArg, "ENABLE")) { /* Inherit current console settings */ DebugLevel = AcpiGbl_DbConsoleDebugLevel; DebugLayer = AcpiDbgLayer; } else { /* Restrict console output to trace points only */ DebugLevel = ACPI_LV_TRACE_POINT; DebugLayer = ACPI_EXECUTER; } Flags = ACPI_TRACE_ENABLED; if (!strcmp (EnableArg, "OPCODE")) { Flags |= ACPI_TRACE_OPCODE; } if (OnceArg && !strcmp (OnceArg, "ONCE")) { Flags |= ACPI_TRACE_ONESHOT; } } (void) AcpiDebugTrace (AcpiDbTraceMethodName, DebugLevel, DebugLayer, Flags); } <file_sep>/****************************************************************************** * * Module Name: dswexec - Dispatcher method execution callbacks; * dispatch to interpreter. * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acdebug.h" #ifdef ACPI_EXEC_APP #include "aecommon.h" #endif #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dswexec") /* * Dispatch table for opcode classes */ static ACPI_EXECUTE_OP AcpiGbl_OpTypeDispatch [] = { AcpiExOpcode_0A_0T_1R, AcpiExOpcode_1A_0T_0R, AcpiExOpcode_1A_0T_1R, AcpiExOpcode_1A_1T_0R, AcpiExOpcode_1A_1T_1R, AcpiExOpcode_2A_0T_0R, AcpiExOpcode_2A_0T_1R, AcpiExOpcode_2A_1T_1R, AcpiExOpcode_2A_2T_1R, AcpiExOpcode_3A_0T_0R, AcpiExOpcode_3A_1T_1R, AcpiExOpcode_6A_0T_1R }; /***************************************************************************** * * FUNCTION: AcpiDsGetPredicateValue * * PARAMETERS: WalkState - Current state of the parse tree walk * ResultObj - if non-zero, pop result from result stack * * RETURN: Status * * DESCRIPTION: Get the result of a predicate evaluation * ****************************************************************************/ ACPI_STATUS AcpiDsGetPredicateValue ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT *ResultObj) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *LocalObjDesc = NULL; ACPI_FUNCTION_TRACE_PTR (DsGetPredicateValue, WalkState); WalkState->ControlState->Common.State = 0; if (ResultObj) { Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not get result from predicate evaluation")); return_ACPI_STATUS (Status); } } else { Status = AcpiDsCreateOperand (WalkState, WalkState->Op, 0); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiExResolveToValue (&WalkState->Operands [0], WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ObjDesc = WalkState->Operands [0]; } if (!ObjDesc) { ACPI_ERROR ((AE_INFO, "No predicate ObjDesc=%p State=%p", ObjDesc, WalkState)); return_ACPI_STATUS (AE_AML_NO_OPERAND); } /* * Result of predicate evaluation must be an Integer * object. Implicitly convert the argument if necessary. */ Status = AcpiExConvertToInteger (ObjDesc, &LocalObjDesc, ACPI_IMPLICIT_CONVERSION); if (ACPI_FAILURE (Status)) { goto Cleanup; } if (LocalObjDesc->Common.Type != ACPI_TYPE_INTEGER) { ACPI_ERROR ((AE_INFO, "Bad predicate (not an integer) ObjDesc=%p State=%p Type=0x%X", ObjDesc, WalkState, ObjDesc->Common.Type)); Status = AE_AML_OPERAND_TYPE; goto Cleanup; } /* Truncate the predicate to 32-bits if necessary */ (void) AcpiExTruncateFor32bitTable (LocalObjDesc); /* * Save the result of the predicate evaluation on * the control stack */ if (LocalObjDesc->Integer.Value) { WalkState->ControlState->Common.Value = TRUE; } else { /* * Predicate is FALSE, we will just toss the * rest of the package */ WalkState->ControlState->Common.Value = FALSE; Status = AE_CTRL_FALSE; } /* Predicate can be used for an implicit return value */ (void) AcpiDsDoImplicitReturn (LocalObjDesc, WalkState, TRUE); Cleanup: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Completed a predicate eval=%X Op=%p\n", WalkState->ControlState->Common.Value, WalkState->Op)); /* Break to debugger to display result */ AcpiDbDisplayResultObject (LocalObjDesc, WalkState); /* * Delete the predicate result object (we know that * we don't need it anymore) */ if (LocalObjDesc != ObjDesc) { AcpiUtRemoveReference (LocalObjDesc); } AcpiUtRemoveReference (ObjDesc); WalkState->ControlState->Common.State = ACPI_CONTROL_NORMAL; return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsExecBeginOp * * PARAMETERS: WalkState - Current state of the parse tree walk * OutOp - Where to return op if a new one is created * * RETURN: Status * * DESCRIPTION: Descending callback used during the execution of control * methods. This is where most operators and operands are * dispatched to the interpreter. * ****************************************************************************/ ACPI_STATUS AcpiDsExecBeginOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **OutOp) { ACPI_PARSE_OBJECT *Op; ACPI_STATUS Status = AE_OK; UINT32 OpcodeClass; ACPI_FUNCTION_TRACE_PTR (DsExecBeginOp, WalkState); Op = WalkState->Op; if (!Op) { Status = AcpiDsLoad2BeginOp (WalkState, OutOp); if (ACPI_FAILURE (Status)) { goto ErrorExit; } Op = *OutOp; WalkState->Op = Op; WalkState->Opcode = Op->Common.AmlOpcode; WalkState->OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); if (AcpiNsOpensScope (WalkState->OpInfo->ObjectType)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "(%s) Popping scope for Op %p\n", AcpiUtGetTypeName (WalkState->OpInfo->ObjectType), Op)); Status = AcpiDsScopeStackPop (WalkState); if (ACPI_FAILURE (Status)) { goto ErrorExit; } } } if (Op == WalkState->Origin) { if (OutOp) { *OutOp = Op; } return_ACPI_STATUS (AE_OK); } /* * If the previous opcode was a conditional, this opcode * must be the beginning of the associated predicate. * Save this knowledge in the current scope descriptor */ if ((WalkState->ControlState) && (WalkState->ControlState->Common.State == ACPI_CONTROL_CONDITIONAL_EXECUTING)) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Exec predicate Op=%p State=%p\n", Op, WalkState)); WalkState->ControlState->Common.State = ACPI_CONTROL_PREDICATE_EXECUTING; /* Save start of predicate */ WalkState->ControlState->Control.PredicateOp = Op; } OpcodeClass = WalkState->OpInfo->Class; /* We want to send namepaths to the load code */ if (Op->Common.AmlOpcode == AML_INT_NAMEPATH_OP) { OpcodeClass = AML_CLASS_NAMED_OBJECT; } /* * Handle the opcode based upon the opcode type */ switch (OpcodeClass) { case AML_CLASS_CONTROL: Status = AcpiDsExecBeginControlOp (WalkState, Op); break; case AML_CLASS_NAMED_OBJECT: if (WalkState->WalkType & ACPI_WALK_METHOD) { /* * Found a named object declaration during method execution; * we must enter this object into the namespace. The created * object is temporary and will be deleted upon completion of * the execution of this method. * * Note 10/2010: Except for the Scope() op. This opcode does * not actually create a new object, it refers to an existing * object. However, for Scope(), we want to indeed open a * new scope. */ if (Op->Common.AmlOpcode != AML_SCOPE_OP) { Status = AcpiDsLoad2BeginOp (WalkState, NULL); } else { Status = AcpiDsScopeStackPush ( Op->Named.Node, Op->Named.Node->Type, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } break; case AML_CLASS_EXECUTE: case AML_CLASS_CREATE: break; default: break; } /* Nothing to do here during method execution */ return_ACPI_STATUS (Status); ErrorExit: Status = AcpiDsMethodError (Status, WalkState); return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsExecEndOp * * PARAMETERS: WalkState - Current state of the parse tree walk * * RETURN: Status * * DESCRIPTION: Ascending callback used during the execution of control * methods. The only thing we really need to do here is to * notice the beginning of IF, ELSE, and WHILE blocks. * ****************************************************************************/ ACPI_STATUS AcpiDsExecEndOp ( ACPI_WALK_STATE *WalkState) { ACPI_PARSE_OBJECT *Op; ACPI_STATUS Status = AE_OK; UINT32 OpType; UINT32 OpClass; ACPI_PARSE_OBJECT *NextOp; ACPI_PARSE_OBJECT *FirstArg; #ifdef ACPI_EXEC_APP char *Namepath; ACPI_OPERAND_OBJECT *ObjDesc; #endif ACPI_FUNCTION_TRACE_PTR (DsExecEndOp, WalkState); Op = WalkState->Op; OpType = WalkState->OpInfo->Type; OpClass = WalkState->OpInfo->Class; if (OpClass == AML_CLASS_UNKNOWN) { ACPI_ERROR ((AE_INFO, "Unknown opcode 0x%X", Op->Common.AmlOpcode)); return_ACPI_STATUS (AE_NOT_IMPLEMENTED); } FirstArg = Op->Common.Value.Arg; /* Init the walk state */ WalkState->NumOperands = 0; WalkState->OperandIndex = 0; WalkState->ReturnDesc = NULL; WalkState->ResultObj = NULL; /* Call debugger for single step support (DEBUG build only) */ Status = AcpiDbSingleStep (WalkState, Op, OpClass); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Decode the Opcode Class */ switch (OpClass) { case AML_CLASS_ARGUMENT: /* Constants, literals, etc. */ if (WalkState->Opcode == AML_INT_NAMEPATH_OP) { Status = AcpiDsEvaluateNamePath (WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } } break; case AML_CLASS_EXECUTE: /* Most operators with arguments */ /* Build resolved operand stack */ Status = AcpiDsCreateOperands (WalkState, FirstArg); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* * All opcodes require operand resolution, with the only exceptions * being the ObjectType and SizeOf operators. */ if (!(WalkState->OpInfo->Flags & AML_NO_OPERAND_RESOLVE)) { /* Resolve all operands */ Status = AcpiExResolveOperands (WalkState->Opcode, &(WalkState->Operands [WalkState->NumOperands -1]), WalkState); } if (ACPI_SUCCESS (Status)) { /* * Dispatch the request to the appropriate interpreter handler * routine. There is one routine per opcode "type" based upon the * number of opcode arguments and return type. */ Status = AcpiGbl_OpTypeDispatch[OpType] (WalkState); } else { /* * Treat constructs of the form "Store(LocalX,LocalX)" as noops when the * Local is uninitialized. */ if ((Status == AE_AML_UNINITIALIZED_LOCAL) && (WalkState->Opcode == AML_STORE_OP) && (WalkState->Operands[0]->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) && (WalkState->Operands[1]->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) && (WalkState->Operands[0]->Reference.Class == WalkState->Operands[1]->Reference.Class) && (WalkState->Operands[0]->Reference.Value == WalkState->Operands[1]->Reference.Value)) { Status = AE_OK; } else { ACPI_EXCEPTION ((AE_INFO, Status, "While resolving operands for [%s]", AcpiPsGetOpcodeName (WalkState->Opcode))); } } /* Always delete the argument objects and clear the operand stack */ AcpiDsClearOperands (WalkState); /* * If a result object was returned from above, push it on the * current result stack */ if (ACPI_SUCCESS (Status) && WalkState->ResultObj) { Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); } break; default: switch (OpType) { case AML_TYPE_CONTROL: /* Type 1 opcode, IF/ELSE/WHILE/NOOP */ /* 1 Operand, 0 ExternalResult, 0 InternalResult */ Status = AcpiDsExecEndControlOp (WalkState, Op); break; case AML_TYPE_METHOD_CALL: /* * If the method is referenced from within a package * declaration, it is not a invocation of the method, just * a reference to it. */ if ((Op->Asl.Parent) && ((Op->Asl.Parent->Asl.AmlOpcode == AML_PACKAGE_OP) || (Op->Asl.Parent->Asl.AmlOpcode == AML_VARIABLE_PACKAGE_OP))) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Method Reference in a Package, Op=%p\n", Op)); Op->Common.Node = (ACPI_NAMESPACE_NODE *) Op->Asl.Value.Arg->Asl.Node; AcpiUtAddReference (Op->Asl.Value.Arg->Asl.Node->Object); return_ACPI_STATUS (AE_OK); } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Method invocation, Op=%p\n", Op)); /* * (AML_METHODCALL) Op->Asl.Value.Arg->Asl.Node contains * the method Node pointer */ /* NextOp points to the op that holds the method name */ NextOp = FirstArg; /* NextOp points to first argument op */ NextOp = NextOp->Common.Next; /* * Get the method's arguments and put them on the operand stack */ Status = AcpiDsCreateOperands (WalkState, NextOp); if (ACPI_FAILURE (Status)) { break; } /* * Since the operands will be passed to another control method, * we must resolve all local references here (Local variables, * arguments to *this* method, etc.) */ Status = AcpiDsResolveOperands (WalkState); if (ACPI_FAILURE (Status)) { /* On error, clear all resolved operands */ AcpiDsClearOperands (WalkState); break; } /* * Tell the walk loop to preempt this running method and * execute the new method */ Status = AE_CTRL_TRANSFER; /* * Return now; we don't want to disturb anything, * especially the operand count! */ return_ACPI_STATUS (Status); case AML_TYPE_CREATE_FIELD: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Executing CreateField Buffer/Index Op=%p\n", Op)); Status = AcpiDsLoad2EndOp (WalkState); if (ACPI_FAILURE (Status)) { break; } Status = AcpiDsEvalBufferFieldOperands (WalkState, Op); if (ACPI_FAILURE (Status)) { break; } #ifdef ACPI_EXEC_APP /* * AcpiExec support for namespace initialization file (initialize * BufferFields in this code.) */ Namepath = AcpiNsGetExternalPathname (Op->Common.Node); Status = AeLookupInitFileEntry (Namepath, &ObjDesc); if (ACPI_SUCCESS (Status)) { Status = AcpiExWriteDataToField (ObjDesc, Op->Common.Node->Object, NULL); if ACPI_FAILURE (Status) { ACPI_EXCEPTION ((AE_INFO, Status, "While writing to buffer field")); } } ACPI_FREE (Namepath); Status = AE_OK; #endif break; case AML_TYPE_CREATE_OBJECT: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Executing CreateObject (Buffer/Package) Op=%p Child=%p ParentOpcode=%4.4X\n", Op, Op->Named.Value.Arg, Op->Common.Parent->Common.AmlOpcode)); switch (Op->Common.Parent->Common.AmlOpcode) { case AML_NAME_OP: /* * Put the Node on the object stack (Contains the ACPI Name * of this object) */ WalkState->Operands[0] = (void *) Op->Common.Parent->Common.Node; WalkState->NumOperands = 1; Status = AcpiDsCreateNode (WalkState, Op->Common.Parent->Common.Node, Op->Common.Parent); if (ACPI_FAILURE (Status)) { break; } /* Fall through */ /*lint -fallthrough */ case AML_INT_EVAL_SUBTREE_OP: Status = AcpiDsEvalDataObjectOperands (WalkState, Op, AcpiNsGetAttachedObject (Op->Common.Parent->Common.Node)); break; default: Status = AcpiDsEvalDataObjectOperands (WalkState, Op, NULL); break; } /* * If a result object was returned from above, push it on the * current result stack */ if (WalkState->ResultObj) { Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); } break; case AML_TYPE_NAMED_FIELD: case AML_TYPE_NAMED_COMPLEX: case AML_TYPE_NAMED_SIMPLE: case AML_TYPE_NAMED_NO_OBJ: Status = AcpiDsLoad2EndOp (WalkState); if (ACPI_FAILURE (Status)) { break; } if (Op->Common.AmlOpcode == AML_REGION_OP) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Executing OpRegion Address/Length Op=%p\n", Op)); Status = AcpiDsEvalRegionOperands (WalkState, Op); if (ACPI_FAILURE (Status)) { break; } } else if (Op->Common.AmlOpcode == AML_DATA_REGION_OP) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Executing DataTableRegion Strings Op=%p\n", Op)); Status = AcpiDsEvalTableRegionOperands (WalkState, Op); if (ACPI_FAILURE (Status)) { break; } } else if (Op->Common.AmlOpcode == AML_BANK_FIELD_OP) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Executing BankField Op=%p\n", Op)); Status = AcpiDsEvalBankFieldOperands (WalkState, Op); if (ACPI_FAILURE (Status)) { break; } } break; case AML_TYPE_UNDEFINED: ACPI_ERROR ((AE_INFO, "Undefined opcode type Op=%p", Op)); return_ACPI_STATUS (AE_NOT_IMPLEMENTED); case AML_TYPE_BOGUS: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Internal opcode=%X type Op=%p\n", WalkState->Opcode, Op)); break; default: ACPI_ERROR ((AE_INFO, "Unimplemented opcode, class=0x%X " "type=0x%X Opcode=0x%X Op=%p", OpClass, OpType, Op->Common.AmlOpcode, Op)); Status = AE_NOT_IMPLEMENTED; break; } } /* * ACPI 2.0 support for 64-bit integers: Truncate numeric * result value if we are executing from a 32-bit ACPI table */ (void) AcpiExTruncateFor32bitTable (WalkState->ResultObj); /* * Check if we just completed the evaluation of a * conditional predicate */ if ((ACPI_SUCCESS (Status)) && (WalkState->ControlState) && (WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING) && (WalkState->ControlState->Control.PredicateOp == Op)) { Status = AcpiDsGetPredicateValue (WalkState, WalkState->ResultObj); WalkState->ResultObj = NULL; } Cleanup: if (WalkState->ResultObj) { /* Break to debugger to display result */ AcpiDbDisplayResultObject (WalkState->ResultObj,WalkState); /* * Delete the result op if and only if: * Parent will not use the result -- such as any * non-nested type2 op in a method (parent will be method) */ AcpiDsDeleteResultIfNotUsed (Op, WalkState->ResultObj, WalkState); } #ifdef _UNDER_DEVELOPMENT if (WalkState->ParserState.Aml == WalkState->ParserState.AmlEnd) { AcpiDbMethodEnd (WalkState); } #endif /* Invoke exception handler on error */ if (ACPI_FAILURE (Status)) { Status = AcpiDsMethodError (Status, WalkState); } /* Always clear the object stack */ WalkState->NumOperands = 0; return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/time.h> #include <dirent.h> #include "devshell.h" #include "sysenter.h" #include "test_common.h" void create_test_file1(void); void write_on_test_file1(void); /* Test truncate() */ int cmd_fs7(int argc, char **argv) { int rc; create_test_file1(); write_on_test_file1(); rc = truncate("/tmp/test1", 157); DEVSHELL_CMD_ASSERT(rc == 0); // TODO: add checks here to verify that the truncation worked as expected rc = unlink("/tmp/test1"); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } static const char test_str[] = "this is a test string\n"; static const char test_str2[] = "hello from the 2nd page"; static const char test_str_exp[] = "This is a test string\n"; static const char test_file[] = "/tmp/test1"; void do_mm_read(void *ptr) { unsigned value; printf("[pid: %d] Before read at %p\n", getpid(), ptr); memcpy(&value, ptr, sizeof(value)); printf("Read OK. Value at %p: %#x\n", ptr, value); } /* mmap file */ int cmd_fmmap1(int argc, char **argv) { int fd, rc; char *vaddr; char buf[64]; size_t file_size; struct stat statbuf; const size_t page_size = getpagesize(); printf("- Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, test_str, sizeof(test_str)-1); DEVSHELL_CMD_ASSERT(rc == sizeof(test_str)-1); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("- File size: %llu\n", (ull_t)file_size); vaddr = mmap(NULL, /* addr */ 2 * page_size, /* length */ PROT_READ | PROT_WRITE, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); if (vaddr == (void *)-1) goto err_case; printf("- vaddr: %p\n", vaddr); printf("- Check that reading at `vaddr` succeeds\n"); do_mm_read(vaddr); printf("- Check we can fork() a process with ramfs mmaps\n"); if (test_sig(do_mm_read, vaddr, 0, 0, 0)) goto err_case; printf("- Check that reading at `vaddr` still succeeds from parent\n"); do_mm_read(vaddr); printf("- Done\n"); printf("- Write something at `vaddr`...\n"); vaddr[0] = 'T'; // has real effect printf("- Write something at `vaddr + file_size`\n"); vaddr[file_size + 0] = '?'; // gets ignored as past of EOF vaddr[file_size + 10] = 'x'; // gets ignored as past of EOF vaddr[file_size + 11] = '\n'; // gets ignored as past of EOF printf("- Check that read mapped area past EOF triggers SIGBUS\n"); if (test_sig(do_mm_read, vaddr + page_size, SIGBUS, 0, 0)) goto err_case; printf("- Close the file descriptor and re-open the file\n"); close(fd); rc = stat(test_file, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); DEVSHELL_CMD_ASSERT(statbuf.st_size == file_size); fd = open(test_file, O_RDONLY, 0644); DEVSHELL_CMD_ASSERT(fd > 0); printf("- Check file's contents\n"); rc = read(fd, buf, file_size); DEVSHELL_CMD_ASSERT(rc == file_size); buf[rc] = 0; if (strcmp(buf, test_str_exp)) { fprintf(stderr, "File contents != expected:\n"); fprintf(stderr, "Contents: <<\n%s>>\n", buf); fprintf(stderr, "Expected: <<\n%s>>\n", test_str_exp); DEVSHELL_CMD_ASSERT(false); } printf("- Re-map and check past-EOF contents\n"); vaddr = mmap(NULL, /* addr */ 2 * page_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); if (vaddr == (void *)-1) goto err_case; /* * At least on ext4 on Linux, the past-EOF contents are kept. That's the * simplest behavior to implement for Tilck as well. */ printf("vaddr[file_size + 0]: %c\n", vaddr[file_size + 0]); printf("vaddr[file_size + 10]: %c\n", vaddr[file_size + 10]); DEVSHELL_CMD_ASSERT(vaddr[file_size + 0] == '?'); DEVSHELL_CMD_ASSERT(vaddr[file_size + 10] == 'x'); printf("DONE\n"); close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); return 0; err_case: if (vaddr == (void *)-1) fprintf(stderr, "mmap failed: %s\n", strerror(errno)); close(fd); unlink(test_file); return 1; } /* mmap file and then do a partial unmap */ static void fmmap2_read_unmapped_mem(void *unused_arg) { int fd, rc; char *vaddr; char buf[64] = {0}; char *page_size_buf; const size_t page_size = getpagesize(); printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); page_size_buf = malloc(page_size); DEVSHELL_CMD_ASSERT(page_size_buf != NULL); for (int i = 0; i < 4; i++) { memset(page_size_buf, 'A'+i, page_size); rc = write(fd, page_size_buf, page_size); DEVSHELL_CMD_ASSERT(rc == page_size); } /* Now, let's mmap the file */ vaddr = mmap(NULL, /* addr */ 4 * page_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); /* Un-map the 2nd page */ rc = munmap(vaddr + page_size, page_size); DEVSHELL_CMD_ASSERT(rc == 0); /* Excepting to receive SIGSEGV from the kernel here */ memcpy(buf, vaddr + page_size, sizeof(buf) - 1); /* ----------- We should NOT get here ------------------- */ free(page_size_buf); close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); exit(1); } /* mmap file and then do a partial unmap */ int cmd_fmmap2(int argc, char **argv) { int rc = test_sig(fmmap2_read_unmapped_mem, NULL, SIGSEGV, 0, 0); unlink(test_file); return rc; } /* mmap file with offset > 0 */ int cmd_fmmap3(int argc, char **argv) { int fd, rc; char *vaddr; char buf[64] = {0}; char exp_buf[64] = {0}; char *page_size_buf; const size_t page_size = getpagesize(); bool failed = false; printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); page_size_buf = malloc(page_size); DEVSHELL_CMD_ASSERT(page_size_buf != NULL); for (int i = 0; i < 4; i++) { memset(page_size_buf, 'A'+i, page_size); rc = write(fd, page_size_buf, page_size); DEVSHELL_CMD_ASSERT(rc == page_size); } /* Now, let's mmap the file at offset > 0 */ vaddr = mmap(NULL, /* addr */ 4 * page_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ page_size); /* offset */ DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); memcpy(buf, vaddr, sizeof(buf) - 1); memset(exp_buf, 'B', sizeof(exp_buf)-1); if (strcmp(buf, exp_buf)) { fprintf(stderr, "Reading vaddr mapped at off > 0 lead to garbage.\n"); fprintf(stderr, "Expected: '%s'\n", exp_buf); fprintf(stderr, "Got: '%s'\n", buf); failed = true; } free(page_size_buf); close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); return failed; } static void fmmap4_read_write_after_eof(bool rw) { int fd, rc; char *vaddr; size_t file_size; char buf[64] = {0}; struct stat statbuf; const size_t page_size = getpagesize(); printf("fmmap4_read_write_after_eof(%s)\n", rw ? "WRITE" : "READ"); printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, test_str, sizeof(test_str)-1); DEVSHELL_CMD_ASSERT(rc == sizeof(test_str)-1); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("File size: %llu\n", (ull_t)file_size); vaddr = mmap(NULL, /* addr */ 2 * page_size, /* length */ PROT_READ | PROT_WRITE, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); /* Expecting to be killed by SIGBUS here */ if (!rw) { /* Read past EOF */ forced_memcpy(buf, vaddr + page_size, sizeof(buf) - 1); } else { /* Write past EOF */ forced_memcpy(vaddr + page_size, buf, sizeof(buf) - 1); } /* If we got here, something went wrong */ printf("ERROR: got to the end, something went wrong\n"); } static void fmmap4_read_after_eof(void *unused) { fmmap4_read_write_after_eof(false); } static void fmmap4_write_after_eof(void *unused) { fmmap4_read_write_after_eof(true); } /* mmap file and read past EOF, expecting SIGBUS */ int cmd_fmmap4(int argc, char **argv) { int rc; if ((rc = test_sig(fmmap4_read_after_eof, NULL, SIGBUS, 0, 0))) goto end; if ((rc = test_sig(fmmap4_write_after_eof, NULL, SIGBUS, 0, 0))) goto end; end: unlink(test_file); return rc; } /* mmap file, truncate (expand) it and write past the original EOF */ int cmd_fmmap5(int argc, char **argv) { int fd, rc; char *vaddr; size_t file_size; char buf[64] = {0}; struct stat statbuf; const size_t page_size = getpagesize(); bool failed = false; printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, test_str, sizeof(test_str)-1); DEVSHELL_CMD_ASSERT(rc == sizeof(test_str)-1); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("File size: %llu\n", (ull_t)file_size); vaddr = mmap(NULL, /* addr */ 2 * page_size, /* length */ PROT_READ | PROT_WRITE, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); rc = ftruncate(fd, page_size + 128); DEVSHELL_CMD_ASSERT(rc == 0); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("(NEW) File size: %llu\n", (ull_t)file_size); /* * This memory write will trigger a page-fault and the kernel should allocate * on-the-fly the page (ramfs_block) for us and, ultimately, resume the * write. */ strcpy(vaddr + page_size, test_str2); close(fd); fd = open(test_file, O_CREAT | O_RDONLY, 0644); DEVSHELL_CMD_ASSERT(fd > 0); /* Check `test_str2` is actually in the file */ rc = lseek(fd, page_size, SEEK_SET); DEVSHELL_CMD_ASSERT(rc == page_size); rc = read(fd, buf, sizeof(buf)-1); DEVSHELL_CMD_ASSERT(rc == sizeof(buf)-1); if (strcmp(buf, test_str2)) { fprintf(stderr, "Reading at offset page_size failure!\n"); fprintf(stderr, "Expected: '%s'\n", test_str2); fprintf(stderr, "Got: '%s'\n", buf); failed = true; } close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); return failed; } /* mmap file, truncate (expand) it and READ past the original EOF */ int cmd_fmmap6(int argc, char **argv) { int fd, rc; char *vaddr; char buf[64]; size_t file_size; struct stat statbuf; const size_t page_size = getpagesize(); bool failed = false; printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, test_str, sizeof(test_str)-1); DEVSHELL_CMD_ASSERT(rc == sizeof(test_str)-1); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("File size: %llu\n", (ull_t)file_size); vaddr = mmap(NULL, /* addr */ 2 * page_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); rc = ftruncate(fd, page_size + 128); DEVSHELL_CMD_ASSERT(rc == 0); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("(NEW) File size: %llu\n", (ull_t)file_size); memset(buf, 'X', sizeof(buf)); /* * This memory read is expected trigger a page fault and the kernel to map * the zero page to vaddr in read-only mode. */ memcpy(buf, vaddr + page_size, sizeof(buf)); for (size_t i = 0; i < sizeof(buf); i++) { if (buf[i]) { fprintf(stderr, "Found a non-zero byte in the past-EOF read\n"); failed = true; } } close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); return failed; } /* mmap file and then trucate it */ static void fmmap7_child(void *unused_arg) { int fd, rc; char *vaddr; size_t file_size; char buf[64] = {0}; struct stat statbuf; char *page_size_buf; const size_t page_size = getpagesize(); printf("Using '%s' as test file\n", test_file); fd = open(test_file, O_CREAT | O_RDWR, 0644); DEVSHELL_CMD_ASSERT(fd > 0); page_size_buf = malloc(page_size); DEVSHELL_CMD_ASSERT(page_size_buf != NULL); for (int i = 0; i < 4; i++) { memset(page_size_buf, 'A'+i, page_size); rc = write(fd, page_size_buf, page_size); DEVSHELL_CMD_ASSERT(rc == page_size); } rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("File size: %llu\n", (ull_t)file_size); printf("Mmap 4 pages of the file\n"); vaddr = mmap(NULL, /* addr */ 4 * page_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ 0); DEVSHELL_CMD_ASSERT(vaddr != (void *)-1); printf("Read from the 2nd mapped page...\n"); memcpy(buf, vaddr + page_size, sizeof(buf)); printf("Got in buf: '%s'\n", buf); memset(buf, 0, sizeof(buf)); printf("Now, trucate the file to just 1 page\n"); /* Truncate the file using truncate() instead of ftruncate() */ rc = truncate(test_file, page_size); DEVSHELL_CMD_ASSERT(rc == 0); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("(NEW) File size: %llu\n", (ull_t)file_size); printf("Now, trying to read the 2nd page (mapped, but after EOF)\n"); /* * On Linux, here we get SIGBUS, as if the file was never bigger than that. * This means that the pages after EOF have been un-mapped by the truncate() * syscall. */ memcpy(buf, vaddr + page_size, sizeof(buf)); /* ------------- we should never get here ----------------- */ fprintf(stderr, "ERROR: We should never get here. "); fprintf(stderr, "Expected to die due to SIGBUS.\n"); printf("Got in buf: '%s'\n", buf); free(page_size_buf); close(fd); rc = unlink(test_file); DEVSHELL_CMD_ASSERT(rc == 0); } /* mmap file and then trucate it */ int cmd_fmmap7(int argc, char **argv) { int rc = test_sig(fmmap7_child, NULL, SIGBUS, 0, 0); unlink(test_file); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included /* * The only purpose of this file is to keep kmalloc.c shorter. * Yes, this file could be turned into a regular C source file, but at the * price of making several static functions and variables in kmalloc.c to be * just non-static. We don't want that. Code isolation is a GOOD thing. */ #endif struct alloc_entry { void *vaddr; size_t size; void *caller_eip; bool leaked; }; static bool leak_detector_enabled; #if KMALLOC_SUPPORT_LEAK_DETECTOR static u32 alloc_entries_count; static struct alloc_entry alloc_entries[1024]; static void *metadata_copies[KMALLOC_HEAPS_COUNT]; void debug_kmalloc_start_leak_detector(bool save_metadata) { disable_preemption(); bzero(alloc_entries, sizeof(alloc_entries)); alloc_entries_count = 0; if (save_metadata) { for (int i = 0; i < ARRAY_SIZE(metadata_copies); i++) { if (!heaps[i].metadata_size) continue; void *buf = kmalloc(heaps[i].metadata_size); if (!buf) panic("leak detector: unable to alloc buffer for metadata copy"); metadata_copies[i] = buf; } for (int i = 0; i < ARRAY_SIZE(metadata_copies); i++) { if (!heaps[i].metadata_size) continue; memcpy(metadata_copies[i], heaps[i].metadata_nodes, heaps[i].metadata_size); } } leak_detector_enabled = true; enable_preemption(); } void debug_kmalloc_stop_leak_detector(bool show_leaks) { disable_preemption(); leak_detector_enabled = false; if (!show_leaks) goto end; u32 leak_count = 0; for (u32 i = 0; i < alloc_entries_count; i++) { if (!alloc_entries[i].leaked) continue; printk("Leaked block at %p (%u B), caller eip: %p\n", alloc_entries[i].vaddr, alloc_entries[i].size, alloc_entries[i].caller_eip); leak_count++; } printk("Total allocs: %u\n", alloc_entries_count); printk("Leak count: %u\n", leak_count); for (int i = 0; i < ARRAY_SIZE(metadata_copies); i++) { struct block_node *md_copy = metadata_copies[i]; if (!md_copy) continue; struct block_node *md = heaps[i].metadata_nodes; size_t len = heaps[i].metadata_size; for (int j = 0; j < len; j++) { if (md[j].raw == md_copy[j].raw) continue; printk("Heap[%d] metadata node #%u DIFFERS [va: %p]\n", i, j, &md[j]); printk("saved: { split: %d, full: %d }\n", md_copy[j].split, md_copy[j].full); printk("curr: { split: %d, full: %d }\n", md[j].split, md[j].full); } } end: for (int i = 0; i < ARRAY_SIZE(metadata_copies); i++) { if (metadata_copies[i]) { kfree2(metadata_copies[i], heaps[i].metadata_size); metadata_copies[i] = NULL; } } enable_preemption(); } static NO_INLINE void debug_kmalloc_register_alloc(void *vaddr, size_t s) { disable_preemption(); VERIFY(alloc_entries_count < ARRAY_SIZE(alloc_entries) - 1); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wframe-address" void *eip_raw = __builtin_return_address(1); void *eip = __builtin_extract_return_addr(eip_raw); #pragma GCC diagnostic pop alloc_entries[alloc_entries_count++] = (struct alloc_entry) { .vaddr = vaddr, .size = s, .caller_eip = eip, .leaked = true, }; enable_preemption(); } static NO_INLINE void debug_kmalloc_register_free(void *vaddr, size_t s) { disable_preemption(); for (u32 i = 0; i < alloc_entries_count; i++) { if (alloc_entries[i].vaddr == vaddr) { VERIFY(alloc_entries[i].size == s); alloc_entries[i].leaked = false; enable_preemption(); return; } } panic("free block at %p, allocated (probably) " "before the start of the leak detector\n", vaddr); enable_preemption(); // in case 'panic' is replaced with a warning. } #else #define debug_kmalloc_register_alloc(...) #define debug_kmalloc_register_free(...) #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/kmalloc.h> #ifdef UNIT_TEST_ENVIRONMENT extern bool kmalloc_initialized; extern struct kmalloc_heap first_heap_struct; extern struct kmalloc_heap *heaps[KMALLOC_HEAPS_COUNT]; extern int used_heaps; extern size_t max_tot_heap_mem_free; #endif <file_sep>#!/usr/bin/env bash pkg="$1" ci= if [ "$1" == "-ci" ]; then pkg="$2" ci=1 fi if [ "$ci" == 1 ]; then cmd="dnf makecache" else cmd="sudo dnf makecache" fi echo "Running the command: $cmd" eval $cmd <file_sep>/****************************************************************************** * * Module Name: evgpeinit - System GPE initialization and update * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acevents.h" #include "acnamesp.h" #define _COMPONENT ACPI_EVENTS ACPI_MODULE_NAME ("evgpeinit") #if (!ACPI_REDUCED_HARDWARE) /* Entire module */ /* * Note: History of _PRW support in ACPICA * * Originally (2000 - 2010), the GPE initialization code performed a walk of * the entire namespace to execute the _PRW methods and detect all GPEs * capable of waking the system. * * As of 10/2010, the _PRW method execution has been removed since it is * actually unnecessary. The host OS must in fact execute all _PRW methods * in order to identify the device/power-resource dependencies. We now put * the onus on the host OS to identify the wake GPEs as part of this process * and to inform ACPICA of these GPEs via the AcpiSetupGpeForWake interface. This * not only reduces the complexity of the ACPICA initialization code, but in * some cases (on systems with very large namespaces) it should reduce the * kernel boot time as well. */ /******************************************************************************* * * FUNCTION: AcpiEvGpeInitialize * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Initialize the GPE data structures and the FADT GPE 0/1 blocks * ******************************************************************************/ ACPI_STATUS AcpiEvGpeInitialize ( void) { UINT32 RegisterCount0 = 0; UINT32 RegisterCount1 = 0; UINT32 GpeNumberMax = 0; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (EvGpeInitialize); ACPI_DEBUG_PRINT_RAW ((ACPI_DB_INIT, "Initializing General Purpose Events (GPEs):\n")); Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Initialize the GPE Block(s) defined in the FADT * * Why the GPE register block lengths are divided by 2: From the ACPI * Spec, section "General-Purpose Event Registers", we have: * * "Each register block contains two registers of equal length * GPEx_STS and GPEx_EN (where x is 0 or 1). The length of the * GPE0_STS and GPE0_EN registers is equal to half the GPE0_LEN * The length of the GPE1_STS and GPE1_EN registers is equal to * half the GPE1_LEN. If a generic register block is not supported * then its respective block pointer and block length values in the * FADT table contain zeros. The GPE0_LEN and GPE1_LEN do not need * to be the same size." */ /* * Determine the maximum GPE number for this machine. * * Note: both GPE0 and GPE1 are optional, and either can exist without * the other. * * If EITHER the register length OR the block address are zero, then that * particular block is not supported. */ if (AcpiGbl_FADT.Gpe0BlockLength && AcpiGbl_FADT.XGpe0Block.Address) { /* GPE block 0 exists (has both length and address > 0) */ RegisterCount0 = (UINT16) (AcpiGbl_FADT.Gpe0BlockLength / 2); GpeNumberMax = (RegisterCount0 * ACPI_GPE_REGISTER_WIDTH) - 1; /* Install GPE Block 0 */ Status = AcpiEvCreateGpeBlock (AcpiGbl_FadtGpeDevice, AcpiGbl_FADT.XGpe0Block.Address, AcpiGbl_FADT.XGpe0Block.SpaceId, RegisterCount0, 0, AcpiGbl_FADT.SciInterrupt, &AcpiGbl_GpeFadtBlocks[0]); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not create GPE Block 0")); } } if (AcpiGbl_FADT.Gpe1BlockLength && AcpiGbl_FADT.XGpe1Block.Address) { /* GPE block 1 exists (has both length and address > 0) */ RegisterCount1 = (UINT16) (AcpiGbl_FADT.Gpe1BlockLength / 2); /* Check for GPE0/GPE1 overlap (if both banks exist) */ if ((RegisterCount0) && (GpeNumberMax >= AcpiGbl_FADT.Gpe1Base)) { ACPI_ERROR ((AE_INFO, "GPE0 block (GPE 0 to %u) overlaps the GPE1 block " "(GPE %u to %u) - Ignoring GPE1", GpeNumberMax, AcpiGbl_FADT.Gpe1Base, AcpiGbl_FADT.Gpe1Base + ((RegisterCount1 * ACPI_GPE_REGISTER_WIDTH) - 1))); /* Ignore GPE1 block by setting the register count to zero */ RegisterCount1 = 0; } else { /* Install GPE Block 1 */ Status = AcpiEvCreateGpeBlock (AcpiGbl_FadtGpeDevice, AcpiGbl_FADT.XGpe1Block.Address, AcpiGbl_FADT.XGpe1Block.SpaceId, RegisterCount1, AcpiGbl_FADT.Gpe1Base, AcpiGbl_FADT.SciInterrupt, &AcpiGbl_GpeFadtBlocks[1]); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not create GPE Block 1")); } /* * GPE0 and GPE1 do not have to be contiguous in the GPE number * space. However, GPE0 always starts at GPE number zero. */ } } /* Exit if there are no GPE registers */ if ((RegisterCount0 + RegisterCount1) == 0) { /* GPEs are not required by ACPI, this is OK */ ACPI_DEBUG_PRINT ((ACPI_DB_INIT, "There are no GPE blocks defined in the FADT\n")); goto Cleanup; } Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiEvUpdateGpes * * PARAMETERS: TableOwnerId - ID of the newly-loaded ACPI table * * RETURN: None * * DESCRIPTION: Check for new GPE methods (_Lxx/_Exx) made available as a * result of a Load() or LoadTable() operation. If new GPE * methods have been installed, register the new methods. * ******************************************************************************/ void AcpiEvUpdateGpes ( ACPI_OWNER_ID TableOwnerId) { ACPI_GPE_XRUPT_INFO *GpeXruptInfo; ACPI_GPE_BLOCK_INFO *GpeBlock; ACPI_GPE_WALK_INFO WalkInfo; ACPI_STATUS Status = AE_OK; /* * Find any _Lxx/_Exx GPE methods that have just been loaded. * * Any GPEs that correspond to new _Lxx/_Exx methods are immediately * enabled. * * Examine the namespace underneath each GpeDevice within the * GpeBlock lists. */ Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return; } WalkInfo.Count = 0; WalkInfo.OwnerId = TableOwnerId; WalkInfo.ExecuteByOwnerId = TRUE; /* Walk the interrupt level descriptor list */ GpeXruptInfo = AcpiGbl_GpeXruptListHead; while (GpeXruptInfo) { /* Walk all Gpe Blocks attached to this interrupt level */ GpeBlock = GpeXruptInfo->GpeBlockListHead; while (GpeBlock) { WalkInfo.GpeBlock = GpeBlock; WalkInfo.GpeDevice = GpeBlock->Node; Status = AcpiNsWalkNamespace (ACPI_TYPE_METHOD, WalkInfo.GpeDevice, ACPI_UINT32_MAX, ACPI_NS_WALK_NO_UNLOCK, AcpiEvMatchGpeMethod, NULL, &WalkInfo, NULL); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "While decoding _Lxx/_Exx methods")); } GpeBlock = GpeBlock->Next; } GpeXruptInfo = GpeXruptInfo->Next; } if (WalkInfo.Count) { ACPI_INFO (("Enabled %u new GPEs", WalkInfo.Count)); } (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return; } /******************************************************************************* * * FUNCTION: AcpiEvMatchGpeMethod * * PARAMETERS: Callback from WalkNamespace * * RETURN: Status * * DESCRIPTION: Called from AcpiWalkNamespace. Expects each object to be a * control method under the _GPE portion of the namespace. * Extract the name and GPE type from the object, saving this * information for quick lookup during GPE dispatch. Allows a * per-OwnerId evaluation if ExecuteByOwnerId is TRUE in the * WalkInfo parameter block. * * The name of each GPE control method is of the form: * "_Lxx" or "_Exx", where: * L - means that the GPE is level triggered * E - means that the GPE is edge triggered * xx - is the GPE number [in HEX] * * If WalkInfo->ExecuteByOwnerId is TRUE, we only execute examine GPE methods * with that owner. * ******************************************************************************/ ACPI_STATUS AcpiEvMatchGpeMethod ( ACPI_HANDLE ObjHandle, UINT32 Level, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *MethodNode = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjHandle); ACPI_GPE_WALK_INFO *WalkInfo = ACPI_CAST_PTR (ACPI_GPE_WALK_INFO, Context); ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_STATUS Status; UINT32 GpeNumber; UINT8 TempGpeNumber; char Name[ACPI_NAMESEG_SIZE + 1]; UINT8 Type; ACPI_FUNCTION_TRACE (EvMatchGpeMethod); /* Check if requested OwnerId matches this OwnerId */ if ((WalkInfo->ExecuteByOwnerId) && (MethodNode->OwnerId != WalkInfo->OwnerId)) { return_ACPI_STATUS (AE_OK); } /* * Match and decode the _Lxx and _Exx GPE method names * * 1) Extract the method name and null terminate it */ ACPI_MOVE_32_TO_32 (Name, &MethodNode->Name.Integer); Name[ACPI_NAMESEG_SIZE] = 0; /* 2) Name must begin with an underscore */ if (Name[0] != '_') { return_ACPI_STATUS (AE_OK); /* Ignore this method */ } /* * 3) Edge/Level determination is based on the 2nd character * of the method name */ switch (Name[1]) { case 'L': Type = ACPI_GPE_LEVEL_TRIGGERED; break; case 'E': Type = ACPI_GPE_EDGE_TRIGGERED; break; default: /* Unknown method type, just ignore it */ ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "Ignoring unknown GPE method type: %s " "(name not of form _Lxx or _Exx)", Name)); return_ACPI_STATUS (AE_OK); } /* 4) The last two characters of the name are the hex GPE Number */ Status = AcpiUtAsciiToHexByte (&Name[2], &TempGpeNumber); if (ACPI_FAILURE (Status)) { /* Conversion failed; invalid method, just ignore it */ ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "Could not extract GPE number from name: %s " "(name is not of form _Lxx or _Exx)", Name)); return_ACPI_STATUS (AE_OK); } /* Ensure that we have a valid GPE number for this GPE block */ GpeNumber = (UINT32) TempGpeNumber; GpeEventInfo = AcpiEvLowGetGpeInfo (GpeNumber, WalkInfo->GpeBlock); if (!GpeEventInfo) { /* * This GpeNumber is not valid for this GPE block, just ignore it. * However, it may be valid for a different GPE block, since GPE0 * and GPE1 methods both appear under \_GPE. */ return_ACPI_STATUS (AE_OK); } if ((ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_HANDLER) || (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_RAW_HANDLER)) { /* If there is already a handler, ignore this GPE method */ return_ACPI_STATUS (AE_OK); } if (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_METHOD) { /* * If there is already a method, ignore this method. But check * for a type mismatch (if both the _Lxx AND _Exx exist) */ if (Type != (GpeEventInfo->Flags & ACPI_GPE_XRUPT_TYPE_MASK)) { ACPI_ERROR ((AE_INFO, "For GPE 0x%.2X, found both _L%2.2X and _E%2.2X methods", GpeNumber, GpeNumber, GpeNumber)); } return_ACPI_STATUS (AE_OK); } /* Disable the GPE in case it's been enabled already. */ (void) AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_DISABLE); /* * Add the GPE information from above to the GpeEventInfo block for * use during dispatch of this GPE. */ GpeEventInfo->Flags &= ~(ACPI_GPE_DISPATCH_MASK); GpeEventInfo->Flags |= (UINT8) (Type | ACPI_GPE_DISPATCH_METHOD); GpeEventInfo->Dispatch.MethodNode = MethodNode; ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "Registered GPE method %s as GPE number 0x%.2X\n", Name, GpeNumber)); return_ACPI_STATUS (AE_OK); } #endif /* !ACPI_REDUCED_HARDWARE */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/debug_utils.h> #include <tilck/mods/tracing.h> static void task_free_all_kernel_allocs(struct task *ti) { ASSERT(!is_preemption_enabled()); while (ti->kallocs_tree_root != NULL) { /* Save a pointer to the alloc object on the stack */ struct kernel_alloc *alloc = ti->kallocs_tree_root; /* Free the allocated chunk */ kfree2(alloc->vaddr, alloc->size); /* Remove the kernel_alloc elem from the tree */ bintree_remove_ptr(&ti->kallocs_tree_root, alloc, struct kernel_alloc, node, vaddr); /* Free the kernel_alloc object itself */ kfree_obj(alloc, struct kernel_alloc); } } static void init_terminated(struct task *ti, int exit_code, int term_sig) { if (DEBUG_QEMU_EXIT_ON_INIT_EXIT) debug_qemu_turn_off_machine(); if (!term_sig) panic("Init exited with code: %d\n", exit_code); else panic("Init terminated by signal %s[%d]\n", get_signal_name(term_sig), term_sig); } static struct process *get_child_reaper(struct process *pi) { /* TODO: support prctl(PR_SET_CHILD_SUBREAPER) */ ASSERT(!is_preemption_enabled()); struct task *child_reaper = get_task(1); /* init */ VERIFY(child_reaper != NULL); return child_reaper->pi; } static void handle_children_of_dying_process(struct task *ti) { struct process *pi = ti->pi; struct task *pos, *temp; struct process *child_reaper = get_child_reaper(pi); list_for_each(pos, temp, &pi->children, siblings_node) { list_remove(&pos->siblings_node); list_add_tail(&child_reaper->children, &pos->siblings_node); pos->pi->parent_pid = child_reaper->pid; if (pi->sa_handlers[SIGCHLD - 1] == SIG_IGN) pos->pi->automatic_reaping = true; if (pos->state == TASK_STATE_ZOMBIE) { /* * Corner case: the dying task had already dead children which it * did not wait for. Their exit code couldn't be retrieved by the * nearest reaper (init) because their parent was still alive when * they died. But now, they also have to be waited by the nearest * reaper, along with their parent. */ wake_up_tasks_waiting_on(pos, task_died); } } } static void close_all_handles(void) { struct process *pi = get_curr_proc(); ASSERT(is_preemption_enabled()); for (int i = 0; i < MAX_HANDLES; i++) { if (pi->handles[i]) { vfs_close(pi->handles[i]); pi->handles[i] = NULL; } } } struct on_task_exit_cb { struct list_node node; void (*cb)(struct task *); }; int register_on_task_exit_cb(void (*cb)(struct task *)) { struct task *ti = get_curr_task(); int rc = 0; disable_preemption(); { struct on_task_exit_cb *obj = kalloc_obj(struct on_task_exit_cb); if (obj) { list_node_init(&obj->node); list_add_tail(&ti->on_exit, &obj->node); obj->cb = cb; } else { rc = -ENOMEM; } } enable_preemption(); return rc; } int unregister_on_task_exit_cb(void (*cb)(struct task *)) { struct task *ti = get_curr_task(); struct on_task_exit_cb *pos, *tmp; int rc = -ENOENT; disable_preemption(); { list_for_each(pos, tmp, &ti->on_exit, node) { if (pos->cb == cb) { list_remove(&pos->node); rc = 0; break; } } } enable_preemption(); return rc; } static void call_on_task_exit_callbacks(void) { struct task *ti = get_curr_task(); struct on_task_exit_cb *pos, *tmp; list_for_each(pos, tmp, &ti->on_exit, node) { pos->cb(ti); kfree_obj(pos, struct on_task_exit_cb); } } /* * Note: we HAVE TO make this function NO_INLINE otherwise clang in release * builds generates code that is incompatible with asm hacks changing both * the stack pointer and the frame pointer. It is worth mentioning that even * copying the whole stack to a new place is still not enough for clang. * Therefore, the simplest and reliable thing we can do is just to make the * following function be non-inlineable and take no arguments. */ NORETURN static NO_INLINE void switch_stack_free_mem_and_schedule(void) { /* WARNING: DO NOT USE ANY STACK VARIABLES HERE */ ASSERT_CURR_TASK_STATE(TASK_STATE_ZOMBIE); /* WARNING: the following call discards the whole stack! */ switch_to_initial_kernel_stack(); /* Free the heap allocations used, including the kernel stack */ free_mem_for_zombie_task(get_curr_task()); /* Run the scheduler */ do_schedule(); /* Reassure the compiler that we won't return */ NOT_REACHED(); } /* * NOTE: this code ASSUMES that user processes have a _single_ thread: * * process = task = thread * * TODO: re-design this function when thread support is introduced. * * NOTE: the kernel "process" has multiple threads (kthreads), but they cannot * be signalled nor killed. */ void terminate_process(int exit_code, int term_sig) { struct task *const ti = get_curr_task(); struct process *const pi = ti->pi; struct task *parent; const bool vforked = pi->vforked; ASSERT(ti->state != TASK_STATE_ZOMBIE); ASSERT(!is_kernel_thread(ti)); ASSERT(is_preemption_enabled()); if (term_sig) trace_task_killed(term_sig); disable_preemption(); if (ti->wobj.type != WOBJ_NONE) { /* * If the task has been waiting on something, we have to reset its wobj * and remove its pointer from the target object's wait_list. */ wait_obj_reset(&ti->wobj); } /* * Sleep-based wake-up timers work without the wait_obj mechanism: we have * to cancel any potential wake-up timer as well. */ task_cancel_wakeup_timer(ti); /* Here we can either be RUNNABLE (if ti->wobj was set) or RUNNING */ ASSERT(ti->state == TASK_STATE_RUNNING || ti->state == TASK_STATE_RUNNABLE); /* Drop the any pending signals and prevent new from being enqueued */ drop_all_pending_signals(ti); ti->nested_sig_handlers = -1; /* * Close all the handles, keeping the preemption enabled while doing so. */ enable_preemption(); { close_all_handles(); } disable_preemption(); /* OK, from now on the preemption won't be enabled until the end */ task_change_state(ti, TASK_STATE_ZOMBIE); ti->wstatus = EXITCODE(exit_code, term_sig); parent = get_task(pi->parent_pid); call_on_task_exit_callbacks(); task_free_all_kernel_allocs(ti); if (!vforked) { remove_all_user_zero_mem_mappings(pi); if (pi->elf) release_subsys_flock(pi->elf); } if (LIKELY(ti->tid != 1)) { /* * What if the dying task has any children? We have to set their parent * to init (pid 1) or to the nearest child subreaper, once that is * supported. */ handle_children_of_dying_process(ti); } else { /* The dying task is PID 1, init */ init_terminated(ti, exit_code, term_sig); } /* Wake-up all the tasks waiting on this specific task to exit */ wake_up_tasks_waiting_on(ti, task_died); if (term_sig) { /* * The process has been killed. It makes sense to perform some additional * actions, in order to preserve the system in a healty state. */ if (pi->did_set_tty_medium_raw) tty_set_medium_raw_mode(pi->proc_tty, false); } if (vforked) { handle_vforked_child_move_on(pi); pi->vforked = true; /* handle_vforked_child_move_on() unsets this */ if (!pi->inherited_mmap_heap) { /* We're in a vfork-ed child: the parent cannot die */ ASSERT(parent != NULL); /* * If we didn't inherit mappings info from the parent and the parent * didn't run the whole time: its `mi` must continue to be NULL. */ ASSERT(!parent->pi->mi); /* Transfer the ownership of our mappings info back to our parent */ parent->pi->mi = pi->mi; } } if (parent) { if (parent->pi->sa_handlers[SIGCHLD - 1] == SIG_IGN) pi->automatic_reaping = true; } set_curr_pdir(get_kernel_pdir()); if (!vforked) pdir_destroy(pi->pdir); switch_stack_free_mem_and_schedule(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/list.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/subsystems.h> struct locked_file; /* forward declaration */ int acquire_subsys_flock(struct mnt_fs *fs, vfs_inode_ptr_t i, enum subsystem subsys, struct locked_file **lock_ref); /* out */ int acquire_subsys_flock_h(fs_handle h, enum subsystem subsys, struct locked_file **lock_ref); /* out */ void retain_subsys_flock(struct locked_file *lf); void release_subsys_flock(struct locked_file *lf); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include "idt_int.h" #include "../generic_x86/pic.h" /* * We first remap the interrupt controllers, and then we install * the appropriate ISRs to the correct entries in the IDT. This * is just like installing the exception handlers. */ void init_irq_handling(void) { ASSERT(!are_interrupts_enabled()); init_pic_8259(32, 40); for (int i = 0; i < ARRAY_SIZE(irq_handlers_lists); i++) { idt_set_entry(32 + (u8)i, irq_entry_points[i], X86_KERNEL_CODE_SEL, IDT_FLAG_PRESENT | IDT_FLAG_INT_GATE | IDT_FLAG_DPL0); irq_set_mask(i); } } <file_sep>#!/bin/bash # SPDX-License-Identifier: BSD-2-Clause PROJ_DIR="@CMAKE_SOURCE_DIR@" TCROOT="@TCROOT@" ARCH="@ARCH@" HOST_ARCH="@HOST_ARCH@" VER="@GCC_TC_VER_@" if [ @USE_SYSCC@ = 0 ]; then GCC_TC="$TCROOT/host_$HOST_ARCH/gcc_${VER}_${ARCH}_glibc/bin" export PATH="$GCC_TC:$PATH" else export SYS_CC="@SYS_CC@" export SYS_CXX="@SYS_CXX@" export PATH="$PROJ_DIR/scripts/build_scripts:$PATH" fi "$TCROOT/$ARCH/musl/install/bin/musl-gcc" "$@" -Wl,-m -Wl,@ARCH_LD_OUTPUT@ <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # --------------------------------------------------------------- # NOTE # # This "script" is NOT meant to be executed directly. # It is included as a source file by scripts/build_toolchain. # # --------------------------------------------------------------- ############################### # x86-i686 GNU toolchain ############################### # $1 dir name # $2 arch name # $3 tc file name function raw_gcc_tc_download { local dest="$1" local arch="$2" local tcname_suffix="$3" local tcname="${arch}--${tcname_suffix}" local tarname=$tcname.tar.bz2 local url="https://toolchains.bootlin.com/downloads/releases/toolchains" download_file_in_cache "$url/$arch/tarballs" "$tarname" extract_cachefile_tar_bz "$tarname" $tcname $dest } function gcc_x86_glibc_patch { # To make musl-gcc happy pushd ${GCC_NAME_PFX}_glibc/bin for x in *; do if [[ $x == i686* ]]; then new_name=$(echo $x | sed 's/i686/i386/g') ln -s $x $new_name fi done for x in *; do if [[ $x == i386-linux-* ]]; then new_name=$(echo $x | sed 's/i386-linux-/i386-/g') ln -s $x $new_name fi done popd } # $1: libc name function download_gcc_tc_internal { local libc="$1" pushd host_${BUILD_ARCH} if ! [ -d ${GCC_NAME_PFX}_${libc} ]; then show_work_on_component_msg "GCC TOOLCHAIN ($ARCH - $libc)" raw_gcc_tc_download \ "${GCC_NAME_PFX}_${libc}" \ "$ARCH_GCC_TC_CODENAME" \ "$libc--$ARCH_GCC_TC_VER" if [[ "$libc" == "glibc" && "$ARCH" == "i386" ]]; then gcc_x86_glibc_patch fi local gcc=${GCC_NAME_PFX}_${libc}/bin/$ARCH_GCC_TC-linux-gcc if ! [ -f $gcc ]; then echo "ERROR (download_gcc_tc_internal): file $gcc NOT found." exit 1 fi if [[ "$HOST_ARCH" == "$BUILD_ARCH" ]]; then local ver=$(generic_get_version_str $gcc) echo "Detected GCC toolchain version: '$ver'" if [[ "$ver" != "$GCC_TC_VER" ]]; then echo "ERROR: gcc version doesn't match expected ($GCC_TC_VER)" exit 1 fi fi else show_skip_component_msg "GCC TOOLCHAIN ($ARCH - $libc)" fi popd } ############################################################ if [[ "$HOST_ARCH" == "x86_64" ]]; then all_funcs_list+=(download_gcc_toolchain) fi function download_gcc_toolchain { if [[ "$DOWNLOAD_IGNORING_SYSCC" != 1 && "$USE_SYSCC" == 1 ]]; then echo "NOTE: Skipping download_gcc_toolchain because USE_SYSCC=1" return 0 fi download_gcc_tc_internal musl } function download_gcc_toolchain_installed_status { if [ -d $TC/host_${BUILD_ARCH}/${GCC_NAME_PFX}_musl ]; then echo "installed" fi } if [[ "$HOST_ARCH" == "x86_64" ]]; then all_funcs_list+=(download_gcc_glibc_toolchain) fi function download_gcc_glibc_toolchain { pushd $TC download_gcc_tc_internal glibc popd } function download_gcc_glibc_toolchain_installed_status { if [ -d $TC/host_${BUILD_ARCH}/${GCC_NAME_PFX}_glibc ]; then echo "installed" fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <elf.h> #if defined(USE_ELF32) && defined(USE_ELF64) #error Invalid configuration: USE_ELF32 and USE_ELF64 both defined. #endif #if defined(USE_ELF32) || (defined(__i386__) && !defined(USE_ELF64)) typedef Elf32_Addr Elf_Addr; typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Phdr Elf_Phdr; typedef Elf32_Shdr Elf_Shdr; typedef Elf32_Sym Elf_Sym; #elif defined(USE_ELF64) || ((defined(__x86_64__) || defined(__aarch64__)) \ && !defined(USE_ELF32)) typedef Elf64_Addr Elf_Addr; typedef Elf64_Ehdr Elf_Ehdr; typedef Elf64_Phdr Elf_Phdr; typedef Elf64_Shdr Elf_Shdr; typedef Elf64_Sym Elf_Sym; #else #error Unknown architecture #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/config_kernel.h> #if ARCH_BITS == 32 #define USE_ELF32 #else #define USE_ELF64 #endif #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <tilck/common/elf_calc_mem_size.c.h> #include <tilck/common/elf_get_section.c.h> #include <tilck/common/build_info.h> #include "common_int.h" #define CHECK(cond) \ do { \ if (!(cond)) { \ printk("CHECK '%s' FAILED\n", #cond); \ return false; \ } \ } while(0) static video_mode_t selected_mode = INVALID_VIDEO_MODE; static char kernel_file_path[64] = KERNEL_FILE_PATH; static char line_buf[64]; static void *kernel_elf_file_paddr; static struct build_info *kernel_build_info; static char *cmdline_buf; static u32 cmdline_buf_sz; static u8 mods_start[32]; static u8 mods_len[32]; static int mods_cnt; static bool kmod_console; static bool kmod_fb; static bool kmod_serial; void write_bootloader_hello_msg(void) { intf->set_color(COLOR_BRIGHT_WHITE); printk("----- Hello from Tilck's %s bootloader! -----\n\n", intf->efi ? "UEFI" : "legacy"); intf->set_color(DEFAULT_FG_COLOR); } void * load_kernel_image(void) { return simple_elf_loader(kernel_elf_file_paddr); } void write_ok_msg(void) { intf->set_color(COLOR_GREEN); printk("[ OK ]\n"); intf->set_color(DEFAULT_FG_COLOR); } void write_fail_msg(void) { intf->set_color(COLOR_RED); printk("[ FAIL ]\n"); intf->set_color(DEFAULT_FG_COLOR); } static bool check_elf_kernel(void) { Elf_Ehdr *header = kernel_elf_file_paddr; Elf_Phdr *phdr = (Elf_Phdr *)(header + 1); if (header->e_ident[EI_MAG0] != ELFMAG0 || header->e_ident[EI_MAG1] != ELFMAG1 || header->e_ident[EI_MAG2] != ELFMAG2 || header->e_ident[EI_MAG3] != ELFMAG3) { printk("Not an ELF file\n"); return false; } if (header->e_ehsize != sizeof(*header)) { printk("Not an ELF32 file\n"); return false; } for (int i = 0; i < header->e_phnum; i++, phdr++) { // Ignore non-load segments. if (phdr->p_type != PT_LOAD) continue; CHECK(phdr->p_vaddr >= KERNEL_BASE_VA); CHECK(phdr->p_paddr >= KERNEL_PADDR); } return true; } size_t get_loaded_kernel_mem_sz(void) { if (!kernel_elf_file_paddr) panic("No loaded kernel"); return elf_calc_mem_size(kernel_elf_file_paddr); } static void parse_kernel_mods_list(void) { char *mods = kernel_build_info->modules_list; char *begin = mods; u8 len; mods_cnt = 0; kmod_console = false; kmod_fb = false; kmod_serial = false; for (char *p = mods; *p; p++) { if (*p != ' ' && p[1]) continue; len = p - begin + !p[1]; if (!strncmp(begin, "console", 7)) kmod_console = true; else if (!strncmp(begin, "fb", 2)) kmod_fb = true; else if (!strncmp(begin, "serial", 6)) kmod_serial = true; if (mods_cnt == ARRAY_SIZE(mods_start)) continue; mods_start[mods_cnt] = begin - mods; mods_len[mods_cnt] = len; begin = p + 1; mods_cnt++; } } static bool load_kernel_file(void) { Elf_Shdr *section; Elf_Ehdr *header; printk("Loading the ELF kernel... "); if (!intf->load_kernel_file(kernel_file_path, &kernel_elf_file_paddr)) { write_fail_msg(); return false; } if (!check_elf_kernel()) { write_fail_msg(); return false; } header = kernel_elf_file_paddr; section = elf_get_section(header, ".tilck_info"); if (!section) { printk("Not a Tilck ELF kernel file\n"); write_fail_msg(); return false; } kernel_build_info = (void *)((char *)header + section->sh_offset); parse_kernel_mods_list(); if (kmod_console) { if (kmod_fb) { if (selected_mode == INVALID_VIDEO_MODE || selected_mode == intf->text_mode) { selected_mode = g_defmode; } } else { selected_mode = intf->text_mode; } } else { selected_mode = INVALID_VIDEO_MODE; } write_ok_msg(); return true; } static void read_kernel_file_path(void) { bool failed = false; while (true) { printk("Kernel file path: "); read_line(line_buf, sizeof(line_buf)); if (!line_buf[0] && !failed) { printk("Keeping the current kernel file.\n"); break; } if (line_buf[0] != '/') { printk("Invalid file path. Expected an absolute path.\n"); continue; } strcpy(kernel_file_path, line_buf); if (!load_kernel_file()) { failed = true; continue; } break; } } static void clear_screen(void) { intf->clear_screen(); write_bootloader_hello_msg(); } static void print_kernel_mods(void) { static char prefix[] = " modules: "; static char prefix_padding[] = " "; char *mods = kernel_build_info->modules_list; int per_line_len = sizeof(prefix) - 1; char tmp[32]; printk("%s", prefix); for (int i = 0; i < mods_cnt; i++) { strncpy(tmp, mods + mods_start[i], mods_len[i]); tmp[mods_len[i]] = 0; if (per_line_len + mods_len[i] > 75) { printk("\n%s", prefix_padding); per_line_len = sizeof(prefix) - 1; } printk("%s ", tmp); per_line_len += mods_len[i] + 1; } printk("\n"); } static void show_menu_item(const char *cmd, const char *name, const char *value, bool q, bool nl) { const size_t namelen = strlen(name); char pad[] = " "; intf->set_color(COLOR_GREEN); printk("%s", cmd); intf->set_color(DEFAULT_FG_COLOR); if (value) { if (namelen <= sizeof(pad) - 1) pad[sizeof(pad) - 1 - namelen] = 0; else pad[0] = 0; printk(") %s:%s ", name, pad); if (q) { intf->set_color(COLOR_MAGENTA); printk("\'"); } else { intf->set_color(COLOR_CYAN); } printk("%s", value); if (q) { printk("\'"); } intf->set_color(DEFAULT_FG_COLOR); if (nl) printk("\n"); } else { printk(") %s\n", name); } } static bool run_interactive_logic(void) { struct generic_video_mode_info gi; struct commit_hash_and_date comm; bool wait_for_key; char buf[8]; while (true) { wait_for_key = true; if (selected_mode != INVALID_VIDEO_MODE) { if (!intf->get_mode_info(selected_mode, &gi)) { printk("ERROR: get_mode_info() failed"); return false; } } extract_commit_hash_and_date(kernel_build_info, &comm); intf->set_color(COLOR_GREEN); printk("Menu\n"); intf->set_color(DEFAULT_FG_COLOR); printk("---------------------------------------------------\n"); show_menu_item("k", "Kernel file", kernel_file_path, false, true); printk(" version: %s\n", kernel_build_info->ver); printk(" commit: %s", comm.hash); if (comm.dirty) printk(" (dirty)"); else if (comm.tags[0]) printk(" (%s)", comm.tags); printk("\n"); printk(" date: %s\n", comm.date); print_kernel_mods(); printk("\n"); show_menu_item("v", "Video mode", "", false, false); if (selected_mode != INVALID_VIDEO_MODE) show_mode(-1, &gi, false); else printk("<none>\n"); show_menu_item("e", "Cmdline", cmdline_buf, true, true); show_menu_item("b", "Boot", NULL, false, true); printk("\n> "); buf[0] = 0; read_line(buf, sizeof(buf)); switch (buf[0]) { case 0: case 'b': return true; case 'k': read_kernel_file_path(); break; case 'v': if (selected_mode != INVALID_VIDEO_MODE && kmod_fb) { show_video_modes(); printk("\n"); selected_mode = get_user_video_mode_choice(); wait_for_key = false; } else { printk("Cannot change video mode with this kernel\n"); } break; case 'e': printk("Cmdline: "); read_line(cmdline_buf, MIN(70, (int)cmdline_buf_sz)); wait_for_key = false; break; default: printk("Invalid command\n"); } if (wait_for_key) { printk("Press ANY key to continue"); intf->read_key(); } clear_screen(); } return true; } static void wait_for_any_key(void) { printk("Press ANY key to continue"); intf->read_key(); } bool common_bootloader_logic(void) { bool in_retry = false; fetch_all_video_modes_once(); selected_mode = g_defmode; cmdline_buf = intf->get_cmdline_buf(&cmdline_buf_sz); if (!cmdline_buf) panic("No cmdline buffer"); if (cmdline_buf_sz < CMDLINE_BUF_SZ) panic("Cmdline buffer too small"); strcpy(cmdline_buf, "tilck "); /* 1st argument, always ignored */ cmdline_buf += 6; cmdline_buf_sz -= 6; if (!load_kernel_file()) return false; printk("\n"); retry: if (in_retry) { wait_for_any_key(); clear_screen(); } in_retry = true; if (BOOT_INTERACTIVE) { if (!run_interactive_logic()) return false; } clear_screen(); if (!intf->load_initrd()) { if (BOOT_INTERACTIVE) goto retry; return false; } if (selected_mode != INVALID_VIDEO_MODE) { if (!intf->set_curr_video_mode(selected_mode)) { if (BOOT_INTERACTIVE) { printk("ERROR: cannot set the selected video mode\n"); goto retry; } /* In this other case, the current video mode will be kept */ } } else { /* No video mode */ if (kmod_serial) { intf->clear_screen(); printk("<No video console>"); } else { printk("\n"); printk("*** FATAL ERROR ***\n"); printk("The kernel supports neither video nor serial console.\n"); if (kmod_console) { printk("The kernel supports text mode but text mode is NOT "); printk("available when\nbooting with UEFI.\n\n"); } printk("Refuse to boot.\n"); goto retry; } } return true; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/page_size.h> #include <tilck/boot/common.h> #undef ASSERT #include <efi.h> #include <efilib.h> #include <efierr.h> #include <tilck/common/assert.h> #include <multiboot.h> #ifndef __EFI_MAIN__ #define EXTERN extern #else #define EXTERN #endif #define EFI_MBI_MAX_ADDR (64 * KB) EXTERN multiboot_info_t *gMbi; EXTERN EFI_HANDLE gImageHandle; EXTERN EFI_LOADED_IMAGE *gLoadedImage; EXTERN EFI_GRAPHICS_OUTPUT_PROTOCOL *gProt; EXTERN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *gFileFsProt; EXTERN EFI_FILE_PROTOCOL *gFileProt; EXTERN EFI_PHYSICAL_ADDRESS gRamdiskPaddr; EXTERN UINTN gRamdiskSize; EXTERN EFI_MEMORY_DESCRIPTOR gMmap[512]; EXTERN UINTN gMmap_size; EXTERN UINTN gDesc_size; EXTERN char *gCmdlineBuf; EXTERN bool gExitBootServicesCalled; extern const struct bootloader_intf efi_boot_intf; EFI_STATUS LoadKernelFile(CHAR16 *filePath, EFI_PHYSICAL_ADDRESS *paddr); EFI_STATUS MultibootSaveMemoryMap(UINTN *mapkey); EFI_STATUS SetupMultibootInfo(void); EFI_STATUS ReserveMemAreaForKernelImage(void); EFI_STATUS LoadRamdisk(EFI_HANDLE image, EFI_LOADED_IMAGE *loaded_image, EFI_PHYSICAL_ADDRESS *ramdisk_paddr_ref, UINTN *gRamdiskSize); EFI_STATUS EarlySetDefaultResolution(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/process.h> soft_int_handler_t fault_handlers[32]; const char *x86_exception_names[32] = { "Division By Zero", "Debug", "Non Maskable Interrupt", "Breakpoint", "Into Detected Overflow", "Out of Bounds", "Invalid Opcode", "No Coprocessor", "Double Fault", "Coprocessor Segment Overrun", "Bad TSS", "Segment Not Present", "Stack Fault", "General Protection Fault", "Page Fault", "Unknown Interrupt", "Coprocessor Fault", "Alignment Check", "Machine Check", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", }; void set_fault_handler(int ex_num, void *ptr) { fault_handlers[ex_num] = (soft_int_handler_t) ptr; } void handle_resumable_fault(regs_t *r) { struct task *curr = get_curr_task(); pop_nested_interrupt(); // the fault set_return_register(curr->fault_resume_regs, 1u << regs_intnum(r)); context_switch(curr->fault_resume_regs); } static void fault_in_panic(regs_t *r) { const int int_num = r->int_num; if (is_fault_resumable(int_num)) return handle_resumable_fault(r); /* * We might be so unlucky that printk() causes some fault(s) too: therefore, * not even trying to print something on the screen is safe. In order to * avoid generating an endless sequence of page faults in the worst case, * just call printk() in SAFE way here. */ fault_resumable_call( ALL_FAULTS_MASK, printk, 5, "FATAL: %s [%d] while in panic state [E: 0x%x, EIP: %p]\n", x86_exception_names[int_num], int_num, r->err_code, regs_get_ip(r)); /* Halt the CPU forever */ while (true) { halt(); } } void handle_fault(regs_t *r) { const int int_num = r->int_num; bool cow = false; ASSERT(is_fault(int_num)); if (UNLIKELY(in_panic())) return fault_in_panic(r); if (LIKELY(int_num == FAULT_PAGE_FAULT)) { cow = handle_potential_cow(r); } if (!cow) { if (is_fault_resumable(int_num)) return handle_resumable_fault(r); if (LIKELY(fault_handlers[int_num] != NULL)) { fault_handlers[int_num](r); } else { panic("Unhandled fault #%i: %s [err: %p] EIP: %p", int_num, x86_exception_names[int_num], r->err_code, regs_get_ip(r)); } } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <cstdio> #include <cstdint> #include <cstdlib> #include <cassert> #include <iostream> #include <vector> #include <unordered_map> #include <random> #include <gtest/gtest.h> #include "fake_funcs_utils.h" #include "kernel_init_funcs.h" extern "C" { #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/worker_thread.h> #include "kernel/wth_int.h" // private header } using namespace std; using namespace testing; static void destroy_last_worker_thread(void) { assert(worker_threads_cnt > 0); const u32 wth = --worker_threads_cnt; struct worker_thread *t = worker_threads[wth]; const u32 queue_size = t->rb.max_elems; assert(t != NULL); safe_ringbuf_destory(&t->rb); kfree_array_obj(t->jobs, struct wjob, queue_size); kfree_obj(t, struct worker_thread); bzero((void *)t, sizeof(*t)); worker_threads[wth] = NULL; } class worker_thread_test : public Test { void SetUp() override { init_kmalloc_for_tests(); init_worker_threads(); } void TearDown() override { destroy_last_worker_thread(); } }; void simple_func1(void *p1) { ASSERT_EQ(p1, TO_PTR(1234)); } TEST_F(worker_thread_test, essential) { bool res = false; struct worker_thread *wth = wth_find_worker(WTH_PRIO_HIGHEST); ASSERT_TRUE(wth_enqueue_on(wth, &simple_func1, TO_PTR(1234))); ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); } TEST_F(worker_thread_test, base) { struct worker_thread *wth = wth_find_worker(WTH_PRIO_HIGHEST); const int max_jobs = wth_get_queue_size(wth); bool res; for (int i = 0; i < max_jobs; i++) { res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); ASSERT_TRUE(res); } res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); // There is no more space left, expecting the ADD failed. ASSERT_FALSE(res); for (int i = 0; i < max_jobs; i++) { ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); } ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); // There are no more jobs, expecting the RUN failed. ASSERT_FALSE(res); } TEST_F(worker_thread_test, advanced) { struct worker_thread *wth = wth_find_worker(WTH_PRIO_HIGHEST); const int max_jobs = wth_get_queue_size(wth); bool res; // Fill half of the buffer. for (int i = 0; i < max_jobs/2; i++) { res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); ASSERT_TRUE(res); } // Consume 1/4. for (int i = 0; i < max_jobs/4; i++) { ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); } // Fill half of the buffer. for (int i = 0; i < max_jobs/2; i++) { res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); ASSERT_TRUE(res); } // Consume 2/4 for (int i = 0; i < max_jobs/2; i++) { ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); } // Fill half of the buffer. for (int i = 0; i < max_jobs/2; i++) { res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); ASSERT_TRUE(res); } // Now the cyclic buffer for sure rotated. // Consume 3/4 for (int i = 0; i < 3*max_jobs/4; i++) { ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); } ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); // There are no more jobs, expecting the RUN failed. ASSERT_FALSE(res); } TEST_F(worker_thread_test, chaos) { struct worker_thread *wth = wth_find_worker(WTH_PRIO_HIGHEST); const int max_jobs = wth_get_queue_size(wth); random_device rdev; default_random_engine e(rdev()); lognormal_distribution<> dist(3.0, 2.5); int slots_used = 0; bool res = false; for (int iters = 0; iters < 10000; iters++) { int c; c = round(dist(e)); for (int i = 0; i < c; i++) { if (slots_used == max_jobs) { ASSERT_FALSE(wth_enqueue_on(wth, &simple_func1, TO_PTR(1234))); break; } res = wth_enqueue_on(wth, &simple_func1, TO_PTR(1234)); ASSERT_TRUE(res); slots_used++; } c = round(dist(e)); for (int i = 0; i < c; i++) { if (slots_used == 0) { ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_FALSE(res); break; } ASSERT_NO_FATAL_FAILURE({ res = wth_process_single_job(wth); }); ASSERT_TRUE(res); slots_used--; } } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <tilck/kernel/term.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/tty_struct.h> #include "termutil.h" static bool rev_colors; void dp_write_raw_int(const char *buf, int len) { struct tty *t = get_curr_process_tty(); t->tintf->write(t->tstate, buf, (size_t)len, !rev_colors ? DP_COLOR : DP_REV_COLOR); } void dp_write_raw(const char *fmt, ...) { char buf[256]; va_list args; int rc; va_start(args, fmt); rc = vsnprintk(buf, sizeof(buf), fmt, args); va_end(args); dp_write_raw_int(buf, rc); } void dp_reverse_colors(void) { struct tty *t = get_curr_process_tty(); if (t->tparams.type == term_type_video) rev_colors = true; else dp_write_raw("%s", REVERSE_VIDEO); } void dp_reset_attrs(void) { struct tty *t = get_curr_process_tty(); if (t->tparams.type == term_type_video) rev_colors = false; else dp_write_raw("%s", RESET_ATTRS); } void dp_move_right(int n) { dp_write_raw("\033[%dC", n); } void dp_move_left(int n) { dp_write_raw("\033[%dD", n); } void dp_move_to_col(int n) { dp_write_raw("\033[%dG", n); } void dp_clear(void) { dp_write_raw(ERASE_DISPLAY); } void dp_move_cursor(int row, int col) { dp_write_raw("\033[%d;%dH", row, col); } void dp_set_cursor_enabled(bool enabled) { dp_write_raw("%s", enabled ? SHOW_CURSOR : HIDE_CURSOR); } void dp_switch_to_alt_buffer(void) { dp_write_raw("%s", USE_ALT_BUF); } void dp_switch_to_default_buffer(void) { dp_write_raw("%s", USE_DEF_BUF); } void dp_write(int row, int col, const char *fmt, ...) { char buf[256]; va_list args; int rc; const int relrow = row - dp_screen_start_row; if (relrow > dp_ctx->row_max) dp_ctx->row_max = relrow; if (relrow < dp_ctx->row_off) return; row -= dp_ctx->row_off; if (row > dp_end_row - 2) return; va_start(args, fmt); rc = vsnprintk(buf, sizeof(buf), fmt, args); va_end(args); if (col == 0) col = dp_start_col + 2; dp_move_cursor(row, col); dp_write_raw_int(buf, rc); } void dp_draw_rect_raw(int row, int col, int h, int w) { ASSERT(w >= 2); ASSERT(h >= 2); dp_write_raw(GFX_ON); dp_move_cursor(row, col); dp_write_raw("l"); for (int i = 0; i < w-2; i++) { dp_write_raw("q"); } dp_write_raw("k"); for (int i = 1; i < h-1; i++) { dp_move_cursor(row+i, col); dp_write_raw("x"); dp_move_cursor(row+i, col+w-1); dp_write_raw("x"); } dp_move_cursor(row+h-1, col); dp_write_raw("m"); for (int i = 0; i < w-2; i++) { dp_write_raw("q"); } dp_write_raw("j"); dp_write_raw(GFX_OFF); } void dp_draw_rect(const char *label, const char *esc_label_color, int row, int col, int h, int w) { ASSERT(w >= 2); ASSERT(h >= 2); dp_write_raw(GFX_ON); dp_write(row, col, "l"); for (int i = 0; i <= w-2; i++) { dp_write(row, col+i+1, "q"); } dp_write(row, col+w-2+1, "k"); for (int i = 1; i < h-1; i++) { dp_write(row+i, col, "x"); dp_write(row+i, col+w-1, "x"); } dp_write(row+h-1, col, "m"); for (int i = 0; i <= w-2; i++) { dp_write(row+h-1, col+i+1, "q"); } dp_write(row+h-1, col+w-2+1, "j"); dp_write_raw(GFX_OFF); if (label) { dp_write(row, col + 2, "%s[ %s ]" RESET_ATTRS, esc_label_color, label); } } void dp_show_modal_msg(const char *msg) { static const char common_msg[] = "Press ANY key to continue"; const int max_line_len = DP_W - 2 - 2 - 2; const int msg_len = (int)strlen(msg); const int row_len = UNSAFE_MAX( UNSAFE_MIN(max_line_len, msg_len), (int)sizeof(common_msg) - 1 ) + 2; const int srow = dp_start_row + DP_H / 2 - 5 / 2; const int scol = dp_cols / 2 - row_len / 2; char buf[DP_W+1]; ASSERT(msg_len <= max_line_len); /* for the moment, no multi-line */ memset(buf, ' ', sizeof(buf) - 1); buf[row_len] = 0; /* Clear the area around the message box */ for (int i = 0; i < 3; i++) dp_write(srow + i, scol, "%s", buf); /* Draw the rect */ dp_draw_rect("Alert", E_COLOR_BR_RED, srow - 1, scol - 1, 5, row_len + 2); /* Draw the actual alert message */ dp_write(srow, scol, " %s", msg); dp_write(srow + 2, dp_cols / 2 - ((int)sizeof(common_msg)-1) / 2, E_COLOR_YELLOW "%s" RESET_ATTRS, common_msg); } <file_sep>How to build and test the ancient versions of Tilck ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-01 "makefile works well. Removing make_iso.sh" * z-ancient-02 "fixing link2.ld and makefile" **Key-commits** (Cygwin only): * z-ancient-02-cygwin-01 "implementing return from syscalls" * z-ancient-02-cygwin-02 "the usermode printf works" * z-ancient-02-cygwin-03 "raising the term buf to 1024 lines and the scroll to 5 lines" **Notes:** The earliest versions of Tilck (called exOS at the time), have been developed under Windows using Cygwin and Cygwin's GCC 5.3, not MinGW. Therefore, compiling them is a bit tricky: the simplest setup requires an old 32-bit system (better if Ubuntu or Debian) and fair amount of patience. Also, keep in mind that many untagged commits might not work at all, especially with the Linux setup: they worked only using the *exact* configuration used at the time (see the Cygwin instructions below). Expect triple-faults and any kind of weirdness, especially with the Linux setup. **Linux instructions** (simpler, but less reliable): 1. Pick up an old 32-bit Linux distro like Ubuntu 14.04 LTS 2. Install the following packages: git, gcc, nasm, GNU make, gcc-mingw-w64-i686, qemu-system-i386 3. Enter in the Tilck main directory and run (using Bash): ``` w=/usr/bin/i686-w64-mingw32 && mkdir bin && \ $(cd $_ && for x in gcc ld objcopy; do ln -s $w-$x $x; done) && \ export PATH="`pwd`/bin:$PATH" ``` 4. Compile with: `make` 5. Run: `qemu-system-i386 -fda os2.img` **Cygwin instructions** (more complicated, but 99% close to the original setup): 1. Pick up a Windows system. At the time Windows 7 64-bit was used, but an up-to-date Windows 10 works too. 2. Install a 32-bit version of Cygwin from the Cygwin Time Machine: http://ctm.crouchingtigerhiddenfruitbat.org/pub/cygwin/setup/setup.html Even the latest 32-bit version (2.918) will work. On Windows 10. The original setup used Windows 7. It's not clear if that might make a difference. 3. Run from a Windows Command Prompt as Administrator: `setup-x86.exe -X`. That is necessary in order to use the Cygwin Time Machine mirrors. 4. When asked to choose the mirror, use: http://ctm.crouchingtigerhiddenfruitbat.org/pub/cygwin/circa/2016/03/02/124013 Or, in general, one from March 2016. The full list is here: http://ctm.crouchingtigerhiddenfruitbat.org/pub/cygwin/circa/index.html 5. Install the cygwin gcc 5.3.0 package (not mingw!), nasm, GNU make and git. 6. Run: `git config --global core.autocrlf false` 7. Clone Tilck's repo with: `git clone https://github.com/vvaltchev/tilck` 8. Checkout an ancient commit, before 4e8c99d6c8cc3dae5ef6faf52968c389939e5b74, like z-ancient-01. 9. Build the project with: `./make_iso.sh` or `make`, depending on the commit. 10. Pick-up and install QEMU for Windows from here: https://www.qemu.org/download/#windows The following version has been tested to work on Windows 10: https://qemu.weilnetz.de/w64/qemu-w64-setup-20220419.exe 11. Run the Win32 QEMU from Cygwin to test the kernel with: ``` "/cygdrive/c/Program Files/qemu/qemu-system-i386.exe" -fda os2.img ``` 12. [Optional] Install Bochs 2.7, the simulator originally used in the early commits. Run bochsdbg.exe and create a configuration adding os2.img as a 3.5" 1.44 MB floppy image. Run the simulation. Press "c" to continue when we hit the Bochs "magic debug breaks". Note: don't run the regular non-dbg version of Bochs, as it won't work because of the debug breaks. 13. Enjoy having spent an insane amount of time just to build a few ancient commits of this amazing project! ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-03 "making the kernel buildable only under a 32-bit linux" **Notes:** Commits in this group can be natively built on 32-bit Linux systems, with GCC 4.8. The Cygwin build has been abandoned because clearly was not good in the long term. **Instructions:** 1. Pick up an old *32-bit* Linux distro like Ubuntu 14.04 LTS 2. Install the following packages: git, gcc, nasm, GNU make, qemu-system-i386 2. Compile with: `make` 3. Run: `qemu-system-i386 -fda os2.img` ------------------------------------------------------------------------------------- **Key-commits:** * f3e41afe14aa "making the kernel buildable under linux64" * z-ancient-04 "moving qtcreator files in a dedicated dir and other minor stuff" * z-ancient-05 "adding int64 support on the 32-bit kernel and making RDTSC to work correctly" **Notes:** Commits in this group can be natively built on 64-bit Linux systems, with GCC 4.8. Keyboard echo and basic syscalls from userspace work. The first version of kmalloc() appeared here. Unit tests have been just introduced in the more recent commits in this group. **Instructions:** 1. Pick up an old *64-bit* Linux distro like Ubuntu 14.04 LTS 2. Install the following packages: git, gcc, nasm, GNU make, qemu-system-i386 3. Compile the kernel with: `make` 4. [optional] Compile the unit tests with: `make tests` 5. Run: `./run_qemu_linux` or `./run_qemu` 6. [optional] Run the unit tests with: `./build/unittests` ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-06 "making some scrips executable" **Notes:** Commits in this group are built with CMake for the first time. A simple `build_toolchain.sh` script has been just introduced. **Instructions:** 1. Pick up an old *64-bit* Ubuntu like 16.04 LTS, but more recent than 14.04 LTS. The GCC 5.4.0 compiler is supported here. 2. Install git, cmake, qemu-system-x86. 3. Run the follow script to install automatically the required packages (Ubuntu-only) and other stuff in the toolchain: `./build_toolchain.sh` 4. Configure the CMake build with: `mkdir build && cd build && cmake ..` 5. Compile with (from the build/ directory): `make` 6. Test the OS with: `./run_qemu` ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-07 "Add errno.h in the kernel" **Notes:** Commits in this group start to have a more powerful build_toolchain script and, for the first time, we start to download a toolchain from bootlin. The nasm compiler is not required on the system anymore and it's downloaded in the toolchain. **Instructions:** 1. Pick up an old *64-bit* Ubuntu like 16.04 LTS, but more recent than 14.04 LTS. 2. Install: git, cmake, qemu-system-x86. 3. Run: `./scripts/build_toolchain` 4. Configure the CMake build with: `mkdir build && cd build && cmake ..` 5. Compile with: `make` (from the build/ directory) 6. Test the OS with: `./run_qemu` ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-08 "Update README" **Notes:** Commits in this group start to have a better build_toolchain script and better CMake code. The unit tests now use the Googletest framework and the whole tooling around that is stable. This is the last commit before the project started to be developed full-time. **Instructions:** 1. Pick up an old *64-bit* Ubuntu like 16.04 LTS, but more recent than 14.04 LTS. 2. Install: git, cmake, qemu-system-x86. 3. Run: `./scripts/build_toolchain` 4. Configure the CMake build and build with just: `make` 5. Test the OS with: `./run_qemu` 6. [Optional] Build unit tests with: `make gtests` 7. [Optional] Run the unit tests with: `./build/gtests` ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-09 "[paging] Rename 'pageTableAddr' to 'ptaddr'" * z-ancient-10 "[shell] Implement the cd command" * z-ancient-11 "[self_tests] Fix fault_resumable_perf" * z-ancient-12 "[shell] Use asm to do the "int 0x80" syscall in cmd_syscall_perf" **Notes:** Commits in this group work for the first time on Ubuntu 18.04 LTS. At this point, started a bit of serious development for filesystem syscalls like read(), write() etc. Process management, scheduling and memory management have a fair amount of functionalities. The framebuffer console and the interactive EFI bootloader have been added here. Ubuntu 18.04 is required because the run_qemu scripts pass deprecated options to qemu-system-i386, which have been removed in the newer releases of QEMU. **Instructions:** 1. Pick up *64-bit* Ubuntu 18.04 LTS. 2. Install: git. 3. Run: `./scripts/build_toolchain` 4. Configure the CMake build and build with just: `make` 5. Test the OS with: `./build/run_qemu` (or `./build/run_nokvm_qemu`) 6. [Optional] Test the UEFI boot with: `./build/run_efi_qemu32` [requires extra toolchain steps] 7. [Optional] Build unit tests with: `make gtests` 8. [Optional] Run the unit tests with: `./build/gtests` ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-13 "Update README.md" **Notes:** The commits in this group finally have a minimal devshell with `ls` working. The musl library is used by default. The shell forwards the unknown commands to busybox. Also, project's name changes from "experimentOS" to "Tilck". **Instructions:** Exactly as above. Ubuntu 18.04 LTS is still required because of the QEMU scripts. ------------------------------------------------------------------------------------- **Key-commits:** * z-ancient-14 "[term] Fix a bug related with \n + improve debug_per_task_cb()" * z-ancient-15 "Merge pull request #57 from vvaltchev/term" **Notes:** This is the last group of "ancient" commits before the stable-* series starts. Here the devshell and the console get improved. Multiple TTYs are supported. **Instructions:** Exactly as above. Ubuntu 18.04 LTS is still required because of the QEMU scripts. ------------------------------------------------------------------------------------- Starting from the commit tagged as stable-001, it's possible to build and run Tilck on modern Linux distributions like Ubuntu 20.04 LTS. The devshell has the `runall` command and Busybox's version of `vi` works. Unfortunately, some scripts like `run_all_tests` still require Python 2.7.x. That has been fixed between stable-004 and stable-005. <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/color_defs.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/term.h> #define VIDEO_ADDR ((u16 *) KERNEL_PA_TO_VA(0xB8000)) #define VIDEO_COLS 80 #define VIDEO_ROWS 25 static void textmode_clear_row(u16 row_num, u8 color) { ASSERT(row_num < VIDEO_ROWS); memset16(VIDEO_ADDR + VIDEO_COLS * row_num, make_vgaentry(' ', color), VIDEO_COLS); } static void textmode_set_char_at(u16 row, u16 col, u16 entry) { ASSERT(row < VIDEO_ROWS); ASSERT(col < VIDEO_COLS); volatile u16 *video = (volatile u16 *)VIDEO_ADDR; video[row * VIDEO_COLS + col] = entry; } static void textmode_set_row(u16 row, u16 *data, bool fpu_allowed) { ASSERT(row < VIDEO_ROWS); void *dest_addr = VIDEO_ADDR + row * VIDEO_COLS; void *src_addr = data; memcpy32(dest_addr, src_addr, VIDEO_COLS >> 1); } /* * This function works, but in practice is 2x slower than just using term's * generic scroll and re-draw the whole screen. */ static void textmode_scroll_one_line_up(void) { memcpy32(VIDEO_ADDR, VIDEO_ADDR + VIDEO_COLS, ((VIDEO_ROWS - 1) * VIDEO_COLS) >> 1); } /* * -------- cursor management functions ----------- * * Here: http://www.osdever.net/FreeVGA/vga/textcur.htm * There is a lot of precious information about how to work with the cursor. */ static void textmode_move_cursor(u16 row, u16 col, int color /* ignored */) { u16 position = (row * VIDEO_COLS) + col; // cursor LOW port to vga INDEX register outb(0x3D4, 0x0F); outb(0x3D5, LO_BITS(position, 8, u8)); // cursor HIGH port to vga INDEX register outb(0x3D4, 0x0E); outb(0x3D5, LO_BITS(position >> 8, 8, u8)); } static void textmode_enable_cursor(void) { const u8 s_start = 0; /* scanline start */ const u8 s_end = 15; /* scanline end */ outb(0x3D4, 0x0A); outb(0x3D5, (inb(0x3D5) & 0xC0) | s_start); // Note: mask with 0xC0 // which keeps only the // higher 2 bits in order // to set bit 5 to 0. outb(0x3D4, 0x0B); outb(0x3D5, (inb(0x3D5) & 0xE0) | s_end); // Mask with 0xE0 keeps // the higher 3 bits. } static void textmode_disable_cursor(void) { /* * Move the cursor off-screen. Yes, it seems an ugly way to do that, but it * seems to be the most compatible way to "disable" the cursor. * As claimed here: http://www.osdever.net/FreeVGA/vga/textcur.htm#enable * the "official" method below (commented) does not work on some hardware. * On my Hannspree SN10E1, I can confirm that the code below causes strange * effects: the cursor is offset-ed 3 chars at the right of the position * it should be. */ textmode_move_cursor(VIDEO_ROWS, VIDEO_COLS, 0); // outb(0x3D4, 0x0A); // outb(0x3D5, inb(0x3D5) | 0x20); } static const struct video_interface ega_text_mode_i = { textmode_set_char_at, textmode_set_row, textmode_clear_row, textmode_move_cursor, textmode_enable_cursor, textmode_disable_cursor, NULL, /* textmode_scroll_one_line_up (see the comment) */ NULL, /* redraw_static_elements */ NULL, /* disable_static_elems_refresh */ NULL, /* enable_static_elems_refresh */ }; void init_textmode_console(void) { pdir_t *pdir = get_curr_pdir(); if (pdir != NULL && !is_mapped(pdir, VIDEO_ADDR)) { int rc = map_page(pdir, VIDEO_ADDR, KERNEL_VA_TO_PA(VIDEO_ADDR), PAGING_FL_RW); if (rc < 0) panic("textmode_console: unable to map VIDEO_ADDR in the virt space"); } init_first_video_term(&ega_text_mode_i, VIDEO_ROWS, VIDEO_COLS, -1); } <file_sep>/****************************************************************************** * * Module Name: utosi - Support for the _OSI predefined control method * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utosi") /****************************************************************************** * * ACPICA policy for new _OSI strings: * * It is the stated policy of ACPICA that new _OSI strings will be integrated * into this module as soon as possible after they are defined. It is strongly * recommended that all ACPICA hosts mirror this policy and integrate any * changes to this module as soon as possible. There are several historical * reasons behind this policy: * * 1) New BIOSs tend to test only the case where the host responds TRUE to * the latest version of Windows, which would respond to the latest/newest * _OSI string. Not responding TRUE to the latest version of Windows will * risk executing untested code paths throughout the DSDT and SSDTs. * * 2) If a new _OSI string is recognized only after a significant delay, this * has the potential to cause problems on existing working machines because * of the possibility that a new and different path through the ASL code * will be executed. * * 3) New _OSI strings are tending to come out about once per year. A delay * in recognizing a new string for a significant amount of time risks the * release of another string which only compounds the initial problem. * *****************************************************************************/ /* * Strings supported by the _OSI predefined control method (which is * implemented internally within this module.) * * March 2009: Removed "Linux" as this host no longer wants to respond true * for this string. Basically, the only safe OS strings are windows-related * and in many or most cases represent the only test path within the * BIOS-provided ASL code. * * The last element of each entry is used to track the newest version of * Windows that the BIOS has requested. */ static ACPI_INTERFACE_INFO AcpiDefaultSupportedInterfaces[] = { /* Operating System Vendor Strings */ {"Windows 2000", NULL, 0, ACPI_OSI_WIN_2000}, /* Windows 2000 */ {"Windows 2001", NULL, 0, ACPI_OSI_WIN_XP}, /* Windows XP */ {"Windows 2001 SP1", NULL, 0, ACPI_OSI_WIN_XP_SP1}, /* Windows XP SP1 */ {"Windows 2001.1", NULL, 0, ACPI_OSI_WINSRV_2003}, /* Windows Server 2003 */ {"Windows 2001 SP2", NULL, 0, ACPI_OSI_WIN_XP_SP2}, /* Windows XP SP2 */ {"Windows 2001.1 SP1", NULL, 0, ACPI_OSI_WINSRV_2003_SP1}, /* Windows Server 2003 SP1 - Added 03/2006 */ {"Windows 2006", NULL, 0, ACPI_OSI_WIN_VISTA}, /* Windows Vista - Added 03/2006 */ {"Windows 2006.1", NULL, 0, ACPI_OSI_WINSRV_2008}, /* Windows Server 2008 - Added 09/2009 */ {"Windows 2006 SP1", NULL, 0, ACPI_OSI_WIN_VISTA_SP1}, /* Windows Vista SP1 - Added 09/2009 */ {"Windows 2006 SP2", NULL, 0, ACPI_OSI_WIN_VISTA_SP2}, /* Windows Vista SP2 - Added 09/2010 */ {"Windows 2009", NULL, 0, ACPI_OSI_WIN_7}, /* Windows 7 and Server 2008 R2 - Added 09/2009 */ {"Windows 2012", NULL, 0, ACPI_OSI_WIN_8}, /* Windows 8 and Server 2012 - Added 08/2012 */ {"Windows 2013", NULL, 0, ACPI_OSI_WIN_8_1}, /* Windows 8.1 and Server 2012 R2 - Added 01/2014 */ {"Windows 2015", NULL, 0, ACPI_OSI_WIN_10}, /* Windows 10 - Added 03/2015 */ {"Windows 2016", NULL, 0, ACPI_OSI_WIN_10_RS1}, /* Windows 10 version 1607 - Added 12/2017 */ {"Windows 2017", NULL, 0, ACPI_OSI_WIN_10_RS2}, /* Windows 10 version 1703 - Added 12/2017 */ {"Windows 2017.2", NULL, 0, ACPI_OSI_WIN_10_RS3}, /* Windows 10 version 1709 - Added 02/2018 */ {"Windows 2018", NULL, 0, ACPI_OSI_WIN_10_RS4}, /* Windows 10 version 1803 - Added 11/2018 */ {"Windows 2018.2", NULL, 0, ACPI_OSI_WIN_10_RS5}, /* Windows 10 version 1809 - Added 11/2018 */ {"Windows 2019", NULL, 0, ACPI_OSI_WIN_10_19H1}, /* Windows 10 version 1903 - Added 08/2019 */ /* Feature Group Strings */ {"Extended Address Space Descriptor", NULL, ACPI_OSI_FEATURE, 0}, /* * All "optional" feature group strings (features that are implemented * by the host) should be dynamically modified to VALID by the host via * AcpiInstallInterface or AcpiUpdateInterfaces. Such optional feature * group strings are set as INVALID by default here. */ {"Module Device", NULL, ACPI_OSI_OPTIONAL_FEATURE, 0}, {"Processor Device", NULL, ACPI_OSI_OPTIONAL_FEATURE, 0}, {"3.0 Thermal Model", NULL, ACPI_OSI_OPTIONAL_FEATURE, 0}, {"3.0 _SCP Extensions", NULL, ACPI_OSI_OPTIONAL_FEATURE, 0}, {"Processor Aggregator Device", NULL, ACPI_OSI_OPTIONAL_FEATURE, 0} }; /******************************************************************************* * * FUNCTION: AcpiUtInitializeInterfaces * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Initialize the global _OSI supported interfaces list * ******************************************************************************/ ACPI_STATUS AcpiUtInitializeInterfaces ( void) { ACPI_STATUS Status; UINT32 i; Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } AcpiGbl_SupportedInterfaces = AcpiDefaultSupportedInterfaces; /* Link the static list of supported interfaces */ for (i = 0; i < (ACPI_ARRAY_LENGTH (AcpiDefaultSupportedInterfaces) - 1); i++) { AcpiDefaultSupportedInterfaces[i].Next = &AcpiDefaultSupportedInterfaces[(ACPI_SIZE) i + 1]; } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtInterfaceTerminate * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Delete all interfaces in the global list. Sets * AcpiGbl_SupportedInterfaces to NULL. * ******************************************************************************/ ACPI_STATUS AcpiUtInterfaceTerminate ( void) { ACPI_STATUS Status; ACPI_INTERFACE_INFO *NextInterface; Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } NextInterface = AcpiGbl_SupportedInterfaces; while (NextInterface) { AcpiGbl_SupportedInterfaces = NextInterface->Next; if (NextInterface->Flags & ACPI_OSI_DYNAMIC) { /* Only interfaces added at runtime can be freed */ ACPI_FREE (NextInterface->Name); ACPI_FREE (NextInterface); } else { /* Interface is in static list. Reset it to invalid or valid. */ if (NextInterface->Flags & ACPI_OSI_DEFAULT_INVALID) { NextInterface->Flags |= ACPI_OSI_INVALID; } else { NextInterface->Flags &= ~ACPI_OSI_INVALID; } } NextInterface = AcpiGbl_SupportedInterfaces; } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtInstallInterface * * PARAMETERS: InterfaceName - The interface to install * * RETURN: Status * * DESCRIPTION: Install the interface into the global interface list. * Caller MUST hold AcpiGbl_OsiMutex * ******************************************************************************/ ACPI_STATUS AcpiUtInstallInterface ( ACPI_STRING InterfaceName) { ACPI_INTERFACE_INFO *InterfaceInfo; /* Allocate info block and space for the name string */ InterfaceInfo = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_INTERFACE_INFO)); if (!InterfaceInfo) { return (AE_NO_MEMORY); } InterfaceInfo->Name = ACPI_ALLOCATE_ZEROED (strlen (InterfaceName) + 1); if (!InterfaceInfo->Name) { ACPI_FREE (InterfaceInfo); return (AE_NO_MEMORY); } /* Initialize new info and insert at the head of the global list */ strcpy (InterfaceInfo->Name, InterfaceName); InterfaceInfo->Flags = ACPI_OSI_DYNAMIC; InterfaceInfo->Next = AcpiGbl_SupportedInterfaces; AcpiGbl_SupportedInterfaces = InterfaceInfo; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtRemoveInterface * * PARAMETERS: InterfaceName - The interface to remove * * RETURN: Status * * DESCRIPTION: Remove the interface from the global interface list. * Caller MUST hold AcpiGbl_OsiMutex * ******************************************************************************/ ACPI_STATUS AcpiUtRemoveInterface ( ACPI_STRING InterfaceName) { ACPI_INTERFACE_INFO *PreviousInterface; ACPI_INTERFACE_INFO *NextInterface; PreviousInterface = NextInterface = AcpiGbl_SupportedInterfaces; while (NextInterface) { if (!strcmp (InterfaceName, NextInterface->Name)) { /* * Found: name is in either the static list * or was added at runtime */ if (NextInterface->Flags & ACPI_OSI_DYNAMIC) { /* Interface was added dynamically, remove and free it */ if (PreviousInterface == NextInterface) { AcpiGbl_SupportedInterfaces = NextInterface->Next; } else { PreviousInterface->Next = NextInterface->Next; } ACPI_FREE (NextInterface->Name); ACPI_FREE (NextInterface); } else { /* * Interface is in static list. If marked invalid, then * it does not actually exist. Else, mark it invalid. */ if (NextInterface->Flags & ACPI_OSI_INVALID) { return (AE_NOT_EXIST); } NextInterface->Flags |= ACPI_OSI_INVALID; } return (AE_OK); } PreviousInterface = NextInterface; NextInterface = NextInterface->Next; } /* Interface was not found */ return (AE_NOT_EXIST); } /******************************************************************************* * * FUNCTION: AcpiUtUpdateInterfaces * * PARAMETERS: Action - Actions to be performed during the * update * * RETURN: Status * * DESCRIPTION: Update _OSI interface strings, disabling or enabling OS vendor * strings or/and feature group strings. * Caller MUST hold AcpiGbl_OsiMutex * ******************************************************************************/ ACPI_STATUS AcpiUtUpdateInterfaces ( UINT8 Action) { ACPI_INTERFACE_INFO *NextInterface; NextInterface = AcpiGbl_SupportedInterfaces; while (NextInterface) { if (((NextInterface->Flags & ACPI_OSI_FEATURE) && (Action & ACPI_FEATURE_STRINGS)) || (!(NextInterface->Flags & ACPI_OSI_FEATURE) && (Action & ACPI_VENDOR_STRINGS))) { if (Action & ACPI_DISABLE_INTERFACES) { /* Mark the interfaces as invalid */ NextInterface->Flags |= ACPI_OSI_INVALID; } else { /* Mark the interfaces as valid */ NextInterface->Flags &= ~ACPI_OSI_INVALID; } } NextInterface = NextInterface->Next; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtGetInterface * * PARAMETERS: InterfaceName - The interface to find * * RETURN: ACPI_INTERFACE_INFO if found. NULL if not found. * * DESCRIPTION: Search for the specified interface name in the global list. * Caller MUST hold AcpiGbl_OsiMutex * ******************************************************************************/ ACPI_INTERFACE_INFO * AcpiUtGetInterface ( ACPI_STRING InterfaceName) { ACPI_INTERFACE_INFO *NextInterface; NextInterface = AcpiGbl_SupportedInterfaces; while (NextInterface) { if (!strcmp (InterfaceName, NextInterface->Name)) { return (NextInterface); } NextInterface = NextInterface->Next; } return (NULL); } /******************************************************************************* * * FUNCTION: AcpiUtOsiImplementation * * PARAMETERS: WalkState - Current walk state * * RETURN: Status * Integer: TRUE (0) if input string is matched * FALSE (-1) if string is not matched * * DESCRIPTION: Implementation of the _OSI predefined control method. When * an invocation of _OSI is encountered in the system AML, * control is transferred to this function. * * (August 2016) * Note: _OSI is now defined to return "Ones" to indicate a match, for * compatibility with other ACPI implementations. On a 32-bit DSDT, Ones * is 0xFFFFFFFF. On a 64-bit DSDT, Ones is 0xFFFFFFFFFFFFFFFF * (ACPI_UINT64_MAX). * * This function always returns ACPI_UINT64_MAX for TRUE, and later code * will truncate this to 32 bits if necessary. * ******************************************************************************/ ACPI_STATUS AcpiUtOsiImplementation ( ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *StringDesc; ACPI_OPERAND_OBJECT *ReturnDesc; ACPI_INTERFACE_INFO *InterfaceInfo; ACPI_INTERFACE_HANDLER InterfaceHandler; ACPI_STATUS Status; UINT64 ReturnValue; ACPI_FUNCTION_TRACE (UtOsiImplementation); /* Validate the string input argument (from the AML caller) */ StringDesc = WalkState->Arguments[0].Object; if (!StringDesc || (StringDesc->Common.Type != ACPI_TYPE_STRING)) { return_ACPI_STATUS (AE_TYPE); } /* Create a return object */ ReturnDesc = AcpiUtCreateInternalObject (ACPI_TYPE_INTEGER); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Default return value is 0, NOT SUPPORTED */ ReturnValue = 0; Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ReturnDesc); return_ACPI_STATUS (Status); } /* Lookup the interface in the global _OSI list */ InterfaceInfo = AcpiUtGetInterface (StringDesc->String.Pointer); if (InterfaceInfo && !(InterfaceInfo->Flags & ACPI_OSI_INVALID)) { /* * The interface is supported. * Update the OsiData if necessary. We keep track of the latest * version of Windows that has been requested by the BIOS. */ if (InterfaceInfo->Value > AcpiGbl_OsiData) { AcpiGbl_OsiData = InterfaceInfo->Value; } ReturnValue = ACPI_UINT64_MAX; } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); /* * Invoke an optional _OSI interface handler. The host OS may wish * to do some interface-specific handling. For example, warn about * certain interfaces or override the true/false support value. */ InterfaceHandler = AcpiGbl_InterfaceHandler; if (InterfaceHandler) { if (InterfaceHandler ( StringDesc->String.Pointer, (UINT32) ReturnValue)) { ReturnValue = ACPI_UINT64_MAX; } } ACPI_DEBUG_PRINT_RAW ((ACPI_DB_INFO, "ACPI: BIOS _OSI(\"%s\") is %ssupported\n", StringDesc->String.Pointer, ReturnValue == 0 ? "not " : "")); /* Complete the return object */ ReturnDesc->Integer.Value = ReturnValue; WalkState->ReturnDesc = ReturnDesc; return_ACPI_STATUS (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static long ramfs_insert_remove_entry_cmp(const void *a, const void *b) { const struct ramfs_entry *e1 = a; const struct ramfs_entry *e2 = b; return strcmp(e1->name, e2->name); } static long ramfs_find_entry_cmp(const void *obj, const void *valptr) { const struct ramfs_entry *e = obj; const char *searched_str = valptr; return strcmp(e->name, searched_str); } static int ramfs_dir_add_entry(struct ramfs_inode *idir, const char *iname, struct ramfs_inode *ie) { struct ramfs_entry *e; size_t enl = strlen(iname) + 1; ASSERT(idir->type == VFS_DIR); if (enl == 1) return -ENOENT; if (enl > sizeof(e->name)) return -ENAMETOOLONG; if (!(e = kalloc_obj(struct ramfs_entry))) return -ENOSPC; ASSERT(ie->parent_dir != NULL); bintree_node_init(&e->node); list_node_init(&e->lnode); e->inode = ie; memcpy(e->name, iname, enl); if (e->name[enl-2] == '/') { e->name[enl-2] = 0; /* drop the trailing slash */ enl--; } e->name_len = (u8) enl; bintree_insert(&idir->entries_tree_root, e, ramfs_insert_remove_entry_cmp, struct ramfs_entry, node); list_add_tail(&idir->entries_list, &e->lnode); ie->nlink++; idir->num_entries++; return 0; } static void ramfs_dir_remove_entry(struct ramfs_inode *idir, struct ramfs_entry *e) { struct ramfs_handle *pos; struct ramfs_inode *ie = e->inode; ASSERT(idir->type == VFS_DIR); /* * Before removing this entry, we have to check if, among the handles opened * for `idir`, there are any having dpos == e. For each one of them, we have * to move `dpos` forward, before removing the entry `e`. */ list_for_each_ro(pos, &idir->handles_list, node) { if (pos->dpos == e) pos->dpos = list_next_obj(pos->dpos, lnode); } bintree_remove(&idir->entries_tree_root, e, ramfs_insert_remove_entry_cmp, struct ramfs_entry, node); list_remove(&e->lnode); ASSERT(ie->nlink > 0); ie->nlink--; idir->num_entries--; kfree_obj(e, struct ramfs_entry); } static struct ramfs_entry * ramfs_dir_get_entry_by_name(struct ramfs_inode *idir, const char *name, ssize_t len) { char buf[RAMFS_ENTRY_MAX_LEN]; memcpy(buf, name, (size_t) len); buf[len] = 0; return bintree_find(idir->entries_tree_root, buf, ramfs_find_entry_cmp, struct ramfs_entry, node); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include "defs.h" #include "utils.h" #include <elf.h> static inline bool IsMemRegionUsable(EFI_MEMORY_DESCRIPTOR *m) { return m->Type == EfiConventionalMemory || m->Type == EfiBootServicesCode || m->Type == EfiBootServicesData; } static inline EFI_PHYSICAL_ADDRESS GetEndOfRegion(EFI_MEMORY_DESCRIPTOR *m) { return m->PhysicalStart + m->NumberOfPages * PAGE_SIZE; } EFI_STATUS KernelLoadMemoryChecks(void) { EFI_MEMORY_DESCRIPTOR *m; EFI_PHYSICAL_ADDRESS p = KERNEL_PADDR; EFI_PHYSICAL_ADDRESS pend = KERNEL_PADDR + get_loaded_kernel_mem_sz(); while (p < pend) { m = GetMemDescForAddress(p); if (!m) { Print(L"ERROR: unable to find memory region for kernel's paddr: " "0x%08x\n", p); return EFI_LOAD_ERROR; } if (!IsMemRegionUsable(m)) { Print(L"ERROR: kernel's load area contains unusable mem areas\n"); Print(L"Kernel's load area: 0x%08x - 0x%08x\n", KERNEL_PADDR, pend); Print(L"Unusable mem region: 0x%08x - 0x%08x\n", m->PhysicalStart, GetEndOfRegion(m)); Print(L"Region type: %d\n", m->Type); return EFI_LOAD_ERROR; } p = GetEndOfRegion(m); } return EFI_SUCCESS; } EFI_STATUS LoadKernelFile(CHAR16 *filePath, EFI_PHYSICAL_ADDRESS *paddr) { static EFI_PHYSICAL_ADDRESS sPaddr; static UINTN sSize; EFI_STATUS status = EFI_LOAD_ERROR; if (sPaddr) { BS->FreePages(sPaddr, sSize / PAGE_SIZE); } /* Temporary load the whole kernel file in a safe location */ status = LoadFileFromDisk(gFileProt, &sPaddr, &sSize, filePath); HANDLE_EFI_ERROR("LoadFileFromDisk"); *paddr = sPaddr; end: return status; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include "devshell.h" #include "sysenter.h" #include "test_common.h" int cmd_brk(int argc, char **argv) { const size_t alloc_size = 1024 * 1024; void *orig_brk = (void *)syscall(SYS_brk, 0); void *b = orig_brk; size_t tot_allocated = 0; for (int i = 0; i < 128; i++) { void *new_brk = b + alloc_size; b = (void *)syscall(SYS_brk, b + alloc_size); if (b != new_brk) break; tot_allocated += alloc_size; } //printf("tot allocated: %u KB\n", tot_allocated / 1024); b = (void *)syscall(SYS_brk, orig_brk); if (b != orig_brk) { printf("Unable to free mem with brk()\n"); return 1; } return 0; } int cmd_mmap(int argc, char **argv) { const int iters_count = 10; const size_t alloc_size = 1 * MB; void *arr[1024]; int max_mb = -1; ull_t tot_duration = 0; for (int iter = 0; iter < iters_count; iter++) { int i; ull_t start = RDTSC(); for (i = 0; i < 64; i++) { errno = 0; void *res = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (res == (void*) -1) { i--; break; } arr[i] = res; } i--; tot_duration += (RDTSC() - start); if (max_mb < 0) { max_mb = i; } else { if (i != max_mb) { printf("[iter: %u] Unable to alloc max_mb (%u) as previous iters\n", iter, max_mb); return 1; } } printf("[iter: %u][mmap_test] Mapped %u MB\n", iter, i + 1); start = RDTSC(); for (; i >= 0; i--) { int rc = munmap(arr[i], alloc_size); if (rc != 0) { printf("munmap(%p) failed with error: %s\n", arr[i], strerror(errno)); return 1; } } tot_duration += (RDTSC() - start); } printf("\nAvg. cycles for mmap + munmap %u MB: %llu million\n", max_mb + 1, (tot_duration / iters_count) / 1000000); return 0; } static void no_munmap_bad_child(void) { const size_t alloc_size = 128 * KB; void *res = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (res == (void*) -1) { printf(STR_CHILD "mmap %zu KB failed!\n", alloc_size / KB); exit(1); } /* DO NOT munmap the memory, expecting the kernel to do that! */ exit(0); } int cmd_mmap2(int argc, char **argv) { int child; int wstatus; child = fork(); if (!child) no_munmap_bad_child(); waitpid(child, &wstatus, 0); return 0; } static size_t fork_oom_alloc_size; static void fork_oom_child(void *buf) { printf("Child [%d]: writing to the whole CoW buffer...\n", getpid()); memset(buf, 0xBB, fork_oom_alloc_size); printf("Child [%d]: done, without failing! [unexpected]\n", getpid()); exit(0); } /* * This is a simply code to empirically discover how much memory we can commit * at the moment. */ static void estimate_usable_mem_child(size_t step_size, int rfd, int wfd) { size_t mem = 0; int rc; printf(STR_CHILD "Pid: %d\n", getpid()); while (true) { char *buf = malloc(step_size); memset(buf, 'A', step_size); mem += step_size; //printf(STR_CHILD "Committed mem: %zu MB\n", mem / MB); rc = write(wfd, &mem, sizeof(mem)); if (rc < 0) { printf(STR_CHILD "write on pipe failed: %s\n", strerror(errno)); break; } } /* We're not supposed to get here */ } static size_t mm_estimate_usable_mem_int(size_t step_size) { int rc, pipefd[2]; int rfd, wfd, wstatus; size_t msg, mem = 0; pid_t childpid; printf(STR_PARENT "Estimating usable memory..\n"); rc = pipe(pipefd); DEVSHELL_CMD_ASSERT(rc >= 0); rfd = pipefd[0]; wfd = pipefd[1]; childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) { estimate_usable_mem_child(step_size, rfd, wfd); exit(0); } rc = fcntl(rfd, F_SETFL, O_NONBLOCK); if (rc < 0) { printf(STR_PARENT "fcntl failed: %s\n", strerror(errno)); goto out; } while (true) { rc = read(rfd, &msg, sizeof(msg)); if (rc < 0) { if (errno == EAGAIN) { rc = waitpid(childpid, &wstatus, WNOHANG); if (rc < 0) { printf(STR_PARENT "waitpid failed: %s\n", strerror(errno)); break; } if (rc == childpid) { if (WIFEXITED(wstatus)) { printf(STR_PARENT "[unexpected] child exited with: %d\n", WEXITSTATUS(wstatus)); } else { printf(STR_PARENT "Child killed by signal %d\n", WTERMSIG(wstatus)); } break; } usleep(50 * 1000); continue; } printf(STR_PARENT "read from pipe failed: %s\n", strerror(errno)); mem = 0; goto out; } if (rc == 0) { if (mem > 0) printf(STR_PARENT "read 0\n"); else printf(STR_PARENT "unexpected read 0\n"); break; } /* Update the max memory we were able to commit */ mem = msg; } if (mem) { printf(STR_PARENT "Estimated usable memory: %zu MB\n", mem / MB); } out: close(rfd); close(wfd); return mem; } size_t mm_estimate_usable_mem(void) { static size_t est_usable_mem; if (!est_usable_mem) { est_usable_mem = mm_estimate_usable_mem_int(1 * MB); if (est_usable_mem < 16 * MB) { /* We'd need a more accurate estimate */ printf("Pid [%d]: Too little usable memory: %zu MB. " "Let's do a finer estimation.\n", getpid(), fork_oom_alloc_size / MB); est_usable_mem = mm_estimate_usable_mem_int(4 * KB); if (!est_usable_mem) { printf("ERROR: unable to estimate usable memory!\n"); return 0; } printf("Pid [%d]: Estimated usable mem: %zu KB\n", getpid(), est_usable_mem / KB); } else { printf("Pid [%d]: Estimated usable mem: %zu MB\n", getpid(), est_usable_mem / MB); } } return est_usable_mem; } /* * Alloc a lot of CoW memory and check that the kernel kills the process in * case an attempt to copy a CoW page fails because we're out of memory. */ int cmd_fork_oom(int argc, char **argv) { void *buf; int rc; if (FORK_NO_COW) { printf(PFX "[SKIP] because FORK_NO_COW=1\n"); return 0; } if (!getenv("TILCK")) { printf(PFX "[SKIP] because we're not running on Tilck\n"); return 0; } fork_oom_alloc_size = mm_estimate_usable_mem(); DEVSHELL_CMD_ASSERT(fork_oom_alloc_size != 0); if (fork_oom_alloc_size <= 500 * MB) { /* * Alloc just a bit more than half of the available memory, because in any * case it won't be possible both the parent and child process to commit * all of that. This makes the test a bit faster ;-) */ fork_oom_alloc_size = fork_oom_alloc_size / 2 + fork_oom_alloc_size / 8; } else { /* * We're running on a machine with plenty of memory, but Tilck's heap * for user mappings is limited to 512 MB at the moment. Therefore, if * we don't commit enough memory, it's possible this test to fail because * the overall memory on the system will be enough for both the parent * and the child. * * Therefore, in this case we just alloc a bit less than the maximum * possible, leaving some space for the fork() itself to succeed. */ fork_oom_alloc_size -= 1 * MB; } if (fork_oom_alloc_size >= 8 * MB) printf("Parent [%d]: Alloc %zu MB...\n", getpid(),fork_oom_alloc_size/MB); else printf("Parent [%d]: Alloc %zu KB...\n", getpid(),fork_oom_alloc_size/KB); buf = malloc(fork_oom_alloc_size); if (!buf) { printf("Parent [%d]: Alloc failed!\n", getpid()); exit(1); } printf("Parent [%d]: Write to the buffer...\n", getpid()); memset(buf, 0xAA, fork_oom_alloc_size); printf("Parent: Done. Now, fork()..\n"); rc = test_sig(&fork_oom_child, buf, SIGKILL, 0, 0); free(buf); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <limits> #include <random> #include <string> #include <type_traits> #include <gtest/gtest.h> using namespace std; extern "C" { #include <tilck/common/printk.h> } template <typename ...Args> string spk_wrapper(const char *fmt, Args&& ...args) { char buf[64]; snprintk(buf, sizeof(buf), fmt, args...); return buf; } TEST(printk, basic) { EXPECT_EQ(spk_wrapper("%%"), "%"); EXPECT_EQ(spk_wrapper("%d", 1234), "1234"); EXPECT_EQ(spk_wrapper("%d", -2), "-2"); EXPECT_EQ(spk_wrapper("%i", -123), "-123"); EXPECT_EQ(spk_wrapper("%x", 0xaab3), "aab3"); EXPECT_EQ(spk_wrapper("%X", 0xaab3), "AAB3"); EXPECT_EQ(spk_wrapper("%o", 0755), "755"); EXPECT_EQ(spk_wrapper("%c", 'a'), "a"); EXPECT_EQ(spk_wrapper("%ld", (long)1234), "1234"); EXPECT_EQ(spk_wrapper("%5d", 2), " 2"); EXPECT_EQ(spk_wrapper("%05d", 2), "00002"); EXPECT_EQ(spk_wrapper("%-5d", 2), "2 "); EXPECT_EQ(spk_wrapper("%5s", "abc"), " abc"); EXPECT_EQ(spk_wrapper("%-5s", "abc"), "abc "); EXPECT_EQ(spk_wrapper("%5c", 'a'), " a"); EXPECT_EQ(spk_wrapper("%-5c", 'a'), "a "); EXPECT_EQ(spk_wrapper("%6X", 0xaab3), " AAB3"); EXPECT_EQ(spk_wrapper("%06X", 0xaab3), "00AAB3"); EXPECT_EQ(spk_wrapper("%lld", 9223372036854775807ll), "9223372036854775807"); EXPECT_EQ(spk_wrapper("%llx", 0xaabbccddeeffll), "aabbccddeeff"); /* Multi-param string */ EXPECT_EQ(spk_wrapper("p[%s] = %d", "opt1", 1234), "p[opt1] = 1234"); } TEST(printk, rare) { /* String precision */ EXPECT_EQ(spk_wrapper("%.3s", "abcdef"), "abc"); /* Precision for integers treated as lpad */ EXPECT_EQ(spk_wrapper("%.4d", 1), "0001"); /* Same as long long */ EXPECT_EQ(spk_wrapper("%Lx", 0xaabbccddeeffll), "aabbccddeeff"); EXPECT_EQ(spk_wrapper("%qx", 0xaabbccddeeffll), "aabbccddeeff"); EXPECT_EQ(spk_wrapper("%jx", 0xaabbccddeeffll), "aabbccddeeff"); /* Half (short) and half half (char) */ EXPECT_EQ(spk_wrapper("%x", (signed char)-1), "ffffffff"); EXPECT_EQ(spk_wrapper("%hx", (signed char)-1), "ffff"); EXPECT_EQ(spk_wrapper("%hhx", (signed char)-1), "ff"); EXPECT_EQ(spk_wrapper("%hd", (short)-1234), "-1234"); EXPECT_EQ(spk_wrapper("%hhd", (signed char)-123), "-123"); /* Corner cases */ EXPECT_EQ(spk_wrapper("%05c", 'a'), " a"); /* zero-pad is ignored */ } TEST(printk, varparam) { EXPECT_EQ(spk_wrapper("%.*s", 3, "abcdef"), "abc"); /* precision */ EXPECT_EQ(spk_wrapper("%.*s", 0, "abcdef"), ""); /* precision=0 */ EXPECT_EQ(spk_wrapper("%*s", 6, "abc"), " abc"); /* left-padding */ EXPECT_EQ(spk_wrapper("%-*s", 6, "abc"), "abc "); /* right-padding */ EXPECT_EQ(spk_wrapper("%0*d", 5, 23), "00023"); /* zero-pad */ EXPECT_EQ(spk_wrapper("%*d", 5, 23), " 23"); /* numeric left-pad */ EXPECT_EQ(spk_wrapper("%-*d", 5, 23), "23 "); /* numeric right-pad */ EXPECT_EQ(spk_wrapper("%*d", -5, 23), "23 "); /* negative num lpad */ EXPECT_EQ(spk_wrapper("%-*d", -5, 23), "23 "); /* negative num rpad */ } TEST(printk, hashsign) { EXPECT_EQ(spk_wrapper("%#x", 0x123), "0x123"); // Just prepend "0x" EXPECT_EQ(spk_wrapper("%#08x", 0x123), "0x000123"); // "0x" counted in lpad EXPECT_EQ(spk_wrapper("%#8x", 0x123), " 0x123"); // "0x" counted in lpad EXPECT_EQ(spk_wrapper("%#-8x", 0x123), "0x123 "); // "0x" counted in rpad EXPECT_EQ(spk_wrapper("%#08X", 0xabc), "0x000ABC"); // "0x" counted in lpad EXPECT_EQ(spk_wrapper("%#o", 0755), "0755"); // Just prepend "0" EXPECT_EQ(spk_wrapper("%#08o", 0755), "00000755"); // "0" counted in lpad EXPECT_EQ(spk_wrapper("%#8o", 0755), " 0755"); // "0" counted in lpad EXPECT_EQ(spk_wrapper("%#-8o", 0755), "0755 "); // "0" counted in rpad /* Corner cases */ EXPECT_EQ(spk_wrapper("%##x", 0x123), "0x123"); EXPECT_EQ(spk_wrapper("%###x", 0x123), "0x123"); } TEST(printk, truncated_seq) { EXPECT_EQ(spk_wrapper("%z"), ""); EXPECT_EQ(spk_wrapper("%l"), ""); EXPECT_EQ(spk_wrapper("%ll"), ""); EXPECT_EQ(spk_wrapper("%0"), ""); EXPECT_EQ(spk_wrapper("%5"), ""); EXPECT_EQ(spk_wrapper("%5"), ""); EXPECT_EQ(spk_wrapper("%-5"), ""); EXPECT_EQ(spk_wrapper("%h"), ""); EXPECT_EQ(spk_wrapper("%hh"), ""); } TEST(printk, incomplete_seq) { EXPECT_EQ(spk_wrapper("%z, hello"), "%, hello"); EXPECT_EQ(spk_wrapper("%l, hello"), "%, hello"); EXPECT_EQ(spk_wrapper("%ll, hello"), "%, hello"); EXPECT_EQ(spk_wrapper("%0, hello"), "%0, hello"); EXPECT_EQ(spk_wrapper("%5, hello"), "%5, hello"); EXPECT_EQ(spk_wrapper("%-5, hello"), "%-5, hello"); EXPECT_EQ(spk_wrapper("%-0, hello"), "%, hello"); /* should be: %-, hello */ EXPECT_EQ(spk_wrapper("%h, hello"), "%, hello"); EXPECT_EQ(spk_wrapper("%hh, hello"), "%, hello"); EXPECT_EQ(spk_wrapper("%#, hello"), "%#, hello"); /* note: %# is kept */ } TEST(printk, invalid_seq) { EXPECT_EQ(spk_wrapper("%w", 123), "%w"); EXPECT_EQ(spk_wrapper("%lll", 123ll), "%l"); EXPECT_EQ(spk_wrapper("%#"), "%#"); EXPECT_EQ(spk_wrapper("%##"), "%#"); EXPECT_EQ(spk_wrapper("%###"), "%#"); EXPECT_EQ(spk_wrapper("%l#d"), "%#d"); EXPECT_EQ(spk_wrapper("%lh"), "%h"); EXPECT_EQ(spk_wrapper("%hl"), "%l"); EXPECT_EQ(spk_wrapper("%hld"), "%ld"); EXPECT_EQ(spk_wrapper("%lhd"), "%hd"); } TEST(printk, pointers) { if (NBITS == 32) { EXPECT_EQ(spk_wrapper("%p", TO_PTR(0xc0aabbc0)), "0xc0aabbc0"); EXPECT_EQ( spk_wrapper("%20p", TO_PTR(0xc0aabbc0)), " 0xc0aabbc0" ); EXPECT_EQ( spk_wrapper("%-20p", TO_PTR(0xc0aabbc0)), "0xc0aabbc0 " ); } else { EXPECT_EQ(spk_wrapper("%p", TO_PTR(0xc0aabbc0)), "0x00000000c0aabbc0"); EXPECT_EQ( spk_wrapper("%20p", TO_PTR(0xc0aabbc0)), " 0x00000000c0aabbc0" ); EXPECT_EQ( spk_wrapper("%-20p", TO_PTR(0xc0aabbc0)), "0x00000000c0aabbc0 " ); } } TEST(printk, size_t) { EXPECT_EQ(spk_wrapper("%zd", (size_t)1234), "1234"); EXPECT_EQ(spk_wrapper("%zu", (size_t)123), "123"); EXPECT_EQ(spk_wrapper("%zx", (size_t)0xaab3), "aab3"); #if NBITS == 64 EXPECT_EQ(spk_wrapper("%zu",(size_t)9223372036854775ll),"9223372036854775"); #endif } TEST(printk, ptrdiff_t) { EXPECT_EQ(spk_wrapper("%td", (size_t)1234), "1234"); EXPECT_EQ(spk_wrapper("%tu", (size_t)123), "123"); EXPECT_EQ(spk_wrapper("%tx", (size_t)0xaab3), "aab3"); #if NBITS == 64 EXPECT_EQ(spk_wrapper("%tu",(size_t)9223372036854775ll),"9223372036854775"); #endif } <file_sep>#pragma once #define REND_BUF_SZ 256 extern char *rend_bufs[6]; extern int used_rend_bufs; void dp_handle_syscall_event(struct trace_event *e); <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # If TEST_GCOV is empty/unset but TRAVIS/CIRCLECI is set, exit # In other words, the TEST_GCOV controls this script only if it is running # under TRAVIS or CIRCLECI, which makes sense. if [[ "$TRAVIS" != "" || "$CIRCLECI" != "" ]]; then if [[ "$TEST_GCOV" == "" ]]; then echo "Exit 0 without doing anything" exit 0 fi fi set -e # exit if any command fails SRC="@CMAKE_SOURCE_DIR@" source $SRC/scripts/bash_includes/script_utils TC="@TCROOT@" BUILD="@CMAKE_BINARY_DIR@" HTML_DIR="@COVERAGE_HTML_DIR@" GCOV="@TOOL_GCOV@" LCOV_DIR="$TC/noarch/lcov-@LCOV_VER@" LCOV="$LCOV_DIR/bin/lcov" GENHTML="$LCOV_DIR/bin/genhtml" function show_help { echo "Usage:" echo " <no options> collect coverage info from the *.gcda files " echo " DISCARDING any previous coverage.info data, " echo " producing a converage.info file" echo echo " --clean clean any coverage files previously generated " echo " and exit" echo echo " --acc collect coverage info WITHOUT DISCARDING the" echo " previous converage.info data, producing a new" echo " converage.info file" echo echo " --codecov only upload the coverage data to CodeCov " echo " assuming that 'coverage.info' exists" echo echo " --gen only generate html coverage output assuming that" echo " the file 'converage.info' exists" echo echo " --info show configuration info" echo " --help show this help message" } function show_config_info { echo "GCOV: $GCOV" echo "LCOV: $LCOV" echo "GENHTML: $GENHTML" echo "BUILD_DIR: $BUILD" echo "HTML_DIR: $HTML_DIR" } function gen_html_coverage { if [ ! -f coverage.info ]; then echo "ERROR: the file coverage.info does NOT exist." exit 1 fi # (Eventually) remove and create the output coverage directory rm -rf "$HTML_DIR"; mkdir -p "$HTML_DIR" # Generate the HTML coverage output $GENHTML --output-directory "$HTML_DIR" coverage.info } function remove_gcda_files { find . -type f -name '*.gcda' -print | xargs /bin/rm -f } function remote_all_lcov_files { rm -f lcov.info coverage.info } echo "Entering in the build directory: '$BUILD'" cd "$BUILD" if [[ "$1" == "-h" || "$1" == "--help" ]]; then show_help exit 0 fi if [[ "$1" == "--info" ]]; then show_config_info exit 0 fi if [[ "$1" == "--clean" ]]; then remove_gcda_files remote_all_lcov_files exit 0 fi echo "NOTE: Use '$GCOV' as gcov tool" if [[ "$1" == "--gen" ]]; then gen_html_coverage exit 0 fi if [[ "$1" == "--codecov" ]]; then if [ ! -f coverage.info ]; then echo "ERROR: the file coverage.info does NOT exist." exit 1 fi if [[ "$CODECOV_TOKEN" == "" ]]; then # # CodeCov does not need CODECOV_TOKEN to be defined for public projects # on some CI providers: TravisCI, CircleCI, AppVeyor, Azure Pipelines, # or GitHub Actions. # # See: https://docs.codecov.io/docs/about-the-codecov-bash-uploader # echo "WARNING: No CODECOV_TOKEN defined. Upload to CodeCov might fail" fi # Remove other files to be sure CodeCov uses only the coverage.info file rm -f lcov.info remove_gcda_files # Upload report to CodeCov if ! [ -d "$BUILD/tmp" ]; then mkdir -p "$BUILD/tmp" fi pushd "$BUILD/tmp" if ! [ -f codecov ]; then curl -Os https://uploader.codecov.io/latest/linux/codecov if ! [ -f codecov ]; then echo "ERROR: codecov did not collect coverage reports" echo "Trying again in 1 minute..." sleep 60 curl -Os https://uploader.codecov.io/latest/linux/codecov if ! [ -f codecov ]; then echo "FATAL ERROR: Codecov cannot collect the coverage reports" exit 1 fi fi fi popd chmod +x "$BUILD/tmp/codecov" "$BUILD/tmp/codecov" -X gcov exit 0 fi gcda_count=$(find . -name '*.gcda' | wc -l) if [[ $gcda_count == 0 ]]; then echo "ERROR: no gcda files found in $BUILD" exit 1 fi if [[ "$1" != "--acc" ]]; then remote_all_lcov_files fi ex_list="" # we're not interested in the 3rd-party code in the toolchain ex_list="$ex_list '@TCROOT@/*'" # of course we're not interested in system headers ex_list="$ex_list '/usr/include/*'" # the header is not used anywhere. It's useful only for manual instrumentation ex_list="$ex_list '$SRC/include/tilck/common/debug/termios_debug.c.h'" # syscalls.h contains wrapper funcs for all the Linux syscalls ex_list="$ex_list '$SRC/include/tilck/kernel/syscalls.h'" # the common panic() is not used in Tilck ex_list="$ex_list '$SRC/common/panic.c'" # we don't have tests triggering an actual kernel panic ex_list="$ex_list '$SRC/common/asserts.c'" run_command "$LCOV -d . --capture --gcov-tool '$GCOV' -o lcov.info" run_command "$LCOV --remove lcov.info $ex_list -o lcov.info" if [[ "$1" == "--acc" && -f coverage.info ]]; then $LCOV -a coverage.info -a lcov.info -o merged.info mv merged.info coverage.info else mv lcov.info coverage.info fi # Remove everything except for our `coverage.info` rm -f lcov.info remove_gcda_files <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct build_info { char commit[160]; /* hash + commit date + tags + [other stuff] */ char ver[32]; /* string version, like "0.1.0" */ char arch[32]; /* arch name, like "i686" */ char extra[32]; /* unused, at the moment */ char modules_list[256]; /* space-separated list of built-in modules */ }; STATIC_ASSERT(sizeof(struct build_info) == 512); struct commit_hash_and_date { char hash[16]; char date[26]; char tags[53]; bool dirty; }; extern const struct build_info tilck_build_info; void extract_commit_hash_and_date(const struct build_info *bi, struct commit_hash_and_date *c); <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # GLOBAL VARIABLES # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/../.. && pwd)" # Include files source $MAIN_DIR/scripts/bash_includes/script_utils ############################################# # FUNCTIONS function show_help { echo "" echo "This script will run ALL the tests (system tests + unit tests) for ALL" echo "the so-called 'other builds' in $MAIN_DIR/other_builds." echo "In order to generate those non-standard builds, you'll likely need to" echo "run the 'gen_other_builds' script. Note: you can also put your own" echo "special builds in that directory. This script will just iterate over " echo "all the subdirectories of 'other_builds' and it will treat each one " echo "of them as a build of Tilck." echo "" echo -ne "${RED}WARNING${RATTRS}: if you're new to Tilck, that's probably " echo -ne "${RED}not${RATTRS} the script you're looking\nfor. " echo -ne "${BROWN}Check out${RATTRS} the main README.md file for info about " echo -ne "how to build Tilck and\nrun its tests.\n" echo "" } function ask_confirm { show_help echo -n "Proceed [y/N] ? " read answer if [[ "$answer" != "y" ]]; then exit 0 fi } ############################################# # MAIN CODE # Exit on any error set -e if [[ "$1" == "-h" || "$1" == "--help" ]]; then show_help exit 0 fi if [[ "$1" != "-y" ]]; then ask_confirm fi cd $MAIN_DIR/other_builds for x in `ls`; do pushd $x echo "********** [begin] Test directory: $x **********" ./gtests ./st/run_all_tests -c echo "********** [end] Test directory: $x **********" popd done <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <gtest/gtest.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/list.h> using namespace std; struct my_struct { const char *data; struct list_node node; my_struct(const char *d) : data(d) { list_node_init(&node); } }; extern "C" { my_struct *debug_list_test_get_struct(struct list_node *n) { my_struct *s = list_to_obj(n, my_struct, node); return s; } const char *debug_list_test_dump_data(struct list_node *n) { return debug_list_test_get_struct(n)->data; } void debug_list_test_dump(struct list *l) { my_struct *pos, *temp; list_for_each(pos, temp, l, node) { printf("%s\n", pos->data); } } } using tvec = vector<const char *>; void check_list_elems(struct list& list_var, const tvec& exp) { size_t i = 0; my_struct *pos, *temp; list_for_each(pos, temp, &list_var, node) { if (i >= exp.size()) { FAIL() << "List is longer than the expected vector"; } if (pos->data != exp[i]) { FAIL() << "List elem[" << i << "] = '" << pos->data << "' != " << exp[i] << " (expected)"; } i++; } } TEST(list_adt, initialization) { struct list list_var = STATIC_LIST_INIT(list_var); ASSERT_TRUE(list_is_empty(&list_var)); ASSERT_TRUE(list_var.first == (struct list_node*)&list_var); ASSERT_TRUE(list_var.last == (struct list_node*)&list_var); bzero(&list_var, sizeof(list_var)); list_init(&list_var); ASSERT_TRUE(list_var.first == (struct list_node*)&list_var); ASSERT_TRUE(list_var.last == (struct list_node*)&list_var); check_list_elems(list_var, tvec{}); } TEST(list_adt, add) { my_struct e1("head"); my_struct e2("tail"); ASSERT_TRUE(list_to_obj(&e1.node, my_struct, node) == &e1); ASSERT_TRUE(list_to_obj(&e2.node, my_struct, node) == &e2); struct list list_var; list_init(&list_var); ASSERT_TRUE(list_is_empty(&list_var)); list_add_after((struct list_node *)&list_var, &e1.node); list_add_after(&e1.node, &e2.node); ASSERT_TRUE(e1.node.next == &e2.node); ASSERT_TRUE(e1.node.next->next == (struct list_node *)&list_var); ASSERT_TRUE(e1.node.prev == (struct list_node *)&list_var); ASSERT_TRUE(e2.node.prev == &e1.node); check_list_elems(list_var, tvec{"head", "tail"}); my_struct e12("mid"); list_add_after(&e1.node, &e12.node); ASSERT_TRUE(e1.node.next == &e12.node); ASSERT_TRUE(e1.node.next->next == &e2.node); ASSERT_TRUE(e1.node.prev == (struct list_node *)&list_var); ASSERT_TRUE(e2.node.prev == &e12.node); ASSERT_TRUE(e2.node.next == (struct list_node *)&list_var); ASSERT_TRUE(list_var.last == &e2.node); ASSERT_TRUE(list_to_obj(&e1.node, my_struct, node) == &e1); ASSERT_TRUE(list_to_obj(&e2.node, my_struct, node) == &e2); ASSERT_TRUE(list_to_obj(&e12.node, my_struct, node) == &e12); check_list_elems(list_var, tvec{"head", "mid", "tail"}); } TEST(list_adt, add_tail) { my_struct e1("head"); my_struct e2("tail"); ASSERT_TRUE(list_to_obj(&e1.node, my_struct, node) == &e1); ASSERT_TRUE(list_to_obj(&e2.node, my_struct, node) == &e2); struct list list_var; list_init(&list_var); ASSERT_TRUE(list_is_empty(&list_var)); list_add_tail(&list_var, &e1.node); list_add_tail(&list_var, &e2.node); check_list_elems(list_var, tvec{"head", "tail"}); my_struct ne("new tail"); list_add_tail(&list_var, &ne.node); EXPECT_TRUE(list_var.last == &ne.node); EXPECT_TRUE(ne.node.next == (struct list_node *)&list_var); EXPECT_TRUE(e2.node.next == &ne.node); EXPECT_TRUE(ne.node.prev == &e2.node); check_list_elems(list_var, tvec{"head", "tail", "new tail"}); } TEST(list_adt, remove_elem) { struct list list_var; list_init(&list_var); my_struct e1("e1"), e2("e2"), e3("e3"); list_add_tail(&list_var, &e1.node); list_add_tail(&list_var, &e2.node); list_add_tail(&list_var, &e3.node); check_list_elems(list_var, tvec{"e1", "e2", "e3"}); ASSERT_TRUE(list_is_node_in_list(&e2.node)); list_remove(&e2.node); check_list_elems(list_var, tvec{"e1", "e3"}); ASSERT_FALSE(list_is_node_in_list(&e2.node)); // now, remove e2 again and check that nothing really happened list_remove(&e2.node); check_list_elems(list_var, tvec{"e1", "e3"}); ASSERT_FALSE(list_is_node_in_list(&e2.node)); struct list_node a_node; list_node_init(&a_node); ASSERT_FALSE(list_is_node_in_list(&a_node)); } TEST(list_adt, add_head) { struct list list_var; list_init(&list_var); my_struct e1("e1"), e2("e2"), e3("e3"); list_add_head(&list_var, &e1.node); list_add_head(&list_var, &e2.node); list_add_head(&list_var, &e3.node); check_list_elems(list_var, tvec{"e3", "e2", "e1"}); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/atomics.h> #include <tilck/common/utils.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> static ATOMIC(u32) g_counter; static u64 g_cycles_begin; struct se_wth_ctx { struct worker_thread *wth; struct kmutex m; struct kcond c; }; static void test_wth_func(void *arg) { g_counter++; } static void test_wth_func2(void *arg) { g_counter++; kernel_sleep_ms(50); } static void end_test(void *arg) { struct se_wth_ctx *ctx = arg; const u32 max_jobs = wth_get_queue_size(ctx->wth); const u32 tot_iters = max_jobs * 10; u64 elapsed = RDTSC() - g_cycles_begin; VERIFY(g_counter == tot_iters); printk("[se_wth] Avg cycles per job " "(enqueue + execute): %" PRIu64 "\n", elapsed/g_counter); printk("[se_wth] end_test() waiting to grab the lock\n"); kmutex_lock(&ctx->m); { printk("[se_wth] end_test() holding the lock and signalling cond\n"); kcond_signal_one(&ctx->c); } kmutex_unlock(&ctx->m); printk("[se_wth] end_test() func completed\n"); } void selftest_wth(void) { const u32 attempts_check = 500 * 1000; struct se_wth_ctx ctx; u32 yields_count = 0; u64 tot_attempts = 0; u32 last_counter_val; u32 counter_now; u32 attempts; u32 max_jobs; u32 tot_iters; bool added; ctx.wth = wth_find_worker(WTH_PRIO_LOWEST); VERIFY(ctx.wth != NULL); max_jobs = wth_get_queue_size(ctx.wth); tot_iters = max_jobs * 10; kcond_init(&ctx.c); kmutex_init(&ctx.m, 0); g_counter = 0; ASSERT(is_preemption_enabled()); printk("[se_wth] BEGIN\n"); g_cycles_begin = RDTSC(); for (u32 i = 0; i < tot_iters; i++) { attempts = 1; last_counter_val = g_counter; bool did_yield = false; do { added = wth_enqueue_on(ctx.wth, &test_wth_func, NULL); attempts++; if (!(attempts % attempts_check)) { counter_now = g_counter; if (counter_now == last_counter_val) { if (did_yield) panic("It seems that jobs don't get executed"); did_yield = true; yields_count++; kernel_yield(); } } } while (!added); tot_attempts += attempts; } last_counter_val = g_counter; printk("[se_wth] Main test done\n"); printk("[se_wth] AVG attempts: %u\n", (u32)(tot_attempts/tot_iters)); printk("[se_wth] Yields: %u\n", yields_count); printk("[se_wth] counter now: %u\n", last_counter_val); printk("[se_wth] now wait for completion...\n"); kernel_sleep(1); attempts = 0; do { counter_now = g_counter; if (counter_now == last_counter_val) { /* * Note: we must keep in mind that we cannot rely that 100% of the time * after kernel_sleep() the worker thread will be able to run, without * being preempted and increment our `g_counter`. In theory we might * still get there first. */ if (attempts++ >= 3) panic("It seems that jobs don't get executed"); kernel_sleep(TIME_SLICE_TICKS); continue; } attempts = 0; last_counter_val = counter_now; kernel_sleep(1); } while (counter_now < tot_iters); printk("[se_wth] DONE, counter: %u\n", counter_now); printk("[se_wth] enqueue end_test()\n"); kmutex_lock(&ctx.m); { printk("[se_wth] Under lock, before enqueue\n"); do { added = wth_enqueue_on(ctx.wth, &end_test, &ctx); } while (!added); printk("[se_wth] Under lock, AFTER enqueue\n"); printk("[se_wth] Now, wait on cond\n"); kcond_wait(&ctx.c, &ctx.m, KCOND_WAIT_FOREVER); } kmutex_unlock(&ctx.m); kcond_destory(&ctx.c); kmutex_destroy(&ctx.m); printk("[se_wth] END\n"); se_regular_end(); } REGISTER_SELF_TEST(wth, se_short, &selftest_wth) void selftest_wth2(void) { struct worker_thread *wth; bool added; int cnt = 0; g_counter = 0; wth = wth_find_worker(WTH_PRIO_LOWEST); ASSERT(wth != NULL); printk("[se_wth] enqueue 10 jobs\n"); while (cnt < 10) { added = wth_enqueue_on(wth, &test_wth_func2, NULL); if (added) cnt++; } printk("[se_wth] done\n"); printk("[se_wth] wait for completion\n"); wth_wait_for_completion(wth); if (g_counter != 10) panic("[se_wth] counter (%d) != 10", g_counter); printk("[se_wth] everything is OK\n"); } REGISTER_SELF_TEST(wth2, se_short, &selftest_wth2) void selftest_wth_perf(void) { struct worker_thread *wth = wth_find_worker(WTH_PRIO_LOWEST); bool added; u32 n = 0; u64 start, elapsed; start = RDTSC(); while (true) { added = wth_enqueue_on(wth, &test_wth_func, NULL); if (!added) break; n++; } elapsed = RDTSC() - start; ASSERT(n > 0); // SA: avoid division by zero warning printk("Avg. job enqueue cycles: %" PRIu64 " [%i jobs]\n", elapsed/n, n); se_regular_end(); } REGISTER_SELF_TEST(wth_perf, se_short, &selftest_wth_perf) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/term.h> #include <tilck/kernel/safe_ringbuf.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> struct term_action; struct term_rb_data { struct kmutex lock; struct safe_ringbuf rb; }; typedef void (*exec_action_func)(term *, struct term_action *); void init_term_rb_data(struct term_rb_data *d, u16 max_elems, u16 elem_size, void *buf); void dispose_term_rb_data(struct term_rb_data *d); void term_handle_full_ringbuf(term *t, struct term_rb_data *rb_data, struct term_action *a, bool *was_empty, exec_action_func exec); /* * C "template" function used to allow code sharing between video term and * serial term. The idea is simple: do NOT treat this as a function, but as * a macro to put in your term_execute_or_enqueue_action() function. This way, * all this code will be inlined in just one place per term implementation. * See video_term's term_execute_or_enqueue_action() implementation. */ static ALWAYS_INLINE void term_exec_everything(term *t, struct term_rb_data *d, exec_action_func exec) { long a[2]; ASSERT(d->rb.elem_size <= sizeof(a)); while (safe_ringbuf_read_elem(&d->rb, a)) exec(t, (struct term_action *) a); } static ALWAYS_INLINE void term_execute_or_enqueue_action_template(term *t, struct term_rb_data *rb_data, struct term_action *a, exec_action_func exec) { bool was_empty; if (UNLIKELY(!safe_ringbuf_write_elem(&rb_data->rb, a, &was_empty))) { term_handle_full_ringbuf(t, rb_data, a, &was_empty, exec); /* NOTE: do not return */ } if (!was_empty) { /* * OK, no matter if we went through term_handle_full_ringbuf() or not, * at the moment we enqueued our action the ringbuf was not empty, * therefore we won't try to execute the actions. That will happen in the * only task that found the ringbuf empty. */ return; } if (UNLIKELY(in_panic()) || !is_preemption_enabled()) { /* We don't need to grab the lock, as the preemption is disabled! */ return term_exec_everything(t, rb_data, exec); } /* Don't disable the preemption, just grab term's lock */ kmutex_lock(&rb_data->lock); { term_exec_everything(t, rb_data, exec); } kmutex_unlock(&rb_data->lock); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/kb.h> struct tty; static ALWAYS_INLINE struct tty *get_curr_tty(void) { extern struct tty *__curr_tty; return __curr_tty; } void tty_send_keyevent(struct tty *t, struct key_event ke, bool block); void tty_setup_for_panic(struct tty *t); int tty_get_num(struct tty *t); void tty_restore_kd_text_mode(struct tty *t); struct tty *get_serial_tty(int n); void tty_reset_termios(struct tty *t); struct tty *get_curr_process_tty(void); int get_curr_proc_tty_term_type(void); ssize_t tty_curr_proc_write(const char *buf, size_t size); void tty_write_on_all_ttys(const char *buf, size_t size); static inline int get_curr_tty_num(void) { return tty_get_num(get_curr_tty()); } /* Used only by the debug panel */ int set_curr_tty(struct tty *t); struct tty *create_tty_nodev(void); void tty_set_raw_mode(struct tty *t); void tty_set_medium_raw_mode(struct tty *t, bool enabled); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define __TILCK_HAL__ #include <tilck/common/basic_defs.h> #include <tilck/common/datetime.h> #include <tilck/kernel/hal_types.h> #if defined(__i386__) || defined(__x86_64__) #define arch_x86_family #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <tilck/kernel/arch/generic_x86/fpu_memcpy.h> #include <tilck/kernel/arch/generic_x86/arch_ints.h> #if defined(__x86_64__) #include <tilck/common/arch/x86_64/utils.h> #include <tilck/kernel/arch/x86_64/arch_utils.h> #else #include <tilck/common/arch/i386/utils.h> #include <tilck/kernel/arch/i386/asm_defs.h> #include <tilck/kernel/arch/i386/arch_utils.h> #include <tilck/kernel/arch/i386/tss.h> #endif #elif defined(__aarch64__) && defined(KERNEL_TEST) /* * Fake stub funcs and defines, just to allow the build of the kernel for * the unit tests */ #define ALL_FAULTS_MASK (0xFFFFFFFF) #define PAGE_FAULT_MASK (1 << 14) #define SYSCALL_SOFT_INTERRUPT 0x80 #define COM1 0 #define COM2 1 #define COM3 2 #define COM4 3 #define X86_PC_TIMER_IRQ 0 static ALWAYS_INLINE bool are_interrupts_enabled(void) { return true; } static ALWAYS_INLINE void disable_interrupts(ulong *var) { /* STUB function: do nothing */ } static ALWAYS_INLINE void enable_interrupts(ulong *var) { /* STUB function: do nothing */ } static ALWAYS_INLINE void disable_interrupts_forced(void) { /* STUB function: do nothing */ } static ALWAYS_INLINE void enable_interrupts_forced(void) { /* STUB function: do nothing */ } static ALWAYS_INLINE void __set_curr_pdir(ulong paddr) { /* STUB function: do nothing */ } static ALWAYS_INLINE ulong __get_curr_pdir() { NOT_IMPLEMENTED(); } static ALWAYS_INLINE void set_return_register(regs_t *r, ulong value) { /* STUB function: do nothing */ } static ALWAYS_INLINE int int_to_irq(int int_num) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE bool is_irq(int int_num) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE bool is_timer_irq(int int_num) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE bool is_fault(int int_num) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE int regs_intnum(regs_t *r) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE void halt(void) { /* STUB function: do nothing */ } static ALWAYS_INLINE void init_fpu_memcpy(void) { /* STUB function: do nothing */ } static ALWAYS_INLINE bool in_hypervisor(void) { return false; } static ALWAYS_INLINE ulong get_rem_stack(void) { return KERNEL_STACK_SIZE; } static ALWAYS_INLINE ulong get_stack_ptr(void) { return 0; } static ALWAYS_INLINE u64 RDTSC(void) { return 0; } #else #error Unsupported architecture. #endif STATIC_ASSERT(ARCH_TASK_MEMBERS_SIZE == sizeof(arch_task_members_t)); STATIC_ASSERT(ARCH_TASK_MEMBERS_ALIGN == alignof(arch_task_members_t)); STATIC_ASSERT(ARCH_PROC_MEMBERS_SIZE == sizeof(arch_proc_members_t)); STATIC_ASSERT(ARCH_PROC_MEMBERS_ALIGN == alignof(arch_proc_members_t)); NORETURN void reboot(void); NORETURN void poweroff(void); void init_segmentation(void); void init_cpu_exception_handling(void); void init_syscall_interfaces(void); void set_kernel_stack(ulong stack); void enable_cpu_features(void); void fpu_context_begin(void); void fpu_context_end(void); void save_current_fpu_regs(bool in_kernel); void restore_fpu_regs(void *task, bool in_kernel); void restore_current_fpu_regs(bool in_kernel); int get_irq_num(regs_t *context); int get_int_num(regs_t *context); void on_first_pdir_update(void); void hw_read_clock(struct datetime *out); u32 hw_timer_setup(u32 hz); bool allocate_fpu_regs(arch_task_members_t *arch_fields); void copy_main_tss_on_regs(regs_t *ctx); void arch_add_initial_mem_regions(); bool arch_add_final_mem_regions(); #define get_task_arch_fields(ti) ((arch_task_members_t*)(void*)((ti)->ti_arch)) #define get_proc_arch_fields(pi) ((arch_proc_members_t*)(void*)((pi)->pi_arch)) <file_sep>/****************************************************************************** * * Module Name: evgpe - General Purpose Event handling and dispatch * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acevents.h" #include "acnamesp.h" #define _COMPONENT ACPI_EVENTS ACPI_MODULE_NAME ("evgpe") #if (!ACPI_REDUCED_HARDWARE) /* Entire module */ /* Local prototypes */ static void ACPI_SYSTEM_XFACE AcpiEvAsynchExecuteGpeMethod ( void *Context); static void ACPI_SYSTEM_XFACE AcpiEvAsynchEnableGpe ( void *Context); /******************************************************************************* * * FUNCTION: AcpiEvUpdateGpeEnableMask * * PARAMETERS: GpeEventInfo - GPE to update * * RETURN: Status * * DESCRIPTION: Updates GPE register enable mask based upon whether there are * runtime references to this GPE * ******************************************************************************/ ACPI_STATUS AcpiEvUpdateGpeEnableMask ( ACPI_GPE_EVENT_INFO *GpeEventInfo) { ACPI_GPE_REGISTER_INFO *GpeRegisterInfo; UINT32 RegisterBit; ACPI_FUNCTION_TRACE (EvUpdateGpeEnableMask); GpeRegisterInfo = GpeEventInfo->RegisterInfo; if (!GpeRegisterInfo) { return_ACPI_STATUS (AE_NOT_EXIST); } RegisterBit = AcpiHwGetGpeRegisterBit (GpeEventInfo); /* Clear the run bit up front */ ACPI_CLEAR_BIT (GpeRegisterInfo->EnableForRun, RegisterBit); /* Set the mask bit only if there are references to this GPE */ if (GpeEventInfo->RuntimeCount) { ACPI_SET_BIT (GpeRegisterInfo->EnableForRun, (UINT8) RegisterBit); } GpeRegisterInfo->EnableMask = GpeRegisterInfo->EnableForRun; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiEvEnableGpe * * PARAMETERS: GpeEventInfo - GPE to enable * * RETURN: Status * * DESCRIPTION: Enable a GPE. * ******************************************************************************/ ACPI_STATUS AcpiEvEnableGpe ( ACPI_GPE_EVENT_INFO *GpeEventInfo) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (EvEnableGpe); /* Enable the requested GPE */ Status = AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_ENABLE); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiEvMaskGpe * * PARAMETERS: GpeEventInfo - GPE to be blocked/unblocked * IsMasked - Whether the GPE is masked or not * * RETURN: Status * * DESCRIPTION: Unconditionally mask/unmask a GPE during runtime. * ******************************************************************************/ ACPI_STATUS AcpiEvMaskGpe ( ACPI_GPE_EVENT_INFO *GpeEventInfo, BOOLEAN IsMasked) { ACPI_GPE_REGISTER_INFO *GpeRegisterInfo; UINT32 RegisterBit; ACPI_FUNCTION_TRACE (EvMaskGpe); GpeRegisterInfo = GpeEventInfo->RegisterInfo; if (!GpeRegisterInfo) { return_ACPI_STATUS (AE_NOT_EXIST); } RegisterBit = AcpiHwGetGpeRegisterBit (GpeEventInfo); /* Perform the action */ if (IsMasked) { if (RegisterBit & GpeRegisterInfo->MaskForRun) { return_ACPI_STATUS (AE_BAD_PARAMETER); } (void) AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_DISABLE); ACPI_SET_BIT (GpeRegisterInfo->MaskForRun, (UINT8) RegisterBit); } else { if (!(RegisterBit & GpeRegisterInfo->MaskForRun)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } ACPI_CLEAR_BIT (GpeRegisterInfo->MaskForRun, (UINT8) RegisterBit); if (GpeEventInfo->RuntimeCount && !GpeEventInfo->DisableForDispatch) { (void) AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_ENABLE); } } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiEvAddGpeReference * * PARAMETERS: GpeEventInfo - Add a reference to this GPE * ClearOnEnable - Clear GPE status before enabling it * * RETURN: Status * * DESCRIPTION: Add a reference to a GPE. On the first reference, the GPE is * hardware-enabled. * ******************************************************************************/ ACPI_STATUS AcpiEvAddGpeReference ( ACPI_GPE_EVENT_INFO *GpeEventInfo, BOOLEAN ClearOnEnable) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (EvAddGpeReference); if (GpeEventInfo->RuntimeCount == ACPI_UINT8_MAX) { return_ACPI_STATUS (AE_LIMIT); } GpeEventInfo->RuntimeCount++; if (GpeEventInfo->RuntimeCount == 1) { /* Enable on first reference */ if (ClearOnEnable) { (void) AcpiHwClearGpe (GpeEventInfo); } Status = AcpiEvUpdateGpeEnableMask (GpeEventInfo); if (ACPI_SUCCESS (Status)) { Status = AcpiEvEnableGpe (GpeEventInfo); } if (ACPI_FAILURE (Status)) { GpeEventInfo->RuntimeCount--; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiEvRemoveGpeReference * * PARAMETERS: GpeEventInfo - Remove a reference to this GPE * * RETURN: Status * * DESCRIPTION: Remove a reference to a GPE. When the last reference is * removed, the GPE is hardware-disabled. * ******************************************************************************/ ACPI_STATUS AcpiEvRemoveGpeReference ( ACPI_GPE_EVENT_INFO *GpeEventInfo) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (EvRemoveGpeReference); if (!GpeEventInfo->RuntimeCount) { return_ACPI_STATUS (AE_LIMIT); } GpeEventInfo->RuntimeCount--; if (!GpeEventInfo->RuntimeCount) { /* Disable on last reference */ Status = AcpiEvUpdateGpeEnableMask (GpeEventInfo); if (ACPI_SUCCESS (Status)) { Status = AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_DISABLE); } if (ACPI_FAILURE (Status)) { GpeEventInfo->RuntimeCount++; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiEvLowGetGpeInfo * * PARAMETERS: GpeNumber - Raw GPE number * GpeBlock - A GPE info block * * RETURN: A GPE EventInfo struct. NULL if not a valid GPE (The GpeNumber * is not within the specified GPE block) * * DESCRIPTION: Returns the EventInfo struct associated with this GPE. This is * the low-level implementation of EvGetGpeEventInfo. * ******************************************************************************/ ACPI_GPE_EVENT_INFO * AcpiEvLowGetGpeInfo ( UINT32 GpeNumber, ACPI_GPE_BLOCK_INFO *GpeBlock) { UINT32 GpeIndex; /* * Validate that the GpeNumber is within the specified GpeBlock. * (Two steps) */ if (!GpeBlock || (GpeNumber < GpeBlock->BlockBaseNumber)) { return (NULL); } GpeIndex = GpeNumber - GpeBlock->BlockBaseNumber; if (GpeIndex >= GpeBlock->GpeCount) { return (NULL); } return (&GpeBlock->EventInfo[GpeIndex]); } /******************************************************************************* * * FUNCTION: AcpiEvGetGpeEventInfo * * PARAMETERS: GpeDevice - Device node. NULL for GPE0/GPE1 * GpeNumber - Raw GPE number * * RETURN: A GPE EventInfo struct. NULL if not a valid GPE * * DESCRIPTION: Returns the EventInfo struct associated with this GPE. * Validates the GpeBlock and the GpeNumber * * Should be called only when the GPE lists are semaphore locked * and not subject to change. * ******************************************************************************/ ACPI_GPE_EVENT_INFO * AcpiEvGetGpeEventInfo ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_GPE_EVENT_INFO *GpeInfo; UINT32 i; ACPI_FUNCTION_ENTRY (); /* A NULL GpeDevice means use the FADT-defined GPE block(s) */ if (!GpeDevice) { /* Examine GPE Block 0 and 1 (These blocks are permanent) */ for (i = 0; i < ACPI_MAX_GPE_BLOCKS; i++) { GpeInfo = AcpiEvLowGetGpeInfo (GpeNumber, AcpiGbl_GpeFadtBlocks[i]); if (GpeInfo) { return (GpeInfo); } } /* The GpeNumber was not in the range of either FADT GPE block */ return (NULL); } /* A Non-NULL GpeDevice means this is a GPE Block Device */ ObjDesc = AcpiNsGetAttachedObject ((ACPI_NAMESPACE_NODE *) GpeDevice); if (!ObjDesc || !ObjDesc->Device.GpeBlock) { return (NULL); } return (AcpiEvLowGetGpeInfo (GpeNumber, ObjDesc->Device.GpeBlock)); } /******************************************************************************* * * FUNCTION: AcpiEvGpeDetect * * PARAMETERS: GpeXruptList - Interrupt block for this interrupt. * Can have multiple GPE blocks attached. * * RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED * * DESCRIPTION: Detect if any GP events have occurred. This function is * executed at interrupt level. * ******************************************************************************/ UINT32 AcpiEvGpeDetect ( ACPI_GPE_XRUPT_INFO *GpeXruptList) { ACPI_GPE_BLOCK_INFO *GpeBlock; ACPI_NAMESPACE_NODE *GpeDevice; ACPI_GPE_REGISTER_INFO *GpeRegisterInfo; ACPI_GPE_EVENT_INFO *GpeEventInfo; UINT32 GpeNumber; UINT32 IntStatus = ACPI_INTERRUPT_NOT_HANDLED; ACPI_CPU_FLAGS Flags; UINT32 i; UINT32 j; ACPI_FUNCTION_NAME (EvGpeDetect); /* Check for the case where there are no GPEs */ if (!GpeXruptList) { return (IntStatus); } /* * We need to obtain the GPE lock for both the data structs and registers * Note: Not necessary to obtain the hardware lock, since the GPE * registers are owned by the GpeLock. */ Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); /* Examine all GPE blocks attached to this interrupt level */ GpeBlock = GpeXruptList->GpeBlockListHead; while (GpeBlock) { GpeDevice = GpeBlock->Node; /* * Read all of the 8-bit GPE status and enable registers in this GPE * block, saving all of them. Find all currently active GP events. */ for (i = 0; i < GpeBlock->RegisterCount; i++) { /* Get the next status/enable pair */ GpeRegisterInfo = &GpeBlock->RegisterInfo[i]; /* * Optimization: If there are no GPEs enabled within this * register, we can safely ignore the entire register. */ if (!(GpeRegisterInfo->EnableForRun | GpeRegisterInfo->EnableForWake)) { ACPI_DEBUG_PRINT ((ACPI_DB_INTERRUPTS, "Ignore disabled registers for GPE %02X-%02X: " "RunEnable=%02X, WakeEnable=%02X\n", GpeRegisterInfo->BaseGpeNumber, GpeRegisterInfo->BaseGpeNumber + (ACPI_GPE_REGISTER_WIDTH - 1), GpeRegisterInfo->EnableForRun, GpeRegisterInfo->EnableForWake)); continue; } /* Now look at the individual GPEs in this byte register */ for (j = 0; j < ACPI_GPE_REGISTER_WIDTH; j++) { /* Detect and dispatch one GPE bit */ GpeEventInfo = &GpeBlock->EventInfo[((ACPI_SIZE) i * ACPI_GPE_REGISTER_WIDTH) + j]; GpeNumber = j + GpeRegisterInfo->BaseGpeNumber; AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); IntStatus |= AcpiEvDetectGpe ( GpeDevice, GpeEventInfo, GpeNumber); Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); } } GpeBlock = GpeBlock->Next; } AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); return (IntStatus); } /******************************************************************************* * * FUNCTION: AcpiEvAsynchExecuteGpeMethod * * PARAMETERS: Context (GpeEventInfo) - Info for this GPE * * RETURN: None * * DESCRIPTION: Perform the actual execution of a GPE control method. This * function is called from an invocation of AcpiOsExecute and * therefore does NOT execute at interrupt level - so that * the control method itself is not executed in the context of * an interrupt handler. * ******************************************************************************/ static void ACPI_SYSTEM_XFACE AcpiEvAsynchExecuteGpeMethod ( void *Context) { ACPI_GPE_EVENT_INFO *GpeEventInfo = Context; ACPI_STATUS Status = AE_OK; ACPI_EVALUATE_INFO *Info; ACPI_GPE_NOTIFY_INFO *Notify; ACPI_FUNCTION_TRACE (EvAsynchExecuteGpeMethod); /* Do the correct dispatch - normal method or implicit notify */ switch (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags)) { case ACPI_GPE_DISPATCH_NOTIFY: /* * Implicit notify. * Dispatch a DEVICE_WAKE notify to the appropriate handler. * NOTE: the request is queued for execution after this method * completes. The notify handlers are NOT invoked synchronously * from this thread -- because handlers may in turn run other * control methods. * * June 2012: Expand implicit notify mechanism to support * notifies on multiple device objects. */ Notify = GpeEventInfo->Dispatch.NotifyList; while (ACPI_SUCCESS (Status) && Notify) { Status = AcpiEvQueueNotifyRequest ( Notify->DeviceNode, ACPI_NOTIFY_DEVICE_WAKE); Notify = Notify->Next; } break; case ACPI_GPE_DISPATCH_METHOD: /* Allocate the evaluation information block */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { Status = AE_NO_MEMORY; } else { /* * Invoke the GPE Method (_Lxx, _Exx) i.e., evaluate the * _Lxx/_Exx control method that corresponds to this GPE */ Info->PrefixNode = GpeEventInfo->Dispatch.MethodNode; Info->Flags = ACPI_IGNORE_RETURN_VALUE; Status = AcpiNsEvaluate (Info); ACPI_FREE (Info); } if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "while evaluating GPE method [%4.4s]", AcpiUtGetNodeName (GpeEventInfo->Dispatch.MethodNode))); } break; default: goto ErrorExit; /* Should never happen */ } /* Defer enabling of GPE until all notify handlers are done */ Status = AcpiOsExecute (OSL_NOTIFY_HANDLER, AcpiEvAsynchEnableGpe, GpeEventInfo); if (ACPI_SUCCESS (Status)) { return_VOID; } ErrorExit: AcpiEvAsynchEnableGpe (GpeEventInfo); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiEvAsynchEnableGpe * * PARAMETERS: Context (GpeEventInfo) - Info for this GPE * Callback from AcpiOsExecute * * RETURN: None * * DESCRIPTION: Asynchronous clear/enable for GPE. This allows the GPE to * complete (i.e., finish execution of Notify) * ******************************************************************************/ static void ACPI_SYSTEM_XFACE AcpiEvAsynchEnableGpe ( void *Context) { ACPI_GPE_EVENT_INFO *GpeEventInfo = Context; ACPI_CPU_FLAGS Flags; Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); (void) AcpiEvFinishGpe (GpeEventInfo); AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); return; } /******************************************************************************* * * FUNCTION: AcpiEvFinishGpe * * PARAMETERS: GpeEventInfo - Info for this GPE * * RETURN: Status * * DESCRIPTION: Clear/Enable a GPE. Common code that is used after execution * of a GPE method or a synchronous or asynchronous GPE handler. * ******************************************************************************/ ACPI_STATUS AcpiEvFinishGpe ( ACPI_GPE_EVENT_INFO *GpeEventInfo) { ACPI_STATUS Status; if ((GpeEventInfo->Flags & ACPI_GPE_XRUPT_TYPE_MASK) == ACPI_GPE_LEVEL_TRIGGERED) { /* * GPE is level-triggered, we clear the GPE status bit after * handling the event. */ Status = AcpiHwClearGpe (GpeEventInfo); if (ACPI_FAILURE (Status)) { return (Status); } } /* * Enable this GPE, conditionally. This means that the GPE will * only be physically enabled if the EnableMask bit is set * in the EventInfo. */ (void) AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_CONDITIONAL_ENABLE); GpeEventInfo->DisableForDispatch = FALSE; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiEvDetectGpe * * PARAMETERS: GpeDevice - Device node. NULL for GPE0/GPE1 * GpeEventInfo - Info for this GPE * GpeNumber - Number relative to the parent GPE block * * RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED * * DESCRIPTION: Detect and dispatch a General Purpose Event to either a function * (e.g. EC) or method (e.g. _Lxx/_Exx) handler. * NOTE: GPE is W1C, so it is possible to handle a single GPE from both * task and irq context in parallel as long as the process to * detect and mask the GPE is atomic. * However the atomicity of ACPI_GPE_DISPATCH_RAW_HANDLER is * dependent on the raw handler itself. * ******************************************************************************/ UINT32 AcpiEvDetectGpe ( ACPI_NAMESPACE_NODE *GpeDevice, ACPI_GPE_EVENT_INFO *GpeEventInfo, UINT32 GpeNumber) { UINT32 IntStatus = ACPI_INTERRUPT_NOT_HANDLED; UINT8 EnabledStatusByte; UINT64 StatusReg; UINT64 EnableReg; UINT32 RegisterBit; ACPI_GPE_REGISTER_INFO *GpeRegisterInfo; ACPI_GPE_HANDLER_INFO *GpeHandlerInfo; ACPI_CPU_FLAGS Flags; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (EvGpeDetect); Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); if (!GpeEventInfo) { GpeEventInfo = AcpiEvGetGpeEventInfo (GpeDevice, GpeNumber); if (!GpeEventInfo) { goto ErrorExit; } } /* Get the info block for the entire GPE register */ GpeRegisterInfo = GpeEventInfo->RegisterInfo; /* Get the register bitmask for this GPE */ RegisterBit = AcpiHwGetGpeRegisterBit (GpeEventInfo); /* GPE currently enabled (enable bit == 1)? */ Status = AcpiHwRead (&EnableReg, &GpeRegisterInfo->EnableAddress); if (ACPI_FAILURE (Status)) { goto ErrorExit; } /* GPE currently active (status bit == 1)? */ Status = AcpiHwRead (&StatusReg, &GpeRegisterInfo->StatusAddress); if (ACPI_FAILURE (Status)) { goto ErrorExit; } /* Check if there is anything active at all in this GPE */ ACPI_DEBUG_PRINT ((ACPI_DB_INTERRUPTS, "Read registers for GPE %02X: Status=%02X, Enable=%02X, " "RunEnable=%02X, WakeEnable=%02X\n", GpeNumber, (UINT32) (StatusReg & RegisterBit), (UINT32) (EnableReg & RegisterBit), GpeRegisterInfo->EnableForRun, GpeRegisterInfo->EnableForWake)); EnabledStatusByte = (UINT8) (StatusReg & EnableReg); if (!(EnabledStatusByte & RegisterBit)) { goto ErrorExit; } /* Invoke global event handler if present */ AcpiGpeCount++; if (AcpiGbl_GlobalEventHandler) { AcpiGbl_GlobalEventHandler (ACPI_EVENT_TYPE_GPE, GpeDevice, GpeNumber, AcpiGbl_GlobalEventHandlerContext); } /* Found an active GPE */ if (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_RAW_HANDLER) { /* Dispatch the event to a raw handler */ GpeHandlerInfo = GpeEventInfo->Dispatch.Handler; /* * There is no protection around the namespace node * and the GPE handler to ensure a safe destruction * because: * 1. The namespace node is expected to always * exist after loading a table. * 2. The GPE handler is expected to be flushed by * AcpiOsWaitEventsComplete() before the * destruction. */ AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); IntStatus |= GpeHandlerInfo->Address ( GpeDevice, GpeNumber, GpeHandlerInfo->Context); Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); } else { /* Dispatch the event to a standard handler or method. */ IntStatus |= AcpiEvGpeDispatch (GpeDevice, GpeEventInfo, GpeNumber); } ErrorExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); return (IntStatus); } /******************************************************************************* * * FUNCTION: AcpiEvGpeDispatch * * PARAMETERS: GpeDevice - Device node. NULL for GPE0/GPE1 * GpeEventInfo - Info for this GPE * GpeNumber - Number relative to the parent GPE block * * RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED * * DESCRIPTION: Dispatch a General Purpose Event to either a function (e.g. EC) * or method (e.g. _Lxx/_Exx) handler. * ******************************************************************************/ UINT32 AcpiEvGpeDispatch ( ACPI_NAMESPACE_NODE *GpeDevice, ACPI_GPE_EVENT_INFO *GpeEventInfo, UINT32 GpeNumber) { ACPI_STATUS Status; UINT32 ReturnValue; ACPI_FUNCTION_TRACE (EvGpeDispatch); /* * Always disable the GPE so that it does not keep firing before * any asynchronous activity completes (either from the execution * of a GPE method or an asynchronous GPE handler.) * * If there is no handler or method to run, just disable the * GPE and leave it disabled permanently to prevent further such * pointless events from firing. */ Status = AcpiHwLowSetGpe (GpeEventInfo, ACPI_GPE_DISABLE); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Unable to disable GPE %02X", GpeNumber)); return_UINT32 (ACPI_INTERRUPT_NOT_HANDLED); } /* * If edge-triggered, clear the GPE status bit now. Note that * level-triggered events are cleared after the GPE is serviced. */ if ((GpeEventInfo->Flags & ACPI_GPE_XRUPT_TYPE_MASK) == ACPI_GPE_EDGE_TRIGGERED) { Status = AcpiHwClearGpe (GpeEventInfo); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Unable to clear GPE %02X", GpeNumber)); (void) AcpiHwLowSetGpe ( GpeEventInfo, ACPI_GPE_CONDITIONAL_ENABLE); return_UINT32 (ACPI_INTERRUPT_NOT_HANDLED); } } GpeEventInfo->DisableForDispatch = TRUE; /* * Dispatch the GPE to either an installed handler or the control * method associated with this GPE (_Lxx or _Exx). If a handler * exists, we invoke it and do not attempt to run the method. * If there is neither a handler nor a method, leave the GPE * disabled. */ switch (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags)) { case ACPI_GPE_DISPATCH_HANDLER: /* Invoke the installed handler (at interrupt level) */ ReturnValue = GpeEventInfo->Dispatch.Handler->Address ( GpeDevice, GpeNumber, GpeEventInfo->Dispatch.Handler->Context); /* If requested, clear (if level-triggered) and re-enable the GPE */ if (ReturnValue & ACPI_REENABLE_GPE) { (void) AcpiEvFinishGpe (GpeEventInfo); } break; case ACPI_GPE_DISPATCH_METHOD: case ACPI_GPE_DISPATCH_NOTIFY: /* * Execute the method associated with the GPE * NOTE: Level-triggered GPEs are cleared after the method completes. */ Status = AcpiOsExecute (OSL_GPE_HANDLER, AcpiEvAsynchExecuteGpeMethod, GpeEventInfo); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Unable to queue handler for GPE %02X - event disabled", GpeNumber)); } break; default: /* * No handler or method to run! * 03/2010: This case should no longer be possible. We will not allow * a GPE to be enabled if it has no handler or method. */ ACPI_ERROR ((AE_INFO, "No handler or method for GPE %02X, disabling event", GpeNumber)); break; } return_UINT32 (ACPI_INTERRUPT_HANDLED); } #endif /* !ACPI_REDUCED_HARDWARE */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/syscalls.h> #include "fs_int.h" int sys_mount(const char *user_source, const char *user_target, const char *user_fstype, unsigned long mountflags, const void *user_data) { return -ENOSYS; } int sys_umount(const char *target, int flags) { return -ENOSYS; } <file_sep>/****************************************************************************** * * Module Name: evxface - External interfaces for ACPI events * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acevents.h" #include "acinterp.h" #define _COMPONENT ACPI_EVENTS ACPI_MODULE_NAME ("evxface") #if (!ACPI_REDUCED_HARDWARE) /* Local prototypes */ static ACPI_STATUS AcpiEvInstallGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, BOOLEAN IsRawHandler, ACPI_GPE_HANDLER Address, void *Context); #endif /******************************************************************************* * * FUNCTION: AcpiInstallNotifyHandler * * PARAMETERS: Device - The device for which notifies will be handled * HandlerType - The type of handler: * ACPI_SYSTEM_NOTIFY: System Handler (00-7F) * ACPI_DEVICE_NOTIFY: Device Handler (80-FF) * ACPI_ALL_NOTIFY: Both System and Device * Handler - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Install a handler for notifications on an ACPI Device, * ThermalZone, or Processor object. * * NOTES: The Root namespace object may have only one handler for each * type of notify (System/Device). Device/Thermal/Processor objects * may have one device notify handler, and multiple system notify * handlers. * ******************************************************************************/ ACPI_STATUS AcpiInstallNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler, void *Context) { ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Device); ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; ACPI_STATUS Status; UINT32 i; ACPI_FUNCTION_TRACE (AcpiInstallNotifyHandler); /* Parameter validation */ if ((!Device) || (!Handler) || (!HandlerType) || (HandlerType > ACPI_MAX_NOTIFY_HANDLER_TYPE)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Root Object: * Registering a notify handler on the root object indicates that the * caller wishes to receive notifications for all objects. Note that * only one global handler can be registered per notify type. * Ensure that a handler is not already installed. */ if (Device == ACPI_ROOT_OBJECT) { for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { if (AcpiGbl_GlobalNotify[i].Handler) { Status = AE_ALREADY_EXISTS; goto UnlockAndExit; } AcpiGbl_GlobalNotify[i].Handler = Handler; AcpiGbl_GlobalNotify[i].Context = Context; } } goto UnlockAndExit; /* Global notify handler installed, all done */ } /* * All Other Objects: * Caller will only receive notifications specific to the target * object. Note that only certain object types are allowed to * receive notifications. */ /* Are Notifies allowed on this object? */ if (!AcpiEvIsNotifyObject (Node)) { Status = AE_TYPE; goto UnlockAndExit; } /* Check for an existing internal object, might not exist */ ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { /* Create a new object */ ObjDesc = AcpiUtCreateInternalObject (Node->Type); if (!ObjDesc) { Status = AE_NO_MEMORY; goto UnlockAndExit; } /* Attach new object to the Node, remove local reference */ Status = AcpiNsAttachObject (Device, ObjDesc, Node->Type); AcpiUtRemoveReference (ObjDesc); if (ACPI_FAILURE (Status)) { goto UnlockAndExit; } } /* Ensure that the handler is not already installed in the lists */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { HandlerObj = ObjDesc->CommonNotify.NotifyList[i]; while (HandlerObj) { if (HandlerObj->Notify.Handler == Handler) { Status = AE_ALREADY_EXISTS; goto UnlockAndExit; } HandlerObj = HandlerObj->Notify.Next[i]; } } } /* Create and populate a new notify handler object */ HandlerObj = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_NOTIFY); if (!HandlerObj) { Status = AE_NO_MEMORY; goto UnlockAndExit; } HandlerObj->Notify.Node = Node; HandlerObj->Notify.HandlerType = HandlerType; HandlerObj->Notify.Handler = Handler; HandlerObj->Notify.Context = Context; /* Install the handler at the list head(s) */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { HandlerObj->Notify.Next[i] = ObjDesc->CommonNotify.NotifyList[i]; ObjDesc->CommonNotify.NotifyList[i] = HandlerObj; } } /* Add an extra reference if handler was installed in both lists */ if (HandlerType == ACPI_ALL_NOTIFY) { AcpiUtAddReference (HandlerObj); } UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallNotifyHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveNotifyHandler * * PARAMETERS: Device - The device for which the handler is installed * HandlerType - The type of handler: * ACPI_SYSTEM_NOTIFY: System Handler (00-7F) * ACPI_DEVICE_NOTIFY: Device Handler (80-FF) * ACPI_ALL_NOTIFY: Both System and Device * Handler - Address of the handler * * RETURN: Status * * DESCRIPTION: Remove a handler for notifies on an ACPI device * ******************************************************************************/ ACPI_STATUS AcpiRemoveNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler) { ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Device); ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; ACPI_OPERAND_OBJECT *PreviousHandlerObj; ACPI_STATUS Status = AE_OK; UINT32 i; ACPI_FUNCTION_TRACE (AcpiRemoveNotifyHandler); /* Parameter validation */ if ((!Device) || (!Handler) || (!HandlerType) || (HandlerType > ACPI_MAX_NOTIFY_HANDLER_TYPE)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Root Object. Global handlers are removed here */ if (Device == ACPI_ROOT_OBJECT) { for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (!AcpiGbl_GlobalNotify[i].Handler || (AcpiGbl_GlobalNotify[i].Handler != Handler)) { Status = AE_NOT_EXIST; goto UnlockAndExit; } ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Removing global notify handler\n")); AcpiGbl_GlobalNotify[i].Handler = NULL; AcpiGbl_GlobalNotify[i].Context = NULL; (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); /* Make sure all deferred notify tasks are completed */ AcpiOsWaitEventsComplete (); } } return_ACPI_STATUS (AE_OK); } /* All other objects: Are Notifies allowed on this object? */ if (!AcpiEvIsNotifyObject (Node)) { return_ACPI_STATUS (AE_TYPE); } /* Must have an existing internal object */ ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { return_ACPI_STATUS (AE_NOT_EXIST); } /* Internal object exists. Find the handler and remove it */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } HandlerObj = ObjDesc->CommonNotify.NotifyList[i]; PreviousHandlerObj = NULL; /* Attempt to find the handler in the handler list */ while (HandlerObj && (HandlerObj->Notify.Handler != Handler)) { PreviousHandlerObj = HandlerObj; HandlerObj = HandlerObj->Notify.Next[i]; } if (!HandlerObj) { Status = AE_NOT_EXIST; goto UnlockAndExit; } /* Remove the handler object from the list */ if (PreviousHandlerObj) /* Handler is not at the list head */ { PreviousHandlerObj->Notify.Next[i] = HandlerObj->Notify.Next[i]; } else /* Handler is at the list head */ { ObjDesc->CommonNotify.NotifyList[i] = HandlerObj->Notify.Next[i]; } (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); /* Make sure all deferred notify tasks are completed */ AcpiOsWaitEventsComplete (); AcpiUtRemoveReference (HandlerObj); } } return_ACPI_STATUS (Status); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveNotifyHandler) /******************************************************************************* * * FUNCTION: AcpiInstallExceptionHandler * * PARAMETERS: Handler - Pointer to the handler function for the * event * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function * ******************************************************************************/ ACPI_STATUS AcpiInstallExceptionHandler ( ACPI_EXCEPTION_HANDLER Handler) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallExceptionHandler); Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Don't allow two handlers. */ if (AcpiGbl_ExceptionHandler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } /* Install the handler */ AcpiGbl_ExceptionHandler = Handler; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallExceptionHandler) #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiInstallSciHandler * * PARAMETERS: Address - Address of the handler * Context - Value passed to the handler on each SCI * * RETURN: Status * * DESCRIPTION: Install a handler for a System Control Interrupt. * ******************************************************************************/ ACPI_STATUS AcpiInstallSciHandler ( ACPI_SCI_HANDLER Address, void *Context) { ACPI_SCI_HANDLER_INFO *NewSciHandler; ACPI_SCI_HANDLER_INFO *SciHandler; ACPI_CPU_FLAGS Flags; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallSciHandler); if (!Address) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Allocate and init a handler object */ NewSciHandler = ACPI_ALLOCATE (sizeof (ACPI_SCI_HANDLER_INFO)); if (!NewSciHandler) { return_ACPI_STATUS (AE_NO_MEMORY); } NewSciHandler->Address = Address; NewSciHandler->Context = Context; Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { goto Exit; } /* Lock list during installation */ Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); SciHandler = AcpiGbl_SciHandlerList; /* Ensure handler does not already exist */ while (SciHandler) { if (Address == SciHandler->Address) { Status = AE_ALREADY_EXISTS; goto UnlockAndExit; } SciHandler = SciHandler->Next; } /* Install the new handler into the global list (at head) */ NewSciHandler->Next = AcpiGbl_SciHandlerList; AcpiGbl_SciHandlerList = NewSciHandler; UnlockAndExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); Exit: if (ACPI_FAILURE (Status)) { ACPI_FREE (NewSciHandler); } return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallSciHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveSciHandler * * PARAMETERS: Address - Address of the handler * * RETURN: Status * * DESCRIPTION: Remove a handler for a System Control Interrupt. * ******************************************************************************/ ACPI_STATUS AcpiRemoveSciHandler ( ACPI_SCI_HANDLER Address) { ACPI_SCI_HANDLER_INFO *PrevSciHandler; ACPI_SCI_HANDLER_INFO *NextSciHandler; ACPI_CPU_FLAGS Flags; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiRemoveSciHandler); if (!Address) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Remove the SCI handler with lock */ Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); PrevSciHandler = NULL; NextSciHandler = AcpiGbl_SciHandlerList; while (NextSciHandler) { if (NextSciHandler->Address == Address) { /* Unlink and free the SCI handler info block */ if (PrevSciHandler) { PrevSciHandler->Next = NextSciHandler->Next; } else { AcpiGbl_SciHandlerList = NextSciHandler->Next; } AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); ACPI_FREE (NextSciHandler); goto UnlockAndExit; } PrevSciHandler = NextSciHandler; NextSciHandler = NextSciHandler->Next; } AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); Status = AE_NOT_EXIST; UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveSciHandler) /******************************************************************************* * * FUNCTION: AcpiInstallGlobalEventHandler * * PARAMETERS: Handler - Pointer to the global event handler function * Context - Value passed to the handler on each event * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function. The global handler * is invoked upon each incoming GPE and Fixed Event. It is * invoked at interrupt level at the time of the event dispatch. * Can be used to update event counters, etc. * ******************************************************************************/ ACPI_STATUS AcpiInstallGlobalEventHandler ( ACPI_GBL_EVENT_HANDLER Handler, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallGlobalEventHandler); /* Parameter validation */ if (!Handler) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Don't allow two handlers. */ if (AcpiGbl_GlobalEventHandler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } AcpiGbl_GlobalEventHandler = Handler; AcpiGbl_GlobalEventHandlerContext = Context; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallGlobalEventHandler) /******************************************************************************* * * FUNCTION: AcpiInstallFixedEventHandler * * PARAMETERS: Event - Event type to enable. * Handler - Pointer to the handler function for the * event * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function and then enables the * event. * ******************************************************************************/ ACPI_STATUS AcpiInstallFixedEventHandler ( UINT32 Event, ACPI_EVENT_HANDLER Handler, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallFixedEventHandler); /* Parameter validation */ if (Event > ACPI_EVENT_MAX) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Do not allow multiple handlers */ if (AcpiGbl_FixedEventHandlers[Event].Handler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } /* Install the handler before enabling the event */ AcpiGbl_FixedEventHandlers[Event].Handler = Handler; AcpiGbl_FixedEventHandlers[Event].Context = Context; Status = AcpiEnableEvent (Event, 0); if (ACPI_FAILURE (Status)) { ACPI_WARNING ((AE_INFO, "Could not enable fixed event - %s (%u)", AcpiUtGetEventName (Event), Event)); /* Remove the handler */ AcpiGbl_FixedEventHandlers[Event].Handler = NULL; AcpiGbl_FixedEventHandlers[Event].Context = NULL; } else { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Enabled fixed event %s (%X), Handler=%p\n", AcpiUtGetEventName (Event), Event, Handler)); } Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallFixedEventHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveFixedEventHandler * * PARAMETERS: Event - Event type to disable. * Handler - Address of the handler * * RETURN: Status * * DESCRIPTION: Disables the event and unregisters the event handler. * ******************************************************************************/ ACPI_STATUS AcpiRemoveFixedEventHandler ( UINT32 Event, ACPI_EVENT_HANDLER Handler) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (AcpiRemoveFixedEventHandler); /* Parameter validation */ if (Event > ACPI_EVENT_MAX) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Disable the event before removing the handler */ Status = AcpiDisableEvent (Event, 0); /* Always Remove the handler */ AcpiGbl_FixedEventHandlers[Event].Handler = NULL; AcpiGbl_FixedEventHandlers[Event].Context = NULL; if (ACPI_FAILURE (Status)) { ACPI_WARNING ((AE_INFO, "Could not disable fixed event - %s (%u)", AcpiUtGetEventName (Event), Event)); } else { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Disabled fixed event - %s (%X)\n", AcpiUtGetEventName (Event), Event)); } (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveFixedEventHandler) /******************************************************************************* * * FUNCTION: AcpiEvInstallGpeHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The GPE number within the GPE block * Type - Whether this GPE should be treated as an * edge- or level-triggered interrupt. * IsRawHandler - Whether this GPE should be handled using * the special GPE handler mode. * Address - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Internal function to install a handler for a General Purpose * Event. * ******************************************************************************/ static ACPI_STATUS AcpiEvInstallGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, BOOLEAN IsRawHandler, ACPI_GPE_HANDLER Address, void *Context) { ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_GPE_HANDLER_INFO *Handler; ACPI_STATUS Status; ACPI_CPU_FLAGS Flags; ACPI_FUNCTION_TRACE (EvInstallGpeHandler); /* Parameter validation */ if ((!Address) || (Type & ~ACPI_GPE_XRUPT_TYPE_MASK)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Allocate and init handler object (before lock) */ Handler = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_GPE_HANDLER_INFO)); if (!Handler) { Status = AE_NO_MEMORY; goto UnlockAndExit; } Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); /* Ensure that we have a valid GPE number */ GpeEventInfo = AcpiEvGetGpeEventInfo (GpeDevice, GpeNumber); if (!GpeEventInfo) { Status = AE_BAD_PARAMETER; goto FreeAndExit; } /* Make sure that there isn't a handler there already */ if ((ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_HANDLER) || (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_RAW_HANDLER)) { Status = AE_ALREADY_EXISTS; goto FreeAndExit; } Handler->Address = Address; Handler->Context = Context; Handler->MethodNode = GpeEventInfo->Dispatch.MethodNode; Handler->OriginalFlags = (UINT8) (GpeEventInfo->Flags & (ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK)); /* * If the GPE is associated with a method, it may have been enabled * automatically during initialization, in which case it has to be * disabled now to avoid spurious execution of the handler. */ if (((ACPI_GPE_DISPATCH_TYPE (Handler->OriginalFlags) == ACPI_GPE_DISPATCH_METHOD) || (ACPI_GPE_DISPATCH_TYPE (Handler->OriginalFlags) == ACPI_GPE_DISPATCH_NOTIFY)) && GpeEventInfo->RuntimeCount) { Handler->OriginallyEnabled = TRUE; (void) AcpiEvRemoveGpeReference (GpeEventInfo); /* Sanity check of original type against new type */ if (Type != (UINT32) (GpeEventInfo->Flags & ACPI_GPE_XRUPT_TYPE_MASK)) { ACPI_WARNING ((AE_INFO, "GPE type mismatch (level/edge)")); } } /* Install the handler */ GpeEventInfo->Dispatch.Handler = Handler; /* Setup up dispatch flags to indicate handler (vs. method/notify) */ GpeEventInfo->Flags &= ~(ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK); GpeEventInfo->Flags |= (UINT8) (Type | (IsRawHandler ? ACPI_GPE_DISPATCH_RAW_HANDLER : ACPI_GPE_DISPATCH_HANDLER)); AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); FreeAndExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); ACPI_FREE (Handler); goto UnlockAndExit; } /******************************************************************************* * * FUNCTION: AcpiInstallGpeHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The GPE number within the GPE block * Type - Whether this GPE should be treated as an * edge- or level-triggered interrupt. * Address - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Install a handler for a General Purpose Event. * ******************************************************************************/ ACPI_STATUS AcpiInstallGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, ACPI_GPE_HANDLER Address, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallGpeHandler); Status = AcpiEvInstallGpeHandler (GpeDevice, GpeNumber, Type, FALSE, Address, Context); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallGpeHandler) /******************************************************************************* * * FUNCTION: AcpiInstallGpeRawHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The GPE number within the GPE block * Type - Whether this GPE should be treated as an * edge- or level-triggered interrupt. * Address - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Install a handler for a General Purpose Event. * ******************************************************************************/ ACPI_STATUS AcpiInstallGpeRawHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, ACPI_GPE_HANDLER Address, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallGpeRawHandler); Status = AcpiEvInstallGpeHandler (GpeDevice, GpeNumber, Type, TRUE, Address, Context); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallGpeRawHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveGpeHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The event to remove a handler * Address - Address of the handler * * RETURN: Status * * DESCRIPTION: Remove a handler for a General Purpose AcpiEvent. * ******************************************************************************/ ACPI_STATUS AcpiRemoveGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, ACPI_GPE_HANDLER Address) { ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_GPE_HANDLER_INFO *Handler; ACPI_STATUS Status; ACPI_CPU_FLAGS Flags; ACPI_FUNCTION_TRACE (AcpiRemoveGpeHandler); /* Parameter validation */ if (!Address) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); /* Ensure that we have a valid GPE number */ GpeEventInfo = AcpiEvGetGpeEventInfo (GpeDevice, GpeNumber); if (!GpeEventInfo) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } /* Make sure that a handler is indeed installed */ if ((ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) != ACPI_GPE_DISPATCH_HANDLER) && (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) != ACPI_GPE_DISPATCH_RAW_HANDLER)) { Status = AE_NOT_EXIST; goto UnlockAndExit; } /* Make sure that the installed handler is the same */ if (GpeEventInfo->Dispatch.Handler->Address != Address) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } /* Remove the handler */ Handler = GpeEventInfo->Dispatch.Handler; GpeEventInfo->Dispatch.Handler = NULL; /* Restore Method node (if any), set dispatch flags */ GpeEventInfo->Dispatch.MethodNode = Handler->MethodNode; GpeEventInfo->Flags &= ~(ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK); GpeEventInfo->Flags |= Handler->OriginalFlags; /* * If the GPE was previously associated with a method and it was * enabled, it should be enabled at this point to restore the * post-initialization configuration. */ if (((ACPI_GPE_DISPATCH_TYPE (Handler->OriginalFlags) == ACPI_GPE_DISPATCH_METHOD) || (ACPI_GPE_DISPATCH_TYPE (Handler->OriginalFlags) == ACPI_GPE_DISPATCH_NOTIFY)) && Handler->OriginallyEnabled) { (void) AcpiEvAddGpeReference (GpeEventInfo, FALSE); if (ACPI_GPE_IS_POLLING_NEEDED (GpeEventInfo)) { /* Poll edge triggered GPEs to handle existing events */ AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); (void) AcpiEvDetectGpe ( GpeDevice, GpeEventInfo, GpeNumber); Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); } } AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); /* Make sure all deferred GPE tasks are completed */ AcpiOsWaitEventsComplete (); /* Now we can free the handler object */ ACPI_FREE (Handler); return_ACPI_STATUS (Status); UnlockAndExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveGpeHandler) /******************************************************************************* * * FUNCTION: AcpiAcquireGlobalLock * * PARAMETERS: Timeout - How long the caller is willing to wait * Handle - Where the handle to the lock is returned * (if acquired) * * RETURN: Status * * DESCRIPTION: Acquire the ACPI Global Lock * * Note: Allows callers with the same thread ID to acquire the global lock * multiple times. In other words, externally, the behavior of the global lock * is identical to an AML mutex. On the first acquire, a new handle is * returned. On any subsequent calls to acquire by the same thread, the same * handle is returned. * ******************************************************************************/ ACPI_STATUS AcpiAcquireGlobalLock ( UINT16 Timeout, UINT32 *Handle) { ACPI_STATUS Status; if (!Handle) { return (AE_BAD_PARAMETER); } /* Must lock interpreter to prevent race conditions */ AcpiExEnterInterpreter (); Status = AcpiExAcquireMutexObject (Timeout, AcpiGbl_GlobalLockMutex, AcpiOsGetThreadId ()); if (ACPI_SUCCESS (Status)) { /* Return the global lock handle (updated in AcpiEvAcquireGlobalLock) */ *Handle = AcpiGbl_GlobalLockHandle; } AcpiExExitInterpreter (); return (Status); } ACPI_EXPORT_SYMBOL (AcpiAcquireGlobalLock) /******************************************************************************* * * FUNCTION: AcpiReleaseGlobalLock * * PARAMETERS: Handle - Returned from AcpiAcquireGlobalLock * * RETURN: Status * * DESCRIPTION: Release the ACPI Global Lock. The handle must be valid. * ******************************************************************************/ ACPI_STATUS AcpiReleaseGlobalLock ( UINT32 Handle) { ACPI_STATUS Status; if (!Handle || (Handle != AcpiGbl_GlobalLockHandle)) { return (AE_NOT_ACQUIRED); } Status = AcpiExReleaseMutexObject (AcpiGbl_GlobalLockMutex); return (Status); } ACPI_EXPORT_SYMBOL (AcpiReleaseGlobalLock) #endif /* !ACPI_REDUCED_HARDWARE */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define KMALLOC_METADATA_BLOCK_NODE_SIZE 1 #define KMALLOC_HEAPS_COUNT 32 #define SMALL_HEAP_MBS 32 #define SMALL_HEAP_SIZE (32 * KB) #define SMALL_HEAP_MD_SIZE \ (calculate_heap_metadata_size(SMALL_HEAP_SIZE, SMALL_HEAP_MBS)) #define KMALLOC_FL_MULTI_STEP (0b10000000000000000000000000000000) #define KMALLOC_FL_NO_ACTUAL_ALLOC (0b01000000000000000000000000000000) #define KMALLOC_FL_DMA (0b00100000000000000000000000000000) #define KMALLOC_FL_RESV_FLAGS_MASK (0b00010000000000000000000000000000) #define KMALLOC_FL_DONT_ACCOUNT (0b00001000000000000000000000000000) #define KMALLOC_FL_SUB_BLOCK_MIN_SIZE_MASK (0b00000111111111111111111111111111) #define KFREE_FL_MULTI_STEP (0b10000000000000000000000000000000) #define KFREE_FL_NO_ACTUAL_FREE (0b01000000000000000000000000000000) #define KFREE_FL_ALLOW_SPLIT (0b00100000000000000000000000000000) typedef bool (*virtual_alloc_and_map_func)(ulong vaddr, size_t page_count); typedef void (*virtual_free_and_unmap_func)(ulong vaddr, size_t page_count); #define calculate_heap_metadata_size(heap_size, min_block_size) \ (2 * (heap_size) / (min_block_size)) #define calculate_heap_min_block_size(heap_size, metadata_size) \ (2 * (heap_size) / (metadata_size)) struct kmalloc_heap; void early_init_kmalloc(void); void init_kmalloc(void); void * general_kmalloc(size_t *size, u32 flags); void general_kfree(void *ptr, size_t *size, u32 flags); bool is_kmalloc_initialized(void); bool kmalloc_create_heap(struct kmalloc_heap *h, ulong vaddr, size_t size, size_t min_block_size, size_t alloc_block_size, /* 0 if linear_mapping=1 */ bool linear_mapping, void *metadata_nodes, // optional virtual_alloc_and_map_func valloc, // optional virtual_free_and_unmap_func vfree); // optional struct kmalloc_heap * kmalloc_create_regular_heap(ulong vaddr, size_t size, size_t min_block_size); void kmalloc_destroy_heap(struct kmalloc_heap *h); struct kmalloc_heap * kmalloc_heap_dup(struct kmalloc_heap *h); struct kmalloc_heap * kmalloc_heap_dup_expanded(struct kmalloc_heap *h, size_t sz); void * per_heap_kmalloc(struct kmalloc_heap *h, size_t *size, u32 flags); void per_heap_kfree(struct kmalloc_heap *h, void *ptr, size_t *size, u32 flags); struct kmalloc_acc { u32 elem_size; u32 elem_count; u32 curr_elem; char *buf; }; void kmalloc_create_accelerator(struct kmalloc_acc *a, u32 elem_s, u32 elem_c); void * kmalloc_accelerator_get_elem(struct kmalloc_acc *a); void kmalloc_destroy_accelerator(struct kmalloc_acc *a); static inline void * kmalloc(size_t size) { return general_kmalloc(&size, 0); } static inline void kfree2(void *ptr, size_t size) { general_kfree(ptr, &size, 0); } void * kzmalloc(size_t size); size_t kmalloc_get_heap_struct_size(void); size_t kmalloc_get_max_tot_heap_free(void); void * aligned_kmalloc(size_t size, u32 align); void aligned_kfree2(void *ptr, size_t size); void * vmalloc(size_t size); void vfree2(void *ptr, size_t size); /* Free function to use when we really don't know chunk's size */ static inline void kfree(void *ptr) { kfree2(ptr, 0); } #define kalloc_obj(type) kmalloc(sizeof(type)) #define kzalloc_obj(type) kzmalloc(sizeof(type)) #define kfree_obj(ptr, type) kfree2((ptr), sizeof(type)) #define kalloc_array_obj(type, cnt) kmalloc(sizeof(type) * (cnt)) #define kzalloc_array_obj(type, cnt) kzmalloc(sizeof(type) * (cnt)) #define kfree_array_obj(ptr, type, cnt) kfree2((ptr), sizeof(type) * (cnt)) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/boot/common.h> extern const struct bootloader_intf *intf; extern video_mode_t g_defmode; void show_video_modes(void); void show_mode(int num, struct generic_video_mode_info *gi, bool is_default); int read_line(char *buf, int buf_sz); void fetch_all_video_modes_once(void); video_mode_t get_user_video_mode_choice(void); void *simple_elf_loader(void *elf); <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) smart_config_file(linker_script.ld ${STAGE3_SCRIPT}) file( GLOB STAGE3_C_SOURCES ${GLOB_CONF_DEP} "*.c" "${CMAKE_SOURCE_DIR}/boot/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.cpp" "${CMAKE_SOURCE_DIR}/common/arch/generic_x86/*.c" ) set(STAGE3_ASM_SOURCES "entry.S" "rm_calls.S") set(STAGE3_BUILD_FLAGS_LIST "") list( APPEND STAGE3_BUILD_FLAGS_LIST -D__TILCK_BOOTLOADER__ -static -fno-pic -mno-red-zone ${GENERAL_DEFS_LIST} ${DBG_FLAGS_LIST} ${OPT_FLAGS_LIST} ${WARN_FLAGS_LIST} ${FREESTANDING_FLAGS_LIST} ${SAFER_BEHAVIOR_FLAGS_LIST} ${LOWLEVEL_BINARIES_FLAGS_LIST} ${DISABLE_FPU_FLAGS_LIST} ) JOIN("${STAGE3_BUILD_FLAGS_LIST}" ${SPACE} STAGE3_BUILD_FLAGS) set( STAGE3_LINK_FLAGS_LIST -nostdlib -static -Wl,--build-id=none -Wl,--script=${STAGE3_SCRIPT} ) JOIN("${STAGE3_LINK_FLAGS_LIST}" ${SPACE} STAGE3_LINK_FLAGS) add_executable( elf_stage3_unstripped EXCLUDE_FROM_ALL ${STAGE3_ASM_SOURCES} ${STAGE3_C_SOURCES} ) add_dependencies(elf_stage3_unstripped kernel) set_target_properties( elf_stage3_unstripped PROPERTIES COMPILE_FLAGS ${STAGE3_BUILD_FLAGS} LINK_FLAGS ${STAGE3_LINK_FLAGS} LINK_DEPENDS ${STAGE3_SCRIPT} ) # -lgcc is necessary for things like 64 bit integers in 32 bit mode. target_link_libraries(elf_stage3_unstripped gcc) <file_sep>/****************************************************************************** * * Name: aclocal.h - Internal data types used across the ACPI subsystem * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACLOCAL_H__ #define __ACLOCAL_H__ /* acpisrc:StructDefs -- for acpisrc conversion */ #define ACPI_SERIALIZED 0xFF typedef UINT32 ACPI_MUTEX_HANDLE; #define ACPI_GLOBAL_LOCK (ACPI_SEMAPHORE) (-1) /* Total number of aml opcodes defined */ #define AML_NUM_OPCODES 0x83 /* Forward declarations */ struct acpi_walk_state; struct acpi_obj_mutex; union acpi_parse_object; /***************************************************************************** * * Mutex typedefs and structs * ****************************************************************************/ /* * Predefined handles for the mutex objects used within the subsystem * All mutex objects are automatically created by AcpiUtMutexInitialize. * * The acquire/release ordering protocol is implied via this list. Mutexes * with a lower value must be acquired before mutexes with a higher value. * * NOTE: any changes here must be reflected in the AcpiGbl_MutexNames * table below also! */ #define ACPI_MTX_INTERPRETER 0 /* AML Interpreter, main lock */ #define ACPI_MTX_NAMESPACE 1 /* ACPI Namespace */ #define ACPI_MTX_TABLES 2 /* Data for ACPI tables */ #define ACPI_MTX_EVENTS 3 /* Data for ACPI events */ #define ACPI_MTX_CACHES 4 /* Internal caches, general purposes */ #define ACPI_MTX_MEMORY 5 /* Debug memory tracking lists */ #define ACPI_MAX_MUTEX 5 #define ACPI_NUM_MUTEX (ACPI_MAX_MUTEX+1) /* Lock structure for reader/writer interfaces */ typedef struct acpi_rw_lock { ACPI_MUTEX WriterMutex; ACPI_MUTEX ReaderMutex; UINT32 NumReaders; } ACPI_RW_LOCK; /* * Predefined handles for spinlocks used within the subsystem. * These spinlocks are created by AcpiUtMutexInitialize */ #define ACPI_LOCK_GPES 0 #define ACPI_LOCK_HARDWARE 1 #define ACPI_MAX_LOCK 1 #define ACPI_NUM_LOCK (ACPI_MAX_LOCK+1) /* This Thread ID means that the mutex is not in use (unlocked) */ #define ACPI_MUTEX_NOT_ACQUIRED ((ACPI_THREAD_ID) -1) /* This Thread ID means an invalid thread ID */ #ifdef ACPI_OS_INVALID_THREAD_ID #define ACPI_INVALID_THREAD_ID ACPI_OS_INVALID_THREAD_ID #else #define ACPI_INVALID_THREAD_ID ((ACPI_THREAD_ID) 0xFFFFFFFF) #endif /* Table for the global mutexes */ typedef struct acpi_mutex_info { ACPI_MUTEX Mutex; UINT32 UseCount; ACPI_THREAD_ID ThreadId; } ACPI_MUTEX_INFO; /* Lock flag parameter for various interfaces */ #define ACPI_MTX_DO_NOT_LOCK 0 #define ACPI_MTX_LOCK 1 /* Field access granularities */ #define ACPI_FIELD_BYTE_GRANULARITY 1 #define ACPI_FIELD_WORD_GRANULARITY 2 #define ACPI_FIELD_DWORD_GRANULARITY 4 #define ACPI_FIELD_QWORD_GRANULARITY 8 #define ACPI_ENTRY_NOT_FOUND NULL /***************************************************************************** * * Namespace typedefs and structs * ****************************************************************************/ /* Operational modes of the AML interpreter/scanner */ typedef enum { ACPI_IMODE_LOAD_PASS1 = 0x01, ACPI_IMODE_LOAD_PASS2 = 0x02, ACPI_IMODE_EXECUTE = 0x03 } ACPI_INTERPRETER_MODE; /* * The Namespace Node describes a named object that appears in the AML. * DescriptorType is used to differentiate between internal descriptors. * * The node is optimized for both 32-bit and 64-bit platforms: * 20 bytes for the 32-bit case, 32 bytes for the 64-bit case. * * Note: The DescriptorType and Type fields must appear in the identical * position in both the ACPI_NAMESPACE_NODE and ACPI_OPERAND_OBJECT * structures. */ typedef struct acpi_namespace_node { union acpi_operand_object *Object; /* Interpreter object */ UINT8 DescriptorType; /* Differentiate object descriptor types */ UINT8 Type; /* ACPI Type associated with this name */ UINT16 Flags; /* Miscellaneous flags */ ACPI_NAME_UNION Name; /* ACPI Name, always 4 chars per ACPI spec */ struct acpi_namespace_node *Parent; /* Parent node */ struct acpi_namespace_node *Child; /* First child */ struct acpi_namespace_node *Peer; /* First peer */ ACPI_OWNER_ID OwnerId; /* Node creator */ /* * The following fields are used by the ASL compiler and disassembler only */ #ifdef ACPI_LARGE_NAMESPACE_NODE union acpi_parse_object *Op; void *MethodLocals; void *MethodArgs; UINT32 Value; UINT32 Length; UINT8 ArgCount; #endif } ACPI_NAMESPACE_NODE; /* Namespace Node flags */ #define ANOBJ_RESERVED 0x01 /* Available for use */ #define ANOBJ_TEMPORARY 0x02 /* Node is create by a method and is temporary */ #define ANOBJ_METHOD_ARG 0x04 /* Node is a method argument */ #define ANOBJ_METHOD_LOCAL 0x08 /* Node is a method local */ #define ANOBJ_SUBTREE_HAS_INI 0x10 /* Used to optimize device initialization */ #define ANOBJ_EVALUATED 0x20 /* Set on first evaluation of node */ #define ANOBJ_ALLOCATED_BUFFER 0x40 /* Method AML buffer is dynamic (InstallMethod) */ #define ANOBJ_NODE_EARLY_INIT 0x80 /* AcpiExec only: Node was create via init file (-fi) */ #define ANOBJ_IS_EXTERNAL 0x08 /* iASL only: This object created via External() */ #define ANOBJ_METHOD_NO_RETVAL 0x10 /* iASL only: Method has no return value */ #define ANOBJ_METHOD_SOME_NO_RETVAL 0x20 /* iASL only: Method has at least one return value */ #define ANOBJ_IS_REFERENCED 0x80 /* iASL only: Object was referenced */ /* Internal ACPI table management - master table list */ typedef struct acpi_table_list { ACPI_TABLE_DESC *Tables; /* Table descriptor array */ UINT32 CurrentTableCount; /* Tables currently in the array */ UINT32 MaxTableCount; /* Max tables array will hold */ UINT8 Flags; } ACPI_TABLE_LIST; /* Flags for above */ #define ACPI_ROOT_ORIGIN_UNKNOWN (0) /* ~ORIGIN_ALLOCATED */ #define ACPI_ROOT_ORIGIN_ALLOCATED (1) #define ACPI_ROOT_ALLOW_RESIZE (2) /* List to manage incoming ACPI tables */ typedef struct acpi_new_table_desc { ACPI_TABLE_HEADER *Table; struct acpi_new_table_desc *Next; } ACPI_NEW_TABLE_DESC; /* Predefined table indexes */ #define ACPI_INVALID_TABLE_INDEX (0xFFFFFFFF) typedef struct acpi_find_context { char *SearchFor; ACPI_HANDLE *List; UINT32 *Count; } ACPI_FIND_CONTEXT; typedef struct acpi_ns_search_data { ACPI_NAMESPACE_NODE *Node; } ACPI_NS_SEARCH_DATA; /* Object types used during package copies */ #define ACPI_COPY_TYPE_SIMPLE 0 #define ACPI_COPY_TYPE_PACKAGE 1 /* Info structure used to convert external<->internal namestrings */ typedef struct acpi_namestring_info { const char *ExternalName; const char *NextExternalChar; char *InternalName; UINT32 Length; UINT32 NumSegments; UINT32 NumCarats; BOOLEAN FullyQualified; } ACPI_NAMESTRING_INFO; /* Field creation info */ typedef struct acpi_create_field_info { ACPI_NAMESPACE_NODE *RegionNode; ACPI_NAMESPACE_NODE *FieldNode; ACPI_NAMESPACE_NODE *RegisterNode; ACPI_NAMESPACE_NODE *DataRegisterNode; ACPI_NAMESPACE_NODE *ConnectionNode; UINT8 *ResourceBuffer; UINT32 BankValue; UINT32 FieldBitPosition; UINT32 FieldBitLength; UINT16 ResourceLength; UINT16 PinNumberIndex; UINT8 FieldFlags; UINT8 Attribute; UINT8 FieldType; UINT8 AccessLength; } ACPI_CREATE_FIELD_INFO; typedef ACPI_STATUS (*ACPI_INTERNAL_METHOD) ( struct acpi_walk_state *WalkState); /* * Bitmapped ACPI types. Used internally only */ #define ACPI_BTYPE_ANY 0x00000000 #define ACPI_BTYPE_INTEGER 0x00000001 #define ACPI_BTYPE_STRING 0x00000002 #define ACPI_BTYPE_BUFFER 0x00000004 #define ACPI_BTYPE_PACKAGE 0x00000008 #define ACPI_BTYPE_FIELD_UNIT 0x00000010 #define ACPI_BTYPE_DEVICE 0x00000020 #define ACPI_BTYPE_EVENT 0x00000040 #define ACPI_BTYPE_METHOD 0x00000080 #define ACPI_BTYPE_MUTEX 0x00000100 #define ACPI_BTYPE_REGION 0x00000200 #define ACPI_BTYPE_POWER 0x00000400 #define ACPI_BTYPE_PROCESSOR 0x00000800 #define ACPI_BTYPE_THERMAL 0x00001000 #define ACPI_BTYPE_BUFFER_FIELD 0x00002000 #define ACPI_BTYPE_DDB_HANDLE 0x00004000 #define ACPI_BTYPE_DEBUG_OBJECT 0x00008000 #define ACPI_BTYPE_REFERENCE_OBJECT 0x00010000 /* From Index(), RefOf(), etc (Type6Opcodes) */ #define ACPI_BTYPE_RESOURCE 0x00020000 #define ACPI_BTYPE_NAMED_REFERENCE 0x00040000 /* Generic unresolved Name or Namepath */ #define ACPI_BTYPE_COMPUTE_DATA (ACPI_BTYPE_INTEGER | ACPI_BTYPE_STRING | ACPI_BTYPE_BUFFER) #define ACPI_BTYPE_DATA (ACPI_BTYPE_COMPUTE_DATA | ACPI_BTYPE_PACKAGE) /* Used by Copy, DeRefOf, Store, Printf, Fprintf */ #define ACPI_BTYPE_DATA_REFERENCE (ACPI_BTYPE_DATA | ACPI_BTYPE_REFERENCE_OBJECT | ACPI_BTYPE_DDB_HANDLE) #define ACPI_BTYPE_DEVICE_OBJECTS (ACPI_BTYPE_DEVICE | ACPI_BTYPE_THERMAL | ACPI_BTYPE_PROCESSOR) #define ACPI_BTYPE_OBJECTS_AND_REFS 0x0001FFFF /* ARG or LOCAL */ #define ACPI_BTYPE_ALL_OBJECTS 0x0000FFFF #pragma pack(1) /* * Information structure for ACPI predefined names. * Each entry in the table contains the following items: * * Name - The ACPI reserved name * ParamCount - Number of arguments to the method * ExpectedReturnBtypes - Allowed type(s) for the return value */ typedef struct acpi_name_info { char Name[ACPI_NAMESEG_SIZE]; UINT16 ArgumentList; UINT8 ExpectedBtypes; } ACPI_NAME_INFO; /* * Secondary information structures for ACPI predefined objects that return * package objects. This structure appears as the next entry in the table * after the NAME_INFO structure above. * * The reason for this is to minimize the size of the predefined name table. */ /* * Used for ACPI_PTYPE1_FIXED, ACPI_PTYPE1_VAR, ACPI_PTYPE2, * ACPI_PTYPE2_MIN, ACPI_PTYPE2_PKG_COUNT, ACPI_PTYPE2_COUNT, * ACPI_PTYPE2_FIX_VAR */ typedef struct acpi_package_info { UINT8 Type; UINT8 ObjectType1; UINT8 Count1; UINT8 ObjectType2; UINT8 Count2; UINT16 Reserved; } ACPI_PACKAGE_INFO; /* Used for ACPI_PTYPE2_FIXED */ typedef struct acpi_package_info2 { UINT8 Type; UINT8 Count; UINT8 ObjectType[4]; UINT8 Reserved; } ACPI_PACKAGE_INFO2; /* Used for ACPI_PTYPE1_OPTION */ typedef struct acpi_package_info3 { UINT8 Type; UINT8 Count; UINT8 ObjectType[2]; UINT8 TailObjectType; UINT16 Reserved; } ACPI_PACKAGE_INFO3; typedef struct acpi_package_info4 { UINT8 Type; UINT8 ObjectType1; UINT8 Count1; UINT8 SubObjectTypes; UINT8 PkgCount; UINT16 Reserved; } ACPI_PACKAGE_INFO4; typedef union acpi_predefined_info { ACPI_NAME_INFO Info; ACPI_PACKAGE_INFO RetInfo; ACPI_PACKAGE_INFO2 RetInfo2; ACPI_PACKAGE_INFO3 RetInfo3; ACPI_PACKAGE_INFO4 RetInfo4; } ACPI_PREDEFINED_INFO; /* Reset to default packing */ #pragma pack() /* Return object auto-repair info */ typedef ACPI_STATUS (*ACPI_OBJECT_CONVERTER) ( struct acpi_namespace_node *Scope, union acpi_operand_object *OriginalObject, union acpi_operand_object **ConvertedObject); typedef struct acpi_simple_repair_info { char Name[ACPI_NAMESEG_SIZE]; UINT32 UnexpectedBtypes; UINT32 PackageIndex; ACPI_OBJECT_CONVERTER ObjectConverter; } ACPI_SIMPLE_REPAIR_INFO; /* * Bitmapped return value types * Note: the actual data types must be contiguous, a loop in nspredef.c * depends on this. */ #define ACPI_RTYPE_ANY 0x00 #define ACPI_RTYPE_NONE 0x01 #define ACPI_RTYPE_INTEGER 0x02 #define ACPI_RTYPE_STRING 0x04 #define ACPI_RTYPE_BUFFER 0x08 #define ACPI_RTYPE_PACKAGE 0x10 #define ACPI_RTYPE_REFERENCE 0x20 #define ACPI_RTYPE_ALL 0x3F #define ACPI_NUM_RTYPES 5 /* Number of actual object types */ /* Info for running the _REG methods */ typedef struct acpi_reg_walk_info { UINT32 Function; UINT32 RegRunCount; ACPI_ADR_SPACE_TYPE SpaceId; } ACPI_REG_WALK_INFO; /***************************************************************************** * * Event typedefs and structs * ****************************************************************************/ /* Dispatch info for each host-installed SCI handler */ typedef struct acpi_sci_handler_info { struct acpi_sci_handler_info *Next; ACPI_SCI_HANDLER Address; /* Address of handler */ void *Context; /* Context to be passed to handler */ } ACPI_SCI_HANDLER_INFO; /* Dispatch info for each GPE -- either a method or handler, cannot be both */ typedef struct acpi_gpe_handler_info { ACPI_GPE_HANDLER Address; /* Address of handler, if any */ void *Context; /* Context to be passed to handler */ ACPI_NAMESPACE_NODE *MethodNode; /* Method node for this GPE level (saved) */ UINT8 OriginalFlags; /* Original (pre-handler) GPE info */ BOOLEAN OriginallyEnabled; /* True if GPE was originally enabled */ } ACPI_GPE_HANDLER_INFO; /* Notify info for implicit notify, multiple device objects */ typedef struct acpi_gpe_notify_info { ACPI_NAMESPACE_NODE *DeviceNode; /* Device to be notified */ struct acpi_gpe_notify_info *Next; } ACPI_GPE_NOTIFY_INFO; /* * GPE dispatch info. At any time, the GPE can have at most one type * of dispatch - Method, Handler, or Implicit Notify. */ typedef union acpi_gpe_dispatch_info { ACPI_NAMESPACE_NODE *MethodNode; /* Method node for this GPE level */ ACPI_GPE_HANDLER_INFO *Handler; /* Installed GPE handler */ ACPI_GPE_NOTIFY_INFO *NotifyList; /* List of _PRW devices for implicit notifies */ } ACPI_GPE_DISPATCH_INFO; /* * Information about a GPE, one per each GPE in an array. * NOTE: Important to keep this struct as small as possible. */ typedef struct acpi_gpe_event_info { union acpi_gpe_dispatch_info Dispatch; /* Either Method, Handler, or NotifyList */ struct acpi_gpe_register_info *RegisterInfo; /* Backpointer to register info */ UINT8 Flags; /* Misc info about this GPE */ UINT8 GpeNumber; /* This GPE */ UINT8 RuntimeCount; /* References to a run GPE */ BOOLEAN DisableForDispatch; /* Masked during dispatching */ } ACPI_GPE_EVENT_INFO; /* Information about a GPE register pair, one per each status/enable pair in an array */ typedef struct acpi_gpe_register_info { ACPI_GENERIC_ADDRESS StatusAddress; /* Address of status reg */ ACPI_GENERIC_ADDRESS EnableAddress; /* Address of enable reg */ UINT16 BaseGpeNumber; /* Base GPE number for this register */ UINT8 EnableForWake; /* GPEs to keep enabled when sleeping */ UINT8 EnableForRun; /* GPEs to keep enabled when running */ UINT8 MaskForRun; /* GPEs to keep masked when running */ UINT8 EnableMask; /* Current mask of enabled GPEs */ } ACPI_GPE_REGISTER_INFO; /* * Information about a GPE register block, one per each installed block -- * GPE0, GPE1, and one per each installed GPE Block Device. */ typedef struct acpi_gpe_block_info { ACPI_NAMESPACE_NODE *Node; struct acpi_gpe_block_info *Previous; struct acpi_gpe_block_info *Next; struct acpi_gpe_xrupt_info *XruptBlock; /* Backpointer to interrupt block */ ACPI_GPE_REGISTER_INFO *RegisterInfo; /* One per GPE register pair */ ACPI_GPE_EVENT_INFO *EventInfo; /* One for each GPE */ UINT64 Address; /* Base address of the block */ UINT32 RegisterCount; /* Number of register pairs in block */ UINT16 GpeCount; /* Number of individual GPEs in block */ UINT16 BlockBaseNumber;/* Base GPE number for this block */ UINT8 SpaceId; BOOLEAN Initialized; /* TRUE if this block is initialized */ } ACPI_GPE_BLOCK_INFO; /* Information about GPE interrupt handlers, one per each interrupt level used for GPEs */ typedef struct acpi_gpe_xrupt_info { struct acpi_gpe_xrupt_info *Previous; struct acpi_gpe_xrupt_info *Next; ACPI_GPE_BLOCK_INFO *GpeBlockListHead; /* List of GPE blocks for this xrupt */ UINT32 InterruptNumber; /* System interrupt number */ } ACPI_GPE_XRUPT_INFO; typedef struct acpi_gpe_walk_info { ACPI_NAMESPACE_NODE *GpeDevice; ACPI_GPE_BLOCK_INFO *GpeBlock; UINT16 Count; ACPI_OWNER_ID OwnerId; BOOLEAN ExecuteByOwnerId; } ACPI_GPE_WALK_INFO; typedef struct acpi_gpe_device_info { UINT32 Index; UINT32 NextBlockBaseIndex; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *GpeDevice; } ACPI_GPE_DEVICE_INFO; typedef ACPI_STATUS (*ACPI_GPE_CALLBACK) ( ACPI_GPE_XRUPT_INFO *GpeXruptInfo, ACPI_GPE_BLOCK_INFO *GpeBlock, void *Context); /* Information about each particular fixed event */ typedef struct acpi_fixed_event_handler { ACPI_EVENT_HANDLER Handler; /* Address of handler. */ void *Context; /* Context to be passed to handler */ } ACPI_FIXED_EVENT_HANDLER; typedef struct acpi_fixed_event_info { UINT8 StatusRegisterId; UINT8 EnableRegisterId; UINT16 StatusBitMask; UINT16 EnableBitMask; } ACPI_FIXED_EVENT_INFO; /* Information used during field processing */ typedef struct acpi_field_info { UINT8 SkipField; UINT8 FieldFlag; UINT32 PkgLength; } ACPI_FIELD_INFO; /***************************************************************************** * * Generic "state" object for stacks * ****************************************************************************/ #define ACPI_CONTROL_NORMAL 0xC0 #define ACPI_CONTROL_CONDITIONAL_EXECUTING 0xC1 #define ACPI_CONTROL_PREDICATE_EXECUTING 0xC2 #define ACPI_CONTROL_PREDICATE_FALSE 0xC3 #define ACPI_CONTROL_PREDICATE_TRUE 0xC4 #define ACPI_STATE_COMMON \ void *Next; \ UINT8 DescriptorType; /* To differentiate various internal objs */\ UINT8 Flags; \ UINT16 Value; \ UINT16 State; /* There are 2 bytes available here until the next natural alignment boundary */ typedef struct acpi_common_state { ACPI_STATE_COMMON } ACPI_COMMON_STATE; /* * Update state - used to traverse complex objects such as packages */ typedef struct acpi_update_state { ACPI_STATE_COMMON union acpi_operand_object *Object; } ACPI_UPDATE_STATE; /* * Pkg state - used to traverse nested package structures */ typedef struct acpi_pkg_state { ACPI_STATE_COMMON UINT32 Index; union acpi_operand_object *SourceObject; union acpi_operand_object *DestObject; struct acpi_walk_state *WalkState; void *ThisTargetObj; UINT32 NumPackages; } ACPI_PKG_STATE; /* * Control state - one per if/else and while constructs. * Allows nesting of these constructs */ typedef struct acpi_control_state { ACPI_STATE_COMMON UINT16 Opcode; union acpi_parse_object *PredicateOp; UINT8 *AmlPredicateStart; /* Start of if/while predicate */ UINT8 *PackageEnd; /* End of if/while block */ UINT64 LoopTimeout; /* While() loop timeout */ } ACPI_CONTROL_STATE; /* * Scope state - current scope during namespace lookups */ typedef struct acpi_scope_state { ACPI_STATE_COMMON ACPI_NAMESPACE_NODE *Node; } ACPI_SCOPE_STATE; typedef struct acpi_pscope_state { ACPI_STATE_COMMON UINT32 ArgCount; /* Number of fixed arguments */ union acpi_parse_object *Op; /* Current op being parsed */ UINT8 *ArgEnd; /* Current argument end */ UINT8 *PkgEnd; /* Current package end */ UINT32 ArgList; /* Next argument to parse */ } ACPI_PSCOPE_STATE; /* * Thread state - one per thread across multiple walk states. Multiple walk * states are created when there are nested control methods executing. */ typedef struct acpi_thread_state { ACPI_STATE_COMMON UINT8 CurrentSyncLevel; /* Mutex Sync (nested acquire) level */ struct acpi_walk_state *WalkStateList; /* Head of list of WalkStates for this thread */ union acpi_operand_object *AcquiredMutexList; /* List of all currently acquired mutexes */ ACPI_THREAD_ID ThreadId; /* Running thread ID */ } ACPI_THREAD_STATE; /* * Result values - used to accumulate the results of nested * AML arguments */ typedef struct acpi_result_values { ACPI_STATE_COMMON union acpi_operand_object *ObjDesc [ACPI_RESULTS_FRAME_OBJ_NUM]; } ACPI_RESULT_VALUES; typedef ACPI_STATUS (*ACPI_PARSE_DOWNWARDS) ( struct acpi_walk_state *WalkState, union acpi_parse_object **OutOp); typedef ACPI_STATUS (*ACPI_PARSE_UPWARDS) ( struct acpi_walk_state *WalkState); /* Global handlers for AML Notifies */ typedef struct acpi_global_notify_handler { ACPI_NOTIFY_HANDLER Handler; void *Context; } ACPI_GLOBAL_NOTIFY_HANDLER; /* * Notify info - used to pass info to the deferred notify * handler/dispatcher. */ typedef struct acpi_notify_info { ACPI_STATE_COMMON UINT8 HandlerListId; ACPI_NAMESPACE_NODE *Node; union acpi_operand_object *HandlerListHead; ACPI_GLOBAL_NOTIFY_HANDLER *Global; } ACPI_NOTIFY_INFO; /* Generic state is union of structs above */ typedef union acpi_generic_state { ACPI_COMMON_STATE Common; ACPI_CONTROL_STATE Control; ACPI_UPDATE_STATE Update; ACPI_SCOPE_STATE Scope; ACPI_PSCOPE_STATE ParseScope; ACPI_PKG_STATE Pkg; ACPI_THREAD_STATE Thread; ACPI_RESULT_VALUES Results; ACPI_NOTIFY_INFO Notify; } ACPI_GENERIC_STATE; /***************************************************************************** * * Interpreter typedefs and structs * ****************************************************************************/ typedef ACPI_STATUS (*ACPI_EXECUTE_OP) ( struct acpi_walk_state *WalkState); /* Address Range info block */ typedef struct acpi_address_range { struct acpi_address_range *Next; ACPI_NAMESPACE_NODE *RegionNode; ACPI_PHYSICAL_ADDRESS StartAddress; ACPI_PHYSICAL_ADDRESS EndAddress; } ACPI_ADDRESS_RANGE; /***************************************************************************** * * Parser typedefs and structs * ****************************************************************************/ /* * AML opcode, name, and argument layout */ typedef struct acpi_opcode_info { #if defined(ACPI_DISASSEMBLER) || defined(ACPI_DEBUG_OUTPUT) char *Name; /* Opcode name (disassembler/debug only) */ #endif UINT32 ParseArgs; /* Grammar/Parse time arguments */ UINT32 RuntimeArgs; /* Interpret time arguments */ UINT16 Flags; /* Misc flags */ UINT8 ObjectType; /* Corresponding internal object type */ UINT8 Class; /* Opcode class */ UINT8 Type; /* Opcode type */ } ACPI_OPCODE_INFO; /* Structure for Resource Tag information */ typedef struct acpi_tag_info { UINT32 BitOffset; UINT32 BitLength; } ACPI_TAG_INFO; /* Value associated with the parse object */ typedef union acpi_parse_value { UINT64 Integer; /* Integer constant (Up to 64 bits) */ UINT32 Size; /* bytelist or field size */ char *String; /* NULL terminated string */ UINT8 *Buffer; /* buffer or string */ char *Name; /* NULL terminated string */ union acpi_parse_object *Arg; /* arguments and contained ops */ ACPI_TAG_INFO Tag; /* Resource descriptor tag info */ } ACPI_PARSE_VALUE; #if defined(ACPI_DISASSEMBLER) || defined(ACPI_DEBUG_OUTPUT) #define ACPI_DISASM_ONLY_MEMBERS(a) a; #else #define ACPI_DISASM_ONLY_MEMBERS(a) #endif #if defined(ACPI_ASL_COMPILER) #define ACPI_CONVERTER_ONLY_MEMBERS(a) a; #else #define ACPI_CONVERTER_ONLY_MEMBERS(a) #endif #define ACPI_PARSE_COMMON \ union acpi_parse_object *Parent; /* Parent op */\ UINT8 DescriptorType; /* To differentiate various internal objs */\ UINT8 Flags; /* Type of Op */\ UINT16 AmlOpcode; /* AML opcode */\ UINT8 *Aml; /* Address of declaration in AML */\ union acpi_parse_object *Next; /* Next op */\ ACPI_NAMESPACE_NODE *Node; /* For use by interpreter */\ ACPI_PARSE_VALUE Value; /* Value or args associated with the opcode */\ UINT8 ArgListLength; /* Number of elements in the arg list */\ ACPI_DISASM_ONLY_MEMBERS (\ UINT16 DisasmFlags; /* Used during AML disassembly */\ UINT8 DisasmOpcode; /* Subtype used for disassembly */\ char *OperatorSymbol; /* Used for C-style operator name strings */\ char AmlOpName[16]) /* Op name (debug only) */\ ACPI_CONVERTER_ONLY_MEMBERS (\ char *InlineComment; /* Inline comment */\ char *EndNodeComment; /* End of node comment */\ char *NameComment; /* Comment associated with the first parameter of the name node */\ char *CloseBraceComment; /* Comments that come after } on the same as } */\ ACPI_COMMENT_NODE *CommentList; /* comments that appears before this node */\ ACPI_COMMENT_NODE *EndBlkComment; /* comments that at the end of a block but before ) or } */\ char *CvFilename; /* Filename associated with this node. Used for ASL/ASL+ converter */\ char *CvParentFilename) /* Parent filename associated with this node. Used for ASL/ASL+ converter */ /* categories of comments */ typedef enum { STANDARD_COMMENT = 1, INLINE_COMMENT, ENDNODE_COMMENT, OPENBRACE_COMMENT, CLOSE_BRACE_COMMENT, STD_DEFBLK_COMMENT, END_DEFBLK_COMMENT, FILENAME_COMMENT, PARENTFILENAME_COMMENT, ENDBLK_COMMENT, INCLUDE_COMMENT } ASL_COMMENT_TYPES; /* Internal opcodes for DisasmOpcode field above */ #define ACPI_DASM_BUFFER 0x00 /* Buffer is a simple data buffer */ #define ACPI_DASM_RESOURCE 0x01 /* Buffer is a Resource Descriptor */ #define ACPI_DASM_STRING 0x02 /* Buffer is a ASCII string */ #define ACPI_DASM_UNICODE 0x03 /* Buffer is a Unicode string */ #define ACPI_DASM_PLD_METHOD 0x04 /* Buffer is a _PLD method bit-packed buffer */ #define ACPI_DASM_UUID 0x05 /* Buffer is a UUID/GUID */ #define ACPI_DASM_EISAID 0x06 /* Integer is an EISAID */ #define ACPI_DASM_MATCHOP 0x07 /* Parent opcode is a Match() operator */ #define ACPI_DASM_LNOT_PREFIX 0x08 /* Start of a LNotEqual (etc.) pair of opcodes */ #define ACPI_DASM_LNOT_SUFFIX 0x09 /* End of a LNotEqual (etc.) pair of opcodes */ #define ACPI_DASM_HID_STRING 0x0A /* String is a _HID or _CID */ #define ACPI_DASM_IGNORE_SINGLE 0x0B /* Ignore the opcode but not it's children */ #define ACPI_DASM_SWITCH 0x0C /* While is a Switch */ #define ACPI_DASM_SWITCH_PREDICATE 0x0D /* Object is a predicate for a Switch or Case block */ #define ACPI_DASM_CASE 0x0E /* If/Else is a Case in a Switch/Case block */ #define ACPI_DASM_DEFAULT 0x0F /* Else is a Default in a Switch/Case block */ /* * List struct used in the -ca option */ typedef struct acpi_comment_node { char *Comment; struct acpi_comment_node *Next; } ACPI_COMMENT_NODE; typedef struct acpi_comment_addr_node { UINT8 *Addr; struct acpi_comment_addr_node *Next; } ACPI_COMMENT_ADDR_NODE; /* * File node - used for "Include" operator file stack and * dependency tree for the -ca option */ typedef struct acpi_file_node { void *File; char *Filename; char *FileStart; /* Points to AML and indicates when the AML for this particular file starts. */ char *FileEnd; /* Points to AML and indicates when the AML for this particular file ends. */ struct acpi_file_node *Next; struct acpi_file_node *Parent; BOOLEAN IncludeWritten; ACPI_COMMENT_NODE *IncludeComment; } ACPI_FILE_NODE; /* * Generic operation (for example: If, While, Store) */ typedef struct acpi_parse_obj_common { ACPI_PARSE_COMMON } ACPI_PARSE_OBJ_COMMON; /* * Extended Op for named ops (Scope, Method, etc.), deferred ops (Methods and OpRegions), * and bytelists. */ typedef struct acpi_parse_obj_named { ACPI_PARSE_COMMON char *Path; UINT8 *Data; /* AML body or bytelist data */ UINT32 Length; /* AML length */ UINT32 Name; /* 4-byte name or zero if no name */ } ACPI_PARSE_OBJ_NAMED; /* This version is used by the iASL compiler only */ #define ACPI_MAX_PARSEOP_NAME 20 typedef struct acpi_parse_obj_asl { ACPI_PARSE_COMMON union acpi_parse_object *Child; union acpi_parse_object *ParentMethod; char *Filename; BOOLEAN FileChanged; char *ParentFilename; char *ExternalName; char *Namepath; char NameSeg[4]; UINT32 ExtraValue; UINT32 Column; UINT32 LineNumber; UINT32 LogicalLineNumber; UINT32 LogicalByteOffset; UINT32 EndLine; UINT32 EndLogicalLine; UINT32 AcpiBtype; UINT32 AmlLength; UINT32 AmlSubtreeLength; UINT32 FinalAmlLength; UINT32 FinalAmlOffset; UINT32 CompileFlags; UINT16 ParseOpcode; UINT8 AmlOpcodeLength; UINT8 AmlPkgLenBytes; UINT8 Extra; char ParseOpName[ACPI_MAX_PARSEOP_NAME]; } ACPI_PARSE_OBJ_ASL; typedef union acpi_parse_object { ACPI_PARSE_OBJ_COMMON Common; ACPI_PARSE_OBJ_NAMED Named; ACPI_PARSE_OBJ_ASL Asl; } ACPI_PARSE_OBJECT; typedef struct asl_comment_state { UINT8 CommentType; UINT32 SpacesBefore; ACPI_PARSE_OBJECT *LatestParseOp; ACPI_PARSE_OBJECT *ParsingParenBraceNode; BOOLEAN CaptureComments; } ASL_COMMENT_STATE; /* * Parse state - one state per parser invocation and each control * method. */ typedef struct acpi_parse_state { UINT8 *AmlStart; /* First AML byte */ UINT8 *Aml; /* Next AML byte */ UINT8 *AmlEnd; /* (last + 1) AML byte */ UINT8 *PkgStart; /* Current package begin */ UINT8 *PkgEnd; /* Current package end */ union acpi_parse_object *StartOp; /* Root of parse tree */ struct acpi_namespace_node *StartNode; union acpi_generic_state *Scope; /* Current scope */ union acpi_parse_object *StartScope; UINT32 AmlSize; } ACPI_PARSE_STATE; /* Parse object flags */ #define ACPI_PARSEOP_GENERIC 0x01 #define ACPI_PARSEOP_NAMED_OBJECT 0x02 #define ACPI_PARSEOP_DEFERRED 0x04 #define ACPI_PARSEOP_BYTELIST 0x08 #define ACPI_PARSEOP_IN_STACK 0x10 #define ACPI_PARSEOP_TARGET 0x20 #define ACPI_PARSEOP_IN_CACHE 0x80 /* Parse object DisasmFlags */ #define ACPI_PARSEOP_IGNORE 0x0001 #define ACPI_PARSEOP_PARAMETER_LIST 0x0002 #define ACPI_PARSEOP_EMPTY_TERMLIST 0x0004 #define ACPI_PARSEOP_PREDEFINED_CHECKED 0x0008 #define ACPI_PARSEOP_CLOSING_PAREN 0x0010 #define ACPI_PARSEOP_COMPOUND_ASSIGNMENT 0x0020 #define ACPI_PARSEOP_ASSIGNMENT 0x0040 #define ACPI_PARSEOP_ELSEIF 0x0080 #define ACPI_PARSEOP_LEGACY_ASL_ONLY 0x0100 /***************************************************************************** * * Hardware (ACPI registers) and PNP * ****************************************************************************/ typedef struct acpi_bit_register_info { UINT8 ParentRegister; UINT8 BitPosition; UINT16 AccessBitMask; } ACPI_BIT_REGISTER_INFO; /* * Some ACPI registers have bits that must be ignored -- meaning that they * must be preserved. */ #define ACPI_PM1_STATUS_PRESERVED_BITS 0x0800 /* Bit 11 */ /* Write-only bits must be zeroed by software */ #define ACPI_PM1_CONTROL_WRITEONLY_BITS 0x2004 /* Bits 13, 2 */ /* For control registers, both ignored and reserved bits must be preserved */ /* * For PM1 control, the SCI enable bit (bit 0, SCI_EN) is defined by the * ACPI specification to be a "preserved" bit - "OSPM always preserves this * bit position", section 4.7.3.2.1. However, on some machines the OS must * write a one to this bit after resume for the machine to work properly. * To enable this, we no longer attempt to preserve this bit. No machines * are known to fail if the bit is not preserved. (May 2009) */ #define ACPI_PM1_CONTROL_IGNORED_BITS 0x0200 /* Bit 9 */ #define ACPI_PM1_CONTROL_RESERVED_BITS 0xC1F8 /* Bits 14-15, 3-8 */ #define ACPI_PM1_CONTROL_PRESERVED_BITS \ (ACPI_PM1_CONTROL_IGNORED_BITS | ACPI_PM1_CONTROL_RESERVED_BITS) #define ACPI_PM2_CONTROL_PRESERVED_BITS 0xFFFFFFFE /* All except bit 0 */ /* * Register IDs * These are the full ACPI registers */ #define ACPI_REGISTER_PM1_STATUS 0x01 #define ACPI_REGISTER_PM1_ENABLE 0x02 #define ACPI_REGISTER_PM1_CONTROL 0x03 #define ACPI_REGISTER_PM2_CONTROL 0x04 #define ACPI_REGISTER_PM_TIMER 0x05 #define ACPI_REGISTER_PROCESSOR_BLOCK 0x06 #define ACPI_REGISTER_SMI_COMMAND_BLOCK 0x07 /* Masks used to access the BitRegisters */ #define ACPI_BITMASK_TIMER_STATUS 0x0001 #define ACPI_BITMASK_BUS_MASTER_STATUS 0x0010 #define ACPI_BITMASK_GLOBAL_LOCK_STATUS 0x0020 #define ACPI_BITMASK_POWER_BUTTON_STATUS 0x0100 #define ACPI_BITMASK_SLEEP_BUTTON_STATUS 0x0200 #define ACPI_BITMASK_RT_CLOCK_STATUS 0x0400 #define ACPI_BITMASK_PCIEXP_WAKE_STATUS 0x4000 /* ACPI 3.0 */ #define ACPI_BITMASK_WAKE_STATUS 0x8000 #define ACPI_BITMASK_ALL_FIXED_STATUS (\ ACPI_BITMASK_TIMER_STATUS | \ ACPI_BITMASK_BUS_MASTER_STATUS | \ ACPI_BITMASK_GLOBAL_LOCK_STATUS | \ ACPI_BITMASK_POWER_BUTTON_STATUS | \ ACPI_BITMASK_SLEEP_BUTTON_STATUS | \ ACPI_BITMASK_RT_CLOCK_STATUS | \ ACPI_BITMASK_PCIEXP_WAKE_STATUS | \ ACPI_BITMASK_WAKE_STATUS) #define ACPI_BITMASK_TIMER_ENABLE 0x0001 #define ACPI_BITMASK_GLOBAL_LOCK_ENABLE 0x0020 #define ACPI_BITMASK_POWER_BUTTON_ENABLE 0x0100 #define ACPI_BITMASK_SLEEP_BUTTON_ENABLE 0x0200 #define ACPI_BITMASK_RT_CLOCK_ENABLE 0x0400 #define ACPI_BITMASK_PCIEXP_WAKE_DISABLE 0x4000 /* ACPI 3.0 */ #define ACPI_BITMASK_SCI_ENABLE 0x0001 #define ACPI_BITMASK_BUS_MASTER_RLD 0x0002 #define ACPI_BITMASK_GLOBAL_LOCK_RELEASE 0x0004 #define ACPI_BITMASK_SLEEP_TYPE 0x1C00 #define ACPI_BITMASK_SLEEP_ENABLE 0x2000 #define ACPI_BITMASK_ARB_DISABLE 0x0001 /* Raw bit position of each BitRegister */ #define ACPI_BITPOSITION_TIMER_STATUS 0x00 #define ACPI_BITPOSITION_BUS_MASTER_STATUS 0x04 #define ACPI_BITPOSITION_GLOBAL_LOCK_STATUS 0x05 #define ACPI_BITPOSITION_POWER_BUTTON_STATUS 0x08 #define ACPI_BITPOSITION_SLEEP_BUTTON_STATUS 0x09 #define ACPI_BITPOSITION_RT_CLOCK_STATUS 0x0A #define ACPI_BITPOSITION_PCIEXP_WAKE_STATUS 0x0E /* ACPI 3.0 */ #define ACPI_BITPOSITION_WAKE_STATUS 0x0F #define ACPI_BITPOSITION_TIMER_ENABLE 0x00 #define ACPI_BITPOSITION_GLOBAL_LOCK_ENABLE 0x05 #define ACPI_BITPOSITION_POWER_BUTTON_ENABLE 0x08 #define ACPI_BITPOSITION_SLEEP_BUTTON_ENABLE 0x09 #define ACPI_BITPOSITION_RT_CLOCK_ENABLE 0x0A #define ACPI_BITPOSITION_PCIEXP_WAKE_DISABLE 0x0E /* ACPI 3.0 */ #define ACPI_BITPOSITION_SCI_ENABLE 0x00 #define ACPI_BITPOSITION_BUS_MASTER_RLD 0x01 #define ACPI_BITPOSITION_GLOBAL_LOCK_RELEASE 0x02 #define ACPI_BITPOSITION_SLEEP_TYPE 0x0A #define ACPI_BITPOSITION_SLEEP_ENABLE 0x0D #define ACPI_BITPOSITION_ARB_DISABLE 0x00 /* Structs and definitions for _OSI support and I/O port validation */ #define ACPI_ALWAYS_ILLEGAL 0x00 typedef struct acpi_interface_info { char *Name; struct acpi_interface_info *Next; UINT8 Flags; UINT8 Value; } ACPI_INTERFACE_INFO; #define ACPI_OSI_INVALID 0x01 #define ACPI_OSI_DYNAMIC 0x02 #define ACPI_OSI_FEATURE 0x04 #define ACPI_OSI_DEFAULT_INVALID 0x08 #define ACPI_OSI_OPTIONAL_FEATURE (ACPI_OSI_FEATURE | ACPI_OSI_DEFAULT_INVALID | ACPI_OSI_INVALID) typedef struct acpi_port_info { char *Name; UINT16 Start; UINT16 End; UINT8 OsiDependency; } ACPI_PORT_INFO; /***************************************************************************** * * Resource descriptors * ****************************************************************************/ /* ResourceType values */ #define ACPI_ADDRESS_TYPE_MEMORY_RANGE 0 #define ACPI_ADDRESS_TYPE_IO_RANGE 1 #define ACPI_ADDRESS_TYPE_BUS_NUMBER_RANGE 2 /* Resource descriptor types and masks */ #define ACPI_RESOURCE_NAME_LARGE 0x80 #define ACPI_RESOURCE_NAME_SMALL 0x00 #define ACPI_RESOURCE_NAME_SMALL_MASK 0x78 /* Bits 6:3 contain the type */ #define ACPI_RESOURCE_NAME_SMALL_LENGTH_MASK 0x07 /* Bits 2:0 contain the length */ #define ACPI_RESOURCE_NAME_LARGE_MASK 0x7F /* Bits 6:0 contain the type */ /* * Small resource descriptor "names" as defined by the ACPI specification. * Note: Bits 2:0 are used for the descriptor length */ #define ACPI_RESOURCE_NAME_IRQ 0x20 #define ACPI_RESOURCE_NAME_DMA 0x28 #define ACPI_RESOURCE_NAME_START_DEPENDENT 0x30 #define ACPI_RESOURCE_NAME_END_DEPENDENT 0x38 #define ACPI_RESOURCE_NAME_IO 0x40 #define ACPI_RESOURCE_NAME_FIXED_IO 0x48 #define ACPI_RESOURCE_NAME_FIXED_DMA 0x50 #define ACPI_RESOURCE_NAME_RESERVED_S2 0x58 #define ACPI_RESOURCE_NAME_RESERVED_S3 0x60 #define ACPI_RESOURCE_NAME_RESERVED_S4 0x68 #define ACPI_RESOURCE_NAME_VENDOR_SMALL 0x70 #define ACPI_RESOURCE_NAME_END_TAG 0x78 /* * Large resource descriptor "names" as defined by the ACPI specification. * Note: includes the Large Descriptor bit in bit[7] */ #define ACPI_RESOURCE_NAME_MEMORY24 0x81 #define ACPI_RESOURCE_NAME_GENERIC_REGISTER 0x82 #define ACPI_RESOURCE_NAME_RESERVED_L1 0x83 #define ACPI_RESOURCE_NAME_VENDOR_LARGE 0x84 #define ACPI_RESOURCE_NAME_MEMORY32 0x85 #define ACPI_RESOURCE_NAME_FIXED_MEMORY32 0x86 #define ACPI_RESOURCE_NAME_ADDRESS32 0x87 #define ACPI_RESOURCE_NAME_ADDRESS16 0x88 #define ACPI_RESOURCE_NAME_EXTENDED_IRQ 0x89 #define ACPI_RESOURCE_NAME_ADDRESS64 0x8A #define ACPI_RESOURCE_NAME_EXTENDED_ADDRESS64 0x8B #define ACPI_RESOURCE_NAME_GPIO 0x8C #define ACPI_RESOURCE_NAME_PIN_FUNCTION 0x8D #define ACPI_RESOURCE_NAME_SERIAL_BUS 0x8E #define ACPI_RESOURCE_NAME_PIN_CONFIG 0x8F #define ACPI_RESOURCE_NAME_PIN_GROUP 0x90 #define ACPI_RESOURCE_NAME_PIN_GROUP_FUNCTION 0x91 #define ACPI_RESOURCE_NAME_PIN_GROUP_CONFIG 0x92 #define ACPI_RESOURCE_NAME_LARGE_MAX 0x92 /***************************************************************************** * * Miscellaneous * ****************************************************************************/ #define ACPI_ASCII_ZERO 0x30 /***************************************************************************** * * Disassembler * ****************************************************************************/ typedef struct acpi_external_list { char *Path; char *InternalPath; struct acpi_external_list *Next; UINT32 Value; UINT16 Length; UINT16 Flags; UINT8 Type; } ACPI_EXTERNAL_LIST; /* Values for Flags field above */ #define ACPI_EXT_RESOLVED_REFERENCE 0x01 /* Object was resolved during cross ref */ #define ACPI_EXT_ORIGIN_FROM_FILE 0x02 /* External came from a file */ #define ACPI_EXT_INTERNAL_PATH_ALLOCATED 0x04 /* Deallocate internal path on completion */ #define ACPI_EXT_EXTERNAL_EMITTED 0x08 /* External() statement has been emitted */ #define ACPI_EXT_ORIGIN_FROM_OPCODE 0x10 /* External came from a External() opcode */ #define ACPI_EXT_CONFLICTING_DECLARATION 0x20 /* External has a conflicting declaration within AML */ typedef struct acpi_external_file { char *Path; struct acpi_external_file *Next; } ACPI_EXTERNAL_FILE; typedef struct acpi_parse_object_list { ACPI_PARSE_OBJECT *Op; struct acpi_parse_object_list *Next; } ACPI_PARSE_OBJECT_LIST; /***************************************************************************** * * Debugger * ****************************************************************************/ typedef struct acpi_db_method_info { ACPI_HANDLE Method; ACPI_HANDLE MainThreadGate; ACPI_HANDLE ThreadCompleteGate; ACPI_HANDLE InfoGate; ACPI_THREAD_ID *Threads; UINT32 NumThreads; UINT32 NumCreated; UINT32 NumCompleted; char *Name; UINT32 Flags; UINT32 NumLoops; char Pathname[ACPI_DB_LINE_BUFFER_SIZE]; char **Args; ACPI_OBJECT_TYPE *Types; /* * Arguments to be passed to method for the commands Threads and * Background. Note, ACPI specifies a maximum of 7 arguments (0 - 6). * * For the Threads command, the Number of threads, ID of current * thread and Index of current thread inside all them created. */ char InitArgs; #ifdef ACPI_DEBUGGER ACPI_OBJECT_TYPE ArgTypes[ACPI_METHOD_NUM_ARGS]; #endif char *Arguments[ACPI_METHOD_NUM_ARGS]; char NumThreadsStr[11]; char IdOfThreadStr[11]; char IndexOfThreadStr[11]; } ACPI_DB_METHOD_INFO; typedef struct acpi_integrity_info { UINT32 Nodes; UINT32 Objects; } ACPI_INTEGRITY_INFO; #define ACPI_DB_DISABLE_OUTPUT 0x00 #define ACPI_DB_REDIRECTABLE_OUTPUT 0x01 #define ACPI_DB_CONSOLE_OUTPUT 0x02 #define ACPI_DB_DUPLICATE_OUTPUT 0x03 typedef struct acpi_object_info { UINT32 Types[ACPI_TOTAL_TYPES]; } ACPI_OBJECT_INFO; /***************************************************************************** * * Debug * ****************************************************************************/ /* Entry for a memory allocation (debug only) */ #define ACPI_MEM_MALLOC 0 #define ACPI_MEM_CALLOC 1 #define ACPI_MAX_MODULE_NAME 16 #define ACPI_COMMON_DEBUG_MEM_HEADER \ struct acpi_debug_mem_block *Previous; \ struct acpi_debug_mem_block *Next; \ UINT32 Size; \ UINT32 Component; \ UINT32 Line; \ char Module[ACPI_MAX_MODULE_NAME]; \ UINT8 AllocType; typedef struct acpi_debug_mem_header { ACPI_COMMON_DEBUG_MEM_HEADER } ACPI_DEBUG_MEM_HEADER; typedef struct acpi_debug_mem_block { ACPI_COMMON_DEBUG_MEM_HEADER UINT64 UserSpace; } ACPI_DEBUG_MEM_BLOCK; #define ACPI_MEM_LIST_GLOBAL 0 #define ACPI_MEM_LIST_NSNODE 1 #define ACPI_MEM_LIST_MAX 1 #define ACPI_NUM_MEM_LISTS 2 /***************************************************************************** * * Info/help support * ****************************************************************************/ typedef struct ah_predefined_name { char *Name; char *Description; #ifndef ACPI_ASL_COMPILER char *Action; #endif } AH_PREDEFINED_NAME; typedef struct ah_device_id { char *Name; char *Description; } AH_DEVICE_ID; typedef struct ah_uuid { char *Description; char *String; } AH_UUID; typedef struct ah_table { char *Signature; char *Description; } AH_TABLE; #endif /* __ACLOCAL_H__ */ <file_sep>/****************************************************************************** * * Module Name: nsrepair - Repair for objects returned by predefined methods * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acinterp.h" #include "acpredef.h" #include "amlresrc.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsrepair") /******************************************************************************* * * This module attempts to repair or convert objects returned by the * predefined methods to an object type that is expected, as per the ACPI * specification. The need for this code is dictated by the many machines that * return incorrect types for the standard predefined methods. Performing these * conversions here, in one place, eliminates the need for individual ACPI * device drivers to do the same. Note: Most of these conversions are different * than the internal object conversion routines used for implicit object * conversion. * * The following conversions can be performed as necessary: * * Integer -> String * Integer -> Buffer * String -> Integer * String -> Buffer * Buffer -> Integer * Buffer -> String * Buffer -> Package of Integers * Package -> Package of one Package * * Additional conversions that are available: * Convert a null return or zero return value to an EndTag descriptor * Convert an ASCII string to a Unicode buffer * * An incorrect standalone object is wrapped with required outer package * * Additional possible repairs: * Required package elements that are NULL replaced by Integer/String/Buffer * ******************************************************************************/ /* Local prototypes */ static const ACPI_SIMPLE_REPAIR_INFO * AcpiNsMatchSimpleRepair ( ACPI_NAMESPACE_NODE *Node, UINT32 ReturnBtype, UINT32 PackageIndex); /* * Special but simple repairs for some names. * * 2nd argument: Unexpected types that can be repaired */ static const ACPI_SIMPLE_REPAIR_INFO AcpiObjectRepairInfo[] = { /* Resource descriptor conversions */ { "_CRS", ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_BUFFER | ACPI_RTYPE_NONE, ACPI_NOT_PACKAGE_ELEMENT, AcpiNsConvertToResource }, { "_DMA", ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_BUFFER | ACPI_RTYPE_NONE, ACPI_NOT_PACKAGE_ELEMENT, AcpiNsConvertToResource }, { "_PRS", ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_BUFFER | ACPI_RTYPE_NONE, ACPI_NOT_PACKAGE_ELEMENT, AcpiNsConvertToResource }, /* Object reference conversions */ { "_DEP", ACPI_RTYPE_STRING, ACPI_ALL_PACKAGE_ELEMENTS, AcpiNsConvertToReference }, /* Unicode conversions */ { "_MLS", ACPI_RTYPE_STRING, 1, AcpiNsConvertToUnicode }, { "_STR", ACPI_RTYPE_STRING | ACPI_RTYPE_BUFFER, ACPI_NOT_PACKAGE_ELEMENT, AcpiNsConvertToUnicode }, { {0,0,0,0}, 0, 0, NULL } /* Table terminator */ }; /******************************************************************************* * * FUNCTION: AcpiNsSimpleRepair * * PARAMETERS: Info - Method execution information block * ExpectedBtypes - Object types expected * PackageIndex - Index of object within parent package (if * applicable - ACPI_NOT_PACKAGE_ELEMENT * otherwise) * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if repair was successful. * * DESCRIPTION: Attempt to repair/convert a return object of a type that was * not expected. * ******************************************************************************/ ACPI_STATUS AcpiNsSimpleRepair ( ACPI_EVALUATE_INFO *Info, UINT32 ExpectedBtypes, UINT32 PackageIndex, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT *NewObject = NULL; ACPI_STATUS Status; const ACPI_SIMPLE_REPAIR_INFO *Predefined; ACPI_FUNCTION_NAME (NsSimpleRepair); /* * Special repairs for certain names that are in the repair table. * Check if this name is in the list of repairable names. */ Predefined = AcpiNsMatchSimpleRepair (Info->Node, Info->ReturnBtype, PackageIndex); if (Predefined) { if (!ReturnObject) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS, "Missing expected return value")); } Status = Predefined->ObjectConverter (Info->Node, ReturnObject, &NewObject); if (ACPI_FAILURE (Status)) { /* A fatal error occurred during a conversion */ ACPI_EXCEPTION ((AE_INFO, Status, "During return object analysis")); return (Status); } if (NewObject) { goto ObjectRepaired; } } /* * Do not perform simple object repair unless the return type is not * expected. */ if (Info->ReturnBtype & ExpectedBtypes) { return (AE_OK); } /* * At this point, we know that the type of the returned object was not * one of the expected types for this predefined name. Attempt to * repair the object by converting it to one of the expected object * types for this predefined name. */ /* * If there is no return value, check if we require a return value for * this predefined name. Either one return value is expected, or none, * for both methods and other objects. * * Try to fix if there was no return object. Warning if failed to fix. */ if (!ReturnObject) { if (ExpectedBtypes && (!(ExpectedBtypes & ACPI_RTYPE_NONE))) { if (PackageIndex != ACPI_NOT_PACKAGE_ELEMENT) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS, "Found unexpected NULL package element")); Status = AcpiNsRepairNullElement (Info, ExpectedBtypes, PackageIndex, ReturnObjectPtr); if (ACPI_SUCCESS (Status)) { return (AE_OK); /* Repair was successful */ } } else { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS, "Missing expected return value")); } return (AE_AML_NO_RETURN_VALUE); } } if (ExpectedBtypes & ACPI_RTYPE_INTEGER) { Status = AcpiNsConvertToInteger (ReturnObject, &NewObject); if (ACPI_SUCCESS (Status)) { goto ObjectRepaired; } } if (ExpectedBtypes & ACPI_RTYPE_STRING) { Status = AcpiNsConvertToString (ReturnObject, &NewObject); if (ACPI_SUCCESS (Status)) { goto ObjectRepaired; } } if (ExpectedBtypes & ACPI_RTYPE_BUFFER) { Status = AcpiNsConvertToBuffer (ReturnObject, &NewObject); if (ACPI_SUCCESS (Status)) { goto ObjectRepaired; } } if (ExpectedBtypes & ACPI_RTYPE_PACKAGE) { /* * A package is expected. We will wrap the existing object with a * new package object. It is often the case that if a variable-length * package is required, but there is only a single object needed, the * BIOS will return that object instead of wrapping it with a Package * object. Note: after the wrapping, the package will be validated * for correct contents (expected object type or types). */ Status = AcpiNsWrapWithPackage (Info, ReturnObject, &NewObject); if (ACPI_SUCCESS (Status)) { /* * The original object just had its reference count * incremented for being inserted into the new package. */ *ReturnObjectPtr = NewObject; /* New Package object */ Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; return (AE_OK); } } /* We cannot repair this object */ return (AE_AML_OPERAND_TYPE); ObjectRepaired: /* Object was successfully repaired */ if (PackageIndex != ACPI_NOT_PACKAGE_ELEMENT) { /* Update reference count of new object */ if (!(Info->ReturnFlags & ACPI_OBJECT_WRAPPED)) { NewObject->Common.ReferenceCount = ReturnObject->Common.ReferenceCount; } ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Converted %s to expected %s at Package index %u\n", Info->FullPathname, AcpiUtGetObjectTypeName (ReturnObject), AcpiUtGetObjectTypeName (NewObject), PackageIndex)); } else { ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Converted %s to expected %s\n", Info->FullPathname, AcpiUtGetObjectTypeName (ReturnObject), AcpiUtGetObjectTypeName (NewObject))); } /* Delete old object, install the new return object */ AcpiUtRemoveReference (ReturnObject); *ReturnObjectPtr = NewObject; Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsMatchSimpleRepair * * PARAMETERS: Node - Namespace node for the method/object * ReturnBtype - Object type that was returned * PackageIndex - Index of object within parent package (if * applicable - ACPI_NOT_PACKAGE_ELEMENT * otherwise) * * RETURN: Pointer to entry in repair table. NULL indicates not found. * * DESCRIPTION: Check an object name against the repairable object list. * *****************************************************************************/ static const ACPI_SIMPLE_REPAIR_INFO * AcpiNsMatchSimpleRepair ( ACPI_NAMESPACE_NODE *Node, UINT32 ReturnBtype, UINT32 PackageIndex) { const ACPI_SIMPLE_REPAIR_INFO *ThisName; /* Search info table for a repairable predefined method/object name */ ThisName = AcpiObjectRepairInfo; while (ThisName->ObjectConverter) { if (ACPI_COMPARE_NAMESEG (Node->Name.Ascii, ThisName->Name)) { /* Check if we can actually repair this name/type combination */ if ((ReturnBtype & ThisName->UnexpectedBtypes) && (ThisName->PackageIndex == ACPI_ALL_PACKAGE_ELEMENTS || PackageIndex == ThisName->PackageIndex)) { return (ThisName); } return (NULL); } ThisName++; } return (NULL); /* Name was not found in the repair table */ } /******************************************************************************* * * FUNCTION: AcpiNsRepairNullElement * * PARAMETERS: Info - Method execution information block * ExpectedBtypes - Object types expected * PackageIndex - Index of object within parent package (if * applicable - ACPI_NOT_PACKAGE_ELEMENT * otherwise) * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status. AE_OK if repair was successful. * * DESCRIPTION: Attempt to repair a NULL element of a returned Package object. * ******************************************************************************/ ACPI_STATUS AcpiNsRepairNullElement ( ACPI_EVALUATE_INFO *Info, UINT32 ExpectedBtypes, UINT32 PackageIndex, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_OPERAND_OBJECT *NewObject; ACPI_FUNCTION_NAME (NsRepairNullElement); /* No repair needed if return object is non-NULL */ if (ReturnObject) { return (AE_OK); } /* * Attempt to repair a NULL element of a Package object. This applies to * predefined names that return a fixed-length package and each element * is required. It does not apply to variable-length packages where NULL * elements are allowed, especially at the end of the package. */ if (ExpectedBtypes & ACPI_RTYPE_INTEGER) { /* Need an Integer - create a zero-value integer */ NewObject = AcpiUtCreateIntegerObject ((UINT64) 0); } else if (ExpectedBtypes & ACPI_RTYPE_STRING) { /* Need a String - create a NULL string */ NewObject = AcpiUtCreateStringObject (0); } else if (ExpectedBtypes & ACPI_RTYPE_BUFFER) { /* Need a Buffer - create a zero-length buffer */ NewObject = AcpiUtCreateBufferObject (0); } else { /* Error for all other expected types */ return (AE_AML_OPERAND_TYPE); } if (!NewObject) { return (AE_NO_MEMORY); } /* Set the reference count according to the parent Package object */ NewObject->Common.ReferenceCount = Info->ParentPackage->Common.ReferenceCount; ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Converted NULL package element to expected %s at index %u\n", Info->FullPathname, AcpiUtGetObjectTypeName (NewObject), PackageIndex)); *ReturnObjectPtr = NewObject; Info->ReturnFlags |= ACPI_OBJECT_REPAIRED; return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiNsRemoveNullElements * * PARAMETERS: Info - Method execution information block * PackageType - An AcpiReturnPackageTypes value * ObjDesc - A Package object * * RETURN: None. * * DESCRIPTION: Remove all NULL package elements from packages that contain * a variable number of subpackages. For these types of * packages, NULL elements can be safely removed. * *****************************************************************************/ void AcpiNsRemoveNullElements ( ACPI_EVALUATE_INFO *Info, UINT8 PackageType, ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_OPERAND_OBJECT **Source; ACPI_OPERAND_OBJECT **Dest; UINT32 Count; UINT32 NewCount; UINT32 i; ACPI_FUNCTION_NAME (NsRemoveNullElements); /* * We can safely remove all NULL elements from these package types: * PTYPE1_VAR packages contain a variable number of simple data types. * PTYPE2 packages contain a variable number of subpackages. */ switch (PackageType) { case ACPI_PTYPE1_VAR: case ACPI_PTYPE2: case ACPI_PTYPE2_COUNT: case ACPI_PTYPE2_PKG_COUNT: case ACPI_PTYPE2_FIXED: case ACPI_PTYPE2_MIN: case ACPI_PTYPE2_REV_FIXED: case ACPI_PTYPE2_FIX_VAR: break; default: case ACPI_PTYPE2_VAR_VAR: case ACPI_PTYPE1_FIXED: case ACPI_PTYPE1_OPTION: return; } Count = ObjDesc->Package.Count; NewCount = Count; Source = ObjDesc->Package.Elements; Dest = Source; /* Examine all elements of the package object, remove nulls */ for (i = 0; i < Count; i++) { if (!*Source) { NewCount--; } else { *Dest = *Source; Dest++; } Source++; } /* Update parent package if any null elements were removed */ if (NewCount < Count) { ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Found and removed %u NULL elements\n", Info->FullPathname, (Count - NewCount))); /* NULL terminate list and update the package count */ *Dest = NULL; ObjDesc->Package.Count = NewCount; } } /******************************************************************************* * * FUNCTION: AcpiNsWrapWithPackage * * PARAMETERS: Info - Method execution information block * OriginalObject - Pointer to the object to repair. * ObjDescPtr - The new package object is returned here * * RETURN: Status, new object in *ObjDescPtr * * DESCRIPTION: Repair a common problem with objects that are defined to * return a variable-length Package of sub-objects. If there is * only one sub-object, some BIOS code mistakenly simply declares * the single object instead of a Package with one sub-object. * This function attempts to repair this error by wrapping a * Package object around the original object, creating the * correct and expected Package with one sub-object. * * Names that can be repaired in this manner include: * _ALR, _CSD, _HPX, _MLS, _PLD, _PRT, _PSS, _TRT, _TSS, * _BCL, _DOD, _FIX, _Sx * ******************************************************************************/ ACPI_STATUS AcpiNsWrapWithPackage ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT *OriginalObject, ACPI_OPERAND_OBJECT **ObjDescPtr) { ACPI_OPERAND_OBJECT *PkgObjDesc; ACPI_FUNCTION_NAME (NsWrapWithPackage); /* * Create the new outer package and populate it. The new * package will have a single element, the lone sub-object. */ PkgObjDesc = AcpiUtCreatePackageObject (1); if (!PkgObjDesc) { return (AE_NO_MEMORY); } PkgObjDesc->Package.Elements[0] = OriginalObject; ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR, "%s: Wrapped %s with expected Package object\n", Info->FullPathname, AcpiUtGetObjectTypeName (OriginalObject))); /* Return the new object in the object pointer */ *ObjDescPtr = PkgObjDesc; Info->ReturnFlags |= ACPI_OBJECT_REPAIRED | ACPI_OBJECT_WRAPPED; return (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included /* * The only purpose of this file is to keep kmalloc.c shorter. * Yes, this file could be turned into a regular C source file, but at the * price of making several static functions and variables in kmalloc.c to be * just non-static. We don't want that. Code isolation is a GOOD thing. */ #endif void kmalloc_create_accelerator(struct kmalloc_acc *a, u32 elem_size, u32 elem_c) { /* The both elem_size and elem_count must be a power of 2 */ ASSERT(roundup_next_power_of_2(elem_size) == elem_size); ASSERT(roundup_next_power_of_2(elem_c) == elem_c); ASSERT(elem_size <= KMALLOC_FL_SUB_BLOCK_MIN_SIZE_MASK); if (elem_size <= SMALL_HEAP_MAX_ALLOC) { /* * All the elements must live in a "small heap". The problem with that * is that elem_size * elem_c must be <= SMALL_HEAP_SIZE. Otherwise, * it's possible nor to use bigger heaps (because their MBS (min block * size) is too big), neither to use small heaps because they cannot * contain `elem_c` elements of size `elem_size`. * * Fix: just reduce the value of `elem_c`. */ ASSERT(elem_size * elem_c <= (SMALL_HEAP_SIZE - SMALL_HEAP_MD_SIZE)); } *a = (struct kmalloc_acc) { .elem_size = elem_size, .elem_count = elem_c, .curr_elem = elem_c, .buf = NULL, }; } void * kmalloc_accelerator_get_elem(struct kmalloc_acc *a) { size_t actual_size; if (a->curr_elem == a->elem_count) { actual_size = a->elem_size * a->elem_count; a->buf = general_kmalloc(&actual_size, /* size (in/out) */ a->elem_size); /* sub_blocks_min_size */ ASSERT(actual_size == a->elem_size * a->elem_count); if (!a->buf) return NULL; a->curr_elem = 0; } return a->buf + (a->elem_size * a->curr_elem++); } void kmalloc_destroy_accelerator(struct kmalloc_acc *a) { size_t actual_size; for (; a->curr_elem < a->elem_count; a->curr_elem++) { actual_size = a->elem_size; general_kfree(a->buf + (a->curr_elem * a->elem_size), /* ptr */ &actual_size, /* size (in/out) */ KFREE_FL_ALLOW_SPLIT); ASSERT(actual_size == a->elem_size); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/paging.h> #define PG_PRESENT_BIT_POS 0u #define PG_RW_BIT_POS 1u #define PG_US_BIT_POS 2u #define PG_WT_BIT_POS 3u #define PG_CD_BIT_POS 4u #define PG_ACC_BIT_POS 5u #define PG_DIRTY_BIT_POS 6u // page_t only #define PG_PAGE_PAT_BIT_POS 7u // page_t only #define PG_4MB_BIT_POS 7u // page_dir_entry_t only #define PG_GLOBAL_BIT_POS 8u // page_t only #define PG_CUSTOM_B0_POS 9u #define PG_CUSTOM_B1_POS 10u #define PG_CUSTOM_B2_POS 11u #define PG_4MB_PAT_BIT_POS 12u // page_dir_entry_t only with psize = 1 #define PG_PRESENT_BIT (1u << PG_PRESENT_BIT_POS) #define PG_RW_BIT (1u << PG_RW_BIT_POS) #define PG_US_BIT (1u << PG_US_BIT_POS) #define PG_WT_BIT (1u << PG_WT_BIT_POS) #define PG_CD_BIT (1u << PG_CD_BIT_POS) #define PG_ACC_BIT (1u << PG_ACC_BIT_POS) #define PG_DIRTY_BIT (1u << PG_DIRTY_BIT_POS) // page_t only #define PG_PAGE_PAT_BIT (1u << PG_PAGE_PAT_BIT_POS) // page_t only #define PG_4MB_BIT (1u << PG_4MB_BIT_POS) // page_dir_entry_t only #define PG_GLOBAL_BIT (1u << PG_GLOBAL_BIT_POS) // page_t only #define PG_CUSTOM_B0 (1u << PG_CUSTOM_B0_POS) #define PG_CUSTOM_B1 (1u << PG_CUSTOM_B1_POS) #define PG_CUSTOM_B2 (1u << PG_CUSTOM_B2_POS) #define PG_CUSTOM_BITS (PG_CUSTOM_B0 | PG_CUSTOM_B1 | PG_CUSTOM_B2) #define PG_4MB_PAT_BIT (1u << PG_4MB_PAT_BIT_POS) #define PAGE_FAULT_FL_PRESENT (1u << 0) #define PAGE_FAULT_FL_RW (1u << 1) #define PAGE_FAULT_FL_US (1u << 2) #define PAGE_FAULT_FL_COW (PAGE_FAULT_FL_PRESENT | PAGE_FAULT_FL_RW) #define BIG_PAGE_SHIFT 22 #define KERNEL_BASE_PD_IDX (KERNEL_BASE_VA >> BIG_PAGE_SHIFT) // A page table entry union x86_page { struct { u32 present : 1; u32 rw : 1; // read only = 0, read/write = 1 u32 us : 1; // user/supervisor u32 wt : 1; // write-through u32 cd : 1; // cache-disabled u32 accessed : 1; u32 dirty : 1; u32 pat : 1; u32 global : 1; u32 avail : 3; u32 pageAddr : 20; // the first 20 bits of the physical addr. }; u32 raw; }; // A page table struct x86_page_table { union x86_page pages[1024]; }; // A page directory entry union x86_page_dir_entry { struct { u32 present : 1; u32 rw : 1; // read only = 0, read/write = 1 u32 us : 1; // us = 0 -> supervisor only, 1 -> user also u32 wt : 1; // write-through u32 cd : 1; // cache-disabled u32 accessed : 1; u32 zero : 1; u32 psize : 1; // page size; 0 = 4 KB, 1 = 4 MB u32 ignored : 1; u32 avail : 3; u32 ptaddr : 20; // the paddr of 'page_table_t *' }; struct { u32 present : 1; u32 rw : 1; // read only = 0, read/write = 1 u32 us : 1; // us = 0 -> supervisor only, 1 -> user also u32 wt : 1; // write-through u32 cd : 1; // cache-disabled u32 accessed : 1; u32 zero : 1; u32 one : 1; // psize must be = 1 (4 MB) u32 ignored : 1; u32 avail : 3; u32 pat : 1; u32 paddr_zero : 9; u32 paddr : 10; // 4-MB pageframe paddr } big_4mb_page; u32 raw; }; // A page directory struct x86_pdir { union x86_page_dir_entry entries[1024]; }; STATIC_ASSERT(sizeof(struct x86_pdir) == PAGE_DIR_SIZE); void map_4mb_page_int(pdir_t *pdir, void *vaddr, ulong paddr, u32 flags); <file_sep>/******************************************************************************* * * Module Name: rsutils - Utilities for the resource manager * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acresrc.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME ("rsutils") /******************************************************************************* * * FUNCTION: AcpiRsDecodeBitmask * * PARAMETERS: Mask - Bitmask to decode * List - Where the converted list is returned * * RETURN: Count of bits set (length of list) * * DESCRIPTION: Convert a bit mask into a list of values * ******************************************************************************/ UINT8 AcpiRsDecodeBitmask ( UINT16 Mask, UINT8 *List) { UINT8 i; UINT8 BitCount; ACPI_FUNCTION_ENTRY (); /* Decode the mask bits */ for (i = 0, BitCount = 0; Mask; i++) { if (Mask & 0x0001) { List[BitCount] = i; BitCount++; } Mask >>= 1; } return (BitCount); } /******************************************************************************* * * FUNCTION: AcpiRsEncodeBitmask * * PARAMETERS: List - List of values to encode * Count - Length of list * * RETURN: Encoded bitmask * * DESCRIPTION: Convert a list of values to an encoded bitmask * ******************************************************************************/ UINT16 AcpiRsEncodeBitmask ( UINT8 *List, UINT8 Count) { UINT32 i; UINT16 Mask; ACPI_FUNCTION_ENTRY (); /* Encode the list into a single bitmask */ for (i = 0, Mask = 0; i < Count; i++) { Mask |= (0x1 << List[i]); } return (Mask); } /******************************************************************************* * * FUNCTION: AcpiRsMoveData * * PARAMETERS: Destination - Pointer to the destination descriptor * Source - Pointer to the source descriptor * ItemCount - How many items to move * MoveType - Byte width * * RETURN: None * * DESCRIPTION: Move multiple data items from one descriptor to another. Handles * alignment issues and endian issues if necessary, as configured * via the ACPI_MOVE_* macros. (This is why a memcpy is not used) * ******************************************************************************/ void AcpiRsMoveData ( void *Destination, void *Source, UINT16 ItemCount, UINT8 MoveType) { UINT32 i; ACPI_FUNCTION_ENTRY (); /* One move per item */ for (i = 0; i < ItemCount; i++) { switch (MoveType) { /* * For the 8-bit case, we can perform the move all at once * since there are no alignment or endian issues */ case ACPI_RSC_MOVE8: case ACPI_RSC_MOVE_GPIO_RES: case ACPI_RSC_MOVE_SERIAL_VEN: case ACPI_RSC_MOVE_SERIAL_RES: memcpy (Destination, Source, ItemCount); return; /* * 16-, 32-, and 64-bit cases must use the move macros that perform * endian conversion and/or accommodate hardware that cannot perform * misaligned memory transfers */ case ACPI_RSC_MOVE16: case ACPI_RSC_MOVE_GPIO_PIN: ACPI_MOVE_16_TO_16 ( &ACPI_CAST_PTR (UINT16, Destination)[i], &ACPI_CAST_PTR (UINT16, Source)[i]); break; case ACPI_RSC_MOVE32: ACPI_MOVE_32_TO_32 ( &ACPI_CAST_PTR (UINT32, Destination)[i], &ACPI_CAST_PTR (UINT32, Source)[i]); break; case ACPI_RSC_MOVE64: ACPI_MOVE_64_TO_64 ( &ACPI_CAST_PTR (UINT64, Destination)[i], &ACPI_CAST_PTR (UINT64, Source)[i]); break; default: return; } } } /******************************************************************************* * * FUNCTION: AcpiRsSetResourceLength * * PARAMETERS: TotalLength - Length of the AML descriptor, including * the header and length fields. * Aml - Pointer to the raw AML descriptor * * RETURN: None * * DESCRIPTION: Set the ResourceLength field of an AML * resource descriptor, both Large and Small descriptors are * supported automatically. Note: Descriptor Type field must * be valid. * ******************************************************************************/ void AcpiRsSetResourceLength ( ACPI_RSDESC_SIZE TotalLength, AML_RESOURCE *Aml) { ACPI_RS_LENGTH ResourceLength; ACPI_FUNCTION_ENTRY (); /* Length is the total descriptor length minus the header length */ ResourceLength = (ACPI_RS_LENGTH) (TotalLength - AcpiUtGetResourceHeaderLength (Aml)); /* Length is stored differently for large and small descriptors */ if (Aml->SmallHeader.DescriptorType & ACPI_RESOURCE_NAME_LARGE) { /* Large descriptor -- bytes 1-2 contain the 16-bit length */ ACPI_MOVE_16_TO_16 ( &Aml->LargeHeader.ResourceLength, &ResourceLength); } else { /* * Small descriptor -- bits 2:0 of byte 0 contain the length * Clear any existing length, preserving descriptor type bits */ Aml->SmallHeader.DescriptorType = (UINT8) ((Aml->SmallHeader.DescriptorType & ~ACPI_RESOURCE_NAME_SMALL_LENGTH_MASK) | ResourceLength); } } /******************************************************************************* * * FUNCTION: AcpiRsSetResourceHeader * * PARAMETERS: DescriptorType - Byte to be inserted as the type * TotalLength - Length of the AML descriptor, including * the header and length fields. * Aml - Pointer to the raw AML descriptor * * RETURN: None * * DESCRIPTION: Set the DescriptorType and ResourceLength fields of an AML * resource descriptor, both Large and Small descriptors are * supported automatically * ******************************************************************************/ void AcpiRsSetResourceHeader ( UINT8 DescriptorType, ACPI_RSDESC_SIZE TotalLength, AML_RESOURCE *Aml) { ACPI_FUNCTION_ENTRY (); /* Set the Resource Type */ Aml->SmallHeader.DescriptorType = DescriptorType; /* Set the Resource Length */ AcpiRsSetResourceLength (TotalLength, Aml); } /******************************************************************************* * * FUNCTION: AcpiRsStrcpy * * PARAMETERS: Destination - Pointer to the destination string * Source - Pointer to the source string * * RETURN: String length, including NULL terminator * * DESCRIPTION: Local string copy that returns the string length, saving a * strcpy followed by a strlen. * ******************************************************************************/ static UINT16 AcpiRsStrcpy ( char *Destination, char *Source) { UINT16 i; ACPI_FUNCTION_ENTRY (); for (i = 0; Source[i]; i++) { Destination[i] = Source[i]; } Destination[i] = 0; /* Return string length including the NULL terminator */ return ((UINT16) (i + 1)); } /******************************************************************************* * * FUNCTION: AcpiRsGetResourceSource * * PARAMETERS: ResourceLength - Length field of the descriptor * MinimumLength - Minimum length of the descriptor (minus * any optional fields) * ResourceSource - Where the ResourceSource is returned * Aml - Pointer to the raw AML descriptor * StringPtr - (optional) where to store the actual * ResourceSource string * * RETURN: Length of the string plus NULL terminator, rounded up to native * word boundary * * DESCRIPTION: Copy the optional ResourceSource data from a raw AML descriptor * to an internal resource descriptor * ******************************************************************************/ ACPI_RS_LENGTH AcpiRsGetResourceSource ( ACPI_RS_LENGTH ResourceLength, ACPI_RS_LENGTH MinimumLength, ACPI_RESOURCE_SOURCE *ResourceSource, AML_RESOURCE *Aml, char *StringPtr) { ACPI_RSDESC_SIZE TotalLength; UINT8 *AmlResourceSource; ACPI_FUNCTION_ENTRY (); TotalLength = ResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER); AmlResourceSource = ACPI_ADD_PTR (UINT8, Aml, MinimumLength); /* * ResourceSource is present if the length of the descriptor is longer * than the minimum length. * * Note: Some resource descriptors will have an additional null, so * we add 1 to the minimum length. */ if (TotalLength > (ACPI_RSDESC_SIZE) (MinimumLength + 1)) { /* Get the ResourceSourceIndex */ ResourceSource->Index = AmlResourceSource[0]; ResourceSource->StringPtr = StringPtr; if (!StringPtr) { /* * String destination pointer is not specified; Set the String * pointer to the end of the current ResourceSource structure. */ ResourceSource->StringPtr = ACPI_ADD_PTR ( char, ResourceSource, sizeof (ACPI_RESOURCE_SOURCE)); } /* * In order for the Resource length to be a multiple of the native * word, calculate the length of the string (+1 for NULL terminator) * and expand to the next word multiple. * * Zero the entire area of the buffer. */ TotalLength = (UINT32) strlen ( ACPI_CAST_PTR (char, &AmlResourceSource[1])) + 1; TotalLength = (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (TotalLength); memset (ResourceSource->StringPtr, 0, TotalLength); /* Copy the ResourceSource string to the destination */ ResourceSource->StringLength = AcpiRsStrcpy ( ResourceSource->StringPtr, ACPI_CAST_PTR (char, &AmlResourceSource[1])); return ((ACPI_RS_LENGTH) TotalLength); } /* ResourceSource is not present */ ResourceSource->Index = 0; ResourceSource->StringLength = 0; ResourceSource->StringPtr = NULL; return (0); } /******************************************************************************* * * FUNCTION: AcpiRsSetResourceSource * * PARAMETERS: Aml - Pointer to the raw AML descriptor * MinimumLength - Minimum length of the descriptor (minus * any optional fields) * ResourceSource - Internal ResourceSource * * RETURN: Total length of the AML descriptor * * DESCRIPTION: Convert an optional ResourceSource from internal format to a * raw AML resource descriptor * ******************************************************************************/ ACPI_RSDESC_SIZE AcpiRsSetResourceSource ( AML_RESOURCE *Aml, ACPI_RS_LENGTH MinimumLength, ACPI_RESOURCE_SOURCE *ResourceSource) { UINT8 *AmlResourceSource; ACPI_RSDESC_SIZE DescriptorLength; ACPI_FUNCTION_ENTRY (); DescriptorLength = MinimumLength; /* Non-zero string length indicates presence of a ResourceSource */ if (ResourceSource->StringLength) { /* Point to the end of the AML descriptor */ AmlResourceSource = ACPI_ADD_PTR (UINT8, Aml, MinimumLength); /* Copy the ResourceSourceIndex */ AmlResourceSource[0] = (UINT8) ResourceSource->Index; /* Copy the ResourceSource string */ strcpy (ACPI_CAST_PTR (char, &AmlResourceSource[1]), ResourceSource->StringPtr); /* * Add the length of the string (+ 1 for null terminator) to the * final descriptor length */ DescriptorLength += ((ACPI_RSDESC_SIZE) ResourceSource->StringLength + 1); } /* Return the new total length of the AML descriptor */ return (DescriptorLength); } /******************************************************************************* * * FUNCTION: AcpiRsGetPrtMethodData * * PARAMETERS: Node - Device node * RetBuffer - Pointer to a buffer structure for the * results * * RETURN: Status * * DESCRIPTION: This function is called to get the _PRT value of an object * contained in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiRsGetPrtMethodData ( ACPI_NAMESPACE_NODE *Node, ACPI_BUFFER *RetBuffer) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (RsGetPrtMethodData); /* Parameters guaranteed valid by caller */ /* Execute the method, no parameters */ Status = AcpiUtEvaluateObject ( Node, METHOD_NAME__PRT, ACPI_BTYPE_PACKAGE, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Create a resource linked list from the byte stream buffer that comes * back from the _CRS method execution. */ Status = AcpiRsCreatePciRoutingTable (ObjDesc, RetBuffer); /* On exit, we must delete the object returned by EvaluateObject */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiRsGetCrsMethodData * * PARAMETERS: Node - Device node * RetBuffer - Pointer to a buffer structure for the * results * * RETURN: Status * * DESCRIPTION: This function is called to get the _CRS value of an object * contained in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiRsGetCrsMethodData ( ACPI_NAMESPACE_NODE *Node, ACPI_BUFFER *RetBuffer) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (RsGetCrsMethodData); /* Parameters guaranteed valid by caller */ /* Execute the method, no parameters */ Status = AcpiUtEvaluateObject ( Node, METHOD_NAME__CRS, ACPI_BTYPE_BUFFER, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Make the call to create a resource linked list from the * byte stream buffer that comes back from the _CRS method * execution. */ Status = AcpiRsCreateResourceList (ObjDesc, RetBuffer); /* On exit, we must delete the object returned by evaluateObject */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiRsGetPrsMethodData * * PARAMETERS: Node - Device node * RetBuffer - Pointer to a buffer structure for the * results * * RETURN: Status * * DESCRIPTION: This function is called to get the _PRS value of an object * contained in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiRsGetPrsMethodData ( ACPI_NAMESPACE_NODE *Node, ACPI_BUFFER *RetBuffer) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (RsGetPrsMethodData); /* Parameters guaranteed valid by caller */ /* Execute the method, no parameters */ Status = AcpiUtEvaluateObject ( Node, METHOD_NAME__PRS, ACPI_BTYPE_BUFFER, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Make the call to create a resource linked list from the * byte stream buffer that comes back from the _CRS method * execution. */ Status = AcpiRsCreateResourceList (ObjDesc, RetBuffer); /* On exit, we must delete the object returned by evaluateObject */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiRsGetAeiMethodData * * PARAMETERS: Node - Device node * RetBuffer - Pointer to a buffer structure for the * results * * RETURN: Status * * DESCRIPTION: This function is called to get the _AEI value of an object * contained in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiRsGetAeiMethodData ( ACPI_NAMESPACE_NODE *Node, ACPI_BUFFER *RetBuffer) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (RsGetAeiMethodData); /* Parameters guaranteed valid by caller */ /* Execute the method, no parameters */ Status = AcpiUtEvaluateObject ( Node, METHOD_NAME__AEI, ACPI_BTYPE_BUFFER, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Make the call to create a resource linked list from the * byte stream buffer that comes back from the _CRS method * execution. */ Status = AcpiRsCreateResourceList (ObjDesc, RetBuffer); /* On exit, we must delete the object returned by evaluateObject */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiRsGetMethodData * * PARAMETERS: Handle - Handle to the containing object * Path - Path to method, relative to Handle * RetBuffer - Pointer to a buffer structure for the * results * * RETURN: Status * * DESCRIPTION: This function is called to get the _CRS or _PRS value of an * object contained in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiRsGetMethodData ( ACPI_HANDLE Handle, const char *Path, ACPI_BUFFER *RetBuffer) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (RsGetMethodData); /* Parameters guaranteed valid by caller */ /* Execute the method, no parameters */ Status = AcpiUtEvaluateObject ( ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Handle), Path, ACPI_BTYPE_BUFFER, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Make the call to create a resource linked list from the * byte stream buffer that comes back from the method * execution. */ Status = AcpiRsCreateResourceList (ObjDesc, RetBuffer); /* On exit, we must delete the object returned by EvaluateObject */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiRsSetSrsMethodData * * PARAMETERS: Node - Device node * InBuffer - Pointer to a buffer structure of the * parameter * * RETURN: Status * * DESCRIPTION: This function is called to set the _SRS of an object contained * in an object specified by the handle passed in * * If the function fails an appropriate status will be returned * and the contents of the callers buffer is undefined. * * Note: Parameters guaranteed valid by caller * ******************************************************************************/ ACPI_STATUS AcpiRsSetSrsMethodData ( ACPI_NAMESPACE_NODE *Node, ACPI_BUFFER *InBuffer) { ACPI_EVALUATE_INFO *Info; ACPI_OPERAND_OBJECT *Args[2]; ACPI_STATUS Status; ACPI_BUFFER Buffer; ACPI_FUNCTION_TRACE (RsSetSrsMethodData); /* Allocate and initialize the evaluation information block */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { return_ACPI_STATUS (AE_NO_MEMORY); } Info->PrefixNode = Node; Info->RelativePathname = METHOD_NAME__SRS; Info->Parameters = Args; Info->Flags = ACPI_IGNORE_RETURN_VALUE; /* * The InBuffer parameter will point to a linked list of * resource parameters. It needs to be formatted into a * byte stream to be sent in as an input parameter to _SRS * * Convert the linked list into a byte stream */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiRsCreateAmlResources (InBuffer, &Buffer); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* Create and initialize the method parameter object */ Args[0] = AcpiUtCreateInternalObject (ACPI_TYPE_BUFFER); if (!Args[0]) { /* * Must free the buffer allocated above (otherwise it is freed * later) */ ACPI_FREE (Buffer.Pointer); Status = AE_NO_MEMORY; goto Cleanup; } Args[0]->Buffer.Length = (UINT32) Buffer.Length; Args[0]->Buffer.Pointer = Buffer.Pointer; Args[0]->Common.Flags = AOPOBJ_DATA_VALID; Args[1] = NULL; /* Execute the method, no return value is expected */ Status = AcpiNsEvaluate (Info); /* Clean up and return the status from AcpiNsEvaluate */ AcpiUtRemoveReference (Args[0]); Cleanup: ACPI_FREE (Info); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/string_util.h> s32 tilck_strtol32(const char *s, const char **endptr, int base, int *err); s64 tilck_strtol64(const char *s, const char **endptr, int base, int *err); u32 tilck_strtoul32(const char *s, const char **endptr, int base, int *err); u64 tilck_strtoul64(const char *s, const char **endptr, int base, int *err); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #if KERNEL_SELFTESTS #include <tilck/common/basic_defs.h> #include <tilck/common/color_defs.h> #include <tilck/common/printk.h> #include <tilck/mods/fb_console.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/hal.h> #include "fb_int.h" void internal_selftest_fb_perf(bool use_fpu) { if (!use_framebuffer()) panic("Unable to test framebuffer's performance: we're in text-mode"); const int iters = 30; u64 start, duration, cycles; if (use_fpu) fpu_context_begin(); { start = RDTSC(); for (int i = 0; i < iters; i++) { u32 color = vga_rgb_colors[i % 2 ? COLOR_WHITE : COLOR_BLACK]; fb_raw_perf_screen_redraw(color, use_fpu); } duration = RDTSC() - start; } if (use_fpu) fpu_context_end(); cycles = duration / iters; u32 pixels = fb_get_width() * fb_get_height(); printk("fb size (pixels): %u\n", pixels); printk("cycles per redraw: %" PRIu64 "\n", cycles); printk("cycles per 32 pixels: %" PRIu64 "\n", 32 * cycles / pixels); printk("use_fpu: %d\n", use_fpu); fb_draw_banner(); } void selftest_fbperf_nofpu(void) { internal_selftest_fb_perf(false); } void selftest_fbperf_fpu(void) { internal_selftest_fb_perf(true); } REGISTER_SELF_TEST(fbperf_nofpu, se_manual, &selftest_fbperf_nofpu) REGISTER_SELF_TEST(fbperf_fpu, se_manual, &selftest_fbperf_fpu) #endif // #if KERNEL_SELFTESTS <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ int vfs_read_ready(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->read_ready) return !!(hb->fl_flags & (O_RDWR | O_RDONLY)); return hb->fops->read_ready(h); } int vfs_write_ready(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->write_ready) return !!(hb->fl_flags & (O_RDWR | O_WRONLY)); return hb->fops->write_ready(h); } int vfs_except_ready(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->except_ready) return false; return hb->fops->except_ready(h); } struct kcond *vfs_get_rready_cond(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->get_rready_cond) return NULL; return hb->fops->get_rready_cond(h); } struct kcond *vfs_get_wready_cond(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->get_wready_cond) return NULL; return hb->fops->get_wready_cond(h); } struct kcond *vfs_get_except_cond(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->get_except_cond) return NULL; return hb->fops->get_except_cond(h); } <file_sep>Contributing to Tilck --------------------------- First off, thanks for taking the time to contribute! Any kind of contribution to the Tilck project is more than welcome. The project needs features and tests in many areas in order to become production-ready. Pull requests will be reviewed and, after addressing any eventual comments from the maintainer, will be merged in the master branch. Pull requests should meet a few requirements: - Contain high-quality code following Tilck's coding style - Build with *all* the currently supported configurations (see [building]) - Pass *all* the existing tests (see [testing]) - Contain tests for the new code - Contain expressive commit messages - Implement features aligned with the goals of the Tilck project **NOTE:** don't be scared to propose an imperfect pull request. You will get help! Code-free contributions are also welcome. The project would benefit from more documentation (HOWTOs, tutorials etc.), but also from artistic assets. [building]: building.md [testing]: testing.md Coding style ------------------------- The project does not have (yet) a formal coding style document, but it's possible to quickly mention a few points: - The snake_case is used - The line length is *strictly* limited to 80 columns - The indentation is *3 spaces* ([see here](https://github.com/vvaltchev/tilck/discussions/88)) - The opening braces are generally on the same line for all code blocks except for functions bodies and the initialization of arrays: ```C void func(int x) { if (x == 3) { do_something(); do_something_else(); } } static const char *const default_env[] = { "OSTYPE=linux-gnu", "TERM=linux", /* ... */ }; ``` - An exception to the rule above is for complex `if` statements that need to be broken across multiple lines: ```C if (eh->header->e_ident[EI_CLASS] != ELF_CURR_CLASS || eh->header->e_machine != ELF_CURR_ARCH) { *wrong_arch = true; return -ENOEXEC; } ``` - The braces should be omitted for single-statement blocks unless that generates confusion - It is often better to leave an empty line after `if (...) {` or `for (...) {`, when the condition/loop header is long compared to the next line, the body is non-trivial and the open brace is on the same line as the `if`/`for` statement. For example, this is good: ```C for (int i = (int)h->heap_data_size_log2 - 1; i >= 0 && tot < size; i--) { const size_t sub_block_size = (1 << i); if (!(size & sub_block_size)) continue; /* ... */ } ``` While this looks kind of ugly: ```C for (int i = (int)h->heap_data_size_log2 - 1; i >= 0 && tot < size; i--) { const size_t sub_block_size = (1 << i); if (!(size & sub_block_size)) continue; /* ... */ } ``` Simply because in the second case, the first line of the body gets partially hidden by loop's header. - For long function signatures, the type goes on the previous line, and the parameters are aligned like this: ```C static int load_segment_by_mmap(fs_handle *elf_h, pdir_t *pdir, Elf_Phdr *phdr, ulong *end_vaddr_ref) ``` - A similar rule applies for long function calls: ```C rc = map_page(pdir, (void *)stack_top + (i << PAGE_SHIFT), KERNEL_VA_TO_PA(p), PAGING_FL_RW | PAGING_FL_US); ``` - However, it's not always required to have only a single argument per line: ```C written += snprintk(buf + written, sizeof(buf) - (u32)written, "%i ", nested_interrupts[i]); ``` - Assignment to all the fields of a struct is generally done with this syntax: ```C *ctx = (struct deferred_kfree_ctx) { .h = h, .ptr = ptr, .user_size = *size, .flags = flags }; ``` - When it's possible to do so, it's preferable to put the code under a lock in a nested code block: ```C ulong var; disable_interrupts(&var); /* under #if KRN_TRACK_NESTED_INTERR */ { nested_interrupts_count--; ASSERT(nested_interrupts_count >= 0); } enable_interrupts(&var); ``` - Comments are great. Long comments are formatted like this: ```C /* * This is a long comment. * Second line. * Third line. */ ``` - Null-pointer checks are generally performed without NULL: ```C if (ptr) do_something(); if (!ptr_b) return; ``` - Long expressions involving the ternary operator `?:` can be formatted like this: ```C new_term = serial_port_fwd ? tty_allocate_and_init_new_serial_term(serial_port_fwd) : tty_allocate_and_init_new_video_term(rows_buf); ``` **NOTE[1]:** all the rules above can be broken if there is enough benefit for doing so. The only rule that has no exceptions so far is the 80-column limit for lines. Keeping that rule improves the readability of the code and prevents the use of excessively long names for identifiers. **NOTE[2]:** project's coding style is *not* written in stone. Proposals to change it will be carefully considered, as long as the person advocating for the change is willing to invest some effort in converting the pre-existing code to the new style. <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static enum term_fret tty_def_state_esc(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; tty_set_state(ctx, &tty_state_esc1); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_lf(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; if ((ctx->t->c_term.c_oflag & (OPOST | ONLCR)) == (OPOST | ONLCR)) { term_make_action_direct_write(a, "\n\r", 2, *color); return TERM_FILTER_WRITE_BLANK; } return TERM_FILTER_WRITE_C; } static enum term_fret tty_def_state_ri(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; if (vterm_get_curr_row(ctx->t->tstate) > 0) { term_make_action_move_cursor_rel(a, -1, 0); } else { term_make_action_non_buf_scroll(a, term_scroll_down, 1); } return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_keep(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { return TERM_FILTER_WRITE_C; } static enum term_fret tty_def_state_ignore(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_shift_out(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; /* shift out: use alternate charset G1 */ ctx->cd->c_set = 1; return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_shift_in(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; /* shift in: return to the default charset G0 */ ctx->cd->c_set = 0; return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_verase(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { term_make_action_del_prev_char(a); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_vwerase(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { term_make_action_del_prev_word(a); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_vkill(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { /* TODO: add support for VKILL */ return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_csi(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; tty_reset_filter_ctx(ctx->t); tty_set_state(ctx, &tty_state_esc2_csi); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_backspace(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { term_make_action_move_cursor_rel(a, 0, -1); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_def_state_raw_lf(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { /* * Typically, terminal emulators just treat \f and \v like a raw linefeed. * Raw linefeed means that the behavior is always just move the cursor to the * next line, without any carriage return. */ *c = '\n'; return TERM_FILTER_WRITE_C; } void tty_update_default_state_tables(struct tty *t) { const struct termios *const c_term = &t->c_term; struct console_data *cd = t->console_data; if (!cd) return; /* serial tty */ bzero(cd->def_state_funcs, 256 * sizeof(term_filter)); cd->def_state_funcs['\n'] = tty_def_state_lf; cd->def_state_funcs['\r'] = tty_def_state_keep; cd->def_state_funcs['\t'] = tty_def_state_keep; cd->def_state_funcs['\a'] = tty_def_state_ignore; /* bell */ cd->def_state_funcs['\f'] = tty_def_state_raw_lf; /* form-feed */ cd->def_state_funcs['\v'] = tty_def_state_raw_lf; /* vertical tab */ cd->def_state_funcs['\b'] = tty_def_state_backspace; cd->def_state_funcs['\033'] = tty_def_state_esc; cd->def_state_funcs['\016'] = tty_def_state_shift_out; cd->def_state_funcs['\017'] = tty_def_state_shift_in; cd->def_state_funcs[0x7f] = tty_def_state_ignore; cd->def_state_funcs[0x9b] = tty_def_state_csi; cd->def_state_funcs[c_term->c_cc[VERASE]] = tty_def_state_verase; cd->def_state_funcs[c_term->c_cc[VWERASE]] = tty_def_state_vwerase; cd->def_state_funcs[c_term->c_cc[VKILL]] = tty_def_state_vkill; } static enum term_fret tty_def_print_untrasl_char(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; int len = snprintk(ctx->tmpbuf, sizeof(ctx->tmpbuf), "{%#x}", *c); term_make_action_direct_write(a, ctx->tmpbuf, (u32)len, *color); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_state_default(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; struct console_data *cd = ctx->cd; s16 tv = cd->c_sets_tables[cd->c_set][*c]; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; if (tv >= 0) { *c = (u8) tv; return TERM_FILTER_WRITE_C; } if (cd->def_state_funcs[*c]) return cd->def_state_funcs[*c](c, color, a, ctx_arg); /* unknown character */ *c = '?'; return TERM_FILTER_WRITE_C; // DEBUG: uncomment for debugging untranslated characters // return tty_def_print_untrasl_char(c, color, a, ctx_arg); } <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tilck_types as tt from . import tasks class printer_struct_process: def __init__(self, val): self.val = val def children(self): proc = self.val # Note: it doesn't make sense to take t['pi']['pid'] because children # tasks are process' main threads, having always tid == pid. children_arr = bu.to_gdb_list_with_field_select( tasks.get_children_list(proc), "tid" ) handles_arr = bu.to_gdb_list(tasks.get_handles(proc)) debug_cmdline = proc['debug_cmdline'] if debug_cmdline: cmdline = "\"{}\"".format(debug_cmdline.string().rstrip()) else: cmdline = "(null)" cwd = proc['str_cwd'].string() mi = "(null)" if proc['mi']: mi = proc['mi'].dereference() return [ ("pid ", proc['pid']), ("cmdline ", cmdline), ("parent_pid ", proc['parent_pid']), ("pgid ", proc['pgid']), ("sid ", proc['sid']), ("brk ", proc['brk']), ("initial_brk ", proc['initial_brk']), ("children ", children_arr), ("did_call_execve ", proc['did_call_execve']), ("vforked ", proc['vforked']), ("inherited_mmap_heap", proc['inherited_mmap_heap']), ("str_cwd ", "\"{}\"".format(cwd)), ("handles ", handles_arr), ("mi ", mi), ] def to_string(self): return bu.fmt_type("struct process", self.val) bu.register_tilck_regex_pp( 'process', '^process$', printer_struct_process ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct x86_cpu_features { bool initialized; char vendor_id[16]; u32 max_basic_cpuid_cmd; u32 max_ext_cpuid_cmd; struct { bool fpu; // 0 bool vme; // 1 bool de; // 2 bool pse; // 3 bool tsc; // 4 bool msr; // 5 bool pae; // 6 bool mse; // 7 bool cx8; // 8 bool apic; // 9 bool res0; // 10 bool sep; // 11 bool mtrr; // 12 bool pge; // 13 bool mca; // 14 bool cmov; // 15 bool pat; // 16 bool pse36; // 17 bool psn; // 18 bool clfsh; // 19 bool res1; // 20 bool ds; // 21 bool acpi; // 22 bool mmx; // 23 bool fxsr; // 24 bool sse; // 25 bool sse2; // 26 bool ss; // 27 bool htt; // 28 bool tm; // 29 bool ia64; // 30 bool pbe; // 31 } edx1; struct { bool sse3; // 0 bool pclmulqdq; // 1 bool dtes64; // 2 bool monitor; // 3 bool ds_cpl; // 4 bool vmx; // 5 bool smx; // 6 bool est; // 7 bool tm2; // 8 bool ssse3; // 9 bool cnxt_id; // 10 bool sdbg; // 11 bool fma; // 12 bool cx16; // 13 bool xtpr; // 14 bool pdcm; // 15 bool res0; // 16 bool pcid; // 17 bool dca; // 18 bool sse4_1; // 19 bool sse4_2; // 20 bool x2apic; // 21 bool movbe; // 22 bool popcnt; // 23 bool tsc_deadline; // 24 bool aes; // 25 bool xsave; // 26 bool osxsave; // 27 bool avx; // 28 bool f16c; // 29 bool rdrnd; // 30 bool hypervisor; // 31 } ecx1; bool avx2; bool invariant_TSC; u8 phys_addr_bits; u8 virt_addr_bits; // Features allowed: bool can_use_sse; bool can_use_sse2; bool can_use_sse4_1; bool can_use_avx; bool can_use_avx2; }; extern volatile struct x86_cpu_features x86_cpu_features; void get_cpu_features(void); void dump_x86_features(void); static ALWAYS_INLINE bool in_hypervisor(void) { return x86_cpu_features.ecx1.hypervisor; } void enable_mtrr(void); void reset_mtrr(u32 num); void set_mtrr(u32 num, u64 paddr, u32 pow2size, u8 mem_type); u32 get_var_mttrs_count(void); int get_free_mtrr(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * Expose the internal data variables of system memory's map. * * WARNING * --------- * This *internal* header is supposed to be used in the very few places where * actually updating system's memory map is allowed. For example: * * - in set_framebuffer_info_from_mbi(), * during the initialization of the framebuffer console * * - in arch_add_initial_mem_regions(), * during system_mmap_set() * * - in arch_add_final_mem_regions(), * during system_mmap_set() * * - in the system map's unit tests * * Outside of kernel's initialization, system's memory map is assumed to be * immutable. */ #pragma once #include <tilck/kernel/system_mmap.h> extern struct mem_region mem_regions[MAX_MEM_REGIONS]; extern int mem_regions_count; void append_mem_region(struct mem_region r); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include "vfs_test_fs.h" static map<tfs_entry *, tfs_entry *> test_mps; void test_fs_register_mp(tfs_entry *where, tfs_entry *target) { auto it = test_mps.find(where); ASSERT_TRUE(it == test_mps.end()); test_mps[where] = target; } void test_fs_clear_mps() { test_mps.clear(); } bool test_fs_is_mountpoint(tfs_entry *e) { return test_mps.find(e) != test_mps.end(); } void test_fs_check_refcounts(tfs_entry *node) { for (auto &p : node->children) { tfs_entry *e = p.second; if (test_fs_is_mountpoint(e)) { ASSERT_EQ(e->ref_count, 1) << "[Info] mp node: " << p.first; } else { ASSERT_EQ(e->ref_count, 0) << "[Info] node: " << p.first; } test_fs_check_refcounts(e); } } static void testfs_get_entry(struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t name_len, struct fs_path *fs_path) { if (!dir_inode && !name) { fs_path->type = VFS_DIR; fs_path->inode = fs->device_data; fs_path->dir_inode = fs->device_data; fs_path->dir_entry = nullptr; return; } string s{name, (size_t)name_len}; tfs_entry *e = (tfs_entry *)dir_inode; //cout << "get_entry: '" << s << "'" << endl; if (s == "." || s == "..") { if (s == ".." && e->parent != nullptr) e = e->parent; fs_path->inode = (void *)e; fs_path->type = e->type; fs_path->dir_inode = e->parent; return; } auto it = e->children.find(s); if (it != e->children.end()) { fs_path->inode = it->second; fs_path->type = it->second->type; } else { fs_path->inode = nullptr; fs_path->type = VFS_NONE; } fs_path->dir_inode = e; } static void vfs_test_fs_exlock(struct mnt_fs *fs) { //printf("EXLOCK: %s\n", fs->fs_type_name); } static void vfs_test_fs_exunlock(struct mnt_fs *fs) { //printf("EXUNLOCK: %s\n", fs->fs_type_name); } static void vfs_test_fs_shlock(struct mnt_fs *fs) { //printf("SHLOCK: %s\n", fs->fs_type_name); } static void vfs_test_fs_shunlock(struct mnt_fs *fs) { //printf("SHUNLOCK: %s\n", fs->fs_type_name); } static int vfs_test_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t i) { tfs_entry *e = (tfs_entry *)i; return ++e->ref_count; } static int vfs_test_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t i) { tfs_entry *e = (tfs_entry *)i; assert(e->ref_count > 0); return --e->ref_count; } static int test_fs_readlink(struct vfs_path *rp, char *buf) { tfs_entry *e = (tfs_entry *)rp->fs_path.inode; if (e->type != VFS_SYMLINK) return -ENOLINK; strcpy(buf, e->symlink); return strlen(e->symlink); } /* * Unfortunately, in C++ non-trivial designated initializers are fully not * supported, so we have to explicitly initialize all the members, in order! */ extern const struct fs_ops static_fsops_testfs = { .get_entry = testfs_get_entry, .get_inode = nullptr, .open = nullptr, .on_close = nullptr, .on_close_last_handle = nullptr, .on_dup_cb = nullptr, .getdents = nullptr, .unlink = nullptr, .stat = nullptr, .mkdir = nullptr, .rmdir = nullptr, .symlink = nullptr, .readlink = test_fs_readlink, .truncate = nullptr, .chmod = nullptr, .rename = nullptr, .link = nullptr, .futimens = nullptr, .retain_inode = vfs_test_retain_inode, .release_inode = vfs_test_release_inode, .syncfs = nullptr, .fs_exlock = vfs_test_fs_exlock, .fs_exunlock = vfs_test_fs_exunlock, .fs_shlock = vfs_test_fs_shlock, .fs_shunlock = vfs_test_fs_shunlock, .exlock_noblk = nullptr, .exunlock = nullptr, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once /* * Tilck text mode color constants */ enum vga_color { /* regular (darker) colors */ COLOR_BLACK = 0, COLOR_BLUE = 1, COLOR_GREEN = 2, COLOR_CYAN = 3, COLOR_RED = 4, COLOR_MAGENTA = 5, COLOR_YELLOW = 6, /* on VGA this is kind-of brown */ COLOR_WHITE = 7, /* light gray */ /* brighter colors */ COLOR_BRIGHT_BLACK = 8, /* dark gray */ COLOR_BRIGHT_BLUE = 9, COLOR_BRIGHT_GREEN = 10, COLOR_BRIGHT_CYAN = 11, COLOR_BRIGHT_RED = 12, COLOR_BRIGHT_MAGENTA = 13, COLOR_BRIGHT_YELLOW = 14, COLOR_BRIGHT_WHITE = 15, }; #define make_color(fg, bg) ((u8)(((fg) | (bg) << 4))) #define get_color_fg(color) ((color) & 0xF) #define get_color_bg(color) (((color) >> 4) & 0xF) #define DEFAULT_FG_COLOR COLOR_WHITE #define DEFAULT_BG_COLOR COLOR_BLACK #define DEFAULT_COLOR16 (make_color(DEFAULT_FG_COLOR, DEFAULT_BG_COLOR)) /* * Entry defs (color + char): the hardware format (VGA textmode) is used also * by the hw-independent subsystems "term" and "fb_console", for convenience. */ #define make_vgaentry(c, color) ((u16)(((u16)c) | ((u16)color << 8))) #define vgaentry_get_fg(e) LO_BITS((e) >> 8, 4, u8) #define vgaentry_get_bg(e) LO_BITS((e) >> 12, 4, u8) #define vgaentry_get_char(e) LO_BITS((e), 8, u8) #define vgaentry_get_color(e) SHR_BITS((e), 8, u8) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_sched.h> #include <tilck/common/basic_defs.h> void kernel_sleep(u64 ticks); /* sleep for `ticks` timer ticks (jiffies) */ void kernel_sleep_ms(u64 ms); /* sleep for `ms` milliseconds */ void delay_us(u32 us); /* busy-wait for `us` microseconds */ static ALWAYS_INLINE u64 ms_to_ticks(u64 ms) { return ms / (1000 / TIMER_HZ); } u64 get_ticks(void); void init_timer(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define _KMALLOC_C_ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/kmalloc_debug.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/sort.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/worker_thread.h> #include <tilck_gen_headers/config_kmalloc.h> #include "kmalloc_debug.h" #include "kmalloc_heap_struct.h" #include "kmalloc_block_node.h" size_t kmalloc_get_heap_struct_size(void) { return sizeof(struct kmalloc_heap); } STATIC_ASSERT(sizeof(struct block_node) == KMALLOC_METADATA_BLOCK_NODE_SIZE); STATIC bool kmalloc_initialized; static const struct block_node s_new_node; // Just zeros. #define HALF(x) ((x) >> 1) #define TWICE(x) ((x) << 1) #define NODE_LEFT(n) (TWICE(n) + 1) #define NODE_RIGHT(n) (TWICE(n) + 2) #define NODE_PARENT(n) (HALF(n-1)) #define NODE_IS_LEFT(n) (((n) & 1) != 0) bool is_kmalloc_initialized(void) { return kmalloc_initialized; } STATIC_INLINE int ptr_to_node(struct kmalloc_heap *h, void *ptr, size_t size) { const ulong size_log = log2_for_power_of_2(size); const ulong offset = (ulong)ptr - h->vaddr; const ulong nodes_before_our = (1 << (h->heap_data_size_log2 - size_log))-1; const ulong position_in_row = offset >> size_log; return (int)(nodes_before_our + position_in_row); } STATIC_INLINE void *node_to_ptr(struct kmalloc_heap *h, int node, size_t size) { const ulong size_log = log2_for_power_of_2(size); const ulong nodes_before_our = (1 << (h->heap_data_size_log2 - size_log))-1; const ulong position_in_row = (u32)node - nodes_before_our; const ulong offset = position_in_row << size_log; return (void *)(offset + h->vaddr); } CONSTEXPR static ALWAYS_INLINE bool is_block_node_free(struct block_node n) { return !(n.raw & (FL_NODE_FULL | FL_NODE_SPLIT)); } static size_t set_free_uplevels(struct kmalloc_heap *h, int *node, size_t size) { struct block_node *nodes = h->metadata_nodes; size_t curr_size = size << 1; int n = *node; ASSERT(!nodes[n].split); nodes[n].full = false; n = NODE_PARENT(n); while (!is_block_node_free(nodes[n])) { struct block_node left = nodes[NODE_LEFT(n)]; struct block_node right = nodes[NODE_RIGHT(n)]; if (!is_block_node_free(left) || !is_block_node_free(right)) { DEBUG_stop_coaleshe; nodes[n].full = left.full && right.full; ASSERT(nodes[n].split); ASSERT((left.full && right.full && nodes[n].full) || !nodes[n].full); curr_size >>= 1; break; } *node = n; // last successful coaleshe. DEBUG_coaleshe; nodes[n].raw &= ~(FL_NODE_SPLIT | FL_NODE_FULL); if (n == 0) break; /* we processed the root node, cannot go further */ n = NODE_PARENT(n); curr_size <<= 1; } /* * We have coaleshed as much nodes as possible, now we have to continue * up to the root just to mark the higher nodes as NOT full, even if they * cannot be coaleshed. */ while (n >= 0) { nodes[n].full = false; n = NODE_PARENT(n); } return curr_size; } static bool actual_allocate_node(struct kmalloc_heap *h, size_t node_size, int node, void **vaddr_ref, bool do_actual_alloc) { bool alloc_failed = false; struct block_node *nodes = h->metadata_nodes; nodes[node].full = true; const ulong vaddr = (ulong)node_to_ptr(h, node, node_size); *vaddr_ref = (void *)vaddr; if (h->linear_mapping || !do_actual_alloc) return true; // nothing to do! ulong alloc_block_vaddr = vaddr & ~(h->alloc_block_size - 1); const size_t alloc_block_count = 1 + ((node_size - 1) >> h->alloc_block_size_log2); /* * Code dealing with the tricky allocation logic. */ for (u32 i = 0; i < alloc_block_count; i++) { int alloc_node = ptr_to_node(h, (void *)alloc_block_vaddr, h->alloc_block_size); ASSERT(node_to_ptr(h, alloc_node, h->alloc_block_size) == (void *)alloc_block_vaddr); DEBUG_allocate_node1; /* * The nodes with alloc_failed=1 are supposed to be processed immediately * by internal_kfree() after actual_allocate_node() failed. */ ASSERT(!nodes[alloc_node].alloc_failed); if (!nodes[alloc_node].allocated) { DEBUG_allocate_node2; bool success = h->valloc_and_map(alloc_block_vaddr, h->alloc_block_size / PAGE_SIZE); if (success) { nodes[alloc_node].allocated = true; } else { nodes[alloc_node].alloc_failed = true; alloc_failed = true; } } if (node_size >= h->alloc_block_size) { ASSERT(!nodes[alloc_node].split); nodes[alloc_node].full = true; } else { ASSERT(nodes[alloc_node].split); } alloc_block_vaddr += h->alloc_block_size; } DEBUG_allocate_node3; return !alloc_failed; } static size_t calculate_node_size(struct kmalloc_heap *h, int node) { size_t size = h->size; for (int cn = node; cn != 0; cn = NODE_PARENT(cn)) { size >>= 1; } return size; } void internal_kmalloc_split_block(struct kmalloc_heap *h, void *const vaddr, const size_t block_size, const size_t leaf_node_size) { ASSERT(leaf_node_size >= h->min_block_size); ASSERT(block_size >= h->min_block_size); ASSERT(roundup_next_power_of_2(leaf_node_size) == leaf_node_size); ASSERT(roundup_next_power_of_2(block_size) == block_size); struct block_node *nodes = h->metadata_nodes; size_t s; int n = ptr_to_node(h, vaddr, block_size); int node_count = 1; ASSERT(nodes[n].full); ASSERT(!nodes[n].split); for (s = block_size; s > leaf_node_size; s >>= 1) { if (s != h->alloc_block_size) { memset(&nodes[n], FL_NODE_SPLIT | FL_NODE_FULL, (size_t)node_count); } else { for (int j = 0; j < node_count; j++) nodes[n + j].raw |= (FL_NODE_SPLIT | FL_NODE_FULL); } node_count <<= 1; n = NODE_LEFT(n); } ASSERT(s == leaf_node_size); if (s != h->alloc_block_size) { memset(&nodes[n], FL_NODE_FULL, (size_t)node_count); } else { for (int j = 0; j < node_count; j++) { nodes[n + j].full = 1; nodes[n + j].split = 0; } } } size_t internal_kmalloc_coalesce_block(struct kmalloc_heap *h, void *const vaddr, const size_t block_size) { struct block_node *nodes = h->metadata_nodes; const int block_node_num = ptr_to_node(h, vaddr, block_size); size_t s; int n = block_node_num; int node_count = 1; size_t already_free_size = 0; ASSERT(nodes[n].full || nodes[n].split); for (s = block_size; s >= h->min_block_size; s >>= 1) { if (s > h->min_block_size) { if (s != h->alloc_block_size) { bzero(&nodes[n], (size_t)node_count); } else { for (int j = n; j < n + node_count; j++) nodes[j].raw &= ~(FL_NODE_SPLIT | FL_NODE_FULL); } } else { for (int j = n; j < n + node_count; j++) { if (!(nodes[j].raw & (FL_NODE_SPLIT | FL_NODE_FULL))) already_free_size += s; nodes[j].raw &= ~(FL_NODE_SPLIT | FL_NODE_FULL); } } node_count <<= 1; n = NODE_LEFT(n); } nodes[block_node_num].full = 1; ASSERT(s < h->min_block_size); return already_free_size; } static void * internal_kmalloc(struct kmalloc_heap *h, const size_t size, /* power of 2 */ const int start_node, size_t start_node_size, bool mark_node_as_allocated, bool do_actual_alloc) /* ignored if linear_mapping = 1 */ { /* * do_actual_alloc -> mark_node_as_allocated (logical implication). */ ASSERT(!do_actual_alloc || mark_node_as_allocated); struct block_node *nodes = h->metadata_nodes; int stack_size = 0; if (!start_node_size) start_node_size = calculate_node_size(h, start_node); SIMULATE_CALL2(start_node_size, start_node); NOREC_LOOP_BEGIN { // Load the "stack" (function arguments) const size_t node_size = LOAD_ARG_FROM_STACK(1, size_t); const int node = LOAD_ARG_FROM_STACK(2, int); HANDLE_SIMULATED_RETURN(); // Handle a SIMULATED "call" DEBUG_kmalloc_call_begin; struct block_node n = nodes[node]; if (n.full) { DEBUG_already_full; SIMULATE_RETURN_NULL(); } if (HALF(node_size) < size) { if (n.split) { DEBUG_already_split; SIMULATE_RETURN_NULL(); } void *vaddr = NULL; bool success; if (mark_node_as_allocated) { success = actual_allocate_node(h, node_size, node, &vaddr, do_actual_alloc); ASSERT(vaddr != NULL); // 'vaddr' is not NULL even when !success } else { success = true; vaddr = node_to_ptr(h, node, node_size); } // Mark the parent nodes as 'full', when necessary. for (int ss = stack_size - 2; ss >= 0; ss--) { const int nn = (int)(long) STACK_VAR[ss].arg2; /* arg2: node */ if (nodes[NODE_LEFT(nn)].full && nodes[NODE_RIGHT(nn)].full) { ASSERT(!nodes[nn].full); nodes[nn].full = true; } } if (UNLIKELY(!success)) { /* * Corner case: in case of non-linearly mapped heaps, a successfull * allocation in the heap metadata does not always mean a sucessfull * kmalloc(), because the underlying allocator [h->valloc_and_map] * might have failed. In this case we have to call per_heap_kfree * and restore kmalloc's heap metadata to the previous state. Also, * all the alloc nodes we be either marked as allocated or * alloc_failed. */ DEBUG_kmalloc_bad_end; size_t actual_size = node_size; per_heap_kfree(h, vaddr, &actual_size, 0); return NULL; } DEBUG_kmalloc_end; if (do_actual_alloc) h->mem_allocated += node_size; return vaddr; } if (!n.split) { DEBUG_kmalloc_split; nodes[node].split = true; } if (!nodes[NODE_LEFT(node)].full) { DEBUG_going_left; SIMULATE_CALL2(HALF(node_size), NODE_LEFT(node)); /* * If we got here, the "call" on the left node "returned" NULL so, * we have to try go to the right node. [In case of success, this * function returns directly.] */ DEBUG_left_failed; } if (!nodes[NODE_RIGHT(node)].full) { DEBUG_going_right; SIMULATE_CALL2(HALF(node_size), NODE_RIGHT(node)); /* * When the above "call" succeeds, we don't get here. When it fails, * we get here and just continue the execution. */ DEBUG_right_failed; } // In case both the nodes are full, just return NULL. SIMULATE_RETURN_NULL(); } NOREC_LOOP_END return NULL; } static void * per_heap_kmalloc_unsafe(struct kmalloc_heap *h, size_t *size, u32 flags) { void *addr; const bool multi_step_alloc = !!(flags & KMALLOC_FL_MULTI_STEP); const bool do_actual_alloc = !(flags & KMALLOC_FL_NO_ACTUAL_ALLOC); const u32 sub_blocks_min_size = flags & KMALLOC_FL_SUB_BLOCK_MIN_SIZE_MASK; ASSERT(*size != 0); ASSERT(!sub_blocks_min_size || sub_blocks_min_size >= h->min_block_size); ASSERT(!is_preemption_enabled()); DEBUG_kmalloc_begin; if (UNLIKELY(*size > h->size)) return NULL; const size_t rounded_up_size = MAX(roundup_next_power_of_2(*size), h->min_block_size); if (!multi_step_alloc || ((rounded_up_size - *size) < h->min_block_size)) { *size = rounded_up_size; addr = internal_kmalloc(h, /* heap */ *size, /* block size */ 0, /* start node */ h->size, /* start node size */ true, /* mark node as allocated */ do_actual_alloc); if (sub_blocks_min_size && addr) { internal_kmalloc_split_block(h, addr, *size, sub_blocks_min_size); } return addr; } /* * multi_step_alloc is true, therefore we can do multiple allocations in * order to allocate almost exactly (round-up at min_block_size) bytes. * * NOTE: we don't have to mark as free the remaining of big_block after the * "for" loop below, because we called internal_kmalloc() with * do_actual_alloc = false. */ const size_t desired_size = *size; void *big_block = internal_kmalloc(h, rounded_up_size, 0, h->size, false, false); if (!big_block) return NULL; const int big_block_node = ptr_to_node(h, big_block, rounded_up_size); size_t tot = 0; for (int i=(int)h->heap_data_size_log2-1; i >= 0 && tot < desired_size; i--) { const size_t s = (1u << i); if (!(desired_size & s)) continue; addr = internal_kmalloc(h, s, big_block_node, rounded_up_size, true, /* mark node as allocated */ do_actual_alloc); ASSERT(addr == big_block + tot); if (sub_blocks_min_size) { internal_kmalloc_split_block(h, addr, s, sub_blocks_min_size); } tot += s; } *size = tot; return big_block; } void * per_heap_kmalloc(struct kmalloc_heap *h, size_t *size, u32 flags) { bool expected = false; void *res; if (!atomic_cas_strong(&h->in_use, &expected, true, mo_relaxed, mo_relaxed)) return NULL; /* heap already in use (we're in IRQ context) */ res = per_heap_kmalloc_unsafe(h, size, flags); atomic_store_explicit(&h->in_use, false, mo_relaxed); return res; } static void internal_kfree(struct kmalloc_heap *h, void *ptr, size_t size, bool allow_split, bool do_actual_free) { ASSERT(size); const int node = ptr_to_node(h, ptr, size); size_t free_size_correction = 0; DEBUG_free1; ASSERT(node_to_ptr(h, node, size) == ptr); ASSERT(roundup_next_power_of_2(size) == size); ASSERT(size >= h->min_block_size); struct block_node *nodes = h->metadata_nodes; if (allow_split && nodes[node].split) { free_size_correction = internal_kmalloc_coalesce_block(h, ptr, size); } h->mem_allocated -= (size - free_size_correction); /* * Regular calls to kfree2() pass to it "regular" blocks returned by * kmalloc(), which are never split. */ ASSERT(!nodes[node].split); { int biggest_free_node = node; // Mark the parent nodes as free, when necessary. size_t biggest_free_size = set_free_uplevels(h, &biggest_free_node, size); DEBUG_free_after_coaleshe; ASSERT(biggest_free_node == node || biggest_free_size != size); if (biggest_free_size < h->alloc_block_size) return; } if (h->linear_mapping || !do_actual_free) return; // nothing to do! ulong alloc_block_vaddr = (ulong)ptr & ~(h->alloc_block_size - 1); const size_t alloc_block_count = 1 + ((size-1) >> h->alloc_block_size_log2); /* * Code dealing with the tricky allocation logic. */ DEBUG_free_alloc_block_count; for (u32 i = 0; i < alloc_block_count; i++) { const int alloc_node = ptr_to_node(h, (void *)alloc_block_vaddr, h->alloc_block_size); DEBUG_check_alloc_block; /* * For nodes smaller than h->alloc_block_size, the page we're freeing MUST * be free. For bigger nodes that kind of checking does not make sense: * a major block owns its all pages and their flags are irrelevant. */ ASSERT(size >= h->alloc_block_size || is_block_node_free(nodes[alloc_node])); if (!allow_split) { ASSERT(nodes[alloc_node].allocated || nodes[alloc_node].alloc_failed); } if (nodes[alloc_node].allocated) { DEBUG_free_freeing_block; h->vfree_and_unmap(alloc_block_vaddr, h->alloc_block_size / PAGE_SIZE); nodes[alloc_node] = s_new_node; } else if (nodes[alloc_node].alloc_failed) { DEBUG_free_skip_alloc_failed_block; nodes[alloc_node].alloc_failed = false; } alloc_block_vaddr += h->alloc_block_size; } } static size_t calculate_block_size(struct kmalloc_heap *h, ulong vaddr) { struct block_node *nodes = h->metadata_nodes; int n = 0; /* root's node index */ ulong va = h->vaddr; /* root's node data address == heap's address */ size_t size = h->size; /* root's node size == heap's size */ while (size > h->min_block_size) { if (!nodes[n].split) break; size >>= 1; if (vaddr >= (va + size)) { va += size; n = NODE_RIGHT(n); } else { n = NODE_LEFT(n); } } return size; } static void debug_check_block_size(struct kmalloc_heap *h, ulong vaddr, size_t size) { size_t cs = calculate_block_size(h, vaddr); if (cs != size) { panic("calculated_size[%u] != user_size[%u] for block at: %p\n", cs, size, vaddr); } } static void per_heap_kfree_unsafe(struct kmalloc_heap *h, void *ptr, size_t *user_size, u32 flags) { size_t size; ulong vaddr = (ulong)ptr; const bool allow_split = !!(flags & KFREE_FL_ALLOW_SPLIT); const bool multi_step_free = !!(flags & KFREE_FL_MULTI_STEP); const bool do_actual_free = !(flags & KFREE_FL_NO_ACTUAL_FREE); ASSERT(!is_preemption_enabled()); ASSERT(vaddr >= h->vaddr); ASSERT(ptr); if (!multi_step_free) { if (*user_size) { size = roundup_next_power_of_2(MAX(*user_size, h->min_block_size)); if (!allow_split) { DEBUG_ONLY(debug_check_block_size(h, vaddr, size)); } } else { ASSERT(!allow_split); size = calculate_block_size(h, vaddr); } *user_size = size; ASSERT(vaddr + size - 1 <= h->heap_last_byte); return internal_kfree(h, ptr, size, allow_split, do_actual_free); } ASSERT(*user_size); size = *user_size; /* * No round-up: when multi_step_free=1 we assume that the * size is the one returned as an out-param by * per_heap_kmalloc(). Also, we don't have to alter * *user_size too. */ ASSERT(vaddr + size - 1 <= h->heap_last_byte); ASSERT(pow2_round_up_at(size, h->min_block_size) == size); size_t tot = 0; for (int i = (int)h->heap_data_size_log2 - 1; i >= 0 && tot < size; i--) { const size_t sub_block_size = (1 << i); if (!(size & sub_block_size)) continue; internal_kfree(h, ptr + tot, sub_block_size, allow_split, do_actual_free); tot += sub_block_size; } ASSERT(tot == size); } struct deferred_kfree_ctx { struct kmalloc_heap *h; void *ptr; size_t user_size; u32 flags; }; static struct deferred_kfree_ctx emergency_deferred_kfree_ctx_array[8]; static struct deferred_kfree_ctx * get_emergency_deferred_kfree_ctx(void *ptr) { for (int i = 0; i < ARRAY_SIZE(emergency_deferred_kfree_ctx_array); i++) { if (emergency_deferred_kfree_ctx_array[i].ptr == NULL) { emergency_deferred_kfree_ctx_array[i].ptr = ptr; return &emergency_deferred_kfree_ctx_array[i]; } } return NULL; } static bool is_emerg_deferred_kfree_ctx(struct deferred_kfree_ctx *ctx) { return IN_RANGE( (ulong)ctx, (ulong)&emergency_deferred_kfree_ctx_array[0], (ulong)&emergency_deferred_kfree_ctx_array[0] + sizeof(emergency_deferred_kfree_ctx_array) ); } static void do_deferred_kfree(void *arg) { struct deferred_kfree_ctx *ctx = arg; disable_preemption(); { per_heap_kfree(ctx->h, ctx->ptr, &ctx->user_size, ctx->flags); bzero(ctx, sizeof(*ctx)); } enable_preemption_nosched(); if (!is_emerg_deferred_kfree_ctx(ctx)) kfree_obj(ctx, struct deferred_kfree_ctx); } NO_INLINE static void per_heap_kfree_used_heap_corner_case(struct kmalloc_heap *h, void *ptr, size_t *size, u32 flags) { const bool multi_step_free = !!(flags & KFREE_FL_MULTI_STEP); /* * Corner case: probably because of ACPICA, we need to free a * heap-allocated object in IRQ context WHILE the very same heap is * already in use. That's extremely unfortunate. */ if (!multi_step_free) { if (*size) { *size = roundup_next_power_of_2(MAX(*size, h->min_block_size)); } else { /* No size: sorry, cannot give you this information in this case */ } } else { /* Here *size is REQUIRED */ ASSERT(*size); } struct deferred_kfree_ctx *ctx = kalloc_obj(struct deferred_kfree_ctx); if (!ctx) { /* Could we get more unlucky that this? */ ctx = get_emergency_deferred_kfree_ctx(ptr); if (!ctx) { /* Give up */ printk("kmalloc: ERROR: can't defer kfree %p: OOM\n", ptr); return; } } *ctx = (struct deferred_kfree_ctx) { .h = h, .ptr = ptr, .user_size = *size, .flags = flags }; if (!wth_enqueue_anywhere(WTH_PRIO_HIGHEST, &do_deferred_kfree, ctx)) printk("kmalloc: ERROR: can't defer kfree %p: enqueue fail\n", ptr); } void per_heap_kfree(struct kmalloc_heap *h, void *ptr, size_t *user_size, u32 flags) { bool expected = false; if (!ptr) return; if (!atomic_cas_strong(&h->in_use, &expected, true, mo_relaxed, mo_relaxed)) { per_heap_kfree_used_heap_corner_case(h, ptr, user_size, flags); return; } per_heap_kfree_unsafe(h, ptr, user_size, flags); atomic_store_explicit(&h->in_use, false, mo_relaxed); } void *kzmalloc(size_t size) { void *res = kmalloc(size); if (!res) return NULL; bzero(res, size); return res; } static void vfree_internal(ulong va_begin, ulong va_end) { for (ulong va = va_begin; va < va_end; va += PAGE_SIZE) unmap_kernel_page(TO_PTR(va), true); } void *vmalloc(size_t size) { size_t actual_sz = pow2_round_up_at(size, PAGE_SIZE); ulong va, va_begin, va_end; void *ptr; if (!hi_vmem_avail()) return kmalloc(size); ptr = kmalloc(size); if (ptr) return ptr; ptr = hi_vmem_reserve(actual_sz); va_begin = (ulong)ptr; va_end = va_begin + actual_sz; for (va = va_begin; va < va_end; va += PAGE_SIZE) { if (map_kernel_page(TO_PTR(va), 0, PAGING_FL_RW | PAGING_FL_DO_ALLOC)) goto oom_case; } return TO_PTR(va_begin); oom_case: va_end = va; vfree_internal(va_begin, va_end); hi_vmem_release(TO_PTR(va_begin), actual_sz); return NULL; } void vfree2(void *ptr, size_t size) { if (!ptr) return; if ((ulong)ptr < LINEAR_MAPPING_END) return kfree2(ptr, size); size_t actual_sz = pow2_round_up_at(size, PAGE_SIZE); ulong va_begin, va_end; va_begin = (ulong)ptr; va_end = va_begin + actual_sz; vfree_internal(va_begin, va_end); hi_vmem_release(TO_PTR(va_begin), actual_sz); } /* Natural continuation of this source file. Purpose: make this file shorter. */ #include "kmalloc_stats.c.h" #include "kmalloc_small_heaps.c.h" #include "kmalloc_heaps.c.h" #include "general_kmalloc.c.h" #include "kmalloc_accelerator.c.h" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static const struct { u32 key; char seq[8]; } ansi_sequences[] = { {KEY_UP, "\033[A"}, {KEY_DOWN, "\033[B"}, {KEY_RIGHT, "\033[C"}, {KEY_LEFT, "\033[D"}, {KEY_NUMPAD_UP, "\033[A"}, {KEY_NUMPAD_DOWN, "\033[B"}, {KEY_NUMPAD_RIGHT, "\033[C"}, {KEY_NUMPAD_LEFT, "\033[D"}, {KEY_PAGE_UP, "\033[5~"}, {KEY_NUMPAD_PAGE_UP, "\033[5~"}, {KEY_PAGE_DOWN, "\033[6~"}, {KEY_NUMPAD_PAGE_DOWN, "\033[6~"}, {KEY_INS, "\033[2~"}, {KEY_NUMPAD_INS, "\033[2~"}, {KEY_DEL, "\033[3~"}, {KEY_NUMPAD_DEL, "\033[3~"}, {KEY_HOME, "\033[1~"}, {KEY_NUMPAD_HOME, "\033[1~"}, {KEY_END, "\033[4~"}, {KEY_NUMPAD_END, "\033[4~"}, {KEY_F1, "\033[[A"}, {KEY_F2, "\033[[B"}, {KEY_F3, "\033[[C"}, {KEY_F4, "\033[[D"}, {KEY_F5, "\033[[E"}, {KEY_F6, "\033[17~"}, {KEY_F7, "\033[18~"}, {KEY_F8, "\033[19~"}, {KEY_F9, "\033[20~"}, {KEY_F10, "\033[21~"}, {KEY_F11, "\033[23~"}, {KEY_F12, "\033[24~"}, }; static bool kb_scancode_to_ansi_seq(u32 key, u8 modifiers, char *seq) { const char *base_seq = NULL; char *p; u32 sl; ASSERT(modifiers < 8); /* * It might not seem very efficient to linearly walk through all the * sequences trying to find the one for `key`. But that's just a perception: * * It's about doing ~30 iterations in the WORST case. For such small values * of N, it's almost always faster to use a linear algorithm than complex * O(1) or O(log(N)) algorithms, because they have significant (hidden) * constants multipliers in the function of N describing their *real*, not * asymptotic, cost. */ for (int i = 0; i < ARRAY_SIZE(ansi_sequences); i++) { if (ansi_sequences[i].key == key) { base_seq = ansi_sequences[i].seq; break; } } if (!base_seq) return false; sl = strlen(base_seq); memcpy(seq, base_seq, sl + 1); if (!modifiers) return true; if (UNLIKELY(seq[1] != '[')) { if (seq[1] == 'O') { /* * The sequence is like F1: \033OP. Before appending the modifiers, * we need to replace 'O' with [1. */ char end_char = seq[2]; seq[1] = '['; seq[2] = '1'; seq[3] = end_char; seq[4] = 0; sl++; /* we increased the size by 1 */ } else { /* Don't know how to deal with such a sequence */ return false; } } else if (!isdigit(seq[2])) { /* * Here the seq starts with ESC [, but a non-digit follows '['. * Example: the HOME key: \033[H * In this case, we need to insert a "1;" between '[' and 'H'. */ if (sl != 3) { /* Don't support UNKNOWN cases like \033[XY: they should not exist */ return false; } char end_char = seq[2]; seq[2] = '1'; seq[3] = end_char; seq[4] = 0; sl++; /* Now we have seq like \033[1H: the code below will complete the job */ } /* * If the seq is like ESC [ <something> <end char>, then we can just * insert after "; <modifiers+1>" between <something> and <end char>. */ char end_char = seq[sl - 1]; p = &seq[sl - 1]; *p++ = ';'; *p++ = '1' + (char)modifiers; *p++ = end_char; *p = 0; return true; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/process.h> void init_cpu_exception_handling(void) { NOT_IMPLEMENTED(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static struct sysfs_inode * sysfs_new_inode(struct sysfs_data *d) { struct sysfs_inode *i = kzalloc_obj(struct sysfs_inode); if (!i) return NULL; i->ino = d->next_inode++; return i; } static void sysfs_destroy_inode(struct sysfs_data *d, struct sysfs_inode *i) { ASSERT(get_ref_count(i) == 0); if (i->type == VFS_SYMLINK) kfree2(i->symlink.path, i->symlink.path_len); kfree_obj(i, struct sysfs_inode); } static struct sysfs_inode * sysfs_create_inode_dir(struct sysfs_data *d, struct sysfs_inode *parent) { struct sysfs_inode *i = sysfs_new_inode(d); if (!i) return NULL; i->type = VFS_DIR; list_init(&i->dir.entries_list); if (!parent) parent = i; /* root case */ if (sysfs_dir_add_entry(i, ".", i, NULL) < 0) { kfree_obj(i, struct sysfs_inode); return NULL; } if (sysfs_dir_add_entry(i, "..", parent, NULL) < 0) { struct sysfs_entry *e = list_first_obj(&i->dir.entries_list, struct sysfs_entry, lnode); sysfs_dir_remove_entry(i, e); kfree_obj(i, struct sysfs_inode); return NULL; } return i; } static struct sysfs_inode * sysfs_create_inode_file(struct sysfs_data *d, struct sysfs_inode *parent, int prop_idx) { ASSERT(parent->type == VFS_DIR); struct sysfs_inode *i = sysfs_new_inode(d); struct sysobj *obj = parent->dir.obj; void **prop_data_arr = obj->prop_data; if (!i) return NULL; i->type = VFS_FILE; i->file.obj = obj; if (obj->type) { i->file.prop = obj->type->properties[prop_idx]; i->file.prop_data = prop_data_arr[prop_idx]; } return i; } static struct sysfs_inode * sysfs_create_inode_symlink(struct sysfs_data *d, struct sysfs_inode *parent, const char *target) { struct sysfs_inode *i = sysfs_new_inode(d); char *path; size_t pl; if (!i) return NULL; pl = strlen(target); if (!(path = kmalloc(pl + 1))) { sysfs_destroy_inode(d, i); return NULL; } memcpy(path, target, pl + 1); i->type = VFS_SYMLINK; i->symlink.path_len = (u32)pl; i->symlink.path = path; return i; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/time.h> #include "devshell.h" #include "sysenter.h" void create_test_file(const char *path, int n) { char abs_path[256]; int rc; sprintf(abs_path, "%s/test_%03d", path, n); rc = creat(abs_path, 0644); DEVSHELL_CMD_ASSERT(rc > 0); close(rc); } int remove_test_file(const char *path, int n) { char abs_path[256]; sprintf(abs_path, "%s/test_%03d", path, n); return unlink(abs_path); } void remove_test_file_expecting_success(const char *path, int n) { int rc; rc = remove_test_file(path, n); DEVSHELL_CMD_ASSERT(rc == 0); } int cmd_fs_perf1(int argc, char **argv) { const int n = 1000; u64 start, end, elapsed; const char *dest_dir = argc > 0 ? argv[0] : "/tmp"; printf("Using '%s' as test dir\n", dest_dir); start = RDTSC(); for (int i = 0; i < n; i++) create_test_file(dest_dir, i); end = RDTSC(); elapsed = (end - start) / n; start = RDTSC(); printf("Avg. creat() cost: %4" PRIu64 " cycles\n", elapsed); for (int i = 0; i < n; i++) remove_test_file_expecting_success(dest_dir, i); end = RDTSC(); elapsed = (end - start) / n; printf("Avg. unlink() cost: %4" PRIu64 " cycles\n", elapsed); return 0; } int cmd_fs_perf2(int argc, char **argv) { const int n = 1024; char path[256]; char buf[1024]; int fd, rc; u64 start, end, elapsed; const char *dest_dir = argc > 0 ? argv[0] : "/tmp"; printf("Using '%s' as test dir\n", dest_dir); sprintf(path, "%s/test_file", dest_dir); fd = open(path, O_WRONLY | O_CREAT, 0644); DEVSHELL_CMD_ASSERT(fd > 0); memset(buf + 0, 'a', 256); memset(buf + 256, 'b', 256); memset(buf + 512, 'c', 256); memset(buf + 768, 'd', 256); start = RDTSC(); for (int i = 0; i < n; i++) { rc = write(fd, buf, 1024); DEVSHELL_CMD_ASSERT(rc == 1024); } end = RDTSC(); elapsed = (end - start); close(fd); printf("Tot written: %d KB\n", n); printf("Avg. cost per KB: %4" PRIu64 " cycles\n", elapsed / KB); rc = unlink(path); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } <file_sep>#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause # pylint: disable=unused-wildcard-import, bad-indentation, wildcard-import # pylint: disable=missing-function-docstring, wrong-import-position # pylint: disable=invalid-name, raise-missing-from, missing-class-docstring # pylint: disable=consider-using-f-string, global-statement import re import sys import time import signal import subprocess import threading import argparse from collections import namedtuple # Constants coming from CMake (this file gets pre-processed by CMake) RUNNERS_DIR = '@CMAKE_SOURCE_DIR@/tests/runners' KERNEL_FILE = '@KERNEL_FILE@' BUILD_DIR = '@CMAKE_BINARY_DIR@' FATPART_FILE = '@CMAKE_BINARY_DIR@/fatpart' GEN_KCOV_REPORT = '@CMAKE_BINARY_DIR@/scripts/generate_kernel_coverage_report' KERNEL_FORCE_TC_ISYSTEM = '@KERNEL_FORCE_TC_ISYSTEM@' sys.path.append(RUNNERS_DIR) from lib.utils import * from lib.detect_kvm import * from lib.env import * from lib.exceptions import * # Runtime-generated constants r_notInBase64Char = re.compile(r'[^A-Za-z0-9+/=]') # Runtime-generated types TestParamsType = namedtuple( 'TestParamsType', ['type', 'name', 'timeout'] ) # Other constants INIT_PATH = '/initrd/bin/init' DEVSHELL_PATH = '/initrd/usr/bin/devshell' KERNEL_HELLO_MSG = 'Hello from Tilck!' # Global variables # Controlled by command line g_params:TestParamsType = None # Internal state g_output = "" g_process = None g_hello_msg_found = False g_shell_exit_code = None g_dumping_gcda_files = False g_gcda_buf = None g_gcda_file = None def set_once_shell_exit_code(val: int): global g_shell_exit_code if g_shell_exit_code is None: g_shell_exit_code = val def set_once_qemu_process(p): global g_process assert(g_process is None) g_process = p def append_to_output(s: str): global g_output g_output += s def write_gcda_file_wrapper(): global g_gcda_file, g_gcda_buf if not write_gcda_file(g_gcda_file, g_gcda_buf): g_process.send_signal(signal.SIGINT) g_gcda_file = None g_gcda_buf = None def handle_hello_msg(line: str): global g_hello_msg_found if not g_hello_msg_found: g_hello_msg_found = True raw_print(line) return # Bad case msg_print("") msg_print("Detected TWICE the kernel hello msg: the machine rebooted.") msg_print("KILLING the VM.") set_once_fail_reason(Fail.reboot) g_process.send_signal(signal.SIGINT) def process_line(line: str): global g_dumping_gcda_files global g_gcda_buf global g_gcda_file stripped = line.rstrip() #raw_print(stripped) if stripped and stripped[0] == '[' and stripped.startswith('[init]'): m = re.search( r'the shell with pid ([0-9]+) exited with status: ([0-9]+)', stripped ) if m: set_once_shell_exit_code(int(m.group(2))) g_dumping_gcda_files = False raw_print(stripped) return if stripped.find(KERNEL_HELLO_MSG) != -1: handle_hello_msg(stripped) return # NOTE: we could kill the VM immediately after a kernel panic, but we'll # loose the backtrace. TODO: detect kernel panic here, but kill the VM after # some timeout (e.g. 1 sec). # # if stripped.find("KERNEL PANIC") != -1: # raw_print("[system test runner] Detected kernel panic: KILLING the VM.") # set_once_fail_reason(Fail.panic) # g_process.send_signal(signal.SIGINT) if not g_dumping_gcda_files: append_to_output(stripped + "\n") raw_print(stripped) if stripped.find(KERNEL_DUMP_GCDA_STR) != -1: g_dumping_gcda_files = True return # Dumping gcda file if not stripped: return if r_notInBase64Char.search(stripped[0]): if g_gcda_file: write_gcda_file_wrapper() g_dumping_gcda_files = False raw_print(stripped) return m = re.search(r'file: (.+)', stripped) if m: if g_gcda_file: write_gcda_file_wrapper() g_gcda_file = m.group(1) g_gcda_buf = '' else: g_gcda_buf += stripped def process_text(text: str, first_output: bool): # python's split always leaves an empty element in case of a trailing # delimiter. For example: # # "a,b,c,".split(",") # # produces # # ["a", "b", "c", ""] # # Therefore, it's always OK to discard the last line and return it, to # be used for the next (which will be appended to it). lines = text.split("\n") if first_output: # Unfortunately, newer versions of QEMU (like 4.x+) dump of ESC sequences # when the serial port is used as "monitor" in order to clear the screen, # move the cursor to 1,1 etc. We *MUST* skip those sequences because we # really really don't want the screen to be cleared between one test run # and another. if lines[0].startswith("\033c"): i = lines[0].find("SeaBIOS") if i != -1: lines[0] = lines[0][i:] # Skip until SeaBIOS else: lines[0] = lines[0][2:] # Just skip the ESC c sequence for ln in lines[:-1]: process_line(ln) return lines[-1] def run_the_vm(): global g_dumping_gcda_files global g_gcda_buf global g_gcda_file args = ['qemu-system-i386', '-m', str(VM_MEMORY_SIZE_IN_MB), '-kernel', KERNEL_FILE, '-nographic', '-device', 'isa-debug-exit,iobase=0xf4,iosize=0x04'] if is_kvm_installed(): args += ['-enable-kvm', '-cpu', 'host'] kernel_cmdline = '-sercon -noacpi ' cmdline = DEVSHELL_PATH init_opts = '-nr -e' if DUMP_COV: cmdline += ' -dcov' init_opts += ' -q' if IN_ANY_CI: kernel_cmdline += ' -sat' # enable sched alive (debug) thread if g_params.type == 'shellcmd': raw_print( "Running the VM with shell command '{}'...".format(g_params.name) ) cmdline += ' -c ' + g_params.name elif g_params.type == 'selftest': raw_print("Running the VM with selftest '{}'...".format(g_params.name)) cmdline += ' -c selftest ' + g_params.name init_opts += ' -ns' else: sys.exit(Fail.invalid_args.value) kernel_cmdline += ' -cmd {} {} -- {}'.format(INIT_PATH, init_opts, cmdline) args += ['-initrd', FATPART_FILE, '-append', kernel_cmdline] if VERBOSE: raw_print(" ".join(args)) raw_print('-' * 80) raw_print("") # Run the QEMU process by using a PIPE for its stdout p = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) set_once_qemu_process(p) # Make the `stdout` file descriptor non-blocking fh_set_blocking_mode(g_process.stdout, False) read_anything = False first_output = True start_time = time.time() incomplete_line = '' while True: text = g_process.stdout.read() # In python 3, read() will return None when there's nothing to read on # a non-blocking stream. On python 2 instead, it used to throw an IOError # and return None only in case of EOF. Now, apprently, there's no way to # detect the EOF case. Therefore, g_process.poll() is used. It returns # process' exit-code if the process terminated, otherwise None. if not text: if g_process.poll() is not None: if incomplete_line: process_line(incomplete_line) break # The process exited, we have to stop reading if not read_anything: time.sleep(0.1) continue curr_time = time.time() e = curr_time - start_time if e >= 1.0: msg_print("WARNING: got nothing in {:.2f} sec".format(e)) start_time = curr_time time.sleep(0.1) continue if not read_anything: elapsed = time.time() - start_time read_anything = True msg_print("First output after {:.2f} s".format(elapsed)) start_time = time.time() text = incomplete_line + text.decode('latin-1') incomplete_line = process_text(text, first_output) if read_anything: first_output = False raw_print('-' * 80) def generate_coverage_if_enabled(): if not DUMP_COV or not REPORT_COV: return # Just do nothing if not run_gen_coverage_report_tool(GEN_KCOV_REPORT): sys.exit(Fail.gcov_error.value) def arg_type_timeout(s): try: value = int(s) if value <= 0: raise TypeError() except: raise argparse.ArgumentTypeError("expected a positive integer") return value ############################################################################### def main(): global g_params set_runner_name("single test runner") parser = argparse.ArgumentParser() parser.add_argument( 'test_type', choices = ['selftest', 'shellcmd'], help = 'type of the test' ) parser.add_argument( 'test_name', type = str, help = 'name of the test to run' ) parser.add_argument( 'timeout', type = arg_type_timeout, help = 'max test run time before timeout (seconds)' ) parser.add_argument( 'qemu_kvm_version', nargs = "?", help = argparse.SUPPRESS ) try: args = parser.parse_args() except SystemExit: sys.exit(Fail.invalid_args.value) g_params = TestParamsType(args.test_type, args.test_name, args.timeout) if args.qemu_kvm_version: set_qemu_kvm_version(args.qemu_kvm_version) if is_cmake_opt_enabled(KERNEL_FORCE_TC_ISYSTEM): unrunnable_build_graceful_exit() detect_kvm() thread = threading.Thread(target = run_the_vm) thread.start() try: thread.join(g_params.timeout) except KeyboardInterrupt: msg_print("KeyboardInterrupt") sys.exit(Fail.user_interruption.value) if thread.is_alive(): # If we get here, after `g_params.timeout`, the test is still running if g_dumping_gcda_files: # If we're just dumping the GCDA file, wait a little more thread.join(30) if thread.is_alive(): # We have to fail with timeout set_once_fail_reason(Fail.timeout) print_timeout_kill_vm_msg(g_params.timeout) g_process.send_signal(signal.SIGINT) thread.join() if g_gcda_file: write_gcda_file_wrapper() if g_output.find("KERNEL PANIC") != -1: set_once_fail_reason(Fail.panic) if no_failures() and g_shell_exit_code != 0: if g_shell_exit_code is not None: msg_print("Shell exited with code {}.".format(g_shell_exit_code)) set_once_fail_reason(Fail.shell_no_zero_exit) else: msg_print("UNKNOWN shell exit code") set_once_fail_reason(Fail.shell_unknown_exit_code) if no_failures(): generate_coverage_if_enabled() sys.exit(get_fail_reason().value) ############################### if __name__ == '__main__': main() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/worker_thread.h> #include <tilck/mods/acpi.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_tasks") static struct worker_thread *wth_events; static struct worker_thread *wth_main; static struct worker_thread *wth_debug; ACPI_STATUS AcpiOsExecute( ACPI_EXECUTE_TYPE Type, ACPI_OSD_EXEC_CALLBACK Function, void *Context) { struct worker_thread *wth; ACPI_FUNCTION_TRACE(__FUNC__); if (!Function) return_ACPI_STATUS(AE_BAD_PARAMETER); switch (Type) { case OSL_NOTIFY_HANDLER: case OSL_GPE_HANDLER: wth = wth_events; break; case OSL_DEBUGGER_MAIN_THREAD: case OSL_DEBUGGER_EXEC_THREAD: wth = wth_debug; break; case OSL_GLOBAL_LOCK_HANDLER: /* fall-through */ case OSL_EC_POLL_HANDLER: /* fall-through */ case OSL_EC_BURST_HANDLER: /* fall-through */ default: wth = wth_main; break; } if (!wth_enqueue_on(wth, Function, Context)) panic("AcpiOsExecute: unable to enqueue job"); return_ACPI_STATUS(AE_OK); } void AcpiOsWaitEventsComplete(void) { ACPI_FUNCTION_TRACE(__FUNC__); wth_wait_for_completion(wth_events); wth_wait_for_completion(wth_main); wth_wait_for_completion(wth_debug); } static struct worker_thread * osl_create_worker_or_die(const char *name, int prio, u16 queue_size) { struct worker_thread *wth; if (!(wth = wth_create_thread(name, prio, queue_size))) panic("ACPI: unable to create worker thread '%s'", name); return wth; } ACPI_STATUS osl_init_tasks(void) { wth_events = osl_create_worker_or_die("acevents", 1, 64); wth_main = osl_create_worker_or_die("acmain", 2, 64); if (ACPI_DEBUGGER_ENABLED) wth_debug = osl_create_worker_or_die("acdebug", 3, 64); return AE_OK; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/string_util.h> #include <tilck/kernel/bintree.h> #define ALLOWED_IMBALANCE 1 #define STACK_PUSH(r) (stack[stack_size++] = (r)) #define STACK_TOP() (stack[stack_size-1]) #define STACK_POP() (stack[--stack_size]) static ALWAYS_INLINE struct bintree_node * obj_to_bintree_node(void *obj, long offset) { return obj ? (struct bintree_node *)((void *)obj + offset) : NULL; } static ALWAYS_INLINE void * bintree_node_to_obj(struct bintree_node *node, long offset) { return node ? ((void *)node - offset) : NULL; } #define OBJTN(o) (obj_to_bintree_node((o), bintree_offset)) #define NTOBJ(n) (bintree_node_to_obj((n), bintree_offset)) #define LEFT_OF(obj) ( OBJTN((obj))->left_obj ) #define RIGHT_OF(obj) ( OBJTN((obj))->right_obj ) #define HEIGHT(obj) ((obj) ? OBJTN((obj))->height : -1) static inline void update_height(struct bintree_node *node, long bintree_offset) { node->height = (u16)MAX(HEIGHT(node->left_obj), HEIGHT(node->right_obj)) + 1; } #define UPDATE_HEIGHT(n) update_height((n), bintree_offset) /* * Rotate the left child of *obj_ref [which is called `n`] clock-wise * * (n) (nl) * / \ / \ * (nl) (nr) => (nll) (n) * / \ / \ * (nll) (nlr) (nlr) (nr) */ void rotate_left_child(void **obj_ref, long bintree_offset) { ASSERT(obj_ref != NULL); ASSERT(*obj_ref != NULL); struct bintree_node *orig_node = OBJTN(*obj_ref); ASSERT(orig_node->left_obj != NULL); struct bintree_node *orig_left_child = OBJTN(orig_node->left_obj); *obj_ref = orig_node->left_obj; orig_node->left_obj = orig_left_child->right_obj; OBJTN(*obj_ref)->right_obj = NTOBJ(orig_node); UPDATE_HEIGHT(orig_node); UPDATE_HEIGHT(orig_left_child); } /* * Rotate the right child of *obj_ref counterclock-wise (symmetric function) * * (n) (nr) * / \ / \ * (nl) (nr) => (n) (nrr) * / \ / \ * (nrl) (nrr) (nl) (nrl) */ void rotate_right_child(void **obj_ref, long bintree_offset) { ASSERT(obj_ref != NULL); ASSERT(*obj_ref != NULL); struct bintree_node *orig_node = OBJTN(*obj_ref); ASSERT(orig_node->right_obj != NULL); struct bintree_node *orig_right_child = OBJTN(orig_node->right_obj); *obj_ref = orig_node->right_obj; orig_node->right_obj = orig_right_child->left_obj; OBJTN(*obj_ref)->left_obj = NTOBJ(orig_node); UPDATE_HEIGHT(orig_node); UPDATE_HEIGHT(orig_right_child); } #define ROTATE_CW_LEFT_CHILD(obj) (rotate_left_child((obj), bintree_offset)) #define ROTATE_CCW_RIGHT_CHILD(obj) (rotate_right_child((obj), bintree_offset)) #define BALANCE(obj) (balance((obj), bintree_offset)) static void balance(void **obj_ref, long bintree_offset) { ASSERT(obj_ref != NULL); if (*obj_ref == NULL) return; void *left_obj = LEFT_OF(*obj_ref); void *right_obj = RIGHT_OF(*obj_ref); int bf = HEIGHT(left_obj) - HEIGHT(right_obj); if (bf > ALLOWED_IMBALANCE) { if (HEIGHT(LEFT_OF(left_obj)) >= HEIGHT(RIGHT_OF(left_obj))) { ROTATE_CW_LEFT_CHILD(obj_ref); } else { ROTATE_CCW_RIGHT_CHILD(&LEFT_OF(*obj_ref)); ROTATE_CW_LEFT_CHILD(obj_ref); } } else if (bf < -ALLOWED_IMBALANCE) { if (HEIGHT(RIGHT_OF(right_obj)) >= HEIGHT(LEFT_OF(right_obj))) { ROTATE_CCW_RIGHT_CHILD(obj_ref); } else { ROTATE_CW_LEFT_CHILD(&RIGHT_OF(*obj_ref)); ROTATE_CCW_RIGHT_CHILD(obj_ref); } } UPDATE_HEIGHT(OBJTN(*obj_ref)); } /* * This function does the actual node removal and it's called exclusively * by bintree_remove_internal() and bintree_remove_ptr_internal() after * building the full-path from the tree's root to the node to remove. */ static void bintree_remove_internal_aux(void **root_obj_ref, void ***stack, int stack_size, long bintree_offset) { if (LEFT_OF(*root_obj_ref) && RIGHT_OF(*root_obj_ref)) { // not-leaf node void **left = &LEFT_OF(*root_obj_ref); void **right = &RIGHT_OF(*root_obj_ref); void **successor_ref = &RIGHT_OF(*root_obj_ref); int saved_stack_size = stack_size; while (LEFT_OF(*successor_ref)) { STACK_PUSH(successor_ref); successor_ref = &LEFT_OF(*successor_ref); } STACK_PUSH(successor_ref); // now *successor_ref is the smallest node at the right side of // *root_obj_ref and so it is its successor. // save *successor's right node (it has no left node!). void *successors_right = RIGHT_OF(*successor_ref); // may be NULL. // replace *root_obj_ref (to be deleted) with *successor_ref *root_obj_ref = *successor_ref; // now we have to replace *obj with its right child *successor_ref = successors_right; // balance the part of the tree up to the original value of 'obj' while (stack_size > saved_stack_size) { BALANCE(STACK_POP()); } // restore root's original left and right links OBJTN(*root_obj_ref)->left_obj = *left; OBJTN(*root_obj_ref)->right_obj = *right; } else { // leaf node: replace with its left/right child. *root_obj_ref = LEFT_OF(*root_obj_ref) ? LEFT_OF(*root_obj_ref) : RIGHT_OF(*root_obj_ref); } while (stack_size > 0) BALANCE(STACK_POP()); } void * bintree_get_first_obj_internal(void *root_obj, long bintree_offset) { if (!root_obj) return NULL; while (LEFT_OF(root_obj) != NULL) root_obj = LEFT_OF(root_obj); return root_obj; } void * bintree_get_last_obj_internal(void *root_obj, long bintree_offset) { if (!root_obj) return NULL; while (RIGHT_OF(root_obj) != NULL) root_obj = RIGHT_OF(root_obj); return root_obj; } static ALWAYS_INLINE long bintree_insrem_ptr_cmp(const void *a, const void *b, long field_off) { const void *f1 = a + field_off; const void *f2 = b + field_off; return *(long *)f1 - *(long *)f2; } static ALWAYS_INLINE long bintree_find_ptr_cmp(const void *obj, const void *val, long field_off) { long obj_field_val = *(long *)((const void *)obj + field_off); return obj_field_val - (long)val; } /* * A powerful macro containing the common code between insert and remove. * Briefly, it finds the place where the given `obj_or_value` is (remove) * or will be (insert), leaving the node-to-root path in the explicit * stack (assumed to exist). * * This common code has been implemented as a "dirty macro" because a * proper C implementation using a function and a dedicated structure * for the stack caused an overhead of about 2% due to the necessary * indirections (even with -O3 and ALWAYS_INLINE). All the possible * alternatives were: * * - keeping duplicate code between insert and remove * * - sharing the code with a C function + bintree_stack struct and * paying 2% overhead for that luxory * * - sharing the code with a macro getting 0% overhead but living * with the potential problems that macros like that might cause * when the code is changed often enough */ #define AVL_BUILD_PATH_TO_OBJ() \ do { \ ASSERT(root_obj_ref != NULL); \ STACK_PUSH(root_obj_ref); \ \ while (*STACK_TOP()) { \ \ long c; \ void **obj_ref = STACK_TOP(); \ struct bintree_node *node = OBJTN(*obj_ref); \ \ if (!(c = CMP(*obj_ref, obj_or_value))) \ break; \ \ STACK_PUSH(c < 0 ? &node->right_obj : &node->left_obj); \ } \ } while (0) /* First, instantiate the generic find, insert and remove functions */ #define BINTREE_PTR_FUNCS 0 #include "avl_find.c.h" #include "avl_insert.c.h" #include "avl_remove.c.h" #undef BINTREE_PTR_FUNCS /* Then, instantiate the specialized versions of those functions */ #define BINTREE_PTR_FUNCS 1 #include "avl_find.c.h" #include "avl_insert.c.h" #include "avl_remove.c.h" #undef BINTREE_PTR_FUNCS #include <tilck/common/norec.h> int bintree_in_order_visit_internal(void *obj, bintree_visit_cb visit_cb, void *visit_cb_arg, long bintree_offset, bool reverse) { int r; if (!obj) return 0; CREATE_SHADOW_STACK(MAX_TREE_HEIGHT, 1); SIMULATE_CALL1(obj); NOREC_LOOP_BEGIN { obj = LOAD_ARG_FROM_STACK(1, void *); void *left_obj = LIKELY(!reverse) ? LEFT_OF(obj) : RIGHT_OF(obj); void *right_obj = LIKELY(!reverse) ? RIGHT_OF(obj) : LEFT_OF(obj); HANDLE_SIMULATED_RETURN(); if (left_obj) SIMULATE_CALL1(left_obj); if ((r = visit_cb(obj, visit_cb_arg))) return r; if (right_obj) SIMULATE_CALL1(right_obj); SIMULATE_RETURN_NULL(); } NOREC_LOOP_END return 0; } /* Re-define STACK_VAR and STACK_SIZE_VAR in order to use them from `ctx` */ #undef STACK_VAR #undef STACK_SIZE_VAR #define STACK_VAR ctx->stack #define STACK_SIZE_VAR ctx->stack_size #include <tilck/common/norec.h> void bintree_in_order_visit_start_internal(struct bintree_walk_ctx *ctx, void *obj, long bintree_offset, bool reverse) { *ctx = (struct bintree_walk_ctx) { .bintree_offset = bintree_offset, .obj = obj, .reverse = reverse, .next_called = false }; INIT_SHADOW_STACK(); } void * bintree_in_order_visit_next(struct bintree_walk_ctx *ctx) { /* * This declaration is necessary to make the LEFT_OF() and RIGHT_OF() macros * to work. NOTE: in *no* case this function might have stack variables other * than just aliases of variables taken from `ctx`. That's because it has to * support our simple yield mechanism: all of its state *must be* in `ctx`. */ const long bintree_offset = ctx->bintree_offset; if (UNLIKELY(!ctx->next_called)) { /* * When this function is called for the time for a given context, an * initial "call" has to be made in order to create the first frame in our * explicit stack. */ ctx->next_called = true; if (LIKELY(ctx->obj != NULL)) SIMULATE_CALL1(ctx->obj); } NOREC_LOOP_BEGIN { void *obj = LOAD_ARG_FROM_STACK(1, void *); void *left_obj = LIKELY(!ctx->reverse) ? LEFT_OF(obj) : RIGHT_OF(obj); void *right_obj = LIKELY(!ctx->reverse) ? RIGHT_OF(obj) : LEFT_OF(obj); HANDLE_SIMULATED_RETURN(); if (left_obj) SIMULATE_CALL1(left_obj); SIMULATE_YIELD(obj); if (right_obj) SIMULATE_CALL1(right_obj); SIMULATE_RETURN_NULL(); } NOREC_LOOP_END return NULL; } <file_sep>/****************************************************************************** * * Module Name: tbdata - Table manager data structure functions * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "actables.h" #include "acevents.h" #define _COMPONENT ACPI_TABLES ACPI_MODULE_NAME ("tbdata") /* Local prototypes */ static ACPI_STATUS AcpiTbCheckDuplication ( ACPI_TABLE_DESC *TableDesc, UINT32 *TableIndex); static BOOLEAN AcpiTbCompareTables ( ACPI_TABLE_DESC *TableDesc, UINT32 TableIndex); /******************************************************************************* * * FUNCTION: AcpiTbCompareTables * * PARAMETERS: TableDesc - Table 1 descriptor to be compared * TableIndex - Index of table 2 to be compared * * RETURN: TRUE if both tables are identical. * * DESCRIPTION: This function compares a table with another table that has * already been installed in the root table list. * ******************************************************************************/ static BOOLEAN AcpiTbCompareTables ( ACPI_TABLE_DESC *TableDesc, UINT32 TableIndex) { ACPI_STATUS Status = AE_OK; BOOLEAN IsIdentical; ACPI_TABLE_HEADER *Table; UINT32 TableLength; UINT8 TableFlags; Status = AcpiTbAcquireTable (&AcpiGbl_RootTableList.Tables[TableIndex], &Table, &TableLength, &TableFlags); if (ACPI_FAILURE (Status)) { return (FALSE); } /* * Check for a table match on the entire table length, * not just the header. */ IsIdentical = (BOOLEAN)((TableDesc->Length != TableLength || memcmp (TableDesc->Pointer, Table, TableLength)) ? FALSE : TRUE); /* Release the acquired table */ AcpiTbReleaseTable (Table, TableLength, TableFlags); return (IsIdentical); } /******************************************************************************* * * FUNCTION: AcpiTbInitTableDescriptor * * PARAMETERS: TableDesc - Table descriptor * Address - Physical address of the table * Flags - Allocation flags of the table * Table - Pointer to the table * * RETURN: None * * DESCRIPTION: Initialize a new table descriptor * ******************************************************************************/ void AcpiTbInitTableDescriptor ( ACPI_TABLE_DESC *TableDesc, ACPI_PHYSICAL_ADDRESS Address, UINT8 Flags, ACPI_TABLE_HEADER *Table) { /* * Initialize the table descriptor. Set the pointer to NULL, since the * table is not fully mapped at this time. */ memset (TableDesc, 0, sizeof (ACPI_TABLE_DESC)); TableDesc->Address = Address; TableDesc->Length = Table->Length; TableDesc->Flags = Flags; ACPI_MOVE_32_TO_32 (TableDesc->Signature.Ascii, Table->Signature); } /******************************************************************************* * * FUNCTION: AcpiTbAcquireTable * * PARAMETERS: TableDesc - Table descriptor * TablePtr - Where table is returned * TableLength - Where table length is returned * TableFlags - Where table allocation flags are returned * * RETURN: Status * * DESCRIPTION: Acquire an ACPI table. It can be used for tables not * maintained in the AcpiGbl_RootTableList. * ******************************************************************************/ ACPI_STATUS AcpiTbAcquireTable ( ACPI_TABLE_DESC *TableDesc, ACPI_TABLE_HEADER **TablePtr, UINT32 *TableLength, UINT8 *TableFlags) { ACPI_TABLE_HEADER *Table = NULL; switch (TableDesc->Flags & ACPI_TABLE_ORIGIN_MASK) { case ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL: Table = AcpiOsMapMemory (TableDesc->Address, TableDesc->Length); break; case ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL: case ACPI_TABLE_ORIGIN_EXTERNAL_VIRTUAL: Table = ACPI_CAST_PTR (ACPI_TABLE_HEADER, ACPI_PHYSADDR_TO_PTR (TableDesc->Address)); break; default: break; } /* Table is not valid yet */ if (!Table) { return (AE_NO_MEMORY); } /* Fill the return values */ *TablePtr = Table; *TableLength = TableDesc->Length; *TableFlags = TableDesc->Flags; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiTbReleaseTable * * PARAMETERS: Table - Pointer for the table * TableLength - Length for the table * TableFlags - Allocation flags for the table * * RETURN: None * * DESCRIPTION: Release a table. The inverse of AcpiTbAcquireTable(). * ******************************************************************************/ void AcpiTbReleaseTable ( ACPI_TABLE_HEADER *Table, UINT32 TableLength, UINT8 TableFlags) { switch (TableFlags & ACPI_TABLE_ORIGIN_MASK) { case ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL: AcpiOsUnmapMemory (Table, TableLength); break; case ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL: case ACPI_TABLE_ORIGIN_EXTERNAL_VIRTUAL: default: break; } } /******************************************************************************* * * FUNCTION: AcpiTbAcquireTempTable * * PARAMETERS: TableDesc - Table descriptor to be acquired * Address - Address of the table * Flags - Allocation flags of the table * * RETURN: Status * * DESCRIPTION: This function validates the table header to obtain the length * of a table and fills the table descriptor to make its state as * "INSTALLED". Such a table descriptor is only used for verified * installation. * ******************************************************************************/ ACPI_STATUS AcpiTbAcquireTempTable ( ACPI_TABLE_DESC *TableDesc, ACPI_PHYSICAL_ADDRESS Address, UINT8 Flags) { ACPI_TABLE_HEADER *TableHeader; switch (Flags & ACPI_TABLE_ORIGIN_MASK) { case ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL: /* Get the length of the full table from the header */ TableHeader = AcpiOsMapMemory (Address, sizeof (ACPI_TABLE_HEADER)); if (!TableHeader) { return (AE_NO_MEMORY); } AcpiTbInitTableDescriptor (TableDesc, Address, Flags, TableHeader); AcpiOsUnmapMemory (TableHeader, sizeof (ACPI_TABLE_HEADER)); return (AE_OK); case ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL: case ACPI_TABLE_ORIGIN_EXTERNAL_VIRTUAL: TableHeader = ACPI_CAST_PTR (ACPI_TABLE_HEADER, ACPI_PHYSADDR_TO_PTR (Address)); if (!TableHeader) { return (AE_NO_MEMORY); } AcpiTbInitTableDescriptor (TableDesc, Address, Flags, TableHeader); return (AE_OK); default: break; } /* Table is not valid yet */ return (AE_NO_MEMORY); } /******************************************************************************* * * FUNCTION: AcpiTbReleaseTempTable * * PARAMETERS: TableDesc - Table descriptor to be released * * RETURN: Status * * DESCRIPTION: The inverse of AcpiTbAcquireTempTable(). * *****************************************************************************/ void AcpiTbReleaseTempTable ( ACPI_TABLE_DESC *TableDesc) { /* * Note that the .Address is maintained by the callers of * AcpiTbAcquireTempTable(), thus do not invoke AcpiTbUninstallTable() * where .Address will be freed. */ AcpiTbInvalidateTable (TableDesc); } /****************************************************************************** * * FUNCTION: AcpiTbValidateTable * * PARAMETERS: TableDesc - Table descriptor * * RETURN: Status * * DESCRIPTION: This function is called to validate the table, the returned * table descriptor is in "VALIDATED" state. * *****************************************************************************/ ACPI_STATUS AcpiTbValidateTable ( ACPI_TABLE_DESC *TableDesc) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (TbValidateTable); /* Validate the table if necessary */ if (!TableDesc->Pointer) { Status = AcpiTbAcquireTable (TableDesc, &TableDesc->Pointer, &TableDesc->Length, &TableDesc->Flags); if (!TableDesc->Pointer) { Status = AE_NO_MEMORY; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbInvalidateTable * * PARAMETERS: TableDesc - Table descriptor * * RETURN: None * * DESCRIPTION: Invalidate one internal ACPI table, this is the inverse of * AcpiTbValidateTable(). * ******************************************************************************/ void AcpiTbInvalidateTable ( ACPI_TABLE_DESC *TableDesc) { ACPI_FUNCTION_TRACE (TbInvalidateTable); /* Table must be validated */ if (!TableDesc->Pointer) { return_VOID; } AcpiTbReleaseTable (TableDesc->Pointer, TableDesc->Length, TableDesc->Flags); TableDesc->Pointer = NULL; return_VOID; } /****************************************************************************** * * FUNCTION: AcpiTbValidateTempTable * * PARAMETERS: TableDesc - Table descriptor * * RETURN: Status * * DESCRIPTION: This function is called to validate the table, the returned * table descriptor is in "VALIDATED" state. * *****************************************************************************/ ACPI_STATUS AcpiTbValidateTempTable ( ACPI_TABLE_DESC *TableDesc) { if (!TableDesc->Pointer && !AcpiGbl_EnableTableValidation) { /* * Only validates the header of the table. * Note that Length contains the size of the mapping after invoking * this work around, this value is required by * AcpiTbReleaseTempTable(). * We can do this because in AcpiInitTableDescriptor(), the Length * field of the installed descriptor is filled with the actual * table length obtaining from the table header. */ TableDesc->Length = sizeof (ACPI_TABLE_HEADER); } return (AcpiTbValidateTable (TableDesc)); } /******************************************************************************* * * FUNCTION: AcpiTbCheckDuplication * * PARAMETERS: TableDesc - Table descriptor * TableIndex - Where the table index is returned * * RETURN: Status * * DESCRIPTION: Avoid installing duplicated tables. However table override and * user aided dynamic table load is allowed, thus comparing the * address of the table is not sufficient, and checking the entire * table content is required. * ******************************************************************************/ static ACPI_STATUS AcpiTbCheckDuplication ( ACPI_TABLE_DESC *TableDesc, UINT32 *TableIndex) { UINT32 i; ACPI_FUNCTION_TRACE (TbCheckDuplication); /* Check if table is already registered */ for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; ++i) { /* Do not compare with unverified tables */ if (!(AcpiGbl_RootTableList.Tables[i].Flags & ACPI_TABLE_IS_VERIFIED)) { continue; } /* * Check for a table match on the entire table length, * not just the header. */ if (!AcpiTbCompareTables (TableDesc, i)) { continue; } /* * Note: the current mechanism does not unregister a table if it is * dynamically unloaded. The related namespace entries are deleted, * but the table remains in the root table list. * * The assumption here is that the number of different tables that * will be loaded is actually small, and there is minimal overhead * in just keeping the table in case it is needed again. * * If this assumption changes in the future (perhaps on large * machines with many table load/unload operations), tables will * need to be unregistered when they are unloaded, and slots in the * root table list should be reused when empty. */ if (AcpiGbl_RootTableList.Tables[i].Flags & ACPI_TABLE_IS_LOADED) { /* Table is still loaded, this is an error */ return_ACPI_STATUS (AE_ALREADY_EXISTS); } else { *TableIndex = i; return_ACPI_STATUS (AE_CTRL_TERMINATE); } } /* Indicate no duplication to the caller */ return_ACPI_STATUS (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiTbVerifyTempTable * * PARAMETERS: TableDesc - Table descriptor * Signature - Table signature to verify * TableIndex - Where the table index is returned * * RETURN: Status * * DESCRIPTION: This function is called to validate and verify the table, the * returned table descriptor is in "VALIDATED" state. * Note that 'TableIndex' is required to be set to !NULL to * enable duplication check. * *****************************************************************************/ ACPI_STATUS AcpiTbVerifyTempTable ( ACPI_TABLE_DESC *TableDesc, char *Signature, UINT32 *TableIndex) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (TbVerifyTempTable); /* Validate the table */ Status = AcpiTbValidateTempTable (TableDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (AE_NO_MEMORY); } /* If a particular signature is expected (DSDT/FACS), it must match */ if (Signature && !ACPI_COMPARE_NAMESEG (&TableDesc->Signature, Signature)) { ACPI_BIOS_ERROR ((AE_INFO, "Invalid signature 0x%X for ACPI table, expected [%s]", TableDesc->Signature.Integer, Signature)); Status = AE_BAD_SIGNATURE; goto InvalidateAndExit; } if (AcpiGbl_EnableTableValidation) { /* Verify the checksum */ Status = AcpiTbVerifyChecksum (TableDesc->Pointer, TableDesc->Length); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, AE_NO_MEMORY, "%4.4s 0x%8.8X%8.8X" " Attempted table install failed", AcpiUtValidNameseg (TableDesc->Signature.Ascii) ? TableDesc->Signature.Ascii : "????", ACPI_FORMAT_UINT64 (TableDesc->Address))); goto InvalidateAndExit; } /* Avoid duplications */ if (TableIndex) { Status = AcpiTbCheckDuplication (TableDesc, TableIndex); if (ACPI_FAILURE (Status)) { if (Status != AE_CTRL_TERMINATE) { ACPI_EXCEPTION ((AE_INFO, Status, "%4.4s 0x%8.8X%8.8X" " Table is already loaded", AcpiUtValidNameseg (TableDesc->Signature.Ascii) ? TableDesc->Signature.Ascii : "????", ACPI_FORMAT_UINT64 (TableDesc->Address))); } goto InvalidateAndExit; } } TableDesc->Flags |= ACPI_TABLE_IS_VERIFIED; } return_ACPI_STATUS (Status); InvalidateAndExit: AcpiTbInvalidateTable (TableDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbResizeRootTableList * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Expand the size of global table array * ******************************************************************************/ ACPI_STATUS AcpiTbResizeRootTableList ( void) { ACPI_TABLE_DESC *Tables; UINT32 TableCount; UINT32 CurrentTableCount, MaxTableCount; UINT32 i; ACPI_FUNCTION_TRACE (TbResizeRootTableList); /* AllowResize flag is a parameter to AcpiInitializeTables */ if (!(AcpiGbl_RootTableList.Flags & ACPI_ROOT_ALLOW_RESIZE)) { ACPI_ERROR ((AE_INFO, "Resize of Root Table Array is not allowed")); return_ACPI_STATUS (AE_SUPPORT); } /* Increase the Table Array size */ if (AcpiGbl_RootTableList.Flags & ACPI_ROOT_ORIGIN_ALLOCATED) { TableCount = AcpiGbl_RootTableList.MaxTableCount; } else { TableCount = AcpiGbl_RootTableList.CurrentTableCount; } MaxTableCount = TableCount + ACPI_ROOT_TABLE_SIZE_INCREMENT; Tables = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) MaxTableCount) * sizeof (ACPI_TABLE_DESC)); if (!Tables) { ACPI_ERROR ((AE_INFO, "Could not allocate new root table array")); return_ACPI_STATUS (AE_NO_MEMORY); } /* Copy and free the previous table array */ CurrentTableCount = 0; if (AcpiGbl_RootTableList.Tables) { for (i = 0; i < TableCount; i++) { if (AcpiGbl_RootTableList.Tables[i].Address) { memcpy (Tables + CurrentTableCount, AcpiGbl_RootTableList.Tables + i, sizeof (ACPI_TABLE_DESC)); CurrentTableCount++; } } if (AcpiGbl_RootTableList.Flags & ACPI_ROOT_ORIGIN_ALLOCATED) { ACPI_FREE (AcpiGbl_RootTableList.Tables); } } AcpiGbl_RootTableList.Tables = Tables; AcpiGbl_RootTableList.MaxTableCount = MaxTableCount; AcpiGbl_RootTableList.CurrentTableCount = CurrentTableCount; AcpiGbl_RootTableList.Flags |= ACPI_ROOT_ORIGIN_ALLOCATED; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiTbGetNextTableDescriptor * * PARAMETERS: TableIndex - Where table index is returned * TableDesc - Where table descriptor is returned * * RETURN: Status and table index/descriptor. * * DESCRIPTION: Allocate a new ACPI table entry to the global table list * ******************************************************************************/ ACPI_STATUS AcpiTbGetNextTableDescriptor ( UINT32 *TableIndex, ACPI_TABLE_DESC **TableDesc) { ACPI_STATUS Status; UINT32 i; /* Ensure that there is room for the table in the Root Table List */ if (AcpiGbl_RootTableList.CurrentTableCount >= AcpiGbl_RootTableList.MaxTableCount) { Status = AcpiTbResizeRootTableList(); if (ACPI_FAILURE (Status)) { return (Status); } } i = AcpiGbl_RootTableList.CurrentTableCount; AcpiGbl_RootTableList.CurrentTableCount++; if (TableIndex) { *TableIndex = i; } if (TableDesc) { *TableDesc = &AcpiGbl_RootTableList.Tables[i]; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiTbTerminate * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Delete all internal ACPI tables * ******************************************************************************/ void AcpiTbTerminate ( void) { UINT32 i; ACPI_FUNCTION_TRACE (TbTerminate); (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); /* Delete the individual tables */ for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; i++) { AcpiTbUninstallTable (&AcpiGbl_RootTableList.Tables[i]); } /* * Delete the root table array if allocated locally. Array cannot be * mapped, so we don't need to check for that flag. */ if (AcpiGbl_RootTableList.Flags & ACPI_ROOT_ORIGIN_ALLOCATED) { ACPI_FREE (AcpiGbl_RootTableList.Tables); } AcpiGbl_RootTableList.Tables = NULL; AcpiGbl_RootTableList.Flags = 0; AcpiGbl_RootTableList.CurrentTableCount = 0; ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "ACPI Tables freed\n")); (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiTbDeleteNamespaceByOwner * * PARAMETERS: TableIndex - Table index * * RETURN: Status * * DESCRIPTION: Delete all namespace objects created when this table was loaded. * ******************************************************************************/ ACPI_STATUS AcpiTbDeleteNamespaceByOwner ( UINT32 TableIndex) { ACPI_OWNER_ID OwnerId; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (TbDeleteNamespaceByOwner); Status = AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (TableIndex >= AcpiGbl_RootTableList.CurrentTableCount) { /* The table index does not exist */ (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (AE_NOT_EXIST); } /* Get the owner ID for this table, used to delete namespace nodes */ OwnerId = AcpiGbl_RootTableList.Tables[TableIndex].OwnerId; (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); /* * Need to acquire the namespace writer lock to prevent interference * with any concurrent namespace walks. The interpreter must be * released during the deletion since the acquisition of the deletion * lock may block, and also since the execution of a namespace walk * must be allowed to use the interpreter. */ Status = AcpiUtAcquireWriteLock (&AcpiGbl_NamespaceRwLock); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiNsDeleteNamespaceByOwner (OwnerId); AcpiUtReleaseWriteLock (&AcpiGbl_NamespaceRwLock); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbAllocateOwnerId * * PARAMETERS: TableIndex - Table index * * RETURN: Status * * DESCRIPTION: Allocates OwnerId in TableDesc * ******************************************************************************/ ACPI_STATUS AcpiTbAllocateOwnerId ( UINT32 TableIndex) { ACPI_STATUS Status = AE_BAD_PARAMETER; ACPI_FUNCTION_TRACE (TbAllocateOwnerId); (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (TableIndex < AcpiGbl_RootTableList.CurrentTableCount) { Status = AcpiUtAllocateOwnerId ( &(AcpiGbl_RootTableList.Tables[TableIndex].OwnerId)); } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbReleaseOwnerId * * PARAMETERS: TableIndex - Table index * * RETURN: Status * * DESCRIPTION: Releases OwnerId in TableDesc * ******************************************************************************/ ACPI_STATUS AcpiTbReleaseOwnerId ( UINT32 TableIndex) { ACPI_STATUS Status = AE_BAD_PARAMETER; ACPI_FUNCTION_TRACE (TbReleaseOwnerId); (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (TableIndex < AcpiGbl_RootTableList.CurrentTableCount) { AcpiUtReleaseOwnerId ( &(AcpiGbl_RootTableList.Tables[TableIndex].OwnerId)); Status = AE_OK; } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbGetOwnerId * * PARAMETERS: TableIndex - Table index * OwnerId - Where the table OwnerId is returned * * RETURN: Status * * DESCRIPTION: returns OwnerId for the ACPI table * ******************************************************************************/ ACPI_STATUS AcpiTbGetOwnerId ( UINT32 TableIndex, ACPI_OWNER_ID *OwnerId) { ACPI_STATUS Status = AE_BAD_PARAMETER; ACPI_FUNCTION_TRACE (TbGetOwnerId); (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (TableIndex < AcpiGbl_RootTableList.CurrentTableCount) { *OwnerId = AcpiGbl_RootTableList.Tables[TableIndex].OwnerId; Status = AE_OK; } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbIsTableLoaded * * PARAMETERS: TableIndex - Index into the root table * * RETURN: Table Loaded Flag * ******************************************************************************/ BOOLEAN AcpiTbIsTableLoaded ( UINT32 TableIndex) { BOOLEAN IsLoaded = FALSE; (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (TableIndex < AcpiGbl_RootTableList.CurrentTableCount) { IsLoaded = (BOOLEAN) (AcpiGbl_RootTableList.Tables[TableIndex].Flags & ACPI_TABLE_IS_LOADED); } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return (IsLoaded); } /******************************************************************************* * * FUNCTION: AcpiTbSetTableLoadedFlag * * PARAMETERS: TableIndex - Table index * IsLoaded - TRUE if table is loaded, FALSE otherwise * * RETURN: None * * DESCRIPTION: Sets the table loaded flag to either TRUE or FALSE. * ******************************************************************************/ void AcpiTbSetTableLoadedFlag ( UINT32 TableIndex, BOOLEAN IsLoaded) { (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); if (TableIndex < AcpiGbl_RootTableList.CurrentTableCount) { if (IsLoaded) { AcpiGbl_RootTableList.Tables[TableIndex].Flags |= ACPI_TABLE_IS_LOADED; } else { AcpiGbl_RootTableList.Tables[TableIndex].Flags &= ~ACPI_TABLE_IS_LOADED; } } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); } /******************************************************************************* * * FUNCTION: AcpiTbLoadTable * * PARAMETERS: TableIndex - Table index * ParentNode - Where table index is returned * * RETURN: Status * * DESCRIPTION: Load an ACPI table * ******************************************************************************/ ACPI_STATUS AcpiTbLoadTable ( UINT32 TableIndex, ACPI_NAMESPACE_NODE *ParentNode) { ACPI_TABLE_HEADER *Table; ACPI_STATUS Status; ACPI_OWNER_ID OwnerId; ACPI_FUNCTION_TRACE (TbLoadTable); /* * Note: Now table is "INSTALLED", it must be validated before * using. */ Status = AcpiGetTableByIndex (TableIndex, &Table); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiNsLoadTable (TableIndex, ParentNode); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Update GPEs for any new _Lxx/_Exx methods. Ignore errors. The host is * responsible for discovering any new wake GPEs by running _PRW methods * that may have been loaded by this table. */ Status = AcpiTbGetOwnerId (TableIndex, &OwnerId); if (ACPI_SUCCESS (Status)) { AcpiEvUpdateGpes (OwnerId); } /* Invoke table handler */ AcpiTbNotifyTable (ACPI_TABLE_EVENT_LOAD, Table); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbInstallAndLoadTable * * PARAMETERS: Address - Physical address of the table * Flags - Allocation flags of the table * Override - Whether override should be performed * TableIndex - Where table index is returned * * RETURN: Status * * DESCRIPTION: Install and load an ACPI table * ******************************************************************************/ ACPI_STATUS AcpiTbInstallAndLoadTable ( ACPI_PHYSICAL_ADDRESS Address, UINT8 Flags, BOOLEAN Override, UINT32 *TableIndex) { ACPI_STATUS Status; UINT32 i; ACPI_FUNCTION_TRACE (TbInstallAndLoadTable); /* Install the table and load it into the namespace */ Status = AcpiTbInstallStandardTable (Address, Flags, TRUE, Override, &i); if (ACPI_FAILURE (Status)) { goto Exit; } Status = AcpiTbLoadTable (i, AcpiGbl_RootNode); Exit: *TableIndex = i; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbUnloadTable * * PARAMETERS: TableIndex - Table index * * RETURN: Status * * DESCRIPTION: Unload an ACPI table * ******************************************************************************/ ACPI_STATUS AcpiTbUnloadTable ( UINT32 TableIndex) { ACPI_STATUS Status = AE_OK; ACPI_TABLE_HEADER *Table; ACPI_FUNCTION_TRACE (TbUnloadTable); /* Ensure the table is still loaded */ if (!AcpiTbIsTableLoaded (TableIndex)) { return_ACPI_STATUS (AE_NOT_EXIST); } /* Invoke table handler */ Status = AcpiGetTableByIndex (TableIndex, &Table); if (ACPI_SUCCESS (Status)) { AcpiTbNotifyTable (ACPI_TABLE_EVENT_UNLOAD, Table); } /* Delete the portion of the namespace owned by this table */ Status = AcpiTbDeleteNamespaceByOwner (TableIndex); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } (void) AcpiTbReleaseOwnerId (TableIndex); AcpiTbSetTableLoadedFlag (TableIndex, FALSE); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiTbNotifyTable * * PARAMETERS: Event - Table event * Table - Validated table pointer * * RETURN: None * * DESCRIPTION: Notify a table event to the users. * ******************************************************************************/ void AcpiTbNotifyTable ( UINT32 Event, void *Table) { /* Invoke table handler if present */ if (AcpiGbl_TableHandler) { (void) AcpiGbl_TableHandler (Event, Table, AcpiGbl_TableHandlerContext); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define MAX_TREE_HEIGHT 32 struct bintree_node { void *left_obj; // pointer to the left container obj void *right_obj; // pointer to the right container obj u16 height; }; static inline void bintree_node_init(struct bintree_node *node) { *node = (struct bintree_node) { .left_obj = NULL, .right_obj = NULL, .height = 0, }; } #include <tilck/common/norec.h> struct bintree_walk_ctx { DECLARE_SHADOW_STACK(MAX_TREE_HEIGHT, 1) long bintree_offset; void *obj; bool reverse; bool next_called; }; #undef STACK_VAR #undef STACK_SIZE_VAR /* * bintree_find_internal() returns true it was actually able to insert the * object and false it case an object with the same 'value' (cmp(a,b) == 0) was * already in the tree. */ bool bintree_insert_internal(void **root_obj_ref, void *obj, cmpfun_ptr cmp, // cmp(*root_obj_ref, obj) long bintree_offset); /* * bintree_find_internal() returns an obj* or NULL. * * NOTE: typeof(root_obj) usually != typeof(value_ptr) * While bintree_insert_internal() uses a compare function for comparing * pointer of objects [containing at offset +bintree_offset a bintree_node], * this function uses a compare function that compares an object* with a * generic pointer to a value. That different approach is necessary to allow * find() to be called without having to create a whole object for the value. * I.e. usually the value used to compare objects is just an integer inside * an object: in that case value_ptr is just a pointer to an integer and the * compare function needs to be able to compare those two different pointers. */ void * bintree_find_internal(void *root_obj, const void *value_ptr, cmpfun_ptr objval_cmpfun, // cmp(root_obj, value_ptr) long bintree_offset); /* * returns a pointer to the removed object (if found) or NULL. */ void * bintree_remove_internal(void **root_obj_ref, void *value_ptr, cmpfun_ptr objval_cmpfun, //cmp(*root_obj_ref,value_ptr) long bintree_offset); typedef int (*bintree_visit_cb) (void *obj, void *arg); int bintree_in_order_visit_internal(void *root_obj, bintree_visit_cb visit_cb, void *visit_cb_arg, long bintree_offset, bool reverse); void bintree_in_order_visit_start_internal(struct bintree_walk_ctx *ctx, void *obj, long bintree_offset, bool reverse); void * bintree_in_order_visit_next(struct bintree_walk_ctx *ctx); void * bintree_get_first_obj_internal(void *root_obj, long bintree_offset); void * bintree_get_last_obj_internal(void *root_obj, long bintree_offset); bool bintree_insert_ptr_internal(void **root_obj_ref, void *obj, long bintree_offset, long field_off); void * bintree_find_ptr_internal(void *root_obj, const void *value_ptr, long bintree_offset, long field_off); void * bintree_remove_ptr_internal(void **root_obj_ref, void *value_ptr, long bintree_offset, long field_off); #define bintree_insert(rootref, obj, cmpfun, struct_type, elem_name) \ bintree_insert_internal((void **)(rootref), (void*)obj, cmpfun, \ OFFSET_OF(struct_type, elem_name)) #define bintree_insert_ptr(rootref, obj, struct_type, elem_name, field_name) \ bintree_insert_ptr_internal((void **)(rootref), (void*)obj, \ OFFSET_OF(struct_type, elem_name), \ OFFSET_OF(struct_type, field_name)) /* * Find the object with key `value` according to objval_cmpfun. * The `value` will be passes as it is to `objval_cmpfun`, which will see it * as a const void * pointer. Whether `value` is a pointer to a value or the * value itself represented in a pointer, depends entirely on the caller, who * controls `objval_cmpfun`. But, it's worth mentioning that, typically, `value` * here is a pointer to a value (e.g. pointer to char array), not the value * itself. In case the value itself can fit in a pointer, usually is better to * use bintree_find_ptr() because it's faster. But WARNING: bintree_find_ptr() * treats `value` as a value, not as a pointer to a value and that's hard-coded. */ #define bintree_find(root_obj, value, objval_cmpfun, struct_type, elem_name) \ bintree_find_internal((void*)(root_obj), \ (value), (objval_cmpfun), \ OFFSET_OF(struct_type, elem_name)) /* * Find the object with key `value`, where value is a pointer-sized integer. * The comparison function is hard-coded and it just compares the given field * (`field_name`) of each obj to the given value. */ #define bintree_find_ptr(root_obj, value, struct_type, elem_name, field_name) \ bintree_find_ptr_internal((void*)(root_obj), \ TO_PTR(value), \ OFFSET_OF(struct_type, elem_name), \ OFFSET_OF(struct_type, field_name)) #define bintree_remove(rootref, value, objval_cmpfun, struct_type, elem_name) \ bintree_remove_internal((void**)(rootref), \ (value), (objval_cmpfun), \ OFFSET_OF(struct_type, elem_name)) #define bintree_remove_ptr(rootref, value, struct_type, elem_name, field_name) \ bintree_remove_ptr_internal((void**)(rootref), \ (value), \ OFFSET_OF(struct_type, elem_name), \ OFFSET_OF(struct_type, field_name)) #define bintree_in_order_visit(root_obj, cb, cb_arg, struct_type, elem_name) \ bintree_in_order_visit_internal((void *)(root_obj), \ (cb), (cb_arg), \ OFFSET_OF(struct_type, elem_name), \ false) #define bintree_in_rorder_visit(root_obj, cb, cb_arg, struct_type, elem_name) \ bintree_in_order_visit_internal((void *)(root_obj), \ (cb), (cb_arg), \ OFFSET_OF(struct_type, elem_name), \ true) #define bintree_get_first_obj(root_obj, struct_type, elem_name) \ bintree_get_first_obj_internal((void *)(root_obj), \ OFFSET_OF(struct_type, elem_name)) #define bintree_get_last_obj(root_obj, struct_type, elem_name) \ bintree_get_last_obj_internal((void *)(root_obj), \ OFFSET_OF(struct_type, elem_name)) #define bintree_in_order_visit_start(ctx, obj, struct_type, elem_name, rev) \ bintree_in_order_visit_start_internal(ctx, \ (void*)(obj), \ OFFSET_OF(struct_type, elem_name), \ rev) <file_sep>/****************************************************************************** * * Name: acefiex.h - Extra OS specific defines, etc. for EFI * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACEFIEX_H__ #define __ACEFIEX_H__ #ifndef ACPI_USE_SYSTEM_CLIBRARY typedef signed char int8_t; typedef short int int16_t; typedef int int32_t; typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; typedef COMPILER_DEPENDENT_INT64 int64_t; typedef COMPILER_DEPENDENT_UINT64 uint64_t; #endif /* ACPI_USE_SYSTEM_CLIBRARY */ #define ACPI_EFI_ERROR(a) (((INTN) a) < 0) #define ACPI_EFI_SUCCESS 0 #define ACPI_EFI_LOAD_ERROR ACPI_EFI_ERR(1) #define ACPI_EFI_INVALID_PARAMETER ACPI_EFI_ERR(2) #define ACPI_EFI_UNSUPPORTED ACPI_EFI_ERR(3) #define ACPI_EFI_BAD_BUFFER_SIZE ACPI_EFI_ERR(4) #define ACPI_EFI_BUFFER_TOO_SMALL ACPI_EFI_ERR(5) #define ACPI_EFI_NOT_READY ACPI_EFI_ERR(6) #define ACPI_EFI_DEVICE_ERROR ACPI_EFI_ERR(7) #define ACPI_EFI_WRITE_PROTECTED ACPI_EFI_ERR(8) #define ACPI_EFI_OUT_OF_RESOURCES ACPI_EFI_ERR(9) #define ACPI_EFI_VOLUME_CORRUPTED ACPI_EFI_ERR(10) #define ACPI_EFI_VOLUME_FULL ACPI_EFI_ERR(11) #define ACPI_EFI_NO_MEDIA ACPI_EFI_ERR(12) #define ACPI_EFI_MEDIA_CHANGED ACPI_EFI_ERR(13) #define ACPI_EFI_NOT_FOUND ACPI_EFI_ERR(14) #define ACPI_EFI_ACCESS_DENIED ACPI_EFI_ERR(15) #define ACPI_EFI_NO_RESPONSE ACPI_EFI_ERR(16) #define ACPI_EFI_NO_MAPPING ACPI_EFI_ERR(17) #define ACPI_EFI_TIMEOUT ACPI_EFI_ERR(18) #define ACPI_EFI_NOT_STARTED ACPI_EFI_ERR(19) #define ACPI_EFI_ALREADY_STARTED ACPI_EFI_ERR(20) #define ACPI_EFI_ABORTED ACPI_EFI_ERR(21) #define ACPI_EFI_PROTOCOL_ERROR ACPI_EFI_ERR(24) typedef UINTN ACPI_EFI_STATUS; typedef VOID *ACPI_EFI_HANDLE; typedef VOID *ACPI_EFI_EVENT; typedef struct { UINT32 Data1; UINT16 Data2; UINT16 Data3; UINT8 Data4[8]; } ACPI_EFI_GUID; typedef struct { UINT16 Year; /* 1998 - 20XX */ UINT8 Month; /* 1 - 12 */ UINT8 Day; /* 1 - 31 */ UINT8 Hour; /* 0 - 23 */ UINT8 Minute; /* 0 - 59 */ UINT8 Second; /* 0 - 59 */ UINT8 Pad1; UINT32 Nanosecond; /* 0 - 999,999,999 */ INT16 TimeZone; /* -1440 to 1440 or 2047 */ UINT8 Daylight; UINT8 Pad2; } ACPI_EFI_TIME; typedef struct _ACPI_EFI_DEVICE_PATH { UINT8 Type; UINT8 SubType; UINT8 Length[2]; } ACPI_EFI_DEVICE_PATH; typedef UINT64 ACPI_EFI_PHYSICAL_ADDRESS; typedef UINT64 ACPI_EFI_VIRTUAL_ADDRESS; typedef enum { AcpiEfiAllocateAnyPages, AcpiEfiAllocateMaxAddress, AcpiEfiAllocateAddress, AcpiEfiMaxAllocateType } ACPI_EFI_ALLOCATE_TYPE; typedef enum { AcpiEfiReservedMemoryType, AcpiEfiLoaderCode, AcpiEfiLoaderData, AcpiEfiBootServicesCode, AcpiEfiBootServicesData, AcpiEfiRuntimeServicesCode, AcpiEfiRuntimeServicesData, AcpiEfiConventionalMemory, AcpiEfiUnusableMemory, AcpiEfiACPIReclaimMemory, AcpiEfiACPIMemoryNVS, AcpiEfiMemoryMappedIO, AcpiEfiMemoryMappedIOPortSpace, AcpiEfiPalCode, AcpiEfiMaxMemoryType } ACPI_EFI_MEMORY_TYPE; /* possible caching types for the memory range */ #define ACPI_EFI_MEMORY_UC 0x0000000000000001 #define ACPI_EFI_MEMORY_WC 0x0000000000000002 #define ACPI_EFI_MEMORY_WT 0x0000000000000004 #define ACPI_EFI_MEMORY_WB 0x0000000000000008 #define ACPI_EFI_MEMORY_UCE 0x0000000000000010 /* physical memory protection on range */ #define ACPI_EFI_MEMORY_WP 0x0000000000001000 #define ACPI_EFI_MEMORY_RP 0x0000000000002000 #define ACPI_EFI_MEMORY_XP 0x0000000000004000 /* range requires a runtime mapping */ #define ACPI_EFI_MEMORY_RUNTIME 0x8000000000000000 #define ACPI_EFI_MEMORY_DESCRIPTOR_VERSION 1 typedef struct { UINT32 Type; UINT32 Pad; ACPI_EFI_PHYSICAL_ADDRESS PhysicalStart; ACPI_EFI_VIRTUAL_ADDRESS VirtualStart; UINT64 NumberOfPages; UINT64 Attribute; } ACPI_EFI_MEMORY_DESCRIPTOR; typedef struct _ACPI_EFI_TABLE_HEARDER { UINT64 Signature; UINT32 Revision; UINT32 HeaderSize; UINT32 CRC32; UINT32 Reserved; } ACPI_EFI_TABLE_HEADER; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_UNKNOWN_INTERFACE) ( void); /* * Text output protocol */ #define ACPI_SIMPLE_TEXT_OUTPUT_PROTOCOL \ { 0x387477c2, 0x69c7, 0x11d2, {0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_RESET) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, BOOLEAN ExtendedVerification); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_OUTPUT_STRING) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, CHAR16 *String); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_TEST_STRING) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, CHAR16 *String); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_QUERY_MODE) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, UINTN ModeNumber, UINTN *Columns, UINTN *Rows); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_SET_MODE) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, UINTN ModeNumber); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_SET_ATTRIBUTE) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, UINTN Attribute); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_CLEAR_SCREEN) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_SET_CURSOR_POSITION) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, UINTN Column, UINTN Row); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_TEXT_ENABLE_CURSOR) ( struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *This, BOOLEAN Enable); typedef struct { INT32 MaxMode; INT32 Mode; INT32 Attribute; INT32 CursorColumn; INT32 CursorRow; BOOLEAN CursorVisible; } ACPI_SIMPLE_TEXT_OUTPUT_MODE; typedef struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE { ACPI_EFI_TEXT_RESET Reset; ACPI_EFI_TEXT_OUTPUT_STRING OutputString; ACPI_EFI_TEXT_TEST_STRING TestString; ACPI_EFI_TEXT_QUERY_MODE QueryMode; ACPI_EFI_TEXT_SET_MODE SetMode; ACPI_EFI_TEXT_SET_ATTRIBUTE SetAttribute; ACPI_EFI_TEXT_CLEAR_SCREEN ClearScreen; ACPI_EFI_TEXT_SET_CURSOR_POSITION SetCursorPosition; ACPI_EFI_TEXT_ENABLE_CURSOR EnableCursor; ACPI_SIMPLE_TEXT_OUTPUT_MODE *Mode; } ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE; /* * Text input protocol */ #define ACPI_SIMPLE_TEXT_INPUT_PROTOCOL \ { 0x387477c1, 0x69c7, 0x11d2, {0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } typedef struct { UINT16 ScanCode; CHAR16 UnicodeChar; } ACPI_EFI_INPUT_KEY; /* * Baseline unicode control chars */ #define CHAR_NULL 0x0000 #define CHAR_BACKSPACE 0x0008 #define CHAR_TAB 0x0009 #define CHAR_LINEFEED 0x000A #define CHAR_CARRIAGE_RETURN 0x000D typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_INPUT_RESET) ( struct _ACPI_SIMPLE_INPUT_INTERFACE *This, BOOLEAN ExtendedVerification); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_INPUT_READ_KEY) ( struct _ACPI_SIMPLE_INPUT_INTERFACE *This, ACPI_EFI_INPUT_KEY *Key); typedef struct _ACPI_SIMPLE_INPUT_INTERFACE { ACPI_EFI_INPUT_RESET Reset; ACPI_EFI_INPUT_READ_KEY ReadKeyStroke; ACPI_EFI_EVENT WaitForKey; } ACPI_SIMPLE_INPUT_INTERFACE; /* * Simple file system protocol */ #define ACPI_SIMPLE_FILE_SYSTEM_PROTOCOL \ { 0x964e5b22, 0x6459, 0x11d2, {0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_VOLUME_OPEN) ( struct _ACPI_EFI_FILE_IO_INTERFACE *This, struct _ACPI_EFI_FILE_HANDLE **Root); #define ACPI_EFI_FILE_IO_INTERFACE_REVISION 0x00010000 typedef struct _ACPI_EFI_FILE_IO_INTERFACE { UINT64 Revision; ACPI_EFI_VOLUME_OPEN OpenVolume; } ACPI_EFI_FILE_IO_INTERFACE; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_OPEN) ( struct _ACPI_EFI_FILE_HANDLE *File, struct _ACPI_EFI_FILE_HANDLE **NewHandle, CHAR16 *FileName, UINT64 OpenMode, UINT64 Attributes); /* Values for OpenMode used above */ #define ACPI_EFI_FILE_MODE_READ 0x0000000000000001 #define ACPI_EFI_FILE_MODE_WRITE 0x0000000000000002 #define ACPI_EFI_FILE_MODE_CREATE 0x8000000000000000 /* Values for Attribute used above */ #define ACPI_EFI_FILE_READ_ONLY 0x0000000000000001 #define ACPI_EFI_FILE_HIDDEN 0x0000000000000002 #define ACPI_EFI_FILE_SYSTEM 0x0000000000000004 #define ACPI_EFI_FILE_RESERVIED 0x0000000000000008 #define ACPI_EFI_FILE_DIRECTORY 0x0000000000000010 #define ACPI_EFI_FILE_ARCHIVE 0x0000000000000020 #define ACPI_EFI_FILE_VALID_ATTR 0x0000000000000037 typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_CLOSE) ( struct _ACPI_EFI_FILE_HANDLE *File); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_DELETE) ( struct _ACPI_EFI_FILE_HANDLE *File); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_READ) ( struct _ACPI_EFI_FILE_HANDLE *File, UINTN *BufferSize, VOID *Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_WRITE) ( struct _ACPI_EFI_FILE_HANDLE *File, UINTN *BufferSize, VOID *Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_SET_POSITION) ( struct _ACPI_EFI_FILE_HANDLE *File, UINT64 Position); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_GET_POSITION) ( struct _ACPI_EFI_FILE_HANDLE *File, UINT64 *Position); #define ACPI_EFI_FILE_INFO_ID \ { 0x9576e92, 0x6d3f, 0x11d2, {0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } typedef struct { UINT64 Size; UINT64 FileSize; UINT64 PhysicalSize; ACPI_EFI_TIME CreateTime; ACPI_EFI_TIME LastAccessTime; ACPI_EFI_TIME ModificationTime; UINT64 Attribute; CHAR16 FileName[1]; } ACPI_EFI_FILE_INFO; #define SIZE_OF_ACPI_EFI_FILE_INFO ACPI_OFFSET(ACPI_EFI_FILE_INFO, FileName) typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_GET_INFO) ( struct _ACPI_EFI_FILE_HANDLE *File, ACPI_EFI_GUID *InformationType, UINTN *BufferSize, VOID *Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_SET_INFO) ( struct _ACPI_EFI_FILE_HANDLE *File, ACPI_EFI_GUID *InformationType, UINTN BufferSize, VOID *Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FILE_FLUSH) ( struct _ACPI_EFI_FILE_HANDLE *File); #define ACPI_EFI_FILE_HANDLE_REVISION 0x00010000 typedef struct _ACPI_EFI_FILE_HANDLE { UINT64 Revision; ACPI_EFI_FILE_OPEN Open; ACPI_EFI_FILE_CLOSE Close; ACPI_EFI_FILE_DELETE Delete; ACPI_EFI_FILE_READ Read; ACPI_EFI_FILE_WRITE Write; ACPI_EFI_FILE_GET_POSITION GetPosition; ACPI_EFI_FILE_SET_POSITION SetPosition; ACPI_EFI_FILE_GET_INFO GetInfo; ACPI_EFI_FILE_SET_INFO SetInfo; ACPI_EFI_FILE_FLUSH Flush; } ACPI_EFI_FILE_STRUCT, *ACPI_EFI_FILE_HANDLE; /* * Loaded image protocol */ #define ACPI_EFI_LOADED_IMAGE_PROTOCOL \ { 0x5B1B31A1, 0x9562, 0x11d2, {0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B} } typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_IMAGE_ENTRY_POINT) ( ACPI_EFI_HANDLE ImageHandle, struct _ACPI_EFI_SYSTEM_TABLE *SystemTable); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_IMAGE_LOAD) ( BOOLEAN BootPolicy, ACPI_EFI_HANDLE ParentImageHandle, ACPI_EFI_DEVICE_PATH *FilePath, VOID *SourceBuffer, UINTN SourceSize, ACPI_EFI_HANDLE *ImageHandle); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_IMAGE_START) ( ACPI_EFI_HANDLE ImageHandle, UINTN *ExitDataSize, CHAR16 **ExitData); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_EXIT) ( ACPI_EFI_HANDLE ImageHandle, ACPI_EFI_STATUS ExitStatus, UINTN ExitDataSize, CHAR16 *ExitData); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_IMAGE_UNLOAD) ( ACPI_EFI_HANDLE ImageHandle); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_STALL) ( UINTN Microseconds); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_SET_WATCHDOG_TIMER) ( UINTN Timeout, UINT64 WatchdogCode, UINTN DataSize, CHAR16 *WatchdogData); #define EFI_IMAGE_INFORMATION_REVISION 0x1000 typedef struct { UINT32 Revision; ACPI_EFI_HANDLE ParentHandle; struct _ACPI_EFI_SYSTEM_TABLE *SystemTable; ACPI_EFI_HANDLE DeviceHandle; ACPI_EFI_DEVICE_PATH *FilePath; VOID *Reserved; UINT32 LoadOptionsSize; VOID *LoadOptions; VOID *ImageBase; UINT64 ImageSize; ACPI_EFI_MEMORY_TYPE ImageCodeType; ACPI_EFI_MEMORY_TYPE ImageDataType; ACPI_EFI_IMAGE_UNLOAD Unload; } ACPI_EFI_LOADED_IMAGE; /* * EFI Memory */ typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_ALLOCATE_PAGES) ( ACPI_EFI_ALLOCATE_TYPE Type, ACPI_EFI_MEMORY_TYPE MemoryType, UINTN NoPages, ACPI_EFI_PHYSICAL_ADDRESS *Memory); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FREE_PAGES) ( ACPI_EFI_PHYSICAL_ADDRESS Memory, UINTN NoPages); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_GET_MEMORY_MAP) ( UINTN *MemoryMapSize, ACPI_EFI_MEMORY_DESCRIPTOR *MemoryMap, UINTN *MapKey, UINTN *DescriptorSize, UINT32 *DescriptorVersion); #define NextMemoryDescriptor(Ptr,Size) ((ACPI_EFI_MEMORY_DESCRIPTOR *) (((UINT8 *) Ptr) + Size)) typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_ALLOCATE_POOL) ( ACPI_EFI_MEMORY_TYPE PoolType, UINTN Size, VOID **Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_FREE_POOL) ( VOID *Buffer); /* * EFI Time */ typedef struct { UINT32 Resolution; UINT32 Accuracy; BOOLEAN SetsToZero; } ACPI_EFI_TIME_CAPABILITIES; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_GET_TIME) ( ACPI_EFI_TIME *Time, ACPI_EFI_TIME_CAPABILITIES *Capabilities); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_SET_TIME) ( ACPI_EFI_TIME *Time); /* * Protocol handler functions */ typedef enum { ACPI_EFI_NATIVE_INTERFACE, ACPI_EFI_PCODE_INTERFACE } ACPI_EFI_INTERFACE_TYPE; typedef enum { AcpiEfiAllHandles, AcpiEfiByRegisterNotify, AcpiEfiByProtocol } ACPI_EFI_LOCATE_SEARCH_TYPE; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_INSTALL_PROTOCOL_INTERFACE) ( ACPI_EFI_HANDLE *Handle, ACPI_EFI_GUID *Protocol, ACPI_EFI_INTERFACE_TYPE InterfaceType, VOID *Interface); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_REINSTALL_PROTOCOL_INTERFACE) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, VOID *OldInterface, VOID *NewInterface); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_UNINSTALL_PROTOCOL_INTERFACE) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, VOID *Interface); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_HANDLE_PROTOCOL) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, VOID **Interface); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_REGISTER_PROTOCOL_NOTIFY) ( ACPI_EFI_GUID *Protocol, ACPI_EFI_EVENT Event, VOID **Registration); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_LOCATE_HANDLE) ( ACPI_EFI_LOCATE_SEARCH_TYPE SearchType, ACPI_EFI_GUID *Protocol, VOID *SearchKey, UINTN *BufferSize, ACPI_EFI_HANDLE *Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_LOCATE_DEVICE_PATH) ( ACPI_EFI_GUID *Protocol, ACPI_EFI_DEVICE_PATH **DevicePath, ACPI_EFI_HANDLE *Device); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_INSTALL_CONFIGURATION_TABLE) ( ACPI_EFI_GUID *Guid, VOID *Table); #define ACPI_EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL 0x00000001 #define ACPI_EFI_OPEN_PROTOCOL_GET_PROTOCOL 0x00000002 #define ACPI_EFI_OPEN_PROTOCOL_TEST_PROTOCOL 0x00000004 #define ACPI_EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER 0x00000008 #define ACPI_EFI_OPEN_PROTOCOL_BY_DRIVER 0x00000010 #define ACPI_EFI_OPEN_PROTOCOL_EXCLUSIVE 0x00000020 typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_OPEN_PROTOCOL) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, VOID **Interface, ACPI_EFI_HANDLE AgentHandle, ACPI_EFI_HANDLE ControllerHandle, UINT32 Attributes); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_CLOSE_PROTOCOL) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, ACPI_EFI_HANDLE AgentHandle, ACPI_EFI_HANDLE ControllerHandle); typedef struct { ACPI_EFI_HANDLE AgentHandle; ACPI_EFI_HANDLE ControllerHandle; UINT32 Attributes; UINT32 OpenCount; } ACPI_EFI_OPEN_PROTOCOL_INFORMATION_ENTRY; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_OPEN_PROTOCOL_INFORMATION) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID *Protocol, ACPI_EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, UINTN *EntryCount); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_PROTOCOLS_PER_HANDLE) ( ACPI_EFI_HANDLE Handle, ACPI_EFI_GUID ***ProtocolBuffer, UINTN *ProtocolBufferCount); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_LOCATE_HANDLE_BUFFER) ( ACPI_EFI_LOCATE_SEARCH_TYPE SearchType, ACPI_EFI_GUID *Protocol, VOID *SearchKey, UINTN *NoHandles, ACPI_EFI_HANDLE **Buffer); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_LOCATE_PROTOCOL) ( ACPI_EFI_GUID *Protocol, VOID *Registration, VOID **Interface); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES) ( ACPI_EFI_HANDLE *Handle, ...); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES) ( ACPI_EFI_HANDLE Handle, ...); typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_CALCULATE_CRC32) ( VOID *Data, UINTN DataSize, UINT32 *Crc32); typedef VOID (ACPI_EFI_API *ACPI_EFI_COPY_MEM) ( VOID *Destination, VOID *Source, UINTN Length); typedef VOID (ACPI_EFI_API *ACPI_EFI_SET_MEM) ( VOID *Buffer, UINTN Size, UINT8 Value); /* * EFI Boot Services Table */ #define ACPI_EFI_BOOT_SERVICES_SIGNATURE 0x56524553544f4f42 #define ACPI_EFI_BOOT_SERVICES_REVISION (ACPI_EFI_SPECIFICATION_MAJOR_REVISION<<16) | (ACPI_EFI_SPECIFICATION_MINOR_REVISION) typedef struct _ACPI_EFI_BOOT_SERVICES { ACPI_EFI_TABLE_HEADER Hdr; #if 0 ACPI_EFI_RAISE_TPL RaiseTPL; ACPI_EFI_RESTORE_TPL RestoreTPL; #else ACPI_EFI_UNKNOWN_INTERFACE RaiseTPL; ACPI_EFI_UNKNOWN_INTERFACE RestoreTPL; #endif ACPI_EFI_ALLOCATE_PAGES AllocatePages; ACPI_EFI_FREE_PAGES FreePages; ACPI_EFI_GET_MEMORY_MAP GetMemoryMap; ACPI_EFI_ALLOCATE_POOL AllocatePool; ACPI_EFI_FREE_POOL FreePool; #if 0 ACPI_EFI_CREATE_EVENT CreateEvent; ACPI_EFI_SET_TIMER SetTimer; ACPI_EFI_WAIT_FOR_EVENT WaitForEvent; ACPI_EFI_SIGNAL_EVENT SignalEvent; ACPI_EFI_CLOSE_EVENT CloseEvent; ACPI_EFI_CHECK_EVENT CheckEvent; #else ACPI_EFI_UNKNOWN_INTERFACE CreateEvent; ACPI_EFI_UNKNOWN_INTERFACE SetTimer; ACPI_EFI_UNKNOWN_INTERFACE WaitForEvent; ACPI_EFI_UNKNOWN_INTERFACE SignalEvent; ACPI_EFI_UNKNOWN_INTERFACE CloseEvent; ACPI_EFI_UNKNOWN_INTERFACE CheckEvent; #endif ACPI_EFI_INSTALL_PROTOCOL_INTERFACE InstallProtocolInterface; ACPI_EFI_REINSTALL_PROTOCOL_INTERFACE ReinstallProtocolInterface; ACPI_EFI_UNINSTALL_PROTOCOL_INTERFACE UninstallProtocolInterface; ACPI_EFI_HANDLE_PROTOCOL HandleProtocol; ACPI_EFI_HANDLE_PROTOCOL PCHandleProtocol; ACPI_EFI_REGISTER_PROTOCOL_NOTIFY RegisterProtocolNotify; ACPI_EFI_LOCATE_HANDLE LocateHandle; ACPI_EFI_LOCATE_DEVICE_PATH LocateDevicePath; ACPI_EFI_INSTALL_CONFIGURATION_TABLE InstallConfigurationTable; ACPI_EFI_IMAGE_LOAD LoadImage; ACPI_EFI_IMAGE_START StartImage; ACPI_EFI_EXIT Exit; ACPI_EFI_IMAGE_UNLOAD UnloadImage; #if 0 ACPI_EFI_EXIT_BOOT_SERVICES ExitBootServices; ACPI_EFI_GET_NEXT_MONOTONIC_COUNT GetNextMonotonicCount; #else ACPI_EFI_UNKNOWN_INTERFACE ExitBootServices; ACPI_EFI_UNKNOWN_INTERFACE GetNextMonotonicCount; #endif ACPI_EFI_STALL Stall; ACPI_EFI_SET_WATCHDOG_TIMER SetWatchdogTimer; #if 0 ACPI_EFI_CONNECT_CONTROLLER ConnectController; ACPI_EFI_DISCONNECT_CONTROLLER DisconnectController; #else ACPI_EFI_UNKNOWN_INTERFACE ConnectController; ACPI_EFI_UNKNOWN_INTERFACE DisconnectController; #endif ACPI_EFI_OPEN_PROTOCOL OpenProtocol; ACPI_EFI_CLOSE_PROTOCOL CloseProtocol; ACPI_EFI_OPEN_PROTOCOL_INFORMATION OpenProtocolInformation; ACPI_EFI_PROTOCOLS_PER_HANDLE ProtocolsPerHandle; ACPI_EFI_LOCATE_HANDLE_BUFFER LocateHandleBuffer; ACPI_EFI_LOCATE_PROTOCOL LocateProtocol; ACPI_EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES InstallMultipleProtocolInterfaces; ACPI_EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES UninstallMultipleProtocolInterfaces; ACPI_EFI_CALCULATE_CRC32 CalculateCrc32; ACPI_EFI_COPY_MEM CopyMem; ACPI_EFI_SET_MEM SetMem; #if 0 ACPI_EFI_CREATE_EVENT_EX CreateEventEx; #else ACPI_EFI_UNKNOWN_INTERFACE CreateEventEx; #endif } ACPI_EFI_BOOT_SERVICES; /* * EFI Runtime Services Table */ #define ACPI_EFI_RUNTIME_SERVICES_SIGNATURE 0x56524553544e5552 #define ACPI_EFI_RUNTIME_SERVICES_REVISION (EFI_SPECIFICATION_MAJOR_REVISION<<16) | (EFI_SPECIFICATION_MINOR_REVISION) typedef struct _ACPI_EFI_RUNTIME_SERVICES { ACPI_EFI_TABLE_HEADER Hdr; ACPI_EFI_GET_TIME GetTime; ACPI_EFI_SET_TIME SetTime; #if 0 ACPI_EFI_GET_WAKEUP_TIME GetWakeupTime; ACPI_EFI_SET_WAKEUP_TIME SetWakeupTime; #else ACPI_EFI_UNKNOWN_INTERFACE GetWakeupTime; ACPI_EFI_UNKNOWN_INTERFACE SetWakeupTime; #endif #if 0 ACPI_EFI_SET_VIRTUAL_ADDRESS_MAP SetVirtualAddressMap; ACPI_EFI_CONVERT_POINTER ConvertPointer; #else ACPI_EFI_UNKNOWN_INTERFACE SetVirtualAddressMap; ACPI_EFI_UNKNOWN_INTERFACE ConvertPointer; #endif #if 0 ACPI_EFI_GET_VARIABLE GetVariable; ACPI_EFI_GET_NEXT_VARIABLE_NAME GetNextVariableName; ACPI_EFI_SET_VARIABLE SetVariable; #else ACPI_EFI_UNKNOWN_INTERFACE GetVariable; ACPI_EFI_UNKNOWN_INTERFACE GetNextVariableName; ACPI_EFI_UNKNOWN_INTERFACE SetVariable; #endif #if 0 ACPI_EFI_GET_NEXT_HIGH_MONO_COUNT GetNextHighMonotonicCount; ACPI_EFI_RESET_SYSTEM ResetSystem; #else ACPI_EFI_UNKNOWN_INTERFACE GetNextHighMonotonicCount; ACPI_EFI_UNKNOWN_INTERFACE ResetSystem; #endif } ACPI_EFI_RUNTIME_SERVICES; /* * EFI System Table */ /* * EFI Configuration Table and GUID definitions */ #define ACPI_TABLE_GUID \ { 0xeb9d2d30, 0x2d88, 0x11d3, {0x9a, 0x16, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d} } #define ACPI_20_TABLE_GUID \ { 0x8868e871, 0xe4f1, 0x11d3, {0xbc, 0x22, 0x0, 0x80, 0xc7, 0x3c, 0x88, 0x81} } typedef struct _ACPI_EFI_CONFIGURATION_TABLE { ACPI_EFI_GUID VendorGuid; VOID *VendorTable; } ACPI_EFI_CONFIGURATION_TABLE; #define ACPI_EFI_SYSTEM_TABLE_SIGNATURE 0x5453595320494249 #define ACPI_EFI_SYSTEM_TABLE_REVISION (ACPI_EFI_SPECIFICATION_MAJOR_REVISION<<16) | (ACPI_EFI_SPECIFICATION_MINOR_REVISION) typedef struct _ACPI_EFI_SYSTEM_TABLE { ACPI_EFI_TABLE_HEADER Hdr; CHAR16 *FirmwareVendor; UINT32 FirmwareRevision; ACPI_EFI_HANDLE ConsoleInHandle; ACPI_SIMPLE_INPUT_INTERFACE *ConIn; ACPI_EFI_HANDLE ConsoleOutHandle; ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut; ACPI_EFI_HANDLE StandardErrorHandle; ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE *StdErr; ACPI_EFI_RUNTIME_SERVICES *RuntimeServices; ACPI_EFI_BOOT_SERVICES *BootServices; UINTN NumberOfTableEntries; ACPI_EFI_CONFIGURATION_TABLE *ConfigurationTable; } ACPI_EFI_SYSTEM_TABLE; /* * EFI PCI I/O Protocol */ #define ACPI_EFI_PCI_IO_PROTOCOL \ { 0x4cf5b200, 0x68b8, 0x4ca5, {0x9e, 0xec, 0xb2, 0x3e, 0x3f, 0x50, 0x2, 0x9a} } typedef enum { AcpiEfiPciIoWidthUint8 = 0, AcpiEfiPciIoWidthUint16, AcpiEfiPciIoWidthUint32, AcpiEfiPciIoWidthUint64, AcpiEfiPciIoWidthFifoUint8, AcpiEfiPciIoWidthFifoUint16, AcpiEfiPciIoWidthFifoUint32, AcpiEfiPciIoWidthFifoUint64, AcpiEfiPciIoWidthFillUint8, AcpiEfiPciIoWidthFillUint16, AcpiEfiPciIoWidthFillUint32, AcpiEfiPciIoWidthFillUint64, AcpiEfiPciIoWidthMaximum } ACPI_EFI_PCI_IO_PROTOCOL_WIDTH; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_PCI_IO_PROTOCOL_CONFIG)( struct _ACPI_EFI_PCI_IO *This, ACPI_EFI_PCI_IO_PROTOCOL_WIDTH Width, UINT32 Offset, UINTN Count, VOID *Buffer); typedef struct { ACPI_EFI_PCI_IO_PROTOCOL_CONFIG Read; ACPI_EFI_PCI_IO_PROTOCOL_CONFIG Write; } ACPI_EFI_PCI_IO_PROTOCOL_CONFIG_ACCESS; typedef ACPI_EFI_STATUS (ACPI_EFI_API *ACPI_EFI_PCI_IO_PROTOCOL_GET_LOCATION)( struct _ACPI_EFI_PCI_IO *This, UINTN *SegmentNumber, UINTN *BusNumber, UINTN *DeviceNumber, UINTN *FunctionNumber); typedef struct _ACPI_EFI_PCI_IO { ACPI_EFI_UNKNOWN_INTERFACE PollMem; ACPI_EFI_UNKNOWN_INTERFACE PollIo; ACPI_EFI_UNKNOWN_INTERFACE Mem; ACPI_EFI_UNKNOWN_INTERFACE Io; ACPI_EFI_PCI_IO_PROTOCOL_CONFIG_ACCESS Pci; ACPI_EFI_UNKNOWN_INTERFACE CopyMem; ACPI_EFI_UNKNOWN_INTERFACE Map; ACPI_EFI_UNKNOWN_INTERFACE Unmap; ACPI_EFI_UNKNOWN_INTERFACE AllocateBuffer; ACPI_EFI_UNKNOWN_INTERFACE FreeBuffer; ACPI_EFI_UNKNOWN_INTERFACE Flush; ACPI_EFI_PCI_IO_PROTOCOL_GET_LOCATION GetLocation; ACPI_EFI_UNKNOWN_INTERFACE Attributes; ACPI_EFI_UNKNOWN_INTERFACE GetBarAttributes; ACPI_EFI_UNKNOWN_INTERFACE SetBarAttributes; UINT64 RomSize; VOID *RomImage; } ACPI_EFI_PCI_IO; /* FILE abstraction */ union acpi_efi_file { struct _ACPI_EFI_FILE_HANDLE File; struct _ACPI_SIMPLE_TEXT_OUTPUT_INTERFACE ConOut; struct _ACPI_SIMPLE_INPUT_INTERFACE ConIn; }; /* EFI definitions */ #if defined(_GNU_EFI) || defined(_EDK2_EFI) /* * This is needed to hide platform specific code from ACPICA */ UINT64 ACPI_EFI_API DivU64x32 ( UINT64 Dividend, UINTN Divisor, UINTN *Remainder); UINT64 ACPI_EFI_API MultU64x32 ( UINT64 Multiplicand, UINTN Multiplier); UINT64 ACPI_EFI_API LShiftU64 ( UINT64 Operand, UINTN Count); UINT64 ACPI_EFI_API RShiftU64 ( UINT64 Operand, UINTN Count); /* * EFI specific prototypes */ ACPI_EFI_STATUS efi_main ( ACPI_EFI_HANDLE Image, ACPI_EFI_SYSTEM_TABLE *SystemTab); int acpi_main ( int argc, char *argv[]); #endif extern ACPI_EFI_GUID AcpiGbl_LoadedImageProtocol; extern ACPI_EFI_GUID AcpiGbl_TextInProtocol; extern ACPI_EFI_GUID AcpiGbl_TextOutProtocol; extern ACPI_EFI_GUID AcpiGbl_FileSystemProtocol; extern ACPI_EFI_GUID AcpiGbl_GenericFileInfo; #endif /* __ACEFIEX_H__ */ <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ZLIB_VER="1.2.11" function download_zlib { local ver="$ZLIB_VER" local tarname="zlib-$ver.tgz" local url="https://github.com/madler/zlib" download_git_repo_in_cache "$url" v$ver $tarname zlib extract_cachefile_tar_gz $tarname -- } all_funcs_list+=(build_zlib) function build_zlib { pushd $ARCH if ! [ -d zlib ]; then show_work_on_component_msg "ZLIB" reset_cc_vars download_zlib cd zlib local p="$TC/$ARCH/zlib/install" if [[ "$HOST_ARCH" == "$ARCH" ]]; then export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" else # Default case export CROSS_PREFIX="${ARCH_GCC_TC}-linux-" set_cc_vars_to_tc fi run_command2 "./configure --prefix='$p' --static" configure.log run_command2 "make -j$BUILD_PAR" build.log run_command2 "make install" install.log export CROSS_PREFIX="" else show_skip_component_msg "ZLIB" fi popd } function build_zlib_installed_status { if [ -d $TC/$ARCH/zlib ]; then if [ -f $TC/$ARCH/zlib/install/lib/libz.a ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once extern "C" { #include <tilck/common/basic_defs.h> void init_pageframe_allocator(); void init_kmalloc(); void init_worker_threads(); void init_kmalloc_for_tests(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct tss_entry { u32 prev_tss; /* ptr to the previous TSS: unused in Tilck */ u32 esp0; /* ESP to use when we change to kernel mode */ u32 ss0; /* SS to use when we change to kernel mode */ /* Unused registers in Tilck (the hardware task-switch is not used) */ u32 esp1; u32 ss1; u32 esp2; u32 ss2; u32 cr3; u32 eip; u32 eflags; u32 eax; u32 ecx; u32 edx; u32 ebx; u32 esp; u32 ebp; u32 esi; u32 edi; u32 es; u32 cs; u32 ss; u32 ds; u32 fs; u32 gs; u32 ldt; u16 trap; u16 iomap_base; } PACKED; <file_sep>/* * Base64 encoding/decoding (RFC1341) * Copyright (c) 2005, <NAME> <<EMAIL>> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef BASE64_H #define BASE64_H unsigned char * base64_encode(const unsigned char *src, size_t len, size_t *out_len); unsigned char * base64_decode(const unsigned char *src, size_t len, size_t *out_len); #endif /* BASE64_H */ <file_sep>from cmake_row import cmake_row, row_type from typing import Deque, List from collections import deque def read_file(filepath): with open(filepath, 'r') as f: return f.readlines() def parse_rows(file_lines: List[str]) -> List[cmake_row]: cmake_rows: List[cmake_row] = [] comment_list: Deque[str] = deque() for i, line in enumerate(file_lines): current_row = cmake_row(line, i) cmake_rows.append(current_row) if current_row.row_type == row_type.VARIABLE: j = i-1 while j >= 0 and cmake_rows[j].row_type == row_type.SLASH_COMMENT: comment_list.appendleft(cmake_rows[j].get_val()) j -= 1 cmake_rows[i] = cmake_row(line, j, list(comment_list)) comment_list.clear() """ In this case we need a new cmake_row to handle all the new information provided by the metadata, so every cmake_row will be constructed twice. The process could also be extracted to other functions, but this respects the seperation of concerns. """ return cmake_rows def write_file(filepath: str, rows: List[cmake_row]): with open(filepath, 'w') as f: for row in rows: f.write(row.serialize() + '\n') <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_kernel.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/sched.h> extern u32 __tick_duration; extern int __tick_adj_ticks_rem; extern u32 clock_drift_adj_loop_delay; void selftest_time(void) { int drift; u32 orig_tick_duration = 0; u32 art_drift_p = 5; ulong var; if (!KRN_CLOCK_DRIFT_COMP) { printk("Skipping the test because KRN_CLOCK_DRIFT_COMP = 0.\n"); goto out; } if (clock_drift_adj_loop_delay > 60 * TIMER_HZ) { printk("Test designed to run with clock_drift_adj_loop_delay <= 60s\n"); printk("clock_drift_adj_loop_delay: %ds\n", clock_drift_adj_loop_delay / TIMER_HZ); printk("=> Skipping the artificial drift in the test\n"); art_drift_p = 0; } /* * Increase tick's actual duration by 5% in order to produce quickly a * huge clock drift. Note: consider that __tick_duration is added to the * current time, TIMER_HZ times per second. * * For example, with TIMER_HZ=100: * * td == 0.01 [ideal tick duration] * * Increasing `td` by 5%: * * td == 0.0105 * * Now after 1 second, we have an artificial drift of: * 0.0005 s * 100 = 0.05 s. * * After 20 seconds, we'll have a drift of 1 second. * * NOTE: * * A positive drift (calculated as: sys_ts - hw_ts) means that we're * going too fast and we have to add a _negative_ adjustment. * * A negative drift, means that we're lagging behind and we need to add a * _positive_ adjustment. */ if (art_drift_p) { disable_interrupts(&var); { if (!__tick_adj_ticks_rem) orig_tick_duration = __tick_duration; } enable_interrupts(&var); if (!orig_tick_duration) { printk("Cannot start the test while there's a drift compensation.\n"); return; } } printk("\n"); printk("Clock drift correction self-test\n"); printk("---------------------------------------------\n\n"); for (int t = 0; !se_is_stop_requested(); t++) { drift = clock_get_second_drift(); if (art_drift_p && t == 0) { /* Save the initial drift */ printk("NOTE: Introduce artificial drift of %d%%\n", art_drift_p); disable_interrupts(&var); { __tick_duration = orig_tick_duration * (100+art_drift_p) / 100; } enable_interrupts(&var); } else if (art_drift_p && (t == 60 || t == 180)) { printk("NOTE: Remove any artificial drift\n"); disable_interrupts(&var); { __tick_duration = orig_tick_duration; } enable_interrupts(&var); } else if (art_drift_p && t == 120) { printk("NOTE: Introduce artificial drift of -%d%%\n", art_drift_p); disable_interrupts(&var); { __tick_duration = orig_tick_duration * (100-art_drift_p) / 100; } enable_interrupts(&var); } printk(NO_PREFIX "[%06d seconds] Drift: %d\n", t, drift); kernel_sleep(TIMER_HZ); } if (art_drift_p) { disable_interrupts(&var); { __tick_duration = orig_tick_duration; } enable_interrupts(&var); } out: if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(time, se_manual, &selftest_time) void selftest_delay(void) { u64 before, after, elapsed; u32 us = 50000; /* 50 ms */ disable_preemption(); { before = get_ticks(); delay_us(us); after = get_ticks(); } enable_preemption(); elapsed = after - before; printk("Expected in ticks: %u\n", us / (1000000 / TIMER_HZ)); printk("Actual ticks: %" PRIu64 "\n", elapsed); } REGISTER_SELF_TEST(delay, se_manual, &selftest_delay) <file_sep>The file structure follows docker standards, and every container can be created by a Dockerfile that sits in a directory is named after the container's name. The reasoning behind this structure is allowing syntax highlighting for all IDEs (see [here](https://stackoverflow.com/questions/27409761/docker-multiple-dockerfiles-in-project)). To build and tag an image from the root folder of the project, just use ```bash docker build -t <username>/<container_name>:<version> \ other/containers/<container_name> ``` Then, to actually run the image in a container in interactive mode use ```bash docker run -it <username>/<container_name> bash ``` <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> /* Reader-preferring rwlock */ struct rwlock_rp { struct kmutex readers_lock; struct ksem writers_sem; int readers_count; #if DEBUG_CHECKS struct task *ex_owner; #endif }; void rwlock_rp_init(struct rwlock_rp *r); void rwlock_rp_destroy(struct rwlock_rp *r); void rwlock_rp_shlock(struct rwlock_rp *r); void rwlock_rp_shunlock(struct rwlock_rp *r); void rwlock_rp_exlock(struct rwlock_rp *r); void rwlock_rp_exunlock(struct rwlock_rp *r); #if DEBUG_CHECKS static inline bool rwlock_rp_is_shlocked(struct rwlock_rp *r) { return r->readers_count > 0; } static inline bool rwlock_rp_holding_exlock(struct rwlock_rp *r) { return r->ex_owner == get_curr_task(); } #endif /* Writer-preferring rwlock */ struct rwlock_wp { struct task *ex_owner; struct kmutex m; struct kcond c; int r; /* readers count */ bool w; /* writer waiting */ bool rec; /* is exlock operation recursive */ u16 rc; /* recursive locking count */ }; void rwlock_wp_init(struct rwlock_wp *rw, bool recursive); void rwlock_wp_destroy(struct rwlock_wp *rw); void rwlock_wp_shlock(struct rwlock_wp *rw); void rwlock_wp_shunlock(struct rwlock_wp *rw); void rwlock_wp_exlock(struct rwlock_wp *rw); void rwlock_wp_exunlock(struct rwlock_wp *rw); #if DEBUG_CHECKS static inline bool rwlock_wp_is_shlocked(struct rwlock_wp *rw) { return rw->r > 0; } static inline bool rwlock_wp_holding_exlock(struct rwlock_wp *rw) { return rw->ex_owner == get_curr_task(); } #endif <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) # Remove -rdynamic set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS) # Options that will be used only when building the actual kernel, not when # building kernel's code for unit testing. set(ACTUAL_KERNEL_ONLY_FLAGS_LIST "") list( APPEND ACTUAL_KERNEL_ONLY_FLAGS_LIST -D__ACTUAL_TILCK_KERNEL_BINARY__ -fno-pic ${LOWLEVEL_BINARIES_FLAGS_LIST} ${DISABLE_FPU_FLAGS_LIST} ) if (KERNEL_GCOV) list(APPEND ACTUAL_KERNEL_ONLY_FLAGS_LIST -fprofile-arcs -ftest-coverage) endif() JOIN("${ACTUAL_KERNEL_ONLY_FLAGS_LIST}" ${SPACE} ACTUAL_KERNEL_ONLY_FLAGS) set(ARCH_START_FILE "start.S") set(ARCH_SOURCES_GLOB "*.S" "*.c") file(GLOB ARCH_SOURCES ${GLOB_CONF_DEP} ${ARCH_SOURCES_GLOB}) file( GLOB ARCH_FAMILY_SOURCES "${CMAKE_SOURCE_DIR}/kernel/arch/${ARCH_FAMILY}/*.c" "${CMAKE_SOURCE_DIR}/kernel/arch/${ARCH_FAMILY}/*/*.c" "${CMAKE_SOURCE_DIR}/common/arch/${ARCH_FAMILY}/*.c" ) # Override CMake's default executable output directory set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}) add_executable( tilck_unstripped ${ARCH_START_FILE} ${ARCH_SOURCES} ${ARCH_FAMILY_SOURCES} ${KERNEL_NOARCH_SOURCES} ) set( KERNEL_LINK_FLAGS_LIST -nostdlib -static -Wl,--build-id=none -Wl,--script=${KERNEL_SCRIPT} ) JOIN("${KERNEL_LINK_FLAGS_LIST}" ${SPACE} KERNEL_LINK_FLAGS) set_target_properties( tilck_unstripped PROPERTIES COMPILE_FLAGS "${KERNEL_FLAGS} ${ACTUAL_KERNEL_ONLY_FLAGS}" LINK_FLAGS "${KERNEL_LINK_FLAGS}" LINK_DEPENDS ${KERNEL_SCRIPT} ) build_all_modules(tilck_unstripped) # -lgcc is necessary for things like 64 bit integers in 32 bit mode. target_link_libraries(tilck_unstripped gcc) if (KERNEL_SYMBOLS) add_custom_command( OUTPUT ${KERNEL_FILE} COMMAND ${BUILD_SCRIPTS}/tilck_set_commit_hash ${ELFHACK} ${KERNEL_UNSTRIPPED} COMMAND ${CMAKE_STRIP} --strip-debug ${KERNEL_UNSTRIPPED} -o ${KERNEL_FILE} COMMAND elfhack32 ${KERNEL_FILE} --copy .symtab .Symtab COMMAND elfhack32 ${KERNEL_FILE} --copy .strtab .Strtab COMMAND elfhack32 ${KERNEL_FILE} --link .Symtab .Strtab COMMAND elfhack32 ${KERNEL_FILE} --rename .symtab osymtab COMMAND elfhack32 ${KERNEL_FILE} --rename .strtab ostrtab COMMAND elfhack32 ${KERNEL_FILE} --rename .Symtab .symtab COMMAND elfhack32 ${KERNEL_FILE} --rename .Strtab .strtab COMMAND elfhack32 ${KERNEL_FILE} --move-metadata COMMAND elfhack32 ${KERNEL_FILE} --drop-last-section COMMAND elfhack32 ${KERNEL_FILE} --drop-last-section COMMAND elfhack32 ${KERNEL_FILE} --set-phdr-rwx-flags 2 r DEPENDS tilck_unstripped elfhack32 ${CMAKE_BINARY_DIR}/scripts/build_apps/elfhack32 COMMENT "Preparing kernel's stripped binary" ) else() add_custom_command( OUTPUT ${KERNEL_FILE} COMMAND ${BUILD_SCRIPTS}/tilck_set_commit_hash ${ELFHACK} ${KERNEL_UNSTRIPPED} COMMAND ${CMAKE_STRIP} --strip-debug ${KERNEL_UNSTRIPPED} -o ${KERNEL_FILE} COMMAND elfhack32 ${KERNEL_FILE} --move-metadata DEPENDS elfhack32 tilck_unstripped COMMENT "Preparing kernel's stripped binary" ) endif() add_custom_target( kernel ALL DEPENDS ${KERNEL_FILE} ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> void simple_test_kthread(void *arg) { u32 i; #if !defined(NDEBUG) && !defined(RELEASE) ulong esp; ulong saved_esp = get_stack_ptr(); #endif printk("[kthread] This is a kernel thread, arg = %p\n", arg); for (i = 0; i < 128*MB; i++) { #if !defined(NDEBUG) && !defined(RELEASE) /* * This VERY IMPORTANT check ensures us that in NO WAY functions like * save_current_task_state() and kernel_context_switch() changed value * of the stack pointer. Unfortunately, we cannot reliably do this check * in RELEASE (= optimized) builds because the compiler plays with the * stack pointer and 'esp' and 'saved_esp' differ by a constant value. */ esp = get_stack_ptr(); if (esp != saved_esp) panic("esp: %p != saved_esp: %p [curr-saved: %d], i = %u", esp, saved_esp, esp - saved_esp, i); #endif if (!(i % (8*MB))) { printk("[kthread] i = %i\n", i/MB); if (se_is_stop_requested()) break; } } printk("[kthread] completed\n"); } void selftest_kthread(void) { int tid = kthread_create(simple_test_kthread, 0, (void *)1); if (tid < 0) panic("Unable to create the simple test kthread"); kthread_join(tid, true); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(kthread, se_med, &selftest_kthread) void selftest_sleep() { const u64 wait_ticks = TIMER_HZ; u64 before = get_ticks(); kernel_sleep(wait_ticks); u64 after = get_ticks(); u64 elapsed = after - before; printk("[sleeping_kthread] elapsed ticks: %" PRIu64 " (expected: %" PRIu64 ")\n", elapsed, wait_ticks); VERIFY((elapsed - wait_ticks) <= TIMER_HZ/10); se_regular_end(); } REGISTER_SELF_TEST(sleep, se_short, &selftest_sleep) void selftest_join() { int tid; printk("[selftest join] create the simple thread\n"); if ((tid = kthread_create(simple_test_kthread, 0, (void *)0xAA0011FF)) < 0) panic("Unable to create simple_test_kthread"); printk("[selftest join] join()\n"); kthread_join(tid, true); printk("[selftest join] kernel thread exited\n"); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(join, se_med, &selftest_join) <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # Exit on any error set -e maindir="@CMAKE_SOURCE_DIR@" bdir="@CMAKE_BINARY_DIR@" dest="@CMAKE_BINARY_DIR@/bootpart" tc="@TCROOT@" host_arch="@HOST_ARCH@" mtoolsdir=$tc/host_${host_arch}/mtools mformat=$mtoolsdir/mformat mlabel=$mtoolsdir/mlabel mmd=$mtoolsdir/mmd mcopy=$mtoolsdir/mcopy mdel=$mtoolsdir/mdel if [ ! -f $dest ]; then # If the 'bootpart' file does not already exist dd status=none if=/dev/zero of=$dest count=@BOOTPART_SZ_SEC@ fi $mformat -i $dest -d 1 -T @BOOTPART_SZ_SEC@ :: $mlabel -i $dest ::BOOT $mmd -i $dest EFI $mmd -i $dest EFI/BOOT if [ -s "@EFI_x86_64_FILE@" ]; then $mcopy -i $dest "@EFI_x86_64_FILE@" ::/EFI/BOOT/ fi if [ -s "@EFI_ia32_FILE@" ]; then $mcopy -i $dest "@EFI_ia32_FILE@" ::/EFI/BOOT/ fi if [ -n "@KERNEL_BOOTPART_PATH@" ]; then $mcopy -i $dest @KERNEL_FILE@ ::/@KERNEL_BOOTPART_PATH@ fi <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fs/kernelfs.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sys_types.h> /* * KernelFS is a special, unmounted, file-system designed for special kernel * objects like pipes. It's existence cannot be avoided since all handles must * have a valid `fs` pointer. * * Currently, only pipes use it. */ static struct mnt_fs *kernelfs; static void no_lock(struct mnt_fs *fs) { } static vfs_inode_ptr_t kernelfs_get_inode(fs_handle h) { return ((struct kfs_handle *)h)->kobj; } static void kernelfs_on_close(fs_handle h) { struct kfs_handle *kh = h; if (kh->kobj->on_handle_close) kh->kobj->on_handle_close(kh); } static void kernelfs_on_close_last_handle(fs_handle h) { struct kfs_handle *kh = h; kh->kobj->destory_obj(kh->kobj); } int kernelfs_stat(struct mnt_fs *fs, vfs_inode_ptr_t i, struct k_stat64 *statbuf) { NOT_IMPLEMENTED(); } static int kernelfs_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { return retain_obj((struct kobj_base *)inode); } static int kernelfs_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { return release_obj((struct kobj_base *)inode); } static int kernelfs_on_dup(fs_handle new_h) { struct kfs_handle *kh = new_h; if (kh->kobj->on_handle_dup) kh->kobj->on_handle_dup(kh); return 0; } struct kfs_handle * kfs_create_new_handle(const struct file_ops *fops, struct kobj_base *kobj, int fl_flags) { struct kfs_handle *h; if (!(h = vfs_create_new_handle(kernelfs, fops))) return NULL; h->kobj = kobj; h->fl_flags = fl_flags; h->fd_flags = 0; /* Retain the object, as, in general, each file-handle retains the inode */ retain_obj(h->kobj); /* * Usually, VFS's open() retains the FS, but in this case, there is no open, * because we're creating and "opening" the "file" at the same time. * Therefore the retain on the FS has to be done here. */ retain_obj(h->fs); return h; } void kfs_destroy_handle(struct kfs_handle *h) { if (h->kobj) release_obj(h->kobj); vfs_free_handle(h); release_obj(kernelfs); } static const struct fs_ops static_fsops_kernelfs = { /* Implemented by the kernel object (e.g. pipe) */ .stat = kernelfs_stat, .retain_inode = kernelfs_retain_inode, .release_inode = kernelfs_release_inode, /* Implemented here */ .on_close = kernelfs_on_close, .on_close_last_handle = kernelfs_on_close_last_handle, .on_dup_cb = kernelfs_on_dup, .get_inode = kernelfs_get_inode, .fs_exlock = no_lock, .fs_exunlock = no_lock, .fs_shlock = no_lock, .fs_shunlock = no_lock, }; static struct mnt_fs *create_kernelfs(void) { struct mnt_fs *fs; /* Disallow multiple instances of kernelfs */ ASSERT(kernelfs == NULL); fs = create_fs_obj("kernelfs", &static_fsops_kernelfs, NULL, VFS_FS_RW); if (!fs) return NULL; fs->ref_count = 1; return fs; } void init_kernelfs(void) { kernelfs = create_kernelfs(); if (!kernelfs) panic("Unable to create kernelfs"); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int ramfs_munmap(struct user_mapping *um, void *vaddrp, size_t len) { return generic_fs_munmap(um, vaddrp, len); } static int ramfs_mmap(struct user_mapping *um, pdir_t *pdir, int flags) { struct ramfs_handle *rh = um->h; struct ramfs_inode *i = rh->inode; ulong vaddr = um->vaddr; struct bintree_walk_ctx ctx; struct ramfs_block *b; u32 pg_flags; int rc; const size_t off_begin = um->off; const size_t off_end = off_begin + um->len; ASSERT(IS_PAGE_ALIGNED(um->len)); if (i->type != VFS_FILE) return -EACCES; if (flags & VFS_MM_DONT_MMAP) goto register_mapping; bintree_in_order_visit_start(&ctx, i->blocks_tree_root, struct ramfs_block, node, false); pg_flags = PAGING_FL_US | PAGING_FL_SHARED; if ((rh->fl_flags & O_RDWR) == O_RDWR) pg_flags |= PAGING_FL_RW; while ((b = bintree_in_order_visit_next(&ctx))) { if ((size_t)b->offset < off_begin) continue; /* skip this block */ if ((size_t)b->offset >= off_end) break; rc = map_page(pdir, (void *)vaddr, KERNEL_VA_TO_PA(b->vaddr), pg_flags); if (rc) { /* mmap failed, we have to unmap the pages already mapped */ vaddr -= PAGE_SIZE; for (; vaddr >= um->vaddr; vaddr -= PAGE_SIZE) { unmap_page_permissive(pdir, (void *)vaddr, false); } return rc; } vaddr += PAGE_SIZE; } register_mapping: if (!(flags & VFS_MM_DONT_REGISTER)) { list_add_tail(&i->mappings_list, &um->inode_node); } return 0; } static bool ramfs_handle_fault_int(struct process *pi, struct user_mapping *um, void *vaddrp, bool p, bool rw) { struct ramfs_handle *rh = um->h; ulong vaddr = (ulong) vaddrp; ulong abs_off; struct ramfs_block *block; int rc; ASSERT(um != NULL); if (p) { /* * The page is present, just is read-only and the user code tried to * write: there's nothing we can do. */ ASSERT(rw); ASSERT((um->prot & PROT_WRITE) == 0); return false; } /* The page is *not* present */ abs_off = um->off + (vaddr - um->vaddr); if (abs_off >= (ulong)rh->inode->fsize) return false; /* Read/write past EOF */ if (rw) { /* Create and map on-the-fly a struct ramfs_block */ if (!(block = ramfs_new_block((offt)(abs_off & PAGE_MASK)))) panic("Out-of-memory: unable to alloc a ramfs_block. No OOM killer"); ramfs_append_new_block(rh->inode, block); } rc = map_page(pi->pdir, (void *)(vaddr & PAGE_MASK), KERNEL_VA_TO_PA(rw ? block->vaddr : &zero_page), PAGING_FL_US | PAGING_FL_RW | PAGING_FL_SHARED); if (rc) panic("Out-of-memory: unable to map a ramfs_block. No OOM killer"); invalidate_page(vaddr); return true; } static bool ramfs_handle_fault(struct user_mapping *um, void *vaddrp, bool p, bool rw) { bool ret; struct process *pi = get_curr_proc(); disable_preemption(); { ret = ramfs_handle_fault_int(pi, um, vaddrp, p, rw); } enable_preemption(); return ret; } <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu class printer_fs_handle_base: def __init__(self, val): self.val = val def to_string(self): return bu.fmt_type("struct fs_handle_base", self.val) def children(self): h = self.val spec_flags = h['spec_flags'] spf_str = "" if spec_flags == 0: spf_str = "(none)" else: if spec_flags & (1 << 0): spf_str += "NO_USER_COPY " if spec_flags & (1 << 1): spf_str += "MMAP" return [ ("pi ", h['pi']['pid']), ("fs ", h['fs']), ("fs_type ", h['fs']['fs_type_name'].string()), ("fd_flags ", h['fd_flags']), ("fl_flags ", h['fl_flags']), ("spec_flags", spf_str), ("pos ", h['pos']), ] bu.register_tilck_regex_pp( 'fs_handle_base', '^fs_handle_base$', printer_fs_handle_base ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define __STRING_UTIL_C__ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/kernel/errno.h> const s8 digit_to_val[128] = { [0 ... 47] = -1, [48] = 0, /* '0' */ [49] = 1, /* '1' */ [50] = 2, /* '2' */ [51] = 3, /* '3' */ [52] = 4, /* '4' */ [53] = 5, /* '5' */ [54] = 6, /* '6' */ [55] = 7, /* '7' */ [56] = 8, /* '7' */ [57] = 9, /* '7' */ [58 ... 64] = -1, [65] = 10, /* 'A' */ [66] = 11, /* 'B' */ [67] = 12, /* 'C' */ [68] = 13, /* 'D' */ [69] = 14, /* 'E' */ [70] = 15, /* 'F' */ [71 ... 96] = -1, [ 97] = 10, /* 'a' */ [ 98] = 11, /* 'b' */ [ 99] = 12, /* 'c' */ [100] = 13, /* 'd' */ [101] = 14, /* 'e' */ [102] = 15, /* 'f' */ [103 ... 127] = -1, }; /* Compile-in strcmp() and strncmp() only when there's no libc */ #if !defined(TESTING) && !defined(USERMODE_APP) int strcmp(const char *s1, const char *s2) { while(*s1 && *s1 == *s2) { s1++; s2++; } return (int)*s1 - (int)*s2; } int strncmp(const char *s1, const char *s2, size_t n) { size_t i = 0; while(i < n && *s1 && *s1 == *s2) { s1++; s2++; i++; } return i == n ? 0 : (int)*s1 - (int)*s2; } int memcmp(const void *_m1, const void *_m2, size_t n) { size_t i = 0; const char *m1 = _m1; const char *m2 = _m2; while(i < n && *m1 == *m2) { m1++; m2++; i++; } return i == n ? 0 : (int)*m1 - (int)*m2; } char *tilck_strstr(const char *haystack, const char *needle) { size_t sl, nl; if (!*haystack || !*needle) return NULL; sl = strlen(haystack); nl = strlen(needle); while (*haystack && sl >= nl) { if (*haystack == *needle && !strncmp(haystack, needle, nl)) return (char *)haystack; haystack++; sl--; } return NULL; } #if !defined(TESTING) && !defined(USERMODE_APP) char *strstr(const char *haystack, const char *needle) \ __attribute__((alias("tilck_strstr"))); #endif char *strcpy(char *dest, const char *src) { char *p = dest; while (*src) *p++ = *src++; *p = 0; return dest; } char *tilck_strncpy(char *dest, const char *src, size_t n) { char *p = dest; size_t i = 0; while (*src && i < n) { *p++ = *src++; i++; } if (i < n) *p = 0; return dest; } #if !defined(TESTING) && !defined(USERMODE_APP) char *strncpy(char *dest, const char *src, size_t n) \ __attribute__((alias("tilck_strncpy"))); #endif char *strcat(char *dest, const char *src) { return strcpy(dest + strlen(dest), src); } char *tilck_strncat(char *dest, const char *src, size_t n) { char *p = dest + strlen(dest); size_t i = 0; while (*src && i < n) { *p++ = *src++; i++; } *p = 0; return dest; } #if !defined(TESTING) && !defined(USERMODE_APP) char *strncat(char *dest, const char *src, size_t n) \ __attribute__((alias("tilck_strncat"))); #endif int tilck_isxdigit(int c) { return c < 128 && digit_to_val[c] >= 0; } #if !defined(TESTING) && !defined(USERMODE_APP) int isxdigit(int c) __attribute__((alias("tilck_isxdigit"))); #endif int tilck_isspace(int c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f'; } #if !defined(TESTING) && !defined(USERMODE_APP) int isspace(int c) __attribute__((alias("tilck_isspace"))); #endif #endif // #if !defined(TESTING) && !defined(USERMODE_APP) int stricmp(const char *s1, const char *s2) { while(*s1 && tolower(*s1) == tolower(*s2)) { s1++; s2++; } return (int)tolower(*s1) - (int)tolower(*s2); } /* * Reverse a string in-place. * NOTE: len == strlen(str): it does NOT include the final \0. */ inline void str_reverse(char *str, size_t len) { ASSERT(len == strlen(str)); if (!len) return; char *end = str + len - 1; while (str < end) { *str ^= *end; *end ^= *str; *str ^= *end; str++; end--; } } #if defined(__aarch64__) && defined(KERNEL_TEST) void *memset16(u16 *s, u16 val, size_t n) { for (size_t i = 0; i < n; i++) s[i] = val; return s; } void *memset32(u32 *s, u32 val, size_t n) { for (size_t i = 0; i < n; i++) s[i] = val; return s; } void *memcpy16(void *dest, const void *src, size_t n) { return memcpy(dest, src, n * 2); } void *memcpy32(void *dest, const void *src, size_t n) { return memcpy(dest, src, n * 4); } #endif <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tasks class cmd_list_tasks(gdb.Command): cmd_name = "list-tasks" def __init__(self): super(cmd_list_tasks, self).__init__( cmd_list_tasks.cmd_name, gdb.COMMAND_USER ) def invoke(self, arg, from_tty): user_only = False kernel_only = False if arg == '/u': user_only = True elif arg == '/k': kernel_only = True elif arg == '': pass # Do nothing else: print("Usage:") print(" list-tasks # List all the tasks") print(" list-tasks /u # List only the user tasks") print(" list-tasks /k # List only the kernel tasks") print("") return tasks_list = tasks.get_all_tasks() print("") for t in tasks_list: pi = t['pi'] tid = str(t['tid']) pid = str(pi['pid']) pid_field = "" state = str(t['state'])[11:] # Skip "TASK_STATE_" what_field = "" what_str = "" if kernel_only: if t['tid'] <= 10000: continue if t['tid'] == 10000: if user_only: break print(" " "------------------ Kernel threads ------------------") print("") continue # Skip kernel's unused task 10000 gdb.execute( "print (struct task *) {}".format(bu.fixhex32(int(t))) ) if t['tid'] > 10000: what_field = t['kthread_name'].string() what_str = 'kthread_name' else: pid_field = "pid = {:>5}, ".format(pid) what_field = pi['debug_cmdline'].string().rstrip() what_str = 'cmdline' print( " " "{{tid = {:>5}, {}{}, {} = {}}}\n".format( tid, pid_field, state, what_str, what_field ) ) class cmd_list_procs(gdb.Command): cmd_name = "list-procs" def __init__(self): super(cmd_list_procs, self).__init__( cmd_list_procs.cmd_name, gdb.COMMAND_USER ) def invoke(self, arg, from_tty): tasks_list = tasks.get_all_tasks() print("") for t in tasks_list: pi = t['pi'] pid = str(pi['pid']) if t['tid'] != pi['pid']: continue gdb.execute( "print (struct process *) {}".format(bu.fixhex32(int(pi))) ) print( " " "{{ pid = {:>5}, cmdline = '{}' }}\n".format( pid, pi['debug_cmdline'].string().rstrip() ) ) class cmd_list_tilck_cmds(gdb.Command): cmd_name = "list-tilck-cmds" def __init__(self): super(cmd_list_tilck_cmds, self).__init__( cmd_list_tilck_cmds.cmd_name, gdb.COMMAND_USER ) def invoke(self, arg, from_tty): for e in bu.gdb_custom_cmds: print(e.cmd_name) # ------------------------------------------------- bu.register_new_custom_gdb_cmd(cmd_list_tasks) bu.register_new_custom_gdb_cmd(cmd_list_procs) bu.register_new_custom_gdb_cmd(cmd_list_tilck_cmds) <file_sep>/******************************************************************************* * * Module Name: dsmthdat - control method arguments and local variables * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdispat.h" #include "acnamesp.h" #include "acinterp.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsmthdat") /* Local prototypes */ static void AcpiDsMethodDataDeleteValue ( UINT8 Type, UINT32 Index, ACPI_WALK_STATE *WalkState); static ACPI_STATUS AcpiDsMethodDataSetValue ( UINT8 Type, UINT32 Index, ACPI_OPERAND_OBJECT *Object, ACPI_WALK_STATE *WalkState); #ifdef ACPI_OBSOLETE_FUNCTIONS ACPI_OBJECT_TYPE AcpiDsMethodDataGetType ( UINT16 Opcode, UINT32 Index, ACPI_WALK_STATE *WalkState); #endif /******************************************************************************* * * FUNCTION: AcpiDsMethodDataInit * * PARAMETERS: WalkState - Current walk state object * * RETURN: Status * * DESCRIPTION: Initialize the data structures that hold the method's arguments * and locals. The data struct is an array of namespace nodes for * each - this allows RefOf and DeRefOf to work properly for these * special data types. * * NOTES: WalkState fields are initialized to zero by the * ACPI_ALLOCATE_ZEROED(). * * A pseudo-Namespace Node is assigned to each argument and local * so that RefOf() can return a pointer to the Node. * ******************************************************************************/ void AcpiDsMethodDataInit ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_TRACE (DsMethodDataInit); /* Init the method arguments */ for (i = 0; i < ACPI_METHOD_NUM_ARGS; i++) { ACPI_MOVE_32_TO_32 (&WalkState->Arguments[i].Name, NAMEOF_ARG_NTE); WalkState->Arguments[i].Name.Integer |= (i << 24); WalkState->Arguments[i].DescriptorType = ACPI_DESC_TYPE_NAMED; WalkState->Arguments[i].Type = ACPI_TYPE_ANY; WalkState->Arguments[i].Flags = ANOBJ_METHOD_ARG; } /* Init the method locals */ for (i = 0; i < ACPI_METHOD_NUM_LOCALS; i++) { ACPI_MOVE_32_TO_32 (&WalkState->LocalVariables[i].Name, NAMEOF_LOCAL_NTE); WalkState->LocalVariables[i].Name.Integer |= (i << 24); WalkState->LocalVariables[i].DescriptorType = ACPI_DESC_TYPE_NAMED; WalkState->LocalVariables[i].Type = ACPI_TYPE_ANY; WalkState->LocalVariables[i].Flags = ANOBJ_METHOD_LOCAL; } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataDeleteAll * * PARAMETERS: WalkState - Current walk state object * * RETURN: None * * DESCRIPTION: Delete method locals and arguments. Arguments are only * deleted if this method was called from another method. * ******************************************************************************/ void AcpiDsMethodDataDeleteAll ( ACPI_WALK_STATE *WalkState) { UINT32 Index; ACPI_FUNCTION_TRACE (DsMethodDataDeleteAll); /* Detach the locals */ for (Index = 0; Index < ACPI_METHOD_NUM_LOCALS; Index++) { if (WalkState->LocalVariables[Index].Object) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Deleting Local%u=%p\n", Index, WalkState->LocalVariables[Index].Object)); /* Detach object (if present) and remove a reference */ AcpiNsDetachObject (&WalkState->LocalVariables[Index]); } } /* Detach the arguments */ for (Index = 0; Index < ACPI_METHOD_NUM_ARGS; Index++) { if (WalkState->Arguments[Index].Object) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Deleting Arg%u=%p\n", Index, WalkState->Arguments[Index].Object)); /* Detach object (if present) and remove a reference */ AcpiNsDetachObject (&WalkState->Arguments[Index]); } } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataInitArgs * * PARAMETERS: *Params - Pointer to a parameter list for the method * MaxParamCount - The arg count for this method * WalkState - Current walk state object * * RETURN: Status * * DESCRIPTION: Initialize arguments for a method. The parameter list is a list * of ACPI operand objects, either null terminated or whose length * is defined by MaxParamCount. * ******************************************************************************/ ACPI_STATUS AcpiDsMethodDataInitArgs ( ACPI_OPERAND_OBJECT **Params, UINT32 MaxParamCount, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; UINT32 Index = 0; ACPI_FUNCTION_TRACE_PTR (DsMethodDataInitArgs, Params); if (!Params) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "No parameter list passed to method\n")); return_ACPI_STATUS (AE_OK); } /* Copy passed parameters into the new method stack frame */ while ((Index < ACPI_METHOD_NUM_ARGS) && (Index < MaxParamCount) && Params[Index]) { /* * A valid parameter. * Store the argument in the method/walk descriptor. * Do not copy the arg in order to implement call by reference */ Status = AcpiDsMethodDataSetValue ( ACPI_REFCLASS_ARG, Index, Params[Index], WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%u args passed to method\n", Index)); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataGetNode * * PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or * ACPI_REFCLASS_ARG * Index - Which Local or Arg whose type to get * WalkState - Current walk state object * Node - Where the node is returned. * * RETURN: Status and node * * DESCRIPTION: Get the Node associated with a local or arg. * ******************************************************************************/ ACPI_STATUS AcpiDsMethodDataGetNode ( UINT8 Type, UINT32 Index, ACPI_WALK_STATE *WalkState, ACPI_NAMESPACE_NODE **Node) { ACPI_FUNCTION_TRACE (DsMethodDataGetNode); /* * Method Locals and Arguments are supported */ switch (Type) { case ACPI_REFCLASS_LOCAL: if (Index > ACPI_METHOD_MAX_LOCAL) { ACPI_ERROR ((AE_INFO, "Local index %u is invalid (max %u)", Index, ACPI_METHOD_MAX_LOCAL)); return_ACPI_STATUS (AE_AML_INVALID_INDEX); } /* Return a pointer to the pseudo-node */ *Node = &WalkState->LocalVariables[Index]; break; case ACPI_REFCLASS_ARG: if (Index > ACPI_METHOD_MAX_ARG) { ACPI_ERROR ((AE_INFO, "Arg index %u is invalid (max %u)", Index, ACPI_METHOD_MAX_ARG)); return_ACPI_STATUS (AE_AML_INVALID_INDEX); } /* Return a pointer to the pseudo-node */ *Node = &WalkState->Arguments[Index]; break; default: ACPI_ERROR ((AE_INFO, "Type %u is invalid", Type)); return_ACPI_STATUS (AE_TYPE); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataSetValue * * PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or * ACPI_REFCLASS_ARG * Index - Which Local or Arg to get * Object - Object to be inserted into the stack entry * WalkState - Current walk state object * * RETURN: Status * * DESCRIPTION: Insert an object onto the method stack at entry Opcode:Index. * Note: There is no "implicit conversion" for locals. * ******************************************************************************/ static ACPI_STATUS AcpiDsMethodDataSetValue ( UINT8 Type, UINT32 Index, ACPI_OPERAND_OBJECT *Object, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (DsMethodDataSetValue); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "NewObj %p Type %2.2X, Refs=%u [%s]\n", Object, Type, Object->Common.ReferenceCount, AcpiUtGetTypeName (Object->Common.Type))); /* Get the namespace node for the arg/local */ Status = AcpiDsMethodDataGetNode (Type, Index, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Increment ref count so object can't be deleted while installed. * NOTE: We do not copy the object in order to preserve the call by * reference semantics of ACPI Control Method invocation. * (See ACPI Specification 2.0C) */ AcpiUtAddReference (Object); /* Install the object */ Node->Object = Object; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataGetValue * * PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or * ACPI_REFCLASS_ARG * Index - Which localVar or argument to get * WalkState - Current walk state object * DestDesc - Where Arg or Local value is returned * * RETURN: Status * * DESCRIPTION: Retrieve value of selected Arg or Local for this method * Used only in AcpiExResolveToValue(). * ******************************************************************************/ ACPI_STATUS AcpiDsMethodDataGetValue ( UINT8 Type, UINT32 Index, ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT **DestDesc) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *Object; ACPI_FUNCTION_TRACE (DsMethodDataGetValue); /* Validate the object descriptor */ if (!DestDesc) { ACPI_ERROR ((AE_INFO, "Null object descriptor pointer")); return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Get the namespace node for the arg/local */ Status = AcpiDsMethodDataGetNode (Type, Index, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Get the object from the node */ Object = Node->Object; /* Examine the returned object, it must be valid. */ if (!Object) { /* * Index points to uninitialized object. * This means that either 1) The expected argument was * not passed to the method, or 2) A local variable * was referenced by the method (via the ASL) * before it was initialized. Either case is an error. */ /* If slack enabled, init the LocalX/ArgX to an Integer of value zero */ if (AcpiGbl_EnableInterpreterSlack) { Object = AcpiUtCreateIntegerObject ((UINT64) 0); if (!Object) { return_ACPI_STATUS (AE_NO_MEMORY); } Node->Object = Object; } /* Otherwise, return the error */ else switch (Type) { case ACPI_REFCLASS_ARG: ACPI_ERROR ((AE_INFO, "Uninitialized Arg[%u] at node %p", Index, Node)); return_ACPI_STATUS (AE_AML_UNINITIALIZED_ARG); case ACPI_REFCLASS_LOCAL: /* * No error message for this case, will be trapped again later to * detect and ignore cases of Store(LocalX,LocalX) */ return_ACPI_STATUS (AE_AML_UNINITIALIZED_LOCAL); default: ACPI_ERROR ((AE_INFO, "Not a Arg/Local opcode: 0x%X", Type)); return_ACPI_STATUS (AE_AML_INTERNAL); } } /* * The Index points to an initialized and valid object. * Return an additional reference to the object */ *DestDesc = Object; AcpiUtAddReference (Object); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsMethodDataDeleteValue * * PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or * ACPI_REFCLASS_ARG * Index - Which localVar or argument to delete * WalkState - Current walk state object * * RETURN: None * * DESCRIPTION: Delete the entry at Opcode:Index. Inserts * a null into the stack slot after the object is deleted. * ******************************************************************************/ static void AcpiDsMethodDataDeleteValue ( UINT8 Type, UINT32 Index, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *Object; ACPI_FUNCTION_TRACE (DsMethodDataDeleteValue); /* Get the namespace node for the arg/local */ Status = AcpiDsMethodDataGetNode (Type, Index, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_VOID; } /* Get the associated object */ Object = AcpiNsGetAttachedObject (Node); /* * Undefine the Arg or Local by setting its descriptor * pointer to NULL. Locals/Args can contain both * ACPI_OPERAND_OBJECTS and ACPI_NAMESPACE_NODEs */ Node->Object = NULL; if ((Object) && (ACPI_GET_DESCRIPTOR_TYPE (Object) == ACPI_DESC_TYPE_OPERAND)) { /* * There is a valid object. * Decrement the reference count by one to balance the * increment when the object was stored. */ AcpiUtRemoveReference (Object); } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsStoreObjectToLocal * * PARAMETERS: Type - Either ACPI_REFCLASS_LOCAL or * ACPI_REFCLASS_ARG * Index - Which Local or Arg to set * ObjDesc - Value to be stored * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Store a value in an Arg or Local. The ObjDesc is installed * as the new value for the Arg or Local and the reference count * for ObjDesc is incremented. * ******************************************************************************/ ACPI_STATUS AcpiDsStoreObjectToLocal ( UINT8 Type, UINT32 Index, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *CurrentObjDesc; ACPI_OPERAND_OBJECT *NewObjDesc; ACPI_FUNCTION_TRACE (DsStoreObjectToLocal); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Type=%2.2X Index=%u Obj=%p\n", Type, Index, ObjDesc)); /* Parameter validation */ if (!ObjDesc) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Get the namespace node for the arg/local */ Status = AcpiDsMethodDataGetNode (Type, Index, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } CurrentObjDesc = AcpiNsGetAttachedObject (Node); if (CurrentObjDesc == ObjDesc) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Obj=%p already installed!\n", ObjDesc)); return_ACPI_STATUS (Status); } /* * If the reference count on the object is more than one, we must * take a copy of the object before we store. A reference count * of exactly 1 means that the object was just created during the * evaluation of an expression, and we can safely use it since it * is not used anywhere else. */ NewObjDesc = ObjDesc; if (ObjDesc->Common.ReferenceCount > 1) { Status = AcpiUtCopyIobjectToIobject ( ObjDesc, &NewObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* * If there is an object already in this slot, we either * have to delete it, or if this is an argument and there * is an object reference stored there, we have to do * an indirect store! */ if (CurrentObjDesc) { /* * Check for an indirect store if an argument * contains an object reference (stored as an Node). * We don't allow this automatic dereferencing for * locals, since a store to a local should overwrite * anything there, including an object reference. * * If both Arg0 and Local0 contain RefOf (Local4): * * Store (1, Arg0) - Causes indirect store to local4 * Store (1, Local0) - Stores 1 in local0, overwriting * the reference to local4 * Store (1, DeRefof (Local0)) - Causes indirect store to local4 * * Weird, but true. */ if (Type == ACPI_REFCLASS_ARG) { /* * If we have a valid reference object that came from RefOf(), * do the indirect store */ if ((ACPI_GET_DESCRIPTOR_TYPE (CurrentObjDesc) == ACPI_DESC_TYPE_OPERAND) && (CurrentObjDesc->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) && (CurrentObjDesc->Reference.Class == ACPI_REFCLASS_REFOF)) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Arg (%p) is an ObjRef(Node), storing in node %p\n", NewObjDesc, CurrentObjDesc)); /* * Store this object to the Node (perform the indirect store) * NOTE: No implicit conversion is performed, as per the ACPI * specification rules on storing to Locals/Args. */ Status = AcpiExStoreObjectToNode (NewObjDesc, CurrentObjDesc->Reference.Object, WalkState, ACPI_NO_IMPLICIT_CONVERSION); /* Remove local reference if we copied the object above */ if (NewObjDesc != ObjDesc) { AcpiUtRemoveReference (NewObjDesc); } return_ACPI_STATUS (Status); } } /* Delete the existing object before storing the new one */ AcpiDsMethodDataDeleteValue (Type, Index, WalkState); } /* * Install the Obj descriptor (*NewObjDesc) into * the descriptor for the Arg or Local. * (increments the object reference count by one) */ Status = AcpiDsMethodDataSetValue (Type, Index, NewObjDesc, WalkState); /* Remove local reference if we copied the object above */ if (NewObjDesc != ObjDesc) { AcpiUtRemoveReference (NewObjDesc); } return_ACPI_STATUS (Status); } #ifdef ACPI_OBSOLETE_FUNCTIONS /******************************************************************************* * * FUNCTION: AcpiDsMethodDataGetType * * PARAMETERS: Opcode - Either AML_FIRST LOCAL_OP or * AML_FIRST_ARG_OP * Index - Which Local or Arg whose type to get * WalkState - Current walk state object * * RETURN: Data type of current value of the selected Arg or Local * * DESCRIPTION: Get the type of the object stored in the Local or Arg * ******************************************************************************/ ACPI_OBJECT_TYPE AcpiDsMethodDataGetType ( UINT16 Opcode, UINT32 Index, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *Object; ACPI_FUNCTION_TRACE (DsMethodDataGetType); /* Get the namespace node for the arg/local */ Status = AcpiDsMethodDataGetNode (Opcode, Index, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_VALUE ((ACPI_TYPE_NOT_FOUND)); } /* Get the object */ Object = AcpiNsGetAttachedObject (Node); if (!Object) { /* Uninitialized local/arg, return TYPE_ANY */ return_VALUE (ACPI_TYPE_ANY); } /* Get the object type */ return_VALUE (Object->Type); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/irq.h> bool kmutex_is_curr_task_holding_lock(struct kmutex *m) { return m->owner_task == get_curr_task(); } void kmutex_init(struct kmutex *m, u32 flags) { DEBUG_ONLY(check_not_in_irq_handler()); bzero(m, sizeof(struct kmutex)); m->flags = flags; list_init(&m->wait_list); } void kmutex_destroy(struct kmutex *m) { bzero(m, sizeof(struct kmutex)); } static ALWAYS_INLINE void kmutex_lock_enable_preemption_wrapper(struct kmutex *m) { #if KERNEL_SELFTESTS if (UNLIKELY(m->flags & KMUTEX_FL_ALLOW_LOCK_WITH_PREEMPT_DISABLED)) { ASSERT(get_preempt_disable_count() == 2); enable_preemption(); /* special case only for self tests */ } #endif } void kmutex_lock(struct kmutex *m) { disable_preemption(); DEBUG_ONLY(check_not_in_irq_handler()); if (!m->owner_task) { /* Nobody owns this mutex, just make this task own it */ m->owner_task = get_curr_task(); if (m->flags & KMUTEX_FL_RECURSIVE) { ASSERT(m->lock_count == 0); m->lock_count++; } kmutex_lock_enable_preemption_wrapper(m); enable_preemption(); return; } if (m->flags & KMUTEX_FL_RECURSIVE) { ASSERT(m->lock_count > 0); if (kmutex_is_curr_task_holding_lock(m)) { m->lock_count++; enable_preemption(); return; } } else { ASSERT(!kmutex_is_curr_task_holding_lock(m)); } #if KMUTEX_STATS_ENABLED m->num_waiters++; m->max_num_waiters = MAX(m->num_waiters, m->max_num_waiters); #endif prepare_to_wait_on(WOBJ_KMUTEX, m, NO_EXTRA, &m->wait_list); kmutex_lock_enable_preemption_wrapper(m); /* * Go to sleep until someone else is holding the lock. * NOTE: we won't be woken up by a signal here, see signal.c. */ enter_sleep_wait_state(); /* ------------------- We've been woken up ------------------- */ #if KMUTEX_STATS_ENABLED m->num_waiters--; #endif /* Now for sure this task should hold the mutex */ ASSERT(kmutex_is_curr_task_holding_lock(m)); /* * DEBUG check: in case we went to sleep with a recursive mutex, then the * lock_count must be just 1 now. */ if (m->flags & KMUTEX_FL_RECURSIVE) { ASSERT(m->lock_count == 1); } } bool kmutex_trylock(struct kmutex *m) { bool success = false; disable_preemption(); DEBUG_ONLY(check_not_in_irq_handler()); if (!m->owner_task) { /* Nobody owns this mutex, just make this task own it */ m->owner_task = get_curr_task(); success = true; if (m->flags & KMUTEX_FL_RECURSIVE) m->lock_count++; } else { /* * There IS an owner task, but we can still acquire the mutex if: * - the mutex is recursive * - the task holding it is actually the current task */ if (m->flags & KMUTEX_FL_RECURSIVE) { if (kmutex_is_curr_task_holding_lock(m)) { m->lock_count++; success = true; } } } enable_preemption(); return success; } void kmutex_unlock(struct kmutex *m) { disable_preemption(); DEBUG_ONLY(check_not_in_irq_handler()); ASSERT(kmutex_is_curr_task_holding_lock(m)); if (m->flags & KMUTEX_FL_RECURSIVE) { ASSERT(m->lock_count > 0); if (--m->lock_count > 0) { enable_preemption(); return; } // m->lock_count == 0: we have to really unlock the mutex } m->owner_task = NULL; /* Unlock one task waiting to acquire the mutex 'm' (if any) */ if (!list_is_empty(&m->wait_list)) { struct wait_obj *task_wo = list_first_obj(&m->wait_list, struct wait_obj, wait_list_node); struct task *ti = CONTAINER_OF(task_wo, struct task, wobj); m->owner_task = ti; if (m->flags & KMUTEX_FL_RECURSIVE) m->lock_count++; ASSERT_TASK_STATE(ti->state, TASK_STATE_SLEEPING); wake_up(ti); } // if (!list_is_empty(&m->wait_list)) enable_preemption(); } <file_sep>/****************************************************************************** * * Module Name: hwxface - Public ACPICA hardware interfaces * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_HARDWARE ACPI_MODULE_NAME ("hwxface") /****************************************************************************** * * FUNCTION: AcpiReset * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Set reset register in memory or IO space. Note: Does not * support reset register in PCI config space, this must be * handled separately. * ******************************************************************************/ ACPI_STATUS AcpiReset ( void) { ACPI_GENERIC_ADDRESS *ResetReg; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiReset); ResetReg = &AcpiGbl_FADT.ResetRegister; /* Check if the reset register is supported */ if (!(AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER) || !ResetReg->Address) { return_ACPI_STATUS (AE_NOT_EXIST); } if (ResetReg->SpaceId == ACPI_ADR_SPACE_SYSTEM_IO) { /* * For I/O space, write directly to the OSL. This bypasses the port * validation mechanism, which may block a valid write to the reset * register. * * NOTE: * The ACPI spec requires the reset register width to be 8, so we * hardcode it here and ignore the FADT value. This maintains * compatibility with other ACPI implementations that have allowed * BIOS code with bad register width values to go unnoticed. */ Status = AcpiOsWritePort ((ACPI_IO_ADDRESS) ResetReg->Address, AcpiGbl_FADT.ResetValue, ACPI_RESET_REGISTER_WIDTH); } else { /* Write the reset value to the reset register */ Status = AcpiHwWrite (AcpiGbl_FADT.ResetValue, ResetReg); } return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiReset) /****************************************************************************** * * FUNCTION: AcpiRead * * PARAMETERS: Value - Where the value is returned * Reg - GAS register structure * * RETURN: Status * * DESCRIPTION: Read from either memory or IO space. * * LIMITATIONS: <These limitations also apply to AcpiWrite> * BitWidth must be exactly 8, 16, 32, or 64. * SpaceID must be SystemMemory or SystemIO. * BitOffset and AccessWidth are currently ignored, as there has * not been a need to implement these. * ******************************************************************************/ ACPI_STATUS AcpiRead ( UINT64 *ReturnValue, ACPI_GENERIC_ADDRESS *Reg) { ACPI_STATUS Status; ACPI_FUNCTION_NAME (AcpiRead); Status = AcpiHwRead (ReturnValue, Reg); return (Status); } ACPI_EXPORT_SYMBOL (AcpiRead) /****************************************************************************** * * FUNCTION: AcpiWrite * * PARAMETERS: Value - Value to be written * Reg - GAS register structure * * RETURN: Status * * DESCRIPTION: Write to either memory or IO space. * ******************************************************************************/ ACPI_STATUS AcpiWrite ( UINT64 Value, ACPI_GENERIC_ADDRESS *Reg) { ACPI_STATUS Status; ACPI_FUNCTION_NAME (AcpiWrite); Status = AcpiHwWrite (Value, Reg); return (Status); } ACPI_EXPORT_SYMBOL (AcpiWrite) #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiReadBitRegister * * PARAMETERS: RegisterId - ID of ACPI Bit Register to access * ReturnValue - Value that was read from the register, * normalized to bit position zero. * * RETURN: Status and the value read from the specified Register. Value * returned is normalized to bit0 (is shifted all the way right) * * DESCRIPTION: ACPI BitRegister read function. Does not acquire the HW lock. * * SUPPORTS: Bit fields in PM1 Status, PM1 Enable, PM1 Control, and * PM2 Control. * * Note: The hardware lock is not required when reading the ACPI bit registers * since almost all of them are single bit and it does not matter that * the parent hardware register can be split across two physical * registers. The only multi-bit field is SLP_TYP in the PM1 control * register, but this field does not cross an 8-bit boundary (nor does * it make much sense to actually read this field.) * ******************************************************************************/ ACPI_STATUS AcpiReadBitRegister ( UINT32 RegisterId, UINT32 *ReturnValue) { ACPI_BIT_REGISTER_INFO *BitRegInfo; UINT32 RegisterValue; UINT32 Value; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_U32 (AcpiReadBitRegister, RegisterId); /* Get the info structure corresponding to the requested ACPI Register */ BitRegInfo = AcpiHwGetBitRegisterInfo (RegisterId); if (!BitRegInfo) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Read the entire parent register */ Status = AcpiHwRegisterRead (BitRegInfo->ParentRegister, &RegisterValue); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Normalize the value that was read, mask off other bits */ Value = ((RegisterValue & BitRegInfo->AccessBitMask) >> BitRegInfo->BitPosition); ACPI_DEBUG_PRINT ((ACPI_DB_IO, "BitReg %X, ParentReg %X, Actual %8.8X, ReturnValue %8.8X\n", RegisterId, BitRegInfo->ParentRegister, RegisterValue, Value)); *ReturnValue = Value; return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiReadBitRegister) /******************************************************************************* * * FUNCTION: AcpiWriteBitRegister * * PARAMETERS: RegisterId - ID of ACPI Bit Register to access * Value - Value to write to the register, in bit * position zero. The bit is automatically * shifted to the correct position. * * RETURN: Status * * DESCRIPTION: ACPI Bit Register write function. Acquires the hardware lock * since most operations require a read/modify/write sequence. * * SUPPORTS: Bit fields in PM1 Status, PM1 Enable, PM1 Control, and * PM2 Control. * * Note that at this level, the fact that there may be actually two * hardware registers (A and B - and B may not exist) is abstracted. * ******************************************************************************/ ACPI_STATUS AcpiWriteBitRegister ( UINT32 RegisterId, UINT32 Value) { ACPI_BIT_REGISTER_INFO *BitRegInfo; ACPI_CPU_FLAGS LockFlags; UINT32 RegisterValue; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_U32 (AcpiWriteBitRegister, RegisterId); /* Get the info structure corresponding to the requested ACPI Register */ BitRegInfo = AcpiHwGetBitRegisterInfo (RegisterId); if (!BitRegInfo) { return_ACPI_STATUS (AE_BAD_PARAMETER); } LockFlags = AcpiOsAcquireLock (AcpiGbl_HardwareLock); /* * At this point, we know that the parent register is one of the * following: PM1 Status, PM1 Enable, PM1 Control, or PM2 Control */ if (BitRegInfo->ParentRegister != ACPI_REGISTER_PM1_STATUS) { /* * 1) Case for PM1 Enable, PM1 Control, and PM2 Control * * Perform a register read to preserve the bits that we are not * interested in */ Status = AcpiHwRegisterRead (BitRegInfo->ParentRegister, &RegisterValue); if (ACPI_FAILURE (Status)) { goto UnlockAndExit; } /* * Insert the input bit into the value that was just read * and write the register */ ACPI_REGISTER_INSERT_VALUE (RegisterValue, BitRegInfo->BitPosition, BitRegInfo->AccessBitMask, Value); Status = AcpiHwRegisterWrite (BitRegInfo->ParentRegister, RegisterValue); } else { /* * 2) Case for PM1 Status * * The Status register is different from the rest. Clear an event * by writing 1, writing 0 has no effect. So, the only relevant * information is the single bit we're interested in, all others * should be written as 0 so they will be left unchanged. */ RegisterValue = ACPI_REGISTER_PREPARE_BITS (Value, BitRegInfo->BitPosition, BitRegInfo->AccessBitMask); /* No need to write the register if value is all zeros */ if (RegisterValue) { Status = AcpiHwRegisterWrite (ACPI_REGISTER_PM1_STATUS, RegisterValue); } } ACPI_DEBUG_PRINT ((ACPI_DB_IO, "BitReg %X, ParentReg %X, Value %8.8X, Actual %8.8X\n", RegisterId, BitRegInfo->ParentRegister, Value, RegisterValue)); UnlockAndExit: AcpiOsReleaseLock (AcpiGbl_HardwareLock, LockFlags); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiWriteBitRegister) #endif /* !ACPI_REDUCED_HARDWARE */ /******************************************************************************* * * FUNCTION: AcpiGetSleepTypeData * * PARAMETERS: SleepState - Numeric sleep state * *SleepTypeA - Where SLP_TYPa is returned * *SleepTypeB - Where SLP_TYPb is returned * * RETURN: Status * * DESCRIPTION: Obtain the SLP_TYPa and SLP_TYPb values for the requested * sleep state via the appropriate \_Sx object. * * The sleep state package returned from the corresponding \_Sx_ object * must contain at least one integer. * * March 2005: * Added support for a package that contains two integers. This * goes against the ACPI specification which defines this object as a * package with one encoded DWORD integer. However, existing practice * by many BIOS vendors is to return a package with 2 or more integer * elements, at least one per sleep type (A/B). * * January 2013: * Therefore, we must be prepared to accept a package with either a * single integer or multiple integers. * * The single integer DWORD format is as follows: * BYTE 0 - Value for the PM1A SLP_TYP register * BYTE 1 - Value for the PM1B SLP_TYP register * BYTE 2-3 - Reserved * * The dual integer format is as follows: * Integer 0 - Value for the PM1A SLP_TYP register * Integer 1 - Value for the PM1A SLP_TYP register * ******************************************************************************/ ACPI_STATUS AcpiGetSleepTypeData ( UINT8 SleepState, UINT8 *SleepTypeA, UINT8 *SleepTypeB) { ACPI_STATUS Status; ACPI_EVALUATE_INFO *Info; ACPI_OPERAND_OBJECT **Elements; ACPI_FUNCTION_TRACE (AcpiGetSleepTypeData); /* Validate parameters */ if ((SleepState > ACPI_S_STATES_MAX) || !SleepTypeA || !SleepTypeB) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Allocate the evaluation information block */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { return_ACPI_STATUS (AE_NO_MEMORY); } /* * Evaluate the \_Sx namespace object containing the register values * for this state */ Info->RelativePathname = AcpiGbl_SleepStateNames[SleepState]; Status = AcpiNsEvaluate (Info); if (ACPI_FAILURE (Status)) { if (Status == AE_NOT_FOUND) { /* The _Sx states are optional, ignore NOT_FOUND */ goto FinalCleanup; } goto WarningCleanup; } /* Must have a return object */ if (!Info->ReturnObject) { ACPI_ERROR ((AE_INFO, "No Sleep State object returned from [%s]", Info->RelativePathname)); Status = AE_AML_NO_RETURN_VALUE; goto WarningCleanup; } /* Return object must be of type Package */ if (Info->ReturnObject->Common.Type != ACPI_TYPE_PACKAGE) { ACPI_ERROR ((AE_INFO, "Sleep State return object is not a Package")); Status = AE_AML_OPERAND_TYPE; goto ReturnValueCleanup; } /* * Any warnings about the package length or the object types have * already been issued by the predefined name module -- there is no * need to repeat them here. */ Elements = Info->ReturnObject->Package.Elements; switch (Info->ReturnObject->Package.Count) { case 0: Status = AE_AML_PACKAGE_LIMIT; break; case 1: if (Elements[0]->Common.Type != ACPI_TYPE_INTEGER) { Status = AE_AML_OPERAND_TYPE; break; } /* A valid _Sx_ package with one integer */ *SleepTypeA = (UINT8) Elements[0]->Integer.Value; *SleepTypeB = (UINT8) (Elements[0]->Integer.Value >> 8); break; case 2: default: if ((Elements[0]->Common.Type != ACPI_TYPE_INTEGER) || (Elements[1]->Common.Type != ACPI_TYPE_INTEGER)) { Status = AE_AML_OPERAND_TYPE; break; } /* A valid _Sx_ package with two integers */ *SleepTypeA = (UINT8) Elements[0]->Integer.Value; *SleepTypeB = (UINT8) Elements[1]->Integer.Value; break; } ReturnValueCleanup: AcpiUtRemoveReference (Info->ReturnObject); WarningCleanup: if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "While evaluating Sleep State [%s]", Info->RelativePathname)); } FinalCleanup: ACPI_FREE (Info); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetSleepTypeData) <file_sep>#!/usr/bin/env bash # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/../.. && pwd)" DISTRO_FILE="$MAIN_DIR/toolchain2/.distro" if ! [ "$RUNNING_IN_CI" == 1 ]; then echo "This script was meant to be run in CI (toolchain_builds.yml)." echo "Outside CI, please use directly the run_all_tests script." exit 1 fi if ! [ -f $DISTRO_FILE ]; then echo "ERROR: file $DISTRO_FILE not found." exit 1 fi distro=$(cat $DISTRO_FILE) if [ "$distro" == "opensuse" ]; then err="$(qemu-system-i386 --help 2>&1)" if echo "$err" | grep membarrier &> /dev/null; then echo "WARNING: skipping the system tests because the QEMU version" echo "on OpenSUSE requires the membarrier syscall, not available on" echo "the current Linux kernel." exit 0 fi fi exec $MAIN_DIR/build/st/run_all_tests "$@" <file_sep>from unittest import TestCase from cmake_row import cmake_row, row_type class test_cmake_row(TestCase): commentline = "" filepath_var_valid = "CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line" noname_var = ":FILEPATH=/usr/bin/addr2line" notype_var = "CMAKE_ADDR2LINE:=/usr/bin/addr2line" bool_var = "CMAKE_ADDR2LINE:BOOL=ON" def test_row_creation(self): var_name = "CMAKE_ADDR2LINE" row = cmake_row(self.filepath_var_valid, 0) with self.subTest(): self.assertEqual(row.name, var_name) with self.subTest(): self.assertEqual(row.row_type, row_type.VARIABLE) with self.subTest(): self.assertEqual(row.get_val(), "/usr/bin/addr2line") with self.subTest(): self.assertEqual(row.row_number, 0) def test_slash_comment_row(self): row = cmake_row("//" + self.filepath_var_valid, 0) with self.subTest(): self.assertEqual(row.row_type, row_type.SLASH_COMMENT) with self.subTest(): self.assertEqual(row.serialize(), "//" + self.filepath_var_valid) def test_pound_comment_row(self): row = cmake_row("#" + self.filepath_var_valid, 0) with self.subTest(): self.assertEqual(row.row_type, row_type.POUND_COMMENT) with self.subTest(): self.assertEqual(row.serialize(), "#" + self.filepath_var_valid) def test_noname_row(self): self.assertRaises(ValueError, cmake_row, self.noname_var, 0) def test_empty_line(self): row = cmake_row("", 0) self.assertEqual(row.row_type, row_type.EMPTY) def test_notype_row(self): self.assertRaises(ValueError, cmake_row, self.notype_var, 0) def test_bool_row(self): """ we use assertEqual instead of assertTrue to avoid false positives with casting any other value to bool. """ row = cmake_row(self.bool_var, 0) with self.subTest(): self.assertEqual(row.val.value, True) with self.subTest(): self.assertEqual(row.serialize(), self.bool_var) def test_emtpy_row(self): row = cmake_row("", 0) self.assertEqual("", row.serialize()) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/syscalls.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/tty_struct.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/system_mmap.h> #include "termutil.h" #include "dp_int.h" struct debugger_cmd { const char *name; const char *alias; int (*handler)(int argc, char **argv); const char *help; }; static int cmd_resolve(int argc, char **argv) { ulong addr = find_addr_of_symbol(argv[0]); if (addr) { dp_write_raw("%p\n", TO_PTR(addr)); } else { dp_write_raw("Symbol '%s' not found\n", argv[0]); } return 0; } static int cmd_reboot(int argc, char **argv) { reboot(); printk("Reboot failed. Leaving the system fully halted."); return -1; } static int cmd_quit(int argc, char **argv) { dp_write_raw("Debugger exit: leaving the system fully halted."); return -1; } static int cmd_mmap(int argc, char **argv) { dump_memory_map(); return 0; } static void cmd_print_help(void) { dp_write_raw("\n"); dp_write_raw("Syntax:\n"); dp_write_raw(" print [<n>] <fmt> <vaddr/sym>\n"); dp_write_raw("\n"); dp_write_raw(" <n> is the number of consecutive items to print\n"); dp_write_raw(" <fmt> is {i|u|x}<bits>\n"); dp_write_raw(" i - signed integer\n"); dp_write_raw(" u - unsigned integer\n"); dp_write_raw(" x - unsigned integer (hex)\n"); dp_write_raw("\n"); } static void do_print_val(char type, u64 val, ulong w) { switch (type) { case 'x': switch (w) { case 1: dp_write_raw("%02x ", *(u8 *)&val); break; case 2: dp_write_raw("%04x ", *(u16 *)&val); break; case 4: dp_write_raw("%08x ", *(u32 *)&val); break; case 8: dp_write_raw("%16lx ", *(u64 *)&val); break; } break; case 'd': case 'i': switch (w) { case 1: dp_write_raw("%10d ", *(s8 *)&val); break; case 2: dp_write_raw("%10d ", *(s16 *)&val); break; case 4: dp_write_raw("%10d ", *(s32 *)&val); break; case 8: dp_write_raw("%20ld ", *(s64 *)&val); break; } break; case 'u': switch (w) { case 1: dp_write_raw("%10u ", *(u8 *)&val); break; case 2: dp_write_raw("%10u ", *(u16 *)&val); break; case 4: dp_write_raw("%10u ", *(u32 *)&val); break; case 8: dp_write_raw("%20lu ", *(u64 *)&val); break; } break; } } static int cmd_print(int argc, char **argv) { int rc, error = 0; char type; ulong vaddr, w, tmp, n = 1; u64 val; if (argc < 2 || argc > 3) { cmd_print_help(); return 0; } tmp = tilck_strtoul(argv[0], NULL, 10, &error); if (!error) { n = tmp; argc--; argv++; } if (argc < 2) { cmd_print_help(); return 0; } type = argv[0][0]; if (argv[0][1]) { w = tilck_strtoul(argv[0]+1, NULL, 10, &error); if (error || (w != 8 && w != 16 && w != 32 && w != 64)) { dp_write_raw("Invalid fmt: '%s'\n", argv[0]); return 0; } w >>= 3; } else { switch (type) { case 'x': w = 1; break; default: w = 4; break; } } if (argv[1][0] == '0' && argv[1][1] == 'x') { vaddr = tilck_strtoul(argv[1] + 2, NULL, 16, &error); if (error) { dp_write_raw("Invalid vaddr: %s\n", argv[1]); return 0; } } else { vaddr = find_addr_of_symbol(argv[1]); if (!vaddr) { dp_write_raw("Symbol '%s' not found\n", argv[1]); return 0; } } for (ulong i = 0; i < n; i++) { if (!(i % (8/w))) { if (i > 0) dp_write_raw("\n"); dp_write_raw("%p: ", vaddr); } rc = virtual_read(get_curr_pdir(), (void *)vaddr, &val, w); if (rc != (int)w) { dp_write_raw("Read error at vaddr: %p\n", vaddr); return 0; } do_print_val(type, val, w); vaddr += w; } dp_write_raw("\n"); return 0; } static int cmd_help(int argc, char **argv); static int cmd_va2pa(int argc, char **argv) { ulong vaddr, pa; int err; if (argc != 1) { dp_write_raw("Expected vaddr\n"); return 0; } if (!(argv[0][0] == '0' && argv[0][1] == 'x')) { dp_write_raw("Expected vaddr\n"); return 0; } vaddr = tilck_strtoul(argv[0] + 2, NULL, 16, &err); if (err) { dp_write_raw("Expected vaddr\n"); return 0; } err = get_mapping2(get_curr_pdir(), TO_PTR(vaddr), &pa); if (err) { dp_write_raw("The vaddr %p is not mapped in the current pdir\n", TO_PTR(vaddr)); return 0; } dp_write_raw("%p\n", TO_PTR(pa)); return 0; } static const struct debugger_cmd all_debug_cmds[] = { { "help", "?", &cmd_help, "show this help" }, { "resolve", "res", &cmd_resolve, "resolve a symbol to a vaddr" }, { "print", "p", &cmd_print, "print <n> <fmt> <vaddr/sym>: reads from mem" }, { "va2pa", NULL, &cmd_va2pa, "va2pa <vaddr>: convert a vaddr to paddr" }, { "mmap", NULL, &cmd_mmap, "Dump system's memory map" }, { "quit", NULL, &cmd_quit, "quit the debugger and halt the machine" }, { "reboot", NULL, &cmd_reboot, "reboot the machine" }, }; static int cmd_help(int argc, char **argv) { dp_write_raw("\n"); dp_write_raw("%-12s %-8s %s\n", "Name", "Alias", "Help"); dp_write_raw("----------------------------------------------------------\n"); for (u32 i = 0; i < ARRAY_SIZE(all_debug_cmds); i++) { const struct debugger_cmd *cmd = &all_debug_cmds[i]; dp_write_raw("%-12s %-8s %s\n", cmd->name, cmd->alias ? cmd->alias : "", cmd->help); } dp_write_raw("\n"); return 0; } int dp_mini_debugger_tool() { struct tty *t = get_curr_process_tty(); fs_handle h; char buf[128]; char *args[8]; ssize_t rc; int last_arg, n_args; if (!t) { printk("ERROR: the current process has no attached TTY\n"); return -1; } disable_preemption(); { devfs_kernel_create_handle_for(t->devfile, &h); } enable_preemption(); if (!h) { printk("ERROR: cannot open process's TTY\n"); return -1; } dp_write_raw("--- Tilck's panic debugger ---\n"); /* drain the input buffer */ handle_set_blocking(h, false); do { rc = vfs_read(h, buf, sizeof(buf)); } while (rc == -EINTR || rc == sizeof(buf)); handle_set_blocking(h, true); while (true) { dp_write_raw("> "); bzero(buf, sizeof(buf)); rc = vfs_read(h, buf, sizeof(buf)); if (rc < 0) break; buf[rc] = 0; n_args = 0; last_arg = 0; for (int i = 0; i < rc; i++) { if (isspace(buf[i])) { if (i != last_arg && !isspace(buf[last_arg])) args[n_args++] = buf + last_arg; buf[i] = 0; last_arg = i + 1; } } if (!n_args) continue; // for (int i = 0; i < n_args; i++) // dp_write_raw("arg[%d]: '%s'\n", i, args[i]); rc = 1; for (u32 i = 0; i < ARRAY_SIZE(all_debug_cmds); i++) { const struct debugger_cmd *cmd = &all_debug_cmds[i]; if (!strcmp(cmd->name, args[0]) || (cmd->alias && !strcmp(cmd->alias, args[0]))) { rc = cmd->handler(n_args - 1, args + 1); break; } } if (rc < 0) break; if (rc == 0) continue; if (n_args > 0) dp_write_raw("Unrecognized command '%s'\n", args[0]); } devfs_kernel_destory_handle(h); return rc; } <file_sep>/****************************************************************************** * * Module Name: exprep - ACPI AML field prep utilities * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlcode.h" #include "acnamesp.h" #include "acdispat.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exprep") /* Local prototypes */ static UINT32 AcpiExDecodeFieldAccess ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 FieldFlags, UINT32 *ReturnByteAlignment); #ifdef ACPI_UNDER_DEVELOPMENT static UINT32 AcpiExGenerateAccess ( UINT32 FieldBitOffset, UINT32 FieldBitLength, UINT32 RegionLength); /******************************************************************************* * * FUNCTION: AcpiExGenerateAccess * * PARAMETERS: FieldBitOffset - Start of field within parent region/buffer * FieldBitLength - Length of field in bits * RegionLength - Length of parent in bytes * * RETURN: Field granularity (8, 16, 32 or 64) and * ByteAlignment (1, 2, 3, or 4) * * DESCRIPTION: Generate an optimal access width for fields defined with the * AnyAcc keyword. * * NOTE: Need to have the RegionLength in order to check for boundary * conditions (end-of-region). However, the RegionLength is a deferred * operation. Therefore, to complete this implementation, the generation * of this access width must be deferred until the region length has * been evaluated. * ******************************************************************************/ static UINT32 AcpiExGenerateAccess ( UINT32 FieldBitOffset, UINT32 FieldBitLength, UINT32 RegionLength) { UINT32 FieldByteLength; UINT32 FieldByteOffset; UINT32 FieldByteEndOffset; UINT32 AccessByteWidth; UINT32 FieldStartOffset; UINT32 FieldEndOffset; UINT32 MinimumAccessWidth = 0xFFFFFFFF; UINT32 MinimumAccesses = 0xFFFFFFFF; UINT32 Accesses; ACPI_FUNCTION_TRACE (ExGenerateAccess); /* Round Field start offset and length to "minimal" byte boundaries */ FieldByteOffset = ACPI_DIV_8 ( ACPI_ROUND_DOWN (FieldBitOffset, 8)); FieldByteEndOffset = ACPI_DIV_8 ( ACPI_ROUND_UP (FieldBitLength + FieldBitOffset, 8)); FieldByteLength = FieldByteEndOffset - FieldByteOffset; ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Bit length %u, Bit offset %u\n", FieldBitLength, FieldBitOffset)); ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Byte Length %u, Byte Offset %u, End Offset %u\n", FieldByteLength, FieldByteOffset, FieldByteEndOffset)); /* * Iterative search for the maximum access width that is both aligned * and does not go beyond the end of the region * * Start at ByteAcc and work upwards to QwordAcc max. (1,2,4,8 bytes) */ for (AccessByteWidth = 1; AccessByteWidth <= 8; AccessByteWidth <<= 1) { /* * 1) Round end offset up to next access boundary and make sure that * this does not go beyond the end of the parent region. * 2) When the Access width is greater than the FieldByteLength, we * are done. (This does not optimize for the perfectly aligned * case yet). */ if (ACPI_ROUND_UP (FieldByteEndOffset, AccessByteWidth) <= RegionLength) { FieldStartOffset = ACPI_ROUND_DOWN (FieldByteOffset, AccessByteWidth) / AccessByteWidth; FieldEndOffset = ACPI_ROUND_UP ((FieldByteLength + FieldByteOffset), AccessByteWidth) / AccessByteWidth; Accesses = FieldEndOffset - FieldStartOffset; ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "AccessWidth %u end is within region\n", AccessByteWidth)); ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Field Start %u, Field End %u -- requires %u accesses\n", FieldStartOffset, FieldEndOffset, Accesses)); /* Single access is optimal */ if (Accesses <= 1) { ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Entire field can be accessed " "with one operation of size %u\n", AccessByteWidth)); return_VALUE (AccessByteWidth); } /* * Fits in the region, but requires more than one read/write. * try the next wider access on next iteration */ if (Accesses < MinimumAccesses) { MinimumAccesses = Accesses; MinimumAccessWidth = AccessByteWidth; } } else { ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "AccessWidth %u end is NOT within region\n", AccessByteWidth)); if (AccessByteWidth == 1) { ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Field goes beyond end-of-region!\n")); /* Field does not fit in the region at all */ return_VALUE (0); } /* * This width goes beyond the end-of-region, back off to * previous access */ ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Backing off to previous optimal access width of %u\n", MinimumAccessWidth)); return_VALUE (MinimumAccessWidth); } } /* * Could not read/write field with one operation, * just use max access width */ ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Cannot access field in one operation, using width 8\n")); return_VALUE (8); } #endif /* ACPI_UNDER_DEVELOPMENT */ /******************************************************************************* * * FUNCTION: AcpiExDecodeFieldAccess * * PARAMETERS: ObjDesc - Field object * FieldFlags - Encoded fieldflags (contains access bits) * ReturnByteAlignment - Where the byte alignment is returned * * RETURN: Field granularity (8, 16, 32 or 64) and * ByteAlignment (1, 2, 3, or 4) * * DESCRIPTION: Decode the AccessType bits of a field definition. * ******************************************************************************/ static UINT32 AcpiExDecodeFieldAccess ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 FieldFlags, UINT32 *ReturnByteAlignment) { UINT32 Access; UINT32 ByteAlignment; UINT32 BitLength; ACPI_FUNCTION_TRACE (ExDecodeFieldAccess); Access = (FieldFlags & AML_FIELD_ACCESS_TYPE_MASK); switch (Access) { case AML_FIELD_ACCESS_ANY: #ifdef ACPI_UNDER_DEVELOPMENT ByteAlignment = AcpiExGenerateAccess (ObjDesc->CommonField.StartFieldBitOffset, ObjDesc->CommonField.BitLength, 0xFFFFFFFF /* Temp until we pass RegionLength as parameter */); BitLength = ByteAlignment * 8; #endif ByteAlignment = 1; BitLength = 8; break; case AML_FIELD_ACCESS_BYTE: case AML_FIELD_ACCESS_BUFFER: /* ACPI 2.0 (SMBus Buffer) */ ByteAlignment = 1; BitLength = 8; break; case AML_FIELD_ACCESS_WORD: ByteAlignment = 2; BitLength = 16; break; case AML_FIELD_ACCESS_DWORD: ByteAlignment = 4; BitLength = 32; break; case AML_FIELD_ACCESS_QWORD: /* ACPI 2.0 */ ByteAlignment = 8; BitLength = 64; break; default: /* Invalid field access type */ ACPI_ERROR ((AE_INFO, "Unknown field access type 0x%X", Access)); return_UINT32 (0); } if (ObjDesc->Common.Type == ACPI_TYPE_BUFFER_FIELD) { /* * BufferField access can be on any byte boundary, so the * ByteAlignment is always 1 byte -- regardless of any ByteAlignment * implied by the field access type. */ ByteAlignment = 1; } *ReturnByteAlignment = ByteAlignment; return_UINT32 (BitLength); } /******************************************************************************* * * FUNCTION: AcpiExPrepCommonFieldObject * * PARAMETERS: ObjDesc - The field object * FieldFlags - Access, LockRule, and UpdateRule. * The format of a FieldFlag is described * in the ACPI specification * FieldAttribute - Special attributes (not used) * FieldBitPosition - Field start position * FieldBitLength - Field length in number of bits * * RETURN: Status * * DESCRIPTION: Initialize the areas of the field object that are common * to the various types of fields. Note: This is very "sensitive" * code because we are solving the general case for field * alignment. * ******************************************************************************/ ACPI_STATUS AcpiExPrepCommonFieldObject ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 FieldFlags, UINT8 FieldAttribute, UINT32 FieldBitPosition, UINT32 FieldBitLength) { UINT32 AccessBitWidth; UINT32 ByteAlignment; UINT32 NearestByteAddress; ACPI_FUNCTION_TRACE (ExPrepCommonFieldObject); /* * Note: the structure being initialized is the * ACPI_COMMON_FIELD_INFO; No structure fields outside of the common * area are initialized by this procedure. */ ObjDesc->CommonField.FieldFlags = FieldFlags; ObjDesc->CommonField.Attribute = FieldAttribute; ObjDesc->CommonField.BitLength = FieldBitLength; /* * Decode the access type so we can compute offsets. The access type gives * two pieces of information - the width of each field access and the * necessary ByteAlignment (address granularity) of the access. * * For AnyAcc, the AccessBitWidth is the largest width that is both * necessary and possible in an attempt to access the whole field in one * I/O operation. However, for AnyAcc, the ByteAlignment is always one * byte. * * For all Buffer Fields, the ByteAlignment is always one byte. * * For all other access types (Byte, Word, Dword, Qword), the Bitwidth is * the same (equivalent) as the ByteAlignment. */ AccessBitWidth = AcpiExDecodeFieldAccess ( ObjDesc, FieldFlags, &ByteAlignment); if (!AccessBitWidth) { return_ACPI_STATUS (AE_AML_OPERAND_VALUE); } /* Setup width (access granularity) fields (values are: 1, 2, 4, 8) */ ObjDesc->CommonField.AccessByteWidth = (UINT8) ACPI_DIV_8 (AccessBitWidth); /* * BaseByteOffset is the address of the start of the field within the * region. It is the byte address of the first *datum* (field-width data * unit) of the field. (i.e., the first datum that contains at least the * first *bit* of the field.) * * Note: ByteAlignment is always either equal to the AccessBitWidth or 8 * (Byte access), and it defines the addressing granularity of the parent * region or buffer. */ NearestByteAddress = ACPI_ROUND_BITS_DOWN_TO_BYTES (FieldBitPosition); ObjDesc->CommonField.BaseByteOffset = (UINT32) ACPI_ROUND_DOWN (NearestByteAddress, ByteAlignment); /* * StartFieldBitOffset is the offset of the first bit of the field within * a field datum. */ ObjDesc->CommonField.StartFieldBitOffset = (UINT8) (FieldBitPosition - ACPI_MUL_8 (ObjDesc->CommonField.BaseByteOffset)); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExPrepFieldValue * * PARAMETERS: Info - Contains all field creation info * * RETURN: Status * * DESCRIPTION: Construct an object of type ACPI_OPERAND_OBJECT with a * subtype of DefField and connect it to the parent Node. * ******************************************************************************/ ACPI_STATUS AcpiExPrepFieldValue ( ACPI_CREATE_FIELD_INFO *Info) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *SecondDesc = NULL; ACPI_STATUS Status; UINT32 AccessByteWidth; UINT32 Type; ACPI_FUNCTION_TRACE (ExPrepFieldValue); /* Parameter validation */ if (Info->FieldType != ACPI_TYPE_LOCAL_INDEX_FIELD) { if (!Info->RegionNode) { ACPI_ERROR ((AE_INFO, "Null RegionNode")); return_ACPI_STATUS (AE_AML_NO_OPERAND); } Type = AcpiNsGetType (Info->RegionNode); if (Type != ACPI_TYPE_REGION) { ACPI_ERROR ((AE_INFO, "Needed Region, found type 0x%X (%s)", Type, AcpiUtGetTypeName (Type))); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } } /* Allocate a new field object */ ObjDesc = AcpiUtCreateInternalObject (Info->FieldType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize areas of the object that are common to all fields */ ObjDesc->CommonField.Node = Info->FieldNode; Status = AcpiExPrepCommonFieldObject (ObjDesc, Info->FieldFlags, Info->Attribute, Info->FieldBitPosition, Info->FieldBitLength); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } /* Initialize areas of the object that are specific to the field type */ switch (Info->FieldType) { case ACPI_TYPE_LOCAL_REGION_FIELD: ObjDesc->Field.RegionObj = AcpiNsGetAttachedObject (Info->RegionNode); /* Fields specific to GenericSerialBus fields */ ObjDesc->Field.AccessLength = Info->AccessLength; if (Info->ConnectionNode) { SecondDesc = Info->ConnectionNode->Object; if (!(SecondDesc->Common.Flags & AOPOBJ_DATA_VALID)) { Status = AcpiDsGetBufferArguments (SecondDesc); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } } ObjDesc->Field.ResourceBuffer = SecondDesc->Buffer.Pointer; ObjDesc->Field.ResourceLength = (UINT16) SecondDesc->Buffer.Length; } else if (Info->ResourceBuffer) { ObjDesc->Field.ResourceBuffer = Info->ResourceBuffer; ObjDesc->Field.ResourceLength = Info->ResourceLength; } ObjDesc->Field.PinNumberIndex = Info->PinNumberIndex; /* Allow full data read from EC address space */ if ((ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_EC) && (ObjDesc->CommonField.BitLength > 8)) { AccessByteWidth = ACPI_ROUND_BITS_UP_TO_BYTES ( ObjDesc->CommonField.BitLength); /* Maximum byte width supported is 255 */ if (AccessByteWidth < 256) { ObjDesc->CommonField.AccessByteWidth = (UINT8) AccessByteWidth; } } ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "RegionField: BitOff %X, Off %X, Gran %X, Region %p\n", ObjDesc->Field.StartFieldBitOffset, ObjDesc->Field.BaseByteOffset, ObjDesc->Field.AccessByteWidth, ObjDesc->Field.RegionObj)); break; case ACPI_TYPE_LOCAL_BANK_FIELD: ObjDesc->BankField.Value = Info->BankValue; ObjDesc->BankField.RegionObj = AcpiNsGetAttachedObject (Info->RegionNode); ObjDesc->BankField.BankObj = AcpiNsGetAttachedObject (Info->RegisterNode); /* An additional reference for the attached objects */ AcpiUtAddReference (ObjDesc->BankField.RegionObj); AcpiUtAddReference (ObjDesc->BankField.BankObj); ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Bank Field: BitOff %X, Off %X, Gran %X, Region %p, BankReg %p\n", ObjDesc->BankField.StartFieldBitOffset, ObjDesc->BankField.BaseByteOffset, ObjDesc->Field.AccessByteWidth, ObjDesc->BankField.RegionObj, ObjDesc->BankField.BankObj)); /* * Remember location in AML stream of the field unit * opcode and operands -- since the BankValue * operands must be evaluated. */ SecondDesc = ObjDesc->Common.NextObject; SecondDesc->Extra.AmlStart = ACPI_CAST_PTR (ACPI_PARSE_OBJECT, Info->DataRegisterNode)->Named.Data; SecondDesc->Extra.AmlLength = ACPI_CAST_PTR (ACPI_PARSE_OBJECT, Info->DataRegisterNode)->Named.Length; break; case ACPI_TYPE_LOCAL_INDEX_FIELD: /* Get the Index and Data registers */ ObjDesc->IndexField.IndexObj = AcpiNsGetAttachedObject (Info->RegisterNode); ObjDesc->IndexField.DataObj = AcpiNsGetAttachedObject (Info->DataRegisterNode); if (!ObjDesc->IndexField.DataObj || !ObjDesc->IndexField.IndexObj) { ACPI_ERROR ((AE_INFO, "Null Index Object during field prep")); AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (AE_AML_INTERNAL); } /* An additional reference for the attached objects */ AcpiUtAddReference (ObjDesc->IndexField.DataObj); AcpiUtAddReference (ObjDesc->IndexField.IndexObj); /* * April 2006: Changed to match MS behavior * * The value written to the Index register is the byte offset of the * target field in units of the granularity of the IndexField * * Previously, the value was calculated as an index in terms of the * width of the Data register, as below: * * ObjDesc->IndexField.Value = (UINT32) * (Info->FieldBitPosition / ACPI_MUL_8 ( * ObjDesc->Field.AccessByteWidth)); * * February 2006: Tried value as a byte offset: * ObjDesc->IndexField.Value = (UINT32) * ACPI_DIV_8 (Info->FieldBitPosition); */ ObjDesc->IndexField.Value = (UINT32) ACPI_ROUND_DOWN ( ACPI_DIV_8 (Info->FieldBitPosition), ObjDesc->IndexField.AccessByteWidth); ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "IndexField: BitOff %X, Off %X, Value %X, " "Gran %X, Index %p, Data %p\n", ObjDesc->IndexField.StartFieldBitOffset, ObjDesc->IndexField.BaseByteOffset, ObjDesc->IndexField.Value, ObjDesc->Field.AccessByteWidth, ObjDesc->IndexField.IndexObj, ObjDesc->IndexField.DataObj)); break; default: /* No other types should get here */ break; } /* * Store the constructed descriptor (ObjDesc) into the parent Node, * preserving the current type of that NamedObj. */ Status = AcpiNsAttachObject ( Info->FieldNode, ObjDesc, AcpiNsGetType (Info->FieldNode)); ACPI_DEBUG_PRINT ((ACPI_DB_BFIELD, "Set NamedObj %p [%4.4s], ObjDesc %p\n", Info->FieldNode, AcpiUtGetNodeName (Info->FieldNode), ObjDesc)); /* Remove local reference to the object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/syscalls.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/process.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/term.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/tty_struct.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/mods/fb_console.h> #include <tilck/mods/tracing.h> #include "termutil.h" #include "dp_int.h" int dp_rows; int dp_cols; int dp_start_row; int dp_end_row; int dp_start_col; int dp_screen_start_row; int dp_screen_rows; bool ui_need_update; const char *modal_msg; struct dp_screen *dp_ctx; fs_handle dp_input_handle; static bool skip_next_keypress; static ATOMIC(bool) dp_running; static struct list dp_screens_list = STATIC_LIST_INIT(dp_screens_list); static inline void dp_write_header(int i, const char *s, bool selected) { if (selected) { dp_write_raw( E_COLOR_BR_WHITE "%d" REVERSE_VIDEO "[%s]" RESET_ATTRS " ", i, s ); } else { dp_write_raw("%d[%s]" RESET_ATTRS " ", i, s); } } static void dp_enter(void) { struct term_params tparams; struct dp_screen *pos; process_term_read_info(&tparams); dp_set_cursor_enabled(false); if (tparams.type == term_type_video) dp_switch_to_alt_buffer(); dp_rows = tparams.rows; dp_cols = tparams.cols; dp_start_row = (dp_rows - DP_H) / 2 + 1; dp_start_col = (dp_cols - DP_W) / 2 + 1; dp_end_row = dp_start_row + DP_H; dp_screen_start_row = dp_start_row + 3; dp_screen_rows = (DP_H - 2 - (dp_screen_start_row - dp_start_row)); list_for_each_ro(pos, &dp_screens_list, node) { pos->row_off = 0; pos->row_max = 0; if (pos->on_dp_enter) pos->on_dp_enter(); } } static void dp_exit(void) { struct term_params tparams; struct dp_screen *pos; process_term_read_info(&tparams); list_for_each_ro(pos, &dp_screens_list, node) { if (pos->on_dp_exit) pos->on_dp_exit(); } if (tparams.type == term_type_video) { dp_switch_to_default_buffer(); } else { dp_clear(); dp_write_raw("\n"); } dp_set_cursor_enabled(true); } void dp_register_screen(struct dp_screen *screen) { struct dp_screen *pos; struct list_node *pred = (struct list_node *)&dp_screens_list; list_for_each_ro(pos, &dp_screens_list, node) { if (pos->index < screen->index) pred = &pos->node; if (pos->index == screen->index) panic("[debugpanel] Index conflict while registering %s at %d", screen->label, screen->index); } list_add_after(pred, &screen->node); } static void redraw_screen(void) { struct dp_screen *pos; char buf[64]; int rc; dp_clear(); dp_move_cursor(dp_start_row + 1, dp_start_col + 2); list_for_each_ro(pos, &dp_screens_list, node) { dp_write_header(pos->index+1, pos->label, pos == dp_ctx); } dp_write_raw("q[Quit]" RESET_ATTRS " "); dp_ctx->draw_func(); dp_draw_rect_raw(dp_start_row, dp_start_col, DP_H, DP_W); dp_move_cursor(dp_start_row, dp_start_col + 2); dp_write_raw(E_COLOR_YELLOW "[ TilckDebugPanel ]" RESET_ATTRS); rc = snprintk(buf, sizeof(buf), "[rows %02d - %02d of %02d]", dp_ctx->row_off + 1, MIN(dp_ctx->row_off + dp_screen_rows, dp_ctx->row_max) + 1, dp_ctx->row_max + 1); dp_move_cursor(dp_end_row - 1, dp_start_col + DP_W - rc - 2); dp_write_raw(E_COLOR_BR_RED "%s" RESET_ATTRS, buf); dp_move_cursor(dp_rows, 1); ui_need_update = false; } static void dp_main_handle_keypress(struct key_event ke) { int rc; if ('0' <= ke.print_char && ke.print_char <= '9') { struct dp_screen *pos; rc = ke.print_char - '0'; list_for_each_ro(pos, &dp_screens_list, node) { if (pos->index == rc - 1 && pos != dp_ctx) { dp_ctx = pos; ui_need_update = true; break; } } } else if (ke.key == KEY_PAGE_DOWN) { if (dp_ctx->row_off + dp_screen_rows < dp_ctx->row_max) { dp_ctx->row_off++; ui_need_update = true; } } else if (ke.key == KEY_PAGE_UP) { if (dp_ctx->row_off > 0) { dp_ctx->row_off--; ui_need_update = true; } } } static int dp_main_body(enum term_type tt, struct key_event ke) { int rc; bool dp_screen_key_handled = false; if (!skip_next_keypress) { dp_main_handle_keypress(ke); if (!ui_need_update && dp_ctx->on_keypress_func) { rc = dp_ctx->on_keypress_func(ke); if (rc == kb_handler_ok_and_stop) return 1; /* skip redraw_screen() */ if (rc != kb_handler_nak) dp_screen_key_handled = true; } } else { skip_next_keypress = false; ui_need_update = true; } if (ui_need_update || modal_msg) { if (tt == term_type_video) term_pause_output(); redraw_screen(); if (modal_msg) { dp_show_modal_msg(modal_msg); modal_msg = NULL; skip_next_keypress = true; } if (tt == term_type_video) term_restart_output(); } return dp_screen_key_handled; } void handle_set_blocking(fs_handle h, bool blocking) { struct fs_handle_base *hb = h; disable_preemption(); { if (blocking) hb->fl_flags &= ~O_NONBLOCK; else hb->fl_flags |= O_NONBLOCK; } enable_preemption(); } void dp_set_input_blocking(bool blocking) { handle_set_blocking(dp_input_handle, blocking); } static void dp_common_entry(bool only_tracing) { enum term_type tt; struct key_event ke; struct tty *t = get_curr_process_tty(); int rc; if (dp_running) return; if (!t) { printk("ERROR: debugpanel: the current process has no attached TTY\n"); return; } disable_preemption(); { devfs_kernel_create_handle_for(t->devfile, &dp_input_handle); } enable_preemption(); if (!dp_input_handle) { printk("ERROR: debugpanel: cannot open process's TTY\n"); return; } dp_running = true; tt = t->tparams.type; dp_ctx = list_first_obj(&dp_screens_list, struct dp_screen, node); dp_enter(); disable_preemption(); { tty_set_raw_mode(t); dp_set_input_blocking(false); } enable_preemption(); bzero(&ke, sizeof(ke)); ui_need_update = true; if (only_tracing) { if (MOD_tracing) dp_tracing_screen(); } else { while (true) { rc = dp_main_body(tt, ke); if (!rc && ke.print_char == 'q') break; if (dp_read_ke_from_tty(&ke) < 0) break; if (ke.print_char == DP_KEY_CTRL_C) break; } } disable_preemption(); { dp_set_input_blocking(true); tty_reset_termios(get_curr_process_tty()); } enable_preemption(); dp_exit(); devfs_kernel_destory_handle(dp_input_handle); dp_running = false; } static int dp_default_entry() { dp_common_entry(false); return 0; } static int dp_direct_tracing_mode_entry() { dp_common_entry(true); return 0; } static int dp_ps_tool() { struct tty *t = get_curr_process_tty(); if (!t) { printk("ERROR: debugpanel: the current process has no attached TTY\n"); return -ENOTTY; } dp_dump_task_list(false, true); dp_write_raw("\r\n"); return 0; } static void dp_init(void) { struct dp_screen *pos; register_tilck_cmd(TILCK_CMD_DEBUG_PANEL, dp_default_entry); register_tilck_cmd(TILCK_CMD_PS_TOOL, dp_ps_tool); register_tilck_cmd(TILCK_CMD_DEBUGGER_TOOL, dp_mini_debugger_tool); if (MOD_tracing) register_tilck_cmd(TILCK_CMD_TRACING_TOOL, dp_direct_tracing_mode_entry); list_for_each_ro(pos, &dp_screens_list, node) { if (pos->first_setup) pos->first_setup(); } } static struct module dp_module = { .name = "debugpanel", .priority = MOD_dp_prio, .init = &dp_init, }; REGISTER_MODULE(&dp_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/process.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/fs/kernelfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/pipe.h> #include <fcntl.h> // system header static inline bool is_fd_in_valid_range(int fd) { return IN_RANGE(fd, 0, MAX_HANDLES); } static int get_free_handle_num_ge(struct process *pi, int ge) { ASSERT(kmutex_is_curr_task_holding_lock(&pi->fslock)); for (int free_fd = ge; free_fd < MAX_HANDLES; free_fd++) if (!pi->handles[free_fd]) return free_fd; return -1; } static int get_free_handle_num(struct process *pi) { return get_free_handle_num_ge(pi, 0); } /* * Even if getting the fs_handle this way is safe now, it won't be anymore * after thread-support is added to the kernel. For example, a thread might * work with given handle while another closes it. * * TODO: introduce a ref-count in the fs_base_handle struct and function like * put_fs_handle() or rename both to something like acquire/release_fs_handle. */ fs_handle get_fs_handle(int fd) { struct task *curr = get_curr_task(); fs_handle handle = NULL; kmutex_lock(&curr->pi->fslock); if (is_fd_in_valid_range(fd) && curr->pi->handles[fd]) handle = curr->pi->handles[fd]; kmutex_unlock(&curr->pi->fslock); return handle; } int sys_open(const char *u_path, int flags, mode_t mode) { int ret, free_fd; struct task *curr = get_curr_task(); char *path = curr->args_copybuf; size_t written = 0; fs_handle h = NULL; STATIC_ASSERT((ARGS_COPYBUF_SIZE / 2) >= MAX_PATH); /* * NOTE: O_DIRECT for regular files (not pipes!) is supported out-of-the-box * because Tilck has no I/O cache. */ if (flags & O_ASYNC) return -EINVAL; if ((flags & O_TMPFILE) == O_TMPFILE) return -EOPNOTSUPP; /* TODO: Tilck does not support O_TMPFILE yet */ /* Apply the umask upfront */ mode &= ~curr->pi->umask; if ((ret = duplicate_user_path(path, u_path, MAX_PATH, &written))) return ret; kmutex_lock(&curr->pi->fslock); if ((free_fd = get_free_handle_num(curr->pi)) < 0) goto no_fds; if ((ret = vfs_open(path, &h, flags, mode)) < 0) goto end; ASSERT(h != NULL); curr->pi->handles[free_fd] = h; ret = free_fd; end: kmutex_unlock(&curr->pi->fslock); return ret; no_fds: ret = -EMFILE; goto end; } int sys_creat(const char *u_path, mode_t mode) { return sys_open(u_path, O_CREAT | O_WRONLY | O_TRUNC, mode); } int sys_unlink(const char *u_path) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; size_t written = 0; int ret; if ((ret = duplicate_user_path(path, u_path, MAX_PATH, &written))) return ret; return vfs_unlink(path); } int sys_rmdir(const char *u_path) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; size_t written = 0; int ret; if ((ret = duplicate_user_path(path, u_path, MAX_PATH, &written))) return ret; return vfs_rmdir(path); } int sys_close(int fd) { struct task *curr = get_curr_task(); fs_handle handle; int ret = 0; if (!(handle = get_fs_handle(fd))) return -EBADF; kmutex_lock(&curr->pi->fslock); { vfs_close(handle); curr->pi->handles[fd] = NULL; } kmutex_unlock(&curr->pi->fslock); return ret; } int sys_mkdir(const char *u_path, mode_t mode) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; size_t written = 0; int ret; /* Apply the umask upfront */ mode &= ~curr->pi->umask; if ((ret = duplicate_user_path(path, u_path, MAX_PATH, &written))) return ret; return vfs_mkdir(path, mode); } int sys_read(int fd, void *u_buf, size_t count) { int ret; struct task *curr = get_curr_task(); struct fs_handle_base *h; if (!(h = get_fs_handle(fd))) return -EBADF; /* * NOTE: * * From `man 2 read`: * * On Linux, read() (and similar system calls) will transfer at most * 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes * actually transferred. (This is true on both 32-bit and 64-bit systems.) * * This means that it's perfectly fine to use `int` instead of ssize_t as * return type of sys_read(). */ count = MIN(count, (size_t)INT32_MAX); if (h->spec_flags & VFS_SPFL_NO_USER_COPY) { ret = (int) vfs_read(h, u_buf, count); } else { count = MIN(count, IO_COPYBUF_SIZE); ret = (int) vfs_read(h, curr->io_copybuf, count); if (ret > 0) { if (copy_to_user(u_buf, curr->io_copybuf, (size_t)ret) < 0) { // Do we have to rewind the stream in this case? I don't think so. ret = -EFAULT; } } } return ret; } int sys_write(int fd, const void *u_buf, size_t count) { struct task *curr = get_curr_task(); struct fs_handle_base *h; int ret; if (!(h = get_fs_handle(fd))) return -EBADF; count = MIN(count, (size_t)INT32_MAX); if (h->spec_flags & VFS_SPFL_NO_USER_COPY) { ret = (int)vfs_write(h, (void *)u_buf, count); } else { count = MIN(count, IO_COPYBUF_SIZE); if (!copy_from_user(curr->io_copybuf, u_buf, count)) ret = (int)vfs_write(h, (char *)curr->io_copybuf, count); else ret = -EFAULT; } return ret; } int sys_pread64(int fd, void *u_buf, size_t count, s64 off) { int ret; struct task *curr = get_curr_task(); struct fs_handle_base *h; if (off < 0 || off > OFFT_MAX) return -EINVAL; if (!(h = get_fs_handle(fd))) return -EBADF; count = MIN(count, (size_t)INT32_MAX); if (h->spec_flags & VFS_SPFL_NO_USER_COPY) { ret = (int) vfs_pread(h, u_buf, count, (offt)off); } else { count = MIN(count, IO_COPYBUF_SIZE); ret = (int) vfs_pread(h, curr->io_copybuf, count, (offt)off); if (ret > 0) { if (copy_to_user(u_buf, curr->io_copybuf, (size_t)ret)) { // Do we have to rewind the stream in this case? I don't think so. ret = -EFAULT; } } } return ret; } int sys_pwrite64(int fd, const void *u_buf, size_t count, s64 off) { struct task *curr = get_curr_task(); struct fs_handle_base *h; int ret; if (off < 0 || off > OFFT_MAX) return -EINVAL; if (!(h = get_fs_handle(fd))) return -EBADF; count = MIN(count, (size_t)INT32_MAX); if (h->spec_flags & VFS_SPFL_NO_USER_COPY) { ret = (int)vfs_pwrite(h, (void *)u_buf, count, (offt)off); } else { count = MIN(count, IO_COPYBUF_SIZE); if (!copy_from_user(curr->io_copybuf, u_buf, count)) ret = (int)vfs_pwrite(h, (char *)curr->io_copybuf, count, (offt)off); else ret = -EFAULT; } return ret; } int sys_ioctl(int fd, ulong request, void *argp) { fs_handle handle = get_fs_handle(fd); if (!handle) return -EBADF; return vfs_ioctl(handle, request, argp); } static bool iov_len_overflow(const struct iovec *iov, int iovcnt) { ssize_t tot_len = 0; for (int i = 0; i < iovcnt; i++) { tot_len += iov[i].iov_len; if (tot_len < 0) return true; /* overflow detected */ } return false; } int sys_writev(int fd, const struct iovec *u_iov, int u_iovcnt) { struct task *curr = get_curr_task(); struct iovec *iov = (void *)curr->args_copybuf; const u32 iovcnt = (u32) u_iovcnt; fs_handle handle; if (u_iovcnt <= 0) return -EINVAL; if (sizeof(struct iovec) * iovcnt > ARGS_COPYBUF_SIZE) return -EINVAL; if (copy_from_user(iov, u_iov, sizeof(struct iovec) * iovcnt)) return -EFAULT; if (iov_len_overflow(iov, u_iovcnt)) return -EINVAL; if (!(handle = get_fs_handle(fd))) return -EBADF; return (int)vfs_writev(handle, iov, u_iovcnt); } int sys_readv(int fd, const struct iovec *u_iov, int u_iovcnt) { struct task *curr = get_curr_task(); struct iovec *iov = (void *)curr->args_copybuf; const u32 iovcnt = (u32) u_iovcnt; fs_handle handle; if (u_iovcnt <= 0) return -EINVAL; if (sizeof(struct iovec) * iovcnt > ARGS_COPYBUF_SIZE) return -EINVAL; if (copy_from_user(iov, u_iov, sizeof(struct iovec) * iovcnt)) return -EFAULT; if (iov_len_overflow(iov, u_iovcnt)) return -EINVAL; if (!(handle = get_fs_handle(fd))) return -EBADF; return (int)vfs_readv(handle, iov, u_iovcnt); } static int call_vfs_stat64(const char *u_path, struct k_stat64 *u_statbuf, bool res_last_sl) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; struct k_stat64 statbuf; int rc = 0; rc = copy_str_from_user(path, u_path, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; if ((rc = vfs_stat64(path, &statbuf, res_last_sl))) return rc; if (copy_to_user(u_statbuf, &statbuf, sizeof(struct k_stat64))) rc = -EFAULT; return rc; } int sys_stat64(const char *u_path, struct k_stat64 *u_statbuf) { return call_vfs_stat64(u_path, u_statbuf, true); } int sys_lstat64(const char *u_path, struct k_stat64 *u_statbuf) { return call_vfs_stat64(u_path, u_statbuf, false); } int sys_fstat64(int fd, struct k_stat64 *u_statbuf) { struct k_stat64 statbuf; fs_handle h; int rc = 0; if (!(h = get_fs_handle(fd))) return -EBADF; if ((rc = vfs_fstat64(h, &statbuf))) return rc; if (copy_to_user(u_statbuf, &statbuf, sizeof(struct k_stat64))) rc = -EFAULT; return rc; } int sys_symlink(const char *u_target, const char *u_linkpath) { struct task *curr = get_curr_task(); char *target = curr->args_copybuf + (ARGS_COPYBUF_SIZE / 4) * 0; char *linkpath = curr->args_copybuf + (ARGS_COPYBUF_SIZE / 4) * 1; int rc = 0; STATIC_ASSERT(ARGS_COPYBUF_SIZE / 4 >= MAX_PATH); rc = copy_str_from_user(target, u_target, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; rc = copy_str_from_user(linkpath, u_linkpath, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; if (!*target || !*linkpath) return -ENOENT; /* target or linkpath is an empty string */ return vfs_symlink(target, linkpath); } int sys_readlink(const char *u_pathname, char *u_buf, size_t u_bufsize) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf + (ARGS_COPYBUF_SIZE / 4) * 0; char *buf = curr->args_copybuf + (ARGS_COPYBUF_SIZE / 4) * 1; size_t ret_bs; int rc; STATIC_ASSERT(ARGS_COPYBUF_SIZE / 4 >= MAX_PATH); rc = copy_str_from_user(path, u_pathname, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; rc = vfs_readlink(path, buf); if (rc < 0) return rc; ret_bs = (size_t) rc; rc = copy_to_user(u_buf, buf, MIN(ret_bs, u_bufsize)); if (rc < 0) return -EFAULT; return (int) ret_bs; } int sys_ia32_truncate64(const char *u_path, s64 len) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; int rc; if (len < 0) return -EINVAL; rc = copy_str_from_user(path, u_path, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; // NOTE: truncating the 64-bit length to a pointer-size integer return vfs_truncate(path, (offt)len); } int sys_ia32_ftruncate64(int fd, s64 len) { fs_handle h; if (!(h = get_fs_handle(fd))) return -EBADF; // NOTE: truncating the 64-bit length to a pointer-size integer return vfs_ftruncate(h, (offt)len); } int sys_llseek(int fd, size_t off_hi, size_t off_low, u64 *u_result, u32 whence) { const s64 off64 = (s64)(((u64)off_hi << 32) | off_low); fs_handle handle; offt new_off; u64 res; STATIC_ASSERT(sizeof(new_off) >= sizeof(offt)); if (!(handle = get_fs_handle(fd))) return -EBADF; if (sizeof(off64) > sizeof(offt)) { /* * Check if we can handle such an offset. See the definition of `offt` * for comments about that. */ if (off64 < INT32_MIN || off64 > INT32_MAX) return -EINVAL; } new_off = vfs_seek(handle, (offt)off64, (int)whence); if (new_off < 0) return (int) new_off; /* return back vfs_seek's error */ res = (u64)new_off; if (copy_to_user(u_result, &res, sizeof(res))) return -EBADF; return 0; } int sys_getdents64(int fd, struct linux_dirent64 *u_dirp, u32 buf_size) { fs_handle handle; if (!(handle = get_fs_handle(fd))) return -EBADF; return vfs_getdents64(handle, u_dirp, buf_size); } int sys_access(const char *u_path, mode_t mode) { // TODO: check mode and file r/w flags. return 0; } /* * NOTE: on Tilck, this syscall _can_ return -ENOMEM, while Linux would return * -EBADF or -EMFILE in the same case. See the comment below. */ int sys_dup2(int oldfd, int newfd) { int rc; fs_handle old_h, new_h; struct task *curr = get_curr_task(); if (!is_fd_in_valid_range(oldfd)) return -EBADF; if (!is_fd_in_valid_range(newfd)) return -EBADF; if (newfd == oldfd) return -EINVAL; kmutex_lock(&curr->pi->fslock); if (!(old_h = get_fs_handle(oldfd))) { rc = -EBADF; goto out; } new_h = get_fs_handle(newfd); if (new_h) { /* * CORNER CASE: In general, the new handle should be available, but the * linux kernel allows the user code to pass also an IN-USE handle: in * that case the behavior is to just silently close that handle, before * reusing it. */ vfs_close(new_h); new_h = NULL; } if ((rc = vfs_dup(old_h, &new_h))) { /* * if (rc == -ENOMEM) * rc = -EBADF; * * [BE_NICE] Creating a new file handle means allocating memory, no matter * if that happens every time like in Tilck or it's deferred using a sort * of dynamic array like the Linux kernel does. A memory allocation can * always fail, even when that's highly unlikely. In such cases, the * kernel _must_ return -ENOMEM. * * Unfortunately, according to the POSIX standard dup() and dup2() cannot * fail with -ENOMEM. Just, it's not part of the POSIX interface and it's * not clear to me why. In the Linux kernel, in the out-of-memory case, * dup() returns -EMFILE while dup2() returns -EBADF. * * Tilck tries to be more honest and returns -ENOMEM. */ goto out; } curr->pi->handles[newfd] = new_h; rc = newfd; out: kmutex_unlock(&curr->pi->fslock); return rc; } int sys_dup(int oldfd) { int rc = -EMFILE, free_fd; struct process *pi = get_curr_proc(); kmutex_lock(&pi->fslock); { free_fd = get_free_handle_num(pi); if (is_fd_in_valid_range(free_fd)) rc = sys_dup2(oldfd, free_fd); } kmutex_unlock(&pi->fslock); return rc; } static void debug_print_fcntl_command(int cmd) { switch (cmd) { case F_DUPFD: printk("fcntl: F_DUPFD\n"); break; case F_DUPFD_CLOEXEC: printk("fcntl: F_DUPFD_CLOEXEC\n"); break; case F_GETFD: printk("fcntl: F_GETFD\n"); break; case F_SETFD: printk("fcntl: F_SETFD\n"); break; case F_GETFL: printk("fcntl: F_GETFL\n"); break; case F_SETFL: printk("fcntl: F_SETFL\n"); break; case F_SETLK: printk("fcntl: F_SETLK\n"); break; case F_SETLKW: printk("fcntl: F_SETLKW\n"); break; case F_GETLK: printk("fcntl: F_GETLK\n"); break; /* Skipping several other commands */ default: printk("fcntl: unknown command\n"); } } void close_cloexec_handles(struct process *pi) { kmutex_lock(&pi->fslock); for (u32 i = 0; i < MAX_HANDLES; i++) { struct fs_handle_base *h = pi->handles[i]; if (h && (h->fd_flags & FD_CLOEXEC)) { vfs_close(h); pi->handles[i] = NULL; } } kmutex_unlock(&pi->fslock); } int sys_fcntl64(int fd, int cmd, int arg) { int rc = 0; struct task *curr = get_curr_task(); struct fs_handle_base *hb; if (!(hb = get_fs_handle(fd))) return -EBADF; switch (cmd) { case F_DUPFD: { kmutex_lock(&curr->pi->fslock); int new_fd = get_free_handle_num_ge(curr->pi, arg); rc = sys_dup2(fd, new_fd); kmutex_unlock(&curr->pi->fslock); return rc; } case F_DUPFD_CLOEXEC: { kmutex_lock(&curr->pi->fslock); int new_fd = get_free_handle_num_ge(curr->pi, arg); if (!(rc = sys_dup2(fd, new_fd))) { /* dup2 succeeded */ struct fs_handle_base *h2 = get_fs_handle(new_fd); ASSERT(h2 != NULL); h2->fd_flags |= FD_CLOEXEC; } kmutex_unlock(&curr->pi->fslock); return rc; } case F_SETFD: hb->fd_flags = arg & 0xffff; break; case F_GETFD: return hb->fd_flags; case F_SETFL: /* * In general, O_DIRECT is implicitly supported by Tilck, but for * pipes O_DIRECT has a different meaning: it makes the pipes to work * in a "packet" mode, which is not supported by Tilck, at the moment. * * Therefore, in order to avoid debugging weird stuff, while in * development, just crash the kernel with NOT_IMPLEMENTED() making the * problem evident. At some point, all the NOT_IMPLEMENTED() statements * will need to be replaced somehow for non-dev builds, where crashing * is certainly not acceptable. */ if (arg & (O_ASYNC | O_DIRECT)) NOT_IMPLEMENTED(); int unchangeable = hb->fl_flags & ~FCNTL_CHANGEABLE_FL; hb->fl_flags = (arg & FCNTL_CHANGEABLE_FL) | unchangeable; break; case F_GETFL: return hb->fl_flags; default: printk("fcntl64: Ignored unknown cmd %d\n", cmd); } return rc; } static int do_chown(const char *u_path, int owner, int group, bool reslink) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; int rc; rc = copy_str_from_user(path, u_path, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; return vfs_chown(path, owner, group, reslink); } int sys_chown(const char *u_path, int owner, int group) { return do_chown(u_path, owner, group, true); } int sys_lchown(const char *u_path, int owner, int group) { return do_chown(u_path, owner, group, false); } int sys_fchown(int fd, uid_t owner, gid_t group) { struct fs_handle_base *hb = get_fs_handle(fd); if (!hb) return -EBADF; if (!(hb->fs->flags & VFS_FS_RW)) return -EROFS; return (owner == 0 && group == 0) ? 0 : -EPERM; } int sys_fsync(int fd) { struct fs_handle_base *hb = get_fs_handle(fd); if (!hb) return -EBADF; return vfs_fsync(hb); } int sys_fdatasync(int fd) { struct fs_handle_base *hb = get_fs_handle(fd); if (!hb) return -EBADF; return vfs_fsync(hb); } int sys_syncfs(int fd) { struct fs_handle_base *hb = get_fs_handle(fd); if (!hb) return -EBADF; vfs_syncfs(hb->fs); return 0; } int sys_sync(void) { vfs_sync(); return 0; } int sys_chmod(const char *u_path, mode_t mode) { struct task *curr = get_curr_task(); char *path = curr->args_copybuf; int rc; rc = copy_str_from_user(path, u_path, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; return vfs_chmod(path, mode); } int sys_fchmod(int fd, mode_t mode) { struct fs_handle_base *hb; hb = get_fs_handle(fd); if (!hb) return -EBADF; if (!(hb->fs->flags & VFS_FS_RW)) return -EROFS; return vfs_fchmod(hb, mode); } static int call_rename_or_link(const char *u_oldpath, const char *u_newpath, int (*vfs_func)(const char *, const char *)) { struct task *curr = get_curr_task(); char *oldpath = curr->args_copybuf; char *newpath = curr->args_copybuf + MAX_PATH; int rc1, rc2; STATIC_ASSERT(ARGS_COPYBUF_SIZE >= 2 * MAX_PATH); rc1 = copy_str_from_user(oldpath, u_oldpath, MAX_PATH, NULL); rc2 = copy_str_from_user(newpath, u_newpath, MAX_PATH, NULL); if (rc1 < 0 || rc2 < 0) return -EFAULT; if (rc1 > 0 || rc2 > 0) return -ENAMETOOLONG; return vfs_func(oldpath, newpath); } int sys_rename(const char *u_oldpath, const char *u_newpath) { return call_rename_or_link(u_oldpath, u_newpath, &vfs_rename); } int sys_link(const char *u_oldpath, const char *u_newpath) { return call_rename_or_link(u_oldpath, u_newpath, &vfs_link); } int sys_pipe(int u_pipefd[2]) { return sys_pipe2(u_pipefd, 0); } int sys_pipe2(int u_pipefd[2], int flags) { struct task *curr = get_curr_task(); struct fs_handle_base *read_h = NULL; struct fs_handle_base *write_h = NULL; struct pipe *p = NULL; int fds[2]; int ret = 0; if (flags & O_DIRECT) return -EINVAL; if (flags & O_NONBLOCK) return -EINVAL; kmutex_lock(&curr->pi->fslock); if (!(p = create_pipe())) { /* * [BE_NICE] According to the POSIX standard, pipe() cannot fail with * -ENOMEM. However, it can fail with -ENFILE or -EMFILE, both of which * are about numeric limits, system-wide or per-process, it doesn't * matter. Also -ENFILE might mean, according to POSIX, that: * * << The user hard limit on memory that can be allocated for pipes has * been reached and the caller is not privileged. >> * * That implies that there _must be_ such a hard limit and, because we * cannot fail with -ENOMEM, such memory for pipes must be also allocated * in advance, which is very bad practically. * * The situation is similar to the case of dup() and dup2() [see the * comment in sys_dup2()] and what the Linux kernel does in case of real * out-of-memory it's simply lying by failing with -ENFILE here. * * Tilck tries to be more honest even at the price of breaking a little * the POSIX standard, by returning -ENOMEM here. */ goto no_mem; } if ((fds[0] = get_free_handle_num(curr->pi)) < 0) goto no_fds; if (!(read_h = pipe_create_read_handle(p))) goto fault; curr->pi->handles[fds[0]] = read_h; if ((fds[1] = get_free_handle_num(curr->pi)) < 0) goto no_fds; if (!(write_h = pipe_create_write_handle(p))) goto fault; curr->pi->handles[fds[1]] = write_h; if (copy_to_user(u_pipefd, fds, sizeof(fds))) goto fault; if (flags & O_CLOEXEC) { read_h->fd_flags |= FD_CLOEXEC; write_h->fd_flags |= FD_CLOEXEC; } end: kmutex_unlock(&curr->pi->fslock); return ret; err_end: if (read_h) { curr->pi->handles[fds[0]] = NULL; kfs_destroy_handle((void *)read_h); } if (write_h) { curr->pi->handles[fds[1]] = NULL; kfs_destroy_handle((void *)write_h); } if (p) { destroy_pipe(p); } goto end; fault: ret = -EFAULT; goto err_end; no_mem: ret = -ENOMEM; goto err_end; no_fds: ret = -EMFILE; goto err_end; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * Following the same philosophy described in fpu_memcpy.c, we want this code * to be optimized even in debug builds. */ #if defined(__GNUC__) && !defined(__clang__) #pragma GCC optimize "-O3" #endif #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/common/color_defs.h> #include <tilck/common/printk.h> #include <tilck/mods/fb_console.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/system_mmap_int.h> #include <tilck/kernel/errno.h> #include "fb_int.h" static ulong fb_paddr; static u32 fb_pitch; static u32 fb_width; static u32 fb_height; static u8 fb_bpp; /* bits per pixel */ u8 fb_red_pos; u8 fb_green_pos; u8 fb_blue_pos; u8 fb_red_mask_size; u8 fb_green_mask_size; u8 fb_blue_mask_size; u32 fb_red_mask; u32 fb_green_mask; u32 fb_blue_mask; u32 fb_size; static u32 fb_bytes_per_pixel; static u32 fb_line_length; ulong fb_vaddr; static u32 *fb_w8_char_scanlines; u32 font_w; u32 font_h; static u32 font_width_bytes; static u32 font_bytes_per_glyph; static u8 *font_glyph_data; #define DARK (168 /* vga */ + 0) #define BRIGHT (252 /* vga */ + 0) u32 vga_rgb_colors[16]; static inline u32 fb_make_color(u32 r, u32 g, u32 b) { return ((r << fb_red_pos) & fb_red_mask) | ((g << fb_green_pos) & fb_green_mask) | ((b << fb_blue_pos) & fb_blue_mask); } void fb_console_get_info(struct fb_console_info *i) { *i = (struct fb_console_info) { .res_x = (u16)fb_width, .res_y = (u16)fb_height, .bpp = (u16)fb_bpp, .font_w = (u16)font_w, .font_h = (u16)font_h, }; } static void fb_init_colors(void) { u32 *c = vga_rgb_colors; c[COLOR_BLACK] = fb_make_color(0 , 0 , 0 ); c[COLOR_BLUE] = fb_make_color(0 , 0 , DARK+30); c[COLOR_GREEN] = fb_make_color(0 , DARK , 0 ); c[COLOR_CYAN] = fb_make_color(0 , DARK , DARK ); c[COLOR_RED] = fb_make_color(DARK , 0 , 0 ); c[COLOR_MAGENTA] = fb_make_color(DARK , 0 , DARK ); c[COLOR_YELLOW] = fb_make_color(DARK , DARK , 0 ); c[COLOR_WHITE] = fb_make_color(DARK+25, DARK+25, DARK+25); c[COLOR_BRIGHT_BLACK] = fb_make_color(DARK-40, DARK-40, DARK-40); c[COLOR_BRIGHT_BLUE] = fb_make_color(0 , 0 , BRIGHT ); c[COLOR_BRIGHT_GREEN] = fb_make_color(0 , BRIGHT , 0 ); c[COLOR_BRIGHT_CYAN] = fb_make_color(0 , BRIGHT , BRIGHT ); c[COLOR_BRIGHT_RED] = fb_make_color(BRIGHT , 0 , 0 ); c[COLOR_BRIGHT_MAGENTA] = fb_make_color(BRIGHT , 0 , BRIGHT ); c[COLOR_BRIGHT_YELLOW] = fb_make_color(BRIGHT , BRIGHT , 0 ); c[COLOR_BRIGHT_WHITE] = fb_make_color(BRIGHT , BRIGHT , BRIGHT ); } /* Note: using these constants won't work on big endian machines */ #define PSF1_FONT_MAGIC 0x0436 #define PSF2_FONT_MAGIC 0x864ab572 void fb_set_font(void *font) { struct { u16 magic; u8 mode; u8 bytes_per_glyph; } *h1 = font; struct { u32 magic; u32 version; /* zero */ u32 header_size; u32 flags; /* 0 if there's no unicode table */ u32 glyphs_count; u32 bytes_per_glyph; u32 height; /* height in pixels */ u32 width; /* width in pixels */ } *h2 = font; if (h2->magic == PSF2_FONT_MAGIC) { font_w = h2->width; font_h = h2->height; font_width_bytes = h2->bytes_per_glyph / font_h; font_glyph_data = (u8 *)h2 + h2->header_size; font_bytes_per_glyph = h2->bytes_per_glyph; } else { VERIFY(h1->magic == PSF1_FONT_MAGIC); font_w = 8; font_h = h1->bytes_per_glyph; font_width_bytes = 1; font_glyph_data = (u8 *)h1 + sizeof(*h1); font_bytes_per_glyph = h1->bytes_per_glyph; } } void set_framebuffer_info_from_mbi(multiboot_info_t *mbi) { __use_framebuffer = true; fb_paddr = (ulong) mbi->framebuffer_addr; fb_pitch = mbi->framebuffer_pitch; fb_width = mbi->framebuffer_width; fb_height = mbi->framebuffer_height; fb_bpp = mbi->framebuffer_bpp; fb_red_pos = mbi->framebuffer_red_field_position; fb_red_mask_size = mbi->framebuffer_red_mask_size; fb_red_mask = ((1u << fb_red_mask_size) - 1) << fb_red_pos; fb_green_pos = mbi->framebuffer_green_field_position; fb_green_mask_size = mbi->framebuffer_green_mask_size; fb_green_mask = ((1u << fb_green_mask_size) - 1) << fb_green_pos; fb_blue_pos = mbi->framebuffer_blue_field_position; fb_blue_mask_size = mbi->framebuffer_blue_mask_size; fb_blue_mask = ((1u << fb_blue_mask_size) - 1) << fb_blue_pos; //printk("red [pos: %2u, mask: %p]\n", fb_red_pos, fb_red_mask); //printk("green [pos: %2u, mask: %p]\n", fb_green_pos, fb_green_mask); //printk("blue [pos: %2u, mask: %p]\n", fb_blue_pos, fb_blue_mask); fb_bytes_per_pixel = fb_bpp / 8; fb_line_length = fb_width * fb_bytes_per_pixel; fb_size = fb_pitch * fb_height; fb_init_colors(); append_mem_region((struct mem_region) { .addr = fb_paddr, .len = fb_size, .type = MULTIBOOT_MEMORY_RESERVED, .extra = MEM_REG_EXTRA_FRAMEBUFFER, }); } void fb_lines_shift_up(u32 src_y, u32 dst_y, u32 lines_count) { memcpy32((void *)(fb_vaddr + fb_pitch * dst_y), (void *)(fb_vaddr + fb_pitch * src_y), (fb_pitch * lines_count) >> 2); } u32 fb_get_width(void) { return fb_width; } u32 fb_get_height(void) { return fb_height; } u32 fb_get_bpp(void) { return fb_bpp; } int fb_user_mmap(pdir_t *pdir, void *vaddr, size_t mmap_len) { if (!map_framebuffer(pdir, fb_paddr, (ulong)vaddr, mmap_len, true)) return -ENOMEM; return 0; } void fb_map_in_kernel_space(void) { fb_vaddr = (ulong) map_framebuffer(get_kernel_pdir(), fb_paddr, 0, fb_size, false); } /* * This function is used only by the failsafe functions: normally, there are * faster ways to draw on-screen than using a pixel by pixel method. */ static inline void fb_draw_pixel(u32 x, u32 y, u32 color) { ASSERT(x < fb_width); ASSERT(y < fb_height); if (fb_bpp == 32) { *(volatile u32 *) (fb_vaddr + (fb_pitch * y) + (x << 2)) = color; } else { // Assumption: bpp is 24 memcpy((void *) (fb_vaddr + (fb_pitch * y) + (x * 3)), &color, 3); } } void fb_raw_color_lines(u32 iy, u32 h, u32 color) { if (LIKELY(fb_bpp == 32)) { ulong v = fb_vaddr + (fb_pitch * iy); if (LIKELY(fb_pitch == fb_line_length)) { memset32((void *)v, color, (fb_pitch * h) >> 2); } else { for (u32 i = 0; i < h; i++, v += fb_pitch) memset((void *)v, (int)color, fb_line_length); } } else { /* * Generic (but slower version) * NOTE: Optimizing for bpp != 32 is completely out of Tilck's goals. */ for (u32 y = iy; y < (iy + h); y++) for (u32 x = 0; x < fb_width; x++) fb_draw_pixel(x, y, color); } } void fb_draw_cursor_raw(u32 ix, u32 iy, u32 color) { if (LIKELY(fb_bpp == 32)) { ix <<= 2; for (u32 y = iy; y < (iy + font_h); y++) { memset32((u32 *)(fb_vaddr + (fb_pitch * y) + ix), color, font_w); } } else { /* * Generic (but slower version) * NOTE: Optimizing for bpp != 32 is completely out of Tilck's goals. */ for (u32 y = iy; y < (iy + font_h); y++) for (u32 x = ix; x < (ix + font_w); x++) fb_draw_pixel(x, y, color); } } void fb_copy_from_screen(u32 ix, u32 iy, u32 w, u32 h, u32 *buf) { ulong vaddr = fb_vaddr + (fb_pitch * iy) + (ix * fb_bytes_per_pixel); if (LIKELY(fb_bpp == 32)) { for (u32 y = 0; y < h; y++, vaddr += fb_pitch) memcpy32(&buf[y * w], (void *)vaddr, w); } else { /* * Generic (but slower version) * NOTE: Optimizing for bpp != 32 is completely out of Tilck's goals. */ for (u32 y = 0; y < h; y++, vaddr += fb_pitch) memcpy((u8 *)buf + y * w * fb_bytes_per_pixel, (void *)vaddr, w * fb_bytes_per_pixel); } } void fb_copy_to_screen(u32 ix, u32 iy, u32 w, u32 h, u32 *buf) { ulong vaddr = fb_vaddr + (fb_pitch * iy) + (ix * fb_bytes_per_pixel); if (LIKELY(fb_bpp == 32)) { for (u32 y = 0; y < h; y++, vaddr += fb_pitch) memcpy32((void *)vaddr, &buf[y * w], w); } else { /* * Generic (but slower version) * NOTE: Optimizing for bpp != 32 is completely out of Tilck's goals. */ for (u32 y = 0; y < h; y++, vaddr += fb_pitch) memcpy((void *)vaddr, (u8 *)buf + y * w * fb_bytes_per_pixel, w * fb_bytes_per_pixel); } } #if DEBUG_CHECKS void debug_dump_glyph(u32 n) { if (!font_glyph_data) { printk("debug_dump_glyph: font_glyph_data == 0: are we in text mode?\n"); return; } const char fgbg[2] = {'#', '.'}; u8 *data = font_glyph_data + font_bytes_per_glyph * n; printk(NO_PREFIX "\nGlyph #%u:\n\n", n); for (u32 row = 0; row < font_h; row++, data += font_width_bytes) { for (u32 b = 0; b < font_width_bytes; b++) { for (u32 i = 0; i < 8; i++) { printk(NO_PREFIX "%c", fgbg[!(data[b] & (1 << i))]); } } printk(NO_PREFIX "\n"); } printk(NO_PREFIX "\n"); } #endif #define draw_char_partial(b) \ do { \ fb_draw_pixel(x + (b << 3) + 7, row, arr[!(data[b] & (1 << 0))]); \ fb_draw_pixel(x + (b << 3) + 6, row, arr[!(data[b] & (1 << 1))]); \ fb_draw_pixel(x + (b << 3) + 5, row, arr[!(data[b] & (1 << 2))]); \ fb_draw_pixel(x + (b << 3) + 4, row, arr[!(data[b] & (1 << 3))]); \ fb_draw_pixel(x + (b << 3) + 3, row, arr[!(data[b] & (1 << 4))]); \ fb_draw_pixel(x + (b << 3) + 2, row, arr[!(data[b] & (1 << 5))]); \ fb_draw_pixel(x + (b << 3) + 1, row, arr[!(data[b] & (1 << 6))]); \ fb_draw_pixel(x + (b << 3) + 0, row, arr[!(data[b] & (1 << 7))]); \ } while (0) void fb_draw_char_failsafe(u32 x, u32 y, u16 e) { u8 *data = font_glyph_data + font_bytes_per_glyph * vgaentry_get_char(e); u32 arr[] = { vga_rgb_colors[vgaentry_get_fg(e)], vga_rgb_colors[vgaentry_get_bg(e)], }; if (FB_CONSOLE_FAILSAFE_OPT) { if (LIKELY(font_width_bytes == 1)) for (u32 row = y; row < (y+font_h); row++, data += font_width_bytes) { draw_char_partial(0); } else if (font_width_bytes == 2) for (u32 row = y; row < (y+font_h); row++, data += font_width_bytes) { draw_char_partial(0); draw_char_partial(1); } else for (u32 row = y; row < (y+font_h); row++, data += font_width_bytes) { for (u32 b = 0; b < font_width_bytes; b++) { draw_char_partial(b); } } } else { for (u32 row = y; row < (y + font_h); row++, data += font_width_bytes) { for (u32 b = 0; b < font_width_bytes; b++) { for (u32 i = 0; i < 8; i++) fb_draw_pixel(x + (b << 3) + (8 - i - 1), /* x */ row, /* y */ arr[!(data[b] & (1 << i))]); /* color */ } } } } /* * ------------------------------------------- * * Optimized funcs * * ------------------------------------------- */ #define PSZ 4 /* pixel size = 32 bpp / 8 = 4 bytes */ #define SL_COUNT 256 /* all possible 8-pixel scanlines */ #define SL_SIZE 8 /* scanline size: 8 pixels */ #define FG_COLORS 16 /* #fg colors */ #define BG_COLORS 16 /* #bg colors */ #define TOT_CHAR_SCANLINES_SIZE (PSZ*SL_COUNT*FG_COLORS*BG_COLORS*SL_SIZE) bool fb_pre_render_char_scanlines(void) { fb_w8_char_scanlines = kmalloc(TOT_CHAR_SCANLINES_SIZE); if (!fb_w8_char_scanlines) return false; for (u32 fg = 0; fg < FG_COLORS; fg++) { for (u32 bg = 0; bg < BG_COLORS; bg++) { for (u32 sl = 0; sl < SL_COUNT; sl++) { for (u32 pix = 0; pix < SL_SIZE; pix++) { fb_w8_char_scanlines[ fg * (BG_COLORS * SL_COUNT * SL_SIZE) + bg * (SL_COUNT * SL_SIZE) + sl * SL_SIZE + (SL_SIZE - pix - 1) ] = (sl & (1 << pix)) ? vga_rgb_colors[fg] : vga_rgb_colors[bg]; } } } } return true; } void fb_draw_char_optimized(u32 x, u32 y, u16 e) { /* Static variables, set once! */ static void *op; if (UNLIKELY(!op)) { ASSERT(font_w == 8 || font_w == 16); if (font_w == 8) op = &&width1; else op = &&width2; } /* -------------- Regular variables --------------- */ const u8 c = vgaentry_get_char(e); ASSUME_WITHOUT_CHECK(!(font_w % 8)); ASSUME_WITHOUT_CHECK(font_h == 16 || font_h == 32); ASSUME_WITHOUT_CHECK(font_bytes_per_glyph==16 || font_bytes_per_glyph==64); void *vaddr = (void *)fb_vaddr + (fb_pitch * y) + (x << 2); u8 *d = font_glyph_data + font_bytes_per_glyph * c; const u32 c_off = (u32)( (vgaentry_get_fg(e) << 15) + (vgaentry_get_bg(e) << 11) ); u32 *scanlines = &fb_w8_char_scanlines[c_off]; goto *op; width1: for (u32 r = 0; r < font_h; r++, d++, vaddr += fb_pitch) memcpy32(vaddr, &scanlines[d[0] << 3], SL_SIZE); return; width2: for (u32 r = 0; r < font_h; r++, d+=2, vaddr += fb_pitch) { memcpy32(vaddr, &scanlines[d[0] << 3], SL_SIZE); memcpy32(vaddr + 32, &scanlines[d[1] << 3], SL_SIZE); } return; } void fb_draw_row_optimized(u32 y, u16 *entries, u32 count, bool fpu) { static const void *ops[] = { &&width_1_nofpu, &&width_1_fpu, &&width_2_nofpu, &&width_2_fpu }; const u32 bpg_shift = 4 + (font_bytes_per_glyph == 64) * 2; // 4 or 6 const u32 w4_shift = 5 + (font_w == 16); // 5 or 6 const void *const op = ops[(font_w == 16) * 2 + fpu]; // ops[0..3] /* -------------- Regular variables --------------- */ const ulong vaddr_base = fb_vaddr + (fb_pitch * y); ASSUME_WITHOUT_CHECK(font_w == 8 || font_w == 16); ASSUME_WITHOUT_CHECK(font_h == 16 || font_h == 32); ASSUME_WITHOUT_CHECK(font_bytes_per_glyph==16 || font_bytes_per_glyph==64); for (u32 ei = 0; ei < count; ei++) { const u16 e = entries[ei]; const u32 c_off = (u32) ( (vgaentry_get_fg(e) << 15) + (vgaentry_get_bg(e) << 11) ); void *vaddr = (void *)vaddr_base + (ei << w4_shift); const u8 *d = &font_glyph_data[vgaentry_get_char(e) << bpg_shift]; u32 *scanlines = &fb_w8_char_scanlines[c_off]; goto *op; width_1_fpu: for (u32 r = 0; r < font_h; r++, d++, vaddr += fb_pitch) fpu_cpy_single_256_nt(vaddr, &scanlines[d[0] << 3]); continue; width_1_nofpu: for (u32 r = 0; r < font_h; r++, d++, vaddr += fb_pitch) memcpy32(vaddr, &scanlines[d[0] << 3], SL_SIZE); continue; width_2_fpu: for (u32 r = 0; r < font_h; r++, d+=2, vaddr += fb_pitch) { fpu_cpy_single_256_nt(vaddr, &scanlines[d[0] << 3]); fpu_cpy_single_256_nt(vaddr + 32, &scanlines[d[1] << 3]); } continue; width_2_nofpu: for (u32 r = 0; r < font_h; r++, d+=2, vaddr += fb_pitch) { memcpy32(vaddr, &scanlines[d[0] << 3], SL_SIZE); memcpy32(vaddr + 32, &scanlines[d[1] << 3], SL_SIZE); } continue; } } #include <linux/fb.h> // system header void fb_fill_fix_info(void *fix_info) { struct fb_fix_screeninfo *fi = fix_info; bzero(fi, sizeof(*fi)); memcpy(fi->id, "fbdev", 5); fi->smem_start = fb_paddr; fi->smem_len = fb_size; fi->line_length = fb_pitch; } void fb_fill_var_info(void *var_info) { struct fb_var_screeninfo *vi = var_info; bzero(vi, sizeof(*vi)); vi->xres = fb_width; vi->yres = fb_height; vi->xres_virtual = fb_width; vi->yres_virtual = fb_height; vi->bits_per_pixel = fb_bpp; vi->red.offset = fb_red_pos; vi->red.length = fb_red_mask_size; vi->green.offset = fb_green_pos; vi->green.length = fb_green_mask_size; vi->blue.offset = fb_blue_pos; vi->blue.length = fb_blue_mask_size; // NOTE: vi->{red, green, blue}.msb_right = 0 } #if KERNEL_SELFTESTS void fb_raw_perf_screen_redraw(u32 color, bool use_fpu) { VERIFY(fb_bpp == 32); VERIFY(fb_pitch == fb_line_length); if (use_fpu) fpu_memset256((void *)fb_vaddr, color, (fb_pitch * fb_height) >> 5); else memset32((void *)fb_vaddr, color, (fb_pitch * fb_height) >> 2); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define DEF_FINST_0(name, ret) \ ret name() { \ return KernelSingleton::get()->name(); \ } #define DEF_FINST_1(name, ret, t1) \ ret name(t1 a1) { \ return KernelSingleton::get()->name(a1); \ } #define DEF_FINST_2(name, ret, t1, t2) \ ret name(t1 a1, t2 a2) { \ return KernelSingleton::get()->name(a1, a2); \ } #define DEF_FINST_3(name, ret, t1, t2, t3) \ ret name(t1 a1, t2 a2, t3 a3) { \ return KernelSingleton::get()->name(a1, a2, a3); \ } #define DEF_FINST_4(name, ret, t1, t2, t3, t4) \ ret name(t1 a1, t2 a2, t3 a3, t4 a4) { \ return KernelSingleton::get()->name(a1, a2, a3, a4); \ } #include "mocking.h" KernelSingleton *KernelSingleton::instance = new KernelSingleton(); extern "C" { #define DEF_0(x, n, ret) DEF_FINST_0(n, ret) #define DEF_1(x, n, ret, t1) DEF_FINST_1(n, ret, t1) #define DEF_2(x, n, ret, t1, t2) DEF_FINST_2(n, ret, t1, t2) #define DEF_3(x, n, ret, t1, t2, t3) DEF_FINST_3(n, ret, t1, t2, t3) #define DEF_4(x, n, ret, t1, t2, t3, t4) DEF_FINST_4(n, ret, t1, t2, t3, t4) #include "mocked_funcs.h" } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define DECL_FUNCS_0(name, ret) \ ret __real_##name(); \ ret __wrap_##name(); #define DECL_FUNCS_1(name, ret, t1) \ ret __real_##name(t1); \ ret __wrap_##name(t1); #define DECL_FUNCS_2(name, ret, t1, t2) \ ret __real_##name(t1, t2); \ ret __wrap_##name(t1, t2); #define DECL_FUNCS_3(name, ret, t1, t2, t3) \ ret __real_##name(t1, t2, t3); \ ret __wrap_##name(t1, t2, t3); #define DECL_FUNCS_4(name, ret, t1, t2, t3, t4) \ ret __real_##name(t1, t2, t3, t4); \ ret __wrap_##name(t1, t2, t3, t4); extern "C" { #include <tilck/common/basic_defs.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/fs/vfs_base.h> #define DEF_0(x, n, ret) DECL_FUNCS_0(n, ret) #define DEF_1(x, n, ret, t1) DECL_FUNCS_1(n, ret, t1) #define DEF_2(x, n, ret, t1, t2) DECL_FUNCS_2(n, ret, t1, t2) #define DEF_3(x, n, ret, t1, t2, t3) DECL_FUNCS_3(n, ret, t1, t2, t3) #define DEF_4(x, n, ret, t1, t2, t3, t4) DECL_FUNCS_4(n, ret, t1, t2, t3, t4) #include "mocked_funcs.h" #undef DEF_0 #undef DEF_1 #undef DEF_2 #undef DEF_3 #undef DEF_4 } #define DEF_0(what, name, ret) \ virtual ret name() { \ return __##what##_##name(); \ } #define DEF_1(what, name, ret, t1) \ virtual ret name(t1 a1) { \ return __##what##_##name(a1); \ } #define DEF_2(what, name, ret, t1, t2) \ virtual ret name(t1 a1, t2 a2) { \ return __##what##_##name(a1, a2); \ } #define DEF_3(what, name, ret, t1, t2, t3) \ virtual ret name(t1 a1, t2 a2, t3 a3) { \ return __##what##_##name(a1, a2, a3); \ } #define DEF_4(what, name, ret, t1, t2, t3, t4) \ virtual ret name(t1 a1, t2 a2, t3 a3, t4 a4) { \ return __##what##_##name(a1, a2, a3, a4); \ } class KernelSingleton { public: KernelSingleton() { prevInstance = instance; instance = this; } virtual ~KernelSingleton() { instance = prevInstance; } #include "mocked_funcs.h" static KernelSingleton *get() { return instance; } protected: static KernelSingleton *instance; KernelSingleton *prevInstance; }; #undef DECL_FUNCS_0 #undef DECL_FUNCS_1 #undef DECL_FUNCS_2 #undef DECL_FUNCS_3 #undef DECL_FUNCS_4 #undef DEF_0 #undef DEF_1 #undef DEF_2 #undef DEF_3 #undef DEF_4 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/tilck_sound.h> #include <tilck/common/printk.h> #include <tilck/kernel/arch/generic_x86/dma.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/hal.h> #include "sb16.h" u8 sb16_curr_pause_cmd; u8 sb16_curr_cont_cmd; u16 sb16_curr_ack_cmd; u16 sb16_curr_mute_sound; static u16 sb16_curr_rate; u8 sb16_get_irq(void) { outb(DSP_MIXER, 0x80); u8 irq_code = inb(DSP_MIXER_DATA); u8 irq; switch (irq_code) { case 0x01: irq = 2; break; case 0x04: irq = 7; break; case 0x08: irq = 10; break; case 0x02: /* fall-through */ default: irq = 5; break; } return irq; } int sb16_detect_dsp_hw_and_reset(void) { u8 status; if (!in_hypervisor()) { /* * It makes sense trying to support such ancient ISA hardware ONLY inside * VMs. In particular, only QEMU has a limited support for SoundBlaster16. */ return -ENODEV; } outb(DSP_RESET, 1); delay_us(3); outb(DSP_RESET, 0); delay_us(1); /* * On real HW we would poll on the status register, waiting for bit 7 to * become set for about 100 us before giving up. But, in case of virtualized * hardware, that makes no sense: IN/OUT instructions trigger interrupts in * the hypervisor and are handled immediately. */ status = inb(DSP_READ_STATUS); if (~status & 128) return -ENODEV; delay_us(1); /* * As above, we should poll on DSP_READ for ~100 us on real hardware, but * that's not our case. */ status = inb(DSP_READ); if (status != 0xAA) return -ENODEV; return 0; } int sb16_check_version(void) { outb(DSP_WRITE, DSP_GET_VER); sb16_info.ver_major = inb(DSP_READ); sb16_info.ver_minor = inb(DSP_READ); if (sb16_info.ver_major < 4) { printk("sb16: DSP (ver. %u.%u) too old\n", sb16_info.ver_major, sb16_info.ver_minor); return -1; } return 0; } void sb16_program_dma(u8 bits, u32 buf_sz) { u32 cnt; u16 mask_reg_cmd; u16 rst_ff_cmd; u16 mode_reg; u16 ch_page_reg; u16 ch_start_reg; u16 ch_count_reg; u16 offset; u8 channel; u8 dma_mode; ASSERT(bits == 8 || bits == 16); if (bits == 8) { cnt = buf_sz; mask_reg_cmd = DMA8_SINGLE_CH_MASK_REG; rst_ff_cmd = DMA8_RST_FLIP_FLOP; mode_reg = DMA8_MODE_REG; ch_page_reg = DMA_CHANNEL_1_PAGE_REG; ch_start_reg = DMA_CHANNEL_1_START_REG; ch_count_reg = DMA_CHANNEL_1_COUNT_REG; offset = sb16_info.buf_paddr & 0xffff; channel = DMA_CHANNEL_1; } else { cnt = buf_sz / 2; mask_reg_cmd = DMA16_SINGLE_CH_MASK_REG; rst_ff_cmd = DMA16_RST_FLIP_FLOP; mode_reg = DMA16_MODE_REG; ch_page_reg = DMA_CHANNEL_5_PAGE_REG; ch_start_reg = DMA_CHANNEL_5_START_REG; ch_count_reg = DMA_CHANNEL_5_COUNT_REG; offset = (sb16_info.buf_paddr & 0xffff) >> 1; channel = DMA_CHANNEL_5; } dma_mode = DMA_SINGLE_MODE | DMA_READ_TX | channel; if (buf_sz == 64 * KB) { SB16_DBG("prog DMA in AUTO INIT mode\n"); dma_mode |= DMA_AUTO_INIT; } else { SB16_DBG("prog DMA in SINGLE CYCLE mode\n"); } outb(mask_reg_cmd, DMA_MASK_CHANNEL | channel); outb(rst_ff_cmd, 1); outb(mode_reg, dma_mode); outb(ch_page_reg, (sb16_info.buf_paddr >> 16) & 0xff); outb(ch_start_reg, (offset ) & 0xff); // low byte outb(ch_start_reg, (offset >> 8) & 0xff); // high byte outb(ch_count_reg, ((cnt-1) ) & 0xff); // low byte outb(ch_count_reg, ((cnt-1) >> 8) & 0xff); // high byte outb(mask_reg_cmd, channel); } void sb16_set_sample_rate(u16 sample_rate) { if (sample_rate != sb16_curr_rate) { outb(DSP_WRITE, DSP_SET_SAMPLE_R); outb(DSP_WRITE, (sample_rate >> 8) & 0xff); // high outb(DSP_WRITE, (sample_rate ) & 0xff); // low sb16_curr_rate = sample_rate; } } void sb16_program(struct tilck_sound_params *p, u32 buf_sz) { u8 prog_mode = 0; u8 sound_fmt = 0; u32 samples_cnt; prog_mode |= DSP_PLAY; if (buf_sz == 32 * KB) { SB16_DBG("prog DSP in AUTO_INIT mode\n"); prog_mode |= DSP_AUTO_INIT; } else { SB16_DBG("prog DSP in SINGLE CYCLE mode\n"); } if (p->bits == 8) { samples_cnt = buf_sz; prog_mode |= DSP_8_BIT_PROG; sb16_curr_pause_cmd = DSP_8_BIT_PAUSE; sb16_curr_cont_cmd = DSP_8_BIT_CONT; sb16_curr_ack_cmd = DSP_8_BIT_ACK; } else { samples_cnt = buf_sz >> 1; prog_mode |= DSP_16_BIT_PROG; sb16_curr_pause_cmd = DSP_16_BIT_PAUSE; sb16_curr_cont_cmd = DSP_16_BIT_CONT; sb16_curr_ack_cmd = DSP_16_BIT_ACK; } sound_fmt |= (p->channels == 1 ? DSP_MONO : DSP_STEREO); sound_fmt |= (p->sign ? DSP_SIGNED : DSP_UNSIGNED); sb16_set_sample_rate(p->sample_rate); outb(DSP_WRITE, prog_mode); outb(DSP_WRITE, sound_fmt); outb(DSP_WRITE, ((samples_cnt-1) ) & 0xff); // count low outb(DSP_WRITE, ((samples_cnt-1) >> 8) & 0xff); // count high } <file_sep>/****************************************************************************** * * Module Name: exstore - AML Interpreter object store support * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdispat.h" #include "acinterp.h" #include "amlcode.h" #include "acnamesp.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exstore") /* Local prototypes */ static ACPI_STATUS AcpiExStoreObjectToIndex ( ACPI_OPERAND_OBJECT *ValDesc, ACPI_OPERAND_OBJECT *DestDesc, ACPI_WALK_STATE *WalkState); static ACPI_STATUS AcpiExStoreDirectToNode ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_NAMESPACE_NODE *Node, ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiExStore * * PARAMETERS: *SourceDesc - Value to be stored * *DestDesc - Where to store it. Must be an NS node * or ACPI_OPERAND_OBJECT of type * Reference; * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Store the value described by SourceDesc into the location * described by DestDesc. Called by various interpreter * functions to store the result of an operation into * the destination operand -- not just simply the actual "Store" * ASL operator. * ******************************************************************************/ ACPI_STATUS AcpiExStore ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *DestDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *RefDesc = DestDesc; ACPI_FUNCTION_TRACE_PTR (ExStore, DestDesc); /* Validate parameters */ if (!SourceDesc || !DestDesc) { ACPI_ERROR ((AE_INFO, "Null parameter")); return_ACPI_STATUS (AE_AML_NO_OPERAND); } /* DestDesc can be either a namespace node or an ACPI object */ if (ACPI_GET_DESCRIPTOR_TYPE (DestDesc) == ACPI_DESC_TYPE_NAMED) { /* * Dest is a namespace node, * Storing an object into a Named node. */ Status = AcpiExStoreObjectToNode (SourceDesc, (ACPI_NAMESPACE_NODE *) DestDesc, WalkState, ACPI_IMPLICIT_CONVERSION); return_ACPI_STATUS (Status); } /* Destination object must be a Reference or a Constant object */ switch (DestDesc->Common.Type) { case ACPI_TYPE_LOCAL_REFERENCE: break; case ACPI_TYPE_INTEGER: /* Allow stores to Constants -- a Noop as per ACPI spec */ if (DestDesc->Common.Flags & AOPOBJ_AML_CONSTANT) { return_ACPI_STATUS (AE_OK); } /*lint -fallthrough */ default: /* Destination is not a Reference object */ ACPI_ERROR ((AE_INFO, "Target is not a Reference or Constant object - [%s] %p", AcpiUtGetObjectTypeName (DestDesc), DestDesc)); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* * Examine the Reference class. These cases are handled: * * 1) Store to Name (Change the object associated with a name) * 2) Store to an indexed area of a Buffer or Package * 3) Store to a Method Local or Arg * 4) Store to the debug object */ switch (RefDesc->Reference.Class) { case ACPI_REFCLASS_REFOF: /* Storing an object into a Name "container" */ Status = AcpiExStoreObjectToNode (SourceDesc, RefDesc->Reference.Object, WalkState, ACPI_IMPLICIT_CONVERSION); break; case ACPI_REFCLASS_INDEX: /* Storing to an Index (pointer into a packager or buffer) */ Status = AcpiExStoreObjectToIndex (SourceDesc, RefDesc, WalkState); break; case ACPI_REFCLASS_LOCAL: case ACPI_REFCLASS_ARG: /* Store to a method local/arg */ Status = AcpiDsStoreObjectToLocal (RefDesc->Reference.Class, RefDesc->Reference.Value, SourceDesc, WalkState); break; case ACPI_REFCLASS_DEBUG: /* * Storing to the Debug object causes the value stored to be * displayed and otherwise has no effect -- see ACPI Specification */ ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "**** Write to Debug Object: Object %p [%s] ****:\n\n", SourceDesc, AcpiUtGetObjectTypeName (SourceDesc))); ACPI_DEBUG_OBJECT (SourceDesc, 0, 0); break; default: ACPI_ERROR ((AE_INFO, "Unknown Reference Class 0x%2.2X", RefDesc->Reference.Class)); ACPI_DUMP_ENTRY (RefDesc, ACPI_LV_INFO); Status = AE_AML_INTERNAL; break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExStoreObjectToIndex * * PARAMETERS: *SourceDesc - Value to be stored * *DestDesc - Named object to receive the value * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Store the object to indexed Buffer or Package element * ******************************************************************************/ static ACPI_STATUS AcpiExStoreObjectToIndex ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *IndexDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *NewDesc; UINT8 Value = 0; UINT32 i; ACPI_FUNCTION_TRACE (ExStoreObjectToIndex); /* * Destination must be a reference pointer, and * must point to either a buffer or a package */ switch (IndexDesc->Reference.TargetType) { case ACPI_TYPE_PACKAGE: /* * Storing to a package element. Copy the object and replace * any existing object with the new object. No implicit * conversion is performed. * * The object at *(IndexDesc->Reference.Where) is the * element within the package that is to be modified. * The parent package object is at IndexDesc->Reference.Object */ ObjDesc = *(IndexDesc->Reference.Where); if (SourceDesc->Common.Type == ACPI_TYPE_LOCAL_REFERENCE && SourceDesc->Reference.Class == ACPI_REFCLASS_TABLE) { /* This is a DDBHandle, just add a reference to it */ AcpiUtAddReference (SourceDesc); NewDesc = SourceDesc; } else { /* Normal object, copy it */ Status = AcpiUtCopyIobjectToIobject ( SourceDesc, &NewDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } if (ObjDesc) { /* Decrement reference count by the ref count of the parent package */ for (i = 0; i < ((ACPI_OPERAND_OBJECT *) IndexDesc->Reference.Object)->Common.ReferenceCount; i++) { AcpiUtRemoveReference (ObjDesc); } } *(IndexDesc->Reference.Where) = NewDesc; /* Increment ref count by the ref count of the parent package-1 */ for (i = 1; i < ((ACPI_OPERAND_OBJECT *) IndexDesc->Reference.Object)->Common.ReferenceCount; i++) { AcpiUtAddReference (NewDesc); } break; case ACPI_TYPE_BUFFER_FIELD: /* * Store into a Buffer or String (not actually a real BufferField) * at a location defined by an Index. * * The first 8-bit element of the source object is written to the * 8-bit Buffer location defined by the Index destination object, * according to the ACPI 2.0 specification. */ /* * Make sure the target is a Buffer or String. An error should * not happen here, since the ReferenceObject was constructed * by the INDEX_OP code. */ ObjDesc = IndexDesc->Reference.Object; if ((ObjDesc->Common.Type != ACPI_TYPE_BUFFER) && (ObjDesc->Common.Type != ACPI_TYPE_STRING)) { return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* * The assignment of the individual elements will be slightly * different for each source type. */ switch (SourceDesc->Common.Type) { case ACPI_TYPE_INTEGER: /* Use the least-significant byte of the integer */ Value = (UINT8) (SourceDesc->Integer.Value); break; case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: /* Note: Takes advantage of common string/buffer fields */ Value = SourceDesc->Buffer.Pointer[0]; break; default: /* All other types are invalid */ ACPI_ERROR ((AE_INFO, "Source must be type [Integer/Buffer/String], found [%s]", AcpiUtGetObjectTypeName (SourceDesc))); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* Store the source value into the target buffer byte */ ObjDesc->Buffer.Pointer[IndexDesc->Reference.Value] = Value; break; default: ACPI_ERROR ((AE_INFO, "Target is not of type [Package/BufferField]")); Status = AE_AML_TARGET_TYPE; break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExStoreObjectToNode * * PARAMETERS: SourceDesc - Value to be stored * Node - Named object to receive the value * WalkState - Current walk state * ImplicitConversion - Perform implicit conversion (yes/no) * * RETURN: Status * * DESCRIPTION: Store the object to the named object. * * The assignment of an object to a named object is handled here. * The value passed in will replace the current value (if any) * with the input value. * * When storing into an object the data is converted to the * target object type then stored in the object. This means * that the target object type (for an initialized target) will * not be changed by a store operation. A CopyObject can change * the target type, however. * * The ImplicitConversion flag is set to NO/FALSE only when * storing to an ArgX -- as per the rules of the ACPI spec. * * Assumes parameters are already validated. * ******************************************************************************/ ACPI_STATUS AcpiExStoreObjectToNode ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_NAMESPACE_NODE *Node, ACPI_WALK_STATE *WalkState, UINT8 ImplicitConversion) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *TargetDesc; ACPI_OPERAND_OBJECT *NewDesc; ACPI_OBJECT_TYPE TargetType; ACPI_FUNCTION_TRACE_PTR (ExStoreObjectToNode, SourceDesc); /* Get current type of the node, and object attached to Node */ TargetType = AcpiNsGetType (Node); TargetDesc = AcpiNsGetAttachedObject (Node); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Storing %p [%s] to node %p [%s]\n", SourceDesc, AcpiUtGetObjectTypeName (SourceDesc), Node, AcpiUtGetTypeName (TargetType))); /* Only limited target types possible for everything except CopyObject */ if (WalkState->Opcode != AML_COPY_OBJECT_OP) { /* * Only CopyObject allows all object types to be overwritten. For * TargetRef(s), there are restrictions on the object types that * are allowed. * * Allowable operations/typing for Store: * * 1) Simple Store * Integer --> Integer (Named/Local/Arg) * String --> String (Named/Local/Arg) * Buffer --> Buffer (Named/Local/Arg) * Package --> Package (Named/Local/Arg) * * 2) Store with implicit conversion * Integer --> String or Buffer (Named) * String --> Integer or Buffer (Named) * Buffer --> Integer or String (Named) */ switch (TargetType) { case ACPI_TYPE_PACKAGE: /* * Here, can only store a package to an existing package. * Storing a package to a Local/Arg is OK, and handled * elsewhere. */ if (WalkState->Opcode == AML_STORE_OP) { if (SourceDesc->Common.Type != ACPI_TYPE_PACKAGE) { ACPI_ERROR ((AE_INFO, "Cannot assign type [%s] to [Package] " "(source must be type Pkg)", AcpiUtGetObjectTypeName (SourceDesc))); return_ACPI_STATUS (AE_AML_TARGET_TYPE); } break; } /* Fallthrough */ case ACPI_TYPE_DEVICE: case ACPI_TYPE_EVENT: case ACPI_TYPE_MUTEX: case ACPI_TYPE_REGION: case ACPI_TYPE_POWER: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_THERMAL: ACPI_ERROR ((AE_INFO, "Target must be [Buffer/Integer/String/Reference]" ", found [%s] (%4.4s)", AcpiUtGetTypeName (Node->Type), Node->Name.Ascii)); return_ACPI_STATUS (AE_AML_TARGET_TYPE); default: break; } } /* * Resolve the source object to an actual value * (If it is a reference object) */ Status = AcpiExResolveObject (&SourceDesc, TargetType, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Do the actual store operation */ switch (TargetType) { /* * The simple data types all support implicit source operand * conversion before the store. */ case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: if ((WalkState->Opcode == AML_COPY_OBJECT_OP) || !ImplicitConversion) { /* * However, CopyObject and Stores to ArgX do not perform * an implicit conversion, as per the ACPI specification. * A direct store is performed instead. */ Status = AcpiExStoreDirectToNode (SourceDesc, Node, WalkState); break; } /* Store with implicit source operand conversion support */ Status = AcpiExStoreObjectToObject (SourceDesc, TargetDesc, &NewDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (NewDesc != TargetDesc) { /* * Store the new NewDesc as the new value of the Name, and set * the Name's type to that of the value being stored in it. * SourceDesc reference count is incremented by AttachObject. * * Note: This may change the type of the node if an explicit * store has been performed such that the node/object type * has been changed. */ Status = AcpiNsAttachObject ( Node, NewDesc, NewDesc->Common.Type); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Store type [%s] into [%s] via Convert/Attach\n", AcpiUtGetObjectTypeName (SourceDesc), AcpiUtGetObjectTypeName (NewDesc))); } break; case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: /* * For all fields, always write the source data to the target * field. Any required implicit source operand conversion is * performed in the function below as necessary. Note, field * objects must retain their original type permanently. */ Status = AcpiExWriteDataToField (SourceDesc, TargetDesc, &WalkState->ResultObj); break; default: /* * CopyObject operator: No conversions for all other types. * Instead, directly store a copy of the source object. * * This is the ACPI spec-defined behavior for the CopyObject * operator. (Note, for this default case, all normal * Store/Target operations exited above with an error). */ Status = AcpiExStoreDirectToNode (SourceDesc, Node, WalkState); break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExStoreDirectToNode * * PARAMETERS: SourceDesc - Value to be stored * Node - Named object to receive the value * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: "Store" an object directly to a node. This involves a copy * and an attach. * ******************************************************************************/ static ACPI_STATUS AcpiExStoreDirectToNode ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_NAMESPACE_NODE *Node, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *NewDesc; ACPI_FUNCTION_TRACE (ExStoreDirectToNode); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Storing [%s] (%p) directly into node [%s] (%p)" " with no implicit conversion\n", AcpiUtGetObjectTypeName (SourceDesc), SourceDesc, AcpiUtGetTypeName (Node->Type), Node)); /* Copy the source object to a new object */ Status = AcpiUtCopyIobjectToIobject (SourceDesc, &NewDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Attach the new object to the node */ Status = AcpiNsAttachObject (Node, NewDesc, NewDesc->Common.Type); AcpiUtRemoveReference (NewDesc); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/mods/tracing.h> STATIC bool simple_wildcard_match(const char *str, const char *expr); STATIC int set_traced_syscalls_int(const char *str); STATIC bool save_param_buffer(void *, long, char *, size_t); STATIC bool dump_param_buffer(ulong, char *, long, long, char *, size_t); extern bool *traced_syscalls; extern char *traced_syscalls_str; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/string_util.h> #include "realmode_call.h" #include "vbe.h" void vga_set_video_mode(u8 mode) { u32 eax, ebx, ecx, edx, esi, edi, flags; /* * ah = 0x0 => set video mode * al = mode => mode [0 .. 0x13] */ eax = mode; realmode_call(&realmode_int_10h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); } bool vbe_get_info_block(struct VbeInfoBlock *vb) { u32 eax, ebx, ecx, edx, esi, edi, flags; bzero(vb, sizeof(*vb)); eax = 0x4f00; edi = (u32) vb; memcpy(vb->VbeSignature, "VBE2", 4); realmode_call(&realmode_int_10h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (eax != 0x004f) return false; return true; } bool vbe_get_mode_info(u16 mode, struct ModeInfoBlock *mi) { u32 eax, ebx, ecx, edx, esi, edi, flags; bzero(mi, sizeof(*mi)); eax = 0x4f01; ecx = mode; edi = (u32) mi; realmode_call(&realmode_int_10h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (eax != 0x004f) return false; return true; } bool vbe_set_video_mode(u16 mode) { u32 eax, ebx, ecx, edx, esi, edi, flags; eax = 0x4f02; ebx = mode | VBE_SET_MODE_FLAG_USE_LINEAR_FB; realmode_call(&realmode_int_10h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (eax != 0x004f) return false; return true; } bool vbe_get_current_mode(u16 *mode) { u32 eax, ebx, ecx, edx, esi, edi, flags; eax = 0x4f03; realmode_call(&realmode_int_10h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (eax != 0x004f) return false; *mode = ebx & 0xffff; return true; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> static struct kcond cond = { 0 }; static struct kmutex cond_mutex = { 0 }; static void kcond_thread_test(void *arg) { const int tn = (int)(ulong)arg; kmutex_lock(&cond_mutex); printk("[thread %i]: under lock, waiting for signal..\n", tn); bool success = kcond_wait(&cond, &cond_mutex, KCOND_WAIT_FOREVER); if (success) printk("[thread %i]: under lock, signal received..\n", tn); else panic("[thread %i]: under lock, kcond_wait() FAILED\n", tn); kmutex_unlock(&cond_mutex); printk("[thread %i]: exit\n", tn); } static void kcond_thread_wait_ticks() { kmutex_lock(&cond_mutex); printk("[kcond wait ticks]: holding the lock, run wait()\n"); bool success = kcond_wait(&cond, &cond_mutex, TIMER_HZ/2); if (!success) printk("[kcond wait ticks]: woke up due to timeout, as expected!\n"); else panic("[kcond wait ticks] FAILED: kcond_wait() returned true."); kmutex_unlock(&cond_mutex); } static void kcond_thread_signal_generator() { int tid; kmutex_lock(&cond_mutex); printk("[thread signal]: under lock, waiting some time..\n"); kernel_sleep(TIMER_HZ / 2); printk("[thread signal]: under lock, signal_all!\n"); kcond_signal_all(&cond); kmutex_unlock(&cond_mutex); printk("[thread signal]: exit\n"); printk("Run thread kcond_thread_wait_ticks\n"); if ((tid = kthread_create(&kcond_thread_wait_ticks, 0, NULL)) < 0) panic("Unable to create a thread for kcond_thread_wait_ticks()"); kthread_join(tid, true); } void selftest_kcond() { int tids[3]; kmutex_init(&cond_mutex, 0); kcond_init(&cond); tids[0] = kthread_create(&kcond_thread_test, 0, (void*) 1); VERIFY(tids[0] > 0); tids[1] = kthread_create(&kcond_thread_test, 0, (void*) 2); VERIFY(tids[1] > 0); tids[2] = kthread_create(&kcond_thread_signal_generator, 0, NULL); VERIFY(tids[2] > 0); kthread_join_all(tids, ARRAY_SIZE(tids), true); kcond_destory(&cond); se_regular_end(); } REGISTER_SELF_TEST(kcond, se_short, &selftest_kcond) <file_sep>#!/usr/bin/env bash if [ -z "$GDB_PORT" ]; then GDB_PORT=1234 fi BUILD_DIR=@CMAKE_BINARY_DIR@ qemu-system-@ARCH@ @QEMU_COMMON_OPTS@ -gdb tcp::$GDB_PORT @QEMU_RAM_OPT@ \ -drive id=img1,format=raw,if=none,file=@IMG_FILE@ \ -device ide-hd,drive=img1,@QEMU_CHS_GEOM@ "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include "termutil.h" #include "dp_int.h" static int line_pos; static int line_len; static char line[72]; typedef void (*key_handler_type)(char *, int); static int read_single_byte(fs_handle h, char *buf, u32 len) { bool esc_timeout = false; int rc; char c; while (true) { rc = vfs_read(h, &c, 1); if (rc == -EAGAIN) { if (len > 0 && buf[0] == DP_KEY_ESC) { /* * We hit a non-terminated escape sequence: let's wait for one * timeout interval and then return 0 if we hit EAGAIN another time. */ if (esc_timeout) return 0; /* stop reading */ esc_timeout = true; } kernel_sleep(TIMER_HZ / 25); continue; } if (rc == 0) return 0; /* stop reading */ if (rc < 0) return rc; /* error */ break; } buf[len] = c; return 1; /* continue reading */ } static void convert_seq_to_key(char *buf, struct key_event *ke) { /* ESC [ <n> ~ */ static const u32 helper_keys[6] = { KEY_HOME, KEY_INS, KEY_DEL, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN, }; if (IN_RANGE_INC(buf[0], 32, 127) || IN_RANGE_INC(buf[0], 1, 26)) { *ke = (struct key_event) { .pressed = true, .print_char = buf[0], .key = 0, }; } else if (buf[0] == DP_KEY_ESC && !buf[1]) { *ke = (struct key_event) { .pressed = true, .print_char = buf[0], .key = 0, }; } else if (buf[0] == DP_KEY_ESC && buf[1] == '[') { u32 key = 0; switch (buf[2]) { case 'A': key = KEY_UP; break; case 'B': key = KEY_DOWN; break; case 'C': key = KEY_RIGHT; break; case 'D': key = KEY_LEFT; break; case '1': case '2': case '3': case '4': case '5': case '6': if (buf[3] == '~' && IN_RANGE_INC(buf[2], '1', '6')) key = helper_keys[buf[2] - '1']; break; /* Compatibility keys, for TERM != linux */ case 'H': key = KEY_HOME; break; case 'F': key = KEY_END; break; } *ke = (struct key_event) { .pressed = true, .print_char = 0, .key = key, }; } else { /* Unknown ESC sequence: do nothing (`ke` will remain zeroed) */ } } int dp_read_ke_from_tty(struct key_event *ke) { fs_handle h = dp_input_handle; char c, buf[16]; int rc; u32 len; enum { state_default, state_in_esc1, state_in_csi_param, state_in_csi_intermediate, } state = state_default; bzero(ke, sizeof(*ke)); bzero(buf, sizeof(buf)); for (len = 0; len < sizeof(buf); len++) { rc = read_single_byte(h, buf, len); if (rc < 0 || (!rc && !len)) return rc; if (!rc) break; c = buf[len]; state_changed: switch (state) { case state_in_csi_intermediate: if (IN_RANGE_INC(c, 0x20, 0x2F)) continue; /* for loop */ /* * The current char must be in range 0x40-0x7E, but we must break * anyway, even it isn't. */ break; /* switch (state) */ case state_in_csi_param: if (IN_RANGE_INC(c, 0x30, 0x3F)) continue; /* for loop */ state = state_in_csi_intermediate; goto state_changed; case state_in_esc1: if (c == '[') { state = state_in_csi_param; continue; /* for loop */ } /* any other non-CSI sequence is ignored */ break; /* switch (state) */ case state_default: if (c == 27) { state = state_in_esc1; continue; /* for loop */ } break; /* switch (state) */ default: NOT_REACHED(); } break; /* for (len = 0; len < sizeof(buf); len++) */ } convert_seq_to_key(buf, ke); return 0; } static inline void dp_erase_last(void) { dp_write_raw("\033[D \033[D"); } static void handle_seq_home(char *buf, int bs) { dp_move_left(line_pos); line_pos = 0; } static void handle_seq_end(char *buf, int bs) { dp_move_right(line_len - line_pos); line_pos = line_len; } static void handle_seq_delete(char *buf, int bs) { if (!line_len || line_pos == line_len) return; line_len--; for (int i = line_pos; i < line_len + 1; i++) { buf[i] = buf[i + 1]; } buf[line_len] = ' '; dp_write_raw_int(buf + line_pos, line_len - line_pos + 1); dp_move_left(line_len - line_pos + 1); } static void handle_seq_left(char *buf, int bs) { if (!line_pos) return; dp_move_left(1); line_pos--; } static void handle_seq_right(char *buf, int bs) { if (line_pos >= line_len) return; dp_move_right(1); line_pos++; } static void handle_esc_seq(u32 key, char *buf, int buf_size) { key_handler_type func = NULL; switch (key) { case KEY_LEFT: func = handle_seq_left; break; case KEY_RIGHT: func = handle_seq_right; break; case KEY_HOME: func = handle_seq_home; break; case KEY_END: func = handle_seq_end; break; case KEY_DEL: func = handle_seq_delete; break; } if (func) func(buf, buf_size); } static void handle_backspace(char *buf, int buf_size) { if (!line_len || !line_pos) return; line_len--; line_pos--; dp_erase_last(); if (line_pos == line_len) return; /* We have to shift left all the chars after line_pos */ for (int i = line_pos; i < line_len + 1; i++) { buf[i] = buf[i+1]; } buf[line_len] = ' '; dp_write_raw_int(buf + line_pos, line_len - line_pos + 1); dp_move_left(line_len - line_pos + 1); } static bool handle_regular_char(char c, char *buf, int bs) { dp_write_raw_int(&c, 1); if (c == '\r' || c == '\n') return false; if (line_pos == line_len) { buf[line_pos++] = c; } else { /* We have to shift right all the chars after line_pos */ for (int i = line_len; i >= line_pos; i--) { buf[i + 1] = buf[i]; } buf[line_pos] = c; dp_write_raw_int(buf + line_pos + 1, line_len - line_pos); line_pos++; dp_move_left(line_len - line_pos + 1); } line_len++; return true; } int dp_read_line(char *buf, int buf_size) { int rc; char c; struct key_event ke; const int max_line_len = MIN(buf_size - 1, (int)sizeof(line) - 1); line_len = line_pos = 0; line_len = (int)strlen(buf); line_pos = line_len; memcpy(line, buf, (size_t)max_line_len); line[line_len] = 0; dp_write_raw("%s", line); while (true) { rc = dp_read_ke_from_tty(&ke); if (rc < 0) { line_len = rc; break; } c = ke.print_char; if (line_len < max_line_len) { if (c == DP_KEY_BACKSPACE || c == '\b') { handle_backspace(buf, buf_size); } else if (!c && ke.key) { handle_esc_seq(ke.key, buf, buf_size); } else if (isprint(c) || c == '\r' || c == '\n') { if (!handle_regular_char(c, buf, buf_size)) break; } } else { ASSERT(line_len == max_line_len); if (c == DP_KEY_BACKSPACE) { handle_backspace(buf, buf_size); } else if (c == '\r' || c == '\n') { dp_write_raw("\r\n"); break; } } } buf[line_len >= 0 ? line_len : 0] = 0; return line_len; } <file_sep>/****************************************************************************** * * Name: achaiku.h - OS specific defines, etc. for Haiku (www.haiku-os.org) * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACHAIKU_H__ #define __ACHAIKU_H__ #define ACPI_USE_STANDARD_HEADERS #define ACPI_USE_SYSTEM_CLIBRARY #include <KernelExport.h> struct mutex; /* Host-dependent types and defines for user- and kernel-space ACPICA */ #define ACPI_MUTEX_TYPE ACPI_OSL_MUTEX #define ACPI_MUTEX struct mutex * #define ACPI_USE_NATIVE_DIVIDE #define ACPI_USE_NATIVE_MATH64 /* #define ACPI_THREAD_ID thread_id */ #define ACPI_SEMAPHORE sem_id #define ACPI_SPINLOCK spinlock * #define ACPI_CPU_FLAGS cpu_status #define COMPILER_DEPENDENT_INT64 int64 #define COMPILER_DEPENDENT_UINT64 uint64 #ifdef B_HAIKU_64_BIT #define ACPI_MACHINE_WIDTH 64 #else #define ACPI_MACHINE_WIDTH 32 #endif #ifdef _KERNEL_MODE /* Host-dependent types and defines for in-kernel ACPICA */ /* ACPICA cache implementation is adequate. */ #define ACPI_USE_LOCAL_CACHE #define ACPI_FLUSH_CPU_CACHE() __asm __volatile("wbinvd"); /* Based on FreeBSD's due to lack of documentation */ extern int AcpiOsAcquireGlobalLock(uint32 *lock); extern int AcpiOsReleaseGlobalLock(uint32 *lock); #define ACPI_ACQUIRE_GLOBAL_LOCK(GLptr, Acq) do { \ (Acq) = AcpiOsAcquireGlobalLock(&((GLptr)->GlobalLock)); \ } while (0) #define ACPI_RELEASE_GLOBAL_LOCK(GLptr, Acq) do { \ (Acq) = AcpiOsReleaseGlobalLock(&((GLptr)->GlobalLock)); \ } while (0) #else /* _KERNEL_MODE */ /* Host-dependent types and defines for user-space ACPICA */ #error "We only support kernel mode ACPI atm." #endif /* _KERNEL_MODE */ #endif /* __ACHAIKU_H__ */ <file_sep>/****************************************************************************** * * Module Name: tbxface - ACPI table-oriented external interfaces * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "actables.h" #define _COMPONENT ACPI_TABLES ACPI_MODULE_NAME ("tbxface") /******************************************************************************* * * FUNCTION: AcpiAllocateRootTable * * PARAMETERS: InitialTableCount - Size of InitialTableArray, in number of * ACPI_TABLE_DESC structures * * RETURN: Status * * DESCRIPTION: Allocate a root table array. Used by iASL compiler and * AcpiInitializeTables. * ******************************************************************************/ ACPI_STATUS AcpiAllocateRootTable ( UINT32 InitialTableCount) { AcpiGbl_RootTableList.MaxTableCount = InitialTableCount; AcpiGbl_RootTableList.Flags = ACPI_ROOT_ALLOW_RESIZE; return (AcpiTbResizeRootTableList ()); } /******************************************************************************* * * FUNCTION: AcpiInitializeTables * * PARAMETERS: InitialTableArray - Pointer to an array of pre-allocated * ACPI_TABLE_DESC structures. If NULL, the * array is dynamically allocated. * InitialTableCount - Size of InitialTableArray, in number of * ACPI_TABLE_DESC structures * AllowResize - Flag to tell Table Manager if resize of * pre-allocated array is allowed. Ignored * if InitialTableArray is NULL. * * RETURN: Status * * DESCRIPTION: Initialize the table manager, get the RSDP and RSDT/XSDT. * * NOTE: Allows static allocation of the initial table array in order * to avoid the use of dynamic memory in confined environments * such as the kernel boot sequence where it may not be available. * * If the host OS memory managers are initialized, use NULL for * InitialTableArray, and the table will be dynamically allocated. * ******************************************************************************/ ACPI_STATUS ACPI_INIT_FUNCTION AcpiInitializeTables ( ACPI_TABLE_DESC *InitialTableArray, UINT32 InitialTableCount, BOOLEAN AllowResize) { ACPI_PHYSICAL_ADDRESS RsdpAddress; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInitializeTables); /* * Setup the Root Table Array and allocate the table array * if requested */ if (!InitialTableArray) { Status = AcpiAllocateRootTable (InitialTableCount); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } else { /* Root Table Array has been statically allocated by the host */ memset (InitialTableArray, 0, (ACPI_SIZE) InitialTableCount * sizeof (ACPI_TABLE_DESC)); AcpiGbl_RootTableList.Tables = InitialTableArray; AcpiGbl_RootTableList.MaxTableCount = InitialTableCount; AcpiGbl_RootTableList.Flags = ACPI_ROOT_ORIGIN_UNKNOWN; if (AllowResize) { AcpiGbl_RootTableList.Flags |= ACPI_ROOT_ALLOW_RESIZE; } } /* Get the address of the RSDP */ RsdpAddress = AcpiOsGetRootPointer (); if (!RsdpAddress) { return_ACPI_STATUS (AE_NOT_FOUND); } /* * Get the root table (RSDT or XSDT) and extract all entries to the local * Root Table Array. This array contains the information of the RSDT/XSDT * in a common, more usable format. */ Status = AcpiTbParseRootTable (RsdpAddress); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL_INIT (AcpiInitializeTables) /******************************************************************************* * * FUNCTION: AcpiReallocateRootTable * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Reallocate Root Table List into dynamic memory. Copies the * root list from the previously provided scratch area. Should * be called once dynamic memory allocation is available in the * kernel. * ******************************************************************************/ ACPI_STATUS ACPI_INIT_FUNCTION AcpiReallocateRootTable ( void) { ACPI_STATUS Status; ACPI_TABLE_DESC *TableDesc; UINT32 i, j; ACPI_FUNCTION_TRACE (AcpiReallocateRootTable); /* * If there are tables unverified, it is required to reallocate the * root table list to clean up invalid table entries. Otherwise only * reallocate the root table list if the host provided a static buffer * for the table array in the call to AcpiInitializeTables(). */ if ((AcpiGbl_RootTableList.Flags & ACPI_ROOT_ORIGIN_ALLOCATED) && AcpiGbl_EnableTableValidation) { return_ACPI_STATUS (AE_SUPPORT); } (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); /* * Ensure OS early boot logic, which is required by some hosts. If the * table state is reported to be wrong, developers should fix the * issue by invoking AcpiPutTable() for the reported table during the * early stage. */ for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; ++i) { TableDesc = &AcpiGbl_RootTableList.Tables[i]; if (TableDesc->Pointer) { ACPI_ERROR ((AE_INFO, "Table [%4.4s] is not invalidated during early boot stage", TableDesc->Signature.Ascii)); } } if (!AcpiGbl_EnableTableValidation) { /* * Now it's safe to do full table validation. We can do deferred * table initialization here once the flag is set. */ AcpiGbl_EnableTableValidation = TRUE; for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; ++i) { TableDesc = &AcpiGbl_RootTableList.Tables[i]; if (!(TableDesc->Flags & ACPI_TABLE_IS_VERIFIED)) { Status = AcpiTbVerifyTempTable (TableDesc, NULL, &j); if (ACPI_FAILURE (Status)) { AcpiTbUninstallTable (TableDesc); } } } } AcpiGbl_RootTableList.Flags |= ACPI_ROOT_ALLOW_RESIZE; Status = AcpiTbResizeRootTableList (); AcpiGbl_RootTableList.Flags |= ACPI_ROOT_ORIGIN_ALLOCATED; (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL_INIT (AcpiReallocateRootTable) /******************************************************************************* * * FUNCTION: AcpiGetTableHeader * * PARAMETERS: Signature - ACPI signature of needed table * Instance - Which instance (for SSDTs) * OutTableHeader - The pointer to the where the table header * is returned * * RETURN: Status and a copy of the table header * * DESCRIPTION: Finds and returns an ACPI table header. Caller provides the * memory where a copy of the header is to be returned * (fixed length). * ******************************************************************************/ ACPI_STATUS AcpiGetTableHeader ( char *Signature, UINT32 Instance, ACPI_TABLE_HEADER *OutTableHeader) { UINT32 i; UINT32 j; ACPI_TABLE_HEADER *Header; /* Parameter validation */ if (!Signature || !OutTableHeader) { return (AE_BAD_PARAMETER); } /* Walk the root table list */ for (i = 0, j = 0; i < AcpiGbl_RootTableList.CurrentTableCount; i++) { if (!ACPI_COMPARE_NAMESEG ( &(AcpiGbl_RootTableList.Tables[i].Signature), Signature)) { continue; } if (++j < Instance) { continue; } if (!AcpiGbl_RootTableList.Tables[i].Pointer) { if ((AcpiGbl_RootTableList.Tables[i].Flags & ACPI_TABLE_ORIGIN_MASK) == ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL) { Header = AcpiOsMapMemory ( AcpiGbl_RootTableList.Tables[i].Address, sizeof (ACPI_TABLE_HEADER)); if (!Header) { return (AE_NO_MEMORY); } memcpy (OutTableHeader, Header, sizeof (ACPI_TABLE_HEADER)); AcpiOsUnmapMemory (Header, sizeof (ACPI_TABLE_HEADER)); } else { return (AE_NOT_FOUND); } } else { memcpy (OutTableHeader, AcpiGbl_RootTableList.Tables[i].Pointer, sizeof (ACPI_TABLE_HEADER)); } return (AE_OK); } return (AE_NOT_FOUND); } ACPI_EXPORT_SYMBOL (AcpiGetTableHeader) /******************************************************************************* * * FUNCTION: AcpiGetTable * * PARAMETERS: Signature - ACPI signature of needed table * Instance - Which instance (for SSDTs) * OutTable - Where the pointer to the table is returned * * RETURN: Status and pointer to the requested table * * DESCRIPTION: Finds and verifies an ACPI table. Table must be in the * RSDT/XSDT. * Note that an early stage AcpiGetTable() call must be paired * with an early stage AcpiPutTable() call. otherwise the table * pointer mapped by the early stage mapping implementation may be * erroneously unmapped by the late stage unmapping implementation * in an AcpiPutTable() invoked during the late stage. * ******************************************************************************/ ACPI_STATUS AcpiGetTable ( char *Signature, UINT32 Instance, ACPI_TABLE_HEADER **OutTable) { UINT32 i; UINT32 j; ACPI_STATUS Status = AE_NOT_FOUND; ACPI_TABLE_DESC *TableDesc; /* Parameter validation */ if (!Signature || !OutTable) { return (AE_BAD_PARAMETER); } /* * Note that the following line is required by some OSPMs, they only * check if the returned table is NULL instead of the returned status * to determined if this function is succeeded. */ *OutTable = NULL; (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); /* Walk the root table list */ for (i = 0, j = 0; i < AcpiGbl_RootTableList.CurrentTableCount; i++) { TableDesc = &AcpiGbl_RootTableList.Tables[i]; if (!ACPI_COMPARE_NAMESEG (&TableDesc->Signature, Signature)) { continue; } if (++j < Instance) { continue; } Status = AcpiTbGetTable (TableDesc, OutTable); break; } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return (Status); } ACPI_EXPORT_SYMBOL (AcpiGetTable) /******************************************************************************* * * FUNCTION: AcpiPutTable * * PARAMETERS: Table - The pointer to the table * * RETURN: None * * DESCRIPTION: Release a table returned by AcpiGetTable() and its clones. * Note that it is not safe if this function was invoked after an * uninstallation happened to the original table descriptor. * Currently there is no OSPMs' requirement to handle such * situations. * ******************************************************************************/ void AcpiPutTable ( ACPI_TABLE_HEADER *Table) { UINT32 i; ACPI_TABLE_DESC *TableDesc; ACPI_FUNCTION_TRACE (AcpiPutTable); if (!Table) { return_VOID; } (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); /* Walk the root table list */ for (i = 0; i < AcpiGbl_RootTableList.CurrentTableCount; i++) { TableDesc = &AcpiGbl_RootTableList.Tables[i]; if (TableDesc->Pointer != Table) { continue; } AcpiTbPutTable (TableDesc); break; } (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_VOID; } ACPI_EXPORT_SYMBOL (AcpiPutTable) /******************************************************************************* * * FUNCTION: AcpiGetTableByIndex * * PARAMETERS: TableIndex - Table index * OutTable - Where the pointer to the table is returned * * RETURN: Status and pointer to the requested table * * DESCRIPTION: Obtain a table by an index into the global table list. Used * internally also. * ******************************************************************************/ ACPI_STATUS AcpiGetTableByIndex ( UINT32 TableIndex, ACPI_TABLE_HEADER **OutTable) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiGetTableByIndex); /* Parameter validation */ if (!OutTable) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* * Note that the following line is required by some OSPMs, they only * check if the returned table is NULL instead of the returned status * to determined if this function is succeeded. */ *OutTable = NULL; (void) AcpiUtAcquireMutex (ACPI_MTX_TABLES); /* Validate index */ if (TableIndex >= AcpiGbl_RootTableList.CurrentTableCount) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } Status = AcpiTbGetTable ( &AcpiGbl_RootTableList.Tables[TableIndex], OutTable); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_TABLES); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetTableByIndex) /******************************************************************************* * * FUNCTION: AcpiInstallTableHandler * * PARAMETERS: Handler - Table event handler * Context - Value passed to the handler on each event * * RETURN: Status * * DESCRIPTION: Install a global table event handler. * ******************************************************************************/ ACPI_STATUS AcpiInstallTableHandler ( ACPI_TABLE_HANDLER Handler, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallTableHandler); if (!Handler) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Don't allow more than one handler */ if (AcpiGbl_TableHandler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } /* Install the handler */ AcpiGbl_TableHandler = Handler; AcpiGbl_TableHandlerContext = Context; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallTableHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveTableHandler * * PARAMETERS: Handler - Table event handler that was installed * previously. * * RETURN: Status * * DESCRIPTION: Remove a table event handler * ******************************************************************************/ ACPI_STATUS AcpiRemoveTableHandler ( ACPI_TABLE_HANDLER Handler) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiRemoveTableHandler); Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Make sure that the installed handler is the same */ if (!Handler || Handler != AcpiGbl_TableHandler) { Status = AE_BAD_PARAMETER; goto Cleanup; } /* Remove the handler */ AcpiGbl_TableHandler = NULL; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveTableHandler) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/time.h> #include <dirent.h> #include "devshell.h" #include "sysenter.h" #include "test_common.h" int cmd_fatmm1(int argc, char **argv) { int fd, rc; char *vaddr; char buf[512]; size_t file_size; struct stat statbuf; const size_t page_size = getpagesize(); const char *test_file_name = DEVSHELL_PATH; const size_t mmap_size = page_size * 2; const size_t mmap_off = page_size * 4; if (!getenv("TILCK")) { printf(PFX "[SKIP] because we're not running on Tilck\n"); return 0; } printf("Using '%s' as test file\n", test_file_name); fd = open(test_file_name, O_RDONLY, 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = fstat(fd, &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); file_size = statbuf.st_size; printf("File size: %llu\n", (ull_t)file_size); vaddr = mmap(NULL, /* addr */ mmap_size, /* length */ PROT_READ, /* prot */ MAP_SHARED, /* flags */ fd, /* fd */ mmap_off); if (vaddr == (void *)-1) { fprintf(stderr, "ERROR: mmap failed: %s\n", strerror(errno)); goto err_end; } printf("- Check that reading at `vaddr` succeeds\n"); do_mm_read(vaddr); if (lseek(fd, mmap_off, SEEK_SET) < 0) { fprintf(stderr, "ERROR: lseek failed: %s\n", strerror(errno)); goto err_end; } for (size_t t = 0; t < mmap_size; t += sizeof(buf)) { rc = read(fd, buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc == sizeof(buf)); if (memcmp(buf, vaddr + t, sizeof(buf))) { fprintf(stderr, "ERROR: content does NOT match\n"); goto err_end; } } printf("- Content matches!\n"); printf("- Check we can fork() a process with fat mmaps\n"); if (test_sig(do_mm_read, vaddr, 0, 0, 0)) goto err_end; printf("- Check that reading at `vaddr` still succeeds from parent\n"); do_mm_read(vaddr); printf("- Now check for SIGSEGV in the unmapped areas\n"); printf("- vaddr + mmap_off + mmap_size\n"); if (test_sig(do_mm_read, vaddr + mmap_off + mmap_size, SIGSEGV, 0, 0)) goto err_end; printf("DONE\n"); close(fd); return 0; err_end: close(fd); return 1; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define BPB_OFFSET 0x00b #define PART_TABLE_OFFSET 0x1be #define DISK_UUID_OFFSET 0x1b8 #define MAX_EBPB_SIZE 128 #define INFO(fmt, ...) \ do { \ if (!opt_quiet) \ fprintf(stdout, "INFO: " fmt, ##__VA_ARGS__); \ } while (0) #define WARNING(fmt, ...) fprintf(stderr, "WARNING: " fmt, ##__VA_ARGS__) #define ERROR(fmt, ...) fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__) /* DOS 3.31 BPB */ struct PACKED bpb { u16 sector_size; u8 sec_per_cluster; u16 res_sectors; u8 num_fats; u16 root_entries; u16 small_sector_count; u8 media_type; u16 sectors_per_fat; u16 sectors_per_track; u16 heads_per_cyl; u32 hidden_sectors; u32 large_sector_count; char __extra[0]; /* declare we're going to write out-of-bounds */ }; struct PACKED ebpb34 { struct bpb bpb; u8 drive_num; u8 bflags; u8 boot_sig; u32 serial; }; struct PACKED mbr_part { u8 boot; u8 start_head; u8 start_sec : 6; u8 start_hi_cyl : 2; u8 start_cyl; u8 id; u8 end_head; u8 end_sec : 6; u8 end_hi_cyl : 2; u8 end_cyl; u32 lba_start; u32 lba_tot; }; static inline u32 bpb_get_sectors_count(struct bpb *b) { return b->small_sector_count ? b->small_sector_count : b->large_sector_count; } static inline u16 get_start_cyl(struct mbr_part *p) { return (u16)p->start_cyl | (((u16)p->start_hi_cyl) << 8); } static inline u16 get_end_cyl(struct mbr_part *p) { return (u16)p->end_cyl | (((u16)p->end_hi_cyl) << 8); } static inline void set_start_cyl(struct mbr_part *p, u16 val) { p->start_cyl = val & 0xff; p->start_hi_cyl = (val >> 8) & 3; } static inline void set_end_cyl(struct mbr_part *p, u16 val) { p->end_cyl = val & 0xff; p->end_hi_cyl = (val >> 8) & 3; } static u32 chs_to_lba(struct bpb *b, u32 c, u32 h, u32 s) { return (c * b->heads_per_cyl + h) * b->sectors_per_track + (s - 1); } static void lba_to_chs(struct bpb *b, u32 lba, u16 *c, u16 *h, u16 *s) { *c = lba / (b->heads_per_cyl * b->sectors_per_track); *h = (lba / b->sectors_per_track) % b->heads_per_cyl; *s = (lba % b->sectors_per_track) + 1; } static u32 get_part_start(struct bpb *b, struct mbr_part *p) { return chs_to_lba(b, get_start_cyl(p), p->start_head, p->start_sec); } static u32 get_part_end(struct bpb *b, struct mbr_part *p) { return chs_to_lba(b, get_end_cyl(p), p->end_head, p->end_sec); } struct PACKED mbr_part_table { struct mbr_part partitions[4]; }; struct mbr_info { unsigned char jmp[3]; struct bpb *b; struct mbr_part_table *t; u32 disk_uuid; }; static void dump_bpb(struct bpb *b) { printf("Bios Parameter Block (DOS 3.31):\n"); printf(" Media type: %#9x\n", b->media_type); printf(" Sector size: %8u\n", b->sector_size); printf(" Heads per cyl: %8u\n", b->heads_per_cyl); printf(" Sectors per track: %8u\n", b->sectors_per_track); printf(" Reserved sectors: %8u\n", b->res_sectors); printf(" Hidden sectors: %8u\n", b->hidden_sectors); printf(" Tot sectors count: %8u\n", bpb_get_sectors_count(b)); printf("\n"); struct ebpb34 *ext = (void *)b; if (ext->boot_sig == 0x28 || ext->boot_sig == 0x29) { printf("Extended fields (DOS 3.4 EBPB):\n"); printf(" BPB signature: %#10x\n", ext->boot_sig); printf(" Serial num: %#10x\n", ext->serial); } } static int bpb_check(struct mbr_info *nfo) { struct bpb *b = nfo->b; struct ebpb34 *ext = (void *)b; if (ext->boot_sig != 0x28 && ext->boot_sig != 0x29) { WARNING("Unsupported BPB signature: %#x\n", ext->boot_sig); if (nfo->jmp[0] != 0xEB) WARNING("Very likely this MBR does NOT contain a BPB at all.\n"); else WARNING("The BPB is likely a DOS 7.1 EBPB\n"); return 1; } if (!b->sector_size) { ERROR("Invalid BIOS Parameter Block: missing sector size\n"); return -1; } if (!b->heads_per_cyl) { ERROR("Invalid BIOS Parameter Block: missing heads per cylinder\n"); return -1; } if (!b->sectors_per_track) { ERROR("Invalid BIOS Parameter Block: missing sectors per track\n"); return -1; } if (!b->res_sectors) { ERROR("Invalid BIOS Parameter Block: resSectors == 0. Must be >= 1.\n"); return -1; } if (!b->small_sector_count && !b->large_sector_count) { ERROR("Invalid BIOS Parameter Block: missing sector count\n"); return -1; } return 0; } struct cmd { const char *name; int params; int (*func)(struct mbr_info *i, char **); }; static bool opt_quiet; static void show_help_and_exit(int argc, char **argv) { printf("Syntax:\n"); printf("\t%s [-q] <file> <command> [<cmd args...>]\n", argv[0]); printf("\n"); printf("Commands:\n"); printf("\tinfo \tDump BPB and list partitions\n"); printf("\tclear \tRemove all the partitions\n"); printf("\tcheck \tDo sanity checks\n"); printf("\tremove <n> \tRemove the partition <n> (1-4)\n"); printf("\tboot <n> \tMake the partition <n> bootable\n"); printf("\tadd <type> <first> <last>\tAdd a new partition in a free slot\n"); printf("\tbpb s h spt tS rS hS sn \tWrite the Bios Parameter Block\n"); printf("\n"); printf("Notes:\n"); printf("\t- Both `first` and `last` are expressed in sectors\n"); printf("\t- `last` can turned into `length` by prefixing it with `+`\n"); printf("\t- The `length` param is KB or MB when followed by K, M (+2M)\n"); printf("\t- `Type` is supposed to be a hex byte, like 0xC\n"); printf("\t- `s` = sector size\n"); printf("\t- `h` = heads per cylinder\n"); printf("\t- `spt` = sectors per track\n"); printf("\t- `tS` = total sectors\n"); printf("\t- `rS` = reserved sectors\n"); printf("\t- `hS` = hidden sectors\n"); printf("\t- `sn` = serial number / disk UUID (hex)\n"); printf("\n"); exit(1); } static int find_first_free(struct mbr_part_table *t) { for (int i = 0; i < 4; i++) if (t->partitions[i].id == 0) return i; return -1; } static int parse_new_part_params(struct bpb *b, char **argv, u8 *rt, u32 *rs, u32 *re) { unsigned long type, start, end; char *endp, *end_str = argv[2]; bool end_is_size = false; errno = 0; type = strtoul(argv[0], NULL, 16); if (errno) { ERROR("Invalid type param (%s). Expected a hex num\n", argv[0]); return -1; } if (!IN_RANGE_INC(type, 0x1, 0xff)) { ERROR("Invalid type param. Range: 0x01 - 0xff\n"); return -1; } if (argv[1][0] == '+') { ERROR("Invalid <start sector> param (%s)\n", argv[1]); return -1; } errno = 0; start = strtoul(argv[1], NULL, 10); if (errno) { ERROR("Invalid <start sector> param (%s)\n", argv[1]); return -1; } if (start > 0xffffffff) { ERROR("start sector cannot fit in LBA (32-bit)\n"); return -1; } if (start < b->res_sectors) { ERROR("start sector falls in reserved area\n"); return -1; } if (start >= bpb_get_sectors_count(b)) { ERROR("start sector is too big for this disk\n"); return -1; } if (*end_str == '+') { end_is_size = true; end_str++; } errno = 0; end = strtoul(end_str, &endp, 10); if (errno) { ERROR("Invalid <end sector> param (%s)\n", argv[1]); return -1; } if (end_is_size) { /* Calculate the actual value of `end` */ if (*endp == 'K') end *= 1024 / b->sector_size; else if (*endp == 'M') end *= (1024 / b->sector_size) * 1024; end += start - 1; } if (end > 0xffffffff) { ERROR("end sector cannot fit in LBA (32-bit)\n"); return -1; } if (end < b->res_sectors) { ERROR("end sector falls in reserved area\n"); return -1; } if (end >= bpb_get_sectors_count(b)) { ERROR("start sector is too big for this disk\n"); return -1; } if (start > end) { ERROR("start (%lu) > end (%lu)\n", start, end); return -1; } *rt = type; *rs = start; *re = end; return 0; } static void do_set_part(struct bpb *b, struct mbr_part_table *t, int n, u8 type, u32 start, u32 end) { struct mbr_part *p = &t->partitions[n]; u16 c, h, s; p->boot = 0; p->id = type; lba_to_chs(b, start, &c, &h, &s); p->start_head = h; p->start_sec = s; set_start_cyl(p, c); lba_to_chs(b, end, &c, &h, &s); p->end_head = h; p->end_sec = s; set_end_cyl(p, c); p->lba_start = start; p->lba_tot = end - start + 1; } static int find_overlapping_part(struct bpb *b, struct mbr_part_table *t, u32 start, u32 end) { for (int i = 0; i < 4; i++) { if (!t->partitions[i].id) continue; struct mbr_part *p = &t->partitions[i]; u32 p_start = get_part_start(b, p); u32 p_end = get_part_end(b, p); if (IN_RANGE_INC(start, p_start, p_end) || IN_RANGE_INC(end, p_start, p_end)) { return i; } } return -1; } static int cmd_add(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; u32 start, end; int n, overlap; u8 type; if (bpb_check(nfo) != 0) { ERROR("Unable to add partitions: unknown disk CHS geometry.\n"); return 1; } n = find_first_free(t); if (n < 0) { ERROR("No free partition slot\n"); return 1; } if (parse_new_part_params(b, argv, &type, &start, &end)) return 1; overlap = find_overlapping_part(b, t, start, end); if (overlap >= 0) { ERROR("the new partition overlaps with partition %d\n", overlap + 1); return 1; } do_set_part(b, t, n, type, start, end); if (n == 0) t->partitions[0].boot = 0x80; return 0; } static int cmd_remove(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; int num = atoi(argv[0]); if (bpb_check(nfo) < 0) return 1; if (!IN_RANGE_INC(num, 1, 4)) { ERROR("Invalid partition number. Valid range: 1-4.\n"); return 1; } memset(&t->partitions[num - 1], 0, sizeof(struct mbr_part)); return 0; } static int cmd_boot(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; int num = atoi(argv[0]); struct mbr_part *p; if (bpb_check(nfo) < 0) return 1; if (!IN_RANGE_INC(num, 1, 4)) { ERROR("Invalid partition number. Valid range: 1-4.\n"); return 1; } num--; p = &t->partitions[num]; if (!p->id) { ERROR("partition %d is UNUSED\n", num + 1); return 1; } for (int i = 0; i < 4; i++) { if (i == num) t->partitions[i].boot = 0x80; else t->partitions[i].boot = 0; } return 0; } static int do_check_partitions(struct bpb *b, struct mbr_part_table *t) { int fail = 0; for (int i = 0; i < 4; i++) { struct mbr_part *p = &t->partitions[i]; if (p->id == 0) continue; u32 s = chs_to_lba(b, get_start_cyl(p), p->start_head, p->start_sec); u32 e = chs_to_lba(b, get_end_cyl(p), p->end_head, p->end_sec); u32 end_lba = p->lba_start + p->lba_tot - 1; if (s != p->lba_start) { printf("WARNING: for partition %d, " "CHS start (%u,%u,%u) -> %u " "DIFFERS FROM declared LBA: %u\n", i+1, get_start_cyl(p), p->start_head, p->start_sec, s, p->lba_start); fail = 1; } else if (e != end_lba) { /* * It makes no sense to check for this condition when * s != p->lba_start, because shifting the `start` automatically * shifts the end too. Just check for this only when `start` matches. */ printf("WARNING: for partition %d, " "CHS end (%u,%u,%u) -> %u " "DIFFERS FROM declared LBA: %u\n", i+1, get_end_cyl(p), p->end_head, p->end_sec, e, end_lba); fail = 1; } } return fail; } static int cmd_info(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; if (bpb_check(nfo) < 0) return 1; printf("\n"); dump_bpb(b); printf("\n"); printf("Disk UUID (if valid):\n"); printf(" Value: %#9x\n", nfo->disk_uuid); printf("\n"); printf("Partitions:\n\n"); printf(" " " n | boot | type | start (chs) | end (chs) |" " lba | other \n"); printf(" " "---+------+------+------------------+------------------+" "----------------+--------------------------------\n"); for (int i = 0; i < 4; i++) { struct mbr_part *p = &t->partitions[i]; if (p->id == 0) { printf(" %d | <unused>\n", i+1); continue; } printf(" %d | %s | 0x%02x | " "(%5u, %3u, %2u) | (%5u, %3u, %2u) | " "[%5u, %5u] | tot: %5u -> %u KB\n", i+1, p->boot & 0x80 ? " * " : " ", p->id, get_start_cyl(p), p->start_head, p->start_sec, get_end_cyl(p), p->end_head, p->end_sec, p->lba_start, p->lba_start + p->lba_tot - 1, p->lba_tot, p->lba_tot * b->sector_size / 1024); } printf("\n"); do_check_partitions(b, t); return 0; } static int cmd_clear(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; if (bpb_check(nfo) < 0) return 1; memset(t, 0, sizeof(*t)); return 0; } static int cmd_check(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct mbr_part_table *t = nfo->t; if (bpb_check(nfo) < 0) return 1; return do_check_partitions(b, t); } static int cmd_bpb(struct mbr_info *nfo, char **argv) { struct bpb *b = nfo->b; struct ebpb34 *e = (void *)b; unsigned long val, bpb_space; if (nfo->jmp[0] == 0xEB && IN_RANGE(nfo->jmp[1], 12, 128)) { /* * There's likely already another BPB here or a hole for a BPB. * Let's determine the available space. */ bpb_space = (u32)nfo->jmp[1] - 11 + 2; /* Off. rel. to the next instr. */ } else { /* * Cannot find a valid initial jmp instruction. * Let's use the space we need. We have no other choice. */ bpb_space = sizeof(*e); if (nfo->jmp[0] != 0) { WARNING("Possibly overriding an MBR without BPB\n"); if (nfo->jmp[0] == 0xFA) WARNING("This 1st byte looks like a x86 CLI instruction\n"); } } if (bpb_space < sizeof(*e)) { ERROR("Available space for BPB: %lu B < %lu B\n", bpb_space, sizeof(*e)); ERROR("Writing a EBPB 3.4 will certaily override MBR code\n"); ERROR("Stop. Nothing was written.\n"); return 1; } /* zero the whole available space as we won't set all of its fields */ memset(e, 0, bpb_space); e->bpb.media_type = 0xf0; /* floppy (good even if media is a USB stick) */ e->drive_num = 0x80; /* standard value for first the disk */ e->boot_sig = 0x28; /* DOS 3.4 EBPB */ { const char *str_val = argv[0]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno || val > 4096) { ERROR("Invalid sector size value '%s'\n", str_val); return 1; } e->bpb.sector_size = val; } { const char *str_val = argv[1]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno || val > 255) { ERROR("Invalid heads per cylinder value '%s'\n", str_val); return 1; } e->bpb.heads_per_cyl = val; } { const char *str_val = argv[2]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno || val > 255) { ERROR("Invalid sectors per track value '%s'\n", str_val); return 1; } e->bpb.sectors_per_track = val; } { const char *str_val = argv[3]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno) { ERROR("Invalid total sectors value '%s'\n", str_val); return 1; } e->bpb.large_sector_count = val; } { const char *str_val = argv[4]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno || val == 0) { ERROR("Invalid reserved sectors value '%s'\n", str_val); return 1; } e->bpb.res_sectors = val; } { const char *str_val = argv[5]; errno = 0; val = strtoul(str_val, NULL, 10); if (errno) { ERROR("Invalid hidden sectors value '%s'\n", str_val); return 1; } e->bpb.hidden_sectors = val; } { const char *str_val = argv[6]; errno = 0; val = strtoul(str_val, NULL, 16); if (errno) { ERROR("Invalid serial/UUID value '%s'\n", str_val); return 1; } e->serial = val; /* Keep BPB's serial in sync with the UUID field */ nfo->disk_uuid = val; } return 0; } #define DECL_CMD(nn, par) {.name = #nn, .params = par, .func = &cmd_##nn} const static struct cmd cmds[] = { DECL_CMD(info, 0), DECL_CMD(clear, 0), DECL_CMD(check, 0), DECL_CMD(remove, 1), DECL_CMD(add, 3), DECL_CMD(boot, 1), DECL_CMD(bpb, 7), }; static int parse_opts(int argc, char ***r_argv, struct cmd *c_ref, const char **file_ref) { char **argv = *r_argv; const char *cmdname; struct cmd cmd = {0}; int i; if (argc <= 2) return -1; /* Forget about the 1st parameter (cmd line) */ argc--; argv++; if (!strcmp(argv[0], "-q")) { opt_quiet = true; argc--; argv++; } if (argc < 2) return -1; /* too few args */ *file_ref = argv[0]; cmdname = argv[1]; for (i = 0; i < ARRAY_SIZE(cmds); i++) { if (!strcmp(cmdname, cmds[i].name)) { cmd = cmds[i]; break; } } if (i == ARRAY_SIZE(cmds)) return -1; /* unknown command */ argc -= 2; /* file and cmd name */ argv += 2; /* file and cmd name */ if (argc < cmd.params) return -1; /* too few args */ *c_ref = cmd; *r_argv = argv; return 0; } int main(int argc, char **argv) { const char *file; struct cmd cmd; char buf[512]; FILE *fh; size_t r; int rc; struct mbr_part_table t; char bpb_buf[MAX_EBPB_SIZE] ALIGNED_AT(4); bool write_back = false; struct mbr_info i = { .b = (void *)bpb_buf, .t = (void *)&t, .disk_uuid = 0, }; STATIC_ASSERT(sizeof(t.partitions[0]) == 16); STATIC_ASSERT(sizeof(t) == 64); /* 4 x 16 bytes */ if (parse_opts(argc, &argv, &cmd, &file) < 0) show_help_and_exit(argc, argv); fh = fopen(file, "r+b"); if (!fh) { ERROR("Failed to open file '%s'\n", file); return 1; } r = fread(buf, 1, 512, fh); if (r != 512) { ERROR("Failed to read the first 512 bytes\n"); return 1; } memcpy(i.jmp, buf + 0, sizeof(i.jmp)); memcpy(bpb_buf, buf + BPB_OFFSET, sizeof(bpb_buf)); memcpy(&t, buf + PART_TABLE_OFFSET, sizeof(t)); memcpy(&i.disk_uuid, buf + DISK_UUID_OFFSET, sizeof(i.disk_uuid)); /* Call func with its specific params */ rc = cmd.func(&i, argv); if (!rc) { if (memcmp(bpb_buf, buf + BPB_OFFSET, sizeof(bpb_buf))) { INFO("BIOS parameter block changed, write it back\n"); memcpy(buf + BPB_OFFSET, bpb_buf, sizeof(bpb_buf)); write_back = true; } if (memcmp(&t, buf + PART_TABLE_OFFSET, sizeof(t))) { INFO("Partition table changed, write it back\n"); memcpy(buf + PART_TABLE_OFFSET, &t, sizeof(t)); write_back = true; } if (memcmp(&i.disk_uuid, buf + DISK_UUID_OFFSET, sizeof(i.disk_uuid))) { INFO("DISK UUID changed, write it back\n"); memcpy(buf + DISK_UUID_OFFSET, &i.disk_uuid, sizeof(i.disk_uuid)); write_back = true; } } if (write_back) { if (fseek(fh, 0, SEEK_SET) < 0) { ERROR("fseek() failed\n"); goto end; } r = fwrite(buf, 1, 512, fh); if (r != 512) { ERROR("Failed to write the first 512 bytes\n"); rc = 1; } } end: fclose(fh); return rc; } <file_sep>FROM fedora:latest RUN yum -y install util-linux sudo <file_sep>#!/bin/sh # # Constants # VR_TGZ="/initrd/usr/lib/vim/vr.tgz" VIM_GZ="/initrd/usr/lib/vim/vim.gz" vim_binary=/tmp/vim/vim # # Main body # set -e oldpwd="$PWD" if ! [ -f $VIM_GZ ] || ! [ -f $VR_TGZ ]; then echo "" echo "VIM is not built-in. Tilck image rebuild needed. Steps:" echo " - Run: ./scripts/build_toolchain -s build_vim" echo " - Run: CMAKE_ARGS='-DEXTRA_VIM=1' ./scripts/cmake_run" echo " - Run: make rem" echo "" exit 1 fi export VIMRUNTIME=/tmp/vim/runtime if ! [ -d $VIMRUNTIME ]; then mkdir -p /tmp/vim cd /tmp/vim if ! tar xfz $VR_TGZ; then echo "ERROR: tar failed" cd / rm -rf /tmp/vim exit 1 fi sed -Ei s/scrolloff=[0-9]*/scrolloff=0/g $VIMRUNTIME/defaults.vim fi if ! [ -f $vim_binary ]; then gzip -cd $VIM_GZ > $vim_binary chmod 755 $vim_binary fi cd $oldpwd # Start vim with no swap file (-n) and no viminfo (-i) # simply because they're useless for the use case of Tilck. exec $vim_binary -n -i NONE "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/paging.h> #define ELF_RAW_HEADER_SIZE 128 struct locked_file; /* forward declaration */ struct elf_program_info { pdir_t *pdir; // The pdir used for the program void *entry; // The address of program's entry point void *stack; // The initial value of the stack pointer void *brk; // The first invalid vaddr (program break) struct locked_file *lf; // ELF's file lock (can be NULL) bool wrong_arch; // The ELF is compiled for the wrong arch bool dyn_exec; // The ELF is a dynamic executable (not supported) }; /* * Loads an ELF program in memory. * * `filepath`: IN arg, the path of the ELF file to load. * * `header_buf`: IN arg, the address of a buffer where to store the first * `ELF_RAW_HEADER_SIZE` bytes of the file at `filepath`. * * 'pinfo': OUT arg, essential info about the loaded program. */ int load_elf_program(const char *filepath, char *header_buf, struct elf_program_info *pinfo); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/list.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/errno.h> /* Shared global variables */ struct task *__current; ATOMIC(int) __disable_preempt = 1; /* see docs/atomics.md */ ATOMIC(int) __need_resched; /* see docs/atomics.md */ struct task *kernel_process; struct process *kernel_process_pi; /* Task lists */ struct list runnable_tasks_list; /* Static variables */ static struct task *tree_by_tid_root; static u64 idle_ticks; static volatile int runnable_tasks_count; static int current_max_pid = -1; static int current_max_kernel_tid = -1; struct task *idle_task; const char *const task_state_str[5] = { [TASK_STATE_INVALID] = "invalid", [TASK_STATE_RUNNABLE] = "runnable", [TASK_STATE_RUNNING] = "running", [TASK_STATE_SLEEPING] = "sleeping", [TASK_STATE_ZOMBIE] = "zombie", }; void enable_preemption(void) { int oldval = atomic_fetch_sub_explicit(&__disable_preempt, 1, mo_relaxed); ASSERT(oldval > 0); if (KRN_RESCHED_ENABLE_PREEMPT) { if (oldval == 1 && need_reschedule() && are_interrupts_enabled()) schedule(); } } bool save_regs_and_schedule(bool skip_disable_preempt) { /* Private declaraction of the low-level yield function */ extern bool asm_save_regs_and_schedule(void *); bool context_switch; if (skip_disable_preempt) { ASSERT(get_preempt_disable_count() == 1); } else { ASSERT(get_preempt_disable_count() == 0); disable_preemption(); } context_switch = asm_save_regs_and_schedule( __builtin_extract_return_addr(__builtin_return_address(0)) ); if (UNLIKELY(!context_switch)) enable_preemption_nosched(); return context_switch; } int get_traced_tasks_count(void) { struct bintree_walk_ctx ctx; struct task *ti; int count = 0; disable_preemption(); { bintree_in_order_visit_start(&ctx, tree_by_tid_root, struct task, tree_by_tid_node, false); while ((ti = bintree_in_order_visit_next(&ctx))) { if (ti->traced) count++; } } enable_preemption(); return count; } int sched_count_proc_in_group(int pgid) { struct bintree_walk_ctx ctx; struct task *ti; int count = 0; disable_preemption(); { bintree_in_order_visit_start(&ctx, tree_by_tid_root, struct task, tree_by_tid_node, false); while ((ti = bintree_in_order_visit_next(&ctx))) { if (ti->pi->pgid == pgid) count++; } } enable_preemption(); return count; } int sched_get_session_of_group(int pgid) { struct bintree_walk_ctx ctx; struct task *ti; int sid = -ESRCH; disable_preemption(); { bintree_in_order_visit_start(&ctx, tree_by_tid_root, struct task, tree_by_tid_node, false); while ((ti = bintree_in_order_visit_next(&ctx))) { if (ti->pi->pgid == pgid) { sid = ti->pi->sid; break; } } } enable_preemption(); return sid; } int get_curr_tid(void) { struct task *c = get_curr_task(); return c ? c->tid : 0; } int get_curr_pid(void) { struct task *c = get_curr_task(); return c ? c->pi->pid : 0; } struct create_pid_visit_ctx { bool kernel_tid; bool lowest_avail_invalid; int id_off; int lowest_available; int lowest_after_current_max; }; static inline int inc_candicate_if_matches(int *cand, int id, int val) { if (*cand != val) return 0; /* Everything is OK */ /* The lowest_<something> candicate cannot be > id */ ASSERT(*cand <= val); /* * We've found a case where the candicate is equal to current task's pgid/sid * and that might be a problem. * * Two cases: * * 1) Candidate == id. This means: candidate == pgid/sid == id. * That's fine: we just hit a group/session leader. By default we'll * skip this candiate (see the impl. below). * * 2) Candidate < id. This means that the pgid/sid is < id and we didn't * hit it before (note: we're doing an in-order visit). For example: * * pid | sid | what * ----+-----+----------- * 1 | 1 | init * 2 | 1 | ash * 8 | 3 | prog1 * * lowest_available = 3 [our candidate] * * We don't want this to happen because 3 is the ID of a session, with * a dead leader. In order to handle this case, we have to increment * lowest_available and restart the whole iteration. We must end up with * lowest_available = 4. Actually, if lowest_after_current_max is a good * value, we're going to use it without restarting the iteration. */ if (*cand == id) return 0; /* We just hit a group/session leader. That's fine */ (*cand)++; return 1; } static int create_new_pid_visit_cb(void *obj, void *arg) { struct task *ti = obj; struct create_pid_visit_ctx *ctx = arg; const int tid = ti->tid - ctx->id_off; if (ctx->kernel_tid) { if (!is_kernel_thread(ti)) return 0; /* skip non-kernel tasks */ ASSERT(tid >= 0); } else { if (!is_main_thread(ti)) return 0; /* skip threads */ ASSERT(tid >= 0); if (tid < ctx->lowest_available) return 0; /* * Both ctx->lowest_available and ctx->lowest_after_current_max are * candidates for the next tid. If one of them gets equal to a sid * without a session leader process or to a pgid without a group leader, * the new process could accidentally become leader of a group/session: * we have to ensure that could never happen. */ const int pgid = ti->pi->pgid; const int sid = ti->pi->sid; const int should_restart = inc_candicate_if_matches(&ctx->lowest_available, tid, pgid) + inc_candicate_if_matches(&ctx->lowest_available, tid, sid) + inc_candicate_if_matches(&ctx->lowest_after_current_max, tid, pgid) + inc_candicate_if_matches(&ctx->lowest_after_current_max, tid, sid); if (should_restart) { ctx->lowest_avail_invalid = true; } } /* * Algorithm: we start with lowest_available (L) == 0. When we hit * tid == L, that means L is not really the lowest, therefore, we guess * the right value of L is L + 1. The first time tid skips one, for example * jumping from 3 to 5, the value of L set by the iteration with tid == 3, * will stuck. That value will be clearly 4. */ if (ctx->lowest_available == tid) ctx->lowest_available++; /* * For lowest_after_current_max (A) the logic is similar. * We start with A = current_max_pid + 1. The first time A is == tid, will * be when tid is current_max_pid + 1. We continue to update A, until the * first hole is found. In case tid never reaches current_max_pid + 1, `A` * will be just be current_max_pid + 1, as expected. */ if (ctx->lowest_after_current_max == tid) ctx->lowest_after_current_max++; return 0; } static int create_id_common(struct create_pid_visit_ctx *ctx, int max_id) { int r; do { ctx->lowest_avail_invalid = false; iterate_over_tasks(&create_new_pid_visit_cb, ctx); r = ctx->lowest_after_current_max <= max_id ? ctx->lowest_after_current_max : ctx->lowest_available <= max_id ? ctx->lowest_available : -1; /* * Typically, ctx->lowest_avail_invalid is not a problem because the new * id will be ctx->lowest_after_current_max. But, in the case we've * finished the IDs, we have to pick the absolutely lowest ID available, * which might be invalid we it matched with a process' pgid/sid. This * can happen only in case of orphaned sessions/process groups. * * NOTE: in case we're going to repeat the loop, lowest_avail_invalid is * reset, but all the rest of the context is unchanged: that's because * ctx->lowest_available has actually a meaningful value: the lowest ID * after pgid/sid we hit. It doesn't mean we can use this value, but it * means we cannot pick consider IDs smaller than it. */ } while (r == ctx->lowest_available && ctx->lowest_avail_invalid); return r; } int create_new_pid(void) { ASSERT(!is_preemption_enabled()); struct create_pid_visit_ctx ctx = { .kernel_tid = false, .id_off = 0, .lowest_available = 0, .lowest_after_current_max = current_max_pid + 1, }; int r = create_id_common(&ctx, MAX_PID); if (r >= 0) current_max_pid = r; return r; } int create_new_kernel_tid(void) { ASSERT(!is_preemption_enabled()); struct create_pid_visit_ctx ctx = { .kernel_tid = true, .id_off = KERNEL_TID_START, .lowest_available = 0, .lowest_after_current_max = current_max_kernel_tid + 1, }; int r = create_id_common(&ctx, KERNEL_MAX_TID); if (r >= 0) { current_max_kernel_tid = r; return r + KERNEL_TID_START; } return -1; } int iterate_over_tasks(bintree_visit_cb func, void *arg) { ASSERT(!is_preemption_enabled()); return bintree_in_order_visit(tree_by_tid_root, func, arg, struct task, tree_by_tid_node); } static void idle(void) { while (true) { ASSERT(is_preemption_enabled()); idle_ticks++; halt(); if (need_reschedule() || runnable_tasks_count > 1) schedule(); } } void yield_until_last(void) { ASSERT(is_preemption_enabled()); do { kernel_yield(); } while (runnable_tasks_count > 2); kernel_yield(); } __attribute__((constructor)) static void create_kernel_process(void) { static char kernel_proc_buf[ sizeof(struct process) + sizeof(struct task) ] ALIGNED_AT(sizeof(void *)); struct task *s_kernel_ti = (struct task *)kernel_proc_buf; struct process *s_kernel_pi = (struct process *)(s_kernel_ti + 1); list_init(&runnable_tasks_list); s_kernel_pi->pid = create_new_pid(); s_kernel_ti->tid = create_new_kernel_tid(); s_kernel_pi->ref_count = 1; s_kernel_ti->pi = s_kernel_pi; init_task_lists(s_kernel_ti); init_process_lists(s_kernel_pi); s_kernel_ti->is_main_thread = true; s_kernel_ti->running_in_kernel = true; memcpy(s_kernel_pi->str_cwd, "/", 2); s_kernel_ti->state = TASK_STATE_SLEEPING; kernel_process = s_kernel_ti; kernel_process_pi = s_kernel_ti->pi; #ifndef UNIT_TEST_ENVIRONMENT if (!in_panic()) { bzero(s_kernel_ti->ti_arch, sizeof(s_kernel_ti->ti_arch)); bzero(s_kernel_pi->pi_arch, sizeof(s_kernel_pi->pi_arch)); add_task(kernel_process); } #endif set_curr_task(kernel_process); } struct process *task_get_pi_opaque(struct task *ti) { if (ti != NULL) return ti->pi; return NULL; } void process_set_tty(struct process *pi, void *t) { pi->proc_tty = t; } void init_sched(void) { int tid; ASSERT(kernel_process_pi->pid == 0); ASSERT(kernel_process_pi->parent_pid == 0); kernel_process->pi->pdir = get_kernel_pdir(); tid = kthread_create(&idle, 0, NULL); if (tid < 0) panic("Unable to create the idle_task!"); idle_task = get_task(tid); } void set_current_task_in_kernel(void) { ASSERT(!is_preemption_enabled()); get_curr_task()->running_in_kernel = true; } static void task_add_to_state_list(struct task *ti) { if (is_worker_thread(ti)) return; switch (atomic_load_explicit(&ti->state, mo_relaxed)) { case TASK_STATE_RUNNABLE: list_add_tail(&runnable_tasks_list, &ti->runnable_node); runnable_tasks_count++; break; case TASK_STATE_SLEEPING: /* no dedicated list */ break; case TASK_STATE_RUNNING: /* no dedicated list: without SMP there's only one 'running' task */ break; case TASK_STATE_ZOMBIE: /* no dedicated list */ break; default: NOT_REACHED(); } } static void task_remove_from_state_list(struct task *ti) { if (is_worker_thread(ti)) return; switch (atomic_load_explicit(&ti->state, mo_relaxed)) { case TASK_STATE_RUNNABLE: list_remove(&ti->runnable_node); runnable_tasks_count--; ASSERT(runnable_tasks_count >= 0); break; case TASK_STATE_SLEEPING: /* no dedicated list */ break; case TASK_STATE_RUNNING: /* no dedicated list */ break; case TASK_STATE_ZOMBIE: /* no dedicated list */ break; default: NOT_REACHED(); } } void task_change_state(struct task *ti, enum task_state new_state) { ulong var; ASSERT(ti->state != new_state); ASSERT(ti->state != TASK_STATE_ZOMBIE); disable_interrupts(&var); { task_remove_from_state_list(ti); atomic_store_explicit(&ti->state, new_state, mo_relaxed); task_add_to_state_list(ti); } enable_interrupts(&var); } void task_change_state_idempotent(struct task *ti, enum task_state new_state) { ulong var; disable_interrupts(&var); { if (atomic_load_explicit(&ti->state, mo_relaxed) != new_state) { task_change_state(ti, new_state); } } enable_interrupts(&var); } void add_task(struct task *ti) { disable_preemption(); { task_add_to_state_list(ti); bintree_insert_ptr(&tree_by_tid_root, ti, struct task, tree_by_tid_node, tid); } enable_preemption(); } void remove_task(struct task *ti) { disable_preemption(); { ASSERT_TASK_STATE(ti->state, TASK_STATE_ZOMBIE); task_remove_from_state_list(ti); bintree_remove_ptr(&tree_by_tid_root, ti, struct task, tree_by_tid_node, tid); free_task(ti); } enable_preemption(); } void sched_account_ticks(void) { struct task *curr = get_curr_task(); const enum task_state state = get_curr_task_state(); const bool is_running = (state == TASK_STATE_RUNNING); const bool is_worker = is_worker_thread(curr); struct sched_ticks *t = &curr->ticks; ASSERT(curr != NULL); ASSERT(!is_preemption_enabled()); t->timeslice++; t->total++; if (curr->running_in_kernel) t->total_kernel++; if (curr != idle_task) { /* * The more currently runnable tasks are, the higher vruntime has to * grow: if case of just 1 runnable task (+1 for idle ignored), vruntime * will increase by just +1. In case of 15 runnable tasks, vruntime will * increase by +15. The logic behind is the following: supposing all the * 15 tasks are runnable and they all start with vruntime = 0, after the * first has run, it will have vruntime = 15 * TIME_SLICE_TICKS and will * have to wait until all the other 14 tasks ran until it can be picked * again. * * Now, picking the task with the lowest vruntime will be more fair than * picking the task with the lowest `total` number of ticks, because * tasks that that consumed 100% of the CPU when no other task was * runnable won't be so much penalized. */ t->vruntime += (u64)(runnable_tasks_count - 1); } /* * need_resched is never set for worker threads when they used too much * CPU time: their timeslice is unlimited and can preempted only be another * worker thread. */ const bool timeout = !is_worker && t->timeslice >= TIME_SLICE_TICKS; if (curr->stopped || !is_running || timeout) sched_set_need_resched(); } static bool sched_should_return_immediately(struct task *curr, enum task_state curr_state) { if (UNLIKELY(in_panic())) return true; if (UNLIKELY(curr->timer_ready && curr_state != TASK_STATE_ZOMBIE)) { /* * Corner case: call to the scheduler with timer_ready set. * * This means that we called task_set_wakeup_timer(), got preempted, * the timer fired and only THEN we went to sleep. This is a perfectly * valid case. We might also have already set the state to SLEEPING. * * Because the timer handler couldn't wake this task up, as it was already * running, the right behavior is just to not going to sleep the first * time we're supposed to. That's AS IF we went to sleep as expected and * woke up very quickly after that. Just don't go to sleep at all. */ if (curr_state != TASK_STATE_RUNNING) { task_change_state(curr, TASK_STATE_RUNNING); } curr->timer_ready = false; return true; /* Give the control back to current task */ } return false; } static struct task * sched_do_select_runnable_task(enum task_state curr_state, bool resched) { struct task *curr = get_curr_task(); struct task *selected = NULL; struct task *pos; list_for_each_ro(pos, &runnable_tasks_list, runnable_node) { ASSERT_TASK_STATE(pos->state, TASK_STATE_RUNNABLE); if (pos->stopped || pos == idle_task) continue; if (pos->timer_ready) { selected = pos; break; } if (!selected || pos->ticks.vruntime < selected->ticks.vruntime) selected = pos; } /* If there is still no selected task, check for current task */ if (!selected) { if (curr_state == TASK_STATE_RUNNING && !curr->stopped) selected = curr; } if (!resched && selected) { /* * If need_resched is not set, the caller didn't want necessarily to * yield, but just give the scheduler an opportunity to switch the current * task. In the loop avoid, the current task was not included because its * state is typically RUNNING, so it's not present in the runnable_list. */ if (curr_state == TASK_STATE_RUNNING && !curr->stopped) if (curr->ticks.vruntime < selected->ticks.vruntime) selected = curr; } return selected; } void do_schedule(void) { enum task_state curr_state = get_curr_task_state(); const bool resched = need_reschedule(); struct task *curr = get_curr_task(); struct task *selected = NULL; ASSERT(!is_preemption_enabled()); /* Essential: clear the `__need_resched` flag */ sched_clear_need_resched(); /* Handle special corner cases */ if (sched_should_return_immediately(curr, curr_state)) return; /* Check for worker threads ready to run */ selected = wth_get_runnable_thread(); /* Check for regular runnable tasks */ if (!selected) { selected = sched_do_select_runnable_task(curr_state, resched); if (!selected) selected = idle_task; /* fall-back to the idle task */ } if (selected != curr) { /* Sanity check */ ASSERT(!selected->stopped); /* If we preempted the process, it is still `running` */ if (curr_state == TASK_STATE_RUNNING) task_change_state(curr, TASK_STATE_RUNNABLE); /* A task switch is required */ switch_to_task(selected); } else { if (LIKELY(!pending_signals())) { /* Just reset the current timeslice */ selected->ticks.timeslice = 0; } else { /* There are pending signals: do a complete task switch */ switch_to_task(selected); } } } struct task *get_task(int tid) { long ltid = tid; struct task *res = NULL; ASSERT(!is_preemption_enabled()); res = bintree_find_ptr(tree_by_tid_root, ltid, struct task, tree_by_tid_node, tid); return res; } struct process *get_process(int pid) { struct task *ti; ASSERT(!is_preemption_enabled()); ti = get_task(pid); if (ti && !is_kernel_thread(ti)) return ti->pi; return NULL; } bool in_currently_dying_task(void) { return get_curr_task_state() == TASK_STATE_ZOMBIE; } int send_signal_to_group(int pgid, int sig) { struct process *curr_pi = get_curr_proc(); struct process *leader = NULL; struct bintree_walk_ctx ctx; struct task *ti; int count = 0; disable_preemption(); bintree_in_order_visit_start(&ctx, tree_by_tid_root, struct task, tree_by_tid_node, false); while ((ti = bintree_in_order_visit_next(&ctx))) { struct process *pi = ti->pi; if (pi->pgid == pgid && pi != curr_pi && pi->pid != 1) { if (pi->pid != pgid) send_signal(pi->pid, sig, true); else leader = pi; count++; } } if (leader) send_signal(leader->pid, sig, true); /* kill the leader last */ enable_preemption(); if (curr_pi->pgid == pgid) { /* kill the current process, as _very_ last */ send_signal(curr_pi->pid, sig, true); count++; } return count > 0 ? 0 : -ESRCH; } int send_signal_to_session(int sid, int sig) { struct process *curr_pi = get_curr_proc(); struct process *leader = NULL; struct bintree_walk_ctx ctx; struct task *ti; int count = 0; disable_preemption(); bintree_in_order_visit_start(&ctx, tree_by_tid_root, struct task, tree_by_tid_node, false); while ((ti = bintree_in_order_visit_next(&ctx))) { struct process *pi = ti->pi; if (pi->pgid == sid && pi != curr_pi && pi->pid != 1) { if (pi->pid != sid) send_signal(pi->pid, sig, true); else leader = pi; count++; } } if (leader) send_signal(leader->pid, sig, true); /* kill the leader last */ enable_preemption(); /* kill the current process, as _very_ last */ if (curr_pi->pgid == sid) { send_signal(curr_pi->pid, sig, true); count++; } return count > 0 ? 0 : -ESRCH; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/list.h> #include <tilck/kernel/hal_types.h> /* Forward declarations */ struct process; struct user_mapping; struct fs_ops; struct locked_file; /* * Opaque type for file handles. * * The only requirement for such handles is that they must have at their * beginning all the members of fs_handle_base. Therefore, a fs_handle MUST * always be castable to fs_handle_base *. */ typedef void *fs_handle; /* Directory entry types */ enum vfs_entry_type { VFS_NONE = 0, VFS_FILE = 1, VFS_DIR = 2, VFS_SYMLINK = 3, VFS_CHAR_DEV = 4, VFS_BLOCK_DEV = 5, VFS_PIPE = 6, }; /* * VFS opaque inode pointer. * * It is the primary member the struct fs_path and it's used by functions like * (stat, fstat), (truncate, ftruncate) in order to have a common implementation * in the FS layer. */ typedef void *vfs_inode_ptr_t; #define CREATE_FS_PATH_STRUCT(name, inode_type, fs_entry_type) \ \ STATIC_ASSERT(sizeof(inode_type) == sizeof(vfs_inode_ptr_t)); \ STATIC_ASSERT(sizeof(fs_entry_type) == sizeof(void *)); \ \ struct name { \ inode_type inode; \ inode_type dir_inode; \ fs_entry_type dir_entry; \ enum vfs_entry_type type; \ } \ CREATE_FS_PATH_STRUCT(fs_path, vfs_inode_ptr_t, void *); struct vfs_path { struct mnt_fs *fs; struct fs_path fs_path; /* other fields */ const char *last_comp; }; #define VFS_FS_RW (1 << 0) /* struct mnt_fs mounted in RW mode */ #define VFS_FS_RQ_DE_SKIP (1 << 1) /* FS requires vfs dents skip */ /* This struct is Tilck's analogue of Linux's "superblock" */ struct mnt_fs { REF_COUNTED_OBJECT; struct locked_file *pss_lock_root; /* Per SubSystem lock tree root */ const char *fs_type_name; /* Statically allocated: do NOT free() */ u32 device_id; u32 flags; void *device_data; const struct fs_ops *fsops; }; /* * Each fs_handle struct should contain at its beginning the fields of the * following base struct [a rough attempt to emulate inheritance in C]. * * TODO: introduce a ref-count in the fs_base_handle struct when implementing * thread support. */ #define FS_HANDLE_BASE_FIELDS \ struct process *pi; \ struct mnt_fs *fs; \ const struct file_ops *fops; \ int fl_flags; \ u16 fd_flags; \ u16 spec_flags; \ struct locked_file *lf; \ union { \ offt h_fpos; /* file offset */ \ offt dir_pos; /* dir position */ \ }; struct fs_handle_base { FS_HANDLE_BASE_FIELDS }; #define MAX_FS_HANDLE_SIZE (32 * sizeof(void *)) /* 128 or 256 bytes */ /* File handle's special flags (spec_flags) */ #define VFS_SPFL_NO_USER_COPY (1 << 0) #define VFS_SPFL_MMAP_SUPPORTED (1 << 1) #define VFS_SPFL_NO_LF (1 << 2) /* * vfs_mmap()'s flags * * By default the mmap() function (called by vfs_mmap) is expected to both do * the actual memory-map and to register the user mapping in inode's * mappings_list (not all file-systems do that, e.g. ramfs does, fat doesn't). * For more about where the mappings_list play a role in ramfs, see the func * ramfs_unmap_past_eof_mappings(). * * However, in certain contexts, like partial un-mapping we might want to just * register the new user-mapping, without actually doing it. That's where the * VFS_MM_DONT_MMAP flag play a role. At the same way, in other exceptional * situations we might not want the FS to register the mapping, but to do it * anyway. */ #define VFS_MM_DONT_MMAP (1 << 0) #define VFS_MM_DONT_REGISTER (1 << 1) int vfs_mmap(struct user_mapping *um, pdir_t *pdir, int flags); int vfs_munmap(struct user_mapping *um, void *vaddr, size_t len); bool vfs_handle_fault(struct user_mapping *um, void *va, bool p, bool rw); int vfs_dup(fs_handle h, fs_handle *dup_h); void vfs_close(fs_handle h); fs_handle get_fs_handle(int fd); static ALWAYS_INLINE bool is_mmap_supported(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *)h; return !!(hb->spec_flags & VFS_SPFL_MMAP_SUPPORTED); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/config_kmalloc.h> #include <tilck_gen_headers/config_userlim.h> #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/mod_kb8042.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck_gen_headers/mod_serial.h> #include <tilck_gen_headers/mod_debugpanel.h> #include <tilck_gen_headers/mod_tracing.h> #include <tilck_gen_headers/mod_sysfs.h> #include <tilck_gen_headers/mod_acpi.h> #include <tilck_gen_headers/mod_pci.h> #include <tilck_gen_headers/mod_sb16.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/term.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sched.h> #include <tilck/mods/fb_console.h> #include "termutil.h" #define DUMP_LABEL(name) dp_write(row++, col, "%-16s", name) #define DUMP_INT(name, val) dp_write(row++, col, " %-16s: %d", name, val) #define DUMP_STR_OPT(opt) dp_write(row++, col, " %-30s: %s", #opt, opt) #define DUMP_INT_OPT(opt) dp_write(row++, col, " %-30s: %d", #opt, opt) #define DUMP_BOOL_OPT(opt) \ dp_write(row++, \ col, \ " %-30s: %s%u" RESET_ATTRS, \ #opt, \ opt ? E_COLOR_GREEN : DP_ESC_COLOR, \ opt) static void dp_show_opts(void) { int row = dp_screen_start_row + 1; int col = dp_start_col + 3; int rows_left; int rows_right; int max_rows; DUMP_LABEL("Main"); DUMP_STR_OPT(BUILDTYPE_STR); DUMP_INT_OPT(DEBUG_CHECKS); DUMP_INT_OPT(TIMER_HZ); DUMP_INT_OPT(KERNEL_STACK_PAGES); DUMP_INT_OPT(USER_STACK_PAGES); DUMP_LABEL("Kernel modules"); DUMP_BOOL_OPT(MOD_acpi); DUMP_BOOL_OPT(MOD_pci); DUMP_BOOL_OPT(MOD_kb8042); DUMP_BOOL_OPT(MOD_console); DUMP_BOOL_OPT(MOD_fb); DUMP_BOOL_OPT(MOD_serial); DUMP_BOOL_OPT(MOD_debugpanel); DUMP_BOOL_OPT(MOD_tracing); DUMP_BOOL_OPT(MOD_sysfs); DUMP_BOOL_OPT(MOD_sb16); DUMP_LABEL("Modules config"); DUMP_INT_OPT(FBCON_BIGFONT_THR); DUMP_BOOL_OPT(FB_CONSOLE_BANNER); DUMP_BOOL_OPT(FB_CONSOLE_CURSOR_BLINK); DUMP_BOOL_OPT(FB_CONSOLE_USE_ALT_FONTS); DUMP_BOOL_OPT(KERNEL_SHOW_LOGO); DUMP_BOOL_OPT(PCI_VENDORS_LIST); DUMP_LABEL("Enabled by default"); DUMP_BOOL_OPT(SERIAL_CON_IN_VIDEO_MODE); DUMP_BOOL_OPT(KRN_TRACK_NESTED_INTERR); DUMP_BOOL_OPT(PANIC_SHOW_STACKTRACE); DUMP_BOOL_OPT(DEBUG_CHECKS); DUMP_BOOL_OPT(KERNEL_SELFTESTS); DUMP_BOOL_OPT(KERNEL_STACK_ISOLATION); DUMP_BOOL_OPT(KERNEL_SYMBOLS); DUMP_BOOL_OPT(KRN_PRINTK_ON_CURR_TTY); DUMP_BOOL_OPT(BOOT_INTERACTIVE); DUMP_BOOL_OPT(KERNEL_64BIT_OFFT); DUMP_BOOL_OPT(KRN_CLOCK_DRIFT_COMP); DUMP_LABEL("Disabled by default"); DUMP_BOOL_OPT(KRN_NO_SYS_WARN); DUMP_BOOL_OPT(KRN_PAGE_FAULT_PRINTK); DUMP_BOOL_OPT(KERNEL_UBSAN); DUMP_BOOL_OPT(TERM_BIG_SCROLL_BUF); DUMP_BOOL_OPT(KRN_RESCHED_ENABLE_PREEMPT); DUMP_BOOL_OPT(KERNEL_BIG_IO_BUF); DUMP_BOOL_OPT(PS2_DO_SELFTEST); DUMP_BOOL_OPT(PS2_VERBOSE_DEBUG_LOG); DUMP_BOOL_OPT(KERNEL_GCOV); DUMP_BOOL_OPT(FORK_NO_COW); DUMP_BOOL_OPT(MMAP_NO_COW); DUMP_BOOL_OPT(PANIC_SHOW_REGS); DUMP_BOOL_OPT(KMALLOC_HEAVY_STATS); DUMP_BOOL_OPT(KMALLOC_FREE_MEM_POISONING); DUMP_BOOL_OPT(KMALLOC_SUPPORT_DEBUG_LOG); DUMP_BOOL_OPT(KMALLOC_SUPPORT_LEAK_DETECTOR); DUMP_BOOL_OPT(BOOTLOADER_POISON_MEMORY); DUMP_BOOL_OPT(FB_CONSOLE_FAILSAFE_OPT); DUMP_LABEL("Other"); DUMP_INT_OPT(PREFERRED_GFX_MODE_W); DUMP_INT_OPT(PREFERRED_GFX_MODE_H); rows_left = row - dp_screen_start_row - 1; row = dp_screen_start_row+1; col = dp_start_col + 48; DUMP_LABEL("Main"); DUMP_INT("HYPERVISOR", in_hypervisor()); DUMP_LABEL("Console"); { struct term_params info; process_term_read_info(&info); DUMP_INT("TERM_ROWS", info.rows); DUMP_INT("TERM_COLS", info.cols); } DUMP_INT("USE_FRAMEBUFFER", use_framebuffer()); if (MOD_fb && use_framebuffer()) { struct fb_console_info fbi; fb_console_get_info(&fbi); DUMP_INT("FB_OPT_FUNCS", fb_is_using_opt_funcs()); DUMP_INT("FB_RES_X", fbi.res_x); DUMP_INT("FB_RES_Y", fbi.res_y); DUMP_INT("FB_BPP", fbi.bpp); DUMP_INT("FB_FONT_W", fbi.font_w); DUMP_INT("FB_FONT_H", fbi.font_h); } DUMP_INT("TTY_COUNT", kopt_ttys); DUMP_LABEL("System clock"); { struct clock_resync_stats stats; clock_get_resync_stats(&stats); DUMP_INT("CLK_IN_RS", clock_in_resync()); DUMP_INT("CLK_IN_FULL_RS", clock_in_full_resync()); DUMP_INT("CLK_FULL_RS_CNT", stats.full_resync_count); DUMP_INT("CLK_FULL_RS_FAIL", stats.full_resync_fail_count); DUMP_INT("CLK_FULL_RS_SUCC", stats.full_resync_success_count); DUMP_INT("CLK_FULL_RS_ADG1", stats.full_resync_abs_drift_gt_1); DUMP_INT("CLK_RESYNC_CNT", stats.multi_second_resync_count); } rows_right = row - dp_screen_start_row - 1; max_rows = MAX(rows_left, rows_right); /* left rectangle */ dp_draw_rect("Build-time", E_COLOR_GREEN, dp_screen_start_row, dp_start_col + 1, max_rows+2, 45); /* right rectangle */ dp_draw_rect("Run-time", E_COLOR_GREEN, dp_screen_start_row, col - 2, max_rows+2, 29); } static struct dp_screen dp_opts_screen = { .index = 0, .label = "Options", .draw_func = dp_show_opts, .on_keypress_func = NULL, }; __attribute__((constructor)) static void dp_opts_init(void) { dp_register_screen(&dp_opts_screen); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/timer.h> void ksem_init(struct ksem *s, int val, int max) { ASSERT(max == KSEM_NO_MAX || max > 0); s->max = max; s->counter = val; list_init(&s->wait_list); } void ksem_destroy(struct ksem *s) { ASSERT(list_is_empty(&s->wait_list)); bzero(s, sizeof(struct ksem)); } static void ksem_do_wait(struct ksem *s, int units, int timeout_ticks) { u64 start_ticks = 0, end_ticks = 0; struct task *curr = get_curr_task(); ASSERT(!is_preemption_enabled()); if (timeout_ticks > 0) { start_ticks = get_ticks(); end_ticks = start_ticks + (u32)timeout_ticks; if (s->counter < units) task_set_wakeup_timer(curr, (u32)timeout_ticks); } else { ASSERT(timeout_ticks == KSEM_WAIT_FOREVER); } while (s->counter < units) { if (timeout_ticks > 0) { if (get_ticks() >= end_ticks) break; } prepare_to_wait_on(WOBJ_SEM, s, (u32)units, &s->wait_list); /* won't wakeup by a signal here, see signal.c */ enter_sleep_wait_state(); /* here the preemption is guaranteed to be enabled */ disable_preemption(); } if (timeout_ticks > 0) task_cancel_wakeup_timer(curr); } int ksem_wait(struct ksem *s, int units, int timeout_ticks) { int rc = -ETIME; ASSERT(units > 0); if (s->max != KSEM_NO_MAX) { if (units > s->max) return -EINVAL; } disable_preemption(); { if (timeout_ticks != KSEM_NO_WAIT) ksem_do_wait(s, units, timeout_ticks); if (s->counter >= units) { s->counter -= units; rc = 0; } } enable_preemption(); return rc; } int ksem_signal(struct ksem *s, int units) { struct wait_obj *wo, *tmp; int rem_counter, rc = 0; ASSERT(units > 0); disable_preemption(); if (s->max != KSEM_NO_MAX) { if (units > s->max) { rc = -EINVAL; goto out; } if (s->counter > s->max - units) { /* * NOTE: `s->counter + units > s->max` got re-written to avoid integer * wrap-around. */ rc = -EDQUOT; goto out; } } s->counter += units; rem_counter = s->counter; list_for_each(wo, tmp, &s->wait_list, wait_list_node) { if (rem_counter <= 0) break; /* not enough units to unblock anybody */ int wait_units = (int)wo->extra; ASSERT(wo->type == WOBJ_SEM); ASSERT(wait_units > 0); if (wait_units <= rem_counter) { struct task *ti = CONTAINER_OF(wo, struct task, wobj); rem_counter -= wait_units; wake_up(ti); } } out: enable_preemption(); return rc; } <file_sep>/****************************************************************************** * * Module Name: psopinfo - AML opcode information functions and dispatch tables * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "acopcode.h" #include "amlcode.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psopinfo") static const UINT8 AcpiGbl_ArgumentCount[] = {0,1,1,1,1,2,2,2,2,3,3,6}; /******************************************************************************* * * FUNCTION: AcpiPsGetOpcodeInfo * * PARAMETERS: Opcode - The AML opcode * * RETURN: A pointer to the info about the opcode. * * DESCRIPTION: Find AML opcode description based on the opcode. * NOTE: This procedure must ALWAYS return a valid pointer! * ******************************************************************************/ const ACPI_OPCODE_INFO * AcpiPsGetOpcodeInfo ( UINT16 Opcode) { #ifdef ACPI_DEBUG_OUTPUT const char *OpcodeName = "Unknown AML opcode"; #endif ACPI_FUNCTION_NAME (PsGetOpcodeInfo); /* * Detect normal 8-bit opcode or extended 16-bit opcode */ if (!(Opcode & 0xFF00)) { /* Simple (8-bit) opcode: 0-255, can't index beyond table */ return (&AcpiGbl_AmlOpInfo [AcpiGbl_ShortOpIndex [(UINT8) Opcode]]); } if (((Opcode & 0xFF00) == AML_EXTENDED_OPCODE) && (((UINT8) Opcode) <= MAX_EXTENDED_OPCODE)) { /* Valid extended (16-bit) opcode */ return (&AcpiGbl_AmlOpInfo [AcpiGbl_LongOpIndex [(UINT8) Opcode]]); } #if defined ACPI_ASL_COMPILER && defined ACPI_DEBUG_OUTPUT #include "asldefine.h" switch (Opcode) { case AML_RAW_DATA_BYTE: OpcodeName = "-Raw Data Byte-"; break; case AML_RAW_DATA_WORD: OpcodeName = "-Raw Data Word-"; break; case AML_RAW_DATA_DWORD: OpcodeName = "-Raw Data Dword-"; break; case AML_RAW_DATA_QWORD: OpcodeName = "-Raw Data Qword-"; break; case AML_RAW_DATA_BUFFER: OpcodeName = "-Raw Data Buffer-"; break; case AML_RAW_DATA_CHAIN: OpcodeName = "-Raw Data Buffer Chain-"; break; case AML_PACKAGE_LENGTH: OpcodeName = "-Package Length-"; break; case AML_UNASSIGNED_OPCODE: OpcodeName = "-Unassigned Opcode-"; break; case AML_DEFAULT_ARG_OP: OpcodeName = "-Default Arg-"; break; default: break; } #endif /* Unknown AML opcode */ ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%s [%4.4X]\n", OpcodeName, Opcode)); return (&AcpiGbl_AmlOpInfo [_UNK]); } /******************************************************************************* * * FUNCTION: AcpiPsGetOpcodeName * * PARAMETERS: Opcode - The AML opcode * * RETURN: A pointer to the name of the opcode (ASCII String) * Note: Never returns NULL. * * DESCRIPTION: Translate an opcode into a human-readable string * ******************************************************************************/ const char * AcpiPsGetOpcodeName ( UINT16 Opcode) { #if defined(ACPI_DISASSEMBLER) || defined (ACPI_DEBUG_OUTPUT) const ACPI_OPCODE_INFO *Op; Op = AcpiPsGetOpcodeInfo (Opcode); /* Always guaranteed to return a valid pointer */ return (Op->Name); #else return ("OpcodeName unavailable"); #endif } /******************************************************************************* * * FUNCTION: AcpiPsGetArgumentCount * * PARAMETERS: OpType - Type associated with the AML opcode * * RETURN: Argument count * * DESCRIPTION: Obtain the number of expected arguments for an AML opcode * ******************************************************************************/ UINT8 AcpiPsGetArgumentCount ( UINT32 OpType) { if (OpType <= AML_TYPE_EXEC_6A_0T_1R) { return (AcpiGbl_ArgumentCount[OpType]); } return (0); } /* * This table is directly indexed by the opcodes It returns * an index into the opcode table (AcpiGbl_AmlOpInfo) */ const UINT8 AcpiGbl_ShortOpIndex[256] = { /* 0 1 2 3 4 5 6 7 */ /* 8 9 A B C D E F */ /* 0x00 */ 0x00, 0x01, _UNK, _UNK, _UNK, _UNK, 0x02, _UNK, /* 0x08 */ 0x03, _UNK, 0x04, 0x05, 0x06, 0x07, 0x6E, _UNK, /* 0x10 */ 0x08, 0x09, 0x0a, 0x6F, 0x0b, 0x81, _UNK, _UNK, /* 0x18 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x20 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x28 */ _UNK, _UNK, _UNK, _UNK, _UNK, 0x63, _PFX, _PFX, /* 0x30 */ 0x67, 0x66, 0x68, 0x65, 0x69, 0x64, 0x6A, 0x7D, /* 0x38 */ 0x7F, 0x80, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x40 */ _UNK, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, /* 0x48 */ _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, /* 0x50 */ _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, /* 0x58 */ _ASC, _ASC, _ASC, _UNK, _PFX, _UNK, _PFX, _ASC, /* 0x60 */ 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, /* 0x68 */ 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, _UNK, /* 0x70 */ 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, /* 0x78 */ 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, /* 0x80 */ 0x2b, 0x2c, 0x2d, 0x2e, 0x70, 0x71, 0x2f, 0x30, /* 0x88 */ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x72, /* 0x90 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x73, 0x74, /* 0x98 */ 0x75, 0x76, _UNK, _UNK, 0x77, 0x78, 0x79, 0x7A, /* 0xA0 */ 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x60, 0x61, /* 0xA8 */ 0x62, 0x82, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xB0 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xB8 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xC0 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xC8 */ _UNK, _UNK, _UNK, _UNK, 0x44, _UNK, _UNK, _UNK, /* 0xD0 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xD8 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xE0 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xE8 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xF0 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0xF8 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, 0x45, }; /* * This table is indexed by the second opcode of the extended opcode * pair. It returns an index into the opcode table (AcpiGbl_AmlOpInfo) */ const UINT8 AcpiGbl_LongOpIndex[NUM_EXTENDED_OPCODE] = { /* 0 1 2 3 4 5 6 7 */ /* 8 9 A B C D E F */ /* 0x00 */ _UNK, 0x46, 0x47, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x08 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x10 */ _UNK, _UNK, 0x48, 0x49, _UNK, _UNK, _UNK, _UNK, /* 0x18 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, 0x7B, /* 0x20 */ 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, /* 0x28 */ 0x52, 0x53, 0x54, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x30 */ 0x55, 0x56, 0x57, 0x7e, _UNK, _UNK, _UNK, _UNK, /* 0x38 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x40 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x48 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x50 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x58 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x60 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x68 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x70 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x78 */ _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, /* 0x80 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x88 */ 0x7C, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <3rd_party/bithacks.h> CONSTEXPR static ALWAYS_INLINE ulong pow2_round_up_at(ulong n, ulong pow2unit) { return (n + pow2unit - 1) & -pow2unit; } CONSTEXPR static ALWAYS_INLINE u64 pow2_round_up_at64(u64 n, u64 pow2unit) { return (n + pow2unit - 1) & -pow2unit; } CONSTEXPR static ALWAYS_INLINE ulong div_round_up(ulong n, ulong unit) { return ((n + unit - 1) / unit); } CONSTEXPR static ALWAYS_INLINE u64 div_round_up64(u64 n, u64 unit) { return ((n + unit - 1) / unit); } CONSTEXPR static ALWAYS_INLINE ulong round_up_at(ulong n, ulong unit) { return div_round_up(n, unit) * unit; } CONSTEXPR static ALWAYS_INLINE u64 round_up_at64(u64 n, u64 unit) { return div_round_up64(n, unit) * unit; } CONSTEXPR static ALWAYS_INLINE ulong round_down_at(ulong n, ulong unit) { return (n / unit) * unit; } CONSTEXPR static ALWAYS_INLINE u64 round_down_at64(u64 n, u64 unit) { return (n / unit) * unit; } CONSTEXPR static ALWAYS_INLINE ulong make_bitmask(ulong width) { ulong w = (sizeof(ulong) * 8) - width; return (((ulong)-1) << w) >> w; } CONSTEXPR static inline u32 get_first_zero_bit_index32(u32 num) { u32 i; ASSERT(num != ~0U); for (i = 0; i < 32; i++) if ((num & (1U << i)) == 0) break; return i; } CONSTEXPR static inline u32 get_first_set_bit_index32(u32 num) { u32 i; ASSERT(num != 0); for (i = 0; i < 32; i++) if (num & (1U << i)) break; return i; } CONSTEXPR static inline u32 get_first_zero_bit_index64(u64 num) { u32 i; ASSERT(num != ~0U); for (i = 0; i < 64; i++) if ((num & (1ull << i)) == 0) break; return i; } CONSTEXPR static inline u32 get_first_set_bit_index64(u64 num) { u32 i; ASSERT(num != 0); for (i = 0; i < 64; i++) if (num & (1ull << i)) break; return i; } CONSTEXPR static inline u32 get_first_zero_bit_index_l(ulong num) { u32 i; ASSERT(num != ~0U); for (i = 0; i < NBITS; i++) if ((num & (1UL << i)) == 0) break; return i; } CONSTEXPR static inline u32 get_first_set_bit_index_l(ulong num) { u32 i; ASSERT(num != 0); for (i = 0; i < NBITS; i++) if (num & (1UL << i)) break; return i; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_sysfs.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/mods/acpi.h> #include <tilck/mods/sysfs.h> #include <tilck/mods/sysfs_utils.h> #include "acpi_int.h" #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> #include <3rd_party/acpi/acinterp.h> #if MOD_sysfs #define PROP_NAME_BUF_SZ 32 #define ACPI_SERIALIZE_MAX_DEPTH 3 typedef offt (*acpi_serialize_func)(ACPI_OBJECT *, char *, offt, int); static struct sysobj *dir_acpi_root; /* /sysfs/acpi */ static const char *acpi_types_str[ACPI_NUM_TYPES] = { [ACPI_TYPE_ANY] = "unknown", [ACPI_TYPE_INTEGER] = "integer", [ACPI_TYPE_STRING] = "string", [ACPI_TYPE_BUFFER] = "buffer", [ACPI_TYPE_PACKAGE] = "package", [ACPI_TYPE_FIELD_UNIT] = "field_unit", [ACPI_TYPE_DEVICE] = "device", [ACPI_TYPE_EVENT] = "event", [ACPI_TYPE_METHOD] = "method", [ACPI_TYPE_MUTEX] = "mutex", [ACPI_TYPE_REGION] = "region", [ACPI_TYPE_POWER] = "power", [ACPI_TYPE_PROCESSOR] = "processor", [ACPI_TYPE_THERMAL] = "thermal", [ACPI_TYPE_BUFFER_FIELD] = "buffer_field", [ACPI_TYPE_DDB_HANDLE] = "ddb_handle", [ACPI_TYPE_DEBUG_OBJECT] = "debug_object", }; static offt acpi_serialize_obj(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth); static offt acpi_serialize_hex(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { if (val->Type != ACPI_TYPE_INTEGER) return 0; return snprintk(buf, buf_sz, "%*s%s%#" PRIx64 "\n", depth * 2, "", depth ? "- " : "", val->Integer.Value); } static offt acpi_serialize_ul_raw(u64 val, char *buf, offt buf_sz, int depth) { return snprintk(buf, buf_sz, "%*s%s%" PRIu64 "\n", depth * 2, "", depth ? "- " : "", val); } static offt acpi_serialize_ul(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { return acpi_serialize_ul_raw(val->Integer.Value, buf, buf_sz, depth); } static offt acpi_serialize_long_raw(u64 val, char *buf, offt buf_sz, int depth) { return snprintk(buf, buf_sz, "%*s%s%" PRId64 "\n", depth * 2, "", depth ? "- " : "", val); } static offt acpi_serialize_long(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { return acpi_serialize_long_raw(val->Integer.Value, buf, buf_sz, depth); } static offt acpi_serialize_eisaid(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { char tmpbuf[ACPI_EISAID_STRING_SIZE]; AcpiExEisaIdToString(tmpbuf, val->Integer.Value); return snprintk(buf, buf_sz, "%s\n", tmpbuf); } static offt acpi_serialize_str(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { return snprintk(buf, buf_sz, "%*s%s%s\n", depth * 2, "", depth ? "- " : "", val->String.Pointer); } static offt acpi_serialize_buf(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { return snprintk(buf, buf_sz, "%*s%s<buffer[%u]>\n", depth * 2, "", depth ? "- " : "", val->Buffer.Length); } static offt acpi_serialize_unknown(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { const char *type = "unknown"; if (val->Type < ACPI_NUM_TYPES) type = acpi_types_str[val->Type]; return snprintk(buf, buf_sz, "%*s%s<%s>\n", depth * 2, "", depth ? "- " : "", type); } static offt acpi_serialize_pkg(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { offt rc, written = 0; if (depth < ACPI_SERIALIZE_MAX_DEPTH) { rc = snprintk(buf + written, buf_sz - written, "%*s%sPackage:\n", depth * 2, "", depth ? "- " : ""); } else { rc = snprintk(buf + written, buf_sz - written, "%*s- <package>\n", depth * 2, ""); return rc; } if (rc <= 0) return written; written += rc; for (u32 i = 0; i < val->Package.Count; i++) { rc = acpi_serialize_obj(&val->Package.Elements[i], buf + written, buf_sz - written, depth + 1); if (rc <= 0) break; written += rc; } return written; } static offt acpi_serialize_obj(ACPI_OBJECT *val, char *buf, offt buf_sz, int depth) { static const acpi_serialize_func ser_funcs[ACPI_NUM_TYPES] = { [ACPI_TYPE_INTEGER] = &acpi_serialize_hex, [ACPI_TYPE_STRING] = &acpi_serialize_str, [ACPI_TYPE_BUFFER] = &acpi_serialize_buf, [ACPI_TYPE_PACKAGE] = &acpi_serialize_pkg, }; acpi_serialize_func func = &acpi_serialize_unknown; if (val->Type < ACPI_NUM_TYPES && ser_funcs[val->Type]) func = ser_funcs[val->Type]; return func(val, buf, buf_sz, depth); } static offt gen_data_load_handle_pidx(ACPI_OBJECT *val, int pidx, int bitx, char fmt, void *buf, offt buf_sz) { offt len = 0; if (pidx >= 0) { if (val->Type != ACPI_TYPE_PACKAGE || (u32)pidx >= val->Package.Count) return 0; /* Not a package: cannot get value at index `pdix` */ /* Read the element at index `pdix` */ val = &val->Package.Elements[pidx]; } if (bitx >= 0) { if (val->Type == ACPI_TYPE_INTEGER) { len = acpi_serialize_ul_raw( !!(val->Integer.Value & (1 << bitx)), buf, buf_sz, 0 ); } } else { switch (fmt) { case 0: /* no fmt */ if (val->Type == ACPI_TYPE_INTEGER) len = acpi_serialize_obj(val, buf, buf_sz, 0); break; case 'u': /* unsigned integer (base 10) */ if (val->Type == ACPI_TYPE_INTEGER) len = acpi_serialize_ul(val, buf, buf_sz, 0); break; case 'x': /* unsigned integer (base 16) */ if (val->Type == ACPI_TYPE_INTEGER) len = acpi_serialize_hex(val, buf, buf_sz, 0); break; case 'd': /* signed integer (base 10) */ if (val->Type == ACPI_TYPE_INTEGER) len = acpi_serialize_long(val, buf, buf_sz, 0); break; case 'E': /* EISAID (ACPI HID in integer compressed form) */ if (val->Type == ACPI_TYPE_INTEGER) len = acpi_serialize_eisaid(val, buf, buf_sz, 0); break; case 's': /* NUL-terminated string */ if (val->Type == ACPI_TYPE_STRING) len = acpi_serialize_str(val, buf, buf_sz, 0); break; default: NOT_REACHED(); /* unknown fmt */ } } return len; } static offt acpi_generic_data_load(struct sysobj *s_obj, void *child_expr, void *buf, offt buf_sz, offt off) { ACPI_HANDLE obj_handle = s_obj->extra; char child_buf[16] = {0}; char *child = NULL; ACPI_OBJECT *val; ACPI_BUFFER res; int pidx = -1; int bitx = -1; offt len = 0; char fmt = 0; res.Length = ACPI_ALLOCATE_BUFFER; res.Pointer = NULL; if (child_expr && ((char *)child_expr)[0] != ':') { strncpy(child_buf, child_expr, sizeof(child_buf) - 1); child = child_buf; if (child[4] == '/') { const char *endptr; pidx = (int)tilck_strtoul(child + 5, &endptr, 10, NULL); if (*endptr) { /* There are non-numeric characters after the prop. index */ if (*endptr == ':') /* bitfield */ bitx = (int)tilck_strtoul(endptr + 1, NULL, 10, NULL); else fmt = *endptr; /* any other format char */ } child[4] = 0; } } else if (child_expr && ((char *)child_expr)[0] == ':') { fmt = ((char *)child_expr)[1]; } if (ACPI_SUCCESS(AcpiEvaluateObject(obj_handle, child, NULL, &res))) { val = res.Pointer; if (pidx >= 0 || fmt) len = gen_data_load_handle_pidx(val, pidx, bitx, fmt, buf, buf_sz); else len = acpi_serialize_obj(val, buf, buf_sz, 0); ACPI_FREE(res.Pointer); } return len; } static offt acpi_prop_methods_load(struct sysobj *s_obj, void *child_name, void *buf, offt buf_sz, offt off) { ACPI_HANDLE obj_handle = s_obj->extra; ACPI_HANDLE child = NULL; ACPI_STATUS rc; ACPI_BUFFER retbuf; offt written = 0; char name[8]; int len; retbuf.Length = sizeof(name); retbuf.Pointer = name; while (true) { rc = AcpiGetNextObject(ACPI_TYPE_METHOD, obj_handle, child, &child); if (ACPI_FAILURE(rc)) break; bzero(name, sizeof(name)); if (ACPI_FAILURE(AcpiGetName(child, ACPI_SINGLE_NAME, &retbuf))) break; len = snprintk(buf + written, buf_sz - written, "%s ", name); if (len <= 0) break; written += len; } if (written > 0) written--; /* drop the trailing space */ len = snprintk(buf + written, buf_sz - written, "\n"); if (len > 0) written += len; return written; } /* Property types */ static struct sysobj_prop_type acpi_prop_type_generic_ro = { .load = &acpi_generic_data_load }; static struct sysobj_prop_type acpi_prop_type_methods_ro = { .load = &acpi_prop_methods_load }; /* Properties */ DEF_STATIC_SYSOBJ_PROP(type, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(value, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(methods, &acpi_prop_type_methods_ro); DEF_STATIC_SYSOBJ_PROP(device_type, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(power_unit, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(design_capacity, &sysobj_ptype_ro_ulong_literal); DEF_STATIC_SYSOBJ_PROP(capacity, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(rem_capacity, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(discharging, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(charging, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(critical_level, &acpi_prop_type_generic_ro); DEF_STATIC_SYSOBJ_PROP(present_rate, &acpi_prop_type_generic_ro); /* Sysfs obj types */ DEF_STATIC_SYSOBJ_TYPE(acpi_basic_sysobj_type, &prop_type, &prop_methods, NULL); DEF_STATIC_SYSOBJ_TYPE(acpi_data_sysobj_type, &prop_type, &prop_value, NULL); DEF_STATIC_SYSOBJ_TYPE(acpi_device_sysobj_type, &prop_type, &prop_methods, NULL); DEF_STATIC_SYSOBJ_TYPE(acpi_battery_sysobj_type, &prop_type, &prop_methods, &prop_device_type, &prop_power_unit, &prop_design_capacity, &prop_capacity, &prop_rem_capacity, &prop_discharging, &prop_charging, &prop_critical_level, &prop_present_rate, NULL); static void acpi_sysobj_data_dtor(ACPI_HANDLE obj, void *ctx) { struct sysobj *s_obj = ctx; ASSERT(s_obj->extra == obj); s_obj->extra = NULL; } struct create_acpi_sys_obj_ctx { ACPI_HANDLE obj; ACPI_OBJECT_TYPE type; union { const char *name; const u32 *name_int; }; const char *type_str; struct sysobj *view_dest_obj; }; static struct sysobj * create_ctrl_battery_sys_obj(struct create_acpi_sys_obj_ctx *ctx) { const char *lfc_cap = "_BIF/2u"; /* last full charge capacity */ const char *pu = ""; ulong design_cap = 0xffffffff; /* unknown */ struct basic_battery_info bi; if (ACPI_SUCCESS(acpi_battery_get_basic_info(ctx->obj, &bi))) { pu = bi.power_unit; if (bi.has_BIX) lfc_cap = "_BIX/3u"; design_cap = bi.design_cap; } ctx->view_dest_obj = &sysfs_power_obj; return sysfs_create_obj(&acpi_battery_sysobj_type, NULL, /* hooks */ ctx->type_str, /* `type` */ NULL, /* `methods` */ "battery", /* `device_type` */ pu, /* `power_unit` */ TO_PTR(design_cap), /* `design_capacity` */ lfc_cap, /* `capacity` */ "_BST/2u", /* `rem_capacity` */ "_BST/0:0", /* `discharging` */ "_BST/0:1", /* `charging` */ "_BST/0:2", /* `critical_level` */ "_BST/1u"); /* `present_rate` */ } static struct sysobj * create_acpi_device_sys_obj(struct create_acpi_sys_obj_ctx *ctx) { if (acpi_is_battery(ctx->obj)) { /* We found a `Control Method Battery` device */ return create_ctrl_battery_sys_obj(ctx); } /* Generic device */ return sysfs_create_obj(&acpi_device_sysobj_type, NULL, /* hooks */ ctx->type_str, /* data for `type` */ NULL); /* data for `methods` */ } static struct sysobj * create_acpi_sys_obj(struct create_acpi_sys_obj_ctx *ctx) { struct sysobj *s_obj = NULL; const char *child_expr = NULL; const char *type_str = ctx->type_str; switch (ctx->type) { case ACPI_TYPE_INTEGER: if (*ctx->name_int == READ_U32("_HID") || *ctx->name_int == READ_U32("_CID")) { child_expr = ":E"; type_str = "EISAID"; } /* fall-through */ case ACPI_TYPE_STRING: /* fall-through */ case ACPI_TYPE_BUFFER: /* fall-through */ case ACPI_TYPE_PACKAGE: s_obj = sysfs_create_obj(&acpi_data_sysobj_type, NULL, /* hooks */ type_str, /* data for `type` */ child_expr); /* data for `value` */ break; case ACPI_TYPE_DEVICE: s_obj = create_acpi_device_sys_obj(ctx); break; default: s_obj = sysfs_create_obj(&acpi_basic_sysobj_type, NULL, /* hooks */ type_str, /* data for `type` */ NULL); /* data for `methods` */ } if (s_obj) s_obj->extra = ctx->obj; return s_obj; } static bool should_skip_obj(ACPI_HANDLE parent, ACPI_HANDLE obj, ACPI_DEVICE_INFO *info) { if (info->Type == ACPI_TYPE_METHOD) return true; return false; } ACPI_STATUS register_acpi_obj_in_sysfs(ACPI_HANDLE parent_obj, ACPI_HANDLE obj, ACPI_DEVICE_INFO *obj_info) { struct create_acpi_sys_obj_ctx ctx = {0}; struct sysobj *s_parent = NULL; struct sysobj *s_obj; char name[8] = {0}; ACPI_STATUS rc; if (parent_obj) { void *ptr; rc = AcpiGetData(parent_obj, &acpi_sysobj_data_dtor, &ptr); if (ACPI_SUCCESS(rc)) s_parent = ptr; } if (obj) { ASSERT(obj_info); if (should_skip_obj(parent_obj, obj, obj_info)) return AE_OK; memcpy(name, &obj_info->Name, sizeof(obj_info->Name)); if (!s_parent) s_parent = dir_acpi_root; rc = AcpiGetData(obj, &acpi_sysobj_data_dtor, (void **)&s_obj); if (ACPI_SUCCESS(rc)) { /* * The `obj` handle points an ACPI_OPERAND_OBJECT we already travered * before, using another ACPI_NAMESPACE_NODE as handle. Therefore, we * already have a sysobj for this NS node: we need just a link. */ if (sysfs_symlink_obj(NULL, s_parent, name, s_obj) < 0) return AE_NO_MEMORY; return AE_OK; } ctx.obj = obj; ctx.type = obj_info->Type; ctx.name = name; ctx.type_str = acpi_types_str[ACPI_TYPE_ANY]; if (ctx.type < ARRAY_SIZE(acpi_types_str)) ctx.type_str = acpi_types_str[ctx.type]; s_obj = create_acpi_sys_obj(&ctx); if (!s_obj) return AE_NO_MEMORY; rc = AcpiAttachData(obj, &acpi_sysobj_data_dtor, s_obj); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiAttachData", NULL, rc); sysfs_destroy_unregistered_obj(s_obj); return rc; } } else { ASSERT(!dir_acpi_root); dir_acpi_root = sysfs_create_empty_obj(); if (!dir_acpi_root) return AE_NO_MEMORY; s_obj = dir_acpi_root; s_parent = &sysfs_root_obj; strcpy(name, "acpi"); } if (name[3] == '_') { /* * Internally, ACPI objects with names shorter than 4 chars use a trailing * underscore character '_' to keep the length fixed, for example "_SB" * becomes "_SB_" and "EC0" become "EC0_". Since in the ACPI spec and in * the full paths generated by ACPICA the underscore is dropped, it is * worth dropping it from our view as well. */ name[3] = 0; } if (sysfs_register_obj(NULL, s_parent, name, s_obj) < 0) { if (obj) { AcpiDetachData(obj, &acpi_sysobj_data_dtor); sysfs_destroy_unregistered_obj(s_obj); } return AE_NO_MEMORY; } if (ctx.view_dest_obj) sysfs_symlink_obj(NULL, ctx.view_dest_obj, name, s_obj); return AE_OK; } #else ACPI_STATUS register_acpi_obj_in_sysfs(ACPI_HANDLE parent_obj, ACPI_HANDLE obj, ACPI_DEVICE_INFO *obj_info) { return AE_OK; } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/mods/sysfs_utils.h> #define DEF_STATIC_SYSOBJ_TYPE(_name, ...) \ \ static struct sysobj_prop *_name##_prop_list[] = { __VA_ARGS__ }; \ static struct sysobj_type _name = { \ .name = #_name, \ .properties = _name##_prop_list \ } #define DEF_STATIC_SYSOBJ(_name, _type, _hooks,...) \ \ static void *_name##_data[] = { __VA_ARGS__ }; \ static struct sysobj _name = { \ .node = STATIC_LIST_NODE_INIT(_name.node), \ .children_list = STATIC_LIST_INIT(_name.children_list), \ .type = _type, \ .hooks = _hooks, \ .prop_data = _name##_data, \ } #define DEF_SHARED_EMPTY_SYSOBJ(_name) \ \ struct sysobj _name = { \ .node = STATIC_LIST_NODE_INIT(_name.node), \ .children_list = STATIC_LIST_INIT(_name.children_list), \ } #define DEF_STATIC_SYSOBJ_PROP(_name, _type) \ static struct sysobj_prop prop_##_name = { \ .name = #_name, \ .type = _type \ } #define DEF_STATIC_SYSOBJ_PROP2(_var_name, _prop_name, _type) \ static struct sysobj_prop _var_name = { \ .name = #_prop_name, \ .type = _type \ } #define RO_STR_BUF_INIT(_value) \ { \ .buf = (char *)_value, \ .buf_sz = sizeof(_value) \ } #define DEF_STATIC_RO_STR_BUF(_name, _value) \ static struct sysfs_buffer _name = RO_STR_BUF_INIT(_value) #define DEF_STATIC_CONF_RW_STRING(_name, _value, _max_len) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_rw_config_str); \ \ static char _name##_buf[_max_len] = _value; \ static struct sysfs_buffer conf_##_name = { \ .buf = _name##_buf, \ .buf_sz = _max_len \ } #define DEF_STATIC_CONF_RO_STRING(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_ro_config_str); \ DEF_STATIC_RO_STR_BUF(conf_##_name, _value) #define DEF_STATIC_CONF_RO_LONG(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_ro_long); \ static long conf_##_name = _value #define DEF_STATIC_CONF_RW_LONG(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_rw_long); \ static long conf_##_name = _value #define DEF_STATIC_CONF_RO_ULONG(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_ro_ulong); \ static ulong conf_##_name = _value #define DEF_STATIC_CONF_RW_ULONG(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_rw_ulong); \ static ulong conf_##_name = _value #define DEF_STATIC_CONF_RO_BOOL(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_ro_bool); \ static bool conf_##_name = _value #define DEF_STATIC_CONF_RW_BOOL(_name, _value) \ \ DEF_STATIC_SYSOBJ_PROP(_name, &sysobj_ptype_rw_bool); \ static bool conf_##_name = _value #define DEF_STATIC_CONF_RO(__type, __name, __value, ...) \ CONCAT(DEF_STATIC_CONF_RO_,__type)(__name, __value, ##__VA_ARGS__) #define DEF_STATIC_CONF_RW(__type, __name, __value, ...) \ CONCAT(DEF_STATIC_CONF_RW_,__type)(__name, __value, ##__VA_ARGS__) #define SYSOBJ_CONF_PROP_PAIR(name) \ &prop_##name, &conf_##name /* Common property types */ struct sysfs_buffer { char *buf; u32 buf_sz; u32 used; }; extern const struct sysobj_prop_type sysobj_ptype_ro_string_literal; extern const struct sysobj_prop_type sysobj_ptype_ro_ulong_literal; extern const struct sysobj_prop_type sysobj_ptype_ro_ulong_hex_literal; extern const struct sysobj_prop_type sysobj_ptype_ulong; extern const struct sysobj_prop_type sysobj_ptype_ro_ulong; extern const struct sysobj_prop_type sysobj_ptype_long; extern const struct sysobj_prop_type sysobj_ptype_ro_long; extern const struct sysobj_prop_type sysobj_ptype_rw_bool; extern const struct sysobj_prop_type sysobj_ptype_ro_bool; extern const struct sysobj_prop_type sysobj_ptype_rw_config_str; extern const struct sysobj_prop_type sysobj_ptype_ro_config_str; extern const struct sysobj_prop_type sysobj_ptype_imm_data; extern const struct sysobj_prop_type sysobj_ptype_databuf; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/atomics.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> void wait_obj_set(struct wait_obj *wo, enum wo_type type, void *ptr, u32 extra, struct list *wait_list) { atomic_store_explicit(&wo->__ptr, ptr, mo_relaxed); disable_preemption(); { ASSERT(list_node_is_null(&wo->wait_list_node) || list_node_is_empty(&wo->wait_list_node)); wo->type = type; wo->extra = extra; list_node_init(&wo->wait_list_node); if (wait_list) list_add_tail(wait_list, &wo->wait_list_node); } enable_preemption(); } void *wait_obj_reset(struct wait_obj *wo) { void *oldp = atomic_exchange_explicit(&wo->__ptr, NULL, mo_relaxed); disable_preemption(); { if (oldp) { wo->type = WOBJ_NONE; if (list_is_node_in_list(&wo->wait_list_node)) list_remove(&wo->wait_list_node); list_node_init(&wo->wait_list_node); } else { ASSERT(wo->type == WOBJ_NONE); } } enable_preemption(); return oldp; } void prepare_to_wait_on(enum wo_type type, void *ptr, u32 extra, struct list *wait_list) { struct task *ti = get_curr_task(); ASSERT(!is_preemption_enabled()); if (UNLIKELY(in_panic())) { /* * Just set the wait object, don't change task's state. * See the comments in kcond_wait() for more context about that. */ wait_obj_set(&ti->wobj, type, ptr, extra, wait_list); return; } ASSERT(ti->state != TASK_STATE_SLEEPING); wait_obj_set(&ti->wobj, type, ptr, extra, wait_list); task_change_state(ti, TASK_STATE_SLEEPING); } void *wake_up(struct task *ti) { void *oldp; disable_preemption(); { oldp = wait_obj_reset(&ti->wobj); if (ti != get_curr_task()) { /* * TODO: if SMP will be ever introduced, here we should call a * function that does NOT "downgrade" a task from RUNNING to RUNNABLE. * Until then, checking that ti != current is enough. */ task_change_state_idempotent(ti, TASK_STATE_RUNNABLE); } } enable_preemption(); return oldp; } /* Multi wait obj stuff */ struct multi_obj_waiter *allocate_mobj_waiter(int elems) { size_t s = sizeof(struct multi_obj_waiter) + sizeof(struct mwobj_elem) * (u32)elems; struct multi_obj_waiter *w = task_temp_kernel_alloc(s); if (!w) return NULL; bzero(w, s); w->count = elems; return w; } void free_mobj_waiter(struct multi_obj_waiter *w) { if (!w) return; for (int i = 0; i < w->count; i++) { mobj_waiter_reset2(w, i); } task_temp_kernel_free(w); } void mobj_waiter_set(struct multi_obj_waiter *w, int index, enum wo_type type, void *ptr, struct list *wait_list) { /* * No chaining is allowed: the waited object pointed by `ptr` is expected to * be a regular (waitable) object like kcond. */ ASSERT(type != WOBJ_MWO_WAITER && type != WOBJ_MWO_ELEM); struct mwobj_elem *e = &w->elems[index]; wait_obj_set(&e->wobj, WOBJ_MWO_ELEM, ptr, NO_EXTRA, wait_list); e->ti = get_curr_task(); e->type = type; } void mobj_waiter_reset(struct mwobj_elem *e) { wait_obj_reset(&e->wobj); e->ti = NULL; e->type = WOBJ_NONE; } void mobj_waiter_reset2(struct multi_obj_waiter *w, int index) { struct mwobj_elem *e = &w->elems[index]; mobj_waiter_reset(e); } void prepare_to_wait_on_multi_obj(struct multi_obj_waiter *w) { prepare_to_wait_on(WOBJ_MWO_WAITER, w, NO_EXTRA, NULL); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/modules_list.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/compiler.h> #include <tilck/common/build_info.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/term.h> char zero_page[PAGE_SIZE] ALIGNED_AT(PAGE_SIZE); #if KERNEL_SYMBOLS char symtab_buf[SYMTAB_MAX_SIZE] ATTR_SECTION(".Symtab") = {0}; char strtab_buf[STRTAB_MAX_SIZE] ATTR_SECTION(".Strtab") = {0}; #else char symtab_buf[1] ATTR_SECTION(".Symtab") = {0}; char strtab_buf[1] ATTR_SECTION(".Strtab") = {0}; #endif bool __use_framebuffer; #if DEBUG_CHECKS const ulong init_st_begin = (ulong)&kernel_initial_stack; const ulong init_st_end = (ulong)&kernel_initial_stack + KERNEL_STACK_SIZE; #endif #ifdef KERNEL_SHOW_LOGO static void print_banner_line(const u8 *s) { printk(NO_PREFIX "\033(0"); for (const u8 *p = s; *p; p++) { printk(NO_PREFIX "%c", *p); } printk(NO_PREFIX "\033(B"); printk(NO_PREFIX "\n"); } static void show_tilck_logo(void) { char *banner[] = { "", "aaaaaaaak aak aak aaaaaak aak aak", "mqqaalqqj aax aax aalqqqqj aax aalj", " aax aax aax aax aaaaalj ", " aax aax aax aax aalqaak ", " aax aax aaaaaaak maaaaaak aax aak", " mqj mqj mqqqqqqj mqqqqqj mqj mqj", "", }; struct term_params tparams; process_term_read_info(&tparams); const u32 cols = tparams.cols; const u32 padding = (u32)(cols / 2 - strlen(banner[1]) / 2); for (int i = 0; i < ARRAY_SIZE(banner); i++) { for (u32 j = 0; j < padding; j++) printk(NO_PREFIX " "); print_banner_line((u8 *)banner[i]); } } #endif static void show_system_info(void) { const int time_slice = 1000 / (TIMER_HZ / TIME_SLICE_TICKS); const char *in_hyp_str = in_hypervisor() ? "yes" : "no"; printk("timer_hz: \e[1m%i\e[m", TIMER_HZ); printk("; time_slice: \e[1m%i\e[m", time_slice); printk(" ms; in_hypervisor: \e[1m%s\e[m\n", in_hyp_str); } void show_hello_message(void) { struct commit_hash_and_date comm; extract_commit_hash_and_date(&tilck_build_info, &comm); if (VER_PATCH > 0) printk("Hello from Tilck \e[1m%d.%d.%d\e[m", VER_MAJOR, VER_MINOR, VER_PATCH); else printk("Hello from Tilck \e[1m%d.%d\e[m", VER_MAJOR, VER_MINOR); printk(", commit: \e[1m%s\e[m", comm.hash); if (comm.dirty) printk(" (dirty)"); else if (comm.tags[0]) printk(" (%s)", comm.tags); printk("\n"); printk("Build type: \e[1m%s\e[m", BUILDTYPE_STR); printk(", compiler: \e[1m%s %d.%d.%d\e[m\n", COMPILER_NAME, COMPILER_MAJOR, COMPILER_MINOR, COMPILER_PATCHLEVEL); show_system_info(); if (KERNEL_SHOW_LOGO) show_tilck_logo(); } WEAK const char *get_signal_name(int signum) { return ""; } const struct build_info tilck_build_info ATTR_SECTION(".tilck_info") = { .commit = {0}, /* It will get patched after the build */ .ver = VER_MAJOR_STR "." VER_MINOR_STR "." VER_PATCH_STR, .arch = ARCH_GCC_TC, .modules_list = ENABLED_MODULES_LIST, }; <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set( WRAPPED_SYMS assert_failed not_reached not_implemented tilck_vprintk kmutex_lock kmutex_unlock fat_ramdisk_prepare_for_mmap wth_create_thread_for wth_wakeup check_in_irq_handler general_kmalloc general_kfree kmalloc_get_first_heap vfs_dup vfs_close use_kernel_arg handle_sys_trace_arg copy_str_from_user copy_from_user experiment_bar experiment_foo ) <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) if (${KERNEL_SYSCC} OR ${USE_SYSCC}) if (${ARCH} STREQUAL "i386") set(CMAKE_C_FLAGS "${ARCH_GCC_FLAGS}") set(CMAKE_CXX_FLAGS "${ARCH_GCC_FLAGS} ${KERNEL_CXX_FLAGS}") if (CMAKE_C_COMPILER_ID STREQUAL "GNU") set(CMAKE_ASM_FLAGS "${ARCH_GCC_FLAGS}") else() # If system's compiler (CC) is Clang, we cannot use it for compiling # our assembly code, because LLVM's assembler (llvm-as) is not 100% # compatible with GAS's intel-syntax dialect. set(CMAKE_ASM_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcc) endif() endif() if (KERNEL_FORCE_TC_ISYSTEM) include_directories(SYSTEM ${GCC_TC_ISYSTEM}) endif() else() set_cross_compiler() endif() smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/generate_coverage_report ${CMAKE_BINARY_DIR}/scripts/generate_kernel_coverage_report ) add_subdirectory(${ARCH}) <file_sep>/****************************************************************************** * * Module Name: dsobject - Dispatcher object management routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acnamesp.h" #include "acinterp.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsobject") /******************************************************************************* * * FUNCTION: AcpiDsBuildInternalObject * * PARAMETERS: WalkState - Current walk state * Op - Parser object to be translated * ObjDescPtr - Where the ACPI internal object is returned * * RETURN: Status * * DESCRIPTION: Translate a parser Op object to the equivalent namespace object * Simple objects are any objects other than a package object! * ******************************************************************************/ ACPI_STATUS AcpiDsBuildInternalObject ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT **ObjDescPtr) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (DsBuildInternalObject); *ObjDescPtr = NULL; if (Op->Common.AmlOpcode == AML_INT_NAMEPATH_OP) { /* * This is a named object reference. If this name was * previously looked up in the namespace, it was stored in * this op. Otherwise, go ahead and look it up now */ if (!Op->Common.Node) { /* Check if we are resolving a named reference within a package */ if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP)) { /* * We won't resolve package elements here, we will do this * after all ACPI tables are loaded into the namespace. This * behavior supports both forward references to named objects * and external references to objects in other tables. */ goto CreateNewObject; } else { Status = AcpiNsLookup (WalkState->ScopeInfo, Op->Common.Value.String, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, NULL, ACPI_CAST_INDIRECT_PTR ( ACPI_NAMESPACE_NODE, &(Op->Common.Node))); if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, Op->Common.Value.String, Status); return_ACPI_STATUS (Status); } } } } CreateNewObject: /* Create and init a new internal ACPI object */ ObjDesc = AcpiUtCreateInternalObject ( (AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode))->ObjectType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } Status = AcpiDsInitObjectFromOp ( WalkState, Op, Op->Common.AmlOpcode, &ObjDesc); if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /* * Handling for unresolved package reference elements. * These are elements that are namepaths. */ if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP)) { ObjDesc->Reference.Resolved = TRUE; if ((Op->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && !ObjDesc->Reference.Node) { /* * Name was unresolved above. * Get the prefix node for later lookup */ ObjDesc->Reference.Node = WalkState->ScopeInfo->Scope.Node; ObjDesc->Reference.Aml = Op->Common.Aml; ObjDesc->Reference.Resolved = FALSE; } } *ObjDescPtr = ObjDesc; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsBuildInternalBufferObj * * PARAMETERS: WalkState - Current walk state * Op - Parser object to be translated * BufferLength - Length of the buffer * ObjDescPtr - Where the ACPI internal object is returned * * RETURN: Status * * DESCRIPTION: Translate a parser Op package object to the equivalent * namespace object * ******************************************************************************/ ACPI_STATUS AcpiDsBuildInternalBufferObj ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, UINT32 BufferLength, ACPI_OPERAND_OBJECT **ObjDescPtr) { ACPI_PARSE_OBJECT *Arg; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PARSE_OBJECT *ByteList; UINT32 ByteListLength = 0; ACPI_FUNCTION_TRACE (DsBuildInternalBufferObj); /* * If we are evaluating a Named buffer object "Name (xxxx, Buffer)". * The buffer object already exists (from the NS node), otherwise it must * be created. */ ObjDesc = *ObjDescPtr; if (!ObjDesc) { /* Create a new buffer object */ ObjDesc = AcpiUtCreateInternalObject (ACPI_TYPE_BUFFER); *ObjDescPtr = ObjDesc; if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } } /* * Second arg is the buffer data (optional) ByteList can be either * individual bytes or a string initializer. In either case, a * ByteList appears in the AML. */ Arg = Op->Common.Value.Arg; /* skip first arg */ ByteList = Arg->Named.Next; if (ByteList) { if (ByteList->Common.AmlOpcode != AML_INT_BYTELIST_OP) { ACPI_ERROR ((AE_INFO, "Expecting bytelist, found AML opcode 0x%X in op %p", ByteList->Common.AmlOpcode, ByteList)); AcpiUtRemoveReference (ObjDesc); return (AE_TYPE); } ByteListLength = (UINT32) ByteList->Common.Value.Integer; } /* * The buffer length (number of bytes) will be the larger of: * 1) The specified buffer length and * 2) The length of the initializer byte list */ ObjDesc->Buffer.Length = BufferLength; if (ByteListLength > BufferLength) { ObjDesc->Buffer.Length = ByteListLength; } /* Allocate the buffer */ if (ObjDesc->Buffer.Length == 0) { ObjDesc->Buffer.Pointer = NULL; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Buffer defined with zero length in AML, creating\n")); } else { ObjDesc->Buffer.Pointer = ACPI_ALLOCATE_ZEROED (ObjDesc->Buffer.Length); if (!ObjDesc->Buffer.Pointer) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize buffer from the ByteList (if present) */ if (ByteList) { memcpy (ObjDesc->Buffer.Pointer, ByteList->Named.Data, ByteListLength); } } ObjDesc->Buffer.Flags |= AOPOBJ_DATA_VALID; Op->Common.Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjDesc); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsCreateNode * * PARAMETERS: WalkState - Current walk state * Node - NS Node to be initialized * Op - Parser object to be translated * * RETURN: Status * * DESCRIPTION: Create the object to be associated with a namespace node * ******************************************************************************/ ACPI_STATUS AcpiDsCreateNode ( ACPI_WALK_STATE *WalkState, ACPI_NAMESPACE_NODE *Node, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_FUNCTION_TRACE_PTR (DsCreateNode, Op); /* * Because of the execution pass through the non-control-method * parts of the table, we can arrive here twice. Only init * the named object node the first time through */ if (AcpiNsGetAttachedObject (Node)) { return_ACPI_STATUS (AE_OK); } if (!Op->Common.Value.Arg) { /* No arguments, there is nothing to do */ return_ACPI_STATUS (AE_OK); } /* Build an internal object for the argument(s) */ Status = AcpiDsBuildInternalObject ( WalkState, Op->Common.Value.Arg, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Re-type the object according to its argument */ Node->Type = ObjDesc->Common.Type; /* Attach obj to node */ Status = AcpiNsAttachObject (Node, ObjDesc, Node->Type); /* Remove local reference to the object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsInitObjectFromOp * * PARAMETERS: WalkState - Current walk state * Op - Parser op used to init the internal object * Opcode - AML opcode associated with the object * RetObjDesc - Namespace object to be initialized * * RETURN: Status * * DESCRIPTION: Initialize a namespace object from a parser Op and its * associated arguments. The namespace object is a more compact * representation of the Op and its arguments. * ******************************************************************************/ ACPI_STATUS AcpiDsInitObjectFromOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, UINT16 Opcode, ACPI_OPERAND_OBJECT **RetObjDesc) { const ACPI_OPCODE_INFO *OpInfo; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (DsInitObjectFromOp); ObjDesc = *RetObjDesc; OpInfo = AcpiPsGetOpcodeInfo (Opcode); if (OpInfo->Class == AML_CLASS_UNKNOWN) { /* Unknown opcode */ return_ACPI_STATUS (AE_TYPE); } /* Perform per-object initialization */ switch (ObjDesc->Common.Type) { case ACPI_TYPE_BUFFER: /* * Defer evaluation of Buffer TermArg operand */ ObjDesc->Buffer.Node = ACPI_CAST_PTR ( ACPI_NAMESPACE_NODE, WalkState->Operands[0]); ObjDesc->Buffer.AmlStart = Op->Named.Data; ObjDesc->Buffer.AmlLength = Op->Named.Length; break; case ACPI_TYPE_PACKAGE: /* * Defer evaluation of Package TermArg operand and all * package elements. (01/2017): We defer the element * resolution to allow forward references from the package * in order to provide compatibility with other ACPI * implementations. */ ObjDesc->Package.Node = ACPI_CAST_PTR ( ACPI_NAMESPACE_NODE, WalkState->Operands[0]); if (!Op->Named.Data) { return_ACPI_STATUS (AE_OK); } ObjDesc->Package.AmlStart = Op->Named.Data; ObjDesc->Package.AmlLength = Op->Named.Length; break; case ACPI_TYPE_INTEGER: switch (OpInfo->Type) { case AML_TYPE_CONSTANT: /* * Resolve AML Constants here - AND ONLY HERE! * All constants are integers. * We mark the integer with a flag that indicates that it started * life as a constant -- so that stores to constants will perform * as expected (noop). ZeroOp is used as a placeholder for optional * target operands. */ ObjDesc->Common.Flags = AOPOBJ_AML_CONSTANT; switch (Opcode) { case AML_ZERO_OP: ObjDesc->Integer.Value = 0; break; case AML_ONE_OP: ObjDesc->Integer.Value = 1; break; case AML_ONES_OP: ObjDesc->Integer.Value = ACPI_UINT64_MAX; /* Truncate value if we are executing from a 32-bit ACPI table */ (void) AcpiExTruncateFor32bitTable (ObjDesc); break; case AML_REVISION_OP: ObjDesc->Integer.Value = ACPI_CA_VERSION; break; default: ACPI_ERROR ((AE_INFO, "Unknown constant opcode 0x%X", Opcode)); Status = AE_AML_OPERAND_TYPE; break; } break; case AML_TYPE_LITERAL: ObjDesc->Integer.Value = Op->Common.Value.Integer; if (AcpiExTruncateFor32bitTable (ObjDesc)) { /* Warn if we found a 64-bit constant in a 32-bit table */ ACPI_WARNING ((AE_INFO, "Truncated 64-bit constant found in 32-bit table: %8.8X%8.8X => %8.8X", ACPI_FORMAT_UINT64 (Op->Common.Value.Integer), (UINT32) ObjDesc->Integer.Value)); } break; default: ACPI_ERROR ((AE_INFO, "Unknown Integer type 0x%X", OpInfo->Type)); Status = AE_AML_OPERAND_TYPE; break; } break; case ACPI_TYPE_STRING: ObjDesc->String.Pointer = Op->Common.Value.String; ObjDesc->String.Length = (UINT32) strlen (Op->Common.Value.String); /* * The string is contained in the ACPI table, don't ever try * to delete it */ ObjDesc->Common.Flags |= AOPOBJ_STATIC_POINTER; break; case ACPI_TYPE_METHOD: break; case ACPI_TYPE_LOCAL_REFERENCE: switch (OpInfo->Type) { case AML_TYPE_LOCAL_VARIABLE: /* Local ID (0-7) is (AML opcode - base AML_FIRST_LOCAL_OP) */ ObjDesc->Reference.Value = ((UINT32) Opcode) - AML_FIRST_LOCAL_OP; ObjDesc->Reference.Class = ACPI_REFCLASS_LOCAL; Status = AcpiDsMethodDataGetNode (ACPI_REFCLASS_LOCAL, ObjDesc->Reference.Value, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc->Reference.Object)); break; case AML_TYPE_METHOD_ARGUMENT: /* Arg ID (0-6) is (AML opcode - base AML_FIRST_ARG_OP) */ ObjDesc->Reference.Value = ((UINT32) Opcode) - AML_FIRST_ARG_OP; ObjDesc->Reference.Class = ACPI_REFCLASS_ARG; Status = AcpiDsMethodDataGetNode (ACPI_REFCLASS_ARG, ObjDesc->Reference.Value, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc->Reference.Object)); break; default: /* Object name or Debug object */ switch (Op->Common.AmlOpcode) { case AML_INT_NAMEPATH_OP: /* Node was saved in Op */ ObjDesc->Reference.Node = Op->Common.Node; ObjDesc->Reference.Class = ACPI_REFCLASS_NAME; if (Op->Common.Node) { ObjDesc->Reference.Object = Op->Common.Node->Object; } break; case AML_DEBUG_OP: ObjDesc->Reference.Class = ACPI_REFCLASS_DEBUG; break; default: ACPI_ERROR ((AE_INFO, "Unimplemented reference type for AML opcode: 0x%4.4X", Opcode)); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } break; } break; default: ACPI_ERROR ((AE_INFO, "Unimplemented data type: 0x%X", ObjDesc->Common.Type)); Status = AE_AML_OPERAND_TYPE; break; } return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> static inline bool user_out_of_range(const void *user_ptr, size_t n) { return ((ulong)user_ptr + n) > KERNEL_BASE_VA; } int copy_from_user(void *dest, const void *user_ptr, size_t n); int copy_to_user(void *user_ptr, const void *src, size_t n); int copy_str_from_user(void *dest, const void *user_ptr, size_t max_size, size_t *written_ptr); int copy_str_array_from_user(void *dest, const char *const *argv, size_t max_size, size_t *written_ptr); int duplicate_user_path(char *dest, const char *user_path, size_t dest_size, size_t *written_ptr /* IN/OUT */); int duplicate_user_argv(char *dest, const char *const *user_argv, size_t dest_size, size_t *written_ptr /* IN/OUT */); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include "defs.h" #include "utils.h" #include <tilck/common/printk.h> #include <tilck/common/arch/generic_x86/x86_utils.h> NORETURN void panic(const char *fmt, ...) { UINTN mapkey; va_list args; if (!gExitBootServicesCalled) { printk("\n"); printk("******************* UEFI BOOTLOADER PANIC ********************"); printk("\n"); va_start(args, fmt); vprintk(fmt, args); va_end(args); printk("\n"); if (GetMemoryMap(&mapkey) == EFI_SUCCESS) { if (BS->ExitBootServices(gImageHandle, mapkey) != EFI_SUCCESS) Print(L"Error in panic: ExitBootServices() failed.\n"); } else { Print(L"Error in panic: GetMemoryMap() failed.\n"); } } disable_interrupts_forced(); while (true) { halt(); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/sort.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/test/mem_regions.h> u32 __mem_lower_kb; u32 __mem_upper_kb; struct mem_region mem_regions[MAX_MEM_REGIONS]; int mem_regions_count; const char *mem_region_extra_to_str(u32 e) { switch (e) { case 0: return " "; case MEM_REG_EXTRA_RAMDISK: return "RDSK"; case MEM_REG_EXTRA_KERNEL: return "KRNL"; case MEM_REG_EXTRA_LOWMEM: return "LMRS"; case MEM_REG_EXTRA_FRAMEBUFFER: return "FBUF"; case MEM_REG_EXTRA_DMA: return "DMA "; default: return "MIXD"; } } void append_mem_region(struct mem_region r) { if (mem_regions_count >= (int)ARRAY_SIZE(mem_regions)) panic("Too many memory regions (limit: %u)", ARRAY_SIZE(mem_regions)); mem_regions[mem_regions_count++] = r; } STATIC long less_than_cmp_mem_region(const void *a, const void *b) { const struct mem_region *m1 = a; const struct mem_region *m2 = b; if (m1->addr < m2->addr) return -1; if (m1->addr == m2->addr) return 0; return 1; } STATIC void sort_mem_regions(void) { insertion_sort_generic(mem_regions, sizeof(struct mem_region), (u32)mem_regions_count, less_than_cmp_mem_region); } void system_mmap_add_ramdisk(ulong start_paddr, ulong end_paddr) { append_mem_region((struct mem_region) { .addr = start_paddr, .len = end_paddr - start_paddr, .type = MULTIBOOT_MEMORY_RESERVED, .extra = MEM_REG_EXTRA_RAMDISK, }); /* * Add one special region (completely overridable by other mem regions) * containing just one page after the ramdisk, in order to handle the corner * case described in fat_ramdisk_prepare_for_mmap(). */ append_mem_region((struct mem_region) { .addr = end_paddr, .len = PAGE_SIZE, .type = MULTIBOOT_MEMORY_AVAILABLE, .extra = MEM_REG_EXTRA_RAMDISK, }); sort_mem_regions(); } int system_mmap_get_ramdisk(int ramdisk_index, void **va, size_t *size) { int rd_count = 0; for (int i = 0; i < mem_regions_count; i++) { struct mem_region *m = mem_regions + i; if (m->extra & MEM_REG_EXTRA_RAMDISK) { if (rd_count == ramdisk_index) { if (va) *va = KERNEL_PA_TO_VA((ulong)m->addr); if (size) *size = (size_t)m->len; return 0; } rd_count++; } } return -1; } STATIC void remove_mem_region(int i) { struct mem_region *ma = mem_regions + i; const int rem = mem_regions_count - i - 1; memcpy(ma, ma + 1, (size_t) rem * sizeof(struct mem_region)); mem_regions_count--; /* decrease the number of memory regions */ } STATIC void swap_mem_regions(int i, int j) { ASSERT(IN_RANGE(i, 0, mem_regions_count)); ASSERT(IN_RANGE(j, 0, mem_regions_count)); struct mem_region temp = mem_regions[i]; mem_regions[i] = mem_regions[j]; mem_regions[j] = temp; } STATIC void remove_mem_region_by_swap_with_last(int i) { ASSERT(0 <= i && i < mem_regions_count); swap_mem_regions(i, mem_regions_count - 1); mem_regions_count--; } STATIC void align_mem_regions_to_page_boundary(void) { for (int i = 0; i < mem_regions_count; i++) { struct mem_region *ma = mem_regions + i; /* * Unfortunately, in general we cannot rely on the memory regions to be * page-aligned (while they will be in most of the cases). Therefore, * we have to forcibly approximate the regions at page-boundaries. */ const u64 ma_end = pow2_round_up_at64(ma->addr + ma->len, PAGE_SIZE); ma->addr &= ~((u64)PAGE_SIZE - 1); /* Don't use PAGE_MASK here: it causes truncation on 32-bit systems */ ma->len = ma_end - ma->addr; } } STATIC void merge_adj_mem_regions(void) { for (int i = 0; i < mem_regions_count - 1; i++) { struct mem_region *ma = mem_regions + i; struct mem_region *ma_next = ma + 1; if (ma_next->type != ma->type || ma_next->extra != ma->extra) continue; if (ma_next->addr != ma->addr + ma->len) continue; /* If we got here, we hit two adjacent regions having the same type */ ma->len += ma_next->len; remove_mem_region(i + 1); i--; /* compensate the i++ in the for loop: we have to keep the index */ } } STATIC bool handle_region_overlap(int r1_index, int r2_index) { if (r1_index == r2_index) return false; struct mem_region *r1 = mem_regions + r1_index; struct mem_region *r2 = mem_regions + r2_index; u64 s1 = r1->addr; u64 s2 = r2->addr; u64 e1 = r1->addr + r1->len; u64 e2 = r2->addr + r2->len; if (s2 < s1) { /* * Case 0: region 2 starts before region 1. * All the cases below are possible (mirrored). * * +----------------------+ * | region 1 | * +----------------------+ * +----------------------+ * | region 2 | * +----------------------+ */ return handle_region_overlap(r2_index, r1_index); } if (s2 >= e1) { /* * Case 1: no-overlap. * * * +----------------------+ * | region 1 | * +----------------------+ * +----------------------+ * | region 2 | * +----------------------+ * * Reason: the regions do not overlap. */ return false; } if (s1 <= s2 && e2 <= e1) { /* * Case 2: full overlap (region 2 is inside 1) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ * * Corner case 2a: * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------------------------+ * | region 2 | * +---------------------------------+ * * Corner case 2b: * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ * * Corner case 2c: * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ if (r1->type >= r2->type) { /* * Region 1's type is stricter than region 2's. Just remove region 2. */ remove_mem_region_by_swap_with_last(r2_index); } else { /* * Region 2's type is stricter, we need to split region 1 in two parts: * +---------------+ +-------------------+ * | region 1-1 | | region 1-2 | * +---------------+ +-------------------+ * +---------------+ * | region 2 | * +---------------+ */ if (s1 == s2 && e1 == e2) { /* * Corner case 2a: regions 1-1 and 1-2 are empty. */ remove_mem_region_by_swap_with_last(r1_index); } else if (s1 == s2) { /* Corner case 2b: region 1-1 is empty */ r1->addr = e2; r1->len = e1 - r1->addr; } else if (e1 == e2) { /* Corner case 2c: region 1-2 is empty */ r1->len = s2 - s1; } else { /* Base case */ r1->len = s2 - s1; append_mem_region((struct mem_region) { .addr = e2, .len = (e1 - e2), .type = r1->type, .extra = r1->extra, }); } } } else { ASSERT(s1 <= s2 && s2 < e1 && e2 > e1); /* * Case 3: partial overlap. * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------------------+ * | region 2 | * +---------------------------+ * * Corner case 3a: * * +----------------------------+ * | region 1 | * +----------------------------+ * +--------------------------------------------+ * | region 2 | * +--------------------------------------------+ */ if (r1->type >= r2->type) { /* * Region 1's type is stricter than region 2's. Move region 2's start. * +---------------------------------+ * | region 1 | * +---------------------------------+ * +-----------+ * | region 2 | * +-----------+ */ r2->addr = e1; r2->len = e2 - r2->addr; } else { /* * Region 2's type is stricter, move region 1's end. * * +-----------------+ * | region 1 | * +-----------------+ * +---------------------------+ * | region 2 | * +---------------------------+ */ if (s1 == s2) { /* Corner case 3a: region 1 would become empty. Remove it. */ remove_mem_region_by_swap_with_last(r1_index); } else { /* Base case: just shrink region 1 */ r1->len = s2 - s1; } } } return true; } STATIC void handle_overlapping_regions(void) { bool any_overlap; do { any_overlap = false; for (int i = 0; i < mem_regions_count - 1; i++) if (handle_region_overlap(i, i + 1)) any_overlap = true; sort_mem_regions(); } while (any_overlap); } STATIC void fix_mem_regions(void) { align_mem_regions_to_page_boundary(); sort_mem_regions(); merge_adj_mem_regions(); handle_overlapping_regions(); } STATIC void add_kernel_phdrs_to_mmap(void) { Elf_Ehdr *h = (Elf_Ehdr*)(KERNEL_PA_TO_VA(KERNEL_PADDR)); Elf_Phdr *phdrs = (void *)h + h->e_phoff; for (int i = 0; i < h->e_phnum; i++) { Elf_Phdr *phdr = phdrs + i; if (phdr->p_type != PT_LOAD) continue; append_mem_region((struct mem_region) { .addr = phdr->p_paddr, .len = phdr->p_memsz, .type = MULTIBOOT_MEMORY_RESERVED, .extra = MEM_REG_EXTRA_KERNEL, }); } } STATIC void set_lower_and_upper_kb(void) { __mem_lower_kb = 0; __mem_upper_kb = 0; for (int i = 0; i < mem_regions_count; i++) { struct mem_region *m = mem_regions + i; if (m->type == MULTIBOOT_MEMORY_AVAILABLE) { __mem_lower_kb = (u32) (m->addr / KB); break; } } for (int i = mem_regions_count - 1; i >= 0; i--) { struct mem_region *m = mem_regions + i; if (m->type == MULTIBOOT_MEMORY_AVAILABLE) { __mem_upper_kb = (u32) ((m->addr + m->len) / KB); break; } } } void dump_memory_map(void) { struct mem_region ma; printk("System memory map from multiboot:\n"); printk("\n"); printk(" START END (T, Extr)\n"); for (int i = 0; i < get_mem_regions_count(); i++) { get_mem_region(i, &ma); printk("%02d) %#018" PRIx64 " - %#018" PRIx64 " (%d, %s) [%8" PRIu64 " KB]\n", i, ma.addr, ma.addr + ma.len - 1, ma.type, mem_region_extra_to_str(ma.extra), ma.len / KB); } printk("\n"); } void system_mmap_set(multiboot_info_t *mbi) { ulong ma_addr = mbi->mmap_addr; arch_add_initial_mem_regions(); while (ma_addr < mbi->mmap_addr + mbi->mmap_length) { multiboot_memory_map_t *ma = (void *)ma_addr; append_mem_region((struct mem_region) { .addr = ma->addr, .len = ma->len, .type = ma->type, .extra = 0, }); ma_addr += ma->size + 4; } add_kernel_phdrs_to_mmap(); fix_mem_regions(); set_lower_and_upper_kb(); if (arch_add_final_mem_regions()) fix_mem_regions(); dump_memory_map(); } int system_mmap_get_region_of(ulong paddr) { for (int i = 0; i < mem_regions_count; i++) { struct mem_region *m = mem_regions + i; if (IN_RANGE(paddr, m->addr, m->addr + m->len)) return i; } return -1; } bool linear_map_mem_region(struct mem_region *r, ulong *vbegin, ulong *vend) { if (r->addr >= LINEAR_MAPPING_SIZE) return false; const ulong pbegin = (ulong) r->addr; const ulong pend = MIN((ulong)(r->addr+r->len), (ulong)LINEAR_MAPPING_SIZE); const bool rw = (r->type == MULTIBOOT_MEMORY_AVAILABLE) || (r->extra & MEM_REG_EXTRA_KERNEL); /* * Allow big_pages (4M) to be used except when the region is a ramdisk. * Reason: fat_ramdisk_prepare_for_mmap() might need to temporary make the * region writable and it's much easier to do with 4k (regular) pages. */ const bool big_pages = !(r->extra & MEM_REG_EXTRA_RAMDISK); const size_t page_count = (pend - pbegin) >> PAGE_SHIFT; *vbegin = (ulong)KERNEL_PA_TO_VA(pbegin); *vend = (ulong)KERNEL_PA_TO_VA(pend); size_t count = map_pages(get_kernel_pdir(), (void *)*vbegin, pbegin, page_count, (big_pages ? PAGING_FL_BIG_PAGES_ALLOWED : 0) | (rw ? PAGING_FL_RW : 0)); if (count != page_count) panic("kmalloc: unable to map regions in the virtual space"); if (still_using_orig_pdir() && pend >= 4 * MB) { set_curr_pdir(get_kernel_pdir()); on_first_pdir_update(); } return true; } bool system_mmap_check_for_extra_ramdisk_region(void *rd) { int ri = system_mmap_get_region_of(KERNEL_VA_TO_PA(rd)); struct mem_region *r; VERIFY(ri >= 0); if (ri == MAX_MEM_REGIONS - 1) return false; /* our region is the last one; no extra region */ /* An extra region, if any, will immediately follow ours */ r = &mem_regions[ri+1]; if (r->type == MULTIBOOT_MEMORY_AVAILABLE && r->extra == mem_regions[ri].extra) { /* Our extra 4k region survived the overlap handling, yey! */ return true; } /* No such extra region: it has been overridden by a reserved one */ return false; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/kb.h> struct list kb_devices_list = STATIC_LIST_INIT(kb_devices_list); void register_keyboard_device(struct kb_dev *kb) { list_add_tail(&kb_devices_list, &kb->node); } void register_keypress_handler(struct keypress_handler_elem *e) { struct kb_dev *kb; list_for_each_ro(kb, &kb_devices_list, node) { kb->register_handler(e); } } u8 kb_get_current_modifiers(struct kb_dev *kb) { u8 shift = 1u * kb_is_shift_pressed(kb); u8 alt = 2u * kb_is_alt_pressed(kb); u8 ctrl = 4u * kb_is_ctrl_pressed(kb); /* * 0 nothing * 1 shift * 2 alt * 3 shift + alt * 4 ctrl * 5 shift + ctrl * 6 alt + ctrl * 7 shift + alt + ctrl */ return shift + alt + ctrl; } /* NOTE: returns 0 if `key` not in [F1 ... F12] */ int kb_get_fn_key_pressed(u32 key) { /* * We know that on the PC architecture, in the PS/2 set 1, keys F1-F12 have * all a scancode long 1 byte. */ if (key >= 256) return 0; static const char fn_table[256] = { [KEY_F1] = 1, [KEY_F2] = 2, [KEY_F3] = 3, [KEY_F4] = 4, [KEY_F5] = 5, [KEY_F6] = 6, [KEY_F7] = 7, [KEY_F8] = 8, [KEY_F9] = 9, [KEY_F10] = 10, [KEY_F11] = 11, [KEY_F12] = 12, }; return fn_table[(u8) key]; } <file_sep># version: v3 FROM ubuntu:20.04 # We don't want any of the interactive features of apt, so we just disable them. ENV DEBIAN_FRONTEND=noninteractive ENV TCROOT=/tc/toolchain2 ENV ARCH=i386 # Install the required system packages RUN apt update && apt upgrade -y && \ apt install git-core gcc g++ gcc-multilib g++-multilib clang cmake \ python3-minimal python3-serial python3-pip apt gawk unzip parted wget \ curl qemu-system-x86 imagemagick -y # Create the shared directories will need for all the toolchains RUN mkdir -p /tc/cache && \ mkdir -p /tc/host_x86_64 && \ mkdir -p /tc/noarch && \ mkdir -p /tc/toolchain2 && \ mkdir -p /tc/toolchain2-gcc64 && \ mkdir -p /tc/toolchain2-gcc73 && \ ln -s /tc/cache /tc/toolchain2/cache && \ ln -s /tc/cache /tc/toolchain2-gcc64/cache && \ ln -s /tc/cache /tc/toolchain2-gcc73/cache && \ ln -s /tc/noarch /tc/toolchain2/noarch && \ ln -s /tc/noarch /tc/toolchain2-gcc64/noarch && \ ln -s /tc/noarch /tc/toolchain2-gcc73/noarch && \ ln -s /tc/host_x86_64 /tc/toolchain2/host_x86_64 && \ ln -s /tc/host_x86_64 /tc/toolchain2-gcc64/host_x86_64 && \ ln -s /tc/host_x86_64 /tc/toolchain2-gcc73/host_x86_64 # Clone Tilck and build the toolchain with the default GCC_TC_VER RUN git clone https://github.com/vvaltchev/tilck.git /tilck-tmp && \ /tilck-tmp/scripts/build_toolchain && \ /tilck-tmp/scripts/build_toolchain -s gnuefi mtools zlib busybox && \ /tilck-tmp/scripts/build_toolchain -s gmock gmock_arch gtest gtest_arch && \ /tilck-tmp/scripts/build_toolchain -s lcov libmusl lua micropython ncurses && \ /tilck-tmp/scripts/build_toolchain -s tcc vim gcc_glibc_toolchain # Prepare the default toolchain for ARCH=x86_64 ENV ARCH=x86_64 RUN /tilck-tmp/scripts/build_toolchain && \ /tilck-tmp/scripts/build_toolchain -s gnuefi mtools zlib busybox && \ /tilck-tmp/scripts/build_toolchain -s gmock gmock_arch gtest gtest_arch && \ /tilck-tmp/scripts/build_toolchain -s lcov libmusl lua micropython ncurses && \ /tilck-tmp/scripts/build_toolchain -s tcc vim gcc_glibc_toolchain # Back to ARCH=i386. Switch the TCROOT and GCC_TC_VER to 6.4.0 and re-build ENV TCROOT=/tc/toolchain2-gcc64 ENV GCC_TC_VER=6.4.0 ENV ARCH=i386 RUN /tilck-tmp/scripts/build_toolchain && \ /tilck-tmp/scripts/build_toolchain -s gnuefi mtools zlib busybox && \ /tilck-tmp/scripts/build_toolchain -s gmock gmock_arch gtest gtest_arch && \ /tilck-tmp/scripts/build_toolchain -s lcov libmusl lua micropython ncurses && \ /tilck-tmp/scripts/build_toolchain -s tcc vim gcc_glibc_toolchain # Switch the TCROOT and GCC_TC_VER to 7.3.0 and re-build the toolchain ENV TCROOT=/tc/toolchain2-gcc73 ENV GCC_TC_VER=7.3.0 RUN /tilck-tmp/scripts/build_toolchain && \ /tilck-tmp/scripts/build_toolchain -s gnuefi mtools zlib busybox && \ /tilck-tmp/scripts/build_toolchain -s gmock gmock_arch gtest gtest_arch && \ /tilck-tmp/scripts/build_toolchain -s lcov libmusl lua micropython ncurses && \ /tilck-tmp/scripts/build_toolchain -s tcc vim gcc_glibc_toolchain RUN rm -rf /tilck-tmp && rm -rf /tc/cache <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_sysfs.h> #if MOD_sysfs #include <tilck/mods/sysfs.h> #include <tilck/mods/sysfs_utils.h> static struct sysobj *dir_sysfs_pci; /* /sysfs/pci */ /* Properties */ DEF_STATIC_SYSOBJ_PROP(vendor_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(device_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(class_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(subclass_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(progif_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(rev_id, &sysobj_ptype_ro_ulong_hex_literal); DEF_STATIC_SYSOBJ_PROP(multi_func, &sysobj_ptype_ro_ulong_literal); DEF_STATIC_SYSOBJ_PROP(class_name, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(subclass_name, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(progif_name, &sysobj_ptype_ro_string_literal); DEF_STATIC_SYSOBJ_PROP(vendor_name, &sysobj_ptype_ro_string_literal); /* Sysfs obj types */ DEF_STATIC_SYSOBJ_TYPE(pci_device_sysobj_type, &prop_vendor_id, &prop_device_id, &prop_class_id, &prop_subclass_id, &prop_progif_id, &prop_rev_id, &prop_multi_func, &prop_class_name, &prop_subclass_name, &prop_progif_name, &prop_vendor_name, NULL); static int pci_create_obj_for_device(struct pci_device *dev) { struct pci_device_class dc = {0}; struct pci_device_basic_info nfo; struct pci_device_loc loc; struct sysobj *obj, *parent; const char *vendor; char name[16]; loc = dev->loc; nfo = dev->nfo; dc.class_id = nfo.class_id; dc.subclass_id = nfo.subclass_id; dc.progif_id = nfo.progif_id; pci_find_device_class_name(&dc); vendor = pci_find_vendor_name(nfo.vendor_id); obj = sysfs_create_obj(&pci_device_sysobj_type, NULL, /* hooks */ TO_PTR(nfo.vendor_id), TO_PTR(nfo.device_id), TO_PTR(nfo.class_id), TO_PTR(nfo.subclass_id), TO_PTR(nfo.progif_id), TO_PTR(nfo.rev_id), TO_PTR(nfo.multi_func), dc.class_name, dc.subclass_name, dc.progif_name, vendor); if (!obj) return -ENOMEM; snprintk(name, sizeof(name), "%04x:%02x:%02x.%x", loc.seg, loc.bus, loc.dev, loc.func); if (sysfs_register_obj(NULL, dir_sysfs_pci, name, obj) < 0) { sysfs_destroy_unregistered_obj(obj); return -ENOMEM; } switch (nfo.class_id) { case PCI_CLASS_MASS_STORAGE: parent = &sysfs_storage_obj; break; case PCI_CLASS_NETWORK: parent = &sysfs_network_obj; break; case PCI_CLASS_DISPLAY: parent = &sysfs_display_obj; break; case PCI_CLASS_MULTIMEDIA: parent = &sysfs_media_obj; break; case PCI_CLASS_BRIDGE: parent = &sysfs_bridge_obj; break; case PCI_CLASS_COMMUNICATION: parent = &sysfs_comm_obj; break; case PCI_CLASS_GENERIC_PERIPHERAL: parent = &sysfs_genp_obj; break; case PCI_CLASS_INPUT: parent = &sysfs_input_obj; break; case PCI_CLASS_SERIAL_BUS: parent = &sysfs_serbus_obj; break; case PCI_CLASS_WIRELESS: parent = &sysfs_wifi_obj; break; case PCI_CLASS_SIGNAL_PROCESSING: parent = &sysfs_sigproc_obj; break; default: parent = &sysfs_other_obj; break; } return sysfs_symlink_obj(NULL, parent, name, obj); } static int pci_create_sysfs_view(void) { struct pci_device *dev; int rc = 0; dir_sysfs_pci = sysfs_create_empty_obj(); if (!dir_sysfs_pci) return -ENOMEM; if (sysfs_register_obj(NULL, &sysfs_root_obj, "pci", dir_sysfs_pci) < 0) { sysfs_destroy_unregistered_obj(dir_sysfs_pci); return -ENOMEM; } list_for_each_ro(dev, &pci_device_list, node) { rc = pci_create_obj_for_device(dev); if (rc) break; } return rc; } #else static int pci_create_sysfs_view(void) { return 0; } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <vector> #include <string> #include <gtest/gtest.h> using namespace std; extern "C" { #include <tilck/kernel/cmdline.h> #include <tilck/kernel/test/cmdline.h> } using tvec = vector<string>; static tvec args; static const tvec& parse_wrapper(const char *cmdline) { args.clear(); parse_kernel_cmdline(cmdline); return args; } void use_kernel_arg(arg_parse_ctx *, int arg_num, const char *arg) { ASSERT_EQ(arg_num, (int)args.size()); args.push_back(arg); } TEST(cmdline, basic) { EXPECT_EQ(parse_wrapper(""), (tvec{})); EXPECT_EQ(parse_wrapper("a"), (tvec{"a"})); EXPECT_EQ(parse_wrapper("a b c"), (tvec{"a", "b", "c"})); } TEST(cmdline, space_should_be_ignored) { EXPECT_EQ(parse_wrapper(" "), (tvec{})); EXPECT_EQ(parse_wrapper(" "), (tvec{})); EXPECT_EQ(parse_wrapper(" a"), (tvec{"a"})); EXPECT_EQ(parse_wrapper("a "), (tvec{"a"})); EXPECT_EQ(parse_wrapper(" a "), (tvec{"a"})); EXPECT_EQ(parse_wrapper(" a b "), (tvec{"a", "b"})); } TEST(cmdline, arg_truncation) { string long_arg; string truncated; string long_line; for (int i = 0; i <= MAX_CMD_ARG_LEN / 10; i++) long_arg += "0123456789"; ASSERT_GT((int)long_arg.size(), MAX_CMD_ARG_LEN); truncated = long_arg; truncated.resize(MAX_CMD_ARG_LEN); EXPECT_EQ(parse_wrapper(long_arg.c_str()), (tvec{truncated})); long_line += " a "; long_line += long_arg; EXPECT_EQ(parse_wrapper(long_line.c_str()), (tvec{"a", truncated})); long_line += " "; EXPECT_EQ(parse_wrapper(long_line.c_str()), (tvec{"a", truncated})); long_line += "last"; EXPECT_EQ(parse_wrapper(long_line.c_str()), (tvec{"a", truncated, "last"})); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/boot/common.h> #include "basic_term.h" #include "vbe.h" #include "common.h" struct ModeInfoBlock *usable_vbe_mode_info_block; struct VbeInfoBlock *vbe_info_block; static int legacy_boot_count_modes(video_mode_t *modes) { int cnt = 0; while (modes[cnt] != INVALID_VIDEO_MODE) cnt++; return cnt; } static void alloc_once_vbe_info_blocks(void) { ulong free_mem; if (!vbe_info_block) { free_mem = get_usable_mem(&g_meminfo, 0x1000, 4 * KB); if (!free_mem) panic("Unable to allocate memory for VbeInfoBlock\n"); vbe_info_block = (void *)free_mem; free_mem = get_usable_mem(&g_meminfo, free_mem + 4 * KB, 4 * KB); if (!free_mem) panic("Unable to allocate memory for struct ModeInfoBlock\n"); usable_vbe_mode_info_block = (void *)free_mem; } } static bool is_mode_usable(struct ModeInfoBlock *mi) { if (!(mi->ModeAttributes & VBE_MODE_ATTRS_GFX_MODE)) return false; if (!(mi->ModeAttributes & VBE_MODE_ATTRS_LINEAR_FB)) return false; if (!(mi->ModeAttributes & VBE_MODE_ATTRS_SUPPORTED)) return false; if (mi->MemoryModel != VB_MEM_MODEL_DIRECT_COLOR) return false; return true; } static int legacy_boot_read_key(void) { return bios_read_char(); } static bool legacy_boot_get_mode_info(video_mode_t m, struct generic_video_mode_info *gi) { struct ModeInfoBlock *mi = usable_vbe_mode_info_block; bool success = false; bzero(gi, sizeof(*gi)); if (m == VGA_COLOR_TEXT_MODE_80x25) { gi->xres = 80; gi->yres = 25; gi->bpp = 4; gi->is_text_mode = true; gi->is_usable = true; success = true; } else if (vbe_get_mode_info(m, mi)) { gi->xres = mi->XResolution; gi->yres = mi->YResolution; gi->bpp = mi->BitsPerPixel; gi->is_text_mode = false; gi->is_usable = is_mode_usable(mi); success = true; } return success; } static void legacy_boot_clear_screen(void) { init_bt(); } static video_mode_t legacy_boot_get_curr_video_mode(void) { return selected_mode; } static bool legacy_boot_set_curr_video_mode(video_mode_t wanted_mode) { if (!vbe_set_video_mode(wanted_mode)) return false; selected_mode = wanted_mode; return true; } static void legacy_boot_get_all_video_modes(video_mode_t **modes, int *count) { video_mode_t *all_modes = NULL; struct VbeInfoBlock *vb; int all_modes_cnt = 0; alloc_once_vbe_info_blocks(); vb = vbe_info_block; if (!vbe_get_info_block(vb)) { if (BOOT_INTERACTIVE) printk("VBE get info failed. Only the text mode is available.\n"); vb = NULL; } if (vb->VbeVersion < 0x200) { if (BOOT_INTERACTIVE) printk("VBE older than 2.0 is not supported.\n"); vb = NULL; } if (vb) { all_modes = get_flat_ptr(vb->VideoModePtr); all_modes_cnt = legacy_boot_count_modes(all_modes); } *modes = all_modes; *count = all_modes_cnt; } static bool legacy_boot_load_kernel_file(const char *path, void **paddr) { if (!load_kernel_file(path)) return false; *paddr = TO_PTR(kernel_file_pa); return true; } static bool legacy_boot_load_initrd(void) { bool success; if (!kernel_file_pa) panic("No loaded kernel file"); success = load_fat_ramdisk(LOADING_INITRD_STR, INITRD_SECTOR, KERNEL_PADDR + get_loaded_kernel_mem_sz(), &initrd_paddr, &initrd_size, true); /* alloc_extra_page */ if (!success) return false; /* Compact initrd's clusters, if necessary */ initrd_size = rd_compact_clusters((void *)initrd_paddr, initrd_size); /* * Increase initrd_size by 1 page in order to allow Tilck's kernel to * align the first data sector, if necessary. */ initrd_size += 4 * KB; return true; } const struct bootloader_intf legacy_boot_intf = { /* Methods */ .read_key = &legacy_boot_read_key, .write_char = &bt_write_char, .clear_screen = &legacy_boot_clear_screen, .set_color = &bt_setcolor, .get_all_video_modes = &legacy_boot_get_all_video_modes, .get_mode_info = &legacy_boot_get_mode_info, .get_curr_video_mode = &legacy_boot_get_curr_video_mode, .set_curr_video_mode = &legacy_boot_set_curr_video_mode, .load_kernel_file = &legacy_boot_load_kernel_file, .load_initrd = &legacy_boot_load_initrd, .get_cmdline_buf = &legacy_boot_get_cmdline_buf, /* Configuration values */ .text_mode = VGA_COLOR_TEXT_MODE_80x25, .efi = false, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/timer.h> #include "pic.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ #define PIC1_COMMAND PIC1 /* PIC1's Command register */ #define PIC1_IMR (PIC1+1) /* PIC1's Interrupt Mask Register */ #define PIC2_COMMAND PIC2 /* PIC2's Command register */ #define PIC2_IMR (PIC2+1) /* PIC2's Interrupt Mask Register */ #define PIC_EOI 0x20 /* End-of-interrupt command code */ #define PIC_SPEC_EOI 0x60 /* Specific End-of-interrupt command */ #define PIC_READ_IRR 0x0a /* OCW3 irq ready next CMD read */ #define PIC_READ_ISR 0x0b /* OCW3 irq service next CMD read */ #define PIC_CASCADE 0x02 /* IR in the master for slave IRQs */ #define ICW1_ICW4 0x01 /* ICW4 (not) needed */ #define ICW1_SINGLE 0x02 /* Single (cascade) mode */ #define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */ #define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */ #define ICW1_INIT 0x10 /* Initialization - required! */ #define ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */ #define ICW4_AUTO 0x02 /* Auto (normal) EOI */ #define ICW4_BUF_SLAVE 0x08 /* Buffered mode/slave */ #define ICW4_BUF_MASTER 0x0C /* Buffered mode/master */ #define ICW4_SFNM 0x10 /* Special fully nested (not) */ static NO_INLINE void pic_io_wait(void) { if (in_hypervisor()) return; delay_us(2); } /* * Initialize the legacy PIT and remap IRQs * * By default, on boot, IRQs 0 to 7 are mapped to IDT entires 8 to 15. This * is a problem in protected mode, because IDT entry 8 is a Double Fault! * Without remapping, every time IRQ0 fires, we'll get a Double Fault, which * is NOT actually what's happening. We send commands to the PIT in order to * make IRQ0 to 15 be remapped to IDT entries 32 to 47. * * NOTE: it leaves all the IRQs masked. */ void init_pic_8259(u8 offset1, u8 offset2) { ASSERT(!are_interrupts_enabled()); outb(PIC1_IMR, 0xff); /* mask everything */ outb(PIC2_IMR, 0xff); /* mask everything */ pic_io_wait(); /* start the initialization sequence - master */ outb(PIC1_COMMAND, ICW1_INIT + ICW1_ICW4); pic_io_wait(); /* set master PIC vector offset */ outb(PIC1_IMR, offset1); pic_io_wait(); /* tell master PIC that there is a slave PIC at IRQ2 */ outb(PIC1_IMR, 1u << PIC_CASCADE); pic_io_wait(); /* set master PIC in default mode */ outb(PIC1_IMR, ICW4_8086); pic_io_wait(); /* start the initialization sequence - slave */ outb(PIC2_COMMAND, ICW1_INIT + ICW1_ICW4); pic_io_wait(); /* set slave PIC vector offset */ outb(PIC2_IMR, offset2); pic_io_wait(); /* tell slave PIC its cascade number */ outb(PIC2_IMR, PIC_CASCADE); pic_io_wait(); /* set slave PIC in default mode */ outb(PIC2_IMR, ICW4_8086); pic_io_wait(); /* wait a lot for the PIC to initialize */ if (!in_hypervisor()) { for (int i = 0; i < 50; i++) pic_io_wait(); } } void pic_send_eoi(int __irq) { ulong var; u8 irq = (u8)__irq; ASSERT(IN_RANGE_INC(__irq, 0, 16)); disable_interrupts(&var); { if (irq < 8) { outb(PIC1_COMMAND, PIC_SPEC_EOI | irq); } else { outb(PIC2_COMMAND, PIC_SPEC_EOI | (irq - 8)); outb(PIC1_COMMAND, PIC_SPEC_EOI | PIC_CASCADE); } } enable_interrupts(&var); } void pic_mask_and_send_eoi(int __irq) { ulong var; u8 irq = (u8)__irq; u8 irq_mask; ASSERT(IN_RANGE_INC(__irq, 0, 16)); disable_interrupts(&var); { if (irq < 8) { irq_mask = inb(PIC1_IMR); irq_mask |= (1 << irq); outb(PIC1_IMR, irq_mask); outb(PIC1_COMMAND, PIC_SPEC_EOI | irq); } else { const u8 ir = irq - 8; irq_mask = inb(PIC2_IMR); irq_mask |= (1 << ir); outb(PIC2_IMR, irq_mask); outb(PIC2_COMMAND, PIC_SPEC_EOI | ir); outb(PIC1_COMMAND, PIC_SPEC_EOI | PIC_CASCADE); } } enable_interrupts(&var); } void irq_set_mask(int irq) { u16 port; ulong var; u8 irq_mask; ASSERT(IN_RANGE_INC(irq, 0, 16)); if (irq == PIC_CASCADE) { /* * This is the cascade irq number where the secondary PIC is attached. * Masking it will also implicitly mask all the IRQs > 7 generated by the * secondary PIC. Therefore, just never mask it. */ return; } if (irq < 8) { port = PIC1_IMR; } else { port = PIC2_IMR; irq -= 8; } disable_interrupts(&var); { irq_mask = inb(port); irq_mask |= (1 << irq); outb(port, irq_mask); } enable_interrupts(&var); } void irq_clear_mask(int irq) { u16 port; ulong var; u8 irq_mask; ASSERT(IN_RANGE_INC(irq, 0, 16)); if (irq < 8) { port = PIC1_IMR; } else { port = PIC2_IMR; irq -= 8; } disable_interrupts(&var); { irq_mask = inb(port); irq_mask &= ~(1 << irq); outb(port, irq_mask); } enable_interrupts(&var); } bool irq_is_masked(int irq) { ulong var; bool res; ASSERT(IN_RANGE_INC(irq, 0, 16)); disable_interrupts(&var); { if (irq < 8) res = inb(PIC1_IMR) & (1 << irq); else res = inb(PIC2_IMR) & (1 << (irq - 8)); } enable_interrupts(&var); return res; } bool pic_is_spur_irq(int irq) { ASSERT(!are_interrupts_enabled()); /* * Check for a spurious wake-up. * * Source: https://wiki.osdev.org/8259_PIC, with some editing. * * When an IRQ occurs, the PIC chip tells the CPU (via. the PIC's INTR * line) that there's an interrupt, and the CPU acknowledges this and * waits for the PIC to send the interrupt vector. This creates a race * condition: if the IRQ disappears after the PIC has told the CPU there's * an interrupt but before the PIC has sent the interrupt vector to the * CPU, then the CPU will be waiting for the PIC to tell it which * interrupt vector but the PIC won't have a valid interrupt vector to * tell the CPU. * * To get around this, the PIC tells the CPU a fake interrupt number. * This is a spurious IRQ. The fake interrupt number is the lowest * priority interrupt number for the corresponding PIC chip (IRQ 7 for the * master PIC, and IRQ 15 for the slave PIC). * * Handling Spurious IRQs * ------------------------- * * For a spurious IRQ, there is no real IRQ and the PIC chip's ISR * (In Service Register) flag for the corresponding IRQ will NOT be set. * This means that the interrupt handler must not send an EOI back to the * PIC to reset the ISR flag, EXCEPT when the spurious IRQ comes from the * 2nd PIC: in that case an EOI must be sent to the master PIC, but NOT * to the slave PIC. */ if (irq == 7) { outb(PIC1_COMMAND, PIC_READ_ISR); u8 isr = inb(PIC1_COMMAND); return !(isr & (1 << 7)); } else if (irq == 15) { outb(PIC2_COMMAND, PIC_READ_ISR); u8 isr = inb(PIC2_COMMAND); if (!(isr & (1 << 7))) { pic_send_eoi(PIC_CASCADE); return true; } } return false; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void realmode_call(void *func, u32 *eax_ref, u32 *ebx_ref, u32 *ecx_ref, u32 *edx_ref, u32 *esi_ref, u32 *edi_ref, u32 *flags_ref); void realmode_call_by_val(void *func, u32 a, u32 b, u32 c, u32 d, u32 si, u32 di); /* * Realmode functions * * Usage: realmode_call(&realmode_func_name, <registers>); */ extern u32 realmode_int_10h; extern u32 realmode_int_13h; extern u32 realmode_int_15h; extern u32 realmode_int_16h; void test_rm_call_working(void); struct VbeFarPtr { u16 off; u16 seg; } PACKED; static ALWAYS_INLINE void *get_flat_ptr(struct VbeFarPtr fp) { return (void *)((u32)fp.off + ((u32)fp.seg) * 16); } char bios_read_char(void); bool read_drive_params(u8 drive, u32 *sectors_per_track, u32 *heads_per_cylinder, u32 *cylinder_count); void read_sectors(u32 dest_paddr, u32 lba_sector, u32 sector_count); <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) ######################## COMMON CODE & DEFINITIONS ############################# set_cross_compiler_userapps() add_definitions(-DUSERMODE_APP) # Force static building for all the user applications set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USERAPPS_CFLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USERAPPS_CFLAGS}") add_custom_target(userapps) include_directories(${CMAKE_SOURCE_DIR}/include) include_directories(${TCROOT}/${ARCH}/zlib/install/include) # [build utils] macro(register_usermode_app) list(APPEND APPS_BIN_FILES "${CMAKE_BINARY_DIR}/userapps/${ARGV0}") add_dependencies(userapps ${ARGV0}) endmacro() macro(add_usermode_app) if (TYPICAL_DEVEL_USERAPPS) set(do_include_this ON) else() set(do_include_this OFF) endif() if ("${ARGV0}" STREQUAL "init") set(do_include_this ON) endif() if ("${ARGV0}" STREQUAL "dp") set(do_include_this ON) endif() if (do_include_this) set(USERAPPS_${ARGV0} ON CACHE BOOL "Include `${ARGV0}` in initrd") endif() unset(do_include_this) if (USERAPPS_${ARGV0}) file( GLOB SOURCES "${ARGV1}${ARGV0}*.c" ) add_executable(${ARGV0} ${SOURCES}) register_usermode_app(${ARGV0}) endif() endmacro() # [/build utils] ################################ TARGETS ####################################### # [simple apps] add_usermode_app(init) add_usermode_app(termtest) add_usermode_app(fbtest) add_usermode_app(play) if (MOD_debugpanel) add_usermode_app(dp) endif() # [/simple apps] # [filedump] file( GLOB FILEDUMP_SOURCES "filedump.c" "${CMAKE_SOURCE_DIR}/common/3rd_party/crc32.c" ) if (TYPICAL_DEVEL_USERAPPS) set(USERAPPS_filedump OFF CACHE BOOL "Include `filedump` in fatpart") else() set(USERAPPS_filedump OFF) endif() if (USERAPPS_filedump) add_executable(filedump ${FILEDUMP_SOURCES}) register_usermode_app(filedump) endif() # [/filedump] # [devshell] file( GLOB DEVSHELL_SOURCES "devshell/*.c" "devshell/${ARCH}.S" "${CMAKE_SOURCE_DIR}/tests/system/*.c" "${CMAKE_SOURCE_DIR}/common/3rd_party/base64.c" ) set(USERAPPS_devshell ON CACHE BOOL "Include `devshell` in fatpart") if (USERAPPS_devshell) add_executable(devshell ${DEVSHELL_SOURCES}) set(DEVSHELL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/devshell) target_include_directories(devshell PUBLIC ${DEVSHELL_SRC_DIR}) target_link_libraries(devshell ${TCROOT}/${ARCH}/zlib/install/lib/libz.a) register_usermode_app(devshell) endif() # [/devshell] # [ncurses test app] if (EXISTS ${NCURSES_INST}/lib/libncurses_g.a) if (TYPICAL_DEVEL_USERAPPS) set(USERAPPS_ncapp OFF CACHE BOOL "Include `ncapp` in fatpart") else() set(USERAPPS_ncapp OFF) endif() if (USERAPPS_ncapp) add_usermode_app(ncapp) target_include_directories(ncapp PUBLIC ${NCURSES_INST}/include) target_link_libraries(ncapp ${NCURSES_INST}/lib/libncurses_g.a) endif() endif() # [/ncurses test app] # [extra] # This macro makes the integration with extra apps much easier. # It's enough for the external app to just add a call to tilck_add_extra_app() # with the full-path of a binary in order to that deliverable to become a file # dependency of Tilck's main target (the image) and get that deliverable copied # in /usr/bin (in Tilck's fatpart). # Example: https://github.com/vvaltchev/tfblib set(USERAPPS_extra ON CACHE BOOL "Build all apps in userapps/extra") macro(tilck_add_extra_app) set(EXTRA_APPS_LIST_copy ${EXTRA_APPS_LIST}) list(APPEND EXTRA_APPS_LIST_copy ${ARGV0}) set(EXTRA_APPS_LIST ${EXTRA_APPS_LIST_copy}) set(EXTRA_APPS_LIST ${EXTRA_APPS_LIST_copy} PARENT_SCOPE) file(RELATIVE_PATH relPath "${CMAKE_BINARY_DIR}" "${ARGV0}") message(STATUS "Adding EXTRA APP: ${relPath}") endmacro() if (USERAPPS_extra) add_subdirectory(extra) endif() set(USERAPPS_FILES_LIST ${APPS_BIN_FILES} PARENT_SCOPE) set(EXTRA_APPS_LIST ${EXTRA_APPS_LIST} PARENT_SCOPE) # [/extra] # [busybox] if (EXISTS ${BUSYBOX_CONFIG}) execute_process( COMMAND ${CMAKE_COMMAND} -E compare_files ${BUSYBOX_CONFIG} ${CMAKE_SOURCE_DIR}/other/busybox.config RESULT_VARIABLE result ) if (result EQUAL 1) set(msg1 "") string(CONCAT msg1 "The busybox build in the toolchain has a " "different config than the one in the source. " "This might have undesired effects. " "Please update your busybox build.") if ("$ENV{CIRCLECI}" STREQUAL "" AND "$ENV{TRAVIS}" STREQUAL "" AND "$ENV{CI}" STREQUAL "") set(msg2 "") string(CONCAT msg2 "How to do that: \n" " 1) rm -rf ${TCROOT_REL}/${ARCH}/busybox\n" " 2) ${BTC_SCRIPT_REL} -s build_busybox") message(FATAL_ERROR "\n${msg1}\n${msg2}") else() message(WARNING "\n${msg1}") endif() elseif (result EQUAL 0) # Nothing to do, everything is fine :-) else() message(FATAL_ERROR "Error while comparing the busybox config files.") endif() else() message(WARNING "\nNo busybox in toolchain.") endif() # [/busybox] <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define EFLAGS_CF 0x0001 #define EFLAGS_PF 0x0004 #define EFLAGS_AF 0x0010 #define EFLAGS_ZF 0x0040 #define EFLAGS_SF 0x0080 #define EFLAGS_TF 0x0100 #define EFLAGS_IF 0x0200 #define EFLAGS_DF 0x0400 #define EFLAGS_OF 0x0800 #define EFLAGS_NT 0x4000 #define EFLAGS_RF 0x10000 #define EFLAGS_VM 0x20000 #define EFLAGS_AC 0x40000 #define EFLAGS_VIF 0x80000 #define EFLAGS_VIP 0x100000 #define EFLAGS_ID 0x200000 #define EFLAGS_IOPL 0x3000 #define MSR_IA32_SYSENTER_CS 0x174 #define MSR_IA32_SYSENTER_ESP 0x175 #define MSR_IA32_SYSENTER_EIP 0x176 #define MSR_IA32_MTRRCAP 0x0fe #define MSR_IA32_MTRR_DEF_TYPE 0x2ff #define MSR_MTRRphysBase0 0x200 #define MSR_MTRRphysMask0 0x201 #define MSR_MTRRphysBase1 0x202 #define MSR_MTRRphysMask1 0x203 #define MSR_MTRRphysBase2 0x204 #define MSR_MTRRphysMask2 0x205 #define MSR_MTRRphysBase3 0x206 #define MSR_MTRRphysMask3 0x207 #define MSR_MTRRphysBase4 0x208 #define MSR_MTRRphysMask4 0x209 #define MSR_MTRRphysBase5 0x20a #define MSR_MTRRphysMask5 0x20b #define MSR_MTRRphysBase6 0x20c #define MSR_MTRRphysMask6 0x20d #define MSR_MTRRphysBase7 0x20e #define MSR_MTRRphysMask7 0x20f #define MSR_IA32_PAT 0x277 #define CR0_PE (1u << 0) #define CR0_MP (1u << 1) #define CR0_EM (1u << 2) #define CR0_TS (1u << 3) #define CR0_ET (1u << 4) #define CR0_NE (1u << 5) #define CR0_WP (1u << 16) #define CR0_AM (1u << 18) #define CR0_NW (1u << 29) #define CR0_CD (1u << 30) #define CR0_PG (1u << 31) #define CR4_PSE (1u << 4) #define CR4_PAE (1u << 5) #define CR4_PGE (1u << 7) #define CR4_OSFXSR (1u << 9) #define CR4_OSXMMEXCPT (1u << 10) #define CR4_OSXSAVE (1u << 18) #define XCR0_X87 (1u << 0) #define XCR0_SSE (1u << 1) #define XCR0_AVX (1u << 2) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <random> #include <memory> #include <set> #include <unordered_set> #include <inttypes.h> #include <gtest/gtest.h> #include "trivial_allocator.h" extern "C" { #include <tilck/kernel/bintree.h> #if defined(__i386__) || defined(__x86_64) #include <tilck/common/arch/generic_x86/x86_utils.h> #else /* TODO: actually implement an equivalent of RDTSC for AARCH64 */ static inline ulong RDTSC(void) { return 0; } #endif } using namespace std; struct int_struct { int val; struct bintree_node node; int_struct() = default; int_struct(int v) { val = v; bintree_node_init(&node); } bool operator<(const int_struct& rhs) const { return val < rhs.val; } bool operator<(const int& rhs) const { return this->val < rhs; } }; static long my_cmpfun(const void *a, const void *b) { int_struct *v1 = (int_struct*)a; int_struct *v2 = (int_struct*)b; return v1->val - v2->val; } /* * -------------------------------------------------------------------------- * DEBUGGING UTILS * -------------------------------------------------------------------------- */ static void indent(int level) { for (int i=0; i < level; i++) printf(" "); } static void node_dump(int_struct *obj, int level) { if (!obj) return; indent(level); struct bintree_node *n = &obj->node; printf("%i [%i]\n", obj->val, n->height); if (!n->left_obj && !n->right_obj) return; if (n->left_obj) { node_dump((int_struct*)n->left_obj, level+1); } else { indent(level+1); printf("L%i\n", obj->val); } if (n->right_obj) { node_dump((int_struct*)n->right_obj, level+1); } else { indent(level+1); printf("R%i\n", obj->val); } } struct visit_ctx { int *arr; int arr_size; int curr_size; }; static int visit_add_val_to_arr(void *obj, void *arg) { int_struct *s = (int_struct *)obj; visit_ctx *ctx = (visit_ctx *)arg; assert(ctx->curr_size < ctx->arr_size); ctx->arr[ctx->curr_size++] = s->val; return 0; } static void in_order_visit(int_struct *obj, int *arr, int arr_size, bool reverse = false) { visit_ctx ctx = {arr, arr_size, 0}; if (!reverse) bintree_in_order_visit(obj, visit_add_val_to_arr, (void *)&ctx, int_struct, node); else bintree_in_rorder_visit(obj, visit_add_val_to_arr, (void *)&ctx, int_struct, node); } static void sbs_in_order_visit(int_struct *obj, int *arr, int arr_size, bool reverse = false) { visit_ctx ctx = {arr, arr_size, 0}; struct bintree_walk_ctx walk_ctx; bintree_in_order_visit_start(&walk_ctx, obj, int_struct, node, reverse); while ((obj = (int_struct *)bintree_in_order_visit_next(&walk_ctx))) { visit_add_val_to_arr(obj, &ctx); } } static bool check_binary_search_tree(int_struct *obj) { if (obj->node.left_obj) { int leftval = ((int_struct*)(obj->node.left_obj))->val; if (leftval >= obj->val) { printf("left child of %i has value %i, which violates BST\n", obj->val, leftval); return false; } if (!check_binary_search_tree((int_struct*)obj->node.left_obj)) return false; } if (obj->node.right_obj) { int rightval = ((int_struct*)(obj->node.right_obj))->val; if (rightval <= obj->val) { printf("right child of %i has value %i, which violates BST\n", obj->val, rightval); return false; } if (!check_binary_search_tree((int_struct*)obj->node.right_obj)) return false; } return true; } static bool is_sorted(int *arr, int size) { if (size <= 1) return true; for (int i = 1; i < size; i++) { if (arr[i-1] > arr[i]) return false; } return true; } static bool is_rsorted(int *arr, int size) { if (size <= 1) return true; for (int i = 1; i < size; i++) { if (arr[i-1] < arr[i]) return false; } return true; } static void dump_array(int *arr, int size) { for (int i = 0; i < size; i++) { printf("%i\n", arr[i]); } printf("\n"); } static void generate_random_array(default_random_engine &e, lognormal_distribution<> &dist, int *arr, int arr_size) { unordered_set<int> s; for (int i = 0; i < arr_size;) { int candidate = dist(e); if (!IN_RANGE_INC(candidate, 1, 1000 * 1000 * 1000)) continue; if (s.insert(candidate).second) { arr[i++] = candidate; } } assert(s.size() == (size_t)arr_size); for (int i = 0; i < arr_size; i++) { assert(arr[i] > 0); } } // TODO: re-write this function in a better way. int check_height(int_struct *obj, bool *failed) { if (!obj) { if (failed) *failed=false; return -1; } assert(obj->node.left_obj != obj); assert(obj->node.right_obj != obj); bool fail1 = false, fail2 = false; int lh = check_height((int_struct*)obj->node.left_obj, &fail1); int rh = check_height((int_struct*)obj->node.right_obj, &fail2); if (fail1 || fail2) { if (failed) { *failed = true; return -1000; } printf("Tree:\n"); node_dump(obj, 0); NOT_REACHED(); } if ( obj->node.height != ( max(lh, rh) + 1 ) ) { printf("[ERROR] obj->node.height != ( max(lh, rh) + 1 ); " "Node val: %i. H: %i vs %i\n", obj->val, obj->node.height, max(lh, rh) + 1); printf("Tree:\n"); node_dump(obj, 0); if (failed != NULL) { *failed = true; return -1000; } NOT_REACHED(); } // balance condition. if (!IN_RANGE_INC(lh-rh, -1, 1)) { printf("[ERROR] lh-rh is %i for node %i; lh:%i, rh:%i\n", lh-rh, obj->val, lh, rh); printf("Tree:\n"); node_dump(obj, 0); if (failed != NULL) { *failed = true; return -1000; } NOT_REACHED(); } if (failed != NULL) *failed = false; return max(lh, rh) + 1; } static long cmpfun_objval(const void *obj, const void *valptr) { int_struct *s = (int_struct*)obj; int ival = *(int*)valptr; return s->val - ival; } #define MAX_ELEMS (1000*1000) struct test_data { int arr[MAX_ELEMS]; int ordered_nums[MAX_ELEMS]; int_struct nodes[MAX_ELEMS]; }; void check_height_vs_elems(int_struct *obj, int elems) { /* * According to wikipedia: * https://en.wikipedia.org/wiki/AVL_tree * * max_h is the upper-limit for the function height(N) for an AVL tree. */ const int max_h = ceil(1.44 * log2(elems+2) - 0.328); if (obj->node.height >= max_h) { FAIL() << "tree's height (" << obj->node.height << ") exceeds the maximum expected: " << max_h-1; } } /* * -------------------------------------------------------------------------- * TESTS * -------------------------------------------------------------------------- */ TEST(avl_bintree, in_order_visit_with_callback) { constexpr const int elems = 32; int_struct arr[elems]; int_struct *root = NULL; for (int i = 0; i < elems; i++) arr[i] = int_struct(i + 1); for (int i = 0; i < elems; i++) bintree_insert(&root, &arr[i], my_cmpfun, int_struct, node); int ordered_nums[elems]; in_order_visit(root, ordered_nums, elems, false); ASSERT_TRUE(is_sorted(ordered_nums, elems)); int rev_ordered_nums[elems]; in_order_visit(root, rev_ordered_nums, elems, true); ASSERT_TRUE(is_rsorted(rev_ordered_nums, elems)); } TEST(avl_bintree, in_order_visit_step_by_step) { constexpr const int elems = 32; int_struct arr[elems]; int_struct *root = NULL; for (int i = 0; i < elems; i++) arr[i] = int_struct(i + 1); for (int i = 0; i < elems; i++) bintree_insert(&root, &arr[i], my_cmpfun, int_struct, node); int ordered_nums[elems]; sbs_in_order_visit(root, ordered_nums, elems, false); ASSERT_TRUE(is_sorted(ordered_nums, elems)); int rev_ordered_nums[elems]; sbs_in_order_visit(root, rev_ordered_nums, elems, true); ASSERT_TRUE(is_rsorted(rev_ordered_nums, elems)); } TEST(avl_bintree, first_last_obj) { constexpr const int elems = 32; int_struct arr[elems]; int_struct *root = NULL; for (int i = 0; i < elems; i++) arr[i] = int_struct(i + 1); for (int i = 0; i < elems; i++) bintree_insert(&root, &arr[i], my_cmpfun, int_struct, node); int_struct *f = (int_struct *)bintree_get_first_obj(root, int_struct, node); ASSERT_TRUE(f != NULL); ASSERT_TRUE(f == &arr[0]); int_struct *l = (int_struct *)bintree_get_last_obj(root, int_struct, node); ASSERT_TRUE(l != NULL); ASSERT_TRUE(l == &arr[elems - 1]); } static void test_insert_rand_data(int iters, int elems, bool slow_checks) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); lognormal_distribution<> dist(6.0, elems <= 100*1000 ? 3 : 5); unique_ptr<test_data> data{new test_data}; for (int iter = 0; iter < iters; iter++) { int_struct *root = &data->nodes[0]; generate_random_array(e, dist, data->arr, elems); if (iter == 0) { cout << "[ INFO ] random seed: " << seed << endl; cout << "[ INFO ] sample numbers: "; for (int i = 0; i < 20 && i < elems; i++) { printf("%i ", data->arr[i]); } printf("\n"); } for (int i = 0; i < elems; i++) { data->nodes[i] = int_struct(data->arr[i]); bintree_insert(&root, &data->nodes[i], my_cmpfun, int_struct, node); if (slow_checks && !check_binary_search_tree(root)) { node_dump(root, 0); FAIL() << "[iteration " << iter << "/" << iters << "] while inserting node " << data->arr[i] << endl; } } ASSERT_NO_FATAL_FAILURE({ check_height_vs_elems(root, elems); }); check_height(root, NULL); in_order_visit(root, data->ordered_nums, elems); if (!is_sorted(data->ordered_nums, elems)) { // For a few elems, it makes sense to print more info. if (elems <= 100) { printf("FAIL. Original:\n"); dump_array(data->arr, elems); printf("Ordered:\n"); dump_array(data->ordered_nums, elems); printf("Tree:\n"); node_dump(root, 0); } FAIL() << "an in-order visit did not produce an ordered-array"; } int elems_to_find = slow_checks ? elems : elems/10; for (int i = 0; i < elems_to_find; i++) { void *res = bintree_find(root, &data->arr[i], cmpfun_objval, int_struct, node); ASSERT_TRUE(res != NULL); ASSERT_TRUE(((int_struct*)res)->val == data->arr[i]); } } } TEST(avl_bintree, insert_quick_test) { test_insert_rand_data(100, 1000, true); } void remove_rand_data(const int elems, const int iters) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); lognormal_distribution<> dist(6.0, elems <= 100*1000 ? 3 : 5); unique_ptr<test_data> data{new test_data}; for (int iter = 0; iter < iters; iter++) { int_struct *root = &data->nodes[0]; generate_random_array(e, dist, data->arr, elems); for (int i = 0; i < elems; i++) { data->nodes[i] = int_struct(data->arr[i]); } if (iter == 0) { cout << "[ INFO ] random seed: " << seed << endl; cout << "[ INFO ] sample numbers: "; for (int i = 0; i < 20 && i < elems; i++) { printf("%i ", data->arr[i]); } printf("\n"); } for (int i = 0; i < elems; i++) { bintree_insert(&root, &data->nodes[i], my_cmpfun, int_struct, node); } for (int i = 0; i < elems; i++) { void *res = bintree_find(root, &data->arr[i], cmpfun_objval, int_struct, node); ASSERT_TRUE(res != NULL); ASSERT_TRUE(((int_struct*)res)->val == data->arr[i]); void *removed_obj = bintree_remove(&root, &data->arr[i], cmpfun_objval, int_struct, node); ASSERT_TRUE(removed_obj != NULL); ASSERT_TRUE(((int_struct*)removed_obj)->val == data->arr[i]); const int new_elems = elems - i - 1; if (new_elems == 0) { ASSERT_TRUE(root == NULL); break; } ASSERT_NO_FATAL_FAILURE({ check_height_vs_elems(root, elems); }); check_height(root, NULL); in_order_visit(root, data->ordered_nums, new_elems); if (!is_sorted(data->ordered_nums, new_elems)) { // For a few elems, it makes sense to print more info. if (elems <= 100) { printf("FAIL. Original:\n"); dump_array(data->arr, new_elems); printf("Ordered:\n"); dump_array(data->ordered_nums, new_elems); printf("Tree:\n"); node_dump(root, 0); } FAIL() << "an in-order visit did not produce " << "an ordered-array, after removing " << data->arr[i]; } } } } TEST(avl_bintree, remove_quick_test) { remove_rand_data(100, 1000); } TEST(avl_bintree, DISABLED_remove_1000_elems_100_iters) { remove_rand_data(1000, 100); } TEST(avl_bintree, DISABLED_remove_1k_elems_1k_iters) { remove_rand_data(1000, 1000); } TEST(avl_bintree, DISABLED_remove_10k_elems_10_iters) { remove_rand_data(10*1000, 10); } TEST(avl_bintree, DISABLED_test_insert_rand_data_tree_10k_iters_100_elems) { test_insert_rand_data(10*1000, 100, true); } TEST(avl_bintree, DISABLED_test_insert_rand_data_tree_10_iters_100k_elems) { test_insert_rand_data(10, 100*1000, false); } TEST(avl_bintree, DISABLED_test_insert_rand_data_tree_1m_elems) { test_insert_rand_data(1, 1000*1000, false); } template <bool use_std_set = false> static void benchmark_avl_bintree_rand_data(const int elems, const int iters) { // prefer always the same seed for comparing results const unsigned long seed = 1094638824; default_random_engine e(seed); lognormal_distribution<> dist(6.0, elems <= 100*1000 ? 3 : 5); unique_ptr<test_data> data{new test_data}; u64 tot = 0; for (int iter = 0; iter < iters; iter++) { int_struct *root = &data->nodes[0]; generate_random_array(e, dist, data->arr, elems); for (int i = 0; i < elems; i++) { data->nodes[i] = int_struct(data->arr[i]); } set< int_struct, std::less<int_struct>, MyTrivialAllocator<int_struct> > S( ((std::less<int_struct>())), ((MyTrivialAllocator<int_struct>( use_std_set ? 1024 * 1024 : 0 ))) ); u64 start = RDTSC(); for (int i = 0; i < elems; i++) { if (use_std_set) { S.insert(data->nodes[i]); } else { bintree_insert(&root, &data->nodes[i], my_cmpfun, int_struct, node); } } for (int i = 0; i < elems; i++) { if (use_std_set) { auto it = S.find(data->arr[i]); VERIFY(it != S.end()); VERIFY(it->val == data->arr[i]); size_t count = S.erase(data->arr[i]); VERIFY(count > 0); } else { void *res = bintree_find(root, &data->arr[i], cmpfun_objval, int_struct, node); VERIFY(res != NULL); VERIFY(((int_struct*)res)->val == data->arr[i]); void *removed_obj = bintree_remove(&root, &data->arr[i], cmpfun_objval, int_struct, node); VERIFY(removed_obj != NULL); VERIFY(((int_struct*)removed_obj)->val == data->arr[i]); } } u64 end = RDTSC(); tot += end - start; } unsigned long cycles_per_iter = (unsigned long)(tot / iters); unsigned long cycles_per_elem = cycles_per_iter / elems; printf("[ INFO ] Avg. cycles per elem: %lu\n", cycles_per_elem); } TEST(avl_bintree, DISABLED_benchmark) { benchmark_avl_bintree_rand_data<false>(10000, 100); } TEST(avl_bintree, DISABLED_benchmark_std_set) { benchmark_avl_bintree_rand_data<true>(10000, 100); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/user.h> #include <tilck/kernel/vdso.h> #include <tilck/mods/tracing.h> #include "gdt_int.h" void soft_interrupt_resume(void); //#define DEBUG_printk printk #define DEBUG_printk(...) STATIC_ASSERT( OFFSET_OF(struct task, fault_resume_regs) == TI_F_RESUME_RS_OFF ); STATIC_ASSERT( OFFSET_OF(struct task, faults_resume_mask) == TI_FAULTS_MASK_OFF ); STATIC_ASSERT(TOT_PROC_AND_TASK_SIZE <= 1024); void task_info_reset_kernel_stack(struct task *ti) { ulong bottom = (ulong)ti->kernel_stack + KERNEL_STACK_SIZE - 1; ti->state_regs = (regs_t *)(bottom & POINTER_ALIGN_MASK); } static inline void push_on_stack(ulong **stack_ptr_ref, ulong val) { (*stack_ptr_ref)--; // Decrease the value of the stack pointer **stack_ptr_ref = val; // *stack_ptr = val } static void push_on_stack2(pdir_t *pdir, ulong **stack_ptr_ref, ulong val) { // Decrease the value of the stack pointer (*stack_ptr_ref)--; // *stack_ptr = val debug_checked_virtual_write(pdir, *stack_ptr_ref, &val, sizeof(ulong)); } static inline void push_on_user_stack(regs_t *r, ulong val) { push_on_stack((ulong **)&r->useresp, val); } static void push_string_on_user_stack(regs_t *r, const char *str) { const size_t len = strlen(str) + 1; // count also the '\0' const size_t aligned_len = round_down_at(len, sizeof(ulong)); const size_t rem = len - aligned_len; r->useresp -= aligned_len + (rem > 0 ? sizeof(ulong) : 0); memcpy((void *)r->useresp, str, aligned_len); if (rem > 0) { ulong smallbuf = 0; memcpy(&smallbuf, str + aligned_len, rem); memcpy((void *)(r->useresp + aligned_len), &smallbuf, sizeof(smallbuf)); } } static int push_args_on_user_stack(regs_t *r, const char *const *argv, u32 argc, const char *const *env, u32 envc) { ulong pointers[32]; ulong env_pointers[96]; if (argc > ARRAY_SIZE(pointers)) return -E2BIG; if (envc > ARRAY_SIZE(env_pointers)) return -E2BIG; // push argv data on stack (it could be anywhere else, as well) for (u32 i = 0; i < argc; i++) { push_string_on_user_stack(r, READ_PTR(&argv[i])); pointers[i] = r->useresp; } // push env data on stack (it could be anywhere else, as well) for (u32 i = 0; i < envc; i++) { push_string_on_user_stack(r, READ_PTR(&env[i])); env_pointers[i] = r->useresp; } // push the env array (in reverse order) push_on_user_stack(r, 0); /* * 2nd mandatory NULL pointer: after the 'env' * pointers there could additional aux information * that some libc implementations check for. * Therefore, it is essential to add another NULL * after the env pointers to inform the libc impl * that no such information exist. For more info, * check __init_libc() in libmusl. */ push_on_user_stack(r, 0); // mandatory final NULL pointer (end of 'env' ptrs) for (u32 i = envc; i > 0; i--) { push_on_user_stack(r, env_pointers[i - 1]); } // push the argv array (in reverse order) push_on_user_stack(r, 0); // mandatory final NULL pointer (end of 'argv') for (u32 i = argc; i > 0; i--) { push_on_user_stack(r, pointers[i - 1]); } // push argc as last (since it will be the first to be pop-ed) push_on_user_stack(r, (ulong)argc); return 0; } static int save_regs_on_user_stack(regs_t *r) { ulong new_useresp = r->useresp; int rc; /* Align the user ESP */ new_useresp &= ALIGNED_MASK(USERMODE_STACK_ALIGN); /* Allocate space on the user stack */ new_useresp -= sizeof(*r); /* Save the registers to the user stack */ rc = copy_to_user(TO_PTR(new_useresp), r, sizeof(*r)); if (rc) { /* Oops, stack overflow */ return -EFAULT; } /* Now, after we saved the registers, update r->useresp */ r->useresp = new_useresp; return 0; } static void restore_regs_from_user_stack(regs_t *r) { ulong old_regs = r->useresp; int rc; /* Restore the registers we previously changed */ rc = copy_from_user(r, TO_PTR(old_regs), sizeof(*r)); if (rc) { /* Oops, something really weird happened here */ enable_preemption(); terminate_process(0, SIGSEGV); NOT_REACHED(); } /* Don't trust user space */ r->cs = X86_USER_CODE_SEL; r->eflags |= EFLAGS_IF; } void setup_pause_trampoline(regs_t *r) { r->eip = pause_trampoline_user_vaddr; } /* See the comments below in setup_sig_handler() */ #define SIG_HANDLER_ALIGN_ADJUST \ ( \ ( \ + USERMODE_STACK_ALIGN \ - sizeof(regs_t) /* regs */ \ - sizeof(ulong) /* signum */ \ ) % USERMODE_STACK_ALIGN \ ) int setup_sig_handler(struct task *ti, enum sig_state sig_state, regs_t *r, ulong user_func, int signum) { if (ti->nested_sig_handlers == 0) { int rc; if (sig_state == sig_pre_syscall) r->eax = (ulong) -EINTR; if ((rc = save_regs_on_user_stack(r)) < 0) return rc; } r->eip = user_func; r->useresp -= SIG_HANDLER_ALIGN_ADJUST; push_on_user_stack(r, (ulong)signum); push_on_user_stack(r, post_sig_handler_user_vaddr); ti->nested_sig_handlers++; /* * Check that the stack pointer + 4 is aligned at a 16-bytes boundary. * The reason for that +4 (word size) is that the stack must be aligned * BEFORE the call instruction, not after it. So, at the first instruction, * the callee will see its ESP in hex ending with a "c", like this: * * 0xbfffce2c # if we add +4, it's aligned at 16 * * and NOT like this: * * 0xbfffce20 # it's already aligned at 16 */ ASSERT(((r->useresp + sizeof(ulong)) & (USERMODE_STACK_ALIGN - 1)) == 0); return 0; } ulong sys_rt_sigreturn(void) { ASSERT(!is_preemption_enabled()); /* Thanks to SYSFL_NO_PREEMPT */ struct task *curr = get_curr_task(); regs_t *r = curr->state_regs; if (LIKELY(curr->nested_sig_handlers > 0)) { trace_printk(10, "Done running signal handler"); r->useresp += sizeof(ulong) /* compensate the "push signum" above */ + SIG_HANDLER_ALIGN_ADJUST; /* compensate the forced stack alignment */ if (!process_signals(curr, sig_in_return, r)) { if (curr->in_sigsuspend) { memcpy(curr->sa_mask, curr->sa_old_mask, sizeof(curr->sa_mask)); curr->in_sigsuspend = false; } restore_regs_from_user_stack(r); } curr->nested_sig_handlers--; ASSERT(curr->nested_sig_handlers >= 0); } else { /* An user process tried to call directly rt_sigreturn() */ r->eax = (ulong) -ENOSYS; } /* * NOTE: we must return r->eax because syscalls are called by handle_syscall * in a generic way like: * * r->eax = (ulong) fptr(...) * * Returning anything else than r->eax would change that register and we * don't wanna do that in a special NORETURN function such this. Here we're * supposed to restore all the user registers as they were before the signal * handler ran. Failing to do that, has an especially visible effect when * a signal handler run after preempting running code in userspace: in that * case, no syscall was made and no register is expected to ever change, * exactly like in context switch. */ return r->eax; } NODISCARD int kthread_create2(kthread_func_ptr func, const char *name, int fl, void *arg) { struct task *ti; int tid, ret = -ENOMEM; ASSERT(name != NULL); regs_t r = { .kernel_resume_eip = (ulong)&soft_interrupt_resume, .custom_flags = 0, .gs = X86_KERNEL_DATA_SEL, .fs = X86_KERNEL_DATA_SEL, .es = X86_KERNEL_DATA_SEL, .ds = X86_KERNEL_DATA_SEL, .edi = 0, .esi = 0, .ebp = 0, .esp = 0, .ebx = 0, .edx = 0, .ecx = 0, .eax = 0, .int_num = 0, .err_code = 0, .eip = (ulong)func, .cs = X86_KERNEL_CODE_SEL, .eflags = 0x2 /* reserved, should be always set */ | EFLAGS_IF, .useresp = 0, .ss = X86_KERNEL_DATA_SEL, }; disable_preemption(); tid = create_new_kernel_tid(); if (tid < 0) { ret = -EAGAIN; goto end; } ti = allocate_new_thread(kernel_process->pi, tid, !!(fl & KTH_ALLOC_BUFS)); if (!ti) goto end; ASSERT(is_kernel_thread(ti)); if (*name == '&') name++; /* see the macro kthread_create() */ ti->kthread_name = name; ti->state = TASK_STATE_RUNNABLE; ti->running_in_kernel = true; task_info_reset_kernel_stack(ti); /* * 1) Push into the stack, function's argument, `arg`. * * 2) Push the address of kthread_exit() into thread's stack in order to it * to be called after thread's function returns. It's AS IF kthread_exit * called the thread `func` with a CALL instruction before doing anything * else. That allows the RET by `func` to jump at the begging of * kthread_exit(). * * 3) Reserve space for the regs on the stack * 4) Copy the actual regs to the new stack */ push_on_stack((ulong **)&ti->state_regs, (ulong)arg); push_on_stack((ulong **)&ti->state_regs, (ulong)&kthread_exit); ti->state_regs = (void *)ti->state_regs - sizeof(regs_t) + 8; memcpy(ti->state_regs, &r, sizeof(r) - 8); ret = ti->tid; if (fl & KTH_WORKER_THREAD) ti->worker_thread = arg; /* * After the following call to add_task(), given that preemption is enabled, * there is NO GUARANTEE that the `tid` returned by this function will still * belong to a valid kernel thread. For example, the kernel thread might run * and terminate before the caller has the chance to run. Therefore, it is up * to the caller to be prepared for that. */ add_task(ti); enable_preemption(); end: return ret; /* tid or error */ } void kthread_exit(void) { /* * WARNING: DO NOT USE ANY STACK VARIABLES HERE. * * The call to switch_to_initial_kernel_stack() will mess-up your whole stack * (but that's what it is supposed to do). In this function, only global * variables can be accessed. * * This function gets called automatically when a kernel thread function * returns, but it can be called manually as well at any point. */ disable_preemption(); wake_up_tasks_waiting_on(get_curr_task(), task_died); task_change_state(get_curr_task(), TASK_STATE_ZOMBIE); /* WARNING: the following call discards the whole stack! */ switch_to_initial_kernel_stack(); /* Free the heap allocations used by the task, including the kernel stack */ free_mem_for_zombie_task(get_curr_task()); /* Remove the from the scheduler and free its struct */ remove_task(get_curr_task()); disable_interrupts_forced(); { set_curr_task(kernel_process); } enable_interrupts_forced(); do_schedule(); } static void setup_usermode_task_regs(regs_t *r, void *entry, void *stack_addr) { *r = (regs_t) { .kernel_resume_eip = (ulong)&soft_interrupt_resume, .custom_flags = 0, .gs = X86_USER_DATA_SEL, .fs = X86_USER_DATA_SEL, .es = X86_USER_DATA_SEL, .ds = X86_USER_DATA_SEL, .edi = 0, .esi = 0, .ebp = 0, .esp = 0, .ebx = 0, .edx = 0, .ecx = 0, .eax = 0, .int_num = 0, .err_code = 0, .eip = (ulong)entry, .cs = X86_USER_CODE_SEL, .eflags = 0x2 /* reserved, should be always set */ | EFLAGS_IF, .useresp = (ulong)stack_addr, .ss = X86_USER_DATA_SEL, }; } static int NO_INLINE setup_first_process(pdir_t *pdir, struct task **ti_ref) { struct task *ti; struct process *pi; VERIFY(create_new_pid() == 1); if (!(ti = allocate_new_process(kernel_process, 1, pdir))) return -ENOMEM; pi = ti->pi; pi->pgid = 1; pi->sid = 1; pi->umask = 0022; ti->state = TASK_STATE_RUNNING; add_task(ti); memcpy(pi->str_cwd, "/", 2); *ti_ref = ti; return 0; } void finalize_usermode_task_setup(struct task *ti, regs_t *user_regs) { ASSERT(!is_preemption_enabled()); ASSERT_TASK_STATE(ti->state, TASK_STATE_RUNNING); task_change_state(ti, TASK_STATE_RUNNABLE); ti->running_in_kernel = false; ASSERT(ti->kernel_stack != NULL); task_info_reset_kernel_stack(ti); ti->state_regs--; // make room for a regs_t struct in the stack *ti->state_regs = *user_regs; // copy the regs_t struct we prepared before } int setup_process(struct elf_program_info *pinfo, struct task *ti, const char *const *argv, const char *const *env, struct task **ti_ref, regs_t *r) { int rc = 0; u32 argv_elems = 0; u32 env_elems = 0; pdir_t *old_pdir; struct process *pi = NULL; ASSERT(!is_preemption_enabled()); *ti_ref = NULL; setup_usermode_task_regs(r, pinfo->entry, pinfo->stack); /* Switch to the new page directory (we're going to write on user's stack) */ old_pdir = get_curr_pdir(); set_curr_pdir(pinfo->pdir); while (READ_PTR(&argv[argv_elems])) argv_elems++; while (READ_PTR(&env[env_elems])) env_elems++; if ((rc = push_args_on_user_stack(r, argv, argv_elems, env, env_elems))) goto err; if (UNLIKELY(!ti)) { /* Special case: applies only for `init`, the first process */ if ((rc = setup_first_process(pinfo->pdir, &ti))) goto err; ASSERT(ti != NULL); pi = ti->pi; } else { /* * Common case: we're creating a new process using the data structures * and the PID from a forked child (the `ti` task). */ pi = ti->pi; if (!pi->vforked) { remove_all_user_zero_mem_mappings(pi); remove_all_file_mappings(pi); process_free_mappings_info(pi); ASSERT(old_pdir == pi->pdir); pdir_destroy(pi->pdir); if (pi->elf) release_subsys_flock(pi->elf); } pi->pdir = pinfo->pdir; old_pdir = NULL; /* NOTE: not calling arch_specific_free_task() */ VERIFY(arch_specific_new_task_setup(ti, NULL)); arch_specific_free_proc(pi); arch_specific_new_proc_setup(pi, NULL); } pi->elf = pinfo->lf; *ti_ref = ti; return 0; err: ASSERT(rc != 0); if (old_pdir) { set_curr_pdir(old_pdir); pdir_destroy(pinfo->pdir); } return rc; } void save_current_task_state(regs_t *r) { struct task *curr = get_curr_task(); ASSERT(curr != NULL); curr->state_regs = r; } /* * Sched functions that are here because of arch-specific statements. */ void set_current_task_in_user_mode(void) { ASSERT(!is_preemption_enabled()); struct task *curr = get_curr_task(); curr->running_in_kernel = false; task_info_reset_kernel_stack(curr); set_kernel_stack((u32)curr->state_regs); } static inline bool is_fpu_enabled_for_task(struct task *ti) { return get_task_arch_fields(ti)->aligned_fpu_regs && (ti->state_regs->custom_flags & REGS_FL_FPU_ENABLED); } static inline void save_curr_fpu_ctx_if_enabled(void) { if (is_fpu_enabled_for_task(get_curr_task())) { hw_fpu_enable(); save_current_fpu_regs(false); hw_fpu_disable(); } } static inline void switch_to_task_pop_nested_interrupts(void) { if (KRN_TRACK_NESTED_INTERR) { ASSERT(get_curr_task() != NULL); if (get_curr_task()->running_in_kernel) if (!is_kernel_thread(get_curr_task())) nested_interrupts_drop_top_syscall(); } } static inline void adjust_nested_interrupts_for_task_in_kernel(struct task *ti) { /* * The new task was running in kernel when it was preempted. * * In theory, there's nothing we have to do here, and that's exactly * what happens when KRN_TRACK_NESTED_INTERR is 0. But, our nice * debug feature for nested interrupts tracking requires a little work: * because of its assumptions (hard-coded in ASSERTS) are that when the * kernel is running, it's always inside some kind of interrupt handler * (fault, int 0x80 [syscall], IRQ) before resuming the next task, we have * to resume the state of the nested_interrupts in one case: the one when * we're resuming a USER task that was running in KERNEL MODE (the kernel * was running on behalf of the task). In that case, when for the first * time the user task got to the kernel, we had a nice 0x80 added in our * nested_interrupts array [even in the case of sysenter] by the function * syscall_entry(). The kernel started to work on behalf of the * user process but, for some reason (typically kernel preemption or * wait on condition) the task was scheduled out. When that happened, * because of the function switch_to_task_pop_nested_interrupts() called * above, the 0x80 value was dropped from `nested_interrupts`. Now that * we have to resume the execution of the user task (but in kernel mode), * we MUST push back that 0x80 in order to compensate the pop that will * occur in kernel's syscall_entry() just before returning back * to the user. That's because the nested_interrupts array is global and * not specific to any given task. Like the registers, it has to be saved * and restored in a consistent way. */ if (!is_kernel_thread(ti)) { push_nested_interrupt(SYSCALL_SOFT_INTERRUPT); } } NORETURN void switch_to_task(struct task *ti) { /* Save the value of ti->state_regs as it will be reset below */ regs_t *state = ti->state_regs; struct task *curr = get_curr_task(); ASSERT(curr != NULL); if (UNLIKELY(ti != curr)) { ASSERT(curr->state != TASK_STATE_RUNNING); ASSERT_TASK_STATE(ti->state, TASK_STATE_RUNNABLE); } ASSERT(!is_preemption_enabled()); /* * Make sure in NO WAY we'll switch to a user task keeping interrupts * disabled. That would be a disaster. */ ASSERT(state->eflags & EFLAGS_IF); /* Do as much as possible work before disabling the interrupts */ task_change_state_idempotent(ti, TASK_STATE_RUNNING); ti->ticks.timeslice = 0; if (!is_kernel_thread(curr) && curr->state != TASK_STATE_ZOMBIE) save_curr_fpu_ctx_if_enabled(); if (!is_kernel_thread(ti)) { if (get_curr_pdir() != ti->pi->pdir) { arch_proc_members_t *arch = get_proc_arch_fields(ti->pi); set_curr_pdir(ti->pi->pdir); if (UNLIKELY(arch->ldt != NULL)) load_ldt(arch->ldt_index_in_gdt, arch->ldt_size); } if (!ti->running_in_kernel) process_signals(ti, sig_in_usermode, state); if (is_fpu_enabled_for_task(ti)) { hw_fpu_enable(); restore_fpu_regs(ti, false); /* leave FPU enabled */ } } /* From here until the end, we have to be as fast as possible */ disable_interrupts_forced(); switch_to_task_pop_nested_interrupts(); enable_preemption_nosched(); ASSERT(is_preemption_enabled()); if (!ti->running_in_kernel) task_info_reset_kernel_stack(ti); else adjust_nested_interrupts_for_task_in_kernel(ti); set_curr_task(ti); ti->timer_ready = false; set_kernel_stack((ulong)ti->state_regs); context_switch(state); } int sys_set_tid_address(int *tidptr) { /* * NOTE: this syscall must always succeed. In case the user pointer * is not valid, we'll send SIGSEGV to the just created thread. */ get_curr_proc()->set_child_tid = tidptr; return get_curr_task()->tid; } bool arch_specific_new_task_setup(struct task *ti, struct task *parent) { arch_task_members_t *arch = get_task_arch_fields(ti); if (FORK_NO_COW) { if (parent) { /* * We parent is set, we're forking a task and we must NOT preserve the * arch fields. But, if we're not forking (parent is set), it means * we're in execve(): in that case there's no point to reset the arch * fields. Actually, here, in the NO_COW case, we MUST NOT do it, in * order to be sure we won't fail. */ bzero(arch, sizeof(arch_task_members_t)); } if (arch->aligned_fpu_regs) { /* * We already have an FPU regs buffer: just clear its contents and * keep it allocated. */ bzero(arch->aligned_fpu_regs, arch->fpu_regs_size); } else { /* We don't have a FPU regs buffer: unless this is kthread, allocate */ if (LIKELY(!is_kernel_thread(ti))) if (!allocate_fpu_regs(arch)) return false; // out-of-memory } } else { /* * We're not in the NO_COW case. We have to free the arch specific fields * (like the fpu_regs buffer) if the parent is NULL. Otherwise, just reset * its members to zero. */ if (parent) { bzero(arch, sizeof(*arch)); } else { arch_specific_free_task(ti); } } return true; } void arch_specific_free_task(struct task *ti) { arch_task_members_t *arch = get_task_arch_fields(ti); aligned_kfree2(arch->aligned_fpu_regs, arch->fpu_regs_size); arch->aligned_fpu_regs = NULL; arch->fpu_regs_size = 0; } void arch_specific_new_proc_setup(struct process *pi, struct process *parent) { arch_proc_members_t *arch = get_proc_arch_fields(pi); if (!parent) return; /* we're done */ memcpy(&pi->pi_arch, &parent->pi_arch, sizeof(pi->pi_arch)); if (arch->ldt) gdt_entry_inc_ref_count(arch->ldt_index_in_gdt); for (int i = 0; i < ARRAY_SIZE(arch->gdt_entries); i++) if (arch->gdt_entries[i]) gdt_entry_inc_ref_count(arch->gdt_entries[i]); pi->set_child_tid = NULL; } void arch_specific_free_proc(struct process *pi) { arch_proc_members_t *arch = get_proc_arch_fields(pi); if (arch->ldt) { gdt_clear_entry(arch->ldt_index_in_gdt); arch->ldt = NULL; } for (int i = 0; i < ARRAY_SIZE(arch->gdt_entries); i++) { if (arch->gdt_entries[i]) { gdt_clear_entry(arch->gdt_entries[i]); arch->gdt_entries[i] = 0; } } } static void handle_fatal_error(regs_t *r, int signum) { send_signal(get_curr_tid(), signum, SIG_FL_PROCESS | SIG_FL_FAULT); } /* General protection fault handler */ void handle_gpf(regs_t *r) { if (!get_curr_task() || is_kernel_thread(get_curr_task())) panic("General protection fault. Error: %p\n", r->err_code); handle_fatal_error(r, SIGSEGV); } /* Illegal instruction fault handler */ void handle_ill(regs_t *r) { if (!get_curr_task() || is_kernel_thread(get_curr_task())) panic("Illegal instruction fault. Error: %p\n", r->err_code); handle_fatal_error(r, SIGILL); } /* Division by zero fault handler */ void handle_div0(regs_t *r) { if (!get_curr_task() || is_kernel_thread(get_curr_task())) panic("Division by zero fault. Error: %p\n", r->err_code); handle_fatal_error(r, SIGFPE); } /* Coproc fault handler */ void handle_cpf(regs_t *r) { if (!get_curr_task() || is_kernel_thread(get_curr_task())) panic("Co-processor (fpu) fault. Error: %p\n", r->err_code); handle_fatal_error(r, SIGFPE); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <cstdio> #include <cstdint> #include <cstdlib> #include <cassert> #include <iostream> #include <vector> #include <unordered_map> #include <random> #include <memory> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "fake_funcs_utils.h" #include "kernel_init_funcs.h" #include "mocking.h" extern "C" { #include <tilck/common/utils.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/self_tests.h> #include <kernel/kmalloc/kmalloc_heap_struct.h> // kmalloc private header #include <kernel/kmalloc/kmalloc_block_node.h> // kmalloc private header extern bool mock_kmalloc; extern bool suppress_printk; extern struct kmalloc_heap *heaps[KMALLOC_HEAPS_COUNT]; void selftest_kmalloc_perf_per_size(int size); void kmalloc_dump_heap_stats(void); void *node_to_ptr(struct kmalloc_heap *h, int node, size_t size); } using namespace std; using namespace testing; #define HALF(x) ((x) >> 1) #define TWICE(x) ((x) << 1) #define NODE_LEFT(n) (TWICE(n) + 1) #define NODE_RIGHT(n) (TWICE(n) + 2) #define NODE_PARENT(n) (HALF(n-1)) #define NODE_IS_LEFT(n) (((n) & 1) != 0) u32 calculate_node_size(struct kmalloc_heap *h, int node) { int i; int curr = node; for (i = 0; curr; i++) { curr = NODE_PARENT(curr); } return h->size >> i; } void save_heaps_metadata(unique_ptr<u8[]> *meta_before) { for (int h = 0; h < KMALLOC_HEAPS_COUNT && heaps[h]; h++) { memcpy(meta_before[h].get(), heaps[h]->metadata_nodes, heaps[h]->metadata_size); } } void print_node_info(int h, int node) { const u32 node_size = calculate_node_size(heaps[h], node); u8 *after = (u8*)heaps[h]->metadata_nodes; printf("[HEAP %i] Node #%i\n", h, node); printf("Node size: %u\n", node_size); printf("Node ptr: %p\n", node_to_ptr(heaps[h], node, node_size)); printf("Value: %u\n", after[node]); } void check_heaps_metadata(unique_ptr<u8[]> *meta_before) { for (int h = 0; h < KMALLOC_HEAPS_COUNT && heaps[h]; h++) { u8 *meta_ptr = meta_before[h].get(); struct kmalloc_heap *heap = heaps[h]; for (u32 i = 0; i < heap->metadata_size; i++) { if (meta_ptr[i] == ((u8*)heap->metadata_nodes)[i]) continue; print_node_info(h, i); printf("Exp value: %i\n", meta_ptr[i]); FAIL(); } } } void kmalloc_chaos_test_sub(default_random_engine &eng, lognormal_distribution<> &dist) { vector<pair<void *, size_t>> allocations; for (int i = 0; i < 1000; i++) { size_t s = round(dist(eng)); if (s == 0) continue; void *r = kmalloc(s); if (r != NULL) { allocations.push_back(make_pair(r, s)); } } for (const auto& e : allocations) { kfree2(e.first, e.second); } } class kmalloc_test : public Test { public: void SetUp() override { init_kmalloc_for_tests(); } void TearDown() override { /* do nothing, for the moment */ } }; #if KERNEL_SELFTESTS TEST_F(kmalloc_test, perf_test) { selftest_kmalloc_perf(); } TEST_F(kmalloc_test, glibc_malloc_comparative_perf_test) { mock_kmalloc = true; selftest_kmalloc_perf(); mock_kmalloc = false; } #endif TEST_F(kmalloc_test, chaos_test) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); cout << "[ INFO ] random seed: " << seed << endl; lognormal_distribution<> dist(5.0, 3); unique_ptr<u8[]> meta_before[KMALLOC_HEAPS_COUNT]; for (int h = 0; h < KMALLOC_HEAPS_COUNT && heaps[h]; h++) { u8 *buf = new u8[heaps[h]->metadata_size]; memset(buf, 0, heaps[h]->metadata_size); meta_before[h].reset(buf); } for (int i = 0; i < 150; i++) { save_heaps_metadata(meta_before); ASSERT_NO_FATAL_FAILURE({ kmalloc_chaos_test_sub(e, dist); }) << "i: " << i; ASSERT_NO_FATAL_FAILURE({ check_heaps_metadata(meta_before); }) << "i: " << i; } } #define COLOR_RED "\033[31m" #define COLOR_YELLOW "\033[93m" #define COLOR_BRIGHT_GREEN "\033[92m" #define ATTR_BOLD "\033[1m" #define ATTR_FAINT "\033[2m" #define RESET_ATTRS "\033[0m" static void dump_heap_node_head(struct block_node n, int w) { printf("%s", ATTR_FAINT); printf("+"); for (int i = 0; i < w-1; i++) printf("-"); printf("%s", RESET_ATTRS); } static void dump_heap_node_head_end(void) { printf(ATTR_FAINT "+\n" RESET_ATTRS); } static void dump_heap_node_tail(struct block_node n, int w) { dump_heap_node_head(n, w); } static void dump_heap_node_tail_end(void) { dump_heap_node_head_end(); } static void dump_heap_node(struct block_node n, int w) { int i; printf(ATTR_FAINT "|" RESET_ATTRS); for (i = 0; i < (w-1)/2-1; i++) printf(" "); printf("%s", COLOR_BRIGHT_GREEN); printf("%s", n.allocated ? "A" : "-"); printf("%s", n.split ? "S" : "-"); printf("%s", n.full ? "F" : "-"); printf("%s", RESET_ATTRS); for (i += 4; i < w; i++) printf(" "); } static void dump_heap_subtree(struct kmalloc_heap *h, int node, int levels) { int width = (1 << (levels - 1)) * 4; int level_width = 1; int n = node; struct block_node *nodes = (struct block_node *)h->metadata_nodes; for (int i = 0; i < levels; i++) { for (int j = 0; j < level_width; j++) dump_heap_node_head(nodes[n + j], width); dump_heap_node_head_end(); for (int j = 0; j < level_width; j++) dump_heap_node(nodes[n + j], width); printf(ATTR_FAINT "|\n" RESET_ATTRS); if (i == levels - 1) { for (int j = 0; j < level_width; j++) dump_heap_node_head(nodes[n + j], width); dump_heap_node_tail_end(); } n = NODE_LEFT(n); level_width <<= 1; width >>= 1; } printf("\n"); } static void check_metadata_row(struct block_node *nodes, const char *row, int &cn) { const char *p = row; assert(*p == '|'); p++; for (; *p; p++) { if (*p == ' ') continue; assert(*p == '-' || *p == 'A' || *p == 'S' || *p == 'F'); u8 val = 0; for (; *p != ' ' && *p != '|'; p++) { assert(*p); switch (*p) { case 'A': val |= FL_NODE_ALLOCATED; break; case 'S': val |= FL_NODE_SPLIT; break; case 'F': val |= FL_NODE_FULL; break; } } EXPECT_EQ(nodes[cn].raw, val) << "node #" << cn; cn++; while (*p == ' ') p++; assert(*p == '|'); } } static void check_metadata(struct block_node *nodes, vector<const char *> expected_vec) { int cn = 0; for (const char *row: expected_vec) { if (*row == '+') continue; check_metadata_row(nodes, row, cn); } } TEST_F(kmalloc_test, split_block) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ 0, /* alloc block size: 0 because linear_mapping=1 */ true, /* linear mapping */ NULL, NULL, NULL); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = h.size / 2; ptr = per_heap_kmalloc(&h, &s, 0); ASSERT_TRUE(ptr != NULL); printf("\nAfter alloc of heap_size/2:\n"); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| --F | --- |", "+---------------+---------------+---------------+---------------+", "| --- | --- | --- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| --- | --- | --- | --- | --- | --- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); EXPECT_TRUE(nodes[0].raw == FL_NODE_SPLIT); EXPECT_TRUE(nodes[1].raw == FL_NODE_FULL); internal_kmalloc_split_block(&h, ptr, s, h.min_block_size); printf("After split_block:\n"); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -SF | --- |", "+---------------+---------------+---------------+---------------+", "| -SF | -SF | --- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| -SF | -SF | -SF | -SF | --- | --- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|--F|--F|--F|--F|---|---|---|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); printf("After kfree leaf node #3:\n"); size_t actual_size = h.min_block_size; per_heap_kfree(&h, (void *)(h.vaddr + h.min_block_size * 3), &actual_size, 0); ASSERT_EQ(actual_size, h.min_block_size); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -S- | --- |", "+---------------+---------------+---------------+---------------+", "| -S- | -SF | --- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| -SF | -S- | -SF | -SF | --- | --- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|---|--F|--F|--F|--F|---|---|---|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } TEST_F(kmalloc_test, coalesce_block) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ 0, /* alloc block size: 0 because linear_mapping=1 */ true, /* linear mapping */ NULL, NULL, NULL); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = h.size / 2; ptr = per_heap_kmalloc(&h, &s, 0); ASSERT_TRUE(ptr != NULL); internal_kmalloc_split_block(&h, ptr, s, h.min_block_size); printf("After split_block:\n"); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -SF | --- |", "+---------------+---------------+---------------+---------------+", "| -SF | -SF | --- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| -SF | -SF | -SF | -SF | --- | --- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|--F|--F|--F|--F|---|---|---|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); internal_kmalloc_coalesce_block(&h, (void *)(h.vaddr + h.size / 4), h.size / 4); printf("After coalesce node #4:\n"); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -SF | --- |", "+---------------+---------------+---------------+---------------+", "| -SF | --F | --- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| -SF | -SF | --- | --- | --- | --- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|---|---|---|---|---|---|---|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } static bool fake_alloc_and_map_func(ulong vaddr, size_t page_count) { return true; } static void fake_free_and_map_func(ulong vaddr, size_t page_count) { /* do nothing */ } TEST_F(kmalloc_test, multi_step_alloc) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ KMALLOC_MIN_HEAP_SIZE / 8, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ fake_alloc_and_map_func, fake_free_and_map_func); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = 15 * h.min_block_size; ptr = per_heap_kmalloc(&h, &s, KMALLOC_FL_MULTI_STEP); EXPECT_EQ(s, 15 * h.min_block_size); EXPECT_EQ(ptr, (void *)h.vaddr); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| --F | -S- |", "+---------------+---------------+---------------+---------------+", "| --- | --- | --F | -S- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| A-F | A-F | A-F | A-F | A-F | A-F | A-F | AS- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|--F|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } TEST_F(kmalloc_test, multi_step_alloc2) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ KMALLOC_MIN_HEAP_SIZE / 8, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ fake_alloc_and_map_func, fake_free_and_map_func); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = 11 * h.min_block_size; ptr = per_heap_kmalloc(&h, &s, KMALLOC_FL_MULTI_STEP); EXPECT_EQ(s, 11 * h.min_block_size); EXPECT_EQ(ptr, (void *)h.vaddr); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| --F | -S- |", "+---------------+---------------+---------------+---------------+", "| --- | --- | -S- | --- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| A-F | A-F | A-F | A-F | A-F | AS- | --- | --- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|---|---|---|---|---|---|---|---|---|---|--F|---|---|---|---|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } TEST_F(kmalloc_test, multi_step_and_split) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ KMALLOC_MIN_HEAP_SIZE / 8, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ fake_alloc_and_map_func, fake_free_and_map_func); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = 15 * h.min_block_size; ptr = per_heap_kmalloc(&h, &s, KMALLOC_FL_MULTI_STEP | h.min_block_size); EXPECT_EQ(s, 15 * h.min_block_size); EXPECT_EQ(ptr, (void *)h.vaddr); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -SF | -S- |", "+---------------+---------------+---------------+---------------+", "| -SF | -SF | -SF | -S- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | ASF | ASF | ASF | ASF | ASF | ASF | AS- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } TEST_F(kmalloc_test, multi_step_free) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ KMALLOC_MIN_HEAP_SIZE / 8, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ fake_alloc_and_map_func, fake_free_and_map_func); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = 15 * h.min_block_size; ptr = per_heap_kmalloc(&h, &s, KMALLOC_FL_MULTI_STEP | h.min_block_size); EXPECT_EQ(s, 15 * h.min_block_size); EXPECT_EQ(ptr, (void *)h.vaddr); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -SF | -S- |", "+---------------+---------------+---------------+---------------+", "| -SF | -SF | -SF | -S- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | ASF | ASF | ASF | ASF | ASF | ASF | AS- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); size_t actual_size = h.min_block_size * 7; per_heap_kfree(&h, (void *)((ulong)ptr + h.min_block_size * 4), &actual_size, KFREE_FL_ALLOW_SPLIT | KFREE_FL_MULTI_STEP); ASSERT_EQ(actual_size, h.min_block_size * 7); printf("After multi-step free:\n"); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -S- | -S- |", "+---------------+---------------+---------------+---------------+", "| -SF | --- | -S- | -S- |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | ASF | --- | --- | --- | AS- | ASF | AS- |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|---|---|---|---|---|---|---|--F|--F|--F|--F|---|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); kmalloc_destroy_heap(&h); } TEST_F(kmalloc_test, partial_free) { void *ptr; size_t s; struct kmalloc_heap h; kmalloc_create_heap(&h, MB, /* vaddr */ KMALLOC_MIN_HEAP_SIZE, /* heap size */ KMALLOC_MIN_HEAP_SIZE / 16, /* min block size */ KMALLOC_MIN_HEAP_SIZE / 8, /* alloc block size */ false, /* linear mapping */ NULL, /* metadata_nodes */ fake_alloc_and_map_func, fake_free_and_map_func); struct block_node *nodes = (struct block_node *)h.metadata_nodes; s = h.size; ptr = per_heap_kmalloc(&h, &s, h.min_block_size); EXPECT_EQ(s, 16 * h.min_block_size); EXPECT_EQ(ptr, (void *)h.vaddr); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -SF |", "+-------------------------------+-------------------------------+", "| -SF | -SF |", "+---------------+---------------+---------------+---------------+", "| -SF | -SF | -SF | -SF |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | ASF | ASF | ASF | ASF | ASF | ASF | ASF |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); EXPECT_EQ(h.mem_allocated, h.size); s = h.min_block_size; ptr = (void *)(h.vaddr + 2 * h.min_block_size); per_heap_kfree(&h, ptr, &s, 0); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -S- | -SF |", "+---------------+---------------+---------------+---------------+", "| -S- | -SF | -SF | -SF |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | AS- | ASF | ASF | ASF | ASF | ASF | ASF |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|---|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); EXPECT_EQ(h.mem_allocated, h.size - h.min_block_size); s = h.min_block_size * 2; ptr = (void *)(h.vaddr + 2 * h.min_block_size); per_heap_kfree(&h, ptr, &s, KFREE_FL_ALLOW_SPLIT); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| -S- | -SF |", "+---------------+---------------+---------------+---------------+", "| -S- | -SF | -SF | -SF |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| ASF | --- | ASF | ASF | ASF | ASF | ASF | ASF |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|--F|--F|---|---|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|--F|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); EXPECT_EQ(h.mem_allocated, h.size - h.min_block_size * 2); s = h.min_block_size * 8; ptr = (void *)(h.vaddr); per_heap_kfree(&h, ptr, &s, KFREE_FL_ALLOW_SPLIT); dump_heap_subtree(&h, 0, 5); check_metadata(nodes, { "+---------------------------------------------------------------+", "| -S- |", "+-------------------------------+-------------------------------+", "| --- | -SF |", "+---------------+---------------+---------------+---------------+", "| --- | --- | -SF | -SF |", "+-------+-------+-------+-------+-------+-------+-------+-------+", "| --- | --- | --- | --- | ASF | ASF | ASF | ASF |", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+", "|---|---|---|---|---|---|---|---|--F|--F|--F|--F|--F|--F|--F|--F|", "+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+" }); EXPECT_EQ(h.mem_allocated, h.size - h.min_block_size * 8); kmalloc_destroy_heap(&h); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/list.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/rwlock.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/sort.h> #include "sysfs_int.h" #include "dents.c.h" #include "inodes.c.h" #include "dirops.c.h" #include "fileops.c.h" #include "types.c.h" #include "lock_and_retain.c.h" void sysfs_create_config_obj(void); static struct mnt_fs *sysfs; static int sysfs_open(struct vfs_path *p, fs_handle *out, int fl, mode_t mod) { struct sysfs_path *sp = (struct sysfs_path *) &p->fs_path; const struct sysobj_prop_type *pt; if (sp->inode) { if (sp->type == VFS_DIR) return sysfs_open_dir(p->fs, sp->inode, out); ASSERT(sp->type == VFS_FILE); if ((fl & O_CREAT) && (fl & O_EXCL)) return -EEXIST; pt = sp->inode->file.prop->type; if (~fl & O_WRONLY) if (!pt || !pt->load) return -EACCES; if (fl & (O_WRONLY | O_RDWR)) if (!pt || !pt->store) return -EACCES; return sysfs_open_file(p->fs, sp->inode, out); } if (fl & O_CREAT) return -EROFS; return -ENOENT; } static vfs_inode_ptr_t sysfs_get_inode(fs_handle h) { struct sysfs_handle *sh = h; return sh->inode; } static int sysfs_stat(struct mnt_fs *fs, vfs_inode_ptr_t i, struct k_stat64 *statbuf) { struct sysfs_inode *inode = i; struct sysfs_data *d = fs->device_data; const struct sysobj_prop_type *pt; bzero(statbuf, sizeof(struct k_stat64)); switch (inode->type) { case VFS_FILE: pt = inode->file.prop->type; statbuf->st_mode = S_IFREG; if (pt) { if (pt->load) statbuf->st_mode |= 0400; if (pt->store) statbuf->st_mode |= 0200; if (pt->get_buf_sz) { statbuf->st_size = (typeof(statbuf->st_size)) ABS( pt->get_buf_sz(inode->file.obj, inode->file.prop_data) ); } } break; case VFS_DIR: statbuf->st_mode = 0555 | S_IFDIR; statbuf->st_size = (typeof(statbuf->st_size)) (inode->dir.num_entries * (offt) sizeof(struct sysfs_entry)); break; case VFS_SYMLINK: statbuf->st_mode = 0777 | S_IFLNK; statbuf->st_size = (typeof(statbuf->st_size)) inode->symlink.path_len; break; default: NOT_IMPLEMENTED(); } statbuf->st_dev = fs->device_id; statbuf->st_ino = inode->ino; statbuf->st_nlink = 1; statbuf->st_uid = 0; /* root */ statbuf->st_gid = 0; /* root */ statbuf->st_blksize = PAGE_SIZE; statbuf->st_blocks = 0; statbuf->st_ctim.tv_sec = d->wrt_time; statbuf->st_mtim = statbuf->st_ctim; statbuf->st_atim = statbuf->st_mtim; return 0; } /* NOTE: `buf` is guaranteed to have room for at least MAX_PATH chars */ static int sysfs_readlink(struct vfs_path *p, char *buf) { struct sysfs_inode *i = p->fs_path.inode; if (i->type != VFS_SYMLINK) return -EINVAL; memcpy(buf, i->symlink.path, i->symlink.path_len); /* skip final \0 */ return (int) i->symlink.path_len; } static void sysfs_syncfs(struct mnt_fs *fs) { struct sysfs_data *d = fs->device_data; struct sysfs_handle *h; while (true) { h = NULL; disable_preemption(); { if (!list_is_empty(&d->dirty_handles)) { h = list_first_obj(&d->dirty_handles, struct sysfs_handle, file.dirty_node); list_remove(&h->file.dirty_node); list_node_init(&h->file.dirty_node); } } enable_preemption(); if (!h) break; sysfs_fsync(h); } } static const struct fs_ops static_fsops_sysfs = { .get_inode = sysfs_get_inode, .open = sysfs_open, .on_close = sysfs_on_close, .on_dup_cb = sysfs_on_dup, .getdents = sysfs_getdents, .unlink = NULL, .mkdir = NULL, .rmdir = NULL, .truncate = NULL, .stat = sysfs_stat, .symlink = NULL, .readlink = sysfs_readlink, .chmod = NULL, .get_entry = sysfs_get_entry, .rename = NULL, .link = NULL, .retain_inode = sysfs_retain_inode, .release_inode = sysfs_release_inode, .syncfs = sysfs_syncfs, .fs_exlock = sysfs_exclusive_lock, .fs_exunlock = sysfs_exclusive_unlock, .fs_shlock = sysfs_shared_lock, .fs_shunlock = sysfs_shared_unlock, }; static u32 sysobj_type_get_prop_count(struct sysobj_type *type) { struct sysobj_prop **prop_ptr = type->properties; u32 count = 0; while (*prop_ptr) { count++; prop_ptr++; } return count; } static struct sysobj * __sysobj_init(struct sysobj *obj, struct sysobj_type *type, struct sysobj_hooks *hooks, void **prop_data, bool prop_data_owned, bool type_owned) { list_node_init(&obj->node); list_init(&obj->children_list); obj->type = type; obj->hooks = hooks; obj->prop_data = prop_data; obj->extra = NULL; obj->prop_data_owned = prop_data_owned; obj->type_owned = type_owned; obj->object_owned = true; /* See sysobj_init() */ obj->inode = NULL; obj->entry = NULL; obj->parent = NULL; return obj; } void sysobj_init(struct sysobj *obj, struct sysobj_type *type, struct sysobj_hooks *hooks, void **prop_data) { ASSERT(obj != NULL); ASSERT(type != NULL); __sysobj_init(obj, type, hooks, prop_data, false, false); /* * The only case (in this file) where the object is NOT owned by sysfs * because the caller created it. */ obj->object_owned = false; } struct sysobj * sysfs_create_obj_va_arr(struct sysobj_type *type, struct sysobj_hooks *hooks, void **prop_data) { struct sysobj *obj; if (!(obj = kalloc_obj(struct sysobj))) return NULL; return __sysobj_init(obj, type, hooks, prop_data, false, false); } struct sysobj * sysfs_create_obj_va(struct sysobj_type *type, struct sysobj_hooks *hooks, va_list args) { void **dyn_prop_data; struct sysobj *obj; u32 i, prop_cnt; prop_cnt = sysobj_type_get_prop_count(type); dyn_prop_data = kzalloc_array_obj(void *, prop_cnt); /* No trailing NULL */ if (!dyn_prop_data) return NULL; for (i = 0; i < prop_cnt; i++) dyn_prop_data[i] = va_arg(args, void *); if (!(obj = sysfs_create_obj_va_arr(type, hooks, dyn_prop_data))) kfree_array_obj(dyn_prop_data, void *, prop_cnt); /* No trailing NULL */ /* * We have to set prop_data_owned because we (sysfs) allocated the prop_data * array. When the sys object is destroyed, we (the sysfs layer) have the * responsability to free that array. */ obj->prop_data_owned = true; return obj; } struct sysobj * sysfs_create_obj(struct sysobj_type *type, struct sysobj_hooks *hooks, ...) { struct sysobj *ret; va_list args; va_start(args, hooks); ret = sysfs_create_obj_va(type, hooks, args); va_end(args); return ret; } struct sysobj * sysfs_create_custom_obj_va(const char *type_name, struct sysobj_hooks *hooks, u32 args_cnt, va_list args) { const u32 prop_cnt = args_cnt / 2; struct sysobj_type *ot; struct sysobj *obj; void **dyn_prop_data; if (args_cnt % 2) { /* Expects N <prop, value> pairs. Cannot have an odd number of args. */ return NULL; } if (!(obj = kalloc_obj(struct sysobj))) return NULL; if (!(ot = kalloc_obj(struct sysobj_type))) { kfree_obj(obj, struct sysobj); return NULL; } ot->name = type_name; ot->properties = kzalloc_array_obj(struct sysobj_prop *, prop_cnt + 1); if (!ot->properties) { kfree_obj(ot, struct sysobj); kfree_obj(obj, struct sysobj_type); return NULL; } dyn_prop_data = kzalloc_array_obj(void *, prop_cnt); /* No trailing NULL */ if (!dyn_prop_data) { kfree_array_obj(ot->properties, struct sysobj_prop *, prop_cnt + 1); kfree_obj(ot, struct sysobj); kfree_obj(obj, struct sysobj_type); return NULL; } for (u32 i = 0; i < prop_cnt; i++) { ot->properties[i] = va_arg(args, void *); dyn_prop_data[i] = va_arg(args, void *); } return __sysobj_init(obj, ot, hooks, dyn_prop_data, true, true); } struct sysobj * sysfs_create_custom_obj(const char *type_name, struct sysobj_hooks *hooks, ...) { struct sysobj *ret; va_list args; u32 cnt = 0; va_start(args, hooks); /* * Count the number of varargs (expected to be in <prop, data> pairs) until * the `prop` arg is NOT null. For example: * * sysfs_create_custom_obj("my_type1", * NULL, // hooks * prop1, data1, * prop2, NULL, * prop3, data3, * NULL); * * Is a valid use case for this function. The `prop` element of the pair * must always be != NULL, but the data part can be NULL instead. */ while (va_arg(args, void *) || (cnt % 2)) cnt++; va_end(args); va_start(args, hooks); ret = sysfs_create_custom_obj_va(type_name, hooks, cnt, args); va_end(args); return ret; } static int sysfs_create_files_for_obj(struct mnt_fs *fs, struct sysobj *obj) { struct sysobj_prop **ptr, *prop; struct sysfs_inode *i; int rc, idx = 0; if (!obj->type) return 0; for (ptr = &obj->type->properties[0]; *ptr != NULL; ptr++, idx++) { prop = *ptr; i = sysfs_create_inode_file(fs->device_data, obj->inode, idx); if (!i) return -ENOMEM; /* NOTE: don't rollback everything */ rc = sysfs_dir_add_entry(obj->inode, prop->name, i, NULL); if (rc) return rc; /* NOTE: don't rollback everything */ } return 0; } void sysfs_destroy_unregistered_obj(struct sysobj *obj) { ASSERT(obj); ASSERT(!obj->inode); ASSERT(obj->object_owned); if (obj->prop_data_owned) { kfree(obj->prop_data); } if (obj->type_owned) { kfree(obj->type->properties); kfree(obj->type); } kfree_obj(obj, struct sysobj); } int sysfs_register_obj(struct mnt_fs *fs, struct sysobj *parent, const char *name, struct sysobj *obj) { struct sysfs_inode *iobj, *iparent; struct sysfs_data *d; int rc; if (!fs) { ASSERT(sysfs != NULL); fs = sysfs; } d = fs->device_data; ASSERT(obj != NULL); if (!parent) { if (d->root->dir.obj) return -EEXIST; if (name) return -EINVAL; iobj = d->root; } else { iparent = parent->inode; if (!iparent) return -EINVAL; /* the parent sysobj is not registered */ if (!(iobj = sysfs_create_inode_dir(d, iparent))) return -ENOMEM; if ((rc = sysfs_dir_add_entry(iparent, name, iobj, &obj->entry))) { sysfs_destroy_inode(d, iobj); return rc; } list_add_tail(&parent->children_list, &obj->node); } iobj->dir.obj = obj; obj->inode = iobj; obj->parent = parent; return sysfs_create_files_for_obj(fs, obj); } struct symlink_tmp { char path[MAX_PATH]; struct sysobj *np_path[96]; /* root to `new_parent` path */ struct sysobj *obj_path[96]; /* root to `obj` path */ }; static int sysfs_get_path_to_root(struct sysobj *obj, struct sysobj **path, int pl) { int i; for (i = 0; obj->parent != NULL && i < pl; obj = obj->parent, i++) path[i] = obj; if (obj->parent) return -ENAMETOOLONG; array_reverse_ptr(path, (u32)i); return i; } int sysfs_symlink_obj(struct mnt_fs *fs, struct sysobj *new_parent, const char *new_name, struct sysobj *obj) { struct symlink_tmp *tmp; struct sysfs_inode *link; struct sysfs_data *sd; struct sysobj *n; int rc, np_nodes, obj_nodes, len; int i, past_lca; /* index of the lowest common ancestor + 1 */ char *path, *path_end; ASSERT(new_parent); ASSERT(new_name); ASSERT(obj); if (!fs) { /* The main sysfs must be initialized */ ASSERT(sysfs != NULL); fs = sysfs; } sd = fs->device_data; if (!(tmp = kzalloc_obj(struct symlink_tmp))) goto oom; path = tmp->path; path_end = tmp->path + sizeof(tmp->path); rc = sysfs_get_path_to_root(new_parent, tmp->np_path, ARRAY_SIZE(tmp->np_path)); if (rc < 0) goto out; np_nodes = rc; rc = sysfs_get_path_to_root(obj, tmp->obj_path, ARRAY_SIZE(tmp->obj_path)); if (rc < 0) goto out; obj_nodes = rc; len = MIN(np_nodes, obj_nodes); i = 0; while (i < len && tmp->np_path[i] == tmp->obj_path[i]) { i++; } past_lca = i; /* Append "../" to the path until it reaches our LCA */ for (i = past_lca; i < np_nodes; i++) { if (path_end - path <= 3) goto nametoolong; *path++ = '.'; *path++ = '.'; *path++ = '/'; } /* Now append the path from LCA to our object */ for (i = past_lca; i < obj_nodes; i++) { n = tmp->obj_path[i]; if (path_end - path <= n->entry->name_len) goto nametoolong; memcpy(path, n->entry->name, n->entry->name_len - 1); path += n->entry->name_len - 1; *path++ = '/'; } if (path == tmp->path) { /* Path is empty, meaning `new_parent` == `obj`: corner case */ *path++ = '.'; } /* `path` always points to the next char to write: go back by 1 */ path--; if (*path == '/') *path = 0; /* Drop the trailing '/' */ /* Create the symlink inode using `path` as target */ link = sysfs_create_inode_symlink(sd, new_parent->inode, tmp->path); if (!link) goto oom; /* Now finally create a dir entry for the symlink */ rc = sysfs_dir_add_entry(new_parent->inode, new_name, link, NULL); if (rc < 0) sysfs_destroy_inode(sd, link); out: /* Free our temporary object, since `link` now has a copy of tmp->path */ kfree_obj(tmp, struct symlink_tmp); return rc; nametoolong: rc = -ENAMETOOLONG; goto out; oom: rc = -ENOMEM; goto out; } struct mnt_fs * create_sysfs(void) { struct mnt_fs *fs; struct sysfs_data *d; if (!(d = kzalloc_obj(struct sysfs_data))) return NULL; fs = create_fs_obj("sysfs", &static_fsops_sysfs, d, VFS_FS_RW); if (!fs) { kfree_obj(d, struct sysfs_data); return NULL; } d->next_inode = 1; d->wrt_time = (time_t)get_timestamp(); rwlock_wp_init(&d->rwlock, false); list_init(&d->dirty_handles); d->root = sysfs_create_inode_dir(d, NULL); if (!d->root) { rwlock_wp_destroy(&d->rwlock); kfree_obj(d, struct sysfs_data); destory_fs_obj(fs); return NULL; } return fs; } struct sysobj * sysfs_create_empty_obj(void) { return sysfs_create_obj_va_arr(NULL, /* type */ NULL, /* hooks */ NULL); /* prop data */ } DEF_SHARED_EMPTY_SYSOBJ(sysfs_root_obj); /* sysfs path: / */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_hw_obj); /* sysfs path: /hw */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_power_obj); /* sysfs path: /hw/power */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_storage_obj); /* sysfs path: /hw/storage */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_network_obj); /* sysfs path: /hw/network */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_display_obj); /* sysfs path: /hw/display */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_media_obj); /* sysfs path: /hw/media */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_bridge_obj); /* sysfs path: /hw/bridge */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_comm_obj); /* sysfs path: /hw/comm */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_genp_obj); /* sysfs path: /hw/generic */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_input_obj); /* sysfs path: /hw/input */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_serbus_obj); /* sysfs path: /hw/serbus */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_wifi_obj); /* sysfs path: /hw/wireless */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_sigproc_obj); /* sysfs path: /hw/sigproc */ DEF_SHARED_EMPTY_SYSOBJ(sysfs_other_obj); /* sysfs path: /hw/other */ #define REGISTER_SYSFS_HW_OBJ(name, obj) \ sysfs_register_obj(sysfs, &sysfs_hw_obj, name, obj) static int main_sysfs_create_default_objects(void) { int rc; if ((rc = sysfs_register_obj(sysfs, NULL, NULL, &sysfs_root_obj))) return rc; if ((rc = sysfs_register_obj(sysfs, &sysfs_root_obj, "hw", &sysfs_hw_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("power", &sysfs_power_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("storage", &sysfs_storage_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("network", &sysfs_network_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("display", &sysfs_display_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("media", &sysfs_media_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("bridge", &sysfs_bridge_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("comm", &sysfs_comm_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("generic", &sysfs_genp_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("input", &sysfs_input_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("serbus", &sysfs_serbus_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("wireless", &sysfs_wifi_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("sigproc", &sysfs_sigproc_obj))) return rc; if ((rc = REGISTER_SYSFS_HW_OBJ("other", &sysfs_other_obj))) return rc; return 0; } void init_sysfs(void) { int rc; if ((rc = vfs_mkdir("/syst", 0777))) panic("vfs_mkdir(\"/syst\") failed with error: %d", rc); sysfs = create_sysfs(); if (!sysfs) panic("Unable to create sysfs"); if ((rc = mp_add(sysfs, "/syst/"))) panic("mp_add() failed with error: %d", rc); if (main_sysfs_create_default_objects() < 0) panic("Unable to create default objects"); sysfs_create_config_obj(); } static struct module sysfs_module = { .name = "sysfs", .priority = MOD_sysfs_prio, .init = &init_sysfs, }; REGISTER_MODULE(&sysfs_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_global.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/kernel/list.h> #include <tilck/kernel/timer.h> #define MAX_NO_DEADLOCK_SET_ELEMS 144 #define SELF_TEST_MAX_NAME_LEN 31 enum se_kind { se_manual, se_short, se_med, se_medlong, se_long }; struct self_test { struct list_node node; const char *name; enum se_kind kind; void (*func)(void); }; #define REGISTER_SELF_TEST(__name, __kind, __func) \ \ static struct self_test se_##__name##_inst = { \ .name = #__name, \ .kind = __kind, \ .func = __func \ }; \ \ __attribute__((constructor)) \ static void __register_se_##__name(void) { \ se_register(&se_##__name##_inst); \ } #if KERNEL_SELFTESTS void init_self_tests(void); #else static inline void init_self_tests(void) { } #endif struct self_test *se_find(const char *name); int se_run(struct self_test *se); bool se_is_stop_requested(void); void se_register(struct self_test *se); void se_regular_end(void); void se_interrupted_end(void); void simple_test_kthread(void *arg); void selftest_kmalloc_perf(void); /* Deadlock detection functions */ void debug_reset_no_deadlock_set(void); void debug_add_task_to_no_deadlock_set(int tid); void debug_remove_task_from_no_deadlock_set(int tid); void debug_no_deadlock_set_report_progress(void); void debug_check_for_deadlock(void); void debug_check_for_any_progress(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/sched.h> #include "termutil.h" static int row; static void debug_dump_slow_irq_handler_count(void) { extern u32 slow_timer_irq_handler_count; if (KRN_TRACK_NESTED_INTERR) { dp_writeln(" Slow timer irq handler counter: %u", slow_timer_irq_handler_count); } } static void debug_dump_spur_irq_count(void) { extern u32 spur_irq_count; const u64 ticks = get_ticks(); if (ticks > TIMER_HZ) dp_writeln(" Spurious IRQ count: %u (%u/sec)", spur_irq_count, spur_irq_count / (ticks / TIMER_HZ)); else dp_writeln(" Spurious IRQ count: %u", spur_irq_count); } static void debug_dump_unhandled_irq_count(void) { extern u32 unhandled_irq_count[256]; u32 tot_count = 0; for (int i = 0; i < ARRAY_SIZE(unhandled_irq_count); i++) tot_count += unhandled_irq_count[i]; if (!tot_count) return; dp_writeln(""); dp_writeln("Unhandled IRQs count table"); for (int i = 0; i < ARRAY_SIZE(unhandled_irq_count); i++) { if (unhandled_irq_count[i]) dp_writeln(" IRQ #%3u: %3u unhandled", i, unhandled_irq_count[i]); } } static void debug_dump_masked_irqs(void) { dp_writeln(""); dp_writeln("Unmasked IRQs: "); for (int i = 0; i < 16; i++) { if (!irq_is_masked(i)) dp_write_raw("#%u ", i); } dp_writeln(""); } static void dp_show_irq_stats(void) { row = dp_screen_start_row; dp_writeln("Kernel IRQ-related counters"); debug_dump_slow_irq_handler_count(); debug_dump_spur_irq_count(); debug_dump_unhandled_irq_count(); debug_dump_masked_irqs(); } static struct dp_screen dp_irqs_screen = { .index = 4, .label = "IRQs", .draw_func = dp_show_irq_stats, .on_keypress_func = NULL, }; __attribute__((constructor)) static void dp_irqs_init(void) { dp_register_screen(&dp_irqs_screen); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include "common_int.h" #define TILCK_MIN_RES_X 640 #define TILCK_MIN_RES_Y 480 struct ok_mode { video_mode_t mode; struct generic_video_mode_info gi; }; const struct bootloader_intf *intf; video_mode_t g_defmode = INVALID_VIDEO_MODE; static struct ok_mode ok_modes[16]; static int ok_modes_cnt; static void append_ok_mode(video_mode_t mode, struct generic_video_mode_info *gi) { if (ok_modes_cnt == ok_modes_cnt - 1) return; ok_modes[ok_modes_cnt].mode = mode; ok_modes[ok_modes_cnt].gi = *gi; ok_modes_cnt++; } void init_common_bootloader_code(const struct bootloader_intf *i) { if (!intf) intf = i; } static bool is_usable_video_mode(struct generic_video_mode_info *gi) { return gi->xres >= TILCK_MIN_RES_X && gi->yres >= TILCK_MIN_RES_Y; } static bool is_default_resolution(u32 w, u32 h) { return w == PREFERRED_GFX_MODE_W && h == PREFERRED_GFX_MODE_H; } static bool is_mode_in_ok_list(video_mode_t mode) { for (int i = 0; i < ok_modes_cnt; i++) if (ok_modes[i].mode == mode) return true; return false; } void show_mode(int num, struct generic_video_mode_info *gi, bool is_default) { if (num >= 0) printk("Mode [%d]: ", num); if (gi->is_text_mode) printk("text mode %u x %u%s\n", gi->xres, gi->yres, is_default ? " [DEFAULT]" : ""); else printk("%u x %u x %d%s\n", gi->xres, gi->yres, gi->bpp, is_default ? " [DEFAULT]" : ""); } void show_video_modes(void) { for (int i = 0; i < ok_modes_cnt; i++) show_mode(i, &ok_modes[i].gi, ok_modes[i].mode == g_defmode); } static video_mode_t filter_modes_int(video_mode_t *all_modes, int all_modes_cnt, int bpp) { struct generic_video_mode_info gi; video_mode_t curr_mode_num; video_mode_t max_mode = INVALID_VIDEO_MODE; video_mode_t min_mode = INVALID_VIDEO_MODE; u32 min_mode_pixels = 0; u32 max_mode_pixels = 0; u32 p; if (intf->text_mode != INVALID_VIDEO_MODE) { gi = (struct generic_video_mode_info) { .xres = 80, .yres = 25, .bpp = 0, .is_text_mode = true, }; append_ok_mode(intf->text_mode, &gi); } for (int i = 0; i < all_modes_cnt; i++) { curr_mode_num = all_modes ? all_modes[i] : (video_mode_t)i; if (!intf->get_mode_info(curr_mode_num, &gi)) continue; if (!gi.is_usable) continue; if (gi.bpp != bpp) continue; if (!is_usable_video_mode(&gi)) continue; p = gi.xres * gi.yres; if (!min_mode_pixels || p < min_mode_pixels) { min_mode_pixels = p; min_mode = curr_mode_num; } if (p > max_mode_pixels) { max_mode_pixels = p; max_mode = curr_mode_num; } if (is_default_resolution(gi.xres, gi.yres)) g_defmode = curr_mode_num; if (ok_modes_cnt < ARRAY_SIZE(ok_modes) - 1) append_ok_mode(curr_mode_num, &gi); } if (g_defmode == INVALID_VIDEO_MODE) { g_defmode = min_mode; } if (max_mode != INVALID_VIDEO_MODE) { /* Display the max mode, even if might not be optimal for Tilck */ if (!is_mode_in_ok_list(max_mode)) { if (!intf->get_mode_info(max_mode, &gi)) panic("get_mode_info(0x%x) failed", max_mode); append_ok_mode(max_mode, &gi); if (g_defmode == INVALID_VIDEO_MODE) g_defmode = max_mode; } } if (g_defmode == INVALID_VIDEO_MODE) { if (ok_modes_cnt > 0) { g_defmode = ok_modes[0].mode; if (g_defmode == intf->text_mode && ok_modes_cnt > 1) g_defmode = ok_modes[1].mode; } } return g_defmode; } video_mode_t filter_video_modes(video_mode_t *all_modes, int all_modes_cnt) { if (g_defmode != INVALID_VIDEO_MODE) panic("filter_video_modes() called twice"); filter_modes_int(all_modes, all_modes_cnt, 32); if (g_defmode == INVALID_VIDEO_MODE || g_defmode == intf->text_mode) { all_modes_cnt = 0; g_defmode = INVALID_VIDEO_MODE; filter_modes_int(all_modes, all_modes_cnt, 24); if (g_defmode == INVALID_VIDEO_MODE) g_defmode = intf->get_curr_video_mode(); } return g_defmode; } video_mode_t get_user_video_mode_choice(void) { int len, err = 0; char buf[16]; long s; while (true) { buf[0] = 0; printk("Select a video mode [0 - %d]: ", ok_modes_cnt - 1); len = read_line(buf, sizeof(buf)); if (!len) { return g_defmode; } s = tilck_strtol(buf, NULL, 10, &err); if (err || s < 0 || s > ok_modes_cnt - 1) { printk("Invalid selection.\n"); continue; } break; } return ok_modes[s].mode; } void fetch_all_video_modes_once(void) { video_mode_t *all_modes = NULL; int all_modes_cnt = 0; if (g_defmode == INVALID_VIDEO_MODE) { intf->get_all_video_modes(&all_modes, &all_modes_cnt); filter_video_modes(all_modes, all_modes_cnt); } } video_mode_t find_default_video_mode(void) { fetch_all_video_modes_once(); return g_defmode; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #if BINTREE_PTR_FUNCS #define CMP(a, b) bintree_insrem_ptr_cmp(a, b, field_off) #else #define CMP(a, b) objval_cmpfun(a, b) #endif #if BINTREE_PTR_FUNCS bool bintree_insert_ptr_internal(void **root_obj_ref, void *obj_or_value, long bintree_offset, long field_off) #else bool bintree_insert_internal(void **root_obj_ref, void *obj_or_value, cmpfun_ptr objval_cmpfun, long bintree_offset) #endif { ASSERT(root_obj_ref != NULL); if (!*root_obj_ref) { *root_obj_ref = obj_or_value; return true; } /* * The stack will contain the whole reverse leaf-to-root path traversed * needed for the balance loop at the end, which simulates the stack * unwinding that happens for recursive implementations. */ void **stack[MAX_TREE_HEIGHT]; int stack_size = 0; void **dest; AVL_BUILD_PATH_TO_OBJ(); dest = STACK_TOP(); if (*dest) return false; /* element already existing */ /* Place our object in its right destination */ *dest = obj_or_value; while (stack_size > 0) BALANCE(STACK_POP()); return true; } <file_sep>/****************************************************************************** * * Name: acutils.h -- prototypes for the common (subsystem-wide) procedures * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef _ACUTILS_H #define _ACUTILS_H extern const UINT8 AcpiGbl_ResourceAmlSizes[]; extern const UINT8 AcpiGbl_ResourceAmlSerialBusSizes[]; /* Strings used by the disassembler and debugger resource dump routines */ #if defined(ACPI_DEBUG_OUTPUT) || defined (ACPI_DISASSEMBLER) || defined (ACPI_DEBUGGER) extern const char *AcpiGbl_BmDecode[]; extern const char *AcpiGbl_ConfigDecode[]; extern const char *AcpiGbl_ConsumeDecode[]; extern const char *AcpiGbl_DecDecode[]; extern const char *AcpiGbl_HeDecode[]; extern const char *AcpiGbl_IoDecode[]; extern const char *AcpiGbl_LlDecode[]; extern const char *AcpiGbl_MaxDecode[]; extern const char *AcpiGbl_MemDecode[]; extern const char *AcpiGbl_MinDecode[]; extern const char *AcpiGbl_MtpDecode[]; extern const char *AcpiGbl_RngDecode[]; extern const char *AcpiGbl_RwDecode[]; extern const char *AcpiGbl_ShrDecode[]; extern const char *AcpiGbl_SizDecode[]; extern const char *AcpiGbl_TrsDecode[]; extern const char *AcpiGbl_TtpDecode[]; extern const char *AcpiGbl_TypDecode[]; extern const char *AcpiGbl_PpcDecode[]; extern const char *AcpiGbl_IorDecode[]; extern const char *AcpiGbl_DtsDecode[]; extern const char *AcpiGbl_CtDecode[]; extern const char *AcpiGbl_SbtDecode[]; extern const char *AcpiGbl_AmDecode[]; extern const char *AcpiGbl_SmDecode[]; extern const char *AcpiGbl_WmDecode[]; extern const char *AcpiGbl_CphDecode[]; extern const char *AcpiGbl_CpoDecode[]; extern const char *AcpiGbl_DpDecode[]; extern const char *AcpiGbl_EdDecode[]; extern const char *AcpiGbl_BpbDecode[]; extern const char *AcpiGbl_SbDecode[]; extern const char *AcpiGbl_FcDecode[]; extern const char *AcpiGbl_PtDecode[]; extern const char *AcpiGbl_PtypDecode[]; #endif /* * For the iASL compiler case, the output is redirected to stderr so that * any of the various ACPI errors and warnings do not appear in the output * files, for either the compiler or disassembler portions of the tool. */ #ifdef ACPI_ASL_COMPILER #include <stdio.h> #define ACPI_MSG_REDIRECT_BEGIN \ FILE *OutputFile = AcpiGbl_OutputFile; \ AcpiOsRedirectOutput (stderr); #define ACPI_MSG_REDIRECT_END \ AcpiOsRedirectOutput (OutputFile); #else /* * non-iASL case - no redirection, nothing to do */ #define ACPI_MSG_REDIRECT_BEGIN #define ACPI_MSG_REDIRECT_END #endif /* * Common error message prefixes */ #ifndef ACPI_MSG_ERROR #define ACPI_MSG_ERROR "ACPI Error: " #endif #ifndef ACPI_MSG_WARNING #define ACPI_MSG_WARNING "ACPI Warning: " #endif #ifndef ACPI_MSG_INFO #define ACPI_MSG_INFO "ACPI: " #endif #ifndef ACPI_MSG_BIOS_ERROR #define ACPI_MSG_BIOS_ERROR "Firmware Error (ACPI): " #endif #ifndef ACPI_MSG_BIOS_WARNING #define ACPI_MSG_BIOS_WARNING "Firmware Warning (ACPI): " #endif /* * Common message suffix */ #define ACPI_MSG_SUFFIX \ AcpiOsPrintf (" (%8.8X/%s-%u)\n", ACPI_CA_VERSION, ModuleName, LineNumber) /* Flags to indicate implicit or explicit string-to-integer conversion */ #define ACPI_IMPLICIT_CONVERSION TRUE #define ACPI_NO_IMPLICIT_CONVERSION FALSE /* Types for Resource descriptor entries */ #define ACPI_INVALID_RESOURCE 0 #define ACPI_FIXED_LENGTH 1 #define ACPI_VARIABLE_LENGTH 2 #define ACPI_SMALL_VARIABLE_LENGTH 3 typedef ACPI_STATUS (*ACPI_WALK_AML_CALLBACK) ( UINT8 *Aml, UINT32 Length, UINT32 Offset, UINT8 ResourceIndex, void **Context); typedef ACPI_STATUS (*ACPI_PKG_CALLBACK) ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context); typedef struct acpi_pkg_info { UINT8 *FreeSpace; ACPI_SIZE Length; UINT32 ObjectSpace; UINT32 NumPackages; } ACPI_PKG_INFO; /* Object reference counts */ #define REF_INCREMENT (UINT16) 0 #define REF_DECREMENT (UINT16) 1 /* AcpiUtDumpBuffer */ #define DB_BYTE_DISPLAY 0x01 #define DB_WORD_DISPLAY 0x02 #define DB_DWORD_DISPLAY 0x04 #define DB_QWORD_DISPLAY 0x08 #define DB_DISPLAY_DATA_ONLY 0x10 /* * utascii - ASCII utilities */ BOOLEAN AcpiUtValidNameseg ( char *Signature); BOOLEAN AcpiUtValidNameChar ( char Character, UINT32 Position); void AcpiUtCheckAndRepairAscii ( UINT8 *Name, char *RepairedName, UINT32 Count); /* * utnonansi - Non-ANSI C library functions */ void AcpiUtStrupr ( char *SrcString); void AcpiUtStrlwr ( char *SrcString); int AcpiUtStricmp ( char *String1, char *String2); /* * utstrsuppt - string-to-integer conversion support functions */ ACPI_STATUS AcpiUtConvertOctalString ( char *String, UINT64 *ReturnValue); ACPI_STATUS AcpiUtConvertDecimalString ( char *String, UINT64 *ReturnValuePtr); ACPI_STATUS AcpiUtConvertHexString ( char *String, UINT64 *ReturnValuePtr); char AcpiUtRemoveWhitespace ( char **String); char AcpiUtRemoveLeadingZeros ( char **String); BOOLEAN AcpiUtDetectHexPrefix ( char **String); void AcpiUtRemoveHexPrefix ( char **String); BOOLEAN AcpiUtDetectOctalPrefix ( char **String); /* * utstrtoul64 - string-to-integer conversion functions */ ACPI_STATUS AcpiUtStrtoul64 ( char *String, UINT64 *RetInteger); UINT64 AcpiUtExplicitStrtoul64 ( char *String); UINT64 AcpiUtImplicitStrtoul64 ( char *String); /* * utglobal - Global data structures and procedures */ ACPI_STATUS AcpiUtInitGlobals ( void); const char * AcpiUtGetMutexName ( UINT32 MutexId); #if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER) const char * AcpiUtGetNotifyName ( UINT32 NotifyValue, ACPI_OBJECT_TYPE Type); #endif const char * AcpiUtGetTypeName ( ACPI_OBJECT_TYPE Type); const char * AcpiUtGetNodeName ( void *Object); const char * AcpiUtGetDescriptorName ( void *Object); const char * AcpiUtGetReferenceName ( ACPI_OPERAND_OBJECT *Object); const char * AcpiUtGetObjectTypeName ( ACPI_OPERAND_OBJECT *ObjDesc); const char * AcpiUtGetRegionName ( UINT8 SpaceId); const char * AcpiUtGetEventName ( UINT32 EventId); const char * AcpiUtGetArgumentTypeName ( UINT32 ArgType); char AcpiUtHexToAsciiChar ( UINT64 Integer, UINT32 Position); ACPI_STATUS AcpiUtAsciiToHexByte ( char *TwoAsciiChars, UINT8 *ReturnByte); UINT8 AcpiUtAsciiCharToHex ( int HexChar); BOOLEAN AcpiUtValidObjectType ( ACPI_OBJECT_TYPE Type); /* * utinit - miscellaneous initialization and shutdown */ ACPI_STATUS AcpiUtHardwareInitialize ( void); void AcpiUtSubsystemShutdown ( void); /* * utcopy - Object construction and conversion interfaces */ ACPI_STATUS AcpiUtBuildSimpleObject( ACPI_OPERAND_OBJECT *Obj, ACPI_OBJECT *UserObj, UINT8 *DataSpace, UINT32 *BufferSpaceUsed); ACPI_STATUS AcpiUtBuildPackageObject ( ACPI_OPERAND_OBJECT *Obj, UINT8 *Buffer, UINT32 *SpaceUsed); ACPI_STATUS AcpiUtCopyIobjectToEobject ( ACPI_OPERAND_OBJECT *Obj, ACPI_BUFFER *RetBuffer); ACPI_STATUS AcpiUtCopyEobjectToIobject ( ACPI_OBJECT *Obj, ACPI_OPERAND_OBJECT **InternalObj); ACPI_STATUS AcpiUtCopyISimpleToIsimple ( ACPI_OPERAND_OBJECT *SourceObj, ACPI_OPERAND_OBJECT *DestObj); ACPI_STATUS AcpiUtCopyIobjectToIobject ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT **DestDesc, ACPI_WALK_STATE *WalkState); /* * utcreate - Object creation */ ACPI_STATUS AcpiUtUpdateObjectReference ( ACPI_OPERAND_OBJECT *Object, UINT16 Action); /* * utdebug - Debug interfaces */ void AcpiUtInitStackPtrTrace ( void); void AcpiUtTrackStackPtr ( void); void AcpiUtTrace ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId); void AcpiUtTracePtr ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, const void *Pointer); void AcpiUtTraceU32 ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, UINT32 Integer); void AcpiUtTraceStr ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, const char *String); void AcpiUtExit ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId); void AcpiUtStatusExit ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, ACPI_STATUS Status); void AcpiUtValueExit ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, UINT64 Value); void AcpiUtPtrExit ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, UINT8 *Ptr); void AcpiUtStrExit ( UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, const char *String); void AcpiUtDebugDumpBuffer ( UINT8 *Buffer, UINT32 Count, UINT32 Display, UINT32 ComponentId); void AcpiUtDumpBuffer ( UINT8 *Buffer, UINT32 Count, UINT32 Display, UINT32 Offset); #ifdef ACPI_APPLICATION void AcpiUtDumpBufferToFile ( ACPI_FILE File, UINT8 *Buffer, UINT32 Count, UINT32 Display, UINT32 BaseOffset); #endif void AcpiUtReportError ( char *ModuleName, UINT32 LineNumber); void AcpiUtReportInfo ( char *ModuleName, UINT32 LineNumber); void AcpiUtReportWarning ( char *ModuleName, UINT32 LineNumber); /* * utdelete - Object deletion and reference counts */ void AcpiUtAddReference ( ACPI_OPERAND_OBJECT *Object); void AcpiUtRemoveReference ( ACPI_OPERAND_OBJECT *Object); void AcpiUtDeleteInternalPackageObject ( ACPI_OPERAND_OBJECT *Object); void AcpiUtDeleteInternalSimpleObject ( ACPI_OPERAND_OBJECT *Object); void AcpiUtDeleteInternalObjectList ( ACPI_OPERAND_OBJECT **ObjList); /* * uteval - object evaluation */ ACPI_STATUS AcpiUtEvaluateObject ( ACPI_NAMESPACE_NODE *PrefixNode, const char *Path, UINT32 ExpectedReturnBtypes, ACPI_OPERAND_OBJECT **ReturnDesc); ACPI_STATUS AcpiUtEvaluateNumericObject ( const char *ObjectName, ACPI_NAMESPACE_NODE *DeviceNode, UINT64 *Value); ACPI_STATUS AcpiUtExecute_STA ( ACPI_NAMESPACE_NODE *DeviceNode, UINT32 *StatusFlags); ACPI_STATUS AcpiUtExecutePowerMethods ( ACPI_NAMESPACE_NODE *DeviceNode, const char **MethodNames, UINT8 MethodCount, UINT8 *OutValues); /* * utids - device ID support */ ACPI_STATUS AcpiUtExecute_HID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId); ACPI_STATUS AcpiUtExecute_UID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId); ACPI_STATUS AcpiUtExecute_CID ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID_LIST **ReturnCidList); ACPI_STATUS AcpiUtExecute_CLS ( ACPI_NAMESPACE_NODE *DeviceNode, ACPI_PNP_DEVICE_ID **ReturnId); /* * utlock - reader/writer locks */ ACPI_STATUS AcpiUtCreateRwLock ( ACPI_RW_LOCK *Lock); void AcpiUtDeleteRwLock ( ACPI_RW_LOCK *Lock); ACPI_STATUS AcpiUtAcquireReadLock ( ACPI_RW_LOCK *Lock); ACPI_STATUS AcpiUtReleaseReadLock ( ACPI_RW_LOCK *Lock); ACPI_STATUS AcpiUtAcquireWriteLock ( ACPI_RW_LOCK *Lock); void AcpiUtReleaseWriteLock ( ACPI_RW_LOCK *Lock); /* * utobject - internal object create/delete/cache routines */ ACPI_OPERAND_OBJECT * AcpiUtCreateInternalObjectDbg ( const char *ModuleName, UINT32 LineNumber, UINT32 ComponentId, ACPI_OBJECT_TYPE Type); void * AcpiUtAllocateObjectDescDbg ( const char *ModuleName, UINT32 LineNumber, UINT32 ComponentId); #define AcpiUtCreateInternalObject(t) AcpiUtCreateInternalObjectDbg (_AcpiModuleName,__LINE__,_COMPONENT,t) #define AcpiUtAllocateObjectDesc() AcpiUtAllocateObjectDescDbg (_AcpiModuleName,__LINE__,_COMPONENT) void AcpiUtDeleteObjectDesc ( ACPI_OPERAND_OBJECT *Object); BOOLEAN AcpiUtValidInternalObject ( void *Object); ACPI_OPERAND_OBJECT * AcpiUtCreatePackageObject ( UINT32 Count); ACPI_OPERAND_OBJECT * AcpiUtCreateIntegerObject ( UINT64 Value); ACPI_OPERAND_OBJECT * AcpiUtCreateBufferObject ( ACPI_SIZE BufferSize); ACPI_OPERAND_OBJECT * AcpiUtCreateStringObject ( ACPI_SIZE StringSize); ACPI_STATUS AcpiUtGetObjectSize( ACPI_OPERAND_OBJECT *Obj, ACPI_SIZE *ObjLength); /* * utosi - Support for the _OSI predefined control method */ ACPI_STATUS AcpiUtInitializeInterfaces ( void); ACPI_STATUS AcpiUtInterfaceTerminate ( void); ACPI_STATUS AcpiUtInstallInterface ( ACPI_STRING InterfaceName); ACPI_STATUS AcpiUtRemoveInterface ( ACPI_STRING InterfaceName); ACPI_STATUS AcpiUtUpdateInterfaces ( UINT8 Action); ACPI_INTERFACE_INFO * AcpiUtGetInterface ( ACPI_STRING InterfaceName); ACPI_STATUS AcpiUtOsiImplementation ( ACPI_WALK_STATE *WalkState); /* * utpredef - support for predefined names */ const ACPI_PREDEFINED_INFO * AcpiUtGetNextPredefinedMethod ( const ACPI_PREDEFINED_INFO *ThisName); const ACPI_PREDEFINED_INFO * AcpiUtMatchPredefinedMethod ( char *Name); void AcpiUtGetExpectedReturnTypes ( char *Buffer, UINT32 ExpectedBtypes); #if (defined ACPI_ASL_COMPILER || defined ACPI_HELP_APP) const ACPI_PREDEFINED_INFO * AcpiUtMatchResourceName ( char *Name); void AcpiUtDisplayPredefinedMethod ( char *Buffer, const ACPI_PREDEFINED_INFO *ThisName, BOOLEAN MultiLine); UINT32 AcpiUtGetResourceBitWidth ( char *Buffer, UINT16 Types); #endif /* * utstate - Generic state creation/cache routines */ void AcpiUtPushGenericState ( ACPI_GENERIC_STATE **ListHead, ACPI_GENERIC_STATE *State); ACPI_GENERIC_STATE * AcpiUtPopGenericState ( ACPI_GENERIC_STATE **ListHead); ACPI_GENERIC_STATE * AcpiUtCreateGenericState ( void); ACPI_THREAD_STATE * AcpiUtCreateThreadState ( void); ACPI_GENERIC_STATE * AcpiUtCreateUpdateState ( ACPI_OPERAND_OBJECT *Object, UINT16 Action); ACPI_GENERIC_STATE * AcpiUtCreatePkgState ( void *InternalObject, void *ExternalObject, UINT32 Index); ACPI_STATUS AcpiUtCreateUpdateStateAndPush ( ACPI_OPERAND_OBJECT *Object, UINT16 Action, ACPI_GENERIC_STATE **StateList); ACPI_GENERIC_STATE * AcpiUtCreateControlState ( void); void AcpiUtDeleteGenericState ( ACPI_GENERIC_STATE *State); /* * utmath */ ACPI_STATUS AcpiUtDivide ( UINT64 InDividend, UINT64 InDivisor, UINT64 *OutQuotient, UINT64 *OutRemainder); ACPI_STATUS AcpiUtShortDivide ( UINT64 InDividend, UINT32 Divisor, UINT64 *OutQuotient, UINT32 *OutRemainder); ACPI_STATUS AcpiUtShortMultiply ( UINT64 InMultiplicand, UINT32 Multiplier, UINT64 *Outproduct); ACPI_STATUS AcpiUtShortShiftLeft ( UINT64 Operand, UINT32 Count, UINT64 *OutResult); ACPI_STATUS AcpiUtShortShiftRight ( UINT64 Operand, UINT32 Count, UINT64 *OutResult); /* * utmisc */ const ACPI_EXCEPTION_INFO * AcpiUtValidateException ( ACPI_STATUS Status); BOOLEAN AcpiUtIsPciRootBridge ( char *Id); #if (defined ACPI_ASL_COMPILER || defined ACPI_EXEC_APP || defined ACPI_NAMES_APP) BOOLEAN AcpiUtIsAmlTable ( ACPI_TABLE_HEADER *Table); #endif ACPI_STATUS AcpiUtWalkPackageTree ( ACPI_OPERAND_OBJECT *SourceObject, void *TargetObject, ACPI_PKG_CALLBACK WalkCallback, void *Context); /* Values for Base above (16=Hex, 10=Decimal) */ #define ACPI_ANY_BASE 0 UINT32 AcpiUtDwordByteSwap ( UINT32 Value); void AcpiUtSetIntegerWidth ( UINT8 Revision); #ifdef ACPI_DEBUG_OUTPUT void AcpiUtDisplayInitPathname ( UINT8 Type, ACPI_NAMESPACE_NODE *ObjHandle, const char *Path); #endif /* * utownerid - Support for Table/Method Owner IDs */ ACPI_STATUS AcpiUtAllocateOwnerId ( ACPI_OWNER_ID *OwnerId); void AcpiUtReleaseOwnerId ( ACPI_OWNER_ID *OwnerId); /* * utresrc */ ACPI_STATUS AcpiUtWalkAmlResources ( ACPI_WALK_STATE *WalkState, UINT8 *Aml, ACPI_SIZE AmlLength, ACPI_WALK_AML_CALLBACK UserFunction, void **Context); ACPI_STATUS AcpiUtValidateResource ( ACPI_WALK_STATE *WalkState, void *Aml, UINT8 *ReturnIndex); UINT32 AcpiUtGetDescriptorLength ( void *Aml); UINT16 AcpiUtGetResourceLength ( void *Aml); UINT8 AcpiUtGetResourceHeaderLength ( void *Aml); UINT8 AcpiUtGetResourceType ( void *Aml); ACPI_STATUS AcpiUtGetResourceEndTag ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 **EndTag); /* * utstring - String and character utilities */ void AcpiUtPrintString ( char *String, UINT16 MaxLength); #if defined ACPI_ASL_COMPILER || defined ACPI_EXEC_APP void UtConvertBackslashes ( char *Pathname); #endif void AcpiUtRepairName ( char *Name); #if defined (ACPI_DEBUGGER) || defined (ACPI_APPLICATION) || defined (ACPI_DEBUG_OUTPUT) BOOLEAN AcpiUtSafeStrcpy ( char *Dest, ACPI_SIZE DestSize, char *Source); void AcpiUtSafeStrncpy ( char *Dest, char *Source, ACPI_SIZE DestSize); BOOLEAN AcpiUtSafeStrcat ( char *Dest, ACPI_SIZE DestSize, char *Source); BOOLEAN AcpiUtSafeStrncat ( char *Dest, ACPI_SIZE DestSize, char *Source, ACPI_SIZE MaxTransferLength); #endif /* * utmutex - mutex support */ ACPI_STATUS AcpiUtMutexInitialize ( void); void AcpiUtMutexTerminate ( void); ACPI_STATUS AcpiUtAcquireMutex ( ACPI_MUTEX_HANDLE MutexId); ACPI_STATUS AcpiUtReleaseMutex ( ACPI_MUTEX_HANDLE MutexId); /* * utalloc - memory allocation and object caching */ ACPI_STATUS AcpiUtCreateCaches ( void); ACPI_STATUS AcpiUtDeleteCaches ( void); ACPI_STATUS AcpiUtValidateBuffer ( ACPI_BUFFER *Buffer); ACPI_STATUS AcpiUtInitializeBuffer ( ACPI_BUFFER *Buffer, ACPI_SIZE RequiredLength); #ifdef ACPI_DBG_TRACK_ALLOCATIONS void * AcpiUtAllocateAndTrack ( ACPI_SIZE Size, UINT32 Component, const char *Module, UINT32 Line); void * AcpiUtAllocateZeroedAndTrack ( ACPI_SIZE Size, UINT32 Component, const char *Module, UINT32 Line); void AcpiUtFreeAndTrack ( void *Address, UINT32 Component, const char *Module, UINT32 Line); void AcpiUtDumpAllocationInfo ( void); void AcpiUtDumpAllocations ( UINT32 Component, const char *Module); ACPI_STATUS AcpiUtCreateList ( const char *ListName, UINT16 ObjectSize, ACPI_MEMORY_LIST **ReturnCache); #endif /* ACPI_DBG_TRACK_ALLOCATIONS */ /* * utaddress - address range check */ ACPI_STATUS AcpiUtAddAddressRange ( ACPI_ADR_SPACE_TYPE SpaceId, ACPI_PHYSICAL_ADDRESS Address, UINT32 Length, ACPI_NAMESPACE_NODE *RegionNode); void AcpiUtRemoveAddressRange ( ACPI_ADR_SPACE_TYPE SpaceId, ACPI_NAMESPACE_NODE *RegionNode); UINT32 AcpiUtCheckAddressRange ( ACPI_ADR_SPACE_TYPE SpaceId, ACPI_PHYSICAL_ADDRESS Address, UINT32 Length, BOOLEAN Warn); void AcpiUtDeleteAddressLists ( void); /* * utxferror - various error/warning output functions */ ACPI_PRINTF_LIKE(5) void ACPI_INTERNAL_VAR_XFACE AcpiUtPredefinedWarning ( const char *ModuleName, UINT32 LineNumber, char *Pathname, UINT16 NodeFlags, const char *Format, ...); ACPI_PRINTF_LIKE(5) void ACPI_INTERNAL_VAR_XFACE AcpiUtPredefinedInfo ( const char *ModuleName, UINT32 LineNumber, char *Pathname, UINT16 NodeFlags, const char *Format, ...); ACPI_PRINTF_LIKE(5) void ACPI_INTERNAL_VAR_XFACE AcpiUtPredefinedBiosError ( const char *ModuleName, UINT32 LineNumber, char *Pathname, UINT16 NodeFlags, const char *Format, ...); void AcpiUtPrefixedNamespaceError ( const char *ModuleName, UINT32 LineNumber, ACPI_GENERIC_STATE *PrefixScope, const char *InternalName, ACPI_STATUS LookupStatus); void AcpiUtMethodError ( const char *ModuleName, UINT32 LineNumber, const char *Message, ACPI_NAMESPACE_NODE *Node, const char *Path, ACPI_STATUS LookupStatus); /* * Utility functions for ACPI names and IDs */ const AH_PREDEFINED_NAME * AcpiAhMatchPredefinedName ( char *Nameseg); const AH_DEVICE_ID * AcpiAhMatchHardwareId ( char *Hid); const char * AcpiAhMatchUuid ( UINT8 *Data); /* * utuuid -- UUID support functions */ #if (defined ACPI_ASL_COMPILER || defined ACPI_EXEC_APP || defined ACPI_HELP_APP) void AcpiUtConvertStringToUuid ( char *InString, UINT8 *UuidBuffer); #endif #endif /* _ACUTILS_H */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "devshell.h" void create_test_file(const char *path, int n); int remove_test_file(const char *path, int n); void remove_test_file_expecting_success(const char *path, int n); bool running_on_tilck(void); void not_on_tilck_message(void); int test_sig(void (*child_func)(void *), void *arg, int ex_sig, int ex_code, int signal_to_send); <file_sep>/****************************************************************************** * * Module Name: psparse - Parser top level AML parse routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* * Parse the AML and build an operation tree as most interpreters, * like Perl, do. Parsing is done by hand rather than with a YACC * generated parser to tightly constrain stack and dynamic memory * usage. At the same time, parsing is kept flexible and the code * fairly compact by parsing based on a list of AML opcode * templates in AmlOpInfo[] */ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "acdispat.h" #include "amlcode.h" #include "acinterp.h" #include "acnamesp.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psparse") /******************************************************************************* * * FUNCTION: AcpiPsGetOpcodeSize * * PARAMETERS: Opcode - An AML opcode * * RETURN: Size of the opcode, in bytes (1 or 2) * * DESCRIPTION: Get the size of the current opcode. * ******************************************************************************/ UINT32 AcpiPsGetOpcodeSize ( UINT32 Opcode) { /* Extended (2-byte) opcode if > 255 */ if (Opcode > 0x00FF) { return (2); } /* Otherwise, just a single byte opcode */ return (1); } /******************************************************************************* * * FUNCTION: AcpiPsPeekOpcode * * PARAMETERS: ParserState - A parser state object * * RETURN: Next AML opcode * * DESCRIPTION: Get next AML opcode (without incrementing AML pointer) * ******************************************************************************/ UINT16 AcpiPsPeekOpcode ( ACPI_PARSE_STATE *ParserState) { UINT8 *Aml; UINT16 Opcode; Aml = ParserState->Aml; Opcode = (UINT16) ACPI_GET8 (Aml); if (Opcode == AML_EXTENDED_PREFIX) { /* Extended opcode, get the second opcode byte */ Aml++; Opcode = (UINT16) ((Opcode << 8) | ACPI_GET8 (Aml)); } return (Opcode); } /******************************************************************************* * * FUNCTION: AcpiPsCompleteThisOp * * PARAMETERS: WalkState - Current State * Op - Op to complete * * RETURN: Status * * DESCRIPTION: Perform any cleanup at the completion of an Op. * ******************************************************************************/ ACPI_STATUS AcpiPsCompleteThisOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_PARSE_OBJECT *Prev; ACPI_PARSE_OBJECT *Next; const ACPI_OPCODE_INFO *ParentInfo; ACPI_PARSE_OBJECT *ReplacementOp = NULL; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (PsCompleteThisOp, Op); /* Check for null Op, can happen if AML code is corrupt */ if (!Op) { return_ACPI_STATUS (AE_OK); /* OK for now */ } AcpiExStopTraceOpcode (Op, WalkState); /* Delete this op and the subtree below it if asked to */ if (((WalkState->ParseFlags & ACPI_PARSE_TREE_MASK) != ACPI_PARSE_DELETE_TREE) || (WalkState->OpInfo->Class == AML_CLASS_ARGUMENT)) { return_ACPI_STATUS (AE_OK); } /* Make sure that we only delete this subtree */ if (Op->Common.Parent) { Prev = Op->Common.Parent->Common.Value.Arg; if (!Prev) { /* Nothing more to do */ goto Cleanup; } /* * Check if we need to replace the operator and its subtree * with a return value op (placeholder op) */ ParentInfo = AcpiPsGetOpcodeInfo (Op->Common.Parent->Common.AmlOpcode); switch (ParentInfo->Class) { case AML_CLASS_CONTROL: break; case AML_CLASS_CREATE: /* * These opcodes contain TermArg operands. The current * op must be replaced by a placeholder return op */ ReplacementOp = AcpiPsAllocOp ( AML_INT_RETURN_VALUE_OP, Op->Common.Aml); if (!ReplacementOp) { Status = AE_NO_MEMORY; } break; case AML_CLASS_NAMED_OBJECT: /* * These opcodes contain TermArg operands. The current * op must be replaced by a placeholder return op */ if ((Op->Common.Parent->Common.AmlOpcode == AML_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_DATA_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BANK_FIELD_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP)) { ReplacementOp = AcpiPsAllocOp ( AML_INT_RETURN_VALUE_OP, Op->Common.Aml); if (!ReplacementOp) { Status = AE_NO_MEMORY; } } else if ((Op->Common.Parent->Common.AmlOpcode == AML_NAME_OP) && (WalkState->PassNumber <= ACPI_IMODE_LOAD_PASS2)) { if ((Op->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP)) { ReplacementOp = AcpiPsAllocOp (Op->Common.AmlOpcode, Op->Common.Aml); if (!ReplacementOp) { Status = AE_NO_MEMORY; } else { ReplacementOp->Named.Data = Op->Named.Data; ReplacementOp->Named.Length = Op->Named.Length; } } } break; default: ReplacementOp = AcpiPsAllocOp ( AML_INT_RETURN_VALUE_OP, Op->Common.Aml); if (!ReplacementOp) { Status = AE_NO_MEMORY; } } /* We must unlink this op from the parent tree */ if (Prev == Op) { /* This op is the first in the list */ if (ReplacementOp) { ReplacementOp->Common.Parent = Op->Common.Parent; ReplacementOp->Common.Value.Arg = NULL; ReplacementOp->Common.Node = Op->Common.Node; Op->Common.Parent->Common.Value.Arg = ReplacementOp; ReplacementOp->Common.Next = Op->Common.Next; } else { Op->Common.Parent->Common.Value.Arg = Op->Common.Next; } } /* Search the parent list */ else while (Prev) { /* Traverse all siblings in the parent's argument list */ Next = Prev->Common.Next; if (Next == Op) { if (ReplacementOp) { ReplacementOp->Common.Parent = Op->Common.Parent; ReplacementOp->Common.Value.Arg = NULL; ReplacementOp->Common.Node = Op->Common.Node; Prev->Common.Next = ReplacementOp; ReplacementOp->Common.Next = Op->Common.Next; Next = NULL; } else { Prev->Common.Next = Op->Common.Next; Next = NULL; } } Prev = Next; } } Cleanup: /* Now we can actually delete the subtree rooted at Op */ AcpiPsDeleteParseTree (Op); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiPsNextParseState * * PARAMETERS: WalkState - Current state * Op - Current parse op * CallbackStatus - Status from previous operation * * RETURN: Status * * DESCRIPTION: Update the parser state based upon the return exception from * the parser callback. * ******************************************************************************/ ACPI_STATUS AcpiPsNextParseState ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_STATUS CallbackStatus) { ACPI_PARSE_STATE *ParserState = &WalkState->ParserState; ACPI_STATUS Status = AE_CTRL_PENDING; ACPI_FUNCTION_TRACE_PTR (PsNextParseState, Op); switch (CallbackStatus) { case AE_CTRL_TERMINATE: /* * A control method was terminated via a RETURN statement. * The walk of this method is complete. */ ParserState->Aml = ParserState->AmlEnd; Status = AE_CTRL_TERMINATE; break; case AE_CTRL_BREAK: ParserState->Aml = WalkState->AmlLastWhile; WalkState->ControlState->Common.Value = FALSE; Status = AE_CTRL_BREAK; break; case AE_CTRL_CONTINUE: ParserState->Aml = WalkState->AmlLastWhile; Status = AE_CTRL_CONTINUE; break; case AE_CTRL_PENDING: ParserState->Aml = WalkState->AmlLastWhile; break; #if 0 case AE_CTRL_SKIP: ParserState->Aml = ParserState->Scope->ParseScope.PkgEnd; Status = AE_OK; break; #endif case AE_CTRL_TRUE: /* * Predicate of an IF was true, and we are at the matching ELSE. * Just close out this package */ ParserState->Aml = AcpiPsGetNextPackageEnd (ParserState); Status = AE_CTRL_PENDING; break; case AE_CTRL_FALSE: /* * Either an IF/WHILE Predicate was false or we encountered a BREAK * opcode. In both cases, we do not execute the rest of the * package; We simply close out the parent (finishing the walk of * this branch of the tree) and continue execution at the parent * level. */ ParserState->Aml = ParserState->Scope->ParseScope.PkgEnd; /* In the case of a BREAK, just force a predicate (if any) to FALSE */ WalkState->ControlState->Common.Value = FALSE; Status = AE_CTRL_END; break; case AE_CTRL_TRANSFER: /* A method call (invocation) -- transfer control */ Status = AE_CTRL_TRANSFER; WalkState->PrevOp = Op; WalkState->MethodCallOp = Op; WalkState->MethodCallNode = (Op->Common.Value.Arg)->Common.Node; /* Will return value (if any) be used by the caller? */ WalkState->ReturnUsed = AcpiDsIsResultUsed (Op, WalkState); break; default: Status = CallbackStatus; if ((CallbackStatus & AE_CODE_MASK) == AE_CODE_CONTROL) { Status = AE_OK; } break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiPsParseAml * * PARAMETERS: WalkState - Current state * * * RETURN: Status * * DESCRIPTION: Parse raw AML and return a tree of ops * ******************************************************************************/ ACPI_STATUS AcpiPsParseAml ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_THREAD_STATE *Thread; ACPI_THREAD_STATE *PrevWalkList = AcpiGbl_CurrentWalkList; ACPI_WALK_STATE *PreviousWalkState; ACPI_FUNCTION_TRACE (PsParseAml); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Entered with WalkState=%p Aml=%p size=%X\n", WalkState, WalkState->ParserState.Aml, WalkState->ParserState.AmlSize)); if (!WalkState->ParserState.Aml) { return_ACPI_STATUS (AE_BAD_ADDRESS); } /* Create and initialize a new thread state */ Thread = AcpiUtCreateThreadState (); if (!Thread) { if (WalkState->MethodDesc) { /* Executing a control method - additional cleanup */ AcpiDsTerminateControlMethod (WalkState->MethodDesc, WalkState); } AcpiDsDeleteWalkState (WalkState); return_ACPI_STATUS (AE_NO_MEMORY); } WalkState->Thread = Thread; /* * If executing a method, the starting SyncLevel is this method's * SyncLevel */ if (WalkState->MethodDesc) { WalkState->Thread->CurrentSyncLevel = WalkState->MethodDesc->Method.SyncLevel; } AcpiDsPushWalkState (WalkState, Thread); /* * This global allows the AML debugger to get a handle to the currently * executing control method. */ AcpiGbl_CurrentWalkList = Thread; /* * Execute the walk loop as long as there is a valid Walk State. This * handles nested control method invocations without recursion. */ ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "State=%p\n", WalkState)); Status = AE_OK; while (WalkState) { if (ACPI_SUCCESS (Status)) { /* * The ParseLoop executes AML until the method terminates * or calls another method. */ Status = AcpiPsParseLoop (WalkState); } ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Completed one call to walk loop, %s State=%p\n", AcpiFormatException (Status), WalkState)); if (WalkState->MethodPathname && WalkState->MethodIsNested) { /* Optional object evaluation log */ ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EVALUATION, "%-26s: %*s%s\n", " Exit nested method", (WalkState->MethodNestingDepth + 1) * 3, " ", &WalkState->MethodPathname[1])); ACPI_FREE (WalkState->MethodPathname); WalkState->MethodIsNested = FALSE; } if (Status == AE_CTRL_TRANSFER) { /* * A method call was detected. * Transfer control to the called control method */ Status = AcpiDsCallControlMethod (Thread, WalkState, NULL); if (ACPI_FAILURE (Status)) { Status = AcpiDsMethodError (Status, WalkState); } /* * If the transfer to the new method method call worked *, a new walk state was created -- get it */ WalkState = AcpiDsGetCurrentWalkState (Thread); continue; } else if (Status == AE_CTRL_TERMINATE) { Status = AE_OK; } else if ((Status != AE_OK) && (WalkState->MethodDesc)) { /* Either the method parse or actual execution failed */ AcpiExExitInterpreter (); if (Status == AE_ABORT_METHOD) { AcpiNsPrintNodePathname ( WalkState->MethodNode, "Aborting method"); AcpiOsPrintf ("\n"); } else { ACPI_ERROR_METHOD ("Aborting method", WalkState->MethodNode, NULL, Status); } AcpiExEnterInterpreter (); /* Check for possible multi-thread reentrancy problem */ if ((Status == AE_ALREADY_EXISTS) && (!(WalkState->MethodDesc->Method.InfoFlags & ACPI_METHOD_SERIALIZED))) { /* * Method is not serialized and tried to create an object * twice. The probable cause is that the method cannot * handle reentrancy. Mark as "pending serialized" now, and * then mark "serialized" when the last thread exits. */ WalkState->MethodDesc->Method.InfoFlags |= ACPI_METHOD_SERIALIZED_PENDING; } } /* We are done with this walk, move on to the parent if any */ WalkState = AcpiDsPopWalkState (Thread); /* Reset the current scope to the beginning of scope stack */ AcpiDsScopeStackClear (WalkState); /* * If we just returned from the execution of a control method or if we * encountered an error during the method parse phase, there's lots of * cleanup to do */ if (((WalkState->ParseFlags & ACPI_PARSE_MODE_MASK) == ACPI_PARSE_EXECUTE && !(WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL)) || (ACPI_FAILURE (Status))) { AcpiDsTerminateControlMethod (WalkState->MethodDesc, WalkState); } /* Delete this walk state and all linked control states */ AcpiPsCleanupScope (&WalkState->ParserState); PreviousWalkState = WalkState; ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "ReturnValue=%p, ImplicitValue=%p State=%p\n", WalkState->ReturnDesc, WalkState->ImplicitReturnObj, WalkState)); /* Check if we have restarted a preempted walk */ WalkState = AcpiDsGetCurrentWalkState (Thread); if (WalkState) { if (ACPI_SUCCESS (Status)) { /* * There is another walk state, restart it. * If the method return value is not used by the parent, * The object is deleted */ if (!PreviousWalkState->ReturnDesc) { /* * In slack mode execution, if there is no return value * we should implicitly return zero (0) as a default value. */ if (AcpiGbl_EnableInterpreterSlack && !PreviousWalkState->ImplicitReturnObj) { PreviousWalkState->ImplicitReturnObj = AcpiUtCreateIntegerObject ((UINT64) 0); if (!PreviousWalkState->ImplicitReturnObj) { return_ACPI_STATUS (AE_NO_MEMORY); } } /* Restart the calling control method */ Status = AcpiDsRestartControlMethod (WalkState, PreviousWalkState->ImplicitReturnObj); } else { /* * We have a valid return value, delete any implicit * return value. */ AcpiDsClearImplicitReturn (PreviousWalkState); Status = AcpiDsRestartControlMethod (WalkState, PreviousWalkState->ReturnDesc); } if (ACPI_SUCCESS (Status)) { WalkState->WalkType |= ACPI_WALK_METHOD_RESTART; } } else { /* On error, delete any return object or implicit return */ AcpiUtRemoveReference (PreviousWalkState->ReturnDesc); AcpiDsClearImplicitReturn (PreviousWalkState); } } /* * Just completed a 1st-level method, save the final internal return * value (if any) */ else if (PreviousWalkState->CallerReturnDesc) { if (PreviousWalkState->ImplicitReturnObj) { *(PreviousWalkState->CallerReturnDesc) = PreviousWalkState->ImplicitReturnObj; } else { /* NULL if no return value */ *(PreviousWalkState->CallerReturnDesc) = PreviousWalkState->ReturnDesc; } } else { if (PreviousWalkState->ReturnDesc) { /* Caller doesn't want it, must delete it */ AcpiUtRemoveReference (PreviousWalkState->ReturnDesc); } if (PreviousWalkState->ImplicitReturnObj) { /* Caller doesn't want it, must delete it */ AcpiUtRemoveReference (PreviousWalkState->ImplicitReturnObj); } } AcpiDsDeleteWalkState (PreviousWalkState); } /* Normal exit */ AcpiExReleaseAllMutexes (Thread); AcpiUtDeleteGenericState (ACPI_CAST_PTR (ACPI_GENERIC_STATE, Thread)); AcpiGbl_CurrentWalkList = PrevWalkList; return_ACPI_STATUS (Status); } <file_sep>#!/usr/bin/env bash pkg="$1" ci= if [ "$1" == "-ci" ]; then pkg="$2" ci=1 fi if ! pacman -Q $pkg &> /dev/null; then echo "We need to install the package $pkg" if [ "$ci" == 1 ]; then cmd="pacman -S --noconfirm $pkg" else cmd="sudo pacman -S $pkg" fi echo "Running the command: $cmd" eval $cmd fi <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/process.h> #include <tilck/kernel/fs/flock.h> #include <tilck/kernel/test/vfs.h> #include <sys/mman.h> // system header #include "ramfs_int.h" #include "getdents.c.h" #include "locking.c.h" #include "dir_entries.c.h" #include "inodes.c.h" #include "stat.c.h" #include "blocks.c.h" #include "mmap.c.h" #include "rw_ops.c.h" #include "open.c.h" #include "mkdir.c.h" static int ramfs_unlink(struct vfs_path *p) { struct ramfs_path *rp = (struct ramfs_path *) &p->fs_path; struct ramfs_data *d = p->fs->device_data; struct ramfs_inode *i = rp->inode; struct ramfs_inode *idir = rp->dir_inode; ASSERT(rwlock_wp_holding_exlock(&d->rwlock)); if (i->type == VFS_DIR) return -EISDIR; if ((idir->mode & 0200) != 0200) /* write permission */ return -EACCES; /* * The only case when `rp->e` is NULL is when path == "/", but we have just * checked the directory case. Therefore, `rp->e` must be valid. */ ASSERT(rp->dir_entry != NULL); /* Remove the dir entry */ ramfs_dir_remove_entry(idir, rp->dir_entry); /* Trucate and delete the inode, if it's not used */ if (!i->nlink && !get_ref_count(i)) { if (i->type == VFS_FILE) { DEBUG_ONLY_UNSAFE(int rc =) ramfs_inode_truncate_safe(i, 0, true /* no_perm_check */); ASSERT(rc == 0); } ramfs_destroy_inode(d, i); } return 0; } static void ramfs_on_close(fs_handle h) { struct ramfs_handle *rh = h; struct ramfs_inode *i = rh->inode; if (i->type == VFS_DIR) { /* Remove this handle from h->inode->handles_list */ list_remove(&rh->node); } } static void ramfs_on_close_last_handle(fs_handle h) { struct ramfs_handle *rh = h; struct ramfs_inode *i = rh->inode; if (!i->nlink) { /* * !get_ref_count(i) => no handle referring to this inode * !i->nlink => no dir entry referring to this inode * * It means the last link (dir entry) pointing to this inode has been * removed while the current task was keeping opened a handle to this * inode. Now, nobody can get to this inode anymore. We have to destroy * it. */ if (i->type == VFS_FILE) ramfs_inode_truncate_safe(i, 0, true); ramfs_destroy_inode(rh->fs->device_data, i); } } /* * This function is supposed to be called ONLY by ramfs_create() in its error * path, as a clean-up. It is *not* a proper way to destroy a whole ramfs * instance after unmounting it. */ static void ramfs_err_case_destroy(struct mnt_fs *fs) { struct ramfs_data *d = fs->device_data; if (d) { if (d->root) { ramfs_destroy_inode(d, d->root); } rwlock_wp_destroy(&d->rwlock); kfree_obj(d, struct ramfs_data); } destory_fs_obj(fs); } static void ramfs_get_entry(struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t name_len, struct fs_path *fs_path) { struct ramfs_data *d = fs->device_data; struct ramfs_inode *idir = dir_inode; struct ramfs_entry *re; if (!dir_inode) { *fs_path = (struct fs_path) { .inode = d->root, .dir_inode = d->root, .dir_entry = NULL, .type = VFS_DIR, }; return; } re = ramfs_dir_get_entry_by_name(idir, name, name_len); *fs_path = (struct fs_path) { .inode = re ? re->inode : NULL, .dir_inode = idir, .dir_entry = re, .type = re ? re->inode->type : VFS_NONE, }; } static vfs_inode_ptr_t ramfs_getinode(fs_handle h) { return ((struct ramfs_handle *)h)->inode; } static int ramfs_symlink(const char *target, struct vfs_path *lp) { struct ramfs_data *d = lp->fs->device_data; struct ramfs_inode *n; n = ramfs_create_inode_symlink(d, lp->fs_path.dir_inode, target); if (!n) return -ENOSPC; return ramfs_dir_add_entry(lp->fs_path.dir_inode, lp->last_comp, n); } /* NOTE: `buf` is guaranteed to have room for at least MAX_PATH chars */ static int ramfs_readlink(struct vfs_path *p, char *buf) { struct ramfs_inode *i = p->fs_path.inode; if (i->type != VFS_SYMLINK) return -EINVAL; memcpy(buf, i->path, i->path_len); /* skip final \0 */ return (int) i->path_len; } static int ramfs_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { ASSERT(inode != NULL); if (!(fs->flags & VFS_FS_RW)) return 1; return retain_obj((struct ramfs_inode *)inode); } static int ramfs_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { ASSERT(inode != NULL); if (!(fs->flags & VFS_FS_RW)) return 1; return release_obj((struct ramfs_inode *)inode); } static int ramfs_chmod(struct mnt_fs *fs, vfs_inode_ptr_t inode, mode_t mode) { struct ramfs_inode *i = inode; int rc; rwlock_wp_exlock(&i->rwlock); { const mode_t special_bits = mode & (mode_t)~0777; const mode_t curr_spec_bits = i->mode & (mode_t)~0777; if (!special_bits || special_bits == curr_spec_bits) { i->mode = curr_spec_bits | (mode & 0777); rc = 0; } else { /* Special bits (e.g. sticky bit etc.) are not supported by Tilck */ rc = -EPERM; } } rwlock_wp_exunlock(&i->rwlock); return rc; } static int ramfs_rename(struct mnt_fs *fs, struct vfs_path *voldp, struct vfs_path *vnewp) { struct ramfs_path *oldp = (void *)&voldp->fs_path; struct ramfs_path *newp = (void *)&vnewp->fs_path; int rc; DEBUG_ONLY_UNSAFE(struct ramfs_data *d = fs->device_data); ASSERT(rwlock_wp_holding_exlock(&d->rwlock)); if (newp->inode != NULL) { if (newp->type == VFS_DIR) { if (oldp->type != VFS_DIR) return -EISDIR; if (newp->inode->num_entries > 2) return -ENOTEMPTY; if ((rc = ramfs_rmdir(vnewp))) return rc; } else { if ((rc = ramfs_unlink(vnewp))) return rc; } } rc = ramfs_dir_add_entry(newp->dir_inode, vnewp->last_comp, oldp->inode); if (rc) { /* * Note: the only way this last call could fail is OOM case because of a * race condition exactly between the rmdir/unlink operation and the * creation of the new entry. In that case, the rename syscall will fail * and the destination path (if existing) would be deleted. This is a rare * case of failing syscall having a side-effect. The eventual problem * could be fixed by disabling the preemption here or by avoiding the * destruction of the entry object and then resuing it. Both of these * solutions aren't very elegant and it seems like it's not worth to * implement either of them, at least at the moment; in the future the * trade-off might change. */ return rc; } /* Finally, this operation cannot fail. */ ramfs_dir_remove_entry(oldp->dir_inode, oldp->dir_entry); return 0; } static int ramfs_link(struct mnt_fs *fs, struct vfs_path *voldp, struct vfs_path *vnewp) { struct ramfs_path *oldp = (void *)&voldp->fs_path; struct ramfs_path *newp = (void *)&vnewp->fs_path; if (oldp->type != VFS_FILE) return -EPERM; if (newp->inode != NULL) return -EEXIST; return ramfs_dir_add_entry(newp->dir_inode, vnewp->last_comp, oldp->inode); } int ramfs_futimens(struct mnt_fs *fs, vfs_inode_ptr_t inode, const struct k_timespec64 times[2]) { struct ramfs_inode *i = inode; if ((i->mode & 0200) != 0200) return -EACCES; i->mtime = times[1]; return 0; } static const struct fs_ops static_fsops_ramfs = { .get_inode = ramfs_getinode, .open = ramfs_open, .on_close = ramfs_on_close, .on_close_last_handle = ramfs_on_close_last_handle, .getdents = ramfs_getdents, .unlink = ramfs_unlink, .mkdir = ramfs_mkdir, .rmdir = ramfs_rmdir, .truncate = ramfs_truncate, .stat = ramfs_stat, .symlink = ramfs_symlink, .readlink = ramfs_readlink, .chmod = ramfs_chmod, .get_entry = ramfs_get_entry, .rename = ramfs_rename, .link = ramfs_link, .futimens = ramfs_futimens, .retain_inode = ramfs_retain_inode, .release_inode = ramfs_release_inode, .fs_exlock = ramfs_exlock, .fs_exunlock = ramfs_exunlock, .fs_shlock = ramfs_shlock, .fs_shunlock = ramfs_shunlock, }; struct mnt_fs *ramfs_create(void) { struct mnt_fs *fs; struct ramfs_data *d; if (!(d = kzalloc_obj(struct ramfs_data))) return NULL; fs = create_fs_obj("ramfs", &static_fsops_ramfs, d, VFS_FS_RW); if (!fs) { kfree_obj(d, struct ramfs_data); return NULL; } rwlock_wp_init(&d->rwlock, false); d->next_inode_num = 1; d->root = ramfs_create_inode_dir(d, 0777, NULL); if (!d->root) { ramfs_err_case_destroy(fs); return NULL; } return fs; } <file_sep>#!/usr/bin/env bash BUILD_DIR="@CMAKE_BINARY_DIR@" if uname -a | grep -i microsoft &> /dev/null; then echo "It looks like you're using WSL (a.k.a. \"Bash for Windows\"): " echo "therefore, KVM is not available." echo "Just run the *nokvm* version of this script." exit 1 fi if ! lsmod | grep kvm &> /dev/null; then echo "WARNING: it looks like KVM is not installed on this machine." echo "Please install qemu-kvm and add the current user to the kvm group " echo "OR just run the *nokvm* version of this script." echo "The launch of QEMU with the -enable-kvm option will likely fail." echo else if [[ $EUID -ne 0 ]]; then if ! getent group kvm | grep &>/dev/null "\b${USER}\b"; then echo "WARNING: it looks like the current user is not in the 'kvm'" echo "group. Likely the launch of QEMU with the -enable-kvm option " echo "will fail." echo fi fi fi $BUILD_DIR/run_efi_nokvm_qemu32 -enable-kvm -cpu host "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ extern "C" { #include <tilck/common/basic_defs.h> } #ifndef __cplusplus #error This is a C++-only header. Use it from a C++ source file. #endif /* * Unfortunately, in C++11 there's no such thing as Dlang's "static if". * Therefore, even if in practice regular IFs behave like "static if"s when * their condition is known at compile-time, this happens at a lower level, * where dead code branches are discarded. At higher levels, we still must * provide an instantiation for every value of `size` we wanna support, * including our spacial '0'. Therefore, it's a useful hack to introduce * something like this `__bad_type`, in order to prevent accidental uses of * (un)signed_by_size<N>::type. */ struct __bad_type { __bad_type() = delete; __bad_type(const __bad_type&) = delete; __bad_type(__bad_type&&) = delete; ~__bad_type() = delete; __bad_type& operator=(__bad_type&&) = delete; __bad_type& operator=(const __bad_type&) { NOT_REACHED(); } }; template <int size> struct signed_by_size; template <> struct signed_by_size<0> { typedef __bad_type type; }; template <> struct signed_by_size<1> { typedef s8 type; }; template <> struct signed_by_size<2> { typedef s16 type; }; template <> struct signed_by_size<4> { typedef s32 type; }; template <> struct signed_by_size<8> { typedef s64 type; }; template <int size> struct unsigned_by_size; template <> struct unsigned_by_size<0> { typedef __bad_type type; }; template <> struct unsigned_by_size<1> { typedef u8 type; }; template <> struct unsigned_by_size<2> { typedef u16 type; }; template <> struct unsigned_by_size<4> { typedef u32 type; }; template <> struct unsigned_by_size<8> { typedef u64 type; }; /* signed -> unsigned_type */ template <typename T> struct unsigned_type; template <> struct unsigned_type<s8> { typedef u8 type; }; template <> struct unsigned_type<s16> { typedef u16 type; }; template <> struct unsigned_type<s32> { typedef u32 type; }; template <> struct unsigned_type<s64> { typedef u64 type; }; #if NBITS == 32 template <> struct unsigned_type<long> { typedef ulong type; }; #endif template <> struct unsigned_type<u8> { typedef u8 type; }; template <> struct unsigned_type<u16> { typedef u16 type; }; template <> struct unsigned_type<u32> { typedef u32 type; }; template <> struct unsigned_type<u64> { typedef u64 type; }; #if NBITS == 32 template <> struct unsigned_type<ulong> { typedef ulong type; }; #endif /* is unsigned */ template <typename T> struct is_unsigned { enum { val = 0 }; }; template <> struct is_unsigned<u8> { enum { val = 1 }; }; template <> struct is_unsigned<u16> { enum { val = 1 }; }; template <> struct is_unsigned<u32> { enum { val = 1 }; }; template <> struct is_unsigned<u64> { enum { val = 1 }; }; #if NBITS == 32 template <> struct is_unsigned<ulong> { enum { val = 1 }; }; #endif /* numeric limits */ template <typename T> struct limits; #define INST_LIMIT_TEMPL(T, m, M) \ template <> \ struct limits<T> { \ static constexpr T min() { return m; }; \ static constexpr T max() { return M; }; \ } INST_LIMIT_TEMPL(u8, 0, UCHAR_MAX); INST_LIMIT_TEMPL(u16, 0, USHRT_MAX); INST_LIMIT_TEMPL(u32, 0, UINT_MAX); INST_LIMIT_TEMPL(u64, 0, ULLONG_MAX); INST_LIMIT_TEMPL(s8, CHAR_MIN, CHAR_MAX); INST_LIMIT_TEMPL(s16, SHRT_MIN, SHRT_MAX); INST_LIMIT_TEMPL(s32, INT_MIN, INT_MAX); INST_LIMIT_TEMPL(s64, LLONG_MIN, LLONG_MAX); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/user.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/gcov.h> #include <tilck/kernel/debug_utils.h> typedef int (*tilck_cmd_func)(); static int sys_tilck_run_selftest(const char *user_selftest); static void *tilck_cmds[TILCK_CMD_COUNT] = { [TILCK_CMD_RUN_SELFTEST] = sys_tilck_run_selftest, [TILCK_CMD_GCOV_GET_NUM_FILES] = sys_gcov_get_file_count, [TILCK_CMD_GCOV_FILE_INFO] = sys_gcov_get_file_info, [TILCK_CMD_GCOV_GET_FILE] = sys_gcov_get_file, [TILCK_CMD_QEMU_POWEROFF] = debug_qemu_turn_off_machine, [TILCK_CMD_SET_SAT_ENABLED] = set_sched_alive_thread_enabled, [TILCK_CMD_DEBUG_PANEL] = NULL, [TILCK_CMD_TRACING_TOOL] = NULL, [TILCK_CMD_PS_TOOL] = NULL, [TILCK_CMD_DEBUGGER_TOOL] = NULL, }; void register_tilck_cmd(int cmd_n, void *func) { ASSERT(0 <= cmd_n && cmd_n < TILCK_CMD_COUNT); VERIFY(tilck_cmds[cmd_n] == NULL); tilck_cmds[cmd_n] = func; } static int sys_tilck_run_selftest(const char *u_selftest) { int rc; struct self_test *se; char buf[96]; if (!KERNEL_SELFTESTS) return -EINVAL; rc = copy_str_from_user(buf, u_selftest, sizeof(buf) - 1, NULL); if (rc != 0) return -EFAULT; se = se_find(buf); if (!se) return -EINVAL; printk("Running self-test: %s\n", buf); return se_run(se); } int sys_tilck_cmd(int cmd_n, ulong a1, ulong a2, ulong a3, ulong a4) { tilck_cmd_func func; if (cmd_n >= TILCK_CMD_COUNT) return -EINVAL; *(void **)(&func) = tilck_cmds[cmd_n]; if (!func) return -EINVAL; return func(a1, a2, a3, a4); } <file_sep>/****************************************************************************** * * Name: acpixf.h - External interfaces to the ACPI subsystem * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACXFACE_H__ #define __ACXFACE_H__ /* Current ACPICA subsystem version in YYYYMMDD format */ #define ACPI_CA_VERSION 0x20200717 #include "acconfig.h" #include "actypes.h" #include "actbl.h" #include "acbuffer.h" /***************************************************************************** * * Macros used for ACPICA globals and configuration * ****************************************************************************/ /* * Ensure that global variables are defined and initialized only once. * * The use of these macros allows for a single list of globals (here) * in order to simplify maintenance of the code. */ #ifdef DEFINE_ACPI_GLOBALS #define ACPI_GLOBAL(type,name) \ extern type name; \ type name #define ACPI_INIT_GLOBAL(type,name,value) \ type name=value #else #ifndef ACPI_GLOBAL #define ACPI_GLOBAL(type,name) \ extern type name #endif #ifndef ACPI_INIT_GLOBAL #define ACPI_INIT_GLOBAL(type,name,value) \ extern type name #endif #endif /* * These macros configure the various ACPICA interfaces. They are * useful for generating stub inline functions for features that are * configured out of the current kernel or ACPICA application. */ #ifndef ACPI_EXTERNAL_RETURN_STATUS #define ACPI_EXTERNAL_RETURN_STATUS(Prototype) \ Prototype; #endif #ifndef ACPI_EXTERNAL_RETURN_OK #define ACPI_EXTERNAL_RETURN_OK(Prototype) \ Prototype; #endif #ifndef ACPI_EXTERNAL_RETURN_VOID #define ACPI_EXTERNAL_RETURN_VOID(Prototype) \ Prototype; #endif #ifndef ACPI_EXTERNAL_RETURN_UINT32 #define ACPI_EXTERNAL_RETURN_UINT32(Prototype) \ Prototype; #endif #ifndef ACPI_EXTERNAL_RETURN_PTR #define ACPI_EXTERNAL_RETURN_PTR(Prototype) \ Prototype; #endif /***************************************************************************** * * Public globals and runtime configuration options * ****************************************************************************/ /* * Enable "slack mode" of the AML interpreter? Default is FALSE, and the * interpreter strictly follows the ACPI specification. Setting to TRUE * allows the interpreter to ignore certain errors and/or bad AML constructs. * * Currently, these features are enabled by this flag: * * 1) Allow "implicit return" of last value in a control method * 2) Allow access beyond the end of an operation region * 3) Allow access to uninitialized locals/args (auto-init to integer 0) * 4) Allow ANY object type to be a source operand for the Store() operator * 5) Allow unresolved references (invalid target name) in package objects * 6) Enable warning messages for behavior that is not ACPI spec compliant */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_EnableInterpreterSlack, FALSE); /* * Automatically serialize all methods that create named objects? Default * is TRUE, meaning that all NonSerialized methods are scanned once at * table load time to determine those that create named objects. Methods * that create named objects are marked Serialized in order to prevent * possible run-time problems if they are entered by more than one thread. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_AutoSerializeMethods, TRUE); /* * Create the predefined _OSI method in the namespace? Default is TRUE * because ACPICA is fully compatible with other ACPI implementations. * Changing this will revert ACPICA (and machine ASL) to pre-OSI behavior. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_CreateOsiMethod, TRUE); /* * Optionally use default values for the ACPI register widths. Set this to * TRUE to use the defaults, if an FADT contains incorrect widths/lengths. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_UseDefaultRegisterWidths, TRUE); /* * Whether or not to validate (map) an entire table to verify * checksum/duplication in early stage before install. Set this to TRUE to * allow early table validation before install it to the table manager. * Note that enabling this option causes errors to happen in some OSPMs * during early initialization stages. Default behavior is to allow such * validation. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_EnableTableValidation, TRUE); /* * Optionally enable output from the AML Debug Object. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_EnableAmlDebugObject, FALSE); /* * Optionally copy the entire DSDT to local memory (instead of simply * mapping it.) There are some BIOSs that corrupt or replace the original * DSDT, creating the need for this option. Default is FALSE, do not copy * the DSDT. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_CopyDsdtLocally, FALSE); /* * Optionally ignore an XSDT if present and use the RSDT instead. * Although the ACPI specification requires that an XSDT be used instead * of the RSDT, the XSDT has been found to be corrupt or ill-formed on * some machines. Default behavior is to use the XSDT if present. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_DoNotUseXsdt, FALSE); /* * Optionally use 32-bit FADT addresses if and when there is a conflict * (address mismatch) between the 32-bit and 64-bit versions of the * address. Although ACPICA adheres to the ACPI specification which * requires the use of the corresponding 64-bit address if it is non-zero, * some machines have been found to have a corrupted non-zero 64-bit * address. Default is FALSE, do not favor the 32-bit addresses. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_Use32BitFadtAddresses, FALSE); /* * Optionally use 32-bit FACS table addresses. * It is reported that some platforms fail to resume from system suspending * if 64-bit FACS table address is selected: * https://bugzilla.kernel.org/show_bug.cgi?id=74021 * Default is TRUE, favor the 32-bit addresses. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_Use32BitFacsAddresses, TRUE); /* * Optionally truncate I/O addresses to 16 bits. Provides compatibility * with other ACPI implementations. NOTE: During ACPICA initialization, * this value is set to TRUE if any Windows OSI strings have been * requested by the BIOS. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_TruncateIoAddresses, FALSE); /* * Disable runtime checking and repair of values returned by control methods. * Use only if the repair is causing a problem on a particular machine. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_DisableAutoRepair, FALSE); /* * Optionally do not install any SSDTs from the RSDT/XSDT during initialization. * This can be useful for debugging ACPI problems on some machines. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_DisableSsdtTableInstall, FALSE); /* * Optionally enable runtime namespace override. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_RuntimeNamespaceOverride, TRUE); /* * We keep track of the latest version of Windows that has been requested by * the BIOS. ACPI 5.0. */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_OsiData, 0); /* * ACPI 5.0 introduces the concept of a "reduced hardware platform", meaning * that the ACPI hardware is no longer required. A flag in the FADT indicates * a reduced HW machine, and that flag is duplicated here for convenience. */ ACPI_INIT_GLOBAL (BOOLEAN, AcpiGbl_ReducedHardware, FALSE); /* * Maximum timeout for While() loop iterations before forced method abort. * This mechanism is intended to prevent infinite loops during interpreter * execution within a host kernel. */ ACPI_INIT_GLOBAL (UINT32, AcpiGbl_MaxLoopIterations, ACPI_MAX_LOOP_TIMEOUT); /* * Optionally ignore AE_NOT_FOUND errors from named reference package elements * during DSDT/SSDT table loading. This reduces error "noise" in platforms * whose firmware is carrying around a bunch of unused package objects that * refer to non-existent named objects. However, If the AML actually tries to * use such a package, the unresolved element(s) will be replaced with NULL * elements. */ ACPI_INIT_GLOBAL (BOOLEAN, AcpiGbl_IgnorePackageResolutionErrors, FALSE); /* * This mechanism is used to trace a specified AML method. The method is * traced each time it is executed. */ ACPI_INIT_GLOBAL (UINT32, AcpiGbl_TraceFlags, 0); ACPI_INIT_GLOBAL (const char *, AcpiGbl_TraceMethodName, NULL); ACPI_INIT_GLOBAL (UINT32, AcpiGbl_TraceDbgLevel, ACPI_TRACE_LEVEL_DEFAULT); ACPI_INIT_GLOBAL (UINT32, AcpiGbl_TraceDbgLayer, ACPI_TRACE_LAYER_DEFAULT); /* * Runtime configuration of debug output control masks. We want the debug * switches statically initialized so they are already set when the debugger * is entered. */ #ifdef ACPI_DEBUG_OUTPUT ACPI_INIT_GLOBAL (UINT32, AcpiDbgLevel, ACPI_DEBUG_DEFAULT); #else ACPI_INIT_GLOBAL (UINT32, AcpiDbgLevel, ACPI_NORMAL_DEFAULT); #endif ACPI_INIT_GLOBAL (UINT32, AcpiDbgLayer, ACPI_COMPONENT_DEFAULT); /* Optionally enable timer output with Debug Object output */ ACPI_INIT_GLOBAL (UINT8, AcpiGbl_DisplayDebugTimer, FALSE); /* * Debugger command handshake globals. Host OSes need to access these * variables to implement their own command handshake mechanism. */ #ifdef ACPI_DEBUGGER ACPI_INIT_GLOBAL (BOOLEAN, AcpiGbl_MethodExecuting, FALSE); ACPI_GLOBAL (char, AcpiGbl_DbLineBuf[ACPI_DB_LINE_BUFFER_SIZE]); #endif /* * Other miscellaneous globals */ ACPI_GLOBAL (ACPI_TABLE_FADT, AcpiGbl_FADT); ACPI_GLOBAL (UINT32, AcpiCurrentGpeCount); ACPI_GLOBAL (BOOLEAN, AcpiGbl_SystemAwakeAndRunning); /***************************************************************************** * * ACPICA public interface configuration. * * Interfaces that are configured out of the ACPICA build are replaced * by inlined stubs by default. * ****************************************************************************/ /* * Hardware-reduced prototypes (default: Not hardware reduced). * * All ACPICA hardware-related interfaces that use these macros will be * configured out of the ACPICA build if the ACPI_REDUCED_HARDWARE flag * is set to TRUE. * * Note: This static build option for reduced hardware is intended to * reduce ACPICA code size if desired or necessary. However, even if this * option is not specified, the runtime behavior of ACPICA is dependent * on the actual FADT reduced hardware flag (HW_REDUCED_ACPI). If set, * the flag will enable similar behavior -- ACPICA will not attempt * to access any ACPI-relate hardware (SCI, GPEs, Fixed Events, etc.) */ #if (!ACPI_REDUCED_HARDWARE) #define ACPI_HW_DEPENDENT_RETURN_STATUS(Prototype) \ ACPI_EXTERNAL_RETURN_STATUS(Prototype) #define ACPI_HW_DEPENDENT_RETURN_OK(Prototype) \ ACPI_EXTERNAL_RETURN_OK(Prototype) #define ACPI_HW_DEPENDENT_RETURN_UINT32(prototype) \ ACPI_EXTERNAL_RETURN_UINT32(prototype) #define ACPI_HW_DEPENDENT_RETURN_VOID(Prototype) \ ACPI_EXTERNAL_RETURN_VOID(Prototype) #else #define ACPI_HW_DEPENDENT_RETURN_STATUS(Prototype) \ static ACPI_INLINE Prototype {return(AE_NOT_CONFIGURED);} #define ACPI_HW_DEPENDENT_RETURN_OK(Prototype) \ static ACPI_INLINE Prototype {return(AE_OK);} #define ACPI_HW_DEPENDENT_RETURN_UINT32(prototype) \ static ACPI_INLINE prototype {return(0);} #define ACPI_HW_DEPENDENT_RETURN_VOID(Prototype) \ static ACPI_INLINE Prototype {return;} #endif /* !ACPI_REDUCED_HARDWARE */ /* * Error message prototypes (default: error messages enabled). * * All interfaces related to error and warning messages * will be configured out of the ACPICA build if the * ACPI_NO_ERROR_MESSAGE flag is defined. */ #ifndef ACPI_NO_ERROR_MESSAGES #define ACPI_MSG_DEPENDENT_RETURN_VOID(Prototype) \ Prototype; #else #define ACPI_MSG_DEPENDENT_RETURN_VOID(Prototype) \ static ACPI_INLINE Prototype {return;} #endif /* ACPI_NO_ERROR_MESSAGES */ /* * Debugging output prototypes (default: no debug output). * * All interfaces related to debug output messages * will be configured out of the ACPICA build unless the * ACPI_DEBUG_OUTPUT flag is defined. */ #ifdef ACPI_DEBUG_OUTPUT #define ACPI_DBG_DEPENDENT_RETURN_VOID(Prototype) \ Prototype; #else #define ACPI_DBG_DEPENDENT_RETURN_VOID(Prototype) \ static ACPI_INLINE Prototype {return;} #endif /* ACPI_DEBUG_OUTPUT */ /* * Application prototypes * * All interfaces used by application will be configured * out of the ACPICA build unless the ACPI_APPLICATION * flag is defined. */ #ifdef ACPI_APPLICATION #define ACPI_APP_DEPENDENT_RETURN_VOID(Prototype) \ Prototype; #else #define ACPI_APP_DEPENDENT_RETURN_VOID(Prototype) \ static ACPI_INLINE Prototype {return;} #endif /* ACPI_APPLICATION */ /* * Debugger prototypes * * All interfaces used by debugger will be configured * out of the ACPICA build unless the ACPI_DEBUGGER * flag is defined. */ #ifdef ACPI_DEBUGGER #define ACPI_DBR_DEPENDENT_RETURN_OK(Prototype) \ ACPI_EXTERNAL_RETURN_OK(Prototype) #define ACPI_DBR_DEPENDENT_RETURN_VOID(Prototype) \ ACPI_EXTERNAL_RETURN_VOID(Prototype) #else #define ACPI_DBR_DEPENDENT_RETURN_OK(Prototype) \ static ACPI_INLINE Prototype {return(AE_OK);} #define ACPI_DBR_DEPENDENT_RETURN_VOID(Prototype) \ static ACPI_INLINE Prototype {return;} #endif /* ACPI_DEBUGGER */ /***************************************************************************** * * ACPICA public interface prototypes * ****************************************************************************/ /* * Initialization */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiInitializeTables ( ACPI_TABLE_DESC *InitialStorage, UINT32 InitialTableCount, BOOLEAN AllowResize)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiInitializeSubsystem ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiEnableSubsystem ( UINT32 Flags)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiInitializeObjects ( UINT32 Flags)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiTerminate ( void)) /* * Miscellaneous global interfaces */ ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnable ( void)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiDisable ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiSubsystemStatus ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetSystemInfo ( ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetStatistics ( ACPI_STATISTICS *Stats)) ACPI_EXTERNAL_RETURN_PTR ( const char * AcpiFormatException ( ACPI_STATUS Exception)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiPurgeCachedObjects ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallInterface ( ACPI_STRING InterfaceName)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiRemoveInterface ( ACPI_STRING InterfaceName)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiUpdateInterfaces ( UINT8 Action)) ACPI_EXTERNAL_RETURN_UINT32 ( UINT32 AcpiCheckAddressRange ( ACPI_ADR_SPACE_TYPE SpaceId, ACPI_PHYSICAL_ADDRESS Address, ACPI_SIZE Length, BOOLEAN Warn)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiDecodePldBuffer ( UINT8 *InBuffer, ACPI_SIZE Length, ACPI_PLD_INFO **ReturnBuffer)) /* * ACPI table load/unload interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiInstallTable ( ACPI_PHYSICAL_ADDRESS Address, BOOLEAN Physical)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiLoadTable ( ACPI_TABLE_HEADER *Table, UINT32 *TableIdx)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiUnloadTable ( UINT32 TableIndex)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiUnloadParentTable ( ACPI_HANDLE Object)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiLoadTables ( void)) /* * ACPI table manipulation interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiReallocateRootTable ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS ACPI_INIT_FUNCTION AcpiFindRootPointer ( ACPI_PHYSICAL_ADDRESS *RsdpAddress)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetTableHeader ( ACPI_STRING Signature, UINT32 Instance, ACPI_TABLE_HEADER *OutTableHeader)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetTable ( ACPI_STRING Signature, UINT32 Instance, ACPI_TABLE_HEADER **OutTable)) ACPI_EXTERNAL_RETURN_VOID ( void AcpiPutTable ( ACPI_TABLE_HEADER *Table)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetTableByIndex ( UINT32 TableIndex, ACPI_TABLE_HEADER **OutTable)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallTableHandler ( ACPI_TABLE_HANDLER Handler, void *Context)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiRemoveTableHandler ( ACPI_TABLE_HANDLER Handler)) /* * Namespace and name interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiWalkNamespace ( ACPI_OBJECT_TYPE Type, ACPI_HANDLE StartObject, UINT32 MaxDepth, ACPI_WALK_CALLBACK DescendingCallback, ACPI_WALK_CALLBACK AscendingCallback, void *Context, void **ReturnValue)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetDevices ( char *HID, ACPI_WALK_CALLBACK UserFunction, void *Context, void **ReturnValue)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetName ( ACPI_HANDLE Object, UINT32 NameType, ACPI_BUFFER *RetPathPtr)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetHandle ( ACPI_HANDLE Parent, ACPI_STRING Pathname, ACPI_HANDLE *RetHandle)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiAttachData ( ACPI_HANDLE Object, ACPI_OBJECT_HANDLER Handler, void *Data)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiDetachData ( ACPI_HANDLE Object, ACPI_OBJECT_HANDLER Handler)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetData ( ACPI_HANDLE Object, ACPI_OBJECT_HANDLER Handler, void **Data)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiDebugTrace ( const char *Name, UINT32 DebugLevel, UINT32 DebugLayer, UINT32 Flags)) /* * Object manipulation and enumeration */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiEvaluateObject ( ACPI_HANDLE Object, ACPI_STRING Pathname, ACPI_OBJECT_LIST *ParameterObjects, ACPI_BUFFER *ReturnObjectBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiEvaluateObjectTyped ( ACPI_HANDLE Object, ACPI_STRING Pathname, ACPI_OBJECT_LIST *ExternalParams, ACPI_BUFFER *ReturnBuffer, ACPI_OBJECT_TYPE ReturnType)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetObjectInfo ( ACPI_HANDLE Object, ACPI_DEVICE_INFO **ReturnBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallMethod ( UINT8 *Buffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetNextObject ( ACPI_OBJECT_TYPE Type, ACPI_HANDLE Parent, ACPI_HANDLE Child, ACPI_HANDLE *OutHandle)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetType ( ACPI_HANDLE Object, ACPI_OBJECT_TYPE *OutType)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetParent ( ACPI_HANDLE Object, ACPI_HANDLE *OutHandle)) /* * Handler interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallInitializationHandler ( ACPI_INIT_HANDLER Handler, UINT32 Function)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallSciHandler ( ACPI_SCI_HANDLER Address, void *Context)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiRemoveSciHandler ( ACPI_SCI_HANDLER Address)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallGlobalEventHandler ( ACPI_GBL_EVENT_HANDLER Handler, void *Context)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallFixedEventHandler ( UINT32 AcpiEvent, ACPI_EVENT_HANDLER Handler, void *Context)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiRemoveFixedEventHandler ( UINT32 AcpiEvent, ACPI_EVENT_HANDLER Handler)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, ACPI_GPE_HANDLER Address, void *Context)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallGpeRawHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, ACPI_GPE_HANDLER Address, void *Context)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiRemoveGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, ACPI_GPE_HANDLER Address)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler, void *Context)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiRemoveNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallAddressSpaceHandler ( ACPI_HANDLE Device, ACPI_ADR_SPACE_TYPE SpaceId, ACPI_ADR_SPACE_HANDLER Handler, ACPI_ADR_SPACE_SETUP Setup, void *Context)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiRemoveAddressSpaceHandler ( ACPI_HANDLE Device, ACPI_ADR_SPACE_TYPE SpaceId, ACPI_ADR_SPACE_HANDLER Handler)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallExceptionHandler ( ACPI_EXCEPTION_HANDLER Handler)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiInstallInterfaceHandler ( ACPI_INTERFACE_HANDLER Handler)) /* * Global Lock interfaces */ ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiAcquireGlobalLock ( UINT16 Timeout, UINT32 *Handle)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiReleaseGlobalLock ( UINT32 Handle)) /* * Interfaces to AML mutex objects */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiAcquireMutex ( ACPI_HANDLE Handle, ACPI_STRING Pathname, UINT16 Timeout)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiReleaseMutex ( ACPI_HANDLE Handle, ACPI_STRING Pathname)) /* * Fixed Event interfaces */ ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnableEvent ( UINT32 Event, UINT32 Flags)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiDisableEvent ( UINT32 Event, UINT32 Flags)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiClearEvent ( UINT32 Event)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetEventStatus ( UINT32 Event, ACPI_EVENT_STATUS *EventStatus)) /* * General Purpose Event (GPE) Interfaces */ ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiUpdateAllGpes ( void)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnableGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiDisableGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiClearGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiSetGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT8 Action)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiFinishGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiMaskGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, BOOLEAN IsMasked)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiMarkGpeForWake ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiSetupGpeForWake ( ACPI_HANDLE ParentDevice, ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiSetGpeWakeMask ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT8 Action)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetGpeStatus ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, ACPI_EVENT_STATUS *EventStatus)) ACPI_HW_DEPENDENT_RETURN_UINT32 ( UINT32 AcpiDispatchGpe ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiDisableAllGpes ( void)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnableAllRuntimeGpes ( void)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnableAllWakeupGpes ( void)) ACPI_HW_DEPENDENT_RETURN_UINT32 ( UINT32 AcpiAnyGpeStatusSet ( void)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetGpeDevice ( UINT32 GpeIndex, ACPI_HANDLE *GpeDevice)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiInstallGpeBlock ( ACPI_HANDLE GpeDevice, ACPI_GENERIC_ADDRESS *GpeBlockAddress, UINT32 RegisterCount, UINT32 InterruptNumber)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiRemoveGpeBlock ( ACPI_HANDLE GpeDevice)) /* * Resource interfaces */ typedef ACPI_STATUS (*ACPI_WALK_RESOURCE_CALLBACK) ( ACPI_RESOURCE *Resource, void *Context); ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetVendorResource ( ACPI_HANDLE Device, char *Name, ACPI_VENDOR_UUID *Uuid, ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetCurrentResources ( ACPI_HANDLE Device, ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetPossibleResources ( ACPI_HANDLE Device, ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetEventResources ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiWalkResourceBuffer ( ACPI_BUFFER *Buffer, ACPI_WALK_RESOURCE_CALLBACK UserFunction, void *Context)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiWalkResources ( ACPI_HANDLE Device, char *Name, ACPI_WALK_RESOURCE_CALLBACK UserFunction, void *Context)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiSetCurrentResources ( ACPI_HANDLE Device, ACPI_BUFFER *InBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetIrqRoutingTable ( ACPI_HANDLE Device, ACPI_BUFFER *RetBuffer)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiResourceToAddress64 ( ACPI_RESOURCE *Resource, ACPI_RESOURCE_ADDRESS64 *Out)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiBufferToResource ( UINT8 *AmlBuffer, UINT16 AmlBufferLength, ACPI_RESOURCE **ResourcePtr)) /* * Hardware (ACPI device) interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiReset ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiRead ( UINT64 *Value, ACPI_GENERIC_ADDRESS *Reg)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiWrite ( UINT64 Value, ACPI_GENERIC_ADDRESS *Reg)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiReadBitRegister ( UINT32 RegisterId, UINT32 *ReturnValue)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiWriteBitRegister ( UINT32 RegisterId, UINT32 Value)) /* * Sleep/Wake interfaces */ ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiGetSleepTypeData ( UINT8 SleepState, UINT8 *Slp_TypA, UINT8 *Slp_TypB)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiEnterSleepStatePrep ( UINT8 SleepState)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiEnterSleepState ( UINT8 SleepState)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiEnterSleepStateS4bios ( void)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiLeaveSleepStatePrep ( UINT8 SleepState)) ACPI_EXTERNAL_RETURN_STATUS ( ACPI_STATUS AcpiLeaveSleepState ( UINT8 SleepState)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiSetFirmwareWakingVector ( ACPI_PHYSICAL_ADDRESS PhysicalAddress, ACPI_PHYSICAL_ADDRESS PhysicalAddress64)) /* * ACPI Timer interfaces */ ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetTimerResolution ( UINT32 *Resolution)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetTimer ( UINT32 *Ticks)) ACPI_HW_DEPENDENT_RETURN_STATUS ( ACPI_STATUS AcpiGetTimerDuration ( UINT32 StartTicks, UINT32 EndTicks, UINT32 *TimeElapsed)) /* * Error/Warning output */ ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(3) void ACPI_INTERNAL_VAR_XFACE AcpiError ( const char *ModuleName, UINT32 LineNumber, const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(4) void ACPI_INTERNAL_VAR_XFACE AcpiException ( const char *ModuleName, UINT32 LineNumber, ACPI_STATUS Status, const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(3) void ACPI_INTERNAL_VAR_XFACE AcpiWarning ( const char *ModuleName, UINT32 LineNumber, const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(1) void ACPI_INTERNAL_VAR_XFACE AcpiInfo ( const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(3) void ACPI_INTERNAL_VAR_XFACE AcpiBiosError ( const char *ModuleName, UINT32 LineNumber, const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(4) void ACPI_INTERNAL_VAR_XFACE AcpiBiosException ( const char *ModuleName, UINT32 LineNumber, ACPI_STATUS Status, const char *Format, ...)) ACPI_MSG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(3) void ACPI_INTERNAL_VAR_XFACE AcpiBiosWarning ( const char *ModuleName, UINT32 LineNumber, const char *Format, ...)) /* * Debug output */ ACPI_DBG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(6) void ACPI_INTERNAL_VAR_XFACE AcpiDebugPrint ( UINT32 RequestedDebugLevel, UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, const char *Format, ...)) ACPI_DBG_DEPENDENT_RETURN_VOID ( ACPI_PRINTF_LIKE(6) void ACPI_INTERNAL_VAR_XFACE AcpiDebugPrintRaw ( UINT32 RequestedDebugLevel, UINT32 LineNumber, const char *FunctionName, const char *ModuleName, UINT32 ComponentId, const char *Format, ...)) ACPI_DBG_DEPENDENT_RETURN_VOID ( void AcpiTracePoint ( ACPI_TRACE_EVENT_TYPE Type, BOOLEAN Begin, UINT8 *Aml, char *Pathname)) ACPI_STATUS AcpiInitializeDebugger ( void); void AcpiTerminateDebugger ( void); void AcpiRunDebugger ( char *BatchBuffer); void AcpiSetDebuggerThreadId ( ACPI_THREAD_ID ThreadId); #endif /* __ACXFACE_H__ */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <cstdio> #include <cstdint> #include <cstdlib> #include <cassert> #include <iostream> #include <vector> #include <unordered_map> #include <random> #include <gtest/gtest.h> #include "fake_funcs_utils.h" #include "kernel_init_funcs.h" using namespace std; using namespace testing; extern "C" { #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/system_mmap_int.h> #include <tilck/kernel/test/mem_regions.h> } struct test_mem_reg { const u64 start; const u64 end; const u32 type; test_mem_reg(u64 start_reg, u64 end_reg, u32 type_reg) : start(start_reg) , end(end_reg) , type(type_reg) { } test_mem_reg(const mem_region &r) : start(r.addr) , end(r.addr + r.len) , type(r.type) { } operator mem_region() const { return mem_region{start, end - start, type, 0 /* extra */}; } bool operator==(const test_mem_reg &rhs) const { return start == rhs.start && end == rhs.end && type == rhs.type; } }; std::ostream& operator<<(std::ostream& os, const test_mem_reg& reg) { return os << "reg(" << hex << "0x" << reg.start << ", " << "0x" << reg.end << ", " << reg.type << ")"; } static void reset_mem_regions(void) { memset(mem_regions, 0, sizeof(mem_regions)); mem_regions_count = 0; } class mem_regions_test : public TestWithParam< pair< vector<test_mem_reg>, /* input regions */ vector<test_mem_reg> /* expected regions */ > > { public: void SetUp() override { memcpy(saved_mem_regions, mem_regions, sizeof(mem_regions)); saved_mem_regions_count = mem_regions_count; } void TearDown() override { memcpy(mem_regions, saved_mem_regions, sizeof(mem_regions)); mem_regions_count = saved_mem_regions_count; } private: struct mem_region saved_mem_regions[MAX_MEM_REGIONS]; int saved_mem_regions_count; }; TEST_P(mem_regions_test, check) { const auto &p = GetParam(); const auto &input = p.first; const auto &expected = p.second; reset_mem_regions(); ASSERT_EQ(mem_regions_count, 0); for (const auto &e: input) { append_mem_region(e); } fix_mem_regions(); ASSERT_EQ(mem_regions_count, (int)expected.size()); for (int i = 0; i < mem_regions_count; i++) { ASSERT_EQ(test_mem_reg(mem_regions[i]), expected[i]); } } static inline pair<vector<test_mem_reg>, vector<test_mem_reg>> make_regions_list_pair(const vector<test_mem_reg> &a, const vector<test_mem_reg> &b) { return make_pair(a, b); } INSTANTIATE_TEST_SUITE_P( do_nothing, mem_regions_test, Values( /* empty set */ make_regions_list_pair( {}, {} ), /* just one region */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1} }, { test_mem_reg{0x0000, 0x1000, 1} } ), /* two adjacent regions of a different type */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1000, 0x2000, 2}, }, { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1000, 0x2000, 2}, } ), /* just two separated regions */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x2000, 0x3000, 2}, }, { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x2000, 0x3000, 2}, } ) ) ); INSTANTIATE_TEST_SUITE_P( reorder, mem_regions_test, Values( make_regions_list_pair( { test_mem_reg{0x1000, 0x2000, 2}, test_mem_reg{0x0000, 0x1000, 1}, }, { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1000, 0x2000, 2}, } ) ) ); INSTANTIATE_TEST_SUITE_P( align_to_4k, mem_regions_test, Values( make_regions_list_pair( { test_mem_reg{0x0000, 0x1, 1}, test_mem_reg{0x2fff, 0x3fff, 2}, test_mem_reg{0x5500, 0x5600, 1}, }, { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x2000, 0x4000, 2}, test_mem_reg{0x5000, 0x6000, 1}, } ) ) ); INSTANTIATE_TEST_SUITE_P( merge, mem_regions_test, Values( /* simple merge */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1000, 0x2000, 1}, }, { test_mem_reg{0x0000, 0x2000, 1}, } ), /* merge after align to 4k [1/2] */ make_regions_list_pair( { test_mem_reg{0x0000, 0x0fff, 1}, test_mem_reg{0x1000, 0x2000, 1}, }, { test_mem_reg{0x0000, 0x2000, 1}, } ), /* merge after align to 4k [2/2] */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1001, 0x2000, 1}, }, { test_mem_reg{0x0000, 0x2000, 1}, } ), /* merge 3 regions */ make_regions_list_pair( { test_mem_reg{0x0000, 0x1000, 1}, test_mem_reg{0x1000, 0x2000, 1}, test_mem_reg{0x2000, 0x3000, 1}, }, { test_mem_reg{0x0000, 0x3000, 1}, } ) ) ); INSTANTIATE_TEST_SUITE_P( full_overlap, mem_regions_test, Values( /* * Full overlap (reg2.type > reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x8000, 1}, test_mem_reg{0x3000, 0x4000, 2}, }, { test_mem_reg{0x0000, 0x3000, 1}, test_mem_reg{0x3000, 0x4000, 2}, test_mem_reg{0x4000, 0x8000, 1}, } ), /* * Full overlap (reg2.type < reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x8000, 2}, test_mem_reg{0x3000, 0x4000, 1}, }, { test_mem_reg{0x0000, 0x8000, 2}, } ), /* * Full overlap corner case (2a, reg2.type < reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------------------------+ * | region 2 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x1000, 0x2000, 1}, test_mem_reg{0x1000, 0x2000, 2}, }, { test_mem_reg{0x1000, 0x2000, 2}, } ), /* * Full overlap corner case (2b, reg2.type < reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 1}, test_mem_reg{0x0000, 0x2000, 2}, }, { test_mem_reg{0x0000, 0x2000, 2}, test_mem_reg{0x2000, 0x4000, 1}, } ), /* * Full overlap corner case (2b, reg2.type > reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x0000, 0x2000, 1}, }, { test_mem_reg{0x0000, 0x4000, 2}, } ), /* * Full overlap corner case (2c, reg2.type < reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 1}, test_mem_reg{0x2000, 0x4000, 2}, }, { test_mem_reg{0x0000, 0x2000, 1}, test_mem_reg{0x2000, 0x4000, 2}, } ), /* * Full overlap corner case (2c, reg2.type > reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------+ * | region 2 | * +---------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x2000, 0x4000, 1}, }, { test_mem_reg{0x0000, 0x4000, 2}, } ) ) ); INSTANTIATE_TEST_SUITE_P( full_overlap_rev, mem_regions_test, Values( /* * Full overlap (reg2.type > reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x3000, 0x4000, 2}, test_mem_reg{0x0000, 0x8000, 1}, }, { test_mem_reg{0x0000, 0x3000, 1}, test_mem_reg{0x3000, 0x4000, 2}, test_mem_reg{0x4000, 0x8000, 1}, } ), /* * Full overlap (reg2.type < reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x3000, 0x4000, 1}, test_mem_reg{0x0000, 0x8000, 2}, }, { test_mem_reg{0x0000, 0x8000, 2}, } ), /* * Full overlap corner case (2b, reg2.type < reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x2000, 2}, test_mem_reg{0x0000, 0x4000, 1}, }, { test_mem_reg{0x0000, 0x2000, 2}, test_mem_reg{0x2000, 0x4000, 1}, } ), /* * Full overlap corner case (2b, reg2.type > reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x2000, 1}, test_mem_reg{0x0000, 0x4000, 2}, }, { test_mem_reg{0x0000, 0x4000, 2}, } ), /* * Full overlap corner case (2c, reg2.type < reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x2000, 0x4000, 2}, test_mem_reg{0x0000, 0x4000, 1}, }, { test_mem_reg{0x0000, 0x2000, 1}, test_mem_reg{0x2000, 0x4000, 2}, } ), /* * Full overlap corner case (2c, reg2.type > reg1.type) * * +---------------+ * | region 2 | * +---------------+ * +---------------------------------+ * | region 1 | * +---------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x2000, 0x4000, 1}, test_mem_reg{0x0000, 0x4000, 2}, }, { test_mem_reg{0x0000, 0x4000, 2}, } ) ) ); INSTANTIATE_TEST_SUITE_P( partial_overlap, mem_regions_test, Values( /* * Partial overlap (reg2.type > reg1.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------------------+ * | region 2 | * +---------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 1}, test_mem_reg{0x2000, 0x8000, 2}, }, { test_mem_reg{0x0000, 0x2000, 1}, test_mem_reg{0x2000, 0x8000, 2}, } ), /* * Partial overlap (reg1.type > reg2.type) * * +---------------------------------+ * | region 1 | * +---------------------------------+ * +---------------------------+ * | region 2 | * +---------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x2000, 0x8000, 1}, }, { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x4000, 0x8000, 1}, } ), /* * Partial overlap (3a, reg2.type > reg1.type) * * +----------------------------+ * | region 1 | * +----------------------------+ * +--------------------------------------------+ * | region 2 | * +--------------------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 1}, test_mem_reg{0x0000, 0x8000, 2}, }, { test_mem_reg{0x0000, 0x8000, 2}, } ), /* * Partial overlap (3a, reg1.type > reg2.type) * * +----------------------------+ * | region 1 | * +----------------------------+ * +--------------------------------------------+ * | region 2 | * +--------------------------------------------+ */ make_regions_list_pair( { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x0000, 0x8000, 1}, }, { test_mem_reg{0x0000, 0x4000, 2}, test_mem_reg{0x4000, 0x8000, 1}, } ) ) ); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include "vfs_test.h" using namespace std; class ramfs_perf : public vfs_test_base { protected: struct mnt_fs *mnt_fs; void SetUp() override { vfs_test_base::SetUp(); mnt_fs = ramfs_create(); ASSERT_TRUE(mnt_fs != NULL); mp_init(mnt_fs); } void TearDown() override { // TODO: destroy ramfs vfs_test_base::TearDown(); } }; static void create_test_file(int n) { char path[256]; fs_handle h; int rc; sprintf(path, "/test_%d", n); rc = vfs_open(path, &h, O_CREAT, 0644); ASSERT_EQ(rc, 0); vfs_close(h); } TEST_F(ramfs_perf, creat) { for (int i = 0; i < 100; i++) create_test_file(i); } <file_sep>#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause # pylint: disable=unused-wildcard-import, bad-indentation, wildcard-import # pylint: disable=missing-function-docstring, wrong-import-position # pylint: disable=invalid-name, raise-missing-from, missing-class-docstring # pylint: disable=consider-using-f-string import os import re import sys import time import gzip import signal import subprocess import threading import filecmp import traceback import argparse # Constants coming from CMake (this file gets pre-processed by CMake) RUNNERS_DIR = "@CMAKE_SOURCE_DIR@/tests/runners" INTERACTIVE_TESTS = "@CMAKE_SOURCE_DIR@/tests/interactive" INTERACTIVE_EXP = "@CMAKE_SOURCE_DIR@/tests/interactive/expected" TILCK_IMAGE = "@IMG_FILE@" TMP_DIR = "@CMAKE_BINARY_DIR@/tmp" PNM2TEXT = "@CMAKE_BINARY_DIR@/scripts/build_apps/pnm2text" FONT_FILE = "@CMAKE_SOURCE_DIR@/modules/fb/font8x16.psf" KERNEL_GCOV = "@KERNEL_GCOV@" GEN_KCOV_REPORT = "@CMAKE_BINARY_DIR@/scripts/generate_kernel_coverage_report" KERNEL_FORCE_TC_ISYSTEM = '@KERNEL_FORCE_TC_ISYSTEM@' QEMU_DEBUG_FILE = "@CMAKE_BINARY_DIR@/tmp/qemu_debugcon.log" QEMU_DEBUG_FILE2 = "@CMAKE_BINARY_DIR@/tmp/qemu_debug.log" CMAKE_CONFIG = { "EXTRA_VIM" : ("@EXTRA_VIM@", True), "FB_CONSOLE_BANNER" : ("@FB_CONSOLE_BANNER@", False), "FB_CONSOLE_CURSOR_BLINK" : ("@FB_CONSOLE_CURSOR_BLINK@", False), "FB_CONSOLE_USE_ALT_FONTS" : ("@FB_CONSOLE_USE_ALT_FONTS@", False), "SERIAL_CON_IN_VIDEO_MODE" : ("@SERIAL_CON_IN_VIDEO_MODE@", True), "BOOTLOADER_LEGACY" : ("@BOOTLOADER_LEGACY@", True), "MOD_console" : ("@MOD_console@", True), "MOD_serial" : ("@MOD_serial@", True), "MOD_fb" : ("@MOD_fb@", True), "MOD_kb8042" : ("@MOD_kb8042@", True), } sys.path.append(RUNNERS_DIR) from lib import qemu from lib.utils import * from lib.detect_kvm import * from lib.env import * from lib.exceptions import * # Global state variables g_process = None g_dumping_gcda_files = False g_timeout = None g_next_screenshot = 0 g_tests = {} g_test_name = None g_keyboard_interrupt = False g_qemu_died = False g_matching_list = None g_passed_list = [] g_just_list = False def set_once_qemu_process(p): global g_process assert(g_process is None) g_process = p def check_cmake_config(): for k, pair in CMAKE_CONFIG.items(): val, exp = is_cmake_opt_enabled(pair[0]), pair[1] if val != exp: msg_print("INVALID CONFIG: expected {} to be `{}`".format(k, exp)) if no_failures(): set_once_fail_reason(Fail.invalid_build_config) if any_failures(): sys.exit(get_fail_reason().value) def wait_for_qemu_to_exit(): while g_process.poll() is None: time.sleep(0.1) def recv_from_qemu_monitor(max_read_attempts): read_anything = False attempts = 0 bbuf = b'' while True: btext = g_process.stdout.read() # Is there any new text? if btext: bbuf += btext read_anything = True time.sleep(0.05) continue # Nope. Did we read anything in the previous iteration? if read_anything: break # Yep, end. # Nope. Is the VM still alive? if g_process.poll() is not None: break # Nope. End returning an empty string # Yep, the VM is still alive. But, should we re-try to read? if max_read_attempts > 0 and attempts == max_read_attempts: break # End returning an empty string # Wait some before re-trying to read time.sleep(0.1) attempts += 1 return bbuf.decode('utf-8') # Handle the escape sequences used by QEMU's monitor. # # NOTE: for performance and simplicity, this code has NOT been designed to # handle any kind of ANSI sequences, not even by just skipping them. # It assumes that QEMU's input something like: # # qESC[KESC[DquESC[KESC[DESC[DquiESC[KESC[DESC[DESC[DquitESC[K # # What's that # ------------ # # It starts with a regular character. After that ESC[K is used to clear the rest # of the console's row and than ESC[D is used to move back by 1 column, after # which the regular character (q) is re-written and then followed by the next # regular character (u). The same steps are repeated for the following chars # with the only detail that every time the number of ESC[D increases by 1. # # What we do # ------------- # # Well, after observing that the string always finishes with ESC[K preceeded by # the a whole substring of regular text, we cheat in the most barbaric way # possible by: # # 1. Skipping the ESC[K sequences. They're useless in this context. # 2. Split the new string by ESC[D # 3. Take the last element of that list def qemu_process_tty_text(ttytext): ttytext = ttytext.replace("\033[K", "") seq = ttytext.split("\033[D") return seq[-1] def echo_qemu_monitor(read_attempts = 3): tty_text = recv_from_qemu_monitor(read_attempts) text = qemu_process_tty_text(tty_text) raw_stdout_write(text) return text def send_to_qemu_monitor(cmd, delay = 0.2): global g_qemu_died if g_qemu_died: return try: g_process.stdin.raw.write("{}\n".format(cmd).encode('utf-8')) except BrokenPipeError: msg_print("BrokenPipeError in send_to_qemu_monitor('{}')".format(cmd)) g_qemu_died = True raise time.sleep(delay) echo_qemu_monitor() def send_single_key_to_vm(key): key_name = None if not key: return if len(key) > 1: key_name = key else: key_name = qemu.KEYS_MAP.get(key, None) if key_name is not None: send_to_qemu_monitor("sendkey " + key_name, 0.05) def send_string_to_vm(s): in_special_key = False spk = "" for k in s: if in_special_key: if k == "}": send_single_key_to_vm(spk) in_special_key = False spk = "" continue spk += k else: if k == "{": in_special_key = True continue send_single_key_to_vm(k) def delete_old_screenshots(): for f in os.listdir(): if not os.path.isfile(f): continue if re.match("s[0-9]+[.](ppm|pbm|png)", f): os.remove(f) def img_convert(img, newtype): cmd = ["convert"] if newtype == "pbm": cmd += [ "-filter", "catrom", "-colorspace", "gray", "+dither", "-colors", "2", "-negate" ] name, ext = os.path.splitext(img) #pylint: disable=unused-variable new_name = name + "." + newtype cmd.append(img) cmd.append("-strip") cmd.append(new_name) res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if res.returncode != 0: out = res.stdout.decode('utf-8') err = res.stderr.decode('utf-8') raise ConvertFailure("stdout: '{}'\nstderr: '{}'".format(out, err)) return new_name def screenshot_to_text(img): cmd = [PNM2TEXT, "-q", FONT_FILE, img] res = subprocess.run(cmd, stdout=subprocess.PIPE) if res.returncode != 0: raise Pnm2TextFailure(res.returncode) return res.stdout.decode('utf-8') def vm_take_screenshot(): global g_next_screenshot name = "s{:03}".format(g_next_screenshot) ppm_name = name + ".ppm" send_to_qemu_monitor("screendump " + ppm_name) g_next_screenshot += 1 return ppm_name def vm_take_stable_screenshot(): time_elapsed = 0.0 prevs = [vm_take_screenshot()] curr = None while True: time_elapsed += STABLE_SCREENSHOT_DELAY if time_elapsed >= STABLE_SCREENSHOT_TIMEOUT: raise StableScreenshotFailure() time.sleep(STABLE_SCREENSHOT_DELAY) curr = vm_take_screenshot() if filecmp.cmp(prevs[-1], curr, False): break # Bang! We got two identical screenshots. # We screenshots differ. if len(prevs) > 1: # We have more than 1 old screeshot. Could be the cursor blinking? if filecmp.cmp(prevs[-2], curr, False): break # Assume it's cursor blinking. # We have to save this screenshot prevs.append(curr) # Great, we're out of the loop. Let's delete the useless screenshots. for s in prevs: os.remove(s) return curr def make_and_save_text_screenshot_base(test_name, n): t = screenshot_to_text(vm_take_stable_screenshot()) if t.find("KERNEL PANIC") != -1: raise KernelPanicFailure(t) raw_print("") raw_print(t) send_to_qemu_monitor("\n") fname = "{}-{}.gz".format(test_name, n) with gzip.open(fname, "w") as fh: fh.write(t.encode('utf-8')) def get_first_different_line(screen_a, screen_b): a = screen_a.splitlines() b = screen_b.splitlines() if len(a) != len(b): raise RuntimeError("The screens don't have the same number of rows") for i in range(len(a)): if a[i] != b[i]: return (i, len(a), a[i], b[i]) return None def false_positive_handler_vim(t, exp_t): # The vim test might fail because of localization. For example, the # line before the last might begin with: # # |"/usr/lib/vim/samples/numbers.txt" 100L, 292B # # OR # # |"/usr/lib/vim/samples/numbers.txt" 100L, 292C # # The code below handles these subtle differences. # # FAQ # -------- # # Q: Why localization might be different? We're not running on Linux # but on Tilck, where we control everything. # # A: Well, yeah, but we also support different toolchains and versions of # libmusl. Also, different versions of vim might be used too. Instead of # creating an "expected" screen series for each test, for each build # configuration, just handle any eventual differences with code. d = get_first_different_line(t, exp_t) assert(d is not None) dx, tot, row, exp_row = d if tot > 2 and dx == tot-2: # The line before the last one: now replace the 'B' with a 'C', # like in the example above. row2 = re.sub(r'(, [0-9]+)B', r'\1C', row) if row2 == exp_row: return True # Everything is fine. return False def check_screenshot_base(test_name, n, false_positive_handler = None): fname = "{}-{}.gz".format(test_name, n) p = os.path.join(INTERACTIVE_EXP, fname) with gzip.open(p, "r") as fh: exp_t = fh.read().decode('utf-8') t = screenshot_to_text(vm_take_stable_screenshot()) if t.find("KERNEL PANIC") != -1: raise KernelPanicFailure(t) if t == exp_t: return # Expectations match, everything is OK. # Mmh.. this still could be a false positive: stable screenshots # are not perfect. Let's try another screenshot before failing. time.sleep(1) t = screenshot_to_text(vm_take_stable_screenshot()) if t.find("KERNEL PANIC") != -1: raise KernelPanicFailure(t) if t == exp_t: return # Expectations match: the problem was non-stable screenshot. # Ok, that's likely a failure, but it might be a special type of false # positive, where there's a difference and it's still acceptable. if false_positive_handler: if false_positive_handler(t, exp_t): return # The false positive handler told us that's fine. raise IntTestScreenshotNoMatchFailure(t, exp_t) # NOTE: utility function used by the interactive tests def do_interactive_actions(test_name, inputs, false_positive_handler = None): counter = 0 def save_screenshot(): nonlocal counter make_and_save_text_screenshot_base(test_name, counter) counter += 1 def check_screenshot(): nonlocal counter check_screenshot_base(test_name, counter, false_positive_handler) counter += 1 action_func = save_screenshot if GEN_TEST_DATA else check_screenshot for x in inputs: raw_print("\n") msg_print("Sending to VM: {}".format(x)) send_to_qemu_monitor("\n") send_string_to_vm(x) action_func() # NOTE: utility function used by the interactive tests def send_to_vm_and_find_text(cmd, dump, patterns): send_string_to_vm(cmd) t = screenshot_to_text(vm_take_stable_screenshot()) if t.find("KERNEL PANIC") != -1: KernelPanicFailure(t) for p in patterns: if t.find(p) == -1: raise IntTestScreenTextCheckFailure(t, p) if dump: raw_print("") raw_print(t) send_to_qemu_monitor("\n") # NOTE: utility function used by the interactive tests # # What does: runs vim and quits from it. # # Reason: vim and its runtime is compressed (tgz) in Tilck's ramdisk. # The first time it's run, the `vim` wrapper script unpacks vim and its # runtime and that takes time. In CI runs, tests like `vim1` and `vim2` # could fail without this warm-up because the unpack operation is CPU-bound # and it might take a few seconds to get it done, while do_interactive_actions() # won't wait enough for that to happen and it will just fail. # def just_run_vim_and_exit(): send_string_to_vm(r"vim{ret}") attempts = 0 while True: t = screenshot_to_text(vm_take_stable_screenshot()) if t.find("VIM - Vi IMproved") != -1: break if attempts >= 4: raise RuntimeError("Cannot start vim") time.sleep(2) attempts += 1 send_string_to_vm(r"{esc}:q{ret}") def run_handle_boot(): # Wait for the bootloader to load everything time.sleep(3) # Wait a little for Tilck to boot time.sleep(1) # Take a screenshot for Tilck's initial screen s = vm_take_stable_screenshot() # Convert (using our pnm2text tool) the image to text text = screenshot_to_text(s) # Dump on our text raw_stdout_write("\n") raw_stdout_write(text) send_to_qemu_monitor("\n") if text.find("Hello from Tilck") == -1: raise NoTilckHelloMessage() if text.find("KERNEL PANIC") != -1: raise KernelPanicFailure() send_string_to_vm(r"clear{ret}") def dump_qemu_debug_files(): msg_print("--- Dump QEMU debugcon log: {} ---".format(QEMU_DEBUG_FILE)) with open(QEMU_DEBUG_FILE, 'r') as fh: raw_print(fh.read()) msg_print("--- END QEMU debugcon log file ---") msg_print("--- Dump QEMU trace log: {} ---".format(QEMU_DEBUG_FILE2)) with open(QEMU_DEBUG_FILE2, 'r') as fh: raw_print(fh.read()) msg_print("--- END QEMU trace log file ---") def run_main_body(): try: # Boot Tilck and make sure everything is alright run_handle_boot() # Call the test func run_all_tests() except StableScreenshotFailure as e: msg_print("Exception: " + str(e)) set_once_fail_reason(Fail.timeout) except (NoTilckHelloMessage, KernelPanicFailure, IntTestScreenTextCheckFailure, IntTestScreenshotNoMatchFailure) as e: msg_print("Exception: " + str(e)) if e.screen_text: raw_stdout_write("Actual screenshot:\n") raw_stdout_write(e.screen_text) if type(e) is IntTestScreenshotNoMatchFailure: raw_stdout_write("\nExpected screenshot:\n") raw_stdout_write(e.expected_text) d = get_first_different_line(e.screen_text, e.expected_text) if d: dx, tot, row, exp_row = d # pylint: disable=unused-variable raw_stdout_write("\n") raw_stdout_write("First diff: {}\n".format(row)) raw_stdout_write("Expected: {}\n".format(exp_row)) if type(e) is NoTilckHelloMessage: set_once_fail_reason(Fail.no_hello_message) elif type(e) is KernelPanicFailure: set_once_fail_reason(Fail.panic) else: set_once_fail_reason(Fail.some_tests_failed) except BrokenPipeError: msg_print("BrokenPipeError") if g_process.poll() is None: msg_print("Note: the QEMU process is still alive") try: echo_qemu_monitor() except Exception as e: msg_print("Cannot read from QEMU monitor: {}".format(str(e))) else: msg_print("Note: QEMU died with: {}".format(g_process.returncode)) # dump_qemu_debug_files() # set_once_fail_reason(Fail.qemu_died_unexpectedly) except Exception as e: if g_keyboard_interrupt: # The main thread has been interrupted by the user: just re-throw # the exception without spamming him/her with useless verbose # errors. raise msg_print("Exception: {}\n{}".format(str(e), traceback.format_exc())) set_once_fail_reason(Fail.other) except: msg_print("Unknown exception:\n" + traceback.format_exc()) set_once_fail_reason(Fail.other) def dump_coverage_data_int(lines): global g_dumping_gcda_files gcda_file = None gcda_data = '' for line in lines: if not g_dumping_gcda_files: if line.find(KERNEL_DUMP_GCDA_STR) != -1: g_dumping_gcda_files = True continue # Dumping GCDA files if not line: if gcda_file and gcda_data: if VERBOSE: msg_print("[debug] Write gcda file: {}".format(gcda_file)) if not write_gcda_file(gcda_file, gcda_data): return False gcda_file = None gcda_data = '' continue if not gcda_file: m = re.search(r'file: (.+)', line) if m: gcda_file = m.group(1) else: if line.find(KERNEL_DUMP_GCDA_END_STR) != -1: break # greaceful stop msg_print("ERROR: expected gcda file name in {}".format(line)) set_once_fail_reason(Fail.gcov_error) break continue gcda_data += line return True def dump_coverage_data(pts_file): # Import the pySerial module here, locally. That allows the script to run # also when pySerial is not present, just coverage reporting won't work. import serial # type: ignore if not is_cmake_opt_enabled(KERNEL_GCOV): msg_print("ERROR: kernel not compiled with KERNEL_GCOV=1") set_once_fail_reason(Fail.invalid_build_config) return msg_print("Performing coverage dump ...") output = b'' read_timeout = 3 if IN_ANY_CI else 0.5 with serial.Serial(pts_file, timeout = read_timeout) as ser: # Enter the shell ser.write("\n".encode("latin-1")) # Ask our devshell to dump the coverage data ser.write("devshell -dcov\n".encode("latin-1")) # Just wait a little in order to allow data to accumulate time.sleep(read_timeout) # Read all the output while True: buf = ser.read(4096) if not buf: break output += buf if not output: raise RuntimeError("Nothing read from {}".format(pts_file)) if VERBOSE: msg_print("[debug] Raw coverage data:") direct_print(output) msg_print("[debug] --- end ---") lines = output.decode('latin-1').splitlines() del output # free the memory used by `output` if dump_coverage_data_int(lines): msg_print("Coverage dump: DONE") else: msg_print("Coverage dump: FAILED") return if REPORT_COV: if not run_gen_coverage_report_tool(GEN_KCOV_REPORT): set_once_fail_reason(Fail.gcov_error) def run(): args = [ 'qemu-system-i386', '-m', str(VM_MEMORY_SIZE_IN_MB), '-display', 'none', '-monitor', 'stdio', '-device', 'isa-debug-exit,iobase=0xf4,iosize=0x04', '-drive', 'id=img1,format=raw,if=none,file=' + TILCK_IMAGE, '-device', 'ide-hd,drive=img1,@QEMU_CHS_GEOM@', '-debugcon', 'file:{}'.format(QEMU_DEBUG_FILE), '-d', 'cpu_reset,guest_errors,trace:*monitor*', '-D', QEMU_DEBUG_FILE2, '-global', 'isa-debugcon.iobase=0x402', '-serial', 'pty', ] if is_kvm_installed(): args += ['-enable-kvm', '-cpu', 'host'] # Run the QEMU process p = subprocess.Popen( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) set_once_qemu_process(p) # Make the `stdout` file descriptor non-blocking fh_set_blocking_mode(g_process.stdout, False) raw_print('-' * 80) start_time = time.time() qemu_hello_msg = echo_qemu_monitor(0) raw_print("") pts_file = None m = re.search(r"char device redirected to ([^ ]+)[ ]", qemu_hello_msg) if m: pts_file = m.group(1) msg_print("Serial port: {}".format(pts_file)) try: run_main_body() except: if g_keyboard_interrupt: # The main thread has been interrupted by the user: just stop. return # Whatever else happened, just re-throw the exception raise if DUMP_COV and no_failures(): try: dump_coverage_data(pts_file) except Exception as e: fmtex = traceback.format_exc() msg_print("Exception: {}\n{}".format(str(e), fmtex)) set_once_fail_reason(Fail.gcov_error) else: msg_print("ERROR: unable to find serial port's device in QEMU's msg") set_once_fail_reason(Fail.qemu_msg_parsing_fail) send_to_qemu_monitor("") send_to_qemu_monitor("quit") wait_for_qemu_to_exit() elapsed = time.time() - start_time raw_print('-' * 80) msg_print("Elapsed: {:.2f} s".format(elapsed)) def setup_tmp_dir(): if not os.path.isdir(TMP_DIR): os.mkdir(TMP_DIR) os.chdir(TMP_DIR) delete_old_screenshots() def check_tool_works(tool, help_opt, keyword): found = False exTrace = None try: res = subprocess.run([tool, help_opt], stdout=subprocess.PIPE) out = res.stdout.decode("utf-8") if out.find(keyword) != -1: found = True except Exception: exTrace = traceback.format_exc() return found, exTrace def check_imagemagick_installed(): found, exTrace = check_tool_works("convert", "-h", "ImageMagick") if not found: msg_print("ERROR: ImageMagick (convert tool) not found on the system") msg_print("Exception:\n{}".format(exTrace)) sys.exit(Fail.invalid_system_config.value) def check_system_config(): check_imagemagick_installed() def check_pnm2text(): found, exTrace = check_tool_works(PNM2TEXT, "-h", "pnm2text") if not found: msg_print("ERROR: pnm2text not found in the build directory") msg_print("ERROR: you might need to run `make`") msg_print("Exception:\n{}".format(exTrace)) sys.exit(Fail.invalid_build_config.value) def load_tests(): global g_tests for f in os.listdir(INTERACTIVE_TESTS): if not f.endswith(".py"): continue name = os.path.splitext(f)[0] p = os.path.join(INTERACTIVE_TESTS, f) with open(p, 'r') as fh: src = fh.read() e = compile(src, p, 'exec') g_tests[name] = e def compute_matching_tests_list(): if not g_test_name or g_test_name == "runall": return g_tests return list(filter(lambda x: x == g_test_name, g_tests)) def dump_list_matching_tests_and_timeout(): if not g_matching_list: msg_print("ERROR: no such test '{}'".format(g_test_name)) sys.exit(Fail.invalid_args.value) msg_print("Total timeout: {}s".format(g_timeout)) msg_print("Tests to run: {}{}".format( "(ALL) " if g_matching_list == g_tests else "", " ".join(g_matching_list) )) raw_print("") def run_all_tests(): global g_passed_list raw_stdout_write("\n") msg_print("Run interactive tests") msg_print("-" * 50) for k in g_matching_list: if k in g_passed_list: continue delete_old_screenshots() msg_print("Interactive test: {}".format(k)) send_to_qemu_monitor("\n") exec(g_tests[k], globals(), {}) raw_stdout_write("\n\n") g_passed_list.append(k) def dump_list_of_tests(): for k in g_tests: raw_print(k) def parse_args(): global g_test_name global g_timeout global g_just_list parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group(required = True) g.add_argument( "-l", "--list", action = "store_true", help = "list all the tests" ) g.add_argument( "-a", "--run_all", action = "store_true", help = "run all the tests" ) g.add_argument( "test_name", nargs = "?", help = "name of the test to run" ) parser.add_argument( "tot_timeout", nargs = "?", type = int, help = "total run timeout" ) parser.add_argument( "qemu_kvm_version", nargs = "?", help = argparse.SUPPRESS ) input_args = sys.argv[1:] if input_args and input_args[0] == "interactive": # Skip the first argument if it's the test type, in order to support the # same interface as `single_test_run` del input_args[0] try: args = parser.parse_args(input_args) except SystemExit: sys.exit(Fail.invalid_args.value) if args.test_name: g_test_name = args.test_name if args.list: g_just_list = True if args.tot_timeout: g_timeout = args.tot_timeout if args.qemu_kvm_version: set_qemu_kvm_version(args.qemu_kvm_version) def join_worker_thread(thread): thread.join(g_timeout) if thread.is_alive(): # If we get here, after `g_timeout` seconds, the test is still running if g_dumping_gcda_files: # If we're just dumping the GCDA file, wait a little more thread.join(30) if thread.is_alive(): # We have to fail with timeout set_once_fail_reason(Fail.timeout) print_timeout_kill_vm_msg(g_timeout) g_process.send_signal(signal.SIGINT) thread.join() def main(): global g_keyboard_interrupt global g_qemu_died global g_matching_list global g_timeout global g_process global g_just_list attempts = 0 set_runner_name("interactive tests runner") parse_args() check_cmake_config() check_system_config() check_pnm2text() setup_tmp_dir() load_tests() if g_just_list: dump_list_of_tests() sys.exit(0) g_matching_list = compute_matching_tests_list() if not g_timeout: g_timeout = 60 * len(g_matching_list) dump_list_matching_tests_and_timeout() detect_kvm() if is_cmake_opt_enabled(KERNEL_FORCE_TC_ISYSTEM): unrunnable_build_graceful_exit() while True: # Reset global variables g_process = None g_qemu_died = False # Create our runner thread thread = threading.Thread(target = run) thread.start() try: join_worker_thread(thread) except KeyboardInterrupt: g_keyboard_interrupt = True msg_print("") msg_print("KeyboardInterrupt") set_once_fail_reason(Fail.user_interruption) g_process.send_signal(signal.SIGINT) thread.join(2) if (g_qemu_died and not g_keyboard_interrupt and get_fail_reason() != Fail.timeout): # It is unclear why while running this test suite in Azure Pipelines # from time to time we get BrokenPipeError caused by the death of the # QEMU process. if attempts < 2: msg_print("QEMU died unexpectedly: retry once more time in 5 secs") reset_fail_reason() time.sleep(5) attempts += 1 continue # QEMU died already twice. Do fail. set_once_fail_reason(Fail.qemu_died_unexpectedly) if IN_ANY_CI and get_fail_reason() == Fail.some_tests_failed: if attempts < 2: # # While running in CI like Azure Pipelines, timing is uncertain: # because of that, it happens (rarely!) that some of the most # demaning interactive tests like `vim` fail because the output # doesn't match exactly the expected one. # # A workaround to this problem could be to increase the internal # delays, making everything to go slower: that might accomodate # the CI case in the < 1% of the cases, but it will make the test # run significantly slower in 99% of the cases. Therefore, we're # taking the opposite approach: run with the same speed and take 2x # of the time, in case of failure. # msg_print("Some tests failed, but we're running in CI: retry once") reset_fail_reason() time.sleep(5) attempts += 1 continue # Default case: we exit the loop after we ran all the tests or there has # been a keyboard interrupt. break sys.exit(get_fail_reason().value) ############################### if __name__ == '__main__': main() <file_sep>#!/bin/sh BUILD_DIR="@CMAKE_BINARY_DIR@" FATPART="$BUILD_DIR/fatpart" if [ -z "$GDB_PORT" ]; then GDB_PORT=1234 fi qemu-system-@ARCH@ @QEMU_COMMON_OPTS@ -gdb tcp::$GDB_PORT \ @QEMU_RAM_OPT@ -kernel "@KERNEL_FILE@" -initrd "$FATPART" "$@" <file_sep># SPDX-License-Identifier: BSD-2-Clause import sys import types class ConstError(TypeError): def __init__(self, name): super(ConstError, self).__init__() self.name = name def __str__(self): return "Cannot re-bind '{}'".format(self.name) class Const: def __init__(self, val): self.val = val def __setattr__(self, name, val): if name in self.__dict__: raise ConstError(name) self.__dict__[name] = val class ConstModule(types.ModuleType): def __init__(self, mod): super(ConstModule, self).__init__(mod) for pair in sys.modules[mod].__dict__.items(): if type(pair[1]) is Const: self.__dict__[pair[0]] = pair[1].val else: self.__dict__[pair[0]] = pair[1] def __setattr__(self, name, value): if name in self.__dict__: raise ConstError(name) self.__dict__[name] = value def ReloadAsConstModule(name): sys.modules[name] = ConstModule(name) <file_sep>/****************************************************************************** * * Module Name: uteval - Object evaluation * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("uteval") /******************************************************************************* * * FUNCTION: AcpiUtEvaluateObject * * PARAMETERS: PrefixNode - Starting node * Path - Path to object from starting node * ExpectedReturnTypes - Bitmap of allowed return types * ReturnDesc - Where a return value is stored * * RETURN: Status * * DESCRIPTION: Evaluates a namespace object and verifies the type of the * return object. Common code that simplifies accessing objects * that have required return objects of fixed types. * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtEvaluateObject ( ACPI_NAMESPACE_NODE *PrefixNode, const char *Path, UINT32 ExpectedReturnBtypes, ACPI_OPERAND_OBJECT **ReturnDesc) { ACPI_EVALUATE_INFO *Info; ACPI_STATUS Status; UINT32 ReturnBtype; ACPI_FUNCTION_TRACE (UtEvaluateObject); /* Allocate the evaluation information block */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { return_ACPI_STATUS (AE_NO_MEMORY); } Info->PrefixNode = PrefixNode; Info->RelativePathname = Path; /* Evaluate the object/method */ Status = AcpiNsEvaluate (Info); if (ACPI_FAILURE (Status)) { if (Status == AE_NOT_FOUND) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "[%4.4s.%s] was not found\n", AcpiUtGetNodeName (PrefixNode), Path)); } else { ACPI_ERROR_METHOD ("Method execution failed", PrefixNode, Path, Status); } goto Cleanup; } /* Did we get a return object? */ if (!Info->ReturnObject) { if (ExpectedReturnBtypes) { ACPI_ERROR_METHOD ("No object was returned from", PrefixNode, Path, AE_NOT_EXIST); Status = AE_NOT_EXIST; } goto Cleanup; } /* Map the return object type to the bitmapped type */ switch ((Info->ReturnObject)->Common.Type) { case ACPI_TYPE_INTEGER: ReturnBtype = ACPI_BTYPE_INTEGER; break; case ACPI_TYPE_BUFFER: ReturnBtype = ACPI_BTYPE_BUFFER; break; case ACPI_TYPE_STRING: ReturnBtype = ACPI_BTYPE_STRING; break; case ACPI_TYPE_PACKAGE: ReturnBtype = ACPI_BTYPE_PACKAGE; break; default: ReturnBtype = 0; break; } if ((AcpiGbl_EnableInterpreterSlack) && (!ExpectedReturnBtypes)) { /* * We received a return object, but one was not expected. This can * happen frequently if the "implicit return" feature is enabled. * Just delete the return object and return AE_OK. */ AcpiUtRemoveReference (Info->ReturnObject); goto Cleanup; } /* Is the return object one of the expected types? */ if (!(ExpectedReturnBtypes & ReturnBtype)) { ACPI_ERROR_METHOD ("Return object type is incorrect", PrefixNode, Path, AE_TYPE); ACPI_ERROR ((AE_INFO, "Type returned from %s was incorrect: %s, expected Btypes: 0x%X", Path, AcpiUtGetObjectTypeName (Info->ReturnObject), ExpectedReturnBtypes)); /* On error exit, we must delete the return object */ AcpiUtRemoveReference (Info->ReturnObject); Status = AE_TYPE; goto Cleanup; } /* Object type is OK, return it */ *ReturnDesc = Info->ReturnObject; Cleanup: ACPI_FREE (Info); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtEvaluateNumericObject * * PARAMETERS: ObjectName - Object name to be evaluated * DeviceNode - Node for the device * Value - Where the value is returned * * RETURN: Status * * DESCRIPTION: Evaluates a numeric namespace object for a selected device * and stores result in *Value. * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtEvaluateNumericObject ( const char *ObjectName, ACPI_NAMESPACE_NODE *DeviceNode, UINT64 *Value) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtEvaluateNumericObject); Status = AcpiUtEvaluateObject (DeviceNode, ObjectName, ACPI_BTYPE_INTEGER, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Get the returned Integer */ *Value = ObjDesc->Integer.Value; /* On exit, we must delete the return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtExecute_STA * * PARAMETERS: DeviceNode - Node for the device * Flags - Where the status flags are returned * * RETURN: Status * * DESCRIPTION: Executes _STA for selected device and stores results in * *Flags. If _STA does not exist, then the device is assumed * to be present/functional/enabled (as per the ACPI spec). * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtExecute_STA ( ACPI_NAMESPACE_NODE *DeviceNode, UINT32 *Flags) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtExecute_STA); Status = AcpiUtEvaluateObject (DeviceNode, METHOD_NAME__STA, ACPI_BTYPE_INTEGER, &ObjDesc); if (ACPI_FAILURE (Status)) { if (AE_NOT_FOUND == Status) { /* * if _STA does not exist, then (as per the ACPI specification), * the returned flags will indicate that the device is present, * functional, and enabled. */ ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "_STA on %4.4s was not found, assuming device is present\n", AcpiUtGetNodeName (DeviceNode))); *Flags = ACPI_UINT32_MAX; Status = AE_OK; } return_ACPI_STATUS (Status); } /* Extract the status flags */ *Flags = (UINT32) ObjDesc->Integer.Value; /* On exit, we must delete the return object */ AcpiUtRemoveReference (ObjDesc); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtExecutePowerMethods * * PARAMETERS: DeviceNode - Node for the device * MethodNames - Array of power method names * MethodCount - Number of methods to execute * OutValues - Where the power method values are returned * * RETURN: Status, OutValues * * DESCRIPTION: Executes the specified power methods for the device and returns * the result(s). * * NOTE: Internal function, no parameter validation * ******************************************************************************/ ACPI_STATUS AcpiUtExecutePowerMethods ( ACPI_NAMESPACE_NODE *DeviceNode, const char **MethodNames, UINT8 MethodCount, UINT8 *OutValues) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_STATUS FinalStatus = AE_NOT_FOUND; UINT32 i; ACPI_FUNCTION_TRACE (UtExecutePowerMethods); for (i = 0; i < MethodCount; i++) { /* * Execute the power method (_SxD or _SxW). The only allowable * return type is an Integer. */ Status = AcpiUtEvaluateObject (DeviceNode, ACPI_CAST_PTR (char, MethodNames[i]), ACPI_BTYPE_INTEGER, &ObjDesc); if (ACPI_SUCCESS (Status)) { OutValues[i] = (UINT8) ObjDesc->Integer.Value; /* Delete the return object */ AcpiUtRemoveReference (ObjDesc); FinalStatus = AE_OK; /* At least one value is valid */ continue; } OutValues[i] = ACPI_UINT8_MAX; if (Status == AE_NOT_FOUND) { continue; /* Ignore if not found */ } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Failed %s on Device %4.4s, %s\n", ACPI_CAST_PTR (char, MethodNames[i]), AcpiUtGetNodeName (DeviceNode), AcpiFormatException (Status))); } return_ACPI_STATUS (FinalStatus); } <file_sep>/****************************************************************************** * * Module Name: hwvalid - I/O request validation * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_HARDWARE ACPI_MODULE_NAME ("hwvalid") /* Local prototypes */ static ACPI_STATUS AcpiHwValidateIoRequest ( ACPI_IO_ADDRESS Address, UINT32 BitWidth); /* * Protected I/O ports. Some ports are always illegal, and some are * conditionally illegal. This table must remain ordered by port address. * * The table is used to implement the Microsoft port access rules that * first appeared in Windows XP. Some ports are always illegal, and some * ports are only illegal if the BIOS calls _OSI with a WinXP string or * later (meaning that the BIOS itelf is post-XP.) * * This provides ACPICA with the desired port protections and * Microsoft compatibility. * * Description of port entries: * DMA: DMA controller * PIC0: Programmable Interrupt Controller (8259A) * PIT1: System Timer 1 * PIT2: System Timer 2 failsafe * RTC: Real-time clock * CMOS: Extended CMOS * DMA1: DMA 1 page registers * DMA1L: DMA 1 Ch 0 low page * DMA2: DMA 2 page registers * DMA2L: DMA 2 low page refresh * ARBC: Arbitration control * SETUP: Reserved system board setup * POS: POS channel select * PIC1: Cascaded PIC * IDMA: ISA DMA * ELCR: PIC edge/level registers * PCI: PCI configuration space */ static const ACPI_PORT_INFO AcpiProtectedPorts[] = { {"DMA", 0x0000, 0x000F, ACPI_OSI_WIN_XP}, {"PIC0", 0x0020, 0x0021, ACPI_ALWAYS_ILLEGAL}, {"PIT1", 0x0040, 0x0043, ACPI_OSI_WIN_XP}, {"PIT2", 0x0048, 0x004B, ACPI_OSI_WIN_XP}, {"RTC", 0x0070, 0x0071, ACPI_OSI_WIN_XP}, {"CMOS", 0x0074, 0x0076, ACPI_OSI_WIN_XP}, {"DMA1", 0x0081, 0x0083, ACPI_OSI_WIN_XP}, {"DMA1L", 0x0087, 0x0087, ACPI_OSI_WIN_XP}, {"DMA2", 0x0089, 0x008B, ACPI_OSI_WIN_XP}, {"DMA2L", 0x008F, 0x008F, ACPI_OSI_WIN_XP}, {"ARBC", 0x0090, 0x0091, ACPI_OSI_WIN_XP}, {"SETUP", 0x0093, 0x0094, ACPI_OSI_WIN_XP}, {"POS", 0x0096, 0x0097, ACPI_OSI_WIN_XP}, {"PIC1", 0x00A0, 0x00A1, ACPI_ALWAYS_ILLEGAL}, {"IDMA", 0x00C0, 0x00DF, ACPI_OSI_WIN_XP}, {"ELCR", 0x04D0, 0x04D1, ACPI_ALWAYS_ILLEGAL}, {"PCI", 0x0CF8, 0x0CFF, ACPI_OSI_WIN_XP} }; #define ACPI_PORT_INFO_ENTRIES ACPI_ARRAY_LENGTH (AcpiProtectedPorts) /****************************************************************************** * * FUNCTION: AcpiHwValidateIoRequest * * PARAMETERS: Address Address of I/O port/register * BitWidth Number of bits (8,16,32) * * RETURN: Status * * DESCRIPTION: Validates an I/O request (address/length). Certain ports are * always illegal and some ports are only illegal depending on * the requests the BIOS AML code makes to the predefined * _OSI method. * ******************************************************************************/ static ACPI_STATUS AcpiHwValidateIoRequest ( ACPI_IO_ADDRESS Address, UINT32 BitWidth) { UINT32 i; UINT32 ByteWidth; ACPI_IO_ADDRESS LastAddress; const ACPI_PORT_INFO *PortInfo; ACPI_FUNCTION_TRACE (HwValidateIoRequest); /* Supported widths are 8/16/32 */ if ((BitWidth != 8) && (BitWidth != 16) && (BitWidth != 32)) { ACPI_ERROR ((AE_INFO, "Bad BitWidth parameter: %8.8X", BitWidth)); return_ACPI_STATUS (AE_BAD_PARAMETER); } PortInfo = AcpiProtectedPorts; ByteWidth = ACPI_DIV_8 (BitWidth); LastAddress = Address + ByteWidth - 1; ACPI_DEBUG_PRINT ((ACPI_DB_IO, "Address %8.8X%8.8X LastAddress %8.8X%8.8X Length %X", ACPI_FORMAT_UINT64 (Address), ACPI_FORMAT_UINT64 (LastAddress), ByteWidth)); /* Maximum 16-bit address in I/O space */ if (LastAddress > ACPI_UINT16_MAX) { ACPI_ERROR ((AE_INFO, "Illegal I/O port address/length above 64K: %8.8X%8.8X/0x%X", ACPI_FORMAT_UINT64 (Address), ByteWidth)); return_ACPI_STATUS (AE_LIMIT); } /* Exit if requested address is not within the protected port table */ if (Address > AcpiProtectedPorts[ACPI_PORT_INFO_ENTRIES - 1].End) { return_ACPI_STATUS (AE_OK); } /* Check request against the list of protected I/O ports */ for (i = 0; i < ACPI_PORT_INFO_ENTRIES; i++, PortInfo++) { /* * Check if the requested address range will write to a reserved * port. There are four cases to consider: * * 1) Address range is contained completely in the port address range * 2) Address range overlaps port range at the port range start * 3) Address range overlaps port range at the port range end * 4) Address range completely encompasses the port range */ if ((Address <= PortInfo->End) && (LastAddress >= PortInfo->Start)) { /* Port illegality may depend on the _OSI calls made by the BIOS */ if (AcpiGbl_OsiData >= PortInfo->OsiDependency) { ACPI_DEBUG_PRINT ((ACPI_DB_VALUES, "Denied AML access to port 0x%8.8X%8.8X/%X (%s 0x%.4X-0x%.4X)\n", ACPI_FORMAT_UINT64 (Address), ByteWidth, PortInfo->Name, PortInfo->Start, PortInfo->End)); return_ACPI_STATUS (AE_AML_ILLEGAL_ADDRESS); } } /* Finished if address range ends before the end of this port */ if (LastAddress <= PortInfo->End) { break; } } return_ACPI_STATUS (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiHwReadPort * * PARAMETERS: Address Address of I/O port/register to read * Value Where value (data) is returned * Width Number of bits * * RETURN: Status and value read from port * * DESCRIPTION: Read data from an I/O port or register. This is a front-end * to AcpiOsReadPort that performs validation on both the port * address and the length. * *****************************************************************************/ ACPI_STATUS AcpiHwReadPort ( ACPI_IO_ADDRESS Address, UINT32 *Value, UINT32 Width) { ACPI_STATUS Status; UINT32 OneByte; UINT32 i; /* Truncate address to 16 bits if requested */ if (AcpiGbl_TruncateIoAddresses) { Address &= ACPI_UINT16_MAX; } /* Validate the entire request and perform the I/O */ Status = AcpiHwValidateIoRequest (Address, Width); if (ACPI_SUCCESS (Status)) { Status = AcpiOsReadPort (Address, Value, Width); return (Status); } if (Status != AE_AML_ILLEGAL_ADDRESS) { return (Status); } /* * There has been a protection violation within the request. Fall * back to byte granularity port I/O and ignore the failing bytes. * This provides compatibility with other ACPI implementations. */ for (i = 0, *Value = 0; i < Width; i += 8) { /* Validate and read one byte */ if (AcpiHwValidateIoRequest (Address, 8) == AE_OK) { Status = AcpiOsReadPort (Address, &OneByte, 8); if (ACPI_FAILURE (Status)) { return (Status); } *Value |= (OneByte << i); } Address++; } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiHwWritePort * * PARAMETERS: Address Address of I/O port/register to write * Value Value to write * Width Number of bits * * RETURN: Status * * DESCRIPTION: Write data to an I/O port or register. This is a front-end * to AcpiOsWritePort that performs validation on both the port * address and the length. * *****************************************************************************/ ACPI_STATUS AcpiHwWritePort ( ACPI_IO_ADDRESS Address, UINT32 Value, UINT32 Width) { ACPI_STATUS Status; UINT32 i; /* Truncate address to 16 bits if requested */ if (AcpiGbl_TruncateIoAddresses) { Address &= ACPI_UINT16_MAX; } /* Validate the entire request and perform the I/O */ Status = AcpiHwValidateIoRequest (Address, Width); if (ACPI_SUCCESS (Status)) { Status = AcpiOsWritePort (Address, Value, Width); return (Status); } if (Status != AE_AML_ILLEGAL_ADDRESS) { return (Status); } /* * There has been a protection violation within the request. Fall * back to byte granularity port I/O and ignore the failing bytes. * This provides compatibility with other ACPI implementations. */ for (i = 0; i < Width; i += 8) { /* Validate and write one byte */ if (AcpiHwValidateIoRequest (Address, 8) == AE_OK) { Status = AcpiOsWritePort (Address, (Value >> i) & 0xFF, 8); if (ACPI_FAILURE (Status)) { return (Status); } } Address++; } return (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/syscalls.h> #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> static int tracer_tool(int argc, char **argv) { if (argc > 0) { printf("ERROR: unknown option '%s'\n", argv[0]); return 1; } int rc = syscall(TILCK_CMD_SYSCALL, TILCK_CMD_TRACING_TOOL); if (rc < 0) printf("ERROR: tracing not compiled-in\n"); return rc; } static int ps_tool(int argc, char **argv) { if (argc > 0) { printf("ERROR: unknown option '%s'\n", argv[0]); return 1; } int rc = syscall(TILCK_CMD_SYSCALL, TILCK_CMD_PS_TOOL); if (rc < 0) printf("ERROR: the ps tool is not compiled-in\n"); return rc; } static int debug_panel(int argc, char **argv) { if (argc > 0) { if (!strcmp(argv[0], "-t")) return tracer_tool(argc-1, argv+1); printf("ERROR: unknown option '%s'\n", argv[0]); return 1; } int rc = syscall(TILCK_CMD_SYSCALL, TILCK_CMD_DEBUG_PANEL); if (rc < 0) printf("ERROR: debug panel not compiled-in\n"); return rc; } int main(int argc, char **argv) { int rc = -1; char *prog_name; if (argc == 0) { printf("ERROR: argc is 0\n"); return 1; } if (!getenv("TILCK")) { printf("ERROR: the debug panel exists only on Tilck!\n"); return 1; } prog_name = basename(argv[0]); if (!strcmp(prog_name, "dp")) { rc = debug_panel(argc-1, argv+1); } else if (!strcmp(prog_name, "tracer")) { rc = tracer_tool(argc-1, argv+1); } else if (!strcmp(prog_name, "ps")) { rc = ps_tool(argc-1, argv+1); } else { printf("Unknown '%s' tool\n", prog_name); rc = -1; } return rc != 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/list.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/user.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/rwlock.h> #include <tilck/kernel/paging.h> #include <dirent.h> // system header static struct mnt_fs *devfs; /* * Registered drivers. */ static struct driver_info *drivers[32]; static u32 drivers_count; struct mnt_fs * get_devfs(void) { return devfs; } struct driver_info * get_driver_info(u16 major) { for (int i = 0; i < ARRAY_SIZE(drivers) && drivers[i]; i++) { if (drivers[i]->major == major) return drivers[i]; } return NULL; } /* * Registers the driver described by 'info'. * Returns driver's major number. */ int register_driver(struct driver_info *info, int arg_major) { u16 major; /* Be sure there's always enough space. */ VERIFY(drivers_count < ARRAY_SIZE(drivers) - 1); if (arg_major < 0) { major = 900; /* Dynamic major start */ for (int i = 0; i < ARRAY_SIZE(drivers) && drivers[i]; i++) { if (drivers[i]->major == major) major++; } } else { major = (u16) arg_major; if (get_driver_info(major)) panic("Duplicate major number: %d", major); } info->major = major; drivers[drivers_count++] = info; return major; } struct devfs_dir { /* * Yes, sub-directories are NOT supported by devfs. The whole filesystem is * just one flat directory. */ enum vfs_entry_type type; /* Must be FIRST, because of devfs_file */ struct list files_list; tilck_ino_t inode; }; struct devfs_data { struct devfs_dir root_dir; struct rwlock_wp rwlock; time_t wrt_time; tilck_ino_t next_inode; }; static inline tilck_ino_t devfs_get_next_inode(struct devfs_data *d) { return d->next_inode++; } int create_dev_file(const char *filename, u16 major, u16 minor, void **devfile) { struct mnt_fs *fs = devfs; struct driver_info *dinfo; struct devfs_data *d; struct devfs_file *f; int rc; ASSERT(devfs != NULL); if (!(dinfo = get_driver_info(major))) return -EINVAL; if (!(f = kzalloc_obj(struct devfs_file))) return -ENOMEM; d = fs->device_data; f->inode = devfs_get_next_inode(d); f->name = filename; f->dev_major = major; f->dev_minor = minor; list_node_init(&f->dir_node); rc = dinfo->create_dev_file(minor, &f->type, &f->nfo); if (rc < 0) { kfree_obj(f, struct devfs_file); return rc; } if (f->type != VFS_CHAR_DEV && f->type != VFS_BLOCK_DEV) { printk("ERROR: driver %s tried to create %s with type: %d\n", dinfo->name, filename, f->type); kfree_obj(f, struct devfs_file); return -EINVAL; } list_add_tail(&d->root_dir.files_list, &f->dir_node); if (devfile) *devfile = f; return 0; } static ssize_t devfs_dir_read(fs_handle h, char *buf, size_t len, offt *pos) { return -EISDIR; } static ssize_t devfs_dir_write(fs_handle h, char *buf, size_t len, offt *pos) { return -EISDIR; } static offt devfs_dir_seek(fs_handle h, offt target_off, int whence) { struct devfs_handle *dh = h; struct devfs_data *d = dh->fs->device_data; struct devfs_file *pos; offt off = 0; if (target_off < 0 || whence != SEEK_SET) return -EINVAL; list_for_each_ro(pos, &d->root_dir.files_list, dir_node) { if (off == target_off) break; off++; } if (off == target_off) { dh->dpos = pos; dh->dir_pos = off; return dh->dir_pos; } return -EINVAL; } static int devfs_dir_ioctl(fs_handle h, ulong request, void *arg) { return -EINVAL; } int devfs_stat(struct mnt_fs *fs, vfs_inode_ptr_t i, struct k_stat64 *statbuf) { struct devfs_file *df = i; struct devfs_data *ddata = fs->device_data; bzero(statbuf, sizeof(struct k_stat64)); statbuf->st_dev = fs->device_id; switch (df->type) { case VFS_DIR: ASSERT(i == &ddata->root_dir); statbuf->st_mode = 0555 | S_IFDIR; statbuf->st_ino = ddata->root_dir.inode; break; case VFS_CHAR_DEV: statbuf->st_mode = 0666 | S_IFCHR; statbuf->st_ino = df->inode; break; default: panic("devfs: Invalid dentry type: %d", df->type); } statbuf->st_nlink = 1; statbuf->st_uid = 0; /* root */ statbuf->st_gid = 0; /* root */ if (df->type == VFS_CHAR_DEV) statbuf->st_rdev = (dev_t)(df->dev_major << 8 | df->dev_minor); statbuf->st_size = 0; statbuf->st_blksize = PAGE_SIZE; statbuf->st_blocks = 0; statbuf->st_ctim.tv_sec = ddata->wrt_time; statbuf->st_mtim = statbuf->st_ctim; statbuf->st_atim = statbuf->st_mtim; return 0; } static const struct file_ops static_ops_devfs = { .read = devfs_dir_read, .write = devfs_dir_write, .seek = devfs_dir_seek, .ioctl = devfs_dir_ioctl, .mmap = NULL, .munmap = NULL, }; static int devfs_open_root_dir(struct mnt_fs *fs, fs_handle *out) { struct devfs_handle *h; if (!(h = vfs_create_new_handle(fs, &static_ops_devfs))) return -ENOMEM; h->type = VFS_DIR; *out = h; return 0; } static int devfs_open_file(struct mnt_fs *fs, struct devfs_file *pos, fs_handle *out) { struct devfs_handle *h; int rc; if (!(h = vfs_create_new_handle(fs, pos->nfo.fops))) return -ENOMEM; if (pos->nfo.create_extra) { if ((rc = pos->nfo.create_extra(pos->dev_minor, h->extra))) return rc; } h->file = pos; h->type = pos->type; h->spec_flags = pos->nfo.spec_flags; *out = h; return 0; } CREATE_FS_PATH_STRUCT(devfs_path, struct devfs_file *, struct devfs_file *); static int devfs_open(struct vfs_path *p, fs_handle *out, int fl, mode_t mod) { struct devfs_path *dp = (struct devfs_path *) &p->fs_path; if (dp->inode) { if (dp->type == VFS_DIR) return devfs_open_root_dir(p->fs, out); if ((fl & O_CREAT) && (fl & O_EXCL)) return -EEXIST; return devfs_open_file(p->fs, dp->inode, out); } if (fl & O_CREAT) return -EROFS; return -ENOENT; } static void devfs_on_close(fs_handle h) { struct devfs_handle *devh = h; if (devh->type != VFS_DIR) { if (devh->file->nfo.destroy_extra) devh->file->nfo.destroy_extra(devh->file->dev_minor, devh->extra); } } static int devfs_on_dup(fs_handle new_h) { struct devfs_handle *h2 = new_h; int rc = 0; if (h2->type != VFS_DIR) { if (h2->file->nfo.on_dup_extra) rc = h2->file->nfo.on_dup_extra(h2->file->dev_minor, h2->extra); } return rc; } static void devfs_exclusive_lock(struct mnt_fs *fs) { struct devfs_data *d = fs->device_data; rwlock_wp_exlock(&d->rwlock); } static void devfs_exclusive_unlock(struct mnt_fs *fs) { struct devfs_data *d = fs->device_data; rwlock_wp_exunlock(&d->rwlock); } static void devfs_shared_lock(struct mnt_fs *fs) { struct devfs_data *d = fs->device_data; rwlock_wp_shlock(&d->rwlock); } static void devfs_shared_unlock(struct mnt_fs *fs) { struct devfs_data *d = fs->device_data; rwlock_wp_shunlock(&d->rwlock); } static int devfs_getdents(fs_handle h, get_dents_func_cb vfs_cb, void *arg) { struct devfs_handle *dh = h; struct devfs_data *d = dh->fs->device_data; int rc = 0; if (dh->type != VFS_DIR) return -ENOTDIR; if (!dh->dpos) { dh->dpos = list_first_obj( &d->root_dir.files_list, struct devfs_file, dir_node ); } list_for_each_ro_kp(dh->dpos, &d->root_dir.files_list, dir_node) { struct vfs_dent64 dent = { .ino = dh->dpos->inode, .type = dh->dpos->type, .name_len = (u8) strlen(dh->dpos->name) + 1, .name = dh->dpos->name, }; if ((rc = vfs_cb(&dent, arg))) break; } return rc; } static void devfs_get_entry(struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t nl, struct fs_path *fs_path) { struct devfs_data *d = fs->device_data; struct devfs_dir *dir; struct devfs_file *pos; if ((!dir_inode && !name) || is_dot_or_dotdot(name, (int)nl)) { *fs_path = (struct fs_path) { .inode = &d->root_dir, .dir_inode = &d->root_dir, .dir_entry = NULL, .type = VFS_DIR, }; return; } dir = dir_inode; bzero(fs_path, sizeof(*fs_path)); list_for_each_ro(pos, &dir->files_list, dir_node) { if (!strncmp(pos->name, name, (size_t)nl)) if (!pos->name[nl]) break; } if (&pos->dir_node != (struct list_node *) &dir->files_list) { *fs_path = (struct fs_path) { .inode = pos, .dir_inode = dir, .dir_entry = pos, .type = pos->type, }; } } static vfs_inode_ptr_t devfs_get_inode(fs_handle h) { struct devfs_handle *dh = h; struct devfs_data *ddata = dh->fs->device_data; switch (dh->type) { case VFS_DIR: return &ddata->root_dir; case VFS_CHAR_DEV: return dh->file; default: panic("devfs: Invalid dentry type: %d", dh->type); } NOT_REACHED(); } static int devfs_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { /* devfs does not support removal of inodes after boot */ return 1; } static int devfs_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { /* devfs does not support removal of inodes after boot */ return 1; } static const struct fs_ops static_fsops_devfs = { .get_inode = devfs_get_inode, .open = devfs_open, .on_close = devfs_on_close, .on_dup_cb = devfs_on_dup, .getdents = devfs_getdents, .unlink = NULL, .mkdir = NULL, .rmdir = NULL, .truncate = NULL, .stat = devfs_stat, .chmod = NULL, .get_entry = devfs_get_entry, .rename = NULL, .link = NULL, .retain_inode = devfs_retain_inode, .release_inode = devfs_release_inode, .fs_exlock = devfs_exclusive_lock, .fs_exunlock = devfs_exclusive_unlock, .fs_shlock = devfs_shared_lock, .fs_shunlock = devfs_shared_unlock, }; struct mnt_fs * create_devfs(void) { struct mnt_fs *fs; struct devfs_data *d; /* Disallow multiple instances of devfs */ ASSERT(devfs == NULL); if (!(d = kzalloc_obj(struct devfs_data))) return NULL; fs = create_fs_obj("devfs", &static_fsops_devfs, d, VFS_FS_RW); if (!fs) { kfree_obj(d, struct devfs_data); return NULL; } d->next_inode = 1; d->root_dir.type = VFS_DIR; d->root_dir.inode = devfs_get_next_inode(d); list_init(&d->root_dir.files_list); rwlock_wp_init(&d->rwlock, false); d->wrt_time = (time_t)get_timestamp(); return fs; } int devfs_kernel_create_handle_for(void *devfile, fs_handle *out) { return devfs_open_file(devfs, devfile, out); } void devfs_kernel_destory_handle(fs_handle h) { devfs_on_close(h); vfs_free_handle(h); } void init_devfs(void) { int rc; if ((rc = vfs_mkdir("/dev", 0777))) panic("vfs_mkdir(\"/dev\") failed with error: %d", rc); devfs = create_devfs(); if (!devfs) panic("Unable to create devfs"); if ((rc = mp_add(devfs, "/dev/"))) panic("mp_add() failed with error: %d", rc); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/system_mmap.h> STATIC void fix_mem_regions(void); STATIC void align_mem_regions_to_page_boundary(void); STATIC void sort_mem_regions(void); STATIC void merge_adj_mem_regions(void); STATIC void handle_overlapping_regions(void); extern struct mem_region mem_regions[MAX_MEM_REGIONS]; extern int mem_regions_count; <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # --------------------------------------------------------------- # NOTE # # This "script" is NOT meant to be executed directly. # It is included as a source file by scripts/build_toolchain. # # --------------------------------------------------------------- function install_debian_family { echo debian > $TC/.distro if [ "$RUNNING_IN_CI" == 1 ]; then $MAIN_DIR/scripts/tc/debian/update fi pkg_list=() pkg_list+=(debianutils) pkg_list+=(tar) pkg_list+=(grep) pkg_list+=(gzip) pkg_list+=(gawk) pkg_list+=(wget) pkg_list+=(git) pkg_list+=(gcc) pkg_list+=(g++) pkg_list+=(make) pkg_list+=(cmake) pkg_list+=(binutils) pkg_list+=(bzip2) pkg_list+=(unzip) pkg_list+=(parted) if [[ "$TC_MINIMAL" != "1" ]]; then pkg_list+=(qemu-system-x86) pkg_list+=(python3) # qemu-system-gui exists only in 20.04 and newer, so we need to check # the distro's major version before checking for that package. major_ver=`lsb_release -r | grep -Eo '[0-9]+' | head -1` if [ $major_ver -ge 20 ]; then pkg_list+=(qemu-system-gui) fi fi to_install=() echo Checking the packages that need to be installed for x in ${pkg_list[@]}; do echo -ne "Checking $x... " if [ "`dpkg -s $x 2>&1 | grep Status`" ]; then echo OK else echo NOT found to_install+=($x) fi done echo # Install the packages if [ ${#to_install[@]} -ne 0 ]; then echo ${#to_install[@]} packages need to be installed tmp="${to_install[@]}" if [ "$RUNNING_IN_CI" == 1 ]; then run_command "apt install -y $tmp" else if ! which sudo &> /dev/null; then run_command "su -c \"apt install $tmp\"" else run_command "sudo apt install $tmp" fi fi else echo "You are all set, no packages need to be installed." fi } function install_fedora { echo fedora > $TC/.distro if [ "$RUNNING_IN_CI" == 1 ]; then $MAIN_DIR/scripts/tc/fedora/update fi pkg_list=() pkg_list+=(which) pkg_list+=(tar) pkg_list+=(grep) pkg_list+=(gzip) pkg_list+=(gawk) pkg_list+=(wget) pkg_list+=(git) pkg_list+=(gcc) pkg_list+=(gcc-c++) pkg_list+=(make) pkg_list+=(cmake) pkg_list+=(binutils) pkg_list+=(bzip2) pkg_list+=(unzip) pkg_list+=(parted) if [[ "$TC_MINIMAL" != "1" ]]; then pkg_list+=(qemu-system-x86) pkg_list+=(qemu-ui-gtk) pkg_list+=(python3) fi to_install=() echo Checking the packages that need to be installed for x in ${pkg_list[@]}; do echo -ne "Checking $x... " if dnf list installed $x &> /dev/null; then echo OK else echo NOT found to_install+=($x) fi done if [ ${#to_install[@]} -ne 0 ]; then echo ${#to_install[@]} packages need to be installed tmp="${to_install[@]}" if [ "$RUNNING_IN_CI" == 1 ]; then run_command "dnf install -y $tmp" else run_command "sudo dnf install $tmp" fi else echo "You are all set, no packages need to be installed." fi } function install_arch { echo arch > $TC/.distro if [ "$RUNNING_IN_CI" == 1 ]; then $MAIN_DIR/scripts/tc/arch/update fi pkg_list=() pkg_list+=(which) pkg_list+=(tar) pkg_list+=(grep) pkg_list+=(gzip) pkg_list+=(gawk) pkg_list+=(wget) pkg_list+=(git) pkg_list+=(gcc) pkg_list+=(make) pkg_list+=(cmake) pkg_list+=(binutils) pkg_list+=(bzip2) pkg_list+=(unzip) pkg_list+=(parted) if [[ "$TC_MINIMAL" != "1" ]]; then pkg_list+=(qemu) pkg_list+=(qemu-system-x86) pkg_list+=(qemu-ui-gtk) pkg_list+=(python3) fi to_install=() echo Checking the packages that need to be installed for x in ${pkg_list[@]}; do echo -ne "Checking $x... " if pacman -Q $x &> /dev/null; then echo OK else echo NOT found to_install+=($x) fi done if [ ${#to_install[@]} -ne 0 ]; then echo ${#to_install[@]} packages need to be installed tmp="${to_install[@]}" if [ "$RUNNING_IN_CI" == 1 ]; then run_command "pacman -S --noconfirm $tmp" else run_command "sudo pacman -S $tmp" fi else echo "You are all set, no packages need to be installed." fi } function install_openSUSE { echo opensuse > $TC/.distro if [ "$RUNNING_IN_CI" == 1 ]; then $MAIN_DIR/scripts/tc/opensuse/update fi pkg_list=() pkg_list+=(which) pkg_list+=(tar) pkg_list+=(grep) pkg_list+=(gzip) pkg_list+=(gawk) pkg_list+=(glibc-locale-base) pkg_list+=(wget) pkg_list+=(git-core) pkg_list+=(gcc) pkg_list+=(gcc-c++) pkg_list+=(make) pkg_list+=(cmake) pkg_list+=(binutils) pkg_list+=(bzip2) pkg_list+=(unzip) pkg_list+=(parted) if [[ "$TC_MINIMAL" != "1" ]]; then pkg_list+=(qemu-x86) pkg_list+=(qemu-ui-gtk) pkg_list+=(python3) fi to_install=() echo Checking the packages that need to be installed for x in ${pkg_list[@]}; do echo -ne "Checking $x... " if rpm -q $x &> /dev/null; then echo OK else echo NOT found to_install+=($x) fi done if [ ${#to_install[@]} -ne 0 ]; then echo ${#to_install[@]} packages need to be installed tmp="${to_install[@]}" if [ "$RUNNING_IN_CI" == 1 ]; then run_command "zypper install -y $tmp" else run_command "sudo zypper install $tmp" fi else echo "You are all set, no packages need to be installed." fi } function install_packages { rel_files=`echo /etc/*release` lsb="/etc/lsb-release" os_rel="/etc/os-release" if ! [ -f /bin/grep ] && ! [ -f /usr/bin/grep ]; then if ! echo 'aaa bbb' | grep aaa &> /dev/null; then echo "The command 'grep' has not been found on the system." echo "We cannot even detect the current linux distribution." echo "Please, install at least grep." exit 1 fi fi # Where lsb-release exists, use only it. # On Mint doing grep /etc/*release reports an error because there is an # upstream-release directory matching that wildcard. Using grep -r is not # a solution since in /etc/upstream-release/* on Mint, Ubuntu is mentioned. if [ -f $lsb ] && [ "$(grep -Ei 'buntu|mint' $lsb)" ]; then echo "Distribution detected: Ubuntu (any) or Mint" echo "" install_debian_family # Debian does not contain the lsb-release file. elif [ -f $os_rel ] && [ "$(grep -Ei 'debian' $os_rel)" ]; then echo "Distribution detected: Debian" echo "" install_debian_family # On Fedora, we need to check if exactly a [Ff]edora-release file exists. elif echo $rel_files | grep -Ei 'fedora' - &> /dev/null; then echo "Distribution detected: Fedora" echo "" install_fedora elif echo $rel_files | grep -Ei 'arch|manjaro|artix' - &> /dev/null; then echo "Distribution detected: Arch or Manjaro or Artix" echo "" install_arch elif [ -f $os_rel ] && [ "$(grep -Ei 'openSUSE' $os_rel)" ]; then echo "Distribution detected: openSUSE" echo "" install_openSUSE else full_list=() full_list+=(wget) full_list+=(tar) full_list+=(grep) full_list+=(gzip) full_list+=(gawk) full_list+=(git) full_list+=(gcc) full_list+=(g++) full_list+=(make) full_list+=(cmake) full_list+=(objdump) full_list+=(rpm2cpio) full_list+=(cpio) full_list+=(bzip2) full_list+=(unzip) full_list+=(parted) full_list+=(qemu-system-i386) to_install_list=() which_installed=0 if which bash &> /dev/null; then which_installed=1 else to_install_list+=(which) fi for x in ${full_list[@]}; do if [ "$which_installed" == 1 ]; then if ! which $x &> /dev/null; then to_install_list+=($x) fi else to_install_list+=($x) fi done if [ ${#to_install_list[@]} -ne 0 ]; then echo "Your distribution is not fully supported by this script." echo "The supported distros are:" echo " * Ubuntu" echo " * Mint" echo " * Debian" echo " * Fedora" echo " * Arch" echo " * Manjaro" echo " * Artix" echo " * openSUSE" echo "In order to build Tilck on this distro, please make sure the " echo "following programs are installed:" for x in ${to_install_list[@]}; do echo " * $x" done echo "After that, re-run this script with --skip-install-pkgs" exit 1 fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/user.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/sys_types.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sched.h> #define FULL_RESYNC_MAX_ATTEMPTS 10 const char *weekdays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; const char *months3[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; static s64 boot_timestamp; static bool in_full_resync; #if KRN_CLOCK_DRIFT_COMP static bool first_sssync_failed; /* first_sub_second_sync_failed */ static int adj_cnt; /* adjustments count (temporary, gets reset) */ #endif /* lifetime statistics about re-syncs */ static struct clock_resync_stats clock_rstats; // Regular value u32 clock_drift_adj_loop_delay = 600 * TIMER_HZ; // Value suitable for the `time` selftest // u32 clock_drift_adj_loop_delay = 60 * TIMER_HZ; extern u64 __time_ns; extern u32 __tick_duration; extern int __tick_adj_val; extern int __tick_adj_ticks_rem; bool clock_in_full_resync(void) { return in_full_resync; } bool clock_in_resync(void) { ulong var; int rem; if (in_full_resync) return true; disable_interrupts(&var); { rem = __tick_adj_ticks_rem; } enable_interrupts(&var); return rem != 0; } void clock_get_resync_stats(struct clock_resync_stats *s) { *s = clock_rstats; } #if KRN_CLOCK_DRIFT_COMP static int clock_get_second_drift2(bool enable_preempt_on_exit) { struct datetime d; s64 sys_ts, hw_ts; u32 under_sec; u64 ts; while (true) { disable_preemption(); hw_read_clock(&d); ts = get_sys_time(); under_sec = (u32)(ts % TS_SCALE); /* * We don't want to measure the drift when we're too close to the second * border line, because there's a real chance to measure this way a * non-existent clock drift. For example: suppose that the seconds value * of the real clock time is 34.999, but we read just 34, of course. * If now our system time is ahead by even just 1 ms [keep in mind we * don't disable the interrupts and ticks to continue to increase], we'd * read something like 35.0001 and get 35 after the truncation. Therefore, * we'll "measure" +1 second of drift, which is completely false! It makes * only sense to measure the drift in the middle of the second. */ if (IN_RANGE(under_sec, TS_SCALE/4, TS_SCALE/4*3)) { sys_ts = boot_timestamp + (s64)(ts / TS_SCALE); break; } /* We weren't in the middle of the second. Sleep 0.1s and try again */ enable_preemption_nosched(); kernel_sleep(TIMER_HZ / 10); } /* NOTE: here we always have the preemption disabled */ if (enable_preempt_on_exit) enable_preemption(); hw_ts = datetime_to_timestamp(d); return (int)(sys_ts - hw_ts); } static bool clock_sub_second_resync(void) { struct datetime d; s64 hw_ts, ts; u64 hw_time_ns; int drift, abs_drift; u32 micro_attempts_cnt; u32 local_full_resync_fails = 0; retry: in_full_resync = true; micro_attempts_cnt = 0; disable_preemption(); hw_read_clock(&d); hw_ts = datetime_to_timestamp(d); while (true) { hw_read_clock(&d); ts = datetime_to_timestamp(d); micro_attempts_cnt++; if (ts != hw_ts) { /* * BOOM! We just detected the exact moment when the HW clock changed * the timestamp (seconds). Now, we have to be super quick about * calculating the adjustments. * * NOTE: we're leaving the loop with preemption disabled! */ break; } /* * From time to time we _have to_ allow other tasks to get some job done, * not stealing the CPU for a whole full second. */ if (!(micro_attempts_cnt % 300)) { enable_preemption_nosched(); { /* Sleep for a 1/5 of a second */ kernel_sleep(TIMER_HZ / 5); } disable_preemption(); /* * Now that we're back, we have to re-read the "old" clock value * because time passed and it's very likely that we're in a new second. * Without re-reading this "old" value, on the next iteration we might * hit the condition `ts != hw_ts` thinking that we've found the second * edge, while just too much time passed. * * Therefore, re-reading the old value (hw_ts) fully restarts our * search for the bleeding edge of the second, hoping that in the next * burst of attempts we'll be lucky enough to find the exact moment * when the HW clock changes the second. * * NOTE: this code has been tested with an infinite loop in `init` * stealing competing for the CPU with this kernel thread and, * reliably, in a few seconds we had been able to end this loop. */ hw_read_clock(&d); hw_ts = datetime_to_timestamp(d); } } /* * Now that we waited until the seconds changed, we have to very quickly * calculate our initial drift (offset) and set __tick_adj_val and * __tick_adj_ticks_rem accordingly to compensate it. */ disable_interrupts_forced(); { hw_time_ns = round_up_at64(__time_ns, TS_SCALE); if (hw_time_ns > __time_ns) { STATIC_ASSERT(TS_SCALE <= BILLION); /* NOTE: abs_drift cannot be > TS_SCALE [typically, 1 BILLION] */ abs_drift = (int)(hw_time_ns - __time_ns); __tick_adj_val = (TS_SCALE / TIMER_HZ) / 10; __tick_adj_ticks_rem = abs_drift / __tick_adj_val; } } enable_interrupts_forced(); clock_rstats.full_resync_count++; /* * We know that we need at most 10 seconds to compensate 1 second of drift, * which is the max we can get at boot-time. Now, just to be sure, wait 15s * and then check we have absolutely no drift measurable in seconds. */ enable_preemption_nosched(); kernel_sleep(15 * TIMER_HZ); drift = clock_get_second_drift2(true); abs_drift = (drift > 0 ? drift : -drift); if (abs_drift > 1) { /* * The absolute drift must be <= 1 here. * abs_drift > 1 is VERY UNLIKELY to happen, but everything is possible, * we have to handle it somehow. Just fail silently and let the rest of * the code in clock_drift_adj() compensate for the multi-second drift. */ in_full_resync = false; clock_rstats.full_resync_fail_count++; clock_rstats.full_resync_abs_drift_gt_1++; return false; } if (abs_drift == 1) { clock_rstats.full_resync_fail_count++; if (++local_full_resync_fails > FULL_RESYNC_MAX_ATTEMPTS) panic("Time-management: drift (%d) must be zero after sync", drift); goto retry; } /* Default case: abs_drift == 0 */ in_full_resync = false; clock_rstats.full_resync_success_count++; return true; } static void clock_multi_second_resync(int drift) { const int abs_drift = (drift > 0 ? drift : -drift); const int adj_val = (TS_SCALE / TIMER_HZ) / (drift > 0 ? -10 : 10); const int adj_ticks = abs_drift * TIMER_HZ * 10; disable_interrupts_forced(); { __tick_adj_val = adj_val; __tick_adj_ticks_rem = adj_ticks; } enable_interrupts_forced(); clock_rstats.multi_second_resync_count++; } static void check_drift_and_sync(void) { /* NOTE: this disables the preemption */ const int drift = clock_get_second_drift2(false); const int abs_drift = (drift > 0 ? drift : -drift); if (abs_drift >= 2) { adj_cnt++; clock_multi_second_resync(drift); } else if ((abs_drift == 1 && adj_cnt > 6) || first_sssync_failed) { /* * The periodic drift compensation works great even in the * "long run" but it's expected very slowly to accumulate with * time some sub-second drift that cannot be measured directly, * because of HW clock's 1s resolution. We'll inevitably end up * introducing some error while compensating the apparent 1 sec * drift (which, in reality was 1.01s, for example). * * To compensate even this 2nd-order problem, it's worth from time * to time to do a full-resync (also called sub-second resync). * This should happen less then once every 24 h, depending on how * accurate the PIT is. */ enable_preemption_nosched(); /* note the clock_get_second_drift2() call */ { clock_sub_second_resync(); adj_cnt = 0; first_sssync_failed = false; } disable_preemption(); } enable_preemption(); } static void clock_drift_adj() { /* Sleep 1 second after boot, in order to get a real value of `__time_ns` */ kernel_sleep(TIMER_HZ); /* * When Tilck starts, in init_system_time() we register system clock's time. * But that time has a resolution of one second. After that, we keep the * time using PIT's interrupts and here below we compensate any drifts. * * The problem is that, since init_system_time() it's super easy for us to * hit a clock drift because `boot_timestamp` is in seconds. For example, we * had no way to know that we were in second 23.99: we'll see just second 23 * and start counting from there. We inevitably start with a drift < 1 sec. * * Now, we could in theory avoid that by looping in init_system_time() until * time changes, but that would mean wasting up to 1 sec of boot time. That's * completely unacceptable. What we can do instead, is to boot and start * working knowing that we have a clock drift < 1 sec and then, in this * kernel thread do the loop, waiting for the time to change and calculating * this way, the initial clock drift. * * The code doing this job is in the function clock_sub_second_resync(). */ if (clock_sub_second_resync()) { /* * Since we got here, everything is alright. There is no more clock drift. * Sleep some time and then start the actual infinite loop of this thread, * which will compensate any clock drifts that might occur as Tilck runs * for a long time. */ kernel_sleep(clock_drift_adj_loop_delay); } else { /* * If we got here, clock_sub_second_resync() detected an abs_drift > 1, * which is an extremely unlikely event. Handling: enter the loop as * described in the positive case, just without sleeping first. * The multi-second drift will be detected and clock_multi_second_resync() * will be called to compensate for that. In addition to that, set the * `first_sssync_failed` variable to true forcing another sub-second sync * after the first (multi-second) one. Note: in this case the condition * `abs_drift >= 2` will be immediately hit. */ first_sssync_failed = true; } while (true) { if (!clock_in_resync()) { /* * It makes sense to check for the clock drift ONLY when there are * NO already ongoing corrections. */ check_drift_and_sync(); } kernel_sleep(clock_drift_adj_loop_delay); } } int clock_get_second_drift(void) { return clock_get_second_drift2(true); } #else int clock_get_second_drift(void) { return 0; } #endif // KRN_CLOCK_DRIFT_COMP void init_system_time(void) { struct datetime d; #if KRN_CLOCK_DRIFT_COMP if (kthread_create(&clock_drift_adj, 0, NULL) < 0) printk("WARNING: unable to create a kthread for clock_drift_adj()\n"); #endif hw_read_clock(&d); boot_timestamp = datetime_to_timestamp(d); if (boot_timestamp < 0) panic("Invalid boot-time UNIX timestamp: %d\n", boot_timestamp); __time_ns = 0; } u64 get_sys_time(void) { u64 ts; ulong var; disable_interrupts(&var); { ts = __time_ns; } enable_interrupts(&var); return ts; } s64 get_timestamp(void) { const u64 ts = get_sys_time(); return boot_timestamp + (s64)(ts / TS_SCALE); } void ticks_to_timespec(u64 ticks, struct k_timespec64 *tp) { const u64 tot = ticks * __tick_duration; tp->tv_sec = (s64)(tot / TS_SCALE); if (TS_SCALE <= BILLION) tp->tv_nsec = (tot % TS_SCALE) * (BILLION / TS_SCALE); else tp->tv_nsec = (tot % TS_SCALE) / (TS_SCALE / BILLION); } u64 timespec_to_ticks(const struct k_timespec64 *tp) { u64 ticks = 0; ticks += div_round_up64((u64)tp->tv_sec * TS_SCALE, __tick_duration); if (TS_SCALE <= BILLION) { ticks += div_round_up64( (u64)tp->tv_nsec / (BILLION / TS_SCALE), __tick_duration ); } else { ticks += div_round_up64( (u64)tp->tv_nsec * (TS_SCALE / BILLION), __tick_duration ); } return ticks; } void real_time_get_timespec(struct k_timespec64 *tp) { const u64 t = get_sys_time(); tp->tv_sec = (s64)boot_timestamp + (s64)(t / TS_SCALE); if (TS_SCALE <= BILLION) tp->tv_nsec = (t % TS_SCALE) * (BILLION / TS_SCALE); else tp->tv_nsec = (t % TS_SCALE) / (TS_SCALE / BILLION); } void monotonic_time_get_timespec(struct k_timespec64 *tp) { /* Same as the real_time clock, for the moment */ real_time_get_timespec(tp); } static void task_cpu_get_timespec(struct k_timespec64 *tp) { struct task *ti = get_curr_task(); disable_preemption(); { ticks_to_timespec(ti->ticks.total, tp); } enable_preemption(); } int sys_gettimeofday(struct k_timeval *user_tv, struct timezone *user_tz) { struct k_timeval tv; struct k_timespec64 tp; struct timezone tz = { .tz_minuteswest = 0, .tz_dsttime = 0, }; real_time_get_timespec(&tp); tv = (struct k_timeval) { .tv_sec = (long)tp.tv_sec, .tv_usec = tp.tv_nsec / 1000, }; if (user_tv) if (copy_to_user(user_tv, &tv, sizeof(tv)) < 0) return -EFAULT; if (user_tz) if (copy_to_user(user_tz, &tz, sizeof(tz)) < 0) return -EFAULT; return 0; } int do_clock_gettime(clockid_t clk_id, struct k_timespec64 *tp) { switch (clk_id) { case CLOCK_REALTIME: case CLOCK_REALTIME_COARSE: real_time_get_timespec(tp); break; case CLOCK_MONOTONIC: case CLOCK_MONOTONIC_COARSE: case CLOCK_MONOTONIC_RAW: monotonic_time_get_timespec(tp); break; case CLOCK_PROCESS_CPUTIME_ID: case CLOCK_THREAD_CPUTIME_ID: task_cpu_get_timespec(tp); break; default: printk("WARNING: unsupported clk_id: %d\n", clk_id); return -EINVAL; } return 0; } int do_clock_getres(clockid_t clk_id, struct k_timespec64 *res) { switch (clk_id) { case CLOCK_REALTIME: case CLOCK_REALTIME_COARSE: case CLOCK_MONOTONIC: case CLOCK_MONOTONIC_COARSE: case CLOCK_MONOTONIC_RAW: case CLOCK_PROCESS_CPUTIME_ID: case CLOCK_THREAD_CPUTIME_ID: *res = (struct k_timespec64) { .tv_sec = 0, .tv_nsec = BILLION/TIMER_HZ, }; break; default: printk("WARNING: unsupported clk_id: %d\n", clk_id); return -EINVAL; } return 0; } /* * ----------------- SYSCALLS ----------------------- */ int sys_clock_gettime32(clockid_t clk_id, struct k_timespec32 *user_tp) { struct k_timespec64 tp64; struct k_timespec32 tp32; int rc; if (!user_tp) return -EINVAL; if ((rc = do_clock_gettime(clk_id, &tp64))) return rc; tp32 = (struct k_timespec32) { .tv_sec = (s32) tp64.tv_sec, .tv_nsec = tp64.tv_nsec, }; if (copy_to_user(user_tp, &tp32, sizeof(tp32)) < 0) return -EFAULT; return 0; } int sys_clock_gettime(clockid_t clk_id, struct k_timespec64 *user_tp) { struct k_timespec64 tp; int rc; if (!user_tp) return -EINVAL; if ((rc = do_clock_gettime(clk_id, &tp))) return rc; if (copy_to_user(user_tp, &tp, sizeof(tp)) < 0) return -EFAULT; return 0; } int sys_clock_getres_time32(clockid_t clk_id, struct k_timespec32 *user_res) { struct k_timespec64 tp64; struct k_timespec32 tp32; int rc; if (!user_res) return -EINVAL; if ((rc = do_clock_getres(clk_id, &tp64))) return rc; tp32 = (struct k_timespec32) { .tv_sec = (s32) tp64.tv_sec, .tv_nsec = tp64.tv_nsec, }; if (copy_to_user(user_res, &tp32, sizeof(tp32)) < 0) return -EFAULT; return 0; } int sys_clock_getres(clockid_t clk_id, struct k_timespec64 *user_res) { struct k_timespec64 tp; int rc; if (!user_res) return -EINVAL; if ((rc = do_clock_gettime(clk_id, &tp))) return rc; if (copy_to_user(user_res, &tp, sizeof(tp)) < 0) return -EFAULT; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <signal.h> #include <stdbool.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <poll.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/prctl.h> #include <sys/ioctl.h> #include <sys/reboot.h> #include <linux/reboot.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/config_init.h> #include <tilck/common/basic_defs.h> /* for MIN() and ARRAY_SIZE() */ static char *start_script_args[2] = { START_SCRIPT, NULL }; static char *shell_args[16] = { DEFAULT_SHELL, [1 ... 15] = NULL }; static int shell_pids[128] = {0}; static volatile bool in_shutdown; static int video_tty_count; static FILE *tty0; static int reboot_cmd; static int fork_and_run_shell_on_tty(int tty); /* -- command line options -- */ static bool opt_quiet; static bool opt_nostart; static bool opt_no_shell_respawn; static bool opt_do_exit; /* -- end -- */ NORETURN static void call_exit(int code) { printf("[init] exit with code: %i\n", code); exit(code); } static void do_graceful_shutdown(void) { in_shutdown = true; printf("[init] Sending SIGTERM to all tasks...\n"); kill(-1, SIGTERM); printf("[init] Waiting at most 1 sec...\n"); } static void init_handle_sig_term(int sig) { printf("[init] Reboot...\n"); do_graceful_shutdown(); reboot_cmd = LINUX_REBOOT_CMD_RESTART; } static void init_handle_sig_usr1(int sig) { printf("[init] Halt...\n"); do_graceful_shutdown(); reboot_cmd = LINUX_REBOOT_CMD_HALT; } static void init_handle_sig_usr2(int sig) { printf("[init] Poweroff...\n"); do_graceful_shutdown(); reboot_cmd = LINUX_REBOOT_CMD_POWER_OFF; } static void init_set_signal_mask(void) { signal(SIGTERM, &init_handle_sig_term); signal(SIGUSR1, &init_handle_sig_usr1); signal(SIGUSR2, &init_handle_sig_usr2); } static void init_reset_signal_mask(void) { signal(SIGTERM, SIG_DFL); signal(SIGUSR1, SIG_DFL); signal(SIGUSR2, SIG_DFL); } static int get_video_tty_count(void) { static int count = 0; struct stat statbuf; char buf[32]; if (!getenv("TILCK")) { /* On Linux we're not going to use multiple TTYs for testing. */ return 1; } if (count) return count; for (int i = 0; i <= MAX_TTYS; i++) { sprintf(buf, "/dev/tty%d", i); if (stat(buf, &statbuf) != 0) break; if (i > 0) count++; /* don't count /dev/tty0 */ } return count; } static void open_std_handles(int tty) { char ttyfile[32] = "/dev/console"; if (tty >= 0) { if (tty < TTYS0_MINOR) sprintf(ttyfile, "/dev/tty%d", tty); else sprintf(ttyfile, "/dev/ttyS%d", tty - TTYS0_MINOR); } int in = open(ttyfile, O_RDONLY); int out = open(ttyfile, O_WRONLY); int err = open(ttyfile, O_WRONLY); if (in != 0) { printf("[init] in: %i, expected: 0\n", in); call_exit(1); } if (out != 1) { printf("[init] out: %i, expected: 1\n", out); call_exit(1); } if (err != 2) { printf("[init] err: %i, expected: 2\n", err); call_exit(1); } } static void run_start_script(void) { int rc, wstatus; struct stat statbuf; pid_t pid; rc = stat(BUSYBOX, &statbuf); if (rc < 0 || (statbuf.st_mode & S_IFMT) != S_IFREG) { printf("[init][WARNING] Unable to run the script %s: " "busybox not found\n", START_SCRIPT); return; } pid = fork(); if (pid < 0) { printf("[init] fork() failed with %d\n", pid); call_exit(1); } if (!pid) { init_reset_signal_mask(); execve(start_script_args[0], start_script_args, NULL); printf("[init] execve(%s) failed with: %s\n", start_script_args[0], strerror(errno)); exit(1); } rc = waitpid(-1, &wstatus, 0); if (rc != pid) { printf("[init] waitpid(-1) returned %d instead of pid %d\n", rc, pid); call_exit(1); } if (!WIFEXITED(wstatus)) { printf("[init] Start script killed by sig %d\n", WTERMSIG(wstatus)); call_exit(1); } if (WEXITSTATUS(wstatus) != 0) { printf("[init] Start script exited with %d\n", WEXITSTATUS(wstatus)); call_exit(1); } } static void do_initial_setup(void) { if (!getenv("TILCK")) { fprintf(stderr, "[init] Tilck specific program. Not tested on Linux\n"); exit(1); // if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) < 0) // perror("prctl(PR_SET_CHILD_SUBREAPER) failed"); } open_std_handles(-1); tty0 = fopen("/dev/tty0", "w"); if (!tty0) { fprintf(stderr, "[init] Unable to open /dev/tty0: %s\n", strerror(errno)); exit(1); } /* * In order to allow the start /etc/start to begin simply with #!/bin/sh * instead of "#!/initrd/bin/busybox ash", we need to create /bin and symlink * busybox to /bin/sh. */ if (mkdir("/bin", 0777) < 0) { fprintf(stderr, "[init] Failed to create /bin: %s\n", strerror(errno)); exit(1); } if (symlink("/initrd/bin/busybox", "/bin/sh") < 0) { fprintf(stderr, "[init] Failed to create symlink: %s\n", strerror(errno)); exit(1); } } static int get_tty_for_shell_pid(pid_t shell_pid) { for (int i = 0; i < ARRAY_SIZE(shell_pids); i++) { if (shell_pids[i] == shell_pid) return i; } return -1; } static void report_shell_exit(pid_t pid, int tty, int wstatus) { const int status = WEXITSTATUS(wstatus); const int term_sig = WTERMSIG(wstatus); if (term_sig) { fprintf(tty0, "[init] the shell with pid %d was killed by signal %d\n", pid, term_sig); } else { fprintf(tty0, "[init] the shell with pid %d exited with status: %d\n", pid, status); } if (opt_no_shell_respawn || in_shutdown) return; fprintf(tty0, "\n"); shell_pids[tty] = fork_and_run_shell_on_tty(tty); } static void report_process_exit(pid_t pid, int wstatus) { if (opt_quiet || !INIT_REPORT_PROC_EXIT) return; const int status = WEXITSTATUS(wstatus); const int term_sig = WTERMSIG(wstatus); if (term_sig) printf("[init] process %d killed by signal: %d\n", pid, term_sig); else printf("[init] process %d exited with status: %d\n", pid, status); } static void show_help_and_exit(void) { printf("\nUsage:\n\n"); printf(" init Regular run. Shell: %s\n", DEFAULT_SHELL); printf(" init -h/--help Show this help and exit\n"); printf(" init -q Quiet: don't report exit of orphan tasks\n"); printf(" init -ns Don't run the script: %s\n", START_SCRIPT); printf(" init -nr Don't respawn shells\n"); printf(" init -- <cmdline> " "Run the specified cmdline instead of the default one.\n"); printf(" " "Example: init -- /bin/devshell -c waitpid2\n"); exit(0); } static void parse_opts(int argc, char **argv) { begin: if (!argc) return; if (!strcmp(*argv, "-q")) { opt_quiet = true; argc--; argv++; goto begin; } if (!strcmp(*argv, "-ns")) { opt_nostart = true; argc--; argv++; goto begin; } if (!strcmp(*argv, "-nr")) { opt_no_shell_respawn = true; argc--; argv++; goto begin; } if (!strcmp(*argv, "-e")) { opt_do_exit = true; argc--; argv++; goto begin; } if (!strcmp(*argv, "--")) { const int elems = MIN(ARRAY_SIZE(shell_args), argc - 1); memcpy(shell_args, argv + 1, elems * sizeof(char *)); return; } /* Unknown option case */ printf("[init] Unknown option '%s'\n", *argv); } static void wait_for_children(int timeout_ms) { const bool was_in_shutdown = in_shutdown; int shell_tty, wstatus; int elapsed_ms = timeout_ms ? 0 : -1; pid_t pid; while (elapsed_ms < timeout_ms) { if (!timeout_ms) { pid = waitpid(-1, &wstatus, 0); } else { pid = waitpid(-1, &wstatus, WNOHANG); if (pid == 0) { /* no child changed its state */ usleep(100 * 1000); /* 100 ms */ elapsed_ms += 100; continue; } } if (pid < 0) { if (errno == EINTR) { if (was_in_shutdown != in_shutdown) { /* Graceful shutdown started */ break; } continue; } if (errno == ECHILD) break; printf("[init] waitpid() returned: %d (%s)\n", errno, strerror(errno)); } shell_tty = get_tty_for_shell_pid(pid); if (shell_tty > 0) report_shell_exit(pid, shell_tty, wstatus); else report_process_exit(pid, wstatus); } } static void setup_console_for_shell(int tty) { if (tty == 1 || (tty == TTYS0_MINOR && !video_tty_count)) { /* * For /dev/tty1 we're already fine. The current process already has tty1 * as controlling terminal (set by the kernel) and do_initial_setup() * called open_std_handles(1). For the other shell instances instead, we * have to correctly setup the tty. */ return; } close(2); close(1); close(0); setsid(); /* Reset the controlling terminal */ open_std_handles(tty); /* Open /dev/ttyN as stdin, stdout and stderr */ ioctl(0, TIOCSCTTY, 0); /* Make ttyN to be the controlling terminal */ tcsetpgrp(0, getpgid(0)); /* Make this pgid the foreground process group */ } static void tilck_console_msg_loop(int tty) { char buf[32]; int poll_timeout = -1; /* infinite */ int rc; struct pollfd fd = { .fd = 0, .events = POLLIN, }; do { const char *serial_tty_suffix = ""; int user_tty_num = tty; if (tty >= TTYS0_MINOR) { poll_timeout = 3000; /* 3 seconds */ serial_tty_suffix = "S"; user_tty_num = tty - TTYS0_MINOR; /* clear the screen */ printf("\033[2J\033[1;1H"); } printf("Tilck console on /dev/tty%s%d\n", serial_tty_suffix, user_tty_num); printf("------------------------------------------\n\n"); printf("Press ENTER to run the shell"); fflush(stdout); } while (poll(&fd, 1, poll_timeout) <= 0); /* drain the input buffer */ do { rc = read(0, buf, sizeof(buf)); if (rc < 0 && errno == EINTR) continue; } while (rc == sizeof(buf)); printf("\n"); } static void getty_handle_sigterm(int sig) { /* clear the screen */ printf("\033[2J\033[1;1H"); /* write a meaningful message on the screen */ printf("System shutdown.\n"); /* graceful exit */ exit(0); } static int fork_and_run_shell_on_tty(int tty) { static bool already_run; pid_t pid = fork(); if (pid < 0) { perror("[init] fork() failed"); call_exit(1); } if (pid) { /* Parent process */ already_run = true; return pid; } /* Child process */ setup_console_for_shell(tty); init_reset_signal_mask(); signal(SIGTERM, &getty_handle_sigterm); if (video_tty_count && (tty > 1 || already_run)) { /* * Instead of wasting resources for running the shell from now, just wait * until an user is connected and presses ENTER. */ tilck_console_msg_loop(tty); } execve(shell_args[0], shell_args, NULL); printf("[init] execve(%s) failed with: %s\n", shell_args[0], strerror(errno)); call_exit(1); } int main(int argc, char **argv, char **env) { int pid = getpid(); struct stat statbuf; if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) show_help_and_exit(); if (pid != 1) { fprintf(stderr, "FATAL ERROR: init has pid %d.\n" "Init expects to be the 1st user process (pid 1) " "to run on the system.\n" "Running it on an already running system is *not* supported.\n", pid); return 1; } video_tty_count = get_video_tty_count(); init_set_signal_mask(); do_initial_setup(); parse_opts(argc - 1, argv + 1); if (!opt_nostart) { run_start_script(); } else { printf("[init] Skipping the start script\n"); } for (int tty = 1; tty <= video_tty_count; tty++) { pid = fork_and_run_shell_on_tty(tty); shell_pids[tty] = pid; if (tty == 1) { /* only the 1st shell gets executed with the specified arguments */ for (int i = 1; i < ARRAY_SIZE(shell_args); i++) shell_args[i] = NULL; } } if (!video_tty_count || SERIAL_CON_IN_VIDEO_MODE) { if (!stat("/dev/ttyS0", &statbuf)) { pid = fork_and_run_shell_on_tty(TTYS0_MINOR); shell_pids[TTYS0_MINOR] = pid; } } wait_for_children(0); if (opt_do_exit) { /* * This option is used by automated system tests run on QEMU. * In that context, init is expected to just exit after all of its * children died. That triggers a call to debug_qemu_turn_off_machine(), * instead of a regular kernel panic. */ exit(0); } wait_for_children(1000); printf("[init] Sync...\n"); sync(); printf("[init] Sending SIGKILL to all tasks...\n"); kill(-1, SIGKILL); wait_for_children(1000); if (reboot(reboot_cmd)) { /* Restart, halt or power-off failed */ exit(2); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/page_size.h> #include "defs.h" #include "utils.h" static multiboot_memory_map_t *multiboot_mmap; static UINT32 mmap_elems_count; static EFI_STATUS AllocateMbi(void) { EFI_STATUS status = EFI_SUCCESS; EFI_PHYSICAL_ADDRESS multiboot_buffer = EFI_MBI_MAX_ADDR; status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &multiboot_buffer); HANDLE_EFI_ERROR("AllocatePages"); BS->SetMem(TO_PTR(multiboot_buffer), 1 * PAGE_SIZE, 0); gMbi = TO_PTR(multiboot_buffer); end: return status; } static void MbiSetFramebufferInfo(void) { EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *mode_info = gProt->Mode->Info; UINTN fb_addr = gProt->Mode->FrameBufferBase; gMbi->flags |= MULTIBOOT_INFO_FRAMEBUFFER_INFO; gMbi->framebuffer_addr = fb_addr; gMbi->framebuffer_pitch = mode_info->PixelsPerScanLine * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL); gMbi->framebuffer_width = mode_info->HorizontalResolution, gMbi->framebuffer_height = mode_info->VerticalResolution, gMbi->framebuffer_bpp = sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL) * 8; gMbi->framebuffer_type = MULTIBOOT_FRAMEBUFFER_TYPE_RGB; if (mode_info->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) { gMbi->framebuffer_red_field_position = 16; gMbi->framebuffer_green_field_position = 8; gMbi->framebuffer_blue_field_position = 0; } else if (mode_info->PixelFormat == PixelRedGreenBlueReserved8BitPerColor) { gMbi->framebuffer_red_field_position = 0; gMbi->framebuffer_green_field_position = 8; gMbi->framebuffer_blue_field_position = 16; } gMbi->framebuffer_red_mask_size = 8; gMbi->framebuffer_green_mask_size = 8; gMbi->framebuffer_blue_mask_size = 8; } static UINT32 EfiToMultibootMemType(UINT32 type) { switch (type) { case EfiReservedMemoryType: case EfiRuntimeServicesCode: case EfiRuntimeServicesData: return MULTIBOOT_MEMORY_RESERVED; case EfiLoaderCode: case EfiLoaderData: case EfiBootServicesCode: case EfiBootServicesData: case EfiConventionalMemory: return MULTIBOOT_MEMORY_AVAILABLE; case EfiUnusableMemory: return MULTIBOOT_MEMORY_BADRAM; case EfiACPIReclaimMemory: return MULTIBOOT_MEMORY_ACPI_RECLAIMABLE; case EfiACPIMemoryNVS: return MULTIBOOT_MEMORY_NVS; case EfiMemoryMappedIO: case EfiMemoryMappedIOPortSpace: case EfiPalCode: return MULTIBOOT_MEMORY_RESERVED; default: /* Let's just be conservative */ return MULTIBOOT_MEMORY_BADRAM; } } static void AddMemoryRegion(UINT64 start, UINT64 end, UINT32 type) { gMbi->flags |= MULTIBOOT_INFO_MEMORY; if (type == MULTIBOOT_MEMORY_AVAILABLE) { if (start < gMbi->mem_lower * KB) gMbi->mem_lower = start / KB; if (end > gMbi->mem_upper * KB) gMbi->mem_upper = end / KB; } multiboot_mmap[mmap_elems_count++] = (multiboot_memory_map_t) { .size = sizeof(multiboot_memory_map_t) - sizeof(u32), .addr = (multiboot_uint64_t)start, .len = (multiboot_uint64_t)(end - start), .type = type, }; } EFI_STATUS MultibootSaveMemoryMap(UINTN *mapkey) { EFI_MEMORY_DESCRIPTOR *desc = NULL; EFI_STATUS status = EFI_SUCCESS; UINT32 last_type = (UINT32) -1; UINT64 last_start = 0; UINT64 last_end = 0; EFI_PHYSICAL_ADDRESS multiboot_mmap_paddr = EFI_MBI_MAX_ADDR; status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &multiboot_mmap_paddr); HANDLE_EFI_ERROR("AllocatePages"); BS->SetMem(TO_PTR(multiboot_mmap_paddr), 1 * PAGE_SIZE, 0); multiboot_mmap = TO_PTR(multiboot_mmap_paddr); status = GetMemoryMap(mapkey); HANDLE_EFI_ERROR("GetMemoryMap"); gMbi->flags |= MULTIBOOT_INFO_MEM_MAP; desc = (void *)gMmap; do { UINT32 type = EfiToMultibootMemType(desc->Type); UINT64 start = desc->PhysicalStart; UINT64 end = start + desc->NumberOfPages * PAGE_SIZE; if (last_type != type || last_end != start) { /* * The new region is not contiguous with the previous one OR it has * a different type. */ if (last_type != (UINT32)-1) { AddMemoryRegion(last_start, last_end, last_type); } last_type = type; last_start = start; } /* * last_type == type && last_end == start * * We're continuing a region of the same "multiboot type", just move the * end forward. */ last_end = end; desc = (void *)desc + gDesc_size; } while ((UINTN)desc < (UINTN)gMmap + gMmap_size); AddMemoryRegion(last_start, last_end, last_type); gMbi->mmap_addr = (UINTN)multiboot_mmap; gMbi->mmap_length = mmap_elems_count * sizeof(multiboot_memory_map_t); end: return status; } static EFI_STATUS MbiSetRamdisk(void) { EFI_STATUS status = EFI_SUCCESS; EFI_PHYSICAL_ADDRESS multiboot_mod_addr = EFI_MBI_MAX_ADDR; multiboot_module_t *mod; status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &multiboot_mod_addr); HANDLE_EFI_ERROR("AllocatePages"); BS->SetMem(TO_PTR(multiboot_mod_addr), 1 * PAGE_SIZE, 0); mod = TO_PTR(multiboot_mod_addr); mod->mod_start = gRamdiskPaddr; mod->mod_end = mod->mod_start + gRamdiskSize; gMbi->flags |= MULTIBOOT_INFO_MODS; gMbi->mods_addr = (UINTN)mod; gMbi->mods_count = 1; end: return status; } static EFI_STATUS MbiSetBootloaderName(void) { static char BootloaderName[] = "TILCK_EFI"; EFI_STATUS status = EFI_SUCCESS; EFI_PHYSICAL_ADDRESS paddr = EFI_MBI_MAX_ADDR; status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &paddr); HANDLE_EFI_ERROR("AllocatePages"); BS->CopyMem(TO_PTR(paddr), BootloaderName, sizeof(BootloaderName)); gMbi->boot_loader_name = (u32)paddr; gMbi->flags |= MULTIBOOT_INFO_BOOT_LOADER_NAME; end: return status; } static EFI_STATUS MbiSetPointerToAcpiTable(void) { static EFI_GUID gAcpi20Table = ACPI_20_TABLE_GUID; EFI_PHYSICAL_ADDRESS tablePaddr; void *table = NULL; for (UINTN i = 0; i < ST->NumberOfTableEntries; i++) { EFI_GUID *g = &ST->ConfigurationTable[i].VendorGuid; if (!CompareGuid(g, &gAcpi20Table)) { table = ST->ConfigurationTable[i].VendorTable; break; } } if (!table) { Print(L"ERROR: ACPI 2.0 configuration table not found\n"); return EFI_NOT_FOUND; } tablePaddr = (EFI_PHYSICAL_ADDRESS)(ulong)table; if (tablePaddr >= UINT32_MAX) { Print(L"Warning: ACPI 2.0 RDSP (0x%08x) out of 32-bit space\n", tablePaddr); return EFI_SUCCESS; } /* * HACK: we're setting ACPI 2.0's RDSP to the `apm_table` field in * multiboot's MBI struct. That's wrong to do (in general), but * unfortunately multiboot 1 does not support ACPI. Until we make at * least this EFI bootloader and the kernel to support multiboot 2.0, * this hack will be used. Note: the "hack" is not an unsafe or dirty * hack simply because: * * - We're booting ONLY the Tilck kernel * - We didn't set MULTIBOOT_INFO_APM_TABLE in gMbi->flags * - We set the gMbi->boot_load_name to "TILCK_EFI" which allows the * kernel to recognize this particular bootloader. * * Of course, if Tilck is booted by GRUB in EFI mode, it won't get this * precious pointer and it will have to resort searching the root pointer * with AcpiFindRootPointer() which is unreliable on UEFI systems. * As a result, ACPI might be unable to find its root pointer and the whole * ACPICA won't be usable. This limitation will be removed when Tilck gets * support for multiboot 2.0 as well. * * History notes * ----------------- * * Q: Why Tilck does not support multiboot 2.0 from the beginning? * * A: Because QEMU doesn't and it was so simply to just support only * multiboot 1.0 everywhere. Supporting only multiboot 2.0 was not an * option because would require always booting Tilck with its * bootloader under QEMU: that's slower for tests and limiting for * debugging purposes. */ gMbi->apm_table = (u32)tablePaddr; return EFI_SUCCESS; } static void MbiSetKernelCmdline(void) { if (gCmdlineBuf[0]) { gMbi->flags |= MULTIBOOT_INFO_CMDLINE; gMbi->cmdline = (u32)(ulong)gCmdlineBuf; } } EFI_STATUS SetupMultibootInfo(void) { EFI_STATUS status; status = AllocateMbi(); HANDLE_EFI_ERROR("AllocateMbi"); status = MbiSetRamdisk(); HANDLE_EFI_ERROR("MbiSetRamdisk"); status = MbiSetBootloaderName(); HANDLE_EFI_ERROR("MbiSetBootloaderName"); status = MbiSetPointerToAcpiTable(); HANDLE_EFI_ERROR("MbiSetPointerToAcpiTable"); MbiSetFramebufferInfo(); MbiSetKernelCmdline(); end: return status; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_console.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/term.h> #include <tilck/kernel/sched.h> #include <tilck/mods/console.h> #include <linux/major.h> // system header #include "tty_int.h" #define TTYS0_MINOR 64 STATIC_ASSERT(TTY_COUNT <= MAX_TTYS); struct tty *ttys[128]; struct tty *__curr_tty; static struct term_params first_term_i; static struct keypress_handler_elem tty_keypress_handler_elem = { .handler = &tty_keypress_handler }; STATIC_ASSERT(ARRAY_SIZE(ttys) > MAX_TTYS); static ssize_t tty_read(fs_handle h, char *buf, size_t size, offt *pos) { struct devfs_handle *dh = h; struct devfs_file *df = dh->file; struct tty *t = df->dev_minor ? ttys[df->dev_minor] : get_curr_tty(); ASSERT(*pos == 0); return tty_read_int(t, dh, buf, size); } static ssize_t tty_write(fs_handle h, char *buf, size_t size, offt *pos) { struct devfs_handle *dh = h; struct devfs_file *df = dh->file; struct tty *t = df->dev_minor ? ttys[df->dev_minor] : get_curr_tty(); ASSERT(*pos == 0); return tty_write_int(t, dh, buf, size); } static int tty_ioctl(fs_handle h, ulong request, void *argp) { struct devfs_handle *dh = h; struct devfs_file *df = dh->file; struct tty *t = df->dev_minor ? ttys[df->dev_minor] : get_curr_tty(); return tty_ioctl_int(t, dh, request, argp); } static struct kcond *tty_get_rready_cond(fs_handle h) { struct devfs_handle *dh = h; struct devfs_file *df = dh->file; struct tty *t = df->dev_minor ? ttys[df->dev_minor] : get_curr_tty(); return &t->input_cond; } static int tty_read_ready(fs_handle h) { struct devfs_handle *dh = h; struct devfs_file *df = dh->file; struct tty *t = df->dev_minor ? ttys[df->dev_minor] : get_curr_tty(); return tty_read_ready_int(t, dh); } int tty_create_extra(int minor, void *extra) { struct tty_handle_extra *eh = extra; eh->read_buf = kzmalloc(TTY_READ_BS); if (!eh->read_buf) return -ENOMEM; return 0; } int tty_on_dup_extra(int minor, void *extra) { struct tty_handle_extra *eh = extra; char *new_buf; ASSERT(eh->read_buf); if (!(new_buf = kmalloc(TTY_READ_BS))) return -ENOMEM; memcpy32(new_buf, eh->read_buf, TTY_READ_BS / 4); eh->read_buf = new_buf; return 0; } void tty_destroy_extra(int minor, void *extra) { struct tty_handle_extra *eh = extra; ASSERT(eh->read_buf); kfree2(eh->read_buf, TTY_READ_BS); } static int tty_create_device_file(int minor, enum vfs_entry_type *type, struct devfs_file_info *nfo) { static const struct file_ops static_ops_tty = { .read = tty_read, .write = tty_write, .ioctl = tty_ioctl, .get_rready_cond = tty_get_rready_cond, .read_ready = tty_read_ready, /* * IMPORTANT: remember to add any NEW ops func also to ttyaux's * ttyaux_create_device_file() function, in ttyaux.c. */ }; *type = VFS_CHAR_DEV; nfo->fops = &static_ops_tty; nfo->create_extra = &tty_create_extra; nfo->destroy_extra = &tty_destroy_extra; nfo->on_dup_extra = &tty_on_dup_extra; return 0; } static void init_tty_struct(struct tty *t, u16 minor, u16 serial_port_fwd) { t->minor = minor; t->serial_port_fwd = serial_port_fwd; t->kd_gfx_mode = KD_TEXT; t->curr_color = make_color(DEFAULT_FG_COLOR, DEFAULT_BG_COLOR); tty_reset_termios(t); if (MOD_console && !serial_port_fwd) reset_console_data(t); } int tty_get_num(struct tty *t) { return t->minor; } void tty_create_devfile_or_panic(const char *filename, u16 major, u16 minor, void **devfile) { int rc; if ((rc = create_dev_file(filename, major, minor, devfile)) < 0) panic("TTY: unable to create devfile /dev/%s (error: %d)", filename, rc); } static term * tty_allocate_and_init_new_video_term(int rows_buf) { const struct term_interface *intf = video_term_intf; term *new_term = intf->alloc(); if (!new_term) panic("TTY: no enough memory a new term instance"); if (intf->video_term_init(new_term, first_term_i.vi, first_term_i.rows, first_term_i.cols, rows_buf) < 0) { intf->free(new_term); return NULL; } return new_term; } static term * tty_allocate_and_init_new_serial_term(u16 serial_port_fwd) { const struct term_interface *intf = serial_term_intf; term *new_term = serial_term_intf->alloc(); if (!new_term) panic("TTY: no enough memory a new term instance"); if (intf->serial_term_init(new_term, serial_port_fwd) < 0) { intf->free(new_term); return NULL; } return new_term; } static void tty_full_destroy(struct tty *t) { if (t->tstate) { t->tintf->dispose(t->tstate); t->tintf->free(t->tstate); } if (MOD_console) { free_console_data(t->console_data); } kfree_array_obj(t->ctrl_handlers, tty_ctrl_sig_func, 256); kfree_obj(t->input_buf, TTY_INPUT_BS); kfree_obj(t, struct tty); } static struct tty * allocate_and_init_tty(u16 minor, u16 serial_port_fwd, int rows_buf) { struct tty *t; term *new_term = get_curr_term(); const struct term_interface *new_term_intf; if (!(t = kzalloc_obj(struct tty))) return NULL; if (!(t->input_buf = kzmalloc(TTY_INPUT_BS))) { tty_full_destroy(t); return NULL; } if (!(t->ctrl_handlers = kzalloc_array_obj(tty_ctrl_sig_func, 256))) { tty_full_destroy(t); return NULL; } if (MOD_console && !serial_port_fwd) { if (!(t->console_data = alloc_console_data())) { tty_full_destroy(t); return NULL; } } init_tty_struct(t, minor, serial_port_fwd); new_term_intf = serial_port_fwd ? serial_term_intf : video_term_intf; if (minor != 1 && !kopt_sercon) { new_term = serial_port_fwd ? tty_allocate_and_init_new_serial_term(serial_port_fwd) : tty_allocate_and_init_new_video_term(rows_buf); } if (!new_term) { kfree_obj(t, struct tty); return NULL; } t->tstate = new_term; t->tintf = new_term_intf; t->tintf->get_params(t->tstate, &t->tparams); tty_reset_filter_ctx(t); return t; } struct tty *create_tty_nodev(void) { struct tty *const t = allocate_and_init_tty(0, 0, 0); if (!t) return NULL; tty_input_init(t); tty_update_default_state_tables(t); return t; } static int internal_init_tty(u16 major, u16 minor, u16 serial_port_fwd) { ASSERT(minor < ARRAY_SIZE(ttys)); ASSERT(!ttys[minor]); struct tty *const t = allocate_and_init_tty(minor, serial_port_fwd, -1); if (!t) return -ENOMEM; snprintk(t->dev_filename, sizeof(t->dev_filename), serial_port_fwd ? "ttyS%d" : "tty%d", serial_port_fwd ? minor - TTYS0_MINOR : minor); if (create_dev_file(t->dev_filename, major, minor, &t->devfile) < 0) { tty_full_destroy(t); return -ENOMEM; } tty_input_init(t); tty_update_default_state_tables(t); ttys[minor] = t; return 0; } static void init_video_ttys(void) { for (u16 i = 1; i <= kopt_ttys; i++) { if (internal_init_tty(TTY_MAJOR, i, 0) < 0) { if (i <= 1) panic("No enough memory for any TTY device"); printk("WARNING: no enough memory for creating /dev/tty%d\n", i); kopt_ttys = i - 1; break; } } } static void init_serial_ttys(void) { /* NOTE: hw-specific stuff in generic code. TODO: fix that. */ static const u16 com_ports[4] = {COM1, COM2, COM3, COM4}; for (u16 i = 0; i < 4; i++) { if (internal_init_tty(TTY_MAJOR, i + TTYS0_MINOR, com_ports[i]) < 0) { printk("WARNING: no enough memory for creating /dev/ttyS%d\n", i); break; } } } struct tty *get_serial_tty(int n) { ASSERT(IN_RANGE(n, 0, 4)); return ttys[TTYS0_MINOR + n]; } ssize_t tty_write_int(struct tty *t, struct devfs_handle *h, const char *buf, size_t size) { size = MIN(size, MAX_TERM_WRITE_LEN); t->tintf->write(t->tstate, buf, size, t->curr_color); return (ssize_t) size; } ssize_t tty_curr_proc_write(const char *buf, size_t size) { return tty_write_int(get_curr_process_tty(), NULL, buf, size); } void tty_write_on_all_ttys(const char *buf, size_t size) { for (u32 i = 0; i < ARRAY_SIZE(ttys); i++) { if (ttys[i]) tty_write_int(ttys[i], NULL, buf, size); } } static void init_tty(void) { process_term_read_info(&first_term_i); struct driver_info *di = kzalloc_obj(struct driver_info); if (!di) panic("TTY: no enough memory for struct driver_info"); di->name = "tty"; di->create_dev_file = tty_create_device_file; register_driver(di, TTY_MAJOR); /* * tty0 is special: not a real tty but a special file always pointing * to the current tty. Therefore, just create the dev file. */ tty_create_devfile_or_panic("tty0", di->major, 0, NULL); if (!kopt_sercon) if (video_term_intf) init_video_ttys(); if (serial_term_intf) init_serial_ttys(); /* Make init's process group to be the fg process group for the first tty */ ttys[kopt_sercon ? TTYS0_MINOR : 1]->fg_pgid = 1; disable_preemption(); { if (!kopt_sercon) register_keypress_handler(&tty_keypress_handler_elem); } enable_preemption(); init_ttyaux(); __curr_tty = ttys[kopt_sercon ? TTYS0_MINOR : 1]; process_set_tty(kernel_process_pi, get_curr_tty()); } static struct module tty_module = { .name = "tty", .priority = MOD_tty_prio, .init = &init_tty, }; REGISTER_MODULE(&tty_module); /* No console funcs */ #if !MOD_console && !defined(KERNEL_TEST) void tty_update_default_state_tables(struct tty *t) { /* do nothing */ } void tty_reset_filter_ctx(struct tty *t) { /* do nothing */ } #endif <file_sep>List of supported Linux syscalls --------------------------------- `Tilck` supports both the `int 0x80` syscall interface and the `sysenter` one. Here below there is an up-to-date table containing the status of each supported syscall at the moment. Because the list of the not-yet-supported syscalls is much longer than the list of supported ones, the table below mentions only the syscalls having some degree of support. The missing syscalls have to be considered as *not implemented yet*. Syscall | Support level ----------------------------|------------------------- sys_exit | full sys_fork | full sys_read | full sys_write | full sys_open | partial++ [1] sys_close | full sys_waitpid | full sys_execve | full sys_chdir | full sys_getpid | full sys_setuid16 | limited [3] sys_getuid16 | limited [3] sys_pause | minimal [2] sys_access | partial sys_brk | full sys_setgid16 | limited [3] sys_getgid16 | limited [3] sys_seteuid16 | limited [3] sys_setegid16 | limited [3] sys_geteuid16 | limited [3] sys_getegid16 | limited [3] sys_ioctl | partial sys_getppid | full sys_gettimeofday | full sys_munmap | full sys_wait4 | full sys_newuname | full sys_llseek | full sys_readv | full sys_writev | full sys_nanosleep_time32 | full sys_prctl | stub sys_getcwd | full sys_mmap_pgoff | full sys_stat64 | full sys_fstat64 | full sys_lstat64 | partial sys_getuid | limited [3] sys_getgid | limited [3] sys_geteuid | limited [3] sys_getegid | limited [3] sys_setuid | limited [3] sys_setgid | limited [3] sys_getdents64 | full sys_fcntl64 | partial sys_gettid | minimal [4] sys_set_thread_area | full sys_exit_group | minimal [5] sys_set_tid_address | stub sys_tkill | partial++ [6] sys_tgkill | partial++ [6] sys_kill | full sys_setsid | full sys_times | minimal [9] sys_clock_gettime | compliant [10] sys_clock_gettime32 | compliant [10] sys_clock_getres | compliant [10] sys_clock_getres_time32 | compliant [10] sys_select | full sys_poll | full sys_readlink | full sys_creat | full sys_unlink | full sys_symlink | full sys_pread64 | full sys_pwrite64 | full sys_vfork | compliant [11] sys_umask | full sys_ia32_truncate64 | full sys_ia32_ftruncate64 | full sys_sync | full sys_syncfs | full sys_chown | limited [3] sys_fchown | limited [3] sys_lchown | limited [3] sys_chmod | full sys_fchmod | full sys_rename | full sys_link | full sys_pipe | full sys_pipe2 | partial++ [13] sys_sched_yield | full sys_getsid | full sys_setpgid | full sys_getpgid | full sys_getpgrp | full sys_utime32 | full sys_utimes | full sys_fsync | compliant sys_fdatasync | compliant sys_dup | full sys_dup2 | full sys_reboot | full sys_rt_sigprocmask | full sys_rt_sigpending | full sys_rt_sigreturn | partial [14] sys_rt_sigaction | partial [14] sys_rt_sigsuspend | partial [14] Definitions: Support level | Meaning ---------------|--------------------------- full | Syscall 100% supported. partial | Syscall partially supported, work-in-progress partial++ | All of the really important flags and modes are supported ... | Most of the advanced stuff very likely is still not supported. stub | The syscall does not return -ENOSYS, but it has actually a stub ... | implementation, at the moment. minimal | Like partial, just even less features are supported compliant | Syscall supported in a way compliant with a full ... | implementation, but actually it has several limitations due to ... | the different design of Tilck. Example: see the note [3]. limited | The syscall supports by design only a subset of the cases ... | supported by the Linux implementation. Notes: 1. The syscall open() now supports read/write access, file creation, mode setting and flags like O_APPEND, O_CLOEXEC, O_EXCL, O_TRUNC. All the "advanced" flags like O_ASYNC are not supported yet. 2. Because custom signal handlers are not supported, pause() puts the process to sleep until a signal actually kills it. 3. Tilck does not support *by design* multiple users nor any form of authentication. Therefore, the following statement is always true: UID == GID == EUID == EGID == 0. All the calls like setuid(), seteuid(), setgid(), setegid(), chown() etc. succeed only when UID/GID == 0. 4. Because the lack of thread support, `gettid()` is the same as `getpid()` 5. Because the lack of thread support, exit_group() behaves as exit() 6. Because the lack of thread support, `tgkill()` works only when `tgid` == `tid`. 7. [Limitation removed] 8. [Limitation removed] 9. At the moment `times()` just updates `tms_utime` and `tms_stime`. 10. Only the clocks CLOCK_REALTIME and CLOCK_MONOTONIC are supported. 11. Behaves exactly as `fork()`. 12. [Limitation removed] 13. The O_DIRECT mode is not supported. 14. Tilck has a partial support for POSIX signals. SIG_IGN and SIG_DFL are fully supported. Custom signal handlers are supported as well, but signal handlers (even of different type) cannot interrupt each other. In other words, nested custom signal handlers are not supported, yet. Also, even if the modern sys_rt_sigaction() interface is implemented, none of its flags like SA_NODEFER, SA_ONSTACK, SA_RESETHAND, SA_RESTART, SA_SIGINFO are supported, at the moment. The per-signal sa_mask is also fixed: while a custom handler is running, all the other signals having a custom handler are masked (terminating signals instead, can always we delieved). In addition, the order of delivery of all signals is unspecified and there is no distinction between regular signals and real-time ones. Also, at the moment, no syscall can be restarted if a signal interrupted it. The syscall sys_rt_sigsuspend() works as expected if we're not calling it from a signal handler otherwise, it returns -EPERM (not allowed according to POSIX). NOTE: while the just-described limited support for POSIX reliable signals might seem too limited, it's worth noting that it already opened a considerable amount of uses, like graceful process termination with SIGTERM. <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause TFBLIB_VER="latest" all_funcs_list+=(build_tfblib) function build_tfblib { if [ ! -d noarch/tfblib ]; then pushd noarch show_work_on_component_msg "TFBLIB" git clone https://github.com/vvaltchev/tfblib ln -s $TC/noarch/tfblib "$MAIN_DIR/userapps/extra" popd else show_skip_component_msg "TFBLIB" fi } function build_tfblib_installed_status { if [ -d $TC/noarch/tfblib ]; then echo "installed noarch" fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/atomics.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/datetime.h> FASTCALL void asm_nop_loop(u32 iters); /* Jiffies */ static u64 __ticks; /* ticks since the timer started */ /* System time */ u64 __time_ns; /* nanoseconds since the timer started */ u32 __tick_duration; /* the real duration of a tick, ~TS_SCALE/TIMER_HZ */ int __tick_adj_val; int __tick_adj_ticks_rem; /* Debug counters */ u32 slow_timer_irq_handler_count; /* Temporary global used by asm_do_bogomips_loop() */ volatile ATOMIC(u32) __bogo_loops; /* Static variables */ static struct list timer_wakeup_list = STATIC_LIST_INIT(timer_wakeup_list); static u32 loops_per_tick; /* Tilck bogoMips as loops/tick */ static u32 loops_per_ms = 5000000; /* loops/millisecond (initial val) */ static u32 loops_per_us = 5000; /* loops/microsecond (initial val) */ u64 get_ticks(void) { u64 curr_ticks; ulong var; disable_interrupts(&var); { curr_ticks = __ticks; } enable_interrupts(&var); return curr_ticks; } void task_set_wakeup_timer(struct task *ti, u32 ticks) { ulong var; ASSERT(ticks > 0); disable_interrupts(&var); { if (ti->ticks_before_wake_up == 0) { ASSERT(!list_is_node_in_list(&ti->wakeup_timer_node)); list_add_tail(&timer_wakeup_list, &ti->wakeup_timer_node); } else { ASSERT(list_is_node_in_list(&ti->wakeup_timer_node)); } ti->ticks_before_wake_up = ticks; } enable_interrupts(&var); } void task_update_wakeup_timer_if_any(struct task *ti, u32 new_ticks) { ulong var; ASSERT(new_ticks > 0); disable_interrupts(&var); { if (ti->ticks_before_wake_up > 0) { ASSERT(list_is_node_in_list(&ti->wakeup_timer_node)); ti->ticks_before_wake_up = new_ticks; } } enable_interrupts(&var); } u32 task_cancel_wakeup_timer(struct task *ti) { ulong var; u32 old; disable_interrupts(&var); { old = ti->ticks_before_wake_up; if (old > 0) { ti->timer_ready = false; ti->ticks_before_wake_up = 0; list_remove(&ti->wakeup_timer_node); } } enable_interrupts(&var); return old; } static void tick_all_timers(void) { struct task *pos, *temp; bool any_woken_up_task = false; ulong var; /* * This is *NOT* the best we can do. In particular, it's terrible to keep * the interrupts disabled while iterating the _whole_ timer_wakeup_list. * * Possible better solutions * ----------------------------- * 1. Keep the tasks to wake-up in a sort of ordered list and then use * relative timers. This way, at each tick we'll have to decrement just one * single counter. We'll start decrement the next counter only when the first * counter reaches 0 and its list node is removed. Of course, if we cannot * use kmalloc() in case of sleep, it gets much harder to create such an * ordered list and make it live inside a member of struct task. Maybe a BST * will do the job, but that would require paying O(logN) per tick for * finding the earliest timer. Not sure how better would be now for N < 50 * (typical), given the huge added constant for the BST functions. Also, the * cancellation of a timer would require some extra effort in order to * re-calculate the relative timer values, while we want the cancellation to * be light-fast because it's run by IRQ handlers. * * 2. Use a fixed number of wakeup lists like: short-term, mid-term and * long-term. Current task's wakeup list node will be placed in one those * lists, depending on far in the future the task is supposted to be woke up. * On every tick, here in tick_all_timers(), ONLY the short-term list will be * iterated. That's a considerable improvement. In a system, there might be * even 1,000 active timers, but how many of them will expire in the next * second? Only a small percentage of them. To further improve the * scalability, it's possible to have even more than 3 lists, or to further * reduce the time-horizon of the short-term list. Periodically, but NOT on * every tick, the `ticks_before_wake_up` field belonging to tasks in the * other wakeup lists will adjusted with bigger decrements and tasks will be * moved from one list to another. That will also happen in case the wakeup * timer is changed for task with an already active timer. This solution * looks much better than solution 1. * * Conclusion * --------------------- * For the moment, given the very limited scale of Tilck (tens of tasks at * most running on the whole system), the current solution is safe and * good-enough but, at some point, a smarter ad-hoc solution should be * devised. Probably solution 2 is the right candidate. */ disable_interrupts(&var); list_for_each(pos, temp, &timer_wakeup_list, wakeup_timer_node) { /* If task is part of this list, it's counter must be > 0 */ ASSERT(pos->ticks_before_wake_up > 0); if (UNLIKELY(--pos->ticks_before_wake_up == 0)) { pos->timer_ready = true; list_remove(&pos->wakeup_timer_node); if (pos->state == TASK_STATE_SLEEPING) { task_change_state(pos, TASK_STATE_RUNNABLE); any_woken_up_task = true; } } } enable_interrupts(&var); if (any_woken_up_task) sched_set_need_resched(); } static void do_sleep_internal(u32 ticks) { ASSERT(are_interrupts_enabled()); disable_preemption(); task_change_state(get_curr_task(), TASK_STATE_SLEEPING); task_set_wakeup_timer(get_curr_task(), ticks); kernel_yield_preempt_disabled(); } void kernel_sleep(u64 ticks) { if (in_panic()) { /* * Typically, we don't sleep in panic of course but, if the kopt_panic_kb * is enabled we'll run a mini interactive debugger, which might run the * debug panel itself, which calls kernel_sleep(). Because don't really * have a scheduler nor a timer anymore, just fake it by returning * immediately. All the code after panic(), run under special conditions * where every hack is allowed :-) */ return; } DEBUG_ONLY(check_not_in_irq_handler()); /* * Implementation: why * --------------------- * * In theory, the function could be implemented just as: * * if (ticks) { * task_set_wakeup_timer(get_curr_task(), ticks); * task_change_state(get_curr_task(), TASK_STATE_SLEEPING); * } * kernel_yield(); * * But that would require task->ticks_before_wake_up to be actually 64-bit, * wide and that's bad on 32-bit systems because: * * - it would require using the soft 64-bit integers (slow) * - it would make impossible, in the case we wanted that, the counter * to be atomic. * * Therefore, in order to use a 32-bit value for 'ticks_before_wake_up' and, * at the same time being able to sleep for more than 2^32-1 ticks, we need * a more tricky implementation (below), and the little extra runtime price * for it is totally fine, since we're going to sleep anyways! * * Implementation: how * ---------------------- * * The simpler way to explain the algorithm is to just assume everything * is in base 10 and that ticks_before_wake_up has 2 digits, while we want * to support 4 digits sleep time. For example, we want to sleep for 234 * ticks. The algorithm first computes 534 % 100 = 34 and then 534 / 100 = 5. * After that, it sleeps q (= 5) times for 99 ticks (max allowed). Clearly, * we missed 5 ticks (5 * 99 < 500) this way, but we'll going to fix that * buy just sleeping 'q' ticks. Thus, by now, we've slept for 500 ticks. * Now we have to sleep for 34 ticks more are we're done. * * The same logic applies to base-2 case with 32-bit and 64-bit integers, * just the numbers are much bigger. The remainder can be computed using * a bitmask, while the division by using just a right shift. */ const u32 rem = ticks & 0xffffffff; const u32 q = ticks >> 32; if (q) { for (u32 i = 0; i < q; i++) { do_sleep_internal(0xffffffff); if (pending_signals()) return; } do_sleep_internal(q); if (pending_signals()) return; } if (rem) { do_sleep_internal(rem); } if (!q && !rem) kernel_yield(); } void kernel_sleep_ms(u64 ms) { kernel_sleep(MAX(1u, ms_to_ticks(ms))); } static ALWAYS_INLINE bool timer_nested_irq(void) { bool res = false; if (KRN_TRACK_NESTED_INTERR) { ulong var; disable_interrupts(&var); if (in_nested_irq_num(X86_PC_TIMER_IRQ)) { slow_timer_irq_handler_count++; res = true; } enable_interrupts(&var); } return res; } static enum irq_action timer_irq_handler(void *ctx) { u32 ns_delta; ASSERT(are_interrupts_enabled()); if (KRN_TRACK_NESTED_INTERR) if (timer_nested_irq()) return IRQ_HANDLED; /* * Compute `ns_delta` by reading `__tick_duration` and `__tick_adj_val` here * without disabling interrupts, because it's safe to do so. Also, decrement * `__tick_adj_ticks_rem` too. Why it's safe: * * 1. `__tick_duration` is immutable * 2. `__tick_adj_val` is changed only by datetime.c while keeping * interrupts disabled and it's read only here. Nested timer IRQs * will be ignored (see above). No other IRQ handler should read it. */ if (__tick_adj_ticks_rem) { ns_delta = (u32)((s32)__tick_duration + __tick_adj_val); __tick_adj_ticks_rem--; } else { ns_delta = __tick_duration; } disable_interrupts_forced(); { /* * Alter __ticks and __time_ns here, while keeping the interrupts disabled * because other IRQ handlers might need to use them. While, as explained * above, `__tick_adj_val` and `__tick_adj_ticks_rem` will never need to * be read or written by IRQ handlers. */ __ticks++; __time_ns += ns_delta; } enable_interrupts_forced(); sched_account_ticks(); tick_all_timers(); return IRQ_HANDLED; } static enum irq_action measure_bogomips_irq_handler(void *ctx); DEFINE_IRQ_HANDLER_NODE(timer, timer_irq_handler, NULL); DEFINE_IRQ_HANDLER_NODE(measure_bogomips, measure_bogomips_irq_handler, NULL); struct bogo_measure_ctx { bool started; bool pass_start; u32 ticks; }; static enum irq_action measure_bogomips_irq_handler(void *arg) { struct bogo_measure_ctx *ctx = arg; if (!ctx->started) return IRQ_NOT_HANDLED; if (UNLIKELY(!ctx->pass_start)) { /* * First IRQ: reset the loops value. * * Reason: the asm_do_bogomips_loop() has been spinning already when we * received this IRQ, but we cannot be sure that it started spinning * immediately after a tick. In order to increase the precision, just * discard the loops so far in this partial tick and start counting zero * from now, when the timer IRQ just arrived. */ __bogo_loops = 0; ctx->pass_start = true; return IRQ_NOT_HANDLED; } /* Successive IRQs */ if (++ctx->ticks == MEASURE_BOGOMIPS_TICKS) { /* We're done */ irq_uninstall_handler(X86_PC_TIMER_IRQ, &measure_bogomips); disable_interrupts_forced(); { loops_per_tick = __bogo_loops * BOGOMIPS_CONST/MEASURE_BOGOMIPS_TICKS; loops_per_ms = loops_per_tick / (1000 / TIMER_HZ); loops_per_us = loops_per_ms / 1000; __bogo_loops = -1; } enable_interrupts_forced(); } return IRQ_NOT_HANDLED; /* always allow the real IRQ handler to go */ } static void do_bogomips_loop(void *arg) { void asm_do_bogomips_loop(void); struct bogo_measure_ctx *ctx = arg; ASSERT(is_preemption_enabled()); disable_preemption(); { ctx->started = true; asm_do_bogomips_loop(); } enable_preemption(); printk("Tilck bogoMips: %u.%03u\n", loops_per_us, loops_per_ms % 1000); } void delay_us(u32 us) { u32 loops; ASSERT(us <= 100 * 1000); if (LIKELY(loops_per_us >= 10)) loops = us * loops_per_us; else loops = (us * loops_per_ms) / 1000; if (LIKELY(loops > 0)) asm_nop_loop(loops); } void init_timer(void) { static struct bogo_measure_ctx ctx; measure_bogomips.context = &ctx; __tick_duration = hw_timer_setup(TS_SCALE / TIMER_HZ); printk("*** Init the kernel timer\n"); if (!wth_enqueue_anywhere(WTH_PRIO_HIGHEST, &do_bogomips_loop, &ctx)) panic("Timer: unable to enqueue job in wth 0"); irq_install_handler(X86_PC_TIMER_IRQ, &measure_bogomips); irq_install_handler(X86_PC_TIMER_IRQ, &timer); } <file_sep> How to measure the code coverage ---------------------------------- ## Prerequisites * Some experience with the scripts `cmake_run` and `build_toolchain`. Read [building](building.md) first. * A clean build directory * The following extra components in the toolchain: - lcov - gtest - vim (advanced case only) - tcc (advanced case only) ## Typical case By following the steps below, you'll measure Tilck's cumulative test coverage for the unit tests, for the kernel self-tests and the system tests as well. That's what is needed most of the time. For the full coverage, the interactive tests need to be run as well. They have more prerequisites (see above) and require a special build configuration as well (see below). 1. Setup the build configuration by running: TEST_GCOV=1 KERNEL_GCOV=1 <TILCK>/scripts/cmake_run 2. Build Tilck and its unit tests: make && make gtests 3. Clean coverage data from previous runs: <BUILD_DIR>/scripts/generate_test_coverage_report --clean 4. Run the unit tests: <BUILD_DIR>/gtests At this point, there should be plenty of `.gcda` files in the build directory. Check that with: `find <BUILD_DIR> -name '*.gcda'` 5. Generate the first coverage report with: <BUILD_DIR>/scripts/generate_test_coverage_report --acc At this point, there should be a `coverage.info` file in the build directory, but we're not done yet. We have only coverage for the **unit tests**. 6. In order to get coverage info for the **kernel self-tests** and the **system tests**, we need to run also: DUMP_COV=1 REPORT_COV=1 <BUILD_DIR>/st/run_all_tests -c 7. At this point, our `coverage.info` file will contain the merged coverage data from both the unit tests run and all the other tests (where kernel coverage was involved as well). Therefore, we can finally generate our HTML report this way: <BUILD_DIR>/scripts/generate_test_coverage_report --gen Open `<BUILD_DIR>/coverage_html/index.html` in your browser. ## Advanced case In order to get the *full* test coverage, it is necessary to run also Tilck's interactive tests as well. (The *interactive* tests simulate real user input (keystrokes on a virtual PS/2 keyboard) and check Tilck's fb console's output by parsing screenshots.) To run them and get the full test coverage it's necessary to: * Check that you have the [pySerial] python-3 module installed on the system * Check that you have [ImageMagick] installed on the system * Replace the **step 1** above with: TEST_GCOV=1 KERNEL_GCOV=1 <TILCK>/scripts/cmake_run --intr * Run the following command **between step 6 and step 7**: DUMP_COV=1 REPORT_COV=1 <BUILD_DIR>/st/run_interactive_test -a The rest of the steps are the same. We just changed build's configuration and run another test before generating the html report. [pySerial]: https://pyserial.readthedocs.io/en/latest/pyserial.html [ImageMagick]: https://imagemagick.org/ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/datetime.h> void hw_read_clock(struct datetime *out) { memset(out, 0, sizeof(*out)); } bool hi_vmem_avail(void) { return false; } int kthread_create2() { return -12; /* ENOMEM */} void invalidate_page() {} void init_serial_port() { } void serial_write() { } void handle_fault() { } void handle_syscall() { } void arch_irq_handling() { } void pic_send_eoi() { } void task_info_reset_kernel_stack() { } void set_kernel_stack() { } void irq_clear_mask() { } void debug_qemu_turn_off_machine() { } void setup_process() { } void gdt_install() { } void idt_install() { } void irq_install() { } void hw_timer_setup() { } void irq_install_handler() { } void irq_uninstall_handler() { } void setup_sysenter_interface() { } void save_current_task_state() { } void switch_to_task() { } void pdir_clone() { } void pdir_deep_clone() { } void pdir_destroy() { } void set_curr_pdir() { } void set_current_task_in_user_mode() { } void arch_specific_new_task_setup() { NOT_REACHED(); } void arch_specific_free_task() { NOT_REACHED(); } void arch_specific_new_proc_setup() { NOT_REACHED(); } void arch_specific_free_proc() { NOT_REACHED(); } void fpu_context_begin() { } void fpu_context_end() { } void map_zero_pages() { NOT_REACHED(); } void dump_var_mtrrs() { } void set_page_rw() { } void poweroff() { NOT_REACHED(); } int get_irq_num(void *ctx) { return -1; } int get_int_num(void *ctx) { return -1; } void retain_pageframes_mapped_at() { } void release_pageframes_mapped_at() { } bool irq_is_masked() { NOT_REACHED(); return false; } void *hi_vmem_reserve(size_t size) { return NULL; } void hi_vmem_release(void *ptr, size_t size) { } void on_first_pdir_update(void) { } void *get_syscall_func_ptr(u32 n) { return NULL; } int get_syscall_num(void *func) { return -1; } void arch_add_initial_mem_regions() { } bool arch_add_final_mem_regions() { return false; } void setup_sig_handler() { NOT_REACHED(); } void setup_pause_trampoline() { NOT_REACHED(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void insertion_sort_ptr(void *arr, u32 elem_count, cmpfun_ptr cmp); void insertion_sort_generic(void *a, ulong elem_sz, u32 elem_count, cmpfun_ptr cmp); void array_reverse_ptr(void *a, u32 elem_count); <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) include_directories(${CMAKE_SOURCE_DIR}/include) include_directories(${CMAKE_SOURCE_DIR}/include/system_headers) add_subdirectory(arch) <file_sep>/****************************************************************************** * * Module Name: utalloc - local memory allocation routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdebug.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utalloc") #if !defined (USE_NATIVE_ALLOCATE_ZEROED) /******************************************************************************* * * FUNCTION: AcpiOsAllocateZeroed * * PARAMETERS: Size - Size of the allocation * * RETURN: Address of the allocated memory on success, NULL on failure. * * DESCRIPTION: Subsystem equivalent of calloc. Allocate and zero memory. * This is the default implementation. Can be overridden via the * USE_NATIVE_ALLOCATE_ZEROED flag. * ******************************************************************************/ void * AcpiOsAllocateZeroed ( ACPI_SIZE Size) { void *Allocation; ACPI_FUNCTION_ENTRY (); Allocation = AcpiOsAllocate (Size); if (Allocation) { /* Clear the memory block */ memset (Allocation, 0, Size); } return (Allocation); } #endif /* !USE_NATIVE_ALLOCATE_ZEROED */ /******************************************************************************* * * FUNCTION: AcpiUtCreateCaches * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Create all local caches * ******************************************************************************/ ACPI_STATUS AcpiUtCreateCaches ( void) { ACPI_STATUS Status; /* Object Caches, for frequently used objects */ Status = AcpiOsCreateCache ("Acpi-Namespace", sizeof (ACPI_NAMESPACE_NODE), ACPI_MAX_NAMESPACE_CACHE_DEPTH, &AcpiGbl_NamespaceCache); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiOsCreateCache ("Acpi-State", sizeof (ACPI_GENERIC_STATE), ACPI_MAX_STATE_CACHE_DEPTH, &AcpiGbl_StateCache); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiOsCreateCache ("Acpi-Parse", sizeof (ACPI_PARSE_OBJ_COMMON), ACPI_MAX_PARSE_CACHE_DEPTH, &AcpiGbl_PsNodeCache); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiOsCreateCache ("Acpi-ParseExt", sizeof (ACPI_PARSE_OBJ_NAMED), ACPI_MAX_EXTPARSE_CACHE_DEPTH, &AcpiGbl_PsNodeExtCache); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiOsCreateCache ("Acpi-Operand", sizeof (ACPI_OPERAND_OBJECT), ACPI_MAX_OBJECT_CACHE_DEPTH, &AcpiGbl_OperandCache); if (ACPI_FAILURE (Status)) { return (Status); } #ifdef ACPI_ASL_COMPILER /* * For use with the ASL-/ASL+ option. This cache keeps track of regular * 0xA9 0x01 comments. */ Status = AcpiOsCreateCache ("Acpi-Comment", sizeof (ACPI_COMMENT_NODE), ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_RegCommentCache); if (ACPI_FAILURE (Status)) { return (Status); } /* * This cache keeps track of the starting addresses of where the comments * lie. This helps prevent duplication of comments. */ Status = AcpiOsCreateCache ("Acpi-Comment-Addr", sizeof (ACPI_COMMENT_ADDR_NODE), ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_CommentAddrCache); if (ACPI_FAILURE (Status)) { return (Status); } /* * This cache will be used for nodes that represent files. */ Status = AcpiOsCreateCache ("Acpi-File", sizeof (ACPI_FILE_NODE), ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_FileCache); if (ACPI_FAILURE (Status)) { return (Status); } #endif #ifdef ACPI_DBG_TRACK_ALLOCATIONS /* Memory allocation lists */ Status = AcpiUtCreateList ("Acpi-Global", 0, &AcpiGbl_GlobalList); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiUtCreateList ("Acpi-Namespace", sizeof (ACPI_NAMESPACE_NODE), &AcpiGbl_NsNodeList); if (ACPI_FAILURE (Status)) { return (Status); } #endif return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtDeleteCaches * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Purge and delete all local caches * ******************************************************************************/ ACPI_STATUS AcpiUtDeleteCaches ( void) { #ifdef ACPI_DBG_TRACK_ALLOCATIONS char Buffer[7]; if (AcpiGbl_DisplayFinalMemStats) { strcpy (Buffer, "MEMORY"); (void) AcpiDbDisplayStatistics (Buffer); } #endif (void) AcpiOsDeleteCache (AcpiGbl_NamespaceCache); AcpiGbl_NamespaceCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_StateCache); AcpiGbl_StateCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_OperandCache); AcpiGbl_OperandCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_PsNodeCache); AcpiGbl_PsNodeCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_PsNodeExtCache); AcpiGbl_PsNodeExtCache = NULL; #ifdef ACPI_ASL_COMPILER (void) AcpiOsDeleteCache (AcpiGbl_RegCommentCache); AcpiGbl_RegCommentCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_CommentAddrCache); AcpiGbl_CommentAddrCache = NULL; (void) AcpiOsDeleteCache (AcpiGbl_FileCache); AcpiGbl_FileCache = NULL; #endif #ifdef ACPI_DBG_TRACK_ALLOCATIONS /* Debug only - display leftover memory allocation, if any */ AcpiUtDumpAllocations (ACPI_UINT32_MAX, NULL); /* Free memory lists */ AcpiOsFree (AcpiGbl_GlobalList); AcpiGbl_GlobalList = NULL; AcpiOsFree (AcpiGbl_NsNodeList); AcpiGbl_NsNodeList = NULL; #endif return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtValidateBuffer * * PARAMETERS: Buffer - Buffer descriptor to be validated * * RETURN: Status * * DESCRIPTION: Perform parameter validation checks on an ACPI_BUFFER * ******************************************************************************/ ACPI_STATUS AcpiUtValidateBuffer ( ACPI_BUFFER *Buffer) { /* Obviously, the structure pointer must be valid */ if (!Buffer) { return (AE_BAD_PARAMETER); } /* Special semantics for the length */ if ((Buffer->Length == ACPI_NO_BUFFER) || (Buffer->Length == ACPI_ALLOCATE_BUFFER) || (Buffer->Length == ACPI_ALLOCATE_LOCAL_BUFFER)) { return (AE_OK); } /* Length is valid, the buffer pointer must be also */ if (!Buffer->Pointer) { return (AE_BAD_PARAMETER); } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtInitializeBuffer * * PARAMETERS: Buffer - Buffer to be validated * RequiredLength - Length needed * * RETURN: Status * * DESCRIPTION: Validate that the buffer is of the required length or * allocate a new buffer. Returned buffer is always zeroed. * ******************************************************************************/ ACPI_STATUS AcpiUtInitializeBuffer ( ACPI_BUFFER *Buffer, ACPI_SIZE RequiredLength) { ACPI_SIZE InputBufferLength; /* Parameter validation */ if (!Buffer || !RequiredLength) { return (AE_BAD_PARAMETER); } /* * Buffer->Length is used as both an input and output parameter. Get the * input actual length and set the output required buffer length. */ InputBufferLength = Buffer->Length; Buffer->Length = RequiredLength; /* * The input buffer length contains the actual buffer length, or the type * of buffer to be allocated by this routine. */ switch (InputBufferLength) { case ACPI_NO_BUFFER: /* Return the exception (and the required buffer length) */ return (AE_BUFFER_OVERFLOW); case ACPI_ALLOCATE_BUFFER: /* * Allocate a new buffer. We directectly call AcpiOsAllocate here to * purposefully bypass the (optionally enabled) internal allocation * tracking mechanism since we only want to track internal * allocations. Note: The caller should use AcpiOsFree to free this * buffer created via ACPI_ALLOCATE_BUFFER. */ Buffer->Pointer = AcpiOsAllocate (RequiredLength); break; case ACPI_ALLOCATE_LOCAL_BUFFER: /* Allocate a new buffer with local interface to allow tracking */ Buffer->Pointer = ACPI_ALLOCATE (RequiredLength); break; default: /* Existing buffer: Validate the size of the buffer */ if (InputBufferLength < RequiredLength) { return (AE_BUFFER_OVERFLOW); } break; } /* Validate allocation from above or input buffer pointer */ if (!Buffer->Pointer) { return (AE_NO_MEMORY); } /* Have a valid buffer, clear it */ memset (Buffer->Pointer, 0, RequiredLength); return (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included /* * The only purpose of this file is to keep kmalloc.c shorter. * Yes, this file could be turned into a regular C source file, but at the * price of making several static functions and variables in kmalloc.c to be * just non-static. We don't want that. Code isolation is a GOOD thing. */ #endif static void * main_heaps_kmalloc(size_t *size, u32 flags) { ASSERT(kmalloc_initialized); // Iterate in reverse-order because the first heaps are the biggest ones. for (int i = used_heaps - 1; i >= 0; i--) { ASSERT(heaps[i] != NULL); void *vaddr; const size_t heap_size = heaps[i]->size; const size_t heap_free = heap_size - heaps[i]->mem_allocated; /* * The heap is too small (unlikely but possible) or the heap has not been * created yet, therefore has size = 0 or just there is not enough free * space in it. */ if (heap_size < *size || heap_free < *size) continue; if (heaps[i]->dma != !!(flags & KMALLOC_FL_DMA)) continue; if ((vaddr = per_heap_kmalloc(heaps[i], size, flags))) { if (KMALLOC_SUPPORT_LEAK_DETECTOR && leak_detector_enabled) { debug_kmalloc_register_alloc(vaddr, *size); } return vaddr; } } return NULL; } static int main_heaps_kfree(void *ptr, size_t *size, u32 flags) { struct kmalloc_heap *h = NULL; const ulong vaddr = (ulong) ptr; ASSERT(kmalloc_initialized); for (int i = used_heaps - 1; i >= 0; i--) { const ulong hva = heaps[i]->vaddr; const ulong hend = heaps[i]->heap_last_byte-heaps[i]->min_block_size+1; if (IN_RANGE_INC(vaddr, hva, hend)) { h = heaps[i]; break; } } if (!h) return -ENOENT; /* * Vaddr must be aligned at least at min_block_size otherwise, something is * wrong with it, maybe it has been allocated with mdalloc()? */ ASSERT((vaddr & (h->min_block_size - 1)) == 0); per_heap_kfree(h, ptr, size, flags); if (KMALLOC_FREE_MEM_POISONING) { memset32(ptr, FREE_MEM_POISON_VAL, *size / 4); } if (KMALLOC_SUPPORT_LEAK_DETECTOR && leak_detector_enabled) { debug_kmalloc_register_free((void *)vaddr, *size); } return 0; } void *general_kmalloc(size_t *size, u32 flags) { void *res; const u32 sub_block_sz = flags & KMALLOC_FL_SUB_BLOCK_MIN_SIZE_MASK; ASSERT(kmalloc_initialized); ASSERT(size != NULL); ASSERT(*size); disable_preemption(); { const size_t orig_size = *size; if (*size <= SMALL_HEAP_MAX_ALLOC || UNLIKELY(sub_block_sz && sub_block_sz <= SMALL_HEAP_MAX_ALLOC)) { /* Small DMA allocations are not allowed */ ASSERT(~flags & KMALLOC_FL_DMA); res = small_heaps_kmalloc(size, flags); } else { res = main_heaps_kmalloc(size, flags); if (UNLIKELY(res == NULL && ~flags & KMALLOC_FL_DMA)) res = main_heaps_kmalloc(size, flags | KMALLOC_FL_DMA); } if (KMALLOC_HEAVY_STATS && res != NULL) if (~flags & KMALLOC_FL_DONT_ACCOUNT) kmalloc_account_alloc(orig_size); } enable_preemption(); return res; } void general_kfree(void *ptr, size_t *size, u32 flags) { int rc; ASSERT(kmalloc_initialized); ASSERT(size != NULL); if (!ptr) return; if (flags & (KFREE_FL_MULTI_STEP | KFREE_FL_ALLOW_SPLIT)) { /* For these special cases, the `size` parameter is MANDATORY */ ASSERT(*size); } disable_preemption(); { if (*size) { /* We know which heap set contains our chunk */ if (*size <= SMALL_HEAP_MAX_ALLOC) { rc = small_heaps_kfree(ptr, size, flags); } else { rc = main_heaps_kfree(ptr, size, flags); } } else { /* We don't know which heap set contains our chunk: try them both */ rc = small_heaps_kfree(ptr, size, flags); if (rc) rc = main_heaps_kfree(ptr, size, flags); } } enable_preemption(); if (rc) panic("kfree: Heap not found for block: %p\n", ptr); } /* * Currently, because of the way kmalloc() is implemented, each chunk of actual * size roundup_next_power_of_2(size) with size < KMALLOC_MAX_ALIGN, is * automatically aligned without the need of any effort. Still, it's worth * using functions like aligned_kmalloc() and aligned_kfree() in order to save * the alignment requirement and allow potentially the use of a different * allocator. */ void *aligned_kmalloc(size_t size, u32 align) { void *res = general_kmalloc(&size, 0); ASSERT(align > 0); ASSERT(align <= size); ASSERT(align <= KMALLOC_MAX_ALIGN); ASSERT(roundup_next_power_of_2(align) == align); if (res != NULL) ASSERT(((ulong)res & (align-1)) == 0); return res; } /* See the comment above aligned_kmalloc() */ void aligned_kfree2(void *ptr, size_t size) { general_kfree(ptr, &size, 0); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/elf_loader.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/interrupts.h> static const char *const default_env[] = { "OSTYPE=linux-gnu", "TERM=linux", "LANG=C", "LC_ALL=C", "CONSOLE=/dev/console", "TILCK=1", "HOME=/", "PS1=\\[\\e[01;32m\\]\\u@\\h\\[\\e[00m\\]:$PWD# ", NULL, }; struct execve_ctx { struct task *curr_user_task; const char *const *env; int reclvl; char hdr_stack[MAX_SCRIPT_REC + 1][ELF_RAW_HEADER_SIZE]; const char *argv_stack[MAX_SCRIPT_REC][USERAPP_MAX_ARGS_COUNT]; }; static int do_execve_int(struct execve_ctx *ctx, const char *path, const char *const *argv); static int execve_get_path(const char *user_path, char **path_ref) { int rc = 0; struct task *curr = get_curr_task(); char *path = curr->misc_buf->path_buf; size_t written = 0; if (!(rc = duplicate_user_path(path, user_path, MAX_PATH, &written))) *path_ref = path; return rc; } static int execve_get_args(const char *const *user_argv, const char *const *user_env, char *const **argv_ref, char *const **env_ref) { int rc = 0; char *const *argv = NULL; char *const *env = NULL; struct task *curr = get_curr_task(); char *dest = (char *)curr->args_copybuf; size_t written = 0; if (user_argv) { argv = (char *const *)(void *)(dest + written); rc = duplicate_user_argv(dest, user_argv, ARGS_COPYBUF_SIZE, &written); if (rc != 0) goto out; } if (user_env) { env = (char *const *)(void *)(dest + written); rc = duplicate_user_argv(dest, user_env, ARGS_COPYBUF_SIZE, &written); if (rc != 0) goto out; } *argv_ref = argv; *env_ref = env; out: return rc; } static void save_cmdline(struct process *pi, const char *const *argv) { char *p = pi->debug_cmdline; char *const end = p + PROCESS_CMDLINE_BUF_SIZE; for (int i = 0; argv[i]; i++) { for (const char *s = argv[i]; *s && p < end; s++) *p++ = *s; if (p == end) break; *p++ = ' '; } if (p < end) *p = 0; else memcpy(p - 4, "...", 4); } static void execve_final_steps(struct task *ti, void *brk, const char *const *argv, regs_t *user_regs) { struct process *pi = ti->pi; ASSERT(!is_preemption_enabled()); finalize_usermode_task_setup(ti, user_regs); /* Final steps */ pi->brk = brk; pi->initial_brk = brk; pi->did_call_execve = true; ti->timer_ready = false; /* * From sigpending(2): * A child created via fork(2) initially has an empty pending signal * set; the pending signal set is preserved across an execve(2). * * From sigsuspend(2): * A child created via fork(2) inherits a copy of its parent's * signal mask; the signal mask is preserved across execve(2). */ ti->nested_sig_handlers = 0; ti->in_sigsuspend = false; reset_all_custom_signal_handlers(ti); if (pi->debug_cmdline) save_cmdline(pi, argv); if (pi->vforked) handle_vforked_child_move_on(pi); } static inline int execve_handle_script(struct execve_ctx *ctx, const char *path, const char *const *argv) { const char **new_argv = ctx->argv_stack[ctx->reclvl]; char *hdr = ctx->hdr_stack[ctx->reclvl]; const char **na = new_argv; int i; hdr[ELF_RAW_HEADER_SIZE - 1] = 0; for (i = 0; argv[i]; i++) { if (i >= USERAPP_MAX_ARGS_COUNT - 2) return -E2BIG; /* too many args */ } hdr += 2; /* skip the shebang sequence ("#!") */ /* skip the spaces between #! and the beginning of the path */ while (*hdr == ' ') hdr++; /* if nothing is left, that's a bad executable */ if (!*hdr) return -ENOEXEC; for (char *l = NULL, *p = hdr; *p && p < hdr + ELF_RAW_HEADER_SIZE; p++) { if (*p == ' ' && !l) { *p++ = 0; l = p; *na++ = hdr; } if (*p == '\n') { *p = 0; *na++ = l ? l : hdr; for (i = 0; argv[i]; i++) na[i] = argv[i]; na[i] = NULL; ctx->reclvl++; new_argv[l ? 2 : 1] = path; return do_execve_int(ctx, new_argv[0], new_argv); } } /* We did not hit '\n': this cannot be accepted as a valid script */ return -ENOEXEC; } static inline void execve_do_task_switch(struct execve_ctx *ctx, struct task *ti) { if (LIKELY(ctx->curr_user_task != NULL)) { ASSERT(ti == ctx->curr_user_task); /* * Handling the difference between the first execve() and all the * others. In case of a regular execve(), `curr_user_task` will always * be != NULL and we can switch again to its 'new image' with * switch_to_task(). */ if (KRN_TRACK_NESTED_INTERR) pop_nested_interrupt(); switch_to_task(ti); } else { /* * In case of curr_user_task == NULL (meaning first_execve()), we just * have to return. Yes, that's weird for execve(), but it makes perfect * sense in our context because we'll calling it from a pretty regular * kernel thread (do_async_init): we CANNOT just switch to another task * without saving the current state etc. We just have to return 0. */ } } static int execve_load_elf(struct execve_ctx *ctx, const char *path, const char *const *argv, struct elf_program_info *pinfo) { char *hdr = ctx->hdr_stack[ctx->reclvl]; int rc; bzero(hdr, ELF_RAW_HEADER_SIZE); if ((rc = load_elf_program(path, hdr, pinfo))) { if (rc == -ENOEXEC && hdr[0] == '#' && hdr[1] == '!') { if (ctx->reclvl == MAX_SCRIPT_REC) return -ELOOP; rc = execve_handle_script(ctx, path, argv); } return rc; } return 0; } static void handle_noexec(struct elf_program_info *pinfo, const char *path) { int term_sig = 0; if (pinfo->wrong_arch) { /* * [BE_NICE] * * Tilck has no problem to just return -ENOEXEC in this case, but * ASH's implementation in busybox does not behave as it should: it * tries to interpret ELF's content AS IF it were a shell script: that * causes weird failures, not affecting Tilck's kernel but still, it * makes harder to realize that the ELF had just the wrong arch (e.g. * compiled for x86_64 instead of i686). */ printk("ERROR: Pid %d tried to execute wrong arch ELF: %s\n", get_curr_pid(), path); term_sig = SIGKILL; } else if (pinfo->dyn_exec) { /* * [BE_NICE] * * Since Tilck has no support for dynamic executables, in this case it * will ignore the INTERP segment and it will jump directly to ELF's entry * point, instead of jumping to dynamic linker's entry point. Therefore, * at the first access to a symbol not in the ELF file itself we'll get a * SIGSEGV. * * In order to avoid wasting people's time debugging why a given program * crashes on Tilck, but not on Linux, it's nice to fail early, and display * a meaningful message. */ printk("ERROR: Pid %d tried to execute a dynamic executable: %s\n", get_curr_pid(), path); term_sig = SIGKILL; } else { /* * Not a special error case, just do nothing. The caller will return * the -ENOEXEC error to userspace. */ } if (term_sig) terminate_process(0, term_sig); } static int do_execve_int(struct execve_ctx *ctx, const char *path, const char *const *argv) { struct elf_program_info pinfo = {0}; struct task *ti = NULL; regs_t user_regs; int rc; ASSERT(is_preemption_enabled()); if ((rc = execve_load_elf(ctx, path, argv, &pinfo))) { /* load failed */ if (rc == -ENOEXEC) handle_noexec(&pinfo, path); return rc; } disable_preemption(); { rc = setup_process(&pinfo, ctx->curr_user_task, argv, ctx->env, &ti, &user_regs); } enable_preemption(); if (UNLIKELY(rc)) return rc; /* setup_process() failed */ /* From now on, we cannot fail */ close_cloexec_handles(ti->pi); disable_preemption(); { execve_final_steps(ti, pinfo.brk, argv, &user_regs); execve_do_task_switch(ctx, ti); /* this might NOT return */ } enable_preemption(); return rc; } static int do_execve(struct task *curr_user_task, const char *path, const char *const *argv, const char *const *env) { struct task *ti = get_curr_task(); const char *const default_argv[] = { path, NULL }; struct execve_ctx *ctx = (void *) ti->misc_buf->execve_ctx; STATIC_ASSERT(sizeof(*ctx) <= sizeof(ti->misc_buf->execve_ctx)); ctx->curr_user_task = curr_user_task; ctx->env = env ? env : default_env; ctx->reclvl = 0; return do_execve_int(ctx, path, argv ? argv : default_argv); } int first_execve(const char *path, const char *const *argv) { return do_execve(NULL, path, argv, NULL); } int sys_execve(const char *user_filename, const char *const *user_argv, const char *const *user_env) { int rc; char *path; char *const *argv = NULL; char *const *env = NULL; struct task *curr = get_curr_task(); ASSERT(curr != NULL); if ((rc = execve_get_path(user_filename, &path))) return rc; if ((rc = execve_get_args(user_argv, user_env, &argv, &env))) return rc; return do_execve(curr, path, (const char *const *)argv, (const char *const *)env); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #include <tilck_gen_headers/config_global.h> #define HAVE_KERNEL_CONFIG /* --------- Boolean config variables --------- */ #cmakedefine01 KRN_NO_SYS_WARN #cmakedefine01 KRN_PAGE_FAULT_PRINTK #cmakedefine01 KERNEL_FORCE_TC_ISYSTEM #cmakedefine01 TINY_KERNEL #cmakedefine01 KERNEL_GCOV #cmakedefine01 KERNEL_UBSAN #cmakedefine01 KERNEL_64BIT_OFFT #cmakedefine01 KRN_CLOCK_DRIFT_COMP /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are some pseudo-constants not designed to be easily changed * because of the code makes assumptions about them. Because of that, those * constants are hard-coded and not available as CMake variables. With time, * some of those constants get "promoted" and moved in CMake, others remain * here. See the comments and think about the potential implications before * promoting a hard-coded constant to a configurable CMake variable. */ /* Don't touch this: set KERNEL_STACK_PAGES instead */ #define KERNEL_STACK_SIZE (KERNEL_STACK_PAGES << PAGE_SHIFT) /* Be careful here */ #define KMALLOC_MAX_ALIGN (64 * KB) #define KMALLOC_MIN_HEAP_SIZE KMALLOC_MAX_ALIGN #define PROCESS_CMDLINE_BUF_SIZE 256 #define MAX_MOUNTPOINTS 16 #define MAX_NESTED_INTERRUPTS 32 #define WTH_MAX_THREADS 64 #define WTH_MAX_PRIO_QUEUE_SIZE 32 #define WTH_KB_QUEUE_SIZE 32 #define WTH_SERIAL_QUEUE_SIZE 32 <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause FBDOOM_VER="0.12.1" function download_fbdoom { if ! [ -f $TC/cache/fbdoom.tgz ]; then local fbdoom="https://github.com/maximevince/fbDOOM.git" local fd_url="https://github.com/freedoom/freedoom/releases/download" local ver="$FBDOOM_VER" local freedoom="freedoom-$ver" local freedoom_zip="$freedoom.zip" if ! git clone --depth 1 "$fbdoom"; then echo "ERROR: unable to clone $fbdoom" rm -rf fbDOOM exit 1 fi pushd fbDOOM || exit 1 if ! [ -d fbdoom ]; then echo "ERROR: the directory `pwd`/fbdoom does not exist!" exit 1 fi pushd fbdoom if ! [ -f m_config.c ]; then echo "ERROR: cannot file m_config.c" exit 1 fi if grep 'homedir = "/mnt"' m_config.c; then sed -i 's/homedir = "\/mnt";/homedir = "\/tmp";/g' m_config.c else echo "WARNING: unable to find the homedir hack in m_config.c" fi if ! [ -f config.h ]; then echo "ERROR: cannot file config.h" exit 1 fi if ! grep FILES_DIR config.h &> /dev/null; then echo "ERROR: cannot file the FILES_DIR define in config.h!" exit 1 fi sed -E -i 's/FILES_DIR .+/FILES_DIR "\/tmp"/g' config.h popd wget $fd_url/v$ver/$freedoom_zip if ! [ -f $freedoom_zip ]; then echo "ERROR: unable to download $fd_url/v$ver/$freedoom_zip" rm -rf fbDOOM exit 1 fi unzip $freedoom_zip || exit 1 mv $freedoom freedoom || exit 1 rm $freedoom_zip pushd freedoom if ! [ -f freedoom1.wad ]; then echo "ERROR: unable to find the freedoom1.wad file" exit 1 fi gzip freedoom1.wad popd popd tar cfz fbdoom.tgz fbDOOM || exit 1 mv fbdoom.tgz $TC/cache fi extract_cachefile_tar_gz fbdoom.tgz -- } all_funcs_list+=(build_fbdoom) function build_fbdoom { pushd $ARCH if ! [ -d fbDOOM ]; then show_work_on_component_msg "FBDOOM" reset_cc_vars download_fbdoom cd fbDOOM if [[ "$HOST_ARCH" == "$ARCH" ]]; then # Note: NOT TESTED yet. # Remember: this scenario (building on $ARCH) is _not_ officially # supported. export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" else # Default case set_cc_vars_to_tc fi export CROSS_COMPILE="${ARCH_GCC_TC}-linux-" export LDFLAGS="-static" pushd fbdoom run_command2 "make NOSDL=1 -j$BUILD_PAR" build.log ${ARCH_GCC_TC}-linux-strip --strip-all fbdoom gzip fbdoom popd export LDFLAGS="" export CROSS_COMPILE="" else show_skip_component_msg "FBDOOM" fi popd } function build_fbdoom_installed_status { if [ -d $TC/$ARCH/fbDOOM/ ]; then if [ -f $TC/$ARCH/fbDOOM/fbdoom/fbdoom.gz ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause TREE_CMD_VER="1.8.0" function download_tree_cmd { local ver="$TREE_CMD_VER" local tarname="tree_cmd-$ver.tgz" local url="https://github.com/vvaltchev/tree-command.git" download_git_repo_in_cache "$url" tilck $tarname tree_cmd extract_cachefile_tar_gz $tarname -- } all_funcs_list+=(build_tree_cmd) function build_tree_cmd { pushd $ARCH if ! [ -d tree_cmd ]; then show_work_on_component_msg "TREE (command)" reset_cc_vars download_tree_cmd cd tree_cmd if [[ "$HOST_ARCH" == "$ARCH" ]]; then # Remember: this scenario (building on $ARCH) is _not_ officially # supported. export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" export CC="$MAIN_DIR/scripts/build_scripts/${ARCH}-gcc" export CXX="$MAIN_DIR/scripts/build_scripts/${ARCH}-g++" else # Default case set_cc_vars_to_tc fi run_command2 "make" build.log else show_skip_component_msg "TREE (command)" fi reset_cc_vars popd } function build_tree_cmd_installed_status { if [ -d $TC/$ARCH/tree_cmd ]; then if [ -f $TC/$ARCH/tree_cmd/tree ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_userlim.h> #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/list.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/bintree.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/hal_types.h> #include <tilck/kernel/elf_loader.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/flock.h> #include <tilck/kernel/sys_types.h> struct kernel_alloc { struct bintree_node node; void *vaddr; size_t size; }; struct mappings_info { struct kmalloc_heap *mmap_heap; size_t mmap_heap_size; struct list mappings; }; struct process { REF_COUNTED_OBJECT; int pid; /* process id (tgid in the Linux kernel) */ int pgid; /* process group ID (same as in Linux) */ int sid; /* process session ID (as in Linux) */ int parent_pid; pdir_t *pdir; void *brk; void *initial_brk; struct mappings_info *mi; struct list children; void *proc_tty; bool did_call_execve; bool automatic_reaping; /* the parent explicitly ignored SIGCHLD */ bool vforked; /* after vfork(), before execve() */ bool inherited_mmap_heap; bool did_set_tty_medium_raw; int *set_child_tid; /* NOTE: this is an user pointer */ struct kmutex fslock; /* protects `handles` and `cwd` */ mode_t umask; struct vfs_path cwd; /* CWD as a struct vfs_path */ char *debug_cmdline; /* debug field used by debugpanel */ struct locked_file *elf; fs_handle handles[MAX_HANDLES]; /* just a small fixed-size array */ /* * The purpose of having this opaque `arch_fields` member here is to avoid * including hal.h in this header. The general idea is that, while it is OK * to have architecture-specific fields in this struct, all the non-arch code * should be able to work with this structure without needing to understand * the arch-specific fields. It's all about trying to isolate as much as * possible non-arch code from arch-specific code. * * NOTE: a simpler solution here might be just using a void * pointer and * having those fields stored elsewhere in the kernel heap. That will * certainly work, but it will require an additional kmalloc/kfree call for * each task creation/destruction _and_ it will increase the likelihood of * a cache miss when trying to access those fields as they won't be in a * memory location contiguous with the current struct. * * Therefore, this approach, at the price of some complexity, achieves * separation of arch from non-arch code without introducing any runtime * cost for that. */ char pi_arch[ARCH_PROC_MEMBERS_SIZE] ALIGNED_AT(ARCH_PROC_MEMBERS_ALIGN); /* large members */ char str_cwd[MAX_PATH]; /* current working directory */ void *sa_handlers[_NSIG - 1]; }; STATIC_ASSERT(sizeof(struct misc_buf) <= PAGE_SIZE); #define TOT_PROC_AND_TASK_SIZE (sizeof(struct task) + sizeof(struct process)) STATIC_ASSERT((sizeof(struct task) & ~POINTER_ALIGN_MASK) == 0); STATIC_ASSERT((sizeof(struct process) & ~POINTER_ALIGN_MASK) == 0); static ALWAYS_INLINE struct task * get_process_task(struct process *pi) { /* * allocate_new_process() allocates `struct task` and `struct process` in one * chunk placing struct process immediately after struct task. */ return ((struct task *)pi) - 1; } static ALWAYS_INLINE bool task_is_parent(struct task *parent, struct task *child) { return child->pi->parent_pid == parent->pi->pid; } int do_fork(bool vfork); void handle_vforked_child_move_on(struct process *pi); int first_execve(const char *abs_path, const char *const *argv); int setup_process(struct elf_program_info *pinfo, struct task *task_to_use, const char *const *argv, const char *const *env, struct task **ti_ref, regs_t *user_regs); void finalize_usermode_task_setup(struct task *ti, regs_t *user_regs); struct task * allocate_new_process(struct task *parent, int pid, pdir_t *new_pdir); struct task * allocate_new_thread(struct process *pi, int tid, bool alloc_bufs); void free_task(struct task *ti); void free_mem_for_zombie_task(struct task *ti); bool arch_specific_new_task_setup(struct task *ti, struct task *parent); void arch_specific_free_task(struct task *ti); void arch_specific_new_proc_setup(struct process *pi, struct process *parent); void arch_specific_free_proc(struct process *pi); void wake_up_tasks_waiting_on(struct task *ti, enum wakeup_reason r); void init_process_lists(struct process *pi); void process_set_cwd2_nolock(struct vfs_path *tp); void process_set_cwd2_nolock_raw(struct process *pi, struct vfs_path *tp); void terminate_process(int exit_code, int term_sig); void close_cloexec_handles(struct process *pi); int setup_sig_handler(struct task *ti, enum sig_state sig_state, regs_t *r, ulong user_func, int signum); void setup_pause_trampoline(regs_t *r); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/string_util.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/interrupts.h> void kcond_init(struct kcond *c) { DEBUG_ONLY(check_not_in_irq_handler()); list_init(&c->wait_list); } bool kcond_is_anyone_waiting(struct kcond *c) { bool ret; disable_preemption(); { ret = !list_is_empty(&c->wait_list); } enable_preemption(); return ret; } bool kcond_wait(struct kcond *c, struct kmutex *m, u32 timeout_ticks) { DEBUG_ONLY(check_not_in_irq_handler()); ASSERT(!m || kmutex_is_curr_task_holding_lock(m)); struct task *curr = get_curr_task(); bool ret; panic_retry_hack: disable_preemption(); prepare_to_wait_on(WOBJ_KCOND, c, NO_EXTRA, &c->wait_list); if (timeout_ticks != KCOND_WAIT_FOREVER) task_set_wakeup_timer(curr, timeout_ticks); if (m) { kmutex_unlock(m); } if (UNLIKELY(in_panic())) { /* * During panic, everything is special. When kopt_panic_kb is enabled, * there's a single task, the current one, and IRQ 1 is enabled too. * Waiting for an event means just waiting for an IRQ. Halting the CPU * is what sleeping means in the special single-task mode we have in * panic, when kopt_panic_kb is enabled. */ halt(); enable_preemption(); } else { /* Go to sleep until a signal is fired or timeout happens */ enter_sleep_wait_state(); } /* ------------------- We've been woken up ------------------- */ /* * wait_obj_reset() returns the older value of wobj.ptr: in case it was * NULL, we'll return true (no timeout). Note: that happens (no wobj) because * in kcond_signal_int() we reset task's wobj before wakeing it up. * * In case `wobj.ptr` was != NULL, we woke up because of the timeout (which * doesn't reset the wobj), therefore return false. */ ret = !wait_obj_reset(&curr->wobj); if (m) { kmutex_lock(m); // Re-acquire the lock [if any] } if (UNLIKELY(in_panic())) { /* * When we're in panic and kopt_panic_kb is enabled, we have just a single * task, no scheduler and no IRQs other than from PS/2 or COM1. Still, * the TTY layer needs condition variables to work in order to canonical * mode to work. We cannot sleep in the proper sense, by we can HALT the * the CPU and wait for an IRQ to wake us up. Now, the problem is that we * will wake up on every IRQ, even if we never got signalled. That would * incorrect behavior from the caller point of view therefore, we need * to check if the wait_obj_reset() succeeded: in the positive case, we * know that's not a timeout here (because signal resets the wobj for us), * so we retry the whole thing. If it didn't succeed, we have been * signalled, so return. In other words, kcond_wait() returns ALWAYS true * during panic. */ if (!ret) goto panic_retry_hack; } return ret; } static void kcond_signal_int(struct kcond *c, struct wait_obj *wo) { ASSERT(!is_preemption_enabled()); DEBUG_ONLY(check_not_in_irq_handler()); struct task *ti = wo->type != WOBJ_MWO_ELEM ? CONTAINER_OF(wo, struct task, wobj) : CONTAINER_OF(wo, struct mwobj_elem, wobj)->ti; if (UNLIKELY(in_panic())) { /* * In this case, we have to ignore the task's state, which cannot change * and just reset the wait object, in order to kcond_wait() to understand * that this condition has been actually signalled. * * See the comments above in kcond_wait() for more context. */ wait_obj_reset(wo); return; } if (ti->state != TASK_STATE_SLEEPING) { /* the signal is lost, that's typical for conditions */ if (wo->type == WOBJ_MWO_ELEM) wait_obj_reset(wo); return; } if (wo->type != WOBJ_MWO_ELEM) { ASSERT(wo->type == WOBJ_KCOND); task_cancel_wakeup_timer(ti); } else { ASSERT(CONTAINER_OF(wo, struct mwobj_elem, wobj)->type == WOBJ_KCOND); } wait_obj_reset(wo); wake_up(ti); } void kcond_signal_one(struct kcond *c) { disable_preemption(); { DEBUG_ONLY(check_not_in_irq_handler()); if (!list_is_empty(&c->wait_list)) { struct wait_obj *wobj = list_first_obj(&c->wait_list, struct wait_obj, wait_list_node); kcond_signal_int(c, wobj); } } enable_preemption(); } void kcond_signal_all(struct kcond *c) { struct wait_obj *wo_pos, *temp; disable_preemption(); { DEBUG_ONLY(check_not_in_irq_handler()); list_for_each(wo_pos, temp, &c->wait_list, wait_list_node) { kcond_signal_int(c, wo_pos); } } enable_preemption(); } void kcond_destory(struct kcond *c) { bzero(c, sizeof(struct kcond)); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/list.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/cmdline.h> #include <tilck/mods/pci.h> #include <tilck/mods/acpi.h> #include "osl.h" #include "acpi_int.h" #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> /* Global APIC initialization status */ enum acpi_init_status acpi_init_status; /* Revision number of the FADT table */ static u8 acpi_fadt_revision; /* HW flags read from FADT */ static u16 acpi_iapc_boot_arch; static u32 acpi_fadt_flags; /* Callback lists */ static struct list on_subsystem_enabled_cb_list = STATIC_LIST_INIT(on_subsystem_enabled_cb_list); static struct list on_full_init_cb_list = STATIC_LIST_INIT(on_full_init_cb_list); static struct list per_acpi_object_cb_list = STATIC_LIST_INIT(per_acpi_object_cb_list); void acpi_reg_on_subsys_enabled_cb(struct acpi_reg_callback_node *cbnode) { list_add_tail(&on_subsystem_enabled_cb_list, &cbnode->node); } void acpi_reg_on_full_init_cb(struct acpi_reg_callback_node *cbnode) { list_add_tail(&on_full_init_cb_list, &cbnode->node); } void acpi_reg_per_object_cb(struct acpi_reg_per_object_cb_node *cbnode) { list_add_tail(&per_acpi_object_cb_list, &cbnode->node); } static ACPI_STATUS call_on_subsys_enabled_cbs(void) { STATIC_ASSERT(sizeof(u32) == sizeof(ACPI_STATUS)); struct acpi_reg_callback_node *pos; ACPI_STATUS rc; list_for_each_ro(pos, &on_subsystem_enabled_cb_list, node) { rc = (ACPI_STATUS)pos->cb(pos->ctx); if (ACPI_FAILURE(rc)) return rc; } return AE_OK; } static void call_on_full_init_cbs(void) { struct acpi_reg_callback_node *pos; list_for_each_ro(pos, &on_full_init_cb_list, node) { pos->cb(pos->ctx); } } void print_acpi_failure(const char *func, const char *farg, ACPI_STATUS rc) { const ACPI_EXCEPTION_INFO *ex = AcpiUtValidateException(rc); if (ex) { printk("ERROR: %s(%s) failed with: %s\n", func, farg ? farg:"", ex->Name); } else { printk("ERROR: %s(%s) failed with: %d\n", func, farg ? farg : "", rc); } } enum tristate acpi_is_8042_present(void) { ASSERT(acpi_init_status >= ais_tables_initialized); if (acpi_fadt_revision >= 3) { if (acpi_iapc_boot_arch & ACPI_FADT_8042) return tri_yes; return tri_no; } return tri_unknown; } enum tristate acpi_is_vga_text_mode_avail(void) { ASSERT(acpi_init_status >= ais_tables_initialized); if (acpi_fadt_revision >= 4) { if (acpi_iapc_boot_arch & ACPI_FADT_NO_VGA) return tri_no; return tri_yes; } return tri_unknown; } static void acpi_read_acpi_hw_flags(void) { ACPI_STATUS rc; struct acpi_table_fadt *fadt; rc = AcpiGetTable(ACPI_SIG_FADT, 1, (struct acpi_table_header **)&fadt); if (rc == AE_NOT_FOUND) return; if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiGetTable", "FADT", rc); return; } acpi_fadt_revision = fadt->Header.Revision; acpi_iapc_boot_arch = fadt->BootFlags; acpi_fadt_flags = fadt->Flags; AcpiPutTable((struct acpi_table_header *)fadt); } void acpi_reboot(void) { struct acpi_table_fadt *fadt = &AcpiGbl_FADT; printk("Performing ACPI reset...\n"); if (acpi_fadt_revision < 2) { printk("ACPI reset failed: not supported (FADT too old)\n"); return; } if (~acpi_fadt_flags & ACPI_FADT_RESET_REGISTER) { printk("ACPI reset failed: not supported\n"); return; } if (fadt->ResetRegister.SpaceId == ACPI_ADR_SPACE_PCI_CONFIG) { pci_config_write( pci_make_loc( 0, /* segment */ 0, /* bus */ (fadt->ResetRegister.Address >> 32) & 0xffff, /* device */ (fadt->ResetRegister.Address >> 16) & 0xffff /* function */ ), fadt->ResetRegister.Address & 0xffff, /* offset */ 8, /* width */ fadt->ResetValue ); } else { /* Supports both the memory and I/O port spaces */ AcpiReset(); } /* Ok, now just loop tight for a bit, while the machine resets */ for (int i = 0; i < 100; i++) delay_us(10 * 1000); /* If we got here, something really weird happened */ printk("ACPI reset failed for an unknown reason\n"); } void acpi_poweroff(void) { ACPI_STATUS rc; ASSERT(are_interrupts_enabled()); rc = AcpiEnterSleepStatePrep(ACPI_STATE_S5); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiEnterSleepStatePrep", NULL, rc); return; } /* AcpiEnterSleepState() requires to be called with interrupts disabled */ disable_interrupts_forced(); rc = AcpiEnterSleepState(ACPI_STATE_S5); /* * In theory, we should never get here but, in practice, everything could * happen. */ print_acpi_failure("AcpiEnterSleepState", NULL, rc); } void acpi_mod_init_tables(void) { ACPI_STATUS rc; ASSERT(acpi_init_status == ais_not_started); AcpiDbgLevel = (ACPI_NORMAL_DEFAULT | ACPI_LV_EVENTS) & ~ACPI_LV_REPAIR; //AcpiGbl_TraceDbgLevel = ACPI_TRACE_LEVEL_ALL; //AcpiGbl_TraceDbgLayer = ACPI_TRACE_LAYER_ALL; printk("ACPI: AcpiInitializeSubsystem\n"); rc = AcpiInitializeSubsystem(); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInitializeSubsystem", NULL, rc); acpi_init_status = ais_failed; return; } printk("ACPI: AcpiInitializeTables\n"); rc = AcpiInitializeTables(NULL, 0, true); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInitializeTables", NULL, rc); acpi_init_status = ais_failed; return; } acpi_init_status = ais_tables_initialized; acpi_read_acpi_hw_flags(); } void acpi_mod_load_tables(void) { ACPI_STATUS rc; if (acpi_init_status == ais_failed) return; ASSERT(acpi_init_status == ais_tables_initialized); printk("ACPI: AcpiLoadTables\n"); rc = AcpiLoadTables(); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiLoadTables", NULL, rc); acpi_init_status = ais_failed; return; } acpi_init_status = ais_tables_loaded; } static ACPI_STATUS call_per_matching_device_cbs(ACPI_HANDLE obj, ACPI_DEVICE_INFO *Info) { struct acpi_reg_per_object_cb_node *pos; const char *hid, *uid, *cls; u32 hid_l, uid_l, cls_l; ACPI_STATUS rc; hid = (Info->Valid & ACPI_VALID_HID) ? Info->HardwareId.String : NULL; hid_l = Info->HardwareId.Length; uid = (Info->Valid & ACPI_VALID_UID) ? Info->UniqueId.String : NULL; uid_l = Info->UniqueId.Length; cls = (Info->Valid & ACPI_VALID_CLS) ? Info->ClassCode.String : NULL; cls_l = Info->ClassCode.Length; list_for_each_ro(pos, &per_acpi_object_cb_list, node) { if (pos->hid && (!hid || strncmp(hid, pos->hid, hid_l))) continue; // HID doesn't match if (pos->uid && (!uid || strncmp(uid, pos->uid, uid_l))) continue; // UID doesn't match if (pos->cls && (!cls || strncmp(cls, pos->cls, cls_l))) continue; // CLS doesn't match if (pos->filter && !pos->filter(obj)) continue; // The filter discarded the object rc = pos->cb(obj, Info, pos->ctx); if (ACPI_FAILURE(rc)) return rc; } return AE_OK; } static ACPI_STATUS acpi_walk_single_obj_with_info(ACPI_HANDLE parent, ACPI_HANDLE obj, ACPI_DEVICE_INFO *Info) { ACPI_STATUS rc; if (Info->Type == ACPI_TYPE_DEVICE) { rc = call_per_matching_device_cbs(obj, Info); if (rc == AE_NO_MEMORY) return rc; /* Only the OOM condition requires the walk to stop */ } rc = register_acpi_obj_in_sysfs(parent, obj, Info); if (rc == AE_NO_MEMORY) return rc; return AE_OK; } static ACPI_STATUS acpi_walk_single_obj(ACPI_HANDLE parent, ACPI_HANDLE obj) { ACPI_DEVICE_INFO *Info; ACPI_STATUS rc; /* Get object's info */ rc = AcpiGetObjectInfo(obj, &Info); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiGetObjectInfo", NULL, rc); return rc; /* Fatal error */ } /* Call the per-obj function */ rc = acpi_walk_single_obj_with_info(parent, obj, Info); ACPI_FREE(Info); return rc; } static ACPI_STATUS acpi_walk_ns(void) { ACPI_HANDLE parent, child; ACPI_STATUS rc; printk("ACPI: walk through all objects in the namespace\n"); parent = NULL; /* means root */ child = NULL; /* means first child */ rc = register_acpi_obj_in_sysfs(parent, child, NULL); if (rc == AE_NO_MEMORY) return rc; while (true) { rc = AcpiGetNextObject(ACPI_TYPE_ANY, parent, child, &child); if (ACPI_FAILURE(rc)) { /* No more children */ if (!parent) break; /* This was the root: stop */ /* Go back upwards */ child = parent; AcpiGetParent(parent, &parent); continue; } /* Call the per-obj function */ rc = acpi_walk_single_obj(parent, child); if (ACPI_FAILURE(rc)) return rc; /* Likely, out-of-memory (OOM) condition. */ /* Check if `child` has any children */ rc = AcpiGetNextObject(ACPI_TYPE_ANY, child, NULL, NULL); if (ACPI_SUCCESS(rc)) { /* Yes, it does. Do DFS. */ parent = child; child = NULL; /* first child */ } } return AE_OK; } static void acpi_handle_fatal_failure_after_enable_subsys(void) { ACPI_STATUS rc; ASSERT(acpi_init_status >= ais_subsystem_enabled); acpi_init_status = ais_failed; printk("ACPI: AcpiTerminate\n"); rc = AcpiTerminate(); if (ACPI_FAILURE(rc)) print_acpi_failure("AcpiTerminate", NULL, rc); } static void acpi_global_event_handler(UINT32 EventType, ACPI_HANDLE Device, UINT32 EventNumber, void *Context) { u32 gpe; if (EventType == ACPI_EVENT_TYPE_FIXED) { printk("ACPI: fixed event #%u\n", EventNumber); return; } if (EventType != ACPI_EVENT_TYPE_GPE) { printk("ACPI: warning: unknown event type: %u\n", EventType); return; } /* We received a GPE */ gpe = EventNumber; printk("ACPI: got GPE #%u\n", gpe); } void acpi_mod_enable_subsystem(void) { ACPI_STATUS rc; if (acpi_init_status == ais_failed) return; ASSERT(acpi_init_status == ais_tables_loaded); ASSERT(is_preemption_enabled()); // AcpiUpdateInterfaces(ACPI_DISABLE_ALL_STRINGS); // AcpiInstallInterface("Windows 2000"); printk("ACPI: AcpiEnableSubsystem\n"); rc = AcpiEnableSubsystem(ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiEnableSubsystem", NULL, rc); acpi_init_status = ais_failed; return; } acpi_init_status = ais_subsystem_enabled; printk("ACPI: AcpiInitializeObjects\n"); rc = AcpiInitializeObjects(ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInitializeObjects", NULL, rc); acpi_handle_fatal_failure_after_enable_subsys(); return; } /* * According to acpica-reference-18.pdf, 4.4.3.1, at this point we have to * execute all the _PRW methods and install our GPE handlers. */ rc = acpi_walk_ns(); if (ACPI_FAILURE(rc)) { print_acpi_failure("acpi_walk_ns", NULL, rc); } printk("ACPI: Call on-subsys-enabled callbacks\n"); rc = call_on_subsys_enabled_cbs(); if (ACPI_FAILURE(rc)) { print_acpi_failure("call_on_subsys_enabled_cbs", NULL, rc); acpi_handle_fatal_failure_after_enable_subsys(); return; } rc = AcpiInstallGlobalEventHandler(&acpi_global_event_handler, NULL); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiInstallGlobalEventHandler", NULL, rc); acpi_handle_fatal_failure_after_enable_subsys(); return; } acpi_init_status = ais_fully_initialized; rc = AcpiUpdateAllGpes(); if (ACPI_FAILURE(rc)) { print_acpi_failure("AcpiUpdateAllGpes", NULL, rc); acpi_handle_fatal_failure_after_enable_subsys(); return; } printk("ACPI: Call on-full-init callbacks\n"); call_on_full_init_cbs(); } bool acpi_has_method(ACPI_HANDLE obj, const char *name) { ACPI_HANDLE ret; return ACPI_SUCCESS(AcpiGetHandle(obj, (ACPI_STRING)name, &ret)); } static void acpi_module_init(void) { if (kopt_noacpi) { printk("ACPI: don't load tables and switch to ACPI mode (-noacpi)\n"); return; } acpi_mod_load_tables(); acpi_mod_enable_subsystem(); } static struct module acpi_module = { .name = "acpi", .priority = MOD_acpi_prio, .init = &acpi_module_init, }; REGISTER_MODULE(&acpi_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include "se_data.h" static void **allocations; static void kmalloc_perf_print_iters(int iters) { printk("[%2d%s iters] ", iters < 1000 ? iters : (iters < 1000000 ? iters / 1000 : iters / 1000000), iters < 1000 ? "" : (iters < 1000000 ? "K" : "M")); } static void kmalloc_perf_per_size(u32 size) { const int iters = size < 4096 ? 10000 : (size <= 16*KB ? 1000 : 100); u64 start, duration; start = RDTSC(); for (int i = 0; i < iters; i++) { allocations[i] = kmalloc(size); if (!allocations[i]) panic("We were unable to allocate %u bytes\n", size); } for (int i = 0; i < iters; i++) { kfree2(allocations[i], size); } duration = RDTSC() - start; kmalloc_perf_print_iters(iters); printk(NO_PREFIX "Cycles per kmalloc(%6i) + kfree: %" PRIu64 "\n", size, duration / (u64) iters); } void selftest_kmalloc_perf(void) { const int iters = 1000; printk("*** kmalloc perf test ***\n"); allocations = kalloc_array_obj(void *, 10000); if (!allocations) panic("No enough memory for the 'allocations' buffer"); u64 start = RDTSC(); for (int i = 0; i < iters; i++) { for (int j = 0; j < RANDOM_VALUES_COUNT; j++) { allocations[j] = kmalloc(random_values[j]); if (!allocations[j]) panic("We were unable to allocate %u bytes\n", random_values[j]); } for (int j = 0; j < RANDOM_VALUES_COUNT; j++) kfree2(allocations[j], random_values[j]); } u64 duration = (RDTSC() - start) / (iters * RANDOM_VALUES_COUNT); kmalloc_perf_print_iters(iters * RANDOM_VALUES_COUNT); printk(NO_PREFIX "Cycles per kmalloc(RANDOM) + kfree: %" PRIu64 "\n", duration); for (u32 s = 32; s <= 256*KB; s *= 2) { if (se_is_stop_requested()) break; kmalloc_perf_per_size(s); } kfree_array_obj(allocations, void *, 10000); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(kmalloc_perf, se_long, &selftest_kmalloc_perf) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define DEBUG_RAMFS_CREATE_INODE_PRINTK 0 static struct ramfs_inode *ramfs_new_inode(struct ramfs_data *d) { struct ramfs_inode *i = kzalloc_obj(struct ramfs_inode); if (!i) return NULL; rwlock_wp_init(&i->rwlock, true); list_init(&i->mappings_list); i->type = VFS_NONE; i->ino = d->next_inode_num++; if (DEBUG_RAMFS_CREATE_INODE_PRINTK) { printk("ramfs: Create inode with ref_count at %p\n", &i->ref_count); } return i; } static struct ramfs_inode * ramfs_create_inode_dir(struct ramfs_data *d, mode_t mode, struct ramfs_inode *parent) { struct ramfs_inode *i = ramfs_new_inode(d); if (!i) return NULL; i->type = VFS_DIR; i->mode = (mode & 0777) | S_IFDIR; list_init(&i->entries_list); list_init(&i->handles_list); if (!parent) { /* root case */ parent = i; } i->parent_dir = parent; if (ramfs_dir_add_entry(i, ".", i) < 0) { kfree_obj(i, struct ramfs_inode); return NULL; } if (ramfs_dir_add_entry(i, "..", parent) < 0) { struct ramfs_entry *e = i->entries_tree_root; ramfs_dir_remove_entry(i, e); kfree_obj(i, struct ramfs_inode); return NULL; } real_time_get_timespec(&i->ctime); i->mtime = i->ctime; return i; } static struct ramfs_inode * ramfs_create_inode_file(struct ramfs_data *d, mode_t mode, struct ramfs_inode *parent) { struct ramfs_inode *i = ramfs_new_inode(d); if (!i) return NULL; i->type = VFS_FILE; i->mode = (mode & 0777) | S_IFREG; i->parent_dir = parent; real_time_get_timespec(&i->ctime); i->mtime = i->ctime; return i; } static int ramfs_destroy_inode(struct ramfs_data *d, struct ramfs_inode *i) { /* * We can destroy only inodes referring to NO blocks (= data) in case of * files and no entries in case of directories. Also, we have to be SURE that * no dir entry nor file handle points to it. */ ASSERT(get_ref_count(i) == 0); ASSERT(i->nlink == 0); switch (i->type) { case VFS_NONE: /* do nothing */ break; case VFS_FILE: ASSERT(i->blocks_tree_root == NULL); break; case VFS_DIR: ASSERT(i->entries_tree_root == NULL); break; case VFS_SYMLINK: kfree2(i->path, i->path_len + 1); break; default: NOT_IMPLEMENTED(); } rwlock_wp_destroy(&i->rwlock); kfree_obj(i, struct ramfs_inode); return 0; } static struct ramfs_inode * ramfs_create_inode_symlink(struct ramfs_data *d, struct ramfs_inode *parent, const char *target) { struct ramfs_inode *i = ramfs_new_inode(d); char *path; size_t pl; if (!i) return NULL; pl = strlen(target); if (!(path = kmalloc(pl + 1))) { ramfs_destroy_inode(d, i); return NULL; } memcpy(path, target, pl + 1); i->type = VFS_SYMLINK; i->mode = 0777 | S_IFLNK; i->parent_dir = parent; i->path_len = pl; i->path = path; real_time_get_timespec(&i->ctime); i->mtime = i->ctime; return i; } <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from collections import namedtuple from . import tilck_types as tt BuildConfig = namedtuple( "BuildConfig", [ "CMAKE_SOURCE_DIR", "MAX_HANDLES", "KERNEL_BASE_VA" ] ) gdb_custom_cmds = [] gdb_custom_cmds_objects = [] regex_pretty_printers = gdb.printing.RegexpCollectionPrettyPrinter("Tilck") config = None def set_build_config(obj): global config assert(config is None) assert(isinstance(obj, BuildConfig)) config = obj def register_new_custom_gdb_cmd(cmd_class): gdb_custom_cmds.append(cmd_class) def init_all_custom_cmds(): assert(not gdb_custom_cmds_objects) for cmd in gdb_custom_cmds: gdb_custom_cmds_objects.append(cmd()) def register_tilck_regex_pp(name, regex, class_name): regex_pretty_printers.add_printer(name, regex, class_name) def offset_of(gdb_type_obj, field): null_obj = gdb.Value(0).cast(gdb_type_obj.pointer()) return null_obj[field].address def container_of(elem_ptr, gdb_type_obj, mem_name): off = offset_of(gdb_type_obj, mem_name) container_addr = gdb.Value(int(elem_ptr) - int(off)) return container_addr.cast(gdb_type_obj.pointer()) def select_field_in_list(arr, f, asString = False): if asString: return [ str(x[f]) for x in arr ] return [ x[f] for x in arr ] def to_gdb_list(arr): if not arr: return "{}" tmp = ", ".join([ str(x) for x in arr ]) return gdb.parse_and_eval("{{{}}}".format(tmp)) def to_gdb_list_with_field_select(arr, field, sep = ", "): return to_gdb_list(select_field_in_list(arr, field, True)) def fixhex16(n): return "0x{:04x}".format(int(n)) def fixhex32(n): return "0x{:08x}".format(int(n)) def fmt_type(name, gdb_val): addr = fixhex32(int(gdb_val.address)) return "*({} *) {}".format(name, addr) def get_list_elems(list_obj_ptr, container_gdb_type, list_node_container_mem): res = [] curr = list_obj_ptr.cast(tt.list_node_p)['next'] while curr != list_obj_ptr: obj = container_of(curr, container_gdb_type, list_node_container_mem) res.append(obj) curr = curr['next'] return res <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck_gen_headers/mod_acpi.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <multiboot.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/elf_loader.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/fs/fat32.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/term.h> #include <tilck/kernel/process.h> #include <tilck/kernel/fs/kernelfs.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/mods/console.h> #include <tilck/mods/fb_console.h> #include <tilck/mods/serial.h> #include <tilck/mods/acpi.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/acexcep.h> static bool read_multiboot_info_passed; static u32 saved_multiboot_magic; static multiboot_info_t *saved_multiboot_mbi; static void read_multiboot_info(void); static void save_multiboot_info(u32 magic, u32 mbi) { saved_multiboot_magic = magic; saved_multiboot_mbi = TO_PTR(mbi); } static void init_video_console(void) { if (in_panic()) { /* * We're in panic and there's no video console yet. Well, we can * initialize it, but we have to check if we at least read the multiboot * info first. */ if (!read_multiboot_info_passed) read_multiboot_info(); } if (!use_framebuffer()) { if (MOD_console) { /* * NOTE: since we got here, we're sure that we have the console module * built-in, but we still have to put the call under an if, in order * to remove the link dependency on that symbol in case the console * module is _not_ built-in. */ if (MOD_acpi && get_acpi_init_status() >= ais_tables_initialized && acpi_is_vga_text_mode_avail() == tri_no) { /* no text mode on this machine */ init_first_term_null(); } else { /* * No ACPI or ACPI tables are not initialized (panic?) or * vga text mode is available or ACPI's FADT is too old to tell * whether text mode is available or not so we assume it is. */ init_textmode_console(); } } return; } /* framebuffer console */ if (!MOD_fb) { /* * This compile-time check (MOD_fb will evalute as 0 or 1) instead, is * strictly necessary, as the kernel could be loaded in graphical mode * without having the `fb` module built-in. In this case, we just won't * display anything on the screen. */ init_first_term_null(); return; } init_fb_console(); } void init_console(void) { printk("*** Init the kernel console\n"); if (kopt_sercon) { if (!serial_term_intf) { /* * We have to use the serial console, but the module is not built-in: * disable it and display an error on video, if we can. Otherwise, * we're simply doomed. */ if (!video_term_intf) goto we_are_doomed; kopt_sercon = false; panic("Unable to init the serial console without the serial module!"); } init_first_serial_term(COM1); printk_flush_ringbuf(); return; } if (!video_term_intf) { /* * We have to use the video console, but the module is not built-in: * disable it and send an error on the serial port, if we can. Otherwise, * we're simply doomed. */ if (!serial_term_intf) goto we_are_doomed; kopt_sercon = true; panic("Unable to init the video console without the console module!"); } init_video_console(); printk_flush_ringbuf(); return; we_are_doomed: disable_interrupts_forced(); while (1) halt(); } static void read_multiboot_info(void) { multiboot_info_t *mbi = saved_multiboot_mbi; if (read_multiboot_info_passed) return; /* We're probably in panic: just do nothing */ if (saved_multiboot_magic != MULTIBOOT_BOOTLOADER_MAGIC) { if (in_panic()) goto out; /* We're already in panic: just fail silently */ panic("The Tilck kernel requires a multiboot-compatible bootloader"); } if (~mbi->flags & MULTIBOOT_INFO_MEM_MAP) { if (in_panic()) goto out; /* We're already in panic: just fail silently */ panic("No memory map in the multiboot info struct"); } if (mbi->flags & MULTIBOOT_INFO_BOOT_LOADER_NAME) { const char *name = TO_PTR(mbi->boot_loader_name); if (!strcmp(name, "TILCK_EFI")) { printk("Multiboot: detected the TILCK_EFI bootloader\n"); printk("Multiboot: ACPI root ptr: %p\n", TO_PTR(mbi->apm_table)); acpi_set_root_pointer(mbi->apm_table); } } /* Loading ramdisk(s) is not even worth considering if we're in panic */ if (!in_panic()) { if (mbi->flags & MULTIBOOT_INFO_MODS) { multiboot_module_t *mods = TO_PTR(mbi->mods_addr); for (u32 i = 0; i < mbi->mods_count; i++) system_mmap_add_ramdisk(mods[i].mod_start, mods[i].mod_end); } } /* Framebuffer info is essential, even if we're in panic */ if (MOD_fb) { if (mbi->flags & MULTIBOOT_INFO_FRAMEBUFFER_INFO) if (mbi->framebuffer_type == MULTIBOOT_FRAMEBUFFER_TYPE_RGB) set_framebuffer_info_from_mbi(mbi); } /* Set system's memory map based on what was provided to us via multiboot */ system_mmap_set(mbi); /* It's safer to stick to the default settings, when we're in panic */ if (!in_panic()) { if (mbi->flags & MULTIBOOT_INFO_CMDLINE) parse_kernel_cmdline(TO_PTR(mbi->cmdline)); } out: read_multiboot_info_passed = true; /* Reset the temporary multiboot variables as they won't be used again */ saved_multiboot_magic = 0; saved_multiboot_mbi = NULL; } static void mount_initrd(void) { /* declare the ramfs_create() function */ struct mnt_fs *ramfs_create(void); struct mnt_fs *initrd, *ramfs; void *ramdisk; size_t ramdisk_size; int rc; if (system_mmap_get_ramdisk(0, &ramdisk, &ramdisk_size) < 0) panic("system_mmap_get_ramdisk_vaddr(0) failed"); if (!(ramfs = ramfs_create())) panic("Unable to create ramfs"); if ((rc = mp_init(ramfs))) panic("mp_init() failed with error: %d", rc); if ((rc = vfs_mkdir("/tmp", 0777))) panic("vfs_mkdir(\"/tmp\") failed with error: %d", rc); /* Set kernel's process `cwd` to the root folder */ { struct vfs_path tp; struct process *pi = kernel_process_pi; ASSERT(pi == get_curr_proc()); tp.fs = mp_get_root(); vfs_get_root_entry(tp.fs, &tp.fs_path); process_set_cwd2_nolock_raw(pi, &tp); } if (LIKELY(ramdisk != NULL)) { if (!(initrd = fat_mount_ramdisk(ramdisk, ramdisk_size, 0))) panic("Unable to mount the initrd fat32 RAMDISK"); if ((rc = vfs_mkdir("/initrd", 0777))) panic("vfs_mkdir(\"/initrd\") failed with error: %d", rc); if ((rc = mp_add(initrd, "/initrd"))) panic("mp_add() failed with error: %d", rc); } else { printk("[WARNING] No RAMDISK found.\n"); } } static void run_init_or_selftest(void) { if (self_test_to_run) { if (KERNEL_SELFTESTS) { self_test_to_run(); return; } panic("The kernel was not compiled with self-tests"); } else { if (system_mmap_get_ramdisk(0, NULL, NULL) < 0) panic("No ramdisk and no selftest requested: nothing to do."); /* Run init or whatever program was passed in the cmdline */ long rc = first_execve(cmd_args[0], cmd_args); if (rc != 0) panic("execve('%s') failed with %i\n", cmd_args[0], rc); } } static void do_async_init() { /* declare the show_hello_message() function */ void show_hello_message(void); mount_initrd(); init_devfs(); init_modules(); init_extra_debug_features(); show_hello_message(); run_init_or_selftest(); } static void async_init(void) { if (kthread_create(&do_async_init, KTH_ALLOC_BUFS, NULL) < 0) panic("Unable to create a kthread for do_async_init()"); } void kmain(u32 multiboot_magic, u32 mbi_addr) { call_kernel_global_ctors(); save_multiboot_info(multiboot_magic, mbi_addr); early_init_serial_ports(); init_cpu_exception_handling(); early_init_paging(); early_init_kmalloc(); read_multiboot_info(); enable_cpu_features(); kmain_early_checks(); init_segmentation(); init_fpu_memcpy(); init_kmalloc(); init_paging(); acpi_mod_init_tables(); init_console(); init_self_tests(); init_irq_handling(); init_sched(); init_syscall_interfaces(); init_worker_threads(); init_timer(); init_system_time(); init_kernelfs(); async_init(); do_schedule(); } <file_sep>/****************************************************************************** * * Module Name: uttrack - Memory allocation tracking routines (debug only) * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* * These procedures are used for tracking memory leaks in the subsystem, and * they get compiled out when the ACPI_DBG_TRACK_ALLOCATIONS is not set. * * Each memory allocation is tracked via a doubly linked list. Each * element contains the caller's component, module name, function name, and * line number. AcpiUtAllocate and AcpiUtAllocateZeroed call * AcpiUtTrackAllocation to add an element to the list; deletion * occurs in the body of AcpiUtFree. */ #include "acpi.h" #include "accommon.h" #ifdef ACPI_DBG_TRACK_ALLOCATIONS #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("uttrack") /* Local prototypes */ static ACPI_DEBUG_MEM_BLOCK * AcpiUtFindAllocation ( ACPI_DEBUG_MEM_BLOCK *Allocation); static ACPI_STATUS AcpiUtTrackAllocation ( ACPI_DEBUG_MEM_BLOCK *Address, ACPI_SIZE Size, UINT8 AllocType, UINT32 Component, const char *Module, UINT32 Line); static ACPI_STATUS AcpiUtRemoveAllocation ( ACPI_DEBUG_MEM_BLOCK *Address, UINT32 Component, const char *Module, UINT32 Line); /******************************************************************************* * * FUNCTION: AcpiUtCreateList * * PARAMETERS: CacheName - Ascii name for the cache * ObjectSize - Size of each cached object * ReturnCache - Where the new cache object is returned * * RETURN: Status * * DESCRIPTION: Create a local memory list for tracking purposed * ******************************************************************************/ ACPI_STATUS AcpiUtCreateList ( const char *ListName, UINT16 ObjectSize, ACPI_MEMORY_LIST **ReturnCache) { ACPI_MEMORY_LIST *Cache; Cache = AcpiOsAllocateZeroed (sizeof (ACPI_MEMORY_LIST)); if (!Cache) { return (AE_NO_MEMORY); } Cache->ListName = ListName; Cache->ObjectSize = ObjectSize; *ReturnCache = Cache; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtAllocateAndTrack * * PARAMETERS: Size - Size of the allocation * Component - Component type of caller * Module - Source file name of caller * Line - Line number of caller * * RETURN: Address of the allocated memory on success, NULL on failure. * * DESCRIPTION: The subsystem's equivalent of malloc. * ******************************************************************************/ void * AcpiUtAllocateAndTrack ( ACPI_SIZE Size, UINT32 Component, const char *Module, UINT32 Line) { ACPI_DEBUG_MEM_BLOCK *Allocation; ACPI_STATUS Status; /* Check for an inadvertent size of zero bytes */ if (!Size) { ACPI_WARNING ((Module, Line, "Attempt to allocate zero bytes, allocating 1 byte")); Size = 1; } Allocation = AcpiOsAllocate (Size + sizeof (ACPI_DEBUG_MEM_HEADER)); if (!Allocation) { /* Report allocation error */ ACPI_WARNING ((Module, Line, "Could not allocate size %u", (UINT32) Size)); return (NULL); } Status = AcpiUtTrackAllocation ( Allocation, Size, ACPI_MEM_MALLOC, Component, Module, Line); if (ACPI_FAILURE (Status)) { AcpiOsFree (Allocation); return (NULL); } AcpiGbl_GlobalList->TotalAllocated++; AcpiGbl_GlobalList->TotalSize += (UINT32) Size; AcpiGbl_GlobalList->CurrentTotalSize += (UINT32) Size; if (AcpiGbl_GlobalList->CurrentTotalSize > AcpiGbl_GlobalList->MaxOccupied) { AcpiGbl_GlobalList->MaxOccupied = AcpiGbl_GlobalList->CurrentTotalSize; } return ((void *) &Allocation->UserSpace); } /******************************************************************************* * * FUNCTION: AcpiUtAllocateZeroedAndTrack * * PARAMETERS: Size - Size of the allocation * Component - Component type of caller * Module - Source file name of caller * Line - Line number of caller * * RETURN: Address of the allocated memory on success, NULL on failure. * * DESCRIPTION: Subsystem equivalent of calloc. * ******************************************************************************/ void * AcpiUtAllocateZeroedAndTrack ( ACPI_SIZE Size, UINT32 Component, const char *Module, UINT32 Line) { ACPI_DEBUG_MEM_BLOCK *Allocation; ACPI_STATUS Status; /* Check for an inadvertent size of zero bytes */ if (!Size) { ACPI_WARNING ((Module, Line, "Attempt to allocate zero bytes, allocating 1 byte")); Size = 1; } Allocation = AcpiOsAllocateZeroed ( Size + sizeof (ACPI_DEBUG_MEM_HEADER)); if (!Allocation) { /* Report allocation error */ ACPI_ERROR ((Module, Line, "Could not allocate size %u", (UINT32) Size)); return (NULL); } Status = AcpiUtTrackAllocation (Allocation, Size, ACPI_MEM_CALLOC, Component, Module, Line); if (ACPI_FAILURE (Status)) { AcpiOsFree (Allocation); return (NULL); } AcpiGbl_GlobalList->TotalAllocated++; AcpiGbl_GlobalList->TotalSize += (UINT32) Size; AcpiGbl_GlobalList->CurrentTotalSize += (UINT32) Size; if (AcpiGbl_GlobalList->CurrentTotalSize > AcpiGbl_GlobalList->MaxOccupied) { AcpiGbl_GlobalList->MaxOccupied = AcpiGbl_GlobalList->CurrentTotalSize; } return ((void *) &Allocation->UserSpace); } /******************************************************************************* * * FUNCTION: AcpiUtFreeAndTrack * * PARAMETERS: Allocation - Address of the memory to deallocate * Component - Component type of caller * Module - Source file name of caller * Line - Line number of caller * * RETURN: None * * DESCRIPTION: Frees the memory at Allocation * ******************************************************************************/ void AcpiUtFreeAndTrack ( void *Allocation, UINT32 Component, const char *Module, UINT32 Line) { ACPI_DEBUG_MEM_BLOCK *DebugBlock; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (UtFree, Allocation); if (NULL == Allocation) { ACPI_ERROR ((Module, Line, "Attempt to delete a NULL address")); return_VOID; } DebugBlock = ACPI_CAST_PTR (ACPI_DEBUG_MEM_BLOCK, (((char *) Allocation) - sizeof (ACPI_DEBUG_MEM_HEADER))); AcpiGbl_GlobalList->TotalFreed++; AcpiGbl_GlobalList->CurrentTotalSize -= DebugBlock->Size; Status = AcpiUtRemoveAllocation (DebugBlock, Component, Module, Line); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not free memory")); } AcpiOsFree (DebugBlock); ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "%p freed (block %p)\n", Allocation, DebugBlock)); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiUtFindAllocation * * PARAMETERS: Allocation - Address of allocated memory * * RETURN: Three cases: * 1) List is empty, NULL is returned. * 2) Element was found. Returns Allocation parameter. * 3) Element was not found. Returns position where it should be * inserted into the list. * * DESCRIPTION: Searches for an element in the global allocation tracking list. * If the element is not found, returns the location within the * list where the element should be inserted. * * Note: The list is ordered by larger-to-smaller addresses. * * This global list is used to detect memory leaks in ACPICA as * well as other issues such as an attempt to release the same * internal object more than once. Although expensive as far * as cpu time, this list is much more helpful for finding these * types of issues than using memory leak detectors outside of * the ACPICA code. * ******************************************************************************/ static ACPI_DEBUG_MEM_BLOCK * AcpiUtFindAllocation ( ACPI_DEBUG_MEM_BLOCK *Allocation) { ACPI_DEBUG_MEM_BLOCK *Element; Element = AcpiGbl_GlobalList->ListHead; if (!Element) { return (NULL); } /* * Search for the address. * * Note: List is ordered by larger-to-smaller addresses, on the * assumption that a new allocation usually has a larger address * than previous allocations. */ while (Element > Allocation) { /* Check for end-of-list */ if (!Element->Next) { return (Element); } Element = Element->Next; } if (Element == Allocation) { return (Element); } return (Element->Previous); } /******************************************************************************* * * FUNCTION: AcpiUtTrackAllocation * * PARAMETERS: Allocation - Address of allocated memory * Size - Size of the allocation * AllocType - MEM_MALLOC or MEM_CALLOC * Component - Component type of caller * Module - Source file name of caller * Line - Line number of caller * * RETURN: Status * * DESCRIPTION: Inserts an element into the global allocation tracking list. * ******************************************************************************/ static ACPI_STATUS AcpiUtTrackAllocation ( ACPI_DEBUG_MEM_BLOCK *Allocation, ACPI_SIZE Size, UINT8 AllocType, UINT32 Component, const char *Module, UINT32 Line) { ACPI_MEMORY_LIST *MemList; ACPI_DEBUG_MEM_BLOCK *Element; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (UtTrackAllocation, Allocation); if (AcpiGbl_DisableMemTracking) { return_ACPI_STATUS (AE_OK); } MemList = AcpiGbl_GlobalList; Status = AcpiUtAcquireMutex (ACPI_MTX_MEMORY); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Search the global list for this address to make sure it is not * already present. This will catch several kinds of problems. */ Element = AcpiUtFindAllocation (Allocation); if (Element == Allocation) { ACPI_ERROR ((AE_INFO, "UtTrackAllocation: Allocation (%p) already present in global list!", Allocation)); goto UnlockAndExit; } /* Fill in the instance data */ Allocation->Size = (UINT32) Size; Allocation->AllocType = AllocType; Allocation->Component = Component; Allocation->Line = Line; AcpiUtSafeStrncpy (Allocation->Module, (char *) Module, ACPI_MAX_MODULE_NAME); if (!Element) { /* Insert at list head */ if (MemList->ListHead) { ((ACPI_DEBUG_MEM_BLOCK *)(MemList->ListHead))->Previous = Allocation; } Allocation->Next = MemList->ListHead; Allocation->Previous = NULL; MemList->ListHead = Allocation; } else { /* Insert after element */ Allocation->Next = Element->Next; Allocation->Previous = Element; if (Element->Next) { (Element->Next)->Previous = Allocation; } Element->Next = Allocation; } UnlockAndExit: Status = AcpiUtReleaseMutex (ACPI_MTX_MEMORY); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtRemoveAllocation * * PARAMETERS: Allocation - Address of allocated memory * Component - Component type of caller * Module - Source file name of caller * Line - Line number of caller * * RETURN: Status * * DESCRIPTION: Deletes an element from the global allocation tracking list. * ******************************************************************************/ static ACPI_STATUS AcpiUtRemoveAllocation ( ACPI_DEBUG_MEM_BLOCK *Allocation, UINT32 Component, const char *Module, UINT32 Line) { ACPI_MEMORY_LIST *MemList; ACPI_STATUS Status; ACPI_FUNCTION_NAME (UtRemoveAllocation); if (AcpiGbl_DisableMemTracking) { return (AE_OK); } MemList = AcpiGbl_GlobalList; if (NULL == MemList->ListHead) { /* No allocations! */ ACPI_ERROR ((Module, Line, "Empty allocation list, nothing to free!")); return (AE_OK); } Status = AcpiUtAcquireMutex (ACPI_MTX_MEMORY); if (ACPI_FAILURE (Status)) { return (Status); } /* Unlink */ if (Allocation->Previous) { (Allocation->Previous)->Next = Allocation->Next; } else { MemList->ListHead = Allocation->Next; } if (Allocation->Next) { (Allocation->Next)->Previous = Allocation->Previous; } ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Freeing %p, size 0%X\n", &Allocation->UserSpace, Allocation->Size)); /* Mark the segment as deleted */ memset (&Allocation->UserSpace, 0xEA, Allocation->Size); Status = AcpiUtReleaseMutex (ACPI_MTX_MEMORY); return (Status); } /******************************************************************************* * * FUNCTION: AcpiUtDumpAllocationInfo * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Print some info about the outstanding allocations. * ******************************************************************************/ void AcpiUtDumpAllocationInfo ( void) { /* ACPI_MEMORY_LIST *MemList; */ ACPI_FUNCTION_TRACE (UtDumpAllocationInfo); /* ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Current allocations", MemList->CurrentCount, ROUND_UP_TO_1K (MemList->CurrentSize))); ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Max concurrent allocations", MemList->MaxConcurrentCount, ROUND_UP_TO_1K (MemList->MaxConcurrentSize))); ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Total (all) internal objects", RunningObjectCount, ROUND_UP_TO_1K (RunningObjectSize))); ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Total (all) allocations", RunningAllocCount, ROUND_UP_TO_1K (RunningAllocSize))); ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Current Nodes", AcpiGbl_CurrentNodeCount, ROUND_UP_TO_1K (AcpiGbl_CurrentNodeSize))); ACPI_DEBUG_PRINT (TRACE_ALLOCATIONS | TRACE_TABLES, ("%30s: %4d (%3d Kb)\n", "Max Nodes", AcpiGbl_MaxConcurrentNodeCount, ROUND_UP_TO_1K ((AcpiGbl_MaxConcurrentNodeCount * sizeof (ACPI_NAMESPACE_NODE))))); */ return_VOID; } /******************************************************************************* * * FUNCTION: AcpiUtDumpAllocations * * PARAMETERS: Component - Component(s) to dump info for. * Module - Module to dump info for. NULL means all. * * RETURN: None * * DESCRIPTION: Print a list of all outstanding allocations. * ******************************************************************************/ void AcpiUtDumpAllocations ( UINT32 Component, const char *Module) { ACPI_DEBUG_MEM_BLOCK *Element; ACPI_DESCRIPTOR *Descriptor; UINT32 NumOutstanding = 0; UINT8 DescriptorType; ACPI_FUNCTION_TRACE (UtDumpAllocations); if (AcpiGbl_DisableMemTracking) { return_VOID; } /* * Walk the allocation list. */ if (ACPI_FAILURE (AcpiUtAcquireMutex (ACPI_MTX_MEMORY))) { return_VOID; } if (!AcpiGbl_GlobalList) { goto Exit; } Element = AcpiGbl_GlobalList->ListHead; while (Element) { if ((Element->Component & Component) && ((Module == NULL) || (0 == strcmp (Module, Element->Module)))) { Descriptor = ACPI_CAST_PTR ( ACPI_DESCRIPTOR, &Element->UserSpace); if (Element->Size < sizeof (ACPI_COMMON_DESCRIPTOR)) { AcpiOsPrintf ("%p Length 0x%04X %9.9s-%4.4u " "[Not a Descriptor - too small]\n", Descriptor, Element->Size, Element->Module, Element->Line); } else { /* Ignore allocated objects that are in a cache */ if (ACPI_GET_DESCRIPTOR_TYPE (Descriptor) != ACPI_DESC_TYPE_CACHED) { AcpiOsPrintf ("%p Length 0x%04X %9.9s-%4.4u [%s] ", Descriptor, Element->Size, Element->Module, Element->Line, AcpiUtGetDescriptorName (Descriptor)); /* Optional object hex dump */ if (AcpiGbl_VerboseLeakDump) { AcpiOsPrintf ("\n"); AcpiUtDumpBuffer ((UINT8 *) Descriptor, Element->Size, DB_BYTE_DISPLAY, 0); } /* Validate the descriptor type using Type field and length */ DescriptorType = 0; /* Not a valid descriptor type */ switch (ACPI_GET_DESCRIPTOR_TYPE (Descriptor)) { case ACPI_DESC_TYPE_OPERAND: if (Element->Size == sizeof (ACPI_OPERAND_OBJECT)) { DescriptorType = ACPI_DESC_TYPE_OPERAND; } break; case ACPI_DESC_TYPE_PARSER: if (Element->Size == sizeof (ACPI_PARSE_OBJECT)) { DescriptorType = ACPI_DESC_TYPE_PARSER; } break; case ACPI_DESC_TYPE_NAMED: if (Element->Size == sizeof (ACPI_NAMESPACE_NODE)) { DescriptorType = ACPI_DESC_TYPE_NAMED; } break; default: break; } /* Display additional info for the major descriptor types */ switch (DescriptorType) { case ACPI_DESC_TYPE_OPERAND: AcpiOsPrintf ("%12.12s RefCount 0x%04X\n", AcpiUtGetTypeName (Descriptor->Object.Common.Type), Descriptor->Object.Common.ReferenceCount); break; case ACPI_DESC_TYPE_PARSER: AcpiOsPrintf ("AmlOpcode 0x%04X\n", Descriptor->Op.Asl.AmlOpcode); break; case ACPI_DESC_TYPE_NAMED: AcpiOsPrintf ("%4.4s\n", AcpiUtGetNodeName (&Descriptor->Node)); break; default: AcpiOsPrintf ( "\n"); break; } } } NumOutstanding++; } Element = Element->Next; } Exit: (void) AcpiUtReleaseMutex (ACPI_MTX_MEMORY); /* Print summary */ if (!NumOutstanding) { ACPI_INFO (("No outstanding allocations")); } else { ACPI_ERROR ((AE_INFO, "%u (0x%X) Outstanding cache allocations", NumOutstanding, NumOutstanding)); } return_VOID; } #endif /* ACPI_DBG_TRACK_ALLOCATIONS */ <file_sep>/****************************************************************************** * * Name: acrestyp.h - Defines, types, and structures for resource descriptors * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACRESTYP_H__ #define __ACRESTYP_H__ /* * Definitions for Resource Attributes */ typedef UINT16 ACPI_RS_LENGTH; /* Resource Length field is fixed at 16 bits */ typedef UINT32 ACPI_RSDESC_SIZE; /* Max Resource Descriptor size is (Length+3) = (64K-1)+3 */ /* * Memory Attributes */ #define ACPI_READ_ONLY_MEMORY (UINT8) 0x00 #define ACPI_READ_WRITE_MEMORY (UINT8) 0x01 #define ACPI_NON_CACHEABLE_MEMORY (UINT8) 0x00 #define ACPI_CACHABLE_MEMORY (UINT8) 0x01 #define ACPI_WRITE_COMBINING_MEMORY (UINT8) 0x02 #define ACPI_PREFETCHABLE_MEMORY (UINT8) 0x03 /*! [Begin] no source code translation */ /* * IO Attributes * The ISA IO ranges are: n000-n0FFh, n400-n4FFh, n800-n8FFh, nC00-nCFFh. * The non-ISA IO ranges are: n100-n3FFh, n500-n7FFh, n900-nBFFh, nCD0-nFFFh. */ /*! [End] no source code translation !*/ #define ACPI_NON_ISA_ONLY_RANGES (UINT8) 0x01 #define ACPI_ISA_ONLY_RANGES (UINT8) 0x02 #define ACPI_ENTIRE_RANGE (ACPI_NON_ISA_ONLY_RANGES | ACPI_ISA_ONLY_RANGES) /* Type of translation - 1=Sparse, 0=Dense */ #define ACPI_SPARSE_TRANSLATION (UINT8) 0x01 /* * IO Port Descriptor Decode */ #define ACPI_DECODE_10 (UINT8) 0x00 /* 10-bit IO address decode */ #define ACPI_DECODE_16 (UINT8) 0x01 /* 16-bit IO address decode */ /* * Interrupt attributes - used in multiple descriptors */ /* Triggering */ #define ACPI_LEVEL_SENSITIVE (UINT8) 0x00 #define ACPI_EDGE_SENSITIVE (UINT8) 0x01 /* Polarity */ #define ACPI_ACTIVE_HIGH (UINT8) 0x00 #define ACPI_ACTIVE_LOW (UINT8) 0x01 #define ACPI_ACTIVE_BOTH (UINT8) 0x02 /* Sharing */ #define ACPI_EXCLUSIVE (UINT8) 0x00 #define ACPI_SHARED (UINT8) 0x01 /* Wake */ #define ACPI_NOT_WAKE_CAPABLE (UINT8) 0x00 #define ACPI_WAKE_CAPABLE (UINT8) 0x01 /* * DMA Attributes */ #define ACPI_COMPATIBILITY (UINT8) 0x00 #define ACPI_TYPE_A (UINT8) 0x01 #define ACPI_TYPE_B (UINT8) 0x02 #define ACPI_TYPE_F (UINT8) 0x03 #define ACPI_NOT_BUS_MASTER (UINT8) 0x00 #define ACPI_BUS_MASTER (UINT8) 0x01 #define ACPI_TRANSFER_8 (UINT8) 0x00 #define ACPI_TRANSFER_8_16 (UINT8) 0x01 #define ACPI_TRANSFER_16 (UINT8) 0x02 /* * Start Dependent Functions Priority definitions */ #define ACPI_GOOD_CONFIGURATION (UINT8) 0x00 #define ACPI_ACCEPTABLE_CONFIGURATION (UINT8) 0x01 #define ACPI_SUB_OPTIMAL_CONFIGURATION (UINT8) 0x02 /* * 16, 32 and 64-bit Address Descriptor resource types */ #define ACPI_MEMORY_RANGE (UINT8) 0x00 #define ACPI_IO_RANGE (UINT8) 0x01 #define ACPI_BUS_NUMBER_RANGE (UINT8) 0x02 #define ACPI_ADDRESS_NOT_FIXED (UINT8) 0x00 #define ACPI_ADDRESS_FIXED (UINT8) 0x01 #define ACPI_POS_DECODE (UINT8) 0x00 #define ACPI_SUB_DECODE (UINT8) 0x01 /* Producer/Consumer */ #define ACPI_PRODUCER (UINT8) 0x00 #define ACPI_CONSUMER (UINT8) 0x01 /* * If possible, pack the following structures to byte alignment */ #ifndef ACPI_MISALIGNMENT_NOT_SUPPORTED #pragma pack(1) #endif /* UUID data structures for use in vendor-defined resource descriptors */ typedef struct acpi_uuid { UINT8 Data[ACPI_UUID_LENGTH]; } ACPI_UUID; typedef struct acpi_vendor_uuid { UINT8 Subtype; UINT8 Data[ACPI_UUID_LENGTH]; } ACPI_VENDOR_UUID; /* * Structures used to describe device resources */ typedef struct acpi_resource_irq { UINT8 DescriptorLength; UINT8 Triggering; UINT8 Polarity; UINT8 Shareable; UINT8 WakeCapable; UINT8 InterruptCount; UINT8 Interrupts[1]; } ACPI_RESOURCE_IRQ; typedef struct acpi_resource_dma { UINT8 Type; UINT8 BusMaster; UINT8 Transfer; UINT8 ChannelCount; UINT8 Channels[1]; } ACPI_RESOURCE_DMA; typedef struct acpi_resource_start_dependent { UINT8 DescriptorLength; UINT8 CompatibilityPriority; UINT8 PerformanceRobustness; } ACPI_RESOURCE_START_DEPENDENT; /* * The END_DEPENDENT_FUNCTIONS_RESOURCE struct is not * needed because it has no fields */ typedef struct acpi_resource_io { UINT8 IoDecode; UINT8 Alignment; UINT8 AddressLength; UINT16 Minimum; UINT16 Maximum; } ACPI_RESOURCE_IO; typedef struct acpi_resource_fixed_io { UINT16 Address; UINT8 AddressLength; } ACPI_RESOURCE_FIXED_IO; typedef struct acpi_resource_fixed_dma { UINT16 RequestLines; UINT16 Channels; UINT8 Width; } ACPI_RESOURCE_FIXED_DMA; /* Values for Width field above */ #define ACPI_DMA_WIDTH8 0 #define ACPI_DMA_WIDTH16 1 #define ACPI_DMA_WIDTH32 2 #define ACPI_DMA_WIDTH64 3 #define ACPI_DMA_WIDTH128 4 #define ACPI_DMA_WIDTH256 5 typedef struct acpi_resource_vendor { UINT16 ByteLength; UINT8 ByteData[1]; } ACPI_RESOURCE_VENDOR; /* Vendor resource with UUID info (introduced in ACPI 3.0) */ typedef struct acpi_resource_vendor_typed { UINT16 ByteLength; UINT8 UuidSubtype; UINT8 Uuid[ACPI_UUID_LENGTH]; UINT8 ByteData[1]; } ACPI_RESOURCE_VENDOR_TYPED; typedef struct acpi_resource_end_tag { UINT8 Checksum; } ACPI_RESOURCE_END_TAG; typedef struct acpi_resource_memory24 { UINT8 WriteProtect; UINT16 Minimum; UINT16 Maximum; UINT16 Alignment; UINT16 AddressLength; } ACPI_RESOURCE_MEMORY24; typedef struct acpi_resource_memory32 { UINT8 WriteProtect; UINT32 Minimum; UINT32 Maximum; UINT32 Alignment; UINT32 AddressLength; } ACPI_RESOURCE_MEMORY32; typedef struct acpi_resource_fixed_memory32 { UINT8 WriteProtect; UINT32 Address; UINT32 AddressLength; } ACPI_RESOURCE_FIXED_MEMORY32; typedef struct acpi_memory_attribute { UINT8 WriteProtect; UINT8 Caching; UINT8 RangeType; UINT8 Translation; } ACPI_MEMORY_ATTRIBUTE; typedef struct acpi_io_attribute { UINT8 RangeType; UINT8 Translation; UINT8 TranslationType; UINT8 Reserved1; } ACPI_IO_ATTRIBUTE; typedef union acpi_resource_attribute { ACPI_MEMORY_ATTRIBUTE Mem; ACPI_IO_ATTRIBUTE Io; /* Used for the *WordSpace macros */ UINT8 TypeSpecific; } ACPI_RESOURCE_ATTRIBUTE; typedef struct acpi_resource_label { UINT16 StringLength; char *StringPtr; } ACPI_RESOURCE_LABEL; typedef struct acpi_resource_source { UINT8 Index; UINT16 StringLength; char *StringPtr; } ACPI_RESOURCE_SOURCE; /* Fields common to all address descriptors, 16/32/64 bit */ #define ACPI_RESOURCE_ADDRESS_COMMON \ UINT8 ResourceType; \ UINT8 ProducerConsumer; \ UINT8 Decode; \ UINT8 MinAddressFixed; \ UINT8 MaxAddressFixed; \ ACPI_RESOURCE_ATTRIBUTE Info; typedef struct acpi_address16_attribute { UINT16 Granularity; UINT16 Minimum; UINT16 Maximum; UINT16 TranslationOffset; UINT16 AddressLength; } ACPI_ADDRESS16_ATTRIBUTE; typedef struct acpi_address32_attribute { UINT32 Granularity; UINT32 Minimum; UINT32 Maximum; UINT32 TranslationOffset; UINT32 AddressLength; } ACPI_ADDRESS32_ATTRIBUTE; typedef struct acpi_address64_attribute { UINT64 Granularity; UINT64 Minimum; UINT64 Maximum; UINT64 TranslationOffset; UINT64 AddressLength; } ACPI_ADDRESS64_ATTRIBUTE; typedef struct acpi_resource_address { ACPI_RESOURCE_ADDRESS_COMMON } ACPI_RESOURCE_ADDRESS; typedef struct acpi_resource_address16 { ACPI_RESOURCE_ADDRESS_COMMON ACPI_ADDRESS16_ATTRIBUTE Address; ACPI_RESOURCE_SOURCE ResourceSource; } ACPI_RESOURCE_ADDRESS16; typedef struct acpi_resource_address32 { ACPI_RESOURCE_ADDRESS_COMMON ACPI_ADDRESS32_ATTRIBUTE Address; ACPI_RESOURCE_SOURCE ResourceSource; } ACPI_RESOURCE_ADDRESS32; typedef struct acpi_resource_address64 { ACPI_RESOURCE_ADDRESS_COMMON ACPI_ADDRESS64_ATTRIBUTE Address; ACPI_RESOURCE_SOURCE ResourceSource; } ACPI_RESOURCE_ADDRESS64; typedef struct acpi_resource_extended_address64 { ACPI_RESOURCE_ADDRESS_COMMON UINT8 RevisionID; ACPI_ADDRESS64_ATTRIBUTE Address; UINT64 TypeSpecific; } ACPI_RESOURCE_EXTENDED_ADDRESS64; typedef struct acpi_resource_extended_irq { UINT8 ProducerConsumer; UINT8 Triggering; UINT8 Polarity; UINT8 Shareable; UINT8 WakeCapable; UINT8 InterruptCount; ACPI_RESOURCE_SOURCE ResourceSource; UINT32 Interrupts[1]; } ACPI_RESOURCE_EXTENDED_IRQ; typedef struct acpi_resource_generic_register { UINT8 SpaceId; UINT8 BitWidth; UINT8 BitOffset; UINT8 AccessSize; UINT64 Address; } ACPI_RESOURCE_GENERIC_REGISTER; typedef struct acpi_resource_gpio { UINT8 RevisionId; UINT8 ConnectionType; UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */ UINT8 PinConfig; UINT8 Shareable; /* For values, see Interrupt Attributes above */ UINT8 WakeCapable; /* For values, see Interrupt Attributes above */ UINT8 IoRestriction; UINT8 Triggering; /* For values, see Interrupt Attributes above */ UINT8 Polarity; /* For values, see Interrupt Attributes above */ UINT16 DriveStrength; UINT16 DebounceTimeout; UINT16 PinTableLength; UINT16 VendorLength; ACPI_RESOURCE_SOURCE ResourceSource; UINT16 *PinTable; UINT8 *VendorData; } ACPI_RESOURCE_GPIO; /* Values for GPIO ConnectionType field above */ #define ACPI_RESOURCE_GPIO_TYPE_INT 0 #define ACPI_RESOURCE_GPIO_TYPE_IO 1 /* Values for PinConfig field above */ #define ACPI_PIN_CONFIG_DEFAULT 0 #define ACPI_PIN_CONFIG_PULLUP 1 #define ACPI_PIN_CONFIG_PULLDOWN 2 #define ACPI_PIN_CONFIG_NOPULL 3 /* Values for IoRestriction field above */ #define ACPI_IO_RESTRICT_NONE 0 #define ACPI_IO_RESTRICT_INPUT 1 #define ACPI_IO_RESTRICT_OUTPUT 2 #define ACPI_IO_RESTRICT_NONE_PRESERVE 3 /* Common structure for I2C, SPI, and UART serial descriptors */ #define ACPI_RESOURCE_SERIAL_COMMON \ UINT8 RevisionId; \ UINT8 Type; \ UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */\ UINT8 SlaveMode; \ UINT8 ConnectionSharing; \ UINT8 TypeRevisionId; \ UINT16 TypeDataLength; \ UINT16 VendorLength; \ ACPI_RESOURCE_SOURCE ResourceSource; \ UINT8 *VendorData; typedef struct acpi_resource_common_serialbus { ACPI_RESOURCE_SERIAL_COMMON } ACPI_RESOURCE_COMMON_SERIALBUS; /* Values for the Type field above */ #define ACPI_RESOURCE_SERIAL_TYPE_I2C 1 #define ACPI_RESOURCE_SERIAL_TYPE_SPI 2 #define ACPI_RESOURCE_SERIAL_TYPE_UART 3 /* Values for SlaveMode field above */ #define ACPI_CONTROLLER_INITIATED 0 #define ACPI_DEVICE_INITIATED 1 typedef struct acpi_resource_i2c_serialbus { ACPI_RESOURCE_SERIAL_COMMON UINT8 AccessMode; UINT16 SlaveAddress; UINT32 ConnectionSpeed; } ACPI_RESOURCE_I2C_SERIALBUS; /* Values for AccessMode field above */ #define ACPI_I2C_7BIT_MODE 0 #define ACPI_I2C_10BIT_MODE 1 typedef struct acpi_resource_spi_serialbus { ACPI_RESOURCE_SERIAL_COMMON UINT8 WireMode; UINT8 DevicePolarity; UINT8 DataBitLength; UINT8 ClockPhase; UINT8 ClockPolarity; UINT16 DeviceSelection; UINT32 ConnectionSpeed; } ACPI_RESOURCE_SPI_SERIALBUS; /* Values for WireMode field above */ #define ACPI_SPI_4WIRE_MODE 0 #define ACPI_SPI_3WIRE_MODE 1 /* Values for DevicePolarity field above */ #define ACPI_SPI_ACTIVE_LOW 0 #define ACPI_SPI_ACTIVE_HIGH 1 /* Values for ClockPhase field above */ #define ACPI_SPI_FIRST_PHASE 0 #define ACPI_SPI_SECOND_PHASE 1 /* Values for ClockPolarity field above */ #define ACPI_SPI_START_LOW 0 #define ACPI_SPI_START_HIGH 1 typedef struct acpi_resource_uart_serialbus { ACPI_RESOURCE_SERIAL_COMMON UINT8 Endian; UINT8 DataBits; UINT8 StopBits; UINT8 FlowControl; UINT8 Parity; UINT8 LinesEnabled; UINT16 RxFifoSize; UINT16 TxFifoSize; UINT32 DefaultBaudRate; } ACPI_RESOURCE_UART_SERIALBUS; /* Values for Endian field above */ #define ACPI_UART_LITTLE_ENDIAN 0 #define ACPI_UART_BIG_ENDIAN 1 /* Values for DataBits field above */ #define ACPI_UART_5_DATA_BITS 0 #define ACPI_UART_6_DATA_BITS 1 #define ACPI_UART_7_DATA_BITS 2 #define ACPI_UART_8_DATA_BITS 3 #define ACPI_UART_9_DATA_BITS 4 /* Values for StopBits field above */ #define ACPI_UART_NO_STOP_BITS 0 #define ACPI_UART_1_STOP_BIT 1 #define ACPI_UART_1P5_STOP_BITS 2 #define ACPI_UART_2_STOP_BITS 3 /* Values for FlowControl field above */ #define ACPI_UART_FLOW_CONTROL_NONE 0 #define ACPI_UART_FLOW_CONTROL_HW 1 #define ACPI_UART_FLOW_CONTROL_XON_XOFF 2 /* Values for Parity field above */ #define ACPI_UART_PARITY_NONE 0 #define ACPI_UART_PARITY_EVEN 1 #define ACPI_UART_PARITY_ODD 2 #define ACPI_UART_PARITY_MARK 3 #define ACPI_UART_PARITY_SPACE 4 /* Values for LinesEnabled bitfield above */ #define ACPI_UART_CARRIER_DETECT (1<<2) #define ACPI_UART_RING_INDICATOR (1<<3) #define ACPI_UART_DATA_SET_READY (1<<4) #define ACPI_UART_DATA_TERMINAL_READY (1<<5) #define ACPI_UART_CLEAR_TO_SEND (1<<6) #define ACPI_UART_REQUEST_TO_SEND (1<<7) typedef struct acpi_resource_pin_function { UINT8 RevisionId; UINT8 PinConfig; UINT8 Shareable; /* For values, see Interrupt Attributes above */ UINT16 FunctionNumber; UINT16 PinTableLength; UINT16 VendorLength; ACPI_RESOURCE_SOURCE ResourceSource; UINT16 *PinTable; UINT8 *VendorData; } ACPI_RESOURCE_PIN_FUNCTION; typedef struct acpi_resource_pin_config { UINT8 RevisionId; UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */ UINT8 Shareable; /* For values, see Interrupt Attributes above */ UINT8 PinConfigType; UINT32 PinConfigValue; UINT16 PinTableLength; UINT16 VendorLength; ACPI_RESOURCE_SOURCE ResourceSource; UINT16 *PinTable; UINT8 *VendorData; } ACPI_RESOURCE_PIN_CONFIG; /* Values for PinConfigType field above */ #define ACPI_PIN_CONFIG_DEFAULT 0 #define ACPI_PIN_CONFIG_BIAS_PULL_UP 1 #define ACPI_PIN_CONFIG_BIAS_PULL_DOWN 2 #define ACPI_PIN_CONFIG_BIAS_DEFAULT 3 #define ACPI_PIN_CONFIG_BIAS_DISABLE 4 #define ACPI_PIN_CONFIG_BIAS_HIGH_IMPEDANCE 5 #define ACPI_PIN_CONFIG_BIAS_BUS_HOLD 6 #define ACPI_PIN_CONFIG_DRIVE_OPEN_DRAIN 7 #define ACPI_PIN_CONFIG_DRIVE_OPEN_SOURCE 8 #define ACPI_PIN_CONFIG_DRIVE_PUSH_PULL 9 #define ACPI_PIN_CONFIG_DRIVE_STRENGTH 10 #define ACPI_PIN_CONFIG_SLEW_RATE 11 #define ACPI_PIN_CONFIG_INPUT_DEBOUNCE 12 #define ACPI_PIN_CONFIG_INPUT_SCHMITT_TRIGGER 13 typedef struct acpi_resource_pin_group { UINT8 RevisionId; UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */ UINT16 PinTableLength; UINT16 VendorLength; UINT16 *PinTable; ACPI_RESOURCE_LABEL ResourceLabel; UINT8 *VendorData; } ACPI_RESOURCE_PIN_GROUP; typedef struct acpi_resource_pin_group_function { UINT8 RevisionId; UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */ UINT8 Shareable; /* For values, see Interrupt Attributes above */ UINT16 FunctionNumber; UINT16 VendorLength; ACPI_RESOURCE_SOURCE ResourceSource; ACPI_RESOURCE_LABEL ResourceSourceLabel; UINT8 *VendorData; } ACPI_RESOURCE_PIN_GROUP_FUNCTION; typedef struct acpi_resource_pin_group_config { UINT8 RevisionId; UINT8 ProducerConsumer; /* For values, see Producer/Consumer above */ UINT8 Shareable; /* For values, see Interrupt Attributes above */ UINT8 PinConfigType; /* For values, see PinConfigType above */ UINT32 PinConfigValue; UINT16 VendorLength; ACPI_RESOURCE_SOURCE ResourceSource; ACPI_RESOURCE_LABEL ResourceSourceLabel; UINT8 *VendorData; } ACPI_RESOURCE_PIN_GROUP_CONFIG; /* ACPI_RESOURCE_TYPEs */ #define ACPI_RESOURCE_TYPE_IRQ 0 #define ACPI_RESOURCE_TYPE_DMA 1 #define ACPI_RESOURCE_TYPE_START_DEPENDENT 2 #define ACPI_RESOURCE_TYPE_END_DEPENDENT 3 #define ACPI_RESOURCE_TYPE_IO 4 #define ACPI_RESOURCE_TYPE_FIXED_IO 5 #define ACPI_RESOURCE_TYPE_VENDOR 6 #define ACPI_RESOURCE_TYPE_END_TAG 7 #define ACPI_RESOURCE_TYPE_MEMORY24 8 #define ACPI_RESOURCE_TYPE_MEMORY32 9 #define ACPI_RESOURCE_TYPE_FIXED_MEMORY32 10 #define ACPI_RESOURCE_TYPE_ADDRESS16 11 #define ACPI_RESOURCE_TYPE_ADDRESS32 12 #define ACPI_RESOURCE_TYPE_ADDRESS64 13 #define ACPI_RESOURCE_TYPE_EXTENDED_ADDRESS64 14 /* ACPI 3.0 */ #define ACPI_RESOURCE_TYPE_EXTENDED_IRQ 15 #define ACPI_RESOURCE_TYPE_GENERIC_REGISTER 16 #define ACPI_RESOURCE_TYPE_GPIO 17 /* ACPI 5.0 */ #define ACPI_RESOURCE_TYPE_FIXED_DMA 18 /* ACPI 5.0 */ #define ACPI_RESOURCE_TYPE_SERIAL_BUS 19 /* ACPI 5.0 */ #define ACPI_RESOURCE_TYPE_PIN_FUNCTION 20 /* ACPI 6.2 */ #define ACPI_RESOURCE_TYPE_PIN_CONFIG 21 /* ACPI 6.2 */ #define ACPI_RESOURCE_TYPE_PIN_GROUP 22 /* ACPI 6.2 */ #define ACPI_RESOURCE_TYPE_PIN_GROUP_FUNCTION 23 /* ACPI 6.2 */ #define ACPI_RESOURCE_TYPE_PIN_GROUP_CONFIG 24 /* ACPI 6.2 */ #define ACPI_RESOURCE_TYPE_MAX 24 /* Master union for resource descriptors */ typedef union acpi_resource_data { ACPI_RESOURCE_IRQ Irq; ACPI_RESOURCE_DMA Dma; ACPI_RESOURCE_START_DEPENDENT StartDpf; ACPI_RESOURCE_IO Io; ACPI_RESOURCE_FIXED_IO FixedIo; ACPI_RESOURCE_FIXED_DMA FixedDma; ACPI_RESOURCE_VENDOR Vendor; ACPI_RESOURCE_VENDOR_TYPED VendorTyped; ACPI_RESOURCE_END_TAG EndTag; ACPI_RESOURCE_MEMORY24 Memory24; ACPI_RESOURCE_MEMORY32 Memory32; ACPI_RESOURCE_FIXED_MEMORY32 FixedMemory32; ACPI_RESOURCE_ADDRESS16 Address16; ACPI_RESOURCE_ADDRESS32 Address32; ACPI_RESOURCE_ADDRESS64 Address64; ACPI_RESOURCE_EXTENDED_ADDRESS64 ExtAddress64; ACPI_RESOURCE_EXTENDED_IRQ ExtendedIrq; ACPI_RESOURCE_GENERIC_REGISTER GenericReg; ACPI_RESOURCE_GPIO Gpio; ACPI_RESOURCE_I2C_SERIALBUS I2cSerialBus; ACPI_RESOURCE_SPI_SERIALBUS SpiSerialBus; ACPI_RESOURCE_UART_SERIALBUS UartSerialBus; ACPI_RESOURCE_COMMON_SERIALBUS CommonSerialBus; ACPI_RESOURCE_PIN_FUNCTION PinFunction; ACPI_RESOURCE_PIN_CONFIG PinConfig; ACPI_RESOURCE_PIN_GROUP PinGroup; ACPI_RESOURCE_PIN_GROUP_FUNCTION PinGroupFunction; ACPI_RESOURCE_PIN_GROUP_CONFIG PinGroupConfig; /* Common fields */ ACPI_RESOURCE_ADDRESS Address; /* Common 16/32/64 address fields */ } ACPI_RESOURCE_DATA; /* Common resource header */ typedef struct acpi_resource { UINT32 Type; UINT32 Length; ACPI_RESOURCE_DATA Data; } ACPI_RESOURCE; /* restore default alignment */ #pragma pack() #define ACPI_RS_SIZE_NO_DATA 8 /* Id + Length fields */ #define ACPI_RS_SIZE_MIN (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (12) #define ACPI_RS_SIZE(Type) (UINT32) (ACPI_RS_SIZE_NO_DATA + sizeof (Type)) /* Macro for walking resource templates with multiple descriptors */ #define ACPI_NEXT_RESOURCE(Res) \ ACPI_ADD_PTR (ACPI_RESOURCE, (Res), (Res)->Length) typedef struct acpi_pci_routing_table { UINT32 Length; UINT32 Pin; UINT64 Address; /* here for 64-bit alignment */ UINT32 SourceIndex; char Source[4]; /* pad to 64 bits so sizeof() works in all cases */ } ACPI_PCI_ROUTING_TABLE; #endif /* __ACRESTYP_H__ */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/color_defs.h> #include <tilck/kernel/term.h> #include "gfx_chars.h" #pragma GCC diagnostic push const u8 fg_csi_to_vga[256] = { [30] = COLOR_BLACK, [31] = COLOR_RED, [32] = COLOR_GREEN, [33] = COLOR_YELLOW, [34] = COLOR_BLUE, [35] = COLOR_MAGENTA, [36] = COLOR_CYAN, [37] = COLOR_WHITE, [90] = COLOR_BRIGHT_BLACK, [91] = COLOR_BRIGHT_RED, [92] = COLOR_BRIGHT_GREEN, [93] = COLOR_BRIGHT_YELLOW, [94] = COLOR_BRIGHT_BLUE, [95] = COLOR_BRIGHT_MAGENTA, [96] = COLOR_BRIGHT_CYAN, [97] = COLOR_BRIGHT_WHITE, }; #ifdef __clang__ #pragma GCC diagnostic ignored "-Winitializer-overrides" #else #pragma GCC diagnostic ignored "-Woverride-init" #endif /* clang-format off */ const s16 tty_default_trans_table[256] = { [0 ... 31] = -1, /* not translated by default */ [32] = 32, [56] = 56, [80] = 80, [104] = 104, [33] = 33, [57] = 57, [81] = 81, [105] = 105, [34] = 34, [58] = 58, [82] = 82, [106] = 106, [35] = 35, [59] = 59, [83] = 83, [107] = 107, [36] = 36, [60] = 60, [84] = 84, [108] = 108, [37] = 37, [61] = 61, [85] = 85, [109] = 109, [38] = 38, [62] = 62, [86] = 86, [110] = 110, [39] = 39, [63] = 63, [87] = 87, [111] = 111, [40] = 40, [64] = 64, [88] = 88, [112] = 112, [41] = 41, [65] = 65, [89] = 89, [113] = 113, [42] = 42, [66] = 66, [90] = 90, [114] = 114, [43] = 43, [67] = 67, [91] = 91, [115] = 115, [44] = 44, [68] = 68, [92] = 92, [116] = 116, [45] = 45, [69] = 69, [93] = 93, [117] = 117, [46] = 46, [70] = 70, [94] = 94, [118] = 118, [47] = 47, [71] = 71, [95] = 95, [119] = 119, [48] = 48, [72] = 72, [96] = 96, [120] = 120, [49] = 49, [73] = 73, [97] = 97, [121] = 121, [50] = 50, [74] = 74, [98] = 98, [122] = 122, [51] = 51, [75] = 75, [99] = 99, [123] = 123, [52] = 52, [76] = 76, [100] = 100, [124] = 124, [53] = 53, [77] = 77, [101] = 101, [125] = 125, [54] = 54, [78] = 78, [102] = 102, [126] = 126, [55] = 55, [79] = 79, [103] = 103, [127 ... 255] = -1, /* not translated */ }; /* clang-format on */ const s16 tty_gfx_trans_table[256] = { [0 ... 255] = -1, /* not translated by default */ [' '] = ' ', ['l'] = CHAR_ULCORNER, ['m'] = CHAR_LLCORNER, ['k'] = CHAR_URCORNER, ['j'] = CHAR_LRCORNER, ['t'] = CHAR_LTEE, ['u'] = CHAR_RTEE, ['v'] = CHAR_BTEE, ['w'] = CHAR_TTEE, ['q'] = CHAR_HLINE, ['x'] = CHAR_VLINE, ['n'] = CHAR_CROSS, ['`'] = CHAR_DIAMOND, ['a'] = CHAR_BLOCK_MID, ['f'] = CHAR_DEGREE, ['g'] = CHAR_PLMINUS, ['~'] = CHAR_BULLET, [','] = CHAR_LARROW, ['+'] = CHAR_RARROW, ['.'] = CHAR_DARROW, ['-'] = CHAR_UARROW, ['h'] = CHAR_BLOCK_LIGHT, ['0'] = CHAR_BLOCK_HEAVY, }; #pragma GCC diagnostic pop <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set( KERNEL_NOARCH_SOURCES_GLOB "${CMAKE_SOURCE_DIR}/kernel/*.c" "${CMAKE_SOURCE_DIR}/kernel/*.cpp" "${CMAKE_SOURCE_DIR}/kernel/*/*.c" "${CMAKE_SOURCE_DIR}/kernel/*/*.cpp" "${CMAKE_SOURCE_DIR}/kernel/fs/*/*.c" "${CMAKE_SOURCE_DIR}/kernel/fs/*/*.cpp" "${CMAKE_SOURCE_DIR}/common/*.c" "${CMAKE_SOURCE_DIR}/common/*.cpp" "${CMAKE_SOURCE_DIR}/common/3rd_party/datetime.c" "${CMAKE_SOURCE_DIR}/common/3rd_party/crc32.c" ) if (KERNEL_SELFTESTS) list( APPEND KERNEL_NOARCH_SOURCES_GLOB "${CMAKE_SOURCE_DIR}/tests/self/*.c" ) endif() file(GLOB KERNEL_NOARCH_SOURCES ${GLOB_CONF_DEP} ${KERNEL_NOARCH_SOURCES_GLOB}) <file_sep>FROM debian:stable-slim ENV DEBIAN_FRONTEND=noninteractive RUN apt update && apt upgrade -y RUN apt-get install sudo <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/paging.h> #include "gdt_int.h" void load_ldt(u32 entry_index_in_gdt, u32 dpl) { ASSERT(!are_interrupts_enabled()); asmVolatile("lldt %w0" : /* no output */ : "q" (X86_SELECTOR(entry_index_in_gdt, TABLE_GDT, dpl)) : "memory"); } <file_sep> /* SPDX-License-Identifier: BSD-2-Clause */ extern "C" { #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/test/itoa.h> extern const s8 digit_to_val[128]; } #include <tilck/common/cpputils.h> #define DIGITS "0123456789abcdef" template <typename T> void __uitoa_fixed(T value, char *buf) { u32 j = sizeof(value) * 8 - 4; char *ptr = buf; for (u32 i = 0; i < sizeof(value) * 2; i++, j-=4) { *ptr++ = DIGITS[(value >> j) & 0xf]; } *ptr = 0; } template <typename T> void __itoa(T svalue, char *buf, int base) { typedef typename unsigned_type<T>::type U; /* same as T, if T is unsigned */ ASSERT(IN_RANGE_INC(base, 2, 16)); char *ptr = buf; if (svalue == 0) { *ptr++ = DIGITS[0]; *ptr = 0; return; } /* If U == T, svalue >= 0 will always be true, at compile time */ U value = svalue >= 0 ? (U) svalue : (U) -svalue; while (value) { *ptr++ = DIGITS[value % (U)base]; value /= (U)base; } /* If U == T, svalue < 0 will always be false, at compile time */ if (svalue < 0) *ptr++ = '-'; *ptr = 0; str_reverse(buf, (size_t)ptr - (size_t)buf); } static inline bool is_valid_digit(u8 d, int base) { return d < 128 && IN_RANGE(digit_to_val[d], 0, base); } template<typename T> T __tilck_strtol(const char *str, const char **endptr, int base, int *error) { T next, res = 0, sign = 1; const char *p; bool overflow; ASSERT(IN_RANGE_INC(base, 2, 16)); if (error) *error = 0; if (!is_unsigned<T>::val) { if (*str == '-') { sign = (T) -1; str++; } } for (p = str; *p; p++) { u8 up = (u8)*p; if (!is_valid_digit(up, base)) break; if (is_unsigned<T>::val) { next = res * (T)base + (T)digit_to_val[up]; overflow = next < res; } else { next = res * (T)base + sign * (T)digit_to_val[up]; overflow = (sign > 0) != (next >= 0); } if (overflow) { if (error) *error = -ERANGE; if (endptr) *endptr = str; return 0; // signed int overflow } res = next; } if (p == str && error) *error = -EINVAL; if (endptr) *endptr = p; return res; } extern "C" { long tilck_strtol(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<long>(s, endptr, base, err); } void uitoa32_hex_fixed(u32 value, char *buf) { __uitoa_fixed(value, buf); } void uitoa64_hex_fixed(u64 value, char *buf) { __uitoa_fixed(value, buf); } void uitoaN_hex_fixed(ulong value, char *buf) { __uitoa_fixed(value, buf); } void itoa32(s32 value, char *buf) { __itoa(value, buf, 10); } void itoa64(s64 value, char *buf) { __itoa(value, buf, 10); } void itoaN(long value, char *buf) { __itoa(value, buf, 10); } void uitoa32(u32 value, char *buf, int base) { __itoa(value, buf, base); } void uitoa64(u64 value, char *buf, int base) { __itoa(value, buf, base); } void uitoaN(ulong value, char *buf, int base) { __itoa(value, buf, base); } #ifdef __TILCK_KERNEL__ /* * No other reason for this #ifdef except to avoid unnecessary code-bloat * in the legacy bootloader. */ ulong tilck_strtoul(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<ulong>(s, endptr, base, err); } #ifdef KERNEL_TEST s32 tilck_strtol32(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<s32>(s, endptr, base, err); } u32 tilck_strtoul32(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<u32>(s, endptr, base, err); } s64 tilck_strtol64(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<s64>(s, endptr, base, err); } u64 tilck_strtoul64(const char *s, const char **endptr, int base, int *err) { return __tilck_strtol<u64>(s, endptr, base, err); } #endif // #ifdef KERNEL_TEST #endif // #ifdef __TILCK_KERNEL__ #if defined(__TILCK_KERNEL__) && !defined(KERNEL_TEST) long strtol(const char *s, char **endptr, int base) { return tilck_strtol(s, (const char **)endptr, base, NULL); } ulong strtoul(const char *s, char **endptr, int base) { return tilck_strtoul(s, (const char **)endptr, base, NULL); } #endif } // extern "C" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <tilck/kernel/process.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/hal.h> extern const char *x86_exception_names[32]; void asm_enable_osxsave(void); void asm_enable_sse(void); void asm_enable_avx(void); static void handle_no_coproc_fault(regs_t *r); #define CPU_FXSAVE_AREA_SIZE 512 /* * NOTE: calculating the exact area save area for XSAVE is tricky since it * depends on the features currently supported by the CPU (it is necessary * to iterate with CPUID calls to do the right calculation). For the moment, * just using a large buffer is a good-enough solution. * * TODO (future): calculate the exact size for the XSAVE area. */ #define CPU_XSAVE_AREA_SIZE 8192 static bool enable_sse(void) { u32 res = fault_resumable_call(ALL_FAULTS_MASK, &asm_enable_sse, 0); if (res) { u32 n = get_first_set_bit_index32(res); printk("CPU: Enable SSE failed: fault %i [%s]\n", n, x86_exception_names[n]); return false; } const char *max_sse = "SSE 1"; x86_cpu_features.can_use_sse = true; if (x86_cpu_features.edx1.sse2) { x86_cpu_features.can_use_sse2 = true; max_sse = "SSE 2"; } if (x86_cpu_features.ecx1.sse3) max_sse = "SSE 3"; if (x86_cpu_features.ecx1.ssse3) max_sse = "SSE 3+ (ssse 3)"; if (x86_cpu_features.ecx1.sse4_1) { max_sse = "SSE 4.1"; x86_cpu_features.can_use_sse4_1 = true; } if (x86_cpu_features.ecx1.sse4_2) max_sse = "SSE 4.2"; printk("CPU: %s enabled\n", max_sse); return true; } static bool enable_osxsave(void) { u32 res = fault_resumable_call(ALL_FAULTS_MASK, &asm_enable_osxsave, 0); if (res) { u32 n = get_first_set_bit_index32(res); printk("CPU: Enable OSXSAVE failed: fault %i [%s]\n", n, x86_exception_names[n]); return false; } return true; } static bool enable_avx(void) { u32 res = fault_resumable_call(ALL_FAULTS_MASK, &asm_enable_avx, 0); if (res) { u32 n = get_first_set_bit_index32(res); printk("CPU: Enable AVX failed: fault %i [%s]\n", n, x86_exception_names[n]); return false; } x86_cpu_features.can_use_avx = true; if (x86_cpu_features.avx2) { x86_cpu_features.can_use_avx2 = true; printk("CPU: AVX 2 enabled\n"); } else { printk("CPU: AVX 1 enabled\n"); } return true; } void init_pat(void) { u64 pat = rdmsr(MSR_IA32_PAT); u8 *entries = (u8 *)&pat; entries[7] = MEM_TYPE_WC; wrmsr(MSR_IA32_PAT, pat); printk("CPU: PAT initialized\n"); } void enable_cpu_features(void) { if (!x86_cpu_features.initialized) get_cpu_features(); if (x86_cpu_features.edx1.sse && x86_cpu_features.edx1.fxsr) { if (!enable_sse()) goto out; } if (x86_cpu_features.ecx1.xsave) { if (!enable_osxsave()) goto out; if (x86_cpu_features.ecx1.avx) if (!enable_avx()) goto out; } out: /* * Disable the FPU (any access to any x87 FPU/MMX/SSE/AVX register). * * 1. This prevents the kernel to access any such register unintentionally * (without using fpu_context_begin/fpu_context_end to save the regs). * * 2. This prevents user space to access any such register without the * kernel knowing about it. When FPU regs are used with TS = 0, the * CPU triggers a "No coprocessor" fault. If the kernel wants to allow * this to happen[1], it will set a flag in the struct task struct, * enable the FPU and resume the process (thread) as if nothing * happened (like for the COW case). Otherwise, the kernel will send * a SIGFPE to the "guilty" process. * * NOTES * ---------------- * [1] In Tilck, we'll allow user space FPU only in the case at least FXSAVE * is available (=> SSE is available). This makes Tilck simpler allowing us * to not having to save the "legacy x87 FPU" context using the "legacy FPU" * instructions. The newer FXSAVE and XSAVE save everything, including the * "legacy x87 FPU" state. */ hw_fpu_disable(); set_fault_handler(FAULT_NO_COPROC, handle_no_coproc_fault); if (x86_cpu_features.edx1.mtrr) enable_mtrr(); if (x86_cpu_features.edx1.pat) init_pat(); printk("CPU: Physical addr bits: %u\n", x86_cpu_features.phys_addr_bits); } static char fpu_kernel_regs[CPU_XSAVE_AREA_SIZE] ALIGNED_AT(64); void save_current_fpu_regs(bool in_kernel) { if (UNLIKELY(!x86_cpu_features.can_use_sse)) return; if (UNLIKELY(in_panic())) return; arch_task_members_t *arch_fields = get_task_arch_fields(get_curr_task()); void *buf = in_kernel ? fpu_kernel_regs : arch_fields->aligned_fpu_regs; ASSERT(buf != NULL); if (x86_cpu_features.can_use_avx) { /* * In eax:edx we're supposed to specific which reg sets to save/restore * using a bitmask. Setting all bits to 1 works well to save/restore * "everything". */ asmVolatile("xsave (%0)" : /* no output */ : "r" (buf), "a" (-1), "d" (-1) : /* no clobber */); } else { asmVolatile("fxsave (%0)" : /* no output */ : "r" (buf) : /* no clobber */); } } void restore_fpu_regs(void *task, bool in_kernel) { if (UNLIKELY(!x86_cpu_features.can_use_sse)) return; if (UNLIKELY(in_panic())) return; arch_task_members_t *arch_fields = get_task_arch_fields((struct task *)task); void *buf = in_kernel ? fpu_kernel_regs : arch_fields->aligned_fpu_regs; ASSERT(buf != NULL); if (x86_cpu_features.can_use_avx) { asmVolatile("xrstor (%0)" : /* no output */ : "r" (buf), "a" (-1), "d" (-1) : /* no clobber */); } else { asmVolatile("fxrstor (%0)" : /* no output */ : "r" (buf) : /* no clobber */); } } void restore_current_fpu_regs(bool in_kernel) { restore_fpu_regs(get_curr_task(), in_kernel); } bool allocate_fpu_regs(arch_task_members_t *arch_fields) { ASSERT(arch_fields->aligned_fpu_regs == NULL); if (x86_cpu_features.can_use_avx) { arch_fields->aligned_fpu_regs = aligned_kmalloc(CPU_XSAVE_AREA_SIZE, 8 * sizeof(void *)); arch_fields->fpu_regs_size = CPU_XSAVE_AREA_SIZE; } else { arch_fields->aligned_fpu_regs = aligned_kmalloc(CPU_FXSAVE_AREA_SIZE, 4 * sizeof(void *)); arch_fields->fpu_regs_size = CPU_FXSAVE_AREA_SIZE; } if (!arch_fields->aligned_fpu_regs) return false; bzero(arch_fields->aligned_fpu_regs, arch_fields->fpu_regs_size); return true; } static void handle_no_coproc_fault(regs_t *r) { if (is_kernel_thread(get_curr_task())) { panic("FPU instructions used in kernel outside an fpu_context!"); } if (!x86_cpu_features.can_use_sse) { /* * TODO: send to the current process SIGFPE in this case. * * Probably for a long time, we won't support the use of legacy x87 FPU * instructions, in case the CPU is so old that it does not have SSE. * The reason is just to avoid implementing save/restore FPU registers * with x87 instructions. We already need to have 2 implementations: * for SSE (FXSAVE) and for AVX (XSAVE). Better avoid a 3rd one useful * only for machines produced before 1998. */ panic("x87 FPU instructions not supported on CPUs without SSE"); } arch_task_members_t *arch_fields = get_task_arch_fields(get_curr_task()); ASSERT(!(r->custom_flags & REGS_FL_FPU_ENABLED)); #if FORK_NO_COW ASSERT(arch_fields->aligned_fpu_regs != NULL); /* * With the current implementation, even when the aligned_fpu_regs are * pre-allocated tasks cannot by default use the FPU. This approach has PROs * and CONs. * * PROs: * - the kernel doesn't have to save/restore unnecessarily the FPU ctx * - tasks using the FPU can be distinguished from the others * - it is simpler to make aligned_fpu_regs pre-allocated work this way * * CONs: * - paying the overhead of a not-strictly necessary fault, once. */ #else /* * We can hit this fault at MOST once in the lifetime of a task. These * sanity checks ensures that, in no case, we allocated the aligned_fpu_regs * and then, for any reason, we scheduled the task with FPU disabled. */ ASSERT(arch_fields->aligned_fpu_regs == NULL); if (!allocate_fpu_regs(arch_fields)) { panic("Cannot allocate memory for the FPU context"); } #endif r->custom_flags |= REGS_FL_FPU_ENABLED; } static volatile bool in_fpu_context; void fpu_context_begin(void) { disable_preemption(); /* NOTE: nested FPU contexts are NOT allowed (unless we're in panic) */ if (LIKELY(!in_panic())) { ASSERT(!in_fpu_context); } in_fpu_context = true; hw_fpu_enable(); save_current_fpu_regs(true); } void fpu_context_end(void) { ASSERT(in_fpu_context); restore_current_fpu_regs(true); hw_fpu_disable(); in_fpu_context = false; enable_preemption(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> /* Limit is 20 bit */ #define GDT_LIMIT_MAX (0x000FFFFF) /* GDT 'flags' (4 bits) */ #define GDT_GRAN_4KB (1 << 3) #define GDT_GRAN_BYTE (0) #define GDT_32BIT (1 << 2) #define GDT_16BIT (0) /* GDT 'access' flags (8 bits) */ #define GDT_ACCESS_ACC (1 << 0) /* * Accessed bit. The CPU sets it to 1 when * the segment is accessed. */ #define GDT_ACCESS_RW (1 << 1) /* * For code segments it means readable, * otherwise the segment is unreadable. * [code segments cannot be writable.] * * For data segments, it means writable. */ #define GDT_ACCESS_DC (1 << 2) /* * Direction/Conforming bit * * For data segments: direction. * 0 the segment grows up (regular) * 1 the segment grown down * * For code segments: conforming. * * 0 the code can be executed only from * the ring set in PL. * * 1 the code can be executed also from * a lower priv. level. E.g. code in * ring 3 can far-jump to conforming * code in ring 2. */ #define GDT_ACCESS_EX (1 << 3) /* * Executable bit. * 0 means a data segment * 1 means a code segment */ #define GDT_ACCESS_S (1 << 4) /* * Descriptor type. * 0 means system (e.g. TSS, LDT) * 1 means regular (code/data) */ #define GDT_ACCESS_PL0 (0 << 5) /* Ring 0 */ #define GDT_ACCESS_PL1 (1 << 5) /* Ring 1 */ #define GDT_ACCESS_PL2 (2 << 5) /* Ring 2 */ #define GDT_ACCESS_PL3 (3 << 5) /* Ring 3 */ #define GDT_ACCESS_PRESENT (1 << 7) /* Must be set for valid segments */ #define GDT_DESC_TYPE_TSS (GDT_ACCESS_PRESENT | GDT_ACCESS_EX | GDT_ACCESS_ACC) #define GDT_DESC_TYPE_LDT (GDT_ACCESS_PRESENT | GDT_ACCESS_RW) /* An useful shortcut for saving some space */ #define GDT_ACC_REG (GDT_ACCESS_PRESENT | GDT_ACCESS_S) struct gdt_entry { u16 limit_low; u16 base_low; u8 base_middle; union { struct { u8 type: 4; /* EX + DC + RW + ACC */ u8 s : 1; /* 0 = system desc, 1 = regular desc */ u8 dpl : 2; /* desc privilege level */ u8 p : 1; /* present */ }; u8 access; }; union { struct { u8 lim_high: 4; u8 avl : 1; /* available bit */ u8 l : 1; /* 64-bit segment (IA-32e only) */ u8 d : 1; /* default operation size. 0 = 16 bit, 1 = 32 bit */ u8 g : 1; /* granularity: 0 = byte, 1 = 4 KB */ }; struct { u8 limit_high: 4; u8 flags: 4; }; }; u8 base_high; } PACKED; #define INVALID_ENTRY_NUM ((u32) -1) #define USER_DESC_FLAGS_EMPTY ((1 << 3) | (1 << 5)) struct user_desc { u32 entry_number; ulong base_addr; u32 limit; union { struct { u32 seg_32bit : 1; /* Controls GDT_32BIT */ u32 contents : 2; /* Controls GDT_ACCESS_DC and GDT_ACCESS_EX */ u32 read_exec_only : 1; /* Controls GDT_ACCESS_RW */ u32 limit_in_pages : 1; /* Controls GDT_GRAN_4KB */ u32 seg_not_present : 1; /* Controls GDT_ACCESS_PRESENT */ u32 useable : 1; u32 ignored : 25; }; u32 flags; }; }; void load_ldt(u32 entry_index_in_gdt, u32 dpl); void gdt_set_entry(struct gdt_entry *e, ulong base, ulong lim, u8 accs, u8 fl); int gdt_add_entry(struct gdt_entry *e); void gdt_clear_entry(u32 index); void gdt_entry_inc_ref_count(u32 n); #define TSS_MAIN 0 #define TSS_DOUBLE_FAULT 1 extern struct tss_entry tss_array[2] ALIGNED_AT(PAGE_SIZE); <file_sep>/****************************************************************************** * * Module Name: psobject - Support for parse objects * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acconvert.h" #include "acnamesp.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psobject") /* Local prototypes */ static ACPI_STATUS AcpiPsGetAmlOpcode ( ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiPsGetAmlOpcode * * PARAMETERS: WalkState - Current state * * RETURN: Status * * DESCRIPTION: Extract the next AML opcode from the input stream. * ******************************************************************************/ static ACPI_STATUS AcpiPsGetAmlOpcode ( ACPI_WALK_STATE *WalkState) { ACPI_ERROR_ONLY (UINT32 AmlOffset); ACPI_FUNCTION_TRACE_PTR (PsGetAmlOpcode, WalkState); WalkState->Aml = WalkState->ParserState.Aml; WalkState->Opcode = AcpiPsPeekOpcode (&(WalkState->ParserState)); /* * First cut to determine what we have found: * 1) A valid AML opcode * 2) A name string * 3) An unknown/invalid opcode */ WalkState->OpInfo = AcpiPsGetOpcodeInfo (WalkState->Opcode); switch (WalkState->OpInfo->Class) { case AML_CLASS_ASCII: case AML_CLASS_PREFIX: /* * Starts with a valid prefix or ASCII char, this is a name * string. Convert the bare name string to a namepath. */ WalkState->Opcode = AML_INT_NAMEPATH_OP; WalkState->ArgTypes = ARGP_NAMESTRING; break; case AML_CLASS_UNKNOWN: /* The opcode is unrecognized. Complain and skip unknown opcodes */ if (WalkState->PassNumber == 2) { ACPI_ERROR_ONLY(AmlOffset = (UINT32) ACPI_PTR_DIFF (WalkState->Aml, WalkState->ParserState.AmlStart)); ACPI_ERROR ((AE_INFO, "Unknown opcode 0x%.2X at table offset 0x%.4X, ignoring", WalkState->Opcode, (UINT32) (AmlOffset + sizeof (ACPI_TABLE_HEADER)))); ACPI_DUMP_BUFFER ((WalkState->ParserState.Aml - 16), 48); #ifdef ACPI_ASL_COMPILER /* * This is executed for the disassembler only. Output goes * to the disassembled ASL output file. */ AcpiOsPrintf ( "/*\nError: Unknown opcode 0x%.2X at table offset 0x%.4X, context:\n", WalkState->Opcode, (UINT32) (AmlOffset + sizeof (ACPI_TABLE_HEADER))); ACPI_ERROR ((AE_INFO, "Aborting disassembly, AML byte code is corrupt")); /* Dump the context surrounding the invalid opcode */ AcpiUtDumpBuffer (((UINT8 *) WalkState->ParserState.Aml - 16), 48, DB_BYTE_DISPLAY, (AmlOffset + sizeof (ACPI_TABLE_HEADER) - 16)); AcpiOsPrintf (" */\n"); /* * Just abort the disassembly, cannot continue because the * parser is essentially lost. The disassembler can then * randomly fail because an ill-constructed parse tree * can result. */ return_ACPI_STATUS (AE_AML_BAD_OPCODE); #endif } /* Increment past one-byte or two-byte opcode */ WalkState->ParserState.Aml++; if (WalkState->Opcode > 0xFF) /* Can only happen if first byte is 0x5B */ { WalkState->ParserState.Aml++; } return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); default: /* Found opcode info, this is a normal opcode */ WalkState->ParserState.Aml += AcpiPsGetOpcodeSize (WalkState->Opcode); WalkState->ArgTypes = WalkState->OpInfo->ParseArgs; break; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsBuildNamedOp * * PARAMETERS: WalkState - Current state * AmlOpStart - Begin of named Op in AML * UnnamedOp - Early Op (not a named Op) * Op - Returned Op * * RETURN: Status * * DESCRIPTION: Parse a named Op * ******************************************************************************/ ACPI_STATUS AcpiPsBuildNamedOp ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT *UnnamedOp, ACPI_PARSE_OBJECT **Op) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg = NULL; ACPI_FUNCTION_TRACE_PTR (PsBuildNamedOp, WalkState); UnnamedOp->Common.Value.Arg = NULL; UnnamedOp->Common.ArgListLength = 0; UnnamedOp->Common.AmlOpcode = WalkState->Opcode; /* * Get and append arguments until we find the node that contains * the name (the type ARGP_NAME). */ while (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) && (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) != ARGP_NAME)) { ASL_CV_CAPTURE_COMMENTS (WalkState); Status = AcpiPsGetNextArg (WalkState, &(WalkState->ParserState), GET_CURRENT_ARG_TYPE (WalkState->ArgTypes), &Arg); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiPsAppendArg (UnnamedOp, Arg); INCREMENT_ARG_LIST (WalkState->ArgTypes); } /* are there any inline comments associated with the NameSeg?? If so, save this. */ ASL_CV_CAPTURE_COMMENTS (WalkState); #ifdef ACPI_ASL_COMPILER if (AcpiGbl_CurrentInlineComment != NULL) { UnnamedOp->Common.NameComment = AcpiGbl_CurrentInlineComment; AcpiGbl_CurrentInlineComment = NULL; } #endif /* * Make sure that we found a NAME and didn't run out of arguments */ if (!GET_CURRENT_ARG_TYPE (WalkState->ArgTypes)) { return_ACPI_STATUS (AE_AML_NO_OPERAND); } /* We know that this arg is a name, move to next arg */ INCREMENT_ARG_LIST (WalkState->ArgTypes); /* * Find the object. This will either insert the object into * the namespace or simply look it up */ WalkState->Op = NULL; Status = WalkState->DescendingCallback (WalkState, Op); if (ACPI_FAILURE (Status)) { if (Status != AE_CTRL_TERMINATE) { ACPI_EXCEPTION ((AE_INFO, Status, "During name lookup/catalog")); } return_ACPI_STATUS (Status); } if (!*Op) { return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); } Status = AcpiPsNextParseState (WalkState, *Op, Status); if (ACPI_FAILURE (Status)) { if (Status == AE_CTRL_PENDING) { Status = AE_CTRL_PARSE_PENDING; } return_ACPI_STATUS (Status); } AcpiPsAppendArg (*Op, UnnamedOp->Common.Value.Arg); #ifdef ACPI_ASL_COMPILER /* save any comments that might be associated with UnnamedOp. */ (*Op)->Common.InlineComment = UnnamedOp->Common.InlineComment; (*Op)->Common.EndNodeComment = UnnamedOp->Common.EndNodeComment; (*Op)->Common.CloseBraceComment = UnnamedOp->Common.CloseBraceComment; (*Op)->Common.NameComment = UnnamedOp->Common.NameComment; (*Op)->Common.CommentList = UnnamedOp->Common.CommentList; (*Op)->Common.EndBlkComment = UnnamedOp->Common.EndBlkComment; (*Op)->Common.CvFilename = UnnamedOp->Common.CvFilename; (*Op)->Common.CvParentFilename = UnnamedOp->Common.CvParentFilename; (*Op)->Named.Aml = UnnamedOp->Common.Aml; UnnamedOp->Common.InlineComment = NULL; UnnamedOp->Common.EndNodeComment = NULL; UnnamedOp->Common.CloseBraceComment = NULL; UnnamedOp->Common.NameComment = NULL; UnnamedOp->Common.CommentList = NULL; UnnamedOp->Common.EndBlkComment = NULL; #endif if ((*Op)->Common.AmlOpcode == AML_REGION_OP || (*Op)->Common.AmlOpcode == AML_DATA_REGION_OP) { /* * Defer final parsing of an OperationRegion body, because we don't * have enough info in the first pass to parse it correctly (i.e., * there may be method calls within the TermArg elements of the body.) * * However, we must continue parsing because the opregion is not a * standalone package -- we don't know where the end is at this point. * * (Length is unknown until parse of the body complete) */ (*Op)->Named.Data = AmlOpStart; (*Op)->Named.Length = 0; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsCreateOp * * PARAMETERS: WalkState - Current state * AmlOpStart - Op start in AML * NewOp - Returned Op * * RETURN: Status * * DESCRIPTION: Get Op from AML * ******************************************************************************/ ACPI_STATUS AcpiPsCreateOp ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT **NewOp) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op; ACPI_PARSE_OBJECT *NamedOp = NULL; ACPI_PARSE_OBJECT *ParentScope; UINT8 ArgumentCount; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (PsCreateOp, WalkState); Status = AcpiPsGetAmlOpcode (WalkState); if (Status == AE_CTRL_PARSE_CONTINUE) { return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); } if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Create Op structure and append to parent's argument list */ WalkState->OpInfo = AcpiPsGetOpcodeInfo (WalkState->Opcode); Op = AcpiPsAllocOp (WalkState->Opcode, AmlOpStart); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } if (WalkState->OpInfo->Flags & AML_NAMED) { Status = AcpiPsBuildNamedOp (WalkState, AmlOpStart, Op, &NamedOp); AcpiPsFreeOp (Op); #ifdef ACPI_ASL_COMPILER if (AcpiGbl_DisasmFlag && WalkState->Opcode == AML_EXTERNAL_OP && Status == AE_NOT_FOUND) { /* * If parsing of AML_EXTERNAL_OP's name path fails, then skip * past this opcode and keep parsing. This is a much better * alternative than to abort the entire disassembler. At this * point, the ParserState is at the end of the namepath of the * external declaration opcode. Setting WalkState->Aml to * WalkState->ParserState.Aml + 2 moves increments the * WalkState->Aml past the object type and the paramcount of the * external opcode. */ WalkState->Aml = WalkState->ParserState.Aml + 2; WalkState->ParserState.Aml = WalkState->Aml; return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); } #endif if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } *NewOp = NamedOp; return_ACPI_STATUS (AE_OK); } /* Not a named opcode, just allocate Op and append to parent */ if (WalkState->OpInfo->Flags & AML_CREATE) { /* * Backup to beginning of CreateXXXfield declaration * BodyLength is unknown until we parse the body */ Op->Named.Data = AmlOpStart; Op->Named.Length = 0; } if (WalkState->Opcode == AML_BANK_FIELD_OP) { /* * Backup to beginning of BankField declaration * BodyLength is unknown until we parse the body */ Op->Named.Data = AmlOpStart; Op->Named.Length = 0; } ParentScope = AcpiPsGetParentScope (&(WalkState->ParserState)); AcpiPsAppendArg (ParentScope, Op); if (ParentScope) { OpInfo = AcpiPsGetOpcodeInfo (ParentScope->Common.AmlOpcode); if (OpInfo->Flags & AML_HAS_TARGET) { ArgumentCount = AcpiPsGetArgumentCount (OpInfo->Type); if (ParentScope->Common.ArgListLength > ArgumentCount) { Op->Common.Flags |= ACPI_PARSEOP_TARGET; } } /* * Special case for both Increment() and Decrement(), where * the lone argument is both a source and a target. */ else if ((ParentScope->Common.AmlOpcode == AML_INCREMENT_OP) || (ParentScope->Common.AmlOpcode == AML_DECREMENT_OP)) { Op->Common.Flags |= ACPI_PARSEOP_TARGET; } } if (WalkState->DescendingCallback != NULL) { /* * Find the object. This will either insert the object into * the namespace or simply look it up */ WalkState->Op = *NewOp = Op; Status = WalkState->DescendingCallback (WalkState, &Op); Status = AcpiPsNextParseState (WalkState, Op, Status); if (Status == AE_CTRL_PENDING) { Status = AE_CTRL_PARSE_PENDING; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiPsCompleteOp * * PARAMETERS: WalkState - Current state * Op - Returned Op * Status - Parse status before complete Op * * RETURN: Status * * DESCRIPTION: Complete Op * ******************************************************************************/ ACPI_STATUS AcpiPsCompleteOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **Op, ACPI_STATUS Status) { ACPI_STATUS Status2; ACPI_FUNCTION_TRACE_PTR (PsCompleteOp, WalkState); /* * Finished one argument of the containing scope */ WalkState->ParserState.Scope->ParseScope.ArgCount--; /* Close this Op (will result in parse subtree deletion) */ Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } *Op = NULL; switch (Status) { case AE_OK: break; case AE_CTRL_TRANSFER: /* We are about to transfer to a called method */ WalkState->PrevOp = NULL; WalkState->PrevArgTypes = WalkState->ArgTypes; return_ACPI_STATUS (Status); case AE_CTRL_END: AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); if (*Op) { WalkState->Op = *Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo ((*Op)->Common.AmlOpcode); WalkState->Opcode = (*Op)->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); (void) AcpiPsNextParseState (WalkState, *Op, Status); Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } break; case AE_CTRL_BREAK: case AE_CTRL_CONTINUE: /* Pop off scopes until we find the While */ while (!(*Op) || ((*Op)->Common.AmlOpcode != AML_WHILE_OP)) { AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } /* Close this iteration of the While loop */ WalkState->Op = *Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo ((*Op)->Common.AmlOpcode); WalkState->Opcode = (*Op)->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); (void) AcpiPsNextParseState (WalkState, *Op, Status); Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } break; case AE_CTRL_TERMINATE: /* Clean up */ do { if (*Op) { Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } AcpiUtDeleteGenericState ( AcpiUtPopGenericState (&WalkState->ControlState)); } AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (*Op); return_ACPI_STATUS (AE_OK); default: /* All other non-AE_OK status */ do { if (*Op) { /* * These Opcodes need to be removed from the namespace because they * get created even if these opcodes cannot be created due to * errors. */ if (((*Op)->Common.AmlOpcode == AML_REGION_OP) || ((*Op)->Common.AmlOpcode == AML_DATA_REGION_OP)) { AcpiNsDeleteChildren ((*Op)->Common.Node); AcpiNsRemoveNode ((*Op)->Common.Node); (*Op)->Common.Node = NULL; AcpiPsDeleteParseTree (*Op); } Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (*Op); #if 0 /* * TBD: Cleanup parse ops on error */ if (*Op == NULL) { AcpiPsPopScope (ParserState, Op, &WalkState->ArgTypes, &WalkState->ArgCount); } #endif WalkState->PrevOp = NULL; WalkState->PrevArgTypes = WalkState->ArgTypes; if (WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL) { /* * There was something that went wrong while executing code at the * module-level. We need to skip parsing whatever caused the * error and keep going. One runtime error during the table load * should not cause the entire table to not be loaded. This is * because there could be correct AML beyond the parts that caused * the runtime error. */ ACPI_INFO (("Ignoring error and continuing table load")); return_ACPI_STATUS (AE_OK); } return_ACPI_STATUS (Status); } /* This scope complete? */ if (AcpiPsHasCompletedScope (&(WalkState->ParserState))) { AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Popped scope, Op=%p\n", *Op)); } else { *Op = NULL; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsCompleteFinalOp * * PARAMETERS: WalkState - Current state * Op - Current Op * Status - Current parse status before complete last * Op * * RETURN: Status * * DESCRIPTION: Complete last Op. * ******************************************************************************/ ACPI_STATUS AcpiPsCompleteFinalOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_STATUS Status) { ACPI_STATUS Status2; ACPI_FUNCTION_TRACE_PTR (PsCompleteFinalOp, WalkState); /* * Complete the last Op (if not completed), and clear the scope stack. * It is easily possible to end an AML "package" with an unbounded number * of open scopes (such as when several ASL blocks are closed with * sequential closing braces). We want to terminate each one cleanly. */ ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "AML package complete at Op %p\n", Op)); do { if (Op) { if (WalkState->AscendingCallback != NULL) { WalkState->Op = Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); WalkState->Opcode = Op->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); Status = AcpiPsNextParseState (WalkState, Op, Status); if (Status == AE_CTRL_PENDING) { Status = AcpiPsCompleteOp (WalkState, &Op, AE_OK); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } if (Status == AE_CTRL_TERMINATE) { Status = AE_OK; /* Clean up */ do { if (Op) { Status2 = AcpiPsCompleteThisOp (WalkState, Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } AcpiPsPopScope (&(WalkState->ParserState), &Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (Op); return_ACPI_STATUS (Status); } else if (ACPI_FAILURE (Status)) { /* First error is most important */ (void) AcpiPsCompleteThisOp (WalkState, Op); return_ACPI_STATUS (Status); } } Status2 = AcpiPsCompleteThisOp (WalkState, Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } AcpiPsPopScope (&(WalkState->ParserState), &Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (Op); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config header file is generated by CMake * and put in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #cmakedefine01 MOD_sysfs <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/syscalls.h> /* Actual implementation, not a stub: only the root user exists. */ int sys_getuid() { return 0; } /* Actual implementation, not a stub: only the root group exists. */ int sys_getgid() { return 0; } /* Actual implementation, not a stub: only the root user exists. */ int sys_geteuid() { return 0; } /* Actual implementation, not a stub: only the root group exists. */ int sys_getegid() { return 0; } /* Actual implementation, not a stub: only the root user exists. */ int sys_setuid(ulong uid) { if (uid == 0) return 0; return -EINVAL; } /* Actual implementation, not a stub: only the root group exists. */ int sys_setgid(ulong gid) { if (gid == 0) return 0; return -EINVAL; } /* Actual implementation: accept only 0 as UID. */ int sys_setuid16(ulong uid) { return sys_setuid((u16)uid); } /* Actual implementation, not a stub: only the root user exists. */ int sys_getuid16() { return 0; } int sys_setgid16(ulong gid) { return sys_setgid((u16)gid); } /* Actual implementation, not a stub: only the root group exists. */ int sys_getgid16(void) { return 0; } /* Actual implementation, not a stub: only the root user exists. */ int sys_geteuid16(void) { return 0; } /* Actual implementation, not a stub: only the root group exists. */ int sys_getegid16(void) { return 0; } <file_sep>/******************************************************************************* * * Module Name: dbexec - debugger control method execution * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdebug.h" #include "acnamesp.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbexec") static ACPI_DB_METHOD_INFO AcpiGbl_DbMethodInfo; /* Local prototypes */ static ACPI_STATUS AcpiDbExecuteMethod ( ACPI_DB_METHOD_INFO *Info, ACPI_BUFFER *ReturnObj); static ACPI_STATUS AcpiDbExecuteSetup ( ACPI_DB_METHOD_INFO *Info); static UINT32 AcpiDbGetOutstandingAllocations ( void); static void ACPI_SYSTEM_XFACE AcpiDbMethodThread ( void *Context); static ACPI_STATUS AcpiDbExecutionWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); static void ACPI_SYSTEM_XFACE AcpiDbSingleExecutionThread ( void *Context); /******************************************************************************* * * FUNCTION: AcpiDbDeleteObjects * * PARAMETERS: Count - Count of objects in the list * Objects - Array of ACPI_OBJECTs to be deleted * * RETURN: None * * DESCRIPTION: Delete a list of ACPI_OBJECTS. Handles packages and nested * packages via recursion. * ******************************************************************************/ void AcpiDbDeleteObjects ( UINT32 Count, ACPI_OBJECT *Objects) { UINT32 i; for (i = 0; i < Count; i++) { switch (Objects[i].Type) { case ACPI_TYPE_BUFFER: ACPI_FREE (Objects[i].Buffer.Pointer); break; case ACPI_TYPE_PACKAGE: /* Recursive call to delete package elements */ AcpiDbDeleteObjects (Objects[i].Package.Count, Objects[i].Package.Elements); /* Free the elements array */ ACPI_FREE (Objects[i].Package.Elements); break; default: break; } } } /******************************************************************************* * * FUNCTION: AcpiDbExecuteMethod * * PARAMETERS: Info - Valid info segment * ReturnObj - Where to put return object * * RETURN: Status * * DESCRIPTION: Execute a control method. * ******************************************************************************/ static ACPI_STATUS AcpiDbExecuteMethod ( ACPI_DB_METHOD_INFO *Info, ACPI_BUFFER *ReturnObj) { ACPI_STATUS Status; ACPI_OBJECT_LIST ParamObjects; ACPI_OBJECT Params[ACPI_DEBUGGER_MAX_ARGS + 1]; UINT32 i; ACPI_FUNCTION_TRACE (DbExecuteMethod); if (AcpiGbl_DbOutputToFile && !AcpiDbgLevel) { AcpiOsPrintf ("Warning: debug output is not enabled!\n"); } ParamObjects.Count = 0; ParamObjects.Pointer = NULL; /* Pass through any command-line arguments */ if (Info->Args && Info->Args[0]) { /* Get arguments passed on the command line */ for (i = 0; (Info->Args[i] && *(Info->Args[i])); i++) { /* Convert input string (token) to an actual ACPI_OBJECT */ Status = AcpiDbConvertToObject (Info->Types[i], Info->Args[i], &Params[i]); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "While parsing method arguments")); goto Cleanup; } } ParamObjects.Count = i; ParamObjects.Pointer = Params; } /* Prepare for a return object of arbitrary size */ ReturnObj->Pointer = AcpiGbl_DbBuffer; ReturnObj->Length = ACPI_DEBUG_BUFFER_SIZE; /* Do the actual method execution */ AcpiGbl_MethodExecuting = TRUE; Status = AcpiEvaluateObject (NULL, Info->Pathname, &ParamObjects, ReturnObj); AcpiGbl_CmSingleStep = FALSE; AcpiGbl_MethodExecuting = FALSE; if (ACPI_FAILURE (Status)) { if ((Status == AE_ABORT_METHOD) || AcpiGbl_AbortMethod) { /* Clear the abort and fall back to the debugger prompt */ ACPI_EXCEPTION ((AE_INFO, Status, "Aborting top-level method")); AcpiGbl_AbortMethod = FALSE; Status = AE_OK; goto Cleanup; } ACPI_EXCEPTION ((AE_INFO, Status, "while executing %s from AML Debugger", Info->Pathname)); if (Status == AE_BUFFER_OVERFLOW) { ACPI_ERROR ((AE_INFO, "Possible buffer overflow within AML Debugger " "buffer (size 0x%X needed 0x%X)", ACPI_DEBUG_BUFFER_SIZE, (UINT32) ReturnObj->Length)); } } Cleanup: AcpiDbDeleteObjects (ParamObjects.Count, Params); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDbExecuteSetup * * PARAMETERS: Info - Valid method info * * RETURN: None * * DESCRIPTION: Setup info segment prior to method execution * ******************************************************************************/ static ACPI_STATUS AcpiDbExecuteSetup ( ACPI_DB_METHOD_INFO *Info) { ACPI_STATUS Status; ACPI_FUNCTION_NAME (DbExecuteSetup); /* Concatenate the current scope to the supplied name */ Info->Pathname[0] = 0; if ((Info->Name[0] != '\\') && (Info->Name[0] != '/')) { if (AcpiUtSafeStrcat (Info->Pathname, sizeof (Info->Pathname), AcpiGbl_DbScopeBuf)) { Status = AE_BUFFER_OVERFLOW; goto ErrorExit; } } if (AcpiUtSafeStrcat (Info->Pathname, sizeof (Info->Pathname), Info->Name)) { Status = AE_BUFFER_OVERFLOW; goto ErrorExit; } AcpiDbPrepNamestring (Info->Pathname); AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); AcpiOsPrintf ("Evaluating %s\n", Info->Pathname); if (Info->Flags & EX_SINGLE_STEP) { AcpiGbl_CmSingleStep = TRUE; AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } else { /* No single step, allow redirection to a file */ AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); } return (AE_OK); ErrorExit: ACPI_EXCEPTION ((AE_INFO, Status, "During setup for method execution")); return (Status); } #ifdef ACPI_DBG_TRACK_ALLOCATIONS UINT32 AcpiDbGetCacheInfo ( ACPI_MEMORY_LIST *Cache) { return (Cache->TotalAllocated - Cache->TotalFreed - Cache->CurrentDepth); } #endif /******************************************************************************* * * FUNCTION: AcpiDbGetOutstandingAllocations * * PARAMETERS: None * * RETURN: Current global allocation count minus cache entries * * DESCRIPTION: Determine the current number of "outstanding" allocations -- * those allocations that have not been freed and also are not * in one of the various object caches. * ******************************************************************************/ static UINT32 AcpiDbGetOutstandingAllocations ( void) { UINT32 Outstanding = 0; #ifdef ACPI_DBG_TRACK_ALLOCATIONS Outstanding += AcpiDbGetCacheInfo (AcpiGbl_StateCache); Outstanding += AcpiDbGetCacheInfo (AcpiGbl_PsNodeCache); Outstanding += AcpiDbGetCacheInfo (AcpiGbl_PsNodeExtCache); Outstanding += AcpiDbGetCacheInfo (AcpiGbl_OperandCache); #endif return (Outstanding); } /******************************************************************************* * * FUNCTION: AcpiDbExecutionWalk * * PARAMETERS: WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Execute a control method. Name is relative to the current * scope. * ******************************************************************************/ static ACPI_STATUS AcpiDbExecutionWalk ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_NAMESPACE_NODE *Node = (ACPI_NAMESPACE_NODE *) ObjHandle; ACPI_BUFFER ReturnObj; ACPI_STATUS Status; ObjDesc = AcpiNsGetAttachedObject (Node); if (ObjDesc->Method.ParamCount) { return (AE_OK); } ReturnObj.Pointer = NULL; ReturnObj.Length = ACPI_ALLOCATE_BUFFER; AcpiNsPrintNodePathname (Node, "Evaluating"); /* Do the actual method execution */ AcpiOsPrintf ("\n"); AcpiGbl_MethodExecuting = TRUE; Status = AcpiEvaluateObject (Node, NULL, NULL, &ReturnObj); AcpiOsPrintf ("Evaluation of [%4.4s] returned %s\n", AcpiUtGetNodeName (Node), AcpiFormatException (Status)); AcpiGbl_MethodExecuting = FALSE; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDbExecute * * PARAMETERS: Name - Name of method to execute * Args - Parameters to the method * Types - * Flags - single step/no single step * * RETURN: None * * DESCRIPTION: Execute a control method. Name is relative to the current * scope. * ******************************************************************************/ void AcpiDbExecute ( char *Name, char **Args, ACPI_OBJECT_TYPE *Types, UINT32 Flags) { ACPI_STATUS Status; ACPI_BUFFER ReturnObj; char *NameString; #ifdef ACPI_DEBUG_OUTPUT UINT32 PreviousAllocations; UINT32 Allocations; #endif /* * Allow one execution to be performed by debugger or single step * execution will be dead locked by the interpreter mutexes. */ if (AcpiGbl_MethodExecuting) { AcpiOsPrintf ("Only one debugger execution is allowed.\n"); return; } #ifdef ACPI_DEBUG_OUTPUT /* Memory allocation tracking */ PreviousAllocations = AcpiDbGetOutstandingAllocations (); #endif if (*Name == '*') { (void) AcpiWalkNamespace (ACPI_TYPE_METHOD, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbExecutionWalk, NULL, NULL, NULL); return; } NameString = ACPI_ALLOCATE (strlen (Name) + 1); if (!NameString) { return; } memset (&AcpiGbl_DbMethodInfo, 0, sizeof (ACPI_DB_METHOD_INFO)); strcpy (NameString, Name); AcpiUtStrupr (NameString); /* Subcommand to Execute all predefined names in the namespace */ if (!strncmp (NameString, "PREDEF", 6)) { AcpiDbEvaluatePredefinedNames (); ACPI_FREE (NameString); return; } AcpiGbl_DbMethodInfo.Name = NameString; AcpiGbl_DbMethodInfo.Args = Args; AcpiGbl_DbMethodInfo.Types = Types; AcpiGbl_DbMethodInfo.Flags = Flags; ReturnObj.Pointer = NULL; ReturnObj.Length = ACPI_ALLOCATE_BUFFER; Status = AcpiDbExecuteSetup (&AcpiGbl_DbMethodInfo); if (ACPI_FAILURE (Status)) { ACPI_FREE (NameString); return; } /* Get the NS node, determines existence also */ Status = AcpiGetHandle (NULL, AcpiGbl_DbMethodInfo.Pathname, &AcpiGbl_DbMethodInfo.Method); if (ACPI_SUCCESS (Status)) { Status = AcpiDbExecuteMethod (&AcpiGbl_DbMethodInfo, &ReturnObj); } ACPI_FREE (NameString); /* * Allow any handlers in separate threads to complete. * (Such as Notify handlers invoked from AML executed above). */ AcpiOsSleep ((UINT64) 10); #ifdef ACPI_DEBUG_OUTPUT /* Memory allocation tracking */ Allocations = AcpiDbGetOutstandingAllocations () - PreviousAllocations; AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); if (Allocations > 0) { AcpiOsPrintf ( "0x%X Outstanding allocations after evaluation of %s\n", Allocations, AcpiGbl_DbMethodInfo.Pathname); } #endif if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Evaluation of %s failed with status %s\n", AcpiGbl_DbMethodInfo.Pathname, AcpiFormatException (Status)); } else { /* Display a return object, if any */ if (ReturnObj.Length) { AcpiOsPrintf ( "Evaluation of %s returned object %p, " "external buffer length %X\n", AcpiGbl_DbMethodInfo.Pathname, ReturnObj.Pointer, (UINT32) ReturnObj.Length); AcpiDbDumpExternalObject (ReturnObj.Pointer, 1); /* Dump a _PLD buffer if present */ if (ACPI_COMPARE_NAMESEG ((ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, AcpiGbl_DbMethodInfo.Method)->Name.Ascii), METHOD_NAME__PLD)) { AcpiDbDumpPldBuffer (ReturnObj.Pointer); } } else { AcpiOsPrintf ("No object was returned from evaluation of %s\n", AcpiGbl_DbMethodInfo.Pathname); } } AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); } /******************************************************************************* * * FUNCTION: AcpiDbMethodThread * * PARAMETERS: Context - Execution info segment * * RETURN: None * * DESCRIPTION: Debugger execute thread. Waits for a command line, then * simply dispatches it. * ******************************************************************************/ static void ACPI_SYSTEM_XFACE AcpiDbMethodThread ( void *Context) { ACPI_STATUS Status; ACPI_DB_METHOD_INFO *Info = Context; ACPI_DB_METHOD_INFO LocalInfo; UINT32 i; UINT8 Allow; ACPI_BUFFER ReturnObj; /* * AcpiGbl_DbMethodInfo.Arguments will be passed as method arguments. * Prevent AcpiGbl_DbMethodInfo from being modified by multiple threads * concurrently. * * Note: The arguments we are passing are used by the ASL test suite * (aslts). Do not change them without updating the tests. */ (void) AcpiOsWaitSemaphore (Info->InfoGate, 1, ACPI_WAIT_FOREVER); if (Info->InitArgs) { AcpiDbUint32ToHexString (Info->NumCreated, Info->IndexOfThreadStr); AcpiDbUint32ToHexString ((UINT32) AcpiOsGetThreadId (), Info->IdOfThreadStr); } if (Info->Threads && (Info->NumCreated < Info->NumThreads)) { Info->Threads[Info->NumCreated++] = AcpiOsGetThreadId(); } LocalInfo = *Info; LocalInfo.Args = LocalInfo.Arguments; LocalInfo.Arguments[0] = LocalInfo.NumThreadsStr; LocalInfo.Arguments[1] = LocalInfo.IdOfThreadStr; LocalInfo.Arguments[2] = LocalInfo.IndexOfThreadStr; LocalInfo.Arguments[3] = NULL; LocalInfo.Types = LocalInfo.ArgTypes; (void) AcpiOsSignalSemaphore (Info->InfoGate, 1); for (i = 0; i < Info->NumLoops; i++) { Status = AcpiDbExecuteMethod (&LocalInfo, &ReturnObj); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s During evaluation of %s at iteration %X\n", AcpiFormatException (Status), Info->Pathname, i); if (Status == AE_ABORT_METHOD) { break; } } #if 0 if ((i % 100) == 0) { AcpiOsPrintf ("%u loops, Thread 0x%x\n", i, AcpiOsGetThreadId ()); } if (ReturnObj.Length) { AcpiOsPrintf ("Evaluation of %s returned object %p Buflen %X\n", Info->Pathname, ReturnObj.Pointer, (UINT32) ReturnObj.Length); AcpiDbDumpExternalObject (ReturnObj.Pointer, 1); } #endif } /* Signal our completion */ Allow = 0; (void) AcpiOsWaitSemaphore (Info->ThreadCompleteGate, 1, ACPI_WAIT_FOREVER); Info->NumCompleted++; if (Info->NumCompleted == Info->NumThreads) { /* Do signal for main thread once only */ Allow = 1; } (void) AcpiOsSignalSemaphore (Info->ThreadCompleteGate, 1); if (Allow) { Status = AcpiOsSignalSemaphore (Info->MainThreadGate, 1); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ( "Could not signal debugger thread sync semaphore, %s\n", AcpiFormatException (Status)); } } } /******************************************************************************* * * FUNCTION: AcpiDbSingleExecutionThread * * PARAMETERS: Context - Method info struct * * RETURN: None * * DESCRIPTION: Create one thread and execute a method * ******************************************************************************/ static void ACPI_SYSTEM_XFACE AcpiDbSingleExecutionThread ( void *Context) { ACPI_DB_METHOD_INFO *Info = Context; ACPI_STATUS Status; ACPI_BUFFER ReturnObj; AcpiOsPrintf ("\n"); Status = AcpiDbExecuteMethod (Info, &ReturnObj); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s During evaluation of %s\n", AcpiFormatException (Status), Info->Pathname); return; } /* Display a return object, if any */ if (ReturnObj.Length) { AcpiOsPrintf ("Evaluation of %s returned object %p, " "external buffer length %X\n", AcpiGbl_DbMethodInfo.Pathname, ReturnObj.Pointer, (UINT32) ReturnObj.Length); AcpiDbDumpExternalObject (ReturnObj.Pointer, 1); } AcpiOsPrintf ("\nBackground thread completed\n%c ", ACPI_DEBUGGER_COMMAND_PROMPT); } /******************************************************************************* * * FUNCTION: AcpiDbCreateExecutionThread * * PARAMETERS: MethodNameArg - Control method to execute * Arguments - Array of arguments to the method * Types - Corresponding array of object types * * RETURN: None * * DESCRIPTION: Create a single thread to evaluate a namespace object. Handles * arguments passed on command line for control methods. * ******************************************************************************/ void AcpiDbCreateExecutionThread ( char *MethodNameArg, char **Arguments, ACPI_OBJECT_TYPE *Types) { ACPI_STATUS Status; UINT32 i; memset (&AcpiGbl_DbMethodInfo, 0, sizeof (ACPI_DB_METHOD_INFO)); AcpiGbl_DbMethodInfo.Name = MethodNameArg; AcpiGbl_DbMethodInfo.InitArgs = 1; AcpiGbl_DbMethodInfo.Args = AcpiGbl_DbMethodInfo.Arguments; AcpiGbl_DbMethodInfo.Types = AcpiGbl_DbMethodInfo.ArgTypes; /* Setup method arguments, up to 7 (0-6) */ for (i = 0; (i < ACPI_METHOD_NUM_ARGS) && *Arguments; i++) { AcpiGbl_DbMethodInfo.Arguments[i] = *Arguments; Arguments++; AcpiGbl_DbMethodInfo.ArgTypes[i] = *Types; Types++; } Status = AcpiDbExecuteSetup (&AcpiGbl_DbMethodInfo); if (ACPI_FAILURE (Status)) { return; } /* Get the NS node, determines existence also */ Status = AcpiGetHandle (NULL, AcpiGbl_DbMethodInfo.Pathname, &AcpiGbl_DbMethodInfo.Method); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s Could not get handle for %s\n", AcpiFormatException (Status), AcpiGbl_DbMethodInfo.Pathname); return; } Status = AcpiOsExecute (OSL_DEBUGGER_EXEC_THREAD, AcpiDbSingleExecutionThread, &AcpiGbl_DbMethodInfo); if (ACPI_FAILURE (Status)) { return; } AcpiOsPrintf ("\nBackground thread started\n"); } /******************************************************************************* * * FUNCTION: AcpiDbCreateExecutionThreads * * PARAMETERS: NumThreadsArg - Number of threads to create * NumLoopsArg - Loop count for the thread(s) * MethodNameArg - Control method to execute * * RETURN: None * * DESCRIPTION: Create threads to execute method(s) * ******************************************************************************/ void AcpiDbCreateExecutionThreads ( char *NumThreadsArg, char *NumLoopsArg, char *MethodNameArg) { ACPI_STATUS Status; UINT32 NumThreads; UINT32 NumLoops; UINT32 i; UINT32 Size; ACPI_MUTEX MainThreadGate; ACPI_MUTEX ThreadCompleteGate; ACPI_MUTEX InfoGate; /* Get the arguments */ NumThreads = strtoul (NumThreadsArg, NULL, 0); NumLoops = strtoul (NumLoopsArg, NULL, 0); if (!NumThreads || !NumLoops) { AcpiOsPrintf ("Bad argument: Threads %X, Loops %X\n", NumThreads, NumLoops); return; } /* * Create the semaphore for synchronization of * the created threads with the main thread. */ Status = AcpiOsCreateSemaphore (1, 0, &MainThreadGate); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not create semaphore for " "synchronization with the main thread, %s\n", AcpiFormatException (Status)); return; } /* * Create the semaphore for synchronization * between the created threads. */ Status = AcpiOsCreateSemaphore (1, 1, &ThreadCompleteGate); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not create semaphore for " "synchronization between the created threads, %s\n", AcpiFormatException (Status)); (void) AcpiOsDeleteSemaphore (MainThreadGate); return; } Status = AcpiOsCreateSemaphore (1, 1, &InfoGate); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not create semaphore for " "synchronization of AcpiGbl_DbMethodInfo, %s\n", AcpiFormatException (Status)); (void) AcpiOsDeleteSemaphore (ThreadCompleteGate); (void) AcpiOsDeleteSemaphore (MainThreadGate); return; } memset (&AcpiGbl_DbMethodInfo, 0, sizeof (ACPI_DB_METHOD_INFO)); /* Array to store IDs of threads */ AcpiGbl_DbMethodInfo.NumThreads = NumThreads; Size = sizeof (ACPI_THREAD_ID) * AcpiGbl_DbMethodInfo.NumThreads; AcpiGbl_DbMethodInfo.Threads = AcpiOsAllocate (Size); if (AcpiGbl_DbMethodInfo.Threads == NULL) { AcpiOsPrintf ("No memory for thread IDs array\n"); (void) AcpiOsDeleteSemaphore (MainThreadGate); (void) AcpiOsDeleteSemaphore (ThreadCompleteGate); (void) AcpiOsDeleteSemaphore (InfoGate); return; } memset (AcpiGbl_DbMethodInfo.Threads, 0, Size); /* Setup the context to be passed to each thread */ AcpiGbl_DbMethodInfo.Name = MethodNameArg; AcpiGbl_DbMethodInfo.Flags = 0; AcpiGbl_DbMethodInfo.NumLoops = NumLoops; AcpiGbl_DbMethodInfo.MainThreadGate = MainThreadGate; AcpiGbl_DbMethodInfo.ThreadCompleteGate = ThreadCompleteGate; AcpiGbl_DbMethodInfo.InfoGate = InfoGate; /* Init arguments to be passed to method */ AcpiGbl_DbMethodInfo.InitArgs = 1; AcpiGbl_DbMethodInfo.Args = AcpiGbl_DbMethodInfo.Arguments; AcpiGbl_DbMethodInfo.Arguments[0] = AcpiGbl_DbMethodInfo.NumThreadsStr; AcpiGbl_DbMethodInfo.Arguments[1] = AcpiGbl_DbMethodInfo.IdOfThreadStr; AcpiGbl_DbMethodInfo.Arguments[2] = AcpiGbl_DbMethodInfo.IndexOfThreadStr; AcpiGbl_DbMethodInfo.Arguments[3] = NULL; AcpiGbl_DbMethodInfo.Types = AcpiGbl_DbMethodInfo.ArgTypes; AcpiGbl_DbMethodInfo.ArgTypes[0] = ACPI_TYPE_INTEGER; AcpiGbl_DbMethodInfo.ArgTypes[1] = ACPI_TYPE_INTEGER; AcpiGbl_DbMethodInfo.ArgTypes[2] = ACPI_TYPE_INTEGER; AcpiDbUint32ToHexString (NumThreads, AcpiGbl_DbMethodInfo.NumThreadsStr); Status = AcpiDbExecuteSetup (&AcpiGbl_DbMethodInfo); if (ACPI_FAILURE (Status)) { goto CleanupAndExit; } /* Get the NS node, determines existence also */ Status = AcpiGetHandle (NULL, AcpiGbl_DbMethodInfo.Pathname, &AcpiGbl_DbMethodInfo.Method); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("%s Could not get handle for %s\n", AcpiFormatException (Status), AcpiGbl_DbMethodInfo.Pathname); goto CleanupAndExit; } /* Create the threads */ AcpiOsPrintf ("Creating %X threads to execute %X times each\n", NumThreads, NumLoops); for (i = 0; i < (NumThreads); i++) { Status = AcpiOsExecute (OSL_DEBUGGER_EXEC_THREAD, AcpiDbMethodThread, &AcpiGbl_DbMethodInfo); if (ACPI_FAILURE (Status)) { break; } } /* Wait for all threads to complete */ (void) AcpiOsWaitSemaphore (MainThreadGate, 1, ACPI_WAIT_FOREVER); AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT); AcpiOsPrintf ("All threads (%X) have completed\n", NumThreads); AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT); CleanupAndExit: /* Cleanup and exit */ (void) AcpiOsDeleteSemaphore (MainThreadGate); (void) AcpiOsDeleteSemaphore (ThreadCompleteGate); (void) AcpiOsDeleteSemaphore (InfoGate); AcpiOsFree (AcpiGbl_DbMethodInfo.Threads); AcpiGbl_DbMethodInfo.Threads = NULL; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_debug.h> #include <tilck/common/atomics.h> #include <tilck/kernel/list.h> #include <tilck/kernel/hal_types.h> void set_fault_handler(int fault, void *ptr); static ALWAYS_INLINE bool in_irq(void) { extern ATOMIC(int) __in_irq_count; return atomic_load_explicit(&__in_irq_count, mo_relaxed) > 0; } #if KRN_TRACK_NESTED_INTERR void check_not_in_irq_handler(void); void check_in_irq_handler(void); void push_nested_interrupt(int int_num); void pop_nested_interrupt(void); void nested_interrupts_drop_top_syscall(void); void panic_dump_nested_interrupts(void); void check_in_no_other_irq_than_timer(void); bool in_nested_irq_num(int irq_num); #else static inline void check_not_in_irq_handler(void) { } static inline void check_in_irq_handler(void) { } static inline void push_nested_interrupt(int int_num) { } static inline void pop_nested_interrupt(void) { } static inline void nested_interrupts_drop_top_syscall(void) { } static inline void panic_dump_nested_interrupts(void) { } static inline void check_in_no_other_irq_than_timer(void) { } static inline bool in_nested_irq_num(int irq_num) { NOT_REACHED(); } #endif <file_sep>/******************************************************************************* * * Module Name: hwregs - Read/write access functions for the various ACPI * control and status registers. * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acevents.h" #define _COMPONENT ACPI_HARDWARE ACPI_MODULE_NAME ("hwregs") #if (!ACPI_REDUCED_HARDWARE) /* Local Prototypes */ static UINT8 AcpiHwGetAccessBitWidth ( UINT64 Address, ACPI_GENERIC_ADDRESS *Reg, UINT8 MaxBitWidth); static ACPI_STATUS AcpiHwReadMultiple ( UINT32 *Value, ACPI_GENERIC_ADDRESS *RegisterA, ACPI_GENERIC_ADDRESS *RegisterB); static ACPI_STATUS AcpiHwWriteMultiple ( UINT32 Value, ACPI_GENERIC_ADDRESS *RegisterA, ACPI_GENERIC_ADDRESS *RegisterB); #endif /* !ACPI_REDUCED_HARDWARE */ /****************************************************************************** * * FUNCTION: AcpiHwGetAccessBitWidth * * PARAMETERS: Address - GAS register address * Reg - GAS register structure * MaxBitWidth - Max BitWidth supported (32 or 64) * * RETURN: Status * * DESCRIPTION: Obtain optimal access bit width * ******************************************************************************/ static UINT8 AcpiHwGetAccessBitWidth ( UINT64 Address, ACPI_GENERIC_ADDRESS *Reg, UINT8 MaxBitWidth) { UINT8 AccessBitWidth; /* * GAS format "register", used by FADT: * 1. Detected if BitOffset is 0 and BitWidth is 8/16/32/64; * 2. AccessSize field is ignored and BitWidth field is used for * determining the boundary of the IO accesses. * GAS format "region", used by APEI registers: * 1. Detected if BitOffset is not 0 or BitWidth is not 8/16/32/64; * 2. AccessSize field is used for determining the boundary of the * IO accesses; * 3. BitOffset/BitWidth fields are used to describe the "region". * * Note: This algorithm assumes that the "Address" fields should always * contain aligned values. */ if (!Reg->BitOffset && Reg->BitWidth && ACPI_IS_POWER_OF_TWO (Reg->BitWidth) && ACPI_IS_ALIGNED (Reg->BitWidth, 8)) { AccessBitWidth = Reg->BitWidth; } else if (Reg->AccessWidth) { AccessBitWidth = ACPI_ACCESS_BIT_WIDTH (Reg->AccessWidth); } else { AccessBitWidth = ACPI_ROUND_UP_POWER_OF_TWO_8 ( Reg->BitOffset + Reg->BitWidth); if (AccessBitWidth <= 8) { AccessBitWidth = 8; } else { while (!ACPI_IS_ALIGNED (Address, AccessBitWidth >> 3)) { AccessBitWidth >>= 1; } } } /* Maximum IO port access bit width is 32 */ if (Reg->SpaceId == ACPI_ADR_SPACE_SYSTEM_IO) { MaxBitWidth = 32; } /* * Return access width according to the requested maximum access bit width, * as the caller should know the format of the register and may enforce * a 32-bit accesses. */ if (AccessBitWidth < MaxBitWidth) { return (AccessBitWidth); } return (MaxBitWidth); } /****************************************************************************** * * FUNCTION: AcpiHwValidateRegister * * PARAMETERS: Reg - GAS register structure * MaxBitWidth - Max BitWidth supported (32 or 64) * Address - Pointer to where the gas->address * is returned * * RETURN: Status * * DESCRIPTION: Validate the contents of a GAS register. Checks the GAS * pointer, Address, SpaceId, BitWidth, and BitOffset. * ******************************************************************************/ ACPI_STATUS AcpiHwValidateRegister ( ACPI_GENERIC_ADDRESS *Reg, UINT8 MaxBitWidth, UINT64 *Address) { UINT8 BitWidth; UINT8 AccessWidth; /* Must have a valid pointer to a GAS structure */ if (!Reg) { return (AE_BAD_PARAMETER); } /* * Copy the target address. This handles possible alignment issues. * Address must not be null. A null address also indicates an optional * ACPI register that is not supported, so no error message. */ ACPI_MOVE_64_TO_64 (Address, &Reg->Address); if (!(*Address)) { return (AE_BAD_ADDRESS); } /* Validate the SpaceID */ if ((Reg->SpaceId != ACPI_ADR_SPACE_SYSTEM_MEMORY) && (Reg->SpaceId != ACPI_ADR_SPACE_SYSTEM_IO)) { ACPI_ERROR ((AE_INFO, "Unsupported address space: 0x%X", Reg->SpaceId)); return (AE_SUPPORT); } /* Validate the AccessWidth */ if (Reg->AccessWidth > 4) { ACPI_ERROR ((AE_INFO, "Unsupported register access width: 0x%X", Reg->AccessWidth)); return (AE_SUPPORT); } /* Validate the BitWidth, convert AccessWidth into number of bits */ AccessWidth = AcpiHwGetAccessBitWidth (*Address, Reg, MaxBitWidth); BitWidth = ACPI_ROUND_UP (Reg->BitOffset + Reg->BitWidth, AccessWidth); if (MaxBitWidth < BitWidth) { ACPI_WARNING ((AE_INFO, "Requested bit width 0x%X is smaller than register bit width 0x%X", MaxBitWidth, BitWidth)); return (AE_SUPPORT); } return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiHwRead * * PARAMETERS: Value - Where the value is returned * Reg - GAS register structure * * RETURN: Status * * DESCRIPTION: Read from either memory or IO space. This is a 64-bit max * version of AcpiRead. * * LIMITATIONS: <These limitations also apply to AcpiHwWrite> * SpaceID must be SystemMemory or SystemIO. * ******************************************************************************/ ACPI_STATUS AcpiHwRead ( UINT64 *Value, ACPI_GENERIC_ADDRESS *Reg) { UINT64 Address; UINT8 AccessWidth; UINT32 BitWidth; UINT8 BitOffset; UINT64 Value64; UINT32 Value32; UINT8 Index; ACPI_STATUS Status; ACPI_FUNCTION_NAME (HwRead); /* Validate contents of the GAS register */ Status = AcpiHwValidateRegister (Reg, 64, &Address); if (ACPI_FAILURE (Status)) { return (Status); } /* * Initialize entire 64-bit return value to zero, convert AccessWidth * into number of bits based */ *Value = 0; AccessWidth = AcpiHwGetAccessBitWidth (Address, Reg, 64); BitWidth = Reg->BitOffset + Reg->BitWidth; BitOffset = Reg->BitOffset; /* * Two address spaces supported: Memory or IO. PCI_Config is * not supported here because the GAS structure is insufficient */ Index = 0; while (BitWidth) { if (BitOffset >= AccessWidth) { Value64 = 0; BitOffset -= AccessWidth; } else { if (Reg->SpaceId == ACPI_ADR_SPACE_SYSTEM_MEMORY) { Status = AcpiOsReadMemory ((ACPI_PHYSICAL_ADDRESS) Address + Index * ACPI_DIV_8 (AccessWidth), &Value64, AccessWidth); } else /* ACPI_ADR_SPACE_SYSTEM_IO, validated earlier */ { Status = AcpiHwReadPort ((ACPI_IO_ADDRESS) Address + Index * ACPI_DIV_8 (AccessWidth), &Value32, AccessWidth); Value64 = (UINT64) Value32; } } /* * Use offset style bit writes because "Index * AccessWidth" is * ensured to be less than 64-bits by AcpiHwValidateRegister(). */ ACPI_SET_BITS (Value, Index * AccessWidth, ACPI_MASK_BITS_ABOVE_64 (AccessWidth), Value64); BitWidth -= BitWidth > AccessWidth ? AccessWidth : BitWidth; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_IO, "Read: %8.8X%8.8X width %2d from %8.8X%8.8X (%s)\n", ACPI_FORMAT_UINT64 (*Value), AccessWidth, ACPI_FORMAT_UINT64 (Address), AcpiUtGetRegionName (Reg->SpaceId))); return (Status); } /****************************************************************************** * * FUNCTION: AcpiHwWrite * * PARAMETERS: Value - Value to be written * Reg - GAS register structure * * RETURN: Status * * DESCRIPTION: Write to either memory or IO space. This is a 64-bit max * version of AcpiWrite. * ******************************************************************************/ ACPI_STATUS AcpiHwWrite ( UINT64 Value, ACPI_GENERIC_ADDRESS *Reg) { UINT64 Address; UINT8 AccessWidth; UINT32 BitWidth; UINT8 BitOffset; UINT64 Value64; UINT8 Index; ACPI_STATUS Status; ACPI_FUNCTION_NAME (HwWrite); /* Validate contents of the GAS register */ Status = AcpiHwValidateRegister (Reg, 64, &Address); if (ACPI_FAILURE (Status)) { return (Status); } /* Convert AccessWidth into number of bits based */ AccessWidth = AcpiHwGetAccessBitWidth (Address, Reg, 64); BitWidth = Reg->BitOffset + Reg->BitWidth; BitOffset = Reg->BitOffset; /* * Two address spaces supported: Memory or IO. PCI_Config is * not supported here because the GAS structure is insufficient */ Index = 0; while (BitWidth) { /* * Use offset style bit reads because "Index * AccessWidth" is * ensured to be less than 64-bits by AcpiHwValidateRegister(). */ Value64 = ACPI_GET_BITS (&Value, Index * AccessWidth, ACPI_MASK_BITS_ABOVE_64 (AccessWidth)); if (BitOffset >= AccessWidth) { BitOffset -= AccessWidth; } else { if (Reg->SpaceId == ACPI_ADR_SPACE_SYSTEM_MEMORY) { Status = AcpiOsWriteMemory ((ACPI_PHYSICAL_ADDRESS) Address + Index * ACPI_DIV_8 (AccessWidth), Value64, AccessWidth); } else /* ACPI_ADR_SPACE_SYSTEM_IO, validated earlier */ { Status = AcpiHwWritePort ((ACPI_IO_ADDRESS) Address + Index * ACPI_DIV_8 (AccessWidth), (UINT32) Value64, AccessWidth); } } /* * Index * AccessWidth is ensured to be less than 32-bits by * AcpiHwValidateRegister(). */ BitWidth -= BitWidth > AccessWidth ? AccessWidth : BitWidth; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_IO, "Wrote: %8.8X%8.8X width %2d to %8.8X%8.8X (%s)\n", ACPI_FORMAT_UINT64 (Value), AccessWidth, ACPI_FORMAT_UINT64 (Address), AcpiUtGetRegionName (Reg->SpaceId))); return (Status); } #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiHwClearAcpiStatus * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Clears all fixed and general purpose status bits * ******************************************************************************/ ACPI_STATUS AcpiHwClearAcpiStatus ( void) { ACPI_STATUS Status; ACPI_CPU_FLAGS LockFlags = 0; ACPI_FUNCTION_TRACE (HwClearAcpiStatus); ACPI_DEBUG_PRINT ((ACPI_DB_IO, "About to write %04X to %8.8X%8.8X\n", ACPI_BITMASK_ALL_FIXED_STATUS, ACPI_FORMAT_UINT64 (AcpiGbl_XPm1aStatus.Address))); LockFlags = AcpiOsAcquireLock (AcpiGbl_HardwareLock); /* Clear the fixed events in PM1 A/B */ Status = AcpiHwRegisterWrite (ACPI_REGISTER_PM1_STATUS, ACPI_BITMASK_ALL_FIXED_STATUS); AcpiOsReleaseLock (AcpiGbl_HardwareLock, LockFlags); if (ACPI_FAILURE (Status)) { goto Exit; } /* Clear the GPE Bits in all GPE registers in all GPE blocks */ Status = AcpiEvWalkGpeList (AcpiHwClearGpeBlock, NULL); Exit: return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiHwGetBitRegisterInfo * * PARAMETERS: RegisterId - Index of ACPI Register to access * * RETURN: The bitmask to be used when accessing the register * * DESCRIPTION: Map RegisterId into a register bitmask. * ******************************************************************************/ ACPI_BIT_REGISTER_INFO * AcpiHwGetBitRegisterInfo ( UINT32 RegisterId) { ACPI_FUNCTION_ENTRY (); if (RegisterId > ACPI_BITREG_MAX) { ACPI_ERROR ((AE_INFO, "Invalid BitRegister ID: 0x%X", RegisterId)); return (NULL); } return (&AcpiGbl_BitRegisterInfo[RegisterId]); } /****************************************************************************** * * FUNCTION: AcpiHwWritePm1Control * * PARAMETERS: Pm1aControl - Value to be written to PM1A control * Pm1bControl - Value to be written to PM1B control * * RETURN: Status * * DESCRIPTION: Write the PM1 A/B control registers. These registers are * different than than the PM1 A/B status and enable registers * in that different values can be written to the A/B registers. * Most notably, the SLP_TYP bits can be different, as per the * values returned from the _Sx predefined methods. * ******************************************************************************/ ACPI_STATUS AcpiHwWritePm1Control ( UINT32 Pm1aControl, UINT32 Pm1bControl) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (HwWritePm1Control); Status = AcpiHwWrite (Pm1aControl, &AcpiGbl_FADT.XPm1aControlBlock); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (AcpiGbl_FADT.XPm1bControlBlock.Address) { Status = AcpiHwWrite (Pm1bControl, &AcpiGbl_FADT.XPm1bControlBlock); } return_ACPI_STATUS (Status); } /****************************************************************************** * * FUNCTION: AcpiHwRegisterRead * * PARAMETERS: RegisterId - ACPI Register ID * ReturnValue - Where the register value is returned * * RETURN: Status and the value read. * * DESCRIPTION: Read from the specified ACPI register * ******************************************************************************/ ACPI_STATUS AcpiHwRegisterRead ( UINT32 RegisterId, UINT32 *ReturnValue) { UINT32 Value = 0; UINT64 Value64; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (HwRegisterRead); switch (RegisterId) { case ACPI_REGISTER_PM1_STATUS: /* PM1 A/B: 16-bit access each */ Status = AcpiHwReadMultiple (&Value, &AcpiGbl_XPm1aStatus, &AcpiGbl_XPm1bStatus); break; case ACPI_REGISTER_PM1_ENABLE: /* PM1 A/B: 16-bit access each */ Status = AcpiHwReadMultiple (&Value, &AcpiGbl_XPm1aEnable, &AcpiGbl_XPm1bEnable); break; case ACPI_REGISTER_PM1_CONTROL: /* PM1 A/B: 16-bit access each */ Status = AcpiHwReadMultiple (&Value, &AcpiGbl_FADT.XPm1aControlBlock, &AcpiGbl_FADT.XPm1bControlBlock); /* * Zero the write-only bits. From the ACPI specification, "Hardware * Write-Only Bits": "Upon reads to registers with write-only bits, * software masks out all write-only bits." */ Value &= ~ACPI_PM1_CONTROL_WRITEONLY_BITS; break; case ACPI_REGISTER_PM2_CONTROL: /* 8-bit access */ Status = AcpiHwRead (&Value64, &AcpiGbl_FADT.XPm2ControlBlock); if (ACPI_SUCCESS (Status)) { Value = (UINT32) Value64; } break; case ACPI_REGISTER_PM_TIMER: /* 32-bit access */ Status = AcpiHwRead (&Value64, &AcpiGbl_FADT.XPmTimerBlock); if (ACPI_SUCCESS (Status)) { Value = (UINT32) Value64; } break; case ACPI_REGISTER_SMI_COMMAND_BLOCK: /* 8-bit access */ Status = AcpiHwReadPort (AcpiGbl_FADT.SmiCommand, &Value, 8); break; default: ACPI_ERROR ((AE_INFO, "Unknown Register ID: 0x%X", RegisterId)); Status = AE_BAD_PARAMETER; break; } if (ACPI_SUCCESS (Status)) { *ReturnValue = (UINT32) Value; } return_ACPI_STATUS (Status); } /****************************************************************************** * * FUNCTION: AcpiHwRegisterWrite * * PARAMETERS: RegisterId - ACPI Register ID * Value - The value to write * * RETURN: Status * * DESCRIPTION: Write to the specified ACPI register * * NOTE: In accordance with the ACPI specification, this function automatically * preserves the value of the following bits, meaning that these bits cannot be * changed via this interface: * * PM1_CONTROL[0] = SCI_EN * PM1_CONTROL[9] * PM1_STATUS[11] * * ACPI References: * 1) Hardware Ignored Bits: When software writes to a register with ignored * bit fields, it preserves the ignored bit fields * 2) SCI_EN: OSPM always preserves this bit position * ******************************************************************************/ ACPI_STATUS AcpiHwRegisterWrite ( UINT32 RegisterId, UINT32 Value) { ACPI_STATUS Status; UINT32 ReadValue; UINT64 ReadValue64; ACPI_FUNCTION_TRACE (HwRegisterWrite); switch (RegisterId) { case ACPI_REGISTER_PM1_STATUS: /* PM1 A/B: 16-bit access each */ /* * Handle the "ignored" bit in PM1 Status. According to the ACPI * specification, ignored bits are to be preserved when writing. * Normally, this would mean a read/modify/write sequence. However, * preserving a bit in the status register is different. Writing a * one clears the status, and writing a zero preserves the status. * Therefore, we must always write zero to the ignored bit. * * This behavior is clarified in the ACPI 4.0 specification. */ Value &= ~ACPI_PM1_STATUS_PRESERVED_BITS; Status = AcpiHwWriteMultiple (Value, &AcpiGbl_XPm1aStatus, &AcpiGbl_XPm1bStatus); break; case ACPI_REGISTER_PM1_ENABLE: /* PM1 A/B: 16-bit access each */ Status = AcpiHwWriteMultiple (Value, &AcpiGbl_XPm1aEnable, &AcpiGbl_XPm1bEnable); break; case ACPI_REGISTER_PM1_CONTROL: /* PM1 A/B: 16-bit access each */ /* * Perform a read first to preserve certain bits (per ACPI spec) * Note: This includes SCI_EN, we never want to change this bit */ Status = AcpiHwReadMultiple (&ReadValue, &AcpiGbl_FADT.XPm1aControlBlock, &AcpiGbl_FADT.XPm1bControlBlock); if (ACPI_FAILURE (Status)) { goto Exit; } /* Insert the bits to be preserved */ ACPI_INSERT_BITS (Value, ACPI_PM1_CONTROL_PRESERVED_BITS, ReadValue); /* Now we can write the data */ Status = AcpiHwWriteMultiple (Value, &AcpiGbl_FADT.XPm1aControlBlock, &AcpiGbl_FADT.XPm1bControlBlock); break; case ACPI_REGISTER_PM2_CONTROL: /* 8-bit access */ /* * For control registers, all reserved bits must be preserved, * as per the ACPI spec. */ Status = AcpiHwRead (&ReadValue64, &AcpiGbl_FADT.XPm2ControlBlock); if (ACPI_FAILURE (Status)) { goto Exit; } ReadValue = (UINT32) ReadValue64; /* Insert the bits to be preserved */ ACPI_INSERT_BITS (Value, ACPI_PM2_CONTROL_PRESERVED_BITS, ReadValue); Status = AcpiHwWrite (Value, &AcpiGbl_FADT.XPm2ControlBlock); break; case ACPI_REGISTER_PM_TIMER: /* 32-bit access */ Status = AcpiHwWrite (Value, &AcpiGbl_FADT.XPmTimerBlock); break; case ACPI_REGISTER_SMI_COMMAND_BLOCK: /* 8-bit access */ /* SMI_CMD is currently always in IO space */ Status = AcpiHwWritePort (AcpiGbl_FADT.SmiCommand, Value, 8); break; default: ACPI_ERROR ((AE_INFO, "Unknown Register ID: 0x%X", RegisterId)); Status = AE_BAD_PARAMETER; break; } Exit: return_ACPI_STATUS (Status); } /****************************************************************************** * * FUNCTION: AcpiHwReadMultiple * * PARAMETERS: Value - Where the register value is returned * RegisterA - First ACPI register (required) * RegisterB - Second ACPI register (optional) * * RETURN: Status * * DESCRIPTION: Read from the specified two-part ACPI register (such as PM1 A/B) * ******************************************************************************/ static ACPI_STATUS AcpiHwReadMultiple ( UINT32 *Value, ACPI_GENERIC_ADDRESS *RegisterA, ACPI_GENERIC_ADDRESS *RegisterB) { UINT32 ValueA = 0; UINT32 ValueB = 0; UINT64 Value64; ACPI_STATUS Status; /* The first register is always required */ Status = AcpiHwRead (&Value64, RegisterA); if (ACPI_FAILURE (Status)) { return (Status); } ValueA = (UINT32) Value64; /* Second register is optional */ if (RegisterB->Address) { Status = AcpiHwRead (&Value64, RegisterB); if (ACPI_FAILURE (Status)) { return (Status); } ValueB = (UINT32) Value64; } /* * OR the two return values together. No shifting or masking is necessary, * because of how the PM1 registers are defined in the ACPI specification: * * "Although the bits can be split between the two register blocks (each * register block has a unique pointer within the FADT), the bit positions * are maintained. The register block with unimplemented bits (that is, * those implemented in the other register block) always returns zeros, * and writes have no side effects" */ *Value = (ValueA | ValueB); return (AE_OK); } /****************************************************************************** * * FUNCTION: AcpiHwWriteMultiple * * PARAMETERS: Value - The value to write * RegisterA - First ACPI register (required) * RegisterB - Second ACPI register (optional) * * RETURN: Status * * DESCRIPTION: Write to the specified two-part ACPI register (such as PM1 A/B) * ******************************************************************************/ static ACPI_STATUS AcpiHwWriteMultiple ( UINT32 Value, ACPI_GENERIC_ADDRESS *RegisterA, ACPI_GENERIC_ADDRESS *RegisterB) { ACPI_STATUS Status; /* The first register is always required */ Status = AcpiHwWrite (Value, RegisterA); if (ACPI_FAILURE (Status)) { return (Status); } /* * Second register is optional * * No bit shifting or clearing is necessary, because of how the PM1 * registers are defined in the ACPI specification: * * "Although the bits can be split between the two register blocks (each * register block has a unique pointer within the FADT), the bit positions * are maintained. The register block with unimplemented bits (that is, * those implemented in the other register block) always returns zeros, * and writes have no side effects" */ if (RegisterB->Address) { Status = AcpiHwWrite (Value, RegisterB); } return (Status); } #endif /* !ACPI_REDUCED_HARDWARE */ <file_sep>#!/usr/bin/env sh exec objdump -M intel -d --no-show-raw-insn "$1" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once /* * Tilck's virtual file system * * As this project's goals are by far different from the Linux ones, this * layer is expected to different from Linux's. */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/sys_types.h> #include <tilck/kernel/hal_types.h> #include <tilck/kernel/sync.h> struct vfs_dent64 { tilck_ino_t ino; enum vfs_entry_type type; u8 name_len; /* NODE: includes the final '\0' */ const char *name; }; typedef int (*get_dents_func_cb) (struct vfs_dent64 *, void *); /* fs ops */ typedef vfs_inode_ptr_t (*func_get_inode) (fs_handle); typedef void (*func_close) (fs_handle); typedef int (*func_open) (struct vfs_path *, fs_handle *, int, mode_t); typedef int (*func_getdents) (fs_handle, get_dents_func_cb, void *); typedef int (*func_unlink) (struct vfs_path *p); typedef int (*func_mkdir) (struct vfs_path *p, mode_t); typedef int (*func_rmdir) (struct vfs_path *p); typedef int (*func_symlink) (const char *, struct vfs_path *); typedef int (*func_readlink) (struct vfs_path *, char *); typedef int (*func_chmod) (struct mnt_fs *, vfs_inode_ptr_t, mode_t); typedef void (*func_fslock_t) (struct mnt_fs *); typedef int (*func_rr_inode) (struct mnt_fs *, vfs_inode_ptr_t); typedef int (*func_futimens) (struct mnt_fs *, vfs_inode_ptr_t, const struct k_timespec64 times[2]); typedef int (*func_2paths) (struct mnt_fs *, struct vfs_path *, struct vfs_path *); typedef func_2paths func_rename; typedef func_2paths func_link; typedef void (*func_get_entry) (struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t name_len, struct fs_path *fs_path); /* mixed fs/file ops */ typedef int (*func_stat) (struct mnt_fs *, vfs_inode_ptr_t, struct k_stat64 *); typedef int (*func_trunc) (struct mnt_fs *, vfs_inode_ptr_t, offt); typedef int (*func_exlock_noblk) (struct mnt_fs *, vfs_inode_ptr_t); /* file ops */ typedef ssize_t (*func_read) (fs_handle, char *, size_t, offt *); typedef ssize_t (*func_write) (fs_handle, char *, size_t, offt *); typedef offt (*func_seek) (fs_handle, offt, int); typedef int (*func_ioctl) (fs_handle, ulong, void *); typedef int (*func_mmap) (struct user_mapping *, pdir_t *, int); typedef int (*func_munmap) (struct user_mapping *, void *, size_t); typedef bool (*func_handle_fault) (struct user_mapping *, void *, bool, bool); typedef int (*func_rwe_ready) (fs_handle); typedef struct kcond *(*func_get_rwe_cond) (fs_handle); typedef int (*func_on_dup_cb) (fs_handle); typedef ssize_t (*func_readv) (fs_handle, const struct iovec *, int); typedef ssize_t (*func_writev) (fs_handle, const struct iovec *, int); typedef int (*func_fsync) (fs_handle); typedef void (*func_syncfs) (struct mnt_fs *); /* * Operations affecting the file system structure (directories, files, etc.). * * What are the fs-lock functions * --------------------------------- * * The four fs-lock funcs below are supposed to be implemented by each * struct mnt_fs in order to protect its tree structure from races, typically by * using a read-write lock under the hood. Yes, that means that for example two * creat() operations even in separate directories cannot happen at the same * time, on the same FS. But, given that Tilck does NOT support SMP, this * approach not only offers a great simplification, but it actually increases * the overall throughput of the system (fine-grain per-directory locking is * pretty expensive). */ struct fs_ops { func_get_entry get_entry; func_get_inode get_inode; func_open open; func_close on_close; func_close on_close_last_handle; func_on_dup_cb on_dup_cb; func_getdents getdents; func_unlink unlink; func_stat stat; func_mkdir mkdir; func_rmdir rmdir; func_symlink symlink; func_readlink readlink; func_trunc truncate; func_chmod chmod; func_rename rename; func_link link; func_futimens futimens; func_rr_inode retain_inode; func_rr_inode release_inode; func_syncfs syncfs; /* file system structure lock funcs */ func_fslock_t fs_exlock; func_fslock_t fs_exunlock; func_fslock_t fs_shlock; func_fslock_t fs_shunlock; /* per-file lock funcs */ func_exlock_noblk exlock_noblk; /* if NULL -> -ENOLOCK */ func_exlock_noblk exunlock; /* if NULL -> 0 */ }; struct file_ops { /* Main funcs, all optional */ func_read read; /* if NULL -> -EBADF */ func_write write; /* if NULL -> -EBADF */ func_ioctl ioctl; /* if NULL -> -ENOTTY */ func_seek seek; /* if NULL -> -ESPIPE */ func_mmap mmap; /* if NULL -> -ENODEV */ func_munmap munmap; /* if NULL -> -ENODEV */ func_fsync sync; /* if NULL -> -EROFS or 0 */ func_fsync datasync; /* if NULL -> -EROFS or 0 */ func_readv readv; /* if NULL, emulated in non-atomic way */ func_writev writev; /* if NULL, emulated in non-atomic way */ func_handle_fault handle_fault; /* if NULL -> false */ /* * Optional, r/w/e ready funcs * * NOTE[1]: implementing at least the read and write ones is essential in * order to support select() and poll(). * * NOTE[2]: `except` here stands for `unfetched exceptional condition`. */ func_rwe_ready read_ready; /* if NULL, return true */ func_rwe_ready write_ready; /* if NULL, return true */ func_rwe_ready except_ready; /* if NULL, return true */ func_get_rwe_cond get_rready_cond; /* if NULL, return NULL */ func_get_rwe_cond get_wready_cond; /* if NULL, return NULL */ func_get_rwe_cond get_except_cond; /* if NULL, return NULL */ }; int vfs_stat64(const char *path, struct k_stat64 *statbuf, bool res_last_sl); int vfs_open(const char *path, fs_handle *out, int flags, mode_t mode); int vfs_unlink(const char *path); int vfs_mkdir(const char *path, mode_t mode); int vfs_rmdir(const char *path); int vfs_truncate(const char *path, offt length); int vfs_symlink(const char *target, const char *linkpath); int vfs_readlink(const char *path, char *buf); int vfs_chown(const char *path, int owner, int group, bool reslink); int vfs_chmod(const char *path, mode_t mode); int vfs_rename(const char *oldpath, const char *newpath); int vfs_link(const char *oldpath, const char *newpath); int vfs_utimens(const char *path, const struct k_timespec64 times[2]); int vfs_ftruncate(fs_handle h, offt length); int vfs_ioctl(fs_handle h, ulong request, void *argp); int vfs_fstat64(fs_handle h, struct k_stat64 *statbuf); int vfs_getdents64(fs_handle h, struct linux_dirent64 *dirp, u32 bs); int vfs_fchmod(fs_handle h, mode_t mode); int vfs_futimens(fs_handle h, const struct k_timespec64 times[2]); int vfs_fsync(fs_handle h); int vfs_fdatasync(fs_handle h); offt vfs_seek(fs_handle h, offt off, int whence); int vfs_read_ready(fs_handle h); int vfs_write_ready(fs_handle h); int vfs_except_ready(fs_handle h); struct kcond *vfs_get_rready_cond(fs_handle h); struct kcond *vfs_get_wready_cond(fs_handle h); struct kcond *vfs_get_except_cond(fs_handle h); ssize_t vfs_read(fs_handle h, void *buf, size_t buf_size); ssize_t vfs_write(fs_handle h, void *buf, size_t buf_size); ssize_t vfs_readv(fs_handle h, const struct iovec *iov, int iovcnt); ssize_t vfs_writev(fs_handle h, const struct iovec *iov, int iovcnt); ssize_t vfs_pread(fs_handle h, void *buf, size_t buf_size, offt off); ssize_t vfs_pwrite(fs_handle h, void *buf, size_t buf_size, offt off); int vfs_exlock_noblock(struct mnt_fs *fs, vfs_inode_ptr_t i); int vfs_exunlock(struct mnt_fs *fs, vfs_inode_ptr_t i); static inline void vfs_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { fs->fsops->retain_inode(fs, inode); } static inline void vfs_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { fs->fsops->release_inode(fs, inode); } static inline void vfs_retain_inode_at(struct vfs_path *p) { vfs_retain_inode(p->fs, p->fs_path.inode); } static inline void vfs_release_inode_at(struct vfs_path *p) { vfs_release_inode(p->fs, p->fs_path.inode); } static ALWAYS_INLINE struct mnt_fs *get_fs(fs_handle h) { ASSERT(h != NULL); return ((struct fs_handle_base *)h)->fs; } static ALWAYS_INLINE void vfs_get_entry(struct mnt_fs *fs, vfs_inode_ptr_t inode, const char *name, ssize_t name_len, struct fs_path *fs_path) { fs->fsops->get_entry(fs, inode, name, name_len, fs_path); } static ALWAYS_INLINE void vfs_get_root_entry(struct mnt_fs *fs, struct fs_path *fs_path) { vfs_get_entry(fs, NULL, NULL, 0, fs_path); } /* Whole-struct mnt_fs locks */ void vfs_fs_exlock(struct mnt_fs *fs); void vfs_fs_exunlock(struct mnt_fs *fs); void vfs_fs_shlock(struct mnt_fs *fs); void vfs_fs_shunlock(struct mnt_fs *fs); /* --- */ int compute_abs_path(const char *path, const char *str_cwd, char *dest, u32 dest_s); u32 vfs_get_new_device_id(void); struct mnt_fs * create_fs_obj(const char *type, const struct fs_ops *fsops, void *device_data, u32 flags); void destory_fs_obj(struct mnt_fs *fs); fs_handle vfs_alloc_handle(void); fs_handle vfs_alloc_handle_raw(void); /* doesn't zero the data */ void vfs_free_handle(fs_handle h); fs_handle vfs_create_new_handle(struct mnt_fs *fs, const struct file_ops *fops); void vfs_syncfs(struct mnt_fs *fs); void vfs_sync(void); /* ------------ Current mount point interface ------------- */ /* * Resolves `path` and returns in `rp` the corresponding VFS path with the * struct mnt_fs retained and locked, in case of success (return 0). * * In case of failure, it returns a value < 0 and the it does *not* require * any further clean-up. */ int vfs_resolve(const char *path, struct vfs_path *rp, bool exlock, bool res_last_sl); int mp_init(struct mnt_fs *root_fs); int mp_add(struct mnt_fs *fs, const char *target_path); int mp_remove(const char *target_path); struct mnt_fs * mp_get_retained_at(struct mnt_fs *host_fs, vfs_inode_ptr_t inode); struct mnt_fs *mp_get_root(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sched.h> ulong vdso_begin = 0; /* fake value */ void copy_main_tss_on_regs(regs_t *ctx) { NOT_IMPLEMENTED(); } void init_segmentation(void) { NOT_IMPLEMENTED(); } <file_sep>#include <iostream> #include <cstdio> #include <random> #include <vector> #include <gtest/gtest.h> using namespace std; using namespace testing; extern "C" { #include <tilck/kernel/ringbuf.h> } TEST(ringbuf, basicTest) { int buffer[3] = {0}; int values[] = {1,2,3,4}; int val; struct ringbuf rb; bool success; ringbuf_init(&rb, ARRAY_SIZE(buffer), sizeof(buffer[0]), buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); for (int i = 0; i < 3; i++) { success = ringbuf_write_elem(&rb, &values[i]); ASSERT_TRUE(success); } success = ringbuf_write_elem(&rb, &values[3]); ASSERT_FALSE(success); ASSERT_TRUE(ringbuf_is_full(&rb)); for (int i = 0; i < 3; i++) { success = ringbuf_read_elem(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[i]); } success = ringbuf_read_elem(&rb, &val); ASSERT_FALSE(success); ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } TEST(ringbuf, basicTest_1) { u8 buffer[3] = {0}; u8 values[] = {1,2,3,4}; u8 val; struct ringbuf rb; bool success; ringbuf_init(&rb, ARRAY_SIZE(buffer), sizeof(buffer[0]), buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); for (int i = 0; i < 3; i++) { success = ringbuf_write_elem1(&rb, values[i]); ASSERT_TRUE(success); } success = ringbuf_write_elem1(&rb, values[3]); ASSERT_FALSE(success); ASSERT_TRUE(ringbuf_is_full(&rb)); for (int i = 0; i < 3; i++) { success = ringbuf_read_elem1(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[i]); } success = ringbuf_read_elem1(&rb, &val); ASSERT_FALSE(success); ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } TEST(ringbuf, rotation) { int buffer[3] = {0}; int values[] = {1,2,3,4,5,6,7,8,9}; int val; struct ringbuf rb; bool success; ringbuf_init(&rb, ARRAY_SIZE(buffer), sizeof(buffer[0]), buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); /* Fill the buffer */ for (int i = 0; i < 3; i++) { success = ringbuf_write_elem(&rb, &values[i]); ASSERT_TRUE(success); } /* Now read 2 elems */ for (int i = 0; i < 2; i++) { success = ringbuf_read_elem(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[i]); } /* Now write 2 new elems */ for (int i = 0; i < 2; i++) { success = ringbuf_write_elem(&rb, &values[3+i]); ASSERT_TRUE(success); } ASSERT_TRUE(ringbuf_is_full(&rb)); /* Now read the whole buffer */ for (int i = 0; i < 3; i++) { success = ringbuf_read_elem(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[2+i]); } ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } TEST(ringbuf, rotation_1) { u8 buffer[3] = {0}; u8 values[] = {1,2,3,4,5,6,7,8,9}; u8 val; struct ringbuf rb; bool success; ringbuf_init(&rb, ARRAY_SIZE(buffer), sizeof(buffer[0]), buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); /* Fill the buffer */ for (int i = 0; i < 3; i++) { success = ringbuf_write_elem1(&rb, values[i]); ASSERT_TRUE(success); } /* Now read 2 elems */ for (int i = 0; i < 2; i++) { success = ringbuf_read_elem1(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[i]); } /* Now write 2 new elems */ for (int i = 0; i < 2; i++) { success = ringbuf_write_elem1(&rb, values[3+i]); ASSERT_TRUE(success); } ASSERT_TRUE(ringbuf_is_full(&rb)); /* Now read the whole buffer */ for (int i = 0; i < 3; i++) { success = ringbuf_read_elem1(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[2+i]); } ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } TEST(ringbuf, unwrite) { int buffer[3] = {0}; int values[] = {10, 20, 30}; int val; struct ringbuf rb; bool success; ringbuf_init(&rb, ARRAY_SIZE(buffer), sizeof(buffer[0]), buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); /* Fill the buffer */ for (int i = 0; i < 3; i++) { success = ringbuf_write_elem(&rb, &values[i]); ASSERT_TRUE(success); } ASSERT_TRUE(ringbuf_is_full(&rb)); for (int i = 2; i >= 0; i--) { success = ringbuf_unwrite_elem(&rb, &val); ASSERT_TRUE(success); ASSERT_EQ(val, values[i]) << "[FAIL for i: " << i << "]"; } success = ringbuf_unwrite_elem(&rb, &val); ASSERT_FALSE(success); ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } TEST(ringbuf, read_write_bytes) { struct ringbuf rb; char buffer[9] = "--------"; char rbuf[9] = {0}; u32 rc; ringbuf_init(&rb, 8, 1, buffer); ASSERT_TRUE(ringbuf_is_empty(&rb)); rc = ringbuf_read_bytes(&rb, (u8 *)rbuf, 8); ASSERT_EQ(rc, 0U); rc = ringbuf_write_bytes(&rb, (u8 *)"12345", 5); ASSERT_EQ(rc, 5U); ASSERT_STREQ(buffer, "12345---"); rc = ringbuf_read_bytes(&rb, (u8 *)rbuf, 3); ASSERT_EQ(rc, 3U); rbuf[rc] = 0; ASSERT_STREQ(rbuf, "123"); rc = ringbuf_write_bytes(&rb, (u8 *)"6789abcdef", 10); ASSERT_EQ(rc, 6U); rc = ringbuf_write_bytes(&rb, (u8 *)"XYZ", 3); ASSERT_EQ(rc, 0U); ASSERT_STREQ(buffer, "9ab45678"); rc = ringbuf_read_bytes(&rb, (u8 *)rbuf, 4); ASSERT_EQ(rc, 4U); rbuf[rc] = 0; ASSERT_STREQ(rbuf, "4567"); rc = ringbuf_write_bytes(&rb, (u8 *)"qwerty", 6); ASSERT_EQ(rc, 4U); ASSERT_STREQ(buffer, "9abqwer8"); rc = ringbuf_read_bytes(&rb, (u8 *)rbuf, 8); ASSERT_EQ(rc, 8U); rbuf[rc] = 0; ASSERT_STREQ(rbuf, "89abqwer"); ASSERT_TRUE(ringbuf_is_empty(&rb)); ringbuf_destory(&rb); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/user.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/signal.h> #include <tilck/mods/tracing.h> #include "idt_int.h" void syscall_int80_entry(void); void sysenter_entry(void); typedef long (*syscall_type)(); #define SYSFL_NO_TRACE 0b00000001 #define SYSFL_NO_SIG 0b00000010 #define SYSFL_NO_PREEMPT 0b00000100 struct syscall { union { void *func; syscall_type fptr; }; u32 flags; }; static void unknown_syscall_int(regs_t *r, u32 sn) { trace_printk(5, "Unknown syscall %i", (int)sn); r->eax = (ulong) -ENOSYS; } static void __unknown_syscall(void) { struct task *curr = get_curr_task(); regs_t *r = curr->state_regs; const u32 sn = r->eax; unknown_syscall_int(r, sn); } #define DECL_SYS(func, flags) { {func}, flags } #define DECL_UNKNOWN_SYSCALL DECL_SYS(__unknown_syscall, 0) /* * The syscall numbers are ARCH-dependent * * The numbers and the syscall names MUST BE in sync with the following file * in the Linux kernel: * * arch/x86/entry/syscalls/syscall_32.tbl * * Lasy synced with Linux 5.15-rc2. */ static struct syscall syscalls[MAX_SYSCALLS] = { [0] = DECL_SYS(sys_restart_syscall, 0), [1] = DECL_SYS(sys_exit, 0), [2] = DECL_SYS(sys_fork, 0), [3] = DECL_SYS(sys_read, 0), [4] = DECL_SYS(sys_write, 0), [5] = DECL_SYS(sys_open, 0), [6] = DECL_SYS(sys_close, 0), [7] = DECL_SYS(sys_waitpid, 0), [8] = DECL_SYS(sys_creat, 0), [9] = DECL_SYS(sys_link, 0), [10] = DECL_SYS(sys_unlink, 0), [11] = DECL_SYS(sys_execve, 0), [12] = DECL_SYS(sys_chdir, 0), [13] = DECL_SYS(sys_time, 0), [14] = DECL_SYS(sys_mknod, 0), [15] = DECL_SYS(sys_chmod, 0), [16] = DECL_SYS(sys_lchown16, 0), [17] = DECL_UNKNOWN_SYSCALL, [18] = DECL_SYS(sys_oldstat, 0), [19] = DECL_SYS(sys_lseek, 0), [20] = DECL_SYS(sys_getpid, 0), [21] = DECL_SYS(sys_mount, 0), [22] = DECL_SYS(sys_oldumount, 0), [23] = DECL_SYS(sys_setuid16, 0), [24] = DECL_SYS(sys_getuid16, 0), [25] = DECL_SYS(sys_stime32, 0), [26] = DECL_SYS(sys_ptrace, 0), [27] = DECL_SYS(sys_alarm, 0), [28] = DECL_SYS(sys_oldfstat, 0), [29] = DECL_SYS(sys_pause, SYSFL_NO_PREEMPT), [30] = DECL_SYS(sys_utime32, 0), [31] = DECL_UNKNOWN_SYSCALL, [32] = DECL_UNKNOWN_SYSCALL, [33] = DECL_SYS(sys_access, 0), [34] = DECL_SYS(sys_nice, 0), [35] = DECL_UNKNOWN_SYSCALL, [36] = DECL_SYS(sys_sync, 0), [37] = DECL_SYS(sys_kill, 0), [38] = DECL_SYS(sys_rename, 0), [39] = DECL_SYS(sys_mkdir, 0), [40] = DECL_SYS(sys_rmdir, 0), [41] = DECL_SYS(sys_dup, 0), [42] = DECL_SYS(sys_pipe, 0), [43] = DECL_SYS(sys_times, 0), [44] = DECL_UNKNOWN_SYSCALL, [45] = DECL_SYS(sys_brk, 0), [46] = DECL_SYS(sys_setgid16, 0), [47] = DECL_SYS(sys_getgid16, 0), [48] = DECL_SYS(sys_signal, 0), [49] = DECL_SYS(sys_geteuid16, 0), [50] = DECL_SYS(sys_getegid16, 0), [51] = DECL_SYS(sys_acct, 0), [52] = DECL_SYS(sys_umount, 0), [53] = DECL_UNKNOWN_SYSCALL, [54] = DECL_SYS(sys_ioctl, 0), [55] = DECL_SYS(sys_fcntl, 0), [56] = DECL_UNKNOWN_SYSCALL, [57] = DECL_SYS(sys_setpgid, 0), [58] = DECL_UNKNOWN_SYSCALL, [59] = DECL_SYS(sys_olduname, 0), [60] = DECL_SYS(sys_umask, 0), [61] = DECL_SYS(sys_chroot, 0), [62] = DECL_SYS(sys_ustat, 0), [63] = DECL_SYS(sys_dup2, 0), [64] = DECL_SYS(sys_getppid, 0), [65] = DECL_SYS(sys_getpgrp, 0), [66] = DECL_SYS(sys_setsid, 0), [67] = DECL_SYS(sys_sigaction, 0), [68] = DECL_SYS(sys_sgetmask, 0), [69] = DECL_SYS(sys_ssetmask, 0), [70] = DECL_SYS(sys_setreuid16, 0), [71] = DECL_SYS(sys_setregid16, 0), [72] = DECL_SYS(sys_sigsuspend, 0), [73] = DECL_SYS(sys_sigpending, 0), [74] = DECL_SYS(sys_sethostname, 0), [75] = DECL_SYS(sys_setrlimit, 0), [76] = DECL_SYS(sys_old_getrlimit, 0), [77] = DECL_SYS(sys_getrusage, 0), [78] = DECL_SYS(sys_gettimeofday, 0), [79] = DECL_SYS(sys_settimeofday, 0), [80] = DECL_SYS(sys_getgroups16, 0), [81] = DECL_SYS(sys_setgroups16, 0), [82] = DECL_SYS(sys_old_select, 0), [83] = DECL_SYS(sys_symlink, 0), [84] = DECL_SYS(sys_lstat, 0), [85] = DECL_SYS(sys_readlink, 0), [86] = DECL_SYS(sys_uselib, 0), [87] = DECL_SYS(sys_swapon, 0), [88] = DECL_SYS(sys_reboot, 0), [89] = DECL_SYS(sys_old_readdir, 0), [90] = DECL_SYS(sys_old_mmap, 0), [91] = DECL_SYS(sys_munmap, 0), [92] = DECL_SYS(sys_truncate, 0), [93] = DECL_SYS(sys_ftruncate, 0), [94] = DECL_SYS(sys_fchmod, 0), [95] = DECL_SYS(sys_fchown16, 0), [96] = DECL_SYS(sys_getpriority, 0), [97] = DECL_SYS(sys_setpriority, 0), [98] = DECL_UNKNOWN_SYSCALL, [99] = DECL_SYS(sys_statfs, 0), [100] = DECL_SYS(sys_fstatfs, 0), [101] = DECL_SYS(sys_ioperm, 0), [102] = DECL_SYS(sys_socketcall, 0), [103] = DECL_SYS(sys_syslog, 0), [104] = DECL_SYS(sys_setitimer, 0), [105] = DECL_SYS(sys_getitimer, 0), [106] = DECL_SYS(sys_newstat, 0), [107] = DECL_SYS(sys_newlstat, 0), [108] = DECL_SYS(sys_newfstat, 0), [109] = DECL_SYS(sys_uname, 0), [110] = DECL_SYS(sys_iopl, 0), [111] = DECL_SYS(sys_vhangup, 0), [112] = DECL_UNKNOWN_SYSCALL, [113] = DECL_SYS(sys_vm86old, 0), [114] = DECL_SYS(sys_wait4, 0), [115] = DECL_SYS(sys_swapoff, 0), [116] = DECL_SYS(sys_sysinfo, 0), [117] = DECL_SYS(sys_ipc, 0), [118] = DECL_SYS(sys_fsync, 0), [119] = DECL_SYS(sys_sigreturn, 0), [120] = DECL_SYS(sys_clone, 0), [121] = DECL_SYS(sys_setdomainname, 0), [122] = DECL_SYS(sys_newuname, 0), [123] = DECL_SYS(sys_modify_ldt, 0), [124] = DECL_SYS(sys_adjtimex_time32, 0), [125] = DECL_SYS(sys_mprotect, 0), [126] = DECL_SYS(sys_sigprocmask, 0), [127] = DECL_UNKNOWN_SYSCALL, [128] = DECL_SYS(sys_init_module, 0), [129] = DECL_SYS(sys_delete_module, 0), [130] = DECL_UNKNOWN_SYSCALL, [131] = DECL_SYS(sys_quotactl, 0), [132] = DECL_SYS(sys_getpgid, 0), [133] = DECL_SYS(sys_fchdir, 0), [134] = DECL_SYS(sys_bdflush, 0), [135] = DECL_SYS(sys_sysfs, 0), [136] = DECL_SYS(sys_personality, 0), [137] = DECL_UNKNOWN_SYSCALL, [138] = DECL_SYS(sys_setfsuid16, 0), [139] = DECL_SYS(sys_setfsgid16, 0), [140] = DECL_SYS(sys_llseek, 0), [141] = DECL_SYS(sys_getdents, 0), [142] = DECL_SYS(sys_select, 0), [143] = DECL_SYS(sys_flock, 0), [144] = DECL_SYS(sys_msync, 0), [145] = DECL_SYS(sys_readv, 0), [146] = DECL_SYS(sys_writev, 0), [147] = DECL_SYS(sys_getsid, 0), [148] = DECL_SYS(sys_fdatasync, 0), [149] = DECL_SYS(sys_sysctl, 0), [150] = DECL_SYS(sys_mlock, 0), [151] = DECL_SYS(sys_munlock, 0), [152] = DECL_SYS(sys_mlockall, 0), [153] = DECL_SYS(sys_munlockall, 0), [154] = DECL_SYS(sys_sched_setparam, 0), [155] = DECL_SYS(sys_sched_getparam, 0), [156] = DECL_SYS(sys_sched_setscheduler, 0), [157] = DECL_SYS(sys_sched_getscheduler, 0), [158] = DECL_SYS(sys_sched_yield, 0), [159] = DECL_SYS(sys_sched_get_priority_max, 0), [160] = DECL_SYS(sys_sched_set_priority_min, 0), [161] = DECL_SYS(sys_sched_rr_get_interval_time32, 0), [162] = DECL_SYS(sys_nanosleep_time32, 0), [163] = DECL_SYS(sys_mremap, 0), [164] = DECL_SYS(sys_setresuid16, 0), [165] = DECL_SYS(sys_getresuid16, 0), [166] = DECL_SYS(sys_vm86, 0), [167] = DECL_UNKNOWN_SYSCALL, [168] = DECL_SYS(sys_poll, 0), [169] = DECL_SYS(sys_nfsservctl, 0), [170] = DECL_SYS(sys_setresgid16, 0), [171] = DECL_SYS(sys_getresgid16, 0), [172] = DECL_SYS(sys_prctl, 0), [173] = DECL_SYS( sys_rt_sigreturn, 0 | SYSFL_NO_TRACE | SYSFL_NO_SIG | SYSFL_NO_PREEMPT ), [174] = DECL_SYS(sys_rt_sigaction, 0), [175] = DECL_SYS(sys_rt_sigprocmask, SYSFL_NO_PREEMPT), [176] = DECL_SYS(sys_rt_sigpending, SYSFL_NO_PREEMPT), [177] = DECL_SYS(sys_rt_sigtimedwait_time32, 0), [178] = DECL_SYS(sys_rt_sigqueueinfo, 0), [179] = DECL_SYS(sys_rt_sigsuspend, SYSFL_NO_PREEMPT), [180] = DECL_SYS(sys_pread64, 0), [181] = DECL_SYS(sys_pwrite64, 0), [182] = DECL_SYS(sys_chown16, 0), [183] = DECL_SYS(sys_getcwd, 0), [184] = DECL_SYS(sys_capget, 0), [185] = DECL_SYS(sys_capset, 0), [186] = DECL_SYS(sys_sigaltstack, 0), [187] = DECL_SYS(sys_sendfile, 0), [188] = DECL_UNKNOWN_SYSCALL, [189] = DECL_UNKNOWN_SYSCALL, [190] = DECL_SYS(sys_vfork, 0), [191] = DECL_SYS(sys_getrlimit, 0), [192] = DECL_SYS(sys_mmap_pgoff, 0), [193] = DECL_SYS(sys_ia32_truncate64, 0), [194] = DECL_SYS(sys_ia32_ftruncate64, 0), [195] = DECL_SYS(sys_stat64, 0), [196] = DECL_SYS(sys_lstat64, 0), [197] = DECL_SYS(sys_fstat64, 0), [198] = DECL_SYS(sys_lchown, 0), [199] = DECL_SYS(sys_getuid, 0), [200] = DECL_SYS(sys_getgid, 0), [201] = DECL_SYS(sys_geteuid, 0), [202] = DECL_SYS(sys_getegid, 0), [203] = DECL_SYS(sys_setreuid, 0), [204] = DECL_SYS(sys_setregid, 0), [205] = DECL_SYS(sys_getgroups, 0), [206] = DECL_SYS(sys_setgroups, 0), [207] = DECL_SYS(sys_fchown, 0), [208] = DECL_SYS(sys_setresuid, 0), [209] = DECL_SYS(sys_getresuid, 0), [210] = DECL_SYS(sys_setresgid, 0), [211] = DECL_SYS(sys_getresgid, 0), [212] = DECL_SYS(sys_chown, 0), [213] = DECL_SYS(sys_setuid, 0), [214] = DECL_SYS(sys_setgid, 0), [215] = DECL_SYS(sys_setfsuid, 0), [216] = DECL_SYS(sys_setfsgid, 0), [217] = DECL_SYS(sys_pivot_root, 0), [218] = DECL_SYS(sys_mincore, 0), [219] = DECL_SYS(sys_madvise, 0), [220] = DECL_SYS(sys_getdents64, 0), [221] = DECL_SYS(sys_fcntl64, 0), [222] = DECL_UNKNOWN_SYSCALL, [223] = DECL_UNKNOWN_SYSCALL, [224] = DECL_SYS(sys_gettid, 0), [225] = DECL_SYS(sys_ia32_readahead, 0), [226] = DECL_SYS(sys_setxattr, 0), [227] = DECL_SYS(sys_lsetxattr, 0), [228] = DECL_SYS(sys_fsetxattr, 0), [229] = DECL_SYS(sys_getxattr, 0), [230] = DECL_SYS(sys_lgetxattr, 0), [231] = DECL_SYS(sys_fgetxattr, 0), [232] = DECL_SYS(sys_listxattr, 0), [233] = DECL_SYS(sys_llistxattr, 0), [234] = DECL_SYS(sys_flistxattr, 0), [235] = DECL_SYS(sys_removexattr, 0), [236] = DECL_SYS(sys_lremovexattr, 0), [237] = DECL_SYS(sys_fremovexattr, 0), [238] = DECL_SYS(sys_tkill, 0), [239] = DECL_SYS(sys_sendfile64, 0), [240] = DECL_SYS(sys_futex_time32, 0), [241] = DECL_SYS(sys_sched_setaffinity, 0), [242] = DECL_SYS(sys_sched_getaffinity, 0), [243] = DECL_SYS(sys_set_thread_area, 0), [244] = DECL_SYS(sys_get_thread_area, 0), [245] = DECL_SYS(sys_io_setup, 0), [246] = DECL_SYS(sys_io_destroy, 0), [247] = DECL_SYS(sys_io_getevents_time32, 0), [248] = DECL_SYS(sys_io_submit, 0), [249] = DECL_SYS(sys_io_cancel, 0), [250] = DECL_SYS(sys_ia32_fadvise64, 0), [251] = DECL_UNKNOWN_SYSCALL, [252] = DECL_SYS(sys_exit_group, 0), [253] = DECL_SYS(sys_lookup_dcookie, 0), [254] = DECL_SYS(sys_epoll_create, 0), [255] = DECL_SYS(sys_epoll_ctl, 0), [256] = DECL_SYS(sys_epoll_wait, 0), [257] = DECL_SYS(sys_remap_file_pages, 0), [258] = DECL_SYS(sys_set_tid_address, 0), [259] = DECL_SYS(sys_timer_create, 0), [260] = DECL_SYS(sys_timer_settime32, 0), [261] = DECL_SYS(sys_timer_gettime32, 0), [262] = DECL_SYS(sys_timer_getoverrun, 0), [263] = DECL_SYS(sys_timer_delete, 0), [264] = DECL_SYS(sys_clock_settime32, 0), [265] = DECL_SYS(sys_clock_gettime32, 0), [266] = DECL_SYS(sys_clock_getres_time32, 0), [267] = DECL_SYS(sys_clock_nanosleep_time32, 0), [268] = DECL_SYS(sys_statfs64, 0), [269] = DECL_SYS(sys_fstatfs64, 0), [270] = DECL_SYS(sys_tgkill, 0), [271] = DECL_SYS(sys_utimes, 0), [272] = DECL_SYS(sys_ia32_fadvise64_64, 0), [273] = DECL_UNKNOWN_SYSCALL, [274] = DECL_SYS(sys_mbind, 0), [275] = DECL_SYS(sys_get_mempolicy, 0), [276] = DECL_SYS(sys_set_mempolicy, 0), [277] = DECL_SYS(sys_mq_open, 0), [278] = DECL_SYS(sys_mq_unlink, 0), [279] = DECL_SYS(sys_mq_timedsend_time32, 0), [280] = DECL_SYS(sys_mq_timedreceive_time32, 0), [281] = DECL_SYS(sys_mq_notify, 0), [282] = DECL_SYS(sys_mq_getsetattr, 0), [283] = DECL_SYS(sys_kexec_load, 0), [284] = DECL_SYS(sys_waitid, 0), [285] = DECL_UNKNOWN_SYSCALL, [286] = DECL_SYS(sys_add_key, 0), [287] = DECL_SYS(sys_request_key, 0), [288] = DECL_SYS(sys_keyctl, 0), [289] = DECL_SYS(sys_ioprio_set, 0), [290] = DECL_SYS(sys_ioprio_get, 0), [291] = DECL_SYS(sys_inotify_init, 0), [292] = DECL_SYS(sys_inotify_add_watch, 0), [293] = DECL_SYS(sys_inotify_rm_watch, 0), [294] = DECL_SYS(sys_migrate_pages, 0), [295] = DECL_SYS(sys_openat, 0), [296] = DECL_SYS(sys_mkdirat, 0), [297] = DECL_SYS(sys_mknodat, 0), [298] = DECL_SYS(sys_fchownat, 0), [299] = DECL_SYS(sys_futimesat_time32, 0), [300] = DECL_SYS(sys_fstatat64, 0), [301] = DECL_SYS(sys_unlinkat, 0), [302] = DECL_SYS(sys_renameat, 0), [303] = DECL_SYS(sys_linkat, 0), [304] = DECL_SYS(sys_symlinkat, 0), [305] = DECL_SYS(sys_readlinkat, 0), [306] = DECL_SYS(sys_fchmodat, 0), [307] = DECL_SYS(sys_faccessat, 0), [308] = DECL_SYS(sys_pselect6_time32, 0), [309] = DECL_SYS(sys_ppoll_time32, 0), [310] = DECL_SYS(sys_unshare, 0), [311] = DECL_SYS(sys_set_robust_list, 0), [312] = DECL_SYS(sys_get_robust_list, 0), [313] = DECL_SYS(sys_splice, 0), [314] = DECL_SYS(sys_ia32_sync_file_range, 0), [315] = DECL_SYS(sys_tee, 0), [316] = DECL_SYS(sys_vmsplice, 0), [317] = DECL_SYS(sys_move_pages, 0), [318] = DECL_SYS(sys_getcpu, 0), [319] = DECL_SYS(sys_epoll_pwait, 0), [320] = DECL_SYS(sys_utimensat_time32, 0), [321] = DECL_SYS(sys_signalfd, 0), [322] = DECL_SYS(sys_timerfd_create, 0), [323] = DECL_SYS(sys_eventfd, 0), [324] = DECL_SYS(sys_fallocate, 0), [325] = DECL_SYS(sys_timerfd_settime32, 0), [326] = DECL_SYS(sys_timerfd_gettime32, 0), [327] = DECL_SYS(sys_signalfd4, 0), [328] = DECL_SYS(sys_eventfd2, 0), [329] = DECL_SYS(sys_epoll_create1, 0), [330] = DECL_SYS(sys_dup3, 0), [331] = DECL_SYS(sys_pipe2, 0), [332] = DECL_SYS(sys_inotify_init1, 0), [333] = DECL_SYS(sys_preadv, 0), [334] = DECL_SYS(sys_pwritev, 0), [335] = DECL_SYS(sys_rt_tgsigqueueinfo, 0), [336] = DECL_SYS(sys_perf_event_open, 0), [337] = DECL_SYS(sys_recvmmsg_time32, 0), [338] = DECL_SYS(sys_fanotify_init, 0), [339] = DECL_SYS(sys_fanotify_mark, 0), [340] = DECL_SYS(sys_prlimit64, 0), [341] = DECL_SYS(sys_name_to_handle_at, 0), [342] = DECL_SYS(sys_open_by_handle_at, 0), [343] = DECL_SYS(sys_clock_adjtime32, 0), [344] = DECL_SYS(sys_syncfs, 0), [345] = DECL_SYS(sys_sendmmsg, 0), [346] = DECL_SYS(sys_setns, 0), [347] = DECL_SYS(sys_process_vm_readv, 0), [348] = DECL_SYS(sys_process_vm_writev, 0), [349] = DECL_SYS(sys_kcmp, 0), [350] = DECL_SYS(sys_finit_module, 0), [351] = DECL_SYS(sys_sched_setattr, 0), [352] = DECL_SYS(sys_sched_getattr, 0), [353] = DECL_SYS(sys_renameat2, 0), [354] = DECL_SYS(sys_seccomp, 0), [355] = DECL_SYS(sys_getrandom, 0), [356] = DECL_SYS(sys_memfd_create, 0), [357] = DECL_SYS(sys_bpf, 0), [358] = DECL_SYS(sys_execveat, 0), [359] = DECL_SYS(sys_socket, 0), [360] = DECL_SYS(sys_socketpair, 0), [361] = DECL_SYS(sys_bind, 0), [362] = DECL_SYS(sys_connect, 0), [363] = DECL_SYS(sys_listen, 0), [364] = DECL_SYS(sys_accept4, 0), [365] = DECL_SYS(sys_getsockopt, 0), [366] = DECL_SYS(sys_setsockopt, 0), [367] = DECL_SYS(sys_getsockname, 0), [368] = DECL_SYS(sys_getpeername, 0), [369] = DECL_SYS(sys_sendto, 0), [370] = DECL_SYS(sys_sendmsg, 0), [371] = DECL_SYS(sys_recvfrom, 0), [372] = DECL_SYS(sys_recvmsg, 0), [373] = DECL_SYS(sys_shutdown, 0), [374] = DECL_SYS(sys_userfaultfd, 0), [375] = DECL_SYS(sys_membarrier, 0), [376] = DECL_SYS(sys_mlock2, 0), [377] = DECL_SYS(sys_copy_file_range, 0), [378] = DECL_SYS(sys_preadv2, 0), [379] = DECL_SYS(sys_pwritev2, 0), [380] = DECL_SYS(sys_pkey_mprotect, 0), [381] = DECL_SYS(sys_pkey_alloc, 0), [382] = DECL_SYS(sys_pkey_free, 0), [383] = DECL_SYS(sys_statx, 0), [384] = DECL_SYS(sys_arch_prctl, 0), [385] = DECL_SYS(sys_io_pgetevents_time32, 0), [386] = DECL_SYS(sys_rseq, 0), [393] = DECL_SYS(sys_semget, 0), [394] = DECL_SYS(sys_semctl, 0), [395] = DECL_SYS(sys_shmget, 0), [396] = DECL_SYS(sys_shmctl, 0), [397] = DECL_SYS(sys_shmat, 0), [398] = DECL_SYS(sys_shmdt, 0), [399] = DECL_SYS(sys_msgget, 0), [400] = DECL_SYS(sys_msgsnd, 0), [401] = DECL_SYS(sys_msgrcv, 0), [402] = DECL_SYS(sys_msgctl, 0), [403] = DECL_SYS(sys_clock_gettime, 0), [404] = DECL_SYS(sys_clock_settime, 0), [405] = DECL_SYS(sys_clock_adjtime, 0), [406] = DECL_SYS(sys_clock_getres, 0), [407] = DECL_SYS(sys_clock_nanosleep, 0), [408] = DECL_SYS(sys_timer_gettime, 0), [409] = DECL_SYS(sys_timer_settime, 0), [410] = DECL_SYS(sys_timerfd_gettime, 0), [411] = DECL_SYS(sys_timerfd_settime, 0), [412] = DECL_SYS(sys_utimensat, 0), [413] = DECL_SYS(sys_pselect6, 0), [414] = DECL_SYS(sys_ppoll, 0), [416] = DECL_SYS(sys_io_pgetevents, 0), [417] = DECL_SYS(sys_recvmmsg, 0), [418] = DECL_SYS(sys_mq_timedsend, 0), [419] = DECL_SYS(sys_mq_timedreceive, 0), [420] = DECL_SYS(sys_semtimedop, 0), [421] = DECL_SYS(sys_rt_sigtimedwait, 0), [422] = DECL_SYS(sys_futex, 0), [423] = DECL_SYS(sys_sched_rr_get_interval, 0), [424] = DECL_SYS(sys_pidfd_send_signal, 0), [425] = DECL_SYS(sys_io_uring_setup, 0), [426] = DECL_SYS(sys_io_uring_enter, 0), [427] = DECL_SYS(sys_io_uring_register, 0), [428] = DECL_SYS(sys_open_tree, 0), [429] = DECL_SYS(sys_move_mount, 0), [430] = DECL_SYS(sys_fsopen, 0), [431] = DECL_SYS(sys_fsconfig, 0), [432] = DECL_SYS(sys_fsmount, 0), [433] = DECL_SYS(sys_fspick, 0), [434] = DECL_SYS(sys_pidfd_open, 0), [435] = DECL_SYS(sys_clone3, 0), [436] = DECL_SYS(sys_close_range, 0), [437] = DECL_SYS(sys_openat2, 0), [438] = DECL_SYS(sys_pidfd_getfd, 0), [439] = DECL_SYS(sys_faccessat2, 0), [440] = DECL_SYS(sys_process_madvise, 0), [441] = DECL_SYS(sys_epoll_pwait2, 0), [442] = DECL_SYS(sys_mount_setattr, 0), [443] = DECL_SYS(sys_quotactl_fd, 0), [444] = DECL_SYS(sys_landlock_create_ruleset, 0), [445] = DECL_SYS(sys_landlock_add_rule, 0), [446] = DECL_SYS(sys_landlock_restrict_self, 0), [447] = DECL_SYS(sys_memfd_secret, 0), [448] = DECL_SYS(sys_process_mrelease, 0), [TILCK_CMD_SYSCALL] = DECL_SYS(sys_tilck_cmd, 0), }; void *get_syscall_func_ptr(u32 n) { if (n >= ARRAY_SIZE(syscalls)) return NULL; return syscalls[n].func; } int get_syscall_num(void *func) { if (!func) return -1; for (int i = 0; i < ARRAY_SIZE(syscalls); i++) if (syscalls[i].func == func) return i; return -1; } static void do_special_syscall(regs_t *r) { struct task *curr = get_curr_task(); const u32 sn = r->eax; const u32 fl = syscalls[sn].flags; const syscall_type fptr = syscalls[sn].fptr; const bool signals = ~fl & SYSFL_NO_SIG; const bool preemptable = ~fl & SYSFL_NO_PREEMPT; const bool traceable = ~fl & SYSFL_NO_TRACE; if (signals) process_signals(curr, sig_pre_syscall, r); if (preemptable) enable_preemption(); if (traceable) trace_sys_enter(sn,r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); r->eax = (u32) fptr(r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); if (traceable) trace_sys_exit(sn,r->eax,r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); if (preemptable) disable_preemption(); if (signals) process_signals(curr, sig_in_syscall, r); } static void do_syscall(regs_t *r) { struct task *curr = get_curr_task(); const u32 sn = r->eax; const syscall_type fptr = syscalls[sn].fptr; process_signals(curr, sig_pre_syscall, r); enable_preemption(); { trace_sys_enter(sn,r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); r->eax = (u32) fptr(r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); trace_sys_exit(sn,r->eax,r->ebx,r->ecx,r->edx,r->esi,r->edi,r->ebp); } disable_preemption(); process_signals(curr, sig_in_syscall, r); } void handle_syscall(regs_t *r) { const u32 sn = r->eax; /* * In case of a sysenter syscall, the eflags are saved in kernel mode after * the cpu disabled the interrupts. Therefore, with the statement below we * force the IF flag to be set in any case (for the int 0x80 case it is not * necessary). */ r->eflags |= EFLAGS_IF; save_current_task_state(r); set_current_task_in_kernel(); if (LIKELY(sn < ARRAY_SIZE(syscalls))) { if (LIKELY(syscalls[sn].flags == 0)) do_syscall(r); else do_special_syscall(r); } else { unknown_syscall_int(r, sn); } set_current_task_in_user_mode(); } void init_syscall_interfaces(void) { /* Set the entry for the int 0x80 syscall interface */ idt_set_entry(SYSCALL_SOFT_INTERRUPT, syscall_int80_entry, X86_KERNEL_CODE_SEL, IDT_FLAG_PRESENT | IDT_FLAG_INT_GATE | IDT_FLAG_DPL3); /* Setup the sysenter interface */ wrmsr(MSR_IA32_SYSENTER_CS, X86_KERNEL_CODE_SEL); wrmsr(MSR_IA32_SYSENTER_EIP, (ulong) &sysenter_entry); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct list_node { struct list_node *next; struct list_node *prev; }; struct list { struct list_node *first; struct list_node *last; }; STATIC_ASSERT(sizeof(struct list) == sizeof(struct list_node)); STATIC_ASSERT(alignof(struct list) == alignof(struct list_node)); #define STATIC_LIST_INIT(name) { \ (struct list_node *)&(name), \ (struct list_node *)&(name) \ } #define STATIC_LIST_NODE_INIT(name) { &(name), &(name) } static inline void list_node_init(struct list_node *n) { n->next = n; n->prev = n; } static inline bool list_node_is_null(struct list_node *n) { return !n->next && !n->prev; } static inline bool list_node_is_empty(struct list_node *n) { return n->next == n && n->prev == n; } static inline void list_init(struct list *n) { list_node_init((struct list_node *)n); } static inline bool list_is_null(struct list *n) { return list_node_is_null((struct list_node *) n); } static inline bool list_is_empty(struct list *n) { return list_node_is_empty((struct list_node *) n); } static inline bool list_is_node_in_list(struct list_node *node) { return !list_node_is_empty(node) && node->prev->next == node && node->next->prev == node; } static inline void list_add_after(struct list_node *curr, struct list_node *elem) { struct list_node *curr_next = curr->next; curr->next = elem; elem->next = curr_next; elem->prev = curr; curr_next->prev = elem; } static inline void list_add_before(struct list_node *curr, struct list_node *elem) { list_add_after(curr->prev, elem); } static inline void list_add_tail(struct list *l, struct list_node *elem) { list_add_before((struct list_node *)l, elem); } static inline void list_add_head(struct list *l, struct list_node *elem) { list_add_after((struct list_node *)l, elem); } static inline void list_remove(struct list_node *elem) { elem->prev->next = elem->next; elem->next->prev = elem->prev; } #define list_to_obj(list_ptr, struct_type, list_member_name) \ CONTAINER_OF(list_ptr, struct_type, list_member_name) #define list_first_obj(list_root_ptr, type, member) \ list_to_obj((list_root_ptr)->first, type, member) #define list_last_obj(list_root_ptr, type, member) \ list_to_obj((list_root_ptr)->last, type, member) // Here 'pos' is an object (struct *), containing a struct list_node 'member' #define list_next_obj(pos, list_mem_name) \ list_to_obj((pos)->list_mem_name.next, typeof(*(pos)), list_mem_name) #define list_prev_obj(pos, list_mem_name) \ list_to_obj((pos)->list_mem_name.prev, typeof(*(pos)), list_mem_name) // Here 'tp' is a temporary variable having the same type of 'pos'. #define list_for_each(pos, tp, list_ptr, member) \ for (pos = list_first_obj(list_ptr, typeof(*pos), member), \ tp = list_next_obj(pos, member); \ &pos->member != (struct list_node *)(list_ptr); \ pos = tp, tp = list_next_obj(tp, member)) #define list_for_each_ro(pos, list_ptr, member) \ for (pos = list_first_obj(list_ptr, typeof(*pos), member); \ &pos->member != (struct list_node *)(list_ptr); \ pos = list_next_obj(pos, member)) /* Same as list_for_each_ro(), but the orig. value of `pos` is kept */ #define list_for_each_ro_kp(pos, list_ptr, member) \ for (; &pos->member != (struct list_node *)(list_ptr); \ pos = list_next_obj(pos, member)) #define list_for_each_reverse(pos, tp, list_ptr, member) \ for (pos = list_last_obj(list_ptr, typeof(*pos), member), \ tp = list_prev_obj(pos, member); \ &pos->member != (list_ptr); \ pos = tp, tp = list_prev_obj(tp, member)) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/mods/tracing.h> #include "termutil.h" #include "dp_tracing_int.h" #if MOD_tracing static inline bool dp_should_full_dump_param(bool exp_block, enum sys_param_kind kind, enum trace_event_type t) { return kind == sys_param_in_out || (t == te_sys_enter && kind == sys_param_in) || (t == te_sys_exit && (!exp_block || kind == sys_param_out)); } static const char * dp_get_esc_color_for_param(const struct sys_param_type *t, const char *rb) { if (rb[0] == '\"' && t->ui_type == ui_type_string) return E_COLOR_RED; if (t == &ptype_errno_or_val && rb[0] == '-') return E_COLOR_WHITE_ON_RED; if (t->ui_type == ui_type_integer) return E_COLOR_BR_BLUE; return ""; } static void dp_dump_rendered_params(const char *sys_name, const struct syscall_info *si) { int dumped_bufs = 0; dp_write_raw("%s(", sys_name); for (int i = 0; i < si->n_params; i++) { const struct sys_param_info *p = &si->params[i]; if (!rend_bufs[i][0]) continue; dp_write_raw(E_COLOR_MAGENTA "%s" RESET_ATTRS ": ", p->name); dp_write_raw( "%s%s" RESET_ATTRS, dp_get_esc_color_for_param(p->type, rend_bufs[i]), rend_bufs[i] ); if (dumped_bufs < used_rend_bufs - 1) dp_write_raw(", "); dumped_bufs++; } dp_write_raw(")"); } static void dp_render_full_dump_single_param(int i, struct trace_event *event, const struct syscall_info *si, const struct sys_param_info *p, const struct sys_param_type *type) { char *data; size_t data_size; long hlp = -1; /* helper param, means "real_size" for ptype_buffer */ struct syscall_event_data *e = &event->sys_ev; if (p->helper_param_name) { int idx = tracing_get_param_idx(si, p->helper_param_name); ASSERT(idx >= 0); hlp = (long) e->args[idx]; } if (!tracing_get_slot(event, si, i, &data, &data_size)) { ASSERT(type->dump_from_val); if (!type->dump_from_val(e->args[i], hlp, rend_bufs[i], REND_BUF_SZ)) snprintk(rend_bufs[i], REND_BUF_SZ, "(raw) %p", e->args[i]); } else { long sz = -1; ASSERT(type->dump); if (p->helper_param_name) sz = hlp; sz = MIN(sz, (long)data_size); if (p->real_sz_in_ret && event->type == te_sys_exit) hlp = e->retval >= 0 ? e->retval : 0; if (!type->dump(e->args[i], data, sz, hlp, rend_bufs[i], REND_BUF_SZ)) snprintk(rend_bufs[i], REND_BUF_SZ, "(raw) %p", e->args[i]); } } static void dp_render_minimal_dump_single_param(int i, struct trace_event *event) { struct syscall_event_data *e = &event->sys_ev; if (!ptype_voidp.dump_from_val(e->args[i], -1, rend_bufs[i], REND_BUF_SZ)) panic("Unable to serialize a ptype_voidp in a render buf"); } static void dp_dump_syscall_with_info(struct trace_event *e, const char *sys_name, const struct syscall_info *si) { used_rend_bufs = 0; for (int i = 0; i < si->n_params; i++) { bzero(rend_bufs[i], REND_BUF_SZ); const struct sys_param_info *p = &si->params[i]; const struct sys_param_type *type = p->type; if (p->invisible) continue; if (dp_should_full_dump_param(exp_block(si), p->kind, e->type)) { dp_render_full_dump_single_param(i, e, si, p, type); used_rend_bufs++; } else if (e->type == te_sys_enter) { dp_render_minimal_dump_single_param(i, e); used_rend_bufs++; } } dp_dump_rendered_params(sys_name, si); } static void dp_dump_ret_val(const struct syscall_info *si, long retval) { if (!si) { if (retval <= 1024 * 1024) { if (retval >= 0) { /* we guess it's just a number */ dp_write_raw(E_COLOR_BR_BLUE "%d" RESET_ATTRS, retval); } else { /* we guess it's an errno */ dp_write_raw(E_COLOR_WHITE_ON_RED "-%s" RESET_ATTRS, get_errno_name(-retval)); } } else { /* we guess it's a pointer */ dp_write_raw("%p", retval); } return; } const struct sys_param_type *rt = si->ret_type; ASSERT(rt->dump_from_val); if (!rt->dump_from_val((ulong)retval, -1, rend_bufs[0], REND_BUF_SZ)) { dp_write_raw("(raw) %p", retval); return; } dp_write_raw( "%s%s" RESET_ATTRS, dp_get_esc_color_for_param(si->ret_type, rend_bufs[0]), rend_bufs[0] ); } static void dp_dump_syscall_event(struct trace_event *event, const char *sys_name, const struct syscall_info *si) { struct syscall_event_data *e = &event->sys_ev; if (event->type == te_sys_enter) { dp_write_raw(E_COLOR_BR_GREEN "ENTER" RESET_ATTRS " "); } else { if (!si || exp_block(si)) dp_write_raw(E_COLOR_BR_BLUE "EXIT" RESET_ATTRS " "); else dp_write_raw(E_COLOR_YELLOW "CALL" RESET_ATTRS " "); } if (si) dp_dump_syscall_with_info(event, sys_name, si); else dp_write_raw("%s()", sys_name); if (event->type == te_sys_exit) { dp_write_raw(" -> "); dp_dump_ret_val(si, e->retval); } dp_write_raw("\r\n"); } void dp_handle_syscall_event(struct trace_event *e) { const char *sys_name = NULL; const struct syscall_info *si = NULL; struct syscall_event_data *se = &e->sys_ev; sys_name = tracing_get_syscall_name(se->sys); ASSERT(sys_name); sys_name += 4; /* skip the "sys_" prefix */ si = tracing_get_syscall_info(se->sys); dp_dump_syscall_event(e, sys_name, si); } #endif // #if MOD_tracing <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include "i8042.h" #define KB_ITERS_TIMEOUT 10000 /* * The array `sw_port_enabled` determines which ports Tilck wants to keep * enabled, not which ports are currently enabled on the controller. * The difference is great because temporarely we can disable all the ports, * but later we must re-enable only the ones "logically" enabled, as determined * by this array. */ static bool sw_port_enabled[2] = { true, /* Primary PS/2 port, keyboard */ false /* Secondary PS/2 port, mouse */ }; void i8042_set_sw_port_enabled_state(u8 port, bool enabled) { ASSERT(port <= 1); sw_port_enabled[port] = enabled; } bool i8042_get_sw_port_enabled_state(u8 port) { ASSERT(port <= 1); return sw_port_enabled[port]; } static NO_INLINE void i8042_io_wait(void) { if (in_hypervisor()) return; delay_us(1); } static bool i8042_wait_cmd_fetched(void) { for (int i = 0; !i8042_is_ready_for_cmd(); i++) { if (i >= KB_ITERS_TIMEOUT) return false; i8042_io_wait(); } return true; } static NODISCARD bool i8042_wait_for_data(void) { for (int i = 0; !i8042_has_pending_data(); i++) { if (i >= KB_ITERS_TIMEOUT) return false; i8042_io_wait(); } return true; } void i8042_drain_any_data(void) { while (i8042_has_pending_data()) { i8042_read_data(); i8042_io_wait(); } } void i8042_force_drain_data(void) { for (int i = 0; i < 16; i++) i8042_read_data(); } static NODISCARD bool i8042_send_cmd(u8 cmd) { if (!i8042_wait_cmd_fetched()) return false; outb(I8042_CMD_PORT, cmd); if (!i8042_wait_cmd_fetched()) return false; return true; } static NODISCARD bool i8042_send_cmd_and_wait_response(u8 cmd) { if (!i8042_send_cmd(cmd)) return false; if (!i8042_wait_for_data()) return false; return true; } static NODISCARD bool i8042_full_wait(void) { u8 ctrl; u32 iters = 0; do { if (iters > KB_ITERS_TIMEOUT) return false; ctrl = inb(I8042_STATUS_PORT); if (ctrl & I8042_STATUS_OUTPUT_FULL) { i8042_read_data(); /* drain the KB's output */ } iters++; i8042_io_wait(); } while (ctrl & (I8042_STATUS_INPUT_FULL | I8042_STATUS_OUTPUT_FULL)); return true; } NODISCARD bool i8042_disable_ports(void) { irq_set_mask(X86_PC_KEYBOARD_IRQ); if (!i8042_full_wait()) return false; if (!i8042_send_cmd(I8042_CMD_PORT1_DISABLE)) return false; if (!i8042_send_cmd(I8042_CMD_PORT2_DISABLE)) return false; if (!i8042_full_wait()) return false; return true; } NODISCARD bool i8042_enable_ports(void) { if (!i8042_full_wait()) return false; if (sw_port_enabled[0]) if (!i8042_send_cmd(I8042_CMD_PORT1_ENABLE)) return false; if (sw_port_enabled[1]) if (!i8042_send_cmd(I8042_CMD_PORT2_ENABLE)) return false; if (!i8042_full_wait()) return false; i8042_force_drain_data(); irq_clear_mask(X86_PC_KEYBOARD_IRQ); return true; } static bool kb_send_cmd_with_arg_unsafe(u8 cmd, u8 arg) { if (!i8042_full_wait()) return false; outb(I8042_DATA_PORT, cmd); if (!i8042_full_wait()) return false; outb(I8042_DATA_PORT, arg); if (!i8042_full_wait()) return false; return true; } bool kb_led_set(u8 val) { bool ok; if (!i8042_disable_ports()) { printk("KB: i8042_disable_ports() fail\n"); return false; } ok = kb_send_cmd_with_arg_unsafe(KB_CMD_SET_LED, val & 0b111); if (!ok) printk("kb_led_set() failed: timeout in i8042_full_wait()\n"); if (!i8042_enable_ports()) { printk("KB: i8042_enable_ports() fail\n"); ok = false; } return ok; } /* * From http://wiki.osdev.org/PS/2_Keyboard * * BITS [0..4]: Repeat rate (00000b = 30 Hz, ..., 11111b = 2 Hz) * BITS [5..6]: Delay before keys repeat (00b = 250 ms, ..., 11b = 1000 ms) * BIT [7]: Must be zero * * Note: this function sets just the repeat rate. */ bool kb_set_typematic_byte(u8 val) { bool ok; if (!i8042_disable_ports()) { printk("KB: i8042_disable_ports() fail\n"); return false; } ok = kb_send_cmd_with_arg_unsafe(KB_CMD_SET_TYPEMATIC_BYTE, val & 0b11111); if (!ok) printk("kb_set_typematic_byte() failed: timeout in i8042_full_wait()\n"); if (!i8042_enable_ports()) { printk("KB: i8042_enable_ports() fail\n"); ok = false; } return ok; } NODISCARD bool i8042_self_test(void) { u8 res, resend_count = 0; bool success = false; if (!i8042_disable_ports()) goto out; do { if (resend_count >= 3) break; if (!i8042_send_cmd_and_wait_response(I8042_CMD_SELFTEST)) goto out; res = i8042_read_data(); resend_count++; } while (res == KB_RESPONSE_RESEND); if (res == I8042_RESPONSE_SELF_TEST_OK) success = true; out: if (!i8042_enable_ports()) success = false; return success; } NODISCARD bool i8042_reset(void) { u8 res; u8 status; u8 resend_count = 0; bool success = false; if (!i8042_disable_ports()) goto out; status = inb(I8042_STATUS_PORT); printk("KB: reset procedure\n"); printk("KB: initial status: %#x\n", status); printk("KB: sending 0xFF (reset) to the controller\n"); if (!i8042_send_cmd_and_wait_response(I8042_CMD_RESET)) goto out; do { if (resend_count >= 3) break; res = i8042_read_data(); printk("KB: response: %#x\n", res); resend_count++; } while (res == KB_RESPONSE_RESEND); if (res != KB_RESPONSE_ACK) { if (res == I8042_RESPONSE_BAT_OK) success = true; goto out; } /* We got an ACK, now wait for the success/failure of the reset itself */ if (!i8042_wait_for_data()) goto out; res = i8042_read_data(); printk("KB: response: %#x\n", res); if (res == I8042_RESPONSE_BAT_OK) success = true; out: if (!i8042_enable_ports()) success = false; printk("KB: reset success: %u\n", success); return success; } bool i8042_read_ctr_unsafe(u8 *ctr) { if (!i8042_send_cmd_and_wait_response(I8042_CMD_READ_CTR)) { printk("KB: send cmd failed\n"); return false; } *ctr = i8042_read_data(); return true; } bool i8042_read_cto_unsafe(u8 *cto) { if (!i8042_send_cmd_and_wait_response(I8042_CMD_READ_CTO)) { printk("KB: send cmd failed\n"); return false; } *cto = i8042_read_data(); return true; } bool i8042_read_regs(u8 *ctr, u8 *cto) { bool ok = true; ASSERT(are_interrupts_enabled()); if (!i8042_disable_ports()) { printk("KB: disable ports failed\n"); ok = false; } if (ctr && ok) ok = i8042_read_ctr_unsafe(ctr); if (cto && ok) ok = i8042_read_cto_unsafe(cto); if (!i8042_enable_ports()) { printk("KB: enable ports failed\n"); ok = false; } return ok; } void i8042_reboot(void) { printk("Performing i8042 reset...\n"); if (!i8042_send_cmd(I8042_CMD_CPU_RESET)) { printk("Unable to reboot using the 8042 controller\n"); return; } /* Ok, now just loop tight for a bit, while the machine resets */ for (int i = 0; i < 100; i++) delay_us(10 * 1000); printk("ERROR: i8042 reset didn't work\n"); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static const struct file_ops static_ops_ramfs = { .read = ramfs_read, .write = ramfs_write, .readv = ramfs_readv, .writev = ramfs_writev, .seek = ramfs_seek, .ioctl = ramfs_ioctl, .mmap = ramfs_mmap, .munmap = ramfs_munmap, .handle_fault = ramfs_handle_fault, }; static int ramfs_open_int(struct mnt_fs *fs, struct ramfs_inode *inode, fs_handle *out, int fl) { struct ramfs_handle *h; if (!(h = vfs_create_new_handle(fs, &static_ops_ramfs))) return -ENOMEM; h->inode = inode; h->spec_flags = VFS_SPFL_MMAP_SUPPORTED; retain_obj(inode); if (inode->type == VFS_DIR) { /* * If we're opening a directory, register its handle in inode's handles * list so that if unlink() is called on an entry E and there are open * handles to E's parent-dir where h->dpos == E, their dpos is moved * forward. This is a VERY CORNER CASE, but it *MUST BE* handled. */ list_node_init(&h->node); list_add_tail(&inode->handles_list, &h->node); h->dpos = list_first_obj(&inode->entries_list, struct ramfs_entry, lnode); } else { if (fl & O_TRUNC) { DEBUG_ONLY_UNSAFE(int rc =) ramfs_inode_truncate_safe(inode, 0, false); ASSERT(rc == 0); } } *out = h; return 0; } static int ramfs_open_existing_checks(int fl, struct ramfs_inode *i) { if (!(fl & O_WRONLY) && (i->mode & 0400) != 0400) return -EACCES; if ((fl & O_WRONLY) && (i->mode & 0200) != 0200) return -EACCES; if ((fl & O_RDWR) && (i->mode & 0600) != 0600) return -EACCES; if ((fl & O_DIRECTORY) && (i->type != VFS_DIR)) return -ENOTDIR; if ((fl & O_CREAT) && (fl & O_EXCL)) return -EEXIST; if ((fl & (O_WRONLY | O_RDWR)) && i->type == VFS_DIR) return -EISDIR; /* * On some systems O_TRUNC | O_RDONLY has undefined behavior and on some * the file might actually be truncated. On Tilck, that is simply NOT * allowed. */ if ((fl & O_TRUNC) && !(fl & (O_WRONLY | O_RDWR))) return -EINVAL; return 0; } static int ramfs_open(struct vfs_path *p, fs_handle *out, int fl, mode_t mod) { struct ramfs_path *rp = (struct ramfs_path *) &p->fs_path; struct ramfs_data *d = p->fs->device_data; struct ramfs_inode *i = rp->inode; struct ramfs_inode *idir = rp->dir_inode; struct locked_file *lf = NULL; int rc; if (!i) { if (!(fl & O_CREAT)) return -ENOENT; if ((idir->mode & 0300) != 0300) /* write + execute */ return -EACCES; if (!(i = ramfs_create_inode_file(d, mod, idir))) return -ENOSPC; rc = acquire_subsys_flock(p->fs, i, SUBSYS_VFS, &lf); if (rc) { ramfs_destroy_inode(d, i); return rc; } if ((rc = ramfs_dir_add_entry(idir, p->last_comp, i))) { ramfs_destroy_inode(d, i); return rc; } } else { if ((idir->mode & 0500) != 0500) /* read + execute */ return -EACCES; if ((rc = ramfs_open_existing_checks(fl, i))) return rc; if (i->type == VFS_FILE && (fl & (O_WRONLY | O_RDWR))) { rc = acquire_subsys_flock(p->fs, i, SUBSYS_VFS, &lf); if (rc) return rc; } } rc = ramfs_open_int(p->fs, i, out, fl); if (LIKELY(!rc)) { /* Success: now set the `lf` field in the file handle */ ((struct fs_handle_base *) *out)->lf = lf; } else { /* Open failed: we have to release the lock obj (if any) */ if (lf) release_subsys_flock(lf); } return rc; } <file_sep>/****************************************************************************** * * Name: hwxfsleep.c - ACPI Hardware Sleep/Wake External Interfaces * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_HARDWARE ACPI_MODULE_NAME ("hwxfsleep") /* Local prototypes */ #if (!ACPI_REDUCED_HARDWARE) static ACPI_STATUS AcpiHwSetFirmwareWakingVector ( ACPI_TABLE_FACS *Facs, ACPI_PHYSICAL_ADDRESS PhysicalAddress, ACPI_PHYSICAL_ADDRESS PhysicalAddress64); #endif static ACPI_STATUS AcpiHwSleepDispatch ( UINT8 SleepState, UINT32 FunctionId); /* * Dispatch table used to efficiently branch to the various sleep * functions. */ #define ACPI_SLEEP_FUNCTION_ID 0 #define ACPI_WAKE_PREP_FUNCTION_ID 1 #define ACPI_WAKE_FUNCTION_ID 2 /* Legacy functions are optional, based upon ACPI_REDUCED_HARDWARE */ static ACPI_SLEEP_FUNCTIONS AcpiSleepDispatch[] = { {ACPI_STRUCT_INIT (LegacyFunction, ACPI_HW_OPTIONAL_FUNCTION (AcpiHwLegacySleep)), ACPI_STRUCT_INIT (ExtendedFunction, AcpiHwExtendedSleep) }, {ACPI_STRUCT_INIT (LegacyFunction, ACPI_HW_OPTIONAL_FUNCTION (AcpiHwLegacyWakePrep)), ACPI_STRUCT_INIT (ExtendedFunction, AcpiHwExtendedWakePrep) }, {ACPI_STRUCT_INIT (LegacyFunction, ACPI_HW_OPTIONAL_FUNCTION (AcpiHwLegacyWake)), ACPI_STRUCT_INIT (ExtendedFunction, AcpiHwExtendedWake) } }; /* * These functions are removed for the ACPI_REDUCED_HARDWARE case: * AcpiSetFirmwareWakingVector * AcpiEnterSleepStateS4bios */ #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiHwSetFirmwareWakingVector * * PARAMETERS: Facs - Pointer to FACS table * PhysicalAddress - 32-bit physical address of ACPI real mode * entry point * PhysicalAddress64 - 64-bit physical address of ACPI protected * mode entry point * * RETURN: Status * * DESCRIPTION: Sets the FirmwareWakingVector fields of the FACS * ******************************************************************************/ static ACPI_STATUS AcpiHwSetFirmwareWakingVector ( ACPI_TABLE_FACS *Facs, ACPI_PHYSICAL_ADDRESS PhysicalAddress, ACPI_PHYSICAL_ADDRESS PhysicalAddress64) { ACPI_FUNCTION_TRACE (AcpiHwSetFirmwareWakingVector); /* * According to the ACPI specification 2.0c and later, the 64-bit * waking vector should be cleared and the 32-bit waking vector should * be used, unless we want the wake-up code to be called by the BIOS in * Protected Mode. Some systems (for example HP dv5-1004nr) are known * to fail to resume if the 64-bit vector is used. */ /* Set the 32-bit vector */ Facs->FirmwareWakingVector = (UINT32) PhysicalAddress; if (Facs->Length > 32) { if (Facs->Version >= 1) { /* Set the 64-bit vector */ Facs->XFirmwareWakingVector = PhysicalAddress64; } else { /* Clear the 64-bit vector if it exists */ Facs->XFirmwareWakingVector = 0; } } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiSetFirmwareWakingVector * * PARAMETERS: PhysicalAddress - 32-bit physical address of ACPI real mode * entry point * PhysicalAddress64 - 64-bit physical address of ACPI protected * mode entry point * * RETURN: Status * * DESCRIPTION: Sets the FirmwareWakingVector fields of the FACS * ******************************************************************************/ ACPI_STATUS AcpiSetFirmwareWakingVector ( ACPI_PHYSICAL_ADDRESS PhysicalAddress, ACPI_PHYSICAL_ADDRESS PhysicalAddress64) { ACPI_FUNCTION_TRACE (AcpiSetFirmwareWakingVector); if (AcpiGbl_FACS) { (void) AcpiHwSetFirmwareWakingVector (AcpiGbl_FACS, PhysicalAddress, PhysicalAddress64); } return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiSetFirmwareWakingVector) /******************************************************************************* * * FUNCTION: AcpiEnterSleepStateS4bios * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Perform a S4 bios request. * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED * ******************************************************************************/ ACPI_STATUS AcpiEnterSleepStateS4bios ( void) { UINT32 InValue; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiEnterSleepStateS4bios); /* Clear the wake status bit (PM1) */ Status = AcpiWriteBitRegister (ACPI_BITREG_WAKE_STATUS, ACPI_CLEAR_STATUS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiHwClearAcpiStatus (); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * 1) Disable all GPEs * 2) Enable all wakeup GPEs */ Status = AcpiHwDisableAllGpes (); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiGbl_SystemAwakeAndRunning = FALSE; Status = AcpiHwEnableAllWakeupGpes (); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ACPI_FLUSH_CPU_CACHE (); Status = AcpiHwWritePort (AcpiGbl_FADT.SmiCommand, (UINT32) AcpiGbl_FADT.S4BiosRequest, 8); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } do { AcpiOsStall (ACPI_USEC_PER_MSEC); Status = AcpiReadBitRegister (ACPI_BITREG_WAKE_STATUS, &InValue); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } while (!InValue); return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiEnterSleepStateS4bios) #endif /* !ACPI_REDUCED_HARDWARE */ /******************************************************************************* * * FUNCTION: AcpiHwSleepDispatch * * PARAMETERS: SleepState - Which sleep state to enter/exit * FunctionId - Sleep, WakePrep, or Wake * * RETURN: Status from the invoked sleep handling function. * * DESCRIPTION: Dispatch a sleep/wake request to the appropriate handling * function. * ******************************************************************************/ static ACPI_STATUS AcpiHwSleepDispatch ( UINT8 SleepState, UINT32 FunctionId) { ACPI_STATUS Status; ACPI_SLEEP_FUNCTIONS *SleepFunctions = &AcpiSleepDispatch[FunctionId]; #if (!ACPI_REDUCED_HARDWARE) /* * If the Hardware Reduced flag is set (from the FADT), we must * use the extended sleep registers (FADT). Note: As per the ACPI * specification, these extended registers are to be used for HW-reduced * platforms only. They are not general-purpose replacements for the * legacy PM register sleep support. */ if (AcpiGbl_ReducedHardware) { Status = SleepFunctions->ExtendedFunction (SleepState); } else { /* Legacy sleep */ Status = SleepFunctions->LegacyFunction (SleepState); } return (Status); #else /* * For the case where reduced-hardware-only code is being generated, * we know that only the extended sleep registers are available */ Status = SleepFunctions->ExtendedFunction (SleepState); return (Status); #endif /* !ACPI_REDUCED_HARDWARE */ } /******************************************************************************* * * FUNCTION: AcpiEnterSleepStatePrep * * PARAMETERS: SleepState - Which sleep state to enter * * RETURN: Status * * DESCRIPTION: Prepare to enter a system sleep state. * This function must execute with interrupts enabled. * We break sleeping into 2 stages so that OSPM can handle * various OS-specific tasks between the two steps. * ******************************************************************************/ ACPI_STATUS AcpiEnterSleepStatePrep ( UINT8 SleepState) { ACPI_STATUS Status; ACPI_OBJECT_LIST ArgList; ACPI_OBJECT Arg; UINT32 SstValue; ACPI_FUNCTION_TRACE (AcpiEnterSleepStatePrep); Status = AcpiGetSleepTypeData (SleepState, &AcpiGbl_SleepTypeA, &AcpiGbl_SleepTypeB); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Execute the _PTS method (Prepare To Sleep) */ ArgList.Count = 1; ArgList.Pointer = &Arg; Arg.Type = ACPI_TYPE_INTEGER; Arg.Integer.Value = SleepState; Status = AcpiEvaluateObject (NULL, METHOD_PATHNAME__PTS, &ArgList, NULL); if (ACPI_FAILURE (Status) && Status != AE_NOT_FOUND) { return_ACPI_STATUS (Status); } /* Setup the argument to the _SST method (System STatus) */ switch (SleepState) { case ACPI_STATE_S0: SstValue = ACPI_SST_WORKING; break; case ACPI_STATE_S1: case ACPI_STATE_S2: case ACPI_STATE_S3: SstValue = ACPI_SST_SLEEPING; break; case ACPI_STATE_S4: SstValue = ACPI_SST_SLEEP_CONTEXT; break; default: SstValue = ACPI_SST_INDICATOR_OFF; /* Default is off */ break; } /* * Set the system indicators to show the desired sleep state. * _SST is an optional method (return no error if not found) */ AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, SstValue); return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiEnterSleepStatePrep) /******************************************************************************* * * FUNCTION: AcpiEnterSleepState * * PARAMETERS: SleepState - Which sleep state to enter * * RETURN: Status * * DESCRIPTION: Enter a system sleep state * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED * ******************************************************************************/ ACPI_STATUS AcpiEnterSleepState ( UINT8 SleepState) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiEnterSleepState); if ((AcpiGbl_SleepTypeA > ACPI_SLEEP_TYPE_MAX) || (AcpiGbl_SleepTypeB > ACPI_SLEEP_TYPE_MAX)) { ACPI_ERROR ((AE_INFO, "Sleep values out of range: A=0x%X B=0x%X", AcpiGbl_SleepTypeA, AcpiGbl_SleepTypeB)); return_ACPI_STATUS (AE_AML_OPERAND_VALUE); } Status = AcpiHwSleepDispatch (SleepState, ACPI_SLEEP_FUNCTION_ID); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiEnterSleepState) /******************************************************************************* * * FUNCTION: AcpiLeaveSleepStatePrep * * PARAMETERS: SleepState - Which sleep state we are exiting * * RETURN: Status * * DESCRIPTION: Perform the first state of OS-independent ACPI cleanup after a * sleep. Called with interrupts DISABLED. * We break wake/resume into 2 stages so that OSPM can handle * various OS-specific tasks between the two steps. * ******************************************************************************/ ACPI_STATUS AcpiLeaveSleepStatePrep ( UINT8 SleepState) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiLeaveSleepStatePrep); Status = AcpiHwSleepDispatch (SleepState, ACPI_WAKE_PREP_FUNCTION_ID); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiLeaveSleepStatePrep) /******************************************************************************* * * FUNCTION: AcpiLeaveSleepState * * PARAMETERS: SleepState - Which sleep state we are exiting * * RETURN: Status * * DESCRIPTION: Perform OS-independent ACPI cleanup after a sleep * Called with interrupts ENABLED. * ******************************************************************************/ ACPI_STATUS AcpiLeaveSleepState ( UINT8 SleepState) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiLeaveSleepState); Status = AcpiHwSleepDispatch (SleepState, ACPI_WAKE_FUNCTION_ID); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiLeaveSleepState) <file_sep> Testing Tilck ------------------------ The project has four types of tests: * [Unit tests](#unit-tests): the arch-independent part of the kernel (most of it) is built as a static library for the *host* architecture and linked together with all the C and C++ files in `tests/unit` and the [googletest] library. * [System tests](#system-tests): classic system tests using the syscall interface. Their source is located in `tests/system`. All those files are linked together as part of the `devshell` user application. * [Kernel self-tests](#kernel-self-tests): a special type of tests built as part of the kernel itself, runnable through a special Tilck syscall. They are located in the `tests/self` directory. * [Interactive tests](#interactive-tests): a special type of tests that simulate real user input via a virtual PS/2 keyboard (through QEMU's monitor) and parse the actual graphical output of Tilck's framebuffer console, comparing it to an expected text screen. Have something in common with [output comparison testing] (see below for more). [output comparison testing]: https://en.wikipedia.org/wiki/Software_testing#Output_comparison_testing Unit tests ------------- Unit tests are a *must* for each software project. They offer a simple way to test portable code in a controlled environment, completely outside of the *real* project. That's super convenient because there's no kernel involved: just a simple Linux binary. The downside of unit tests is that they cannot test low-level code, requiring real (or virtual) hardware. Mock-ups help to overcome most of those limitations and are used in this project but still, unit tests cannot replace other kinds of testing. Said that, most of the code *can* and *shall be* be tested this way. ![Tilck's unit tests](http://vvaltchev.github.io/tilck_imgs/v2/gtests.png) #### How the unit tests are compiled As mentioned above, Tilck's unit tests are compiled by linking together a static library made by compiling kernel's arch-independent code for the *host* architecture, plus the files in `tests/unit`. It is important to remark what building for the *host* architecture means: the kernel code *and* the tests must build on *any* architecture, even if Tilck has no support it, simply because they are made by *portable* code. For example, while *currently* Tilck has no ARM support, its unit tests build and run just fine on any ARM machine running Linux. The testing framework used is [googletest] and all the tests are written in C++11. That's because C++'s abstractions are very convenient for writing tests in a shorter and more expressive way compared to C. Also, the overhead of having temporary C++ objects created, copied, and destroyed (even quite often) is *insignificant* compared to the overhead of starting a VM for running the kernel itself. The unit tests are the *fastest* way of testing Tilck's code at runtime: currently, the whole suite passes in **under 4 seconds**, using the slowest debug build and in **under 2 seconds** in the case of release builds. #### Prerequisites In order to build the unit tests, it is necessary to download and build the [googletest] library in Tilck's toolchain. To do that, just run: ./scripts/build_toolchain -s build_gtest #### Build and run Building the unit tests is as simple as running: make gtests And running them is simple as: ./build/gtests It's worth noticing that the [googletest] framework offers nice command-line options such as `--gtest_filter`. To list them all, just run the executable with the `--help` option. For out-of-tree builds and other build-related topics, check the dedicated [building] document. #### Special configurations Despite unit tests' the code built is supposed to be portable, sometimes subtle portability bugs issues come out. For example, because the host machine is always x86_64 and Tilck's only target architecture for the moment is i686, that means that unit tests are never built on 32-bit machines, while the kernel noarch code is built both for 32-bit and for 64-bit machines. To make the unit tests robust against any kind of 32/64 bit portability issues, a special option has been introduced in Tilck's build system: `ARCH_GTESTS`. When it's enabled, the unit tests are built for the *target* architecture instead. Of course, in the general case we cannot run those tests on the *host* machine, but in the lucky x86 case we actually *can* do that. Such build configuration is part of the CI testing and helped discover and fix a fair amount of portability issues. To build the unit tests for the *target* architecture, first build the [googletest] framework for that architecture with: ./scripts/build_toolchain -s build_gtest_arch And then enable the `ARCH_GTESTS` CMake option (see [building] document to learn how to that). [building]: building.md [googletest]: https://github.com/google/googletest System tests --------------- Tilck's system tests are exactly what everybody would expect as a primary way of testing a kernel: userspace applications executing syscalls and checking their effect. In this case, all of them are part of one single binary, called `devshell`. That app is a trivial shell that was actually used in the past as a shell when Tilck was not ready to run Busybox's `ASH` yet. Today, it's used just as a runner for `shellcmds`, an *internal name* for system tests. The source code of `devshell` is split between `userapps/devshell`, which contains application's core and the individual *shellcmds*, which are located in `tests/system`. ![Tilck's devshell](http://vvaltchev.github.io/tilck_imgs/v2/devshell.png) #### Running the tests on Tilck One way of running those tests is to do that directly on Tilck. Just run: runall That works because `runall` is a symlink to `devshell` and it's equivalent to running: devshell -c runall Of course, any specific test can be run instead of `runall` in the same way: devshell -c <TESTNAME> It's possible to list all the tests in a human-friendly form by running `devshell` and then `help` or by running: `devshell -c help`. Tilck's test infrastructure instead, runs `devshell -l`. ![Tilck's system tests](http://vvaltchev.github.io/tilck_imgs/v2/runall.png) #### Running the tests with the runner Another way of running Tilck's system tests is using `run_all_tests`: a python script designed to run multiple types of tests. Due to its versatility, it is possible that *in the future* it will be able to run *all* the types of tests supported in the Tilck project. Back to the topic, running just the classic system tests is simple as: <BUILD_DIR>/st/run_all_tests -T shellcmd It essential to remark that, by default, this script runs *each* test in a dedicated VM. This means, powering on a QEMU virtual machine, booting Tilck, and only then running just a single test. It is *slow*, but not so much: all of that happens in **less than 1 second** on a typical laptop (using KVM) and currently, all the tests way pass in less than 1 minute (slowest debug build). The main advantage of this approach is that if the kernel crashes on a single test, we'll still have it tested on all the other cases. Another advantage is that there's a *strict* timeout for each test, enforced by the test runner itself and, in case of timeout, the VM is killed. Despite that, it is still desirable being able to run all the system tests by powering just one VM; to do that, just add the `-c` option to command above: <BUILD_DIR>/st/run_all_tests -T shellcmd -c In this case, the runner will just run `devshell -c runall` as we saw above. In case of a failure, we'll still see the whole output but, the runner will consider `runall` as one test, in the *tests passed* report at the end. Also, the whole run will have a single timeout from the runner's point of view. ![Tilck's test runner](http://vvaltchev.github.io/tilck_imgs/v2/runner01.png) #### Runner's other options The runner supports a variety of other options. Check them with `--help`. One of them is, indeed, `-T` which allows us to specify the test type. Running the command above without `-T shellcmd` will work but it will *also* run the kernel self-tests and any other kind of tests eventually supported. With the `-l` option it is possible to list the tests matching the current criteria (dry-run), while with the `-f` option it is possible to filter the tests using a regex. #### The "extra" special test While anything part of the kernel/userspace interface can be tested with *shellcmds* as described above, sometimes that's simply not very convenient to do. For example, to check that BusyBox's `tar` works as expected on Tilck, it would be nicer to use a shell script instead of writing a test in C. That's why a special shellcmd called `extra` has been introduced. It's just a mini test-runner for all the scripts in `tests/system/scripts`. It fails when a script fails (exits with a code different than 0). This "special" shellcmd is actually a regular shellcmd from the point of view of the test infrastructure and can be run the same way as all the other tests of the same type. Kernel self-tests ------------------- Tilck's self-tests are, roughly speaking, just a bunch of kernel functions that our `devshell` run by calling a special syscall, `sys_tilck_cmd()`. Their source is located in the `tests/self` directory. By default, they're built-in Tilck, on any configuration except when `TINY_KERNEL` is enabled. To compile them out of the kernel's binary, just disable the `KERNEL_SELFTESTS` CMake option (see [building]). ## Running the self-tests Because a failure in a *kernel* self-test means almost always a kernel panic, most of the time it isn't very convenient to run them manually in Tilck. Also, because the self-tests *by definition* check the correctness of *core* kernel features like mutexes, there's no safe way (in general) to impose a timeout and *safely kill* the test when it's taking too long to complete: that can be done safely only from *outside* the kernel itself. Because of all of that, it is better to run the self-tests with the `run_all_tests` runner, on the host machine: it will power on a VM for each test and, of course, it will kill the VM in case of a timeout. To do that, run: <BUILD_DIR>/st/run_all_tests -T selftest To list all the self-tests run: <BUILD_DIR>/st/run_all_tests -T selftest -l ## Running the self-tests directly on Tilck In some special cases, it *does* make sense to run some self-tests directly on Tilck, especially the *perf* ones. Those tests are actually *performance* tests, not *functional* ones. A classic test of this kind is `kmalloc_perf`, introduced to measure the performance of Tilck's memory allocator. To run it or any other self-test directly on Tilck, use the `selftest` symlink to `devshell` this way: selftest <test-name> Some tests like `kmalloc_perf` are affected a lot by the optimization level. If you run them on Tilck, you'll see quite a difference between regular DEBUG builds and optimized RELEASE builds with `DEBUG_CHECKS=0` (see [building]). One more nice thing about the `kmalloc_perf` test is that it can be run as a unit test as well. In particular, if the unit tests are built for the same *target* architecture as the kernel itself (using `ARCH_GTESTS=1`, see [Unit tests](#unit-tests) (above) and [building]), we can reproduce on the *host* machine a performance test with results very close to what we get can on get Tilck: that makes a lot easier to measure and improve the implementation of any piece of kernel code. Interactive tests ------------------- #### Introduction While it would be great to test the whole kernel just using the above-mentioned test types, sometimes that's not possible. Consider the PS/2 keyboard driver: its code is *never* covered during the system tests because they use the serial port for input/output and that's not a defect: that's the *right* way to fetch the output from system tests. Simply, even the *right* way have some inevitable limitations. While it's true that with some serious mocking it would be possible to test part of the PS/2 driver in unit tests, that's not very convenient and it's far too *unrealistic*: no IRQs, no (real or emulated) 8042 controller, etc. A better way is to test it against a *reference* implementation like the one in QEMU but, how to do that? QEMU's monitor has an interface for sending keystrokes to the VM, but the real problem is the following: when Tilck's console gets its input from the PS/2 keyboard, its output goes to the default (video) monitor, not to the serial port and that's how it should be. In order to check if the output produced after a given input is correct, the test infrastructure needs somehow to compare what's on the (virtual) screen with something expected. In other words, that means comparing images and that's pretty problematic. #### Why comparing images is bad It should be clear at this point that testing some code-paths in the kernel requires somehow to compare images to check the correctness of the output and that's pretty bad, as the intuition might suggest. Comparing images as binary blobs is easy but *extremely fragile* because even if a *single* pixel differs, the whole test will fail. This issue can be mitigated by avoiding mutable elements on the screen (e.g. date/time info) but the problem is still there because small and innocent changes will break such tests. In addition to that, images take space and that creates logistic challenges as well: where to store the set of expected images (screenshots)? Project's git repository doesn't look like a good place for that purpose. Create a dedicated "assets" git repo and use git sub-modules or make the scripts to download the "assets" from somewhere else? How to keep everything in sync? All of those approaches could work with enough effort, but none of them is in Tilck's minimalistic/extra-light style. #### Tilck's approach What would be really cool is to work with VM screenshots the same way we do with plain text because, after all, we're always only interested in the text contained in those images, nothing else. So, the solution is to use an OCR, right? **Wrong**: OCRs are big, bloated, and tend to be not very reliable even with purely digitally-generated images, like in this case. A **perfect** solution would be to have a custom OCR that knows exactly the font used by Tilck and take advantage of that to do an image-to-text conversion in a **100% reliable** way. While that initially seemed hard to do, it turned out that it required just a few hundred lines of C code (also thanks to the fact that QEMU saves screenshots in the [PPM] file format). That's how the [pnm2text] tool was born. Now, with a perfect image-to-text conversion not only it's trivial to do exact output comparisons like in the case of [output comparison testing], but we can also define tests that just search for a series of words in the output and, based on that, define test's outcome as *pass* or *fail*. Both kinds of tests exist in Tilck. [PPM]: https://en.wikipedia.org/wiki/Netpbm#File_formats [pnm2text]: ../scripts/build_apps/pnm2text.c #### Running the interactive tests (advanced) Tilck's interactive tests require a special build configuration and extra packages in the toolchain. Please check [building] before proceeding further. **Steps** - Check that you have [ImageMagick] installed on the system - Check and install the list of extra packages required for the special build in the `cmake_run` script (look for the `--intr` option). Currently, only `vim` is required. - Create a dedicated build directory and enter there - Run: `<TILCK>/cmake_run --intr` - Build the kernel as always with `make` - Run the tests with: `./st/run_interactive_test -a` In case of an incompatible configuration, it will fail by reporting one or multiple INVALID CONFIG errors like: [interactive tests runner] INVALID CONFIG: expected EXTRA_VIM to be `True` [interactive tests runner] INVALID CONFIG: expected FB_CONSOLE_BANNER to be `False` [interactive tests runner] INVALID CONFIG: expected FB_CONSOLE_CURSOR_BLINK to be `False` ![Tilck screenshots](http://vvaltchev.github.io/tilck_imgs/v2/interactive03.png) **Using the top runner** It is certainly possible and convenient to use the main runner (`run_all_tests`) for the interactive tests as well. That's because of its filter feature and because it displays the output of a test run only in case of a failure: it is *higher-level* tool, designed to run *many* tests. To run the interactive tests with it, just execute: ./st/run_all_tests -T interactive -t any Notes: 1. It is necessary to use the `-t` option because the timeout length of interactive tests is higher than the default timeout used by the runner. 2. In case of a **configuration incompatible** with interactive tests, the runner will just say that there aren't any tests matching the criteria. Also, listing all the tests with `-L` won't mention the interactive tests at all. That's because, 99% of the time people won't use a build config for interactive tests: as mentioned before, these are a kind of *exotic* type of tests and if there are not available, that's perfectly fine. 3. To run the interactive tests along with all the other tests as well, just drop the `-T interactive` option. Keep in mind that doing so will also run the `long` shellcmd tests. Set a timeout different than `any` to avoid that. Checking the list of all tests with `-L` and the timeout labels with `-j` will help. [ImageMagick]: https://imagemagick.org/ <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(EFI_BUILD_BASE_FLAGS_LIST "") list( APPEND EFI_BUILD_BASE_FLAGS_LIST -D__TILCK_EFI_BOOTLOADER__ -fno-stack-protector -fshort-wchar -mno-red-zone -DEFI_DEBUG=0 # Because of -Wundef -DEFI_DEBUG_CLEAR_MEMORY=0 # Because of -Wundef ${GENERAL_DEFS_LIST} ${DBG_FLAGS_LIST} ${OPT_FLAGS_LIST} ${WARN_FLAGS_LIST} ${FREESTANDING_FLAGS_LIST} ${SAFER_BEHAVIOR_FLAGS_LIST} ) JOIN("${EFI_BUILD_BASE_FLAGS_LIST}" ${SPACE} EFI_BUILD_BASE_FLAGS) set( efi_bootloader_deps ) if (${ARCH} STREQUAL "i386") add_subdirectory(ia32) list( APPEND efi_bootloader_deps efi_ia32_bootloader ${EFI_ia32_FILE} ) endif() if (${HOST_ARCH} STREQUAL "x86_64") add_subdirectory(x86_64) list( APPEND efi_bootloader_deps efi_x86_64_bootloader ${EFI_x86_64_FILE} ) endif() add_custom_target( efi_bootloader DEPENDS ${efi_bootloader_deps} ) <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu fixhex16 = bu.fixhex16 fixhex32 = bu.fixhex32 class printer_regs: def __init__(self, val): self.val = val def to_string(self): return bu.fmt_type("struct x86_regs", self.val) def children(self): r = self.val resume_eip = gdb.parse_and_eval( "(void *){}".format(r["kernel_resume_eip"]) ) resume_eip_str = str(resume_eip) eip = r["eip"] eip_str = None if eip < bu.config.KERNEL_BASE_VA: eip_str = fixhex32(r["eip"]) else: eip_str = gdb.parse_and_eval( "(void *){}".format(eip) ) cs = r["cs"] & 0xffff ds = r["ds"] & 0xffff es = r["es"] & 0xffff fs = r["fs"] & 0xffff gs = r["gs"] & 0xffff res = [ ("resume_eip ", resume_eip), ("custom_flags", fixhex32(r["custom_flags"])), ("gs ", fixhex16(gs)), ("es ", fixhex16(es)), ("ds ", fixhex16(ds)), ("fs ", fixhex16(fs)), ("edi ", fixhex32(r["edi"])), ("esi ", fixhex32(r["esi"])), ("ebp ", fixhex32(r["ebp"])), ("esp ", fixhex32(r["esp"])), ("ebx ", fixhex32(r["ebx"])), ("edx ", fixhex32(r["edx"])), ("ecx ", fixhex32(r["ecx"])), ("eax ", fixhex32(r["eax"])), ("int_num ", r["int_num"]), ("err_code ", fixhex32(r["err_code"])), ("eip ", eip_str), ("cs ", fixhex16(cs)), ("eflags ", fixhex32(r["eflags"])), ("useresp ", fixhex32(r["useresp"])), ] if resume_eip_str.find("asm_save_regs_and_schedule") == -1: # Actual value of the stack segment ss = r["ss"] & 0xffff res += [ ("ss ", fixhex16(ss)), ] else: # asm_save_regs_and_schedule() does NOT save SS on the stack. # What we see there instead is its 1st argument, caller's return EIP. calc_eip = gdb.parse_and_eval("(void *){}".format(r["ss"])) res.append(("[true_eip] ", calc_eip)) return res bu.register_tilck_regex_pp( 'regs_t', '^(regs_t|x86_regs)$', printer_regs ) <file_sep> /* * List of PCI IDs generated by scripts/dev/generate_pci_ids, part of the * Tilck project. * * Source data fetched from the `pciids` project: * https://github.com/pciutils/pciids/blob/master/pci.ids?raw=true * * Follows the original comments from the top of the `pci.ids` file. * * * List of PCI ID's * * Version: 2020.08.13 * Date: 2020-08-13 03:15:02 * * Maintained by <NAME>, <NAME>, and other volunteers from * the PCI ID Project at https://pci-ids.ucw.cz/. * * New data are always welcome, especially if they are accurate. If you have * anything to contribute, please follow the instructions at the web site. * * This file can be distributed under either the GNU General Public License * (version 2 or higher) or the 3-clause BSD License. * * The database is a compilation of factual data, and as such the copyright * only covers the aggregation and formatting. The copyright is held by * <NAME> and <NAME>. * */ #include <tilck/kernel/pci.h> const struct pci_vendor pci_vendors_list[] = { { 0x0001, "SafeNet (wrong ID)" }, { 0x0010, "Allied Telesis, Inc (Wrong ID)" }, { 0x0014, "Loongson Technology LLC" }, { 0x001c, "PEAK-System Technik GmbH" }, { 0x003d, "Lockheed Martin-Marietta Corp" }, { 0x0059, "Tiger Jet Network Inc. (Wrong ID)" }, { 0x0070, "Hauppauge computer works Inc." }, { 0x0071, "Nebula Electronics Ltd." }, { 0x0095, "Silicon Image, Inc. (Wrong ID)" }, { 0x00a7, "Teles AG (Wrong ID)" }, { 0x0100, "nCipher Security" }, { 0x0123, "General Dynamics" }, { 0x0128, "Dell (wrong ID)" }, { 0x018a, "LevelOne" }, { 0x01de, "Oxide Computer Company" }, { 0x021b, "Compaq Computer Corporation" }, { 0x0270, "Hauppauge computer works Inc. (Wrong ID)" }, { 0x0291, "Davicom Semiconductor, Inc. (Wrong ID)" }, { 0x02ac, "SpeedStream" }, { 0x02e0, "XFX Pine Group Inc. (Wrong ID)" }, { 0x0303, "Hewlett-Packard Company (Wrong ID)" }, { 0x0308, "ZyXEL Communications Corporation (Wrong ID)" }, { 0x0315, "SK-Electronics Co., Ltd." }, { 0x0357, "TTTech Computertechnik AG (Wrong ID)" }, { 0x0432, "SCM Microsystems, Inc." }, { 0x0497, "Dell Inc. (wrong ID)" }, { 0x0675, "Dynalink" }, { 0x0721, "Sapphire, Inc." }, { 0x0731, "Jingjia Microelectronics Co Ltd" }, { 0x0777, "Ubiquiti Networks, Inc." }, { 0x0795, "Wired Inc." }, { 0x07d1, "D-Link System Inc" }, { 0x0824, "T1042 [Freescale]" }, { 0x0925, "VIA Technologies, Inc. (Wrong ID)" }, { 0x0a89, "BREA Technologies Inc" }, { 0x0b0b, "Rhino Equipment Corp." }, { 0x0e11, "Compaq Computer Corporation" }, { 0x0e55, "HaSoTec GmbH" }, { 0x0eac, "SHF Communication Technologies AG" }, { 0x0f62, "Acrox Technologies Co., Ltd." }, { 0x1000, "Broadcom / LSI" }, { 0x1001, "Kolter Electronic" }, { 0x1002, "Advanced Micro Devices, Inc. [AMD/ATI]" }, { 0x1003, "ULSI Systems" }, { 0x1004, "VLSI Technology Inc" }, { 0x1005, "Avance Logic Inc. [ALI]" }, { 0x1006, "Reply Group" }, { 0x1007, "NetFrame Systems Inc" }, { 0x1008, "Epson" }, { 0x100a, "Phoenix Technologies" }, { 0x100b, "National Semiconductor Corporation" }, { 0x100c, "Tseng Labs Inc" }, { 0x100d, "AST Research Inc" }, { 0x100e, "Weitek" }, { 0x1010, "Video Logic, Ltd." }, { 0x1011, "Digital Equipment Corporation" }, { 0x1012, "Micronics Computers Inc" }, { 0x1013, "Cirrus Logic" }, { 0x1014, "IBM" }, { 0x1015, "LSI Logic Corp of Canada" }, { 0x1016, "ICL Personal Systems" }, { 0x1017, "SPEA Software AG" }, { 0x1018, "Unisys Systems" }, { 0x1019, "Elitegroup Computer Systems" }, { 0x101a, "AT&T GIS (NCR)" }, { 0x101b, "Vitesse Semiconductor" }, { 0x101c, "Western Digital" }, { 0x101d, "Maxim Integrated Products" }, { 0x101e, "American Megatrends Inc." }, { 0x101f, "PictureTel" }, { 0x1020, "Hitachi Computer Products" }, { 0x1021, "OKI Electric Industry Co. Ltd." }, { 0x1022, "Advanced Micro Devices, Inc. [AMD]" }, { 0x1023, "Trident Microsystems" }, { 0x1024, "Zenith Data Systems" }, { 0x1025, "Acer Incorporated [ALI]" }, { 0x1028, "Dell" }, { 0x1029, "Siemens Nixdorf IS" }, { 0x102a, "LSI Logic" }, { 0x102b, "Matrox Electronics Systems Ltd." }, { 0x102c, "Chips and Technologies" }, { 0x102d, "Wyse Technology Inc." }, { 0x102e, "Olivetti Advanced Technology" }, { 0x102f, "Toshiba America" }, { 0x1030, "TMC Research" }, { 0x1031, "Miro Computer Products AG" }, { 0x1032, "Compaq" }, { 0x1033, "NEC Corporation" }, { 0x1034, "Framatome Connectors USA Inc." }, { 0x1035, "Comp. & Comm. Research Lab" }, { 0x1036, "Future Domain Corp." }, { 0x1037, "Hitachi Micro Systems" }, { 0x1038, "AMP, Inc" }, { 0x1039, "Silicon Integrated Systems [SiS]" }, { 0x103a, "Seiko Epson Corporation" }, { 0x103b, "Tatung Corp. Of America" }, { 0x103c, "Hewlett-Packard Company" }, { 0x103e, "Solliday Engineering" }, { 0x103f, "Synopsys/Logic Modeling Group" }, { 0x1040, "Accelgraphics Inc." }, { 0x1041, "Computrend" }, { 0x1042, "Micron" }, { 0x1043, "ASUSTeK Computer Inc." }, { 0x1044, "Adaptec (formerly DPT)" }, { 0x1045, "OPTi Inc." }, { 0x1046, "IPC Corporation, Ltd." }, { 0x1047, "Genoa Systems Corp" }, { 0x1048, "Elsa AG" }, { 0x1049, "Fountain Technologies, Inc." }, { 0x104a, "STMicroelectronics" }, { 0x104b, "BusLogic" }, { 0x104c, "Texas Instruments" }, { 0x104d, "Sony Corporation" }, { 0x104e, "Oak Technology, Inc" }, { 0x104f, "Co-time Computer Ltd" }, { 0x1050, "Winbond Electronics Corp" }, { 0x1051, "Anigma, Inc." }, { 0x1052, "?Young Micro Systems" }, { 0x1053, "Young Micro Systems" }, { 0x1054, "Hitachi, Ltd" }, { 0x1055, "Microchip Technology / SMSC" }, { 0x1056, "ICL" }, { 0x1057, "Motorola" }, { 0x1058, "Electronics & Telecommunications RSH" }, { 0x1059, "Kontron" }, { 0x105a, "Promise Technology, Inc." }, { 0x105b, "Foxconn International, Inc." }, { 0x105c, "Wipro Infotech Limited" }, { 0x105d, "Number 9 Computer Company" }, { 0x105e, "Vtech Computers Ltd" }, { 0x105f, "Infotronic America Inc" }, { 0x1060, "United Microelectronics [UMC]" }, { 0x1061, "I.I.T." }, { 0x1062, "Maspar Computer Corp" }, { 0x1063, "Ocean Office Automation" }, { 0x1064, "Alcatel" }, { 0x1065, "Texas Microsystems" }, { 0x1066, "PicoPower Technology" }, { 0x1067, "Mitsubishi Electric" }, { 0x1068, "Diversified Technology" }, { 0x1069, "Mylex Corporation" }, { 0x106a, "Aten Research Inc" }, { 0x106b, "Apple Inc." }, { 0x106c, "Hynix Semiconductor" }, { 0x106d, "Sequent Computer Systems" }, { 0x106e, "DFI, Inc" }, { 0x106f, "City Gate Development Ltd" }, { 0x1070, "Daewoo Telecom Ltd" }, { 0x1071, "Mitac" }, { 0x1072, "GIT Co Ltd" }, { 0x1073, "Yamaha Corporation" }, { 0x1074, "NexGen Microsystems" }, { 0x1075, "Advanced Integrations Research" }, { 0x1076, "Chaintech Computer Co. Ltd" }, { 0x1077, "QLogic Corp." }, { 0x1078, "Cyrix Corporation" }, { 0x1079, "I-Bus" }, { 0x107a, "NetWorth" }, { 0x107b, "Gateway, Inc." }, { 0x107c, "LG Electronics [Lucky Goldstar Co. Ltd]" }, { 0x107d, "LeadTek Research Inc." }, { 0x107e, "Interphase Corporation" }, { 0x107f, "Data Technology Corporation" }, { 0x1080, "Contaq Microsystems" }, { 0x1081, "Supermac Technology" }, { 0x1082, "EFA Corporation of America" }, { 0x1083, "Forex Computer Corporation" }, { 0x1084, "Parador" }, { 0x1086, "J. Bond Computer Systems" }, { 0x1087, "Cache Computer" }, { 0x1088, "Microcomputer Systems (M) Son" }, { 0x1089, "Data General Corporation" }, { 0x108a, "SBS Technologies" }, { 0x108c, "Oakleigh Systems Inc." }, { 0x108d, "Olicom" }, { 0x108e, "Oracle/SUN" }, { 0x108f, "Systemsoft" }, { 0x1090, "Compro Computer Services, Inc." }, { 0x1091, "Intergraph Corporation" }, { 0x1092, "Diamond Multimedia Systems" }, { 0x1093, "National Instruments" }, { 0x1094, "First International Computers [FIC]" }, { 0x1095, "Silicon Image, Inc." }, { 0x1096, "Alacron" }, { 0x1097, "Appian Technology" }, { 0x1098, "Quantum Designs (H.K.) Ltd" }, { 0x1099, "Samsung Electronics Co., Ltd" }, { 0x109a, "<NAME>" }, { 0x109b, "Gemlight Computer Ltd." }, { 0x109c, "Megachips Corporation" }, { 0x109d, "Zida Technologies Ltd." }, { 0x109e, "Brooktree Corporation" }, { 0x109f, "Trigem Computer Inc." }, { 0x10a0, "Meidensha Corporation" }, { 0x10a1, "Juko Electronics Ind. Co. Ltd" }, { 0x10a2, "Quantum Corporation" }, { 0x10a3, "Everex Systems Inc" }, { 0x10a4, "Globe Manufacturing Sales" }, { 0x10a5, "Smart Link Ltd." }, { 0x10a6, "Informtech Industrial Ltd." }, { 0x10a7, "Benchmarq Microelectronics" }, { 0x10a8, "Sierra Semiconductor" }, { 0x10a9, "Silicon Graphics Intl. Corp." }, { 0x10aa, "ACC Microelectronics" }, { 0x10ab, "Digicom" }, { 0x10ac, "Honeywell IAC" }, { 0x10ad, "Symphony Labs" }, { 0x10ae, "Cornerstone Technology" }, { 0x10af, "Micro Computer Systems Inc" }, { 0x10b0, "CardExpert Technology" }, { 0x10b1, "Cabletron Systems Inc" }, { 0x10b2, "Raytheon Company" }, { 0x10b3, "Databook Inc" }, { 0x10b4, "STB Systems Inc" }, { 0x10b5, "PLX Technology, Inc." }, { 0x10b6, "Madge Networks" }, { 0x10b7, "3Com Corporation" }, { 0x10b8, "Standard Microsystems Corp [SMC]" }, { 0x10b9, "ULi Electronics Inc." }, { 0x10ba, "Mitsubishi Electric Corp." }, { 0x10bb, "Dapha Electronics Corporation" }, { 0x10bc, "Advanced Logic Research" }, { 0x10bd, "Surecom Technology" }, { 0x10be, "Tseng Labs International Co." }, { 0x10bf, "Most Inc" }, { 0x10c0, "Boca Research Inc." }, { 0x10c1, "ICM Co., Ltd." }, { 0x10c2, "Auspex Systems Inc." }, { 0x10c3, "Samsung Semiconductors, Inc." }, { 0x10c4, "Award Software International Inc." }, { 0x10c5, "Xerox Corporation" }, { 0x10c6, "Rambus Inc." }, { 0x10c7, "Media Vision" }, { 0x10c8, "Neomagic Corporation" }, { 0x10c9, "Dataexpert Corporation" }, { 0x10ca, "Fujitsu Microelectr., Inc." }, { 0x10cb, "Omron Corporation" }, { 0x10cc, "Mai Logic Incorporated" }, { 0x10cd, "Advanced System Products, Inc" }, { 0x10ce, "Radius" }, { 0x10cf, "Fujitsu Limited." }, { 0x10d1, "FuturePlus Systems Corp." }, { 0x10d2, "Molex Incorporated" }, { 0x10d3, "Jabil Circuit Inc" }, { 0x10d4, "Hualon Microelectronics" }, { 0x10d5, "Autologic Inc." }, { 0x10d6, "Cetia" }, { 0x10d7, "BCM Advanced Research" }, { 0x10d8, "Advanced Peripherals Labs" }, { 0x10d9, "Macronix, Inc. [MXIC]" }, { 0x10da, "Compaq IPG-Austin" }, { 0x10db, "Rohm LSI Systems, Inc." }, { 0x10dc, "CERN/ECP/EDU" }, { 0x10dd, "<NAME>" }, { 0x10de, "NVIDIA Corporation" }, { 0x10df, "Emulex Corporation" }, { 0x10e0, "Integrated Micro Solutions Inc." }, { 0x10e1, "Tekram Technology Co.,Ltd." }, { 0x10e2, "Aptix Corporation" }, { 0x10e3, "Tundra Semiconductor Corp." }, { 0x10e4, "Tandem Computers" }, { 0x10e5, "Micro Industries Corporation" }, { 0x10e6, "Gainbery Computer Products Inc." }, { 0x10e7, "Vadem" }, { 0x10e8, "Applied Micro Circuits Corp." }, { 0x10e9, "Alps Electric Co., Ltd." }, { 0x10ea, "Integraphics" }, { 0x10eb, "Artists Graphics" }, { 0x10ec, "Realtek Semiconductor Co., Ltd." }, { 0x10ed, "Ascii Corporation" }, { 0x10ee, "Xilinx Corporation" }, { 0x10ef, "Racore Computer Products, Inc." }, { 0x10f0, "Peritek Corporation" }, { 0x10f1, "Tyan Computer" }, { 0x10f2, "Achme Computer, Inc." }, { 0x10f3, "Alaris, Inc." }, { 0x10f4, "S-MOS Systems, Inc." }, { 0x10f5, "NKK Corporation" }, { 0x10f6, "Creative Electronic Systems SA" }, { 0x10f7, "Matsushita Electric Industrial Co., Ltd." }, { 0x10f8, "Altos India Ltd" }, { 0x10f9, "PC Direct" }, { 0x10fa, "Truevision" }, { 0x10fb, "Thesys Gesellschaft fuer Mikroelektronik mbH" }, { 0x10fc, "I-O Data Device, Inc." }, { 0x10fd, "Soyo Computer, Inc" }, { 0x10fe, "Fast Multimedia AG" }, { 0x10ff, "NCube" }, { 0x1100, "Jazz Multimedia" }, { 0x1101, "Initio Corporation" }, { 0x1102, "Creative Labs" }, { 0x1103, "HighPoint Technologies, Inc." }, { 0x1104, "RasterOps Corp." }, { 0x1105, "Sigma Designs, Inc." }, { 0x1106, "VIA Technologies, Inc." }, { 0x1107, "Stratus Computers" }, { 0x1108, "Proteon, Inc." }, { 0x1109, "Cogent Data Technologies, Inc." }, { 0x110a, "Siemens AG" }, { 0x110b, "Chromatic Research Inc." }, { 0x110c, "Mini-Max Technology, Inc." }, { 0x110d, "Znyx Advanced Systems" }, { 0x110e, "CPU Technology" }, { 0x110f, "Ross Technology" }, { 0x1110, "Powerhouse Systems" }, { 0x1111, "Santa Cruz Operation" }, { 0x1112, "Osicom Technologies Inc" }, { 0x1113, "Accton Technology Corporation" }, { 0x1114, "Atmel Corporation" }, { 0x1115, "3D Labs" }, { 0x1116, "Data Translation" }, { 0x1117, "Datacube, Inc" }, { 0x1118, "Berg Electronics" }, { 0x1119, "ICP Vortex Computersysteme GmbH" }, { 0x111a, "Efficient Networks, Inc" }, { 0x111b, "Teledyne Electronic Systems" }, { 0x111c, "Tricord Systems Inc." }, { 0x111d, "Microsemi / PMC / IDT" }, { 0x111e, "Eldec" }, { 0x111f, "Precision Digital Images" }, { 0x1120, "Dell EMC" }, { 0x1121, "Zilog" }, { 0x1122, "Multi-tech Systems, Inc." }, { 0x1123, "Excellent Design, Inc." }, { 0x1124, "Leutron Vision AG" }, { 0x1125, "Eurocore" }, { 0x1126, "Vigra" }, { 0x1127, "FORE Systems Inc" }, { 0x1129, "Firmworks" }, { 0x112a, "Hermes Electronics Company, Ltd." }, { 0x112b, "<NAME> AGHeidelberger Druckmaschinen AG" }, { 0x112c, "Zenith Data Systems" }, { 0x112d, "Ravicad" }, { 0x112e, "Infomedia Microelectronics Inc." }, { 0x112f, "Dalsa Inc." }, { 0x1130, "Computervision" }, { 0x1131, "Philips Semiconductors" }, { 0x1132, "Mitel Corp." }, { 0x1133, "Dialogic Corporation" }, { 0x1134, "Mercury Computer Systems" }, { 0x1135, "Fuji Xerox Co Ltd" }, { 0x1136, "Momentum Data Systems" }, { 0x1137, "Cisco Systems Inc" }, { 0x1138, "Ziatech Corporation" }, { 0x1139, "Dynamic Pictures, Inc" }, { 0x113a, "FWB Inc" }, { 0x113b, "Network Computing Devices" }, { 0x113c, "Cyclone Microsystems, Inc." }, { 0x113d, "Leading Edge Products Inc" }, { 0x113e, "Sanyo Electric Co - Computer Engineering Dept" }, { 0x113f, "Equinox Systems, Inc." }, { 0x1140, "Intervoice Inc" }, { 0x1141, "Crest Microsystem Inc" }, { 0x1142, "Alliance Semiconductor Corporation" }, { 0x1143, "NetPower, Inc" }, { 0x1144, "C<NAME>" }, { 0x1145, "Workbit Corporation" }, { 0x1146, "Force Computers" }, { 0x1147, "Interface Corp" }, { 0x1148, "SysKonnect" }, { 0x1149, "Win System Corporation" }, { 0x114a, "VMIC" }, { 0x114b, "Canopus Co., Ltd" }, { 0x114c, "Annabooks" }, { 0x114d, "IC Corporation" }, { 0x114e, "Nikon Systems Inc" }, { 0x114f, "Digi International" }, { 0x1150, "Thinking Machines Corp" }, { 0x1151, "JAE Electronics Inc." }, { 0x1152, "Megatek" }, { 0x1153, "Land Win Electronic Corp" }, { 0x1154, "Melco Inc" }, { 0x1155, "Pine Technology Ltd" }, { 0x1156, "Periscope Engineering" }, { 0x1157, "Avsys Corporation" }, { 0x1158, "Voarx R & D Inc" }, { 0x1159, "MuTech Corporation" }, { 0x115a, "Harlequin Ltd" }, { 0x115b, "Parallax Graphics" }, { 0x115c, "Photron Ltd." }, { 0x115d, "Xircom" }, { 0x115e, "Peer Protocols Inc" }, { 0x115f, "Maxtor Corporation" }, { 0x1160, "Megasoft Inc" }, { 0x1161, "PFU Limited" }, { 0x1162, "OA Laboratory Co Ltd" }, { 0x1163, "Rendition" }, { 0x1164, "Advanced Peripherals Technologies" }, { 0x1165, "Imagraph Corporation" }, { 0x1166, "Broadcom" }, { 0x1167, "Mutoh Industries Inc" }, { 0x1168, "Thine Electronics Inc" }, { 0x1169, "Centre for Development of Advanced Computing" }, { 0x116a, "Luminex Software, Inc." }, { 0x116b, "Connectware Inc" }, { 0x116c, "Intelligent Resources Integrated Systems" }, { 0x116d, "Martin-Marietta" }, { 0x116e, "Electronics for Imaging" }, { 0x116f, "Workstation Technology" }, { 0x1170, "Inventec Corporation" }, { 0x1171, "Loughborough Sound Images Plc" }, { 0x1172, "Altera Corporation" }, { 0x1173, "Adobe Systems, Inc" }, { 0x1174, "Bridgeport Machines" }, { 0x1175, "Mitron Computer Inc." }, { 0x1176, "SBE Incorporated" }, { 0x1177, "Silicon Engineering" }, { 0x1178, "Alfa, Inc." }, { 0x1179, "Toshiba Corporation" }, { 0x117a, "A-Trend Technology" }, { 0x117b, "L G Electronics, Inc." }, { 0x117c, "ATTO Technology, Inc." }, { 0x117d, "<NAME>" }, { 0x117e, "T/R Systems" }, { 0x117f, "Integrated Circuit Systems" }, { 0x1180, "Ricoh Co Ltd" }, { 0x1181, "Telmatics International" }, { 0x1183, "Fujikura Ltd" }, { 0x1184, "Forks Inc" }, { 0x1185, "Dataworld International Ltd" }, { 0x1186, "D-Link System Inc" }, { 0x1187, "Advanced Technology Laboratories, Inc." }, { 0x1188, "Shima Seiki Manufacturing Ltd." }, { 0x1189, "Matsushita Electronics Co Ltd" }, { 0x118a, "Hilevel Technology" }, { 0x118b, "Hypertec Pty Limited" }, { 0x118c, "Corollary, Inc" }, { 0x118d, "BitFlow Inc" }, { 0x118e, "Hermstedt GmbH" }, { 0x118f, "Green Logic" }, { 0x1190, "Tripace" }, { 0x1191, "Artop Electronic Corp" }, { 0x1192, "Densan Company Ltd" }, { 0x1193, "Zeitnet Inc." }, { 0x1194, "Toucan Technology" }, { 0x1195, "Ratoc System Inc" }, { 0x1196, "Hytec Electronics Ltd" }, { 0x1197, "Gage Applied Sciences, Inc." }, { 0x1198, "Lambda Systems Inc" }, { 0x1199, "Attachmate Corporation" }, { 0x119a, "Mind Share, Inc." }, { 0x119b, "Omega Micro Inc." }, { 0x119c, "Information Technology Inst." }, { 0x119d, "Bug, Inc. Sapporo Japan" }, { 0x119e, "Fujitsu Microelectronics Ltd." }, { 0x119f, "Bull HN Information Systems" }, { 0x11a0, "Convex Computer Corporation" }, { 0x11a1, "Hamamatsu Photonics K.K." }, { 0x11a2, "Sierra Research and Technology" }, { 0x11a3, "Deuretzbacher GmbH & Co. Eng. KG" }, { 0x11a4, "Barco Graphics NV" }, { 0x11a5, "Microunity Systems Eng. Inc" }, { 0x11a6, "Pure Data Ltd." }, { 0x11a7, "Power Computing Corp." }, { 0x11a8, "Systech Corp." }, { 0x11a9, "InnoSys Inc." }, { 0x11aa, "Actel" }, { 0x11ab, "Marvell Technology Group Ltd." }, { 0x11ac, "Canon Information Systems Research Aust." }, { 0x11ad, "Lite-On Communications Inc" }, { 0x11ae, "Aztech System Ltd" }, { 0x11af, "Avid Technology Inc." }, { 0x11b0, "V3 Semiconductor Inc." }, { 0x11b1, "Apricot Computers" }, { 0x11b2, "<NAME>" }, { 0x11b3, "Barr Systems Inc." }, { 0x11b4, "Leitch Technology International" }, { 0x11b5, "Radstone Technology Plc" }, { 0x11b6, "United Video Corp" }, { 0x11b7, "Motorola" }, { 0x11b8, "XPoint Technologies, Inc" }, { 0x11b9, "Pathlight Technology Inc." }, { 0x11ba, "Videotron Corp" }, { 0x11bb, "Pyramid Technology" }, { 0x11bc, "Network Peripherals Inc" }, { 0x11bd, "Pinnacle Systems Inc." }, { 0x11be, "International Microcircuits Inc" }, { 0x11bf, "Astrodesign, Inc." }, { 0x11c0, "<NAME>" }, { 0x11c1, "LSI Corporation" }, { 0x11c2, "Sand Microelectronics" }, { 0x11c3, "NEC Corporation" }, { 0x11c4, "Document Technologies, Inc" }, { 0x11c5, "Shiva Corporation" }, { 0x11c6, "Dainippon Screen Mfg. Co. Ltd" }, { 0x11c7, "D.C.M. Data Systems" }, { 0x11c8, "Dolphin Interconnect Solutions AS" }, { 0x11c9, "Magma" }, { 0x11ca, "LSI Systems, Inc" }, { 0x11cb, "Specialix Research Ltd." }, { 0x11cc, "Michels & Kleberhoff Computer GmbH" }, { 0x11cd, "HAL Computer Systems, Inc." }, { 0x11ce, "Netaccess" }, { 0x11cf, "Pioneer Electronic Corporation" }, { 0x11d0, "Lockheed Martin Federal Systems-Manassas" }, { 0x11d1, "Auravision" }, { 0x11d2, "Intercom Inc." }, { 0x11d3, "Trancell Systems Inc" }, { 0x11d4, "Analog Devices" }, { 0x11d5, "Ikon Corporation" }, { 0x11d6, "Tekelec Telecom" }, { 0x11d7, "Trenton Technology, Inc." }, { 0x11d8, "Image Technologies Development" }, { 0x11d9, "TEC Corporation" }, { 0x11da, "Novell" }, { 0x11db, "Sega Enterprises Ltd" }, { 0x11dc, "Questra Corporation" }, { 0x11dd, "Crosfield Electronics Limited" }, { 0x11de, "Zoran Corporation" }, { 0x11df, "New Wave PDG" }, { 0x11e0, "Cray Communications A/S" }, { 0x11e1, "GEC Plessey Semi Inc." }, { 0x11e2, "Samsung Information Systems America" }, { 0x11e3, "Quicklogic Corporation" }, { 0x11e4, "Second Wave Inc" }, { 0x11e5, "IIX Consulting" }, { 0x11e6, "Mitsui-Zosen System Research" }, { 0x11e7, "Toshiba America, Elec. Company" }, { 0x11e8, "Digital Processing Systems Inc." }, { 0x11e9, "Highwater Designs Ltd." }, { 0x11ea, "<NAME>" }, { 0x11eb, "Formation Inc." }, { 0x11ec, "Coreco Inc" }, { 0x11ed, "Mediamatics" }, { 0x11ee, "Dome Imaging Systems Inc" }, { 0x11ef, "Nicolet Technologies B.V." }, { 0x11f0, "Compu-Shack" }, { 0x11f1, "Symbios Logic Inc" }, { 0x11f2, "Picture Tel Japan K.K." }, { 0x11f3, "Keithley Metrabyte" }, { 0x11f4, "Kinetic Systems Corporation" }, { 0x11f5, "Computing Devices International" }, { 0x11f6, "Compex" }, { 0x11f7, "Scientific Atlanta" }, { 0x11f8, "PMC-Sierra Inc." }, { 0x11f9, "I-Cube Inc" }, { 0x11fa, "Kasan Electronics Company, Ltd." }, { 0x11fb, "Datel Inc" }, { 0x11fc, "Silicon Magic" }, { 0x11fd, "High Street Consultants" }, { 0x11fe, "Pepperl+Fuchs Comtrol, Inc." }, { 0x11ff, "Scion Corporation" }, { 0x1200, "CSS Corporation" }, { 0x1201, "Vista Controls Corp" }, { 0x1202, "Network General Corp." }, { 0x1203, "Bayer Corporation, Agfa Division" }, { 0x1204, "Lattice Semiconductor Corporation" }, { 0x1205, "Array Corporation" }, { 0x1206, "Amdahl Corporation" }, { 0x1208, "Parsytec GmbH" }, { 0x1209, "SCI Systems Inc" }, { 0x120a, "Synaptel" }, { 0x120b, "Adaptive Solutions" }, { 0x120c, "Technical Corp." }, { 0x120d, "Compression Labs, Inc." }, { 0x120e, "Cyclades Corporation" }, { 0x120f, "Essential Communications" }, { 0x1210, "Hyperparallel Technologies" }, { 0x1211, "Braintech Inc" }, { 0x1213, "Applied Intelligent Systems, Inc." }, { 0x1214, "Performance Technologies, Inc." }, { 0x1215, "Interware Co., Ltd" }, { 0x1216, "Purup Prepress A/S" }, { 0x1217, "O2 Micro, Inc." }, { 0x1218, "Hybricon Corp." }, { 0x1219, "First Virtual Corporation" }, { 0x121a, "3Dfx Interactive, Inc." }, { 0x121b, "Advanced Telecommunications Modules" }, { 0x121c, "Nippon Texaco., Ltd" }, { 0x121d, "LiPPERT ADLINK Technology GmbH" }, { 0x121e, "CSPI" }, { 0x121f, "Arcus Technology, Inc." }, { 0x1220, "<NAME>" }, { 0x1221, "Contec Co., Ltd" }, { 0x1222, "Ancor Communications, Inc." }, { 0x1223, "Artesyn Communication Products" }, { 0x1224, "Interactive Images" }, { 0x1225, "Power I/O, Inc." }, { 0x1227, "EIZO Rugged Solutions" }, { 0x1228, "Norsk Elektro Optikk A/S" }, { 0x1229, "Data Kinesis Inc." }, { 0x122a, "Integrated Telecom" }, { 0x122b, "LG Industrial Systems Co., Ltd" }, { 0x122c, "Sican GmbH" }, { 0x122d, "Aztech System Ltd" }, { 0x122e, "Xyratex" }, { 0x122f, "<NAME>" }, { 0x1230, "Fishcamp Engineering" }, { 0x1231, "Woodward McCoach, Inc." }, { 0x1232, "GPT Limited" }, { 0x1233, "Bus-Tech, Inc." }, { 0x1235, "SMART Modular Technologies" }, { 0x1236, "Sigma Designs Corporation" }, { 0x1237, "Alta Technology Corporation" }, { 0x1238, "Adtran" }, { 0x1239, "3DO Company" }, { 0x123a, "Visicom Laboratories, Inc." }, { 0x123b, "Seeq Technology, Inc." }, { 0x123c, "Century Systems, Inc." }, { 0x123d, "Engineering Design Team, Inc." }, { 0x123e, "Simutech, Inc." }, { 0x123f, "LSI Logic" }, { 0x1240, "Marathon Technologies Corp." }, { 0x1241, "DSC Communications" }, { 0x1242, "JNI Corporation" }, { 0x1243, "Delphax" }, { 0x1244, "AVM GmbH" }, { 0x1245, "A.P.D., S.A." }, { 0x1246, "Dipix Technologies, Inc." }, { 0x1247, "Xylon Research, Inc." }, { 0x1248, "Central Data Corporation" }, { 0x1249, "Samsung Electronics Co., Ltd." }, { 0x124a, "AEG Electrocom GmbH" }, { 0x124b, "SBS/Greenspring Modular I/O" }, { 0x124c, "Solitron Technologies, Inc." }, { 0x124d, "Stallion Technologies, Inc." }, { 0x124e, "Cylink" }, { 0x124f, "Infortrend Technology, Inc." }, { 0x1250, "Hitachi Microcomputer System Ltd" }, { 0x1251, "VLSI Solutions Oy" }, { 0x1253, "Guzik Technical Enterprises" }, { 0x1254, "Linear Systems Ltd." }, { 0x1255, "Optibase Ltd" }, { 0x1256, "Perceptive Solutions, Inc." }, { 0x1257, "Vertex Networks, Inc." }, { 0x1258, "Gilbarco, Inc." }, { 0x1259, "Allied Telesis" }, { 0x125a, "ABB Power Systems" }, { 0x125b, "Asix Electronics Corporation" }, { 0x125c, "Aurora Technologies, Inc." }, { 0x125d, "ESS Technology" }, { 0x125e, "Specialvideo Engineering SRL" }, { 0x125f, "Concurrent Technologies, Inc." }, { 0x1260, "Intersil Corporation" }, { 0x1261, "Matsushita-Kotobuki Electronics Industries, Ltd." }, { 0x1262, "ES Computer Company, Ltd." }, { 0x1263, "Sonic Solutions" }, { 0x1264, "Aval Nagasaki Corporation" }, { 0x1265, "Casio Computer Co., Ltd." }, { 0x1266, "Microdyne Corporation" }, { 0x1267, "S. A. Telecommunications" }, { 0x1268, "Tektronix" }, { 0x1269, "Thomson-CSF/TTM" }, { 0x126a, "Lexmark International, Inc." }, { 0x126b, "Adax, Inc." }, { 0x126c, "Northern Telecom" }, { 0x126d, "Splash Technology, Inc." }, { 0x126e, "Sumitomo Metal Industries, Ltd." }, { 0x126f, "Silicon Motion, Inc." }, { 0x1270, "Olympus Optical Co., Ltd." }, { 0x1271, "GW Instruments" }, { 0x1272, "Telematics International" }, { 0x1273, "Hughes Network Systems" }, { 0x1274, "Ensoniq" }, { 0x1275, "Network Appliance Corporation" }, { 0x1276, "Switched Network Technologies, Inc." }, { 0x1277, "Comstream" }, { 0x1278, "Transtech Parallel Systems Ltd." }, { 0x1279, "Transmeta Corporation" }, { 0x127a, "Rockwell International" }, { 0x127b, "Pixera Corporation" }, { 0x127c, "Crosspoint Solutions, Inc." }, { 0x127d, "Vela Research" }, { 0x127e, "<NAME>." }, { 0x127f, "Fujifilm" }, { 0x1280, "Photoscript Group Ltd." }, { 0x1281, "Yokogawa Electric Corporation" }, { 0x1282, "Davicom Semiconductor, Inc." }, { 0x1283, "Integrated Technology Express, Inc." }, { 0x1284, "Sahara Networks, Inc." }, { 0x1285, "Platform Technologies, Inc." }, { 0x1286, "Mazet GmbH" }, { 0x1287, "M-Pact, Inc." }, { 0x1288, "Timestep Corporation" }, { 0x1289, "AVC Technology, Inc." }, { 0x128a, "Asante Technologies, Inc." }, { 0x128b, "Transwitch Corporation" }, { 0x128c, "Retix Corporation" }, { 0x128d, "G2 Networks, Inc." }, { 0x128e, "Hoontech Corporation/Samho Multi Tech Ltd." }, { 0x128f, "Tateno Dennou, Inc." }, { 0x1290, "Sord Computer Corporation" }, { 0x1291, "NCS Computer Italia" }, { 0x1292, "Tritech Microelectronics Inc" }, { 0x1293, "Media Reality Technology" }, { 0x1294, "Rhetorex, Inc." }, { 0x1295, "Imagenation Corporation" }, { 0x1296, "Kofax Image Products" }, { 0x1297, "Holco Enterprise Co, Ltd/Shuttle Computer" }, { 0x1298, "Spellcaster Telecommunications Inc." }, { 0x1299, "Knowledge Technology Lab." }, { 0x129a, "VMetro, inc." }, { 0x129b, "Image Access" }, { 0x129c, "Jaycor" }, { 0x129d, "Compcore Multimedia, Inc." }, { 0x129e, "Victor Company of Japan, Ltd." }, { 0x129f, "OEC Medical Systems, Inc." }, { 0x12a0, "Allen-Bradley Company" }, { 0x12a1, "Simpact Associates, Inc." }, { 0x12a2, "Newgen Systems Corporation" }, { 0x12a3, "Lucent Technologies" }, { 0x12a4, "NTT Electronics Corporation" }, { 0x12a5, "Vision Dynamics Ltd." }, { 0x12a6, "Scalable Networks, Inc." }, { 0x12a7, "AMO GmbH" }, { 0x12a8, "News Datacom" }, { 0x12a9, "Xiotech Corporation" }, { 0x12aa, "SDL Communications, Inc." }, { 0x12ab, "YUAN High-Tech Development Co., Ltd." }, { 0x12ac, "Measurex Corporation" }, { 0x12ad, "Multidata GmbH" }, { 0x12ae, "Alteon Networks Inc." }, { 0x12af, "TDK USA Corp" }, { 0x12b0, "Jorge Scientific Corp" }, { 0x12b1, "GammaLink" }, { 0x12b2, "General Signal Networks" }, { 0x12b3, "Inter-Face Co Ltd" }, { 0x12b4, "FutureTel Inc" }, { 0x12b5, "Granite Systems Inc." }, { 0x12b6, "Natural Microsystems" }, { 0x12b7, "Cognex Corporation" }, { 0x12b8, "Korg" }, { 0x12b9, "3Com Corp, Modem Division" }, { 0x12ba, "BittWare, Inc." }, { 0x12bb, "Nippon Unisoft Corporation" }, { 0x12bc, "Array Microsystems" }, { 0x12bd, "Computerm Corp." }, { 0x12be, "Anchor Chips Inc." }, { 0x12bf, "Fujifilm Microdevices" }, { 0x12c0, "Infimed" }, { 0x12c1, "GMM Research Corp" }, { 0x12c2, "Mentec Limited" }, { 0x12c3, "Holtek Microelectronics Inc" }, { 0x12c4, "Connect Tech Inc" }, { 0x12c5, "Picture Elements Incorporated" }, { 0x12c6, "Mitani Corporation" }, { 0x12c7, "Dialogic Corp" }, { 0x12c8, "G Force Co, Ltd" }, { 0x12c9, "Gigi Operations" }, { 0x12ca, "Integrated Computing Engines" }, { 0x12cb, "Antex Electronics Corporation" }, { 0x12cc, "Pluto Technologies International" }, { 0x12cd, "Aims Lab" }, { 0x12ce, "Netspeed Inc." }, { 0x12cf, "Prophet Systems, Inc." }, { 0x12d0, "GDE Systems, Inc." }, { 0x12d1, "PSITech" }, { 0x12d2, "NVidia / SGS Thomson (Joint Venture)" }, { 0x12d3, "Vingmed Sound A/S" }, { 0x12d4, "Ulticom (Formerly DGM&S)" }, { 0x12d5, "Equator Technologies Inc" }, { 0x12d6, "Analogic Corp" }, { 0x12d7, "Biotronic SRL" }, { 0x12d8, "Pericom Semiconductor" }, { 0x12d9, "Aculab PLC" }, { 0x12da, "True Time Inc." }, { 0x12db, "Annapolis Micro Systems, Inc" }, { 0x12dc, "Symicron Computer Communication Ltd." }, { 0x12dd, "Management Graphics" }, { 0x12de, "Rainbow Technologies" }, { 0x12df, "SBS Technologies Inc" }, { 0x12e0, "Chase Research" }, { 0x12e1, "Nintendo Co, Ltd" }, { 0x12e2, "Datum Inc. Bancomm-Timing Division" }, { 0x12e3, "Imation Corp - Medical Imaging Systems" }, { 0x12e4, "Brooktrout Technology Inc" }, { 0x12e5, "Apex Semiconductor Inc" }, { 0x12e6, "Cirel Systems" }, { 0x12e7, "Sunsgroup Corporation" }, { 0x12e8, "Crisc Corp" }, { 0x12e9, "GE Spacenet" }, { 0x12ea, "Zuken" }, { 0x12eb, "Aureal Semiconductor" }, { 0x12ec, "3A International, Inc." }, { 0x12ed, "Optivision Inc." }, { 0x12ee, "Orange Micro" }, { 0x12ef, "Vienna Systems" }, { 0x12f0, "Pentek" }, { 0x12f1, "Sorenson Vision Inc" }, { 0x12f2, "Gammagraphx, Inc." }, { 0x12f3, "Radstone Technology" }, { 0x12f4, "Megatel" }, { 0x12f5, "Forks" }, { 0x12f6, "<NAME>" }, { 0x12f7, "Cognex" }, { 0x12f8, "Electronic Design GmbH" }, { 0x12f9, "Four Fold Ltd" }, { 0x12fb, "Spectrum Signal Processing" }, { 0x12fc, "Capital Equipment Corp" }, { 0x12fd, "I2S" }, { 0x12fe, "ESD Electronic System Design GmbH" }, { 0x12ff, "Lexicon" }, { 0x1300, "Harman International Industries Inc" }, { 0x1302, "Computer Sciences Corp" }, { 0x1303, "Innovative Integration" }, { 0x1304, "Juniper Networks" }, { 0x1305, "Netphone, Inc" }, { 0x1306, "Duet Technologies" }, { 0x1307, "Measurement Computing" }, { 0x1308, "Jato Technologies Inc." }, { 0x1309, "AB Semiconductor Ltd" }, { 0x130a, "Mitsubishi Electric Microcomputer" }, { 0x130b, "Colorgraphic Communications Corp" }, { 0x130c, "Ambex Technologies, Inc" }, { 0x130d, "Accelerix Inc" }, { 0x130e, "Yamatake-Honeywell Co. Ltd" }, { 0x130f, "Advanet Inc" }, { 0x1310, "Gespac" }, { 0x1311, "Videoserver, Inc" }, { 0x1312, "Acuity Imaging, Inc" }, { 0x1313, "Yaskawa Electric Co." }, { 0x1315, "Wavesat" }, { 0x1316, "Teradyne Inc" }, { 0x1317, "ADMtek" }, { 0x1318, "Packet Engines Inc." }, { 0x1319, "Fortemedia, Inc" }, { 0x131a, "Finisar Corp." }, { 0x131c, "Nippon Electro-Sensory Devices Corp" }, { 0x131d, "Sysmic, Inc." }, { 0x131e, "Xinex Networks Inc" }, { 0x131f, "Siig Inc" }, { 0x1320, "Crypto AG" }, { 0x1321, "Arcobel Graphics BV" }, { 0x1322, "MTT Co., Ltd" }, { 0x1323, "Dome Inc" }, { 0x1324, "Sphere Communications" }, { 0x1325, "Salix Technologies, Inc" }, { 0x1326, "Seachange international" }, { 0x1327, "Voss scientific" }, { 0x1328, "quadrant international" }, { 0x1329, "Productivity Enhancement" }, { 0x132a, "Microcom Inc." }, { 0x132b, "Broadband Technologies" }, { 0x132c, "Micrel Inc" }, { 0x132d, "Integrated Silicon Solution, Inc." }, { 0x1330, "MMC Networks" }, { 0x1331, "RadiSys Corporation" }, { 0x1332, "Micro Memory" }, { 0x1334, "Redcreek Communications, Inc" }, { 0x1335, "Videomail, Inc" }, { 0x1337, "Third Planet Publishing" }, { 0x1338, "BT Electronics" }, { 0x133a, "Vtel Corp" }, { 0x133b, "Softcom Microsystems" }, { 0x133c, "Holontech Corp" }, { 0x133d, "SS Technologies" }, { 0x133e, "Virtual Computer Corp" }, { 0x133f, "SCM Microsystems" }, { 0x1340, "Atalla Corp" }, { 0x1341, "Kyoto Microcomputer Co" }, { 0x1342, "Promax Systems Inc" }, { 0x1343, "Phylon Communications Inc" }, { 0x1344, "Micron Technology Inc" }, { 0x1345, "Arescom Inc" }, { 0x1347, "Odetics" }, { 0x1349, "Sumitomo Electric Industries, Ltd." }, { 0x134a, "DTC Technology Corp." }, { 0x134b, "ARK Research Corp." }, { 0x134c, "Chori Joho System Co. Ltd" }, { 0x134d, "PCTel Inc" }, { 0x134e, "CSTI" }, { 0x134f, "Algo System Co Ltd" }, { 0x1350, "Systec Co. Ltd" }, { 0x1351, "Sonix Inc" }, { 0x1353, "Vierling Communication SAS" }, { 0x1354, "Dwave System Inc" }, { 0x1355, "Kratos Analytical Ltd" }, { 0x1356, "The Logical Co" }, { 0x1359, "Prisa Networks" }, { 0x135a, "Brain Boxes" }, { 0x135b, "Giganet Inc" }, { 0x135c, "Quatech Inc" }, { 0x135d, "ABB Network Partner AB" }, { 0x135e, "Sealevel Systems Inc" }, { 0x135f, "I-Data International A-S" }, { 0x1360, "<NAME>" }, { 0x1361, "Soliton Systems K.K." }, { 0x1362, "Fujifacom Corporation" }, { 0x1363, "Phoenix Technology Ltd" }, { 0x1364, "ATM Communications Inc" }, { 0x1365, "Hypercope GmbH" }, { 0x1366, "Teijin Seiki Co. Ltd" }, { 0x1367, "Hitachi Zosen Corporation" }, { 0x1368, "Skyware Corporation" }, { 0x1369, "Digigram" }, { 0x136a, "High Soft Tech" }, { 0x136b, "Kawasaki Steel Corporation" }, { 0x136c, "Adtek System Science Co Ltd" }, { 0x136d, "Gigalabs Inc" }, { 0x136f, "Applied Magic Inc" }, { 0x1370, "ATL Products" }, { 0x1371, "CNet Technology Inc" }, { 0x1373, "Silicon Vision Inc" }, { 0x1374, "Silicom Ltd." }, { 0x1375, "Argosystems Inc" }, { 0x1376, "LMC" }, { 0x1377, "Electronic Equipment Production & Distribution GmbH" }, { 0x1378, "Telemann Co. Ltd" }, { 0x1379, "Asahi Kasei Microsystems Co Ltd" }, { 0x137a, "Mark of the Unicorn Inc" }, { 0x137b, "PPT Vision" }, { 0x137c, "Iwatsu Electric Co Ltd" }, { 0x137d, "Dynachip Corporation" }, { 0x137e, "Patriot Scientific Corporation" }, { 0x137f, "Japan Satellite Systems Inc" }, { 0x1380, "Sanritz Automation Co Ltd" }, { 0x1381, "Brains Co. Ltd" }, { 0x1382, "Marian - Electronic & Software" }, { 0x1383, "Controlnet Inc" }, { 0x1384, "Reality Simulation Systems Inc" }, { 0x1385, "Netgear" }, { 0x1386, "Video Domain Technologies" }, { 0x1387, "Systran Corp" }, { 0x1388, "Hitachi Information Technology Co Ltd" }, { 0x1389, "Applicom International" }, { 0x138a, "Fusion Micromedia Corp" }, { 0x138b, "Tokimec Inc" }, { 0x138c, "Silicon Reality" }, { 0x138d, "Future Techno Designs pte Ltd" }, { 0x138e, "Basler GmbH" }, { 0x138f, "Patapsco Designs Inc" }, { 0x1390, "Concept Development Inc" }, { 0x1391, "Development Concepts Inc" }, { 0x1392, "Medialight Inc" }, { 0x1393, "Moxa Technologies Co Ltd" }, { 0x1394, "Level One Communications" }, { 0x1395, "Ambicom Inc" }, { 0x1396, "Cipher Systems Inc" }, { 0x1397, "Cologne Chip Designs GmbH" }, { 0x1398, "Clarion co. Ltd" }, { 0x1399, "Rios systems Co Ltd" }, { 0x139a, "Alacritech Inc" }, { 0x139b, "Mediasonic Multimedia Systems Ltd" }, { 0x139c, "Quantum 3d Inc" }, { 0x139d, "EPL limited" }, { 0x139e, "Media4" }, { 0x139f, "Aethra s.r.l." }, { 0x13a0, "Crystal Group Inc" }, { 0x13a1, "Kawasaki Heavy Industries Ltd" }, { 0x13a2, "Ositech Communications Inc" }, { 0x13a3, "Hifn Inc." }, { 0x13a4, "Rascom Inc" }, { 0x13a5, "Audio Digital Imaging Inc" }, { 0x13a6, "Videonics Inc" }, { 0x13a7, "Teles AG" }, { 0x13a8, "Exar Corp." }, { 0x13a9, "Siemens Medical Systems, Ultrasound Group" }, { 0x13aa, "Broadband Networks Inc" }, { 0x13ab, "Arcom Control Systems Ltd" }, { 0x13ac, "Motion Media Technology Ltd" }, { 0x13ad, "Nexus Inc" }, { 0x13ae, "ALD Technology Ltd" }, { 0x13af, "T.Sqware" }, { 0x13b0, "Maxspeed Corp" }, { 0x13b1, "Tamura corporation" }, { 0x13b2, "Techno Chips Co. Ltd" }, { 0x13b3, "Lanart Corporation" }, { 0x13b4, "Wellbean Co Inc" }, { 0x13b5, "ARM" }, { 0x13b6, "Dlog GmbH" }, { 0x13b7, "Logic Devices Inc" }, { 0x13b8, "Nokia Telecommunications oy" }, { 0x13b9, "Elecom Co Ltd" }, { 0x13ba, "Oxford Instruments" }, { 0x13bb, "Sanyo Technosound Co Ltd" }, { 0x13bc, "Bitran Corporation" }, { 0x13bd, "Sharp corporation" }, { 0x13be, "Miroku Jyoho Service Co. Ltd" }, { 0x13bf, "Sharewave Inc" }, { 0x13c0, "Microgate Corporation" }, { 0x13c1, "3ware Inc" }, { 0x13c2, "Technotrend Systemtechnik GmbH" }, { 0x13c3, "Janz Computer AG" }, { 0x13c4, "Phase Metrics" }, { 0x13c5, "Alphi Technology Corp" }, { 0x13c6, "Condor Engineering Inc" }, { 0x13c7, "Blue Chip Technology Ltd" }, { 0x13c8, "Apptech Inc" }, { 0x13c9, "Eaton Corporation" }, { 0x13ca, "Iomega Corporation" }, { 0x13cb, "Yano Electric Co Ltd" }, { 0x13cc, "BARCO" }, { 0x13cd, "Compatible Systems Corporation" }, { 0x13ce, "Cocom A/S" }, { 0x13cf, "Studio Audio & Video Ltd" }, { 0x13d0, "Techsan Electronics Co Ltd" }, { 0x13d1, "Abocom Systems Inc" }, { 0x13d2, "Shark Multimedia Inc" }, { 0x13d4, "Graphics Microsystems Inc" }, { 0x13d5, "Media 100 Inc" }, { 0x13d6, "K.I. Technology Co Ltd" }, { 0x13d7, "Toshiba Engineering Corporation" }, { 0x13d8, "Phobos corporation" }, { 0x13d9, "Apex PC Solutions Inc" }, { 0x13da, "Intresource Systems pte Ltd" }, { 0x13db, "Janich & Klass Computertechnik GmbH" }, { 0x13dc, "Netboost Corporation" }, { 0x13dd, "Multimedia Bundle Inc" }, { 0x13de, "ABB Robotics Products AB" }, { 0x13df, "E-Tech Inc" }, { 0x13e0, "GVC Corporation" }, { 0x13e1, "Silicom Multimedia Systems Inc" }, { 0x13e2, "Dynamics Research Corporation" }, { 0x13e3, "Nest Inc" }, { 0x13e4, "Calculex Inc" }, { 0x13e5, "Telesoft Design Ltd" }, { 0x13e6, "Argosy research Inc" }, { 0x13e7, "NAC Incorporated" }, { 0x13e8, "Chip Express Corporation" }, { 0x13e9, "Intraserver Technology Inc" }, { 0x13ea, "Dallas Semiconductor" }, { 0x13eb, "Hauppauge Computer Works Inc" }, { 0x13ec, "Zydacron Inc" }, { 0x13ed, "Raytheion E-Systems" }, { 0x13ee, "Hayes Microcomputer Products Inc" }, { 0x13ef, "Coppercom Inc" }, { 0x13f0, "Sundance Technology Inc / IC Plus Corp" }, { 0x13f1, "Oce' - Technologies B.V." }, { 0x13f2, "Ford Microelectronics Inc" }, { 0x13f3, "Mcdata Corporation" }, { 0x13f4, "Troika Networks, Inc." }, { 0x13f5, "Kansai Electric Co. Ltd" }, { 0x13f6, "C-Media Electronics Inc" }, { 0x13f7, "Wildfire Communications" }, { 0x13f8, "Ad Lib Multimedia Inc" }, { 0x13f9, "NTT Advanced Technology Corp." }, { 0x13fa, "Pentland Systems Ltd" }, { 0x13fb, "Aydin Corp" }, { 0x13fc, "Computer Peripherals International" }, { 0x13fd, "Micro Science Inc" }, { 0x13fe, "Advantech Co. Ltd" }, { 0x13ff, "Silicon Spice Inc" }, { 0x1400, "Artx Inc" }, { 0x1401, "CR-Systems A/S" }, { 0x1402, "Meilhaus Electronic GmbH" }, { 0x1403, "Ascor Inc" }, { 0x1404, "Fundamental Software Inc" }, { 0x1405, "Excalibur Systems Inc" }, { 0x1406, "Oce' Printing Systems GmbH" }, { 0x1407, "Lava Computer mfg Inc" }, { 0x1408, "Aloka Co. Ltd" }, { 0x1409, "Timedia Technology Co Ltd" }, { 0x140a, "DSP Research Inc" }, { 0x140b, "Abaco Systems, Inc." }, { 0x140c, "Elmic Systems Inc" }, { 0x140d, "Matsushita Electric Works Ltd" }, { 0x140e, "Goepel Electronic GmbH" }, { 0x140f, "Salient Systems Corp" }, { 0x1410, "Midas lab Inc" }, { 0x1411, "Ikos Systems Inc" }, { 0x1412, "VIA Technologies Inc." }, { 0x1413, "Addonics" }, { 0x1414, "Microsoft Corporation" }, { 0x1415, "Oxford Semiconductor Ltd" }, { 0x1416, "Multiwave Innovation pte Ltd" }, { 0x1417, "Convergenet Technologies Inc" }, { 0x1418, "Kyushu electronics systems Inc" }, { 0x1419, "Excel Switching Corp" }, { 0x141a, "Apache Micro Peripherals Inc" }, { 0x141b, "Zoom Telephonics Inc" }, { 0x141d, "Digitan Systems Inc" }, { 0x141e, "Fanuc Ltd" }, { 0x141f, "Visiontech Ltd" }, { 0x1420, "Psion Dacom plc" }, { 0x1421, "Ads Technologies Inc" }, { 0x1422, "Ygrec Systems Co Ltd" }, { 0x1423, "Custom Technology Corp." }, { 0x1424, "Videoserver Connections" }, { 0x1425, "Chelsio Communications Inc" }, { 0x1426, "Storage Technology Corp." }, { 0x1427, "Better On-Line Solutions" }, { 0x1428, "Edec Co Ltd" }, { 0x1429, "Unex Technology Corp." }, { 0x142a, "Kingmax Technology Inc" }, { 0x142b, "Radiolan" }, { 0x142c, "Minton Optic Industry Co Ltd" }, { 0x142d, "Pix stream Inc" }, { 0x142e, "Vitec Multimedia" }, { 0x142f, "Radicom Research Inc" }, { 0x1430, "ITT Aerospace/Communications Division" }, { 0x1431, "Gilat Satellite Networks" }, { 0x1432, "Edimax Computer Co." }, { 0x1433, "Eltec Elektronik GmbH" }, { 0x1435, "RTD Embedded Technologies, Inc." }, { 0x1436, "CIS Technology Inc" }, { 0x1437, "Nissin Inc Co" }, { 0x1438, "Atmel-dream" }, { 0x1439, "Outsource Engineering & Mfg. Inc" }, { 0x143a, "Stargate Solutions Inc" }, { 0x143b, "Canon Research Center, America" }, { 0x143c, "Amlogic Inc" }, { 0x143d, "Tamarack Microelectronics Inc" }, { 0x143e, "Jones Futurex Inc" }, { 0x143f, "Lightwell Co Ltd - Zax Division" }, { 0x1440, "ALGOL Corp." }, { 0x1441, "AGIE Ltd" }, { 0x1442, "Phoenix Contact GmbH & Co." }, { 0x1443, "Unibrain S.A." }, { 0x1444, "TRW" }, { 0x1445, "Logical DO Ltd" }, { 0x1446, "Graphin Co Ltd" }, { 0x1447, "AIM GmBH" }, { 0x1448, "Alesis Studio Electronics" }, { 0x1449, "TUT Systems Inc" }, { 0x144a, "Adlink Technology" }, { 0x144b, "Verint Systems Inc." }, { 0x144c, "Catalina Research Inc" }, { 0x144d, "Samsung Electronics Co Ltd" }, { 0x144e, "OLITEC" }, { 0x144f, "Askey Computer Corp." }, { 0x1450, "Octave Communications Ind." }, { 0x1451, "SP3D Chip Design GmBH" }, { 0x1453, "MYCOM Inc" }, { 0x1454, "Altiga Networks" }, { 0x1455, "Logic Plus Plus Inc" }, { 0x1456, "Advanced Hardware Architectures" }, { 0x1457, "Nuera Communications Inc" }, { 0x1458, "Gigabyte Technology Co., Ltd" }, { 0x1459, "DOOIN Electronics" }, { 0x145a, "Escalate Networks Inc" }, { 0x145b, "PRAIM SRL" }, { 0x145c, "Cryptek" }, { 0x145d, "Gallant Computer Inc" }, { 0x145e, "Aashima Technology B.V." }, { 0x145f, "Baldor Electric Company" }, { 0x1460, "DYNARC INC" }, { 0x1461, "Avermedia Technologies Inc" }, { 0x1462, "Micro-Star International Co., Ltd. [MSI]" }, { 0x1463, "Fast Corporation" }, { 0x1464, "Interactive Circuits & Systems Ltd" }, { 0x1465, "GN NETTEST Telecom DIV." }, { 0x1466, "Designpro Inc." }, { 0x1467, "DIGICOM SPA" }, { 0x1468, "AMBIT Microsystem Corp." }, { 0x1469, "Cleveland Motion Controls" }, { 0x146a, "Aeroflex" }, { 0x146b, "Parascan Technologies Ltd" }, { 0x146c, "Ruby Tech Corp." }, { 0x146d, "Tachyon, INC." }, { 0x146e, "Williams Electronics Games, Inc." }, { 0x146f, "Multi Dimensional Consulting Inc" }, { 0x1470, "Bay Networks" }, { 0x1471, "Integrated Telecom Express Inc" }, { 0x1472, "DAIKIN Industries, Ltd" }, { 0x1473, "ZAPEX Technologies Inc" }, { 0x1474, "<NAME> & Associates" }, { 0x1475, "PICAZO Communications" }, { 0x1476, "MORTARA Instrument Inc" }, { 0x1477, "Net Insight" }, { 0x1478, "DIATREND Corporation" }, { 0x1479, "TORAY Industries Inc" }, { 0x147a, "FORMOSA Industrial Computing" }, { 0x147b, "ABIT Computer Corp." }, { 0x147c, "AWARE, Inc." }, { 0x147d, "Interworks Computer Products" }, { 0x147e, "Matsushita Graphic Communication Systems, Inc." }, { 0x147f, "NIHON UNISYS, Ltd." }, { 0x1480, "SCII Telecom" }, { 0x1481, "BIOPAC Systems Inc" }, { 0x1482, "ISYTEC - Integrierte Systemtechnik GmBH" }, { 0x1483, "LABWAY Corporation" }, { 0x1484, "Logic Corporation" }, { 0x1485, "ERMA - Electronic GmBH" }, { 0x1486, "L3 Communications Telemetry & Instrumentation" }, { 0x1487, "MARQUETTE Medical Systems" }, { 0x1489, "KYE Systems Corporation" }, { 0x148a, "OPTO" }, { 0x148b, "INNOMEDIALOGIC Inc." }, { 0x148c, "Tul Corporation / PowerColor" }, { 0x148d, "DIGICOM Systems, Inc." }, { 0x148e, "OSI Plus Corporation" }, { 0x148f, "Plant Equipment, Inc." }, { 0x1490, "Stone Microsystems PTY Ltd." }, { 0x1491, "ZEAL Corporation" }, { 0x1492, "Time Logic Corporation" }, { 0x1493, "MAKER Communications" }, { 0x1494, "WINTOP Technology, Inc." }, { 0x1495, "TOKAI Communications Industry Co. Ltd" }, { 0x1496, "JOYTECH Computer Co., Ltd." }, { 0x1497, "SMA Regelsysteme GmBH" }, { 0x1498, "TEWS Technologies GmbH" }, { 0x1499, "EMTEC CO., Ltd" }, { 0x149a, "ANDOR Technology Ltd" }, { 0x149b, "SEIKO Instruments Inc" }, { 0x149c, "OVISLINK Corp." }, { 0x149d, "NEWTEK Inc" }, { 0x149e, "Mapletree Networks Inc." }, { 0x149f, "LECTRON Co Ltd" }, { 0x14a0, "SOFTING GmBH" }, { 0x14a1, "Systembase Co Ltd" }, { 0x14a2, "Millennium Engineering Inc" }, { 0x14a3, "Maverick Networks" }, { 0x14a4, "Lite-On Technology Corporation" }, { 0x14a5, "XIONICS Document Technologies Inc" }, { 0x14a6, "INOVA Computers GmBH & Co KG" }, { 0x14a7, "MYTHOS Systems Inc" }, { 0x14a8, "FEATRON Technologies Corporation" }, { 0x14a9, "HIVERTEC Inc" }, { 0x14aa, "Advanced MOS Technology Inc" }, { 0x14ab, "Mentor Graphics Corp." }, { 0x14ac, "Novaweb Technologies Inc" }, { 0x14ad, "Time Space Radio AB" }, { 0x14ae, "CTI, Inc" }, { 0x14af, "Guillemot Corporation" }, { 0x14b0, "BST Communication Technology Ltd" }, { 0x14b1, "Nextcom K.K." }, { 0x14b2, "ENNOVATE Networks Inc" }, { 0x14b3, "XPEED Inc" }, { 0x14b4, "PHILIPS Business Electronics B.V." }, { 0x14b5, "Creamware GmBH" }, { 0x14b6, "Quantum Data Corp." }, { 0x14b7, "PROXIM Inc" }, { 0x14b8, "Techsoft Technology Co Ltd" }, { 0x14b9, "Cisco Aironet Wireless Communications" }, { 0x14ba, "INTERNIX Inc." }, { 0x14bb, "SEMTECH Corporation" }, { 0x14bc, "Globespan Semiconductor Inc." }, { 0x14bd, "CARDIO Control N.V." }, { 0x14be, "L3 Communications" }, { 0x14bf, "SPIDER Communications Inc." }, { 0x14c0, "COMPAL Electronics Inc" }, { 0x14c1, "MYRICOM Inc." }, { 0x14c2, "DTK Computer" }, { 0x14c3, "MEDIATEK Corp." }, { 0x14c4, "IWASAKI Information Systems Co Ltd" }, { 0x14c5, "Automation Products AB" }, { 0x14c6, "Data Race Inc" }, { 0x14c7, "Modular Technology Holdings Ltd" }, { 0x14c8, "Turbocomm Tech. Inc." }, { 0x14c9, "ODIN Telesystems Inc" }, { 0x14ca, "PE Logic Corp." }, { 0x14cb, "Billionton Systems Inc" }, { 0x14cc, "NAKAYO Telecommunications Inc" }, { 0x14cd, "Universal Global Scientific Industrial Co.,Ltd" }, { 0x14ce, "Whistle Communications" }, { 0x14cf, "TEK Microsystems Inc." }, { 0x14d0, "<NAME>" }, { 0x14d1, "Computer Hi-Tech Co Ltd" }, { 0x14d2, "Titan Electronics Inc" }, { 0x14d3, "CIRTECH (UK) Ltd" }, { 0x14d4, "Panacom Technology Corp" }, { 0x14d5, "Nitsuko Corporation" }, { 0x14d6, "Accusys Inc" }, { 0x14d7, "Hirakawa Hewtech Corp" }, { 0x14d8, "HOPF Elektronik GmBH" }, { 0x14d9, "Alliance Semiconductor Corporation" }, { 0x14da, "National Aerospace Laboratories" }, { 0x14db, "AFAVLAB Technology Inc" }, { 0x14dc, "Amplicon Liveline Ltd" }, { 0x14dd, "Boulder Design Labs Inc" }, { 0x14de, "Applied Integration Corporation" }, { 0x14df, "ASIC Communications Corp" }, { 0x14e1, "INVERTEX" }, { 0x14e2, "INFOLIBRIA" }, { 0x14e3, "AMTELCO" }, { 0x14e4, "Broadcom Inc. and subsidiaries" }, { 0x14e5, "Pixelfusion Ltd" }, { 0x14e6, "SHINING Technology Inc" }, { 0x14e7, "3CX" }, { 0x14e8, "RAYCER Inc" }, { 0x14e9, "GARNETS System CO Ltd" }, { 0x14ea, "Planex Communications, Inc" }, { 0x14eb, "SEIKO EPSON Corp" }, { 0x14ec, "Agilent Technologies" }, { 0x14ed, "DATAKINETICS Ltd" }, { 0x14ee, "MASPRO KENKOH Corp" }, { 0x14ef, "CARRY Computer ENG. CO Ltd" }, { 0x14f0, "<NAME>" }, { 0x14f1, "Conexant Systems, Inc." }, { 0x14f2, "MOBILITY Electronics" }, { 0x14f3, "BroadLogic" }, { 0x14f4, "TOKYO Electronic Industry CO Ltd" }, { 0x14f5, "SOPAC Ltd" }, { 0x14f6, "COYOTE Technologies LLC" }, { 0x14f7, "WOLF Technology Inc" }, { 0x14f8, "AUDIOCODES Inc" }, { 0x14f9, "AG COMMUNICATIONS" }, { 0x14fa, "<NAME>" }, { 0x14fb, "TRANSAS MARINE (UK) Ltd" }, { 0x14fc, "Quadrics Ltd" }, { 0x14fd, "JAPAN Computer Industry Inc" }, { 0x14fe, "ARCHTEK TELECOM Corp" }, { 0x14ff, "TWINHEAD INTERNATIONAL Corp" }, { 0x1500, "DELTA Electronics, Inc" }, { 0x1501, "BANKSOFT CANADA Ltd" }, { 0x1502, "MITSUBISHI ELECTRIC LOGISTICS SUPPORT Co Ltd" }, { 0x1503, "KAWASAKI LSI USA Inc" }, { 0x1504, "KAISER Electronics" }, { 0x1505, "ITA INGENIEURBURO FUR TESTAUFGABEN GmbH" }, { 0x1506, "CHAMELEON Systems Inc" }, { 0x1507, "Motorola ?? / HTEC" }, { 0x1508, "HONDA CONNECTORS/MHOTRONICS Inc" }, { 0x1509, "FIRST INTERNATIONAL Computer Inc" }, { 0x150a, "FORVUS RESEARCH Inc" }, { 0x150b, "YAMASHITA Systems Corp" }, { 0x150c, "KYOPAL CO Ltd" }, { 0x150d, "WARPSPPED Inc" }, { 0x150e, "C-PORT Corp" }, { 0x150f, "INTEC GmbH" }, { 0x1510, "BEHAVIOR TECH Computer Corp" }, { 0x1511, "CENTILLIUM Technology Corp" }, { 0x1512, "ROSUN Technologies Inc" }, { 0x1513, "Raychem" }, { 0x1514, "TFL LAN Inc" }, { 0x1515, "Advent design" }, { 0x1516, "MYSON Technology Inc" }, { 0x1517, "ECHOTEK Corp" }, { 0x1518, "Kontron" }, { 0x1519, "TELEFON AKTIEBOLAGET LM Ericsson" }, { 0x151a, "Globetek" }, { 0x151b, "COMBOX Ltd" }, { 0x151c, "DIGITAL AUDIO LABS Inc" }, { 0x151d, "Fujitsu Computer Products Of America" }, { 0x151e, "MATRIX Corp" }, { 0x151f, "TOPIC SEMICONDUCTOR Corp" }, { 0x1520, "CHAPLET System Inc" }, { 0x1521, "BELL Corp" }, { 0x1522, "MainPine Ltd" }, { 0x1523, "MUSIC Semiconductors" }, { 0x1524, "ENE Technology Inc" }, { 0x1525, "IMPACT Technologies" }, { 0x1526, "ISS, Inc" }, { 0x1527, "SOLECTRON" }, { 0x1528, "ACKSYS" }, { 0x1529, "AMERICAN MICROSystems Inc" }, { 0x152a, "QUICKTURN DESIGN Systems" }, { 0x152b, "FLYTECH Technology CO Ltd" }, { 0x152c, "MACRAIGOR Systems LLC" }, { 0x152d, "QUANTA Computer Inc" }, { 0x152e, "MELEC Inc" }, { 0x152f, "PHILIPS - CRYPTO" }, { 0x1530, "ACQIS Technology Inc" }, { 0x1531, "CHRYON Corp" }, { 0x1532, "ECHELON Corp" }, { 0x1533, "BALTIMORE" }, { 0x1534, "ROAD Corp" }, { 0x1535, "EVERGREEN Technologies Inc" }, { 0x1536, "ACTIS Computer" }, { 0x1537, "DATALEX COMMUNCATIONS" }, { 0x1538, "ARALION Inc" }, { 0x1539, "ATELIER INFORMATIQUES et ELECTRONIQUE ETUDES S.A." }, { 0x153a, "<NAME>" }, { 0x153b, "TERRATEC Electronic GmbH" }, { 0x153c, "ANTAL Electronic" }, { 0x153d, "FILANET Corp" }, { 0x153e, "TECHWELL Inc" }, { 0x153f, "MIPS Technologies, Inc." }, { 0x1540, "PROVIDEO MULTIMEDIA Co Ltd" }, { 0x1541, "MACHONE Communications" }, { 0x1542, "Concurrent Real-Time" }, { 0x1543, "SILICON Laboratories" }, { 0x1544, "DCM DATA Systems" }, { 0x1545, "VISIONTEK" }, { 0x1546, "IOI Technology Corp" }, { 0x1547, "MITUTOYO Corp" }, { 0x1548, "JET PROPULSION Laboratory" }, { 0x1549, "INTERCONNECT Systems Solutions" }, { 0x154a, "MAX Technologies Inc" }, { 0x154b, "COMPUTEX Co Ltd" }, { 0x154c, "VISUAL Technology Inc" }, { 0x154d, "PAN INTERNATIONAL Industrial Corp" }, { 0x154e, "SERVOTEST Ltd" }, { 0x154f, "STRATABEAM Technology" }, { 0x1550, "OPEN NETWORK Co Ltd" }, { 0x1551, "SMART Electronic DEVELOPMENT GmBH" }, { 0x1552, "RACAL AIRTECH Ltd" }, { 0x1553, "CHICONY Electronics Co Ltd" }, { 0x1554, "PROLINK Microsystems Corp" }, { 0x1555, "GESYTEC GmBH" }, { 0x1556, "PLDA" }, { 0x1557, "MEDIASTAR Co Ltd" }, { 0x1558, "CLEVO/KAPOK Computer" }, { 0x1559, "SI LOGIC Ltd" }, { 0x155a, "INNOMEDIA Inc" }, { 0x155b, "PROTAC INTERNATIONAL Corp" }, { 0x155c, "Cemax-Icon Inc" }, { 0x155d, "Mac System Co Ltd" }, { 0x155e, "LP Elektronik GmbH" }, { 0x155f, "Perle Systems Ltd" }, { 0x1560, "Terayon Communications Systems" }, { 0x1561, "Viewgraphics Inc" }, { 0x1562, "Symbol Technologies" }, { 0x1563, "A-Trend Technology Co Ltd" }, { 0x1564, "Yamakatsu Electronics Industry Co Ltd" }, { 0x1565, "Biostar Microtech Int'l Corp" }, { 0x1566, "Ardent Technologies Inc" }, { 0x1567, "Jungsoft" }, { 0x1568, "DDK Electronics Inc" }, { 0x1569, "Palit Microsystems Inc." }, { 0x156a, "Avtec Systems" }, { 0x156b, "2wire Inc" }, { 0x156c, "Vidac Electronics GmbH" }, { 0x156d, "Alpha-Top Corp" }, { 0x156e, "Alfa Inc" }, { 0x156f, "M-Systems Flash Disk Pioneers Ltd" }, { 0x1570, "Lecroy Corp" }, { 0x1571, "Contemporary Controls" }, { 0x1572, "Otis Elevator Company" }, { 0x1573, "Lattice - Vantis" }, { 0x1574, "Fairchild Semiconductor" }, { 0x1575, "Voltaire Advanced Data Security Ltd" }, { 0x1576, "Viewcast COM" }, { 0x1578, "HITT" }, { 0x1579, "Dual Technology Corp" }, { 0x157a, "Japan Elecronics Ind Inc" }, { 0x157b, "Star Multimedia Corp" }, { 0x157c, "Eurosoft (UK)" }, { 0x157d, "Gemflex Networks" }, { 0x157e, "Transition Networks" }, { 0x157f, "PX Instruments Technology Ltd" }, { 0x1580, "Primex Aerospace Co" }, { 0x1581, "SEH Computertechnik GmbH" }, { 0x1582, "Cytec Corp" }, { 0x1583, "Inet Technologies Inc" }, { 0x1584, "Uniwill Computer Corp" }, { 0x1585, "Logitron" }, { 0x1586, "Lancast Inc" }, { 0x1587, "Konica Corp" }, { 0x1588, "Solidum Systems Corp" }, { 0x1589, "Atlantek Microsystems Pty Ltd" }, { 0x158a, "Digalog Systems Inc" }, { 0x158b, "Allied Data Technologies" }, { 0x158c, "Hitachi Semiconductor & Devices Sales Co Ltd" }, { 0x158d, "Point Multimedia Systems" }, { 0x158e, "Lara Technology Inc" }, { 0x158f, "D<NAME>" }, { 0x1590, "Hewlett Packard Enterprise" }, { 0x1591, "ARN" }, { 0x1592, "Syba Tech Ltd" }, { 0x1593, "Bops Inc" }, { 0x1594, "Netgame Ltd" }, { 0x1595, "Diva Systems Corp" }, { 0x1596, "Folsom Research Inc" }, { 0x1597, "Memec Design Services" }, { 0x1598, "Granite Microsystems" }, { 0x1599, "Delta Electronics Inc" }, { 0x159a, "General Instrument" }, { 0x159b, "Faraday Technology Corp" }, { 0x159c, "Stratus Computer Systems" }, { 0x159d, "Ningbo Harrison Electronics Co Ltd" }, { 0x159e, "A-Max Technology Co Ltd" }, { 0x159f, "Galea Network Security" }, { 0x15a0, "Compumaster SRL" }, { 0x15a1, "Geocast Network Systems" }, { 0x15a2, "Catalyst Enterprises Inc" }, { 0x15a3, "Italtel" }, { 0x15a4, "X-Net OY" }, { 0x15a5, "Toyota Macs Inc" }, { 0x15a6, "Sunlight Ultrasound Technologies Ltd" }, { 0x15a7, "SSE Telecom Inc" }, { 0x15a8, "Shanghai Communications Technologies Center" }, { 0x15aa, "<NAME>" }, { 0x15ab, "Bluesteel Networks Inc" }, { 0x15ac, "North Atlantic Instruments" }, { 0x15ad, "VMware" }, { 0x15ae, "<NAME>" }, { 0x15b0, "Zoltrix International Ltd" }, { 0x15b1, "Source Technology Inc" }, { 0x15b2, "Mosaid Technologies Inc" }, { 0x15b3, "Mellanox Technologies" }, { 0x15b4, "CCI/TRIAD" }, { 0x15b5, "Cimetrics Inc" }, { 0x15b6, "Texas Memory Systems Inc" }, { 0x15b7, "Sandisk Corp" }, { 0x15b8, "ADDI-DATA GmbH" }, { 0x15b9, "Maestro Digital Communications" }, { 0x15ba, "Impacct Technology Corp" }, { 0x15bb, "Portwell Inc" }, { 0x15bc, "Agilent Technologies" }, { 0x15bd, "DFI Inc" }, { 0x15be, "Sola Electronics" }, { 0x15bf, "High Tech Computer Corp (HTC)" }, { 0x15c0, "BVM Ltd" }, { 0x15c1, "Quantel" }, { 0x15c2, "Newer Technology Inc" }, { 0x15c3, "Taiwan Mycomp Co Ltd" }, { 0x15c4, "EVSX Inc" }, { 0x15c5, "Procomp Informatics Ltd" }, { 0x15c6, "Technical University of Budapest" }, { 0x15c7, "Tateyama System Laboratory Co Ltd" }, { 0x15c8, "Penta Media Co Ltd" }, { 0x15c9, "Serome Technology Inc" }, { 0x15ca, "Bitboys OY" }, { 0x15cb, "AG Electronics Ltd" }, { 0x15cc, "Hotrail Inc" }, { 0x15cd, "Dreamtech Co Ltd" }, { 0x15ce, "Genrad Inc" }, { 0x15cf, "Hilscher GmbH" }, { 0x15d1, "Infineon Technologies AG" }, { 0x15d2, "FIC (First International Computer Inc)" }, { 0x15d3, "NDS Technologies Israel Ltd" }, { 0x15d4, "Iwill Corp" }, { 0x15d5, "Tatung Co" }, { 0x15d6, "Entridia Corp" }, { 0x15d7, "Rockwell-Collins Inc" }, { 0x15d8, "Cybernetics Technology Co Ltd" }, { 0x15d9, "Super Micro Computer Inc" }, { 0x15da, "Cyberfirm Inc" }, { 0x15db, "Applied Computing Systems Inc" }, { 0x15dc, "Litronic Inc" }, { 0x15dd, "Sigmatel Inc" }, { 0x15de, "Malleable Technologies Inc" }, { 0x15df, "Infinilink Corp" }, { 0x15e0, "Cacheflow Inc" }, { 0x15e1, "Voice Technologies Group Inc" }, { 0x15e2, "Quicknet Technologies Inc" }, { 0x15e3, "Networth Technologies Inc" }, { 0x15e4, "VSN Systemen BV" }, { 0x15e5, "Valley technologies Inc" }, { 0x15e6, "Agere Inc" }, { 0x15e7, "Get Engineering Corp" }, { 0x15e8, "National Datacomm Corp" }, { 0x15e9, "Pacific Digital Corp" }, { 0x15ea, "<NAME>." }, { 0x15eb, "DResearch Digital Media Systems GmbH" }, { 0x15ec, "Beckhoff GmbH" }, { 0x15ed, "Macrolink Inc" }, { 0x15ee, "In Win Development Inc" }, { 0x15ef, "Intelligent Paradigm Inc" }, { 0x15f0, "B-Tree Systems Inc" }, { 0x15f1, "Times N Systems Inc" }, { 0x15f2, "Diagnostic Instruments Inc" }, { 0x15f3, "Digitmedia Corp" }, { 0x15f4, "Valuesoft" }, { 0x15f5, "Power Micro Research" }, { 0x15f6, "Extreme Packet Device Inc" }, { 0x15f7, "Banctec" }, { 0x15f8, "Koga Electronics Co" }, { 0x15f9, "Zenith Electronics Corp" }, { 0x15fa, "J.P. Axzam Corp" }, { 0x15fb, "Zilog Inc" }, { 0x15fc, "Techsan Electronics Co Ltd" }, { 0x15fd, "N-CUBED.NET" }, { 0x15fe, "Kinpo Electronics Inc" }, { 0x15ff, "Fastpoint Technologies Inc" }, { 0x1600, "Northrop Grumman - Canada Ltd" }, { 0x1601, "Tenta Technology" }, { 0x1602, "Prosys-tec Inc" }, { 0x1603, "Nokia Wireless Communications" }, { 0x1604, "Central System Research Co Ltd" }, { 0x1605, "Pairgain Technologies" }, { 0x1606, "Europop AG" }, { 0x1607, "Lava Semiconductor Manufacturing Inc" }, { 0x1608, "Automated Wagering International" }, { 0x1609, "Scimetric Instruments Inc" }, { 0x1612, "Telesynergy Research Inc." }, { 0x1618, "Stone Ridge Technology" }, { 0x1619, "FarSite Communications Ltd" }, { 0x161f, "Rioworks" }, { 0x1621, "Lynx Studio Technology, Inc." }, { 0x1626, "TDK Semiconductor Corp." }, { 0x1629, "Kongsberg Spacetec AS" }, { 0x1631, "<NAME> B.V." }, { 0x1638, "Standard Microsystems Corp [SMC]" }, { 0x163c, "Smart Link Ltd." }, { 0x1641, "MKNet Corp." }, { 0x1642, "Bitland(ShenZhen) Information Technology Co., Ltd." }, { 0x1657, "Cavium QLogic" }, { 0x165a, "Epix Inc" }, { 0x165c, "Gidel Ltd." }, { 0x165d, "Hsing Tech. Enterprise Co., Ltd." }, { 0x165f, "Linux Media Labs, LLC" }, { 0x1661, "Worldspace Corp." }, { 0x1668, "Actiontec Electronics Inc" }, { 0x166d, "Broadcom Corporation" }, { 0x1677, "Bernecker + Rainer" }, { 0x1678, "NetEffect" }, { 0x1679, "Tokyo Electron Device Ltd." }, { 0x167b, "ZyDAS Technology Corp." }, { 0x167d, "Samsung Electro-Mechanics Co., Ltd." }, { 0x167e, "ONNTO Corp." }, { 0x1681, "Hercules" }, { 0x1682, "XFX Pine Group Inc." }, { 0x1688, "CastleNet Technology Inc." }, { 0x168a, "Utimaco IS GmbH" }, { 0x168c, "Qualcomm Atheros" }, { 0x1695, "EPoX Computer Co., Ltd." }, { 0x169c, "Netcell Corporation" }, { 0x169d, "Club-3D VB (Wrong ID)" }, { 0x16a5, "Tekram Technology Co.,Ltd." }, { 0x16ab, "Global Sun Technology Inc" }, { 0x16ae, "SafeNet Inc" }, { 0x16af, "SparkLAN Communications, Inc." }, { 0x16b4, "Aspex Semiconductor Ltd" }, { 0x16b8, "Sonnet Technologies, Inc." }, { 0x16be, "Creatix Polymedia GmbH" }, { 0x16c3, "Synopsys, Inc." }, { 0x16c6, "Micrel-Kendin" }, { 0x16c8, "Octasic Inc." }, { 0x16c9, "EONIC B.V. The Netherlands" }, { 0x16ca, "CENATEK Inc" }, { 0x16cd, "Advantech Co. Ltd" }, { 0x16ce, "Roland Corp." }, { 0x16d5, "Acromag, Inc." }, { 0x16da, "Advantech Co., Ltd." }, { 0x16df, "PIKA Technologies Inc." }, { 0x16e2, "Geotest-MTS" }, { 0x16e3, "European Space Agency" }, { 0x16e5, "Intellon Corp." }, { 0x16ec, "U.S. Robotics" }, { 0x16ed, "<NAME>." }, { 0x16f2, "ETAS GmbH" }, { 0x16f3, "Jetway Information Co., Ltd." }, { 0x16f4, "Vweb Corp" }, { 0x16f6, "VideoTele.com, Inc." }, { 0x1702, "Internet Machines Corporation (IMC)" }, { 0x1705, "Digital First, Inc." }, { 0x170b, "NetOctave" }, { 0x170c, "YottaYotta Inc." }, { 0x1719, "EZChip Technologies" }, { 0x1725, "Vitesse Semiconductor" }, { 0x172a, "Accelerated Encryption" }, { 0x1734, "Fujitsu Technology Solutions" }, { 0x1735, "Aten International Co. Ltd." }, { 0x1737, "Linksys" }, { 0x173b, "Altima (nee Broadcom)" }, { 0x1743, "Peppercon AG" }, { 0x1745, "ViXS Systems, Inc." }, { 0x1749, "RLX Technologies" }, { 0x174b, "PC Partner Limited / Sapphire Technology" }, { 0x174d, "WellX Telecom SA" }, { 0x175c, "AudioScience Inc" }, { 0x175e, "Sanera Systems, Inc." }, { 0x1760, "TEDIA spol. s r. o." }, { 0x1761, "Pickering Interfaces Ltd" }, { 0x1771, "InnoVISION Multimedia Ltd." }, { 0x1775, "General Electric" }, { 0x177d, "Cavium, Inc." }, { 0x1787, "Hightech Information System Ltd." }, { 0x1789, "Ennyah Technologies Corp." }, { 0x1796, "Research Centre Juelich" }, { 0x1797, "Intersil Techwell" }, { 0x1799, "Belkin" }, { 0x179a, "id Quantique" }, { 0x179c, "Data Patterns" }, { 0x17a0, "Genesys Logic, Inc" }, { 0x17aa, "Lenovo" }, { 0x17ab, "Phillips Components" }, { 0x17af, "Hightech Information System Ltd." }, { 0x17b3, "Hawking Technologies" }, { 0x17b4, "Indra Networks, Inc." }, { 0x17c0, "Wistron Corp." }, { 0x17c2, "Newisys, Inc." }, { 0x17cb, "Qualcomm" }, { 0x17cc, "NetChip Technology, Inc" }, { 0x17cd, "Cadence Design Systems, Inc." }, { 0x17cf, "Z-Com, Inc." }, { 0x17d3, "Areca Technology Corp." }, { 0x17d5, "Exar Corp." }, { 0x17db, "Cray Inc" }, { 0x17de, "KWorld Computer Co. Ltd." }, { 0x17df, "Dini Group" }, { 0x17e4, "Sectra AB" }, { 0x17e6, "MaxLinear" }, { 0x17ee, "Connect Components Ltd" }, { 0x17f2, "Albatron Corp." }, { 0x17f3, "RDC Semiconductor, Inc." }, { 0x17f7, "Topdek Semiconductor Inc." }, { 0x17f9, "Gemtek Technology Co., Ltd" }, { 0x17fc, "IOGEAR, Inc." }, { 0x17fe, "InProComm Inc." }, { 0x17ff, "Benq Corporation" }, { 0x1800, "Qualcore Logic Inc." }, { 0x1803, "ProdaSafe GmbH" }, { 0x1804, "Ralink corp. (wrong ID)" }, { 0x1805, "Euresys S.A." }, { 0x1809, "Lumanate, Inc." }, { 0x180c, "IEI Integration Corp" }, { 0x1813, "Ambient Technologies Inc" }, { 0x1814, "Ralink corp." }, { 0x1815, "Devolo AG" }, { 0x1820, "InfiniCon Systems Inc." }, { 0x1822, "Twinhan Technology Co. Ltd" }, { 0x182d, "SiteCom Europe BV" }, { 0x182e, "Raza Microelectronics, Inc." }, { 0x182f, "Broadcom" }, { 0x1830, "Credence Systems Corporation" }, { 0x183b, "MikroM GmbH" }, { 0x1846, "Alcatel-Lucent" }, { 0x1849, "ASRock Incorporation" }, { 0x184a, "Thales Computers" }, { 0x1850, "Advantest Corporation" }, { 0x1851, "Microtune, Inc." }, { 0x1852, "Anritsu Corp." }, { 0x1853, "SMSC Automotive Infotainment System Group" }, { 0x1854, "LG Electronics, Inc." }, { 0x185b, "Compro Technology, Inc." }, { 0x185f, "Wistron NeWeb Corp." }, { 0x1864, "SilverBack" }, { 0x1867, "Topspin Communications" }, { 0x186c, "Humusoft, s.r.o." }, { 0x186f, "WiNRADiO Communications" }, { 0x1876, "L-3 Communications" }, { 0x187e, "ZyXEL Communications Corporation" }, { 0x1885, "Avvida Systems Inc." }, { 0x1888, "Varisys Ltd" }, { 0x188a, "Ample Communications, Inc" }, { 0x1890, "Egenera, Inc." }, { 0x1894, "KNC One" }, { 0x1896, "B&B Electronics Manufacturing Company, Inc." }, { 0x1897, "AMtek" }, { 0x18a1, "Astute Networks Inc." }, { 0x18a2, "Stretch Inc." }, { 0x18a3, "AT&T" }, { 0x18ac, "DViCO Corporation" }, { 0x18b8, "Ammasso" }, { 0x18bc, "GeCube Technologies, Inc." }, { 0x18c3, "Micronas Semiconductor Holding AG" }, { 0x18c8, "Cray Inc" }, { 0x18c9, "ARVOO Engineering BV" }, { 0x18ca, "XGI Technology Inc. (eXtreme Graphics Innovation)" }, { 0x18d2, "Sitecom Europe BV (Wrong ID)" }, { 0x18d4, "Celestica" }, { 0x18d8, "Dialogue Technology Corp." }, { 0x18dd, "Artimi Inc" }, { 0x18df, "LeWiz Communications" }, { 0x18e6, "MPL AG" }, { 0x18eb, "Advance Multimedia Internet Technology, Inc." }, { 0x18ec, "Cesnet, z.s.p.o." }, { 0x18ee, "Chenming Mold Ind. Corp." }, { 0x18f1, "Spectrum GmbH" }, { 0x18f4, "Napatech A/S" }, { 0x18f6, "NextIO" }, { 0x18f7, "Commtech, Inc." }, { 0x18fb, "Resilience Corporation" }, { 0x1904, "Hangzhou Silan Microelectronics Co., Ltd." }, { 0x1905, "Micronas USA, Inc." }, { 0x1912, "Renesas Technology Corp." }, { 0x1919, "Soltek Computer Inc." }, { 0x1923, "Sangoma Technologies Corp." }, { 0x1924, "Solarflare Communications" }, { 0x192a, "BiTMICRO Networks Inc." }, { 0x192e, "TransDimension" }, { 0x1931, "Option N.V." }, { 0x1932, "DiBcom" }, { 0x193c, "MAXIM Integrated Products" }, { 0x193d, "Hangzhou H3C Technologies Co., Ltd." }, { 0x193f, "AHA Products Group" }, { 0x1942, "ClearSpeed Technology plc" }, { 0x1947, "C-guys, Inc." }, { 0x1948, "Alpha Networks Inc." }, { 0x194a, "DapTechnology B.V." }, { 0x1954, "One Stop Systems, Inc." }, { 0x1957, "Freescale Semiconductor Inc" }, { 0x1958, "Faster Technology, LLC." }, { 0x1959, "PA Semi, Inc" }, { 0x1966, "Orad Hi-Tec Systems" }, { 0x1969, "Qualcomm Atheros" }, { 0x196a, "Sensory Networks Inc." }, { 0x196d, "Club-3D BV" }, { 0x196e, "PNY" }, { 0x1971, "AGEIA Technologies, Inc." }, { 0x1974, "Star Electronics GmbH & Co. KG" }, { 0x1976, "TRENDnet" }, { 0x1977, "Parsec" }, { 0x197b, "JMicron Technology Corp." }, { 0x1982, "Distant Early Warning Communications Inc" }, { 0x1987, "Phison Electronics Corporation" }, { 0x1989, "Montilio Inc." }, { 0x198a, "Nallatech Ltd." }, { 0x1993, "Innominate Security Technologies AG" }, { 0x1999, "A-Logics" }, { 0x199a, "Pulse-LINK, Inc." }, { 0x199d, "Xsigo Systems" }, { 0x199f, "Auvitek" }, { 0x19a2, "Emulex Corporation" }, { 0x19a8, "DAQDATA GmbH" }, { 0x19ac, "Kasten Chase Applied Research" }, { 0x19ae, "Progeny Systems Corporation" }, { 0x19ba, "ZyXEL Communications Corp." }, { 0x19c1, "Exegy Inc." }, { 0x19d1, "Motorola Expedience" }, { 0x19d4, "Quixant Limited" }, { 0x19da, "ZOTAC International (MCO) Ltd." }, { 0x19de, "Pico Computing" }, { 0x19e2, "Vector Informatik GmbH" }, { 0x19e3, "DDRdrive LLC" }, { 0x19e5, "Huawei Technologies Co., Ltd." }, { 0x19e7, "NET (Network Equipment Technologies)" }, { 0x19ee, "Netronome Systems, Inc." }, { 0x19f1, "BFG Tech" }, { 0x19ff, "Eclipse Electronic Systems, Inc." }, { 0x1a03, "ASPEED Technology, Inc." }, { 0x1a05, "deltaww" }, { 0x1a07, "Kvaser AB" }, { 0x1a08, "Sierra semiconductor" }, { 0x1a0e, "DekTec Digital Video B.V." }, { 0x1a17, "Force10 Networks, Inc." }, { 0x1a1d, "GFaI e.V." }, { 0x1a1e, "3Leaf Systems, Inc." }, { 0x1a22, "Ambric Inc." }, { 0x1a29, "Fortinet, Inc." }, { 0x1a2b, "Ascom AG" }, { 0x1a30, "Lantiq" }, { 0x1a32, "Quanta Microsystems, Inc" }, { 0x1a3b, "AzureWave" }, { 0x1a41, "Tilera Corp." }, { 0x1a4a, "SLAC National Accelerator Lab TID-AIR" }, { 0x1a51, "Hectronic AB" }, { 0x1a55, "Rohde & Schwarz DVS GmbH" }, { 0x1a56, "Bigfoot Networks, Inc." }, { 0x1a57, "Highly Reliable Systems" }, { 0x1a58, "Razer USA Ltd." }, { 0x1a5d, "Celoxica" }, { 0x1a5e, "Aprius Inc." }, { 0x1a5f, "System TALKS Inc." }, { 0x1a68, "VirtenSys Limited" }, { 0x1a71, "XenSource, Inc." }, { 0x1a73, "Violin Memory, Inc" }, { 0x1a76, "Wavesat" }, { 0x1a77, "Lightfleet Corporation" }, { 0x1a78, "Virident Systems Inc." }, { 0x1a84, "Commex Technologies" }, { 0x1a88, "<NAME>" }, { 0x1a8a, "StarBridge, Inc." }, { 0x1a8c, "Verigy Pte. Ltd." }, { 0x1a8e, "DRS Technologies" }, { 0x1aa8, "Ciprico, Inc." }, { 0x1aae, "Global Velocity, Inc." }, { 0x1ab4, "Distributed Management Task Force, Inc. (DMTF)" }, { 0x1ab6, "CalDigit, Inc." }, { 0x1ab8, "Parallels, Inc." }, { 0x1ab9, "Espia Srl" }, { 0x1ac1, "Global Unichip Corp." }, { 0x1ac8, "<NAME>" }, { 0x1acc, "Point of View BV" }, { 0x1ad7, "Spectracom Corporation" }, { 0x1ade, "Spin Master Ltd." }, { 0x1ae0, "Google, Inc." }, { 0x1ae3, "SANBlaze Technology, Inc." }, { 0x1ae7, "First Wise Media GmbH" }, { 0x1ae8, "Silicon Software GmbH" }, { 0x1ae9, "Wilocity Ltd." }, { 0x1aea, "Alcor Micro" }, { 0x1aec, "Wolfson Microelectronics" }, { 0x1aed, "SanDisk" }, { 0x1aee, "Caustic Graphics Inc." }, { 0x1af4, "Red Hat, Inc." }, { 0x1af5, "Netezza Corp." }, { 0x1afa, "J & W Electronics Co., Ltd." }, { 0x1b03, "Magnum Semiconductor, Inc," }, { 0x1b08, "MSC Technologies GmbH" }, { 0x1b0a, "Pegatron" }, { 0x1b13, "Jaton Corp" }, { 0x1b1a, "K&F Computing Research Co." }, { 0x1b21, "ASMedia Technology Inc." }, { 0x1b26, "Netcope Technologies, a.s." }, { 0x1b2c, "Opal-RT Technologies Inc." }, { 0x1b36, "Red Hat, Inc." }, { 0x1b37, "Signal Processing Devices Sweden AB" }, { 0x1b39, "sTec, Inc." }, { 0x1b3a, "Westar Display Technologies" }, { 0x1b3e, "Teradata Corp." }, { 0x1b40, "Schooner Information Technology, Inc." }, { 0x1b47, "Numascale AS" }, { 0x1b4b, "Marvell Technology Group Ltd." }, { 0x1b55, "NetUP Inc." }, { 0x1b66, "DELTACAST" }, { 0x1b6f, "Etron Technology, Inc." }, { 0x1b73, "Fresco Logic" }, { 0x1b74, "OpenVox Communication Co. Ltd." }, { 0x1b79, "Absolute Analysis" }, { 0x1b85, "OCZ Technology Group, Inc." }, { 0x1b94, "Signatec / Dynamic Signals Corp" }, { 0x1b96, "Western Digital" }, { 0x1b9a, "XAVi Technologies Corp." }, { 0x1baa, "QNAP Systems, Inc." }, { 0x1bad, "ReFLEX CES" }, { 0x1bb0, "SimpliVity Corporation" }, { 0x1bb1, "Seagate Technology PLC" }, { 0x1bb3, "Bluecherry" }, { 0x1bb5, "Quantenna Communications, Inc." }, { 0x1bbf, "Maxeler Technologies Ltd." }, { 0x1bcf, "NEC Corporation" }, { 0x1bd0, "Astronics Corporation" }, { 0x1bd4, "Inspur Electronic Information Industry Co., Ltd." }, { 0x1bee, "IXXAT Automation GmbH" }, { 0x1bef, "Lantiq" }, { 0x1bf4, "VTI Instruments Corporation" }, { 0x1bfd, "EeeTOP" }, { 0x1c09, "CSP, Inc." }, { 0x1c1c, "Symphony" }, { 0x1c1f, "SoftLab-NSK" }, { 0x1c28, "Lite-On IT Corp. / Plextor" }, { 0x1c2c, "Silicom Denmark" }, { 0x1c32, "Highland Technology, Inc." }, { 0x1c33, "Daktronics, Inc" }, { 0x1c36, "Annapurna Labs Ltd." }, { 0x1c3b, "Accensus, LLC" }, { 0x1c44, "Enmotus Inc" }, { 0x1c58, "HGST, Inc." }, { 0x1c5c, "SK hynix" }, { 0x1c5f, "Beijing Memblaze Technology Co. Ltd." }, { 0x1c63, "Science and Research Centre of Computer Technology (JSC \"NICEVT\")" }, { 0x1c7e, "TTTech Computertechnik AG" }, { 0x1c7f, "Elektrobit Austria GmbH" }, { 0x1c8a, "TSF5 Corporation" }, { 0x1c8c, "Mobiveil, Inc." }, { 0x1cb0, "Shannon Systems" }, { 0x1cb1, "Collion UG & Co.KG" }, { 0x1cb5, "Focusrite Audio Engineering Ltd" }, { 0x1cb8, "Dawning Information Industry Co., Ltd." }, { 0x1cc1, "ADATA Technology Co., Ltd." }, { 0x1cc4, "Union Memory (Shenzhen)" }, { 0x1cc5, "Embedded Intelligence, Inc." }, { 0x1cc7, "Radian Memory Systems Inc." }, { 0x1ccf, "Zoom Corporation" }, { 0x1cd2, "SesKion GmbH" }, { 0x1cd7, "Nanjing Magewell Electronics Co., Ltd." }, { 0x1cdd, "secunet Security Networks AG" }, { 0x1ce4, "Exablaze" }, { 0x1cf0, "Akitio" }, { 0x1cf7, "Subspace Dynamics" }, { 0x1d00, "Pure Storage" }, { 0x1d05, "Tongfang Hongkong Limited" }, { 0x1d0f, "Amazon.com, Inc." }, { 0x1d17, "Zhaoxin" }, { 0x1d18, "RME" }, { 0x1d1d, "CNEX Labs" }, { 0x1d21, "Allo" }, { 0x1d22, "Baidu Technology" }, { 0x1d26, "Kalray Inc." }, { 0x1d37, "NovaSparks" }, { 0x1d40, "Techman Electronics (Changshu) Co., Ltd." }, { 0x1d44, "DPT" }, { 0x1d49, "Lenovo" }, { 0x1d4c, "Diamanti, Inc." }, { 0x1d5c, "Fantasia Trading LLC" }, { 0x1d61, "Technobox, Inc." }, { 0x1d62, "Nebbiolo Technologies" }, { 0x1d65, "Imagine Communications Corp." }, { 0x1d6a, "Aquantia Corp." }, { 0x1d6c, "Atomic Rules LLC" }, { 0x1d72, "Xiaomi" }, { 0x1d78, "DERA Storage" }, { 0x1d7c, "Aerotech, Inc." }, { 0x1d82, "NETINT Technologies Inc." }, { 0x1d87, "Fuzhou Rockchip Electronics Co., Ltd" }, { 0x1d8f, "Enyx" }, { 0x1d93, "YADRO (KNS Group)" }, { 0x1d94, "Chengdu Haiguang IC Design Co., Ltd." }, { 0x1d95, "Graphcore Ltd" }, { 0x1d97, "Shenzhen Longsys Electronics Co., Ltd." }, { 0x1d9b, "Facebook, Inc." }, { 0x1da1, "Teko Telecom S.r.l." }, { 0x1da2, "Sapphire Technology Limited" }, { 0x1da3, "Habana Labs Ltd." }, { 0x1db2, "ATP ELECTRONICS INC" }, { 0x1dbb, "NGD Systems, Inc." }, { 0x1dbf, "Guizhou Huaxintong Semiconductor Technology Co., Ltd" }, { 0x1dc5, "FADU Inc." }, { 0x1dcd, "Liqid Inc." }, { 0x1dd8, "Pensando Systems" }, { 0x1de0, "Groq" }, { 0x1de1, "Tekram Technology Co.,Ltd." }, { 0x1de5, "Eideticom, Inc" }, { 0x1dee, "Biwin Storage Technology Co., Ltd." }, { 0x1def, "Ampere Computing, LLC" }, { 0x1df3, "Ethernity Networks" }, { 0x1df7, "opencpi.org" }, { 0x1dfc, "JSC NT-COM" }, { 0x1e0f, "KIOXIA Corporation" }, { 0x1e17, "Arnold & Richter Cine Technik GmbH & Co. Betriebs KG" }, { 0x1e24, "Squirrels Research Labs" }, { 0x1e26, "Fujitsu Client Computing Limited" }, { 0x1e36, "Shanghai Enflame Technology Co. Ltd" }, { 0x1e38, "Blaize, Inc" }, { 0x1e3d, "Burlywood, Inc" }, { 0x1e49, "Yangtze Memory Technologies Co.,Ltd" }, { 0x1e4b, "MAXIO Technology (Hangzhou) Ltd." }, { 0x1e4c, "GSI Technology" }, { 0x1e57, "Beijing Panyi Technology Co., Ltd" }, { 0x1e6b, "Axiado Corp." }, { 0x1e85, "Heitec AG" }, { 0x1e89, "ID Quantique SA" }, { 0x1e94, "Calian SED" }, { 0x1e95, "Solid State Storage Technology Corporation" }, { 0x1fc0, "Ascom (Finland) Oy" }, { 0x1fc1, "QLogic, Corp." }, { 0x1fc9, "Tehuti Networks Ltd." }, { 0x1fcc, "StreamLabs" }, { 0x1fce, "Cognio Inc." }, { 0x1fd4, "SUNIX Co., Ltd." }, { 0x2000, "Smart Link Ltd." }, { 0x2001, "Temporal Research Ltd" }, { 0x2003, "Smart Link Ltd." }, { 0x2004, "Smart Link Ltd." }, { 0x2048, "Beijing SpaceControl Technology Co.Ltd" }, { 0x20f4, "TRENDnet" }, { 0x2116, "ZyDAS Technology Corp." }, { 0x21c3, "21st Century Computer Corp." }, { 0x22b8, "Flex-Logix Technologies" }, { 0x22db, "Missing Link Electronics, Inc." }, { 0x2304, "Colorgraphic Communications Corp." }, { 0x2348, "Racore" }, { 0x2646, "Kingston Technology Company, Inc." }, { 0x270b, "Xantel Corporation" }, { 0x270f, "Chaintech Computer Co. Ltd" }, { 0x2711, "AVID Technology Inc." }, { 0x2955, "Connectix Virtual PC" }, { 0x2a15, "3D Vision(?)" }, { 0x2bd8, "ROPEX Industrie-Elektronik GmbH" }, { 0x3000, "Hansol Electronics Inc." }, { 0x3112, "<NAME>." }, { 0x3130, "AUDIOTRAK" }, { 0x3142, "Post Impression Systems." }, { 0x31ab, "Zonet" }, { 0x3388, "Hint Corp" }, { 0x3411, "Quantum Designs (H.K.) Inc" }, { 0x3442, "Bihl+Wiedemann GmbH" }, { 0x3475, "Arastra Inc." }, { 0x3513, "ARCOM Control Systems Ltd" }, { 0x37d9, "ITD Firm ltd." }, { 0x3842, "eVga.com. Corp." }, { 0x38ef, "4Links" }, { 0x3d3d, "3DLabs" }, { 0x4005, "Avance Logic Inc." }, { 0x4033, "Addtron Technology Co, Inc." }, { 0x4040, "NetXen Incorporated" }, { 0x4143, "Digital Equipment Corp" }, { 0x4144, "Alpha Data" }, { 0x4150, "ONA Electroerosion" }, { 0x415a, "Auzentech, Inc." }, { 0x416c, "Aladdin Knowledge Systems" }, { 0x4254, "DVBSky" }, { 0x4321, "Tata Power Strategic Electronics Division" }, { 0x4348, "WCH.CN" }, { 0x434e, "CAST Navigation LLC" }, { 0x4444, "Internext Compression Inc" }, { 0x4468, "Bridgeport machines" }, { 0x4594, "Cogetec Informatique Inc" }, { 0x45fb, "Baldor Electric Company" }, { 0x4624, "Budker Institute of Nuclear Physics" }, { 0x4651, "TXIC" }, { 0x4680, "Umax Computer Corp" }, { 0x4843, "Hercules Computer Technology Inc" }, { 0x4916, "RedCreek Communications Inc" }, { 0x4943, "Growth Networks" }, { 0x494f, "ACCES I/O Products, Inc." }, { 0x4978, "Axil Computer Inc" }, { 0x4a14, "NetVin" }, { 0x4b10, "Buslogic Inc." }, { 0x4c48, "LUNG HWA Electronics" }, { 0x4c52, "LR-Link" }, { 0x4c53, "SBS Technologies" }, { 0x4ca1, "Seanix Technology Inc" }, { 0x4d51, "MediaQ Inc." }, { 0x4d54, "Microtechnica Co Ltd" }, { 0x4d56, "MATRIX VISION GmbH" }, { 0x4ddc, "ILC Data Device Corp" }, { 0x5045, "University of Toronto" }, { 0x5046, "GemTek Technology Corporation" }, { 0x5053, "Voyetra Technologies" }, { 0x50b2, "TerraTec Electronic GmbH" }, { 0x5136, "S S Technologies" }, { 0x5143, "Qualcomm Inc" }, { 0x5145, "Ensoniq (Old)" }, { 0x5168, "Animation Technologies Inc." }, { 0x5301, "Alliance Semiconductor Corp." }, { 0x5333, "S3 Graphics Ltd." }, { 0x5431, "AuzenTech, Inc." }, { 0x544c, "Teralogic Inc" }, { 0x544d, "TBS Technologies" }, { 0x5452, "SCANLAB AG" }, { 0x5455, "Technische Universitaet Berlin" }, { 0x5456, "GoTView" }, { 0x5519, "Cnet Technologies, Inc." }, { 0x5544, "Dunord Technologies" }, { 0x5555, "Genroco, Inc" }, { 0x5646, "Vector Fabrics BV" }, { 0x5654, "VoiceTronix Pty Ltd" }, { 0x5678, "Dawicontrol Computersysteme GmbH" }, { 0x5700, "Netpower" }, { 0x5845, "X-ES, Inc." }, { 0x584d, "AuzenTech Co., Ltd." }, { 0x5851, "Exacq Technologies" }, { 0x5853, "XenSource, Inc." }, { 0x5854, "GoTView" }, { 0x5ace, "Beholder International Ltd." }, { 0x6205, "TBS Technologies (wrong ID)" }, { 0x6209, "TBS Technologies (wrong ID)" }, { 0x631c, "SmartInfra Ltd" }, { 0x6356, "UltraStor" }, { 0x6374, "c't Magazin fuer Computertechnik" }, { 0x6409, "Logitec Corp." }, { 0x6549, "Teradici Corp." }, { 0x6666, "Decision Computer International Co." }, { 0x6688, "Zycoo Co., Ltd" }, { 0x6900, "Red Hat, Inc." }, { 0x7063, "pcHDTV" }, { 0x7284, "HT OMEGA Inc." }, { 0x7357, "IOxOS Technologies SA" }, { 0x7401, "EndRun Technologies" }, { 0x7470, "TP-LINK Technologies Co., Ltd." }, { 0x7604, "O.N. Electronic Co Ltd." }, { 0x7bde, "MIDAC Corporation" }, { 0x7fed, "PowerTV" }, { 0x8008, "Quancom Electronic GmbH" }, { 0x807d, "Asustek Computer, Inc." }, { 0x8086, "Intel Corporation" }, { 0x8088, "Beijing Wangxun Technology Co., Ltd." }, { 0x80ee, "InnoTek Systemberatung GmbH" }, { 0x8322, "Sodick America Corp." }, { 0x8384, "SigmaTel" }, { 0x8401, "TRENDware International Inc." }, { 0x8686, "ScaleMP" }, { 0x8800, "Trigem Computer Inc." }, { 0x8866, "T-Square Design Inc." }, { 0x8888, "Silicon Magic" }, { 0x8912, "TRX" }, { 0x8c4a, "Winbond" }, { 0x8e0e, "Computone Corporation" }, { 0x8e2e, "KTI" }, { 0x9004, "Adaptec" }, { 0x9005, "Adaptec" }, { 0x907f, "Atronics" }, { 0x919a, "Gigapixel Corp" }, { 0x9412, "Holtek" }, { 0x9413, "Softlogic Co., Ltd." }, { 0x9618, "JusonTech Corporation" }, { 0x9699, "Omni Media Technology Inc" }, { 0x9710, "MosChip Semiconductor Technology Ltd." }, { 0x9850, "3Com (wrong ID)" }, { 0x9902, "Stargen Inc." }, { 0x9d32, "Beijing Starblaze Technology Co. Ltd." }, { 0xa0a0, "AOPEN Inc." }, { 0xa0f1, "UNISYS Corporation" }, { 0xa200, "NEC Corporation" }, { 0xa259, "<NAME>" }, { 0xa25b, "Hewlett Packard GmbH PL24-MKT" }, { 0xa304, "Sony" }, { 0xa727, "3Com Corporation" }, { 0xaa00, "iTuner" }, { 0xaa01, "iTuner" }, { 0xaa02, "iTuner" }, { 0xaa03, "iTuner" }, { 0xaa04, "iTuner" }, { 0xaa05, "iTuner" }, { 0xaa06, "iTuner" }, { 0xaa07, "iTuner" }, { 0xaa08, "iTuner" }, { 0xaa09, "iTuner" }, { 0xaa0a, "iTuner" }, { 0xaa0b, "iTuner" }, { 0xaa0c, "iTuner" }, { 0xaa0d, "iTuner" }, { 0xaa0e, "iTuner" }, { 0xaa0f, "iTuner" }, { 0xaa42, "Scitex Digital Video" }, { 0xaa55, "Ncomputing X300 PCI-Engine" }, { 0xaaaa, "Adnaco Technology Inc." }, { 0xabcd, "Vadatech Inc." }, { 0xac1e, "Digital Receiver Technology Inc" }, { 0xac3d, "Actuality Systems" }, { 0xad00, "Alta Data Technologies LLC" }, { 0xaecb, "Adrienne Electronics Corporation" }, { 0xaffe, "Sirrix AG security technologies" }, { 0xb100, "OpenVox Communication Co. Ltd." }, { 0xb10b, "Uakron PCI Project" }, { 0xb1b3, "Shiva Europe Limited" }, { 0xb1d9, "ATCOM Technology co., LTD." }, { 0xbd11, "Pinnacle Systems, Inc. (Wrong ID)" }, { 0xbdbd, "Blackmagic Design" }, { 0xc001, "TSI Telsys" }, { 0xc0a9, "Micron/Crucial Technology" }, { 0xc0de, "Motorola" }, { 0xc0fe, "Motion Engineering, Inc." }, { 0xca3b, "Cambrionix Ltd." }, { 0xca50, "Varian Australia Pty Ltd" }, { 0xcace, "CACE Technologies, Inc." }, { 0xcaed, "Canny Edge" }, { 0xcafe, "Chrysalis-ITS" }, { 0xcc53, "ScaleFlux Inc." }, { 0xcccc, "Catapult Communications" }, { 0xccec, "Curtiss-Wright Controls Embedded Computing" }, { 0xcddd, "Tyzx, Inc." }, { 0xceba, "KEBA AG" }, { 0xd161, "Digium, Inc." }, { 0xd209, "Ultimarc" }, { 0xd4d4, "Dy4 Systems Inc" }, { 0xd531, "I+ME ACTIA GmbH" }, { 0xd84d, "Exsys" }, { 0xdada, "Datapath Limited" }, { 0xdb10, "<NAME>" }, { 0xdc93, "Dawicontrol GmbH" }, { 0xdcba, "Dynamic Engineering" }, { 0xdd01, "Digital Devices GmbH" }, { 0xdead, "Indigita Corporation" }, { 0xdeaf, "Middle Digital Inc." }, { 0xdeda, "XIMEA" }, { 0xe000, "Winbond" }, { 0xe159, "Tiger Jet Network Inc." }, { 0xe1c5, "Elcus" }, { 0xe4bf, "EKF Elektronik GmbH" }, { 0xe4e4, "Xorcom" }, { 0xe55e, "Essence Technology, Inc." }, { 0xea01, "Eagle Technology" }, { 0xea60, "RME" }, { 0xeabb, "Aashima Technology B.V." }, { 0xeace, "Endace Measurement Systems, Ltd" }, { 0xec80, "Belkin Corporation" }, { 0xecc0, "Echo Digital Audio Corporation" }, { 0xedd8, "ARK Logic Inc" }, { 0xf043, "ASUSTeK Computer Inc. (Wrong ID)" }, { 0xf05b, "Foxconn International, Inc. (Wrong ID)" }, { 0xf15e, "SiFive, Inc." }, { 0xf1d0, "AJA Video" }, { 0xf5f5, "F5 Networks, Inc." }, { 0xf849, "ASRock Incorporation (Wrong ID)" }, { 0xfa57, "Interagon AS" }, { 0xfab7, "Fabric7 Systems, Inc." }, { 0xfebd, "Ultraview Corp." }, { 0xfeda, "Broadcom Inc" }, { 0xfede, "Fedetec Inc." }, { 0xfffd, "XenSource, Inc." }, { 0xfffe, "VMWare Inc (temporary ID)" }, { 0xffff, "Illegal Vendor ID" }, }; <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tilck_types as tt from . import tasks class cmd_get_task(gdb.Command): cmd_name = "get-task" def __init__(self): super(cmd_get_task, self).__init__( cmd_get_task.cmd_name, gdb.COMMAND_USER ) def show_usage(self): print("Usage: get-task <tid>") def invoke(self, arg, from_tty): try: tid = int(arg) except: self.show_usage() return task = tasks.get_task(tid) if not task: print("No such task") return gdb.execute("print *(struct task *){}".format(int(task))) class cmd_get_proc(gdb.Command): cmd_name = "get-proc" def __init__(self): super(cmd_get_proc, self).__init__( cmd_get_proc.cmd_name, gdb.COMMAND_USER ) def show_usage(self): print("Use: get-proc <pid>") def invoke(self, arg, from_tty): try: pid = int(arg) except: self.show_usage() return proc = tasks.get_proc(pid) if not proc: print("No such process") return gdb.execute("print *(struct process *){}".format(int(proc))) class cmd_get_handle2(gdb.Command): cmd_name = "get-handle2" def __init__(self): super(cmd_get_handle2, self).__init__( cmd_get_handle2.cmd_name, gdb.COMMAND_USER ) def show_usage(self): print("Use: get-handle2 <pid> <handle_number>") def invoke(self, arg, from_tty): try: pid, hn = arg.split(" ") pid = int(pid) hn = int(hn) except: self.show_usage() return proc = tasks.get_proc(pid) if not proc: print("No such process") return handle = tasks.get_handle(proc, hn) if not handle: print("No such handle") return gdb.execute("print *(struct fs_handle_base *){}".format(int(handle))) class cmd_get_handle(gdb.Command): cmd_name = "get-handle" def __init__(self): super(cmd_get_handle, self).__init__( cmd_get_handle.cmd_name, gdb.COMMAND_USER ) def show_usage(self): print("Use: get-handle <handle_number> # assuming the current process") def invoke(self, arg, from_tty): try: hn = int(arg) except: self.show_usage() return curr = gdb.parse_and_eval("__current->pi") handle = tasks.get_handle(curr, hn) if not handle: print("No such handle") return gdb.execute("print *(struct fs_handle_base *){}".format(int(handle))) class cmd_get_curr(gdb.Command): cmd_name = "get-curr" def __init__(self): super(cmd_get_curr, self).__init__( cmd_get_curr.cmd_name, gdb.COMMAND_USER ) def invoke(self, arg, from_tty): gdb.execute("print *__current") class cmd_get_currp(gdb.Command): cmd_name = "get-currp" def __init__(self): super(cmd_get_currp, self).__init__( cmd_get_currp.cmd_name, gdb.COMMAND_USER ) def invoke(self, arg, from_tty): gdb.execute("print *__current->pi") # ------------------------------------------------------ bu.register_new_custom_gdb_cmd(cmd_get_task) bu.register_new_custom_gdb_cmd(cmd_get_proc) bu.register_new_custom_gdb_cmd(cmd_get_handle2) bu.register_new_custom_gdb_cmd(cmd_get_handle) bu.register_new_custom_gdb_cmd(cmd_get_curr) bu.register_new_custom_gdb_cmd(cmd_get_currp) <file_sep>/******************************************************************************* * * Module Name: rsdumpinfo - Tables used to display resource descriptors. * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acresrc.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME ("rsdumpinfo") #if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DISASSEMBLER) || defined(ACPI_DEBUGGER) #define ACPI_RSD_OFFSET(f) (UINT8) ACPI_OFFSET (ACPI_RESOURCE_DATA,f) #define ACPI_PRT_OFFSET(f) (UINT8) ACPI_OFFSET (ACPI_PCI_ROUTING_TABLE,f) #define ACPI_RSD_TABLE_SIZE(name) (sizeof(name) / sizeof (ACPI_RSDUMP_INFO)) /******************************************************************************* * * Resource Descriptor info tables * * Note: The first table entry must be a Title or Literal and must contain * the table length (number of table entries) * ******************************************************************************/ ACPI_RSDUMP_INFO AcpiRsDumpIrq[7] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpIrq), "IRQ", NULL}, {ACPI_RSD_UINT8 , ACPI_RSD_OFFSET (Irq.DescriptorLength), "Descriptor Length", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Irq.Triggering), "Triggering", AcpiGbl_HeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Irq.Polarity), "Polarity", AcpiGbl_LlDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Irq.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_UINT8 , ACPI_RSD_OFFSET (Irq.InterruptCount), "Interrupt Count", NULL}, {ACPI_RSD_SHORTLIST,ACPI_RSD_OFFSET (Irq.Interrupts[0]), "Interrupt List", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpDma[6] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpDma), "DMA", NULL}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Dma.Type), "Speed", AcpiGbl_TypDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Dma.BusMaster), "Mastering", AcpiGbl_BmDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Dma.Transfer), "Transfer Type", AcpiGbl_SizDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Dma.ChannelCount), "Channel Count", NULL}, {ACPI_RSD_SHORTLIST,ACPI_RSD_OFFSET (Dma.Channels[0]), "Channel List", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpStartDpf[4] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpStartDpf), "Start-Dependent-Functions",NULL}, {ACPI_RSD_UINT8 , ACPI_RSD_OFFSET (StartDpf.DescriptorLength), "Descriptor Length", NULL}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (StartDpf.CompatibilityPriority), "Compatibility Priority", AcpiGbl_ConfigDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (StartDpf.PerformanceRobustness), "Performance/Robustness", AcpiGbl_ConfigDecode} }; ACPI_RSDUMP_INFO AcpiRsDumpEndDpf[1] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpEndDpf), "End-Dependent-Functions", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpIo[6] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpIo), "I/O", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Io.IoDecode), "Address Decoding", AcpiGbl_IoDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Io.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Io.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Io.Alignment), "Alignment", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Io.AddressLength), "Address Length", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpFixedIo[3] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpFixedIo), "Fixed I/O", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (FixedIo.Address), "Address", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (FixedIo.AddressLength), "Address Length", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpVendor[3] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpVendor), "Vendor Specific", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Vendor.ByteLength), "Length", NULL}, {ACPI_RSD_LONGLIST, ACPI_RSD_OFFSET (Vendor.ByteData[0]), "Vendor Data", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpEndTag[1] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpEndTag), "EndTag", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpMemory24[6] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpMemory24), "24-Bit Memory Range", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Memory24.WriteProtect), "Write Protect", AcpiGbl_RwDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Memory24.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Memory24.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Memory24.Alignment), "Alignment", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Memory24.AddressLength), "Address Length", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpMemory32[6] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpMemory32), "32-Bit Memory Range", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Memory32.WriteProtect), "Write Protect", AcpiGbl_RwDecode}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Memory32.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Memory32.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Memory32.Alignment), "Alignment", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Memory32.AddressLength), "Address Length", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpFixedMemory32[4] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpFixedMemory32), "32-Bit Fixed Memory Range",NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (FixedMemory32.WriteProtect), "Write Protect", AcpiGbl_RwDecode}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (FixedMemory32.Address), "Address", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (FixedMemory32.AddressLength), "Address Length", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpAddress16[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpAddress16), "16-Bit WORD Address Space",NULL}, {ACPI_RSD_ADDRESS, 0, NULL, NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Address16.Address.Granularity), "Granularity", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Address16.Address.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Address16.Address.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Address16.Address.TranslationOffset), "Translation Offset", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Address16.Address.AddressLength), "Address Length", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (Address16.ResourceSource), NULL, NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpAddress32[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpAddress32), "32-Bit DWORD Address Space", NULL}, {ACPI_RSD_ADDRESS, 0, NULL, NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Address32.Address.Granularity), "Granularity", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Address32.Address.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Address32.Address.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Address32.Address.TranslationOffset), "Translation Offset", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (Address32.Address.AddressLength), "Address Length", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (Address32.ResourceSource), NULL, NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpAddress64[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpAddress64), "64-Bit QWORD Address Space", NULL}, {ACPI_RSD_ADDRESS, 0, NULL, NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (Address64.Address.Granularity), "Granularity", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (Address64.Address.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (Address64.Address.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (Address64.Address.TranslationOffset), "Translation Offset", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (Address64.Address.AddressLength), "Address Length", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (Address64.ResourceSource), NULL, NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpExtAddress64[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpExtAddress64), "64-Bit Extended Address Space", NULL}, {ACPI_RSD_ADDRESS, 0, NULL, NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.Address.Granularity), "Granularity", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.Address.Minimum), "Address Minimum", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.Address.Maximum), "Address Maximum", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.Address.TranslationOffset), "Translation Offset", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.Address.AddressLength), "Address Length", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (ExtAddress64.TypeSpecific), "Type-Specific Attribute", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpExtIrq[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpExtIrq), "Extended IRQ", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (ExtendedIrq.ProducerConsumer), "Type", AcpiGbl_ConsumeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (ExtendedIrq.Triggering), "Triggering", AcpiGbl_HeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (ExtendedIrq.Polarity), "Polarity", AcpiGbl_LlDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (ExtendedIrq.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (ExtendedIrq.ResourceSource), NULL, NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (ExtendedIrq.InterruptCount), "Interrupt Count", NULL}, {ACPI_RSD_DWORDLIST,ACPI_RSD_OFFSET (ExtendedIrq.Interrupts[0]), "Interrupt List", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpGenericReg[6] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpGenericReg), "Generic Register", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (GenericReg.SpaceId), "Space ID", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (GenericReg.BitWidth), "Bit Width", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (GenericReg.BitOffset), "Bit Offset", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (GenericReg.AccessSize), "Access Size", NULL}, {ACPI_RSD_UINT64, ACPI_RSD_OFFSET (GenericReg.Address), "Address", NULL} }; ACPI_RSDUMP_INFO AcpiRsDumpGpio[16] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpGpio), "GPIO", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Gpio.RevisionId), "RevisionId", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Gpio.ConnectionType), "ConnectionType", AcpiGbl_CtDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Gpio.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (Gpio.PinConfig), "PinConfig", AcpiGbl_PpcDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.IoRestriction), "IoRestriction", AcpiGbl_IorDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Gpio.Triggering), "Triggering", AcpiGbl_HeDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.Polarity), "Polarity", AcpiGbl_LlDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Gpio.DriveStrength), "DriveStrength", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Gpio.DebounceTimeout), "DebounceTimeout", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (Gpio.ResourceSource), "ResourceSource", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Gpio.PinTableLength), "PinTableLength", NULL}, {ACPI_RSD_WORDLIST, ACPI_RSD_OFFSET (Gpio.PinTable), "PinTable", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (Gpio.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (Gpio.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpPinFunction[10] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPinFunction), "PinFunction", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinFunction.RevisionId), "RevisionId", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinFunction.PinConfig), "PinConfig", AcpiGbl_PpcDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinFunction.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinFunction.FunctionNumber), "FunctionNumber", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (PinFunction.ResourceSource), "ResourceSource", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinFunction.PinTableLength), "PinTableLength", NULL}, {ACPI_RSD_WORDLIST, ACPI_RSD_OFFSET (PinFunction.PinTable), "PinTable", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinFunction.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (PinFunction.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpPinConfig[11] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPinConfig), "PinConfig", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinConfig.RevisionId), "RevisionId", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinConfig.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinConfig.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinConfig.PinConfigType), "PinConfigType", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (PinConfig.PinConfigValue), "PinConfigValue", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (PinConfig.ResourceSource), "ResourceSource", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinConfig.PinTableLength), "PinTableLength", NULL}, {ACPI_RSD_WORDLIST, ACPI_RSD_OFFSET (PinConfig.PinTable), "PinTable", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinConfig.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (PinConfig.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpPinGroup[8] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPinGroup), "PinGroup", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinGroup.RevisionId), "RevisionId", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinGroup.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinGroup.PinTableLength), "PinTableLength", NULL}, {ACPI_RSD_WORDLIST, ACPI_RSD_OFFSET (PinGroup.PinTable), "PinTable", NULL}, {ACPI_RSD_LABEL, ACPI_RSD_OFFSET (PinGroup.ResourceLabel), "ResourceLabel", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinGroup.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (PinGroup.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpPinGroupFunction[9] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPinGroupFunction), "PinGroupFunction", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinGroupFunction.RevisionId), "RevisionId", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinGroupFunction.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinGroupFunction.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinGroupFunction.FunctionNumber), "FunctionNumber", NULL}, {ACPI_RSD_SOURCE_LABEL, ACPI_RSD_OFFSET (PinGroupFunction.ResourceSourceLabel), "ResourceSourceLabel", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (PinGroupFunction.ResourceSource), "ResourceSource", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinGroupFunction.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (PinGroupFunction.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpPinGroupConfig[10] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPinGroupConfig), "PinGroupConfig", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinGroupConfig.RevisionId), "RevisionId", NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinGroupConfig.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (PinGroupConfig.Shareable), "Sharing", AcpiGbl_ShrDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (PinGroupConfig.PinConfigType), "PinConfigType", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (PinGroupConfig.PinConfigValue), "PinConfigValue", NULL}, {ACPI_RSD_SOURCE_LABEL, ACPI_RSD_OFFSET (PinGroupConfig.ResourceSourceLabel), "ResourceSourceLabel", NULL}, {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (PinGroupConfig.ResourceSource), "ResourceSource", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (PinGroupConfig.VendorLength), "VendorLength", NULL}, {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (PinGroupConfig.VendorData), "VendorData", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpFixedDma[4] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpFixedDma), "FixedDma", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (FixedDma.RequestLines), "RequestLines", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (FixedDma.Channels), "Channels", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (FixedDma.Width), "TransferWidth", AcpiGbl_DtsDecode}, }; #define ACPI_RS_DUMP_COMMON_SERIAL_BUS \ {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (CommonSerialBus.RevisionId), "RevisionId", NULL}, \ {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (CommonSerialBus.Type), "Type", AcpiGbl_SbtDecode}, \ {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (CommonSerialBus.ProducerConsumer), "ProducerConsumer", AcpiGbl_ConsumeDecode}, \ {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (CommonSerialBus.SlaveMode), "SlaveMode", AcpiGbl_SmDecode}, \ {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (CommonSerialBus.ConnectionSharing),"ConnectionSharing", AcpiGbl_ShrDecode}, \ {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (CommonSerialBus.TypeRevisionId), "TypeRevisionId", NULL}, \ {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (CommonSerialBus.TypeDataLength), "TypeDataLength", NULL}, \ {ACPI_RSD_SOURCE, ACPI_RSD_OFFSET (CommonSerialBus.ResourceSource), "ResourceSource", NULL}, \ {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (CommonSerialBus.VendorLength), "VendorLength", NULL}, \ {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (CommonSerialBus.VendorData), "VendorData", NULL}, ACPI_RSDUMP_INFO AcpiRsDumpCommonSerialBus[11] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpCommonSerialBus), "Common Serial Bus", NULL}, ACPI_RS_DUMP_COMMON_SERIAL_BUS }; ACPI_RSDUMP_INFO AcpiRsDumpI2cSerialBus[14] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpI2cSerialBus), "I2C Serial Bus", NULL}, ACPI_RS_DUMP_COMMON_SERIAL_BUS {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (I2cSerialBus.AccessMode), "AccessMode", AcpiGbl_AmDecode}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (I2cSerialBus.ConnectionSpeed), "ConnectionSpeed", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (I2cSerialBus.SlaveAddress), "SlaveAddress", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpSpiSerialBus[18] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpSpiSerialBus), "Spi Serial Bus", NULL}, ACPI_RS_DUMP_COMMON_SERIAL_BUS {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (SpiSerialBus.WireMode), "WireMode", AcpiGbl_WmDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (SpiSerialBus.DevicePolarity), "DevicePolarity", AcpiGbl_DpDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (SpiSerialBus.DataBitLength), "DataBitLength", NULL}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (SpiSerialBus.ClockPhase), "ClockPhase", AcpiGbl_CphDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (SpiSerialBus.ClockPolarity), "ClockPolarity", AcpiGbl_CpoDecode}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (SpiSerialBus.DeviceSelection), "DeviceSelection", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (SpiSerialBus.ConnectionSpeed), "ConnectionSpeed", NULL}, }; ACPI_RSDUMP_INFO AcpiRsDumpUartSerialBus[20] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpUartSerialBus), "Uart Serial Bus", NULL}, ACPI_RS_DUMP_COMMON_SERIAL_BUS {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.FlowControl), "FlowControl", AcpiGbl_FcDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.StopBits), "StopBits", AcpiGbl_SbDecode}, {ACPI_RSD_3BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.DataBits), "DataBits", AcpiGbl_BpbDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.Endian), "Endian", AcpiGbl_EdDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (UartSerialBus.Parity), "Parity", AcpiGbl_PtDecode}, {ACPI_RSD_UINT8, ACPI_RSD_OFFSET (UartSerialBus.LinesEnabled), "LinesEnabled", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (UartSerialBus.RxFifoSize), "RxFifoSize", NULL}, {ACPI_RSD_UINT16, ACPI_RSD_OFFSET (UartSerialBus.TxFifoSize), "TxFifoSize", NULL}, {ACPI_RSD_UINT32, ACPI_RSD_OFFSET (UartSerialBus.DefaultBaudRate), "ConnectionSpeed", NULL}, }; /* * Tables used for common address descriptor flag fields */ ACPI_RSDUMP_INFO AcpiRsDumpGeneralFlags[5] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpGeneralFlags), NULL, NULL}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.ProducerConsumer), "Consumer/Producer", AcpiGbl_ConsumeDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.Decode), "Address Decode", AcpiGbl_DecDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.MinAddressFixed), "Min Relocatability", AcpiGbl_MinDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.MaxAddressFixed), "Max Relocatability", AcpiGbl_MaxDecode} }; ACPI_RSDUMP_INFO AcpiRsDumpMemoryFlags[5] = { {ACPI_RSD_LITERAL, ACPI_RSD_TABLE_SIZE (AcpiRsDumpMemoryFlags), "Resource Type", (void *) "Memory Range"}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.Info.Mem.WriteProtect), "Write Protect", AcpiGbl_RwDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Address.Info.Mem.Caching), "Caching", AcpiGbl_MemDecode}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Address.Info.Mem.RangeType), "Range Type", AcpiGbl_MtpDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.Info.Mem.Translation), "Translation", AcpiGbl_TtpDecode} }; ACPI_RSDUMP_INFO AcpiRsDumpIoFlags[4] = { {ACPI_RSD_LITERAL, ACPI_RSD_TABLE_SIZE (AcpiRsDumpIoFlags), "Resource Type", (void *) "I/O Range"}, {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Address.Info.Io.RangeType), "Range Type", AcpiGbl_RngDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.Info.Io.Translation), "Translation", AcpiGbl_TtpDecode}, {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Address.Info.Io.TranslationType), "Translation Type", AcpiGbl_TrsDecode} }; /* * Table used to dump _PRT contents */ ACPI_RSDUMP_INFO AcpiRsDumpPrt[5] = { {ACPI_RSD_TITLE, ACPI_RSD_TABLE_SIZE (AcpiRsDumpPrt), NULL, NULL}, {ACPI_RSD_UINT64, ACPI_PRT_OFFSET (Address), "Address", NULL}, {ACPI_RSD_UINT32, ACPI_PRT_OFFSET (Pin), "Pin", NULL}, {ACPI_RSD_STRING, ACPI_PRT_OFFSET (Source[0]), "Source", NULL}, {ACPI_RSD_UINT32, ACPI_PRT_OFFSET (SourceIndex), "Source Index", NULL} }; #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> void on_first_pdir_update(void) { /* DO NOTHING, AT THE MOMENT */ } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/process.h> #include <linux/major.h> // system header #include "tty_int.h" int get_curr_proc_tty_term_type(void) { struct tty *t = get_curr_proc()->proc_tty; return (int)t->tparams.type; } struct tty *get_curr_process_tty(void) { return get_curr_proc()->proc_tty; } static ssize_t ttyaux_read(fs_handle h, char *buf, size_t size, offt *pos) { ASSERT(*pos == 0); return tty_read_int(get_curr_process_tty(), h, buf, size); } static ssize_t ttyaux_write(fs_handle h, char *buf, size_t size, offt *pos) { ASSERT(*pos == 0); return tty_write_int(get_curr_process_tty(), h, buf, size); } static int ttyaux_ioctl(fs_handle h, ulong request, void *argp) { return tty_ioctl_int(get_curr_process_tty(), h, request, argp); } static struct kcond *ttyaux_get_rready_cond(fs_handle h) { return &get_curr_process_tty()->input_cond; } static int ttyaux_read_ready(fs_handle h) { return tty_read_ready_int(get_curr_process_tty(), h); } static int ttyaux_create_device_file(int minor, enum vfs_entry_type *type, struct devfs_file_info *nfo) { static const struct file_ops static_ops_ttyaux = { .read = ttyaux_read, .write = ttyaux_write, .ioctl = ttyaux_ioctl, .get_rready_cond = ttyaux_get_rready_cond, .read_ready = ttyaux_read_ready, }; *type = VFS_CHAR_DEV; nfo->fops = &static_ops_ttyaux; nfo->create_extra = &tty_create_extra; nfo->destroy_extra = &tty_destroy_extra; nfo->on_dup_extra = &tty_on_dup_extra; return 0; } /* * Creates the special /dev/tty file which redirects the tty_* funcs to the * tty that was current when the process was created. */ void init_ttyaux(void) { struct driver_info *di = kzalloc_obj(struct driver_info); if (!di) panic("TTY: no enough memory for struct driver_info"); di->name = "ttyaux"; di->create_dev_file = ttyaux_create_device_file; register_driver(di, TTYAUX_MAJOR); tty_create_devfile_or_panic("tty", TTYAUX_MAJOR, 0, NULL); tty_create_devfile_or_panic("console", TTYAUX_MAJOR, 1, NULL); } <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tilck_types as tt def get_all_tasks(): tasks = [] root = gdb.lookup_symbol("tree_by_tid_root")[0] def walk(tasks_list, task): if not task: return tasks_list.append(task) left = task['tree_by_tid_node']['left_obj'].cast(tt.task_p) right = task['tree_by_tid_node']['right_obj'].cast(tt.task_p) walk(tasks_list, left) walk(tasks_list, right) walk(tasks, root.value()) tasks = sorted(tasks, key = lambda t: int(t['tid'])) return tasks def get_children_list(proc): return bu.get_list_elems( proc['children'].address, # pointer to list object tt.task, # container type "siblings_node" # container's list node member name ) def get_task(tid): tasks = get_all_tasks() for t in tasks: task_tid = int(t['tid']) if task_tid == tid: return t return None def get_proc(pid): tasks = get_all_tasks() for t in tasks: pi = t['pi'] if pi['pid'] == pid: return pi return None def get_handles(proc): handles_list = [] handles = proc['handles'] for i in range(bu.config.MAX_HANDLES): if handles[i]: handles_list.append(i) return handles_list def get_handle(proc, n): if n not in range(0, bu.config.MAX_HANDLES): return None return proc['handles'][n].cast(tt.fs_handle_base_p) def get_handle_num(proc, handle_obj_ptr): handles = proc['handles'] for i in range(bu.config.MAX_HANDLES): if handles[i] == handle_obj_ptr: return i return None <file_sep> #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/hal.h> /* Internal stuff (used by process.c, process32.c, misc.c, sched.c, fork.c) */ extern char *kernel_initial_stack[KERNEL_STACK_SIZE]; void switch_to_initial_kernel_stack(void); void free_common_task_allocs(struct task *ti); void process_free_mappings_info(struct process *pi); static ALWAYS_INLINE void set_curr_task(struct task *ti) { extern struct task *__current; #ifndef UNIT_TEST_ENVIRONMENT DEBUG_ONLY(check_not_in_irq_handler()); ASSERT(!are_interrupts_enabled()); #endif __current = ti; } <file_sep>#!/usr/bin/env bash if [ ! -f $1 ]; then dd status=none if=/dev/zero of=$1 bs=1M count=$2 fi <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_kb8042.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/debug_utils.h> #include <tilck/mods/acpi.h> NORETURN void poweroff(void) { printk("Halting the system...\n"); if (MOD_acpi) { if (get_acpi_init_status() >= ais_subsystem_enabled) { acpi_poweroff(); } } disable_interrupts_forced(); /* * We get here if one of the following statements is true: * * - No acpi module * - The acpi initialization failed * - The acpi poweroff procedure failed * * Therefore, try the qemu debug power off method, if we're running on a * hypervisor. */ if (in_hypervisor()) debug_qemu_turn_off_machine(); /* * Eveything failed. Just print a message confirming that's safe to turn off * the machine. */ printk("System halted.\n"); while (true) { halt(); } } /* Reboot the machine, using the best method available */ NORETURN void reboot(void) { printk("Rebooting the machine...\n"); disable_interrupts_forced(); if (MOD_acpi && !in_panic()) { if (get_acpi_init_status() >= ais_subsystem_enabled) { acpi_reboot(); } } /* * We get here if one of the following statements is true: * * - No acpi module * - The acpi initialization failed * - The acpi reboot procedure failed * * Therefore, try the legacy i8042 reset. */ if (MOD_kb8042) i8042_reboot(); panic("Unable to reboot the machine"); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * WARNING: despite the name, safe_ringbuf is not SAFE in every use pattern. * Read at the documentation in the header file: safe_ringbuf.h. */ extern "C" { #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/atomics.h> #include <tilck/kernel/safe_ringbuf.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/hal.h> } #include <tilck/common/cpputils.h> static ALWAYS_INLINE bool rb_stat_is_empty(struct generic_safe_ringbuf_stat *s) { return s->read_pos == s->write_pos && !s->full; } bool safe_ringbuf_is_empty(struct safe_ringbuf *rb) { bool res; ulong var; disable_interrupts(&var); { res = rb_stat_is_empty(&rb->s); } enable_interrupts(&var); return res; } bool safe_ringbuf_is_full(struct safe_ringbuf *rb) { struct generic_safe_ringbuf_stat cs; cs.__raw = atomic_load_explicit(&rb->s.raw, mo_relaxed); return cs.full; } static ALWAYS_INLINE void begin_debug_write_checks(struct safe_ringbuf *rb) { DEBUG_ONLY(atomic_fetch_add_explicit(&rb->nested_writes, 1, mo_relaxed)); } static ALWAYS_INLINE void end_debug_write_checks(struct safe_ringbuf *rb) { DEBUG_ONLY(atomic_fetch_sub_explicit(&rb->nested_writes, 1, mo_relaxed)); } static ALWAYS_INLINE void begin_debug_read_checks(struct safe_ringbuf *rb) { #if DEBUG_CHECKS int nw = atomic_load_explicit(&rb->nested_writes, mo_relaxed); if (nw) panic("Read from safe_ringbuf interrupted on-going write. Not supported"); #endif } static ALWAYS_INLINE void end_debug_read_checks(struct safe_ringbuf *rb) { /* Do nothing, at the moment */ } extern "C" { void safe_ringbuf_init(struct safe_ringbuf *rb, u16 max_elems, u16 e_size, void *buf) { ASSERT(max_elems <= 32768); rb->max_elems = max_elems; rb->elem_size = e_size; rb->buf = (u8 *)buf; rb->s.raw = 0; #if DEBUG_CHECKS rb->nested_writes = 0; #endif } void safe_ringbuf_destory(struct safe_ringbuf *rb) { bzero(rb, sizeof(struct safe_ringbuf)); } } // extern "C" template <int static_elem_size = 0> static ALWAYS_INLINE bool __safe_ringbuf_write(struct safe_ringbuf *rb, void *elem_ptr, bool *was_empty) { typedef typename unsigned_by_size<static_elem_size>::type T; struct generic_safe_ringbuf_stat cs, ns; const u16 e_size = rb->elem_size; bool ret = true; begin_debug_write_checks(rb); do { cs.__raw = rb->s.__raw; ns.__raw = rb->s.__raw; if (UNLIKELY(cs.full)) { *was_empty = false; ret = false; goto out; } ns.write_pos = (ns.write_pos + 1) % rb->max_elems; if (ns.write_pos == ns.read_pos) ns.full = true; } while (!atomic_cas_weak(&rb->s.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); if (static_elem_size) ((T *)rb->buf)[cs.write_pos] = *(T *)elem_ptr; else memcpy(rb->buf + cs.write_pos * e_size, elem_ptr, e_size); *was_empty = rb_stat_is_empty(&cs); out: end_debug_write_checks(rb); return ret; } template <int static_elem_size = 0> static ALWAYS_INLINE bool __safe_ringbuf_read(struct safe_ringbuf *rb, void *elem_ptr /* out */) { typedef typename unsigned_by_size<static_elem_size>::type T; struct generic_safe_ringbuf_stat cs, ns; const u16 e_size = rb->elem_size; bool ret = true; if (static_elem_size) ASSERT(rb->elem_size == static_elem_size); begin_debug_read_checks(rb); do { cs.__raw = rb->s.__raw; ns.__raw = rb->s.__raw; if (rb_stat_is_empty(&cs)) { ret = false; goto out; } if (static_elem_size) *(T *)elem_ptr = ((T *)rb->buf)[cs.read_pos]; else memcpy(elem_ptr, rb->buf + cs.read_pos * e_size, e_size); ns.read_pos = (ns.read_pos + 1) % rb->max_elems; ns.full = false; } while (!atomic_cas_weak(&rb->s.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); out: end_debug_read_checks(rb); return ret; } extern "C" { bool safe_ringbuf_write_elem(struct safe_ringbuf *rb, void *e, bool *was_empty) { return __safe_ringbuf_write<>(rb, e, was_empty); } bool safe_ringbuf_read_elem(struct safe_ringbuf *rb, void *elem_ptr /* out */) { return __safe_ringbuf_read<>(rb, elem_ptr); } #define INST_WRITE_FUNC(s, n) \ bool safe_ringbuf_write_##s(struct safe_ringbuf *rb, void *e, bool *empty) {\ return __safe_ringbuf_write<n>(rb, e, empty); \ } #define INST_READ_FUNC(s, n) \ bool safe_ringbuf_read_##s(struct safe_ringbuf *rb, void *elem_ptr) { \ return __safe_ringbuf_read<n>(rb, elem_ptr); \ } // For the moment, the following instantiations are NOT needed in Tilck. // No point in adding code-bloat to the kernel. As a use-cases come out, // un-comment the individual functions. // INST_WRITE_FUNC(ulong, sizeof(void *)) INST_WRITE_FUNC(1, 1) // INST_WRITE_FUNC(2, 2) // INST_WRITE_FUNC(4, 4) // INST_WRITE_FUNC(8, 8) // INST_READ_FUNC(ulong, sizeof(void *)) INST_READ_FUNC(1, 1) // INST_READ_FUNC(2, 2) // INST_READ_FUNC(4, 4) // INST_READ_FUNC(8, 8) } // extern "C" <file_sep># SPDX-License-Identifier: BSD-2-Clause import os import sys from .lang_aux import Const, ReloadAsConstModule def env_bool(x): return Const(os.environ.get(x, '0') == '1') def env_int(x, val): return Const(int(os.environ.get(x, str(val)))) VM_MEMORY_SIZE_IN_MB = env_int('TILCK_VM_MEM', 128) GEN_TEST_DATA = env_bool('GEN_TEST_DATA') IN_TRAVIS = env_bool('TRAVIS') IN_CIRCLECI = env_bool('CIRCLECI') IN_AZURE = env_bool('AZURE_HTTP_USER_AGENT') CI = env_bool('CI') DUMP_COV = env_bool('DUMP_COV') REPORT_COV = env_bool('REPORT_COV') VERBOSE = env_bool('VERBOSE') IN_ANY_CI = Const(IN_TRAVIS.val or IN_CIRCLECI.val or IN_AZURE.val or CI.val) ReloadAsConstModule(__name__) <file_sep>#!/usr/bin/env bash if ! git --version &> /dev/null; then echo "<unknown commit>" exit 0 fi set -e ver=`git rev-parse --short=8 HEAD` commit_date=`git --no-pager log -1 --format="%ai"` if [[ $(git diff --stat) != '' ]]; then echo "dirty:$ver $commit_date" else tags="" for x in `git tag --points-at HEAD`; do tags="$tags$x," done if [[ "$tags" != "" ]]; then # Prepend "tags:" tags="tags:$tags" # Drop the trailing "," tags=$(echo $tags | sed 's/.$//') fi echo "$ver $commit_date $tags" fi <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_global.h> #include <tilck/common/arch/generic_x86/asm_consts.h> #if KERNEL_STACK_PAGES == 1 #define ASM_KERNEL_STACK_SZ 4096 #elif KERNEL_STACK_PAGES == 2 #define ASM_KERNEL_STACK_SZ 8192 #elif KERNEL_STACK_PAGES == 4 #define ASM_KERNEL_STACK_SZ 16384 #else #error Unsupported value of KERNEL_STACK_PAGES #endif #define REGS_FL_FPU_ENABLED 8 /* Some useful asm macros */ #ifdef ASM_FILE #define NBITS 64 #define FUNC(x) .type x, @function; x #define END_FUNC(x) .size x, .-(x) #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define __TILCK_PANIC_H__ NORETURN void panic(const char *fmt, ...); NORETURN void not_reached(const char *file, int line); NORETURN void not_implemented(const char *file, int line); static ALWAYS_INLINE bool in_panic(void) { extern volatile bool __in_panic; return __in_panic; } static ALWAYS_INLINE bool in_panic_debugger(void) { extern volatile bool __in_panic_debugger; return __in_panic_debugger; } static ALWAYS_INLINE bool in_kernel_shutdown(void) { extern volatile bool __in_kernel_shutdown; return __in_kernel_shutdown; } #ifndef NDEBUG #define DEBUG_ONLY(x) x #define DEBUG_ONLY_UNSAFE(x) x #define DEBUG_CHECKED_SUCCESS(x) \ do { \ bool __checked_success = x; \ ASSERT(__checked_success); \ } while (0) /* NO_TEST_ASSERT is like ASSERT(x) but it's ignored in unit tests */ #ifndef UNIT_TEST_ENVIRONMENT #define NO_TEST_ASSERT(x) ASSERT(x) #else #define NO_TEST_ASSERT(x) do { /* nothing */ } while (0) #endif #else #define DEBUG_ONLY_UNSAFE(x) /* expand to nothing */ #define DEBUG_ONLY(x) do { /* nothing */ } while (0) #define NO_TEST_ASSERT(x) do { /* nothing */ } while (0) #define DEBUG_CHECKED_SUCCESS(x) x #endif /* VERIFY is like ASSERT, but it's always enabled */ #define VERIFY(x) \ do { \ if (UNLIKELY(!(x))) { \ assert_failed(#x , __FILE__, __LINE__); \ } \ } while (0) #define NOT_REACHED() not_reached(__FILE__, __LINE__) #define NOT_IMPLEMENTED() not_implemented(__FILE__, __LINE__) #ifndef NO_TILCK_ASSERT #include <tilck/common/assert.h> #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_console.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/term.h> #include <tilck/kernel/kb.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/cmdline.h> #include <termios.h> // system header #include <fcntl.h> // system header #include <linux/kd.h> // system header #include "tty_int.h" static void tty_inbuf_write_elem(struct tty *t, u8 c, bool block); static void tty_keypress_echo(struct tty *t, char c); #include "tty_ctrl_handlers.c.h" static void tty_keypress_echo(struct tty *t, char c) { struct termios *const c_term = &t->c_term; if (t->serial_port_fwd) return; if (t->kd_gfx_mode == KD_GRAPHICS) return; if (c == '\n' && (c_term->c_lflag & ECHONL)) { /* * From termios' man page: * * ECHONL: If ICANON is also set, echo the NL character even if ECHO * is not set. */ t->tintf->write(t->tstate, &c, 1, t->curr_color); return; } if (!(c_term->c_lflag & ECHO)) { /* If ECHO is not enabled, just don't echo. */ return; } /* echo is enabled */ if (c_term->c_lflag & ICANON) { if (c == c_term->c_cc[VEOF]) { /* In canonical mode, EOF is never echoed */ return; } if (c_term->c_lflag & ECHOK) { if (c == c_term->c_cc[VKILL]) { t->tintf->write(t->tstate, &c, 1, t->curr_color); return; } } if (c_term->c_lflag & ECHOE) { /* * From termios' man page: * * ECHOE * If ICANON is also set, the ERASE character erases the * preceding input character, and WERASE erases the preceding * word. */ if (c == c_term->c_cc[VWERASE] || c == c_term->c_cc[VERASE]) { t->tintf->write(t->tstate, &c, 1, t->curr_color); return; } } } /* * From termios' man page: * * ECHOCTL * (not in POSIX) If ECHO is also set, terminal special * characters other than TAB, NL, START, and STOP are echoed as ^X, * where X is the character with ASCII code 0x40 greater than the * special character. For example, character 0x08 (BS) is echoed * as ^H. * */ if ((c < ' ' || c == 0x7F) && (c_term->c_lflag & ECHOCTL)) { if (c != '\t' && c != '\n') { if (c != c_term->c_cc[VSTART] && c != c_term->c_cc[VSTOP]) { char mini_buf[2] = { '^', c + 0x40 }; t->tintf->write(t->tstate, mini_buf, 2, t->curr_color); return; } } } /* Just ECHO a regular character */ t->tintf->write(t->tstate, &c, 1, t->curr_color); } static inline bool tty_inbuf_is_empty(struct tty *t) { bool ret; disable_preemption(); { ret = ringbuf_is_empty(&t->input_ringbuf); } enable_preemption(); return ret; } void tty_inbuf_reset(struct tty *t) { disable_preemption(); { ringbuf_reset(&t->input_ringbuf); t->end_line_delim_count = 0; } enable_preemption(); } static inline u8 tty_inbuf_read_elem(struct tty *t) { u8 ret = 0; disable_preemption(); { ASSERT(!tty_inbuf_is_empty(t)); DEBUG_CHECKED_SUCCESS(ringbuf_read_elem1(&t->input_ringbuf, &ret)); kcond_signal_all(&t->output_cond); } enable_preemption(); return ret; } static inline bool tty_inbuf_drop_last_written_elem(struct tty *t) { bool ret; tty_keypress_echo(t, (char)t->c_term.c_cc[VERASE]); disable_preemption(); { ret = ringbuf_unwrite_elem(&t->input_ringbuf, NULL); } enable_preemption(); return ret; } static void tty_inbuf_write_elem(struct tty *t, u8 c, bool block) { ASSERT(in_panic() || !block || is_preemption_enabled()); bool ok; while (true) { disable_preemption(); { ok = ringbuf_write_elem1(&t->input_ringbuf, c); } enable_preemption(); if (LIKELY(ok)) { /* Everything is fine, we wrote the `c` in the ringbuf */ tty_keypress_echo(t, (char)c); break; } /* Oops, our buffer is full. And now what? */ if (!block) { /* We cannot block, discard the data! */ break; } /* OK, signal all consumers waiting for input (tty_read()) */ kcond_signal_all(&t->input_cond); /* Now, block on the `output_cond` waiting for a consumer to signal us */ kcond_wait(&t->output_cond, NULL, TIME_SLICE_TICKS); } } static int tty_handle_non_printable_key(struct kb_dev *kb, struct tty *t, u32 key, bool block) { char seq[16]; const u8 modifiers = kb_get_current_modifiers(kb); const bool found = kb->scancode_to_ansi_seq(key, modifiers, seq); const char *p = seq; if (!found) { /* Unknown/unsupported sequence: just do nothing avoiding weird effects */ return kb_handler_nak; } while (*p) { tty_inbuf_write_elem(t, (u8) *p++, block); } if (!(t->c_term.c_lflag & ICANON)) kcond_signal_one(&t->input_cond); return kb_handler_ok_and_continue; } static inline bool tty_is_line_delim_char(struct tty *t, u8 c) { return c == '\n' || c == t->c_term.c_cc[VEOF] || c == t->c_term.c_cc[VEOL] || c == t->c_term.c_cc[VEOL2]; } static void tty_keypress_handle_canon_mode(struct tty *t, u32 key, u8 c, bool block) { if (c == t->c_term.c_cc[VERASE]) { tty_inbuf_drop_last_written_elem(t); } else { tty_inbuf_write_elem(t, c, block); if (tty_is_line_delim_char(t, c)) { t->end_line_delim_count++; kcond_signal_one(&t->input_cond); } } } void tty_send_keyevent(struct tty *t, struct key_event ke, bool block) { u8 c = (u8)ke.print_char; if (c == '\r') { if (t->c_term.c_iflag & IGNCR) return; /* ignore the carriage return */ if (t->c_term.c_iflag & ICRNL) c = '\n'; } else if (c == '\n') { if (t->c_term.c_iflag & INLCR) c = '\r'; } /* Ctrl+C, Ctrl+D, Ctrl+Z etc.*/ if (tty_handle_special_controls(t, c, block)) return; if (t->c_term.c_lflag & ICANON) { tty_keypress_handle_canon_mode(t, ke.key, c, block); return; } /* raw mode input handling */ tty_inbuf_write_elem(t, c, block); kcond_signal_one(&t->input_cond); return; } static int tty_keypress_handler_int(struct tty *t, struct kb_dev *kb, struct key_event ke) { u8 c = (u8)ke.print_char; ASSERT(kb != NULL); if (!c) return tty_handle_non_printable_key(kb, t, ke.key, false); if (kb_is_alt_pressed(kb)) tty_inbuf_write_elem(t, '\e', false); if (kb_is_ctrl_pressed(kb)) { if (isalpha(c) || c == '\\' || c == '[') { /* ctrl ignores the case of the letter */ c = (u8)(toupper(c) - 'A' + 1); } } ke.print_char = (char)c; tty_send_keyevent(t, ke, false); return kb_handler_ok_and_continue; } int set_curr_tty(struct tty *t) { int res = -EPERM; disable_preemption(); { if (__curr_tty->kd_gfx_mode == KD_TEXT) { __curr_tty = t; if (t->tintf->get_type() == term_type_video) set_curr_video_term(t->tstate); res = 0; } } enable_preemption(); return res; } enum kb_handler_action tty_keypress_handler(struct kb_dev *kb, struct key_event ke) { struct tty *const t = get_curr_tty(); const u32 key = ke.key; if (t->mediumraw_mode) { const u8 mr = kb->translate_to_mediumraw(ke); if (!mr) { /* * For any reason, we don't have a MEDIUMRAW translation for that key. * Just ignore the key press/release, that's it. */ return kb_handler_ok_and_stop; } tty_inbuf_write_elem(t, mr, false); kcond_signal_one(&t->input_cond); return kb_handler_ok_and_stop; } if (!ke.pressed) return kb_handler_nak; if (key == KEY_PAGE_UP && kb_is_shift_pressed(kb)) { t->tintf->scroll_up(t->tstate, TERM_SCROLL_LINES); return kb_handler_ok_and_stop; } if (key == KEY_PAGE_DOWN && kb_is_shift_pressed(kb)) { t->tintf->scroll_down(t->tstate, TERM_SCROLL_LINES); return kb_handler_ok_and_stop; } if (kb_is_alt_pressed(kb)) { struct tty *other_tty; int fn = kb_get_fn_key_pressed(key); if (fn > 0 && t->kd_gfx_mode == KD_TEXT) { if (fn > kopt_ttys) return kb_handler_ok_and_stop; /* just ignore the key stroke */ other_tty = ttys[fn]; if (other_tty == t) return kb_handler_ok_and_stop; /* just ignore the key stroke */ ASSERT(other_tty != NULL); set_curr_tty(other_tty); return kb_handler_ok_and_stop; } } return tty_keypress_handler_int(t, kb, ke); } static size_t tty_flush_read_buf(struct devfs_handle *h, char *buf, size_t size) { struct tty_handle_extra *eh = (void *)&h->extra; offt rem = eh->read_buf_used - eh->read_pos; ASSERT(rem >= 0); size_t m = MIN((size_t)rem, size); memcpy(buf, eh->read_buf + eh->read_pos, m); eh->read_pos += m; if (eh->read_pos == eh->read_buf_used) { eh->read_buf_used = 0; eh->read_pos = 0; } return m; } /* * Returns: * - TRUE when caller's read loop should continue * - FALSE when caller's read loop should STOP */ static bool tty_internal_read_single_char_from_kb(struct tty *t, struct devfs_handle *h, bool *delim_break) { struct tty_handle_extra *eh = (void *)&h->extra; u8 c = tty_inbuf_read_elem(t); eh->read_buf[eh->read_buf_used++] = (char)c; if (t->c_term.c_lflag & ICANON) { if (tty_is_line_delim_char(t, c)) { ASSERT(t->end_line_delim_count > 0); t->end_line_delim_count--; *delim_break = true; /* All line delimiters except EOF are kept */ if (c == t->c_term.c_cc[VEOF]) eh->read_buf_used--; } return !*delim_break; } /* * In raw mode it makes no sense to read until a line delim is * found: we should read the minimum necessary. */ return !(eh->read_buf_used >= t->c_term.c_cc[VMIN]); } static inline bool tty_internal_should_read_return(struct tty *t, struct devfs_handle *h, size_t read_cnt, bool delim_break) { struct tty_handle_extra *eh = (void *)&h->extra; if (t->c_term.c_lflag & ICANON) { return delim_break || (t->end_line_delim_count > 0 && (eh->read_buf_used == TTY_READ_BS || read_cnt == TTY_INPUT_BS)); } /* Raw mode handling */ return read_cnt >= t->c_term.c_cc[VMIN]; } bool tty_read_ready_int(struct tty *t, struct devfs_handle *h) { struct tty_handle_extra *eh = (void *)&h->extra; if (t->c_term.c_lflag & ICANON) { return eh->read_allowed_to_return || t->end_line_delim_count > 0; } /* Raw mode handling */ return ringbuf_get_elems(&t->input_ringbuf) >= t->c_term.c_cc[VMIN]; } ssize_t tty_read_int(struct tty *t, struct devfs_handle *h, char *buf, size_t size) { struct tty_handle_extra *eh = (void *)&h->extra; struct process *pi = get_curr_proc(); size_t read_count = 0; bool delim_break; ASSERT(is_preemption_enabled()); if (!t->serial_port_fwd && !in_panic()) { if (pi->proc_tty != t) { /* * Cannot read from this TTY, as it's a video TTY (not serial) and it's * not the process' controlling terminal. */ return -EIO; } if (pi->pgid != t->fg_pgid) { /* * Cannot read from TTY, as the process is not in the terminal's * foreground process group. */ return -EIO; } } if (!size) return 0; if (eh->read_buf_used) { if (!(h->fl_flags & O_NONBLOCK)) return (ssize_t) tty_flush_read_buf(h, buf, size); /* * The file description is in NON-BLOCKING mode: this means we cannot * just return the buffer to the user even if there is something left in * it because the tty might be in canonical mode (and we're not sure the * user pressed ENTER). Therefore, we have to check an additional flag * called read_allowed_to_return that is set if the user actually pressed * ENTER (precisely: a line delimiter has been written to the tty). In * the BLOCKING mode case (default), we can, instead, actually flush the * buffer and return because read_buf_used > 0 means just that user's * buffer was just not big enough. */ if (eh->read_allowed_to_return) { ssize_t ret = (ssize_t) tty_flush_read_buf(h, buf, size); if (!eh->read_buf_used) eh->read_allowed_to_return = false; return ret; } } if (t->c_term.c_lflag & ICANON) t->tintf->set_col_offset(t->tstate, -1 /* current col */); eh->read_allowed_to_return = false; do { if ((h->fl_flags & O_NONBLOCK) && tty_inbuf_is_empty(t)) return -EAGAIN; while (tty_inbuf_is_empty(t)) { kcond_wait(&t->input_cond, NULL, KCOND_WAIT_FOREVER); if (pending_signals()) return -EINTR; } delim_break = false; if (!(h->fl_flags & O_NONBLOCK)) { ASSERT(eh->read_buf_used == 0); ASSERT(eh->read_pos == 0); } while (!tty_inbuf_is_empty(t) && eh->read_buf_used < TTY_READ_BS && tty_internal_read_single_char_from_kb(t, h, &delim_break)) { } if (!(h->fl_flags & O_NONBLOCK) || !(t->c_term.c_lflag & ICANON)) read_count += tty_flush_read_buf(h, buf+read_count, size-read_count); ASSERT(t->end_line_delim_count >= 0); } while (!tty_internal_should_read_return(t, h, read_count, delim_break)); if (h->fl_flags & O_NONBLOCK) { /* * If we got here in NONBLOCK mode, that means we exited the loop properly * with tty_internal_should_read_return() returning true. Now we have to * flush the read buffer. */ read_count += tty_flush_read_buf(h, buf+read_count, size-read_count); if (eh->read_buf_used) eh->read_allowed_to_return = true; } return (ssize_t) read_count; } void tty_update_ctrl_handlers(struct tty *t) { bzero(t->ctrl_handlers, 256 * sizeof(tty_ctrl_sig_func)); tty_set_ctrl_handler(t, VSTOP, tty_ctrl_stop); tty_set_ctrl_handler(t, VSTART, tty_ctrl_start); tty_set_ctrl_handler(t, VINTR, tty_ctrl_intr); tty_set_ctrl_handler(t, VSUSP, tty_ctrl_susp); tty_set_ctrl_handler(t, VQUIT, tty_ctrl_quit); tty_set_ctrl_handler(t, VEOF, tty_ctrl_eof); tty_set_ctrl_handler(t, VEOL, tty_ctrl_eol); tty_set_ctrl_handler(t, VEOL2, tty_ctrl_eol2); tty_set_ctrl_handler(t, VREPRINT, tty_ctrl_reprint); tty_set_ctrl_handler(t, VDISCARD, tty_ctrl_discard); tty_set_ctrl_handler(t, VLNEXT, tty_ctrl_lnext); } void tty_input_init(struct tty *t) { kcond_init(&t->output_cond); kcond_init(&t->input_cond); ringbuf_init(&t->input_ringbuf, TTY_INPUT_BS, 1, t->input_buf); tty_update_ctrl_handlers(t); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once void fat_dump_info(void *fatpart_begin); <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error import sys import re # Add Tilck's "other/" directory to our import path and import base_utils sys.path.append("@CMAKE_SOURCE_DIR@/other") import gdb_scripts.base_utils as bu # Set the build config as early as possible using the constants coming from # CMake (this file gets pre-processed by CMake) bu.set_build_config( bu.BuildConfig( "@CMAKE_SOURCE_DIR@", int("@MAX_HANDLES@"), int("@KERNEL_BASE_VA@", 16), ) ) # Import the rest of our gdb_scripts import gdb_scripts.list_cmds import gdb_scripts.get_cmds import gdb_scripts.process_printer import gdb_scripts.task_printer import gdb_scripts.regs_printer import gdb_scripts.mobj_printer import gdb_scripts.fs_handle_printer import gdb_scripts.mi_printer # Init all the custom GDB commands bu.init_all_custom_cmds() # Register all the regex pretty printers gdb.printing.register_pretty_printer( gdb.current_objfile(), bu.regex_pretty_printers ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> /* * x86 IDT entry flags: * * +-----------------+--------------+-----------+--------------------+ * | Present [1 bit] | DPL [2 bits] | S [1 bit] | Gate type [4 bits] | * +-----------------+--------------+-----------+--------------------+ * * Difference between an interrupt gate and a trap gate: for interrupt gates, * interrupts are automatically disabled and eflags is saved (iret restores * it as well). * * DPL: the minimum level the current descriptor should have to call this gate. * This allow kernel to prevent user mode to trigger interrupts, simulating * hardware interrupts or faults. In order to "int 0x80" to work, it needs to * have, indeed, DPL = 3. */ #define IDT_FLAG_INT_GATE (0xE << 0) /* 32 bit interrupt gate */ #define IDT_FLAG_TRAP_GATE (0xF << 0) /* 32 bit trap gate */ #define IDT_FLAG_TASK_GATE (0x5 << 0) /* 32 bit task gate */ #define IDT_FLAG_DPL0 (0 << 5) #define IDT_FLAG_DPL1 (1 << 5) #define IDT_FLAG_DPL2 (2 << 5) #define IDT_FLAG_DPL3 (3 << 5) #define IDT_FLAG_PRESENT (1 << 7) struct idt_entry { u16 offset_low; u16 selector; u8 always0; u8 flags; u16 offset_high; } PACKED; void load_idt(struct idt_entry *entries, u16 entries_count); void idt_set_entry(u8 num, void *handler, u16 selector, u8 flags); <file_sep>#!/usr/bin/env ruby def prnthelp puts "Hello sir, what would you like to do?" puts "1: dir" puts "2: exit" end def loop prnthelp case gets.chomp.to_i when 1 then puts "you chose dir!" when 2 then puts "you chose exit!" exit end loop end loop <file_sep>#!/bin/bash AR="@CMAKE_AR@" RANLIB="@CMAKE_RANLIB@" OBJCOPY="@CMAKE_OBJCOPY@" ELFHACK_PREFIX="@CMAKE_BINARY_DIR@/scripts/build_apps/elfhack" ARCH_GTESTS="@ARCH_GTESTS@" ARCH_BITS="@ARCH_BITS@" HOST_ARCH_BITS="@HOST_ARCH_BITS@" ROOT="@CMAKE_SOURCE_DIR@" QUIET=1 source $ROOT/scripts/bash_includes/script_utils if [[ $ARCH_GTESTS == OFF || $ARCH_GTESTS == false || $ARCH_GTEST == 0 ]]; then ELFHACK=${ELFHACK_PREFIX}${HOST_ARCH_BITS} else ELFHACK=${ELFHACK_PREFIX}${ARCH_BITS} fi if printf "" &> /dev/null; then has_printf=1 fi PREFIX="${GREEN}[ WS ]${RATTRS} " if [ -z "$1" ]; then >&2 echo -e "${PREFIX}Expected archive file" exit 1 fi if ! [ -f "$1" ]; then >&2 echo -e "${PREFIX}The file '$1' does not exist" exit 1 fi file=$(realpath $1) shift TEMPDIR=$(mktemp -d -p .) if ! [ -d $TEMPDIR ]; then >&2 echo -e "${PREFIX}Failed to create temp directory" exit 1 fi pushd $TEMPDIR &> /dev/null echo -e "${PREFIX}Extract all object files from archive $(basename $file)..." last_obj="" count=1 for obj in `ar t $file | sort`; do if [[ "$obj" != "$last_obj" ]]; then count=1 else count=$((count + 1)) fi $AR xoN $count $file $obj mv $obj $obj.$count.o last_obj=$obj done echo -e "${PREFIX}Patch all the object files..." for obj in *; do unset obj_syms_map declare -A obj_syms_map list=$($ELFHACK $obj --list-text-syms) for x in $list; do obj_syms_map[$x]=1 done for sym in "$@"; do if [[ ${obj_syms_map[$sym]} != 1 ]]; then continue; fi addr=$($ELFHACK $obj --get-text-sym $sym) sobj=${obj::-4} if [[ $has_printf == 1 ]]; then printf "${PREFIX}Weaken sym ${GREEN}%-35s${RATTRS} in %s\n" $sym $sobj else echo "${PREFIX}Weaken sym ${sym} in $sobj" fi $OBJCOPY $obj \ --add-symbol __real_$sym=.text:$addr,function,global \ --globalize-symbol=$sym \ --weaken-symbol=$sym \ done done echo -e "${PREFIX}Re-create the archive file $(basename $file)..." rm $file $AR qc $file *.o $RANLIB $file popd &> /dev/null rm -rf $TEMPDIR echo -e "${PREFIX}Done" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/fs/flock.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/user.h> #include <tilck/kernel/debug_utils.h> #include <dirent.h> // system header #include "../fs_int.h" #include "vfs_mp.c.h" #include "vfs_locking.c.h" #include "vfs_resolve.c.h" #include "vfs_getdents.c.h" #include "vfs_op_ready.c.h" static u32 next_device_id; /* ------------ handle-based functions ------------- */ void vfs_close(fs_handle h) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct process *pi = get_curr_proc(); struct fs_handle_base *hb = h; struct mnt_fs *fs = hb->fs; struct locked_file *lf = hb->lf; const struct fs_ops *fsops = fs->fsops; if (!pi->vforked) remove_all_mappings_of_handle(pi, h); if (fsops->on_close) fsops->on_close(h); if (fsops->release_inode(fs, fsops->get_inode(h)) == 0) { if (fsops->on_close_last_handle) fsops->on_close_last_handle(h); } vfs_free_handle(h); if (lf) release_subsys_flock(lf); release_obj(fs); /* the minimum ref-count that a mounted fs can have is 1 */ ASSERT(get_ref_count(fs) > 0); } /* * Note: because of the way file handles are allocated on Tilck, dup() can * fail with -ENOMEM, while on POSIX systems that is not allowed. * * TODO: fix the file-handles allocation mechanism in order to make impossible * dup() failing with -ENOMEM, by substantially pre-allocating the memory for * the file handle objects. */ int vfs_dup(fs_handle h, fs_handle *dup_h) { ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; const struct fs_ops *fsops = hb->fs->fsops; struct fs_handle_base *new_handle; int rc; if (!hb) return -EBADF; if (!(new_handle = vfs_alloc_handle_raw())) return -ENOMEM; memcpy32(new_handle, h, MAX_FS_HANDLE_SIZE / 4); fsops->retain_inode(hb->fs, fsops->get_inode(h)); if (fsops->on_dup_cb) { if ((rc = fsops->on_dup_cb(new_handle))) { fsops->release_inode(hb->fs, fsops->get_inode(h)); vfs_free_handle(new_handle); return rc; } } *dup_h = new_handle; /* The new file descriptor does NOT share old file descriptor's fd_flags */ new_handle->fd_flags = 0; /* Check that the locked_file object (if any) is still the same */ ASSERT(new_handle->lf == hb->lf); /* Retain locked_file object (if any) */ if (hb->lf) retain_subsys_flock(hb->lf); retain_obj(hb->fs); return 0; } ssize_t vfs_read(fs_handle h, void *buf, size_t buf_size) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->read) return -EBADF; if ((hb->fl_flags & O_WRONLY) && !(hb->fl_flags & O_RDWR)) return -EBADF; /* file not opened for reading */ return hb->fops->read(h, buf, buf_size, &hb->h_fpos); } ssize_t vfs_write(fs_handle h, void *buf, size_t buf_size) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->write) return -EBADF; if (!(hb->fl_flags & (O_WRONLY | O_RDWR))) return -EBADF; /* file not opened for writing */ return hb->fops->write(h, buf, buf_size, &hb->h_fpos); } ssize_t vfs_pread(fs_handle h, void *buf, size_t buf_size, offt off) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->read) return -EBADF; if ((hb->fl_flags & O_WRONLY) && !(hb->fl_flags & O_RDWR)) return -EBADF; /* file not opened for reading */ return hb->fops->read(h, buf, buf_size, &off); } ssize_t vfs_pwrite(fs_handle h, void *buf, size_t buf_size, offt off) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->write) return -EBADF; if (!(hb->fl_flags & (O_WRONLY | O_RDWR))) return -EBADF; /* file not opened for writing */ return hb->fops->write(h, buf, buf_size, &off); } offt vfs_seek(fs_handle h, offt off, int whence) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) return -EINVAL; /* Tilck does NOT support SEEK_DATA and SEEK_HOLE */ struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->seek) return -ESPIPE; return hb->fops->seek(h, off, whence); } int vfs_ioctl(fs_handle h, ulong request, void *argp) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; if (!hb->fops->ioctl) return -ENOTTY; // Yes, ENOTTY *IS* the right error. See the man page. return hb->fops->ioctl(h, request, argp); } int vfs_ftruncate(fs_handle h, offt length) { struct fs_handle_base *hb = (struct fs_handle_base *) h; const struct fs_ops *fsops = hb->fs->fsops; if (!fsops->truncate) return -EROFS; return fsops->truncate(hb->fs, fsops->get_inode(h), length); } int vfs_fstat64(fs_handle h, struct k_stat64 *statbuf) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(h != NULL); struct fs_handle_base *hb = (struct fs_handle_base *) h; struct mnt_fs *fs = hb->fs; const struct fs_ops *fsops = fs->fsops; return fsops->stat(fs, fsops->get_inode(h), statbuf); } int vfs_fsync(fs_handle h) { struct fs_handle_base *hb = h; int rc = 0; ASSERT(is_preemption_enabled()); if (~hb->fs->flags & VFS_FS_RW) return -EROFS; if (hb->fops->sync) rc = hb->fops->sync(h); return rc; } int vfs_fdatasync(fs_handle h) { struct fs_handle_base *hb = h; int rc = 0; ASSERT(is_preemption_enabled()); if (~hb->fs->flags & VFS_FS_RW) return -EROFS; if (hb->fops->datasync) rc = hb->fops->datasync(h); else if (hb->fops->sync) rc = hb->fops->sync(h); return rc; } /* ----------- path-based functions -------------- */ typedef int (*vfs_func_impl)(struct mnt_fs *, struct vfs_path *, ulong, ulong, ulong); static ALWAYS_INLINE int __vfs_path_funcs_wrapper(const char *path, bool exlock, bool res_last_sl, vfs_func_impl func, ulong a1, ulong a2, ulong a3) { struct vfs_path p; int rc; NO_TEST_ASSERT(is_preemption_enabled()); if ((rc = vfs_resolve(path, &p, exlock, res_last_sl)) < 0) return rc; ASSERT(p.fs != NULL); rc = func(p.fs, &p, a1, a2, a3); vfs_smart_fs_unlock(p.fs, exlock); release_obj(p.fs); return rc; } #define vfs_path_funcs_wrapper(path, exlock, rsl, func, a1, a2, a3) \ __vfs_path_funcs_wrapper(path, \ exlock, \ rsl, \ (vfs_func_impl)(void *)func, \ (ulong)a1, (ulong)a2, (ulong)a3) static ALWAYS_INLINE int vfs_open_impl(struct mnt_fs *fs, struct vfs_path *p, fs_handle *out, int flags, mode_t mode) { const enum vfs_entry_type type = p->fs_path.type; int rc; if (flags & O_DIRECTORY) { if (type != VFS_DIR) return -ENOTDIR; } if ((rc = fs->fsops->open(p, out, flags, mode))) return rc; { struct fs_handle_base *hb = *out; /* open() succeeded, the FS is already retained */ hb->fl_flags = flags; if (flags & O_CLOEXEC) hb->fd_flags |= FD_CLOEXEC; if (type == VFS_FILE && (fs->flags & VFS_FS_RW)) { if (flags & (O_WRONLY | O_RDWR)) { if (~hb->spec_flags & VFS_SPFL_NO_LF) ASSERT(hb->lf != NULL); } } } /* file handles retain their struct mnt_fs */ retain_obj(fs); return 0; } int vfs_open(const char *path, fs_handle *out, int flags, mode_t mode) { return vfs_path_funcs_wrapper( path, true, /* exlock */ true, /* res_last_sl */ &vfs_open_impl, out, flags, mode ); } static ALWAYS_INLINE int vfs_stat64_impl(struct mnt_fs *fs, struct vfs_path *p, struct k_stat64 *statbuf, bool res_last_sl, ulong unused1) { if (!p->fs_path.inode) return -ENOENT; return fs->fsops->stat(fs, p->fs_path.inode, statbuf); } int vfs_stat64(const char *path, struct k_stat64 *statbuf, bool res_last_sl) { return vfs_path_funcs_wrapper( path, false, /* exlock */ res_last_sl, /* res_last_sl */ &vfs_stat64_impl, statbuf, res_last_sl, 0 ); } static ALWAYS_INLINE int vfs_mkdir_impl(struct mnt_fs *fs, struct vfs_path *p, mode_t mode, ulong x, ulong y) { if (!fs->fsops->mkdir) return -EPERM; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (p->fs_path.inode) return -EEXIST; return fs->fsops->mkdir(p, mode); } int vfs_mkdir(const char *path, mode_t mode) { return vfs_path_funcs_wrapper( path, true, /* exlock */ false, /* res_last_sl */ vfs_mkdir_impl, mode, 0, 0 ); } static ALWAYS_INLINE int vfs_rmdir_impl(struct mnt_fs *fs, struct vfs_path *p, ulong u1, ulong u2, ulong u3) { if (!fs->fsops->rmdir) return -EPERM; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (!p->fs_path.inode) return -ENOENT; return fs->fsops->rmdir(p); } int vfs_rmdir(const char *path) { return vfs_path_funcs_wrapper( path, true, /* exlock */ false, /* res_last_sl */ vfs_rmdir_impl, 0, 0, 0 ); } static ALWAYS_INLINE int vfs_unlink_impl(struct mnt_fs *fs, struct vfs_path *p, ulong u1, ulong u2, ulong u3) { if (!fs->fsops->unlink) return -EPERM; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (!p->fs_path.inode) return -ENOENT; return fs->fsops->unlink(p); } int vfs_unlink(const char *path) { return vfs_path_funcs_wrapper( path, true, /* exlock */ false, /* res_last_sl */ vfs_unlink_impl, 0, 0, 0 ); } static ALWAYS_INLINE int vfs_truncate_impl(struct mnt_fs *fs, struct vfs_path *p, offt len, ulong x, ulong y) { struct locked_file *lf = NULL; int rc; if (!fs->fsops->truncate) return -EROFS; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (!p->fs_path.inode) return -ENOENT; rc = acquire_subsys_flock(fs, p->fs_path.inode, SUBSYS_VFS, &lf); if (rc) return rc; /* We couldn't acquire the lock */ /* Got the lock, great. Now do truncate the file */ rc = fs->fsops->truncate(fs, p->fs_path.inode, len); /* Release the lock */ release_subsys_flock(lf); return rc; } int vfs_truncate(const char *path, offt len) { return vfs_path_funcs_wrapper( path, false, /* exlock */ true, /* res_last_sl */ vfs_truncate_impl, len, 0, 0 ); } static ALWAYS_INLINE int vfs_symlink_impl(struct mnt_fs *fs, struct vfs_path *p, const char *target, ulong u1, ulong u2) { if (!fs->fsops->symlink) return -EPERM; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (p->fs_path.inode) return -EEXIST; /* the linkpath already exists! */ return fs->fsops->symlink(target, p); } int vfs_symlink(const char *target, const char *linkpath) { return vfs_path_funcs_wrapper( linkpath, true, /* exlock */ false, /* res_last_sl */ vfs_symlink_impl, target, 0, 0 ); } static ALWAYS_INLINE int vfs_readlink_impl(struct mnt_fs *fs, struct vfs_path *p, char *buf, ulong u1, ulong u2) { if (!fs->fsops->readlink) { /* * If there's no readlink(), symlinks are not supported by the FS, ergo * the last component of `path` cannot be referring to a symlink. */ return -EINVAL; } if (!p->fs_path.inode) return -ENOENT; return fs->fsops->readlink(p, buf); } /* NOTE: `buf` is guaranteed to have room for at least MAX_PATH chars */ int vfs_readlink(const char *path, char *buf) { return vfs_path_funcs_wrapper( path, false, /* exlock */ false, /* res_last_sl */ vfs_readlink_impl, buf, 0, 0 ); } static ALWAYS_INLINE int vfs_chown_impl(struct mnt_fs *fs, struct vfs_path *p, int owner, int group, bool reslink) { return (owner == 0 && group == 0) ? 0 : -EPERM; } int vfs_chown(const char *path, int owner, int group, bool reslink) { return vfs_path_funcs_wrapper( path, false, /* exlock */ reslink, /* res_last_sl */ vfs_chown_impl, owner, group, reslink ); } static ALWAYS_INLINE int vfs_chmod_impl(struct mnt_fs *fs, struct vfs_path *p, mode_t mode) { if (!fs->fsops->chmod) return -EPERM; if (!(fs->flags & VFS_FS_RW)) return -EROFS; if (!p->fs_path.inode) return -ENOENT; return fs->fsops->chmod(fs, p->fs_path.inode, mode); } int vfs_chmod(const char *path, mode_t mode) { return vfs_path_funcs_wrapper( path, false, /* exlock */ true, /* res_last_sl */ vfs_chmod_impl, mode, 0, 0 ); } static ALWAYS_INLINE int vfs_utimens_impl(struct mnt_fs *fs, struct vfs_path *p, const struct k_timespec64 ts[2]) { if (!fs->fsops->futimens) return -EROFS; if (!p->fs_path.inode) return -ENOENT; return fs->fsops->futimens(fs, p->fs_path.inode, ts); } int vfs_utimens(const char *path, const struct k_timespec64 times[2]) { return vfs_path_funcs_wrapper( path, true, /* exlock */ true, /* res_last_sl */ vfs_utimens_impl, times, 0, 0 ); } static int vfs_rename_or_link(const char *oldpath, const char *newpath, func_2paths (*get_func_ptr)(struct mnt_fs *)) { struct mnt_fs *fs; func_2paths func; struct vfs_path oldp, newp; int rc; NO_TEST_ASSERT(is_preemption_enabled()); /* First, just resolve the old path using a shared lock */ if ((rc = vfs_resolve(oldpath, &oldp, false, false)) < 0) return rc; ASSERT(oldp.fs != NULL); fs = oldp.fs; if (!oldp.fs_path.inode) { /* The old path does not exist */ vfs_smart_fs_unlock(fs, false); release_obj(fs); return -ENOENT; } /* Everything was fine: now retain the file and release the lock */ vfs_retain_inode_at(&oldp); vfs_smart_fs_unlock(fs, false); /* Now, resolve the new path grabbing an exclusive lock */ if ((rc = vfs_resolve(newpath, &newp, true, false)) < 0) { /* * Oops, something when wrong: release the oldpath's inode and fs. * Note: no need for release anything about the new path since the func * already does that in the error cases. */ vfs_release_inode_at(&oldp); release_obj(fs); return rc; } ASSERT(newp.fs != NULL); /* * OK, now we're at a crucial point: check if the two files belong to the * same struct mnt_fs. */ if (newp.fs != fs) { /* * They do *not* belong to the same fs. It's impossible to continue. * We have to release: the exlock and the retain count of the new * fs plus the retain count of old's inode and its struct mnt_fs. */ vfs_smart_fs_unlock(newp.fs, true); release_obj(newp.fs); vfs_release_inode_at(&oldp); release_obj(fs); return -EXDEV; } /* * Great! They *do* belong to the same fs. Now we have to just release one * fs retain count and the old inode's retain count as well. */ release_obj(fs); vfs_release_inode_at(&oldp); /* note: we're still holding an exlock on fs */ /* Finally, we can call struct mnt_fs's func (if any) */ func = get_func_ptr(fs); rc = func ? fs->flags & VFS_FS_RW ? func(fs, &oldp, &newp) : -EROFS /* read-only struct mnt_fs */ : -EPERM; /* not supported */ /* We're done, release fs's exlock and its retain count */ vfs_smart_fs_unlock(fs, true); release_obj(fs); return rc; } static ALWAYS_INLINE func_2paths vfs_get_rename_func(struct mnt_fs *fs) { return fs->fsops->rename; } static ALWAYS_INLINE func_2paths vfs_get_link_func(struct mnt_fs *fs) { return fs->fsops->link; } int vfs_rename(const char *oldpath, const char *newpath) { return vfs_rename_or_link(oldpath, newpath, &vfs_get_rename_func); } int vfs_link(const char *oldpath, const char *newpath) { return vfs_rename_or_link(oldpath, newpath, &vfs_get_link_func); } int vfs_fchmod(fs_handle h, mode_t mode) { struct fs_handle_base *hb = h; const struct fs_ops *fsops = hb->fs->fsops; return fsops->chmod(hb->fs, fsops->get_inode(h), mode); } int vfs_mmap(struct user_mapping *um, pdir_t *pdir, int flags) { struct fs_handle_base *hb = um->h; const struct file_ops *fops = hb->fops; if (!fops->mmap) return -ENODEV; ASSERT(fops->munmap != NULL); return fops->mmap(um, pdir, flags); } int vfs_munmap(struct user_mapping *um, void *vaddr, size_t len) { struct fs_handle_base *hb = um->h; const struct file_ops *fops = hb->fops; if (!fops->munmap) return -ENODEV; ASSERT(fops->mmap != NULL); return fops->munmap(um, vaddr, len); } bool vfs_handle_fault(struct user_mapping *um, void *va, bool p, bool rw) { struct fs_handle_base *hb = um->h; const struct file_ops *fops = hb->fops; if (!fops->handle_fault) return false; return fops->handle_fault(um, va, p, rw); } int vfs_futimens(fs_handle h, const struct k_timespec64 times[2]) { struct fs_handle_base *hb = h; const struct fs_ops *fsops = hb->fs->fsops; if (!fsops->futimens) return -EROFS; return fsops->futimens(hb->fs, fsops->get_inode(h), times); } ssize_t vfs_readv(fs_handle h, const struct iovec *iov, int iovcnt) { struct fs_handle_base *hb = h; struct task *curr = get_curr_task(); ssize_t ret = 0; ssize_t rc; size_t len; if (hb->fops->readv) return hb->fops->readv(h, iov, iovcnt); /* * readv() is not implemented in the file system: implement here it in a * generic but non-atomic way. There's nothing more we can do. Also, the * POSIX standard does not require readv() to be atomic: * * https://pubs.opengroup.org/onlinepubs/9699919799/ * * Note: Linux's man page claims that readv/writev must be atomic: that's * possible now because all of the Linux file systems support internally the * scatter/gather I/O. On Tilck, not all the file systems will support it. */ for (int i = 0; i < iovcnt; i++) { len = MIN(iov[i].iov_len, IO_COPYBUF_SIZE); rc = vfs_read(h, curr->io_copybuf, len); if (rc < 0) { ret = rc; break; } if (copy_to_user(iov[i].iov_base, curr->io_copybuf, len)) return -EFAULT; ret += rc; if (rc < (ssize_t)iov[i].iov_len) break; // Not enough data to fill all the user buffers. } return ret; } ssize_t vfs_writev(fs_handle h, const struct iovec *iov, int iovcnt) { struct fs_handle_base *hb = h; struct task *curr = get_curr_task(); ssize_t ret = 0; ssize_t rc; size_t len; if (hb->fops->writev) return hb->fops->writev(h, iov, iovcnt); /* * writev() is not implemented in the file system: implement here it in a * generic but non-atomic way. There's nothing more we can do. Also, the * POSIX standard does not require writev() to be atomic: * * https://pubs.opengroup.org/onlinepubs/9699919799/ * * Note: Linux's man page claims that readv/writev must be atomic: that's * possible now because all of the Linux file systems support internally the * scatter/gather I/O. On Tilck, not all the file systems will support it. */ for (int i = 0; i < iovcnt; i++) { len = MIN(iov[i].iov_len, IO_COPYBUF_SIZE); if (copy_from_user(curr->io_copybuf, iov[i].iov_base, len)) return -EFAULT; rc = vfs_write(h, curr->io_copybuf, len); if (rc < 0) { ret = rc; break; } ret += rc; if (rc < (ssize_t)iov[i].iov_len) { // For some reason (perfectly legit) we couldn't write the whole // user data (i.e. network card's buffers are full). break; } } return ret; } u32 vfs_get_new_device_id(void) { return next_device_id++; } struct mnt_fs * create_fs_obj(const char *type, const struct fs_ops *fsops, void *device_data, u32 flags) { struct mnt_fs *fs = kzalloc_obj(struct mnt_fs); if (!fs) return NULL; fs->pss_lock_root = NULL; fs->fs_type_name = type; fs->fsops = fsops; fs->device_data = device_data; fs->flags = flags; fs->device_id = vfs_get_new_device_id(); return fs; } void destory_fs_obj(struct mnt_fs *fs) { ASSERT(!fs->pss_lock_root); kfree_obj(fs, struct mnt_fs); } int vfs_exlock_noblock(struct mnt_fs *fs, vfs_inode_ptr_t i) { int rc; if (!(fs->flags & VFS_FS_RW)) return 0; /* always succeed for read-only mounted filesystems */ if (!fs->fsops->exlock_noblk) { /* Make sure its counterpart function neither exists */ ASSERT(!fs->fsops->exunlock); return -ENOLCK; } /* Make sure its counterpart function do exists as well */ ASSERT(fs->fsops->exunlock != NULL); /* Retain the fs, the inode and finally try to grab the exlock */ retain_obj(fs); vfs_retain_inode(fs, i); rc = fs->fsops->exlock_noblk(fs, i); if (rc != 0) { /* error case: we must release the inode and the fs obj */ vfs_release_inode(fs, i); release_obj(fs); } return rc; } int vfs_exunlock(struct mnt_fs *fs, vfs_inode_ptr_t i) { int rc; if (!(fs->flags & VFS_FS_RW)) return 0; /* always succeed for read-only mounted filesystems */ if (!fs->fsops->exunlock) { /* Make sure its counterpart function neither exists */ ASSERT(!fs->fsops->exlock_noblk); return -ENOLCK; } /* Make sure its counterpart function do exists as well */ ASSERT(fs->fsops->exlock_noblk != NULL); rc = fs->fsops->exunlock(fs, i); if (!rc) { /* success case: release the inode and the fs obj */ vfs_release_inode(fs, i); release_obj(fs); } return rc; } #define PANIC_HANDLES 4 static char panic_handles[PANIC_HANDLES][MAX_FS_HANDLE_SIZE] ALIGNED_AT(MAX_FS_HANDLE_SIZE); static bool panic_handles_used[PANIC_HANDLES]; fs_handle vfs_alloc_handle_raw(void) { if (UNLIKELY(in_panic())) { for (int i = 0; i < PANIC_HANDLES; i++) { if (!panic_handles_used[i]) { panic_handles_used[i] = true; return panic_handles[i]; } } return NULL; } return kmalloc(MAX_FS_HANDLE_SIZE); } void vfs_free_handle(fs_handle h) { if (UNLIKELY(in_panic())) { for (int i = 0; i < PANIC_HANDLES; i++) { if (&panic_handles[i] == h) { panic_handles_used[i] = false; break; } } return; } kfree2(h, MAX_FS_HANDLE_SIZE); } fs_handle vfs_alloc_handle(void) { fs_handle h = vfs_alloc_handle_raw(); if (h) bzero(h, MAX_FS_HANDLE_SIZE); return h; } fs_handle vfs_create_new_handle(struct mnt_fs *fs, const struct file_ops *fops) { struct fs_handle_base *hb = vfs_alloc_handle(); if (!hb) return NULL; hb->pi = get_curr_proc(); hb->fs = fs; hb->fops = fops; return hb; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) if (ARCH_GTESTS) set_cross_compiler_gtests() else() set(TOOL_GCOV "${GCOV}") endif() include_directories(${CMAKE_SOURCE_DIR}) include_directories(${CMAKE_SOURCE_DIR}/include) include_directories(${CMAKE_SOURCE_DIR}/include/system_headers) include_directories(${GTEST_SOURCE_DIR}/include) include_directories(${GMOCK_SOURCE_DIR}/include) # Create a static library target for kernel's arch-independent code. add_library( kernel_for_test STATIC EXCLUDE_FROM_ALL ${KERNEL_NOARCH_SOURCES} ${CMAKE_SOURCE_DIR}/other/mock_experiments.c ) set_target_properties( kernel_for_test PROPERTIES COMPILE_FLAGS "${KERNEL_NO_ARCH_FLAGS}" ) set(LIB_KERNEL "libkernel_test_patched.a") add_custom_command( OUTPUT ${LIB_KERNEL} COMMAND cp libkernel_for_test.a ${LIB_KERNEL} COMMAND ${TOOL_WS} ${LIB_KERNEL} ${WRAPPED_SYMS} DEPENDS kernel_for_test ${TOOL_WS} elfhack32 elfhack64 COMMENT "Patching the kernel archive to allow wrapping of symbols in the same TU" VERBATIM ) add_custom_target( kernel_test_patched DEPENDS ${LIB_KERNEL} ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/generate_coverage_report ${CMAKE_BINARY_DIR}/scripts/generate_test_coverage_report ) if (${HOST_ARCH_FAMILY} STREQUAL "generic_x86") file( GLOB SOURCES "*.c" "*.cpp" "${CMAKE_SOURCE_DIR}/common/3rd_party/datetime.c" "${CMAKE_SOURCE_DIR}/common/arch/${ARCH_FAMILY}/*.c" ) else() file( GLOB SOURCES "*.c" "*.cpp" "${CMAKE_SOURCE_DIR}/common/3rd_party/datetime.c" ) endif() # Override CMake's default executable output directory set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}) add_executable(gtests EXCLUDE_FROM_ALL ${SOURCES}) add_dependencies(gtests kernel_test_patched) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-register") set(GTESTS_FLAGS_LIST "") list( APPEND GTESTS_FLAGS_LIST -DTESTING -fPIC -fno-strict-aliasing ${CLANG_OPTS} ${COMMON_FLAGS} ${GCOV_COMPILE_FLAGS} -Wno-format-security ) JOIN("${GTESTS_FLAGS_LIST}" ${SPACE} GTESTS_FLAGS) set_target_properties( gtests PROPERTIES COMPILE_FLAGS "${GTESTS_FLAGS}" LINK_FLAGS "${GCOV_LINK_FLAGS}" ) target_link_libraries(gtests ${GTEST_TC_BUILD_DIR}/lib/libgtest.a) target_link_libraries(gtests ${GTEST_TC_BUILD_DIR}/lib/libgtest_main.a) target_link_libraries(gtests ${GMOCK_TC_BUILD_DIR}/lib/libgmock.a) target_link_libraries(gtests ${GMOCK_TC_BUILD_DIR}/lib/libgmock_main.a) target_link_libraries(gtests pthread) target_link_libraries(gtests ${CMAKE_CURRENT_BINARY_DIR}/${LIB_KERNEL}) build_all_modules(gtests "_noarch" TRUE) target_link_libraries(gtests ${CMAKE_CURRENT_BINARY_DIR}/${LIB_KERNEL}) <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause MICROPYTHON_VER="1.13-tilck" function download_micropython { local ver="$MICROPYTHON_VER" local tarname="micropython-$ver.tgz" local url="https://github.com/vvaltchev/micropython.git" download_git_repo_in_cache "$url" v$ver $tarname micropython extract_cachefile_tar_gz $tarname -- } if [[ $HOST_ARCH == "i386" ]] || [[ $HOST_ARCH == "x86_64" ]]; then all_funcs_list+=(build_micropython) fi function build_micropython { if [[ $HOST_ARCH != "i386" ]] && [[ $HOST_ARCH != "x86_64" ]]; then echo "ERROR: HOST_ARCH=$HOST_ARCH not supported" return fi pushd $ARCH if ! [ -d micropython ]; then show_work_on_component_msg "MICROPYTHON" reset_cc_vars download_micropython cd micropython if [[ "$HOST_ARCH" != "$BUILD_ARCH" ]]; then # Case HOST_ARCH == ARCH # Note: if HOST_ARCH not in [BUILD_ARCH, ARCH], we fail earlier. # # Note: NOT TESTED yet. # Remember: this scenario (building on $ARCH) is _not_ officially # supported. export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" else # Default case set_cc_vars_to_tc export CROSS_COMPILE="${ARCH_GCC_TC}-linux-" fi export LDFLAGS_EXTRA="-static" local opts="MICROPY_PY_FFI=0 MICROPY_PY_THREAD=0" pushd mpy-cross run_command2 "make $opts -j$BUILD_PAR" build.log popd pushd ports/unix run_command2 "make submodules" make_submodules.log run_command2 "make $opts -j$BUILD_PAR" build.log popd export LDFLAGS_EXTRA="" export CROSS_COMPILE="" else show_skip_component_msg "MICROPYTHON" fi popd } function build_micropython_installed_status { if [ -d $TC/$ARCH/micropython ]; then if [ -f $TC/$ARCH/micropython/ports/unix/micropython ]; then echo "installed $ARCH" fi fi } <file_sep>/****************************************************************************** * * Module Name: exmisc - ACPI AML (p-code) execution - specific opcodes * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlcode.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exmisc") /******************************************************************************* * * FUNCTION: AcpiExGetObjectReference * * PARAMETERS: ObjDesc - Create a reference to this object * ReturnDesc - Where to store the reference * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Obtain and return a "reference" to the target object * Common code for the RefOfOp and the CondRefOfOp. * ******************************************************************************/ ACPI_STATUS AcpiExGetObjectReference ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ReturnDesc, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *ReferenceObj; ACPI_OPERAND_OBJECT *ReferencedObj; ACPI_FUNCTION_TRACE_PTR (ExGetObjectReference, ObjDesc); *ReturnDesc = NULL; switch (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc)) { case ACPI_DESC_TYPE_OPERAND: if (ObjDesc->Common.Type != ACPI_TYPE_LOCAL_REFERENCE) { return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* * Must be a reference to a Local or Arg */ switch (ObjDesc->Reference.Class) { case ACPI_REFCLASS_LOCAL: case ACPI_REFCLASS_ARG: case ACPI_REFCLASS_DEBUG: /* The referenced object is the pseudo-node for the local/arg */ ReferencedObj = ObjDesc->Reference.Object; break; default: ACPI_ERROR ((AE_INFO, "Invalid Reference Class 0x%2.2X", ObjDesc->Reference.Class)); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } break; case ACPI_DESC_TYPE_NAMED: /* * A named reference that has already been resolved to a Node */ ReferencedObj = ObjDesc; break; default: ACPI_ERROR ((AE_INFO, "Invalid descriptor type 0x%X", ACPI_GET_DESCRIPTOR_TYPE (ObjDesc))); return_ACPI_STATUS (AE_TYPE); } /* Create a new reference object */ ReferenceObj = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_REFERENCE); if (!ReferenceObj) { return_ACPI_STATUS (AE_NO_MEMORY); } ReferenceObj->Reference.Class = ACPI_REFCLASS_REFOF; ReferenceObj->Reference.Object = ReferencedObj; *ReturnDesc = ReferenceObj; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Object %p Type [%s], returning Reference %p\n", ObjDesc, AcpiUtGetObjectTypeName (ObjDesc), *ReturnDesc)); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExDoMathOp * * PARAMETERS: Opcode - AML opcode * Integer0 - Integer operand #0 * Integer1 - Integer operand #1 * * RETURN: Integer result of the operation * * DESCRIPTION: Execute a math AML opcode. The purpose of having all of the * math functions here is to prevent a lot of pointer dereferencing * to obtain the operands. * ******************************************************************************/ UINT64 AcpiExDoMathOp ( UINT16 Opcode, UINT64 Integer0, UINT64 Integer1) { ACPI_FUNCTION_ENTRY (); switch (Opcode) { case AML_ADD_OP: /* Add (Integer0, Integer1, Result) */ return (Integer0 + Integer1); case AML_BIT_AND_OP: /* And (Integer0, Integer1, Result) */ return (Integer0 & Integer1); case AML_BIT_NAND_OP: /* NAnd (Integer0, Integer1, Result) */ return (~(Integer0 & Integer1)); case AML_BIT_OR_OP: /* Or (Integer0, Integer1, Result) */ return (Integer0 | Integer1); case AML_BIT_NOR_OP: /* NOr (Integer0, Integer1, Result) */ return (~(Integer0 | Integer1)); case AML_BIT_XOR_OP: /* XOr (Integer0, Integer1, Result) */ return (Integer0 ^ Integer1); case AML_MULTIPLY_OP: /* Multiply (Integer0, Integer1, Result) */ return (Integer0 * Integer1); case AML_SHIFT_LEFT_OP: /* ShiftLeft (Operand, ShiftCount, Result)*/ /* * We need to check if the shiftcount is larger than the integer bit * width since the behavior of this is not well-defined in the C language. */ if (Integer1 >= AcpiGbl_IntegerBitWidth) { return (0); } return (Integer0 << Integer1); case AML_SHIFT_RIGHT_OP: /* ShiftRight (Operand, ShiftCount, Result) */ /* * We need to check if the shiftcount is larger than the integer bit * width since the behavior of this is not well-defined in the C language. */ if (Integer1 >= AcpiGbl_IntegerBitWidth) { return (0); } return (Integer0 >> Integer1); case AML_SUBTRACT_OP: /* Subtract (Integer0, Integer1, Result) */ return (Integer0 - Integer1); default: return (0); } } /******************************************************************************* * * FUNCTION: AcpiExDoLogicalNumericOp * * PARAMETERS: Opcode - AML opcode * Integer0 - Integer operand #0 * Integer1 - Integer operand #1 * LogicalResult - TRUE/FALSE result of the operation * * RETURN: Status * * DESCRIPTION: Execute a logical "Numeric" AML opcode. For these Numeric * operators (LAnd and LOr), both operands must be integers. * * Note: cleanest machine code seems to be produced by the code * below, rather than using statements of the form: * Result = (Integer0 && Integer1); * ******************************************************************************/ ACPI_STATUS AcpiExDoLogicalNumericOp ( UINT16 Opcode, UINT64 Integer0, UINT64 Integer1, BOOLEAN *LogicalResult) { ACPI_STATUS Status = AE_OK; BOOLEAN LocalResult = FALSE; ACPI_FUNCTION_TRACE (ExDoLogicalNumericOp); switch (Opcode) { case AML_LOGICAL_AND_OP: /* LAnd (Integer0, Integer1) */ if (Integer0 && Integer1) { LocalResult = TRUE; } break; case AML_LOGICAL_OR_OP: /* LOr (Integer0, Integer1) */ if (Integer0 || Integer1) { LocalResult = TRUE; } break; default: ACPI_ERROR ((AE_INFO, "Invalid numeric logical opcode: %X", Opcode)); Status = AE_AML_INTERNAL; break; } /* Return the logical result and status */ *LogicalResult = LocalResult; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExDoLogicalOp * * PARAMETERS: Opcode - AML opcode * Operand0 - operand #0 * Operand1 - operand #1 * LogicalResult - TRUE/FALSE result of the operation * * RETURN: Status * * DESCRIPTION: Execute a logical AML opcode. The purpose of having all of the * functions here is to prevent a lot of pointer dereferencing * to obtain the operands and to simplify the generation of the * logical value. For the Numeric operators (LAnd and LOr), both * operands must be integers. For the other logical operators, * operands can be any combination of Integer/String/Buffer. The * first operand determines the type to which the second operand * will be converted. * * Note: cleanest machine code seems to be produced by the code * below, rather than using statements of the form: * Result = (Operand0 == Operand1); * ******************************************************************************/ ACPI_STATUS AcpiExDoLogicalOp ( UINT16 Opcode, ACPI_OPERAND_OBJECT *Operand0, ACPI_OPERAND_OBJECT *Operand1, BOOLEAN *LogicalResult) { ACPI_OPERAND_OBJECT *LocalOperand1 = Operand1; UINT64 Integer0; UINT64 Integer1; UINT32 Length0; UINT32 Length1; ACPI_STATUS Status = AE_OK; BOOLEAN LocalResult = FALSE; int Compare; ACPI_FUNCTION_TRACE (ExDoLogicalOp); /* * Convert the second operand if necessary. The first operand * determines the type of the second operand, (See the Data Types * section of the ACPI 3.0+ specification.) Both object types are * guaranteed to be either Integer/String/Buffer by the operand * resolution mechanism. */ switch (Operand0->Common.Type) { case ACPI_TYPE_INTEGER: Status = AcpiExConvertToInteger (Operand1, &LocalOperand1, ACPI_IMPLICIT_CONVERSION); break; case ACPI_TYPE_STRING: Status = AcpiExConvertToString ( Operand1, &LocalOperand1, ACPI_IMPLICIT_CONVERT_HEX); break; case ACPI_TYPE_BUFFER: Status = AcpiExConvertToBuffer (Operand1, &LocalOperand1); break; default: ACPI_ERROR ((AE_INFO, "Invalid object type for logical operator: %X", Operand0->Common.Type)); Status = AE_AML_INTERNAL; break; } if (ACPI_FAILURE (Status)) { goto Cleanup; } /* * Two cases: 1) Both Integers, 2) Both Strings or Buffers */ if (Operand0->Common.Type == ACPI_TYPE_INTEGER) { /* * 1) Both operands are of type integer * Note: LocalOperand1 may have changed above */ Integer0 = Operand0->Integer.Value; Integer1 = LocalOperand1->Integer.Value; switch (Opcode) { case AML_LOGICAL_EQUAL_OP: /* LEqual (Operand0, Operand1) */ if (Integer0 == Integer1) { LocalResult = TRUE; } break; case AML_LOGICAL_GREATER_OP: /* LGreater (Operand0, Operand1) */ if (Integer0 > Integer1) { LocalResult = TRUE; } break; case AML_LOGICAL_LESS_OP: /* LLess (Operand0, Operand1) */ if (Integer0 < Integer1) { LocalResult = TRUE; } break; default: ACPI_ERROR ((AE_INFO, "Invalid comparison opcode: %X", Opcode)); Status = AE_AML_INTERNAL; break; } } else { /* * 2) Both operands are Strings or both are Buffers * Note: Code below takes advantage of common Buffer/String * object fields. LocalOperand1 may have changed above. Use * memcmp to handle nulls in buffers. */ Length0 = Operand0->Buffer.Length; Length1 = LocalOperand1->Buffer.Length; /* Lexicographic compare: compare the data bytes */ Compare = memcmp (Operand0->Buffer.Pointer, LocalOperand1->Buffer.Pointer, (Length0 > Length1) ? Length1 : Length0); switch (Opcode) { case AML_LOGICAL_EQUAL_OP: /* LEqual (Operand0, Operand1) */ /* Length and all bytes must be equal */ if ((Length0 == Length1) && (Compare == 0)) { /* Length and all bytes match ==> TRUE */ LocalResult = TRUE; } break; case AML_LOGICAL_GREATER_OP: /* LGreater (Operand0, Operand1) */ if (Compare > 0) { LocalResult = TRUE; goto Cleanup; /* TRUE */ } if (Compare < 0) { goto Cleanup; /* FALSE */ } /* Bytes match (to shortest length), compare lengths */ if (Length0 > Length1) { LocalResult = TRUE; } break; case AML_LOGICAL_LESS_OP: /* LLess (Operand0, Operand1) */ if (Compare > 0) { goto Cleanup; /* FALSE */ } if (Compare < 0) { LocalResult = TRUE; goto Cleanup; /* TRUE */ } /* Bytes match (to shortest length), compare lengths */ if (Length0 < Length1) { LocalResult = TRUE; } break; default: ACPI_ERROR ((AE_INFO, "Invalid comparison opcode: %X", Opcode)); Status = AE_AML_INTERNAL; break; } } Cleanup: /* New object was created if implicit conversion performed - delete */ if (LocalOperand1 != Operand1) { AcpiUtRemoveReference (LocalOperand1); } /* Return the logical result and status */ *LogicalResult = LocalResult; return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/user.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/process.h> #include <tilck/kernel/vdso.h> #include <tilck/kernel/cmdline.h> #include <tilck/mods/tracing.h> #include "paging_int.h" #include "../generic_x86/paging_generic_x86.h" #include <sys/mman.h> // system header pdir_t *__kernel_pdir; static char kpdir_buf[sizeof(pdir_t)] ALIGNED_AT(PAGE_SIZE); static ALWAYS_INLINE page_table_t * pdir_get_page_table(pdir_t *pdir, u32 i) { return KERNEL_PA_TO_VA(pdir->entries[i].ptaddr << PAGE_SHIFT); } bool handle_potential_cow(void *context) { regs_t *r = context; u32 vaddr; if ((r->err_code & PAGE_FAULT_FL_COW) != PAGE_FAULT_FL_COW) return false; asmVolatile("movl %%cr2, %0" : "=r"(vaddr)); const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); const void *const page_vaddr = (void *)(vaddr & PAGE_MASK); page_table_t *pt = pdir_get_page_table(get_curr_pdir(), pd_index); if (!(pt->pages[pt_index].avail & PAGE_COW_ORIG_RW)) return false; /* Not a COW page */ const u32 orig_page_paddr = (u32) pt->pages[pt_index].pageAddr << PAGE_SHIFT; if (pf_ref_count_get(orig_page_paddr) == 1) { /* This page is not shared anymore. No need for copying it. */ #if DEBUG_CHECKS const ulong paddr = (ulong) pt->pages[pt_index].pageAddr << PAGE_SHIFT; ASSERT(KERNEL_PA_TO_VA(paddr) != &zero_page); #endif pt->pages[pt_index].rw = true; pt->pages[pt_index].avail = 0; invalidate_page_hw(vaddr); return true; } // Allocate a new page. void *new_page_vaddr = kmalloc(PAGE_SIZE); if (!new_page_vaddr) { // Out-of-memory case struct task *curr = get_curr_task(); if (!curr->running_in_kernel) { // The task was not running in kernel: we can safely kill it. printk("Out-of-memory: killing pid %d\n", get_curr_pid()); send_signal(get_curr_pid(), SIGKILL, SIG_FL_PROCESS | SIG_FL_FAULT); return true; } else { // We cannot kill a task running in kernel during a CoW page fault // In this case (but in the one above too), Linux puts the process to // sleep, while the OOM killer runs and frees some memory. panic("Out-of-memory: can't copy a CoW page [pid %d]", get_curr_pid()); } } ASSERT(IS_PAGE_ALIGNED(new_page_vaddr)); // Copy page's contents memcpy32(new_page_vaddr, page_vaddr, PAGE_SIZE / 4); // Get the paddr of the new page const ulong paddr = KERNEL_VA_TO_PA(new_page_vaddr); // A just-allocated pageframe MUST have ref-count == 0 ASSERT(pf_ref_count_get(paddr) == 0); // Increase the ref-count of the new pageframe pf_ref_count_inc(paddr); // Decrease the ref-count of the original pageframe. pf_ref_count_dec(orig_page_paddr); // Re-map the vaddr to its new (writable) pageframe pt->pages[pt_index].pageAddr = SHR_BITS(paddr, PAGE_SHIFT, u32); pt->pages[pt_index].rw = true; pt->pages[pt_index].avail = 0; invalidate_page_hw(vaddr); return true; } static void kernel_page_fault_panic(regs_t *r, u32 vaddr, bool rw, bool p) { long off = 0; const char *sym_name = find_sym_at_addr_safe(r->eip, &off, NULL); panic("PAGE FAULT in attempt to %s %p from %s%s\nEIP: %p [%s + %d]\n", rw ? "WRITE" : "READ", vaddr, "kernel", !p ? " (NON present)." : ".", r->eip, sym_name ? sym_name : "???", off); } void handle_page_fault_int(regs_t *r) { u32 vaddr; asmVolatile("movl %%cr2, %0" : "=r"(vaddr)); bool p = !!(r->err_code & PAGE_FAULT_FL_PRESENT); bool rw = !!(r->err_code & PAGE_FAULT_FL_RW); bool us = !!(r->err_code & PAGE_FAULT_FL_US); int sig = SIGSEGV; struct user_mapping *um; if (!us) { /* * Tilck does not support kernel-space page faults caused by the kernel, * while it allows user-space page faults caused by kernel (CoW pages). * Therefore, such a fault is necessary caused by a bug. * We have to panic. */ kernel_page_fault_panic(r, vaddr, rw, p); } um = process_get_user_mapping((void *)vaddr); if (um) { /* * Call vfs_handle_fault() only if in first place the mapping allowed * writing or if it didn't but the memory access type was a READ. */ if (!!(um->prot & PROT_WRITE) || !rw) { if (vfs_handle_fault(um, (void *)vaddr, p, rw)) return; sig = SIGBUS; } } if (KRN_PAGE_FAULT_PRINTK) { printk("[%d] USER PAGE FAULT in attempt to %s %p%s\n", get_curr_pid(), rw ? "WRITE" : "READ", TO_PTR(vaddr), !p ? " (NON present)." : "."); printk("EIP: %p\n", TO_PTR(r->eip)); if (get_curr_proc()->debug_cmdline) printk("Cmdline: %s\n", get_curr_proc()->debug_cmdline); } trace_printk( 5, "USER PAGE FAULT in attempt to %s %p%s, EIP: %p, Cmdline: '%s'", rw ? "WRITE" : "READ", TO_PTR(vaddr), !p ? " (NON present)" : "", TO_PTR(r->eip), get_curr_proc()->debug_cmdline ); send_signal(get_curr_tid(), sig, SIG_FL_PROCESS | SIG_FL_FAULT); } bool is_mapped(pdir_t *pdir, void *vaddrp) { page_table_t *pt; const ulong vaddr = (ulong) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); page_dir_entry_t *e = &pdir->entries[pd_index]; if (!e->present) return false; if (e->psize) /* 4-MB page */ return e->present; pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); return pt->pages[pt_index].present; } bool is_rw_mapped(pdir_t *pdir, void *vaddrp) { page_table_t *pt; const ulong vaddr = (ulong) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); page_dir_entry_t *e = &pdir->entries[pd_index]; page_t page; if (!e->present) return false; if (e->psize) /* 4-MB page */ return e->present && e->rw; pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); page = pt->pages[pt_index]; return page.present && page.rw; } void set_page_rw(pdir_t *pdir, void *vaddrp, bool rw) { page_table_t *pt; const ulong vaddr = (ulong) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); ASSERT(KERNEL_VA_TO_PA(pt) != 0); pt->pages[pt_index].rw = rw; invalidate_page_hw(vaddr); } static inline int __unmap_page(pdir_t *pdir, void *vaddrp, bool free_pageframe, bool permissive) { page_table_t *pt; const ulong vaddr = (ulong) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); if (permissive) { if (KERNEL_VA_TO_PA(pt) == 0) return -EINVAL; if (!pt->pages[pt_index].present) return -EINVAL; } else { ASSERT(KERNEL_VA_TO_PA(pt) != 0); ASSERT(pt->pages[pt_index].present); } const ulong paddr = (ulong) pt->pages[pt_index].pageAddr << PAGE_SHIFT; pt->pages[pt_index].raw = 0; invalidate_page_hw(vaddr); if (!pf_ref_count_dec(paddr) && free_pageframe) { ASSERT(paddr != KERNEL_VA_TO_PA(zero_page)); kfree2(KERNEL_PA_TO_VA(paddr), PAGE_SIZE); } return 0; } void unmap_page(pdir_t *pdir, void *vaddrp, bool free_pageframe) { __unmap_page(pdir, vaddrp, free_pageframe, false); } int unmap_page_permissive(pdir_t *pdir, void *vaddrp, bool free_pageframe) { return __unmap_page(pdir, vaddrp, free_pageframe, true); } void unmap_pages(pdir_t *pdir, void *vaddr, size_t page_count, bool do_free) { for (size_t i = 0; i < page_count; i++) { unmap_page(pdir, (char *)vaddr + (i << PAGE_SHIFT), do_free); } } size_t unmap_pages_permissive(pdir_t *pdir, void *vaddr, size_t page_count, bool do_free) { size_t unmapped_pages = 0; int rc; for (size_t i = 0; i < page_count; i++) { rc = unmap_page_permissive( pdir, (char *)vaddr + (i << PAGE_SHIFT), do_free ); unmapped_pages += (rc == 0); } return unmapped_pages; } ulong get_mapping(pdir_t *pdir, void *vaddrp) { page_table_t *pt; const ulong vaddr = (ulong)vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 0x3FF; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT) & 0x3FF; page_dir_entry_t e; page_t p; /* * This function shall be never called for the linear-mapped zone of the * the kernel virtual memory. */ ASSERT(vaddr < KERNEL_BASE_VA || vaddr >= LINEAR_MAPPING_END); e.raw = pdir->entries[pd_index].raw; ASSERT(e.present); ASSERT(e.ptaddr != 0); pt = KERNEL_PA_TO_VA(e.ptaddr << PAGE_SHIFT); p.raw = pt->pages[pt_index].raw; ASSERT(p.present); return ((ulong) p.pageAddr << PAGE_SHIFT) | (vaddr & OFFSET_IN_PAGE_MASK); } int get_mapping2(pdir_t *pdir, void *vaddrp, ulong *pa_ref) { page_table_t *pt; const ulong vaddr = (ulong)vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 0x3FF; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT) & 0x3FF; page_dir_entry_t e; page_t p; /* Get page directory's entry for this vaddr */ e.raw = pdir->entries[pd_index].raw; if (!e.present) return -EFAULT; if (!e.psize) { /* Regular entry, pointing to a page table */ ASSERT(e.ptaddr != 0); /* Get the page table */ pt = KERNEL_PA_TO_VA(e.ptaddr << PAGE_SHIFT); /* Get the page entry for `vaddr` within the page table */ p.raw = pt->pages[pt_index].raw; if (!p.present) return -EFAULT; *pa_ref = ((ulong) p.pageAddr << PAGE_SHIFT) | (vaddr & OFFSET_IN_PAGE_MASK); } else { /* Big page (4 MB) entry */ *pa_ref = ((ulong) e.big_4mb_page.paddr << BIG_PAGE_SHIFT) | (vaddr & (4 * MB - 1)); } return 0; } NODISCARD int map_page_int(pdir_t *pdir, void *vaddrp, ulong paddr, u32 hw_flags) { page_table_t *pt; const u32 vaddr = (u32) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); ASSERT(!(vaddr & OFFSET_IN_PAGE_MASK)); // the vaddr must be page-aligned ASSERT(!(paddr & OFFSET_IN_PAGE_MASK)); // the paddr must be page-aligned pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); ASSERT(IS_PAGE_ALIGNED(pt)); if (UNLIKELY(KERNEL_VA_TO_PA(pt) == 0)) { // we have to create a page table for mapping 'vaddr'. pt = kzalloc_obj(page_table_t); if (UNLIKELY(!pt)) return -ENOMEM; ASSERT(IS_PAGE_ALIGNED(pt)); pdir->entries[pd_index].raw = PG_PRESENT_BIT | PG_RW_BIT | (hw_flags & PG_US_BIT) | KERNEL_VA_TO_PA(pt); } if (pt->pages[pt_index].present) return -EADDRINUSE; pt->pages[pt_index].raw = PG_PRESENT_BIT | hw_flags | paddr; pf_ref_count_inc(paddr); invalidate_page_hw(vaddr); return 0; } NODISCARD size_t map_pages_int(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, bool big_pages_allowed, u32 hw_flags) { int rc; size_t pages = 0; size_t big_pages = 0; size_t rem_pages = page_count; u32 big_page_flags; ASSERT(!((ulong)vaddr & OFFSET_IN_PAGE_MASK)); ASSERT(!(paddr & OFFSET_IN_PAGE_MASK)); if (big_pages_allowed && rem_pages >= 1024) { for (; pages < rem_pages; pages++) { if (!((ulong)vaddr & (4*MB - 1)) && !(paddr & (4*MB - 1))) break; rc = map_page_int(pdir, vaddr, paddr, hw_flags); if (UNLIKELY(rc < 0)) goto out; vaddr += PAGE_SIZE; paddr += PAGE_SIZE; } rem_pages -= pages; big_page_flags = hw_flags | PG_4MB_BIT | PG_PRESENT_BIT; big_page_flags &= ~PG_GLOBAL_BIT; for (; big_pages < (rem_pages >> 10); big_pages++) { map_4mb_page_int(pdir, vaddr, paddr, big_page_flags); vaddr += (4 * MB); paddr += (4 * MB); } rem_pages -= (big_pages << 10); } for (size_t i = 0; i < rem_pages; i++, pages++) { rc = map_page_int(pdir, vaddr, paddr, hw_flags); if (UNLIKELY(rc < 0)) goto out; vaddr += PAGE_SIZE; paddr += PAGE_SIZE; } out: return (big_pages << 10) + pages; } NODISCARD int map_page(pdir_t *pdir, void *vaddrp, ulong paddr, u32 pg_flags) { const bool rw = !!(pg_flags & PAGING_FL_RW); const bool us = !!(pg_flags & PAGING_FL_US); u32 avail_bits = 0; int rc; if (pg_flags & PAGING_FL_SHARED) avail_bits |= PAGE_SHARED; if (pg_flags & PAGING_FL_DO_ALLOC) { void *va; ASSERT(paddr == 0); if (!(va = kmalloc(PAGE_SIZE))) return -ENOMEM; if (pg_flags & PAGING_FL_ZERO_PG) bzero(va, PAGE_SIZE); paddr = KERNEL_VA_TO_PA(va); } else { /* PAGING_FL_ZERO_PG cannot be used without PAGING_FL_DO_ALLOC */ ASSERT(~pg_flags & PAGING_FL_ZERO_PG); } rc = map_page_int(pdir, vaddrp, paddr, (u32)(avail_bits << PG_CUSTOM_B0_POS) | (u32)(us << PG_US_BIT_POS) | (u32)(rw << PG_RW_BIT_POS) | (u32)((!us) << PG_GLOBAL_BIT_POS)); /* Kernel pages are global */ if (UNLIKELY(rc != 0) && (pg_flags & PAGING_FL_DO_ALLOC)) { kfree2(KERNEL_PA_TO_VA(paddr), PAGE_SIZE); } return rc; } NODISCARD int map_zero_page(pdir_t *pdir, void *vaddrp, u32 pg_flags) { u32 avail_bits = 0; const bool us = !!(pg_flags & PAGING_FL_US); /* Zero pages are always private */ ASSERT(!(pg_flags & PAGING_FL_SHARED)); if (pg_flags & PAGING_FL_RW) avail_bits |= PAGE_COW_ORIG_RW; return map_page_int(pdir, vaddrp, KERNEL_VA_TO_PA(&zero_page), (u32)(us << PG_US_BIT_POS) | (u32)(avail_bits << PG_CUSTOM_B0_POS) | (u32)((!us) << PG_GLOBAL_BIT_POS)); /* Kernel pages are global */ } NODISCARD size_t map_pages(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, u32 pg_flags) { const bool us = !!(pg_flags & PAGING_FL_US); const bool rw = !!(pg_flags & PAGING_FL_RW); const bool big_pages = !!(pg_flags & PAGING_FL_BIG_PAGES_ALLOWED); u32 avail_bits = 0; if (pg_flags & PAGING_FL_SHARED) avail_bits |= PAGE_SHARED; if (pg_flags & PAGING_FL_DO_ALLOC) NOT_IMPLEMENTED(); return map_pages_int(pdir, vaddr, paddr, page_count, big_pages, (u32)(avail_bits << PG_CUSTOM_B0_POS) | (u32)(us << PG_US_BIT_POS) | (u32)(rw << PG_RW_BIT_POS) | (u32)((!us) << PG_GLOBAL_BIT_POS)); } pdir_t *pdir_clone(pdir_t *pdir) { pdir_t *new_pdir = kalloc_obj(pdir_t); if (!new_pdir) return NULL; ASSERT(IS_PAGE_ALIGNED(new_pdir)); memcpy32(new_pdir, pdir, sizeof(pdir_t) / 4); for (u32 i = 0; i < KERNEL_BASE_PD_IDX; i++) { /* User-space cannot use 4-MB pages */ ASSERT(!pdir->entries[i].psize); if (!pdir->entries[i].present) continue; page_table_t *pt = kalloc_obj(page_table_t); if (UNLIKELY(!pt)) { for (; i > 0; i--) { if (pdir->entries[i - 1].present) kfree_obj(pdir_get_page_table(pdir, i - 1), page_table_t); } kfree_obj(new_pdir, pdir_t); return NULL; } ASSERT(IS_PAGE_ALIGNED(pt)); new_pdir->entries[i].ptaddr=SHR_BITS(KERNEL_VA_TO_PA(pt),PAGE_SHIFT,u32); } for (u32 i = 0; i < KERNEL_BASE_PD_IDX; i++) { if (!pdir->entries[i].present) continue; page_table_t *orig_pt = pdir_get_page_table(pdir, i); page_table_t *new_pt = pdir_get_page_table(new_pdir, i); /* Mark all the non-shared pages in that page-table as COW. */ for (u32 j = 0; j < 1024; j++) { page_t *const p = &orig_pt->pages[j]; if (!p->present) continue; const ulong orig_paddr = (ulong)p->pageAddr << PAGE_SHIFT; /* Sanity-check: a mapped page MUST have ref-count > 0 */ ASSERT(pf_ref_count_get(orig_paddr) > 0); if (!(p->avail & PAGE_SHARED)) { if (p->rw) p->avail |= PAGE_COW_ORIG_RW; p->rw = false; } pf_ref_count_inc(orig_paddr); } // copy the page table memcpy(new_pt, orig_pt, sizeof(page_table_t)); } return new_pdir; } pdir_t * pdir_deep_clone(pdir_t *pdir) { STATIC_ASSERT(sizeof(pdir_t) == PAGE_SIZE); STATIC_ASSERT(sizeof(page_table_t) == PAGE_SIZE); struct kmalloc_acc acc; kmalloc_create_accelerator(&acc, PAGE_SIZE, 4); pdir_t *new_pdir = kmalloc_accelerator_get_elem(&acc); if (UNLIKELY(!new_pdir)) goto oom_exit; ASSERT(IS_PAGE_ALIGNED(new_pdir)); for (u32 i = 0; i < KERNEL_BASE_PD_IDX; i++) { new_pdir->entries[i].raw = pdir->entries[i].raw; /* User-space cannot use 4-MB pages */ ASSERT(!pdir->entries[i].psize); if (!pdir->entries[i].present) continue; page_table_t *orig_pt = pdir_get_page_table(pdir, i); page_table_t *new_pt = kmalloc_accelerator_get_elem(&acc); if (UNLIKELY(!new_pt)) goto oom_exit; ASSERT(IS_PAGE_ALIGNED(new_pt)); for (u32 j = 0; j < 1024; j++) { new_pt->pages[j].raw = orig_pt->pages[j].raw; if (!orig_pt->pages[j].present) continue; void *new_page = kmalloc_accelerator_get_elem(&acc); if (!new_page) goto oom_exit; ASSERT(IS_PAGE_ALIGNED(new_page)); ulong orig_page_paddr = (ulong)orig_pt->pages[j].pageAddr << PAGE_SHIFT; void *orig_page = KERNEL_PA_TO_VA(orig_page_paddr); u32 new_page_paddr = KERNEL_VA_TO_PA(new_page); ASSERT(pf_ref_count_get(new_page_paddr) == 0); pf_ref_count_inc(new_page_paddr); memcpy32(new_page, orig_page, PAGE_SIZE / 4); new_pt->pages[j].pageAddr = SHR_BITS(new_page_paddr, PAGE_SHIFT, u32); } new_pdir->entries[i].ptaddr = SHR_BITS(KERNEL_VA_TO_PA(new_pt), PAGE_SHIFT, u32); } for (u32 i = KERNEL_BASE_PD_IDX; i < 1024; i++) { new_pdir->entries[i].raw = pdir->entries[i].raw; } kmalloc_destroy_accelerator(&acc); return new_pdir; oom_exit: kmalloc_destroy_accelerator(&acc); if (new_pdir) pdir_destroy(new_pdir); return NULL; } void pdir_destroy(pdir_t *pdir) { // Kernel's pdir cannot be destroyed! ASSERT(pdir != __kernel_pdir); for (u32 i = 0; i < KERNEL_BASE_PD_IDX; i++) { if (!pdir->entries[i].present) continue; page_table_t *pt = pdir_get_page_table(pdir, i); for (u32 j = 0; j < 1024; j++) { if (!pt->pages[j].present) continue; const ulong paddr = (ulong)pt->pages[j].pageAddr << PAGE_SHIFT; if (pf_ref_count_dec(paddr) == 0) kfree2(KERNEL_PA_TO_VA(paddr), PAGE_SIZE); } // We freed all the pages, now free the whole page-table. kfree_obj(pt, page_table_t); } // We freed all pages and all the page-tables, now free pdir. kfree_obj(pdir, pdir_t); } void map_4mb_page_int(pdir_t *pdir, void *vaddrp, ulong paddr, u32 flags) { const u32 vaddr = (u32) vaddrp; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); ASSERT(!(vaddr & (4*MB - 1))); // the vaddr must be 4MB-aligned ASSERT(!(paddr & (4*MB - 1))); // the paddr must be 4MB-aligned // Check that the entry has not been used. ASSERT(!pdir->entries[pd_index].present); // Check that there is no page table associated with this entry. ASSERT(!pdir->entries[pd_index].ptaddr); pdir->entries[pd_index].raw = flags | paddr; } static inline bool in_big_4mb_page(pdir_t *pdir, void *vaddrp) { const u32 vaddr = (u32) vaddrp; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); page_dir_entry_t *e = &pdir->entries[pd_index]; return e->present && e->psize; } static void set_big_4mb_page_pat_wc(pdir_t *pdir, void *vaddrp) { const u32 vaddr = (u32) vaddrp; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); page_dir_entry_t *e = &pdir->entries[pd_index]; // 111 => entry[7] in the PAT MSR. See init_pat() e->big_4mb_page.pat = 1; e->big_4mb_page.cd = 1; e->big_4mb_page.wt = 1; invalidate_page_hw(vaddr); } static void set_4kb_page_pat_wc(pdir_t *pdir, void *vaddrp) { page_table_t *pt; const u32 vaddr = (u32) vaddrp; const u32 pt_index = (vaddr >> PAGE_SHIFT) & 1023; const u32 pd_index = (vaddr >> BIG_PAGE_SHIFT); ASSERT(!(vaddr & OFFSET_IN_PAGE_MASK)); // the vaddr must be page-aligned pt = KERNEL_PA_TO_VA(pdir->entries[pd_index].ptaddr << PAGE_SHIFT); ASSERT(IS_PAGE_ALIGNED(pt)); ASSERT(pt != NULL); // 111 => entry[7] in the PAT MSR. See init_pat() pt->pages[pt_index].pat = 1; pt->pages[pt_index].cd = 1; pt->pages[pt_index].wt = 1; invalidate_page_hw(vaddr); } void set_pages_pat_wc(pdir_t *pdir, void *vaddr, size_t size) { ASSERT(!((ulong)vaddr & OFFSET_IN_PAGE_MASK)); ASSERT(IS_PAGE_ALIGNED(size)); const void *end = vaddr + size; while (vaddr < end) { if (in_big_4mb_page(pdir, vaddr)) { set_big_4mb_page_pat_wc(pdir, vaddr); vaddr += 4 * MB; continue; } set_4kb_page_pat_wc(pdir, vaddr); vaddr += PAGE_SIZE; } } void early_init_paging(void) { set_fault_handler(FAULT_PAGE_FAULT, handle_page_fault); __kernel_pdir = (pdir_t *) kpdir_buf; set_kernel_process_pdir(__kernel_pdir); } void init_hi_vmem_heap(void) { size_t hi_vmem_size; ulong hi_vmem_start; u32 hi_vmem_start_pidx; u32 hi_vmem_end_pidx; if (LINEAR_MAPPING_MB <= 896) { hi_vmem_size = 128 * MB; } else { panic("LINEAR_MAPPING_MB (%d) is too big", LINEAR_MAPPING_MB); } hi_vmem_start = LINEAR_MAPPING_END; hi_vmem_start_pidx = hi_vmem_start >> BIG_PAGE_SHIFT; hi_vmem_end_pidx = hi_vmem_start_pidx + (hi_vmem_size >> BIG_PAGE_SHIFT); hi_vmem_heap = kmalloc_create_regular_heap(hi_vmem_start, hi_vmem_size, 4 * PAGE_SIZE); // min_block_size if (!hi_vmem_heap) panic("Failed to create the hi vmem heap"); for (u32 i = hi_vmem_start_pidx; i < hi_vmem_end_pidx; i++) { page_table_t *pt; page_dir_entry_t *e = &__kernel_pdir->entries[i]; ASSERT(!e->present); if (!(pt = kzalloc_obj(page_table_t))) panic("Unable to alloc ptable for hi_vmem at %p", i << BIG_PAGE_SHIFT); ASSERT(IS_PAGE_ALIGNED(pt)); e->raw = PG_PRESENT_BIT | PG_RW_BIT | PG_US_BIT | KERNEL_VA_TO_PA(pt); } } void *failsafe_map_framebuffer(ulong paddr, ulong size) { /* * Paging has not been initialized yet: probably we're in panic. * At this point, the kernel still uses page_size_buf as pdir, with only * the first 4 MB of the physical mapped at KERNEL_BASE_VA. */ ulong vaddr = FAILSAFE_FB_VADDR; __kernel_pdir = (pdir_t *)page_size_buf; u32 big_pages_to_use = pow2_round_up_at(size, 4 * MB) / (4 * MB); for (u32 i = 0; i < big_pages_to_use; i++) { map_4mb_page_int(__kernel_pdir, (void *)vaddr + i * 4 * MB, paddr + i * 4 * MB, PG_PRESENT_BIT | PG_RW_BIT | PG_4MB_BIT); } return (void *)vaddr; } int virtual_read_unsafe(pdir_t *pdir, void *extern_va, void *dest, size_t len) { ulong pgoff, pa; size_t tot, to_read; void *va; ASSERT(len <= INT32_MAX); for (tot = 0; tot < len; extern_va += to_read, tot += to_read) { if (get_mapping2(pdir, extern_va, &pa) < 0) return -EFAULT; pgoff = ((ulong)extern_va) & OFFSET_IN_PAGE_MASK; to_read = MIN(PAGE_SIZE - pgoff, len - tot); va = KERNEL_PA_TO_VA(pa); memcpy(dest + tot, va, to_read); } return (int)tot; } int virtual_write_unsafe(pdir_t *pdir, void *extern_va, void *src, size_t len) { ulong pgoff, pa; size_t tot, to_write; void *va; ASSERT(len <= INT32_MAX); for (tot = 0; tot < len; extern_va += to_write, tot += to_write) { if (get_mapping2(pdir, extern_va, &pa) < 0) return -EFAULT; pgoff = ((ulong)extern_va) & OFFSET_IN_PAGE_MASK; to_write = MIN(PAGE_SIZE - pgoff, len - tot); va = KERNEL_PA_TO_VA(pa); memcpy(va, src + tot, to_write); } return (int)tot; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define __EFI_MAIN__ #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/config_kernel.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_serial.h> #include <tilck_gen_headers/mod_fb.h> #include "defs.h" #include "utils.h" #include <tilck/boot/common.h> /** * efi_main - The entry point for the EFI application * @image: firmware-allocated handle that identifies the image * @ST: EFI system table */ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *__ST) { EFI_STATUS status; void *kernel_entry; UINTN mapkey; init_common_bootloader_code(&efi_boot_intf); InitializeLib(image, __ST); gImageHandle = image; status = BS->OpenProtocol(image, &LoadedImageProtocol, (void**) &gLoadedImage, image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); HANDLE_EFI_ERROR("OpenProtocol(LoadedImageProtocol)"); // // For debugging with GDB (see docs/debugging.md) // if (EFI_BOOTLOADER_DEBUG) { Print(L"\n"); Print(L"------------ EFI BOOTLOADER DEBUG ------------\n"); Print(L"Pointer size: %d\n", sizeof(void *)); Print(L"JumpToKernel: 0x%x\n", (void *)JumpToKernel); Print(L"BaseAddr: 0x%x\n", gLoadedImage->ImageBase + 0x1000); Print(L"Press ANY key to continue..."); WaitForKeyPress(); } EarlySetDefaultResolution(); ST->ConOut->EnableCursor(ST->ConOut, true); write_bootloader_hello_msg(); status = BS->OpenProtocol(gLoadedImage->DeviceHandle, &FileSystemProtocol, (void **)&gFileFsProt, image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); HANDLE_EFI_ERROR("OpenProtocol FileSystemProtocol"); status = gFileFsProt->OpenVolume(gFileFsProt, &gFileProt); HANDLE_EFI_ERROR("OpenVolume"); status = ReserveMemAreaForKernelImage(); HANDLE_EFI_ERROR("ReserveMemAreaForKernelImage"); if (!common_bootloader_logic()) { status = EFI_ABORTED; goto end; } status = SetupMultibootInfo(); HANDLE_EFI_ERROR("SetupMultibootInfo"); status = BS->CloseProtocol(gLoadedImage->DeviceHandle, &FileSystemProtocol, image, NULL); HANDLE_EFI_ERROR("CloseProtocol(FileSystemProtocol)"); gFileFsProt = NULL; status = BS->CloseProtocol(image, &LoadedImageProtocol, image, NULL); HANDLE_EFI_ERROR("CloseProtocol(LoadedImageProtocol)"); gLoadedImage = NULL; status = MultibootSaveMemoryMap(&mapkey); HANDLE_EFI_ERROR("MultibootSaveMemoryMap"); status = KernelLoadMemoryChecks(); HANDLE_EFI_ERROR("KernelLoadMemoryChecks"); gExitBootServicesCalled = true; status = BS->ExitBootServices(image, mapkey); HANDLE_EFI_ERROR("BS->ExitBootServices"); /* --- Point of no return: from here on, we MUST NOT fail --- */ kernel_entry = load_kernel_image(); JumpToKernel(kernel_entry); end: /* --- we should never get here in the normal case --- */ WaitForKeyPress(); return status; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${GLOB_CONF_DEP} ${CMAKE_CURRENT_SOURCE_DIR}/*) set(EXTRA_APPS_LIST "") foreach(child ${children}) if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${child}) message(STATUS "Adding EXTRA user apps directory '${child}'") add_subdirectory(${child}) endif() endforeach() set(EXTRA_APPS_LIST ${EXTRA_APPS_LIST} PARENT_SCOPE) <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause OVMF_VER="latest" # $1: omvf_arch function download_ovmf_internal { local ovmf_arch="$1" local url="https://www.kraxel.org/repos/jenkins/edk2/" # Unfortunately, the OVMF builds on kraxel.org are in the RPM format. # Therefore, we need to make sure that rpm2cpio is installed. install_rpm2cpio wget -nd -r --no-parent -A "edk2.git-ovmf-${ovmf_arch}*" "$url" rpm2cpio edk2.git-ovmf-${ovmf_arch}* | cpio -idmv mv ./usr/share/edk2.git/* . rm -rf ./usr rm -rf ./robots* rm -rf *.rpm mv ovmf-${ovmf_arch} ovmf } # $1: omvf_arch # $2: arch (our convention) function check_and_download_ovmf { pushd $2 if ! [ -d ovmf ]; then show_work_on_component_msg "OVMF (arch: $2)" download_ovmf_internal $1 else show_skip_component_msg "(arch: $2)" fi popd } all_funcs_list+=(download_ovmf) function download_ovmf { check_and_download_ovmf ia32 i386 check_and_download_ovmf x64 x86_64 } function download_ovmf_installed_status { if [ -d $TC/$ARCH/ovmf ]; then local ret="" if [ -f $TC/$ARCH/ovmf/OVMF-pure-efi.fd ]; then ret="$ret $ARCH" fi if [[ "$ARCH" != "$HOST_ARCH" ]]; then if [ -f $TC/$HOST_ARCH/ovmf/OVMF-pure-efi.fd ]; then ret="$ret $HOST_ARCH" fi fi if [ -n "ret" ]; then echo "installed$ret" else echo "error" fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <sys/wait.h> #include "devshell.h" #include "sysenter.h" #include "test_common.h" static void do_bigargv_test(size_t len) { char *big_arg = malloc(len); char *argv[] = { DEVSHELL_PATH, big_arg, NULL }; memset(big_arg, 'a', len); big_arg[len-1] = 0; close(0); close(1); close(2); execvpe(DEVSHELL_PATH, argv, shell_env); /* If we got here, execve() failed */ if (errno == E2BIG) exit(123); exit(99); /* unexpected case */ } static bool fails_with_e2big(size_t len) { int pid; int wstatus; pid = fork(); if (pid < 0) { perror("fork() failed"); exit(1); } if (!pid) do_bigargv_test(len); waitpid(pid, &wstatus, 0); if (!WIFEXITED(wstatus)) { printf("Test child killed by signal: %s\n", strsignal(WTERMSIG(wstatus))); exit(1); } if (WEXITSTATUS(wstatus) == 99) { printf("execve() in the child failed with something != E2BIG\n"); exit(1); } /* * At this point, only two options left: * - execve() failed with E2BIG and the child exited with our special 123 * - execve() did NOT fail and executed the program with either failed * or succeeded, but anyway exited with something different than 123. */ return WEXITSTATUS(wstatus) == 123; } int cmd_bigargv(int argc, char **argv) { size_t l = 1024; size_t r = 16 * 4096; size_t a0; size_t argv_len = 0, env_len = 0; if (!running_on_tilck()) { not_on_tilck_message(); return 0; } DEVSHELL_CMD_ASSERT(!fails_with_e2big(l)); DEVSHELL_CMD_ASSERT(fails_with_e2big(r)); while (l < r) { size_t v = (l + r) / 2; if (fails_with_e2big(v)) { r = v; } else { l = v + 1; } } size_t v = l - 1; assert(!fails_with_e2big(v)); assert(fails_with_e2big(v + 1)); a0 = strlen(DEVSHELL_PATH) + 1; for (char **e = shell_env; *e; e++) { env_len += strlen(*e) + 1 + sizeof(void *); } env_len += 1 * sizeof(void *); // +1 for the final NULL argv_len = 3 * sizeof(void *); // +3 pointer size integers [a0,a1,NULL] argv_len += a0; // len(argv[0]) + 1 argv_len += v; // max argv[1] length size_t grand_tot = argv_len + env_len; size_t expected_tot = USER_ARGS_PAGE_COUNT * getpagesize(); printf("fix argv[0] length: %zu\n", a0); printf("max argv[1] length: %zu\n", v); printf("tot argv length: %zu\n", argv_len); printf("tot env length: %zu\n", env_len); printf("grand_tot : %zu\n", grand_tot); printf("expected_tot : %zu\n", expected_tot); DEVSHELL_CMD_ASSERT(grand_tot == expected_tot); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config header file is generated by CMake * and put in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once /* ------ Value-based config variables -------- */ #define TTY_COUNT @TTY_COUNT@ #define TERM_SCROLL_LINES @TERM_SCROLL_LINES@ /* --------- Boolean config variables --------- */ #cmakedefine01 MOD_console #cmakedefine01 TERM_BIG_SCROLL_BUF #cmakedefine01 KERNEL_SHOW_LOGO #cmakedefine01 SERIAL_CON_IN_VIDEO_MODE #cmakedefine01 KRN_PRINTK_ON_CURR_TTY /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are some pseudo-constants not designed to be easily changed * because of the code makes assumptions about them. Because of that, those * constants are hard-coded and not available as CMake variables. With time, * some of those constants get "promoted" and moved in CMake, others remain * here. See the comments and think about the potential implications before * promoting a hard-coded constant to a configurable CMake variable. */ #define TTY_INPUT_BS 1024 #define FAILSAFE_COLS 80u #define FAILSAFE_ROWS 25u <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> /* * DEBUG utils used to dump into a human-readable form a termios struct. * NOTE: This is intentionally a "header" and not a C file, in order to avoid * bootloaders to get this code compiled-in. However, this is NOT a regular * header file that contains declarations, but actually just a C file "exposed" * as a header, as the ".c.h" extension remarks. */ #include <termios.h> // system header #include <sys/ioctl.h> // system header #ifndef USERMODE_APP #include <tilck/common/string_util.h> #define TERMIOS_DEBUG_PRINT(...) printk(NO_PREFIX __VA_ARGS__) #else #include <stdio.h> #define TERMIOS_DEBUG_PRINT(...) printf(__VA_ARGS__) #endif #define PRINT_FLAG(val, flag) \ if ((val) & flag) TERMIOS_DEBUG_PRINT(#flag " ") #define PRINT_IFEQ(val, e) \ if ((val) == (e)) TERMIOS_DEBUG_PRINT(#e " ") static void dump_c_iflag(struct termios *t) { TERMIOS_DEBUG_PRINT("c_iflag: "); PRINT_FLAG(t->c_iflag, IGNBRK); PRINT_FLAG(t->c_iflag, BRKINT); PRINT_FLAG(t->c_iflag, IGNPAR); PRINT_FLAG(t->c_iflag, PARMRK); PRINT_FLAG(t->c_iflag, INPCK); PRINT_FLAG(t->c_iflag, ISTRIP); PRINT_FLAG(t->c_iflag, INLCR); PRINT_FLAG(t->c_iflag, IGNCR); PRINT_FLAG(t->c_iflag, ICRNL); PRINT_FLAG(t->c_iflag, IUCLC); PRINT_FLAG(t->c_iflag, IXON); PRINT_FLAG(t->c_iflag, IXANY); PRINT_FLAG(t->c_iflag, IXOFF); PRINT_FLAG(t->c_iflag, IMAXBEL); PRINT_FLAG(t->c_iflag, IUTF8); TERMIOS_DEBUG_PRINT("\n"); } static void dump_c_oflag(struct termios *t) { TERMIOS_DEBUG_PRINT("c_oflag: "); PRINT_FLAG(t->c_oflag, OPOST); PRINT_FLAG(t->c_oflag, OLCUC); PRINT_FLAG(t->c_oflag, ONLCR); PRINT_FLAG(t->c_oflag, OCRNL); PRINT_FLAG(t->c_oflag, ONOCR); PRINT_FLAG(t->c_oflag, ONLRET); PRINT_FLAG(t->c_oflag, OFILL); PRINT_FLAG(t->c_oflag, OFDEL); PRINT_FLAG(t->c_oflag, NLDLY); // mask PRINT_FLAG(t->c_oflag, CRDLY); // mask PRINT_FLAG(t->c_oflag, TABDLY); // mask PRINT_FLAG(t->c_oflag, BSDLY); // mask PRINT_FLAG(t->c_oflag, VTDLY); // mask PRINT_FLAG(t->c_oflag, FFDLY); // mask TERMIOS_DEBUG_PRINT("\n"); } static void dump_c_cflag(struct termios *t) { TERMIOS_DEBUG_PRINT("c_oflag: "); int val = (t->c_cflag & CBAUD); if (val & CBAUDEX) { val &= ~CBAUDEX; PRINT_IFEQ(val, B57600); PRINT_IFEQ(val, B115200); PRINT_IFEQ(val, B230400); PRINT_IFEQ(val, B460800); PRINT_IFEQ(val, B500000); PRINT_IFEQ(val, B576000); PRINT_IFEQ(val, B921600); PRINT_IFEQ(val, B1000000); PRINT_IFEQ(val, B1152000); PRINT_IFEQ(val, B1500000); PRINT_IFEQ(val, B2000000); PRINT_IFEQ(val, B2500000); PRINT_IFEQ(val, B3000000); PRINT_IFEQ(val, B3500000); PRINT_IFEQ(val, B4000000); } else { PRINT_IFEQ(val, B0); PRINT_IFEQ(val, B50); PRINT_IFEQ(val, B75); PRINT_IFEQ(val, B110); PRINT_IFEQ(val, B134); PRINT_IFEQ(val, B150); PRINT_IFEQ(val, B200); PRINT_IFEQ(val, B300); PRINT_IFEQ(val, B600); PRINT_IFEQ(val, B1200); PRINT_IFEQ(val, B1800); PRINT_IFEQ(val, B2400); PRINT_IFEQ(val, B4800); PRINT_IFEQ(val, B9600); PRINT_IFEQ(val, B19200); PRINT_IFEQ(val, B38400); } val = t->c_cflag & CSIZE; PRINT_IFEQ(val, CS5); PRINT_IFEQ(val, CS6); PRINT_IFEQ(val, CS7); PRINT_IFEQ(val, CS8); PRINT_FLAG(t->c_cflag, CSTOPB); PRINT_FLAG(t->c_cflag, CREAD); PRINT_FLAG(t->c_cflag, PARENB); PRINT_FLAG(t->c_cflag, PARODD); PRINT_FLAG(t->c_cflag, HUPCL); PRINT_FLAG(t->c_cflag, CLOCAL); PRINT_FLAG(t->c_cflag, CIBAUD); // mask PRINT_FLAG(t->c_cflag, CMSPAR); PRINT_FLAG(t->c_cflag, CRTSCTS); TERMIOS_DEBUG_PRINT("\n"); } static void dump_c_lflag(struct termios *t) { TERMIOS_DEBUG_PRINT("c_lflag: "); PRINT_FLAG(t->c_lflag, ISIG); PRINT_FLAG(t->c_lflag, ICANON); PRINT_FLAG(t->c_lflag, XCASE); PRINT_FLAG(t->c_lflag, ECHO); PRINT_FLAG(t->c_lflag, ECHOE); PRINT_FLAG(t->c_lflag, ECHOK); PRINT_FLAG(t->c_lflag, ECHONL); PRINT_FLAG(t->c_lflag, ECHOCTL); PRINT_FLAG(t->c_lflag, ECHOPRT); PRINT_FLAG(t->c_lflag, ECHOKE); PRINT_FLAG(t->c_lflag, FLUSHO); PRINT_FLAG(t->c_lflag, NOFLSH); PRINT_FLAG(t->c_lflag, TOSTOP); PRINT_FLAG(t->c_lflag, PENDIN); PRINT_FLAG(t->c_lflag, IEXTEN); TERMIOS_DEBUG_PRINT("\n"); } static const char *get_cc_name(cc_t cc) { #define CC_ENTRY(e) [e] = #e static const char *cc_names[NCCS] = { CC_ENTRY(VINTR), CC_ENTRY(VQUIT), CC_ENTRY(VERASE), CC_ENTRY(VKILL), CC_ENTRY(VEOF), CC_ENTRY(VTIME), CC_ENTRY(VMIN), CC_ENTRY(VSWTC), CC_ENTRY(VSTART), CC_ENTRY(VSTOP), CC_ENTRY(VSUSP), CC_ENTRY(VEOL), CC_ENTRY(VREPRINT), CC_ENTRY(VDISCARD), CC_ENTRY(VWERASE), CC_ENTRY(VLNEXT), CC_ENTRY(VEOL2), }; #undef CC_ENTRY return cc_names[cc]; } static void dump_c_cc(struct termios *t) { TERMIOS_DEBUG_PRINT("c_cc: \n"); for (u8 i = 0; i < NCCS; i++) { const char *name = get_cc_name(i); if (name) TERMIOS_DEBUG_PRINT("[%-12s]: 0x%x\n", name, t->c_cc[i]); else TERMIOS_DEBUG_PRINT("[%-12d]: 0x%x\n", i, t->c_cc[i]); } TERMIOS_DEBUG_PRINT("\n"); } static void debug_dump_termios(struct termios *t) { dump_c_iflag(t); dump_c_oflag(t); dump_c_cflag(t); dump_c_lflag(t); dump_c_cc(t); } #undef PRINT_FLAG #undef TERMIOS_DEBUG_PRINT <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "defs.h" #define CHECK(cond) \ do { \ if (!(cond)) { \ Print(L"CHECK '%a' FAILED\n", #cond); \ status = EFI_LOAD_ERROR; \ goto end; \ } \ } while(0) #define HANDLE_EFI_ERROR(op) \ do { \ if (EFI_ERROR(status)) { \ Print(L"[%a] Error: %r\n", op, status); \ goto end; \ } \ } while (0) void JumpToKernel(void *entry_point); EFI_STATUS GetMemoryMap(UINTN *mapkey); EFI_MEMORY_DESCRIPTOR * GetMemDescForAddress(EFI_PHYSICAL_ADDRESS paddr); EFI_STATUS KernelLoadMemoryChecks(void); EFI_INPUT_KEY WaitForKeyPress(void); EFI_STATUS LoadFileFromDisk(EFI_FILE_PROTOCOL *fileProt, EFI_PHYSICAL_ADDRESS *paddr, UINTN *fileSz, CHAR16 *filePath); void ShowProgress(SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut, const CHAR16 *PrefixStr, UINTN curr, UINTN tot); EFI_STATUS ReadDiskWithProgress(SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut, const CHAR16 *loadingStr, EFI_BLOCK_IO_PROTOCOL *blockio, UINT64 Offset, UINTN BufferSize, void *Buffer); EFI_STATUS ReadAlignedBlock(EFI_BLOCK_IO_PROTOCOL *blockio, UINTN offset, /* offset in bytes, aligned to blockSize */ UINTN len, /* length in bytes, aligned to blockSize */ void *buf); EFI_DEVICE_PATH * DevicePathGetLastValidNode(EFI_DEVICE_PATH *dp); void TruncateDevicePath(EFI_DEVICE_PATH *dp); EFI_DEVICE_PATH * GetCopyOfParentDevicePathNode(EFI_DEVICE_PATH *dp); EFI_STATUS GetHandlerForDevicePath(EFI_DEVICE_PATH *dp, EFI_GUID *supportedProt, EFI_HANDLE *refHandle); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #ifndef USERMODE_APP #define PRINTK_FL_DEFAULT 0 #define PRINTK_FL_NO_PREFIX 1 ATTR_PRINTF_LIKE(1) void printk(const char *fmt, ...); #if defined(__TILCK_KERNEL__) || defined(UNIT_TEST_ENVIRONMENT) #define PRINTK_CTRL_CHAR '\x01' void tilck_vprintk(u32 flags, const char *fmt, va_list args); static inline void vprintk(const char *fmt, va_list args) { tilck_vprintk(PRINTK_FL_DEFAULT, fmt, args); } int vsnprintk(char *buf, size_t size, const char *fmt, va_list args); int snprintk(char *buf, size_t size, const char *fmt, ...); void printk_flush_ringbuf(void); #else /* Legacy bootloader's basic_printk doesn't have `flags` */ void vprintk(const char *fmt, va_list args); #endif #ifndef UNIT_TEST_ENVIRONMENT #define NO_PREFIX "\x01\x01\x20\x20" #else #define NO_PREFIX "" #endif #else /* * Code in `common/` such as fat32_base.c is used also in user apps like * fathack.c and it will be great to be able to printk there as well instead * of using dirty #ifdef USERMODE_APP switches to decide whether to use printk * or printf. */ #include <stdio.h> #define printk printf #define vprintk vprintf /* * NOTE: not including snprintk() because it's available only for the kernel * itself, not in the `common` code. See basic_printk.c, the one used for the * `common` code. */ #endif // #ifndef USERMODE_APP <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #ifdef __FPU_MEMCPY_C__ #define EXTERN extern #else #define EXTERN #endif /* * ----------------------------------------------- * * Extra performant memcpy versions * * ----------------------------------------------- */ void fpu_memcpy256_avx2(void *dest, const void *src, u32 n); void fpu_memcpy256_sse2(void *dest, const void *src, u32 n); void fpu_memcpy256_sse(void *dest, const void *src, u32 n); /* Non-temporal hint for the destination */ void fpu_memcpy256_nt_avx2(void *dest, const void *src, u32 n); void fpu_memcpy256_nt_sse2(void *dest, const void *src, u32 n); void fpu_memcpy256_nt_sse(void *dest, const void *src, u32 n); /* Non-temporal hint for the source */ void fpu_memcpy256_nt_read_avx2(void *dest, const void *src, u32 n); void fpu_memcpy256_nt_read_sse4_1(void *dest, const void *src, u32 n); /* Memset */ void fpu_memset256_sse2(void *dest, u32 val32, u32 n); void fpu_memset256_avx2(void *dest, u32 val32, u32 n); EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_nt_avx2(void *dest, const void *src) { asmVolatile("vmovdqa (%0), %%ymm0\n\t" "vmovdqa 32(%0), %%ymm1\n\t" "vmovntdq %%ymm0, (%1)\n\t" "vmovntdq %%ymm1, 32(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_nt_read_avx2(void *dest, const void *src) { asmVolatile("vmovntdqa (%0), %%ymm0\n\t" "vmovntdqa 32(%0), %%ymm1\n\t" "vmovdqa %%ymm0, (%1)\n\t" "vmovdqa %%ymm1, 32(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_avx2(void *dest, const void *src) { asmVolatile("vmovdqa (%0), %%ymm0\n\t" "vmovdqa 32(%0), %%ymm1\n\t" "vmovdqa %%ymm0, (%1)\n\t" "vmovdqa %%ymm1, 32(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_avx2(void *dest, const void *src) { asmVolatile("vmovdqa (%0), %%ymm0\n\t" "vmovntdq %%ymm0, (%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_read_avx2(void *dest, const void *src) { asmVolatile("vmovntdqa (%0), %%ymm0\n\t" "vmovdqa %%ymm0, (%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_avx2(void *dest, const void *src) { asmVolatile("vmovdqa (%0), %%ymm0\n\t" "vmovdqa %%ymm0, (%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_nt_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movdqa 16(%0), %%xmm1\n\t" "movdqa 32(%0), %%xmm2\n\t" "movdqa 48(%0), %%xmm3\n\t" "movntdq %%xmm0, (%1)\n\t" "movntdq %%xmm1, 16(%1)\n\t" "movntdq %%xmm2, 32(%1)\n\t" "movntdq %%xmm3, 48(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movdqa 16(%0), %%xmm1\n\t" "movdqa 32(%0), %%xmm2\n\t" "movdqa 48(%0), %%xmm3\n\t" "movdqa %%xmm0, (%1)\n\t" "movdqa %%xmm1, 16(%1)\n\t" "movdqa %%xmm2, 32(%1)\n\t" "movdqa %%xmm3, 48(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_512_nt_read_sse4_1(void *dest, const void *src) { asmVolatile("movntdqa (%0), %%xmm0\n\t" "movntdqa 16(%0), %%xmm1\n\t" "movntdqa 32(%0), %%xmm2\n\t" "movntdqa 48(%0), %%xmm3\n\t" "movdqa %%xmm0, (%1)\n\t" "movdqa %%xmm1, 16(%1)\n\t" "movdqa %%xmm2, 32(%1)\n\t" "movdqa %%xmm3, 48(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_read_sse4_1(void *dest, const void *src) { asmVolatile("movntdqa (%0), %%xmm0\n\t" "movntdqa 16(%0), %%xmm1\n\t" "movdqa %%xmm0, (%1)\n\t" "movdqa %%xmm1, 16(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movdqa 16(%0), %%xmm1\n\t" "movntdq %%xmm0, (%1)\n\t" "movntdq %%xmm1, 16(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movdqa 16(%0), %%xmm1\n\t" "movdqa %%xmm0, (%1)\n\t" "movdqa %%xmm1, 16(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_128_nt_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movntdq %%xmm0, (%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_128_sse2(void *dest, const void *src) { asmVolatile("movdqa (%0), %%xmm0\n\t" "movdqa %%xmm0, (%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_sse(void *dest, const void *src) { asmVolatile("movq (%0), %%mm0\n\t" "movq 8(%0), %%mm1\n\t" "movq 16(%0), %%mm2\n\t" "movq 24(%0), %%mm3\n\t" "movntq %%mm0, (%1)\n\t" "movntq %%mm1, 8(%1)\n\t" "movntq %%mm2, 16(%1)\n\t" "movntq %%mm3, 24(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_sse(void *dest, const void *src) { asmVolatile("movq (%0), %%mm0\n\t" "movq 8(%0), %%mm1\n\t" "movq 16(%0), %%mm2\n\t" "movq 24(%0), %%mm3\n\t" "movq %%mm0, (%1)\n\t" "movq %%mm1, 8(%1)\n\t" "movq %%mm2, 16(%1)\n\t" "movq %%mm3, 24(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_128_nt_sse(void *dest, const void *src) { asmVolatile("movq (%0), %%mm0\n\t" "movq 8(%0), %%mm1\n\t" "movntq %%mm0, (%1)\n\t" "movntq %%mm1, 8(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_128_sse(void *dest, const void *src) { asmVolatile("movq (%0), %%mm0\n\t" "movq 8(%0), %%mm1\n\t" "movq %%mm0, (%1)\n\t" "movq %%mm1, 8(%1)\n\t" : /* no output */ : "r" (src), "r" (dest) : "memory"); } void memcpy256_failsafe(void *dest, const void *src, u32 n); FASTCALL void memcpy_single_256_failsafe(void *dest, const void *src); /* Non-temporal hint for the destination */ /* 'n' is the number of 32-byte (256-bit) data packets to copy */ EXTERN inline void fpu_memcpy256_nt(void *dest, const void *src, u32 n) { if (x86_cpu_features.can_use_avx2) fpu_memcpy256_nt_avx2(dest, src, n); else if (x86_cpu_features.can_use_sse2) fpu_memcpy256_nt_sse2(dest, src, n); else if (x86_cpu_features.can_use_sse) fpu_memcpy256_nt_sse(dest, src, n); else memcpy256_failsafe(dest, src, n); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ EXTERN inline void fpu_memcpy256(void *dest, const void *src, u32 n) { if (x86_cpu_features.can_use_avx2) fpu_memcpy256_avx2(dest, src, n); else if (x86_cpu_features.can_use_sse2) fpu_memcpy256_sse2(dest, src, n); else if (x86_cpu_features.can_use_sse) fpu_memcpy256_sse(dest, src, n); else memcpy256_failsafe(dest, src, n); } /* Non-temporal hint for the source */ /* 'n' is the number of 32-byte (256-bit) data packets to copy */ EXTERN inline void fpu_memcpy256_nt_read(void *dest, const void *src, u32 n) { if (x86_cpu_features.can_use_avx2) fpu_memcpy256_nt_read_avx2(dest, src, n); else if (x86_cpu_features.can_use_sse4_1) fpu_memcpy256_nt_read_sse4_1(dest, src, n); else if (x86_cpu_features.can_use_sse2) fpu_memcpy256_sse2(dest, src, n); else if (x86_cpu_features.can_use_sse) fpu_memcpy256_sse(dest, src, n); else memcpy256_failsafe(dest, src, n); } EXTERN inline void fpu_memset256(void *dest, u32 val32, u32 n) { if (x86_cpu_features.can_use_avx2) fpu_memset256_avx2(dest, val32, n); else if (x86_cpu_features.can_use_sse2) fpu_memset256_sse2(dest, val32, n); else memset(dest, (int)val32, n << 5); } void FASTCALL __asm_fpu_cpy_single_256_nt(void *dest, const void *src); void FASTCALL __asm_fpu_cpy_single_256_nt_read(void *dest, const void *src); EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt(void *dest, const void *src) { __asm_fpu_cpy_single_256_nt(dest, src); } EXTERN ALWAYS_INLINE FASTCALL void fpu_cpy_single_256_nt_read(void *dest, const void *src) { __asm_fpu_cpy_single_256_nt_read(dest, src); } void init_fpu_memcpy(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <cstdio> #include <iostream> #include <memory> #include <map> #include <gtest/gtest.h> #include "kernel_init_funcs.h" extern "C" { #include <tilck/kernel/fs/fat32.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/common/utils.h> #include <tilck/kernel/test/fat32.h> #include <3rd_party/crc32.h> } using namespace std; void test_dump_buf(char *buf, const char *buf_name, int off, int count) { printf("%s", buf_name); for (int k = 0; k < count; k++) printf("%02x ", (unsigned char) buf[off + k]); printf("\n"); } static void fat32_read_compare_bufs(ssize_t bytes_read, ssize_t roff, char *b1, char *b2) { for (int j = 0; j < bytes_read; j++) { if (b1[j] != b2[j]) { printf("Byte #%li differs:\n", (long)roff+j); test_dump_buf(b1, "buf1: ", j, 16); test_dump_buf(b2, "buf2: ", j, 16); FAIL(); } } } const char *load_once_file(const char *filepath, size_t *fsize = nullptr) { static map<const char *, pair<unique_ptr<const char[]>, size_t>> files_loaded; auto it = files_loaded.find(filepath); if (it == files_loaded.end()) { long file_size; char *buf; FILE *fp; fp = fopen(filepath, "rb"); assert(fp != nullptr); fseek(fp, 0, SEEK_END); file_size = ftell(fp); buf = new char [file_size]; assert(buf != nullptr); fseek(fp, 0, SEEK_SET); ssize_t bytes_read = fread(buf, 1, file_size, fp); assert(bytes_read == file_size); (void)bytes_read; fclose(fp); auto &e = files_loaded[filepath]; e.first.reset(buf); e.second = file_size; } auto &e = files_loaded[filepath]; if (fsize) *fsize = e.second; return e.first.get(); } TEST(fat32, DISABLED_dumpinfo) { const char *buf = load_once_file(PROJ_BUILD_DIR "/test_fatpart"); fat_dump_info((void *) buf); struct fat_hdr *hdr = (struct fat_hdr *)buf; struct fat_entry *e = fat_search_entry(hdr, fat_unknown, "/nonesistentfile", NULL); ASSERT_TRUE(e == NULL); } TEST(fat32, read_content_of_shortname_file) { const char *buf = load_once_file(PROJ_BUILD_DIR "/test_fatpart"); char data[128] = {0}; struct fat_hdr *hdr; struct fat_entry *e; hdr = (struct fat_hdr *)buf; e = fat_search_entry(hdr, fat_unknown, "/testdir/dir1/f1", NULL); ASSERT_TRUE(e != NULL); fat_read_whole_file(hdr, e, data, sizeof(data)); ASSERT_STREQ("hello world!\n", data); } TEST(fat32, read_content_of_longname_file) { const char *buf = load_once_file(PROJ_BUILD_DIR "/test_fatpart"); char data[128] = {0}; struct fat_hdr *hdr; struct fat_entry *e; hdr = (struct fat_hdr *)buf; e = fat_search_entry(hdr, fat_unknown, "/testdir/This_is_a_file_with_a_veeeery_long_name.txt", NULL); ASSERT_TRUE(e != NULL); fat_read_whole_file(hdr, e, data, sizeof(data)); ASSERT_STREQ("Content of file with a long name\n", data); } TEST(fat32, read_whole_file) { struct fat_hdr *hdr = (struct fat_hdr *) load_once_file(PROJ_BUILD_DIR "/test_fatpart"); struct fat_entry *e = fat_search_entry(hdr, fat_unknown, "/bigfile", NULL); char *content = (char *)calloc(1, e->DIR_FileSize); fat_read_whole_file(hdr, e, content, e->DIR_FileSize); uint32_t fat_crc = crc32(0, content, e->DIR_FileSize); free(content); size_t fsize; const char *buf = load_once_file(PROJ_BUILD_DIR "/test_sysroot/bigfile", &fsize); uint32_t actual_file_crc = crc32(0, buf, fsize); ASSERT_EQ(fat_crc, actual_file_crc); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/string_util.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/errno.h> static void drop_last_component(char **d_ref, char *const dest) { char *d = *d_ref; d--; /* go back to the last written char */ ASSERT(*d == '/'); while (d > dest + 1) { *d-- = 0; if (*d == '/') { d++; /* * advance 'd' before breaking: it points to the next dest * char, not to the last written one. */ break; } } *d_ref = d; } int compute_abs_path(const char *path, const char *str_cwd, char *dest, u32 dest_s) { const char *p; char *d = dest; ASSERT(*str_cwd == '/'); if (!*path) return -ENOENT; if (*path != '/') { u32 cl = (u32)strlen(str_cwd); ASSERT(cl > 0); /* The current working directory is ALWAYS supposed to be ending in '/' */ ASSERT(str_cwd[cl - 1] == '/'); if (dest_s < strlen(path) + cl + 1) return -ENAMETOOLONG; memcpy(dest, str_cwd, cl + 1); d = dest + cl; } else { /* path is absolute */ if (dest_s < strlen(path) + 1) return -ENAMETOOLONG; } for (p = path; *p;) { if (*p == '/' && p[1] == '/') { p++; continue; /* skip multiple slashes */ } if (*p != '.') goto copy_char; /* the current character, *p, is '.' */ if (d > dest && d[-1] != '/') goto copy_char; if (p[1] == '/' || !p[1]) { p++; // skip '.' if (*p) // the path does NOT end here p++; continue; } else if (p[1] == '.' && (p[2] == '/' || !p[2])) { ASSERT(d > dest); if (d > dest + 1) drop_last_component(&d, dest); /* * else * dest == "/": we cannot go past that */ p += 2; /* skip ".." */ if (*p) // the path does NOT end here p++; continue; } else { copy_char: *d++ = *p++; /* default case: just copy the character */ } } ASSERT(d > dest); if (d > dest + 1 && d[-1] == '/') { if (p[-1] != '/') { /* drop the trailing '/' only if the user path did NOT end with '/' */ d--; } } ASSERT(d > dest); // dest must contain at least 1 char, '/'. *d = 0; return 0; } <file_sep> Use of atomics in Tilck --------------------------- Being Tilck a non-SMP kernel, apparently, it should never need to use atomics. Actually, that's not true. While it is true that there no need for any type of *sequential consistency* in a non-SMP kernel, the need for simple atomicity remains in order to the kernel to be portable. While on i386 and on x86_64 the load/store operations on pointer-size variables are inherently atomic (but again, without sequential consistency guaratees), on other architectures, typically RISC ones, that's simply not true. There, it might be even necessary to use two instructions to store a 32-bit immediate value to a memory location. Because of that, for variables that need to be accessed also from interrupt context or for variables that are shared across multiple tasks (ref-counts), C11 atomics are used with the memory-model parameter set to *relaxed*. With the *relaxed* memory-model, on architectures like x86, the atomic load/store operations will be translated into simple `MOV` instructions, as if there was no involvment with atomic semantics at all while, on other architectures, special instructions for atomics will be used. Why we need simply atomicity for certain variables: examples ------------------------------------------------------------- Think about a variable like `__disable_preempt`, used both in regular code and in interrupt handlers. Now imagine that it takes two separate instructions to store a value into it. What happens if an IRQs gets delivered after the first instruction, but before the second one? Well get a *corrupt* value for the variable and everything will get messed up. The same example applies for reference count variables used in objects shared across all the tasks in the system (like fs objects). What happens if, in the middle of a non-atomic store to such reference count, the task gets preempted by the scheduler and another task to made to run? We'll get a corrupted value. Volatile vs Atomic --------------------- Please note that the following implications are *not* true: - volatile -> atomic - atomic -> volatile Therefore, it makes sense to have: - atomic variables which are *not* also volatile - volatile variables which are *not* also atomic - volatile atomic variables An example: the `state` field in `struct task`. It needs to be *atomic* because its value can be read and updated by interrupt handlers (see `wth.c`), but it also needs to be *volatile* because it is read in loops (see `sys_waitpid`) waiting for it to change. Theoretically, in case of consecutive atomic loads, the compiler is *not* obliged to perform every time an actual read and it might cache the value in a register, according to the C11 atomics model. <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void init_bt(void); void bt_write_char(char c); void bt_setcolor(u8 color); void bt_movecur(int row, int col); u16 bt_get_curr_row(void); u16 bt_get_curr_col(void); <file_sep>/******************************************************************************* * * Module Name: rsmisc - Miscellaneous resource descriptors * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acresrc.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME ("rsmisc") #define INIT_RESOURCE_TYPE(i) i->ResourceOffset #define INIT_RESOURCE_LENGTH(i) i->AmlOffset #define INIT_TABLE_LENGTH(i) i->Value #define COMPARE_OPCODE(i) i->ResourceOffset #define COMPARE_TARGET(i) i->AmlOffset #define COMPARE_VALUE(i) i->Value /******************************************************************************* * * FUNCTION: AcpiRsConvertAmlToResource * * PARAMETERS: Resource - Pointer to the resource descriptor * Aml - Where the AML descriptor is returned * Info - Pointer to appropriate conversion table * * RETURN: Status * * DESCRIPTION: Convert an external AML resource descriptor to the corresponding * internal resource descriptor * ******************************************************************************/ ACPI_STATUS AcpiRsConvertAmlToResource ( ACPI_RESOURCE *Resource, AML_RESOURCE *Aml, ACPI_RSCONVERT_INFO *Info) { ACPI_RS_LENGTH AmlResourceLength; void *Source; void *Destination; char *Target; UINT8 Count; UINT8 FlagsMode = FALSE; UINT16 ItemCount = 0; UINT16 Temp16 = 0; ACPI_FUNCTION_TRACE (RsConvertAmlToResource); if (!Info) { return_ACPI_STATUS (AE_BAD_PARAMETER); } if (((ACPI_SIZE) Resource) & 0x3) { /* Each internal resource struct is expected to be 32-bit aligned */ ACPI_WARNING ((AE_INFO, "Misaligned resource pointer (get): %p Type 0x%2.2X Length %u", Resource, Resource->Type, Resource->Length)); } /* Extract the resource Length field (does not include header length) */ AmlResourceLength = AcpiUtGetResourceLength (Aml); /* * First table entry must be ACPI_RSC_INITxxx and must contain the * table length (# of table entries) */ Count = INIT_TABLE_LENGTH (Info); while (Count) { /* * Source is the external AML byte stream buffer, * destination is the internal resource descriptor */ Source = ACPI_ADD_PTR (void, Aml, Info->AmlOffset); Destination = ACPI_ADD_PTR (void, Resource, Info->ResourceOffset); switch (Info->Opcode) { case ACPI_RSC_INITGET: /* * Get the resource type and the initial (minimum) length */ memset (Resource, 0, INIT_RESOURCE_LENGTH (Info)); Resource->Type = INIT_RESOURCE_TYPE (Info); Resource->Length = INIT_RESOURCE_LENGTH (Info); break; case ACPI_RSC_INITSET: break; case ACPI_RSC_FLAGINIT: FlagsMode = TRUE; break; case ACPI_RSC_1BITFLAG: /* * Mask and shift the flag bit */ ACPI_SET8 (Destination, ((ACPI_GET8 (Source) >> Info->Value) & 0x01)); break; case ACPI_RSC_2BITFLAG: /* * Mask and shift the flag bits */ ACPI_SET8 (Destination, ((ACPI_GET8 (Source) >> Info->Value) & 0x03)); break; case ACPI_RSC_3BITFLAG: /* * Mask and shift the flag bits */ ACPI_SET8 (Destination, ((ACPI_GET8 (Source) >> Info->Value) & 0x07)); break; case ACPI_RSC_COUNT: ItemCount = ACPI_GET8 (Source); ACPI_SET8 (Destination, ItemCount); Resource->Length = Resource->Length + (Info->Value * (ItemCount - 1)); break; case ACPI_RSC_COUNT16: ItemCount = AmlResourceLength; ACPI_SET16 (Destination, ItemCount); Resource->Length = Resource->Length + (Info->Value * (ItemCount - 1)); break; case ACPI_RSC_COUNT_GPIO_PIN: Target = ACPI_ADD_PTR (void, Aml, Info->Value); ItemCount = ACPI_GET16 (Target) - ACPI_GET16 (Source); Resource->Length = Resource->Length + ItemCount; ItemCount = ItemCount / 2; ACPI_SET16 (Destination, ItemCount); break; case ACPI_RSC_COUNT_GPIO_VEN: ItemCount = ACPI_GET8 (Source); ACPI_SET8 (Destination, ItemCount); Resource->Length = Resource->Length + (Info->Value * ItemCount); break; case ACPI_RSC_COUNT_GPIO_RES: /* * Vendor data is optional (length/offset may both be zero) * Examine vendor data length field first */ Target = ACPI_ADD_PTR (void, Aml, (Info->Value + 2)); if (ACPI_GET16 (Target)) { /* Use vendor offset to get resource source length */ Target = ACPI_ADD_PTR (void, Aml, Info->Value); ItemCount = ACPI_GET16 (Target) - ACPI_GET16 (Source); } else { /* No vendor data to worry about */ ItemCount = Aml->LargeHeader.ResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER) - ACPI_GET16 (Source); } Resource->Length = Resource->Length + ItemCount; ACPI_SET16 (Destination, ItemCount); break; case ACPI_RSC_COUNT_SERIAL_VEN: ItemCount = ACPI_GET16 (Source) - Info->Value; Resource->Length = Resource->Length + ItemCount; ACPI_SET16 (Destination, ItemCount); break; case ACPI_RSC_COUNT_SERIAL_RES: ItemCount = (AmlResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER)) - ACPI_GET16 (Source) - Info->Value; Resource->Length = Resource->Length + ItemCount; ACPI_SET16 (Destination, ItemCount); break; case ACPI_RSC_LENGTH: Resource->Length = Resource->Length + Info->Value; break; case ACPI_RSC_MOVE8: case ACPI_RSC_MOVE16: case ACPI_RSC_MOVE32: case ACPI_RSC_MOVE64: /* * Raw data move. Use the Info value field unless ItemCount has * been previously initialized via a COUNT opcode */ if (Info->Value) { ItemCount = Info->Value; } AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_GPIO_PIN: /* Generate and set the PIN data pointer */ Target = (char *) ACPI_ADD_PTR (void, Resource, (Resource->Length - ItemCount * 2)); *(UINT16 **) Destination = ACPI_CAST_PTR (UINT16, Target); /* Copy the PIN data */ Source = ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Source)); AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_GPIO_RES: /* Generate and set the ResourceSource string pointer */ Target = (char *) ACPI_ADD_PTR (void, Resource, (Resource->Length - ItemCount)); *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target); /* Copy the ResourceSource string */ Source = ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Source)); AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_SERIAL_VEN: /* Generate and set the Vendor Data pointer */ Target = (char *) ACPI_ADD_PTR (void, Resource, (Resource->Length - ItemCount)); *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target); /* Copy the Vendor Data */ Source = ACPI_ADD_PTR (void, Aml, Info->Value); AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_SERIAL_RES: /* Generate and set the ResourceSource string pointer */ Target = (char *) ACPI_ADD_PTR (void, Resource, (Resource->Length - ItemCount)); *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target); /* Copy the ResourceSource string */ Source = ACPI_ADD_PTR ( void, Aml, (ACPI_GET16 (Source) + Info->Value)); AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_SET8: memset (Destination, Info->AmlOffset, Info->Value); break; case ACPI_RSC_DATA8: Target = ACPI_ADD_PTR (char, Resource, Info->Value); memcpy (Destination, Source, ACPI_GET16 (Target)); break; case ACPI_RSC_ADDRESS: /* * Common handler for address descriptor flags */ if (!AcpiRsGetAddressCommon (Resource, Aml)) { return_ACPI_STATUS (AE_AML_INVALID_RESOURCE_TYPE); } break; case ACPI_RSC_SOURCE: /* * Optional ResourceSource (Index and String) */ Resource->Length += AcpiRsGetResourceSource (AmlResourceLength, Info->Value, Destination, Aml, NULL); break; case ACPI_RSC_SOURCEX: /* * Optional ResourceSource (Index and String). This is the more * complicated case used by the Interrupt() macro */ Target = ACPI_ADD_PTR (char, Resource, Info->AmlOffset + (ItemCount * 4)); Resource->Length += AcpiRsGetResourceSource (AmlResourceLength, (ACPI_RS_LENGTH) (((ItemCount - 1) * sizeof (UINT32)) + Info->Value), Destination, Aml, Target); break; case ACPI_RSC_BITMASK: /* * 8-bit encoded bitmask (DMA macro) */ ItemCount = AcpiRsDecodeBitmask (ACPI_GET8 (Source), Destination); if (ItemCount) { Resource->Length += (ItemCount - 1); } Target = ACPI_ADD_PTR (char, Resource, Info->Value); ACPI_SET8 (Target, ItemCount); break; case ACPI_RSC_BITMASK16: /* * 16-bit encoded bitmask (IRQ macro) */ ACPI_MOVE_16_TO_16 (&Temp16, Source); ItemCount = AcpiRsDecodeBitmask (Temp16, Destination); if (ItemCount) { Resource->Length += (ItemCount - 1); } Target = ACPI_ADD_PTR (char, Resource, Info->Value); ACPI_SET8 (Target, ItemCount); break; case ACPI_RSC_EXIT_NE: /* * Control - Exit conversion if not equal */ switch (Info->ResourceOffset) { case ACPI_RSC_COMPARE_AML_LENGTH: if (AmlResourceLength != Info->Value) { goto Exit; } break; case ACPI_RSC_COMPARE_VALUE: if (ACPI_GET8 (Source) != Info->Value) { goto Exit; } break; default: ACPI_ERROR ((AE_INFO, "Invalid conversion sub-opcode")); return_ACPI_STATUS (AE_BAD_PARAMETER); } break; default: ACPI_ERROR ((AE_INFO, "Invalid conversion opcode")); return_ACPI_STATUS (AE_BAD_PARAMETER); } Count--; Info++; } Exit: if (!FlagsMode) { /* Round the resource struct length up to the next boundary (32 or 64) */ Resource->Length = (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (Resource->Length); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiRsConvertResourceToAml * * PARAMETERS: Resource - Pointer to the resource descriptor * Aml - Where the AML descriptor is returned * Info - Pointer to appropriate conversion table * * RETURN: Status * * DESCRIPTION: Convert an internal resource descriptor to the corresponding * external AML resource descriptor. * ******************************************************************************/ ACPI_STATUS AcpiRsConvertResourceToAml ( ACPI_RESOURCE *Resource, AML_RESOURCE *Aml, ACPI_RSCONVERT_INFO *Info) { void *Source = NULL; void *Destination; char *Target; ACPI_RSDESC_SIZE AmlLength = 0; UINT8 Count; UINT16 Temp16 = 0; UINT16 ItemCount = 0; ACPI_FUNCTION_TRACE (RsConvertResourceToAml); if (!Info) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* * First table entry must be ACPI_RSC_INITxxx and must contain the * table length (# of table entries) */ Count = INIT_TABLE_LENGTH (Info); while (Count) { /* * Source is the internal resource descriptor, * destination is the external AML byte stream buffer */ Source = ACPI_ADD_PTR (void, Resource, Info->ResourceOffset); Destination = ACPI_ADD_PTR (void, Aml, Info->AmlOffset); switch (Info->Opcode) { case ACPI_RSC_INITSET: memset (Aml, 0, INIT_RESOURCE_LENGTH (Info)); AmlLength = INIT_RESOURCE_LENGTH (Info); AcpiRsSetResourceHeader ( INIT_RESOURCE_TYPE (Info), AmlLength, Aml); break; case ACPI_RSC_INITGET: break; case ACPI_RSC_FLAGINIT: /* * Clear the flag byte */ ACPI_SET8 (Destination, 0); break; case ACPI_RSC_1BITFLAG: /* * Mask and shift the flag bit */ ACPI_SET_BIT (*ACPI_CAST8 (Destination), (UINT8) ((ACPI_GET8 (Source) & 0x01) << Info->Value)); break; case ACPI_RSC_2BITFLAG: /* * Mask and shift the flag bits */ ACPI_SET_BIT (*ACPI_CAST8 (Destination), (UINT8) ((ACPI_GET8 (Source) & 0x03) << Info->Value)); break; case ACPI_RSC_3BITFLAG: /* * Mask and shift the flag bits */ ACPI_SET_BIT (*ACPI_CAST8 (Destination), (UINT8) ((ACPI_GET8 (Source) & 0x07) << Info->Value)); break; case ACPI_RSC_COUNT: ItemCount = ACPI_GET8 (Source); ACPI_SET8 (Destination, ItemCount); AmlLength = (UINT16) (AmlLength + (Info->Value * (ItemCount - 1))); break; case ACPI_RSC_COUNT16: ItemCount = ACPI_GET16 (Source); AmlLength = (UINT16) (AmlLength + ItemCount); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_COUNT_GPIO_PIN: ItemCount = ACPI_GET16 (Source); ACPI_SET16 (Destination, AmlLength); AmlLength = (UINT16) (AmlLength + ItemCount * 2); Target = ACPI_ADD_PTR (void, Aml, Info->Value); ACPI_SET16 (Target, AmlLength); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_COUNT_GPIO_VEN: ItemCount = ACPI_GET16 (Source); ACPI_SET16 (Destination, ItemCount); AmlLength = (UINT16) ( AmlLength + (Info->Value * ItemCount)); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_COUNT_GPIO_RES: /* Set resource source string length */ ItemCount = ACPI_GET16 (Source); ACPI_SET16 (Destination, AmlLength); /* Compute offset for the Vendor Data */ AmlLength = (UINT16) (AmlLength + ItemCount); Target = ACPI_ADD_PTR (void, Aml, Info->Value); /* Set vendor offset only if there is vendor data */ ACPI_SET16 (Target, AmlLength); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_COUNT_SERIAL_VEN: ItemCount = ACPI_GET16 (Source); ACPI_SET16 (Destination, ItemCount + Info->Value); AmlLength = (UINT16) (AmlLength + ItemCount); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_COUNT_SERIAL_RES: ItemCount = ACPI_GET16 (Source); AmlLength = (UINT16) (AmlLength + ItemCount); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_LENGTH: AcpiRsSetResourceLength (Info->Value, Aml); break; case ACPI_RSC_MOVE8: case ACPI_RSC_MOVE16: case ACPI_RSC_MOVE32: case ACPI_RSC_MOVE64: if (Info->Value) { ItemCount = Info->Value; } AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_GPIO_PIN: Destination = (char *) ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Destination)); Source = * (UINT16 **) Source; AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_GPIO_RES: /* Used for both ResourceSource string and VendorData */ Destination = (char *) ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Destination)); Source = * (UINT8 **) Source; AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_SERIAL_VEN: Destination = (char *) ACPI_ADD_PTR (void, Aml, (AmlLength - ItemCount)); Source = * (UINT8 **) Source; AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_MOVE_SERIAL_RES: Destination = (char *) ACPI_ADD_PTR (void, Aml, (AmlLength - ItemCount)); Source = * (UINT8 **) Source; AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode); break; case ACPI_RSC_ADDRESS: /* Set the Resource Type, General Flags, and Type-Specific Flags */ AcpiRsSetAddressCommon (Aml, Resource); break; case ACPI_RSC_SOURCEX: /* * Optional ResourceSource (Index and String) */ AmlLength = AcpiRsSetResourceSource ( Aml, (ACPI_RS_LENGTH) AmlLength, Source); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_SOURCE: /* * Optional ResourceSource (Index and String). This is the more * complicated case used by the Interrupt() macro */ AmlLength = AcpiRsSetResourceSource (Aml, Info->Value, Source); AcpiRsSetResourceLength (AmlLength, Aml); break; case ACPI_RSC_BITMASK: /* * 8-bit encoded bitmask (DMA macro) */ ACPI_SET8 (Destination, AcpiRsEncodeBitmask (Source, *ACPI_ADD_PTR (UINT8, Resource, Info->Value))); break; case ACPI_RSC_BITMASK16: /* * 16-bit encoded bitmask (IRQ macro) */ Temp16 = AcpiRsEncodeBitmask ( Source, *ACPI_ADD_PTR (UINT8, Resource, Info->Value)); ACPI_MOVE_16_TO_16 (Destination, &Temp16); break; case ACPI_RSC_EXIT_LE: /* * Control - Exit conversion if less than or equal */ if (ItemCount <= Info->Value) { goto Exit; } break; case ACPI_RSC_EXIT_NE: /* * Control - Exit conversion if not equal */ switch (COMPARE_OPCODE (Info)) { case ACPI_RSC_COMPARE_VALUE: if (*ACPI_ADD_PTR (UINT8, Resource, COMPARE_TARGET (Info)) != COMPARE_VALUE (Info)) { goto Exit; } break; default: ACPI_ERROR ((AE_INFO, "Invalid conversion sub-opcode")); return_ACPI_STATUS (AE_BAD_PARAMETER); } break; case ACPI_RSC_EXIT_EQ: /* * Control - Exit conversion if equal */ if (*ACPI_ADD_PTR (UINT8, Resource, COMPARE_TARGET (Info)) == COMPARE_VALUE (Info)) { goto Exit; } break; default: ACPI_ERROR ((AE_INFO, "Invalid conversion opcode")); return_ACPI_STATUS (AE_BAD_PARAMETER); } Count--; Info++; } Exit: return_ACPI_STATUS (AE_OK); } #if 0 /* Previous resource validations */ if (Aml->ExtAddress64.RevisionID != AML_RESOURCE_EXTENDED_ADDRESS_REVISION) { return_ACPI_STATUS (AE_SUPPORT); } if (Resource->Data.StartDpf.PerformanceRobustness >= 3) { return_ACPI_STATUS (AE_AML_BAD_RESOURCE_VALUE); } if (((Aml->Irq.Flags & 0x09) == 0x00) || ((Aml->Irq.Flags & 0x09) == 0x09)) { /* * Only [ActiveHigh, EdgeSensitive] or [ActiveLow, LevelSensitive] * polarity/trigger interrupts are allowed (ACPI spec, section * "IRQ Format"), so 0x00 and 0x09 are illegal. */ ACPI_ERROR ((AE_INFO, "Invalid interrupt polarity/trigger in resource list, 0x%X", Aml->Irq.Flags)); return_ACPI_STATUS (AE_BAD_DATA); } Resource->Data.ExtendedIrq.InterruptCount = Temp8; if (Temp8 < 1) { /* Must have at least one IRQ */ return_ACPI_STATUS (AE_AML_BAD_RESOURCE_LENGTH); } if (Resource->Data.Dma.Transfer == 0x03) { ACPI_ERROR ((AE_INFO, "Invalid DMA.Transfer preference (3)")); return_ACPI_STATUS (AE_BAD_DATA); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/datetime.h> #define CMOS_CONTROL_PORT 0x70 #define CMOS_DATA_PORT 0x71 #define REG_SECONDS 0x00 #define REG_MINUTES 0x02 #define REG_HOURS 0x04 #define REG_WEEKDAY 0x06 #define REG_DAY 0x07 #define REG_MONTH 0x08 #define REG_YEAR 0x09 #define REG_STATUS_REG_A 0x0A #define REG_STATUS_REG_B 0x0B #define STATUS_REG_A_UPDATE_IN_PROGRESS 0x80 static inline u8 bcd_to_dec(u8 bcd) { return ((bcd & 0xf0) >> 1) + ((bcd & 0xf0) >> 3) + (bcd & 0xf); } static inline u32 cmos_read_reg(u8 reg) { u8 NMI_disable_bit = 0; // temporary outb(CMOS_CONTROL_PORT, (u8)(NMI_disable_bit << 7) | reg); return inb(CMOS_DATA_PORT); } static inline bool cmos_is_update_in_progress(void) { return cmos_read_reg(REG_STATUS_REG_A) & STATUS_REG_A_UPDATE_IN_PROGRESS; } static void cmod_read_datetime_raw(struct datetime *d) { d->sec = (u8) cmos_read_reg(REG_SECONDS); d->min = (u8) cmos_read_reg(REG_MINUTES); d->hour = (u8) cmos_read_reg(REG_HOURS); d->weekday = (u8) cmos_read_reg(REG_WEEKDAY); d->day = (u8) cmos_read_reg(REG_DAY); d->month = (u8) cmos_read_reg(REG_MONTH); d->year = (u16) cmos_read_reg(REG_YEAR); } void hw_read_clock(struct datetime *out) { struct datetime d, dlast; u32 reg_b; bool use_24h; bool use_binary; bool hour_pm_bit; reg_b = cmos_read_reg(REG_STATUS_REG_B); use_24h = !!(reg_b & (1 << 1)); use_binary = !!(reg_b & (1 << 2)); while (cmos_is_update_in_progress()); // wait an eventual update to complete cmod_read_datetime_raw(&d); do { dlast = d; while (cmos_is_update_in_progress());//wait an eventual update to complete cmod_read_datetime_raw(&d); /* * Read until we get the same result twice: this is necessary to get a * consistent set of values. */ } while (dlast.raw != d.raw); hour_pm_bit = d.hour & 0x80; d.hour &= ~0x80; if (!use_binary) { d.sec = bcd_to_dec(d.sec); d.min = bcd_to_dec(d.min); d.hour = bcd_to_dec(d.hour); d.day = bcd_to_dec(d.day); d.month = bcd_to_dec(d.month); d.year = bcd_to_dec((u8) d.year); } if (!use_24h) { if (d.hour == 12) { if (!hour_pm_bit) d.hour = 0; /* 12 am is midnight => hour 0 */ } else { if (hour_pm_bit) d.hour = (d.hour + 12) % 24; } } /* * This allows to support years from 1970 to 2069, * without knowing the century. Yes, knowing the century is a mess and * requires asking through ACPI (if supported) for the "century" register. * See: https://wiki.osdev.org/CMOS. */ d.year = (u16)(d.year + (d.year < 70 ? 2000 : 1900)); *out = d; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(TOOL_WS ${CMAKE_BINARY_DIR}/scripts/weaken_syms) # # Internal macro use by the build_and_link_module() function # macro(__build_and_link_module_patch_logic) set(PATCHED_MOD_FILE "libmod_${modname}_patched.a") add_custom_command( OUTPUT ${PATCHED_MOD_FILE} COMMAND cp libmod_${modname}${variant}.a ${PATCHED_MOD_FILE} COMMAND ${TOOL_WS} ${PATCHED_MOD_FILE} ${WRAPPED_SYMS} DEPENDS mod_${modname}${variant} ${TOOL_WS} elfhack32 elfhack64 COMMENT "Patching the module ${modname} to allow wrapping of symbols" VERBATIM ) add_custom_target( mod_${modname}_patched DEPENDS ${PATCHED_MOD_FILE} ) endmacro() # # Build and statically link a kernel module # # ARGV0: target # ARGV1: module name # ARGV2: special flag: If equal to "_noarch", don't build the arch code. # ARGV3: patch flag: run the WS_TOOL to weaken all the symbols in the static # archive if the flag is true. # function(build_and_link_module target modname) set(variant "${ARGV2}") set(DO_PATCH "${ARGV3}") set(MOD_${modname}_SOURCES_GLOB "") # message(STATUS "build_module(${target} ${modname} ${variant})") list( APPEND MOD_${modname}_SOURCES_GLOB "${CMAKE_SOURCE_DIR}/modules/${modname}/*.c" "${CMAKE_SOURCE_DIR}/modules/${modname}/*.cpp" ) if (NOT "${variant}" STREQUAL "_noarch") if (NOT "${variant}" STREQUAL "") message(FATAL_ERROR "Flag must be \"_noarch\" or empty.") endif() list( APPEND MOD_${modname}_SOURCES_GLOB "${CMAKE_SOURCE_DIR}/modules/${modname}/${ARCH}/*.c" "${CMAKE_SOURCE_DIR}/modules/${modname}/${ARCH_FAMILY}/*.c" ) endif() file( GLOB MOD_${modname}_SOURCES # Output variable ${GLOB_CONF_DEP} # The CONFIGURE_DEPENDS option ${MOD_${modname}_SOURCES_GLOB} # The input GLOB text ) # It's totally possible that some modules contain exclusively arch-only # code. In that case, the list of sources will be empty when the flag # "noarch" is passed and we just won't create any target. if (MOD_${modname}_SOURCES) add_library( mod_${modname}${variant} STATIC EXCLUDE_FROM_ALL ${MOD_${modname}_SOURCES} ) if ("${variant}" STREQUAL "_noarch") set_target_properties( mod_${modname}${variant} PROPERTIES COMPILE_FLAGS "${KERNEL_NO_ARCH_FLAGS}" ) if (DO_PATCH) __build_and_link_module_patch_logic() endif(DO_PATCH) else() set_target_properties( mod_${modname}${variant} PROPERTIES COMPILE_FLAGS "${KERNEL_FLAGS} ${ACTUAL_KERNEL_ONLY_FLAGS}" ) endif() # Link the patched or the regular module version if (DO_PATCH) add_dependencies(${target} mod_${modname}_patched) target_link_libraries( ${target} ${CMAKE_CURRENT_BINARY_DIR}/${PATCHED_MOD_FILE} ) else() target_link_libraries(${target} mod_${modname}${variant}) endif() endif(MOD_${modname}_SOURCES) endfunction() # # Build and link all modules to a given target # function(build_all_modules TARGET_NAME) set(TARGET_VARIANT "${ARGV1}") set(DO_PATCH "${ARGV2}") target_link_libraries(${TARGET_NAME} -Wl,--whole-archive) foreach (mod ${modules_list}) if ("${TARGET_VARIANT}" STREQUAL "_noarch") list(FIND no_arch_modules_whitelist ${mod} _index) if (${_index} EQUAL -1) continue() endif() else() # Even if it's ugly, check here if the module should be compiled-in # or not. In the "noarch" case, always compile the modules in, because # they are needed for unit tests. if (NOT MOD_${mod}) continue() endif() endif() if (EXISTS ${CMAKE_SOURCE_DIR}/modules/${mod}/${mod}.cmake) # Use the custom per-module CMake file include(${CMAKE_SOURCE_DIR}/modules/${mod}/${mod}.cmake) else() # Use the generic build & link code build_and_link_module( ${TARGET_NAME} ${mod} ${TARGET_VARIANT} ${DO_PATCH} ) endif() endforeach() target_link_libraries(${TARGET_NAME} -Wl,--no-whole-archive) endfunction() <file_sep>#!/bin/sh (cd build && qemu-img convert -O vmdk tilck.img tilck.vmdk) <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(HAVE_ALT_FONTS 0) if (EXISTS ${CMAKE_SOURCE_DIR}/other/alt_fonts/font16x32.psf) if (EXISTS ${CMAKE_SOURCE_DIR}/other/alt_fonts/font8x16.psf) set(HAVE_ALT_FONTS 1) endif() endif() if (${HAVE_ALT_FONTS} AND ${FB_CONSOLE_USE_ALT_FONTS}) file( GLOB font_files ${GLOB_CONF_DEP} "${CMAKE_SOURCE_DIR}/other/alt_fonts/*.psf" ) else() file( GLOB font_files ${GLOB_CONF_DEP} "${CMAKE_SOURCE_DIR}/modules/fb/*.psf" ) endif() # B2O = Binary to Object file [options] list(APPEND B2O -O ${ARCH_ELF_NAME} -B ${ARCH_BFD} -I binary) foreach(font_file ${font_files}) get_filename_component(font_name ${font_file} NAME_WE) get_filename_component(font_dir ${font_file} DIRECTORY) set(obj_file ${CMAKE_CURRENT_BINARY_DIR}/${font_name}.o) add_custom_command( OUTPUT ${obj_file} COMMAND ${CMAKE_OBJCOPY} ${B2O} ${font_name}.psf ${obj_file} WORKING_DIRECTORY ${font_dir} DEPENDS ${font_file} COMMENT "Copy into ELF object file: ${font_name}.psf" ) list(APPEND FONT_OBJ_FILES_LIST ${obj_file}) endforeach() add_custom_target( fonts${TARGET_VARIANT} DEPENDS ${FONT_OBJ_FILES_LIST} ) add_dependencies(${TARGET_NAME} fonts${TARGET_VARIANT}) target_link_libraries(${TARGET_NAME} ${CMAKE_CURRENT_BINARY_DIR}/font8x16.o) target_link_libraries(${TARGET_NAME} ${CMAKE_CURRENT_BINARY_DIR}/font16x32.o) build_and_link_module(${TARGET_NAME} "fb" ${TARGET_VARIANT}) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct ringbuf { u32 read_pos; u32 write_pos; u32 elems; u32 max_elems; u32 elem_size; u8 *buf; }; inline bool ringbuf_is_empty(struct ringbuf *rb) { return rb->elems == 0; } inline bool ringbuf_is_full(struct ringbuf *rb) { return rb->elems == rb->max_elems; } inline size_t ringbuf_get_elems(struct ringbuf *rb) { return rb->elems; } inline void ringbuf_reset(struct ringbuf *rb) { rb->read_pos = rb->write_pos = rb->elems = 0; } void ringbuf_init(struct ringbuf *rb, size_t elems, size_t elem_size, void *b); void ringbuf_destory(struct ringbuf *rb); bool ringbuf_write_elem(struct ringbuf *rb, void *elem_ptr); bool ringbuf_read_elem(struct ringbuf *rb, void *elem_ptr /* out */); bool ringbuf_unwrite_elem(struct ringbuf *rb, void *elem_ptr /* out */); size_t ringbuf_write_bytes(struct ringbuf *rb, u8 *buf, size_t len); size_t ringbuf_read_bytes(struct ringbuf *rb, u8 *buf, size_t len); inline bool ringbuf_write_elem1(struct ringbuf *rb, u8 val) { if (ringbuf_is_full(rb)) return false; rb->buf[rb->write_pos] = val; rb->write_pos = (rb->write_pos + 1) % rb->max_elems; rb->elems++; return true; } inline bool ringbuf_read_elem1(struct ringbuf *rb, u8 *elem_ptr) { if (ringbuf_is_empty(rb)) return false; *elem_ptr = rb->buf[rb->read_pos]; rb->read_pos = (rb->read_pos + 1) % rb->max_elems; rb->elems--; return true; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/elf_types.h> #define SELFTEST_PREFIX "selftest_" struct elf_symbol_info { void *vaddr; u32 size; const char *name; }; void call_kernel_global_ctors(void); ulong find_addr_of_symbol(const char *searched_sym); const char *find_sym_at_addr(ulong vaddr, long *off, u32 *sym_size); const char *find_sym_at_addr_safe(ulong vaddr, long *off, u32 *sym_size); int foreach_symbol(int (*cb)(struct elf_symbol_info *, void *), void *arg); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> /* i8042's I/O ports */ #define I8042_DATA_PORT 0x60 /* 0x60 is a read/write data port */ #define I8042_CMD_PORT 0x64 /* 0x64 is for cmds, when it's written */ #define I8042_STATUS_PORT 0x64 /* 0x64 is for status, when it's read */ /* Status flags */ #define I8042_STATUS_OUTPUT_FULL (1 << 0) /* must be 1 before reading */ #define I8042_STATUS_INPUT_FULL (1 << 1) /* must be 0 before writing */ /* CTR (Controller Configuration Byte) flags */ #define I8042_CTR_PORT1_INT_ENABLED (1 << 0) #define I8042_CTR_PORT2_INT_ENABLED (1 << 1) #define I8042_CTR_SYS_FLAG (1 << 2) #define I8042_CTR_PORT1_CLK_DISABLED (1 << 4) #define I8042_CTR_PORT2_CLK_DISABLED (1 << 5) #define I8042_CTR_PS2_PORT_TRANSL (1 << 6) /* PS/2 Controller commands */ #define I8042_CMD_CPU_RESET 0xFE #define I8042_CMD_RESET 0xFF #define I8042_CMD_SELFTEST 0xAA #define I8042_CMD_PORT1_DISABLE 0xAD #define I8042_CMD_PORT1_ENABLE 0xAE #define I8042_CMD_PORT2_DISABLE 0xA7 #define I8042_CMD_PORT2_ENABLE 0xA8 #define I8042_CMD_READ_CTR 0x20 /* Controller Config. Byte */ #define I8042_CMD_READ_CTO 0xD0 /* Controller Output Port */ /* PS/2 Controller response codes */ #define I8042_RESPONSE_BAT_OK 0xAA #define I8042_RESPONSE_SELF_TEST_OK 0x55 /* PS/2 Keyboard commands */ #define KB_CMD_SET_LED 0xED #define KB_CMD_SET_TYPEMATIC_BYTE 0xF3 /* PS/2 Keyboard response codes */ #define KB_RESPONSE_ACK 0xFA #define KB_RESPONSE_RESEND 0xFE /* Logical state functions */ void i8042_set_sw_port_enabled_state(u8 port, bool enabled); bool i8042_get_sw_port_enabled_state(u8 port); /* HW keyboard-specific functions */ bool kb_led_set(u8 val); bool kb_set_typematic_byte(u8 val); /* HW controller functions */ bool i8042_read_ctr_unsafe(u8 *ctr); bool i8042_read_cto_unsafe(u8 *cto); void i8042_drain_any_data(void); void i8042_force_drain_data(void); bool i8042_read_regs(u8 *ctr, u8 *cto); void i8042_reboot(void); NODISCARD bool i8042_self_test(void); NODISCARD bool i8042_reset(void); NODISCARD bool i8042_disable_ports(void); NODISCARD bool i8042_enable_ports(void); static inline u8 i8042_read_status(void) { return inb(I8042_STATUS_PORT); } static inline u8 i8042_read_data(void) { return inb(I8042_DATA_PORT); } static inline NODISCARD bool i8042_has_pending_data(void) { return !!(inb(I8042_STATUS_PORT) & I8042_STATUS_OUTPUT_FULL); } static inline NODISCARD bool i8042_is_ready_for_cmd(void) { return !(inb(I8042_STATUS_PORT) & I8042_STATUS_INPUT_FULL); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included /* * The only purpose of this file is to keep kmalloc.c shorter. * Yes, this file could be turned into a regular C source file, but at the * price of making several static functions and variables in kmalloc.c to be * just non-static. We don't want that. Code isolation is a GOOD thing. */ #endif #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/list.h> #include <tilck/kernel/test/kmalloc.h> STATIC struct kmalloc_heap first_heap_struct; STATIC struct kmalloc_heap *heaps[KMALLOC_HEAPS_COUNT]; STATIC int used_heaps; STATIC size_t max_tot_heap_mem_free; void *kmalloc_get_first_heap(size_t *size) { static char buf[KMALLOC_FIRST_HEAP_SIZE] ALIGNED_AT(KMALLOC_MAX_ALIGN); STATIC_ASSERT((KMALLOC_FIRST_HEAP_SIZE % (64 * KB)) == 0); if (size) *size = KMALLOC_FIRST_HEAP_SIZE; return buf; } #include "kmalloc_leak_detector.c.h" static void kmalloc_heap_set_pre_calculated_values(struct kmalloc_heap *h) { h->heap_last_byte = h->vaddr + h->size - 1; h->heap_data_size_log2 = log2_for_power_of_2(h->size); h->alloc_block_size_log2 = log2_for_power_of_2(h->alloc_block_size); h->metadata_size = calculate_heap_metadata_size(h->size, h->min_block_size); } bool kmalloc_create_heap(struct kmalloc_heap *h, ulong vaddr, size_t size, size_t min_block_size, size_t alloc_block_size, bool linear_mapping, void *metadata_nodes, virtual_alloc_and_map_func valloc, virtual_free_and_unmap_func vfree) { if (size != SMALL_HEAP_SIZE) { // heap size has to be a multiple of KMALLOC_MIN_HEAP_SIZE ASSERT((size & (KMALLOC_MIN_HEAP_SIZE - 1)) == 0); // heap size must be a power of 2 ASSERT(roundup_next_power_of_2(size) == size); // vaddr must be aligned at least at KMALLOC_MAX_ALIGN ASSERT((vaddr & (KMALLOC_MAX_ALIGN - 1)) == 0); } if (!linear_mapping) { // alloc block size has to be a multiple of PAGE_SIZE ASSERT((alloc_block_size & (PAGE_SIZE - 1)) == 0); ASSERT(alloc_block_size <= KMALLOC_MAX_ALIGN); } else { ASSERT(alloc_block_size == 0); } bzero(h, sizeof(*h)); h->metadata_size = calculate_heap_metadata_size(size, min_block_size); h->valloc_and_map = valloc; h->vfree_and_unmap = vfree; if (!metadata_nodes) { // It is OK to pass NULL as 'metadata_nodes' if at least one heap exists. ASSERT(heaps[0] != NULL); ASSERT(heaps[0]->vaddr != 0); metadata_nodes = vmalloc(h->metadata_size); if (!metadata_nodes) return false; } h->vaddr = vaddr; h->size = size; h->min_block_size = min_block_size; h->alloc_block_size = alloc_block_size; h->metadata_nodes = metadata_nodes; h->region = -1; kmalloc_heap_set_pre_calculated_values(h); bzero(h->metadata_nodes, h->metadata_size); h->linear_mapping = linear_mapping; return true; } struct kmalloc_heap * kmalloc_create_regular_heap(ulong vaddr, size_t size, size_t min_block_size) { struct kmalloc_heap *h = kalloc_obj(struct kmalloc_heap); bool success; if (!h) return NULL; success = kmalloc_create_heap(h, vaddr, size, min_block_size, 0, /* alloc_block_size */ true, /* linear_mapping */ NULL, /* metadata_nodes */ NULL, /* valloc */ NULL); /* vfree */ if (!success) { kfree_obj(h, struct kmalloc_heap); return NULL; } return h; } void kmalloc_destroy_heap(struct kmalloc_heap *h) { vfree2(h->metadata_nodes, h->metadata_size); bzero(h, sizeof(struct kmalloc_heap)); } struct kmalloc_heap * kmalloc_heap_dup_expanded(struct kmalloc_heap *h, size_t new_size) { struct kmalloc_heap *new_heap; /* `new_size` must at least as big as the old one */ ASSERT(new_size >= h->size); /* `new_size` must be a power of 2 */ ASSERT(roundup_next_power_of_2(new_size) == new_size); if (!h) return NULL; if (!(new_heap = kalloc_obj(struct kmalloc_heap))) return NULL; memcpy(new_heap, h, sizeof(struct kmalloc_heap)); new_heap->size = new_size; new_heap->metadata_size = calculate_heap_metadata_size(new_size, new_heap->min_block_size); new_heap->metadata_nodes = vmalloc(new_heap->metadata_size); if (!new_heap->metadata_nodes) { kfree_obj(new_heap, struct kmalloc_heap); return NULL; } if (new_size == h->size) { memcpy(new_heap->metadata_nodes, h->metadata_nodes, h->metadata_size); return new_heap; } kmalloc_heap_set_pre_calculated_values(new_heap); bzero(new_heap->metadata_nodes, new_heap->metadata_size); struct block_node *new_nodes = new_heap->metadata_nodes; struct block_node *old_nodes = h->metadata_nodes; size_t nodes_per_row = 1; int new_idx, old_idx; for (size_t size = new_heap->size; size >= h->min_block_size; size /= 2) { new_idx = ptr_to_node(new_heap, TO_PTR(h->vaddr), size); if (size > h->size) { new_nodes[new_idx].split = true; } else { old_idx = ptr_to_node(h, TO_PTR(h->vaddr), size); memcpy(&new_nodes[new_idx], &old_nodes[old_idx], nodes_per_row); nodes_per_row *= 2; } } return new_heap; } struct kmalloc_heap * kmalloc_heap_dup(struct kmalloc_heap *h) { return kmalloc_heap_dup_expanded(h, h->size); } static size_t find_biggest_heap_size(ulong vaddr, ulong limit) { ulong curr_max = 512 * MB; ulong curr_end; while (curr_max) { curr_end = vaddr + curr_max; if (vaddr < curr_end && curr_end <= limit) break; curr_max >>= 1; } return curr_max; } static int kmalloc_internal_add_heap(void *vaddr, size_t heap_size) { const size_t min_block_size = SMALL_HEAP_MAX_ALLOC + 1; const size_t metadata_size = calculate_heap_metadata_size(heap_size, min_block_size); if (used_heaps >= ARRAY_SIZE(heaps)) return -1; if (!used_heaps) { heaps[used_heaps] = &first_heap_struct; } else { heaps[used_heaps] = kmalloc(MAX(sizeof(struct kmalloc_heap), SMALL_HEAP_MAX_ALLOC + 1)); if (!heaps[used_heaps]) panic("Unable to alloc memory for struct struct kmalloc_heap"); } bool success = kmalloc_create_heap(heaps[used_heaps], (ulong)vaddr, heap_size, min_block_size, 0, /* alloc_block_size */ true, /* linear mapping */ vaddr, /* metadata_nodes */ NULL, NULL); VERIFY(success); VERIFY(heaps[used_heaps] != NULL); /* * We passed to kmalloc_create_heap() the begining of the heap as 'metadata' * in order to avoid using another heap (that might not be large enough) for * that. Now we MUST register that area in the metadata itself, by doing an * allocation using per_heap_kmalloc(). */ size_t actual_metadata_size = metadata_size; void *md_allocated = per_heap_kmalloc(heaps[used_heaps], &actual_metadata_size, 0); if (KMALLOC_HEAVY_STATS) kmalloc_account_alloc(metadata_size); /* * We have to be SURE that the allocation returned the very beginning of * the heap, as we expected. */ VERIFY(md_allocated == vaddr); return used_heaps++; } static long greater_than_heap_cmp(const void *a, const void *b) { const struct kmalloc_heap *const *ha_ref = a; const struct kmalloc_heap *const *hb_ref = b; const struct kmalloc_heap *ha = *ha_ref; const struct kmalloc_heap *hb = *hb_ref; if (ha->size < hb->size) return 1; if (ha->size == hb->size) return 0; return -1; } static void init_kmalloc_fill_region(int region, ulong vaddr, ulong limit, bool dma) { int heap_index; vaddr = pow2_round_up_at( vaddr, MIN(KMALLOC_MIN_HEAP_SIZE, KMALLOC_MAX_ALIGN) ); if (vaddr >= limit) return; while (true) { size_t heap_size = find_biggest_heap_size(vaddr, limit); if (heap_size < KMALLOC_MIN_HEAP_SIZE) break; heap_index = kmalloc_internal_add_heap((void *)vaddr, heap_size); if (heap_index < 0) { printk("kmalloc: no heap slot for heap at %p, size: %zu KB\n", TO_PTR(vaddr), heap_size / KB); break; } heaps[heap_index]->region = region; heaps[heap_index]->dma = dma; vaddr = heaps[heap_index]->vaddr + heaps[heap_index]->size; } } void early_init_kmalloc(void) { int heap_index; ASSERT(!kmalloc_initialized); list_init(&small_heaps_list); list_init(&avail_small_heaps_list); used_heaps = 0; bzero(heaps, sizeof(heaps)); { size_t first_heap_size; void *first_heap_ptr; first_heap_ptr = kmalloc_get_first_heap(&first_heap_size); heap_index = kmalloc_internal_add_heap(first_heap_ptr, first_heap_size); } VERIFY(heap_index == 0); kmalloc_initialized = true; /* we have at least 1 heap */ if (KMALLOC_HEAVY_STATS) { kmalloc_init_heavy_stats(); kmalloc_account_alloc(heaps[0]->metadata_size); } } void init_kmalloc(void) { struct mem_region r; ulong vbegin, vend; ASSERT(kmalloc_initialized); ASSERT(used_heaps == 1); heaps[0]->region = system_mmap_get_region_of(KERNEL_VA_TO_PA(kmalloc_get_first_heap(NULL))); for (int i = 0; i < get_mem_regions_count(); i++) { get_mem_region(i, &r); if (!linear_map_mem_region(&r, &vbegin, &vend)) break; if (r.type == MULTIBOOT_MEMORY_AVAILABLE) { const bool dma = r.extra == MEM_REG_EXTRA_DMA; if (!r.extra || dma) init_kmalloc_fill_region(i, vbegin, vend, dma); if (vend == LINEAR_MAPPING_END) break; } } insertion_sort_ptr(heaps, (u32)used_heaps, greater_than_heap_cmp); for (int i = 0; i < KMALLOC_HEAPS_COUNT; i++) { struct kmalloc_heap *h = heaps[i]; if (!h) continue; max_tot_heap_mem_free += (h->size - h->mem_allocated); } } size_t kmalloc_get_max_tot_heap_free(void) { return max_tot_heap_mem_free; } void debug_kmalloc_get_heap_info_by_ptr(struct kmalloc_heap *h, struct debug_kmalloc_heap_info *i) { *i = (struct debug_kmalloc_heap_info) { .vaddr = h->vaddr, .size = h->size, .mem_allocated = h->mem_allocated, .min_block_size = h->min_block_size, .alloc_block_size = h->alloc_block_size, .region = h->region, }; } bool debug_kmalloc_get_heap_info(int heap_num, struct debug_kmalloc_heap_info *i) { struct kmalloc_heap *h = heaps[heap_num]; if (!h) return false; debug_kmalloc_get_heap_info_by_ptr(h, i); return true; } void debug_kmalloc_get_stats(struct debug_kmalloc_stats *stats) { *stats = (struct debug_kmalloc_stats) { .small_heaps = shs, .chunk_sizes_count = KMALLOC_HEAVY_STATS ? alloc_arr_used : 0, }; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/mods/pci.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_hw") STATIC_ASSERT(IRQ_HANDLED == ACPI_INTERRUPT_HANDLED); STATIC_ASSERT(IRQ_NOT_HANDLED == ACPI_INTERRUPT_NOT_HANDLED); static struct irq_handler_node *osl_irq_handlers; ACPI_STATUS osl_init_irqs(void) { osl_irq_handlers = kzalloc_array_obj(struct irq_handler_node, 16); if (!osl_irq_handlers) panic("ACPI: unable to allocate memory for IRQ handlers"); return AE_OK; } ACPI_STATUS AcpiOsInstallInterruptHandler( UINT32 InterruptNumber, ACPI_OSD_HANDLER ServiceRoutine, void *Context) { struct irq_handler_node *n; ACPI_FUNCTION_TRACE(__FUNC__); if (!ServiceRoutine) return_ACPI_STATUS(AE_BAD_PARAMETER); if (!IN_RANGE((int)InterruptNumber, 0, 16)) return_ACPI_STATUS(AE_BAD_PARAMETER); n = &osl_irq_handlers[InterruptNumber]; if (n->handler) return_ACPI_STATUS(AE_ALREADY_EXISTS); list_node_init(&n->node); n->handler = (irq_handler_t)ServiceRoutine; n->context = Context; printk("ACPI: install handler for IRQ #%u\n", InterruptNumber); irq_install_handler(InterruptNumber, n); return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsRemoveInterruptHandler( UINT32 InterruptNumber, ACPI_OSD_HANDLER ServiceRoutine) { struct irq_handler_node *n; ACPI_FUNCTION_TRACE(__FUNC__); if (!ServiceRoutine) return_ACPI_STATUS(AE_BAD_PARAMETER); if (!IN_RANGE((int)InterruptNumber, 0, 16)) return_ACPI_STATUS(AE_BAD_PARAMETER); n = &osl_irq_handlers[InterruptNumber]; if (!n->handler) return_ACPI_STATUS(AE_NOT_EXIST); if (n->handler != ServiceRoutine) return_ACPI_STATUS(AE_BAD_PARAMETER); printk("ACPI: remove handler for IRQ #%u\n", InterruptNumber); irq_uninstall_handler(InterruptNumber, n); return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsReadPciConfiguration( ACPI_PCI_ID *PciId, UINT32 Reg, UINT64 *Value, UINT32 Width) { u32 val; int rc; ACPI_FUNCTION_TRACE(__FUNC__); if (Width == 64) return_ACPI_STATUS(AE_SUPPORT); rc = pci_config_read( pci_make_loc( PciId->Segment, PciId->Bus, PciId->Device, PciId->Function ), Reg, Width, &val ); switch (rc) { case 0: break; /* everything is fine */ case -ERANGE: /* fall-through */ case -EINVAL: return_ACPI_STATUS(AE_BAD_PARAMETER); default: return_ACPI_STATUS(AE_ERROR); } *Value = val; return AE_OK; } ACPI_STATUS AcpiOsWritePciConfiguration( ACPI_PCI_ID *PciId, UINT32 Reg, UINT64 Value, UINT32 Width) { int rc; ACPI_FUNCTION_TRACE(__FUNC__); if (Width == 64) return_ACPI_STATUS(AE_SUPPORT); rc = pci_config_write( pci_make_loc( PciId->Segment, PciId->Bus, PciId->Device, PciId->Function ), Reg, Width, (u32)Value ); switch (rc) { case 0: break; /* everything is fine */ case -ERANGE: /* fall-through */ case -EINVAL: return_ACPI_STATUS(AE_BAD_PARAMETER); default: return_ACPI_STATUS(AE_ERROR); } return AE_OK; } <file_sep>/******************************************************************************* * * Module Name: utresrc - Resource management utilities * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acresrc.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utresrc") /* * Base sizes of the raw AML resource descriptors, indexed by resource type. * Zero indicates a reserved (and therefore invalid) resource type. */ const UINT8 AcpiGbl_ResourceAmlSizes[] = { /* Small descriptors */ 0, 0, 0, 0, ACPI_AML_SIZE_SMALL (AML_RESOURCE_IRQ), ACPI_AML_SIZE_SMALL (AML_RESOURCE_DMA), ACPI_AML_SIZE_SMALL (AML_RESOURCE_START_DEPENDENT), ACPI_AML_SIZE_SMALL (AML_RESOURCE_END_DEPENDENT), ACPI_AML_SIZE_SMALL (AML_RESOURCE_IO), ACPI_AML_SIZE_SMALL (AML_RESOURCE_FIXED_IO), ACPI_AML_SIZE_SMALL (AML_RESOURCE_FIXED_DMA), 0, 0, 0, ACPI_AML_SIZE_SMALL (AML_RESOURCE_VENDOR_SMALL), ACPI_AML_SIZE_SMALL (AML_RESOURCE_END_TAG), /* Large descriptors */ 0, ACPI_AML_SIZE_LARGE (AML_RESOURCE_MEMORY24), ACPI_AML_SIZE_LARGE (AML_RESOURCE_GENERIC_REGISTER), 0, ACPI_AML_SIZE_LARGE (AML_RESOURCE_VENDOR_LARGE), ACPI_AML_SIZE_LARGE (AML_RESOURCE_MEMORY32), ACPI_AML_SIZE_LARGE (AML_RESOURCE_FIXED_MEMORY32), ACPI_AML_SIZE_LARGE (AML_RESOURCE_ADDRESS32), ACPI_AML_SIZE_LARGE (AML_RESOURCE_ADDRESS16), ACPI_AML_SIZE_LARGE (AML_RESOURCE_EXTENDED_IRQ), ACPI_AML_SIZE_LARGE (AML_RESOURCE_ADDRESS64), ACPI_AML_SIZE_LARGE (AML_RESOURCE_EXTENDED_ADDRESS64), ACPI_AML_SIZE_LARGE (AML_RESOURCE_GPIO), ACPI_AML_SIZE_LARGE (AML_RESOURCE_PIN_FUNCTION), ACPI_AML_SIZE_LARGE (AML_RESOURCE_COMMON_SERIALBUS), ACPI_AML_SIZE_LARGE (AML_RESOURCE_PIN_CONFIG), ACPI_AML_SIZE_LARGE (AML_RESOURCE_PIN_GROUP), ACPI_AML_SIZE_LARGE (AML_RESOURCE_PIN_GROUP_FUNCTION), ACPI_AML_SIZE_LARGE (AML_RESOURCE_PIN_GROUP_CONFIG), }; const UINT8 AcpiGbl_ResourceAmlSerialBusSizes[] = { 0, ACPI_AML_SIZE_LARGE (AML_RESOURCE_I2C_SERIALBUS), ACPI_AML_SIZE_LARGE (AML_RESOURCE_SPI_SERIALBUS), ACPI_AML_SIZE_LARGE (AML_RESOURCE_UART_SERIALBUS), }; /* * Resource types, used to validate the resource length field. * The length of fixed-length types must match exactly, variable * lengths must meet the minimum required length, etc. * Zero indicates a reserved (and therefore invalid) resource type. */ static const UINT8 AcpiGbl_ResourceTypes[] = { /* Small descriptors */ 0, 0, 0, 0, ACPI_SMALL_VARIABLE_LENGTH, /* 04 IRQ */ ACPI_FIXED_LENGTH, /* 05 DMA */ ACPI_SMALL_VARIABLE_LENGTH, /* 06 StartDependentFunctions */ ACPI_FIXED_LENGTH, /* 07 EndDependentFunctions */ ACPI_FIXED_LENGTH, /* 08 IO */ ACPI_FIXED_LENGTH, /* 09 FixedIO */ ACPI_FIXED_LENGTH, /* 0A FixedDMA */ 0, 0, 0, ACPI_VARIABLE_LENGTH, /* 0E VendorShort */ ACPI_FIXED_LENGTH, /* 0F EndTag */ /* Large descriptors */ 0, ACPI_FIXED_LENGTH, /* 01 Memory24 */ ACPI_FIXED_LENGTH, /* 02 GenericRegister */ 0, ACPI_VARIABLE_LENGTH, /* 04 VendorLong */ ACPI_FIXED_LENGTH, /* 05 Memory32 */ ACPI_FIXED_LENGTH, /* 06 Memory32Fixed */ ACPI_VARIABLE_LENGTH, /* 07 Dword* address */ ACPI_VARIABLE_LENGTH, /* 08 Word* address */ ACPI_VARIABLE_LENGTH, /* 09 ExtendedIRQ */ ACPI_VARIABLE_LENGTH, /* 0A Qword* address */ ACPI_FIXED_LENGTH, /* 0B Extended* address */ ACPI_VARIABLE_LENGTH, /* 0C Gpio* */ ACPI_VARIABLE_LENGTH, /* 0D PinFunction */ ACPI_VARIABLE_LENGTH, /* 0E *SerialBus */ ACPI_VARIABLE_LENGTH, /* 0F PinConfig */ ACPI_VARIABLE_LENGTH, /* 10 PinGroup */ ACPI_VARIABLE_LENGTH, /* 11 PinGroupFunction */ ACPI_VARIABLE_LENGTH, /* 12 PinGroupConfig */ }; /******************************************************************************* * * FUNCTION: AcpiUtWalkAmlResources * * PARAMETERS: WalkState - Current walk info * PARAMETERS: Aml - Pointer to the raw AML resource template * AmlLength - Length of the entire template * UserFunction - Called once for each descriptor found. If * NULL, a pointer to the EndTag is returned * Context - Passed to UserFunction * * RETURN: Status * * DESCRIPTION: Walk a raw AML resource list(buffer). User function called * once for each resource found. * ******************************************************************************/ ACPI_STATUS AcpiUtWalkAmlResources ( ACPI_WALK_STATE *WalkState, UINT8 *Aml, ACPI_SIZE AmlLength, ACPI_WALK_AML_CALLBACK UserFunction, void **Context) { ACPI_STATUS Status; UINT8 *EndAml; UINT8 ResourceIndex; UINT32 Length; UINT32 Offset = 0; UINT8 EndTag[2] = {0x79, 0x00}; ACPI_FUNCTION_TRACE (UtWalkAmlResources); /* The absolute minimum resource template is one EndTag descriptor */ if (AmlLength < sizeof (AML_RESOURCE_END_TAG)) { return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG); } /* Point to the end of the resource template buffer */ EndAml = Aml + AmlLength; /* Walk the byte list, abort on any invalid descriptor type or length */ while (Aml < EndAml) { /* Validate the Resource Type and Resource Length */ Status = AcpiUtValidateResource (WalkState, Aml, &ResourceIndex); if (ACPI_FAILURE (Status)) { /* * Exit on failure. Cannot continue because the descriptor * length may be bogus also. */ return_ACPI_STATUS (Status); } /* Get the length of this descriptor */ Length = AcpiUtGetDescriptorLength (Aml); /* Invoke the user function */ if (UserFunction) { Status = UserFunction ( Aml, Length, Offset, ResourceIndex, Context); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* An EndTag descriptor terminates this resource template */ if (AcpiUtGetResourceType (Aml) == ACPI_RESOURCE_NAME_END_TAG) { /* * There must be at least one more byte in the buffer for * the 2nd byte of the EndTag */ if ((Aml + 1) >= EndAml) { return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG); } /* * Don't attempt to perform any validation on the 2nd byte. * Although all known ASL compilers insert a zero for the 2nd * byte, it can also be a checksum (as per the ACPI spec), * and this is occasionally seen in the field. July 2017. */ /* Return the pointer to the EndTag if requested */ if (!UserFunction) { *Context = Aml; } /* Normal exit */ return_ACPI_STATUS (AE_OK); } Aml += Length; Offset += Length; } /* Did not find an EndTag descriptor */ if (UserFunction) { /* Insert an EndTag anyway. AcpiRsGetListLength always leaves room */ (void) AcpiUtValidateResource (WalkState, EndTag, &ResourceIndex); Status = UserFunction (EndTag, 2, Offset, ResourceIndex, Context); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG); } /******************************************************************************* * * FUNCTION: AcpiUtValidateResource * * PARAMETERS: WalkState - Current walk info * Aml - Pointer to the raw AML resource descriptor * ReturnIndex - Where the resource index is returned. NULL * if the index is not required. * * RETURN: Status, and optionally the Index into the global resource tables * * DESCRIPTION: Validate an AML resource descriptor by checking the Resource * Type and Resource Length. Returns an index into the global * resource information/dispatch tables for later use. * ******************************************************************************/ ACPI_STATUS AcpiUtValidateResource ( ACPI_WALK_STATE *WalkState, void *Aml, UINT8 *ReturnIndex) { AML_RESOURCE *AmlResource; UINT8 ResourceType; UINT8 ResourceIndex; ACPI_RS_LENGTH ResourceLength; ACPI_RS_LENGTH MinimumResourceLength; ACPI_FUNCTION_ENTRY (); /* * 1) Validate the ResourceType field (Byte 0) */ ResourceType = ACPI_GET8 (Aml); /* * Byte 0 contains the descriptor name (Resource Type) * Examine the large/small bit in the resource header */ if (ResourceType & ACPI_RESOURCE_NAME_LARGE) { /* Verify the large resource type (name) against the max */ if (ResourceType > ACPI_RESOURCE_NAME_LARGE_MAX) { goto InvalidResource; } /* * Large Resource Type -- bits 6:0 contain the name * Translate range 0x80-0x8B to index range 0x10-0x1B */ ResourceIndex = (UINT8) (ResourceType - 0x70); } else { /* * Small Resource Type -- bits 6:3 contain the name * Shift range to index range 0x00-0x0F */ ResourceIndex = (UINT8) ((ResourceType & ACPI_RESOURCE_NAME_SMALL_MASK) >> 3); } /* * Check validity of the resource type, via AcpiGbl_ResourceTypes. * Zero indicates an invalid resource. */ if (!AcpiGbl_ResourceTypes[ResourceIndex]) { goto InvalidResource; } /* * Validate the ResourceLength field. This ensures that the length * is at least reasonable, and guarantees that it is non-zero. */ ResourceLength = AcpiUtGetResourceLength (Aml); MinimumResourceLength = AcpiGbl_ResourceAmlSizes[ResourceIndex]; /* Validate based upon the type of resource - fixed length or variable */ switch (AcpiGbl_ResourceTypes[ResourceIndex]) { case ACPI_FIXED_LENGTH: /* Fixed length resource, length must match exactly */ if (ResourceLength != MinimumResourceLength) { goto BadResourceLength; } break; case ACPI_VARIABLE_LENGTH: /* Variable length resource, length must be at least the minimum */ if (ResourceLength < MinimumResourceLength) { goto BadResourceLength; } break; case ACPI_SMALL_VARIABLE_LENGTH: /* Small variable length resource, length can be (Min) or (Min-1) */ if ((ResourceLength > MinimumResourceLength) || (ResourceLength < (MinimumResourceLength - 1))) { goto BadResourceLength; } break; default: /* Shouldn't happen (because of validation earlier), but be sure */ goto InvalidResource; } AmlResource = ACPI_CAST_PTR (AML_RESOURCE, Aml); if (ResourceType == ACPI_RESOURCE_NAME_SERIAL_BUS) { /* Validate the BusType field */ if ((AmlResource->CommonSerialBus.Type == 0) || (AmlResource->CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE)) { if (WalkState) { ACPI_ERROR ((AE_INFO, "Invalid/unsupported SerialBus resource descriptor: BusType 0x%2.2X", AmlResource->CommonSerialBus.Type)); } return (AE_AML_INVALID_RESOURCE_TYPE); } } /* Optionally return the resource table index */ if (ReturnIndex) { *ReturnIndex = ResourceIndex; } return (AE_OK); InvalidResource: if (WalkState) { ACPI_ERROR ((AE_INFO, "Invalid/unsupported resource descriptor: Type 0x%2.2X", ResourceType)); } return (AE_AML_INVALID_RESOURCE_TYPE); BadResourceLength: if (WalkState) { ACPI_ERROR ((AE_INFO, "Invalid resource descriptor length: Type " "0x%2.2X, Length 0x%4.4X, MinLength 0x%4.4X", ResourceType, ResourceLength, MinimumResourceLength)); } return (AE_AML_BAD_RESOURCE_LENGTH); } /******************************************************************************* * * FUNCTION: AcpiUtGetResourceType * * PARAMETERS: Aml - Pointer to the raw AML resource descriptor * * RETURN: The Resource Type with no extraneous bits (except the * Large/Small descriptor bit -- this is left alone) * * DESCRIPTION: Extract the Resource Type/Name from the first byte of * a resource descriptor. * ******************************************************************************/ UINT8 AcpiUtGetResourceType ( void *Aml) { ACPI_FUNCTION_ENTRY (); /* * Byte 0 contains the descriptor name (Resource Type) * Examine the large/small bit in the resource header */ if (ACPI_GET8 (Aml) & ACPI_RESOURCE_NAME_LARGE) { /* Large Resource Type -- bits 6:0 contain the name */ return (ACPI_GET8 (Aml)); } else { /* Small Resource Type -- bits 6:3 contain the name */ return ((UINT8) (ACPI_GET8 (Aml) & ACPI_RESOURCE_NAME_SMALL_MASK)); } } /******************************************************************************* * * FUNCTION: AcpiUtGetResourceLength * * PARAMETERS: Aml - Pointer to the raw AML resource descriptor * * RETURN: Byte Length * * DESCRIPTION: Get the "Resource Length" of a raw AML descriptor. By * definition, this does not include the size of the descriptor * header or the length field itself. * ******************************************************************************/ UINT16 AcpiUtGetResourceLength ( void *Aml) { ACPI_RS_LENGTH ResourceLength; ACPI_FUNCTION_ENTRY (); /* * Byte 0 contains the descriptor name (Resource Type) * Examine the large/small bit in the resource header */ if (ACPI_GET8 (Aml) & ACPI_RESOURCE_NAME_LARGE) { /* Large Resource type -- bytes 1-2 contain the 16-bit length */ ACPI_MOVE_16_TO_16 (&ResourceLength, ACPI_ADD_PTR (UINT8, Aml, 1)); } else { /* Small Resource type -- bits 2:0 of byte 0 contain the length */ ResourceLength = (UINT16) (ACPI_GET8 (Aml) & ACPI_RESOURCE_NAME_SMALL_LENGTH_MASK); } return (ResourceLength); } /******************************************************************************* * * FUNCTION: AcpiUtGetResourceHeaderLength * * PARAMETERS: Aml - Pointer to the raw AML resource descriptor * * RETURN: Length of the AML header (depends on large/small descriptor) * * DESCRIPTION: Get the length of the header for this resource. * ******************************************************************************/ UINT8 AcpiUtGetResourceHeaderLength ( void *Aml) { ACPI_FUNCTION_ENTRY (); /* Examine the large/small bit in the resource header */ if (ACPI_GET8 (Aml) & ACPI_RESOURCE_NAME_LARGE) { return (sizeof (AML_RESOURCE_LARGE_HEADER)); } else { return (sizeof (AML_RESOURCE_SMALL_HEADER)); } } /******************************************************************************* * * FUNCTION: AcpiUtGetDescriptorLength * * PARAMETERS: Aml - Pointer to the raw AML resource descriptor * * RETURN: Byte length * * DESCRIPTION: Get the total byte length of a raw AML descriptor, including the * length of the descriptor header and the length field itself. * Used to walk descriptor lists. * ******************************************************************************/ UINT32 AcpiUtGetDescriptorLength ( void *Aml) { ACPI_FUNCTION_ENTRY (); /* * Get the Resource Length (does not include header length) and add * the header length (depends on if this is a small or large resource) */ return (AcpiUtGetResourceLength (Aml) + AcpiUtGetResourceHeaderLength (Aml)); } /******************************************************************************* * * FUNCTION: AcpiUtGetResourceEndTag * * PARAMETERS: ObjDesc - The resource template buffer object * EndTag - Where the pointer to the EndTag is returned * * RETURN: Status, pointer to the end tag * * DESCRIPTION: Find the EndTag resource descriptor in an AML resource template * Note: allows a buffer length of zero. * ******************************************************************************/ ACPI_STATUS AcpiUtGetResourceEndTag ( ACPI_OPERAND_OBJECT *ObjDesc, UINT8 **EndTag) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtGetResourceEndTag); /* Allow a buffer length of zero */ if (!ObjDesc->Buffer.Length) { *EndTag = ObjDesc->Buffer.Pointer; return_ACPI_STATUS (AE_OK); } /* Validate the template and get a pointer to the EndTag */ Status = AcpiUtWalkAmlResources (NULL, ObjDesc->Buffer.Pointer, ObjDesc->Buffer.Length, NULL, (void **) EndTag); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/rwlock.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/timer.h> #define RWLOCK_TH_ITERS 1000 #define RWLOCK_READERS 20 #define RWLOCK_WRITERS 20 #define RETRY_COUNT 4 static struct rwlock_rp test_rwlrp; static struct rwlock_wp test_rwlwp; static int se_rwlock_vars[3]; static const int se_rwlock_set_1[3] = {1, 2, 3}; static const int se_rwlock_set_2[3] = {10, 20, 30}; static ATOMIC(int) readers_running; static ATOMIC(int) writers_running; struct se_rwlock_ctx { void (*shlock)(void *); void (*shunlock)(void *); void (*exlock)(void *); void (*exunlock)(void *); void *arg; }; static struct se_rwlock_ctx se_rp_ctx = { .shlock = (void *) rwlock_rp_shlock, .shunlock = (void *) rwlock_rp_shunlock, .exlock = (void *) rwlock_rp_exlock, .exunlock = (void *) rwlock_rp_exunlock, .arg = (void *) &test_rwlrp, }; static struct se_rwlock_ctx se_wp_ctx = { .shlock = (void *) rwlock_wp_shlock, .shunlock = (void *) rwlock_wp_shunlock, .exlock = (void *) rwlock_wp_exlock, .exunlock = (void *) rwlock_wp_exunlock, .arg = (void *) &test_rwlwp, }; static void se_rwlock_set_vars(const int *set) { for (int i = 0; i < ARRAY_SIZE(se_rwlock_vars); i++) { se_rwlock_vars[i] = set[i]; kernel_yield(); } } static void se_rwlock_check_set_eq(const int *set) { for (int i = 0; i < ARRAY_SIZE(se_rwlock_vars); i++) { VERIFY(se_rwlock_vars[i] == set[i]); kernel_yield(); } } static void se_rwlock_read_thread(void *arg) { struct se_rwlock_ctx *ctx = arg; readers_running++; for (int iter = 0; iter < RWLOCK_TH_ITERS; iter++) { if (se_is_stop_requested()) break; ctx->shlock(ctx->arg); { if (se_rwlock_vars[0] == se_rwlock_set_1[0]) se_rwlock_check_set_eq(se_rwlock_set_1); else se_rwlock_check_set_eq(se_rwlock_set_2); } ctx->shunlock(ctx->arg); } readers_running--; } static void se_rwlock_write_thread(void *arg) { struct se_rwlock_ctx *ctx = arg; writers_running++; for (int iter = 0; iter < RWLOCK_TH_ITERS; iter++) { if (se_is_stop_requested()) break; ctx->exlock(ctx->arg); { kernel_yield(); if (se_rwlock_vars[0] == se_rwlock_set_1[0]) { se_rwlock_check_set_eq(se_rwlock_set_1); se_rwlock_set_vars(se_rwlock_set_2); } else { se_rwlock_check_set_eq(se_rwlock_set_2); se_rwlock_set_vars(se_rwlock_set_1); } kernel_yield(); } ctx->exunlock(ctx->arg); } writers_running--; } static void se_rwlock_common(int *rt, int *wt, struct se_rwlock_ctx *ctx) { se_rwlock_set_vars(se_rwlock_set_1); for (u32 i = 0; i < RWLOCK_READERS; i++) { rt[i] = kthread_create(se_rwlock_read_thread, 0, ctx); VERIFY(rt[i] > 0); } for (u32 i = 0; i < RWLOCK_WRITERS; i++) { wt[i] = kthread_create(se_rwlock_write_thread, 0, ctx); VERIFY(wt[i] > 0); } } void selftest_rwlock_rp() { int rt[RWLOCK_READERS]; int wt[RWLOCK_WRITERS]; int retry; readers_running = writers_running = 0; rwlock_rp_init(&test_rwlrp); /* * Since we're testing a read-preferring rwlock, we except that, after all * readers have finished, there will still be writers running. At the same * way, we expect that, if we join first the writers, there won't be any * running readers. */ printk("-------- sub-test: join readers and then writers -----------\n"); for (retry = 0; retry < RETRY_COUNT; retry++) { se_rwlock_common(rt, wt, &se_rp_ctx); kthread_join_all(rt, ARRAY_SIZE(rt), true); printk("After readers, running writers: %d\n", writers_running); if (writers_running == 0) { kthread_join_all(wt, ARRAY_SIZE(wt), true); if (se_is_stop_requested()) break; printk("running writers == 0, expected > 0. Re-try sub-test\n"); continue; } /* writers_running > 0: ideal case */ kthread_join_all(wt, ARRAY_SIZE(wt), true); break; } VERIFY(retry < RETRY_COUNT); if (se_is_stop_requested()) goto end; printk("-------- sub-test: join writers and then readers -----------\n"); for (retry = 0; retry < RETRY_COUNT; retry++) { se_rwlock_common(rt, wt, &se_rp_ctx); kthread_join_all(wt, ARRAY_SIZE(wt), true); if (se_is_stop_requested()) goto end; printk("After writers, running readers: %d\n", readers_running); if (readers_running > 0) { kthread_join_all(rt, ARRAY_SIZE(rt), true); if (se_is_stop_requested()) break; printk("running readers > 0, expected == 0. Re-try subtest.\n"); continue; } /* readers_running == 0: ideal case */ kthread_join_all(rt, ARRAY_SIZE(rt), true); break; } VERIFY(retry < RETRY_COUNT); end: rwlock_rp_destroy(&test_rwlrp); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(rwlock_rp, se_med, &selftest_rwlock_rp) void selftest_rwlock_wp() { int rt[RWLOCK_READERS]; int wt[RWLOCK_WRITERS]; int retry; readers_running = writers_running = 0; rwlock_wp_init(&test_rwlwp, false); printk("-------- sub-test: join readers and then writers -----------\n"); /* * Same as above, but in this case we're testing a write-preferring rwlock. * Therefore, after joining the readers, there should be 0 writers running; * after joining the writers, there should be some readers running. */ for (retry = 0; retry < RETRY_COUNT; retry++) { se_rwlock_common(rt, wt, &se_wp_ctx); kthread_join_all(rt, ARRAY_SIZE(rt), true); printk("After readers, running writers: %d\n", writers_running); if (writers_running > 0) { kthread_join_all(wt, ARRAY_SIZE(wt), true); if (se_is_stop_requested()) break; printk("running writers > 0, expected == 0. Re-try sub-test.\n"); continue; } /* writers_running == 0: that's exactly we'd expect in the ideal case */ kthread_join_all(wt, ARRAY_SIZE(wt), true); break; } VERIFY(retry < RETRY_COUNT); if (se_is_stop_requested()) goto end; printk("-------- sub-test: join writers and then readers -----------\n"); for (retry = 0; retry < RETRY_COUNT; retry++) { se_rwlock_common(rt, wt, &se_wp_ctx); kthread_join_all(wt, ARRAY_SIZE(wt), true); printk("After writers, running readers: %d\n", readers_running); if (readers_running == 0) { kthread_join_all(rt, ARRAY_SIZE(rt), true); if (se_is_stop_requested()) break; printk("running readers == 0, expected > 0. Re-try sub-test\n"); continue; } /* readers_running > 0: ideal case */ kthread_join_all(rt, ARRAY_SIZE(rt), true); break; } VERIFY(retry < RETRY_COUNT); end: rwlock_wp_destroy(&test_rwlwp); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(rwlock_wp, se_med, &selftest_rwlock_wp) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void dump_eflags(u32 f); <file_sep>#!/bin/sh objdump -D -Mintel,i8086 -b binary -m i386 $@ <file_sep>/****************************************************************************** * * Module Name: exutils - interpreter/scanner utilities * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ /* * DEFINE_AML_GLOBALS is tested in amlcode.h * to determine whether certain global names should be "defined" or only * "declared" in the current compilation. This enhances maintainability * by enabling a single header file to embody all knowledge of the names * in question. * * Exactly one module of any executable should #define DEFINE_GLOBALS * before #including the header files which use this convention. The * names in question will be defined and initialized in that module, * and declared as extern in all other modules which #include those * header files. */ #define DEFINE_AML_GLOBALS #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlcode.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exutils") /* Local prototypes */ static UINT32 AcpiExDigitsNeeded ( UINT64 Value, UINT32 Base); /******************************************************************************* * * FUNCTION: AcpiExEnterInterpreter * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Enter the interpreter execution region. Failure to enter * the interpreter region is a fatal system error. Used in * conjunction with ExitInterpreter. * ******************************************************************************/ void AcpiExEnterInterpreter ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (ExEnterInterpreter); Status = AcpiUtAcquireMutex (ACPI_MTX_INTERPRETER); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Could not acquire AML Interpreter mutex")); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Could not acquire AML Namespace mutex")); } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiExExitInterpreter * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Exit the interpreter execution region. This is the top level * routine used to exit the interpreter when all processing has * been completed, or when the method blocks. * * Cases where the interpreter is unlocked internally: * 1) Method will be blocked on a Sleep() AML opcode * 2) Method will be blocked on an Acquire() AML opcode * 3) Method will be blocked on a Wait() AML opcode * 4) Method will be blocked to acquire the global lock * 5) Method will be blocked waiting to execute a serialized control * method that is currently executing * 6) About to invoke a user-installed opregion handler * ******************************************************************************/ void AcpiExExitInterpreter ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (ExExitInterpreter); Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Could not release AML Namespace mutex")); } Status = AcpiUtReleaseMutex (ACPI_MTX_INTERPRETER); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "Could not release AML Interpreter mutex")); } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiExTruncateFor32bitTable * * PARAMETERS: ObjDesc - Object to be truncated * * RETURN: TRUE if a truncation was performed, FALSE otherwise. * * DESCRIPTION: Truncate an ACPI Integer to 32 bits if the execution mode is * 32-bit, as determined by the revision of the DSDT. * ******************************************************************************/ BOOLEAN AcpiExTruncateFor32bitTable ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_FUNCTION_ENTRY (); /* * Object must be a valid number and we must be executing * a control method. Object could be NS node for AML_INT_NAMEPATH_OP. */ if ((!ObjDesc) || (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) || (ObjDesc->Common.Type != ACPI_TYPE_INTEGER)) { return (FALSE); } if ((AcpiGbl_IntegerByteWidth == 4) && (ObjDesc->Integer.Value > (UINT64) ACPI_UINT32_MAX)) { /* * We are executing in a 32-bit ACPI table. Truncate * the value to 32 bits by zeroing out the upper 32-bit field */ ObjDesc->Integer.Value &= (UINT64) ACPI_UINT32_MAX; return (TRUE); } return (FALSE); } /******************************************************************************* * * FUNCTION: AcpiExAcquireGlobalLock * * PARAMETERS: FieldFlags - Flags with Lock rule: * AlwaysLock or NeverLock * * RETURN: None * * DESCRIPTION: Obtain the ACPI hardware Global Lock, only if the field * flags specify that it is to be obtained before field access. * ******************************************************************************/ void AcpiExAcquireGlobalLock ( UINT32 FieldFlags) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (ExAcquireGlobalLock); /* Only use the lock if the AlwaysLock bit is set */ if (!(FieldFlags & AML_FIELD_LOCK_RULE_MASK)) { return_VOID; } /* Attempt to get the global lock, wait forever */ Status = AcpiExAcquireMutexObject (ACPI_WAIT_FOREVER, AcpiGbl_GlobalLockMutex, AcpiOsGetThreadId ()); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not acquire Global Lock")); } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiExReleaseGlobalLock * * PARAMETERS: FieldFlags - Flags with Lock rule: * AlwaysLock or NeverLock * * RETURN: None * * DESCRIPTION: Release the ACPI hardware Global Lock * ******************************************************************************/ void AcpiExReleaseGlobalLock ( UINT32 FieldFlags) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (ExReleaseGlobalLock); /* Only use the lock if the AlwaysLock bit is set */ if (!(FieldFlags & AML_FIELD_LOCK_RULE_MASK)) { return_VOID; } /* Release the global lock */ Status = AcpiExReleaseMutexObject (AcpiGbl_GlobalLockMutex); if (ACPI_FAILURE (Status)) { /* Report the error, but there isn't much else we can do */ ACPI_EXCEPTION ((AE_INFO, Status, "Could not release Global Lock")); } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiExDigitsNeeded * * PARAMETERS: Value - Value to be represented * Base - Base of representation * * RETURN: The number of digits. * * DESCRIPTION: Calculate the number of digits needed to represent the Value * in the given Base (Radix) * ******************************************************************************/ static UINT32 AcpiExDigitsNeeded ( UINT64 Value, UINT32 Base) { UINT32 NumDigits; UINT64 CurrentValue; ACPI_FUNCTION_TRACE (ExDigitsNeeded); /* UINT64 is unsigned, so we don't worry about a '-' prefix */ if (Value == 0) { return_UINT32 (1); } CurrentValue = Value; NumDigits = 0; /* Count the digits in the requested base */ while (CurrentValue) { (void) AcpiUtShortDivide (CurrentValue, Base, &CurrentValue, NULL); NumDigits++; } return_UINT32 (NumDigits); } /******************************************************************************* * * FUNCTION: AcpiExEisaIdToString * * PARAMETERS: OutString - Where to put the converted string (8 bytes) * CompressedId - EISAID to be converted * * RETURN: None * * DESCRIPTION: Convert a numeric EISAID to string representation. Return * buffer must be large enough to hold the string. The string * returned is always exactly of length ACPI_EISAID_STRING_SIZE * (includes null terminator). The EISAID is always 32 bits. * ******************************************************************************/ void AcpiExEisaIdToString ( char *OutString, UINT64 CompressedId) { UINT32 SwappedId; ACPI_FUNCTION_ENTRY (); /* The EISAID should be a 32-bit integer */ if (CompressedId > ACPI_UINT32_MAX) { ACPI_WARNING ((AE_INFO, "Expected EISAID is larger than 32 bits: " "0x%8.8X%8.8X, truncating", ACPI_FORMAT_UINT64 (CompressedId))); } /* Swap ID to big-endian to get contiguous bits */ SwappedId = AcpiUtDwordByteSwap ((UINT32) CompressedId); /* First 3 bytes are uppercase letters. Next 4 bytes are hexadecimal */ OutString[0] = (char) (0x40 + (((unsigned long) SwappedId >> 26) & 0x1F)); OutString[1] = (char) (0x40 + ((SwappedId >> 21) & 0x1F)); OutString[2] = (char) (0x40 + ((SwappedId >> 16) & 0x1F)); OutString[3] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 12); OutString[4] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 8); OutString[5] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 4); OutString[6] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 0); OutString[7] = 0; } /******************************************************************************* * * FUNCTION: AcpiExIntegerToString * * PARAMETERS: OutString - Where to put the converted string. At least * 21 bytes are needed to hold the largest * possible 64-bit integer. * Value - Value to be converted * * RETURN: Converted string in OutString * * DESCRIPTION: Convert a 64-bit integer to decimal string representation. * Assumes string buffer is large enough to hold the string. The * largest string is (ACPI_MAX64_DECIMAL_DIGITS + 1). * ******************************************************************************/ void AcpiExIntegerToString ( char *OutString, UINT64 Value) { UINT32 Count; UINT32 DigitsNeeded; UINT32 Remainder; ACPI_FUNCTION_ENTRY (); DigitsNeeded = AcpiExDigitsNeeded (Value, 10); OutString[DigitsNeeded] = 0; for (Count = DigitsNeeded; Count > 0; Count--) { (void) AcpiUtShortDivide (Value, 10, &Value, &Remainder); OutString[Count-1] = (char) ('0' + Remainder);\ } } /******************************************************************************* * * FUNCTION: AcpiExPciClsToString * * PARAMETERS: OutString - Where to put the converted string (7 bytes) * ClassCode - PCI class code to be converted (3 bytes) * * RETURN: Converted string in OutString * * DESCRIPTION: Convert 3-bytes PCI class code to string representation. * Return buffer must be large enough to hold the string. The * string returned is always exactly of length * ACPI_PCICLS_STRING_SIZE (includes null terminator). * ******************************************************************************/ void AcpiExPciClsToString ( char *OutString, UINT8 ClassCode[3]) { ACPI_FUNCTION_ENTRY (); /* All 3 bytes are hexadecimal */ OutString[0] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[0], 4); OutString[1] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[0], 0); OutString[2] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[1], 4); OutString[3] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[1], 0); OutString[4] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[2], 4); OutString[5] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[2], 0); OutString[6] = 0; } /******************************************************************************* * * FUNCTION: AcpiIsValidSpaceId * * PARAMETERS: SpaceId - ID to be validated * * RETURN: TRUE if SpaceId is a valid/supported ID. * * DESCRIPTION: Validate an operation region SpaceID. * ******************************************************************************/ BOOLEAN AcpiIsValidSpaceId ( UINT8 SpaceId) { if ((SpaceId >= ACPI_NUM_PREDEFINED_REGIONS) && (SpaceId < ACPI_USER_REGION_BEGIN) && (SpaceId != ACPI_ADR_SPACE_DATA_TABLE) && (SpaceId != ACPI_ADR_SPACE_FIXED_HARDWARE)) { return (FALSE); } return (TRUE); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/kmalloc_debug.h> #include "termutil.h" #include "dp_int.h" static size_t heaps_alloc[KMALLOC_HEAPS_COUNT]; static struct debug_kmalloc_heap_info hi; static struct debug_kmalloc_stats stats; static size_t tot_usable_mem_kb; static size_t tot_used_mem_kb; static long tot_diff; static void dp_heaps_on_enter(void) { tot_usable_mem_kb = 0; tot_used_mem_kb = 0; tot_diff = 0; for (int i = 0; i < KMALLOC_HEAPS_COUNT; i++) { if (!debug_kmalloc_get_heap_info(i, &hi)) break; const ulong size_kb = hi.size / KB; const ulong allocated_kb = hi.mem_allocated / KB; const long diff = (long)hi.mem_allocated - (long)heaps_alloc[i]; tot_usable_mem_kb += size_kb; tot_used_mem_kb += allocated_kb; tot_diff += diff; } // SA: avoid division by zero warning ASSERT(tot_usable_mem_kb > 0); debug_kmalloc_get_stats(&stats); } static void dp_show_kmalloc_heaps(void) { int row = dp_screen_start_row; const int col = dp_start_col + 40; dp_writeln2("[ Small heaps ]"); dp_writeln2("count: %3d [peak: %3d]", stats.small_heaps.tot_count, stats.small_heaps.peak_count); dp_writeln2("non-full: %3d [peak: %3d]", stats.small_heaps.not_full_count, stats.small_heaps.peak_not_full_count); row = dp_screen_start_row; dp_writeln("Usable: %6u KB", tot_usable_mem_kb); dp_writeln("Used: %6u KB (%u%%)", tot_used_mem_kb, (tot_used_mem_kb * 100) / tot_usable_mem_kb); dp_writeln("Diff: %s%s%6d KB" RESET_ATTRS " [%d B]", dp_sign_value_esc_color(tot_diff), tot_diff > 0 ? "+" : " ", tot_diff / (long)KB, tot_diff); dp_writeln(""); dp_writeln( " H# " TERM_VLINE " R# " TERM_VLINE " vaddr " TERM_VLINE " size " TERM_VLINE " used " TERM_VLINE " MBS " TERM_VLINE " diff " ); dp_writeln( GFX_ON "qqqqnqqqqnqqqqqqqqqqqqnqqqqqqqqnqqqqqqqqnqqqqqqqnqqqqqqqqqq" GFX_OFF ); for (int i = 0; i < KMALLOC_HEAPS_COUNT; i++) { if (!debug_kmalloc_get_heap_info(i, &hi)) break; char region_str[8] = "--"; ASSERT(hi.size); const ulong size_kb = hi.size / KB; const ulong allocated_kb = hi.mem_allocated / KB; const long diff = (long)hi.mem_allocated - (long)heaps_alloc[i]; if (hi.region >= 0) snprintk(region_str, sizeof(region_str), "%02d", hi.region); dp_writeln( " %2d " TERM_VLINE " %s " TERM_VLINE " %p " TERM_VLINE " %3u %s " TERM_VLINE " %3u.%u%% " TERM_VLINE " %4d " TERM_VLINE " %s%4d %s ", i, region_str, hi.vaddr, size_kb < 1024 ? size_kb : size_kb / 1024, size_kb < 1024 ? "KB" : "MB", allocated_kb * 100 / size_kb, (allocated_kb * 1000 / size_kb) % 10, hi.min_block_size, diff > 0 ? "+" : " ", dp_int_abs(diff) < 4096 ? diff : diff / 1024, dp_int_abs(diff) < 4096 ? "B " : "KB" ); } dp_writeln(""); } static void dp_heaps_on_exit(void) { for (int i = 0; i < KMALLOC_HEAPS_COUNT; i++) { if (!debug_kmalloc_get_heap_info(i, &hi)) break; heaps_alloc[i] = hi.mem_allocated; } } static struct dp_screen dp_heaps_screen = { .index = 2, .label = "Heaps", .draw_func = dp_show_kmalloc_heaps, .on_keypress_func = NULL, .on_dp_enter = dp_heaps_on_enter, .on_dp_exit = dp_heaps_on_exit, }; __attribute__((constructor)) static void dp_heaps_init(void) { dp_register_screen(&dp_heaps_screen); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck/common/basic_defs.h> #include <tilck/common/fat32_base.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <multiboot.h> #include "basic_term.h" #include "realmode_call.h" #include "mm.h" #include "common.h" static void dump_progress(const char *prefix_str, u32 curr, u32 tot) { bt_movecur(bt_get_curr_row(), 0); printk("%s%u%% ", prefix_str, 100 * curr / tot); } static u32 calc_fat_ramdisk_metadata_sz(struct fat_hdr *hdr) { const u32 sector_size = fat_get_sector_size(hdr); const u32 first_data_sector = fat_get_first_data_sector(hdr); /* Note: the `first_data_sector` is *relative* to the start of the ramdisk */ return sector_size * (first_data_sector + 1); } static void read_sectors_with_progress(const char *prefix_str, u32 paddr, u32 first_sector, u32 count) { const u32 chunk_sectors = 1024; const u32 chunks_count = count / chunk_sectors; const u32 rem = count - chunks_count * chunk_sectors; for (u32 chunk = 0; chunk < chunks_count; chunk++) { const u32 sectors_read = chunk * chunk_sectors; if (sectors_read > 0) dump_progress(prefix_str, sectors_read, count); read_sectors(paddr, first_sector, chunk_sectors); paddr += chunk_sectors * SECTOR_SIZE; first_sector += chunk_sectors; } if (rem > 0) { read_sectors(paddr, first_sector, rem); } dump_progress(prefix_str, count, count); } u32 rd_compact_clusters(void *ramdisk, u32 rd_size) { u32 ff_clu_off; /* offset of ramdisk's first free cluster */ ff_clu_off = fat_get_first_free_cluster_off(ramdisk); if (ff_clu_off < rd_size) { printk("Compacting ramdisk... "); fat_compact_clusters(ramdisk); ff_clu_off = fat_get_first_free_cluster_off(ramdisk); rd_size = fat_calculate_used_bytes(ramdisk); if (rd_size != ff_clu_off) { printk("\n"); panic("fat_compact_clusters() failed: %u != %u", rd_size, ff_clu_off); } write_ok_msg(); } return rd_size; } static bool overlap_with_kernel_file(ulong pa, ulong sz) { if (!kernel_file_pa) return false; /* The kernel hasn't been loaded yet */ const ulong kbegin = kernel_file_pa; const ulong kend = kernel_file_pa + kernel_file_sz; return IN_RANGE(pa, kbegin, kend) || IN_RANGE(pa + sz, kbegin, kend); } static bool check_fat_header(struct fat_hdr *hdr) { /* * Minimum sanity checks for determining if we correctly read a real FAT * header or some corrupted data. */ if (hdr->BPB_BytsPerSec != SECTOR_SIZE) return false; switch (fat_get_type(hdr)) { case fat12_type: /* We never use FAT12: something must be wrong */ return false; case fat16_type: { struct fat16_header2 *h2 = (void *)(hdr + 1); if (h2->BS_FilSysType[0] != 'F' || h2->BS_FilSysType[1] != 'A' || h2->BS_FilSysType[2] != 'T') { /* * The FAT specification does not require BS_FilSysType to be set, * but the Tilck tools and most of the FAT tools in general do set * this field to a reasonable value like FAT16 or FAT32. If it * does not start with "FAT", something is wrong. */ return false; } } break; case fat32_type: { struct fat32_header2 *h2 = (void *)(hdr + 1); if (h2->BS_FilSysType[0] != 'F' || h2->BS_FilSysType[1] != 'A' || h2->BS_FilSysType[2] != 'T') { /* Same as for fat16_type */ return false; } } break; default: /* We couldn't determine the FAT type */ return false; } return true; } bool load_fat_ramdisk(const char *load_str, u32 first_sec, ulong min_paddr, ulong *ref_rd_paddr, u32 *ref_rd_size, bool alloc_extra_page) { u32 rd_sectors; /* rd_size in 512-bytes sectors (rounded-up) */ u32 rd_size; /* ramdisk size (used bytes in the fat partition) */ u32 rd_metadata_sz; /* size of ramdisk's metadata, including the FATs */ ulong rd_paddr; /* ramdisk physical address */ ulong free_mem; ulong size_to_alloc; printk("%s", load_str); free_mem = get_usable_mem(&g_meminfo, min_paddr, SECTOR_SIZE); if (!free_mem || overlap_with_kernel_file(free_mem, SECTOR_SIZE)) goto oom; // Read FAT's header read_sectors(free_mem, first_sec, 1 /* read just 1 sector */); // Do some sanity checks against data corruption if (!check_fat_header((void *)free_mem)) goto corrupted; // Determine FAT's metadata size rd_metadata_sz = calc_fat_ramdisk_metadata_sz((void *)free_mem); // Get a free mem area big enough for it free_mem = get_usable_mem(&g_meminfo, min_paddr, rd_metadata_sz); if (!free_mem || overlap_with_kernel_file(free_mem, rd_metadata_sz)) goto oom; // Now read all the meta-data up to the first data sector. read_sectors(free_mem, first_sec, rd_metadata_sz / SECTOR_SIZE); // Finally we're able to determine how big is the fatpart (pure data) rd_size = fat_calculate_used_bytes((void *)free_mem); /* Calculate rd_size in sectors, rounding up at SECTOR_SIZE */ rd_sectors = (rd_size + SECTOR_SIZE - 1) / SECTOR_SIZE; size_to_alloc = SECTOR_SIZE * rd_sectors; if (alloc_extra_page) size_to_alloc += PAGE_SIZE; // Finally, get a mem area big enough for the whole FAT partition free_mem = get_usable_mem(&g_meminfo, min_paddr, size_to_alloc); if (!free_mem || overlap_with_kernel_file(free_mem, size_to_alloc)) goto oom; rd_paddr = free_mem; read_sectors_with_progress(load_str, rd_paddr, first_sec, rd_sectors); bt_movecur(bt_get_curr_row(), 0); printk("%s", load_str); write_ok_msg(); /* Return ramdisk's paddr and size using the OUT parameters */ *ref_rd_paddr = rd_paddr; *ref_rd_size = rd_size; return true; oom: printk("No free memory for loading the ramdisk\n"); goto end; corrupted: printk("FAT header corrupted\n"); goto end; end: write_fail_msg(); return false; } <file_sep>#!/bin/sh objdump -D -Mintel,i386 -b binary -m i386 $@ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/list.h> struct user_mapping { struct list_node pi_node; struct list_node inode_node; struct process *pi; fs_handle h; size_t len; size_t off; union { void *vaddrp; ulong vaddr; }; int prot; }; struct user_mapping * process_add_user_mapping(fs_handle h, void *v, size_t ln, size_t off, int prot); void process_remove_user_mapping(struct user_mapping *um); void full_remove_user_mapping(struct process *pi, struct user_mapping *um); void remove_all_mappings_of_handle(struct process *pi, fs_handle h); void remove_all_user_zero_mem_mappings(struct process *pi); struct user_mapping *process_get_user_mapping(void *vaddr); void remove_all_file_mappings(struct process *pi); struct mappings_info * duplicate_mappings_info(struct process *new_pi, struct mappings_info *mi); /* Internal functions */ bool user_valloc_and_map(ulong user_vaddr, size_t page_count); void user_vfree_and_unmap(ulong user_vaddr, size_t page_count); void user_unmap_zero_page(ulong user_vaddr, size_t page_count); bool user_map_zero_page(ulong user_vaddr, size_t page_count); int generic_fs_munmap(struct user_mapping *um, void *vaddrp, size_t len); /* Special one-time funcs */ void set_kernel_process_pdir(pdir_t *pdir); <file_sep>/****************************************************************************** * * Module Name: dsopcode - Dispatcher support for regions and fields * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acevents.h" #include "actables.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsopcode") /* Local prototypes */ static ACPI_STATUS AcpiDsInitBufferField ( UINT16 AmlOpcode, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *BufferDesc, ACPI_OPERAND_OBJECT *OffsetDesc, ACPI_OPERAND_OBJECT *LengthDesc, ACPI_OPERAND_OBJECT *ResultDesc); /******************************************************************************* * * FUNCTION: AcpiDsInitializeRegion * * PARAMETERS: ObjHandle - Region namespace node * * RETURN: Status * * DESCRIPTION: Front end to EvInitializeRegion * ******************************************************************************/ ACPI_STATUS AcpiDsInitializeRegion ( ACPI_HANDLE ObjHandle) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ObjDesc = AcpiNsGetAttachedObject (ObjHandle); /* Namespace is NOT locked */ Status = AcpiEvInitializeRegion (ObjDesc); return (Status); } /******************************************************************************* * * FUNCTION: AcpiDsInitBufferField * * PARAMETERS: AmlOpcode - CreateXxxField * ObjDesc - BufferField object * BufferDesc - Host Buffer * OffsetDesc - Offset into buffer * LengthDesc - Length of field (CREATE_FIELD_OP only) * ResultDesc - Where to store the result * * RETURN: Status * * DESCRIPTION: Perform actual initialization of a buffer field * ******************************************************************************/ static ACPI_STATUS AcpiDsInitBufferField ( UINT16 AmlOpcode, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *BufferDesc, ACPI_OPERAND_OBJECT *OffsetDesc, ACPI_OPERAND_OBJECT *LengthDesc, ACPI_OPERAND_OBJECT *ResultDesc) { UINT32 Offset; UINT32 BitOffset; UINT32 BitCount; UINT8 FieldFlags; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsInitBufferField, ObjDesc); /* Host object must be a Buffer */ if (BufferDesc->Common.Type != ACPI_TYPE_BUFFER) { ACPI_ERROR ((AE_INFO, "Target of Create Field is not a Buffer object - %s", AcpiUtGetObjectTypeName (BufferDesc))); Status = AE_AML_OPERAND_TYPE; goto Cleanup; } /* * The last parameter to all of these opcodes (ResultDesc) started * out as a NameString, and should therefore now be a NS node * after resolution in AcpiExResolveOperands(). */ if (ACPI_GET_DESCRIPTOR_TYPE (ResultDesc) != ACPI_DESC_TYPE_NAMED) { ACPI_ERROR ((AE_INFO, "(%s) destination not a NS Node [%s]", AcpiPsGetOpcodeName (AmlOpcode), AcpiUtGetDescriptorName (ResultDesc))); Status = AE_AML_OPERAND_TYPE; goto Cleanup; } Offset = (UINT32) OffsetDesc->Integer.Value; /* * Setup the Bit offsets and counts, according to the opcode */ switch (AmlOpcode) { case AML_CREATE_FIELD_OP: /* Offset is in bits, count is in bits */ FieldFlags = AML_FIELD_ACCESS_BYTE; BitOffset = Offset; BitCount = (UINT32) LengthDesc->Integer.Value; /* Must have a valid (>0) bit count */ if (BitCount == 0) { ACPI_BIOS_ERROR ((AE_INFO, "Attempt to CreateField of length zero")); Status = AE_AML_OPERAND_VALUE; goto Cleanup; } break; case AML_CREATE_BIT_FIELD_OP: /* Offset is in bits, Field is one bit */ BitOffset = Offset; BitCount = 1; FieldFlags = AML_FIELD_ACCESS_BYTE; break; case AML_CREATE_BYTE_FIELD_OP: /* Offset is in bytes, field is one byte */ BitOffset = 8 * Offset; BitCount = 8; FieldFlags = AML_FIELD_ACCESS_BYTE; break; case AML_CREATE_WORD_FIELD_OP: /* Offset is in bytes, field is one word */ BitOffset = 8 * Offset; BitCount = 16; FieldFlags = AML_FIELD_ACCESS_WORD; break; case AML_CREATE_DWORD_FIELD_OP: /* Offset is in bytes, field is one dword */ BitOffset = 8 * Offset; BitCount = 32; FieldFlags = AML_FIELD_ACCESS_DWORD; break; case AML_CREATE_QWORD_FIELD_OP: /* Offset is in bytes, field is one qword */ BitOffset = 8 * Offset; BitCount = 64; FieldFlags = AML_FIELD_ACCESS_QWORD; break; default: ACPI_ERROR ((AE_INFO, "Unknown field creation opcode 0x%02X", AmlOpcode)); Status = AE_AML_BAD_OPCODE; goto Cleanup; } /* Entire field must fit within the current length of the buffer */ if ((BitOffset + BitCount) > (8 * (UINT32) BufferDesc->Buffer.Length)) { Status = AE_AML_BUFFER_LIMIT; ACPI_BIOS_EXCEPTION ((AE_INFO, Status, "Field [%4.4s] at bit offset/length %u/%u " "exceeds size of target Buffer (%u bits)", AcpiUtGetNodeName (ResultDesc), BitOffset, BitCount, 8 * (UINT32) BufferDesc->Buffer.Length)); goto Cleanup; } /* * Initialize areas of the field object that are common to all fields * For FieldFlags, use LOCK_RULE = 0 (NO_LOCK), * UPDATE_RULE = 0 (UPDATE_PRESERVE) */ Status = AcpiExPrepCommonFieldObject ( ObjDesc, FieldFlags, 0, BitOffset, BitCount); if (ACPI_FAILURE (Status)) { goto Cleanup; } ObjDesc->BufferField.BufferObj = BufferDesc; ObjDesc->BufferField.IsCreateField = AmlOpcode == AML_CREATE_FIELD_OP; /* Reference count for BufferDesc inherits ObjDesc count */ BufferDesc->Common.ReferenceCount = (UINT16) (BufferDesc->Common.ReferenceCount + ObjDesc->Common.ReferenceCount); Cleanup: /* Always delete the operands */ AcpiUtRemoveReference (OffsetDesc); AcpiUtRemoveReference (BufferDesc); if (AmlOpcode == AML_CREATE_FIELD_OP) { AcpiUtRemoveReference (LengthDesc); } /* On failure, delete the result descriptor */ if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ResultDesc); /* Result descriptor */ } else { /* Now the address and length are valid for this BufferField */ ObjDesc->BufferField.Flags |= AOPOBJ_DATA_VALID; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsEvalBufferFieldOperands * * PARAMETERS: WalkState - Current walk * Op - A valid BufferField Op object * * RETURN: Status * * DESCRIPTION: Get BufferField Buffer and Index * Called from AcpiDsExecEndOp during BufferField parse tree walk * ******************************************************************************/ ACPI_STATUS AcpiDsEvalBufferFieldOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *NextOp; ACPI_FUNCTION_TRACE_PTR (DsEvalBufferFieldOperands, Op); /* * This is where we evaluate the address and length fields of the * CreateXxxField declaration */ Node = Op->Common.Node; /* NextOp points to the op that holds the Buffer */ NextOp = Op->Common.Value.Arg; /* Evaluate/create the address and length operands */ Status = AcpiDsCreateOperands (WalkState, NextOp); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { return_ACPI_STATUS (AE_NOT_EXIST); } /* Resolve the operands */ Status = AcpiExResolveOperands ( Op->Common.AmlOpcode, ACPI_WALK_OPERANDS, WalkState); if (ACPI_FAILURE (Status)) { ACPI_ERROR ((AE_INFO, "(%s) bad operand(s), status 0x%X", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), Status)); return_ACPI_STATUS (Status); } /* Initialize the Buffer Field */ if (Op->Common.AmlOpcode == AML_CREATE_FIELD_OP) { /* NOTE: Slightly different operands for this opcode */ Status = AcpiDsInitBufferField (Op->Common.AmlOpcode, ObjDesc, WalkState->Operands[0], WalkState->Operands[1], WalkState->Operands[2], WalkState->Operands[3]); } else { /* All other, CreateXxxField opcodes */ Status = AcpiDsInitBufferField (Op->Common.AmlOpcode, ObjDesc, WalkState->Operands[0], WalkState->Operands[1], NULL, WalkState->Operands[2]); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsEvalRegionOperands * * PARAMETERS: WalkState - Current walk * Op - A valid region Op object * * RETURN: Status * * DESCRIPTION: Get region address and length * Called from AcpiDsExecEndOp during OpRegion parse tree walk * ******************************************************************************/ ACPI_STATUS AcpiDsEvalRegionOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *OperandDesc; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *NextOp; ACPI_ADR_SPACE_TYPE SpaceId; ACPI_FUNCTION_TRACE_PTR (DsEvalRegionOperands, Op); /* * This is where we evaluate the address and length fields of the * OpRegion declaration */ Node = Op->Common.Node; /* NextOp points to the op that holds the SpaceID */ NextOp = Op->Common.Value.Arg; SpaceId = (ACPI_ADR_SPACE_TYPE) NextOp->Common.Value.Integer; /* NextOp points to address op */ NextOp = NextOp->Common.Next; /* Evaluate/create the address and length operands */ Status = AcpiDsCreateOperands (WalkState, NextOp); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Resolve the length and address operands to numbers */ Status = AcpiExResolveOperands ( Op->Common.AmlOpcode, ACPI_WALK_OPERANDS, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { return_ACPI_STATUS (AE_NOT_EXIST); } /* * Get the length operand and save it * (at Top of stack) */ OperandDesc = WalkState->Operands[WalkState->NumOperands - 1]; ObjDesc->Region.Length = (UINT32) OperandDesc->Integer.Value; AcpiUtRemoveReference (OperandDesc); /* A zero-length operation region is unusable. Just warn */ if (!ObjDesc->Region.Length && (SpaceId < ACPI_NUM_PREDEFINED_REGIONS)) { ACPI_WARNING ((AE_INFO, "Operation Region [%4.4s] has zero length (SpaceId %X)", Node->Name.Ascii, SpaceId)); } /* * Get the address and save it * (at top of stack - 1) */ OperandDesc = WalkState->Operands[WalkState->NumOperands - 2]; ObjDesc->Region.Address = (ACPI_PHYSICAL_ADDRESS) OperandDesc->Integer.Value; AcpiUtRemoveReference (OperandDesc); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "RgnObj %p Addr %8.8X%8.8X Len %X\n", ObjDesc, ACPI_FORMAT_UINT64 (ObjDesc->Region.Address), ObjDesc->Region.Length)); Status = AcpiUtAddAddressRange (ObjDesc->Region.SpaceId, ObjDesc->Region.Address, ObjDesc->Region.Length, Node); /* Now the address and length are valid for this opregion */ ObjDesc->Region.Flags |= AOPOBJ_DATA_VALID; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsEvalTableRegionOperands * * PARAMETERS: WalkState - Current walk * Op - A valid region Op object * * RETURN: Status * * DESCRIPTION: Get region address and length. * Called from AcpiDsExecEndOp during DataTableRegion parse * tree walk. * ******************************************************************************/ ACPI_STATUS AcpiDsEvalTableRegionOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT **Operand; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *NextOp; ACPI_TABLE_HEADER *Table; UINT32 TableIndex; ACPI_FUNCTION_TRACE_PTR (DsEvalTableRegionOperands, Op); /* * This is where we evaluate the Signature string, OemId string, * and OemTableId string of the Data Table Region declaration */ Node = Op->Common.Node; /* NextOp points to Signature string op */ NextOp = Op->Common.Value.Arg; /* * Evaluate/create the Signature string, OemId string, * and OemTableId string operands */ Status = AcpiDsCreateOperands (WalkState, NextOp); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Operand = &WalkState->Operands[0]; /* * Resolve the Signature string, OemId string, * and OemTableId string operands */ Status = AcpiExResolveOperands ( Op->Common.AmlOpcode, ACPI_WALK_OPERANDS, WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* Find the ACPI table */ Status = AcpiTbFindTable ( Operand[0]->String.Pointer, Operand[1]->String.Pointer, Operand[2]->String.Pointer, &TableIndex); if (ACPI_FAILURE (Status)) { if (Status == AE_NOT_FOUND) { ACPI_ERROR ((AE_INFO, "ACPI Table [%4.4s] OEM:(%s, %s) not found in RSDT/XSDT", Operand[0]->String.Pointer, Operand[1]->String.Pointer, Operand[2]->String.Pointer)); } goto Cleanup; } Status = AcpiGetTableByIndex (TableIndex, &Table); if (ACPI_FAILURE (Status)) { goto Cleanup; } ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { Status = AE_NOT_EXIST; goto Cleanup; } ObjDesc->Region.Address = ACPI_PTR_TO_PHYSADDR (Table); ObjDesc->Region.Length = Table->Length; ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "RgnObj %p Addr %8.8X%8.8X Len %X\n", ObjDesc, ACPI_FORMAT_UINT64 (ObjDesc->Region.Address), ObjDesc->Region.Length)); /* Now the address and length are valid for this opregion */ ObjDesc->Region.Flags |= AOPOBJ_DATA_VALID; Cleanup: AcpiUtRemoveReference (Operand[0]); AcpiUtRemoveReference (Operand[1]); AcpiUtRemoveReference (Operand[2]); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsEvalDataObjectOperands * * PARAMETERS: WalkState - Current walk * Op - A valid DataObject Op object * ObjDesc - DataObject * * RETURN: Status * * DESCRIPTION: Get the operands and complete the following data object types: * Buffer, Package. * ******************************************************************************/ ACPI_STATUS AcpiDsEvalDataObjectOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ArgDesc; UINT32 Length; ACPI_FUNCTION_TRACE (DsEvalDataObjectOperands); /* The first operand (for all of these data objects) is the length */ /* * Set proper index into operand stack for AcpiDsObjStackPush * invoked inside AcpiDsCreateOperand. */ WalkState->OperandIndex = WalkState->NumOperands; /* Ignore if child is not valid */ if (!Op->Common.Value.Arg) { ACPI_ERROR ((AE_INFO, "Missing child while evaluating opcode %4.4X, Op %p", Op->Common.AmlOpcode, Op)); return_ACPI_STATUS (AE_OK); } Status = AcpiDsCreateOperand (WalkState, Op->Common.Value.Arg, 1); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiExResolveOperands (WalkState->Opcode, &(WalkState->Operands [WalkState->NumOperands -1]), WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Extract length operand */ ArgDesc = WalkState->Operands [WalkState->NumOperands - 1]; Length = (UINT32) ArgDesc->Integer.Value; /* Cleanup for length operand */ Status = AcpiDsObjStackPop (1, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiUtRemoveReference (ArgDesc); /* * Create the actual data object */ switch (Op->Common.AmlOpcode) { case AML_BUFFER_OP: Status = AcpiDsBuildInternalBufferObj ( WalkState, Op, Length, &ObjDesc); break; case AML_PACKAGE_OP: case AML_VARIABLE_PACKAGE_OP: Status = AcpiDsBuildInternalPackageObj ( WalkState, Op, Length, &ObjDesc); break; default: return_ACPI_STATUS (AE_AML_BAD_OPCODE); } if (ACPI_SUCCESS (Status)) { /* * Return the object in the WalkState, unless the parent is a package - * in this case, the return object will be stored in the parse tree * for the package. */ if ((!Op->Common.Parent) || ((Op->Common.Parent->Common.AmlOpcode != AML_PACKAGE_OP) && (Op->Common.Parent->Common.AmlOpcode != AML_VARIABLE_PACKAGE_OP) && (Op->Common.Parent->Common.AmlOpcode != AML_NAME_OP))) { WalkState->ResultObj = ObjDesc; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsEvalBankFieldOperands * * PARAMETERS: WalkState - Current walk * Op - A valid BankField Op object * * RETURN: Status * * DESCRIPTION: Get BankField BankValue * Called from AcpiDsExecEndOp during BankField parse tree walk * ******************************************************************************/ ACPI_STATUS AcpiDsEvalBankFieldOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *OperandDesc; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *NextOp; ACPI_PARSE_OBJECT *Arg; ACPI_FUNCTION_TRACE_PTR (DsEvalBankFieldOperands, Op); /* * This is where we evaluate the BankValue field of the * BankField declaration */ /* NextOp points to the op that holds the Region */ NextOp = Op->Common.Value.Arg; /* NextOp points to the op that holds the Bank Register */ NextOp = NextOp->Common.Next; /* NextOp points to the op that holds the Bank Value */ NextOp = NextOp->Common.Next; /* * Set proper index into operand stack for AcpiDsObjStackPush * invoked inside AcpiDsCreateOperand. * * We use WalkState->Operands[0] to store the evaluated BankValue */ WalkState->OperandIndex = 0; Status = AcpiDsCreateOperand (WalkState, NextOp, 0); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiExResolveToValue (&WalkState->Operands[0], WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ACPI_DUMP_OPERANDS (ACPI_WALK_OPERANDS, AcpiPsGetOpcodeName (Op->Common.AmlOpcode), 1); /* * Get the BankValue operand and save it * (at Top of stack) */ OperandDesc = WalkState->Operands[0]; /* Arg points to the start Bank Field */ Arg = AcpiPsGetArg (Op, 4); while (Arg) { /* Ignore OFFSET and ACCESSAS terms here */ if (Arg->Common.AmlOpcode == AML_INT_NAMEDFIELD_OP) { Node = Arg->Common.Node; ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { return_ACPI_STATUS (AE_NOT_EXIST); } ObjDesc->BankField.Value = (UINT32) OperandDesc->Integer.Value; } /* Move to next field in the list */ Arg = Arg->Common.Next; } AcpiUtRemoveReference (OperandDesc); return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <stdint.h> #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> #include <termios.h> #include <assert.h> #include <tilck/common/basic_defs.h> /* for STATIC_ASSERT and ARRAY_SIZE */ #define HIST_SIZE 16 #define SEQ_UP "\033[A\0\0\0\0\0" #define SEQ_DOWN "\033[B\0\0\0\0\0" #define SEQ_RIGHT "\033[C\0\0\0\0\0" #define SEQ_LEFT "\033[D\0\0\0\0\0" #define SEQ_DELETE "\033[3~\0\0\0\0" #define SEQ_HOME "\033[1~\0\0\0\0" #define SEQ_END "\033[4~\0\0\0\0" #define SEQ_HOME2 "\033[H\0\0\0\0\0" #define SEQ_END2 "\033[F\0\0\0\0\0" STATIC_ASSERT(sizeof(SEQ_UP) == 9); STATIC_ASSERT(sizeof(SEQ_DOWN) == 9); STATIC_ASSERT(sizeof(SEQ_RIGHT) == 9); STATIC_ASSERT(sizeof(SEQ_LEFT) == 9); STATIC_ASSERT(sizeof(SEQ_DELETE) == 9); STATIC_ASSERT(sizeof(SEQ_HOME) == 9); STATIC_ASSERT(sizeof(SEQ_END) == 9); STATIC_ASSERT(sizeof(SEQ_HOME2) == 9); STATIC_ASSERT(sizeof(SEQ_END2) == 9); #define SN(s) (*(uint64_t*)(s)) #define WRITE_BS "\033[D \033[D\0" #define KEY_BACKSPACE 0x7f static char cmd_history[HIST_SIZE][256]; static unsigned hist_count; static unsigned curr_hist_cmd_to_show; static int curr_line_pos; static inline void move_right(int n) { char buf[16]; int rc = sprintf(buf, "\033[%dC", n); write(1, buf, rc); } static inline void move_left(int n) { char buf[16]; int rc = sprintf(buf, "\033[%dD", n); write(1, buf, rc); } static inline void put_in_history(const char *cmdline) { strcpy(cmd_history[hist_count++ % HIST_SIZE], cmdline); } static const char *get_prev_cmd(unsigned count) { if (!count || count > hist_count || count > HIST_SIZE) return NULL; return cmd_history[(hist_count - count) % HIST_SIZE]; } static inline void raw_mode_erase_last(void) { write(1, WRITE_BS, 7); } static void erase_line_on_screen(int curr_cmd_len) { for (; curr_cmd_len > 0; curr_cmd_len--) { raw_mode_erase_last(); } } static uint64_t read_esc_seq(void) { char c; int len = 0; union { char buf[8]; uint64_t num; } data; data.num = 0; data.buf[len++] = '\033'; if (read(0, &c, 1) <= 0) return 0; if (c != '[') return 0; /* unknown escape sequence */ data.buf[len++] = c; while (true) { if (read(0, &c, 1) <= 0) return 0; data.buf[len++] = c; if (IN_RANGE_INC(c, 0x40, 0x7E) && c != '[') break; if (len == 8) return 0; /* no more space in our 64-bit int (seq too long) */ } return data.num; } static void handle_seq_home(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { move_left(curr_line_pos); curr_line_pos = 0; } static void handle_seq_end(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { move_right(*c_cmd_len - curr_line_pos); curr_line_pos = *c_cmd_len; } static void handle_seq_delete(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { if (!*c_cmd_len || curr_line_pos == *c_cmd_len) return; (*c_cmd_len)--; for (int i = curr_line_pos; i < *c_cmd_len + 1; i++) { buf[i] = buf[i+1]; } buf[*c_cmd_len] = ' '; write(1, buf + curr_line_pos, *c_cmd_len - curr_line_pos + 1); move_left(*c_cmd_len - curr_line_pos + 1); } static void handle_seq_left(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { if (!curr_line_pos) return; move_left(1); curr_line_pos--; } static void handle_seq_right(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { if (curr_line_pos >= *c_cmd_len) return; move_right(1); curr_line_pos++; } static void handle_seq_updown(uint64_t seq, char *buf, int bs, char *c_cmd, int *c_cmd_len) { const char *cmd; if (curr_line_pos != *c_cmd_len - 1) { if (curr_line_pos < *c_cmd_len) { move_right(*c_cmd_len - curr_line_pos); curr_line_pos = *c_cmd_len; } } if (seq == SN(SEQ_UP)) { cmd = get_prev_cmd(curr_hist_cmd_to_show + 1); if (!cmd) return; if (!curr_hist_cmd_to_show) { buf[*c_cmd_len] = 0; strncpy(c_cmd, buf, bs); } curr_hist_cmd_to_show++; } else { cmd = get_prev_cmd(curr_hist_cmd_to_show - 1); if (cmd) { curr_hist_cmd_to_show--; } else { cmd = c_cmd; if (curr_hist_cmd_to_show == 1) curr_hist_cmd_to_show--; } } erase_line_on_screen(*c_cmd_len); strncpy(buf, cmd, bs); *c_cmd_len = strlen(buf); write(1, buf, *c_cmd_len); curr_line_pos = *c_cmd_len; } static struct { uint64_t seq; void (*fptr)(uint64_t, char *, int, char *, int *); } handle_esc_seq_table[] = { {0, handle_seq_home}, {0, handle_seq_end}, {0, handle_seq_delete}, {0, handle_seq_left}, {0, handle_seq_right}, {0, handle_seq_updown}, {0, handle_seq_updown}, {0, handle_seq_home}, {0, handle_seq_end}, }; static void initialize_once_handle_esc_seq_table(void) { static bool initalized; if (initalized) return; handle_esc_seq_table[0].seq = SN(SEQ_HOME); handle_esc_seq_table[1].seq = SN(SEQ_END); handle_esc_seq_table[2].seq = SN(SEQ_DELETE); handle_esc_seq_table[3].seq = SN(SEQ_LEFT); handle_esc_seq_table[4].seq = SN(SEQ_RIGHT); handle_esc_seq_table[5].seq = SN(SEQ_UP); handle_esc_seq_table[6].seq = SN(SEQ_DOWN); handle_esc_seq_table[7].seq = SN(SEQ_HOME2); handle_esc_seq_table[8].seq = SN(SEQ_END2); initalized = true; } static void handle_esc_seq(char *buf, int buf_size, char *c_cmd, int *c_cmd_len) { uint64_t seq = read_esc_seq(); if (!seq) return; initialize_once_handle_esc_seq_table(); for (int i = 0; i < ARRAY_SIZE(handle_esc_seq_table); i++) if (handle_esc_seq_table[i].seq == seq) handle_esc_seq_table[i].fptr(seq, buf, buf_size, c_cmd, c_cmd_len); } static void handle_backspace(char *buf, int buf_size, char *c_cmd, int *c_cmd_len) { if (!(*c_cmd_len) || !curr_line_pos) return; (*c_cmd_len)--; curr_line_pos--; raw_mode_erase_last(); if (curr_line_pos == (*c_cmd_len)) return; /* We have to shift left all the chars after curr_line_pos */ for (int i = curr_line_pos; i < (*c_cmd_len) + 1; i++) { buf[i] = buf[i+1]; } buf[(*c_cmd_len)] = ' '; write(1, buf + curr_line_pos, (*c_cmd_len) - curr_line_pos + 1); move_left(*c_cmd_len - curr_line_pos + 1); } static bool handle_regular_char(char c, char *buf, int bs, char *c_cmd, int *c_cmd_len) { int rc = write(1, &c, 1); if (rc < 0) { perror("write error"); *c_cmd_len = rc; return false; } if (c == '\n') return false; if (curr_line_pos == (*c_cmd_len)) { buf[curr_line_pos++] = c; } else { /* We have to shift right all the chars after curr_line_pos */ for (int i = (*c_cmd_len); i >= curr_line_pos; i--) { buf[i + 1] = buf[i]; } buf[curr_line_pos] = c; write(1, buf + curr_line_pos + 1, (*c_cmd_len) - curr_line_pos); curr_line_pos++; move_left(*c_cmd_len - curr_line_pos + 1); } (*c_cmd_len)++; return true; } int read_command(char *buf, int buf_size) { int rc; char c; int c_cmd_len = 0; struct termios orig_termios, t; char curr_cmd[buf_size]; // VLA tcgetattr(0, &orig_termios); t = orig_termios; t.c_iflag &= ~(BRKINT | INPCK | ISTRIP | IXON); t.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); tcsetattr(0, TCSAFLUSH, &t); curr_hist_cmd_to_show = 0; curr_line_pos = 0; while (c_cmd_len < buf_size - 1) { rc = read(0, &c, 1); if (rc == 0) break; if (rc < 0) { perror("read error"); c_cmd_len = rc; break; } if (c == KEY_BACKSPACE) { handle_backspace(buf, buf_size, curr_cmd, &c_cmd_len); } else if (c == '\033') { handle_esc_seq(buf, buf_size, curr_cmd, &c_cmd_len); } else if (isprint(c) || (isspace(c) && c != '\t')) { if (!handle_regular_char(c, buf, buf_size, curr_cmd, &c_cmd_len)) break; } else { /* just ignore everything else */ } } buf[c_cmd_len >= 0 ? c_cmd_len : 0] = 0; if (c_cmd_len > 0) put_in_history(buf); tcsetattr(0, TCSAFLUSH, &orig_termios); return c_cmd_len; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/test/fork.h> STATIC int fork_dup_all_handles(struct process *pi) { ASSERT(!is_preemption_enabled()); for (u32 i = 0; i < MAX_HANDLES; i++) { int rc; fs_handle dup_h = NULL; fs_handle h = pi->handles[i]; struct user_mapping *um; if (!h) continue; rc = vfs_dup(h, &dup_h); if (rc < 0 || !dup_h) { enable_preemption(); { for (u32 j = 0; j < i; j++) vfs_close(pi->handles[j]); } disable_preemption(); return -ENOMEM; } /* Update file handle's process pointer to the new process */ ((struct fs_handle_base *)dup_h)->pi = pi; /* Replace the older (parent's) handle with the new one */ pi->handles[i] = dup_h; if (!pi->mi) continue; list_for_each_ro(um, &pi->mi->mappings, pi_node) { if (um->h == h) um->h = dup_h; } } return 0; } // Returns child's pid int do_fork(bool vfork) { int pid; int rc = -EAGAIN; struct task *child = NULL; struct task *curr = get_curr_task(); struct process *curr_pi = curr->pi; pdir_t *new_pdir = NULL; disable_preemption(); ASSERT_TASK_STATE(curr->state, TASK_STATE_RUNNING); if ((pid = create_new_pid()) < 0) goto out; /* NOTE: rc is already set to -EAGAIN */ if (vfork) { if (!(child = allocate_new_process(curr, pid, curr_pi->pdir))) goto oom_case; } else { if (FORK_NO_COW) new_pdir = pdir_deep_clone(curr_pi->pdir); else new_pdir = pdir_clone(curr_pi->pdir); if (!new_pdir) goto oom_case; if (!(child = allocate_new_process(curr, pid, new_pdir))) goto oom_case; /* Set new_pdir in order to avoid its double-destruction */ new_pdir = NULL; } /* Child's kernel stack must be set */ ASSERT(child->kernel_stack != NULL); child->state = TASK_STATE_RUNNABLE; child->running_in_kernel = false; task_info_reset_kernel_stack(child); child->state_regs--; // make room for a regs_t struct in child's stack *child->state_regs = *curr->state_regs; // copy parent's regs_t set_return_register(child->state_regs, 0); // Make the parent to get child's pid as return value. set_return_register(curr->state_regs, (ulong) child->tid); if (fork_dup_all_handles(child->pi) < 0) goto oom_case; add_task(child); if (vfork) { curr->stopped = true; curr->vfork_stopped = true; } else { /* * X86-specific note: * Force the CR3 reflush using the current (parent's) pdir. * Without doing that, COW on parent's pages doesn't work immediately. * That is better than invalidating all the pages affected, one by one. */ set_curr_pdir(curr_pi->pdir); } enable_preemption(); if (vfork) { /* * Call the scheduler to wait until the child dies or calls execve(). * NOTE: we won't be woken up by a signal here, see signal.c. */ schedule(); /* Make absolutely sure that we're running because we're not stopped */ ASSERT(!curr->stopped); ASSERT(!curr->vfork_stopped); /* Check that the child died or called execve() */ ASSERT( (child->pi->did_call_execve && !child->pi->vforked) || child->state == TASK_STATE_ZOMBIE ); } return child->tid; oom_case: rc = -ENOMEM; if (new_pdir) pdir_destroy(new_pdir); if (child) { child->state = TASK_STATE_ZOMBIE; free_common_task_allocs(child); free_task(child); } out: enable_preemption(); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/pipe.h> #include <tilck/kernel/fs/kernelfs.h> #include <tilck/kernel/ringbuf.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> struct pipe { KOBJ_BASE_FIELDS char *buf; struct ringbuf rb; struct kmutex mutex; struct kcond not_full_cond; struct kcond not_empty_cond; struct kcond err_cond; ATOMIC(int) read_handles; ATOMIC(int) write_handles; }; static ssize_t pipe_read(fs_handle h, char *buf, size_t size, offt *pos) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; bool sig_pending = false; ssize_t rc = 0; ASSERT(*pos == 0); if (!size) return 0; kmutex_lock(&p->mutex); while (true) { rc = (ssize_t)ringbuf_read_bytes(&p->rb, (u8 *)buf, size); if (rc) break; /* Everything is alright, we read something */ if (atomic_load_explicit(&p->write_handles, mo_relaxed) == 0) { /* No more writers, always return 0, no matter what. */ break; } if (kh->fl_flags & O_NONBLOCK) { rc = -EAGAIN; break; } /* Wait for writers to fill up the buffer */ kcond_wait(&p->not_empty_cond, &p->mutex, KCOND_WAIT_FOREVER); /* After wake up */ if (pending_signals()) { sig_pending = true; break; } } /* * Wake up one blocked writer instead of all of them. * * Rationale: it is totally possible that just a single writer will fill up * the whole buffer and, after that, the other writers will wake up just to * discover they need to go back sleeping again. To spare those unnecessary * context switches, we just wake up a single writer and, after it's done it * will wake up writer if the buffer is still not full. * * The situation is perfectly symmetric for the readers as well, that's why * here below we wake up another reader if the buffer is not empty. */ kcond_signal_one(&p->not_full_cond); if (!ringbuf_is_empty(&p->rb)) { /* The buffer is not empty: wake up one more reader, if any */ kcond_signal_one(&p->not_empty_cond); } /* Unlock the pipe's state lock and return */ kmutex_unlock(&p->mutex); return !sig_pending ? rc : -EINTR; } static ssize_t pipe_write(fs_handle h, char *buf, size_t size, offt *pos) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; bool sig_pending = false; ssize_t rc = 0; ASSERT(*pos == 0); if (!size) return 0; kmutex_lock(&p->mutex); while (true) { if (atomic_load_explicit(&p->read_handles, mo_relaxed) == 0) { /* Broken pipe */ send_signal(get_curr_pid(), SIGPIPE, true); rc = -EPIPE; break; } rc = (ssize_t)ringbuf_write_bytes(&p->rb, (u8 *)buf, size); if (rc) break; /* Everything is alright, we wrote something */ if (kh->fl_flags & O_NONBLOCK) { rc = -EAGAIN; break; } /* Wait for readers to empty the buffer */ kcond_wait(&p->not_full_cond, &p->mutex, KCOND_WAIT_FOREVER); /* After wake up */ if (pending_signals()) { sig_pending = true; break; } } /* * Wake up one blocked reader, instead of all of them. * See the comments in pipe_read() above. */ kcond_signal_one(&p->not_empty_cond); if (!ringbuf_is_full(&p->rb)) { /* The buffer is not full: wake up one more writer, if any */ kcond_signal_one(&p->not_full_cond); } /* Unlock the pipe's state lock and return */ kmutex_unlock(&p->mutex); return !sig_pending ? rc : -EINTR; } static int pipe_read_ready(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; bool ret; kmutex_lock(&p->mutex); { ret = !ringbuf_is_empty(&p->rb) || atomic_load_explicit(&p->write_handles, mo_relaxed) == 0; } kmutex_unlock(&p->mutex); return ret; } static struct kcond *pipe_get_rready_cond(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; return &p->not_empty_cond; } static int pipe_write_ready(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; bool ret; kmutex_lock(&p->mutex); { ret = !ringbuf_is_full(&p->rb) || atomic_load_explicit(&p->read_handles, mo_relaxed) == 0; } kmutex_unlock(&p->mutex); return ret; } static struct kcond *pipe_get_wready_cond(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; return &p->not_full_cond; } static int pipe_except_ready(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; int ret = 0; kmutex_lock(&p->mutex); { if (atomic_load_explicit(&p->read_handles, mo_relaxed) == 0) ret |= POLLERR; if (atomic_load_explicit(&p->write_handles, mo_relaxed) == 0) ret |= POLLHUP; } kmutex_unlock(&p->mutex); return ret; } static struct kcond *pipe_get_except_cond(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; return &p->err_cond; } static const struct file_ops static_ops_pipe_read_end = { .read = pipe_read, .read_ready = pipe_read_ready, .except_ready = pipe_except_ready, .get_rready_cond = pipe_get_rready_cond, .get_except_cond = pipe_get_except_cond, }; static const struct file_ops static_ops_pipe_write_end = { .write = pipe_write, .except_ready = pipe_except_ready, .write_ready = pipe_write_ready, .get_wready_cond = pipe_get_wready_cond, .get_except_cond = pipe_get_except_cond, }; void destroy_pipe(struct pipe *p) { kcond_destory(&p->err_cond); kcond_destory(&p->not_empty_cond); kcond_destory(&p->not_full_cond); kmutex_destroy(&p->mutex); ringbuf_destory(&p->rb); kfree2(p->buf, PIPE_BUF_SIZE); kfree_obj(p, struct pipe); } static void pipe_on_handle_close(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; int old; old = atomic_fetch_sub_explicit( (kh->fl_flags & O_WRONLY) ? &p->write_handles : &p->read_handles, 1, mo_relaxed ); ASSERT(old > 0); if (old == 1) { kcond_signal_all(&p->not_full_cond); kcond_signal_all(&p->not_empty_cond); kcond_signal_all(&p->err_cond); } } static void pipe_on_handle_dup(fs_handle h) { struct kfs_handle *kh = h; struct pipe *p = (void *)kh->kobj; if (kh->fl_flags & O_WRONLY) { atomic_fetch_add_explicit(&p->write_handles, 1, mo_relaxed); } else { atomic_fetch_add_explicit(&p->read_handles, 1, mo_relaxed); } } struct pipe *create_pipe(void) { struct pipe *p; if (!(p = (void *)kzalloc_obj(struct pipe))) return NULL; if (!(p->buf = kmalloc(PIPE_BUF_SIZE))) { kfree_obj(p, struct pipe); return NULL; } p->on_handle_close = &pipe_on_handle_close; p->on_handle_dup = &pipe_on_handle_dup; p->destory_obj = (void *)&destroy_pipe; ringbuf_init(&p->rb, PIPE_BUF_SIZE, 1, p->buf); kmutex_init(&p->mutex, 0); kcond_init(&p->not_full_cond); kcond_init(&p->not_empty_cond); kcond_init(&p->err_cond); return p; } fs_handle pipe_create_read_handle(struct pipe *p) { fs_handle res = NULL; res = kfs_create_new_handle(&static_ops_pipe_read_end, (void *)p, O_RDONLY); if (res != NULL) atomic_fetch_add_explicit(&p->read_handles, 1, mo_relaxed); return res; } fs_handle pipe_create_write_handle(struct pipe *p) { fs_handle res = NULL; res = kfs_create_new_handle(&static_ops_pipe_write_end, (void*)p, O_WRONLY); if (res != NULL) atomic_fetch_add_explicit(&p->write_handles, 1, mo_relaxed); return res; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static struct ramfs_block *ramfs_new_block(offt page) { struct ramfs_block *b; /* Allocate memory for the block object */ if (!(b = kalloc_obj(struct ramfs_block))) return NULL; /* Allocate block's data */ if (!(b->vaddr = kzmalloc(PAGE_SIZE))) { kfree_obj(b, struct ramfs_block); return NULL; } /* Retain the pageframe used by this block */ retain_pageframes_mapped_at(get_kernel_pdir(), b->vaddr, PAGE_SIZE); /* Init the block object */ bintree_node_init(&b->node); b->offset = page; return b; } static void ramfs_destroy_block(struct ramfs_block *b) { /* Release the pageframe used by this block */ release_pageframes_mapped_at(get_kernel_pdir(), b->vaddr, PAGE_SIZE); /* Free the memory pointed by this block */ kfree2(b->vaddr, PAGE_SIZE); /* Free the memory used by the block object itself */ kfree_obj(b, struct ramfs_block); } static void ramfs_append_new_block(struct ramfs_inode *inode, struct ramfs_block *block) { DEBUG_ONLY_UNSAFE(bool success =) bintree_insert_ptr(&inode->blocks_tree_root, block, struct ramfs_block, node, offset); ASSERT(success); inode->blocks_count++; } static int ramfs_inode_extend(struct ramfs_inode *i, offt new_len) { ASSERT(rwlock_wp_holding_exlock(&i->rwlock)); ASSERT(new_len > i->fsize); i->fsize = new_len; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define _TILCK_BASIC_DEFS_H_ #include <tilck_gen_headers/config_global.h> /* * TESTING is defined when kernel unit tests are compiled and it affects * actual kernel headers but NOT kernel's C files. * * KERNEL_TEST is defined when the noarch part of the kernel is compiled for * unit tests. Therefore, it affects only the kernel's C files. * * UNIT_TEST_ENVIRONMENT is defined when TESTING or KERNEL_TEST is defined. * It make sense to be used in kernel headers that can be both used by the * kernel and by the tests itself, in particular when calling kernel header-only * code. Therefore, that macro it is the one that should be used the most since * it allows consistent behavior for headers & C files. */ #if defined(TESTING) || defined(KERNEL_TEST) #define UNIT_TEST_ENVIRONMENT #endif #if (defined(__TILCK_KERNEL__) || \ defined(UNIT_TEST_ENVIRONMENT) || \ defined(__cplusplus)) && !defined(__MOD_ACPICA__) #include <tilck_gen_headers/config_kernel.h> #endif #ifdef __cplusplus #if !KERNEL_FORCE_TC_ISYSTEM /* Default case: real kernel build */ #include <cstdint> // system header #include <climits> // system header #else /* Special case: non-runnable static analysis build */ #include <stdint.h> // system header #include <limits.h> // system header #endif #define STATIC_ASSERT(s) static_assert(s, "Static assertion failed") #else #include <stdint.h> // system header #include <stddef.h> // system header #include <stdbool.h> // system header #include <stdalign.h> // system header #include <inttypes.h> // system header #include <limits.h> // system header #define STATIC_ASSERT(s) _Static_assert(s, "Static assertion failed") #endif // #ifdef __cplusplus #ifndef __USE_MISC #define __USE_MISC #endif #include <stdarg.h> #include <sys/types.h> // system header (just for ulong) #ifdef __i386__ STATIC_ASSERT(sizeof(void *) == 4); STATIC_ASSERT(sizeof(long) == sizeof(void *)); #define BITS32 #define NBITS 32 #elif defined(__x86_64__) STATIC_ASSERT(sizeof(void *) == 8); STATIC_ASSERT(sizeof(long) == sizeof(void *)); #define BITS64 #define NBITS 64 #elif defined(__aarch64__) && (defined(USERMODE_APP) || defined(UNIT_TEST_ENVIRONMENT)) /* * The Tilck kernel doesn't support ARM or AARCH64 (yet), but it can be * compiled on Linux-aarch64 as host architecture. Therefore, we need * to build the build apps for aarch64. */ STATIC_ASSERT(sizeof(void *) == 8); STATIC_ASSERT(sizeof(long) == sizeof(void *)); #define BITS64 #define NBITS 64 #else #error Architecture not supported. #endif #ifndef TESTING #ifndef __cplusplus #define NORETURN _Noreturn /* C11 no return attribute */ #else #undef NULL #define NULL nullptr #define NORETURN [[ noreturn ]] /* C++11 no return attribute */ #endif #else #define NORETURN #endif #define OFFSET_OF(st, m) __builtin_offsetof(st, m) #define ALWAYS_INLINE __attribute__((always_inline)) inline #define NO_INLINE __attribute__((noinline)) #define asmVolatile __asm__ volatile #define asm __asm__ #define typeof(x) __typeof__(x) #define PURE __attribute__((pure)) #define CONSTEXPR __attribute__((const)) #define WEAK __attribute__((weak)) #define PACKED __attribute__((packed)) #define NODISCARD __attribute__((warn_unused_result)) #define ASSUME_WITHOUT_CHECK(x) if (!(x)) __builtin_unreachable(); #define ALIGNED_AT(x) __attribute__ ((aligned(x))) #define ATTR_PRINTF_LIKE(c) __attribute__ ((__format__ (__printf__, c, c+1))) #define ATTR_SECTION(s) __attribute__ ((section (s))) #ifdef BITS32 #define FASTCALL __attribute__((fastcall)) #else #define FASTCALL #endif typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; /* Pointer-size signed integer */ /* * Just use `long`. We support only LP64 compilers and 32/64 bit architectures. * 16-bit architectures where sizeof(long) > sizeof(void *) won't be supported. */ /* Pointer-size unsigned integer */ /* Just use `ulong` (from sys/types.h). Reason: see the comment for long */ /* What we're relying on */ STATIC_ASSERT(sizeof(ulong) == sizeof(long)); STATIC_ASSERT(sizeof(ulong) == sizeof(void *)); /* * Tilck's off_t, unrelated with any external files. * * The size of `offt` determine the max size of files and devices that Tilck * can access. By default, it's a signed 64-bit integer and that doesn't have * a measurable impact on Tilck's performance even on 32-bit systems where * 64-bit integers require multiple instructions and two registers. But, the * size of `offt` is configurable in order to force the code to not make direct * assumptions about its size. Also, on some small-scale embedded systems, it * might be convenient to consider disabling the KERNEL_64BIT_OFFT and save * some space in structs, along with a few CPU cycles. */ #ifdef HAVE_KERNEL_CONFIG #if KERNEL_64BIT_OFFT typedef int64_t offt; #define OFFT_MAX ((offt)INT64_MAX) #else typedef long offt; #define OFFT_MAX ((offt)LONG_MAX) #endif STATIC_ASSERT(sizeof(offt) >= sizeof(long)); #endif /* * An useful two-pass concatenation macro. * * The reason for using a two-pass macro is to allow the arguments to expand * in case they are using macros themselfs. Consider the following example: * * #define SOME_STRING_LITERAL "hello world" * #define WIDE_STR_LITERAL _CONCAT(L, SOME_STRING_LITERAL) * * The macro `WIDE_STR_LITERAL` will expand to: LSOME_STRING_LITERAL. That * clearly is NOT what we wanted. While, by using the two-pass expansion we * get `WIDE_STR_LITERAL` expanded to: L"hello world". */ #define _CONCAT(a, b) a##b #define CONCAT(a, b) _CONCAT(a, b) /* * UNSAFE against double-evaluation MIN, MAX, ABS, CLAMP macros. * They are necessary for all the cases when the compiler (GCC and Clang) * fails to compile with the other ones. The known cases are: * * - Initialization of struct fields like: * struct x var = (x) { .field1 = MIN(a, b), .field2 = 0 }; * * - Use bit-field variable as argument of MIN() or MAX() * * There might be other cases as well. */ #define UNSAFE_MIN(x, y) (((x) <= (y)) ? (x) : (y)) #define UNSAFE_MAX(x, y) (((x) > (y)) ? (x) : (y)) #define UNSAFE_MIN3(x, y, z) UNSAFE_MIN(UNSAFE_MIN((x), (y)), (z)) #define UNSAFE_MAX3(x, y, z) UNSAFE_MAX(UNSAFE_MAX((x), (y)), (z)) #define UNSAFE_ABS(x) ((x) >= 0 ? (x) : -(x)) #define UNSAFE_CLAMP(val, minval, maxval) \ UNSAFE_MIN(UNSAFE_MAX((val), (minval)), (maxval)) /* * SAFE against double-evaluation MIN, MAX, ABS, CLAMP macros. * Use these when possible. In all the other cases, use their UNSAFE version. */ #define MIN(a, b) \ ({ \ const typeof(a) CONCAT(_a, __LINE__) = (a); \ const typeof(b) CONCAT(_b, __LINE__) = (b); \ UNSAFE_MIN(CONCAT(_a, __LINE__), CONCAT(_b, __LINE__)); \ }) #define MAX(a, b) \ ({ \ const typeof(a) CONCAT(_a, __LINE__) = (a); \ const typeof(b) CONCAT(_b, __LINE__) = (b); \ UNSAFE_MAX(CONCAT(_a, __LINE__), CONCAT(_b, __LINE__)); \ }) #define MIN3(a, b, c) \ ({ \ const typeof(a) CONCAT(_a, __LINE__) = (a); \ const typeof(b) CONCAT(_b, __LINE__) = (b); \ const typeof(c) CONCAT(_c, __LINE__) = (c); \ UNSAFE_MIN3(CONCAT(_a, __LINE__), \ CONCAT(_b, __LINE__), \ CONCAT(_c, __LINE__)); \ }) #define MAX3(a, b, c) \ ({ \ const typeof(a) CONCAT(_a, __LINE__) = (a); \ const typeof(b) CONCAT(_b, __LINE__) = (b); \ const typeof(c) CONCAT(_c, __LINE__) = (c); \ UNSAFE_MAX3(CONCAT(_a, __LINE__), \ CONCAT(_b, __LINE__), \ CONCAT(_c, __LINE__)); \ }) #define CLAMP(val, minval, maxval) \ ({ \ const typeof(val) CONCAT(_v, __LINE__) = (val); \ const typeof(minval) CONCAT(_mv, __LINE__) = (minval); \ const typeof(maxval) CONCAT(_Mv, __LINE__) = (maxval); \ UNSAFE_CLAMP(CONCAT(_v, __LINE__), \ CONCAT(_mv, __LINE__), \ CONCAT(_Mv, __LINE__)); \ }) #define ABS(x) \ ({ \ const typeof(x) CONCAT(_v, __LINE__) = (x); \ UNSAFE_ABS(CONCAT(_v, __LINE__)); \ }) #define LIKELY(x) __builtin_expect((x), true) #define UNLIKELY(x) __builtin_expect((x), false) #define ARRAY_SIZE(a) ((int)(sizeof(a)/sizeof((a)[0]))) #define CONTAINER_OF(elem_ptr, struct_type, mem_name) \ ( \ (struct_type *)(void *)( \ ((char *)elem_ptr) - OFFSET_OF(struct_type, mem_name) \ ) \ ) /* * Brutal double-cast converting any integer to a void * pointer. * * This unsafe macro is a nice cosmetic sugar for all the cases where a integer * not always having pointer-size width has to be converted to a pointer. * * Typical use cases: * - multiboot 1 code uses 32-bit integers for rappresenting addresses, even * on 64-bit architectures. * * - in EFI code, EFI_PHYSICAL_ADDRESS is 64-bit wide, even on 32-bit * machines. */ #define TO_PTR(n) ((void *)(ulong)(n)) #ifndef __clang__ #define DO_NOT_OPTIMIZE_AWAY(x) asmVolatile("" : "+r" ( TO_PTR(x) )) #else static ALWAYS_INLINE void __do_not_opt_away(void *x) { asmVolatile("" ::: "memory"); } #define DO_NOT_OPTIMIZE_AWAY(x) (__do_not_opt_away((void *)(x))) #endif #define ALIGNED_MASK(n) (~((n) - 1)) #define POINTER_ALIGN_MASK ALIGNED_MASK(sizeof(void *)) // Standard compare function signature among generic objects. typedef long (*cmpfun_ptr)(const void *a, const void *b); #ifndef NO_TILCK_STATIC_WRAPPER #ifdef UNIT_TEST_ENVIRONMENT #define STATIC #define STATIC_INLINE #else #define STATIC static #define STATIC_INLINE static inline #endif #endif /* * Macros and inline functions designed to minimize the ugly code necessary * if we want to compile with -Wconversion. */ #define U32_BITMASK(n) ((u32)((1u << (n)) - 1u)) #define U64_BITMASK(n) ((u64)((1ull << (n)) - 1u)) /* * Get the lower `n` bits from val. * * Use case: * * union { u32 a: 20; b: 12 } u; * u32 var = 123; * u.a = var; // does NOT compile with -Wconversion * u.a = LO_BITS(var, 20, u32); // always compiles * * NOTE: Tilck support only Clang's -Wconversion, not GCC's. */ #if defined(BITS64) #define LO_BITS(val, n, t) ((t)((val) & U64_BITMASK(n))) #elif defined(BITS32) #define LO_BITS(val, n, t) ((t)((val) & U32_BITMASK(n))) #endif /* * Like LO_BITS() but first right-shift `val` by `rs` bits and than get its * lower N-rs bits in a -Wconversion-safe way. * * NOTE: Tilck support only clang's -Wconversion, not GCC's. */ #define SHR_BITS(val, rs, t) LO_BITS( ((val) >> (rs)), NBITS-(rs), t ) /* Checks if 'addr' is in the range [begin, end) */ #define IN_RANGE(addr, begin, end) ((begin) <= (addr) && (addr) < (end)) /* Checks if 'addr' is in the range [begin, end] */ #define IN_RANGE_INC(addr, begin, end) ((begin) <= (addr) && (addr) <= (end)) /* * With modern GCC compilers, things like *(u32 *)(ptr + off) are undefined * behavior if `ptr+off` is not aligned correctly, even on architectures * like x86 that natively support unaligned access. That's because in the C * standard (since C89) unaligned access is considered UB. * * From C11 (draft N1570): * << * Conversion between two pointer types produces a result that is * incorrectly aligned (6.3.2.3). * >> * * See GCC's bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93031 * * The correct solution to read/write values where the address might be * unaligned is to use __builtin_memcpy(): it will just emit a single MOV * instruction on x86, while it could do more on architectures where unaligned * access is not allowed. */ #define SAFE_READ(addr, type) ({ \ type __rres; \ __builtin_memcpy(&__rres, (void *)(addr), sizeof(__rres)); \ __rres; \ }) #define SAFE_WRITE(addr, type, val) ({ \ const type __wtmp = (val); \ __builtin_memcpy((void *)(addr), &__wtmp, sizeof(__wtmp)); \ }) #define READ_U16(addr) SAFE_READ((addr), u16) #define READ_S16(addr) SAFE_READ((addr), s16) #define READ_U32(addr) SAFE_READ((addr), u32) #define READ_S32(addr) SAFE_READ((addr), s32) #define READ_U64(addr) SAFE_READ((addr), u64) #define READ_S64(addr) SAFE_READ((addr), s64) #define READ_ULONG(addr) SAFE_READ((addr), ulong) #define READ_LONG(addr) SAFE_READ((addr), long) #define READ_PTR(addr) SAFE_READ((addr), void *) #define WRITE_U16(addr, val) SAFE_WRITE((addr), u16, (val)) #define WRITE_S16(addr, val) SAFE_WRITE((addr), s16, (val)) #define WRITE_U32(addr, val) SAFE_WRITE((addr), u32, (val)) #define WRITE_S32(addr, val) SAFE_WRITE((addr), s32, (val)) #define WRITE_U64(addr, val) SAFE_WRITE((addr), u64, (val)) #define WRITE_S64(addr, val) SAFE_WRITE((addr), s64, (val)) #define WRITE_ULONG(addr, val) SAFE_WRITE((addr), ulong, (val)) #define WRITE_LONG(addr, val) SAFE_WRITE((addr), long, (val)) #define WRITE_PTR(addr, val) SAFE_WRITE((addr), void *, (val)) /* Other utils */ enum tristate { tri_unknown = -1, tri_no = 0, tri_yes = 1, }; /* Includes */ #include <tilck/common/panic.h> <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_console.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/term.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/datetime.h> #define PRINTK_BUF_SZ 224 #define PRINTK_PREFIXBUF_SZ 32 #ifdef BITS32 #define PRINTK_SAFE_STACK_SPACE 1536 #else #define PRINTK_SAFE_STACK_SPACE 2048 /* TODO: check this */ #endif #define PRINTK_COLOR COLOR_GREEN #define PRINTK_RINGBUF_FLUSH_COLOR COLOR_CYAN #define PRINTK_NOSPACE_IN_RBUF_FLUSH_COLOR COLOR_MAGENTA #define PRINTK_PANIC_COLOR COLOR_RED struct ringbuf_stat { union { struct { u32 read_pos : 14; u32 write_pos : 14; u32 full : 1; u32 first_printk : 1; u32 newline : 1; u32 unused0 : 1; }; ATOMIC(u32) raw; u32 __raw; }; }; #if TINY_KERNEL static char printk_rbuf[2 * KB]; #else static char printk_rbuf[8 * KB]; #endif static volatile struct ringbuf_stat printk_rbuf_stat = { .newline = 1 }; bool __in_printk; /* * NOTE: the ring buf cannot be larger than 16K elems because of the size of the * read_pos and write_pos bit-fields. */ STATIC_ASSERT(sizeof(printk_rbuf) <= 16 * KB); static void printk_direct_flush_no_tty(const char *buf, size_t size, u8 color) { /* * tty has not been initialized yet, therefore we have to translate here * \n to \r\n, by writing character by character to term. */ for (u32 i = 0; i < size; i++) { if (buf[i] == '\n') term_write("\r", 1, color); term_write(&buf[i], 1, color); } } static void printk_direct_flush(const char *buf, size_t size, u8 color) { if (!size) return; __in_printk = true; { if (LIKELY(get_curr_tty() != NULL)) { /* tty has been initialized and set a term write filter func */ if (UNLIKELY(in_kernel_shutdown())) tty_write_on_all_ttys(buf, size); else if (KRN_PRINTK_ON_CURR_TTY || !get_curr_process_tty()) term_write(buf, size, color); else tty_curr_proc_write(buf, size); } else { printk_direct_flush_no_tty(buf, size, color); } } __in_printk = false; return; } static ALWAYS_INLINE u32 printk_calc_used(const struct ringbuf_stat *cs) { u32 used = (cs->write_pos - cs->read_pos) % sizeof(printk_rbuf); if (!used) used = cs->full ? sizeof(printk_rbuf) : 0; return used; } static void __printk_flush_ringbuf(char *tmpbuf, u32 buf_size) { struct ringbuf_stat cs, ns; u32 used, to_read = 0; while (true) { do { cs = printk_rbuf_stat; ns = printk_rbuf_stat; used = printk_calc_used(&cs); /* We can read at most 'buf_size' bytes at a time */ to_read = UNSAFE_MIN(buf_size, used); /* And copy them to our minibuf */ for (u32 i = 0; i < to_read; i++) tmpbuf[i] = printk_rbuf[(cs.read_pos + i) % sizeof(printk_rbuf)]; /* Increase read_pos and decrease used */ ns.read_pos = (ns.read_pos + to_read) % sizeof(printk_rbuf); if (!to_read) ns.first_printk = 0; /* Repeat that until we were able to do that atomically */ } while (!atomic_cas_weak(&printk_rbuf_stat.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); /* Note: we checked that `first_printk` in `cs` was unset! */ if (!to_read) break; printk_direct_flush(tmpbuf, to_read, PRINTK_RINGBUF_FLUSH_COLOR); } } void printk_flush_ringbuf(void) { char minibuf[80]; __printk_flush_ringbuf(minibuf, sizeof(minibuf)); } static void printk_append_to_ringbuf(const char *buf, size_t size) { static const char err_msg[] = "{_DROPPED_}\n"; struct ringbuf_stat cs, ns; u32 used; if (!size) return; do { cs = printk_rbuf_stat; ns = printk_rbuf_stat; used = printk_calc_used(&cs); if (used + size >= sizeof(printk_rbuf)) { /* Corner case: the ring buffer is full */ if (term_is_initialized()) { printk_direct_flush(buf, size, PRINTK_NOSPACE_IN_RBUF_FLUSH_COLOR); return; } if (buf != err_msg && used < sizeof(printk_rbuf) - 1) { size = MIN(sizeof(printk_rbuf) - used - 1, sizeof(err_msg)); printk_append_to_ringbuf(err_msg, size); } return; } ns.write_pos = (ns.write_pos + size) % sizeof(printk_rbuf); if (ns.write_pos == ns.read_pos) ns.full = 1; } while (!atomic_cas_weak(&printk_rbuf_stat.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); // Now we have some allocated space in the ringbuf for (u32 i = 0; i < size; i++) printk_rbuf[(cs.write_pos + i) % sizeof(printk_rbuf)] = buf[i]; } /* * Sets atomically first_printk=1 and returns the old ringbuf_stat. */ static struct ringbuf_stat try_set_first_printk_on_stack(bool newline) { struct ringbuf_stat cs, ns; do { cs = printk_rbuf_stat; ns = printk_rbuf_stat; ns.first_printk = 1; ns.newline = newline; } while (!atomic_cas_weak(&printk_rbuf_stat.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); return cs; } static void restore_first_printk_value(void) { struct ringbuf_stat cs, ns; do { cs = printk_rbuf_stat; ns = printk_rbuf_stat; ns.first_printk = 0; } while (!atomic_cas_weak(&printk_rbuf_stat.raw, &cs.__raw, ns.__raw, mo_relaxed, mo_relaxed)); } STATIC int vsnprintk_with_truc_suffix(char *buf, u32 bufsz, const char *fmt, va_list args) { static const char truncated_str[] = "[...]"; int written = vsnprintk(buf, bufsz, fmt, args); if (written == (int)bufsz) { /* * Corner case: the buffer is completely full and the final \0 has been * included in 'written'. */ memcpy(buf + bufsz - sizeof(truncated_str), truncated_str, sizeof(truncated_str)); written--; } return written; } static void __tilck_vprintk(char *prefixbuf, char *buf, u32 bufsz, u32 flags, const char *fmt, va_list args) { bool prefix = !in_panic(); bool has_newline = false; struct ringbuf_stat old; int written, prefix_sz = 0; if (fmt[0] == PRINTK_CTRL_CHAR) { char cmd = fmt[1]; fmt += 4; if (NO_PREFIX[0]) { /* NO_PREFIX is not empty, so we're not in unit tests */ if (cmd == NO_PREFIX[1]) prefix = false; } } if (flags & PRINTK_FL_NO_PREFIX) prefix = false; written = vsnprintk_with_truc_suffix(buf, bufsz, fmt, args); for (int i = 0; i < written; i++) { if (buf[i] == '\n') { has_newline = true; break; } } old = try_set_first_printk_on_stack(has_newline); if (prefix && old.newline) { const u64 systime = get_sys_time(); prefix_sz = snprintk( prefixbuf, PRINTK_PREFIXBUF_SZ, "[%5u.%03u] %s", (u32)(systime / TS_SCALE), (u32)((systime % TS_SCALE) / (TS_SCALE / 1000)), bufsz < PRINTK_BUF_SZ ? "[LOWSS] " : "" ); } else { prefix = false; } if (!term_is_initialized()) { printk_append_to_ringbuf(prefixbuf, (size_t) prefix_sz); printk_append_to_ringbuf(buf, (size_t) written); restore_first_printk_value(); return; } if (in_panic()) { u8 color = in_panic_debugger() ? DEFAULT_FG_COLOR : PRINTK_PANIC_COLOR; printk_direct_flush(buf, (size_t) written, color); restore_first_printk_value(); return; } disable_preemption(); { if (!old.first_printk) { /* * OK, we were the first. Now, flush our buffer directly and loop * flushing anything that, in the meanwhile, printk() calls from IRQs * generated. */ printk_direct_flush(prefixbuf, (size_t) prefix_sz, PRINTK_COLOR); printk_direct_flush(buf, (size_t) written, PRINTK_COLOR); __printk_flush_ringbuf(buf, bufsz); /* * No need to call restore_first_printk_value(): printk_flush_ringbuf * clears the `first_printk` bit for us. */ } else { /* * We were NOT the first printk on the stack: we're in an IRQ handler * and can only append our data to the ringbuf. On return, at some * point, the first printk(), in printk_flush_ringbuf() [case above] * will flush our data. */ printk_append_to_ringbuf(prefixbuf, (size_t) prefix_sz); printk_append_to_ringbuf(buf, (size_t) written); } } enable_preemption(); } static void __regular_tilck_vprintk(u32 flags, const char *fmt, va_list args) { char prefixbuf[PRINTK_PREFIXBUF_SZ]; char buf[PRINTK_BUF_SZ]; __tilck_vprintk(prefixbuf, buf, sizeof(buf), flags, fmt, args); } static void __low_ssp_tilck_vprintk(u32 flags, const char *fmt, va_list args) { char prefixbuf[PRINTK_PREFIXBUF_SZ]; char buf[64]; __tilck_vprintk(prefixbuf, buf, sizeof(buf), flags, fmt, args); } void tilck_vprintk(u32 flags, const char *fmt, va_list args) { static char p_prefixbuf[PRINTK_PREFIXBUF_SZ]; static char p_buf[PRINTK_BUF_SZ]; if (in_panic()) __tilck_vprintk(p_prefixbuf, p_buf, sizeof(p_buf), flags, fmt, args); else if (get_rem_stack() < PRINTK_SAFE_STACK_SPACE) panic("No stack space for vprintk(\"%s\")", fmt); else if (get_rem_stack() < PRINTK_SAFE_STACK_SPACE + 512) __low_ssp_tilck_vprintk(flags, fmt, args); else __regular_tilck_vprintk(flags, fmt, args); } void printk(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintk(fmt, args); va_end(args); } <file_sep>/******************************************************************************* * * Module Name: nsxfeval - Public interfaces to the ACPI subsystem * ACPI Object evaluation interfaces * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acinterp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsxfeval") /* Local prototypes */ static void AcpiNsResolveReferences ( ACPI_EVALUATE_INFO *Info); /******************************************************************************* * * FUNCTION: AcpiEvaluateObjectTyped * * PARAMETERS: Handle - Object handle (optional) * Pathname - Object pathname (optional) * ExternalParams - List of parameters to pass to a method, * terminated by NULL. May be NULL * if no parameters are being passed. * ReturnBuffer - Where to put the object return value (if * any). Required. * ReturnType - Expected type of return object * * RETURN: Status * * DESCRIPTION: Find and evaluate the given object, passing the given * parameters if necessary. One of "Handle" or "Pathname" must * be valid (non-null) * ******************************************************************************/ ACPI_STATUS AcpiEvaluateObjectTyped ( ACPI_HANDLE Handle, ACPI_STRING Pathname, ACPI_OBJECT_LIST *ExternalParams, ACPI_BUFFER *ReturnBuffer, ACPI_OBJECT_TYPE ReturnType) { ACPI_STATUS Status; BOOLEAN FreeBufferOnError = FALSE; ACPI_HANDLE TargetHandle; char *FullPathname; ACPI_FUNCTION_TRACE (AcpiEvaluateObjectTyped); /* Return buffer must be valid */ if (!ReturnBuffer) { return_ACPI_STATUS (AE_BAD_PARAMETER); } if (ReturnBuffer->Length == ACPI_ALLOCATE_BUFFER) { FreeBufferOnError = TRUE; } /* Get a handle here, in order to build an error message if needed */ TargetHandle = Handle; if (Pathname) { Status = AcpiGetHandle (Handle, Pathname, &TargetHandle); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } FullPathname = AcpiNsGetExternalPathname (TargetHandle); if (!FullPathname) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Evaluate the object */ Status = AcpiEvaluateObject (TargetHandle, NULL, ExternalParams, ReturnBuffer); if (ACPI_FAILURE (Status)) { goto Exit; } /* Type ANY means "don't care about return value type" */ if (ReturnType == ACPI_TYPE_ANY) { goto Exit; } if (ReturnBuffer->Length == 0) { /* Error because caller specifically asked for a return value */ ACPI_ERROR ((AE_INFO, "%s did not return any object", FullPathname)); Status = AE_NULL_OBJECT; goto Exit; } /* Examine the object type returned from EvaluateObject */ if (((ACPI_OBJECT *) ReturnBuffer->Pointer)->Type == ReturnType) { goto Exit; } /* Return object type does not match requested type */ ACPI_ERROR ((AE_INFO, "Incorrect return type from %s - received [%s], requested [%s]", FullPathname, AcpiUtGetTypeName (((ACPI_OBJECT *) ReturnBuffer->Pointer)->Type), AcpiUtGetTypeName (ReturnType))); if (FreeBufferOnError) { /* * Free a buffer created via ACPI_ALLOCATE_BUFFER. * Note: We use AcpiOsFree here because AcpiOsAllocate was used * to allocate the buffer. This purposefully bypasses the * (optionally enabled) allocation tracking mechanism since we * only want to track internal allocations. */ AcpiOsFree (ReturnBuffer->Pointer); ReturnBuffer->Pointer = NULL; } ReturnBuffer->Length = 0; Status = AE_TYPE; Exit: ACPI_FREE (FullPathname); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiEvaluateObjectTyped) /******************************************************************************* * * FUNCTION: AcpiEvaluateObject * * PARAMETERS: Handle - Object handle (optional) * Pathname - Object pathname (optional) * ExternalParams - List of parameters to pass to method, * terminated by NULL. May be NULL * if no parameters are being passed. * ReturnBuffer - Where to put method's return value (if * any). If NULL, no value is returned. * * RETURN: Status * * DESCRIPTION: Find and evaluate the given object, passing the given * parameters if necessary. One of "Handle" or "Pathname" must * be valid (non-null) * ******************************************************************************/ ACPI_STATUS AcpiEvaluateObject ( ACPI_HANDLE Handle, ACPI_STRING Pathname, ACPI_OBJECT_LIST *ExternalParams, ACPI_BUFFER *ReturnBuffer) { ACPI_STATUS Status; ACPI_EVALUATE_INFO *Info; ACPI_SIZE BufferSpaceNeeded; UINT32 i; ACPI_FUNCTION_TRACE (AcpiEvaluateObject); /* Allocate and initialize the evaluation information block */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Convert and validate the device handle */ Info->PrefixNode = AcpiNsValidateHandle (Handle); if (!Info->PrefixNode) { Status = AE_BAD_PARAMETER; goto Cleanup; } /* * Get the actual namespace node for the target object. * Handles these cases: * * 1) Null node, valid pathname from root (absolute path) * 2) Node and valid pathname (path relative to Node) * 3) Node, Null pathname */ if ((Pathname) && (ACPI_IS_ROOT_PREFIX (Pathname[0]))) { /* The path is fully qualified, just evaluate by name */ Info->PrefixNode = NULL; } else if (!Handle) { /* * A handle is optional iff a fully qualified pathname is specified. * Since we've already handled fully qualified names above, this is * an error. */ if (!Pathname) { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Both Handle and Pathname are NULL")); } else { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Null Handle with relative pathname [%s]", Pathname)); } Status = AE_BAD_PARAMETER; goto Cleanup; } Info->RelativePathname = Pathname; /* * Convert all external objects passed as arguments to the * internal version(s). */ if (ExternalParams && ExternalParams->Count) { Info->ParamCount = (UINT16) ExternalParams->Count; /* Warn on impossible argument count */ if (Info->ParamCount > ACPI_METHOD_NUM_ARGS) { ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, ACPI_WARN_ALWAYS, "Excess arguments (%u) - using only %u", Info->ParamCount, ACPI_METHOD_NUM_ARGS)); Info->ParamCount = ACPI_METHOD_NUM_ARGS; } /* * Allocate a new parameter block for the internal objects * Add 1 to count to allow for null terminated internal list */ Info->Parameters = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) Info->ParamCount + 1) * sizeof (void *)); if (!Info->Parameters) { Status = AE_NO_MEMORY; goto Cleanup; } /* Convert each external object in the list to an internal object */ for (i = 0; i < Info->ParamCount; i++) { Status = AcpiUtCopyEobjectToIobject ( &ExternalParams->Pointer[i], &Info->Parameters[i]); if (ACPI_FAILURE (Status)) { goto Cleanup; } } Info->Parameters[Info->ParamCount] = NULL; } #ifdef _FUTURE_FEATURE /* * Begin incoming argument count analysis. Check for too few args * and too many args. */ switch (AcpiNsGetType (Info->Node)) { case ACPI_TYPE_METHOD: /* Check incoming argument count against the method definition */ if (Info->ObjDesc->Method.ParamCount > Info->ParamCount) { ACPI_ERROR ((AE_INFO, "Insufficient arguments (%u) - %u are required", Info->ParamCount, Info->ObjDesc->Method.ParamCount)); Status = AE_MISSING_ARGUMENTS; goto Cleanup; } else if (Info->ObjDesc->Method.ParamCount < Info->ParamCount) { ACPI_WARNING ((AE_INFO, "Excess arguments (%u) - only %u are required", Info->ParamCount, Info->ObjDesc->Method.ParamCount)); /* Just pass the required number of arguments */ Info->ParamCount = Info->ObjDesc->Method.ParamCount; } /* * Any incoming external objects to be passed as arguments to the * method must be converted to internal objects */ if (Info->ParamCount) { /* * Allocate a new parameter block for the internal objects * Add 1 to count to allow for null terminated internal list */ Info->Parameters = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) Info->ParamCount + 1) * sizeof (void *)); if (!Info->Parameters) { Status = AE_NO_MEMORY; goto Cleanup; } /* Convert each external object in the list to an internal object */ for (i = 0; i < Info->ParamCount; i++) { Status = AcpiUtCopyEobjectToIobject ( &ExternalParams->Pointer[i], &Info->Parameters[i]); if (ACPI_FAILURE (Status)) { goto Cleanup; } } Info->Parameters[Info->ParamCount] = NULL; } break; default: /* Warn if arguments passed to an object that is not a method */ if (Info->ParamCount) { ACPI_WARNING ((AE_INFO, "%u arguments were passed to a non-method ACPI object", Info->ParamCount)); } break; } #endif /* Now we can evaluate the object */ Status = AcpiNsEvaluate (Info); /* * If we are expecting a return value, and all went well above, * copy the return value to an external object. */ if (!ReturnBuffer) { goto CleanupReturnObject; } if (!Info->ReturnObject) { ReturnBuffer->Length = 0; goto Cleanup; } if (ACPI_GET_DESCRIPTOR_TYPE (Info->ReturnObject) == ACPI_DESC_TYPE_NAMED) { /* * If we received a NS Node as a return object, this means that * the object we are evaluating has nothing interesting to * return (such as a mutex, etc.) We return an error because * these types are essentially unsupported by this interface. * We don't check up front because this makes it easier to add * support for various types at a later date if necessary. */ Status = AE_TYPE; Info->ReturnObject = NULL; /* No need to delete a NS Node */ ReturnBuffer->Length = 0; } if (ACPI_FAILURE (Status)) { goto CleanupReturnObject; } /* Dereference Index and RefOf references */ AcpiNsResolveReferences (Info); /* Get the size of the returned object */ Status = AcpiUtGetObjectSize (Info->ReturnObject, &BufferSpaceNeeded); if (ACPI_SUCCESS (Status)) { /* Validate/Allocate/Clear caller buffer */ Status = AcpiUtInitializeBuffer (ReturnBuffer, BufferSpaceNeeded); if (ACPI_FAILURE (Status)) { /* * Caller's buffer is too small or a new one can't * be allocated */ ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Needed buffer size %X, %s\n", (UINT32) BufferSpaceNeeded, AcpiFormatException (Status))); } else { /* We have enough space for the object, build it */ Status = AcpiUtCopyIobjectToEobject ( Info->ReturnObject, ReturnBuffer); } } CleanupReturnObject: if (Info->ReturnObject) { /* * Delete the internal return object. NOTE: Interpreter must be * locked to avoid race condition. */ AcpiExEnterInterpreter (); /* Remove one reference on the return object (should delete it) */ AcpiUtRemoveReference (Info->ReturnObject); AcpiExExitInterpreter (); } Cleanup: /* Free the input parameter list (if we created one) */ if (Info->Parameters) { /* Free the allocated parameter block */ AcpiUtDeleteInternalObjectList (Info->Parameters); } ACPI_FREE (Info); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiEvaluateObject) /******************************************************************************* * * FUNCTION: AcpiNsResolveReferences * * PARAMETERS: Info - Evaluation info block * * RETURN: Info->ReturnObject is replaced with the dereferenced object * * DESCRIPTION: Dereference certain reference objects. Called before an * internal return object is converted to an external ACPI_OBJECT. * * Performs an automatic dereference of Index and RefOf reference objects. * These reference objects are not supported by the ACPI_OBJECT, so this is a * last resort effort to return something useful. Also, provides compatibility * with other ACPI implementations. * * NOTE: does not handle references within returned package objects or nested * references, but this support could be added later if found to be necessary. * ******************************************************************************/ static void AcpiNsResolveReferences ( ACPI_EVALUATE_INFO *Info) { ACPI_OPERAND_OBJECT *ObjDesc = NULL; ACPI_NAMESPACE_NODE *Node; /* We are interested in reference objects only */ if ((Info->ReturnObject)->Common.Type != ACPI_TYPE_LOCAL_REFERENCE) { return; } /* * Two types of references are supported - those created by Index and * RefOf operators. A name reference (AML_NAMEPATH_OP) can be converted * to an ACPI_OBJECT, so it is not dereferenced here. A DdbHandle * (AML_LOAD_OP) cannot be dereferenced, nor can it be converted to * an ACPI_OBJECT. */ switch (Info->ReturnObject->Reference.Class) { case ACPI_REFCLASS_INDEX: ObjDesc = *(Info->ReturnObject->Reference.Where); break; case ACPI_REFCLASS_REFOF: Node = Info->ReturnObject->Reference.Object; if (Node) { ObjDesc = Node->Object; } break; default: return; } /* Replace the existing reference object */ if (ObjDesc) { AcpiUtAddReference (ObjDesc); AcpiUtRemoveReference (Info->ReturnObject); Info->ReturnObject = ObjDesc; } return; } /******************************************************************************* * * FUNCTION: AcpiWalkNamespace * * PARAMETERS: Type - ACPI_OBJECT_TYPE to search for * StartObject - Handle in namespace where search begins * MaxDepth - Depth to which search is to reach * DescendingCallback - Called during tree descent * when an object of "Type" is found * AscendingCallback - Called during tree ascent * when an object of "Type" is found * Context - Passed to user function(s) above * ReturnValue - Location where return value of * UserFunction is put if terminated early * * RETURNS Return value from the UserFunction if terminated early. * Otherwise, returns NULL. * * DESCRIPTION: Performs a modified depth-first walk of the namespace tree, * starting (and ending) at the object specified by StartHandle. * The callback function is called whenever an object that matches * the type parameter is found. If the callback function returns * a non-zero value, the search is terminated immediately and this * value is returned to the caller. * * The point of this procedure is to provide a generic namespace * walk routine that can be called from multiple places to * provide multiple services; the callback function(s) can be * tailored to each task, whether it is a print function, * a compare function, etc. * ******************************************************************************/ ACPI_STATUS AcpiWalkNamespace ( ACPI_OBJECT_TYPE Type, ACPI_HANDLE StartObject, UINT32 MaxDepth, ACPI_WALK_CALLBACK DescendingCallback, ACPI_WALK_CALLBACK AscendingCallback, void *Context, void **ReturnValue) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiWalkNamespace); /* Parameter validation */ if ((Type > ACPI_TYPE_LOCAL_MAX) || (!MaxDepth) || (!DescendingCallback && !AscendingCallback)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* * Need to acquire the namespace reader lock to prevent interference * with any concurrent table unloads (which causes the deletion of * namespace objects). We cannot allow the deletion of a namespace node * while the user function is using it. The exception to this are the * nodes created and deleted during control method execution -- these * nodes are marked as temporary nodes and are ignored by the namespace * walk. Thus, control methods can be executed while holding the * namespace deletion lock (and the user function can execute control * methods.) */ Status = AcpiUtAcquireReadLock (&AcpiGbl_NamespaceRwLock); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Lock the namespace around the walk. The namespace will be * unlocked/locked around each call to the user function - since the user * function must be allowed to make ACPICA calls itself (for example, it * will typically execute control methods during device enumeration.) */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { goto UnlockAndExit; } /* Now we can validate the starting node */ if (!AcpiNsValidateHandle (StartObject)) { Status = AE_BAD_PARAMETER; goto UnlockAndExit2; } Status = AcpiNsWalkNamespace (Type, StartObject, MaxDepth, ACPI_NS_WALK_UNLOCK, DescendingCallback, AscendingCallback, Context, ReturnValue); UnlockAndExit2: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); UnlockAndExit: (void) AcpiUtReleaseReadLock (&AcpiGbl_NamespaceRwLock); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiWalkNamespace) /******************************************************************************* * * FUNCTION: AcpiNsGetDeviceCallback * * PARAMETERS: Callback from AcpiGetDevice * * RETURN: Status * * DESCRIPTION: Takes callbacks from WalkNamespace and filters out all non- * present devices, or if they specified a HID, it filters based * on that. * ******************************************************************************/ static ACPI_STATUS AcpiNsGetDeviceCallback ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_GET_DEVICES_INFO *Info = Context; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; UINT32 Flags; ACPI_PNP_DEVICE_ID *Hid; ACPI_PNP_DEVICE_ID_LIST *Cid; UINT32 i; BOOLEAN Found; int NoMatch; Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } Node = AcpiNsValidateHandle (ObjHandle); Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } if (!Node) { return (AE_BAD_PARAMETER); } /* * First, filter based on the device HID and CID. * * 01/2010: For this case where a specific HID is requested, we don't * want to run _STA until we have an actual HID match. Thus, we will * not unnecessarily execute _STA on devices for which the caller * doesn't care about. Previously, _STA was executed unconditionally * on all devices found here. * * A side-effect of this change is that now we will continue to search * for a matching HID even under device trees where the parent device * would have returned a _STA that indicates it is not present or * not functioning (thus aborting the search on that branch). */ if (Info->Hid != NULL) { Status = AcpiUtExecute_HID (Node, &Hid); if (Status == AE_NOT_FOUND) { return (AE_OK); } else if (ACPI_FAILURE (Status)) { return (AE_CTRL_DEPTH); } NoMatch = strcmp (Hid->String, Info->Hid); ACPI_FREE (Hid); if (NoMatch) { /* * HID does not match, attempt match within the * list of Compatible IDs (CIDs) */ Status = AcpiUtExecute_CID (Node, &Cid); if (Status == AE_NOT_FOUND) { return (AE_OK); } else if (ACPI_FAILURE (Status)) { return (AE_CTRL_DEPTH); } /* Walk the CID list */ Found = FALSE; for (i = 0; i < Cid->Count; i++) { if (strcmp (Cid->Ids[i].String, Info->Hid) == 0) { /* Found a matching CID */ Found = TRUE; break; } } ACPI_FREE (Cid); if (!Found) { return (AE_OK); } } } /* Run _STA to determine if device is present */ Status = AcpiUtExecute_STA (Node, &Flags); if (ACPI_FAILURE (Status)) { return (AE_CTRL_DEPTH); } if (!(Flags & ACPI_STA_DEVICE_PRESENT) && !(Flags & ACPI_STA_DEVICE_FUNCTIONING)) { /* * Don't examine the children of the device only when the * device is neither present nor functional. See ACPI spec, * description of _STA for more information. */ return (AE_CTRL_DEPTH); } /* We have a valid device, invoke the user function */ Status = Info->UserFunction (ObjHandle, NestingLevel, Info->Context, ReturnValue); return (Status); } /******************************************************************************* * * FUNCTION: AcpiGetDevices * * PARAMETERS: HID - HID to search for. Can be NULL. * UserFunction - Called when a matching object is found * Context - Passed to user function * ReturnValue - Location where return value of * UserFunction is put if terminated early * * RETURNS Return value from the UserFunction if terminated early. * Otherwise, returns NULL. * * DESCRIPTION: Performs a modified depth-first walk of the namespace tree, * starting (and ending) at the object specified by StartHandle. * The UserFunction is called whenever an object of type * Device is found. If the user function returns * a non-zero value, the search is terminated immediately and this * value is returned to the caller. * * This is a wrapper for WalkNamespace, but the callback performs * additional filtering. Please see AcpiNsGetDeviceCallback. * ******************************************************************************/ ACPI_STATUS AcpiGetDevices ( char *HID, ACPI_WALK_CALLBACK UserFunction, void *Context, void **ReturnValue) { ACPI_STATUS Status; ACPI_GET_DEVICES_INFO Info; ACPI_FUNCTION_TRACE (AcpiGetDevices); /* Parameter validation */ if (!UserFunction) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* * We're going to call their callback from OUR callback, so we need * to know what it is, and their context parameter. */ Info.Hid = HID; Info.Context = Context; Info.UserFunction = UserFunction; /* * Lock the namespace around the walk. * The namespace will be unlocked/locked around each call * to the user function - since this function * must be allowed to make Acpi calls itself. */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiNsWalkNamespace (ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, ACPI_NS_WALK_UNLOCK, AcpiNsGetDeviceCallback, NULL, &Info, ReturnValue); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetDevices) /******************************************************************************* * * FUNCTION: AcpiAttachData * * PARAMETERS: ObjHandle - Namespace node * Handler - Handler for this attachment * Data - Pointer to data to be attached * * RETURN: Status * * DESCRIPTION: Attach arbitrary data and handler to a namespace node. * ******************************************************************************/ ACPI_STATUS AcpiAttachData ( ACPI_HANDLE ObjHandle, ACPI_OBJECT_HANDLER Handler, void *Data) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; /* Parameter validation */ if (!ObjHandle || !Handler || !Data) { return (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } /* Convert and validate the handle */ Node = AcpiNsValidateHandle (ObjHandle); if (!Node) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } Status = AcpiNsAttachData (Node, Handler, Data); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (Status); } ACPI_EXPORT_SYMBOL (AcpiAttachData) /******************************************************************************* * * FUNCTION: AcpiDetachData * * PARAMETERS: ObjHandle - Namespace node handle * Handler - Handler used in call to AcpiAttachData * * RETURN: Status * * DESCRIPTION: Remove data that was previously attached to a node. * ******************************************************************************/ ACPI_STATUS AcpiDetachData ( ACPI_HANDLE ObjHandle, ACPI_OBJECT_HANDLER Handler) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; /* Parameter validation */ if (!ObjHandle || !Handler) { return (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } /* Convert and validate the handle */ Node = AcpiNsValidateHandle (ObjHandle); if (!Node) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } Status = AcpiNsDetachData (Node, Handler); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (Status); } ACPI_EXPORT_SYMBOL (AcpiDetachData) /******************************************************************************* * * FUNCTION: AcpiGetData * * PARAMETERS: ObjHandle - Namespace node * Handler - Handler used in call to AttachData * Data - Where the data is returned * * RETURN: Status * * DESCRIPTION: Retrieve data that was previously attached to a namespace node. * ******************************************************************************/ ACPI_STATUS AcpiGetData ( ACPI_HANDLE ObjHandle, ACPI_OBJECT_HANDLER Handler, void **Data) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; /* Parameter validation */ if (!ObjHandle || !Handler || !Data) { return (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } /* Convert and validate the handle */ Node = AcpiNsValidateHandle (ObjHandle); if (!Node) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } Status = AcpiNsGetAttachedData (Node, Handler, Data); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (Status); } ACPI_EXPORT_SYMBOL (AcpiGetData) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #define KB (1024u) #define MB (1024u * 1024u) #define VER_MAJOR @tilck_VERSION_MAJOR@ #define VER_MINOR @tilck_VERSION_MINOR@ #define VER_PATCH @tilck_VERSION_PATCH@ #define VER_MAJOR_STR "@tilck_VERSION_MAJOR@" #define VER_MINOR_STR "@tilck_VERSION_MINOR@" #define VER_PATCH_STR "@tilck_VERSION_PATCH@" #define ARCH_GCC_TC "@ARCH_GCC_TC@" #define PROJ_BUILD_DIR "@CMAKE_BINARY_DIR@" #define BUILDTYPE_STR "@CMAKE_BUILD_TYPE@" #define DEVSHELL_PATH "@TILCK_DEVSHELL_PATH@" #define KERNEL_STACK_PAGES @KERNEL_STACK_PAGES@ #define KERNEL_PADDR @KERNEL_PADDR@ #define KERNEL_BASE_VA @KERNEL_BASE_VA@ #define LINEAR_MAPPING_MB @LINEAR_MAPPING_MB@UL #define ARCH_BITS @ARCH_BITS@ /* --------- Boolean config variables --------- */ #cmakedefine01 FAT_TEST_DIR #cmakedefine01 DEBUG_CHECKS /* ----------- Convenience defines ------------ */ #if DEBUG_CHECKS #ifdef NDEBUG #undef NDEBUG #endif #endif #ifdef KERNEL_TEST #define KERNEL_TEST_INT 1 #else #define KERNEL_TEST_INT 0 #endif #ifdef TILCK_RELEASE_BUILD #define IS_RELEASE_BUILD 1 #else #define IS_RELEASE_BUILD 0 #endif /* ----------- Derived constants ----------- */ #if defined(TESTING) || defined(KERNEL_TEST) extern void *kernel_va; /* For the unit tests, we need to override the following defines */ #undef KERNEL_BASE_VA #undef LINEAR_MAPPING_MB #define KERNEL_BASE_VA ((ulong)kernel_va) #define LINEAR_MAPPING_MB (128u) #endif #define LINEAR_MAPPING_SIZE (LINEAR_MAPPING_MB << 20) #define LINEAR_MAPPING_END (KERNEL_BASE_VA + LINEAR_MAPPING_SIZE) /* Constants that have no reason to be changed */ #define FREE_MEM_POISON_VAL 0xFAABCAFE /* * ----------- User tasks constants ----------- * * WARNING: some of them are NOT really "configurable" without having to modify * a lot of code. Think about the potential implications changing the following * constants or, worse, before promoting them to be configurable as CMake * variables. */ #define USER_ARGS_PAGE_COUNT 1 #define MAX_TTYS 9 #define MAX_PATH 256 #define MAX_PID 8191 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static char numkey[128] = { [71] = '7', '8', '9', [75] = '4', '5', '6', [79] = '1', '2', '3', [82] = '0', '.', }; static char kbd_us[128] = { 0, '\033', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\x7f', /* Backspace key => ASCII DEL */ '\t', /* Tab */ 'q', 'w', 'e', 'r', /* 19 */ 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\r', 0, /* 29 - Control */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ '\'', '`', 0, /* Left shift */ '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ 'm', ',', '.', '/', 0, /* Right shift */ '*', 0, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock*/ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key*/ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, '\\', 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ }; static char kbd_us_up[128] = { 0, 27, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '\b', '\t', /* Tab */ 'Q', 'W', 'E', 'R', /* 19 */ 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n', 0, /* 29 - Control */ 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', /* 39 */ '\"', '~', 0, /* Left shift */ '|', 'Z', 'X', 'C', 'V', 'B', 'N', /* 49 */ 'M', '<', '>', '?', 0, /* Right shift */ '*', 0, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock */ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key */ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, '|', 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ }; static char *us_kb_layouts[2] = { kbd_us, kbd_us_up }; static u8 mediumraw_e0_keys[256] = { [KEY_NUMPAD_UP] = 0x67, // non-numpad up [KEY_NUMPAD_DOWN] = 0x6c, // non-numpad down [KEY_NUMPAD_RIGHT] = 0x6a, // non-numpad right [KEY_NUMPAD_LEFT] = 0x69, // non-numpad left [KEY_LEFT_CTRL] = 0x61, // right ctrl [KEY_LEFT_ALT] = 0x64, // right alt [KEY_NUMPAD_INS] = 0x6e, // non-numpad INS [KEY_NUMPAD_HOME] = 0x66, // non-numpad HOME [KEY_NUMPAD_DEL] = 0x6f, // non-numpad DEL [KEY_NUMPAD_END] = 0x6b, // non-numpad END [KEY_NUMPAD_PAGE_UP] = 0x68, // non-numpad page up [KEY_NUMPAD_PAGE_DOWN] = 0x6d, // non-numpad page down [0x1c] = 0x60, // numpad enter [0x35] = 0x62, // numpad slash }; <file_sep> /* * List of PCI IDs generated by scripts/dev/generate_pci_ids, part of the * Tilck project. * * Source data fetched from the `pciids` project: * https://github.com/pciutils/pciids/blob/master/pci.ids?raw=true * * Follows the original comments from the top of the `pci.ids` file. * * * List of PCI ID's * * Version: 2020.08.13 * Date: 2020-08-13 03:15:02 * * Maintained by <NAME>, <NAME>, and other volunteers from * the PCI ID Project at https://pci-ids.ucw.cz/. * * New data are always welcome, especially if they are accurate. If you have * anything to contribute, please follow the instructions at the web site. * * This file can be distributed under either the GNU General Public License * (version 2 or higher) or the 3-clause BSD License. * * The database is a compilation of factual data, and as such the copyright * only covers the aggregation and formatting. The copyright is held by * <NAME> and <NAME>. * */ #include <tilck/mods/pci.h> const struct pci_device_class pci_device_classes_list[] = { { 0x00, 0x00, 0x00, "Unclassified device", "Non-VGA unclassified device", NULL }, { 0x00, 0x01, 0x00, "Unclassified device", "VGA compatible unclassified device", NULL }, { 0x01, 0x00, 0x00, "Mass storage controller", "SCSI storage controller", NULL }, { 0x01, 0x01, 0x00, "Mass storage controller", "IDE interface", "ISA Compat. mode-only" }, { 0x01, 0x01, 0x05, "Mass storage controller", "IDE interface", "PCI native mode-only" }, { 0x01, 0x01, 0x0a, "Mass storage controller", "IDE interface", "ISA Compat. mode, w/ support of PCI native mode" }, { 0x01, 0x01, 0x0f, "Mass storage controller", "IDE interface", "PCI native mode, w/ support of ISA compat. mode" }, { 0x01, 0x01, 0x80, "Mass storage controller", "IDE interface", "ISA Compat. mode-only w/ bus master" }, { 0x01, 0x01, 0x85, "Mass storage controller", "IDE interface", "PCI native mode-only w/ bus master" }, { 0x01, 0x01, 0x8a, "Mass storage controller", "IDE interface", "ISA Compat. mode, w/ support of PCI native mode, w/ bus master" }, { 0x01, 0x01, 0x8f, "Mass storage controller", "IDE interface", "PCI native mode, w/ support of ISA compat. mode, w/ bus master" }, { 0x01, 0x02, 0x00, "Mass storage controller", "Floppy disk controller", NULL }, { 0x01, 0x03, 0x00, "Mass storage controller", "IPI bus controller", NULL }, { 0x01, 0x04, 0x00, "Mass storage controller", "RAID bus controller", NULL }, { 0x01, 0x05, 0x20, "Mass storage controller", "ATA controller", "ADMA single stepping" }, { 0x01, 0x05, 0x30, "Mass storage controller", "ATA controller", "ADMA continuous operation" }, { 0x01, 0x06, 0x00, "Mass storage controller", "SATA controller", "Vendor specific" }, { 0x01, 0x06, 0x01, "Mass storage controller", "SATA controller", "AHCI 1.0" }, { 0x01, 0x06, 0x02, "Mass storage controller", "SATA controller", "Serial Storage Bus" }, { 0x01, 0x07, 0x01, "Mass storage controller", "Serial Attached SCSI controller", "Serial Storage Bus" }, { 0x01, 0x08, 0x01, "Mass storage controller", "Non-Volatile memory controller", "NVMHCI" }, { 0x01, 0x08, 0x02, "Mass storage controller", "Non-Volatile memory controller", "NVM Express" }, { 0x01, 0x80, 0x00, "Mass storage controller", "Mass storage controller", NULL }, { 0x02, 0x00, 0x00, "Network controller", "Ethernet controller", NULL }, { 0x02, 0x01, 0x00, "Network controller", "Token ring network controller", NULL }, { 0x02, 0x02, 0x00, "Network controller", "FDDI network controller", NULL }, { 0x02, 0x03, 0x00, "Network controller", "ATM network controller", NULL }, { 0x02, 0x04, 0x00, "Network controller", "ISDN controller", NULL }, { 0x02, 0x05, 0x00, "Network controller", "WorldFip controller", NULL }, { 0x02, 0x06, 0x00, "Network controller", "PICMG controller", NULL }, { 0x02, 0x07, 0x00, "Network controller", "Infiniband controller", NULL }, { 0x02, 0x08, 0x00, "Network controller", "Fabric controller", NULL }, { 0x02, 0x80, 0x00, "Network controller", "Network controller", NULL }, { 0x03, 0x00, 0x00, "Display controller", "VGA compatible controller", "VGA controller" }, { 0x03, 0x00, 0x01, "Display controller", "VGA compatible controller", "8514 controller" }, { 0x03, 0x01, 0x00, "Display controller", "XGA compatible controller", NULL }, { 0x03, 0x02, 0x00, "Display controller", "3D controller", NULL }, { 0x03, 0x80, 0x00, "Display controller", "Display controller", NULL }, { 0x04, 0x00, 0x00, "Multimedia controller", "Multimedia video controller", NULL }, { 0x04, 0x01, 0x00, "Multimedia controller", "Multimedia audio controller", NULL }, { 0x04, 0x02, 0x00, "Multimedia controller", "Computer telephony device", NULL }, { 0x04, 0x03, 0x00, "Multimedia controller", "Audio device", NULL }, { 0x04, 0x80, 0x00, "Multimedia controller", "Multimedia controller", NULL }, { 0x05, 0x00, 0x00, "Memory controller", "RAM memory", NULL }, { 0x05, 0x01, 0x00, "Memory controller", "FLASH memory", NULL }, { 0x05, 0x80, 0x00, "Memory controller", "Memory controller", NULL }, { 0x06, 0x00, 0x00, "Bridge", "Host bridge", NULL }, { 0x06, 0x01, 0x00, "Bridge", "ISA bridge", NULL }, { 0x06, 0x02, 0x00, "Bridge", "EISA bridge", NULL }, { 0x06, 0x03, 0x00, "Bridge", "MicroChannel bridge", NULL }, { 0x06, 0x04, 0x00, "Bridge", "PCI bridge", "Normal decode" }, { 0x06, 0x04, 0x01, "Bridge", "PCI bridge", "Subtractive decode" }, { 0x06, 0x05, 0x00, "Bridge", "PCMCIA bridge", NULL }, { 0x06, 0x06, 0x00, "Bridge", "NuBus bridge", NULL }, { 0x06, 0x07, 0x00, "Bridge", "CardBus bridge", NULL }, { 0x06, 0x08, 0x00, "Bridge", "RACEway bridge", "Transparent mode" }, { 0x06, 0x08, 0x01, "Bridge", "RACEway bridge", "Endpoint mode" }, { 0x06, 0x09, 0x40, "Bridge", "Semi-transparent PCI-to-PCI bridge", "Primary bus towards host CPU" }, { 0x06, 0x09, 0x80, "Bridge", "Semi-transparent PCI-to-PCI bridge", "Secondary bus towards host CPU" }, { 0x06, 0x0a, 0x00, "Bridge", "InfiniBand to PCI host bridge", NULL }, { 0x06, 0x80, 0x00, "Bridge", "Bridge", NULL }, { 0x07, 0x00, 0x00, "Communication controller", "Serial controller", "8250" }, { 0x07, 0x00, 0x01, "Communication controller", "Serial controller", "16450" }, { 0x07, 0x00, 0x02, "Communication controller", "Serial controller", "16550" }, { 0x07, 0x00, 0x03, "Communication controller", "Serial controller", "16650" }, { 0x07, 0x00, 0x04, "Communication controller", "Serial controller", "16750" }, { 0x07, 0x00, 0x05, "Communication controller", "Serial controller", "16850" }, { 0x07, 0x00, 0x06, "Communication controller", "Serial controller", "16950" }, { 0x07, 0x01, 0x00, "Communication controller", "Parallel controller", "SPP" }, { 0x07, 0x01, 0x01, "Communication controller", "Parallel controller", "BiDir" }, { 0x07, 0x01, 0x02, "Communication controller", "Parallel controller", "ECP" }, { 0x07, 0x01, 0x03, "Communication controller", "Parallel controller", "IEEE1284" }, { 0x07, 0x01, 0xfe, "Communication controller", "Parallel controller", "IEEE1284 Target" }, { 0x07, 0x02, 0x00, "Communication controller", "Multiport serial controller", NULL }, { 0x07, 0x03, 0x00, "Communication controller", "Modem", "Generic" }, { 0x07, 0x03, 0x01, "Communication controller", "Modem", "Hayes/16450" }, { 0x07, 0x03, 0x02, "Communication controller", "Modem", "Hayes/16550" }, { 0x07, 0x03, 0x03, "Communication controller", "Modem", "Hayes/16650" }, { 0x07, 0x03, 0x04, "Communication controller", "Modem", "Hayes/16750" }, { 0x07, 0x04, 0x00, "Communication controller", "GPIB controller", NULL }, { 0x07, 0x05, 0x00, "Communication controller", "Smard Card controller", NULL }, { 0x07, 0x80, 0x00, "Communication controller", "Communication controller", NULL }, { 0x08, 0x00, 0x00, "Generic system peripheral", "PIC", "8259" }, { 0x08, 0x00, 0x01, "Generic system peripheral", "PIC", "ISA PIC" }, { 0x08, 0x00, 0x02, "Generic system peripheral", "PIC", "EISA PIC" }, { 0x08, 0x00, 0x10, "Generic system peripheral", "PIC", "IO-APIC" }, { 0x08, 0x00, 0x20, "Generic system peripheral", "PIC", "IO(X)-APIC" }, { 0x08, 0x01, 0x00, "Generic system peripheral", "DMA controller", "8237" }, { 0x08, 0x01, 0x01, "Generic system peripheral", "DMA controller", "ISA DMA" }, { 0x08, 0x01, 0x02, "Generic system peripheral", "DMA controller", "EISA DMA" }, { 0x08, 0x02, 0x00, "Generic system peripheral", "Timer", "8254" }, { 0x08, 0x02, 0x01, "Generic system peripheral", "Timer", "ISA Timer" }, { 0x08, 0x02, 0x02, "Generic system peripheral", "Timer", "EISA Timers" }, { 0x08, 0x02, 0x03, "Generic system peripheral", "Timer", "HPET" }, { 0x08, 0x03, 0x00, "Generic system peripheral", "RTC", "Generic" }, { 0x08, 0x03, 0x01, "Generic system peripheral", "RTC", "ISA RTC" }, { 0x08, 0x04, 0x00, "Generic system peripheral", "PCI Hot-plug controller", NULL }, { 0x08, 0x05, 0x00, "Generic system peripheral", "SD Host controller", NULL }, { 0x08, 0x06, 0x00, "Generic system peripheral", "IOMMU", NULL }, { 0x08, 0x80, 0x00, "Generic system peripheral", "System peripheral", NULL }, { 0x09, 0x00, 0x00, "Input device controller", "Keyboard controller", NULL }, { 0x09, 0x01, 0x00, "Input device controller", "Digitizer Pen", NULL }, { 0x09, 0x02, 0x00, "Input device controller", "Mouse controller", NULL }, { 0x09, 0x03, 0x00, "Input device controller", "Scanner controller", NULL }, { 0x09, 0x04, 0x00, "Input device controller", "Gameport controller", "Generic" }, { 0x09, 0x04, 0x10, "Input device controller", "Gameport controller", "Extended" }, { 0x09, 0x80, 0x00, "Input device controller", "Input device controller", NULL }, { 0x0a, 0x00, 0x00, "Docking station", "Generic Docking Station", NULL }, { 0x0a, 0x80, 0x00, "Docking station", "Docking Station", NULL }, { 0x0b, 0x00, 0x00, "Processor", "386", NULL }, { 0x0b, 0x01, 0x00, "Processor", "486", NULL }, { 0x0b, 0x02, 0x00, "Processor", "Pentium", NULL }, { 0x0b, 0x10, 0x00, "Processor", "Alpha", NULL }, { 0x0b, 0x20, 0x00, "Processor", "Power PC", NULL }, { 0x0b, 0x30, 0x00, "Processor", "MIPS", NULL }, { 0x0b, 0x40, 0x00, "Processor", "Co-processor", NULL }, { 0x0c, 0x00, 0x00, "Serial bus controller", "FireWire (IEEE 1394)", "Generic" }, { 0x0c, 0x00, 0x10, "Serial bus controller", "FireWire (IEEE 1394)", "OHCI" }, { 0x0c, 0x01, 0x00, "Serial bus controller", "ACCESS Bus", NULL }, { 0x0c, 0x02, 0x00, "Serial bus controller", "SSA", NULL }, { 0x0c, 0x03, 0x00, "Serial bus controller", "USB controller", "UHCI" }, { 0x0c, 0x03, 0x10, "Serial bus controller", "USB controller", "OHCI" }, { 0x0c, 0x03, 0x20, "Serial bus controller", "USB controller", "EHCI" }, { 0x0c, 0x03, 0x30, "Serial bus controller", "USB controller", "XHCI" }, { 0x0c, 0x03, 0x40, "Serial bus controller", "USB controller", "USB4 Host Interface" }, { 0x0c, 0x03, 0x80, "Serial bus controller", "USB controller", "Unspecified" }, { 0x0c, 0x03, 0xfe, "Serial bus controller", "USB controller", "USB Device" }, { 0x0c, 0x04, 0x00, "Serial bus controller", "Fibre Channel", NULL }, { 0x0c, 0x05, 0x00, "Serial bus controller", "SMBus", NULL }, { 0x0c, 0x06, 0x00, "Serial bus controller", "InfiniBand", NULL }, { 0x0c, 0x07, 0x00, "Serial bus controller", "IPMI Interface", "SMIC" }, { 0x0c, 0x07, 0x01, "Serial bus controller", "IPMI Interface", "KCS" }, { 0x0c, 0x07, 0x02, "Serial bus controller", "IPMI Interface", "BT (Block Transfer)" }, { 0x0c, 0x08, 0x00, "Serial bus controller", "SERCOS interface", NULL }, { 0x0c, 0x09, 0x00, "Serial bus controller", "CANBUS", NULL }, { 0x0d, 0x00, 0x00, "Wireless controller", "IRDA controller", NULL }, { 0x0d, 0x01, 0x00, "Wireless controller", "Consumer IR controller", NULL }, { 0x0d, 0x10, 0x00, "Wireless controller", "RF controller", NULL }, { 0x0d, 0x11, 0x00, "Wireless controller", "Bluetooth", NULL }, { 0x0d, 0x12, 0x00, "Wireless controller", "Broadband", NULL }, { 0x0d, 0x20, 0x00, "Wireless controller", "802.1a controller", NULL }, { 0x0d, 0x21, 0x00, "Wireless controller", "802.1b controller", NULL }, { 0x0d, 0x80, 0x00, "Wireless controller", "Wireless controller", NULL }, { 0x0e, 0x00, 0x00, "Intelligent controller", "I2O", NULL }, { 0x0f, 0x01, 0x00, "Satellite communications controller", "Satellite TV controller", NULL }, { 0x0f, 0x02, 0x00, "Satellite communications controller", "Satellite audio communication controller", NULL }, { 0x0f, 0x03, 0x00, "Satellite communications controller", "Satellite voice communication controller", NULL }, { 0x0f, 0x04, 0x00, "Satellite communications controller", "Satellite data communication controller", NULL }, { 0x10, 0x00, 0x00, "Encryption controller", "Network and computing encryption device", NULL }, { 0x10, 0x10, 0x00, "Encryption controller", "Entertainment encryption device", NULL }, { 0x10, 0x80, 0x00, "Encryption controller", "Encryption controller", NULL }, { 0x11, 0x00, 0x00, "Signal processing controller", "DPIO module", NULL }, { 0x11, 0x01, 0x00, "Signal processing controller", "Performance counters", NULL }, { 0x11, 0x10, 0x00, "Signal processing controller", "Communication synchronizer", NULL }, { 0x11, 0x20, 0x00, "Signal processing controller", "Signal processing management", NULL }, { 0x11, 0x80, 0x00, "Signal processing controller", "Signal processing controller", NULL }, { 0x12, 0x00, 0x00, "Processing accelerators", "Processing accelerators", NULL }, { 0x12, 0x01, 0x00, "Processing accelerators", "AI Inference Accelerator", NULL }, { 0x13, 0x00, 0x00, "Non-Essential Instrumentation", NULL, NULL }, { 0x40, 0x00, 0x00, "Coprocessor", NULL, NULL }, { 0xff, 0x00, 0x00, "Unassigned class", NULL, NULL }, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #define WTH_PRIO_HIGHEST 0 #define WTH_PRIO_LOWEST 255 struct worker_thread; void init_worker_threads(); struct task * wth_get_task(struct worker_thread *wth); u32 wth_get_queue_size(struct worker_thread *wth); int wth_get_priority(struct worker_thread *wth); const char * wth_get_name(struct worker_thread *wth); struct task * wth_get_runnable_thread(void); struct worker_thread * wth_create_thread(const char *name, int priority, u16 queue_size); struct worker_thread * wth_find_worker(int lowest_prio); NODISCARD bool wth_enqueue_on(struct worker_thread *wth, void (*func)(void *), void *arg); NODISCARD bool wth_enqueue_anywhere(int lowest_prio, void (*func)(void *), void *arg); void wth_wait_for_completion(struct worker_thread *wth); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/signal.h> #include <features.h> // system header #if defined(__GLIBC__) && !defined(__USE_LARGEFILE64) #define __USE_LARGEFILE64 #endif #include <sys/types.h> // system header #include <sys/time.h> // system header #include <sys/times.h> // system header #include <sys/uio.h> // system header #include <sys/select.h> // system header #include <time.h> // system header #include <poll.h> // system header #include <utime.h> // system header #include <sys/stat.h> // system header #include <unistd.h> // system header #include <sys/utsname.h> // system header #include <sys/stat.h> // system header #include <fcntl.h> // system header #define MAX_SYSCALLS 500 typedef u64 tilck_ino_t; /* From the man page of getdents64() */ struct linux_dirent64 { u64 d_ino; /* 64-bit inode number */ u64 d_off; /* 64-bit offset to next structure */ unsigned short d_reclen; /* Size of this dirent */ unsigned char d_type; /* File type */ char d_name[]; /* Filename (null-terminated) */ }; struct k_sigaction { union { void (*handler)(int); void (*sigact_handler)(int, void * /* siginfo */, void *); }; ulong sa_flags; void (*restorer)(void); ulong sa_mask[K_SIGACTION_MASK_WORDS]; }; /* * Classic timeval struct, with pointer-size tv_sec and tv_usec. * Suffers from the Y2038 bug on 32-bit systems. */ struct k_timeval { long tv_sec; long tv_usec; }; /* * Classic utimbuf using pointer-size as time_t. * Suffers from the Y2038 bug on 32-bit systems. */ struct k_utimbuf { long actime; long modtime; }; struct k_rusage { struct k_timeval ru_utime; struct k_timeval ru_stime; /* linux extentions */ long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; long reserved[16]; }; #ifdef BITS32 STATIC_ASSERT(sizeof(struct k_rusage) == 136); #endif /* * Classic (old) timespec. Suffers from the Y2038 bug on ALL systems. */ struct k_timespec32 { s32 tv_sec; long tv_nsec; }; /* * Modern timespec struct. */ struct k_timespec64 { s64 tv_sec; long tv_nsec; }; #ifdef BITS32 /* * Classic stat64 struct for 32-bit systems. * * It replaced the older "struct stat" which had no forced 64-bit fields on * 32-bit systems. For example, st_dev was just a long. But the story is not * over: before "struct stat" there was a version of that struct now called * "__old_kernel_stat" in Linux that used short for many fields like st_dev, * st_ino, st_uid etc. * * Suffers from the Y2038 bug because of the k_timespec32 fields. Workaround * used by libmusl? Using statx() and struct statx. */ struct k_stat64 { u64 st_dev; u32 __st_dev_padding; ulong __st_ino_truncated; u32 st_mode; u32 st_nlink; ulong st_uid; ulong st_gid; u64 st_rdev; u32 __st_rdev_padding; s64 st_size; ulong st_blksize; s64 st_blocks; struct k_timespec32 st_atim; struct k_timespec32 st_mtim; struct k_timespec32 st_ctim; u64 st_ino; }; #else /* * Modern struct stat for 64-bit systems. * * Note: it's called simply "stat" in the Linux kernel. */ struct k_stat64 { ulong st_dev; ulong st_ino; ulong st_nlink; u32 st_mode; u32 st_uid; u32 st_gid; u32 __pad0; ulong st_rdev; long st_size; long st_blksize; long st_blocks; struct k_timespec64 st_atim; struct k_timespec64 st_mtim; struct k_timespec64 st_ctim; long __unused[3]; }; #endif #ifndef O_DIRECTORY #define O_DIRECTORY __O_DIRECTORY #endif #ifndef O_TMPFILE #define O_TMPFILE (__O_TMPFILE | O_DIRECTORY) #endif #ifndef O_DIRECT #define O_DIRECT __O_DIRECT #endif #ifndef O_NOATIME #define O_NOATIME __O_NOATIME #endif #ifndef O_PATH #define O_PATH __O_PATH #endif #define FCNTL_CHANGEABLE_FL ( \ O_APPEND | \ O_ASYNC | \ O_DIRECT | \ O_NOATIME | \ O_NONBLOCK \ ) #define EXITCODE(ret, sig) ((ret) << 8 | (sig)) #define STOPCODE(sig) ((sig) << 8 | 0x7f) #define CONTINUED 0xffff #define COREFLAG 0x80 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #ifndef __TILCK_ATOMICS__ #error Never include fake_atomics.h directly. Include atomics.h. #endif /* * Fake C11 atomics implementation * -------------------------------- * * Purpose * --------- * Make it possible the build to pass and eventually have the code using them * to run correctly in single-threaded mode. * * Use cases * ---------------- * At the moment, in two cases: for unit tests built with an old compiler like * gcc 4.8 which does not support C11 atomics and for static analysis builds * which might require fancy tricks like using a system compiler but changing * it's sysroot with -isystem (option KERNEL_FORCE_TC_ISYSTEM=1): in that * scenario, when compiling C++ files it's not possible to include <atomic>. * Note: because some special static analysis builds requiring fake atomics are * NOT supposed to be run, that's perfectly safe. */ #define atomic_compare_exchange_strong_explicit(ptr, expval, newval, m1, m2) \ __sync_bool_compare_and_swap(ptr, *(expval), newval) #define atomic_compare_exchange_weak_explicit(ptr, expval, newval, m1, m2) \ __sync_bool_compare_and_swap(ptr, *(expval), newval) #define atomic_exchange_explicit(ptr, newval, mo) \ ({ \ typeof(*(ptr)) __old_v; \ do { \ __old_v = *(ptr); \ } while (!__sync_bool_compare_and_swap(ptr, __old_v, newval)); \ __old_v; \ }) #define atomic_store_explicit(ptr, newval, mo) \ (void)atomic_exchange_explicit(ptr, newval, mo) #define atomic_load_explicit(ptr, mo) \ __sync_fetch_and_add(ptr, 0) #define atomic_fetch_add_explicit(ptr, val, mo) \ __sync_fetch_and_add(ptr, val) #define atomic_fetch_sub_explicit(ptr, val, mo) \ __sync_fetch_and_sub(ptr, val) /* * HACK: completely unsafe, but OK as we're implementing FAKE atomics that are * only good enough for the build to pass and eventually some unit test code to * execute these functions in a single thread. */ #define ATOMIC(x) x #define mo_relaxed 0 #define mo_consume 1 #define mo_acquire 2 #define mo_release 3 #define mo_acq_rel 4 #define mo_seq_cst 5 <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tasks class printer_struct_task: def __init__(self, val): self.val = val def children(self): task = self.val pi = task['pi'] state_regs = "(null)" if pi['pid'] != 0: pi_str = "(struct process *) {}".format(bu.fixhex32(int(pi))) else: pi_str = "<kernel_process_pi>" if task['state_regs']: state_regs = task['state_regs'].dereference() return [ ("tid ", task["tid"]), ("pi ", pi_str), ("state ", task["state"]), ("kthread_name ", task["kthread_name"]), ("is_main_thread ", task["is_main_thread"]), ("running_in_kernel ", task['running_in_kernel']), ("stopped ", task['stopped']), ("was_stopped ", task['was_stopped']), ("vfork_stopped ", task['vfork_stopped']), ("traced ", task['traced']), ("kernel_stack ", task['kernel_stack']), ("args_copybuf ", task['args_copybuf']), ("io_copybuf ", task['io_copybuf']), ("wstatus ", task['wstatus']), ("timeslice_ticks ", task['ticks']['timeslice']), ("total_ticks ", task['ticks']['total']), ("total_kernel_ticks ", task['ticks']['total_kernel']), ("ticks_before_wake_up", task['ticks_before_wake_up']), ("timer_ready ", task['timer_ready']), ("wobj ", task['wobj']), ("state_regs ", state_regs), ] def to_string(self): return bu.fmt_type("struct task", self.val) bu.register_tilck_regex_pp( 'task', '^task$', printer_struct_task ) <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause BUSYBOX_VER="1.33.1" function internal_build_busybox { echo "Building busybox... " reset_cc_vars cp $MAIN_DIR/other/busybox.config .config if [[ "$HOST_ARCH" != "$ARCH" ]]; then export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" else # Default case set_cc_vars_to_tc fi export CROSS_COMPILE="${ARCH_GCC_TC}-linux-" run_command2 "make -j$BUILD_PAR" build.log export CROSS_COMPILE="" export CC_POST_FLAGS="" busybox_fix_config_file # Save a copy of the last built .config file cp .config .last_build_config } all_funcs_list+=(build_busybox) function build_busybox { pushd $ARCH if [ -d busybox ]; then s1=`sha1sum ./busybox/.config | cut -d " " -f 1` s2=`sha1sum ./busybox/.last_build_config | cut -d " " -f 1` if [ "$s1" != "$s2" ]; then echo "Busybox: .config != .last_build_config" echo -n "Do you want to rebuild with the new config? [Y/n]: " read answer if [[ "$answer" == "" || "$answer" == "y" ]]; then echo -n "Do you want an incremental build? [Y/n]: " read answer if [[ "$answer" == "" || "$answer" == "y" ]]; then pushd busybox internal_build_busybox popd else rm -rf busybox fi fi fi fi if ! [ -d busybox ]; then show_work_on_component_msg "BUSYBOX" local ver="$BUSYBOX_VER" local tarname=busybox-$ver.tar.bz2 download_file_in_cache "https://busybox.net/downloads" "$tarname" extract_cachefile_tar_bz $tarname busybox-$ver busybox pushd busybox internal_build_busybox popd elif [ "$REBUILD" == "1" ]; then pushd busybox internal_build_busybox popd else show_skip_component_msg "BUSYBOX" fi popd } function build_busybox_installed_status { if [ -d $TC/$ARCH/busybox ]; then if [ -f $TC/$ARCH/busybox/busybox ]; then echo "installed $ARCH" else echo "error" fi fi } function busybox_fix_config_file { # Remove the date-time row (in order to allow config diff to work) sed -i -e '4d' .config # Remove all empty lines sed -i '/CONFIG_/!d' .config # Sort all the lines LC_ALL=C sort -sr .config > .config_sorted mv .config_sorted .config } all_funcs_list+=(config_busybox) function config_busybox { pushd $ARCH if ! [ -d busybox ]; then echo "ERROR: busybox not found in toolchain" exit 1 fi pushd busybox make menuconfig echo -n "Do you want to update busybox.config with the new config? [Y/n]: " read answer busybox_fix_config_file if [[ "$answer" == "" || "$answer" == "y" ]]; then cp .config $MAIN_DIR/other/busybox.config echo "Source file $MAIN_DIR/other/busybox.config UPDATED" fi popd popd build_busybox } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> uint32_t crc32(uint32_t crc, const void *buf, size_t size); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define RANDOM_VALUES_COUNT 1000 extern unsigned int random_values[RANDOM_VALUES_COUNT]; <file_sep>/****************************************************************************** * * Module Name: utprint - Formatted printing routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utprint") #define ACPI_FORMAT_SIGN 0x01 #define ACPI_FORMAT_SIGN_PLUS 0x02 #define ACPI_FORMAT_SIGN_PLUS_SPACE 0x04 #define ACPI_FORMAT_ZERO 0x08 #define ACPI_FORMAT_LEFT 0x10 #define ACPI_FORMAT_UPPER 0x20 #define ACPI_FORMAT_PREFIX 0x40 /* Local prototypes */ static ACPI_SIZE AcpiUtBoundStringLength ( const char *String, ACPI_SIZE Count); static char * AcpiUtBoundStringOutput ( char *String, const char *End, char c); static char * AcpiUtFormatNumber ( char *String, char *End, UINT64 Number, UINT8 Base, INT32 Width, INT32 Precision, UINT8 Type); static char * AcpiUtPutNumber ( char *String, UINT64 Number, UINT8 Base, BOOLEAN Upper); /******************************************************************************* * * FUNCTION: AcpiUtBoundStringLength * * PARAMETERS: String - String with boundary * Count - Boundary of the string * * RETURN: Length of the string. Less than or equal to Count. * * DESCRIPTION: Calculate the length of a string with boundary. * ******************************************************************************/ static ACPI_SIZE AcpiUtBoundStringLength ( const char *String, ACPI_SIZE Count) { UINT32 Length = 0; while (*String && Count) { Length++; String++; Count--; } return (Length); } /******************************************************************************* * * FUNCTION: AcpiUtBoundStringOutput * * PARAMETERS: String - String with boundary * End - Boundary of the string * c - Character to be output to the string * * RETURN: Updated position for next valid character * * DESCRIPTION: Output a character into a string with boundary check. * ******************************************************************************/ static char * AcpiUtBoundStringOutput ( char *String, const char *End, char c) { if (String < End) { *String = c; } ++String; return (String); } /******************************************************************************* * * FUNCTION: AcpiUtPutNumber * * PARAMETERS: String - Buffer to hold reverse-ordered string * Number - Integer to be converted * Base - Base of the integer * Upper - Whether or not using upper cased digits * * RETURN: Updated position for next valid character * * DESCRIPTION: Convert an integer into a string, note that, the string holds a * reversed ordered number without the trailing zero. * ******************************************************************************/ static char * AcpiUtPutNumber ( char *String, UINT64 Number, UINT8 Base, BOOLEAN Upper) { const char *Digits; UINT64 DigitIndex; char *Pos; Pos = String; Digits = Upper ? AcpiGbl_UpperHexDigits : AcpiGbl_LowerHexDigits; if (Number == 0) { *(Pos++) = '0'; } else { while (Number) { (void) AcpiUtDivide (Number, Base, &Number, &DigitIndex); *(Pos++) = Digits[DigitIndex]; } } /* *(Pos++) = '0'; */ return (Pos); } /******************************************************************************* * * FUNCTION: AcpiUtScanNumber * * PARAMETERS: String - String buffer * NumberPtr - Where the number is returned * * RETURN: Updated position for next valid character * * DESCRIPTION: Scan a string for a decimal integer. * ******************************************************************************/ const char * AcpiUtScanNumber ( const char *String, UINT64 *NumberPtr) { UINT64 Number = 0; while (isdigit ((int) *String)) { AcpiUtShortMultiply (Number, 10, &Number); Number += *(String++) - '0'; } *NumberPtr = Number; return (String); } /******************************************************************************* * * FUNCTION: AcpiUtPrintNumber * * PARAMETERS: String - String buffer * Number - The number to be converted * * RETURN: Updated position for next valid character * * DESCRIPTION: Print a decimal integer into a string. * ******************************************************************************/ const char * AcpiUtPrintNumber ( char *String, UINT64 Number) { char AsciiString[20]; const char *Pos1; char *Pos2; Pos1 = AcpiUtPutNumber (AsciiString, Number, 10, FALSE); Pos2 = String; while (Pos1 != AsciiString) { *(Pos2++) = *(--Pos1); } *Pos2 = 0; return (String); } /******************************************************************************* * * FUNCTION: AcpiUtFormatNumber * * PARAMETERS: String - String buffer with boundary * End - Boundary of the string * Number - The number to be converted * Base - Base of the integer * Width - Field width * Precision - Precision of the integer * Type - Special printing flags * * RETURN: Updated position for next valid character * * DESCRIPTION: Print an integer into a string with any base and any precision. * ******************************************************************************/ static char * AcpiUtFormatNumber ( char *String, char *End, UINT64 Number, UINT8 Base, INT32 Width, INT32 Precision, UINT8 Type) { char *Pos; char Sign; char Zero; BOOLEAN NeedPrefix; BOOLEAN Upper; INT32 i; char ReversedString[66]; /* Parameter validation */ if (Base < 2 || Base > 16) { return (NULL); } if (Type & ACPI_FORMAT_LEFT) { Type &= ~ACPI_FORMAT_ZERO; } NeedPrefix = ((Type & ACPI_FORMAT_PREFIX) && Base != 10) ? TRUE : FALSE; Upper = (Type & ACPI_FORMAT_UPPER) ? TRUE : FALSE; Zero = (Type & ACPI_FORMAT_ZERO) ? '0' : ' '; /* Calculate size according to sign and prefix */ Sign = '\0'; if (Type & ACPI_FORMAT_SIGN) { if ((INT64) Number < 0) { Sign = '-'; Number = - (INT64) Number; Width--; } else if (Type & ACPI_FORMAT_SIGN_PLUS) { Sign = '+'; Width--; } else if (Type & ACPI_FORMAT_SIGN_PLUS_SPACE) { Sign = ' '; Width--; } } if (NeedPrefix) { Width--; if (Base == 16) { Width--; } } /* Generate full string in reverse order */ Pos = AcpiUtPutNumber (ReversedString, Number, Base, Upper); i = (INT32) ACPI_PTR_DIFF (Pos, ReversedString); /* Printing 100 using %2d gives "100", not "00" */ if (i > Precision) { Precision = i; } Width -= Precision; /* Output the string */ if (!(Type & (ACPI_FORMAT_ZERO | ACPI_FORMAT_LEFT))) { while (--Width >= 0) { String = AcpiUtBoundStringOutput (String, End, ' '); } } if (Sign) { String = AcpiUtBoundStringOutput (String, End, Sign); } if (NeedPrefix) { String = AcpiUtBoundStringOutput (String, End, '0'); if (Base == 16) { String = AcpiUtBoundStringOutput ( String, End, Upper ? 'X' : 'x'); } } if (!(Type & ACPI_FORMAT_LEFT)) { while (--Width >= 0) { String = AcpiUtBoundStringOutput (String, End, Zero); } } while (i <= --Precision) { String = AcpiUtBoundStringOutput (String, End, '0'); } while (--i >= 0) { String = AcpiUtBoundStringOutput (String, End, ReversedString[i]); } while (--Width >= 0) { String = AcpiUtBoundStringOutput (String, End, ' '); } return (String); } /******************************************************************************* * * FUNCTION: vsnprintf * * PARAMETERS: String - String with boundary * Size - Boundary of the string * Format - Standard printf format * Args - Argument list * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to a string using argument list pointer. * ******************************************************************************/ int vsnprintf ( char *String, ACPI_SIZE Size, const char *Format, va_list Args) { UINT8 Base; UINT8 Type; INT32 Width; INT32 Precision; char Qualifier; UINT64 Number; char *Pos; char *End; char c; const char *s; const void *p; INT32 Length; int i; Pos = String; if (Size != ACPI_UINT32_MAX) { End = String + Size; } else { End = ACPI_CAST_PTR(char, ACPI_UINT32_MAX); } for (; *Format; ++Format) { if (*Format != '%') { Pos = AcpiUtBoundStringOutput (Pos, End, *Format); continue; } Type = 0; Base = 10; /* Process sign */ do { ++Format; if (*Format == '#') { Type |= ACPI_FORMAT_PREFIX; } else if (*Format == '0') { Type |= ACPI_FORMAT_ZERO; } else if (*Format == '+') { Type |= ACPI_FORMAT_SIGN_PLUS; } else if (*Format == ' ') { Type |= ACPI_FORMAT_SIGN_PLUS_SPACE; } else if (*Format == '-') { Type |= ACPI_FORMAT_LEFT; } else { break; } } while (1); /* Process width */ Width = -1; if (isdigit ((int) *Format)) { Format = AcpiUtScanNumber (Format, &Number); Width = (INT32) Number; } else if (*Format == '*') { ++Format; Width = va_arg (Args, int); if (Width < 0) { Width = -Width; Type |= ACPI_FORMAT_LEFT; } } /* Process precision */ Precision = -1; if (*Format == '.') { ++Format; if (isdigit ((int) *Format)) { Format = AcpiUtScanNumber (Format, &Number); Precision = (INT32) Number; } else if (*Format == '*') { ++Format; Precision = va_arg (Args, int); } if (Precision < 0) { Precision = 0; } } /* Process qualifier */ Qualifier = -1; if (*Format == 'h' || *Format == 'l' || *Format == 'L') { Qualifier = *Format; ++Format; if (Qualifier == 'l' && *Format == 'l') { Qualifier = 'L'; ++Format; } } switch (*Format) { case '%': Pos = AcpiUtBoundStringOutput (Pos, End, '%'); continue; case 'c': if (!(Type & ACPI_FORMAT_LEFT)) { while (--Width > 0) { Pos = AcpiUtBoundStringOutput (Pos, End, ' '); } } c = (char) va_arg (Args, int); Pos = AcpiUtBoundStringOutput (Pos, End, c); while (--Width > 0) { Pos = AcpiUtBoundStringOutput (Pos, End, ' '); } continue; case 's': s = va_arg (Args, char *); if (!s) { s = "<NULL>"; } Length = (INT32) AcpiUtBoundStringLength (s, Precision); if (!(Type & ACPI_FORMAT_LEFT)) { while (Length < Width--) { Pos = AcpiUtBoundStringOutput (Pos, End, ' '); } } for (i = 0; i < Length; ++i) { Pos = AcpiUtBoundStringOutput (Pos, End, *s); ++s; } while (Length < Width--) { Pos = AcpiUtBoundStringOutput (Pos, End, ' '); } continue; case 'o': Base = 8; break; case 'X': Type |= ACPI_FORMAT_UPPER; /* FALLTHROUGH */ case 'x': Base = 16; break; case 'd': case 'i': Type |= ACPI_FORMAT_SIGN; case 'u': break; case 'p': if (Width == -1) { Width = 2 * sizeof (void *); Type |= ACPI_FORMAT_ZERO; } p = va_arg (Args, void *); Pos = AcpiUtFormatNumber ( Pos, End, ACPI_TO_INTEGER (p), 16, Width, Precision, Type); continue; default: Pos = AcpiUtBoundStringOutput (Pos, End, '%'); if (*Format) { Pos = AcpiUtBoundStringOutput (Pos, End, *Format); } else { --Format; } continue; } if (Qualifier == 'L') { Number = va_arg (Args, UINT64); if (Type & ACPI_FORMAT_SIGN) { Number = (INT64) Number; } } else if (Qualifier == 'l') { Number = va_arg (Args, unsigned long); if (Type & ACPI_FORMAT_SIGN) { Number = (INT32) Number; } } else if (Qualifier == 'h') { Number = (UINT16) va_arg (Args, int); if (Type & ACPI_FORMAT_SIGN) { Number = (INT16) Number; } } else { Number = va_arg (Args, unsigned int); if (Type & ACPI_FORMAT_SIGN) { Number = (signed int) Number; } } Pos = AcpiUtFormatNumber (Pos, End, Number, Base, Width, Precision, Type); } if (Size > 0) { if (Pos < End) { *Pos = '\0'; } else { End[-1] = '\0'; } } return ((int) ACPI_PTR_DIFF (Pos, String)); } /******************************************************************************* * * FUNCTION: snprintf * * PARAMETERS: String - String with boundary * Size - Boundary of the string * Format, ... - Standard printf format * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to a string. * ******************************************************************************/ int snprintf ( char *String, ACPI_SIZE Size, const char *Format, ...) { va_list Args; int Length; va_start (Args, Format); Length = vsnprintf (String, Size, Format, Args); va_end (Args); return (Length); } /******************************************************************************* * * FUNCTION: sprintf * * PARAMETERS: String - String with boundary * Format, ... - Standard printf format * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to a string. * ******************************************************************************/ int sprintf ( char *String, const char *Format, ...) { va_list Args; int Length; va_start (Args, Format); Length = vsnprintf (String, ACPI_UINT32_MAX, Format, Args); va_end (Args); return (Length); } #ifdef ACPI_APPLICATION /******************************************************************************* * * FUNCTION: vprintf * * PARAMETERS: Format - Standard printf format * Args - Argument list * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to stdout using argument list pointer. * ******************************************************************************/ int vprintf ( const char *Format, va_list Args) { ACPI_CPU_FLAGS Flags; int Length; Flags = AcpiOsAcquireLock (AcpiGbl_PrintLock); Length = vsnprintf (AcpiGbl_PrintBuffer, sizeof (AcpiGbl_PrintBuffer), Format, Args); (void) fwrite (AcpiGbl_PrintBuffer, Length, 1, ACPI_FILE_OUT); AcpiOsReleaseLock (AcpiGbl_PrintLock, Flags); return (Length); } /******************************************************************************* * * FUNCTION: printf * * PARAMETERS: Format, ... - Standard printf format * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to stdout. * ******************************************************************************/ int printf ( const char *Format, ...) { va_list Args; int Length; va_start (Args, Format); Length = vprintf (Format, Args); va_end (Args); return (Length); } /******************************************************************************* * * FUNCTION: vfprintf * * PARAMETERS: File - File descriptor * Format - Standard printf format * Args - Argument list * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to a file using argument list pointer. * ******************************************************************************/ int vfprintf ( FILE *File, const char *Format, va_list Args) { ACPI_CPU_FLAGS Flags; int Length; Flags = AcpiOsAcquireLock (AcpiGbl_PrintLock); Length = vsnprintf (AcpiGbl_PrintBuffer, sizeof (AcpiGbl_PrintBuffer), Format, Args); (void) fwrite (AcpiGbl_PrintBuffer, Length, 1, File); AcpiOsReleaseLock (AcpiGbl_PrintLock, Flags); return (Length); } /******************************************************************************* * * FUNCTION: fprintf * * PARAMETERS: File - File descriptor * Format, ... - Standard printf format * * RETURN: Number of bytes actually written. * * DESCRIPTION: Formatted output to a file. * ******************************************************************************/ int fprintf ( FILE *File, const char *Format, ...) { va_list Args; int Length; va_start (Args, Format); Length = vfprintf (File, Format, Args); va_end (Args); return (Length); } #endif <file_sep>/****************************************************************************** * * Module Name: nspredef - Validation of ACPI predefined methods and objects * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define ACPI_CREATE_PREDEFINED_TABLE #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acpredef.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nspredef") /******************************************************************************* * * This module validates predefined ACPI objects that appear in the namespace, * at the time they are evaluated (via AcpiEvaluateObject). The purpose of this * validation is to detect problems with BIOS-exposed predefined ACPI objects * before the results are returned to the ACPI-related drivers. * * There are several areas that are validated: * * 1) The number of input arguments as defined by the method/object in the * ASL is validated against the ACPI specification. * 2) The type of the return object (if any) is validated against the ACPI * specification. * 3) For returned package objects, the count of package elements is * validated, as well as the type of each package element. Nested * packages are supported. * * For any problems found, a warning message is issued. * ******************************************************************************/ /* Local prototypes */ static ACPI_STATUS AcpiNsCheckReference ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT *ReturnObject); static UINT32 AcpiNsGetBitmappedType ( ACPI_OPERAND_OBJECT *ReturnObject); /******************************************************************************* * * FUNCTION: AcpiNsCheckReturnValue * * PARAMETERS: Node - Namespace node for the method/object * Info - Method execution information block * UserParamCount - Number of parameters actually passed * ReturnStatus - Status from the object evaluation * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status * * DESCRIPTION: Check the value returned from a predefined name. * ******************************************************************************/ ACPI_STATUS AcpiNsCheckReturnValue ( ACPI_NAMESPACE_NODE *Node, ACPI_EVALUATE_INFO *Info, UINT32 UserParamCount, ACPI_STATUS ReturnStatus, ACPI_OPERAND_OBJECT **ReturnObjectPtr) { ACPI_STATUS Status; const ACPI_PREDEFINED_INFO *Predefined; /* If not a predefined name, we cannot validate the return object */ Predefined = Info->Predefined; if (!Predefined) { return (AE_OK); } /* * If the method failed or did not actually return an object, we cannot * validate the return object */ if ((ReturnStatus != AE_OK) && (ReturnStatus != AE_CTRL_RETURN_VALUE)) { return (AE_OK); } /* * Return value validation and possible repair. * * 1) Don't perform return value validation/repair if this feature * has been disabled via a global option. * * 2) We have a return value, but if one wasn't expected, just exit, * this is not a problem. For example, if the "Implicit Return" * feature is enabled, methods will always return a value. * * 3) If the return value can be of any type, then we cannot perform * any validation, just exit. */ if (AcpiGbl_DisableAutoRepair || (!Predefined->Info.ExpectedBtypes) || (Predefined->Info.ExpectedBtypes == ACPI_RTYPE_ALL)) { return (AE_OK); } /* * Check that the type of the main return object is what is expected * for this predefined name */ Status = AcpiNsCheckObjectType (Info, ReturnObjectPtr, Predefined->Info.ExpectedBtypes, ACPI_NOT_PACKAGE_ELEMENT); if (ACPI_FAILURE (Status)) { goto Exit; } /* * * 4) If there is no return value and it is optional, just return * AE_OK (_WAK). */ if (!(*ReturnObjectPtr)) { goto Exit; } /* * For returned Package objects, check the type of all sub-objects. * Note: Package may have been newly created by call above. */ if ((*ReturnObjectPtr)->Common.Type == ACPI_TYPE_PACKAGE) { Info->ParentPackage = *ReturnObjectPtr; Status = AcpiNsCheckPackage (Info, ReturnObjectPtr); if (ACPI_FAILURE (Status)) { /* We might be able to fix some errors */ if ((Status != AE_AML_OPERAND_TYPE) && (Status != AE_AML_OPERAND_VALUE)) { goto Exit; } } } /* * The return object was OK, or it was successfully repaired above. * Now make some additional checks such as verifying that package * objects are sorted correctly (if required) or buffer objects have * the correct data width (bytes vs. dwords). These repairs are * performed on a per-name basis, i.e., the code is specific to * particular predefined names. */ Status = AcpiNsComplexRepairs (Info, Node, Status, ReturnObjectPtr); Exit: /* * If the object validation failed or if we successfully repaired one * or more objects, mark the parent node to suppress further warning * messages during the next evaluation of the same method/object. */ if (ACPI_FAILURE (Status) || (Info->ReturnFlags & ACPI_OBJECT_REPAIRED)) { Node->Flags |= ANOBJ_EVALUATED; } return (Status); } /******************************************************************************* * * FUNCTION: AcpiNsCheckObjectType * * PARAMETERS: Info - Method execution information block * ReturnObjectPtr - Pointer to the object returned from the * evaluation of a method or object * ExpectedBtypes - Bitmap of expected return type(s) * PackageIndex - Index of object within parent package (if * applicable - ACPI_NOT_PACKAGE_ELEMENT * otherwise) * * RETURN: Status * * DESCRIPTION: Check the type of the return object against the expected object * type(s). Use of Btype allows multiple expected object types. * ******************************************************************************/ ACPI_STATUS AcpiNsCheckObjectType ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT **ReturnObjectPtr, UINT32 ExpectedBtypes, UINT32 PackageIndex) { ACPI_OPERAND_OBJECT *ReturnObject = *ReturnObjectPtr; ACPI_STATUS Status = AE_OK; char TypeBuffer[96]; /* Room for 10 types */ /* A Namespace node should not get here, but make sure */ if (ReturnObject && ACPI_GET_DESCRIPTOR_TYPE (ReturnObject) == ACPI_DESC_TYPE_NAMED) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Invalid return type - Found a Namespace node [%4.4s] type %s", ReturnObject->Node.Name.Ascii, AcpiUtGetTypeName (ReturnObject->Node.Type))); return (AE_AML_OPERAND_TYPE); } /* * Convert the object type (ACPI_TYPE_xxx) to a bitmapped object type. * The bitmapped type allows multiple possible return types. * * Note, the cases below must handle all of the possible types returned * from all of the predefined names (including elements of returned * packages) */ Info->ReturnBtype = AcpiNsGetBitmappedType (ReturnObject); if (Info->ReturnBtype == ACPI_RTYPE_ANY) { /* Not one of the supported objects, must be incorrect */ goto TypeErrorExit; } /* For reference objects, check that the reference type is correct */ if ((Info->ReturnBtype & ExpectedBtypes) == ACPI_RTYPE_REFERENCE) { Status = AcpiNsCheckReference (Info, ReturnObject); return (Status); } /* Attempt simple repair of the returned object if necessary */ Status = AcpiNsSimpleRepair (Info, ExpectedBtypes, PackageIndex, ReturnObjectPtr); if (ACPI_SUCCESS (Status)) { return (AE_OK); /* Successful repair */ } TypeErrorExit: /* Create a string with all expected types for this predefined object */ AcpiUtGetExpectedReturnTypes (TypeBuffer, ExpectedBtypes); if (!ReturnObject) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Expected return object of type %s", TypeBuffer)); } else if (PackageIndex == ACPI_NOT_PACKAGE_ELEMENT) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return type mismatch - found %s, expected %s", AcpiUtGetObjectTypeName (ReturnObject), TypeBuffer)); } else { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return Package type mismatch at index %u - " "found %s, expected %s", PackageIndex, AcpiUtGetObjectTypeName (ReturnObject), TypeBuffer)); } return (AE_AML_OPERAND_TYPE); } /******************************************************************************* * * FUNCTION: AcpiNsCheckReference * * PARAMETERS: Info - Method execution information block * ReturnObject - Object returned from the evaluation of a * method or object * * RETURN: Status * * DESCRIPTION: Check a returned reference object for the correct reference * type. The only reference type that can be returned from a * predefined method is a named reference. All others are invalid. * ******************************************************************************/ static ACPI_STATUS AcpiNsCheckReference ( ACPI_EVALUATE_INFO *Info, ACPI_OPERAND_OBJECT *ReturnObject) { /* * Check the reference object for the correct reference type (opcode). * The only type of reference that can be converted to an ACPI_OBJECT is * a reference to a named object (reference class: NAME) */ if (ReturnObject->Reference.Class == ACPI_REFCLASS_NAME) { return (AE_OK); } ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, Info->NodeFlags, "Return type mismatch - unexpected reference object type [%s] %2.2X", AcpiUtGetReferenceName (ReturnObject), ReturnObject->Reference.Class)); return (AE_AML_OPERAND_TYPE); } /******************************************************************************* * * FUNCTION: AcpiNsGetBitmappedType * * PARAMETERS: ReturnObject - Object returned from method/obj evaluation * * RETURN: Object return type. ACPI_RTYPE_ANY indicates that the object * type is not supported. ACPI_RTYPE_NONE indicates that no * object was returned (ReturnObject is NULL). * * DESCRIPTION: Convert object type into a bitmapped object return type. * ******************************************************************************/ static UINT32 AcpiNsGetBitmappedType ( ACPI_OPERAND_OBJECT *ReturnObject) { UINT32 ReturnBtype; if (!ReturnObject) { return (ACPI_RTYPE_NONE); } /* Map ACPI_OBJECT_TYPE to internal bitmapped type */ switch (ReturnObject->Common.Type) { case ACPI_TYPE_INTEGER: ReturnBtype = ACPI_RTYPE_INTEGER; break; case ACPI_TYPE_BUFFER: ReturnBtype = ACPI_RTYPE_BUFFER; break; case ACPI_TYPE_STRING: ReturnBtype = ACPI_RTYPE_STRING; break; case ACPI_TYPE_PACKAGE: ReturnBtype = ACPI_RTYPE_PACKAGE; break; case ACPI_TYPE_LOCAL_REFERENCE: ReturnBtype = ACPI_RTYPE_REFERENCE; break; default: /* Not one of the supported objects, must be incorrect */ ReturnBtype = ACPI_RTYPE_ANY; break; } return (ReturnBtype); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/self_tests.h> #include <elf.h> // system header #include <multiboot.h> // system header in include/system_headers /* * NOTE: this flag affect affect sched_alive_thread() only when it is actually * running. By default it does *not* run. It gets activated only by the kernel * cmdline option -sat. */ static volatile bool sched_alive_thread_enabled = true; static void sched_alive_thread() { for (int counter = 0; ; counter++) { if (sched_alive_thread_enabled) { printk("---- Sched alive thread: %d ----\n", counter); if (KERNEL_SELFTESTS && (counter % 2)) { debug_check_for_deadlock(); debug_check_for_any_progress(); } } kernel_sleep(TIMER_HZ); } } void init_extra_debug_features(void) { if (kopt_sched_alive_thread) if (kthread_create(&sched_alive_thread, 0, NULL) < 0) panic("Unable to create a kthread for sched_alive_thread()"); } int set_sched_alive_thread_enabled(bool enabled) { sched_alive_thread_enabled = enabled; return 0; } void kmain_early_checks(void) { if (KERNEL_FORCE_TC_ISYSTEM) panic("Builds with KERNEL_FORCE_TC_ISYSTEM=1 are not supposed to run"); } #if SLOW_DEBUG_REF_COUNT /* * Set here the address of the ref_count to track. */ void *debug_refcount_obj = (void *)0; /* Return the new value */ int __retain_obj(int *ref_count) { int ret; ATOMIC(int) *atomic = (ATOMIC(int) *)ref_count; ret = atomic_fetch_add_explicit(atomic, 1, mo_relaxed) + 1; if (!debug_refcount_obj || ref_count == debug_refcount_obj) { printk(COLOR_GREEN "refcount at %p: %d -> %d" RESET_ATTRS "\n", ref_count, ret-1, ret); } return ret; } /* Return the new value */ int __release_obj(int *ref_count) { int old, ret; ATOMIC(int) *atomic = (ATOMIC(int) *)ref_count; old = atomic_fetch_sub_explicit(atomic, 1, mo_relaxed); ASSERT(old > 0); ret = old - 1; if (!debug_refcount_obj || ref_count == debug_refcount_obj) { printk(COLOR_RED "refcount at %p: %d -> %d" RESET_ATTRS "\n", ref_count, old, ret); } return ret; } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> /* * When this flag is set in the 'avail' bits in page_t, in means that the page * is writeable even if it marked as read-only and that, on a write attempt * the page has to be copied (copy-on-write). */ #define PAGE_COW_ORIG_RW (1 << 0) /* * When this flag is set in the 'avail' bits in page_t, it means that the page * is shared and, therefore, can never become a CoW page. */ #define PAGE_SHARED (1 << 1) /* ---------------------------------------------- */ extern char zero_page[PAGE_SIZE] ALIGNED_AT(PAGE_SIZE); extern u32 *pageframes_refcount; extern ulong phys_mem_lim; extern struct kmalloc_heap *hi_vmem_heap; static ALWAYS_INLINE u32 __pf_ref_count_inc(u32 paddr) { return ++pageframes_refcount[paddr >> PAGE_SHIFT]; } static ALWAYS_INLINE u32 __pf_ref_count_dec(u32 paddr) { ASSERT(pageframes_refcount[paddr >> PAGE_SHIFT] > 0); return --pageframes_refcount[paddr >> PAGE_SHIFT]; } static ALWAYS_INLINE u32 pf_ref_count_inc(u32 paddr) { if (UNLIKELY(paddr >= phys_mem_lim)) return 0; return __pf_ref_count_inc(paddr); } static ALWAYS_INLINE u32 pf_ref_count_dec(u32 paddr) { if (UNLIKELY(paddr >= phys_mem_lim)) return 0; return __pf_ref_count_dec(paddr); } static ALWAYS_INLINE u32 pf_ref_count_get(u32 paddr) { if (UNLIKELY(paddr >= phys_mem_lim)) return 0; return pageframes_refcount[paddr >> PAGE_SHIFT]; } void init_hi_vmem_heap(void); void *failsafe_map_framebuffer(ulong paddr, ulong size); int virtual_read_unsafe(pdir_t *pdir, void *extern_va, void *dest, size_t len); int virtual_write_unsafe(pdir_t *pdir, void *extern_va, void *src, size_t len); size_t map_zero_pages(pdir_t *pdir, void *vaddrp, size_t page_count, u32 pg_flags); void handle_page_fault_int(regs_t *r); void handle_page_fault(regs_t *r); <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). just_run_vim_and_exit() do_interactive_actions( "vim1", [ r"vim /usr/lib/vim/samples/numbers.txt{ret}", r"{esc}:29{ret}", r"{down}", r"{down}", r"{down}", r"{esc}:3{ret}", r"{up}", r"{up}", r"{esc}:q{ret}", ], false_positive_handler_vim ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once void gcov_dump_coverage(void); int sys_gcov_get_file_count(void); int sys_gcov_get_file_info(int fn, char *user_fname_buf, u32 fname_buf_size, u32 *user_fsize); int sys_gcov_get_file(int fn, char *user_buf); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <memory> #include <cstdlib> struct TrivialAllocatorData { char *buf; size_t used; size_t buf_size; ~TrivialAllocatorData() { free(buf); } }; template <class T> class MyTrivialAllocator { public: using value_type = T; std::shared_ptr<TrivialAllocatorData> data; MyTrivialAllocator() noexcept { } MyTrivialAllocator(size_t sz) noexcept { if (sz == 0) return; data = std::make_shared<TrivialAllocatorData>(); data->buf = reinterpret_cast<char *>(malloc(sz)); if (!data->buf) { data.reset(); return; } data->buf_size = sz; data->used = 0; } ~MyTrivialAllocator() noexcept = default; template<class U> MyTrivialAllocator(const MyTrivialAllocator<U>& rhs) noexcept { data = rhs.data; } T *allocate (std::size_t elems_count) { const size_t n = elems_count * sizeof(value_type); if (!data) return nullptr; if (data->used + n > data->buf_size) { return nullptr; } T *ret = reinterpret_cast<T *>(data->buf + data->used); data->used += n; return ret; } void deallocate (T* p, std::size_t n) { /* do nothing */ } }; template <class T, class U> bool operator==(const MyTrivialAllocator<T>& a, const MyTrivialAllocator<U>& b) noexcept { return true; } template <class T, class U> bool operator!=(const MyTrivialAllocator<T>& a, const MyTrivialAllocator<U>& b) noexcept { return false; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * Tilck's userspace interface for sound drivers (e.g. /dev/sb16). * * TODO: drop this by implementing Linux's kernel ALSA interface. */ #pragma once #include <tilck/common/basic_defs.h> #define TILCK_IOCTL_SOUND_ACQUIRE 1 #define TILCK_IOCTL_SOUND_RELEASE 2 #define TILCK_IOCTL_SOUND_SETUP 3 #define TILCK_IOCTL_SOUND_PAUSE 4 #define TILCK_IOCTL_SOUND_CONTINUE 5 #define TILCK_IOCTL_SOUND_GET_INFO 6 #define TILCK_IOCTL_SOUND_WAIT_COMPLETION 7 /* Used with TILCK_IOCTL_SOUND_GET_INFO */ struct tilck_sound_card_info { char name[32]; u32 max_sample_rate; u32 max_bits; u32 max_channels; }; /* Used with TILCK_IOCTL_SOUND_SETUP */ struct tilck_sound_params { u16 sample_rate; /* 44100, 22050 etc. */ u8 bits; /* 8 or 16 */ u8 channels; /* 1 or 2 */ u8 sign; /* 0 = unsigned, 1 = signed */ }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #if !defined(TESTING) && !defined(USERMODE_APP) #ifdef STATIC_TILCK_ASM_STRING /* Some targets demand those symbols to be static to avoid link conflicts */ #define EXTERN static #else /* * This nice trick allows the code for the following functions to be emitted, * when not inlined, in only one translation unit, the one that declare them * as "extern". This is a little better than just using static inline because * avoids code duplication when the compiler decide to not inline a given * function. Compared to using static + ALWAYS_INLINE this gives the compiler * the maximum freedom to optimize. */ #ifdef __STRING_UTIL_C__ #define EXTERN extern #else #define EXTERN #endif #endif #if !(defined(__aarch64__) && defined(KERNEL_TEST)) /* * Don't define this function in this special case, because we're going to * include <string.h>. */ int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); int memcmp(const void *m1, const void *m2, size_t n); char *strstr(const char *haystack, const char *needle); char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t n); int isxdigit(int c); int isspace(int c); #endif EXTERN inline bool isalpha_lower(int c) { return IN_RANGE_INC(c, 'a', 'z'); } EXTERN inline bool isalpha_upper(int c) { return IN_RANGE_INC(c, 'A', 'Z'); } EXTERN inline int isalpha(int c) { return isalpha_lower(c) || isalpha_upper(c); } EXTERN inline int tolower(int c) { return isalpha_upper(c) ? c + 32 : c; } EXTERN inline int toupper(int c) { return isalpha_lower(c) ? c - 32 : c; } EXTERN inline int isdigit(int c) { return IN_RANGE_INC(c, '0', '9'); } EXTERN inline int isprint(int c) { return IN_RANGE_INC(c, ' ', '~'); } #if defined(__i386__) || defined(__x86_64__) #include <tilck/common/arch/generic_x86/asm_x86_strings.h> #elif defined(__aarch64__) && defined(KERNEL_TEST) /* * The Tilck kernel has no support for AARCH64 per se, but its noarch * code can be compiled as part of the unit tests on an AARCH64 host. */ #include <string.h> void *memset16(u16 *s, u16 val, size_t n); void *memset32(u32 *s, u32 val, size_t n); void *memcpy16(void *dest, const void *src, size_t n); void *memcpy32(void *dest, const void *src, size_t n); #endif #undef EXTERN #ifdef __MOD_ACPICA__ long strtol(const char *__restrict, char **__restrict, int base); ulong strtoul(const char *__restrict, char **__restrict, int base); #endif #else #include <string.h> #include <ctype.h> #include <stdarg.h> #endif // #if !defined(TESTING) && !defined(USERMODE_APP) static ALWAYS_INLINE bool slash_or_nul(char c) { return !c || c == '/'; } static inline bool is_dot_or_dotdot(const char *n, int nl) { return (n[0] == '.' && (nl == 1 || (n[1] == '.' && nl == 2))); } int stricmp(const char *s1, const char *s2); void str_reverse(char *str, size_t len); void itoa32(s32 value, char *destBuf); void itoa64(s64 value, char *destBuf); void itoaN(long value, char *buf); /* pointer-size */ void uitoa32(u32 value, char *buf, int base); void uitoa64(u64 value, char *buf, int base); void uitoaN(ulong value, char *buf, int base); /* pointer-size */ void uitoa32_hex_fixed(u32 value, char *buf); void uitoa64_hex_fixed(u64 value, char *buf); void uitoaN_hex_fixed(ulong value, char *buf); /* pointer-size */ long tilck_strtol(const char *str, const char **endptr, int base, int *error); ulong tilck_strtoul(const char *str, const char **endptr, int base, int *error); int tilck_strcmp(const char *s1, const char *s2); int tilck_strncmp(const char *s1, const char *s2, size_t n); int tilck_memcmp(const void *m1, const void *m2, size_t n); char *tilck_strstr(const char *haystack, const char *needle); char *tilck_strcpy(char *dest, const char *src); char *tilck_strncpy(char *dest, const char *src, size_t n); char *tilck_strcat(char *dest, const char *src); char *tilck_strncat(char *dest, const char *src, size_t n); int tilck_isxdigit(int c); int tilck_isspace(int c); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/list.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_malloc") #define ACPI_HEAP_SIZE (128 * KB) #define ACPI_HEAP_MBS 32 #define ACPI_HEAP_MAX_OBJ_SIZE 128 static struct kmalloc_heap *acpi_heap; static ulong acpi_heap_va; static ulong acpi_heap_last_obj_addr; static void * acpi_osl_do_alloc(size_t sz) { void *vaddr = NULL; if (sz <= ACPI_HEAP_MAX_OBJ_SIZE) { disable_preemption(); { vaddr = per_heap_kmalloc(acpi_heap, &sz, 0); } enable_preemption_nosched(); } if (!vaddr) vaddr = kmalloc(sz); return vaddr; } static void acpi_osl_do_free(void *ptr) { ulong va = (ulong)ptr; size_t sz = 0; if (IN_RANGE_INC(va, acpi_heap_va, acpi_heap_last_obj_addr)) { disable_preemption(); { per_heap_kfree(acpi_heap, ptr, &sz, 0); } enable_preemption_nosched(); } else { kfree(ptr); } } void * AcpiOsAllocate(ACPI_SIZE Size) { const size_t sz = (size_t)Size; void *vaddr; ulong var; ACPI_FUNCTION_TRACE(__FUNC__); if (Size >= 512 * MB) { /* * Don't allow that, ever. Note some kind of check is mandatory, even if * the machine has more than 512 MB of contiguous free memory, just * because ACPI_SIZE is 64-bit wide, while kmalloc()'s size parameter * is a pointer-size integer. In general, ACPICA shouldn't even consider * allocating so large chunks of memory, no matter what. ACPI_SIZE is * 64-bit wide just because it's used for other purposes as well (memory * regions, even on 32-bit systems, can indeed be larger than 2^32 bytes). */ return_PTR(NULL); } // if (in_irq()) { // printk("ACPI: AcpiOsAllocate(%zu) called in IRQ context\n", sz); // } disable_interrupts(&var); { vaddr = acpi_osl_do_alloc(sz); } enable_interrupts(&var); return_PTR(vaddr); } void AcpiOsFree(void *Memory) { ACPI_FUNCTION_TRACE(__FUNC__); ulong var; disable_interrupts(&var); { acpi_osl_do_free(Memory); } enable_interrupts(&var); return_VOID; } ACPI_STATUS osl_init_malloc(void) { acpi_heap_va = (ulong)kmalloc(ACPI_HEAP_SIZE); if (!acpi_heap_va) return AE_NO_MEMORY; acpi_heap = kmalloc_create_regular_heap(acpi_heap_va, ACPI_HEAP_SIZE, ACPI_HEAP_MBS); if (!acpi_heap) { kfree2((void *)acpi_heap_va, ACPI_HEAP_SIZE); acpi_heap_va = 0; return AE_NO_MEMORY; } acpi_heap_last_obj_addr = acpi_heap_va + ACPI_HEAP_SIZE - ACPI_HEAP_MBS; return AE_OK; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ############################### # Mtools ############################### MTOOLS_VER="4.0.23" all_funcs_list+=(build_mtools) function build_mtools { pushd host_${HOST_ARCH} if ! [ -d mtools ]; then show_work_on_component_msg "MTOOLS" local pkgname="mtools-$MTOOLS_VER" local tarname=$pkgname.tar.gz download_file_in_cache "ftp://ftp.gnu.org/gnu/mtools" "$tarname" extract_cachefile_tar_gz $tarname $pkgname mtools cd mtools reset_cc_vars run_command2 ./configure configure.log run_command2 "make -j$BUILD_PAR" build.log else show_skip_component_msg "MTOOLS" fi popd } function build_mtools_installed_status { if [ -d $TC/host_${HOST_ARCH}/mtools ]; then if [ -f $TC/host_${HOST_ARCH}/mtools/mtools ]; then echo "installed host_${HOST_ARCH}" else echo "error" fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/user.h> #include <tilck/kernel/vdso.h> #include <tilck/mods/tracing.h> bool arch_specific_new_task_setup(struct task *ti, struct task *parent) { NOT_IMPLEMENTED(); } void arch_specific_free_task(struct task *ti) { NOT_IMPLEMENTED(); } void arch_specific_new_proc_setup(struct process *pi, struct process *parent) { NOT_IMPLEMENTED(); } void arch_specific_free_proc(struct process *pi) { NOT_IMPLEMENTED(); } NODISCARD int kthread_create2(kthread_func_ptr func, const char *name, int fl, void *arg) { NOT_IMPLEMENTED(); } NORETURN void switch_to_task(struct task *ti) { NOT_IMPLEMENTED(); } void finalize_usermode_task_setup(struct task *ti, regs_t *user_regs) { NOT_IMPLEMENTED(); } int setup_process(struct elf_program_info *pinfo, struct task *ti, const char *const *argv, const char *const *env, struct task **ti_ref, regs_t *r) { NOT_IMPLEMENTED(); } void setup_pause_trampoline(regs_t *r) { NOT_IMPLEMENTED(); } int setup_sig_handler(struct task *ti, enum sig_state sig_state, regs_t *r, ulong user_func, int signum) { NOT_IMPLEMENTED(); } void task_info_reset_kernel_stack(struct task *ti) { NOT_IMPLEMENTED(); } void save_current_task_state(regs_t *r) { NOT_IMPLEMENTED(); } <file_sep># SPDX-License-Identifier: BSD-2-Clause import sys # Runtime config vars runnerName = "<UNKNOWN>" def direct_print(data): sys.stdout.buffer.write(data) sys.stdout.buffer.flush() def raw_print(msg): sys.stdout.buffer.write(msg.encode('utf-8')) sys.stdout.buffer.write('\n'.encode('utf-8')) sys.stdout.buffer.flush() def raw_stdout_write(msg): sys.stdout.buffer.write(msg.encode('utf-8')) sys.stdout.buffer.flush() def msg_print(msg): raw_print("[{}] {}".format(runnerName, msg)) def set_runner_name(name): global runnerName runnerName = name <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_fb.h> #include <tilck_gen_headers/mod_console.h> #include <tilck/common/basic_defs.h> #include <tilck/common/color_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/term.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/cmdline.h> #include <tilck/mods/fb_console.h> #include <tilck/mods/acpi.h> #include "fb_int.h" extern char _binary_font8x16_psf_start; extern char _binary_font16x32_psf_start; static bool use_optimized; static u32 fb_term_rows; static u32 fb_term_cols; static u32 fb_offset_y; static bool cursor_enabled; static bool banner_refresh_disabled; static u16 cursor_row; static u16 cursor_col; static u32 *under_cursor_buf; static volatile bool cursor_visible = true; static struct task *blink_thread_ti; static const u32 blink_half_period = (TIMER_HZ * 45)/100; static u32 cursor_color; /* * Battery charge per mille. Valid values in range [0, 1000]. * * Special values: * * -1 No initialized * -2 Read failed with an unrecoverable error * * See: fb_banner_update_battery_pm() */ static int batt_charge_pm = -1; static struct video_interface framebuffer_vi; static void fb_save_under_cursor_buf(void) { if (!under_cursor_buf) return; if (cursor_row >= fb_term_rows || cursor_col >= fb_term_cols) return; const u32 ix = cursor_col * font_w; const u32 iy = fb_offset_y + cursor_row * font_h; fb_copy_from_screen(ix, iy, font_w, font_h, under_cursor_buf); } static void fb_restore_under_cursor_buf(void) { if (!under_cursor_buf) return; if (cursor_row >= fb_term_rows || cursor_col >= fb_term_cols) return; const u32 ix = cursor_col * font_w; const u32 iy = fb_offset_y + cursor_row * font_h; fb_copy_to_screen(ix, iy, font_w, font_h, under_cursor_buf); } static void fb_reset_blink_timer(void) { if (!blink_thread_ti) return; cursor_visible = true; task_update_wakeup_timer_if_any(blink_thread_ti, blink_half_period); } /* video_interface */ static void fb_set_char_at_failsafe(u16 row, u16 col, u16 entry) { fb_draw_char_failsafe(col * font_w, fb_offset_y + row * font_h, entry); if (row == cursor_row && col == cursor_col) fb_save_under_cursor_buf(); fb_reset_blink_timer(); } static void fb_set_char_at_optimized(u16 row, u16 col, u16 entry) { fb_draw_char_optimized(col * font_w, fb_offset_y + row * font_h, entry); if (row == cursor_row && col == cursor_col) fb_save_under_cursor_buf(); fb_reset_blink_timer(); } static void fb_clear_row(u16 row_num, u8 color) { const u32 iy = fb_offset_y + row_num * font_h; fb_raw_color_lines(iy, font_h, vga_rgb_colors[get_color_bg(color)]); if (cursor_row == row_num) fb_save_under_cursor_buf(); } static void fb_move_cursor(u16 row, u16 col, int cursor_vga_color) { if (!under_cursor_buf) return; fb_restore_under_cursor_buf(); if (row != cursor_row || col != cursor_col) cursor_visible = true; cursor_row = row; cursor_col = col; if (cursor_vga_color >= 0) cursor_color = vga_rgb_colors[cursor_vga_color]; if (!cursor_enabled) return; fb_save_under_cursor_buf(); if (cursor_visible) { if (cursor_row < fb_term_rows && cursor_col < fb_term_cols) { fb_draw_cursor_raw(cursor_col * font_w, fb_offset_y + cursor_row * font_h, cursor_color); } fb_reset_blink_timer(); } } static void fb_enable_cursor(void) { if (cursor_enabled) return; /* * The cursor was disabled and now we have to re-enable it again. In the * meanwhile many thing might happened, like the whole screen scrolled. * Therefore, before enabling the cursor, we have to update the * under_cursor_buf. */ fb_save_under_cursor_buf(); cursor_enabled = true; fb_move_cursor(cursor_row, cursor_col, -1); } static void fb_disable_cursor(void) { if (!cursor_enabled) return; cursor_enabled = false; fb_move_cursor(cursor_row, cursor_col, -1); } static void fb_set_row_failsafe(u16 row, u16 *data, bool fpu_allowed) { for (u16 i = 0; i < fb_term_cols; i++) fb_set_char_at_failsafe(row, i, data[i]); fb_reset_blink_timer(); } static void fb_set_row_optimized(u16 row, u16 *data, bool fpu_allowed) { fb_draw_row_optimized(fb_offset_y + row * font_h, data, fb_term_cols, fpu_allowed); fb_reset_blink_timer(); } void fb_draw_banner(void); static void fb_disable_banner_refresh(void) { banner_refresh_disabled = true; } static void fb_enable_banner_refresh(void) { banner_refresh_disabled = false; fb_draw_banner(); } // --------------------------------------------- static struct video_interface framebuffer_vi = { fb_set_char_at_failsafe, fb_set_row_failsafe, fb_clear_row, fb_move_cursor, fb_enable_cursor, fb_disable_cursor, NULL, /* scroll_one_line_up: used only when running in a VM */ fb_draw_banner, fb_disable_banner_refresh, fb_enable_banner_refresh, }; static void fb_blink_thread() { while (true) { if (cursor_enabled) { cursor_visible = !cursor_visible; fb_move_cursor(cursor_row, cursor_col, -1); } kernel_sleep(blink_half_period); } } static void fb_draw_string_at_raw(u32 x, u32 y, const char *str, u8 color) { if (use_optimized) for (; *str; str++, x += font_w) fb_draw_char_optimized(x, y, make_vgaentry(*str, color)); else for (; *str; str++, x += font_w) fb_draw_char_failsafe(x, y, make_vgaentry(*str, color)); } static void fb_setup_banner(void) { if (in_panic()) return; fb_offset_y = (20 * font_h) / 10; } static void fb_banner_update_battery_pm(void) { ulong charge; int rc; if (batt_charge_pm == -2) return; /* Read already failed with an unrecoverable error */ if (get_acpi_init_status() != ais_fully_initialized) return; /* Do nothing */ /* Do the actual read */ rc = acpi_get_all_batteries_charge_per_mille(&charge); if (!rc) batt_charge_pm = (int)charge; else if (rc != -ENOMEM) batt_charge_pm = -2; /* Unrecoverable error (anything != out of memory) */ } static u32 fb_banner_left_side(char *buf, size_t buf_sz) { int ttynum = 1; int rc; if (get_curr_tty()) ttynum = get_curr_tty_num(); if (ttynum > 0) { rc = snprintk(buf, buf_sz, "Tilck [%s] [tty %d]", BUILDTYPE_STR, ttynum); } else { rc = snprintk(buf, buf_sz, "Tilck [%s]", BUILDTYPE_STR); } ASSERT(rc >= 0); return MIN((u32)rc, buf_sz); } static u32 fb_banner_right_side(char *buf, size_t buf_sz) { struct datetime d; int rc; if (batt_charge_pm == -1) { /* * Read the current battery charge per mille ONLY IF the value has never * been read. The purpose of this is to avoid forcing battery's controller * to do too many charge reads. * * The actual value is updated peridically by fb_update_banner(). */ fb_banner_update_battery_pm(); } timestamp_to_datetime(get_timestamp(), &d); if (batt_charge_pm >= 0) { rc = snprintk(buf, buf_sz, "[Battery: %d.%d%%] [%02i %s %i %02i:%02i]", batt_charge_pm / 10, batt_charge_pm % 10, d.day, months3[d.month - 1], d.year, d.hour, d.min); } else { rc = snprintk(buf, buf_sz, "[%02i %s %i %02i:%02i]", d.day, months3[d.month - 1], d.year, d.hour, d.min); } ASSERT(rc >= 0); return MIN((u32)rc, buf_sz); } void fb_draw_banner(void) { static bool oom; static char *lbuf; static char *rbuf; if (oom || !fb_offset_y) return; if (!lbuf) { lbuf = kmalloc(fb_term_cols + 1); if (!lbuf) { oom = true; return; } } if (!rbuf) { rbuf = kmalloc(fb_term_cols + 1); if (!rbuf) { oom = true; return; } } u32 llen, rlen, padding = 0; ASSERT(fb_offset_y >= font_h); /* * Prepare banner's content. * * It's worth remarking that we're passing to our aux funcs fb_term_cols + 1 * as length which is the real buffer's length, not `fb_term_cols`. That's * because snprintk() will always zero-terminate the buffer and it cannot do * that in the corner case where all the columns have been used, without * dropping one column. I.e. with a buffer of 80 chars, we can have at most * 79 chars of data + 1 for the NUL terminator. Therefore, our buffers are +1 * char bigger. */ llen = fb_banner_left_side(lbuf, fb_term_cols + 1); rlen = fb_banner_right_side(rbuf, fb_term_cols + 1 - llen); if (llen + rlen < fb_term_cols) { /* Calculate the padding */ padding = fb_term_cols - llen - rlen; /* Insert the padding after the content in the left buffer */ memset(lbuf + llen, ' ', padding); } /* Copy the whole right buffer in the left buffer, after the padding */ memcpy(lbuf + llen + padding, rbuf, rlen); /* Make sure that, if we used the whole buffer, it is NUL-terminated */ lbuf[fb_term_cols] = 0; /* Clear the banner area */ fb_raw_color_lines(0, fb_offset_y, 0 /* black */); /* Draw the horizontal banner separation line */ fb_raw_color_lines(fb_offset_y - 4, 1, vga_rgb_colors[COLOR_BRIGHT_WHITE]); /* Draw the actual banner's text */ fb_draw_string_at_raw(0, font_h/2, lbuf, COLOR_BRIGHT_YELLOW); /* Clear the remaining screen area below the banner and the text */ u32 top_lines_used = fb_offset_y + font_h * fb_term_rows; fb_raw_color_lines(top_lines_used, fb_get_height() - top_lines_used, vga_rgb_colors[COLOR_BLACK]); } static void fb_update_banner() { while (true) { if (!banner_refresh_disabled) { fb_banner_update_battery_pm(); fb_draw_banner(); } kernel_sleep(30 * TIMER_HZ); } } static u32 fb_console_on_acpi_full_init_func(void *ctx) { if (!banner_refresh_disabled) fb_draw_banner(); return 0; } static struct acpi_reg_callback_node fb_console_on_acpi_full_init_node = { .node = STATIC_LIST_NODE_INIT(fb_console_on_acpi_full_init_node.node), .cb = &fb_console_on_acpi_full_init_func, .ctx = NULL }; static void fb_scroll_one_line_up(void) { bool enabled = cursor_enabled; if (enabled) fb_disable_cursor(); fb_lines_shift_up(fb_offset_y + font_h, /* source: row 1 (+ following) */ fb_offset_y, /* destination: row 0 */ fb_get_height() - fb_offset_y - font_h); if (enabled) fb_enable_cursor(); } static void async_pre_render_scanlines() { if (!fb_pre_render_char_scanlines()) { printk("fb_console: WARNING: fb_pre_render_char_scanlines failed.\n"); return; } disable_interrupts_forced(); { use_optimized = true; framebuffer_vi.set_char_at = fb_set_char_at_optimized; framebuffer_vi.set_row = fb_set_row_optimized; } enable_interrupts_forced(); } static void fb_use_optimized_funcs_if_possible(void) { if (in_hypervisor()) framebuffer_vi.scroll_one_line_up = fb_scroll_one_line_up; if (in_panic()) return; if (kopt_fb_no_opt) { printk("fb_console: optimized funcs won't be used (kopt_fb_no_opt)\n"); return; } if (font_w % 8) { printk("fb_console: WARNING: using slower code for font %d x %d\n", font_w, font_h); printk("fb_console: switch to a font having width = 8, 16, 24, ...\n"); return; } if (fb_get_bpp() != 32) { printk("fb_console: WARNING: using slower code for bpp = %d\n", fb_get_bpp()); printk("fb_console: switch to a resolution with bpp = 32 if possible\n"); return; } if (kmalloc_get_max_tot_heap_free() < FBCON_OPT_FUNCS_MIN_FREE_HEAP) { printk("fb_console: Not using fast funcs in order to save memory\n"); return; } if (kthread_create(async_pre_render_scanlines, 0, NULL) < 0) printk("fb_console: WARNING: unable to create a kthread for " "async_pre_render_scanlines\n"); } bool fb_is_using_opt_funcs(void) { return use_optimized; } static void fb_create_cursor_blinking_thread(void) { int tid = kthread_create(fb_blink_thread, 0, NULL); if (tid < 0) { printk("WARNING: unable to create the fb_blink_thread\n"); return; } disable_preemption(); { blink_thread_ti = get_task(tid); ASSERT(blink_thread_ti != NULL); } enable_preemption(); } void init_fb_console(void) { ASSERT(use_framebuffer()); ASSERT(fb_get_width() > 0); cursor_color = vga_rgb_colors[COLOR_BRIGHT_WHITE]; void *font = fb_get_width() / 8 <= FBCON_BIGFONT_THR ? (void *)&_binary_font8x16_psf_start : (void *)&_binary_font16x32_psf_start; fb_set_font(font); fb_map_in_kernel_space(); if (FB_CONSOLE_BANNER) fb_setup_banner(); fb_term_rows = (fb_get_height() - fb_offset_y) / font_h; fb_term_cols = fb_get_width() / font_w; if (!in_panic()) { under_cursor_buf = kalloc_array_obj(u32, font_w * font_h); if (!under_cursor_buf) printk("WARNING: fb_console: unable to allocate under_cursor_buf!\n"); } else { fb_term_cols = MIN(fb_term_cols, FAILSAFE_COLS); fb_term_rows = MIN(fb_term_rows, FAILSAFE_ROWS); } init_first_video_term(&framebuffer_vi, (u16) fb_term_rows, (u16) fb_term_cols, -1); printk_flush_ringbuf(); printk("fb_console: screen resolution: %i x %i x %i bpp\n", fb_get_width(), fb_get_height(), fb_get_bpp()); printk("fb_console: font size: %i x %i, term size: %i x %i\n", font_w, font_h, fb_term_cols, fb_term_rows); fb_use_optimized_funcs_if_possible(); if (in_panic()) return; if (FB_CONSOLE_CURSOR_BLINK) fb_create_cursor_blinking_thread(); if (fb_offset_y) { if (kthread_create(fb_update_banner, 0, NULL) > 0) { /* Success */ if (MOD_acpi) { acpi_reg_on_full_init_cb(&fb_console_on_acpi_full_init_node); } } else { /* Oops! Something went wrong */ printk("WARNING: unable to create the fb_update_banner\n"); } } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/list.h> struct module { const char *name; int priority; void (*init)(void); }; void init_modules(void); void register_module(struct module *m); #define REGISTER_MODULE(m) \ __attribute__((constructor)) \ static void __register_module(void) \ { \ register_module(m); \ } /* Order of initialization of Tilck's modules */ #define MOD_sysfs_prio 10 /* first */ #define MOD_pci_prio 20 #define MOD_acpi_prio 30 #define MOD_kb_prio 50 #define MOD_tracing_prio 100 #define MOD_tty_prio 200 #define MOD_fbdev_prio 300 #define MOD_serial_prio 400 #define MOD_sb16_prio 410 #define MOD_dp_prio 1000 /* last */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <sys/syscall.h> // system header #define TILCK_CMD_SYSCALL 499 enum tilck_cmd { TILCK_CMD_RUN_SELFTEST = 0, TILCK_CMD_GCOV_GET_NUM_FILES = 1, TILCK_CMD_GCOV_FILE_INFO = 2, TILCK_CMD_GCOV_GET_FILE = 3, TILCK_CMD_QEMU_POWEROFF = 4, TILCK_CMD_SET_SAT_ENABLED = 5, TILCK_CMD_DEBUG_PANEL = 6, TILCK_CMD_TRACING_TOOL = 7, TILCK_CMD_PS_TOOL = 8, TILCK_CMD_DEBUGGER_TOOL = 9, /* Number of elements in the enum */ TILCK_CMD_COUNT = 10, }; #if defined(__x86_64__) #define STAT_SYSCALL_N SYS_stat #define LSTAT_SYSCALL_N SYS_lstat #define FSTAT_SYSCALL_N SYS_fstat #define FCNTL_SYSCALL_N SYS_fcntl #define MMAP_SYSCALL_N SYS_mmap #elif defined(__i386__) #define STAT_SYSCALL_N SYS_stat64 #define LSTAT_SYSCALL_N SYS_lstat64 #define FSTAT_SYSCALL_N SYS_fstat64 #define FCNTL_SYSCALL_N SYS_fcntl64 #define MMAP_SYSCALL_N 192 #undef SYS_getuid #undef SYS_getgid #undef SYS_geteuid #undef SYS_getegid #define SYS_getuid 199 #define SYS_getgid 200 #define SYS_geteuid 201 #define SYS_getegid 202 #define SYS_getuid16 24 #define SYS_getgid16 47 #define SYS_geteuid16 49 #define SYS_getegid16 50 #undef SYS_lchown #undef SYS_fchown #undef SYS_chown #define SYS_lchown 198 #define SYS_fchown 207 #define SYS_chown 212 #define SYS_lchown16 16 #define SYS_fchown16 95 #define SYS_chown16 182 #define SYS_llseek 140 #undef SYS_gettimeofday #define SYS_gettimeofday 78 #elif defined(__aarch64__) && (defined(KERNEL_TEST) || defined(TESTING)) /* Allow this just for the unit tests */ #else #error Architecture not supported #endif <file_sep>#!/usr/bin/python3 # SPDX-License-Identifier: BSD-2-Clause import os import sys def help(): print("cmp_build_dirs: a tool for comparing the size all the object files") print("between two builds of the same project") print() print("Syntax:") print(" cmp_build_dirs <build_dir_before> <build_dir_after> " "[exclude subdirs...]") print() def not_a_directory_error(d): print("{} is not a directory".format(d)) def get_object_files_dict(d, ex_dirs): obj_files = {} for folder, subfolders, files in os.walk(d): folder_rel = os.path.relpath(folder, d) skip = False for ex in ex_dirs: if folder_rel.startswith(ex): skip = True break if skip: continue for f in files: fname, fext = os.path.splitext(f) if fext == '.o': path = os.path.join(folder,f) rel_path = os.path.relpath(path, d) obj_files[rel_path] = os.stat(path).st_size return obj_files def main(): if len(sys.argv) < 3: help() return dir1 = sys.argv[1] dir2 = sys.argv[2] ex_dirs = sys.argv[3:] if not os.path.isdir(dir1): not_a_directory_error(dir1) return if not os.path.isdir(dir2): not_a_directory_error(dir2) return before = get_object_files_dict(dir1, ex_dirs) after = get_object_files_dict(dir2, ex_dirs) diffs = {} # file -> [size_before, size_after] for f in before: sz_before = before.get(f, 0) sz_after = after.get(f, 0) if sz_after != sz_before: diffs[f] = [sz_before, sz_after] for f in after: if not f in before: diffs[f] = [0, after[f]] darr = list(diffs.items()) darr.sort(key = lambda p: p[1][1] - p[1][0]) print("Differences for common files (size after vs before)") print("-" * 100) for p in darr: bsz, asz = p[1] if bsz and asz: print("{:<110} {:>10}".format(p[0], asz - bsz)) print() print("Files existing only in the <before> directory: {}".format(dir1)) print("-" * 100) for p in darr: bsz, asz = p[1] if bsz and not asz: print("{:<110} {:>10}".format(p[0], bsz)) print() print("Files existing only in the <after> directory: {}".format(dir2)) print("-" * 100) for p in darr: bsz, asz = p[1] if not bsz and asz: print("{:<110} {:>10}".format(p[0], asz)) if __name__ == '__main__': main() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/sort.h> /* * Insertion sort for pointer-size "objects". */ void insertion_sort_ptr(void *a, u32 elem_count, cmpfun_ptr cmp) { ulong *arr = a; for (u32 i = 1; i < elem_count; i++) { ulong elem = arr[i]; // save the element that has to be placed u32 j; // 'j' is its destination for (j = i; j > 0 && cmp(&arr[j - 1], &elem) > 0; j--) { arr[j] = arr[j-1]; // the first arr[j] was arr[i] = elem. } arr[j] = elem; } } /* * Generic insertion_sort implementation for objects of size 'elem_size'. */ void insertion_sort_generic(void *a, ulong elem_size, u32 elem_count, cmpfun_ptr cmp) { char elem[256]; u32 j; ASSERT(elem_size <= sizeof(elem)); for (u32 i = 1; i < elem_count; i++) { memcpy(&elem, a + i * elem_size, elem_size); /* elem = a[i] */ for (j = i; j > 0 && cmp(a + (j - 1) * elem_size, &elem) > 0; j--) { memcpy(a + j * elem_size, a + (j - 1) * elem_size, elem_size); /* a[j] = a[j-1] */ } memcpy(a + j * elem_size, &elem, elem_size); /* a[j] = elem */ } } /* Reverse an array of pointer-sized elements */ void array_reverse_ptr(void *a, u32 elem_count) { ulong *arr = a; ulong tmp; for (u32 i = 0; i < elem_count / 2; i++) { tmp = arr[i]; arr[i] = arr[elem_count - i - 1]; arr[elem_count - i - 1] = tmp; } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_kernel.h> #include <tilck/common/basic_defs.h> #if KERNEL_UBSAN /* * Struct definitions taken from GCC's source: * libsanitizer/ubsan/ubsan_value.h * libsanitizer/ubsan/ubsan_handlers.h */ struct TypeDescriptor { u16 TypeKind; u16 TypeInfo; char TypeName[]; }; struct SourceLocation { const char *Filename; u32 Line; u32 Column; }; struct TypeMismatchDataV1 { struct SourceLocation Loc; const struct TypeDescriptor *Type; unsigned char LogAlignment; unsigned char TypeCheckKind; }; static void generic_ub_handler(const char *ub_name) { if (in_panic()) return; panic("UBSAN: %s", ub_name); } #define EMIT_GENERIC_UB_HANDLER(name) \ void __ubsan_handle_##name() { generic_ub_handler(#name); } void __ubsan_handle_type_mismatch_v1(struct TypeMismatchDataV1 *d, ulong ptr) { if (in_panic()) return; if (!ptr) { panic("UBSAN: null pointer dereference\nUBSAN: %s:%u:%u", d->Loc.Filename, d->Loc.Line, d->Loc.Column); } else if (d->LogAlignment && (ptr & ((1 << d->LogAlignment) - 1))) { panic("UBSAN: unaligned access ptr: %p alignment: %u\nUBSAN: %s:%u:%u", ptr, 1 << d->LogAlignment, d->Loc.Filename, d->Loc.Line, d->Loc.Column); } else { panic("UBSAN: type_mismatch_v1\nUBSAN: %s:%u:%u", d->Loc.Filename, d->Loc.Line, d->Loc.Column); } } EMIT_GENERIC_UB_HANDLER(divrem_overflow) EMIT_GENERIC_UB_HANDLER(shift_out_of_bounds) EMIT_GENERIC_UB_HANDLER(builtin_unreachable) EMIT_GENERIC_UB_HANDLER(missing_return) EMIT_GENERIC_UB_HANDLER(vla_bound_not_positive) EMIT_GENERIC_UB_HANDLER(type_mismatch) EMIT_GENERIC_UB_HANDLER(type_mismatch_abort) EMIT_GENERIC_UB_HANDLER(add_overflow) EMIT_GENERIC_UB_HANDLER(sub_overflow) EMIT_GENERIC_UB_HANDLER(mul_overflow) EMIT_GENERIC_UB_HANDLER(negate_overflow) EMIT_GENERIC_UB_HANDLER(load_invalid_value) EMIT_GENERIC_UB_HANDLER(divrem_overflow_abort) EMIT_GENERIC_UB_HANDLER(shift_out_of_bounds_abort) EMIT_GENERIC_UB_HANDLER(vla_bound_not_positive_abort) EMIT_GENERIC_UB_HANDLER(add_overflow_abort) EMIT_GENERIC_UB_HANDLER(sub_overflow_abort) EMIT_GENERIC_UB_HANDLER(mul_overflow_abort) EMIT_GENERIC_UB_HANDLER(negate_overflow_abort) EMIT_GENERIC_UB_HANDLER(load_invalid_value_abort) EMIT_GENERIC_UB_HANDLER(float_cast_overflow) EMIT_GENERIC_UB_HANDLER(float_cast_overflow_abort) EMIT_GENERIC_UB_HANDLER(out_of_bounds) EMIT_GENERIC_UB_HANDLER(out_of_bounds_abort) EMIT_GENERIC_UB_HANDLER(nonnull_arg) EMIT_GENERIC_UB_HANDLER(nonnull_arg_abort) EMIT_GENERIC_UB_HANDLER(nonnull_return) EMIT_GENERIC_UB_HANDLER(nonnull_return_abort) EMIT_GENERIC_UB_HANDLER(dynamic_type_cache_miss) EMIT_GENERIC_UB_HANDLER(dynamic_type_cache_miss_abort) #endif // #if KERNEL_UBSAN <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <stdbool.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/utsname.h> #include <pwd.h> #include <libgen.h> #include "devshell.h" bool dump_coverage; char **shell_argv; char **shell_env; static char cmd_arg_buffers[MAX_ARGS][256]; static char *cmd_argv[MAX_ARGS]; static const char *devshell_path[] = { "/bin/", "/usr/bin/" }; static bool contains_slash(const char *s) { for (; *s; s++) { if (*s == '/') return true; } return false; } static void shell_builtin_cd(int argc) { const char *dest_dir = "/"; if (argc == 2 && strlen(cmd_argv[1])) dest_dir = cmd_argv[1]; if (argc > 2) { fprintf(stderr, PFX "cd: too many arguments\n"); return; } if (chdir(dest_dir)) { fprintf(stderr, PFX "cd: can't cd to '%s': %s\n", dest_dir, strerror(errno)); } } static bool is_file(const char *filepath) { struct stat statbuf; if (stat(filepath, &statbuf) < 0) return false; return (statbuf.st_mode & S_IFMT) == S_IFREG; } static void wait_child_cmd(int child_pid) { int wstatus; waitpid(child_pid, &wstatus, 0); if (!WIFEXITED(wstatus)) { int term_sig = WTERMSIG(wstatus); printf("\n"); if (term_sig != SIGINT) printf(PFX "Command terminated by signal: %d (%s)\n", term_sig, strsignal(term_sig)); return; } if (WEXITSTATUS(wstatus)) printf(PFX "Command exited with status: %d\n", WEXITSTATUS(wstatus)); } static void shell_run_child(int argc) { char buf[MAX_PATH]; int saved_errno; int i; run_if_known_command(cmd_argv[0], argc - 1, cmd_argv + 1); /* Since we got here, cmd_argv[0] was NOT a known built-in command */ if (!contains_slash(cmd_argv[0])) { if (argc > MAX_ARGS) { fprintf(stderr, PFX "Too many arguments. Limit: %d\n", MAX_ARGS); exit(1); } for (i = 0; i < ARRAY_SIZE(devshell_path); i++) { strcpy(buf, devshell_path[i]); strcat(buf, cmd_argv[0]); if (is_file(buf)) break; } if (i == ARRAY_SIZE(devshell_path)) { fprintf(stderr, PFX "Command '%s' not found\n", cmd_argv[0]); exit(1); } cmd_argv[0] = buf; } execve(cmd_argv[0], cmd_argv, shell_env); /* if we got here, execve() failed */ saved_errno = errno; perror(cmd_argv[0]); exit(saved_errno); } static int parse_cmd_line(const char *cmd_line) { int argc = 0; char quote_char; char *arg = NULL; bool in_arg = false; bool in_quotes = false; for (const char *p = cmd_line; *p && *p != '\n'; p++) { if (!in_arg) { if (*p == ' ') continue; if (argc == MAX_ARGS) break; in_arg = true; cmd_argv[argc] = cmd_arg_buffers[argc]; arg = cmd_argv[argc]; argc++; } if (!in_quotes) { if (*p == ' ') { in_arg = false; *arg = 0; continue; } if (*p == '\'' || *p == '"') { in_quotes = true; quote_char = *p; continue; } } else { if (*p == quote_char) { in_quotes = false; continue; } } *arg++ = *p; } if (in_arg) *arg = 0; cmd_argv[argc] = NULL; if (in_quotes) { fprintf(stderr, PFX "ERROR: Unterminated quote %c\n", quote_char); return 0; } return argc; } static void process_cmd_line(const char *cmd_line) { int child_pid; int argc = parse_cmd_line(cmd_line); if (!argc || !cmd_argv[0][0]) return; if (!strcmp(cmd_argv[0], "cd")) { shell_builtin_cd(argc); return; } if (!strcmp(cmd_argv[0], "exit")) { exit(0); } if ((child_pid = fork()) < 0) { perror("fork failed"); return; } if (!child_pid) { shell_run_child(argc); } wait_child_cmd(child_pid); } static void show_help_and_exit(void) { show_common_help_intro(); printf(COLOR_RED "Usage:" RESET_ATTRS "\n\n"); printf(" devshell %-15s Just run the interactive shell\n", " "); printf(" devshell %-15s Show this help and exit\n\n", "-h, --help"); printf(" Internal test-infrastructure options\n"); printf(" ------------------------------------\n\n"); printf(" devshell %-15s List the built-in (test) commands\n", "-l"); printf(" devshell %-15s Just dump the kernel coverage data\n\n", "-dcov"); printf(" devshell [-dcov] -c <cmd> [arg1 [arg2 [arg3...]]]\n"); printf("%-28s Run the <cmd> built-in command and exit.\n", " "); printf("%-28s In case -c is preceded by -dcov, the devshell\n", " "); printf("%-28s also dumps the kernel coverage data on-screen.\n", " "); exit(0); } static void parse_opt(int argc, char **argv) { for (; argc > 0; argc--, argv++) { if (!strlen(*argv)) continue; if (!strcmp(*argv, "-h") || !strcmp(*argv, "--help")) show_help_and_exit(); if (!strcmp(*argv, "-l")) dump_list_of_commands_and_exit(); if (!strcmp(*argv, "-dcov")) { if (argc > 1) { dump_coverage = true; continue; } dump_coverage_files(); exit(0); } if (argc == 1) goto unknown_opt; /* argc > 1 */ if (!strcmp(*argv, "-c")) { printf(PFX "Executing built-in command '%s'\n", argv[1]); run_if_known_command(argv[1], argc - 2, argv + 2); printf(PFX "Unknown built-in command '%s'\n", argv[1]); return; } unknown_opt: printf(PFX "Unknown option '%s'\n", *argv); break; } } const char *get_devshell_path(void) { if (!getenv("TILCK")) { /* * When running this test on Linux, we cannot expect to find the devshell * in the same abs path (/initrd/...) as on Tilck. */ return "/proc/self/exe"; } return DEVSHELL_PATH; } static void setup_signals(void) { sigset_t set; int rc; signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); sigemptyset(&set); rc = sigprocmask(SIG_SETMASK, &set, NULL); if (rc) { fprintf(stderr, "devshell: sigprocmask() failed with: %s (%d)\n", strerror(errno), errno); exit(1); } } int main(int argc, char **argv, char **env) { static char cmdline_buf[256]; static char cwd_buf[256]; static struct termios orig_termios; const char *cmdname; char uc = '#'; int rc; setup_signals(); /* Save current term's mode */ tcgetattr(0, &orig_termios); shell_argv = argv; shell_env = env; if (!argc) { fprintf(stderr, PFX "Weird error: argc == 0\n"); return 1; } strncpy(cwd_buf, argv[0], sizeof(cwd_buf) - 1); cmdname = basename(cwd_buf); if (strcmp(cmdname, "devshell")) { printf(PFX "Executing built-in command '%s'\n", cmdname); run_if_known_command(cmdname, argc - 1, argv + 1); printf(PFX "Unknown built-in command '%s'\n", cmdname); return 1; } if (argc > 1) { parse_opt(argc - 1, argv + 1); exit(1); } /* No command specified in the options: run in interactive mode */ if (getuid() != 0) uc = '$'; while (true) { if (getcwd(cwd_buf, sizeof(cwd_buf)) != cwd_buf) { fprintf(stderr, PFX "getcwd() failed: %s", strerror(errno)); return 1; } printf(COLOR_RED "[TilckDevShell]" RESET_ATTRS ":%s%c ", cwd_buf, uc); fflush(stdout); rc = read_command(cmdline_buf, sizeof(cmdline_buf)); if (rc < 0) { fprintf(stderr, PFX "I/O error\n"); break; } if (rc) process_cmd_line(cmdline_buf); /* Restore term's mode, in case the command corrupted it */ tcsetattr(0, TCSAFLUSH, &orig_termios); } return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This file contains functions used by wth.c, but are NOT placed there * in order to allow unit tests to wrap them (with -Wl,--wrap). */ #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/errno.h> #include "wth_int.h" int wth_create_thread_for(struct worker_thread *t) { const int tid = kthread_create(wth_run, KTH_WORKER_THREAD, t); if (tid < 0) return -ENOMEM; t->task = get_task(tid); return 0; } void wth_wakeup(struct worker_thread *t) { struct task *curr = get_curr_task(); enum task_state exp_state = TASK_STATE_SLEEPING; t->waiting_for_jobs = false; atomic_cas_strong(&t->task->state, &exp_state, TASK_STATE_RUNNABLE, mo_relaxed, mo_relaxed); /* * Note: we don't care whether atomic_cas_strong() succeeded or not. * Reason: if it didn't succeed, that's because an IRQ preempted us * and made its state to be runnable. */ struct worker_thread *curr_tt = curr->worker_thread; if (!curr_tt || t->priority < curr_tt->priority) sched_set_need_resched(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/signal.h> #include <tilck/kernel/process.h> static bool tty_ctrl_stop(struct tty *t, bool block) { if (t->c_term.c_iflag & IXON) { // TODO: eventually support pause transmission, one day. return true; } return false; } static bool tty_ctrl_start(struct tty *t, bool block) { if (t->c_term.c_iflag & IXON) { // TODO: eventually support pause transmission, one day. return true; } return false; } static bool tty_ctrl_intr(struct tty *t, bool block) { if (t->c_term.c_lflag & ISIG) { tty_keypress_echo(t, (char)t->c_term.c_cc[VINTR]); tty_inbuf_reset(t); send_signal_to_group(t->fg_pgid, SIGINT); return true; } return false; } static bool tty_ctrl_susp(struct tty *t, bool block) { if (t->c_term.c_lflag & ISIG) { tty_keypress_echo(t, (char)t->c_term.c_cc[VSUSP]); if (!t->serial_port_fwd) printk("SUSP not supported yet\n"); return true; } return false; } static bool tty_ctrl_quit(struct tty *t, bool block) { if (t->c_term.c_lflag & ISIG) { tty_keypress_echo(t, (char)t->c_term.c_cc[VQUIT]); tty_inbuf_reset(t); send_signal_to_group(t->fg_pgid, SIGQUIT); return true; } return false; } static bool tty_ctrl_eof(struct tty *t, bool block) { if (t->c_term.c_lflag & ICANON) { t->end_line_delim_count++; tty_inbuf_write_elem(t, t->c_term.c_cc[VEOF], block); kcond_signal_one(&t->input_cond); return true; } return false; } static bool tty_ctrl_eol(struct tty *t, bool block) { if (t->c_term.c_lflag & ICANON) { t->end_line_delim_count++; tty_inbuf_write_elem(t, t->c_term.c_cc[VEOL], block); kcond_signal_one(&t->input_cond); return true; } return false; } static bool tty_ctrl_eol2(struct tty *t, bool block) { if (t->c_term.c_lflag & ICANON) { t->end_line_delim_count++; tty_inbuf_write_elem(t, t->c_term.c_cc[VEOL2], block); kcond_signal_one(&t->input_cond); return true; } return false; } static bool tty_ctrl_reprint(struct tty *t, bool block) { if (t->c_term.c_lflag & (ICANON | IEXTEN)) { tty_keypress_echo(t, (char)t->c_term.c_cc[VREPRINT]); if (!t->serial_port_fwd) printk("REPRINT not supported yet\n"); return true; } return false; } static bool tty_ctrl_discard(struct tty *t, bool block) { /* * From termios' man page: * VDISCARD * (not in POSIX; not supported under Linux; 017, SI, Ctrl-O) * Toggle: start/stop discarding pending output. Recognized when * IEXTEN is set, and then not passed as input. * * Since it is not supported under Linux, it won't be supported under * Tilck either. */ return false; } static bool tty_ctrl_lnext(struct tty *t, bool block) { if (t->c_term.c_lflag & IEXTEN) { if (!t->serial_port_fwd) printk("LNEXT not supported yet\n"); return true; } return false; } static void tty_set_ctrl_handler(struct tty *t, u8 ctrl_type, tty_ctrl_sig_func h) { u8 c = t->c_term.c_cc[ctrl_type]; if (!c) { /* * The character #num associated with the control char 'ctrl_type' is 0: * this means that the user doesn't what the terminal to support that * specific control character at all. We cannot associate any handler with * it. */ return; } t->ctrl_handlers[c] = h; } static inline bool tty_handle_special_controls(struct tty *t, u8 c, bool block) { tty_ctrl_sig_func handler = t->ctrl_handlers[c]; if (handler) return handler(t, block); return false; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ struct vfs_getdents_ctx { struct fs_handle_base *h; struct linux_dirent64 *user_dirp; u32 buf_size; u32 offset; u32 fs_flags; offt off; struct linux_dirent64 ent; }; static inline unsigned char vfs_type_to_linux_dirent_type(enum vfs_entry_type t) { static const unsigned char table[] = { [VFS_NONE] = DT_UNKNOWN, [VFS_FILE] = DT_REG, [VFS_DIR] = DT_DIR, [VFS_SYMLINK] = DT_LNK, [VFS_CHAR_DEV] = DT_CHR, [VFS_BLOCK_DEV] = DT_BLK, [VFS_PIPE] = DT_FIFO, }; ASSERT(t != VFS_NONE); return table[t]; } static int vfs_getdents_cb(struct vfs_dent64 *vde, void *arg) { const u16 entry_size = sizeof(struct linux_dirent64) + vde->name_len; struct linux_dirent64 *user_ent; struct vfs_getdents_ctx *ctx = arg; char *user_ent_dname; if (ctx->fs_flags & VFS_FS_RQ_DE_SKIP) { /* * Pseudo-hack used fortunately *only* by the FAT32 struct mnt_fs: it * implements here in the VFS layer a trivial mechanism to skip the first * `pos` entries of a directory in case the struct mnt_fs does not have a * way to just "save" the current position and resume from there in each * call of the mnt_fs-op getdents(). * * TODO: implement in FAT32 a way to walk a directory step-by-step, * instead of having to walk all the entries every time and skipping the * already "returned" entries. This way we could drop VFS_FS_RQ_DE_SKIP. */ if (ctx->off < ctx->h->dir_pos) { ctx->off++; return 0; /* skip the dentry */ } } if (ctx->offset + entry_size > ctx->buf_size) { if (!ctx->offset) { /* * We haven't "returned" any entries yet and the buffer is too small * for our first entry. */ return -EINVAL; } /* We "returned" at least one entry */ return (int) ctx->offset; } ctx->ent.d_ino = vde->ino; ctx->ent.d_off = (u64) ctx->off + 1; /* "offset" (=ID) of the next dent */ ctx->ent.d_reclen = entry_size; ctx->ent.d_type = vfs_type_to_linux_dirent_type(vde->type); user_ent = (void *)((char *)ctx->user_dirp + ctx->offset); user_ent_dname = (char *)user_ent + OFFSET_OF(struct linux_dirent64, d_name); if (copy_to_user(user_ent, &ctx->ent, sizeof(ctx->ent)) < 0) return -EFAULT; if (copy_to_user(user_ent_dname, vde->name, vde->name_len) < 0) return -EFAULT; ctx->offset += entry_size; ctx->off++; ctx->h->dir_pos++; return 0; } int vfs_getdents64(fs_handle h, struct linux_dirent64 *user_dirp, u32 buf_size) { NO_TEST_ASSERT(is_preemption_enabled()); struct fs_handle_base *hb = (struct fs_handle_base *) h; int rc; ASSERT(hb != NULL); ASSERT(hb->fs->fsops->getdents); struct vfs_getdents_ctx ctx = { .h = hb, .user_dirp = user_dirp, .buf_size = buf_size, .offset = 0, .fs_flags = hb->fs->flags, .off = hb->fs->flags & VFS_FS_RQ_DE_SKIP ? 0 : ctx.h->dir_pos, .ent = { 0 }, }; /* See the comment in vfs.h about the "fs-locks" */ vfs_fs_shlock(hb->fs); { rc = hb->fs->fsops->getdents(hb, &vfs_getdents_cb, &ctx); if (!rc) rc = (int) ctx.offset; } vfs_fs_shunlock(hb->fs); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_userlim.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/user.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/timer.h> struct select_ctx { int nfds; fd_set *sets[3]; fd_set *u_sets[3]; struct k_timeval *tv; struct k_timeval *user_tv; int cond_cnt; u32 timeout_ticks; }; static const func_get_rwe_cond gcf[3] = { &vfs_get_rready_cond, &vfs_get_wready_cond, &vfs_get_except_cond }; static const func_rwe_ready grf[3] = { &vfs_read_ready, &vfs_write_ready, &vfs_except_ready, }; static int select_count_cond_per_set(struct select_ctx *c, fd_set *set, func_get_rwe_cond gcfunc) { if (!set) return 0; for (int i = 0; i < c->nfds; i++) { if (!FD_ISSET(i, set)) continue; fs_handle h = get_fs_handle(i); if (!h) return -EBADF; if (gcfunc(h)) c->cond_cnt++; } return 0; } static int select_set_kcond(int nfds, struct multi_obj_waiter *w, int *idx, fd_set *set, func_get_rwe_cond get_cond) { fs_handle h; struct kcond *c; if (!set) return 0; for (int i = 0; i < nfds; i++) { if (!FD_ISSET(i, set)) continue; if (!(h = get_fs_handle(i))) return -EBADF; c = get_cond(h); if (c) { ASSERT((*idx) < w->count); mobj_waiter_set(w, (*idx)++, WOBJ_KCOND, c, &c->wait_list); } } return 0; } static int select_set_ready(int nfds, fd_set *set, func_rwe_ready is_ready) { int tot = 0; if (!set) return tot; for (int i = 0; i < nfds; i++) { if (!FD_ISSET(i, set)) continue; fs_handle h = get_fs_handle(i); if (!h || !is_ready(h)) { FD_CLR(i, set); } else { tot++; } } return tot; } static int count_ready_streams_per_set(int nfds, fd_set *set, func_rwe_ready is_ready) { int count = 0; if (!set) return count; for (int j = 0; j < nfds; j++) { if (!FD_ISSET(j, set)) continue; fs_handle h = get_fs_handle(j); if (h && is_ready(h)) count++; } return count; } static int count_ready_streams(int nfds, fd_set *sets[3]) { int count = 0; for (int i = 0; i < 3; i++) { count += count_ready_streams_per_set(nfds, sets[i], grf[i]); } return count; } static int select_wait_on_cond(struct select_ctx *c) { struct task *curr = get_curr_task(); struct multi_obj_waiter *waiter = NULL; int idx = 0; int rc = 0; if (!(waiter = allocate_mobj_waiter(c->cond_cnt))) return -ENOMEM; for (int i = 0; i < 3; i++) { if ((rc = select_set_kcond(c->nfds, waiter, &idx, c->sets[i], gcf[i]))) goto out; } if (c->tv) { ASSERT(c->timeout_ticks > 0); task_set_wakeup_timer(curr, c->timeout_ticks); } while (true) { disable_preemption(); prepare_to_wait_on_multi_obj(waiter); enter_sleep_wait_state(); if (pending_signals()) break; if (c->tv) { if (curr->wobj.type) { /* we woke-up because of the timeout */ wait_obj_reset(&curr->wobj); c->tv->tv_sec = 0; c->tv->tv_usec = 0; } else { /* * We woke-up because of a kcond was signaled, but that does NOT * mean that even the signaled conditions correspond to ready * streams. We have to check that. */ if (!count_ready_streams(c->nfds, c->sets)) continue; /* No ready streams, we have to wait again. */ u32 rem = task_cancel_wakeup_timer(curr); c->tv->tv_sec = rem / TIMER_HZ; c->tv->tv_usec = (rem % TIMER_HZ) * (1000000 / TIMER_HZ); } } else { /* No timeout: we woke-up because of a kcond was signaled */ if (!count_ready_streams(c->nfds, c->sets)) continue; /* No ready streams, we have to wait again. */ } /* count_ready_streams() returned > 0 */ break; } out: free_mobj_waiter(waiter); if (pending_signals()) return -EINTR; return rc; } static int select_read_user_sets(fd_set *sets[3], fd_set *u_sets[3]) { struct task *curr = get_curr_task(); for (int i = 0; i < 3; i++) { if (!u_sets[i]) continue; sets[i] = ((fd_set*) curr->args_copybuf) + i; if (copy_from_user(sets[i], u_sets[i], sizeof(fd_set))) return -EFAULT; } return 0; } static int select_read_user_tv(struct k_timeval *user_tv, struct k_timeval **tv_ref, u32 *timeout) { struct task *curr = get_curr_task(); struct k_timeval *tv = NULL; if (user_tv) { tv = (void *) ((fd_set *)curr->args_copybuf + 3); if (copy_from_user(tv, user_tv, sizeof(struct k_timeval))) return -EFAULT; u64 tmp = 0; tmp += (u64)tv->tv_sec * TIMER_HZ; tmp += (u64)tv->tv_usec / (1000000 / TIMER_HZ); /* NOTE: select() can't sleep for more than UINT32_MAX ticks */ *timeout = (u32) CLAMP(tmp, 1u, UINT32_MAX); } *tv_ref = tv; return 0; } static int select_compute_cond_cnt(struct select_ctx *c) { int rc; if (!c->tv || c->timeout_ticks > 0) { for (int i = 0; i < 3; i++) { if ((rc = select_count_cond_per_set(c, c->sets[i], gcf[i]))) return rc; } } return 0; } static int select_write_user_sets(struct select_ctx *c) { fd_set **sets = c->sets; fd_set **u_sets = c->u_sets; int total_ready_count = 0; for (int i = 0; i < 3; i++) { total_ready_count += select_set_ready(c->nfds, sets[i], grf[i]); if (u_sets[i] && copy_to_user(u_sets[i], sets[i], sizeof(fd_set))) return -EFAULT; } if (c->tv && copy_to_user(c->user_tv, c->tv, sizeof(struct k_timeval))) return -EFAULT; return total_ready_count; } int sys_select(int user_nfds, fd_set *user_rfds, fd_set *user_wfds, fd_set *user_efds, struct k_timeval *user_tv) { struct select_ctx ctx = (struct select_ctx) { .nfds = user_nfds, .sets = { 0 }, .u_sets = { user_rfds, user_wfds, user_efds }, .tv = NULL, .user_tv = user_tv, .cond_cnt = 0, .timeout_ticks = 0, }; int rc; if (user_nfds < 0 || user_nfds > MAX_HANDLES) return -EINVAL; if ((rc = select_read_user_sets(ctx.sets, ctx.u_sets))) return rc; if ((rc = select_read_user_tv(user_tv, &ctx.tv, &ctx.timeout_ticks))) return rc; if ((rc = count_ready_streams(ctx.nfds, ctx.sets)) > 0) return select_write_user_sets(&ctx); if ((rc = select_compute_cond_cnt(&ctx))) return rc; if (ctx.cond_cnt > 0 && (!user_tv || ctx.timeout_ticks > 0)) { /* * The count of condition variables for all the file descriptors is * greater than 0. That's typical. */ if ((rc = select_wait_on_cond(&ctx))) return rc; } else { /* * It is not that difficult cond_cnt to be 0: it's enough the specified * files to NOT have r/w/e get kcond functions. Also, all the sets might * be NULL (see the comment below). */ if (ctx.timeout_ticks > 0) { /* * Corner case: no conditions on which to wait, but timeout is > 0: * this is still a valid case. Many years ago the following call: * select(0, NULL, NULL, NULL, &tv) * was even used as a portable implementation of nanosleep(). */ kernel_sleep(ctx.timeout_ticks); if (pending_signals()) return -EINTR; } } return select_write_user_sets(&ctx); } <file_sep>#!/bin/sh exec ranlib "$@" <file_sep>/****************************************************************************** * * Module Name: exconcat - Concatenate-type AML operators * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "amlresrc.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exconcat") /* Local Prototypes */ static ACPI_STATUS AcpiExConvertToObjectTypeString ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc); /******************************************************************************* * * FUNCTION: AcpiExDoConcatenate * * PARAMETERS: Operand0 - First source object * Operand1 - Second source object * ActualReturnDesc - Where to place the return object * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Concatenate two objects with the ACPI-defined conversion * rules as necessary. * NOTE: * Per the ACPI spec (up to 6.1), Concatenate only supports Integer, * String, and Buffer objects. However, we support all objects here * as an extension. This improves the usefulness of both Concatenate * and the Printf/Fprintf macros. The extension returns a string * describing the object type for the other objects. * 02/2016. * ******************************************************************************/ ACPI_STATUS AcpiExDoConcatenate ( ACPI_OPERAND_OBJECT *Operand0, ACPI_OPERAND_OBJECT *Operand1, ACPI_OPERAND_OBJECT **ActualReturnDesc, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *LocalOperand0 = Operand0; ACPI_OPERAND_OBJECT *LocalOperand1 = Operand1; ACPI_OPERAND_OBJECT *TempOperand1 = NULL; ACPI_OPERAND_OBJECT *ReturnDesc; char *Buffer; ACPI_OBJECT_TYPE Operand0Type; ACPI_OBJECT_TYPE Operand1Type; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (ExDoConcatenate); /* Operand 0 preprocessing */ switch (Operand0->Common.Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: Operand0Type = Operand0->Common.Type; break; default: /* For all other types, get the "object type" string */ Status = AcpiExConvertToObjectTypeString ( Operand0, &LocalOperand0); if (ACPI_FAILURE (Status)) { goto Cleanup; } Operand0Type = ACPI_TYPE_STRING; break; } /* Operand 1 preprocessing */ switch (Operand1->Common.Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: Operand1Type = Operand1->Common.Type; break; default: /* For all other types, get the "object type" string */ Status = AcpiExConvertToObjectTypeString ( Operand1, &LocalOperand1); if (ACPI_FAILURE (Status)) { goto Cleanup; } Operand1Type = ACPI_TYPE_STRING; break; } /* * Convert the second operand if necessary. The first operand (0) * determines the type of the second operand (1) (See the Data Types * section of the ACPI specification). Both object types are * guaranteed to be either Integer/String/Buffer by the operand * resolution mechanism. */ switch (Operand0Type) { case ACPI_TYPE_INTEGER: Status = AcpiExConvertToInteger (LocalOperand1, &TempOperand1, ACPI_IMPLICIT_CONVERSION); break; case ACPI_TYPE_BUFFER: Status = AcpiExConvertToBuffer (LocalOperand1, &TempOperand1); break; case ACPI_TYPE_STRING: switch (Operand1Type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: /* Other types have already been converted to string */ Status = AcpiExConvertToString ( LocalOperand1, &TempOperand1, ACPI_IMPLICIT_CONVERT_HEX); break; default: Status = AE_OK; break; } break; default: ACPI_ERROR ((AE_INFO, "Invalid object type: 0x%X", Operand0->Common.Type)); Status = AE_AML_INTERNAL; } if (ACPI_FAILURE (Status)) { goto Cleanup; } /* Take care with any newly created operand objects */ if ((LocalOperand1 != Operand1) && (LocalOperand1 != TempOperand1)) { AcpiUtRemoveReference (LocalOperand1); } LocalOperand1 = TempOperand1; /* * Both operands are now known to be the same object type * (Both are Integer, String, or Buffer), and we can now perform * the concatenation. * * There are three cases to handle, as per the ACPI spec: * * 1) Two Integers concatenated to produce a new Buffer * 2) Two Strings concatenated to produce a new String * 3) Two Buffers concatenated to produce a new Buffer */ switch (Operand0Type) { case ACPI_TYPE_INTEGER: /* Result of two Integers is a Buffer */ /* Need enough buffer space for two integers */ ReturnDesc = AcpiUtCreateBufferObject ( (ACPI_SIZE) ACPI_MUL_2 (AcpiGbl_IntegerByteWidth)); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } Buffer = (char *) ReturnDesc->Buffer.Pointer; /* Copy the first integer, LSB first */ memcpy (Buffer, &Operand0->Integer.Value, AcpiGbl_IntegerByteWidth); /* Copy the second integer (LSB first) after the first */ memcpy (Buffer + AcpiGbl_IntegerByteWidth, &LocalOperand1->Integer.Value, AcpiGbl_IntegerByteWidth); break; case ACPI_TYPE_STRING: /* Result of two Strings is a String */ ReturnDesc = AcpiUtCreateStringObject ( ((ACPI_SIZE) LocalOperand0->String.Length + LocalOperand1->String.Length)); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } Buffer = ReturnDesc->String.Pointer; /* Concatenate the strings */ strcpy (Buffer, LocalOperand0->String.Pointer); strcat (Buffer, LocalOperand1->String.Pointer); break; case ACPI_TYPE_BUFFER: /* Result of two Buffers is a Buffer */ ReturnDesc = AcpiUtCreateBufferObject ( ((ACPI_SIZE) Operand0->Buffer.Length + LocalOperand1->Buffer.Length)); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } Buffer = (char *) ReturnDesc->Buffer.Pointer; /* Concatenate the buffers */ memcpy (Buffer, Operand0->Buffer.Pointer, Operand0->Buffer.Length); memcpy (Buffer + Operand0->Buffer.Length, LocalOperand1->Buffer.Pointer, LocalOperand1->Buffer.Length); break; default: /* Invalid object type, should not happen here */ ACPI_ERROR ((AE_INFO, "Invalid object type: 0x%X", Operand0->Common.Type)); Status = AE_AML_INTERNAL; goto Cleanup; } *ActualReturnDesc = ReturnDesc; Cleanup: if (LocalOperand0 != Operand0) { AcpiUtRemoveReference (LocalOperand0); } if (LocalOperand1 != Operand1) { AcpiUtRemoveReference (LocalOperand1); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExConvertToObjectTypeString * * PARAMETERS: ObjDesc - Object to be converted * ReturnDesc - Where to place the return object * * RETURN: Status * * DESCRIPTION: Convert an object of arbitrary type to a string object that * contains the namestring for the object. Used for the * concatenate operator. * ******************************************************************************/ static ACPI_STATUS AcpiExConvertToObjectTypeString ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT **ResultDesc) { ACPI_OPERAND_OBJECT *ReturnDesc; const char *TypeString; TypeString = AcpiUtGetTypeName (ObjDesc->Common.Type); ReturnDesc = AcpiUtCreateStringObject ( ((ACPI_SIZE) strlen (TypeString) + 9)); /* 9 For "[ Object]" */ if (!ReturnDesc) { return (AE_NO_MEMORY); } strcpy (ReturnDesc->String.Pointer, "["); strcat (ReturnDesc->String.Pointer, TypeString); strcat (ReturnDesc->String.Pointer, " Object]"); *ResultDesc = ReturnDesc; return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExConcatTemplate * * PARAMETERS: Operand0 - First source object * Operand1 - Second source object * ActualReturnDesc - Where to place the return object * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Concatenate two resource templates * ******************************************************************************/ ACPI_STATUS AcpiExConcatTemplate ( ACPI_OPERAND_OBJECT *Operand0, ACPI_OPERAND_OBJECT *Operand1, ACPI_OPERAND_OBJECT **ActualReturnDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ReturnDesc; UINT8 *NewBuf; UINT8 *EndTag; ACPI_SIZE Length0; ACPI_SIZE Length1; ACPI_SIZE NewLength; ACPI_FUNCTION_TRACE (ExConcatTemplate); /* * Find the EndTag descriptor in each resource template. * Note1: returned pointers point TO the EndTag, not past it. * Note2: zero-length buffers are allowed; treated like one EndTag */ /* Get the length of the first resource template */ Status = AcpiUtGetResourceEndTag (Operand0, &EndTag); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Length0 = ACPI_PTR_DIFF (EndTag, Operand0->Buffer.Pointer); /* Get the length of the second resource template */ Status = AcpiUtGetResourceEndTag (Operand1, &EndTag); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Length1 = ACPI_PTR_DIFF (EndTag, Operand1->Buffer.Pointer); /* Combine both lengths, minimum size will be 2 for EndTag */ NewLength = Length0 + Length1 + sizeof (AML_RESOURCE_END_TAG); /* Create a new buffer object for the result (with one EndTag) */ ReturnDesc = AcpiUtCreateBufferObject (NewLength); if (!ReturnDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* * Copy the templates to the new buffer, 0 first, then 1 follows. One * EndTag descriptor is copied from Operand1. */ NewBuf = ReturnDesc->Buffer.Pointer; memcpy (NewBuf, Operand0->Buffer.Pointer, Length0); memcpy (NewBuf + Length0, Operand1->Buffer.Pointer, Length1); /* Insert EndTag and set the checksum to zero, means "ignore checksum" */ NewBuf[NewLength - 1] = 0; NewBuf[NewLength - 2] = ACPI_RESOURCE_NAME_END_TAG | 1; /* Return the completed resource template */ *ActualReturnDesc = ReturnDesc; return_ACPI_STATUS (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include "devshell.h" #include "test_common.h" static void pipe_cmd1_child(int rfd, int wfd) { char buf[64]; int rc; printf(STR_CHILD "read from pipe...\n"); rc = read(rfd, buf, sizeof(buf)); if (rc < 0) { printf(STR_CHILD "read returned %d, error: %s\n", rc, strerror(errno)); exit(1); } buf[rc] = 0; printf(STR_CHILD "got: '%s'\n", buf); printf(STR_CHILD "Done.\n"); exit(0); } /* Basic pipe read/write test between parent and child process */ int cmd_pipe1(int argc, char **argv) { char buf[64]; int rfd, wfd; int wstatus; int rc; pid_t childpid; printf(STR_PARENT "Creating the pipe..\n"); { int pipefd[2]; rc = pipe(pipefd); if (rc < 0) { printf(STR_PARENT "pipe() failed. Error: %s\n", strerror(errno)); return 1; } rfd = pipefd[0]; wfd = pipefd[1]; } printf(STR_PARENT "Doing fork()..\n"); childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) pipe_cmd1_child(rfd, wfd); printf(STR_PARENT "Wait 100 ms\n"); usleep(100 * 1000); printf(STR_PARENT "Writing 'hello' to the pipe..\n"); strcpy(buf, "hello"); rc = write(wfd, buf, strlen(buf)); if (rc < 0) { printf(STR_PARENT "write() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "Done.\n"); rc = waitpid(childpid, &wstatus, 0); if (rc < 0) { printf(STR_PARENT "waitpid() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "Child done.\n"); return 0; } static void pipe_cmd2_child(int rfd, int wfd) { char buf[64] = "whatever"; int rc; printf(STR_CHILD "close the read side of the pipe\n"); close(rfd); printf(STR_CHILD "write to pipe, expecting SIGPIPE\n"); errno = 0; rc = write(wfd, buf, sizeof(buf)); printf(STR_CHILD "write returned %d (%s)\n", rc, strerror(errno)); printf(STR_CHILD "while we expected to die\n"); exit(1); } /* Test the broken pipe case */ int cmd_pipe2(int argc, char **argv) { int code, term_sig; int rfd, wfd; int wstatus; int rc; pid_t childpid; printf(STR_PARENT "Creating the pipe..\n"); { int pipefd[2]; rc = pipe(pipefd); if (rc < 0) { printf(STR_PARENT "pipe() failed. Error: %s\n", strerror(errno)); return 1; } rfd = pipefd[0]; wfd = pipefd[1]; } printf(STR_PARENT "Close the read side of the pipe\n"); close(rfd); printf(STR_PARENT "Doing fork()..\n"); childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) pipe_cmd2_child(rfd, wfd); printf(STR_PARENT "Done.\n"); rc = waitpid(childpid, &wstatus, 0); if (rc < 0) { printf(STR_PARENT "waitpid() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "Child done.\n"); code = WEXITSTATUS(wstatus); term_sig = WTERMSIG(wstatus); if (term_sig != SIGPIPE) { printf(STR_PARENT "The child didn't die with SIGPIPE as expected\n"); printf(STR_PARENT "exit code: %d, term_sig: %d\n", code, term_sig); return 1; } printf(STR_PARENT "The child died with SIGPIPE, as expected\n"); return 0; } static void pipe_cmd3_child(void *unused_arg) { int pipefd[2]; int rc; printf("Ignore SIGPIPE..\n"); signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE */ printf("Calling pipe()\n"); rc = pipe(pipefd); if (rc < 0) { printf("pipe() failed. Error: %s\n", strerror(errno)); exit(1); } printf("Close the read side of the pipe...\n"); close(pipefd[0]); printf("Trying to write something..\n"); rc = write(pipefd[1], &rc, sizeof(rc)); if (rc >= 0) { printf("write() succeeded returning %d instead of failing\n", rc); exit(1); } if (errno != EPIPE) { printf("write() failed with %s instead of with EPIPE\n", strerror(errno)); exit(1); } printf("write() failed with EPIPE, as expected\n"); exit(0); } /* Test the broken pipe case with SIGPIPE ignored */ int cmd_pipe3(int argc, char **argv) { int rc; printf("Try the broken pipe case with SIGPIPE ignored...\n"); rc = test_sig(&pipe_cmd3_child, NULL, 0, 0, 0); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } /* Test pipes with O_NONBLOCK */ int cmd_pipe4(int argc, char **argv) { char buf[64]; int pipefd[2]; int rc; int tot; printf("Calling pipe()\n"); rc = pipe(pipefd); if (rc < 0) { printf("pipe() failed. Error: %s\n", strerror(errno)); return 1; } printf("Set the read fd in NONBLOCK mode\n"); rc = fcntl(pipefd[0], F_GETFL); if (rc < 0) { printf("fcntl(pipefd[0], F_GETFL) failed: %s\n", strerror(errno)); return 1; } rc = fcntl(pipefd[0], F_SETFL, rc | O_NONBLOCK); if (rc < 0) { printf("fcntl(pipefd[0], F_SETFL) failed: %s\n", strerror(errno)); return 1; } printf("read() expecting to get EAGAIN\n"); rc = read(pipefd[0], buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc == -1); DEVSHELL_CMD_ASSERT(errno == EAGAIN); printf("write() hello\n"); rc = write(pipefd[1], "hello", 5); DEVSHELL_CMD_ASSERT(rc == 5); printf("read() expecting to get 'hello'\n"); rc = read(pipefd[0], buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc == 5); buf[rc] = 0; DEVSHELL_CMD_ASSERT(!strcmp(buf, "hello")); printf("Set the write fd in NONBLOCK mode\n"); rc = fcntl(pipefd[1], F_GETFL); if (rc < 0) { printf("fcntl(pipefd[0], F_GETFL) failed: %s\n", strerror(errno)); return 1; } rc = fcntl(pipefd[1], F_SETFL, rc | O_NONBLOCK); if (rc < 0) { printf("fcntl(pipefd[0], F_SETFL) failed: %s\n", strerror(errno)); return 1; } printf("write until EAGAIN is hit\n"); for (tot = 0; ; tot++) { rc = write(pipefd[1], buf, 1); if (rc < 0) break; } rc = errno; printf("write() failed [expected] with: %s\n", strerror(rc)); printf("bytes written: %d\n", tot); DEVSHELL_CMD_ASSERT(rc == EAGAIN); printf("Done.\n"); close(pipefd[0]); close(pipefd[1]); return 0; } static void pipe_reader_child(int id, int fd) { int tot_read = 0; char buf[4096]; int rc; int fail = 0; int to_read; while (true) { to_read = rand() % sizeof(buf) + 1; rc = read(fd, buf, to_read); if (rc < 0) { printf("[reader %d]: read(%d) failed with %s\n", id, to_read, strerror(errno)); fail = 1; break; } if (rc == 0) break; tot_read += rc; } printf("[reader %d]: tot_read: %d (%d KB)\n", id, tot_read, tot_read / KB); exit(fail); } static void pipe_writer_child(int id, int fd, int write_lim) { int tot_written = 0; char buf[4096]; int rc; int fail = 0; int to_write = 0; while (tot_written < write_lim) { to_write = rand() % sizeof(buf) + 1; if (tot_written + to_write > write_lim) { /* Make sure to write no more than `write_lim` */ to_write = write_lim - tot_written; } rc = write(fd, buf, to_write); if (rc < 0) { printf("[writer %d]: write(%d) failed with %s\n", id, to_write, strerror(errno)); fail = 1; break; } tot_written += rc; } printf("[writer %d]: tot_written: %d (%d KB)\n", id, tot_written, tot_written / KB); close(fd); exit(fail); } static int pipe_random_test(int readers, int writers) { int pipefd[2]; int wstatus; int rc; int fail = 0; printf("[Pipe random test] readers: %d, writers: %d\n", readers, writers); rc = pipe(pipefd); if (rc < 0) { printf("pipe() failed. Error: %s\n", strerror(errno)); return 1; } if (!getenv("TILCK")) { fcntl(pipefd[0], F_SETPIPE_SZ, 4096); fcntl(pipefd[1], F_SETPIPE_SZ, 4096); } for (int i = 0; i < writers; i++) { rc = fork(); if (rc < 0) { printf("[Pipe random test] fork failed with %s\n", strerror(errno)); fail = 1; break; } if (!rc) { close(pipefd[0]); pipe_writer_child(i, pipefd[1], readers * 32 * KB); } } for (int i = 0; i < readers; i++) { rc = fork(); if (rc < 0) { printf("[Pipe random test] fork failed with %s\n", strerror(errno)); fail = 1; break; } if (!rc) { close(pipefd[1]); pipe_reader_child(i, pipefd[0]); } } close(pipefd[0]); close(pipefd[1]); printf("[Pipe random test] wait for children\n"); do { rc = waitpid(-1, &wstatus, 0); if (rc > 0) { int code = WEXITSTATUS(wstatus); int term_sig = WTERMSIG(wstatus); if (code || term_sig) { printf("[Pipe random test] child %d failed, " "code: %d, sig: %d\n", rc, code, term_sig); fail = 1; } } } while (rc > 0); printf("[Pipe random test] done\n"); return fail; } int cmd_pipe5(int argc, char **argv) { int rc; if ((rc = pipe_random_test(10, 1))) return rc; if ((rc = pipe_random_test(1, 10))) return rc; if ((rc = pipe_random_test(5, 5))) return rc; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/process_mm.h> #include <tilck/kernel/process.h> #include <tilck/kernel/paging_hw.h> struct user_mapping * process_add_user_mapping(fs_handle h, void *vaddr, size_t len, size_t off, int prot) { struct process *pi = get_curr_proc(); struct user_mapping *um; ASSERT((len & OFFSET_IN_PAGE_MASK) == 0); ASSERT(!is_preemption_enabled()); ASSERT(!process_get_user_mapping(vaddr)); ASSERT(pi->mi); if (!(um = kzalloc_obj(struct user_mapping))) return NULL; list_node_init(&um->pi_node); list_node_init(&um->inode_node); um->pi = pi; um->h = h; um->len = len; um->vaddrp = vaddr; um->off = off; um->prot = prot; list_add_tail(&pi->mi->mappings, &um->pi_node); return um; } void process_remove_user_mapping(struct user_mapping *um) { ASSERT(!is_preemption_enabled()); list_remove(&um->pi_node); list_remove(&um->inode_node); kfree_obj(um, struct user_mapping); } struct user_mapping *process_get_user_mapping(void *vaddrp) { const ulong vaddr = (ulong)vaddrp; struct process *pi = get_curr_proc(); struct user_mapping *pos; ASSERT(!is_preemption_enabled()); if (pi->mi) { /* * Given that pi->mi->mappings contains at the moment only the memory * mappings done with mmap(), some small processes that don't use dynamic * memory allocation will not even have this field (pi->mi == NULL). * * For the rest, the list is supposed to be *short*, so a linear scan * is acceptable for the moment. If in the future we start to put * there also the mappings for program's text and data and expect to have * more than a few elements, it will be necessary to use a BST to perform * the lookup here below. */ list_for_each_ro(pos, &pi->mi->mappings, pi_node) { if (IN_RANGE(vaddr, pos->vaddr, pos->vaddr + pos->len)) return pos; } } return NULL; } void remove_all_user_zero_mem_mappings(struct process *pi) { struct user_mapping *um; struct list *mappings_list_p; ASSERT(!is_preemption_enabled()); if (!pi->mi) return; mappings_list_p = &pi->mi->mappings; list_for_each_ro(um, mappings_list_p, pi_node) { if (!um->h) full_remove_user_mapping(pi, um); } ASSERT(list_is_empty(mappings_list_p)); } void remove_all_mappings_of_handle(struct process *pi, fs_handle h) { struct user_mapping *pos, *temp; struct mappings_info *mi = pi->mi; if (!mi) return; disable_preemption(); { list_for_each(pos, temp, &mi->mappings, pi_node) { if (pos->h == h) full_remove_user_mapping(pi, pos); } } enable_preemption(); } void full_remove_user_mapping(struct process *pi, struct user_mapping *um) { struct mappings_info *mi = pi->mi; size_t actual_len = um->len; ASSERT(mi); ASSERT(mi->mmap_heap); if (um->h) vfs_munmap(um, um->vaddrp, actual_len); per_heap_kfree(mi->mmap_heap, um->vaddrp, &actual_len, KFREE_FL_ALLOW_SPLIT | KFREE_FL_MULTI_STEP | KFREE_FL_NO_ACTUAL_FREE); process_remove_user_mapping(um); } void remove_all_file_mappings(struct process *pi) { fs_handle *h; for (u32 i = 0; i < MAX_HANDLES; i++) { if (!(h = pi->handles[i])) continue; remove_all_mappings_of_handle(pi, h); } } struct mappings_info * duplicate_mappings_info(struct process *new_pi, struct mappings_info *mi) { struct mappings_info *new_mi = NULL; struct user_mapping *um, *um2; if (!(new_mi = kalloc_obj(struct mappings_info))) goto oom_case; list_init(&new_mi->mappings); if (!(new_mi->mmap_heap = kmalloc_heap_dup(mi->mmap_heap))) goto oom_case; new_mi->mmap_heap_size = mi->mmap_heap_size; list_for_each_ro(um, &mi->mappings, pi_node) { if (!(um2 = kalloc_obj(struct user_mapping))) goto oom_case; /* First just copy the mapping info */ *um2 = *um; /* Re-assign the process pointer */ um2->pi = new_pi; /* Re-init the new nodes */ list_node_init(&um2->pi_node); list_node_init(&um2->inode_node); /* Add the pi_node to new process's mappings list */ list_add_tail(&new_mi->mappings, &um2->pi_node); /* * If the inode_node belongs to a list (mappings per inode) * add the new mapping's inode_node to the same list. */ if (list_is_node_in_list(&um->inode_node)) list_add_after(&um->inode_node, &um2->inode_node); } return new_mi; oom_case: if (new_mi) { if (new_mi->mmap_heap) { kmalloc_destroy_heap(new_mi->mmap_heap); kfree2(new_mi->mmap_heap, kmalloc_get_heap_struct_size()); } list_for_each(um, um2, &new_mi->mappings, pi_node) { list_remove(&um->pi_node); kfree_obj(um, struct user_mapping); } kfree_obj(new_mi, struct mappings_info); } return NULL; } void user_vfree_and_unmap(ulong user_vaddr, size_t page_count) { pdir_t *pdir = get_curr_pdir(); ulong va = user_vaddr; for (size_t i = 0; i < page_count; i++, va += PAGE_SIZE) { if (!is_mapped(pdir, (void *)va)) continue; unmap_page(pdir, (void *)va, true); } } bool user_valloc_and_map_slow(ulong user_vaddr, size_t page_count) { pdir_t *pdir = get_curr_pdir(); ulong pa, va = user_vaddr; void *kernel_vaddr; for (size_t i = 0; i < page_count; i++, va += PAGE_SIZE) { if (is_mapped(pdir, (void *)va)) { user_vfree_and_unmap(user_vaddr, i); return false; } if (!(kernel_vaddr = kmalloc(PAGE_SIZE))) { user_vfree_and_unmap(user_vaddr, i); return false; } pa = KERNEL_VA_TO_PA(kernel_vaddr); if (map_page(pdir, (void *)va, pa, PAGING_FL_RWUS) != 0) { kfree2(kernel_vaddr, PAGE_SIZE); user_vfree_and_unmap(user_vaddr, i); return false; } } return true; } bool user_valloc_and_map(ulong user_vaddr, size_t page_count) { pdir_t *pdir = get_curr_pdir(); size_t size = (size_t)page_count << PAGE_SHIFT; size_t count; void *kernel_vaddr = general_kmalloc(&size, KMALLOC_FL_MULTI_STEP | PAGE_SIZE); if (!kernel_vaddr) return user_valloc_and_map_slow(user_vaddr, page_count); ASSERT(size == (size_t)page_count << PAGE_SHIFT); count = map_pages(pdir, (void *)user_vaddr, KERNEL_VA_TO_PA(kernel_vaddr), page_count, PAGING_FL_US | PAGING_FL_RW); if (count != page_count) { unmap_pages(pdir, (void *)user_vaddr, count, false); general_kfree(kernel_vaddr, &size, KFREE_FL_ALLOW_SPLIT | KFREE_FL_MULTI_STEP); return false; } return true; } void user_unmap_zero_page(ulong user_vaddr, size_t page_count) { pdir_t *pdir = get_curr_pdir(); unmap_pages(pdir, (void *)user_vaddr, page_count, true); } bool user_map_zero_page(ulong user_vaddr, size_t page_count) { size_t count = map_zero_pages(get_curr_pdir(), (void *)user_vaddr, page_count, PAGING_FL_US | PAGING_FL_RW); if (count != page_count) { user_unmap_zero_page(user_vaddr, count); return false; } return true; } int generic_fs_munmap(struct user_mapping *um, void *vaddrp, size_t len) { struct fs_handle_base *hb = um->h; struct process *pi = hb->pi; ulong vaddr = (ulong)vaddrp; ulong vend = vaddr + len; ASSERT(IS_PAGE_ALIGNED(len)); for (; vaddr < vend; vaddr += PAGE_SIZE) { unmap_page_permissive(pi->pdir, (void *)vaddr, false); } return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/process.h> STATIC int fork_dup_all_handles(struct process *pi); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/safe_ringbuf.h> #include <tilck/kernel/sync.h> struct wjob { void (*func)(void *); void *arg; }; struct worker_thread { const char *name; struct wjob *jobs; struct safe_ringbuf rb; struct task *task; struct kcond completion; int priority; /* 0 is the max priority */ volatile bool waiting_for_jobs; }; extern struct worker_thread *worker_threads[WTH_MAX_THREADS]; extern int worker_threads_cnt; void wth_run(void *arg); void wth_wakeup(struct worker_thread *t); bool wth_process_single_job(struct worker_thread *t); int wth_create_thread_for(struct worker_thread *t); <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # --------------------------------------------------------------- # NOTE # # This "script" is NOT meant to be executed directly. # It is included as a source file by scripts/build_toolchain. # # --------------------------------------------------------------- function custom_gcc_cross_tc { url="https://vvaltchev.github.io/cache" tarname="x86-i386-musl-1.1.24-gcc-9.4.0-aarch64.tar.bz2" pushd $TC/host if ! [ -d gcc_9_4_0_i386_musl ]; then download_file_in_cache "$url" "$tarname" extract_cachefile_tar_bz $tarname -- cd gcc_9_4_0_i386_musl/bin for x in i686-linux-musl-*; do n=$(echo $x | sed s/musl-//); mv $x $n; done rm i686-linux-cc fi popd } function custom_gcc_cross_tc_installed_status { if [ -d $TC/host_${HOST_ARCH}/gcc_9_4_0_i386_musl ]; then echo "installed i386" fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #define BUILTIN_SIZE_THRESHOLD 16 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wvla" EXTERN inline size_t strlen(const char *str) { /* * Algorithm * -------------- * * 0. ASSUME DF = 0 (the compiler assumes that already everywhere!) * 1. ecx = -1 * 2. eax = 0 * 3. edi = str * 4. while (ecx != 0) { * ZF = (al == *(BYTE *)edi); * edi++; * ecx--; * if (ZF) break; * } * 5. ecx = ~ecx; * 6. ecx--; * * For more details: https://stackoverflow.com/questions/26783797/ * * The story behind the "unused" variable * ---------------------------------------- * * Because of the way repne scasb works, the pointer has to be stored in EDI, * but it will also be modified by it. At that point, it would sound * reasonable to put EDI in clobbers, but GCC does not allow that. The * work-around suggested by the official documentation: * https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html * is to store the modified input register into an (unused) output variable. * * * Alternative implementation without "volatile" * ----------------------------------------------- * * The following implementation doesn't use "volatile", it's much simpler and * allows, in theory, the compiler to generate better code. Unfortunately, * at the moment, this alternative implementation causes GCC to generate more * instructions, rising the code size of Tilck by ~600 bytes. The code-size * impact per-se would not be problem, but the extra instructions slowing * down strlen() are. It's unclear why that's happening. The "nice" code is * left here for further research in the future. * * u32 count; * asm("repne scasb\n\t" * : "=c" (count), "+D" (str) * : "a" (0), "c" (-1), "m" MEM_CLOBBER_NOSZ(str, const char)); * return (~count)-1; */ register u32 count asm("ecx"); ulong unused; asmVolatile("repne scasb\n\t" "notl %%ecx\n\t" "decl %%ecx\n\t" : "=c" (count), "=D" (unused) : "a" (0), "c" (-1), "D" (str) : "cc"); return count; } /* dest and src can overloap only partially */ EXTERN inline void *memcpy(void *dest, const void *src, size_t n) { void *saved_dest = dest; /* * (Partial) No-overlap check. * NOTE: this check allows intentionally an overlap in the following cases: * * 1. * +----------------+ * | DEST | * +----------------+ * +----------------+ * | SRC | * +----------------+ * * 2. * +----------------+ * | DEST | * +----------------+ * +----------------+ * | SRC | * +----------------+ * * 3. * +----------------+ * | DEST | * +----------------+ * +----------+ * | SRC | * +----------+ * * Which can be expressed with: * [ DEST <= SRC ] * * * 4. * +----------------+ * | DEST | * +----------------+ * +----------------+ * | SRC | * +----------------+ * * Which can be expressed with: * [ SRC + n <= DEST ] */ ASSERT( dest <= src || ((ulong)src + n <= (ulong)dest) ); if (__builtin_constant_p(n) && n <= BUILTIN_SIZE_THRESHOLD) return __builtin_memcpy(dest, src, n); asm("rep movsl\n\t" // copy 4 bytes at a time, n/4 times "mov %k5, %%ecx\n\t" // then: ecx = (register) = n%4 "rep movsb\n\t" // copy 1 byte at a time, n%4 times : "+D"(dest), "+S"(src), "=c"(n), "=m" MEM_CLOBBER(dest, char, n) : "c"(n >> 2), "r"(n & 3), "m" MEM_CLOBBER(src, const char, n)); return saved_dest; } EXTERN inline void *memcpy32(void *dest, const void *src, size_t n) { void *saved_dest = dest; ASSERT( dest <= src || ((ulong)src + n <= (ulong)dest) ); asm("rep movsl\n\t" : "+D"(dest), "+S"(src), "=c"(n), "=m" MEM_CLOBBER(dest, u32, n) : "c"(n), "m" MEM_CLOBBER(src, u32, n)); return saved_dest; } /* dest and src might overlap anyhow */ EXTERN inline void *memmove(void *dest, const void *src, size_t n) { if (__builtin_constant_p(n) && n <= BUILTIN_SIZE_THRESHOLD) return __builtin_memmove(dest, src, n); if (dest <= src || ((ulong)src + n <= (ulong)dest)) { memcpy(dest, src, n); } else { /* * In this SRC + n >= DEST: * * +----------------+ * | DEST | * +----------------+ * +----------------+ * | SRC | * +----------------+ * * Using the forward direction will cause a corruption of the SRC buffer, * while, the backwards direction solves the problem. */ u32 unused; asmVolatile("std\n\t" "rep movsb\n\t" "cld\n\t" : "=c" (n), "=S" (src), "=D" (unused) : "c" (n), "S" ((char*)src+n-1), "D" ((char*)dest+n-1) : "cc", "memory"); } return dest; } /* * Set 'n' bytes pointed by 's' to 'c'. */ EXTERN inline void *memset(void *s, int c, size_t n) { void *saved = s; if (__builtin_constant_p(n) && n <= BUILTIN_SIZE_THRESHOLD) return __builtin_memset(s, c, n); asm("rep stosb" : "+D" (s), "+a" (c), "+c" (n), "=m" MEM_CLOBBER(s, char, n)); return saved; } /* * Set 'n' 16-bit elems pointed by 's' to 'val'. */ EXTERN inline void *memset16(u16 *s, u16 val, size_t n) { void *saved = s; asm("rep stosw" : "+D" (s), "+a" (val), "+c" (n), "=m" MEM_CLOBBER(s, u16, n)); return saved; } /* * Set 'n' 32-bit elems pointed by 's' to 'val'. */ EXTERN inline void *memset32(u32 *s, u32 val, size_t n) { void *saved = s; asm("rep stosl" : "+D" (s), "+a" (val), "+c" (n), "=m" MEM_CLOBBER(s, u32, n)); return saved; } EXTERN inline void bzero(void *s, size_t n) { asm("rep stosl\n\t" // zero 4 byte at a time, n / 4 times "mov %k5, %%ecx\n\t" // ecx = (register) = n % 4 "rep stosb\n\t" // zero 1 byte at a time, n % 3 times : "+D" (s), "=c" (n), "=m" MEM_CLOBBER(s, char, n) : "a" (0), "c" (n >> 2), "r" (n & 3)); } #pragma GCC diagnostic pop <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #if defined(__TILCK_KERNEL__) && !defined(__TILCK_HAL__) #error Never include this header directly. Do #include <tilck/kernel/hal.h>. #endif #include <tilck_gen_headers/config_kernel.h> #include <tilck/kernel/arch/x86_64/asm_defs.h> struct x86_64_regs { /* STUB struct */ s32 int_num; u32 err_code; u64 rsp, rbp, rax, rip; u32 custom_flags; }; struct x86_64_arch_proc_members { /* STUB struct */ ulong some_var; /* avoid error: empty struct has size 0 in C, 1 in C++ */ }; struct x86_64_arch_task_members { u16 fpu_regs_size; void *aligned_fpu_regs; }; static ALWAYS_INLINE int regs_intnum(regs_t *r) { NOT_IMPLEMENTED(); return 0; } static ALWAYS_INLINE void set_return_register(regs_t *r, ulong value) { NOT_IMPLEMENTED(); } NORETURN static ALWAYS_INLINE void context_switch(regs_t *r) { NOT_IMPLEMENTED(); } static ALWAYS_INLINE ulong get_rem_stack(void) { return (get_stack_ptr() & ((ulong)KERNEL_STACK_SIZE - 1)); } static ALWAYS_INLINE void *regs_get_stack_ptr(regs_t *r) { return TO_PTR(r->rsp); } static ALWAYS_INLINE void *regs_get_frame_ptr(regs_t *r) { return TO_PTR(r->rbp); } static ALWAYS_INLINE void *regs_get_ip(regs_t *r) { return TO_PTR(r->rip); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/mods/acpi.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> #define BATT_UNKNOWN_CHARGE 0xffffffff struct basic_battery_info { ulong design_cap; const char *power_unit; const char *bif_method; /* _BIF or _BIX */ u32 lfc_idx; /* Last Full Charge Capacity Property Index */ bool has_BIX; }; void print_acpi_failure(const char *func, const char *farg, ACPI_STATUS rc); ACPI_STATUS register_acpi_obj_in_sysfs(ACPI_HANDLE parent_obj, ACPI_HANDLE obj, ACPI_DEVICE_INFO *obj_info); bool acpi_has_method(ACPI_HANDLE obj, const char *name); bool acpi_is_battery(ACPI_HANDLE obj); ACPI_STATUS acpi_battery_get_basic_info(ACPI_HANDLE obj, struct basic_battery_info *bi); <file_sep>/****************************************************************************** * * Module Name: dswload - Dispatcher first pass namespace load callbacks * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #ifdef ACPI_ASL_COMPILER #include "acdisasm.h" #endif #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dswload") /******************************************************************************* * * FUNCTION: AcpiDsInitCallbacks * * PARAMETERS: WalkState - Current state of the parse tree walk * PassNumber - 1, 2, or 3 * * RETURN: Status * * DESCRIPTION: Init walk state callbacks * ******************************************************************************/ ACPI_STATUS AcpiDsInitCallbacks ( ACPI_WALK_STATE *WalkState, UINT32 PassNumber) { switch (PassNumber) { case 0: /* Parse only - caller will setup callbacks */ WalkState->ParseFlags = ACPI_PARSE_LOAD_PASS1 | ACPI_PARSE_DELETE_TREE | ACPI_PARSE_DISASSEMBLE; WalkState->DescendingCallback = NULL; WalkState->AscendingCallback = NULL; break; case 1: /* Load pass 1 */ WalkState->ParseFlags = ACPI_PARSE_LOAD_PASS1 | ACPI_PARSE_DELETE_TREE; WalkState->DescendingCallback = AcpiDsLoad1BeginOp; WalkState->AscendingCallback = AcpiDsLoad1EndOp; break; case 2: /* Load pass 2 */ WalkState->ParseFlags = ACPI_PARSE_LOAD_PASS1 | ACPI_PARSE_DELETE_TREE; WalkState->DescendingCallback = AcpiDsLoad2BeginOp; WalkState->AscendingCallback = AcpiDsLoad2EndOp; break; case 3: /* Execution pass */ WalkState->ParseFlags |= ACPI_PARSE_EXECUTE | ACPI_PARSE_DELETE_TREE; WalkState->DescendingCallback = AcpiDsExecBeginOp; WalkState->AscendingCallback = AcpiDsExecEndOp; break; default: return (AE_BAD_PARAMETER); } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsLoad1BeginOp * * PARAMETERS: WalkState - Current state of the parse tree walk * OutOp - Where to return op if a new one is created * * RETURN: Status * * DESCRIPTION: Descending callback used during the loading of ACPI tables. * ******************************************************************************/ ACPI_STATUS AcpiDsLoad1BeginOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **OutOp) { ACPI_PARSE_OBJECT *Op; ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_OBJECT_TYPE ObjectType; char *Path; UINT32 Flags; ACPI_FUNCTION_TRACE_PTR (DsLoad1BeginOp, WalkState->Op); Op = WalkState->Op; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Op=%p State=%p\n", Op, WalkState)); /* We are only interested in opcodes that have an associated name */ if (Op) { if (!(WalkState->OpInfo->Flags & AML_NAMED)) { *OutOp = Op; return_ACPI_STATUS (AE_OK); } /* Check if this object has already been installed in the namespace */ if (Op->Common.Node) { *OutOp = Op; return_ACPI_STATUS (AE_OK); } } Path = AcpiPsGetNextNamestring (&WalkState->ParserState); /* Map the raw opcode into an internal object type */ ObjectType = WalkState->OpInfo->ObjectType; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "State=%p Op=%p [%s]\n", WalkState, Op, AcpiUtGetTypeName (ObjectType))); switch (WalkState->Opcode) { case AML_SCOPE_OP: /* * The target name of the Scope() operator must exist at this point so * that we can actually open the scope to enter new names underneath it. * Allow search-to-root for single namesegs. */ Status = AcpiNsLookup (WalkState->ScopeInfo, Path, ObjectType, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT, WalkState, &(Node)); #ifdef ACPI_ASL_COMPILER if (Status == AE_NOT_FOUND) { /* * Table disassembly: * Target of Scope() not found. Generate an External for it, and * insert the name into the namespace. */ AcpiDmAddOpToExternalList (Op, Path, ACPI_TYPE_DEVICE, 0, 0); Status = AcpiNsLookup (WalkState->ScopeInfo, Path, ObjectType, ACPI_IMODE_LOAD_PASS1, ACPI_NS_SEARCH_PARENT, WalkState, &Node); } #endif if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, Path, Status); return_ACPI_STATUS (Status); } /* * Check to make sure that the target is * one of the opcodes that actually opens a scope */ switch (Node->Type) { case ACPI_TYPE_ANY: case ACPI_TYPE_LOCAL_SCOPE: /* Scope */ case ACPI_TYPE_DEVICE: case ACPI_TYPE_POWER: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_THERMAL: /* These are acceptable types */ break; case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: /* * These types we will allow, but we will change the type. * This enables some existing code of the form: * * Name (DEB, 0) * Scope (DEB) { ... } * * Note: silently change the type here. On the second pass, * we will report a warning */ ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Type override - [%4.4s] had invalid type (%s) " "for Scope operator, changed to type ANY\n", AcpiUtGetNodeName (Node), AcpiUtGetTypeName (Node->Type))); Node->Type = ACPI_TYPE_ANY; WalkState->ScopeInfo->Common.Value = ACPI_TYPE_ANY; break; case ACPI_TYPE_METHOD: /* * Allow scope change to root during execution of module-level * code. Root is typed METHOD during this time. */ if ((Node == AcpiGbl_RootNode) && (WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL)) { break; } /*lint -fallthrough */ default: /* All other types are an error */ ACPI_ERROR ((AE_INFO, "Invalid type (%s) for target of " "Scope operator [%4.4s] (Cannot override)", AcpiUtGetTypeName (Node->Type), AcpiUtGetNodeName (Node))); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } break; default: /* * For all other named opcodes, we will enter the name into * the namespace. * * Setup the search flags. * Since we are entering a name into the namespace, we do not want to * enable the search-to-root upsearch. * * There are only two conditions where it is acceptable that the name * already exists: * 1) the Scope() operator can reopen a scoping object that was * previously defined (Scope, Method, Device, etc.) * 2) Whenever we are parsing a deferred opcode (OpRegion, Buffer, * BufferField, or Package), the name of the object is already * in the namespace. */ if (WalkState->DeferredNode) { /* This name is already in the namespace, get the node */ Node = WalkState->DeferredNode; Status = AE_OK; break; } /* * If we are executing a method, do not create any namespace objects * during the load phase, only during execution. */ if (WalkState->MethodNode) { Node = NULL; Status = AE_OK; break; } Flags = ACPI_NS_NO_UPSEARCH; if ((WalkState->Opcode != AML_SCOPE_OP) && (!(WalkState->ParseFlags & ACPI_PARSE_DEFERRED_OP))) { if (WalkState->NamespaceOverride) { Flags |= ACPI_NS_OVERRIDE_IF_FOUND; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[%s] Override allowed\n", AcpiUtGetTypeName (ObjectType))); } else { Flags |= ACPI_NS_ERROR_IF_FOUND; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[%s] Cannot already exist\n", AcpiUtGetTypeName (ObjectType))); } } else { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[%s] Both Find or Create allowed\n", AcpiUtGetTypeName (ObjectType))); } /* * Enter the named type into the internal namespace. We enter the name * as we go downward in the parse tree. Any necessary subobjects that * involve arguments to the opcode must be created as we go back up the * parse tree later. */ Status = AcpiNsLookup (WalkState->ScopeInfo, Path, ObjectType, ACPI_IMODE_LOAD_PASS1, Flags, WalkState, &Node); if (ACPI_FAILURE (Status)) { if (Status == AE_ALREADY_EXISTS) { /* The name already exists in this scope */ if (Node->Flags & ANOBJ_IS_EXTERNAL) { /* * Allow one create on an object or segment that was * previously declared External */ Node->Flags &= ~ANOBJ_IS_EXTERNAL; Node->Type = (UINT8) ObjectType; /* Just retyped a node, probably will need to open a scope */ if (AcpiNsOpensScope (ObjectType)) { Status = AcpiDsScopeStackPush ( Node, ObjectType, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } Status = AE_OK; } } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, Path, Status); return_ACPI_STATUS (Status); } } break; } /* Common exit */ if (!Op) { /* Create a new op */ Op = AcpiPsAllocOp (WalkState->Opcode, WalkState->Aml); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } } /* Initialize the op */ #ifdef ACPI_CONSTANT_EVAL_ONLY Op->Named.Path = Path; #endif if (Node) { /* * Put the Node in the "op" object that the parser uses, so we * can get it again quickly when this scope is closed */ Op->Common.Node = Node; Op->Named.Name = Node->Name.Integer; } AcpiPsAppendArg (AcpiPsGetParentScope (&WalkState->ParserState), Op); *OutOp = Op; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsLoad1EndOp * * PARAMETERS: WalkState - Current state of the parse tree walk * * RETURN: Status * * DESCRIPTION: Ascending callback used during the loading of the namespace, * both control methods and everything else. * ******************************************************************************/ ACPI_STATUS AcpiDsLoad1EndOp ( ACPI_WALK_STATE *WalkState) { ACPI_PARSE_OBJECT *Op; ACPI_OBJECT_TYPE ObjectType; ACPI_STATUS Status = AE_OK; #ifdef ACPI_ASL_COMPILER UINT8 ParamCount; #endif ACPI_FUNCTION_TRACE (DsLoad1EndOp); Op = WalkState->Op; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Op=%p State=%p\n", Op, WalkState)); /* * Disassembler: handle create field operators here. * * CreateBufferField is a deferred op that is typically processed in load * pass 2. However, disassembly of control method contents walk the parse * tree with ACPI_PARSE_LOAD_PASS1 and AML_CREATE operators are processed * in a later walk. This is a problem when there is a control method that * has the same name as the AML_CREATE object. In this case, any use of the * name segment will be detected as a method call rather than a reference * to a buffer field. * * This earlier creation during disassembly solves this issue by inserting * the named object in the ACPI namespace so that references to this name * would be a name string rather than a method call. */ if ((WalkState->ParseFlags & ACPI_PARSE_DISASSEMBLE) && (WalkState->OpInfo->Flags & AML_CREATE)) { Status = AcpiDsCreateBufferField (Op, WalkState); return_ACPI_STATUS (Status); } /* We are only interested in opcodes that have an associated name */ if (!(WalkState->OpInfo->Flags & (AML_NAMED | AML_FIELD))) { return_ACPI_STATUS (AE_OK); } /* Get the object type to determine if we should pop the scope */ ObjectType = WalkState->OpInfo->ObjectType; if (WalkState->OpInfo->Flags & AML_FIELD) { /* * If we are executing a method, do not create any namespace objects * during the load phase, only during execution. */ if (!WalkState->MethodNode) { if (WalkState->Opcode == AML_FIELD_OP || WalkState->Opcode == AML_BANK_FIELD_OP || WalkState->Opcode == AML_INDEX_FIELD_OP) { Status = AcpiDsInitFieldObjects (Op, WalkState); } } return_ACPI_STATUS (Status); } /* * If we are executing a method, do not create any namespace objects * during the load phase, only during execution. */ if (!WalkState->MethodNode) { if (Op->Common.AmlOpcode == AML_REGION_OP) { Status = AcpiExCreateRegion (Op->Named.Data, Op->Named.Length, (ACPI_ADR_SPACE_TYPE) ((Op->Common.Value.Arg)->Common.Value.Integer), WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } else if (Op->Common.AmlOpcode == AML_DATA_REGION_OP) { Status = AcpiExCreateRegion (Op->Named.Data, Op->Named.Length, ACPI_ADR_SPACE_DATA_TABLE, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } if (Op->Common.AmlOpcode == AML_NAME_OP) { /* For Name opcode, get the object type from the argument */ if (Op->Common.Value.Arg) { ObjectType = (AcpiPsGetOpcodeInfo ( (Op->Common.Value.Arg)->Common.AmlOpcode))->ObjectType; /* Set node type if we have a namespace node */ if (Op->Common.Node) { Op->Common.Node->Type = (UINT8) ObjectType; } } } #ifdef ACPI_ASL_COMPILER /* * For external opcode, get the object type from the argument and * get the parameter count from the argument's next. */ if (AcpiGbl_DisasmFlag && Op->Common.Node && Op->Common.AmlOpcode == AML_EXTERNAL_OP) { /* * Note, if this external is not a method * Op->Common.Value.Arg->Common.Next->Common.Value.Integer == 0 * Therefore, ParamCount will be 0. */ ParamCount = (UINT8) Op->Common.Value.Arg->Common.Next->Common.Value.Integer; ObjectType = (UINT8) Op->Common.Value.Arg->Common.Value.Integer; Op->Common.Node->Flags |= ANOBJ_IS_EXTERNAL; Op->Common.Node->Type = (UINT8) ObjectType; AcpiDmCreateSubobjectForExternal ((UINT8)ObjectType, &Op->Common.Node, ParamCount); /* * Add the external to the external list because we may be * emitting code based off of the items within the external list. */ AcpiDmAddOpToExternalList (Op, Op->Named.Path, (UINT8)ObjectType, ParamCount, ACPI_EXT_ORIGIN_FROM_OPCODE | ACPI_EXT_RESOLVED_REFERENCE); } #endif /* * If we are executing a method, do not create any namespace objects * during the load phase, only during execution. */ if (!WalkState->MethodNode) { if (Op->Common.AmlOpcode == AML_METHOD_OP) { /* * MethodOp PkgLength NameString MethodFlags TermList * * Note: We must create the method node/object pair as soon as we * see the method declaration. This allows later pass1 parsing * of invocations of the method (need to know the number of * arguments.) */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "LOADING-Method: State=%p Op=%p NamedObj=%p\n", WalkState, Op, Op->Named.Node)); if (!AcpiNsGetAttachedObject (Op->Named.Node)) { WalkState->Operands[0] = ACPI_CAST_PTR (void, Op->Named.Node); WalkState->NumOperands = 1; Status = AcpiDsCreateOperands ( WalkState, Op->Common.Value.Arg); if (ACPI_SUCCESS (Status)) { Status = AcpiExCreateMethod (Op->Named.Data, Op->Named.Length, WalkState); } WalkState->Operands[0] = NULL; WalkState->NumOperands = 0; if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } } /* Pop the scope stack (only if loading a table) */ if (!WalkState->MethodNode && Op->Common.AmlOpcode != AML_EXTERNAL_OP && AcpiNsOpensScope (ObjectType)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "(%s): Popping scope for Op %p\n", AcpiUtGetTypeName (ObjectType), Op)); Status = AcpiDsScopeStackPop (WalkState); } return_ACPI_STATUS (Status); } <file_sep>/******************************************************************************* * * Module Name: nsobject - Utilities for objects attached to namespace * table entries * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsobject") /******************************************************************************* * * FUNCTION: AcpiNsAttachObject * * PARAMETERS: Node - Parent Node * Object - Object to be attached * Type - Type of object, or ACPI_TYPE_ANY if not * known * * RETURN: Status * * DESCRIPTION: Record the given object as the value associated with the * name whose ACPI_HANDLE is passed. If Object is NULL * and Type is ACPI_TYPE_ANY, set the name as having no value. * Note: Future may require that the Node->Flags field be passed * as a parameter. * * MUTEX: Assumes namespace is locked * ******************************************************************************/ ACPI_STATUS AcpiNsAttachObject ( ACPI_NAMESPACE_NODE *Node, ACPI_OPERAND_OBJECT *Object, ACPI_OBJECT_TYPE Type) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *LastObjDesc; ACPI_OBJECT_TYPE ObjectType = ACPI_TYPE_ANY; ACPI_FUNCTION_TRACE (NsAttachObject); /* * Parameter validation */ if (!Node) { /* Invalid handle */ ACPI_ERROR ((AE_INFO, "Null NamedObj handle")); return_ACPI_STATUS (AE_BAD_PARAMETER); } if (!Object && (ACPI_TYPE_ANY != Type)) { /* Null object */ ACPI_ERROR ((AE_INFO, "Null object, but type not ACPI_TYPE_ANY")); return_ACPI_STATUS (AE_BAD_PARAMETER); } if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED) { /* Not a name handle */ ACPI_ERROR ((AE_INFO, "Invalid handle %p [%s]", Node, AcpiUtGetDescriptorName (Node))); return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Check if this object is already attached */ if (Node->Object == Object) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Obj %p already installed in NameObj %p\n", Object, Node)); return_ACPI_STATUS (AE_OK); } /* If null object, we will just install it */ if (!Object) { ObjDesc = NULL; ObjectType = ACPI_TYPE_ANY; } /* * If the source object is a namespace Node with an attached object, * we will use that (attached) object */ else if ((ACPI_GET_DESCRIPTOR_TYPE (Object) == ACPI_DESC_TYPE_NAMED) && ((ACPI_NAMESPACE_NODE *) Object)->Object) { /* * Value passed is a name handle and that name has a * non-null value. Use that name's value and type. */ ObjDesc = ((ACPI_NAMESPACE_NODE *) Object)->Object; ObjectType = ((ACPI_NAMESPACE_NODE *) Object)->Type; } /* * Otherwise, we will use the parameter object, but we must type * it first */ else { ObjDesc = (ACPI_OPERAND_OBJECT *) Object; /* Use the given type */ ObjectType = Type; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Installing %p into Node %p [%4.4s]\n", ObjDesc, Node, AcpiUtGetNodeName (Node))); /* Detach an existing attached object if present */ if (Node->Object) { AcpiNsDetachObject (Node); } if (ObjDesc) { /* * Must increment the new value's reference count * (if it is an internal object) */ AcpiUtAddReference (ObjDesc); /* * Handle objects with multiple descriptors - walk * to the end of the descriptor list */ LastObjDesc = ObjDesc; while (LastObjDesc->Common.NextObject) { LastObjDesc = LastObjDesc->Common.NextObject; } /* Install the object at the front of the object list */ LastObjDesc->Common.NextObject = Node->Object; } Node->Type = (UINT8) ObjectType; Node->Object = ObjDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsDetachObject * * PARAMETERS: Node - A Namespace node whose object will be detached * * RETURN: None. * * DESCRIPTION: Detach/delete an object associated with a namespace node. * if the object is an allocated object, it is freed. * Otherwise, the field is simply cleared. * ******************************************************************************/ void AcpiNsDetachObject ( ACPI_NAMESPACE_NODE *Node) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_FUNCTION_TRACE (NsDetachObject); ObjDesc = Node->Object; if (!ObjDesc || (ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA)) { return_VOID; } if (Node->Flags & ANOBJ_ALLOCATED_BUFFER) { /* Free the dynamic aml buffer */ if (ObjDesc->Common.Type == ACPI_TYPE_METHOD) { ACPI_FREE (ObjDesc->Method.AmlStart); } } if (ObjDesc->Common.Type == ACPI_TYPE_REGION) { AcpiUtRemoveAddressRange(ObjDesc->Region.SpaceId, Node); } /* Clear the Node entry in all cases */ Node->Object = NULL; if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_OPERAND) { /* Unlink object from front of possible object list */ Node->Object = ObjDesc->Common.NextObject; /* Handle possible 2-descriptor object */ if (Node->Object && (Node->Object->Common.Type != ACPI_TYPE_LOCAL_DATA)) { Node->Object = Node->Object->Common.NextObject; } /* * Detach the object from any data objects (which are still held by * the namespace node) */ if (ObjDesc->Common.NextObject && ((ObjDesc->Common.NextObject)->Common.Type == ACPI_TYPE_LOCAL_DATA)) { ObjDesc->Common.NextObject = NULL; } } /* Reset the node type to untyped */ Node->Type = ACPI_TYPE_ANY; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Node %p [%4.4s] Object %p\n", Node, AcpiUtGetNodeName (Node), ObjDesc)); /* Remove one reference on the object (and all subobjects) */ AcpiUtRemoveReference (ObjDesc); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsGetAttachedObject * * PARAMETERS: Node - Namespace node * * RETURN: Current value of the object field from the Node whose * handle is passed * * DESCRIPTION: Obtain the object attached to a namespace node. * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiNsGetAttachedObject ( ACPI_NAMESPACE_NODE *Node) { ACPI_FUNCTION_TRACE_PTR (NsGetAttachedObject, Node); if (!Node) { ACPI_WARNING ((AE_INFO, "Null Node ptr")); return_PTR (NULL); } if (!Node->Object || ((ACPI_GET_DESCRIPTOR_TYPE (Node->Object) != ACPI_DESC_TYPE_OPERAND) && (ACPI_GET_DESCRIPTOR_TYPE (Node->Object) != ACPI_DESC_TYPE_NAMED)) || ((Node->Object)->Common.Type == ACPI_TYPE_LOCAL_DATA)) { return_PTR (NULL); } return_PTR (Node->Object); } /******************************************************************************* * * FUNCTION: AcpiNsGetSecondaryObject * * PARAMETERS: Node - Namespace node * * RETURN: Current value of the object field from the Node whose * handle is passed. * * DESCRIPTION: Obtain a secondary object associated with a namespace node. * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiNsGetSecondaryObject ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_FUNCTION_TRACE_PTR (NsGetSecondaryObject, ObjDesc); if ((!ObjDesc) || (ObjDesc->Common.Type== ACPI_TYPE_LOCAL_DATA) || (!ObjDesc->Common.NextObject) || ((ObjDesc->Common.NextObject)->Common.Type == ACPI_TYPE_LOCAL_DATA)) { return_PTR (NULL); } return_PTR (ObjDesc->Common.NextObject); } /******************************************************************************* * * FUNCTION: AcpiNsAttachData * * PARAMETERS: Node - Namespace node * Handler - Handler to be associated with the data * Data - Data to be attached * * RETURN: Status * * DESCRIPTION: Low-level attach data. Create and attach a Data object. * ******************************************************************************/ ACPI_STATUS AcpiNsAttachData ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT_HANDLER Handler, void *Data) { ACPI_OPERAND_OBJECT *PrevObjDesc; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *DataDesc; /* We only allow one attachment per handler */ PrevObjDesc = NULL; ObjDesc = Node->Object; while (ObjDesc) { if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) && (ObjDesc->Data.Handler == Handler)) { return (AE_ALREADY_EXISTS); } PrevObjDesc = ObjDesc; ObjDesc = ObjDesc->Common.NextObject; } /* Create an internal object for the data */ DataDesc = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_DATA); if (!DataDesc) { return (AE_NO_MEMORY); } DataDesc->Data.Handler = Handler; DataDesc->Data.Pointer = Data; /* Install the data object */ if (PrevObjDesc) { PrevObjDesc->Common.NextObject = DataDesc; } else { Node->Object = DataDesc; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsDetachData * * PARAMETERS: Node - Namespace node * Handler - Handler associated with the data * * RETURN: Status * * DESCRIPTION: Low-level detach data. Delete the data node, but the caller * is responsible for the actual data. * ******************************************************************************/ ACPI_STATUS AcpiNsDetachData ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT_HANDLER Handler) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *PrevObjDesc; PrevObjDesc = NULL; ObjDesc = Node->Object; while (ObjDesc) { if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) && (ObjDesc->Data.Handler == Handler)) { if (PrevObjDesc) { PrevObjDesc->Common.NextObject = ObjDesc->Common.NextObject; } else { Node->Object = ObjDesc->Common.NextObject; } AcpiUtRemoveReference (ObjDesc); return (AE_OK); } PrevObjDesc = ObjDesc; ObjDesc = ObjDesc->Common.NextObject; } return (AE_NOT_FOUND); } /******************************************************************************* * * FUNCTION: AcpiNsGetAttachedData * * PARAMETERS: Node - Namespace node * Handler - Handler associated with the data * Data - Where the data is returned * * RETURN: Status * * DESCRIPTION: Low level interface to obtain data previously associated with * a namespace node. * ******************************************************************************/ ACPI_STATUS AcpiNsGetAttachedData ( ACPI_NAMESPACE_NODE *Node, ACPI_OBJECT_HANDLER Handler, void **Data) { ACPI_OPERAND_OBJECT *ObjDesc; ObjDesc = Node->Object; while (ObjDesc) { if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) && (ObjDesc->Data.Handler == Handler)) { *Data = ObjDesc->Data.Pointer; return (AE_OK); } ObjDesc = ObjDesc->Common.NextObject; } return (AE_NOT_FOUND); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include "realmode_call.h" extern u32 realmode_test_out; void realmode_call_asm(void *f, u32 *a, u32 *b, u32 *c, u32 *d, u32 *si, u32 *di, u32 *flags_ref); void realmode_call(void *func, u32 *eax_ref, u32 *ebx_ref, u32 *ecx_ref, u32 *edx_ref, u32 *esi_ref, u32 *edi_ref, u32 *flags_ref) { ASSERT(func != NULL); ASSERT(eax_ref != NULL); ASSERT(ebx_ref != NULL); ASSERT(ecx_ref != NULL); ASSERT(edx_ref != NULL); ASSERT(esi_ref != NULL); ASSERT(edi_ref != NULL); ASSERT(flags_ref != NULL); realmode_call_asm(func, eax_ref, ebx_ref, ecx_ref, edx_ref, esi_ref, edi_ref, flags_ref); if (*eax_ref == 0xBAADCAFE && *ebx_ref == 0xCAFEBABE) panic("RM fault: 0x%x\n" "eip: %p\n" "flags: %p\n", *ecx_ref, (*edx_ref >> 16) * 16 + (*edx_ref & 0xffff), *esi_ref & 0xffff); } void realmode_call_by_val(void *func, u32 a, u32 b, u32 c, u32 d, u32 si, u32 di) { u32 flags_ignored; ASSERT(func != NULL); realmode_call(func, &a, &b, &c, &d, &si, &di, &flags_ignored); } void test_rm_call_working(void) { u32 eax, ebx, ecx, edx, esi, edi, flags; realmode_call(&realmode_test_out, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); ASSERT(eax == 2*1024*1024); ASSERT(ebx == 99); ASSERT(ecx == 100); ASSERT(edx == 102); ASSERT(esi == 300); ASSERT(edi == 350); } char bios_read_char(void) { u32 eax, ebx, ecx, edx, esi, edi, flags; /* * ah = 0x0 => read key press */ eax = 0; realmode_call(&realmode_int_16h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); /* * Return: * ah => scan code of the key pressed down * al => ASCII char */ return (char)(eax & 0xff); /* return just the ASCII char */ } bool read_drive_params(u8 drive, u32 *sectors_per_track, u32 *heads_per_cylinder, u32 *cylinder_count) { u32 eax, ebx, ecx, edx, esi, edi, flags; edx = drive; /* DL = drive number */ eax = 0x8 << 8; /* AH = read drive params */ realmode_call(&realmode_int_13h, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); *heads_per_cylinder = ((edx >> 8) & 0xff) + 1; /* DH = MAX head num */ /* sector count = lower 6 bits of CX (actual count, not MAX sector) */ *sectors_per_track = ecx & 63; /* cyl is max cylinder number (therefore count + cyl + 1) */ /* higher 8 bits of CX => lower 8 bits of cyl */ /* bits 6, 7 of CX => bits 8, 9 of cyl (higher 2 bits) */ *cylinder_count = 1 + (((ecx >> 8) & 0xff) | ((ecx & 192) << 2)); if (flags & EFLAGS_CF) return false; return true; } extern u32 realmode_read_sectors; extern u32 curr_sec; u16 saved_cx; u16 saved_dx; void dump_chs(void) { /* * the higher 8 bits of CX are the lower 8 bits of cyl * the bits 6, 7 of CX are the higher (8, 9) bits of cyl */ u32 cyl = saved_cx >> 8u | ((saved_cx & 192u) << 2u); u32 head = saved_dx >> 8; u32 sec = saved_cx & 63; /* the lower 6 bits of CX */ printk("CHS used: %u, %u, %u\n", cyl, head, sec); } void read_sectors(u32 dest_paddr, u32 lba_sector, u32 sector_count) { u32 eax, ebx, ecx, edx, esi, edi, flags; eax = dest_paddr; ebx = lba_sector; ecx = lba_sector + sector_count - 1; realmode_call(&realmode_read_sectors, &eax, &ebx, &ecx, &edx, &esi, &edi, &flags); if (eax) { printk("[ FAILED ]\n"); printk("Read failed with last op err: %p\n", TO_PTR(eax >> 8)); printk("LBA sector: %u\n", curr_sec); dump_chs(); panic("Unrecoverable read error"); } } <file_sep>/****************************************************************************** * * Module Name: utobject - ACPI object create/delete/size/cache routines * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utobject") /* Local prototypes */ static ACPI_STATUS AcpiUtGetSimpleObjectSize ( ACPI_OPERAND_OBJECT *Obj, ACPI_SIZE *ObjLength); static ACPI_STATUS AcpiUtGetPackageObjectSize ( ACPI_OPERAND_OBJECT *Obj, ACPI_SIZE *ObjLength); static ACPI_STATUS AcpiUtGetElementLength ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context); /******************************************************************************* * * FUNCTION: AcpiUtCreateInternalObjectDbg * * PARAMETERS: ModuleName - Source file name of caller * LineNumber - Line number of caller * ComponentId - Component type of caller * Type - ACPI Type of the new object * * RETURN: A new internal object, null on failure * * DESCRIPTION: Create and initialize a new internal object. * * NOTE: We always allocate the worst-case object descriptor because * these objects are cached, and we want them to be * one-size-satisfies-any-request. This in itself may not be * the most memory efficient, but the efficiency of the object * cache should more than make up for this! * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiUtCreateInternalObjectDbg ( const char *ModuleName, UINT32 LineNumber, UINT32 ComponentId, ACPI_OBJECT_TYPE Type) { ACPI_OPERAND_OBJECT *Object; ACPI_OPERAND_OBJECT *SecondObject; ACPI_FUNCTION_TRACE_STR (UtCreateInternalObjectDbg, AcpiUtGetTypeName (Type)); /* Allocate the raw object descriptor */ Object = AcpiUtAllocateObjectDescDbg ( ModuleName, LineNumber, ComponentId); if (!Object) { return_PTR (NULL); } switch (Type) { case ACPI_TYPE_REGION: case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: /* These types require a secondary object */ SecondObject = AcpiUtAllocateObjectDescDbg ( ModuleName, LineNumber, ComponentId); if (!SecondObject) { AcpiUtDeleteObjectDesc (Object); return_PTR (NULL); } SecondObject->Common.Type = ACPI_TYPE_LOCAL_EXTRA; SecondObject->Common.ReferenceCount = 1; /* Link the second object to the first */ Object->Common.NextObject = SecondObject; break; default: /* All others have no secondary object */ break; } /* Save the object type in the object descriptor */ Object->Common.Type = (UINT8) Type; /* Init the reference count */ Object->Common.ReferenceCount = 1; /* Any per-type initialization should go here */ return_PTR (Object); } /******************************************************************************* * * FUNCTION: AcpiUtCreatePackageObject * * PARAMETERS: Count - Number of package elements * * RETURN: Pointer to a new Package object, null on failure * * DESCRIPTION: Create a fully initialized package object * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiUtCreatePackageObject ( UINT32 Count) { ACPI_OPERAND_OBJECT *PackageDesc; ACPI_OPERAND_OBJECT **PackageElements; ACPI_FUNCTION_TRACE_U32 (UtCreatePackageObject, Count); /* Create a new Package object */ PackageDesc = AcpiUtCreateInternalObject (ACPI_TYPE_PACKAGE); if (!PackageDesc) { return_PTR (NULL); } /* * Create the element array. Count+1 allows the array to be null * terminated. */ PackageElements = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) Count + 1) * sizeof (void *)); if (!PackageElements) { ACPI_FREE (PackageDesc); return_PTR (NULL); } PackageDesc->Package.Count = Count; PackageDesc->Package.Elements = PackageElements; return_PTR (PackageDesc); } /******************************************************************************* * * FUNCTION: AcpiUtCreateIntegerObject * * PARAMETERS: InitialValue - Initial value for the integer * * RETURN: Pointer to a new Integer object, null on failure * * DESCRIPTION: Create an initialized integer object * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiUtCreateIntegerObject ( UINT64 InitialValue) { ACPI_OPERAND_OBJECT *IntegerDesc; ACPI_FUNCTION_TRACE (UtCreateIntegerObject); /* Create and initialize a new integer object */ IntegerDesc = AcpiUtCreateInternalObject (ACPI_TYPE_INTEGER); if (!IntegerDesc) { return_PTR (NULL); } IntegerDesc->Integer.Value = InitialValue; return_PTR (IntegerDesc); } /******************************************************************************* * * FUNCTION: AcpiUtCreateBufferObject * * PARAMETERS: BufferSize - Size of buffer to be created * * RETURN: Pointer to a new Buffer object, null on failure * * DESCRIPTION: Create a fully initialized buffer object * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiUtCreateBufferObject ( ACPI_SIZE BufferSize) { ACPI_OPERAND_OBJECT *BufferDesc; UINT8 *Buffer = NULL; ACPI_FUNCTION_TRACE_U32 (UtCreateBufferObject, BufferSize); /* Create a new Buffer object */ BufferDesc = AcpiUtCreateInternalObject (ACPI_TYPE_BUFFER); if (!BufferDesc) { return_PTR (NULL); } /* Create an actual buffer only if size > 0 */ if (BufferSize > 0) { /* Allocate the actual buffer */ Buffer = ACPI_ALLOCATE_ZEROED (BufferSize); if (!Buffer) { ACPI_ERROR ((AE_INFO, "Could not allocate size %u", (UINT32) BufferSize)); AcpiUtRemoveReference (BufferDesc); return_PTR (NULL); } } /* Complete buffer object initialization */ BufferDesc->Buffer.Flags |= AOPOBJ_DATA_VALID; BufferDesc->Buffer.Pointer = Buffer; BufferDesc->Buffer.Length = (UINT32) BufferSize; /* Return the new buffer descriptor */ return_PTR (BufferDesc); } /******************************************************************************* * * FUNCTION: AcpiUtCreateStringObject * * PARAMETERS: StringSize - Size of string to be created. Does not * include NULL terminator, this is added * automatically. * * RETURN: Pointer to a new String object * * DESCRIPTION: Create a fully initialized string object * ******************************************************************************/ ACPI_OPERAND_OBJECT * AcpiUtCreateStringObject ( ACPI_SIZE StringSize) { ACPI_OPERAND_OBJECT *StringDesc; char *String; ACPI_FUNCTION_TRACE_U32 (UtCreateStringObject, StringSize); /* Create a new String object */ StringDesc = AcpiUtCreateInternalObject (ACPI_TYPE_STRING); if (!StringDesc) { return_PTR (NULL); } /* * Allocate the actual string buffer -- (Size + 1) for NULL terminator. * NOTE: Zero-length strings are NULL terminated */ String = ACPI_ALLOCATE_ZEROED (StringSize + 1); if (!String) { ACPI_ERROR ((AE_INFO, "Could not allocate size %u", (UINT32) StringSize)); AcpiUtRemoveReference (StringDesc); return_PTR (NULL); } /* Complete string object initialization */ StringDesc->String.Pointer = String; StringDesc->String.Length = (UINT32) StringSize; /* Return the new string descriptor */ return_PTR (StringDesc); } /******************************************************************************* * * FUNCTION: AcpiUtValidInternalObject * * PARAMETERS: Object - Object to be validated * * RETURN: TRUE if object is valid, FALSE otherwise * * DESCRIPTION: Validate a pointer to be of type ACPI_OPERAND_OBJECT * ******************************************************************************/ BOOLEAN AcpiUtValidInternalObject ( void *Object) { ACPI_FUNCTION_NAME (UtValidInternalObject); /* Check for a null pointer */ if (!Object) { ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "**** Null Object Ptr\n")); return (FALSE); } /* Check the descriptor type field */ switch (ACPI_GET_DESCRIPTOR_TYPE (Object)) { case ACPI_DESC_TYPE_OPERAND: /* The object appears to be a valid ACPI_OPERAND_OBJECT */ return (TRUE); default: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%p is not an ACPI operand obj [%s]\n", Object, AcpiUtGetDescriptorName (Object))); break; } return (FALSE); } /******************************************************************************* * * FUNCTION: AcpiUtAllocateObjectDescDbg * * PARAMETERS: ModuleName - Caller's module name (for error output) * LineNumber - Caller's line number (for error output) * ComponentId - Caller's component ID (for error output) * * RETURN: Pointer to newly allocated object descriptor. Null on error * * DESCRIPTION: Allocate a new object descriptor. Gracefully handle * error conditions. * ******************************************************************************/ void * AcpiUtAllocateObjectDescDbg ( const char *ModuleName, UINT32 LineNumber, UINT32 ComponentId) { ACPI_OPERAND_OBJECT *Object; ACPI_FUNCTION_TRACE (UtAllocateObjectDescDbg); Object = AcpiOsAcquireObject (AcpiGbl_OperandCache); if (!Object) { ACPI_ERROR ((ModuleName, LineNumber, "Could not allocate an object descriptor")); return_PTR (NULL); } /* Mark the descriptor type */ ACPI_SET_DESCRIPTOR_TYPE (Object, ACPI_DESC_TYPE_OPERAND); ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "%p Size %X\n", Object, (UINT32) sizeof (ACPI_OPERAND_OBJECT))); return_PTR (Object); } /******************************************************************************* * * FUNCTION: AcpiUtDeleteObjectDesc * * PARAMETERS: Object - An Acpi internal object to be deleted * * RETURN: None. * * DESCRIPTION: Free an ACPI object descriptor or add it to the object cache * ******************************************************************************/ void AcpiUtDeleteObjectDesc ( ACPI_OPERAND_OBJECT *Object) { ACPI_FUNCTION_TRACE_PTR (UtDeleteObjectDesc, Object); /* Object must be of type ACPI_OPERAND_OBJECT */ if (ACPI_GET_DESCRIPTOR_TYPE (Object) != ACPI_DESC_TYPE_OPERAND) { ACPI_ERROR ((AE_INFO, "%p is not an ACPI Operand object [%s]", Object, AcpiUtGetDescriptorName (Object))); return_VOID; } (void) AcpiOsReleaseObject (AcpiGbl_OperandCache, Object); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiUtGetSimpleObjectSize * * PARAMETERS: InternalObject - An ACPI operand object * ObjLength - Where the length is returned * * RETURN: Status * * DESCRIPTION: This function is called to determine the space required to * contain a simple object for return to an external user. * * The length includes the object structure plus any additional * needed space. * ******************************************************************************/ static ACPI_STATUS AcpiUtGetSimpleObjectSize ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_SIZE *ObjLength) { ACPI_SIZE Length; ACPI_SIZE Size; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (UtGetSimpleObjectSize, InternalObject); /* Start with the length of the (external) Acpi object */ Length = sizeof (ACPI_OBJECT); /* A NULL object is allowed, can be a legal uninitialized package element */ if (!InternalObject) { /* * Object is NULL, just return the length of ACPI_OBJECT * (A NULL ACPI_OBJECT is an object of all zeroes.) */ *ObjLength = ACPI_ROUND_UP_TO_NATIVE_WORD (Length); return_ACPI_STATUS (AE_OK); } /* A Namespace Node should never appear here */ if (ACPI_GET_DESCRIPTOR_TYPE (InternalObject) == ACPI_DESC_TYPE_NAMED) { /* A namespace node should never get here */ ACPI_ERROR ((AE_INFO, "Received a namespace node [%4.4s] " "where an operand object is required", ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, InternalObject)->Name.Ascii)); return_ACPI_STATUS (AE_AML_INTERNAL); } /* * The final length depends on the object type * Strings and Buffers are packed right up against the parent object and * must be accessed bytewise or there may be alignment problems on * certain processors */ switch (InternalObject->Common.Type) { case ACPI_TYPE_STRING: Length += (ACPI_SIZE) InternalObject->String.Length + 1; break; case ACPI_TYPE_BUFFER: Length += (ACPI_SIZE) InternalObject->Buffer.Length; break; case ACPI_TYPE_INTEGER: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_POWER: /* No extra data for these types */ break; case ACPI_TYPE_LOCAL_REFERENCE: switch (InternalObject->Reference.Class) { case ACPI_REFCLASS_NAME: /* * Get the actual length of the full pathname to this object. * The reference will be converted to the pathname to the object */ Size = AcpiNsGetPathnameLength (InternalObject->Reference.Node); if (!Size) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Length += ACPI_ROUND_UP_TO_NATIVE_WORD (Size); break; default: /* * No other reference opcodes are supported. * Notably, Locals and Args are not supported, but this may be * required eventually. */ ACPI_ERROR ((AE_INFO, "Cannot convert to external object - " "unsupported Reference Class [%s] 0x%X in object %p", AcpiUtGetReferenceName (InternalObject), InternalObject->Reference.Class, InternalObject)); Status = AE_TYPE; break; } break; default: ACPI_ERROR ((AE_INFO, "Cannot convert to external object - " "unsupported type [%s] 0x%X in object %p", AcpiUtGetObjectTypeName (InternalObject), InternalObject->Common.Type, InternalObject)); Status = AE_TYPE; break; } /* * Account for the space required by the object rounded up to the next * multiple of the machine word size. This keeps each object aligned * on a machine word boundary. (preventing alignment faults on some * machines.) */ *ObjLength = ACPI_ROUND_UP_TO_NATIVE_WORD (Length); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtGetElementLength * * PARAMETERS: ACPI_PKG_CALLBACK * * RETURN: Status * * DESCRIPTION: Get the length of one package element. * ******************************************************************************/ static ACPI_STATUS AcpiUtGetElementLength ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context) { ACPI_STATUS Status = AE_OK; ACPI_PKG_INFO *Info = (ACPI_PKG_INFO *) Context; ACPI_SIZE ObjectSpace; switch (ObjectType) { case ACPI_COPY_TYPE_SIMPLE: /* * Simple object - just get the size (Null object/entry is handled * here also) and sum it into the running package length */ Status = AcpiUtGetSimpleObjectSize (SourceObject, &ObjectSpace); if (ACPI_FAILURE (Status)) { return (Status); } Info->Length += ObjectSpace; break; case ACPI_COPY_TYPE_PACKAGE: /* Package object - nothing much to do here, let the walk handle it */ Info->NumPackages++; State->Pkg.ThisTargetObj = NULL; break; default: /* No other types allowed */ return (AE_BAD_PARAMETER); } return (Status); } /******************************************************************************* * * FUNCTION: AcpiUtGetPackageObjectSize * * PARAMETERS: InternalObject - An ACPI internal object * ObjLength - Where the length is returned * * RETURN: Status * * DESCRIPTION: This function is called to determine the space required to * contain a package object for return to an external user. * * This is moderately complex since a package contains other * objects including packages. * ******************************************************************************/ static ACPI_STATUS AcpiUtGetPackageObjectSize ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_SIZE *ObjLength) { ACPI_STATUS Status; ACPI_PKG_INFO Info; ACPI_FUNCTION_TRACE_PTR (UtGetPackageObjectSize, InternalObject); Info.Length = 0; Info.ObjectSpace = 0; Info.NumPackages = 1; Status = AcpiUtWalkPackageTree ( InternalObject, NULL, AcpiUtGetElementLength, &Info); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * We have handled all of the objects in all levels of the package. * just add the length of the package objects themselves. * Round up to the next machine word. */ Info.Length += ACPI_ROUND_UP_TO_NATIVE_WORD ( sizeof (ACPI_OBJECT)) * (ACPI_SIZE) Info.NumPackages; /* Return the total package length */ *ObjLength = Info.Length; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtGetObjectSize * * PARAMETERS: InternalObject - An ACPI internal object * ObjLength - Where the length will be returned * * RETURN: Status * * DESCRIPTION: This function is called to determine the space required to * contain an object for return to an API user. * ******************************************************************************/ ACPI_STATUS AcpiUtGetObjectSize ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_SIZE *ObjLength) { ACPI_STATUS Status; ACPI_FUNCTION_ENTRY (); if ((ACPI_GET_DESCRIPTOR_TYPE (InternalObject) == ACPI_DESC_TYPE_OPERAND) && (InternalObject->Common.Type == ACPI_TYPE_PACKAGE)) { Status = AcpiUtGetPackageObjectSize (InternalObject, ObjLength); } else { Status = AcpiUtGetSimpleObjectSize (InternalObject, ObjLength); } return (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <multiboot.h> #define MEM_USABLE 1 #define MEM_RESERVED 2 #define MEM_ACPI_RECLAIMABLE 3 #define MEM_ACPI_NVS_MEMORY 4 #define MEM_BAD 5 struct mem_area { u64 base; u64 len; u32 type; u32 acpi; }; struct mem_info { struct mem_area *mem_areas; u32 count; }; /* * Reads from BIOS system's memory map and store it in the ma_buffer. * At the end, it sets the fields of the struct mem_info structure `mi`. */ void read_memory_map(void *buffer, size_t buf_size, struct mem_info *mi); void poison_usable_memory(struct mem_info *mi); /* * Get the first usable memory area of size `size` with address >= `min_paddr`. * Returns `0` in case of failure. */ ulong get_usable_mem(struct mem_info *mi, ulong min_paddr, ulong size); /* Get usable memory at the highest address possible */ ulong get_high_usable_mem(struct mem_info *mi, ulong size); static inline u32 bios_to_multiboot_mem_region(u32 bios_mem_type) { STATIC_ASSERT(MEM_USABLE == MULTIBOOT_MEMORY_AVAILABLE); STATIC_ASSERT(MEM_RESERVED == MULTIBOOT_MEMORY_RESERVED); STATIC_ASSERT(MEM_ACPI_RECLAIMABLE == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE); STATIC_ASSERT(MEM_ACPI_NVS_MEMORY == MULTIBOOT_MEMORY_NVS); STATIC_ASSERT(MEM_BAD == MULTIBOOT_MEMORY_BADRAM); return bios_mem_type; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define __FPU_MEMCPY_C__ /* * The code in this translation unit, in particular the *single* funcs defined * in fpu_memcpy.h have to be FAST, even in debug builds. It is important the * hot-patched fpu_cpy_single_256_nt, created by copying the once of the * fpu_cpy_*single* funcs to just execute the necessary MOVs and then just a * RET. No prologue/epilogue, no frame pointer, no stack variables. * NOTE: clearly, the code works well even if -O0 and without the PRAGMAs * below. Just, we want it to be fast in debug builds to improve the user * experience there. */ #if defined(__GNUC__) && !defined(__clang__) #pragma GCC optimize "-O3" #pragma GCC optimize "-fomit-frame-pointer" #endif #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/arch/generic_x86/fpu_memcpy.h> void memcpy256_failsafe(void *dest, const void *src, u32 n) { memcpy32(dest, src, n * 8); } FASTCALL void memcpy_single_256_failsafe(void *dest, const void *src) { memcpy32(dest, src, 8); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_nt_avx2(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_nt_avx2(dest, src); if (n % 2) fpu_cpy_single_256_nt_avx2(dest, src); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_nt_sse2(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_nt_sse2(dest, src); if (n % 2) fpu_cpy_single_256_nt_sse2(dest, src); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_nt_sse(void *dest, const void *src, u32 n) { for (register u32 i = 0; i < n; i++, src += 32, dest += 32) fpu_cpy_single_256_nt_sse(dest, src); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_avx2(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_avx2(dest, src); if (n % 2) fpu_cpy_single_256_avx2(dest, src); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_sse2(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_sse2(dest, src); if (n % 2) fpu_cpy_single_256_sse2(dest, src); } /* 'n' is the number of 32-byte (256-bit) data packets to copy */ void fpu_memcpy256_sse(void *dest, const void *src, u32 n) { for (register u32 i = 0; i < n; i++, src += 32, dest += 32) fpu_cpy_single_256_sse(dest, src); } void fpu_memcpy256_nt_read_avx2(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_nt_read_avx2(dest, src); if (n % 2) fpu_cpy_single_256_nt_read_avx2(dest, src); } void fpu_memcpy256_nt_read_sse4_1(void *dest, const void *src, u32 n) { u32 len64 = n / 2; for (register u32 i = 0; i < len64; i++, src += 64, dest += 64) fpu_cpy_single_512_nt_read_sse4_1(dest, src); if (n % 2) fpu_cpy_single_256_nt_read_sse4_1(dest, src); } void fpu_memset256_sse2(void *dest, u32 val32, u32 n) { char val256[32] ALIGNED_AT(32); memset32((void *)val256, val32, 8); for (register u32 i = 0; i < n; i++, dest += 32) fpu_cpy_single_256_nt_sse2(dest, val256); } void fpu_memset256_avx2(void *dest, u32 val32, u32 n) { char val256[32] ALIGNED_AT(32); memset32((void *)val256, val32, 8); for (register u32 i = 0; i < n; i++, dest += 32) fpu_cpy_single_256_nt_avx2(dest, val256); } static void init_fpu_memcpy_internal_check(void *func, const char *fname, u32 size) { if (!fname) { panic("init_fpu_memcpy: failed to find the symbol at %p\n", func); return; } if (size > 128) { panic("init_fpu_memcpy: the source function at %p is too big!\n", func); return; } } static void *get_fpu_cpy_single_256_nt_func(void) { if (!kopt_no_fpu_memcpy) { if (x86_cpu_features.can_use_avx2) return &fpu_cpy_single_256_nt_avx2; if (x86_cpu_features.can_use_sse2) return &fpu_cpy_single_256_nt_sse2; if (x86_cpu_features.can_use_sse) return &fpu_cpy_single_256_nt_sse; } /* See the comment below in init_fpu_memcpy() */ return IS_RELEASE_BUILD ? &memcpy_single_256_failsafe : NULL; } static void *get_fpu_cpy_single_256_nt_read_func(void) { if (!kopt_no_fpu_memcpy) { if (x86_cpu_features.can_use_avx2) return &fpu_cpy_single_256_nt_read_avx2; if (x86_cpu_features.can_use_sse4_1) return &fpu_cpy_single_256_nt_read_sse4_1; if (x86_cpu_features.can_use_sse2) return &fpu_cpy_single_256_sse2; /* no "nt" read here */ if (x86_cpu_features.can_use_sse) return &fpu_cpy_single_256_sse; /* no "nt" read here */ } /* See the comment below in init_fpu_memcpy() */ return IS_RELEASE_BUILD ? &memcpy_single_256_failsafe : NULL; } static void simple_hot_patch(void *dest, void *func, size_t max_size) { if (KERNEL_SYMBOLS) { const char *func_name; long offset; u32 size; func_name = find_sym_at_addr((ulong)func, &offset, &size); init_fpu_memcpy_internal_check(func, func_name, size); memcpy(dest, func, size); } else { memcpy(dest, func, max_size); } } void init_fpu_memcpy(void) { void *func; if (kopt_no_fpu_memcpy) { /* * NOTE: Just show the message, do NOT return. Perform the hot patch with * the failsafe functions in order to skip the JMP in the original code. * * See __asm_fpu_cpy_single_256_nt and __asm_fpu_cpy_single_256_nt_read. */ printk("INFO: fpu_memcpy is disabled (kopt_no_fpu_memcpy)\n"); } /* * NOTE: don't hot-patch the *_fpu_cpy_single_* funcs in the failsafe case. * Reason: unless we're using GCC, this file won't be compiled with -O3 * and memcpy_single_256_failsafe() will contain a call to memset32() * instead of inlining its body: that makes impossible the copy of the * function's body in __asm_fpu* because by default the compiler emit * relative call instructions (E8 opcode in x86): if we move the body, the * relative call will jump to the wrong place. The alternative of making * memset32() always inline doesn't work either with Clang because, because * of the lack of optimizations, the body of memcpy_single_256_failsafe() * will become huge and full of useless instructions and it won't fit * the 128 bytes reserved in __asm_fpu*, and making that slots bigger just * to contain the crappy code is NOT a solution. Therefore, since clang * does not support the #pragma optimize like GCC, the less evil for the * failsafe case is just to leave the __asm_fpu_* funcs unpatched, keeping * their original body: this means just making an unconditional jmp to * memcpy_single_256_failsafe() and from there a call to memset32(). It seems * by far the less evil solution. * * */ if ((func = get_fpu_cpy_single_256_nt_func())) { simple_hot_patch(&__asm_fpu_cpy_single_256_nt, func, 128); } if ((func = get_fpu_cpy_single_256_nt_read_func())) { simple_hot_patch(&__asm_fpu_cpy_single_256_nt_read, func, 128); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ typedef void (*action_func)(struct vterm *, ulong, ulong, ulong); struct actions_table_item { action_func func; u32 action_kind; }; #define ENTRY(func, n) { (void *)(__term_action_##func), n } static const struct actions_table_item actions_table[] = { [a_none] = ENTRY(none, 0), [a_write] = ENTRY(write, 3), [a_direct_write] = ENTRY(direct_write, 3), [a_del_generic] = ENTRY(del, 2), [a_scroll] = ENTRY(scroll, 2), [a_set_col_offset] = ENTRY(set_col_offset, 1), [a_move_cur] = ENTRY(move_cur, 4), [a_move_cur_rel] = ENTRY(move_cur_rel, 4), [a_reset] = ENTRY(reset, 0), [a_pause_output] = ENTRY(pause_output, 0), [a_restart_output] = ENTRY(restart_output, 0), [a_enable_cursor] = ENTRY(enable_cursor, 1), [a_non_buf_scroll] = ENTRY(non_buf_scroll, 2), [a_use_alt_buffer] = ENTRY(use_alt_buffer, 1), [a_insert_blank_lines] = ENTRY(ins_blank_lines, 1), [a_delete_lines] = ENTRY(del_lines, 1), [a_set_scroll_region] = ENTRY(set_scroll_region, 2), [a_insert_blank_chars] = ENTRY(ins_blank_chars, 1), [a_simple_del_chars] = ENTRY(del_chars_in_line, 1), [a_simple_erase_chars] = ENTRY(erase_chars_in_line, 1), }; #undef ENTRY static void term_execute_action(struct vterm *t, struct term_action *a) { ASSERT(a->type3 < ARRAY_SIZE(actions_table)); const struct actions_table_item *it = &actions_table[a->type3]; switch (it->action_kind) { case 0: CALL_ACTION_FUNC_0(it->func, t); break; case 1: CALL_ACTION_FUNC_1(it->func, t, a->arg); break; case 2: CALL_ACTION_FUNC_2(it->func, t, a->arg1, a->arg2); break; case 3: CALL_ACTION_FUNC_3(it->func, t, a->ptr, a->len, a->col); break; case 4: CALL_ACTION_FUNC_2(it->func, t, a->arg16_1, a->arg16_2); break; default: NOT_REACHED(); } } static void term_execute_or_enqueue_action(struct vterm *t, struct term_action *a) { term_execute_or_enqueue_action_template(t, &t->rb_data, a, (void *)&term_execute_action); } static void vterm_write(term *t, const char *buf, size_t len, u8 color) { struct term_action a; ASSERT(len < MB); if (in_panic()) { term_action_write(t, buf, (u32)len, color); return; } term_make_action_write(&a, buf, (u32)len, color); term_execute_or_enqueue_action(t, &a); } static void vterm_scroll_up(term *t, u32 rows) { struct term_action a; term_make_action_scroll(&a, term_scroll_up, rows); term_execute_or_enqueue_action(t, &a); } static void vterm_scroll_down(term *t, u32 rows) { struct term_action a; term_make_action_scroll(&a, term_scroll_down, rows); term_execute_or_enqueue_action(t, &a); } static void vterm_set_col_offset(term *_t, int off) { struct vterm *const t = _t; struct term_action a; term_make_action_set_col_off(&a, off >= 0 ? (u32)off : t->c); term_execute_or_enqueue_action(t, &a); } static void vterm_pause_output(term *t) { struct term_action a; term_make_action_pause_output(&a); term_execute_or_enqueue_action(t, &a); } static void vterm_restart_output(term *t) { struct term_action a; term_make_action_restart_output(&a); term_execute_or_enqueue_action(t, &a); } /* ---------------- term non-action interface funcs --------------------- */ u16 vterm_get_curr_row(struct vterm *t) { return t->r; } u16 vterm_get_curr_col(struct vterm *t) { return t->c; } static void vterm_set_filter(term *_t, term_filter func, void *ctx) { struct vterm *const t = _t; t->filter = func; t->filter_ctx = ctx; } static bool vterm_is_initialized(term *_t) { struct vterm *const t = _t; return t->initialized; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <map> #include "vfs_test_fs.h" static tfs_entry *root1 = ROOT_NODE( N_DIR( "a", N_SYM("linkToOtherFs1", "./b/c2/fs2_1"), N_SYM("linkToOtherFs2", "./b/c2/x/l1"), N_SYM("p2", "b/p3"), N_DIR( "b", N_SYM("p3", "c/p4"), N_SYM("link_to_nowhere", "/a/b/x/y/z/blabla"), N_DIR( "c", N_SYM("p4", "./f1"), N_FILE("f1"), N_FILE("f2"), N_SYM("c2_rel_link", "../c2"), N_SYM("parent_of_c2_rel_link", "../c2/.."), ), N_DIR("c2"), /* --> root2 */ N_DIR(".hdir"), ) ), N_DIR("dev"), /* --> root3 */ N_SYM("abs_s1", "/a/b/c/f1"), N_SYM("rel_s1", "a/b/c/f1"), N_SYM("l0", "l1"), N_SYM("l1", "l0"), N_SYM("p0", "p1"), N_SYM("p1", "a/p2"), ); static tfs_entry *root2 = ROOT_NODE( N_DIR( "x", N_SYM("l1", "/a"), N_DIR( "y", N_DIR("z") ) ), N_FILE("fs2_1"), N_FILE("fs2_2") ); static tfs_entry *root3 = ROOT_NODE( N_DIR( "xd", N_DIR( "yd", N_DIR("zd") ) ), N_FILE("fd1"), N_FILE("fd2") ); static struct mnt_fs fs1 = create_test_fs("fs1", root1); static struct mnt_fs fs2 = create_test_fs("fs2", root2); static struct mnt_fs fs3 = create_test_fs("fs3", root3); static void reset_all_fs_refcounts() { root1->reset_refcounts(); root2->reset_refcounts(); root3->reset_refcounts(); fs1.ref_count = 1; fs2.ref_count = 1; fs3.ref_count = 1; } static void check_all_fs_refcounts() { test_fs_check_refcounts(root1); test_fs_check_refcounts(root2); test_fs_check_refcounts(root3); ASSERT_EQ(fs1.ref_count, 5); ASSERT_EQ(fs2.ref_count, 2); ASSERT_EQ(fs3.ref_count, 2); } static int resolve(const char *path, struct vfs_path *p, bool res_last_sl) { int rc; if ((rc = vfs_resolve(path, p, true, res_last_sl)) < 0) return rc; vfs_fs_exunlock(p->fs); release_obj(p->fs); return rc; } class vfs_resolve_test : public vfs_test_base { protected: void SetUp() override { vfs_test_base::SetUp(); mp_init(&fs1); mp_add(&fs2, "/a/b/c2"); mp_add(&fs3, "/dev"); test_fs_register_mp(path(root1, {"a", "b", "c2"}), root2); test_fs_register_mp(path(root1, {"dev"}), root3); { /* * The kernel_process does not have `cwd` set. * That is set in a lazy way on the first vfs_resolve() call. * TODO: make `cwd` to be always set. */ struct vfs_path *tp = &get_curr_proc()->cwd; tp->fs = mp_get_root(); vfs_get_root_entry(tp->fs, &tp->fs_path); retain_obj(tp->fs); vfs_retain_inode_at(tp); } ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } void TearDown() override { ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); release_obj(mp_get_root()); /* * Compensate the effect of mp_init, mp_add etc. * TODO: implement and call mp_remove() for each mnt_fs instead. */ release_obj(&fs1); /* mp_init(&fs1) */ release_obj(&fs1); /* mp_add(&fs2,...) */ release_obj(&fs1); /* mp_add(&fs3,...) */ release_obj(&fs2); release_obj(&fs3); reset_all_fs_refcounts(); test_fs_clear_mps(); vfs_test_base::TearDown(); } }; class vfs_resolve_multi_fs : public vfs_resolve_test { }; class vfs_resolve_symlinks : public vfs_resolve_test { }; TEST_F(vfs_resolve_test, basic_test) { int rc; struct vfs_path p; ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* root path */ rc = resolve("/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.dir_inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* regular 1-level path */ rc = resolve("/a", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.dir_inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "a"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* non-existent 1-level path */ rc = resolve("/x", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs_path.dir_inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_NONE); ASSERT_STREQ(p.last_comp, "x"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* regular 2-level path */ rc = resolve("/a/b", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "b"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* regular 2-level path + trailing slash */ rc = resolve("/a/b/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "b/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* 2-level path with non-existent component in the middle */ rc = resolve("/x/b", &p, true); ASSERT_EQ(rc, -ENOENT); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* 4-level path ending with file */ rc = resolve("/a/b/c/f1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a", "b", "c"})); ASSERT_TRUE(p.fs_path.type == VFS_FILE); ASSERT_STREQ(p.last_comp, "f1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* 4-level path ending with file + trailing slash */ rc = resolve("/a/b/c/f1/", &p, true); ASSERT_EQ(rc, -ENOTDIR); ASSERT_STREQ(p.last_comp, nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_test, corner_cases) { int rc; struct vfs_path p; ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* empty path */ rc = resolve("", &p, true); ASSERT_EQ(rc, -ENOENT); ASSERT_STREQ(p.last_comp, nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* multiple slashes [root] */ rc = resolve("/////", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "/////"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* multiple slashes [in the middle] */ rc = resolve("/a/b/c////f1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a", "b", "c"})); ASSERT_TRUE(p.fs_path.type == VFS_FILE); ASSERT_STREQ(p.last_comp, "f1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* multiple slashes [at the beginning] */ rc = resolve("//a/b/c/f1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_TRUE(p.fs_path.type == VFS_FILE); ASSERT_STREQ(p.last_comp, "f1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* multiple slashes [at the end] */ rc = resolve("/a/b/////", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "b/////"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* dir entry starting with '.' */ rc = resolve("/a/b/.hdir", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", ".hdir"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a", "b"})); ASSERT_STREQ(p.last_comp, ".hdir"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* dir entry starting with '.' + trailing slash */ rc = resolve("/a/b/.hdir/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", ".hdir"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a", "b"})); ASSERT_STREQ(p.last_comp, ".hdir/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_test, single_dot) { int rc; struct vfs_path p; rc = resolve("/a/.", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/./", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "./"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/.", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/./", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "./"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/./b/c", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "c"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_test, double_dot) { int rc; struct vfs_path p; rc = resolve("/a/b/c/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/../", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "../"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/../..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/../../", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "../"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/../../new", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_NONE); ASSERT_STREQ(p.last_comp, "new"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/../../new/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs_path.dir_inode == path(root1, {"a"})); ASSERT_TRUE(p.fs_path.type == VFS_NONE); ASSERT_STREQ(p.last_comp, "new/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/../", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, "../"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/../..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/../..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs_path.type == VFS_DIR); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_multi_fs, basic_case) { int rc; struct vfs_path p; /* target-mnt_fs's root without slash */ rc = resolve("/a/b/c2", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_STREQ(p.last_comp, "c2"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* target-mnt_fs's root with slash */ rc = resolve("/a/b/c2/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_STREQ(p.last_comp, "c2/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x"})); ASSERT_STREQ(p.last_comp, "x"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/fs2_1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"fs2_1"})); ASSERT_STREQ(p.last_comp, "fs2_1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/y", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x", "y"})); ASSERT_STREQ(p.last_comp, "y"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/y/z", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x", "y", "z"})); ASSERT_STREQ(p.last_comp, "z"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/y/z/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x", "y", "z"})); ASSERT_STREQ(p.last_comp, "z/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_multi_fs, dot_dot) { int rc; struct vfs_path p; rc = resolve("/a/b/c2/x/y/z/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x", "y"})); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/y/z/../", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root2, {"x", "y"})); ASSERT_STREQ(p.last_comp, "../"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* new file after '..' */ rc = resolve("/a/b/c2/x/y/z/../new_file", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs_path.dir_inode == path(root2, {"x", "y"})); ASSERT_STREQ(p.last_comp, "new_file"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* new dir after '..' */ rc = resolve("/a/b/c2/x/y/z/../new_dir/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs_path.dir_inode == path(root2, {"x", "y"})); ASSERT_STREQ(p.last_comp, "new_dir/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c2/x/../", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_TRUE(p.fs == &fs2); ASSERT_STREQ(p.last_comp, "../"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* ../ crossing the mnt_fs-boundary [c2 is a mount-point] */ rc = resolve("/a/b/c2/x/../..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_TRUE(p.fs == &fs1); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/dev/..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs == &fs1); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/dev/../a", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_TRUE(p.fs == &fs1); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_multi_fs, rel_paths) { int rc; struct vfs_path p; struct process *pi = get_curr_proc(); rc = resolve("/dev/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root3); ASSERT_TRUE(p.fs == &fs3); ASSERT_STREQ(p.last_comp, "dev/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); pi->cwd = p; bzero(&p, sizeof(p)); rc = resolve(".", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root3); ASSERT_TRUE(p.fs == &fs3); ASSERT_STREQ(p.last_comp, "."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("..", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs_path.inode == root1); ASSERT_TRUE(p.fs == &fs1); ASSERT_STREQ(p.last_comp, ".."); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_symlinks, basic_tests) { int rc; struct vfs_path p; rc = resolve("/abs_s1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_STREQ(p.last_comp, "abs_s1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/rel_s1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_STREQ(p.last_comp, "rel_s1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/c2_rel_link", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs2); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_STREQ(p.last_comp, "c2_rel_link"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/c2_rel_link/", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs2); ASSERT_TRUE(p.fs_path.inode == root2); ASSERT_STREQ(p.last_comp, "c2_rel_link/"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/c/parent_of_c2_rel_link", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_STREQ(p.last_comp, "parent_of_c2_rel_link"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/b/link_to_nowhere/c/d/f", &p, true); ASSERT_EQ(rc, -ENOENT); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.fs == nullptr); ASSERT_STREQ(p.last_comp, nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_symlinks, nested_symlinks) { int rc; struct vfs_path p; rc = resolve("/a/p2", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b", "c", "f1"})); ASSERT_STREQ(p.last_comp, "p2"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_symlinks, real_eloop) { int rc; struct vfs_path p; rc = resolve("/l0", &p, true); ASSERT_EQ(rc, -ELOOP); ASSERT_TRUE(p.fs == nullptr); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.last_comp == nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_symlinks, too_many_links_eloop) { int rc; struct vfs_path p; /* 1 plus max nested symlinks */ rc = resolve("/p1", &p, true); ASSERT_EQ(rc, -ELOOP); ASSERT_TRUE(p.fs == nullptr); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.last_comp == nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); /* 2 plus max nested symlinks */ rc = resolve("/p0", &p, true); ASSERT_EQ(rc, -ELOOP); ASSERT_TRUE(p.fs == nullptr); ASSERT_TRUE(p.fs_path.inode == nullptr); ASSERT_TRUE(p.last_comp == nullptr); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } TEST_F(vfs_resolve_symlinks, cross_fs_symlinks) { int rc; struct vfs_path p; rc = resolve("/a/linkToOtherFs1", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs2); ASSERT_TRUE(p.fs_path.inode == path(root2, {"fs2_1"})); ASSERT_STREQ(p.last_comp, "linkToOtherFs1"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/linkToOtherFs2", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a"})); ASSERT_STREQ(p.last_comp, "linkToOtherFs2"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); rc = resolve("/a/linkToOtherFs2/b", &p, true); ASSERT_EQ(rc, 0); ASSERT_TRUE(p.fs_path.inode != nullptr); ASSERT_TRUE(p.fs == &fs1); ASSERT_TRUE(p.fs_path.inode == path(root1, {"a", "b"})); ASSERT_STREQ(p.last_comp, "b"); ASSERT_NO_FATAL_FAILURE({ check_all_fs_refcounts(); }); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <limits> #include <random> #include <string> #include <type_traits> #include <inttypes.h> #include <gtest/gtest.h> using namespace std; extern "C" { #include <tilck/common/string_util.h> #include <tilck/kernel/test/itoa.h> } // Wrapper defined only for s32, s64, u32, u64. template <typename T> inline void itoa_wrapper(T val, char *buf); // Wrapper defined only for u32, u64. template <typename T> inline void uitoa_hex_wrapper(T val, char *buf, bool fixed); // Wrapper defined only for u32, u64. template <typename T> inline void sprintf_hex_wrapper(T val, char *buf, bool fixed); template <> inline void itoa_wrapper<s32>(s32 val, char *buf) { itoa32(val, buf); } template <> inline void itoa_wrapper<s64>(s64 val, char *buf) { itoa64(val, buf); } template <> inline void itoa_wrapper<u32>(u32 val, char *buf) { uitoa32(val, buf, 10); } template <> inline void itoa_wrapper<u64>(u64 val, char *buf) { uitoa64(val, buf, 10); } // strtol() wrapper (s32 and s64 only) template <typename T> inline T strtol_wrapper(const char *s, int base); template <> inline s32 strtol_wrapper<s32>(const char *s, int base) { return tilck_strtol32(s, NULL, base, NULL); } template <> inline s64 strtol_wrapper<s64>(const char *s, int base) { return tilck_strtol64(s, NULL, base, NULL); } template <> inline u32 strtol_wrapper<u32>(const char *s, int base) { return tilck_strtoul32(s, NULL, base, NULL); } template <> inline u64 strtol_wrapper<u64>(const char *s, int base) { return tilck_strtoul64(s, NULL, base, NULL); } template<> inline void uitoa_hex_wrapper<u32>(u32 val, char *buf, bool fixed) { if (!fixed) uitoa32(val, buf, 16); else uitoa32_hex_fixed(val, buf); } template<> inline void uitoa_hex_wrapper<u64>(u64 val, char *buf, bool fixed) { if (!fixed) uitoa64(val, buf, 16); else uitoa64_hex_fixed(val, buf); } template <> inline void sprintf_hex_wrapper<u32>(u32 val, char *buf, bool fixed) { if (fixed) sprintf(buf, "%08x", val); else sprintf(buf, "%x", val); } template <> inline void sprintf_hex_wrapper<u64>(u64 val, char *buf, bool fixed) { if (fixed) sprintf(buf, "%016" PRIx64, val); else sprintf(buf, "%" PRIx64, val); } template <typename T, bool hex = false, bool fixed = false> typename enable_if<hex, void>::type check(T val) { char expected[64]; char got[64]; memset(expected, '*', sizeof(expected)); memset(got, '*', sizeof(got)); sprintf_hex_wrapper<T>(val, expected, fixed); uitoa_hex_wrapper<T>(val, got, fixed); ASSERT_STREQ(got, expected); } template <typename T, bool hex = false, bool fixed = false> typename enable_if<!hex, void>::type check(T val) { char expected[64]; char got[64]; memset(expected, '*', sizeof(expected)); memset(got, '*', sizeof(got)); strcpy(expected, to_string(val).c_str()); itoa_wrapper(val, got); ASSERT_STREQ(got, expected); } template <typename T, bool hex = false, bool fixed = false> void check_basic_set() { auto check_func = check<T, hex, fixed>; ASSERT_NO_FATAL_FAILURE({ check_func(numeric_limits<T>::lowest()); check_func(numeric_limits<T>::min()); check_func(numeric_limits<T>::max()); check_func(numeric_limits<T>::min() + 1); check_func(numeric_limits<T>::max() - 1); }); } template <typename T, bool hex = false, bool fixed = false> void generic_itoa_test_body() { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); auto check_func = check<T, hex, fixed>; auto check_basic_set_func = check_basic_set<T, hex, fixed>; uniform_int_distribution<T> dist(numeric_limits<T>::min(), numeric_limits<T>::max()); ASSERT_NO_FATAL_FAILURE({ check_basic_set_func(); }); for (int i = 0; i < 100000; i++) ASSERT_NO_FATAL_FAILURE({ check_func(dist(e)); }); } TEST(itoa, u32_dec) { auto test_func = generic_itoa_test_body<u32>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, u64_dec) { auto test_func = generic_itoa_test_body<u64>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, s32_dec) { auto test_func = generic_itoa_test_body<s32>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, s64_dec) { auto test_func = generic_itoa_test_body<s64>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, u32_hex) { auto test_func = generic_itoa_test_body<u32, true>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, u64_hex) { auto test_func = generic_itoa_test_body<u64, true>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, u32_hex_fixed) { auto test_func = generic_itoa_test_body<u32, true, true>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(itoa, u64_hex_fixed) { auto test_func = generic_itoa_test_body<u64, true, true>; ASSERT_NO_FATAL_FAILURE({ test_func(); }); } TEST(tilck_strtol, basic_tests) { EXPECT_EQ(strtol_wrapper<s32>("0", 10), 0); EXPECT_EQ(strtol_wrapper<s32>("1", 10), 1); EXPECT_EQ(strtol_wrapper<s32>("12", 10), 12); EXPECT_EQ(strtol_wrapper<s32>("123", 10), 123); EXPECT_EQ(strtol_wrapper<s32>("-1", 10), -1); EXPECT_EQ(strtol_wrapper<s32>("-123", 10), -123); EXPECT_EQ(strtol_wrapper<s32>("00123", 10), 123); EXPECT_EQ(strtol_wrapper<s32>("2147483647", 10), 2147483647); // INT_MAX EXPECT_EQ(strtol_wrapper<s32>("2147483648", 10), 0); // INT_MAX + 1 EXPECT_EQ(strtol_wrapper<s32>("-2147483648", 10), -2147483648); // INT_MIN EXPECT_EQ(strtol_wrapper<s32>("-2147483649", 10), 0); // INT_MIN - 1 EXPECT_EQ(strtol_wrapper<s32>("123abc", 10), 123); EXPECT_EQ(strtol_wrapper<s32>("123 abc", 10), 123); EXPECT_EQ(strtol_wrapper<s32>("-123abc", 10), -123); EXPECT_EQ(strtol_wrapper<s32>("a", 16), 10); EXPECT_EQ(strtol_wrapper<s32>("ff", 16), 255); EXPECT_EQ(strtol_wrapper<s32>("02bbffdd", 16), 0x02bbffdd); EXPECT_EQ(strtol_wrapper<s32>("111001", 2), 0b111001); EXPECT_EQ(strtol_wrapper<s32>("755", 8), 0755); } TEST(tilck_strtoll, basic_tests) { EXPECT_EQ(strtol_wrapper<s64>("2147483648", 10), 2147483648); // INT_MAX+1 EXPECT_EQ(strtol_wrapper<s64>("21474836480", 10), 21474836480); EXPECT_EQ( strtol_wrapper<s64>("9223372036854775807", 10), 9223372036854775807ll ); // LLONG_MAX EXPECT_EQ( strtol_wrapper<s64>("-9223372036854775808", 10), -9223372036854775807ll - 1ll ); // LLONG_MIN } TEST(tilck_strtoul, basic_tests) { EXPECT_EQ(strtol_wrapper<u32>("0", 10), 0u); EXPECT_EQ(strtol_wrapper<u32>("1234", 10), 1234u); EXPECT_EQ(strtol_wrapper<u32>("a", 16), 10u); EXPECT_EQ(strtol_wrapper<u32>("ff", 16), 255u); EXPECT_EQ(strtol_wrapper<u32>("02bbffdd", 16), 0x02bbffddu); EXPECT_EQ(strtol_wrapper<u32>("111001", 2), 0b111001u); EXPECT_EQ(strtol_wrapper<u32>("755", 8), 0755u); EXPECT_EQ(strtol_wrapper<u32>("-1", 10), 0u); EXPECT_EQ(strtol_wrapper<u32>("-134", 10), 0u); } TEST(tilck_strtol, errors) { const char *str; const char *endptr; int error; int res; str = "abc"; res = tilck_strtol32(str, &endptr, 10, &error); EXPECT_EQ(res, 0); EXPECT_EQ(endptr, str); EXPECT_EQ(error, -EINVAL); str = "2147483648"; // INT_MAX + 1 res = tilck_strtol32(str, &endptr, 10, &error); EXPECT_EQ(res, 0); EXPECT_EQ(endptr, str); EXPECT_EQ(error, -ERANGE); str = "-2147483649"; // INT_MIN - 1 res = tilck_strtol32(str, &endptr, 10, &error); EXPECT_EQ(res, 0); EXPECT_EQ(error, -ERANGE); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static struct kmutex mp_mutex = STATIC_KMUTEX_INIT(mp_mutex, 0); static struct mountpoint mps2[MAX_MOUNTPOINTS]; static struct mnt_fs *mp_root; int mp_init(struct mnt_fs *root_fs) { /* do not support changing the root struct mnt_fs */ NO_TEST_ASSERT(!mp_root); #ifdef UNIT_TEST_ENVIRONMENT bzero(mps2, sizeof(mps2)); #endif mp_root = root_fs; retain_obj(mp_root); return 0; } struct mnt_fs *mp_get_root(void) { ASSERT(mp_root != NULL); return mp_root; } struct mnt_fs *mp_get_at_nolock(struct mnt_fs *host_fs, vfs_inode_ptr_t inode) { ASSERT(kmutex_is_curr_task_holding_lock(&mp_mutex)); for (int i = 0; i < ARRAY_SIZE(mps2); i++) if (mps2[i].host_fs_inode == inode && mps2[i].host_fs == host_fs) return mps2[i].target_fs; return NULL; } struct mnt_fs *mp_get_retained_at(struct mnt_fs *host_fs, vfs_inode_ptr_t inode) { struct mnt_fs *ret; kmutex_lock(&mp_mutex); { if ((ret = mp_get_at_nolock(host_fs, inode))) retain_obj(ret); } kmutex_unlock(&mp_mutex); return ret; } struct mountpoint *mp_get_retained_mp_of(struct mnt_fs *target_fs) { int i; struct mountpoint *res = NULL; kmutex_lock(&mp_mutex); { for (i = 0; i < ARRAY_SIZE(mps2); i++) if (mps2[i].target_fs == target_fs) break; if (i < ARRAY_SIZE(mps2)) { res = &mps2[i]; retain_obj(res); } } kmutex_unlock(&mp_mutex); return res; } int mp_add(struct mnt_fs *target_fs, const char *target_path) { struct vfs_path p; int i, rc; /* * We need to resolve target_path in order to get the host_fs and the * host_fs's inode. */ if ((rc = vfs_resolve(target_path, &p, false, true))) return rc; if (p.fs_path.type != VFS_DIR) { vfs_fs_shunlock(p.fs); release_obj(p.fs); return -ENOTDIR; } vfs_retain_inode_at(&p); /* * Unlock the host fs but do *not* release its ref-count: each entry in the * `mps2` table retains its `host_fs`, its `host_fs_inode` and its * `target_fs`. */ vfs_fs_shunlock(p.fs); kmutex_lock(&mp_mutex); /* we need to have the root struct mnt_fs set */ ASSERT(mp_root != NULL); if (mp_get_at_nolock(p.fs, p.fs_path.inode)) { vfs_release_inode_at(&p); kmutex_unlock(&mp_mutex); return -EBUSY; /* the target path is already a mount-point */ } for (i = 0; i < ARRAY_SIZE(mps2); i++) { if (mps2[i].target_fs == target_fs) { vfs_release_inode_at(&p); kmutex_unlock(&mp_mutex); return -EPERM; /* mounting multiple times a FS is NOT permitted */ } } /* search for a free slot in the `mps2` table */ for (i = 0; i < ARRAY_SIZE(mps2); i++) if (!mps2[i].host_fs) break; if (i < ARRAY_SIZE(mps2)) { /* we've found a free slot */ mps2[i] = (struct mountpoint) { .host_fs = p.fs, .host_fs_inode = p.fs_path.inode, .target_fs = target_fs, }; rc = 0; /* Now that we've succeeded, we must retain the target_fs as well */ retain_obj(target_fs); } else { /* no free slot, sorry */ rc = -EMFILE; vfs_release_inode_at(&p); release_obj(p.fs); } kmutex_unlock(&mp_mutex); return rc; } int mp_remove(const char *target_path) { NOT_IMPLEMENTED(); } void vfs_syncfs(struct mnt_fs *fs) { ASSERT(is_preemption_enabled()); if (~fs->flags & VFS_FS_RW) return; /* the filesystem is mounted as read-only: nothing to sync */ if (fs->fsops->syncfs) fs->fsops->syncfs(fs); } void vfs_sync(void) { ASSERT(is_preemption_enabled()); kmutex_lock(&mp_mutex); { vfs_syncfs(mp_root); for (int i = 0; i < ARRAY_SIZE(mps2); i++) { if (mps2[i].host_fs) vfs_syncfs(mps2[i].target_fs); } } kmutex_unlock(&mp_mutex); } <file_sep>/****************************************************************************** * * Module Name: exoparg1 - AML execution - opcodes with 1 argument * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "acdispat.h" #include "acinterp.h" #include "amlcode.h" #include "acnamesp.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exoparg1") /*! * Naming convention for AML interpreter execution routines. * * The routines that begin execution of AML opcodes are named with a common * convention based upon the number of arguments, the number of target operands, * and whether or not a value is returned: * * AcpiExOpcode_xA_yT_zR * * Where: * * xA - ARGUMENTS: The number of arguments (input operands) that are * required for this opcode type (0 through 6 args). * yT - TARGETS: The number of targets (output operands) that are required * for this opcode type (0, 1, or 2 targets). * zR - RETURN VALUE: Indicates whether this opcode type returns a value * as the function return (0 or 1). * * The AcpiExOpcode* functions are called via the Dispatcher component with * fully resolved operands. !*/ /******************************************************************************* * * FUNCTION: AcpiExOpcode_0A_0T_1R * * PARAMETERS: WalkState - Current state (contains AML opcode) * * RETURN: Status * * DESCRIPTION: Execute operator with no operands, one return value * ******************************************************************************/ ACPI_STATUS AcpiExOpcode_0A_0T_1R ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *ReturnDesc = NULL; ACPI_FUNCTION_TRACE_STR (ExOpcode_0A_0T_1R, AcpiPsGetOpcodeName (WalkState->Opcode)); /* Examine the AML opcode */ switch (WalkState->Opcode) { case AML_TIMER_OP: /* Timer () */ /* Create a return object of type Integer */ ReturnDesc = AcpiUtCreateIntegerObject (AcpiOsGetTimer ()); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } break; default: /* Unknown opcode */ ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", WalkState->Opcode)); Status = AE_AML_BAD_OPCODE; break; } Cleanup: /* Delete return object on error */ if ((ACPI_FAILURE (Status)) || WalkState->ResultObj) { AcpiUtRemoveReference (ReturnDesc); WalkState->ResultObj = NULL; } else { /* Save the return value */ WalkState->ResultObj = ReturnDesc; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExOpcode_1A_0T_0R * * PARAMETERS: WalkState - Current state (contains AML opcode) * * RETURN: Status * * DESCRIPTION: Execute Type 1 monadic operator with numeric operand on * object stack * ******************************************************************************/ ACPI_STATUS AcpiExOpcode_1A_0T_0R ( ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_STR (ExOpcode_1A_0T_0R, AcpiPsGetOpcodeName (WalkState->Opcode)); /* Examine the AML opcode */ switch (WalkState->Opcode) { case AML_RELEASE_OP: /* Release (MutexObject) */ Status = AcpiExReleaseMutex (Operand[0], WalkState); break; case AML_RESET_OP: /* Reset (EventObject) */ Status = AcpiExSystemResetEvent (Operand[0]); break; case AML_SIGNAL_OP: /* Signal (EventObject) */ Status = AcpiExSystemSignalEvent (Operand[0]); break; case AML_SLEEP_OP: /* Sleep (MsecTime) */ Status = AcpiExSystemDoSleep (Operand[0]->Integer.Value); break; case AML_STALL_OP: /* Stall (UsecTime) */ Status = AcpiExSystemDoStall ((UINT32) Operand[0]->Integer.Value); break; case AML_UNLOAD_OP: /* Unload (Handle) */ Status = AcpiExUnloadTable (Operand[0]); break; default: /* Unknown opcode */ ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", WalkState->Opcode)); Status = AE_AML_BAD_OPCODE; break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExOpcode_1A_1T_0R * * PARAMETERS: WalkState - Current state (contains AML opcode) * * RETURN: Status * * DESCRIPTION: Execute opcode with one argument, one target, and no * return value. * ******************************************************************************/ ACPI_STATUS AcpiExOpcode_1A_1T_0R ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_FUNCTION_TRACE_STR (ExOpcode_1A_1T_0R, AcpiPsGetOpcodeName (WalkState->Opcode)); /* Examine the AML opcode */ switch (WalkState->Opcode) { case AML_LOAD_OP: Status = AcpiExLoadOp (Operand[0], Operand[1], WalkState); break; default: /* Unknown opcode */ ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", WalkState->Opcode)); Status = AE_AML_BAD_OPCODE; goto Cleanup; } Cleanup: return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExOpcode_1A_1T_1R * * PARAMETERS: WalkState - Current state (contains AML opcode) * * RETURN: Status * * DESCRIPTION: Execute opcode with one argument, one target, and a * return value. * ******************************************************************************/ ACPI_STATUS AcpiExOpcode_1A_1T_1R ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *ReturnDesc = NULL; ACPI_OPERAND_OBJECT *ReturnDesc2 = NULL; UINT32 Temp32; UINT32 i; UINT64 PowerOfTen; UINT64 Digit; ACPI_FUNCTION_TRACE_STR (ExOpcode_1A_1T_1R, AcpiPsGetOpcodeName (WalkState->Opcode)); /* Examine the AML opcode */ switch (WalkState->Opcode) { case AML_BIT_NOT_OP: case AML_FIND_SET_LEFT_BIT_OP: case AML_FIND_SET_RIGHT_BIT_OP: case AML_FROM_BCD_OP: case AML_TO_BCD_OP: case AML_CONDITIONAL_REF_OF_OP: /* Create a return object of type Integer for these opcodes */ ReturnDesc = AcpiUtCreateInternalObject (ACPI_TYPE_INTEGER); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } switch (WalkState->Opcode) { case AML_BIT_NOT_OP: /* Not (Operand, Result) */ ReturnDesc->Integer.Value = ~Operand[0]->Integer.Value; break; case AML_FIND_SET_LEFT_BIT_OP: /* FindSetLeftBit (Operand, Result) */ ReturnDesc->Integer.Value = Operand[0]->Integer.Value; /* * Acpi specification describes Integer type as a little * endian unsigned value, so this boundary condition is valid. */ for (Temp32 = 0; ReturnDesc->Integer.Value && Temp32 < ACPI_INTEGER_BIT_SIZE; ++Temp32) { ReturnDesc->Integer.Value >>= 1; } ReturnDesc->Integer.Value = Temp32; break; case AML_FIND_SET_RIGHT_BIT_OP: /* FindSetRightBit (Operand, Result) */ ReturnDesc->Integer.Value = Operand[0]->Integer.Value; /* * The Acpi specification describes Integer type as a little * endian unsigned value, so this boundary condition is valid. */ for (Temp32 = 0; ReturnDesc->Integer.Value && Temp32 < ACPI_INTEGER_BIT_SIZE; ++Temp32) { ReturnDesc->Integer.Value <<= 1; } /* Since the bit position is one-based, subtract from 33 (65) */ ReturnDesc->Integer.Value = Temp32 == 0 ? 0 : (ACPI_INTEGER_BIT_SIZE + 1) - Temp32; break; case AML_FROM_BCD_OP: /* FromBcd (BCDValue, Result) */ /* * The 64-bit ACPI integer can hold 16 4-bit BCD characters * (if table is 32-bit, integer can hold 8 BCD characters) * Convert each 4-bit BCD value */ PowerOfTen = 1; ReturnDesc->Integer.Value = 0; Digit = Operand[0]->Integer.Value; /* Convert each BCD digit (each is one nybble wide) */ for (i = 0; (i < AcpiGbl_IntegerNybbleWidth) && (Digit > 0); i++) { /* Get the least significant 4-bit BCD digit */ Temp32 = ((UINT32) Digit) & 0xF; /* Check the range of the digit */ if (Temp32 > 9) { ACPI_ERROR ((AE_INFO, "BCD digit too large (not decimal): 0x%X", Temp32)); Status = AE_AML_NUMERIC_OVERFLOW; goto Cleanup; } /* Sum the digit into the result with the current power of 10 */ ReturnDesc->Integer.Value += (((UINT64) Temp32) * PowerOfTen); /* Shift to next BCD digit */ Digit >>= 4; /* Next power of 10 */ PowerOfTen *= 10; } break; case AML_TO_BCD_OP: /* ToBcd (Operand, Result) */ ReturnDesc->Integer.Value = 0; Digit = Operand[0]->Integer.Value; /* Each BCD digit is one nybble wide */ for (i = 0; (i < AcpiGbl_IntegerNybbleWidth) && (Digit > 0); i++) { (void) AcpiUtShortDivide (Digit, 10, &Digit, &Temp32); /* * Insert the BCD digit that resides in the * remainder from above */ ReturnDesc->Integer.Value |= (((UINT64) Temp32) << ACPI_MUL_4 (i)); } /* Overflow if there is any data left in Digit */ if (Digit > 0) { ACPI_ERROR ((AE_INFO, "Integer too large to convert to BCD: 0x%8.8X%8.8X", ACPI_FORMAT_UINT64 (Operand[0]->Integer.Value))); Status = AE_AML_NUMERIC_OVERFLOW; goto Cleanup; } break; case AML_CONDITIONAL_REF_OF_OP: /* CondRefOf (SourceObject, Result) */ /* * This op is a little strange because the internal return value is * different than the return value stored in the result descriptor * (There are really two return values) */ if ((ACPI_NAMESPACE_NODE *) Operand[0] == AcpiGbl_RootNode) { /* * This means that the object does not exist in the namespace, * return FALSE */ ReturnDesc->Integer.Value = 0; goto Cleanup; } /* Get the object reference, store it, and remove our reference */ Status = AcpiExGetObjectReference (Operand[0], &ReturnDesc2, WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } Status = AcpiExStore (ReturnDesc2, Operand[1], WalkState); AcpiUtRemoveReference (ReturnDesc2); /* The object exists in the namespace, return TRUE */ ReturnDesc->Integer.Value = ACPI_UINT64_MAX; goto Cleanup; default: /* No other opcodes get here */ break; } break; case AML_STORE_OP: /* Store (Source, Target) */ /* * A store operand is typically a number, string, buffer or lvalue * Be careful about deleting the source object, * since the object itself may have been stored. */ Status = AcpiExStore (Operand[0], Operand[1], WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* It is possible that the Store already produced a return object */ if (!WalkState->ResultObj) { /* * Normally, we would remove a reference on the Operand[0] * parameter; But since it is being used as the internal return * object (meaning we would normally increment it), the two * cancel out, and we simply don't do anything. */ WalkState->ResultObj = Operand[0]; WalkState->Operands[0] = NULL; /* Prevent deletion */ } return_ACPI_STATUS (Status); /* * ACPI 2.0 Opcodes */ case AML_COPY_OBJECT_OP: /* CopyObject (Source, Target) */ Status = AcpiUtCopyIobjectToIobject ( Operand[0], &ReturnDesc, WalkState); break; case AML_TO_DECIMAL_STRING_OP: /* ToDecimalString (Data, Result) */ Status = AcpiExConvertToString ( Operand[0], &ReturnDesc, ACPI_EXPLICIT_CONVERT_DECIMAL); if (ReturnDesc == Operand[0]) { /* No conversion performed, add ref to handle return value */ AcpiUtAddReference (ReturnDesc); } break; case AML_TO_HEX_STRING_OP: /* ToHexString (Data, Result) */ Status = AcpiExConvertToString ( Operand[0], &ReturnDesc, ACPI_EXPLICIT_CONVERT_HEX); if (ReturnDesc == Operand[0]) { /* No conversion performed, add ref to handle return value */ AcpiUtAddReference (ReturnDesc); } break; case AML_TO_BUFFER_OP: /* ToBuffer (Data, Result) */ Status = AcpiExConvertToBuffer (Operand[0], &ReturnDesc); if (ReturnDesc == Operand[0]) { /* No conversion performed, add ref to handle return value */ AcpiUtAddReference (ReturnDesc); } break; case AML_TO_INTEGER_OP: /* ToInteger (Data, Result) */ /* Perform "explicit" conversion */ Status = AcpiExConvertToInteger (Operand[0], &ReturnDesc, 0); if (ReturnDesc == Operand[0]) { /* No conversion performed, add ref to handle return value */ AcpiUtAddReference (ReturnDesc); } break; case AML_SHIFT_LEFT_BIT_OP: /* ShiftLeftBit (Source, BitNum) */ case AML_SHIFT_RIGHT_BIT_OP: /* ShiftRightBit (Source, BitNum) */ /* These are two obsolete opcodes */ ACPI_ERROR ((AE_INFO, "%s is obsolete and not implemented", AcpiPsGetOpcodeName (WalkState->Opcode))); Status = AE_SUPPORT; goto Cleanup; default: /* Unknown opcode */ ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", WalkState->Opcode)); Status = AE_AML_BAD_OPCODE; goto Cleanup; } if (ACPI_SUCCESS (Status)) { /* Store the return value computed above into the target object */ Status = AcpiExStore (ReturnDesc, Operand[1], WalkState); } Cleanup: /* Delete return object on error */ if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ReturnDesc); } /* Save return object on success */ else if (!WalkState->ResultObj) { WalkState->ResultObj = ReturnDesc; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExOpcode_1A_0T_1R * * PARAMETERS: WalkState - Current state (contains AML opcode) * * RETURN: Status * * DESCRIPTION: Execute opcode with one argument, no target, and a return value * ******************************************************************************/ ACPI_STATUS AcpiExOpcode_1A_0T_1R ( ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *TempDesc; ACPI_OPERAND_OBJECT *ReturnDesc = NULL; ACPI_STATUS Status = AE_OK; UINT32 Type; UINT64 Value; ACPI_FUNCTION_TRACE_STR (ExOpcode_1A_0T_1R, AcpiPsGetOpcodeName (WalkState->Opcode)); /* Examine the AML opcode */ switch (WalkState->Opcode) { case AML_LOGICAL_NOT_OP: /* LNot (Operand) */ ReturnDesc = AcpiUtCreateIntegerObject ((UINT64) 0); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } /* * Set result to ONES (TRUE) if Value == 0. Note: * ReturnDesc->Integer.Value is initially == 0 (FALSE) from above. */ if (!Operand[0]->Integer.Value) { ReturnDesc->Integer.Value = ACPI_UINT64_MAX; } break; case AML_DECREMENT_OP: /* Decrement (Operand) */ case AML_INCREMENT_OP: /* Increment (Operand) */ /* * Create a new integer. Can't just get the base integer and * increment it because it may be an Arg or Field. */ ReturnDesc = AcpiUtCreateInternalObject (ACPI_TYPE_INTEGER); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } /* * Since we are expecting a Reference operand, it can be either a * NS Node or an internal object. */ TempDesc = Operand[0]; if (ACPI_GET_DESCRIPTOR_TYPE (TempDesc) == ACPI_DESC_TYPE_OPERAND) { /* Internal reference object - prevent deletion */ AcpiUtAddReference (TempDesc); } /* * Convert the Reference operand to an Integer (This removes a * reference on the Operand[0] object) * * NOTE: We use LNOT_OP here in order to force resolution of the * reference operand to an actual integer. */ Status = AcpiExResolveOperands (AML_LOGICAL_NOT_OP, &TempDesc, WalkState); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "While resolving operands for [%s]", AcpiPsGetOpcodeName (WalkState->Opcode))); goto Cleanup; } /* * TempDesc is now guaranteed to be an Integer object -- * Perform the actual increment or decrement */ if (WalkState->Opcode == AML_INCREMENT_OP) { ReturnDesc->Integer.Value = TempDesc->Integer.Value + 1; } else { ReturnDesc->Integer.Value = TempDesc->Integer.Value - 1; } /* Finished with this Integer object */ AcpiUtRemoveReference (TempDesc); /* * Store the result back (indirectly) through the original * Reference object */ Status = AcpiExStore (ReturnDesc, Operand[0], WalkState); break; case AML_OBJECT_TYPE_OP: /* ObjectType (SourceObject) */ /* * Note: The operand is not resolved at this point because we want to * get the associated object, not its value. For example, we don't * want to resolve a FieldUnit to its value, we want the actual * FieldUnit object. */ /* Get the type of the base object */ Status = AcpiExResolveMultiple (WalkState, Operand[0], &Type, NULL); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* Allocate a descriptor to hold the type. */ ReturnDesc = AcpiUtCreateIntegerObject ((UINT64) Type); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } break; case AML_SIZE_OF_OP: /* SizeOf (SourceObject) */ /* * Note: The operand is not resolved at this point because we want to * get the associated object, not its value. */ /* Get the base object */ Status = AcpiExResolveMultiple ( WalkState, Operand[0], &Type, &TempDesc); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* * The type of the base object must be integer, buffer, string, or * package. All others are not supported. * * NOTE: Integer is not specifically supported by the ACPI spec, * but is supported implicitly via implicit operand conversion. * rather than bother with conversion, we just use the byte width * global (4 or 8 bytes). */ switch (Type) { case ACPI_TYPE_INTEGER: Value = AcpiGbl_IntegerByteWidth; break; case ACPI_TYPE_STRING: Value = TempDesc->String.Length; break; case ACPI_TYPE_BUFFER: /* Buffer arguments may not be evaluated at this point */ Status = AcpiDsGetBufferArguments (TempDesc); Value = TempDesc->Buffer.Length; break; case ACPI_TYPE_PACKAGE: /* Package arguments may not be evaluated at this point */ Status = AcpiDsGetPackageArguments (TempDesc); Value = TempDesc->Package.Count; break; default: ACPI_ERROR ((AE_INFO, "Operand must be Buffer/Integer/String/Package" " - found type %s", AcpiUtGetTypeName (Type))); Status = AE_AML_OPERAND_TYPE; goto Cleanup; } if (ACPI_FAILURE (Status)) { goto Cleanup; } /* * Now that we have the size of the object, create a result * object to hold the value */ ReturnDesc = AcpiUtCreateIntegerObject (Value); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } break; case AML_REF_OF_OP: /* RefOf (SourceObject) */ Status = AcpiExGetObjectReference ( Operand[0], &ReturnDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } break; case AML_DEREF_OF_OP: /* DerefOf (ObjReference | String) */ /* Check for a method local or argument, or standalone String */ if (ACPI_GET_DESCRIPTOR_TYPE (Operand[0]) == ACPI_DESC_TYPE_NAMED) { TempDesc = AcpiNsGetAttachedObject ( (ACPI_NAMESPACE_NODE *) Operand[0]); if (TempDesc && ((TempDesc->Common.Type == ACPI_TYPE_STRING) || (TempDesc->Common.Type == ACPI_TYPE_LOCAL_REFERENCE))) { Operand[0] = TempDesc; AcpiUtAddReference (TempDesc); } else { Status = AE_AML_OPERAND_TYPE; goto Cleanup; } } else { switch ((Operand[0])->Common.Type) { case ACPI_TYPE_LOCAL_REFERENCE: /* * This is a DerefOf (LocalX | ArgX) * * Must resolve/dereference the local/arg reference first */ switch (Operand[0]->Reference.Class) { case ACPI_REFCLASS_LOCAL: case ACPI_REFCLASS_ARG: /* Set Operand[0] to the value of the local/arg */ Status = AcpiDsMethodDataGetValue ( Operand[0]->Reference.Class, Operand[0]->Reference.Value, WalkState, &TempDesc); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* * Delete our reference to the input object and * point to the object just retrieved */ AcpiUtRemoveReference (Operand[0]); Operand[0] = TempDesc; break; case ACPI_REFCLASS_REFOF: /* Get the object to which the reference refers */ TempDesc = Operand[0]->Reference.Object; AcpiUtRemoveReference (Operand[0]); Operand[0] = TempDesc; break; default: /* Must be an Index op - handled below */ break; } break; case ACPI_TYPE_STRING: break; default: Status = AE_AML_OPERAND_TYPE; goto Cleanup; } } if (ACPI_GET_DESCRIPTOR_TYPE (Operand[0]) != ACPI_DESC_TYPE_NAMED) { if ((Operand[0])->Common.Type == ACPI_TYPE_STRING) { /* * This is a DerefOf (String). The string is a reference * to a named ACPI object. * * 1) Find the owning Node * 2) Dereference the node to an actual object. Could be a * Field, so we need to resolve the node to a value. */ Status = AcpiNsGetNodeUnlocked (WalkState->ScopeInfo->Scope.Node, Operand[0]->String.Pointer, ACPI_NS_SEARCH_PARENT, ACPI_CAST_INDIRECT_PTR ( ACPI_NAMESPACE_NODE, &ReturnDesc)); if (ACPI_FAILURE (Status)) { goto Cleanup; } Status = AcpiExResolveNodeToValue ( ACPI_CAST_INDIRECT_PTR ( ACPI_NAMESPACE_NODE, &ReturnDesc), WalkState); goto Cleanup; } } /* Operand[0] may have changed from the code above */ if (ACPI_GET_DESCRIPTOR_TYPE (Operand[0]) == ACPI_DESC_TYPE_NAMED) { /* * This is a DerefOf (ObjectReference) * Get the actual object from the Node (This is the dereference). * This case may only happen when a LocalX or ArgX is * dereferenced above, or for references to device and * thermal objects. */ switch (((ACPI_NAMESPACE_NODE *) Operand[0])->Type) { case ACPI_TYPE_DEVICE: case ACPI_TYPE_THERMAL: /* These types have no node subobject, return the NS node */ ReturnDesc = Operand[0]; break; default: /* For most types, get the object attached to the node */ ReturnDesc = AcpiNsGetAttachedObject ( (ACPI_NAMESPACE_NODE *) Operand[0]); AcpiUtAddReference (ReturnDesc); break; } } else { /* * This must be a reference object produced by either the * Index() or RefOf() operator */ switch (Operand[0]->Reference.Class) { case ACPI_REFCLASS_INDEX: /* * The target type for the Index operator must be * either a Buffer or a Package */ switch (Operand[0]->Reference.TargetType) { case ACPI_TYPE_BUFFER_FIELD: TempDesc = Operand[0]->Reference.Object; /* * Create a new object that contains one element of the * buffer -- the element pointed to by the index. * * NOTE: index into a buffer is NOT a pointer to a * sub-buffer of the main buffer, it is only a pointer to a * single element (byte) of the buffer! * * Since we are returning the value of the buffer at the * indexed location, we don't need to add an additional * reference to the buffer itself. */ ReturnDesc = AcpiUtCreateIntegerObject ((UINT64) TempDesc->Buffer.Pointer[Operand[0]->Reference.Value]); if (!ReturnDesc) { Status = AE_NO_MEMORY; goto Cleanup; } break; case ACPI_TYPE_PACKAGE: /* * Return the referenced element of the package. We must * add another reference to the referenced object, however. */ ReturnDesc = *(Operand[0]->Reference.Where); if (!ReturnDesc) { /* * Element is NULL, do not allow the dereference. * This provides compatibility with other ACPI * implementations. */ return_ACPI_STATUS (AE_AML_UNINITIALIZED_ELEMENT); } AcpiUtAddReference (ReturnDesc); break; default: ACPI_ERROR ((AE_INFO, "Unknown Index TargetType 0x%X in reference object %p", Operand[0]->Reference.TargetType, Operand[0])); Status = AE_AML_OPERAND_TYPE; goto Cleanup; } break; case ACPI_REFCLASS_REFOF: ReturnDesc = Operand[0]->Reference.Object; if (ACPI_GET_DESCRIPTOR_TYPE (ReturnDesc) == ACPI_DESC_TYPE_NAMED) { ReturnDesc = AcpiNsGetAttachedObject ( (ACPI_NAMESPACE_NODE *) ReturnDesc); if (!ReturnDesc) { break; } /* * June 2013: * BufferFields/FieldUnits require additional resolution */ switch (ReturnDesc->Common.Type) { case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: Status = AcpiExReadDataFromField ( WalkState, ReturnDesc, &TempDesc); if (ACPI_FAILURE (Status)) { goto Cleanup; } ReturnDesc = TempDesc; break; default: /* Add another reference to the object */ AcpiUtAddReference (ReturnDesc); break; } } break; default: ACPI_ERROR ((AE_INFO, "Unknown class in reference(%p) - 0x%2.2X", Operand[0], Operand[0]->Reference.Class)); Status = AE_TYPE; goto Cleanup; } } break; default: ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", WalkState->Opcode)); Status = AE_AML_BAD_OPCODE; goto Cleanup; } Cleanup: /* Delete return object on error */ if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ReturnDesc); } /* Save return object on success */ else { WalkState->ResultObj = ReturnDesc; } return_ACPI_STATUS (Status); } <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). send_string_to_vm(r"fbtest{ret}") s = vm_take_stable_screenshot() send_string_to_vm(r"{ret}") actual = img_convert(s, "png") expected = os.path.join(INTERACTIVE_EXP, "fbtest.png") if not filecmp.cmp(actual, expected, False): raise IntTestScreenshotNoMatchFailure( "<image: {}>".format(actual), "<image: {}>".format(expected) ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/mod_acpi.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/list.h> enum acpi_init_status { ais_failed = -1, ais_not_started = 0, ais_tables_initialized = 1, ais_tables_loaded = 2, ais_subsystem_enabled = 3, ais_fully_initialized = 4, }; #if MOD_acpi static inline enum acpi_init_status get_acpi_init_status(void) { extern enum acpi_init_status acpi_init_status; return acpi_init_status; } void acpi_mod_init_tables(void); void acpi_set_root_pointer(ulong); #else #define get_acpi_init_status() ais_not_started #define acpi_mod_init_tables() #define acpi_set_root_pointer(...) #endif enum tristate acpi_is_8042_present(void); enum tristate acpi_is_vga_text_mode_avail(void); typedef u32 (*acpi_reg_callback)(void *); struct acpi_reg_callback_node { struct list_node node; acpi_reg_callback cb; void *ctx; }; /* * Register a callback that will be called immediately the ACPI subsystem has * been enabled at hardware level and we iterated through all the objects in * ACPI namespace. */ void acpi_reg_on_subsys_enabled_cb(struct acpi_reg_callback_node *node); /* * Register a callback that will be called once ACPI has been fully initialized. * * NOTE: any errors returned by the callbacks are IGNORED. The only reason they * are required to return an integer it to reuse the same interface used by the * acpi_reg_on_subsys_enabled_cb() function. */ void acpi_reg_on_full_init_cb(struct acpi_reg_callback_node *node); typedef u32 (*acpi_per_object_callback)(void *obj_handle, void *device_info, void *ctx); struct acpi_reg_per_object_cb_node { struct list_node node; acpi_per_object_callback cb; void *ctx; const char *hid; /* Required matching HID (if not NULL) */ const char *uid; /* Required matching UID (if not NULL) */ const char *cls; /* Required matching CLS (if not NULL) */ /* * Optional filter function. * In case filtering using the fields above is not enough a filter function * pointer can be provided. The callback `cb` will be called only when the * filter has returned true. */ bool (*filter)(void *obj_handle); }; /* * Register a callback that will be called during the first iteration over all * the objects in the ACPI namespace, immediately after the ACPI subsystem has * been enabled. */ void acpi_reg_per_object_cb(struct acpi_reg_per_object_cb_node *cbnode); /* Reboot the machine using the official ACPI method */ void acpi_reboot(void); /* Power-off the machine (transition to state ACPI S5) */ void acpi_poweroff(void); /* Get the average charge per mille of all batteries */ int acpi_get_all_batteries_charge_per_mille(ulong *ret); <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(EARLY_BOOT_SCRIPT ${CMAKE_BINARY_DIR}/boot/legacy/early_boot_script.ld) set(STAGE3_SCRIPT ${CMAKE_BINARY_DIR}/boot/legacy/stage3/linker_script.ld) set(KERNEL_SCRIPT ${CMAKE_BINARY_DIR}/kernel/arch/${ARCH}/linker_script.ld) set(MUSL_GCC ${CMAKE_BINARY_DIR}/scripts/musl-gcc) set(MUSL_GXX ${CMAKE_BINARY_DIR}/scripts/musl-g++) hex2dec(${BL_ST2_DATA_SEG} BL_ST2_DATA_SEG_DEC) math(EXPR BL_BASE_ADDR_DEC "${BL_ST2_DATA_SEG_DEC} * 16 + ${EARLY_BOOT_SZ} + ${STAGE3_ENTRY_OFF}") dec2hex(${BL_BASE_ADDR_DEC} BL_BASE_ADDR) file(GLOB config_glob ${GLOB_CONF_DEP} "${CMAKE_SOURCE_DIR}/config/*.h") foreach(config_path ${config_glob}) get_filename_component(config_name ${config_path} NAME_WE) smart_config_file( ${config_path} ${CMAKE_BINARY_DIR}/tilck_gen_headers/${config_name}.h ) endforeach() smart_config_file( ${CMAKE_SOURCE_DIR}/config/modules_list.h ${CMAKE_BINARY_DIR}/tilck_gen_headers/modules_list.h ) smart_config_file( ${CMAKE_SOURCE_DIR}/config/config_init.h ${CMAKE_BINARY_DIR}/tilck_gen_headers/config_init.h ) smart_config_file( ${CMAKE_SOURCE_DIR}/boot/legacy/early_boot_script.ld ${EARLY_BOOT_SCRIPT} ) smart_config_file( ${CMAKE_SOURCE_DIR}/kernel/arch/${ARCH}/linker_script.ld ${KERNEL_SCRIPT} ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/musl-gcc ${MUSL_GCC} ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/musl-g++ ${MUSL_GXX} ) smart_config_file( ${CMAKE_SOURCE_DIR}/tests/runners/single_test_run ${CMAKE_BINARY_DIR}/st/single_test_run ) smart_config_file( ${CMAKE_SOURCE_DIR}/tests/runners/run_all_tests ${CMAKE_BINARY_DIR}/st/run_all_tests ) smart_config_file( ${CMAKE_SOURCE_DIR}/tests/runners/run_interactive_test ${CMAKE_BINARY_DIR}/st/run_interactive_test ) smart_config_file( ${CMAKE_SOURCE_DIR}/other/cmake/config_fatpart ${CMAKE_BINARY_DIR}/config_fatpart ) smart_config_file( ${CMAKE_SOURCE_DIR}/other/tilck_unstripped-gdb.py ${CMAKE_BINARY_DIR}/tilck_unstripped-gdb.py ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/weaken_syms ${CMAKE_BINARY_DIR}/scripts/weaken_syms ) # Run qemu scripts list( APPEND run_qemu_files run_nokvm_qemu run_qemu run_multiboot_nokvm_qemu run_multiboot_qemu run_efi_nokvm_qemu64 run_efi_qemu64 debug_run_qemu ) if (${ARCH} STREQUAL "i386") list( APPEND run_qemu_files run_efi_nokvm_qemu32 run_efi_qemu32 ) endif() foreach(script_file ${run_qemu_files}) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/qemu/${script_file} ${CMAKE_BINARY_DIR}/${script_file} ) endforeach() include_directories(${CMAKE_BINARY_DIR}) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/process.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/user.h> #include <tilck/kernel/syscalls.h> #include "gdt_int.h" #include "double_fault.h" static struct gdt_entry initial_gdt_in_bss[8]; static s32 initial_gdt_refcount_in_bss[ARRAY_SIZE(initial_gdt_in_bss)]; static u32 gdt_size = ARRAY_SIZE(initial_gdt_in_bss); static struct gdt_entry *gdt = initial_gdt_in_bss; static s32 *gdt_refcount = initial_gdt_refcount_in_bss; /* * Tilck doesn't use i386's tasks because they don't exist in many * architectures. Therefore, we have just need a two tss entries: one generic * and one dedicated for the double-fault handling. * * NOTE: TSS entries do not require to be aligned at page boundary, but they * should not cross page boundaries. * * From Intel's System Programming Guide: << * Avoid placing a page boundary in the part of the TSS that the processor * reads during a task switch (the first 104 bytes). The processor may not * correctly perform address translations if a boundary occurs in this area. * During a task switch, the processor reads and writes into the first 104 * bytes of each TSS (using contiguous physical addresses beginning with the * physical address of the first byte of the TSS). So, after TSS access * begins, if part of the 104 bytes is not physically contiguous, the * processor will access incorrect information without generating a * page-fault exception. * >> */ struct tss_entry tss_array[2] ALIGNED_AT(PAGE_SIZE); static void load_gdt(struct gdt_entry *gdt, u32 entries_count); void gdt_set_entry(struct gdt_entry *e, ulong base, ulong limit, u8 access, u8 flags) { /* * This function is supposed to be used only for gdt_entry elements NOT in * gdt (like &gdt[3]). Usually, `e` is just pointer to variable on the stack * later passed as argument to set_entry_num(). */ ASSERT(!((ulong)gdt <= (ulong)e && (ulong)e < ((ulong)gdt + gdt_size))); ASSERT(limit <= GDT_LIMIT_MAX); /* limit is only 20 bits */ ASSERT(flags <= 0xf); /* flags is 4 bits */ e->base_low = (base & 0xffff); e->base_middle = (base >> 16) & 0xff; e->base_high = (base >> 24) & 0xff; e->limit_low = (limit & 0xffff); e->limit_high = (limit >> 16) & 0x0f; e->access = access; e->flags = flags & 0xf; } static void set_entry_num(u32 n, struct gdt_entry *e) { ulong var; disable_interrupts(&var); { ASSERT(n < gdt_size); ASSERT(gdt_refcount[n] >= 0); gdt[n] = *e; gdt_refcount[n]++; } enable_interrupts(&var); } void gdt_clear_entry(u32 n) { ulong var; disable_interrupts(&var); { ASSERT(n < gdt_size); ASSERT(gdt_refcount[n] > 0); if (--gdt_refcount[n] == 0) { bzero(&gdt[n], sizeof(struct gdt_entry)); } } enable_interrupts(&var); } void gdt_entry_inc_ref_count(u32 n) { ulong var; disable_interrupts(&var); { ASSERT(n < gdt_size); ASSERT(gdt_refcount[n] > 0); ASSERT(gdt[n].access); gdt_refcount[n]++; } enable_interrupts(&var); } static void set_entry_num2(u32 n, ulong base, ulong limit, u8 access, u8 flags) { struct gdt_entry e; gdt_set_entry(&e, base, limit, access, flags); set_entry_num(n, &e); } static NODISCARD int gdt_expand(void) { void *old_gdt_ptr; void *old_gdt_refcount_ptr; u32 old_gdt_size; u32 new_size; ASSERT(are_interrupts_enabled()); disable_preemption(); { old_gdt_ptr = gdt; old_gdt_refcount_ptr = gdt_refcount; old_gdt_size = gdt_size; new_size = gdt_size * 2; if (new_size > 64 * KB) { enable_preemption(); return -ENOMEM; } void *new_gdt = kzalloc_array_obj(struct gdt_entry, new_size); void *new_gdt_refcount; if (!new_gdt) { enable_preemption(); return -ENOMEM; } new_gdt_refcount = kzalloc_array_obj(s32, new_size); if (!new_gdt_refcount) { kfree2(new_gdt, new_size); enable_preemption(); return -1; } memcpy(new_gdt, gdt, sizeof(struct gdt_entry) * gdt_size); memcpy(new_gdt_refcount, gdt_refcount, sizeof(s32) * gdt_size); disable_interrupts_forced(); { gdt = new_gdt; gdt_size = new_size; gdt_refcount = new_gdt_refcount; load_gdt(new_gdt, new_size); } enable_interrupts_forced(); } enable_preemption(); if (old_gdt_ptr != initial_gdt_in_bss) { ASSERT(old_gdt_refcount_ptr != initial_gdt_refcount_in_bss); kfree_array_obj(old_gdt_ptr, struct gdt_entry, old_gdt_size); kfree_array_obj(old_gdt_refcount_ptr, s32, old_gdt_size); } return 0; } int gdt_add_entry(struct gdt_entry *e) { int rc = -1; disable_preemption(); { for (u32 n = 1; n < gdt_size; n++) { if (!gdt[n].access) { set_entry_num(n, e); rc = (int)n; break; } } } enable_preemption(); return rc; } static int gdt_add_ldt_entry(void *ldt_ptr, u32 size) { struct gdt_entry e; gdt_set_entry(&e, (ulong) ldt_ptr, size, GDT_DESC_TYPE_LDT, GDT_GRAN_BYTE | GDT_32BIT); return gdt_add_entry(&e); } void set_kernel_stack(ulong stack) { ulong var; disable_interrupts(&var); { /* Kernel stack segment = data seg */ tss_array[TSS_MAIN].ss0 = X86_KERNEL_DATA_SEL; tss_array[TSS_MAIN].esp0 = stack; wrmsr(MSR_IA32_SYSENTER_ESP, stack); } enable_interrupts(&var); } static void load_gdt(struct gdt_entry *g, u32 entries_count) { ASSERT(!are_interrupts_enabled()); ASSERT(entries_count <= 64 * KB); struct { u16 size_minus_one; struct gdt_entry *gdt_vaddr; } PACKED gdt_ptr = { (u16)(sizeof(struct gdt_entry) * entries_count - 1), g, }; asmVolatile("lgdt (%0)" : /* no output */ : "q" (&gdt_ptr) : "memory"); } void load_tss(u32 entry_index_in_gdt, u32 dpl) { ASSERT(!are_interrupts_enabled()); ASSERT(dpl <= 3); /* descriptor privilege level [0..3] */ /* * Inline assembly comments: here we need to use %w0 instead of %0 * beacuse 'ltr' requires a 16-bit register, like AX. That's what does * the 'w' modifier [https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html]. */ asmVolatile("ltr %w0" : /* no output */ : "q" (X86_SELECTOR(entry_index_in_gdt, TABLE_GDT, dpl)) : "memory"); } void init_segmentation(void) { ASSERT(!are_interrupts_enabled()); /* Our NULL descriptor */ set_entry_num2(0, 0, 0, 0, 0); /* Kernel code segment */ set_entry_num2(1, 0, /* base addr */ GDT_LIMIT_MAX, /* full 4-GB segment */ GDT_ACC_REG | GDT_ACCESS_PL0 | GDT_ACCESS_RW | GDT_ACCESS_EX, GDT_GRAN_4KB | GDT_32BIT); /* Kernel data segment */ set_entry_num2(2, 0, GDT_LIMIT_MAX, GDT_ACC_REG | GDT_ACCESS_PL0 | GDT_ACCESS_RW, GDT_GRAN_4KB | GDT_32BIT); /* Usermode code segment */ set_entry_num2(3, 0, GDT_LIMIT_MAX, GDT_ACC_REG | GDT_ACCESS_PL3 | GDT_ACCESS_RW | GDT_ACCESS_EX, GDT_GRAN_4KB | GDT_32BIT); /* Usermode data segment */ set_entry_num2(4, 0, GDT_LIMIT_MAX, GDT_ACC_REG | GDT_ACCESS_PL3 | GDT_ACCESS_RW, GDT_GRAN_4KB | GDT_32BIT); /* GDT entry for our TSS */ set_entry_num2(5, (ulong)&tss_array[TSS_MAIN], /* TSS addr */ sizeof(tss_array[TSS_MAIN]), /* limit: struct TSS size */ GDT_DESC_TYPE_TSS | GDT_ACCESS_PL0, GDT_GRAN_BYTE | GDT_32BIT); /* Register other special GDT entires */ register_double_fault_tss_entry(); /* Load the GDT */ load_gdt(gdt, gdt_size); /* Load the TSS */ load_tss(5 /* TSS index in GDT */, 0 /* priv. level */); } static void DEBUG_set_thread_area(struct user_desc *d) { printk(NO_PREFIX "set_thread_area(e: %i,\n" " base: %p,\n" " lim: %p,\n" " 32-bit: %u,\n", d->entry_number, TO_PTR(d->base_addr), TO_PTR(d->limit), d->seg_32bit); printk(NO_PREFIX " contents: %u,\n" " re_only: %u,\n" " lim in pag: %u,\n", d->contents, d->read_exec_only, d->limit_in_pages); printk(NO_PREFIX " seg_not_pres: %u,\n" " useable: %u)\n", d->seg_not_present, d->useable); } static int find_available_slot_in_user_task(void) { struct process *pi = get_curr_proc(); arch_proc_members_t *arch = get_proc_arch_fields(pi); for (int i = 0; i < ARRAY_SIZE(arch->gdt_entries); i++) if (!arch->gdt_entries[i]) return i; return -1; } static int get_user_task_slot_for_gdt_entry(u32 gdt_entry_num) { struct process *pi = get_curr_proc(); arch_proc_members_t *arch = get_proc_arch_fields(pi); for (int i = 0; i < ARRAY_SIZE(arch->gdt_entries); i++) if (arch->gdt_entries[i] == gdt_entry_num) return i; return -1; } static void gdt_set_slot(struct process *pi, u16 slot, u16 gdt_index) { get_proc_arch_fields(pi)->gdt_entries[slot] = gdt_index; } int sys_set_thread_area(void *arg) { int rc = 0; struct gdt_entry e = {0}; struct user_desc dc; struct user_desc *ud = arg; rc = copy_from_user(&dc, ud, sizeof(struct user_desc)); if (rc != 0) return -EFAULT; disable_preemption(); if (!(dc.flags == USER_DESC_FLAGS_EMPTY && !dc.base_addr && !dc.limit)) { gdt_set_entry(&e, dc.base_addr, dc.limit, 0, 0); e.s = 1; e.dpl = 3; e.d = dc.seg_32bit; e.type |= (dc.contents << 2); e.type |= !dc.read_exec_only ? GDT_ACCESS_RW : 0; e.g = dc.limit_in_pages; e.avl = dc.useable; e.p = !dc.seg_not_present; } else { /* The user passed an empty descriptor: entry_number cannot be -1 */ if (dc.entry_number == INVALID_ENTRY_NUM) { rc = -EINVAL; goto out; } } if (dc.entry_number == INVALID_ENTRY_NUM) { int slot = find_available_slot_in_user_task(); if (slot < 0) { rc = -ESRCH; goto out; } dc.entry_number = (u32)gdt_add_entry(&e); if (dc.entry_number == INVALID_ENTRY_NUM) { rc = gdt_expand(); if (rc < 0) { rc = -ESRCH; goto out; } dc.entry_number = (u32)gdt_add_entry(&e); ASSERT(dc.entry_number != INVALID_ENTRY_NUM); } gdt_set_slot(get_curr_proc(), (u16)slot, (u16)dc.entry_number); goto out; } /* Handling the case where the user specified a GDT entry number */ int slot = get_user_task_slot_for_gdt_entry(dc.entry_number); if (slot < 0) { /* A GDT entry with that index has never been allocated by this task */ if (dc.entry_number >= gdt_size || gdt[dc.entry_number].access) { /* The entry is out-of-bounds or it's used by another task */ rc = -EINVAL; goto out; } /* The entry is available, now find a slot */ slot = find_available_slot_in_user_task(); if (slot < 0) { /* Unable to find a free slot in this struct task struct */ rc = -ESRCH; goto out; } gdt_set_slot(get_curr_proc(), (u16)slot, (u16)dc.entry_number); } ASSERT(dc.entry_number < gdt_size); set_entry_num(dc.entry_number, &e); /* * We're here because either we found a slot already containing this index * (therefore it must be valid) or the index is in-bounds and it is free. */ out: enable_preemption(); if (!rc) { /* * Positive case: we get here with rc = SUCCESS, now flush back the * the struct user_desc (we might have changed its entry_number). */ rc = copy_to_user(ud, &dc, sizeof(struct user_desc)); if (rc < 0) rc = -EFAULT; } return rc; } void copy_main_tss_on_regs(regs_t *ctx) { *ctx = (regs_t) { .kernel_resume_eip = 0, .custom_flags = 0, .gs = tss_array[TSS_MAIN].gs, .fs = tss_array[TSS_MAIN].fs, .es = tss_array[TSS_MAIN].es, .ds = tss_array[TSS_MAIN].ds, .edi = tss_array[TSS_MAIN].edi, .esi = tss_array[TSS_MAIN].esi, .ebp = tss_array[TSS_MAIN].ebp, .esp = tss_array[TSS_MAIN].esp, .ebx = tss_array[TSS_MAIN].ebx, .edx = tss_array[TSS_MAIN].edx, .ecx = tss_array[TSS_MAIN].ecx, .eax = tss_array[TSS_MAIN].eax, .int_num = 0, .err_code = 0, .eip = tss_array[TSS_MAIN].eip, .cs = tss_array[TSS_MAIN].cs, .eflags = tss_array[TSS_MAIN].eflags, .useresp = tss_array[TSS_MAIN].esp, .ss = tss_array[TSS_MAIN].ss0, }; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define DMA8_SINGLE_CH_MASK_REG 0x0A #define DMA16_SINGLE_CH_MASK_REG 0xD4 #define DMA8_MODE_REG 0x0B #define DMA16_MODE_REG 0xD6 #define DMA8_RST_FLIP_FLOP 0x0C #define DMA16_RST_FLIP_FLOP 0xD8 /* Flags for DMA8_MODE_REG */ #define DMA_DEMAND_MODE 0b00000000 /* Bits 7:6 */ #define DMA_SINGLE_MODE 0b01000000 /* Bits 7:6 */ #define DMA_BLOCK_MODE 0b10000000 /* Bits 7:6 */ #define DMA_CASCADE_MODE 0b11000000 /* Bits 7:6 */ #define DMA_ADDR_INC 0b00000000 /* Bit 5 */ #define DMA_ADDR_DEC 0b00100000 /* Bit 5 */ #define DMA_SINGLE_CYCLE 0b00000000 /* Bit 4 */ #define DMA_AUTO_INIT 0b00010000 /* Bit 4 */ #define DMA_VERIFY_TX 0b00000000 /* Bits 3:2 */ #define DMA_WRITE_TX 0b00000100 /* Bits 3:2 */ #define DMA_READ_TX 0b00001000 /* Bits 3:2 */ /* DMA_CHANNEL_0 is unusable */ #define DMA_CHANNEL_1 0b00000001 /* Bits 1:0 */ #define DMA_CHANNEL_2 0b00000010 /* Bits 1:0 */ #define DMA_CHANNEL_3 0b00000011 /* Bits 1:0 */ /* DMA_CHANNEL_4 is unusable */ #define DMA_CHANNEL_5 0b00000001 /* Bits 1:0 */ #define DMA_CHANNEL_6 0b00000010 /* Bits 1:0 */ #define DMA_CHANNEL_7 0b00000011 /* Bits 1:0 */ /* Flags for SINGLE_CH_MASK_REG */ #define DMA_MASK_CHANNEL 0b00000100 /* DMA channels "page" address registers */ /* DMA_CHANNEL_0 is unusable */ #define DMA_CHANNEL_1_PAGE_REG 0x83 #define DMA_CHANNEL_2_PAGE_REG 0x81 #define DMA_CHANNEL_3_PAGE_REG 0x82 /* DMA_CHANNEL_4 is unusable */ #define DMA_CHANNEL_5_PAGE_REG 0x8B #define DMA_CHANNEL_6_PAGE_REG 0x89 #define DMA_CHANNEL_7_PAGE_REG 0x8A /* DMA start/count registers */ #define DMA_CHANNEL_1_START_REG 0x02 #define DMA_CHANNEL_1_COUNT_REG 0x03 #define DMA_CHANNEL_2_START_REG 0x04 #define DMA_CHANNEL_2_COUNT_REG 0x05 #define DMA_CHANNEL_3_START_REG 0x06 #define DMA_CHANNEL_3_COUNT_REG 0x07 #define DMA_CHANNEL_5_START_REG 0xC4 #define DMA_CHANNEL_5_COUNT_REG 0xC6 #define DMA_CHANNEL_6_START_REG 0xC8 #define DMA_CHANNEL_6_COUNT_REG 0xCA #define DMA_CHANNEL_7_START_REG 0xCC #define DMA_CHANNEL_7_COUNT_REG 0xCE <file_sep>/****************************************************************************** * * Module Name: dsmethod - Parser/Interpreter interface - control method parsing * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acparser.h" #include "amlcode.h" #include "acdebug.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsmethod") /* Local prototypes */ static ACPI_STATUS AcpiDsDetectNamedOpcodes ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **OutOp); static ACPI_STATUS AcpiDsCreateMethodMutex ( ACPI_OPERAND_OBJECT *MethodDesc); /******************************************************************************* * * FUNCTION: AcpiDsAutoSerializeMethod * * PARAMETERS: Node - Namespace Node of the method * ObjDesc - Method object attached to node * * RETURN: Status * * DESCRIPTION: Parse a control method AML to scan for control methods that * need serialization due to the creation of named objects. * * NOTE: It is a bit of overkill to mark all such methods serialized, since * there is only a problem if the method actually blocks during execution. * A blocking operation is, for example, a Sleep() operation, or any access * to an operation region. However, it is probably not possible to easily * detect whether a method will block or not, so we simply mark all suspicious * methods as serialized. * * NOTE2: This code is essentially a generic routine for parsing a single * control method. * ******************************************************************************/ ACPI_STATUS AcpiDsAutoSerializeMethod ( ACPI_NAMESPACE_NODE *Node, ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_STATUS Status; ACPI_PARSE_OBJECT *Op = NULL; ACPI_WALK_STATE *WalkState; ACPI_FUNCTION_TRACE_PTR (DsAutoSerializeMethod, Node); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Method auto-serialization parse [%4.4s] %p\n", AcpiUtGetNodeName (Node), Node)); /* Create/Init a root op for the method parse tree */ Op = AcpiPsAllocOp (AML_METHOD_OP, ObjDesc->Method.AmlStart); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } AcpiPsSetName (Op, Node->Name.Integer); Op->Common.Node = Node; /* Create and initialize a new walk state */ WalkState = AcpiDsCreateWalkState (Node->OwnerId, NULL, NULL, NULL); if (!WalkState) { AcpiPsFreeOp (Op); return_ACPI_STATUS (AE_NO_MEMORY); } Status = AcpiDsInitAmlWalk (WalkState, Op, Node, ObjDesc->Method.AmlStart, ObjDesc->Method.AmlLength, NULL, 0); if (ACPI_FAILURE (Status)) { AcpiDsDeleteWalkState (WalkState); AcpiPsFreeOp (Op); return_ACPI_STATUS (Status); } WalkState->DescendingCallback = AcpiDsDetectNamedOpcodes; /* Parse the method, scan for creation of named objects */ Status = AcpiPsParseAml (WalkState); AcpiPsDeleteParseTree (Op); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsDetectNamedOpcodes * * PARAMETERS: WalkState - Current state of the parse tree walk * OutOp - Unused, required for parser interface * * RETURN: Status * * DESCRIPTION: Descending callback used during the loading of ACPI tables. * Currently used to detect methods that must be marked serialized * in order to avoid problems with the creation of named objects. * ******************************************************************************/ static ACPI_STATUS AcpiDsDetectNamedOpcodes ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **OutOp) { ACPI_FUNCTION_NAME (AcpiDsDetectNamedOpcodes); /* We are only interested in opcodes that create a new name */ if (!(WalkState->OpInfo->Flags & (AML_NAMED | AML_CREATE | AML_FIELD))) { return (AE_OK); } /* * At this point, we know we have a Named object opcode. * Mark the method as serialized. Later code will create a mutex for * this method to enforce serialization. * * Note, ACPI_METHOD_IGNORE_SYNC_LEVEL flag means that we will ignore the * Sync Level mechanism for this method, even though it is now serialized. * Otherwise, there can be conflicts with existing ASL code that actually * uses sync levels. */ WalkState->MethodDesc->Method.SyncLevel = 0; WalkState->MethodDesc->Method.InfoFlags |= (ACPI_METHOD_SERIALIZED | ACPI_METHOD_IGNORE_SYNC_LEVEL); ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Method serialized [%4.4s] %p - [%s] (%4.4X)\n", WalkState->MethodNode->Name.Ascii, WalkState->MethodNode, WalkState->OpInfo->Name, WalkState->Opcode)); /* Abort the parse, no need to examine this method any further */ return (AE_CTRL_TERMINATE); } /******************************************************************************* * * FUNCTION: AcpiDsMethodError * * PARAMETERS: Status - Execution status * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Called on method error. Invoke the global exception handler if * present, dump the method data if the debugger is configured * * Note: Allows the exception handler to change the status code * ******************************************************************************/ ACPI_STATUS AcpiDsMethodError ( ACPI_STATUS Status, ACPI_WALK_STATE *WalkState) { UINT32 AmlOffset; ACPI_NAME Name = 0; ACPI_FUNCTION_ENTRY (); /* Ignore AE_OK and control exception codes */ if (ACPI_SUCCESS (Status) || (Status & AE_CODE_CONTROL)) { return (Status); } /* Invoke the global exception handler */ if (AcpiGbl_ExceptionHandler) { /* Exit the interpreter, allow handler to execute methods */ AcpiExExitInterpreter (); /* * Handler can map the exception code to anything it wants, including * AE_OK, in which case the executing method will not be aborted. */ AmlOffset = (UINT32) ACPI_PTR_DIFF (WalkState->Aml, WalkState->ParserState.AmlStart); if (WalkState->MethodNode) { Name = WalkState->MethodNode->Name.Integer; } else if (WalkState->DeferredNode) { Name = WalkState->DeferredNode->Name.Integer; } Status = AcpiGbl_ExceptionHandler (Status, Name, WalkState->Opcode, AmlOffset, NULL); AcpiExEnterInterpreter (); } AcpiDsClearImplicitReturn (WalkState); if (ACPI_FAILURE (Status)) { AcpiDsDumpMethodStack (Status, WalkState, WalkState->Op); /* Display method locals/args if debugger is present */ #ifdef ACPI_DEBUGGER AcpiDbDumpMethodInfo (Status, WalkState); #endif } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDsCreateMethodMutex * * PARAMETERS: ObjDesc - The method object * * RETURN: Status * * DESCRIPTION: Create a mutex object for a serialized control method * ******************************************************************************/ static ACPI_STATUS AcpiDsCreateMethodMutex ( ACPI_OPERAND_OBJECT *MethodDesc) { ACPI_OPERAND_OBJECT *MutexDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (DsCreateMethodMutex); /* Create the new mutex object */ MutexDesc = AcpiUtCreateInternalObject (ACPI_TYPE_MUTEX); if (!MutexDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Create the actual OS Mutex */ Status = AcpiOsCreateMutex (&MutexDesc->Mutex.OsMutex); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (MutexDesc); return_ACPI_STATUS (Status); } MutexDesc->Mutex.SyncLevel = MethodDesc->Method.SyncLevel; MethodDesc->Method.Mutex = MutexDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsBeginMethodExecution * * PARAMETERS: MethodNode - Node of the method * ObjDesc - The method object * WalkState - current state, NULL if not yet executing * a method. * * RETURN: Status * * DESCRIPTION: Prepare a method for execution. Parses the method if necessary, * increments the thread count, and waits at the method semaphore * for clearance to execute. * ******************************************************************************/ ACPI_STATUS AcpiDsBeginMethodExecution ( ACPI_NAMESPACE_NODE *MethodNode, ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (DsBeginMethodExecution, MethodNode); if (!MethodNode) { return_ACPI_STATUS (AE_NULL_ENTRY); } AcpiExStartTraceMethod (MethodNode, ObjDesc, WalkState); /* Prevent wraparound of thread count */ if (ObjDesc->Method.ThreadCount == ACPI_UINT8_MAX) { ACPI_ERROR ((AE_INFO, "Method reached maximum reentrancy limit (255)")); return_ACPI_STATUS (AE_AML_METHOD_LIMIT); } /* * If this method is serialized, we need to acquire the method mutex. */ if (ObjDesc->Method.InfoFlags & ACPI_METHOD_SERIALIZED) { /* * Create a mutex for the method if it is defined to be Serialized * and a mutex has not already been created. We defer the mutex creation * until a method is actually executed, to minimize the object count */ if (!ObjDesc->Method.Mutex) { Status = AcpiDsCreateMethodMutex (ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* * The CurrentSyncLevel (per-thread) must be less than or equal to * the sync level of the method. This mechanism provides some * deadlock prevention. * * If the method was auto-serialized, we just ignore the sync level * mechanism, because auto-serialization of methods can interfere * with ASL code that actually uses sync levels. * * Top-level method invocation has no walk state at this point */ if (WalkState && (!(ObjDesc->Method.InfoFlags & ACPI_METHOD_IGNORE_SYNC_LEVEL)) && (WalkState->Thread->CurrentSyncLevel > ObjDesc->Method.Mutex->Mutex.SyncLevel)) { ACPI_ERROR ((AE_INFO, "Cannot acquire Mutex for method [%4.4s]" ", current SyncLevel is too large (%u)", AcpiUtGetNodeName (MethodNode), WalkState->Thread->CurrentSyncLevel)); return_ACPI_STATUS (AE_AML_MUTEX_ORDER); } /* * Obtain the method mutex if necessary. Do not acquire mutex for a * recursive call. */ if (!WalkState || !ObjDesc->Method.Mutex->Mutex.ThreadId || (WalkState->Thread->ThreadId != ObjDesc->Method.Mutex->Mutex.ThreadId)) { /* * Acquire the method mutex. This releases the interpreter if we * block (and reacquires it before it returns) */ Status = AcpiExSystemWaitMutex ( ObjDesc->Method.Mutex->Mutex.OsMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Update the mutex and walk info and save the original SyncLevel */ if (WalkState) { ObjDesc->Method.Mutex->Mutex.OriginalSyncLevel = WalkState->Thread->CurrentSyncLevel; ObjDesc->Method.Mutex->Mutex.ThreadId = WalkState->Thread->ThreadId; /* * Update the current SyncLevel only if this is not an auto- * serialized method. In the auto case, we have to ignore * the sync level for the method mutex (created for the * auto-serialization) because we have no idea of what the * sync level should be. Therefore, just ignore it. */ if (!(ObjDesc->Method.InfoFlags & ACPI_METHOD_IGNORE_SYNC_LEVEL)) { WalkState->Thread->CurrentSyncLevel = ObjDesc->Method.SyncLevel; } } else { ObjDesc->Method.Mutex->Mutex.OriginalSyncLevel = ObjDesc->Method.Mutex->Mutex.SyncLevel; ObjDesc->Method.Mutex->Mutex.ThreadId = AcpiOsGetThreadId (); } } /* Always increase acquisition depth */ ObjDesc->Method.Mutex->Mutex.AcquisitionDepth++; } /* * Allocate an Owner ID for this method, only if this is the first thread * to begin concurrent execution. We only need one OwnerId, even if the * method is invoked recursively. */ if (!ObjDesc->Method.OwnerId) { Status = AcpiUtAllocateOwnerId (&ObjDesc->Method.OwnerId); if (ACPI_FAILURE (Status)) { goto Cleanup; } } /* * Increment the method parse tree thread count since it has been * reentered one more time (even if it is the same thread) */ ObjDesc->Method.ThreadCount++; AcpiMethodCount++; return_ACPI_STATUS (Status); Cleanup: /* On error, must release the method mutex (if present) */ if (ObjDesc->Method.Mutex) { AcpiOsReleaseMutex (ObjDesc->Method.Mutex->Mutex.OsMutex); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsCallControlMethod * * PARAMETERS: Thread - Info for this thread * ThisWalkState - Current walk state * Op - Current Op to be walked * * RETURN: Status * * DESCRIPTION: Transfer execution to a called control method * ******************************************************************************/ ACPI_STATUS AcpiDsCallControlMethod ( ACPI_THREAD_STATE *Thread, ACPI_WALK_STATE *ThisWalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *MethodNode; ACPI_WALK_STATE *NextWalkState = NULL; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_EVALUATE_INFO *Info; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCallControlMethod, ThisWalkState); ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Calling method %p, currentstate=%p\n", ThisWalkState->PrevOp, ThisWalkState)); /* * Get the namespace entry for the control method we are about to call */ MethodNode = ThisWalkState->MethodCallNode; if (!MethodNode) { return_ACPI_STATUS (AE_NULL_ENTRY); } ObjDesc = AcpiNsGetAttachedObject (MethodNode); if (!ObjDesc) { return_ACPI_STATUS (AE_NULL_OBJECT); } /* Init for new method, possibly wait on method mutex */ Status = AcpiDsBeginMethodExecution ( MethodNode, ObjDesc, ThisWalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Begin method parse/execution. Create a new walk state */ NextWalkState = AcpiDsCreateWalkState ( ObjDesc->Method.OwnerId, NULL, ObjDesc, Thread); if (!NextWalkState) { Status = AE_NO_MEMORY; goto Cleanup; } /* * The resolved arguments were put on the previous walk state's operand * stack. Operands on the previous walk state stack always * start at index 0. Also, null terminate the list of arguments */ ThisWalkState->Operands [ThisWalkState->NumOperands] = NULL; /* * Allocate and initialize the evaluation information block * TBD: this is somewhat inefficient, should change interface to * DsInitAmlWalk. For now, keeps this struct off the CPU stack */ Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { Status = AE_NO_MEMORY; goto Cleanup; } Info->Parameters = &ThisWalkState->Operands[0]; Status = AcpiDsInitAmlWalk (NextWalkState, NULL, MethodNode, ObjDesc->Method.AmlStart, ObjDesc->Method.AmlLength, Info, ACPI_IMODE_EXECUTE); ACPI_FREE (Info); if (ACPI_FAILURE (Status)) { goto Cleanup; } NextWalkState->MethodNestingDepth = ThisWalkState->MethodNestingDepth + 1; /* * Delete the operands on the previous walkstate operand stack * (they were copied to new objects) */ for (i = 0; i < ObjDesc->Method.ParamCount; i++) { AcpiUtRemoveReference (ThisWalkState->Operands [i]); ThisWalkState->Operands [i] = NULL; } /* Clear the operand stack */ ThisWalkState->NumOperands = 0; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "**** Begin nested execution of [%4.4s] **** WalkState=%p\n", MethodNode->Name.Ascii, NextWalkState)); ThisWalkState->MethodPathname = AcpiNsGetNormalizedPathname (MethodNode, TRUE); ThisWalkState->MethodIsNested = TRUE; /* Optional object evaluation log */ ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EVALUATION, "%-26s: %*s%s\n", " Nested method call", NextWalkState->MethodNestingDepth * 3, " ", &ThisWalkState->MethodPathname[1])); /* Invoke an internal method if necessary */ if (ObjDesc->Method.InfoFlags & ACPI_METHOD_INTERNAL_ONLY) { Status = ObjDesc->Method.Dispatch.Implementation (NextWalkState); if (Status == AE_OK) { Status = AE_CTRL_TERMINATE; } } return_ACPI_STATUS (Status); Cleanup: /* On error, we must terminate the method properly */ AcpiDsTerminateControlMethod (ObjDesc, NextWalkState); AcpiDsDeleteWalkState (NextWalkState); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsRestartControlMethod * * PARAMETERS: WalkState - State for preempted method (caller) * ReturnDesc - Return value from the called method * * RETURN: Status * * DESCRIPTION: Restart a method that was preempted by another (nested) method * invocation. Handle the return value (if any) from the callee. * ******************************************************************************/ ACPI_STATUS AcpiDsRestartControlMethod ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT *ReturnDesc) { ACPI_STATUS Status; int SameAsImplicitReturn; ACPI_FUNCTION_TRACE_PTR (DsRestartControlMethod, WalkState); ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "****Restart [%4.4s] Op %p ReturnValueFromCallee %p\n", AcpiUtGetNodeName (WalkState->MethodNode), WalkState->MethodCallOp, ReturnDesc)); ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, " ReturnFromThisMethodUsed?=%X ResStack %p Walk %p\n", WalkState->ReturnUsed, WalkState->Results, WalkState)); /* Did the called method return a value? */ if (ReturnDesc) { /* Is the implicit return object the same as the return desc? */ SameAsImplicitReturn = (WalkState->ImplicitReturnObj == ReturnDesc); /* Are we actually going to use the return value? */ if (WalkState->ReturnUsed) { /* Save the return value from the previous method */ Status = AcpiDsResultPush (ReturnDesc, WalkState); if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (ReturnDesc); return_ACPI_STATUS (Status); } /* * Save as THIS method's return value in case it is returned * immediately to yet another method */ WalkState->ReturnDesc = ReturnDesc; } /* * The following code is the optional support for the so-called * "implicit return". Some AML code assumes that the last value of the * method is "implicitly" returned to the caller, in the absence of an * explicit return value. * * Just save the last result of the method as the return value. * * NOTE: this is optional because the ASL language does not actually * support this behavior. */ else if (!AcpiDsDoImplicitReturn (ReturnDesc, WalkState, FALSE) || SameAsImplicitReturn) { /* * Delete the return value if it will not be used by the * calling method or remove one reference if the explicit return * is the same as the implicit return value. */ AcpiUtRemoveReference (ReturnDesc); } } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsTerminateControlMethod * * PARAMETERS: MethodDesc - Method object * WalkState - State associated with the method * * RETURN: None * * DESCRIPTION: Terminate a control method. Delete everything that the method * created, delete all locals and arguments, and delete the parse * tree if requested. * * MUTEX: Interpreter is locked * ******************************************************************************/ void AcpiDsTerminateControlMethod ( ACPI_OPERAND_OBJECT *MethodDesc, ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_TRACE_PTR (DsTerminateControlMethod, WalkState); /* MethodDesc is required, WalkState is optional */ if (!MethodDesc) { return_VOID; } if (WalkState) { /* Delete all arguments and locals */ AcpiDsMethodDataDeleteAll (WalkState); /* * Delete any namespace objects created anywhere within the * namespace by the execution of this method. Unless: * 1) This method is a module-level executable code method, in which * case we want make the objects permanent. * 2) There are other threads executing the method, in which case we * will wait until the last thread has completed. */ if (!(MethodDesc->Method.InfoFlags & ACPI_METHOD_MODULE_LEVEL) && (MethodDesc->Method.ThreadCount == 1)) { /* Delete any direct children of (created by) this method */ (void) AcpiExExitInterpreter (); AcpiNsDeleteNamespaceSubtree (WalkState->MethodNode); (void) AcpiExEnterInterpreter (); /* * Delete any objects that were created by this method * elsewhere in the namespace (if any were created). * Use of the ACPI_METHOD_MODIFIED_NAMESPACE optimizes the * deletion such that we don't have to perform an entire * namespace walk for every control method execution. */ if (MethodDesc->Method.InfoFlags & ACPI_METHOD_MODIFIED_NAMESPACE) { (void) AcpiExExitInterpreter (); AcpiNsDeleteNamespaceByOwner (MethodDesc->Method.OwnerId); (void) AcpiExEnterInterpreter (); MethodDesc->Method.InfoFlags &= ~ACPI_METHOD_MODIFIED_NAMESPACE; } } /* * If method is serialized, release the mutex and restore the * current sync level for this thread */ if (MethodDesc->Method.Mutex) { /* Acquisition Depth handles recursive calls */ MethodDesc->Method.Mutex->Mutex.AcquisitionDepth--; if (!MethodDesc->Method.Mutex->Mutex.AcquisitionDepth) { WalkState->Thread->CurrentSyncLevel = MethodDesc->Method.Mutex->Mutex.OriginalSyncLevel; AcpiOsReleaseMutex ( MethodDesc->Method.Mutex->Mutex.OsMutex); MethodDesc->Method.Mutex->Mutex.ThreadId = 0; } } } /* Decrement the thread count on the method */ if (MethodDesc->Method.ThreadCount) { MethodDesc->Method.ThreadCount--; } else { ACPI_ERROR ((AE_INFO, "Invalid zero thread count in method")); } /* Are there any other threads currently executing this method? */ if (MethodDesc->Method.ThreadCount) { /* * Additional threads. Do not release the OwnerId in this case, * we immediately reuse it for the next thread executing this method */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "*** Completed execution of one thread, %u threads remaining\n", MethodDesc->Method.ThreadCount)); } else { /* This is the only executing thread for this method */ /* * Support to dynamically change a method from NotSerialized to * Serialized if it appears that the method is incorrectly written and * does not support multiple thread execution. The best example of this * is if such a method creates namespace objects and blocks. A second * thread will fail with an AE_ALREADY_EXISTS exception. * * This code is here because we must wait until the last thread exits * before marking the method as serialized. */ if (MethodDesc->Method.InfoFlags & ACPI_METHOD_SERIALIZED_PENDING) { if (WalkState) { ACPI_INFO (( "Marking method %4.4s as Serialized " "because of AE_ALREADY_EXISTS error", WalkState->MethodNode->Name.Ascii)); } /* * Method tried to create an object twice and was marked as * "pending serialized". The probable cause is that the method * cannot handle reentrancy. * * The method was created as NotSerialized, but it tried to create * a named object and then blocked, causing the second thread * entrance to begin and then fail. Workaround this problem by * marking the method permanently as Serialized when the last * thread exits here. */ MethodDesc->Method.InfoFlags &= ~ACPI_METHOD_SERIALIZED_PENDING; MethodDesc->Method.InfoFlags |= (ACPI_METHOD_SERIALIZED | ACPI_METHOD_IGNORE_SYNC_LEVEL); MethodDesc->Method.SyncLevel = 0; } /* No more threads, we can free the OwnerId */ if (!(MethodDesc->Method.InfoFlags & ACPI_METHOD_MODULE_LEVEL)) { AcpiUtReleaseOwnerId (&MethodDesc->Method.OwnerId); } } AcpiExStopTraceMethod ((ACPI_NAMESPACE_NODE *) MethodDesc->Method.Node, MethodDesc, WalkState); return_VOID; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <stdbool.h> #include <fcntl.h> #include <linux/fb.h> #include <linux/kd.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <unistd.h> #include <time.h> #define FB_DEVICE "/dev/fb0" #define TTY_DEVICE "/dev/tty" #define FB_ASSUMPTION(x) \ if (!(x)) { \ fprintf(stderr, "fb mode assumption '%s' failed\n", #x); \ return false; \ } static struct fb_var_screeninfo fbi; static struct fb_fix_screeninfo fb_fixinfo; static char *buffer; static size_t fb_size; static size_t fb_pitch; static size_t fb_pitch_div4; static int fbfd = -1, ttyfd = -1; static inline void memset32(void *s, uint32_t val, size_t n) { for (size_t i = 0; i < n; i++) ((volatile uint32_t*)s)[i] = val; } static inline uint32_t make_color(uint8_t red, uint8_t green, uint8_t blue) { return red << fbi.red.offset | green << fbi.green.offset | blue << fbi.blue.offset; } static inline void set_pixel(uint32_t x, uint32_t y, uint32_t color) { ((volatile uint32_t *)buffer)[x + y * fb_pitch_div4] = color; } static void clear_screen(uint32_t color) { memset32(buffer, color, fb_size >> 2); } static void fill_rect(uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint32_t color) { for (uint32_t cy = y; cy < y + h; cy++) memset32(buffer + cy * fb_pitch + (x << 2), color, w); } static bool check_fb_assumptions(void) { FB_ASSUMPTION(fbi.bits_per_pixel == 32); FB_ASSUMPTION((fbi.red.offset % 8) == 0); FB_ASSUMPTION((fbi.green.offset % 8) == 0); FB_ASSUMPTION((fbi.blue.offset % 8) == 0); FB_ASSUMPTION((fbi.transp.offset % 8) == 0); FB_ASSUMPTION(fbi.red.length == 8); FB_ASSUMPTION(fbi.green.length == 8); FB_ASSUMPTION(fbi.blue.length == 8); FB_ASSUMPTION(fbi.transp.length == 0); FB_ASSUMPTION(fbi.xoffset == 0); FB_ASSUMPTION(fbi.yoffset == 0); FB_ASSUMPTION(fbi.red.msb_right == 0); FB_ASSUMPTION(fbi.green.msb_right == 0); FB_ASSUMPTION(fbi.blue.msb_right == 0); return true; } static bool fb_acquire(void) { fbfd = open(FB_DEVICE, O_RDWR); if (fbfd < 0) { fprintf(stderr, "unable to open '%s'\n", FB_DEVICE); return false; } if (ioctl(fbfd, FBIOGET_FSCREENINFO, &fb_fixinfo) != 0) { fprintf(stderr, "ioctl(FBIOGET_FSCREENINFO) failed\n"); return false; } if (ioctl (fbfd, FBIOGET_VSCREENINFO, &fbi) != 0) { fprintf(stderr, "ioctl(FBIOGET_VSCREENINFO) failed\n"); return false; } fb_pitch = fb_fixinfo.line_length; fb_size = fb_pitch * fbi.yres; fb_pitch_div4 = fb_pitch >> 2; if (!check_fb_assumptions()) return false; ttyfd = open(TTY_DEVICE, O_RDWR); if (ttyfd < 0) { fprintf(stderr, "Unable to open '%s'\n", TTY_DEVICE); return false; } if (ioctl(ttyfd, KDSETMODE, KD_GRAPHICS) != 0) { fprintf(stderr, "WARNING: unable set tty into " "graphics mode on '%s'\n", TTY_DEVICE); } buffer = mmap(0, fb_size, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0); if (buffer == MAP_FAILED) { fprintf(stderr, "Unable to mmap framebuffer '%s'\n", FB_DEVICE); return false; } return true; } static void fb_release(void) { if (buffer) munmap(buffer, fb_size); if (ttyfd != -1) { ioctl(ttyfd, KDSETMODE, KD_TEXT); close(ttyfd); } if (fbfd != -1) close(fbfd); } static void draw_something(void) { clear_screen(make_color(0, 0, 0)); fill_rect(50, 50, 100, 100, make_color(255, 0, 0)); fill_rect(50 + 100, 50, 100, 100, make_color(0, 255, 0)); fill_rect(50 + 200, 50, 100, 100, make_color(0, 0, 255)); } static void dump_fb_fix_info(void) { fbfd = open(FB_DEVICE, O_RDWR); if (fbfd < 0) { fprintf(stderr, "unable to open '%s'\n", FB_DEVICE); return; } if (ioctl(fbfd, FBIOGET_FSCREENINFO, &fb_fixinfo) != 0) { fprintf(stderr, "ioctl(FBIOGET_FSCREENINFO) failed\n"); return; } printf("id: %s\n", fb_fixinfo.id); printf("smem_start: %p\n", (void *)fb_fixinfo.smem_start); printf("smem_len: %u\n", fb_fixinfo.smem_len); printf("type: %u\n", fb_fixinfo.type); printf("visual: %u\n", fb_fixinfo.visual); printf("xpanstep: %u\n", fb_fixinfo.xpanstep); printf("ypanstep: %u\n", fb_fixinfo.ypanstep); printf("ywrapstep: %u\n", fb_fixinfo.ywrapstep); printf("line_length: %u\n", fb_fixinfo.line_length); printf("mmio_start: %p\n", (void *)fb_fixinfo.mmio_start); printf("mmio_len: %u\n", fb_fixinfo.mmio_len); } static void dump_fb_var_info(void) { fbfd = open(FB_DEVICE, O_RDWR); if (fbfd < 0) { fprintf(stderr, "unable to open '%s'\n", FB_DEVICE); return; } if (ioctl (fbfd, FBIOGET_VSCREENINFO, &fbi) != 0) { fprintf(stderr, "ioctl(FBIOGET_VSCREENINFO) failed\n"); return; } printf("xres: %u\n", fbi.xres); printf("yres: %u\n", fbi.yres); printf("xres_virtual: %u\n", fbi.xres_virtual); printf("yres_virtual: %u\n", fbi.yres_virtual); printf("height (mm): %u\n", fbi.height); printf("width (mm): %u\n", fbi.width); printf("pixclock (ps): %u\n", fbi.pixclock); printf("red:\n"); printf(" offset: %u\n", fbi.red.offset); printf(" length: %u\n", fbi.red.length); printf(" msb_right: %u\n", fbi.red.msb_right); printf("green:\n"); printf(" offset: %u\n", fbi.green.offset); printf(" length: %u\n", fbi.green.length); printf(" msb_right: %u\n", fbi.green.msb_right); printf("blue:\n"); printf(" offset: %u\n", fbi.blue.offset); printf(" length: %u\n", fbi.blue.length); printf(" msb_right: %u\n", fbi.blue.msb_right); } int main(int argc, char **argv) { if (argc > 1) { if (!strcmp(argv[1], "-fi")) dump_fb_fix_info(); else if (!strcmp(argv[1], "-vi")) dump_fb_var_info(); else printf("Unknown option '%s'\n", argv[1]); return 0; } if (!fb_acquire()) { fb_release(); return 1; } draw_something(); getchar(); fb_release(); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/fat32_base.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/fs/vfs_base.h> struct fat_fs_device_data { struct fat_hdr *hdr; /* vaddr of the beginning of the FAT partition */ enum fat_type type; u32 cluster_size; u32 root_cluster; bool mmap_support; /* * A pointer to root directory's entries. Notice that this isn't a random * choice: the first entry in the root directory the is "Volume ID" entry, * which has some of the traits of regular dir entries, but it doesn't have * the cluster information (we cannot pass it to fat_get_first_cluster()), * so it still requires to be treated in a special way. That's the main * reason for calling this member `root_dir_entries` and not `root_entry` * as in the past: because it does not complain a 100% with the idea of a * regular fat_entry. */ struct fat_entry *root_dir_entries; }; struct fatfs_handle { /* struct fs_handle_base */ FS_HANDLE_BASE_FIELDS /* fs-specific members */ struct fat_entry *e; u32 curr_cluster; }; STATIC_ASSERT(sizeof(struct fatfs_handle) <= MAX_FS_HANDLE_SIZE); struct mnt_fs *fat_mount_ramdisk(void *vaddr, size_t rd_size, u32 flags); void fat_umount_ramdisk(struct mnt_fs *fs); struct datetime fat_datetime_to_regular_datetime(u16 date, u16 time, u8 timetenth); /* * On FAT, there are no inodes and dir entries. Just dir entries. * Therefore, what is called `inode` in VFS will be a `entry` here. * The `dir_entry` instead will be unused. */ #define inode entry #define dir_inode parent_entry #define dir_entry unused CREATE_FS_PATH_STRUCT(fat_fs_path, struct fat_entry *, void *); #undef inode #undef dir_inode #undef dir_entry <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/fs/fat32.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/user.h> #include <dirent.h> // system header int fat_mmap(struct user_mapping *um, pdir_t *pdir, int flags); int fat_munmap(struct user_mapping *um, void *vaddrp, size_t len); int fat_ramdisk_prepare_for_mmap(struct fat_fs_device_data *d, size_t rd_size); /* * Special fat_walk() wrapper handling the special case where `e` is NOT a dir * entry but a pointer to the entries in the root directory. */ static inline int fat_fs_walk_generic(struct fat_fs_device_data *d, struct fat_walk_static_params *static_walk_params, struct fat_entry *e) { return fat_walk(static_walk_params, e == d->root_dir_entries ? d->root_cluster : fat_get_first_cluster(e)); } STATIC ssize_t fat_read(fs_handle handle, char *buf, size_t bufsize, offt *pos) { struct fatfs_handle *h = (struct fatfs_handle *) handle; struct fat_fs_device_data *d = h->fs->device_data; offt fsize = (offt)h->e->DIR_FileSize; offt written_to_buf = 0; if (pos != &h->h_fpos) { /* * We don't support pread() for this filesystem, at the moment. * TODO: make fat32 support pread64(). */ return -EPERM; } if (h->e->directory) return -EISDIR; if (*pos >= fsize) { /* * The cursor is at the end or past the end: nothing to read. */ return 0; } do { char *data = fat_get_pointer_to_cluster_data(d->hdr, h->curr_cluster); const offt file_rem = fsize - *pos; const offt buf_rem = (offt)bufsize - written_to_buf; const offt cluster_off = *pos % (offt)d->cluster_size; const offt cluster_rem = (offt)d->cluster_size - cluster_off; const offt to_read = MIN3(cluster_rem, buf_rem, file_rem); ASSERT(to_read >= 0); memcpy(buf + written_to_buf, data + cluster_off, (size_t)to_read); written_to_buf += to_read; *pos += to_read; if (to_read < cluster_rem) { /* * We read less than cluster_rem because the buf was not big enough * or because the file was not big enough. In either case, we cannot * continue. */ break; } // find the next cluster u32 fatval = fat_read_fat_entry(d->hdr, d->type, 0, h->curr_cluster); if (fat_is_end_of_clusterchain(d->type, fatval)) { ASSERT(*pos == fsize); break; } // we do not expect BAD CLUSTERS ASSERT(!fat_is_bad_cluster(d->type, fatval)); h->curr_cluster = fatval; // go reading the new cluster in the chain. } while (true); return (ssize_t)written_to_buf; } STATIC int fat_rewind(fs_handle handle) { struct fatfs_handle *h = (struct fatfs_handle *) handle; h->h_fpos = 0; h->curr_cluster = fat_get_first_cluster(h->e); return 0; } STATIC offt fat_seek_forward(fs_handle handle, offt dist) { struct fatfs_handle *h = (struct fatfs_handle *) handle; struct fat_fs_device_data *d = h->fs->device_data; offt fsize = (offt)h->e->DIR_FileSize; offt moved_distance = 0; if (dist == 0) return h->h_fpos; if (h->h_fpos + dist > fsize) { /* Allow, like Linux does, to seek past the end of a file. */ h->h_fpos += dist; h->curr_cluster = (u32) -1; /* invalid cluster */ return (offt) h->h_fpos; } do { const offt file_rem = fsize - h->h_fpos; const offt dist_rem = dist - moved_distance; const offt cluster_off = h->h_fpos % (offt)d->cluster_size; const offt cluster_rem = (offt)d->cluster_size - cluster_off; const offt to_move = MIN3(cluster_rem, dist_rem, file_rem); ASSERT(to_move >= 0); moved_distance += to_move; h->h_fpos += to_move; if (to_move < cluster_rem) break; // find the next cluster u32 fatval = fat_read_fat_entry(d->hdr, d->type, 0, h->curr_cluster); if (fat_is_end_of_clusterchain(d->type, fatval)) { ASSERT(h->h_fpos == fsize); break; } // we do not expect BAD CLUSTERS ASSERT(!fat_is_bad_cluster(d->type, fatval)); h->curr_cluster = fatval; // go reading the new cluster in the chain. } while (true); return (offt)h->h_fpos; } struct fat_count_dirents_ctx { offt count; }; static int fat_count_dirents_cb(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *entry, const char *long_name, void *arg) { struct fat_count_dirents_ctx *ctx = arg; ctx->count++; return 0; } /* * Count the number of entries in a given FAT directory. * TODO: implement fat_count_dirents() in a more efficient way. */ STATIC offt fat_count_dirents(struct fat_fs_device_data *d, struct fat_entry *e) { int rc; struct fat_count_dirents_ctx ctx = { .count = 0 }; struct fat_walk_static_params walk_params = { .ctx = NULL, /* no need for long name ctx */ .h = d->hdr, .ft = d->type, .cb = &fat_count_dirents_cb, .arg = &ctx, }; ASSERT(e->directory); rc = fat_fs_walk_generic(d, &walk_params, e); return rc ? rc : ctx.count; } static offt fat_seek_dir(struct fatfs_handle *fh, offt off) { if (off < 0) return -EINVAL; if (off > fat_count_dirents(fh->fs->device_data, fh->e)) return -EINVAL; fh->dir_pos = off; return fh->dir_pos; } STATIC offt fat_seek(fs_handle handle, offt off, int whence) { struct fatfs_handle *fh = handle; if (fh->e->directory) { if (whence != SEEK_SET) return -EINVAL; return fat_seek_dir(fh, off); } offt curr_pos = fh->h_fpos; switch (whence) { case SEEK_SET: if (off < 0) return -EINVAL; /* invalid negative offset */ fat_rewind(handle); break; case SEEK_END: if (off >= 0) break; struct fatfs_handle *h = (struct fatfs_handle *) handle; off = (offt) h->e->DIR_FileSize + off; if (off < 0) return -EINVAL; fat_rewind(handle); break; case SEEK_CUR: if (off < 0) { off = curr_pos + off; if (off < 0) return -EINVAL; fat_rewind(handle); } break; default: return -EINVAL; } return fat_seek_forward(handle, off); } struct datetime fat_datetime_to_regular_datetime(u16 date, u16 time, u8 timetenth) { struct datetime d; d.day = date & 0b11111; // 5 bits: [0..4] d.month = (date >> 5) & 0b1111; // 4 bits: [5..8] d.year = (date >> 9) & 0b1111111; // 7 bits: [9..15] d.year += 1980; d.sec = time & 0b11111; // 5 bits: [0..4] d.min = (time >> 5) & 0b111111; // 6 bits: [5..10] d.hour = (time >> 11) & 0b11111; // 5 bits: [11..15] d.sec += timetenth / 10; return d; } static inline tilck_ino_t fat_entry_to_inode(struct fat_hdr *hdr, struct fat_entry *e) { return (tilck_ino_t)((long)e - (long)hdr); } STATIC int fat_stat(struct mnt_fs *fs, vfs_inode_ptr_t i, struct k_stat64 *statbuf) { struct fat_entry *e = i; struct datetime crt_time, wrt_time; if (!e) return -ENOENT; bzero(statbuf, sizeof(struct k_stat64)); statbuf->st_dev = fs->device_id; statbuf->st_ino = fat_entry_to_inode(fs->device_data, e); statbuf->st_mode = 0777; statbuf->st_nlink = 1; statbuf->st_uid = 0; /* root */ statbuf->st_gid = 0; /* root */ statbuf->st_rdev = 0; /* device ID, if a special file */ statbuf->st_size = e->DIR_FileSize; statbuf->st_blksize = 4096; statbuf->st_blocks = statbuf->st_size / 512; if (e->directory || e->volume_id) statbuf->st_mode |= S_IFDIR; else statbuf->st_mode |= S_IFREG; crt_time = fat_datetime_to_regular_datetime(e->DIR_CrtDate, e->DIR_CrtTime, e->DIR_CrtTimeTenth); wrt_time = fat_datetime_to_regular_datetime(e->DIR_WrtDate, e->DIR_WrtTime, 0 /* No WrtTimeTenth */); statbuf->st_ctim.tv_sec = (time_t)datetime_to_timestamp(crt_time); statbuf->st_mtim.tv_sec = (time_t)datetime_to_timestamp(wrt_time); statbuf->st_atim = statbuf->st_mtim; return 0; } struct fat_getdents_ctx { struct fatfs_handle *fh; get_dents_func_cb vfs_cb; void *vfs_ctx; int rc; }; static int fat_getdents_cb(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *entry, const char *long_name, void *arg) { char short_name[16]; const char *entname = long_name ? long_name : short_name; struct fat_getdents_ctx *ctx = arg; if (entname == short_name) fat_get_short_name(entry, short_name); struct vfs_dent64 dent = { .ino = fat_entry_to_inode(hdr, entry), .type = entry->directory ? VFS_DIR : VFS_FILE, .name_len = (u8) strlen(entname) + 1, .name = entname, }; return ctx->vfs_cb(&dent, ctx->vfs_ctx); } static int fat_getdents(fs_handle h, get_dents_func_cb cb, void *arg) { struct fatfs_handle *fh = h; struct fat_fs_device_data *d = fh->fs->device_data; struct fat_getdents_ctx ctx; struct fat_walk_long_name_ctx walk_ctx; struct fat_walk_static_params walk_params; int rc; if (!fh->e->directory && !fh->e->volume_id) return -ENOTDIR; ctx = (struct fat_getdents_ctx) { .fh = fh, .vfs_cb = cb, .vfs_ctx = arg, .rc = 0, }; walk_params = (struct fat_walk_static_params) { .ctx = &walk_ctx, .h = d->hdr, .ft = d->type, .cb = &fat_getdents_cb, .arg = &ctx, }; rc = fat_fs_walk_generic(d, &walk_params, fh->e); return rc ? rc : ctx.rc; } STATIC void fat_exclusive_lock(struct mnt_fs *fs) { if (!(fs->flags & VFS_FS_RW)) return; /* read-only: no lock is needed */ NOT_IMPLEMENTED(); } STATIC void fat_exclusive_unlock(struct mnt_fs *fs) { if (!(fs->flags & VFS_FS_RW)) return; /* read-only: no lock is needed */ NOT_IMPLEMENTED(); } STATIC void fat_shared_lock(struct mnt_fs *fs) { if (!(fs->flags & VFS_FS_RW)) return; /* read-only: no lock is needed */ NOT_IMPLEMENTED(); } STATIC void fat_shared_unlock(struct mnt_fs *fs) { if (!(fs->flags & VFS_FS_RW)) return; /* read-only: no lock is needed */ NOT_IMPLEMENTED(); } STATIC ssize_t fat_write(fs_handle handle, char *buf, size_t len, offt *pos) { struct fatfs_handle *h = (struct fatfs_handle *) handle; struct mnt_fs *fs = h->fs; if (h->e->directory) return -EISDIR; if (!(fs->flags & VFS_FS_RW)) return -EBADF; /* read-only file system: can't write */ NOT_IMPLEMENTED(); } STATIC int fat_ioctl(fs_handle h, ulong request, void *arg) { return -EINVAL; } static const struct file_ops static_ops_fat = { .read = fat_read, .seek = fat_seek, .write = fat_write, .ioctl = fat_ioctl, .mmap = fat_mmap, .munmap = fat_munmap, }; STATIC int fat_open(struct vfs_path *p, fs_handle *out, int fl, mode_t mode) { struct fatfs_handle *h; struct mnt_fs *fs = p->fs; struct fat_fs_path *fp = (struct fat_fs_path *)&p->fs_path; struct fat_entry *e = fp->entry; struct fat_fs_device_data *d = fs->device_data; if (!e) { if (!(fs->flags & VFS_FS_RW)) if (fl & O_CREAT) return -EROFS; return -ENOENT; } if ((fl & O_CREAT) && (fl & O_EXCL)) return -EEXIST; if (!(fs->flags & VFS_FS_RW)) if (fl & (O_WRONLY | O_RDWR)) return -EROFS; if (!(h = vfs_create_new_handle(fs, &static_ops_fat))) return -ENOMEM; h->e = e; h->h_fpos = 0; h->curr_cluster = fat_get_first_cluster(e); if (d->mmap_support) h->spec_flags = VFS_SPFL_MMAP_SUPPORTED; *out = h; return 0; } static inline void fat_get_root_entry(struct fat_fs_device_data *d, struct fat_fs_path *fp) { *fp = (struct fat_fs_path) { .entry = d->root_dir_entries, .parent_entry = d->root_dir_entries, .unused = NULL, .type = VFS_DIR, }; } static void fat_get_entry(struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t name_len, struct fs_path *fs_path) { struct fat_fs_device_data *d = fs->device_data; struct fat_fs_path *fp = (struct fat_fs_path *)fs_path; struct fat_walk_static_params walk_params; struct fat_entry *dir_entry; struct fat_search_ctx ctx; if (!dir_inode && !name) // both dir_inode and name are NULL: return fat_get_root_entry(d, fp); // getting a path to the root dir dir_entry = dir_inode ? dir_inode : d->root_dir_entries; if (UNLIKELY(dir_entry == d->root_dir_entries)) if (is_dot_or_dotdot(name, (int)name_len)) return fat_get_root_entry(d, fp); walk_params = (struct fat_walk_static_params) { .ctx = &ctx.walk_ctx, .h = d->hdr, .ft = d->type, .cb = &fat_search_entry_cb, .arg = &ctx, }; fat_init_search_ctx(&ctx, name, true); fat_fs_walk_generic(d, &walk_params, dir_entry); struct fat_entry *res = !ctx.not_dir ? ctx.result : NULL; enum vfs_entry_type type = VFS_NONE; if (res) { const u32 clu = fat_get_first_cluster(res); type = res->directory ? VFS_DIR : VFS_FILE; if (type == VFS_DIR && (clu == 0 || clu == d->root_cluster)) { res = d->root_dir_entries; type = VFS_DIR; } } *fp = (struct fat_fs_path) { .entry = res, .parent_entry = dir_entry, .unused = NULL, .type = type, }; } static vfs_inode_ptr_t fat_get_inode(fs_handle h) { return ((struct fatfs_handle *)h)->e; } static int fat_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { if (fs->flags & VFS_FS_RW) NOT_IMPLEMENTED(); return 1; } static int fat_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { if (fs->flags & VFS_FS_RW) NOT_IMPLEMENTED(); return 1; } static const struct fs_ops static_fsops_fat = { .get_inode = fat_get_inode, .open = fat_open, .getdents = fat_getdents, .unlink = NULL, .mkdir = NULL, .rmdir = NULL, .truncate = NULL, .stat = fat_stat, .chmod = NULL, .get_entry = fat_get_entry, .rename = NULL, .link = NULL, .retain_inode = fat_retain_inode, .release_inode = fat_release_inode, .fs_exlock = fat_exclusive_lock, .fs_exunlock = fat_exclusive_unlock, .fs_shlock = fat_shared_lock, .fs_shunlock = fat_shared_unlock, }; struct mnt_fs *fat_mount_ramdisk(void *vaddr, size_t rd_size, u32 flags) { struct fat_fs_device_data *d; struct mnt_fs *fs; if (flags & VFS_FS_RW) panic("fat_mount_ramdisk: r/w mode is NOT currently supported"); d = kzalloc_obj(struct fat_fs_device_data); if (!d) return NULL; d->hdr = (struct fat_hdr *) vaddr; d->type = fat_get_type(d->hdr); d->cluster_size = d->hdr->BPB_SecPerClus * d->hdr->BPB_BytsPerSec; d->root_dir_entries = fat_get_rootdir(d->hdr, d->type, &d->root_cluster); fs = create_fs_obj("fat", &static_fsops_fat, d, flags | VFS_FS_RQ_DE_SKIP); if (!fs) { kfree_obj(d, struct fat_fs_device_data); return NULL; } if (!fat_ramdisk_prepare_for_mmap(d, rd_size)) d->mmap_support = true; return fs; } void fat_umount_ramdisk(struct mnt_fs *fs) { kfree_obj(fs->device_data, struct fat_fs_device_data); destory_fs_obj(fs); } <file_sep>/******************************************************************************* * * Module Name: rscalc - Calculate stream and list lengths * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acresrc.h" #include "acnamesp.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME ("rscalc") /* Local prototypes */ static UINT8 AcpiRsCountSetBits ( UINT16 BitField); static ACPI_RS_LENGTH AcpiRsStructOptionLength ( ACPI_RESOURCE_SOURCE *ResourceSource); static UINT32 AcpiRsStreamOptionLength ( UINT32 ResourceLength, UINT32 MinimumTotalLength); /******************************************************************************* * * FUNCTION: AcpiRsCountSetBits * * PARAMETERS: BitField - Field in which to count bits * * RETURN: Number of bits set within the field * * DESCRIPTION: Count the number of bits set in a resource field. Used for * (Short descriptor) interrupt and DMA lists. * ******************************************************************************/ static UINT8 AcpiRsCountSetBits ( UINT16 BitField) { UINT8 BitsSet; ACPI_FUNCTION_ENTRY (); for (BitsSet = 0; BitField; BitsSet++) { /* Zero the least significant bit that is set */ BitField &= (UINT16) (BitField - 1); } return (BitsSet); } /******************************************************************************* * * FUNCTION: AcpiRsStructOptionLength * * PARAMETERS: ResourceSource - Pointer to optional descriptor field * * RETURN: Status * * DESCRIPTION: Common code to handle optional ResourceSourceIndex and * ResourceSource fields in some Large descriptors. Used during * list-to-stream conversion * ******************************************************************************/ static ACPI_RS_LENGTH AcpiRsStructOptionLength ( ACPI_RESOURCE_SOURCE *ResourceSource) { ACPI_FUNCTION_ENTRY (); /* * If the ResourceSource string is valid, return the size of the string * (StringLength includes the NULL terminator) plus the size of the * ResourceSourceIndex (1). */ if (ResourceSource->StringPtr) { return ((ACPI_RS_LENGTH) (ResourceSource->StringLength + 1)); } return (0); } /******************************************************************************* * * FUNCTION: AcpiRsStreamOptionLength * * PARAMETERS: ResourceLength - Length from the resource header * MinimumTotalLength - Minimum length of this resource, before * any optional fields. Includes header size * * RETURN: Length of optional string (0 if no string present) * * DESCRIPTION: Common code to handle optional ResourceSourceIndex and * ResourceSource fields in some Large descriptors. Used during * stream-to-list conversion * ******************************************************************************/ static UINT32 AcpiRsStreamOptionLength ( UINT32 ResourceLength, UINT32 MinimumAmlResourceLength) { UINT32 StringLength = 0; ACPI_FUNCTION_ENTRY (); /* * The ResourceSourceIndex and ResourceSource are optional elements of * some Large-type resource descriptors. */ /* * If the length of the actual resource descriptor is greater than the * ACPI spec-defined minimum length, it means that a ResourceSourceIndex * exists and is followed by a (required) null terminated string. The * string length (including the null terminator) is the resource length * minus the minimum length, minus one byte for the ResourceSourceIndex * itself. */ if (ResourceLength > MinimumAmlResourceLength) { /* Compute the length of the optional string */ StringLength = ResourceLength - MinimumAmlResourceLength - 1; } /* * Round the length up to a multiple of the native word in order to * guarantee that the entire resource descriptor is native word aligned */ return ((UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (StringLength)); } /******************************************************************************* * * FUNCTION: AcpiRsGetAmlLength * * PARAMETERS: Resource - Pointer to the resource linked list * ResourceListSize - Size of the resource linked list * SizeNeeded - Where the required size is returned * * RETURN: Status * * DESCRIPTION: Takes a linked list of internal resource descriptors and * calculates the size buffer needed to hold the corresponding * external resource byte stream. * ******************************************************************************/ ACPI_STATUS AcpiRsGetAmlLength ( ACPI_RESOURCE *Resource, ACPI_SIZE ResourceListSize, ACPI_SIZE *SizeNeeded) { ACPI_SIZE AmlSizeNeeded = 0; ACPI_RESOURCE *ResourceEnd; ACPI_RS_LENGTH TotalSize; ACPI_FUNCTION_TRACE (RsGetAmlLength); /* Traverse entire list of internal resource descriptors */ ResourceEnd = ACPI_ADD_PTR (ACPI_RESOURCE, Resource, ResourceListSize); while (Resource < ResourceEnd) { /* Validate the descriptor type */ if (Resource->Type > ACPI_RESOURCE_TYPE_MAX) { return_ACPI_STATUS (AE_AML_INVALID_RESOURCE_TYPE); } /* Sanity check the length. It must not be zero, or we loop forever */ if (!Resource->Length) { return_ACPI_STATUS (AE_AML_BAD_RESOURCE_LENGTH); } /* Get the base size of the (external stream) resource descriptor */ TotalSize = AcpiGbl_AmlResourceSizes [Resource->Type]; /* * Augment the base size for descriptors with optional and/or * variable-length fields */ switch (Resource->Type) { case ACPI_RESOURCE_TYPE_IRQ: /* Length can be 3 or 2 */ if (Resource->Data.Irq.DescriptorLength == 2) { TotalSize--; } break; case ACPI_RESOURCE_TYPE_START_DEPENDENT: /* Length can be 1 or 0 */ if (Resource->Data.Irq.DescriptorLength == 0) { TotalSize--; } break; case ACPI_RESOURCE_TYPE_VENDOR: /* * Vendor Defined Resource: * For a Vendor Specific resource, if the Length is between 1 and 7 * it will be created as a Small Resource data type, otherwise it * is a Large Resource data type. */ if (Resource->Data.Vendor.ByteLength > 7) { /* Base size of a Large resource descriptor */ TotalSize = sizeof (AML_RESOURCE_LARGE_HEADER); } /* Add the size of the vendor-specific data */ TotalSize = (ACPI_RS_LENGTH) (TotalSize + Resource->Data.Vendor.ByteLength); break; case ACPI_RESOURCE_TYPE_END_TAG: /* * End Tag: * We are done -- return the accumulated total size. */ *SizeNeeded = AmlSizeNeeded + TotalSize; /* Normal exit */ return_ACPI_STATUS (AE_OK); case ACPI_RESOURCE_TYPE_ADDRESS16: /* * 16-Bit Address Resource: * Add the size of the optional ResourceSource info */ TotalSize = (ACPI_RS_LENGTH) (TotalSize + AcpiRsStructOptionLength ( &Resource->Data.Address16.ResourceSource)); break; case ACPI_RESOURCE_TYPE_ADDRESS32: /* * 32-Bit Address Resource: * Add the size of the optional ResourceSource info */ TotalSize = (ACPI_RS_LENGTH) (TotalSize + AcpiRsStructOptionLength ( &Resource->Data.Address32.ResourceSource)); break; case ACPI_RESOURCE_TYPE_ADDRESS64: /* * 64-Bit Address Resource: * Add the size of the optional ResourceSource info */ TotalSize = (ACPI_RS_LENGTH) (TotalSize + AcpiRsStructOptionLength ( &Resource->Data.Address64.ResourceSource)); break; case ACPI_RESOURCE_TYPE_EXTENDED_IRQ: /* * Extended IRQ Resource: * Add the size of each additional optional interrupt beyond the * required 1 (4 bytes for each UINT32 interrupt number) */ TotalSize = (ACPI_RS_LENGTH) (TotalSize + ((Resource->Data.ExtendedIrq.InterruptCount - 1) * 4) + /* Add the size of the optional ResourceSource info */ AcpiRsStructOptionLength ( &Resource->Data.ExtendedIrq.ResourceSource)); break; case ACPI_RESOURCE_TYPE_GPIO: TotalSize = (ACPI_RS_LENGTH) (TotalSize + (Resource->Data.Gpio.PinTableLength * 2) + Resource->Data.Gpio.ResourceSource.StringLength + Resource->Data.Gpio.VendorLength); break; case ACPI_RESOURCE_TYPE_PIN_FUNCTION: TotalSize = (ACPI_RS_LENGTH) (TotalSize + (Resource->Data.PinFunction.PinTableLength * 2) + Resource->Data.PinFunction.ResourceSource.StringLength + Resource->Data.PinFunction.VendorLength); break; case ACPI_RESOURCE_TYPE_SERIAL_BUS: TotalSize = AcpiGbl_AmlResourceSerialBusSizes [ Resource->Data.CommonSerialBus.Type]; TotalSize = (ACPI_RS_LENGTH) (TotalSize + Resource->Data.I2cSerialBus.ResourceSource.StringLength + Resource->Data.I2cSerialBus.VendorLength); break; case ACPI_RESOURCE_TYPE_PIN_CONFIG: TotalSize = (ACPI_RS_LENGTH) (TotalSize + (Resource->Data.PinConfig.PinTableLength * 2) + Resource->Data.PinConfig.ResourceSource.StringLength + Resource->Data.PinConfig.VendorLength); break; case ACPI_RESOURCE_TYPE_PIN_GROUP: TotalSize = (ACPI_RS_LENGTH) (TotalSize + (Resource->Data.PinGroup.PinTableLength * 2) + Resource->Data.PinGroup.ResourceLabel.StringLength + Resource->Data.PinGroup.VendorLength); break; case ACPI_RESOURCE_TYPE_PIN_GROUP_FUNCTION: TotalSize = (ACPI_RS_LENGTH) (TotalSize + Resource->Data.PinGroupFunction.ResourceSource.StringLength + Resource->Data.PinGroupFunction.ResourceSourceLabel.StringLength + Resource->Data.PinGroupFunction.VendorLength); break; case ACPI_RESOURCE_TYPE_PIN_GROUP_CONFIG: TotalSize = (ACPI_RS_LENGTH) (TotalSize + Resource->Data.PinGroupConfig.ResourceSource.StringLength + Resource->Data.PinGroupConfig.ResourceSourceLabel.StringLength + Resource->Data.PinGroupConfig.VendorLength); break; default: break; } /* Update the total */ AmlSizeNeeded += TotalSize; /* Point to the next object */ Resource = ACPI_ADD_PTR (ACPI_RESOURCE, Resource, Resource->Length); } /* Did not find an EndTag resource descriptor */ return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG); } /******************************************************************************* * * FUNCTION: AcpiRsGetListLength * * PARAMETERS: AmlBuffer - Pointer to the resource byte stream * AmlBufferLength - Size of AmlBuffer * SizeNeeded - Where the size needed is returned * * RETURN: Status * * DESCRIPTION: Takes an external resource byte stream and calculates the size * buffer needed to hold the corresponding internal resource * descriptor linked list. * ******************************************************************************/ ACPI_STATUS AcpiRsGetListLength ( UINT8 *AmlBuffer, UINT32 AmlBufferLength, ACPI_SIZE *SizeNeeded) { ACPI_STATUS Status; UINT8 *EndAml; UINT8 *Buffer; UINT32 BufferSize; UINT16 Temp16; UINT16 ResourceLength; UINT32 ExtraStructBytes; UINT8 ResourceIndex; UINT8 MinimumAmlResourceLength; AML_RESOURCE *AmlResource; ACPI_FUNCTION_TRACE (RsGetListLength); *SizeNeeded = ACPI_RS_SIZE_MIN; /* Minimum size is one EndTag */ EndAml = AmlBuffer + AmlBufferLength; /* Walk the list of AML resource descriptors */ while (AmlBuffer < EndAml) { /* Validate the Resource Type and Resource Length */ Status = AcpiUtValidateResource (NULL, AmlBuffer, &ResourceIndex); if (ACPI_FAILURE (Status)) { /* * Exit on failure. Cannot continue because the descriptor length * may be bogus also. */ return_ACPI_STATUS (Status); } AmlResource = (void *) AmlBuffer; /* Get the resource length and base (minimum) AML size */ ResourceLength = AcpiUtGetResourceLength (AmlBuffer); MinimumAmlResourceLength = AcpiGbl_ResourceAmlSizes[ResourceIndex]; /* * Augment the size for descriptors with optional * and/or variable length fields */ ExtraStructBytes = 0; Buffer = AmlBuffer + AcpiUtGetResourceHeaderLength (AmlBuffer); switch (AcpiUtGetResourceType (AmlBuffer)) { case ACPI_RESOURCE_NAME_IRQ: /* * IRQ Resource: * Get the number of bits set in the 16-bit IRQ mask */ ACPI_MOVE_16_TO_16 (&Temp16, Buffer); ExtraStructBytes = AcpiRsCountSetBits (Temp16); break; case ACPI_RESOURCE_NAME_DMA: /* * DMA Resource: * Get the number of bits set in the 8-bit DMA mask */ ExtraStructBytes = AcpiRsCountSetBits (*Buffer); break; case ACPI_RESOURCE_NAME_VENDOR_SMALL: case ACPI_RESOURCE_NAME_VENDOR_LARGE: /* * Vendor Resource: * Get the number of vendor data bytes */ ExtraStructBytes = ResourceLength; /* * There is already one byte included in the minimum * descriptor size. If there are extra struct bytes, * subtract one from the count. */ if (ExtraStructBytes) { ExtraStructBytes--; } break; case ACPI_RESOURCE_NAME_END_TAG: /* * End Tag: This is the normal exit */ return_ACPI_STATUS (AE_OK); case ACPI_RESOURCE_NAME_ADDRESS32: case ACPI_RESOURCE_NAME_ADDRESS16: case ACPI_RESOURCE_NAME_ADDRESS64: /* * Address Resource: * Add the size of the optional ResourceSource */ ExtraStructBytes = AcpiRsStreamOptionLength ( ResourceLength, MinimumAmlResourceLength); break; case ACPI_RESOURCE_NAME_EXTENDED_IRQ: /* * Extended IRQ Resource: * Using the InterruptTableLength, add 4 bytes for each additional * interrupt. Note: at least one interrupt is required and is * included in the minimum descriptor size (reason for the -1) */ ExtraStructBytes = (Buffer[1] - 1) * sizeof (UINT32); /* Add the size of the optional ResourceSource */ ExtraStructBytes += AcpiRsStreamOptionLength ( ResourceLength - ExtraStructBytes, MinimumAmlResourceLength); break; case ACPI_RESOURCE_NAME_GPIO: /* Vendor data is optional */ if (AmlResource->Gpio.VendorLength) { ExtraStructBytes += AmlResource->Gpio.VendorOffset - AmlResource->Gpio.PinTableOffset + AmlResource->Gpio.VendorLength; } else { ExtraStructBytes += AmlResource->LargeHeader.ResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER) - AmlResource->Gpio.PinTableOffset; } break; case ACPI_RESOURCE_NAME_PIN_FUNCTION: /* Vendor data is optional */ if (AmlResource->PinFunction.VendorLength) { ExtraStructBytes += AmlResource->PinFunction.VendorOffset - AmlResource->PinFunction.PinTableOffset + AmlResource->PinFunction.VendorLength; } else { ExtraStructBytes += AmlResource->LargeHeader.ResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER) - AmlResource->PinFunction.PinTableOffset; } break; case ACPI_RESOURCE_NAME_SERIAL_BUS: MinimumAmlResourceLength = AcpiGbl_ResourceAmlSerialBusSizes[ AmlResource->CommonSerialBus.Type]; ExtraStructBytes += AmlResource->CommonSerialBus.ResourceLength - MinimumAmlResourceLength; break; case ACPI_RESOURCE_NAME_PIN_CONFIG: /* Vendor data is optional */ if (AmlResource->PinConfig.VendorLength) { ExtraStructBytes += AmlResource->PinConfig.VendorOffset - AmlResource->PinConfig.PinTableOffset + AmlResource->PinConfig.VendorLength; } else { ExtraStructBytes += AmlResource->LargeHeader.ResourceLength + sizeof (AML_RESOURCE_LARGE_HEADER) - AmlResource->PinConfig.PinTableOffset; } break; case ACPI_RESOURCE_NAME_PIN_GROUP: ExtraStructBytes += AmlResource->PinGroup.VendorOffset - AmlResource->PinGroup.PinTableOffset + AmlResource->PinGroup.VendorLength; break; case ACPI_RESOURCE_NAME_PIN_GROUP_FUNCTION: ExtraStructBytes += AmlResource->PinGroupFunction.VendorOffset - AmlResource->PinGroupFunction.ResSourceOffset + AmlResource->PinGroupFunction.VendorLength; break; case ACPI_RESOURCE_NAME_PIN_GROUP_CONFIG: ExtraStructBytes += AmlResource->PinGroupConfig.VendorOffset - AmlResource->PinGroupConfig.ResSourceOffset + AmlResource->PinGroupConfig.VendorLength; break; default: break; } /* * Update the required buffer size for the internal descriptor structs * * Important: Round the size up for the appropriate alignment. This * is a requirement on IA64. */ if (AcpiUtGetResourceType (AmlBuffer) == ACPI_RESOURCE_NAME_SERIAL_BUS) { BufferSize = AcpiGbl_ResourceStructSerialBusSizes[ AmlResource->CommonSerialBus.Type] + ExtraStructBytes; } else { BufferSize = AcpiGbl_ResourceStructSizes[ResourceIndex] + ExtraStructBytes; } BufferSize = (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (BufferSize); *SizeNeeded += BufferSize; ACPI_DEBUG_PRINT ((ACPI_DB_RESOURCES, "Type %.2X, AmlLength %.2X InternalLength %.2X\n", AcpiUtGetResourceType (AmlBuffer), AcpiUtGetDescriptorLength (AmlBuffer), BufferSize)); /* * Point to the next resource within the AML stream using the length * contained in the resource descriptor header */ AmlBuffer += AcpiUtGetDescriptorLength (AmlBuffer); } /* Did not find an EndTag resource descriptor */ return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG); } /******************************************************************************* * * FUNCTION: AcpiRsGetPciRoutingTableLength * * PARAMETERS: PackageObject - Pointer to the package object * BufferSizeNeeded - UINT32 pointer of the size buffer * needed to properly return the * parsed data * * RETURN: Status * * DESCRIPTION: Given a package representing a PCI routing table, this * calculates the size of the corresponding linked list of * descriptions. * ******************************************************************************/ ACPI_STATUS AcpiRsGetPciRoutingTableLength ( ACPI_OPERAND_OBJECT *PackageObject, ACPI_SIZE *BufferSizeNeeded) { UINT32 NumberOfElements; ACPI_SIZE TempSizeNeeded = 0; ACPI_OPERAND_OBJECT **TopObjectList; UINT32 Index; ACPI_OPERAND_OBJECT *PackageElement; ACPI_OPERAND_OBJECT **SubObjectList; BOOLEAN NameFound; UINT32 TableIndex; ACPI_FUNCTION_TRACE (RsGetPciRoutingTableLength); NumberOfElements = PackageObject->Package.Count; /* * Calculate the size of the return buffer. * The base size is the number of elements * the sizes of the * structures. Additional space for the strings is added below. * The minus one is to subtract the size of the UINT8 Source[1] * member because it is added below. * * But each PRT_ENTRY structure has a pointer to a string and * the size of that string must be found. */ TopObjectList = PackageObject->Package.Elements; for (Index = 0; Index < NumberOfElements; Index++) { /* Dereference the subpackage */ PackageElement = *TopObjectList; /* We must have a valid Package object */ if (!PackageElement || (PackageElement->Common.Type != ACPI_TYPE_PACKAGE)) { return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* * The SubObjectList will now point to an array of the * four IRQ elements: Address, Pin, Source and SourceIndex */ SubObjectList = PackageElement->Package.Elements; /* Scan the IrqTableElements for the Source Name String */ NameFound = FALSE; for (TableIndex = 0; TableIndex < PackageElement->Package.Count && !NameFound; TableIndex++) { if (*SubObjectList && /* Null object allowed */ ((ACPI_TYPE_STRING == (*SubObjectList)->Common.Type) || ((ACPI_TYPE_LOCAL_REFERENCE == (*SubObjectList)->Common.Type) && ((*SubObjectList)->Reference.Class == ACPI_REFCLASS_NAME)))) { NameFound = TRUE; } else { /* Look at the next element */ SubObjectList++; } } TempSizeNeeded += (sizeof (ACPI_PCI_ROUTING_TABLE) - 4); /* Was a String type found? */ if (NameFound) { if ((*SubObjectList)->Common.Type == ACPI_TYPE_STRING) { /* * The length String.Length field does not include the * terminating NULL, add 1 */ TempSizeNeeded += ((ACPI_SIZE) (*SubObjectList)->String.Length + 1); } else { TempSizeNeeded += AcpiNsGetPathnameLength ( (*SubObjectList)->Reference.Node); } } else { /* * If no name was found, then this is a NULL, which is * translated as a UINT32 zero. */ TempSizeNeeded += sizeof (UINT32); } /* Round up the size since each element must be aligned */ TempSizeNeeded = ACPI_ROUND_UP_TO_64BIT (TempSizeNeeded); /* Point to the next ACPI_OPERAND_OBJECT */ TopObjectList++; } /* * Add an extra element to the end of the list, essentially a * NULL terminator */ *BufferSizeNeeded = TempSizeNeeded + sizeof (ACPI_PCI_ROUTING_TABLE); return_ACPI_STATUS (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/list.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include "acpi_int.h" static struct list batteries_list = STATIC_LIST_INIT(batteries_list); struct battery { struct list_node node; ACPI_HANDLE *handle; struct basic_battery_info bi; }; bool acpi_is_battery(ACPI_HANDLE obj) { /* * Evalutating the _BIX method requires the installation of an additional * address space handler (see AcpiInstallAddressSpaceHandler() in ACPICA and * OperationRegion in the ACPI spec) for the embedded controller on some * machines. Tilck has no support for that, yet. * * For the reasons above, force-setting `has_BIX` to false. */ bool has_BIX = false; bool has_BIF = acpi_has_method(obj, "_BIF"); bool has_BST = acpi_has_method(obj, "_BST"); bool has_STA = acpi_has_method(obj, "_STA"); return (has_BIF || has_BIX) && has_BST && has_STA; } ACPI_STATUS acpi_battery_get_basic_info(ACPI_HANDLE obj, struct basic_battery_info *bi) { ACPI_STATUS rc; ACPI_BUFFER res; ACPI_OBJECT *bif; ACPI_OBJECT *elems; int pu_idx = 0; int dcap_idx = 1; bool has_BIX = false; res.Length = ACPI_ALLOCATE_BUFFER; res.Pointer = NULL; bi->bif_method = "_BIF"; bi->lfc_idx = 2; bi->design_cap = BATT_UNKNOWN_CHARGE; // See the comments in acpi_is_battery(). // has_BIX = acpi_has_method(obj, "_BIX"); if (has_BIX) { bi->bif_method = "_BIX"; bi->lfc_idx++; bi->has_BIX = true; pu_idx++; dcap_idx++; } else { bi->has_BIX = false; } rc = AcpiEvaluateObject(obj, (char *)bi->bif_method, NULL, &res); if (ACPI_FAILURE(rc)) return rc; bif = res.Pointer; if (bif->Package.Count >= 3) { elems = bif->Package.Elements; if (elems[pu_idx].Integer.Value == 0) bi->power_unit = "mWh"; else if (elems[pu_idx].Integer.Value == 1) bi->power_unit = "mAh"; else bi->power_unit = NULL; /* unknown */ bi->design_cap = (ulong) elems[dcap_idx].Integer.Value; } ACPI_FREE(res.Pointer); return AE_OK; } static ACPI_STATUS batter_get_last_charge_cap(ACPI_HANDLE *obj, struct basic_battery_info *bi, ulong *value) { ACPI_STATUS rc; ACPI_BUFFER res; ACPI_OBJECT *bif; res.Length = ACPI_ALLOCATE_BUFFER; res.Pointer = NULL; rc = AcpiEvaluateObject(obj, (char *)bi->bif_method, NULL, &res); if (ACPI_FAILURE(rc)) return rc; bif = res.Pointer; if (bif->Type != ACPI_TYPE_PACKAGE) goto type_error; if (bi->lfc_idx >= bif->Package.Count) goto type_error; if (bif->Package.Elements[bi->lfc_idx].Type != ACPI_TYPE_INTEGER) goto type_error; /* Common case */ *value = (ulong) bif->Package.Elements[bi->lfc_idx].Integer.Value; out: ACPI_FREE(res.Pointer); return rc; type_error: rc = AE_TYPE; goto out; } static ACPI_STATUS acpi_battery_get_charge_per_mille(struct battery *bat, ulong *ret) { ACPI_STATUS rc; ACPI_BUFFER res; ACPI_OBJECT *bst, *obj_val; ulong cap = BATT_UNKNOWN_CHARGE; ulong rem = 0; res.Length = ACPI_ALLOCATE_BUFFER; res.Pointer = NULL; if (!bat->bi.design_cap) return AE_NOT_EXIST; /* Empty batter slot */ rc = batter_get_last_charge_cap(bat->handle, &bat->bi, &cap); if (ACPI_FAILURE(rc)) return rc; if (cap == BATT_UNKNOWN_CHARGE) goto unknown_charge_err; rc = AcpiEvaluateObject(bat->handle, "_BST", NULL, &res); if (ACPI_FAILURE(rc)) return rc; bst = res.Pointer; if (bst->Type != ACPI_TYPE_PACKAGE) goto type_error; if (bst->Package.Count < 4) goto type_error; /* * Point to the "Battery Remaining Capacity" field * ACPI 6.3 spec, table 10-333: BST Return Package Values. */ obj_val = &bst->Package.Elements[2]; if (obj_val->Type != ACPI_TYPE_INTEGER) goto type_error; /* De-reference the value */ rem = (ulong) obj_val->Integer.Value; if (rem == BATT_UNKNOWN_CHARGE) goto unknown_charge_err; if (rem > cap) { /* * While charging, on some machines, the remaining capacity will be set * to the design capacity. Without the current check, that leads to a * charge% greater than 100%. */ rem = cap; } if (cap > 0) *ret = rem * 1000 / cap; /* common case */ else if (!rem) *ret = 0; /* weird case: cap == rem == 0 */ else rc = AE_ERROR; /* non-sense: cap == 0, but rem > 0 */ out: ACPI_FREE(res.Pointer); return rc; type_error: rc = AE_TYPE; goto out; unknown_charge_err: rc = AE_NOT_EXIST; goto out; } int acpi_get_all_batteries_charge_per_mille(ulong *ret) { ulong charge_per_mille_sum = 0; ulong batt_cnt = 0; struct battery *bat; ACPI_STATUS rc; list_for_each_ro(bat, &batteries_list, node) { ulong tmp; if (!bat->bi.design_cap) continue; /* empty battery slot */ rc = acpi_battery_get_charge_per_mille(bat, &tmp); if (ACPI_FAILURE(rc)) { switch (rc) { case AE_NO_MEMORY: return -ENOMEM; case AE_NOT_EXIST: return -ENOENT; case AE_TYPE: return -EPROTOTYPE; /* Note: abusing UNIX errors :-) */ default: return -EIO; } } charge_per_mille_sum += tmp; batt_cnt++; } if (!batt_cnt) return -ENOENT; *ret = charge_per_mille_sum / batt_cnt; return 0; } static ACPI_STATUS on_battery_cb(void *obj_handle, void *device_info, void *ctx) { struct battery *b; ACPI_STATUS rc; if (!(b = kzalloc_obj(struct battery))) return AE_NO_MEMORY; list_node_init(&b->node); b->handle = obj_handle; rc = acpi_battery_get_basic_info(obj_handle, &b->bi); if (ACPI_FAILURE(rc)) { kfree_obj(b, struct battery); return rc; } list_add_tail(&batteries_list, &b->node); return AE_OK; } __attribute__((constructor)) static void __reg_batteries_cbs(void) { static struct acpi_reg_per_object_cb_node batteries = { .cb = &on_battery_cb, .filter = &acpi_is_battery }; list_node_init(&batteries.node); acpi_reg_per_object_cb(&batteries); } <file_sep>FROM archlinux:latest RUN pacman -Syu --noconfirm sudo <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> enum fat_type { fat_unknown = 0, // unknown FAT type fat12_type = 1, fat16_type = 2, fat32_type = 4, }; struct fat_hdr { u8 BS_jmpBoot[3]; char BS_OEMName[8]; u16 BPB_BytsPerSec; u8 BPB_SecPerClus; u16 BPB_RsvdSecCnt; u8 BPB_NumFATs; u16 BPB_RootEntCnt; u16 BPB_TotSec16; u8 BPB_Media; u16 BPB_FATSz16; u16 BPB_SecPerTrk; u16 BPB_NumHeads; u32 BPB_HiddSec; u32 BPB_TotSec32; } PACKED; struct fat16_header2 { u8 BS_DrvNum; u8 BS_Reserved1; u8 BS_BootSig; u32 BS_VolID; char BS_VolLab[11]; char BS_FilSysType[8]; } PACKED; struct fat32_header2 { u32 BPB_FATSz32; u16 BPB_ExtFlags; u16 BPB_FSVer; u32 BPB_RootClus; u16 BPB_FSInfo; u16 BPB_BkBootSec; u8 BPB_Reserved[12]; u8 BS_DrvNum; u8 BS_Reserved1; u8 BS_BootSig; u32 BS_VolID; char BS_VolLab[11]; char BS_FilSysType[8]; } PACKED; /* * Special flags in DIR_NTRes telling us if the base part or the extention of * a short name is entirely in lower case. */ #define FAT_ENTRY_NTRES_BASE_LOW_CASE 0x08 #define FAT_ENTRY_NTRES_EXT_LOW_CASE 0x10 /* In case an extact comparison using DIR_Name is needed */ #define FAT_DIR_DOT ". " #define FAT_DIR_DOT_DOT ".. " struct fat_entry { char DIR_Name[11]; u8 readonly : 1; // lower-bit u8 hidden : 1; u8 system : 1; u8 volume_id : 1; u8 directory : 1; u8 archive : 1; u8 resbit1 : 1; // reserved bit u8 resbit2 : 1; // reserved bit u8 DIR_NTRes; // reserved to be used by Windows NT u8 DIR_CrtTimeTenth; // creation time, tenth of seconds (0-199) u16 DIR_CrtTime; // creation time, granularity: 2 seconds u16 DIR_CrtDate; // creation date u16 DIR_LstAccDate; // last access date u16 DIR_FstClusHI; // high word of entry's first cluster u16 DIR_WrtTime; // time of last write u16 DIR_WrtDate; // date of last write u16 DIR_FstClusLO; // low word of entry's first cluster u32 DIR_FileSize; } PACKED; struct fat_long_entry { u8 LDIR_Ord; u8 LDIR_Name1[10]; u8 LDIR_Attr; u8 LDIR_Type; /* 0 means sub-comp of a long name entry. != 0 reserved. */ u8 LDIR_Chksum; u8 LDIR_Name2[12]; u16 LDIR_FstClusLO; /* must be always 0 in this context. */ u8 LDIR_Name3[4]; } PACKED; static inline bool is_long_name_entry(struct fat_entry *e) { return e->readonly && e->hidden && e->system && e->volume_id; } // FAT INTERNALS --------------------------------------------------------------- enum fat_type fat_get_type(struct fat_hdr *hdr); struct fat_entry * fat_get_rootdir(struct fat_hdr *hdr, enum fat_type ft, u32 *cluster /*out*/); void fat_get_short_name(struct fat_entry *entry, char *destbuf); u32 fat_get_sector_for_cluster(struct fat_hdr *hdr, u32 N); u32 fat_read_fat_entry(struct fat_hdr *hdr, enum fat_type ft, u32 fatN, u32 clusterN); void fat_write_fat_entry(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clusterN, u32 value); u32 fat_get_first_data_sector(struct fat_hdr *hdr); u32 fat_get_cluster_count(struct fat_hdr *hdr); static inline u32 fat_get_reserved_sectors_count(struct fat_hdr *hdr) { return hdr->BPB_RsvdSecCnt; } static inline u32 fat_get_sector_size(struct fat_hdr *hdr) { return hdr->BPB_BytsPerSec; } static inline u32 fat_get_cluster_size(struct fat_hdr *hdr) { return hdr->BPB_BytsPerSec * hdr->BPB_SecPerClus; } // FATSz is the number of sectors per FAT static inline u32 fat_get_FATSz(struct fat_hdr *hdr) { if (hdr->BPB_FATSz16 != 0) return hdr->BPB_FATSz16; struct fat32_header2 *h2 = (struct fat32_header2*)(hdr+1); return h2->BPB_FATSz32; } static inline u32 fat_get_TotSec(struct fat_hdr *hdr) { return hdr->BPB_TotSec16 != 0 ? hdr->BPB_TotSec16 : hdr->BPB_TotSec32; } static inline u32 fat_get_root_dir_sectors(struct fat_hdr *hdr) { const u32 bps = hdr->BPB_BytsPerSec; return ((hdr->BPB_RootEntCnt * 32u) + (bps - 1u)) / bps; } static inline u32 fat_get_first_cluster(struct fat_entry *e) { return (u32)e->DIR_FstClusHI << 16u | e->DIR_FstClusLO; } static inline void fat_set_first_cluster(struct fat_entry *e, u32 clu) { e->DIR_FstClusHI = clu >> 16; e->DIR_FstClusLO = clu & 0xFFFF; } static inline bool fat_is_end_of_clusterchain(enum fat_type ft, u32 val) { ASSERT(ft == fat16_type || ft == fat32_type); /* * NOTES about the FAT32 case: despite the FAT32 File System Specification * states that EOC is when val >= 0x0FFFFFF8, in practice we can found also * values in the range [0x0FFFFFF0, 0x0FFFFFF6] which technically are * "reserved". So, how do we treat them? Well, it seems reasonable to treat * them as EOC by checking any val >= 0x0FFFFFF0 except 0x0FFFFFF7 (bad * cluster case). */ return ft == fat16_type ? val >= 0xFFF8 : val >= 0x0FFFFFF0 && val != 0x0FFFFFF7; } static inline bool fat_is_bad_cluster(enum fat_type ft, u32 val) { ASSERT(ft == fat16_type || ft == fat32_type); return ft == fat16_type ? val == 0xFFF7 : val == 0x0FFFFFF7; } static inline void * fat_get_pointer_to_cluster_data(struct fat_hdr *hdr, u32 clusterN) { u32 sector = fat_get_sector_for_cluster(hdr, clusterN); return ((u8*)hdr + sector * hdr->BPB_BytsPerSec); } static inline u32 fat_get_dir_entries_per_cluster(struct fat_hdr *h) { return ((u32)h->BPB_BytsPerSec*h->BPB_SecPerClus)/sizeof(struct fat_entry); } // PUBLIC interface ------------------------------------------------------------ bool fat32_is_valid_filename_character(char c); struct fat_walk_long_name_ctx { bool is_valid; /* long name valid ? */ u8 lname_buf[256]; /* long name buffer */ s16 lname_sz; /* long name size */ s16 lname_chksum; /* long name checksum */ }; typedef int (*fat_dentry_cb)(struct fat_hdr *, enum fat_type, struct fat_entry *, const char *, /* long name */ void *); /* user data pointer */ struct fat_walk_static_params { struct fat_walk_long_name_ctx *ctx; struct fat_hdr *h; enum fat_type ft; fat_dentry_cb cb; void *arg; }; /* * Walk the FAT directory having dir entries in the specified cluster. * For the root directory, just set cluster = 0. */ int fat_walk(struct fat_walk_static_params *p, u32 cluster); struct fat_entry * fat_search_entry(struct fat_hdr *hdr, enum fat_type ft, const char *abspath, int *err); size_t fat_get_file_size(struct fat_entry *entry); u32 fat_get_first_free_cluster_off(struct fat_hdr *hdr); u32 fat_calculate_used_bytes(struct fat_hdr *hdr); void fat_compact_clusters(struct fat_hdr *hdr); bool fat_is_first_data_sector_aligned(struct fat_hdr *hdr, u32 page_size); void fat_align_first_data_sector(struct fat_hdr *hdr, u32 page_size); size_t fat_read_whole_file(struct fat_hdr *hdr, struct fat_entry *entry, char *dest_buf, size_t dest_buf_size); // IMPLEMENTATION INTERNALS -------------------------------------------------- struct fat_search_ctx { // Input fields const char *path; // the searched path. bool single_comp; // search only for the first component // Output fields struct fat_entry *result; // the found entry or NULL u32 subdir_cluster; // the cluster of the subdir's we have to walk to bool not_dir; // path ended with '/' but entry was NOT a dir // Internal fields char pc[256]; // path component size_t pcl; // path component's length char shortname[16]; // short name of the current entry struct fat_walk_long_name_ctx walk_ctx; // walk context: contains long names }; void fat_init_search_ctx(struct fat_search_ctx *ctx, const char *path, bool single_comp); int fat_search_entry_cb(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *entry, const char *long_name, void *arg); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/mod_debugpanel.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/list.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/fs/vfs.h> #include <sys/prctl.h> // system header STATIC_ASSERT(IS_PAGE_ALIGNED(KERNEL_STACK_SIZE)); STATIC_ASSERT(IS_PAGE_ALIGNED(IO_COPYBUF_SIZE)); STATIC_ASSERT(IS_PAGE_ALIGNED(ARGS_COPYBUF_SIZE)); #define ISOLATED_STACK_HI_VMEM_SPACE (KERNEL_STACK_SIZE + (2 * PAGE_SIZE)) static void *alloc_kernel_isolated_stack(struct process *pi) { void *vaddr_in_block; void *block_vaddr; void *direct_va; ulong direct_pa; size_t count; ASSERT(pi->pdir != NULL); direct_va = kzmalloc(KERNEL_STACK_SIZE); if (!direct_va) return NULL; direct_pa = KERNEL_VA_TO_PA(direct_va); block_vaddr = hi_vmem_reserve(ISOLATED_STACK_HI_VMEM_SPACE); if (!block_vaddr) { kfree2(direct_va, KERNEL_STACK_SIZE); return NULL; } vaddr_in_block = (void *)((ulong)block_vaddr + PAGE_SIZE); count = map_pages(get_kernel_pdir(), vaddr_in_block, direct_pa, KERNEL_STACK_PAGES, PAGING_FL_RW); if (count != KERNEL_STACK_PAGES) { unmap_pages(get_kernel_pdir(), vaddr_in_block, count, false); hi_vmem_release(block_vaddr, ISOLATED_STACK_HI_VMEM_SPACE); kfree2(direct_va, KERNEL_STACK_SIZE); return NULL; } return vaddr_in_block; } static void free_kernel_isolated_stack(struct process *pi, void *vaddr_in_block) { void *block_vaddr = (void *)((ulong)vaddr_in_block - PAGE_SIZE); ulong direct_pa = get_mapping(get_kernel_pdir(), vaddr_in_block); void *direct_va = KERNEL_PA_TO_VA(direct_pa); unmap_pages(get_kernel_pdir(), vaddr_in_block, KERNEL_STACK_PAGES, false); hi_vmem_release(block_vaddr, ISOLATED_STACK_HI_VMEM_SPACE); kfree2(direct_va, KERNEL_STACK_SIZE); } #define TOT_IOBUF_AND_ARGS_BUF_PG (USER_ARGS_PAGE_COUNT + USER_ARGS_PAGE_COUNT) STATIC_ASSERT( TOT_IOBUF_AND_ARGS_BUF_PG == 2 || TOT_IOBUF_AND_ARGS_BUF_PG == 4 || TOT_IOBUF_AND_ARGS_BUF_PG == 8 || TOT_IOBUF_AND_ARGS_BUF_PG == 16 || TOT_IOBUF_AND_ARGS_BUF_PG == 32 || TOT_IOBUF_AND_ARGS_BUF_PG == 64 ); #undef TOT_IOBUF_AND_ARGS_BUF_PG static void alloc_kernel_stack(struct task *ti) { if (KERNEL_STACK_ISOLATION) { ti->kernel_stack = alloc_kernel_isolated_stack(ti->pi); } else { ti->kernel_stack = kzmalloc(KERNEL_STACK_SIZE); } } static void free_kernel_stack(struct task *ti) { if (KERNEL_STACK_ISOLATION) { free_kernel_isolated_stack(ti->pi, ti->kernel_stack); } else { kfree2(ti->kernel_stack, KERNEL_STACK_SIZE); } } static bool do_common_task_allocs(struct task *ti, bool alloc_bufs) { alloc_kernel_stack(ti); if (!ti->kernel_stack) return false; if (alloc_bufs) { ti->io_copybuf = kmalloc(IO_COPYBUF_SIZE + ARGS_COPYBUF_SIZE); if (!ti->io_copybuf) { free_kernel_stack(ti); return false; } ti->args_copybuf = (void *)((ulong)ti->io_copybuf + IO_COPYBUF_SIZE); } return true; } void process_free_mappings_info(struct process *pi) { struct mappings_info *mi = pi->mi; if (mi && !pi->vforked) { ASSERT(mi->mmap_heap); kmalloc_destroy_heap(mi->mmap_heap); kfree2(mi->mmap_heap, kmalloc_get_heap_struct_size()); kfree_obj(mi, struct mappings_info); pi->mi = NULL; } } void free_common_task_allocs(struct task *ti) { struct process *pi = ti->pi; process_free_mappings_info(pi); free_kernel_stack(ti); kfree2(ti->io_copybuf, IO_COPYBUF_SIZE + ARGS_COPYBUF_SIZE); ti->io_copybuf = NULL; ti->args_copybuf = NULL; ti->kernel_stack = NULL; } void free_mem_for_zombie_task(struct task *ti) { ASSERT_TASK_STATE(ti->state, TASK_STATE_ZOMBIE); #if DEBUG_CHECKS if (ti == get_curr_task()) { volatile ulong stack_var = 123; if (!IN_RANGE((ulong)&stack_var & PAGE_MASK, init_st_begin, init_st_end)) panic("free_mem_for_zombie_task() called w/o switch to initial stack"); } #endif free_common_task_allocs(ti); if (ti->pi->automatic_reaping) { /* The SIGCHLD signal has been EXPLICITLY ignored by the parent */ remove_task(ti); } } void init_task_lists(struct task *ti) { bintree_node_init(&ti->tree_by_tid_node); list_node_init(&ti->runnable_node); list_node_init(&ti->wakeup_timer_node); list_node_init(&ti->siblings_node); list_init(&ti->tasks_waiting_list); list_init(&ti->on_exit); bzero(&ti->wobj, sizeof(struct wait_obj)); } void init_process_lists(struct process *pi) { list_init(&pi->children); kmutex_init(&pi->fslock, KMUTEX_FL_RECURSIVE); } struct task * allocate_new_process(struct task *parent, int pid, pdir_t *new_pdir) { struct process *pi, *parent_pi = parent->pi; struct task *ti = NULL; bool common_allocs = false; bool arch_fields = false; if (UNLIKELY(!(ti = kmalloc(TOT_PROC_AND_TASK_SIZE)))) goto oom_case; pi = (struct process *)(ti + 1); /* The first process (init) has as parent == kernel_process */ ASSERT(parent != NULL); memcpy(ti, parent, sizeof(struct task)); memcpy(pi, parent_pi, sizeof(struct process)); if (MOD_debugpanel) { if (UNLIKELY(!(pi->debug_cmdline = kzmalloc(PROCESS_CMDLINE_BUF_SIZE)))) goto oom_case; if (parent_pi->debug_cmdline) { memcpy(pi->debug_cmdline, parent_pi->debug_cmdline, PROCESS_CMDLINE_BUF_SIZE); } } pi->parent_pid = parent_pi->pid; pi->pdir = new_pdir; pi->ref_count = 1; pi->pid = pid; pi->did_call_execve = false; pi->automatic_reaping = false; pi->cwd.fs = NULL; pi->vforked = false; if (new_pdir != parent_pi->pdir) { if (parent_pi->mi) { if (UNLIKELY(!(pi->mi = duplicate_mappings_info(pi, parent_pi->mi)))) goto oom_case; } if (pi->elf) retain_subsys_flock(pi->elf); } else { pi->vforked = true; } pi->inherited_mmap_heap = !!pi->mi; ti->pi = pi; ti->tid = pid; ti->is_main_thread = true; ti->timer_ready = false; /* * From fork(2): * The child's set of pending signals is initially empty. * * From sigpending(2): * A child created via fork(2) initially has an empty pending signal * set; the pending signal set is preserved across an execve(2). */ drop_all_pending_signals(ti); /* Reset sched ticks in the new process */ bzero(&ti->ticks, sizeof(ti->ticks)); /* Copy parent's `cwd` while retaining the `fs` and the inode obj */ process_set_cwd2_nolock_raw(pi, &parent_pi->cwd); if (UNLIKELY(!(common_allocs = do_common_task_allocs(ti, true)))) goto oom_case; if (UNLIKELY(!(arch_fields = arch_specific_new_task_setup(ti, parent)))) goto oom_case; arch_specific_new_proc_setup(pi, parent_pi); // NOTE: cannot fail init_task_lists(ti); init_process_lists(pi); list_add_tail(&parent_pi->children, &ti->siblings_node); pi->proc_tty = parent_pi->proc_tty; return ti; oom_case: if (ti) { if (arch_fields) arch_specific_free_task(ti); if (common_allocs) free_common_task_allocs(ti); if (pi->cwd.fs) { vfs_release_inode_at(&pi->cwd); release_obj(pi->cwd.fs); } process_free_mappings_info(ti->pi); if (MOD_debugpanel && pi->debug_cmdline) kfree2(pi->debug_cmdline, PROCESS_CMDLINE_BUF_SIZE); kfree2(ti, TOT_PROC_AND_TASK_SIZE); } return NULL; } struct task *allocate_new_thread(struct process *pi, int tid, bool alloc_bufs) { ASSERT(pi != NULL); struct task *process_task = get_process_task(pi); struct task *ti = kzalloc_obj(struct task); if (!ti || !(ti->pi = pi) || !do_common_task_allocs(ti, alloc_bufs)) { if (ti) /* do_common_task_allocs() failed */ free_common_task_allocs(ti); kfree_obj(ti, struct task); return NULL; } ti->tid = tid; ti->is_main_thread = false; init_task_lists(ti); arch_specific_new_task_setup(ti, process_task); return ti; } static void free_process_int(struct process *pi) { ASSERT(get_ref_count(pi) > 0); if (LIKELY(pi->cwd.fs != NULL)) { /* * When we change the current directory or when we fork a process, we * set a new value for the struct vfs_path pi->cwd which has its inode * retained as well as its owning fs. Here we have to release those * ref-counts. */ vfs_release_inode_at(&pi->cwd); release_obj(pi->cwd.fs); } if (release_obj(pi) == 0) { arch_specific_free_proc(pi); kfree2(get_process_task(pi), TOT_PROC_AND_TASK_SIZE); if (MOD_debugpanel) kfree2(pi->debug_cmdline, PROCESS_CMDLINE_BUF_SIZE); } } void free_task(struct task *ti) { ASSERT_TASK_STATE(ti->state, TASK_STATE_ZOMBIE); arch_specific_free_task(ti); ASSERT(!ti->kernel_stack); ASSERT(!ti->io_copybuf); ASSERT(!ti->args_copybuf); list_remove(&ti->siblings_node); if (is_main_thread(ti)) free_process_int(ti->pi); else kfree_obj(ti, struct task); } void *task_temp_kernel_alloc(size_t size) { struct task *curr = get_curr_task(); void *ptr = NULL; disable_preemption(); { ptr = kmalloc(size); if (ptr) { struct kernel_alloc *alloc = kzalloc_obj(struct kernel_alloc); if (alloc) { bintree_node_init(&alloc->node); alloc->vaddr = ptr; alloc->size = size; bintree_insert_ptr(&curr->kallocs_tree_root, alloc, struct kernel_alloc, node, vaddr); } else { kfree2(ptr, size); ptr = NULL; } } } enable_preemption(); return ptr; } void task_temp_kernel_free(void *ptr) { struct task *curr = get_curr_task(); struct kernel_alloc *alloc; if (!ptr) return; disable_preemption(); { alloc = bintree_find_ptr(curr->kallocs_tree_root, ptr, struct kernel_alloc, node, vaddr); ASSERT(alloc != NULL); kfree2(alloc->vaddr, alloc->size); bintree_remove_ptr(&curr->kallocs_tree_root, alloc, struct kernel_alloc, node, vaddr); kfree_obj(alloc, struct kernel_alloc); } enable_preemption(); } void set_kernel_process_pdir(pdir_t *pdir) { kernel_process_pi->pdir = pdir; } /* * *************************************************************** * * SYSCALLS * * *************************************************************** */ mode_t sys_umask(mode_t mask) { struct process *pi = get_curr_proc(); mode_t old = pi->umask; pi->umask = mask & 0777; return old; } int sys_getpid(void) { return get_curr_proc()->pid; } int sys_gettid(void) { return get_curr_task()->tid; } int kthread_join(int tid, bool ignore_signals) { struct task *curr = get_curr_task(); struct task *ti; int rc = 0; ASSERT(is_preemption_enabled()); disable_preemption(); while ((ti = get_task(tid))) { if (pending_signals()) { wait_obj_reset(&curr->wobj); if (!ignore_signals) { rc = -EINTR; break; } } prepare_to_wait_on(WOBJ_TASK, TO_PTR(ti->tid), NO_EXTRA, &ti->tasks_waiting_list); enter_sleep_wait_state(); /* after enter_sleep_wait_state() the preemption is be enabled */ disable_preemption(); } enable_preemption(); return rc; } int kthread_join_all(const int *tids, size_t n, bool ignore_signals) { int rc = 0; for (size_t i = 0; i < n; i++) { rc = kthread_join(tids[i], ignore_signals); if (rc) break; } return rc; } void handle_vforked_child_move_on(struct process *pi) { struct task *parent; ASSERT(!is_preemption_enabled()); ASSERT(pi->vforked); parent = get_task(pi->parent_pid); ASSERT(parent != NULL); ASSERT(parent->stopped); ASSERT(parent->vfork_stopped); parent->stopped = false; parent->vfork_stopped = false; pi->vforked = false; } int sys_getppid(void) { return get_curr_proc()->parent_pid; } /* create new session */ int sys_setsid(void) { struct process *pi = get_curr_proc(); int rc = -EPERM; disable_preemption(); if (!sched_count_proc_in_group(pi->pid)) { pi->pgid = pi->pid; pi->sid = pi->pid; pi->proc_tty = NULL; rc = pi->sid; } enable_preemption(); return rc; } /* get current session id */ int sys_getsid(int pid) { return get_curr_proc()->sid; } int sys_setpgid(int pid, int pgid) { struct process *pi; int sid; int rc = 0; if (pgid < 0) return -EINVAL; disable_preemption(); if (!pid) { pi = get_curr_proc(); } else { pi = get_process(pid); if (!pi) { rc = -ESRCH; goto out; } if (pi->did_call_execve) { rc = -EACCES; goto out; } /* Cannot move processes in other sessions */ if (pi->sid != get_curr_proc()->sid) { rc = -EPERM; goto out; } } if (pgid) { sid = sched_get_session_of_group(pgid); /* * If the process group exists (= there's at least one process with * pi->pgid == pgid), it must be in the same session as `pid` and the * calling process. */ if (sid >= 0 && sid != pi->sid) { rc = -EPERM; goto out; } /* Set process' pgid to `pgid` */ pi->pgid = pgid; } else { /* pgid is 0: make the process a group leader */ pi->pgid = pi->pid; } out: enable_preemption(); return rc; } int sys_getpgid(int pid) { struct process *pi; int ret = -ESRCH; if (!pid) return get_curr_proc()->pgid; disable_preemption(); { if ((pi = get_process(pid))) ret = pi->pgid; } enable_preemption(); return ret; } int sys_getpgrp(void) { return get_curr_proc()->pgid; } int sys_prctl(int option, ulong a2, ulong a3, ulong a4, ulong a5) { // TODO: actually implement sys_prctl() if (option == PR_SET_NAME) { // printk("[TID: %d] PR_SET_NAME '%s'\n", get_curr_task()->tid, a2); // TODO: save the task name in struct task. return 0; } printk("[TID: %d] Unknown option: %d\n", get_curr_tid(), option); return -EINVAL; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/system_mmap_int.h> #define MAX_DMA (256 * KB) STATIC_ASSERT(MAX_DMA <= 16 * MB); STATIC_ASSERT((MAX_DMA & (64 * KB - 1)) == 0); void arch_add_initial_mem_regions() { /* We want to keep the first 64 KB as reserved */ append_mem_region((struct mem_region) { .addr = 0, .len = 64 * KB, .type = MULTIBOOT_MEMORY_RESERVED, .extra = MEM_REG_EXTRA_LOWMEM, }); /* * Because we don't mmap regions not explicitly declared as AVAILABLE, we * miss some regions in the lower 1 MB. ACPI need to access them. Therefore, * create a fake 1 MB wide region marked as "available". Of course, it will * be overriden by the real system mem regions, but parts of it will remain. */ append_mem_region((struct mem_region) { .addr = 0, .len = 1024 * KB, .type = MULTIBOOT_MEMORY_AVAILABLE, .extra = MEM_REG_EXTRA_LOWMEM, }); } bool arch_add_final_mem_regions() { u64 tot_dma = 0; for (int i = 0; i < mem_regions_count; i++) { struct mem_region *m = mem_regions + i; if (m->type != MULTIBOOT_MEMORY_AVAILABLE || m->extra || m->addr > 16*MB) continue; if (tot_dma >= MAX_DMA) break; /* * We found a mem region that: * - is available * - begins in the first 16 MB * - has no extra flags * * * +--------------------------------------------+ * | Region | * +--------------------------------------------+ * +----------------------------+ * | Usable by DMA | * +----------------------------+ * * In this case we're going to add a new DMA region and shrink the * current one: * * +---------------+ * | Region | * +---------------+ * +----------------------------+ * | Usable by DMA | * +----------------------------+ * */ u64 dma_len = MIN(16 * MB - m->addr, MAX_DMA - tot_dma); append_mem_region((struct mem_region) { .addr = m->addr, .len = dma_len, .type = MULTIBOOT_MEMORY_AVAILABLE, .extra = MEM_REG_EXTRA_DMA, }); m->addr += dma_len; m->len -= dma_len; tot_dma += dma_len; } return true; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> extern const ulong vdso_begin; extern const ulong vdso_end; extern const ulong sysexit_user_code_user_vaddr; extern const ulong post_sig_handler_user_vaddr; extern const ulong pause_trampoline_user_vaddr; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/rwlock.h> #include <tilck/kernel/sched.h> void rwlock_rp_init(struct rwlock_rp *r) { kmutex_init(&r->readers_lock, 0); ksem_init(&r->writers_sem, 1, 1); r->readers_count = 0; DEBUG_ONLY(r->ex_owner = NULL); } void rwlock_rp_destroy(struct rwlock_rp *r) { DEBUG_ONLY(r->ex_owner = NULL); r->readers_count = 0; ksem_destroy(&r->writers_sem); kmutex_destroy(&r->readers_lock); } void rwlock_rp_shlock(struct rwlock_rp *r) { kmutex_lock(&r->readers_lock); { if (++r->readers_count == 1) ksem_wait(&r->writers_sem, 1, KSEM_WAIT_FOREVER); } kmutex_unlock(&r->readers_lock); } void rwlock_rp_shunlock(struct rwlock_rp *r) { kmutex_lock(&r->readers_lock); { if (--r->readers_count == 0) ksem_signal(&r->writers_sem, 1); } kmutex_unlock(&r->readers_lock); } void rwlock_rp_exlock(struct rwlock_rp *r) { ksem_wait(&r->writers_sem, 1, KSEM_WAIT_FOREVER); ASSERT(r->ex_owner == NULL); DEBUG_ONLY(r->ex_owner = get_curr_task()); } void rwlock_rp_exunlock(struct rwlock_rp *r) { ASSERT(r->ex_owner == get_curr_task()); DEBUG_ONLY(r->ex_owner = NULL); ksem_signal(&r->writers_sem, 1); } /* ---------------------------------------------- */ void rwlock_wp_init(struct rwlock_wp *rw, bool recursive) { kmutex_init(&rw->m, 0); kcond_init(&rw->c); rw->ex_owner = NULL; rw->r = 0; rw->w = false; rw->rec = recursive; } void rwlock_wp_destroy(struct rwlock_wp *rw) { rw->ex_owner = NULL; rw->w = false; rw->r = 0; kcond_destory(&rw->c); kmutex_destroy(&rw->m); } void rwlock_wp_shlock(struct rwlock_wp *rw) { kmutex_lock(&rw->m); { /* Wait until there's at least one writer waiting (they have priority) */ while (rw->w) { kcond_wait(&rw->c, &rw->m, KCOND_WAIT_FOREVER); } /* * OK, no writer is waiting and we're holding the mutex: we can safely * increment the readers count and claim that the acquired a shared * lock. */ rw->r++; } kmutex_unlock(&rw->m); } void rwlock_wp_shunlock(struct rwlock_wp *rw) { kmutex_lock(&rw->m); { /* * Decrement the readers count and, in case there no more readers, signal * the condition in order to wake-up the writers are waiting on it. */ if (--rw->r == 0) kcond_signal_one(&rw->c); } kmutex_unlock(&rw->m); } static void rwlock_wp_exlock_int(struct rwlock_wp *rw) { if (rw->rec) { if (rw->ex_owner == get_curr_task()) { ASSERT(rw->w); ASSERT(rw->rc >= 1); rw->rc++; return; } } /* Wait our turn until other writers are waiting to write */ while (rw->w) { kcond_wait(&rw->c, &rw->m, KCOND_WAIT_FOREVER); } /* * OK, no writer is waiting to write and we're holding the mutex: now * it's our turn to wait on the condition `readers > 0`. */ rw->w = true; /* Wait until there are any readers currently holding the rwlock */ while (rw->r > 0) { kcond_wait(&rw->c, &rw->m, KCOND_WAIT_FOREVER); } /* * No more readers: great. Now we're really holding an exclusive access to * the rwlock. New readers cannot acquire a shared lock because `w` is set * and other writes cannot acquire it, for the same reason. */ ASSERT(rw->ex_owner == NULL); rw->ex_owner = get_curr_task(); if (rw->rec) { /* recursive locking count */ ASSERT(rw->rc == 0); rw->rc++; } } void rwlock_wp_exlock(struct rwlock_wp *rw) { kmutex_lock(&rw->m); { rwlock_wp_exlock_int(rw); } kmutex_unlock(&rw->m); } static void rwlock_wp_exunlock_int(struct rwlock_wp *rw) { ASSERT(rw->ex_owner == get_curr_task()); if (rw->rec) { /* recursive locking count */ ASSERT(rw->rec > 0); ASSERT(rw->w); rw->rc--; if (rw->rc > 0) return; } rw->ex_owner = NULL; /* The `w` flag must be set */ ASSERT(rw->w); /* Unset the `w` flag (no more writers) */ rw->w = false; /* Signal all the readers potentially waiting on the condition */ kcond_signal_all(&rw->c); } void rwlock_wp_exunlock(struct rwlock_wp *rw) { kmutex_lock(&rw->m); { rwlock_wp_exunlock_int(rw); } kmutex_unlock(&rw->m); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/fs/vfs.h> #include <tilck/mods/sysfs.h> #include <tilck/mods/sysfs_utils.h> struct sysfs_inode; #define SYSFS_ENTRY_SIZE 64 #define SYSFS_ENTRY_MAX_LEN ( \ SYSFS_ENTRY_SIZE \ - sizeof(struct bintree_node) \ - sizeof(struct list_node) \ - sizeof(struct ramfs_inode *) \ - sizeof(u8) \ ) struct sysfs_entry { struct bintree_node node; struct list_node lnode; struct sysfs_inode *inode; u8 name_len; /* NOTE: includes the final \0 */ char name[SYSFS_ENTRY_MAX_LEN]; }; STATIC_ASSERT(sizeof(struct sysfs_entry) == SYSFS_ENTRY_SIZE); struct sysfs_inode { REF_COUNTED_OBJECT; enum vfs_entry_type type; tilck_ino_t ino; union { struct { struct sysobj *obj; struct sysobj_prop *prop; void *prop_data; } file; struct { offt num_entries; struct ramfs_entry *entries_tree_root; struct list entries_list; struct sysobj *obj; } dir; struct { u32 path_len; char *path; } symlink; }; }; struct sysfs_data { struct sysfs_inode *root; struct rwlock_wp rwlock; tilck_ino_t next_inode; time_t wrt_time; struct list dirty_handles; }; struct sysfs_handle { /* struct fs_handle_base */ FS_HANDLE_BASE_FIELDS enum vfs_entry_type type; struct sysfs_inode *inode; union { struct { char *data; offt data_len; offt data_max_len; struct list_node dirty_node; } file; struct { struct sysfs_entry *dpos; } dir; }; }; CREATE_FS_PATH_STRUCT(sysfs_path, struct sysfs_inode *, struct sysfs_entry *); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define DEFINE_TERM_ACTION_0(name) \ static void \ __term_action_##name(term *_t, ulong __u1, ulong __u2, ulong __u3) { \ struct vterm *const t = _t; \ term_action_##name(t); \ } #define DEFINE_TERM_ACTION_1(name, t1) \ static void \ __term_action_##name(term *_t, ulong __a1, ulong __u1, ulong __u2) { \ struct vterm *const t = _t; \ term_action_##name(t, (t1)__a1); \ } #define DEFINE_TERM_ACTION_2(name, t1, t2) \ static void \ __term_action_##name(term *_t, ulong __a1, ulong __a2, ulong __u1) { \ struct vterm *const t = _t; \ term_action_##name(t, (t1)__a1, (t2)__a2); \ } #define DEFINE_TERM_ACTION_3(name, t1, t2, t3) \ static void \ __term_action_##name(term *_t, ulong __a1, ulong __a2, ulong __a3) { \ struct vterm *const t = _t; \ term_action_##name(t, (t1)__a1, (t2)__a2, (t3)__a3); \ } #define CALL_ACTION_FUNC_0(func, t) \ (func)((t), 0, 0, 0) #define CALL_ACTION_FUNC_1(func, t, a1) \ (func)((t), (ulong)(a1), 0, 0) #define CALL_ACTION_FUNC_2(func, t, a1, a2) \ (func)((t), (ulong)(a1), (ulong)(a2), 0) #define CALL_ACTION_FUNC_3(func, t, a1, a2, a3) \ (func)((t), (ulong)(a1), (ulong)(a2), (ulong)(a3)) static void term_action_none(struct vterm *const t) { /* do nothing */ } DEFINE_TERM_ACTION_0(none) static void term_action_enable_cursor(struct vterm *const t, bool val) { term_int_enable_cursor(t, val); } DEFINE_TERM_ACTION_1(enable_cursor, bool) static void term_action_scroll(struct vterm *const t, u32 lines, enum term_scroll_type st) { ASSERT(st == term_scroll_up || st == term_scroll_down); if (st == term_scroll_up) term_int_scroll_up(t, lines); else term_int_scroll_down(t, lines); } DEFINE_TERM_ACTION_2(scroll, u32, enum term_scroll_type) static void term_action_non_buf_scroll(struct vterm *const t, u16 n, enum term_scroll_type st) { ASSERT(st == term_scroll_up || st == term_scroll_down); if (st == term_scroll_up) term_internal_non_buf_scroll_up(t, n); else term_internal_non_buf_scroll_down(t, n); } DEFINE_TERM_ACTION_2(non_buf_scroll, u16, enum term_scroll_type) static void term_action_move_cur(struct vterm *const t, int row, int col) { term_int_move_cur(t, row, col); } DEFINE_TERM_ACTION_2(move_cur, int, int) static void term_action_write(struct vterm *const t, const char *buf, u32 len, u8 color) { const struct video_interface *const vi = t->vi; ts_scroll_to_bottom(t); vi->enable_cursor(); for (u32 i = 0; i < len; i++) { if (UNLIKELY(t->filter == NULL)) { /* Early term use by printk(), before tty has been initialized */ term_internal_write_char2(t, buf[i], color); continue; } /* * NOTE: We MUST store buf[i] in a local variable because the filter * function is absolutely allowed to modify its contents!! * * (Of course, buf is *not* required to point to writable memory.) */ char c = buf[i]; struct term_action a = { .type1 = a_none }; enum term_fret r = t->filter((u8 *)&c, &color, &a, t->filter_ctx); if (LIKELY(r == TERM_FILTER_WRITE_C)) term_internal_write_char2(t, c, color); term_execute_action(t, &a); } if (t->cursor_enabled) vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); } DEFINE_TERM_ACTION_3(write, const char *, u32, u8) /* Direct write without any filter nor move_cursor/flush */ static void term_action_direct_write(struct vterm *const t, char *buf, u32 len, u8 color) { for (u32 i = 0; i < len; i++) term_internal_write_char2(t, buf[i], color); } DEFINE_TERM_ACTION_3(direct_write, char *, u32, u8) static void term_action_set_col_offset(struct vterm *const t, u16 off) { t->col_offset = off; } DEFINE_TERM_ACTION_1(set_col_offset, u16) static void term_action_move_cur_rel(struct vterm *const t, s16 dr, s16 dc) { if (!t->buffer) return; t->r = (u16) CLAMP((int)t->r + dr, 0, t->rows - 1); t->c = (u16) CLAMP((int)t->c + dc, 0, t->cols - 1); if (t->cursor_enabled) t->vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); } DEFINE_TERM_ACTION_2(move_cur_rel, s16, s16) static void term_action_reset(struct vterm *const t) { t->vi->enable_cursor(); term_int_move_cur(t, 0, 0); t->scroll = t->max_scroll = 0; for (u16 i = 0; i < t->rows; i++) ts_clear_row(t, i, DEFAULT_COLOR16); if (t->tabs_buf) memset(t->tabs_buf, 0, t->cols * t->rows); } DEFINE_TERM_ACTION_0(reset) static void term_action_erase_in_display(struct vterm *const t, int mode) { const u16 entry = make_vgaentry(' ', DEFAULT_COLOR16); switch (mode) { case 0: /* Clear the screen from the cursor position up to the end */ for (u16 col = t->c; col < t->cols; col++) { buf_set_entry(t, t->r, col, entry); t->vi->set_char_at(t->r, col, entry); } for (u16 i = t->r + 1; i < t->rows; i++) ts_clear_row(t, i, DEFAULT_COLOR16); break; case 1: /* Clear the screen from the beginning up to cursor's position */ for (u16 i = 0; i < t->r; i++) ts_clear_row(t, i, DEFAULT_COLOR16); for (u16 col = 0; col < t->c; col++) { buf_set_entry(t, t->r, col, entry); t->vi->set_char_at(t->r, col, entry); } break; case 2: /* Clear the whole screen */ for (u16 i = 0; i < t->rows; i++) ts_clear_row(t, i, DEFAULT_COLOR16); break; case 3: /* Clear the whole screen and erase the scroll buffer */ { u16 row = t->r; u16 col = t->c; term_action_reset(t); if (t->cursor_enabled) t->vi->move_cursor(row, col, DEFAULT_COLOR16); } break; default: return; } } DEFINE_TERM_ACTION_1(erase_in_display, int) static void term_action_erase_in_line(struct vterm *const t, int mode) { const u16 entry = make_vgaentry(' ', DEFAULT_COLOR16); switch (mode) { case 0: for (u16 col = t->c; col < t->cols; col++) { buf_set_entry(t, t->r, col, entry); t->vi->set_char_at(t->r, col, entry); } break; case 1: for (u16 col = 0; col < t->c; col++) { buf_set_entry(t, t->r, col, entry); t->vi->set_char_at(t->r, col, entry); } break; case 2: ts_clear_row(t, t->r, vgaentry_get_color(entry)); break; default: return; } } DEFINE_TERM_ACTION_1(erase_in_line, int) static void term_action_del(struct vterm *const t, enum term_del_type del_type, int m) { switch (del_type) { case TERM_DEL_PREV_CHAR: term_internal_write_backspace(t, get_curr_cell_color(t)); break; case TERM_DEL_PREV_WORD: term_internal_delete_last_word(t, get_curr_cell_color(t)); break; case TERM_DEL_ERASE_IN_DISPLAY: term_action_erase_in_display(t, m); break; case TERM_DEL_ERASE_IN_LINE: term_action_erase_in_line(t, m); break; default: NOT_REACHED(); } } DEFINE_TERM_ACTION_2(del, enum term_del_type, int) static void term_action_ins_blank_chars(struct vterm *const t, u16 n) { const u16 row = t->r; u16 *const buf_row = get_buf_row(t, row); n = (u16)MIN(n, t->cols - t->c); memmove(&buf_row[t->c + n], &buf_row[t->c], 2 * (t->cols - t->c - n)); for (u16 c = t->c; c < t->c + n; c++) buf_row[c] = make_vgaentry(' ', vgaentry_get_color(buf_row[c])); for (u16 c = t->c; c < t->cols; c++) t->vi->set_char_at(row, c, buf_row[c]); } DEFINE_TERM_ACTION_1(ins_blank_chars, u16) static void term_action_del_chars_in_line(struct vterm *const t, u16 n) { const u16 row = t->r; u16 *const buf_row = get_buf_row(t, row); const u16 maxN = (u16)MIN(n, t->cols - t->c); const u16 cN = t->cols - t->c - maxN; /* copied count */ memmove(&buf_row[t->c], &buf_row[t->c + maxN], 2 * cN); for (u16 c = t->c + cN; c < MIN(t->c + cN + n - maxN, t->cols); c++) buf_row[c] = make_vgaentry(' ', vgaentry_get_color(buf_row[c])); for (u16 c = t->c; c < t->cols; c++) t->vi->set_char_at(row, c, buf_row[c]); } DEFINE_TERM_ACTION_1(del_chars_in_line, u16) static void term_action_erase_chars_in_line(struct vterm *const t, u16 n) { const u16 row = t->r; u16 *const buf_row = get_buf_row(t, row); for (u16 c = t->c; c < MIN(t->cols, t->c + n); c++) buf_row[c] = make_vgaentry(' ', vgaentry_get_color(buf_row[c])); for (u16 c = t->c; c < t->cols; c++) t->vi->set_char_at(row, c, buf_row[c]); } DEFINE_TERM_ACTION_1(erase_chars_in_line, u16) static void term_action_pause_output(struct vterm *const t) { if (t->vi->disable_static_elems_refresh) t->vi->disable_static_elems_refresh(); t->vi->disable_cursor(); t->saved_vi = t->vi; t->vi = &no_output_vi; } DEFINE_TERM_ACTION_0(pause_output) static void term_action_restart_output(struct vterm *const t) { t->vi = t->saved_vi; term_redraw(t); if (t->scroll == t->max_scroll) term_int_enable_cursor(t, t->cursor_enabled); if (!in_panic()) { if (t->vi->redraw_static_elements) t->vi->redraw_static_elements(); if (t->vi->enable_static_elems_refresh) t->vi->enable_static_elems_refresh(); } } DEFINE_TERM_ACTION_0(restart_output) static void term_action_use_alt_buffer(struct vterm *const t, bool use_alt_buffer) { u16 *b = get_buf_row(t, 0); if (t->using_alt_buffer == use_alt_buffer) return; if (use_alt_buffer) { if (!t->screen_buf_copy) { if (term_allocate_alt_buffers(t) < 0) return; /* just do nothing: the main buffer will be used */ } t->start_scroll_region = &t->alt_scroll_region_start; t->end_scroll_region = &t->alt_scroll_region_end; t->tabs_buf = t->alt_tabs_buf; t->saved_cur_row = t->r; t->saved_cur_col = t->c; memcpy(t->screen_buf_copy, b, sizeof(u16) * t->rows * t->cols); } else { ASSERT(t->screen_buf_copy != NULL); memcpy(b, t->screen_buf_copy, sizeof(u16) * t->rows * t->cols); t->r = t->saved_cur_row; t->c = t->saved_cur_col; t->tabs_buf = t->main_tabs_buf; t->start_scroll_region = &t->main_scroll_region_start; t->end_scroll_region = &t->main_scroll_region_end; } t->using_alt_buffer = use_alt_buffer; t->vi->disable_cursor(); term_redraw(t); term_int_enable_cursor(t, t->cursor_enabled); } DEFINE_TERM_ACTION_1(use_alt_buffer, bool) static void term_action_ins_blank_lines(struct vterm *const t, u32 n) { const u16 eR = *t->end_scroll_region + 1; if (!t->buffer || !n) return; if (t->r >= eR) return; /* we're outside the scrolling region: do nothing */ t->c = 0; n = MIN(n, (u32)(eR - t->r)); for (u32 row = eR - n; row > t->r; row--) buf_copy_row(t, row - 1 + n, row - 1); for (u16 row = t->r; row < t->r + n; row++) ts_buf_clear_row(t, row, DEFAULT_COLOR16); term_redraw_scroll_region(t); } DEFINE_TERM_ACTION_1(ins_blank_lines, u32) static void term_action_del_lines(struct vterm *const t, u32 n) { const u16 eR = *t->end_scroll_region + 1; if (!t->buffer || !n) return; if (t->r >= eR) return; /* we're outside the scrolling region: do nothing */ n = MIN(n, (u32)(eR - t->r)); for (u32 row = t->r; row <= t->r + n; row++) buf_copy_row(t, row, row + n); for (u32 row = eR - n; row < eR; row++) ts_buf_clear_row(t, (u16)row, DEFAULT_COLOR16); term_redraw_scroll_region(t); } DEFINE_TERM_ACTION_1(del_lines, u32) static void term_action_set_scroll_region(struct vterm *const t, u16 start, u16 end) { start = (u16) CLAMP(start, 0u, t->rows - 1u); end = (u16) CLAMP(end, 0u, t->rows - 1u); if (start >= end) return; *t->start_scroll_region = start; *t->end_scroll_region = end; term_int_move_cur(t, 0, 0); } DEFINE_TERM_ACTION_2(set_scroll_region, u16, u16) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/ringbuf.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/bintree.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/debug_utils.h> #include <tilck/mods/tracing.h> #define TRACE_BUF_SIZE (128 * KB) struct symbol_node { struct bintree_node node; u32 sys_n; void *vaddr; const char *name; }; static struct kmutex tracing_lock; static struct kcond tracing_cond; static struct ringbuf tracing_rb; static void *tracing_buf; static u32 syms_count; static struct symbol_node *syms_buf; static struct symbol_node *syms_bintree; static const struct syscall_info **syscalls_info; static s8 (*params_slots)[MAX_SYSCALLS][6]; static s8 *syscalls_fmts; STATIC char *traced_syscalls_str; static int traced_syscalls_count; bool *traced_syscalls; bool __force_exp_block; bool __tracing_on; bool __tracing_dump_big_bufs; int __tracing_printk_lvl = 10; const char *get_signal_name(int signum) { static const char *sig_names[_NSIG] = { [SIGHUP] = "SIGHUP", [SIGINT] = "SIGINT", [SIGQUIT] = "SIGQUIT", [SIGILL] = "SIGILL", [SIGABRT] = "SIGABRT", [SIGFPE] = "SIGFPE", [SIGKILL] = "SIGKILL", [SIGSEGV] = "SIGSEGV", [SIGPIPE] = "SIGPIPE", [SIGALRM] = "SIGALRM", [SIGTERM] = "SIGTERM", [SIGUSR1] = "SIGUSR1", [SIGUSR2] = "SIGUSR2", [SIGCHLD] = "SIGCHLD", [SIGCONT] = "SIGCONT", [SIGSTOP] = "SIGSTOP", [SIGTSTP] = "SIGTSTP", [SIGTTIN] = "SIGTTIN", [SIGTTOU] = "SIGTTOU", [SIGBUS] = "SIGBUS", [SIGPOLL] = "SIGPOLL", [SIGPROF] = "SIGPROF", [SIGSYS] = "SIGSYS", [SIGTRAP] = "SIGTRAP", [SIGURG] = "SIGURG", [SIGVTALRM] = "SIGVTALRM", [SIGXCPU] = "SIGXCPU", [SIGXFSZ] = "SIGXFSZ", [SIGPWR] = "SIGPWR", [SIGWINCH] = "SIGWINCH", }; return sig_names[signum] ? sig_names[signum] : ""; } static int elf_symbol_cb(struct elf_symbol_info *i, void *arg) { struct symbol_node *sym_node; int sys_n; if (!i->name || strncmp(i->name, "sys_", 4)) return 0; /* not a syscall symbol */ if ((sys_n = get_syscall_num(i->vaddr)) < 0) return 0; /* not a syscall, just a function start with sys_ */ sym_node = &syms_buf[syms_count]; *sym_node = (struct symbol_node) { .sys_n = (u32) sys_n, .vaddr = i->vaddr, .name = i->name, }; bintree_node_init(&sym_node->node); bintree_insert_ptr(&syms_bintree, sym_node, struct symbol_node, node, vaddr); syms_count++; return 0; } const char * tracing_get_syscall_name(u32 n) { void *ptr; struct symbol_node *node; if (!(ptr = get_syscall_func_ptr(n))) return NULL; node = bintree_find_ptr(syms_bintree, ptr, struct symbol_node, node, vaddr); if (!node) return NULL; return node->name; } int tracing_get_param_idx(const struct syscall_info *si, const char *name) { for (int i = 0; i < si->n_params; i++) { const struct sys_param_info *p = &si->params[i]; /* * NOTE: using pointer comparison instead of strcmp() for strings. * This code assumes that in the metadata the same string literal will * be used both for the parameter name and the `helper_param_name` field. */ if (p->name == name) return i; } return -1; } static void trace_syscall_enter_save_params(const struct syscall_info *si, struct trace_event *e) { if (!si) return; struct syscall_event_data *se = &e->sys_ev; char *buf = NULL; size_t bs = 0; int idx; for (int i = 0; i < si->n_params; i++) { const struct sys_param_info *p = &si->params[i]; const struct sys_param_type *t = p->type; if (t->save && (p->kind == sys_param_in || p->kind == sys_param_in_out)) { long sz = -1; if (p->helper_param_name) { idx = tracing_get_param_idx(si, p->helper_param_name); ASSERT(idx >= 0); sz = (long) se->args[idx]; } tracing_get_slot(e, si, i, &buf, &bs); ASSERT(buf && bs > 0); t->save(TO_PTR(se->args[i]), sz, buf, bs); } } } static void trace_syscall_exit_save_params(const struct syscall_info *si, struct trace_event *e) { if (!si) return; struct syscall_event_data *se = &e->sys_ev; char *buf = NULL; size_t bs = 0; int idx; for (int i = 0; i < si->n_params; i++) { const struct sys_param_info *p = &si->params[i]; const struct sys_param_type *t = p->type; const bool outp = p->kind == sys_param_out || p->kind == sys_param_in_out; if (t->save && (!exp_block(si) || outp)) { long sz = -1; if (p->helper_param_name) { idx = tracing_get_param_idx(si, p->helper_param_name); ASSERT(idx >= 0); sz = (long) se->args[idx]; } tracing_get_slot(e, si, i, &buf, &bs); ASSERT(buf && bs > 0); t->save(TO_PTR(se->args[i]), sz, buf, bs); } } } static void enqueue_trace_event(struct trace_event *e) { kmutex_lock(&tracing_lock); { ringbuf_write_elem(&tracing_rb, e); kcond_signal_one(&tracing_cond); } kmutex_unlock(&tracing_lock); } void trace_syscall_enter_int(u32 sys, ulong a1, ulong a2, ulong a3, ulong a4, ulong a5, ulong a6) { const struct syscall_info *si = tracing_get_syscall_info(sys); if (!get_curr_task()->traced) return; /* the current task is not traced */ if (si && !exp_block(si)) return; /* don't trace the enter event */ struct trace_event e = { .type = te_sys_enter, .tid = get_curr_tid(), .sys_time = get_sys_time(), .sys_ev = { .sys = sys, .args = {a1,a2,a3,a4,a5,a6} } }; trace_syscall_enter_save_params(si, &e); enqueue_trace_event(&e); } void trace_syscall_exit_int(u32 sys, long retval, ulong a1, ulong a2, ulong a3, ulong a4, ulong a5, ulong a6) { const struct syscall_info *si = tracing_get_syscall_info(sys); if (!get_curr_task()->traced) return; /* the current task is not traced */ struct trace_event e = { .type = te_sys_exit, .tid = get_curr_tid(), .sys_time = get_sys_time(), .sys_ev = { .sys = sys, .retval = retval, .args = {a1,a2,a3,a4,a5,a6} } }; trace_syscall_exit_save_params(si, &e); enqueue_trace_event(&e); } void trace_printk_int(int level, const char *fmt, ...) { ASSERT(level >= 1); if (__tracing_printk_lvl < level) return; struct trace_event e = { .type = te_printk, .tid = get_curr_tid(), .sys_time = get_sys_time(), .p_ev = { .level = level, } }; va_list args; va_start(args, fmt); vsnprintk(e.p_ev.buf, sizeof(e.p_ev.buf), fmt, args); va_end(args); enqueue_trace_event(&e); } void trace_signal_delivered_int(int target_tid, int signum) { struct task *ti; disable_preemption(); { ti = get_task(target_tid); } enable_preemption(); if (!ti) return; if (!ti->traced) return; /* the task is not traced */ struct trace_event e = { .type = te_signal_delivered, .tid = target_tid, .sys_time = get_sys_time(), .sig_ev = { .signum = signum } }; enqueue_trace_event(&e); } void trace_task_killed_int(int signum) { if (!get_curr_task()->traced) return; /* the current task is not traced */ struct trace_event e = { .type = te_killed, .tid = get_curr_tid(), .sys_time = get_sys_time(), .sig_ev = { .signum = signum } }; enqueue_trace_event(&e); } bool read_trace_event_noblock(struct trace_event *e) { bool ret; kmutex_lock(&tracing_lock); { ret = ringbuf_read_elem(&tracing_rb, e); } kmutex_unlock(&tracing_lock); return ret; } bool read_trace_event(struct trace_event *e, u32 timeout_ticks) { bool ret; kmutex_lock(&tracing_lock); { if (ringbuf_is_empty(&tracing_rb)) kcond_wait(&tracing_cond, &tracing_lock, timeout_ticks); ret = ringbuf_read_elem(&tracing_rb, e); } kmutex_unlock(&tracing_lock); return ret; } const struct syscall_info * tracing_get_syscall_info(u32 n) { if (n >= MAX_SYSCALLS) return NULL; return syscalls_info[n]; } #define NULL_TRACE_EVENT ((struct trace_event *)0) #define GET_SLOT(e, fmt_n, slot_n) ((e)->sys_ev.fmt##fmt_n.d##slot_n) #define GET_SLOT_ABS_OFF(fmt_n, slot_n) \ ((ulong)GET_SLOT(NULL_TRACE_EVENT, fmt_n, slot_n)) #define GET_SLOT_OFF(fmt_n, slot_n) \ (GET_SLOT_ABS_OFF(fmt_n, slot_n) - GET_SLOT_ABS_OFF(fmt_n, 0)) #define GET_SLOT_SIZE(fmt_n, slot_n) \ sizeof(GET_SLOT(NULL_TRACE_EVENT, fmt_n, slot_n)) #define CAN_USE_SLOT(sys, fmt_n, slot_n, size) \ (GET_SLOT_SIZE(fmt_n, slot_n) >= size && is_slot_free(sys, slot_n)) static const size_t fmt_offsets[2][4] = { /* fmt 0 */ { GET_SLOT_ABS_OFF(0, 0), GET_SLOT_ABS_OFF(0, 1), GET_SLOT_ABS_OFF(0, 2), GET_SLOT_ABS_OFF(0, 3), }, /* fmt 1 */ { GET_SLOT_ABS_OFF(1, 0), GET_SLOT_ABS_OFF(1, 1), GET_SLOT_ABS_OFF(1, 2), 0, }, }; static const size_t fmt_sizes[2][4] = { /* fmt 0 */ { GET_SLOT_SIZE(0, 0), GET_SLOT_SIZE(0, 1), GET_SLOT_SIZE(0, 2), GET_SLOT_SIZE(0, 3), }, /* fmt 1 */ { GET_SLOT_SIZE(1, 0), GET_SLOT_SIZE(1, 1), GET_SLOT_SIZE(1, 2), 0, }, }; bool tracing_get_slot(struct trace_event *e, const struct syscall_info *si, int p_idx, char **buf, size_t *size) { ASSERT(e->type == te_sys_enter || e->type == te_sys_exit); const s8 slot = (*params_slots)[e->sys_ev.sys][p_idx]; s8 fmt; if (slot == NO_SLOT) return false; fmt = syscalls_fmts[si->sys_n]; *buf = (char *)e + fmt_offsets[fmt][slot]; *size = fmt_sizes[fmt][slot]; return true; } static bool is_slot_free(u32 sys, int slot) { ASSERT(slot >= 0); for (int i = 0; i < 6; i++) if ((*params_slots)[sys][i] == slot) return false; return true; } static bool alloc_for_fmt0(u32 sys, int p_idx, size_t size) { s8 slot = NO_SLOT; if (!size) return true; /* we're fine: no need to allocate anything for this param */ if (CAN_USE_SLOT(sys, 0, 3, size)) slot = 3; else if (CAN_USE_SLOT(sys, 0, 2, size)) slot = 2; else if (CAN_USE_SLOT(sys, 0, 1, size)) slot = 1; else if (CAN_USE_SLOT(sys, 0, 0, size)) slot = 0; else return false; /* we failed: another fmt should be used for this syscall */ (*params_slots)[sys][p_idx] = slot; return true; /* everything is alright */ } static bool alloc_for_fmt1(u32 sys, int p_idx, size_t size) { s8 slot = NO_SLOT; if (!size) return true; /* we're fine: no need to allocate anything for this param */ if (CAN_USE_SLOT(sys, 1, 2, size)) slot = 2; else if (CAN_USE_SLOT(sys, 1, 1, size)) slot = 1; else if (CAN_USE_SLOT(sys, 1, 0, size)) slot = 0; else return false; /* we failed: another fmt should be used for this syscall */ (*params_slots)[sys][p_idx] = slot; return true; /* everything is alright */ } static void tracing_populate_syscalls_info(void) { const struct syscall_info *si; for (si = tracing_metadata; si->sys_n != INVALID_SYSCALL; si++) { syscalls_info[si->sys_n] = si; } } static void tracing_reset_slot_info(u32 sys) { for (int j = 0; j < 6; j++) (*params_slots)[sys][j] = NO_SLOT; } static void tracing_allocate_slots_for_params(void) { const struct syscall_info *si; bool failed; for (u32 i = 0; i < MAX_SYSCALLS; i++) tracing_reset_slot_info(i); for (si = tracing_metadata; si->sys_n != INVALID_SYSCALL; si++) { const struct sys_param_info *p = si->params; const u32 sys_n = si->sys_n; failed = false; syscalls_fmts[sys_n] = 0; /* fmt 0 */ for (int i = 0; i < si->n_params; i++) if ((failed = !alloc_for_fmt0(sys_n, i, p[i].type->slot_size))) break; if (!failed) continue; failed = false; syscalls_fmts[sys_n] = 1; /* fmt 1 */ tracing_reset_slot_info(sys_n); for (int i = 0; i < si->n_params; i++) if ((failed = !alloc_for_fmt1(sys_n, i, p[i].type->slot_size))) break; if (!failed) continue; panic("Unable to alloc param slots for syscall #%u", sys_n); } } static void debug_tracing_dump_syscalls_fmt(void) { const struct syscall_info *si; s8 fmt; for (si = tracing_metadata; si->sys_n != INVALID_SYSCALL; si++) { fmt = syscalls_fmts[si->sys_n]; printk("sys #%u -> fmt %d\n", si->sys_n, fmt); } } void get_traced_syscalls_str(char *buf, size_t len) { memcpy(buf, traced_syscalls_str, MIN(len, TRACED_SYSCALLS_STR_LEN)); } int get_traced_syscalls_count(void) { return traced_syscalls_count; } /* * Minimalistic wildcard matching function. * * It supports only '*' at the end of an expression like: * * ab* matches: abc, ab, abcdefgh, etc. * * matches EVERYTHING * * And the jolly character '?' which matches exactly one character (any). * * NOTE: * ab*c matches NOTHING because '*' must be the last char, if present. * */ STATIC bool simple_wildcard_match(const char *str, const char *expr) { for (; *str && *expr; str++, expr++) { if (*expr == '*') return !expr[1]; /* always fail if '*' is NOT the last char */ if (*str != *expr && *expr != '?') return false; /* not a match */ } /* Both `expr` and `str` ended: match */ if (!*expr && !*str) return true; /* If `str` just ended while `expr` has just one more '*': match */ if (*expr == '*' && !expr[1]) return true; return false; /* not a match */ } STATIC int handle_sys_trace_arg(const char *arg) { struct bintree_walk_ctx ctx; struct symbol_node *n; bool match_sign = true; if (!*arg) return 0; /* empty string */ if (*arg == '!') { if (!arg[1]) return 0; /* empty negation string */ match_sign = false; arg++; } bintree_in_order_visit_start(&ctx, syms_bintree, struct symbol_node, node, false); while ((n = bintree_in_order_visit_next(&ctx))) { if (simple_wildcard_match(n->name + 4, arg)) traced_syscalls[n->sys_n] = match_sign; } return 0; } STATIC int set_traced_syscalls_int(const char *str) { const size_t len = strlen(str); const char *s = str; char *p, buf[32]; int rc; if (len >= TRACED_SYSCALLS_STR_LEN) return -ENAMETOOLONG; for (p = buf; *s; s++) { if (p == buf + sizeof(buf)) return -ENAMETOOLONG; if (*s == ',' || *s == ' ') { *p = 0; p = buf; if ((rc = handle_sys_trace_arg(buf))) return rc; continue; } *p++ = *s; } if (p > buf) { *p = 0; if ((rc = handle_sys_trace_arg(buf))) return rc; } traced_syscalls_count = 0; for (int i = 0; i < MAX_SYSCALLS; i++) if (traced_syscalls[i]) traced_syscalls_count++; memcpy(traced_syscalls_str, str, len + 1); return 0; } static void reset_traced_syscalls(void) { for (int i = 0; i < MAX_SYSCALLS; i++) traced_syscalls[i] = false; } int set_traced_syscalls(const char *s) { int rc; disable_preemption(); { reset_traced_syscalls(); if ((rc = set_traced_syscalls_int(s))) reset_traced_syscalls(); } enable_preemption(); return rc; } int tracing_get_in_buffer_events_count(void) { int rc; kmutex_lock(&tracing_lock); { rc = (int)ringbuf_get_elems(&tracing_rb); // integer narrowing } kmutex_unlock(&tracing_lock); return rc; } static void tracing_init_oom_panic(const char *buf_name) { panic("Unable to allocate %s in init_tracing()", buf_name); } void init_tracing(void) { if (!(tracing_buf = kzmalloc(TRACE_BUF_SIZE))) tracing_init_oom_panic("tracing_buf"); if (!(syms_buf = kalloc_array_obj(struct symbol_node, MAX_SYSCALLS))) tracing_init_oom_panic("syms_buf"); if (!(syscalls_info = kzalloc_array_obj(void *, MAX_SYSCALLS))) tracing_init_oom_panic("syscalls_info"); if (!(params_slots = kmalloc(sizeof(*params_slots)))) tracing_init_oom_panic("params_slots"); if (!(syscalls_fmts = kzalloc_array_obj(s8, MAX_SYSCALLS))) tracing_init_oom_panic("syscalls_fmts"); if (!(traced_syscalls = kmalloc(MAX_SYSCALLS))) tracing_init_oom_panic("traced_syscalls"); if (!(traced_syscalls_str = kmalloc(TRACED_SYSCALLS_STR_LEN))) tracing_init_oom_panic("traced_syscalls_str"); ringbuf_init(&tracing_rb, TRACE_BUF_SIZE / sizeof(struct trace_event), sizeof(struct trace_event), tracing_buf); kmutex_init(&tracing_lock, 0); kcond_init(&tracing_cond); foreach_symbol(elf_symbol_cb, NULL); tracing_populate_syscalls_info(); tracing_allocate_slots_for_params(); set_traced_syscalls("*"); } static struct module dp_module = { .name = "tracing", .priority = MOD_tracing_prio, .init = &init_tracing, }; REGISTER_MODULE(&dp_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <3rd_party/crc32.h> int read_wrapper(int fd, char *buf, int len) { int rc, tot = 0; while (tot < len) { rc = read(fd, buf + tot, len - tot); if (!rc) break; if (rc < 0) return rc; tot += rc; } return tot; } int main(int argc, char **argv) { int fd, bs, rc, off = 0; char *buf; if (argc < 3) { fprintf(stderr, "Usage: %s <file> <bufsize>\n", argv[0]); return 1; } bs = atoi(argv[2]); if (bs <= 0) { fprintf(stderr, "Invalid bufsize\n"); return 1; } fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return 1; } buf = malloc(bs); if (!buf) { fprintf(stderr, "out-of-memory\n"); return 1; } do { if ((rc = read_wrapper(fd, buf, bs)) < 0) { perror("read"); break; } uint32_t checksum = crc32(0, buf, rc); printf("[%08x] %08x\n", off, checksum); off += rc; } while (rc == bs); free(buf); close(fd); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <system_headers/multiboot.h> #define MAX_MEM_REGIONS 512 #define MEM_REG_EXTRA_RAMDISK (1 << 0) #define MEM_REG_EXTRA_KERNEL (1 << 1) #define MEM_REG_EXTRA_LOWMEM (1 << 2) #define MEM_REG_EXTRA_FRAMEBUFFER (1 << 3) #define MEM_REG_EXTRA_DMA (1 << 4) struct mem_region { u64 addr; u64 len; u32 type; /* multiboot_memory_map_t's type */ u32 extra; /* bit mask */ }; void system_mmap_add_ramdisk(ulong start_paddr, ulong end_paddr); int system_mmap_get_ramdisk(int ramdisk_index, void **va, size_t *size); void system_mmap_set(multiboot_info_t *mbi); int system_mmap_get_region_of(ulong paddr); bool linear_map_mem_region(struct mem_region *r, ulong *vbegin, ulong *vend); bool system_mmap_check_for_extra_ramdisk_region(void *rd); const char *mem_region_extra_to_str(u32 e); void dump_memory_map(void); static ALWAYS_INLINE int get_mem_regions_count(void) { extern int mem_regions_count; return mem_regions_count; } static ALWAYS_INLINE void get_mem_region(int n, struct mem_region *r) { extern struct mem_region mem_regions[MAX_MEM_REGIONS]; *r = mem_regions[n]; } static ALWAYS_INLINE ulong get_phys_mem_mb(void) { extern u32 __mem_upper_kb; return __mem_upper_kb >> 10; } static ALWAYS_INLINE u64 get_phys_mem_size(void) { extern u32 __mem_upper_kb; return ((u64)__mem_upper_kb) << 10; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <cstdio> #include <random> #include <vector> #include <algorithm> #include <gtest/gtest.h> using namespace std; using namespace testing; extern "C" { #include <tilck/kernel/sort.h> } static long less_than_cmp_int(const void *a, const void *b) { const long a_val = *(const long *)a; const long b_val = *(const long *)b; if (a_val < b_val) return -1; if (a_val == b_val) return 0; return 1; } static bool my_is_sorted(ulong *arr, int len, cmpfun_ptr cmp) { if (len <= 1) return true; for (int i = 0; i < len - 1; i++) if (cmp(&arr[i], &arr[i+1]) > 0) return false; return true; } void random_fill_vec(default_random_engine &eng, lognormal_distribution<> &dist, vector<long> &v, u32 elems) { v.clear(); v.resize(elems); for (u32 i = 0; i < elems; i++) { v[i] = (long) round(dist(eng)); } } TEST(insertion_sort_ptr, basic_test) { long vec[] = { 3, 4, 1, 0, -3, 10, 2 }; insertion_sort_ptr((ulong *)&vec, ARRAY_SIZE(vec), less_than_cmp_int); ASSERT_TRUE(my_is_sorted((ulong *)vec, ARRAY_SIZE(vec), less_than_cmp_int)); } TEST(insertion_sort_ptr, random) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); lognormal_distribution<> dist(5.0, 3); cout << "[ INFO ] random seed: " << seed << endl; vector<long> vec; random_fill_vec(e, dist, vec, 1000); insertion_sort_ptr((ulong *)&vec[0], vec.size(), less_than_cmp_int); ASSERT_TRUE(my_is_sorted((ulong *)&vec[0], vec.size(), less_than_cmp_int)); } TEST(insertion_sort_generic, basic_test) { long vec[] = { 3, 4, 1, 0, -3, 10, 2 }; insertion_sort_generic((ulong *)&vec, sizeof(long), ARRAY_SIZE(vec), less_than_cmp_int); ASSERT_TRUE(my_is_sorted((ulong *)vec, ARRAY_SIZE(vec), less_than_cmp_int)); } TEST(insertion_sort_generic, random) { random_device rdev; const auto seed = rdev(); default_random_engine e(seed); lognormal_distribution<> dist(5.0, 3); cout << "[ INFO ] random seed: " << seed << endl; vector<long> vec; random_fill_vec(e, dist, vec, 1000); insertion_sort_generic((ulong *)&vec[0], sizeof(vec[0]), vec.size(), less_than_cmp_int); ASSERT_TRUE(my_is_sorted((ulong *)&vec[0], vec.size(), less_than_cmp_int)); } bool array_reverse_ptr_check(const vector<ulong> &vec) { vector<ulong> copy = vec; array_reverse_ptr((void *)&vec[0], (u32)vec.size()); reverse(copy.begin(), copy.end()); return copy == vec; } TEST(reverse_array, basic) { EXPECT_TRUE(array_reverse_ptr_check({ })); EXPECT_TRUE(array_reverse_ptr_check({ 1 })); EXPECT_TRUE(array_reverse_ptr_check({ 1, 2 })); EXPECT_TRUE(array_reverse_ptr_check({ 1, 2, 3 })); EXPECT_TRUE(array_reverse_ptr_check({ 1, 2, 3, 4 })); } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) # Remove -rdynamic set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS) if (${ARCH} STREQUAL "i386") set_cross_compiler() else() # If we're compiling the legacy bootloader, ${ARCH} is either i386 or x86_64 # but that doesn't really matter, because the bootloader itself will be # always 32-bit. Now, since ${ARCH} is x86_64, we cannot really use our # pre-built GCC toolchain because it has been configured to work only # for its target architecture (x86_64 in this case) and fails in a cumbersome # ways if we try to use it with -m32 etc. Better just stick with the system # GCC. Fortunately, for the bootloader we won't need anything libmusl etc. # so it _should_ always work. set(CMAKE_C_FLAGS "-m32 -march=i686") set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${KERNEL_CXX_FLAGS}") set(CMAKE_ASM_FLAGS "${CMAKE_C_FLAGS}") set(TOOL_GCOV "${GCOV}") endif() # Common directories, both for early_boot and for elf_stage3_unstripped include_directories( ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/include/system_headers ) link_directories( ${CMAKE_SOURCE_DIR}/boot/legacy ) set(EARLY_STAGES_SOURCES "boot.S" "boot_enable_a20.S") add_executable( early_boot EXCLUDE_FROM_ALL ${EARLY_STAGES_SOURCES} ) set_target_properties( early_boot PROPERTIES COMPILE_FLAGS "-ffreestanding -nostdinc" LINK_FLAGS "-nostdlib -Wl,--script=${EARLY_BOOT_SCRIPT}" LINK_DEPENDS ${EARLY_BOOT_SCRIPT} ) set(dd_opts1 "status=none" "conv=notrunc" "oflag=append") add_custom_command( OUTPUT elf_stage3 COMMAND ${CMAKE_STRIP} --strip-debug stage3/elf_stage3_unstripped -o elf_stage3 COMMAND elfhack32 elf_stage3 --verify-flat-elf COMMAND elfhack32 elf_stage3 --check-entry-point ${BL_BASE_ADDR} DEPENDS elf_stage3_unstripped elfhack32 ${CMAKE_BINARY_DIR}/scripts/build_apps/elfhack32 ) add_custom_command( OUTPUT ${BOOTLOADER_BIN_FILE} COMMAND cp early_boot ${BOOTLOADER_BIN_FILE} COMMAND dd ${dd_opts1} if=elf_stage3 of=${BOOTLOADER_BIN_FILE} DEPENDS early_boot elf_stage3 COMMENT "Linking the legacy BIOS bootloader" ) add_custom_target( bootloader DEPENDS ${BOOTLOADER_BIN_FILE} ) add_subdirectory(stage3) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/paging.h> #include <tilck/kernel/hal.h> extern const ulong init_st_begin; extern const ulong init_st_end; void dump_stacktrace(void *ebp, pdir_t *pdir); void dump_regs(regs_t *r); int debug_qemu_turn_off_machine(void); void kmain_early_checks(void); void init_extra_debug_features(void); int set_sched_alive_thread_enabled(bool enabled); void register_tilck_cmd(int cmd_n, void *func); void *get_syscall_func_ptr(u32 n); int get_syscall_num(void *func); /* * Debug-only checks useful to verify that kernel_yield() + context_switch() * do NOT change the current ESP. Sure, at some point when we decide that * those function will never be touched again we could remove this code, but * until then, in a fast-growing and changing code base like the current one, * it makes sense to constantly check that there are *no* subtle bugs in the * probably most critical code. * * One of the places where the following two debug checks are used is inside * wth_run()'s code: it is the perfect place for such checks, because * it really often yields and gets the control back. * * The KERNEL_STACK_ISOLATION sure works as well, but it catches bugs only * when the stack pointer is completely out of the allocated stack area for the * current task. With following macros allows instead, any kind of such problems * will be caught much earlier. */ #if !defined(NDEBUG) && !defined(RELEASE) #define DEBUG_SAVE_ESP() \ ulong curr_esp; \ ulong saved_esp = get_stack_ptr(); #define DEBUG_CHECK_ESP() \ curr_esp = get_stack_ptr(); \ if (curr_esp != saved_esp) \ panic("ESP changed. Saved: %p, Curr: %p", saved_esp, curr_esp); #else #define DEBUG_SAVE_ESP() #define DEBUG_CHECK_ESP() #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once /* ------ Value-based config variables -------- */ #define FBCON_BIGFONT_THR @FBCON_BIGFONT_THR@ /* --------- Boolean config variables --------- */ #cmakedefine01 MOD_fb #cmakedefine01 FB_CONSOLE_BANNER #cmakedefine01 FB_CONSOLE_CURSOR_BLINK #cmakedefine01 FB_CONSOLE_USE_ALT_FONTS #cmakedefine01 FB_CONSOLE_FAILSAFE_OPT /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are some pseudo-constants not designed to be easily changed * because of the code makes assumptions about them. Because of that, those * constants are hard-coded and not available as CMake variables. With time, * some of those constants get "promoted" and moved in CMake, others remain * here. See the comments and think about the potential implications before * promoting a hard-coded constant to a configurable CMake variable. */ #define FBCON_OPT_FUNCS_MIN_FREE_HEAP (16 * MB) #define FAILSAFE_FB_VADDR (KERNEL_BASE_VA + (1024 - 64) * MB) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/arch/generic_x86/x86_utils.h> #include <tilck/common/color_defs.h> #define VIDEO_ADDR ((u16*)(0xB8000)) #define TERM_COLS 80 #define TERM_ROWS 25 static u16 curr_row; static u16 curr_col; static u16 curr_color; void bt_setcolor(u8 color) { curr_color = color; } u16 bt_get_curr_row(void) { return curr_row; } u16 bt_get_curr_col(void) { return curr_col; } void bt_movecur(int row, int col) { row = CLAMP(row, 0, TERM_ROWS - 1); col = CLAMP(col, 0, TERM_COLS - 1); u16 position = row * TERM_COLS + col; // cursor LOW port to vga INDEX register outb(0x3D4, 0x0F); outb(0x3D5, (u8)(position & 0xFF)); // cursor HIGH port to vga INDEX register outb(0x3D4, 0x0E); outb(0x3D5, (u8)((position >> 8) & 0xFF)); curr_row = (u16)row; curr_col = (u16)col; } static void bt_incr_row(void) { if (curr_row < TERM_ROWS - 1) { ++curr_row; return; } // We have to scroll... memmove(VIDEO_ADDR, VIDEO_ADDR + TERM_COLS, TERM_COLS * (TERM_ROWS - 1) * 2); u16 *lastRow = VIDEO_ADDR + TERM_COLS * (TERM_ROWS - 1); memset16(lastRow, make_vgaentry(' ', curr_color), TERM_COLS); } void bt_write_char(char c) { if (c == '\n') { curr_col = 0; /* treat \n as \r\n */ bt_incr_row(); bt_movecur(curr_row, curr_col); return; } if (c == '\r') { bt_movecur(curr_row, 0); return; } if (c == '\b') { if (curr_col > 0) bt_movecur(curr_row, curr_col - 1); return; } if (c == '\t') return; /* ignore tabs */ volatile u16 *video = (volatile u16 *)VIDEO_ADDR; const size_t offset = curr_row * TERM_COLS + curr_col; video[offset] = make_vgaentry(c, curr_color); ++curr_col; if (curr_col == TERM_COLS) { curr_col = 0; bt_incr_row(); } bt_movecur(curr_row, curr_col); } void init_bt(void) { /* * Set the current row and the current col to 0, in case the BSS variables * were not zero-ed because of some bug. We still need to be able to show * something on the screen. */ curr_row = curr_col = 0; bt_movecur(0, 0); bt_setcolor(make_color(DEFAULT_FG_COLOR, DEFAULT_BG_COLOR)); memset16(VIDEO_ADDR, make_vgaentry(' ', curr_color), TERM_COLS * TERM_ROWS); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/debug_utils.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_mm") void * AcpiOsMapMemory( ACPI_PHYSICAL_ADDRESS Where, ACPI_SIZE RawLength) { ACPI_PHYSICAL_ADDRESS paddr = Where & PAGE_MASK; ACPI_SIZE Length = pow2_round_up_at(Where + RawLength - paddr, PAGE_SIZE); size_t cnt, pg_count; void *va; ACPI_FUNCTION_TRACE(__FUNC__); if (paddr + Length <= LINEAR_MAPPING_SIZE) return_PTR(KERNEL_PA_TO_VA(Where)); // printk("ACPI: mmap 0x%08llx (len: %zu -> %zuK)\n", // paddr, RawLength, Length/KB); if (!(va = hi_vmem_reserve(Length))) { ACPI_ERROR((AE_INFO, "hi_vmem_reserve() failed\n")); return_PTR(NULL); } pg_count = Length >> PAGE_SHIFT; cnt = map_kernel_pages(va, paddr, pg_count, PAGING_FL_RW); if (cnt < pg_count) { unmap_pages_permissive(get_kernel_pdir(), va, cnt, false); hi_vmem_release(va, Length); ACPI_ERROR((AE_INFO, "cnt (%zu) < pg_count (%zu)\n", cnt, pg_count)); return_PTR(NULL); } return_PTR(TO_PTR((ulong)va + (Where & OFFSET_IN_PAGE_MASK))); } void AcpiOsUnmapMemory( void *LogicalAddr, ACPI_SIZE RawSz) { ulong vaddr = (ulong)LogicalAddr; ulong aligned_vaddr = vaddr & PAGE_MASK; ACPI_SIZE Size = pow2_round_up_at(vaddr + RawSz - aligned_vaddr, PAGE_SIZE); size_t pg_count; ACPI_FUNCTION_TRACE(__FUNC__); if (aligned_vaddr + Size <= LINEAR_MAPPING_END) return_VOID; //printk("ACPI: UNmap %p (len: %zu -> %zuK)\n", // LogicalAddr, RawSz, Size/KB); pg_count = Size >> PAGE_SHIFT; unmap_kernel_pages(TO_PTR(aligned_vaddr), pg_count, false); hi_vmem_release(TO_PTR(aligned_vaddr), Size); return_VOID; } ACPI_STATUS AcpiOsGetPhysicalAddress( void *LogicalAddress, ACPI_PHYSICAL_ADDRESS *PhysicalAddress) { ulong paddr; ACPI_FUNCTION_TRACE(__FUNC__); if (!LogicalAddress || !PhysicalAddress) return_ACPI_STATUS(AE_BAD_PARAMETER); if (get_mapping2(get_kernel_pdir(), LogicalAddress, &paddr) < 0) return_ACPI_STATUS(AE_ERROR); *PhysicalAddress = paddr; return_ACPI_STATUS(AE_OK); } BOOLEAN AcpiOsReadable( void *Pointer, ACPI_SIZE Length) { ulong va = (ulong)Pointer; ulong va_end = va + Length; ACPI_FUNCTION_TRACE(__FUNC__); if (va < KERNEL_BASE_VA) return_UINT8(false); if (va_end <= LINEAR_MAPPING_END) return_UINT8(true); while (va < va_end) { if (!is_mapped(get_kernel_pdir(), TO_PTR(va))) return_UINT8(false); va += PAGE_SIZE; } return_UINT8(true); } BOOLEAN AcpiOsWritable( void *Pointer, ACPI_SIZE Length) { ulong va = (ulong)Pointer; ulong va_end = va + Length; struct mem_region m; int reg_count = get_mem_regions_count(); ACPI_FUNCTION_TRACE(__FUNC__); if (va < KERNEL_BASE_VA) return_UINT8(false); for (int i = 0; i < reg_count; i++) { get_mem_region(i, &m); if (m.type != MULTIBOOT_MEMORY_AVAILABLE) continue; if (~m.extra & MEM_REG_EXTRA_KERNEL) continue; if (~m.extra & MEM_REG_EXTRA_RAMDISK) continue; /* OK, now `m` points to a kernel/ramdisk region */ if (IN_RANGE(va, m.addr, m.addr + m.len)) { /* * The address falls inside a read/write protected region. * We cannot allow ACPICA to believe it's writable. */ return_UINT8(false); } } if (va_end <= LINEAR_MAPPING_END) return_UINT8(true); while (va < va_end) { if (!is_rw_mapped(get_kernel_pdir(), TO_PTR(va))) return_UINT8(false); va += PAGE_SIZE; } return_UINT8(true); } ACPI_STATUS AcpiOsReadMemory( ACPI_PHYSICAL_ADDRESS Address, UINT64 *Value, UINT32 Width) { void *va; ACPI_FUNCTION_TRACE(__FUNC__); if ((Address + (Width >> 3)) > LINEAR_MAPPING_SIZE) { /* * In order to support this, we'll need to implement some sort of * memory mapping cache. Mapping and un-mapping a page for a single * read/write is definitively unaccetable. */ NOT_IMPLEMENTED(); } else { va = KERNEL_PA_TO_VA(Address); } switch (Width) { case 8: *Value = *(volatile u8 *)va; break; case 16: *Value = *(volatile u16 *)va; break; case 32: *Value = *(volatile u32 *)va; break; case 64: *Value = *(volatile u64 *)va; break; default: return_ACPI_STATUS(AE_BAD_PARAMETER); } return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsWriteMemory( ACPI_PHYSICAL_ADDRESS Address, UINT64 Value, UINT32 Width) { void *va; ACPI_FUNCTION_TRACE(__FUNC__); if ((Address + (Width >> 3)) > LINEAR_MAPPING_SIZE) { /* See the comment in AcpiOsReadMemory() */ NOT_IMPLEMENTED(); } else { va = KERNEL_PA_TO_VA(Address); } switch (Width) { case 8: *(volatile u8 *)va = Value; break; case 16: *(volatile u16 *)va = Value; break; case 32: *(volatile u32 *)va = Value; break; case 64: *(volatile u64 *)va = Value; break; default: return_ACPI_STATUS(AE_BAD_PARAMETER); } return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsReadPort( ACPI_IO_ADDRESS Address, UINT32 *Value, UINT32 Width) { u16 ioport = (u16)Address; ACPI_FUNCTION_TRACE(__FUNC__); if (Address > 0xffff) return_ACPI_STATUS(AE_NOT_EXIST); switch (Width) { case 8: *Value = (u32)inb(ioport); break; case 16: *Value = (u32)inw(ioport); break; case 32: *Value = (u32)inl(ioport); break; default: return_ACPI_STATUS(AE_BAD_PARAMETER); } return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsWritePort( ACPI_IO_ADDRESS Address, UINT32 Value, UINT32 Width) { u16 ioport = (u16)Address; ACPI_FUNCTION_TRACE(__FUNC__); if (Address > 0xffff) return_ACPI_STATUS(AE_NOT_EXIST); switch (Width) { case 8: outb(ioport, (u8)Value); break; case 16: outw(ioport, (u16)Value); break; case 32: outl(ioport, (u32)Value); break; default: return_ACPI_STATUS(AE_BAD_PARAMETER); } return_ACPI_STATUS(AE_OK); } <file_sep># SPDX-License-Identifier: BSD-2-Clause QEMU_SPECIAL_KEYS = { " " : "spc", "!" : "shift-1", '"' : "shift-apostrophe", "#" : "shift-3", "$" : "shift-4", "%" : "shift-5", "&" : "shift-7", "'" : "apostrophe", "(" : "shift-9", ")" : "shift-0", "*" : "shift-8", "+" : "shift-equal", "," : "comma", "-" : "minus", "." : "dot", "/" : "slash", ":" : "shift-semicolon", ";" : "semicolon", "<" : "shift-comma", "=" : "equal", ">" : "shift-dot", "?" : "shift-slash", "@" : "shift-2", "[" : "bracket_left", "\\" : "backslash", "]" : "bracket_right", "^" : "shift-6", "_" : "shift-minus", "`" : "grave_accent", "{" : "shift-bracket_left", "|" : "shift-backslash", "}" : "shift-bracket_right", "~" : "shift-grave_accent" } KEYS_MAP = { chr(x): chr(x) if x in range(ord('a'), ord('z')+1) or x in range(ord('0'),ord('9')+1) else 'shift-' + chr(x).lower() if x in range(ord('A'), ord('Z')+1) else QEMU_SPECIAL_KEYS[chr(x)] if chr(x) in QEMU_SPECIAL_KEYS else None for x in range(27, 128) } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/time.h> #include <dirent.h> #include "devshell.h" #include "sysenter.h" #include "test_common.h" static char pagebuf[4096]; void create_test_file1(void) { int fd, rc; fd = open("/tmp/test1", O_CREAT | O_WRONLY, 0644); DEVSHELL_CMD_ASSERT(fd > 0); printf("writing 'a'...\n"); memset(pagebuf, 'a', 3 * KB); rc = write(fd, pagebuf, 3 * KB); DEVSHELL_CMD_ASSERT(rc == 3 * KB); printf("writing 'b'...\n"); memset(pagebuf, 'b', 3 * KB); rc = write(fd, pagebuf, 3 * KB); DEVSHELL_CMD_ASSERT(rc == 3 * KB); printf("writing 'c'...\n"); memset(pagebuf, 'c', 3 * KB); rc = write(fd, pagebuf, 3 * KB); DEVSHELL_CMD_ASSERT(rc == 3 * KB); close(fd); } void write_on_test_file1(void) { int fd, rc; off_t off; char buf[32] = "hello world"; fd = open("/tmp/test1", O_WRONLY); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, buf, 32); DEVSHELL_CMD_ASSERT(rc == 32); off = lseek(fd, 4096, SEEK_SET); DEVSHELL_CMD_ASSERT(off == 4096); rc = write(fd, "XXX", 3); DEVSHELL_CMD_ASSERT(rc == 3); close(fd); } static void read_past_end(void) { int rc, fd; off_t off; char buf[32] = { [0 ... 30] = 'a', [31] = 0 }; fd = open("/tmp/test1", O_RDONLY); DEVSHELL_CMD_ASSERT(fd > 0); off = lseek(fd, 64 * KB, SEEK_SET); printf("off: %d\n", (int)off); rc = read(fd, buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc == 0); printf("buf: '%s'\n", buf); close(fd); } /* * Generic create file/write/read/seek test */ int cmd_fs1(int argc, char **argv) { create_test_file1(); write_on_test_file1(); read_past_end(); // TODO: add a function here to check how EXACTLY the file should look like unlink("/tmp/test1"); return 0; } /* * Test creat() [indirectly O_TRUNC] and open(O_CREAT + O_EXCL). */ int cmd_fs2(int argc, char **argv) { int fd, rc; char buf[32]; struct stat statbuf; fd = creat("/tmp/test2", 0644); DEVSHELL_CMD_ASSERT(fd > 0); rc = write(fd, "test\n", 5); DEVSHELL_CMD_ASSERT(rc == 5); close(fd); /* * Being creat(path, mode) equivalent to: * open(path, O_CREAT|O_WRONLY|O_TRUNC, mode) * we expect creat() to succeed even if the file already exists. */ rc = creat("/tmp/test2", 0644); DEVSHELL_CMD_ASSERT(rc > 0); close(rc); /* * Now, since creat() implies O_TRUNC, we have to check that the file has * been actually truncated. */ fd = open("/tmp/test2", O_RDONLY); DEVSHELL_CMD_ASSERT(fd > 0); rc = read(fd, buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc == 0); close(fd); rc = stat("/tmp/test2", &statbuf); DEVSHELL_CMD_ASSERT(rc == 0); DEVSHELL_CMD_ASSERT(statbuf.st_size == 0); DEVSHELL_CMD_ASSERT(statbuf.st_blocks == 0); /* Instead, this open() call using O_EXCL is expected to FAIL */ rc = open("/tmp/test2", O_CREAT | O_EXCL | O_WRONLY, 0644); DEVSHELL_CMD_ASSERT(rc < 0); DEVSHELL_CMD_ASSERT(errno == EEXIST); unlink("/tmp/test2"); return 0; } /* * Test a corner case for RAMFS: remove the next dentry while reading the * contents of a directory with getdents64(). */ int cmd_fs3(int argc, char **argv) { struct linux_dirent64 *de; char dentsbuf[192]; int fd, rc, off = 0; DIR *d; if (!running_on_tilck()) { not_on_tilck_message(); return 0; } rc = mkdir("/tmp/r", 0755); DEVSHELL_CMD_ASSERT(rc == 0); for (int i = 0; i < 20; i++) create_test_file("/tmp/r", i); d = opendir("/tmp/r"); DEVSHELL_CMD_ASSERT(d != NULL); fd = dirfd(d); rc = getdents64(fd, (void *)dentsbuf, sizeof(dentsbuf)); DEVSHELL_CMD_ASSERT(rc > 0); printf("getdents64: %d\n", rc); for (de = (void *) dentsbuf, off = 0; off < rc; off += de->d_reclen) { de = (void *)(dentsbuf + off); // printf("entry: '%s'\n", de->d_name); } int last_n = atoi(de->d_name + 5); /* skip "test_" */ printf("last entry: '%s' (%d)\n", de->d_name, last_n); /* * The next elem, at least on Tilck's ramfs, will be "test_${last_n+1}" * because the getdents64 keep the creation order. Remove that elem. */ printf("Remove the next entry: test_%03d\n", last_n + 1); remove_test_file_expecting_success("/tmp/r", last_n + 1); /* * Now, if this special case has been handled correctly, we should continue * from last_n + 2. */ rc = getdents64(fd, (void *)dentsbuf, sizeof(dentsbuf)); DEVSHELL_CMD_ASSERT(rc > 0); printf("getdents64: %d\n", rc); if (getenv("TILCK")) { /* * Tilck's RAMFS keep the creation order: that's why we can reason about * which dentry will the next one. In general, that's not possible. */ de = (void *) dentsbuf; printf("Next entry: '%s'\n", de->d_name); DEVSHELL_CMD_ASSERT(atoi(de->d_name + 5) == last_n + 2); printf("The next dentry was last_n + 2 as expected\n"); } rc = closedir(d); DEVSHELL_CMD_ASSERT(rc == 0); for (int i = 0; i < 20; i++) { if (i != last_n+1) { remove_test_file_expecting_success("/tmp/r", i); } else { rc = remove_test_file("/tmp/r", i); DEVSHELL_CMD_ASSERT(rc < 0); DEVSHELL_CMD_ASSERT(errno == ENOENT); } } rc = rmdir("/tmp/r"); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } static void fs4_aux_read_dents(DIR *d, /* dir handle */ long *dposs, /* array of positions */ int s, /* start index */ int n, /* if >= 0, #elems, otherwise, all of them */ int j, /* if >= 0, index of element to check name */ const char *v, /* if j >= 0, check name[j] == v */ bool cdots) /* check that '.' and '..' exist */ { struct dirent *de; for (int i = s; n >= 0 ? (i < s + n) : 1; i++) { if (telldir(d) != dposs[i]) { printf("telldir != dposs for i = %d\n", i); printf("telldir: %ld\n", telldir(d)); printf("dposs: %ld\n", dposs[i]); exit(1); } de = readdir(d); if (n >= 0) DEVSHELL_CMD_ASSERT(de != NULL); else if (!de) break; // printf("dposs[%3d]: %11ld, entry: %s\n", i, dposs[i], de->d_name); if (cdots) { if (i == 0) DEVSHELL_CMD_ASSERT(strcmp(de->d_name, ".") == 0); if (i == 1) DEVSHELL_CMD_ASSERT(strcmp(de->d_name, "..") == 0); } if (j >= 0 && i == j) DEVSHELL_CMD_ASSERT(strcmp(de->d_name, v) == 0); } } static void generic_fs_dir_seek_test(DIR *d, const int n_files, const int seek_n, const int seek_n2, bool cdots) { char saved_entry_name[256]; long dposs[n_files + 3]; struct dirent *de; printf("Reading dir entries...\n"); for (int i = 0; ; i++) { dposs[i] = telldir(d); de = readdir(d); if (!de) { printf("Done (%d dirents)\n", i); if (cdots) DEVSHELL_CMD_ASSERT(i >= n_files+2); else DEVSHELL_CMD_ASSERT(i >= n_files); break; } if (i == seek_n) strcpy(saved_entry_name, de->d_name); // printf("dposs[%3d]: %11ld, entry: %s\n", i, dposs[i], de->d_name); } printf("seek to the position of entry #%d: %ld\n", seek_n, dposs[seek_n]); seekdir(d, dposs[seek_n]); fs4_aux_read_dents(d, dposs, seek_n, -1, seek_n, saved_entry_name, cdots); printf("seek to the position of entry #%d: %ld\n", seek_n2, dposs[seek_n2]); seekdir(d, dposs[seek_n2]); fs4_aux_read_dents(d, dposs, seek_n2, 4, -1, NULL, cdots); seekdir(d, 0); printf("seek to the position of entry #0: 0\n"); DEVSHELL_CMD_ASSERT(telldir(d) == 0); fs4_aux_read_dents(d, dposs, 0, 4, -1, NULL, cdots); printf("Do rewinddir()...\n"); rewinddir(d); DEVSHELL_CMD_ASSERT(telldir(d) == 0); fs4_aux_read_dents(d, dposs, 0, 4, -1, NULL, cdots); printf("Everything looks good\n"); } /* * Test telldir(), seekdir() and rewinddir() on RAMFS. */ int cmd_fs4(int argc, char **argv) { const int n_files = 100; int rc; DIR *d; if (!running_on_tilck()) { not_on_tilck_message(); return 0; } /* preparing the test environment */ rc = mkdir("/tmp/r", 0755); DEVSHELL_CMD_ASSERT(rc == 0); for (int i = 0; i < n_files; i++) create_test_file("/tmp/r", i); d = opendir("/tmp/r"); DEVSHELL_CMD_ASSERT(d != NULL); /* ---------------- actual test's code --------------------- */ generic_fs_dir_seek_test(d, n_files, 90, 4, true); /* ---------------- clean up the test environment ----------- */ rc = closedir(d); DEVSHELL_CMD_ASSERT(rc == 0); for (int i = 0; i < n_files; i++) remove_test_file_expecting_success("/tmp/r", i); rc = rmdir("/tmp/r"); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } /* * Test telldir(), seekdir() and rewinddir() on FAT32 */ int cmd_fs5(int argc, char **argv) { const int n_files = 100; DIR *d; int rc; if (!running_on_tilck()) { not_on_tilck_message(); return 0; } if (!FAT_TEST_DIR) { printf(PFX "[SKIP] because FAT_TEST_DIR == 0\n"); return 0; } d = opendir("/tdir"); DEVSHELL_CMD_ASSERT(d != NULL); generic_fs_dir_seek_test(d, n_files, 90, 4, true); rc = closedir(d); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } /* * Test telldir(), seekdir() and rewinddir() on DEVFS */ int cmd_fs6(int argc, char **argv) { DIR *d; int rc; if (!running_on_tilck()) { not_on_tilck_message(); return 0; } d = opendir("/dev"); DEVSHELL_CMD_ASSERT(d != NULL); generic_fs_dir_seek_test(d, 6, 5, 2, false); rc = closedir(d); DEVSHELL_CMD_ASSERT(rc == 0); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/syscalls.h> #define INVALID_SYSCALL ((u32) -1) #define NO_SLOT -1 #define TRACED_SYSCALLS_STR_LEN 128u enum trace_event_type { te_invalid, te_sys_enter, te_sys_exit, te_printk, te_signal_delivered, te_killed, }; struct syscall_event_data { u32 sys; long retval; ulong args[6]; union { struct { char d0[64]; char d1[64]; char d2[32]; char d3[16]; } fmt0; struct { char d0[128]; char d1[32]; char d2[16]; } fmt1; }; }; struct printk_event_data { int level; /* Verbosity level. Must be > 1 */ char buf[192]; /* Actual log entry */ }; struct signal_event_data { int signum; }; struct trace_event { enum trace_event_type type; int tid; u64 sys_time; union { struct syscall_event_data sys_ev; struct printk_event_data p_ev; struct signal_event_data sig_ev; }; }; STATIC_ASSERT(sizeof(struct trace_event) <= 256); enum sys_param_ui_type { ui_type_other, ui_type_integer, ui_type_string, }; struct sys_param_type { const char *name; u32 slot_size; enum sys_param_ui_type ui_type; /* Returns false if buf_size is too small */ bool (*save)(void *ptr, long size, char *buf, size_t buf_size); /* Returns false if dest_buf_size is too small */ bool (*dump)(ulong orig, char *b, long bs, long hlp, char *dst, size_t d_bs); /* Returns false if dest_buf_size is too small */ bool (*dump_from_val)(ulong val, long hlp, char *dest, size_t dest_buf_size); }; enum sys_param_kind { sys_param_in, sys_param_out, sys_param_in_out, }; struct sys_param_info { const char *name; const struct sys_param_type *type; /* IN, OUT or IN/OUT */ enum sys_param_kind kind; /* name of another (helper) param, typically a buffer size */ const char *helper_param_name; /* true if the retval of the func represents the real value of this buffer */ bool real_sz_in_ret; /* invisible: if true, the param won't be dumped (see llseek) */ bool invisible; }; enum sys_saved_param_fmt { sys_fmt0 = 0, sys_fmt1 = 1, }; struct syscall_info { /* syscall number */ u32 sys_n; /* number of parameters */ s8 n_params; /* * True if the syscall is expected to block. In other words: * => do we care about the ENTER event? * * exp_block = false DOES NOT mean that the syscall cannot block due to * I/O like sys_rename, sys_link etc. But that that's not interesting 99.9% * of the time. It's interesting instead to observe the ENTER and EXIT events * for syscalls like read(), write(), select(), poll(), waitpid() etc. */ bool exp_block; /* return type of the syscall */ const struct sys_param_type *ret_type; /* info about its parameters */ struct sys_param_info params[6]; }; void init_tracing(void); bool read_trace_event(struct trace_event *e, u32 timeout_ticks); bool read_trace_event_noblock(struct trace_event *e); void trace_syscall_enter_int(u32 sys, ulong a1, ulong a2, ulong a3, ulong a4, ulong a5, ulong a6); void trace_syscall_exit_int(u32 sys, long retval, ulong a1, ulong a2, ulong a3, ulong a4, ulong a5, ulong a6); void trace_printk_int(int level, const char *fmt, ...); void trace_signal_delivered_int(int target_tid, int signum); void trace_task_killed_int(int signum); const char * tracing_get_syscall_name(u32 n); const struct syscall_info * tracing_get_syscall_info(u32 n); bool tracing_get_slot(struct trace_event *e, const struct syscall_info *si, int p_idx, char **buf, size_t *s); int tracing_get_param_idx(const struct syscall_info *si, const char *name); const char * get_errno_name(int errno); const char * get_signal_name(int signum); int get_traced_syscalls_count(void); int get_traced_tasks_count(void); void get_traced_syscalls_str(char *buf, size_t len); int set_traced_syscalls(const char *str); int tracing_get_in_buffer_events_count(void); extern const struct syscall_info *tracing_metadata; extern const struct sys_param_type ptype_int; extern const struct sys_param_type ptype_voidp; extern const struct sys_param_type ptype_oct; extern const struct sys_param_type ptype_errno_or_val; extern const struct sys_param_type ptype_errno_or_ptr; extern const struct sys_param_type ptype_buffer; extern const struct sys_param_type ptype_big_buf; extern const struct sys_param_type ptype_path; extern const struct sys_param_type ptype_open_flags; extern const struct sys_param_type ptype_iov_in; extern const struct sys_param_type ptype_iov_out; extern const struct sys_param_type ptype_int32_pair; extern const struct sys_param_type ptype_doff64; extern const struct sys_param_type ptype_whence; extern const struct sys_param_type ptype_u64_ptr; extern const struct sys_param_type ptype_signum; static ALWAYS_INLINE bool tracing_is_enabled_on_sys(u32 sys_n) { extern bool *traced_syscalls; if (sys_n >= MAX_SYSCALLS) return false; return traced_syscalls[sys_n]; } static ALWAYS_INLINE bool exp_block(const struct syscall_info *si) { extern bool __force_exp_block; return __force_exp_block || si->exp_block; } static ALWAYS_INLINE void tracing_set_enabled(bool val) { extern bool __tracing_on; __tracing_on = val; } static ALWAYS_INLINE bool tracing_is_enabled(void) { extern bool __tracing_on; return __tracing_on; } static ALWAYS_INLINE void tracing_set_force_exp_block(bool enabled) { extern bool __force_exp_block; __force_exp_block = enabled; } static ALWAYS_INLINE bool tracing_is_force_exp_block_enabled(void) { extern bool __force_exp_block; return __force_exp_block; } static ALWAYS_INLINE bool tracing_are_dump_big_bufs_on(void) { extern bool __tracing_dump_big_bufs; return __tracing_dump_big_bufs; } static ALWAYS_INLINE void tracing_set_dump_big_bufs_opt(bool enabled) { extern bool __tracing_dump_big_bufs; __tracing_dump_big_bufs = enabled; } static ALWAYS_INLINE int tracing_get_printk_lvl(void) { extern int __tracing_printk_lvl; return __tracing_printk_lvl; } static ALWAYS_INLINE void tracing_set_printk_lvl(int lvl) { extern int __tracing_printk_lvl; __tracing_printk_lvl = lvl; } #define trace_sys_enter(sn, ...) \ if (MOD_tracing && UNLIKELY(tracing_is_enabled())) { \ if (UNLIKELY(get_curr_task()->traced)) \ if (UNLIKELY(tracing_is_enabled_on_sys(sn))) \ trace_syscall_enter_int(sn, __VA_ARGS__); \ } #define trace_sys_exit(sn, ret, ...) \ if (MOD_tracing && UNLIKELY(tracing_is_enabled())) { \ if (UNLIKELY(get_curr_task()->traced)) \ if (UNLIKELY(tracing_is_enabled_on_sys(sn))) \ trace_syscall_exit_int(sn, (long)(ret), __VA_ARGS__); \ } #define trace_printk(lvl, fmt, ...) \ if (MOD_tracing && UNLIKELY(tracing_is_enabled())) { \ trace_printk_int((lvl), fmt, ##__VA_ARGS__); \ } #define trace_signal_delivered(target_tid, signum) \ if (MOD_tracing && UNLIKELY(tracing_is_enabled())) { \ trace_signal_delivered_int(target_tid, signum); \ } #define trace_task_killed(signum) \ if (MOD_tracing && UNLIKELY(tracing_is_enabled())) { \ trace_task_killed_int(signum); \ } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/process_int.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/debug_utils.h> #include "double_fault.h" #include "gdt_int.h" #include "idt_int.h" extern volatile bool __in_double_fault; void double_fault_handler_asm(void); static int double_fault_tss_num; static const struct tss_entry df_tss_data = { .esp0 = ((ulong)kernel_initial_stack + PAGE_SIZE - 4), .ss0 = X86_KERNEL_DATA_SEL, .cr3 = 0 /* updated later */, .eip = (ulong)&double_fault_handler_asm, .eflags = 0x2, .cs = X86_KERNEL_CODE_SEL, .es = X86_KERNEL_DATA_SEL, .ss = X86_KERNEL_DATA_SEL, .ds = X86_KERNEL_DATA_SEL, .fs = X86_KERNEL_DATA_SEL, .gs = X86_KERNEL_DATA_SEL, .esp = ((ulong)kernel_initial_stack + PAGE_SIZE - 4), }; static inline void double_fault_tss_update_cr3(void) { tss_array[TSS_DOUBLE_FAULT].cr3 = read_cr3(); } void register_double_fault_tss_entry(void) { struct gdt_entry e; memcpy(&tss_array[TSS_DOUBLE_FAULT], &df_tss_data, sizeof(struct tss_entry)); double_fault_tss_update_cr3(); gdt_set_entry(&e, (ulong)&tss_array[TSS_DOUBLE_FAULT], sizeof(tss_array[TSS_DOUBLE_FAULT]), GDT_DESC_TYPE_TSS | GDT_ACCESS_PL0, GDT_GRAN_BYTE | GDT_32BIT); double_fault_tss_num = gdt_add_entry(&e); if (double_fault_tss_num < 0) panic("Unable to add a GDT entry for the double fault TSS"); /* Install the task gate for the double fault */ idt_set_entry(FAULT_DOUBLE_FAULT, NULL, /* offset is not used for task gates: must be 0 */ X86_SELECTOR(double_fault_tss_num, TABLE_GDT, 0), IDT_FLAG_PRESENT | IDT_FLAG_TASK_GATE | IDT_FLAG_DPL0); } void double_fault_handler(void) { __in_double_fault = true; panic("[Double fault] Kernel stack: %p", get_curr_task()->kernel_stack); } /* ------------------------------------------------- */ void on_first_pdir_update(void) { double_fault_tss_update_cr3(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/mman.h> #include "devshell.h" static void child_generate_gpf(void *unused) { /* cause a general fault protection */ asmVolatile("hlt"); } static void child_generate_non_cow_page_fault(void *unused) { /* cause non-CoW page fault */ int val = 25; memcpy((int *)0xabc, &val, sizeof(val)); } static void child_generate_sigill(void *unused) { execute_illegal_instruction(); } static void child_generate_sigfpe(void *unused) { volatile int zero_val = 0; volatile int val = 35 / zero_val; printf("FAIL: expected SIGFPE, got val: %d\n", val); exit(1); } static void child_generate_sigabrt(void *unused) { abort(); } static void child_generate_and_ignore_sigint(void *unused) { signal(SIGINT, SIG_IGN); /* ignore SIGINT */ raise(SIGINT); /* expect nothing to happen */ exit(0); } struct generic_child_ctx { int sig; void *handler; int masked_sig1; int masked_sig2; void (*main_action_cb)(struct generic_child_ctx *); void (*after_unmask_cb)(void); }; static void gc_action_pause(struct generic_child_ctx *ctx) { pause(); } static void gc_action_self_kill(struct generic_child_ctx *ctx) { kill(getpid(), ctx->sig); } static void gc_action_gen_gpf(struct generic_child_ctx *ctx) { child_generate_gpf(NULL); } static void gc_action_gen_page_fault(struct generic_child_ctx *ctx) { child_generate_non_cow_page_fault(NULL); } void mask_signal(int sig) { sigset_t set; int rc; sigemptyset(&set); sigaddset(&set, sig); rc = sigprocmask(SIG_BLOCK, &set, NULL); if (rc != 0) { printf("FAIL: sigprocmask() failed with %s (%d)\n", strerror(errno), errno); exit(1); } } void unmask_signal(int sig) { sigset_t set; int rc; sigemptyset(&set); sigaddset(&set, sig); rc = sigprocmask(SIG_UNBLOCK, &set, NULL); if (rc != 0) { printf("FAIL: sigprocmask() failed with %s (%d)\n", strerror(errno), errno); exit(1); } } static void generic_child_do_mask(struct generic_child_ctx *ctx, sigset_t *set) { int rc; sigemptyset(set); if (ctx->masked_sig1) sigaddset(set, ctx->masked_sig1); if (ctx->masked_sig2) sigaddset(set, ctx->masked_sig2); rc = sigprocmask(SIG_BLOCK, set, NULL); if (rc != 0) { printf("FAIL[1]: sigprocmask() failed with: %s (%d)\n", strerror(errno), errno); exit(1); } } static void generic_child_check_pending(struct generic_child_ctx *ctx) { sigset_t pending_set; int rc = sigpending(&pending_set); if (rc != 0) { printf("FAIL[2]: sigpending failed with: %s (%d)\n", strerror(errno), errno); exit(1); } if (ctx->masked_sig1) { if (!sigismember(&pending_set, ctx->masked_sig1)) { printf("FAIL[3]: masked_sig1 is NOT pending\n"); exit(1); } } if (ctx->masked_sig2) { if (!sigismember(&pending_set, ctx->masked_sig2)) { printf("FAIL[3]: masked_sig2 is NOT pending\n"); exit(1); } } } static void generic_child(void *arg) { struct generic_child_ctx *ctx = arg; sigset_t set; int rc; signal(ctx->sig, ctx->handler); if (ctx->masked_sig1 || ctx->masked_sig2) generic_child_do_mask(ctx, &set); if (ctx->main_action_cb) ctx->main_action_cb(ctx); else pause(); if (ctx->after_unmask_cb) { generic_child_check_pending(ctx); /* * Run the after_mask_cb callback. The purpose of this callback is to * alter the global state used by signal handlers in a way to allow the * test to distinguish the case where the signal handler has been run * despite being masked (bug) from the one where the signal handler has * been run after the signal handler is unblocked here below. */ ctx->after_unmask_cb(); rc = sigprocmask(SIG_UNBLOCK, &set, NULL); if (rc != 0) { printf("FAIL[3]: sigprocmask() failed with: %s (%d)\n", strerror(errno), errno); exit(1); } } exit(0); } int test_sig(void (*child_func)(void *), void *arg, int expected_sig, int expected_code, int signal_to_send) { int code, term_sig; int child_pid; int wstatus; int rc; child_pid = fork(); if (child_pid < 0) { printf("fork() failed\n"); return 1; } if (!child_pid) { child_func(arg); exit(0); } if (signal_to_send) { printf("parent: wait 100ms...\n"); usleep(100 * 1000); printf("parent: send signal %d to child\n", signal_to_send); kill(child_pid, signal_to_send); } rc = waitpid(-1, &wstatus, 0); if (rc != child_pid) { printf("waitpid returned %d instead of child's pid: %d\n", rc, child_pid); return 1; } code = WEXITSTATUS(wstatus); term_sig = WTERMSIG(wstatus); if (expected_sig > 0) { if (code != 0) { printf("FAIL: expected child to exit with 0, got: %d\n", code); return 1; } if (term_sig != expected_sig) { printf("FAIL: expected child exit due to signal " "%d, instead got terminated by: %d\n", expected_sig, term_sig); return 1; } printf("parent: the child exited with signal %d, as expected.\n", expected_sig); } else { if (term_sig != 0) { printf("FAIL: expected child to exit with code %d, " "it got terminated with signal: %d\n", expected_code, term_sig); return 1; } if (code != expected_code) { printf("FAIL: expected child exit with " "code %d, got: %d\n", expected_code, code); return 1; } printf("parent: the child exited with code %d, as expected.\n", expected_code); } return 0; } /* Trigger SIGSEGV it with a real fault */ int cmd_sigsegv0(int argc, char **argv) { return test_sig(child_generate_gpf, NULL, SIGSEGV, 0, 0); } /* Mask SIGSEGV and then trigger it with a real GPF */ int cmd_sigsegv1(int argc, char **argv) { mask_signal(SIGSEGV); return test_sig(child_generate_gpf, NULL, SIGSEGV, 0, 0); } /* Mask SIGSEGV and then trigger it with a real page-fault */ int cmd_sigsegv2(int argc, char **argv) { mask_signal(SIGSEGV); return test_sig(child_generate_non_cow_page_fault, NULL, SIGSEGV, 0, 0); } /* Mask SIGILL and then trigger it with a real fault */ int cmd_sigill(int argc, char **argv) { mask_signal(SIGILL); return test_sig(child_generate_sigill, NULL, SIGILL, 0, 0); } /* Mask SIGFPE and then trigger it with a real fault */ int cmd_sigfpe(int argc, char **argv) { mask_signal(SIGFPE); return test_sig(child_generate_sigfpe, NULL, SIGFPE, 0, 0); } int cmd_sigabrt(int argc, char **argv) { return test_sig(child_generate_sigabrt, NULL, SIGABRT, 0, 0); } int cmd_sig_ignore(int argc, char **argv) { return test_sig(child_generate_and_ignore_sigint, NULL, 0, 0, 0); } static int compare_sig_tests(int id, sigset_t *set, sigset_t *oldset) { for (int i = 1; i < 32; i++) { if (sigismember(set, i) != sigismember(oldset, i)) { printf( "[case %d], set[%d]: %d != oldset[%d]: %d\n", id, i, sigismember(set, i), i, sigismember(oldset, i) ); return 1; } } return 0; } int cmd_sigmask(int argc, char **argv) { int rc; sigset_t set, oldset; sigemptyset(&set); rc = sigprocmask(SIG_SETMASK, &set, NULL); DEVSHELL_CMD_ASSERT(rc == 0); rc = sigprocmask(0 /* how ignored */, NULL, &oldset); DEVSHELL_CMD_ASSERT(rc == 0); if (compare_sig_tests(0, &set, &oldset)) return 1; sigemptyset(&set); rc = sigprocmask(SIG_SETMASK, &set, NULL); DEVSHELL_CMD_ASSERT(rc == 0); rc = sigprocmask(0 /* how ignored */, NULL, &oldset); DEVSHELL_CMD_ASSERT(rc == 0); if (compare_sig_tests(1, &set, &oldset)) return 1; sigemptyset(&set); sigaddset(&set, 5); sigaddset(&set, 10); sigaddset(&set, 12); sigaddset(&set, 20); rc = sigprocmask(SIG_BLOCK, &set, NULL); DEVSHELL_CMD_ASSERT(rc == 0); rc = sigprocmask(0 /* how ignored */, NULL, &oldset); DEVSHELL_CMD_ASSERT(rc == 0); if (compare_sig_tests(2, &set, &oldset)) return 1; sigemptyset(&set); sigaddset(&set, 12); rc = sigprocmask(SIG_UNBLOCK, &set, NULL); DEVSHELL_CMD_ASSERT(rc == 0); sigdelset(&oldset, 12); memcpy(&set, &oldset, sizeof(sigset_t)); rc = sigprocmask(0 /* how ignored */, NULL, &oldset); DEVSHELL_CMD_ASSERT(rc == 0); if (compare_sig_tests(3, &set, &oldset)) return 1; return 0; } static volatile bool test_got_sig[_NSIG]; void child_sig_handler(int signum) { printf("child: handle signal: %d\n", signum); if (!is_stack_aligned_16()) { printf("child: stack is NOT aligned at 16-bytes boundary\n"); exit(1); } test_got_sig[signum] = true; fflush(stdout); } static bool got_all_signals(int n) { switch (n) { case 1: return test_got_sig[SIGHUP]; case 2: return test_got_sig[SIGHUP] && test_got_sig[SIGINT]; default: abort(); } } static void test_sig_child_body(int n, bool busy_loop) { /* * Special variables FORCED to be on the stack by using "volatile" and the * magic DO_NOT_OPTIMIZE_AWAY(). We need them to check that the kernel * restored correctly the stack pointer after the signal handler run. */ volatile unsigned long magic1 = 0xcafebabe; volatile unsigned long magic2 = 0x11223344; DO_NOT_OPTIMIZE_AWAY(magic1); DO_NOT_OPTIMIZE_AWAY(magic2); memset((void *)test_got_sig, 0, sizeof(test_got_sig)); signal(SIGHUP, &child_sig_handler); signal(SIGINT, &child_sig_handler); if (busy_loop) { for (int i = 0; i < 100*1000*1000; i++) { if (got_all_signals(n)) break; } } else { pause(); } if (!got_all_signals(n)) { int count = 0; if (n >= 1) { count += test_got_sig[SIGHUP]; if (n >= 2) count += test_got_sig[SIGINT]; } if (busy_loop) printf("child: timeout!\n"); printf("child: didn't run handlers for all expected signals [%d/%d]\n", count, n); fflush(stdout); exit(1); } if (magic1 != 0xcafebabe || magic2 != 0x11223344) { printf("child: magic variables got corrupted!\n"); exit(1); } exit(0); } static int test_sig_n(int n, bool busy_loop, int exp_term_sig) { int code, term_sig; int child_pid; int wstatus; int rc; DEVSHELL_CMD_ASSERT(n == 1 || n == 2); child_pid = fork(); if (!child_pid) { test_sig_child_body(n, busy_loop); } /* --- parent --- */ /* * Sleep a bit in order to give some time to the child to enter in the busy * loop. NOTE: this is an extremely poor way of synchronizing two tasks, * even if it's simple and "just works" for tests. * * TODO: impl. a proper synchronization mechanism for sig3 and sig4 tests. */ usleep(25 * 1000); if (exp_term_sig) { kill(child_pid, exp_term_sig); } else { kill(child_pid, SIGHUP); if (n >= 2) kill(child_pid, SIGINT); } rc = waitpid(child_pid, &wstatus, 0); if (rc != child_pid) { printf("waitpid returned %d instead of child's pid: %d\n", rc, child_pid); return 1; } code = WEXITSTATUS(wstatus); term_sig = WTERMSIG(wstatus); printf("parent: child exit code: %d, term_sig: %d\n", code, term_sig); if (exp_term_sig) { if (term_sig != exp_term_sig) { printf("FAIL: expected child to be killed by sig %d. It did not.\n", exp_term_sig); return 1; } } else { if (term_sig || code != 0) { printf("FAIL: expected child to exit gracefully. It did not.\n"); return 1; } } return 0; } /* Test delivery of single signal durning syscall */ int cmd_sig1(int argc, char **argv) { return test_sig_n(1, false, 0); } /* Test delivery of two signals durning syscall */ int cmd_sig2(int argc, char **argv) { return test_sig_n(2, false, 0); } /* Test signal delivery while user space is running */ int cmd_sig3(int argc, char **argv) { return test_sig_n(1, true, 0); } /* Test killing signal delivery while user space is running */ int cmd_sig4(int argc, char **argv) { return test_sig_n(1, true, SIGKILL); } static int sig_handler_call_exit_code = 42; static void sig_handler_call_exit(int sig) { exit(sig_handler_call_exit_code); } static void increase_call_exit_code(void) { sig_handler_call_exit_code++; } /* Test that exit() works in signal handlers */ int cmd_sig5(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGTERM, .handler = &sig_handler_call_exit, .masked_sig1 = 0, .masked_sig2 = 0, .main_action_cb = &gc_action_pause, }; return test_sig( &generic_child, &ctx, 0, 42, SIGTERM ); } static void sig_handler_self_kill(int sig) { kill(getpid(), SIGQUIT); } /* Test that kill() works in signal handlers */ int cmd_sig6(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGTERM, .handler = &sig_handler_self_kill, .masked_sig1 = 0, .masked_sig2 = 0, .main_action_cb = &gc_action_pause, }; return test_sig( &generic_child, &ctx, SIGQUIT, 0, SIGTERM ); } /* * Test that with sigprocmask() a signal handler won't be executed until * the signal in unmasked. */ int cmd_sig7(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGTERM, .handler = &sig_handler_call_exit, .masked_sig1 = SIGTERM, .masked_sig2 = 0, .after_unmask_cb = &increase_call_exit_code, .main_action_cb = &gc_action_self_kill, }; return test_sig( &generic_child, &ctx, 0, 43, 0 ); } /* Test that with sigprocmask() a terminating signal still be masked */ int cmd_sig8(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGTERM, .handler = SIG_DFL, /* default action: terminate for SIGTERM */ .masked_sig1 = SIGTERM, .masked_sig2 = 0, .main_action_cb = &gc_action_self_kill, }; return test_sig( &generic_child, &ctx, 0, 0, 0 ); } /* Test that with sigprocmask() a SIGSEGV signal will still be masked */ int cmd_sigsegv3(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGSEGV, .handler = SIG_DFL, /* default action: terminate for SIGSEGV */ .masked_sig1 = SIGSEGV, .masked_sig2 = 0, .main_action_cb = &gc_action_self_kill, }; return test_sig( &generic_child, &ctx, 0, 0, 0 ); } /* Test that with sigprocmask() we cannot mask SIGKILL */ int cmd_sig9(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGKILL, .handler = SIG_DFL, .masked_sig1 = SIGKILL, .masked_sig2 = 0, .main_action_cb = &gc_action_pause, }; return test_sig( &generic_child, &ctx, SIGKILL, 0, SIGKILL ); } static bool is_single_signal_pending(int sig) { sigset_t set; int rc; sigemptyset(&set); sigaddset(&set, sig); rc = sigpending(&set); if (rc != 0) { printf("FAIL: sigpending() failed with %s (%d)\n", strerror(errno), errno); exit(1); } return sigismember(&set, sig); } static void forking_sig_handler(int sig) { int code, term_sig; int child_pid; int wstatus; int rc; DEVSHELL_CMD_ASSERT(sig == SIGUSR1); printf("child: send SIGUSR2 to myself, knowing that it is masked\n"); rc = kill(getpid(), SIGUSR2); DEVSHELL_CMD_ASSERT(rc == 0); if (!is_single_signal_pending(SIGUSR2)) { printf("FAIL: SIGUSR2 is not pending in child\n"); exit(1); } child_pid = fork(); if (child_pid < 0) { printf("FAIL: fork() in sig handler failed with %s (%d)\n", strerror(errno), errno); exit(1); } if (!child_pid) { /* Mask SIGUSR1 because we know that our parent will send that */ mask_signal(SIGUSR1); printf("** grandchild forked from signal handler, runs **\n"); if (is_single_signal_pending(SIGUSR2)) { printf("FAIL: SIGUSR2 is pending in grandchild\n"); exit(1); } /* Make sure to wait FOR THAN ENOUGH for SIGUSR1 to come */ usleep(100 * 1000); /* Check that it is pending */ if (!is_single_signal_pending(SIGUSR1)) { printf("FAIL: grandchild: SIGUSR1 is not pending\n"); exit(1); } exit(42); } printf("child inside signal handler: sleep 10ms\n"); usleep(50 * 1000); printf("child inside signal handler: send SIGUSR1 to grandchild\n"); kill(child_pid, SIGUSR1); rc = waitpid(child_pid, &wstatus, 0); if (rc != child_pid) { printf("child inside signal handler: waitpid() returned %d instead of " "child's pid: %d\n", rc, child_pid); exit(1); } code = WEXITSTATUS(wstatus); term_sig = WTERMSIG(wstatus); printf("child inside signal handler: gradchild exit code: %d, sig: %d\n", code, term_sig); if (code != 42) { printf("FAIL: expected exit code == 42, got: %d\n", code); exit(1); } } /* Test that we can call fork() in a signal handler */ int cmd_sig10(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGUSR1, .handler = &forking_sig_handler, .masked_sig1 = SIGUSR2, .masked_sig2 = 0, .main_action_cb = &gc_action_pause, }; return test_sig( &generic_child, &ctx, 0, 0, SIGUSR1 ); } static void execve_sig_handler(int sig) { int code, term_sig; int child_pid; int wstatus; int rc; DEVSHELL_CMD_ASSERT(sig == SIGUSR1); child_pid = fork(); if (child_pid < 0) { printf("FAIL: fork() in sig handler failed with %s (%d)\n", strerror(errno), errno); exit(1); } if (!child_pid) { printf("grandchild: send SIGUSR2 to myself, knowing that it is masked\n"); rc = kill(getpid(), SIGUSR2); DEVSHELL_CMD_ASSERT(rc == 0); if (!is_single_signal_pending(SIGUSR2)) { printf("FAIL: SIGUSR2 is not pending in grandchild\n"); exit(1); } printf("grandchild: execute devshell, with SIGUSR2 pending\n"); execle(get_devshell_path(), "devshell", "--blah", NULL, shell_env); /* We should never get here */ printf("grandchild: execl failed with: %s (%d)\n", strerror(errno), errno); exit(1); } rc = waitpid(child_pid, &wstatus, 0); if (rc != child_pid) { printf("child inside signal handler: waitpid() returned %d instead of " "child's pid: %d\n", rc, child_pid); exit(1); } code = WEXITSTATUS(wstatus); term_sig = WTERMSIG(wstatus); printf("child inside signal handler: gradchild exit code: %d, sig: %d\n", code, term_sig); if (term_sig != SIGUSR2) { printf("FAIL: expected granchild to die with SIGUSR2, got instead: %d\n", term_sig); exit(1); } printf("child inside signal handler: " "the gradchild was killed by SIGUSR2, as expected\n"); } /* Test that we can call fork() in a signal handler */ int cmd_sig11(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGUSR1, .handler = &execve_sig_handler, .masked_sig1 = SIGUSR2, .masked_sig2 = 0, .main_action_cb = &gc_action_pause, }; return test_sig( &generic_child, &ctx, 0, 0, SIGUSR1 ); } /* Test sigsuspend() */ int cmd_sig12(int argc, char **argv) { sigset_t set, saved_mask; int rc; printf("sigsuspend() test: setup the initial mask\n"); sigemptyset(&saved_mask); sigaddset(&saved_mask, SIGINT); sigaddset(&saved_mask, SIGQUIT); sigaddset(&saved_mask, SIGPWR); rc = sigprocmask(SIG_SETMASK, &saved_mask, NULL); if (rc) { printf("sigprocmask() failed with %s (%d)\n", strerror(errno), errno); exit(1); } printf("mask SIGUSR1 and SIGUSR2\n"); mask_signal(SIGUSR1); mask_signal(SIGUSR2); memset((void *)test_got_sig, 0, sizeof(test_got_sig)); signal(SIGUSR1, &child_sig_handler); signal(SIGUSR2, &child_sig_handler); printf("send both SIGUSR1 and SIGUSR2 to myself\n"); kill(getpid(), SIGUSR1); kill(getpid(), SIGUSR2); printf("prepare the new mask which blocks everything but SIGUSR1\n"); sigfillset(&set); sigdelset(&set, SIGUSR1); DEVSHELL_CMD_ASSERT(test_got_sig[SIGUSR1] == false); /* Call sigsupend and expect SIGUSR1 to be delievered */ printf("call sigsuspend()\n"); sigsuspend(&set); DEVSHELL_CMD_ASSERT(test_got_sig[SIGUSR1] == true); DEVSHELL_CMD_ASSERT(test_got_sig[SIGUSR2] == false); printf("unmask SIGUSR2\n"); unmask_signal(SIGUSR2); DEVSHELL_CMD_ASSERT(test_got_sig[SIGUSR2] == true); unmask_signal(SIGUSR1); printf("retrive the original mask, expecting no change.\n"); rc = sigprocmask(0, NULL, &set); if (rc) { printf("sigprocmask() failed with %s (%d)\n", strerror(errno), errno); exit(1); } for (int i = 1; i < _NSIG; i++) { if (sigismember(&set, i) != sigismember(&saved_mask, i)) { printf("FAIL: the current and saved mask differ\n"); printf("current mask[%d]: %d\n", i, sigismember(&set, i)); printf("saved mask[%d]: %d\n", i, sigismember(&saved_mask, i)); } } return 0; } static volatile int sig_chld_count; static void handle_sigchld(int sig) { printf("parent: got SIGCHLD, count: %d\n", ++sig_chld_count); } /* Test that SIGCHLD is sent when a child changes its state */ int cmd_sig13(int argc, char **argv) { int child_pid; int wstatus; int rc; sig_chld_count = 0; child_pid = fork(); if (child_pid < 0) { printf("parent: fork() failed with %s (%d)\n", strerror(errno), errno); exit(1); } if (!child_pid) { printf("child: hello!\n"); printf("child: waiting a little...\n"); usleep(300 * 1000); printf("child: done\n"); usleep(50 * 1000); printf("child: exit(42)\n"); exit(42); } signal(SIGCHLD, &handle_sigchld); printf("parent: wait...\n"); usleep(50 * 1000); printf("parent: send SIGSTOP..\n"); kill(child_pid, SIGSTOP); printf("parent: wait...\n"); usleep(50 * 1000); printf("parent: send SIGCONT..\n"); kill(child_pid, SIGCONT); printf("parent: wait...\n"); usleep(200 * 1000); printf("parent: waitpid()\n"); do { rc = waitpid(child_pid, &wstatus, 0); } while (rc < 0 && errno == EINTR); DEVSHELL_CMD_ASSERT(rc == child_pid); DEVSHELL_CMD_ASSERT(WEXITSTATUS(wstatus) == 42); DEVSHELL_CMD_ASSERT(WTERMSIG(wstatus) == 0); DEVSHELL_CMD_ASSERT(sig_chld_count == 3); return 0; } /* Test that we can handle SIGSEGV, triggered by GPF */ int cmd_sigsegv4(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGSEGV, .handler = &sig_handler_call_exit, .masked_sig1 = SIGSEGV, /* mask the signal: that should have no effect */ .masked_sig2 = 0, .main_action_cb = &gc_action_gen_gpf, }; return test_sig( &generic_child, &ctx, 0, 42, 0 ); } /* Test that we can handle SIGSEGV, triggered by page fault */ int cmd_sigsegv5(int argc, char **argv) { struct generic_child_ctx ctx = { .sig = SIGSEGV, .handler = &sig_handler_call_exit, .masked_sig1 = SIGSEGV, /* mask the signal: that should have no effect */ .masked_sig2 = 0, .main_action_cb = &gc_action_gen_page_fault, }; return test_sig( &generic_child, &ctx, 0, 42, 0 ); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/term.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/timer.h> #include "pic.h" struct list irq_handlers_lists[16] = { STATIC_LIST_INIT(irq_handlers_lists[ 0]), STATIC_LIST_INIT(irq_handlers_lists[ 1]), STATIC_LIST_INIT(irq_handlers_lists[ 2]), STATIC_LIST_INIT(irq_handlers_lists[ 3]), STATIC_LIST_INIT(irq_handlers_lists[ 4]), STATIC_LIST_INIT(irq_handlers_lists[ 5]), STATIC_LIST_INIT(irq_handlers_lists[ 6]), STATIC_LIST_INIT(irq_handlers_lists[ 7]), STATIC_LIST_INIT(irq_handlers_lists[ 8]), STATIC_LIST_INIT(irq_handlers_lists[ 9]), STATIC_LIST_INIT(irq_handlers_lists[10]), STATIC_LIST_INIT(irq_handlers_lists[11]), STATIC_LIST_INIT(irq_handlers_lists[12]), STATIC_LIST_INIT(irq_handlers_lists[13]), STATIC_LIST_INIT(irq_handlers_lists[14]), STATIC_LIST_INIT(irq_handlers_lists[15]), }; u32 unhandled_irq_count[256]; u32 spur_irq_count; void idt_set_entry(u8 num, void *handler, u16 sel, u8 flags); /* This installs a custom IRQ handler for the given IRQ */ void irq_install_handler(u8 irq, struct irq_handler_node *n) { ulong var; disable_interrupts(&var); { list_add_tail(&irq_handlers_lists[irq], &n->node); } enable_interrupts(&var); irq_clear_mask(irq); } /* This clears the handler for a given IRQ */ void irq_uninstall_handler(u8 irq, struct irq_handler_node *n) { ulong var; disable_interrupts(&var); { list_remove(&n->node); if (list_is_empty(&irq_handlers_lists[irq])) irq_set_mask(irq); } enable_interrupts(&var); } static inline void handle_irq_set_mask_and_eoi(int irq) { if (KRN_TRACK_NESTED_INTERR) { /* * We can really allow nested IRQ0 only if we track the nested interrupts, * otherwise, the timer handler won't be able to know it's running in a * nested way and "bad things may happen". */ if (irq != X86_PC_TIMER_IRQ) pic_mask_and_send_eoi(irq); else pic_send_eoi(irq); } else { pic_mask_and_send_eoi(irq); } } static inline void handle_irq_clear_mask(int irq) { if (KRN_TRACK_NESTED_INTERR) { if (irq != X86_PC_TIMER_IRQ) irq_clear_mask(irq); } else { irq_clear_mask(irq); } } void arch_irq_handling(regs_t *r) { enum irq_action hret = IRQ_NOT_HANDLED; const int irq = r->int_num - 32; struct irq_handler_node *pos; ASSERT(!are_interrupts_enabled()); ASSERT(!is_preemption_enabled()); if (pic_is_spur_irq(irq)) { spur_irq_count++; return; } push_nested_interrupt(r->int_num); handle_irq_set_mask_and_eoi(irq); enable_interrupts_forced(); { list_for_each_ro(pos, &irq_handlers_lists[irq], node) { hret = pos->handler(pos->context); if (hret != IRQ_NOT_HANDLED) break; } if (hret == IRQ_NOT_HANDLED) unhandled_irq_count[irq]++; } disable_interrupts_forced(); handle_irq_clear_mask(irq); pop_nested_interrupt(); } int get_irq_num(regs_t *context) { return int_to_irq(context->int_num); } int get_int_num(regs_t *context) { return context->int_num; } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(BUILD_BOOTPART ${CMAKE_BINARY_DIR}/scripts/build_bootpart) set(BUILD_FATPART ${CMAKE_BINARY_DIR}/scripts/build_fatpart) set(BUILD_TEST_FATPART ${CMAKE_BINARY_DIR}/scripts/build_test_fatpart) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/build_bootpart ${BUILD_BOOTPART} ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/build_fatpart ${BUILD_FATPART} ) smart_config_file( ${CMAKE_SOURCE_DIR}/scripts/templates/build_test_fatpart ${BUILD_TEST_FATPART} ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/fat32_base.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define MAX_ACTIONS 3 #define NO_ACTIONS() { NULL, NULL, NULL, NULL } #define ACTIONS_1(a1) { a1, NULL, NULL, NULL } #define ACTIONS_2(a1, a2) { a1, a2, NULL, NULL } #define ACTIONS_3(a1, a2, a3) { a1, a2, a3, NULL } struct action_ctx { int fd; void *vaddr; struct stat statbuf; }; typedef int (*act_t)(struct action_ctx *); struct action { const char *params[2]; act_t pre_mmap_actions[MAX_ACTIONS+1]; act_t actions[MAX_ACTIONS+1]; act_t post_munmap_actions[MAX_ACTIONS+1]; }; /* Global variables */ static u32 used_bytes; static u32 ff_clu_off; /* --- */ static int action_mmap(struct action_ctx *ctx) { ASSERT(ctx->vaddr == NULL); ASSERT(ctx->fd > 0); ASSERT(ctx->statbuf.st_size > 0); ctx->vaddr = mmap(NULL, /* addr */ ctx->statbuf.st_size, /* length */ PROT_READ|PROT_WRITE, /* prot */ MAP_SHARED, /* flags */ ctx->fd, /* fd */ 0); /* offset */ if (ctx->vaddr == (void *)-1) { perror("mmap() failed"); return -1; } return 0; } static int action_munmap(struct action_ctx *ctx) { int rc = munmap(ctx->vaddr, ctx->statbuf.st_size); if (rc < 0) { perror("munmap() failed"); return -1; } ctx->vaddr = NULL; return 0; } static int action_calc_used_bytes(struct action_ctx *ctx) { ff_clu_off = fat_get_first_free_cluster_off(ctx->vaddr); used_bytes = fat_calculate_used_bytes(ctx->vaddr); if (ff_clu_off > used_bytes) { fprintf(stderr, "FATAL ERROR: ff_clu_off (%u) > used_bytes (%u)\n", ff_clu_off, used_bytes); return 1; } return 0; } static int action_truncate(struct action_ctx *ctx) { if (ftruncate(ctx->fd, used_bytes) < 0) { perror("ftruncate() failed"); return 1; } return 0; } static int action_print_used_bytes(struct action_ctx *ctx) { printf("%u\n", used_bytes); return 0; } static int action_expand_file_by_4k(struct action_ctx *ctx) { if (ftruncate(ctx->fd, ctx->statbuf.st_size + 4096) < 0) { perror("ftruncate() failed"); return 1; } if (fstat(ctx->fd, &ctx->statbuf) < 0) { perror("stat() failed"); return 1; } return 0; } static int action_do_align(struct action_ctx *ctx) { if (used_bytes > ctx->statbuf.st_size) { fprintf(stderr, "FATAL ERROR: used bytes (%u) > st_size (%ld)\n", used_bytes, ctx->statbuf.st_size); return 1; } if (fat_is_first_data_sector_aligned(ctx->vaddr, 4096)) { printf("INFO: First data sector already aligned\n"); return 0; } if (used_bytes < ctx->statbuf.st_size) { fprintf(stderr, "INFO: fat file NOT truncated.\n"); fprintf(stderr, "INFO: used bytes (%u) < st_size (%ld)\n", used_bytes, ctx->statbuf.st_size); } /* * While on the Linux kernel (and on Tilck as well) it's fine to expand or * shrink a file while being memory-mapped, that's NOT true on WSL. While * it's true that WSL is not supposed to be Tilck's main build host type, * it is still nice to support it, in particular because that does not * require a huge effort; just minor fixes here and there. */ if (action_munmap(ctx) < 0) return -1; action_expand_file_by_4k(ctx); if (action_mmap(ctx) < 0) return -1; fat_align_first_data_sector(ctx->vaddr, 4096); return 0; } struct action actions[] = { { {"-t", "--truncate"}, NO_ACTIONS(), ACTIONS_1(action_calc_used_bytes), ACTIONS_1(action_truncate), }, { {"-c", "--calc_used_bytes"}, NO_ACTIONS(), ACTIONS_1(action_calc_used_bytes), ACTIONS_1(action_print_used_bytes), }, { {"-a", "--align_first_data_sector"}, NO_ACTIONS(), ACTIONS_2(action_calc_used_bytes, action_do_align), NO_ACTIONS(), }, }; void show_help_and_exit(int argc, char **argv) { printf("Syntax:\n"); printf(" %s -t, --truncate <fat part file>\n", argv[0]); printf(" %s -c, --calc_used_bytes <fat part file>\n", argv[0]); printf(" %s -a, --align_first_data_sector <fat part file>\n", argv[0]); exit(1); } static int parse_opts(int argc, char **argv, struct action **a_ref, const char **file_ref) { struct action *a = NULL; if (argc < 3) return -1; for (int i = 0; !a && i < ARRAY_SIZE(actions); i++) { for (int j = 0; j < 2; j++) if (!strcmp(argv[1], actions[i].params[j])) a = &actions[i]; } if (!a) return -1; *a_ref = a; *file_ref = argv[2]; return 0; } int main(int argc, char **argv) { int failed; const char *file; struct action *a; struct action_ctx ctx = {0}; if (parse_opts(argc, argv, &a, &file) < 0) show_help_and_exit(argc, argv); if (stat(file, &ctx.statbuf) < 0) { perror("stat() failed"); return 1; } if (!S_ISREG(ctx.statbuf.st_mode) && !S_ISBLK(ctx.statbuf.st_mode)) { fprintf(stderr, "Invalid file type\n"); return 1; } ctx.fd = open(file, O_RDWR); if (ctx.fd < 0) { perror("open() failed"); return 1; } for (act_t *f = a->pre_mmap_actions; *f; f++) if ((failed = (*f)(&ctx))) goto out; if (action_mmap(&ctx) < 0) { failed = 1; goto out; } for (act_t *f = a->actions; *f; f++) if ((failed = (*f)(&ctx))) goto out; if (action_munmap(&ctx) < 0) { failed = 1; goto out; } for (act_t *f = a->post_munmap_actions; *f; f++) if ((failed = (*f)(&ctx))) goto out; out: close(ctx.fd); return failed; } <file_sep>#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause # pylint: disable=unused-wildcard-import, bad-indentation, wildcard-import # pylint: disable=missing-function-docstring, wrong-import-position # pylint: disable=invalid-name, raise-missing-from, missing-class-docstring # pylint: disable=consider-using-f-string import os import re import sys import time import argparse import subprocess import ctypes import concurrent.futures as ft from typing import List, Dict, Tuple # Constants coming from CMake (this file gets pre-processed by CMake) RUNNERS_DIR = '@CMAKE_SOURCE_DIR@/tests/runners' KERNEL_FILE = '@KERNEL_FILE@' BUILD_DIR = '@CMAKE_BINARY_DIR@' KERNEL_FORCE_TC_ISYSTEM = '@KERNEL_FORCE_TC_ISYSTEM@' ELFHACK = '@CMAKE_BINARY_DIR@/scripts/build_apps/elfhack@ARCH_BITS@' sys.path.append(RUNNERS_DIR) from lib.utils import * from lib.detect_kvm import * from lib.env import * from lib.exceptions import * # Constants # Placeholder timeout value for manual tests, more convenient than 0 for sorting MANUAL_TEST_TIMEOUT = 10000 # Must match with `enum se_kind` in self_tests.h TIMEOUTS = { 'manual' : MANUAL_TEST_TIMEOUT, 'short': 12, 'med': 36, 'medlong': 72, 'long': 108, } TIMEOUTS_BY_KIND_NUM = list(TIMEOUTS.values()) INV_TIMEOUTS = { TIMEOUTS[k]: k for k in TIMEOUTS } INF_STR_TIMEOUTS = ['any', 'all', 'inf'] ordered_timeouts = sorted(list(INV_TIMEOUTS.keys())) # Timeout used for the `runall` shellcmd (-c option) ALL_TESTS_TIMEOUT = 4 * TIMEOUTS['med'] load_tests_func_by_type_list = [ 'load_list_of_kernel_self_tests', 'load_list_of_shell_cmd_tests', 'load_list_of_interactive_tests', ] tt_pretty_names = { val: TEST_TYPES_PRETTY[i] for i, val in enumerate(TEST_TYPES) } load_tests_func_by_type = { val: load_tests_func_by_type_list[i] for i, val in enumerate(TEST_TYPES) } tt_indexes = { val : i for i, val in enumerate(TEST_TYPES) } # Global variables tests_by_type : Dict[str, List[Tuple[str,int]]] = { k: [] for k in TEST_TYPES } tests_to_run : Dict[str, int] = { k: 0 for k in TEST_TYPES } tests_passed : Dict[str, int] = { k: 0 for k in TEST_TYPES } test_runners : Dict[str, str] = { k: "" for k in TEST_TYPES } def timeout_name(val): if val in INV_TIMEOUTS: return INV_TIMEOUTS[val] for t in ordered_timeouts: if val <= t: return INV_TIMEOUTS[t] return "(other)" def arg_type_test(s): if s in TEST_TYPES: return s tt = list(filter(lambda x: x.startswith(s), TEST_TYPES)) if len(tt) == 0: raise argparse.ArgumentTypeError("No such test type: '{}'".format(s)) if len(tt) > 1: raise argparse.ArgumentTypeError("Ambiguous test type: '{}'".format(s)) return tt[0] def arg_type_timeout(s): if s in TIMEOUTS: return TIMEOUTS[s] if s in INF_STR_TIMEOUTS: return 0 # OK, at this point 's' must be an integer try: return int(s) except: raise argparse.ArgumentTypeError( "Timeout must be an integer or one of: {}" .format(", ".join(list(TIMEOUTS.keys()) + INF_STR_TIMEOUTS)) ) def load_all_tests(): for tt in TEST_TYPES: tests_by_type[tt] = globals()[load_tests_func_by_type[tt]]() def load_list_of_interactive_tests(): result = [] rit = os.path.join(BUILD_DIR, 'st', 'run_interactive_test') try: output = subprocess.check_output([rit, '-l']).decode("utf-8") except subprocess.CalledProcessError as e: if e.returncode == Fail.invalid_build_config.value: # That's perfectly fine: this build has not been configured for # running interactive tests. Just return an empty list. return [] if e.returncode == Fail.invalid_system_config.value: # That's also possible (i.e. ImageMagick is not installed). Return # an empty list as above return [] # Oops, something weird happened: we cannot ignore the error. raise arr = output.split("\n") for r in arr: r = r.strip() if r: result.append([r, TIMEOUTS['medlong']]) test_runners["interactive"] = "@CMAKE_BINARY_DIR@/st/run_interactive_test" return result def load_list_of_shell_cmd_tests(): result = [] devshell = os.path.join(BUILD_DIR, 'userapps', 'devshell') output = subprocess.check_output([devshell, '-l']).decode("utf-8") arr = output.split("\n") for r in arr: r = r.rstrip() if not r: continue name, tt = r.split(' ') if not tt.startswith('tt_'): continue tt = tt[3:] # Skip the "tt_" prefix result.append([name, TIMEOUTS[tt]]) test_runners["shellcmd"] = "@CMAKE_BINARY_DIR@/st/single_test_run" return sorted(result, key = lambda x: x[1]) # Mapping of struct self_test defined in self_tests.h # TODO: make it work for 64-bit kernels as well class kernel_selftest_struct(ctypes.Structure): _fields_ = [("node", ctypes.c_char * 8), ("name", ctypes.c_char * 4), ("kind", ctypes.c_int), ("func", ctypes.c_char * 4)] def get_sym_data(sym): raw = subprocess \ .check_output([ELFHACK, KERNEL_FILE, '--dump-sym', sym]) \ .decode('utf-8') raw_arr = raw.split(' ')[:-1] # skip the last '\n' char data = [ int('0x' + x, 16) for x in raw_arr ] return bytes(data) def get_selftest_obj(sym): return kernel_selftest_struct.from_buffer_copy(get_sym_data(sym)) def load_list_of_kernel_self_tests(): result = [] rows = subprocess \ .check_output(['nm', KERNEL_FILE]) \ .decode("utf-8") \ .split("\n") for row in rows: row = row.rstrip() if not row: continue _, _, name = row.split(' ') m = re.match(r'^se_(.+)_inst$', name) if not m: continue sym_name = name test_name = m.group(1) obj = get_selftest_obj(sym_name) tt = TIMEOUTS_BY_KIND_NUM[obj.kind] result.append([test_name, tt]) test_runners["selftest"] = "@CMAKE_BINARY_DIR@/st/single_test_run" return sorted(result, key = lambda x: x[1]) def internal_single_test_runner_thread(test_type : str, test : str, timeout : int, show_output : bool): raw_print( "[ RUNNING ] {}: '{}' [timeout: {}]".format(test_type, test, timeout) ) cmdline = [ test_runners[test_type], test_type, test, str(timeout), get_qemu_kvm_version(), ] start_time = time.time() p = subprocess.Popen( cmdline, stdin = subprocess.DEVNULL, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, ) if show_output: raw_print("") bin_output = b'' while p.poll() is None: bintext = p.stdout.read() if not bintext: time.sleep(0.1) continue if show_output: direct_print(bintext) else: bin_output += bintext elapsed = time.time() - start_time if p.returncode == Fail.success.value: raw_print("[ PASSED ] after {:.2f} seconds\n".format(elapsed)) else: if not show_output: raw_print("") direct_print(bin_output) raw_print( "[ FAILED ] after {:.2f} seconds with: {}\n" .format(elapsed, get_fail_by_code(p.returncode)) ) return p.returncode def internal_run_test(test_type : str, test : str, timeout : int, show_output : bool = False): with ft.ThreadPoolExecutor(max_workers = 1) as executor: future = executor.submit( internal_single_test_runner_thread, test_type, test, timeout, show_output ) return future.result() def does_test_match_criteria(x : Tuple[str,int], reg : str, max_timeout : int, allow_manual : bool): name : str = x[0] timeout : int = x[1] is_runall = name in ['runall', 'runall_manual'] is_manual = timeout == MANUAL_TEST_TIMEOUT timeout_check = timeout <= max_timeout manual_check = not is_manual or allow_manual matches_filter = re.match(reg, name) and (timeout_check or manual_check) return is_runall or (matches_filter and manual_check) def list_tests(reg : str, max_timeout : int, test_type : str): col_names : List[Tuple[str, int]] = [ ('test name', 30), ('test type', 12), ('timeout', 10), ] raw_stdout_write("\n") for x in col_names: raw_stdout_write('+-') raw_stdout_write(''.center(x[1], '-')) raw_stdout_write('+\n') for x in col_names: raw_stdout_write('| ') raw_stdout_write(x[0].center(x[1], ' ')) raw_stdout_write('|\n') for x in col_names: raw_stdout_write('+-') raw_stdout_write(''.center(x[1], '-')) raw_stdout_write('+\n') for tt in TEST_TYPES: count = 0 if test_type and tt != test_type: continue for x in tests_by_type[tt]: if does_test_match_criteria(x, reg, max_timeout, True): tval = x[1] if tval != MANUAL_TEST_TIMEOUT: t = "{}".format(tval) else: t = "<manual>" raw_stdout_write('| ') raw_stdout_write(x[0].ljust(col_names[0][1])) raw_stdout_write('| ') raw_stdout_write(tt.ljust(col_names[1][1])) raw_stdout_write('| ') raw_stdout_write(t.ljust(col_names[2][1])) raw_stdout_write('|\n') count += 1 if count > 0: for x in col_names: raw_stdout_write('+-') raw_stdout_write(''.center(x[1], '-')) raw_stdout_write('+\n') raw_stdout_write('\n') def get_sum(per_test_counter): return sum(per_test_counter[k] for k in per_test_counter) def run_test(test_type : str, x : Tuple[str,int], # test, timeout show_output : bool): if get_sum(tests_to_run) == 0: raw_print("") tests_to_run[test_type] += 1 ret = internal_run_test(test_type, x[0], x[1], show_output) if ret == Fail.success.value: tests_passed[test_type] += 1 elif ret == Fail.shell_unknown_exit_code.value: # From time to time, the per-second message by the "sched alive thread" # interleaves the shell's exit code like that: # # [init] the shell with [ 2.139] ---- Sched alive thread: 2 ---- # pid 2 exited with status: 0 # # And this prevents the runner to correctly parse shell's exit code, # resulting in a false positive failure. # # To mitigate this problem, let's re-run the test just once, if it has # failed with: shell_unknown_exit_code. ret = internal_run_test(test_type, x[0], x[1], show_output) if ret == Fail.success.value: tests_passed[test_type] += 1 def run_all_tests(max_timeout : int, show_output : bool, reg : str, fail_on_zero : bool, test_type : str, allow_manual : bool): for tt in TEST_TYPES: if test_type and tt != test_type: continue for x in tests_by_type[tt]: if does_test_match_criteria(x, reg, max_timeout, allow_manual): run_test(tt, x, show_output) if fail_on_zero: if sum(tests_to_run.values()) == 0: found = [] for tt in TEST_TYPES: for x in tests_by_type[tt]: if re.match(reg, x[0]): found.append(x) if not found: raw_print("ERROR: No tests matching the '{}' regex.".format(reg)) else: raw_print( "ERROR: No tests matching " "the '{}' regex having timeout <= {}" .format(reg, max_timeout) ) raw_print( "Tests matching the regex with timeout > {}:" .format(max_timeout) ) for x in found: if x[1] != MANUAL_TEST_TIMEOUT: raw_print(" {} [timeout: {}s]".format(x[0].ljust(20), x[1])) else: raw_print(" {} [manual test]".format(x[0].ljust(20))) sys.exit(Fail.no_tests_matching.value) def dump_test_stats(): raw_print('-' * 80) for tt in TEST_TYPES: if tests_to_run[tt]: raw_print("{} passed: {}/{}" .format(tt_pretty_names[tt], tests_passed[tt], tests_to_run[tt])) def parse_args(): parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group() g.add_argument( "-l", "--list-tests", action = "store_true", help = "List all tests matching the criteria (dry-run)" ) g.add_argument( "-L", "--list-all-tests", action = "store_true", help = "List all tests, no matter their timeout (same as -l -t any)" ) g.add_argument( "-j", "--list-timeouts", action = "store_true", help = "List the predefined timeout values with labels usable with -t" ) parser.add_argument( "-c", "--compact-run", action = "store_true", help = "Run all the shellcmds in a single VM run (faster)" ) parser.add_argument( "-o", "--show-output", action = "store_true", help = "Show test's output even in case of success" ) parser.add_argument( "-a", "--allow-manual", action = "store_true", help = "Allow manual tests to be run by this script. " "Warning: some manual tests make the kernel to panic and that " "will be interpreted as a failure by this test runner." ) parser.add_argument( "-f", "--filter", type = str, default = ".*", help = "Run only tests matching the given regex filter" ) parser.add_argument( "-t", "--max-timeout", type = arg_type_timeout, default = TIMEOUTS['med'], help = "Run only tests having timeout <= MAX_TIMEOUT " "(default: {})".format(TIMEOUTS['med']) ) parser.add_argument( "-T", "--test_type", type = arg_type_test, help = "Run only tests of the given type. Minimal prefixes are " "accepted (e.g. 'se' is interpreted as selftest)." ) try: args = parser.parse_args() except SystemExit: sys.exit(Fail.invalid_args.value) return args def list_timeouts(): for tname, tval in TIMEOUTS.items(): if tname != 'manual': raw_print("{:8}: {:3} seconds".format(tname, tval)) for s in INF_STR_TIMEOUTS: raw_print("{:8}: <no timeout>".format(s)) def main(): set_runner_name("test runner") load_all_tests() args = parse_args() if args.compact_run: tests_by_type['shellcmd'] = [ ['runall', ALL_TESTS_TIMEOUT] ] if args.list_timeouts: list_timeouts() sys.exit(0) if args.list_all_tests: args.max_timeout = MANUAL_TEST_TIMEOUT args.list_tests = True if args.max_timeout == 0: args.max_timeout = MANUAL_TEST_TIMEOUT if args.list_tests: list_tests(args.filter, args.max_timeout, args.test_type) sys.exit(0) detect_kvm() if is_cmake_opt_enabled(KERNEL_FORCE_TC_ISYSTEM): unrunnable_build_graceful_exit() try: run_all_tests(args.max_timeout, args.show_output, args.filter, not args.compact_run, args.test_type, args.allow_manual) except KeyboardInterrupt: msg_print("KeyboardInterrupt") sys.exit(Fail.user_interruption.value) dump_test_stats() if get_sum(tests_passed) != get_sum(tests_to_run): sys.exit(Fail.some_tests_failed.value) ############################### if __name__ == '__main__': main() <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include "defs.h" #include "utils.h" #include <tilck/common/utils.h> #if defined(BITS32) void JumpToKernel(void *entry_point) { /* Jump to the kernel */ asmVolatile("jmp *%%ecx" : /* no output */ : "a" (MULTIBOOT_BOOTLOADER_MAGIC), "b" (gMbi), "c" (entry_point) : /* no clobber */); } #elif defined(BITS64) /* Defined in switchmode.S */ void switch_to_pm32_and_jump_to_kernel(multiboot_info_t *mbi, void *entry); void JumpToKernel(void *entry_point) { switch_to_pm32_and_jump_to_kernel(gMbi, entry_point); } #else #error Unknown architectre #endif EFI_INPUT_KEY WaitForKeyPress(void) { UINTN index; EFI_INPUT_KEY k; EFI_EVENT event = ST->ConIn->WaitForKey; BS->WaitForEvent(1, // number of events in the array pointed by &event &event, // pointer to events array (1 elem in our case). &index); // index of the last matching event in the array // Read the key, allowing WaitForKey to block again. ST->ConIn->ReadKeyStroke(ST->ConIn, &k); return k; } EFI_STATUS LoadFileFromDisk(EFI_FILE_PROTOCOL *fProt, EFI_PHYSICAL_ADDRESS *paddr, UINTN *fileSz, CHAR16 *filePath) { EFI_FILE_PROTOCOL *fileHandle = NULL; EFI_STATUS status = EFI_SUCCESS; UINTN pagesCount, fileInfoBufSz, readSz; char fileInfoBuf[sizeof(EFI_FILE_INFO) + 64]; EFI_FILE_INFO *nfo = (void *)fileInfoBuf; status = fProt->Open(fProt, &fileHandle, filePath, EFI_FILE_MODE_READ, 0); HANDLE_EFI_ERROR("fileProt->Open"); fileInfoBufSz = sizeof(fileInfoBuf); status = fProt->GetInfo(fileHandle, &gEfiFileInfoGuid, &fileInfoBufSz, nfo); HANDLE_EFI_ERROR("fileProt->GetInfo"); readSz = (UINTN)nfo->FileSize; *fileSz = pow2_round_up_at(readSz, PAGE_SIZE); pagesCount = *fileSz / PAGE_SIZE; status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData, pagesCount, paddr); HANDLE_EFI_ERROR("AllocatePages"); status = fProt->Read(fileHandle, &readSz, TO_PTR(*paddr)); HANDLE_EFI_ERROR("fileProt->Read"); end: if (fileHandle) { fileHandle->Close(fileHandle); } return status; } EFI_STATUS GetMemoryMap(UINTN *mapkey) { UINT32 desc_ver; EFI_STATUS status; gMmap_size = sizeof(gMmap); status = BS->GetMemoryMap(&gMmap_size,gMmap,mapkey,&gDesc_size,&desc_ver); HANDLE_EFI_ERROR("BS->GetMemoryMap"); end: return status; } EFI_MEMORY_DESCRIPTOR * GetMemDescForAddress(EFI_PHYSICAL_ADDRESS paddr) { EFI_MEMORY_DESCRIPTOR *desc = NULL; desc = (void *)gMmap; do { UINT64 start = desc->PhysicalStart; UINT64 end = start + desc->NumberOfPages * PAGE_SIZE; if (IN_RANGE(paddr, start, end)) return desc; desc = (void *)desc + gDesc_size; } while ((UINTN)desc < (UINTN)gMmap + gMmap_size); return NULL; } void ShowProgress(SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut, const CHAR16 *PrefixStr, UINTN curr, UINTN tot) { ConOut->SetCursorPosition(ConOut, 0, ConOut->Mode->CursorRow); Print(L"%s%u%%", PrefixStr, 100 * curr / tot); } EFI_STATUS ReadAlignedBlock(EFI_BLOCK_IO_PROTOCOL *blockio, UINTN offset, /* offset in bytes, aligned to blockSize */ UINTN len, /* length in bytes, aligned to blockSize */ void *buf) { const UINT32 blockSize = blockio->Media->BlockSize; const UINT32 mediaId = blockio->Media->MediaId; EFI_STATUS status = EFI_SUCCESS; if (offset % blockSize) { status = EFI_INVALID_PARAMETER; goto end; } if (len < blockSize || (len % blockSize)) { status = EFI_BAD_BUFFER_SIZE; goto end; } status = blockio->ReadBlocks(blockio, mediaId, offset / blockSize, /* offset in blocks */ len, /* length in bytes */ buf); if (EFI_ERROR(status)) { Print(L"offset: %u\n", offset); Print(L"length: %u\n", len); Print(L"logical part: %u\n", blockio->Media->LogicalPartition); HANDLE_EFI_ERROR("ReadBlocks"); } end: return status; } EFI_STATUS ReadDiskWithProgress(SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut, const CHAR16 *loadingStr, EFI_BLOCK_IO_PROTOCOL *blockio, UINT64 Offset, UINTN BufferSize, void *Buffer) { const UINTN ChunkSize = 256 * KB; const UINTN ChunkCount = BufferSize / ChunkSize; const UINTN rem = BufferSize - ChunkCount * ChunkSize; EFI_STATUS status = EFI_SUCCESS; for (u32 chunk = 0; chunk < ChunkCount; chunk++) { if (chunk > 0) { ShowProgress(ST->ConOut, loadingStr, chunk * ChunkSize, BufferSize); } status = ReadAlignedBlock(blockio, Offset, ChunkSize, Buffer); HANDLE_EFI_ERROR("ReadAlignedBlock"); Offset += ChunkSize; Buffer += ChunkSize; } if (rem > 0) { status = ReadAlignedBlock(blockio, Offset, rem, Buffer); HANDLE_EFI_ERROR("ReadAlignedBlock"); } ShowProgress(ST->ConOut, loadingStr, BufferSize, BufferSize); end: return status; } EFI_DEVICE_PATH * DevicePathGetLastValidNode(EFI_DEVICE_PATH *dp) { EFI_DEVICE_PATH *curr = dp; EFI_DEVICE_PATH *prev = dp; for (; !IsDevicePathEnd(curr); curr = NextDevicePathNode(curr)) { prev = curr; } return prev; } void TruncateDevicePath(EFI_DEVICE_PATH *dp) { EFI_DEVICE_PATH *lastDp = DevicePathGetLastValidNode(dp); SetDevicePathEndNode(lastDp); } EFI_DEVICE_PATH * GetCopyOfParentDevicePathNode(EFI_DEVICE_PATH *dp) { EFI_DEVICE_PATH *parent = DuplicateDevicePath(dp); TruncateDevicePath(parent); return parent; } EFI_STATUS GetHandlerForDevicePath(EFI_DEVICE_PATH *dp, EFI_GUID *supportedProt, EFI_HANDLE *refHandle) { EFI_DEVICE_PATH *dpCopy = dp; EFI_STATUS status = EFI_SUCCESS; status = BS->LocateDevicePath(supportedProt, &dpCopy, refHandle); HANDLE_EFI_ERROR("LocateDevicePath"); if (!IsDevicePathEnd(dpCopy)) { Print(L"ERROR: Cannot get a handler for device path:\n"); Print(L" \"%s\"\n", DevicePathToStr(dp)); Print(L"ERROR: Closest match:\n"); Print(L" \"%s\"\n", DevicePathToStr(dpCopy)); status = EFI_ABORTED; } end: return status; } <file_sep>from unittest import TestCase from cmake_var import metadata class test_custom_metadata(TestCase): generic_comment = """ GROUP KRN DEPENDS_ON A, B, C REALTYPE INT""".splitlines() invalid_keyword_comment = """ FOO KRN""".splitlines() def test_metadata_creation_correct(self): m = metadata(self.generic_comment) with self.subTest(): self.assertEqual(m.group, "KRN") with self.subTest(): self.assertEqual(m.depends_on, ["A", "B", "C"]) with self.subTest(): self.assertEqual(m.realtype, "INT") def test_metdata_creation_invalid_keyword(self): self.assertRaises(ValueError, metadata, self.invalid_keyword_comment) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/tilck_sound.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/user.h> #include <tilck/kernel/process.h> #include <tilck/kernel/timer.h> #include "sb16.h" /* One-time sb16 configuration shared with sb16_hw.c */ struct sb16_info sb16_info; /* Device's MAJOR number */ static u16 sb16_major; /* * Shared state between the IRQ handler and the rest of the code. * * NOTE: it's not necessary to use atomics because most of the time we disable * the interrupts while accessing the following state variables. In other cases, * like in sb16_ioctl_wait_for_completion() do just poll on sb16_playing: * volatile is mandatory, but no need for atomics. It's worth remarking that * in the simple model used by this driver, only ONE task at a time can acquire * and use this sound device. Therefore, no need for need for any kind of fancy * synchronization mechanisms. */ static volatile bool producer_is_sleeping; static volatile bool sb16_have_slot[2]; static volatile bool sb16_playing; static volatile u8 sb16_slot; /* DSP config */ static struct tilck_sound_params dsp_params; static u32 curr_buf_sz; /* The task currently owning the sound device */ static struct task *owner; static int sb16_alloc_buf(void) { size_t sz = 64 * KB; sb16_info.buf = general_kmalloc(&sz, KMALLOC_FL_DMA); if (!sb16_info.buf) return -ENOMEM; sb16_info.buf_paddr = KERNEL_VA_TO_PA(sb16_info.buf); /* The buffer must be aligned at 64-KB boundary */ ASSERT((sb16_info.buf_paddr & (64 * KB - 1)) == 0); return 0; } static enum irq_action sb16_handle_irq(void *ctx) { SB16_DBG("sb16, irq, completed slot: %u\n", sb16_slot); /* Mark the current slot as "used" */ sb16_have_slot[sb16_slot] = false; /* Switch to the other slot */ sb16_slot = !sb16_slot; /* ACK the hardware */ sb16_irq_ack(); if (!sb16_have_slot[sb16_slot]) { SB16_DBG("sb16, irq, no data for slot %u: STOP\n", sb16_slot); /* We don't have data ready in the new slot, stop */ sb16_pause(); sb16_playing = false; } else { SB16_DBG("sb16, irq, switch to slot: %u\n", sb16_slot); } if (producer_is_sleeping) { if (owner && owner->state == TASK_STATE_SLEEPING) task_change_state(owner, TASK_STATE_RUNNABLE); } return IRQ_HANDLED; } DEFINE_IRQ_HANDLER_NODE(dsp_irq_node, &sb16_handle_irq, NULL); static int sb16_install_irq_handler(void) { sb16_info.irq = sb16_get_irq(); printk("sb16: using irq #%u\n", sb16_info.irq); irq_install_handler(sb16_info.irq, &dsp_irq_node); return 0; } static ssize_t sb16_read(fs_handle h, char *user_buf, size_t size, offt *pos) { return 0; } static void sb16_fill_buf_with_mute(void *buf, size_t len) { u16 mute = (u16)(dsp_params.sign ? 0 : (1 << ((u32)dsp_params.bits-1)) - 1); if (dsp_params.bits == 8) memset(buf, mute, len); else memset16(buf, mute, len / 2); } static void sb16_fill_slot_with_mute(u8 slot) { u8 *buf = sb16_info.buf + (slot << 15); sb16_fill_buf_with_mute(buf, 32 * KB); } static void do_start_play(u8 next_slot, u32 sz) { static bool played_anything; bool currently_playing; disable_interrupts_forced(); { /* Mark the data in the next slot as "ready" */ SB16_DBG("write(): mark slot %u as available\n", next_slot); sb16_have_slot[next_slot] = true; currently_playing = sb16_playing; } enable_interrupts_forced(); if (!currently_playing) { SB16_DBG("write(): not playing, START!\n"); ASSERT(next_slot == 0); sb16_slot = next_slot; sb16_have_slot[1] = false; sb16_fill_slot_with_mute(1); sb16_playing = true; curr_buf_sz = MAX(sz, played_anything ? 4 * KB : 8 * KB); played_anything = true; sb16_program_dma(dsp_params.bits, sz < 32 * KB ? sz : 64 * KB); sb16_program(&dsp_params, curr_buf_sz); } else { SB16_DBG("write(): playing slot %u, do nothing\n", !next_slot); } } static ssize_t sb16_write(fs_handle h, char *user_buf, size_t size, offt *pos) { if (get_curr_task() != owner) { /* The current task, does not own the resource */ return -EPERM; } if (!dsp_params.bits) { /* Audio hasn't been configured with TILCK_IOCTL_SOUND_SETUP yet */ return -EINVAL; } const size_t sz = MIN(size, 32 * KB); bool must_sleep; u8 next_slot; u8 *dest_buf; do { must_sleep = false; disable_interrupts_forced(); { if (sb16_playing) { next_slot = !sb16_slot; if (sb16_have_slot[next_slot] || curr_buf_sz < 32 * KB) { if (curr_buf_sz < 32 * KB) SB16_DBG("force sleep on write() because buf < 32KB\n"); must_sleep = true; } } else { next_slot = 0; } } enable_interrupts_forced(); if (must_sleep) { SB16_DBG("write() requires to sleep (waiting for slot)\n"); producer_is_sleeping = true; kernel_sleep_ms(100); task_cancel_wakeup_timer(get_curr_task()); if (pending_signals()) return -EINTR; producer_is_sleeping = false; } } while (must_sleep); SB16_DBG("write(): using slot: %u\n", next_slot); dest_buf = sb16_info.buf + (next_slot << 15); if (copy_from_user(dest_buf, user_buf, sz)) return -EFAULT; if (sz < 32 * KB) { if (dsp_params.bits == 16 || dsp_params.channels == 2) { if (sz % 2) return -EINVAL; if (dsp_params.bits == 16 && dsp_params.channels == 2) if (sz % 4) return -EINVAL; } SB16_DBG("write(): small buf %u, fill %u with mute\n", sz, 32*KB - sz); sb16_fill_buf_with_mute(dest_buf + sz, 32 * KB - sz); } do_start_play(next_slot, sz); return (ssize_t)sz; } static int sb16_ioctl_sound_setup(struct tilck_sound_params *user_params) { if (get_curr_task() != owner) { /* The current task, does not own the resource */ return -EPERM; } if (sb16_playing) return -EBUSY; if (copy_from_user(&dsp_params, user_params, sizeof(dsp_params))) return -EFAULT; if (dsp_params.sample_rate <= 44100 && (dsp_params.bits == 8 || dsp_params.bits == 16) && (dsp_params.channels == 1 || dsp_params.channels == 2) && (dsp_params.sign == 0 || dsp_params.sign == 1)) { sb16_have_slot[0] = false; sb16_have_slot[1] = false; sb16_fill_slot_with_mute(0); sb16_fill_slot_with_mute(1); return 0; } bzero(&dsp_params, sizeof(dsp_params)); return -EINVAL; } static void sb16_release_on_exit(struct task *ti) { ASSERT(!is_preemption_enabled()); disable_interrupts_forced(); { owner = NULL; } enable_interrupts_forced(); SB16_DBG("sb16: release ownership from TID: %d\n", ti->tid); } static int sb16_ioctl_acquire(void) { int rc = 0; disable_preemption(); { if (owner && get_curr_task() != owner) { /* The current task, does not own the resource */ rc = -EPERM; } else { rc = register_on_task_exit_cb(&sb16_release_on_exit); if (rc >= 0) owner = get_curr_task(); } } enable_preemption(); return rc; } static int sb16_ioctl_release(void) { int rc = 0; disable_preemption(); { if (get_curr_task() != owner) { /* The current task does not own the resource */ rc = -EPERM; } else { unregister_on_task_exit_cb(&sb16_release_on_exit); owner = NULL; } } enable_preemption(); return rc; } static int sb16_ioctl_get_info(struct tilck_sound_card_info *user_info) { static const struct tilck_sound_card_info info = { .name = "sb16", .max_sample_rate = 44100, .max_bits = 16, .max_channels = 2, }; if (copy_to_user(user_info, &info, sizeof(info))) return -EFAULT; return 0; } static int sb16_ioctl_wait_for_completion(void) { if (get_curr_task() != owner) { /* The current task does not own the resource */ return -EPERM; } while (sb16_playing) { producer_is_sleeping = true; kernel_sleep_ms(100); task_cancel_wakeup_timer(get_curr_task()); if (pending_signals()) return -EINTR; producer_is_sleeping = false; } return 0; } static int sb16_ioctl(fs_handle h, ulong request, void *user_argp) { switch (request) { case TILCK_IOCTL_SOUND_ACQUIRE: return sb16_ioctl_acquire(); case TILCK_IOCTL_SOUND_RELEASE: return sb16_ioctl_release(); case TILCK_IOCTL_SOUND_SETUP: return sb16_ioctl_sound_setup(user_argp); case TILCK_IOCTL_SOUND_GET_INFO: return sb16_ioctl_get_info(user_argp); case TILCK_IOCTL_SOUND_WAIT_COMPLETION: return sb16_ioctl_wait_for_completion(); default: return -EINVAL; } } static int create_sb16_device(int minor, enum vfs_entry_type *type, struct devfs_file_info *nfo) { static const struct file_ops static_ops_sb16 = { .read = sb16_read, .write = sb16_write, .ioctl = sb16_ioctl, }; *type = VFS_CHAR_DEV; nfo->fops = &static_ops_sb16; nfo->spec_flags = VFS_SPFL_NO_USER_COPY; return 0; } static void init_sb16(void) { int rc; if (sb16_detect_dsp_hw_and_reset() < 0) return; if (sb16_check_version() < 0) return; printk("sb16: hw init success, version: %u.%u\n", sb16_info.ver_major, sb16_info.ver_minor); if (sb16_install_irq_handler() < 0) return; if (sb16_alloc_buf() < 0) { printk("sb16: failed to alloc buffer\n"); return; } outb(DSP_WRITE, DSP_ENABLE_SPKR); struct driver_info *di = kalloc_obj(struct driver_info); if (!di) { printk("sb16: out of memory\n"); return; } di->name = "sb16"; di->create_dev_file = create_sb16_device; rc = register_driver(di, -1); if (rc < 0) { printk("sb16: failed to register driver (%d)\n", rc); return; } sb16_major = (u16) rc; rc = create_dev_file("sb16", sb16_major, 0 /* minor */, NULL); if (rc != 0) panic("sb16: unable to create /dev/sb16 (error: %d)", rc); } static struct module sb16_module = { .name = "sb16", .priority = MOD_sb16_prio, .init = &init_sb16, }; REGISTER_MODULE(&sb16_module); <file_sep>/******************************************************************************* * * Module Name: dbdisply - debug display commands * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "amlcode.h" #include "acdispat.h" #include "acnamesp.h" #include "acparser.h" #include "acinterp.h" #include "acevents.h" #include "acdebug.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbdisply") /* Local prototypes */ static void AcpiDbDumpParserDescriptor ( ACPI_PARSE_OBJECT *Op); static void * AcpiDbGetPointer ( void *Target); static ACPI_STATUS AcpiDbDisplayNonRootHandlers ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue); /* * System handler information. * Used for Handlers command, in AcpiDbDisplayHandlers. */ #define ACPI_PREDEFINED_PREFIX "%25s (%.2X) : " #define ACPI_HANDLER_NAME_STRING "%30s : " #define ACPI_HANDLER_PRESENT_STRING "%-9s (%p)\n" #define ACPI_HANDLER_PRESENT_STRING2 "%-9s (%p)" #define ACPI_HANDLER_NOT_PRESENT_STRING "%-9s\n" /* All predefined Address Space IDs */ static ACPI_ADR_SPACE_TYPE AcpiGbl_SpaceIdList[] = { ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_ADR_SPACE_SYSTEM_IO, ACPI_ADR_SPACE_PCI_CONFIG, ACPI_ADR_SPACE_EC, ACPI_ADR_SPACE_SMBUS, ACPI_ADR_SPACE_CMOS, ACPI_ADR_SPACE_PCI_BAR_TARGET, ACPI_ADR_SPACE_IPMI, ACPI_ADR_SPACE_GPIO, ACPI_ADR_SPACE_GSBUS, ACPI_ADR_SPACE_PLATFORM_COMM, ACPI_ADR_SPACE_PLATFORM_RT, ACPI_ADR_SPACE_DATA_TABLE, ACPI_ADR_SPACE_FIXED_HARDWARE }; /* Global handler information */ typedef struct acpi_handler_info { void *Handler; char *Name; } ACPI_HANDLER_INFO; static ACPI_HANDLER_INFO AcpiGbl_HandlerList[] = { {&AcpiGbl_GlobalNotify[0].Handler, "System Notifications"}, {&AcpiGbl_GlobalNotify[1].Handler, "Device Notifications"}, {&AcpiGbl_TableHandler, "ACPI Table Events"}, {&AcpiGbl_ExceptionHandler, "Control Method Exceptions"}, {&AcpiGbl_InterfaceHandler, "OSI Invocations"} }; /******************************************************************************* * * FUNCTION: AcpiDbGetPointer * * PARAMETERS: Target - Pointer to string to be converted * * RETURN: Converted pointer * * DESCRIPTION: Convert an ascii pointer value to a real value * ******************************************************************************/ static void * AcpiDbGetPointer ( void *Target) { void *ObjPtr; ACPI_SIZE Address; Address = strtoul (Target, NULL, 16); ObjPtr = ACPI_TO_POINTER (Address); return (ObjPtr); } /******************************************************************************* * * FUNCTION: AcpiDbDumpParserDescriptor * * PARAMETERS: Op - A parser Op descriptor * * RETURN: None * * DESCRIPTION: Display a formatted parser object * ******************************************************************************/ static void AcpiDbDumpParserDescriptor ( ACPI_PARSE_OBJECT *Op) { const ACPI_OPCODE_INFO *Info; Info = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); AcpiOsPrintf ("Parser Op Descriptor:\n"); AcpiOsPrintf ("%20.20s : %4.4X\n", "Opcode", Op->Common.AmlOpcode); ACPI_DEBUG_ONLY_MEMBERS (AcpiOsPrintf ("%20.20s : %s\n", "Opcode Name", Info->Name)); AcpiOsPrintf ("%20.20s : %p\n", "Value/ArgList", Op->Common.Value.Arg); AcpiOsPrintf ("%20.20s : %p\n", "Parent", Op->Common.Parent); AcpiOsPrintf ("%20.20s : %p\n", "NextOp", Op->Common.Next); } /******************************************************************************* * * FUNCTION: AcpiDbDecodeAndDisplayObject * * PARAMETERS: Target - String with object to be displayed. Names * and hex pointers are supported. * OutputType - Byte, Word, Dword, or Qword (B|W|D|Q) * * RETURN: None * * DESCRIPTION: Display a formatted ACPI object * ******************************************************************************/ void AcpiDbDecodeAndDisplayObject ( char *Target, char *OutputType) { void *ObjPtr; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *ObjDesc; UINT32 Display = DB_BYTE_DISPLAY; char Buffer[80]; ACPI_BUFFER RetBuf; ACPI_STATUS Status; UINT32 Size; if (!Target) { return; } /* Decode the output type */ if (OutputType) { AcpiUtStrupr (OutputType); if (OutputType[0] == 'W') { Display = DB_WORD_DISPLAY; } else if (OutputType[0] == 'D') { Display = DB_DWORD_DISPLAY; } else if (OutputType[0] == 'Q') { Display = DB_QWORD_DISPLAY; } } RetBuf.Length = sizeof (Buffer); RetBuf.Pointer = Buffer; /* Differentiate between a number and a name */ if ((Target[0] >= 0x30) && (Target[0] <= 0x39)) { ObjPtr = AcpiDbGetPointer (Target); if (!AcpiOsReadable (ObjPtr, 16)) { AcpiOsPrintf ( "Address %p is invalid in this address space\n", ObjPtr); return; } /* Decode the object type */ switch (ACPI_GET_DESCRIPTOR_TYPE (ObjPtr)) { case ACPI_DESC_TYPE_NAMED: /* This is a namespace Node */ if (!AcpiOsReadable (ObjPtr, sizeof (ACPI_NAMESPACE_NODE))) { AcpiOsPrintf ( "Cannot read entire Named object at address %p\n", ObjPtr); return; } Node = ObjPtr; goto DumpNode; case ACPI_DESC_TYPE_OPERAND: /* This is a ACPI OPERAND OBJECT */ if (!AcpiOsReadable (ObjPtr, sizeof (ACPI_OPERAND_OBJECT))) { AcpiOsPrintf ( "Cannot read entire ACPI object at address %p\n", ObjPtr); return; } AcpiUtDebugDumpBuffer (ObjPtr, sizeof (ACPI_OPERAND_OBJECT), Display, ACPI_UINT32_MAX); AcpiExDumpObjectDescriptor (ObjPtr, 1); break; case ACPI_DESC_TYPE_PARSER: /* This is a Parser Op object */ if (!AcpiOsReadable (ObjPtr, sizeof (ACPI_PARSE_OBJECT))) { AcpiOsPrintf ( "Cannot read entire Parser object at address %p\n", ObjPtr); return; } AcpiUtDebugDumpBuffer (ObjPtr, sizeof (ACPI_PARSE_OBJECT), Display, ACPI_UINT32_MAX); AcpiDbDumpParserDescriptor ((ACPI_PARSE_OBJECT *) ObjPtr); break; default: /* Is not a recognizable object */ AcpiOsPrintf ( "Not a known ACPI internal object, descriptor type %2.2X\n", ACPI_GET_DESCRIPTOR_TYPE (ObjPtr)); Size = 16; if (AcpiOsReadable (ObjPtr, 64)) { Size = 64; } /* Just dump some memory */ AcpiUtDebugDumpBuffer (ObjPtr, Size, Display, ACPI_UINT32_MAX); break; } return; } /* The parameter is a name string that must be resolved to a Named obj */ Node = AcpiDbLocalNsLookup (Target); if (!Node) { return; } DumpNode: /* Now dump the NS node */ Status = AcpiGetName (Node, ACPI_FULL_PATHNAME_NO_TRAILING, &RetBuf); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not convert name to pathname\n"); } else { AcpiOsPrintf ("Object %p: Namespace Node - Pathname: %s\n", Node, (char *) RetBuf.Pointer); } if (!AcpiOsReadable (Node, sizeof (ACPI_NAMESPACE_NODE))) { AcpiOsPrintf ("Invalid Named object at address %p\n", Node); return; } AcpiUtDebugDumpBuffer ((void *) Node, sizeof (ACPI_NAMESPACE_NODE), Display, ACPI_UINT32_MAX); AcpiExDumpNamespaceNode (Node, 1); ObjDesc = AcpiNsGetAttachedObject (Node); if (ObjDesc) { AcpiOsPrintf ("\nAttached Object %p:", ObjDesc); if (!AcpiOsReadable (ObjDesc, sizeof (ACPI_OPERAND_OBJECT))) { AcpiOsPrintf ("Invalid internal ACPI Object at address %p\n", ObjDesc); return; } if (ACPI_GET_DESCRIPTOR_TYPE ( ((ACPI_NAMESPACE_NODE *) ObjDesc)) == ACPI_DESC_TYPE_NAMED) { AcpiOsPrintf (" Namespace Node - "); Status = AcpiGetName ((ACPI_NAMESPACE_NODE *) ObjDesc, ACPI_FULL_PATHNAME_NO_TRAILING, &RetBuf); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not convert name to pathname\n"); } else { AcpiOsPrintf ("Pathname: %s", (char *) RetBuf.Pointer); } AcpiOsPrintf ("\n"); AcpiUtDebugDumpBuffer ((void *) ObjDesc, sizeof (ACPI_NAMESPACE_NODE), Display, ACPI_UINT32_MAX); } else { AcpiOsPrintf ("\n"); AcpiUtDebugDumpBuffer ((void *) ObjDesc, sizeof (ACPI_OPERAND_OBJECT), Display, ACPI_UINT32_MAX); } AcpiExDumpObjectDescriptor (ObjDesc, 1); } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayMethodInfo * * PARAMETERS: StartOp - Root of the control method parse tree * * RETURN: None * * DESCRIPTION: Display information about the current method * ******************************************************************************/ void AcpiDbDisplayMethodInfo ( ACPI_PARSE_OBJECT *StartOp) { ACPI_WALK_STATE *WalkState; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *RootOp; ACPI_PARSE_OBJECT *Op; const ACPI_OPCODE_INFO *OpInfo; UINT32 NumOps = 0; UINT32 NumOperands = 0; UINT32 NumOperators = 0; UINT32 NumRemainingOps = 0; UINT32 NumRemainingOperands = 0; UINT32 NumRemainingOperators = 0; BOOLEAN CountRemaining = FALSE; WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } ObjDesc = WalkState->MethodDesc; Node = WalkState->MethodNode; AcpiOsPrintf ("Currently executing control method is [%4.4s]\n", AcpiUtGetNodeName (Node)); AcpiOsPrintf ("%X Arguments, SyncLevel = %X\n", (UINT32) ObjDesc->Method.ParamCount, (UINT32) ObjDesc->Method.SyncLevel); RootOp = StartOp; while (RootOp->Common.Parent) { RootOp = RootOp->Common.Parent; } Op = RootOp; while (Op) { if (Op == StartOp) { CountRemaining = TRUE; } NumOps++; if (CountRemaining) { NumRemainingOps++; } /* Decode the opcode */ OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); switch (OpInfo->Class) { case AML_CLASS_ARGUMENT: if (CountRemaining) { NumRemainingOperands++; } NumOperands++; break; case AML_CLASS_UNKNOWN: /* Bad opcode or ASCII character */ continue; default: if (CountRemaining) { NumRemainingOperators++; } NumOperators++; break; } Op = AcpiPsGetDepthNext (StartOp, Op); } AcpiOsPrintf ( "Method contains: %X AML Opcodes - %X Operators, %X Operands\n", NumOps, NumOperators, NumOperands); AcpiOsPrintf ( "Remaining to execute: %X AML Opcodes - %X Operators, %X Operands\n", NumRemainingOps, NumRemainingOperators, NumRemainingOperands); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayLocals * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display all locals for the currently running control method * ******************************************************************************/ void AcpiDbDisplayLocals ( void) { ACPI_WALK_STATE *WalkState; WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } AcpiDbDecodeLocals (WalkState); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayArguments * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display all arguments for the currently running control method * ******************************************************************************/ void AcpiDbDisplayArguments ( void) { ACPI_WALK_STATE *WalkState; WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } AcpiDbDecodeArguments (WalkState); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayResults * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display current contents of a method result stack * ******************************************************************************/ void AcpiDbDisplayResults ( void) { UINT32 i; ACPI_WALK_STATE *WalkState; ACPI_OPERAND_OBJECT *ObjDesc; UINT32 ResultCount = 0; ACPI_NAMESPACE_NODE *Node; ACPI_GENERIC_STATE *Frame; UINT32 Index; /* Index onto current frame */ WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } Node = WalkState->MethodNode; if (WalkState->Results) { ResultCount = WalkState->ResultCount; } AcpiOsPrintf ("Method [%4.4s] has %X stacked result objects\n", AcpiUtGetNodeName (Node), ResultCount); /* From the top element of result stack */ Frame = WalkState->Results; Index = (ResultCount - 1) % ACPI_RESULTS_FRAME_OBJ_NUM; for (i = 0; i < ResultCount; i++) { ObjDesc = Frame->Results.ObjDesc[Index]; AcpiOsPrintf ("Result%u: ", i); AcpiDbDisplayInternalObject (ObjDesc, WalkState); if (Index == 0) { Frame = Frame->Results.Next; Index = ACPI_RESULTS_FRAME_OBJ_NUM; } Index--; } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayCallingTree * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display current calling tree of nested control methods * ******************************************************************************/ void AcpiDbDisplayCallingTree ( void) { ACPI_WALK_STATE *WalkState; ACPI_NAMESPACE_NODE *Node; WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } AcpiOsPrintf ("Current Control Method Call Tree\n"); while (WalkState) { Node = WalkState->MethodNode; AcpiOsPrintf (" [%4.4s]\n", AcpiUtGetNodeName (Node)); WalkState = WalkState->Next; } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayObjectType * * PARAMETERS: ObjectArg - User entered NS node handle * * RETURN: None * * DESCRIPTION: Display type of an arbitrary NS node * ******************************************************************************/ void AcpiDbDisplayObjectType ( char *ObjectArg) { ACPI_SIZE Arg; ACPI_HANDLE Handle; ACPI_DEVICE_INFO *Info; ACPI_STATUS Status; UINT32 i; Arg = strtoul (ObjectArg, NULL, 16); Handle = ACPI_TO_POINTER (Arg); Status = AcpiGetObjectInfo (Handle, &Info); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not get object info, %s\n", AcpiFormatException (Status)); return; } AcpiOsPrintf ("ADR: %8.8X%8.8X, Flags: %X\n", ACPI_FORMAT_UINT64 (Info->Address), Info->Flags); AcpiOsPrintf ("S1D-%2.2X S2D-%2.2X S3D-%2.2X S4D-%2.2X\n", Info->HighestDstates[0], Info->HighestDstates[1], Info->HighestDstates[2], Info->HighestDstates[3]); AcpiOsPrintf ("S0W-%2.2X S1W-%2.2X S2W-%2.2X S3W-%2.2X S4W-%2.2X\n", Info->LowestDstates[0], Info->LowestDstates[1], Info->LowestDstates[2], Info->LowestDstates[3], Info->LowestDstates[4]); if (Info->Valid & ACPI_VALID_HID) { AcpiOsPrintf ("HID: %s\n", Info->HardwareId.String); } if (Info->Valid & ACPI_VALID_UID) { AcpiOsPrintf ("UID: %s\n", Info->UniqueId.String); } if (Info->Valid & ACPI_VALID_CID) { for (i = 0; i < Info->CompatibleIdList.Count; i++) { AcpiOsPrintf ("CID %u: %s\n", i, Info->CompatibleIdList.Ids[i].String); } } ACPI_FREE (Info); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayResultObject * * PARAMETERS: ObjDesc - Object to be displayed * WalkState - Current walk state * * RETURN: None * * DESCRIPTION: Display the result of an AML opcode * * Note: Currently only displays the result object if we are single stepping. * However, this output may be useful in other contexts and could be enabled * to do so if needed. * ******************************************************************************/ void AcpiDbDisplayResultObject ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState) { #ifndef ACPI_APPLICATION if (AcpiGbl_DbThreadId != AcpiOsGetThreadId()) { return; } #endif /* Only display if single stepping */ if (!AcpiGbl_CmSingleStep) { return; } AcpiOsPrintf ("ResultObj: "); AcpiDbDisplayInternalObject (ObjDesc, WalkState); AcpiOsPrintf ("\n"); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayArgumentObject * * PARAMETERS: ObjDesc - Object to be displayed * WalkState - Current walk state * * RETURN: None * * DESCRIPTION: Display the result of an AML opcode * ******************************************************************************/ void AcpiDbDisplayArgumentObject ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_WALK_STATE *WalkState) { #ifndef ACPI_APPLICATION if (AcpiGbl_DbThreadId != AcpiOsGetThreadId()) { return; } #endif if (!AcpiGbl_CmSingleStep) { return; } AcpiOsPrintf ("ArgObj: "); AcpiDbDisplayInternalObject (ObjDesc, WalkState); } #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiDbDisplayGpes * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display the current GPE structures * ******************************************************************************/ void AcpiDbDisplayGpes ( void) { ACPI_GPE_BLOCK_INFO *GpeBlock; ACPI_GPE_XRUPT_INFO *GpeXruptInfo; ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_GPE_REGISTER_INFO *GpeRegisterInfo; char *GpeType; ACPI_GPE_NOTIFY_INFO *Notify; UINT32 GpeIndex; UINT32 Block = 0; UINT32 i; UINT32 j; UINT32 Count; char Buffer[80]; ACPI_BUFFER RetBuf; ACPI_STATUS Status; RetBuf.Length = sizeof (Buffer); RetBuf.Pointer = Buffer; Block = 0; /* Walk the GPE lists */ GpeXruptInfo = AcpiGbl_GpeXruptListHead; while (GpeXruptInfo) { GpeBlock = GpeXruptInfo->GpeBlockListHead; while (GpeBlock) { Status = AcpiGetName (GpeBlock->Node, ACPI_FULL_PATHNAME_NO_TRAILING, &RetBuf); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not convert name to pathname\n"); } if (GpeBlock->Node == AcpiGbl_FadtGpeDevice) { GpeType = "FADT-defined GPE block"; } else { GpeType = "GPE Block Device"; } AcpiOsPrintf ( "\nBlock %u - Info %p DeviceNode %p [%s] - %s\n", Block, GpeBlock, GpeBlock->Node, Buffer, GpeType); AcpiOsPrintf ( " Registers: %u (%u GPEs)\n", GpeBlock->RegisterCount, GpeBlock->GpeCount); AcpiOsPrintf ( " GPE range: 0x%X to 0x%X on interrupt %u\n", GpeBlock->BlockBaseNumber, GpeBlock->BlockBaseNumber + (GpeBlock->GpeCount - 1), GpeXruptInfo->InterruptNumber); AcpiOsPrintf ( " RegisterInfo: %p Status %8.8X%8.8X Enable %8.8X%8.8X\n", GpeBlock->RegisterInfo, ACPI_FORMAT_UINT64 ( GpeBlock->RegisterInfo->StatusAddress.Address), ACPI_FORMAT_UINT64 ( GpeBlock->RegisterInfo->EnableAddress.Address)); AcpiOsPrintf (" EventInfo: %p\n", GpeBlock->EventInfo); /* Examine each GPE Register within the block */ for (i = 0; i < GpeBlock->RegisterCount; i++) { GpeRegisterInfo = &GpeBlock->RegisterInfo[i]; AcpiOsPrintf ( " Reg %u: (GPE %.2X-%.2X) " "RunEnable %2.2X WakeEnable %2.2X" " Status %8.8X%8.8X Enable %8.8X%8.8X\n", i, GpeRegisterInfo->BaseGpeNumber, GpeRegisterInfo->BaseGpeNumber + (ACPI_GPE_REGISTER_WIDTH - 1), GpeRegisterInfo->EnableForRun, GpeRegisterInfo->EnableForWake, ACPI_FORMAT_UINT64 ( GpeRegisterInfo->StatusAddress.Address), ACPI_FORMAT_UINT64 ( GpeRegisterInfo->EnableAddress.Address)); /* Now look at the individual GPEs in this byte register */ for (j = 0; j < ACPI_GPE_REGISTER_WIDTH; j++) { GpeIndex = (i * ACPI_GPE_REGISTER_WIDTH) + j; GpeEventInfo = &GpeBlock->EventInfo[GpeIndex]; if (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags) == ACPI_GPE_DISPATCH_NONE) { /* This GPE is not used (no method or handler), ignore it */ continue; } AcpiOsPrintf ( " GPE %.2X: %p RunRefs %2.2X Flags %2.2X (", GpeBlock->BlockBaseNumber + GpeIndex, GpeEventInfo, GpeEventInfo->RuntimeCount, GpeEventInfo->Flags); /* Decode the flags byte */ if (GpeEventInfo->Flags & ACPI_GPE_LEVEL_TRIGGERED) { AcpiOsPrintf ("Level, "); } else { AcpiOsPrintf ("Edge, "); } if (GpeEventInfo->Flags & ACPI_GPE_CAN_WAKE) { AcpiOsPrintf ("CanWake, "); } else { AcpiOsPrintf ("RunOnly, "); } switch (ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags)) { case ACPI_GPE_DISPATCH_NONE: AcpiOsPrintf ("NotUsed"); break; case ACPI_GPE_DISPATCH_METHOD: AcpiOsPrintf ("Method"); break; case ACPI_GPE_DISPATCH_HANDLER: AcpiOsPrintf ("Handler"); break; case ACPI_GPE_DISPATCH_NOTIFY: Count = 0; Notify = GpeEventInfo->Dispatch.NotifyList; while (Notify) { Count++; Notify = Notify->Next; } AcpiOsPrintf ("Implicit Notify on %u devices", Count); break; case ACPI_GPE_DISPATCH_RAW_HANDLER: AcpiOsPrintf ("RawHandler"); break; default: AcpiOsPrintf ("UNKNOWN: %X", ACPI_GPE_DISPATCH_TYPE (GpeEventInfo->Flags)); break; } AcpiOsPrintf (")\n"); } } Block++; GpeBlock = GpeBlock->Next; } GpeXruptInfo = GpeXruptInfo->Next; } } #endif /* !ACPI_REDUCED_HARDWARE */ /******************************************************************************* * * FUNCTION: AcpiDbDisplayHandlers * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Display the currently installed global handlers * ******************************************************************************/ void AcpiDbDisplayHandlers ( void) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; ACPI_ADR_SPACE_TYPE SpaceId; UINT32 i; /* Operation region handlers */ AcpiOsPrintf ("\nOperation Region Handlers at the namespace root:\n"); ObjDesc = AcpiNsGetAttachedObject (AcpiGbl_RootNode); if (ObjDesc) { for (i = 0; i < ACPI_ARRAY_LENGTH (AcpiGbl_SpaceIdList); i++) { SpaceId = AcpiGbl_SpaceIdList[i]; AcpiOsPrintf (ACPI_PREDEFINED_PREFIX, AcpiUtGetRegionName ((UINT8) SpaceId), SpaceId); HandlerObj = AcpiEvFindRegionHandler ( SpaceId, ObjDesc->CommonNotify.Handler); if (HandlerObj) { AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING, (HandlerObj->AddressSpace.HandlerFlags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) ? "Default" : "User", HandlerObj->AddressSpace.Handler); goto FoundHandler; } /* There is no handler for this SpaceId */ AcpiOsPrintf ("None\n"); FoundHandler:; } /* Find all handlers for user-defined SpaceIDs */ HandlerObj = ObjDesc->CommonNotify.Handler; while (HandlerObj) { if (HandlerObj->AddressSpace.SpaceId >= ACPI_USER_REGION_BEGIN) { AcpiOsPrintf (ACPI_PREDEFINED_PREFIX, "User-defined ID", HandlerObj->AddressSpace.SpaceId); AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING, (HandlerObj->AddressSpace.HandlerFlags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) ? "Default" : "User", HandlerObj->AddressSpace.Handler); } HandlerObj = HandlerObj->AddressSpace.Next; } } #if (!ACPI_REDUCED_HARDWARE) /* Fixed event handlers */ AcpiOsPrintf ("\nFixed Event Handlers:\n"); for (i = 0; i < ACPI_NUM_FIXED_EVENTS; i++) { AcpiOsPrintf (ACPI_PREDEFINED_PREFIX, AcpiUtGetEventName (i), i); if (AcpiGbl_FixedEventHandlers[i].Handler) { AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING, "User", AcpiGbl_FixedEventHandlers[i].Handler); } else { AcpiOsPrintf (ACPI_HANDLER_NOT_PRESENT_STRING, "None"); } } #endif /* !ACPI_REDUCED_HARDWARE */ /* Miscellaneous global handlers */ AcpiOsPrintf ("\nMiscellaneous Global Handlers:\n"); for (i = 0; i < ACPI_ARRAY_LENGTH (AcpiGbl_HandlerList); i++) { AcpiOsPrintf (ACPI_HANDLER_NAME_STRING, AcpiGbl_HandlerList[i].Name); if (AcpiGbl_HandlerList[i].Handler) { AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING, "User", AcpiGbl_HandlerList[i].Handler); } else { AcpiOsPrintf (ACPI_HANDLER_NOT_PRESENT_STRING, "None"); } } /* Other handlers that are installed throughout the namespace */ AcpiOsPrintf ("\nOperation Region Handlers for specific devices:\n"); (void) AcpiWalkNamespace (ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, AcpiDbDisplayNonRootHandlers, NULL, NULL, NULL); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayNonRootHandlers * * PARAMETERS: ACPI_WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Display information about all handlers installed for a * device object. * ******************************************************************************/ static ACPI_STATUS AcpiDbDisplayNonRootHandlers ( ACPI_HANDLE ObjHandle, UINT32 NestingLevel, void *Context, void **ReturnValue) { ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjHandle); ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; char *Pathname; ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { return (AE_OK); } Pathname = AcpiNsGetNormalizedPathname (Node, TRUE); if (!Pathname) { return (AE_OK); } /* Display all handlers associated with this device */ HandlerObj = ObjDesc->CommonNotify.Handler; while (HandlerObj) { AcpiOsPrintf (ACPI_PREDEFINED_PREFIX, AcpiUtGetRegionName ((UINT8) HandlerObj->AddressSpace.SpaceId), HandlerObj->AddressSpace.SpaceId); AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING2, (HandlerObj->AddressSpace.HandlerFlags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) ? "Default" : "User", HandlerObj->AddressSpace.Handler); AcpiOsPrintf (" Device Name: %s (%p)\n", Pathname, Node); HandlerObj = HandlerObj->AddressSpace.Next; } ACPI_FREE (Pathname); return (AE_OK); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <iostream> #include <map> #include "vfs_test.h" using namespace std; struct tfs_entry { const char *name; vfs_entry_type type; const char *symlink; tfs_entry *parent; int ref_count; map<string, tfs_entry *> children; tfs_entry *set_parents() { for (auto &p : children) { p.second->parent = this; p.second->set_parents(); } return this; } void reset_refcounts() { for (auto &p : children) { p.second->ref_count = 0; p.second->reset_refcounts(); } } }; #define _NODE(n, t, s, ...) new tfs_entry{n, t, s, 0, 0, {__VA_ARGS__}} #define N_FILE(name) make_pair(name, _NODE(name, VFS_FILE, 0)) #define N_SYM(name, s) make_pair(name, _NODE(name, VFS_SYMLINK, s)) #define N_DIR(name, ...) make_pair(name, _NODE(name, VFS_DIR, 0, __VA_ARGS__)) #define ROOT_NODE(...) (_NODE("", VFS_DIR, 0, __VA_ARGS__))->set_parents() extern const struct fs_ops static_fsops_testfs; void test_fs_register_mp(tfs_entry *where, tfs_entry *target); void test_fs_clear_mps(); bool test_fs_is_mountpoint(tfs_entry *e); void test_fs_check_refcounts(tfs_entry *node); inline struct mnt_fs create_test_fs(const char *name, tfs_entry *root) { struct mnt_fs fs { .ref_count = 1, .pss_lock_root = nullptr, .fs_type_name = name, .device_id = 0, .flags = 0, .device_data = root, .fsops = &static_fsops_testfs, }; return fs; } inline tfs_entry * path(tfs_entry *e, initializer_list<const char *> comps) { for (auto comp_name : comps) { auto it = e->children.find(comp_name); if (it == e->children.end()) return nullptr; e = it->second; } return e; } <file_sep>#!/usr/bin/python3 BOARD_SIZE = 8 def under_attack(col, queens): left = right = col for r, c in reversed(queens): left, right = left - 1, right + 1 if c in (left, col, right): return True return False def solve(n): if n == 0: return [[]] smaller_solutions = solve(n - 1) return [solution+[(n,i+1)] for i in range(BOARD_SIZE) for solution in smaller_solutions if not under_attack(i+1, solution)] for answer in solve(BOARD_SIZE): print (answer) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static void ramfs_file_exlock(fs_handle h) { struct ramfs_handle *rh = h; rwlock_wp_exlock(&rh->inode->rwlock); } static void ramfs_file_exunlock(fs_handle h) { struct ramfs_handle *rh = h; rwlock_wp_exunlock(&rh->inode->rwlock); } static void ramfs_file_shlock(fs_handle h) { struct ramfs_handle *rh = h; rwlock_wp_shlock(&rh->inode->rwlock); } static void ramfs_file_shunlock(fs_handle h) { struct ramfs_handle *rh = h; rwlock_wp_shunlock(&rh->inode->rwlock); } static void ramfs_exlock(struct mnt_fs *fs) { struct ramfs_data *d = fs->device_data; rwlock_wp_exlock(&d->rwlock); } static void ramfs_exunlock(struct mnt_fs *fs) { struct ramfs_data *d = fs->device_data; rwlock_wp_exunlock(&d->rwlock); } static void ramfs_shlock(struct mnt_fs *fs) { struct ramfs_data *d = fs->device_data; rwlock_wp_shlock(&d->rwlock); } static void ramfs_shunlock(struct mnt_fs *fs) { struct ramfs_data *d = fs->device_data; rwlock_wp_shunlock(&d->rwlock); } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause CMAKE_VERSION_TO_DOWNLOAD="3.2.3" CMAKE_MIN_VERSION="3.2.0" function download_cmake_internal { show_work_on_component_msg "CMAKE" local ver1=$(get_version_comp $CMAKE_VERSION_TO_DOWNLOAD 1) local ver2=$(get_version_comp $CMAKE_VERSION_TO_DOWNLOAD 2) local ver3=$(get_version_comp $CMAKE_VERSION_TO_DOWNLOAD 3) local filename=cmake-${ver1}.${ver2}.${ver3}-Linux-x86_64 local tarname=$filename.tar.gz download_file_in_cache "https://cmake.org/files/v${ver1}.${ver2}" "$tarname" extract_cachefile_tar_gz $tarname $filename cmake CMAKE=$TC/host_$HOST_ARCH/cmake/bin/cmake } if [[ $HOST_ARCH == "i386" ]] || [[ $HOST_ARCH == "x86_64" ]]; then all_funcs_list+=(download_cmake) fi function download_cmake { pushd host_$HOST_ARCH if ! [ -d cmake ]; then if ! cmake --version &> /dev/null || [[ "$NO_SYS_CMAKE" == 1 ]]; then if [[ "$NO_SYS_CMAKE" == 1 ]] && which cmake &> /dev/null; then echo "Note: NO_SYS_CMAKE=1" fi if [[ "$HOST_ARCH" == "$BUILD_ARCH" ]]; then # Default case: we have to download CMake. download_cmake_internal else echo "ERROR: cmake >= 3.2 NOT FOUND on the system" echo "In this *unofficially* supported scenario where HOST_ARCH !=" echo " $BUILD_ARCH you have to manually install cmake on the system" exit 1 fi else # CMake is installed: let's check its version local ver=$(generic_get_version_str cmake) local major=$(get_version_comp $ver 1) local minor=$(get_version_comp $ver 2) local min_major=$(get_version_comp $CMAKE_MIN_VERSION 1) local min_minor=$(get_version_comp $CMAKE_MIN_VERSION 2) if [ $major -lt $min_major ]; then # The installed CMake is too old. download_cmake_internal elif [ $major -eq $min_major ] && [ $minor -lt $min_minor ]; then # The installed CMake is too old. download_cmake_internal else # The installed version is >= $CMAKE_MIN_VERSION. Using it. CMAKE=cmake echo "NOTE: Using system's CMake (version $major.$minor)" fi fi else show_skip_component_msg "CMAKE" fi popd } function download_cmake_installed_status { if [ -f $TC/host_$HOST_ARCH/cmake/bin/cmake ]; then echo "installed" elif cmake --version &> /dev/null; then echo "skipped" fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <gtest/gtest.h> #include "kernel_init_funcs.h" extern "C" { #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/process.h> #include <tilck/kernel/fs/fat32.h> #include <tilck/kernel/test/vfs.h> #include "kernel/fs/fs_int.h" } #define TEST_FATPART_FILE PROJ_BUILD_DIR "/test_fatpart" // Implemented in fat32_test.cpp const char *load_once_file(const char *filepath, size_t *fsize = nullptr); void test_dump_buf(char *buf, const char *buf_name, int off, int count); class vfs_test_base : public ::testing::Test { protected: void SetUp() override { init_kmalloc_for_tests(); } void TearDown() override { /* do nothing, for the moment */ } }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <gtest/gtest.h> extern "C" { #include <tilck/common/string_util.h> } TEST(strstr, basic) { const char *haystack = "haystack"; const char *needle = "needle"; const char *hay = "hay"; const char *empty = ""; ASSERT_STREQ(tilck_strstr(empty, needle), (char *) NULL); ASSERT_STREQ(tilck_strstr(haystack, needle), (char *) NULL); ASSERT_STREQ(tilck_strstr(haystack, hay), haystack); } TEST(strncpy, basic) { char dest[4] = {}; const char *src = "a"; tilck_strncpy(dest, src, 2); ASSERT_STREQ(dest, "a"); } TEST(strncat, basic) { char dest[6] = "abc"; const char *src = "d"; tilck_strncat(dest, src, 4); ASSERT_STREQ(dest, "abcd"); } TEST(isxdigit, basic) { ASSERT_EQ(tilck_isxdigit(48), true); ASSERT_EQ(tilck_isxdigit(58), false); ASSERT_EQ(tilck_isxdigit(71), false); ASSERT_EQ(tilck_isxdigit(127), false); ASSERT_EQ(tilck_isxdigit(128), false); } TEST(isspace, basic) { ASSERT_EQ(tilck_isspace(' '), true); ASSERT_EQ(tilck_isspace('\n'), true); ASSERT_EQ(tilck_isspace('a'), false); } TEST(str_reverse, basic) { char short_string[] = "abc"; char empty[] = ""; str_reverse(empty, 0); ASSERT_STREQ(empty, ""); str_reverse(short_string, 3); ASSERT_STREQ(short_string, "cba"); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once static bool kmalloc_debug_log; #if KMALLOC_SUPPORT_DEBUG_LOG #define DEBUG_COND (kmalloc_debug_log) #define DEBUG_printk(...) if (DEBUG_COND) printk(__VA_ARGS__) #else #define DEBUG_printk(...) if (0) printk(__VA_ARGS__) #endif void debug_kmalloc_start_log(void) { if (!KMALLOC_SUPPORT_DEBUG_LOG) panic("kmalloc debug logs funcs are NOT compiled in"); kmalloc_debug_log = true; } void debug_kmalloc_stop_log(void) { if (!KMALLOC_SUPPORT_DEBUG_LOG) panic("kmalloc debug logs funcs are NOT compiled in"); kmalloc_debug_log = false; } #define DEBUG_stop_coaleshe \ \ DEBUG_printk("STOP: unable to mark node #%i (size %zu) as free\n", \ n, curr_size); \ \ DEBUG_printk("node left: full: %i, split: %i\n", \ left.full, left.split); \ \ DEBUG_printk("node right: full: %i, split: %i\n", \ right.full, left.split) \ #define DEBUG_coaleshe \ DEBUG_printk("Marking node #%i (size: %zu) as free\n", n, curr_size) #define DEBUG_allocate_node1 \ DEBUG_printk("For node #%i, using alloc block (%i/%zu): %p (node #%u)\n",\ ptr_to_node(h, (void *)vaddr, node_size), i+1, \ alloc_block_count, TO_PTR(alloc_block_vaddr), alloc_node) \ #define DEBUG_allocate_node2 \ DEBUG_printk("Allocating block of pages..\n") #define DEBUG_allocate_node3 \ DEBUG_printk("Returning addr %p (%zu alloc blocks)\n", \ TO_PTR(vaddr), \ alloc_block_count) \ #define DEBUG_kmalloc_begin \ DEBUG_printk("kmalloc(%zu)...\n", *size) #define DEBUG_kmalloc_call_begin \ DEBUG_printk("Node #%i, node_size = %zu, vaddr = %p\n", \ node, node_size, node_to_ptr(h, node, node_size)) \ #define DEBUG_kmalloc_bad_end \ DEBUG_printk("kmalloc_bad_end: ptr: %p, node #%i, size: %zu\n", \ vaddr, node, size) \ #define DEBUG_kmalloc_end \ DEBUG_printk("kmalloc_end: ptr: %p, node #%i, size: %zu\n", \ vaddr, node, size) \ #define DEBUG_already_full \ DEBUG_printk("Already FULL, return NULL\n") #define DEBUG_already_split \ DEBUG_printk("Already split, return NULL\n") #define DEBUG_kmalloc_split \ DEBUG_printk("Splitting node #%u...\n", node) #define DEBUG_going_left \ DEBUG_printk("going to left..\n") #define DEBUG_left_failed \ DEBUG_printk("allocation on left node not possible, trying with right..\n") #define DEBUG_going_right \ DEBUG_printk("going on right..\n") #define DEBUG_right_failed \ DEBUG_printk("allocation on right node was not possible, return NULL.\n") #define DEBUG_free1 \ DEBUG_printk("kfree: ptr: %p, node #%i (size %zu)\n", ptr, node, size) #define DEBUG_free_after_coaleshe \ DEBUG_printk("After coaleshe, biggest_free_node #%i, " \ "biggest_free_size = %zu\n", \ biggest_free_node, biggest_free_size) \ #define DEBUG_free_alloc_block_count \ DEBUG_printk("The block node used up to %zu pages\n", alloc_block_count) #define DEBUG_check_alloc_block \ DEBUG_printk("Checking alloc block i = %i, pNode = %i, pAddr = %p, " \ "alloc = %i, free = %i, split = %i\n", \ i, alloc_node, TO_PTR(alloc_block_vaddr), \ nodes[alloc_node].allocated, \ !nodes[alloc_node].full, \ nodes[alloc_node].split) \ #define DEBUG_free_freeing_block \ DEBUG_printk("---> FREEING the ALLOC BLOCK!\n") #define DEBUG_free_skip_alloc_failed_block \ DEBUG_printk("---> SKIP alloc-failed ALLOC BLOCK!\n") <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/boot/common.h> #include <multiboot.h> /* * Static address of a single bios memory area struct: it must be in the lowest * 64 KB and must be hard-coded (because we don't know the memory map yet!). */ #define BIOS_MEM_AREA_BUF (16 * KB) struct mem_info; extern const struct bootloader_intf legacy_boot_intf; extern struct ModeInfoBlock *usable_vbe_mode_info_block; extern struct VbeInfoBlock *vbe_info_block; extern video_mode_t selected_mode; extern struct mem_info g_meminfo; extern ulong initrd_paddr; extern u32 initrd_size; extern ulong bp_paddr; extern u32 bp_size; extern ulong kernel_file_pa; extern u32 kernel_file_sz; multiboot_info_t * setup_multiboot_info(ulong ramdisk_paddr, ulong ramdisk_size); u32 rd_compact_clusters(void *ramdisk, u32 rd_size); bool load_fat_ramdisk(const char *load_str, u32 first_sec, ulong min_paddr, ulong *ref_rd_paddr, u32 *ref_rd_size, bool alloc_extra_page); bool load_kernel_file(const char *filepath); void alloc_mbi(void); char * legacy_boot_get_cmdline_buf(u32 *buf_sz); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static long sysfs_insert_remove_entry_cmp(const void *a, const void *b) { const struct sysfs_entry *e1 = a; const struct sysfs_entry *e2 = b; return strcmp(e1->name, e2->name); } static long sysfs_find_entry_cmp(const void *obj, const void *valptr) { const struct sysfs_entry *e = obj; const char *searched_str = valptr; return strcmp(e->name, searched_str); } static int sysfs_getdents(fs_handle h, get_dents_func_cb cb, void *arg) { struct sysfs_handle *sh = h; struct sysfs_inode *inode = sh->inode; int rc = 0; if (inode->type != VFS_DIR) return -ENOTDIR; list_for_each_ro_kp(sh->dir.dpos, &inode->dir.entries_list, lnode) { struct vfs_dent64 dent = { .ino = sh->dir.dpos->inode->ino, .type = sh->dir.dpos->inode->type, .name_len = sh->dir.dpos->name_len, .name = sh->dir.dpos->name, }; if ((rc = cb(&dent, arg))) break; } return rc; } static struct sysfs_entry * sysfs_dir_get_entry_by_name(struct sysfs_inode *idir, const char *name, ssize_t len) { char buf[SYSFS_ENTRY_MAX_LEN]; memcpy(buf, name, (size_t) len); buf[len] = 0; return bintree_find(idir->dir.entries_tree_root, buf, sysfs_find_entry_cmp, struct sysfs_entry, node); } static void sysfs_get_entry(struct mnt_fs *fs, void *dir_inode, const char *name, ssize_t name_len, struct fs_path *fs_path) { struct sysfs_data *d = fs->device_data; struct sysfs_inode *idir = dir_inode; struct sysfs_entry *e; if (!dir_inode) { *fs_path = (struct fs_path) { .inode = d->root, .dir_inode = d->root, .dir_entry = NULL, .type = VFS_DIR, }; return; } e = sysfs_dir_get_entry_by_name(idir, name, name_len); *fs_path = (struct fs_path) { .inode = e ? e->inode : NULL, .dir_inode = idir, .dir_entry = e, .type = e ? e->inode->type : VFS_NONE, }; } static int sysfs_dir_add_entry(struct sysfs_inode *idir, const char *iname, struct sysfs_inode *ie, struct sysfs_entry **entry_ref) { struct sysfs_entry *e; size_t enl = strlen(iname) + 1; bool success; ASSERT(idir->type == VFS_DIR); if (enl == 1) return -ENOENT; if (enl > sizeof(e->name)) return -ENAMETOOLONG; if (!(e = kalloc_obj(struct sysfs_entry))) return -ENOSPC; list_node_init(&e->lnode); bintree_node_init(&e->node); e->inode = ie; memcpy(e->name, iname, enl); if (e->name[enl-2] == '/') { e->name[enl-2] = 0; /* drop the trailing slash */ enl--; } e->name_len = (u8) enl; success = bintree_insert(&idir->dir.entries_tree_root, e, sysfs_insert_remove_entry_cmp, struct sysfs_entry, node); if (!success) { kfree_obj(e, struct sysfs_entry); return -EEXIST; } list_add_tail(&idir->dir.entries_list, &e->lnode); idir->dir.num_entries++; if (entry_ref) *entry_ref = e; return 0; } static void sysfs_dir_remove_entry(struct sysfs_inode *idir, struct sysfs_entry *e) { ASSERT(idir->type == VFS_DIR); bintree_remove(&idir->dir.entries_tree_root, e, sysfs_insert_remove_entry_cmp, struct sysfs_entry, node); list_remove(&e->lnode); idir->dir.num_entries--; kfree_obj(e, struct sysfs_entry); } <file_sep>/******************************************************************************* * * Module Name: dbinput - user front-end to the AML debugger * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acdebug.h" #ifdef ACPI_APPLICATION #include "acapps.h" #endif #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbinput") /* Local prototypes */ static UINT32 AcpiDbGetLine ( char *InputBuffer); static UINT32 AcpiDbMatchCommand ( char *UserCommand); static void AcpiDbDisplayCommandInfo ( const char *Command, BOOLEAN DisplayAll); static void AcpiDbDisplayHelp ( char *Command); static BOOLEAN AcpiDbMatchCommandHelp ( const char *Command, const ACPI_DB_COMMAND_HELP *Help); /* * Top-level debugger commands. * * This list of commands must match the string table below it */ enum AcpiExDebuggerCommands { CMD_NOT_FOUND = 0, CMD_NULL, CMD_ALLOCATIONS, CMD_ARGS, CMD_ARGUMENTS, CMD_BREAKPOINT, CMD_BUSINFO, CMD_CALL, CMD_DEBUG, CMD_DISASSEMBLE, CMD_DISASM, CMD_DUMP, CMD_EVALUATE, CMD_EXECUTE, CMD_EXIT, CMD_FIELDS, CMD_FIND, CMD_GO, CMD_HANDLERS, CMD_HELP, CMD_HELP2, CMD_HISTORY, CMD_HISTORY_EXE, CMD_HISTORY_LAST, CMD_INFORMATION, CMD_INTEGRITY, CMD_INTO, CMD_LEVEL, CMD_LIST, CMD_LOCALS, CMD_LOCKS, CMD_METHODS, CMD_NAMESPACE, CMD_NOTIFY, CMD_OBJECTS, CMD_OSI, CMD_OWNER, CMD_PATHS, CMD_PREDEFINED, CMD_PREFIX, CMD_QUIT, CMD_REFERENCES, CMD_RESOURCES, CMD_RESULTS, CMD_SET, CMD_STATS, CMD_STOP, CMD_TABLES, CMD_TEMPLATE, CMD_TRACE, CMD_TREE, CMD_TYPE, #ifdef ACPI_APPLICATION CMD_ENABLEACPI, CMD_EVENT, CMD_GPE, CMD_GPES, CMD_SCI, CMD_SLEEP, CMD_CLOSE, CMD_LOAD, CMD_OPEN, CMD_UNLOAD, CMD_TERMINATE, CMD_BACKGROUND, CMD_THREADS, CMD_TEST, #endif }; #define CMD_FIRST_VALID 2 /* Second parameter is the required argument count */ static const ACPI_DB_COMMAND_INFO AcpiGbl_DbCommands[] = { {"<NOT FOUND>", 0}, {"<NULL>", 0}, {"ALLOCATIONS", 0}, {"ARGS", 0}, {"ARGUMENTS", 0}, {"BREAKPOINT", 1}, {"BUSINFO", 0}, {"CALL", 0}, {"DEBUG", 1}, {"DISASSEMBLE", 1}, {"DISASM", 1}, {"DUMP", 1}, {"EVALUATE", 1}, {"EXECUTE", 1}, {"EXIT", 0}, {"FIELDS", 1}, {"FIND", 1}, {"GO", 0}, {"HANDLERS", 0}, {"HELP", 0}, {"?", 0}, {"HISTORY", 0}, {"!", 1}, {"!!", 0}, {"INFORMATION", 0}, {"INTEGRITY", 0}, {"INTO", 0}, {"LEVEL", 0}, {"LIST", 0}, {"LOCALS", 0}, {"LOCKS", 0}, {"METHODS", 0}, {"NAMESPACE", 0}, {"NOTIFY", 2}, {"OBJECTS", 0}, {"OSI", 0}, {"OWNER", 1}, {"PATHS", 0}, {"PREDEFINED", 0}, {"PREFIX", 0}, {"QUIT", 0}, {"REFERENCES", 1}, {"RESOURCES", 0}, {"RESULTS", 0}, {"SET", 3}, {"STATS", 1}, {"STOP", 0}, {"TABLES", 0}, {"TEMPLATE", 1}, {"TRACE", 1}, {"TREE", 0}, {"TYPE", 1}, #ifdef ACPI_APPLICATION {"ENABLEACPI", 0}, {"EVENT", 1}, {"GPE", 1}, {"GPES", 0}, {"SCI", 0}, {"SLEEP", 0}, {"CLOSE", 0}, {"LOAD", 1}, {"OPEN", 1}, {"UNLOAD", 1}, {"TERMINATE", 0}, {"BACKGROUND", 1}, {"THREADS", 3}, {"TEST", 1}, #endif {NULL, 0} }; /* * Help for all debugger commands. First argument is the number of lines * of help to output for the command. * * Note: Some commands are not supported by the kernel-level version of * the debugger. */ static const ACPI_DB_COMMAND_HELP AcpiGbl_DbCommandHelp[] = { {0, "\nNamespace Access:", "\n"}, {1, " Businfo", "Display system bus info\n"}, {1, " Disassemble <Method>", "Disassemble a control method\n"}, {1, " Find <AcpiName> (? is wildcard)", "Find ACPI name(s) with wildcards\n"}, {1, " Integrity", "Validate namespace integrity\n"}, {1, " Methods", "Display list of loaded control methods\n"}, {1, " Fields <AddressSpaceId>", "Display list of loaded field units by space ID\n"}, {1, " Namespace [Object] [Depth]", "Display loaded namespace tree/subtree\n"}, {1, " Notify <Object> <Value>", "Send a notification on Object\n"}, {1, " Objects [ObjectType]", "Display summary of all objects or just given type\n"}, {1, " Owner <OwnerId> [Depth]", "Display loaded namespace by object owner\n"}, {1, " Paths", "Display full pathnames of namespace objects\n"}, {1, " Predefined", "Check all predefined names\n"}, {1, " Prefix [<Namepath>]", "Set or Get current execution prefix\n"}, {1, " References <Addr>", "Find all references to object at addr\n"}, {1, " Resources [DeviceName]", "Display Device resources (no arg = all devices)\n"}, {1, " Set N <NamedObject> <Value>", "Set value for named integer\n"}, {1, " Template <Object>", "Format/dump a Buffer/ResourceTemplate\n"}, {1, " Type <Object>", "Display object type\n"}, {0, "\nControl Method Execution:", "\n"}, {1, " Evaluate <Namepath> [Arguments]", "Evaluate object or control method\n"}, {1, " Execute <Namepath> [Arguments]", "Synonym for Evaluate\n"}, #ifdef ACPI_APPLICATION {1, " Background <Namepath> [Arguments]", "Evaluate object/method in a separate thread\n"}, {1, " Thread <Threads><Loops><NamePath>", "Spawn threads to execute method(s)\n"}, #endif {1, " Debug <Namepath> [Arguments]", "Single-Step a control method\n"}, {7, " [Arguments] formats:", "Control method argument formats\n"}, {1, " Hex Integer", "Integer\n"}, {1, " \"Ascii String\"", "String\n"}, {1, " (Hex Byte List)", "Buffer\n"}, {1, " (01 42 7A BF)", "Buffer example (4 bytes)\n"}, {1, " [Package Element List]", "Package\n"}, {1, " [0x01 0x1234 \"string\"]", "Package example (3 elements)\n"}, {0, "\nMiscellaneous:", "\n"}, {1, " Allocations", "Display list of current memory allocations\n"}, {2, " Dump <Address>|<Namepath>", "\n"}, {0, " [Byte|Word|Dword|Qword]", "Display ACPI objects or memory\n"}, {1, " Handlers", "Info about global handlers\n"}, {1, " Help [Command]", "This help screen or individual command\n"}, {1, " History", "Display command history buffer\n"}, {1, " Level <DebugLevel>] [console]", "Get/Set debug level for file or console\n"}, {1, " Locks", "Current status of internal mutexes\n"}, {1, " Osi [Install|Remove <name>]", "Display or modify global _OSI list\n"}, {1, " Quit or Exit", "Exit this command\n"}, {8, " Stats <SubCommand>", "Display namespace and memory statistics\n"}, {1, " Allocations", "Display list of current memory allocations\n"}, {1, " Memory", "Dump internal memory lists\n"}, {1, " Misc", "Namespace search and mutex stats\n"}, {1, " Objects", "Summary of namespace objects\n"}, {1, " Sizes", "Sizes for each of the internal objects\n"}, {1, " Stack", "Display CPU stack usage\n"}, {1, " Tables", "Info about current ACPI table(s)\n"}, {1, " Tables", "Display info about loaded ACPI tables\n"}, #ifdef ACPI_APPLICATION {1, " Terminate", "Delete namespace and all internal objects\n"}, #endif {1, " ! <CommandNumber>", "Execute command from history buffer\n"}, {1, " !!", "Execute last command again\n"}, {0, "\nMethod and Namespace Debugging:", "\n"}, {5, " Trace <State> [<Namepath>] [Once]", "Trace control method execution\n"}, {1, " Enable", "Enable all messages\n"}, {1, " Disable", "Disable tracing\n"}, {1, " Method", "Enable method execution messages\n"}, {1, " Opcode", "Enable opcode execution messages\n"}, {3, " Test <TestName>", "Invoke a debug test\n"}, {1, " Objects", "Read/write/compare all namespace data objects\n"}, {1, " Predefined", "Validate all ACPI predefined names (_STA, etc.)\n"}, {1, " Execute predefined", "Execute all predefined (public) methods\n"}, {0, "\nControl Method Single-Step Execution:","\n"}, {1, " Arguments (or Args)", "Display method arguments\n"}, {1, " Breakpoint <AmlOffset>", "Set an AML execution breakpoint\n"}, {1, " Call", "Run to next control method invocation\n"}, {1, " Go", "Allow method to run to completion\n"}, {1, " Information", "Display info about the current method\n"}, {1, " Into", "Step into (not over) a method call\n"}, {1, " List [# of Aml Opcodes]", "Display method ASL statements\n"}, {1, " Locals", "Display method local variables\n"}, {1, " Results", "Display method result stack\n"}, {1, " Set <A|L> <#> <Value>", "Set method data (Arguments/Locals)\n"}, {1, " Stop", "Terminate control method\n"}, {1, " Tree", "Display control method calling tree\n"}, {1, " <Enter>", "Single step next AML opcode (over calls)\n"}, #ifdef ACPI_APPLICATION {0, "\nFile Operations:", "\n"}, {1, " Close", "Close debug output file\n"}, {1, " Load <Input Filename>", "Load ACPI table from a file\n"}, {1, " Open <Output Filename>", "Open a file for debug output\n"}, {1, " Unload <Namepath>", "Unload an ACPI table via namespace object\n"}, {0, "\nHardware Simulation:", "\n"}, {1, " EnableAcpi", "Enable ACPI (hardware) mode\n"}, {1, " Event <F|G> <Value>", "Generate AcpiEvent (Fixed/GPE)\n"}, {1, " Gpe <GpeNum> [GpeBlockDevice]", "Simulate a GPE\n"}, {1, " Gpes", "Display info on all GPE devices\n"}, {1, " Sci", "Generate an SCI\n"}, {1, " Sleep [SleepState]", "Simulate sleep/wake sequence(s) (0-5)\n"}, #endif {0, NULL, NULL} }; /******************************************************************************* * * FUNCTION: AcpiDbMatchCommandHelp * * PARAMETERS: Command - Command string to match * Help - Help table entry to attempt match * * RETURN: TRUE if command matched, FALSE otherwise * * DESCRIPTION: Attempt to match a command in the help table in order to * print help information for a single command. * ******************************************************************************/ static BOOLEAN AcpiDbMatchCommandHelp ( const char *Command, const ACPI_DB_COMMAND_HELP *Help) { char *Invocation = Help->Invocation; UINT32 LineCount; /* Valid commands in the help table begin with a couple of spaces */ if (*Invocation != ' ') { return (FALSE); } while (*Invocation == ' ') { Invocation++; } /* Match command name (full command or substring) */ while ((*Command) && (*Invocation) && (*Invocation != ' ')) { if (tolower ((int) *Command) != tolower ((int) *Invocation)) { return (FALSE); } Invocation++; Command++; } /* Print the appropriate number of help lines */ LineCount = Help->LineCount; while (LineCount) { AcpiOsPrintf ("%-38s : %s", Help->Invocation, Help->Description); Help++; LineCount--; } return (TRUE); } /******************************************************************************* * * FUNCTION: AcpiDbDisplayCommandInfo * * PARAMETERS: Command - Command string to match * DisplayAll - Display all matching commands, or just * the first one (substring match) * * RETURN: None * * DESCRIPTION: Display help information for a Debugger command. * ******************************************************************************/ static void AcpiDbDisplayCommandInfo ( const char *Command, BOOLEAN DisplayAll) { const ACPI_DB_COMMAND_HELP *Next; BOOLEAN Matched; Next = AcpiGbl_DbCommandHelp; while (Next->Invocation) { Matched = AcpiDbMatchCommandHelp (Command, Next); if (!DisplayAll && Matched) { return; } Next++; } } /******************************************************************************* * * FUNCTION: AcpiDbDisplayHelp * * PARAMETERS: Command - Optional command string to display help. * if not specified, all debugger command * help strings are displayed * * RETURN: None * * DESCRIPTION: Display help for a single debugger command, or all of them. * ******************************************************************************/ static void AcpiDbDisplayHelp ( char *Command) { const ACPI_DB_COMMAND_HELP *Next = AcpiGbl_DbCommandHelp; if (!Command) { /* No argument to help, display help for all commands */ AcpiOsPrintf ("\nSummary of AML Debugger Commands\n\n"); while (Next->Invocation) { AcpiOsPrintf ("%-38s%s", Next->Invocation, Next->Description); Next++; } AcpiOsPrintf ("\n"); } else { /* Display help for all commands that match the subtring */ AcpiDbDisplayCommandInfo (Command, TRUE); } } /******************************************************************************* * * FUNCTION: AcpiDbGetNextToken * * PARAMETERS: String - Command buffer * Next - Return value, end of next token * * RETURN: Pointer to the start of the next token. * * DESCRIPTION: Command line parsing. Get the next token on the command line * ******************************************************************************/ char * AcpiDbGetNextToken ( char *String, char **Next, ACPI_OBJECT_TYPE *ReturnType) { char *Start; UINT32 Depth; ACPI_OBJECT_TYPE Type = ACPI_TYPE_INTEGER; /* At end of buffer? */ if (!String || !(*String)) { return (NULL); } /* Remove any spaces at the beginning, ignore blank lines */ while (*String && isspace (*String)) { String++; } if (!(*String)) { return (NULL); } switch (*String) { case '"': /* This is a quoted string, scan until closing quote */ String++; Start = String; Type = ACPI_TYPE_STRING; /* Find end of string */ while (*String && (*String != '"')) { String++; } break; case '(': /* This is the start of a buffer, scan until closing paren */ String++; Start = String; Type = ACPI_TYPE_BUFFER; /* Find end of buffer */ while (*String && (*String != ')')) { String++; } break; case '{': /* This is the start of a field unit, scan until closing brace */ String++; Start = String; Type = ACPI_TYPE_FIELD_UNIT; /* Find end of buffer */ while (*String && (*String != '}')) { String++; } break; case '[': /* This is the start of a package, scan until closing bracket */ String++; Depth = 1; Start = String; Type = ACPI_TYPE_PACKAGE; /* Find end of package (closing bracket) */ while (*String) { /* Handle String package elements */ if (*String == '"') { /* Find end of string */ String++; while (*String && (*String != '"')) { String++; } if (!(*String)) { break; } } else if (*String == '[') { Depth++; /* A nested package declaration */ } else if (*String == ']') { Depth--; if (Depth == 0) /* Found final package closing bracket */ { break; } } String++; } break; default: Start = String; /* Find end of token */ while (*String && !isspace (*String)) { String++; } break; } if (!(*String)) { *Next = NULL; } else { *String = 0; *Next = String + 1; } *ReturnType = Type; return (Start); } /******************************************************************************* * * FUNCTION: AcpiDbGetLine * * PARAMETERS: InputBuffer - Command line buffer * * RETURN: Count of arguments to the command * * DESCRIPTION: Get the next command line from the user. Gets entire line * up to the next newline * ******************************************************************************/ static UINT32 AcpiDbGetLine ( char *InputBuffer) { UINT32 i; UINT32 Count; char *Next; char *This; if (AcpiUtSafeStrcpy (AcpiGbl_DbParsedBuf, sizeof (AcpiGbl_DbParsedBuf), InputBuffer)) { AcpiOsPrintf ( "Buffer overflow while parsing input line (max %u characters)\n", (UINT32) sizeof (AcpiGbl_DbParsedBuf)); return (0); } This = AcpiGbl_DbParsedBuf; for (i = 0; i < ACPI_DEBUGGER_MAX_ARGS; i++) { AcpiGbl_DbArgs[i] = AcpiDbGetNextToken (This, &Next, &AcpiGbl_DbArgTypes[i]); if (!AcpiGbl_DbArgs[i]) { break; } This = Next; } /* Uppercase the actual command */ AcpiUtStrupr (AcpiGbl_DbArgs[0]); Count = i; if (Count) { Count--; /* Number of args only */ } return (Count); } /******************************************************************************* * * FUNCTION: AcpiDbMatchCommand * * PARAMETERS: UserCommand - User command line * * RETURN: Index into command array, -1 if not found * * DESCRIPTION: Search command array for a command match * ******************************************************************************/ static UINT32 AcpiDbMatchCommand ( char *UserCommand) { UINT32 i; if (!UserCommand || UserCommand[0] == 0) { return (CMD_NULL); } for (i = CMD_FIRST_VALID; AcpiGbl_DbCommands[i].Name; i++) { if (strstr ( ACPI_CAST_PTR (char, AcpiGbl_DbCommands[i].Name), UserCommand) == AcpiGbl_DbCommands[i].Name) { return (i); } } /* Command not recognized */ return (CMD_NOT_FOUND); } /******************************************************************************* * * FUNCTION: AcpiDbCommandDispatch * * PARAMETERS: InputBuffer - Command line buffer * WalkState - Current walk * Op - Current (executing) parse op * * RETURN: Status * * DESCRIPTION: Command dispatcher. * ******************************************************************************/ ACPI_STATUS AcpiDbCommandDispatch ( char *InputBuffer, ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { UINT32 Temp; UINT64 Temp64; UINT32 CommandIndex; UINT32 ParamCount; char *CommandLine; ACPI_STATUS Status = AE_CTRL_TRUE; /* If AcpiTerminate has been called, terminate this thread */ if (AcpiGbl_DbTerminateLoop) { return (AE_CTRL_TERMINATE); } /* Find command and add to the history buffer */ ParamCount = AcpiDbGetLine (InputBuffer); CommandIndex = AcpiDbMatchCommand (AcpiGbl_DbArgs[0]); /* * We don't want to add the !! command to the history buffer. It * would cause an infinite loop because it would always be the * previous command. */ if (CommandIndex != CMD_HISTORY_LAST) { AcpiDbAddToHistory (InputBuffer); } /* Verify that we have the minimum number of params */ if (ParamCount < AcpiGbl_DbCommands[CommandIndex].MinArgs) { AcpiOsPrintf ("%u parameters entered, [%s] requires %u parameters\n", ParamCount, AcpiGbl_DbCommands[CommandIndex].Name, AcpiGbl_DbCommands[CommandIndex].MinArgs); AcpiDbDisplayCommandInfo ( AcpiGbl_DbCommands[CommandIndex].Name, FALSE); return (AE_CTRL_TRUE); } /* Decode and dispatch the command */ switch (CommandIndex) { case CMD_NULL: if (Op) { return (AE_OK); } break; case CMD_ALLOCATIONS: #ifdef ACPI_DBG_TRACK_ALLOCATIONS AcpiUtDumpAllocations ((UINT32) -1, NULL); #endif break; case CMD_ARGS: case CMD_ARGUMENTS: AcpiDbDisplayArguments (); break; case CMD_BREAKPOINT: AcpiDbSetMethodBreakpoint (AcpiGbl_DbArgs[1], WalkState, Op); break; case CMD_BUSINFO: AcpiDbGetBusInfo (); break; case CMD_CALL: AcpiDbSetMethodCallBreakpoint (Op); Status = AE_OK; break; case CMD_DEBUG: AcpiDbExecute (AcpiGbl_DbArgs[1], &AcpiGbl_DbArgs[2], &AcpiGbl_DbArgTypes[2], EX_SINGLE_STEP); break; case CMD_DISASSEMBLE: case CMD_DISASM: #ifdef ACPI_DISASSEMBLER (void) AcpiDbDisassembleMethod (AcpiGbl_DbArgs[1]); #else AcpiOsPrintf ("The AML Disassembler is not configured/present\n"); #endif break; case CMD_DUMP: AcpiDbDecodeAndDisplayObject (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_EVALUATE: case CMD_EXECUTE: AcpiDbExecute (AcpiGbl_DbArgs[1], &AcpiGbl_DbArgs[2], &AcpiGbl_DbArgTypes[2], EX_NO_SINGLE_STEP); break; case CMD_FIND: Status = AcpiDbFindNameInNamespace (AcpiGbl_DbArgs[1]); break; case CMD_FIELDS: Status = AcpiUtStrtoul64 (AcpiGbl_DbArgs[1], &Temp64); if (ACPI_FAILURE (Status) || Temp64 >= ACPI_NUM_PREDEFINED_REGIONS) { AcpiOsPrintf ( "Invalid address space ID: must be between 0 and %u inclusive\n", ACPI_NUM_PREDEFINED_REGIONS - 1); return (AE_OK); } Status = AcpiDbDisplayFields ((UINT32) Temp64); break; case CMD_GO: AcpiGbl_CmSingleStep = FALSE; return (AE_OK); case CMD_HANDLERS: AcpiDbDisplayHandlers (); break; case CMD_HELP: case CMD_HELP2: AcpiDbDisplayHelp (AcpiGbl_DbArgs[1]); break; case CMD_HISTORY: AcpiDbDisplayHistory (); break; case CMD_HISTORY_EXE: /* ! command */ CommandLine = AcpiDbGetFromHistory (AcpiGbl_DbArgs[1]); if (!CommandLine) { return (AE_CTRL_TRUE); } Status = AcpiDbCommandDispatch (CommandLine, WalkState, Op); return (Status); case CMD_HISTORY_LAST: /* !! command */ CommandLine = AcpiDbGetFromHistory (NULL); if (!CommandLine) { return (AE_CTRL_TRUE); } Status = AcpiDbCommandDispatch (CommandLine, WalkState, Op); return (Status); case CMD_INFORMATION: AcpiDbDisplayMethodInfo (Op); break; case CMD_INTEGRITY: AcpiDbCheckIntegrity (); break; case CMD_INTO: if (Op) { AcpiGbl_CmSingleStep = TRUE; return (AE_OK); } break; case CMD_LEVEL: if (ParamCount == 0) { AcpiOsPrintf ( "Current debug level for file output is: %8.8X\n", AcpiGbl_DbDebugLevel); AcpiOsPrintf ( "Current debug level for console output is: %8.8X\n", AcpiGbl_DbConsoleDebugLevel); } else if (ParamCount == 2) { Temp = AcpiGbl_DbConsoleDebugLevel; AcpiGbl_DbConsoleDebugLevel = strtoul (AcpiGbl_DbArgs[1], NULL, 16); AcpiOsPrintf ( "Debug Level for console output was %8.8X, now %8.8X\n", Temp, AcpiGbl_DbConsoleDebugLevel); } else { Temp = AcpiGbl_DbDebugLevel; AcpiGbl_DbDebugLevel = strtoul (AcpiGbl_DbArgs[1], NULL, 16); AcpiOsPrintf ( "Debug Level for file output was %8.8X, now %8.8X\n", Temp, AcpiGbl_DbDebugLevel); } break; case CMD_LIST: #ifdef ACPI_DISASSEMBLER AcpiDbDisassembleAml (AcpiGbl_DbArgs[1], Op); #else AcpiOsPrintf ("The AML Disassembler is not configured/present\n"); #endif break; case CMD_LOCKS: AcpiDbDisplayLocks (); break; case CMD_LOCALS: AcpiDbDisplayLocals (); break; case CMD_METHODS: Status = AcpiDbDisplayObjects ("METHOD", AcpiGbl_DbArgs[1]); break; case CMD_NAMESPACE: AcpiDbDumpNamespace (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_NOTIFY: Temp = strtoul (AcpiGbl_DbArgs[2], NULL, 0); AcpiDbSendNotify (AcpiGbl_DbArgs[1], Temp); break; case CMD_OBJECTS: AcpiUtStrupr (AcpiGbl_DbArgs[1]); Status = AcpiDbDisplayObjects (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_OSI: AcpiDbDisplayInterfaces (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_OWNER: AcpiDbDumpNamespaceByOwner (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_PATHS: AcpiDbDumpNamespacePaths (); break; case CMD_PREFIX: AcpiDbSetScope (AcpiGbl_DbArgs[1]); break; case CMD_REFERENCES: AcpiDbFindReferences (AcpiGbl_DbArgs[1]); break; case CMD_RESOURCES: AcpiDbDisplayResources (AcpiGbl_DbArgs[1]); break; case CMD_RESULTS: AcpiDbDisplayResults (); break; case CMD_SET: AcpiDbSetMethodData (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2], AcpiGbl_DbArgs[3]); break; case CMD_STATS: Status = AcpiDbDisplayStatistics (AcpiGbl_DbArgs[1]); break; case CMD_STOP: return (AE_NOT_IMPLEMENTED); case CMD_TABLES: AcpiDbDisplayTableInfo (AcpiGbl_DbArgs[1]); break; case CMD_TEMPLATE: AcpiDbDisplayTemplate (AcpiGbl_DbArgs[1]); break; case CMD_TRACE: AcpiDbTrace (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2], AcpiGbl_DbArgs[3]); break; case CMD_TREE: AcpiDbDisplayCallingTree (); break; case CMD_TYPE: AcpiDbDisplayObjectType (AcpiGbl_DbArgs[1]); break; #ifdef ACPI_APPLICATION /* Hardware simulation commands. */ case CMD_ENABLEACPI: #if (!ACPI_REDUCED_HARDWARE) Status = AcpiEnable(); if (ACPI_FAILURE(Status)) { AcpiOsPrintf("AcpiEnable failed (Status=%X)\n", Status); return (Status); } #endif /* !ACPI_REDUCED_HARDWARE */ break; case CMD_EVENT: AcpiOsPrintf ("Event command not implemented\n"); break; case CMD_GPE: AcpiDbGenerateGpe (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2]); break; case CMD_GPES: AcpiDbDisplayGpes (); break; case CMD_SCI: AcpiDbGenerateSci (); break; case CMD_SLEEP: Status = AcpiDbSleep (AcpiGbl_DbArgs[1]); break; /* File I/O commands. */ case CMD_CLOSE: AcpiDbCloseDebugFile (); break; case CMD_LOAD: { ACPI_NEW_TABLE_DESC *ListHead = NULL; Status = AcGetAllTablesFromFile (AcpiGbl_DbArgs[1], ACPI_GET_ALL_TABLES, &ListHead); if (ACPI_SUCCESS (Status)) { AcpiDbLoadTables (ListHead); } } break; case CMD_OPEN: AcpiDbOpenDebugFile (AcpiGbl_DbArgs[1]); break; /* User space commands. */ case CMD_TERMINATE: AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT); AcpiUtSubsystemShutdown (); /* * TBD: [Restructure] Need some way to re-initialize without * re-creating the semaphores! */ AcpiGbl_DbTerminateLoop = TRUE; /* AcpiInitialize (NULL); */ break; case CMD_BACKGROUND: AcpiDbCreateExecutionThread (AcpiGbl_DbArgs[1], &AcpiGbl_DbArgs[2], &AcpiGbl_DbArgTypes[2]); break; case CMD_THREADS: AcpiDbCreateExecutionThreads (AcpiGbl_DbArgs[1], AcpiGbl_DbArgs[2], AcpiGbl_DbArgs[3]); break; /* Debug test commands. */ case CMD_PREDEFINED: AcpiDbCheckPredefinedNames (); break; case CMD_TEST: AcpiDbExecuteTest (AcpiGbl_DbArgs[1]); break; case CMD_UNLOAD: AcpiDbUnloadAcpiTable (AcpiGbl_DbArgs[1]); break; #endif case CMD_EXIT: case CMD_QUIT: if (Op) { AcpiOsPrintf ("Method execution terminated\n"); return (AE_CTRL_TERMINATE); } if (!AcpiGbl_DbOutputToFile) { AcpiDbgLevel = ACPI_DEBUG_DEFAULT; } #ifdef ACPI_APPLICATION AcpiDbCloseDebugFile (); #endif AcpiGbl_DbTerminateLoop = TRUE; return (AE_CTRL_TERMINATE); case CMD_NOT_FOUND: default: AcpiOsPrintf ("%s: unknown command\n", AcpiGbl_DbArgs[0]); return (AE_CTRL_TRUE); } if (ACPI_SUCCESS (Status)) { Status = AE_CTRL_TRUE; } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbExecuteThread * * PARAMETERS: Context - Not used * * RETURN: None * * DESCRIPTION: Debugger execute thread. Waits for a command line, then * simply dispatches it. * ******************************************************************************/ void ACPI_SYSTEM_XFACE AcpiDbExecuteThread ( void *Context) { (void) AcpiDbUserCommands (); AcpiGbl_DbThreadsTerminated = TRUE; } /******************************************************************************* * * FUNCTION: AcpiDbUserCommands * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Command line execution for the AML debugger. Commands are * matched and dispatched here. * ******************************************************************************/ ACPI_STATUS AcpiDbUserCommands ( void) { ACPI_STATUS Status = AE_OK; AcpiOsPrintf ("\n"); /* TBD: [Restructure] Need a separate command line buffer for step mode */ while (!AcpiGbl_DbTerminateLoop) { /* Wait the readiness of the command */ Status = AcpiOsWaitCommandReady (); if (ACPI_FAILURE (Status)) { break; } /* Just call to the command line interpreter */ AcpiGbl_MethodExecuting = FALSE; AcpiGbl_StepToNextCall = FALSE; (void) AcpiDbCommandDispatch (AcpiGbl_DbLineBuf, NULL, NULL); /* Notify the completion of the command */ Status = AcpiOsNotifyCommandComplete (); if (ACPI_FAILURE (Status)) { break; } } if (ACPI_FAILURE (Status) && Status != AE_CTRL_TERMINATE) { ACPI_EXCEPTION ((AE_INFO, Status, "While parsing command line")); } return (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/boot/common.h> #include "defs.h" #include "utils.h" static void efi_boot_write_char(char c) { Print(L"%c", c); } static int efi_boot_read_key(void) { EFI_INPUT_KEY k = WaitForKeyPress(); return k.UnicodeChar & 0xff; } static bool efi_boot_get_mode_info(video_mode_t m, struct generic_video_mode_info *gi) { EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *mi = NULL; UINTN sizeof_info = 0; EFI_STATUS status; bzero(gi, sizeof(*gi)); status = gProt->QueryMode(gProt, m, &sizeof_info, &mi); if (EFI_ERROR(status)) return false; gi->xres = mi->HorizontalResolution; gi->yres = mi->VerticalResolution; gi->bpp = 0; gi->is_text_mode = false; gi->is_usable = false; if (mi->PixelFormat == PixelBlueGreenRedReserved8BitPerColor || mi->PixelFormat == PixelRedGreenBlueReserved8BitPerColor) { gi->bpp = 32; gi->is_usable = true; } return true; } static void efi_boot_clear_screen(void) { EFI_STATUS status; UINTN rows, cols; /* * Unfortunately, on some machines, the UEFI firmware doesn't do what we * expect when we call: * * ST->ConOut->ClearScreen(ST->ConOut); * * Instead, it resets the video mode back to its DEFAULT mode and only then * clears the screen. That's particularly bad for high-res displays where * when using the native resolution is the text is almost unreadable and, * in general, such behavior completely defeats the purpose of our nice * EarlySetDefaultResolution() function. * * Therefore, we're clear the screen in a different way. */ status = ST->ConOut->QueryMode(ST->ConOut, ST->ConOut->Mode->Mode, &cols, &rows); if (EFI_ERROR(status)) { Print(L"ERROR: unable to query the current text mode: %r\n", status); return; } status = ST->ConOut->SetCursorPosition(ST->ConOut, 0, 0); if (EFI_ERROR(status)) return; for (UINTN i = 0; i < (rows * cols); i += 30) ST->ConOut->OutputString(ST->ConOut, L" "); ST->ConOut->SetCursorPosition(ST->ConOut, 0, 0); } static video_mode_t efi_boot_get_curr_video_mode(void) { return gProt->Mode->Mode; } bool efi_boot_set_curr_video_mode(video_mode_t wanted_mode) { video_mode_t orig_mode = gProt->Mode->Mode; EFI_STATUS status = EFI_SUCCESS; if (wanted_mode != orig_mode) { efi_boot_clear_screen(); status = gProt->SetMode(gProt, wanted_mode); if (EFI_ERROR(status)) { gProt->SetMode(gProt, orig_mode); /* NOTE: do not handle failures */ efi_boot_clear_screen(); } } return status == EFI_SUCCESS; } static void efi_boot_get_all_video_modes(video_mode_t **modes, int *count) { *modes = NULL; *count = (int)gProt->Mode->MaxMode; } static bool efi_boot_load_kernel_file(const char *path, void **paddr) { static CHAR16 tmp_path[128]; EFI_PHYSICAL_ADDRESS kernel_file_paddr; const char *p = path; int i; for (i = 0; *p && i < ARRAY_SIZE(tmp_path); i++, p++) { tmp_path[i] = *p != '/' ? *p : '\\'; } if (i == ARRAY_SIZE(tmp_path)) { Print(L"File path too long\n"); return false; } tmp_path[i] = 0; if (EFI_ERROR(LoadKernelFile(tmp_path, &kernel_file_paddr))) return false; *paddr = TO_PTR(kernel_file_paddr); return true; } static void efi_boot_set_color(u8 color) { ST->ConOut->SetAttribute(ST->ConOut, color); } static bool efi_boot_load_initrd(void) { EFI_STATUS status; status = LoadRamdisk(gImageHandle, gLoadedImage, &gRamdiskPaddr, &gRamdiskSize); HANDLE_EFI_ERROR("LoadRamdisk failed"); end: return status == EFI_SUCCESS; } char *efi_boot_get_cmdline_buf(UINT32 *buf_sz) { EFI_PHYSICAL_ADDRESS buf = EFI_MBI_MAX_ADDR; EFI_STATUS status = EFI_SUCCESS; if (!gCmdlineBuf) { status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, &buf); if (EFI_ERROR(status)) { Print(L"ERROR: cannot allocate cmdline buffer\n"); return NULL; } gCmdlineBuf = TO_PTR(buf); BS->SetMem(gCmdlineBuf, CMDLINE_BUF_SZ, 0); } *buf_sz = CMDLINE_BUF_SZ; return gCmdlineBuf; } const struct bootloader_intf efi_boot_intf = { /* Methods */ .read_key = &efi_boot_read_key, .write_char = &efi_boot_write_char, .clear_screen = &efi_boot_clear_screen, .set_color = &efi_boot_set_color, .get_all_video_modes = &efi_boot_get_all_video_modes, .get_mode_info = &efi_boot_get_mode_info, .get_curr_video_mode = &efi_boot_get_curr_video_mode, .set_curr_video_mode = &efi_boot_set_curr_video_mode, .load_kernel_file = &efi_boot_load_kernel_file, .load_initrd = &efi_boot_load_initrd, .get_cmdline_buf = &efi_boot_get_cmdline_buf, /* Configuration values */ .text_mode = INVALID_VIDEO_MODE, .efi = true, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> NORETURN void assert_failed(const char *expr, const char *file, int line) { panic("ASSERTION '%s' FAILED in %s:%i\n", expr, file, line); } NORETURN void not_reached(const char *file, int line) { panic("NOT_REACHED in %s:%i\n", file, line); } NORETURN void not_implemented(const char *file, int line) { panic("NOT_IMPLEMENTED in %s:%i\n", file, line); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/user.h> #include <tilck/mods/tracing.h> STATIC bool save_param_buffer(void *data, long data_sz, char *dest_buf, size_t dest_bs) { if (data_sz == -1) { /* assume that `data` is a C string */ int rc = copy_str_from_user(dest_buf, data, dest_bs, NULL); if (rc < 0) { /* Reading from `data` caused a PAGE fault */ memcpy(dest_buf, "<fault>", 8); } else if (rc > 0) { /* * The user buffer is bigger than our reserved space: just truncate it. */ dest_buf[dest_bs - 1] = 0; } } else { ASSERT(data_sz >= 0); const size_t actual_sz = MIN((size_t)data_sz, dest_bs); if (copy_from_user(dest_buf, data, actual_sz)) memcpy(dest_buf, "<fault>", 8); } return true; } STATIC bool dump_param_buffer(ulong orig, char *data, long data_bs, long real_sz, char *dest, size_t dest_bs) { ASSERT(dest_bs > 8); if (!orig) { snprintk(dest, dest_bs, "NULL"); return true; } if (data_bs == -1) { /* assume that `data` is a C string */ data_bs = (long)strlen(data); } if (!tracing_are_dump_big_bufs_on() && real_sz > 0) real_sz = MIN(real_sz, 16); char minibuf[8]; char *s; char *data_end = data + (real_sz < 0 ? data_bs : MIN(real_sz, data_bs)); char *dest_end = dest + dest_bs; *dest++ = '\"'; for (s = data; s < data_end; s++) { char c = *s; long ml = 0; switch (c) { case '\n': snprintk(minibuf, sizeof(minibuf), "\\n"); break; case '\r': snprintk(minibuf, sizeof(minibuf), "\\r"); break; case '\"': snprintk(minibuf, sizeof(minibuf), "\\\""); break; case '\\': snprintk(minibuf, sizeof(minibuf), "\\\\"); break; default: if (isprint(c)) { minibuf[0] = c; minibuf[1] = 0; } else { snprintk(minibuf, sizeof(minibuf), "\\x%x", (u8)c); } } ml = (long)strlen(minibuf); if (dest_end - dest < ml - 1) { dest = dest_end; break; } memcpy(dest, minibuf, (size_t)ml); dest += ml; } if (dest >= dest_end - 4) { dest[-1] = 0; dest[-2] = '\"'; dest[-3] = '.'; dest[-4] = '.'; dest[-5] = '.'; } else { if (s == data_end && real_sz > 0 && data_bs < real_sz) { *dest++ = '.'; *dest++ = '.'; *dest++ = '.'; } *dest++ = '\"'; *dest = 0; } return true; } const struct sys_param_type ptype_buffer = { .name = "char *", .slot_size = 32, .ui_type = ui_type_string, .save = save_param_buffer, .dump = dump_param_buffer, .dump_from_val = NULL, }; const struct sys_param_type ptype_big_buf = { .name = "char *", .slot_size = 128, .ui_type = ui_type_string, .save = save_param_buffer, .dump = dump_param_buffer, .dump_from_val = NULL, }; const struct sys_param_type ptype_path = { .name = "char *", .slot_size = 64, .ui_type = ui_type_string, .save = save_param_buffer, .dump = dump_param_buffer, .dump_from_val = NULL, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/elf_types.h> #include <tilck/common/utils.h> #include <elf.h> /* * NOTE[1]: the code is in a source-header (.c.h) in order to avoid it to be * compiled and linked in binaries that don't need it, with the whole package * of C files in common/. * * NOTE[2]: this file uses Tilck's generic ELF types (Elf_Ehdr instead of * Elf_Ehdr32 etc.). In your code, you might need to define USE_ELF32 or * USE_ELF64 to work with ELF files having bitness different than your NBITS. */ static size_t elf_calc_mem_size(Elf_Ehdr *h) { Elf_Phdr *phdrs = (Elf_Phdr *)((char*)h + h->e_phoff); Elf_Addr min_pbegin = 0; Elf_Addr max_pend = 0; for (uint32_t i = 0; i < h->e_phnum; i++) { Elf_Phdr *p = phdrs + i; Elf_Addr pend = pow2_round_up_at(p->p_paddr + p->p_memsz, p->p_align); if (i == 0 || p->p_paddr < min_pbegin) min_pbegin = p->p_paddr; if (pend > max_pend) max_pend = pend; } return max_pend - min_pbegin; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include "common_int.h" int read_line(char *buf, int buf_sz) { int len = 0; int c; for (char *s = buf; *s; s++) { printk("%c", *s); len++; } while (true) { c = intf->read_key(); if (c == '\r' || c == '\n') { printk("\n"); break; } if (!isprint(c)) { if (c == '\b' && len > 0) { printk("\b \b"); len--; } continue; } if (len < buf_sz - 1) { printk("%c", c); buf[len++] = c; } } buf[len] = 0; return len; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/.. && pwd)" function no_ccmake_error { echo echo "ERROR: the ccmake tool has not been found on this system." echo "Install it on your system before re-running this command." echo "Hint: on Ubuntu/Debian systems, its package name is: cmake-curses-gui." echo echo "Important remarks" echo "----------------------" echo "The ccmake tool is not installed automatically by the build_toolchain" echo "script simply because it is not mandatory for building nor configuring" echo "Tilck. It is just a nicer curses GUI alternative to re-running the" echo "cmake_run script with the new options on the command line, like this: " echo echo " ./script/cmake_run -DTERM_BIG_SCROLL_BUF=1 -DKERNEL_SHOW_LOGO=0" echo } function no_build_dir_error { echo echo "ERROR: the build directory '$BUILD_DIR' does not exist." echo echo "Typical case" echo "----------------------" echo "The build directory does not exist because you haven't run yet the" echo "cmake_run script in project's root directory. Run it first." echo echo "Advanced case" echo "----------------------" echo "If you're trying to configure a build directory outside of project's" echo "root directory, run this script (TILCK_ROOT/scripts/run_config)" echo "by passing the build directory as argument." echo } function invalid_build_directory { echo echo "ERROR: the build directory '$BUILD_DIR' is NOT a valid CMake build" echo "ERROR: directory. Reason: it does not contain a CMakeCache.txt file." echo echo "Hint: run the cmake_run script first." echo } if which bash &> /dev/null; then # The "which" tool is installed, we can use it to check for `ccmake` if ! which ccmake &> /dev/null; then no_ccmake_error exit 1 fi else # No "which" tool. Try to determine if `ccmake` exists by calling it. if ! ccmake --help &> /dev/null; then no_ccmake_error exit 1 fi fi # OK, ccmake exists. if [ -z "$1" ]; then BUILD_DIR="$MAIN_DIR/build" else BUILD_DIR="$1" fi if ! [ -d "$BUILD_DIR" ]; then no_build_dir_error exit 1 fi # OK, also the BUILD_DIR exists. But is it a valid cmake directory? if ! [ -f "$BUILD_DIR/CMakeCache.txt" ]; then invalid_build_directory exit 1 fi # Yes, everything is correct. Now run ccmake. ccmake "$BUILD_DIR" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This whole file exists in order to allow non-bootloader/kernel code to use * the 'common' code. Since that common code (like fat32_base) uses ASSERT * and panic(), we need to have a common generic and weak panic implementation, * meant for traditional usermode code. */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #ifndef USERMODE_APP /* * NOTE: this case exists ONLY to make the file to compile! * The bootloaders and the kernel MUST have their custom panic() function. */ #include <tilck/common/printk.h> #define abort() while (1) #define printf printk #define vprintf vprintk #else #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #endif NORETURN WEAK void panic(const char *fmt, ...) { printf("\n********************* PANIC *********************\n"); va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); printf("\n"); abort(); } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause NCURSES_VER="6.1" all_funcs_list+=(build_ncurses) function build_ncurses { pushd $ARCH if ! [ -d ncurses ]; then show_work_on_component_msg "NCURSES" reset_cc_vars local ver="$NCURSES_VER" local tarname=ncurses-$ver.tar.gz local install_dir=$TC/$ARCH/ncurses/install download_file_in_cache "https://ftp.gnu.org/pub/gnu/ncurses" "$tarname" extract_cachefile_tar_gz $tarname ncurses-$ver ncurses mkdir -p $install_dir cd ncurses local o1="--host=${ARCH_SHORT}-pc-linux-gnu --prefix=$install_dir" local o2="--datarootdir=/usr/share --disable-db-install" local o4="--without-progs --without-cxx --without-cxx-binding" local o5="--without-ada --without-manpages --without-dlsym" if [[ "$HOST_ARCH" == "$ARCH" ]]; then export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" else set_cc_vars_to_tc fi run_command2 "./configure $o1 $o2 $o3 $o4 $o5" configure.log run_command2 "make -j$BUILD_PAR" build.log run_command2 "make install" install.log export CC_POST_FLAGS="" else show_skip_component_msg "NCURSES" fi popd } function build_ncurses_installed_status { if [ -d $TC/$ARCH/ncurses ]; then if [ -f $TC/$ARCH/ncurses/install/lib/libncurses.a ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_console.h> #include <tilck/common/color_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/common/string_util.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/term.h> #include <tilck/kernel/term_aux.h> #include <tilck/kernel/safe_ringbuf.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/cmdline.h> #include "video_term_int.h" struct vterm { bool initialized; bool cursor_enabled; bool using_alt_buffer; struct term_rb_data rb_data; u16 tabsize; /* term's current tab size */ u16 rows; /* term's rows count */ u16 cols; /* term's columns count */ u16 col_offset; u16 r; /* current row */ u16 c; /* current col */ const struct video_interface *vi; const struct video_interface *saved_vi; u16 *buffer; /* the whole screen buffer */ u16 *screen_buf_copy; /* when != NULL, contains one screenshot */ u32 scroll; /* != max_scroll only while scrolling */ u32 max_scroll; /* buffer rows used - rows. Its value is 0 until the screen scrolls for the first time */ u32 total_buffer_rows; /* >= term rows */ u32 extra_buffer_rows; /* => total_buffer_rows - rows. Always >= 0 */ u16 saved_cur_row; /* keeps primary buffer's cursor's row */ u16 saved_cur_col; /* keeps primary buffer's cursor's col */ u16 main_scroll_region_start; u16 main_scroll_region_end; u16 alt_scroll_region_start; u16 alt_scroll_region_end; u16 *start_scroll_region; u16 *end_scroll_region; bool *tabs_buf; bool *main_tabs_buf; bool *alt_tabs_buf; struct term_action actions_buf[32]; term_filter filter; void *filter_ctx; }; static struct vterm first_instance; static u16 failsafe_buffer[FAILSAFE_COLS * FAILSAFE_ROWS]; /* ------------ No-output video-interface ------------------ */ static void no_vi_set_char_at(u16 row, u16 col, u16 entry) { } static void no_vi_set_row(u16 row, u16 *data, bool fpu_allowed) { } static void no_vi_clear_row(u16 row_num, u8 color) { } static void no_vi_move_cursor(u16 row, u16 col, int color) { } static void no_vi_enable_cursor(void) { } static void no_vi_disable_cursor(void) { } static void no_vi_scroll_one_line_up(void) { } static void no_vi_redraw_static_elements(void) { } static void no_vi_disable_static_elems_refresh(void) { } static void no_vi_enable_static_elems_refresh(void) { } static const struct video_interface no_output_vi = { no_vi_set_char_at, no_vi_set_row, no_vi_clear_row, no_vi_move_cursor, no_vi_enable_cursor, no_vi_disable_cursor, no_vi_scroll_one_line_up, no_vi_redraw_static_elements, no_vi_disable_static_elems_refresh, no_vi_enable_static_elems_refresh }; /* --------------------------------------------------------- */ /* * Performance note: using macros instead of ALWAYS_INLINE funcs because, * despite the forced inlining, even with -O3, the compiler optimizes better * this code when macros are used instead of inline funcs. Better means * a smaller binary. * * Measurements * -------------- * * full debug build, -O0 -fno-inline-funcs EXCEPT the ALWAYS_INLINE ones * ----------------------------------------------------------------------- * * Before (inline funcs): * text data bss dec hex filename * 466397 34104 316082 816583 c75c7 ./build/tilck * * After (with macros): * text data bss dec hex filename * 465421 34104 316082 815607 c71f7 ./build/tilck * full optimization, -O3, no debug checks: * ------------------------------------------- * * Before (inline funcs): * * text data bss dec hex filename * 301608 29388 250610 581606 8dfe6 tilck * * After (with macros): * text data bss dec hex filename * 301288 29388 250610 581286 8dea6 tilck */ #define calc_buf_row(t, r) (((r) + (t)->scroll) % (t)->total_buffer_rows) #define get_buf_row(t, r) (&(t)->buffer[calc_buf_row((t), (r)) * (t)->cols]) #define buf_set_entry(t, r, c, e) (get_buf_row((t), (r))[(c)] = (e)) #define buf_get_entry(t, r, c) (get_buf_row((t), (r))[(c)]) #define buf_get_char_at(t, r, c) (vgaentry_get_char(buf_get_entry((t),(r),(c)))) static void buf_copy_row(struct vterm *t, u32 dest, u32 src) { if (UNLIKELY(dest == src)) return; memcpy(get_buf_row(t, dest), get_buf_row(t, src), t->cols * 2); } static ALWAYS_INLINE bool ts_is_at_bottom(struct vterm *t) { return t->scroll == t->max_scroll; } static ALWAYS_INLINE u8 get_curr_cell_color(struct vterm *t) { if (!t->buffer) return 0; return vgaentry_get_color(buf_get_entry(t, t->r, t->c)); } static ALWAYS_INLINE u8 get_curr_cell_fg_color(struct vterm *t) { if (!t->buffer) return 0; return vgaentry_get_fg(buf_get_entry(t, t->r, t->c)); } static void term_int_enable_cursor(struct vterm *t, bool val) { if (val == 0) { t->vi->disable_cursor(); t->cursor_enabled = false; } else { ASSERT(val == 1); t->vi->enable_cursor(); t->vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); t->cursor_enabled = true; } } static void term_redraw2(struct vterm *t, u16 s, u16 e) { const bool fpu_allowed = !in_irq() && !in_panic(); if (!t->buffer) return; if (fpu_allowed) fpu_context_begin(); for (u16 row = s; row < e; row++) t->vi->set_row(row, get_buf_row(t, row), fpu_allowed); if (fpu_allowed) fpu_context_end(); } static inline void term_redraw(struct vterm *t) { term_redraw2(t, 0, t->rows); } static inline void term_redraw_scroll_region(struct vterm *t) { term_redraw2(t, *t->start_scroll_region, *t->end_scroll_region + 1); } static void ts_set_scroll(struct vterm *t, u32 requested_scroll) { /* * 1. scroll cannot be > max_scroll * 2. scroll cannot be < max_scroll - extra_buffer_rows, where * extra_buffer_rows = total_buffer_rows - VIDEO_ROWS. * In other words, if for example total_buffer_rows is 26, and max_scroll * is 1000, scroll cannot be less than 1000 + 25 - 26 = 999, which means * exactly 1 scroll row (extra_buffer_rows == 1). */ const u32 min_scroll = t->max_scroll > t->extra_buffer_rows ? t->max_scroll - t->extra_buffer_rows : 0; requested_scroll = CLAMP(requested_scroll, min_scroll, t->max_scroll); if (requested_scroll == t->scroll) return; /* nothing to do */ t->scroll = requested_scroll; term_redraw(t); } static ALWAYS_INLINE void ts_scroll_up(struct vterm *t, u32 lines) { if (lines > t->scroll) ts_set_scroll(t, 0); else ts_set_scroll(t, t->scroll - lines); } static ALWAYS_INLINE void ts_scroll_down(struct vterm *t, u32 lines) { ts_set_scroll(t, t->scroll + lines); } static ALWAYS_INLINE void ts_scroll_to_bottom(struct vterm *t) { if (t->scroll != t->max_scroll) { ts_set_scroll(t, t->max_scroll); } } static void ts_buf_clear_row(struct vterm *t, u16 row, u8 color) { if (!t->buffer) return; memset16(get_buf_row(t, row), make_vgaentry(' ', color), t->cols); } static void ts_clear_row(struct vterm *t, u16 row, u8 color) { ts_buf_clear_row(t, row, color); t->vi->clear_row(row, color); } static void term_int_scroll_up(struct vterm *t, u32 lines) { ts_scroll_up(t, lines); if (t->cursor_enabled) { if (!ts_is_at_bottom(t)) { t->vi->disable_cursor(); } else { t->vi->enable_cursor(); t->vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); } } } static void term_int_scroll_down(struct vterm *t, u32 lines) { ts_scroll_down(t, lines); if (t->cursor_enabled) { if (ts_is_at_bottom(t)) { t->vi->enable_cursor(); t->vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); } } } static void term_internal_non_buf_scroll_up(struct vterm *t, u16 n) { const u16 sR = *t->start_scroll_region; const u16 eR = *t->end_scroll_region + 1; if (!t->buffer || !n) return; n = (u16)MIN(n, eR - sR); for (u32 row = sR; (int)row < eR - n; row++) buf_copy_row(t, row, row + n); for (u16 row = eR - n; row < eR; row++) ts_buf_clear_row(t, row, DEFAULT_COLOR16); term_redraw_scroll_region(t); } static void term_internal_non_buf_scroll_down(struct vterm *t, u16 n) { const u16 sR = *t->start_scroll_region; const u16 eR = *t->end_scroll_region + 1; if (!t->buffer || !n) return; n = (u16)MIN(n, t->rows); for (u32 row = eR - n; row > sR; row--) buf_copy_row(t, row - 1 + n, row - 1); for (u16 row = sR; row < n; row++) ts_buf_clear_row(t, row, DEFAULT_COLOR16); term_redraw_scroll_region(t); } static void term_int_move_cur(struct vterm *t, int row, int col) { if (!t->buffer) return; t->r = (u16) CLAMP(row, 0, t->rows - 1); t->c = (u16) CLAMP(col, 0, t->cols - 1); if (t->cursor_enabled) t->vi->move_cursor(t->r, t->c, get_curr_cell_fg_color(t)); } static void term_internal_incr_row(struct vterm *t) { const u16 sR = *t->start_scroll_region; const u16 eR = *t->end_scroll_region + 1; t->col_offset = 0; if (t->r < eR - 1) { ++t->r; return; } if (sR || eR < t->rows) { term_int_move_cur(t, t->r, 0); if (t->r == eR - 1) term_internal_non_buf_scroll_up(t, 1); else if (t->r < t->rows - 1) ++t->r; return; } t->max_scroll++; if (t->vi->scroll_one_line_up) { t->scroll++; t->vi->scroll_one_line_up(); } else { ts_set_scroll(t, t->max_scroll); } ts_clear_row(t, t->rows - 1, DEFAULT_COLOR16); } static void term_internal_write_printable_char(struct vterm *t, u8 c, u8 color) { const u16 entry = make_vgaentry(c, color); buf_set_entry(t, t->r, t->c, entry); t->vi->set_char_at(t->r, t->c, entry); t->c++; } static void term_internal_write_tab(struct vterm *t, u8 color) { int rem = t->cols - t->c - 1; if (!t->tabs_buf) { if (rem) term_internal_write_printable_char(t, ' ', color); return; } u32 tab_col = (u32) MIN(round_up_at(t->c+1, t->tabsize), (u32)t->cols-1) - 1; t->tabs_buf[t->r * t->cols + tab_col] = 1; t->c = (u16)(tab_col + 1); } static void term_internal_write_backspace(struct vterm *t, u8 color) { if (!t->c || t->c <= t->col_offset) return; const u16 space_entry = make_vgaentry(' ', color); t->c--; if (!t->tabs_buf || !t->tabs_buf[t->r * t->cols + t->c]) { buf_set_entry(t, t->r, t->c, space_entry); t->vi->set_char_at(t->r, t->c, space_entry); return; } /* we hit the end of a tab */ t->tabs_buf[t->r * t->cols + t->c] = 0; for (int i = t->tabsize - 1; i >= 0; i--) { if (!t->c || t->c == t->col_offset) break; if (t->tabs_buf[t->r * t->cols + t->c - 1]) break; /* we hit the previous tab */ if (buf_get_char_at(t, t->r, t->c - 1) != ' ') break; t->c--; } } static void term_internal_delete_last_word(struct vterm *t, u8 color) { u8 c; while (t->c > 0) { c = buf_get_char_at(t, t->r, t->c - 1); if (c != ' ') break; term_internal_write_backspace(t, color); } while (t->c > 0) { c = buf_get_char_at(t, t->r, t->c - 1); if (c == ' ') break; term_internal_write_backspace(t, color); } } static void term_internal_write_char2(struct vterm *t, char c, u8 color) { switch (c) { case '\n': term_internal_incr_row(t); break; case '\r': t->c = 0; break; case '\t': term_internal_write_tab(t, color); break; default: if (t->c == t->cols) { t->c = 0; term_internal_incr_row(t); } term_internal_write_printable_char(t, (u8)c, color); break; } } static int term_allocate_alt_buffers(struct vterm *t) { t->screen_buf_copy = kalloc_array_obj(u16, t->rows * t->cols); if (!t->screen_buf_copy) return -ENOMEM; if (!t->alt_tabs_buf) { t->alt_tabs_buf = kzmalloc(t->rows * t->cols); if (!t->alt_tabs_buf) { kfree_array_obj(t->screen_buf_copy, u16, t->rows * t->cols); t->screen_buf_copy = NULL; return -ENOMEM; } } return 0; } static void term_execute_action(struct vterm *t, struct term_action *a); #include "term_actions.c.h" #include "term_action_wrappers.c.h" #if DEBUG_CHECKS static void debug_term_dump_font_table(term *_t) { struct vterm *const t = _t; static const u8 hex_digits[] = "0123456789abcdef"; const u8 color = DEFAULT_COLOR16; term_internal_incr_row(t); t->c = 0; for (u32 i = 0; i < 6; i++) term_internal_write_printable_char(t, ' ', color); for (u32 i = 0; i < 16; i++) { term_internal_write_printable_char(t, hex_digits[i], color); term_internal_write_printable_char(t, ' ', color); } term_internal_incr_row(t); term_internal_incr_row(t); t->c = 0; for (u8 i = 0; i < 16; i++) { term_internal_write_printable_char(t, '0', color); term_internal_write_printable_char(t, 'x', color); term_internal_write_printable_char(t, hex_digits[i], color); for (u8 j = 0; j < 3; j++) term_internal_write_printable_char(t, ' ', color); for (u8 j = 0; j < 16; j++) { u8 c = i * 16 + j; term_internal_write_printable_char(t, c, color); term_internal_write_printable_char(t, ' ', color); } term_internal_incr_row(t); t->c = 0; } term_internal_incr_row(t); t->c = 0; } #endif static term * alloc_term_struct(void) { return kzalloc_obj(struct vterm); } static void free_term_struct(term *_t) { struct vterm *const t = _t; ASSERT(t != &first_instance); kfree_obj(t, struct vterm); } static void dispose_term(term *_t) { struct vterm *const t = _t; ASSERT(t != &first_instance); dispose_term_rb_data(&t->rb_data); if (t->buffer) { kfree_array_obj(t->buffer, u16, t->total_buffer_rows * t->cols); t->buffer = NULL; } if (t->main_tabs_buf) { kfree2(t->main_tabs_buf, t->cols * t->rows); t->main_tabs_buf = NULL; } if (t->alt_tabs_buf) { kfree2(t->alt_tabs_buf, t->cols * t->rows); t->alt_tabs_buf = NULL; } if (t->screen_buf_copy) { kfree_array_obj(t->screen_buf_copy, u16, t->rows * t->cols); t->screen_buf_copy = NULL; } } static void vterm_get_params(term *_t, struct term_params *out) { struct vterm *const t = _t; *out = (struct term_params) { .rows = t->rows, .cols = t->cols, .type = term_type_video, .vi = t->vi, }; } /* * Calculate an optimal number of extra buffer rows to use for a term of size * `rows` x `cols`, in order to minimize the memory waste (happening when the * buffer size is not a power of 2). */ static u32 term_calc_extra_buf_rows(u16 rows, u16 cols) { u32 buf_size = 0; if (cols <= 80) buf_size = 32 * KB; else if (cols <= 100) buf_size = 64 * KB; else if (cols <= 128) buf_size = 128 * KB; else buf_size = 256 * KB; if (kopt_big_scroll_buf) buf_size *= 4; return (buf_size / 2) / cols - rows; } static int init_vterm(term *_t, const struct video_interface *intf, u16 rows, u16 cols, int rows_buf) { struct vterm *const t = _t; ASSERT(t != &first_instance || !are_interrupts_enabled()); t->tabsize = 8; if (intf) { t->cols = cols; t->rows = rows; t->saved_vi = intf; t->vi = (t == &first_instance) ? intf : &no_output_vi; } else { t->cols = 80; t->rows = 25; t->saved_vi = &no_output_vi; t->vi = &no_output_vi; } t->main_scroll_region_start = t->alt_scroll_region_start = 0; t->main_scroll_region_end = t->alt_scroll_region_end = t->rows - 1; t->start_scroll_region = &t->main_scroll_region_start; t->end_scroll_region = &t->main_scroll_region_end; init_term_rb_data(&t->rb_data, ARRAY_SIZE(t->actions_buf), sizeof(struct term_action), t->actions_buf); if (!in_panic() && intf) { t->extra_buffer_rows = rows_buf >= 0 ? (u32)rows_buf : term_calc_extra_buf_rows(rows, cols); t->total_buffer_rows = t->rows + t->extra_buffer_rows; if (is_kmalloc_initialized()) t->buffer = kmalloc(2 * t->total_buffer_rows * t->cols); } if (t->buffer) { t->main_tabs_buf = kzmalloc(t->cols * t->rows); if (t->main_tabs_buf) { t->tabs_buf = t->main_tabs_buf; } else { if (t != &first_instance) { kfree2(t->buffer, 2 * t->total_buffer_rows * t->cols); return -ENOMEM; } printk("WARNING: unable to allocate main_tabs_buf\n"); } } else { /* We're in panic or we were unable to allocate the buffer */ if (t != &first_instance) return -ENOMEM; t->cols = (u16) MIN((u16)FAILSAFE_COLS, t->cols); t->rows = (u16) MIN((u16)FAILSAFE_ROWS, t->rows); t->extra_buffer_rows = 0; t->total_buffer_rows = t->rows; t->buffer = failsafe_buffer; if (!in_panic() && intf) printk("ERROR: unable to allocate the term buffer.\n"); } for (u16 i = 0; i < t->rows; i++) ts_clear_row(t, i, DEFAULT_COLOR16); t->cursor_enabled = true; t->vi->enable_cursor(); term_int_move_cur(t, 0, 0); t->initialized = true; printk("video_term: buffer rows: %u (%u screens)\n", t->total_buffer_rows, t->total_buffer_rows / t->rows); return 0; } static term *vterm_get_first_inst(void) { return &first_instance; } static enum term_type vterm_get_type(void) { return term_type_video; } static const struct term_interface intf = { .get_type = vterm_get_type, .is_initialized = vterm_is_initialized, .get_params = vterm_get_params, .write = vterm_write, .scroll_up = vterm_scroll_up, .scroll_down = vterm_scroll_down, .set_col_offset = vterm_set_col_offset, .pause_output = vterm_pause_output, .restart_output = vterm_restart_output, .set_filter = vterm_set_filter, .get_first_term = vterm_get_first_inst, .video_term_init = init_vterm, .serial_term_init = NULL, .alloc = alloc_term_struct, .free = free_term_struct, .dispose = dispose_term, #if DEBUG_CHECKS .debug_dump_font_table = debug_term_dump_font_table, #endif }; __attribute__((constructor)) static void register_term(void) { register_term_intf(&intf); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/utils.h> #include <tilck/kernel/process.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/sys_types.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/interrupts.h> #include <tilck/mods/tracing.h> typedef void (*action_type)(struct task *, int signum, int fl); static void __add_sig(ulong *set, int signum) { ASSERT(signum > 0); signum--; int slot = signum / NBITS; int index = signum % NBITS; if (slot >= K_SIGACTION_MASK_WORDS) return; /* just silently ignore signals that we don't support */ set[slot] |= (1 << index); } static void add_pending_sig(struct task *ti, int signum, int fl) { __add_sig(ti->sa_pending, signum); if (fl & SIG_FL_FAULT) __add_sig(ti->sa_fault_pending, signum); } static void __del_sig(ulong *set, int signum) { ASSERT(signum > 0); signum--; int slot = signum / NBITS; int index = signum % NBITS; if (slot >= K_SIGACTION_MASK_WORDS) return; /* just silently ignore signals that we don't support */ set[slot] &= ~(1 << index); } static void del_pending_sig(struct task *ti, int signum) { __del_sig(ti->sa_pending, signum); __del_sig(ti->sa_fault_pending, signum); } static bool __is_sig_set(ulong *set, int signum) { ASSERT(signum > 0); signum--; int slot = signum / NBITS; int index = signum % NBITS; if (slot >= K_SIGACTION_MASK_WORDS) return false; /* just silently ignore signals that we don't support */ return !!(set[slot] & (1 << index)); } static bool is_pending_sig(struct task *ti, int signum) { return __is_sig_set(ti->sa_pending, signum); } static bool is_sig_masked(struct task *ti, int signum) { return __is_sig_set(ti->sa_mask, signum); } static int get_first_pending_sig(struct task *ti, enum sig_state sig_state) { for (u32 i = 0; i < K_SIGACTION_MASK_WORDS; i++) { ulong val = ti->sa_pending[i]; if (val != 0) { u32 idx = get_first_set_bit_index_l(val); int signum = (int)(i * NBITS + idx + 1); if (!is_sig_masked(ti, signum)) return signum; } } return -1; } void drop_all_pending_signals(void *__curr) { ASSERT(!is_preemption_enabled()); struct task *ti = __curr; for (u32 i = 0; i < K_SIGACTION_MASK_WORDS; i++) { ti->sa_pending[i] = 0; ti->sa_fault_pending[i] = 0; } } void reset_all_custom_signal_handlers(void *__curr) { ASSERT(!is_preemption_enabled()); struct task *ti = __curr; struct process *pi = ti->pi; for (u32 i = 1; i < _NSIG; i++) { if (pi->sa_handlers[i-1] != SIG_DFL && pi->sa_handlers[i-1] != SIG_IGN) pi->sa_handlers[i-1] = SIG_DFL; } } static void kill_task_now_or_later(struct task *ti, void *regs, int signum, enum sig_state sig_state) { if (ti == get_curr_task()) { /* We can terminate the task immediately */ enable_preemption(); terminate_process(0, signum); NOT_REACHED(); } else { /* We have to setup a trampoline to any syscall */ setup_pause_trampoline(regs); } } bool process_signals(void *__ti, enum sig_state sig_state, void *regs) { ASSERT(!is_preemption_enabled()); struct task *ti = __ti; int sig; ASSERT(ti == get_curr_task() || sig_state == sig_in_usermode); /* Unmask the pending signals caused by HW faults */ for (u32 i = 0; i < K_SIGACTION_MASK_WORDS; i++) { ti->sa_mask[i] &= ~ti->sa_fault_pending[i]; } if (is_pending_sig(ti, SIGKILL)) { /* * SIGKILL will always have absolute priority over anything else: no * matter if there are other pending signals or we're already running * a custom signal handler. */ kill_task_now_or_later(ti, regs, SIGKILL, sig_state); return true; } if (ti->nested_sig_handlers > 0 && sig_state != sig_in_return) { /* * For the moment, in Tilck only signal handlers (even of different types) * will not be able to interrupt each other. This is the equivalent of * having each sigaction's sa_mask = 0xffffffff[...]. */ return false; } sig = get_first_pending_sig(ti, sig_state); if (sig < 0) return false; trace_signal_delivered(ti->tid, sig); __sighandler_t handler = ti->pi->sa_handlers[sig - 1]; if (handler) { trace_printk(10, "Setup signal handler %p for TID %d for signal %s[%d]", handler, ti->tid, get_signal_name(sig), sig); del_pending_sig(ti, sig); if (setup_sig_handler(ti, sig_state, regs, (ulong)handler, sig) < 0) { /* We got a FAULT while trying to setup the user stack */ printk("WARNING: can't setup stack for task %d: kill\n", ti->tid); kill_task_now_or_later(ti, regs, SIGKILL, sig_state); } } else { /* * If we got here, there is no registered custom handler for the signal, * the signal has not been ignored explicitly and the default action for * the signal is terminate. */ kill_task_now_or_later(ti, regs, sig, sig_state); } return true; } static void signal_wakeup_task(struct task *ti) { if (!ti->vfork_stopped) { if (ti->state == TASK_STATE_SLEEPING) { /* * We must NOT wake up tasks waiting on a mutex or on a semaphore: * supporting spurious wake-ups there, is just a waste of resources. * On the contrary, if a task is waiting on a condition or sleeping * in kernel_sleep(), we HAVE to wake it up. */ if (ti->wobj.type != WOBJ_KMUTEX && ti->wobj.type != WOBJ_SEM) wake_up(ti); } ti->stopped = false; } else { /* * The task is vfork_stopped: we cannot make it runnable, nor kill it * right now. Just registering the signal as pending is enough. As soon * as the process wakes up, the killing signal will be delivered. * Supporting the killing a of vforked process (while its child is still * alive and has not called execve()) is just too tricky. * * TODO: consider supporting killing of vforked process. */ } } static void action_terminate(struct task *ti, int signum, int fl) { ASSERT(!is_preemption_enabled()); ASSERT(!is_kernel_thread(ti)); add_pending_sig(ti, signum, fl); if (!is_sig_masked(ti, signum)) { signal_wakeup_task(ti); } } static void action_ignore(struct task *ti, int signum, int fl) { if (ti->tid == 1 && signum != SIGCHLD) { printk( "WARNING: ignoring signal %s[%d] sent to init (pid 1)\n", get_signal_name(signum), signum ); } } static void action_stop(struct task *ti, int signum, int fl) { ASSERT(!is_kernel_thread(ti)); trace_signal_delivered(ti->tid, signum); ti->stopped = true; ti->wstatus = STOPCODE(signum); wake_up_tasks_waiting_on(ti, task_stopped); if (ti == get_curr_task()) schedule_preempt_disabled(); } static void action_continue(struct task *ti, int signum, int fl) { ASSERT(!is_kernel_thread(ti)); if (ti->vfork_stopped) return; trace_signal_delivered(ti->tid, signum); ti->stopped = false; ti->wstatus = CONTINUED; wake_up_tasks_waiting_on(ti, task_continued); } static const action_type signal_default_actions[_NSIG] = { [SIGHUP] = action_terminate, [SIGINT] = action_terminate, [SIGQUIT] = action_terminate, [SIGILL] = action_terminate, [SIGABRT] = action_terminate, [SIGFPE] = action_terminate, [SIGKILL] = action_terminate, [SIGSEGV] = action_terminate, [SIGPIPE] = action_terminate, [SIGALRM] = action_terminate, [SIGTERM] = action_terminate, [SIGUSR1] = action_terminate, [SIGUSR2] = action_terminate, [SIGCHLD] = action_ignore, [SIGCONT] = action_continue, [SIGSTOP] = action_stop, [SIGTSTP] = action_stop, [SIGTTIN] = action_stop, [SIGTTOU] = action_stop, [SIGBUS] = action_terminate, [SIGPOLL] = action_terminate, [SIGPROF] = action_terminate, [SIGSYS] = action_terminate, [SIGTRAP] = action_terminate, [SIGURG] = action_ignore, [SIGVTALRM] = action_terminate, [SIGXCPU] = action_terminate, [SIGXFSZ] = action_terminate, [SIGWINCH] = action_terminate, }; static void do_send_signal(struct task *ti, int signum, int fl) { ASSERT(IN_RANGE(signum, 0, _NSIG)); if (signum == 0) { /* * Do nothing, but don't treat it as an error. * * From kill(2): * If sig is 0, then no signal is sent, but error checking is still * performed; this can be used to check for the existence of a * process ID or process group ID. */ return; } if (signum >= _NSIG) return; /* ignore unknown and unsupported signal */ if (ti->nested_sig_handlers < 0) return; /* the task is dying, no signals allowed */ __sighandler_t h = ti->pi->sa_handlers[signum - 1]; if (ti->tid == 1 && h == SIG_DFL) { /* * From kill(2): * The only signals that can be sent to process ID 1, the init process, * are those for which init has explicitly installed signal handlers. * This is done to assure the system is not brought down accidentally. */ h = SIG_IGN; } if (h == SIG_IGN) { action_ignore(ti, signum, fl); } else if (h == SIG_DFL) { action_type action_func = signal_default_actions[signum] != NULL ? signal_default_actions[signum] : action_terminate; if (action_func) action_func(ti, signum, fl); } else { add_pending_sig(ti, signum, fl); if (!is_sig_masked(ti, signum)) signal_wakeup_task(ti); } } int send_signal2(int pid, int tid, int signum, int flags) { struct task *ti; int rc = -ESRCH; disable_preemption(); if (!(ti = get_task(tid))) goto err_end; if (is_kernel_thread(ti)) goto err_end; /* cannot send signals to kernel threads */ /* When `whole_process` is true, tid must be == pid */ if ((flags & SIG_FL_PROCESS) && ti->pi->pid != tid) goto err_end; if (ti->pi->pid != pid) goto err_end; if (signum == 0) goto end; /* the user app is just checking permissions */ if (ti->state == TASK_STATE_ZOMBIE) goto end; /* do nothing */ /* TODO: update this code when thread support is added */ do_send_signal(ti, signum, flags); end: rc = 0; err_end: enable_preemption(); return rc; } bool pending_signals(void) { struct task *curr = get_curr_task(); STATIC_ASSERT(K_SIGACTION_MASK_WORDS <= 2); if (curr->nested_sig_handlers > 0) { /* * Because we don't support nested signal handlers at the moment, it's * much better to return false inconditionally here. Otherwise, in case * a signal was sent during a signal handler, most syscalls will return * -EINTR and the user program will likely end up in an stuck in an * endless loop. * * TODO: add support for nested signal handlers. */ return false; } if (K_SIGACTION_MASK_WORDS == 1) return (curr->sa_pending[0] & ~curr->sa_mask[0]) != 0; else return (curr->sa_pending[0] & ~curr->sa_mask[0]) != 0 || (curr->sa_pending[1] & ~curr->sa_mask[1]) != 0; } /* * ------------------------------------- * SYSCALLS * ------------------------------------- */ /* NOTE: deprecated syscall */ int sys_tkill(int tid, int sig) { if (!IN_RANGE(sig, 0, _NSIG) || tid <= 0) return -EINVAL; return send_signal(tid, sig, false); } int sys_tgkill(int pid /* linux: tgid */, int tid, int sig) { if (pid != tid) { printk("sys_tgkill: pid != tid NOT SUPPORTED yet.\n"); return -EINVAL; } if (!IN_RANGE(sig, 0, _NSIG) || pid <= 0 || tid <= 0) return -EINVAL; return send_signal2(pid, tid, sig, false); } static int kill_each_task(void *obj, void *arg) { struct task *ti = obj; int sig = *(int *)arg; if (ti != get_curr_task() && !is_kernel_thread(ti)) { send_signal(ti->tid, sig, false); } return 0; } int sys_kill(int pid, int sig) { if (!IN_RANGE(sig, 0, _NSIG)) return -EINVAL; if (pid == 0) return send_signal_to_group(get_curr_proc()->pgid, sig); if (pid == -1) { /* * From kill(2): * sig is sent to every process for which the calling process has * permission to send signals, except for process 1 (init) */ disable_preemption(); { iterate_over_tasks(&kill_each_task, &sig); } enable_preemption(); return 0; } if (pid < -1) return send_signal_to_group(-pid, sig); /* pid > 0 */ return send_signal(pid, sig, true); } static int sigaction_int(int signum, const struct k_sigaction *user_act) { struct task *curr = get_curr_task(); struct k_sigaction act; if (copy_from_user(&act, user_act, sizeof(act)) != 0) return -EFAULT; if (act.sa_flags & SA_NOCLDSTOP) { return -EINVAL; /* not supported */ } if (act.sa_flags & SA_NOCLDWAIT) { return -EINVAL; /* not supported */ } if (act.sa_flags & SA_SIGINFO) { return -EINVAL; /* not supported */ } if (act.sa_flags & SA_ONSTACK) { return -EINVAL; /* not supported */ } if (act.sa_flags & SA_RESETHAND) { /* TODO: add support for this simple flag */ } if (act.sa_flags & SA_NODEFER) { /* * Just ignore this. For the moment, Tilck will block the delivery of * signals with custom handlers, if ANY signal handler is running. */ } if (act.sa_flags & SA_RESTART) { /* For the moment, silently signore this important flag too. */ } curr->pi->sa_handlers[signum - 1] = act.handler; return 0; } int sys_rt_sigaction(int signum, const struct k_sigaction *user_act, struct k_sigaction *user_oldact, size_t sigsetsize) { struct task *curr = get_curr_task(); struct k_sigaction oldact; int rc = 0; if (!IN_RANGE(signum, 1, _NSIG)) return -EINVAL; if (signum == SIGKILL || signum == SIGSTOP) return -EINVAL; if (sigsetsize < sizeof(oldact.sa_mask)) return -EINVAL; disable_preemption(); { if (user_oldact != NULL) { oldact = (struct k_sigaction) { .handler = curr->pi->sa_handlers[signum - 1], .sa_flags = 0, .restorer = NULL }; /* * Since we don't support per-signal masks, just made up on-the-fly * the "mask" we're using: all signals are masked except for SIGKILL * and SIGSTOP. */ memset(&oldact.sa_mask, 0xff, sizeof(oldact.sa_mask)); __del_sig(oldact.sa_mask, SIGKILL); __del_sig(oldact.sa_mask, SIGSTOP); } if (user_act != NULL) { rc = sigaction_int(signum, user_act); } } enable_preemption(); if (!rc && user_oldact != NULL) { rc = copy_to_user(user_oldact, &oldact, sizeof(oldact)); if (!rc) { if (sigsetsize > sizeof(oldact.sa_mask)) { ulong diff = sigsetsize - sizeof(oldact.sa_mask); rc = copy_to_user( (char *)user_oldact + sizeof(oldact), zero_page, diff ); if (rc) rc = -EFAULT; } } else { rc = -EFAULT; } } return rc; } int sys_rt_sigprocmask(int how, sigset_t *user_set, sigset_t *user_oldset, size_t sigsetsize) { ASSERT(!is_preemption_enabled()); /* Thanks to SYSFL_NO_PREEMPT */ struct task *ti = get_curr_task(); int rc; if (user_oldset) { rc = copy_to_user(user_oldset, ti->sa_mask, sigsetsize); if (rc) return -EFAULT; if (sigsetsize > sizeof(ti->sa_mask)) { const size_t diff = sigsetsize - sizeof(ti->sa_mask); rc = copy_to_user( (char *)user_oldset + sizeof(ti->sa_mask), zero_page, diff ); if (rc) return -EFAULT; } } if (user_set) { for (u32 i = 0; i < K_SIGACTION_MASK_WORDS; i++) { ulong w = 0; rc = copy_from_user( &w, (char *)user_set + i * sizeof(ulong), sizeof(ulong) ); if (rc) return -EFAULT; switch (how) { case SIG_BLOCK: ti->sa_mask[i] |= w; break; case SIG_UNBLOCK: ti->sa_mask[i] &= ~w; break; case SIG_SETMASK: ti->sa_mask[i] = w; break; default: return -EINVAL; } } __del_sig(ti->sa_mask, SIGSTOP); __del_sig(ti->sa_mask, SIGKILL); } return 0; } int sys_rt_sigpending(sigset_t *u_set, size_t sigsetsize) { ASSERT(!is_preemption_enabled()); /* Thanks to SYSFL_NO_PREEMPT */ struct task *ti = get_curr_task(); int rc; if (!u_set) return 0; rc = copy_to_user(u_set, ti->sa_pending, sigsetsize); if (rc) return -EFAULT; if (sigsetsize > sizeof(ti->sa_pending)) { const size_t diff = sigsetsize - sizeof(ti->sa_pending); rc = copy_to_user( (char *)u_set + sizeof(ti->sa_pending), zero_page, diff ); if (rc) return -EFAULT; } return 0; } int sys_rt_sigsuspend(sigset_t *u_mask, size_t sigsetsize) { ASSERT(!is_preemption_enabled()); /* Thanks to SYSFL_NO_PREEMPT */ struct task *curr = get_curr_task(); int rc; if (curr->nested_sig_handlers > 0) { /* * For the moment, we don't support nested signal handlers. Therefore, * it doesn't make sense allowing sigsuspend() to be called from a signal * handler and expect a signal to be delivered. * * TODO: add support for nested signal handlers. */ return -EPERM; } /* * The `in_sigsuspend` flag must NOT be set here, as we already checked * that we're not running inside a signal handler. */ ASSERT(!curr->in_sigsuspend); if (sigsetsize < sizeof(curr->sa_mask)) return -EINVAL; /* OK, we're not in a signal handler. Now, save the current signal mask. */ memcpy(curr->sa_old_mask, curr->sa_mask, sizeof(curr->sa_old_mask)); /* Now try to set the new mask */ rc = copy_from_user(curr->sa_mask, u_mask, sizeof(curr->sa_mask)); if (rc) { /* Oops, u_mask pointed to invalid memory in userspace */ /* Restore the saved mask */ memcpy(curr->sa_mask, curr->sa_old_mask, sizeof(curr->sa_old_mask)); return -EFAULT; } /* * We must raise the `in_sigsuspend` flag, otherwise the old mask won't be * restored. */ curr->in_sigsuspend = true; /* * OK, now the signal mask has been updated, but we cannot still fully trust * user code and allow it to mask SIGKILL and SIGSTOP. */ __del_sig(curr->sa_mask, SIGKILL); __del_sig(curr->sa_mask, SIGSTOP); /* * OK, now go to sleep, behaving like sys_pause(). sys_rt_sigreturn() will * restore the old mask. */ return sys_pause(); } int sys_pause(void) { ASSERT(!is_preemption_enabled()); /* Thanks to SYSFL_NO_PREEMPT */ /* * Note: sys_pause() doesn't really need to run with preemption disabled like * sys_rt_sigsuspend() does. It's just more convenient this way because it * allows sys_rt_sigsuspend() to call it directly. */ while (!pending_signals()) { task_change_state(get_curr_task(), TASK_STATE_SLEEPING); schedule_preempt_disabled(); disable_preemption(); } return -EINTR; } int sys_sigprocmask(ulong a1, ulong a2, ulong a3) { NOT_IMPLEMENTED(); // deprecated interface } int sys_sigaction(ulong a1, ulong a2, ulong a3) { NOT_IMPLEMENTED(); // deprecated interface } __sighandler_t sys_signal(int signum, __sighandler_t handler) { NOT_IMPLEMENTED(); // deprecated interface } <file_sep>/****************************************************************************** * * Module Name: tbfadt - FADT table utilities * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "actables.h" #define _COMPONENT ACPI_TABLES ACPI_MODULE_NAME ("tbfadt") /* Local prototypes */ static void AcpiTbInitGenericAddress ( ACPI_GENERIC_ADDRESS *GenericAddress, UINT8 SpaceId, UINT8 ByteWidth, UINT64 Address, const char *RegisterName, UINT8 Flags); static void AcpiTbConvertFadt ( void); static void AcpiTbSetupFadtRegisters ( void); static UINT64 AcpiTbSelectAddress ( char *RegisterName, UINT32 Address32, UINT64 Address64); /* Table for conversion of FADT to common internal format and FADT validation */ typedef struct acpi_fadt_info { const char *Name; UINT16 Address64; UINT16 Address32; UINT16 Length; UINT8 DefaultLength; UINT8 Flags; } ACPI_FADT_INFO; #define ACPI_FADT_OPTIONAL 0 #define ACPI_FADT_REQUIRED 1 #define ACPI_FADT_SEPARATE_LENGTH 2 #define ACPI_FADT_GPE_REGISTER 4 static ACPI_FADT_INFO FadtInfoTable[] = { {"Pm1aEventBlock", ACPI_FADT_OFFSET (XPm1aEventBlock), ACPI_FADT_OFFSET (Pm1aEventBlock), ACPI_FADT_OFFSET (Pm1EventLength), ACPI_PM1_REGISTER_WIDTH * 2, /* Enable + Status register */ ACPI_FADT_REQUIRED}, {"Pm1bEventBlock", ACPI_FADT_OFFSET (XPm1bEventBlock), ACPI_FADT_OFFSET (Pm1bEventBlock), ACPI_FADT_OFFSET (Pm1EventLength), ACPI_PM1_REGISTER_WIDTH * 2, /* Enable + Status register */ ACPI_FADT_OPTIONAL}, {"Pm1aControlBlock", ACPI_FADT_OFFSET (XPm1aControlBlock), ACPI_FADT_OFFSET (Pm1aControlBlock), ACPI_FADT_OFFSET (Pm1ControlLength), ACPI_PM1_REGISTER_WIDTH, ACPI_FADT_REQUIRED}, {"Pm1bControlBlock", ACPI_FADT_OFFSET (XPm1bControlBlock), ACPI_FADT_OFFSET (Pm1bControlBlock), ACPI_FADT_OFFSET (Pm1ControlLength), ACPI_PM1_REGISTER_WIDTH, ACPI_FADT_OPTIONAL}, {"Pm2ControlBlock", ACPI_FADT_OFFSET (XPm2ControlBlock), ACPI_FADT_OFFSET (Pm2ControlBlock), ACPI_FADT_OFFSET (Pm2ControlLength), ACPI_PM2_REGISTER_WIDTH, ACPI_FADT_SEPARATE_LENGTH}, {"PmTimerBlock", ACPI_FADT_OFFSET (XPmTimerBlock), ACPI_FADT_OFFSET (PmTimerBlock), ACPI_FADT_OFFSET (PmTimerLength), ACPI_PM_TIMER_WIDTH, ACPI_FADT_SEPARATE_LENGTH}, /* ACPI 5.0A: Timer is optional */ {"Gpe0Block", ACPI_FADT_OFFSET (XGpe0Block), ACPI_FADT_OFFSET (Gpe0Block), ACPI_FADT_OFFSET (Gpe0BlockLength), 0, ACPI_FADT_SEPARATE_LENGTH | ACPI_FADT_GPE_REGISTER}, {"Gpe1Block", ACPI_FADT_OFFSET (XGpe1Block), ACPI_FADT_OFFSET (Gpe1Block), ACPI_FADT_OFFSET (Gpe1BlockLength), 0, ACPI_FADT_SEPARATE_LENGTH | ACPI_FADT_GPE_REGISTER} }; #define ACPI_FADT_INFO_ENTRIES \ (sizeof (FadtInfoTable) / sizeof (ACPI_FADT_INFO)) /* Table used to split Event Blocks into separate status/enable registers */ typedef struct acpi_fadt_pm_info { ACPI_GENERIC_ADDRESS *Target; UINT16 Source; UINT8 RegisterNum; } ACPI_FADT_PM_INFO; static ACPI_FADT_PM_INFO FadtPmInfoTable[] = { {&AcpiGbl_XPm1aStatus, ACPI_FADT_OFFSET (XPm1aEventBlock), 0}, {&AcpiGbl_XPm1aEnable, ACPI_FADT_OFFSET (XPm1aEventBlock), 1}, {&AcpiGbl_XPm1bStatus, ACPI_FADT_OFFSET (XPm1bEventBlock), 0}, {&AcpiGbl_XPm1bEnable, ACPI_FADT_OFFSET (XPm1bEventBlock), 1} }; #define ACPI_FADT_PM_INFO_ENTRIES \ (sizeof (FadtPmInfoTable) / sizeof (ACPI_FADT_PM_INFO)) /******************************************************************************* * * FUNCTION: AcpiTbInitGenericAddress * * PARAMETERS: GenericAddress - GAS struct to be initialized * SpaceId - ACPI Space ID for this register * ByteWidth - Width of this register * Address - Address of the register * RegisterName - ASCII name of the ACPI register * * RETURN: None * * DESCRIPTION: Initialize a Generic Address Structure (GAS) * See the ACPI specification for a full description and * definition of this structure. * ******************************************************************************/ static void AcpiTbInitGenericAddress ( ACPI_GENERIC_ADDRESS *GenericAddress, UINT8 SpaceId, UINT8 ByteWidth, UINT64 Address, const char *RegisterName, UINT8 Flags) { UINT8 BitWidth; /* * Bit width field in the GAS is only one byte long, 255 max. * Check for BitWidth overflow in GAS. */ BitWidth = (UINT8) (ByteWidth * 8); if (ByteWidth > 31) /* (31*8)=248, (32*8)=256 */ { /* * No error for GPE blocks, because we do not use the BitWidth * for GPEs, the legacy length (ByteWidth) is used instead to * allow for a large number of GPEs. */ if (!(Flags & ACPI_FADT_GPE_REGISTER)) { ACPI_ERROR ((AE_INFO, "%s - 32-bit FADT register is too long (%u bytes, %u bits) " "to convert to GAS struct - 255 bits max, truncating", RegisterName, ByteWidth, (ByteWidth * 8))); } BitWidth = 255; } /* * The 64-bit Address field is non-aligned in the byte packed * GAS struct. */ ACPI_MOVE_64_TO_64 (&GenericAddress->Address, &Address); /* All other fields are byte-wide */ GenericAddress->SpaceId = SpaceId; GenericAddress->BitWidth = BitWidth; GenericAddress->BitOffset = 0; GenericAddress->AccessWidth = 0; /* Access width ANY */ } /******************************************************************************* * * FUNCTION: AcpiTbSelectAddress * * PARAMETERS: RegisterName - ASCII name of the ACPI register * Address32 - 32-bit address of the register * Address64 - 64-bit address of the register * * RETURN: The resolved 64-bit address * * DESCRIPTION: Select between 32-bit and 64-bit versions of addresses within * the FADT. Used for the FACS and DSDT addresses. * * NOTES: * * Check for FACS and DSDT address mismatches. An address mismatch between * the 32-bit and 64-bit address fields (FIRMWARE_CTRL/X_FIRMWARE_CTRL and * DSDT/X_DSDT) could be a corrupted address field or it might indicate * the presence of two FACS or two DSDT tables. * * November 2013: * By default, as per the ACPICA specification, a valid 64-bit address is * used regardless of the value of the 32-bit address. However, this * behavior can be overridden via the AcpiGbl_Use32BitFadtAddresses flag. * ******************************************************************************/ static UINT64 AcpiTbSelectAddress ( char *RegisterName, UINT32 Address32, UINT64 Address64) { if (!Address64) { /* 64-bit address is zero, use 32-bit address */ return ((UINT64) Address32); } if (Address32 && (Address64 != (UINT64) Address32)) { /* Address mismatch between 32-bit and 64-bit versions */ ACPI_BIOS_WARNING ((AE_INFO, "32/64X %s address mismatch in FADT: " "0x%8.8X/0x%8.8X%8.8X, using %u-bit address", RegisterName, Address32, ACPI_FORMAT_UINT64 (Address64), AcpiGbl_Use32BitFadtAddresses ? 32 : 64)); /* 32-bit address override */ if (AcpiGbl_Use32BitFadtAddresses) { return ((UINT64) Address32); } } /* Default is to use the 64-bit address */ return (Address64); } /******************************************************************************* * * FUNCTION: AcpiTbParseFadt * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Initialize the FADT, DSDT and FACS tables * (FADT contains the addresses of the DSDT and FACS) * ******************************************************************************/ void AcpiTbParseFadt ( void) { UINT32 Length; ACPI_TABLE_HEADER *Table; ACPI_TABLE_DESC *FadtDesc; ACPI_STATUS Status; /* * The FADT has multiple versions with different lengths, * and it contains pointers to both the DSDT and FACS tables. * * Get a local copy of the FADT and convert it to a common format * Map entire FADT, assumed to be smaller than one page. */ FadtDesc = &AcpiGbl_RootTableList.Tables[AcpiGbl_FadtIndex]; Status = AcpiTbGetTable (FadtDesc, &Table); if (ACPI_FAILURE (Status)) { return; } Length = FadtDesc->Length; /* * Validate the FADT checksum before we copy the table. Ignore * checksum error as we want to try to get the DSDT and FACS. */ (void) AcpiTbVerifyChecksum (Table, Length); /* Create a local copy of the FADT in common ACPI 2.0+ format */ AcpiTbCreateLocalFadt (Table, Length); /* All done with the real FADT, unmap it */ AcpiTbPutTable (FadtDesc); /* Obtain the DSDT and FACS tables via their addresses within the FADT */ AcpiTbInstallStandardTable ( (ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.XDsdt, ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL, FALSE, TRUE, &AcpiGbl_DsdtIndex); /* If Hardware Reduced flag is set, there is no FACS */ if (!AcpiGbl_ReducedHardware) { if (AcpiGbl_FADT.Facs) { AcpiTbInstallStandardTable ( (ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.Facs, ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL, FALSE, TRUE, &AcpiGbl_FacsIndex); } if (AcpiGbl_FADT.XFacs) { AcpiTbInstallStandardTable ( (ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.XFacs, ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL, FALSE, TRUE, &AcpiGbl_XFacsIndex); } } } /******************************************************************************* * * FUNCTION: AcpiTbCreateLocalFadt * * PARAMETERS: Table - Pointer to BIOS FADT * Length - Length of the table * * RETURN: None * * DESCRIPTION: Get a local copy of the FADT and convert it to a common format. * Performs validation on some important FADT fields. * * NOTE: We create a local copy of the FADT regardless of the version. * ******************************************************************************/ void AcpiTbCreateLocalFadt ( ACPI_TABLE_HEADER *Table, UINT32 Length) { /* * Check if the FADT is larger than the largest table that we expect * (typically the current ACPI specification version). If so, truncate * the table, and issue a warning. */ if (Length > sizeof (ACPI_TABLE_FADT)) { ACPI_BIOS_WARNING ((AE_INFO, "FADT (revision %u) is longer than %s length, " "truncating length %u to %u", Table->Revision, ACPI_FADT_CONFORMANCE, Length, (UINT32) sizeof (ACPI_TABLE_FADT))); } /* Clear the entire local FADT */ memset (&AcpiGbl_FADT, 0, sizeof (ACPI_TABLE_FADT)); /* Copy the original FADT, up to sizeof (ACPI_TABLE_FADT) */ memcpy (&AcpiGbl_FADT, Table, ACPI_MIN (Length, sizeof (ACPI_TABLE_FADT))); /* Take a copy of the Hardware Reduced flag */ AcpiGbl_ReducedHardware = FALSE; if (AcpiGbl_FADT.Flags & ACPI_FADT_HW_REDUCED) { AcpiGbl_ReducedHardware = TRUE; } /* Convert the local copy of the FADT to the common internal format */ AcpiTbConvertFadt (); /* Initialize the global ACPI register structures */ AcpiTbSetupFadtRegisters (); } /******************************************************************************* * * FUNCTION: AcpiTbConvertFadt * * PARAMETERS: None - AcpiGbl_FADT is used. * * RETURN: None * * DESCRIPTION: Converts all versions of the FADT to a common internal format. * Expand 32-bit addresses to 64-bit as necessary. Also validate * important fields within the FADT. * * NOTE: AcpiGbl_FADT must be of size (ACPI_TABLE_FADT), and must * contain a copy of the actual BIOS-provided FADT. * * Notes on 64-bit register addresses: * * After this FADT conversion, later ACPICA code will only use the 64-bit "X" * fields of the FADT for all ACPI register addresses. * * The 64-bit X fields are optional extensions to the original 32-bit FADT * V1.0 fields. Even if they are present in the FADT, they are optional and * are unused if the BIOS sets them to zero. Therefore, we must copy/expand * 32-bit V1.0 fields to the 64-bit X fields if the 64-bit X field is originally * zero. * * For ACPI 1.0 FADTs (that contain no 64-bit addresses), all 32-bit address * fields are expanded to the corresponding 64-bit X fields in the internal * common FADT. * * For ACPI 2.0+ FADTs, all valid (non-zero) 32-bit address fields are expanded * to the corresponding 64-bit X fields, if the 64-bit field is originally * zero. Adhering to the ACPI specification, we completely ignore the 32-bit * field if the 64-bit field is valid, regardless of whether the host OS is * 32-bit or 64-bit. * * Possible additional checks: * (AcpiGbl_FADT.Pm1EventLength >= 4) * (AcpiGbl_FADT.Pm1ControlLength >= 2) * (AcpiGbl_FADT.PmTimerLength >= 4) * Gpe block lengths must be multiple of 2 * ******************************************************************************/ static void AcpiTbConvertFadt ( void) { const char *Name; ACPI_GENERIC_ADDRESS *Address64; UINT32 Address32; UINT8 Length; UINT8 Flags; UINT32 i; /* * For ACPI 1.0 FADTs (revision 1 or 2), ensure that reserved fields which * should be zero are indeed zero. This will workaround BIOSs that * inadvertently place values in these fields. * * The ACPI 1.0 reserved fields that will be zeroed are the bytes located * at offset 45, 55, 95, and the word located at offset 109, 110. * * Note: The FADT revision value is unreliable. Only the length can be * trusted. */ if (AcpiGbl_FADT.Header.Length <= ACPI_FADT_V2_SIZE) { AcpiGbl_FADT.PreferredProfile = 0; AcpiGbl_FADT.PstateControl = 0; AcpiGbl_FADT.CstControl = 0; AcpiGbl_FADT.BootFlags = 0; } /* * Now we can update the local FADT length to the length of the * current FADT version as defined by the ACPI specification. * Thus, we will have a common FADT internally. */ AcpiGbl_FADT.Header.Length = sizeof (ACPI_TABLE_FADT); /* * Expand the 32-bit DSDT addresses to 64-bit as necessary. * Later ACPICA code will always use the X 64-bit field. */ AcpiGbl_FADT.XDsdt = AcpiTbSelectAddress ("DSDT", AcpiGbl_FADT.Dsdt, AcpiGbl_FADT.XDsdt); /* If Hardware Reduced flag is set, we are all done */ if (AcpiGbl_ReducedHardware) { return; } /* Examine all of the 64-bit extended address fields (X fields) */ for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++) { /* * Get the 32-bit and 64-bit addresses, as well as the register * length and register name. */ Address32 = *ACPI_ADD_PTR (UINT32, &AcpiGbl_FADT, FadtInfoTable[i].Address32); Address64 = ACPI_ADD_PTR (ACPI_GENERIC_ADDRESS, &AcpiGbl_FADT, FadtInfoTable[i].Address64); Length = *ACPI_ADD_PTR (UINT8, &AcpiGbl_FADT, FadtInfoTable[i].Length); Name = FadtInfoTable[i].Name; Flags = FadtInfoTable[i].Flags; /* * Expand the ACPI 1.0 32-bit addresses to the ACPI 2.0 64-bit "X" * generic address structures as necessary. Later code will always use * the 64-bit address structures. * * November 2013: * Now always use the 64-bit address if it is valid (non-zero), in * accordance with the ACPI specification which states that a 64-bit * address supersedes the 32-bit version. This behavior can be * overridden by the AcpiGbl_Use32BitFadtAddresses flag. * * During 64-bit address construction and verification, * these cases are handled: * * Address32 zero, Address64 [don't care] - Use Address64 * * No override: if AcpiGbl_Use32BitFadtAddresses is FALSE, and: * Address32 non-zero, Address64 zero - Copy/use Address32 * Address32 non-zero == Address64 non-zero - Use Address64 * Address32 non-zero != Address64 non-zero - Warning, use Address64 * * Override: if AcpiGbl_Use32BitFadtAddresses is TRUE, and: * Address32 non-zero, Address64 zero - Copy/use Address32 * Address32 non-zero == Address64 non-zero - Copy/use Address32 * Address32 non-zero != Address64 non-zero - Warning, copy/use Address32 * * Note: SpaceId is always I/O for 32-bit legacy address fields */ if (Address32) { if (Address64->Address) { if (Address64->Address != (UINT64) Address32) { /* Address mismatch */ ACPI_BIOS_WARNING ((AE_INFO, "32/64X address mismatch in FADT/%s: " "0x%8.8X/0x%8.8X%8.8X, using %u-bit address", Name, Address32, ACPI_FORMAT_UINT64 (Address64->Address), AcpiGbl_Use32BitFadtAddresses ? 32 : 64)); } /* * For each extended field, check for length mismatch * between the legacy length field and the corresponding * 64-bit X length field. * Note: If the legacy length field is > 0xFF bits, ignore * this check. (GPE registers can be larger than the * 64-bit GAS structure can accommodate, 0xFF bits). */ if ((ACPI_MUL_8 (Length) <= ACPI_UINT8_MAX) && (Address64->BitWidth != ACPI_MUL_8 (Length))) { ACPI_BIOS_WARNING ((AE_INFO, "32/64X length mismatch in FADT/%s: %u/%u", Name, ACPI_MUL_8 (Length), Address64->BitWidth)); } } /* * Hardware register access code always uses the 64-bit fields. * So if the 64-bit field is zero or is to be overridden, * initialize it with the 32-bit fields. * Note that when the 32-bit address favor is specified, the * 64-bit fields are always re-initialized so that * AccessSize/BitWidth/BitOffset fields can be correctly * configured to the values to trigger a 32-bit compatible * access mode in the hardware register access code. */ if (!Address64->Address || AcpiGbl_Use32BitFadtAddresses) { AcpiTbInitGenericAddress (Address64, ACPI_ADR_SPACE_SYSTEM_IO, Length, (UINT64) Address32, Name, Flags); } } if (FadtInfoTable[i].Flags & ACPI_FADT_REQUIRED) { /* * Field is required (PM1aEvent, PM1aControl). * Both the address and length must be non-zero. */ if (!Address64->Address || !Length) { ACPI_BIOS_ERROR ((AE_INFO, "Required FADT field %s has zero address and/or length: " "0x%8.8X%8.8X/0x%X", Name, ACPI_FORMAT_UINT64 (Address64->Address), Length)); } } else if (FadtInfoTable[i].Flags & ACPI_FADT_SEPARATE_LENGTH) { /* * Field is optional (PM2Control, GPE0, GPE1) AND has its own * length field. If present, both the address and length must * be valid. */ if ((Address64->Address && !Length) || (!Address64->Address && Length)) { ACPI_BIOS_WARNING ((AE_INFO, "Optional FADT field %s has valid %s but zero %s: " "0x%8.8X%8.8X/0x%X", Name, (Length ? "Length" : "Address"), (Length ? "Address": "Length"), ACPI_FORMAT_UINT64 (Address64->Address), Length)); } } } } /******************************************************************************* * * FUNCTION: AcpiTbSetupFadtRegisters * * PARAMETERS: None, uses AcpiGbl_FADT. * * RETURN: None * * DESCRIPTION: Initialize global ACPI PM1 register definitions. Optionally, * force FADT register definitions to their default lengths. * ******************************************************************************/ static void AcpiTbSetupFadtRegisters ( void) { ACPI_GENERIC_ADDRESS *Target64; ACPI_GENERIC_ADDRESS *Source64; UINT8 Pm1RegisterByteWidth; UINT32 i; /* * Optionally check all register lengths against the default values and * update them if they are incorrect. */ if (AcpiGbl_UseDefaultRegisterWidths) { for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++) { Target64 = ACPI_ADD_PTR (ACPI_GENERIC_ADDRESS, &AcpiGbl_FADT, FadtInfoTable[i].Address64); /* * If a valid register (Address != 0) and the (DefaultLength > 0) * (Not a GPE register), then check the width against the default. */ if ((Target64->Address) && (FadtInfoTable[i].DefaultLength > 0) && (FadtInfoTable[i].DefaultLength != Target64->BitWidth)) { ACPI_BIOS_WARNING ((AE_INFO, "Invalid length for FADT/%s: %u, using default %u", FadtInfoTable[i].Name, Target64->BitWidth, FadtInfoTable[i].DefaultLength)); /* Incorrect size, set width to the default */ Target64->BitWidth = FadtInfoTable[i].DefaultLength; } } } /* * Get the length of the individual PM1 registers (enable and status). * Each register is defined to be (event block length / 2). Extra divide * by 8 converts bits to bytes. */ Pm1RegisterByteWidth = (UINT8) ACPI_DIV_16 (AcpiGbl_FADT.XPm1aEventBlock.BitWidth); /* * Calculate separate GAS structs for the PM1x (A/B) Status and Enable * registers. These addresses do not appear (directly) in the FADT, so it * is useful to pre-calculate them from the PM1 Event Block definitions. * * The PM event blocks are split into two register blocks, first is the * PM Status Register block, followed immediately by the PM Enable * Register block. Each is of length (Pm1EventLength/2) * * Note: The PM1A event block is required by the ACPI specification. * However, the PM1B event block is optional and is rarely, if ever, * used. */ for (i = 0; i < ACPI_FADT_PM_INFO_ENTRIES; i++) { Source64 = ACPI_ADD_PTR (ACPI_GENERIC_ADDRESS, &AcpiGbl_FADT, FadtPmInfoTable[i].Source); if (Source64->Address) { AcpiTbInitGenericAddress (FadtPmInfoTable[i].Target, Source64->SpaceId, Pm1RegisterByteWidth, Source64->Address + (FadtPmInfoTable[i].RegisterNum * Pm1RegisterByteWidth), "PmRegisters", 0); } } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/string_util.h> #include <tilck/kernel/fs/fat32.h> /* * ********************************************* * DEBUG util code * ********************************************* */ static void dump_fixed_str(const char *what, char *str, u32 len) { char buf[256]; len = MIN((u32)ARRAY_SIZE(buf), len); buf[len]=0; memcpy(buf, str, len); printk("%s: '%s'\n", what, buf); } void fat_dump_common_header(void *data) { struct fat_hdr *bpb = data; dump_fixed_str("EOM name", bpb->BS_OEMName, sizeof(bpb->BS_OEMName)); printk("Bytes per sec: %u\n", bpb->BPB_BytsPerSec); printk("Sectors per cluster: %u\n", bpb->BPB_SecPerClus); printk("Reserved sectors count: %u\n", bpb->BPB_RsvdSecCnt); printk("Num FATs: %u\n", bpb->BPB_NumFATs); printk("Root ent count: %u\n", bpb->BPB_RootEntCnt); printk("Tot Sec 16: %u\n", bpb->BPB_TotSec16); printk("Media: %u\n", bpb->BPB_Media); printk("FATz16: %u\n", bpb->BPB_FATSz16); printk("Sectors per track: %u\n", bpb->BPB_SecPerTrk); printk("Num heads: %u\n", bpb->BPB_NumHeads); printk("Hidden sectors: %u\n", bpb->BPB_HiddSec); printk("Total Sec 32: %u\n", bpb->BPB_TotSec32); } static void dump_fat16_headers(struct fat_hdr *common_hdr) { struct fat16_header2 *hdr = (struct fat16_header2*) (common_hdr+1); printk("BS_DrvNum: %u\n", hdr->BS_DrvNum); printk("BS_BootSig: %u\n", hdr->BS_BootSig); printk("BS_VolID: %p\n", TO_PTR(hdr->BS_VolID)); dump_fixed_str("BS_VolLab", hdr->BS_VolLab, sizeof(hdr->BS_VolLab)); dump_fixed_str("BS_FilSysType", hdr->BS_FilSysType, sizeof(hdr->BS_FilSysType)); } static void dump_fat32_headers(struct fat_hdr *common_hdr) { struct fat32_header2 *hdr = (struct fat32_header2*) (common_hdr+1); printk("BPB_FATSz32: %u\n", hdr->BPB_FATSz32); printk("BPB_ExtFlags: %u\n", hdr->BPB_ExtFlags); printk("BPB_FSVer: %u\n", hdr->BPB_FSVer); printk("BPB_RootClus: %u\n", hdr->BPB_RootClus); printk("BPB_FSInfo: %u\n", hdr->BPB_FSInfo); printk("BPB_BkBootSec: %u\n", hdr->BPB_BkBootSec); printk("BS_DrvNum: %u\n", hdr->BS_DrvNum); printk("BS_BootSig: %u\n", hdr->BS_BootSig); printk("BS_VolID: %p\n", TO_PTR(hdr->BS_VolID)); dump_fixed_str("BS_VolLab", hdr->BS_VolLab, sizeof(hdr->BS_VolLab)); dump_fixed_str("BS_FilSysType", hdr->BS_FilSysType, sizeof(hdr->BS_FilSysType)); } static void dump_entry_attrs(struct fat_entry *entry) { printk("readonly: %u\n", entry->readonly); printk("hidden: %u\n", entry->hidden); printk("system: %u\n", entry->system); printk("vol id: %u\n", entry->volume_id); printk("directory: %u\n", entry->directory); printk("archive: %u\n", entry->archive); } struct debug_fat_walk_ctx { struct fat_walk_static_params walk_params; struct fat_walk_long_name_ctx walk_ctx; int level; }; static int dump_dir_entry(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *entry, const char *long_name, void *arg) { char shortname[16]; fat_get_short_name(entry, shortname); struct debug_fat_walk_ctx *ctx = arg; char indentbuf[4*16] = {0}; for (int i = 0; i < 4 * ctx->level; i++) indentbuf[i] = ' '; if (!entry->directory) { printk("%s%s: %u bytes\n", indentbuf, long_name ? long_name : shortname, entry->DIR_FileSize); } else { printk("%s%s\n", indentbuf, long_name ? long_name : shortname); } if (entry->directory) { if (strcmp(shortname, ".") && strcmp(shortname, "..")) { ctx->level++; fat_walk(&ctx->walk_params, fat_get_first_cluster(entry)); ctx->level--; } } return 0; } void fat_dump_info(void *fatpart_begin) { struct fat_hdr *hdr = fatpart_begin; fat_dump_common_header(fatpart_begin); printk("\n"); enum fat_type ft = fat_get_type(hdr); ASSERT(ft != fat12_type); if (ft == fat16_type) { dump_fat16_headers(fatpart_begin); } else { dump_fat32_headers(hdr); } printk("\n"); struct debug_fat_walk_ctx ctx = { .walk_params = { .ctx = &ctx.walk_ctx, .h = hdr, .ft = ft, .cb = &dump_dir_entry, .arg = &ctx, }, .level = 0, }; fat_walk(&ctx.walk_params, 0); } <file_sep>/******************************************************************************* * * Module Name: nsalloc - Namespace allocation and deletion utilities * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsalloc") /******************************************************************************* * * FUNCTION: AcpiNsCreateNode * * PARAMETERS: Name - Name of the new node (4 char ACPI name) * * RETURN: New namespace node (Null on failure) * * DESCRIPTION: Create a namespace node * ******************************************************************************/ ACPI_NAMESPACE_NODE * AcpiNsCreateNode ( UINT32 Name) { ACPI_NAMESPACE_NODE *Node; #ifdef ACPI_DBG_TRACK_ALLOCATIONS UINT32 Temp; #endif ACPI_FUNCTION_TRACE (NsCreateNode); Node = AcpiOsAcquireObject (AcpiGbl_NamespaceCache); if (!Node) { return_PTR (NULL); } ACPI_MEM_TRACKING (AcpiGbl_NsNodeList->TotalAllocated++); #ifdef ACPI_DBG_TRACK_ALLOCATIONS Temp = AcpiGbl_NsNodeList->TotalAllocated - AcpiGbl_NsNodeList->TotalFreed; if (Temp > AcpiGbl_NsNodeList->MaxOccupied) { AcpiGbl_NsNodeList->MaxOccupied = Temp; } #endif Node->Name.Integer = Name; ACPI_SET_DESCRIPTOR_TYPE (Node, ACPI_DESC_TYPE_NAMED); return_PTR (Node); } /******************************************************************************* * * FUNCTION: AcpiNsDeleteNode * * PARAMETERS: Node - Node to be deleted * * RETURN: None * * DESCRIPTION: Delete a namespace node. All node deletions must come through * here. Detaches any attached objects, including any attached * data. If a handler is associated with attached data, it is * invoked before the node is deleted. * ******************************************************************************/ void AcpiNsDeleteNode ( ACPI_NAMESPACE_NODE *Node) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *NextDesc; ACPI_FUNCTION_NAME (NsDeleteNode); if (!Node) { return_VOID; } /* Detach an object if there is one */ AcpiNsDetachObject (Node); /* * Delete an attached data object list if present (objects that were * attached via AcpiAttachData). Note: After any normal object is * detached above, the only possible remaining object(s) are data * objects, in a linked list. */ ObjDesc = Node->Object; while (ObjDesc && (ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA)) { /* Invoke the attached data deletion handler if present */ if (ObjDesc->Data.Handler) { ObjDesc->Data.Handler (Node, ObjDesc->Data.Pointer); } NextDesc = ObjDesc->Common.NextObject; AcpiUtRemoveReference (ObjDesc); ObjDesc = NextDesc; } /* Special case for the statically allocated root node */ if (Node == AcpiGbl_RootNode) { return; } /* Now we can delete the node */ (void) AcpiOsReleaseObject (AcpiGbl_NamespaceCache, Node); ACPI_MEM_TRACKING (AcpiGbl_NsNodeList->TotalFreed++); ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Node %p, Remaining %X\n", Node, AcpiGbl_CurrentNodeCount)); } /******************************************************************************* * * FUNCTION: AcpiNsRemoveNode * * PARAMETERS: Node - Node to be removed/deleted * * RETURN: None * * DESCRIPTION: Remove (unlink) and delete a namespace node * ******************************************************************************/ void AcpiNsRemoveNode ( ACPI_NAMESPACE_NODE *Node) { ACPI_NAMESPACE_NODE *ParentNode; ACPI_NAMESPACE_NODE *PrevNode; ACPI_NAMESPACE_NODE *NextNode; ACPI_FUNCTION_TRACE_PTR (NsRemoveNode, Node); ParentNode = Node->Parent; PrevNode = NULL; NextNode = ParentNode->Child; /* Find the node that is the previous peer in the parent's child list */ while (NextNode != Node) { PrevNode = NextNode; NextNode = NextNode->Peer; } if (PrevNode) { /* Node is not first child, unlink it */ PrevNode->Peer = Node->Peer; } else { /* * Node is first child (has no previous peer). * Link peer list to parent */ ParentNode->Child = Node->Peer; } /* Delete the node and any attached objects */ AcpiNsDeleteNode (Node); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsInstallNode * * PARAMETERS: WalkState - Current state of the walk * ParentNode - The parent of the new Node * Node - The new Node to install * Type - ACPI object type of the new Node * * RETURN: None * * DESCRIPTION: Initialize a new namespace node and install it amongst * its peers. * * Note: Current namespace lookup is linear search. This appears * to be sufficient as namespace searches consume only a small * fraction of the execution time of the ACPI subsystem. * ******************************************************************************/ void AcpiNsInstallNode ( ACPI_WALK_STATE *WalkState, ACPI_NAMESPACE_NODE *ParentNode, /* Parent */ ACPI_NAMESPACE_NODE *Node, /* New Child*/ ACPI_OBJECT_TYPE Type) { ACPI_OWNER_ID OwnerId = 0; ACPI_NAMESPACE_NODE *ChildNode; ACPI_FUNCTION_TRACE (NsInstallNode); if (WalkState) { /* * Get the owner ID from the Walk state. The owner ID is used to * track table deletion and deletion of objects created by methods. */ OwnerId = WalkState->OwnerId; if ((WalkState->MethodDesc) && (ParentNode != WalkState->MethodNode)) { /* * A method is creating a new node that is not a child of the * method (it is non-local). Mark the executing method as having * modified the namespace. This is used for cleanup when the * method exits. */ WalkState->MethodDesc->Method.InfoFlags |= ACPI_METHOD_MODIFIED_NAMESPACE; } } /* Link the new entry into the parent and existing children */ Node->Peer = NULL; Node->Parent = ParentNode; ChildNode = ParentNode->Child; if (!ChildNode) { ParentNode->Child = Node; } else { /* Add node to the end of the peer list */ while (ChildNode->Peer) { ChildNode = ChildNode->Peer; } ChildNode->Peer = Node; } /* Init the new entry */ Node->OwnerId = OwnerId; Node->Type = (UINT8) Type; ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%4.4s (%s) [Node %p Owner %3.3X] added to %4.4s (%s) [Node %p]\n", AcpiUtGetNodeName (Node), AcpiUtGetTypeName (Node->Type), Node, OwnerId, AcpiUtGetNodeName (ParentNode), AcpiUtGetTypeName (ParentNode->Type), ParentNode)); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsDeleteChildren * * PARAMETERS: ParentNode - Delete this objects children * * RETURN: None. * * DESCRIPTION: Delete all children of the parent object. In other words, * deletes a "scope". * ******************************************************************************/ void AcpiNsDeleteChildren ( ACPI_NAMESPACE_NODE *ParentNode) { ACPI_NAMESPACE_NODE *NextNode; ACPI_NAMESPACE_NODE *NodeToDelete; ACPI_FUNCTION_TRACE_PTR (NsDeleteChildren, ParentNode); if (!ParentNode) { return_VOID; } /* Deallocate all children at this level */ NextNode = ParentNode->Child; while (NextNode) { /* Grandchildren should have all been deleted already */ if (NextNode->Child) { ACPI_ERROR ((AE_INFO, "Found a grandchild! P=%p C=%p", ParentNode, NextNode)); } /* * Delete this child node and move on to the next child in the list. * No need to unlink the node since we are deleting the entire branch. */ NodeToDelete = NextNode; NextNode = NextNode->Peer; AcpiNsDeleteNode (NodeToDelete); }; /* Clear the parent's child pointer */ ParentNode->Child = NULL; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsDeleteNamespaceSubtree * * PARAMETERS: ParentNode - Root of the subtree to be deleted * * RETURN: None. * * DESCRIPTION: Delete a subtree of the namespace. This includes all objects * stored within the subtree. * ******************************************************************************/ void AcpiNsDeleteNamespaceSubtree ( ACPI_NAMESPACE_NODE *ParentNode) { ACPI_NAMESPACE_NODE *ChildNode = NULL; UINT32 Level = 1; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsDeleteNamespaceSubtree); if (!ParentNode) { return_VOID; } /* Lock namespace for possible update */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_VOID; } /* * Traverse the tree of objects until we bubble back up * to where we started. */ while (Level > 0) { /* Get the next node in this scope (NULL if none) */ ChildNode = AcpiNsGetNextNode (ParentNode, ChildNode); if (ChildNode) { /* Found a child node - detach any attached object */ AcpiNsDetachObject (ChildNode); /* Check if this node has any children */ if (ChildNode->Child) { /* * There is at least one child of this node, * visit the node */ Level++; ParentNode = ChildNode; ChildNode = NULL; } } else { /* * No more children of this parent node. * Move up to the grandparent. */ Level--; /* * Now delete all of the children of this parent * all at the same time. */ AcpiNsDeleteChildren (ParentNode); /* New "last child" is this parent node */ ChildNode = ParentNode; /* Move up the tree to the grandparent */ ParentNode = ParentNode->Parent; } } (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsDeleteNamespaceByOwner * * PARAMETERS: OwnerId - All nodes with this owner will be deleted * * RETURN: Status * * DESCRIPTION: Delete entries within the namespace that are owned by a * specific ID. Used to delete entire ACPI tables. All * reference counts are updated. * * MUTEX: Locks namespace during deletion walk. * ******************************************************************************/ void AcpiNsDeleteNamespaceByOwner ( ACPI_OWNER_ID OwnerId) { ACPI_NAMESPACE_NODE *ChildNode; ACPI_NAMESPACE_NODE *DeletionNode; ACPI_NAMESPACE_NODE *ParentNode; UINT32 Level; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_U32 (NsDeleteNamespaceByOwner, OwnerId); if (OwnerId == 0) { return_VOID; } /* Lock namespace for possible update */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_VOID; } DeletionNode = NULL; ParentNode = AcpiGbl_RootNode; ChildNode = NULL; Level = 1; /* * Traverse the tree of nodes until we bubble back up * to where we started. */ while (Level > 0) { /* * Get the next child of this parent node. When ChildNode is NULL, * the first child of the parent is returned */ ChildNode = AcpiNsGetNextNode (ParentNode, ChildNode); if (DeletionNode) { AcpiNsDeleteChildren (DeletionNode); AcpiNsRemoveNode (DeletionNode); DeletionNode = NULL; } if (ChildNode) { if (ChildNode->OwnerId == OwnerId) { /* Found a matching child node - detach any attached object */ AcpiNsDetachObject (ChildNode); } /* Check if this node has any children */ if (ChildNode->Child) { /* * There is at least one child of this node, * visit the node */ Level++; ParentNode = ChildNode; ChildNode = NULL; } else if (ChildNode->OwnerId == OwnerId) { DeletionNode = ChildNode; } } else { /* * No more children of this parent node. * Move up to the grandparent. */ Level--; if (Level != 0) { if (ParentNode->OwnerId == OwnerId) { DeletionNode = ParentNode; } } /* New "last child" is this parent node */ ChildNode = ParentNode; /* Move up the tree to the grandparent */ ParentNode = ParentNode->Parent; } } (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_VOID; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #define NESTED_FAULTING_CODE_MAX_LEVELS 4 #ifdef __i386__ static void faulting_code_div0(void) { asmVolatile("mov $0, %edx\n\t" "mov $1, %eax\n\t" "mov $0, %ecx\n\t" "div %ecx\n\t"); } static void faulting_code(void) { printk("hello from div by 0 faulting code\n"); disable_preemption(); faulting_code_div0(); /* * Note: because the above asm will trigger a div by 0 fault, we'll never * reach the enable_preemption() below. This is an intentional way of testing * that fault_resumable_call() will restore correctly the value of * __disable_preempt in case of fault. */ enable_preemption(); } static void faulting_code2(void) { #ifndef __clang_analyzer__ /* * The static analyzer cannot possible imagine that we want intentionally * to trigger a PAGE FAULT and check that it has been handeled correctly. */ ulong *ptr = NULL; bzero(ptr, sizeof(ulong)); #endif } static void nested_faulting_code(int level) { if (level == NESTED_FAULTING_CODE_MAX_LEVELS) { printk("[level %i]: *** call faulting code ***\n", level); faulting_code2(); NOT_REACHED(); } printk("[level %i]: do recursive nested call\n", level); u32 r = fault_resumable_call(ALL_FAULTS_MASK, // mask nested_faulting_code, // func 1, // #args level + 1); // arg1 if (level == NESTED_FAULTING_CODE_MAX_LEVELS - 1) VERIFY(r == 1 << FAULT_PAGE_FAULT); else if (level == NESTED_FAULTING_CODE_MAX_LEVELS - 2) VERIFY(r == 1 << FAULT_DIVISION_BY_ZERO); else if (level == NESTED_FAULTING_CODE_MAX_LEVELS - 3) VERIFY(r == 0); if (r) { if (level == NESTED_FAULTING_CODE_MAX_LEVELS - 1) { printk("[level %i]: the call faulted (r = %u). " "Let's do another faulty call\n", level, r); faulting_code_div0(); NOT_REACHED(); } else { printk("[level %i]: the call faulted (r = %u)\n", level, r); } } else { printk("[level %i]: the call was OK\n", level); } printk("[level %i]: we reached the end\n", level); } void selftest_fault_res(void) { u32 r; printk("fault_resumable with just printk()\n"); r = fault_resumable_call(ALL_FAULTS_MASK, printk, 2, "hi from fault resumable: %s\n", "arg1"); printk("returned %u\n", r); VERIFY(r == 0); printk("fault_resumable with code causing div by 0\n"); r = fault_resumable_call(1 << FAULT_DIVISION_BY_ZERO, faulting_code, 0); printk("returned %u\n", r); VERIFY(r == 1 << FAULT_DIVISION_BY_ZERO); printk("fault_resumable with code causing page fault\n"); r = fault_resumable_call(1 << FAULT_PAGE_FAULT, faulting_code2, 0); printk("returned %u\n", r); VERIFY(r == 1 << FAULT_PAGE_FAULT); printk("[level 0]: do recursive nested call\n"); r = fault_resumable_call(ALL_FAULTS_MASK, // all faults nested_faulting_code, 1, // nargs 1); // arg1: level printk("[level 0]: call returned %u\n", r); VERIFY(r == 0); se_regular_end(); } REGISTER_SELF_TEST(fault_res, se_short, &selftest_fault_res) static NO_INLINE void do_nothing(ulong a1, ulong a2, ulong a3, ulong a4, ulong a5, ulong a6) { DO_NOT_OPTIMIZE_AWAY(a1); DO_NOT_OPTIMIZE_AWAY(a2); DO_NOT_OPTIMIZE_AWAY(a3); DO_NOT_OPTIMIZE_AWAY(a4); DO_NOT_OPTIMIZE_AWAY(a5); DO_NOT_OPTIMIZE_AWAY(a6); } void selftest_fault_res_perf(void) { const int iters = 100000; u64 start, duration; start = RDTSC(); for (int i = 0; i < iters; i++) do_nothing(1,2,3,4,5,6); duration = RDTSC() - start; printk("regular call: %llu cycles\n", duration/iters); start = RDTSC(); for (int i = 0; i < iters; i++) fault_resumable_call(0, do_nothing, 6, 1, 2, 3, 4, 5, 6); duration = RDTSC() - start; printk("fault resumable call: %llu cycles\n", duration/iters); se_regular_end(); } REGISTER_SELF_TEST(fault_res_perf, se_short, &selftest_fault_res_perf) #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define CHAR_BLOCK_LIGHT 0xb0 // # #define CHAR_BLOCK_MID 0xb1 // # #define CHAR_BLOCK_HEAVY 0xdb // # #define CHAR_VLINE 0xb3 // | #define CHAR_RTEE 0xb4 // -| #define CHAR_LTEE 0xc3 // |- #define CHAR_LLCORNER 0xc0 // |_ #define CHAR_LRCORNER 0xd9 // _| #define CHAR_ULCORNER 0xda // #define CHAR_URCORNER 0xbf // #define CHAR_BTEE 0xc1 // _|_ #define CHAR_TTEE 0xc2 // T #define CHAR_HLINE 0xc4 // -- #define CHAR_CROSS 0xc5 // + #define CHAR_DIAMOND 0x04 #define CHAR_DEGREE 0xf8 #define CHAR_PLMINUS 0xf1 #define CHAR_BULLET 0x07 #define CHAR_LARROW 0x1b #define CHAR_RARROW 0x1a #define CHAR_DARROW 0x19 #define CHAR_UARROW 0x18 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/build_info.h> void extract_commit_hash_and_date(const struct build_info *bi, struct commit_hash_and_date *c) { const char *date, *comm, *tags; size_t len; c->hash[0] = 0; c->date[0] = 0; c->tags[0] = 0; c->dirty = !strncmp(bi->commit, "dirty:", 6); comm = bi->commit + (c->dirty ? 6 : 0); len = strlen(comm); date = strstr(comm, " "); if (date) { /* set hash's field length max length */ len = (size_t)(date - comm); date++; } /* copy the hash field */ len = MIN(len, sizeof(c->hash) - 1); memcpy(c->hash, comm, len); c->hash[len] = 0; if (!date) return; /* copy the date field */ len = 25u; /* fixed length for the date */ STATIC_ASSERT(sizeof(c->date) > 25u); strncpy(c->date, date, len); c->date[len] = 0; tags = strstr(date, "tags:"); if (!tags) return; tags += 5; /* skip "tags:" */ /* copy the tags field */ len = MIN(sizeof(c->tags) - 1, strlen(tags)); memcpy(c->tags, tags, len); c->tags[len] = 0; } <file_sep><p align="center"> <img src="http://vvaltchev.github.io/tilck_imgs/v2/tilck-logo-v5.png" alt="Tilck - A Tiny Linux-Compatible Kernel"> </p> [![Build Status](https://vkvaltchev.visualstudio.com/Tilck/_apis/build/status/Tilck?branchName=master)](https://vkvaltchev.visualstudio.com/Tilck/_build/latest?definitionId=1&branchName=master) [![codecov](https://codecov.io/gh/vvaltchev/tilck/branch/master/graph/badge.svg)](https://codecov.io/gh/vvaltchev/tilck) [![License](https://img.shields.io/badge/License-BSD%202--Clause-orange.svg)](https://opensource.org/licenses/BSD-2-Clause) <a href="https://youtu.be/Ce1pMlZO_mI"> <img align="right" src="http://vvaltchev.github.io/tilck_imgs/v2/main2-smaller-70p-yt.png" alt="Tilck" > </a> Contents ---------------------------------------- * [Overview](#overview) - [What is Tilck?](#what-is-tilck) * [Future plans](#future-plans) - [What Tilck is NOT ?](#what-tilck-is-not-) * [Tilck vs Linux](#tilck-vs-linux) * [Features](#features) - [Hardware support](#hardware-support) - [File systems](#file-systems) - [Processes and signals](#processes-and-signals) - [I/O](#io) - [Console](#console) - [Userspace applications](#userspace-applications) - [Screenshots](#screenshots) * [Booting Tilck](#booting-tilck) - [Tilck's bootloader](#tilcks-bootloader) - [3rd-party bootloaders](#3rd-party-bootloaders) * [Grub support](#grub-support) * [Documentation and HOWTOs](#documentation-and-howtos) - [Building Tilck](#building-tilck) - [Testing Tilck](#testing-tilck) - [Debugging Tilck](#debugging-tilck) * [Tilck's debug panel](#tilcks-debug-panel) - [Contributing to Tilck](#contributing-to-tilck) * [A comment about user experience](#a-comment-about-user-experience) * [FAQ](#faq) Overview ---------------------------------------- <p align="center"> <img src="http://vvaltchev.github.io/tilck_imgs/v2/overview.png" border="0"> </p> ### What is Tilck? `Tilck` is an educational *monolithic* x86 kernel designed to be Linux-compatible at binary level. Project's small-scale and simple design makes it the **perfect playground** for playing in kernel mode while retaining the ability to compare how the *very same* *usermode bits* run on the Linux kernel as well. That's a **rare feature** in the realm of educational kernels. Because of that, building a program for Tilck requires just a `i686-musl` toolchain from [bootlin.com](https://toolchains.bootlin.com). Tilck has **no need** to have its own set of custom written applications, like most educational kernels do. It just runs mainstream Linux programs like the **BusyBox** suite. While the Linux-compatibility and the monolithic design might seem a limitation from the OS research point of view, on the other side, such design bring the whole project much closer to *real-world* applications in the future, compared to the case where some serious (or huge) effort is required to port pre-existing software on it. Also, nothing stops Tilck from implementing custom non-Linux syscalls that aware apps might take advantage of. #### Future plans In the long term, depending on how successful the project will be, `Tilck` might become suitable for **embedded systems** on which a fully deterministic and ultra low-latency system is required. With a fair amount of luck, `Tilck` might be able to fill the gap between *Embedded Linux* and typical real-time operating systems like *FreeRTOS* or *Zephyr*. In any case, at some point it will be ported to the `ARM` family and it might be adapted to run on MMU-less CPUs as well. Tilck would be a perfect fit for that because consuming a tiny amount of RAM has always been a key point in Tilck's design. Indeed, the kernel can boot and run on a i686 QEMU machine with just 3 MB of memory *today*. Of course, that's pointless on x86, but on an ARM Cortex-R that won't be anymore the case. In addition to that, adding a basic support for networking and storage is part of the plans even if details have not been defined yet. Networking support might be limited to UDP + IP (at least at the beginning) and usable on a limited set of network cards. The same applies for storage: not all kinds of block devices will be supported, and a few filesystems (maybe just fat32 and ext2) will implemented in the kernel. The support for FUSE filesystems will be considered. One major milestone for the project will be to support both networking and storage for a specific SoC like Raspberry Pi 3 (or 4) but that could possibly happen only after Tilck has been ported to ARM64. ### What Tilck is NOT ? * An attempt to re-write and/or replace the Linux kernel. Tilck is a completely different kernel that has a *partial* compatibility with Linux just in order to take advantage of its programs and toolchains. Also, that helps a lot to validate its correctness: if a program works correctly on Linux, it must work the same way on Tilck as well (minus not-implemented features). **But**, having a fair amount of Linux programs working on it, is just a *starting point*: with time, Tilck will evolve in a different way and it will have its own unique set of features as well. * A kernel suitable for a *desktop* operating system. No X server works on Tilck, not only because a considerable amount of extra features will be required for that, but because working in that direction is *completely outside* of project's goals. See also: https://github.com/vvaltchev/tilck/discussions/81 #### Tilck vs Linux Tilck is fundamentally different from Linux as it **does not** aim to target multi-user server nor desktop machines, at all because that would be pointless: Linux is **not** big & complex because of a *poor* implementation, but because of the incredible amount of features it offers and the *intrinsic* complexity they require. In other words, **Linux is great** given the problem it solves. Tilck will offer *fewer* features in exchange for: - simpler code (by far) - smaller binary size - extremely deterministic behavior - ultra low-latency - easier development & testing - extra robustness In conclusion, while this is still an *educational* project at the moment, it has been written keeping in mind those goals and it has a test infrastructure that ambitiously tries to be almost *enterprise-level* (see [Testing](#testing-tilck)). Features ---------------------------------------- Tilck is a preemptable monolithic (but with compile-time modules) *NIX kernel, implementing about ~100 Linux syscalls (both via `int 0x80` and `sysenter`) on x86. At its core, the kernel is not x86-centric even if it runs only on x86 at the moment. Everything arch-specific is isolated. Because of that, most of kernel's code can be already compiled for any architecture and can be used in kernel's unit tests. #### Hardware support While the kernel uses a fair amount of **legacy hardware** like the 8259 PICs for IRQs, the legacy 8254 PIT for the system timer, the legacy 16550 UART for serial communication, the 8042 kb controller, the 8237 ISA DMA, and the Sound Blaster 16 sound card (QEMU only), it has also support for some **recent hardware** features like SSE, AVX and AVX2 fpu instructions, PAT, i686 sysenter, enumeration of PCI Express devices (via ECAM) and, above all, **ACPI** support via ACPICA. ACPI is currently used to receive power-button events, to reboot or power-off the machine, and to read the current parameters of machine's batteries (when implemented via ACPI control methods). ##### Comments about physical hardware The operating system has been regularly tested on physical hardware from its inception by booting it with an USB stick (see the notes below). Test machines include actual i686 machines, older x86_64 machines with BIOS-only firmware, newer x86_64 machines with UEFI+CSM and finally super-recent pure-UEFI machines. For a long time, Tilck's development strictly complied with the following rule: *if you cannot test it on real hardware, do not implement it in Tilck*. Only recently, that rule has been relaxed a little in order to play with SB16. It is possible that, in the future, there might be a few other drivers that would be tested only on virtual machines: their development is justified by the educational value it will bring to the operating system and the infrastructure built for them will be reused for other drivers of the same kind. **But** that will *never* become a common practice. Tilck is designed to work on real hardware, where any kind of weird things happen. Being reliable there is *critical* for Tilck's success. #### File systems Tilck has a simple but full-featured (both soft and hard links, file holes, memory mapping, etc.) **ramfs** implementation, a minimalistic **devfs** implementation, read-only support for FAT16 and **FAT32** (used for initrd) allowing memory-mapping of files, and a **sysfs** implementation used to provide a full view of **ACPI's** **namespace**, the list of all PCI(e) devices and Tilck's compile-time configuration. Clearly, in order to work with multiple file systems at once, Tilck has a simple **VFS** implementation as well. **Note**: there is no support for block devices in Tilck yet, so everything is in-memory. #### Processes and signals While Tilck uses internally the concept of thread, multi-threading is not currently exposed to userspace (kernel threads exist, of course). Both `fork()` and `vfork()` are properly implemented and copy-on-write is used for fork-ed processes. The `waitpid()` syscall is fully implemented (which implies process groups etc.). The support for POSIX signals is partial: custom signal handlers are supported using the `rt_sigaction()` interface, but most of the SA_* flags are not supported and handlers cannot interrupt each other, yet. `rt_sigprocmask()`, `sys_rt_sigpending()`, `sys_rt_sigsuspend()` work as expected, as well as special signals like SIGSTOP, SIGCONT and SIGCHLD. For more details, see the [syscalls] document. One interesting feature in this area deserves a special mention: despite the lack of multi-threading in userspace, Tilck has full support for TLS (thread-local storage) via `set_thread_area()`, because `libmusl` requires it, even for classic single-threaded processes. #### I/O In addition to the classic `read()` and `write()` syscalls, Tilck supports vectored I/O via `readv()` and `writev()` as well. In addition to that, non blocking I/O, `select()` and `poll()` are supported too. Fortunately, no program so far needed `epoll` :-) #### Console Tilck has a console supporting more than 90% of Linux's console's features. It works in the same way (using layers of abstraction) both in text mode and in framebuffer mode. The effort to implement such a powerful console was driven by the goal to make **Vim** work smoothly on Tilck, with syntax highlighting etc. While it's true that such a thing has a little to do with "proper" kernel development, being able to run a "beast" like Vim on a simple kernel like Tilck, is a great achievement by itself because it shows that Tilck can run correctly programs having a fair amount of complexity. #### Userspace applications Tilck can run a fair amount of console applications like the **BusyBox** suite, **Vim**, **TinyCC**, **Micropython**, **Lua**, and framebuffer applications like a port of DOOM for the Linux console called **fbDOOM**. Check project's [wiki page] for more info about that. #### Screenshots ![Tilck screenshots](http://vvaltchev.github.io/tilck_imgs/v2/thumbnails.png) For full-size screenshots and much more stuff, check Tilck's [wiki page]. [syscalls]: docs/syscalls.md [wiki page]: https://github.com/vvaltchev/tilck/wiki Booting Tilck ---------------------------------------- ### Tilck's bootloader `Tilck` comes with an interactive bootloader working both on legacy BIOS and on UEFI systems as well. The bootloader allows the user to choose the desired video mode, the kernel file itself and to edit kernel's cmdline. ![Tilck's bootloader](http://vvaltchev.github.io/tilck_imgs/v2/bootloader.png) ### 3rd-party bootloaders `Tilck` can be loaded by any bootloader supporting `multiboot 1.0`. For example, qemu's built-in bootloader works perfectly with `Tilck`: qemu-system-i386 -kernel ./build/tilck -initrd ./build/fatpart Actually that way of booting the kernel is used in the system tests. A shortcut for it is: ./build/run_multiboot_qemu #### Grub support `Tilck` can be easily booted with GRUB. Just edit your `/etc/grub.d/40_custom` file (or create another one) by adding an entry like: ``` menuentry "Tilck" { multiboot <PATH-TO-TILCK-BUILD-DIR>/tilck module --nounzip <PATH-TO-TILCK-BUILD-DIR>/fatpart boot } ``` After that, just run `update-grub` as root and reboot your machine. Documentation and HOWTOs -------------------------- Project's main documentation can be found in the `docs/` directory. However, [Tilck's wiki](https://github.com/vvaltchev/tilck/wiki) can be used to navigate through those documention files with the addition of much extra content like screenshots. Here below, instead, there's a quick *starter* guide, focusing on the most common scenarios. ### Building Tilck The project supports a fair amount of build configurations and customizations but building using its default configuration can be described in just a few steps. The *only* true requirement for building Tilck is having a Linux x86_64 host system or Microsoft's `WSL`. Steps: * Enter project's root directory. * Build the toolchain (just the first time) with: `./scripts/build_toolchain` * Compile the kernel and prepare the bootable image with: `make` At this point, there will be an image file named `tilck.img` in the `build` directory. The easiest way for actually trying `Tilck` at that point is to run: `./build/run_qemu`. #### Running it on physical hardware The `tilck.img` image is, of course, bootable on physical machines as well, both on UEFI systems and on legacy ones. Just flush the image file with `dd` to a usb stick and reboot your machine. #### Other configurations To learn much more about how to build and configure Tilck, check the [building] guide in the `docs/` directory. [building]: docs/building.md ### Testing Tilck Tilck has **unit tests**, **kernel self-tests**, **system tests** (using the syscall interface), and **automated interactive system tests** (simulating real user input through QEMU's monitor) all in the same repository, completely integrated with its build system. In addition to that, there's full code coverage support and useful scripts for generating HTML reports (see the [coverage] guide). Finally, Tilck is fully integrated with the [Azure Pipelines] [CI], which validates each pushed branch with builds and test runs in a variety of configurations. Kernel's coverage data is also uploaded to [CodeCov]. Below, there are some basic instructions to run most of Tilck's tests. For the whole story, please read the [testing] document. [Azure Pipelines]: https://azure.microsoft.com/en-us/services/devops/pipelines [CI]: https://en.wikipedia.org/wiki/Continuous_integration [CodeCov]: https://codecov.io #### Running Tilck's tests Running Tilck's tests is extremely simple: it just requires to have `python 3` installed on the machine. For the **self-tests** and the classic **system tests**, run: <BUILD_DIR>/st/run_all_tests -c To run the **unit tests** instead: * Install the [googletest] library (once) with: `./scripts/build_toolchain -s build_gtest` * Build the unit tests with: `make gtests` * Run them with: `<BUILD_DIR>/gtests` To learn much more about Tilck's tests in general and to understand how to run its *interactive* system tests as well, read the [testing] document. [testing]: docs/testing.md [googletest]: https://github.com/google/googletest ### Debugging Tilck With `QEMU`'s integrated `GDB` server, it's possible to debug the Tilck kernel with GDB almost as if it were a regular process. It just gets tricky when context switches happen, but GDB cannot help with that. To debug it with GDB, follow the steps: - (Optional) Prepare a debug build of Tilck, for a better debugging experience. - Run Tilck's VM with: `./build/run_nokvm_qemu` but, remain at the bootloader stage. - In a different terminal, run: `gdb ./build/tilck_unstripped`. - In GDB, run: `target remote :1234` to connect to QEMU's gdb server. - Set one or more breakpoints using commands like: `break kmain`. - Type `c` to allow execution to continue and boot the OS by pressing ENTER in the bootloader. In order to make the debugging experience better, Tilck comes with a set of **GDB scripts** (see `other/gdb_scripts`). With them, it's super-easy to list all the tasks on the system, the handles currently opened by any given process and more. In order to learn how to take advantage of those GDB scripts and anything else related to debugging the Tilck project, check the [debugging] document. [debugging]: docs/debugging.md #### Tilck's debug panel <img align="right" src="http://vvaltchev.github.io/tilck_imgs/v2/screenshots/dp04.png" alt="Tilck's debug panel" width="50%" height="50%"> Debugging Tilck with GDB while it's running inside a VM is very convenient, but in other cases (e.g. Tilck on real hardware) we don't have GDB support. In addition to that, even when the kernel is running inside a VM, there are some features that are just much more convient to expose directly from the kernel itself rather than through GDB scripts. One way to expose kernel info to userspace is to use `sysfs`, but that's not necessarily the most convenient way for everything (still, Tilck does have [sysfs] implementation), especially when *interaction* with the kernel itself is needed for debugging purposes. To help in those cases, a *debug panel* has been introduced inside Tilck itself. It started as something like Linux's [Magic SysRq] which evolved in a sort of TUI application with debug info plus tracing capabilities for user processes. In the future, it will support some proper debugging features as well. To learn more about it, check the the [debugging] document. [sysfs]: https://github.com/vvaltchev/tilck/wiki/Tilck's-sysfs [Magic SysRq]: https://en.wikipedia.org/wiki/Magic_SysRq_key ### Contributing to Tilck Contributing to the Tilck project is not only possible, but it's encouraged. For more about that, check the guidelines in the [contributing] document. [contributing]: docs/contributing.md A comment about user experience ---------------------------------- Tilck particularly distinguishes itself from many open source projects in one way: it really cares about the **user experience** (where "user" means "developer"). It's not the typical super-cool low-level project that's insanely complex to build and configure; it's not a project requiring 200 things to be installed on the host machine. Building such projects may require hours or even days of effort (think about special configurations e.g. building with a cross-compiler). Tilck instead, has been designed to be trivial to build and test even by inexperienced people with basic knowledge of Linux. It has a sophisticated script for building its own toolchain that works on all the major Linux distributions and a powerful CMake-based build system. The build of Tilck produces an image ready to be tested with QEMU or written on a USB stick. (To some degree, it's like what the `buildroot` project does for Linux, but it's much simpler.) Finally, the project includes also scripts for running Tilck on QEMU with various configurations (BIOS boot, UEFI boot, direct (multi-)boot with QEMU's `-kernel` option, etc.). #### Motivation The reason for having the above mentioned features is to offer its users and potential contributors a really **nice** experience, avoiding any kind of frustration. Hopefully, even the most experienced engineers will enjoy a zero effort experience. But it's not all about reducing the frustration. It's also about _not scaring_ students and junior developers who might be just curious to see what this project is all about and maybe eager to write a simple program for it and/or add a couple of `printk()`'s here and there in their fork. Hopefully, some of those people *just playing* with Tilck might actually want to contribute to its development. In conclusion, even if some parts of the project itself are be pretty complex, at least building and running its tests **must be** something anyone can do. [coverage]: docs/coverage.md FAQ --------------------- Here below, there is a list of *frequently* asked questions. This list is *not* supposed to be exaustive and it will change over time. For the *full list* of questions on Tilck, check the [Q & A page] in the [Discussions] section instead. [Q & A page]: https://github.com/vvaltchev/tilck/discussions/categories/q-a [Discussions]: https://github.com/vvaltchev/tilck/discussions - [Why Tilck does not have the feature/abstraction XYZ like other kernels do?](https://github.com/vvaltchev/tilck/discussions/83) - [Why Tilck runs only on x86 (ia-32)?](https://github.com/vvaltchev/tilck/discussions/84) - [Why having support for FAT32?](https://github.com/vvaltchev/tilck/discussions/85) - [Why keeping the initrd mounted?](https://github.com/vvaltchev/tilck/discussions/86) - [Why using 3 spaces as indentation?](https://github.com/vvaltchev/tilck/discussions/88) - [Why many commit messages are so short?](https://github.com/vvaltchev/tilck/discussions/89) - [Can a lightweight X server run on Tilck today?](https://github.com/vvaltchev/tilck/discussions/81) - [Compiling Tilck with TCC & self-hosting?](https://github.com/vvaltchev/tilck/discussions/93) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/syscalls.h> #include <tilck/mods/tracing.h> #include "syscall_types.h" static const struct syscall_info __tracing_metadata[] = { #if defined(__i386__) || defined(__x86_64) SYSCALL_TYPE_0(SYS_fork), SYSCALL_TYPE_0(SYS_pause), SYSCALL_TYPE_0(SYS_getuid), SYSCALL_TYPE_0(SYS_getgid), SYSCALL_TYPE_0(SYS_geteuid), SYSCALL_TYPE_0(SYS_getegid), #if defined(__i386__) SYSCALL_TYPE_0(SYS_getuid16), SYSCALL_TYPE_0(SYS_getgid16), SYSCALL_TYPE_0(SYS_geteuid16), SYSCALL_TYPE_0(SYS_getegid16), #endif SYSCALL_TYPE_0(SYS_gettid), SYSCALL_TYPE_0(SYS_setsid), SYSCALL_TYPE_0(SYS_sync), SYSCALL_TYPE_0(SYS_getppid), SYSCALL_TYPE_0(SYS_getpgrp), SYSCALL_TYPE_0(SYS_sched_yield), SYSCALL_TYPE_1(SYS_close, "fd"), SYSCALL_TYPE_1(SYS_dup, "dup"), SYSCALL_TYPE_1(SYS_getpgid, "pid"), SYSCALL_TYPE_1(SYS_getsid, "pid"), SYSCALL_TYPE_2(SYS_creat, "path", "mode"), SYSCALL_TYPE_2(SYS_chmod, "path", "mode"), SYSCALL_TYPE_2(SYS_mkdir, "path", "mode"), SYSCALL_TYPE_2(SYS_access, "path", "mode"), SYSCALL_TYPE_3(SYS_unlink, "path"), SYSCALL_TYPE_3(SYS_rmdir, "path"), SYSCALL_TYPE_3(SYS_chdir, "path"), SYSCALL_TYPE_4(SYS_link, "oldpath", "newpath"), SYSCALL_TYPE_4(SYS_symlink, "target", "linkpath"), SYSCALL_TYPE_4(SYS_rename, "oldpath", "newpath"), SYSCALL_TYPE_5(SYS_setpgid, "pid", "pgid"), SYSCALL_TYPE_5(SYS_dup2, "oldfd", "newfd"), #if defined(__i386__) SYSCALL_TYPE_6(SYS_chown16, "path", "owner", "group"), SYSCALL_TYPE_6(SYS_lchown16, "path", "owner", "group"), SYSCALL_TYPE_7(SYS_fchown16, "fd", "owner", "group"), #endif SYSCALL_TYPE_6(SYS_chown, "path", "owner", "group"), SYSCALL_TYPE_6(SYS_lchown, "path", "owner", "group"), SYSCALL_TYPE_7(SYS_fchown, "fd", "owner", "group"), SYSCALL_RW(SYS_read, "fd", "buf", &ptype_big_buf, sys_param_out, "count"), SYSCALL_RW(SYS_write, "fd", "buf", &ptype_big_buf, sys_param_in, "count"), SYSCALL_RW(SYS_readv, "fd", "iov", &ptype_iov_out, sys_param_out, "iovcnt"), SYSCALL_RW(SYS_writev, "fd", "iov", &ptype_iov_in, sys_param_in, "iovcnt"), { .sys_n = SYS_kill, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("pid", &ptype_int, sys_param_in), SIMPLE_PARAM("sig", &ptype_signum, sys_param_in), } }, { .sys_n = SYS_tkill, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("tid", &ptype_int, sys_param_in), SIMPLE_PARAM("sig", &ptype_signum, sys_param_in), } }, { .sys_n = SYS_exit, .n_params = 1, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("status", &ptype_int, sys_param_in), } }, { .sys_n = SYS_exit_group, .n_params = 1, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("status", &ptype_int, sys_param_in), } }, { .sys_n = SYS_vfork, .n_params = 0, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { } }, { .sys_n = SYS_getcwd, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { BUFFER_PARAM("buf", &ptype_buffer, sys_param_out, "size"), SIMPLE_PARAM("size", &ptype_int, sys_param_in), }, }, { .sys_n = SYS_open, .n_params = 3, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("path", &ptype_path, sys_param_in), SIMPLE_PARAM("flags", &ptype_open_flags, sys_param_in), SIMPLE_PARAM("mode", &ptype_oct, sys_param_in), } }, { .sys_n = STAT_SYSCALL_N, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("path", &ptype_path, sys_param_in), SIMPLE_PARAM("statbuf", &ptype_voidp, sys_param_out), }, }, { .sys_n = LSTAT_SYSCALL_N, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("path", &ptype_path, sys_param_in), SIMPLE_PARAM("statbuf", &ptype_voidp, sys_param_out), }, }, { .sys_n = FSTAT_SYSCALL_N, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("fd", &ptype_int, sys_param_in), SIMPLE_PARAM("statbuf", &ptype_voidp, sys_param_out), }, }, { .sys_n = SYS_execve, .n_params = 3, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("filename", &ptype_path, sys_param_in), SIMPLE_PARAM("argv", &ptype_voidp, sys_param_in), SIMPLE_PARAM("envp", &ptype_voidp, sys_param_in), }, }, { .sys_n = SYS_brk, .n_params = 1, .exp_block = false, .ret_type = &ptype_voidp, .params = { SIMPLE_PARAM("vaddr", &ptype_voidp, sys_param_in), } }, #ifdef __i386__ /* waitpid is old and has been supported on amd64. Replacement: wait4 */ { .sys_n = SYS_waitpid, .n_params = 3, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("pid", &ptype_int, sys_param_in), SIMPLE_PARAM("wstatus", &ptype_voidp, sys_param_out), SIMPLE_PARAM("options", &ptype_int, sys_param_in), } }, #endif { .sys_n = SYS_wait4, .n_params = 4, .exp_block = true, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("pid", &ptype_int, sys_param_in), SIMPLE_PARAM("wstatus", &ptype_voidp, sys_param_out), SIMPLE_PARAM("options", &ptype_int, sys_param_in), SIMPLE_PARAM("rusage", &ptype_voidp, sys_param_out), } }, { .sys_n = SYS_umask, .n_params = 1, .exp_block = false, .ret_type = &ptype_oct, .params = { SIMPLE_PARAM("mask", &ptype_oct, sys_param_in), }, }, { .sys_n = SYS_ioctl, .n_params = 3, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("fd", &ptype_int, sys_param_in), SIMPLE_PARAM("request", &ptype_voidp, sys_param_in), SIMPLE_PARAM("argp", &ptype_voidp, sys_param_in), }, }, { .sys_n = FCNTL_SYSCALL_N, .n_params = 3, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("fd", &ptype_int, sys_param_in), SIMPLE_PARAM("cmd", &ptype_voidp, sys_param_in), SIMPLE_PARAM("arg", &ptype_voidp, sys_param_in), }, }, { .sys_n = SYS_uname, .n_params = 1, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("buf", &ptype_voidp, sys_param_in), }, }, { .sys_n = SYS_rt_sigaction, .n_params = 4, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("signum", &ptype_int, sys_param_in), SIMPLE_PARAM("act", &ptype_voidp, sys_param_in), SIMPLE_PARAM("oldact", &ptype_voidp, sys_param_in), SIMPLE_PARAM("sigsetsize", &ptype_int, sys_param_in), }, }, { .sys_n = SYS_rt_sigprocmask, .n_params = 4, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("how", &ptype_int, sys_param_in), SIMPLE_PARAM("set", &ptype_voidp, sys_param_in), SIMPLE_PARAM("oldset", &ptype_voidp, sys_param_in), SIMPLE_PARAM("sigsetsize", &ptype_int, sys_param_in), }, }, { .sys_n = SYS_pipe, .n_params = 1, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("pipefd", &ptype_int32_pair, sys_param_out), } }, { .sys_n = SYS_pipe2, .n_params = 2, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("pipefd", &ptype_int32_pair, sys_param_out), SIMPLE_PARAM("flags", &ptype_open_flags, sys_param_in), } }, { .sys_n = SYS_set_thread_area, .n_params = 1, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("u_info", &ptype_voidp, sys_param_in), } }, { .sys_n = SYS_prctl, .n_params = 1, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("option", &ptype_int, sys_param_in), } }, { .sys_n = MMAP_SYSCALL_N, .n_params = 6, .exp_block = false, .ret_type = &ptype_errno_or_ptr, .params = { SIMPLE_PARAM("addr", &ptype_voidp, sys_param_in), SIMPLE_PARAM("len", &ptype_int, sys_param_in), SIMPLE_PARAM("prot", &ptype_int, sys_param_in), SIMPLE_PARAM("flags", &ptype_int, sys_param_in), SIMPLE_PARAM("fd", &ptype_int, sys_param_in), SIMPLE_PARAM("pgoffset", &ptype_int, sys_param_in), } }, { .sys_n = SYS_set_tid_address, .n_params = 1, .exp_block = false, .ret_type = &ptype_voidp, .params = { SIMPLE_PARAM("tidptr", &ptype_voidp, sys_param_in), }, }, #ifdef __i386__ { .sys_n = SYS_llseek, .n_params = 5, .exp_block = false, .ret_type = &ptype_errno_or_val, .params = { SIMPLE_PARAM("fd", &ptype_int, sys_param_in), COMPLEX_PARAM("off", &ptype_doff64, sys_param_in, "off_low"), HIDDEN_PARAM("off_low", &ptype_int, sys_param_in), SIMPLE_PARAM("result", &ptype_u64_ptr, sys_param_out), SIMPLE_PARAM("whence", &ptype_whence, sys_param_in), }, }, #endif #else /* * TODO: add tracing metadata for AARCH64 */ #endif { .sys_n = INVALID_SYSCALL }, }; const struct syscall_info *tracing_metadata = __tracing_metadata; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/list.h> #include <tilck/kernel/user.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/rwlock.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/bintree.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/process_mm.h> #include <dirent.h> // system header struct ramfs_inode; struct ramfs_block { struct bintree_node node; offt offset; /* MUST BE divisible by PAGE_SIZE */ void *vaddr; }; /* * Ramfs entries do not *necessarily* need to have a fixed size, as they are * allocated dynamically on the heap. Said that, a fixed-size entry struct is * simpler to manage and faster to alloc/free, in particular with Tilck's * current kmalloc implementation. */ #define RAMFS_ENTRY_SIZE 256 #define RAMFS_ENTRY_MAX_LEN ( \ RAMFS_ENTRY_SIZE \ - sizeof(struct bintree_node) \ - sizeof(struct list_node) \ - sizeof(struct ramfs_inode *) \ - sizeof(u8) \ ) struct ramfs_entry { struct bintree_node node; struct list_node lnode; struct ramfs_inode *inode; u8 name_len; /* NOTE: includes the final \0 */ char name[RAMFS_ENTRY_MAX_LEN]; }; STATIC_ASSERT(sizeof(struct ramfs_entry) == RAMFS_ENTRY_SIZE); struct ramfs_inode { /* * Inode's ref-count is the number of file handles currently pointing to * this inode. */ REF_COUNTED_OBJECT; tilck_ino_t ino; enum vfs_entry_type type; struct rwlock_wp rwlock; nlink_t nlink; mode_t mode; size_t blocks_count; /* count of page-size blocks */ struct ramfs_inode *parent_dir; struct list mappings_list; /* see ramfs_unmap_past_eof_mappings() */ union { /* valid when type == VFS_FILE */ struct { offt fsize; struct ramfs_block *blocks_tree_root; }; /* valid when type == VFS_DIR */ struct { offt num_entries; struct ramfs_entry *entries_tree_root; struct list entries_list; struct list handles_list; }; /* valid when type == VFS_SYMLINK */ struct { size_t path_len; char *path; }; }; /* TODO: consider introducing `atime` */ struct k_timespec64 mtime; struct k_timespec64 ctime; }; struct ramfs_handle { /* struct fs_handle_base */ FS_HANDLE_BASE_FIELDS /* ramfs-specific fields */ struct ramfs_inode *inode; /* valid only if inode->type == VFS_DIR */ struct { struct list_node node; /* node in inode->handles_list */ struct ramfs_entry *dpos; /* current entry position */ }; }; STATIC_ASSERT(sizeof(struct ramfs_handle) <= MAX_FS_HANDLE_SIZE); struct ramfs_data { struct rwlock_wp rwlock; tilck_ino_t next_inode_num; struct ramfs_inode *root; }; CREATE_FS_PATH_STRUCT(ramfs_path, struct ramfs_inode *, struct ramfs_entry *); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/process.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/errno.h> #include <elf.h> #include <multiboot.h> void dump_stacktrace(void *ebp, pdir_t *pdir) { NOT_IMPLEMENTED(); } void dump_regs(regs_t *r) { NOT_IMPLEMENTED(); } <file_sep>#!/usr/bin/env bash pkg="$1" ci= if [ "$1" == "-ci" ]; then pkg="$2" ci=1 fi if [ "$ci" == 1 ]; then cmd="zypper refresh" else cmd="sudo zypper refresh" fi echo "Running the command: $cmd" eval $cmd <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <multiboot.h> static ALWAYS_INLINE bool use_framebuffer(void) { extern bool __use_framebuffer; return __use_framebuffer; } void set_framebuffer_info_from_mbi(multiboot_info_t *mbi); void init_fb_console(void); // Debug/devel function void debug_dump_glyph(u32 n); // Runtime debug info funcs [debugpanel] struct fb_console_info { u16 res_x; u16 res_y; u16 bpp; u16 font_h; u16 font_w; }; bool fb_is_using_opt_funcs(void); void fb_console_get_info(struct fb_console_info *i); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <cstdio> #include <cstdint> #include <cstdlib> #include <cstring> #include <cassert> #include <iostream> #include <vector> #include <unordered_map> #include <random> using namespace std; extern "C" { #include <tilck/common/utils.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/kmalloc.h> #include <kernel/kmalloc/kmalloc_heap_struct.h> // kmalloc private header #include <kernel/kmalloc/kmalloc_block_node.h> // kmalloc private header #include <tilck/kernel/test/mem_regions.h> #include <tilck/kernel/test/kmalloc.h> extern bool suppress_printk; void *kernel_va = nullptr; static unordered_map<ulong, ulong> mappings; void initialize_test_kernel_heap() { const ulong test_mem_size = 256 * MB; if (kernel_va != nullptr) { bzero(kernel_va, test_mem_size); mappings.clear(); return; } kernel_va = aligned_alloc(MB, test_mem_size); bzero(kernel_va, test_mem_size); mem_regions_count = 1; mem_regions[0] = (struct mem_region) { .addr = 0, .len = test_mem_size, .type = MULTIBOOT_MEMORY_AVAILABLE, .extra = 0, }; } void init_kmalloc_for_tests() { bzero(&kmalloc_initialized, sizeof(kmalloc_initialized)); bzero((void *)&first_heap_struct, sizeof(first_heap_struct)); bzero(&heaps, sizeof(heaps)); bzero(&used_heaps, sizeof(used_heaps)); bzero(&max_tot_heap_mem_free, sizeof(max_tot_heap_mem_free)); initialize_test_kernel_heap(); suppress_printk = true; early_init_kmalloc(); init_kmalloc(); suppress_printk = false; } int map_page(pdir_t *, void *vaddr, ulong paddr, u32 pg_flags) { ASSERT(!((ulong)vaddr & OFFSET_IN_PAGE_MASK)); // check page-aligned ASSERT(!(paddr & OFFSET_IN_PAGE_MASK)); // check page-aligned mappings[(ulong)vaddr] = paddr; return 0; } size_t map_pages(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, u32 pg_flags) { for (size_t i = 0; i < page_count; i++) { int rc = map_page(pdir, (char *)vaddr + (i << PAGE_SHIFT), paddr + (i << PAGE_SHIFT), 0); VERIFY(rc == 0); } return page_count; } void unmap_page(pdir_t *, void *vaddrp, bool free_pageframe) { mappings[(ulong)vaddrp] = INVALID_PADDR; } int unmap_page_permissive(pdir_t *, void *vaddrp, bool free_pageframe) { unmap_page(nullptr, vaddrp, free_pageframe); return 0; } void unmap_pages(pdir_t *pdir, void *vaddr, size_t count, bool do_free) { for (size_t i = 0; i < count; i++) { unmap_page(pdir, (char *)vaddr + (i << PAGE_SHIFT), do_free); } } size_t unmap_pages_permissive(pdir_t *pd, void *va, size_t count, bool do_free) { for (size_t i = 0; i < count; i++) { unmap_page_permissive(pd, (char *)va + (i << PAGE_SHIFT), do_free); } return count; } bool is_mapped(pdir_t *, void *vaddrp) { ulong vaddr = (ulong)vaddrp & PAGE_MASK; if (vaddr + PAGE_SIZE < LINEAR_MAPPING_END) return true; return mappings.find(vaddr) != mappings.end(); } ulong get_mapping(pdir_t *, void *vaddrp) { return mappings[(ulong)vaddrp]; } int virtual_read(pdir_t *pdir, void *extern_va, void *dest, size_t len) { memcpy(dest, extern_va, len); return 0; } int virtual_write(pdir_t *pdir, void *extern_va, void *src, size_t len) { memcpy(extern_va, src, len); return 0; } } // extern "C" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> int debug_qemu_turn_off_machine(void) { if (!in_hypervisor()) return -ENXIO; outb(0xf4, 0x00); return -EIO; } void dump_raw_stack(ulong addr) { printk("Raw stack dump:\n"); for (int i = 0; i < 36; i += 4) { printk("%p: ", TO_PTR(addr)); for (int j = 0; j < 4; j++) { printk("%p ", *(void **)addr); addr += sizeof(ulong); } printk("\n"); } } void dump_eflags(u32 f) { printk("eflags: %p [ %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s], IOPL: %u\n", TO_PTR(f), f & EFLAGS_CF ? "CF " : "", f & EFLAGS_PF ? "PF " : "", f & EFLAGS_AF ? "AF " : "", f & EFLAGS_ZF ? "ZF " : "", f & EFLAGS_SF ? "SF " : "", f & EFLAGS_TF ? "TF " : "", f & EFLAGS_IF ? "IF " : "", f & EFLAGS_DF ? "DF " : "", f & EFLAGS_OF ? "OF " : "", f & EFLAGS_NT ? "NT " : "", f & EFLAGS_RF ? "RF " : "", f & EFLAGS_VM ? "VM " : "", f & EFLAGS_AC ? "AC " : "", f & EFLAGS_VIF ? "VIF " : "", f & EFLAGS_VIP ? "VIP " : "", f & EFLAGS_ID ? "ID " : "", f & EFLAGS_IOPL); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static offt sysfs_call_load(struct sysobj *obj, struct sysobj_prop *prop, void *prop_data, void *load_buf, offt buf_len, offt off) { offt rc; if (obj->hooks && obj->hooks->pre_load) { rc = obj->hooks->pre_load(obj, prop, prop_data); if (rc < 0) return rc; } rc = prop->type->load(obj, prop_data, load_buf, buf_len, off); if (obj->hooks && obj->hooks->post_load) obj->hooks->post_load(obj, prop, prop_data); return rc; } static offt sysfs_call_store(struct sysobj *obj, struct sysobj_prop *prop, void *prop_data, void *buf, offt buf_len) { offt rc; if (obj->hooks && obj->hooks->pre_store) { rc = obj->hooks->pre_store(obj, prop, prop_data); if (rc < 0) return rc; } rc = prop->type->store(obj, prop_data, buf, buf_len); if (obj->hooks && obj->hooks->post_store) obj->hooks->post_store(obj, prop, prop_data); return rc; } static int sysfs_load_data(struct sysfs_handle *h) { struct sysfs_inode *i = h->inode; struct sysobj_prop *prop = i->file.prop; struct sysobj *obj = i->file.obj; void *prop_data = i->file.prop_data; void *data; offt rc; ASSERT(!h->file.data); ASSERT(!h->file.data_len); ASSERT(h->file.data_max_len > 0); ASSERT(prop->type); data = kmalloc((size_t)h->file.data_max_len); if (!data) return -ENOMEM; rc = sysfs_call_load(obj, prop, prop_data, data, h->file.data_max_len, 0); if (rc < 0) { kfree2(data, (size_t)h->file.data_max_len); return (int)rc; } disable_preemption(); { h->file.data = data; h->file.data_len = rc; } enable_preemption(); return 0; } static void sysfs_flush_data(struct sysfs_handle *sh) { ASSERT(sh->type == VFS_FILE); struct sysfs_inode *i = sh->inode; struct sysobj_prop *prop = i->file.prop; struct sysobj *obj = i->file.obj; void *prop_data = i->file.prop_data; offt data_len = sh->file.data_len; void *data = sh->file.data; ASSERT(prop->type); ASSERT(sh->file.data_max_len > 0); ASSERT(sh->file.data != NULL); disable_preemption(); { if (list_is_node_in_list(&sh->file.dirty_node)) { /* We have to flush our buffer with a store() operation */ if (sysfs_call_store(obj, prop, prop_data, data, data_len) >= 0) { list_remove(&sh->file.dirty_node); list_node_init(&sh->file.dirty_node); } else { /* We ignore a failure in this case */ } } } enable_preemption(); } static void sysfs_free_data(struct sysfs_handle *sh) { /* Reset the data* fields the way sysfs_load_data() expects them */ ASSERT(!list_is_node_in_list(&sh->file.dirty_node)); if (sh->file.data) { kfree2(sh->file.data, (size_t)sh->file.data_max_len); } sh->file.data = NULL; sh->file.data_len = 0; } static void sysfs_flush_and_free_data(struct sysfs_handle *sh) { sysfs_flush_data(sh); sysfs_free_data(sh); } static int sysfs_fsync(fs_handle h) { struct sysfs_handle *sh = h; if (sh->file.data_max_len > 0) { if (sh->file.data) sysfs_flush_data(sh); } return 0; } static ssize_t sysfs_file_read(fs_handle h, char *buf, size_t len, offt *pos) { struct sysfs_handle *sh = h; struct sysfs_inode *i = sh->inode; struct sysobj_prop *prop = i->file.prop; struct sysobj *obj = i->file.obj; void *pd = i->file.prop_data; offt rc, rem; if (!prop->type || !prop->type->load) return 0; if (LIKELY(sh->file.data_max_len == 0)) { if (*pos == 0) { rc = sysfs_call_load(obj, prop, pd, buf, (offt)len, 0); *pos = LONG_MAX; } else { rc = 0; } } else if (sh->file.data_max_len < 0) { rc = sysfs_call_load(obj, prop, pd, buf, (offt)len, *pos); if (rc > 0) *pos += rc; } else { if (!sh->file.data) { if ((rc = sysfs_load_data(sh))) return 0; /* no memory for the per-handle buffer */ } rem = sh->file.data_len - *pos; ASSERT(rem >= 0); rc = CLAMP(rem, 0, (offt)len); memcpy(buf, sh->file.data + *pos, (size_t)rc); *pos += rc; } return (ssize_t)rc; } static ssize_t sysfs_file_write(fs_handle h, char *buf, size_t len, offt *pos) { struct sysfs_handle *sh = h; struct sysfs_inode *i = sh->inode; struct sysobj_prop *prop = i->file.prop; struct sysobj *obj = i->file.obj; void *pd = i->file.prop_data; struct sysfs_data *d = sh->fs->device_data; offt rc, rem; if (!prop->type || !prop->type->store) return -EINVAL; if (LIKELY(sh->file.data_max_len == 0)) { rc = sysfs_call_store(obj, prop, pd, buf, (offt)len); } else if (UNLIKELY(sh->file.data_max_len < 0)) { /* * In this case there should be NO store function at all. But, it's worth * keeping this else-if case in allow any kind of weird sharing of * property types across properties and because of the symmetry with * the read case above. */ rc = -EINVAL; } else { if (!sh->file.data) { if ((rc = sysfs_load_data(sh))) return -ENOSPC; /* no memory for the per-handle buffer */ } rem = sh->file.data_max_len - *pos; ASSERT(rem >= 0); rc = CLAMP(rem, 0, (offt)len); memcpy(sh->file.data + *pos, buf, (size_t)rc); *pos += rc; disable_preemption(); { if (*pos > sh->file.data_len) sh->file.data_len = *pos; list_add_tail(&d->dirty_handles, &sh->file.dirty_node); } enable_preemption(); } return (ssize_t)rc; } static int sysfs_file_ioctl(fs_handle h, ulong request, void *arg) { return -EINVAL; } static offt sysfs_file_seek(fs_handle h, offt target_off, int whence) { struct sysfs_handle *sh = h; const offt len = ABS(sh->file.data_max_len); offt new_pos = sh->h_fpos; switch (whence) { case SEEK_SET: new_pos = target_off; break; case SEEK_CUR: new_pos += target_off; break; case SEEK_END: new_pos = len + target_off; break; default: return -EINVAL; } if (new_pos < 0 || (!len && new_pos > 0)) return -EINVAL; sh->h_fpos = new_pos; return new_pos; } static void sysfs_on_close(fs_handle h) { struct sysfs_handle *sh = h; if (sh->type != VFS_FILE) return; if (sh->file.data_max_len > 0 && sh->file.data) { sysfs_flush_and_free_data(sh); } } static int sysfs_on_dup(fs_handle new_h) { struct sysfs_handle *h2 = new_h; if (h2->type != VFS_FILE) return 0; if (!h2->inode->file.prop->type) return 0; if (h2->file.data_max_len > 0) { if (h2->file.data) { /* * Flush the data in the buffers using the old handle in order to * guarantee up-to-date data in case userland code decides to write * on the file using the new handle. */ sysfs_flush_data(h2); /* * Reset the data field in the new handle: it will be reloaded on * demand in case of read/write. */ h2->file.data = NULL; sysfs_free_data(h2); /* performs just reset */ } } return 0; } int sysfs_mmap(struct user_mapping *um, pdir_t *pdir, int flags) { struct sysfs_handle *sh = um->h; struct sysfs_inode *inode = sh->inode; struct sysobj_prop *prop = inode->file.prop; const struct sysobj_prop_type *pt = prop->type; const size_t pg_count = um->len >> PAGE_SHIFT; ulong vaddr = um->vaddr; size_t mapped_cnt, buf_sz; void *data = NULL; if (sh->type != VFS_FILE) return -EACCES; if (flags & VFS_MM_DONT_MMAP) return 0; if (sh->file.data_max_len >= 0) return -EACCES; /* Do not support mmap in the = 0 and > 0 cases */ buf_sz = (size_t)ABS(sh->file.data_max_len); if (!pt || !pt->get_data_ptr) return -EACCES; data = pt->get_data_ptr(inode->file.obj, inode->file.prop_data); if (!data) return -EACCES; if (um->off + um->len > buf_sz) return -EACCES; mapped_cnt = map_pages(pdir, (void *)vaddr, KERNEL_VA_TO_PA(data) + um->off, pg_count, PAGING_FL_US | PAGING_FL_SHARED); if (mapped_cnt != pg_count) { unmap_pages_permissive(pdir, (void *)vaddr, mapped_cnt, false); return -ENOMEM; } return 0; } int sysfs_munmap(struct user_mapping *um, void *vaddrp, size_t len) { struct sysfs_handle *sh = um->h; if (sh->type != VFS_FILE) return -EACCES; if (sh->file.data_max_len >= 0) return -EACCES; /* Do not support mmap in the = 0 and > 0 cases */ return generic_fs_munmap(um, vaddrp, len); } static const struct file_ops static_ops_file_sysfs = { .read = sysfs_file_read, .write = sysfs_file_write, .seek = sysfs_file_seek, .ioctl = sysfs_file_ioctl, .mmap = sysfs_mmap, .munmap = sysfs_munmap, .sync = sysfs_fsync, .datasync = sysfs_fsync, }; static int sysfs_open_file(struct mnt_fs *fs, struct sysfs_inode *pos, fs_handle *out) { struct sysfs_handle *h; struct sysobj_prop *prop = pos->file.prop; void *prop_data = pos->file.prop_data; offt buf_sz = 0, rc; if (prop->type) { if (prop->type->get_buf_sz) buf_sz = prop->type->get_buf_sz(pos->file.obj, prop_data); } if (!(h = vfs_create_new_handle(fs, &static_ops_file_sysfs))) return -ENOMEM; h->type = VFS_FILE; h->file.data = NULL; h->file.data_len = 0; h->file.data_max_len = buf_sz; h->spec_flags = VFS_SPFL_NO_LF; h->inode = pos; list_node_init(&h->file.dirty_node); retain_obj(pos); if (h->file.data_max_len > 0) { if ((rc = sysfs_load_data(h))) { vfs_close(h); return (int)rc; } } *out = h; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/elf_types.h> #include <tilck/common/utils.h> #include <elf.h> /* * NOTE[1]: the code is in a source-header (.c.h) in order to avoid it to be * compiled and linked in binaries that don't need it, with the whole package * of C files in common/. * * NOTE[2]: this file uses Tilck's generic ELF types (Elf_Ehdr instead of * Elf_Ehdr32 etc.). In your code, you might need to define USE_ELF32 or * USE_ELF64 to work with ELF files having bitness different than your NBITS. */ static Elf_Shdr * elf_get_section(Elf_Ehdr *h, const char *section_name) { Elf_Shdr *sections = (Elf_Shdr *) ((char *)h + h->e_shoff); Elf_Shdr *section_header_strtab = sections + h->e_shstrndx; for (uint32_t i = 0; i < h->e_shnum; i++) { Elf_Shdr *s = sections + i; char *name = (char *)h + section_header_strtab->sh_offset + s->sh_name; if (!strcmp(name, section_name)) { return s; } } return NULL; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once extern u32 font_w; extern u32 font_h; extern u32 vga_rgb_colors[16]; extern bool __use_framebuffer; u32 fb_get_width(void); u32 fb_get_height(void); u32 fb_get_bpp(void); void fb_map_in_kernel_space(void); void fb_raw_color_lines(u32 iy, u32 h, u32 color); void fb_draw_cursor_raw(u32 ix, u32 iy, u32 color); void fb_draw_char_failsafe(u32 x, u32 y, u16 entry); void fb_draw_char_optimized(u32 x, u32 y, u16 e); void fb_draw_row_optimized(u32 y, u16 *entries, u32 count, bool fpu); void fb_copy_from_screen(u32 ix, u32 iy, u32 w, u32 h, u32 *buf); void fb_copy_to_screen(u32 ix, u32 iy, u32 w, u32 h, u32 *buf); void fb_lines_shift_up(u32 src_y, u32 dst_y, u32 lines_count); bool fb_pre_render_char_scanlines(void); bool fb_alloc_shadow_buffer(void); void fb_raw_perf_screen_redraw(u32 color, bool use_fpu); void fb_set_font(void *font); void fb_draw_banner(void); void fb_fill_fix_info(void *fix_info); void fb_fill_var_info(void *var_info); int fb_user_mmap(pdir_t *pdir, void *vaddr, size_t mmap_len); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int ramfs_stat_nolock(struct mnt_fs *fs, struct ramfs_inode *inode, struct k_stat64 *statbuf) { ASSERT(inode); if ((inode->parent_dir->mode & 0500) != 0500) /* read + execute */ return -EACCES; bzero(statbuf, sizeof(struct k_stat64)); statbuf->st_dev = fs->device_id; statbuf->st_ino = inode->ino; statbuf->st_mode = inode->mode; statbuf->st_nlink = inode->nlink; statbuf->st_uid = 0; /* root */ statbuf->st_gid = 0; /* root */ statbuf->st_rdev = 0; /* device ID if a special file: therefore, NO. */ switch (inode->type) { case VFS_FILE: statbuf->st_size = (typeof(statbuf->st_size)) inode->fsize; break; case VFS_DIR: statbuf->st_size = (typeof(statbuf->st_size)) (inode->num_entries * (offt) sizeof(struct ramfs_entry)); break; case VFS_SYMLINK: statbuf->st_size = (typeof(statbuf->st_size)) inode->path_len; break; default: NOT_IMPLEMENTED(); break; } statbuf->st_blksize = PAGE_SIZE; statbuf->st_blocks = (typeof(statbuf->st_blocks)) (inode->blocks_count * (PAGE_SIZE / 512)); statbuf->st_ctim = to_stat_timespec(inode->ctime); statbuf->st_mtim = to_stat_timespec(inode->mtime); statbuf->st_atim = to_stat_timespec(inode->mtime); return 0; } static int ramfs_stat(struct mnt_fs *fs, vfs_inode_ptr_t i, struct k_stat64 *statbuf) { struct ramfs_inode *inode = i; int rc; if (!inode) return -ENOENT; rwlock_wp_shlock(&inode->rwlock); { rc = ramfs_stat_nolock(fs, inode, statbuf); } rwlock_wp_shunlock(&inode->rwlock); return rc; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/bintree.h> #include <tilck/kernel/list.h> #include "se_data.h" struct simple_obj { struct bintree_node bnode; struct list_node lnode; ulong value; }; static long sobj_cmp(const void *a, const void *value) { const struct simple_obj *e1 = a; return (long)e1->value - *(const long*)value; } NO_INLINE static struct simple_obj * find_obj_with_bst(struct bintree_node *bst_root, ulong value) { return bintree_find_ptr(bst_root, value, struct simple_obj, bnode, value); } NO_INLINE static struct simple_obj * find_obj_with_bst2(struct bintree_node *bst_root, ulong value) { return bintree_find(bst_root, &value, &sobj_cmp, struct simple_obj, bnode); } NO_INLINE static struct simple_obj * find_obj_with_list(struct list *nodes_list_ref, ulong value) { struct simple_obj *pos; list_for_each_ro(pos, nodes_list_ref, lnode) { if (pos->value == value) return pos; } return NULL; } static void do_bintree_perf_test(u32 elems, bool lookup, struct simple_obj *(*bst_lookup)( struct bintree_node *, ulong )) { struct bintree_node *bst_root = NULL; struct list nodes_list; struct simple_obj *obj; struct simple_obj *nodes; u64 start, duration; u32 bst_cycles, list_cycles; const u32 iters = 100; VERIFY(elems <= RANDOM_VALUES_COUNT); kernel_yield(); if (se_is_stop_requested()) return; nodes = kalloc_array_obj(struct simple_obj, elems); if (!nodes) panic("No enough memory to alloc `nodes`"); list_init(&nodes_list); for (u32 i = 0; i < elems; i++) { bintree_node_init(&nodes[i].bnode); list_node_init(&nodes[i].lnode); nodes[i].value = random_values[i]; } disable_preemption(); start = RDTSC(); for (u32 i = 0; i < elems; i++) { bintree_insert_ptr(&bst_root, &nodes[i], struct simple_obj, bnode, value); } duration = RDTSC() - start; bst_cycles = (u32)(duration / elems); start = RDTSC(); for (u32 i = 0; i < elems; i++) { list_add_tail(&nodes_list, &nodes[i].lnode); } duration = RDTSC() - start; list_cycles = (u32)(duration / elems); if (lookup) { start = RDTSC(); for (u32 j = 0; j < iters; j++) { for (u32 i = 0; i < elems; i++) { obj = bst_lookup(bst_root, random_values[i]); ASSERT(obj != NULL); (void)obj; } } duration = RDTSC() - start; bst_cycles = (u32)(duration / (iters * elems)); start = RDTSC(); for (u32 j = 0; j < iters; j++) { for (u32 i = 0; i < elems; i++) { obj = find_obj_with_list(&nodes_list, random_values[i]); ASSERT(obj != NULL); (void)obj; } } duration = RDTSC() - start; list_cycles = (u32)(duration / (iters * elems)); } enable_preemption(); printk(" %5u | %5u | %5u \n", elems, bst_cycles, list_cycles); kfree_array_obj(nodes, struct simple_obj, elems); } void selftest_bintree_perf(void) { static const u32 lookup_elems[] = { 10, 15, 20, 25, 35, 50, 75, 100, 250, 500, 1000 }; printk("Tilck's BST ptr-lookup performance compared to linked list\n"); printk("\n"); printk(" elems | bst | list\n"); printk("-------------+------------+--------------\n"); for (int i = 0; i < ARRAY_SIZE(lookup_elems); i++) { do_bintree_perf_test(lookup_elems[i], true, find_obj_with_bst); if (se_is_stop_requested()) return; } printk("\n"); printk("Tilck's BST generic-lookup performance compared to linked list\n"); printk("\n"); printk(" elems | bst | list\n"); printk("-------------+------------+--------------\n"); for (int i = 0; i < ARRAY_SIZE(lookup_elems); i++) { do_bintree_perf_test(lookup_elems[i], true, find_obj_with_bst2); if (se_is_stop_requested()) return; } printk("\n"); printk("Tilck's BST insert performance compared to linked list\n"); printk("\n"); printk(" elems | bst | list\n"); printk("-------------+------------+--------------\n"); do_bintree_perf_test(250, false, NULL); do_bintree_perf_test(500, false, NULL); do_bintree_perf_test(1000, false, NULL); printk("\n"); printk("\n"); } REGISTER_SELF_TEST(bintree_perf, se_med, &selftest_bintree_perf) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define __SYSCALLS_C__ #include <tilck/common/basic_defs.h> #include <tilck/common/build_info.h> #include <tilck/common/string_util.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/user.h> #include <tilck/kernel/process.h> #include <tilck/kernel/signal.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/fs/vfs.h> #define LINUX_REBOOT_MAGIC1 0xfee1dead #define LINUX_REBOOT_MAGIC2 672274793 #define LINUX_REBOOT_MAGIC2A 85072278 #define LINUX_REBOOT_MAGIC2B 369367448 #define LINUX_REBOOT_MAGIC2C 537993216 #define LINUX_REBOOT_CMD_RESTART 0x1234567 #define LINUX_REBOOT_CMD_RESTART2 0xa1b2c3d4 #define LINUX_REBOOT_CMD_HALT 0xcdef0123 #define LINUX_REBOOT_CMD_POWER_OFF 0x4321fedc int sys_madvise(void *addr, size_t len, int advice) { // TODO (future): consider implementing at least part of sys_madvice(). return 0; } int do_nanosleep(const struct k_timespec64 *req, struct k_timespec64 *rem) { u64 ticks_to_sleep; u64 exp_wake_up_ticks; ticks_to_sleep = timespec_to_ticks(req); exp_wake_up_ticks = get_ticks() + ticks_to_sleep; kernel_sleep(ticks_to_sleep); /* After wake-up */ rem->tv_sec = 0; rem->tv_nsec = 0; if (pending_signals()) { u64 ticks = get_ticks(); if (ticks < exp_wake_up_ticks) ticks_to_timespec(exp_wake_up_ticks - ticks, rem); return -EINTR; } return 0; } int sys_nanosleep_time32(const struct k_timespec32 *user_req, struct k_timespec32 *user_rem) { struct k_timespec32 req32; struct k_timespec64 req; struct k_timespec32 rem32; struct k_timespec64 rem; int rc; if (copy_from_user(&req32, user_req, sizeof(req))) return -EFAULT; req = (struct k_timespec64) { .tv_sec = req32.tv_sec, .tv_nsec = req32.tv_nsec, }; rc = do_nanosleep(&req, &rem); if (user_rem) { rem32 = (struct k_timespec32) { .tv_sec = (s32) rem.tv_sec, .tv_nsec = rem.tv_nsec, }; if (copy_to_user(user_rem, &rem32, sizeof(rem32))) return -EFAULT; } return rc; } int sys_newuname(struct utsname *user_buf) { struct commit_hash_and_date comm; struct utsname buf = {0}; extract_commit_hash_and_date(&tilck_build_info, &comm); strcpy(buf.sysname, "Tilck"); strcpy(buf.nodename, "tilck"); strcpy(buf.version, comm.hash); strcpy(buf.release, tilck_build_info.ver); strcpy(buf.machine, tilck_build_info.arch); if (copy_to_user(user_buf, &buf, sizeof(struct utsname)) < 0) return -EFAULT; return 0; } NORETURN int sys_exit(int exit_status) { terminate_process(exit_status, 0 /* term_sig */); /* Necessary to guarantee to the compiler that we won't return. */ NOT_REACHED(); } NORETURN int sys_exit_group(int status) { // TODO: update when user threads are supported sys_exit(status); } ulong sys_times(struct tms *user_buf) { struct task *curr = get_curr_task(); struct tms buf; // TODO (threads): when threads are supported, update sys_times() // TODO: consider supporting tms_cutime and tms_cstime in sys_times() disable_preemption(); { buf = (struct tms) { .tms_utime = (clock_t) curr->ticks.total, .tms_stime = (clock_t) curr->ticks.total_kernel, .tms_cutime = 0, .tms_cstime = 0, }; } enable_preemption(); if (copy_to_user(user_buf, &buf, sizeof(buf)) != 0) return (ulong) -EBADF; return (ulong) get_ticks(); } int sys_fork(void) { return do_fork(false); } int sys_vfork(void) { return do_fork(true); } static int stop_all_user_tasks(void *task, void *unused) { struct task *ti = task; if (!is_kernel_thread(ti) && ti != get_curr_task()) { printk("Stopping TID %d\n", ti->tid); ti->stopped = true; } return 0; } static void kernel_shutdown(void) { /* This is just a stub */ extern volatile bool __in_kernel_shutdown; __in_kernel_shutdown = true; printk("The system is shutting down.\n"); disable_preemption(); { iterate_over_tasks(&stop_all_user_tasks, NULL); } enable_preemption(); /* Give kernel threads a chance to run and complete their work */ for (int i = 0; i < 10; i++) kernel_yield(); printk("Shutdown complete.\n"); } int sys_reboot(u32 magic, u32 magic2, u32 cmd, void *arg) { if (magic != LINUX_REBOOT_MAGIC1) return -EINVAL; if (magic2 != LINUX_REBOOT_MAGIC2 && magic2 != LINUX_REBOOT_MAGIC2A && magic2 != LINUX_REBOOT_MAGIC2B && magic2 != LINUX_REBOOT_MAGIC2C) { return -EINVAL; } switch (cmd) { case LINUX_REBOOT_CMD_RESTART: case LINUX_REBOOT_CMD_RESTART2: kernel_shutdown(); reboot(); break; case LINUX_REBOOT_CMD_HALT: kernel_shutdown(); disable_interrupts_forced(); while (true) { halt(); } break; case LINUX_REBOOT_CMD_POWER_OFF: kernel_shutdown(); poweroff(); break; default: return -EINVAL; } return 0; } int sys_sched_yield(void) { kernel_yield(); return 0; } int sys_utimes(const char *u_path, const struct k_timeval u_times[2]) { struct k_timeval ts[2]; struct k_timespec64 new_ts[2]; char *path = get_curr_task()->args_copybuf; if (copy_str_from_user(path, u_path, MAX_PATH, NULL)) return -EFAULT; if (u_times) { if (copy_from_user(ts, u_times, sizeof(ts))) return -EFAULT; new_ts[0] = (struct k_timespec64) { .tv_sec = ts[0].tv_sec, .tv_nsec = ((long)ts[0].tv_usec) * 1000, }; new_ts[1] = (struct k_timespec64) { .tv_sec = ts[1].tv_sec, .tv_nsec = ((long)ts[1].tv_usec) * 1000, }; } else { /* * If `u_times` is NULL, the access and modification times of the file * are set to the current time. */ real_time_get_timespec(&new_ts[0]); new_ts[1] = new_ts[0]; } return vfs_utimens(path, new_ts); } int sys_utime32(const char *u_path, const struct k_utimbuf *u_times) { struct k_utimbuf ts; struct k_timespec64 new_ts[2]; char *path = get_curr_task()->args_copybuf; if (copy_from_user(&ts, u_times, sizeof(ts))) return -EFAULT; if (copy_str_from_user(path, u_path, MAX_PATH, NULL)) return -EFAULT; new_ts[0] = (struct k_timespec64) { .tv_sec = ts.actime, .tv_nsec = 0, }; new_ts[1] = (struct k_timespec64) { .tv_sec = ts.modtime, .tv_nsec = 0, }; return vfs_utimens(path, new_ts); } int sys_utimensat_time32(int dirfd, const char *u_path, const struct k_timespec32 times[2], int flags) { // TODO (future): consider implementing sys_utimensat() [modern] return -ENOSYS; } int sys_futimesat_time32(int dirfd, const char *u_path, const struct k_timeval times[2]) { // TODO (future): consider implementing sys_futimesat_time32() [obsolete] return -ENOSYS; } int sys_socketcall(int call, ulong *args) { return -ENOSYS; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/timer.h> #define KMUTEX_SEK_TH_ITERS 100000 #define KMUTEX_TH_COUNT 128 static struct kmutex test_mutex; static int sek_vars[3]; static const int sek_set_1[3] = {1, 2, 3}; static const int sek_set_2[3] = {10, 20, 30}; static int tids[KMUTEX_TH_COUNT]; static int tid_by_idx1[KMUTEX_TH_COUNT]; static int tid_by_idx2[KMUTEX_TH_COUNT]; static volatile u8 ord_th_states[KMUTEX_TH_COUNT]; static volatile bool ord_test_done; static int idx1, idx2; static struct kmutex order_mutex; static void sek_set_vars(const int *set) { for (int i = 0; i < ARRAY_SIZE(sek_vars); i++) { sek_vars[i] = set[i]; kernel_yield(); } } static void sek_check_set_eq(const int *set) { for (int i = 0; i < ARRAY_SIZE(sek_vars); i++) { VERIFY(sek_vars[i] == set[i]); kernel_yield(); } } static void sek_thread(void *unused) { for (int iter = 0; iter < KMUTEX_SEK_TH_ITERS; iter++) { if (UNLIKELY(se_is_stop_requested())) { printk("sek_thread: STOP at iter %d/%d\n", iter, KMUTEX_SEK_TH_ITERS); break; } kmutex_lock(&test_mutex); { kernel_yield(); if (sek_vars[0] == sek_set_1[0]) { sek_check_set_eq(sek_set_1); sek_set_vars(sek_set_2); } else { sek_check_set_eq(sek_set_2); sek_set_vars(sek_set_1); } kernel_yield(); } kmutex_unlock(&test_mutex); debug_no_deadlock_set_report_progress(); } // for (int iter = 0; iter < KMUTEX_SEK_TH_ITERS; iter++) } void selftest_kmutex() { int local_tids[3]; kmutex_init(&test_mutex, 0); sek_set_vars(sek_set_1); debug_reset_no_deadlock_set(); for (int i = 0; i < 3; i++) { local_tids[i] = kthread_create(sek_thread, 0, NULL); VERIFY(local_tids[i] > 0); debug_add_task_to_no_deadlock_set(local_tids[i]); } debug_add_task_to_no_deadlock_set(get_curr_tid()); kthread_join_all(local_tids, ARRAY_SIZE(local_tids), true); debug_reset_no_deadlock_set(); kmutex_destroy(&test_mutex); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(kmutex, se_med, &selftest_kmutex) /* -------------------------------------------------- */ /* Recursive mutex test */ /* -------------------------------------------------- */ static void test_kmutex_thread(void *arg) { int tn = (int)(ulong)arg; printk("%i) before lock\n", tn); kmutex_lock(&test_mutex); printk("%i) under lock..\n", tn); // TODO: replace with delay_us() for (u32 i = 0; i < 128*MB; i++) { asmVolatile("nop"); } kmutex_unlock(&test_mutex); printk("%i) after lock\n", tn); } static void test_kmutex_thread_trylock() { printk("3) before trylock\n"); bool locked = kmutex_trylock(&test_mutex); if (locked) { printk("3) trylock SUCCEEDED: under lock..\n"); kmutex_unlock(&test_mutex); printk("3) after lock\n"); } else { printk("3) trylock returned FALSE\n"); } } void selftest_kmutex_rec() { bool success; int local_tids[3]; printk("kmutex recursive test\n"); kmutex_init(&test_mutex, KMUTEX_FL_RECURSIVE); kmutex_lock(&test_mutex); printk("Locked once\n"); kmutex_lock(&test_mutex); printk("Locked twice\n"); success = kmutex_trylock(&test_mutex); if (!success) { panic("kmutex_trylock() failed on the same thread"); } printk("Locked 3 times (last with trylock)\n"); local_tids[0] = kthread_create(test_kmutex_thread_trylock, 0, NULL); VERIFY(local_tids[0] > 0); kthread_join(local_tids[0], true); kmutex_unlock(&test_mutex); printk("Unlocked once\n"); kmutex_unlock(&test_mutex); printk("Unlocked twice\n"); kmutex_unlock(&test_mutex); printk("Unlocked 3 times\n"); local_tids[0] = kthread_create(&test_kmutex_thread, 0, (void*) 1); VERIFY(local_tids[0] > 0); local_tids[1] = kthread_create(&test_kmutex_thread, 0, (void*) 2); VERIFY(local_tids[1] > 0); local_tids[2] = kthread_create(&test_kmutex_thread_trylock, 0, NULL); VERIFY(local_tids[2] > 0); kthread_join_all(local_tids, ARRAY_SIZE(local_tids), true); kmutex_destroy(&test_mutex); se_regular_end(); } REGISTER_SELF_TEST(kmutex_rec, se_med, &selftest_kmutex_rec) /* -------------------------------------------------- */ /* Strong order test */ /* -------------------------------------------------- */ /* * HOW IT WORKS * -------------- * * The idea is to check that our kmutex implementation behaves like a strong * binary semaphore. In other words, if given task A tried to acquire the mutex * M before any given task B, on unlock() it MUST BE woken up and hold the mutex * BEFORE task B does. * * In order to do that, we create many threads and substantially make each one * of them to try to acquire the test_mutex. At the end, we would like to verify * that they acquired the mutex *in order*. But, what does *in order* mean? * How we do know which is the correct order? The creation of threads does NOT * have any order. For example: thread B, created AFTER thread A, may run before * it. Well, in order to do that, we use another mutex, called `order_mutex`. * Threads first get any order using `order_mutex` and then, in that order, they * try to acquire `test_mutex`. Of course, threads might be so fast that each * thread just acquires and releases both the mutexes without being preempted * and no thread really sleeps on kmutex_lock(). In order to prevent that, we * sleep while holding the `test_mutex`. For a better understanding, see the * comments below. */ static void kmutex_ord_th(void *arg) { int tid = get_curr_tid(); int local_id = (int)(long)arg; ord_th_states[local_id] = 1; /* * Since in practice, currently on Tilck, threads are executed pretty much * in the same order as they're created, we use the HACK below in order to * kind-of randomize the moment when they actually acquire the order_mutex, * simulating the general case where the `order_mutex` is strictly required. */ kernel_sleep( ((u32)tid / sizeof(void *)) % 7 ); ord_th_states[local_id] = 2; if (se_is_stop_requested()) goto end; ord_th_states[local_id] = 3; kmutex_lock(&order_mutex); { tid_by_idx1[idx1++] = tid; /* * Note: disabling the preemption while holding the lock! This is *not* * a good practice and MUST BE avoided everywhere in real code except in * this test, where HACKS are needed in order to test the properties of * kmutex itself. */ ord_th_states[local_id] = 4; disable_preemption(); } kmutex_unlock(&order_mutex); ord_th_states[local_id] = 5; /* * Note: calling kmutex_lock() with preemption disabled! This is even worse * than calling kmutex_unlock() with preemption disabled. By definition, * it should *never* work because acquiring the mutex may require this thread * to go to sleep, if it has already an owner. But, for the purposes of this * test, we really need nobody to be able to preempt this thread in the * period of time between the acquisition of `order_mutex` and the attempt to * acquire `test_mutex` because we used `order_mutex` exactly in order to * make the attempts to acquire `test_mutex` happen all together. Ultimately, * we're testing that, if all threads try to lock `test_mutex` at the same * time, they're gonna to ultimately acquire the lock in the same order they * called kmutex_lock(). */ kmutex_lock(&test_mutex); { /* * Note: here, the preemption is enabled, even if we called kmutex_lock() * with preemption disabled. That's because of the "magic" kmutex flag * KMUTEX_FL_ALLOW_LOCK_WITH_PREEMPT_DISABLED designed specifically for * this self test. It allows the lock to be called while preemption is * disabled and it enables preemption forcibly, no matter what, before * going to sleep. */ ord_th_states[local_id] = 6; ASSERT(is_preemption_enabled()); tid_by_idx2[idx2++] = tid; /* * After registering this thread at position `idx2`, now sleep for 1 tick * WHILE holding the lock, in order to force all the other tasks to sleep * on kmutex_lock(), creating a queue. This is another trick necessary to * check that strong ordering actually occurs. Without it, threads might * be so fast that they just: * * - acquire & release the order mutex without sleeping * - acquire & release the test mutex without sleeping * * Therefore, the whole test will be pointless. Now instead, when * KMUTEX_STATS_ENABLED is 1, we can check that the order_mutex has * typically max_num_waiters = 0, while the test mutex has max_num_waiters * equals to almost its maxiumum (127). Typically, it's ~122. */ if (!se_is_stop_requested()) { ord_th_states[local_id] = 7; kernel_sleep(1); ord_th_states[local_id] = 8; } } kmutex_unlock(&test_mutex); end: ord_th_states[local_id] = 9; } static void kmutex_ord_supervisor_thread() { int time_ms = 0; while (!ord_test_done) { if (se_is_stop_requested()) break; if (time_ms > 0 && (time_ms % 5000) == 0) { printk("[kmutex_ord_supervisor] %d sec elapsed\n", time_ms / 1000); int cnt[10] = {0}; for (int i = 0; i < KMUTEX_TH_COUNT; i++) cnt[ord_th_states[i]]++; printk("[kmutex_ord_supervisor] Report per state:\n"); for (int i = 0; i < 10; i++) printk("[kmutex_ord_supervisor] state %d: %d threads\n", i, cnt[i]); printk("\n\n"); } kernel_sleep_ms(100); time_ms += 100; } } void selftest_kmutex_ord() { u32 unlucky_threads = 0; int tid, supervisor_tid; idx1 = idx2 = 0; ord_test_done = false; bzero((void *)ord_th_states, sizeof(ord_th_states)); kmutex_init(&test_mutex, KMUTEX_FL_ALLOW_LOCK_WITH_PREEMPT_DISABLED); kmutex_init(&order_mutex, 0); for (int i = 0; i < ARRAY_SIZE(tids); i++) { if ((tid = kthread_create(&kmutex_ord_th, 0, TO_PTR(i))) < 0) panic("[selftest] Unable to create kthread for kmutex_ord_th()"); if (se_is_stop_requested()) goto end; tids[i] = tid; } supervisor_tid = kthread_create(&kmutex_ord_supervisor_thread, 0, NULL); if (supervisor_tid < 0) panic("[selftest] Unable to create the supervisor kthread"); kthread_join_all(tids, ARRAY_SIZE(tids), true); ord_test_done = true; kthread_join(supervisor_tid, true); if (se_is_stop_requested()) goto end; #if KMUTEX_STATS_ENABLED printk("order_mutex max waiters: %u\n", order_mutex.max_num_waiters); printk("test_mutex max waiters: %u\n", test_mutex.max_num_waiters); VERIFY(test_mutex.max_num_waiters > 0); #endif for (int i = 0; i < ARRAY_SIZE(tids); i++) { int t1, t2; t1 = tid_by_idx1[i]; t2 = tid_by_idx2[i]; if (t2 < 0) { unlucky_threads++; continue; } if (t2 != t1) panic("kmutex strong order test failed"); } if (unlucky_threads > 0) { if (unlucky_threads > ARRAY_SIZE(tids) / 2) panic("Too many unlucky threads"); printk("[selftests] Note: there were %u/%u unlucky threads", unlucky_threads, ARRAY_SIZE(tids)); } end: kmutex_destroy(&order_mutex); kmutex_destroy(&test_mutex); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(kmutex_ord, se_med, &selftest_kmutex_ord) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/list.h> extern const char *x86_exception_names[32]; extern struct list irq_handlers_lists[16]; extern void (*irq_entry_points[16])(void); extern soft_int_handler_t fault_handlers[32]; static ALWAYS_INLINE int int_to_irq(int int_num) { return int_num >= 32 ? int_num - 32 : -1; } static ALWAYS_INLINE bool is_irq(int int_num) { return int_num >= 32 && int_num != SYSCALL_SOFT_INTERRUPT; } static ALWAYS_INLINE bool is_timer_irq(int int_num) { return int_to_irq(int_num) == X86_PC_TIMER_IRQ; } static ALWAYS_INLINE bool is_fault(int int_num) { return IN_RANGE(int_num, 0, 32); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/process.h> #include <tilck/kernel/user.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/fs/vfs.h> static void set_process_str_cwd(struct process *pi, const char *path) { ASSERT(kmutex_is_curr_task_holding_lock(&pi->fslock)); size_t pl = strlen(path); memcpy(pi->str_cwd, path, pl + 1); if (pl > 1) { if (pi->str_cwd[pl - 1] == '/') pl--; /* drop the trailing slash */ /* on the other side, pi->str_cwd has always a trailing '/' */ pi->str_cwd[pl] = '/'; pi->str_cwd[pl + 1] = 0; } } static int getcwd_nolock(struct process *pi, char *user_buf, size_t buf_size) { ASSERT(kmutex_is_curr_task_holding_lock(&pi->fslock)); const size_t cl = strlen(pi->str_cwd) + 1; if (!user_buf || !buf_size) return -EINVAL; if (buf_size < cl) return -ERANGE; if (copy_to_user(user_buf, pi->str_cwd, cl)) return -EFAULT; if (cl > 2) { /* NOTE: `cl` counts the trailing `\0` */ ASSERT(user_buf[cl - 2] == '/'); user_buf[cl - 2] = 0; /* drop the trailing '/' */ } return (int) cl; } /* * This function does NOT release the former `fs` and `path` and should be * used ONLY directly once during the initialization in main.c and during * fork(). For all the other cases, call process_set_cwd2_nolock(). */ void process_set_cwd2_nolock_raw(struct process *pi, struct vfs_path *tp) { ASSERT(tp->fs != NULL); ASSERT(tp->fs_path.inode != NULL); retain_obj(tp->fs); vfs_retain_inode_at(tp); pi->cwd = *tp; } void process_set_cwd2_nolock(struct vfs_path *tp) { struct process *pi = get_curr_proc(); ASSERT(kmutex_is_curr_task_holding_lock(&pi->fslock)); ASSERT(pi->cwd.fs != NULL); ASSERT(pi->cwd.fs_path.inode != NULL); /* * We have to release the inode at that path and the fs containing it, before * changing them with process_set_cwd2_nolock_raw(). */ vfs_release_inode_at(&pi->cwd); release_obj(pi->cwd.fs); process_set_cwd2_nolock_raw(pi, tp); } int sys_chdir(const char *user_path) { int rc = 0; struct vfs_path p; struct task *curr = get_curr_task(); struct process *pi = curr->pi; char *orig_path = curr->args_copybuf; char *path = curr->args_copybuf + ARGS_COPYBUF_SIZE / 2; STATIC_ASSERT(ARRAY_SIZE(pi->str_cwd) == MAX_PATH); STATIC_ASSERT((ARGS_COPYBUF_SIZE / 2) >= MAX_PATH); rc = copy_str_from_user(orig_path, user_path, MAX_PATH, NULL); if (rc < 0) return -EFAULT; if (rc > 0) return -ENAMETOOLONG; kmutex_lock(&pi->fslock); { if ((rc = vfs_resolve(orig_path, &p, false, true))) goto out; if (!p.fs_path.inode) { rc = -ENOENT; vfs_fs_shunlock(p.fs); release_obj(p.fs); goto out; } if (p.fs_path.type != VFS_DIR) { rc = -ENOTDIR; vfs_fs_shunlock(p.fs); release_obj(p.fs); goto out; } process_set_cwd2_nolock(&p); /* * We need to unlock and release the fs because vfs_resolve() retained * and locked it. */ vfs_fs_shunlock(p.fs); release_obj(p.fs); DEBUG_ONLY_UNSAFE(rc =) compute_abs_path(orig_path, pi->str_cwd, path, MAX_PATH); /* * compute_abs_path() MUST NOT fail, because we have been already able * to resolve the path. */ ASSERT(rc == 0); set_process_str_cwd(pi, path); } out: kmutex_unlock(&pi->fslock); return rc; } int sys_getcwd(char *user_buf, size_t buf_size) { int rc; struct process *pi = get_curr_proc(); kmutex_lock(&pi->fslock); { rc = getcwd_nolock(pi, user_buf, buf_size); } kmutex_unlock(&pi->fslock); return rc; } <file_sep> Contents of this directory --------------------------- This directory contains all the user applications built with using Tilck's build system. Each application has to be explicitly added into the CMakeLists.txt file. Applications can be made by more than once C file and the pattern used by the build system is to treat all C files matching the wildcard `${APPNAME}*.c` as part of the application named `${APPNAME}`. How to run other apps on Tilck -------------------------------- If you want to test your own application on Tilck, you have two choices: 1. Make it compatible with Tilck's CMake build system and put a symlink to its root directory in `extra` [see `extra/README.md` for more]. 2. Compile it and link it *statically* using Tilck's GCC libmusl toolchain [`toolchain2/x86_gcc_toolchain`]. After that, could can just drop the executable in sysroot/usr/bin. In order to just rebuild Tilck's image, updating the sysroot, use the `make rebuild_img` command. <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # Exit on any error set -e maindir="@CMAKE_SOURCE_DIR@" bdir="@CMAKE_BINARY_DIR@" dest="@CMAKE_BINARY_DIR@/test_fatpart" tc="@TCROOT@" host_arch="@HOST_ARCH@" mtoolsdir=$tc/host_${host_arch}/mtools mformat=$mtoolsdir/mformat mlabel=$mtoolsdir/mlabel mmd=$mtoolsdir/mmd mcopy=$mtoolsdir/mcopy if [ ! -f $dest ]; then # If the 'fatpart' file does not already exist dd status=none if=/dev/zero of=$dest bs=1M count=35 fi # mformat options # -d <N> ; num of FAT copies # -F ; force FAT32 to be used # -c <N> ; sectors per cluster # -t <N> ; cylinders # -h <N> ; heads # -s <N> ; sectors $mformat -i $dest -d 1 -F -c 1 -t 70 -h 16 -s 63 :: $mlabel -i $dest ::TILCK rm -rf $bdir/test_sysroot mkdir $bdir/test_sysroot cp -r $maindir/tests/unit/test_sysroot $bdir/ cd $bdir/test_sysroot # Create file with random data dd if=/dev/urandom of=./bigfile bs=1 count=1048599 # 1 MB + 23 bytes # first, create the directories for f in $(find * -type d); do $mmd -i $dest $f done # then, copy all the files in sysroot for f in $(find * -type f); do $mcopy -i $dest $f ::/$f done <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/hal.h> void handle_syscall(regs_t *); void handle_fault(regs_t *); void arch_irq_handling(regs_t *r); /* * Nested IRQ counter needed for in_irq(). * * Note: the `__in_irq_count` mechanism tracks only nested IRQs and has NOTHING * to do with `KRN_TRACK_NESTED_INTERR` which is a debug util that tracks all * the interrupt types, including: syscalls, faults and IRQs. */ ATOMIC(int) __in_irq_count; static ALWAYS_INLINE void inc_irq_count(void) { atomic_fetch_add_explicit(&__in_irq_count, 1, mo_relaxed); } static ALWAYS_INLINE void dec_irq_count(void) { DEBUG_ONLY_UNSAFE(int oldval =) atomic_fetch_sub_explicit(&__in_irq_count, 1, mo_relaxed); ASSERT(oldval > 0); } #if KRN_TRACK_NESTED_INTERR static int nested_interrupts_count; static int nested_interrupts[MAX_NESTED_INTERRUPTS] = { [0 ... MAX_NESTED_INTERRUPTS-1] = -1, }; inline void push_nested_interrupt(int int_num) { ulong var; disable_interrupts(&var); /* under #if KRN_TRACK_NESTED_INTERR */ { ASSERT(nested_interrupts_count < MAX_NESTED_INTERRUPTS); ASSERT(nested_interrupts_count >= 0); nested_interrupts[nested_interrupts_count++] = int_num; } enable_interrupts(&var); } inline void pop_nested_interrupt(void) { ulong var; disable_interrupts(&var); /* under #if KRN_TRACK_NESTED_INTERR */ { nested_interrupts_count--; ASSERT(nested_interrupts_count >= 0); } enable_interrupts(&var); } bool in_nested_irq_num(int irq_num) { ASSERT(!are_interrupts_enabled()); for (int i = nested_interrupts_count - 2; i >= 0; i--) if (int_to_irq(nested_interrupts[i]) == irq_num) return true; return false; } void check_not_in_irq_handler(void) { if (!in_panic()) { if (in_irq()) panic("NOT expected to be in an IRQ handler"); } } void check_in_irq_handler(void) { if (!in_panic()) { if (!in_irq()) panic("Expected TO BE in an IRQ handler (but we're NOT)"); } } void check_in_no_other_irq_than_timer(void) { ulong var; if (in_panic()) return; disable_interrupts(&var); /* under #if KRN_TRACK_NESTED_INTERR */ { if (nested_interrupts_count > 0) { int n = nested_interrupts[nested_interrupts_count - 1]; if (is_irq(n) && !is_timer_irq(n)) panic("NOT expected to be in an IRQ handler != IRQ0 [timer]"); } } enable_interrupts(&var); } static void DEBUG_check_not_same_interrupt_nested(int int_num) { ASSERT(!are_interrupts_enabled()); for (int i = nested_interrupts_count - 1; i >= 0; i--) if (nested_interrupts[i] == int_num) { if (int_num == 32) { /* * Tolerate nested IRQ 0 for debug purposes: to make sure that the * timer handler *never* gets so slow that IRQ #0 gets fired again * before it finishes. */ return; } panic("Same interrupt (%i) twice in nested_interrupts[]", int_num); } } void nested_interrupts_drop_top_syscall(void) { if (nested_interrupts_count > 0) { ASSERT(nested_interrupts_count == 1); ASSERT(nested_interrupts[0] == SYSCALL_SOFT_INTERRUPT); pop_nested_interrupt(); } } void panic_dump_nested_interrupts(void) { VERIFY(in_panic()); if (!kopt_panic_kb) { ASSERT(!are_interrupts_enabled()); } char buf[128]; int written = 0; written += snprintk(buf + written, sizeof(buf), "Interrupts: [ "); for (int i = nested_interrupts_count - 1; i >= 0; i--) { written += snprintk(buf + written, sizeof(buf) - (u32)written, "%i ", nested_interrupts[i]); } /* written += */ snprintk(buf + written, sizeof(buf) - (u32) written, "]\n"); printk("%s", buf); } #else static ALWAYS_INLINE void DEBUG_check_not_same_interrupt_nested(int n) { } #endif // KRN_TRACK_NESTED_INTERR static void irq_resched(regs_t *r) { /* Check if we just disabled the preemption or it was disabled before */ if (get_preempt_disable_count() == 1) { /* It wasn't disabled before: save the current state (registers) */ save_current_task_state(r); /* Re-enable the interrupts, keeping preemption disabled */ enable_interrupts_forced(); /* Call do_schedule() with preemption disabled, as mandatory */ do_schedule(); } } void irq_entry(regs_t *r) { ASSERT(get_curr_task() != NULL); DEBUG_check_not_same_interrupt_nested(regs_intnum(r)); /* We expect here that the CPU disabled the interrupts */ ASSERT(!are_interrupts_enabled()); /* Disable the preemption */ disable_preemption(); /* Increase the always-enabled in_irq_count counter */ inc_irq_count(); /* Call the arch-dependent IRQ handling logic */ arch_irq_handling(r); /* Decrease the always-enabled in_irq_count counter */ dec_irq_count(); /* Check that arch_irq_handling restored the interrupts state to disabled */ ASSERT(!are_interrupts_enabled()); /* Check that the preemption is disabled as well */ ASSERT(!is_preemption_enabled()); /* Run the scheduler if necessary (it will enable interrupts) */ if (need_reschedule()) irq_resched(r); /* * In case do_schedule() returned or there was no need for resched, just * re-enable the preemption and return. */ enable_preemption_nosched(); } void syscall_entry(regs_t *r) { /* * Interrupts are disabled in order to have a slightly better tracking of * the nested interrupts (debug feature). The preemption must always be * enabled here. */ ASSERT(!are_interrupts_enabled()); ASSERT(is_preemption_enabled()); push_nested_interrupt(0x80); disable_preemption(); enable_interrupts_forced(); { handle_syscall(r); } disable_interrupts_forced(); enable_preemption_nosched(); pop_nested_interrupt(); ASSERT(is_preemption_enabled()); } void fault_entry(regs_t *r) { /* * Here preemption could be either enabled or disabled. Typically is enabled, * but it's totally possible for example a page fault to occur in the kernel * while preemption is disabled. */ ASSERT(!are_interrupts_enabled()); push_nested_interrupt(regs_intnum(r)); disable_preemption(); enable_interrupts_forced(); handle_fault(r); /* * Pop the nested interrupt and process signals while preemption is * still disabled. */ pop_nested_interrupt(); process_signals(get_curr_task(), sig_in_fault, r); enable_preemption(); disable_interrupts_forced(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/kernel/kb.h> #include <tilck/kernel/list.h> #include <tilck/kernel/fs/vfs_base.h> #define DP_W 76 #define DP_H 23 typedef enum kb_handler_action (*dp_keypress_func)(struct key_event); struct dp_screen { struct list_node node; int index; int row_off; int row_max; const char *label; void (*first_setup)(void); void (*draw_func)(void); void (*on_dp_enter)(void); void (*on_dp_exit)(void); dp_keypress_func on_keypress_func; }; extern int dp_rows; extern int dp_cols; extern int dp_start_row; extern int dp_end_row; extern int dp_start_col; extern int dp_screen_start_row; extern int dp_screen_rows; extern bool ui_need_update; extern const char *modal_msg; extern struct dp_screen *dp_ctx; extern fs_handle dp_input_handle; static inline long dp_int_abs(long val) { return val >= 0 ? val : -val; } void dp_register_screen(struct dp_screen *screen); int dp_read_ke_from_tty(struct key_event *ke); void dp_set_input_blocking(bool blocking); int dp_read_line(char *buf, int buf_size); enum kb_handler_action dp_tracing_screen(void); void dp_dump_task_list(bool kernel_tasks, bool plain_text); void handle_set_blocking(fs_handle h, bool blocking); int dp_mini_debugger_tool(); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> // Defining some necessary symbols just to make the linker happy. void *kernel_initial_stack = NULL; void asm_save_regs_and_schedule() { NOT_REACHED(); } void switch_to_initial_kernel_stack() { NOT_REACHED(); } void fault_resumable_call() { NOT_REACHED(); } void asm_do_bogomips_loop(void) { NOT_REACHED(); } void asm_nop_loop(void) { NOT_REACHED(); } <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). # Switch to tty2 send_to_vm_and_find_text(r"{alt-f2}", True, []) # Start the shell send_to_vm_and_find_text(r"{ret}", True, []) # Enter in the debug panel send_to_vm_and_find_text(r"dp{ret}", True, [ "TilckDebugPanel", "TERM_ROWS", "DEBUG_CHECKS", ]) # Select the tasks tab send_to_vm_and_find_text(r"4", True, [ "pid", "tty", "cmdline", ]) # Enter in select mode send_to_vm_and_find_text(r"{ret}", True, []) # Select the 2nd process (ASH on tty 1) send_to_vm_and_find_text(r"{down}", True, []) # Mark the process as TRACED send_to_vm_and_find_text(r"{t}", True, []) # Enter in tracing mode send_to_vm_and_find_text(r"{ctrl-t}", True, []) # Start the actual tracing send_to_vm_and_find_text(r"{ret}", True, []) # Switch back to tty1 send_to_vm_and_find_text(r"{alt-f1}", True, []) # Just run `ls` send_to_vm_and_find_text(r"ls{ret}", True, []) # Switch back to tty2 and check the tracing output send_to_vm_and_find_text(r"{alt-f2}", True, [ "open", "wait4", "close", "poll", "writev", ]) # Stop the actual tracing send_to_vm_and_find_text(r"{ret}", True, []) # Exit from tracing mode send_to_vm_and_find_text(r"q", True, []) # Exit from the debug panel send_string_to_vm(r"q") <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/user.h> #include <tilck/mods/fb_console.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/process.h> #include <tilck/kernel/process_mm.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/fs/vfs.h> #include <linux/fb.h> // system header #include <linux/major.h> // system header #include <sys/mman.h> // system header #include "fb_int.h" extern ulong fb_vaddr; extern u32 fb_size; static ssize_t total_fb_pages_mapped; static struct list mappings_list = STATIC_LIST_INIT(mappings_list); static ssize_t fb_read(fs_handle h, char *user_buf, size_t size, offt *pos) { ssize_t actual_size = MIN((ssize_t)fb_size - (ssize_t)*pos, (ssize_t)size); void *src = (char *)fb_vaddr + *pos; *pos += actual_size; if (copy_to_user(user_buf, src, (size_t)actual_size)) return -EFAULT; return actual_size; } static ssize_t fb_write(fs_handle h, char *user_buf, size_t size, offt *pos) { ssize_t actual_size = MIN((ssize_t)fb_size - (ssize_t)*pos, (ssize_t)size); void *dest = (char *)fb_vaddr + *pos; *pos += actual_size; if (copy_from_user(dest, user_buf, (size_t)actual_size)) return -EFAULT; return actual_size; } static offt fb_seek(fs_handle h, offt off, int whence) { struct devfs_handle *dh = h; offt new_pos = -1; switch (whence) { case SEEK_SET: new_pos = off; break; case SEEK_CUR: new_pos = dh->h_fpos + off; break; case SEEK_END: new_pos = dh->h_fpos - off; break; } if (new_pos < 0 || (size_t)new_pos > fb_size) return -EINVAL; dh->h_fpos = new_pos; return dh->h_fpos; } static int fb_ioctl(fs_handle h, ulong request, void *argp) { if (request == FBIOGET_FSCREENINFO) { struct fb_fix_screeninfo fix_info; int rc; fb_fill_fix_info(&fix_info); rc = copy_to_user(argp, &fix_info, sizeof(fix_info)); if (rc != 0) return -EFAULT; return 0; } if (request == FBIOGET_VSCREENINFO) { struct fb_var_screeninfo var_info; int rc; fb_fill_var_info(&var_info); rc = copy_to_user(argp, &var_info, sizeof(var_info)); if (rc != 0) return -EFAULT; return 0; } return -EINVAL; } static int fbdev_mmap(struct user_mapping *um, pdir_t *pdir, int flags) { int rc; ASSERT(IS_PAGE_ALIGNED(um->len)); if (um->off != 0) return -EINVAL; /* not supported, at least for the moment */ if (flags & VFS_MM_DONT_MMAP) goto register_mapping; if ((rc = fb_user_mmap(pdir, um->vaddrp, um->len)) < 0) return rc; total_fb_pages_mapped += um->len >> PAGE_SHIFT; register_mapping: if (!(flags & VFS_MM_DONT_REGISTER)) { list_add_tail(&mappings_list, &um->inode_node); } return 0; } static int fbdev_munmap(struct user_mapping *um, void *vaddr, size_t len) { struct fs_handle_base *hb = um->h; size_t unmapped_count; bool dying_task = false; ASSERT(IS_PAGE_ALIGNED(len)); ASSERT(hb->pi == get_curr_proc()); if (get_process_task(hb->pi)->state == TASK_STATE_ZOMBIE) dying_task = true; unmapped_count = unmap_pages_permissive( hb->pi->pdir, vaddr, len >> PAGE_SHIFT, false ); total_fb_pages_mapped -= (size_t)unmapped_count; ASSERT(total_fb_pages_mapped >= 0); /* * [BE_NICE] In case we're in a dying task() [we've been called indirectly by * terminate_process()] and no other process in the system has any pages of * the framebuffer mapped, then make sure that the current TTY is restored * back in KD_TEXT mode, in order to give back to the user the control. * * NOTE: that's a special Tilck-only behavior: on Linux, TTY won't be * restored in KD_TEXT mode and, therefore, the system won't be usable by * a user physically near the machine. Not even switching to a Xorg instance * with ALT+F1, ALT+F2, etc. works. It's required to use Magic SysRq * shortcuts to reboot the machine or connect to it remotely to do that. */ if (total_fb_pages_mapped == 0 && dying_task) { tty_restore_kd_text_mode(hb->pi->proc_tty); } return 0; } static int create_fb_device(int minor, enum vfs_entry_type *type, struct devfs_file_info *nfo) { static const struct file_ops static_ops_fb = { .read = fb_read, .write = fb_write, .seek = fb_seek, .ioctl = fb_ioctl, .mmap = fbdev_mmap, .munmap = fbdev_munmap, }; *type = VFS_CHAR_DEV; nfo->fops = &static_ops_fb; nfo->spec_flags = VFS_SPFL_NO_USER_COPY | VFS_SPFL_MMAP_SUPPORTED; return 0; } static void init_fbdev(void) { if (!use_framebuffer()) return; struct driver_info *di = kalloc_obj(struct driver_info); if (!di) panic("TTY: no enough memory for init_tty()"); di->name = "fb"; di->create_dev_file = create_fb_device; register_driver(di, FB_MAJOR); int rc = create_dev_file("fb0", FB_MAJOR, 0 /* minor */, NULL); if (rc != 0) panic("TTY: unable to create /dev/fb0 (error: %d)", rc); } static struct module fb_module = { .name = "fb", .priority = MOD_fbdev_prio, .init = &init_fbdev, }; REGISTER_MODULE(&fb_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/mods/serial.h> #include <tilck/kernel/hal.h> /* * Definitions from: * https://en.wikibooks.org/wiki/Serial_Programming/8250_UART_Programming */ #define UART_THR 0 /* [ W] Transmitter Holding Buffer */ #define UART_RBR 0 /* [R ] Receiver Buffer */ #define UART_DLL 0 /* [RW] DLAB: Divisor Latch Low Byte */ #define UART_IER 1 /* [RW] Interrupt Enable Register */ #define UART_DLH 1 /* [RW] DLAB: Divisor Latch High Byte */ #define UART_IIR 2 /* [R ] Interrupt Identification Register */ #define UART_FCR 2 /* [ W] FIFO Control Register */ #define UART_LCR 3 /* [RW] Line Control Register */ #define UART_MCR 4 /* [RW] Modem Control Register */ #define UART_LSR 5 /* [R ] Line Status Register */ #define UART_MSR 6 /* [R ] Modem Status Register */ #define UART_SR 7 /* [RW] Scratch Register */ /* Interrupt Enable Register (IER) */ #define IER_NO_INTR 0b00000000 #define IER_RCV_AVAIL_INTR 0b00000001 #define IER_TR_EMPTY_INTR 0b00000010 #define IER_RCV_LINE_STAT_INTR 0b00000100 #define IER_MOD_STAT_INTR 0b00001000 #define IER_SLEEP_MODE_INTR 0b00010000 #define IER_LOW_PWR_INTR 0b00100000 /* Line Status Register (LSR) */ #define LSR_DATA_READY 0b00000001 #define LSR_OVERRUN_ERROR 0b00000010 #define LSR_PARITY_ERROR 0b00000100 #define LSR_FRAMING_ERROR 0b00001000 #define LSR_BREAK_INTERRUPT 0b00010000 #define LSR_EMPTY_TR_REG 0b00100000 #define LSR_EMPTY_DATA_HOLD_REG 0b01000000 #define LSR_ERROR_RECV_FIFO 0b10000000 /* Line Control Register (LCR) */ /* bits: xx */ #define LCR_5_BITS 0b00000000 #define LCR_6_BITS 0b00000001 #define LCR_7_BITS 0b00000010 #define LCR_8_BITS 0b00000011 /* bits: x */ #define LCR_1_STOP_BIT 0b00000000 #define LCR_1_5_OR_2_STOP_BITS 0b00000100 /* bits: xxx */ #define LCR_NO_PARITY 0b00000000 #define LCR_ODD_PARITY 0b00001000 #define LCR_EVEN_PARITY 0b00011000 #define LCR_MARK_PARITY 0b00101000 #define LCR_SPACE_PARITY 0b00111000 #define LCR_SET_BREAK_ENABLE 0b01000000 #define LCR_SET_DIV_LATCH_ACC_BIT 0b10000000 /* FIFO Control Register (FCR) */ #define FCR_ENABLE_FIFOs 0b00000001 #define FCR_CLEAR_RECV_FIFO 0b00000010 #define FCR_CLEAR_TR_FIFO 0b00000100 #define FCR_DMA_MODE 0b00001000 #define FCR_RESERVED 0b00010000 /* DO NOT USE */ #define FCR_64_BYTE_FIFO 0b00100000 #define FCR_INT_TRIG_LEVEL_0 0b00000000 /* 1 byte (16 and 64 byte FIFO) */ #define FCR_INT_TRIG_LEVEL_1 0b01000000 /* 4 / 16 bytes (64 byte FIFO) */ #define FCR_INT_TRIG_LEVEL_2 0b10000000 /* 8 / 32 bytes (64 byte FIFO) */ #define FCR_INT_TRIG_LEVEL_3 0b11000000 /* 14 / 56 bytes (64 byte FIFO) */ /* Modem Control Register (MCR) */ #define MCR_DTR 0b00000001 /* Data Terminal Ready */ #define MCR_RTS 0b00000010 /* Request To Send */ #define MCR_AUX_OUTPUT_1 0b00000100 #define MCR_AUX_OUTPUT_2 0b00001000 /* Necessary for interrupts to for most of the controllers */ #define MCR_LOOPBACK_MODE 0b00010000 #define MCR_AUTOFLOW_CTRL 0b00100000 /* Only on 16750 */ #define MCR_RESERVED_1 0b01000000 #define MCR_RESERVED_2 0b10000000 /* Modem Status Register (MSR) */ #define MSR_DELTA_CTS 0b00000001 /* Delta Clear To Send */ #define MSR_DELTA_DSR 0b00000010 /* Delta Data Set Ready */ #define MSR_TERI 0b00000100 /* Trailing Edge Ring Indicator */ #define MSR_DELTA_DCD 0b00001000 /* Delta Data Carrier Detect */ #define MSR_CTS 0b00010000 /* Clear To Send */ #define MSR_DSR 0b00100000 /* Data Set Ready */ #define MSR_RI 0b01000000 /* Ring Indicator */ #define MSR_CD 0b10000000 /* Carrier Detect */ /* Set DLAB [Divisor Latch Access Bit] to `value` */ static void uart_set_dlab(u16 port, bool value) { u8 lcr = inb(port + UART_LCR); lcr = (u8)((lcr & 0b01111111) | (value << 7)); outb(port + UART_LCR, lcr); } static void uart_set_divisor_latch(u16 port, u16 value) { uart_set_dlab(port, 1); outb(port + UART_DLL, LO_BITS(value, 8, u8)); outb(port + UART_DLH, LO_BITS(value >> 8, 8, u8)); uart_set_dlab(port, 0); } void init_serial_port(u16 port) { outb(port + UART_IER, IER_NO_INTR); uart_set_divisor_latch(port, 1 /* 115200 baud */); outb(port + UART_LCR, LCR_8_BITS | LCR_1_STOP_BIT | LCR_NO_PARITY); outb(port + UART_FCR, FCR_ENABLE_FIFOs | FCR_CLEAR_RECV_FIFO | FCR_CLEAR_TR_FIFO | FCR_INT_TRIG_LEVEL_3); outb(port + UART_MCR, MCR_DTR | MCR_RTS | MCR_AUX_OUTPUT_2); outb(port + UART_IER, IER_RCV_AVAIL_INTR); } bool serial_read_ready(u16 port) { return !!(inb(port + UART_LSR) & LSR_DATA_READY); } void serial_wait_for_read(u16 port) { while (!serial_read_ready(port)) { } } char serial_read(u16 port) { serial_wait_for_read(port); return (char) inb(port); } bool serial_write_ready(u16 port) { return !!(inb(port + UART_LSR) & LSR_EMPTY_TR_REG); } void serial_wait_for_write(u16 port) { while (!serial_write_ready(port)) { } } void serial_write(u16 port, char c) { serial_wait_for_write(port); outb(port, (u8)c); } <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tilck_types as tt WOBJ_NONE = gdb.parse_and_eval("WOBJ_NONE") WOBJ_TASK = gdb.parse_and_eval("WOBJ_TASK") WOBJ_MWO_WAITER = gdb.parse_and_eval("WOBJ_MWO_WAITER") class printer_mwobj_elem: def __init__(self, val): self.val = val def to_string(self): return "mwobj_elem" def children(self): e = self.val wobj = e["wobj"] return [ ("type", e["type"]), ("extra", wobj["extra"]), ("ptr", wobj["__ptr"]), ] class printer_multi_obj_waiter: def __init__(self, val): self.val = val def display_hint(self): return 'array' def children(self): mwobj = self.val count = mwobj['count'] elems = mwobj['elems'] arr = [] for i in range(count): arr.append((str(i), elems[i])) return arr def to_string(self): return bu.fmt_type("struct multi_obj_waiter", self.val) class printer_wait_obj: def __init__(self, val): self.val = val def children(self): wobj = self.val if wobj['type'] == WOBJ_NONE: return [] res = [ ("type", wobj['type']), ("extra", wobj['extra']), ] if wobj['type'] == WOBJ_TASK: tidval = wobj['__data'] if tidval < -1: tidval = "<any child with pgid = {}>".format(-tidval) elif tidval == -1: tidval = "<any child>" elif tidval == 0: tidval = "<any child with same pgid>" res.append(("tid", tidval)) elif wobj['type'] == WOBJ_MWO_WAITER: mwobj = wobj['__ptr'].cast(tt.multi_obj_waiter_p) res.append(("ptr", mwobj.dereference())) else: res.append(("ptr", wobj['__ptr'])) return res def to_string(self): return bu.fmt_type("struct wait_obj", self.val) bu.register_tilck_regex_pp( 'wait_obj', '^wait_obj$', printer_wait_obj ) bu.register_tilck_regex_pp( 'multi_obj_waiter', '^multi_obj_waiter$', printer_multi_obj_waiter ) bu.register_tilck_regex_pp( 'mwobj_elem', '^mwobj_elem$', printer_mwobj_elem ) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/fs/vfs_base.h> struct mnt_fs *ramfs_create(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <zlib.h> #include <3rd_party/base64.h> #include "devshell.h" static void write_buf_on_screen(void *buf, unsigned size) { size_t b64_size; unsigned char *b64 = base64_encode(buf, size, &b64_size); if (!b64) { printf("[ERROR] base64_encode() failed\n"); exit(1); } fwrite(b64, 1, b64_size, stdout); free(b64); } static void compress_buf(void *buf, unsigned buf_size, void *zbuf, unsigned *zbuf_size) { z_stream defstream; defstream.zalloc = Z_NULL; defstream.zfree = Z_NULL; defstream.opaque = Z_NULL; defstream.data_type = Z_BINARY; defstream.avail_in = buf_size; defstream.next_in = buf; defstream.avail_out = *zbuf_size; defstream.next_out = zbuf; deflateInit2(&defstream, Z_BEST_COMPRESSION, Z_DEFLATED, MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); deflate(&defstream, Z_FINISH); deflateEnd(&defstream); *zbuf_size = defstream.total_out; } void dump_coverage_files(void) { int rc; void *buf, *zbuf; char fname[256]; unsigned fsize; const int fn = tilck_get_num_gcov_files(); // this syscall cannot fail tilck_set_sched_alive_thread_enabled(false); printf("** GCOV gcda files **\n"); for (int i = 0; i < fn; i++) { rc = tilck_get_gcov_file_info(i, fname, sizeof(fname), &fsize); if (rc != 0) { printf("[ERROR] tilck_get_gcov_file_info() failed with %d\n", rc); exit(1); } assert((fsize % 4) == 0); buf = malloc(fsize); zbuf = malloc(fsize); if (!buf || !zbuf) { printf("[ERROR] Out-of-memory\n"); exit(1); } printf("\nfile: %s\n", fname); rc = tilck_get_gcov_file(i, buf); if (rc != 0) { printf("[ERROR] tilck_get_gcov_file() failed with %d\n", rc); exit(1); } compress_buf(buf, fsize, zbuf, &fsize); write_buf_on_screen(zbuf, fsize); free(zbuf); free(buf); } printf("\n"); printf("** GCOV gcda files END **\n\n"); tilck_set_sched_alive_thread_enabled(true); } <file_sep>/****************************************************************************** * * Module Name: dswload2 - Dispatcher second pass namespace load callbacks * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acevents.h" #ifdef ACPI_EXEC_APP #include "aecommon.h" #endif #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dswload2") /******************************************************************************* * * FUNCTION: AcpiDsLoad2BeginOp * * PARAMETERS: WalkState - Current state of the parse tree walk * OutOp - Where to return op if a new one is created * * RETURN: Status * * DESCRIPTION: Descending callback used during the loading of ACPI tables. * ******************************************************************************/ ACPI_STATUS AcpiDsLoad2BeginOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **OutOp) { ACPI_PARSE_OBJECT *Op; ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_OBJECT_TYPE ObjectType; char *BufferPtr; UINT32 Flags; ACPI_FUNCTION_TRACE (DsLoad2BeginOp); Op = WalkState->Op; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Op=%p State=%p\n", Op, WalkState)); if (Op) { if ((WalkState->ControlState) && (WalkState->ControlState->Common.State == ACPI_CONTROL_CONDITIONAL_EXECUTING)) { /* We are executing a while loop outside of a method */ Status = AcpiDsExecBeginOp (WalkState, OutOp); return_ACPI_STATUS (Status); } /* We only care about Namespace opcodes here */ if ((!(WalkState->OpInfo->Flags & AML_NSOPCODE) && (WalkState->Opcode != AML_INT_NAMEPATH_OP)) || (!(WalkState->OpInfo->Flags & AML_NAMED))) { return_ACPI_STATUS (AE_OK); } /* Get the name we are going to enter or lookup in the namespace */ if (WalkState->Opcode == AML_INT_NAMEPATH_OP) { /* For Namepath op, get the path string */ BufferPtr = Op->Common.Value.String; if (!BufferPtr) { /* No name, just exit */ return_ACPI_STATUS (AE_OK); } } else { /* Get name from the op */ BufferPtr = ACPI_CAST_PTR (char, &Op->Named.Name); } } else { /* Get the namestring from the raw AML */ BufferPtr = AcpiPsGetNextNamestring (&WalkState->ParserState); } /* Map the opcode into an internal object type */ ObjectType = WalkState->OpInfo->ObjectType; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "State=%p Op=%p Type=%X\n", WalkState, Op, ObjectType)); switch (WalkState->Opcode) { case AML_FIELD_OP: case AML_BANK_FIELD_OP: case AML_INDEX_FIELD_OP: Node = NULL; Status = AE_OK; break; case AML_INT_NAMEPATH_OP: /* * The NamePath is an object reference to an existing object. * Don't enter the name into the namespace, but look it up * for use later. */ Status = AcpiNsLookup (WalkState->ScopeInfo, BufferPtr, ObjectType, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT, WalkState, &(Node)); break; case AML_SCOPE_OP: /* Special case for Scope(\) -> refers to the Root node */ if (Op && (Op->Named.Node == AcpiGbl_RootNode)) { Node = Op->Named.Node; Status = AcpiDsScopeStackPush (Node, ObjectType, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } else { /* * The Path is an object reference to an existing object. * Don't enter the name into the namespace, but look it up * for use later. */ Status = AcpiNsLookup (WalkState->ScopeInfo, BufferPtr, ObjectType, ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT, WalkState, &(Node)); if (ACPI_FAILURE (Status)) { #ifdef ACPI_ASL_COMPILER if (Status == AE_NOT_FOUND) { Status = AE_OK; } else { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, BufferPtr, Status); } #else ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, BufferPtr, Status); #endif return_ACPI_STATUS (Status); } } /* * We must check to make sure that the target is * one of the opcodes that actually opens a scope */ switch (Node->Type) { case ACPI_TYPE_ANY: case ACPI_TYPE_LOCAL_SCOPE: /* Scope */ case ACPI_TYPE_DEVICE: case ACPI_TYPE_POWER: case ACPI_TYPE_PROCESSOR: case ACPI_TYPE_THERMAL: /* These are acceptable types */ break; case ACPI_TYPE_INTEGER: case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: /* * These types we will allow, but we will change the type. * This enables some existing code of the form: * * Name (DEB, 0) * Scope (DEB) { ... } */ ACPI_WARNING ((AE_INFO, "Type override - [%4.4s] had invalid type (%s) " "for Scope operator, changed to type ANY", AcpiUtGetNodeName (Node), AcpiUtGetTypeName (Node->Type))); Node->Type = ACPI_TYPE_ANY; WalkState->ScopeInfo->Common.Value = ACPI_TYPE_ANY; break; case ACPI_TYPE_METHOD: /* * Allow scope change to root during execution of module-level * code. Root is typed METHOD during this time. */ if ((Node == AcpiGbl_RootNode) && (WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL)) { break; } /*lint -fallthrough */ default: /* All other types are an error */ ACPI_ERROR ((AE_INFO, "Invalid type (%s) for target of " "Scope operator [%4.4s] (Cannot override)", AcpiUtGetTypeName (Node->Type), AcpiUtGetNodeName (Node))); return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } break; default: /* All other opcodes */ if (Op && Op->Common.Node) { /* This op/node was previously entered into the namespace */ Node = Op->Common.Node; if (AcpiNsOpensScope (ObjectType)) { Status = AcpiDsScopeStackPush (Node, ObjectType, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } return_ACPI_STATUS (AE_OK); } /* * Enter the named type into the internal namespace. We enter the name * as we go downward in the parse tree. Any necessary subobjects that * involve arguments to the opcode must be created as we go back up the * parse tree later. * * Note: Name may already exist if we are executing a deferred opcode. */ if (WalkState->DeferredNode) { /* This name is already in the namespace, get the node */ Node = WalkState->DeferredNode; Status = AE_OK; break; } Flags = ACPI_NS_NO_UPSEARCH; if (WalkState->PassNumber == ACPI_IMODE_EXECUTE) { /* Execution mode, node cannot already exist, node is temporary */ Flags |= ACPI_NS_ERROR_IF_FOUND; if (!(WalkState->ParseFlags & ACPI_PARSE_MODULE_LEVEL)) { Flags |= ACPI_NS_TEMPORARY; } } #ifdef ACPI_ASL_COMPILER /* * Do not open a scope for AML_EXTERNAL_OP * AcpiNsLookup can open a new scope based on the object type * of this op. AML_EXTERNAL_OP is a declaration rather than a * definition. In the case that this external is a method object, * AcpiNsLookup will open a new scope. However, an AML_EXTERNAL_OP * associated with the ACPI_TYPE_METHOD is a declaration, rather than * a definition. Flags is set to avoid opening a scope for any * AML_EXTERNAL_OP. */ if (WalkState->Opcode == AML_EXTERNAL_OP) { Flags |= ACPI_NS_DONT_OPEN_SCOPE; } #endif /* * For name creation opcodes, the full namepath prefix must * exist, except for the final (new) nameseg. */ if (WalkState->OpInfo->Flags & AML_NAMED) { Flags |= ACPI_NS_PREFIX_MUST_EXIST; } /* Add new entry or lookup existing entry */ Status = AcpiNsLookup (WalkState->ScopeInfo, BufferPtr, ObjectType, ACPI_IMODE_LOAD_PASS2, Flags, WalkState, &Node); if (ACPI_SUCCESS (Status) && (Flags & ACPI_NS_TEMPORARY)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "***New Node [%4.4s] %p is temporary\n", AcpiUtGetNodeName (Node), Node)); } break; } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, BufferPtr, Status); return_ACPI_STATUS (Status); } if (!Op) { /* Create a new op */ Op = AcpiPsAllocOp (WalkState->Opcode, WalkState->Aml); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize the new op */ if (Node) { Op->Named.Name = Node->Name.Integer; } *OutOp = Op; } /* * Put the Node in the "op" object that the parser uses, so we * can get it again quickly when this scope is closed */ Op->Common.Node = Node; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsLoad2EndOp * * PARAMETERS: WalkState - Current state of the parse tree walk * * RETURN: Status * * DESCRIPTION: Ascending callback used during the loading of the namespace, * both control methods and everything else. * ******************************************************************************/ ACPI_STATUS AcpiDsLoad2EndOp ( ACPI_WALK_STATE *WalkState) { ACPI_PARSE_OBJECT *Op; ACPI_STATUS Status = AE_OK; ACPI_OBJECT_TYPE ObjectType; ACPI_NAMESPACE_NODE *Node; ACPI_PARSE_OBJECT *Arg; ACPI_NAMESPACE_NODE *NewNode; UINT32 i; UINT8 RegionSpace; #ifdef ACPI_EXEC_APP ACPI_OPERAND_OBJECT *ObjDesc; char *Namepath; #endif ACPI_FUNCTION_TRACE (DsLoad2EndOp); Op = WalkState->Op; ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Opcode [%s] Op %p State %p\n", WalkState->OpInfo->Name, Op, WalkState)); /* Check if opcode had an associated namespace object */ if (!(WalkState->OpInfo->Flags & AML_NSOBJECT)) { return_ACPI_STATUS (AE_OK); } if (Op->Common.AmlOpcode == AML_SCOPE_OP) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Ending scope Op=%p State=%p\n", Op, WalkState)); } ObjectType = WalkState->OpInfo->ObjectType; /* * Get the Node/name from the earlier lookup * (It was saved in the *op structure) */ Node = Op->Common.Node; /* * Put the Node on the object stack (Contains the ACPI Name of * this object) */ WalkState->Operands[0] = (void *) Node; WalkState->NumOperands = 1; /* Pop the scope stack */ if (AcpiNsOpensScope (ObjectType) && (Op->Common.AmlOpcode != AML_INT_METHODCALL_OP)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "(%s) Popping scope for Op %p\n", AcpiUtGetTypeName (ObjectType), Op)); Status = AcpiDsScopeStackPop (WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } } /* * Named operations are as follows: * * AML_ALIAS * AML_BANKFIELD * AML_CREATEBITFIELD * AML_CREATEBYTEFIELD * AML_CREATEDWORDFIELD * AML_CREATEFIELD * AML_CREATEQWORDFIELD * AML_CREATEWORDFIELD * AML_DATA_REGION * AML_DEVICE * AML_EVENT * AML_FIELD * AML_INDEXFIELD * AML_METHOD * AML_METHODCALL * AML_MUTEX * AML_NAME * AML_NAMEDFIELD * AML_OPREGION * AML_POWERRES * AML_PROCESSOR * AML_SCOPE * AML_THERMALZONE */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Create-Load [%s] State=%p Op=%p NamedObj=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), WalkState, Op, Node)); /* Decode the opcode */ Arg = Op->Common.Value.Arg; switch (WalkState->OpInfo->Type) { case AML_TYPE_CREATE_FIELD: /* * Create the field object, but the field buffer and index must * be evaluated later during the execution phase */ Status = AcpiDsCreateBufferField (Op, WalkState); if ACPI_FAILURE (Status) { ACPI_EXCEPTION ((AE_INFO, Status, "CreateBufferField failure")); goto Cleanup; } break; case AML_TYPE_NAMED_FIELD: /* * If we are executing a method, initialize the field */ if (WalkState->MethodNode) { Status = AcpiDsInitFieldObjects (Op, WalkState); } switch (Op->Common.AmlOpcode) { case AML_INDEX_FIELD_OP: Status = AcpiDsCreateIndexField ( Op, (ACPI_HANDLE) Arg->Common.Node, WalkState); break; case AML_BANK_FIELD_OP: Status = AcpiDsCreateBankField (Op, Arg->Common.Node, WalkState); break; case AML_FIELD_OP: Status = AcpiDsCreateField (Op, Arg->Common.Node, WalkState); break; default: /* All NAMED_FIELD opcodes must be handled above */ break; } break; case AML_TYPE_NAMED_SIMPLE: Status = AcpiDsCreateOperands (WalkState, Arg); if (ACPI_FAILURE (Status)) { goto Cleanup; } switch (Op->Common.AmlOpcode) { case AML_PROCESSOR_OP: Status = AcpiExCreateProcessor (WalkState); break; case AML_POWER_RESOURCE_OP: Status = AcpiExCreatePowerResource (WalkState); break; case AML_MUTEX_OP: Status = AcpiExCreateMutex (WalkState); break; case AML_EVENT_OP: Status = AcpiExCreateEvent (WalkState); break; case AML_ALIAS_OP: Status = AcpiExCreateAlias (WalkState); break; default: /* Unknown opcode */ Status = AE_OK; goto Cleanup; } /* Delete operands */ for (i = 1; i < WalkState->NumOperands; i++) { AcpiUtRemoveReference (WalkState->Operands[i]); WalkState->Operands[i] = NULL; } break; case AML_TYPE_NAMED_COMPLEX: switch (Op->Common.AmlOpcode) { case AML_REGION_OP: case AML_DATA_REGION_OP: if (Op->Common.AmlOpcode == AML_REGION_OP) { RegionSpace = (ACPI_ADR_SPACE_TYPE) ((Op->Common.Value.Arg)->Common.Value.Integer); } else { RegionSpace = ACPI_ADR_SPACE_DATA_TABLE; } /* * The OpRegion is not fully parsed at this time. The only valid * argument is the SpaceId. (We must save the address of the * AML of the address and length operands) * * If we have a valid region, initialize it. The namespace is * unlocked at this point. * * Need to unlock interpreter if it is locked (if we are running * a control method), in order to allow _REG methods to be run * during AcpiEvInitializeRegion. */ if (WalkState->MethodNode) { /* * Executing a method: initialize the region and unlock * the interpreter */ Status = AcpiExCreateRegion (Op->Named.Data, Op->Named.Length, RegionSpace, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } Status = AcpiEvInitializeRegion ( AcpiNsGetAttachedObject (Node)); break; case AML_NAME_OP: Status = AcpiDsCreateNode (WalkState, Node, Op); if (ACPI_FAILURE (Status)) { goto Cleanup; } #ifdef ACPI_EXEC_APP /* * AcpiExec support for namespace initialization file (initialize * Name opcodes in this code.) */ Namepath = AcpiNsGetExternalPathname (Node); Status = AeLookupInitFileEntry (Namepath, &ObjDesc); if (ACPI_SUCCESS (Status)) { /* Detach any existing object, attach new object */ if (Node->Object) { AcpiNsDetachObject (Node); } AcpiNsAttachObject (Node, ObjDesc, ObjDesc->Common.Type); } ACPI_FREE (Namepath); Status = AE_OK; #endif break; case AML_METHOD_OP: /* * MethodOp PkgLength NameString MethodFlags TermList * * Note: We must create the method node/object pair as soon as we * see the method declaration. This allows later pass1 parsing * of invocations of the method (need to know the number of * arguments.) */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "LOADING-Method: State=%p Op=%p NamedObj=%p\n", WalkState, Op, Op->Named.Node)); if (!AcpiNsGetAttachedObject (Op->Named.Node)) { WalkState->Operands[0] = ACPI_CAST_PTR (void, Op->Named.Node); WalkState->NumOperands = 1; Status = AcpiDsCreateOperands ( WalkState, Op->Common.Value.Arg); if (ACPI_SUCCESS (Status)) { Status = AcpiExCreateMethod ( Op->Named.Data, Op->Named.Length, WalkState); } WalkState->Operands[0] = NULL; WalkState->NumOperands = 0; if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } break; default: /* All NAMED_COMPLEX opcodes must be handled above */ break; } break; case AML_CLASS_INTERNAL: /* case AML_INT_NAMEPATH_OP: */ break; case AML_CLASS_METHOD_CALL: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "RESOLVING-MethodCall: State=%p Op=%p NamedObj=%p\n", WalkState, Op, Node)); /* * Lookup the method name and save the Node */ Status = AcpiNsLookup (WalkState->ScopeInfo, Arg->Common.Value.String, ACPI_TYPE_ANY, ACPI_IMODE_LOAD_PASS2, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, WalkState, &(NewNode)); if (ACPI_SUCCESS (Status)) { /* * Make sure that what we found is indeed a method * We didn't search for a method on purpose, to see if the name * would resolve */ if (NewNode->Type != ACPI_TYPE_METHOD) { Status = AE_AML_OPERAND_TYPE; } /* We could put the returned object (Node) on the object stack for * later, but for now, we will put it in the "op" object that the * parser uses, so we can get it again at the end of this scope */ Op->Common.Node = NewNode; } else { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, Arg->Common.Value.String, Status); } break; default: break; } Cleanup: /* Remove the Node pushed at the very beginning */ WalkState->Operands[0] = NULL; WalkState->NumOperands = 0; return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <poll.h> #include "devshell.h" void regular_poll_or_select_on_pipe_child(int rfd, int wfd) { const static char msg[] = "hello from poll1!"; int rc, tot = 0; char buf[64]; printf(STR_CHILD "Hello from child, wait 100ms\n"); usleep(100 * 1000); printf(STR_CHILD "write() on the pipe\n"); rc = write(wfd, msg, sizeof(msg)); if (rc <= 0) { printf(STR_CHILD "ERR: write() returned %d -> %s\n", rc, strerror(errno)); exit(1); } printf(STR_CHILD "wait 200ms\n"); usleep(200 * 1000); printf(STR_CHILD "read from rfd\n"); for (int i = 0; i < 64; i++) { rc = read(rfd, buf, sizeof(buf)); if (rc < 0) { printf( STR_CHILD "ERR: read() returned %d -> %s\n", rc, strerror(errno) ); exit(1); } if (rc == 0) break; tot += rc; } printf(STR_CHILD "tot read: %d\n", tot); printf(STR_CHILD "exit(0)\n"); exit(0); } /* Regular comunication with child via pipe, before poll timeout */ int cmd_poll1(int argc, char **argv) { struct pollfd fds[1]; int pipefd[2]; int wstatus; int rc, fl, tot; int failed = 0; char buf[64]; pid_t childpid; signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE */ printf(STR_PARENT "Calling pipe()\n"); rc = pipe(pipefd); if (rc < 0) { printf(STR_PARENT "pipe() failed. Error: %s\n", strerror(errno)); exit(1); } printf(STR_PARENT "fork()..\n"); childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) regular_poll_or_select_on_pipe_child(pipefd[0], pipefd[1]); fds[0] = (struct pollfd) { .fd = pipefd[0], /* read end of the pipe */ .events = POLLIN }; /* Now, wait for the child to start and write something to the pipe */ do { rc = poll(fds, 1, 3000 /* ms */); } while (rc < 0 && errno == EINTR); if (rc < 0) { printf(STR_PARENT "ERROR: poll() failed with: %s\n", strerror(errno)); failed = 1; goto wait_child_and_return; } if (rc == 0) { printf(STR_PARENT "ERROR: poll() timed out (unexpected)\n"); failed = 1; goto wait_child_and_return; } if (rc != 1) { printf(STR_PARENT "ERROR: poll() returned %d (expected: 1)\n", rc); failed = 1; goto wait_child_and_return; } if (!(fds[0].revents & POLLIN)) { printf(STR_PARENT "ERROR: no POLLIN in fds[0].revents\n"); failed = 1; goto wait_child_and_return; } rc = read(fds[0].fd, buf, sizeof(buf)); if (rc < 0) { printf( STR_PARENT "ERROR: read(fds[0]) failed with: %s\n", strerror(errno) ); failed = 1; goto wait_child_and_return; } buf[rc] = 0; printf(STR_PARENT "Got: '%s' from child\n", buf); printf(STR_PARENT "Now make wfd nonblock and fill the buffer\n"); fl = fcntl(pipefd[1], F_GETFL, 0); if (fl < 0) { printf(STR_PARENT "fcntl(pipefd[1]) failed with: %s\n", strerror(errno)); goto wait_child_and_return; } fl |= O_NONBLOCK; rc = fcntl(pipefd[1], F_SETFL, fl); DEVSHELL_CMD_ASSERT(rc == 0); tot = 0; do { if ((rc = write(pipefd[1], &buf[0], 1)) > 0) tot += rc; } while (rc > 0); printf(STR_PARENT "Restore the blocking mode on wfd\n"); rc = fcntl(pipefd[1], F_SETFL, fl & ~O_NONBLOCK); DEVSHELL_CMD_ASSERT(rc == 0); printf(STR_PARENT "The pipe buffer is full after writing %d bytes\n", tot); printf(STR_PARENT "Now poll() wfd with POLLOUT\n"); fds[0] = (struct pollfd) { .fd = pipefd[1], /* write end of the pipe */ .events = POLLOUT }; do { rc = poll(fds, 1, 3000 /* ms */); } while (rc < 0 && errno == EINTR); if (rc < 0) { printf(STR_PARENT "ERROR: poll() failed with: %s\n", strerror(errno)); failed = 1; goto wait_child_and_return; } if (rc == 0) { printf(STR_PARENT "ERROR: poll() timed out (unexpected)\n"); failed = 1; goto wait_child_and_return; } if (rc != 1) { printf(STR_PARENT "ERROR: poll() returned %d (expected: 1)\n", rc); failed = 1; goto wait_child_and_return; } if (!(fds[0].revents & POLLOUT)) { printf(STR_PARENT "ERROR: no POLLOUT in fds[0].revents\n"); failed = 1; goto wait_child_and_return; } printf(STR_PARENT "poll() completed with POLLOUT as expected\n"); wait_child_and_return: printf(STR_PARENT "waitpid()..\n"); rc = waitpid(childpid, &wstatus, 0); if (rc < 0) { printf(STR_PARENT "waitpid() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "waitpid() done\n"); close(pipefd[0]); close(pipefd[1]); return failed; } int cmd_poll2(int argc, char **argv) { int rc; struct pollfd fds[] = { { .fd = 0, .events = POLLIN } }; /* NOTE: using timeout of 1 ms which is < 1 tick */ printf("Running poll(fd, ..., 1 ms)\n"); rc = poll(fds, ARRAY_SIZE(fds), 1); if (rc < 0) { perror("poll"); return 1; } printf("poll() returned: %d\n", rc); if (rc != 0) { printf("poll() did *not* timeout as expected\n"); return 1; } printf("poll() timed out, as expected\n"); return 0; } int cmd_poll3(int argc, char **argv) { struct pollfd fds[1]; int pipefd[2]; char buf[64]; int rc; printf("Creating a pipe...\n"); rc = pipe(pipefd); if (rc < 0) { printf("pipe() failed. Error: %s\n", strerror(errno)); return 1; } fds[0] = (struct pollfd) { .fd = pipefd[0], .events = POLLIN }; printf("Running poll(rfd, ..., 0 ms)\n"); rc = poll(fds, ARRAY_SIZE(fds), 0); if (rc < 0) { perror("poll"); return 1; } printf("poll() returned (immediately): %d\n", rc); if (rc != 0) { printf("poll() did *not* return 0 as expected\n"); return 1; } printf("Write something on the pipe\n"); rc = write(pipefd[1], "hello", 5); DEVSHELL_CMD_ASSERT(rc == 5); printf("Running poll(rfd, ..., 0 ms)\n"); rc = poll(fds, ARRAY_SIZE(fds), 0); if (rc < 0) { perror("poll"); return 1; } printf("poll() returned (immediately): %d\n", rc); if (rc != 1) { printf("poll() did return 1 as expected\n"); return 1; } printf("fds[0].revents = %p\n", (void*)(long)fds[0].revents); if (!(fds[0].revents & POLLIN)) { printf("ERROR: fds[0].revents did *not* contain POLLIN, as expected\n"); return 1; } printf("Everything is alright, got POLLIN\n"); rc = read(fds[0].fd, buf, sizeof(buf)); DEVSHELL_CMD_ASSERT(rc > 0); buf[rc] = 0; printf("Got from the pipe: '%s'\n", buf); close(pipefd[0]); close(pipefd[1]); return 0; } static void wait_and_close_child(int fd) { printf(STR_CHILD "Sleep 100 ms\n"); usleep(100 * 1000); printf(STR_CHILD "Close the other side of the pipe [fd: %d]\n", fd); close(fd); printf(STR_CHILD "exit(0)\n"); exit(0); } static int common_pollerr_pollhup_test(const bool close_read) { struct pollfd fds[1]; int pipefd[2]; int wstatus; int rc; int saved_errno; pid_t childpid; int fail = 0; int fdn = close_read ? 0 : 1; const char *name = close_read ? "read" : "write"; signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE */ printf(STR_PARENT "Calling pipe()\n"); rc = pipe(pipefd); if (rc < 0) { printf(STR_PARENT "pipe() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "fork()..\n"); childpid = fork(); DEVSHELL_CMD_ASSERT(childpid >= 0); if (!childpid) wait_and_close_child(pipefd[fdn]); printf(STR_PARENT "Close the %s side of the pipe [fd: %d]\n", name, pipefd[fdn]); close(pipefd[fdn]); fds[0] = (struct pollfd) { .fd = pipefd[1 - fdn], /* read or write side of the pipe */ .events = 0 /* wait for errors */ }; printf(STR_PARENT "poll({pipefd[%d]: %d, 0}, ...)\n", 1-fdn, pipefd[1-fdn]); rc = poll(fds, 1, -1); if (rc < 0) { printf(STR_PARENT "poll() failed with: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "poll() returned: %d [expected: 0]\n", rc); if (fds[0].revents & POLLIN) printf(STR_PARENT "POLLIN in revents\n"); if (fds[0].revents & POLLOUT) printf(STR_PARENT "POLLOUT in revents\n"); if (fds[0].revents & POLLERR) printf(STR_PARENT "POLLERR in revents\n"); if (fds[0].revents & POLLHUP) printf(STR_PARENT "POLLHUP in revents\n"); if (close_read && !(fds[0].revents & POLLERR)) { printf(STR_PARENT "FAIL: No POLLERR in revents\n"); fail = 1; } if (!close_read && !(fds[0].revents & POLLHUP)) { printf(STR_PARENT "FAIL: No POLLHUP in revents\n"); fail = 1; } printf(STR_PARENT "waitpid()..\n"); rc = waitpid(childpid, &wstatus, 0); if (rc < 0) { printf(STR_PARENT "waitpid() failed. Error: %s\n", strerror(errno)); return 1; } printf(STR_PARENT "waitpid() done\n"); printf(STR_PARENT "%s()...\n", name); errno = 0; if (close_read) { rc = write(pipefd[1], &wstatus, sizeof(wstatus)); } else { rc = read(pipefd[0], &wstatus, sizeof(wstatus)); } saved_errno = errno; if (rc > 0) { /* if rc > 0, fail in both cases */ printf(STR_PARENT "FAIL: %s() unexpectedly returned %d!\n", name, rc); return 1; } printf(STR_PARENT "%s() returned %d; errno: %s\n", name, rc, saved_errno ? strerror(saved_errno) : "<no error>"); if (close_read) { /* * When we close the read side of the pipe, we expect the write() to fail * with -1 and errno to be EPIPE. */ if (!rc || saved_errno != EPIPE) fail = 1; } else { /* * When we close the write side of the pipe, we expect the read() to just * return 0. */ if (rc < 0) fail = 1; } if (fail) printf(STR_PARENT "TEST *FAILED*\n"); return fail; } /* * Use a pipe to communicate with child, expect POLLERR in parent after closing * the read side of the pipe. */ int cmd_pollerr(int argc, char **argv) { return common_pollerr_pollhup_test(true); } /* * Use a pipe to communicate with child, expect POLLHUP in parent after closing * the write side of the pipe. */ int cmd_pollhup(int argc, char **argv) { return common_pollerr_pollhup_test(false); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/sort.h> #include "wth_int.h" int worker_threads_cnt; struct worker_thread *worker_threads[WTH_MAX_THREADS]; u32 wth_get_queue_size(struct worker_thread *wth) { return wth->rb.max_elems; } struct task *wth_get_task(struct worker_thread *wth) { return wth->task; } int wth_get_priority(struct worker_thread *wth) { return wth->priority; } const char * wth_get_name(struct worker_thread *wth) { return wth->name; } static long wth_cmp_func(const void *a, const void *b) { const struct worker_thread *const *wa = a; const struct worker_thread *const *wb = b; return (*wa)->priority - (*wb)->priority; } NODISCARD bool wth_enqueue_on(struct worker_thread *t, void (*func)(void *), void *arg) { bool success, was_empty; ASSERT(t != NULL); struct wjob new_job = { .func = func, .arg = arg, }; disable_preemption(); #if DEBUG_CHECKS /* * Trying to enqueue a job from the same job thread can cause a deadlock when * the ringbuf is full if the caller waits in a loop for the enqueue to * succeed: the runner function won't get the control back until it gets the * control to execute a job and, clearly, this is a contradiction, leading to * an endless loop. Exception: if we're running in IRQ that interrupted the * current task, which might be the job runner we'd like to enqueue in, we * have to allow the enqueue to happen. Simple example: a key press generates * an IRQ #1 which interrupts the worker thread #1 and wants to enqueue a job * there. We MUST allow that to happen. */ if (get_curr_task() == t->task) check_in_irq_handler(); #endif success = safe_ringbuf_write_elem(&t->rb, &new_job, &was_empty); if (success && was_empty && t->waiting_for_jobs) { wth_wakeup(t); } enable_preemption(); return success; } NODISCARD bool wth_enqueue_anywhere(int lowest_prio, void (*func)(void *), void *arg) { struct worker_thread *wth; if (lowest_prio == 0) /* optimization for highest prio case */ return wth_enqueue_on(worker_threads[0], func, arg); for (int i = worker_threads_cnt-1; i >= 0; i--) { wth = worker_threads[i]; if (wth->name) continue; /* skip dedicated worker threads */ if (wth->priority > lowest_prio) continue; if (wth_enqueue_on(wth, func, arg)) return true; /* success */ } return false; } struct worker_thread * wth_find_worker(int lowest_prio) { struct worker_thread *wth; if (lowest_prio == 0) /* optimization for highest prio case */ return worker_threads[0]; for (int i = worker_threads_cnt-1; i >= 0; i--) { wth = worker_threads[i]; if (wth->name) continue; /* skip dedicated worker threads */ if (wth->priority <= lowest_prio) return wth; } return worker_threads[0]; } bool wth_process_single_job(struct worker_thread *t) { bool success; struct wjob job_to_run; success = safe_ringbuf_read_elem(&t->rb, &job_to_run); if (success) { /* Run the job with preemption enabled */ job_to_run.func(job_to_run.arg); } return success; } void wth_run(void *arg) { struct worker_thread *t = arg; bool job_run; ASSERT(t != NULL); DEBUG_SAVE_ESP() /* see debug_utils.h */ while (true) { DEBUG_CHECK_ESP() /* see debug_utils.h */ t->waiting_for_jobs = false; do { job_run = wth_process_single_job(t); } while (job_run); disable_interrupts_forced(); { if (safe_ringbuf_is_empty(&t->rb)) { t->task->state = TASK_STATE_SLEEPING; t->waiting_for_jobs = true; } } enable_interrupts_forced(); if (t->waiting_for_jobs) { kcond_signal_all(&t->completion); schedule(); } } } struct task *wth_get_runnable_thread(void) { ASSERT(!is_preemption_enabled()); struct worker_thread *selected = NULL; for (int i = 0; i < worker_threads_cnt; i++) { struct worker_thread *t = worker_threads[i]; if (t->task->state == TASK_STATE_RUNNABLE) if (!selected || t->priority < selected->priority) selected = t; } return selected ? selected->task : NULL; } struct worker_thread * wth_create_thread(const char *name, int priority, u16 queue_size) { struct worker_thread *t; int rc, idx; ASSERT(!is_preemption_enabled()); DEBUG_ONLY(check_not_in_irq_handler()); if (worker_threads_cnt >= ARRAY_SIZE(worker_threads)) return NULL; /* too many worker threads */ t = kzalloc_obj(struct worker_thread); if (!t) return NULL; idx = worker_threads_cnt; t->name = name; t->priority = priority; t->jobs = kzalloc_array_obj(struct wjob, queue_size); if (!t->jobs) { kfree_obj(t, struct worker_thread); return NULL; } kcond_init(&t->completion); safe_ringbuf_init(&t->rb, queue_size, sizeof(struct wjob), t->jobs); if ((rc = wth_create_thread_for(t))) { kfree_array_obj(t->jobs, struct wjob, queue_size); kfree_obj(t, struct worker_thread); return NULL; } worker_threads[idx] = t; /* Double-check that worker_threads_cnt did not change */ ASSERT(idx == worker_threads_cnt); worker_threads_cnt++; /* Sort all the worker threads */ insertion_sort_ptr(worker_threads, (u32)worker_threads_cnt, &wth_cmp_func); return t; } void wth_wait_for_completion(struct worker_thread *wth) { while (!wth->waiting_for_jobs) kcond_wait(&wth->completion, NULL, TIMER_HZ / 10); } static void init_wth_create_worker_or_die(int prio, u16 queue_size) { if (!wth_create_thread(NULL, prio, queue_size)) panic("WTH: failed to create worker thread with prio %d", prio); } void init_worker_threads(void) { worker_threads_cnt = 0; init_wth_create_worker_or_die(0, WTH_MAX_PRIO_QUEUE_SIZE); } <file_sep>#!/usr/bin/env sh sed -E -i 's/[a-f0-9]{8}/ADDR32/g' "$1" <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause ############################## # Build gtest ############################## GTEST_VER="1.12.1" GTEST_DIRNAME="gtest-$GTEST_VER" GTEST_SRC_DIR="$TC/noarch/$GTEST_DIRNAME" GMOCK_DIRNAME="gmock-$GTEST_VER" function download_googletest { local tarname="$GTEST_DIRNAME.tgz" local url="https://github.com/google/googletest.git" if ! [ -d $GTEST_SRC_DIR ]; then download_git_repo_in_cache "$url" release-$GTEST_VER $tarname googletest pushd $TC/noarch extract_cachefile_tar_gz $tarname "googletest" $GTEST_DIRNAME popd if [ -d $TC/cache/googletest ]; then # Delete the old locations of googletest # TODO: drop this once we upgrade to toolchain3 rm -rf $TC/cache/googletest rm -rf $TC/host_i386/gtest rm -rf $TC/host_x86_64/gtest fi if ! [ -L $TC/cache/googletest ]; then # Create a symlink to allow older commits being able to build # TODO: drop this once we upgrade to toolchain3 pushd $TC/cache ln -s $GTEST_SRC_DIR googletest popd fi fi } all_funcs_list+=(build_gtest) function build_gtest { download_googletest pushd host_$HOST_ARCH if ! [ -d $GTEST_DIRNAME ]; then show_work_on_component_msg "GOOGLE TEST ($HOST_ARCH)" mkdir $GTEST_DIRNAME cd $GTEST_DIRNAME reset_cc_vars $CMAKE \ -DCMAKE_BUILD_TYPE=Debug \ -DGOOGLETEST_VERSION=$GTEST_VER \ $GTEST_SRC_DIR/googletest run_command2 "make -j$BUILD_PAR" build.log else show_skip_component_msg "GOOGLE TEST ($HOST_ARCH)" fi popd } function build_gtest_installed_status { if [ -d $TC/host_$HOST_ARCH/$GTEST_DIRNAME ]; then if [ -f $TC/host_$HOST_ARCH/$GTEST_DIRNAME/lib/libgtest.a ]; then echo "installed host_$HOST_ARCH" else echo "error" fi fi } all_funcs_list+=(build_gmock) function build_gmock { download_googletest pushd host_$HOST_ARCH if ! [ -d $GMOCK_DIRNAME ]; then show_work_on_component_msg "GOOGLE MOCK ($HOST_ARCH)" mkdir $GMOCK_DIRNAME cd $GMOCK_DIRNAME reset_cc_vars $CMAKE \ -DCMAKE_BUILD_TYPE=Debug \ -DGOOGLETEST_VERSION=$GTEST_VER \ $GTEST_SRC_DIR/googlemock run_command2 "make -j$BUILD_PAR" build.log else show_skip_component_msg "GOOGLE MOCK ($HOST_ARCH)" fi popd } function build_gmock_installed_status { if [ -d $TC/host_$HOST_ARCH/$GMOCK_DIRNAME ]; then if [ -f $TC/host_$HOST_ARCH/$GMOCK_DIRNAME/lib/libgmock.a ]; then echo "installed host_$HOST_ARCH" else echo "error" fi fi } if [[ "$HOST_ARCH" == "x86_64" || "$HOST_ARCH" == "i386" ]]; then all_funcs_list+=(build_gtest_arch) fi function build_gtest_arch { download_googletest pushd host_$ARCH if ! [ -d $GTEST_DIRNAME ]; then show_work_on_component_msg "GOOGLE TEST ($ARCH)" download_gcc_glibc_toolchain # We have to save the current path and prepend the GLIBC toolchain # to it, because we're targeting the host system. local saved_path="$PATH" export PATH="$GCC_TOOLCHAIN_GLIBC:$PATH" mkdir $GTEST_DIRNAME cd $GTEST_DIRNAME # After this, we'll use the $GCC_TOOLCHAIN_GLIBC toolchain, which is # a cross-toolchain, but uses glibc. set_cc_vars_to_tc $CMAKE \ -DCMAKE_BUILD_TYPE=Debug \ -DGOOGLETEST_VERSION=$GTEST_VER \ $GTEST_SRC_DIR/googletest run_command2 "make -j" build.log # Restore the PATH so that other functions will end up calling the musl # toolchain with $ARCH-linux-gcc. export PATH="$saved_path" else show_skip_component_msg "GOOGLE TEST ($ARCH)" fi popd } function build_gtest_arch_installed_status { if [ -d $TC/host_$ARCH/$GTEST_DIRNAME ]; then if [ -f $TC/host_$ARCH/$GTEST_DIRNAME/lib/libgtest.a ]; then echo "installed host_$ARCH" else echo "failed" fi fi } if [[ "$HOST_ARCH" == "x86_64" || "$HOST_ARCH" == "i386" ]]; then all_funcs_list+=(build_gmock_arch) fi function build_gmock_arch { download_googletest pushd host_$ARCH if ! [ -d $GMOCK_DIRNAME ]; then show_work_on_component_msg "GOOGLE TEST ($ARCH)" download_gcc_glibc_toolchain # We have to save the current path and prepend the GLIBC toolchain # to it, because we're targeting the host system. local saved_path="$PATH" export PATH="$GCC_TOOLCHAIN_GLIBC:$PATH" mkdir $GMOCK_DIRNAME cd $GMOCK_DIRNAME # After this, we'll use the $GCC_TOOLCHAIN_GLIBC toolchain, which is # a cross-toolchain, but uses glibc. set_cc_vars_to_tc $CMAKE \ -DCMAKE_BUILD_TYPE=Debug \ -DGOOGLETEST_VERSION=$GTEST_VER \ $GTEST_SRC_DIR/googlemock run_command2 "make -j" build.log # Restore the PATH so that other functions will end up calling the musl # toolchain with $ARCH-linux-gcc. export PATH="$saved_path" else show_skip_component_msg "GOOGLE TEST ($ARCH)" fi popd } function build_gmock_arch_installed_status { if [ -d $TC/host_$ARCH/$GMOCK_DIRNAME ]; then if [ -f $TC/host_$ARCH/$GMOCK_DIRNAME/lib/libgmock.a ]; then echo "installed host_$ARCH" else echo "failed" fi fi } <file_sep> What is the purpose of this directory -------------------------------------- This directory has been created in order to facilitate the integration of 3rd-party projects with Tilck's build system. If a 3rd-party project follows the rules below, Tilck's build system will automatically compile and copy project's binaries in Tilck's image. An excellent example project is the `tfblib` project: https://github.com/vvaltchev/tfblib. It can be built independently as any CMake project for Linux on any architecture but, when a symlink (or a copy) of its root directory is put here in `extra`, it integrates *smoothly* with Tilck's build system and the binaries it produces become visible from `Tilck` in the `/usr/bin` directory. Integration rules ------------------- 1. The project must use `CMake` 2. The project must be written in C/C++ 3. The project must produce exclusively statically linked binaries 4. The project must work on same architecture `Tilck` is built for 5. The project must build correctly using a `libmusl` GCC toolchain 6. The project must be careful with the syscalls used. Many `Linux` syscalls are not supported yet on `Tilck`. See the supported syscalls in https://github.com/vvaltchev/tilck/blob/master/docs/syscalls.md 7. The project must *not* use the `project()` CMake command when it is being compiled in Tilck. In order detect that, use something like: ```CMake if (NOT "${CMAKE_PROJECT_NAME}" STREQUAL "tilck") project(Cool3rdPartyProject C) else() message(STATUS "Building Cool3rdPartyProject as part of Tilck") endif() ``` 8. At the end (preferably) of the root `CMakeLists.txt`, the 3rd project have to list the absolute path of all the binaries that have to be copied in Tilck's image, using the `tilck_add_extra_app()` CMake macro. For example: ```CMake if (${CMAKE_PROJECT_NAME} STREQUAL "tilck") tilck_add_extra_app(${CMAKE_CURRENT_BINARY_DIR}/SomeOutputDir/app1) endif() ``` The binaries enlisted this way will be visible from `Tilck` in `/usr/bin`. <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(GENERAL_DEFS_LIST "") if (CMAKE_BUILD_TYPE STREQUAL "Release") message(STATUS "Preparing a RELEASE build...") list(APPEND GENERAL_DEFS_LIST "-DNDEBUG -DTILCK_RELEASE_BUILD") set(OPT_FLAGS_LIST -O3) elseif (CMAKE_BUILD_TYPE STREQUAL "MinSizeRel") message(STATUS "Preparing a MinSizeRel build...") list(APPEND GENERAL_DEFS_LIST "-DNDEBUG -DTILCK_RELEASE_BUILD") set(OPT_FLAGS_LIST -Os) elseif (CMAKE_BUILD_TYPE STREQUAL "Debug") message(STATUS "Preparing a DEBUG build...") list(APPEND GENERAL_DEFS_LIST "-DTILCK_DEBUG_BUILD") set(OPT_FLAGS_LIST -O0 -fno-inline-functions) else() message(FATAL_ERROR "Unknown build type: '${CMAKE_BUILD_TYPE}'") endif() if (TEST_GCOV OR KERNEL_GCOV) if (NOT EXISTS ${TCROOT}/noarch/lcov-${LCOV_VER}) show_missing_lcov_error() endif() endif() if (TEST_GCOV) set(GCOV_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage") set(GCOV_LINK_FLAGS "-fprofile-arcs -lgcov") endif() set( DBG_FLAGS_LIST -ggdb -fno-omit-frame-pointer ) set( WARN_FLAGS_LIST -Wall -Wextra -Werror -Wshadow -Wvla -Wcast-align -Wno-unused-function -Wno-unused-parameter -Wno-unused-label ) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") if (WCONV) show_wconv_warning() endif() if (CMAKE_C_COMPILER_VERSION VERSION_LESS "5.0.0") # See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119 list(APPEND WARN_FLAGS_LIST "-Wno-missing-braces") list(APPEND WARN_FLAGS_LIST "-Wno-missing-field-initializers") endif() endif() if (CMAKE_C_COMPILER_ID STREQUAL "Clang") list(APPEND WARN_FLAGS_LIST "-Wno-missing-braces") if (USE_SYSCC) show_clang_and_syscc_error() endif() if (NOT KERNEL_SYSCC) if (WCONV) show_wconv_warning() endif() endif() endif() set( FREESTANDING_FLAGS_LIST -ffreestanding -fno-builtin ) JOIN("${FREESTANDING_FLAGS_LIST}" ${SPACE} FREESTANDING_FLAGS) set( SAFER_BEHAVIOR_FLAGS_LIST -fno-strict-aliasing -fwrapv -Wundef ) JOIN("${SAFER_BEHAVIOR_FLAGS_LIST}" ${SPACE} SAFER_BEHAVIOR_FLAGS) JOIN("${GENERAL_DEFS_LIST}" ${SPACE} GENERAL_DEFS) JOIN("${DBG_FLAGS_LIST}" ${SPACE} DBG_FLAGS) JOIN("${OPT_FLAGS_LIST}" ${SPACE} OPT_FLAGS) JOIN("${WARN_FLAGS_LIST}" ${SPACE} WARN_FLAGS) set(COMMON_FLAGS "${GENERAL_DEFS} ${DBG_FLAGS} ${OPT_FLAGS} ${WARN_FLAGS}") # Kernel flags set(GENERAL_KERNEL_FLAGS_LIST "") list( APPEND GENERAL_KERNEL_FLAGS_LIST -D__TILCK_KERNEL__ ${FREESTANDING_FLAGS_LIST} ${SAFER_BEHAVIOR_FLAGS_LIST} ) if (${KERNEL_SYSCC} OR ${USE_SYSCC}) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") # # Unfortunately, when FORTIFY_SOURCE is enabled, new GCC compilers like # 9.x require the libc to implement extra functions and, apparently, they # don't care about -ffreestanding, nor care to put those functions in # libgcc, which Tilck links, statically. # # Therefore, in SYSCC builds, we fail with: # # select.c:126: undefined reference to `__fdelt_chk' # # For the moment, it's OK to just disable those extra checks. # TODO: consider enabling _FORTIFY_SOURCE in Tilck. # list( APPEND GENERAL_KERNEL_FLAGS_LIST -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 ) endif() endif() if (WCONV) list(APPEND GENERAL_KERNEL_FLAGS_LIST "-Wconversion") endif() if (KERNEL_UBSAN) list( APPEND GENERAL_KERNEL_FLAGS_LIST -fsanitize=integer-divide-by-zero -fsanitize=nonnull-attribute,returns-nonnull-attribute -fsanitize=bool,enum -fsanitize=unreachable -fsanitize=null ) # # Cannot enable -fsanitize=alignment, with Clang because it generates leaf # functions which misalign the stack pointer. What happens when get an IRQ # while running one of those functions? If UBSAN is enabled, we'll get # panic, otherwise everything is fine, because x86 allows unaligned access. # # See: # - https://bugs.llvm.org/show_bug.cgi?id=49828 # - https://forum.osdev.org/viewtopic.php?f=13&t=42430&start=0 # if (CMAKE_C_COMPILER_ID STREQUAL "GNU") list( APPEND GENERAL_KERNEL_FLAGS_LIST -fsanitize=alignment -fsanitize-recover=alignment ) endif() if (NOT ${GCC_TC_VER} VERSION_LESS "7.3.0") # GCC >= 7.3.0 support some additional UBSAN features. list( APPEND GENERAL_KERNEL_FLAGS_LIST -fsanitize=shift-exponent -fsanitize=shift-base ) endif() endif() JOIN("${GENERAL_KERNEL_FLAGS_LIST}" ${SPACE} GENERAL_KERNEL_FLAGS) set(KERNEL_FLAGS "${COMMON_FLAGS} ${GENERAL_KERNEL_FLAGS}") set( KERNEL_NO_ARCH_FLAGS_LIST -DKERNEL_TEST -fPIC ${KERNEL_FLAGS} ${GCOV_COMPILE_FLAGS} ) JOIN("${KERNEL_NO_ARCH_FLAGS_LIST}" ${SPACE} KERNEL_NO_ARCH_FLAGS) set( KERNEL_CXX_FLAGS_LIST -fno-exceptions -fno-use-cxa-atexit -fno-rtti ) JOIN("${KERNEL_CXX_FLAGS_LIST}" ${SPACE} KERNEL_CXX_FLAGS) set( LOWLEVEL_BINARIES_FLAGS_LIST -fno-common -fno-exceptions -fno-stack-protector -fno-asynchronous-unwind-tables -mno-red-zone # Allow easier disassembly debugging # -mpush-args # -mno-accumulate-outgoing-args # -mno-stack-arg-probe ) JOIN("${LOWLEVEL_BINARIES_FLAGS_LIST}" ${SPACE} LOWLEVEL_BINARIES_FLAGS) # # On x86, -mgeneral-regs-only is supported only by GCC >= 7.0. # Clang supports it only on Aarch64 and the patch for making it generic # has been abandoned: https://reviews.llvm.org/D38479 # set(MGENERAL_REGS_ONLY_SUPPORTED OFF) if (${KERNEL_SYSCC} OR ${USE_SYSCC}) # Special case: we're using the system compiler if (CMAKE_C_COMPILER_ID STREQUAL "GNU") if (${CMAKE_C_COMPILER_VERSION} VERSION_LESS "7.3.0") # GCC-only flags for older GCC compilers list( APPEND DISABLE_FPU_FLAGS_LIST -mno-fp-ret-in-387 -mskip-rax-setup ) else() set(MGENERAL_REGS_ONLY_SUPPORTED ON) endif() endif() else() # DEFAULT CASE: we're using a GCC compiler from our toolchain if (${GCC_TC_VER} VERSION_LESS "7.3.0") # GCC-only flags for older GCC compilers list( APPEND DISABLE_FPU_FLAGS_LIST -mno-fp-ret-in-387 -mskip-rax-setup ) else() set(MGENERAL_REGS_ONLY_SUPPORTED ON) endif() endif() # Disable the generation of any kind of FPU instructions if (${MGENERAL_REGS_ONLY_SUPPORTED}) list( APPEND DISABLE_FPU_FLAGS_LIST -mgeneral-regs-only ) else() list( APPEND DISABLE_FPU_FLAGS_LIST -mno-80387 -mno-mmx -mno-3dnow -mno-sse -mno-sse2 -mno-avx ) endif() JOIN("${DISABLE_FPU_FLAGS_LIST}" ${SPACE} DISABLE_FPU_FLAGS) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/config_kernel.h> #if ARCH_BITS == 32 #define USE_ELF32 #else #define USE_ELF64 #endif #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/elf_types.h> #include <elf.h> /* * Simple ELF loader used by both the EFI bootloader and the legacy one. * It assumes that the whole ELF file is loaded in memory at the address * pointed by `elf`. It returns the physical address of executable's entry * point, even when `header->e_entry` is a virtual address (see the code). */ void *simple_elf_loader(void *elf) { Elf_Ehdr *header = elf; Elf_Phdr *phdr = (Elf_Phdr *)((char*)header + header->e_phoff); void *entry; /* Just set the entry in case the search with IN_RANGE() below fails */ entry = TO_PTR(header->e_entry); for (int i = 0; i < header->e_phnum; i++, phdr++) { // Ignore non-load segments. if (phdr->p_type != PT_LOAD) continue; bzero(TO_PTR(phdr->p_paddr), phdr->p_memsz); memcpy(TO_PTR(phdr->p_paddr), (char *) header + phdr->p_offset, phdr->p_filesz); if (IN_RANGE(header->e_entry, phdr->p_vaddr, phdr->p_vaddr + phdr->p_filesz)) { /* * If e_entry is a vaddr (address >= KERNEL_BASE_VA), we need to * calculate its paddr because here paging is OFF. Therefore, * compute its offset from the beginning of the segment and add it * to the paddr of the segment. */ entry = TO_PTR(phdr->p_paddr + (header->e_entry - phdr->p_vaddr)); } } return entry; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <locale.h> #include <ncurses/ncurses.h> #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) #define printc(name) printw(#name ": "); addch(name); printw("\n"); static const char *msg_next = "Press ANY key to move to the next screen or 'q' to exit"; static const char *msg_last = "Press ANY key to exit"; static void scr_special_chars(void) { printw("Special characters:\n"); /* Expected to work on all linux terminals. Work on Tilck. */ printc(ACS_HLINE); printc(ACS_LLCORNER); printc(ACS_ULCORNER); printc(ACS_VLINE); printc(ACS_LRCORNER); printc(ACS_URCORNER); printc(ACS_LTEE); printc(ACS_RTEE); printc(ACS_BTEE); printc(ACS_TTEE); printc(ACS_PLUS); /* Mostly work on all linux terminals. Work on Tilck. */ printc(ACS_DIAMOND); printc(ACS_CKBOARD); printc(ACS_DEGREE); printc(ACS_PLMINUS); printc(ACS_BULLET); /* Not expected to work on all linux terminals. Work on Tilck. */ printc(ACS_LARROW); printc(ACS_RARROW); printc(ACS_DARROW); printc(ACS_UARROW); printc(ACS_BOARD); printc(ACS_BLOCK); } static void scr_colors(void) { printw("Colors:\n"); for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) init_pair(1 + 8 * i + j, i, j); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { attron(COLOR_PAIR(1 + 8 * i + j)); printw("a"); attroff(COLOR_PAIR(1 + 8 * i + j)); } printw("\n"); } for (int i = 0; i < 8; i++) init_pair(i+1, i, COLOR_BLACK); for (int i = 0; i < 8; i++) { attron(COLOR_PAIR(i+1)); printw("Normal "); attroff(COLOR_PAIR(i+1)); attron(COLOR_PAIR(i+1) | A_BOLD); printw("Bright "); attroff(COLOR_PAIR(i+1) | A_BOLD); attron(COLOR_PAIR(i+1) | A_REVERSE); printw("Reverse"); attroff(COLOR_PAIR(i+1) | A_REVERSE); printw(" "); attron(COLOR_PAIR(i+1) | A_REVERSE | A_BOLD); printw("Rev+bright\n"); attroff(COLOR_PAIR(i+1) | A_REVERSE | A_BOLD); } } static void (*const funcs[])(void) = { &scr_special_chars, &scr_colors }; int main() { initscr(); if (!has_colors()) { endwin(); printf("No color support\n"); return 1; } cbreak(); noecho(); start_color(); for (unsigned i = 0; i < ARRAY_SIZE(funcs); i++) { clear(); move(0, 0); funcs[i](); refresh(); mvprintw(LINES - 1, 0, i < ARRAY_SIZE(funcs) - 1 ? msg_next : msg_last); if (getch() == 'q') break; } endwin(); printf("the application exited gracefully\n"); return 0; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause LUA_VER="5.4.1" function download_lua { local version="$LUA_VER" local filename="lua" local tarname="lua-$version.tar.gz" local url="https://www.lua.org/ftp/" download_file_in_cache "$url" "$tarname" lua extract_cachefile_tar_gz "$tarname" "lua-$version" "lua" } all_funcs_list+=(build_lua) function build_lua { pushd $ARCH reset_cc_vars show_work_on_component_msg "LUA" if ! [ -d "lua" ]; then download_lua cd lua if [[ "$HOST_ARCH" == "$ARCH" ]]; then # Remember: this scenario (building on $ARCH) is _not_ officially # supported. export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" export CC="$MAIN_DIR/scripts/build_scripts/${ARCH}-gcc" export CXX="$MAIN_DIR/scripts/build_scripts/${ARCH}-g++" else set_cc_vars_to_tc fi # Patch Lua's Makefile to remove "-Wl,-E" sed -i 's/-Wl,-E//g' src/Makefile # Build the lua and luac static binaries echo "Building lua..." local flags="" flags="CC=\"$CC\" MYCFLAGS=\"-std=gnu99\"" flags="$flags AR=\"$AR rcu\" RANLIB=\"$RANLIB\"" flags="$flags MYLDFLAGS=\"-static\"" run_command2 "make $flags" build.log echo "Lua built successfully" else show_skip_component_msg "LUA" fi reset_cc_vars popd } function build_lua_installed_status { if [ -d $TC/$ARCH/lua ]; then if [ -f $TC/$ARCH/lua/src/lua ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # Constants GCC_MIN_VERSION="6.4.0" GXX_MIN_VERSION="6.4.0" # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/.. && pwd)" source $MAIN_DIR/scripts/bash_includes/script_utils if [[ "$1" == "--contrib" ]]; then export CC='clang' export CXX='clang++' CMAKE_ARGS="-DKERNEL_SYSCC=1 -DWCONV=1 -DKMALLOC_HEAVY_STATS=1" CMAKE_ARGS="$CMAKE_ARGS -DTIMER_HZ=250 -DTERM_BIG_SCROLL_BUF=1" CMAKE_ARGS="$CMAKE_ARGS -DKRN_RESCHED_ENABLE_PREEMPT=1" CMAKE_ARGS="$CMAKE_ARGS -DKERNEL_UBSAN=1" CMAKE_ARGS="$CMAKE_ARGS -DBOOTLOADER_POISON_MEMORY=1" CMAKE_ARGS="$CMAKE_ARGS -DKMALLOC_FREE_MEM_POISONING=1" export CMAKE_ARGS echo echo -e "${YELLOW}Contributor mode${RATTRS}: " echo echo -e " - CC=${LMAGENTA}'${CC}'${RATTRS}" echo -e " - CXX=${LMAGENTA}'${CXX}'${RATTRS}" echo -e " - CMAKE_ARGS=${LMAGENTA}'${CMAKE_ARGS}'${RATTRS}" echo elif [[ "$1" == "--intr" ]]; then export CC="gcc" export CXX="g++" CMAKE_ARGS="-DFB_CONSOLE_BANNER=0 -DFB_CONSOLE_CURSOR_BLINK=0" CMAKE_ARGS="$CMAKE_ARGS -DFB_CONSOLE_USE_ALT_FONTS=0 -DTTY_COUNT=2" CMAKE_ARGS="$CMAKE_ARGS -DEXTRA_VIM=1 -DKRN_NO_SYS_WARN=0" CMAKE_ARGS="$CMAKE_ARGS -DBOOT_INTERACTIVE=0 -DPREFERRED_GFX_MODE_W=640" CMAKE_ARGS="$CMAKE_ARGS -DPREFERRED_GFX_MODE_H=480 -DMOD_acpi=0" export CMAKE_ARGS echo echo -e "${YELLOW}Interactive tests mode${RATTRS}" echo echo -e " - CC=${LMAGENTA}'${CC}'${RATTRS}" echo -e " - CXX=${LMAGENTA}'${CXX}'${RATTRS}" echo -e " - TEST_GCOV=${LMAGENTA}'${TEST_GCOV}'${RATTRS}" echo -e " - KERNEL_GCOV=${LMAGENTA}'${KERNEL_GCOV}'${RATTRS}" echo -e " - CMAKE_ARGS=${LMAGENTA}'${CMAKE_ARGS}'${RATTRS}" echo fi curr_dir="`pwd`" if [[ "$curr_dir" == "$MAIN_DIR" ]]; then build_dir="$MAIN_DIR/build" mkdir -p "$build_dir" else build_dir="$curr_dir" fi echo "[cmake_run] Using '$build_dir' as build directory" # If CC is set but the file $CC does not exist # replace CC with `which $CC` (its absolute path) if [ -n "$CC" ] && [ ! -f "$CC" ]; then CC="`which $CC`" fi # If CXX is set but the file $CXX does not exist # replace CXX with `which $CXX` (its absolute path) if [ -n "$CXX" ] && [ ! -f "$CXX" ]; then CXX="`which $CXX`" fi # Check compiler's version only if this is the first time we ran CMake: # after that, CMake will cache compiler's information and changing CC/CXX # won't affect the build at all. if ! [ -f "$build_dir/CMakeCache.txt" ]; then if [ -z "$CC" ]; then CC="gcc" fi if [ -z "$CXX" ]; then CXX="g++" fi if ! which $CC &> /dev/null; then echo "CC compiler '$CC' not found." exit 1 fi if ! which $CXX &> /dev/null; then echo "CXX compiler '$CXX' not found." exit 1 fi if $CC --version | grep gcc &> /dev/null; then ver=$(generic_get_version_str $CC) fail_if_too_old $CC $ver $GCC_MIN_VERSION fi if $CXX --version | grep g++ &> /dev/null; then ver=$(generic_get_version_str $CXX) fail_if_too_old $CXX $ver $GXX_MIN_VERSION fi fi export CC export CXX if [ -f $MAIN_DIR/toolchain2/host/cmake/bin/cmake ]; then export CMAKE="$MAIN_DIR/toolchain2/host/cmake/bin/cmake" else export CMAKE="cmake" fi if [[ "$RELEASE" == "1" || "$REL" == "1" ]]; then BUILD_TYPE="Release" else BUILD_TYPE="Debug" fi echo "[cmake_run] Using '$CMAKE' as CMake executable" cd $build_dir $CMAKE \ -DCMAKE_BUILD_TYPE=$BUILD_TYPE \ -DCMAKE_EXPORT_COMPILE_COMMANDS=1 \ $CMAKE_ARGS "$@" "$MAIN_DIR" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/sort.h> static int mods_count; static struct module *modules[32]; void register_module(struct module *m) { ASSERT(mods_count < ARRAY_SIZE(modules) - 1); modules[mods_count++] = m; } static long mod_cmp_func(const void *a, const void *b) { const struct module * const *ma = a; const struct module * const *mb = b; return (*ma)->priority - (*mb)->priority; } void init_modules(void) { insertion_sort_ptr(modules, (u32)mods_count, &mod_cmp_func); for (int i = 0; i < mods_count; i++) { struct module *m = modules[i]; printk("*** Init kernel module: %s\n", m->name); m->init(); } } <file_sep>/****************************************************************************** * * Name: actbl.h - Basic ACPI Table Definitions * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACTBL_H__ #define __ACTBL_H__ /******************************************************************************* * * Fundamental ACPI tables * * This file contains definitions for the ACPI tables that are directly consumed * by ACPICA. All other tables are consumed by the OS-dependent ACPI-related * device drivers and other OS support code. * * The RSDP and FACS do not use the common ACPI table header. All other ACPI * tables use the header. * ******************************************************************************/ /* * Values for description table header signatures for tables defined in this * file. Useful because they make it more difficult to inadvertently type in * the wrong signature. */ #define ACPI_SIG_DSDT "DSDT" /* Differentiated System Description Table */ #define ACPI_SIG_FADT "FACP" /* Fixed ACPI Description Table */ #define ACPI_SIG_FACS "FACS" /* Firmware ACPI Control Structure */ #define ACPI_SIG_OSDT "OSDT" /* Override System Description Table */ #define ACPI_SIG_PSDT "PSDT" /* Persistent System Description Table */ #define ACPI_SIG_RSDP "RSD PTR " /* Root System Description Pointer */ #define ACPI_SIG_RSDT "RSDT" /* Root System Description Table */ #define ACPI_SIG_XSDT "XSDT" /* Extended System Description Table */ #define ACPI_SIG_SSDT "SSDT" /* Secondary System Description Table */ #define ACPI_RSDP_NAME "RSDP" /* Short name for RSDP, not signature */ #define ACPI_OEM_NAME "OEM" /* Short name for OEM, not signature */ /* * All tables and structures must be byte-packed to match the ACPI * specification, since the tables are provided by the system BIOS */ #pragma pack(1) /* * Note: C bitfields are not used for this reason: * * "Bitfields are great and easy to read, but unfortunately the C language * does not specify the layout of bitfields in memory, which means they are * essentially useless for dealing with packed data in on-disk formats or * binary wire protocols." (Or ACPI tables and buffers.) "If you ask me, * this decision was a design error in C. Ritchie could have picked an order * and stuck with it." <NAME>. * See http://stackoverflow.com/a/1053662/41661 */ /******************************************************************************* * * Master ACPI Table Header. This common header is used by all ACPI tables * except the RSDP and FACS. * ******************************************************************************/ typedef struct acpi_table_header { char Signature[ACPI_NAMESEG_SIZE]; /* ASCII table signature */ UINT32 Length; /* Length of table in bytes, including this header */ UINT8 Revision; /* ACPI Specification minor version number */ UINT8 Checksum; /* To make sum of entire table == 0 */ char OemId[ACPI_OEM_ID_SIZE]; /* ASCII OEM identification */ char OemTableId[ACPI_OEM_TABLE_ID_SIZE]; /* ASCII OEM table identification */ UINT32 OemRevision; /* OEM revision number */ char AslCompilerId[ACPI_NAMESEG_SIZE]; /* ASCII ASL compiler vendor ID */ UINT32 AslCompilerRevision; /* ASL compiler version */ } ACPI_TABLE_HEADER; /******************************************************************************* * * GAS - Generic Address Structure (ACPI 2.0+) * * Note: Since this structure is used in the ACPI tables, it is byte aligned. * If misaligned access is not supported by the hardware, accesses to the * 64-bit Address field must be performed with care. * ******************************************************************************/ typedef struct acpi_generic_address { UINT8 SpaceId; /* Address space where struct or register exists */ UINT8 BitWidth; /* Size in bits of given register */ UINT8 BitOffset; /* Bit offset within the register */ UINT8 AccessWidth; /* Minimum Access size (ACPI 3.0) */ UINT64 Address; /* 64-bit address of struct or register */ } ACPI_GENERIC_ADDRESS; /******************************************************************************* * * RSDP - Root System Description Pointer (Signature is "RSD PTR ") * Version 2 * ******************************************************************************/ typedef struct acpi_table_rsdp { char Signature[8]; /* ACPI signature, contains "RSD PTR " */ UINT8 Checksum; /* ACPI 1.0 checksum */ char OemId[ACPI_OEM_ID_SIZE]; /* OEM identification */ UINT8 Revision; /* Must be (0) for ACPI 1.0 or (2) for ACPI 2.0+ */ UINT32 RsdtPhysicalAddress; /* 32-bit physical address of the RSDT */ UINT32 Length; /* Table length in bytes, including header (ACPI 2.0+) */ UINT64 XsdtPhysicalAddress; /* 64-bit physical address of the XSDT (ACPI 2.0+) */ UINT8 ExtendedChecksum; /* Checksum of entire table (ACPI 2.0+) */ UINT8 Reserved[3]; /* Reserved, must be zero */ } ACPI_TABLE_RSDP; /* Standalone struct for the ACPI 1.0 RSDP */ typedef struct acpi_rsdp_common { char Signature[8]; UINT8 Checksum; char OemId[ACPI_OEM_ID_SIZE]; UINT8 Revision; UINT32 RsdtPhysicalAddress; } ACPI_RSDP_COMMON; /* Standalone struct for the extended part of the RSDP (ACPI 2.0+) */ typedef struct acpi_rsdp_extension { UINT32 Length; UINT64 XsdtPhysicalAddress; UINT8 ExtendedChecksum; UINT8 Reserved[3]; } ACPI_RSDP_EXTENSION; /******************************************************************************* * * RSDT/XSDT - Root System Description Tables * Version 1 (both) * ******************************************************************************/ typedef struct acpi_table_rsdt { ACPI_TABLE_HEADER Header; /* Common ACPI table header */ UINT32 TableOffsetEntry[1]; /* Array of pointers to ACPI tables */ } ACPI_TABLE_RSDT; typedef struct acpi_table_xsdt { ACPI_TABLE_HEADER Header; /* Common ACPI table header */ UINT64 TableOffsetEntry[1]; /* Array of pointers to ACPI tables */ } ACPI_TABLE_XSDT; #define ACPI_RSDT_ENTRY_SIZE (sizeof (UINT32)) #define ACPI_XSDT_ENTRY_SIZE (sizeof (UINT64)) /******************************************************************************* * * FACS - Firmware ACPI Control Structure (FACS) * ******************************************************************************/ typedef struct acpi_table_facs { char Signature[4]; /* ASCII table signature */ UINT32 Length; /* Length of structure, in bytes */ UINT32 HardwareSignature; /* Hardware configuration signature */ UINT32 FirmwareWakingVector; /* 32-bit physical address of the Firmware Waking Vector */ UINT32 GlobalLock; /* Global Lock for shared hardware resources */ UINT32 Flags; UINT64 XFirmwareWakingVector; /* 64-bit version of the Firmware Waking Vector (ACPI 2.0+) */ UINT8 Version; /* Version of this table (ACPI 2.0+) */ UINT8 Reserved[3]; /* Reserved, must be zero */ UINT32 OspmFlags; /* Flags to be set by OSPM (ACPI 4.0) */ UINT8 Reserved1[24]; /* Reserved, must be zero */ } ACPI_TABLE_FACS; /* Masks for GlobalLock flag field above */ #define ACPI_GLOCK_PENDING (1) /* 00: Pending global lock ownership */ #define ACPI_GLOCK_OWNED (1<<1) /* 01: Global lock is owned */ /* Masks for Flags field above */ #define ACPI_FACS_S4_BIOS_PRESENT (1) /* 00: S4BIOS support is present */ #define ACPI_FACS_64BIT_WAKE (1<<1) /* 01: 64-bit wake vector supported (ACPI 4.0) */ /* Masks for OspmFlags field above */ #define ACPI_FACS_64BIT_ENVIRONMENT (1) /* 00: 64-bit wake environment is required (ACPI 4.0) */ /******************************************************************************* * * FADT - Fixed ACPI Description Table (Signature "FACP") * Version 6 * ******************************************************************************/ /* Fields common to all versions of the FADT */ typedef struct acpi_table_fadt { ACPI_TABLE_HEADER Header; /* Common ACPI table header */ UINT32 Facs; /* 32-bit physical address of FACS */ UINT32 Dsdt; /* 32-bit physical address of DSDT */ UINT8 Model; /* System Interrupt Model (ACPI 1.0) - not used in ACPI 2.0+ */ UINT8 PreferredProfile; /* Conveys preferred power management profile to OSPM. */ UINT16 SciInterrupt; /* System vector of SCI interrupt */ UINT32 SmiCommand; /* 32-bit Port address of SMI command port */ UINT8 AcpiEnable; /* Value to write to SMI_CMD to enable ACPI */ UINT8 AcpiDisable; /* Value to write to SMI_CMD to disable ACPI */ UINT8 S4BiosRequest; /* Value to write to SMI_CMD to enter S4BIOS state */ UINT8 PstateControl; /* Processor performance state control*/ UINT32 Pm1aEventBlock; /* 32-bit port address of Power Mgt 1a Event Reg Blk */ UINT32 Pm1bEventBlock; /* 32-bit port address of Power Mgt 1b Event Reg Blk */ UINT32 Pm1aControlBlock; /* 32-bit port address of Power Mgt 1a Control Reg Blk */ UINT32 Pm1bControlBlock; /* 32-bit port address of Power Mgt 1b Control Reg Blk */ UINT32 Pm2ControlBlock; /* 32-bit port address of Power Mgt 2 Control Reg Blk */ UINT32 PmTimerBlock; /* 32-bit port address of Power Mgt Timer Ctrl Reg Blk */ UINT32 Gpe0Block; /* 32-bit port address of General Purpose Event 0 Reg Blk */ UINT32 Gpe1Block; /* 32-bit port address of General Purpose Event 1 Reg Blk */ UINT8 Pm1EventLength; /* Byte Length of ports at Pm1xEventBlock */ UINT8 Pm1ControlLength; /* Byte Length of ports at Pm1xControlBlock */ UINT8 Pm2ControlLength; /* Byte Length of ports at Pm2ControlBlock */ UINT8 PmTimerLength; /* Byte Length of ports at PmTimerBlock */ UINT8 Gpe0BlockLength; /* Byte Length of ports at Gpe0Block */ UINT8 Gpe1BlockLength; /* Byte Length of ports at Gpe1Block */ UINT8 Gpe1Base; /* Offset in GPE number space where GPE1 events start */ UINT8 CstControl; /* Support for the _CST object and C-States change notification */ UINT16 C2Latency; /* Worst case HW latency to enter/exit C2 state */ UINT16 C3Latency; /* Worst case HW latency to enter/exit C3 state */ UINT16 FlushSize; /* Processor memory cache line width, in bytes */ UINT16 FlushStride; /* Number of flush strides that need to be read */ UINT8 DutyOffset; /* Processor duty cycle index in processor P_CNT reg */ UINT8 DutyWidth; /* Processor duty cycle value bit width in P_CNT register */ UINT8 DayAlarm; /* Index to day-of-month alarm in RTC CMOS RAM */ UINT8 MonthAlarm; /* Index to month-of-year alarm in RTC CMOS RAM */ UINT8 Century; /* Index to century in RTC CMOS RAM */ UINT16 BootFlags; /* IA-PC Boot Architecture Flags (see below for individual flags) */ UINT8 Reserved; /* Reserved, must be zero */ UINT32 Flags; /* Miscellaneous flag bits (see below for individual flags) */ ACPI_GENERIC_ADDRESS ResetRegister; /* 64-bit address of the Reset register */ UINT8 ResetValue; /* Value to write to the ResetRegister port to reset the system */ UINT16 ArmBootFlags; /* ARM-Specific Boot Flags (see below for individual flags) (ACPI 5.1) */ UINT8 MinorRevision; /* FADT Minor Revision (ACPI 5.1) */ UINT64 XFacs; /* 64-bit physical address of FACS */ UINT64 XDsdt; /* 64-bit physical address of DSDT */ ACPI_GENERIC_ADDRESS XPm1aEventBlock; /* 64-bit Extended Power Mgt 1a Event Reg Blk address */ ACPI_GENERIC_ADDRESS XPm1bEventBlock; /* 64-bit Extended Power Mgt 1b Event Reg Blk address */ ACPI_GENERIC_ADDRESS XPm1aControlBlock; /* 64-bit Extended Power Mgt 1a Control Reg Blk address */ ACPI_GENERIC_ADDRESS XPm1bControlBlock; /* 64-bit Extended Power Mgt 1b Control Reg Blk address */ ACPI_GENERIC_ADDRESS XPm2ControlBlock; /* 64-bit Extended Power Mgt 2 Control Reg Blk address */ ACPI_GENERIC_ADDRESS XPmTimerBlock; /* 64-bit Extended Power Mgt Timer Ctrl Reg Blk address */ ACPI_GENERIC_ADDRESS XGpe0Block; /* 64-bit Extended General Purpose Event 0 Reg Blk address */ ACPI_GENERIC_ADDRESS XGpe1Block; /* 64-bit Extended General Purpose Event 1 Reg Blk address */ ACPI_GENERIC_ADDRESS SleepControl; /* 64-bit Sleep Control register (ACPI 5.0) */ ACPI_GENERIC_ADDRESS SleepStatus; /* 64-bit Sleep Status register (ACPI 5.0) */ UINT64 HypervisorId; /* Hypervisor Vendor ID (ACPI 6.0) */ } ACPI_TABLE_FADT; /* Masks for FADT IA-PC Boot Architecture Flags (boot_flags) [Vx]=Introduced in this FADT revision */ #define ACPI_FADT_LEGACY_DEVICES (1) /* 00: [V2] System has LPC or ISA bus devices */ #define ACPI_FADT_8042 (1<<1) /* 01: [V3] System has an 8042 controller on port 60/64 */ #define ACPI_FADT_NO_VGA (1<<2) /* 02: [V4] It is not safe to probe for VGA hardware */ #define ACPI_FADT_NO_MSI (1<<3) /* 03: [V4] Message Signaled Interrupts (MSI) must not be enabled */ #define ACPI_FADT_NO_ASPM (1<<4) /* 04: [V4] PCIe ASPM control must not be enabled */ #define ACPI_FADT_NO_CMOS_RTC (1<<5) /* 05: [V5] No CMOS real-time clock present */ /* Masks for FADT ARM Boot Architecture Flags (arm_boot_flags) ACPI 5.1 */ #define ACPI_FADT_PSCI_COMPLIANT (1) /* 00: [V5+] PSCI 0.2+ is implemented */ #define ACPI_FADT_PSCI_USE_HVC (1<<1) /* 01: [V5+] HVC must be used instead of SMC as the PSCI conduit */ /* Masks for FADT flags */ #define ACPI_FADT_WBINVD (1) /* 00: [V1] The WBINVD instruction works properly */ #define ACPI_FADT_WBINVD_FLUSH (1<<1) /* 01: [V1] WBINVD flushes but does not invalidate caches */ #define ACPI_FADT_C1_SUPPORTED (1<<2) /* 02: [V1] All processors support C1 state */ #define ACPI_FADT_C2_MP_SUPPORTED (1<<3) /* 03: [V1] C2 state works on MP system */ #define ACPI_FADT_POWER_BUTTON (1<<4) /* 04: [V1] Power button is handled as a control method device */ #define ACPI_FADT_SLEEP_BUTTON (1<<5) /* 05: [V1] Sleep button is handled as a control method device */ #define ACPI_FADT_FIXED_RTC (1<<6) /* 06: [V1] RTC wakeup status is not in fixed register space */ #define ACPI_FADT_S4_RTC_WAKE (1<<7) /* 07: [V1] RTC alarm can wake system from S4 */ #define ACPI_FADT_32BIT_TIMER (1<<8) /* 08: [V1] ACPI timer width is 32-bit (0=24-bit) */ #define ACPI_FADT_DOCKING_SUPPORTED (1<<9) /* 09: [V1] Docking supported */ #define ACPI_FADT_RESET_REGISTER (1<<10) /* 10: [V2] System reset via the FADT RESET_REG supported */ #define ACPI_FADT_SEALED_CASE (1<<11) /* 11: [V3] No internal expansion capabilities and case is sealed */ #define ACPI_FADT_HEADLESS (1<<12) /* 12: [V3] No local video capabilities or local input devices */ #define ACPI_FADT_SLEEP_TYPE (1<<13) /* 13: [V3] Must execute native instruction after writing SLP_TYPx register */ #define ACPI_FADT_PCI_EXPRESS_WAKE (1<<14) /* 14: [V4] System supports PCIEXP_WAKE (STS/EN) bits (ACPI 3.0) */ #define ACPI_FADT_PLATFORM_CLOCK (1<<15) /* 15: [V4] OSPM should use platform-provided timer (ACPI 3.0) */ #define ACPI_FADT_S4_RTC_VALID (1<<16) /* 16: [V4] Contents of RTC_STS valid after S4 wake (ACPI 3.0) */ #define ACPI_FADT_REMOTE_POWER_ON (1<<17) /* 17: [V4] System is compatible with remote power on (ACPI 3.0) */ #define ACPI_FADT_APIC_CLUSTER (1<<18) /* 18: [V4] All local APICs must use cluster model (ACPI 3.0) */ #define ACPI_FADT_APIC_PHYSICAL (1<<19) /* 19: [V4] All local xAPICs must use physical dest mode (ACPI 3.0) */ #define ACPI_FADT_HW_REDUCED (1<<20) /* 20: [V5] ACPI hardware is not implemented (ACPI 5.0) */ #define ACPI_FADT_LOW_POWER_S0 (1<<21) /* 21: [V5] S0 power savings are equal or better than S3 (ACPI 5.0) */ /* Values for PreferredProfile (Preferred Power Management Profiles) */ enum AcpiPreferredPmProfiles { PM_UNSPECIFIED = 0, PM_DESKTOP = 1, PM_MOBILE = 2, PM_WORKSTATION = 3, PM_ENTERPRISE_SERVER = 4, PM_SOHO_SERVER = 5, PM_APPLIANCE_PC = 6, PM_PERFORMANCE_SERVER = 7, PM_TABLET = 8 }; /* Values for SleepStatus and SleepControl registers (V5+ FADT) */ #define ACPI_X_WAKE_STATUS 0x80 #define ACPI_X_SLEEP_TYPE_MASK 0x1C #define ACPI_X_SLEEP_TYPE_POSITION 0x02 #define ACPI_X_SLEEP_ENABLE 0x20 /* Reset to default packing */ #pragma pack() /* * Internal table-related structures */ typedef union acpi_name_union { UINT32 Integer; char Ascii[4]; } ACPI_NAME_UNION; /* Internal ACPI Table Descriptor. One per ACPI table. */ typedef struct acpi_table_desc { ACPI_PHYSICAL_ADDRESS Address; ACPI_TABLE_HEADER *Pointer; UINT32 Length; /* Length fixed at 32 bits (fixed in table header) */ ACPI_NAME_UNION Signature; ACPI_OWNER_ID OwnerId; UINT8 Flags; UINT16 ValidationCount; } ACPI_TABLE_DESC; /* * Maximum value of the ValidationCount field in ACPI_TABLE_DESC. * When reached, ValidationCount cannot be changed any more and the table will * be permanently regarded as validated. * * This is to prevent situations in which unbalanced table get/put operations * may cause premature table unmapping in the OS to happen. * * The maximum validation count can be defined to any value, but should be * greater than the maximum number of OS early stage mapping slots to avoid * leaking early stage table mappings to the late stage. */ #define ACPI_MAX_TABLE_VALIDATIONS ACPI_UINT16_MAX /* Masks for Flags field above */ #define ACPI_TABLE_ORIGIN_EXTERNAL_VIRTUAL (0) /* Virtual address, external maintained */ #define ACPI_TABLE_ORIGIN_INTERNAL_PHYSICAL (1) /* Physical address, internally mapped */ #define ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL (2) /* Virtual address, internallly allocated */ #define ACPI_TABLE_ORIGIN_MASK (3) #define ACPI_TABLE_IS_VERIFIED (4) #define ACPI_TABLE_IS_LOADED (8) /* * Get the remaining ACPI tables */ #include "actbl1.h" #include "actbl2.h" #include "actbl3.h" /* Macros used to generate offsets to specific table fields */ #define ACPI_FADT_OFFSET(f) (UINT16) ACPI_OFFSET (ACPI_TABLE_FADT, f) /* * Sizes of the various flavors of FADT. We need to look closely * at the FADT length because the version number essentially tells * us nothing because of many BIOS bugs where the version does not * match the expected length. In other words, the length of the * FADT is the bottom line as to what the version really is. * * For reference, the values below are as follows: * FADT V1 size: 0x074 * FADT V2 size: 0x084 * FADT V3 size: 0x0F4 * FADT V4 size: 0x0F4 * FADT V5 size: 0x10C * FADT V6 size: 0x114 */ #define ACPI_FADT_V1_SIZE (UINT32) (ACPI_FADT_OFFSET (Flags) + 4) #define ACPI_FADT_V2_SIZE (UINT32) (ACPI_FADT_OFFSET (MinorRevision) + 1) #define ACPI_FADT_V3_SIZE (UINT32) (ACPI_FADT_OFFSET (SleepControl)) #define ACPI_FADT_V5_SIZE (UINT32) (ACPI_FADT_OFFSET (HypervisorId)) #define ACPI_FADT_V6_SIZE (UINT32) (sizeof (ACPI_TABLE_FADT)) #define ACPI_FADT_CONFORMANCE "ACPI 6.1 (FADT version 6)" #endif /* __ACTBL_H__ */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/system_mmap.h> #include <tilck/kernel/vdso.h> #include <tilck/kernel/cmdline.h> #include "paging_generic_x86.h" u32 *pageframes_refcount; ulong phys_mem_lim; struct kmalloc_heap *hi_vmem_heap; void retain_pageframes_mapped_at(pdir_t *pdir, void *vaddrp, size_t len) { ASSERT(IS_PAGE_ALIGNED(vaddrp)); ASSERT(IS_PAGE_ALIGNED(len)); ulong paddr; ulong vaddr = (ulong)vaddrp; const ulong vaddr_end = vaddr + len; for (; vaddr < vaddr_end; vaddr += PAGE_SIZE) { if (get_mapping2(pdir, (void *)vaddr, &paddr) < 0) continue; /* not mapped, that's fine */ __pf_ref_count_inc(paddr); } } void release_pageframes_mapped_at(pdir_t *pdir, void *vaddrp, size_t len) { ASSERT(IS_PAGE_ALIGNED(vaddrp)); ASSERT(IS_PAGE_ALIGNED(len)); ulong paddr; ulong vaddr = (ulong)vaddrp; const ulong vaddr_end = vaddr + len; for (; vaddr < vaddr_end; vaddr += PAGE_SIZE) { if (get_mapping2(pdir, (void *)vaddr, &paddr) < 0) continue; /* not mapped, that's fine */ __pf_ref_count_dec(paddr); } } void invalidate_page(ulong vaddr) { invalidate_page_hw(vaddr); } void init_paging(void) { int rc; void *user_vdso_vaddr; size_t pagesframes_refcount_bufsize; phys_mem_lim = (ulong)MIN(get_phys_mem_size(), (u64)LINEAR_MAPPING_SIZE); /* * Allocate the buffer used for keeping a ref-count for each pageframe. * This is necessary for COW. */ pagesframes_refcount_bufsize = (phys_mem_lim >> PAGE_SHIFT) * sizeof(pageframes_refcount[0]); pageframes_refcount = kzmalloc(pagesframes_refcount_bufsize); if (!pageframes_refcount) { if (in_panic()) return; /* We're in panic: silently ignore the failure */ panic("Unable to allocate pageframes_refcount"); } pf_ref_count_inc(KERNEL_VA_TO_PA(zero_page)); /* Initialize the kmalloc heap used for the "hi virtual mem" area */ init_hi_vmem_heap(); /* * Now use the just-created hi vmem heap to reserve a page for the user * vdso-like page and expect it to be == USER_VDSO_VADDR. */ user_vdso_vaddr = hi_vmem_reserve(PAGE_SIZE); if (user_vdso_vaddr != (void *)USER_VDSO_VADDR) panic("user_vdso_vaddr != USER_VDSO_VADDR"); /* * Map a special vdso-like page used for the sysenter interface. * This is the only user-mapped page with a vaddr in the kernel space. */ rc = map_page(get_kernel_pdir(), user_vdso_vaddr, KERNEL_VA_TO_PA(&vdso_begin), PAGING_FL_US); if (rc < 0) panic("Unable to map the vdso-like page"); } void * map_framebuffer(pdir_t *pdir, ulong paddr, ulong vaddr, ulong size, bool user_mmap) { if (!get_kernel_pdir()) return failsafe_map_framebuffer(paddr, size); if (!pageframes_refcount) return failsafe_map_framebuffer(paddr, size); size_t count; const size_t page_count = pow2_round_up_at(size, PAGE_SIZE) / PAGE_SIZE; const u32 pg_flags = PAGING_FL_RW | PAGING_FL_SHARED | (user_mmap ? PAGING_FL_US : 0); if (!vaddr) { ASSERT(!user_mmap); /* user mappings always have a vaddr at this layer */ vaddr = (ulong) hi_vmem_reserve(size); if (!vaddr) { /* * This should NEVER happen. The allocation of the hi vmem does not * depend at all from the system. It's all on Tilck. We have 128 MB * of virtual space that we can allocate as we want. Unless there's * a bug in kmalloc(), we'll never get here. */ if (in_panic()) { /* * But, in the extremely unlucky case we end up here, there's still * one thing we can do, at least to be able to show something on * the screen: use a failsafe VADDR for the framebuffer. */ vaddr = FAILSAFE_FB_VADDR; } else { panic("Unable to reserve hi vmem for the framebuffer"); } } } count = map_pages(pdir, (void *)vaddr, paddr, page_count, pg_flags); if (count < page_count) { if (user_mmap) { /* This is bad, but not terrible */ printk("WARNING: unable to mmap framebuffer at %p\n", (void *)vaddr); unmap_pages_permissive(pdir, (void *)vaddr, count, false); return NULL; } /* * What if this is the only framebuffer available for showing something * on the screen? Well, we're screwed. But this should *never* happen. */ panic("Unable to map the framebuffer in the virtual space"); } if (kopt_fb_no_wc) { printk("paging: skip marking framebuffer pages as WC (kopt_fb_no_wc)\n"); return (void *)vaddr; } if (x86_cpu_features.edx1.pat) { size = pow2_round_up_at(size, PAGE_SIZE); set_pages_pat_wc(pdir, (void *) vaddr, size); return (void *)vaddr; } if (!x86_cpu_features.edx1.mtrr || user_mmap) return (void *)vaddr; /* * PAT is not available: we have to use MTRRs in order to make the paddr * region be of type WC (write-combining). */ int selected_mtrr = get_free_mtrr(); ulong pow2size = roundup_next_power_of_2(size); if (selected_mtrr < 0) { /* * Show the error, but still don't fail because the framebuffer can work * even without setting its memory region to be WC. */ printk("ERROR: No MTRR available for framebuffer"); return (void *)vaddr; } if (pow2_round_up_at(paddr, pow2size) != paddr) { /* As above, show the error, but DO NOT fail */ printk("ERROR: paddr (%p) not aligned at power-of-two", TO_PTR(paddr)); return (void *)vaddr; } set_mtrr((u32)selected_mtrr, paddr, pow2size, MEM_TYPE_WC); return (void *)vaddr; } bool hi_vmem_avail(void) { return hi_vmem_heap != NULL; } void *hi_vmem_reserve(size_t size) { void *res = NULL; disable_preemption(); { if (LIKELY(hi_vmem_heap != NULL)) res = per_heap_kmalloc(hi_vmem_heap, &size, 0); } enable_preemption(); return res; } void hi_vmem_release(void *ptr, size_t size) { disable_preemption(); { per_heap_kfree(hi_vmem_heap, ptr, &size, 0); } enable_preemption(); } int virtual_read(pdir_t *pdir, void *extern_va, void *dest, size_t len) { int rc; disable_preemption(); { rc = virtual_read_unsafe(pdir, extern_va, dest, len); } enable_preemption(); return rc; } int virtual_write(pdir_t *pdir, void *extern_va, void *src, size_t len) { int rc; disable_preemption(); { rc = virtual_write_unsafe(pdir, extern_va, src, len); } enable_preemption(); return rc; } NODISCARD size_t map_zero_pages(pdir_t *pdir, void *vaddrp, size_t page_count, u32 pg_flags) { size_t n; ulong vaddr = (ulong) vaddrp; for (n = 0; n < page_count; n++, vaddr += PAGE_SIZE) { if (map_zero_page(pdir, (void *)vaddr, pg_flags) != 0) break; } return n; } void handle_page_fault(regs_t *r) { if (in_panic()) { printk("Page fault while already in panic state.\n"); while (true) { halt(); } } ASSERT(!is_preemption_enabled()); handle_page_fault_int(r); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/process.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/timer.h> static struct ksem test_sem; enum sem_test_state { NOT_STARTED, BLOCKED, DONE, }; struct sem_test_data { int units; ATOMIC(enum sem_test_state) state; int tid; }; static struct sem_test_data sem_test_waiters[] = { { 1, NOT_STARTED, -1 }, { 3, NOT_STARTED, -1 }, { 5, NOT_STARTED, -1 }, { 10, NOT_STARTED, -1 }, }; static void ksem_test_wait_thread(void *arg) { struct sem_test_data *ctx = arg; int rc; printk("ksem wait thread %d, wait: %d\n", get_curr_tid(), ctx->units); ctx->state = BLOCKED; rc = ksem_wait(&test_sem, ctx->units, KSEM_WAIT_FOREVER); if (rc != 0) { panic("ksem_wait() failed with: %d\n", rc); } printk("wait(%d) done, rem_counter: %d\n", ctx->units, test_sem.counter); ctx->state = DONE; } static void wait_for_all_blocked(void) { while (true) { bool all_blocked = true; for (u32 i = 0; i < ARRAY_SIZE(sem_test_waiters); i++) { if (sem_test_waiters[i].state != BLOCKED) { all_blocked = false; break; } } if (all_blocked) break; kernel_yield(); } } static void ksem_test_check_sem_counter(int expected) { disable_preemption(); if (test_sem.counter == expected) goto out; printk("FAIL: counter: %d != expected: %d\n", test_sem.counter, expected); for (u32 i = 0; i < ARRAY_SIZE(sem_test_waiters); i++) { struct task *task = get_task(sem_test_waiters[i].tid); printk("waiter[%u, tid: %d]: units: %d, state: %d, task state: %s\n", i, sem_test_waiters[i].tid, sem_test_waiters[i].units, sem_test_waiters[i].state, task ? task_state_str[task->state] : "N/A"); } panic("ksem test failure"); out: enable_preemption(); } void selftest_ksem() { int tid, rc; ksem_init(&test_sem, 0, 1000); printk("Running the wait threads...\n"); disable_preemption(); { for (u32 i = 0; i < ARRAY_SIZE(sem_test_waiters); i++) { tid = kthread_create(ksem_test_wait_thread, 0, &sem_test_waiters[i]); VERIFY(tid > 0); sem_test_waiters[i].tid = tid; } } printk("Waiting for them to block...\n"); enable_preemption(); wait_for_all_blocked(); VERIFY(sem_test_waiters[0].state == BLOCKED); VERIFY(sem_test_waiters[1].state == BLOCKED); VERIFY(sem_test_waiters[2].state == BLOCKED); VERIFY(sem_test_waiters[3].state == BLOCKED); ksem_test_check_sem_counter(0); printk("signal(2)\n"); rc = ksem_signal(&test_sem, 2); VERIFY(rc == 0); yield_until_last(); ksem_test_check_sem_counter(1); VERIFY(sem_test_waiters[0].state == DONE); VERIFY(sem_test_waiters[1].state == BLOCKED); VERIFY(sem_test_waiters[2].state == BLOCKED); VERIFY(sem_test_waiters[3].state == BLOCKED); printk("signal(9)\n"); rc = ksem_signal(&test_sem, 9); VERIFY(rc == 0); yield_until_last(); ksem_test_check_sem_counter(2); VERIFY(sem_test_waiters[0].state == DONE); VERIFY(sem_test_waiters[1].state == DONE); VERIFY(sem_test_waiters[2].state == DONE); VERIFY(sem_test_waiters[3].state == BLOCKED); printk("signal(5)\n"); rc = ksem_signal(&test_sem, 5); VERIFY(rc == 0); yield_until_last(); ksem_test_check_sem_counter(2+5); VERIFY(sem_test_waiters[0].state == DONE); VERIFY(sem_test_waiters[1].state == DONE); VERIFY(sem_test_waiters[2].state == DONE); VERIFY(sem_test_waiters[3].state == BLOCKED); printk("signal(3)\n"); rc = ksem_signal(&test_sem, 3); VERIFY(rc == 0); yield_until_last(); ksem_test_check_sem_counter(0); VERIFY(sem_test_waiters[0].state == DONE); VERIFY(sem_test_waiters[1].state == DONE); VERIFY(sem_test_waiters[2].state == DONE); VERIFY(sem_test_waiters[3].state == DONE); printk("Done\n"); ksem_destroy(&test_sem); if (se_is_stop_requested()) se_interrupted_end(); else se_regular_end(); } REGISTER_SELF_TEST(ksem, se_short, &selftest_ksem) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) #define PAGE_SHIFT 12u #if !defined(PAGE_SIZE) || (defined(PAGE_SIZE) && PAGE_SIZE == 4096) #undef PAGE_SIZE #define PAGE_SIZE 4096u #else #error PAGE_SIZE already defined with different value #endif #else #error Unsupported architecture. #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void register_double_fault_tss_entry(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once enum subsystem { SUBSYS_INVALID = 0, SUBSYS_VFS = 1, SUBSYS_PROCMGNT = 2, }; <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/assert.h> #include <tilck/common/string_util.h> #include <tilck/common/fat32_base.h> /* * The following code uses in many cases the CamelCase naming convention * because it is based on the Microsoft's public document: * * Microsoft Extensible Firmware Initiative * FAT32 File System Specification * * FAT: General Overview of On-Disk Format * * Version 1.03, December 6, 2000 * * Keeping the exact same names as the official document, helps a lot. */ #define FAT_ENTRY_LAST ((char)0) #define FAT_ENTRY_AVAILABLE ((char)0xE5) static u8 shortname_checksum(u8 *shortname) { u8 sum = 0; for (int i = 0; i < 11; i++) { // NOTE: The operation is an unsigned char rotate right sum = (u8)( ((sum & 1u) ? 0x80u : 0u) + (sum >> 1u) + *shortname++ ); } return sum; } static const bool fat32_valid_chars[256] = { [0 ... 32] = 0, [33] = 0, /* ! */ [34] = 0, /* " */ [35] = 1, /* # */ [36] = 1, /* $ */ [37] = 1, /* % */ [38] = 1, /* & */ [39] = 1, /* ' */ [40] = 1, /* ( */ [41] = 1, /* ) */ [42] = 0, /* * */ [43] = 1, /* + */ [44] = 1, /* , */ [45] = 1, /* - */ [46] = 1, /* . */ [47] = 0, /* / */ [48] = 1, /* 0 */ [49] = 1, /* 1 */ [50] = 1, /* 2 */ [51] = 1, /* 3 */ [52] = 1, /* 4 */ [53] = 1, /* 5 */ [54] = 1, /* 6 */ [55] = 1, /* 7 */ [56] = 1, /* 8 */ [57] = 1, /* 9 */ [58] = 0, /* : */ [59] = 1, /* ; */ [60] = 0, /* < */ [61] = 1, /* = */ [62] = 0, /* > */ [63] = 0, /* ? */ [64] = 1, /* @ */ [65] = 1, /* A */ [66] = 1, /* B */ [67] = 1, /* C */ [68] = 1, /* D */ [69] = 1, /* E */ [70] = 1, /* F */ [71] = 1, /* G */ [72] = 1, /* H */ [73] = 1, /* I */ [74] = 1, /* J */ [75] = 1, /* K */ [76] = 1, /* L */ [77] = 1, /* M */ [78] = 1, /* N */ [79] = 1, /* O */ [80] = 1, /* P */ [81] = 1, /* Q */ [82] = 1, /* R */ [83] = 1, /* S */ [84] = 1, /* T */ [85] = 1, /* U */ [86] = 1, /* V */ [87] = 1, /* W */ [88] = 1, /* X */ [89] = 1, /* Y */ [90] = 1, /* Z */ [91] = 1, /* [ */ [92] = 0, /* \ */ [93] = 1, /* ] */ [94] = 1, /* ^ */ [95] = 1, /* _ */ [96] = 1, /* ` */ [97] = 1, /* a */ [98] = 1, /* b */ [99] = 1, /* c */ [100] = 1, /* d */ [101] = 1, /* e */ [102] = 1, /* f */ [103] = 1, /* g */ [104] = 1, /* h */ [105] = 1, /* i */ [106] = 1, /* j */ [107] = 1, /* k */ [108] = 1, /* l */ [109] = 1, /* m */ [110] = 1, /* n */ [111] = 1, /* o */ [112] = 1, /* p */ [113] = 1, /* q */ [114] = 1, /* r */ [115] = 1, /* s */ [116] = 1, /* t */ [117] = 1, /* u */ [118] = 1, /* v */ [119] = 1, /* w */ [120] = 1, /* x */ [121] = 1, /* y */ [122] = 1, /* z */ [123] = 1, /* { */ [124] = 0, /* | */ [125] = 1, /* } */ [126] = 1, /* ~ */ [127 ... 255] = 0, }; bool fat32_is_valid_filename_character(char c) { return fat32_valid_chars[(u8)c]; } /* * WARNING: this implementation supports only the ASCII subset of UTF16. */ static void fat_handle_long_dir_entry(struct fat_walk_long_name_ctx *ctx, struct fat_long_entry *le) { char entrybuf[13] = {0}; int ebuf_size=0; if (ctx->lname_chksum != le->LDIR_Chksum) { bzero(ctx->lname_buf, sizeof(ctx->lname_chksum)); ctx->lname_sz = 0; ctx->lname_chksum = le->LDIR_Chksum; ctx->is_valid = true; } if (!ctx->is_valid) return; for (int i = 0; i < 10; i += 2) { u8 c = le->LDIR_Name1[i]; /* NON-ASCII characters are NOT supported */ if (le->LDIR_Name1[i+1] != 0) { ctx->is_valid = false; return; } if (c == 0 || c == 0xFF) goto end; entrybuf[ebuf_size++] = (char)c; } for (int i = 0; i < 12; i += 2) { u8 c = le->LDIR_Name2[i]; /* NON-ASCII characters are NOT supported */ if (le->LDIR_Name2[i+1] != 0) { ctx->is_valid = false; return; } if (c == 0 || c == 0xFF) goto end; entrybuf[ebuf_size++] = (char)c; } for (int i = 0; i < 4; i += 2) { u8 c = le->LDIR_Name3[i]; /* NON-ASCII characters are NOT supported */ if (le->LDIR_Name3[i+1] != 0) { ctx->is_valid = false; return; } if (c == 0 || c == 0xFF) goto end; entrybuf[ebuf_size++] = (char)c; } end: for (int i = ebuf_size-1; i >= 0; i--) { char c = entrybuf[i]; if (!fat32_is_valid_filename_character(c)) { ctx->is_valid = false; break; } ctx->lname_buf[ctx->lname_sz++] = (u8) c; } } static const char * finalize_long_name(struct fat_walk_long_name_ctx *ctx, struct fat_entry *e) { const s16 e_checksum = shortname_checksum((u8 *)e->DIR_Name); if (ctx->lname_chksum == e_checksum) { ctx->lname_buf[ctx->lname_sz] = 0; str_reverse((char *)ctx->lname_buf, (size_t)ctx->lname_sz); return (const char *) ctx->lname_buf; } return NULL; } int fat_walk(struct fat_walk_static_params *p, u32 cluster) { struct fat_walk_long_name_ctx *const ctx = p->ctx; const u32 entries_per_cluster = fat_get_dir_entries_per_cluster(p->h); struct fat_entry *dentries = NULL; ASSERT(p->ft == fat16_type || p->ft == fat32_type); if (cluster == 0) dentries = fat_get_rootdir(p->h, p->ft, &cluster); if (ctx) { bzero(ctx->lname_buf, sizeof(ctx->lname_buf)); ctx->lname_sz = 0; ctx->lname_chksum = -1; ctx->is_valid = false; } while (true) { if (cluster != 0) { /* * if cluster != 0, cluster is used and entry is overriden. * That's because on FAT16 we know only the sector of the root dir. * In that case, fat_get_rootdir() returns 0 as cluster. In all the * other cases, we need only the cluster. */ dentries = fat_get_pointer_to_cluster_data(p->h, cluster); } ASSERT(dentries != NULL); for (u32 i = 0; i < entries_per_cluster; i++) { if (ctx && is_long_name_entry(&dentries[i])) { fat_handle_long_dir_entry(ctx, (void *)&dentries[i]); continue; } // the first "file" is the volume ID. Skip it. if (dentries[i].volume_id) continue; // the entry was used, but now is free if (dentries[i].DIR_Name[0] == FAT_ENTRY_AVAILABLE) continue; // that means all the rest of the entries are free. if (dentries[i].DIR_Name[0] == FAT_ENTRY_LAST) return 0; const char *long_name_ptr = NULL; if (ctx && ctx->lname_sz > 0 && ctx->is_valid) long_name_ptr = finalize_long_name(ctx, &dentries[i]); int ret = p->cb(p->h, p->ft, dentries + i, long_name_ptr, p->arg); if (ctx) { ctx->lname_sz = 0; ctx->lname_chksum = -1; } if (ret) { /* the callback returns a value != 0 to request a walk STOP. */ return 0; } } /* * In case fat_walk has been called on the root dir on a FAT16, * cluster is 0 (invalid) and there is no next cluster in the chain. This * fact seriously limits the number of items in the root dir of a FAT16 * volume. */ if (cluster == 0) break; /* * If we're here, it means that there is more then one cluster for the * entries of this directory. We have to follow the chain. */ u32 val = fat_read_fat_entry(p->h, p->ft, 0, cluster); if (fat_is_end_of_clusterchain(p->ft, val)) break; // that's it: we hit an exactly full cluster. /* We do not handle BAD CLUSTERS */ ASSERT(!fat_is_bad_cluster(p->ft, val)); cluster = val; } return 0; } u32 fat_get_cluster_count(struct fat_hdr *hdr) { const u32 FATSz = fat_get_FATSz(hdr); const u32 TotSec = fat_get_TotSec(hdr); const u32 RootDirSectors = fat_get_root_dir_sectors(hdr); const u32 FatAreaSize = hdr->BPB_NumFATs * FATSz; const u32 DataSec = TotSec-(hdr->BPB_RsvdSecCnt+FatAreaSize+RootDirSectors); return DataSec / hdr->BPB_SecPerClus; } enum fat_type fat_get_type(struct fat_hdr *hdr) { const u32 CountofClusters = fat_get_cluster_count(hdr); if (CountofClusters < 4085) { /* Volume is FAT12 */ return fat12_type; } else if (CountofClusters < 65525) { /* Volume is FAT16 */ return fat16_type; } else { /* Volume is FAT32 */ return fat32_type; } } static void * fat_get_entry_ptr(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clu) { STATIC_ASSERT(fat16_type == 2); STATIC_ASSERT(fat32_type == 4); ASSERT(ft == fat16_type || ft == fat32_type); ASSERT(fatN < h->BPB_NumFATs); const u32 FATSz = fat_get_FATSz(h); const u32 FATOffset = clu * ft; const u32 ThisFATSecNum = fatN * FATSz + h->BPB_RsvdSecCnt + (FATOffset / h->BPB_BytsPerSec); const u32 ThisFATEntOffset = FATOffset % h->BPB_BytsPerSec; u8 *const SecBuf = (u8*)h + ThisFATSecNum * h->BPB_BytsPerSec; return SecBuf + ThisFATEntOffset; } /* * Reads the entry in the FAT 'fatN' for cluster 'clusterN'. * The entry may be 16 or 32 bit. It returns 32-bit integer for convenience. */ u32 fat_read_fat_entry(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clusterN) { void *ptr; ASSERT(ft == fat16_type || ft == fat32_type); ptr = fat_get_entry_ptr(h, ft, fatN, clusterN); return ft == fat16_type ? *(u16 *)ptr : (*(u32 *)ptr) & 0x0FFFFFFF; } void fat_write_fat_entry(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clusterN, u32 value) { void *ptr; ASSERT(ft == fat16_type || ft == fat32_type); ptr = fat_get_entry_ptr(h, ft, fatN, clusterN); if (ft == fat16_type) { ASSERT((value & 0xFFFF0000U) == 0); /* the top 16 bits cannot be used */ *(u16 *)ptr = (u16)value; } else { ASSERT((value & 0xF0000000U) == 0); /* the top 4 bits cannot be used */ u32 oldval = *(u32 *)ptr & 0xF0000000U; *(u32 *)ptr = oldval | value; } } u32 fat_get_first_data_sector(struct fat_hdr *hdr) { u32 RootDirSectors = fat_get_root_dir_sectors(hdr); u32 FATSz; if (hdr->BPB_FATSz16 != 0) { FATSz = hdr->BPB_FATSz16; } else { struct fat32_header2 *h32 = (struct fat32_header2*) (hdr+1); FATSz = h32->BPB_FATSz32; } u32 FirstDataSector = hdr->BPB_RsvdSecCnt + (hdr->BPB_NumFATs * FATSz) + RootDirSectors; return FirstDataSector; } u32 fat_get_sector_for_cluster(struct fat_hdr *hdr, u32 N) { u32 FirstDataSector = fat_get_first_data_sector(hdr); // FirstSectorofCluster return ((N - 2) * hdr->BPB_SecPerClus) + FirstDataSector; } struct fat_entry * fat_get_rootdir(struct fat_hdr *hdr, enum fat_type ft, u32 *cluster /* out */) { ASSERT(ft == fat16_type || ft == fat32_type); u32 sector; if (ft == fat16_type) { u32 FirstDataSector = (u32)hdr->BPB_RsvdSecCnt + (u32)(hdr->BPB_NumFATs * hdr->BPB_FATSz16); sector = FirstDataSector; *cluster = 0; /* On FAT16 the root dir entry is NOT a cluster chain! */ } else { /* FAT32 case */ struct fat32_header2 *h32 = (struct fat32_header2 *) (hdr + 1); *cluster = h32->BPB_RootClus; sector = fat_get_sector_for_cluster(hdr, *cluster); } return (struct fat_entry*) ((u8*)hdr + (hdr->BPB_BytsPerSec * sector)); } void fat_get_short_name(struct fat_entry *entry, char *destbuf) { u32 i = 0; u32 d = 0; for (i = 0; i < 8 && entry->DIR_Name[i] != ' '; i++) { char c = entry->DIR_Name[i]; destbuf[d++] = (entry->DIR_NTRes & FAT_ENTRY_NTRES_BASE_LOW_CASE) ? (char)tolower(c) : c; } i = 8; // beginning of the extension part. if (entry->DIR_Name[i] != ' ') { destbuf[d++] = '.'; for (; i < 11 && entry->DIR_Name[i] != ' '; i++) { char c = entry->DIR_Name[i]; destbuf[d++] = (entry->DIR_NTRes & FAT_ENTRY_NTRES_EXT_LOW_CASE) ? (char)tolower(c) : c; } } destbuf[d] = 0; } static bool fat_fetch_next_component(struct fat_search_ctx *ctx) { ASSERT(ctx->pcl == 0); /* * Fetch a path component from the abspath: we'll use it while iterating * the whole directory. On a match, we reset pcl and start a new walk on * the subdirectory. */ while (*ctx->path && *ctx->path != '/') { ctx->pc[ctx->pcl++] = *ctx->path++; } ctx->pc[ctx->pcl++] = 0; return ctx->pcl != 0; } int fat_search_entry_cb(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *entry, const char *long_name, void *arg) { struct fat_search_ctx *ctx = arg; if (ctx->pcl == 0) { if (!fat_fetch_next_component(ctx)) { // The path was empty, so no path component has been fetched. return -1; } } /* * NOTE: the following is NOT fully FAT32 compliant: for long names this * code compares file names using a CASE SENSITIVE comparison! * This HACK allows a UNIX system like Tilck to use FAT32 [case sensitivity * is a MUST in UNIX] by just forcing each file to have a long name, even * when that is not necessary. */ if (long_name) { if (strcmp(long_name, ctx->pc)) { // no match, continue. return 0; } // we have a long-name match (case sensitive) } else { /* * no long name: for short names, we do a compliant case INSENSITIVE * string comparison. */ fat_get_short_name(entry, ctx->shortname); if (stricmp(ctx->shortname, ctx->pc)) { // no match, continue. return 0; } // we have a short-name match (case insensitive) } // we've found a match. if (ctx->single_comp || *ctx->path == 0) { ctx->result = entry; // if the path ended, that's it. Just return. return -1; } /* * The next char in path MUST be a '/' since otherwise * fat_fetch_next_component() would have continued, until a '/' or a * '\0' is hit. */ ASSERT(*ctx->path == '/'); // path's next char is a '/': maybe there are more components in the path. ctx->path++; if (*ctx->path == 0) { /* * The path just ended with '/'. That's OK only if entry is acutally is * a directory. */ if (entry->directory) ctx->result = entry; else ctx->not_dir = true; return -1; } if (!entry->directory) return -1; // if the entry is not a directory, we failed. // The path did not end: we have to do a walk in the sub-dir. ctx->pcl = 0; ctx->subdir_cluster = fat_get_first_cluster(entry); return -1; } void fat_init_search_ctx(struct fat_search_ctx *ctx, const char *path, bool single_comp) { bzero(ctx, sizeof(struct fat_search_ctx)); #ifdef __clang_analyzer__ ctx->pcl = 0; /* SA: make it sure ctx.pcl is zeroed */ ctx->result = NULL; /* SA: make it sure ctx.result is zeroed */ #endif ctx->path = path; ctx->single_comp = single_comp; } struct fat_entry * fat_search_entry(struct fat_hdr *hdr, enum fat_type ft, const char *abspath, int *err) { struct fat_walk_static_params walk_params; struct fat_search_ctx ctx; if (ft == fat_unknown) ft = fat_get_type(hdr); ASSERT(*abspath == '/'); abspath++; if (!*abspath) { /* the whole abspath was just '/' */ u32 unused; return fat_get_rootdir(hdr, ft, &unused); } walk_params = (struct fat_walk_static_params) { .ctx = &ctx.walk_ctx, .h = hdr, .ft = ft, .cb = &fat_search_entry_cb, .arg = &ctx, }; fat_init_search_ctx(&ctx, abspath, false); fat_walk(&walk_params, 0); while (ctx.subdir_cluster) { const u32 cluster = ctx.subdir_cluster; ctx.subdir_cluster = 0; fat_walk(&walk_params, cluster); } if (err) { if (ctx.not_dir) *err = -20; /* -ENOTDIR */ else *err = !ctx.result ? -2 /* ENOENT */: 0; } return ctx.result; } size_t fat_get_file_size(struct fat_entry *entry) { return entry->DIR_FileSize; } size_t fat_read_whole_file(struct fat_hdr *hdr, struct fat_entry *entry, char *dest_buf, size_t dest_buf_size) { const enum fat_type ft = fat_get_type(hdr); const u32 cs = fat_get_cluster_size(hdr); const size_t fsize = entry->DIR_FileSize; u32 cluster = fat_get_first_cluster(entry); size_t tot_read = 0; do { char *data = fat_get_pointer_to_cluster_data(hdr, cluster); const size_t file_rem = fsize - tot_read; const size_t dest_buf_rem = dest_buf_size - tot_read; const size_t rem = MIN(file_rem, dest_buf_rem); if (rem <= cs) { // read what is needed memcpy(dest_buf + tot_read, data, rem); tot_read += rem; break; } // read the whole cluster memcpy(dest_buf + tot_read, data, cs); tot_read += cs; ASSERT((fsize - tot_read) > 0); // find the next cluster u32 fatval = fat_read_fat_entry(hdr, ft, 0, cluster); if (fat_is_end_of_clusterchain(ft, fatval)) { // rem is still > 0, this should NOT be the last cluster. // Still, everything could happen. Just stop. break; } // we do not expect BAD CLUSTERS ASSERT(!fat_is_bad_cluster(ft, fatval)); cluster = fatval; // go reading the new cluster in the chain. } while (tot_read < fsize); return tot_read; } struct compact_ctx { struct fat_walk_static_params walk_params; u32 ffc; /* first free cluster */ }; static int fat_compact_walk_cb(struct fat_hdr *hdr, enum fat_type ft, struct fat_entry *e, const char *longname, void *arg) { const u32 first_clu = fat_get_first_cluster(e); const u32 clu_size = fat_get_cluster_size(hdr); u32 clu = first_clu, next_clu, last_clu = 0; struct compact_ctx *const ctx = arg; { char name[16]; fat_get_short_name(e, name); if (is_dot_or_dotdot(name, (int)strlen(name))) return 0; /* It makes no sense to visit '.' and '..' */ } do { next_clu = fat_read_fat_entry(hdr, ft, 0, clu); /* Move forward `ctx->ffc`, if necessary */ while (fat_read_fat_entry(hdr, ft, 0, ctx->ffc)) { ctx->ffc++; } if (clu > ctx->ffc) { void *src = fat_get_pointer_to_cluster_data(hdr, clu); void *dest = fat_get_pointer_to_cluster_data(hdr, ctx->ffc); memcpy(dest, src, clu_size); if (clu == first_clu) fat_set_first_cluster(e, ctx->ffc); else fat_write_fat_entry(hdr, ft, 0, last_clu, ctx->ffc); fat_write_fat_entry(hdr, ft, 0, ctx->ffc, next_clu); fat_write_fat_entry(hdr, ft, 0, clu, 0); clu = ctx->ffc++; } last_clu = clu; clu = next_clu; } while (!fat_is_end_of_clusterchain(ft, clu)); if (e->directory) { fat_walk(&ctx->walk_params, fat_get_first_cluster(e)); } return 0; } void fat_compact_clusters(struct fat_hdr *hdr) { const u32 count = fat_get_cluster_count(hdr); const enum fat_type ft = fat_get_type(hdr); struct compact_ctx cctx; for (cctx.ffc = 0; cctx.ffc < count; cctx.ffc++) { if (!fat_read_fat_entry(hdr, ft, 0, cctx.ffc)) break; } cctx.walk_params = (struct fat_walk_static_params) { .ctx = NULL, .h = hdr, .ft = ft, .cb = &fat_compact_walk_cb, .arg = &cctx, }; fat_walk(&cctx.walk_params, 0); } u32 fat_get_first_free_cluster_off(struct fat_hdr *hdr) { u32 clu, ff_sector; const u32 cluster_count = fat_get_cluster_count(hdr); const enum fat_type ft = fat_get_type(hdr); for (clu = 0; clu < cluster_count; clu++) { if (!fat_read_fat_entry(hdr, ft, 0, clu)) break; } ff_sector = fat_get_sector_for_cluster(hdr, clu); return (ff_sector + 1) * hdr->BPB_BytsPerSec; } u32 fat_calculate_used_bytes(struct fat_hdr *hdr) { const u32 cluster_count = fat_get_cluster_count(hdr); const enum fat_type ft = fat_get_type(hdr); u32 val, clu, ff_sector; for (clu = cluster_count; clu > 0; clu--) { val = fat_read_fat_entry(hdr, ft, 0, clu-1); if (val && !fat_is_bad_cluster(ft, val)) break; } if (!clu) return 0; /* fat partition completely corrupt */ ff_sector = fat_get_sector_for_cluster(hdr, clu); return (ff_sector + 1) * hdr->BPB_BytsPerSec; } bool fat_is_first_data_sector_aligned(struct fat_hdr *hdr, u32 page_size) { u32 fdc = fat_get_first_data_sector(hdr); u32 fdc_off = fdc * hdr->BPB_BytsPerSec; return (fdc_off % page_size) == 0; } /* * Aligns the first data sector to `page_size`, by moving all the data sectors * by a number of bytes between 0 and page_size-1. * * WARNING: this function assumes it is safe to write up to 1 page after the * value returned by fat_calculate_used_bytes(). */ void fat_align_first_data_sector(struct fat_hdr *hdr, u32 page_size) { const u32 used = fat_calculate_used_bytes(hdr); const u32 fdc = fat_get_first_data_sector(hdr); const u32 bps = hdr->BPB_BytsPerSec; const u32 fdc_off = fdc * bps; const u32 rem = page_size - (fdc_off % page_size); const u32 rem_sectors = rem / hdr->BPB_BytsPerSec; const u32 res_data = hdr->BPB_RsvdSecCnt * bps; char *const data = (char *)hdr + res_data; ASSERT((page_size % bps) == 0); ASSERT((rem % bps) == 0); if (!rem) return; /* already aligned, nothing to do */ /* Make sure fat_is_first_data_sector_aligned() returns false */ ASSERT(!fat_is_first_data_sector_aligned(hdr, page_size)); /* Move forward the data by `rem` bytes */ memmove(data + rem, data, used - res_data); /* Increase the number of reserved sectors by `rem_sectors` */ hdr->BPB_RsvdSecCnt += rem_sectors; /* Now, make sure fat_is_first_data_sector_aligned() returns true */ ASSERT(fat_is_first_data_sector_aligned(hdr, page_size)); /* Finally, zero the data now part of the reserved sectors */ bzero(data, rem); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/kernel/fs/flock.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/bintree.h> struct locked_file { REF_COUNTED_OBJECT; struct bintree_node node; enum subsystem owner; struct mnt_fs *fs; vfs_inode_ptr_t inode; }; int acquire_subsys_flock(struct mnt_fs *fs, vfs_inode_ptr_t i, enum subsystem subsys, struct locked_file **lock_ref) { struct locked_file *lf; int rc; disable_preemption(); { lf = bintree_find_ptr(fs->pss_lock_root, i, struct locked_file, node, inode); if (lf) { if (lf->owner == subsys) { *lock_ref = lf; /* the subsystem already owns the exlock */ retain_obj(lf); /* retain the locked_file object */ enable_preemption(); return 0; } enable_preemption(); return -ETXTBSY; /* the lock is owned by another subsystem */ } } enable_preemption(); /* There's no such lock object: let's try to grab the real lock */ rc = vfs_exlock_noblock(fs, i); if (rc < 0 && UNLIKELY(rc != -ENOLCK)) { /* * Too bad: something else holds the lock. * * NOTE: this means we're accepting accepting the case where the call * failed with -ENOLCK, meaning that no per-file locking mechanism has * been implemented at fs-level. That's fine: it just means that the FS * cannot be a network FS, with its own locking logic beyond the current * machine. In this case, only the per-subsystem locking offered by this * code will be available. */ return rc; } /* We've got it. Great! */ lf = kzalloc_obj(struct locked_file); if (UNLIKELY(!lf)) { /* Oops, out of memory! */ vfs_exunlock(fs, i); return -ENOMEM; } /* We're cool: setup the lock object and append it to the right list */ lf->owner = subsys; lf->fs = fs; lf->inode = i; retain_obj(lf); retain_obj(lf->fs); disable_preemption(); { bintree_insert_ptr(&fs->pss_lock_root, lf, struct locked_file, node, inode); } enable_preemption(); *lock_ref = lf; return 0; } void retain_subsys_flock(struct locked_file *lf) { retain_obj(lf); } void release_subsys_flock(struct locked_file *lf) { const int curr_ref_count = release_obj(lf); int rc; if (curr_ref_count > 0) return; /* that's it */ /* * We have to destroy the lock object, but first we have to release the * actual per-file lock. */ rc = vfs_exunlock(lf->fs, lf->inode); if (rc < 0 && UNLIKELY(rc != -ENOLCK)) { /* * Weird: something went wrong while trying to release the lock. * This MUST never happen, if the `lf` is a valid object, returned by * acquire_subsys_flock(), after acquiring the per-lock. * If we got here, there's a bug in filesystem's exlock/exunlock impl. * * NOTE: we're accepting accepting the case where the call failed with * -ENOLCK. See the comments in acquire_subsys_flock(). */ panic("Failed to release per-file lock with: %d", rc); } /* Now, remove the lock object from the list */ disable_preemption(); { bintree_remove_ptr(&lf->fs->pss_lock_root, lf, struct locked_file, node, inode); } enable_preemption(); /* Release `lf->fs` and destroy the `lf` object itself */ release_obj(lf->fs); kfree_obj(lf, struct locked_file); } int acquire_subsys_flock_h(fs_handle h, enum subsystem subsys, struct locked_file **lock_ref) { struct fs_handle_base *hb = h; struct mnt_fs *fs = hb->fs; vfs_inode_ptr_t i = fs->fsops->get_inode(hb); if (!i) return -EBADF; return acquire_subsys_flock(fs, i, subsys, lock_ref); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int sysfs_retain_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { ASSERT(inode != NULL); return retain_obj((struct sysfs_inode *)inode); } static int sysfs_release_inode(struct mnt_fs *fs, vfs_inode_ptr_t inode) { ASSERT(inode != NULL); return release_obj((struct sysfs_inode *)inode); } static void sysfs_exclusive_lock(struct mnt_fs *fs) { struct sysfs_data *d = fs->device_data; rwlock_wp_exlock(&d->rwlock); } static void sysfs_exclusive_unlock(struct mnt_fs *fs) { struct sysfs_data *d = fs->device_data; rwlock_wp_exunlock(&d->rwlock); } static void sysfs_shared_lock(struct mnt_fs *fs) { struct sysfs_data *d = fs->device_data; rwlock_wp_shlock(&d->rwlock); } static void sysfs_shared_unlock(struct mnt_fs *fs) { struct sysfs_data *d = fs->device_data; rwlock_wp_shunlock(&d->rwlock); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> bool experiment_bar(void) { return true; } int experiment_foo(int n) { if (!experiment_bar()) return -1; return n * 10; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/mod_serial.h> #include <tilck/common/basic_defs.h> void init_serial_port(u16 port); bool serial_read_ready(u16 port); void serial_wait_for_read(u16 port); char serial_read(u16 port); bool serial_write_ready(u16 port); void serial_wait_for_write(u16 port); void serial_write(u16 port, char c); #if MOD_serial void early_init_serial_ports(void); #else static inline void early_init_serial_ports(void) { } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> extern "C" { void initialize_test_kernel_heap(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck_gen_headers/config_global.h> #include <tilck/common/arch/generic_x86/asm_consts.h> #if KERNEL_STACK_PAGES == 1 #define ASM_KERNEL_STACK_SZ 4096 #elif KERNEL_STACK_PAGES == 2 #define ASM_KERNEL_STACK_SZ 8192 #elif KERNEL_STACK_PAGES == 4 #define ASM_KERNEL_STACK_SZ 16384 #else #error Unsupported value of KERNEL_STACK_PAGES #endif #define TI_F_RESUME_RS_OFF 20 /* offset of: fault_resume_regs */ #define TI_FAULTS_MASK_OFF 24 /* offset of: faults_resume_mask */ #define SIZEOF_REGS 84 #define REGS_EIP_OFF 64 #define REGS_USERESP_OFF 76 #define REGS_FL_SYSENTER 1 #define REGS_FL_FPU_ENABLED 8 #define X86_KERNEL_CODE_SEL 0x08 #define X86_KERNEL_DATA_SEL 0x10 #define X86_USER_CODE_SEL 0x1b #define X86_USER_DATA_SEL 0x23 /* Some useful asm macros */ #ifdef ASM_FILE #define NBITS 32 #define FUNC(x) .type x, @function; x #define END_FUNC(x) .size x, .-(x) #define EBP_OFFSET_ARG1 8 #define EBP_OFFSET_ARG2 12 #define EBP_OFFSET_ARG3 16 .macro asm_disable_cr0_ts mov eax, CR0 and eax, ~8 mov CR0, eax .endm .macro push_custom_flags additional_flags mov eax, CR0 and eax, 8 // CR0_TS xor eax, 8 // flip the bit: // we use FPU_ENABLED while TS=1 means FPU disabled or eax, \additional_flags push eax // custom_flags asm_disable_cr0_ts .endm .macro pop_custom_flags pop eax // custom_flags and eax, 8 // REGS_FL_FPU_ENABLED xor eax, 8 // flip the bit mov ebx, CR0 and ebx, ~8 or ebx, eax mov CR0, ebx .endm .macro skip_push_custom_flags push 0 .endm .macro skip_pop_custom_flags add esp, 4 .endm .macro save_base_regs pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax # Note: the value of the pushed ESP is the one before # the pusha instruction. push ds push es push fs push gs .endm .macro resume_base_regs pop gs pop fs pop es pop ds popa .endm .macro kernel_entry_common save_base_regs mov ax, X86_KERNEL_DATA_SEL mov ds, ax mov es, ax mov fs, ax mov gs, ax .endm .macro kernel_exit_common resume_base_regs add esp, 8 // Discards the pushed err_code and int_num iret .endm #endif <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause TCC_VER="15e9b7384e709120" function download_tcc { local url="git://repo.or.cz/tinycc.git" local ver="$TCC_VER" local tarname="tcc-$ver.tgz" download_git_repo_in_cache "$url" $ver $tarname tcc extract_cachefile_tar_gz $tarname -- } if [[ $HOST_ARCH == "i386" ]] || [[ $HOST_ARCH == "x86_64" ]]; then all_funcs_list+=(build_tcc) fi function build_tcc { if [[ $HOST_ARCH != "i386" ]] && [[ $HOST_ARCH != "x86_64" ]]; then echo "ERROR: HOST_ARCH=$HOST_ARCH not supported" return fi if [ ! -d $ARCH/tcc ]; then reset_cc_vars if [[ "$HOST_ARCH" == "$BUILD_ARCH" ]]; then install_32bit_libs fi # Download the gcc toolchain even in the case HOST != BUILD_ARCH # because we'll need its sysroot to be deployed in Tilck's image. DOWNLOAD_IGNORING_SYSCC="1" download_gcc_toolchain DOWNLOAD_IGNORING_SYSCC="" fi pushd $ARCH if [ ! -d tcc ]; then show_work_on_component_msg "TCC" download_tcc cd tcc # Variables for making the compiler to work on Tilck # Note: these vars are used by --crtprefix and --libpaths # and do not affect the compiler in case just -c is used to # compile a single C file, without linking. local p="/" local lib="/lib/$ARCH_GCC_TC-tilck-musl" # To test it on the Linux build machine # local tc=$TC/host_${HOST_ARCH}/${GCC_NAME_PFX}_musl # local p="$tc/$ARCH/tcc/install" # local lib=$tc/$ARCH_GCC_TC-buildroot-linux-musl/sysroot/lib local ldflags="-Wl,--oformat=$ARCH_ELF_NAME -static" if [[ "$HOST_ARCH" == "$ARCH" ]]; then export SYS_CC="$CC" export SYS_CXX="$CXX" export CC_POST_FLAGS="-specs $MUSL_INSTALL/lib/musl-gcc.specs" # Hack: unfortunately, while tcc's build system uses the # just-built tcc in order to build libtcc1.a and, one of its files # (bcheck.c) needs to include standard headers, which most of them # like stdlib.h get found because of fall-back logic in the compiler, # but the specific ones in sys, bits and gnu don't (they are included # indirectly by standard headers). Therefore, the `tcc` compiler # fall-backs to the path specified by -B.. (pointing to the project's # root directory). So, one dirty hack to workaround this problem is # just to symlink the missing dirs in the local directory. This avoids # touching tcc's build system's code. ln -s /usr/include/$ARCH-linux-gnu/sys include/ ln -s /usr/include/$ARCH-linux-gnu/bits include/ ln -s /usr/include/$ARCH-linux-gnu/gnu include/ else # Default case set_cc_vars_to_tc fi # Hack: unfortunately, the TCC build wants to build, with the # cross-compiler, the c2str tool, from the conftest.c file, instead of # using a system compiler. In other words, c2str is incompatible with the # cross build support (for the TinyCC itself, not its targets!). The only # solution appears to be at the moment to just patch the Makefile to # use it always just the system "gcc" to build that tool. sed -i -e 's/$S$(CC) -DC2STR/gcc -DC2STR/g' Makefile local flags="--enable-cross --cross-prefix=$ARCH_GCC_TC-linux-" local flags="$flags --enable-static --cpu=$ARCH" local af="$flags --prefix=$p --extra-ldflags='$ldflags'" local af="$af --crtprefix=$lib --libpaths=$lib" if [ -f .our_tag ]; then local tag=`cat .our_tag` local githash="$tag" local def_githash="-DTCC_GITHASH=\\\\\\\"${githash}\\\\\\\"" local make_vars="DEF_GITHASH=\"$def_githash\"" fi run_command2 "./configure $af" configure.log run_command2 "make $make_vars cross-$ARCH" build.log # Just to test on the local machine # run_command2 "make install" install.log # Note the configure --strip-binaries option does not work $ARCH_GCC_TC-linux-strip --strip-all $ARCH-tcc else show_skip_component_msg "TCC" fi popd } function build_tcc_installed_status { if [ -d $TC/$ARCH/tcc ]; then if [ -f $TC/$ARCH/tcc/${ARCH}-tcc ]; then echo "installed $ARCH" else echo "error" fi fi } <file_sep>/******************************************************************************* * * Module Name: utmisc - common utility procedures * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utmisc") /******************************************************************************* * * FUNCTION: AcpiUtIsPciRootBridge * * PARAMETERS: Id - The HID/CID in string format * * RETURN: TRUE if the Id is a match for a PCI/PCI-Express Root Bridge * * DESCRIPTION: Determine if the input ID is a PCI Root Bridge ID. * ******************************************************************************/ BOOLEAN AcpiUtIsPciRootBridge ( char *Id) { /* * Check if this is a PCI root bridge. * ACPI 3.0+: check for a PCI Express root also. */ if (!(strcmp (Id, PCI_ROOT_HID_STRING)) || !(strcmp (Id, PCI_EXPRESS_ROOT_HID_STRING))) { return (TRUE); } return (FALSE); } #if (defined ACPI_ASL_COMPILER || defined ACPI_EXEC_APP || defined ACPI_NAMES_APP) /******************************************************************************* * * FUNCTION: AcpiUtIsAmlTable * * PARAMETERS: Table - An ACPI table * * RETURN: TRUE if table contains executable AML; FALSE otherwise * * DESCRIPTION: Check ACPI Signature for a table that contains AML code. * Currently, these are DSDT,SSDT,PSDT. All other table types are * data tables that do not contain AML code. * ******************************************************************************/ BOOLEAN AcpiUtIsAmlTable ( ACPI_TABLE_HEADER *Table) { /* These are the only tables that contain executable AML */ if (ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_DSDT) || ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_PSDT) || ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_SSDT) || ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_OSDT) || ACPI_IS_OEM_SIG (Table->Signature)) { return (TRUE); } return (FALSE); } #endif /******************************************************************************* * * FUNCTION: AcpiUtDwordByteSwap * * PARAMETERS: Value - Value to be converted * * RETURN: UINT32 integer with bytes swapped * * DESCRIPTION: Convert a 32-bit value to big-endian (swap the bytes) * ******************************************************************************/ UINT32 AcpiUtDwordByteSwap ( UINT32 Value) { union { UINT32 Value; UINT8 Bytes[4]; } Out; union { UINT32 Value; UINT8 Bytes[4]; } In; ACPI_FUNCTION_ENTRY (); In.Value = Value; Out.Bytes[0] = In.Bytes[3]; Out.Bytes[1] = In.Bytes[2]; Out.Bytes[2] = In.Bytes[1]; Out.Bytes[3] = In.Bytes[0]; return (Out.Value); } /******************************************************************************* * * FUNCTION: AcpiUtSetIntegerWidth * * PARAMETERS: Revision From DSDT header * * RETURN: None * * DESCRIPTION: Set the global integer bit width based upon the revision * of the DSDT. For Revision 1 and 0, Integers are 32 bits. * For Revision 2 and above, Integers are 64 bits. Yes, this * makes a difference. * ******************************************************************************/ void AcpiUtSetIntegerWidth ( UINT8 Revision) { if (Revision < 2) { /* 32-bit case */ AcpiGbl_IntegerBitWidth = 32; AcpiGbl_IntegerNybbleWidth = 8; AcpiGbl_IntegerByteWidth = 4; } else { /* 64-bit case (ACPI 2.0+) */ AcpiGbl_IntegerBitWidth = 64; AcpiGbl_IntegerNybbleWidth = 16; AcpiGbl_IntegerByteWidth = 8; } } /******************************************************************************* * * FUNCTION: AcpiUtCreateUpdateStateAndPush * * PARAMETERS: Object - Object to be added to the new state * Action - Increment/Decrement * StateList - List the state will be added to * * RETURN: Status * * DESCRIPTION: Create a new state and push it * ******************************************************************************/ ACPI_STATUS AcpiUtCreateUpdateStateAndPush ( ACPI_OPERAND_OBJECT *Object, UINT16 Action, ACPI_GENERIC_STATE **StateList) { ACPI_GENERIC_STATE *State; ACPI_FUNCTION_ENTRY (); /* Ignore null objects; these are expected */ if (!Object) { return (AE_OK); } State = AcpiUtCreateUpdateState (Object, Action); if (!State) { return (AE_NO_MEMORY); } AcpiUtPushGenericState (StateList, State); return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtWalkPackageTree * * PARAMETERS: SourceObject - The package to walk * TargetObject - Target object (if package is being copied) * WalkCallback - Called once for each package element * Context - Passed to the callback function * * RETURN: Status * * DESCRIPTION: Walk through a package, including subpackages * ******************************************************************************/ ACPI_STATUS AcpiUtWalkPackageTree ( ACPI_OPERAND_OBJECT *SourceObject, void *TargetObject, ACPI_PKG_CALLBACK WalkCallback, void *Context) { ACPI_STATUS Status = AE_OK; ACPI_GENERIC_STATE *StateList = NULL; ACPI_GENERIC_STATE *State; ACPI_OPERAND_OBJECT *ThisSourceObj; UINT32 ThisIndex; ACPI_FUNCTION_TRACE (UtWalkPackageTree); State = AcpiUtCreatePkgState (SourceObject, TargetObject, 0); if (!State) { return_ACPI_STATUS (AE_NO_MEMORY); } while (State) { /* Get one element of the package */ ThisIndex = State->Pkg.Index; ThisSourceObj = State->Pkg.SourceObject->Package.Elements[ThisIndex]; State->Pkg.ThisTargetObj = &State->Pkg.SourceObject->Package.Elements[ThisIndex]; /* * Check for: * 1) An uninitialized package element. It is completely * legal to declare a package and leave it uninitialized * 2) Not an internal object - can be a namespace node instead * 3) Any type other than a package. Packages are handled in else * case below. */ if ((!ThisSourceObj) || (ACPI_GET_DESCRIPTOR_TYPE (ThisSourceObj) != ACPI_DESC_TYPE_OPERAND) || (ThisSourceObj->Common.Type != ACPI_TYPE_PACKAGE)) { Status = WalkCallback (ACPI_COPY_TYPE_SIMPLE, ThisSourceObj, State, Context); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } State->Pkg.Index++; while (State->Pkg.Index >= State->Pkg.SourceObject->Package.Count) { /* * We've handled all of the objects at this level, This means * that we have just completed a package. That package may * have contained one or more packages itself. * * Delete this state and pop the previous state (package). */ AcpiUtDeleteGenericState (State); State = AcpiUtPopGenericState (&StateList); /* Finished when there are no more states */ if (!State) { /* * We have handled all of the objects in the top level * package just add the length of the package objects * and exit */ return_ACPI_STATUS (AE_OK); } /* * Go back up a level and move the index past the just * completed package object. */ State->Pkg.Index++; } } else { /* This is a subobject of type package */ Status = WalkCallback ( ACPI_COPY_TYPE_PACKAGE, ThisSourceObj, State, Context); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Push the current state and create a new one * The callback above returned a new target package object. */ AcpiUtPushGenericState (&StateList, State); State = AcpiUtCreatePkgState ( ThisSourceObj, State->Pkg.ThisTargetObj, 0); if (!State) { /* Free any stacked Update State objects */ while (StateList) { State = AcpiUtPopGenericState (&StateList); AcpiUtDeleteGenericState (State); } return_ACPI_STATUS (AE_NO_MEMORY); } } } /* We should never get here */ ACPI_ERROR ((AE_INFO, "State list did not terminate correctly")); return_ACPI_STATUS (AE_AML_INTERNAL); } #ifdef ACPI_DEBUG_OUTPUT /******************************************************************************* * * FUNCTION: AcpiUtDisplayInitPathname * * PARAMETERS: Type - Object type of the node * ObjHandle - Handle whose pathname will be displayed * Path - Additional path string to be appended. * (NULL if no extra path) * * RETURN: ACPI_STATUS * * DESCRIPTION: Display full pathname of an object, DEBUG ONLY * ******************************************************************************/ void AcpiUtDisplayInitPathname ( UINT8 Type, ACPI_NAMESPACE_NODE *ObjHandle, const char *Path) { ACPI_STATUS Status; ACPI_BUFFER Buffer; ACPI_FUNCTION_ENTRY (); /* Only print the path if the appropriate debug level is enabled */ if (!(AcpiDbgLevel & ACPI_LV_INIT_NAMES)) { return; } /* Get the full pathname to the node */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiNsHandleToPathname (ObjHandle, &Buffer, TRUE); if (ACPI_FAILURE (Status)) { return; } /* Print what we're doing */ switch (Type) { case ACPI_TYPE_METHOD: AcpiOsPrintf ("Executing "); break; default: AcpiOsPrintf ("Initializing "); break; } /* Print the object type and pathname */ AcpiOsPrintf ("%-12s %s", AcpiUtGetTypeName (Type), (char *) Buffer.Pointer); /* Extra path is used to append names like _STA, _INI, etc. */ if (Path) { AcpiOsPrintf (".%s", Path); } AcpiOsPrintf ("\n"); ACPI_FREE (Buffer.Pointer); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/paging_hw.h> #include "../generic_x86/paging_generic_x86.h" pdir_t *__kernel_pdir; void early_init_paging(void) { NOT_IMPLEMENTED(); } void *failsafe_map_framebuffer(ulong paddr, ulong size) { NOT_IMPLEMENTED(); } int virtual_read_unsafe(pdir_t *pdir, void *extern_va, void *dest, size_t len) { NOT_IMPLEMENTED(); } int virtual_write_unsafe(pdir_t *pdir, void *extern_va, void *src, size_t len) { NOT_IMPLEMENTED(); } ulong get_mapping(pdir_t *pdir, void *vaddrp) { NOT_IMPLEMENTED(); } int get_mapping2(pdir_t *pdir, void *vaddrp, ulong *pa_ref) { NOT_IMPLEMENTED(); } void handle_page_fault_int(regs_t *r) { NOT_IMPLEMENTED(); } bool is_mapped(pdir_t *pdir, void *vaddrp) { NOT_IMPLEMENTED(); } bool is_rw_mapped(pdir_t *pdir, void *vaddrp) { NOT_IMPLEMENTED(); } void set_page_rw(pdir_t *pdir, void *vaddrp, bool rw) { NOT_IMPLEMENTED(); } NODISCARD int map_page(pdir_t *pdir, void *vaddrp, ulong paddr, u32 pg_flags) { NOT_IMPLEMENTED(); } NODISCARD size_t map_pages(pdir_t *pdir, void *vaddr, ulong paddr, size_t page_count, u32 pg_flags) { NOT_IMPLEMENTED(); } NODISCARD int map_zero_page(pdir_t *pdir, void *vaddrp, u32 pg_flags) { NOT_IMPLEMENTED(); } static inline int __unmap_page(pdir_t *pdir, void *vaddrp, bool free_pageframe, bool permissive) { NOT_IMPLEMENTED(); } void unmap_page(pdir_t *pdir, void *vaddrp, bool free_pageframe) { __unmap_page(pdir, vaddrp, free_pageframe, false); } int unmap_page_permissive(pdir_t *pdir, void *vaddrp, bool free_pageframe) { return __unmap_page(pdir, vaddrp, free_pageframe, true); } void unmap_pages(pdir_t *pdir, void *vaddr, size_t page_count, bool do_free) { for (size_t i = 0; i < page_count; i++) { unmap_page(pdir, (char *)vaddr + (i << PAGE_SHIFT), do_free); } } size_t unmap_pages_permissive(pdir_t *pdir, void *vaddr, size_t page_count, bool do_free) { NOT_IMPLEMENTED(); } pdir_t *pdir_clone(pdir_t *pdir) { NOT_IMPLEMENTED(); } void pdir_destroy(pdir_t *pdir) { NOT_IMPLEMENTED(); } void set_pages_pat_wc(pdir_t *pdir, void *vaddr, size_t size) { NOT_IMPLEMENTED(); } bool handle_potential_cow(void *context) { NOT_IMPLEMENTED(); } void init_hi_vmem_heap(void) { NOT_IMPLEMENTED(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/datetime.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/mods/tracing.h> #include "termutil.h" #include "dp_tracing_int.h" #if MOD_tracing static char *line_buf; /* Shared data with dp_tracing_sys.c */ char *rend_bufs[6]; int used_rend_bufs; /* -- */ void init_dp_tracing(void) { for (int i = 0; i < 6; i++) { if (!(rend_bufs[i] = kmalloc(REND_BUF_SZ))) panic("[dp] Unable to allocate rend_buf[%d]", i); } if (!(line_buf = kmalloc(TRACED_SYSCALLS_STR_LEN))) panic("[dp] Unable to allocate line_buf"); } static void tracing_ui_show_help(void) { dp_write_raw("\r\n\r\n"); dp_write_raw(E_COLOR_YELLOW "Tracing mode help" RESET_ATTRS "\r\n"); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "o" RESET_ATTRS " : Toggle always enter + exit\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "b" RESET_ATTRS " : Toggle dump big buffers\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "e" RESET_ATTRS " : Edit syscalls wildcard expr " E_COLOR_RED "[1]" RESET_ATTRS "\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "k" RESET_ATTRS " : Set trace_printk() level\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "l" RESET_ATTRS " : List traced syscalls\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "p" RESET_ATTRS " : Dump user tasks list\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "P" RESET_ATTRS " : Dump full task list\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "t" RESET_ATTRS " : Edit list of traced PIDs\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " E_COLOR_YELLOW "q" RESET_ATTRS " : Back to the debug panel\r\n" RESET_ATTRS ); dp_write_raw( E_COLOR_YELLOW " " "ENTER" RESET_ATTRS " : Start / stop tracing\r\n" ); dp_write_raw("\r\n" E_COLOR_RED "[1]" RESET_ATTRS " "); dp_write_raw("In the wildcard expr the " E_COLOR_BR_WHITE "*" RESET_ATTRS " character is allowed only once, at the end.\r\n"); dp_write_raw("The " E_COLOR_BR_WHITE "!" RESET_ATTRS " character can be " "used, at the beginning of each sub-expr, to negate it.\r\n"); dp_write_raw("Single sub-expressions are separated by comma or space. " "The " E_COLOR_BR_WHITE "?" RESET_ATTRS " character is\r\n"); dp_write_raw("supported and has the usual meaning " "(matches 1 single char, any).\r\n"); dp_write_raw( E_COLOR_BR_WHITE "Example: " RESET_ATTRS "read*,write*,!readlink* \r\n" ); } static void tracing_ui_msg(void) { dp_write_raw( E_COLOR_YELLOW "Tilck syscall tracing (h: help)\r\n" RESET_ATTRS ); dp_write_raw( TERM_VLINE " Always ENTER+EXIT: %s " TERM_VLINE " Big bufs: %s " TERM_VLINE " #Sys traced: " E_COLOR_BR_BLUE "%d" RESET_ATTRS " " TERM_VLINE " #Tasks traced: " E_COLOR_BR_BLUE "%d" RESET_ATTRS " " TERM_VLINE "\r\n" TERM_VLINE " Printk lvl: " E_COLOR_BR_BLUE "%d" RESET_ATTRS "\r\n", tracing_is_force_exp_block_enabled() ? E_COLOR_GREEN "ON" RESET_ATTRS : E_COLOR_RED "OFF" RESET_ATTRS, tracing_are_dump_big_bufs_on() ? E_COLOR_GREEN "ON" RESET_ATTRS : E_COLOR_RED "OFF" RESET_ATTRS, get_traced_syscalls_count(), get_traced_tasks_count(), tracing_get_printk_lvl() ); get_traced_syscalls_str(line_buf, TRACED_SYSCALLS_STR_LEN); dp_write_raw( TERM_VLINE " Trace expr: " E_COLOR_YELLOW "%s" RESET_ATTRS, line_buf ); dp_write_raw("\r\n"); dp_write_raw(E_COLOR_YELLOW "> " RESET_ATTRS); } static void dp_dump_tracing_event(struct trace_event *e) { dp_write_raw( "%05u.%03u [%05d] ", (u32)(e->sys_time / TS_SCALE), (u32)((e->sys_time % TS_SCALE) / (TS_SCALE / 1000)), e->tid ); switch (e->type) { case te_sys_enter: case te_sys_exit: dp_handle_syscall_event(e); break; case te_printk: dp_write_raw( E_COLOR_YELLOW "LOG" RESET_ATTRS "[%02d]: %s\r\n", e->p_ev.level, e->p_ev.buf ); break; case te_signal_delivered: dp_write_raw( E_COLOR_YELLOW "GOT SIGNAL: " RESET_ATTRS "%s[%d]\r\n", get_signal_name(e->sig_ev.signum), e->sig_ev.signum ); break; case te_killed: dp_write_raw( E_COLOR_BR_RED "KILLED BY SIGNAL: " RESET_ATTRS "%s[%d]\r\n", get_signal_name(e->sig_ev.signum), e->sig_ev.signum ); break; default: dp_write_raw( E_COLOR_BR_RED "<unknown event %d>\r\n" RESET_ATTRS, e->type ); } } static bool dp_tracing_screen_main_loop(void) { struct trace_event e; int rc; char c; while (true) { /* Check the input for Ctrl+C */ rc = vfs_read(dp_input_handle, &c, 1); if (rc < 0 && rc != -EAGAIN) return false; /* exit because of an error */ if (rc == 1) { switch (c) { case 'q': return false; /* clean exit */ case DP_KEY_ENTER: return true; /* stop dumping the trace buffer */ } } if (read_trace_event(&e, TIMER_HZ / 10)) dp_dump_tracing_event(&e); } NOT_REACHED(); } static void dp_edit_trace_syscall_str(void) { get_traced_syscalls_str(line_buf, TRACED_SYSCALLS_STR_LEN); dp_move_left(2); dp_write_raw(E_COLOR_YELLOW "expr> " RESET_ATTRS); dp_set_input_blocking(true); dp_read_line(line_buf, TRACED_SYSCALLS_STR_LEN); dp_set_input_blocking(false); if (set_traced_syscalls(line_buf) < 0) dp_write_raw(E_COLOR_RED "Invalid input\r\n" RESET_ATTRS); } static void dp_edit_trace_printk_level(void) { line_buf[0] = 0; dp_move_left(2); dp_write_raw(E_COLOR_YELLOW "Level [0, 100]: " RESET_ATTRS); dp_set_input_blocking(true); dp_read_line(line_buf, TRACED_SYSCALLS_STR_LEN); dp_set_input_blocking(false); int err = 0; long val = tilck_strtol(line_buf, NULL, 10, &err); if (err || val < 0 || val > 100) { dp_write_raw("\r\n"); dp_write_raw(E_COLOR_RED "Invalid input\r\n" RESET_ATTRS); return; } tracing_set_printk_lvl((int) val); } struct traced_list_cb_ctx { char *buf; size_t buf_sz; size_t written; }; static int dp_tracing_get_traced_list_str_cb(void *obj, void *arg) { struct task *ti = obj; struct traced_list_cb_ctx *ctx = arg; char tidstr[16]; size_t s; if (!ti->traced) return 0; s = (size_t)snprintk(tidstr, sizeof(tidstr), "%d,", ti->tid); if (ctx->written + s + 1 < ctx->buf_sz) { strcpy(ctx->buf + ctx->written, tidstr); ctx->written += s; } /* Disable tracing */ ti->traced = false; return 0; } static int dp_set_task_as_traced(const char *tidstr, int *traced_cnt) { long tid = tilck_strtol(tidstr, NULL, 10, NULL); if (tid <= 0) return -1; struct task *ti; disable_preemption(); { ti = get_task((int)tid); if (ti) { ti->traced = true; (*traced_cnt)++; } } enable_preemption(); return 0; } static int dp_set_traced_tids_str(const char *str, int *traced_cnt) { const char *s = str; char *p, buf[32]; int rc; for (p = buf; *s; s++) { if (p == buf + sizeof(buf)) return -ENAMETOOLONG; if (*s == ',' || *s == ' ') { *p = 0; p = buf; if ((rc = dp_set_task_as_traced(buf, traced_cnt))) return rc; continue; } *p++ = *s; } if (p > buf) { *p = 0; if ((rc = dp_set_task_as_traced(buf, traced_cnt))) return rc; } return 0; } static void dp_edit_traced_list(void) { int traced_cnt = 0; line_buf[0] = 0; struct traced_list_cb_ctx ctx = { .buf = line_buf, .buf_sz = TRACED_SYSCALLS_STR_LEN, .written = 0, }; disable_preemption(); { iterate_over_tasks(dp_tracing_get_traced_list_str_cb, &ctx); } enable_preemption(); dp_move_left(2); dp_write_raw(E_COLOR_YELLOW "PIDs> " RESET_ATTRS); dp_set_input_blocking(true); dp_read_line(line_buf, TRACED_SYSCALLS_STR_LEN); dp_set_input_blocking(false); dp_write_raw("\r\n"); if (dp_set_traced_tids_str(line_buf, &traced_cnt) < 0) { dp_write_raw("Invalid input\r\n"); } else { dp_write_raw("Tracing %d tasks\r\n", traced_cnt); } } static void dp_list_traced_syscalls(void) { dp_write_raw("\r\n\r\n"); dp_write_raw(E_COLOR_YELLOW "Traced syscalls list" RESET_ATTRS); dp_write_raw("\r\n"); for (u32 i = 0; i < MAX_SYSCALLS; i++) { if (!tracing_is_enabled_on_sys(i)) continue; dp_write_raw("%s ", 4 + tracing_get_syscall_name(i)); } dp_write_raw("\r\n"); } static int dp_tracing_dump_remaining_events(void) { char c; int rem; struct key_event ke; struct trace_event e; if (!(rem = tracing_get_in_buffer_events_count())) return 0; /* no remaining events in the buffer */ dp_write_raw("Discard remaining %d events in the buf? [Y/n] ", rem); do { if (dp_read_ke_from_tty(&ke) < 0) return -1; /* unexpected I/O error */ c = ke.print_char; } while (c != 'y' && c != 'n' && c != '\r'); if (c == '\r') c = 'y'; dp_write_raw_int(&c, 1); while (true) { if (!read_trace_event_noblock(&e)) break; if (c == 'n') dp_dump_tracing_event(&e); } dp_write_raw("\r\n"); return 1; } enum kb_handler_action dp_tracing_screen(void) { char c; int rc; bool should_continue; dp_set_cursor_enabled(true); dp_clear(); dp_move_cursor(1, 1); tracing_ui_msg(); while (true) { dp_set_input_blocking(true); { rc = vfs_read(dp_input_handle, &c, 1); } dp_set_input_blocking(false); if (rc <= 0) break; /* something gone wrong */ if (c == 'q') break; /* clean exit */ if (c == DP_KEY_ENTER) { dp_write_raw("\r\n"); dp_write_raw( E_COLOR_GREEN "-- Tracing active --" RESET_ATTRS "\r\n\r\n" ); tracing_set_enabled(true); { should_continue = dp_tracing_screen_main_loop(); } tracing_set_enabled(false); if (!should_continue) break; dp_write_raw( E_COLOR_RED "-- Tracing stopped --" RESET_ATTRS "\r\n" ); if ((rc = dp_tracing_dump_remaining_events()) < 0) break; /* unexpected I/O error */ dp_write_raw("\r\n"); tracing_ui_msg(); continue; } switch (c) { case 'o': dp_write_raw("%c", c); tracing_set_force_exp_block(!tracing_is_force_exp_block_enabled()); break; case 'b': dp_write_raw("%c", c); tracing_set_dump_big_bufs_opt(!tracing_are_dump_big_bufs_on()); break; case 'h': dp_write_raw("%c", c); tracing_ui_show_help(); break; case 'p': dp_write_raw("%c", c); dp_dump_task_list(false, true); break; case 'P': dp_write_raw("%c", c); dp_dump_task_list(true, true); break; case 'l': dp_write_raw("%c", c); dp_list_traced_syscalls(); break; case 'e': dp_edit_trace_syscall_str(); break; case 'k': dp_edit_trace_printk_level(); break; case 't': dp_edit_traced_list(); break; default: continue; } dp_write_raw("\r\n\r\n"); tracing_ui_msg(); } ui_need_update = true; dp_set_cursor_enabled(false); return kb_handler_ok_and_continue; } #endif // #if MOD_tracing <file_sep> # Building & configuring Tilck ## Contents * [Introduction](#introduction) * [Building Tilck's toolchain](#building-tilcks-toolchain) - [Extra packages](#extra-packages) * [Building Tilck](#building-tilck) * [Configuring Tilck](#configuring-tilck) * [Build types](#build-types) * [Running the UEFI bootloader on QEMU](#running-the-uefi-bootloader-on-qemu) * [Building Tilck's unit tests](#building-tilcks-unit-tests) * [Building Tilck with Clang (advanced)](#building-tilck-with-clang-advanced) * [Special build configurations (advanced)](#special-build-configurations-advanced) ## Introduction Tilck has a CMake-based build system relying on a local toolchain, built by the `build_toolchain` Bash script. The first time Tilck's repo is cloned, it is necessary to build Tilck's local toolchain by running that script. After that, it will be possible to prepare Tilck's build by running CMake in any chosen build directory. While running `cmake` directly it is possible, the strongly recommended practice in Tilck is to run the wrapper script `cmake_run` instead. That script checks the version of the GCC compiler on the machine, offers handy shortcuts, allows us to use a CMake binary from the local toolchain, and other things. ## Building Tilck's toolchain When run without any options, the `build_toolchain` script installs a minimal set of packages (e.g. cross GCC toolchain, busybox, etc.) in the local toolchain. While it's part of Tilck's philosophy to have as fewer dependencies as possible, there still are some packages required to be installed at *system level* (e.g. gcc, git, wget, tar, grep, make, etc.) simply because they're needed to build Tilck's toolchain itself. Once run, the `build_toolchain` script will take care of detecting which packages need to be installed and it will also run the right command for your Linux distribution to install them (e.g. `sudo apt install gcc g++ git [...]`). Most of the mainstream Linux distributions are supported. In the case you're using a distro not supported, the script will just dump a list of programs that need to be installed manually on the system before the script could continue further. ### Extra packages After the first run of `build_toolchain` finishes, it's possible to build Tilck but, that doesn't mean the script becomes useless. Actually, most of the packages that it can install are not installed by default. The idea behind that is to perform the first setup as quickly as possible. To see all the packages available, just run the script with `-h`. Single packages can be installed using the `-s` option. To be more precise, the script calls them *functions* because in some cases (e.g. config_busybx) they are meant to just (re)configure a package. **Shortcut**: while the script lists its functions with their full name, it accepts also short names like `gtest` instead of `build_gtest` and `ovmf` instead of `download_ovmf`. ## Building Tilck To build Tilck, it's necessary to run first `<TILCK_DIR>/scripts/cmake_run` in the chosen build directory (e.g. `~john/builds/tilck01`) and then just run `make` there. That means that **out-of-tree builds** are supported effortlessly. But, because 99% of the time it's just fine to have a `build` directory inside our project's main directory (e.g. `~john/devel/tilck`), we can simple run `./scripts/cmake_run` there. It will detect that's our main directory and it will create the `build` subdir. After that, we'll still have to enter the `build` directory and run `make` there, because that's where CMake placed its generated makefiles. In reality, there's a more convenient **shortcut**: just run `make` in project's main directory, using the trivial wrapper Makefile included in Tilck's source: it will simply run `$(MAKE) -C build`. In case the `build/` directory does not exist yet, it will also run the `cmake_run` wrapper script first. #### Build performance notes To speed up Tilck's build, it's possible to increase the level of parallelism with GNU make's option `-j<N>`. For example, `make -j4` means that at most 4 instances of the compiler will be run in parallel. **WARNING**: increasing the level of parallelism requires significantly more memory in the host system It's hard to estimate in general how much memory each instance of GCC or Clang will use for compiling a C or C++ file, but it makes sense to be conservative and to account for ~1 GB of RAM per GCC/Clang instance. Therefore, `make -j4` would require at least 4 GB of available memory in the host system used for building Tilck. Still, it's possible to increase the level of parallelism at your own discretion, keeping in mind that in case the Linux host system runs out of memory while building this project (or anything else!), the OOM killer will run and **that will make the system potentially unstable/unusable**. **See:** * Issue https://github.com/vvaltchev/tilck/issues/101 * https://unix.stackexchange.com/questions/316644/ * https://unix.stackexchange.com/questions/208568/ * https://unix.stackexchange.com/questions/153585/ * https://lwn.net/Articles/317814/ ## Configuring Tilck When `cmake_run` is run, all configuration options are dumped on the screen as CMake info messages. Therefore, changing one of them is easy as running: ./scripts/cmake_run -DDEBUG_CHECKS=0 (Note: `cmake_run` forwards its arguments to CMake.) But, that's certainly not the best way to (re)configure Tilck. A more convenient way is to use CMake's console tool called `ccmake`, part of `cmake-curses-gui` package (at least on Debian systems). Its main advantage is that all the options are visible and editable in an interactive way and that for each option there is a description. It's not visually cool and fancy like Linux's Kconfig, but it's fully integrated with CMake and does a good job, overall. (Maybe in the future Tilck will switch to Kconfig or some custom tool for a better user experience even in this case.) Running `ccmake` is simple as: ccmake ./build But, as for the `cmake_run` case, it's **highly recommended** to run its wrapper script called `run_config`: ./scripts/run_config It has additional error-checking and prevents trivial errors like running `ccmake .` (which will create an empty CMakeCache.txt in `.`) instead of `ccmake build/` in project's main directory. Of course, it supports out-of-tree builds as well: just pass the build directory as first argument. Finally, there is also a wrapper for people used with Kconfig too, working when the in-tree build directory is used (again, 99% of the time): make config Or: make menuconfig They have both the same effect as running `run_config`. In summary, it's convenient to use `run_config` or `make config` instead of running `ccmake` directly because of its error-checking and because at some point Tilck will have something with a better UI than `ccmake` that will be run by the wrapper scripts. ## Build types Tilck's build types differ only by the optimization flags used. Three build types are currently supported: * Debug: `-O0 -fno-inline-functions` * Release: `-O3` * MinSizeRel: `-Os` Tilck's default build type is: Debug. It's worth noting that very few projects are built by default with `-O0 -fno-inline-functions` because the code produced is very inefficient. Fortunately, Tilck still performs very well in this case. Therefore, it's convenient to use this build type in particular when debugging Tilck because the value of all local variables will be visible in GDB (no optimizations, no inlining). Changing Tilck's build type is simple as running: ./scripts/cmake_run -DCMAKE_BUILD_TYPE=Release For `Release` builds there's a nice shortcut: REL=1 ./scripts/cmake_run Finally, it's necessary to remark that, because level of compiler's optimization is the **only** thing that distinguishes the build types, ASSERTs are checked no matter the build type. To compile them out, it's necessary to turn off the `DEBUG_CHECKS` flag. ## Running the UEFI bootloader on QEMU While Tilck's image is bootable on a UEFI machine, QEMU doesn't by default get installed with a UEFI firmware. Therefore, typically we boot Tilck using only its legacy bootloader. But, when some work has to be done on the UEFI bootloader, it's very convenient (and quicker) to test it on a VM, before running it on real hardware. To do that, it's necessary to first to ask the `build_toolchain` script to download the Open Virtual Machine Firmware ([OVMF]) with: ./scripts/build_toolchain -s download_ovmf After that, it will be possible to boot Tilck by running: ./build/run_efi_qemu32 Note: there's a `run_efi_qemu64` script as well. Its purpose is to test the very realistic case where modern x86_64 machines run Tilck and the UEFI bootloader has to switch from `long mode` to `protected mode 32` before jumping to the kernel. ## Building Tilck's unit tests Tilck uses the [googletest] framework for unit tests and that's not downloaded by `build_toolchain` when it's run without arguments. In order to install that framework in the toolchain, just run: ./scripts/build_toolchain -s gtest gmock After that, you'll need to run the `cmake_run` script again: ./scripts/cmake_run # For in-tree builds Or: ./scripts/cmake_run <BUILD_DIR> # For out-of-tree builds Finally, just build the unit tests with: make gtests To run them, execute: ./build/gtests **Note**: there's more about the unit tests, including special build configurations. For all of that, see the [testing] document. ## Building Tilck with system's compiler (advanced) While for most of the projects it makes sense to build by default with system's compiler and require some special setup in order to work with a cross-compiler, for Tilck is exactly the opposite. Tilck's build system has been designed around the idea of using by default a pre-built toolchain from [bootlin.com] for building the kernel, the boot loaders, and Tilck's user apps (the system compiler is used for anything else that has to run on the host machine instead). That is extremely convenient because it saves a lot of time and disk space to anyone who wants to build Tilck (those pre-built toolchains take just ~60 MB of space) and it's also versatile because porting Tilck to a new architecture would be trivial, from the point of view of the build system. Still, in some rare cases using the system's compiler is helpful. For example, when we want to debug an application to understand what happens at libc level (Tilck uses [libmusl] as libc), we have to build [libmusl] and use the system compiler instead of the one from [bootlin.com] because we need all the debug symbols etc. To do that, first check that: - You have a GCC installed on your system - Your GCC version can build i686 binaries. On all the systems in the Debian family (like Ubuntu, Mint etc.), install the `gcc-multilib` and `g++-multilib` packages for that. Then, install [libmusl] in the toolchain with: ./scripts/build_toolchain -s build_libmusl After that, remove the `build` directory and run `cmake_run` this way: USE_SYSCC=1 ./scripts/cmake_run In case there are multiple versions of GCC installed on the system (e.g. gcc-7 and gcc-9), also the `CC` and `CXX` variables can be set. **Warning**: being this an advanced use case, the user should have some confidence with build systems, cross compilers (etc.) in order to deal with any eventual issues on his/her particular system, in particular if it's not a *mainstream* Linux distribution. While the default build of Tilck is widely supported and it has very few external dependencies (it uses the same pre-built toolchain), in this case system's configuration matters. Still, Tilck's `build_toolchain` script and the build system are regularly tested on the following Linux distributions: * Ubuntu (primary) * Debian * Mint * Fedora * Arch * Manjaro * openSUSE [bootlin.com]: https://toolchains.bootlin.com [libmusl]: https://www.musl-libc.org/ ## Building Tilck with Clang (advanced) The Tilck project **cannot** be entirely built with a Clang toolchain, at the moment. But, it still has partial support for Clang because: * Supporting more than compiler (in general) improves the code * Clang sometimes reports warnings in cases where GCC doesn't (the opposite is true as well) * The `-Wconversion` flag as implemented in Clang is very useful * Clang's [Static Analyzer] is great * Tilck has a custom plug-in for the Clang's [Static Analyzer] (but currently it's not open source) #### How to build with Clang 1. Install `clang` and `clang++` and make sure it can build i686 binaries. 2. Run: `CC=clang CXX=clang++ ./scripts/cmake_run -DKERNEL_SYSCC=1` 3. Build as always with `make` The `KERNEL_SYSCC` option makes the build system to use `CC` and `CXX` to build kernel's C and C++ files, while still building the assembly files with the pre-built GCC toolchain from [bootlin.com]. **Note**: no matter the `KERNEL_SYSCC` option, kernel's unit tests (see [testing]) are always built using system's compiler. Therefore, setting `CC=clang CXX=clang++` will cause the unit tests to be completely built with Clang: this scenario is fully supported and has no tricky limitations. #### Why we can't build the whole project with Clang? 1. Major problem: `llvm-as` is not 100% compatible with `gas`. In particular, it does not support expressions as literals (e.g. 0x1000 + 32 * 8) in the same way `gas` does. 2. Minor problem: Clang does not support the Microsoft ABI when the output's type is not a [PE] binary, while GCC does not support [PE] as output at all. That prevents using Clang to build the EFI bootloader. A dedicated build of the EFI bootloader for Clang *can* be written, but it would be very different from the GCC one but, supporting two completely different builds for the same target is an overkill, especially because it wouldn't be enough for building *everything* with Clang (see the problem above). ## Special build configurations (advanced) Tilck has a predefined list of supported configurations which must always build and pass all the tests. Most of them are built & run each time a branch is pushed by the [Azure Pipelines] CI but some of them are left out because of the limited resources available there. Anyway, independently of the amount of resources available in CI builds, we need a simple way to test everything on our local machines. That's why the directory `scripts/build_generators` has been created. Each file there is shell script which creates a different configuration by calling `cmake_run` with a specific set of options. On top of that, there's the `./scripts/adv/gen_other_builds` script which actually *builds* the kernel and its unit tests for each configuration, and finally, there's (in the same directory) the `test_all_other_builds` script which *runs* all the tests (except the interactive ones) for each configuration. **Note**: these scripts expect a variety of additional packages to be installed both on the host machine and in Tilck's toolchain. Before running them for the first time, check (following the sections above) that the whole project can build with the system's compiler (GCC) and that the kernel and the unit tests can build with Clang as well because both of those build configurations are used. [testing]: testing.md [googletest]: https://github.com/google/googletest [Azure Pipelines]: https://azure.microsoft.com/en-us/services/devops/pipelines [Static Analyzer]: https://clang-analyzer.llvm.org/ [OVMF]: https://github.com/tianocore/tianocore.github.io/wiki/OVMF [PE]: https://en.wikipedia.org/wiki/Portable_Executable <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #if defined(__GNUC__) && !defined(__clang__) #define COMPILER_NAME "gcc" #define COMPILER_MAJOR __GNUC__ #define COMPILER_MINOR __GNUC_MINOR__ #define COMPILER_PATCHLEVEL __GNUC_PATCHLEVEL__ #elif defined(__clang__) #define COMPILER_NAME "clang" #define COMPILER_MAJOR __clang_major__ #define COMPILER_MINOR __clang_minor__ #define COMPILER_PATCHLEVEL __clang_patchlevel__ #else #error Compiler not supported #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * NOTE: there's no #pragma once in this header. It is supposed to be included * more than once, when necessary. * * Q: Why having a separate header for ASSERT instead of just using panic.h ? * * A: Because an ASSERT macro is defined in gnu-efi as well. Because of that, * the EFI bootloader cannot build. Currently, panic.h includes automatically * assert.h in all the cases except where NO_TILCK_ASSERT is defined. Because * ASSERTs are used in headers as well, in order to include gnu-efi headers * is necessary to #undef ASSERT and re-define it after including the gnu-efi * headers by including this header again. */ #include <tilck/common/basic_defs.h> NORETURN void assert_failed(const char *expr, const char *file, int line); #ifdef ASSERT #undef ASSERT #endif #ifndef NDEBUG #define ASSERT(x) \ do { \ if (UNLIKELY(!(x))) { \ assert_failed(#x , __FILE__, __LINE__); \ } \ } while (0) #else #define ASSERT(x) do { /* nothing */ } while (0) #endif <file_sep>/****************************************************************************** * * Module Name: exresolv - AML Interpreter object resolution * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exresolv") /* Local prototypes */ static ACPI_STATUS AcpiExResolveObjectToValue ( ACPI_OPERAND_OBJECT **StackPtr, ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiExResolveToValue * * PARAMETERS: **StackPtr - Points to entry on ObjStack, which can * be either an (ACPI_OPERAND_OBJECT *) * or an ACPI_HANDLE. * WalkState - Current method state * * RETURN: Status * * DESCRIPTION: Convert Reference objects to values * ******************************************************************************/ ACPI_STATUS AcpiExResolveToValue ( ACPI_OPERAND_OBJECT **StackPtr, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (ExResolveToValue, StackPtr); if (!StackPtr || !*StackPtr) { ACPI_ERROR ((AE_INFO, "Internal - null pointer")); return_ACPI_STATUS (AE_AML_NO_OPERAND); } /* * The entity pointed to by the StackPtr can be either * 1) A valid ACPI_OPERAND_OBJECT, or * 2) A ACPI_NAMESPACE_NODE (NamedObj) */ if (ACPI_GET_DESCRIPTOR_TYPE (*StackPtr) == ACPI_DESC_TYPE_OPERAND) { Status = AcpiExResolveObjectToValue (StackPtr, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } if (!*StackPtr) { ACPI_ERROR ((AE_INFO, "Internal - null pointer")); return_ACPI_STATUS (AE_AML_NO_OPERAND); } } /* * Object on the stack may have changed if AcpiExResolveObjectToValue() * was called (i.e., we can't use an _else_ here.) */ if (ACPI_GET_DESCRIPTOR_TYPE (*StackPtr) == ACPI_DESC_TYPE_NAMED) { Status = AcpiExResolveNodeToValue ( ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, StackPtr), WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Resolved object %p\n", *StackPtr)); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExResolveObjectToValue * * PARAMETERS: StackPtr - Pointer to an internal object * WalkState - Current method state * * RETURN: Status * * DESCRIPTION: Retrieve the value from an internal object. The Reference type * uses the associated AML opcode to determine the value. * ******************************************************************************/ static ACPI_STATUS AcpiExResolveObjectToValue ( ACPI_OPERAND_OBJECT **StackPtr, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *StackDesc; ACPI_OPERAND_OBJECT *ObjDesc = NULL; UINT8 RefType; ACPI_FUNCTION_TRACE (ExResolveObjectToValue); StackDesc = *StackPtr; /* This is an object of type ACPI_OPERAND_OBJECT */ switch (StackDesc->Common.Type) { case ACPI_TYPE_LOCAL_REFERENCE: RefType = StackDesc->Reference.Class; switch (RefType) { case ACPI_REFCLASS_LOCAL: case ACPI_REFCLASS_ARG: /* * Get the local from the method's state info * Note: this increments the local's object reference count */ Status = AcpiDsMethodDataGetValue (RefType, StackDesc->Reference.Value, WalkState, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "[Arg/Local %X] ValueObj is %p\n", StackDesc->Reference.Value, ObjDesc)); /* * Now we can delete the original Reference Object and * replace it with the resolved value */ AcpiUtRemoveReference (StackDesc); *StackPtr = ObjDesc; break; case ACPI_REFCLASS_INDEX: switch (StackDesc->Reference.TargetType) { case ACPI_TYPE_BUFFER_FIELD: /* Just return - do not dereference */ break; case ACPI_TYPE_PACKAGE: /* If method call or CopyObject - do not dereference */ if ((WalkState->Opcode == AML_INT_METHODCALL_OP) || (WalkState->Opcode == AML_COPY_OBJECT_OP)) { break; } /* Otherwise, dereference the PackageIndex to a package element */ ObjDesc = *StackDesc->Reference.Where; if (ObjDesc) { /* * Valid object descriptor, copy pointer to return value * (i.e., dereference the package index) * Delete the ref object, increment the returned object */ AcpiUtAddReference (ObjDesc); *StackPtr = ObjDesc; } else { /* * A NULL object descriptor means an uninitialized element of * the package, can't dereference it */ ACPI_ERROR ((AE_INFO, "Attempt to dereference an Index to " "NULL package element Idx=%p", StackDesc)); Status = AE_AML_UNINITIALIZED_ELEMENT; } break; default: /* Invalid reference object */ ACPI_ERROR ((AE_INFO, "Unknown TargetType 0x%X in Index/Reference object %p", StackDesc->Reference.TargetType, StackDesc)); Status = AE_AML_INTERNAL; break; } break; case ACPI_REFCLASS_REFOF: case ACPI_REFCLASS_DEBUG: case ACPI_REFCLASS_TABLE: /* Just leave the object as-is, do not dereference */ break; case ACPI_REFCLASS_NAME: /* Reference to a named object */ /* Dereference the name */ if ((StackDesc->Reference.Node->Type == ACPI_TYPE_DEVICE) || (StackDesc->Reference.Node->Type == ACPI_TYPE_THERMAL)) { /* These node types do not have 'real' subobjects */ *StackPtr = (void *) StackDesc->Reference.Node; } else { /* Get the object pointed to by the namespace node */ *StackPtr = (StackDesc->Reference.Node)->Object; AcpiUtAddReference (*StackPtr); } AcpiUtRemoveReference (StackDesc); break; default: ACPI_ERROR ((AE_INFO, "Unknown Reference type 0x%X in %p", RefType, StackDesc)); Status = AE_AML_INTERNAL; break; } break; case ACPI_TYPE_BUFFER: Status = AcpiDsGetBufferArguments (StackDesc); break; case ACPI_TYPE_PACKAGE: Status = AcpiDsGetPackageArguments (StackDesc); break; case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "FieldRead SourceDesc=%p Type=%X\n", StackDesc, StackDesc->Common.Type)); Status = AcpiExReadDataFromField (WalkState, StackDesc, &ObjDesc); /* Remove a reference to the original operand, then override */ AcpiUtRemoveReference (*StackPtr); *StackPtr = (void *) ObjDesc; break; default: break; } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExResolveMultiple * * PARAMETERS: WalkState - Current state (contains AML opcode) * Operand - Starting point for resolution * ReturnType - Where the object type is returned * ReturnDesc - Where the resolved object is returned * * RETURN: Status * * DESCRIPTION: Return the base object and type. Traverse a reference list if * necessary to get to the base object. * ******************************************************************************/ ACPI_STATUS AcpiExResolveMultiple ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT *Operand, ACPI_OBJECT_TYPE *ReturnType, ACPI_OPERAND_OBJECT **ReturnDesc) { ACPI_OPERAND_OBJECT *ObjDesc = ACPI_CAST_PTR (void, Operand); ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Operand); ACPI_OBJECT_TYPE Type; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiExResolveMultiple); /* Operand can be either a namespace node or an operand descriptor */ switch (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc)) { case ACPI_DESC_TYPE_OPERAND: Type = ObjDesc->Common.Type; break; case ACPI_DESC_TYPE_NAMED: Type = ((ACPI_NAMESPACE_NODE *) ObjDesc)->Type; ObjDesc = AcpiNsGetAttachedObject (Node); /* If we had an Alias node, use the attached object for type info */ if (Type == ACPI_TYPE_LOCAL_ALIAS) { Type = ((ACPI_NAMESPACE_NODE *) ObjDesc)->Type; ObjDesc = AcpiNsGetAttachedObject ( (ACPI_NAMESPACE_NODE *) ObjDesc); } switch (Type) { case ACPI_TYPE_DEVICE: case ACPI_TYPE_THERMAL: /* These types have no attached subobject */ break; default: /* All other types require a subobject */ if (!ObjDesc) { ACPI_ERROR ((AE_INFO, "[%4.4s] Node is unresolved or uninitialized", AcpiUtGetNodeName (Node))); return_ACPI_STATUS (AE_AML_UNINITIALIZED_NODE); } break; } break; default: return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* If type is anything other than a reference, we are done */ if (Type != ACPI_TYPE_LOCAL_REFERENCE) { goto Exit; } /* * For reference objects created via the RefOf, Index, or Load/LoadTable * operators, we need to get to the base object (as per the ACPI * specification of the ObjectType and SizeOf operators). This means * traversing the list of possibly many nested references. */ while (ObjDesc->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) { switch (ObjDesc->Reference.Class) { case ACPI_REFCLASS_REFOF: case ACPI_REFCLASS_NAME: /* Dereference the reference pointer */ if (ObjDesc->Reference.Class == ACPI_REFCLASS_REFOF) { Node = ObjDesc->Reference.Object; } else /* AML_INT_NAMEPATH_OP */ { Node = ObjDesc->Reference.Node; } /* All "References" point to a NS node */ if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED) { ACPI_ERROR ((AE_INFO, "Not a namespace node %p [%s]", Node, AcpiUtGetDescriptorName (Node))); return_ACPI_STATUS (AE_AML_INTERNAL); } /* Get the attached object */ ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { /* No object, use the NS node type */ Type = AcpiNsGetType (Node); goto Exit; } /* Check for circular references */ if (ObjDesc == Operand) { return_ACPI_STATUS (AE_AML_CIRCULAR_REFERENCE); } break; case ACPI_REFCLASS_INDEX: /* Get the type of this reference (index into another object) */ Type = ObjDesc->Reference.TargetType; if (Type != ACPI_TYPE_PACKAGE) { goto Exit; } /* * The main object is a package, we want to get the type * of the individual package element that is referenced by * the index. * * This could of course in turn be another reference object. */ ObjDesc = *(ObjDesc->Reference.Where); if (!ObjDesc) { /* NULL package elements are allowed */ Type = 0; /* Uninitialized */ goto Exit; } break; case ACPI_REFCLASS_TABLE: Type = ACPI_TYPE_DDB_HANDLE; goto Exit; case ACPI_REFCLASS_LOCAL: case ACPI_REFCLASS_ARG: if (ReturnDesc) { Status = AcpiDsMethodDataGetValue (ObjDesc->Reference.Class, ObjDesc->Reference.Value, WalkState, &ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiUtRemoveReference (ObjDesc); } else { Status = AcpiDsMethodDataGetNode (ObjDesc->Reference.Class, ObjDesc->Reference.Value, WalkState, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { Type = ACPI_TYPE_ANY; goto Exit; } } break; case ACPI_REFCLASS_DEBUG: /* The Debug Object is of type "DebugObject" */ Type = ACPI_TYPE_DEBUG_OBJECT; goto Exit; default: ACPI_ERROR ((AE_INFO, "Unknown Reference Class 0x%2.2X", ObjDesc->Reference.Class)); return_ACPI_STATUS (AE_AML_INTERNAL); } } /* * Now we are guaranteed to have an object that has not been created * via the RefOf or Index operators. */ Type = ObjDesc->Common.Type; Exit: /* Convert internal types to external types */ switch (Type) { case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: Type = ACPI_TYPE_FIELD_UNIT; break; case ACPI_TYPE_LOCAL_SCOPE: /* Per ACPI Specification, Scope is untyped */ Type = ACPI_TYPE_ANY; break; default: /* No change to Type required */ break; } *ReturnType = Type; if (ReturnDesc) { *ReturnDesc = ObjDesc; } return_ACPI_STATUS (AE_OK); } <file_sep>/****************************************************************************** * * Module Name: dscontrol - Support for execution control opcodes - * if/else/while/return * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "amlcode.h" #include "acdispat.h" #include "acinterp.h" #include "acdebug.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dscontrol") /******************************************************************************* * * FUNCTION: AcpiDsExecBeginControlOp * * PARAMETERS: WalkList - The list that owns the walk stack * Op - The control Op * * RETURN: Status * * DESCRIPTION: Handles all control ops encountered during control method * execution. * ******************************************************************************/ ACPI_STATUS AcpiDsExecBeginControlOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status = AE_OK; ACPI_GENERIC_STATE *ControlState; ACPI_FUNCTION_NAME (DsExecBeginControlOp); ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Op=%p Opcode=%2.2X State=%p\n", Op, Op->Common.AmlOpcode, WalkState)); switch (Op->Common.AmlOpcode) { case AML_WHILE_OP: /* * If this is an additional iteration of a while loop, continue. * There is no need to allocate a new control state. */ if (WalkState->ControlState) { if (WalkState->ControlState->Control.AmlPredicateStart == (WalkState->ParserState.Aml - 1)) { /* Reset the state to start-of-loop */ WalkState->ControlState->Common.State = ACPI_CONTROL_CONDITIONAL_EXECUTING; break; } } /*lint -fallthrough */ case AML_IF_OP: /* * IF/WHILE: Create a new control state to manage these * constructs. We need to manage these as a stack, in order * to handle nesting. */ ControlState = AcpiUtCreateControlState (); if (!ControlState) { Status = AE_NO_MEMORY; break; } /* * Save a pointer to the predicate for multiple executions * of a loop */ ControlState->Control.AmlPredicateStart = WalkState->ParserState.Aml - 1; ControlState->Control.PackageEnd = WalkState->ParserState.PkgEnd; ControlState->Control.Opcode = Op->Common.AmlOpcode; ControlState->Control.LoopTimeout = AcpiOsGetTimer () + ((UINT64) AcpiGbl_MaxLoopIterations * ACPI_100NSEC_PER_SEC); /* Push the control state on this walk's control stack */ AcpiUtPushGenericState (&WalkState->ControlState, ControlState); break; case AML_ELSE_OP: /* Predicate is in the state object */ /* If predicate is true, the IF was executed, ignore ELSE part */ if (WalkState->LastPredicate) { Status = AE_CTRL_TRUE; } break; case AML_RETURN_OP: break; default: break; } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDsExecEndControlOp * * PARAMETERS: WalkList - The list that owns the walk stack * Op - The control Op * * RETURN: Status * * DESCRIPTION: Handles all control ops encountered during control method * execution. * ******************************************************************************/ ACPI_STATUS AcpiDsExecEndControlOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status = AE_OK; ACPI_GENERIC_STATE *ControlState; ACPI_FUNCTION_NAME (DsExecEndControlOp); switch (Op->Common.AmlOpcode) { case AML_IF_OP: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[IF_OP] Op=%p\n", Op)); /* * Save the result of the predicate in case there is an * ELSE to come */ WalkState->LastPredicate = (BOOLEAN) WalkState->ControlState->Common.Value; /* * Pop the control state that was created at the start * of the IF and free it */ ControlState = AcpiUtPopGenericState (&WalkState->ControlState); AcpiUtDeleteGenericState (ControlState); break; case AML_ELSE_OP: break; case AML_WHILE_OP: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[WHILE_OP] Op=%p\n", Op)); ControlState = WalkState->ControlState; if (ControlState->Common.Value) { /* Predicate was true, the body of the loop was just executed */ /* * This infinite loop detection mechanism allows the interpreter * to escape possibly infinite loops. This can occur in poorly * written AML when the hardware does not respond within a while * loop and the loop does not implement a timeout. */ if (ACPI_TIME_AFTER (AcpiOsGetTimer (), ControlState->Control.LoopTimeout)) { Status = AE_AML_LOOP_TIMEOUT; break; } /* * Go back and evaluate the predicate and maybe execute the loop * another time */ Status = AE_CTRL_PENDING; WalkState->AmlLastWhile = ControlState->Control.AmlPredicateStart; break; } /* Predicate was false, terminate this while loop */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[WHILE_OP] termination! Op=%p\n",Op)); /* Pop this control state and free it */ ControlState = AcpiUtPopGenericState (&WalkState->ControlState); AcpiUtDeleteGenericState (ControlState); break; case AML_RETURN_OP: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "[RETURN_OP] Op=%p Arg=%p\n",Op, Op->Common.Value.Arg)); /* * One optional operand -- the return value * It can be either an immediate operand or a result that * has been bubbled up the tree */ if (Op->Common.Value.Arg) { /* Since we have a real Return(), delete any implicit return */ AcpiDsClearImplicitReturn (WalkState); /* Return statement has an immediate operand */ Status = AcpiDsCreateOperands (WalkState, Op->Common.Value.Arg); if (ACPI_FAILURE (Status)) { return (Status); } /* * If value being returned is a Reference (such as * an arg or local), resolve it now because it may * cease to exist at the end of the method. */ Status = AcpiExResolveToValue ( &WalkState->Operands [0], WalkState); if (ACPI_FAILURE (Status)) { return (Status); } /* * Get the return value and save as the last result * value. This is the only place where WalkState->ReturnDesc * is set to anything other than zero! */ WalkState->ReturnDesc = WalkState->Operands[0]; } else if (WalkState->ResultCount) { /* Since we have a real Return(), delete any implicit return */ AcpiDsClearImplicitReturn (WalkState); /* * The return value has come from a previous calculation. * * If value being returned is a Reference (such as * an arg or local), resolve it now because it may * cease to exist at the end of the method. * * Allow references created by the Index operator to return * unchanged. */ if ((ACPI_GET_DESCRIPTOR_TYPE (WalkState->Results->Results.ObjDesc[0]) == ACPI_DESC_TYPE_OPERAND) && ((WalkState->Results->Results.ObjDesc [0])->Common.Type == ACPI_TYPE_LOCAL_REFERENCE) && ((WalkState->Results->Results.ObjDesc [0])->Reference.Class != ACPI_REFCLASS_INDEX)) { Status = AcpiExResolveToValue ( &WalkState->Results->Results.ObjDesc [0], WalkState); if (ACPI_FAILURE (Status)) { return (Status); } } WalkState->ReturnDesc = WalkState->Results->Results.ObjDesc [0]; } else { /* No return operand */ if (WalkState->NumOperands) { AcpiUtRemoveReference (WalkState->Operands [0]); } WalkState->Operands[0] = NULL; WalkState->NumOperands = 0; WalkState->ReturnDesc = NULL; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Completed RETURN_OP State=%p, RetVal=%p\n", WalkState, WalkState->ReturnDesc)); /* End the control method execution right now */ Status = AE_CTRL_TERMINATE; break; case AML_NOOP_OP: /* Just do nothing! */ break; case AML_BREAKPOINT_OP: AcpiDbSignalBreakPoint (WalkState); /* Call to the OSL in case OS wants a piece of the action */ Status = AcpiOsSignal (ACPI_SIGNAL_BREAKPOINT, "Executed AML Breakpoint opcode"); break; case AML_BREAK_OP: case AML_CONTINUE_OP: /* ACPI 2.0 */ /* Pop and delete control states until we find a while */ while (WalkState->ControlState && (WalkState->ControlState->Control.Opcode != AML_WHILE_OP)) { ControlState = AcpiUtPopGenericState (&WalkState->ControlState); AcpiUtDeleteGenericState (ControlState); } /* No while found? */ if (!WalkState->ControlState) { return (AE_AML_NO_WHILE); } /* Was: WalkState->AmlLastWhile = WalkState->ControlState->Control.AmlPredicateStart; */ WalkState->AmlLastWhile = WalkState->ControlState->Control.PackageEnd; /* Return status depending on opcode */ if (Op->Common.AmlOpcode == AML_BREAK_OP) { Status = AE_CTRL_BREAK; } else { Status = AE_CTRL_CONTINUE; } break; default: ACPI_ERROR ((AE_INFO, "Unknown control opcode=0x%X Op=%p", Op->Common.AmlOpcode, Op)); Status = AE_AML_BAD_OPCODE; break; } return (Status); } <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: disable=unused-wildcard-import import re import subprocess import traceback from .stdio import * from .env import * kvm_installed = False qemu_kvm_version = None def is_kvm_installed(): return kvm_installed def get_qemu_kvm_version(): if not kvm_installed: return "" if not qemu_kvm_version: return "<unknown>" return qemu_kvm_version def set_qemu_kvm_version(version): global kvm_installed, qemu_kvm_version kvm_installed = True qemu_kvm_version = version def detect_kvm(): global kvm_installed, qemu_kvm_version if IN_ANY_CI: raw_print("IN_ANY_CI=1, assuming KVM is not usable") return if qemu_kvm_version: raw_print("Assumed qemu-kvm version: {}".format(qemu_kvm_version)) return try: r = subprocess.check_output(['kvm', '--version']).decode('utf-8') kvm_installed = True m = re.search('QEMU.*version +((?:[0-9]+[.])+[0-9]+)', r) if m: qemu_kvm_version = m.groups(0)[0] raw_print("Detected qemu-kvm, version: {}".format(qemu_kvm_version)) else: raw_print("Detected qemu-kvm, but UNKNOWN version. Version string:") raw_print(r) except: raw_print( "\n" "*** WARNING: qemu-kvm not found on the system ***\n" "Running the tests without hardware virtualization is slow and " "inefficient.\n" "Install qemu-kvm on your system for a better performance." "\n" ) def print_timeout_kill_vm_msg(timeout): msg_print( "The VM is alive after the timeout " "of {} seconds. KILLING IT.".format(timeout) ) <file_sep>#!/bin/sh # Symlink the essential directories from /initrd to / dirs="bin etc usr lib" for d in $dirs; do if ! [ -d /initrd/$d ]; then continue fi mkdir -p $d for x in /initrd/$d/*; do if [ -f $x ]; then ln -s $x $d/ elif [ -d $x ]; then dname=$(basename $x) mkdir -p /$d/$dname for y in /initrd/$d/$dname/*; do if [ "$y" = "/initrd/$d/$dname/*" ]; then break fi ln -s $y /$d/$dname/ done fi done done # Create symlinks for all the busybox's applets /initrd/bin/busybox --install -s /bin # Create a symlink for the `env` applet in /usr/bin/env ln -s /initrd/bin/busybox /usr/bin/env # Create symlinks for some devshell cmds cd /usr/bin ln -s devshell runall ln -s devshell selftest # Create a symlink for the debug-panel tools ln -s /initrd/usr/bin/dp tracer ln -s /initrd/usr/bin/dp ps <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include "devshell.h" #define CMD_ENTRY(name, len, enabled) int cmd_##name(int argc, char **argv); #include "cmds_table.h" #undef CMD_ENTRY #define CMD_ENTRY(name, len, enabled) {#name, cmd_ ## name, len, enabled}, static struct test_cmd_entry _cmds_table[] = { #include "cmds_table.h" {NULL, NULL, 0, 0} }; struct test_cmd_entry *cmds_table = _cmds_table; <file_sep>/****************************************************************************** * * Name: actilck.h - OS specific defines, etc. for Tilck * *****************************************************************************/ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #define ACPI_USE_SYSTEM_CLIBRARY #define ACPI_USE_NATIVE_MATH64 #define ACPI_USE_NATIVE_DIVIDE #define ACPI_USE_LOCAL_CACHE #define ACPI_MACHINE_WIDTH NBITS <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/arch/generic_x86/x86_utils.h> NORETURN void panic(const char *fmt, ...) { printk("\n********************* BOOTLOADER PANIC *********************\n"); va_list args; va_start(args, fmt); vprintk(fmt, args); va_end(args); printk("\n"); while (true) { halt(); } } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static int ramfs_getdents(fs_handle h, get_dents_func_cb cb, void *arg) { struct ramfs_handle *rh = h; struct ramfs_inode *inode = rh->inode; int rc = 0; if (inode->type != VFS_DIR) return -ENOTDIR; if ((inode->mode & 0400) != 0400) /* read permission */ return -EACCES; list_for_each_ro_kp(rh->dpos, &inode->entries_list, lnode) { struct vfs_dent64 dent = { .ino = rh->dpos->inode->ino, .type = rh->dpos->inode->type, .name_len = rh->dpos->name_len, .name = rh->dpos->name, }; if ((rc = cb(&dent, arg))) break; } return rc; } <file_sep>/****************************************************************************** * * Module Name: utclib - ACPICA implementations of C library functions * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define ACPI_CLIBRARY #include "acpi.h" #include "accommon.h" /* * This module contains implementations of the standard C library functions * that are required by the ACPICA code at both application level and kernel * level. * * The module is an optional feature that can be used if a local/system * C library is not available. Some operating system kernels may not have * an internal C library. * * In general, these functions are less efficient than an inline or assembly * code implementation. * * These C functions and the associated prototypes are enabled by default * unless the ACPI_USE_SYSTEM_CLIBRARY symbol is defined. This is usually * automatically defined for the ACPICA applications such as iASL and * AcpiExec, so that these user-level applications use the local C library * instead of the functions in this module. */ /******************************************************************************* * * Functions implemented in this module: * * FUNCTION: memcmp * FUNCTION: memcpy * FUNCTION: memset * FUNCTION: strlen * FUNCTION: strcpy * FUNCTION: strncpy * FUNCTION: strcmp * FUNCTION: strchr * FUNCTION: strncmp * FUNCTION: strcat * FUNCTION: strncat * FUNCTION: strstr * FUNCTION: strtoul * FUNCTION: toupper * FUNCTION: tolower * FUNCTION: is* functions * ******************************************************************************/ #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utclib") #ifndef ACPI_USE_SYSTEM_CLIBRARY /* Entire module */ /******************************************************************************* * * FUNCTION: memcmp * * PARAMETERS: Buffer1 - First Buffer * Buffer2 - Second Buffer * Count - Maximum # of bytes to compare * * RETURN: Index where Buffers mismatched, or 0 if Buffers matched * * DESCRIPTION: Compare two Buffers, with a maximum length * ******************************************************************************/ int memcmp ( void *VBuffer1, void *VBuffer2, ACPI_SIZE Count) { char *Buffer1 = (char *) VBuffer1; char *Buffer2 = (char *) VBuffer2; for ( ; Count-- && (*Buffer1 == *Buffer2); Buffer1++, Buffer2++) { } return ((Count == ACPI_SIZE_MAX) ? 0 : ((unsigned char) *Buffer1 - (unsigned char) *Buffer2)); } /******************************************************************************* * * FUNCTION: memmove * * PARAMETERS: Dest - Target of the copy * Src - Source buffer to copy * Count - Number of bytes to copy * * RETURN: Dest * * DESCRIPTION: Copy arbitrary bytes of memory with respect to the overlapping * ******************************************************************************/ void * memmove ( void *Dest, const void *Src, ACPI_SIZE Count) { char *New = (char *) Dest; char *Old = (char *) Src; if (Old > New) { /* Copy from the beginning */ while (Count) { *New = *Old; New++; Old++; Count--; } } else if (Old < New) { /* Copy from the end */ New = New + Count - 1; Old = Old + Count - 1; while (Count) { *New = *Old; New--; Old--; Count--; } } return (Dest); } /******************************************************************************* * * FUNCTION: memcpy * * PARAMETERS: Dest - Target of the copy * Src - Source buffer to copy * Count - Number of bytes to copy * * RETURN: Dest * * DESCRIPTION: Copy arbitrary bytes of memory * ******************************************************************************/ void * memcpy ( void *Dest, const void *Src, ACPI_SIZE Count) { char *New = (char *) Dest; char *Old = (char *) Src; while (Count) { *New = *Old; New++; Old++; Count--; } return (Dest); } /******************************************************************************* * * FUNCTION: memset * * PARAMETERS: Dest - Buffer to set * Value - Value to set each byte of memory * Count - Number of bytes to set * * RETURN: Dest * * DESCRIPTION: Initialize a buffer to a known value. * ******************************************************************************/ void * memset ( void *Dest, int Value, ACPI_SIZE Count) { char *New = (char *) Dest; while (Count) { *New = (char) Value; New++; Count--; } return (Dest); } /******************************************************************************* * * FUNCTION: strlen * * PARAMETERS: String - Null terminated string * * RETURN: Length * * DESCRIPTION: Returns the length of the input string * ******************************************************************************/ ACPI_SIZE strlen ( const char *String) { UINT32 Length = 0; /* Count the string until a null is encountered */ while (*String) { Length++; String++; } return (Length); } /******************************************************************************* * * FUNCTION: strpbrk * * PARAMETERS: String - Null terminated string * Delimiters - Delimiters to match * * RETURN: The first occurrence in the string of any of the bytes in the * delimiters * * DESCRIPTION: Search a string for any of a set of the delimiters * ******************************************************************************/ char * strpbrk ( const char *String, const char *Delimiters) { const char *Delimiter; for ( ; *String != '\0'; ++String) { for (Delimiter = Delimiters; *Delimiter != '\0'; Delimiter++) { if (*String == *Delimiter) { return (ACPI_CAST_PTR (char, String)); } } } return (NULL); } /******************************************************************************* * * FUNCTION: strtok * * PARAMETERS: String - Null terminated string * Delimiters - Delimiters to match * * RETURN: Pointer to the next token * * DESCRIPTION: Split string into tokens * ******************************************************************************/ char* strtok ( char *String, const char *Delimiters) { char *Begin = String; static char *SavedPtr; if (Begin == NULL) { if (SavedPtr == NULL) { return (NULL); } Begin = SavedPtr; } SavedPtr = strpbrk (Begin, Delimiters); while (SavedPtr == Begin) { *Begin++ = '\0'; SavedPtr = strpbrk (Begin, Delimiters); } if (SavedPtr) { *SavedPtr++ = '\0'; return (Begin); } else { return (NULL); } } /******************************************************************************* * * FUNCTION: strcpy * * PARAMETERS: DstString - Target of the copy * SrcString - The source string to copy * * RETURN: DstString * * DESCRIPTION: Copy a null terminated string * ******************************************************************************/ char * strcpy ( char *DstString, const char *SrcString) { char *String = DstString; /* Move bytes brute force */ while (*SrcString) { *String = *SrcString; String++; SrcString++; } /* Null terminate */ *String = 0; return (DstString); } /******************************************************************************* * * FUNCTION: strncpy * * PARAMETERS: DstString - Target of the copy * SrcString - The source string to copy * Count - Maximum # of bytes to copy * * RETURN: DstString * * DESCRIPTION: Copy a null terminated string, with a maximum length * ******************************************************************************/ char * strncpy ( char *DstString, const char *SrcString, ACPI_SIZE Count) { char *String = DstString; /* Copy the string */ for (String = DstString; Count && (Count--, (*String++ = *SrcString++)); ) {;} /* Pad with nulls if necessary */ while (Count--) { *String = 0; String++; } /* Return original pointer */ return (DstString); } /******************************************************************************* * * FUNCTION: strcmp * * PARAMETERS: String1 - First string * String2 - Second string * * RETURN: Index where strings mismatched, or 0 if strings matched * * DESCRIPTION: Compare two null terminated strings * ******************************************************************************/ int strcmp ( const char *String1, const char *String2) { for ( ; (*String1 == *String2); String2++) { if (!*String1++) { return (0); } } return ((unsigned char) *String1 - (unsigned char) *String2); } /******************************************************************************* * * FUNCTION: strchr * * PARAMETERS: String - Search string * ch - character to search for * * RETURN: Ptr to char or NULL if not found * * DESCRIPTION: Search a string for a character * ******************************************************************************/ char * strchr ( const char *String, int ch) { for ( ; (*String); String++) { if ((*String) == (char) ch) { return ((char *) String); } } return (NULL); } /******************************************************************************* * * FUNCTION: strncmp * * PARAMETERS: String1 - First string * String2 - Second string * Count - Maximum # of bytes to compare * * RETURN: Index where strings mismatched, or 0 if strings matched * * DESCRIPTION: Compare two null terminated strings, with a maximum length * ******************************************************************************/ int strncmp ( const char *String1, const char *String2, ACPI_SIZE Count) { for ( ; Count-- && (*String1 == *String2); String2++) { if (!*String1++) { return (0); } } return ((Count == ACPI_SIZE_MAX) ? 0 : ((unsigned char) *String1 - (unsigned char) *String2)); } /******************************************************************************* * * FUNCTION: strcat * * PARAMETERS: DstString - Target of the copy * SrcString - The source string to copy * * RETURN: DstString * * DESCRIPTION: Append a null terminated string to a null terminated string * ******************************************************************************/ char * strcat ( char *DstString, const char *SrcString) { char *String; /* Find end of the destination string */ for (String = DstString; *String++; ) { ; } /* Concatenate the string */ for (--String; (*String++ = *SrcString++); ) { ; } return (DstString); } /******************************************************************************* * * FUNCTION: strncat * * PARAMETERS: DstString - Target of the copy * SrcString - The source string to copy * Count - Maximum # of bytes to copy * * RETURN: DstString * * DESCRIPTION: Append a null terminated string to a null terminated string, * with a maximum count. * ******************************************************************************/ char * strncat ( char *DstString, const char *SrcString, ACPI_SIZE Count) { char *String; if (Count) { /* Find end of the destination string */ for (String = DstString; *String++; ) { ; } /* Concatenate the string */ for (--String; (*String++ = *SrcString++) && --Count; ) { ; } /* Null terminate if necessary */ if (!Count) { *String = 0; } } return (DstString); } /******************************************************************************* * * FUNCTION: strstr * * PARAMETERS: String1 - Target string * String2 - Substring to search for * * RETURN: Where substring match starts, Null if no match found * * DESCRIPTION: Checks if String2 occurs in String1. This is not really a * full implementation of strstr, only sufficient for command * matching * ******************************************************************************/ char * strstr ( char *String1, char *String2) { ACPI_SIZE Length; Length = strlen (String2); if (!Length) { return (String1); } while (strlen (String1) >= Length) { if (memcmp (String1, String2, Length) == 0) { return (String1); } String1++; } return (NULL); } /******************************************************************************* * * FUNCTION: strtoul * * PARAMETERS: String - Null terminated string * Terminator - Where a pointer to the terminating byte is * returned * Base - Radix of the string * * RETURN: Converted value * * DESCRIPTION: Convert a string into a 32-bit unsigned value. * Note: use strtoul64 for 64-bit integers. * ******************************************************************************/ UINT32 strtoul ( const char *String, char **Terminator, UINT32 Base) { UINT32 converted = 0; UINT32 index; UINT32 sign; const char *StringStart; UINT32 ReturnValue = 0; ACPI_STATUS Status = AE_OK; /* * Save the value of the pointer to the buffer's first * character, save the current errno value, and then * skip over any white space in the buffer: */ StringStart = String; while (isspace (*String) || *String == '\t') { ++String; } /* * The buffer may contain an optional plus or minus sign. * If it does, then skip over it but remember what is was: */ if (*String == '-') { sign = ACPI_SIGN_NEGATIVE; ++String; } else if (*String == '+') { ++String; sign = ACPI_SIGN_POSITIVE; } else { sign = ACPI_SIGN_POSITIVE; } /* * If the input parameter Base is zero, then we need to * determine if it is octal, decimal, or hexadecimal: */ if (Base == 0) { if (*String == '0') { if (tolower (*(++String)) == 'x') { Base = 16; ++String; } else { Base = 8; } } else { Base = 10; } } else if (Base < 2 || Base > 36) { /* * The specified Base parameter is not in the domain of * this function: */ goto done; } /* * For octal and hexadecimal bases, skip over the leading * 0 or 0x, if they are present. */ if (Base == 8 && *String == '0') { String++; } if (Base == 16 && *String == '0' && tolower (*(++String)) == 'x') { String++; } /* * Main loop: convert the string to an unsigned long: */ while (*String) { if (isdigit (*String)) { index = (UINT32) ((UINT8) *String - '0'); } else { index = (UINT32) toupper (*String); if (isupper (index)) { index = index - 'A' + 10; } else { goto done; } } if (index >= Base) { goto done; } /* * Check to see if value is out of range: */ if (ReturnValue > ((ACPI_UINT32_MAX - (UINT32) index) / (UINT32) Base)) { Status = AE_ERROR; ReturnValue = 0; /* reset */ } else { ReturnValue *= Base; ReturnValue += index; converted = 1; } ++String; } done: /* * If appropriate, update the caller's pointer to the next * unconverted character in the buffer. */ if (Terminator) { if (converted == 0 && ReturnValue == 0 && String != NULL) { *Terminator = (char *) StringStart; } else { *Terminator = (char *) String; } } if (Status == AE_ERROR) { ReturnValue = ACPI_UINT32_MAX; } /* * If a minus sign was present, then "the conversion is negated": */ if (sign == ACPI_SIGN_NEGATIVE) { ReturnValue = (ACPI_UINT32_MAX - ReturnValue) + 1; } return (ReturnValue); } /******************************************************************************* * * FUNCTION: toupper * * PARAMETERS: c - Character to convert * * RETURN: Converted character as an int * * DESCRIPTION: Convert character to uppercase * ******************************************************************************/ int toupper ( int c) { return (islower(c) ? ((c)-0x20) : (c)); } /******************************************************************************* * * FUNCTION: tolower * * PARAMETERS: c - Character to convert * * RETURN: Converted character as an int * * DESCRIPTION: Convert character to lowercase * ******************************************************************************/ int tolower ( int c) { return (isupper(c) ? ((c)+0x20) : (c)); } /******************************************************************************* * * FUNCTION: is* function array * * DESCRIPTION: is* functions use the ctype table below * ******************************************************************************/ const UINT8 AcpiGbl_Ctypes[257] = { _ACPI_CN, /* 0x00 0 NUL */ _ACPI_CN, /* 0x01 1 SOH */ _ACPI_CN, /* 0x02 2 STX */ _ACPI_CN, /* 0x03 3 ETX */ _ACPI_CN, /* 0x04 4 EOT */ _ACPI_CN, /* 0x05 5 ENQ */ _ACPI_CN, /* 0x06 6 ACK */ _ACPI_CN, /* 0x07 7 BEL */ _ACPI_CN, /* 0x08 8 BS */ _ACPI_CN|_ACPI_SP, /* 0x09 9 TAB */ _ACPI_CN|_ACPI_SP, /* 0x0A 10 LF */ _ACPI_CN|_ACPI_SP, /* 0x0B 11 VT */ _ACPI_CN|_ACPI_SP, /* 0x0C 12 FF */ _ACPI_CN|_ACPI_SP, /* 0x0D 13 CR */ _ACPI_CN, /* 0x0E 14 SO */ _ACPI_CN, /* 0x0F 15 SI */ _ACPI_CN, /* 0x10 16 DLE */ _ACPI_CN, /* 0x11 17 DC1 */ _ACPI_CN, /* 0x12 18 DC2 */ _ACPI_CN, /* 0x13 19 DC3 */ _ACPI_CN, /* 0x14 20 DC4 */ _ACPI_CN, /* 0x15 21 NAK */ _ACPI_CN, /* 0x16 22 SYN */ _ACPI_CN, /* 0x17 23 ETB */ _ACPI_CN, /* 0x18 24 CAN */ _ACPI_CN, /* 0x19 25 EM */ _ACPI_CN, /* 0x1A 26 SUB */ _ACPI_CN, /* 0x1B 27 ESC */ _ACPI_CN, /* 0x1C 28 FS */ _ACPI_CN, /* 0x1D 29 GS */ _ACPI_CN, /* 0x1E 30 RS */ _ACPI_CN, /* 0x1F 31 US */ _ACPI_XS|_ACPI_SP, /* 0x20 32 ' ' */ _ACPI_PU, /* 0x21 33 '!' */ _ACPI_PU, /* 0x22 34 '"' */ _ACPI_PU, /* 0x23 35 '#' */ _ACPI_PU, /* 0x24 36 '$' */ _ACPI_PU, /* 0x25 37 '%' */ _ACPI_PU, /* 0x26 38 '&' */ _ACPI_PU, /* 0x27 39 ''' */ _ACPI_PU, /* 0x28 40 '(' */ _ACPI_PU, /* 0x29 41 ')' */ _ACPI_PU, /* 0x2A 42 '*' */ _ACPI_PU, /* 0x2B 43 '+' */ _ACPI_PU, /* 0x2C 44 ',' */ _ACPI_PU, /* 0x2D 45 '-' */ _ACPI_PU, /* 0x2E 46 '.' */ _ACPI_PU, /* 0x2F 47 '/' */ _ACPI_XD|_ACPI_DI, /* 0x30 48 '0' */ _ACPI_XD|_ACPI_DI, /* 0x31 49 '1' */ _ACPI_XD|_ACPI_DI, /* 0x32 50 '2' */ _ACPI_XD|_ACPI_DI, /* 0x33 51 '3' */ _ACPI_XD|_ACPI_DI, /* 0x34 52 '4' */ _ACPI_XD|_ACPI_DI, /* 0x35 53 '5' */ _ACPI_XD|_ACPI_DI, /* 0x36 54 '6' */ _ACPI_XD|_ACPI_DI, /* 0x37 55 '7' */ _ACPI_XD|_ACPI_DI, /* 0x38 56 '8' */ _ACPI_XD|_ACPI_DI, /* 0x39 57 '9' */ _ACPI_PU, /* 0x3A 58 ':' */ _ACPI_PU, /* 0x3B 59 ';' */ _ACPI_PU, /* 0x3C 60 '<' */ _ACPI_PU, /* 0x3D 61 '=' */ _ACPI_PU, /* 0x3E 62 '>' */ _ACPI_PU, /* 0x3F 63 '?' */ _ACPI_PU, /* 0x40 64 '@' */ _ACPI_XD|_ACPI_UP, /* 0x41 65 'A' */ _ACPI_XD|_ACPI_UP, /* 0x42 66 'B' */ _ACPI_XD|_ACPI_UP, /* 0x43 67 'C' */ _ACPI_XD|_ACPI_UP, /* 0x44 68 'D' */ _ACPI_XD|_ACPI_UP, /* 0x45 69 'E' */ _ACPI_XD|_ACPI_UP, /* 0x46 70 'F' */ _ACPI_UP, /* 0x47 71 'G' */ _ACPI_UP, /* 0x48 72 'H' */ _ACPI_UP, /* 0x49 73 'I' */ _ACPI_UP, /* 0x4A 74 'J' */ _ACPI_UP, /* 0x4B 75 'K' */ _ACPI_UP, /* 0x4C 76 'L' */ _ACPI_UP, /* 0x4D 77 'M' */ _ACPI_UP, /* 0x4E 78 'N' */ _ACPI_UP, /* 0x4F 79 'O' */ _ACPI_UP, /* 0x50 80 'P' */ _ACPI_UP, /* 0x51 81 'Q' */ _ACPI_UP, /* 0x52 82 'R' */ _ACPI_UP, /* 0x53 83 'S' */ _ACPI_UP, /* 0x54 84 'T' */ _ACPI_UP, /* 0x55 85 'U' */ _ACPI_UP, /* 0x56 86 'V' */ _ACPI_UP, /* 0x57 87 'W' */ _ACPI_UP, /* 0x58 88 'X' */ _ACPI_UP, /* 0x59 89 'Y' */ _ACPI_UP, /* 0x5A 90 'Z' */ _ACPI_PU, /* 0x5B 91 '[' */ _ACPI_PU, /* 0x5C 92 '\' */ _ACPI_PU, /* 0x5D 93 ']' */ _ACPI_PU, /* 0x5E 94 '^' */ _ACPI_PU, /* 0x5F 95 '_' */ _ACPI_PU, /* 0x60 96 '`' */ _ACPI_XD|_ACPI_LO, /* 0x61 97 'a' */ _ACPI_XD|_ACPI_LO, /* 0x62 98 'b' */ _ACPI_XD|_ACPI_LO, /* 0x63 99 'c' */ _ACPI_XD|_ACPI_LO, /* 0x64 100 'd' */ _ACPI_XD|_ACPI_LO, /* 0x65 101 'e' */ _ACPI_XD|_ACPI_LO, /* 0x66 102 'f' */ _ACPI_LO, /* 0x67 103 'g' */ _ACPI_LO, /* 0x68 104 'h' */ _ACPI_LO, /* 0x69 105 'i' */ _ACPI_LO, /* 0x6A 106 'j' */ _ACPI_LO, /* 0x6B 107 'k' */ _ACPI_LO, /* 0x6C 108 'l' */ _ACPI_LO, /* 0x6D 109 'm' */ _ACPI_LO, /* 0x6E 110 'n' */ _ACPI_LO, /* 0x6F 111 'o' */ _ACPI_LO, /* 0x70 112 'p' */ _ACPI_LO, /* 0x71 113 'q' */ _ACPI_LO, /* 0x72 114 'r' */ _ACPI_LO, /* 0x73 115 's' */ _ACPI_LO, /* 0x74 116 't' */ _ACPI_LO, /* 0x75 117 'u' */ _ACPI_LO, /* 0x76 118 'v' */ _ACPI_LO, /* 0x77 119 'w' */ _ACPI_LO, /* 0x78 120 'x' */ _ACPI_LO, /* 0x79 121 'y' */ _ACPI_LO, /* 0x7A 122 'z' */ _ACPI_PU, /* 0x7B 123 '{' */ _ACPI_PU, /* 0x7C 124 '|' */ _ACPI_PU, /* 0x7D 125 '}' */ _ACPI_PU, /* 0x7E 126 '~' */ _ACPI_CN, /* 0x7F 127 DEL */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x80 to 0x8F */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x90 to 0x9F */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xA0 to 0xAF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xB0 to 0xBF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xC0 to 0xCF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xD0 to 0xDF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xE0 to 0xEF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xF0 to 0xFF */ 0 /* 0x100 */ }; #endif /* ACPI_USE_SYSTEM_CLIBRARY */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once #include <tilck_gen_headers/config_global.h> /* ------ Value-based config variables -------- */ #define USER_STACK_PAGES @USER_STACK_PAGES@ /* --------- Boolean config variables --------- */ #cmakedefine01 FORK_NO_COW #cmakedefine01 MMAP_NO_COW /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are many dervied constants and convenience constants like * COMPILER_NAME along with some pseudo-constants like USERMODE_VADDR_END not * designed to be easily changed because of the code makes assumptions about * them. Because of that, those constants are hard-coded and not available as * CMake variables. With time, some of those constants get "promoted" and moved * in CMake, others remain here. See the comments and think about the potential * implications before promoting a hard-coded constant to a configurable CMake * variable. */ #define USER_VDSO_VADDR (LINEAR_MAPPING_END) #define USERMODE_VADDR_END (KERNEL_BASE_VA) /* biggest user vaddr + 1 */ #define MAX_BRK (0x40000000) /* +1 GB (virtual memory) */ #define USER_MMAP_BEGIN MAX_BRK /* +1 GB (virtual memory) */ #define USER_MMAP_MIN_SZ (16 * MB) #define USER_MMAP_MAX_SZ (1024 * MB) #define USERMODE_STACK_ALIGN 16u #define USERMODE_STACK_MAX \ ((USERMODE_VADDR_END - 1) & ALIGNED_MASK(USERMODE_STACK_ALIGN)) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/process.h> #include "idt_int.h" void handle_gpf(regs_t *r); void handle_ill(regs_t *r); void handle_div0(regs_t *r); void handle_cpf(regs_t *r); extern void (*fault_entry_points[32])(void); static struct idt_entry idt[256]; void load_idt(struct idt_entry *entries, u16 entries_count) { struct { u16 size_minus_one; struct idt_entry *idt_addr; } PACKED idt_ptr = { sizeof(struct idt_entry) * entries_count - 1, entries }; asmVolatile("lidt (%0)" : /* no output */ : "q" (&idt_ptr) : "memory"); } void idt_set_entry(u8 num, void *handler, u16 selector, u8 flags) { const u32 base = (u32) handler; /* The interrupt routine address (offset in the code segment) */ idt[num].offset_low = LO_BITS(base, 16, u16); idt[num].offset_high = LO_BITS(base >> 16, 16, u16); /* Selector of the code segment to use for the 'offset' address */ idt[num].selector = selector; idt[num].always0 = 0; idt[num].flags = flags; } static void handle_debugbreak(regs_t *r) { /* * Do nothing, literally. The purpose of this way of handling `int 3` is to * allow during development to easily put a breakpoint in user-space code and * from GDB (using remote debugging) to put a HW breakpoint here. * * On Linux, the behavior of `int 3` is quite different, but that's fine. * This interrupt is anyway used only for debugging purposes. In the future, * it is absolutely possible that Tilck will handle it in a different way. * For the moment, the kernel offers no debugging features of userspace * programs (= no such thing as ptrace). */ asmVolatile("nop"); } void init_cpu_exception_handling(void) { /* Set the entries for the x86 faults (exceptions) */ for (u8 i = 0; i < 32; i++) { idt_set_entry(i, fault_entry_points[i], X86_KERNEL_CODE_SEL, IDT_FLAG_PRESENT | IDT_FLAG_INT_GATE | IDT_FLAG_DPL0); } /* * Set a special entry for the breakpoint FAULT, allowing `int 3` to work * from userspace, without triggering a GPF, in the same way int 0x80 is * allowed by init_syscall_interfaces(). */ idt_set_entry(FAULT_BREAKPOINT, fault_entry_points[FAULT_BREAKPOINT], X86_KERNEL_CODE_SEL, IDT_FLAG_PRESENT | IDT_FLAG_INT_GATE | IDT_FLAG_DPL3); load_idt(idt, ARRAY_SIZE(idt)); set_fault_handler(FAULT_GENERAL_PROTECTION, handle_gpf); set_fault_handler(FAULT_INVALID_OPCODE, handle_ill); set_fault_handler(FAULT_DIVISION_BY_ZERO, handle_div0); set_fault_handler(FAULT_COPROC_FAULT, handle_cpf); set_fault_handler(FAULT_BREAKPOINT, handle_debugbreak); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/atomics.h> #include <tilck/kernel/modules.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/sched.h> #include <tilck/mods/serial.h> /* NOTE: hw-specific stuff in generic code. TODO: fix that. */ struct serial_device { const char *name; u16 ioport; struct tty *tty; ATOMIC(int) jobs_cnt; struct worker_thread *wth; }; struct serial_device legacy_serial_ports[] = { { .name = "COM1", .ioport = COM1, }, { .name = "COM2", .ioport = COM2, }, { .name = "COM3", .ioport = COM3, }, { .name = "COM4", .ioport = COM4, }, }; static void ser_bh_handler(void *ctx) { struct serial_device *const dev = ctx; struct tty *const t = dev->tty; const u16 p = dev->ioport; char c; while (serial_read_ready(p)) { c = serial_read(p); tty_send_keyevent(t, make_key_event(0, c, true), true); } dev->jobs_cnt--; } static enum irq_action serial_con_irq_handler(void *ctx) { struct serial_device *const dev = ctx; if (!serial_read_ready(dev->ioport)) return IRQ_NOT_HANDLED; /* Not an IRQ from this "device" [irq sharing] */ if (dev->jobs_cnt >= 2) return IRQ_HANDLED; if (UNLIKELY(in_panic())) { /* Special panic-only trick: see the comment in keyboard_irq_handler() */ ulong val; disable_interrupts(&val); { dev->jobs_cnt++; ser_bh_handler(dev); } enable_interrupts(&val); return IRQ_HANDLED; } if (!wth_enqueue_on(dev->wth, &ser_bh_handler, dev)) { printk("Serial: WARNING: hit job queue limit\n"); return IRQ_HANDLED; } dev->jobs_cnt++; return IRQ_HANDLED; } void early_init_serial_ports(void) { init_serial_port(COM1); init_serial_port(COM2); init_serial_port(COM3); init_serial_port(COM4); } DEFINE_IRQ_HANDLER_NODE(com1, serial_con_irq_handler, &legacy_serial_ports[0]); DEFINE_IRQ_HANDLER_NODE(com2, serial_con_irq_handler, &legacy_serial_ports[1]); DEFINE_IRQ_HANDLER_NODE(com3, serial_con_irq_handler, &legacy_serial_ports[2]); DEFINE_IRQ_HANDLER_NODE(com4, serial_con_irq_handler, &legacy_serial_ports[3]); static void init_serial_comm(void) { struct worker_thread *wth; disable_preemption(); { wth = wth_create_thread("serial", 1, WTH_SERIAL_QUEUE_SIZE); if (!wth) panic("Serial: Unable to create a worker thread for IRQs"); } enable_preemption(); for (int i = 0; i < ARRAY_SIZE(legacy_serial_ports); i++) { struct serial_device *dev = &legacy_serial_ports[i]; dev->tty = get_serial_tty((int)i); dev->wth = wth; } irq_install_handler(X86_PC_COM1_COM3_IRQ, &com1); irq_install_handler(X86_PC_COM1_COM3_IRQ, &com3); irq_install_handler(X86_PC_COM2_COM4_IRQ, &com2); irq_install_handler(X86_PC_COM2_COM4_IRQ, &com4); } static struct module serial_module = { .name = "serial", .priority = MOD_serial_prio, .init = &init_serial_comm, }; REGISTER_MODULE(&serial_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #define SB16_DBG_ENABLED 0 #define DSP_MIXER 0x224 #define DSP_MIXER_DATA 0x225 #define DSP_RESET 0x226 #define DSP_READ 0x22A #define DSP_WRITE 0x22C #define DSP_READ_STATUS 0x22E #define DSP_8_BIT_ACK DSP_READ_STATUS #define DSP_16_BIT_ACK 0x22F #define DSP_16_BIT_PROG 0xB0 #define DSP_8_BIT_PROG 0xC0 #define DSP_AUTO_INIT 0x06 #define DSP_PLAY 0x00 #define DSP_RECORD 0x08 #define DSP_MONO 0x00 #define DSP_STEREO 0x20 #define DSP_UNSIGNED 0x00 #define DSP_SIGNED 0x10 #define DSP_SET_SAMPLE_R 0x41 #define DSP_ENABLE_SPKR 0xD1 #define DSP_DISABLE_SPKR 0xD3 #define DSP_GET_VER 0xE1 #define DSP_8_BIT_PAUSE 0xD0 #define DSP_8_BIT_CONT 0xD4 #define DSP_16_BIT_PAUSE 0xD5 #define DSP_16_BIT_CONT 0xD6 struct sb16_info { u8 *buf; ulong buf_paddr; u8 irq; u8 ver_major; u8 ver_minor; }; extern struct sb16_info sb16_info; u8 sb16_get_irq(void); int sb16_detect_dsp_hw_and_reset(void); int sb16_check_version(void); void sb16_program_dma(u8 bits, u32 buf_sz); void sb16_program(struct tilck_sound_params *params, u32 buf_sz); void sb16_generate_test_sound(void); static inline void sb16_irq_ack(void) { extern u16 sb16_curr_ack_cmd; inb(sb16_curr_ack_cmd); } static inline void sb16_pause(void) { extern u8 sb16_curr_pause_cmd; outb(DSP_WRITE, sb16_curr_pause_cmd); } static inline void sb16_continue(void) { extern u8 sb16_curr_cont_cmd; outb(DSP_WRITE, sb16_curr_cont_cmd); } #if SB16_DBG_ENABLED #define SB16_DBG(...) printk(__VA_ARGS__) #else #define SB16_DBG(...) { } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #define STACK_VAR (h->alloc_stack) #define KMALLOC_ALLOC_STACK_SIZE 32 #include <tilck/common/norec.h> #include <tilck/common/atomics.h> struct kmalloc_heap { ulong vaddr; size_t size; size_t mem_allocated; void *metadata_nodes; int region; ATOMIC(bool) in_use; size_t min_block_size; size_t alloc_block_size; virtual_alloc_and_map_func valloc_and_map; virtual_free_and_unmap_func vfree_and_unmap; /* -- pre-calculated values -- */ size_t heap_data_size_log2; size_t alloc_block_size_log2; size_t metadata_size; ulong heap_last_byte; /* addr + size - 1 */ /* -- */ bool linear_mapping; bool dma; /* * Explicit stack used by per_heap_kmalloc() * * NOTE: this stack is per-heap because some kmalloc heaps might use * kmalloc itself as valloc/vfree funcs [see process_mm.c]. In such cases, * is unsafe to keep just one global alloc_stack. */ struct explicit_stack_elem2 alloc_stack[KMALLOC_ALLOC_STACK_SIZE]; }; void *kmalloc_get_first_heap(size_t *size); void internal_kmalloc_split_block(struct kmalloc_heap *h, void *const vaddr, const size_t block_size, const size_t leaf_node_size); size_t internal_kmalloc_coalesce_block(struct kmalloc_heap *h, void *const vaddr, const size_t block_size); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> struct datetime { union { struct { u8 sec; /* Seconds (0-60) */ u8 min; /* Minutes (0-59) */ u8 hour; /* Hours (0-23) */ u8 weekday; /* Weekday (0-6, Sunday = 0) */ u8 day; /* Month day (1 - 31) */ u8 month; /* Month (1 - 12) */ u16 year; /* Absolute year (e.g. 1542, 2019, 2059, ...) */ }; u64 raw; }; }; int timestamp_to_datetime(int64_t t, struct datetime *d); int64_t datetime_to_timestamp(struct datetime d); <file_sep>#!/bin/sh exec ar "$@" <file_sep>#!/bin/sh exec strip "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef CMDLINE_INCL_HACK #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_kb8042.h> #include <tilck_gen_headers/config_debug.h> #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/test/cmdline.h> const char *cmd_args[MAX_CMD_ARGS] = { "/initrd/bin/init", [1 ... 15] = NULL }; void (*self_test_to_run)(void); typedef const char *wordstr; typedef void (*kopt_handler)(const char *arg); static char args_buf[PAGE_SIZE]; static size_t args_buf_used; static size_t last_custom_cmd_n; enum kopt_type { KOPT_TYPE_bool, KOPT_TYPE_long, KOPT_TYPE_ulong, KOPT_TYPE_wordstr, }; struct kopt { const char *name; const char *alias; enum kopt_type type; void *data; }; static void kopt_handle_bool(bool *var, const char *arg) { if (*arg == '-') *var = true; else if (!strcmp(arg, "0")) *var = false; else if (!strcmp(arg, "1")) *var = true; else NOT_REACHED(); } static void kopt_handle_long(long *var, const char *arg) { int err = 0; long res; res = tilck_strtol(arg, NULL, 10, &err); if (err) { printk("WARNING: failed to parse integer argument '%s'\n", arg); return; } *var = res; } static void kopt_handle_ulong(ulong *var, const char *arg) { int base = 10, err = 0; ulong res; if (arg[0] == '0' && arg[1] == 'x') { base = 16; arg += 2; } res = tilck_strtoul(arg, NULL, base, &err); if (err) { printk("WARNING: failed to parse unsigned argument '%s'\n", arg); return; } *var = res; } static void kopt_handle_wordstr(const char **var, const char *arg) { size_t len = strlen(arg); if (args_buf_used + len + 1 >= PAGE_SIZE) { printk("WARNING: no buffer space for argument: '%s'\n", arg); return; } memcpy(args_buf + args_buf_used, arg, len + 1); *var = args_buf + args_buf_used; args_buf_used += len + 1; } #define CMDLINE_INCL_HACK #define ALL_KOPTS_BEGIN #define ALL_KOPTS_END #define DEFINE_KOPT(name, alias, type, default) \ type kopt_##name = default; #include "cmdline.c" #undef ALL_KOPTS_BEGIN #undef ALL_KOPTS_END #undef CMDLINE_INCL_HACK #undef DEFINE_KOPT #define ALL_KOPTS_BEGIN static const struct kopt all_kopts[] = { #define ALL_KOPTS_END }; #define DEFINE_KOPT(name, alias, type, default) \ { #name, #alias, KOPT_TYPE_##type, &kopt_##name }, #endif // #ifndef CMDLINE_INCL_HACK /* * HACK: the following piece of code will be emitted twice, because this file * includes itself. The first time CMDLINE_INCL_HACK will be defined (see the * include "cmdline.c" above: this will make DEFINE_KOPT() generate global vars * and funcs. The second time (here), CMDLINE_INCL_HACK won't be defined, and * DEFINE_KOPT() will generate entries in the `all_kopts` array. * * It's worth remarking that however dirty, this trick is well-known and used * multiple times in the Linux kernel as well. */ ALL_KOPTS_BEGIN /* name ,alias, type, default */ DEFINE_KOPT(ttys , , long, TTY_COUNT) DEFINE_KOPT(selftest , , wordstr, NULL) DEFINE_KOPT(sched_alive_thread, sat , bool, false) DEFINE_KOPT(sercon , , bool, !MOD_console) DEFINE_KOPT(noacpi , , bool, false) DEFINE_KOPT(fb_no_opt , , bool, false) DEFINE_KOPT(fb_no_wc , , bool, false) DEFINE_KOPT(no_fpu_memcpy , , bool, false) DEFINE_KOPT(panic_kb , pk , bool, false) DEFINE_KOPT(panic_nobt , nobt, bool, !PANIC_SHOW_STACKTRACE) DEFINE_KOPT(panic_regs , pr , bool, PANIC_SHOW_REGS) DEFINE_KOPT(panic_mmap , pm , bool, false) DEFINE_KOPT(big_scroll_buf , bb , bool, TERM_BIG_SCROLL_BUF) DEFINE_KOPT(ps2_log , plg , bool, PS2_VERBOSE_DEBUG_LOG) DEFINE_KOPT(ps2_selftest , pse , bool, PS2_DO_SELFTEST) ALL_KOPTS_END #ifndef CMDLINE_INCL_HACK static void handle_cmdline_arg(const char *arg) { size_t arg_len = strlen(arg); if (last_custom_cmd_n == ARRAY_SIZE(cmd_args) - 1) panic("Too many arguments"); if (args_buf_used + arg_len + 1 >= sizeof(args_buf)) panic("Args too long"); memcpy(args_buf + args_buf_used, arg, arg_len + 1); cmd_args[last_custom_cmd_n++] = args_buf + args_buf_used; args_buf_used += arg_len + 1; } static void handle_selftest_kopt(void) { char buf[MAX_CMD_ARG_LEN + 1] = SELFTEST_PREFIX; ulong addr; if (!kopt_selftest) return; strcat(buf, kopt_selftest); buf[sizeof(buf) - 1] = 0; /* Always truncate the buffer */ addr = find_addr_of_symbol(buf); if (!addr) { printk("*******************************************************\n"); printk("ERROR: self test function '%s' not found.\n", buf); printk("*******************************************************\n"); return; } printk("*** Run selftest: '%s' ***\n", kopt_selftest); self_test_to_run = (void *) addr; } enum arg_state { INITIAL_STATE, WAITING_FOR_VALUE, FINAL_STATE_CMDLINE, }; struct arg_parse_ctx { enum arg_state state; const struct kopt *last_opt; }; static void handle_arg_generic(const struct kopt *opt, const char *arg) { switch (opt->type) { case KOPT_TYPE_bool: kopt_handle_bool(opt->data, arg); break; case KOPT_TYPE_long: kopt_handle_long(opt->data, arg); break; case KOPT_TYPE_ulong: kopt_handle_ulong(opt->data, arg); break; case KOPT_TYPE_wordstr: kopt_handle_wordstr(opt->data, arg); break; default: NOT_REACHED(); } } STATIC void use_kernel_arg(struct arg_parse_ctx *ctx, int arg_num, const char *arg) { const struct kopt *opt; u32 i; switch (ctx->state) { case FINAL_STATE_CMDLINE: handle_cmdline_arg(arg); break; case WAITING_FOR_VALUE: handle_arg_generic(ctx->last_opt, arg); ctx->state = INITIAL_STATE; break; case INITIAL_STATE: { if (!strcmp(arg, "0") || !strcmp(arg, "1")) { if (ctx->last_opt && ctx->last_opt->type == KOPT_TYPE_bool) { handle_arg_generic(ctx->last_opt, arg); break; } } if (!strcmp(arg, "-cmd") || !strcmp(arg, "--")) { ctx->state = FINAL_STATE_CMDLINE; break; } for (i = 0; i < ARRAY_SIZE(all_kopts); i++) { if (*arg != '-') continue; if (!strcmp(arg+1, all_kopts[i].name)) break; if (all_kopts[i].alias[0] != '\0') if (!strcmp(arg+1, all_kopts[i].alias)) break; } if (i == ARRAY_SIZE(all_kopts)) { if (arg_num > 0 || *arg == '-') printk("WARNING: Unrecognized cmdline option '%s'\n", arg); break; } opt = &all_kopts[i]; ctx->last_opt = opt; if (opt->type == KOPT_TYPE_bool) { handle_arg_generic(opt, arg); } else { ctx->state = WAITING_FOR_VALUE; } break; } } } static void do_args_validation(void) { if (kopt_sercon) { if (kopt_ttys != TTY_COUNT) { printk("WARNING: Ignored -ttys because of -sercon\n"); } kopt_ttys = 1; } if (kopt_ttys <= 0 || kopt_ttys > MAX_TTYS) { printk("WARNING: Invalid value '%ld' for ttys. Expected range: [1, %d]\n", kopt_ttys, MAX_TTYS); kopt_ttys = TTY_COUNT; } handle_selftest_kopt(); } static inline void end_arg(struct arg_parse_ctx *ctx, char *buf, char **argbuf_ref, int *arg_count_ref) { **argbuf_ref = 0; *argbuf_ref = buf; use_kernel_arg(ctx, (*arg_count_ref)++, buf); } static void debug_check_all_kopts(void) { for (u32 i = 0; i < ARRAY_SIZE(all_kopts); i++) { for (u32 j = 0; j < ARRAY_SIZE(all_kopts); j++) { if (i <= j) { /* * Avoid comparing twice the same pair and skip the comparison * between an element and itself. */ continue; } const char *ni = all_kopts[i].name; const char *nj = all_kopts[j].name; const char *ai = all_kopts[i].alias; const char *aj = all_kopts[j].alias; if (!strcmp(ni, nj) || (aj[0] && !strcmp(ni, aj)) || (ai[0] && !strcmp(ai, nj)) || (ai[0] && aj[0] && !strcmp(ai, aj))) { panic("Name conflict between kopt[%u] and kopt[%u]", i, j); } } if (!strcmp(all_kopts[i].name, "cmd") || !strcmp(all_kopts[i].alias, "cmd")) { panic("Cannot use 'cmd' as name or alias for kopt[%u]", i); } } } void parse_kernel_cmdline(const char *cmdline) { char buf[MAX_CMD_ARG_LEN + 1]; char *argbuf = buf; int arg_count = 0; struct arg_parse_ctx ctx = {0}; #ifndef UNIT_TEST_ENVIRONMENT printk("Kernel cmdline: '%s'\n", cmdline); #endif DEBUG_ONLY(debug_check_all_kopts()); for (const char *p = cmdline; *p;) { if (*p == ' ') { if (argbuf != buf) end_arg(&ctx, buf, &argbuf, &arg_count); p++; continue; } if ((argbuf - buf) >= MAX_CMD_ARG_LEN) { /* argument truncation: we have no more buffer for this argument */ end_arg(&ctx, buf, &argbuf, &arg_count); /* handle the trunc. arg */ while (*p && *p != ' ') p++; /* skip until the next arg */ continue; /* continue the parsing */ } *argbuf++ = *p++; } if (argbuf != buf) end_arg(&ctx, buf, &argbuf, &arg_count); do_args_validation(); } #endif // #ifndef CMDLINE_INCL_HACK <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/color_defs.h> #include <tilck/common/string_util.h> #include <tilck/kernel/fs/vfs_base.h> #include <tilck/kernel/fs/devfs.h> #include <tilck/kernel/term.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/tty_struct.h> #include <tilck/kernel/tty.h> #include <tilck/kernel/kmalloc.h> #include "console_int.h" #include "console_def_state.c.h" void *alloc_console_data(void) { struct console_data *cd; if (!(cd = kzalloc_obj(struct console_data))) return NULL; if (!(cd->def_state_funcs = kzalloc_array_obj(term_filter, 256))) { kfree_obj(cd, struct console_data); return NULL; } return cd; } void free_console_data(void *data) { if (data) { struct console_data *cd = data; kfree_array_obj(cd->def_state_funcs, term_filter, 256); kfree_obj(data, struct console_data); } } void reset_console_data(struct tty *t) { struct console_data *const cd = t->console_data; cd->user_color = t->curr_color; cd->c_set = 0; cd->c_sets_tables[0] = tty_default_trans_table; cd->c_sets_tables[1] = tty_gfx_trans_table; cd->filter_ctx.t = t; cd->filter_ctx.cd = cd; } void tty_reset_filter_ctx(struct tty *t) { struct console_data *cd = t->console_data; if (!cd) return; /* serial tty */ struct twfilter_ctx *ctx = &cd->filter_ctx; ctx->pbc = ctx->ibc = 0; ctx->t = t; ctx->cd = cd; tty_set_state(ctx, &tty_state_default); } static void tty_csi_ABCD_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { int d[4] = {0}; d[c - 'A'] = (int) MAX(1u, params[0]); term_make_action_move_cursor_rel( a, -d[0] + d[1], d[2] - d[3] ); } static void tty_csi_m_handler_param(u32 p, u8 *color, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; struct console_data *const cd = ctx->cd; u8 fg = get_color_fg(cd->user_color); u8 bg = get_color_bg(cd->user_color); switch(p) { case 0: /* Reset all attributes */ fg = DEFAULT_FG_COLOR; bg = DEFAULT_BG_COLOR; cd->attrs = 0; goto set_color; case 39: /* Reset fg color to the default value */ fg = DEFAULT_FG_COLOR; goto set_color; case 49: /* Reset bg color to the default value */ bg = DEFAULT_BG_COLOR; goto set_color; case 1: cd->attrs |= TTY_ATTR_BOLD; goto set_color; case 7: cd->attrs |= TTY_ATTR_REVERSE; goto set_color; default: /* fall-through */ break; } if ((30 <= p && p <= 37) || (90 <= p && p <= 97)) { /* Set foreground color */ fg = fg_csi_to_vga[p]; goto set_color; } else if ((40 <= p && p <= 47) || (100 <= p && p <= 107)) { /* Set background color */ bg = fg_csi_to_vga[p - 10]; goto set_color; } return; set_color: cd->user_color = make_color(fg, bg); if ((cd->attrs & TTY_ATTR_BOLD) && fg <= 7) fg += 8; if (cd->attrs & TTY_ATTR_REVERSE) t->curr_color = make_color(bg, fg); else t->curr_color = make_color(fg, bg); *color = t->curr_color; } static void tty_csi_m_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { if (!pc) { /* * Omitting all params, for example: "ESC[m", is equivalent to * having just one parameter set to 0. */ params[pc++] = 0; } for (int i = 0; i < pc; i++) { tty_csi_m_handler_param(params[i], color, ctx); } } static inline void tty_move_cursor_begin_nth_row(struct tty *t, struct term_action *a, u32 row) { const u32 new_row = MIN( vterm_get_curr_row(t->tstate) + row, t->tparams.rows - 1u ); term_make_action_move_cursor(a, new_row, 0); } static void tty_csi_EF_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; ASSERT(c == 'E' || c == 'F'); if (c == 'E') { /* Move the cursor 'n' lines down and set col = 0 */ tty_move_cursor_begin_nth_row(t, a, MAX(1u, params[0])); } else { /* Move the cursor 'n' lines up and set col = 0 */ tty_move_cursor_begin_nth_row(t, a, -MAX(1u, params[0])); } } static void tty_csi_G_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; /* Move the cursor to the column 'n' (absolute, 1-based) */ params[0] = MAX(1u, params[0]) - 1; term_make_action_move_cursor( a, vterm_get_curr_row(t->tstate), MIN((u32)params[0], t->tparams.cols - 1u) ); } static void tty_csi_fH_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; /* Move the cursor to (n, m) (absolute, 1-based) */ params[0] = MAX(1u, params[0]) - 1; params[1] = MAX(1u, params[1]) - 1; term_make_action_move_cursor( a, UNSAFE_MIN((u32)params[0], t->tparams.rows - 1u), UNSAFE_MIN((u32)params[1], t->tparams.cols - 1u) ); } static void tty_csi_J_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_erase_in_display(a, params[0]); } static void tty_csi_K_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_erase_in_line(a, params[0]); } static void tty_csi_S_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_non_buf_scroll( a, term_scroll_up, UNSAFE_MAX(1, params[0]) ); } static void tty_csi_T_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_non_buf_scroll( a, term_scroll_down, UNSAFE_MAX(1, params[0]) ); } static void tty_csi_n_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; char dsr[16] = {0}; if (params[0] == 6) { /* CPR (Cursor Position Report) */ snprintk(dsr, sizeof(dsr), "\033[%u;%uR", vterm_get_curr_row(t->tstate) + 1, vterm_get_curr_col(t->tstate) + 1); } else if (params[0] == 5) { /* DSR (Device Status Report) */ snprintk(dsr, sizeof(dsr), "\033[0n"); } if (dsr[0]) { tty_reset_filter_ctx(ctx->t); for (char *p = dsr; *p; p++) tty_send_keyevent(t, make_key_event(0, *p, true), true); } } static void tty_csi_s_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; /* SCP (Save Cursor Position) */ ctx->cd->saved_cur_row = vterm_get_curr_row(t->tstate); ctx->cd->saved_cur_col = vterm_get_curr_col(t->tstate); } static void tty_csi_u_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct console_data *const cd = ctx->cd; /* RCP (Restore Cursor Position) */ term_make_action_move_cursor( a, cd->saved_cur_row, cd->saved_cur_col ); } static void tty_csi_d_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; /* VPA: Move cursor to the indicated row, current column */ params[0] = MAX(1u, params[0]) - 1; term_make_action_move_cursor( a, UNSAFE_MIN((u32)params[0], t->tparams.rows - 1u), vterm_get_curr_col(t->tstate) ); } static void tty_csi_hpa_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; /* HPA: Move cursor to the indicated column, current row */ params[0] = MAX(1u, params[0]) - 1; term_make_action_move_cursor( a, vterm_get_curr_row(t->tstate), UNSAFE_MIN((u32)params[0], t->tparams.cols - 1u) ); } static void tty_csi_pvt_ext_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { if (c == 'c') { /* * Linux-specific cursor appearance manipulation. * See: www.kernel.org/doc/html/latest/admin-guide/vga-softcursor.html * * TODO: [console] consider supporting ESC [ ? <n> c */ return; } switch (params[0]) { case 25: if (c == 'h') /* Show the cursor */ term_make_action_set_cursor_enabled(a, true); else if (c == 'l') /* Hide the cursor */ term_make_action_set_cursor_enabled(a, false); break; case 1049: if (c == 'h') term_make_action_use_alt_buffer(a, true); else if (c == 'l') term_make_action_use_alt_buffer(a, false); break; default: /* unknown private CSI extension: do nothing */ break; } } static void tty_csi_L_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_ins_blank_lines(a, MAX(1u, params[0])); } static void tty_csi_M_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { term_make_action_del_lines(a, MAX(1u, params[0])); } static void tty_csi_r_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const u32 s = params[0] ? params[0] - 1u : 0u; const u32 e = params[1] ? params[1] - 1u : ctx->t->tparams.rows - 1u; if (s >= e) return; /* ignore */ term_make_action_set_scroll_region(a, s, e); } static void tty_csi_c_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { struct tty *const t = ctx->t; static const char buf[] = "\033[?6c"; /* meaning: I'm a VT102 */ tty_reset_filter_ctx(ctx->t); for (const char *p = buf; *p; p++) tty_send_keyevent(t, make_key_event(0, *p, true), true); } static void tty_csi_ICH_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const u16 n = (u16)MIN(params[0], (u32)UINT16_MAX); term_make_action_ins_blank_chars(a, UNSAFE_MAX(1u, n)); } static void tty_csi_P_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const u16 n = (u16)MIN(params[0], (u32)UINT16_MAX); term_make_action_simple_del_chars(a, UNSAFE_MAX(1u, n)); } static void tty_csi_a_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const int n = MAX(1, (int)params[0]); term_make_action_move_cursor_rel(a, 0, n); } static void tty_csi_e_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const int n = MAX(1, (int)params[0]); term_make_action_move_cursor_rel(a, n, 0); } static void tty_csi_X_handler(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const u16 n = (u16)MIN(params[0], (u32)UINT16_MAX); term_make_action_simple_erase_chars(a, UNSAFE_MAX(1u, n)); } typedef void (*csi_seq_handler)(u32 *params, int pc, u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx); static csi_seq_handler csi_handlers[256] = { ['@'] = tty_csi_ICH_handler, /* ICH: Insert # blank chars */ ['A'] = tty_csi_ABCD_handler, /* CUU: Move the cursor up */ ['B'] = tty_csi_ABCD_handler, /* CUD: Move the cursor down */ ['C'] = tty_csi_ABCD_handler, /* CUF: Move the cursor right */ ['D'] = tty_csi_ABCD_handler, /* CUB: Move the cursor left */ ['E'] = tty_csi_EF_handler, /* CNL: Move N lines down; set col=0 */ ['F'] = tty_csi_EF_handler, /* CPL: Move N lines up; set col=0 */ ['G'] = tty_csi_G_handler, /* CHA: Move to col N [abs, 1-based] */ ['H'] = tty_csi_fH_handler, /* CUP: Move to (N, M) [abs, 1-based] */ ['J'] = tty_csi_J_handler, /* ED: Erase in display */ ['K'] = tty_csi_K_handler, /* EL: Erase in line */ ['L'] = tty_csi_L_handler, /* IL: Insert # blank lines */ ['M'] = tty_csi_M_handler, /* DL: Delete # lines */ ['P'] = tty_csi_P_handler, /* DCH: Del # chars in the curr line */ ['S'] = tty_csi_S_handler, /* SU: Non-buf scroll-up */ ['T'] = tty_csi_T_handler, /* SD: Non-buf scroll-down */ ['X'] = tty_csi_X_handler, /* ECH: Erase # chars in the curr line */ ['a'] = tty_csi_a_handler, /* HPR: move right # columns */ ['c'] = tty_csi_c_handler, /* DA: query term type */ ['d'] = tty_csi_d_handler, /* VPA: Move to row N (abs), same col */ ['e'] = tty_csi_e_handler, /* VPR: move down # rows */ ['f'] = tty_csi_fH_handler, /* HVP: Move to (N, M) [abs, 1-based] */ ['g'] = NULL, /* TBC: not implemented */ ['h'] = NULL, /* SM: not implemented */ ['l'] = NULL, /* RM: not implemented */ ['m'] = tty_csi_m_handler, /* SGR: Select Graphic Rendition */ ['n'] = tty_csi_n_handler, /* DSR: Device Status Report */ ['q'] = NULL, /* DECLL: not implemented */ ['r'] = tty_csi_r_handler, /* DECSTBM: not implemented */ ['s'] = tty_csi_s_handler, /* SCP: Save Cursor Position */ ['u'] = tty_csi_u_handler, /* RCP: Restore Cursor Position */ ['`'] = tty_csi_hpa_handler, /* HPA: Move to col N (abs), same row */ }; static enum term_fret tty_filter_end_csi_seq(u8 c, u8 *color, struct term_action *a, struct twfilter_ctx *ctx) { const char *endptr; u32 params[NPAR] = {0}; bool csi_pvt_ext = false; int pc = 0; ctx->param_bytes[ctx->pbc] = 0; ctx->interm_bytes[ctx->ibc] = 0; if (ctx->pbc) { endptr = ctx->param_bytes - 1; if (ctx->param_bytes[0] == '?') { csi_pvt_ext = true; endptr++; } do { params[pc++] = (u32) tilck_strtol(endptr + 1, &endptr, 10, NULL); } while (*endptr); } if (LIKELY(!csi_pvt_ext)) { if (LIKELY(csi_handlers[c] != NULL)) csi_handlers[c](params, pc, c, color, a, ctx); } else { /* CSI ? <n> <c> */ tty_csi_pvt_ext_handler(params, pc, c, color, a, ctx); } tty_reset_filter_ctx(ctx->t); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_state_esc2_csi(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *ctx = ctx_arg; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; if (0x30 <= *c && *c <= 0x3F) { /* This is a parameter byte */ if (ctx->pbc >= ARRAY_SIZE(ctx->param_bytes)) { /* * The param bytes exceed our limits, something gone wrong: just return * back to the default state ignoring this escape sequence. */ tty_reset_filter_ctx(ctx->t); return TERM_FILTER_WRITE_BLANK; } ctx->param_bytes[ctx->pbc++] = (char) *c; return TERM_FILTER_WRITE_BLANK; } if (0x20 <= *c && *c <= 0x2F) { /* This is an "intermediate" byte */ if (ctx->ibc >= ARRAY_SIZE(ctx->interm_bytes)) { /* As above, the param bytes exceed our limits */ tty_reset_filter_ctx(ctx->t); return TERM_FILTER_WRITE_BLANK; } ctx->interm_bytes[ctx->ibc++] = (char) *c; return TERM_FILTER_WRITE_BLANK; } if (0x40 <= *c && *c <= 0x7E) { /* Final CSI byte */ return tty_filter_end_csi_seq(*c, color, a, ctx); } /* We shouldn't get here. Something's gone wrong: return the default state */ tty_reset_filter_ctx(ctx->t); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_state_esc2_unknown(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *ctx = ctx_arg; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; if (0x40 <= *c && *c <= 0x5f) { /* End of any possible (unknown) escape sequence */ tty_set_state(ctx, &tty_state_default); } return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_state_esc1(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *ctx = ctx_arg; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; switch (*c) { case '[': tty_reset_filter_ctx(ctx->t); tty_set_state(ctx, &tty_state_esc2_csi); break; case 'c': { struct tty *t = ctx->t; term_make_action_reset(a); tty_inbuf_reset(t); t->kd_gfx_mode = KD_TEXT; t->curr_color = DEFAULT_COLOR16; reset_console_data(t); tty_reset_termios(t); tty_update_default_state_tables(t); tty_reset_filter_ctx(t); } break; case '(': tty_set_state(ctx, &tty_state_esc2_par0); break; case ')': tty_set_state(ctx, &tty_state_esc2_par1); break; case 'D': /* linefeed */ tty_set_state(ctx, &tty_state_default); return tty_def_state_lf(c, color, a, ctx_arg); case 'M': /* reverse linefeed */ tty_set_state(ctx, &tty_state_default); return tty_def_state_ri(c, color, a, ctx_arg); default: tty_set_state(ctx, &tty_state_esc2_unknown); /* * We need to handle now this case because the sequence might be 1-char * long, like "^[_". Therefore, if the current character is in the * [0x40, 0x5f] range, we have to go back to the default state. * Otherwise, this is the identifier of a more complex sequence which * will end with the first character in the range [0x40, 0x5f]. */ return tty_state_esc2_unknown(c, color, a, ctx); } return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_change_translation_table(struct twfilter_ctx *ctx, u8 *c, int c_set) { struct console_data *const cd = ctx->cd; switch (*c) { case 'B': cd->c_sets_tables[c_set] = tty_default_trans_table; break; case '0': cd->c_sets_tables[c_set] = tty_gfx_trans_table; break; case 'U': case 'K': default: /* do nothing */ break; } tty_set_state(ctx, &tty_state_default); return TERM_FILTER_WRITE_BLANK; } static enum term_fret tty_state_esc2_par0(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; return tty_change_translation_table(ctx_arg, c, 0); } static enum term_fret tty_state_esc2_par1(u8 *c, u8 *color, struct term_action *a, void *ctx_arg) { struct twfilter_ctx *const ctx = ctx_arg; int rc; if ((rc = tty_pre_filter(ctx, c)) >= 0) return (enum term_fret)rc; return tty_change_translation_table(ctx_arg, c, 1); } static void tty_set_state(struct twfilter_ctx *ctx, term_filter new_state) { struct tty *const t = ctx->t; ctx->non_default_state = new_state != &tty_state_default; t->tintf->set_filter(t->tstate, new_state, ctx); } static int tty_pre_filter(struct twfilter_ctx *ctx, u8 *c) { if (ctx->non_default_state) { switch (*c) { case '\033': /* ESC in the middle of any sequence, just starts a new one */ tty_reset_filter_ctx(ctx->t); tty_set_state(ctx, &tty_state_esc1); return TERM_FILTER_WRITE_BLANK; default: /* fall-through */ break; } } return -1; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_debug.h> #include <tilck_gen_headers/config_boot.h> #include <tilck_gen_headers/config_kmalloc.h> #include <tilck_gen_headers/config_userlim.h> #include <tilck_gen_headers/config_mm.h> #include <tilck_gen_headers/config_sched.h> #include <tilck_gen_headers/mod_kb8042.h> #include <tilck_gen_headers/mod_console.h> #include <tilck_gen_headers/mod_fb.h> #include <tilck_gen_headers/mod_serial.h> #include <tilck_gen_headers/mod_debugpanel.h> #include <tilck_gen_headers/mod_tracing.h> #include <tilck_gen_headers/mod_sysfs.h> #include <tilck_gen_headers/mod_acpi.h> #include <tilck_gen_headers/mod_pci.h> #include <tilck_gen_headers/mod_sb16.h> #include <tilck/common/build_info.h> #include <tilck/mods/sysfs.h> #include <tilck/mods/sysfs_utils.h> /* config */ DEF_STATIC_CONF_RO(STRING, buildtype, BUILDTYPE_STR); DEF_STATIC_CONF_RO(STRING, version, tilck_build_info.ver); DEF_STATIC_CONF_RO(STRING, arch, tilck_build_info.arch); DEF_STATIC_CONF_RO(STRING, commit, tilck_build_info.commit); DEF_STATIC_CONF_RO(BOOL, debugchecks, DEBUG_CHECKS); /* config/kernel */ DEF_STATIC_CONF_RO(ULONG, timer_hz, TIMER_HZ); DEF_STATIC_CONF_RO(ULONG, stack_pages, KERNEL_STACK_PAGES); DEF_STATIC_CONF_RO(ULONG, user_stack_pages, USER_STACK_PAGES); DEF_STATIC_CONF_RO(BOOL, track_nested_int, KRN_TRACK_NESTED_INTERR); DEF_STATIC_CONF_RO(BOOL, panic_backtrace, PANIC_SHOW_STACKTRACE); DEF_STATIC_CONF_RO(BOOL, panic_regs, PANIC_SHOW_REGS); DEF_STATIC_CONF_RO(BOOL, selftests, KERNEL_SELFTESTS); DEF_STATIC_CONF_RO(BOOL, stack_isolation, KERNEL_STACK_ISOLATION); DEF_STATIC_CONF_RO(BOOL, symbols, KERNEL_SYMBOLS); DEF_STATIC_CONF_RO(BOOL, printk_on_curr_tty, KRN_PRINTK_ON_CURR_TTY); DEF_STATIC_CONF_RO(BOOL, resched_enable_preempt, KRN_RESCHED_ENABLE_PREEMPT); DEF_STATIC_CONF_RO(BOOL, big_io_buf, KERNEL_BIG_IO_BUF); DEF_STATIC_CONF_RO(BOOL, gcov, KERNEL_GCOV); DEF_STATIC_CONF_RO(BOOL, fork_no_cow, FORK_NO_COW); DEF_STATIC_CONF_RO(BOOL, mmap_no_cow, MMAP_NO_COW); DEF_STATIC_CONF_RO(BOOL, ubsan, KERNEL_UBSAN); DEF_STATIC_CONF_RO(BOOL, kernel_64bit_offt, KERNEL_64BIT_OFFT); DEF_STATIC_CONF_RO(BOOL, clock_drift_comp, KRN_CLOCK_DRIFT_COMP); /* config/console */ DEF_STATIC_CONF_RO(ULONG, big_font_threshold, FBCON_BIGFONT_THR); DEF_STATIC_CONF_RO(BOOL, banner, FB_CONSOLE_BANNER); DEF_STATIC_CONF_RO(BOOL, cursor_blink, FB_CONSOLE_CURSOR_BLINK); DEF_STATIC_CONF_RO(BOOL, use_alt_fonts, FB_CONSOLE_USE_ALT_FONTS); DEF_STATIC_CONF_RO(BOOL, show_logo, KERNEL_SHOW_LOGO); DEF_STATIC_CONF_RO(BOOL, big_scroll_buf, TERM_BIG_SCROLL_BUF); DEF_STATIC_CONF_RO(BOOL, failsafe_opt, FB_CONSOLE_FAILSAFE_OPT); /* config/modules */ DEF_STATIC_CONF_RO(BOOL, sysfs, MOD_sysfs); DEF_STATIC_CONF_RO(BOOL, pci, MOD_pci); DEF_STATIC_CONF_RO(BOOL, acpi, MOD_acpi); DEF_STATIC_CONF_RO(BOOL, kb8042, MOD_kb8042); DEF_STATIC_CONF_RO(BOOL, tracing, MOD_tracing); DEF_STATIC_CONF_RO(BOOL, console, MOD_console); DEF_STATIC_CONF_RO(BOOL, fb, MOD_fb); DEF_STATIC_CONF_RO(BOOL, serial, MOD_serial); DEF_STATIC_CONF_RO(BOOL, sb16, MOD_sb16); DEF_STATIC_CONF_RO(BOOL, debugpanel, MOD_debugpanel); void sysfs_create_config_obj(void) { struct sysobj *config, *kernel, *console, *modules; config = sysfs_create_custom_obj( "config", NULL, /* hooks */ SYSOBJ_CONF_PROP_PAIR(buildtype), SYSOBJ_CONF_PROP_PAIR(version), SYSOBJ_CONF_PROP_PAIR(arch), SYSOBJ_CONF_PROP_PAIR(commit), SYSOBJ_CONF_PROP_PAIR(debugchecks), NULL ); if (!config) goto fail; if (sysfs_register_obj(NULL, &sysfs_root_obj, "config", config)) goto fail; kernel = sysfs_create_custom_obj( "kernel", NULL, /* hooks */ SYSOBJ_CONF_PROP_PAIR(timer_hz), SYSOBJ_CONF_PROP_PAIR(stack_pages), SYSOBJ_CONF_PROP_PAIR(user_stack_pages), SYSOBJ_CONF_PROP_PAIR(track_nested_int), SYSOBJ_CONF_PROP_PAIR(panic_backtrace), SYSOBJ_CONF_PROP_PAIR(panic_regs), SYSOBJ_CONF_PROP_PAIR(selftests), SYSOBJ_CONF_PROP_PAIR(stack_isolation), SYSOBJ_CONF_PROP_PAIR(symbols), SYSOBJ_CONF_PROP_PAIR(printk_on_curr_tty), SYSOBJ_CONF_PROP_PAIR(resched_enable_preempt), SYSOBJ_CONF_PROP_PAIR(big_io_buf), SYSOBJ_CONF_PROP_PAIR(gcov), SYSOBJ_CONF_PROP_PAIR(fork_no_cow), SYSOBJ_CONF_PROP_PAIR(mmap_no_cow), SYSOBJ_CONF_PROP_PAIR(ubsan), SYSOBJ_CONF_PROP_PAIR(kernel_64bit_offt), SYSOBJ_CONF_PROP_PAIR(clock_drift_comp), NULL ); if (!kernel) goto fail; if (sysfs_register_obj(NULL, config, "kernel", kernel)) goto fail; console = sysfs_create_custom_obj( "console", NULL, /* hooks */ SYSOBJ_CONF_PROP_PAIR(big_font_threshold), SYSOBJ_CONF_PROP_PAIR(banner), SYSOBJ_CONF_PROP_PAIR(cursor_blink), SYSOBJ_CONF_PROP_PAIR(use_alt_fonts), SYSOBJ_CONF_PROP_PAIR(show_logo), SYSOBJ_CONF_PROP_PAIR(big_scroll_buf), SYSOBJ_CONF_PROP_PAIR(failsafe_opt), NULL ); if (!console) goto fail; if (sysfs_register_obj(NULL, config, "console", console)) goto fail; modules = sysfs_create_custom_obj( "modules", NULL, /* hooks */ SYSOBJ_CONF_PROP_PAIR(sysfs), SYSOBJ_CONF_PROP_PAIR(pci), SYSOBJ_CONF_PROP_PAIR(acpi), SYSOBJ_CONF_PROP_PAIR(kb8042), SYSOBJ_CONF_PROP_PAIR(tracing), SYSOBJ_CONF_PROP_PAIR(console), SYSOBJ_CONF_PROP_PAIR(fb), SYSOBJ_CONF_PROP_PAIR(serial), SYSOBJ_CONF_PROP_PAIR(sb16), SYSOBJ_CONF_PROP_PAIR(debugpanel), NULL ); if (!modules) goto fail; if (sysfs_register_obj(NULL, config, "modules", modules)) goto fail; /* Success */ return; fail: panic("Unable to create the sysfs config obj"); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/errno.h> static const char *errno_names[] = { [EPERM] = "EPERM", [ENOENT] = "ENOENT", [ESRCH] = "ESRCH", [EINTR] = "EINTR", [EIO] = "EIO", [ENXIO] = "ENXIO", [E2BIG] = "E2BIG", [ENOEXEC] = "ENOEXEC", [EBADF] = "EBADF", [ECHILD] = "ECHILD", [EAGAIN] = "EAGAIN", [ENOMEM] = "ENOMEM", [EACCES] = "EACCES", [EFAULT] = "EFAULT", [ENOTBLK] = "ENOTBLK", [EBUSY] = "EBUSY", [EEXIST] = "EEXIST", [EXDEV] = "EXDEV", [ENODEV] = "ENODEV", [ENOTDIR] = "ENOTDIR", [EISDIR] = "EISDIR", [EINVAL] = "EINVAL", [ENFILE] = "ENFILE", [EMFILE] = "EMFILE", [ENOTTY] = "ENOTTY", [ETXTBSY] = "ETXTBSY", [EFBIG] = "EFBIG", [ENOSPC] = "ENOSPC", [ESPIPE] = "ESPIPE", [EROFS] = "EROFS", [EMLINK] = "EMLINK", [EPIPE] = "EPIPE", [EDOM] = "EDOM", [ERANGE] = "ERANGE", [EDEADLK] = "EDEADLK", [ENAMETOOLONG] = "ENAMETOOLONG", [ENOLCK] = "ENOLCK", [ENOSYS] = "ENOSYS", [ENOTEMPTY] = "ENOTEMPTY", [ELOOP] = "ELOOP", [ENOMSG] = "ENOMSG", [EIDRM] = "EIDRM", [ECHRNG] = "ECHRNG", [EL2NSYNC] = "EL2NSYNC", [EL3HLT] = "EL3HLT", [EL3RST] = "EL3RST", [ELNRNG] = "ELNRNG", [EUNATCH] = "EUNATCH", [ENOCSI] = "ENOCSI", [EL2HLT] = "EL2HLT", [EBADE] = "EBADE", [EBADR] = "EBADR", [EXFULL] = "EXFULL", [ENOANO] = "ENOANO", [EBADRQC] = "EBADRQC", [EBADSLT] = "EBADSLT", [EBFONT] = "EBFONT", [ENOSTR] = "ENOSTR", [ENODATA] = "ENODATA", [ETIME] = "ETIME", [ENOSR] = "ENOSR", [ENONET] = "ENONET", [ENOPKG] = "ENOPKG", [EREMOTE] = "EREMOTE", [ENOLINK] = "ENOLINK", [EADV] = "EADV", [ESRMNT] = "ESRMNT", [ECOMM] = "ECOMM", [EPROTO] = "EPROTO", [EMULTIHOP] = "EMULTIHOP", [EDOTDOT] = "EDOTDOT", [EBADMSG] = "EBADMSG", [EOVERFLOW] = "EOVERFLOW", [ENOTUNIQ] = "ENOTUNIQ", [EBADFD] = "EBADFD", [EREMCHG] = "EREMCHG", [ELIBACC] = "ELIBACC", [ELIBBAD] = "ELIBBAD", [ELIBSCN] = "ELIBSCN", [ELIBMAX] = "ELIBMAX", [ELIBEXEC] = "ELIBEXEC", [EILSEQ] = "EILSEQ", [ERESTART] = "ERESTART", [ESTRPIPE] = "ESTRPIPE", [EUSERS] = "EUSERS", [ENOTSOCK] = "ENOTSOCK", [EDESTADDRREQ] = "EDESTADDRREQ", [EMSGSIZE] = "EMSGSIZE", [EPROTOTYPE] = "EPROTOTYPE", [ENOPROTOOPT] = "ENOPROTOOPT", [EPROTONOSUPPORT] = "EPROTONOSUPPORT", [ESOCKTNOSUPPORT] = "ESOCKTNOSUPPORT", [EOPNOTSUPP] = "EOPNOTSUPP", [EPFNOSUPPORT] = "EPFNOSUPPORT", [EAFNOSUPPORT] = "EAFNOSUPPORT", [EADDRINUSE] = "EADDRINUSE", [EADDRNOTAVAIL] = "EADDRNOTAVAIL", [ENETDOWN] = "ENETDOWN", [ENETUNREACH] = "ENETUNREACH", [ENETRESET] = "ENETRESET", [ECONNABORTED] = "ECONNABORTED", [ECONNRESET] = "ECONNRESET", [ENOBUFS] = "ENOBUFS", [EISCONN] = "EISCONN", [ENOTCONN] = "ENOTCONN", [ESHUTDOWN] = "ESHUTDOWN", [ETOOMANYREFS] = "ETOOMANYREFS", [ETIMEDOUT] = "ETIMEDOUT", [ECONNREFUSED] = "ECONNREFUSED", [EHOSTDOWN] = "EHOSTDOWN", [EHOSTUNREACH] = "EHOSTUNREACH", [EALREADY] = "EALREADY", [EINPROGRESS] = "EINPROGRESS", [ESTALE] = "ESTALE", [EUCLEAN] = "EUCLEAN", [ENOTNAM] = "ENOTNAM", [ENAVAIL] = "ENAVAIL", [EISNAM] = "EISNAM", [EREMOTEIO] = "EREMOTEIO", [EDQUOT] = "EDQUOT", [ENOMEDIUM] = "ENOMEDIUM", [EMEDIUMTYPE] = "EMEDIUMTYPE", [ECANCELED] = "ECANCELED", [ENOKEY] = "ENOKEY", [EKEYEXPIRED] = "EKEYEXPIRED", [EKEYREVOKED] = "EKEYREVOKED", [EKEYREJECTED] = "EKEYREJECTED", [EOWNERDEAD] = "EOWNERDEAD", [ENOTRECOVERABLE] = "ENOTRECOVERABLE", [ERFKILL] = "ERFKILL", [EHWPOISON] = "EHWPOISON", }; const char *get_errno_name(int errno) { if (errno <= 0 || errno >= (int)ARRAY_SIZE(errno_names)) return NULL; return errno_names[errno]; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> /* Check for the 'j' length modifier (intmax_t) */ STATIC_ASSERT(sizeof(intmax_t) == sizeof(long long)); static bool write_in_buf_str(char **buf_ref, char *buf_end, const char *s, int len) { char *ptr = *buf_ref; if (len >= 0) { while (*s && len > 0 && ptr < buf_end) { *ptr++ = *s++; len--; } } else { while (*s && ptr < buf_end) { *ptr++ = *s++; } } *buf_ref = ptr; return ptr < buf_end; } static inline bool write_in_buf_char(char **buf_ref, char *buf_end, char c) { char *ptr = *buf_ref; *ptr++ = c; *buf_ref = ptr; return ptr < buf_end; } enum printk_width { pw_long_long = 0, pw_long = 1, pw_default = 2, pw_short = 3, pw_char = 4 }; static const ulong width_val[] = { [pw_long_long] = 0, /* unused */ [pw_long] = 8 * sizeof(long), [pw_default] = 8 * sizeof(int), [pw_short] = 8 * sizeof(short), [pw_char] = 8 * sizeof(char), }; struct snprintk_ctx { /* Fundamental context variables */ const char *fmt; va_list args; char *buf; /* dest buffer */ char *buf_end; /* dest buffer's end */ /* The following params are reset on each call of process_seq */ enum printk_width width; int lpad; int rpad; int precision; bool zero_lpad; bool hash_sign; /* Helper buffers */ char intbuf[64]; }; static void snprintk_ctx_reset_state(struct snprintk_ctx *ctx) { ctx->width = pw_default; ctx->lpad = 0; ctx->rpad = 0; ctx->precision = -1; ctx->zero_lpad = false; ctx->hash_sign = false; } #define WRITE_CHAR(c) \ do { \ if (!write_in_buf_char(&ctx->buf, ctx->buf_end, (c))) \ goto out_of_dest_buffer; \ } while (0) static bool write_0x_prefix(struct snprintk_ctx *ctx, char fmtX) { if (fmtX == 'x' || fmtX == 'p' || fmtX == 'o') { WRITE_CHAR('0'); if (fmtX == 'x' || fmtX == 'p') WRITE_CHAR('x'); } return true; out_of_dest_buffer: return false; } static bool write_str(struct snprintk_ctx *ctx, char fmtX, const char *str) { int sl = (int) strlen(str); int lpad = MAX(0, ctx->lpad - sl); int rpad = MAX(0, ctx->rpad - sl); bool zero_lpad = ctx->zero_lpad; char pad_char = ' '; /* Cannot have both left padding _and_ right padding */ ASSERT(!lpad || !rpad); if (ctx->precision >= 0 && fmtX != 's') { /* Note: we don't support floating point numbers */ zero_lpad = true; lpad = MAX(0, ctx->precision - sl); } if (ctx->hash_sign) { int off = 0; if (fmtX == 'x') off = 2; else if (fmtX == 'o') off = 1; lpad = MAX(0, lpad - off); rpad = MAX(0, rpad - off); } if (zero_lpad) { if (fmtX != 'c') pad_char = '0'; if (ctx->hash_sign) { if (!write_0x_prefix(ctx, fmtX)) goto out_of_dest_buffer; } } for (int i = 0; i < lpad; i++) WRITE_CHAR(pad_char); if ((fmtX == 'p' || ctx->hash_sign) && pad_char != '0') { if (!write_0x_prefix(ctx, fmtX)) goto out_of_dest_buffer; } if (!write_in_buf_str(&ctx->buf, ctx->buf_end, str, ctx->precision)) goto out_of_dest_buffer; for (int i = 0; i < rpad; i++) WRITE_CHAR(pad_char); return true; out_of_dest_buffer: return false; } static const u8 diuox_base[128] = { ['d'] = 10, ['i'] = 10, ['u'] = 10, ['o'] = 8, ['x'] = 16, ['X'] = 16, }; static bool write_char_param(struct snprintk_ctx *ctx, char fmtX) { ctx->intbuf[0] = (char)va_arg(ctx->args, long); ctx->intbuf[1] = 0; return write_str(ctx, 'c', ctx->intbuf); } static bool write_string_param(struct snprintk_ctx *ctx, char fmtX) { const char *str = va_arg(ctx->args, const char *); if (!str) str = "(null)"; return write_str(ctx, fmtX, str); } static bool write_pointer_param(struct snprintk_ctx *ctx, char fmtX) { uitoaN_hex_fixed(va_arg(ctx->args, ulong), ctx->intbuf); return write_str(ctx, fmtX, ctx->intbuf); } static bool write_number_param(struct snprintk_ctx *ctx, char fmtX) { ulong width = width_val[ctx->width]; u8 base = diuox_base[(u8)fmtX]; char *intbuf = ctx->intbuf; ASSERT(base); if (fmtX == 'd' || fmtX == 'i') { if (ctx->width == pw_long_long) itoa64(va_arg(ctx->args, s64), intbuf); else itoaN(sign_extend(va_arg(ctx->args, long), width), intbuf); } else { if (ctx->width == pw_long_long) uitoa64(va_arg(ctx->args, u64), intbuf, base); else uitoaN(va_arg(ctx->args, ulong) & make_bitmask(width), intbuf, base); } if (fmtX == 'X') { fmtX = 'x'; for (char *p = ctx->intbuf; *p; p++) *p = (char) toupper(*p); } return write_str(ctx, fmtX, intbuf); } typedef bool (*write_param_func)(struct snprintk_ctx *, char); static const write_param_func write_funcs[32] = { ['d' - 97] = &write_number_param, ['i' - 97] = &write_number_param, ['o' - 97] = &write_number_param, ['u' - 97] = &write_number_param, ['x' - 97] = &write_number_param, ['c' - 97] = &write_char_param, ['s' - 97] = &write_string_param, ['p' - 97] = &write_pointer_param, }; static const enum printk_width double_mods[2][3] = { /* 'l' modifier */ { pw_default, pw_long, pw_long_long }, /* 'h' modifier */ { pw_default, pw_short, pw_char }, }; static const enum printk_width single_mods[2] = { /* 'z' and 't' modifiers */ pw_long, /* 'L', 'q', 'j' modifiers */ pw_long_long, }; static bool process_seq(struct snprintk_ctx *ctx) { /* Here're just after '%' */ if (*ctx->fmt == '%' || (u8)*ctx->fmt >= 128) { /* %% or % followed by non-ascii char */ WRITE_CHAR(*ctx->fmt); return true; } goto process_next_char_in_seq; move_to_next_char_in_seq: ctx->fmt++; process_next_char_in_seq: if (!*ctx->fmt) goto truncated_seq; if (isalpha_lower(*ctx->fmt)) { u8 idx = (u8)*ctx->fmt - 97; if (write_funcs[idx]) { if (!write_funcs[idx](ctx, *ctx->fmt)) goto out_of_dest_buffer; goto end_sequence; } } else if (*ctx->fmt == 'X') { if (!write_number_param(ctx, 'X')) goto out_of_dest_buffer; goto end_sequence; } switch (*ctx->fmt) { case '0': ctx->zero_lpad = true; goto move_to_next_char_in_seq; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ctx->lpad = (int)tilck_strtol(ctx->fmt, &ctx->fmt, 10, NULL); goto process_next_char_in_seq; case '*': /* Exactly like the 0-9 case, but we must take the value from a param */ ctx->lpad = (int)va_arg(ctx->args, long); if (ctx->lpad < 0) { ctx->rpad = -ctx->lpad; ctx->lpad = 0; } goto move_to_next_char_in_seq; case '-': if (ctx->fmt[1] != '*') { ctx->rpad = (int)tilck_strtol(ctx->fmt + 1, &ctx->fmt, 10, NULL); } else { ctx->rpad = (int)va_arg(ctx->args, long); if (ctx->rpad < 0) ctx->rpad = -ctx->rpad; ctx->fmt += 2; /* skip '-' and '*' */ } goto process_next_char_in_seq; case '.': if (ctx->fmt[1] != '*') { ctx->precision = (int)tilck_strtol(ctx->fmt + 1, &ctx->fmt, 10, NULL); } else { ctx->precision = MAX(0, (int)va_arg(ctx->args, long)); ctx->fmt += 2; } goto process_next_char_in_seq; case '#': if (ctx->hash_sign) { if (!*++ctx->fmt) goto incomplete_seq; /* note: forcing "%#" to be printed */ goto process_next_char_in_seq; /* skip this '#' and move on */ } if (ctx->fmt[-1] != '%') goto incomplete_seq; if (!ctx->fmt[1]) goto unknown_seq; ctx->hash_sign = true; goto move_to_next_char_in_seq; case 'z': /* fall-through */ case 't': /* fall-through */ case 'j': /* fall-through */ case 'q': /* fall-through */ case 'L': if (ctx->width != pw_default) goto unknown_seq; ctx->width = single_mods[*ctx->fmt != 'z' && *ctx->fmt != 't']; goto move_to_next_char_in_seq; case 'l': /* fall-through */ case 'h': { int idx = -1; int m = *ctx->fmt != 'l'; /* choose the sub-array: 'l' or 'h' */ /* Find the index in the sub-array with the current width mod */ for (int i = 0; i < 3; i++) { if (ctx->width == double_mods[m][i]) idx = i; } /* Invalid current width modifier */ if (idx < 0 || idx == 2) goto unknown_seq; /* %lll, %hhh, %lh, %hl, ... */ /* Move to the next modifier (e.g. default -> long -> long long) */ ctx->width = double_mods[m][idx + 1]; goto move_to_next_char_in_seq; } default: unknown_seq: incomplete_seq: WRITE_CHAR('%'); if (ctx->hash_sign) WRITE_CHAR('#'); if (ctx->zero_lpad) { WRITE_CHAR('0'); ctx->zero_lpad = false; } if (ctx->rpad) { ctx->lpad = -ctx->rpad; ctx->rpad = 0; } if (ctx->lpad) { itoaN(ctx->lpad, ctx->intbuf); ctx->lpad = 0; write_str(ctx, 'd', ctx->intbuf); } WRITE_CHAR(*ctx->fmt); goto end_sequence; } /* Make `break` unusable in the switch, in order to avoid confusion */ NOT_REACHED(); end_sequence: snprintk_ctx_reset_state(ctx); return true; truncated_seq: out_of_dest_buffer: return false; } int vsnprintk(char *initial_buf, size_t size, const char *__fmt, va_list __args) { struct snprintk_ctx __ctx; /* ctx has to be a pointer because of macros */ struct snprintk_ctx *ctx = &__ctx; snprintk_ctx_reset_state(ctx); ctx->fmt = __fmt; ctx->buf = initial_buf; ctx->buf_end = initial_buf + size; va_copy(ctx->args, __args); for (char fmtX; (fmtX = *ctx->fmt); ctx->fmt++) { if (LIKELY(fmtX != '%')) { /* Regular character: just write it */ WRITE_CHAR(fmtX); } else { /* fmt is '%': move it forward */ ctx->fmt++; /* process the whole '%' sequence (it's often longer than 1 char) */ if (!process_seq(ctx)) break; /* our dest is full or fmt finished early */ } } truncated_seq: out_of_dest_buffer: ctx->buf[ ctx->buf < ctx->buf_end ? 0 : -1 ] = 0; return (int)(ctx->buf - initial_buf); } int snprintk(char *buf, size_t size, const char *fmt, ...) { int written; va_list args; va_start(args, fmt); written = vsnprintk(buf, size, fmt, args); va_end(args); return written; } <file_sep>#!/bin/sh exec $SYS_CXX -m32 -march=i686 "$@" $CC_POST_FLAGS <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ static ssize_t sysfs_dir_read(fs_handle h, char *buf, size_t len, offt *pos) { return -EISDIR; } static ssize_t sysfs_dir_write(fs_handle h, char *buf, size_t len, offt *pos) { return -EISDIR; } static int sysfs_dir_ioctl(fs_handle h, ulong request, void *arg) { return -EINVAL; } static offt sysfs_dir_seek(fs_handle h, offt target_off, int whence) { struct sysfs_handle *sh = h; struct sysfs_entry *pos; offt off = 0; if (target_off < 0 || whence != SEEK_SET) return -EINVAL; list_for_each_ro(pos, &sh->inode->dir.entries_list, lnode) { if (off == target_off) break; off++; } if (off == target_off) { sh->dir.dpos = pos; sh->dir_pos = off; return sh->dir_pos; } return -EINVAL; } static const struct file_ops static_ops_dir_sysfs = { .read = sysfs_dir_read, .write = sysfs_dir_write, .seek = sysfs_dir_seek, .ioctl = sysfs_dir_ioctl, .mmap = NULL, .munmap = NULL, }; static int sysfs_open_dir(struct mnt_fs *fs, struct sysfs_inode *pos, fs_handle *out) { struct sysfs_handle *h; if (!(h = vfs_create_new_handle(fs, &static_ops_dir_sysfs))) return -ENOMEM; h->type = VFS_DIR; h->dir.dpos = list_first_obj(&pos->dir.entries_list, struct sysfs_entry, lnode); h->inode = pos; retain_obj(pos); *out = h; return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mocking.h" using namespace testing; extern "C" { #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include <tilck/kernel/user.h> #include <tilck/mods/tracing.h> #include <tilck/kernel/test/tracing.h> } class MockingTracer : public KernelSingleton { public: MOCK_METHOD(int, copy_str_from_user, (void *, const void *, size_t, size_t *), (override)); MOCK_METHOD(int, copy_from_user, (void *, const void *, size_t), (override)); }; TEST(tracer_test, save_param_buffer) { MockingTracer mock; long data_sz = -1; void *data = (void *)"test"; char dest_buf_1[8]; const size_t dest_bs_1 = sizeof(dest_buf_1); char dest_buf_2[8]; const size_t dest_bs_2 = sizeof(dest_buf_2); char dest_buf_3[8]; const size_t dest_bs_3 = sizeof(dest_buf_3); EXPECT_CALL(mock, copy_str_from_user) .WillOnce(Return(-1)) .WillOnce([] (void *dest, const void *user_ptr, size_t, size_t *) { strcpy((char *)dest, (char *)user_ptr); return 1; }); // rc < 0 EXPECT_TRUE(save_param_buffer(data, data_sz, dest_buf_1, dest_bs_1)); EXPECT_STREQ(dest_buf_1, "<fault>"); // rc > 0 void *data_2 = (void *)"VeryVeryLong"; EXPECT_TRUE(save_param_buffer(data_2, data_sz, dest_buf_2, dest_bs_2)); EXPECT_STREQ(dest_buf_2, "VeryVer"); // data_sz >= 0 data_sz = 5; EXPECT_CALL(mock, copy_from_user) .WillOnce(Return(1)); EXPECT_TRUE(save_param_buffer(data, data_sz, dest_buf_3, dest_bs_3)); EXPECT_STREQ(dest_buf_3, "<fault>"); } TEST(tracer_test, dump_param_buffer) { MockingTracer mock; ulong orig = 1; long data_bs = -1; long real_sz = -1; char *data_1 = (char *)"\r"; char dest_1[10]; const size_t dest_bs_1 = sizeof(dest_1); char *data_2 = (char *)"\""; char dest_2[10]; const size_t dest_bs_2 = sizeof(dest_2); char *data_3 = (char *)"\\"; char dest_3[10]; const size_t dest_bs_3 = sizeof(dest_3); EXPECT_TRUE(dump_param_buffer(orig, data_1, data_bs, real_sz, dest_1, dest_bs_1)); EXPECT_STREQ(dest_1, "\"\\r\""); EXPECT_TRUE(dump_param_buffer(orig, data_2, data_bs, real_sz, dest_2, dest_bs_2)); EXPECT_STREQ(dest_2, "\"\\\"\""); EXPECT_TRUE(dump_param_buffer(orig, data_3, data_bs, real_sz, dest_3, dest_bs_3)); EXPECT_STREQ(dest_3, "\"\\\\\""); // For `if (dest_end - dest < ml - 1)` path // and `if (dest >= dest_end - 4)` path char *data_4 = (char *)"VeryVeryLong"; char dest_4[10]; const size_t dest_bs_4 = sizeof(dest_4); EXPECT_TRUE(dump_param_buffer(orig, data_4, data_bs, real_sz, dest_4, dest_bs_4)); EXPECT_STREQ(dest_4, "\"Very...\""); // For `if (s == data_end && real_sz > 0 && data_bs < real_sz)` path char *data_5 = (char *)"abcd"; char dest_5[10]; const size_t dest_bs_5 = sizeof(dest_5); real_sz = 2; EXPECT_TRUE(dump_param_buffer(orig, data_5, data_bs, real_sz, dest_5, dest_bs_5)); EXPECT_STREQ(dest_5, "\"ab\""); } <file_sep># SPDX-License-Identifier: BSD-2-Clause cmake_minimum_required(VERSION 3.2) set(SPACE " ") function(JOIN VALUES GLUE OUTPUT) string(REPLACE ";" "${GLUE}" _TMP_STR "${VALUES}") set(${OUTPUT} "${_TMP_STR}" PARENT_SCOPE) endfunction() function(PREPEND var prefix) set(listVar "") foreach(f ${ARGN}) list(APPEND listVar "${prefix}${f}") endforeach(f) set(${var} "${listVar}" PARENT_SCOPE) endfunction(PREPEND) macro(define_env_cache_str_var) if (NOT DEFINED ${ARGV0}) if (NOT "$ENV{${ARGV0}}" STREQUAL "") set(${ARGV0} "$ENV{${ARGV0}}" CACHE INTERNAL "") else() set(${ARGV0} "${ARGV1}" CACHE INTERNAL "") endif() else() if ("$ENV{PERMISSIVE}" STREQUAL "") if (NOT "$ENV{${ARGV0}}" STREQUAL "") if (NOT "$ENV{${ARGV0}}" STREQUAL "${${ARGV0}}") set(msg "") string(CONCAT msg "Environment var ${ARGV0}='$ENV{${ARGV0}}' " "differs from cached value='${${ARGV0}}'. " "The whole build directory must be ERASED " "in order to change that.") message(FATAL_ERROR "\n${msg}") endif() endif() endif() endif() endmacro() macro(define_env_cache_bool_var) if (NOT DEFINED _CACHE_${ARGV0}) if (NOT "$ENV{${ARGV0}}" STREQUAL "") set(_CACHE_${ARGV0} "$ENV{${ARGV0}}" CACHE INTERNAL "") else() set(_CACHE_${ARGV0} 0 CACHE INTERNAL "") endif() else() if (NOT "$ENV{${ARGV0}}" STREQUAL "") if (NOT "$ENV{${ARGV0}}" STREQUAL "${_CACHE_${ARGV0}}") set(msg "") string(CONCAT msg "Environment variable ${ARGV0}='$ENV{${ARGV0}}' " "differs from cached value='${${ARGV0}}'. " "The whole build directory must be ERASED " "in order to change that.") message(FATAL_ERROR "\n${msg}") endif() endif() endif() if (_CACHE_${ARGV0}) set(${ARGV0} 1) else() set(${ARGV0} 0) endif() endmacro() macro(set_cross_compiler) if (USE_SYSCC) if (${ARCH} STREQUAL "i386") set(CMAKE_C_FLAGS "${ARCH_GCC_FLAGS}") set(CMAKE_CXX_FLAGS "${ARCH_GCC_FLAGS} ${KERNEL_CXX_FLAGS}") set(CMAKE_ASM_FLAGS "${ARCH_GCC_FLAGS}") else() # Assume that the system's compiler is already able to build for # the given target architecture without additional flags. endif() set(TOOL_GCOV "${GCOV}") else() # DEFAULT CASE: use our pre-built toolchain set(CMAKE_C_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_CXX_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-g++) set(CMAKE_ASM_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_OBJCOPY ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-objcopy) set(CMAKE_STRIP ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-strip) set(CMAKE_AR ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ar) set(CMAKE_RANLIB ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ranlib) set(TOOL_GCOV ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcov) endif() endmacro() macro(set_cross_compiler_userapps) if (USE_SYSCC) set(CMAKE_C_COMPILER "${CMAKE_BINARY_DIR}/scripts/musl-gcc") set(CMAKE_CXX_COMPILER "${CMAKE_BINARY_DIR}/scripts/musl-g++") set(CMAKE_ASM_COMPILER "${CMAKE_BINARY_DIR}/scripts/musl-gcc") set(TOOL_GCOV "${GCOV}") else() # DEFAULT CASE: use our pre-built toolchain set(CMAKE_C_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_CXX_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-g++) set(CMAKE_ASM_COMPILER ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_OBJCOPY ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-objcopy) set(CMAKE_STRIP ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-strip) set(CMAKE_AR ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ar) set(CMAKE_RANLIB ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ranlib) set(TOOL_GCOV ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-gcov) endif() endmacro() macro(set_cross_compiler_gtests) # This macro is used in case ARCH_GTESTS is ON. if (USE_SYSCC) # Special case: the user wants to use system's compiler to compile code # for the target architecture. Just use our basic set_cross_compiler() # macro. set_cross_compiler() else() # DEFAULT CASE: use our pre-built toolchain # We want to use a cross-compiler BUT it has to use glibc instead of # libmusl as libc. set(CMAKE_C_COMPILER ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_CXX_COMPILER ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-g++) set(CMAKE_ASM_COMPILER ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-gcc) set(CMAKE_OBJCOPY ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-objcopy) set(CMAKE_STRIP ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-strip) set(CMAKE_AR ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ar) set(CMAKE_RANLIB ${GCC_TOOLCHAIN}/${ARCH_GCC_TC}-linux-ranlib) set(TOOL_GCOV ${GCC_TOOLCHAIN_GLIBC}/${ARCH_GCC_TC}-linux-gcov) endif() endmacro() #message("CMAKE_ASM_COMPILE_OBJECT: ${CMAKE_ASM_COMPILE_OBJECT}") #message("CMAKE_C_LINK_EXECUTABLE: ${CMAKE_C_LINK_EXECUTABLE}") #message("CMAKE_C_COMPILE_OBJECT: ${CMAKE_C_COMPILE_OBJECT}") #message("CMAKE_C_LINK_FLAGS: ${CMAKE_C_LINK_FLAGS}") #message("CMAKE_CXX_COMPILE_OBJECT: ${CMAKE_CXX_COMPILE_OBJECT}") function(h2d_char hc dec_out) if ("${hc}" MATCHES "[0-9]") set(${dec_out} ${hc} PARENT_SCOPE) elseif ("${hc}" STREQUAL "a") set(${dec_out} 10 PARENT_SCOPE) elseif("${hc}" STREQUAL "b") set(${dec_out} 11 PARENT_SCOPE) elseif("${hc}" STREQUAL "c") set(${dec_out} 12 PARENT_SCOPE) elseif("${hc}" STREQUAL "d") set(${dec_out} 13 PARENT_SCOPE) elseif("${hc}" STREQUAL "e") set(${dec_out} 14 PARENT_SCOPE) elseif("${hc}" STREQUAL "f") set(${dec_out} 15 PARENT_SCOPE) else() message(FATAL_ERROR "Invalid digit '${hc}'") endif() endfunction() function(hex2dec val out) if (NOT "${val}" MATCHES "^0x[0-9a-f]+$") message(FATAL_ERROR "Invalid hex number '${val}'") endif() string(LENGTH "${val}" len) math(EXPR len "${len} - 2") string(SUBSTRING "${val}" 2 ${len} val) # skip the "0x" prefix set(res 0) set(mul 1) math(EXPR len "${len} - 1") foreach (i RANGE "${len}") math(EXPR j "${len} - ${i}") string(SUBSTRING "${val}" ${j} 1 c) h2d_char(${c} c) math(EXPR res "${res} + ${c} * ${mul}") math(EXPR mul "${mul} * 16") if (${res} LESS 0) string(CONCAT err "The hex number 0x${val} is too big " "for CMake: it does not fit in a signed 32-bit int") message(FATAL_ERROR "${err}") endif() endforeach() set(${out} ${res} PARENT_SCOPE) endfunction() function(dec2hex val out) if (NOT "${val}" MATCHES "^[0-9]+$") message(FATAL_ERROR "Invalid decimal number '${val}'") endif() set(hex_chars "0123456789abcdef") set(res "") if (${val} EQUAL 0) set(${out} "0x0" PARENT_SCOPE) else() while (${val} GREATER 0) math (EXPR q "${val} % 16") string(SUBSTRING "${hex_chars}" ${q} 1 c) set(res "${c}${res}") math (EXPR val "${val} / 16") endwhile() set(${out} "0x${res}" PARENT_SCOPE) endif() endfunction() function(smart_config_file src dest) configure_file( ${src} ${dest}.tmp @ONLY ) execute_process( COMMAND ${CMAKE_COMMAND} -E compare_files ${dest}.tmp ${dest} RESULT_VARIABLE NEED_UPDATE OUTPUT_QUIET ERROR_QUIET ) if(NEED_UPDATE) execute_process( COMMAND ${CMAKE_COMMAND} -E rename ${dest}.tmp ${dest} ) else() if(${CMAKE_VERSION} VERSION_LESS "3.17.0") execute_process( COMMAND ${CMAKE_COMMAND} -E remove ${dest}.tmp ) else() # The `remove` command has been deprecated in CMake 3.17 execute_process( COMMAND ${CMAKE_COMMAND} -E rm ${dest}.tmp ) endif() endif() set_source_files_properties(${dest} PROPERTIES GENERATED TRUE) endfunction() <file_sep>/****************************************************************************** * * Name: acpredef - Information table for ACPI predefined methods and objects * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef __ACPREDEF_H__ #define __ACPREDEF_H__ /****************************************************************************** * * Return Package types * * 1) PTYPE1 packages do not contain subpackages. * * ACPI_PTYPE1_FIXED: Fixed-length length, 1 or 2 object types: * object type * count * object type * count * * ACPI_PTYPE1_VAR: Variable-length length. Zero-length package is allowed: * object type (Int/Buf/Ref) * * ACPI_PTYPE1_OPTION: Package has some required and some optional elements * (Used for _PRW) * * * 2) PTYPE2 packages contain a Variable-length number of subpackages. Each * of the different types describe the contents of each of the subpackages. * * ACPI_PTYPE2: Each subpackage contains 1 or 2 object types. Zero-length * parent package is allowed: * object type * count * object type * count * (Used for _ALR,_MLS,_PSS,_TRT,_TSS) * * ACPI_PTYPE2_COUNT: Each subpackage has a count as first element. * Zero-length parent package is allowed: * object type * (Used for _CSD,_PSD,_TSD) * * ACPI_PTYPE2_PKG_COUNT: Count of subpackages at start, 1 or 2 object types: * object type * count * object type * count * (Used for _CST) * * ACPI_PTYPE2_FIXED: Each subpackage is of Fixed-length. Zero-length * parent package is allowed. * (Used for _PRT) * * ACPI_PTYPE2_MIN: Each subpackage has a Variable-length but minimum length. * Zero-length parent package is allowed: * (Used for _HPX) * * ACPI_PTYPE2_REV_FIXED: Revision at start, each subpackage is Fixed-length * (Used for _ART, _FPS) * * ACPI_PTYPE2_FIX_VAR: Each subpackage consists of some fixed-length elements * followed by an optional element. Zero-length parent package is allowed. * object type * count * object type * count = 0 (optional) * (Used for _DLM) * * ACPI_PTYPE2_VAR_VAR: Variable number of subpackages, each of either a * constant or variable length. The subpackages are preceded by a * constant number of objects. * (Used for _LPI, _RDI) * * ACPI_PTYPE2_UUID_PAIR: Each subpackage is preceded by a UUID Buffer. The UUID * defines the format of the package. Zero-length parent package is * allowed. * (Used for _DSD) * *****************************************************************************/ enum AcpiReturnPackageTypes { ACPI_PTYPE1_FIXED = 1, ACPI_PTYPE1_VAR = 2, ACPI_PTYPE1_OPTION = 3, ACPI_PTYPE2 = 4, ACPI_PTYPE2_COUNT = 5, ACPI_PTYPE2_PKG_COUNT = 6, ACPI_PTYPE2_FIXED = 7, ACPI_PTYPE2_MIN = 8, ACPI_PTYPE2_REV_FIXED = 9, ACPI_PTYPE2_FIX_VAR = 10, ACPI_PTYPE2_VAR_VAR = 11, ACPI_PTYPE2_UUID_PAIR = 12, ACPI_PTYPE_CUSTOM = 13 }; /* Support macros for users of the predefined info table */ #define METHOD_PREDEF_ARGS_MAX 4 #define METHOD_ARG_BIT_WIDTH 3 #define METHOD_ARG_MASK 0x0007 #define ARG_COUNT_IS_MINIMUM 0x8000 #define METHOD_MAX_ARG_TYPE ACPI_TYPE_PACKAGE #define METHOD_GET_ARG_COUNT(ArgList) ((ArgList) & METHOD_ARG_MASK) #define METHOD_GET_NEXT_TYPE(ArgList) (((ArgList) >>= METHOD_ARG_BIT_WIDTH) & METHOD_ARG_MASK) /* Macros used to build the predefined info table */ #define METHOD_0ARGS 0 #define METHOD_1ARGS(a1) (1 | (a1 << 3)) #define METHOD_2ARGS(a1,a2) (2 | (a1 << 3) | (a2 << 6)) #define METHOD_3ARGS(a1,a2,a3) (3 | (a1 << 3) | (a2 << 6) | (a3 << 9)) #define METHOD_4ARGS(a1,a2,a3,a4) (4 | (a1 << 3) | (a2 << 6) | (a3 << 9) | (a4 << 12)) #define METHOD_RETURNS(type) (type) #define METHOD_NO_RETURN_VALUE 0 #define PACKAGE_INFO(a,b,c,d,e,f) {{{(a),(b),(c),(d)}, ((((UINT16)(f)) << 8) | (e)), 0}} /* Support macros for the resource descriptor info table */ #define WIDTH_1 0x0001 #define WIDTH_2 0x0002 #define WIDTH_3 0x0004 #define WIDTH_8 0x0008 #define WIDTH_16 0x0010 #define WIDTH_32 0x0020 #define WIDTH_64 0x0040 #define VARIABLE_DATA 0x0080 #define NUM_RESOURCE_WIDTHS 8 #define WIDTH_ADDRESS WIDTH_16 | WIDTH_32 | WIDTH_64 #ifdef ACPI_CREATE_PREDEFINED_TABLE /****************************************************************************** * * Predefined method/object information table. * * These are the names that can actually be evaluated via AcpiEvaluateObject. * Not present in this table are the following: * * 1) Predefined/Reserved names that are not usually evaluated via * AcpiEvaluateObject: * _Lxx and _Exx GPE methods * _Qxx EC methods * _T_x compiler temporary variables * _Wxx wake events * * 2) Predefined names that never actually exist within the AML code: * Predefined resource descriptor field names * * 3) Predefined names that are implemented within ACPICA: * _OSI * * The main entries in the table each contain the following items: * * Name - The ACPI reserved name * ArgumentList - Contains (in 16 bits), the number of required * arguments to the method (3 bits), and a 3-bit type * field for each argument (up to 4 arguments). The * METHOD_?ARGS macros generate the correct packed data. * ExpectedBtypes - Allowed type(s) for the return value. * 0 means that no return value is expected. * * For methods that return packages, the next entry in the table contains * information about the expected structure of the package. This information * is saved here (rather than in a separate table) in order to minimize the * overall size of the stored data. * * Note: The additional braces are intended to promote portability. * * Note2: Table is used by the kernel-resident subsystem, the iASL compiler, * and the AcpiHelp utility. * * TBD: _PRT - currently ignore reversed entries. Attempt to fix in nsrepair. * Possibly fixing package elements like _BIF, etc. * *****************************************************************************/ const ACPI_PREDEFINED_INFO AcpiGbl_PredefinedMethods[] = { {{"_AC0", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC1", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC2", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC3", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC4", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC5", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC6", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC7", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC8", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AC9", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ADR", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_AEI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_AL0", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL1", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL2", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL3", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL4", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL5", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL6", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL7", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL8", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_AL9", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_ALC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ALI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ALP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ALR", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each 2 (Ints) */ PACKAGE_INFO (ACPI_PTYPE2, ACPI_RTYPE_INTEGER, 2,0,0,0), {{"_ALT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ART", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int(rev), n Pkg (2 Ref/11 Int) */ PACKAGE_INFO (ACPI_PTYPE2_REV_FIXED, ACPI_RTYPE_REFERENCE, 2, ACPI_RTYPE_INTEGER, 11,0), {{"_BBN", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BCL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Ints) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 0,0,0,0), {{"_BCM", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_BCT", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BDN", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BFS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_BIF", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (9 Int),(4 Str) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 9, ACPI_RTYPE_STRING, 4,0), {{"_BIX", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (16 Int),(4 Str) */ PACKAGE_INFO (ACPI_PTYPE_CUSTOM, ACPI_RTYPE_INTEGER, 16, ACPI_RTYPE_STRING, 4,0), {{"_BLT", METHOD_3ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_BMA", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BMC", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_BMD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (5 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 5,0,0,0), {{"_BMS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BQC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BST", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (4 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 4,0,0,0), {{"_BTH", METHOD_1ARGS (ACPI_TYPE_INTEGER), /* ACPI 6.0 */ METHOD_NO_RETURN_VALUE}}, {{"_BTM", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_BTP", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_CBA", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* See PCI firmware spec 3.0 */ {{"_CCA", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* ACPI 5.1 */ {{"_CDM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_CID", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Ints/Strs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING, 0,0,0,0), {{"_CLS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (3 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 3,0,0,0), {{"_CPC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Ints/Bufs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER | ACPI_RTYPE_BUFFER, 0,0,0,0), {{"_CR3", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_CRS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_CRT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_CSD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int(n), n-1 Int) */ PACKAGE_INFO (ACPI_PTYPE2_COUNT, ACPI_RTYPE_INTEGER, 0,0,0,0), {{"_CST", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int(n), n Pkg (1 Buf/3 Int) */ PACKAGE_INFO (ACPI_PTYPE2_PKG_COUNT,ACPI_RTYPE_BUFFER, 1, ACPI_RTYPE_INTEGER, 3,0), {{"_CWS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_DCK", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_DCS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_DDC", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER | ACPI_RTYPE_BUFFER)}}, {{"_DDN", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_STRING)}}, {{"_DEP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_DGS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_DIS", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_DLM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (1 Ref, 0/1 Optional Buf/Ref) */ PACKAGE_INFO (ACPI_PTYPE2_FIX_VAR, ACPI_RTYPE_REFERENCE, 1, ACPI_RTYPE_REFERENCE | ACPI_RTYPE_BUFFER, 0,0), {{"_DMA", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_DOD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Ints) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 0,0,0,0), {{"_DOS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_DSD", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each: 1 Buf, 1 Pkg */ PACKAGE_INFO (ACPI_PTYPE2_UUID_PAIR, ACPI_RTYPE_BUFFER, 1, ACPI_RTYPE_PACKAGE, 1,0), {{"_DSM", METHOD_4ARGS (ACPI_TYPE_BUFFER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_PACKAGE), METHOD_RETURNS (ACPI_RTYPE_ALL)}}, /* Must return a value, but it can be of any type */ {{"_DSS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_DSW", METHOD_3ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_DTI", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EC_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_EDL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs)*/ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_EJ0", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EJ1", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EJ2", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EJ3", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EJ4", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_EJD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_STRING)}}, {{"_ERR", METHOD_3ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_STRING, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* Internal use only, used by ACPICA test suites */ {{"_EVT", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_FDE", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_FDI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (16 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 16,0,0,0), {{"_FDM", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_FIF", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (4 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 4,0,0,0), {{"_FIT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, /* ACPI 6.0 */ {{"_FIX", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Ints) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 0,0,0,0), {{"_FPS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int(rev), n Pkg (5 Int) */ PACKAGE_INFO (ACPI_PTYPE2_REV_FIXED,ACPI_RTYPE_INTEGER, 5, 0,0,0), {{"_FSL", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_FST", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (3 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 3,0,0,0), {{"_GAI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GCP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GHL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GLK", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GPD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GPE", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* _GPE method, not _GPE scope */ {{"_GRT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_GSB", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_GTF", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_GTM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_GTS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_GWS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_HID", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING)}}, {{"_HMA", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_HOT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_HPP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (4 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 4,0,0,0), /* * For _HPX, a single package is returned, containing a variable-length number * of subpackages. Each subpackage contains a PCI record setting. * There are several different type of record settings, of different * lengths, but all elements of all settings are Integers. */ {{"_HPX", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (var Ints) */ PACKAGE_INFO (ACPI_PTYPE2_MIN, ACPI_RTYPE_INTEGER, 5,0,0,0), {{"_HRV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_IFT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* See IPMI spec */ {{"_INI", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_IRC", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_LCK", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_LID", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_LPD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int(rev), n Pkg (2 Int) */ PACKAGE_INFO (ACPI_PTYPE2_REV_FIXED, ACPI_RTYPE_INTEGER, 2,0,0,0), {{"_LPI", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (3 Int, n Pkg (10 Int/Buf) */ PACKAGE_INFO (ACPI_PTYPE2_VAR_VAR, ACPI_RTYPE_INTEGER, 3, ACPI_RTYPE_INTEGER | ACPI_RTYPE_BUFFER | ACPI_RTYPE_STRING, 10,0), {{"_LSI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 3,0,0,0), {{"_LSR", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 1, ACPI_RTYPE_BUFFER, 1,0), {{"_LSW", METHOD_3ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_BUFFER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_MAT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_MBM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (8 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 8,0,0,0), {{"_MLS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (1 Str/1 Buf) */ PACKAGE_INFO (ACPI_PTYPE2, ACPI_RTYPE_STRING, 1, ACPI_RTYPE_BUFFER, 1,0), {{"_MSG", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_MSM", METHOD_4ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_MTL", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_NBS", METHOD_0ARGS, /* ACPI 6.3 */ METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_NCH", METHOD_0ARGS, /* ACPI 6.3 */ METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_NIC", METHOD_0ARGS, /* ACPI 6.3 */ METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_NIG", METHOD_0ARGS, /* ACPI 6.3 */ METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_NIH", METHOD_1ARGS (ACPI_TYPE_BUFFER), /* ACPI 6.3 */ METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_NTT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_OFF", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_ON_", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_OS_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_STRING)}}, {{"_OSC", METHOD_4ARGS (ACPI_TYPE_BUFFER, ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_BUFFER), METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_OST", METHOD_3ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER, ACPI_TYPE_BUFFER), METHOD_NO_RETURN_VALUE}}, {{"_PAI", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PCL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PCT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (2 Buf) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_BUFFER, 2,0,0,0), {{"_PDC", METHOD_1ARGS (ACPI_TYPE_BUFFER), METHOD_NO_RETURN_VALUE}}, {{"_PDL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PIC", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_PIF", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (3 Int),(3 Str) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 3, ACPI_RTYPE_STRING, 3,0), {{"_PLD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Bufs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_BUFFER, 0,0,0,0), {{"_PMC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (11 Int),(3 Str) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 11, ACPI_RTYPE_STRING, 3,0), {{"_PMD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PMM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PPC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PPE", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* See dig64 spec */ {{"_PR0", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PR1", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PR2", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PR3", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PRE", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PRL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PRR", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Ref) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_REFERENCE, 1,0,0,0), {{"_PRS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, /* * For _PRT, many BIOSs reverse the 3rd and 4th Package elements (Source * and SourceIndex). This bug is so prevalent that there is code in the * ACPICA Resource Manager to detect this and switch them back. For now, * do not allow and issue a warning. To allow this and eliminate the * warning, add the ACPI_RTYPE_REFERENCE type to the 4th element (index 3) * in the statement below. */ {{"_PRT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (4): Int,Int,Int/Ref,Int */ PACKAGE_INFO (ACPI_PTYPE2_FIXED, 4, ACPI_RTYPE_INTEGER, ACPI_RTYPE_INTEGER, ACPI_RTYPE_INTEGER | ACPI_RTYPE_REFERENCE, ACPI_RTYPE_INTEGER), {{"_PRW", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each: Pkg/Int,Int,[Variable-length Refs] (Pkg is Ref/Int) */ PACKAGE_INFO (ACPI_PTYPE1_OPTION, 2, ACPI_RTYPE_INTEGER | ACPI_RTYPE_PACKAGE, ACPI_RTYPE_INTEGER, ACPI_RTYPE_REFERENCE, 0), {{"_PS0", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_PS1", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_PS2", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_PS3", METHOD_0ARGS, METHOD_NO_RETURN_VALUE}}, {{"_PSC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PSD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (5 Int) with count */ PACKAGE_INFO (ACPI_PTYPE2_COUNT, ACPI_RTYPE_INTEGER, 0,0,0,0), {{"_PSE", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_PSL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_PSR", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PSS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each (6 Int) */ PACKAGE_INFO (ACPI_PTYPE2, ACPI_RTYPE_INTEGER, 6,0,0,0), {{"_PSV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PSW", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_PTC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (2 Buf) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_BUFFER, 2,0,0,0), {{"_PTP", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_PTS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_PUR", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (2 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 2,0,0,0), {{"_PXM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_RDI", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (1 Int, n Pkg (m Ref)) */ PACKAGE_INFO (ACPI_PTYPE2_VAR_VAR, ACPI_RTYPE_INTEGER, 1, ACPI_RTYPE_REFERENCE,0,0), {{"_REG", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_REV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_RMV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_ROM", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_RST", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_NO_RETURN_VALUE}}, {{"_RTV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* * For _S0_ through _S5_, the ACPI spec defines a return Package * containing 1 Integer, but most DSDTs have it wrong - 2,3, or 4 integers. * Allow this by making the objects "Variable-length length", but all elements * must be Integers. */ {{"_S0_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S1_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S2_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S3_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S4_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S5_", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (1 Int) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 1,0,0,0), {{"_S1D", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S2D", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S3D", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S4D", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S0W", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S1W", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S2W", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S3W", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_S4W", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SBS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SCP", METHOD_1ARGS (ACPI_TYPE_INTEGER) | ARG_COUNT_IS_MINIMUM, METHOD_NO_RETURN_VALUE}}, /* Acpi 1.0 allowed 1 integer arg. Acpi 3.0 expanded to 3 args. Allow both. */ {{"_SDD", METHOD_1ARGS (ACPI_TYPE_BUFFER), METHOD_NO_RETURN_VALUE}}, {{"_SEG", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SHL", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SLI", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_SPD", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SRS", METHOD_1ARGS (ACPI_TYPE_BUFFER), METHOD_NO_RETURN_VALUE}}, {{"_SRT", METHOD_1ARGS (ACPI_TYPE_BUFFER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SRV", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* See IPMI spec */ {{"_SST", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_STA", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_STM", METHOD_3ARGS (ACPI_TYPE_BUFFER, ACPI_TYPE_BUFFER, ACPI_TYPE_BUFFER), METHOD_NO_RETURN_VALUE}}, {{"_STP", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_STR", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_STV", METHOD_2ARGS (ACPI_TYPE_INTEGER, ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SUB", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_STRING)}}, {{"_SUN", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_SWS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TC1", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TC2", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TDL", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TFP", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TIP", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TIV", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TMP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TPC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TPT", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_TRT", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each 2 Ref/6 Int */ PACKAGE_INFO (ACPI_PTYPE2, ACPI_RTYPE_REFERENCE, 2, ACPI_RTYPE_INTEGER, 6, 0), {{"_TSD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each 5 Int with count */ PACKAGE_INFO (ACPI_PTYPE2_COUNT,ACPI_RTYPE_INTEGER, 5,0,0,0), {{"_TSN", METHOD_0ARGS, /* ACPI 6.0 */ METHOD_RETURNS (ACPI_RTYPE_REFERENCE)}}, {{"_TSP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TSS", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Pkgs) each 5 Int */ PACKAGE_INFO (ACPI_PTYPE2, ACPI_RTYPE_INTEGER, 5,0,0,0), {{"_TST", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_TTS", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_NO_RETURN_VALUE}}, {{"_TZD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Variable-length (Refs) */ PACKAGE_INFO (ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0,0,0), {{"_TZM", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_REFERENCE)}}, {{"_TZP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_UID", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING)}}, {{"_UPC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_PACKAGE)}}, /* Fixed-length (4 Int) */ PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 4,0,0,0), {{"_UPD", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_UPP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, {{"_VPO", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* Acpi 1.0 defined _WAK with no return value. Later, it was changed to return a package */ {{"_WAK", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_NONE | ACPI_RTYPE_INTEGER | ACPI_RTYPE_PACKAGE)}}, PACKAGE_INFO (ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 2,0,0,0), /* Fixed-length (2 Int), but is optional */ /* _WDG/_WED are MS extensions defined by "Windows Instrumentation" */ {{"_WDG", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_BUFFER)}}, {{"_WED", METHOD_1ARGS (ACPI_TYPE_INTEGER), METHOD_RETURNS (ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_BUFFER)}}, {{"_WPC", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* ACPI 6.1 */ {{"_WPP", METHOD_0ARGS, METHOD_RETURNS (ACPI_RTYPE_INTEGER)}}, /* ACPI 6.1 */ PACKAGE_INFO (0,0,0,0,0,0) /* Table terminator */ }; #else extern const ACPI_PREDEFINED_INFO AcpiGbl_PredefinedMethods[]; #endif #if (defined ACPI_CREATE_RESOURCE_TABLE && defined ACPI_APPLICATION) /****************************************************************************** * * Predefined names for use in Resource Descriptors. These names do not * appear in the global Predefined Name table (since these names never * appear in actual AML byte code, only in the original ASL) * * Note: Used by iASL compiler and AcpiHelp utility only. * *****************************************************************************/ const ACPI_PREDEFINED_INFO AcpiGbl_ResourceNames[] = { {{"_ADR", WIDTH_16 | WIDTH_64, 0}}, {{"_ALN", WIDTH_8 | WIDTH_16 | WIDTH_32, 0}}, {{"_ASI", WIDTH_8, 0}}, {{"_ASZ", WIDTH_8, 0}}, {{"_ATT", WIDTH_64, 0}}, {{"_BAS", WIDTH_16 | WIDTH_32, 0}}, {{"_BM_", WIDTH_1, 0}}, {{"_DBT", WIDTH_16, 0}}, /* Acpi 5.0 */ {{"_DEC", WIDTH_1, 0}}, {{"_DMA", WIDTH_8, 0}}, {{"_DPL", WIDTH_1, 0}}, /* Acpi 5.0 */ {{"_DRS", WIDTH_16, 0}}, /* Acpi 5.0 */ {{"_END", WIDTH_1, 0}}, /* Acpi 5.0 */ {{"_FLC", WIDTH_2, 0}}, /* Acpi 5.0 */ {{"_GRA", WIDTH_ADDRESS, 0}}, {{"_HE_", WIDTH_1, 0}}, {{"_INT", WIDTH_16 | WIDTH_32, 0}}, {{"_IOR", WIDTH_2, 0}}, /* Acpi 5.0 */ {{"_LEN", WIDTH_8 | WIDTH_ADDRESS, 0}}, {{"_LIN", WIDTH_8, 0}}, /* Acpi 5.0 */ {{"_LL_", WIDTH_1, 0}}, {{"_MAF", WIDTH_1, 0}}, {{"_MAX", WIDTH_ADDRESS, 0}}, {{"_MEM", WIDTH_2, 0}}, {{"_MIF", WIDTH_1, 0}}, {{"_MIN", WIDTH_ADDRESS, 0}}, {{"_MOD", WIDTH_1, 0}}, /* Acpi 5.0 */ {{"_MTP", WIDTH_2, 0}}, {{"_PAR", WIDTH_8, 0}}, /* Acpi 5.0 */ {{"_PHA", WIDTH_1, 0}}, /* Acpi 5.0 */ {{"_PIN", WIDTH_16, 0}}, /* Acpi 5.0 */ {{"_PPI", WIDTH_8, 0}}, /* Acpi 5.0 */ {{"_POL", WIDTH_1 | WIDTH_2, 0}}, /* Acpi 5.0 */ {{"_RBO", WIDTH_8, 0}}, {{"_RBW", WIDTH_8, 0}}, {{"_RNG", WIDTH_1, 0}}, {{"_RT_", WIDTH_8, 0}}, /* Acpi 3.0 */ {{"_RW_", WIDTH_1, 0}}, {{"_RXL", WIDTH_16, 0}}, /* Acpi 5.0 */ {{"_SHR", WIDTH_2, 0}}, {{"_SIZ", WIDTH_2, 0}}, {{"_SLV", WIDTH_1, 0}}, /* Acpi 5.0 */ {{"_SPE", WIDTH_32, 0}}, /* Acpi 5.0 */ {{"_STB", WIDTH_2, 0}}, /* Acpi 5.0 */ {{"_TRA", WIDTH_ADDRESS, 0}}, {{"_TRS", WIDTH_1, 0}}, {{"_TSF", WIDTH_8, 0}}, /* Acpi 3.0 */ {{"_TTP", WIDTH_1, 0}}, {{"_TXL", WIDTH_16, 0}}, /* Acpi 5.0 */ {{"_TYP", WIDTH_2 | WIDTH_16, 0}}, {{"_VEN", VARIABLE_DATA, 0}}, /* Acpi 5.0 */ PACKAGE_INFO (0,0,0,0,0,0) /* Table terminator */ }; const ACPI_PREDEFINED_INFO AcpiGbl_ScopeNames[] = { {{"_GPE", 0, 0}}, {{"_PR_", 0, 0}}, {{"_SB_", 0, 0}}, {{"_SI_", 0, 0}}, {{"_TZ_", 0, 0}}, PACKAGE_INFO (0,0,0,0,0,0) /* Table terminator */ }; #else extern const ACPI_PREDEFINED_INFO AcpiGbl_ResourceNames[]; #endif #endif <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # GLOBAL VARIABLES # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/../.. && pwd)" # Include files source $MAIN_DIR/scripts/bash_includes/script_utils function show_help { echo "" echo "This script will create the directory other_builds and build Tilck and" echo "its tests in a variety of configurations, some of which them are not" echo "very common. In order to all the builds to succeed, additional " echo "packages are expected to be installed in the host system, other than" echo -ne "the ones installed by the ${GREEN}build_toolchain${RATTRS} script." echo -ne " In addition, the\n" echo "script needs to be run multiple times in order to download & build " echo "optional components. In particular:" echo "" echo " - gcc-multilib (debian package name)" echo " [A version of gcc able to build i386 binaries on x86_64]" echo " [Use your package manager to install that on your system]" echo "" echo " - clang and clang++" echo " [Use your package manager to install that on your system]" echo "" echo " - toolchain2/host/gtest" echo " [Get with: build_toolchain -s build_gtest]" echo "" echo " - toolchain2/i386/gtest" echo " [Get with: build_toolchain -s build_gtest_arch]" echo "" echo " - toolchain2/noarch/lcov" echo " [Get with: build_toolchain -s build_lcov]" echo "" echo " - toolchain2/i386/musl" echo " [Get with: build_toolchain -s build_libmusl]" echo "" echo "Build configurations that will be generated and built:" for x in $MAIN_DIR/scripts/build_generators/*; do echo " - $(basename $x)" done echo "" echo -ne "${RED}WARNING${RATTRS}: if you're new to Tilck, that's probably " echo -ne "${RED}not${RATTRS} the script you're looking\nfor. " echo -ne "${BROWN}Check out${RATTRS} the docs/building.md file for info " echo -ne "about how to build Tilck and\nthe docs/testing.md file for info " echo -ne "about how to run its tests.\n" echo "" } function ask_confirm { show_help echo -n "Proceed [y/N] ? " read answer if [[ "$answer" != "y" ]]; then exit 0 fi } ############################################# # MAIN CODE # Exit on any error set -e if [[ "$1" == "-h" || "$1" == "--help" ]]; then show_help exit 0 fi if [[ "$1" != "-y" ]]; then ask_confirm fi mkdir -p $MAIN_DIR/other_builds cd $MAIN_DIR/other_builds for gen_script in $MAIN_DIR/scripts/build_generators/*; do name=$(basename $gen_script) echo "************ Build: $name ************" mkdir -p $name pushd $name $gen_script make -j 4 make -j 4 gtests popd done <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/bintree.h> struct debug_kmalloc_heap_info { ulong vaddr; size_t size; size_t mem_allocated; size_t min_block_size; size_t alloc_block_size; int region; }; struct kmalloc_small_heaps_stats { int tot_count; int peak_count; int not_full_count; int peak_not_full_count; int empty_count; int lifetime_created_heaps_count; }; struct debug_kmalloc_chunks_ctx { struct bintree_walk_ctx ctx; }; struct debug_kmalloc_stats { struct kmalloc_small_heaps_stats small_heaps; size_t chunk_sizes_count; }; bool debug_kmalloc_get_heap_info(int heap_num, struct debug_kmalloc_heap_info *i); void debug_kmalloc_get_heap_info_by_ptr(struct kmalloc_heap *h, struct debug_kmalloc_heap_info *i); void debug_kmalloc_get_stats(struct debug_kmalloc_stats *stats); void debug_kmalloc_chunks_stats_start_read(struct debug_kmalloc_chunks_ctx *ctx); bool debug_kmalloc_chunks_stats_next(struct debug_kmalloc_chunks_ctx *ctx, size_t *size, size_t *count); /* Leak-detector and kmalloc logging */ void debug_kmalloc_start_leak_detector(bool save_metadata); void debug_kmalloc_stop_leak_detector(bool show_leaks); void debug_kmalloc_start_log(void); void debug_kmalloc_stop_log(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include <errno.h> #include <time.h> #include <inttypes.h> #include <unistd.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/kd.h> #include <fcntl.h> #include <poll.h> #include <x86intrin.h> /* for __rdtsc() */ #ifdef USERMODE_APP /* The application is compiled with Tilck's build system */ #include <tilck/common/debug/termios_debug.c.h> #else #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) #endif #define RDTSC() __rdtsc() #define CSI_ERASE_DISPLAY "\033[2J" #define CSI_MOVE_CURSOR_TOP_LEFT "\033[1;1H" struct termios orig_termios; void term_set_raw_mode(void) { struct termios t = orig_termios; printf("Setting tty to 'raw' mode\n"); // "Full" raw mode t.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); t.c_oflag &= ~(OPOST); t.c_cflag |= (CS8); t.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); tcsetattr(0, TCSAFLUSH, &t); } void save_termios(void) { tcgetattr(0, &orig_termios); } void restore_termios(void) { tcsetattr(0, TCSAFLUSH, &orig_termios); ioctl(0, KDSKBMODE, K_XLATE); } void one_read(void) { int ret; char buf[32]; printf("one byte RAW read\n"); term_set_raw_mode(); ret = read(0, buf, 32); printf("read(%d): ", ret); for (int i = 0; i < ret; i++) { if (buf[i] == '\033') printf("ESC "); else if (buf[i] == '\n') printf("NL "); else if (buf[i] == '\r') printf("CR "); else if (isprint(buf[i])) printf("%c ", buf[i]); else printf("[%#x] ", buf[i]); } printf("\n"); } void echo_read(void) { int ret; char buf[16]; printf("echo_read()\n"); term_set_raw_mode(); while (1) { ret = read(0, buf, sizeof(buf)); write(1, buf, ret); if (ret == 1 && (buf[0] == '\n' || buf[0] == '\r')) break; } } void show_read_res(int r, char c) { if (r > 0) printf("read(%d): %#x\n", r, c); else printf("read(%d)\n", r); } void read_1_canon_mode(void) { char buf[32] = {0}; int r; printf("read_1_canon_mode(): read 2 chars, one-by-one\n"); r = read(0, buf, 1); show_read_res(r, buf[0]); r = read(0, buf, 1); show_read_res(r, buf[0]); } void read_canon_mode(void) { char buf[32] = {0}; int r; printf("Regular read in canonical mode\n"); r = read(0, buf, 32); printf("read(%d): %s", r, buf); } void read_ttys0_canon_mode(void) { char buf[32] = {0}; int r, fd; fd = open("/dev/ttyS0", O_RDONLY); if (fd < 0) { perror("Open /dev/ttyS0 failed"); return; } printf("Regular read from /dev/ttyS0 in canonical mode\n"); r = read(fd, buf, 32); printf("read(%d): %s", r, buf); close(fd); } void write_to_stdin(void) { char c = 'a'; int r; printf("Write 'a' to stdin\n"); r = write(0, &c, 1); printf("write() -> %d\n", r); printf("now read 1 byte from stdin\n"); r = read(0, &c, 1); printf("read(%d): %#x\n", r, c); } double timespec_diff(const struct timespec *t1, const struct timespec *t0) { return (t1->tv_sec - t0->tv_sec) + (t1->tv_nsec - t0->tv_nsec) / 1.0e9; } void timespec_to_human_str(char *buf, size_t bufsz, double t) { if (t >= 1.0) snprintf(buf, bufsz, "%7.3f s", t); else if (t >= 0.001) snprintf(buf, bufsz, "%7.3f ms", t * 1.0e3); else if (t >= 0.000001) snprintf(buf, bufsz, "%7.3f us", t * 1.0e6); else snprintf(buf, bufsz, "%7.3f ns", t * 1.0e9); } void console_perf_test(void) { static const char letters[] = "ABCDEFGHIJ<KEY>"; int iters = 3; struct winsize w; char *buf, tot_time_s[32], c_time_s[32]; ssize_t r, tot, written; struct timespec ts_before, ts_after; uint64_t start, end, c; double tot_time_real, tot_time, time_c, cycles_per_sec; if (ioctl(1, TIOCGWINSZ, &w) != 0) { perror("ioctl() failed"); return; } tot = w.ws_row * w.ws_col; buf = malloc(tot); if (!buf) { fprintf(stderr, "Out of memory\n"); return; } for (int i = 0; i < tot; i++) { buf[i] = letters[i % (sizeof(letters) - 1)]; } printf("%s", CSI_ERASE_DISPLAY CSI_MOVE_CURSOR_TOP_LEFT); retry: clock_gettime(CLOCK_REALTIME, &ts_before); start = RDTSC(); for (int i = 0; i < iters; i++) { for (r = 0, written = 0; written < tot; written += r) { r = write(1, buf + written, tot - written); if (r < 0) { perror("write() failed"); return; } } } end = RDTSC(); clock_gettime(CLOCK_REALTIME, &ts_after); c = (end - start) / iters; tot_time_real = timespec_diff(&ts_after, &ts_before); tot_time = tot_time_real / iters; time_c = tot_time / (double)tot; cycles_per_sec = (end - start) / tot_time_real; if (tot_time_real <= 0.1) { /* * We're way too fast: it makes sense to do more iterations to gain a * more accurate measurement. */ iters *= 10; goto retry; } timespec_to_human_str(tot_time_s, sizeof(tot_time_s), tot_time); timespec_to_human_str(c_time_s, sizeof(c_time_s), time_c); printf("Term size: %d rows x %d cols\n", w.ws_row, w.ws_col); printf("Tot iterations: %d\n\n", iters); printf("Screen redraw: %12" PRIu64 " cycles (%s)\n", c, tot_time_s); printf("Avg. character cost: %12" PRIu64 " cycles (%s)\n", c/tot, c_time_s); printf("Cycles per sec: %12.0f cycles/sec\n", cycles_per_sec); free(buf); } void read_nonblock(void) { int rc; char buf[32]; int saved_flags = fcntl(0, F_GETFL, 0); printf("Setting non-block mode for fd 0\r\n"); rc = fcntl(0, F_SETFL, saved_flags | O_NONBLOCK); if (rc != 0) { fprintf(stderr, "fcntl() failed: %s\r\n", strerror(errno)); return; } for (int i = 0; ; i++) { rc = read(0, buf, 1); if (rc >= 0) { buf[rc] = 0; printf("[iter %d] read() = %d [buf: '%s']\r\n", i, rc, buf); if (buf[0] == 'q') break; } else { printf("[iter %d] read() = %d (errno: %d => %s)\r\n", i, rc, errno, strerror(errno)); usleep(500*1000); } } // Restore the original flags rc = fcntl(0, F_SETFL, saved_flags); if (rc != 0) fprintf(stderr, "fcntl() failed: %s\r\n", strerror(errno)); } void read_nonblock_rawmode(void) { term_set_raw_mode(); read_nonblock(); } static void write_full_row(void) { struct winsize w; ioctl(1, TIOCGWINSZ, &w); printf("Term size: %d rows x %d cols\n\n", w.ws_row, w.ws_col); printf("TEST 1) Full row with '-':\n"); for (int i = 0; i < w.ws_col; i++) putchar('-'); printf("[text after full row]\n\n\n"); printf("TEST 2) Now full row with '-' + \\n\n"); for (int i = 0; i < w.ws_col; i++) putchar('-'); putchar('\n'); printf("[text after full row]\n\n"); } static void sleep_then_read(void) { char buf[32] = {0}; int rc; printf("sleep\n"); sleep(2); printf("sleep done, reading\n"); rc = read(0, buf, sizeof(buf)); printf("read(): %d -> '%s'\n", rc, buf); } static void sym_read(void) { char buf[32] = {0}; int rc; if (!fork()) { printf("[child]\n"); rc = read(0, buf, sizeof(buf)); printf("[child] read(): %d -> '%s'\n", rc, buf); exit(0); } printf("[parent] reading...\n"); rc = read(0, buf, sizeof(buf)); printf("[parent] read(): %d -> '%s'\n", rc, buf); waitpid(-1, NULL, 0); } static void poll_and_read(void) { char buf[32] = {0}; int rc, pos = 0; struct pollfd fds[] = { { .fd = 0, .events = POLLIN, .revents = 0 } }; printf("Setting TTY in raw mode\n"); term_set_raw_mode(); while (1) { rc = poll(fds, 1 /* nfds */, 1000 /* ms */); printf("poll() -> %d\r\n", rc); if (rc > 0) { if (fds[0].revents & POLLIN) { printf("fd %d -> POLLIN\r\n", fds[0].fd); break; } if (fds[0].revents & POLLPRI) printf("fd %d -> POLLPRI\r\n", fds[0].fd); if (fds[0].revents & POLLRDHUP) printf("fd %d -> POLLRDHUP\r\n", fds[0].fd); if (fds[0].revents & POLLERR) printf("fd %d -> POLLERR\r\n", fds[0].fd); if (fds[0].revents & POLLHUP) printf("fd %d -> POLLHUP\r\n", fds[0].fd); if (fds[0].revents & POLLNVAL) printf("fd %d -> POLLNVAL\r\n", fds[0].fd); } } printf("poll() said there's something to read. read():\r\n"); for (pos = 0; pos < 32; pos++) { rc = read(0, buf + pos, 1); printf("read() -> %d\r\n", rc); printf("buf[%d]: %#x\r\n", pos, (unsigned)buf[pos]); rc = poll(fds, 1 /* nfds */, 50 /* ms */); printf("poll() -> %d\r\n", rc); if (rc > 0) { if (fds[0].revents & POLLIN) { printf("fd %d -> POLLIN\r\n", fds[0].fd); continue; } } printf("Nothing more to read, break\r\n"); break; } } static void medium_raw_read(void) { char c; int rc; if (ioctl(0, KDSKBMODE, K_MEDIUMRAW) != 0) { printf("Unable to set mediumraw mode.\r\n"); return; } term_set_raw_mode(); do { rc = read(0, &c, 1); if (!rc) break; if (c & 0x80) printf("released %#x", (unsigned char)(c & ~0x80)); else printf("PRESSED %#x", (unsigned char)(c & ~0x80)); printf("\r\n"); } while (c != 0x10 /* q */); } #ifdef USERMODE_APP static void dump_termios(void) { debug_dump_termios(&orig_termios); } #endif #define CMD_ENTRY(opt, func) { (opt), #func, &func } static struct { const char *opt; const char *func_name; void (*func)(void); } commands[] = { CMD_ENTRY("-r", one_read), CMD_ENTRY("-e", echo_read), CMD_ENTRY("-1", read_1_canon_mode), CMD_ENTRY("-c", read_canon_mode), CMD_ENTRY("-w", write_to_stdin), #ifdef USERMODE_APP CMD_ENTRY("-s", dump_termios), #endif CMD_ENTRY("-p", console_perf_test), CMD_ENTRY("-n", read_nonblock), CMD_ENTRY("-nr", read_nonblock_rawmode), CMD_ENTRY("-fr", write_full_row), CMD_ENTRY("-sr", sleep_then_read), CMD_ENTRY("-mr", sym_read), CMD_ENTRY("-cs", read_ttys0_canon_mode), CMD_ENTRY("-pr", poll_and_read), CMD_ENTRY("-xmr", medium_raw_read), }; static void show_help(void) { printf("Options:\n"); for (size_t i = 0; i < ARRAY_SIZE(commands); i++) { printf(" %-3s %s()\n", commands[i].opt, commands[i].func_name); } } int main(int argc, char ** argv) { void (*cmdfunc)(void) = show_help; if (argc < 2) { show_help(); return 1; } for (size_t i = 0; i < ARRAY_SIZE(commands); i++) { if (!strcmp(argv[1], commands[i].opt)) { cmdfunc = commands[i].func; break; } } save_termios(); cmdfunc(); restore_termios(); if (cmdfunc != &show_help) printf("\rOriginal tty mode restored\n"); return 0; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_boot.h> #include <tilck/common/basic_defs.h> #include <tilck/common/page_size.h> #include <tilck/common/assert.h> #include <tilck/common/fat32_base.h> #include <tilck/common/utils.h> #include "defs.h" #include "utils.h" struct load_ramdisk_ctx { EFI_BLOCK_IO_PROTOCOL *blockio; UINT32 total_fat_size; UINT32 rounded_tot_fat_sz; /* Rounded up at PAGE_SIZE */ UINT32 tot_used_bytes; UINT32 rounded_tot_used_bytes; /* Rounded up at PAGE_SIZE */ void *fat_hdr; }; static EFI_STATUS LoadRamdisk_GetTotFatSize(struct load_ramdisk_ctx *ctx) { const UINTN initrd_off = INITRD_SECTOR * SECTOR_SIZE; EFI_PHYSICAL_ADDRESS paddr = 0; EFI_STATUS status; UINT32 fat_sec_sz; void *fat_hdr; status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, /* just 1 page */ &paddr); HANDLE_EFI_ERROR("AllocatePages"); fat_hdr = TO_PTR(paddr); status = ReadAlignedBlock(ctx->blockio, initrd_off, PAGE_SIZE, fat_hdr); HANDLE_EFI_ERROR("ReadAlignedBlock"); fat_sec_sz = fat_get_sector_size(fat_hdr); ctx->total_fat_size = (fat_get_first_data_sector(fat_hdr) + 1) * fat_sec_sz; ctx->rounded_tot_fat_sz = round_up_at(ctx->total_fat_size, PAGE_SIZE); status = BS->FreePages(paddr, 1); HANDLE_EFI_ERROR("FreePages"); end: return status; } static EFI_STATUS LoadRamdisk_GetTotUsedBytes(struct load_ramdisk_ctx *ctx) { const UINTN initrd_off = INITRD_SECTOR * SECTOR_SIZE; EFI_PHYSICAL_ADDRESS paddr = 0; EFI_STATUS status; void *fat_hdr; /* Allocate memory for storing the whole FAT table */ status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData, ctx->rounded_tot_fat_sz / PAGE_SIZE, &paddr); HANDLE_EFI_ERROR("AllocatePages"); fat_hdr = TO_PTR(paddr); status = ReadAlignedBlock(ctx->blockio, initrd_off, ctx->total_fat_size, fat_hdr); HANDLE_EFI_ERROR("ReadAlignedBlock"); ctx->tot_used_bytes = fat_calculate_used_bytes(fat_hdr); ctx->rounded_tot_used_bytes = round_up_at(ctx->tot_used_bytes, PAGE_SIZE); /* * Now we know everything. Free the memory used so far and allocate the * big buffer to store all the "used" clusters of the FAT32 partition, * including clearly the header and the FAT table. */ status = BS->FreePages(paddr, ctx->rounded_tot_fat_sz / PAGE_SIZE); HANDLE_EFI_ERROR("FreePages"); end: return status; } static EFI_STATUS LoadRamdisk_CompactClusters(struct load_ramdisk_ctx *ctx) { EFI_STATUS status = EFI_SUCCESS; void *fat_hdr = ctx->fat_hdr; UINT32 ff_clu_off; ff_clu_off = fat_get_first_free_cluster_off(fat_hdr); if (ff_clu_off < ctx->tot_used_bytes) { Print(L"Compacting ramdisk... "); fat_compact_clusters(fat_hdr); ff_clu_off = fat_get_first_free_cluster_off(fat_hdr); ctx->tot_used_bytes = fat_calculate_used_bytes(fat_hdr); if (ctx->tot_used_bytes != ff_clu_off) { Print(L"fat_compact_clusters failed: %u != %u\n", ctx->tot_used_bytes, ff_clu_off); status = EFI_ABORTED; goto end; } write_ok_msg(); } end: return status; } static EFI_STATUS LoadRamdisk_AllocMem(struct load_ramdisk_ctx *ctx) { EFI_STATUS status; EFI_PHYSICAL_ADDRESS paddr; /* * Because Tilck is 32-bit and it maps the first LINEAR_MAPPING_SIZE of * physical memory at KERNEL_BASE_VA, we really cannot accept ANY address * in the 64-bit space, because from Tilck we won't be able to read from * there. The address of the ramdisk we actually be at most: * * LINEAR_MAPPING_SIZE - "size of ramdisk" * * The AllocateMaxAddress allocation type is exactly what we need to use in * this case. As explained in the UEFI specification: * * Allocation requests of Type AllocateMaxAddress allocate any available * range of pages whose uppermost address is less than or equal to the * address pointed to by Memory on input. * * Additional notes * -------------------------- * Note the `(ctx.rounded_tot_used_bytes / PAGE_SIZE) + 1` expression below. * * +1 page is allocated to allow, evenutally, the Tilck kernel * to align it's data clusters at page boundary. */ paddr = LINEAR_MAPPING_SIZE; status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, (ctx->rounded_tot_used_bytes / PAGE_SIZE) + 1, &paddr); HANDLE_EFI_ERROR("AllocatePages"); ctx->fat_hdr = TO_PTR(paddr); end: return status; } static EFI_STATUS GetPhysBlockIODeviceHandle(EFI_LOADED_IMAGE *img, EFI_HANDLE *ref) { EFI_DEVICE_PATH *parentDpCopy = NULL; EFI_HANDLE parentDpHandle = NULL; EFI_STATUS status; parentDpCopy = GetCopyOfParentDevicePathNode( DevicePathFromHandle(img->DeviceHandle) ); status = GetHandlerForDevicePath(parentDpCopy, &BlockIoProtocol, &parentDpHandle); HANDLE_EFI_ERROR("GetHandlerForDevicePath"); /* Everything is OK, we can return the handle via the OUT parameter */ *ref = parentDpHandle; end: if (parentDpCopy) FreePool(parentDpCopy); return status; } EFI_STATUS ReserveMemAreaForKernelImage(void) { EFI_PHYSICAL_ADDRESS p; for (p = KERNEL_PADDR; p < KERNEL_PADDR + 4 * MB; p += 16 * PAGE_SIZE) { EFI_PHYSICAL_ADDRESS tmp = p; BS->AllocatePages(AllocateAddress, EfiBootServicesData, 16, &tmp); /* * NOTE: it does NOT matter if AllocatePages() fails or not. What we need * to enforce is just that after KERNEL_PADDR there are at least 4 MB of * memory not usable for the ramdisk. That's because AllocatePages() does * not have an "AllocateMinAddress" parameter and it's unsafe to assume * that the ramdisk just won't be placed there. If the ramdisk is placed * there, kernel's image (see simple_elf_loader()) will simply overwrite * it and that's pretty undesirable. */ } return EFI_SUCCESS; } EFI_STATUS LoadRamdisk(EFI_HANDLE image, EFI_LOADED_IMAGE *loadedImg, EFI_PHYSICAL_ADDRESS *rd_paddr_ref, UINTN *rd_size_ref) { const UINTN initrd_off = INITRD_SECTOR * SECTOR_SIZE; EFI_STATUS status = EFI_SUCCESS; EFI_HANDLE bioDeviceHandle = NULL; struct load_ramdisk_ctx ctx = {0}; status = GetPhysBlockIODeviceHandle(loadedImg, &bioDeviceHandle); HANDLE_EFI_ERROR("GetPhysBlockIODeviceHandle"); status = BS->OpenProtocol(bioDeviceHandle, &BlockIoProtocol, (void **)&ctx.blockio, image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); HANDLE_EFI_ERROR("OpenProtocol(BlockIoProtocol)"); Print(LOADING_INITRD_STR_U); status = LoadRamdisk_GetTotFatSize(&ctx); HANDLE_EFI_ERROR("LoadRamdisk_GetTotFatSize"); status = LoadRamdisk_GetTotUsedBytes(&ctx); HANDLE_EFI_ERROR("LoadRamdisk_GetTotUsedBytes"); status = LoadRamdisk_AllocMem(&ctx); HANDLE_EFI_ERROR("LoadRamdisk_AllocMem"); status = ReadDiskWithProgress(ST->ConOut, LOADING_INITRD_STR_U, ctx.blockio, initrd_off, ctx.rounded_tot_used_bytes, ctx.fat_hdr); HANDLE_EFI_ERROR("ReadDiskWithProgress"); /* Now we're done with the BlockIoProtocol, close it. */ BS->CloseProtocol(bioDeviceHandle, &BlockIoProtocol, image, NULL); ctx.blockio = NULL; ST->ConOut->SetCursorPosition(ST->ConOut, 0, ST->ConOut->Mode->CursorRow); Print(LOADING_INITRD_STR_U); write_ok_msg(); status = LoadRamdisk_CompactClusters(&ctx); HANDLE_EFI_ERROR("LoadRamdisk_CompactClusters"); /* * Pass via multiboot 'used bytes' as RAMDISK size instead of the real * RAMDISK size. This is useful if the kernel uses the RAMDISK read-only. * * Note[1]: we've increased the value by 1 page in order to allow Tilck's * kernel to align the first data sector, if necessary. * * Note[2]: previously we allocated one additional page. */ *rd_size_ref = ctx.tot_used_bytes + PAGE_SIZE; /* Return (as OUR param) a pointer to the ramdisk */ *rd_paddr_ref = (UINTN)ctx.fat_hdr; end: if (ctx.blockio) BS->CloseProtocol(bioDeviceHandle, &BlockIoProtocol, image, NULL); return status; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> void init_pic_8259(u8 offset1, u8 offset2); void pic_mask_and_send_eoi(int irq); void pic_send_eoi(int irq); bool pic_is_spur_irq(int irq); void irq_set_mask(int irq); void irq_clear_mask(int irq); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/common/utils.h> #include <tilck/common/string_util.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/worker_thread.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/cmdline.h> #include <tilck/kernel/errno.h> static struct list se_list = STATIC_LIST_INIT(se_list); static volatile bool se_stop_requested; static struct self_test *se_running; static struct task *se_user_task; static void se_actual_register(struct self_test *se) { struct self_test *pos; if (strlen(se->name) >= SELF_TEST_MAX_NAME_LEN) panic("Self test name '%s' too long\n", se->name); list_for_each_ro(pos, &se_list, node) { if (pos == se) continue; if (!strcmp(pos->name, se->name)) panic("Cannot register self-test '%s': duplicate name!", se->name); } } void se_register(struct self_test *se) { list_add_tail(&se_list, &se->node); } bool se_is_stop_requested(void) { return se_stop_requested; } struct self_test *se_find(const char *name) { char name_buf[SELF_TEST_MAX_NAME_LEN+1]; const char *name_to_use = name; size_t len = strlen(name); const char *p = name + len - 1; const char *p2 = name; char *s = name_buf; struct self_test *pos; if (len >= SELF_TEST_MAX_NAME_LEN) return NULL; /* * Find the position of the last '_', going backwards. * Reason: drop the {_manual, _short, _med, _long} suffix. */ while (p > name) { if (*p == '_') { if (strcmp(p, "_manual") && strcmp(p, "_short") && strcmp(p, "_med") && strcmp(p, "_long")) { /* * Some self-tests like kmutex_ord use '_' in their name. In those * cases, we should never discard whatever was after the last '_'. */ p = name; } break; } p--; } if (p > name) { while (p2 < p) *s++ = *p2++; *s = 0; name_to_use = name_buf; } list_for_each_ro(pos, &se_list, node) { if (!strcmp(pos->name, name_to_use)) return pos; } return NULL; } static void se_internal_run(struct self_test *se) { ASSERT(se_user_task != NULL); /* Common self test setup code */ disable_preemption(); { se_stop_requested = false; se_running = se; } enable_preemption(); /* Run the actual self test */ se->func(); /* Common self test tear down code */ disable_preemption(); { se_stop_requested = false; se_running = NULL; } enable_preemption(); } int se_run(struct self_test *se) { int tid; int rc = 0; disable_preemption(); { if (se_running) { printk("self-tests: parallel runs not allowed (tid: %d)\n", get_curr_tid()); enable_preemption(); return -EBUSY; } se_user_task = get_curr_task(); } enable_preemption(); tid = kthread_create(se_internal_run, KTH_ALLOC_BUFS, se); if (tid > 0) { rc = kthread_join(tid, false); if (rc) { se_stop_requested = true; printk("self-tests: stop requested\n"); rc = kthread_join(tid, true); } } else { printk("self-tests: kthread_create() failed with: %d\n", tid); rc = tid; } disable_preemption(); { se_user_task = NULL; } enable_preemption(); return rc; } void se_regular_end(void) { printk("Self-test completed.\n"); } void se_interrupted_end(void) { printk("Self-test interrupted.\n"); } void init_self_tests(void) { struct self_test *se; list_for_each_ro(se, &se_list, node) { se_actual_register(se); } } void selftest_list(void) { static const char *se_kind_str[] = { [se_short] = "short", [se_med] = "med", [se_long] = "long", [se_manual] = "manual" }; struct self_test *se; list_for_each_ro(se, &se_list, node) { printk("%-20s [%s]\n", se->name, se_kind_str[se->kind]); } } REGISTER_SELF_TEST(list, se_manual, &selftest_list) <file_sep># SPDX-License-Identifier: BSD-2-Clause # pylint: skip-file # # NOTE: this file, as all the others in this directory, run in the same global # context as their runner (run_interactive_test). just_run_vim_and_exit() do_interactive_actions( "vim2", [ r"cd /usr/lib/vim/samples{ret}vim perl.pl{ret}", r"{esc}:open python.py{ret}", r"{esc}:open ruby.rb{ret}", r"{esc}:open shell.sh{ret}", r"{esc}:q{ret}cd /{ret}", ], false_positive_handler_vim ) <file_sep>#!/usr/bin/env bash rawImg="tilck.img" vmdk="tilck.vmdk" pushd ./build sudo losetup -D sudo losetup /dev/loop0 $rawImg sudo chmod o+rw /dev/loop0 rm -f $vmdk VBoxManage internalcommands createrawvmdk -filename $vmdk -rawdisk /dev/loop0 sudo chown $USER $vmdk popd <file_sep>/****************************************************************************** * * Module Name: nsload - namespace loading/expanding/contracting procedures * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acdispat.h" #include "actables.h" #include "acinterp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsload") /* Local prototypes */ #ifdef ACPI_FUTURE_IMPLEMENTATION ACPI_STATUS AcpiNsUnloadNamespace ( ACPI_HANDLE Handle); static ACPI_STATUS AcpiNsDeleteSubtree ( ACPI_HANDLE StartHandle); #endif /******************************************************************************* * * FUNCTION: AcpiNsLoadTable * * PARAMETERS: TableIndex - Index for table to be loaded * Node - Owning NS node * * RETURN: Status * * DESCRIPTION: Load one ACPI table into the namespace * ******************************************************************************/ ACPI_STATUS AcpiNsLoadTable ( UINT32 TableIndex, ACPI_NAMESPACE_NODE *Node) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsLoadTable); /* If table already loaded into namespace, just return */ if (AcpiTbIsTableLoaded (TableIndex)) { Status = AE_ALREADY_EXISTS; goto Unlock; } ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "**** Loading table into namespace ****\n")); Status = AcpiTbAllocateOwnerId (TableIndex); if (ACPI_FAILURE (Status)) { goto Unlock; } /* * Parse the table and load the namespace with all named * objects found within. Control methods are NOT parsed * at this time. In fact, the control methods cannot be * parsed until the entire namespace is loaded, because * if a control method makes a forward reference (call) * to another control method, we can't continue parsing * because we don't know how many arguments to parse next! */ Status = AcpiNsParseTable (TableIndex, Node); if (ACPI_SUCCESS (Status)) { AcpiTbSetTableLoadedFlag (TableIndex, TRUE); } else { /* * On error, delete any namespace objects created by this table. * We cannot initialize these objects, so delete them. There are * a couple of especially bad cases: * AE_ALREADY_EXISTS - namespace collision. * AE_NOT_FOUND - the target of a Scope operator does not * exist. This target of Scope must already exist in the * namespace, as per the ACPI specification. */ AcpiNsDeleteNamespaceByOwner ( AcpiGbl_RootTableList.Tables[TableIndex].OwnerId); AcpiTbReleaseOwnerId (TableIndex); return_ACPI_STATUS (Status); } Unlock: if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Now we can parse the control methods. We always parse * them here for a sanity check, and if configured for * just-in-time parsing, we delete the control method * parse trees. */ ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "**** Begin Table Object Initialization\n")); AcpiExEnterInterpreter (); Status = AcpiDsInitializeObjects (TableIndex, Node); AcpiExExitInterpreter (); ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "**** Completed Table Object Initialization\n")); return_ACPI_STATUS (Status); } #ifdef ACPI_OBSOLETE_FUNCTIONS /******************************************************************************* * * FUNCTION: AcpiLoadNamespace * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Load the name space from what ever is pointed to by DSDT. * (DSDT points to either the BIOS or a buffer.) * ******************************************************************************/ ACPI_STATUS AcpiNsLoadNamespace ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiLoadNameSpace); /* There must be at least a DSDT installed */ if (AcpiGbl_DSDT == NULL) { ACPI_ERROR ((AE_INFO, "DSDT is not in memory")); return_ACPI_STATUS (AE_NO_ACPI_TABLES); } /* * Load the namespace. The DSDT is required, * but the SSDT and PSDT tables are optional. */ Status = AcpiNsLoadTableByType (ACPI_TABLE_ID_DSDT); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Ignore exceptions from these */ (void) AcpiNsLoadTableByType (ACPI_TABLE_ID_SSDT); (void) AcpiNsLoadTableByType (ACPI_TABLE_ID_PSDT); ACPI_DEBUG_PRINT_RAW ((ACPI_DB_INIT, "ACPI Namespace successfully loaded at root %p\n", AcpiGbl_RootNode)); return_ACPI_STATUS (Status); } #endif #ifdef ACPI_FUTURE_IMPLEMENTATION /******************************************************************************* * * FUNCTION: AcpiNsDeleteSubtree * * PARAMETERS: StartHandle - Handle in namespace where search begins * * RETURNS Status * * DESCRIPTION: Walks the namespace starting at the given handle and deletes * all objects, entries, and scopes in the entire subtree. * * Namespace/Interpreter should be locked or the subsystem should * be in shutdown before this routine is called. * ******************************************************************************/ static ACPI_STATUS AcpiNsDeleteSubtree ( ACPI_HANDLE StartHandle) { ACPI_STATUS Status; ACPI_HANDLE ChildHandle; ACPI_HANDLE ParentHandle; ACPI_HANDLE NextChildHandle; ACPI_HANDLE Dummy; UINT32 Level; ACPI_FUNCTION_TRACE (NsDeleteSubtree); ParentHandle = StartHandle; ChildHandle = NULL; Level = 1; /* * Traverse the tree of objects until we bubble back up * to where we started. */ while (Level > 0) { /* Attempt to get the next object in this scope */ Status = AcpiGetNextObject (ACPI_TYPE_ANY, ParentHandle, ChildHandle, &NextChildHandle); ChildHandle = NextChildHandle; /* Did we get a new object? */ if (ACPI_SUCCESS (Status)) { /* Check if this object has any children */ if (ACPI_SUCCESS (AcpiGetNextObject (ACPI_TYPE_ANY, ChildHandle, NULL, &Dummy))) { /* * There is at least one child of this object, * visit the object */ Level++; ParentHandle = ChildHandle; ChildHandle = NULL; } } else { /* * No more children in this object, go back up to * the object's parent */ Level--; /* Delete all children now */ AcpiNsDeleteChildren (ChildHandle); ChildHandle = ParentHandle; Status = AcpiGetParent (ParentHandle, &ParentHandle); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } } /* Now delete the starting object, and we are done */ AcpiNsRemoveNode (ChildHandle); return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiNsUnloadNameSpace * * PARAMETERS: Handle - Root of namespace subtree to be deleted * * RETURN: Status * * DESCRIPTION: Shrinks the namespace, typically in response to an undocking * event. Deletes an entire subtree starting from (and * including) the given handle. * ******************************************************************************/ ACPI_STATUS AcpiNsUnloadNamespace ( ACPI_HANDLE Handle) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsUnloadNameSpace); /* Parameter validation */ if (!AcpiGbl_RootNode) { return_ACPI_STATUS (AE_NO_NAMESPACE); } if (!Handle) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* This function does the real work */ Status = AcpiNsDeleteSubtree (Handle); return_ACPI_STATUS (Status); } #endif <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_tracing.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/timer.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/fault_resumable.h> #include <tilck/kernel/user.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/signal.h> #include <tilck/mods/tracing.h> void syscall_int80_entry(void); void sysenter_entry(void); typedef long (*syscall_type)(); #define SYSFL_NO_TRACE 0b00000001 #define SYSFL_NO_SIG 0b00000010 #define SYSFL_NO_PREEMPT 0b00000100 struct syscall { union { void *func; syscall_type fptr; }; u32 flags; }; static void unknown_syscall_int(regs_t *r, u32 sn) { trace_printk(5, "Unknown syscall %i", (int)sn); r->rax = (ulong) -ENOSYS; } static void __unknown_syscall(void) { struct task *curr = get_curr_task(); regs_t *r = curr->state_regs; const u32 sn = r->rax; unknown_syscall_int(r, sn); } #define DECL_SYS(func, flags) { {func}, flags } #define DECL_UNKNOWN_SYSCALL DECL_SYS(__unknown_syscall, 0) /* * The syscall numbers are ARCH-dependent * * The numbers and the syscall names MUST BE in sync with the following file * in the Linux kernel: * * ADD SYSCALL LINUX TBL FILE * * Lasy synced with Linux 5.15-rc2. */ static struct syscall syscalls[MAX_SYSCALLS] = { [TILCK_CMD_SYSCALL] = DECL_SYS(sys_tilck_cmd, 0), }; void *get_syscall_func_ptr(u32 n) { NOT_IMPLEMENTED(); return syscalls[n].fptr; } int get_syscall_num(void *func) { NOT_IMPLEMENTED(); } void handle_syscall(regs_t *r) { NOT_IMPLEMENTED(); } void init_syscall_interfaces(void) { NOT_IMPLEMENTED(); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * SAFE_RINGBUF: a reentrant ring buffer implementation designed as an efficient * non-interrupt blocking mechanism to transfer data between IRQ handlers and * regular (preemptable) kernel code. * * What is SAFE to do: * * - Produce data (by writing to the ring buffer) from interrupt handlers * code (nested interrupts supported). * * - Consume data (by reading from the ring buffer) from preemptable code in * process context. Such code must NEVER be able to preempt/interrupt * the producer code. It always must be the other way around. * * In other words: * * Producer code might interrupt consumer code or producer code. Consumer * code must NEVER interrupt producer code, otherwise it might ready corrupt * data. * * What is NOT safe to do: * * - Have a consumer that interrupted a producer, no matter the context. * The safe ring buffer is "safe" only in one direction, as explained * above. * * - Use the safe_ringbuf in a SMP machine (Tilck does not support that now) * without proper external protection (spin locks). * * Usage example: * * - vterm_write() creates an action and calls * term_execute_or_enqueue_action(). * * - term_execute_or_enqueue_action() calls * term_execute_or_enqueue_action_template(). * * - term_execute_or_enqueue_action_template() writes to the ring buffer and * ONLY in the case `was_empty` was true, starts acting like a consumer * by calling term_exec_everything() which reads from the buffer in a loop. * * It doesn't matter the context IRQ (handler or not) in which vterm_write() was * called. The point is that only the task that wrote to the ringbuffer first * and found it empty becomes the consumer. All the other tasks or nested * interrupt handlers, interrupting the consumer will just write to the ring * buffer and exit. Wait a second: how on earth IRQ handlers will end up calling * vterm_write()? Only one way: if they call printk (they shouldn't but can) and * printk's buffer got full and it has no other choice than to flush directly * its to buffer to the term. Pretty unlikely, but possible. */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> struct generic_safe_ringbuf_stat { union { struct { u32 read_pos : 15; u32 write_pos : 15; u32 full : 1; u32 avail_bit : 1; }; ATOMIC(u32) raw; u32 __raw; }; }; struct safe_ringbuf { u16 max_elems; u16 elem_size; struct generic_safe_ringbuf_stat s; u8 *buf; #if DEBUG_CHECKS ATOMIC(int) nested_writes; #endif }; bool safe_ringbuf_is_empty(struct safe_ringbuf *rb); bool safe_ringbuf_is_full(struct safe_ringbuf *rb); void safe_ringbuf_init(struct safe_ringbuf *rb, u16 max_elems, u16 e_size, void *b); void safe_ringbuf_destory(struct safe_ringbuf *rb); /* Generic read/write funcs */ bool safe_ringbuf_write_elem(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_read_elem(struct safe_ringbuf *rb, void *elem_ptr /* out */); /* Pointer-size read/write funcs */ bool safe_ringbuf_write_ulong(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_read_ulong(struct safe_ringbuf *rb, void *elem_ptr /* out */); /* Size-specific read/write funcs */ bool safe_ringbuf_write_1(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_write_2(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_write_4(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_write_8(struct safe_ringbuf *rb, void *e, bool *was_empty); bool safe_ringbuf_read_1(struct safe_ringbuf *rb, void *elem_ptr /* out */); bool safe_ringbuf_read_2(struct safe_ringbuf *rb, void *elem_ptr /* out */); bool safe_ringbuf_read_4(struct safe_ringbuf *rb, void *elem_ptr /* out */); bool safe_ringbuf_read_8(struct safe_ringbuf *rb, void *elem_ptr /* out */); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/kernel/term.h> #include <tilck/kernel/term_aux.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/safe_ringbuf.h> #include <tilck/kernel/sync.h> #include <tilck/mods/serial.h> struct term_action { /* Only one action is supported: write */ const char *buf; size_t len; }; STATIC_ASSERT(sizeof(struct term_action) == (2 * sizeof(ulong))); struct sterm { bool initialized; u16 serial_port_fwd; struct term_rb_data rb_data; struct term_action actions_buf[32]; }; static struct sterm first_instance; static enum term_type sterm_get_type(void) { return term_type_serial; } static bool sterm_is_initialized(term *_t) { struct sterm *const t = _t; return t->initialized; } static void sterm_get_params(term *_t, struct term_params *out) { *out = (struct term_params) { .rows = 25, .cols = 80, .type = term_type_serial, .vi = NULL, }; } static void sterm_action_write(term *_t, const char *buf, size_t len) { struct sterm *const t = _t; for (u32 i = 0; i < len; i++) { if (buf[i] == '\n') serial_write(t->serial_port_fwd, '\r'); serial_write(t->serial_port_fwd, buf[i]); } } static ALWAYS_INLINE void sterm_execute_action(term *t, struct term_action *a) { sterm_action_write(t, a->buf, a->len); } static void serial_term_execute_or_enqueue_action(struct sterm *t, struct term_action *a) { term_execute_or_enqueue_action_template(t, &t->rb_data, a, &sterm_execute_action); } static void sterm_write(term *_t, const char *buf, size_t len, u8 color) { struct sterm *const t = _t; struct term_action a = { .buf = buf, .len = len, }; serial_term_execute_or_enqueue_action(t, &a); } static term *sterm_get_first_inst(void) { return &first_instance; } static term * alloc_sterm_struct(void) { return kzalloc_obj(struct sterm); } static void free_sterm_struct(term *_t) { struct sterm *const t = _t; ASSERT(t != &first_instance); kfree_obj(t, struct sterm); } static void dispose_sterm(term *_t) { struct sterm *const t = _t; dispose_term_rb_data(&t->rb_data); } static int sterm_init(term *_t, u16 serial_port_fwd) { struct sterm *const t = _t; t->serial_port_fwd = serial_port_fwd; init_term_rb_data(&t->rb_data, ARRAY_SIZE(t->actions_buf), sizeof(struct term_action), t->actions_buf); t->initialized = true; return 0; } static void sterm_ignored() { /* do nothing */ } static const struct term_interface intf = { .get_type = sterm_get_type, .is_initialized = sterm_is_initialized, .get_params = sterm_get_params, .write = sterm_write, .scroll_up = (void*)sterm_ignored, .scroll_down = (void*)sterm_ignored, .set_col_offset = (void*)sterm_ignored, .pause_output = (void*)sterm_ignored, .restart_output = (void*)sterm_ignored, .set_filter = (void*)sterm_ignored, .get_first_term = sterm_get_first_inst, .video_term_init = NULL, .serial_term_init = sterm_init, .alloc = alloc_sterm_struct, .free = free_sterm_struct, .dispose = dispose_sterm, }; __attribute__((constructor)) static void register_term(void) { register_term_intf(&intf); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/utils.h> #include <tilck/common/printk.h> #include <tilck/common/arch/generic_x86/cpu_features.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/paging.h> #define MTRR_DEF_TYPE_MTRR_ENABLED (1u << 11) #define MTRR_PHYS_MASK_VALID (1u << 11) static void enable_mtrr_int(void) { u64 mtrr_dt = rdmsr(MSR_IA32_MTRR_DEF_TYPE); mtrr_dt |= MTRR_DEF_TYPE_MTRR_ENABLED; wrmsr(MSR_IA32_MTRR_DEF_TYPE, mtrr_dt); } static void disable_mtrr_int(void) { u64 mtrr_dt = rdmsr(MSR_IA32_MTRR_DEF_TYPE); mtrr_dt &= ~MTRR_DEF_TYPE_MTRR_ENABLED; wrmsr(MSR_IA32_MTRR_DEF_TYPE, mtrr_dt); } void enable_mtrr(void) { u64 mtrr_dt = rdmsr(MSR_IA32_MTRR_DEF_TYPE); if (!(mtrr_dt & MTRR_DEF_TYPE_MTRR_ENABLED)) { enable_mtrr_int(); } printk("CPU: MTRR enabled\n"); } u32 get_var_mttrs_count(void) { if (!x86_cpu_features.edx1.mtrr) return 0; return rdmsr(MSR_IA32_MTRRCAP) & 255; } int get_free_mtrr(void) { u32 var_mtrr_count = get_var_mttrs_count(); u32 selected = 0; for (u32 i = 0; i < var_mtrr_count; i++, selected++) { u64 mask_reg = rdmsr(MSR_MTRRphysBase0 + 2 * i + 1); bool used = !!(mask_reg & MTRR_DEF_TYPE_MTRR_ENABLED); if (!used) return (int)selected; } return -1; } static void cache_disable(ulong *saved_cr0) { ulong cr0 = read_cr0(); *saved_cr0 = cr0; cr0 |= CR0_CD; /* * Clear the NW (not write-through) bit in order to set caching * in "No-fill Cache Mode", where the memory coherency is maintained. */ cr0 &= ~CR0_NW; write_cr0(cr0); } static void cache_enable(ulong *saved_cr0) { write_cr0(*saved_cr0); } struct mtrr_change_ctx { ulong eflags; ulong cr4; ulong cr0; }; /* * As described in: * Intel's System Programming Guide (Vol. 3A), Section 11.11.7.2 */ static void pre_mtrr_change(struct mtrr_change_ctx *ctx) { disable_interrupts(&ctx->eflags); /* Save CR4 */ ctx->cr4 = read_cr4(); cache_disable(&ctx->cr0); /* Flush all the WB entries in the cache and invalidate the rest */ write_back_and_invl_cache(); /* Flush all TLB entries by re-loading CR3 */ write_cr3(read_cr3()); disable_mtrr_int(); } /* * As described in: * Intel's System Programming Guide (Vol. 3A), Section 11.11.7.2 */ static void post_mtrr_change(struct mtrr_change_ctx *ctx) { /* Flush all the WB entries in the cache and invalidate the rest */ write_back_and_invl_cache(); /* Flush all TLB entries by re-loading CR3 */ write_cr3(read_cr3()); enable_mtrr_int(); cache_enable(&ctx->cr0); /* Restore CR4 */ write_cr4(ctx->cr4); enable_interrupts(&ctx->eflags); } void set_mtrr(u32 num, u64 paddr, u32 pow2size, u8 mem_type) { ASSERT(num < get_var_mttrs_count()); ASSERT(pow2size > 0); ASSERT(roundup_next_power_of_2(pow2size) == pow2size); ASSERT(pow2_round_up_at64(paddr, pow2size) == paddr); ASSERT(x86_cpu_features.edx1.mtrr); struct mtrr_change_ctx ctx; pre_mtrr_change(&ctx); { u64 mask64 = ~((u64)pow2size - 1); u64 physBaseVal = ((u64)paddr & PAGE_MASK) | mem_type; u64 physMaskVal; physMaskVal = mask64 & ((1ull << x86_cpu_features.phys_addr_bits) - 1); physMaskVal |= MTRR_PHYS_MASK_VALID; wrmsr(MSR_MTRRphysBase0 + 2 * num, physBaseVal); wrmsr(MSR_MTRRphysBase0 + 2 * num + 1, physMaskVal); } post_mtrr_change(&ctx); } void reset_mtrr(u32 num) { struct mtrr_change_ctx ctx; ASSERT(num < get_var_mttrs_count()); pre_mtrr_change(&ctx); { wrmsr(MSR_MTRRphysBase0 + 2 * num + 1, 0); wrmsr(MSR_MTRRphysBase0 + 2 * num, 0); } post_mtrr_change(&ctx); } <file_sep>--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Host configuration** - Linux distro and version - Compiler (name and version) - Host CPU architecture **Toolchain configuration** - How was the `build_toolchain` script run? (e.g. environment variables) **Tilck build configuration** - How did `cmake` was run? Did you use the `run_cmake` wrapper? For build errors, please attach the full build log of a *clean* build. - Tilck commit: please indicate the exact commit used to reproduce the problem **Type of issue (select one)** - Toolchain build problem - Tilck build problem - Tilck boot problem - Tilck test failure - Incorrect behavior - Panic - Other **Reproduction details** - Is the issue reproducible in a deterministic way? - Is the issue reproducible both on real hardware and QEMU or just on real HW? - If applicable, describe the hardware machine used to run Tilck. - Indicate the exact steps to reproduce the problem **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Additional context** Add any other context about the problem here. <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/self_tests.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/sync.h> static struct kcond conds[2]; static ATOMIC(int) mobj_se_test_signal_counter; static bool mobj_se_test_assumption_failed; static void mobj_waiter_sig_thread(void *arg) { ulong n = (ulong) arg; u64 ticks_to_sleep = (u64)(n + 1) * TIMER_HZ / 2; printk("[thread %lu] sleep for %" PRIu64 " ticks\n", n, ticks_to_sleep); kernel_sleep(ticks_to_sleep); printk("[thread %lu] signal cond %ld\n", n, n); kcond_signal_one(&conds[n]); mobj_se_test_signal_counter++; } static void mobj_waiter_wait_thread(void *arg) { printk("[wait th] Start\n"); if (mobj_se_test_signal_counter > 0) { printk("[wait th] Test timing assumption failed, re-try\n"); mobj_se_test_assumption_failed = true; return; } struct multi_obj_waiter *w = allocate_mobj_waiter(ARRAY_SIZE(conds)); VERIFY(w != NULL); for (int j = 0; j < ARRAY_SIZE(conds); j++) mobj_waiter_set(w, j, WOBJ_KCOND, &conds[j], &conds[j].wait_list); for (int i = 0; i < ARRAY_SIZE(conds); i++) { printk("[wait th]: going to sleep on waiter obj\n"); disable_preemption(); prepare_to_wait_on_multi_obj(w); enter_sleep_wait_state(); printk("[wait th ] wake up #%u\n", i); for (int j = 0; j < w->count; j++) { struct mwobj_elem *me = &w->elems[j]; if (me->type && !me->wobj.type) { printk("[wait th ] -> condition #%u was signaled\n", j); mobj_waiter_reset(me); } } } free_mobj_waiter(w); } void selftest_mobj_waiter() { int tids[ARRAY_SIZE(conds)]; int w_tid; retry: mobj_se_test_signal_counter = 0; mobj_se_test_assumption_failed = false; for (int i = 0; i < ARRAY_SIZE(conds); i++) { kcond_init(&conds[i]); tids[i] = kthread_create(&mobj_waiter_sig_thread, 0, TO_PTR(i)); VERIFY(tids[i] > 0); } w_tid = kthread_create(&mobj_waiter_wait_thread, 0, NULL); VERIFY(w_tid > 0); kthread_join_all(tids, ARRAY_SIZE(tids), true); kthread_join(w_tid, true); for (int i = 0; i < ARRAY_SIZE(conds); i++) kcond_destory(&conds[i]); if (mobj_se_test_assumption_failed) goto retry; se_regular_end(); } REGISTER_SELF_TEST(mobj_waiter, se_short, &selftest_mobj_waiter) <file_sep>/****************************************************************************** * * Name: acobject.h - Definition of ACPI_OPERAND_OBJECT (Internal object only) * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #ifndef _ACOBJECT_H #define _ACOBJECT_H /* acpisrc:StructDefs -- for acpisrc conversion */ /* * The ACPI_OPERAND_OBJECT is used to pass AML operands from the dispatcher * to the interpreter, and to keep track of the various handlers such as * address space handlers and notify handlers. The object is a constant * size in order to allow it to be cached and reused. * * Note: The object is optimized to be aligned and will not work if it is * byte-packed. */ #if ACPI_MACHINE_WIDTH == 64 #pragma pack(8) #else #pragma pack(4) #endif /******************************************************************************* * * Common Descriptors * ******************************************************************************/ /* * Common area for all objects. * * DescriptorType is used to differentiate between internal descriptors, and * must be in the same place across all descriptors * * Note: The DescriptorType and Type fields must appear in the identical * position in both the ACPI_NAMESPACE_NODE and ACPI_OPERAND_OBJECT * structures. */ #define ACPI_OBJECT_COMMON_HEADER \ union acpi_operand_object *NextObject; /* Objects linked to parent NS node */\ UINT8 DescriptorType; /* To differentiate various internal objs */\ UINT8 Type; /* ACPI_OBJECT_TYPE */\ UINT16 ReferenceCount; /* For object deletion management */\ UINT8 Flags; /* * Note: There are 3 bytes available here before the * next natural alignment boundary (for both 32/64 cases) */ /* Values for Flag byte above */ #define AOPOBJ_AML_CONSTANT 0x01 /* Integer is an AML constant */ #define AOPOBJ_STATIC_POINTER 0x02 /* Data is part of an ACPI table, don't delete */ #define AOPOBJ_DATA_VALID 0x04 /* Object is initialized and data is valid */ #define AOPOBJ_OBJECT_INITIALIZED 0x08 /* Region is initialized */ #define AOPOBJ_REG_CONNECTED 0x10 /* _REG was run */ #define AOPOBJ_SETUP_COMPLETE 0x20 /* Region setup is complete */ #define AOPOBJ_INVALID 0x40 /* Host OS won't allow a Region address */ /****************************************************************************** * * Basic data types * *****************************************************************************/ typedef struct acpi_object_common { ACPI_OBJECT_COMMON_HEADER } ACPI_OBJECT_COMMON; typedef struct acpi_object_integer { ACPI_OBJECT_COMMON_HEADER UINT8 Fill[3]; /* Prevent warning on some compilers */ UINT64 Value; } ACPI_OBJECT_INTEGER; /* * Note: The String and Buffer object must be identical through the * pointer and length elements. There is code that depends on this. * * Fields common to both Strings and Buffers */ #define ACPI_COMMON_BUFFER_INFO(_Type) \ _Type *Pointer; \ UINT32 Length; /* Null terminated, ASCII characters only */ typedef struct acpi_object_string { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_BUFFER_INFO (char) /* String in AML stream or allocated string */ } ACPI_OBJECT_STRING; typedef struct acpi_object_buffer { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_BUFFER_INFO (UINT8) /* Buffer in AML stream or allocated buffer */ UINT32 AmlLength; UINT8 *AmlStart; ACPI_NAMESPACE_NODE *Node; /* Link back to parent node */ } ACPI_OBJECT_BUFFER; typedef struct acpi_object_package { ACPI_OBJECT_COMMON_HEADER ACPI_NAMESPACE_NODE *Node; /* Link back to parent node */ union acpi_operand_object **Elements; /* Array of pointers to AcpiObjects */ UINT8 *AmlStart; UINT32 AmlLength; UINT32 Count; /* # of elements in package */ } ACPI_OBJECT_PACKAGE; /****************************************************************************** * * Complex data types * *****************************************************************************/ typedef struct acpi_object_event { ACPI_OBJECT_COMMON_HEADER ACPI_SEMAPHORE OsSemaphore; /* Actual OS synchronization object */ } ACPI_OBJECT_EVENT; typedef struct acpi_object_mutex { ACPI_OBJECT_COMMON_HEADER UINT8 SyncLevel; /* 0-15, specified in Mutex() call */ UINT16 AcquisitionDepth; /* Allow multiple Acquires, same thread */ ACPI_MUTEX OsMutex; /* Actual OS synchronization object */ ACPI_THREAD_ID ThreadId; /* Current owner of the mutex */ struct acpi_thread_state *OwnerThread; /* Current owner of the mutex */ union acpi_operand_object *Prev; /* Link for list of acquired mutexes */ union acpi_operand_object *Next; /* Link for list of acquired mutexes */ ACPI_NAMESPACE_NODE *Node; /* Containing namespace node */ UINT8 OriginalSyncLevel; /* Owner's original sync level (0-15) */ } ACPI_OBJECT_MUTEX; typedef struct acpi_object_region { ACPI_OBJECT_COMMON_HEADER UINT8 SpaceId; ACPI_NAMESPACE_NODE *Node; /* Containing namespace node */ union acpi_operand_object *Handler; /* Handler for region access */ union acpi_operand_object *Next; ACPI_PHYSICAL_ADDRESS Address; UINT32 Length; } ACPI_OBJECT_REGION; typedef struct acpi_object_method { ACPI_OBJECT_COMMON_HEADER UINT8 InfoFlags; UINT8 ParamCount; UINT8 SyncLevel; union acpi_operand_object *Mutex; union acpi_operand_object *Node; UINT8 *AmlStart; union { ACPI_INTERNAL_METHOD Implementation; union acpi_operand_object *Handler; } Dispatch; UINT32 AmlLength; ACPI_OWNER_ID OwnerId; UINT8 ThreadCount; } ACPI_OBJECT_METHOD; /* Flags for InfoFlags field above */ #define ACPI_METHOD_MODULE_LEVEL 0x01 /* Method is actually module-level code */ #define ACPI_METHOD_INTERNAL_ONLY 0x02 /* Method is implemented internally (_OSI) */ #define ACPI_METHOD_SERIALIZED 0x04 /* Method is serialized */ #define ACPI_METHOD_SERIALIZED_PENDING 0x08 /* Method is to be marked serialized */ #define ACPI_METHOD_IGNORE_SYNC_LEVEL 0x10 /* Method was auto-serialized at table load time */ #define ACPI_METHOD_MODIFIED_NAMESPACE 0x20 /* Method modified the namespace */ /****************************************************************************** * * Objects that can be notified. All share a common NotifyInfo area. * *****************************************************************************/ /* * Common fields for objects that support ASL notifications */ #define ACPI_COMMON_NOTIFY_INFO \ union acpi_operand_object *NotifyList[2]; /* Handlers for system/device notifies */\ union acpi_operand_object *Handler; /* Handler for Address space */ /* COMMON NOTIFY for POWER, PROCESSOR, DEVICE, and THERMAL */ typedef struct acpi_object_notify_common { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_NOTIFY_INFO } ACPI_OBJECT_NOTIFY_COMMON; typedef struct acpi_object_device { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_NOTIFY_INFO ACPI_GPE_BLOCK_INFO *GpeBlock; } ACPI_OBJECT_DEVICE; typedef struct acpi_object_power_resource { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_NOTIFY_INFO UINT32 SystemLevel; UINT32 ResourceOrder; } ACPI_OBJECT_POWER_RESOURCE; typedef struct acpi_object_processor { ACPI_OBJECT_COMMON_HEADER /* The next two fields take advantage of the 3-byte space before NOTIFY_INFO */ UINT8 ProcId; UINT8 Length; ACPI_COMMON_NOTIFY_INFO ACPI_IO_ADDRESS Address; } ACPI_OBJECT_PROCESSOR; typedef struct acpi_object_thermal_zone { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_NOTIFY_INFO } ACPI_OBJECT_THERMAL_ZONE; /****************************************************************************** * * Fields. All share a common header/info field. * *****************************************************************************/ /* * Common bitfield for the field objects * "Field Datum" -- a datum from the actual field object * "Buffer Datum" -- a datum from a user buffer, read from or to be written to the field */ #define ACPI_COMMON_FIELD_INFO \ UINT8 FieldFlags; /* Access, update, and lock bits */\ UINT8 Attribute; /* From AccessAs keyword */\ UINT8 AccessByteWidth; /* Read/Write size in bytes */\ ACPI_NAMESPACE_NODE *Node; /* Link back to parent node */\ UINT32 BitLength; /* Length of field in bits */\ UINT32 BaseByteOffset; /* Byte offset within containing object */\ UINT32 Value; /* Value to store into the Bank or Index register */\ UINT8 StartFieldBitOffset;/* Bit offset within first field datum (0-63) */\ UINT8 AccessLength; /* For serial regions/fields */ /* COMMON FIELD (for BUFFER, REGION, BANK, and INDEX fields) */ typedef struct acpi_object_field_common { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_FIELD_INFO union acpi_operand_object *RegionObj; /* Parent Operation Region object (REGION/BANK fields only) */ } ACPI_OBJECT_FIELD_COMMON; typedef struct acpi_object_region_field { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_FIELD_INFO UINT16 ResourceLength; union acpi_operand_object *RegionObj; /* Containing OpRegion object */ UINT8 *ResourceBuffer; /* ResourceTemplate for serial regions/fields */ UINT16 PinNumberIndex; /* Index relative to previous Connection/Template */ UINT8 *InternalPccBuffer; /* Internal buffer for fields associated with PCC */ } ACPI_OBJECT_REGION_FIELD; typedef struct acpi_object_bank_field { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_FIELD_INFO union acpi_operand_object *RegionObj; /* Containing OpRegion object */ union acpi_operand_object *BankObj; /* BankSelect Register object */ } ACPI_OBJECT_BANK_FIELD; typedef struct acpi_object_index_field { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_FIELD_INFO /* * No "RegionObj" pointer needed since the Index and Data registers * are each field definitions unto themselves. */ union acpi_operand_object *IndexObj; /* Index register */ union acpi_operand_object *DataObj; /* Data register */ } ACPI_OBJECT_INDEX_FIELD; /* The BufferField is different in that it is part of a Buffer, not an OpRegion */ typedef struct acpi_object_buffer_field { ACPI_OBJECT_COMMON_HEADER ACPI_COMMON_FIELD_INFO BOOLEAN IsCreateField; /* Special case for objects created by CreateField() */ union acpi_operand_object *BufferObj; /* Containing Buffer object */ } ACPI_OBJECT_BUFFER_FIELD; /****************************************************************************** * * Objects for handlers * *****************************************************************************/ typedef struct acpi_object_notify_handler { ACPI_OBJECT_COMMON_HEADER ACPI_NAMESPACE_NODE *Node; /* Parent device */ UINT32 HandlerType; /* Type: Device/System/Both */ ACPI_NOTIFY_HANDLER Handler; /* Handler address */ void *Context; union acpi_operand_object *Next[2]; /* Device and System handler lists */ } ACPI_OBJECT_NOTIFY_HANDLER; typedef struct acpi_object_addr_handler { ACPI_OBJECT_COMMON_HEADER UINT8 SpaceId; UINT8 HandlerFlags; ACPI_ADR_SPACE_HANDLER Handler; ACPI_NAMESPACE_NODE *Node; /* Parent device */ void *Context; ACPI_ADR_SPACE_SETUP Setup; union acpi_operand_object *RegionList; /* Regions using this handler */ union acpi_operand_object *Next; } ACPI_OBJECT_ADDR_HANDLER; /* Flags for address handler (HandlerFlags) */ #define ACPI_ADDR_HANDLER_DEFAULT_INSTALLED 0x01 /****************************************************************************** * * Special internal objects * *****************************************************************************/ /* * The Reference object is used for these opcodes: * Arg[0-6], Local[0-7], IndexOp, NameOp, RefOfOp, LoadOp, LoadTableOp, DebugOp * The Reference.Class differentiates these types. */ typedef struct acpi_object_reference { ACPI_OBJECT_COMMON_HEADER UINT8 Class; /* Reference Class */ UINT8 TargetType; /* Used for Index Op */ UINT8 Resolved; /* Reference has been resolved to a value */ void *Object; /* NameOp=>HANDLE to obj, IndexOp=>ACPI_OPERAND_OBJECT */ ACPI_NAMESPACE_NODE *Node; /* RefOf or Namepath */ union acpi_operand_object **Where; /* Target of Index */ UINT8 *IndexPointer; /* Used for Buffers and Strings */ UINT8 *Aml; /* Used for deferred resolution of the ref */ UINT32 Value; /* Used for Local/Arg/Index/DdbHandle */ } ACPI_OBJECT_REFERENCE; /* Values for Reference.Class above */ typedef enum { ACPI_REFCLASS_LOCAL = 0, /* Method local */ ACPI_REFCLASS_ARG = 1, /* Method argument */ ACPI_REFCLASS_REFOF = 2, /* Result of RefOf() TBD: Split to Ref/Node and Ref/OperandObj? */ ACPI_REFCLASS_INDEX = 3, /* Result of Index() */ ACPI_REFCLASS_TABLE = 4, /* DdbHandle - Load(), LoadTable() */ ACPI_REFCLASS_NAME = 5, /* Reference to a named object */ ACPI_REFCLASS_DEBUG = 6, /* Debug object */ ACPI_REFCLASS_MAX = 6 } ACPI_REFERENCE_CLASSES; /* * Extra object is used as additional storage for types that * have AML code in their declarations (TermArgs) that must be * evaluated at run time. * * Currently: Region and FieldUnit types */ typedef struct acpi_object_extra { ACPI_OBJECT_COMMON_HEADER ACPI_NAMESPACE_NODE *Method_REG; /* _REG method for this region (if any) */ ACPI_NAMESPACE_NODE *ScopeNode; void *RegionContext; /* Region-specific data */ UINT8 *AmlStart; UINT32 AmlLength; } ACPI_OBJECT_EXTRA; /* Additional data that can be attached to namespace nodes */ typedef struct acpi_object_data { ACPI_OBJECT_COMMON_HEADER ACPI_OBJECT_HANDLER Handler; void *Pointer; } ACPI_OBJECT_DATA; /* Structure used when objects are cached for reuse */ typedef struct acpi_object_cache_list { ACPI_OBJECT_COMMON_HEADER union acpi_operand_object *Next; /* Link for object cache and internal lists*/ } ACPI_OBJECT_CACHE_LIST; /****************************************************************************** * * ACPI_OPERAND_OBJECT Descriptor - a giant union of all of the above * *****************************************************************************/ typedef union acpi_operand_object { ACPI_OBJECT_COMMON Common; ACPI_OBJECT_INTEGER Integer; ACPI_OBJECT_STRING String; ACPI_OBJECT_BUFFER Buffer; ACPI_OBJECT_PACKAGE Package; ACPI_OBJECT_EVENT Event; ACPI_OBJECT_METHOD Method; ACPI_OBJECT_MUTEX Mutex; ACPI_OBJECT_REGION Region; ACPI_OBJECT_NOTIFY_COMMON CommonNotify; ACPI_OBJECT_DEVICE Device; ACPI_OBJECT_POWER_RESOURCE PowerResource; ACPI_OBJECT_PROCESSOR Processor; ACPI_OBJECT_THERMAL_ZONE ThermalZone; ACPI_OBJECT_FIELD_COMMON CommonField; ACPI_OBJECT_REGION_FIELD Field; ACPI_OBJECT_BUFFER_FIELD BufferField; ACPI_OBJECT_BANK_FIELD BankField; ACPI_OBJECT_INDEX_FIELD IndexField; ACPI_OBJECT_NOTIFY_HANDLER Notify; ACPI_OBJECT_ADDR_HANDLER AddressSpace; ACPI_OBJECT_REFERENCE Reference; ACPI_OBJECT_EXTRA Extra; ACPI_OBJECT_DATA Data; ACPI_OBJECT_CACHE_LIST Cache; /* * Add namespace node to union in order to simplify code that accepts both * ACPI_OPERAND_OBJECTs and ACPI_NAMESPACE_NODEs. The structures share * a common DescriptorType field in order to differentiate them. */ ACPI_NAMESPACE_NODE Node; } ACPI_OPERAND_OBJECT; /****************************************************************************** * * ACPI_DESCRIPTOR - objects that share a common descriptor identifier * *****************************************************************************/ /* Object descriptor types */ #define ACPI_DESC_TYPE_CACHED 0x01 /* Used only when object is cached */ #define ACPI_DESC_TYPE_STATE 0x02 #define ACPI_DESC_TYPE_STATE_UPDATE 0x03 #define ACPI_DESC_TYPE_STATE_PACKAGE 0x04 #define ACPI_DESC_TYPE_STATE_CONTROL 0x05 #define ACPI_DESC_TYPE_STATE_RPSCOPE 0x06 #define ACPI_DESC_TYPE_STATE_PSCOPE 0x07 #define ACPI_DESC_TYPE_STATE_WSCOPE 0x08 #define ACPI_DESC_TYPE_STATE_RESULT 0x09 #define ACPI_DESC_TYPE_STATE_NOTIFY 0x0A #define ACPI_DESC_TYPE_STATE_THREAD 0x0B #define ACPI_DESC_TYPE_WALK 0x0C #define ACPI_DESC_TYPE_PARSER 0x0D #define ACPI_DESC_TYPE_OPERAND 0x0E #define ACPI_DESC_TYPE_NAMED 0x0F #define ACPI_DESC_TYPE_MAX 0x0F typedef struct acpi_common_descriptor { void *CommonPointer; UINT8 DescriptorType; /* To differentiate various internal objs */ } ACPI_COMMON_DESCRIPTOR; typedef union acpi_descriptor { ACPI_COMMON_DESCRIPTOR Common; ACPI_OPERAND_OBJECT Object; ACPI_NAMESPACE_NODE Node; ACPI_PARSE_OBJECT Op; } ACPI_DESCRIPTOR; #pragma pack() #endif /* _ACOBJECT_H */ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/interrupts.h> #include <tilck/kernel/sched.h> static inline bool in_fault_resumable_code(void) { return get_curr_task()->faults_resume_mask != 0; } static inline bool is_fault_resumable(int fault_num) { ASSERT(fault_num <= 31); return (1u << fault_num) & get_curr_task()->faults_resume_mask; } static inline int get_fault_num(u32 r) { for (int i = 0; i < 32; i++) if (r & (1 << i)) return i; return -1; } void handle_resumable_fault(regs_t *r); u32 fault_resumable_call(u32 faults_mask, void *func, u32 nargs, ...); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/mod_pci.h> #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/modules.h> #include <tilck/mods/pci.h> #include <tilck/mods/acpi.h> #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> #include "pci_classes.c.h" #if PCI_VENDORS_LIST #include "pci_vendors.c.h" #else const struct pci_vendor pci_vendors_list[] = { { 0xffff, "Illegal Vendor ID" } }; #endif #define PCI_CONFIG_ADDRESS 0xcf8 #define PCI_CONFIG_DATA 0xcfc #define PCI_DEV_BASE_INFO 0x00 #define PCI_CLASS_INFO_OFF 0x08 #define PCI_HDR_TYPE_OFF 0x0e #define PCI_HDR1_SECOND_BUS 0x19 #define PCI_HDR1_SUBORD_BUS 0x1a #define BUS_NOT_VISITED 0 #define BUS_TO_VISIT 1 #define BUS_VISITED 2 struct pci_segment { u64 base_paddr; u16 segment; u8 start_bus; u8 end_bus; }; static u32 pcie_segments_cnt; static struct pci_segment *pcie_segments; static struct list pci_device_list; static ulong (*pcie_get_conf_vaddr)(struct pci_device_loc); static u8 *pci_buses; /* valid ONLY during init_pci() */ static ulong mmio_bus_va; /* valid ONLY during init_pci() */ static struct pci_device_loc mmio_bus; /* valid if mmio_bus_va != 0 */ int (*__pci_config_read_func)(struct pci_device_loc, u32, u32, u32 *); int (*__pci_config_write_func)(struct pci_device_loc, u32, u32, u32); #include "pci_sysfs.c.h" static void pci_mark_bus_to_visit(u8 bus) { if (pci_buses[bus] == BUS_NOT_VISITED) { pci_buses[bus] = BUS_TO_VISIT; } } static void pci_mark_bus_as_visited(u8 bus) { pci_buses[bus] = BUS_VISITED; } const char * pci_find_vendor_name(u16 id) { for (int i = 0; i < ARRAY_SIZE(pci_vendors_list); i++) if (pci_vendors_list[i].vendor_id == id) return pci_vendors_list[i].name; return NULL; } void pci_find_device_class_name(struct pci_device_class *dev_class) { int i; dev_class->class_name = NULL; dev_class->subclass_name = NULL; dev_class->progif_name = NULL; for (i = 0; i < ARRAY_SIZE(pci_device_classes_list); i++) { if (pci_device_classes_list[i].class_id == dev_class->class_id) { dev_class->class_name = pci_device_classes_list[i].class_name; break; } } if (!dev_class->class_name) return; /* PCI device class not found */ /* Ok, we've found the device class, now look for the subclass */ for (; i < ARRAY_SIZE(pci_device_classes_list); i++) { if (pci_device_classes_list[i].class_id != dev_class->class_id) break; /* it's pointless to search further */ if (pci_device_classes_list[i].subclass_id == dev_class->subclass_id) { dev_class->subclass_name = pci_device_classes_list[i].subclass_name; break; } } if (!dev_class->subclass_name) return; /* PCI device sub-class not found */ /* Ok, we've found both the class and the subclass. Look for a progif */ for (; i < ARRAY_SIZE(pci_device_classes_list); i++) { if (pci_device_classes_list[i].subclass_id != dev_class->subclass_id) break; /* it's pointless to search further */ if (pci_device_classes_list[i].progif_id == dev_class->progif_id) { dev_class->progif_name = pci_device_classes_list[i].progif_name; break; } } } static inline u32 pci_get_config_io_addr(struct pci_device_loc loc, u32 off) { const u32 bus = loc.bus; const u32 dev = loc.dev; const u32 func = loc.func; return 0x80000000 | (bus << 16) | (dev << 11) | (func << 8) | (off & ~3u); } static int pci_ioport_config_read(struct pci_device_loc loc, u32 off, u32 width, u32 *val) { const u16 data_port = PCI_CONFIG_DATA + (off & 3); const u32 len = width >> 3; if (UNLIKELY(loc.seg != 0)) return -EINVAL; /* Conventional PCI has no segment support */ if (UNLIKELY((off & (len - 1u)) != 0)) return -EINVAL; if (UNLIKELY(off + len > 256)) return -EINVAL; /* Write the address to the PCI config. space addr I/O port */ outl(PCI_CONFIG_ADDRESS, pci_get_config_io_addr(loc, off)); /* Read the data from the PCI config. space data I/O port */ switch (width) { case 8: *val = inb(data_port); break; case 16: *val = inw(data_port); break; case 32: *val = inl(data_port); break; default: return -EINVAL; } return 0; } static int pci_ioport_config_write(struct pci_device_loc loc, u32 off, u32 width, u32 val) { const u16 data_port = PCI_CONFIG_DATA + (off & 3); const u32 len = width >> 3; if (UNLIKELY(loc.seg != 0)) return -EINVAL; /* Conventional PCI has no segment support */ if (UNLIKELY((off & (len - 1u)) != 0)) return -EINVAL; if (UNLIKELY(off + len > 256)) return -EINVAL; /* Write the address to the PCI config. space addr I/O port */ outl(PCI_CONFIG_ADDRESS, pci_get_config_io_addr(loc, off)); /* Write the data to the PCI config. space data I/O port */ switch (width) { case 8: outb(data_port, (u8)val); break; case 16: outw(data_port, (u16)val); break; case 32: outl(data_port, (u32)val); break; default: return -EINVAL; } return 0; } static struct pci_segment * pcie_get_segment(u16 seg) { for (u32 i = 0; i < pcie_segments_cnt; i++) if (pcie_segments[i].segment == seg) return &pcie_segments[i]; return NULL; } static int pcie_calc_config_paddr(struct pci_device_loc loc, ulong *paddr) { struct pci_segment *seg; u64 paddr64; seg = pcie_get_segment(loc.seg); if (!seg) return -EINVAL; if (!IN_RANGE_INC(loc.bus, seg->start_bus, seg->end_bus)) return -ERANGE; paddr64 = seg->base_paddr + ((u64)(loc.bus - seg->start_bus) << 20) + ((u32)loc.dev << 15) + ((u32)loc.func << 12); if (NBITS == 32 && paddr64 > (0xffffffff - 4096)) return -E2BIG; *paddr = (ulong)paddr64; return 0; } struct pci_device * pci_get_object(struct pci_device_loc loc) { struct pci_device *pos; list_for_each_ro(pos, &pci_device_list, node) { if (pos->loc.raw == loc.raw) return pos; } return NULL; } static ulong discovery_pcie_get_conf_vaddr(struct pci_device_loc loc) { struct pci_segment *seg = pcie_get_segment(loc.seg); ASSERT(seg != NULL); ASSERT(mmio_bus_va != 0); ASSERT(loc.seg == mmio_bus.seg && loc.bus == mmio_bus.bus); if (!IN_RANGE_INC(loc.bus, seg->start_bus, seg->end_bus)) return 0; /* bus number out of range */ return mmio_bus_va + ((u32)loc.dev << 15) + ((u32)loc.func << 12); } static ulong regular_pcie_get_conf_vaddr(struct pci_device_loc loc) { struct pci_device *dev = pci_get_object(loc); return dev ? (ulong)dev->ext_config : 0; } static int pci_mmio_config_read(struct pci_device_loc loc, u32 off, u32 width, u32 *val) { ulong va = pcie_get_conf_vaddr(loc); const u32 len = width >> 3; if (!va) return -EINVAL; if (UNLIKELY((off & (len - 1u)) != 0)) return -EINVAL; if (UNLIKELY(off + len > 4096)) return -EINVAL; va += off; switch (width) { case 8: *val = *(volatile u8 *)va; break; case 16: *val = *(volatile u16 *)va; break; case 32: *val = *(volatile u32 *)va; break; default: return -EINVAL; } return 0; } static int pci_mmio_config_write(struct pci_device_loc loc, u32 off, u32 width, u32 val) { ulong va = pcie_get_conf_vaddr(loc); const u32 len = width >> 3; if (!va) return -EINVAL; if (UNLIKELY((off & (len - 1u)) != 0)) return -EINVAL; if (UNLIKELY(off + len > 4096)) return -EINVAL; va += off; switch (width) { case 8: *(volatile u8 *)va = (u8)val; break; case 16: *(volatile u16 *)va = (u16)val; break; case 32: *(volatile u32 *)va = (u32)val; break; default: return -EINVAL; } return 0; } int pci_device_get_info(struct pci_device_loc loc, struct pci_device_basic_info *nfo) { int rc; u32 tmp; if ((rc = pci_config_read(loc, PCI_DEV_BASE_INFO, 32, &nfo->__dev_vendr))) return rc; if (nfo->vendor_id == 0xffff || nfo->vendor_id == 0) return -ENOENT; if ((rc = pci_config_read(loc, PCI_CLASS_INFO_OFF, 32, &nfo->__class_info))) return rc; if ((rc = pci_config_read(loc, PCI_HDR_TYPE_OFF, 8, &tmp))) return rc; nfo->__header_type = tmp & 0xff; return 0; } /* * Initialize the support for the Enhanced Configuration Access Mechanism, * used by PCI Express. */ static void init_pci_ecam(void) { ACPI_STATUS rc; ACPI_TABLE_HEADER *hdr; const ACPI_EXCEPTION_INFO *ex; struct acpi_mcfg_allocation *it; if (get_acpi_init_status() < ais_tables_initialized) { printk("PCI: no ACPI. Don't check for MCFG\n"); return; } if (!MOD_acpi) return; rc = AcpiGetTable("MCFG", 1, &hdr); if (rc == AE_NOT_FOUND) { printk("PCI: ACPI table MCFG not found.\n"); return; } if (ACPI_FAILURE(rc)) { ex = AcpiUtValidateException(rc); if (ex) printk("PCI: AcpiGetTable() failed with: %s\n", ex->Name); else printk("PCI: AcpiGetTable() failed with: %d\n", rc); return; } pcie_segments_cnt = (hdr->Length - sizeof(struct acpi_table_mcfg)) / sizeof(*it); it = (void *)((char *)hdr + sizeof(struct acpi_table_mcfg)); printk("PCI: ACPI table MCFG found.\n"); printk("PCI: MCFG has %u elements\n", pcie_segments_cnt); pcie_segments = kalloc_array_obj(struct pci_segment, pcie_segments_cnt); if (UNLIKELY(!pcie_segments)) { printk("PCI: ERROR: no memory for PCIe segments list\n"); pcie_segments_cnt = 0; return; } for (u32 i = 0; i < pcie_segments_cnt; i++, it++) { printk("PCI: MCFG elem[%u]\n", i); printk(" Base paddr: %#llx\n", it->Address); printk(" Segment: %u\n", it->PciSegment); printk(" Start bus: %u\n", it->StartBusNumber); printk(" End bus: %u\n", it->EndBusNumber); pcie_segments[i] = (struct pci_segment) { .base_paddr = it->Address, .segment = it->PciSegment, .start_bus = it->StartBusNumber, .end_bus = it->EndBusNumber, }; } AcpiPutTable(hdr); } static void pci_dump_device_info(struct pci_device_loc loc, struct pci_device_basic_info *nfo) { struct pci_device_class dc = {0}; const char *vendor; dc.class_id = nfo->class_id; dc.subclass_id = nfo->subclass_id; dc.progif_id = nfo->progif_id; pci_find_device_class_name(&dc); vendor = pci_find_vendor_name(nfo->vendor_id); printk("PCI: %04x:%02x:%02x.%x: ", loc.seg, loc.bus, loc.dev, loc.func); if (dc.subclass_name && dc.progif_name) { if (vendor) printk("%s: %s %s\n", dc.subclass_name, vendor, dc.progif_name); else printk("%s (%s)\n", dc.subclass_name, dc.progif_name); } else if (dc.subclass_name) { if (vendor) printk("%s: %s\n", dc.subclass_name, vendor); else printk("%s\n", dc.subclass_name); } else if (dc.class_name) { if (vendor) { if (dc.subclass_id) printk("%s: %s (subclass: %#x)\n", dc.class_name, vendor, dc.subclass_id); else printk("%s: %s\n", dc.class_name, vendor); } else { if (dc.subclass_id) printk("%s (subclass: %#x)\n", dc.class_name, dc.subclass_id); else printk("%s\n", dc.class_name); } } else { if (vendor) printk("vendor: %s, class: %#x, subclass: %#x\n", vendor, dc.class_id, dc.subclass_id); else printk("class: %#x, subclass: %#x\n", dc.class_id, dc.subclass_id); } } static int pci_discover_leaf_node(struct pci_device_loc loc, struct pci_device_basic_info *nfo) { struct pci_device *dev; ulong paddr; int rc; pci_dump_device_info(loc, nfo); if (!(dev = kzalloc_obj(struct pci_device))) return -ENOMEM; list_node_init(&dev->node); dev->loc = loc; dev->nfo = *nfo; list_add_tail(&pci_device_list, &dev->node); if (!pcie_segments_cnt) return 0; /* No PCI express, we're done */ /* PCI express: we have to set the `ext_config` field */ rc = pcie_calc_config_paddr(loc, &paddr); if (rc < 0) { printk("PCI: ERROR: pcie_calc_config_paddr() failed with %d\n", rc); goto err_end; } dev->ext_config = hi_vmem_reserve(4096); if (!dev->ext_config) { rc = -ENOMEM; goto err_end; } rc = map_kernel_page(dev->ext_config, paddr, PAGING_FL_RW); if (rc < 0) goto err_end; return 0; err_end: if (dev->ext_config) hi_vmem_release(dev->ext_config, 4096); list_remove(&dev->node); kfree2(dev, sizeof(struct pci_device)); return rc; } static bool pci_discover_device_func(struct pci_device_loc loc, struct pci_device_basic_info *dev_nfo) { struct pci_device_basic_info __nfo; struct pci_device_basic_info *nfo = &__nfo; u32 secondary_bus; u32 subordinate_bus; int rc; if (loc.func != 0) { if (pci_device_get_info(loc, nfo)) return false; /* no such device function */ } else { ASSERT(dev_nfo != NULL); nfo = dev_nfo; } rc = pci_discover_leaf_node(loc, nfo); if (rc) { printk("PCI: ERROR: pci_discover_leaf_node() failed with: %d\n", rc); return false; /* OOM (out of memory) */ } if (nfo->class_id == PCI_CLASS_BRIDGE && nfo->subclass_id == PCI_SUBCLASS_PCI_BRIDGE) { if (pci_config_read(loc, PCI_HDR1_SECOND_BUS, 8, &secondary_bus)) { printk("PCI: error while reading from config space\n"); return false; } if (pci_config_read(loc, PCI_HDR1_SUBORD_BUS, 8, &subordinate_bus)) { printk("PCI: error while reading from config space\n"); return false; } for (u32 i = secondary_bus; i <= subordinate_bus; i++) pci_mark_bus_to_visit((u8)i); } return true; } static bool pci_discover_device(struct pci_device_loc loc) { struct pci_device_basic_info nfo; ASSERT(loc.func == 0); if (pci_device_get_info(loc, &nfo)) return false; /* no such device */ if (!pci_discover_device_func(loc, &nfo)) { printk("PCI: ERROR discover func 0 failed on existing device!\n"); return false; } if (nfo.multi_func) { /* Multi-function device */ for (u8 func = 1; func < 8; func++) { loc.func = func; pci_discover_device_func(loc, NULL); } } return true; } static bool pci_before_discover_bus(struct pci_segment *seg, u8 bus) { const size_t mmap_sz = 1 * MB; const size_t mmap_pages_cnt = mmap_sz >> PAGE_SHIFT; ulong paddr; u16 seg_num; size_t cnt; void *va; int rc; if (!seg) return true; /* nothing to do */ seg_num = seg->segment; mmio_bus = pci_make_loc(seg_num, bus, 0, 0); rc = pcie_calc_config_paddr(mmio_bus, &paddr); switch (rc) { case 0: /* Success: nothing to do */ break; case -EINVAL: /* This should NEVER happen */ panic("PCI: segment %04x not registered", seg_num); break; case -ERANGE: /* This should also never happen, unless there's a HW problem */ printk("PCI: bus #%u out-of-range in segment %04x\n", bus, seg_num); return false; case -E2BIG: printk("PCI: paddr for seg %04x does not fit in 32-bit\n", seg_num); return false; default: printk("PCI: pcie_calc_config_paddr() failed with: %d\n", rc); return false; } va = hi_vmem_reserve(mmap_sz); if (!va) { printk("PCI: ERROR: hi vmem OOM for %04x:%02x\n", seg_num, bus); return false; } cnt = map_pages(get_kernel_pdir(), va, paddr, mmap_pages_cnt, 0); if (cnt != mmap_pages_cnt) { printk("PCI: ERROR: mmap failed for %04x:%02x\n", seg_num, bus); hi_vmem_release(va, mmap_sz); return false; } mmio_bus_va = (ulong) va; return true; } static void pci_after_discover_bus(struct pci_segment *seg, u8 bus) { const size_t mmap_sz = 1 * MB; const size_t mmap_pages_cnt = mmap_sz >> PAGE_SHIFT; if (!seg) return; /* nothing to do */ ASSERT(mmio_bus.seg == seg->segment); ASSERT(mmio_bus.bus == bus); unmap_kernel_pages((void *)mmio_bus_va, mmap_pages_cnt, false); hi_vmem_release((void *)mmio_bus_va, mmap_sz); mmio_bus_va = 0; } static void pci_discover_bus(struct pci_segment *seg, u8 bus) { const u16 seg_num = seg ? seg->segment : 0; struct pci_device_loc loc = pci_make_loc(seg_num, bus, 0, 0); pci_mark_bus_as_visited(bus); if (bus > 0) { /* * Call pci_before_discover_bus() only for bus > 0 because for bus 0 * we already called it in pci_discover_segment(). */ if (!pci_before_discover_bus(seg, bus)) return; } for (u8 dev = 0; dev < 32; dev++) { loc.dev = dev; pci_discover_device(loc); } pci_after_discover_bus(seg, bus); } static void pci_discover_segment(struct pci_segment *seg) { const u16 seg_num = seg ? seg->segment : 0; struct pci_device_basic_info nfo; int visit_count; if (!pci_before_discover_bus(seg, 0)) return; if (pci_device_get_info(pci_make_loc(seg_num, 0, 0, 0), &nfo)) { printk("PCI: ERROR: cannot get info for host bridge %04x\n", seg_num); pci_after_discover_bus(seg, 0); return; } if (nfo.multi_func) { /* Multiple PCI controllers */ for (u8 func = 1; func < 8; func++) { if (pci_device_get_info(pci_make_loc(0, 0, 0, func), &nfo)) break; pci_mark_bus_to_visit(func); } } pci_discover_bus(seg, 0); /* Discover devices in the additional buses marked for visit */ do { visit_count = 0; for (u32 bus = 1; bus < 256; bus++) { if (pci_buses[bus] == BUS_TO_VISIT) { pci_discover_bus(seg, (u8)bus); visit_count++; } } } while (visit_count > 0); } static void init_pci(void) { int rc; list_init(&pci_device_list); /* Read the ACPI table MCFG (if any) */ init_pci_ecam(); /* Alloc the temporary `pci_buses` buffer */ if (!(pci_buses = kzalloc_array_obj(u8, 256))) { printk("PCI: ERROR: unable to alloc the pci_buses buffer\n"); return; } if (pcie_segments_cnt) { /* PCI Express is supported */ __pci_config_read_func = &pci_mmio_config_read; __pci_config_write_func = &pci_mmio_config_write; pcie_get_conf_vaddr = &discovery_pcie_get_conf_vaddr; /* Iterate over all the PCI Express segment groups */ for (u32 i = 0; i < pcie_segments_cnt; i++) pci_discover_segment(&pcie_segments[i]); pcie_get_conf_vaddr = &regular_pcie_get_conf_vaddr; } else { /* No PCI Express support */ __pci_config_read_func = &pci_ioport_config_read; __pci_config_write_func = &pci_ioport_config_write; pci_discover_segment(NULL); } /* Free the temporary pci_buses buffer */ kfree_array_obj(pci_buses, u8, 256); pci_buses = NULL; rc = pci_create_sysfs_view(); if (rc) printk("PCI: unable to create view in sysfs. Error: %d\n", -rc); } static struct module pci_module = { .name = "pci", .priority = MOD_pci_prio, .init = &init_pci, }; REGISTER_MODULE(&pci_module); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/sync.h> #include <tilck/kernel/kmalloc.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/timer.h> #include <limits.h> // system header #include <3rd_party/acpi/acpi.h> #include <3rd_party/acpi/accommon.h> ACPI_MODULE_NAME("osl_sync") /* * --------------------------------------- * OSL SPINLOCK * --------------------------------------- */ ACPI_STATUS AcpiOsCreateLock(ACPI_SPINLOCK *OutHandle) { ACPI_FUNCTION_TRACE(__FUNC__); if (!OutHandle) return_ACPI_STATUS(AE_BAD_PARAMETER); /* * Tilck does not support SMP, therefore there's no need for real spinlocks: * disabling the interrupts is enough. Hopefully, ACPI will accept a NULL * value, by treating the handle as completely opaque value. */ *OutHandle = NULL; return_ACPI_STATUS(AE_OK); } void AcpiOsDeleteLock(ACPI_SPINLOCK Handle) { ACPI_FUNCTION_TRACE(__FUNC__); } ACPI_CPU_FLAGS AcpiOsAcquireLock(ACPI_SPINLOCK Handle) { ulong flags; ACPI_FUNCTION_TRACE(__FUNC__); disable_interrupts(&flags); return_VALUE(flags); } void AcpiOsReleaseLock( ACPI_SPINLOCK Handle, ACPI_CPU_FLAGS Flags) { ulong flags = (ulong) Flags; enable_interrupts(&flags); ACPI_FUNCTION_TRACE(__FUNC__); return_VOID; } /* * --------------------------------------- * OSL SEMAPHORE * --------------------------------------- */ ACPI_STATUS AcpiOsCreateSemaphore( UINT32 MaxUnits, UINT32 InitialUnits, ACPI_SEMAPHORE *OutHandle) { struct ksem *s; ACPI_FUNCTION_TRACE(__FUNC__); if (MaxUnits == ACPI_NO_UNIT_LIMIT) MaxUnits = INT_MAX; if (MaxUnits > INT_MAX || InitialUnits > INT_MAX || !OutHandle) return_ACPI_STATUS(AE_BAD_PARAMETER); if (!(s = kalloc_obj(struct ksem))) return_ACPI_STATUS(AE_NO_MEMORY); ksem_init(s, (int)InitialUnits, (int)MaxUnits); *OutHandle = s; return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsDeleteSemaphore(ACPI_SEMAPHORE Handle) { struct ksem *s = Handle; ACPI_FUNCTION_TRACE(__FUNC__); if (!Handle) return_ACPI_STATUS(AE_BAD_PARAMETER); ksem_destroy(s); kfree2(Handle, sizeof(struct ksem)); return_ACPI_STATUS(AE_OK); } ACPI_STATUS AcpiOsWaitSemaphore( ACPI_SEMAPHORE Handle, UINT32 Units, UINT16 Timeout) { struct ksem *s = Handle; u64 ticks; int rc; ACPI_FUNCTION_TRACE(__FUNC__); if (Units > INT_MAX || !Handle) return_ACPI_STATUS(AE_BAD_PARAMETER); ticks = ms_to_ticks(Timeout); if (ticks > INT_MAX) return_ACPI_STATUS(AE_BAD_PARAMETER); rc = ksem_wait(s, (int)Units, (int)ticks); switch (rc) { case 0: return_ACPI_STATUS(AE_OK); case -EINVAL: return_ACPI_STATUS(AE_BAD_PARAMETER); case -ETIME: return_ACPI_STATUS(AE_TIME); default: return_ACPI_STATUS(AE_ERROR); } } ACPI_STATUS AcpiOsSignalSemaphore( ACPI_SEMAPHORE Handle, UINT32 Units) { struct ksem *s = Handle; int rc; ACPI_FUNCTION_TRACE(__FUNC__); if (Units > INT_MAX || !Handle) return_ACPI_STATUS(AE_BAD_PARAMETER); rc = ksem_signal(s, (int)Units); switch (rc) { case 0: return_ACPI_STATUS(AE_OK); case -EINVAL: return_ACPI_STATUS(AE_BAD_PARAMETER); case -EDQUOT: return_ACPI_STATUS(AE_LIMIT); default: return_ACPI_STATUS(AE_ERROR); } } <file_sep>#!/bin/sh exec $SYS_CXX "$@" $CC_POST_FLAGS <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ void vfs_fs_exlock(struct mnt_fs *fs) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(fs != NULL); ASSERT(fs->fsops->fs_exlock); fs->fsops->fs_exlock(fs); } void vfs_fs_exunlock(struct mnt_fs *fs) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(fs != NULL); ASSERT(fs->fsops->fs_exunlock); fs->fsops->fs_exunlock(fs); } void vfs_fs_shlock(struct mnt_fs *fs) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(fs != NULL); ASSERT(fs->fsops->fs_shlock); fs->fsops->fs_shlock(fs); } void vfs_fs_shunlock(struct mnt_fs *fs) { NO_TEST_ASSERT(is_preemption_enabled()); ASSERT(fs != NULL); ASSERT(fs->fsops->fs_shunlock); fs->fsops->fs_shunlock(fs); } <file_sep>#!/bin/sh # SPDX-License-Identifier: BSD-2-Clause have_bss=`readelf -S $1 | grep bss` if [ -z "$have_bss" ]; then exit 0 fi echo echo '**** ERROR: the kernel has contents in BSS! ****' echo exit 1 <file_sep>/****************************************************************************** * * Module Name: exconfig - Namespace reconfiguration (Load/Unload opcodes) * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acinterp.h" #include "acnamesp.h" #include "actables.h" #include "acdispat.h" #include "acevents.h" #include "amlcode.h" #define _COMPONENT ACPI_EXECUTER ACPI_MODULE_NAME ("exconfig") /* Local prototypes */ static ACPI_STATUS AcpiExAddTable ( UINT32 TableIndex, ACPI_OPERAND_OBJECT **DdbHandle); static ACPI_STATUS AcpiExRegionRead ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Length, UINT8 *Buffer); /******************************************************************************* * * FUNCTION: AcpiExAddTable * * PARAMETERS: Table - Pointer to raw table * ParentNode - Where to load the table (scope) * DdbHandle - Where to return the table handle. * * RETURN: Status * * DESCRIPTION: Common function to Install and Load an ACPI table with a * returned table handle. * ******************************************************************************/ static ACPI_STATUS AcpiExAddTable ( UINT32 TableIndex, ACPI_OPERAND_OBJECT **DdbHandle) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_FUNCTION_TRACE (ExAddTable); /* Create an object to be the table handle */ ObjDesc = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_REFERENCE); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Init the table handle */ ObjDesc->Common.Flags |= AOPOBJ_DATA_VALID; ObjDesc->Reference.Class = ACPI_REFCLASS_TABLE; ObjDesc->Reference.Value = TableIndex; *DdbHandle = ObjDesc; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExLoadTableOp * * PARAMETERS: WalkState - Current state with operands * ReturnDesc - Where to store the return object * * RETURN: Status * * DESCRIPTION: Load an ACPI table from the RSDT/XSDT * ******************************************************************************/ ACPI_STATUS AcpiExLoadTableOp ( ACPI_WALK_STATE *WalkState, ACPI_OPERAND_OBJECT **ReturnDesc) { ACPI_STATUS Status; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_NAMESPACE_NODE *ParentNode; ACPI_NAMESPACE_NODE *StartNode; ACPI_NAMESPACE_NODE *ParameterNode = NULL; ACPI_OPERAND_OBJECT *DdbHandle; UINT32 TableIndex; ACPI_FUNCTION_TRACE (ExLoadTableOp); /* Find the ACPI table in the RSDT/XSDT */ AcpiExExitInterpreter (); Status = AcpiTbFindTable ( Operand[0]->String.Pointer, Operand[1]->String.Pointer, Operand[2]->String.Pointer, &TableIndex); AcpiExEnterInterpreter (); if (ACPI_FAILURE (Status)) { if (Status != AE_NOT_FOUND) { return_ACPI_STATUS (Status); } /* Table not found, return an Integer=0 and AE_OK */ DdbHandle = AcpiUtCreateIntegerObject ((UINT64) 0); if (!DdbHandle) { return_ACPI_STATUS (AE_NO_MEMORY); } *ReturnDesc = DdbHandle; return_ACPI_STATUS (AE_OK); } /* Default nodes */ StartNode = WalkState->ScopeInfo->Scope.Node; ParentNode = AcpiGbl_RootNode; /* RootPath (optional parameter) */ if (Operand[3]->String.Length > 0) { /* * Find the node referenced by the RootPathString. This is the * location within the namespace where the table will be loaded. */ Status = AcpiNsGetNodeUnlocked (StartNode, Operand[3]->String.Pointer, ACPI_NS_SEARCH_PARENT, &ParentNode); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* ParameterPath (optional parameter) */ if (Operand[4]->String.Length > 0) { if ((Operand[4]->String.Pointer[0] != AML_ROOT_PREFIX) && (Operand[4]->String.Pointer[0] != AML_PARENT_PREFIX)) { /* * Path is not absolute, so it will be relative to the node * referenced by the RootPathString (or the NS root if omitted) */ StartNode = ParentNode; } /* Find the node referenced by the ParameterPathString */ Status = AcpiNsGetNodeUnlocked (StartNode, Operand[4]->String.Pointer, ACPI_NS_SEARCH_PARENT, &ParameterNode); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* Load the table into the namespace */ ACPI_INFO (("Dynamic OEM Table Load:")); AcpiExExitInterpreter (); Status = AcpiTbLoadTable (TableIndex, ParentNode); AcpiExEnterInterpreter (); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiExAddTable (TableIndex, &DdbHandle); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Complete the initialization/resolution of new objects */ AcpiExExitInterpreter(); AcpiNsInitializeObjects(); AcpiExEnterInterpreter(); /* Parameter Data (optional) */ if (ParameterNode) { /* Store the parameter data into the optional parameter object */ Status = AcpiExStore (Operand[5], ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, ParameterNode), WalkState); if (ACPI_FAILURE (Status)) { (void) AcpiExUnloadTable (DdbHandle); AcpiUtRemoveReference (DdbHandle); return_ACPI_STATUS (Status); } } *ReturnDesc = DdbHandle; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExRegionRead * * PARAMETERS: ObjDesc - Region descriptor * Length - Number of bytes to read * Buffer - Pointer to where to put the data * * RETURN: Status * * DESCRIPTION: Read data from an operation region. The read starts from the * beginning of the region. * ******************************************************************************/ static ACPI_STATUS AcpiExRegionRead ( ACPI_OPERAND_OBJECT *ObjDesc, UINT32 Length, UINT8 *Buffer) { ACPI_STATUS Status; UINT64 Value; UINT32 RegionOffset = 0; UINT32 i; /* Bytewise reads */ for (i = 0; i < Length; i++) { Status = AcpiEvAddressSpaceDispatch (ObjDesc, NULL, ACPI_READ, RegionOffset, 8, &Value); if (ACPI_FAILURE (Status)) { return (Status); } *Buffer = (UINT8) Value; Buffer++; RegionOffset++; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiExLoadOp * * PARAMETERS: ObjDesc - Region or Buffer/Field where the table will be * obtained * Target - Where a handle to the table will be stored * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Load an ACPI table from a field or operation region * * NOTE: Region Fields (Field, BankField, IndexFields) are resolved to buffer * objects before this code is reached. * * If source is an operation region, it must refer to SystemMemory, as * per the ACPI specification. * ******************************************************************************/ ACPI_STATUS AcpiExLoadOp ( ACPI_OPERAND_OBJECT *ObjDesc, ACPI_OPERAND_OBJECT *Target, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *DdbHandle; ACPI_TABLE_HEADER *TableHeader; ACPI_TABLE_HEADER *Table; UINT32 TableIndex; ACPI_STATUS Status; UINT32 Length; ACPI_FUNCTION_TRACE (ExLoadOp); /* Source Object can be either an OpRegion or a Buffer/Field */ switch (ObjDesc->Common.Type) { case ACPI_TYPE_REGION: ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Load table from Region %p\n", ObjDesc)); /* Region must be SystemMemory (from ACPI spec) */ if (ObjDesc->Region.SpaceId != ACPI_ADR_SPACE_SYSTEM_MEMORY) { return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* * If the Region Address and Length have not been previously * evaluated, evaluate them now and save the results. */ if (!(ObjDesc->Common.Flags & AOPOBJ_DATA_VALID)) { Status = AcpiDsGetRegionArguments (ObjDesc); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* Get the table header first so we can get the table length */ TableHeader = ACPI_ALLOCATE (sizeof (ACPI_TABLE_HEADER)); if (!TableHeader) { return_ACPI_STATUS (AE_NO_MEMORY); } Status = AcpiExRegionRead (ObjDesc, sizeof (ACPI_TABLE_HEADER), ACPI_CAST_PTR (UINT8, TableHeader)); Length = TableHeader->Length; ACPI_FREE (TableHeader); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Must have at least an ACPI table header */ if (Length < sizeof (ACPI_TABLE_HEADER)) { return_ACPI_STATUS (AE_INVALID_TABLE_LENGTH); } /* * The original implementation simply mapped the table, with no copy. * However, the memory region is not guaranteed to remain stable and * we must copy the table to a local buffer. For example, the memory * region is corrupted after suspend on some machines. Dynamically * loaded tables are usually small, so this overhead is minimal. * * The latest implementation (5/2009) does not use a mapping at all. * We use the low-level operation region interface to read the table * instead of the obvious optimization of using a direct mapping. * This maintains a consistent use of operation regions across the * entire subsystem. This is important if additional processing must * be performed in the (possibly user-installed) operation region * handler. For example, AcpiExec and ASLTS depend on this. */ /* Allocate a buffer for the table */ Table = ACPI_ALLOCATE (Length); if (!Table) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Read the entire table */ Status = AcpiExRegionRead (ObjDesc, Length, ACPI_CAST_PTR (UINT8, Table)); if (ACPI_FAILURE (Status)) { ACPI_FREE (Table); return_ACPI_STATUS (Status); } break; case ACPI_TYPE_BUFFER: /* Buffer or resolved RegionField */ ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Load table from Buffer or Field %p\n", ObjDesc)); /* Must have at least an ACPI table header */ if (ObjDesc->Buffer.Length < sizeof (ACPI_TABLE_HEADER)) { return_ACPI_STATUS (AE_INVALID_TABLE_LENGTH); } /* Get the actual table length from the table header */ TableHeader = ACPI_CAST_PTR ( ACPI_TABLE_HEADER, ObjDesc->Buffer.Pointer); Length = TableHeader->Length; /* Table cannot extend beyond the buffer */ if (Length > ObjDesc->Buffer.Length) { return_ACPI_STATUS (AE_AML_BUFFER_LIMIT); } if (Length < sizeof (ACPI_TABLE_HEADER)) { return_ACPI_STATUS (AE_INVALID_TABLE_LENGTH); } /* * Copy the table from the buffer because the buffer could be * modified or even deleted in the future */ Table = ACPI_ALLOCATE (Length); if (!Table) { return_ACPI_STATUS (AE_NO_MEMORY); } memcpy (Table, TableHeader, Length); break; default: return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* Install the new table into the local data structures */ ACPI_INFO (("Dynamic OEM Table Load:")); AcpiExExitInterpreter (); Status = AcpiTbInstallAndLoadTable (ACPI_PTR_TO_PHYSADDR (Table), ACPI_TABLE_ORIGIN_INTERNAL_VIRTUAL, TRUE, &TableIndex); AcpiExEnterInterpreter (); if (ACPI_FAILURE (Status)) { /* Delete allocated table buffer */ ACPI_FREE (Table); return_ACPI_STATUS (Status); } /* * Add the table to the namespace. * * Note: Load the table objects relative to the root of the namespace. * This appears to go against the ACPI specification, but we do it for * compatibility with other ACPI implementations. */ Status = AcpiExAddTable (TableIndex, &DdbHandle); if (ACPI_FAILURE (Status)) { /* On error, TablePtr was deallocated above */ return_ACPI_STATUS (Status); } /* Complete the initialization/resolution of new objects */ AcpiExExitInterpreter (); AcpiNsInitializeObjects (); AcpiExEnterInterpreter (); /* Store the DdbHandle into the Target operand */ Status = AcpiExStore (DdbHandle, Target, WalkState); if (ACPI_FAILURE (Status)) { (void) AcpiExUnloadTable (DdbHandle); /* TablePtr was deallocated above */ AcpiUtRemoveReference (DdbHandle); return_ACPI_STATUS (Status); } /* Remove the reference by added by AcpiExStore above */ AcpiUtRemoveReference (DdbHandle); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiExUnloadTable * * PARAMETERS: DdbHandle - Handle to a previously loaded table * * RETURN: Status * * DESCRIPTION: Unload an ACPI table * ******************************************************************************/ ACPI_STATUS AcpiExUnloadTable ( ACPI_OPERAND_OBJECT *DdbHandle) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *TableDesc = DdbHandle; UINT32 TableIndex; ACPI_FUNCTION_TRACE (ExUnloadTable); /* * Temporarily emit a warning so that the ASL for the machine can be * hopefully obtained. This is to say that the Unload() operator is * extremely rare if not completely unused. */ ACPI_WARNING ((AE_INFO, "Received request to unload an ACPI table")); /* * May 2018: Unload is no longer supported for the following reasons: * 1) A correct implementation on some hosts may not be possible. * 2) Other ACPI implementations do not correctly/fully support it. * 3) It requires host device driver support which does not exist. * (To properly support namespace unload out from underneath.) * 4) This AML operator has never been seen in the field. */ ACPI_EXCEPTION ((AE_INFO, AE_NOT_IMPLEMENTED, "AML Unload operator is not supported")); /* * Validate the handle * Although the handle is partially validated in AcpiExReconfiguration() * when it calls AcpiExResolveOperands(), the handle is more completely * validated here. * * Handle must be a valid operand object of type reference. Also, the * DdbHandle must still be marked valid (table has not been previously * unloaded) */ if ((!DdbHandle) || (ACPI_GET_DESCRIPTOR_TYPE (DdbHandle) != ACPI_DESC_TYPE_OPERAND) || (DdbHandle->Common.Type != ACPI_TYPE_LOCAL_REFERENCE) || (!(DdbHandle->Common.Flags & AOPOBJ_DATA_VALID))) { return_ACPI_STATUS (AE_AML_OPERAND_TYPE); } /* Get the table index from the DdbHandle */ TableIndex = TableDesc->Reference.Value; /* * Release the interpreter lock so that the table lock won't have * strict order requirement against it. */ AcpiExExitInterpreter (); Status = AcpiTbUnloadTable (TableIndex); AcpiExEnterInterpreter (); /* * Invalidate the handle. We do this because the handle may be stored * in a named object and may not be actually deleted until much later. */ if (ACPI_SUCCESS (Status)) { DdbHandle->Common.Flags &= ~AOPOBJ_DATA_VALID; } return_ACPI_STATUS (Status); } <file_sep>#!/usr/bin/env bash # $1 -> elfhack binary # $2 -> kernel elf file set -e SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" hash=`$SOURCE_DIR/get_commit_hash` exec "$1" "$2" --set-sym-strval .tilck_info tilck_build_info "$hash" <file_sep>#!/bin/sh objdump -D -Mintel,x86-64 -b binary -m i386 $@ <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> /* * NOTE: PNM stands for: portable anymap format (PNM). * This tool supports only PBM (monochrome) and PPM (24 bpp). */ #define PSF1_MAGIC 0x0436 #define PSF2_MAGIC 0x864ab572 struct psf1_header { uint16_t magic; uint8_t mode; uint8_t bytes_per_glyph; }; struct psf2_header { uint32_t magic; uint32_t version; uint32_t header_size; uint32_t flags; uint32_t glyphs_count; uint32_t bytes_per_glyph; uint32_t height; /* height in pixels */ uint32_t width; /* width in pixels */ }; static int font_fd = -1; static size_t font_file_sz; static void *font; static uint32_t font_w; static uint32_t font_h; static uint32_t font_w_bytes; static uint32_t font_bytes_per_glyph; static uint8_t *font_data; static int pnm_fd = -1; static size_t pnm_file_sz; static void *pnm; static void *pnm_data; static int pnm_w; static int pnm_h; static int pnm_w_bytes; static int pnm_w_bytes_half; static int pnm_type; static int rows; static int cols; static bool opt_border = true; static bool opt_quiet = false; static uint8_t (*recognize_char)(void *, int, int); static void (*img_get_char)(int, int, char *); static void img_p4_get_char8(int row, int col, char *dest); static void img_p4_get_char16(int row, int col, char *dest); static uint8_t recognize_char_at_w8(void *img_ptr, int r, int c); static uint8_t recognize_char_at_w16(void *img_ptr, int r, int c); static int open_and_mmap_file(const char *f, void **buf_ref, int *fd_ref, size_t *sz_ref) { struct stat statbuf; int rc, fd = open(f, O_RDONLY); if (fd < 0) return -errno; if (fstat(fd, &statbuf) < 0) goto err_end; *buf_ref = mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0); if (*buf_ref == (void *)-1) goto err_end; *sz_ref = statbuf.st_size; *fd_ref = fd; return 0; err_end: rc = -errno; close(fd); return rc; } static int parse_font_file(void) { struct psf1_header *h1 = font; struct psf2_header *h2 = font; if (h2->magic == PSF2_MAGIC) { font = h2; font_w = h2->width; font_h = h2->height; font_w_bytes = h2->bytes_per_glyph / h2->height; font_data = font + h2->header_size; font_bytes_per_glyph = h2->bytes_per_glyph; } else if (h1->magic == PSF1_MAGIC) { font = h1; font_w = 8; font_h = h1->bytes_per_glyph; font_w_bytes = 1; font_data = font + sizeof(struct psf1_header); font_bytes_per_glyph = h1->bytes_per_glyph; } else { return -1; } if (!opt_quiet) { fprintf(stderr, "Detected %s font: ", h2->magic == PSF2_MAGIC ? "PSF2" : "PSF1"); fprintf(stderr, "%d x %d\n", font_w, font_h); } if (font_w != 8 && font_w != 16) return -1; /* font width not supported */ if (font_w == 8) recognize_char = &recognize_char_at_w8; else recognize_char = &recognize_char_at_w16; return 0; } static int parse_pnm_file(void) { char type[32]; char wstr[16], hstr[16], mvstr[16]; size_t i, n, nl = 2; sscanf(pnm, "%31s %15s %15s", type, wstr, hstr); if (!strcmp(type, "P4")) { pnm_type = 4; } else if (!strcmp(type, "P6")) { sscanf(pnm, "%31s %15s %15s %15s", type, wstr, hstr, mvstr); pnm_type = 6; nl = 3; if (atoi(mvstr) != 255) return -1; } else { return -1; } pnm_w = atoi(wstr); pnm_h = atoi(hstr); if (!pnm_w || !pnm_h) return -1; rows = pnm_h / font_h; cols = pnm_w / font_w; for (i = 0, n = 0; i < pnm_file_sz && n < nl; i++) { if (((char *)pnm)[i] == 10) n++; } if (i == pnm_file_sz) return -1; /* corrupted pnm file */ pnm_data = (char *)pnm + i; if (pnm_type == 4) pnm_w_bytes = (pnm_w + 7) / 8; else if (pnm_type == 6) pnm_w_bytes = pnm_w * 3; pnm_w_bytes_half = pnm_w_bytes / 2; if (!opt_quiet) { fprintf(stderr, "Detected %s image: %d x %d\n", pnm_type == 4 ? "PBM" : "PPM", pnm_w, pnm_h); fprintf(stderr, "Screen size: %d x %d\n", cols, rows); } return 0; } static uint8_t recognize_char_at_w8(void *img_ptr, int r, int c) { int i, y; uint8_t *img = img_ptr; for (i = 0, y = 0; i < 256 && y < font_h; i++) { uint8_t *g = (void *)(font_data + font_bytes_per_glyph * i); if (!memcmp(img, g, font_h)) { i++; break; } for (y = 0; y < font_h; y++) if ((uint8_t)~img[y] != g[y]) break; } return i < 256 ? i-1 : '?'; } static uint8_t recognize_char_at_w16(void *img_ptr, int r, int c) { uint16_t *img = img_ptr; int i, y; for (i = 0, y = 0; i < 256 && y < font_h; i++) { uint16_t *g = (void *)(font_data + font_bytes_per_glyph * i); if (!memcmp(img, g, 2 * font_h)) { i++; break; } for (y = 0; y < font_h; y++) if ((uint16_t)~img[y] != g[y]) break; } return i < 256 ? i-1 : '?'; } static const char transl[256] = { [ 1] = '-', [176] = '#', [177] = '#', [179] = '|', [180] = '+', [191] = '+', [192] = '+', [193] = '+', [194] = '+', [195] = '+', [196] = '-', [197] = '+', [217] = '+', [218] = '+', [219] = '#', [223] = '+', }; static void img_p4_get_char8(int row, int col, char *dest) { void *p = pnm_data + pnm_w_bytes * font_h * row + col; for (int y = 0; y < font_h; y++) ((uint8_t *)dest)[y] = ((uint8_t *)p)[y * pnm_w_bytes]; } static void img_p4_get_char16(int row, int col, char *dest) { void *p = pnm_data + pnm_w_bytes * font_h * row + 2 * col; for (int y = 0; y < font_h; y++) ((uint16_t *)dest)[y] = ((uint16_t *)p)[y * pnm_w_bytes_half]; } static void img_p6_get_colors(uint8_t *p8, uint32_t colors[2]) { colors[0] = *(uint32_t *)p8 & 0x00ffffff; for (int y = 0; y < font_h; y++, p8 += pnm_w_bytes) { for (int b = 0; b < font_w_bytes; b++) { for (int x = 0; x < font_w; x++) { uint32_t c = *(uint32_t *)(p8 + 3 * (x + b * 8)) & 0x00ffffff; if (c != colors[0]) { colors[1] = c; return; } } } } /* No foreground color: alright, it must be a blank character */ colors[1] = 0x00ffffff; } static void img_p6_get_char(int row, int col, char *dest) { void *p = pnm_data + pnm_w_bytes * font_h * row + 24 * col * font_w_bytes; uint8_t *p8 = (uint8_t *)p; uint32_t colors[2] = {0}; img_p6_get_colors(p8, colors); for (int y = 0; y < font_h; y++, p8 += pnm_w_bytes) { for (int b = 0, val = 0; b < font_w_bytes; b++, val = 0) { for (int x = 0; x < 8; x++, val <<= 1) { uint32_t c = *(uint32_t *)(p8 + 3 * (x + b * 8)) & 0x00ffffff; if (c == colors[0]) { /* do nothing: keep the zero */ } else if (c == colors[1]) { val |= 1; } else { /* Oops: we've found a 3rd color. We cannot recognize this. */ bzero(dest, font_w_bytes * font_h); return; } } val >>= 1; ((uint8_t *)dest)[font_w_bytes * y + b] = (val & 0xff); } } } static void recognize_and_print_char(int row, int col) { char imgbuf[font_w_bytes * font_h]; // VLA bzero(imgbuf, font_w_bytes * font_h); img_get_char(row, col, imgbuf); uint8_t c = recognize_char(&imgbuf, row, col); putchar( 32 <= c && c <= 127 ? c : transl[c] ? transl[c] : '?' ); } static void show_help(FILE *fh) { fprintf(fh, "Usage:\n"); fprintf(fh, " pnm2text [-nq] <psf_font> <pnm_screenshot>\n\n"); fprintf(fh, "Options:\n"); fprintf(fh, " -n Don't print any border\n"); fprintf(fh, " -q Quiet: no info messages\n"); } static void show_help_and_exit(void) { show_help(stderr); exit(1); } static void print_hline(void) { putchar('+'); for (int c = 0; c < cols; c++) putchar('-'); putchar('+'); putchar('\n'); } static void parse_and_dump_screen_with_border(void) { print_hline(); for (int r = 0; r < rows; r++) { putchar('|'); for (int c = 0; c < cols; c++) recognize_and_print_char(r, c); putchar('|'); putchar('\n'); } print_hline(); } int main(int argc, char **argv) { int rc; while (argc > 1 && argv[1][0] == '-') { if (!strcmp(argv[1], "-n")) { opt_border = false; } else if (!strcmp(argv[1], "-q")) { opt_quiet = true; } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) { show_help(stdout); return 0; } else { fprintf(stderr, "ERROR: unknown option '%s'\n", argv[1]); show_help_and_exit(); } argc--; argv++; } if (argc < 3) show_help_and_exit(); if ((rc = open_and_mmap_file(argv[1], &font, &font_fd, &font_file_sz)) < 0) { fprintf(stderr, "ERROR: unable to open and mmap '%s': %s\n", argv[1], strerror(errno)); return 1; } if ((rc = open_and_mmap_file(argv[2], &pnm, &pnm_fd, &pnm_file_sz)) < 0) { fprintf(stderr, "ERROR: unable to open and mmap '%s': %s\n", argv[2], strerror(errno)); return 1; } if (parse_font_file() < 0) { fprintf(stderr, "ERROR: invalid font file\n"); close(font_fd); close(pnm_fd); return 1; } if (parse_pnm_file() < 0) { fprintf(stderr, "ERROR: invalid file. It must have P4 or P6 as type\n"); return 1; } if (pnm_type == 4) { if (font_w_bytes == 1) img_get_char = &img_p4_get_char8; else img_get_char = &img_p4_get_char16; } else { /* png_type == "P6" */ img_get_char = &img_p6_get_char; } if (opt_border) { parse_and_dump_screen_with_border(); } else { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) recognize_and_print_char(r, c); putchar('\n'); } } close(font_fd); close(pnm_fd); return 0; } <file_sep>/****************************************************************************** * * Module Name: utcopy - Internal to external object translation utilities * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utcopy") /* Local prototypes */ static ACPI_STATUS AcpiUtCopyIsimpleToEsimple ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_OBJECT *ExternalObject, UINT8 *DataSpace, ACPI_SIZE *BufferSpaceUsed); static ACPI_STATUS AcpiUtCopyIelementToIelement ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context); static ACPI_STATUS AcpiUtCopyIpackageToEpackage ( ACPI_OPERAND_OBJECT *InternalObject, UINT8 *Buffer, ACPI_SIZE *SpaceUsed); static ACPI_STATUS AcpiUtCopyEsimpleToIsimple( ACPI_OBJECT *UserObj, ACPI_OPERAND_OBJECT **ReturnObj); static ACPI_STATUS AcpiUtCopyEpackageToIpackage ( ACPI_OBJECT *ExternalObject, ACPI_OPERAND_OBJECT **InternalObject); static ACPI_STATUS AcpiUtCopySimpleObject ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *DestDesc); static ACPI_STATUS AcpiUtCopyIelementToEelement ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context); static ACPI_STATUS AcpiUtCopyIpackageToIpackage ( ACPI_OPERAND_OBJECT *SourceObj, ACPI_OPERAND_OBJECT *DestObj, ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiUtCopyIsimpleToEsimple * * PARAMETERS: InternalObject - Source object to be copied * ExternalObject - Where to return the copied object * DataSpace - Where object data is returned (such as * buffer and string data) * BufferSpaceUsed - Length of DataSpace that was used * * RETURN: Status * * DESCRIPTION: This function is called to copy a simple internal object to * an external object. * * The DataSpace buffer is assumed to have sufficient space for * the object. * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyIsimpleToEsimple ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_OBJECT *ExternalObject, UINT8 *DataSpace, ACPI_SIZE *BufferSpaceUsed) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (UtCopyIsimpleToEsimple); *BufferSpaceUsed = 0; /* * Check for NULL object case (could be an uninitialized * package element) */ if (!InternalObject) { return_ACPI_STATUS (AE_OK); } /* Always clear the external object */ memset (ExternalObject, 0, sizeof (ACPI_OBJECT)); /* * In general, the external object will be the same type as * the internal object */ ExternalObject->Type = InternalObject->Common.Type; /* However, only a limited number of external types are supported */ switch (InternalObject->Common.Type) { case ACPI_TYPE_STRING: ExternalObject->String.Pointer = (char *) DataSpace; ExternalObject->String.Length = InternalObject->String.Length; *BufferSpaceUsed = ACPI_ROUND_UP_TO_NATIVE_WORD ( (ACPI_SIZE) InternalObject->String.Length + 1); memcpy ((void *) DataSpace, (void *) InternalObject->String.Pointer, (ACPI_SIZE) InternalObject->String.Length + 1); break; case ACPI_TYPE_BUFFER: ExternalObject->Buffer.Pointer = DataSpace; ExternalObject->Buffer.Length = InternalObject->Buffer.Length; *BufferSpaceUsed = ACPI_ROUND_UP_TO_NATIVE_WORD ( InternalObject->String.Length); memcpy ((void *) DataSpace, (void *) InternalObject->Buffer.Pointer, InternalObject->Buffer.Length); break; case ACPI_TYPE_INTEGER: ExternalObject->Integer.Value = InternalObject->Integer.Value; break; case ACPI_TYPE_LOCAL_REFERENCE: /* This is an object reference. */ switch (InternalObject->Reference.Class) { case ACPI_REFCLASS_NAME: /* * For namepath, return the object handle ("reference") * We are referring to the namespace node */ ExternalObject->Reference.Handle = InternalObject->Reference.Node; ExternalObject->Reference.ActualType = AcpiNsGetType (InternalObject->Reference.Node); break; default: /* All other reference types are unsupported */ return_ACPI_STATUS (AE_TYPE); } break; case ACPI_TYPE_PROCESSOR: ExternalObject->Processor.ProcId = InternalObject->Processor.ProcId; ExternalObject->Processor.PblkAddress = InternalObject->Processor.Address; ExternalObject->Processor.PblkLength = InternalObject->Processor.Length; break; case ACPI_TYPE_POWER: ExternalObject->PowerResource.SystemLevel = InternalObject->PowerResource.SystemLevel; ExternalObject->PowerResource.ResourceOrder = InternalObject->PowerResource.ResourceOrder; break; default: /* * There is no corresponding external object type */ ACPI_ERROR ((AE_INFO, "Unsupported object type, cannot convert to external object: %s", AcpiUtGetTypeName (InternalObject->Common.Type))); return_ACPI_STATUS (AE_SUPPORT); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIelementToEelement * * PARAMETERS: ACPI_PKG_CALLBACK * * RETURN: Status * * DESCRIPTION: Copy one package element to another package element * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyIelementToEelement ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context) { ACPI_STATUS Status = AE_OK; ACPI_PKG_INFO *Info = (ACPI_PKG_INFO *) Context; ACPI_SIZE ObjectSpace; UINT32 ThisIndex; ACPI_OBJECT *TargetObject; ACPI_FUNCTION_ENTRY (); ThisIndex = State->Pkg.Index; TargetObject = (ACPI_OBJECT *) &((ACPI_OBJECT *) (State->Pkg.DestObject))->Package.Elements[ThisIndex]; switch (ObjectType) { case ACPI_COPY_TYPE_SIMPLE: /* * This is a simple or null object */ Status = AcpiUtCopyIsimpleToEsimple (SourceObject, TargetObject, Info->FreeSpace, &ObjectSpace); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_COPY_TYPE_PACKAGE: /* * Build the package object */ TargetObject->Type = ACPI_TYPE_PACKAGE; TargetObject->Package.Count = SourceObject->Package.Count; TargetObject->Package.Elements = ACPI_CAST_PTR (ACPI_OBJECT, Info->FreeSpace); /* * Pass the new package object back to the package walk routine */ State->Pkg.ThisTargetObj = TargetObject; /* * Save space for the array of objects (Package elements) * update the buffer length counter */ ObjectSpace = ACPI_ROUND_UP_TO_NATIVE_WORD ( (ACPI_SIZE) TargetObject->Package.Count * sizeof (ACPI_OBJECT)); break; default: return (AE_BAD_PARAMETER); } Info->FreeSpace += ObjectSpace; Info->Length += ObjectSpace; return (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIpackageToEpackage * * PARAMETERS: InternalObject - Pointer to the object we are returning * Buffer - Where the object is returned * SpaceUsed - Where the object length is returned * * RETURN: Status * * DESCRIPTION: This function is called to place a package object in a user * buffer. A package object by definition contains other objects. * * The buffer is assumed to have sufficient space for the object. * The caller must have verified the buffer length needed using * the AcpiUtGetObjectSize function before calling this function. * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyIpackageToEpackage ( ACPI_OPERAND_OBJECT *InternalObject, UINT8 *Buffer, ACPI_SIZE *SpaceUsed) { ACPI_OBJECT *ExternalObject; ACPI_STATUS Status; ACPI_PKG_INFO Info; ACPI_FUNCTION_TRACE (UtCopyIpackageToEpackage); /* * First package at head of the buffer */ ExternalObject = ACPI_CAST_PTR (ACPI_OBJECT, Buffer); /* * Free space begins right after the first package */ Info.Length = ACPI_ROUND_UP_TO_NATIVE_WORD (sizeof (ACPI_OBJECT)); Info.FreeSpace = Buffer + ACPI_ROUND_UP_TO_NATIVE_WORD (sizeof (ACPI_OBJECT)); Info.ObjectSpace = 0; Info.NumPackages = 1; ExternalObject->Type = InternalObject->Common.Type; ExternalObject->Package.Count = InternalObject->Package.Count; ExternalObject->Package.Elements = ACPI_CAST_PTR (ACPI_OBJECT, Info.FreeSpace); /* * Leave room for an array of ACPI_OBJECTS in the buffer * and move the free space past it */ Info.Length += (ACPI_SIZE) ExternalObject->Package.Count * ACPI_ROUND_UP_TO_NATIVE_WORD (sizeof (ACPI_OBJECT)); Info.FreeSpace += ExternalObject->Package.Count * ACPI_ROUND_UP_TO_NATIVE_WORD (sizeof (ACPI_OBJECT)); Status = AcpiUtWalkPackageTree (InternalObject, ExternalObject, AcpiUtCopyIelementToEelement, &Info); *SpaceUsed = Info.Length; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIobjectToEobject * * PARAMETERS: InternalObject - The internal object to be converted * RetBuffer - Where the object is returned * * RETURN: Status * * DESCRIPTION: This function is called to build an API object to be returned * to the caller. * ******************************************************************************/ ACPI_STATUS AcpiUtCopyIobjectToEobject ( ACPI_OPERAND_OBJECT *InternalObject, ACPI_BUFFER *RetBuffer) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtCopyIobjectToEobject); if (InternalObject->Common.Type == ACPI_TYPE_PACKAGE) { /* * Package object: Copy all subobjects (including * nested packages) */ Status = AcpiUtCopyIpackageToEpackage (InternalObject, RetBuffer->Pointer, &RetBuffer->Length); } else { /* * Build a simple object (no nested objects) */ Status = AcpiUtCopyIsimpleToEsimple (InternalObject, ACPI_CAST_PTR (ACPI_OBJECT, RetBuffer->Pointer), ACPI_ADD_PTR (UINT8, RetBuffer->Pointer, ACPI_ROUND_UP_TO_NATIVE_WORD (sizeof (ACPI_OBJECT))), &RetBuffer->Length); /* * build simple does not include the object size in the length * so we add it in here */ RetBuffer->Length += sizeof (ACPI_OBJECT); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyEsimpleToIsimple * * PARAMETERS: ExternalObject - The external object to be converted * RetInternalObject - Where the internal object is returned * * RETURN: Status * * DESCRIPTION: This function copies an external object to an internal one. * NOTE: Pointers can be copied, we don't need to copy data. * (The pointers have to be valid in our address space no matter * what we do with them!) * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyEsimpleToIsimple ( ACPI_OBJECT *ExternalObject, ACPI_OPERAND_OBJECT **RetInternalObject) { ACPI_OPERAND_OBJECT *InternalObject; ACPI_FUNCTION_TRACE (UtCopyEsimpleToIsimple); /* * Simple types supported are: String, Buffer, Integer */ switch (ExternalObject->Type) { case ACPI_TYPE_STRING: case ACPI_TYPE_BUFFER: case ACPI_TYPE_INTEGER: case ACPI_TYPE_LOCAL_REFERENCE: InternalObject = AcpiUtCreateInternalObject ( (UINT8) ExternalObject->Type); if (!InternalObject) { return_ACPI_STATUS (AE_NO_MEMORY); } break; case ACPI_TYPE_ANY: /* This is the case for a NULL object */ *RetInternalObject = NULL; return_ACPI_STATUS (AE_OK); default: /* All other types are not supported */ ACPI_ERROR ((AE_INFO, "Unsupported object type, cannot convert to internal object: %s", AcpiUtGetTypeName (ExternalObject->Type))); return_ACPI_STATUS (AE_SUPPORT); } /* Must COPY string and buffer contents */ switch (ExternalObject->Type) { case ACPI_TYPE_STRING: InternalObject->String.Pointer = ACPI_ALLOCATE_ZEROED ((ACPI_SIZE) ExternalObject->String.Length + 1); if (!InternalObject->String.Pointer) { goto ErrorExit; } memcpy (InternalObject->String.Pointer, ExternalObject->String.Pointer, ExternalObject->String.Length); InternalObject->String.Length = ExternalObject->String.Length; break; case ACPI_TYPE_BUFFER: InternalObject->Buffer.Pointer = ACPI_ALLOCATE_ZEROED (ExternalObject->Buffer.Length); if (!InternalObject->Buffer.Pointer) { goto ErrorExit; } memcpy (InternalObject->Buffer.Pointer, ExternalObject->Buffer.Pointer, ExternalObject->Buffer.Length); InternalObject->Buffer.Length = ExternalObject->Buffer.Length; /* Mark buffer data valid */ InternalObject->Buffer.Flags |= AOPOBJ_DATA_VALID; break; case ACPI_TYPE_INTEGER: InternalObject->Integer.Value = ExternalObject->Integer.Value; break; case ACPI_TYPE_LOCAL_REFERENCE: /* An incoming reference is defined to be a namespace node */ InternalObject->Reference.Class = ACPI_REFCLASS_REFOF; InternalObject->Reference.Object = ExternalObject->Reference.Handle; break; default: /* Other types can't get here */ break; } *RetInternalObject = InternalObject; return_ACPI_STATUS (AE_OK); ErrorExit: AcpiUtRemoveReference (InternalObject); return_ACPI_STATUS (AE_NO_MEMORY); } /******************************************************************************* * * FUNCTION: AcpiUtCopyEpackageToIpackage * * PARAMETERS: ExternalObject - The external object to be converted * InternalObject - Where the internal object is returned * * RETURN: Status * * DESCRIPTION: Copy an external package object to an internal package. * Handles nested packages. * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyEpackageToIpackage ( ACPI_OBJECT *ExternalObject, ACPI_OPERAND_OBJECT **InternalObject) { ACPI_STATUS Status = AE_OK; ACPI_OPERAND_OBJECT *PackageObject; ACPI_OPERAND_OBJECT **PackageElements; UINT32 i; ACPI_FUNCTION_TRACE (UtCopyEpackageToIpackage); /* Create the package object */ PackageObject = AcpiUtCreatePackageObject ( ExternalObject->Package.Count); if (!PackageObject) { return_ACPI_STATUS (AE_NO_MEMORY); } PackageElements = PackageObject->Package.Elements; /* * Recursive implementation. Probably ok, since nested external * packages as parameters should be very rare. */ for (i = 0; i < ExternalObject->Package.Count; i++) { Status = AcpiUtCopyEobjectToIobject ( &ExternalObject->Package.Elements[i], &PackageElements[i]); if (ACPI_FAILURE (Status)) { /* Truncate package and delete it */ PackageObject->Package.Count = i; PackageElements[i] = NULL; AcpiUtRemoveReference (PackageObject); return_ACPI_STATUS (Status); } } /* Mark package data valid */ PackageObject->Package.Flags |= AOPOBJ_DATA_VALID; *InternalObject = PackageObject; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyEobjectToIobject * * PARAMETERS: ExternalObject - The external object to be converted * InternalObject - Where the internal object is returned * * RETURN: Status * * DESCRIPTION: Converts an external object to an internal object. * ******************************************************************************/ ACPI_STATUS AcpiUtCopyEobjectToIobject ( ACPI_OBJECT *ExternalObject, ACPI_OPERAND_OBJECT **InternalObject) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (UtCopyEobjectToIobject); if (ExternalObject->Type == ACPI_TYPE_PACKAGE) { Status = AcpiUtCopyEpackageToIpackage ( ExternalObject, InternalObject); } else { /* * Build a simple object (no nested objects) */ Status = AcpiUtCopyEsimpleToIsimple (ExternalObject, InternalObject); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopySimpleObject * * PARAMETERS: SourceDesc - The internal object to be copied * DestDesc - New target object * * RETURN: Status * * DESCRIPTION: Simple copy of one internal object to another. Reference count * of the destination object is preserved. * ******************************************************************************/ static ACPI_STATUS AcpiUtCopySimpleObject ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT *DestDesc) { UINT16 ReferenceCount; ACPI_OPERAND_OBJECT *NextObject; ACPI_STATUS Status; ACPI_SIZE CopySize; /* Save fields from destination that we don't want to overwrite */ ReferenceCount = DestDesc->Common.ReferenceCount; NextObject = DestDesc->Common.NextObject; /* * Copy the entire source object over the destination object. * Note: Source can be either an operand object or namespace node. */ CopySize = sizeof (ACPI_OPERAND_OBJECT); if (ACPI_GET_DESCRIPTOR_TYPE (SourceDesc) == ACPI_DESC_TYPE_NAMED) { CopySize = sizeof (ACPI_NAMESPACE_NODE); } memcpy (ACPI_CAST_PTR (char, DestDesc), ACPI_CAST_PTR (char, SourceDesc), CopySize); /* Restore the saved fields */ DestDesc->Common.ReferenceCount = ReferenceCount; DestDesc->Common.NextObject = NextObject; /* New object is not static, regardless of source */ DestDesc->Common.Flags &= ~AOPOBJ_STATIC_POINTER; /* Handle the objects with extra data */ switch (DestDesc->Common.Type) { case ACPI_TYPE_BUFFER: /* * Allocate and copy the actual buffer if and only if: * 1) There is a valid buffer pointer * 2) The buffer has a length > 0 */ if ((SourceDesc->Buffer.Pointer) && (SourceDesc->Buffer.Length)) { DestDesc->Buffer.Pointer = ACPI_ALLOCATE (SourceDesc->Buffer.Length); if (!DestDesc->Buffer.Pointer) { return (AE_NO_MEMORY); } /* Copy the actual buffer data */ memcpy (DestDesc->Buffer.Pointer, SourceDesc->Buffer.Pointer, SourceDesc->Buffer.Length); } break; case ACPI_TYPE_STRING: /* * Allocate and copy the actual string if and only if: * 1) There is a valid string pointer * (Pointer to a NULL string is allowed) */ if (SourceDesc->String.Pointer) { DestDesc->String.Pointer = ACPI_ALLOCATE ((ACPI_SIZE) SourceDesc->String.Length + 1); if (!DestDesc->String.Pointer) { return (AE_NO_MEMORY); } /* Copy the actual string data */ memcpy (DestDesc->String.Pointer, SourceDesc->String.Pointer, (ACPI_SIZE) SourceDesc->String.Length + 1); } break; case ACPI_TYPE_LOCAL_REFERENCE: /* * We copied the reference object, so we now must add a reference * to the object pointed to by the reference * * DDBHandle reference (from Load/LoadTable) is a special reference, * it does not have a Reference.Object, so does not need to * increase the reference count */ if (SourceDesc->Reference.Class == ACPI_REFCLASS_TABLE) { break; } AcpiUtAddReference (SourceDesc->Reference.Object); break; case ACPI_TYPE_REGION: /* * We copied the Region Handler, so we now must add a reference */ if (DestDesc->Region.Handler) { AcpiUtAddReference (DestDesc->Region.Handler); } break; /* * For Mutex and Event objects, we cannot simply copy the underlying * OS object. We must create a new one. */ case ACPI_TYPE_MUTEX: Status = AcpiOsCreateMutex (&DestDesc->Mutex.OsMutex); if (ACPI_FAILURE (Status)) { return (Status); } break; case ACPI_TYPE_EVENT: Status = AcpiOsCreateSemaphore (ACPI_NO_UNIT_LIMIT, 0, &DestDesc->Event.OsSemaphore); if (ACPI_FAILURE (Status)) { return (Status); } break; default: /* Nothing to do for other simple objects */ break; } return (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIelementToIelement * * PARAMETERS: ACPI_PKG_CALLBACK * * RETURN: Status * * DESCRIPTION: Copy one package element to another package element * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyIelementToIelement ( UINT8 ObjectType, ACPI_OPERAND_OBJECT *SourceObject, ACPI_GENERIC_STATE *State, void *Context) { ACPI_STATUS Status = AE_OK; UINT32 ThisIndex; ACPI_OPERAND_OBJECT **ThisTargetPtr; ACPI_OPERAND_OBJECT *TargetObject; ACPI_FUNCTION_ENTRY (); ThisIndex = State->Pkg.Index; ThisTargetPtr = (ACPI_OPERAND_OBJECT **) &State->Pkg.DestObject->Package.Elements[ThisIndex]; switch (ObjectType) { case ACPI_COPY_TYPE_SIMPLE: /* A null source object indicates a (legal) null package element */ if (SourceObject) { /* * This is a simple object, just copy it */ TargetObject = AcpiUtCreateInternalObject ( SourceObject->Common.Type); if (!TargetObject) { return (AE_NO_MEMORY); } Status = AcpiUtCopySimpleObject (SourceObject, TargetObject); if (ACPI_FAILURE (Status)) { goto ErrorExit; } *ThisTargetPtr = TargetObject; } else { /* Pass through a null element */ *ThisTargetPtr = NULL; } break; case ACPI_COPY_TYPE_PACKAGE: /* * This object is a package - go down another nesting level * Create and build the package object */ TargetObject = AcpiUtCreatePackageObject ( SourceObject->Package.Count); if (!TargetObject) { return (AE_NO_MEMORY); } TargetObject->Common.Flags = SourceObject->Common.Flags; /* Pass the new package object back to the package walk routine */ State->Pkg.ThisTargetObj = TargetObject; /* Store the object pointer in the parent package object */ *ThisTargetPtr = TargetObject; break; default: return (AE_BAD_PARAMETER); } return (Status); ErrorExit: AcpiUtRemoveReference (TargetObject); return (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIpackageToIpackage * * PARAMETERS: SourceObj - Pointer to the source package object * DestObj - Where the internal object is returned * WalkState - Current Walk state descriptor * * RETURN: Status * * DESCRIPTION: This function is called to copy an internal package object * into another internal package object. * ******************************************************************************/ static ACPI_STATUS AcpiUtCopyIpackageToIpackage ( ACPI_OPERAND_OBJECT *SourceObj, ACPI_OPERAND_OBJECT *DestObj, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (UtCopyIpackageToIpackage); DestObj->Common.Type = SourceObj->Common.Type; DestObj->Common.Flags = SourceObj->Common.Flags; DestObj->Package.Count = SourceObj->Package.Count; /* * Create the object array and walk the source package tree */ DestObj->Package.Elements = ACPI_ALLOCATE_ZEROED ( ((ACPI_SIZE) SourceObj->Package.Count + 1) * sizeof (void *)); if (!DestObj->Package.Elements) { ACPI_ERROR ((AE_INFO, "Package allocation failure")); return_ACPI_STATUS (AE_NO_MEMORY); } /* * Copy the package element-by-element by walking the package "tree". * This handles nested packages of arbitrary depth. */ Status = AcpiUtWalkPackageTree (SourceObj, DestObj, AcpiUtCopyIelementToIelement, WalkState); if (ACPI_FAILURE (Status)) { /* On failure, delete the destination package object */ AcpiUtRemoveReference (DestObj); } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiUtCopyIobjectToIobject * * PARAMETERS: SourceDesc - The internal object to be copied * DestDesc - Where the copied object is returned * WalkState - Current walk state * * RETURN: Status * * DESCRIPTION: Copy an internal object to a new internal object * ******************************************************************************/ ACPI_STATUS AcpiUtCopyIobjectToIobject ( ACPI_OPERAND_OBJECT *SourceDesc, ACPI_OPERAND_OBJECT **DestDesc, ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (UtCopyIobjectToIobject); /* Create the top level object */ *DestDesc = AcpiUtCreateInternalObject (SourceDesc->Common.Type); if (!*DestDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Copy the object and possible subobjects */ if (SourceDesc->Common.Type == ACPI_TYPE_PACKAGE) { Status = AcpiUtCopyIpackageToIpackage ( SourceDesc, *DestDesc, WalkState); } else { Status = AcpiUtCopySimpleObject (SourceDesc, *DestDesc); } /* Delete the allocated object if copy failed */ if (ACPI_FAILURE (Status)) { AcpiUtRemoveReference (*DestDesc); } return_ACPI_STATUS (Status); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once /* --------- Boolean config variables --------- */ #cmakedefine01 INIT_REPORT_PROC_EXIT /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are many dervied constants and convenience constants not * designed to be easily changed because of the code makes assumptions about * them. Because of that, those constants are hard-coded and not available as * CMake variables. With time, some of those constants get "promoted" and moved * in CMake, others remain here. See the comments and think about the potential * implications before promoting a hard-coded constant to a configurable CMake * variable. */ #define BUSYBOX "/initrd/bin/busybox" #define START_SCRIPT "/initrd/etc/start" #define DEFAULT_SHELL "/bin/ash" #define TTYS0_MINOR 64 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #if !defined(__i386__) && !defined(__x86_64__) #error This header can be used only for x86 and x86-64 architectures. #endif #include <tilck/common/basic_defs.h> #include <tilck/common/arch/generic_x86/asm_consts.h> /* * HACK: include directly <ia32intrin.h> because <x86intrin.h> includes too much * stuff like FPU-related funcs which don't compile on x86_64 because we have * disabled FPU instructions. */ #define _X86INTRIN_H_INCLUDED /* for GCC */ #define _X86GPRINTRIN_H_INCLUDED /* for GCC 11 */ #define __X86INTRIN_H /* for clang */ #include <ia32intrin.h> #define X86_PC_TIMER_IRQ 0 #define X86_PC_KEYBOARD_IRQ 1 #define X86_PC_COM2_COM4_IRQ 3 #define X86_PC_COM1_COM3_IRQ 4 #define X86_PC_SOUND_IRQ 5 #define X86_PC_FLOPPY_IRQ 6 #define X86_PC_LPT1_OR_SLAVE_IRQ 7 #define X86_PC_RTC_IRQ 8 #define X86_PC_ACPI_IRQ 9 #define X86_PC_PCI1_IRQ 10 #define X86_PC_PCI2_IRQ 11 #define X86_PC_PS2_MOUSE_IRQ 12 #define X86_PC_MATH_COPROC_IRQ 13 #define X86_PC_HD_IRQ 14 /* * The following FAULTs are valid both for x86 (i386+) and for x86_64. */ #define FAULT_DIVISION_BY_ZERO 0 #define FAULT_DEBUG 1 #define FAULT_NMI 2 #define FAULT_BREAKPOINT 3 #define FAULT_INTO_DEC_OVERFLOW 4 #define FAULT_OUT_OF_BOUNDS 5 #define FAULT_INVALID_OPCODE 6 #define FAULT_NO_COPROC 7 #define FAULT_DOUBLE_FAULT 8 #define FAULT_COPROC_SEG_OVERRRUN 9 #define FAULT_BAD_TSS 10 #define FAULT_SEG_NOT_PRESENT 11 #define FAULT_STACK_FAULT 12 #define FAULT_GENERAL_PROTECTION 13 #define FAULT_PAGE_FAULT 14 #define FAULT_UNKNOWN_INTERRUPT 15 #define FAULT_COPROC_FAULT 16 #define FAULT_ALIGN_FAULT 17 #define FAULT_MACHINE_CHECK 18 #define SYSCALL_SOFT_INTERRUPT 0x80 #define MEM_TYPE_UC 0x00 // Uncacheable #define MEM_TYPE_WC 0x01 // Write Combining #define MEM_TYPE_R1 0x02 // Reserved 1 #define MEM_TYPE_R2 0x03 // Reserved 2 #define MEM_TYPE_WT 0x04 // Write Through #define MEM_TYPE_WP 0x05 // Write Protected #define MEM_TYPE_WB 0x06 // Write Back #define MEM_TYPE_UC_ 0x07 // Uncached (PAT only) #define COM1 0x3f8 #define COM2 0x2f8 #define COM3 0x3e8 #define COM4 0x2e8 /* * x86 selectors are 16 bit integers: * * +------------------+----------------+--------------+ * | index [13 bits] | table [1 bit] | RPL [2 bits] | * +------- ----------+----------------+--------------+ * * table: * 0 means the index is in GDT * 1 means the index is in LDT * * RPL: requested privilege level [0..3] */ #define TABLE_GDT 0 #define TABLE_LDT 1 #define X86_SELECTOR(idx, table, rpl) ((u16)((idx << 3) | (table << 2) | (rpl))) /* Defines useful when calling fault_resumable_call() */ #define ALL_FAULTS_MASK (0xFFFFFFFF) #define PAGE_FAULT_MASK (1 << FAULT_PAGE_FAULT) #define RDTSC() __rdtsc() #define MEM_CLOBBER(var, type, size) (*(type (*)[size])(var)) #if defined(__GNUC__) && !defined(__clang__) #define MEM_CLOBBER_NOSZ(var, type) (*(type (*)[])(var)) #else /* * NOTE: clang does not support the *(type (*)[])(var) syntax to clobber * memory areas with unspecified size. * * See: https://bugs.llvm.org/show_bug.cgi?id=47866 */ #define MEM_CLOBBER_NOSZ(var, type) MEM_CLOBBER((var), type, 64 * KB) #endif static ALWAYS_INLINE void outb(u16 port, u8 val) { asmVolatile( "outb %[value], %[port]" : /* no output */ : [value] "a"(val), [port] "Nd"(port) ); } static ALWAYS_INLINE u8 inb(u16 port) { u8 ret; asmVolatile( "inb %[port], %[result]" : [result] "=a"(ret) : [port] "Nd"(port) ); return ret; } static ALWAYS_INLINE void outw(u16 port, u16 val) { asmVolatile( "outw %[value], %[port]" : /* no output */ : [value] "a"(val), [port] "Nd"(port) ); } static ALWAYS_INLINE u16 inw(u16 port) { u16 ret; asmVolatile( "inw %[port], %[result]" : [result] "=a"(ret) : [port] "Nd"(port) ); return ret; } static ALWAYS_INLINE void outl(u16 port, u32 val) { asmVolatile( "outl %[value], %[port]" : /* no output */ : [value] "a"(val), [port] "Nd"(port) ); } static ALWAYS_INLINE u32 inl(u16 port) { u32 ret; asmVolatile( "inl %[port], %[result]" : [result] "=a"(ret) : [port] "Nd"(port) ); return ret; } static ALWAYS_INLINE void halt(void) { asmVolatile("hlt"); } static ALWAYS_INLINE void wrmsr(u32 msr_id, u64 msr_value) { asmVolatile( "wrmsr" : : "c" (msr_id), "A" (msr_value) ); } static ALWAYS_INLINE u64 rdmsr(u32 msr_id) { u64 msr_value; asmVolatile( "rdmsr" : "=A" (msr_value) : "c" (msr_id) ); return msr_value; } static ALWAYS_INLINE ulong get_eflags(void) { ulong eflags; asmVolatile("pushf\n\t" "pop %0\n\t" : "=g"(eflags) ); return eflags; } static ALWAYS_INLINE void set_eflags(ulong f) { asmVolatile("push %0\n\t" "popf\n\t" : /* no output */ : "r" (f) : "cc"); } static ALWAYS_INLINE void enable_interrupts_forced(void) { #ifndef UNIT_TEST_ENVIRONMENT asmVolatile("sti"); #endif } static ALWAYS_INLINE void disable_interrupts_forced(void) { #ifndef UNIT_TEST_ENVIRONMENT asmVolatile("cli"); #endif } static ALWAYS_INLINE bool are_interrupts_enabled(void) { return !!(get_eflags() & EFLAGS_IF); } static ALWAYS_INLINE void disable_interrupts(ulong *const var) { *var = get_eflags(); if (*var & EFLAGS_IF) { disable_interrupts_forced(); } } static ALWAYS_INLINE void enable_interrupts(const ulong *const var) { if (*var & EFLAGS_IF) { enable_interrupts_forced(); } } /* * Invalidates the TLB entry used for resolving the page containing 'vaddr'. */ static ALWAYS_INLINE void invalidate_page_hw(ulong vaddr) { asmVolatile("invlpg (%0)" : /* no output */ :"r" (vaddr) : "memory"); } static ALWAYS_INLINE void write_back_and_invl_cache(void) { asmVolatile("wbinvd"); } static ALWAYS_INLINE void cpuid(u32 code, u32 *a, u32 *b, u32 *c, u32 *d) { asm("cpuid" : "=a"(*a), "=b" (*b), "=c" (*c), "=d"(*d) : "a"(code), "b" (0), "c" (0), "d" (0) : "memory"); } static ALWAYS_INLINE ulong read_cr0(void) { ulong res; asmVolatile("mov %%cr0, %0" : "=r" (res) : /* no input */ : /* no clobber */); return res; } static ALWAYS_INLINE void write_cr0(ulong val) { asmVolatile("mov %0, %%cr0" : /* no output */ : "r" (val) : /* no clobber */); } static ALWAYS_INLINE ulong read_cr3(void) { ulong res; asmVolatile("mov %%cr3, %0" : "=r" (res) : /* no input */ : /* no clobber */); return res; } static ALWAYS_INLINE void write_cr3(ulong val) { asmVolatile("mov %0, %%cr3" : /* no output */ : "r" (val) : /* no clobber */); } static ALWAYS_INLINE ulong read_cr4(void) { ulong res; asmVolatile("mov %%cr4, %0" : "=r" (res) : /* no input */ : /* no clobber */); return res; } static ALWAYS_INLINE void write_cr4(ulong val) { asmVolatile("mov %0, %%cr4" : /* no output */ : "r" (val) : /* no clobber */); } static ALWAYS_INLINE void hw_fpu_enable(void) { write_cr0(read_cr0() & ~CR0_TS); } static ALWAYS_INLINE void hw_fpu_disable(void) { write_cr0(read_cr0() | CR0_TS); } static ALWAYS_INLINE bool hw_is_fpu_enabled(void) { return !(read_cr0() & CR0_TS); } static ALWAYS_INLINE ulong __get_curr_pdir() { return read_cr3(); } static ALWAYS_INLINE void __set_curr_pdir(ulong paddr) { write_cr3(paddr); } void i8042_reboot(void); <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ /* * This is a TEMPLATE. The actual config file is generated by CMake and stored * in <BUILD_DIR>/tilck_gen_headers/. */ #pragma once /* ------ Value-based config variables -------- */ #define TIMER_HZ @TIMER_HZ@ /* --------- Boolean config variables --------- */ #cmakedefine01 KRN_RESCHED_ENABLE_PREEMPT /* * -------------------------------------------------------------------------- * Hard-coded global & derived constants * -------------------------------------------------------------------------- * * Here below there are some pseudo-constants not designed to be easily changed * because of the code makes assumptions about them. Because of that, those * constants are hard-coded and not available as CMake variables. With time, * some of those constants get "promoted" and moved in CMake, others remain * here. See the comments and think about the potential implications before * promoting a hard-coded constant to a configurable CMake variable. */ #define MEASURE_BOGOMIPS_TICKS (TIMER_HZ / 10) #define BOGOMIPS_CONST 10000 <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck_gen_headers/config_userlim.h> #include <tilck/common/basic_defs.h> #include <tilck/kernel/syscalls.h> #include <tilck/kernel/user.h> #include <tilck/kernel/sched.h> #include <tilck/kernel/paging.h> #include <tilck/kernel/fs/vfs.h> #include <tilck/kernel/timer.h> static int poll_count_conds(struct pollfd *fds, nfds_t nfds) { int cnt = 0; for (nfds_t i = 0; i < nfds; i++) { fds[i].revents = 0; fs_handle h = get_fs_handle(fds[i].fd); if (!h) { fds[i].revents = POLLNVAL; /* invalid file descriptor */ continue; } if (fds[i].events & (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) { fds[i].events |= POLLIN; /* treat all IN events as POLLIN */ if (vfs_get_rready_cond(h)) cnt++; } if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) { fds[i].events |= POLLOUT; /* treat all OUT events as POLLOUT */ if (vfs_get_wready_cond(h)) cnt++; } if (fds[i].events & POLL_MSG) { /* TODO (future): add support for POLL_MSG */ } if (vfs_get_except_cond(h)) cnt++; /* poll() automatically listens for exception events */ } return cnt; } static void poll_set_conds(struct multi_obj_waiter *w, struct pollfd *fds, nfds_t nfds, int cond_cnt) { int idx = 0; for (nfds_t i = 0; i < nfds; i++) { fs_handle h = get_fs_handle(fds[i].fd); if (!h) { fds[i].revents = POLLNVAL; /* invalid file descriptor */ continue; } if (fds[i].events & POLLIN) { struct kcond *c = vfs_get_rready_cond(h); if (c != NULL) { ASSERT(idx < cond_cnt); mobj_waiter_set(w, idx++, WOBJ_KCOND, c, &c->wait_list); } } if (fds[i].events & POLLOUT) { struct kcond *c = vfs_get_wready_cond(h); if (c != NULL) { ASSERT(idx < cond_cnt); mobj_waiter_set(w, idx++, WOBJ_KCOND, c, &c->wait_list); } } if (true) { /* * poll() always waits for exceptions: "if (true)" has been used just * for symmetry with the other cases */ struct kcond *c = vfs_get_except_cond(h); if (c != NULL) { ASSERT(idx < cond_cnt); mobj_waiter_set(w, idx++, WOBJ_KCOND, c, &c->wait_list); } } } } static int poll_count_ready_fds(struct pollfd *fds, nfds_t nfds) { int cnt = 0; int rc; for (nfds_t i = 0; i < nfds; i++) { fs_handle h = get_fs_handle(fds[i].fd); if (!h) { fds[i].revents = POLLNVAL; /* invalid file descriptor */ continue; } if (fds[i].events & POLLIN) { if (vfs_read_ready(h)) { fds[i].revents |= POLLIN; cnt++; continue; } } if (fds[i].events & POLLOUT) { if (vfs_write_ready(h)) { fds[i].revents |= POLLOUT; cnt++; continue; } } if (true) { /* just for symmetry */ if ((rc = vfs_except_ready(h))) { fds[i].revents |= rc > 0 ? rc : POLLERR; cnt++; continue; } } } return cnt; } static int poll_wait_on_cond(struct pollfd *fds, nfds_t nfds, int timeout, int cond_cnt) { struct task *curr = get_curr_task(); struct multi_obj_waiter *waiter = NULL; int ready_fds_cnt = 0; if (!(waiter = allocate_mobj_waiter(cond_cnt))) return -ENOMEM; poll_set_conds(waiter, fds, nfds, cond_cnt); if (!timeout) { ready_fds_cnt = poll_count_ready_fds(fds, nfds); free_mobj_waiter(waiter); return ready_fds_cnt; } if (timeout > 0) { u32 ticks = MAX((u32)timeout / (1000 / TIMER_HZ), 1u); task_set_wakeup_timer(curr, ticks); } while (true) { disable_preemption(); prepare_to_wait_on_multi_obj(waiter); enter_sleep_wait_state(); if (pending_signals()) break; if (timeout > 0) { if (curr->wobj.type) { /* we woke-up because of the timeout */ wait_obj_reset(&curr->wobj); } else { /* * We woke-up because of a kcond was signaled, but that does NOT * mean that even the signaled conditions correspond to ready * streams. We have to check that. */ ready_fds_cnt = poll_count_ready_fds(fds, nfds); if (!ready_fds_cnt) continue; /* No ready streams, we have to wait again. */ task_cancel_wakeup_timer(curr); } } else { /* No timeout: we woke-up because of a kcond was signaled */ ready_fds_cnt = poll_count_ready_fds(fds, nfds); if (!ready_fds_cnt) continue; /* No ready streams, we have to wait again. */ } break; } free_mobj_waiter(waiter); if (pending_signals()) return -EINTR; return ready_fds_cnt; } int sys_poll(struct pollfd *user_fds, nfds_t nfds, int timeout) { struct task *curr = get_curr_task(); struct pollfd *fds = curr->args_copybuf; int rc, ready_fds_cnt; int cond_cnt = 0; if (sizeof(struct pollfd) * nfds > ARGS_COPYBUF_SIZE) return -EINVAL; if (copy_from_user(fds, user_fds, sizeof(struct pollfd) * nfds)) return -EFAULT; for (u32 i = 0; i < nfds; i++) fds[i].revents = 0; ready_fds_cnt = poll_count_ready_fds(fds, nfds); if (ready_fds_cnt > 0) goto end; if (timeout != 0) cond_cnt = poll_count_conds(fds, nfds); if (cond_cnt > 0) { if ((rc = poll_wait_on_cond(fds, nfds, timeout, cond_cnt)) < 0) return rc; ready_fds_cnt = rc; } else { if (timeout > 0) { kernel_sleep((u64)timeout / (1000 / TIMER_HZ)); if (pending_signals()) return -EINTR; } ready_fds_cnt = poll_count_ready_fds(fds, nfds); } end: if (copy_to_user(user_fds, fds, sizeof(struct pollfd) * nfds)) return -EFAULT; return ready_fds_cnt; } <file_sep>#!/usr/bin/env bash # SPDX-License-Identifier: BSD-2-Clause # GLOBAL VARIABLES # Project's root directory SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" MAIN_DIR="$(cd $SOURCE_DIR/../.. && pwd)" # Include files source $MAIN_DIR/scripts/bash_includes/script_utils # CONSTANTS CM=$MAIN_DIR/scripts/cmake_run ############################################################## if [ -n "$AZURE_HTTP_USER_AGENT" ]; then sudo -E $MAIN_DIR/scripts/build_toolchain -s build_libmusl fi USE_SYSCC=1 $CM "$@" <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/printk.h> #include <tilck/kernel/debug_utils.h> #include <tilck/kernel/hal.h> #include <tilck/kernel/irq.h> #include <tilck/kernel/process.h> #include <tilck/kernel/elf_utils.h> #include <tilck/kernel/paging_hw.h> #include <tilck/kernel/errno.h> #include <tilck/kernel/arch/generic_x86/debug_utils_x86.h> #include <elf.h> #include <multiboot.h> static size_t stackwalk32(void **frames, size_t count, void *ebp, pdir_t *pdir) { bool curr_pdir = false; void *retAddr; size_t i; if (!ebp) { ebp = __builtin_frame_address(0); } if (!pdir) { pdir = get_curr_pdir(); curr_pdir = true; } for (i = 0; i < count; i++) { if ((ulong)ebp < KERNEL_BASE_VA) break; if (curr_pdir) { retAddr = *((void **)ebp + 1); ebp = *((void **)ebp); } else { if (virtual_read(pdir, (void **)ebp + 1, &retAddr, 4) < 0) break; if (virtual_read(pdir, (void **)ebp, &ebp, 4) < 0) break; } if (!ebp || !retAddr) break; frames[i] = retAddr; } return i; } void dump_stacktrace(void *ebp, pdir_t *pdir) { void *frames[32] = {0}; size_t c = stackwalk32(frames, ARRAY_SIZE(frames), ebp, pdir); printk("Stacktrace (%u frames):\n", c); for (size_t i = 0; i < c; i++) { long off = 0; u32 sym_size; ulong va = (ulong)frames[i]; const char *sym_name; sym_name = find_sym_at_addr(va, &off, &sym_size); if (sym_name && off == 0) { /* * Since we're resolving return addresses, not addresses, we have to * keep in mind that offset == 0 means that the next instruction after * a call was the beginning of a new function. This happens when a * function calls a NORETURN function like panic(). In this case, in * order to correctly resolve the caller's function name, we need to * decrease the vaddr when searching for the symbol name. */ sym_name = find_sym_at_addr(va - 1, &off, &sym_size); /* * Now we have to increase the offset value because in the backtrace * the original vaddr will be shown. [We passed "va-1" instead of "va" * because we wanted the previous function, now we have to adjust the * offset.] */ off++; } printk("[%p] %s + %ld\n", TO_PTR(va), sym_name ? sym_name : "???", off); } printk("\n"); } void dump_regs(regs_t *r) { dump_eflags(r->eflags); printk("ss: %p, cs: %p, ds: %p, esp: %p\n", TO_PTR(r->ss), TO_PTR(r->cs), TO_PTR(r->ds), TO_PTR(r->useresp)); printk("eip: %p, eax: %p, ecx: %p, edx: %p\n", TO_PTR(r->eip), TO_PTR(r->eax), TO_PTR(r->ecx), TO_PTR(r->edx)); printk("ebx: %p, ebp: %p, esi: %p, edi: %p\n", TO_PTR(r->ebx), TO_PTR(r->ebp), TO_PTR(r->esi), TO_PTR(r->edi)); } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #ifndef _KMALLOC_C_ #error This is NOT a header file and it is not meant to be included /* * The only purpose of this file is to keep kmalloc.c shorter. * Yes, this file could be turned into a regular C source file, but at the * price of making several static functions and variables in kmalloc.c to be * just non-static. We don't want that. Code isolation is a GOOD thing. */ #endif #include <tilck/kernel/bintree.h> struct kmalloc_acc_alloc { struct bintree_node node; size_t size; size_t count; }; static size_t alloc_arr_elems; static size_t alloc_arr_used; static struct kmalloc_acc_alloc *alloc_arr; static struct kmalloc_acc_alloc *alloc_tree_root; static void kmalloc_account_alloc(size_t size) { struct kmalloc_acc_alloc *obj; if (!alloc_arr) return; obj = bintree_find_ptr(alloc_tree_root, size, struct kmalloc_acc_alloc, node, size); if (obj) { obj->count++; return; } if (alloc_arr_used == alloc_arr_elems) { /* * While it won't be very complex to make `alloc_arr` to be dynamically * resizable (with re-allocation + copy), it seems unnecessary to add * such a feature for this debug utility. Reason: currently, there are * just 42 distinct chunk sizes in Tilck, after running all of its system * tests, while with the current pre-allocated buffer (16 KB), we have * than 800+ slots, for 32-bit systems. This 20-fold ratio seems enough * even for the medium-long term. In particular, it's enough for the * kmalloc perf test, which ends up requiring > 588 slots. */ panic("kmalloc: No more space in alloc_arr"); } obj = &alloc_arr[alloc_arr_used++]; bintree_node_init(&obj->node); obj->size = size; obj->count = 1; DEBUG_CHECKED_SUCCESS( bintree_insert_ptr(&alloc_tree_root, obj, struct kmalloc_acc_alloc, node, size) ); } static void kmalloc_init_heavy_stats(void) { ASSERT(!is_preemption_enabled()); if (KERNEL_TEST_INT) { /* It does not make sense to run those heavy stats in unit tests */ return; } const size_t alloc_arr_bytes = 4 * PAGE_SIZE; alloc_arr_elems = alloc_arr_bytes / sizeof(struct kmalloc_acc_alloc); alloc_arr_used = 0; alloc_arr = kmalloc(alloc_arr_bytes); if (!alloc_arr) panic("Unable to alloc memory for the kmalloc heavy stats"); printk("kmalloc: heavy stats enabled (%zu elems)\n", alloc_arr_elems); kmalloc_account_alloc(alloc_arr_bytes); } void debug_kmalloc_chunks_stats_start_read(struct debug_kmalloc_chunks_ctx *ctx) { if (!KMALLOC_HEAVY_STATS) return; ASSERT(!is_preemption_enabled()); bintree_in_order_visit_start(&ctx->ctx, alloc_tree_root, struct kmalloc_acc_alloc, node, true); } bool debug_kmalloc_chunks_stats_next(struct debug_kmalloc_chunks_ctx *ctx, size_t *size, size_t *count) { if (!KMALLOC_HEAVY_STATS) return false; ASSERT(!is_preemption_enabled()); struct kmalloc_acc_alloc *obj; obj = bintree_in_order_visit_next(&ctx->ctx); if (!obj) return false; *size = obj->size; *count = obj->count; return true; } <file_sep>/****************************************************************************** * * Module Name: utxface - External interfaces, miscellaneous utility functions * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acdebug.h" #define _COMPONENT ACPI_UTILITIES ACPI_MODULE_NAME ("utxface") /******************************************************************************* * * FUNCTION: AcpiTerminate * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Shutdown the ACPICA subsystem and release all resources. * ******************************************************************************/ ACPI_STATUS ACPI_INIT_FUNCTION AcpiTerminate ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiTerminate); /* Shutdown and free all resources */ AcpiUtSubsystemShutdown (); /* Free the mutex objects */ AcpiUtMutexTerminate (); /* Now we can shutdown the OS-dependent layer */ Status = AcpiOsTerminate (); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL_INIT (AcpiTerminate) #ifndef ACPI_ASL_COMPILER /******************************************************************************* * * FUNCTION: AcpiSubsystemStatus * * PARAMETERS: None * * RETURN: Status of the ACPI subsystem * * DESCRIPTION: Other drivers that use the ACPI subsystem should call this * before making any other calls, to ensure the subsystem * initialized successfully. * ******************************************************************************/ ACPI_STATUS AcpiSubsystemStatus ( void) { if (AcpiGbl_StartupFlags & ACPI_INITIALIZED_OK) { return (AE_OK); } else { return (AE_ERROR); } } ACPI_EXPORT_SYMBOL (AcpiSubsystemStatus) /******************************************************************************* * * FUNCTION: AcpiGetSystemInfo * * PARAMETERS: OutBuffer - A buffer to receive the resources for the * device * * RETURN: Status - the status of the call * * DESCRIPTION: This function is called to get information about the current * state of the ACPI subsystem. It will return system information * in the OutBuffer. * * If the function fails an appropriate status will be returned * and the value of OutBuffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiGetSystemInfo ( ACPI_BUFFER *OutBuffer) { ACPI_SYSTEM_INFO *InfoPtr; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiGetSystemInfo); /* Parameter validation */ Status = AcpiUtValidateBuffer (OutBuffer); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Validate/Allocate/Clear caller buffer */ Status = AcpiUtInitializeBuffer (OutBuffer, sizeof (ACPI_SYSTEM_INFO)); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Populate the return buffer */ InfoPtr = (ACPI_SYSTEM_INFO *) OutBuffer->Pointer; InfoPtr->AcpiCaVersion = ACPI_CA_VERSION; /* System flags (ACPI capabilities) */ InfoPtr->Flags = ACPI_SYS_MODE_ACPI; /* Timer resolution - 24 or 32 bits */ if (AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER) { InfoPtr->TimerResolution = 24; } else { InfoPtr->TimerResolution = 32; } /* Clear the reserved fields */ InfoPtr->Reserved1 = 0; InfoPtr->Reserved2 = 0; /* Current debug levels */ InfoPtr->DebugLayer = AcpiDbgLayer; InfoPtr->DebugLevel = AcpiDbgLevel; return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiGetSystemInfo) /******************************************************************************* * * FUNCTION: AcpiGetStatistics * * PARAMETERS: Stats - Where the statistics are returned * * RETURN: Status - the status of the call * * DESCRIPTION: Get the contents of the various system counters * ******************************************************************************/ ACPI_STATUS AcpiGetStatistics ( ACPI_STATISTICS *Stats) { ACPI_FUNCTION_TRACE (AcpiGetStatistics); /* Parameter validation */ if (!Stats) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Various interrupt-based event counters */ Stats->SciCount = AcpiSciCount; Stats->GpeCount = AcpiGpeCount; memcpy (Stats->FixedEventCount, AcpiFixedEventCount, sizeof (AcpiFixedEventCount)); /* Other counters */ Stats->MethodCount = AcpiMethodCount; return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiGetStatistics) /***************************************************************************** * * FUNCTION: AcpiInstallInitializationHandler * * PARAMETERS: Handler - Callback procedure * Function - Not (currently) used, see below * * RETURN: Status * * DESCRIPTION: Install an initialization handler * * TBD: When a second function is added, must save the Function also. * ****************************************************************************/ ACPI_STATUS AcpiInstallInitializationHandler ( ACPI_INIT_HANDLER Handler, UINT32 Function) { if (!Handler) { return (AE_BAD_PARAMETER); } if (AcpiGbl_InitHandler) { return (AE_ALREADY_EXISTS); } AcpiGbl_InitHandler = Handler; return (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiInstallInitializationHandler) /***************************************************************************** * * FUNCTION: AcpiPurgeCachedObjects * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Empty all caches (delete the cached objects) * ****************************************************************************/ ACPI_STATUS AcpiPurgeCachedObjects ( void) { ACPI_FUNCTION_TRACE (AcpiPurgeCachedObjects); (void) AcpiOsPurgeCache (AcpiGbl_StateCache); (void) AcpiOsPurgeCache (AcpiGbl_OperandCache); (void) AcpiOsPurgeCache (AcpiGbl_PsNodeCache); (void) AcpiOsPurgeCache (AcpiGbl_PsNodeExtCache); return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiPurgeCachedObjects) /***************************************************************************** * * FUNCTION: AcpiInstallInterface * * PARAMETERS: InterfaceName - The interface to install * * RETURN: Status * * DESCRIPTION: Install an _OSI interface to the global list * ****************************************************************************/ ACPI_STATUS AcpiInstallInterface ( ACPI_STRING InterfaceName) { ACPI_STATUS Status; ACPI_INTERFACE_INFO *InterfaceInfo; /* Parameter validation */ if (!InterfaceName || (strlen (InterfaceName) == 0)) { return (AE_BAD_PARAMETER); } Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } /* Check if the interface name is already in the global list */ InterfaceInfo = AcpiUtGetInterface (InterfaceName); if (InterfaceInfo) { /* * The interface already exists in the list. This is OK if the * interface has been marked invalid -- just clear the bit. */ if (InterfaceInfo->Flags & ACPI_OSI_INVALID) { InterfaceInfo->Flags &= ~ACPI_OSI_INVALID; Status = AE_OK; } else { Status = AE_ALREADY_EXISTS; } } else { /* New interface name, install into the global list */ Status = AcpiUtInstallInterface (InterfaceName); } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallInterface) /***************************************************************************** * * FUNCTION: AcpiRemoveInterface * * PARAMETERS: InterfaceName - The interface to remove * * RETURN: Status * * DESCRIPTION: Remove an _OSI interface from the global list * ****************************************************************************/ ACPI_STATUS AcpiRemoveInterface ( ACPI_STRING InterfaceName) { ACPI_STATUS Status; /* Parameter validation */ if (!InterfaceName || (strlen (InterfaceName) == 0)) { return (AE_BAD_PARAMETER); } Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiUtRemoveInterface (InterfaceName); AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveInterface) /***************************************************************************** * * FUNCTION: AcpiInstallInterfaceHandler * * PARAMETERS: Handler - The _OSI interface handler to install * NULL means "remove existing handler" * * RETURN: Status * * DESCRIPTION: Install a handler for the predefined _OSI ACPI method. * invoked during execution of the internal implementation of * _OSI. A NULL handler simply removes any existing handler. * ****************************************************************************/ ACPI_STATUS AcpiInstallInterfaceHandler ( ACPI_INTERFACE_HANDLER Handler) { ACPI_STATUS Status; Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } if (Handler && AcpiGbl_InterfaceHandler) { Status = AE_ALREADY_EXISTS; } else { AcpiGbl_InterfaceHandler = Handler; } AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallInterfaceHandler) /***************************************************************************** * * FUNCTION: AcpiUpdateInterfaces * * PARAMETERS: Action - Actions to be performed during the * update * * RETURN: Status * * DESCRIPTION: Update _OSI interface strings, disabling or enabling OS vendor * string or/and feature group strings. * ****************************************************************************/ ACPI_STATUS AcpiUpdateInterfaces ( UINT8 Action) { ACPI_STATUS Status; Status = AcpiOsAcquireMutex (AcpiGbl_OsiMutex, ACPI_WAIT_FOREVER); if (ACPI_FAILURE (Status)) { return (Status); } Status = AcpiUtUpdateInterfaces (Action); AcpiOsReleaseMutex (AcpiGbl_OsiMutex); return (Status); } /***************************************************************************** * * FUNCTION: AcpiCheckAddressRange * * PARAMETERS: SpaceId - Address space ID * Address - Start address * Length - Length * Warn - TRUE if warning on overlap desired * * RETURN: Count of the number of conflicts detected. * * DESCRIPTION: Check if the input address range overlaps any of the * ASL operation region address ranges. * ****************************************************************************/ UINT32 AcpiCheckAddressRange ( ACPI_ADR_SPACE_TYPE SpaceId, ACPI_PHYSICAL_ADDRESS Address, ACPI_SIZE Length, BOOLEAN Warn) { UINT32 Overlaps; ACPI_STATUS Status; Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (0); } Overlaps = AcpiUtCheckAddressRange (SpaceId, Address, (UINT32) Length, Warn); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (Overlaps); } ACPI_EXPORT_SYMBOL (AcpiCheckAddressRange) #endif /* !ACPI_ASL_COMPILER */ /******************************************************************************* * * FUNCTION: AcpiDecodePldBuffer * * PARAMETERS: InBuffer - Buffer returned by _PLD method * Length - Length of the InBuffer * ReturnBuffer - Where the decode buffer is returned * * RETURN: Status and the decoded _PLD buffer. User must deallocate * the buffer via ACPI_FREE. * * DESCRIPTION: Decode the bit-packed buffer returned by the _PLD method into * a local struct that is much more useful to an ACPI driver. * ******************************************************************************/ ACPI_STATUS AcpiDecodePldBuffer ( UINT8 *InBuffer, ACPI_SIZE Length, ACPI_PLD_INFO **ReturnBuffer) { ACPI_PLD_INFO *PldInfo; UINT32 *Buffer = ACPI_CAST_PTR (UINT32, InBuffer); UINT32 Dword; /* Parameter validation */ if (!InBuffer || !ReturnBuffer || (Length < ACPI_PLD_REV1_BUFFER_SIZE)) { return (AE_BAD_PARAMETER); } PldInfo = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_PLD_INFO)); if (!PldInfo) { return (AE_NO_MEMORY); } /* First 32-bit DWord */ ACPI_MOVE_32_TO_32 (&Dword, &Buffer[0]); PldInfo->Revision = ACPI_PLD_GET_REVISION (&Dword); PldInfo->IgnoreColor = ACPI_PLD_GET_IGNORE_COLOR (&Dword); PldInfo->Red = ACPI_PLD_GET_RED (&Dword); PldInfo->Green = ACPI_PLD_GET_GREEN (&Dword); PldInfo->Blue = ACPI_PLD_GET_BLUE (&Dword); /* Second 32-bit DWord */ ACPI_MOVE_32_TO_32 (&Dword, &Buffer[1]); PldInfo->Width = ACPI_PLD_GET_WIDTH (&Dword); PldInfo->Height = ACPI_PLD_GET_HEIGHT(&Dword); /* Third 32-bit DWord */ ACPI_MOVE_32_TO_32 (&Dword, &Buffer[2]); PldInfo->UserVisible = ACPI_PLD_GET_USER_VISIBLE (&Dword); PldInfo->Dock = ACPI_PLD_GET_DOCK (&Dword); PldInfo->Lid = ACPI_PLD_GET_LID (&Dword); PldInfo->Panel = ACPI_PLD_GET_PANEL (&Dword); PldInfo->VerticalPosition = ACPI_PLD_GET_VERTICAL (&Dword); PldInfo->HorizontalPosition = ACPI_PLD_GET_HORIZONTAL (&Dword); PldInfo->Shape = ACPI_PLD_GET_SHAPE (&Dword); PldInfo->GroupOrientation = ACPI_PLD_GET_ORIENTATION (&Dword); PldInfo->GroupToken = ACPI_PLD_GET_TOKEN (&Dword); PldInfo->GroupPosition = ACPI_PLD_GET_POSITION (&Dword); PldInfo->Bay = ACPI_PLD_GET_BAY (&Dword); /* Fourth 32-bit DWord */ ACPI_MOVE_32_TO_32 (&Dword, &Buffer[3]); PldInfo->Ejectable = ACPI_PLD_GET_EJECTABLE (&Dword); PldInfo->OspmEjectRequired = ACPI_PLD_GET_OSPM_EJECT (&Dword); PldInfo->CabinetNumber = ACPI_PLD_GET_CABINET (&Dword); PldInfo->CardCageNumber = ACPI_PLD_GET_CARD_CAGE (&Dword); PldInfo->Reference = ACPI_PLD_GET_REFERENCE (&Dword); PldInfo->Rotation = ACPI_PLD_GET_ROTATION (&Dword); PldInfo->Order = ACPI_PLD_GET_ORDER (&Dword); if (Length >= ACPI_PLD_REV2_BUFFER_SIZE) { /* Fifth 32-bit DWord (Revision 2 of _PLD) */ ACPI_MOVE_32_TO_32 (&Dword, &Buffer[4]); PldInfo->VerticalOffset = ACPI_PLD_GET_VERT_OFFSET (&Dword); PldInfo->HorizontalOffset = ACPI_PLD_GET_HORIZ_OFFSET (&Dword); } *ReturnBuffer = PldInfo; return (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiDecodePldBuffer) <file_sep>/******************************************************************************* * * Module Name: dbxface - AML Debugger external interfaces * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * 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, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "amlcode.h" #include "acdebug.h" #include "acinterp.h" #include "acparser.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME ("dbxface") /* Local prototypes */ static ACPI_STATUS AcpiDbStartCommand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op); #ifdef ACPI_OBSOLETE_FUNCTIONS void AcpiDbMethodEnd ( ACPI_WALK_STATE *WalkState); #endif #ifdef ACPI_DISASSEMBLER static ACPI_PARSE_OBJECT * AcpiDbGetDisplayOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op); #endif /******************************************************************************* * * FUNCTION: AcpiDbStartCommand * * PARAMETERS: WalkState - Current walk * Op - Current executing Op, from AML interpreter * * RETURN: Status * * DESCRIPTION: Enter debugger command loop * ******************************************************************************/ static ACPI_STATUS AcpiDbStartCommand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_STATUS Status; /* TBD: [Investigate] are there namespace locking issues here? */ /* AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); */ /* Go into the command loop and await next user command */ AcpiGbl_MethodExecuting = TRUE; Status = AE_CTRL_TRUE; while (Status == AE_CTRL_TRUE) { /* Notify the completion of the command */ Status = AcpiOsNotifyCommandComplete (); if (ACPI_FAILURE (Status)) { goto ErrorExit; } /* Wait the readiness of the command */ Status = AcpiOsWaitCommandReady (); if (ACPI_FAILURE (Status)) { goto ErrorExit; } Status = AcpiDbCommandDispatch (AcpiGbl_DbLineBuf, WalkState, Op); } /* AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); */ ErrorExit: if (ACPI_FAILURE (Status) && Status != AE_CTRL_TERMINATE) { ACPI_EXCEPTION ((AE_INFO, Status, "While parsing/handling command line")); } return (Status); } /******************************************************************************* * * FUNCTION: AcpiDbSignalBreakPoint * * PARAMETERS: WalkState - Current walk * * RETURN: Status * * DESCRIPTION: Called for AML_BREAKPOINT_OP * ******************************************************************************/ void AcpiDbSignalBreakPoint ( ACPI_WALK_STATE *WalkState) { #ifndef ACPI_APPLICATION if (AcpiGbl_DbThreadId != AcpiOsGetThreadId ()) { return; } #endif /* * Set the single-step flag. This will cause the debugger (if present) * to break to the console within the AML debugger at the start of the * next AML instruction. */ AcpiGbl_CmSingleStep = TRUE; AcpiOsPrintf ("**break** Executed AML BreakPoint opcode\n"); } #ifdef ACPI_DISASSEMBLER /******************************************************************************* * * FUNCTION: AcpiDbGetDisplayOp * * PARAMETERS: WalkState - Current walk * Op - Current executing op (from aml interpreter) * * RETURN: Opcode to display * * DESCRIPTION: Find the opcode to display during single stepping * ******************************************************************************/ static ACPI_PARSE_OBJECT * AcpiDbGetDisplayOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op) { ACPI_PARSE_OBJECT *DisplayOp; ACPI_PARSE_OBJECT *ParentOp; DisplayOp = Op; ParentOp = Op->Common.Parent; if (ParentOp) { if ((WalkState->ControlState) && (WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING)) { /* * We are executing the predicate of an IF or WHILE statement * Search upwards for the containing IF or WHILE so that the * entire predicate can be displayed. */ while (ParentOp) { if ((ParentOp->Common.AmlOpcode == AML_IF_OP) || (ParentOp->Common.AmlOpcode == AML_WHILE_OP)) { DisplayOp = ParentOp; break; } ParentOp = ParentOp->Common.Parent; } } else { while (ParentOp) { if ((ParentOp->Common.AmlOpcode == AML_IF_OP) || (ParentOp->Common.AmlOpcode == AML_ELSE_OP) || (ParentOp->Common.AmlOpcode == AML_SCOPE_OP) || (ParentOp->Common.AmlOpcode == AML_METHOD_OP) || (ParentOp->Common.AmlOpcode == AML_WHILE_OP)) { break; } DisplayOp = ParentOp; ParentOp = ParentOp->Common.Parent; } } } return DisplayOp; } #endif /******************************************************************************* * * FUNCTION: AcpiDbSingleStep * * PARAMETERS: WalkState - Current walk * Op - Current executing op (from aml interpreter) * OpcodeClass - Class of the current AML Opcode * * RETURN: Status * * DESCRIPTION: Called just before execution of an AML opcode. * ******************************************************************************/ ACPI_STATUS AcpiDbSingleStep ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, UINT32 OpcodeClass) { ACPI_PARSE_OBJECT *Next; ACPI_STATUS Status = AE_OK; UINT32 OriginalDebugLevel; UINT32 AmlOffset; ACPI_FUNCTION_ENTRY (); #ifndef ACPI_APPLICATION if (AcpiGbl_DbThreadId != AcpiOsGetThreadId ()) { return (AE_OK); } #endif /* Check the abort flag */ if (AcpiGbl_AbortMethod) { AcpiGbl_AbortMethod = FALSE; return (AE_ABORT_METHOD); } AmlOffset = (UINT32) ACPI_PTR_DIFF (Op->Common.Aml, WalkState->ParserState.AmlStart); /* Check for single-step breakpoint */ if (WalkState->MethodBreakpoint && (WalkState->MethodBreakpoint <= AmlOffset)) { /* Check if the breakpoint has been reached or passed */ /* Hit the breakpoint, resume single step, reset breakpoint */ AcpiOsPrintf ("***Break*** at AML offset %X\n", AmlOffset); AcpiGbl_CmSingleStep = TRUE; AcpiGbl_StepToNextCall = FALSE; WalkState->MethodBreakpoint = 0; } /* Check for user breakpoint (Must be on exact Aml offset) */ else if (WalkState->UserBreakpoint && (WalkState->UserBreakpoint == AmlOffset)) { AcpiOsPrintf ("***UserBreakpoint*** at AML offset %X\n", AmlOffset); AcpiGbl_CmSingleStep = TRUE; AcpiGbl_StepToNextCall = FALSE; WalkState->MethodBreakpoint = 0; } /* * Check if this is an opcode that we are interested in -- * namely, opcodes that have arguments */ if (Op->Common.AmlOpcode == AML_INT_NAMEDFIELD_OP) { return (AE_OK); } switch (OpcodeClass) { case AML_CLASS_UNKNOWN: case AML_CLASS_ARGUMENT: /* constants, literals, etc. do nothing */ return (AE_OK); default: /* All other opcodes -- continue */ break; } /* * Under certain debug conditions, display this opcode and its operands */ if ((AcpiGbl_DbOutputToFile) || (AcpiGbl_CmSingleStep) || (AcpiDbgLevel & ACPI_LV_PARSE)) { if ((AcpiGbl_DbOutputToFile) || (AcpiDbgLevel & ACPI_LV_PARSE)) { AcpiOsPrintf ("\nAML Debug: Next AML Opcode to execute:\n"); } /* * Display this op (and only this op - zero out the NEXT field * temporarily, and disable parser trace output for the duration of * the display because we don't want the extraneous debug output) */ OriginalDebugLevel = AcpiDbgLevel; AcpiDbgLevel &= ~(ACPI_LV_PARSE | ACPI_LV_FUNCTIONS); Next = Op->Common.Next; Op->Common.Next = NULL; /* Now we can disassemble and display it */ #ifdef ACPI_DISASSEMBLER AcpiDmDisassemble (WalkState, AcpiDbGetDisplayOp (WalkState, Op), ACPI_UINT32_MAX); #else /* * The AML Disassembler is not configured - at least we can * display the opcode value and name */ AcpiOsPrintf ("AML Opcode: %4.4X %s\n", Op->Common.AmlOpcode, AcpiPsGetOpcodeName (Op->Common.AmlOpcode)); #endif if ((Op->Common.AmlOpcode == AML_IF_OP) || (Op->Common.AmlOpcode == AML_WHILE_OP)) { if (WalkState->ControlState->Common.Value) { AcpiOsPrintf ("Predicate = [True], IF block was executed\n"); } else { AcpiOsPrintf ("Predicate = [False], Skipping IF block\n"); } } else if (Op->Common.AmlOpcode == AML_ELSE_OP) { AcpiOsPrintf ("Predicate = [False], ELSE block was executed\n"); } /* Restore everything */ Op->Common.Next = Next; AcpiOsPrintf ("\n"); if ((AcpiGbl_DbOutputToFile) || (AcpiDbgLevel & ACPI_LV_PARSE)) { AcpiOsPrintf ("\n"); } AcpiDbgLevel = OriginalDebugLevel; } /* If we are not single stepping, just continue executing the method */ if (!AcpiGbl_CmSingleStep) { return (AE_OK); } /* * If we are executing a step-to-call command, * Check if this is a method call. */ if (AcpiGbl_StepToNextCall) { if (Op->Common.AmlOpcode != AML_INT_METHODCALL_OP) { /* Not a method call, just keep executing */ return (AE_OK); } /* Found a method call, stop executing */ AcpiGbl_StepToNextCall = FALSE; } /* * If the next opcode is a method call, we will "step over" it * by default. */ if (Op->Common.AmlOpcode == AML_INT_METHODCALL_OP) { /* Force no more single stepping while executing called method */ AcpiGbl_CmSingleStep = FALSE; /* * Set the breakpoint on/before the call, it will stop execution * as soon as we return */ WalkState->MethodBreakpoint = 1; /* Must be non-zero! */ } AcpiExExitInterpreter (); Status = AcpiDbStartCommand (WalkState, Op); AcpiExEnterInterpreter (); /* User commands complete, continue execution of the interrupted method */ return (Status); } /******************************************************************************* * * FUNCTION: AcpiInitializeDebugger * * PARAMETERS: None * * RETURN: Status * * DESCRIPTION: Init and start debugger * ******************************************************************************/ ACPI_STATUS AcpiInitializeDebugger ( void) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInitializeDebugger); /* Init globals */ AcpiGbl_DbBuffer = NULL; AcpiGbl_DbFilename = NULL; AcpiGbl_DbOutputToFile = FALSE; AcpiGbl_DbDebugLevel = ACPI_LV_VERBOSITY2; AcpiGbl_DbConsoleDebugLevel = ACPI_NORMAL_DEFAULT | ACPI_LV_TABLES; AcpiGbl_DbOutputFlags = ACPI_DB_CONSOLE_OUTPUT; AcpiGbl_DbOpt_NoIniMethods = FALSE; AcpiGbl_DbOpt_NoRegionSupport = FALSE; AcpiGbl_DbBuffer = AcpiOsAllocate (ACPI_DEBUG_BUFFER_SIZE); if (!AcpiGbl_DbBuffer) { return_ACPI_STATUS (AE_NO_MEMORY); } memset (AcpiGbl_DbBuffer, 0, ACPI_DEBUG_BUFFER_SIZE); /* Initial scope is the root */ AcpiGbl_DbScopeBuf [0] = AML_ROOT_PREFIX; AcpiGbl_DbScopeBuf [1] = 0; AcpiGbl_DbScopeNode = AcpiGbl_RootNode; /* Initialize user commands loop */ AcpiGbl_DbTerminateLoop = FALSE; /* * If configured for multi-thread support, the debug executor runs in * a separate thread so that the front end can be in another address * space, environment, or even another machine. */ if (AcpiGbl_DebuggerConfiguration & DEBUGGER_MULTI_THREADED) { /* These were created with one unit, grab it */ Status = AcpiOsInitializeDebugger (); if (ACPI_FAILURE (Status)) { AcpiOsPrintf ("Could not get debugger mutex\n"); return_ACPI_STATUS (Status); } /* Create the debug execution thread to execute commands */ AcpiGbl_DbThreadsTerminated = FALSE; Status = AcpiOsExecute (OSL_DEBUGGER_MAIN_THREAD, AcpiDbExecuteThread, NULL); if (ACPI_FAILURE (Status)) { ACPI_EXCEPTION ((AE_INFO, Status, "Could not start debugger thread")); AcpiGbl_DbThreadsTerminated = TRUE; return_ACPI_STATUS (Status); } } else { AcpiGbl_DbThreadId = AcpiOsGetThreadId (); } return_ACPI_STATUS (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiInitializeDebugger) /******************************************************************************* * * FUNCTION: AcpiTerminateDebugger * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Stop debugger * ******************************************************************************/ void AcpiTerminateDebugger ( void) { /* Terminate the AML Debugger */ AcpiGbl_DbTerminateLoop = TRUE; if (AcpiGbl_DebuggerConfiguration & DEBUGGER_MULTI_THREADED) { /* Wait the AML Debugger threads */ while (!AcpiGbl_DbThreadsTerminated) { AcpiOsSleep (100); } AcpiOsTerminateDebugger (); } if (AcpiGbl_DbBuffer) { AcpiOsFree (AcpiGbl_DbBuffer); AcpiGbl_DbBuffer = NULL; } /* Ensure that debug output is now disabled */ AcpiGbl_DbOutputFlags = ACPI_DB_DISABLE_OUTPUT; } ACPI_EXPORT_SYMBOL (AcpiTerminateDebugger) /******************************************************************************* * * FUNCTION: AcpiSetDebuggerThreadId * * PARAMETERS: ThreadId - Debugger thread ID * * RETURN: None * * DESCRIPTION: Set debugger thread ID * ******************************************************************************/ void AcpiSetDebuggerThreadId ( ACPI_THREAD_ID ThreadId) { AcpiGbl_DbThreadId = ThreadId; } ACPI_EXPORT_SYMBOL (AcpiSetDebuggerThreadId) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <stdlib.h> static inline int do_sysenter_call0(int syscall) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall) : "memory", "cc"); #else abort(); #endif return ret; } static inline int do_sysenter_call1(int syscall, void *arg1) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall), "b" (arg1) : "memory", "cc"); #else abort(); #endif return ret; } static inline int do_sysenter_call2(int syscall, void *arg1, void *arg2) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall), "b" (arg1), "c" (arg2) : "memory", "cc"); #else abort(); #endif return ret; } static inline int do_sysenter_call3(int syscall, void *arg1, void *arg2, void *arg3) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall), "b" (arg1), "c" (arg2), "d" (arg3) : "memory", "cc"); #else abort(); #endif return ret; } static inline int do_sysenter_call4(int syscall, void *a1, void *a2, void *a3, void *a4) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall), "b" (a1), "c" (a2), "d" (a3), "S" (a4) : "memory", "cc"); #else abort(); #endif return ret; } static inline int do_sysenter_call5(int syscall, void *a1, void *a2, void *a3, void *a4, void *a5) { int ret; #ifdef __i386__ asmVolatile ("pushl $1f\n\t" "pushl %%ecx\n\t" "pushl %%edx\n\t" "pushl %%ebp\n\t" "movl %%esp, %%ebp\n\t" "sysenter\n\t" "1:\n\t" : "=a" (ret) : "a" (syscall),"b" (a1), "c" (a2), "d" (a3), "S" (a4), "D" (a5) : "memory", "cc"); #else abort(); #endif return ret; } #define sysenter_call0(n) \ do_sysenter_call0((n)) #define sysenter_call1(n, a1) \ do_sysenter_call1((n), TO_PTR(a1)) #define sysenter_call2(n, a1, a2) \ do_sysenter_call2((n), TO_PTR(a1), TO_PTR(a2)) #define sysenter_call3(n, a1, a2, a3) \ do_sysenter_call3((n), TO_PTR(a1), TO_PTR(a2), TO_PTR(a3)) #define sysenter_call4(n, a1, a2, a3, a4) \ do_sysenter_call4((n), TO_PTR(a1), TO_PTR(a2), TO_PTR(a3), TO_PTR(a4)) #define sysenter_call5(n, a1, a2, a3, a4, a5) \ do_sysenter_call5((n), \ TO_PTR(a1), \ TO_PTR(a2), \ TO_PTR(a3), \ TO_PTR(a4), \ TO_PTR(a5)) <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <tilck/common/string_util.h> #include <tilck/common/printk.h> #include "common.h" #include "mm.h" #include "vbe.h" static multiboot_info_t *mbi; static multiboot_module_t *mod; static multiboot_memory_map_t *mmmap; static char *cmdline_buf; char * legacy_boot_get_cmdline_buf(u32 *buf_sz) { ASSERT(cmdline_buf != NULL); *buf_sz = CMDLINE_BUF_SZ; return cmdline_buf; } void alloc_mbi(void) { ulong free_mem; free_mem = get_usable_mem(&g_meminfo, 16 * KB, 48 * KB); if (!free_mem) panic("Unable to allocate memory for the multiboot info"); mbi = (multiboot_info_t *) free_mem; bzero(mbi, sizeof(*mbi)); mod = (multiboot_module_t *)((char *)mbi + sizeof(*mbi)); bzero(mod, sizeof(*mod)); cmdline_buf = (char *)mod + (1 /* count */ * sizeof(multiboot_module_t)); bzero(cmdline_buf, CMDLINE_BUF_SZ); mmmap = (void *)(cmdline_buf + CMDLINE_BUF_SZ); bzero(mmmap, g_meminfo.count * sizeof(multiboot_memory_map_t)); } multiboot_info_t * setup_multiboot_info(ulong ramdisk_paddr, ulong ramdisk_size) { ASSERT(mbi != NULL); ASSERT(mod != NULL); mbi->flags |= MULTIBOOT_INFO_MEMORY; mbi->mem_lower = 0; mbi->mem_upper = 0; if (cmdline_buf[0]) { mbi->flags |= MULTIBOOT_INFO_CMDLINE; mbi->cmdline = (u32) cmdline_buf; } mbi->flags |= MULTIBOOT_INFO_FRAMEBUFFER_INFO; if (selected_mode == VGA_COLOR_TEXT_MODE_80x25) { mbi->framebuffer_addr = 0xB8000; mbi->framebuffer_pitch = 80 * 2; mbi->framebuffer_width = 80; mbi->framebuffer_height = 25; mbi->framebuffer_bpp = 4; mbi->framebuffer_type = MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT; } else { struct ModeInfoBlock *mi = usable_vbe_mode_info_block; if (!vbe_get_mode_info(selected_mode, mi)) panic("vbe_get_mode_info(0x%x) failed", selected_mode); mbi->framebuffer_addr = mi->PhysBasePtr; mbi->framebuffer_pitch = mi->BytesPerScanLine; mbi->framebuffer_width = mi->XResolution; mbi->framebuffer_height = mi->YResolution; mbi->framebuffer_bpp = mi->BitsPerPixel; mbi->framebuffer_type = MULTIBOOT_FRAMEBUFFER_TYPE_RGB; mbi->framebuffer_red_field_position = mi->RedFieldPosition; mbi->framebuffer_red_mask_size = mi->RedMaskSize; mbi->framebuffer_green_field_position = mi->GreenFieldPosition; mbi->framebuffer_green_mask_size = mi->GreenMaskSize; mbi->framebuffer_blue_field_position = mi->BlueFieldPosition; mbi->framebuffer_blue_mask_size = mi->BlueMaskSize; if (vbe_info_block->VbeVersion >= 0x300) mbi->framebuffer_pitch = mi->LinBytesPerScanLine; } mbi->flags |= MULTIBOOT_INFO_MODS; mbi->mods_addr = (u32)mod; mbi->mods_count = 1; mod->mod_start = ramdisk_paddr; mod->mod_end = mod->mod_start + ramdisk_size; mbi->flags |= MULTIBOOT_INFO_MEM_MAP; mbi->mmap_addr = (u32)mmmap; mbi->mmap_length = g_meminfo.count * sizeof(multiboot_memory_map_t); for (u32 i = 0; i < g_meminfo.count; i++) { struct mem_area *ma = g_meminfo.mem_areas + i; if (ma->type == MEM_USABLE) { if (ma->base < mbi->mem_lower * KB) mbi->mem_lower = (u32)(ma->base / KB); if (ma->base + ma->len > mbi->mem_upper * KB) mbi->mem_upper = (u32)((ma->base + ma->len) / KB); } mmmap[i] = (multiboot_memory_map_t) { .size = sizeof(multiboot_memory_map_t) - sizeof(u32), .addr = ma->base, .len = ma->len, .type = bios_to_multiboot_mem_region(ma->type), }; } return mbi; } <file_sep>/* SPDX-License-Identifier: BSD-2-Clause */ #include <tilck/common/basic_defs.h> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mocking.h" using namespace std; using namespace testing; /* * Mocking of C functions in the kernel * * Instructions: * * 1. add all the functions that we would like to mock in the WRAPPED_SYMS * list in other/cmake/wrapped_syms.cmake * * 2. add all of those functions in tests/unit/mocked_funcs.h, with their * correct signature * * 3. create gMOCK classes with one or more mocked "methods" like MockingBar * * 4. instantiate ONE mock object per TEST and use it with EXPECT_CALL or * ON_CALL, as explained in the gmock documentation */ extern "C" { bool experiment_bar(); int experiment_foo(int); } class MockingBar : public KernelSingleton { public: MOCK_METHOD(bool, experiment_bar, (), (override)); }; /* * Base case: call the functions without any mocking, and expect them to work. */ TEST(experiment, gfuncs1) { ASSERT_EQ(experiment_bar(), true); ASSERT_EQ(experiment_foo(5), 50); ASSERT_EQ(experiment_foo(6), 60); } /* * Basic mocking: mock experiment_bar() to first fail and then to succeed. * Note: experiment_foo() remains in its original form, despite the jump * through KernelSingleton's vtable. */ TEST(experiment, gfuncs2) { MockingBar mock; EXPECT_CALL(mock, experiment_bar) .WillOnce(Return(false)) .WillOnce(Return(true)); ASSERT_EQ(experiment_foo(5), -1); ASSERT_EQ(experiment_foo(5), 50); } <file_sep>#!/bin/sh exec size "$@" <file_sep># SPDX-License-Identifier: BSD-2-Clause import gdb # pylint: disable=import-error from . import base_utils as bu from . import tilck_types as tt from . import tasks class printer_user_mapping: def __init__(self, val): self.val = val def to_string(self): return "mapping" def children(self): m = self.val pi = m["pi"] h = m["h"] handle_str = "(null)" if h: handle_n = tasks.get_handle_num(pi, h) if handle_n: handle_str = str(handle_n) else: handle_str = "<unknown handle at: {}>".format(bu.fixhex32(int(h))) return [ ("pid ", pi['pid']), ("handle ", handle_str), ("prot ", m["prot"]), ("offset ", hex(m["off"])), ("va_begin ", bu.fixhex32(m["vaddr"])), ("va_end ", bu.fixhex32(m["vaddr"] + m["len"])), ("length ", m["len"]), ] class printer_mappings_info: def __init__(self, val): self.val = val def to_string(self): return bu.fmt_type("struct mappings_info", self.val) def children(self): mi = self.val res = [] mappings = bu.get_list_elems( mi["mappings"].address, tt.user_mapping, "pi_node" ) for i, e in enumerate(mappings): res.append(("[{}]".format(i), e.dereference())) return res bu.register_tilck_regex_pp( 'mappings_info', '^mappings_info$', printer_mappings_info ) bu.register_tilck_regex_pp( 'user_mapping', '^user_mapping$', printer_user_mapping )
9e0c8c8d8bafa73d133e41f201badc756c92978a
[ "CMake", "Ruby", "Markdown", "Makefile", "Dockerfile", "Python", "C", "C++", "Shell" ]
684
Shell
vvaltchev/tilck
e9c27da4dd15f5f8a927b11f31484aec3f1429f0
ccf8d9933be1269b85388e5b21645b831ecf5412
refs/heads/master
<repo_name>ozyhale/mvc-project<file_sep>/mvc/Libs/Session.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of Session * * @author Manipis */ class Session { public static function start(){ session_start(); } public static function set_username($username){ $_SESSION['username'] = $username; } public static function get_username(){ return $_SESSION['username']; } public static function is_username_set(){ return isset($_SESSION['username']); } public static function unset_username(){ unset($_SESSION['username']); } public static function destroy(){ session_destroy(); } } ?> <file_sep>/mvc/Libs/Model.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of Model * * @author Manipis */ class Model { public function __construct() { $this->con = mysql_connect(SERVER, USERNAME, PASSWORD); if(!$this->con){ echo mysql_error(); }else{ mysql_select_db('db_mvc'); } } public function close(){ mysql_close($this->con); } } ?> <file_sep>/mvc/Libs/Controller.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Mao ni ang main controller... i.extend ni sa every controller para mainherit nia ang method nga read_url() * * @author Manipis */ abstract class Controller { public function perform_actions() { if (isset($_GET['action'])) { //kung na set ang $_GET['action'] matawag nato ang method nga gi.specify sa action //for example: //www.site.com/index.php?action=login // //'index' ang atong CLASS //ang METHOD nato kay 'login' //so pag.instantiate sa index nga class ($class = new Index();) //ma.tawag pod ang login nga function $method = $_GET['action']; if (count($_GET) == 1) { //ang count($_GET)... ihapon niya kung pila kbouk ang elements sa sulod sa //$_GET nga variable kung //kung 1 gane //meaning.. walay parameters //pero kung greater than 1 gne //naa nay PARAMETERS @call_user_func(array($this, $method)); //tawagon na nato ang function nga gihatag sa url... //ang function nga call_user_func() mao na xia ang mutawag sa //method nga gispecify sa url } else { //else kung naay PARAMETERS, //for example: www.site.com/administrator.php?action=filter&year=3rd&course=IT //so meaning to say ang 'year' ug ang 'course' kay mga PARAMETERS... $parameters = array_slice($_GET, 1); //sliced nako para ang $_GET['action'] kay dili maapil as parameter @call_user_func_array(array($this, $method), $parameters); } } } public abstract function display(); } ?> <file_sep>/mvc/index.php <?php require_once 'Config/config.php'; require_once 'Libs/Model.php'; require_once 'Libs/Controller.php'; require_once 'Libs/Session.php'; require_once 'Libs/smarty/libs/Smarty.class.php'; require_once 'Model/User_Model.php'; Session::start(); class Index extends Controller{ private $smarty; //views private $user_model; //model public function __construct() { $this->smarty = new Smarty(); $this->smarty->assign('title', 'Home'); $this->smarty->assign('site', 'Sitename'); $this->smarty->assign('alert', ''); if(Session::is_username_set()){ $this->smarty->assign('tpl_file', 'Views/logout.tpl'); }else{ $this->smarty->assign('tpl_file', 'Views/login.tpl'); } $this->user_model = new User_Model(); } public function login(){ $username = $_POST['username']; $password = $_POST['<PASSWORD>']; if($this->user_model->is_username_exist($username) and $this->user_model->is_password_exist($password)){ Session::set_username($username); header('Location: /mvc/'); }else{ $this->smarty->assign('alert', '<h4><font color="red">Error Logging in!</font></h4>'); } } public function logout(){ Session::unset_username(); Session::destroy(); header('Location: /mvc/'); } public function search_user($username){ return $username; } public function display(){ $this->perform_actions(); //perform actions according to what function is specified in index.php?action=[action] $this->user_model->close(); $this->smarty->display('Views/template/simple.tpl'); } } $controller = new Index(); $controller->display(); //display contents in the controller ?><file_sep>/mvc/Model/User_Model.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of User_Model * * @author Manipis */ class User_Model extends Model { private $username; private $password; public function is_username_exist($username) { $result = mysql_query("SELECT * FROM tbl_users WHERE username='$username'"); return mysql_num_rows($result) > 0; } public function is_password_exist($password) { $result = mysql_query("SELECT * FROM tbl_users WHERE password='$password'"); return mysql_num_rows($result) > 0; } public function set_username($username) { $this->username = $username; } public function set_password($password) { $this->password = $password; } public function save() { $query = "INSERT INTO tbl_users" . "(username, password)" . "VALUES" . "($this->username, $this->password)"; $result = mysql_query($query); return $result; } } ?> <file_sep>/mvc/Config/config.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ define('SERVER', 'localhost'); define('USERNAME', 'root'); define('PASSWORD', ''); define('DATABASE', 'db_mvc'); ?>
771d9f19f5eb414a699d99158564669dc12f0288
[ "PHP" ]
6
PHP
ozyhale/mvc-project
8fbc6bb263aa01238468ca349dba25f58014a9a4
a951538abbcfc76c6f35e610f88a849d0d0592c5
refs/heads/master
<file_sep>import XCTest import SimExec import SimExecAgent //private let udid = "F16240A8-B724-4724-AB34-3D54F9EE1B90" private let udid = "0C737A0A-2CFB-45FC-9A41-70155C98460D" final class SimExecAgentTests: XCTestCase { var agent: SimExecAgentTool? override func setUp() { let agent = try! SimExecAgentTool(queue: .main) self.agent = agent } override func tearDown() { agent?.terminate() agent = nil } func testFirstState() throws { let exp = expectation(description: "") let client = SimExecAgentClient(host: "localhost", queue: .main) client.errorHandler = { (error) in XCTFail("\(error)") } client.start() client.stateHandler = { (state) in XCTAssertEqual(state, SimExecAgentTool.State.ready) exp.fulfill() } wait(for: [exp], timeout: 10) } func testFullSuccess() throws { let exp = expectation(description: "") let client = SimExecAgentClient(host: "localhost", queue: .main) client.errorHandler = { (error) in XCTFail("\(error)") } client.start() var stateIndex = 0 client.stateHandler = { (state) in switch stateIndex { case 0: XCTAssertEqual(state, .ready) case 1: XCTAssertEqual(state, .start) case 2: XCTAssertEqual(state, .build) case 3: XCTAssertEqual(state, .launch) case 4: XCTAssertEqual(state, .running) case 5: XCTAssertEqual(state, .ready) default: break } stateIndex += 1 } client.screenshotHandler = { (file) in guard let image = NSImage(contentsOf: file) else { XCTFail("broken image") return } print(image.size) } let source = """ import UIKit class ViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.green fputs("stdout\\n", stdout) fflush(stdout) fputs("stderr\\n", stderr) fflush(stderr) } } """ client.request(SimExecAgentTool.Request(source: source, udid: udid)) { (response) in do { let response = try response.get() XCTAssertEqual(response.out, "stdout\n") XCTAssertEqual(response.error, "stderr\n") exp.fulfill() } catch { XCTFail("\(error)") } } wait(for: [exp], timeout: 300) } func testBuildFailure() { let exp = expectation(description: "") let client = SimExecAgentClient(host: "localhost", queue: .main) client.errorHandler = { (error) in XCTFail("\(error)") } client.start() var stateIndex = 0 client.stateHandler = { (state) in switch stateIndex { case 0: XCTAssertEqual(state, .ready) case 1: XCTAssertEqual(state, .start) case 2: XCTAssertEqual(state, .build) case 3: XCTAssertEqual(state, .ready) default: break } stateIndex += 1 } let source = """ import UIKit class ViewController : UIViewController { override func viewDidFooBar() { super.viewDidLoad() } } """ client.request(SimExecAgentTool.Request(source: source, udid: udid)) { (response) in do { _ = try response.get() XCTFail("broken source passed") } catch { XCTAssertEqual(stateIndex, 4) let str = "\(error)" XCTAssertTrue(str.contains("viewDidFooBar")) exp.fulfill() } } wait(for: [exp], timeout: 300) } func testConflictClients() { var startClient2: (() -> Void)! let exp = expectation(description: "") let client = SimExecAgentClient(host: "localhost", queue: .main) client.errorHandler = { (error) in XCTFail("\(error)") } client.start() let client2 = SimExecAgentClient(host: "localhost", queue: .main) client2.errorHandler = { (error) in XCTFail("\(error)") } var stateIndex = 0 client.stateHandler = { (state) in switch stateIndex { case 0: XCTAssertEqual(state, .ready) case 1: XCTAssertEqual(state, .start) startClient2() default: break } stateIndex += 1 } let source = """ import UIKit class ViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.green fputs("stdout\\n", stdout) fflush(stdout) fputs("stderr\\n", stderr) fflush(stderr) } } """ client.request(SimExecAgentTool.Request(source: source, udid: udid)) { (response) in do { let response = try response.get() XCTAssertEqual(response.out, "stdout\n") XCTAssertEqual(response.error, "stderr\n") exp.fulfill() } catch { XCTFail("\(error)") } } startClient2 = { client2.start() client2.request(SimExecAgentTool.Request(source: source, udid: udid)) { (response) in do { _ = try response.get() XCTFail("double request accepted") } catch { let str = "\(error)" XCTAssertTrue(str.contains("not ready")) } } } wait(for: [exp], timeout: 300) } } <file_sep>import XCTest import SimExec //private let udid = "F16240A8-B724-4724-AB34-3D54F9EE1B90" private let udid = "0C737A0A-2CFB-45FC-9A41-70155C98460D" final class SimExecTests: XCTestCase { var fs: FileSystem! override func setUp() { fs = FileSystem(applicationName: "SimExecTests") } override func tearDown() { fs.deleteKeepedTemporaryFiles() } func testSuccess() throws { let sourceFile = try fs.makeTemporaryDirectory(name: "source", deleteAfter: true) .appendingPathComponent("source.swift") let source = """ import UIKit class ViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.green fputs("stdout\\n", stdout) fflush(stdout) fputs("stderr\\n", stderr) fflush(stderr) } } """ try source.data(using: .utf8)!.write(to: sourceFile) let options = SimExecTool.Options(sourceFile: sourceFile, simulatorDeviceUDID: udid, keepTemporaryFiles: true) let tool = SimExecTool(options: options) try tool.run() } func testBuildFailure() throws { let sourceFile = try fs.makeTemporaryDirectory(name: "source", deleteAfter: true) .appendingPathComponent("source.swift") let source = """ import UIKit class ViewController : UIViewController { override func viewDidFooBar() { super.viewDidLoad() } } """ try source.data(using: .utf8)!.write(to: sourceFile) let options = SimExecTool.Options(sourceFile: sourceFile, simulatorDeviceUDID: udid, keepTemporaryFiles: true) let tool = SimExecTool(options: options) do { try tool.run() XCTFail("broken code passed") } catch { switch error { case let e as Xcodebuild.BuildError: let str = e.out.toUTF8Robust() XCTAssertTrue(str.contains("viewDidFooBar")) default: XCTFail("invalid error type") } } } } <file_sep>import Foundation import SimExec public struct ControlMessage { public var code: String public init(code: String) { self.code = code } public func validate() throws { guard let _ = code.range(of: "ViewController") else { throw MessageError("you must define ViewController class") } guard let _ = code.range(of: "UIKit") else { throw MessageError("you must import UIKit") } } public static func parse(_ message: String) -> ControlMessage? { let quote = "```" guard let quoteRange0 = message.range(of: quote) else { return nil } guard let quoteRange1 = message.range(of: quote, options: [], range: (quoteRange0.upperBound...).relative(to: message), locale: nil) else { return nil } var code = String(message[quoteRange0.upperBound..<quoteRange1.lowerBound]) code = code.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return ControlMessage(code: code) } } <file_sep>import Foundation import SimExec public final class SimExecAgentTool { public enum State : String, Codable { case ready case start case build case launch case running public init(from state: SimExecTool.State) { switch state { case .start: self = .start case .build: self = .build case .launch: self = .launch case .running: self = .running case .complete: self = .ready } } } public struct Request : Codable { public var source: String public var udid: String public init(source: String, udid: String) { self.source = source self.udid = udid } } public struct Response : Codable { public var out: String public var error: String } public let queue: DispatchQueue private var adapter: SimExecAgentSocketAdapter! private var execQueue: DispatchQueue? private let fileSystem: FileSystem public private(set) var state: State { didSet { stateHandler?(state) } } public var stateHandler: ((State) -> Void)? public var screenshotHandler: ((URL) -> Void)? public init(queue: DispatchQueue) throws { let tag = "SimExecAgent" self.queue = queue self.fileSystem = FileSystem(applicationName: tag) self.state = .ready self.adapter = try SimExecAgentSocketAdapter(agent: self, fileSystem: fileSystem) } deinit { print("SimExecAgent.deinit") terminate() } public func terminate() { self.adapter.terminate() } public func request(_ request: Request, completionHandler: @escaping (Result<Response, Error>) -> Void) { do { guard case .ready = self.state else { throw MessageError("not ready now") } self.state = .start let execQueue = DispatchQueue(label: "SimExecAgent.execQueue") self.execQueue = execQueue execQueue.async { self.exec(request: request, completionHandler: completionHandler) } } catch { completionHandler(.failure(error)) } } private func exec(request: Request, completionHandler: @escaping (Result<Response, Error>) -> Void) { do { let fs = FileSystem(applicationName: "SimExecAgentTool") defer { fs.deleteKeepedTemporaryFiles() } let workDir = try fs.makeTemporaryDirectory(name: "work", deleteAfter: true) let sourceFile = workDir.appendingPathComponent("ViewController.swift") try request.source.write(to: sourceFile, atomically: true, encoding: .utf8) let options = SimExecTool.Options(sourceFile: sourceFile, simulatorDeviceUDID: request.udid, keepTemporaryFiles: false) let tool = SimExecTool(options: options) tool.stateHandler = { (state) in self.queue.async { self.state = State(from: state) } } tool.screenshotHandler = { (file) in self.queue.async { self.screenshotHandler?(file) } } try tool.run() let out = try Data(contentsOf: tool.outFile!).toUTF8Robust() let err = try Data(contentsOf: tool.errorFile!).toUTF8Robust() let response = SimExecAgentTool.Response(out: out, error: err) queue.async { completionHandler(.success(response)) } } catch { queue.async { self.state = .ready completionHandler(.failure(error)) } } } public static func main(arguments: [String]) -> Never { do { let tool = try SimExecAgentTool(queue: DispatchQueue.main) _ = tool dispatchMain() } catch { fatalError("\(error)") } } } <file_sep>import SimExecDiscord SimExecDiscordTool.main(arguments: CommandLine.arguments) <file_sep>import Foundation public typealias CodableError = Error & Encodable & Decodable public struct CodableErrorTypeInfo { public var type: CodableError.Type public var name: String public init(type: CodableError.Type, name: String? = nil) { self.type = type self.name = name ?? "\(type)" } } <file_sep>import Foundation public final class IDPool { private var ids: Set<Int> public init() { self.ids = Set() } public func create() -> IDHolder { var id = 1 while ids.contains(id) { id += 1 } ids.insert(id) return IDHolder(pool: self, id: id) } public func release(id: Int) { ids.remove(id) } } public final class IDHolder { private weak var pool: IDPool? public var id: Int public init(pool: IDPool, id: Int) { self.pool = pool self.id = id } deinit { pool?.release(id: id) } } <file_sep>import Foundation import FineJSON import RichJSONParser import SimExec public protocol MessageProtocol : Codable { static var name: String { get } } public let messageTypes: [MessageProtocol.Type] = [ AgentStateEvent.self, AgentRequestRequest.self, AgentRequestResponse.self ] extension MessageProtocol { public static var name: String { return "\(self)" } } extension MessageProtocol { public func dispatch_KeyedEncodingContainer_encode<K>( container: inout KeyedEncodingContainer<K>, forKey key: K) throws where K : CodingKey { try container.encode(self, forKey: key) } } public struct AgentStateEvent : MessageProtocol { public var state: SimExecAgentTool.State } public struct AgentRequestRequest : MessageProtocol { public var request: SimExecAgentTool.Request } public struct AgentRequestResponse : MessageProtocol { public var result: Result<SimExecAgentTool.Response, Error> public init(result: Result<SimExecAgentTool.Response, Error>) { self.result = result } public init(from decoder: Decoder) throws { self.result = try decodeResult(from: decoder, errorTypes: codableErrorTypes) } public func encode(to encoder: Encoder) throws { try encodeResult(result, to: encoder, errorTypes: codableErrorTypes) } } <file_sep>import SimExecAgent SimExecAgentTool.main(arguments: CommandLine.arguments) <file_sep>import Foundation import Network import RichJSONParser import SimExec public final class MessageConnection { private let connection: JSONConnection public var errorHandler: ((Error) -> Void)? public var closedHandler: (() -> Void)? public var receiveHandler: ((MessageProtocol) -> Void)? public var connectedHandler: (() -> Void)? public var fileHandler: ((URL) -> Void)? { get { return connection.fileHandler } set { connection.fileHandler = newValue } } public init(connection: NWConnection, fileSystem: FileSystem) { self.connection = JSONConnection(connection: connection, fileSystem: fileSystem) } public func start(queue: DispatchQueue) { connection.errorHandler = { [weak self] (error) in self?.errorHandler?(error) } connection.closedHandler = { [weak self] in self?.closedHandler?() } connection.receiveHandler = { [weak self] (json) in guard let self = self else { return } do { try self.onReceive(json: json) } catch { self.connection.close() self.errorHandler?(error) } } connection.connectedHandler = { [weak self] in self?.connectedHandler?() } connection.start(queue: queue) } public func close() { connection.close() } public func send(message: MessageProtocol) throws { let container = MessageCodableContainer(message) let json = try container.encodeToJSON() connection.send(json: json, completionHandler: nil) } public func send(file: URL, completionHandler: (() -> Void)?) { connection.send(file: file, completionHandler: completionHandler) } private func onReceive(json: ParsedJSON) throws { let container = try MessageCodableContainer.decode(from: json) receiveHandler?(container.value) } } <file_sep>import Foundation public protocol DecodableByProxy : Decodable { associatedtype CodableProxy : Decodable init(fromCodableProxy p: CodableProxy) } extension DecodableByProxy { public init(from decoder: Decoder) throws { let c = try decoder.singleValueContainer() let p = try c.decode(CodableProxy.self) self.init(fromCodableProxy: p) } } public protocol EncodableByProxy : Encodable { associatedtype CodableProxy : Encodable func encodeToCodableProxy() -> CodableProxy } extension EncodableByProxy { public func encode(to encoder: Encoder) throws { let p = encodeToCodableProxy() var c = encoder.singleValueContainer() try c.encode(p) } } <file_sep>import Foundation public struct MessageError : ErrorBase, Codable { public var message: String public init(_ message: String) { self.message = message } public var description: String { return message } } <file_sep>import Foundation public struct ExitStatusError : ErrorBase { public var executable: URL public var arguments: [String] public var status: Int32 public var error: Data? public var description: String { var m = [ "exit status=\(status)", "command=\(executable.path)", "arguments=\(arguments)" ] if let error = error { m.append("error=\(error.toUTF8Robust())") } return m.joined(separator: ", ") } } extension Process { public func exitStatusError(errorData: Data?) -> ExitStatusError { return ExitStatusError(executable: executableURL!, arguments: arguments!, status: terminationStatus, error: errorData) } } <file_sep>import Foundation public struct Xcodebuild { public struct BuildError : ErrorBase { public var out: Data public var error: Data public var description: String { let lines = [ "output:", out.toUTF8Robust(), "error:", error.toUTF8Robust() ] return lines.joined(separator: "\n") } } public struct SDK : Codable { public var canonicalName: String public var displayName: String public var platform: String public var sdkVersion: String } public typealias ShowSDKsResponse = [SDK] public typealias BuildSettings = [String: String] public struct ShowBuildSettingsResponseItem : Codable { public var action: String public var buildSettings: BuildSettings public var target: String } public typealias ShowBuildSettingsResponse = [ShowBuildSettingsResponseItem] public var project: URL public var scheme: String public var configuration: String public var sdk: String private func baseArgs() -> [String] { return [ "xcodebuild", "-project", project.path, "-scheme", scheme, "-configuration", configuration, "-sdk", sdk ] } public static func showSDKs() throws -> ShowSDKsResponse { let args = [ "xcodebuild", "-showsdks", "-json" ] let out = try capture(arguments: args) return try ShowSDKsResponse.decode(fromJSONData: out) } public func showBuildSettings() throws -> ShowBuildSettingsResponse { let args = baseArgs() + [ "-showBuildSettings", "-json" ] let out = try capture(arguments: args) return try ShowBuildSettingsResponse.decode(fromJSONData: out) } public func build(destinationUDID: String) throws { let args = baseArgs() + [ "-destination", "id=\(destinationUDID)", "-quiet" ] var out = Data() var error = Data() let p = try runProcess(arguments: args, out: Pipe.output { (d) in out.append(d) }, error: Pipe.output { (d) in error.append(d) }) guard p.terminationStatus == EXIT_SUCCESS else { throw BuildError(out: out, error: error) } } } <file_sep>// swift-tools-version:5.0 import PackageDescription let package = Package( name: "SimExec", platforms: [.macOS(.v10_14)], dependencies: [ .package(url: "https://github.com/omochi/FineJSON", from: "1.13.0"), .package(url: "https://github.com/nuclearace/SwiftDiscord", .branch("development")) ], targets: [ .target(name: "SimExec", dependencies: ["FineJSON"]), .testTarget(name: "SimExecTests", dependencies: ["SimExec"]), .target(name: "sim-exec", dependencies: ["SimExec"]), .target(name: "SimExecAgent", dependencies: ["SimExec", "FineJSON"]), .target(name: "sim-exec-agent", dependencies: ["SimExecAgent"]), .testTarget(name: "SimExecAgentTests", dependencies: ["SimExecAgent"]), .target(name: "SimExecDiscord", dependencies: ["SimExecAgent", "SwiftDiscord"]), .target(name: "sim-exec-discord", dependencies: ["SimExecDiscord"]) ] ) <file_sep>extension Optional { public mutating func take() -> Wrapped? { let x = self self = nil return x } } <file_sep>import Foundation import Network import SimExec public final class SimExecAgentClient { private let host: String private let connection: MessageConnection private let fileSystem: FileSystem private let queue: DispatchQueue public private(set) var state: SimExecAgentTool.State = .ready { didSet { stateHandler?(state) } } public var stateHandler: ((SimExecAgentTool.State) -> Void)? public var screenshotHandler: ((URL) -> Void)? public var errorHandler: ((Error) -> Void)? private var requestCompletionHandler: ((Result<SimExecAgentTool.Response, Error>) -> Void)? public init(host: String, queue: DispatchQueue) { self.host = host self.queue = queue self.fileSystem = FileSystem(applicationName: "SimExecAgentClient") let conn = NWConnection(host: NWEndpoint.Host(host), port: SimExecAgentSocketAdapter.port, using: NWParameters(tls: nil)) self.connection = MessageConnection(connection: conn, fileSystem: fileSystem) connection.errorHandler = { [weak self] (error) in self?.onConnectionError(error) } connection.closedHandler = { [weak self] () in self?.onConnectionClosed() } connection.receiveHandler = { [weak self] (message) in self?.onReceive(message: message) } connection.fileHandler = { [weak self] (file) in self?.onFile(file) } } public func start() { connection.start(queue: queue) } public func request(_ request: SimExecAgentTool.Request, completionHandler: @escaping (Result<SimExecAgentTool.Response, Error>) -> Void) { do { try connection.send(message: AgentRequestRequest(request: request)) requestCompletionHandler = completionHandler } catch { completionHandler(.failure(error)) } } private func onConnectionError(_ error: Error) { handleError(error) } private func onConnectionClosed() { handleError(MessageError("connection closed")) } private func onReceive(message: MessageProtocol) { switch message { case let m as AgentStateEvent: self.state = m.state case let m as AgentRequestResponse: let h = requestCompletionHandler.take() h?(m.result) default: handleError(MessageError("unknown message: \(type(of: message))")) } } private func onFile(_ file: URL) { screenshotHandler?(file) } private func handleError(_ error: Error) { let h = requestCompletionHandler.take() h?(.failure(error)) errorHandler?(error) } } <file_sep>import Foundation extension FileManager { public func fileExists(at url: URL) -> Bool { return fileExists(atPath: url.path) } public func fileExists(at url: URL, isDirectory: inout Bool) -> Bool { var isDir = ObjCBool(false) let ret = fileExists(atPath: url.path, isDirectory: &isDir) isDirectory = isDir.boolValue return ret } public func attributesOfItem(at url: URL) throws -> [FileAttributeKey : Any] { return try attributesOfItem(atPath: url.path) } public func copyItem(at srcURL: URL, to dstURL: URL, overwrite: Bool) throws { if overwrite, fileExists(at: dstURL) { try removeItem(at: dstURL) } try copyItem(at: srcURL, to: dstURL) } public func changeCurrentDirectory(to url: URL) throws { guard changeCurrentDirectoryPath(url.path) else { throw MessageError("change directory failed: \(url.path)") } } } <file_sep>import XCTest import Network import SimExec import SimExecAgent final class TransportTests: XCTestCase { func testFileSend() throws { let exp = expectation(description: "") let fs1 = FileSystem(applicationName: "fs1") let fs2 = FileSystem(applicationName: "fs2") var conn1: JSONConnection! var conn2: JSONConnection! createConnectionPair(fs1: fs1, fs2: fs2) { (pair) in do { let pair = try pair.get() conn1 = pair.0 conn2 = pair.1 conn1.errorHandler = { (error) in XCTFail("\(error)") } conn2.errorHandler = { (error) in XCTFail("\(error)") } var si = 0 var send: (() -> Void)? send = { let file = resourceDirectory .appendingPathComponent("SimExecAgentTests") .appendingPathComponent("image\(si).png") conn1.send(file: file, completionHandler: { si += 1 if si == 3 { return } send!() }) } send!() var ri = 0 let expectedSizes = [ CGSize(width: 600, height: 600), CGSize(width: 700, height: 600), CGSize(width: 800, height: 600) ] conn2.fileHandler = { (file) in let image = NSImage(contentsOf: file)! XCTAssertEqual(image.size, expectedSizes[ri]) ri += 1 if ri == 3 { exp.fulfill() return } } } catch { XCTFail("\(error)") } } wait(for: [exp], timeout: 30) } private func createConnectionPair(fs1: FileSystem, fs2: FileSystem, handler: @escaping (Result<(JSONConnection, JSONConnection), Error>) -> Void) { do { let port = NWEndpoint.Port(31514) var listen: NWListener? = try NWListener(using: NWParameters(tls: nil), on: port) let nwConn2 = NWConnection(host: "localhost", port: port, using: NWParameters(tls: nil)) let conn2 = JSONConnection(connection: nwConn2, fileSystem: fs2) conn2.errorHandler = { (error) in listen = nil handler(.failure(error)) } listen!.stateUpdateHandler = { (state) in switch state { case .failed(let error): listen = nil handler(.failure(error)) default: break } } listen!.newConnectionHandler = { (nwConn1) in let conn1 = JSONConnection(connection: nwConn1, fileSystem: fs1) conn1.start(queue: .main) let pair = (conn1, conn2) listen?.cancel() listen = nil handler(.success(pair)) } listen!.start(queue: .main) conn2.start(queue: .main) } catch { handler(.failure(error)) } } } <file_sep>import SimExec SimExecTool.main(args: CommandLine.arguments) <file_sep>import Foundation public final class SimExecTool { public struct Options { public var sourceFile: URL public var simulatorDeviceUDID: String public var keepTemporaryFiles: Bool public init(sourceFile: URL, simulatorDeviceUDID: String, keepTemporaryFiles: Bool) { self.sourceFile = sourceFile self.simulatorDeviceUDID = simulatorDeviceUDID self.keepTemporaryFiles = keepTemporaryFiles } } public enum State : String, Codable { case start case build case launch case running case complete } private let options: Options private let fileSystem: FileSystem private let logger: Logger public private(set) var state: State { didSet { stateHandler?(state) } } public var stateHandler: ((State) -> Void)? public var screenshotHandler: ((URL) -> Void)? private var projectDir: URL? private var buildDir: URL? private var simctl: Simctl? private var appFile: URL? public private(set) var outFile: URL? public private(set) var errorFile: URL? public private(set) var screenshotFiles: [URL] = [] public init(options: Options) { let tag = "SimExecTool" self.options = options self.fileSystem = FileSystem(applicationName: tag) self.logger = Logger(tag: tag) self.state = State.start } public func run() throws { defer { if !options.keepTemporaryFiles { fileSystem.deleteKeepedTemporaryFiles() } } let simctl = Simctl(udid: options.simulatorDeviceUDID) self.simctl = simctl try assertDevice() try checkout() try build() try bootDevice() try installAppToDevice() try launchApp() try takeScreenshots() try terminateApp() } private func assertDevice() throws { let device = try simctl!.status() guard device.isAvailable else { throw MessageError("device not available: udid=\(device.udid)") } } private func checkout() throws { let checkoutDir = try fileSystem.makeTemporaryDirectory(name: "checkout", deleteAfter: true) let projDir = checkoutDir .appendingPathComponent("TempApp") let templateDir = resourceDirectory .appendingPathComponent("TempAppTemplate") try fm.copyItem(at: templateDir, to: projDir) let sourceDestPath = projDir .appendingPathComponent("TempApp") .appendingPathComponent("ViewController.swift") try fm.copyItem(at: options.sourceFile, to: sourceDestPath, overwrite: true) logger.debug("projDir=\(projDir.path)") self.projectDir = projDir } private func build() throws { self.state = .build try fm.changeCurrentDirectory(to: projectDir!) let sdks = try Xcodebuild.showSDKs() guard let sdk = (sdks.first { $0.platform == "iphonesimulator" && $0.sdkVersion == "12.2" }) else { throw MessageError("sdk not found") } let xcodebuild = Xcodebuild(project: URL(fileURLWithPath: "TempApp.xcodeproj"), scheme: "TempApp", configuration: "Debug", sdk: sdk.canonicalName) let buildSettingsResponse = try xcodebuild.showBuildSettings() guard let item = (buildSettingsResponse.first { $0.action == "build" && $0.target == "TempApp" }) else { throw MessageError("build setting not found") } guard let buildDirStr = item.buildSettings["CONFIGURATION_BUILD_DIR"] else { throw MessageError("no CONFIGURATION_BUILD_DIR") } let buildDir = URL(fileURLWithPath: buildDirStr) logger.debug("buildDir=\(buildDir.path)") try xcodebuild.build(destinationUDID: options.simulatorDeviceUDID) self.buildDir = buildDir self.appFile = buildDir.appendingPathComponent("TempApp.app") } private func bootDevice() throws { self.state = .launch var device = try simctl!.status() if device.state == "Booted" { logger.debug("device is booted") return } logger.debug("boot device") try simctl!.boot() sleep(3) device = try simctl!.status() guard device.state == "Booted" else { throw MessageError("device boot failed") } } private func installAppToDevice() throws { logger.debug("install app") try simctl!.install(appURL: appFile!) } private func launchApp() throws { logger.debug("launch app") let dir = self.buildDir! try fm.changeCurrentDirectory(to: dir) self.outFile = dir.appendingPathComponent("out.txt") self.errorFile = dir.appendingPathComponent("error.txt") try simctl!.launch(appID: "simexec.TempApp", outFile: outFile!, errorFile: errorFile!) self.state = .running } private func takeScreenshots() throws { let dir = self.buildDir! for i in 0..<4 { sleep(3) let file = dir.appendingPathComponent("ss.\(i).png") logger.debug("take ss: \(file.path)") try simctl!.screenshot(file: file) screenshotFiles.append(file) screenshotHandler?(file) } } private func terminateApp() throws { logger.debug("terminate app") try simctl!.terminate(appID: "simexec.TempApp") self.state = .complete } public static func main(args: [String]) -> Never { do { let options = try Options.parse(args: args) let tool = SimExecTool(options: options) try tool.run() exit(EXIT_SUCCESS) } catch { fatalError("\(error)") } } } extension SimExecTool.Options { public static func parse(args: [String]) throws -> SimExecTool.Options { var args = args args.removeFirst() var sourceOrNone: URL? var deviceOrNone: String? var keepTemps: Bool = false var i = 0 func takeValue(key: String) throws -> String? { let arg = args[i] guard arg == key else { return nil } i += 1 guard i < args.count else { throw MessageError("parameter not specified for \(key)") } let opt = args[i] i += 1 return opt } func takeFlag(key: String) -> Bool { let arg = args[i] guard arg == key else { return false } i += 1 return true } while i < args.count { if let sourceStr = try takeValue(key: "--source") { sourceOrNone = URL(fileURLWithPath: sourceStr) continue } if let deviceStr = try takeValue(key: "--device") { deviceOrNone = deviceStr continue } if takeFlag(key: "--keep-temps") { keepTemps = true continue } break } guard let source = sourceOrNone else { throw MessageError("source not specified") } guard let device = deviceOrNone else { throw MessageError("device not specified") } return SimExecTool.Options(sourceFile: source, simulatorDeviceUDID: device, keepTemporaryFiles: keepTemps) } } <file_sep>extension Result { public var value: Success? { switch self { case .success(let v): return v case .failure: return nil } } public var error: Failure? { switch self { case .success: return nil case .failure(let e): return e } } public init(value: Success?, error: Failure?) { if let value = value { self = .success(value) } else { self = .failure(error!) } } } <file_sep>import Foundation import AppKit import SimExec import SimExecAgent import SwiftDiscord public final class SimExecDiscordTool : DiscordClientDelegate { private let queue: DispatchQueue private var discord: DiscordClient! private var simulatorUDID: String! private var simExec: SimExecAgentClient? private var requestedChannel: DiscordTextChannel? private var responseView: ResponseView? public init(queue: DispatchQueue) throws { self.queue = queue let env = ProcessInfo.processInfo.environment guard let token = env["DISCORD_TOKEN"], !token.isEmpty else { throw MessageError("no DISCORD_TOKEN") } guard let udid = env["SIM_UDID"], !udid.isEmpty else { throw MessageError("no SIM_UDID") } self.simulatorUDID = udid discord = DiscordClient(token: DiscordToken(stringLiteral: "Bot " + token), delegate: self) discord.handleQueue = queue discord.connect() } deinit { print("deinit") } public func client(_ client: DiscordClient, didConnect connected: Bool) { // let game = DiscordActivity(name: "xxx", type: DiscordActivityType.game) client.setPresence(DiscordPresenceUpdate(game: nil)) // client.user?. } public func client(_ client: DiscordClient, didCreateMessage message: DiscordMessage) { guard let botUser = client.user, let channel = message.channel, !message.author.bot, !message.mentionEveryone, !message.pinned, (message.mentions.contains { $0.id == botUser.id }) else { return } guard let cm = ControlMessage.parse(message.content) else { return } if let _ = self.simExec { sendBusyImmediately(channelID: channel.id) return } self.requestedChannel = channel self.responseView = ResponseView(discord: discord, channel: channel) do { try cm.validate() } catch { self.responseView?.message = "\(error)" reset() return } let simExec = SimExecAgentClient(host: "localhost", queue: queue) self.simExec = simExec simExec.errorHandler = { [weak self] (error) in self?.handleSimExecError(error) } simExec.screenshotHandler = { [weak self] (file) in guard let self = self, let cid = self.responseView?.channel.id else { return } do { let data = try Data(contentsOf: file) let filename = file.lastPathComponent let upload = DiscordFileUpload(data: data, filename: filename, mimeType: "image/png") let message = DiscordMessage(content: filename, embed: nil, files: [upload], tts: false) self.discord.sendMessage(message, to: cid) self.responseView?.reset() } catch { print("ss failure: \(error)") } } simExec.stateHandler = { [weak self] (state) in guard let self = self else { return } switch state { case .ready: break case .start: self.updateResponse(message: "準備中・・・") case .build: self.updateResponse(message: "ビルド中・・・") case .launch: self.updateResponse(message: "起動中・・・") case .running: self.updateResponse(message: "実行中・・・") } } simExec.start() simExec.request(SimExecAgentTool.Request(source: cm.code, udid: simulatorUDID)) { [weak self] (response) in guard let self = self else { return } do { let response = try response.get() let msg = "標準出力:\n\(response.out)" self.updateResponse(message: msg) self.reset() } catch { self.handleSimExecError(error) } } } private func sendBusyImmediately(channelID: ChannelID) { sendResponseImmediately(message: "今忙しいのでまた後にしてください。", channelID: channelID) } private func sendResponseImmediately(message: String, channelID: ChannelID?) { guard let cid = channelID ?? requestedChannel?.id else { return } discord.sendMessage(DiscordMessage(content: message), to: cid) } private func handleSimExecError(_ error: Error) { defer { reset() } let msg = "問題が発生しました:\n\(error)" updateResponse(message: msg) } private func updateResponse(message: String) { responseView?.message = message } private func reset() { simExec = nil requestedChannel = nil responseView = nil } public static func main(arguments: [String]) { do { let tool = try SimExecDiscordTool(queue: DispatchQueue.main) _ = tool dispatchMain() } catch { fatalError("\(error)") } } } <file_sep>import Foundation import os.log public final class Logger { private let tag: String public init(tag: String) { self.tag = tag } public func debug(_ message: String) { log(type: .debug, message: message) } public func error(_ message: String) { log(type: .error, message: message) } public func critical(_ message: String) { log(type: .fault, message: message) } private func log(type: OSLogType, message: String) { os_log(type, "[%@] %@", tag, message) } } <file_sep>import Foundation import Network import RichJSONParser import SimExec public final class SimExecAgentSocketAdapter { public static let port: NWEndpoint.Port = NWEndpoint.Port(35120) unowned let agent: SimExecAgentTool private let fileSystem: FileSystem private var queue: DispatchQueue { return agent.queue } private let logger: Logger private let nwListener: NWListener private var connections: [MessageConnection] private var fileSendingCount: Int = 0 private var pendingAgentResponses: [(MessageConnection, AgentRequestResponse)] = [] public var errorHandler: ((Error) -> Void)? public init(agent: SimExecAgentTool, fileSystem: FileSystem) throws { self.agent = agent self.fileSystem = fileSystem self.logger = Logger(tag: "SimExecAgentSocketAdapter") self.nwListener = try NWListener(using: NWParameters(tls: nil), on: SimExecAgentSocketAdapter.port) self.connections = [] nwListener.stateUpdateHandler = { [weak self] (state) in guard let self = self else { return } switch state { case .failed(let error): self.errorHandler?(error) return default: return } } nwListener.newConnectionHandler = { [weak self] (connection) in self?.onNewConnection(connection) } agent.stateHandler = { [weak self] (state) in guard let self = self else { return } for conn in self.connections { self.send(conneciton: conn, message: AgentStateEvent(state: state)) } } agent.screenshotHandler = { [weak self] (file) in guard let self = self else { return } for conn in self.connections { self.send(connection: conn, file: file) } } nwListener.start(queue: queue) } deinit { print("SimExecAgentSocketAdapter.deinit") terminate() } public func terminate() { for connection in connections { connection.close() } connections.removeAll() nwListener.cancel() } private func onNewConnection(_ connection: NWConnection) { let conn = MessageConnection(connection: connection, fileSystem: fileSystem) conn.errorHandler = { [weak self, weak conn] (error) in guard let self = self, let conn = conn else { return } self.logger.error("\(error)") self.removeConneciton(conn) } conn.receiveHandler = { [weak self, weak conn] (message) in guard let self = self, let conn = conn else { return } do { try self.onReceive(connection: conn, message: message) } catch { self.logger.error("\(error)") self.removeConneciton(conn) } } conn.closedHandler = { [weak self, weak conn] in guard let self = self, let conn = conn else { return } self.removeConneciton(conn) } connections.append(conn) conn.start(queue: queue) send(conneciton: conn, message: AgentStateEvent(state: agent.state)) } private func removeConneciton(_ connection: MessageConnection) { connection.close() connections.removeAll { $0 === connection } } private func isValid(connection: MessageConnection) -> Bool { return connections.contains { $0 === connection } } private func onReceive(connection: MessageConnection, message: MessageProtocol) throws { switch message { case let m as AgentRequestRequest: agent.request(m.request, completionHandler: { (response) in self.pendingAgentResponses.append((connection, AgentRequestResponse(result: response))) self.maySendAgentResponse() }) default: throw MessageError("unsupported message: \(type(of: message))") } } private func maySendAgentResponse() { if fileSendingCount > 0 { print("wait!") return } for (conn, resp) in pendingAgentResponses { self.send(conneciton: conn, message: resp) } pendingAgentResponses.removeAll() } private func send(conneciton: MessageConnection, message: MessageProtocol) { guard isValid(connection: conneciton) else { return } do { try conneciton.send(message: message) } catch { logger.error("\(error)") removeConneciton(conneciton) } } private func send(connection: MessageConnection, file: URL) { guard isValid(connection: connection) else { return } fileSendingCount += 1 connection.send(file: file, completionHandler: { [weak self] in guard let self = self else { return } self.fileSendingCount -= 1 self.maySendAgentResponse() }) } } <file_sep>import Foundation import FineJSON private enum ResultCodingKeys : CodingKey { case value case error } public func decodeResult<T>(from decoder: Decoder, errorTypes: [CodableErrorTypeInfo]) throws -> Result<T, Error> where T : Decodable { let c = try decoder.container(keyedBy: ResultCodingKeys.self) if c.contains(.error) { let error = try decodeDecodableError(from: c, forKey: .error, errorTypes: errorTypes) return Result.failure(error) } let value = try c.decode(T.self, forKey: .value) return Result.success(value) } public func encodeResult<T>(_ result: Result<T, Error>, to encoder: Encoder, errorTypes: [CodableErrorTypeInfo]) throws where T : Encodable { var c = encoder.container(keyedBy: ResultCodingKeys.self) switch result { case .success(let value): try c.encode(value, forKey: .value) case .failure(let error): try encodeEncodableError(error, to: &c, forKey: .error, errorTypes: errorTypes) } } private enum ErrorContainerCodingKeys : CodingKey { case type case value } private func decodeDecodableError<K>(from container: KeyedDecodingContainer<K>, forKey key: K, errorTypes: [CodableErrorTypeInfo]) throws -> Error where K : CodingKey { let c = try container.nestedContainer(keyedBy: ErrorContainerCodingKeys.self, forKey: key) let typeName = try c.decode(String.self, forKey: .type) guard let typeInfo = (errorTypes.first { $0.name == typeName }) else { throw DecodingError.custom(message: "unknown error type: \(typeName)", codingPath: container.codingPath, location: container.sourceLocation) } let error: Error = try typeInfo.type.dispatch_KeyedDecodingContainer_decode(container: c, forKey: .value) return error } private func encodeEncodableError<K>(_ error: Error, to container: inout KeyedEncodingContainer<K>, forKey key: K, errorTypes: [CodableErrorTypeInfo]) throws where K : CodingKey { var c = container.nestedContainer(keyedBy: ErrorContainerCodingKeys.self, forKey: key) let (typeInfo, error) = errorToEncodableError(error, errorTypes: errorTypes) try c.encode(typeInfo.name, forKey: .type) try error.dispatch_KeyedEncodingContainer_encode(container: &c, forKey: .value) } private func errorToEncodableError(_ error: Error, errorTypes: [CodableErrorTypeInfo]) -> (CodableErrorTypeInfo, CodableError) { let originalType = type(of: error) if let typeInfo = (errorTypes.first { $0.type == originalType }) { return (typeInfo, error as! CodableError) } let message = "\(error)" let typeInfo = CodableErrorTypeInfo(type: MessageError.self) return (typeInfo, MessageError(message)) } <file_sep>import Foundation extension Pipe { public static func output(_ handler: @escaping (Data) -> Void) -> Pipe { let pipe = Pipe() pipe.fileHandleForReading.readabilityHandler = { (h) in let chunk = h.availableData handler(chunk) } return pipe } } <file_sep>import Foundation private let randomStringCharacters: [Character] = { let str = [ "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789" ].joined() return str.map { $0 } }() public func randomString(length: Int) -> String { let chars = randomStringCharacters var s = "" for _ in 0..<length { let char = chars.randomElement()! s.append(char) } return s } <file_sep>import Foundation extension Data { public func toUTF8() throws -> String { if let str = String(data: self, encoding: .utf8) { return str } throw MessageError("UTF-8 decode failed") } public func toUTF8Robust() -> String { var data = self data.append(0) let (str, _) = data.withUnsafeBytes { (bufPtr: UnsafeRawBufferPointer) -> (result: String, repairsMade: Bool) in let ptr = bufPtr.baseAddress!.assumingMemoryBound(to: UInt8.self) return String.decodeCString(ptr, as: Unicode.UTF8.self, repairingInvalidCodeUnits: true)! } return str } } <file_sep>import Foundation import SimExec import SwiftDiscord public final class ResponseView { private let discord: DiscordClient public let channel: DiscordChannel private var isNetworking: Bool private var isDirty: Bool private var messageID: MessageID? public var message: String? { didSet { isDirty = true update() } } public init(discord: DiscordClient, channel: DiscordChannel) { self.discord = discord self.channel = channel self.isNetworking = false self.isDirty = false } public func reset() { messageID = nil } private func update() { if !isDirty { return } if isNetworking { return } if let messageID = self.messageID { if let message = self.message { isDirty = false isNetworking = true discord.editMessage(messageID, on: channel.id, content: message) { [self] (message, response) in self.isNetworking = false defer { self.update() } self.messageID = message?.id } } else { isDirty = false isNetworking = true discord.deleteMessage(messageID, on: channel.id) { [self] (ok, response) in self.isNetworking = false defer { self.update() } self.messageID = nil } } } else { if let message = self.message { isDirty = false isNetworking = true discord.sendMessage(DiscordMessage(content: message), to: channel.id) { [self] (message, response) in self.isNetworking = false defer { self.update() } self.messageID = message?.id } } } } } <file_sep>import Foundation public struct Simctl { public typealias Devices = [String: [Device]] public struct Device: Codable { public var state: String public var isAvailable: Bool public var name: String public var udid: String } public struct ListResponse: Codable { public var devices: Devices } public static func list() throws -> ListResponse { let args = [ "xcrun", "simctl", "list", "--json" ] let data = try capture(arguments: args) return try ListResponse.decode(fromJSONData: data) } public func status() throws -> Device { let res = try Simctl.list() let devices = res.devices.flatMap { $1 } guard let device = (devices.first { $0.udid == udid }) else { throw MessageError("device not found: udid=\(udid)") } return device } public func boot() throws { let args = [ "xcrun", "simctl", "boot", udid ] try system(arguments: args) } public func install(appURL: URL) throws { let args = [ "xcrun", "simctl", "install", udid, appURL.path ] try system(arguments: args) } public func launch(appID: String, outFile: URL? = nil, errorFile: URL? = nil) throws { var args = [ "xcrun", "simctl", "launch", ] if let outFile = outFile { args.append("--stdout=\(outFile.path)") } if let errorFile = errorFile { args.append("--stderr=\(errorFile.path)") } args += [udid, appID] try system(arguments: args) } public func screenshot(file: URL) throws { let args = [ "xcrun", "simctl", "io", udid, "screenshot", "--type=png", file.path ] try system(arguments: args) } public func terminate(appID: String) throws { let args = [ "xcrun", "simctl", "terminate", udid, appID ] try system(arguments: args) } public var udid: String } <file_sep># SimExec - [video](https://www.youtube.com/watch?v=1ZEHfmchixA) # License MIT <file_sep>import SimExec import FineJSON public struct MessageCodableContainer : Codable { public enum CodingKeys : CodingKey { case type case value } public var value: MessageProtocol public init(_ value: MessageProtocol) { self.value = value } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) let typeName = try c.decode(String.self, forKey: .type) guard let type: MessageProtocol.Type = (messageTypes.first { $0.name == typeName }) else { throw DecodingError.custom(message: "unknown type: \(typeName)", codingPath: decoder.codingPath, location: decoder.sourceLocation) } let value = try type.dispatch_KeyedDecodingContainer_decode(container: c, forKey: .value) self.init(value) } public func encode(to encoder: Encoder) throws { var c = encoder.container(keyedBy: CodingKeys.self) try c.encode(type(of: value).name, forKey: .type) try value.dispatch_KeyedEncodingContainer_encode(container: &c, forKey: .value) } } <file_sep>import Foundation import SimExec private let _errorTypes: [CodableError.Type] = [ MessageError.self ] public let codableErrorTypes: [CodableErrorTypeInfo] = _errorTypes.map { (t) in CodableErrorTypeInfo(type: t) } <file_sep>import Foundation public func findCommand(_ command: String) throws -> URL { if (command as NSString).isAbsolutePath { return URL(fileURLWithPath: command) } let args = ["/usr/bin/which", command] guard let strData = try? capture(arguments: args) else { throw MessageError("command not found: \(command)") } var str = try strData.toUTF8() str = str.trimmingCharacters(in: .whitespacesAndNewlines) precondition((str as NSString).isAbsolutePath) return URL(fileURLWithPath: str) } public func system(arguments: [String]) throws { let p = try runProcess(arguments: arguments) guard p.terminationStatus == EXIT_SUCCESS else { throw p.exitStatusError(errorData: nil) } } public func capture(arguments: [String]) throws -> Data { var out = Data() var error = Data() let p = try runProcess(arguments: arguments, out: Pipe.output { (d) in out.append(d) }, error: Pipe.output { (d) in error.append(d) }) guard p.terminationStatus == EXIT_SUCCESS else { throw p.exitStatusError(errorData: error) } return out } public func runProcess(arguments: [String], out: Any? = nil, error: Any? = nil) throws -> Process { let p = Process() p.executableURL = try findCommand(arguments[0]) p.arguments = arguments[1...].map { $0 } p.standardOutput = out p.standardError = error try p.run() p.waitUntilExit() return p } <file_sep>import Foundation internal let fm = FileManager.default public final class FileSystem { private let applicationName: String private var keepedTemporaryFiles: [URL] = [] public init(applicationName: String) { self.applicationName = applicationName } public func makeTemporaryDirectory(name: String, deleteAfter: Bool) throws -> URL { let path = try makeTemporaryPath(name: name, deleteAfter: deleteAfter) try fm.createDirectory(at: path, withIntermediateDirectories: true) return path } public func makeTemporaryPath(name: String, deleteAfter: Bool) throws -> URL { let tempRootDir = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(applicationName) while true { let pathName = "\(name).\(randomString(length: 8))" let path = tempRootDir.appendingPathComponent(pathName) if fm.fileExists(at: path) { continue } if deleteAfter { keepedTemporaryFiles.append(path) } return path } } public func deleteKeepedTemporaryFiles() { for d in keepedTemporaryFiles { _ = try? fm.removeItem(at: d) } keepedTemporaryFiles = [] } } <file_sep>import Foundation public let resourceDirectory: URL = URL(fileURLWithPath: #file) .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent() .appendingPathComponent("Resources") <file_sep>import Foundation import FineJSON import RichJSONParser extension Decodable { public static func decode(fromJSONData data: Data) throws -> Self { let decoder = FineJSONDecoder() return try decoder.decode(self, from: data) } public static func decode(from json: ParsedJSON) throws -> Self { let decoder = FineJSONDecoder() return try decoder.decode(self, from: json) } public static func dispatch_KeyedDecodingContainer_decode<K>(container: KeyedDecodingContainer<K>, forKey key: K) throws -> Self { return try container.decode(self, forKey: key) } } extension Encodable { public func encodeToJSON() throws -> JSON { let encoder = FineJSONEncoder() return try encoder.encodeToJSON(self) } public func dispatch_KeyedEncodingContainer_encode<K>(container: inout KeyedEncodingContainer<K>, forKey key: K) throws { try container.encode(self, forKey: key) } } <file_sep>import Foundation import Network import SimExec import FineJSON import RichJSONParser public final class JSONConnection { private struct SendTask { public enum Content { case json(JSON) case file(id: IDHolder) } public var content: Content public var completionHandler: (() -> Void)? } private struct FileSend { public var id: IDHolder public var file: URL public var sentSize: Int public var totalSize: Int? public var stream: InputStream? public var completionHandler: (() -> Void)? } private struct FileReceive { public var id: Int public var file: URL public var receivedSize: Int public var totalSize: Int public var stream: OutputStream } public let connection: NWConnection private let fileSystem: FileSystem private var receiveBuffer: Data private var sendQueue: [SendTask] private var isSending: Bool private let idPool: IDPool private var fileSends: [Int: FileSend] private var receiveDir: URL? private var fileReceives: [Int: FileReceive] public var timeout: TimeInterval? = 3 private var timeoutWork: DispatchWorkItem? public var errorHandler: ((Error) -> Void)? public var receiveHandler: ((ParsedJSON) -> Void)? public var fileHandler: ((URL) -> Void)? public var closedHandler: (() -> Void)? public var connectedHandler: (() -> Void)? public init(connection: NWConnection, fileSystem: FileSystem) { self.connection = connection self.fileSystem = fileSystem self.receiveBuffer = Data() self.sendQueue = [] self.isSending = false self.idPool = IDPool() self.fileSends = [:] self.fileReceives = [:] connection.stateUpdateHandler = { [weak self] (state) in guard let self = self else { return } switch state { case .failed(let error): self.timeoutWork?.cancel() self.timeoutWork = nil self.emitError(error) case .ready: self.timeoutWork?.cancel() self.timeoutWork = nil self.connectedHandler?() self.driveSending() default: break } } } private func update(fileSend: FileSend) { fileSends[fileSend.id.id] = fileSend } private func update(fileReceive: FileReceive) { fileReceives[fileReceive.id] = fileReceive } public func start(queue: DispatchQueue) { if let timeout = self.timeout { let timeoutWork = DispatchWorkItem { [weak self] in guard let self = self else { return } self.emitError(MessageError("connection timeout")) } self.timeoutWork = timeoutWork queue.asyncAfter(deadline: DispatchTime.now() + timeout, execute: timeoutWork) } connection.start(queue: queue) receive() } public func close() { timeoutWork?.cancel() timeoutWork = nil connection.cancel() for fileSend in fileSends.values { if let stream = fileSend.stream { stream.close() } } fileSends.removeAll() if let dir = receiveDir { _ = try? fm.removeItem(at: dir) receiveDir = nil } } public func send(json: JSON, completionHandler: (() -> Void)?) { let task = SendTask(content: .json(json), completionHandler: completionHandler) sendQueue.append(task) driveSending() } public func send(file: URL, completionHandler: (() -> Void)?) { let fileSend = FileSend(id: idPool.create(), file: file, sentSize: 0, totalSize: nil, stream: nil, completionHandler: completionHandler) fileSends[fileSend.id.id] = fileSend let task = SendTask(content: .file(id: fileSend.id), completionHandler: nil) sendQueue.append(task) driveSending() } private func driveSending() { guard connection.state == .ready else { return } if isSending { return } if sendQueue.isEmpty { return } let task = sendQueue.removeFirst() switch task.content { case .json(let json): let serializer = JSONSerializer() let body = serializer.serialize(json) let data = build(body: body, fields: [:]) _send(data: data) { () in task.completionHandler?() } case .file(id: let idHolder): do { try _send(fileSendID: idHolder.id, task: task) } catch { self.emitError(error) } } } private func _send(fileSendID id: Int, task: SendTask) throws { var fileSend = fileSends[id]! if fileSend.stream == nil { let attrs = try fm.attributesOfItem(at: fileSend.file) guard let size = attrs[FileAttributeKey.size] as? Int else { throw MessageError("unknown file size: \(fileSend.file.path)") } guard let stream = InputStream(url: fileSend.file) else { throw MessageError("InputStream init failed: \(fileSend.file.path)") } stream.open() if let error = stream.streamError { throw error } fileSend.stream = stream fileSend.totalSize = size self.update(fileSend: fileSend) } let sendSize = min(1024, fileSend.totalSize! - fileSend.sentSize) var chunk = Data(count: sendSize) let streamReadSize = chunk.withUnsafeMutableBytes { (buf: UnsafeMutableRawBufferPointer) -> Int in fileSend.stream!.read(buf.bindMemory(to: UInt8.self).baseAddress!, maxLength: sendSize) } if let error = fileSend.stream!.streamError { throw error } precondition(sendSize == streamReadSize) let data = build(body: chunk, fields: [ "file": "\(id)", "name": fileSend.file.lastPathComponent, "offset": "\(fileSend.sentSize)", "total": "\(fileSend.totalSize!)" ]) print("send: ===\n\(data.toUTF8Robust())===") _send(data: data) { [weak self] () in guard let self = self else { return } task.completionHandler?() var fileSend = self.fileSends[id]! fileSend.sentSize += sendSize if fileSend.sentSize < fileSend.totalSize! { self.update(fileSend: fileSend) let task = SendTask(content: .file(id: fileSend.id), completionHandler: nil) self.sendQueue.append(task) } else { fileSend.stream!.close() if let error = fileSend.stream!.streamError { throw error } self.fileSends.removeValue(forKey: id) fileSend.completionHandler?() } } } private func build(body: Data, fields: [String: String]) -> Data { var fields = fields fields["length"] = "\(body.count)" var header = fields .map { (k, v) in "\(k)=\(v)" } .joined(separator: "\n") header += "\n\n" let data = header.data(using: .utf8)! + body return data } private func _send(data: Data, completionHandler: @escaping () throws -> Void) { precondition(!isSending) isSending = true connection.send(content: data, contentContext: .defaultStream, isComplete: false, completion: .contentProcessed({ [weak self] (error) in guard let self = self else { return } self.isSending = false do { if let error = error { throw error } try completionHandler() self.driveSending() } catch { self.emitError(error) } })) } private func receive() { connection.receive(minimumIncompleteLength: 1, maximumLength: 1024) { [weak self] (data, context, isFinished, error) in guard let self = self else { return } if let error = error { self.emitError(error) return } if let data = data { self.receiveBuffer.append(data) do { try self.parse() } catch { self.emitError(error) return } } if isFinished { self.closedHandler?() self.connection.cancel() return } self.receive() } } private func emitError(_ error: Error) { close() errorHandler?(error) } private func parse() throws { while true { let more = try parseSingle() if more { continue } break } } typealias More = Bool private func parseSingle() throws -> More { let sep = "\n\n".data(using: .utf8)! if connection.state == .cancelled { return false } guard let sepRange = receiveBuffer.range(of: sep) else { return false } guard let header = String(data: receiveBuffer[..<sepRange.lowerBound], encoding: .utf8) else { throw MessageError("invalid data received") } print("header=\(header)") let lines = header.components(separatedBy: "\n") let fields = lines.compactMap { (line: String) -> (String, String)? in guard let eqPos = line.range(of: "=") else { return nil } let key = String(line[..<eqPos.lowerBound]) let value = String(line[eqPos.upperBound...]) return (key, value) } let fieldMap: [String: String] = Dictionary(fields, uniquingKeysWith: { $1 }) guard let lengthStr = fieldMap["length"], let length = Int(lengthStr) else { throw MessageError("no length") } let bodyStart = sepRange.upperBound let bodyEnd = bodyStart + length if receiveBuffer.count < bodyEnd { return false } let body = receiveBuffer[bodyStart..<bodyEnd] receiveBuffer = Data(receiveBuffer[bodyEnd...]) if let fileIDStr = fieldMap["file"], let fileID = Int(fileIDStr) { try process(fileID: fileID, body: body, header: fieldMap) return true } else { let parser = try JSONParser(data: body) let json = try parser.parse() receiveHandler?(json) return true } } private func process(fileID id: Int, body: Data, header: [String: String]) throws { guard let name = header["name"], let offsetStr = header["offset"], let offset = Int(offsetStr), let totalStr = header["total"], let total = Int(totalStr) else { throw MessageError("invalid file header: \(header)") } if receiveDir == nil { let name = "JSONConnection/receiveDir" self.receiveDir = try fileSystem.makeTemporaryDirectory(name: name, deleteAfter: true) } if fileReceives[id] == nil { let file = receiveDir! .appendingPathComponent(name) _ = try? fm.removeItem(at: file) guard let stream = OutputStream(url: file, append: false) else { throw MessageError("OutputStream init failed: \(file.path)") } stream.open() if let error = stream.streamError { throw error } let fileReceive = FileReceive(id: id, file: file, receivedSize: 0, totalSize: total, stream: stream) guard offset == 0 else { throw MessageError("first offset not 0: \(offset)") } update(fileReceive: fileReceive) } var fileReceive = fileReceives[id]! let streamWrittenSize = body.withUnsafeBytes { (buf) -> Int in fileReceive.stream.write(buf.bindMemory(to: UInt8.self).baseAddress!, maxLength: body.count) } if let error = fileReceive.stream.streamError { throw error } precondition(streamWrittenSize == body.count) fileReceive.receivedSize += body.count precondition(fileReceive.receivedSize <= fileReceive.totalSize) update(fileReceive: fileReceive) if fileReceive.receivedSize == fileReceive.totalSize { fileReceive.stream.close() if let error = fileReceive.stream.streamError { throw error } fileReceives.removeValue(forKey: id) self.fileHandler?(fileReceive.file) } } }
65f4e49e0aef81f1142533da0cea654090de276b
[ "Swift", "Markdown" ]
39
Swift
omochi/SimExec
6a61ee876748cb0e76a4b28dbcac899cde8f4612
98f1070c015071c29707c75e43710a5702b7ccc3
refs/heads/master
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 5 11:50:19 2020 @author: nsai """ import xlrd import re import nltk from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from unicodedata import normalize from sklearn.neighbors import NearestNeighbors from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.cluster import MiniBatchKMeans import numpy as np import pandas as pd ## The general approach is to creat TF-IDF vectors and then using K-means for clustering ## Opening xlsx file wb = xlrd.open_workbook("/Users/nsai/Downloads/OneDrive_1_30-04-2020/Company Descriptions.xlsx") longCompanyDescp = [] companyName = [] ## Creating a List of company names and company description from the file for s in wb.sheets(): for row in range(1,s.nrows,1): companyName.append(s.cell(row,0).value) if s.cell(row,2).value == "": longCompanyDescp.append(s.cell(row,1).value) else : longCompanyDescp.append(s.cell(row,2).value) ## Creating a dictionary of Company names and their description as k,v pairs company_dict = dict(zip(companyName,longCompanyDescp)) ##Cleaning description by removing stop words and numbers def clean_descp(text): letters_only = re.sub('[^a-zA-Z]', ' ', text) words = letters_only.lower().split() new_words = [] for w in words: w_norm = normalize('NFKD', w).encode('ASCII','ignore').decode('ASCII') new_words.append(w_norm) stopwords_eng = set(stopwords.words("english")) useful_words = [x for x in new_words if not x in stopwords_eng] # Combine words into a paragraph again useful_words_string = ' '.join(useful_words) return(useful_words_string) clean_companyDescp = map(clean_descp,longCompanyDescp) clean_company_dict = dict(zip(companyName,clean_companyDescp)) ## Creating TF-IDF Vectors from the descriptions def tokenize(text): tokens = nltk.word_tokenize(text) #stems = stem_words(tokens, stemmer) return tokens tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english') tfs = tfidf.fit_transform(clean_company_dict.values()) #Finding Nearest Neighbours model_tf_idf = NearestNeighbors(metric='cosine', algorithm='brute') model_tf_idf.fit(tfs) #Inputs a query tf_idf vector, the dictionary of companies, the knn model, and the number of neighbors #Prints the k nearest neighbors def print_nearest_neighbors(query_tf_idf, full_company_dictionary, knn_model, k): distances, indices = knn_model.kneighbors(query_tf_idf, n_neighbors = k+1) nearest_neighbors = [list(full_company_dictionary.keys())[x] for x in indices.flatten()] for company in range(len(nearest_neighbors)): if company == 0: print ('Query Company: {0}\n'.format(nearest_neighbors[company])) else: print ('{0}: {1}\n'.format(company, nearest_neighbors[company])) print_nearest_neighbors(tfs[8], clean_company_dict, model_tf_idf, k=5) ## Calculating the right number of clusters by plotting ## the Sum of Squared Errors for different clusters and finding the elbow def find_optimal_clusters(data, max_k): iters = range(2, max_k+1, 4) sse = [] for k in iters: sse.append(MiniBatchKMeans(n_clusters=k).fit(data).inertia_) print('Fit {} clusters'.format(k)) f, ax = plt.subplots(1, 1) ax.plot(iters, sse, marker='o') ax.set_xlabel('Cluster Centers') ax.set_xticks(iters) ax.set_xticklabels(iters) ax.set_ylabel('SSE') ax.set_title('SSE by Cluster Center Plot') find_optimal_clusters(tfs,40) ##Running k-means and plotting with k obtained from elbow method k = 28 km = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=5, verbose=1) km.fit(tfs) ## Assigning cluster values to companies as a dictionary cluster_assignment_dict = {} for i in set(km.labels_): current_cluster_companies = [list(clean_company_dict.keys())[x] for x in np.where(km.labels_ == i)[0]] cluster_assignment_dict[i] = current_cluster_companies ## Assigning Labels to clusters using description of companies in that cluster cluster_themes_dict = {} for key in cluster_assignment_dict.keys(): current_tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english') current_tfs = current_tfidf.fit_transform(map(clean_descp,cluster_assignment_dict[key])) current_tf_idfs = dict(zip(current_tfidf.get_feature_names(), current_tfidf.idf_)) tf_idfs_tuples = current_tf_idfs.items() cluster_themes_dict[key] = sorted(tf_idfs_tuples, key = lambda x: x[1])[:1] ##Output format compList = [] labelList = [] for v in cluster_assignment_dict.values(): compList.append(v) for values in cluster_themes_dict.values(): labelList.append(values[0][0]) def createDict(label,comp): labelCol = [] for i in range(len(comp)): labelCol.append(label) df = pd.DataFrame(list(zip(labelCol,comp)),columns = ["Label","Company"]) df.to_csv("/Users/nsai/Documents/Research/task3_2.csv",mode = "a") for i in range(0,27,1): createDict(labelList[i],compList[i])<file_sep># NLP-WebScrape Work related to Clustering and scraping Naukri.com 1. Need chromedriver for Web Scraping 2. Change wd to current wd in code <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 3 16:28:41 2020 Create an output CSV file with area, job title, company, experience, salary, location, description, tags associated, posting date, scraping date. @author: nsai """ from bs4 import BeautifulSoup from selenium import webdriver import pandas as pd from csv import DictReader from urllib.parse import urlparse from datetime import date ## Using Selenium with BeautifulSoup as using just BeautifulSoup is causing Captcha issues ## Cannot independently use Selenium as there are no unique XPaths, hence use of both Selenium and BS4 is necessary #Variables to print scraping_date= 0 pages = 0 driver = webdriver.Chrome("/Users/nsai/Documents/Research/chromedriver") #Function to get Soup from the web page def get_soup(url): driver = webdriver.Chrome("/Users/nsai/Documents/Research/chromedriver") driver.get(url) html = driver.page_source soup = BeautifulSoup(html,"html.parser") driver.close() return soup #Function to scrape all parameters from the web page def extract_all(soup,area): global pages areas = [] scrape_date = [] jobTitles = [] #Scrape Job Titles for title in soup.find_all('a', {'class': 'title fw500 ellipsis'}): titleText = title.text jobTitles.append(titleText) companyTitles = [] #Scrape Company Name for company in soup.find_all('a',{'class': 'subTitle ellipsis fleft'}): companyText = company.text companyTitles.append(companyText) experience = [] #Scrape Experience for exp in soup.find_all('li',{'class': 'fleft grey-text br2 placeHolderLi experience'}): experienceText = exp.text experience.append(experienceText) salary = [] #Scrape Salary for sal in soup.find_all('li',{'class': 'fleft grey-text br2 placeHolderLi salary'}): salaryText = sal.text salary.append(salaryText) description = [] #Scrape Job Description for jd in soup.find_all('div',{'class' : 'job-description fs12 grey-text'}): jdText = jd.text description.append(jdText) tags = [] #Scrape tags for t in soup.find_all('ul',{'class' : 'tags has-description'}): tags_sub = [] for t1 in t: tags_sub.append(t1.text) tags.append(tags_sub) dates = [] #Scrape Date of posting job for d in soup.find_all('div',{'class' : 'type br2 fleft grey'}): dText = d.text dates.append(dText) # Loop to populate area for job r = len(list(zip(jobTitles,companyTitles,experience,salary,description,tags,dates))) for i in range(0,r,1): areas.append(area) #Loop to populate scrape date for j in range(0,r,1): scrape_date.append(date.today()) #Extracting number of posts and dividing the number of posts by 20 to get number of pages num_posts = soup.find('span',{'class' : 'fleft grey-text mr-5 fs12'}) np = num_posts.text[-4:] pages = int(np,10)//20 df1 = pd.DataFrame(list(zip(areas,jobTitles,companyTitles,experience,salary,description,tags,dates,scrape_date))) return df1 #Function to loop through all pages for a job posting def page_loop(url,area): base_url = urlparse(url) print(url) for i in range(2, pages): newurl = base_url._replace(path = base_url.path + "-" + str(i)) try: soup = get_soup(newurl.geturl()) df1 = extract_all(soup,area) print(newurl.geturl()) print(df1) df1.to_csv("/Users/nsai/Documents/Research/task2.csv", mode = "a") except: continue ## Looping through the given csv and creating a Pandas DataFrame to store the results in a csv with open("/Users/nsai/Downloads/OneDrive_1_30-04-2020/link_by_areas.csv","r") as read_obj: csv_dict_reader = DictReader(read_obj) for row in csv_dict_reader : soup = get_soup(row['link']) df = extract_all(soup,row['type']) print(df) df.to_csv("/Users/nsai/Documents/Research/task2.csv", mode = "a",header = ["Area","Job Title","Company","Experience", "Salary","Job Description","Tags","Posting Date","Scraping Date"]) page_loop(row['link'],row['type']) <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 30 22:49:08 2020 @author: nsai The final output should have a file with fields: year, filename, count of high competition (with its synonyms) and count of technological competition """ import urllib import os from bs4 import BeautifulSoup from nltk.corpus import stopwords from nltk.corpus import webtext from nltk.metrics import BigramAssocMeasures from nltk.collocations import BigramCollocationFinder from nltk.corpus import wordnet as wn ## Counter and Synonyms for High Competition and Technological Comeptition - Tried using Wordnet ## but synonyms for compound words are out of context def synCounter(filepath,file,subdir): filename = file countHighComp = 0 countTechComp = 0 year = os.path.basename(subdir) synHighComp = {"high" : ["competition"],"heavy" :["competition"] ,"highly" : ["competitive"], "competitive" : ["pressures","pressure","markets","position"], "hard":["competition"],"very" : ["competitive"],"many": ["competitors","contenders"], "competition" : ["competition"],"face" : ["competition"]} synTechComp = {"technological" : ["competition","competence","capacity","competitors","competency","competitor"], "technical" : ["competence","competition","capacity","competitors","competency","competitor"]} ##Trying wordnet synonyms for competition # for ss in wn.synsets('competition'): # for l in ss.lemmas(): # print(l.name()) ## Getting Text from HTML using BeautifulSoup4 url = "file:///" + filepath html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,"lxml") text = soup.get_text() ##Cleaning text lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) ##Moving text to new file file1 = open("/Users/nsai/Documents/Research/newfile.txt","w") file1.write(text) file1.close() #Cleaning files for stopwords and punctuation words = [w.lower() for w in webtext.words("/Users/nsai/Documents/Research/newfile.txt")]#could just use "text" variable instead of a file bcf = BigramCollocationFinder.from_words(words) stopset = set(stopwords.words('english')) filter_stops = lambda w: len(w) < 3 or w in stopset bcf.apply_word_filter(filter_stops) ##Identifying Bigrams using Maximum Likelihood ratio bcf1 = (bcf.nbest(BigramAssocMeasures.likelihood_ratio, 6000)) listToStr = " ".join(map(str,bcf1)) file2 = open("/Users/nsai/Documents/Research/newfile2.txt","w") file2.write(listToStr) ##Convert List to Dict dictBCF = {} for (key, value) in bcf1: dictBCF.setdefault(key, []).append(value) wordListHighComp = [] wordListTechComp = [] ##Converting words to dictionary for k in dictBCF.keys() & synHighComp.keys(): resHighCompKey = [] resHighCompValue = [] resDict = {} for v in synHighComp[k]: for values in dictBCF[k]: if values == v: #Broken countHighComp += 1 resHighCompKey.append(k) resHighCompValue.append(values) resDict = dict(zip(resHighCompKey,resHighCompValue)) wordListHighComp.append(resDict) for k in dictBCF.keys() & synTechComp.keys(): resTechCompKey = [] resTechCompValue = [] resDict = {} for v in synTechComp[k]: for values in dictBCF[k]: if values == v : countTechComp += 1 resTechCompKey.append(k) resTechCompValue.append(values) resDict = dict(zip(resTechCompKey,resTechCompValue)) wordListTechComp.append(resDict) while {} in wordListHighComp: wordListHighComp.remove({}) while {} in wordListTechComp: wordListTechComp.remove({}) ## File write file3 = open("/Users/nsai/Documents/Research/task1.txt","a") file3.write(f"High Competition and its synonmys count : {countHighComp}\n") file3.write(f"Synonyms of High Competition present (Depicted as (k,v) pairs): \n") for w in wordListHighComp: file3.write(f"{w}\t") file3.write("\n") file3.write(f"Technological Competiton and its synonyms count : {countTechComp}\n") file3.write("Synonyms of Technological Competition present (Depicted as (k,v) pairs): \n") for w in wordListTechComp: file3.write(f"{w} ") file3.write("\n") file3.write(f"file name is : {filename}\n") file3.write(f"year is : {year}\n") file3.write("\n") # Print Values print("high competition and its synonmys count : ", countHighComp) print("Synonyms of High Competition present :", wordListHighComp ) print("Technological competition and its synonyms count : " , countTechComp) print("Synonyms of Technological Competition present :", wordListTechComp) print("file name is : " , filename) print("year is : ",year) file3.close() file2.close() ##Loop through all directories rootdir = "/Users/nsai/Downloads/OneDrive_1_30-04-2020/10K" filename = "" count = 0 for subdir, dirs, files in os.walk(rootdir): for file in files: #print os.path.join(subdir, file) filepath = subdir + os.sep + file if filepath.endswith(".html"): synCounter(filepath,file,subdir)
23bd0882d254c583d85e3777a83ad6793b884ad2
[ "Markdown", "Python" ]
4
Python
nsai11/NLP-WebScrap
1ee5ded8e7515b40f19acd3b4f810b14fd9b524c
1e53f2081c73cc4935638b560e4d38181fef50f2
refs/heads/master
<repo_name>hitfortime/Demo1<file_sep>/DemoApp/DemoApp/Auth.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DemoApp { public partial class Auth : Form { Form reg; public Auth() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.Hide(); reg = new Reg(); reg.Show(); } } }
0f58701ffff9ad618775aa4d3587905fff5eb247
[ "C#" ]
1
C#
hitfortime/Demo1
1ce08b2ec2c07ef14dace0118bbdc867721e3ee1
23a8d809ff98a7d4c0de80165c854cae734f886d
refs/heads/master
<file_sep>package provider.serviceimpl; import com.service.DemoService; public class DemoServiceImpl implements DemoService { public String demoService(String word) { return "hello buddbo provider"+word; } }
a664475c41807cf6cf4193901e3c9f9d04f04053
[ "Java" ]
1
Java
TQLfuture/dubbo-spring-demo
d247edb06f781ad38ae61ee88e894cc1f79d6472
d073d215697928d9fcfa11bdeaff5e75cedb8a4c
refs/heads/master
<repo_name>Anthony-Martino/tech-elevator-capstones<file_sep>/m1-19_Capstone/src/main/java/com/techelevator/File/FileReader.java package com.techelevator.File; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FileReader { private File inputFile = new File("vendingmachine.csv"); //return a list of strings which is each line in the csv file //Why: convert the file to a storable list public List<String> readCSV() { //may be private List<String> listOfInventory = new ArrayList<String>(); try(Scanner fileScanner = new Scanner(inputFile)) { while(fileScanner.hasNextLine()) { listOfInventory.add(fileScanner.nextLine()); } } catch(Exception e) { System.out.println("Invalid inventory file, Shutting down"); System.exit(1); } return listOfInventory; } //Splitter // split each string redux "|" into an array and add to list of String[] // Why: take list of inventory and separate each line into an array of separate values // we can access keys by fileReader.splitter.get(i)[0] public List<String[]> getSplitInventoryItems() { List<String> listOfInventory = readCSV(); List<String[]> output = new ArrayList(); for (String lines : listOfInventory) { output.add(lines.split("\\|")); } return output; } } <file_sep>/m2-09-Capstone/src/main/java/com/techelevator/model/SiteDAO.java package com.techelevator.model; import java.time.LocalDate; import java.util.List; public interface SiteDAO { public List<Site> getAvailableSitesByCampgroundId(int campgroundId, LocalDate fromDate, LocalDate toDate); } <file_sep>/m3-12_Capstone/src/test/java/com/techelevator/npgeek/selenium/pageobject/HomePage.java package com.techelevator.npgeek.selenium.pageobject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class HomePage { private WebDriver driver; public HomePage(WebDriver driver) { this.driver = driver; } public ParkDetailPage clickParkImageLink() { WebElement parkImageLink = driver.findElement(By.cssSelector(".park-row-container img")); parkImageLink.click(); return new ParkDetailPage(driver); } public SurveyInputPage clickSurveyLink() { WebElement surveyLink = driver.findElement(By.linkText("Survey")); surveyLink.click(); return new SurveyInputPage(driver); } public HomePage clickHomePageLink() { WebElement homeLink = driver.findElement(By.linkText("Home")); homeLink.click(); return new HomePage(driver); } } <file_sep>/m2-09-Capstone/src/test/java/com/techelevator/JDBCCampgroundDAOIntegrationTest.java package com.techelevator; import static org.junit.Assert.assertEquals; import java.sql.SQLException; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.rowset.SqlRowSet; import com.techelevator.model.Campground; import com.techelevator.model.CampgroundDAO; import com.techelevator.model.Park; import com.techelevator.model.ParkDAO; import com.techelevator.model.jdbc.JDBCCampgroundDAO; import com.techelevator.model.jdbc.JDBCParkDAO; public class JDBCCampgroundDAOIntegrationTest extends DAOIntegrationTest{ private CampgroundDAO dao; private JdbcTemplate jdbcTemplate; private static SingleConnectionDataSource dataSource; @BeforeClass public static void setupDataSource() { dataSource = new SingleConnectionDataSource(); dataSource.setUrl("jdbc:postgresql://localhost:5432/campground"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setAutoCommit(false); } @AfterClass public static void closeDataSource() throws SQLException { dataSource.destroy(); } @After public void rollback() throws SQLException { dataSource.getConnection().rollback(); } @Before public void setupTest() { dao = new JDBCCampgroundDAO(dataSource); jdbcTemplate = new JdbcTemplate(dataSource); } @Test public void test_get_all_campgrounds_by_park_id() { int parkId = insertParkReturnParkId("taco", "tacoland"); List<Campground> camps = dao.getCampgroundsByParkId(parkId); int originalSize = camps.size(); insertCampground(parkId, "Testcamp"); camps = dao.getCampgroundsByParkId((int) parkId); assertEquals("Wrong number of campgrounds returned", originalSize + 1, camps.size()); } private int insertCampground (int parkId, String name) { String sqlCamp = "INSERT INTO campground (campground_id, park_id, name, open_from_mm, open_to_mm, daily_fee) " + "VALUES (DEFAULT, ?, ?, '01', '12', '$100.00') RETURNING campground_id"; SqlRowSet results = jdbcTemplate.queryForRowSet(sqlCamp, parkId, name); results.next(); return results.getInt(1); } private int insertParkReturnParkId (String name, String location) { String sqlPark = "INSERT INTO park(park_id, name, location, establish_date, area, visitors, description) " + "VALUES(DEFAULT, ?, ?, '1900-02-01', 65443, 128472, 'This Park Rulez Yo') RETURNING park_id"; SqlRowSet results = jdbcTemplate.queryForRowSet(sqlPark, name, location); results.next(); int parkId = results.getInt(1); return parkId; } } <file_sep>/m3-12_Capstone/src/test/java/com/techelevator/npgeek/selenium/pageobject/ParkDetailPage.java package com.techelevator.npgeek.selenium.pageobject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class ParkDetailPage { private WebDriver driver; public ParkDetailPage(WebDriver driver) { this.driver = driver; } } <file_sep>/m1-19_Capstone/src/main/java/com/techelevator/Stock/Item.java package com.techelevator.Stock; public abstract class Item { private String name; private String price; public Item(String name, String price) { this.name = name; this.price = price; } //getName public String getName() { return name; } //getPrice public int getPrice() { double dollarPrice = Double.parseDouble(price); int returnPrice = (int)(dollarPrice * 100); return returnPrice; } //abstract getMessage public abstract String getMessage(); }<file_sep>/m1-19_Capstone/src/main/java/com/techelevator/VendingMachineCLI.java package com.techelevator; import java.io.IOException; import java.util.List; import com.techelevator.File.FilePrinter; import com.techelevator.view.Menu; public class VendingMachineCLI { private static final String MAIN_MENU_OPTION_DISPLAY_ITEMS = "Display Vending Machine Items"; private static final String MAIN_MENU_OPTION_PURCHASE = "Purchase"; private static final String[] MAIN_MENU_OPTIONS = { MAIN_MENU_OPTION_DISPLAY_ITEMS, MAIN_MENU_OPTION_PURCHASE,}; private static final String PURCHASE_MENU_FEED_MONEY = "Feed Money"; private static final String PURCHASE_MENU_OPTION_SELECT_PRODUCT = "Select Product"; private static final String PURCHASE_MENU_OPTION_FINISH_TRANSACTION = "Finish Transaction"; private static final String[] PURCHASE_MENU_OPTIONS = { PURCHASE_MENU_FEED_MONEY, PURCHASE_MENU_OPTION_SELECT_PRODUCT, PURCHASE_MENU_OPTION_FINISH_TRANSACTION}; private Menu menu; private VendingMachine vendingMachine; private FilePrinter logger; public VendingMachineCLI(Menu menu) { this.menu = menu; } public void run() throws IOException { vendingMachine = new VendingMachine(); logger = new FilePrinter(); while(true) { String choice = (String)menu.getChoiceFromOptions(MAIN_MENU_OPTIONS); if(choice.equals(MAIN_MENU_OPTION_DISPLAY_ITEMS)) { menu.printString(displayInventory()); } else if(choice.equals(MAIN_MENU_OPTION_PURCHASE)) { while (true) { String purchaseChoice = (String)menu.getPurchaseChoiceFromOptions(PURCHASE_MENU_OPTIONS, getCurrentBalance()) ; if(purchaseChoice.equals(PURCHASE_MENU_FEED_MONEY)) { System.out.print("Please insert bills "); feedMoney(menu.getUserDeposit()); } else if (purchaseChoice.equals(PURCHASE_MENU_OPTION_SELECT_PRODUCT)) { System.out.print("Please select a product key to purchase "); String key = menu.getUserItemKey(); try { purchaseProduct(key); } catch (NullPointerException e) { menu.printString("\nERROR: " + key + " is not a valid selection"); } } else if (purchaseChoice.equals(PURCHASE_MENU_OPTION_FINISH_TRANSACTION)) { menu.end(getPurchasedItemNoises(), dispenseCoins()); break; } } } } } public static void main(String[] args) throws IOException { Menu menu = new Menu(System.in, System.out); VendingMachineCLI cli = new VendingMachineCLI(menu); cli.run(); } //private methods private String displayInventory() { return ("\n" + vendingMachine.displayInventory()); } private void feedMoney(int moneyIn) throws IOException { vendingMachine.feedMoney(moneyIn); } private void purchaseProduct(String key) throws IOException { if (!isInStock(key)) { menu.productNotInStock(key); } else if(!isPurchaseAble(key)) { menu.insufficientFunds(); } else { vendingMachine.purchaseProduct(key); String productName = vendingMachine.getItemName(key); menu.printString("\nYou purchased, " + productName + ". Enjoy!"); } } //delegate methods private String getPurchasedItemNoises() { return vendingMachine.displayItemNoises(); } private String dispenseCoins() throws IOException { return vendingMachine.dispenseCoins(); } private String getCurrentBalance() { return vendingMachine.getCurrentBalance(); } private boolean isPurchaseAble(String key) { return vendingMachine.isPurchaseable(key); } private boolean isInStock(String key) { return vendingMachine.isInStock(key); } } <file_sep>/m3-12_Capstone/src/test/java/com/techelevator/npgeek/selenium/pageobject/SurveyInputPage.java package com.techelevator.npgeek.selenium.pageobject; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.Select; public class SurveyInputPage { private WebDriver driver; public SurveyInputPage(WebDriver driver) { this.driver = driver; } public SurveyInputPage selectFavoritePark(String park) { WebElement selectFavoritePark = driver.findElement(By.id("parkCode")); Select dropdown = new Select(selectFavoritePark); dropdown.selectByVisibleText(park); return this; } public SurveyInputPage selectEmailAddress(String emailAddress) { WebElement emailField = driver.findElement(By.name("emailAddress")); emailField.sendKeys(emailAddress); return this; } public SurveyInputPage selectState(String state) { WebElement selectState = driver.findElement(By.id("state")); Select dropdown = new Select(selectState); dropdown.selectByVisibleText(state); return this; } public SurveyInputPage selectActivityLevel(String activityLevel) { WebElement radioButton = driver.findElement(By.cssSelector("form:radiobutton[value='" + activityLevel + "']")); radioButton.click(); return this; } public SurveyResultPage submitForm() { WebElement submitButton = driver.findElement(By.className("submit")); submitButton.click(); return new SurveyResultPage(driver); } } <file_sep>/m2-09-Capstone/src/main/java/com/techelevator/model/ReservationDAO.java package com.techelevator.model; import java.time.LocalDate; import java.util.List; public interface ReservationDAO { public long createReservation(int siteId, String name, LocalDate startDate, LocalDate toDate); } <file_sep>/m2-09-Capstone/src/main/java/com/techelevator/model/jdbc/JDBCCampgroundDAO.java package com.techelevator.model.jdbc; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import com.techelevator.model.Campground; import com.techelevator.model.CampgroundDAO; public class JDBCCampgroundDAO implements CampgroundDAO { private JdbcTemplate jdbcTemplate; public JDBCCampgroundDAO(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } //NEEDS TESTING @Override public List<Campground> getCampgroundsByParkId(int parkId) { List<Campground> campgrounds = new ArrayList<Campground>(); String sqlCampgroundById = "SELECT campground_id, park_id, name, open_from_mm, open_to_mm, daily_fee " + "FROM campground " + "WHERE park_id = ?"; SqlRowSet results = jdbcTemplate.queryForRowSet(sqlCampgroundById, parkId); while (results.next()) { Campground c = mapRowToCampground(results); campgrounds.add(c); } return campgrounds; } private Campground mapRowToCampground(SqlRowSet results) { Campground campground = new Campground(); campground.setCampGroundId(results.getLong("campground_id")); campground.setParkId(results.getInt("park_id")); campground.setName(results.getString("name")); campground.setOpenFrom(results.getInt("open_from_mm")); campground.setOpenTo(results.getInt("open_to_mm")); campground.setDailyFee(results.getDouble("daily_fee")); return campground; } } <file_sep>/m2-09-Capstone/src/main/java/com/techelevator/CampgroundCLI.java package com.techelevator; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import java.time.LocalDate; import java.util.List; import com.techelevator.model.*; import com.techelevator.model.jdbc.*; import com.techelevator.view.Menu; public class CampgroundCLI { private static final String PARK_INFORMATION_VIEW_CAMPGROUND = "View Campgrounds"; private static final String PARK_INFORMATION_SEARCH_RESERVATION = "Search for Reservation"; private static final String RETURN_TO_PREVIOUS_SCREEN = "Return to Previous Screen"; private static final String[] PARK_INFORMATION_SCREEN = { PARK_INFORMATION_VIEW_CAMPGROUND, PARK_INFORMATION_SEARCH_RESERVATION, RETURN_TO_PREVIOUS_SCREEN }; private static final String CAMPGROUND_RESERVATION_SEARCH = "Search for Available Reservation"; private static final String[] CAMPGROUND_SELECTION_SCREEN = { CAMPGROUND_RESERVATION_SEARCH, RETURN_TO_PREVIOUS_SCREEN }; private Menu menu; private ReservationManager admin; private List<Park> allParks; private Park userSelectedPark; private List<Campground> camps; private Campground userSelectedCamp; private int userCampChoice; private LocalDate arrivalDate; private LocalDate departureDate; private List<Site> availableSites; private int userSelectedSiteId; private String userName; private long confirmationId; public static void main(String[] args) { Menu menu = new Menu(System.in, System.out); CampgroundCLI application = new CampgroundCLI(menu); application.run(); } public CampgroundCLI(Menu menu) { this.menu = menu; admin = new ReservationManager(); } private void run() { while (true) { handlesParkScreen(); mainMenu: while (true) { String parkInfoScreenChoice = handlesCampChoiceScreen(); if (parkInfoScreenChoice.equals(PARK_INFORMATION_VIEW_CAMPGROUND)) { menu.displayCampgroundsInfo(camps, userSelectedPark); while (true) { String campgroundsScreenChoice = (String) menu.getChoiceFromOptions(CAMPGROUND_SELECTION_SCREEN); if (campgroundsScreenChoice.equals(CAMPGROUND_RESERVATION_SEARCH)) { //this method handles getting the camp selection, arrival and departure dates, and makes the reservation. //If the user selects to return to the main menu the boolean returns true and it will break to the mainMenu location //If the user selects 0 to cancel, then the boolean returns false and the loop will break back once boolean userSelectedToReturnToMainScreen = handlesCampgroundChoiceAndSiteChoiceAndMakesReservation(); if (userSelectedToReturnToMainScreen) { break mainMenu; } else { break; } } else if (campgroundsScreenChoice.equals(RETURN_TO_PREVIOUS_SCREEN)) { break; } } } else if (parkInfoScreenChoice.equals(PARK_INFORMATION_SEARCH_RESERVATION)) { // THIS IS BONUS get list of available sites per park } else if (parkInfoScreenChoice.equals(RETURN_TO_PREVIOUS_SCREEN)) { break; } } } } private void handlesParkScreen() { allParks = admin.getAllParks(); userSelectedPark = menu.getParkChoiceFromOptions(allParks); menu.displayParkInfo(userSelectedPark); } private String handlesCampChoiceScreen() { String parkInfoScreenChoice = (String) menu.getChoiceFromOptions(PARK_INFORMATION_SCREEN); camps = admin.getCampgroundsByParkId((int) userSelectedPark.getParkId()); return parkInfoScreenChoice; } //Handles getting user campground choice, //uses get available dates method //if there are no available sites user is prompted if they want to search again or return to main menu (return true) //once the user makes a reservation it returns to main menu (return true) private boolean handlesCampgroundChoiceAndSiteChoiceAndMakesReservation() { while (true) { userCampChoice = (int) menu.getCampChoiceFromOptions(camps); if (userCampChoice == 0) { return false; } else { userSelectedCamp = camps.get(userCampChoice - 1); } handleGetDatesAndAvailableSites(); while (availableSites.size() == 0) { if ((boolean) menu.noAvailableSitesPromptAlternateDate()) { handleGetDatesAndAvailableSites(); } else { return true; } } menu.displayAvailableSites(availableSites, userSelectedCamp, arrivalDate, departureDate); while (true) { if (!handleReservation()) { return false; } else { return true; } } } } //Handles making a reservation and displaying conformation Id private boolean handleReservation() { while (true) { userSelectedSiteId = (int) menu.waitForValidSiteIdFromUser(availableSites); if (userSelectedSiteId == 0) { return false; } userName = (String) menu.getNameFromUserInput(); confirmationId = admin.createReservation(userSelectedSiteId, userName, arrivalDate, departureDate); menu.printConformationId(confirmationId); return true; } } //Handles getting arrival and departure dates from user private void handleGetDatesAndAvailableSites() { arrivalDate = menu.waitForValidArrivalDateFromUser(); departureDate = menu.waitForValidDepartureDateFromUser(arrivalDate); availableSites = admin.getAvailableSitesByCampgroundId((int) userSelectedCamp.getCampGroundId(), arrivalDate, departureDate); } } <file_sep>/m1-19_Capstone/src/main/java/com/techelevator/Stock/Items/Gum.java package com.techelevator.Stock.Items; import com.techelevator.Stock.Item; public class Gum extends Item { public Gum(String name, String price) { super(name, price); } public String getMessage() { return "Chew Chew, Yum!"; } } <file_sep>/m1-19_Capstone/src/main/java/com/techelevator/view/Menu.java package com.techelevator.view; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Scanner; public class Menu { private PrintWriter out; private Scanner in; public Menu(InputStream input, OutputStream output) { this.out = new PrintWriter(output); this.in = new Scanner(input); } //1st menu public Object getChoiceFromOptions(Object[] options) { Object choice = null; while(choice == null) { displayMenuOptions(options); choice = getChoiceFromUserInput(options); } return choice; } //Purchase (2nd) menu public Object getPurchaseChoiceFromOptions(Object[] options, String balance) { Object choice = null; while(choice == null) { displayPurchaseMenuOptions(options, balance); choice = getChoiceFromUserInput(options); } return choice; } //generic print to console public void printString(String thingToPrint) { out.println(thingToPrint); } //used if user selects 1: FEED MONEY public int getUserDeposit() { while (true) { String input = in.nextLine(); if (input.equals("1") || input.equals("2") || input.equals("5") || input.equals("10")) { int userInput = Integer.parseInt(input); return userInput; } else { out.println("\nERROR: Please insert a valid currency denomination $(1, 2, 5, or 10)"); return 0; } } } //used if user selects 2: SelectProduct public String getUserItemKey() { String userInput = in.nextLine(); return userInput; } //used in purchase product method in CLI public void productNotInStock(String key) { out.println("\n" + key + " is currently SOLD OUT"); } //used in purchase product method in CLI public void insufficientFunds() { out.println("\n*****INSUFFICIENT BALANCE*****"); } //3: Finish Transaction public void end(String noises, String coins) { printItemNoises(noises); printDispensedCoins(coins); } //Finish Transaction private void printItemNoises(String noises) { out.println("\n" + noises); } //Finish Transaction private void printDispensedCoins(String coins) { out.println(coins); } //Used in both Menus private Object getChoiceFromUserInput(Object[] options) { Object choice = null; String userInput = in.nextLine(); try { int selectedOption = Integer.valueOf(userInput); if(selectedOption > 0 && selectedOption <= options.length) { choice = options[selectedOption - 1]; } } catch(NumberFormatException e) { // eat the exception, an error message will be displayed below since choice will be null } if(choice == null) { out.println("\n*** "+userInput+" is not a valid option ***\n"); } return choice; } //1st menu private void displayMenuOptions(Object[] options) { out.println(); for(int i = 0; i < options.length; i++) { int optionNum = i+1; out.println(optionNum+") "+options[i]); } out.print("\nPlease choose an option >>> "); out.flush(); } //used in second menu to display purchase price private void printCurrentBalance(String balance) { out.println("\nCurrent Balance: $" + balance + "\n"); } //2nd menu private void displayPurchaseMenuOptions(Object[] options, String balance) { out.println(); for(int i = 0; i < options.length; i++) { int optionNum = i+1; out.println(optionNum+") "+options[i]); } printCurrentBalance(balance); out.print("Please choose an option >>> "); out.flush(); } } <file_sep>/m1-19_Capstone/src/main/java/com/techelevator/Stock/Items/Chips.java package com.techelevator.Stock.Items; import com.techelevator.Stock.Item; public class Chips extends Item { public Chips(String name, String price) { super(name, price); } public String getMessage() { return "Crunch Crunch, Yum!"; } } <file_sep>/m1-19_Capstone/src/main/java/com/techelevator/Purchases/CoinBox.java package com.techelevator.Purchases; import java.math.BigDecimal; public class CoinBox { // EVERYTHING HERE IS DEALT WITH IN PENNIES AS INTS private int balance; public CoinBox() { } //adds money to balance //this will come in as pennies so no need to * 100 public void addMoney(int moneyIn) { balance += moneyIn; } //removes money from balance //this will come in as pennies so no need to * 100 public void spendMoney(int itemPrice) { balance -= itemPrice; } public boolean isEnoughAvailableBalance(int itemPrice) { if (itemPrice <= balance) { return true; } else { return false; } } //return balance public int getCurrentBalanceInPennies() { return balance; } //while balance > 0 //subtracts coin amounts from balance and updates balance //keeps track of total coins dispensed and returns string //resets balance to 0 (this only occurs when transaction ends) public String dispenseCoins() { String coinDispenser = ""; int quarterCounter = 0; int dimeCounter = 0; int nickelCounter = 0; double actualBalance = ((double)balance) / 100; String endingBalance = ""; endingBalance += endingBalance.format("%.2f", actualBalance); while (balance > 0) { if (balance >= 25) { quarterCounter++; balance -= 25; } else if (balance >= 10) { dimeCounter++; balance -= 10; } else if (balance >= 5) { nickelCounter++; balance -= 5; } } coinDispenser = "Dispensing " + quarterCounter + " quarters\n" + "Dispensing " + dimeCounter + " dimes\n" + "Dispensing " + nickelCounter + " nickels\n" + "Total change dispensed: $" + endingBalance; balance = 0; return coinDispenser; } }
8ffa4b321132f4023f1f3af640542155057f1a84
[ "Java" ]
15
Java
Anthony-Martino/tech-elevator-capstones
a4d108373bc82be3ebcb00e93a2c2c140c1691e6
bf311f1a98fcd613bc07c281cbe19110a2216f5f
refs/heads/master
<file_sep>//刷新验证码 function changeImg() { var imgSrc = $("#imgObj"); var src = imgSrc.attr("src"); imgSrc.attr("src", chgUrl(src)); } //时间戳 //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳 function chgUrl(url) { var timestamp = (new Date()).valueOf(); if ((url.indexOf("?") >= 0)) { url = url.substring(0,url.indexOf("?")); } url = url + "?timestamp=" + timestamp; return url; } function checkCode(){ var code = $("#checkCode").val(); var flag = false; if(code == ""){ alert("请输入验证码!"); } else { $.ajax({ url:'checkCode/' + code, async:false, type:'post', contentType:'application/json' , dataType:'json', error:function(data){alert("系统错误....");}, success:function(data){ if(data.ok == 1){ flag = true; } else { alert("验证码错误"); } } }); } return flag; } function login(){ if(checkCode()){ var code = $("#checkCode").val(); var name = $("#name").val(); var password = $("#<PASSWORD>").val(); $.ajax({ url:'member/checkMember', data:'' }); } } $(document).ready(function(){ $("#checkCode").blur(function(){ checkCode(); }); });<file_sep>GameTechnologyManager ===================== 后台管理系统
dce276bda7571094379a44f7bb7c2e796650b585
[ "JavaScript", "Markdown" ]
2
JavaScript
wgslucky/GameTechnologyManager
075cd1e92844d11a1f404a8b81d803bca12223d5
ea1907f290c1f38f5fc8cfcd7549104fb5f9f529
refs/heads/master
<file_sep>//Volume of cuboid = l*b*h. Create two objects of a class including two values of l,b,h. Display volume of both individually and also add both l,b,h. Further find volume of cuboid using values of resultant l,b,h. #include<iostream> class volume { private: int l,b,h; public: void get() { std::cout<<"Enter length, breadth & height of object : "; std::cin>>l>>b>>h; } friend void multiply(volume one, volume two); friend void add(volume one, volume two); }; void multiply(volume one, volume two) { int x,y,z; x=one.l; y=one.b; z=one.h; std::cout<<"Volume of object one : "; std::cout<<x*y*z<<"\n"; x=two.l; y=two.b; z=two.h; std::cout<<"Volume of object two : "; std::cout<<x*y*z<<"\n"; } void add(volume one, volume two) { int l=one.l+two.l; int b=one.b+two.b; int h=one.h+two.h; std::cout<<"New length, breadth & height : "<<l<<","<<b<<","<<h<<"\n"; std::cout<<"Volume of new object : "; std::cout<<l*b*h<<"\n"; } int main() { volume one; volume two; one.get(); two.get(); multiply(one,two); add(one,two); return 0; } <file_sep>//Series upto 10 terms - 1 2 4 7 .... #include<iostream> int main() { int n=1,i; for(i=0;i<10;i++) { n=n+i; std::cout<<n<<"\t"; } return 0; } <file_sep>//FILE HANDLING. Reading from file. #include<iostream> #include<fstream> int main() { std::ifstream objif; char st[50]; std::cout<<"Enter file name : "; std::cin>>st; objif.open(st); if(objif) { while(!objif.eof()) //eof() is a function in ifstream class in C++. In C, EOF is variable. { objif.getline(st,50); std::cout<<st<<"\n"; } objif.close(); } else { std::cout<<"FIle NOT FOUND!\n"; } return 0; } <file_sep>//Destructor. #include<iostream> int count=0; class demo { public: int a,b; demo() { std::cout<<"Enter two numbers : "; std::cin>>a>>b; std::cout<<"Sum : "<<a+b<<"\n"; } ~demo() { count++; std::cout<<count<<" Destructed!\n"; } demo(int a, int b) { std::cout<<"Sum of 5 & 10 : "<<a+b<<"\n"; } }; int main() { demo object; demo object1(10,5); return 0; } <file_sep>//FILE HANDLING. Writing in a file. #include<iostream> #include<fstream> int main() { std::ofstream objof; //Directly making object as I declared header file of class at the top char st[50]; objof.open("abc.txt"); std::cout<<"Enter content to write in file : "; std::cin.getline(st,50); objof<<st; std::cout<<"File created!\n"; objof.close(); return 0; } <file_sep>//Addition of two no. #include<iostream> int main() { int n,a,b; std::cout<<"Enter the 1st no. : "; std::cin>>a; std::cout<<"Enter the 2nd no. : "; std::cin>>b; n=a+b; std::cout<<"Add = "<<n; return 0; } <file_sep>//Program to differntiate b/w public and local variable. Thenafter use of *thispointer*. #include<iostream> class abc { public: int z; //Public Variable void test(int z) //Local Variable { this->z=z*z; //Last two 'z' here, are local variable & first 'z' became public. JAVA uses '.' instead of '->' std::cout<<z; //Local variable's output=10 } void display() { std::cout<<"\n"<<z<<"\n"; //Public variable's output=100 } }; int main() { abc object; object.test(10); object.display(); return 0; } <file_sep>//Multilevel Inheritence. Same name can be stored too as student data. Then search and display. #include<iostream> #include<string.h> class student { protected: char stud[50][50]; //2-D array for no. of data and name int n,i; public: student() //Constructor { std::cout<<"Enter number of data to take input : "; std::cin>>n; for(i=0;i<n;i++) { std::cout<<"Enter name "<<(i+1)<<" : "; std::cin>>stud[i]; } std::cout<<"\n"; } }; class marks: public student { protected: int m[50]; public: marks() { for(i=0;i<n;i++) { std::cout<<"Enter marks of "<<(i+1)<<" : "; std::cin>>m[i]; } std::cout<<"\n"; } }; class search: public marks { private: char name[50]; int c,flag; public: search() { std::cout<<"Enter name to search : "; std::cin>>name; for(i=0;i<n;i++) { c=strcmp(stud[i],name); if(c==0) { std::cout<<"Searched name and marks : "<<stud[i]<<" & "<<m[i]<<"\n"; flag++; } } if(flag==0) { std::cout<<"Not found!\n"; } } }; int main() { search data; return 0; } <file_sep>//Program to differntiate b/w public and local variable. #include<iostream> class abc { public: int z; //Public Variable void test(int z) //Local Variable { z=z*z; //All 'z' here, are local variable std::cout<<z; //Local variable's output } void display() { std::cout<<"\n"<<z<<"\n"; //Public variable's output } }; int main() { abc object; object.test(10); object.display(); return 0; } <file_sep>//Customer details using fstream. Insert, Display, Update and Delete. See Append! #include<iostream> #include<fstream> #include<stdio.h> class customer { public: int id, price; char name[50], product[50]; void insert() { std::fstream objins; objins.open("customer.dat", std::ios::out | std::ios::binary | std::ios::app); //new std::cout<<"Enter customer id : "; std::cin>>id; std::cout<<"Enter customer name : "; std::cin>>name; std::cout<<"Enter product name : "; std::cin>>product; std::cout<<"Enter price : "; std::cin>>price; objins.write((char *)this, sizeof(customer)); std::cout<<"File CREATED!\n"; objins.close(); } void display() { std::fstream objdis; objdis.open("customer.dat", std::ios::in | std::ios::binary); while(objdis.read((char *)this, sizeof(customer))) { std::cout<<"\nID : "<<id; std::cout<<"\nName : "<<name; std::cout<<"\nProduct : "<<product; std::cout<<"\nPrice : "<<price; } objdis.close(); } void deletedata() { int option; std::fstream objdel, objnew; objdel.open("customer.dat", std::ios::in | std::ios::binary); objnew.open("updatedcustomer.dat", std::ios::out | std::ios::binary); std::cout<<"Enter the ID to delete : "; std::cin>>option; while(objdel.read((char *)this, sizeof(customer))) { if(option!=id) { objnew.write((char *)this, sizeof(customer)); } } objnew.close(); objdel.close(); remove("customer.dat"); rename("updatedcustomer.dat","customer.dat"); std::cout<<"Data DELETED!\n"; } void update() { int option; std::fstream objup, objupnew; objup.open("customer.dat", std::ios::in | std::ios::binary); objupnew.open("newupdatedcustomer.dat", std::ios::out | std::ios::binary | std::ios::app); std::cout<<"Enter customer id : "; std::cin>>option; while(objup.read((char *)this, sizeof(customer))) { if(option!=id) { objupnew.write((char *)this, sizeof(customer)); } else { std::cout<<"Enter customer name : "; std::cin>>name; std::cout<<"Enter product name : "; std::cin>>product; std::cout<<"Enter price : "; std::cin>>price; objupnew.write((char *)this, sizeof(customer)); } } objup.close(); objupnew.close(); remove("customer.dat"); rename("newupdatedcustomer.dat","customer.dat"); std::cout<<"Data UPDATED!\n"; } }; int main() { customer info; int choice; char a; do { std::cout<<"\nEnter your choice :\n1) Insert\n2) Display\n3) Delete\n4) Update\n"; std::cin>>choice; switch(choice) { case 1: info.insert(); break; case 2: info.display(); break; case 3: info.deletedata(); break; case 4: info.update(); break; } std::cout<<"\nDo you wanna CONTINUE? YES(Y) or NO(N)\n"; std::cin>>a; } while(a=='y' || a=='Y'); return 0; } <file_sep>//Friend function. Sum of three values. #include<iostream> class abc { private: int a,b,c; public: void get() { std::cout<<"Enter three values : "; std::cin>>a>>b>>c; } void display() { std::cout<<"Display of three inputs : "; std::cout<<a<<","<<b<<","<<c<<"\n"; } friend void add(abc); }; void add(abc object) { int x,y,z; x=object.a; y=object.b; z=object.c; std::cout<<"Sum of three values is : "; std::cout<<x+y+z<<"\n"; } int main() { abc object; object.get(); object.display(); add(object); return 0; } <file_sep>//Constructor example. #include<iostream> class demo { public: int a,b,c; demo() //constructor { std::cout<<"Enter three numbers : "; std::cin>>a>>b>>c; } demo(int x, int y) //constructor { a=x+y; b=x-y; c=x*y; } void display() { std::cout<<a<<"\n"<<b<<"\n"<<c<<"\n"; } }; int main() { demo d1; //d1 is object demo d2(50,20); std::cout<<"Display 1 : \n"; d1.display(); std::cout<<"Display 2 : \n"; d2.display(); return 0; } <file_sep>//FILE HANDLING. Copy a content of one file to another. #include<iostream> #include<fstream> int main() { std::ifstream read; std::ofstream write1; char st[50]; read.open("abc.txt"); write1.open("newabc.txt"); while(!read.eof()) { read.getline(st,50); write1<<st; std::cout<<"File copied!\n"; } read.close(); write1.close(); return 0; } <file_sep>//Add three largest digit no. #include<iostream> int main() { int a[3],i,n=0; for(i=0;i<3;i++) { std::cout<<"Enter the number a["<<i<<"] : "; std::cin>>a[i]; if(a[i]==999 || a[i]==998 || a[i]==997) { n=n+a[i]; } } if(n==2994) { std::cout<<"Answer is : "<<n<<"\n"; } else { std::cout<<"ERROR"; } return 0; } <file_sep>//POLYMORPHISM. Calculate the area of circle, rectangle & triangle using FUNCTION OVERLOADING. #include<iostream> class calculate { public: float area; void shape(int r) { area=3.14*r*r; std::cout<<"Area of Circle is "<<area<<"\n"; } void shape(int l, int b) { area=l*b; std::cout<<"Area of Rectangle is "<<area<<"\n"; } void shape(float l, int b) { area=0.5*l*b; std::cout<<"Area of Triangle is "<<area<<"\n"; } }; int main() { float tri=5; calculate object; object.shape(2); object.shape(5,2); object.shape(tri,2); return 0; } <file_sep>/* Create a class 'shape' in which make a function TRIANGLE with three arguments to calculate the area of triangle depending on their sides. Make another function to display the addition and average of the three sides and also display the types of triangle. Create a function POLYGON with two arguments to decide whether that shape is square or rectangle and find their areas. */ #include<iostream> #include<math.h> class shape { public: void triangle(int a, int b, int c) { float equi,isosc,scal,s,h; if(a==b && b==c && c==a) { equi=sqrt(3)*pow(a,2)/4; std::cout<<"Area of Equilateral Triangle is : "<<equi<<std::endl; } else if(a!=b && b!=c && c!=a) { s=(a+b+c)/2; scal=sqrt((s*(s-a)*(s-b)*(s-c))); std::cout<<"Area of Scalene Triangle is : "<<scal<<std::endl; } else //((a!=b || b!=c || c!=a) && (a==b || b==c || c==a)) { if(c==a && b!=a && b!=c) { h=sqrt(pow(a,2) - pow((b/2),2)); isosc=0.5*b*h; std::cout<<"Area of Isoceles Triangle is : "<<isosc<<std::endl; } else if(b==a && c!=a && c!=b) { h=sqrt(pow(b,2) - pow((c/2),2)); isosc=0.5*c*h; std::cout<<"Area of Isoceles Triangle is : "<<isosc<<std::endl; } else { h=sqrt(pow(c,2) - pow((a/2),2)); isosc=0.5*a*h; std::cout<<"Area of Isosceles Triangle is : "<<isosc<<std::endl; } } } void avg(int a, int b, int c) { float add,average; add=a+b+c; average=add/3; std::cout<<"Addition of three sides is : "<<add<<std::endl; std::cout<<"Average of three sides is : "<<average<<std::endl; if(a==b && b==c && c==a) { std::cout<<"Triangle is Equilateral."<<std::endl; } else if(a!=b && b!=c && c!=a) { std::cout<<"Triangle is Scalene."<<std::endl; } else //((a!=b || b!=c || c!=a) && (a==b || b==c || c==a)) { std::cout<<"Triangle is Isosceles."<<std::endl; } } }; int main() { int x,y,z; shape s1; std::cout<<"Enter three sides of triangle : "; std::cin>>x>>y>>z; s1.triangle(x,y,z); s1.avg(x,y,z); return 0; } <file_sep>//Count the no. of duplicate value in an array. #include<iostream> int main() { int i,j,k,temp=0,n,a[50],count,b; std::cout<<"Enter the number of values to be taken : "; std::cin>>n; for(i=0;i<n;i++) { std::cout<<"a["<<i<<"]="; std::cin>>a[i]; } for(i=0;i<n;i++) { count=1; b=a[i]; temp=0; for(k=0;k<i;k++) //checking from start { if(b==a[k]) { temp=1; } } for(j=i+1;j<n;j++) //comparing from further no. { if(a[i]==a[j] && temp==0) { count++; } } if(temp==0) { std::cout<<"Number : "<<a[i]<<" & "<<"Frequency : "<<count<<std::endl; } } return 0; } <file_sep>//FILE HANDLING. Banking System. 1) Create account. 2) Deposit. 3) Withdraw. 4) Balance Enquiry. #include<iostream> #include<fstream> #include<stdio.h> class bank { public: long accno, inibal; char name[50]; void create() { std::fstream objcre; objcre.open("bank.dat", std::ios::out | std::ios::binary | std::ios::app); std::cout<<"\nEnter Name : "; std::cin>>name; std::cout<<"Enter Account number : "; std::cin>>accno; std::cout<<"Enter Initial balance : "; std::cin>>inibal; objcre.write((char *)this, sizeof(bank)); std::cout<<"Account CREATED!\n"; objcre.close(); } void deposit() { long add, accde; std::fstream objdep, objdepnew; objdep.open("bank.dat", std::ios::in | std::ios::binary); objdepnew.open("newbank.dat", std::ios::out | std::ios::binary); std::cout<<"Enter the Account number to deposit : "; std::cin>>accde; while(objdep.read((char *)this, sizeof(bank))) { if(accde!=accno) { objdepnew.write((char *)this, sizeof(bank)); } else { std::cout<<"Enter the amount to deposit : "; std::cin>>add; inibal=add+inibal; std::cout<<"Total balance : "<<inibal; objdepnew.write((char *)this, sizeof(bank)); } } objdep.close(); objdepnew.close(); remove("bank.dat"); rename("newbank.dat","bank.dat"); std::cout<<"\nAmount of Rs."<<add<<" is deposited SUCCESSFULLY!"; } void withdraw() { long subt, accwi; std::fstream objwith, objwithnew; objwith.open("bank.dat", std::ios::in | std::ios::binary); objwithnew.open("newbank.dat", std::ios::out | std::ios::binary); std::cout<<"Enter the Account number to withdraw from : "; std::cin>>accwi; while(objwith.read((char *)this, sizeof(bank))) { if(accwi!=accno) { objwithnew.write((char *)this, sizeof(bank)); } else { std::cout<<"\nEnter the amount to withdraw : "; std::cin>>subt; if(inibal>=subt) { inibal=inibal-subt; std::cout<<"Total balance : "<<inibal; objwithnew.write((char *)this, sizeof(bank)); std::cout<<"\nAmount of Rs."<<subt<<" is been withdrawn SUCCESSFULLY!"; } else { std::cout<<"Insufficient balance."; objwithnew.write((char *)this, sizeof(bank)); } } } objwith.close(); objwithnew.close(); remove("bank.dat"); rename("newbank.dat","bank.dat"); } void balance() { std::fstream objbal; objbal.open("bank.dat", std::ios::in | std::ios::binary); while(objbal.read((char *)this, sizeof(bank))) { std::cout<<"\nName : "<<name; std::cout<<"\nAccount number : "<<accno; std::cout<<"\nBalance : "<<inibal; } objbal.close(); } }; int main() { bank system; int choice; char a; do { std::cout<<"List of Options :\n1) Create account.\n2) Deposit.\n3) Withdraw.\n4) Balance Enquiry.\n\nEnter option : "; std::cin>>choice; switch(choice) { case 1: system.create(); break; case 2: system.deposit(); break; case 3: system.withdraw(); break; case 4: system.balance(); break; default: std::cout<<"Enter valid number.\n"; break; } std::cout<<"\n\nIf you wanna continue then press Y else N : "; std::cin>>a; std::cout<<std::endl; } while(a=='Y' || a=='y'); return 0; } <file_sep>//Multilevel inheritence. Bank account details. #include<iostream> class bank { protected: char name1[50], place1[50]; public: bank() { std::cout<<"Bank name : "; std::cin>>name1; std::cout<<"Bank city : "; std::cin>>place1; } }; class branch : public bank { protected: char name2[50], place2[50]; public: branch() { std::cout<<"Branch name : "; std::cin>>name2; std::cout<<"Branch area : "; std::cin>>place2; } }; class loan : public branch { protected: int a,r; public: loan() { std::cout<<"Amount : "; std::cin>>a; std::cout<<"Rate in % : "; std::cin>>r; } void display() { std::cout<<"\nBank name : "<<name1; std::cout<<"\nBank city : "<<place1; std::cout<<"\nBranch name : "<<name2; std::cout<<"\nBranch area : "<<place2; std::cout<<"\nAmount : "<<a; std::cout<<"\nRate in % : "<<r<<"\n"; } }; int main() { loan details; details.display(); return 0; } <file_sep>//Create two objects of a class : 1) India 2)Australia. Default constructor: 5 Player names & Score. Main: Who won the match. #include<iostream> #include<string.h> class cricket { public: char n[10][10],k[10]; int s[10],i,y,score; cricket() { score=0; for(i=0;i<3;i++) { std::cout<<"Player : "; std::cin>>n[i]; std::cout<<"Score : "; std::cin>>s[i]; score=s[i]+score; } } void manofthematch() { y=s[0]; for(i=0;i<3;i++) { if(y<s[i]) { y=s[i]; strcpy(k,n[i]); } } std::cout<<"Man of the Match is "<<k<<" with score "<<y<<".\n"; } }; int main() { std::cout<<"India : \n"; cricket india; std::cout<<"India's score : "<<india.score<<"\n"; std::cout<<"\nAustralia : \n"; cricket australia; std::cout<<"Australia's score : "<<australia.score<<"\n"; if(india.score>australia.score) { std::cout<<"\nIndia WON the match.\n"; india.manofthematch(); } else { std::cout<<"\nAustralia WON the match.\n"; australia.manofthematch(); } return 0; } <file_sep>//Reverse each word of a string. #include<iostream> int main() { char st[100],kt[100]; int i,j,k=0,l; std::cout<<"Enter the string : "; std::cin.getline(st,100); for(l=0;st[l]!='\0';l++); st[++l]=' '; for(i=0;i<=l;i++) { if(st[i]==' ') { kt[k]='\0'; for(j=k;j>=0;j--) { std::cout<<kt[j]; } k=0; std::cout<<" "; } else { kt[k]=st[i]; k++; } } return 0; } <file_sep>//Multiple Inheritence. Students details. #include<iostream> class detail { protected: char name[50]; int rno; public: void getdet() { std::cout<<"\nEnter name : "; std::cin>>name; std::cout<<"Enter roll No. : "; std::cin>>rno; } }; class marks { protected: int m1,m2,m3; public: void getmar() { std::cout<<"Enter three marks m1,m2,m3 : "; std::cin>>m1>>m2>>m3; } }; class result : public detail, public marks { public: void display() { std::cout<<"\nName : "<<name<<"\n"; std::cout<<"Roll no. : "<<rno<<"\n"; std::cout<<"Total marks : "<<(m1+m2+m3)<<"\n"; std::cout<<"Average marks : "<<((m1+m2+m3)/3)<<"\n"; } }; int main() { result student[2]; for(int i=0;i<2;i++) { student[i].getdet(); student[i].getmar(); } for(int i=0;i<2;i++) { student[i].display(); } return 0; } <file_sep>//COMPILE TIME POLYMORPHISM : OPERATOR OVERLOADING : with parameter. #include<iostream> class demo { int l,b,h,v; public: void get() { std::cout<<"Enter l,b,h : "; std::cin>>l>>b>>h; } void display() { v=l*b*h; std::cout<<"Volume of cuboid is : "<<v<<"\n"; } demo operator + (demo d1) { demo d3; d3.l=this->l+d1.l; d3.b=this->b+d1.b; d3.h=this->h+d1.h; return d3; } }; int main() { demo d1,d2,d3; d1.get(); d1.display(); d2.get(); d2.display(); d3=d1 +d2; //d1 is passed as parameter and +d2 is for calling function d3.display(); return 0; } <file_sep>//DATA FILE. Use of fstream. Very IMPORTANT. #include<iostream> #include<fstream> class student { public: int rno; char name[50]; void insert() { std::fstream objfs; objfs.open("student.dat", std::ios::out | std::ios::binary); std::cout<<"\nInput values :\nEnter Roll No. : "; std::cin>>rno; std::cout<<"Enter Name : "; std::cin>>name; objfs.write((char *)this, sizeof(student)); std::cout<<"File created.\n"; objfs.close(); } void display() { std::fstream fs; fs.open("student.dat", std::ios::in | std::ios::binary); while(fs.read((char *)this, sizeof(student))) { std::cout<<"\nOutput values :\nRoll no. : "<<rno<<"\n"; std::cout<<"Name : "<<name<<"\n"; } fs.close(); } }; int main() { student detail; int choice, n=0; while(n==0) { std::cout<<"\nOPTIONS :\n 1) Insert\n 2) Display\n 3) Exit\nEnter choice : "; std::cin>>choice; switch(choice) { case 1: detail.insert(); break; case 2: detail.display(); break; case 3: n=1; std::cout<<"\nFile EXIT!\n"; break; default: std::cout<<"Invalid!"; break; } } return 0; } <file_sep>//Using pointer in inheritence. Take the input in a function in a parent class. Check if they are perfect square or not. If not, then what should be added to make it a perfect square. Make child class, in that add those numbers which should be added to make perfect square and display. #include<iostream> class check { protected: int s[2],n[2],i,j,sum; public: void get() { for(i=0;i<2;i++) { std::cout<<"Enter number "<<i+1<<" : "; std::cin>>s[i]; } for(i=0;i<2;i++) { for(j=1;j<=(s[i]/2);j++) { if(j*j==s[i]) { std::cout<<"Perfect square!\n"; break; } else if(j*j>s[i]) { n[i]=j*j-s[i]; std::cout<<"Number added to make "<<s[i]<<" a Perfect square : "<<n[i]<<".\n"; break; } } } } }; class add: public check { public: void display() { sum=0; for(i=0;i<2;i++) { sum=sum+n[i]; } std::cout<<"Sum of numbers to be added : "<<sum<<".\n"; } }; int main() { check call, *p; add callchild, *q; p=&call; p->get(); q=&callchild; q->display(); //callho raha hai but answer ni aayega kyo ki do alag alag pointer object h return 0; } <file_sep>//Function with object. Add two distance. Enter using km and meter. #include<iostream> class distance { public: int a,b; float c; void get() { std::cout<<"\n"<<"Enter distance in Kilometer : "; std::cin>>a; std::cout<<"Enter distance in meter : "; std::cin>>b; } void display() { c=(a+(float)b/1000); std::cout<<c<<"\n"; } void add(distance d1, distance d2) { a=d1.a+d2.a; b=d1.b+d2.b; } }; int main() { distance d1,d2,d3; std::cout<<"\nDistance D1 :"; d1.get(); std::cout<<"Total D1 distance in km is : "; d1.display(); std::cout<<"\nDistance D2 :"; d2.get(); std::cout<<"Total D2 distance in km is : "; d2.display(); d3.add(d1,d2); std::cout<<"\nTotal distance is : "; d3.display(); return 0; } <file_sep>//FILE HANDLING: Transfer data of one file to another in CAPITAL and SMALL ALPHABETS. #include<iostream> #include<fstream> #include<string.h> #include<ctype.h> int main() { std::ifstream objif; std::ofstream objof; char s[50], k[50]; int i, count=1; objif.open("newnewabc.txt"); objof.open("copiedfile.txt"); while(!objif.eof()) { objif.getline(s,50); std::cout<<s; for(i=0;i<strlen(s);i++) { if(isspace(s[i])) { count++; } if(count%2==0) { k[i]=tolower(s[i]); } else { k[i]=toupper(s[i]); } } } objof<<k; std::cout<<"\nFile COPIED! From newnewabc.txt to copiedfile.txt\n"; objof.close(); objif.close(); return 0; } <file_sep>// Inheritance. Single Level. #include<iostream> class base { protected: //Now, it can only be accessed by it's child. int a,b,c; public: //Now, it can be accessed my main fuction. void get() { std::cout<<"Enter three input a,b,c : "; std::cin>>a>>b>>c; //a,b,c are in same class, so get() function can access this. } }; class sub : public base //sub is the child of base. It inherited the property of base. { int x,y; public: void display() { x=a+b+c; y=a*b*c; std::cout<<"Summation : "<<x<<"\n"<<"Multiplication : "<<y<<"\n"; } }; int main() { sub object; object.get(); object.display(); return 0; } <file_sep>//COMPILE TIME POLYMORPHISM : OPERATOR OVERLOADING : without parameter. #include<iostream> class demo { int a; public: void operator + () { a=101; std::cout<<a<<"\n"; } void operator - () { a=102; std::cout<<a<<"\n"; } void operator * () { a=103; std::cout<<a<<"\n"; } void operator ! () { a=104; std::cout<<a<<"\n"; } void operator ++ () { a=105; std::cout<<a<<"\n"; } void operator -- () { a=106; std::cout<<a<<"\n"; } }; int main() { demo d; +d; //calling class's function -d; *d; !d; ++d; --d; return 0; } <file_sep>//Series upto 10 terms - 3 10 29 66 .... #include<iostream> #include<math.h> main() { int n,i; for(i=1;i<11;i++) { n=pow(i,3)+2; std::cout<<n<<"\t"; } } <file_sep>//Find sum of total salary of three employes after working int two companies for a year per. Use OPERATOR OVERLOADING. #include<iostream> class company { char name[3][20]; int sal[6],i,k; public: void get() { for(i=0;i<3;i++) { std::cout<<"Enter Name of employ "<<i+1<<" : "; std::cin>>name[i]; std::cout<<"Enter Salary of employ "<<i+1<<" : "; std::cin>>sal[i]; } } void display() { k=0; for(i=0;i<3;i++) { k=k+sal[i]; } std::cout<<"Salary total : "<<k<<"\n"; } company operator + (company apple) { company sum; for(i=0;i<3;i++) { sum.sal[i]=this->sal[i] + apple.sal[i]; //this.sal[i] takes parameter passed i.e. microsoft here } return sum; } }; int main() { company apple, microsoft, sum; std::cout<<"\nApple:\n"; apple.get(); apple.display(); std::cout<<"\nMicrosoft:\n"; microsoft.get(); microsoft.display(); std::cout<<"\nTotal:\n"; sum=apple +microsoft; sum.display(); return 0; } <file_sep>//POLYMORPHISM CONCEPT EXPLAINED! This is of RUN TIME : FUNCTION OVERRIDING. //MUST SEE the application. #include<iostream> class parent { public: void display() { std::cout<<"Parent.\n"; } }; class child: public parent { public: void display() { parent::display(); //SPECIAL: use this to call parent function in a child std::cout<<"Child.\n"; } }; int main() { child object; object.display(); return 0; } <file_sep>//Function with object. Add two time. Enter using hr min and sec. #include<iostream> class time1 { public: int a,b,c; void get() { std::cout<<"\n"<<"Enter hours : "; std::cin>>a; std::cout<<"Enter minutes : "; std::cin>>b; std::cout<<"Enter seconds : "; std::cin>>c; } void display() { std::cout<<a<<":"<<b<<":"<<c<<"\n"; } void add(time1 t1, time1 t2) { a=t1.a+t2.a; b=t1.b+t2.b; if(b>=60) { b=b-60; a++; } c=t1.c+t2.c; do { if(c>=60) { c=c-60; b++; if(b>=60) { b=b-60; a++; } } }while(c>=60); /* c=t1.c+t2.c; //second logic if(c>=60) { b=b+(c/60); c=c%60; } if(b>=60) { a=a+(b/60); b=b%60; } */ } }; int main() { time1 t1,t2,t3; std::cout<<"\nTime T1 :"; t1.get(); std::cout<<"Time T1 : "; t1.display(); std::cout<<"\nTime T2 :"; t2.get(); std::cout<<"Time T2 : "; t2.display(); t3.add(t1,t2); std::cout<<"\nTotal time is : "; t3.display(); return 0; } <file_sep>//FILE HANDLING: Count no. of words, symbols and digits. Using ctype header file. #include<iostream> #include<fstream> #include<string.h> #include<ctype.h> int main() { std::ifstream objif; char s[50]; int i, digits=0, words=1, symbols=0; objif.open("newnewabc.txt"); while(!objif.eof()) { objif.getline(s,50); std::cout<<s; for(i=0;i<strlen(s);i++) { if(isdigit(s[i])) { digits++; } else if(isspace(s[i])) { words++; } else if(!isalpha(s[i])) { symbols++; } } } objif.close(); std::cout<<"\nDigits : "<<digits<<"\nWords : "<<words<<"\nSymbols : "<<symbols<<"\n"; return 0; } <file_sep>//Basics of Class and Object with Public, Private and Protected. #include<iostream> class demo { public: int a,b,c; void add(int x, int y) { a=x+y; b=x-y; c=x*y; } void display() { std::cout<<a<<"\n"<<b<<"\n"<<c<<"\n"; } void test() { std::cout<<a<<"\n"<<b<<"\n"<<c<<"\n"; } }; main() { int x,y; demo d1; std::cout<<"Enter the two numbers : "; std::cin>>x>>y; d1.add(x,y); d1.display(); std::cout<<"Enter the three numbers : "; std::cin>>d1.a>>d1.b>>d1.c; std::cout<<"Test : \n"; d1.test(); std::cout<<"Display : \n"; d1.display(); } <file_sep>//ABSTRACT CLASS! Virtual Function. #include<iostream> class input //Abstract class { protected: char fname[10],mname[10],lname[10]; public: input() //we can use function too { std::cout<<"Enter first name : "; std::cin>>fname; std::cout<<"Enter middle name : "; std::cin>>mname; std::cout<<"Enter last name : "; std::cin>>lname; } virtual void display() = 0; //override }; class concatenate: public input { public: void display() //override { std::cout<<"Full name : "<<fname<<"."<<mname[0]<<"."<<lname<<"\n"; } }; int main() { concatenate name; name.display(); return 0; } <file_sep>//Heirarchy. WAP that defines a shape class with a constructor that gives value to width & height. Then define two sub-classes triangle and rectangle, that calculate the area of the shape area(). In the main, define two varibles a triangle and a rectangle and then call the area() function in this two variables. #include<iostream> class shape { protected: int a,b,area; public: shape() { std::cout<<"\nEnter two values : "; std::cin>>a>>b; } }; class triangle: public shape { public: void display() { area=0.5*a*b; std::cout<<"Triangle's area : "<<area<<"\n"; } }; class rectangle: public shape { public: void display() { area=a*b; std::cout<<"Rectangle's area : "<<area<<"\n"; } }; int main() { triangle ta; ta.display(); rectangle ra; ra.display(); return 0; } <file_sep>//Display the initials of 3 word name. // <NAME> == A.V.Jaiswal && A.V.J #include<iostream> int main() { char st[50]; int i,space=0,count=0,times=0; std::cout<<"Enter the name : "; std::cin.getline(st,50); for(i=0;st[i]!='\0';i++) { if(i==0) { std::cout<<st[i]<<"."; } if(st[i]==' ') { space++; } if(count==0) { if(space==1) { std::cout<<st[i+1]<<"."; count++; } } if(space==2) { std::cout<<st[i+1]; } } std::cout<<std::endl; space=0; count=0; for(i=0;st[i]!='\0';i++) { if(i==0) { std::cout<<st[i]<<"."; } if(st[i]==' ') { space++; } if(count==0) { if(space==1) { std::cout<<st[i+1]<<"."; count++; } } if(times==0) { if(space==2) { std::cout<<st[i+1]; times++; } } } std::cout<<std::endl; return 0; } <file_sep>//FILE HANDLING. Copy a content of two files in one. #include<iostream> #include<fstream> #include<ctype.h> int main() { std::ifstream read1, read2; std::ofstream write1; char st[50],pt; int i; read1.open("abc.txt"); read2.open("newabc.txt"); write1.open("newnewabc.txt"); while(!read1.eof()) { read1.getline(st,50); write1<<st; } while(!read2.eof()) { read2.getline(st,50); for(i=0;st[i]!='\0';i++) { if(islower(st[i])) { pt=toupper(st[i]); write1<<pt; std::cout<<pt; } else { write1<<st[i]; std::cout<<st[i]; } } } std::cout<<"\nTwo files copied in one!\n"; read1.close(); read2.close(); write1.close(); return 0; } <file_sep>//File Position Pointer: Using Ending. #include<iostream> #include<fstream> int main() { std::fstream object; char st[50]; int l=0; object.open("file.txt", std::ios::in); object.seekg(-9,std::ios::end); while(!object.eof()) { object.getline(st,50); std::cout<<st; l=object.tellg(); } std::cout<<"\nSize : "<<l<<"\n"; object.close(); return 0; } <file_sep>//Multiple inheritence. Which country won the most medals. //Constructor use kia to sochega ki phele kis class ke pass jaau. Isslie humne functions ka use kia h. //SEE PREVIOUS PROGRAM TOO. #include<iostream> class india { protected: int g1,s1,b1; public: void getind() { std::cout<<"India:\n"<<"Gold : "; std::cin>>g1; std::cout<<"Silver : "; std::cin>>s1; std::cout<<"Bronze : "; std::cin>>b1; } }; class russia { protected: int g2,s2,b2; public: void getrus() { std::cout<<"\nRussia:\n"<<"Gold : "; std::cin>>g2; std::cout<<"Silver : "; std::cin>>s2; std::cout<<"Bronze : "; std::cin>>b2; } }; class germany { protected: int g3,s3,b3; public: void getger() { std::cout<<"\nGermany:\n"<<"Gold : "; std::cin>>g3; std::cout<<"Silver : "; std::cin>>s3; std::cout<<"Bronze : "; std::cin>>b3; } }; class result: public india, public russia, public germany { public: void display() { if(g1>g2 && g1>g3) { std::cout<<"MAX Gold is with India : "<<g1<<"\n"; } else if(g2>g1 && g2>g3) { std::cout<<"MAX Gold is with Russia : "<<g2<<"\n"; } else { std::cout<<"MAX Gold is with Germany : "<<g3<<"\n"; } if(s1>s2 && s1>s3) { std::cout<<"MAX Silver is with India : "<<s1<<"\n"; } else if(s2>s1 && s2>s3) { std::cout<<"MAX Silver is with Russia : "<<s2<<"\n"; } else { std::cout<<"MAX Silver is with Germany : "<<s3<<"\n"; } if(b1>b2 && b1>b3) { std::cout<<"MAX Gold is with India : "<<b1<<"\n"; } else if(b2>b1 && b2>b3) { std::cout<<"MAX Gold is with Russia : "<<b2<<"\n"; } else { std::cout<<"MAX Gold is with Germany : "<<b3<<"\n"; } } }; int main() { result max; max.getind(); max.getrus(); max.getger(); std::cout<<"\n"; max.display(); return 0; }
d4a24c38cf6e3dc416b643ee7b69c9da7d102a22
[ "C++" ]
41
C++
iam844/Cpp
4181982bbfe9ebae6ac34a3a748c2accf4fb2c95
cc54e31ef676cc9bf56c82b1a1d2389ca2c7f04d
refs/heads/master
<file_sep># Generated by Django 3.0.4 on 2020-03-18 16:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('todo', '0003_remove_todoitem_created_at'), ] operations = [ migrations.AddField( model_name='todoitem', name='isDone', field=models.BooleanField(default=False), ), ] <file_sep># Generated by Django 3.0.4 on 2020-03-18 02:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('todo', '0002_todoitem_created_at'), ] operations = [ migrations.RemoveField( model_name='todoitem', name='created_at', ), ] <file_sep>from django.db import models class TodoItem(models.Model): content = models.TextField() isDone = models.BooleanField(default=False)
b1ab5e61113dfcfd3b55d07aa462e4de31e7de38
[ "Python" ]
3
Python
brunogcpinheiro/django-todo-app
d85527e70810ddbe99ae2382fb3ea4391a115c73
5a43ce056aa5a3ebcbbcd844d16a2e7aef65ad01
refs/heads/master
<repo_name>kresnaba/konversi_panjang<file_sep>/README.md # konversi_panjang tugas 1 <file_sep>/class.php <?php class konversi { public $masuk; public $op; function utama () { if ($this->op=="inc") $hasil=$this->inc($this->angka); elseif ($this->op=="cm") $hasil=$this->cm($this->angka); elseif ($this->op=="ft") $hasil=$this->ft($this->angka); elseif ($this->op=="mil") $hasil=$this->mil($this->angka); elseif ($this->op=="km") $hasil=$this->km($this->angka); elseif ($this->op=="us") $hasil=$this->us($this->angka); elseif ($this->op=="fmi") $hasil=$this->fmi($this->angka); elseif ($this->op=="fm") $hasil=$this->fm($this->angka); elseif ($this->op=="angs") $hasil=$this->angs($this->angka); elseif ($this->op=="tc") $hasil=$this->tc($this->angka); elseif ($this->op=="pc") $hasil=$this->pc($this->angka); echo $hasil; } function inc ($masuk){ $hsl=$masuk*39.37; return $hsl; } function cm($masuk){ $hsl=$masuk*100; return $hsl; } function ft ($masuk){ $hsl=$masuk*3.28; return $hsl; } function mil ($masuk){ $hsl=$masuk*3.28/5280; return $hsl; } function km ($masuk){ $hsl=$masuk/1000; return $hsl; } function US ($masuk){ $hsl=$masuk*3.28/6076; return $hsl; } function fmi ($masuk){ $hsl=$masuk*10; return $hsl; } function fm ($masuk){ $hsl=$masuk*10; return $hsl; } function angs ($masuk){ $hsl=$masuk*10; return $hsl; } function tc ($masuk){ $hsl=$panjang/946*10; return $hsl; } function pc ($masuk){ $hsl=$panjang/3.09*10; return $hsl; } } ?> <file_sep>/proses.php <?php include "class.php"; $vhitung= new konversi; $vhitung->angka=$_POST['angka']; $vhitung->op=$_POST['cmbop']; $vhitung->utama(); ?><file_sep>/form.php <?php echo "</BR><div align ='center'><font color ='#CC0033' size='5'>Proses Konversi Satuan Panjang dari meter</font></div></BR>" ?> <FORM name="frm_hitung" action="proses.php" method="post"> <input type="text" name="angka"/> <select name="cmbop"> <option value="inc">inc</option> <option value="cm">cm</option> <option value="mil">mil</option> <option value="ft">ft</option> <option value="km">km</option> <option value="us">us</option> <option value="fmi">fmi</option> <option value="fm">fm</option> <option value="angs">angs</option> <option value="tc">tc</option> <option value="pc">pc</option> </select> <input type="submit" value="="/> </FORM>
d94fff5162a0da438614acaafb98b415d9e54fee
[ "Markdown", "PHP" ]
4
Markdown
kresnaba/konversi_panjang
1e82722ede7e66b9305b1b106737938f2274fce6
3312896c1a6bee15e8b05ca37140f42cdc37e60e
refs/heads/master
<file_sep># MobCategories Brief Overview: The application can consist of two pages: - List page: - The list page should contain a list with products categorized per category. - Each item in the list should display full name and thumbnail of the image (if present). - Clicking an item will cause the application to open the detail view. - Detail page: The detail page should display the following information of the selected product: - Name of the product. - Image with bigger view. - Price of the product. # Language - Kotlin ## Architecture Android Model-View-ViewModel (MVVM) design architecture with the Repository pattern. # Libraries Used - `Koin` - Dependency injection - `Retrofit` - Making network request - `Coroutines` - Asynchronous processing - `Glide` - Image Loading - `Mockito` - Mocking dependencies during `unit test` ## Tests This app was built with testability in mind. ## Extras - Data was obtained from `http://mobcategories.s3-website-eu-west-1.amazonaws.com`<file_sep>package com.afolayanseyi.mobcategories.network import com.afolayanseyi.mobcategories.data.model.MobCategory import kotlinx.coroutines.Deferred import retrofit2.http.GET interface NetworkApi { @GET("/") fun fetchMobCategories(): Deferred<List<MobCategory>> }<file_sep>package com.afolayanseyi.mobcategories.ui.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.afolayanseyi.mobcategories.R import com.afolayanseyi.mobcategories.data.ProductClickListener import com.afolayanseyi.mobcategories.data.adapter.MobCategoryAdapter import com.afolayanseyi.mobcategories.data.model.Product import com.afolayanseyi.mobcategories.data.model.Result import com.afolayanseyi.mobcategories.databinding.FragmentProductListBinding import com.afolayanseyi.mobcategories.ui.ProductListViewModel import com.afolayanseyi.mobcategories.utils.PRODUCT_ARGS_EXTRA import com.google.android.material.snackbar.Snackbar import org.koin.androidx.viewmodel.ext.android.viewModel class ProductListFragment : Fragment(), ProductClickListener { private val productListViewModel: ProductListViewModel by viewModel() private lateinit var fragmentProductListBinding: FragmentProductListBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { fragmentProductListBinding = DataBindingUtil .inflate(inflater, R.layout.fragment_product_list, container, false) fragmentProductListBinding.viewModel = productListViewModel productListViewModel.mobCategoriesLiveData.observe(this, Observer { result -> when (result) { is Result.Loading -> { showProgress() } is Result.Success -> { hideProgress() fragmentProductListBinding.recycler.apply { val categoriesList = result.data adapter = MobCategoryAdapter( categoriesList, this@ProductListFragment ) layoutManager = LinearLayoutManager(requireContext()) } } is Result.Error -> { hideProgress() showErrorMessage(result.exception) } } }) return fragmentProductListBinding.root } private fun showErrorMessage(exception: Exception) { val message = if (exception.message.isNullOrEmpty()) { getString(R.string.error_message) } else { exception.message!! } val snackBar = Snackbar.make(fragmentProductListBinding.recycler, message, Snackbar.LENGTH_LONG) snackBar.setAction(getString(R.string.retry_text)) { productListViewModel.getMobCategories() } snackBar.show() } private fun hideProgress() { fragmentProductListBinding.progressBar.visibility = View.GONE } private fun showProgress() { fragmentProductListBinding.progressBar.visibility = View.VISIBLE } override fun onProductClick(product: Product) { val bundle = Bundle().apply { putParcelable(PRODUCT_ARGS_EXTRA, product) } findNavController().navigate( R.id.action_productListFragment_to_productDetailFragment, bundle ) } } <file_sep>package com.afolayanseyi.mobcategories.utils const val BASE_API_URL = "http://mobcategories.s3-website-eu-west-1.amazonaws.com" const val PRODUCT_ARGS_EXTRA = "PRODUCT_ARGS_EXTRA"<file_sep>package com.afolayanseyi.mobcategories.ui.main import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import com.afolayanseyi.mobcategories.R class MainActivity : AppCompatActivity() { private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navController = Navigation.findNavController(this, R.id.navHostFragment) NavigationUI.setupActionBarWithNavController(this, navController, null) appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build() } override fun onSupportNavigateUp(): Boolean { return NavigationUI.navigateUp(navController, appBarConfiguration) } } <file_sep>package com.afolayanseyi.mobcategories.data import com.afolayanseyi.mobcategories.data.model.MobCategory import com.afolayanseyi.mobcategories.network.NetworkApi import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class MobCategoriesRepositoryImpl(private val networkApi: NetworkApi) : MobCategoriesRepository { override suspend fun getMobCategoriesAsync(): Deferred<List<MobCategory>> = withContext(Dispatchers.IO) { networkApi.fetchMobCategories() } }<file_sep>package com.afolayanseyi.mobcategories.di import com.afolayanseyi.mobcategories.ui.ProductListViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { ProductListViewModel(get()) } }<file_sep>package com.afolayanseyi.mobcategories.ui import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.afolayanseyi.mobcategories.LiveDataTestUtil import com.afolayanseyi.mobcategories.data.MobCategoriesRepositoryImpl import com.afolayanseyi.mobcategories.data.model.Result import com.afolayanseyi.mobcategories.utils.testCategory import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import kotlinx.coroutines.* import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.* import org.mockito.MockitoAnnotations @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class ProductListViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() private val mobCategoriesRepository: MobCategoriesRepositoryImpl = mock() private lateinit var viewModel: ProductListViewModel private val mainThreadSurrogate = newSingleThreadContext("UI thread") @Before fun setUp() { MockitoAnnotations.initMocks(this) Dispatchers.setMain(mainThreadSurrogate) viewModel = ProductListViewModel(mobCategoriesRepository) } @After fun tearDown() { Dispatchers.resetMain() mainThreadSurrogate.close() } @Test fun test_retrieveSummaryData() { viewModel.getMobCategories() Assert.assertNotNull(viewModel.mobCategoriesLiveData) } @Test fun testViewModel_getMobCategories_forSuccess() { runBlocking { launch(Dispatchers.Main) { val expectedResult = async { listOf(testCategory) } whenever(mobCategoriesRepository.getMobCategoriesAsync()).thenReturn(expectedResult) viewModel.getMobCategories() // wait till loading is over delay(1000) val liveDataValue = LiveDataTestUtil.getValue(viewModel.mobCategoriesLiveData) Assert.assertNotNull(liveDataValue) Assert.assertEquals(liveDataValue, Result.Success(listOf(testCategory))) } } } @Test fun testViewModel_loading() { runBlocking { launch(Dispatchers.Main) { viewModel.getMobCategories() val liveDataValue = LiveDataTestUtil.getValue(viewModel.mobCategoriesLiveData) Assert.assertNotNull(liveDataValue) Assert.assertEquals(liveDataValue, Result.Loading) } } } }<file_sep>package com.afolayanseyi.mobcategories.di import com.afolayanseyi.mobcategories.data.MobCategoriesRepository import com.afolayanseyi.mobcategories.data.MobCategoriesRepositoryImpl import com.afolayanseyi.mobcategories.network.NetworkApi import com.afolayanseyi.mobcategories.utils.GlideImageLoader import com.afolayanseyi.mobcategories.utils.ImageLoader import com.afolayanseyi.mobcategories.utils.BASE_API_URL import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val appModule = module { single { createRetrofit(createOkHttpClient()) } single { createNetworkApi(get()) } } val repositoryModule = module { single { MobCategoriesRepositoryImpl(get()) as MobCategoriesRepository } } val imageLoader = module { single { GlideImageLoader() as ImageLoader } } fun createOkHttpClient(): OkHttpClient { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor).build() } fun createRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .baseUrl(BASE_API_URL) .client(okHttpClient) .build() } fun createNetworkApi(retrofit: Retrofit): NetworkApi { return retrofit.create(NetworkApi::class.java) }<file_sep>package com.afolayanseyi.mobcategories.utils import android.widget.ImageView import com.afolayanseyi.mobcategories.R import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy class GlideImageLoader : ImageLoader { override fun loadImage(imageView: ImageView, url: String) { val imageUrl = BASE_API_URL.plus(url) Glide.with(imageView) .load(imageUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .error(R.drawable.ic_empty_product) .placeholder(R.drawable.ic_empty_product) .into(imageView) } }<file_sep>package com.afolayanseyi.mobcategories import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import com.afolayanseyi.mobcategories.ui.main.ProductListFragment import org.hamcrest.CoreMatchers.not import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ProductListFragmentTest { @Test fun testProductListFragmentHasRecyclerView() { launchFragmentInContainer<ProductListFragment>() onView(withId(R.id.recycler)).check(matches(isDisplayed())) } @Test fun testProductListFragmentHasProgressBar() { launchFragmentInContainer<ProductListFragment>() onView(withId(R.id.progressBar)).check(matches(isDisplayed())) } @Test fun testHasProgressBar_canDismissAfterListIsLoaded() { launchFragmentInContainer<ProductListFragment>() onView(withId(R.id.progressBar)).check(matches(isDisplayed())) Thread.sleep(5000) onView(withId(R.id.progressBar)).check(matches(not(isDisplayed()))) } }<file_sep>package com.afolayanseyi.mobcategories.ui import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.afolayanseyi.mobcategories.data.MobCategoriesRepository import com.afolayanseyi.mobcategories.data.model.MobCategory import com.afolayanseyi.mobcategories.data.model.Result import kotlinx.coroutines.launch class ProductListViewModel( private val repository: MobCategoriesRepository ) : ViewModel() { val mobCategoriesLiveData = MutableLiveData<Result<List<MobCategory>>>() init { getMobCategories() } fun getMobCategories() { mobCategoriesLiveData.postValue(Result.Loading) viewModelScope.launch { try { val categories = repository.getMobCategoriesAsync().await() mobCategoriesLiveData.postValue(Result.Success(categories)) } catch (exception: Exception) { mobCategoriesLiveData.postValue(Result.Error(exception)) } } } }<file_sep>package com.afolayanseyi.mobcategories.app import android.app.Application import com.afolayanseyi.mobcategories.di.appModule import com.afolayanseyi.mobcategories.di.imageLoader import com.afolayanseyi.mobcategories.di.repositoryModule import com.afolayanseyi.mobcategories.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin class MobCategoryApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MobCategoryApplication) androidLogger() modules(listOf(appModule, imageLoader, repositoryModule, viewModelModule)) } } } <file_sep>package com.afolayanseyi.mobcategories.data.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize data class MobCategory( var id: String? = null, var name: String? = null, var description: String? = null, var products: List<Product> = listOf() ) @Parcelize data class Product( var id: String? = null, var categoryId: String? = null, var name: String? = null, var url: String? = null, var description: String? = null, var salePrice: SalePrice? = null ): Parcelable @Parcelize data class SalePrice( var amount: String? = null, var currency: String? = null ): Parcelable { fun joinCurrencyAndAmount() = currency.plus(amount) } <file_sep>package com.afolayanseyi.mobcategories.data.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.afolayanseyi.mobcategories.data.model.Product import com.afolayanseyi.mobcategories.databinding.LayoutSingleProductItemBinding class ProductAdapter(private val productsList: List<Product>, private val onItemClick: ((Product) -> Unit)) : RecyclerView.Adapter<ProductAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = LayoutSingleProductItemBinding.inflate(layoutInflater, parent, false) return ViewHolder( itemBinding ) } override fun getItemCount(): Int { return productsList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val product = productsList[position] holder.apply { bind(createOnClickListener(product), product) } } private fun createOnClickListener(product: Product): View.OnClickListener { return View.OnClickListener { onItemClick.invoke(product) } } class ViewHolder(private val itemBinding: LayoutSingleProductItemBinding) : RecyclerView.ViewHolder(itemBinding.root) { fun bind(listener: View.OnClickListener, product: Product) { itemBinding.clickListener = listener itemBinding.product = product } } } <file_sep>package com.afolayanseyi.mobcategories import android.content.pm.PackageInfo import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.afolayanseyi.mobcategories.app.MobCategoryApplication import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.regex.Pattern @RunWith(AndroidJUnit4::class) class MobCategoryApplicationTest { private lateinit var application: MobCategoryApplication @Before @Throws(Exception::class) fun setUp() { application = MobCategoryApplication() } @Test fun useAppContext() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.afolayanseyi.mobcategories", appContext.packageName) } @Throws(Exception::class) fun testCorrectVersion() { val info: PackageInfo = application.packageManager.getPackageInfo(application.packageName, 0) assertNotNull(info) assertTrue(Pattern.matches("\\d\\.\\d", info.versionName)) } } <file_sep>package com.afolayanseyi.mobcategories.utils import com.afolayanseyi.mobcategories.data.model.MobCategory import com.afolayanseyi.mobcategories.data.model.Product import com.afolayanseyi.mobcategories.data.model.SalePrice val testProduct: Product get() = Product( id = "1", categoryId = "36802", name = "Bread", url = "/Bread.jpg", description = "", salePrice = salePrice ) val salePrice = SalePrice ( amount = "0.81", currency = "EUR" ) val testCategory = MobCategory ( id = "36802", name = "Food", description = "", products = listOf(testProduct) ) <file_sep>package com.afolayanseyi.mobcategories.data import com.afolayanseyi.mobcategories.network.NetworkApi import com.afolayanseyi.mobcategories.utils.testCategory import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import kotlinx.coroutines.* import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.MockitoAnnotations class MobCategoriesRepositoryImplTest { lateinit var repositoryImpl: MobCategoriesRepositoryImpl private val networkApi: NetworkApi = mock() private val mainThreadSurrogate = newSingleThreadContext("UI thread") @Before fun setUp(){ MockitoAnnotations.initMocks(this) Dispatchers.setMain(mainThreadSurrogate) repositoryImpl = MobCategoriesRepositoryImpl(networkApi) } @After fun tearDown() { Dispatchers.resetMain() mainThreadSurrogate.close() } @Test fun test_fetchCategories_forSuccess(){ runBlocking { launch(Dispatchers.Main) { val expectedResult = async { listOf(testCategory) } whenever(networkApi.fetchMobCategories()).thenReturn(expectedResult) val mobCategoriesAsync = repositoryImpl.getMobCategoriesAsync() verify(networkApi).fetchMobCategories() assert(mobCategoriesAsync.isCompleted) } } } }<file_sep>package com.afolayanseyi.mobcategories.ui.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.afolayanseyi.mobcategories.R import com.afolayanseyi.mobcategories.data.model.Product import com.afolayanseyi.mobcategories.databinding.FragmentProductDetailBinding import com.afolayanseyi.mobcategories.utils.PRODUCT_ARGS_EXTRA class ProductDetailFragment : Fragment() { private lateinit var fragmentProductDetailBinding: FragmentProductDetailBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { fragmentProductDetailBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_product_detail, container, false) return fragmentProductDetailBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val product = it.getParcelable<Product>(PRODUCT_ARGS_EXTRA)!! fragmentProductDetailBinding.product = product } } } <file_sep>package com.afolayanseyi.mobcategories.ui.main import android.os.Bundle import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.afolayanseyi.mobcategories.R import com.afolayanseyi.mobcategories.utils.PRODUCT_ARGS_EXTRA import com.afolayanseyi.mobcategories.utils.testProduct import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ProductDetailFragmentTest { @Rule @JvmField var mActivityTestRule = ActivityTestRule(MainActivity::class.java) @Before fun setUp() { val fragmentArgs = Bundle().apply { putParcelable(PRODUCT_ARGS_EXTRA, testProduct) } launchFragmentInContainer<ProductDetailFragment>(fragmentArgs = fragmentArgs) } @Test fun testProductDetailFragment() { onView(withId(R.id.productImageView)).check(matches(isDisplayed())) onView(withId(R.id.productNameTextView)).check(matches(withText(testProduct.name))) onView(withId(R.id.productPriceTextView)).check(matches(withText(testProduct.salePrice!!.joinCurrencyAndAmount()))) } @Test fun productDetailsFragment_mainViewsPresent() { onView(withId(R.id.productImageView)).check(matches(isDisplayed())) onView(withId(R.id.productNameTextView)).check(matches(isDisplayed())) onView(withId(R.id.productPriceTextView)).check(matches(isDisplayed())) } }<file_sep>package com.afolayanseyi.mobcategories.ui.main import android.view.View import androidx.fragment.app.testing.launchFragmentInContainer import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.matcher.ViewMatchers.assertThat import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.rule.ActivityTestRule import com.afolayanseyi.mobcategories.R import junit.framework.Assert.assertNotNull import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.Matchers.greaterThan import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class MainActivityTest { @get:Rule var rule = ActivityTestRule(MainActivity::class.java) @Test @Throws(Exception::class) fun ensureRecyclerViewIsPresent() { val activity = rule.activity launchFragmentInContainer<ProductListFragment>() val viewById: View = activity.findViewById(R.id.recycler) assertThat(viewById, notNullValue()) assertThat(viewById, instanceOf(RecyclerView::class.java)) val recyclerView: RecyclerView = viewById as RecyclerView assertNotNull(recyclerView) //wait till list is loaded Thread.sleep(10000) val adapter: RecyclerView.Adapter<*>? = recyclerView.adapter assertThat(adapter, instanceOf(RecyclerView.Adapter::class.java)) //confirm that the list of categories is more than 1 assertThat(adapter!!.itemCount, greaterThan(1)) } }<file_sep>package com.afolayanseyi.mobcategories.data import com.afolayanseyi.mobcategories.data.model.MobCategory import kotlinx.coroutines.Deferred interface MobCategoriesRepository { suspend fun getMobCategoriesAsync(): Deferred<List<MobCategory>> }<file_sep>package com.afolayanseyi.mobcategories.data import com.afolayanseyi.mobcategories.data.model.Product interface ProductClickListener { fun onProductClick(product: Product) }<file_sep>package com.afolayanseyi.mobcategories.data.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.afolayanseyi.mobcategories.data.ProductClickListener import com.afolayanseyi.mobcategories.data.model.MobCategory import com.afolayanseyi.mobcategories.databinding.LayoutCategoriesListBinding class MobCategoryAdapter(private val categoriesList: List<MobCategory>, private val productClickListener: ProductClickListener) : RecyclerView.Adapter<MobCategoryAdapter.CategoryViewHolder>() { override fun getItemCount(): Int = categoriesList.size override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): CategoryViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = LayoutCategoriesListBinding.inflate(layoutInflater, parent, false) return CategoryViewHolder( itemBinding ) } override fun onBindViewHolder( holder: CategoryViewHolder, position: Int ) { holder.bind(categoriesList[position]) holder.productClickListener = productClickListener } class CategoryViewHolder(private val itemBinding: LayoutCategoriesListBinding) : RecyclerView.ViewHolder(itemBinding.root) { lateinit var productClickListener: ProductClickListener fun bind(mobCategory: MobCategory) { itemBinding.category = mobCategory val linearLayoutManager = LinearLayoutManager(itemBinding.root.context, LinearLayoutManager.VERTICAL, false) itemBinding.productsRecyclerView.layoutManager = linearLayoutManager val productAdapter = ProductAdapter( mobCategory.products ) { product -> productClickListener.onProductClick(product) } itemBinding.productsRecyclerView.adapter = productAdapter } } }<file_sep>package com.afolayanseyi.mobcategories.utils import android.widget.ImageView import android.widget.TextView import androidx.databinding.BindingAdapter import com.afolayanseyi.mobcategories.data.model.SalePrice @BindingAdapter("productImage") fun loadImage(imageView: ImageView, url: String) { GlideImageLoader().loadImage(imageView, url) } @BindingAdapter("price") fun loadPrice(priceTextView: TextView, salePrice: SalePrice) = salePrice.run { priceTextView.text = joinCurrencyAndAmount() }
d111d11b3fde95803532df04be10b372b89b81b3
[ "Markdown", "Kotlin" ]
25
Markdown
Afolayan/MobCategories
de0474bc2fe2969bafc2f6843779355f53c332f7
6139ee40ed61b9a35feb73992daeda1dc198ccee
refs/heads/master
<repo_name>guyi02/Server-graphql<file_sep>/src/Resolvers/Query.js import jwt from "jsonwebtoken"; export default { getUsers: async (root, {}, { userToken, User }) => { const [bearer, token] = userToken.split(" "); if (!token) { throw new Error("Você não possui um token"); } jwt.verify(token, "my<PASSWORD>", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); const users = await User.find({}); return users; }, getUser: async (root, { id }, { userToken, User }) => { const [bearer, token] = userToken.split(" "); if (!token) { throw new Error("Você não possui um token"); } jwt.verify(token, "mysecret", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); const user = await User.findById(id); return user; }, getTeams: async (root, {}, { Team }) => await Team.find({}).sort({ team_name: 1 }), }; <file_sep>/server.js import { GraphQLServer } from "graphql-yoga"; import mongoose from "mongoose"; import { importSchema } from "graphql-import"; import resolvers from "./src/Resolvers/index"; require("dotenv").config(); mongoose.connect(process.env.MONGO_URI, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, }); // Models import User from "./src/Models/User"; import Player from "./src/Models/Player"; import Team from "./src/Models/Team"; // linha 1 recebe os schemas //linha 2 recebe os resolvers ou controllers const server = new GraphQLServer({ typeDefs: importSchema("./src/Schema/index.graphql"), resolvers, context: ({ request, response, connection }) => { const userToken = request.headers.authorization; return { userToken, User, Player, Team, }; }, }); const options = { port: 4000 }; server.start(options, () => console.log("rodando servidor na porta: " + options.port), ); <file_sep>/src/Models/Player.js import mongoose from "mongoose"; const PlayerSchema = new mongoose.Schema({ name: String, surname: String, play_for_team: { type: mongoose.Schema.Types.ObjectId, ref: "Team", default: null, }, nick_name: { type: String, unique: true, }, height: Number, weight: Number, foot: String, phone: String, profile_img: String, profile_video: String, description: String, cpf: { type: String, required: true, unique: true, }, habilities: { pace: Number, drible: Number, defense: Number, shoot: Number, pass: Number, physic: Number, }, diferencials: { good: String, very_good: String, excelent: String, }, avaliable_days: [ { _id: false, day: String, }, ], avaliable_hours: [ { _id: false, hour: String, }, ], goals: Number, position: String, position_secondary: String, available: { type: Boolean, default: false, }, created_at: { type: Date, default: Date.now, }, }); export default mongoose.model("Player", PlayerSchema); <file_sep>/src/Models/Team.js import mongoose from "mongoose"; const TeamSchema = new mongoose.Schema({ team_name: { type: String, required: true, unique: true }, team_image: { type: String, }, players: [{ type: mongoose.Schema.Types.ObjectId, ref: "Player", default: null }], month_payment: [{ _id: { type: mongoose.Schema.ObjectId, auto: true }, player_id: { type: mongoose.Schema.Types.ObjectId, ref: "Player" }, player_name: {type: String}, value: { type: Number }, created_at: { type: Date, default: Date.now } }], spending: [{ _id: { type: mongoose.Schema.ObjectId, auto: true }, value: { type: Number }, description: { type: String }, created_at: { type: Date, default: Date.now }, }], profit: [{ _id: { type: mongoose.Schema.ObjectId, auto: true }, value: { type: Number }, description: { type: String }, created_at: { type: Date, default: Date.now }, }], find_player: { type: Boolean, default: false }, find_positions: [{ _id: false, position: {type: String} }], created_at: { type: Date, }, }); export default mongoose.model("Team", TeamSchema); <file_sep>/src/Resolvers/Mutation.js import jwt from "jsonwebtoken"; import bcrypt from "bcryptjs"; import cloudinary from "cloudinary"; require("dotenv").config(); export default { // USER createUser: async (root, { dados }, { User }) => { const { email, password, confirmPassword, is_team, players, team, pro_user, trial, } = dados; const verifiUser = await User.findOne({ email }); if (verifiUser) { throw new Error("Email já cadastrado"); } if (password !== confirmPassword) { throw new Error("Senhas não conferem"); } try { const user = await new User({ email, password, is_team, players, team, pro_user, trial, }).save(); return user; } catch (error) { return error; } }, updateUser: async (root, { dados }, { userToken, User }) => { const [bearer, token] = userToken.split(" "); jwt.verify(token, "mysecret", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); try { const userUpdated = await User.findByIdAndUpdate( { _id: dados.id }, { $set: dados }, { new: true } ); return userUpdated; } catch (error) { return error; } }, deleteUser: async (root, { _id }, { userToken, User }) => { const [bearer, token] = userToken.split(" "); jwt.verify(token, "mysecret", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); const verifiUser = await User.findOne({ _id }); if (!verifiUser) { throw new Error("Usuário não existente"); } try { await User.findByIdAndDelete({ _id }); return { message: "Deletado com sucesso!", }; } catch (error) { return error; } }, // AUTH login: async (root, { dados: { email, password } }, { User }) => { const user = await User.findOne({ email }); if (!user) { throw new Error("Usuário não cadastrado"); } const passwordMatch = await bcrypt.compare(password, user.password); if (!passwordMatch) { throw new Error("Senha inválida"); } const responseToken = jwt.sign( { id: user.id, username: user.email, }, "mysecret", { expiresIn: "1d", // token will expire in 15days } ); return { token: `Bearer ${responseToken}`, user, logged: true, }; }, refreshToken: async (root, { dados: { token } }) => { const [bearer, mytoken] = token.split(" "); try { const tryDecode = await jwt.verify(mytoken, "mysecret"); return { token, logged: true, }; } catch (error) { throw new Error("Token inválido!"); } }, // PLAYER RegisterPlayer: async (root, { dados }, { userToken, Player }) => { const [bearer, token] = userToken.split(" "); if (!token) throw new Error("Usuário não autenticado"); if (!token) { throw new Error("Você não possui um token"); } jwt.verify(token, "mysecret", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); const verifiUser = await Player.findOne({ cpf: dados.cpf }); if (verifiUser) { throw new Error("Usuário já cadastrado com este CPF!"); } const objArgs = JSON.parse(JSON.stringify(dados)); try { const player = await new Player(objArgs).save(); return player; } catch (error) { return error; } }, // TEAM RegisterTeam: async (root, { dados }, { userToken, Team }) => { const [bearer, token] = userToken.split(" "); if (!token) throw new Error("Usuário não autenticado"); jwt.verify(token, "<PASSWORD>", (err, decode) => { if (err || !decode) { throw new Error("Usuário não autenticado"); } }); const objArgs = JSON.parse(JSON.stringify(dados)); try { const team = await new Team(objArgs).save(); return team; } catch (error) { if (error.code === 11000) throw new Error("Já existe time com este nome cadastrado"); } }, singleUpload: async (root, { file }) => { cloudinary.config({ cloud_name: process.env.CLOUD_NAME, api_key: process.env.API_KEY, api_secret: process.env.API_SECRET, }); const { filename, createReadStream, mimetype, encoding } = await file; const uploadToCloudinary = () => { return new Promise((resolve, reject) => { const uploadStream = cloudinary.v2.uploader.upload_stream( { folder: "app_assets", public_id: filename.split(".").slice(0, -1).join("."), invalidate: true, }, (error, result) => { if (result) { resolve(result); } else { reject(error); } } ); const stream = createReadStream(); stream.pipe(uploadStream); }); }; const result = await uploadToCloudinary(); return { filename, mimetype, encoding, uri: result.url, }; }, }; <file_sep>/src/Models/Match.js import mongoose from "mongoose"; const MatchSchema = new mongoose.Schema({ team_home: { team: { type: mongoose.Schema.Types.ObjectId, ref: "Team", required: true }, players: [ { type: mongoose.Schema.Types.ObjectId, ref: "Player" } ], goals: Number, cards: Number }, team_away: { team: { type: mongoose.Schema.Types.ObjectId, ref: "Team", required: true }, players: [ { type: mongoose.Schema.Types.ObjectId, ref: "Player" } ] }, place: { address: String, reference: String, }, game_start_in: String, finished: Boolean, created_at: { type: Date, default: Date.now }, }); export default mongoose.model("Match", MatchSchema); <file_sep>/src/Models/User.js import mongoose from "mongoose"; import bcrypt from 'bcryptjs' const UserSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true }, is_team: { type: Boolean, default: false }, team: { type: mongoose.Schema.Types.ObjectId, ref: 'Team' }, players: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Player' } ], pro_user: { active: { type: Boolean, default: false }, start_in: { type: Date } }, trial: { is_trial: { type: Boolean, default: false }, start_in: { type: Date }, } }); UserSchema.pre('save', async function (next) { if (!this.isModified('password')) { return next() } this.password = await bcrypt.hash(this.password, 8); }) export default mongoose.model("User", UserSchema);
504a82729bc98bb42d87d7d99e2d651190ae1936
[ "JavaScript" ]
7
JavaScript
guyi02/Server-graphql
bf491d51bdf7d7dc73d37cb568dce661f9de7581
a069514bd2521c935ec6220a561732c318d55c63
refs/heads/master
<file_sep>function produceDrivingRange(blockRange) { return function(start, end) { const startingBlock = parseInt(start); const endingBlock = parseInt(end); let distance = Math.abs(endingBlock - startingBlock); let numberOfBlocks = blockRange - distance; if (numberOfBlocks < 0) { return `${Math.abs(numberOfBlocks)} blocks out of range`; } else { return `within range by ${numberOfBlocks}`; } }; }; function produceTipCalculator(percent) { return function(amount) { return amount * percent; }; }; function createDriver() { let driverId = 0; return class { constructor(name) { this.name = name; this.id = ++driverId; } }; };
e405329c698a0c744c188361dbd6008d500e215e
[ "JavaScript" ]
1
JavaScript
MargaritaKhodzka/js-advanced-scope-closures-lab-v-000
b358a0739a4b8b6d55dab4dd48b8b04eae34b799
759c1ef7807b2509679597dc0bbd7991f6c9470d
refs/heads/master
<file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-11-19 * * @file TinyCondition.h * * @remark * */ #ifndef __TINY_CONDITION_H__ #define __TINY_CONDITION_H__ #include "tiny_base.h" #include "TinyMutex.h" TINY_BEGIN_DECLS #ifdef _WIN32 typedef HANDLE ct_cond_t; #else /* Linux */ typedef pthread_cond_t ct_cond_t; #endif /* _WIN32 */ typedef struct _TinyCondition { TinyMutex mutex; ct_cond_t job; bool is_ready; } TinyCondition; TinyCondition * TinyCondition_New(void); TinyRet TinyCondition_Construct(TinyCondition *thiz); TinyRet TinyCondition_Dispose(TinyCondition *thiz); void TinyCondition_Delete(TinyCondition *thiz); bool TinyCondition_Wait(TinyCondition *thiz); bool TinyCondition_NotifyOne(TinyCondition *thiz); bool TinyCondition_NotifyAll(TinyCondition *thiz); TINY_END_DECLS #endif /* __TINY_CONDITION_H__ */ <file_sep>#----------------------------------------------------------------------------- # # build # #----------------------------------------------------------------------------- SET(SRC stream_api.h util.h StreamSender.h StreamReceiver.h rtp.c util.c StreamSender.c StreamReceiver.c ) #---------------------- #---------------------------------------------------------------------------- # shared library #---------------------------------------------------------------------------- ADD_LIBRARY(stream_shared SHARED ${SRC}) SET_TARGET_PROPERTIES(stream_shared PROPERTIES OUTPUT_NAME "stream") SET_TARGET_PROPERTIES(stream_shared PROPERTIES LINKER_LANGUAGE C) TARGET_LINK_LIBRARIES(stream_shared ${SRTP_LIB} ${OS_LIB} tiny_static) #----------------------------------------------------------------------------- # # test # #----------------------------------------------------------------------------- ADD_SUBDIRECTORY(test)<file_sep>#----------------------------------------------------------------------------- # # build # #----------------------------------------------------------------------------- ADD_EXECUTABLE(test_receiver receiver.c) SET_TARGET_PROPERTIES(test_receiver PROPERTIES LINKER_LANGUAGE C) TARGET_LINK_LIBRARIES(test_receiver stream_shared ${OS_LIB}) ADD_EXECUTABLE(test_sender sender.c) SET_TARGET_PROPERTIES(test_sender PROPERTIES LINKER_LANGUAGE C) TARGET_LINK_LIBRARIES(test_sender stream_shared ${OS_LIB}) <file_sep>#APP_ABI := armeabi armeabi-v7a mips x86 APP_ABI := armeabi #APP_API := arm64-v8a #APP_API := all #APP_API := x86 APP_PLATFORM := android-21 <file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-11-19 * * @file TinySemaphore.h * * @remark * */ #ifndef __TINY_SEMAPHORE_H__ #define __TINY_SEMAPHORE_H__ #include "tiny_base.h" TINY_BEGIN_DECLS #if (defined __LINUX__) || (defined __ANDROID__) #include <semaphore.h> #endif #ifdef __MAC_OSX__ #include <semaphore.h> #include <fcntl.h> #include <limits.h> #endif #ifdef _WIN32 #define MAX_SEM_SIZE 128 typedef HANDLE ct_sem_t; #endif /* _WIN32 */ #if (defined __LINUX__) || (defined __ANDROID__) typedef sem_t ct_sem_t; #endif #ifdef __MAC_OSX__ typedef struct _ct_sem_t { char name[PATH_MAX + 1]; sem_t * sem; } ct_sem_t; #endif typedef struct _TinySemaphore { ct_sem_t sem; } TinySemaphore; TinySemaphore * TinySemaphore_New(void); TinyRet TinySemaphore_Construct(TinySemaphore *thiz); TinyRet TinySemaphore_Dispose(TinySemaphore *thiz); void TinySemaphore_Delete(TinySemaphore *thiz); bool TinySemaphore_Wait(TinySemaphore *thiz); bool TinySemaphore_Post(TinySemaphore *thiz); TINY_END_DECLS #endif /* __TINY_SEMAPHORE_H__ */ <file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-11-19 * * @file TinyCondition.c * * @remark * */ #include "TinyCondition.h" #include "tiny_memory.h" #include "tiny_log.h" #define TAG "TinyCondition" TinyCondition * TinyCondition_New(void) { TinyCondition *thiz = NULL; do { TinyRet ret = TINY_RET_OK; thiz = (TinyCondition *)tiny_malloc(sizeof(TinyCondition)); if (thiz == NULL) { break; } ret = TinyCondition_Construct(thiz); if (RET_FAILED(ret)) { TinyCondition_Delete(thiz); thiz = NULL; break; } } while (0); return thiz; } TinyRet TinyCondition_Construct(TinyCondition *thiz) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); do { memset(thiz, 0, sizeof(TinyCondition)); thiz->is_ready = false; ret = TinyMutex_Construct(&thiz->mutex); if (RET_FAILED(ret)) { break; } #ifdef _WIN32 thiz->job = CreateEvent(NULL, FALSE, FALSE, NULL); if (thiz->job == NULL) { LOG_E(TAG, "TinyCondition_Construct: CreateEvent failed"); ret = TINY_RET_E_INTERNAL; break; } #else if (pthread_cond_init(&thiz->job, NULL) != 0) { LOG_E(TAG, "TinyCondition_Construct: pthread_cond_init failed"); ret = TINY_RET_E_INTERNAL; break; } #endif ret = TINY_RET_OK; } while (false); return ret; } TinyRet TinyCondition_Dispose(TinyCondition *thiz) { RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); TinyMutex_Dispose(&thiz->mutex); #ifdef _WIN32 if (thiz->job) { CloseHandle(thiz->job); } #else pthread_cond_destroy(&thiz->job); #endif return TINY_RET_OK; } void TinyCondition_Delete(TinyCondition *thiz) { RETURN_IF_FAIL(thiz); TinyCondition_NotifyAll(thiz); TinyCondition_Dispose(thiz); tiny_free(thiz); } bool TinyCondition_Wait(TinyCondition *thiz) { bool result = false; RETURN_VAL_IF_FAIL(thiz, false); #ifdef _WIN32 switch (WaitForSingleObject(thiz->job, INFINITE)) { case WAIT_OBJECT_0: result = true; break; /* ָ���Ķ�����һ��������󣬸ö���û�б�ӵ�иö�����߳����߳̽���ǰ�ͷš� ������������Ȩ��ͬ��������øú������̡߳�����������ó�Ϊ���ź�״̬��*/ case WAIT_ABANDONED: result = false; break; case WAIT_TIMEOUT: result = false; break; default: result = false; break; } #else result = true; TinyMutex_Lock(&thiz->mutex); thiz->is_ready = false; while (thiz->is_ready == false) { pthread_cond_wait(&thiz->job, &(thiz->mutex.mutex)); } TinyMutex_Unlock(&thiz->mutex); #endif return result; } bool TinyCondition_NotifyOne(TinyCondition *thiz) { bool ret = true; RETURN_VAL_IF_FAIL(thiz, false); #ifdef _WIN32 SetEvent(thiz->job); #else TinyMutex_Lock(&thiz->mutex); do { thiz->is_ready = true; if (pthread_cond_signal(&thiz->job) != 0) { ret = false; break; } ret = true; } while (0); TinyMutex_Unlock(&thiz->mutex); #endif return ret; } bool TinyCondition_NotifyAll(TinyCondition *thiz) { bool ret = true; RETURN_VAL_IF_FAIL(thiz, false); #ifdef _WIN32 SetEvent(thiz->job); #else TinyMutex_Lock(&thiz->mutex); do { thiz->is_ready = true; if (pthread_cond_broadcast(&thiz->job) != 0) { ret = false; break; } ret = true; } while (0); TinyMutex_Unlock(&thiz->mutex); #endif return ret; } <file_sep>#---------------------------------------------------------------------------- # <EMAIL> # # 2011-6-24 # # #---------------------------------------------------------------------------- LOCAL_PATH := $(call my-dir) INC_SRTP := ../libsrtp/include INC_CRYPTO := ../libsrtp/crypto/include INC_TINY_BASE := ../src/Tiny/Base INC_TINY_LOG := ../src/Tiny/Log INC_TINY_MEMORY := ../src/Tiny/Memory INC_TINY_CONTAINER := ../src/Tiny/Container INC_TINY_THREAD := ../src/Tiny/Thread INC_STREAM := ../src/Stream INC_ALL := $(INC_SRTP) \ $(INC_CRYPTO) \ $(INC_TINY_BASE) \ $(INC_TINY_LOG) \ $(INC_TINY_MEMORY) \ $(INC_TINY_CONTAINER) \ $(INC_TINY_THREAD) \ $(INC_STREAM) MY_CFLAGS := -D __ANDROID__ \ -fPIC \ -Wno-multichar #MY_ARCH := arm64-v8a MY_ARCH := armeabi #---------------------------------------------------------------------------- # libsrtp.so #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := srtp2 LOCAL_SRC_FILES := ../../libsrtp/libsrtp2.so include $(PREBUILT_SHARED_LIBRARY) #---------------------------------------------------------------------------- # test: rtpw #---------------------------------------------------------------------------- #include $(CLEAR_VARS) #LOCAL_MODULE := rtpw #SRC_DIR := ../../libsrtp/test #LOCAL_SRC_FILES := $(SRC_DIR)/rtp.c \ $(SRC_DIR)/rtpw.c #LOCAL_C_FLAGS := $(MY_CFLAGS) #LOCAL_C_INCLUDES := $(INC_SRTP) $(INC_CRYPTO) #LOCAL_STATIC_LIBRARIES := libsrtp2 #include $(BUILD_EXECUTABLE) #---------------------------------------------------------------------------- # libtiny.a #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := tiny SRC_DIR := ../../src/Tiny LOCAL_SRC_FILES := $(SRC_DIR)/Base/tiny_ret.c \ $(SRC_DIR)/Base/tiny_time.c \ $(SRC_DIR)/Log/tiny_log_print.c \ $(SRC_DIR)/Memory/tiny_memory.c \ $(SRC_DIR)/Container/TinyList.c \ $(SRC_DIR)/Container/TinyMap.c \ $(SRC_DIR)/Container/TinyQueue.c \ $(SRC_DIR)/Thread/TinyCondition.c \ $(SRC_DIR)/Thread/TinyMutex.c \ $(SRC_DIR)/Thread/TinySemaphore.c \ $(SRC_DIR)/Thread/TinyThread.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) include $(BUILD_STATIC_LIBRARY) #---------------------------------------------------------------------------- # libstream.so #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := stream SRC_DIR := ../../src/Stream LOCAL_SRC_FILES := $(SRC_DIR)/rtp.c \ $(SRC_DIR)/util.c \ $(SRC_DIR)/StreamSender.c \ $(SRC_DIR)/StreamReceiver.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) LOCAL_SHARED_LIBRARIES := libsrtp2 LOCAL_STATIC_LIBRARIES := libtiny LOCAL_LDLIBS := -llog include $(BUILD_SHARED_LIBRARY) #---------------------------------------------------------------------------- # libstream_r_jni.so #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := stream_r_jni SRC_DIR := ../../src/Stream LOCAL_SRC_FILES := $(SRC_DIR)/com_ouyang_srtp_SrtpStreamReceiver.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) LOCAL_SHARED_LIBRARIES := stream LOCAL_LDLIBS := -llog include $(BUILD_SHARED_LIBRARY) #---------------------------------------------------------------------------- # libstream_s_jni.so #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := stream_s_jni SRC_DIR := ../../src/Stream LOCAL_SRC_FILES := $(SRC_DIR)/com_ouyang_srtp_SrtpStreamSender.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) LOCAL_SHARED_LIBRARIES := stream LOCAL_LDLIBS := -llog include $(BUILD_SHARED_LIBRARY) #---------------------------------------------------------------------------- # test: receiver #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := receiver SRC_DIR := ../../src/Stream/test LOCAL_SRC_FILES := $(SRC_DIR)/receiver.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) LOCAL_SHARED_LIBRARIES := stream LOCAL_LDLIBS := -llog include $(BUILD_EXECUTABLE) #---------------------------------------------------------------------------- # test: sender #---------------------------------------------------------------------------- include $(CLEAR_VARS) LOCAL_MODULE := sender SRC_DIR := ../../src/Stream/test LOCAL_SRC_FILES := $(SRC_DIR)/sender.c LOCAL_C_FLAGS := $(MY_CFLAGS) LOCAL_C_INCLUDES := $(INC_ALL) LOCAL_SHARED_LIBRARIES := stream LOCAL_LDLIBS := -llog include $(BUILD_EXECUTABLE)<file_sep>/** * * Copyright (C) 2007-2012 coding.tom * * @author <EMAIL> * @date 2013-5-25 * * @file StreamSender.h * * @version 2013.8.6 * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #ifndef __STREAM_RECEIVER_H__ #define __STREAM_RECEIVER_H__ #include "tiny_base.h" #include "stream_api.h" TINY_BEGIN_DECLS struct _StreamSender; typedef struct _StreamSender StreamSender; STREAM_API StreamSender * StreamSender_New(void); STREAM_API TinyRet StreamSender_Construct(StreamSender *thiz); STREAM_API void StreamSender_Dispose(StreamSender *thiz); STREAM_API void StreamSender_Delete(StreamSender *thiz); STREAM_API TinyRet StreamSender_Initialize(StreamSender *thiz, const char *ip, int port, const char *key, uint32_t ssrc); STREAM_API void StreamSender_Finalize(StreamSender *thiz); STREAM_API TinyRet StreamSender_Sendto(StreamSender *thiz, const char * buf, size_t size); TINY_END_DECLS #endif /* __STREAM_RECEIVER_H__ */<file_sep>/** * * Copyright (C) 2007-2012 coding.tom * * @author <EMAIL> * @date 2013-5-25 * * @file StreamReceiver.c * * @version 2013.8.6 * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #include "StreamReceiver.h" #include "util.h" #include <tiny_log.h> #include <tiny_memory.h> #include <TinyThread.h> #include <config.h> #include <rtp.h> #include <arpa/inet.h> #define TAG "StreamReceiver" #define PACKET_LEN 1378 #define MAX_KEY_LEN 96 static void loop(void *param); struct _StreamReceiver { int sock; srtp_policy_t policy; rtp_receiver_t receiver; TinyThread thread; StreamPacketHandler handler; bool running; }; StreamReceiver * StreamReceiver_New(void) { StreamReceiver *thiz = NULL; do { thiz = (StreamReceiver *)tiny_malloc(sizeof(StreamReceiver)); if (thiz == NULL) { LOG_D(TAG, "tiny_malloc FAILED."); break; } if (RET_FAILED(StreamReceiver_Construct(thiz))) { StreamReceiver_Delete(thiz); thiz = NULL; break; } } while (false); return thiz; } TinyRet StreamReceiver_Construct(StreamReceiver *thiz) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); do { srtp_err_status_t status; memset(thiz, 0, sizeof(StreamReceiver)); thiz->handler = NULL; thiz->running = false; memset(&thiz->policy, 0, sizeof(srtp_policy_t)); TinyThread_Construct(&thiz->thread); TinyThread_Initialize(&thiz->thread, loop, thiz, "StreamReceiver"); status = srtp_init(); if (status != 0) { LOG_E(TAG, "srtp_init failed: %d", status); ret = TINY_RET_E_INTERNAL; break; } } while (false); return ret; } void StreamReceiver_Dispose(StreamReceiver *thiz) { RETURN_IF_FAIL(thiz); StreamReceiver_Stop(thiz); srtp_shutdown(); memset(thiz, 0, sizeof(StreamReceiver)); } void StreamReceiver_Delete(StreamReceiver *thiz) { RETURN_IF_FAIL(thiz); StreamReceiver_Dispose(thiz); tiny_free(thiz); } TinyRet StreamReceiver_Start(StreamReceiver *thiz, const char *ip, int port, const char *keyBase64, uint32_t ssrc, StreamPacketHandler handler) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(ip, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(port, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(keyBase64, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(ssrc, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(handler, TINY_RET_E_ARG_NULL); thiz->handler = handler; do { srtp_err_status_t status; char key[MAX_KEY_LEN]; srtp_sec_serv_t sec_servs = sec_serv_none; struct in_addr address; struct sockaddr_in name; int expected_len = 0; int len = 0; int pad = 0; if (thiz->running) { LOG_E(TAG, "already started"); ret = TINY_RET_E_STARTED; break; } if (0 == inet_aton(ip, &address)) { LOG_E(TAG, "cannot parse IP v4 address %s", ip); ret = TINY_RET_E_ARG_INVALID; break; } if (address.s_addr == INADDR_NONE) { LOG_E(TAG, "address error: %s", ip); ret = TINY_RET_E_ARG_INVALID; break; } thiz->sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (thiz->sock < 0) { LOG_E(TAG, "couldn't open socket: %d\n", errno); ret = TINY_RET_E_ARG_INVALID; break; } name.sin_addr = address; name.sin_family = PF_INET; name.sin_port = htons(port); LOG_E(TAG, "Start: %s:%d", inet_ntoa(name.sin_addr), ntohs(name.sin_port)); /** * 128 bit key */ sec_servs |= sec_serv_conf; // -e // sec_servs |= sec_serv_auth; // -a srtp_crypto_policy_set_rtp_default(&thiz->policy.rtp); srtp_crypto_policy_set_rtcp_default(&thiz->policy.rtcp); thiz->policy.ssrc.type = ssrc_any_inbound; thiz->policy.ssrc.value = ssrc; thiz->policy.key = (uint8_t *) key; thiz->policy.ekt = NULL; thiz->policy.next = NULL; thiz->policy.window_size = 128; thiz->policy.allow_repeat_tx = 0; thiz->policy.rtp.sec_serv = sec_servs; thiz->policy.rtcp.sec_serv = sec_serv_none; /* we don't do RTCP anyway */ /* * read key from hexadecimal or base64 on command line into an octet string */ pad = 0; expected_len = (thiz->policy.rtp.cipher_key_len * 4)/3; len = base64_string_to_octet_string(key, &pad, keyBase64, expected_len); if (pad != 0) { LOG_E(TAG, "error : padding in base64 unexpected"); ret = TINY_RET_E_ARG_INVALID; break; } /* check that hex string is the right length */ if (len < expected_len) { LOG_E(TAG, "error: too few digits in key/salt (should be %d digits, found %d)", expected_len, len); ret = TINY_RET_E_ARG_INVALID; break; } if ((int) strlen(keyBase64) > thiz->policy.rtp.cipher_key_len * 2) { LOG_E(TAG, "error: too many digits in key/salt (should be %d hexadecimal digits, found %u)", thiz->policy.rtp.cipher_key_len * 2, (unsigned)strlen(keyBase64)); ret = TINY_RET_E_ARG_INVALID; break; } printf("set master key/salt to %s/", octet_string_hex_string(key, 16)); printf("%s\n", octet_string_hex_string(key + 16, 14)); if (bind(thiz->sock, (struct sockaddr *)&name, sizeof(name)) < 0) { close(thiz->sock); LOG_E(TAG, "socket bind error"); ret = TINY_RET_E_SOCKET_BIND; break; } thiz->receiver = rtp_receiver_alloc(); if (thiz->receiver == NULL) { LOG_E(TAG, "rtp_receiver_alloc failed"); ret = TINY_RET_E_NEW; break; } rtp_receiver_init(thiz->receiver, thiz->sock, name, ssrc); status = (srtp_err_status_t) rtp_receiver_init_srtp(thiz->receiver, &(thiz->policy)); if (status != srtp_err_status_ok) { LOG_E(TAG, "error: srtp_create() failed with code %d", status); ret = TINY_RET_E_INTERNAL; break; } TinyThread_Start(&thiz->thread); } while (false); return ret; } TinyRet StreamReceiver_Stop(StreamReceiver *thiz) { RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); if (thiz->running) { close(thiz->sock); thiz->running = false; TinyThread_Join(&thiz->thread); rtp_receiver_deinit_srtp(thiz->receiver); rtp_receiver_dealloc(thiz->receiver); } return TINY_RET_OK; } static void loop(void *param) { StreamReceiver *thiz = (StreamReceiver *)param; LOG_D(TAG, "start receiving ..."); thiz->running = true; while (thiz->running) { char packet[PACKET_LEN]; int packet_len = PACKET_LEN; int size = 0; size = rtp_recvfrom(thiz->receiver, packet, &packet_len); if (size < 0) { LOG_D(TAG, "recvfrom < 0"); break; } thiz->handler(packet, size); } LOG_D(TAG, "stop receiving"); }<file_sep>#include <jni.h> #include <tiny_log.h> #include <StreamSender.h> #ifdef __cplusplus extern "C" { #endif #define TAG "stream_s_jni" static StreamSender * _gSender = NULL; /* * Class: com_ouyang_srtp_SrtpStreamSender * Method: initialize * Signature: (Ljava/lang/String;ILjava/lang/String;I)I */ JNIEXPORT jint JNICALL _initialize(JNIEnv *env, jobject obj, jstring ip, jint port, jstring key, jint ssrc) { const char * c_ip = NULL; int c_port = 0; const char * c_key = NULL; int c_ssrc = 0; LOG_D(TAG, "_initialize"); c_port = port; c_ssrc = ssrc; c_ip = (*env)->GetStringUTFChars(env, ip, NULL); if (c_ip == NULL) { LOG_E(TAG, "ip invalid"); return -1; } c_key = (*env)->GetStringUTFChars(env, key, NULL); if (c_key == NULL) { LOG_E(TAG, "key invalid"); return -2; } return StreamSender_Initialize(_gSender, c_ip, c_port, c_key, c_ssrc); } /* * Class: com_ouyang_srtp_SrtpStreamSender * Method: destroy * Signature: ()I */ JNIEXPORT jint JNICALL _destroy(JNIEnv *env, jobject obj) { LOG_D(TAG, "_destroy"); StreamSender_Finalize(_gSender); return 0; } /* * Class: com_ouyang_srtp_SrtpStreamSender * Method: Sendto * Signature: ([BI)I */ JNIEXPORT jint JNICALL _sendto(JNIEnv *env, jobject obj, jbyteArray buf, jint len) { jbyte* buffer = (*env)->GetByteArrayElements(env, buf, 0); char* c_buf = (char *)buffer; int c_len = len; LOG_D(TAG, "_sendto: %d", len); return StreamSender_Sendto(_gSender, c_buf, (size_t) c_len); } static const char * _theClass = "com/ouyang/srtp/SrtpStreamSender"; static JNINativeMethod _theMethods[] = { {"initialize", "(Ljava/lang/String;ILjava/lang/String;I)I", &_initialize}, {"destroy", "()I", &_destroy}, {"sendto", "([BI)I", &_sendto}, }; jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; jclass clazz; int version = -1; LOG_I(TAG, "-> JNI_OnLoad"); do { if ((*vm)->GetEnv(vm, (void *) &env, JNI_VERSION_1_6) == JNI_OK) { version = JNI_VERSION_1_6; LOG_I(TAG, "JNI 1.6"); } else { if ((*vm)->GetEnv(vm, (void *) &env, JNI_VERSION_1_4) == JNI_OK) { version = JNI_VERSION_1_4; LOG_I(TAG, "JNI 1.4"); } else { break; } } // Get jclass with env->FindClass. clazz = (*env)->FindClass(env, _theClass); if (clazz == NULL) { LOG_E(TAG, "Find class failed: %s", _theClass); version = JNI_ERR; break; } LOG_I(TAG, "FindClass OK: %s", _theClass); // Register methods with env->RegisterNatives. if ((*env)->RegisterNatives(env, clazz, _theMethods, sizeof(_theMethods) / sizeof(JNINativeMethod)) < 0) { LOG_E(TAG, "RegisterNatives failed."); version = JNI_ERR; break; } LOG_D(TAG, "RegisterNatives OK."); _gSender = StreamSender_New(); } while (0); return version; } void JNI_OnUnload(JavaVM* vm, void* reserved) { LOG_I(TAG, "%s", "JNI_OnUnload"); StreamSender_Delete(_gSender); } #ifdef __cplusplus } #endif<file_sep>#include "StreamReceiver.h" #include <tiny_log.h> #define TAG "receiver" static FILE * fp = NULL; static void packet_handler(const char *packet, int len) { LOG_D(TAG, "packet_handler: %d", len); fwrite(packet, (size_t)len, 1, fp); } int main(int argc, char *argv[]) { StreamReceiver * thiz = StreamReceiver_New(); const char *key = "<KEY>"; const char *ip = "192.168.31.119"; // ubuntu // const char *ip = "192.168.31.135"; int port = 9999; uint32_t ssrc = 1; if (argc != 2) { printf("usage: %s [filename]\n", argv[0]); return 0; } fp = fopen(argv[1], "wb"); if (fp == NULL) { printf("open file failed: %s\n", argv[1]); return 1; } StreamReceiver_Start(thiz, ip, port, key, ssrc, packet_handler); // StreamReceiver_Stop(thiz); int c = getchar(); // while (1) // { // sleep(10); // } fclose(fp); return 0; } <file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-7-9 * * @file stream_api.h * * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #ifndef __STREAM_API_H__ #define __STREAM_API_H__ #ifdef _MSC_VER # if (defined stream_shared_EXPORTS) # define DLLEXPORT _declspec(dllexport) # else # define DLLEXPORT _declspec(dllimport) # endif # define DLLLOCAL #else # ifdef __ANDROID__ # define DLLEXPORT # define DLLLOCAL # else # define DLLEXPORT __attribute__ ((visibility("default"))) # define DLLLOCAL __attribute__ ((visibility("hidden"))) # endif /* __ANDROID__ */ #endif /* _MHAP_VER */ #ifdef STREAM_STATIC # define STREAM_API #else # define STREAM_API DLLEXPORT #endif /* STREAM_STATIC */ #endif /* __STREAM_API_H__ */ <file_sep>#include "StreamSender.h" //#define file "./demo.h264" #define PACKET_SIZE 1375 #define USEC_RATE (5e5) int main(int argc, char *argv[]) { const char *key = "<KEY>"; const char *ip = "192.168.31.119"; // const char *ip = "192.168.31.135"; int port = 9999; uint32_t ssrc = 1; FILE * fp = NULL; StreamSender * thiz = StreamSender_New(); if (argc != 2) { printf("usage: %s [filename]\n", argv[0]); return 0; } fp = fopen(argv[1], "rb"); if (fp == NULL) { printf("open file failed: %s\n", argv[1]); return 1; } if (RET_FAILED(StreamSender_Initialize(thiz, ip, port, key, ssrc))) { printf("StreamSender_Initialize failed\n"); return 2; } printf("Sending ...\n"); while (1) { TinyRet ret = TINY_RET_OK; char buf[PACKET_SIZE]; size_t size = 0; int read_len = rand() % PACKET_SIZE; memset(buf, 0, PACKET_SIZE); size = fread(buf, 1, read_len, fp); if (size <= 0) { printf("size: %ld\n", size); break; } // printf("PACKET_SIZE: %d\n", PACKET_SIZE); // printf("size: %ld\n", size); ret = StreamSender_Sendto(thiz, buf, size); printf("StreamSender_Sendto: %lld\n", ret); usleep(USEC_RATE); } fclose(fp); StreamSender_Finalize(thiz); StreamSender_Delete(thiz); return 0; } <file_sep>/** * * Copyright (C) 2007-2012 coding.tom * * @author <EMAIL> * @date 2013-5-25 * * @file StreamReceiver.h * * @version 2013.8.6 * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #ifndef __STREAM_RECEIVER_H__ #define __STREAM_RECEIVER_H__ #include "tiny_base.h" #include "stream_api.h" TINY_BEGIN_DECLS struct _StreamReceiver; typedef struct _StreamReceiver StreamReceiver; STREAM_API StreamReceiver * StreamReceiver_New(void); STREAM_API TinyRet StreamReceiver_Construct(StreamReceiver *thiz); STREAM_API void StreamReceiver_Dispose(StreamReceiver *thiz); STREAM_API void StreamReceiver_Delete(StreamReceiver *thiz); typedef void (*StreamPacketHandler)(const char *data, int size); STREAM_API TinyRet StreamReceiver_Start(StreamReceiver *thiz, const char *ip, int port, const char *keyBase64, uint32_t ssrc, StreamPacketHandler handler); STREAM_API TinyRet StreamReceiver_Stop(StreamReceiver *thiz); TINY_END_DECLS #endif /* __STREAM_RECEIVER_H__ */ <file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-11-19 * * @file TinyThread.h * * @remark * */ #ifndef __TINY_THREAD_H__ #define __TINY_THREAD_H__ #include "tiny_base.h" #ifdef _WIN32 #else #include <pthread.h> #endif TINY_BEGIN_DECLS #ifdef _WIN32 typedef void * ThreadHandler; typedef unsigned long ThreadId; #else /* Linux */ typedef int ThreadHandler; typedef pthread_t ThreadId; #endif /* _WIN32 */ #define THREAD_NAME_LEN 256 typedef enum _TinyThreadStatus { ThreadInit = 0, ThreadRunning = 1, ThreadStop = 2, } TinyThreadStatus; typedef void (*ThreadLoop)(void *param); typedef struct _TinyThread { char name[THREAD_NAME_LEN]; TinyThreadStatus status; ThreadLoop loop; ThreadHandler thread_handler; ThreadId thread_id; void * thread_param; } TinyThread; TinyThread * TinyThread_New(void); TinyRet TinyThread_Construct(TinyThread *thiz); TinyRet TinyThread_Initialize(TinyThread *thiz, ThreadLoop loop, void *param, const char *name); TinyRet TinyThread_Dispose(TinyThread *thiz); void TinyThread_Delete(TinyThread *thiz); const char * TinyThread_GetName(TinyThread *thiz); bool TinyThread_Start(TinyThread *thiz); bool TinyThread_Join(TinyThread *thiz); TINY_END_DECLS #endif /* __TINY_THREAD_H__ */ <file_sep>CMAKE_MINIMUM_REQUIRED(VERSION 2.8) PROJECT(stream C) SET(PROJ_NAME "stream") #--------------------------------------------------------------------------------------- # # c flags # #--------------------------------------------------------------------------------------- ADD_DEFINITIONS(-DTINY_DEBUG) #--------------------------------------------------------------------------------------- # WIN32 #--------------------------------------------------------------------------------------- IF(WIN32) MESSAGE(STATUS "build ${PROJ_NAME}for Windows") ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS) ADD_DEFINITIONS(-DUNICODE) ADD_DEFINITIONS(-D_UNICODE) ELSE(WIN32) ADD_DEFINITIONS(-Wno-multichar) # release ADD_DEFINITIONS(-O3) # debug #ADD_DEFINITIONS(-g) ADD_DEFINITIONS(-fPIC) #----------------------------------------------------------------------------------- # APPLE MACOSX #----------------------------------------------------------------------------------- IF(APPLE) MESSAGE(STATUS "build ${PROJ_NAME} for osx") ADD_DEFINITIONS(-D__MAC_OSX__) # Apple LLVM Compiler # SET(CMAKE_CXX_COMPILER /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++) # LLVM gcc Compiler SET(CMAKE_CXX_COMPILER /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++) SET(CMAKE_CXX_FLAGS -m64) #SET(CMAKE_CXX_COMPILER g++) #SET(CMAKE_CXX_FLAGS -m64) #----------------------------------------------------------------------------------- # Linux #----------------------------------------------------------------------------------- ELSE(APPLE) MESSAGE(STATUS "build ${PROJ_NAME} for Linux") ADD_DEFINITIONS(-D__LINUX__) ENDIF(APPLE) ENDIF(WIN32) #--------------------------------------------------------------------------------------- # # include dir # #--------------------------------------------------------------------------------------- INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/libsrtp/crypto/include) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/libsrtp/include) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Tiny/Base) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Tiny/Log) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Tiny/Memory) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Tiny/Container) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Tiny/Thread) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/Stream) #-------------------------------------------------------------------------------------- # # lib # #-------------------------------------------------------------------------------------- IF (WIN32) SET(OS_LIB) SET(SRTP_LIB ${PROJECT_SOURCE_DIR}/libsrtp/libsrtp2.lib) ELSE (WIN32) IF(APPLE) SET(OS_LIB pthread) SET(SRTP_LIB ${PROJECT_SOURCE_DIR}/libsrtp/libsrtp2.a) ELSE(APPLE) SET(OS_LIB pthread) SET(SRTP_LIB ${PROJECT_SOURCE_DIR}/libsrtp/libsrtp2.a) ENDIF(APPLE) ENDIF (WIN32) MESSAGE(STATUS "srtp_lib: ${SRTP_LIB}") MESSAGE(STATUS "os_lib: ${OS_LIB}") #------------------------------------------------------------------------------------- # set output dir #------------------------------------------------------------------------------------- SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/output) SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/output) MESSAGE(STATUS "executable output: ${EXECUTABLE_OUTPUT_PATH}") MESSAGE(STATUS "library output: ${LIBRARY_OUTPUT_PATH}") #------------------------------------------------------------------------------------- # # project # #------------------------------------------------------------------------------------- ADD_SUBDIRECTORY(src) <file_sep>/** * * Copyright (C) 2007-2012 coding.tom * * @author <EMAIL> * @date 2013-5-25 * * @file StreamSender.c * * @version 2013.8.6 * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #include "StreamSender.h" #include <tiny_log.h> #include <tiny_memory.h> #include <config.h> #include <rtp.h> #include <arpa/inet.h> #include "util.h" #define TAG "StreamSender" #define MAX_KEY_LEN 96 struct _StreamSender { int sock; srtp_policy_t policy; rtp_sender_t sender; bool initialized; }; StreamSender *StreamSender_New(void) { StreamSender *thiz = NULL; LOG_D(TAG, "New"); do { thiz = (StreamSender *) tiny_malloc(sizeof(StreamSender)); if (thiz == NULL) { LOG_D(TAG, "tiny_malloc FAILED."); break; } if (RET_FAILED(StreamSender_Construct(thiz))) { StreamSender_Delete(thiz); thiz = NULL; break; } } while (false); return thiz; } TinyRet StreamSender_Construct(StreamSender *thiz) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); LOG_D(TAG, "Construct"); do { srtp_err_status_t status; memset(thiz, 0, sizeof(StreamSender)); thiz->initialized = false; memset(&thiz->policy, 0, sizeof(srtp_policy_t)); status = srtp_init(); if (status != 0) { LOG_E(TAG, "srtp_init failed: %d", status); ret = TINY_RET_E_INTERNAL; break; } } while (false); return ret; } void StreamSender_Dispose(StreamSender *thiz) { RETURN_IF_FAIL(thiz); LOG_D(TAG, "Dispose"); StreamSender_Finalize(thiz); srtp_shutdown(); memset(thiz, 0, sizeof(StreamSender)); } void StreamSender_Delete(StreamSender *thiz) { RETURN_IF_FAIL(thiz); LOG_D(TAG, "Delete"); StreamSender_Dispose(thiz); tiny_free(thiz); } TinyRet StreamSender_Initialize(StreamSender *thiz, const char *ip, int port, const char *keyBase64, uint32_t ssrc) { TinyRet ret = TINY_RET_OK; LOG_D(TAG, "Initialize"); do { srtp_err_status_t status; char key[MAX_KEY_LEN]; srtp_sec_serv_t sec_servs = sec_serv_none; struct in_addr address; struct sockaddr_in name; int expected_len = 0; int len = 0; int pad = 0; if (thiz->initialized) { LOG_E(TAG, "already initialized"); ret = TINY_RET_E_INITIALIZED; break; } if (0 == inet_aton(ip, &address)) { LOG_E(TAG, "cannot parse IP v4 address %s", ip); ret = TINY_RET_E_ARG_INVALID; break; } if (address.s_addr == INADDR_NONE) { LOG_E(TAG, "address error: %s", ip); ret = TINY_RET_E_ARG_INVALID; break; } thiz->sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (thiz->sock < 0) { LOG_E(TAG, "couldn't open socket: %d\n", errno); ret = TINY_RET_E_ARG_INVALID; break; } name.sin_addr = address; name.sin_family = PF_INET; name.sin_port = htons(port); LOG_E(TAG, "RtpReceiver: %s:%d", inet_ntoa(name.sin_addr), ntohs(name.sin_port)); /** * 128 bit key */ sec_servs |= sec_serv_conf; // -e // sec_servs |= sec_serv_auth; // -a srtp_crypto_policy_set_rtp_default(&thiz->policy.rtp); srtp_crypto_policy_set_rtcp_default(&thiz->policy.rtcp); thiz->policy.ssrc.type = ssrc_any_outbound; thiz->policy.ssrc.value = ssrc; thiz->policy.key = (uint8_t *) key; thiz->policy.ekt = NULL; thiz->policy.next = NULL; thiz->policy.window_size = 128; thiz->policy.allow_repeat_tx = 0; thiz->policy.rtp.sec_serv = sec_servs; thiz->policy.rtcp.sec_serv = sec_serv_none; /* we don't do RTCP anyway */ /* * read key from hexadecimal or base64 on command line into an octet string */ pad = 0; expected_len = (thiz->policy.rtp.cipher_key_len * 4) / 3; len = base64_string_to_octet_string(key, &pad, keyBase64, expected_len); if (pad != 0) { LOG_E(TAG, "error : padding in base64 unexpected"); ret = TINY_RET_E_ARG_INVALID; break; } /* check that hex string is the right length */ if (len < expected_len) { LOG_E(TAG, "error: too few digits in key/salt (should be %d digits, found %d)", expected_len, len); ret = TINY_RET_E_ARG_INVALID; break; } if ((int) strlen(keyBase64) > thiz->policy.rtp.cipher_key_len * 2) { LOG_E(TAG, "error: too many digits in key/salt (should be %d hexadecimal digits, found %u)", thiz->policy.rtp.cipher_key_len * 2, (unsigned) strlen(keyBase64)); ret = TINY_RET_E_ARG_INVALID; break; } printf("set master key/salt to %s/", octet_string_hex_string(key, 16)); printf("%s\n", octet_string_hex_string(key + 16, 14)); /** * 这里应该可以指定本地发送端口 */ /* bind to local socket (to match crypto policy, if need be) */ { struct sockaddr_in local; memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(port); ret = bind(thiz->sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (ret < 0) { LOG_E(TAG, "bind failed: %d", port); ret = TINY_RET_E_ARG_INVALID; break; } } thiz->sender = rtp_sender_alloc(); if (thiz->sender == NULL) { LOG_E(TAG, "rtp_sender_alloc failed"); ret = TINY_RET_E_NEW; break; } rtp_sender_init(thiz->sender, thiz->sock, name, ssrc); status = (srtp_err_status_t) rtp_sender_init_srtp(thiz->sender, &thiz->policy); if (status != srtp_err_status_ok) { LOG_E(TAG, "error: srtp_create() failed with code %d", status); ret = TINY_RET_E_INTERNAL; break; } thiz->initialized = true; } while (false); return ret; } // 19461 #define MAX_PACKET (1024 * 10) TinyRet StreamSender_Sendto(StreamSender *thiz, const char * buf, size_t size) { TinyRet ret = TINY_RET_OK; do { const char *p = buf; size_t sent = 0; if (!thiz->initialized) { LOG_E(TAG, "not initialized"); ret = TINY_RET_E_NOT_INITIALIZED; break; } while (sent < size) { size_t notSent = size - sent; size_t len = (notSent < MAX_PACKET) ? notSent : MAX_PACKET; // LOG_E(TAG, "LEN: %ld", len); int count = rtp_sendto(thiz->sender, p, (int)len); if (count < 0) { ret = TINY_RET_E_INTERNAL; break; } sent += len; p += len; } } while (false); return ret; } void StreamSender_Finalize(StreamSender *thiz) { LOG_D(TAG, "Finalize"); if (!thiz->initialized) { return; } if (thiz->sender != NULL) { if (thiz->sender->srtp_ctx != NULL) { rtp_sender_deinit_srtp(thiz->sender); } rtp_sender_dealloc(thiz->sender); } close(thiz->sock); thiz->initialized = false; }<file_sep>#include <jni.h> #include <stdlib.h> #include <tiny_log.h> #include <StreamReceiver.h> #ifdef __cplusplus extern "C" { #endif #define TAG "stream_r_jni" static StreamReceiver * _receiver = NULL; static JavaVM * _jvm = NULL; static jobject _handler = NULL; static jmethodID _onPacket_MethodID = NULL; /** * public interface SrtpStreamHandler { * void onPacket(byte[] data, int size) * } */ static jmethodID getMethodID_onPacket(JNIEnv *env, jobject handler) { jclass clazz; const char *signature = "([BI)V"; clazz = (*env)->GetObjectClass(env, handler); if (clazz == NULL) { LOG_I("%s", "GetObjectClass failed"); return NULL; } return (*env)->GetMethodID(env, clazz, "onPacket", signature); } typedef struct _env_t { JNIEnv *env; bool attached; } env_t; static bool env_open(env_t *e) { if (_jvm == NULL) { LOG_I("%s", "_jvm is NULL"); return false; } e->env = NULL; e->attached = false; (*_jvm)->AttachCurrentThread(_jvm, &e->env, NULL); if (e->env == NULL) { LOG_I("%s", "AttachCurrentThread failed"); e->attached = false; return false; } e->attached = true; return true; } static void env_close(env_t *e) { if (e->attached) { (*_jvm)->DetachCurrentThread(_jvm); } } //static void test(JNIEnv *env) //{ // const char *ppp = "hello"; // int len = 5; // // jbyteArray data; // jint size; // // data = (*env)->NewByteArray(env, len); // (*env)->SetByteArrayRegion(env, data, 0, len, (jbyte *) ppp); // // size = len; // // (*env)->CallVoidMethod(env, _handler, _onPacket_MethodID, data, size); //} static void packet_handler(const char *packet, int len) { env_t e; LOG_D(TAG, "packet_handler: %d", len); if (_handler == NULL) { LOG_I("%s", "_handler is NULL"); return; } if (env_open(&e)) { JNIEnv *env = e.env; jbyteArray j_data = (*env)->NewByteArray(env, len); jint j_size = len; (*env)->SetByteArrayRegion(env, j_data, 0, len, (jbyte *) packet); (*env)->CallVoidMethod(env, _handler, _onPacket_MethodID, j_data, j_size); (*env)->ReleaseByteArrayElements(env, j_data, (*env)->GetByteArrayElements(env, j_data, NULL), 0); env_close(&e); } return; } /* * Class: com_ouyang_srtp_SrtpStreamReceiver * Method: initialize * Signature: ()I */ JNIEXPORT jint JNICALL _initialize(JNIEnv * env, jobject obj) { LOG_D(TAG, "_initialize"); if (_receiver != NULL) { LOG_D(TAG, "already initialized"); return -1; } _receiver = StreamReceiver_New(); return 0; } /* * Class: com_ouyang_srtp_SrtpStreamReceiver * Method: destroy * Signature: ()I */ JNIEXPORT jint JNICALL _destroy(JNIEnv *env, jobject obj) { LOG_D(TAG, "_destroy"); if (_receiver == NULL) { LOG_D(TAG, "not initialized"); return -1; } StreamReceiver_Delete(_receiver); return 0; } /* * Class: com_ouyang_srtp_SrtpStreamReceiver * Method: start * Signature: (Ljava/lang/String;ILjava/lang/String;ILcom/ouyang/srtp/SrtpStreamHandler;)I */ JNIEXPORT jint JNICALL _start(JNIEnv *env, jobject obj, jstring ip, jint port, jstring key, jint ssrc, jobject handler) { const char * c_ip = NULL; int c_port = 0; const char * c_key = NULL; int c_ssrc = 0; LOG_D(TAG, "_start"); if (_receiver == NULL) { LOG_D(TAG, "not initialized"); return -1; } c_port = port; c_ssrc = ssrc; c_ip = (*env)->GetStringUTFChars(env, ip, NULL); if (c_ip == NULL) { LOG_E(TAG, "ip invalid"); return -2; } c_key = (*env)->GetStringUTFChars(env, key, NULL); if (c_key == NULL) { LOG_E(TAG, "key invalid"); return -3; } /** * store jvm & handler */ (*env)->GetJavaVM(env, &_jvm); _handler = (*env)->NewGlobalRef(env, handler); _onPacket_MethodID = getMethodID_onPacket(env, _handler); if (RET_FAILED(StreamReceiver_Start(_receiver, c_ip, c_port, c_key, c_ssrc, packet_handler))) { _handler = NULL; return -4; } return 0; } /* * Class: com_ouyang_srtp_SrtpStreamReceiver * Method: stop * Signature: ()I */ JNIEXPORT jint JNICALL _stop(JNIEnv * env, jobject obj) { LOG_D(TAG, "_stop"); if (_receiver == NULL) { LOG_D(TAG, "not initialized"); return -1; } if (RET_FAILED(StreamReceiver_Stop(_receiver))) { return -2; } _jvm = NULL; _handler = NULL; return 0; } static const char * _theClass = "com/ouyang/srtp/SrtpStreamReceiver"; static JNINativeMethod _theMethods[] = { {"initialize", "()I", &_initialize}, {"destroy", "()I", &_destroy}, {"start", "(Ljava/lang/String;ILjava/lang/String;ILcom/ouyang/srtp/SrtpStreamHandler;)I", &_start}, {"stop", "()I", &_stop}, }; jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; jclass clazz; int version = -1; LOG_I(TAG, "-> JNI_OnLoad"); do { if ((*vm)->GetEnv(vm, (void *) &env, JNI_VERSION_1_6) == JNI_OK) { version = JNI_VERSION_1_6; LOG_I(TAG, "JNI 1.6"); } else { if ((*vm)->GetEnv(vm, (void *) &env, JNI_VERSION_1_4) == JNI_OK) { version = JNI_VERSION_1_4; LOG_I(TAG, "JNI 1.4"); } else { break; } } // Get jclass with env->FindClass. clazz = (*env)->FindClass(env, _theClass); if (clazz == NULL) { LOG_E(TAG, "Find class failed: %s", _theClass); version = JNI_ERR; break; } LOG_I(TAG, "FindClass OK: %s", _theClass); // Register methods with env->RegisterNatives. if ((*env)->RegisterNatives(env, clazz, _theMethods, sizeof(_theMethods) / sizeof(JNINativeMethod)) < 0) { LOG_E(TAG, "RegisterNatives failed."); version = JNI_ERR; break; } LOG_D(TAG, "RegisterNatives OK."); } while (0); return version; } void JNI_OnUnload(JavaVM* vm, void* reserved) { LOG_I(TAG, "%s", "JNI_OnUnload"); } #ifdef __cplusplus } #endif<file_sep># libsrtp-android libsrtp for android ## how to build git submodule init git submodule update ## export CC=/home/ouyang/android/arm-linux-androideabi-4.6/bin/arm-linux-androideabi-gcc export TOOLCHAIN=$ANDROID_NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64 export CC=$TOOLCHAIN/bin/arm-linux-androideabi-gcc export SYSROOT=$ANDROID_NDK/platforms/android-21/arch-arm export CFLAGS="--sysroot=$SYSROOT -g" export LDFLAGS="-L$SYSROOT/usr/lib -g" ln -snf $SYSROOT/usr/lib/crtbegin_so.o ./ ln -snf $SYSROOT/usr/lib/crtend_so.o ./ ./configure --host=x86_64 make make libsrtp2.so ## how to test (rtpw not -a) ./test/rtpw -r -b 7MB1gHv/o96kMuO1cqT0Z0xOoslqwq7nw/2lpuSO -d all -e 128 192.168.31.119 9999 ffmpeg -re -f avfoundation -r 30 -i 0:0 -threads 0 -vcodec libx264 -an -pix_fmt yuv420p -r 30 -f rawvideo -tune zerolatency -vf scale=1280:720 -b:v 299k -bufsize 299k -payload_type 99 -ssrc 1 -f rtp -srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params 7MB1gHv/o96kMuO1cqT0Z0xOoslqwq7nw/2lpuSO srtp://192.168.31.119:9999?rtcpport=9999&localrtcpport=9999&pkt_size=1378​ <file_sep>/** * Copyright (C) 2013-2015 * * @author <EMAIL> * @date 2013-11-19 * * @file TinyMutex.h * * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #ifndef __TINY_MUTEX_H__ #define __TINY_MUTEX_H__ #ifdef _WIN32 #else #include <pthread.h> #endif #include "tiny_base.h" TINY_BEGIN_DECLS #ifdef _WIN32 typedef CRITICAL_SECTION ct_mutex_t; #else /* Linux */ typedef pthread_mutex_t ct_mutex_t; #endif /* _WIN32 */ typedef struct _TinyMutex { ct_mutex_t mutex; } TinyMutex; TinyMutex * TinyMutex_New(void); TinyRet TinyMutex_Construct(TinyMutex *thiz); TinyRet TinyMutex_Dispose(TinyMutex *thiz); void TinyMutex_Delete(TinyMutex *thiz); bool TinyMutex_Lock(TinyMutex *thiz); bool TinyMutex_Unlock(TinyMutex *thiz); TINY_END_DECLS #endif /* __TINY_MUTEX_H__ */
2c4e134bf7316ff1b368d28fd602a5007678ad38
[ "Makefile", "C", "CMake", "Markdown" ]
20
C
yellowmichael/libsrtp-android
a3e581e262a52abc8747a6409aabf42f81430a47
67248587d3dcc635c2466a1bb1e436f92651fca1
refs/heads/master
<repo_name>lambpati/CS4499<file_sep>/Examples/Employee.h #pragma once #include <string> #include <iostream> class Employee{ private: std::string firstname; std::string lastname; int salary; public: Employee(std::string first, std::string last, int sal): firstname(first), lastname(last), salary(sal){} //Methods int getSalary() const { return salary;} void printEmployee() const { std::cout << firstname << lastname << ", $" << salary << std::endl;} bool operator<(Employee const& e) const {return this->salary < e.getSalary();} // Used for sorting }; <file_sep>/Homework/Homework5.cc #include <iostream> #include <vector> #include <algorithm> #include "Vehicle.hh" #include "Truck.hh" void TruckEst(float price){ std::cout << "Estimated value of as of April 1st, 2024: $" << price << '\n'; } std::vector<float> estVal(std::vector<Truck> const& truck, float const& ref){ std::vector<float> v; for(int i = 0; i < truck.size(); i++){ v.push_back(truck[i].estimateValue(ref)); } return v; } int main(int argc, char const *argv[]) { Truck chevy = Truck(2015,0, 37000, "Chevrolet", "Colorado",2015.152,true,5000); std::cout << "Original date: " << chevy.getValue_Date() << '\n'; std::cout << "Original value: " << chevy.getValue() << '\n'; chevy.updateValue(2021.1534); //February 25 2021 std::cout << "value_date: " << chevy.getValue_Date() << '\n'; std::cout << "Updated value: " << chevy.getValue() << '\n'; //TRUCK TIME std::vector<Truck> trucks; trucks.push_back(Truck(2007,199045,13995,"Chevrolet","Kodiak",2021.046,false,16000)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=528987000&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26keywordPhrases%3Dkodiak%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2018,60631,38900,"Ford","F150",2021.046,true,11500)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=565487356&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2015,185268,20995,"Chevrolet","Silverado",2021.046,true,13800)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=572109373&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2019,37345,54762,"GMC","Sierra",2021.046,true,14000)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=559209670&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&makeCode1=GMC&modelCode1=GMCC25PU&clickType=listing trucks.push_back(Truck(2017,42930,37980,"RAM","Laramie",2021.046,true,4190)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=570103032&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&makeCode1=RAM&modelCode1=RM1500&clickType=listing std::vector<float> price = estVal(trucks,2024.061); std::for_each(price.begin(),price.end(),TruckEst); return 0; } <file_sep>/Homework/CS4499_Homework1_PatienceLamb.cpp // <NAME> // Homework 1 #include <iostream> int main(int argc, char const *argv[]) { std:std::cout << "Hello World! My name is Patience. " << '\n'; return 0; } <file_sep>/Examples/Example17.cpp // File IO #include <iostream> #include <string> #include <fstream> // File handling (ifstream, ofstream) using namespace std; int main(int argc, char const *argv[]) { ifstream input; ofstream output; int x; string next; string line; input.open("input.txt", fstream::in); input >> x; //Read an int from input.txt into x cout << "x: " << x << endl; input >> next; cout << "next: " << next << '\n'; //input.getline(line,10); // cout << "line: " << line << endl; input.close(); output.open("output.txt",fstream::app); output << "New number: " << 14323 << endl; output.close(); return 0; } <file_sep>/Homework/Wesley/Warren.cc #include "Rabbit.hh" #include "Warren.hh" #include "FileOut.hh" #include <iostream> #include <algorithm> #include <sstream> #include <vector> #include <random> #include <fstream> Warren::Warren(std::vector<Rabbit> rabbit): bunnies(rabbit){} Warren::Warren(){} void Warren::initialize(){ for (size_t i = 0; i < 10; i++) { Rabbit rabbit = copulate(); makePattern(); rabbit.setColor(getColor()); toFile(rabbit); bunnies.push_back(rabbit); } } int Warren::randomNum() { std::random_device rd; std::minstd_rand0 generator(rd()); std::uniform_int_distribution<int> dist(0,100); return dist(generator); } void Warren::setSex(){ int n = randomNum(); if (n < 47){ sex = "M"; } else if (n < 94){ sex = "F"; } else { sex = "X"; } } void Warren::makePattern(){ int n = randomNum()%4; switch (n) { case 0: color = "Brown"; break; case 1: color = "Black"; break; case 2: color = "White"; break; case 3: color = "Spotted"; break; } } void Warren::Rad(){ int n = randomNum(); if (n < 3){ radioactive = 1; } else { radioactive = 0; } } void Warren::readName(){ std::ifstream bunnynames; names.resize(101,"Placeholder"); bunnynames.open("bunnynamesbetter.txt", std::fstream::in); while (bunnynames.is_open()) { for(auto i = 0; i < names.size(); i++){ std::getline(bunnynames,names[i]); } bunnynames.close(); } } bool Warren::booleans(){ int n = randomNum(); if(n < 50){ return 1; } return 0; } int Warren::addYear(Rabbit rabbit){ return rabbit.getAge()+1; } void Warren::begin(int timesCalled){ std::stringstream output; FileOut fileOut; for(int i = 0; i < bunnies.size(); i++){ int age = addYear(bunnies.at(i)); bunnies.at(i).setAge(age); } output << "Round " << timesCalled << '\n'; int bAge; for(int age = 0; age <= 50; age++){ int count = 0; for(int i = 0; i < bunnies.size(); i++){ if(bunnies.at(i).getAge() == age){ count++; } } output << "Number of bunnies at age " << age << ": " << count << '\n'; } int born = birth(); int converted = countRad(); makeRad(); int die = dead(); int numBunnies = bunnies.size(); output << "Number of bunnies: " << numBunnies << '\n'; output << "Number of bunnies died: " << die << '\n'; output << "Number of bunnies born: "<< born << '\n'; output << "Number of bunnies converted: "<< converted << '\n'; fileOut.writeOutput(output.str()); } bool Warren::died(int k){ if(bunnies.at(k).getAge() >= 10 && bunnies.at(k).getRad() == 0){ return 1; } else if(bunnies.at(k).getAge() >= 50 && bunnies.at(k).getRad() == 1){ return 1; } return 0; } int Warren::dead(){ int bunniesDead = 0; std::stringstream output; FileOut fileOut; std::vector<Rabbit>::iterator values = bunnies.begin(); while(values != bunnies.end()){ if(values->getAge() >= 10 && values->getRad() == 0){ output << "Rabbit " << values->getName() << " died at age " << values->getAge() << '\n'; fileOut.writeOutput(output.str()); bunniesDead++; bunnies.erase(values); } else if(values->getAge() >= 50 && values->getRad() == 1){ output << "Rabbit " << values->getName() << " died at age " << values->getAge() << '\n'; fileOut.writeOutput(output.str()); bunniesDead++; bunnies.erase(values); } else{ values++; } } return bunniesDead; } int Warren::birth(){ int NumberBorn = 0; std::vector<Rabbit> reproduce = mate(); for (auto i = 0; i < reproduce.size()-1 && !reproduce.empty(); i++) { reproduce = mate(); Rabbit rabbit1 = reproduce.at(i); Rabbit rabbit2 = reproduce.at(i+1); if((rabbit1.getGender() == "F" && rabbit2.getGender() == "M") || (rabbit1.getGender() == "M" && rabbit2.getGender() == "F")){ Rabbit baby = copulate(); std::string color = parentalColor(rabbit1,rabbit2); baby.setColor(color); toFile(baby); NumberBorn++; bunnies.push_back(baby); i += 2; } else if((rabbit1.getGender() == "X" && rabbit2.getGender() == "M") || (rabbit1.getGender() == "M" && rabbit2.getGender() == "X")){ bool isSuccess = booleans(); if(isSuccess){ Rabbit baby = copulate(); std::string color = parentalColor(rabbit1,rabbit2); baby.setColor(color); toFile(baby); NumberBorn++; bunnies.push_back(baby); i += 2; } } else if((rabbit1.getGender() == "X" && rabbit2.getGender() == "F") || (rabbit1.getGender() == "F" && rabbit2.getGender() == "X")){ bool isSuccess = booleans(); if(isSuccess){ Rabbit baby = copulate(); std::string color = parentalColor(rabbit1,rabbit2); baby.setColor(color); toFile(baby); NumberBorn++; bunnies.push_back(baby); i += 2; } } } return NumberBorn; } std::string Warren::parentalColor(Rabbit rabbit1, Rabbit rabbit2){ bool color = booleans(); if(color == 1){ return rabbit1.getColor(); } return rabbit2.getColor(); } std::vector<Rabbit> Warren::mate(){ std::vector<Rabbit> reproducable; for(size_t i = 0; i < bunnies.size(); i++){ if(bunnies[i].getAge() <= 8){ if(bunnies[i].getAge() >= 2){ if(!bunnies[i].getRad()){ reproducable.push_back(bunnies[i]); } } } } return reproducable; } Rabbit Warren::copulate(){ Rabbit baby; setSex(); baby.setGender(getGender()); Rad(); baby.setRad(getRad()); readName(); baby.setName(getName()); return baby; } void Warren::makeRad(){ std::vector<size_t> normBunnies = notRad(); for (size_t i = 0; i < countRad() && !normBunnies.empty(); i++) { int pos = randomNum()%normBunnies.size(); bunnies[normBunnies[pos]].setRad(1); normBunnies.erase(normBunnies.begin()+pos); } } std::vector<size_t> Warren::notRad(){ std::vector<size_t> normBunnies; for(size_t i = 0; i < bunnies.size(); i++){ if(!bunnies.at(i).getRad()){ normBunnies.push_back(i); } } return normBunnies; } int Warren::countRad(){ int NumberMutant = 0; for(Rabbit b: bunnies){ if(b.getRad()){ NumberMutant++; } } return NumberMutant; } void Warren::toFile(Rabbit baby){ std::stringstream output; FileOut fileOut; output<< "Rabbit "<< baby.getName() << " " << baby.getGender() << " "<< baby.getColor() << " " << baby.getRad() << " was born!\n"; fileOut.writeOutput(output.str()); } <file_sep>/Examples/Example5.cpp // Example 5 // Strings // <NAME> #include <iostream> #include <string> int main(int argc, char const *argv[]) { //char greeting[6] = { 'h','e','l','l','o','\0'}; // C-style string std::string greeting; std::string second_greeting; greeting = "Hello world"; std::cout << greeting << '\n'; second_greeting = greeting + "!!"; std::cout << second_greeting << '\n'; std::cout << second_greeting.length() << '\n'; // Can utilize [] operator in string class to access characters for (size_t i = 0; i < greeting.length(); i++) { std::cout << greeting[i] << '\n'; } // Not best practice, [] doesn't check for out of bounds // std::cout << "Out of bounds access: " << greeting[100] << '\n'; // std::cout << "Bound checking access: " << greeting.at(100) << '\n'; if(greeting == second_greeting){ std::cout << "Greetings are the same" << '\n'; } // Gives result of the difference of the character lengths // Returns 0 if strings match, positive if string is greater/longer and // negative if strong is shorter/less than std::cout << "Results of comparison: " << second_greeting.compare(greeting) << '\n'; std::string sentence = "Yes, we went to Applebees after we left the football game"; int firstWe = sentence.find("we "); std::cout << firstWe << '\n'; std::cout << sentence.at(firstWe) << '\n'; // If you get rid of the space, it finds the "went" int secondWe = sentence.find("we ", firstWe + 1); std::cout << secondWe << '\n'; // Returns a -1 if not found int thirdWe = sentence.find("we ", secondWe + 1); std::cout << std::string::npos << std::endl; std::cout << thirdWe << '\n'; std::cout << "Is A in our sentence?" << '\n'; if(sentence.find("A") >= 0){ std::cout << "Yes." << '\n'; } else { std::cout << "No." << '\n'; } // Shorter way using ternary operator: std::cout << (sentence.find("A") >= 0 ? "Yes." : "No.") << '\n'; return 0; } <file_sep>/Homework/Homework3.1.cc // <NAME> // Homework 3.1 #include <iostream> #include <vector> #include <cmath> using namespace std; // Set the rn value to seed in a global sense long rn = 101101; // Create the normalized value in a global sense float norm; vector<int> bins(100,0); // Make a pair of rn and norm to call later on float randlcg(long g, long c, long p){ rn = (g * rn + c) % p; norm = (float) rn/p; return norm; } long period(long g, long c, long p){ long count = 0; while(rn != 101101){ randlcg(g,c,p); count++; } return count; } int main(int argc, char const *argv[]) { long g = 61; long c = 1; long p =pow(2,24); float mean; // Number of random numbers to generate int number; float accumulator; // Uncomment the value you would like to use for # of Random Numbers number = 100; // number = 10000; // number = 1000000; // number = 100000000; for (int i = 1; i <= number; i++) { norm = randlcg(g,c,p); int index = static_cast<int>(norm*100); bins.at(index)++; accumulator += norm; } mean = accumulator/number; // Commenting this out for more concise output // for (int k = 0; k < bins.size(); k++){ // cout << "Bin " << k << ":" << bins.at(k) << endl; // } cout << "Mean of " << number << " pseudorandom numbers: " << mean << endl; // If the LCG was a perfect pseudorandom number generator, the mean = 0.5 // half way between the minimum value (0) and the maximum value (1) for all // values of numbers. // As the amount of random numbers generated increased, a more uniform // distribution was produced (the graphs created a "box" shaped graph). // A perfect pseudorandom number generator would create a uniform uniform // distribution with a few points or many points and would maintain the // distribution without repeating values. // Calculate the period of the LCG long periodf = period(g,c,p); cout << "The period is: " << periodf << endl; return 0; } <file_sep>/Examples/Accum.h #pragma once template <class T> class Accum { private: T total; public: Accum(T start) : total(start) {}; T getTotal() const { return total; } T operator +=(T const& t) { return total = total + t; } } <file_sep>/Examples/Example20.cc // Example 20 // Accumulate #include <iostream> #include <vector> #include <algorithm> #include <numeric> //Accumulate (and also inner product) int main(int argc, char const *argv[]) { std::vector<int> a{1,2,3,4,5}; std::vector<int> b(1,2,0,4); int total=0; for (auto i : a) { total += i; } std::cout << "Total of vector a: "<< total << std::endl; total = accumulate(begin(a), end(a), 0); std::cout << "Total of vector a (accumulate): " << total << '\n'; //Count only even numbers total = accumulate(begin(a),end(a),0, [](int total, int i){ if (i%2 == 0) return total + i; return total;}) return 0; } <file_sep>/Examples/Person.h #pragma once // Only include this once #include <string> class Person { private: // Attributes/characteristics std::string firstname; std::string lastname; int arbitrarynumber; public: // Constructors Person(std::string, std::string, int arbitrary); Person(); // Default constructor // Destructor ~Person(); // Methods std::string getName(); int getNumber(); }; <file_sep>/Examples/Example6.cpp // Example 6 // Vectors // <NAME> #include <iostream> #include <vector> #include <random> using namespace std; int main(int argc, char const *argv[]) { vector<int> iv(10); // Create integer vector iv with size 10 vector<int> iv2(10,0); // Initialize all elements to 0 cout << "iv: " << '\n'; for(int i = 0; i < iv.size(); i++){ iv.at(i) = i + 1; cout << "iv[" << i << "] = " << iv.at(i) << endl; } cout << "iv2: " << '\n'; for(int i = 0; i < iv2.size(); i++){ cout << "iv2[" << i << "] = " << iv2.at(i) << endl; } cout << "Max size: " << iv.max_size() << endl; //Maximum number of elements // a container can hold vector<int> grades; int num_students; cout << "Size: " << grades.size() << endl; cout << "Enter number of students: "; cin >> num_students; grades.resize(num_students); cout << "Size now: " << grades.size() << endl; int grade; grades.resize(0); do { cout << "Enter integer grade (0 to exit): "; cin >> grade; grades.push_back(grade); // Insert element at back } while(grade != 0); grades.pop_back(); //Deletes last element cout << "Size now: " << grades.size() << endl; cout << "grades: " << '\n'; for(int i = 0; i < grades.size(); i++){ cout << "grades[" << i << "] = " << grades.at(i) << endl; } // Random number generator random_device rd; mt19937 mt(rd()); uniform_real_distribution<double> dist(0.0, 1.0); double rand; // Binning random values vector<int> bins(10, 0); for(int k = 0; k < 10000; k++){ rand = dist(mt); int index = static_cast<int>(rand*10); // Static cast // cout << rand << "\t" << index << endl; // cout << rand << endl; bins.at(index)++; } for (int k = 0; k < bins.size(); k++){ cout << "Bin " << k << ":" << bins.at(k) << endl; } return 0; } <file_sep>/Homework/Truck.cc #include "Truck.hh" Truck::Truck(int y, float mile, float val, std::string man, std::string mod, float date, bool isAwd, int towing) : Vehicle(y,mile,val,man,mod,date), awd(isAwd), towingCapacity(towing){} Truck::Truck(){ Vehicle(); awd = true; towingCapacity = 5000; } Truck::~Truck(){} <file_sep>/Examples/PersonOperatorOverloads.cc #include "PersonOperatorOverloads.h" #include <iostream> Person::Person(std::string first, std::string last, int arbitrary) : // Constructor implementation firstname(first), lastname(last), arbitrarynumber(arbitrary) // Constructor initializer { std::cout << "Constructing " << firstname << " " << lastname << std::endl; } //Operator Overloads bool Person::operator<(Person const& p) const { return this->arbitrarynumber < p.arbitrarynumber; //left side is the left side of < in main case } bool Person::operator<(int i) const{ return arbitrarynumber < i; } bool operator<(int i, Person const& p){ // can only do const on member function return i < p.arbitrarynumber; //abritrary number is private so cannot access directly } // as p is const&, get number must be const or will error // Can declare this function as a friend of Person, and then use arbitrarynumber (not preferred) <file_sep>/Examples/Example11.cpp // Example 11 // const // <NAME> #include <iostream> using namespace std; /* int DoubleIt(int& x){ x = x*2; return x; } */ int DoubleIt(int const& x){ //x = x*2; return x*2; } int main(int argc, char const *argv[]) { int i = 3; int const CI = 3; i = 4; // CI = 4; //Cannot do this int& ri = i; ri = 5; int const& cri = i; // cri = 6; // cannot do this // int& rCI = CI; int& const rCI = CI; int j = 10; int doubleJ = DoubleIt(j); cout << "doubleJ: " << doubleJ << endl; cout << "j: " << j << endl; return 0; } <file_sep>/Examples/Example2.cpp // Example 2 // If, switch statements // <NAME> #include <iostream> #include <cmath> using namespace std; int main(int argc, char const *argv[]) { double x = 3.5; double y = 3.7; bool litmus; litmus = (y>4) && (x>4); cout << "\t litmus = \n" << litmus << endl; if (litmus) { cout << "x and y are greater than 4 \n"; } else if (x>4) { cout << "x is greater than 4 \n"; } else if (y>4) { cout << "y is greater than 4 \n"; } else { cout << "x and y are less than or equal to 4 \n"; } switch (litmus) { case 1: cout << "x and y are greater than 4 \n"; break; case 0: cout << "x and y are both not greater than 4 \n"; break; default: cout << "default executed \n"; break; } while (x<10) { cout << "x = " << ++x << endl; } // Ctrl+C exits with an infinite loop // x++: executes statements then increments // ++x: increments then executes statements cout << "End of while loop. \n"; do{ cout << "x = " << ++x << endl; } while (x<10); for (int i = 0; i <= 20; i++) { // cout << "i = " << i << endl; if(i%100 == 0){ //Do something every 100 times cout << "i = " << i << endl; } } return 0; } <file_sep>/Homework/Homework2pt1.cc // Homework 2 pt 1 // <NAME> #include <iostream> #include <cmath> using namespace std; double washer(float r1, float r2, float h){ // r1 is the inner radius // r2 is the outer radius // h is the height double volume = M_PI * (pow(r2,2)- pow(r1,2)) * h; return volume; } int main(int argc, char const *argv[]) { float r1 = 0; float r2 = 0; float h = 0; cout << "Enter inner radius: "; cin >> r1; cout << "Enter outer radius: "; cin >> r2; cout << "Enter height: "; cin >> h; std::cout << "Volume is: "<< washer(r1,r2,h) << '\n'; return 0; } <file_sep>/Homework/emojicode.cc #include <iostream> using namespace std; int main(int argc, char const *argv[]) { for(int 😍 = 1; 😍 < 10; 😍++){ } return 0; } <file_sep>/Homework/MidProj/population.hh #pragma once #include "Bunny.hh" #include "Driver.hh" #include "Population.hh" #include "FileOut.hh" #include <iostream> #include <algorithm> #include <sstream> #include <vector> class Population { private: std::vector<Bunny> bunnies; Driver driver; int population; public: //Constructors Population(std::vector<Bunny> bunny, Driver drive); Population(); //Getters std::vector<Bunny> getAllBunnies() const {return bunnies;} //Methods int isBorn(); bool isDead(int k); int killB(); void convertToRMVB(); void start(int num); void initialize(); std::string chooseColor(Bunny bunny1, Bunny bunny2); std::vector<Bunny> canReproduce(); Bunny makeBaby(); std::vector<size_t> IsNotRMVB(); int IsRMVB(); void toConsole(Bunny bunny); int age1year(Bunny bunny); int isAge(int age); }; <file_sep>/Examples/Example15.cpp // Example 15 Operator Overloads #include "PersonOperatorOverloads.h" #include <iostream> using namespace std; int main(int argc, char const *argv[]) { Person Leslie("Leslie", "Kerby", 123); Person Andres("Andres", "Sewell", 789); cout << "Leslie < Andres: " << ((Leslie < Andres) ? "True" : "False") << endl; cout << "Leslie < 300: " << ((Leslie < 300) ? "True" : "False") << endl; cout << "300 < Andres: " << ((300 < Leslie) ? "True" : "False") << endl; return 0; } <file_sep>/Examples/Example3.cpp // Example 3 // Functions // <NAME> #include <iostream> #include <cmath> using namespace std; double power(double b,int exp){ double res = 1; for (int i=1; i<=exp; i++){ res *= b; } return res; } int main(int argc, char const *argv[]) { int base = 2; int exponent = 3; int result = 1; for (int i=1; i<=exponent; i++){ result *= base; } cout << base << "^" << exponent << "=" << result << endl; base = 5; exponent = 10; result = 1; for (int i=1; i<=exponent; i++){ result *= base; } cout << base << "^" << exponent << "=" << result << endl; cout << power(base,exponent) << endl; // Actually works C++ converts int to double return 0; } <file_sep>/Homework/Truck.hh #pragma once #include <string> #include "Vehicle.hh" class Truck : public Vehicle{ private: bool awd; // Assuming is otherwise awd or not int towingCapacity; public: Truck(int, float, float, std::string, std::string, float, bool, int); Truck(); ~Truck(); bool getAwd() const{ return awd; } int getTowing_capacity() const{ return towingCapacity; } void setAwd(bool isAWD){ awd = isAWD; } void setTowing_capacity(int towing){ towingCapacity = towing; } }; <file_sep>/Homework/MidProj/Driver.cc #include "Driver.hh" #include "ReadNames.hh" #include <random> Driver::Driver(std::string gend, std::string col, std::string nam, bool isRMVB): gender(gend), color(col), name(nam), radioactive_mutant_vampire_bunny(isRMVB) { } Driver::Driver(){} int Driver::generateNumber() { std::random_device rd; std::minstd_rand0 generator(rd()); std::uniform_int_distribution<int> dist(0,100); return dist(generator); } void Driver::generateGender(){ int n = generateNumber(); if (n < 47){ gender = "M"; } else if (n < 94){ gender = "F"; } else { gender = "X"; } } void Driver::generateColor(){ int n = generateNumber(); if (n < 25){ color = "White"; } else if(n < 50){ color = "Brown"; } else if(n < 75){ color = "Spotted"; } else { color = "Black"; } } void Driver::generateRMVB(){ int n = generateNumber(); if (n < 3){ radioactive_mutant_vampire_bunny = 1; } else { radioactive_mutant_vampire_bunny = 0; } } void Driver::generateName(){ int n = generateNumber(); ReadNames input; input.read(n); name = input.getName(); } bool Driver::chooseBetween(){ int n = generateNumber(); // If 1, choose first bunny's color if(n < 50){ return 1; } // If 0 choose second bunny's color return 0; } <file_sep>/Examples/PersonOperatorOverloads.h #pragma once // Only include this once #include <string> class Person { private: // Attributes/characteristics std::string firstname; std::string lastname; int arbitrarynumber; friend bool operator<(int i, Person const& p); // allows free function to access members public: // Constructors Person(std::string, std::string, int arbitrary); Person(); // Default constructor // Methods std::string getName(); int getNumber(); //Operator PersonOperatorOverloads bool operator<(Person const& p) const; bool operator<(int i) const; }; //bool operator<(int i, Person const& p); <file_sep>/Homework/Homework3.cc #include <iostream> #include <vector> #include <algorithm> #include "Vehicle.hh" #include "Truck.hh" void printVehicle(Vehicle v){ std::cout << "Vehicle: " << v.getYear() << " " << v.getManufacturer() << " " << v.getModel() << " " << v.getMileage() << " miles $" << v.getValue() << '\n'; } void printTruck(Truck t){ printVehicle(t); std::cout << "\t" << "is AWD? " << t.getAwd() << " and tows " << t.getTowing_capacity() << " lbs"<< '\n'; } int main(int argc, char const *argv[]) { Vehicle vehicle; // Default vehicle std::cout << "Default vehicle:" << '\n'; printVehicle(vehicle); std::cout << "New vehicle:" << '\n'; Vehicle cherokee(2016,50000,15000,"Jeep","Cherokee"); // Construct non-default printVehicle(cherokee); cherokee.setYear(1995); cherokee.setModel("Civic"); cherokee.setMileage(120000); cherokee.setValue(2500); cherokee.setManufacturer("Honda"); std::cout << "Changed vehicle: \n"; printVehicle(cherokee); std::cout << "\n \n"; Truck truck; //Default truck std::cout << "Default truck:" << '\n'; printTruck(truck); std::cout << "New truck:" << '\n'; Truck tundra(2008,120000,50000,"Toyota","Tundra",true,4000); printTruck(tundra); tundra.setAwd(false); tundra.setTowing_capacity(3000); std::cout << "Changed truck: \n"; printTruck(tundra); std::cout << "\n \n"; std::vector<Truck> trucks; trucks.push_back(Truck(2007,199045,13995,"Chevrolet","Kodiak",false,16000)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=528987000&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26keywordPhrases%3Dkodiak%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2018,60631,38900,"Ford","F150",true,11500)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=565487356&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2015,185268,20995,"Chevrolet","Silverado",true,13800)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=572109373&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&clickType=spotlight trucks.push_back(Truck(2019,37345,54762,"GMC","Sierra",true,14000)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=559209670&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&makeCode1=GMC&modelCode1=GMCC25PU&clickType=listing trucks.push_back(Truck(2017,42930,37980,"RAM","Laramie",true,4190)); // https://www.kbb.com/cars-for-sale/vehicledetails.xhtml?listingId=570103032&zip=83201&referrer=%2Fcars-for-sale%2Fsearchresults.xhtml%3Fzip%3D83201%26city%3DPocatello%26sortBy%3Drelevance%26location%3D%255Bobject%2BObject%255D%26vehicleStyleCodes%3DTRUCKS%26incremental%3Dall%26state%3DID%26firstRecord%3D0%26marketExtension%3Dinclude%26relevanceConfig%3Ddefault%26searchRadius%3D50%26isNewSearch%3Dfalse&numRecords=25&vehicleStyleCodes=TRUCKS&firstRecord=0&searchRadius=50&makeCode1=RAM&modelCode1=RM1500&clickType=listing for_each(trucks.begin(), trucks.end(), printTruck); vehicle.updateValue(2021.15); std::cout << "Current value: " << vehicle.getValue() << '\n'; return 0; } <file_sep>/Homework/Homework2pt2.cc // Homework 2 pt 2 // <NAME> #include <iostream> #include <cmath> using namespace std; long randlcg(long g, long c, long p, long rn){ rn = (g * rn + c) % p; return rn; } float norm(long p, long rn){ float norm; norm = (float) rn/p; return norm; } float previousValue(float value){ static float prev = value; return prev; } int main(int argc, char const *argv[]) { int g = 61; int c = 1; long p = pow(2,24); // Start random number at seed long rn = 101101; //Store previousValue long previousValue; float prevnorm; // Normalized value (starting at normalized seed) float normalized = norm(p,rn); for (int i = 1; i <= 30; i++) { previousValue = rn; prevnorm = norm(p,previousValue); rn = randlcg(g,c,p,rn); normalized = norm(p,rn); cout << "Random number " << i <<": " << normalized << endl; cout << "Previous random number " << i-1 << ": " << prevnorm << endl; } return 0; } <file_sep>/Examples/Example7.cpp // Example 7 // Classes // <NAME> #include <iostream> #include "PersonClass.h" using namespace std; int main(int argc, char const *argv[]) { Person:::Person() : arbitrarynumber(0){ } return 0; } <file_sep>/Examples/Example22.cc // Example 22 // Template functions #include <string> #include <iostream> using namespace std; template <class T> T Max(T t1, T t2){ return(t1 < t2) ? t2 : t1; } int main(int argc, char const *argv[]) { cout << "Max of 33 and 44: " << Max(33,44) << endl; string string1 = "Hello"; string string2 = "World"; cout << "Max of " << string1 << " and " << string2 << " is: " << Max(string1,string2) << endl; return 0; } <file_sep>/Homework/MidProj/Driver.hh #pragma once #include <random> #include "Driver.hh" class Driver{ private: std::string gender; std::string color; std::string name; bool radioactive_mutant_vampire_bunny; public: //Constructors Driver(std::string gend, std::string col, std::string nam, bool isRMVB); Driver(); //Getters std::string getGender() const{return gender;} std::string getColor() const{return color;} std::string getName() const{return name;} bool getIsRMVB() const{return radioactive_mutant_vampire_bunny;} //Setters void setGender(std::string gend){gender=gend;} void setColor(std::string col){color=col;} void setIsRMVB(bool rmvb){radioactive_mutant_vampire_bunny=rmvb;} //Methods int generateNumber(); void generateGender(); void generateColor(); void generateRMVB(); void generateName(); bool chooseBetween(); }; <file_sep>/Homework/Wesley/Rabbit.hh #pragma once #include <string> class Rabbit{ private: std::string sex; std::string color; int age; std::string names; bool radioactive; public: Rabbit(std::string gender, std::string col, int year, std::string name, bool rad); Rabbit(); void setGender(std::string gender) {sex = gender;} void setColor(std::string col) {color = col;} void setAge(int years) {age = years;} void setName(std::string nam){names = nam;} void setRad(bool rad) {radioactive = rad;} std::string getGender() const {return sex;} std::string getColor() const {return color;} int getAge() const {return age;} std::string getName() const {return names;} bool getRad() const {return radioactive;} }; <file_sep>/Examples/Example18.cpp // Example 18 // Algorithms: count, count_if #include <vector> #include <algorithm> #include <string> #include <iostream> using namespace std; int main(int argc, char const *argv[]) { vector<int> v{2,7,1,6,2,-2,3,0, -3, -5}; // count //count (beginning iterator, ending iterator, target-value to match) //first old way int twos = 0; int const target = 2; for(size_t i=0; i<v.size(); i++){ if (v.at(i) == target) twos++; } // size_t: type of unsigned int, chooses something large enough to hold the size // of the largest object your system could handle; use it instead of int when // describing the size of the something cout << "How many twos?" << twos << endl; twos = 0; // the count way twos = count(v.begin(), v.end(), target); twos = count(begin(v), end(v), target); cout << "How many twos?" << twos << endl; cout << "How many 7s?" << cout(begin(v), end(v), 7) << endl; // count_if //count_if(begin iter,end iter,function returning bool) // Count how many are odd // first old way int odds = 0; for(auto elem: v){ if (elem % 2 != 0) odds++; } cout << "Number of odds: " << odds << endl; odds = count_if(begin(v), end(v), [](auto elem){return(elem %2 != 0);}); return 0; } <file_sep>/Examples/Example21.cc #include "Employee.h" #include <string> #include <iostream> #include <vector> int main(int argc, char const *argv[]) { Emplyee Leslie("Leslie", "Kerby", 1000); cout << "Leslie's salary: " << Leslie.getSalary() << std::endl; Leslie.printEmployee(); std::vector<Employee> staff{ {"Leslie","Kerby",1000}, {"Obvious","Artificial",20000}, {"Fake","Name",1000}, {"Alan","Turing",2000}, {"Grace","Hopper",2000}, {"Anita","Borg",2000} }; stable_sort(begin(staff),end(staff)); //sort(begin(staff),end(staff)); return 0; } <file_sep>/Homework/Wesley/Rabbit.cc #include "Rabbit.hh" Rabbit::Rabbit(): age(0){} <file_sep>/Examples/Example4.cpp // Example 4 // More functions // <NAME> #include <iostream> using namespace std; int numCalls=0; unsigned long int factorial_forloop(int n){ unsigned long int fact = 1; for(int i=n; i>0; i--){ fact *= i; } return fact; } unsigned long int factorial_recursion(int n){ //Dont define numCalls here to avoid local static int numC; numCalls++; if(n == 1){ return 1; } else{ return n*factorial_recursion(n-1); } } unsigned long int factorial_recursion(int n, int &num){ num++; if(n == 1){ return 1; } else{ return n*factorial_recursion(n-1, num); } } //n! = n*(n-1)*(n-2)*...*1 //0!=1 int main(int argc, char const *argv[]) { int x; int num = 0; cout << "Give me an integer: "; cin >> x; cout << "Factorial of " << x << " = " << factorial_forloop(x) << endl; cout << "Factorial of recursion " << x << " = " << factorial_recursion(x) << endl; cout << "Factorial of recursion (overloaded) " << factorial_recursion(x,num) << '\n'; cout << "Number of calls: " << num << '\n'; cout << "Memory address of x: " << &x << endl; //Find processor time float y; clock_t time_total; //Time using pow functions time_total = clock(); for (int i = 0; i < 100000000; i++) { y = pow(i,5); } time_total = clock() -time_total; std::cout << "Using pow(): " << time_total/CLOCKS_PER_SECOND << "seconds" << '\n'; //Time using multiplication functions for (int i = 0; i < 100000000; i++) { y = i*i*i*i*i; } time_total = clock() -time_total; std::cout << "Using multiplication: " << time_total/CLOCKS_PER_SECOND << "seconds" << '\n'; //Time for factorial_forloop for (int i = 0; i < 100000000; i++) { factorial_forloop(20) } time_total = clock() -time_total; std::cout << "Using for loop: " << time_total/CLOCKS_PER_SECOND << "seconds" << '\n'; //Time for factorial_recursion for (int i = 0; i < 100000000; i++) { factorial_recursion(20) } time_total = clock() -time_total; std::cout << "Using recusion: " << time_total/CLOCKS_PER_SECOND << "seconds" << '\n' return 0; } <file_sep>/Homework/Pointers.cc #include <iostream> int main(int argc, char const *argv[]) { int x; int y; int* p1; p1 = &x; *p1 = 99; std::cout << "Value of x: " << x << '\n'; std::cout << "Value of p1: " << p1 << '\n'; p1 = &y; *p1 = -300; std::cout << "Value of y: " << y << '\n'; std::cout << "Value of p1: " << p1 << '\n'; return 0; } <file_sep>/Homework/MidProj/Bunny.cc #include "Bunny.hh" //Constructors Bunny::Bunny(std::string gend, std::string col, int years, std::string nam, bool isRMVB): gender(gend), color(col), age(years), name(nam), radioactive_mutant_vampire_bunny(isRMVB) { } Bunny::Bunny(): age(0) { } <file_sep>/Homework/Wesley/FileOut.cc #include <fstream> #include <iostream> #include <string> #include "FileOut.hh" #include <vector> FileOut::FileOut(std::string outp): out(outp){} FileOut::FileOut(){} void FileOut::writeOutput(std::string out){ std::ofstream output; output.open("output.txt",std::fstream::app); output << out; std::cout << out; output.close(); } <file_sep>/Homework/Wesley/FileOut.hh #pragma once #include <fstream> #include <iostream> #include <string> #include <vector> class FileOut{ private: std::string out; public: FileOut(std::string outp); FileOut(); void writeOutput(std::string out); }; <file_sep>/Homework/MidProj/MidProj.cc #include "Bunny.hh" #include "Driver.hh" #include "Population.hh" #include <iostream> int main(int argc, char const *argv[]) { std::vector<Bunny> bunnies; Driver driver; Population population(bunnies, driver); population.initialize(); int numberRounds = 0; while (!population.getAllBunnies().empty()) { numberRounds++; population.start(numberRounds); } return 0; } <file_sep>/Homework/MidProj/ReadNames.cc #include <fstream> #include <iostream> #include <string> #include "ReadNames.hh" #include <vector> ReadNames::ReadNames(std::vector<std::string> v, std::string nam): allNames(v), names(nam){ std::ifstream bunnynames; allNames.resize(101,"Placeholder"); bunnynames.open("bunnynamesbetter.txt", std::fstream::in); while (bunnynames.is_open()) { for(auto i = 0; i < allNames.size(); i++){ std::getline(bunnynames,allNames[i]); } bunnynames.close(); } } ReadNames::ReadNames(){ std::ifstream bunnynames; allNames.resize(101,"Placeholder"); bunnynames.open("bunnynamesbetter.txt", std::fstream::in); while (bunnynames.is_open()) { for(auto i = 0; i < allNames.size(); i++){ std::getline(bunnynames,allNames[i]); } bunnynames.close(); } } void ReadNames::read(int lineNum){ names = allNames.at(lineNum); } <file_sep>/Homework/MidProj/ReadNames.hh #pragma once #include <fstream> #include <string> #include <vector> class ReadNames{ private: std::vector<std::string> allNames; std::string names; public: ReadNames(std::vector<std::string> v, std::string nam); ReadNames(); //Getters std::string getName() const {return names;} // Methods void read(int lineNum); }; <file_sep>/Examples/Example1.cpp // <NAME> // Example1.cpp #include <iostream> // preprocessor command, needed for cin and cout #include <cmath> // pow() // math.h is the header file and more standard using namespace std; // otherwise you have to type out std:cout and etc // Don't use namespaces in more complicated code // Don't use TABs; use spaces int main() { int x = 0; int y = 0; double z = 0; const double pi = 3.14159; // Can't assign const variables (p1 += 1) cout << "Hello World!" << '\n'; cout << "x: "; cin >> x; cout << x << endl; // If uou put in a float, C++ TRUNCATES in to an int // If you put in a string x will be a 0 cout << int(42.675) << endl; // Same behaviour for type casting cout << "y: "; cin >> y; z = pi*pow(x,2); cout << "z = " << z << endl; return 0; // Never used y -- not good design: either use y or don't define and ask for it } <file_sep>/Examples/Example16.cpp #include <random> #include <iostream> using namespace std; int main(int argc, char const *argv[]) { random_device rd; mt19937 generator(rd()); // is an LCG by default uniform_int_distribution<int> dist(0,100); for(int i = 0; i < 1000000; i++){ int num = dist(generator); if (num%100 == 0){ std::cout << num << '\n'; } } return 0; } <file_sep>/Homework/MidProj/Population.cc #include "Bunny.hh" #include "Driver.hh" #include "Population.hh" #include "FileOut.hh" #include <iostream> #include <algorithm> #include <sstream> #include <vector> Population::Population(std::vector<Bunny> bunny, Driver drive): bunnies(bunny), driver(drive){} Population::Population(){} void Population::initialize(){ for (size_t i = 0; i < 10; i++) { Bunny bunny = makeBaby(); driver.generateColor(); bunny.setColor(driver.getColor()); toConsole(bunny); bunnies.push_back(bunny); } } int Population::age1year(Bunny bunny){ return bunny.getAge()+1; } void Population::start(int timesCalled){ std::stringstream buffer; FileOut fileOut; for(int i = 0; i < bunnies.size(); i++){ int age = age1year(bunnies.at(i)); bunnies.at(i).setAge(age); } buffer << "Round " << timesCalled << '\n'; int bAge; for(int age = 0; age <= 50; age++){ int count = 0; for(int i = 0; i < bunnies.size(); i++){ if(bunnies.at(i).getAge() == age){ count++; } } buffer << "Amount of bunnies at age " << age << ": " << count << '\n'; } int born = isBorn(); int converted = IsRMVB(); convertToRMVB(); int dead = killB(); int numBunnies = bunnies.size(); int female = count_if(bunnies.begin(),bunnies.end(), [](auto females){return (females.getGender() == "F");}); int male = count_if(bunnies.begin(),bunnies.end(), [](auto males){return (males.getGender() == "M");}); int x = count_if(bunnies.begin(),bunnies.end(), [](auto xs){return (xs.getGender() == "X");}); buffer << "Amount of bunnies: " << numBunnies << '\n'; buffer << "Amount of females: " << female << " amount of males: " << male << " amount of GenderX: " << x << '\n'; buffer << "Amount of bunnies died: " << dead << '\n'; buffer << "Amount of bunnies born: "<< born << '\n'; buffer << "Amount of bunnies converted: "<< converted << '\n'; fileOut.writeOutput(buffer.str()); } bool Population::isDead(int k){ if(bunnies.at(k).getAge() >= 10 && bunnies.at(k).getRMVB() == 0){ return 1; } else if(bunnies.at(k).getAge() >= 50 && bunnies.at(k).getRMVB() == 1){ return 1; } return 0; } int Population::killB(){ int bunniesDead = 0; std::stringstream buffer; FileOut fileOut; std::vector<Bunny>::iterator values = bunnies.begin(); while(values != bunnies.end()){ if(values->getAge() >= 10 && values->getRMVB() == 0){ buffer << "Bunny " << values->getName() << " died at age " << values->getAge() << '\n'; fileOut.writeOutput(buffer.str()); bunniesDead++; bunnies.erase(values); } else if(values->getAge() >= 50 && values->getRMVB() == 1){ buffer << "Bunny " << values->getName() << " died at age " << values->getAge() << '\n'; fileOut.writeOutput(buffer.str()); bunniesDead++; bunnies.erase(values); } else{ values++; } } return bunniesDead; } int Population::isBorn(){ int amountBorn = 0; std::vector<Bunny> reproduce = canReproduce(); for (auto i = 0; i < reproduce.size()-1 && !reproduce.empty(); i++) { reproduce = canReproduce(); Bunny bunny1 = reproduce.at(i); Bunny bunny2 = reproduce.at(i+1); if((bunny1.getGender() == "F" && bunny2.getGender() == "M") || (bunny1.getGender() == "M" && bunny2.getGender() == "F")){ Bunny baby = makeBaby(); std::string color = chooseColor(bunny1,bunny2); baby.setColor(color); toConsole(baby); amountBorn++; bunnies.push_back(baby); i += 2; } else if((bunny1.getGender() == "X" && bunny2.getGender() == "M") || (bunny1.getGender() == "M" && bunny2.getGender() == "X")){ bool isSuccess = driver.chooseBetween(); if(isSuccess){ Bunny baby = makeBaby(); std::string color = chooseColor(bunny1,bunny2); baby.setColor(color); toConsole(baby); amountBorn++; bunnies.push_back(baby); i += 2; } } else if((bunny1.getGender() == "X" && bunny2.getGender() == "F") || (bunny1.getGender() == "F" && bunny2.getGender() == "X")){ bool isSuccess = driver.chooseBetween(); if(isSuccess){ Bunny baby = makeBaby(); std::string color = chooseColor(bunny1,bunny2); baby.setColor(color); toConsole(baby); amountBorn++; bunnies.push_back(baby); i += 2; } } } return amountBorn; } std::string Population::chooseColor(Bunny bunny1, Bunny bunny2){ bool color = driver.chooseBetween(); if(color == 1){ return bunny1.getColor(); } return bunny2.getColor(); } std::vector<Bunny> Population::canReproduce(){ std::vector<Bunny> reproducable; for(size_t i = 0; i < bunnies.size(); i++){ if(bunnies[i].getAge() <= 8){ if(bunnies[i].getAge() >= 2){ if(!bunnies[i].getRMVB()){ reproducable.push_back(bunnies[i]); } } } } return reproducable; } Bunny Population::makeBaby(){ Bunny baby; driver.generateGender(); baby.setGender(driver.getGender()); driver.generateRMVB(); baby.setRMVB(driver.getIsRMVB()); driver.generateName(); baby.setName(driver.getName()); return baby; } void Population::convertToRMVB(){ IsRMVB(); std::vector<size_t> normBunnies = IsNotRMVB(); for (size_t i = 0; i < IsRMVB() && !normBunnies.empty(); i++) { int pos = driver.generateNumber()%normBunnies.size(); bunnies[normBunnies[pos]].setRMVB(1); normBunnies.erase(normBunnies.begin()+pos); i++; } } std::vector<size_t> Population::IsNotRMVB(){ std::vector<size_t> normBunnies; for(size_t i = 0; i < bunnies.size(); i++){ if(!bunnies.at(i).getRMVB()){ normBunnies.push_back(i); } } return normBunnies; } int Population::IsRMVB(){ int amountMutant = 0; for(Bunny b: bunnies){ if(b.getRMVB()){ amountMutant++; } } return amountMutant; } void Population::toConsole(Bunny baby){ std::stringstream buffer; FileOut fileOut; buffer<< "Bunny "<< baby.getName() << " " << baby.getGender() << " "<< baby.getColor() << " " << baby.getRMVB() << " was born!\n"; fileOut.writeOutput(buffer.str()); } <file_sep>/Homework/Wesley/Main.cc #include "Rabbit.hh" #include "Warren.hh" #include <iostream> int main(int argc, char const *argv[]) { std::vector<Rabbit> rabbits; Warren warren(rabbits); warren.initialize(); int numberRounds = 0; while (!warren.getAllBunnies().empty()) { numberRounds++; warren.begin(numberRounds); } return 0; } <file_sep>/Homework/Vehicle.hh #pragma once #include <string> class Vehicle { private: int year; float mileage; // For cars which might have a decimal value mileage float value; // For cents if necessary std::string manufacturer; std::string model; float value_date; public: // Constructors Vehicle(int, float, float, std::string, std::string, float); Vehicle(); //Destructor ~Vehicle(); // Getter int getYear() const { return year; } float getMileage() const { return mileage; } float getValue() const { return value; } std::string getManufacturer() const { return manufacturer; } std::string getModel() const { return model; } float getValue_Date() const { return value_date; } // Setter void setYear(int y){ year = y; }; void setMileage(float mile){ mileage = mile; } void setValue(float val){ value = val; } void setManufacturer(std::string man){ manufacturer = man; } void setModel(std::string mod){ model = mod; } void setValueDate(float date){ value_date = date; } //Methods void updateValue(float current_date); float estimateValue(float estimated_date) const; }; <file_sep>/Examples/Enum.h #pragma once //Old/standard/unscoped enum namespace Statuses { enum Status { Pending, // Compiler to 0 Approved, // Compiler to 1 Cancelled // Compiler to 2 }; // Cannot have another variable in entire program called "Pending" etc // Namespace allows other variables called "Pending" outside of namespace } // New/Strong/Scoped enum enum class FileError { notfound, // static_cast to 0 ok // static_cast to 1 }; enum class NetworkError { disconnected, ok }; // Two "ok"s is fine <file_sep>/Homework/MidProj/Bunny.hh #pragma once #include <string> class Bunny{ private: std::string gender; std::string color; int age; std::string name; bool radioactive_mutant_vampire_bunny; public: // Constructors Bunny(std::string gend, std::string col, int years, std::string nam, bool isRMVB); Bunny(); // Default constructor // Getters std::string getGender() const {return gender;} std::string getColor() const {return color;} int getAge() const {return age;} std::string getName() const {return name;} bool getRMVB() const {return radioactive_mutant_vampire_bunny;} // Setters void setGender(std::string gend) {gender = gend;} void setColor(std::string col) {color = col;} void setAge(int years) {age = years;} void setName(std::string nam){name = nam;} void setRMVB(bool yn) {radioactive_mutant_vampire_bunny = yn;} }; <file_sep>/Homework/Vehicle.cc #include "Vehicle.hh" #include <cmath> Vehicle::Vehicle(int y, float mile, float val, std::string man, std::string mod, float date) : year(y), mileage(mile), value(val), manufacturer(man), model(mod), value_date(date) {} Vehicle::Vehicle(){ //Default constructor implementation year = 2015; mileage = 60000; value = 20000; manufacturer = "Chevrolet"; model = "Colorado"; value_date = 2021.1534; // February 25, 2021 } Vehicle::~Vehicle(){} void Vehicle::updateValue(float current_date){ value = value*pow((1-0.15),current_date-value_date); value_date = current_date; } float Vehicle::estimateValue(float estimated_date) const { float estimatedValue; estimatedValue = value*pow((1-0.15),estimated_date-value_date); return estimatedValue; } <file_sep>/Homework/Wesley/Warren.hh #pragma once #include "Rabbit.hh" #include "Warren.hh" #include "FileOut.hh" #include <iostream> #include <algorithm> #include <sstream> #include <random> #include <vector> class Warren { private: std::vector<Rabbit> bunnies; int population; std::string sex; std::string color; std::vector<std::string> names; std::string name; bool radioactive; public: //Constructors Warren(std::vector<Rabbit> rabbit); Warren(); std::vector<Rabbit> getAllBunnies(){return bunnies;} std::string getColor(){return color;} std::string getName(){return name;} std::string getGender(){return sex;} bool getRad(){return radioactive;} int randomNum(); void setSex(); void Rad(); void makePattern(); void makeRad(); void readName(); bool booleans(); int birth(); bool died(int k); int dead(); void begin(int num); void initialize(); std::string parentalColor(Rabbit rabbit1, Rabbit rabbit2); std::vector<Rabbit> mate(); Rabbit copulate(); std::vector<size_t> notRad(); int countRad(); void toFile(Rabbit rabbit); int addYear(Rabbit rabbit); }; <file_sep>/Examples/PersonConst.hh #pragma once // Only include this once #include <string> class Person { private: // Attributes/characteristics std::string firstname; std::string lastname; int arbitrarynumber; public: // Constructors Person(std::string, std::string, int arbitrary); Person(); // Default constructor // Destructor ~Person(); // Methods std::string getName() const; //Const after method name to indicate method is constant, not the return type. int getNumber() const; void setNumber(int); //Do not declare setter method const; }; <file_sep>/Examples/Example23.cc // Example 23 // Template classes #include <string> #include <iostream> #include "Accum.h" using namespace std; int main(int argc, char const *argv[]) { Accum<int> integrers(0); integers += 3; integers += 7; cout << integers.getTotal() << endl; return 0; } <file_sep>/Examples/Example9.cpp // Example 9 // Enumerators // <NAME> #include "Enum.h" #include <iostream> using namespace std; int main(int argc, char const *argv[]) { // Old enum; Status s = Pending; std::cout << "s = " << s << '\n'; // Should static_cast for good form std::cout << "s = " << static_cast<int>(s) << '\n'; s = Approved; std::cout << "s = " << static_cast<int>(s) << '\n'; // New/Scoped enum FileError fe = FileError::notfound; //std::cout << "fe = " << fe << '\n'; // Will result in error std::cout << "fe = " << static_cast<int>(fe) << '\n'; fe = FileError::ok; std::cout << "fe = " << static_cast<int>(fe) << '\n'; NetworkError ne = NetworkError::disconnected; std::cout << "ne = " << static_cast<int>(ne) << '\n'; return 0; } <file_sep>/Examples/Example10.cpp // Example 10 // References and Pointers // <NAME> #include <iostream> #include "Person.h" using namespace std; void change_x(int& x2) { x2 = 42;} int main(int argc, char const *argv[]) { /* REFERENCES */ int x = 5; cout << "x = " << x << endl; cout << "Address of x: " << &x << endl; int& xref = x; // You can use int & xref; I prefer int&; gives the value at certain reference // &xref gives address of xref cout << "xref = " << xref << endl; cout << "&xref = " << &xref << endl; xref = 7; int y = 31; // xref = &y; // Cannot change address cout<< "x = " <<x << endl; change_x(x); //int& x2 = x cout << "x = " << x << endl; xref = y; cout << "x = " << x << endl; // Can create a reference to an object Person p1("Andres", "Sewell", 789); Person& p1ref = p1; cout << "p1ref: " << p1ref.getName() " " << p1ref.getNumber() << endl; cout << "\n \n"; /* POINTERS */ int* xptr = &x; cout << "Address of xptr = " << &xptr << endl; cout << "The value of xptr = " << xptr << endl; cout << "The value of x (deref of xptr) = " << *xptr << endl; (*xptr)++; cout << "Value of x now: " << *xptr << endl; cout << "X has changed: " << x << endl; *xptr++; // Be careful -- move pointers cout << "Address of xptr: " << xptr << endl; xptr = &y; cout << "Dereference xptr (value of y): " << *xptr << endl; vector<string> texts; texts.push_back("First"); texts.push_back("Second"); texts.push_back("Third"); for(int i = 0; i < texts.size(); i++){ cout << texts.at(i) << endl; } // Can also use a pointer string* textptr = &texts.at(0); cout << *textptr << endl; textptr++; cout << *textptr << endl; textptr++; cout << *textptr << endl; // We dont know whel to stop (where the collection ends) // This is similar to an iterator. We will talk about iterators later in class // Now, pointers to objects Person* p1ptr = &p1; cout << "p1ptr: " << p1ptr << endl; cout << "p1ptr: " << (*p1ptr).getName() << " " << (*p1ptr).getNumber() << endl; // This is not how you should do it, but note that you need parenthesis // Otherwise it will call getName or getNumber for the reference in memory // Do it this way: cout << "p1ptr: " << p1ptr->getName() << " " << p1ptr->getNumber() << endl; // When you are calling methods on an object use the "." operator // When you are calling methods on a pointer, use the "->" operator int* badptr; *badptr = 3; //Goes to change the value pointed at, but its not pointing to anything cout << *badptr << endl; cout << badptr << endl; // Current C++ tries to fix this for you // but don't assume all compilers will act this way -- may segfault int* goodptr = nullptr; if(goodptr) { *goodptr = 3; cout << "goodptr: " << *goodptr << endl; // Always initializing and checking can be tedious, but it is usually done in // large codes to make sure you dont have a fatal crash } return 0; }
9323568f1327fbfbfb267da93d8490368c1e1a6c
[ "C++" ]
53
C++
lambpati/CS4499
6696c9ffbb035beb26b4d8740799dfbae143ce71
848ff511d0aa89948d430753c0f4d68d2e23d7fb
refs/heads/master
<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <conio.h> void swap(int *a,int *b) { int i = *a;//포인터 변수선언 *a = *b; *b = i; } void main()//메인함수 { int a = 0;//변수 초기화 int b = 0; printf("\n값 입력: "); scanf("%d %d", &a, &b); swap(&a,&b);//주소값에서 서로 swap printf("출력: %d %d", a, b); _getch(); } <file_sep>#include<iostream> #include<stdlib.h> #include<time.h> using namespace std; void shellsort(int v[], int n); void swap(int* a, int* b); void DataPrint(int item[], int iCount) { for (int iCnt = 0; iCnt < iCount; iCnt++) { cout << item[iCnt] << endl; } } void SetData(int item[], int iCount) { srand((unsigned int)time(NULL)); for (int iCnt = 0; iCnt < iCount; iCnt++) { item[iCnt] = rand() % iCount; } } #define iMaxCnt 100 void main() { int i; srand((unsigned)time(NULL)); int v[iMaxCnt]; SetData(v, iMaxCnt); shellsort(v, iMaxCnt); DataPrint(v, iMaxCnt); } void ShellsortOpti(int v[], int n) { int gap, i, j, k, temp; for (gap = 1; gap > n; gap = 3 * gap + 1); for (gap /= 3; gap > 0; gap /= 3) { for (i = 0; i < gap; i++) { for (j = i + gap; j < n; j = j + gap) { temp = v[j]; k = j; while (k > gap - 1 && v[k - gap] > temp) { v[k] = v[k - gap]; k -= gap; } v[k] = temp; } } } } void shellsort(int v[], int n) { int gap, i, j, k, temp; for (gap = n / 2; gap > 0; gap = gap / 2) { for (i = 0; i < gap; i++) { for (j = i + gap; j < n; j = j + gap) { temp = v[j]; k = j; while (k > gap - 1 && v[k - gap] > temp) { v[k] = v[k - gap]; k -= gap; } v[k] = temp; } } } } void swap(int* a, int* b) { if (*a > *b) { int t = *a; *a = *b; *b = t; } }<file_sep>#include "TCore.h" HDC g_hScreenDC; HDC g_hOffScreenDC; bool TCore::GameInit() { m_Timer.Init(); I_Input.Init(); // 제 1의 버퍼 전면버퍼 m_hScreenDC = GetDC(m_hWnd); // 제 2의 버퍼를 생성한다. m_hOffScreenDC = CreateCompatibleDC(m_hScreenDC);// 메모리 m_hOffScreenBitmap = CreateCompatibleBitmap( m_hScreenDC, m_rtClient.right, m_rtClient.bottom ); // 반환값 = 이전 선택되어 있던 비트맵 m_hOldBitmap = (HBITMAP)SelectObject(m_hOffScreenDC, m_hOffScreenBitmap); g_hScreenDC = m_hScreenDC; g_hOffScreenDC = m_hOffScreenDC; // m_hOffScreenDC 를 지운다. COLORREF bkColor = RGB(255, 255, 255); m_hbrBack = CreateSolidBrush(bkColor); m_hbrOld = (HBRUSH)SelectObject(m_hOffScreenDC, m_hbrBack); m_hPen = CreatePen(PS_SOLID, 0, RGB(255, 0, 0)); m_hOldPen = (HPEN)SelectObject(m_hOffScreenDC, m_hPen); // 폰트 m_fontDefault = CreateFont( 20, 0, 0, FW_BOLD, 0,0,0,0, HANGEUL_CHARSET, 3,2,1, VARIABLE_PITCH | FF_ROMAN, _T("고딕")); m_fontDefaultOld = (HFONT)SelectObject(m_hOffScreenDC, m_fontDefault); Init(); return true; } bool TCore::GameRelease() { Release(); SelectObject(m_hOffScreenDC, m_hOldPen); DeleteObject(m_hPen); SelectObject(m_hOffScreenDC, m_hbrOld); DeleteObject(m_hbrBack); SelectObject(m_hOffScreenDC, m_hOldBitmap); SelectObject(m_hOffScreenDC, m_fontDefaultOld); DeleteObject(m_fontDefault); // GetDC()로 얻은 DC는 ReleaseDC로 삭제한다. ReleaseDC(m_hWnd, m_hScreenDC); m_Timer.Release(); I_Input.Release(); return true; } bool TCore::GameFrame() { m_Timer.Frame(); I_Input.Frame(); PreFrame(); Frame(); PostFrame(); return true; } bool TCore::PreRender() { SelectObject(m_hOffScreenDC, m_hbrBack); PatBlt(m_hOffScreenDC, 0, 0, m_rtClient.right, m_rtClient.bottom, PATCOPY); return true; } bool TCore::PostRender() { // m_hOffScreenDC 이미지를 m_hScreenDC로 복사해라. BitBlt(m_hScreenDC, m_rtClient.left, m_rtClient.top, m_rtClient.right, m_rtClient.bottom, m_hOffScreenDC, 0, 0, SRCCOPY); return true; } bool TCore::DrawDebug(TCHAR* pString, int iX, int iY) { if (m_hOffScreenDC != NULL) { SetBkColor(m_hOffScreenDC, RGB(255, 0, 0)); SetTextColor(m_hOffScreenDC, RGB(0, 0, 255)); SetBkMode(m_hOffScreenDC, TRANSPARENT); SetTextAlign(m_hOffScreenDC, TA_LEFT); TextOut(m_hOffScreenDC, iX, iY, pString, wcslen(pString)); } return true; } bool TCore::DrawDebug() { RECT rect; if (m_hOffScreenDC != NULL) { GetClientRect(m_hWnd, &rect); SetBkColor(m_hOffScreenDC, RGB(255, 0, 0)); SetTextColor(m_hOffScreenDC, RGB(0, 0, 255)); SetBkMode(m_hOffScreenDC, TRANSPARENT); // 그리기 DrawText(m_hOffScreenDC, m_Timer.m_csBuffer, -1, &rect, DT_LEFT | DT_VCENTER); } return true; } bool TCore::GameRender() { PreRender(); Render(); m_Timer.Render(); I_Input.Render(); DrawDebug(); PostRender(); return true; } bool TCore::GameRun() { GameFrame(); GameRender(); return true; }; void TCore::MsgEvent(MSG msg) { I_Input.MsgEvent(msg); }; bool TCore::ResizeClient(UINT iWidth, UINT iHeight) { TWindow::ResizeClient(iWidth, iHeight); if (m_hScreenDC == NULL || m_hOffScreenDC == NULL) return true; // 삭제전에는 반드시 적용된 상태를 복원하고 생성해야 한다. SelectObject(m_hOffScreenDC, m_hOldBitmap); DeleteObject(m_hOffScreenBitmap); m_hOffScreenBitmap = CreateCompatibleBitmap( m_hScreenDC, m_rtClient.right, m_rtClient.bottom); // 반환값 = 이전 선택되어 있던 비트맵 m_hOldBitmap = (HBITMAP)SelectObject(m_hOffScreenDC, m_hOffScreenBitmap); return true; } TCore::TCore() { } TCore::~TCore() { } <file_sep>#pragma once #include "TFigure.h" class TTriangle : public TFigure { public: void Draw(); //오버라이딩 public: TTriangle(); TTriangle(int x,int y,int width,int height); ~TTriangle(); }; <file_sep>#include<stdio.h> //½Ã°è ¿¹Á¦ void main() { int hour = 0; int sec = 0; int min = 0; int j = 0; for (sec = 1; sec <= 100; sec++) { printf("%3d:%3d:%3d", hour, min, sec); for (j = 1; j < 55000000; j++) { for (int k = 0; k < 20; k++) { putchar('\010'); } if (sec > 60) { sec = 0; if (min > 60) { hour++; min = 0; } else { min++; } } } } }<file_sep>#include "TUdpSocket.h" #include "SDebugString.h" int TUdpSocket::GetIPList() { char szHostName[1024] = {0,}; int iValue = ::gethostname(szHostName, 1024 ); if( iValue==0 ) { for( int i=0; i < 255;i++ ) { struct hostent* pHost; pHost = gethostbyname(szHostName ); if( pHost != NULL ) { if( pHost->h_addr_list[i] ) { BYTE ip[4]; char iplist[256] = {0,}; ip[0] = (BYTE)pHost->h_addr_list[i][0]; ip[1] = (BYTE)pHost->h_addr_list[i][1]; ip[2] = (BYTE)pHost->h_addr_list[i][2]; ip[3] = (BYTE)pHost->h_addr_list[i][3]; sprintf_s( iplist, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3] ); m_ipList.push_back(iplist); } else { break; } } } } return m_ipList.size(); } bool TUdpSocket::Init() { GetIPList(); m_RecvSocket = socket( AF_INET, SOCK_DGRAM, 0 ); m_Socket = socket( AF_INET, SOCK_DGRAM, 0 ); int optval = 1; setsockopt( m_RecvSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); setsockopt( m_Socket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); m_RecvAddr.sin_family = AF_INET; m_RecvAddr.sin_port = htons(9001); m_RecvAddr.sin_addr.s_addr= htonl(INADDR_ANY); int retval = ::bind( m_RecvSocket, (SOCKADDR*)&m_RecvAddr, sizeof(m_RecvAddr)); if( retval == SOCKET_ERROR ) { I_Debug.Print("[%s]", "Error!!!!!"); return false; } BOOL bEnable = TRUE; retval = setsockopt( m_Socket, SOL_SOCKET, SO_BROADCAST, (char*)&bEnable, sizeof(bEnable)); if( retval == SOCKET_ERROR ) { I_Debug.Print("[%s]", "Error!!!!!"); return false; } m_SendAddr.sin_family = AF_INET; m_SendAddr.sin_port = htons(10001); m_SendAddr.sin_addr.s_addr= htonl(INADDR_BROADCAST); CreateThread(); return true; } bool TUdpSocket::Run() { int retval, addrlen; SOCKADDR_IN PeerAddr; char buf[2048]= "udpsocket-test"; while(1) { retval = sendto(m_Socket, buf, strlen(buf), 0, (SOCKADDR*)&m_SendAddr, sizeof(m_SendAddr)); if( retval == SOCKET_ERROR ) break; //OutputDebugStringA((char*)buf); /*I_Debug.Print("[SEND]IP=%s, PORT=%d, %s", inet_ntoa(m_SendAddr.sin_addr), ntohs(m_SendAddr.sin_port), buf);*/ ZeroMemory( buf, sizeof(char)*2048); addrlen = sizeof(PeerAddr); retval = recvfrom(m_RecvSocket, buf, 2048, 0, (SOCKADDR*)&PeerAddr, &addrlen); if( retval == SOCKET_ERROR ) break; buf[retval] = 0; //OutputDebugStringA((char*)buf); I_Debug.Print("[RECV]IP=%s, PORT=%d, %s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buf); Sleep(1000); } closesocket(m_Socket); m_Socket = 0; return true; } bool TUdpSocket::Release() { if(m_Socket != 0 ) { closesocket(m_Socket); m_Socket = 0; } return true; } TUdpSocket::TUdpSocket(void) { m_Socket = 0; } TUdpSocket::~TUdpSocket(void) { } <file_sep>#include "CCCore.h" bool CCCore::GameInit() { m_Timer.Init(); m_Input.Init(); // 제 1의 버퍼 전면버퍼 m_hScreenDC = GetDC(m_hWnd); // 제 2의 버퍼를 생성한다. m_hOffScreenDC = CreateCompatibleDC(m_hScreenDC); //메모리 m_hOffScreenBitmap = CreateCompatibleBitmap( m_hScreenDC, m_rtClient.right, m_rtClient.bottom); // 반환값 = 이전 선택되어 있던 비트맵 m_hOldBitmap = (HBITMAP)SelectObject(m_hOffScreenDC, m_hOffScreenBitmap); Init(); return true; } bool CCCore::GameRelease() { Release(); SelectObject(m_hOffScreenDC, m_hOldBitmap); ReleaseDC(m_hWnd, m_hScreenDC); m_Timer.Release(); m_Input.Release(); return true; } bool CCCore::GameFrame() { m_Timer.Frame(); m_Input.Frame(); Frame(); return true; } bool CCCore::PreRender() { // m_hOffScreenDC를 지운다. COLORREF bkColor = RGB(255, 255, 255); HBRUSH hbrBack = CreateSolidBrush(bkColor); SelectObject(m_hOffScreenDC, hbrBack); PatBlt(m_hOffScreenDC, 0, 0, m_rtClient.right, m_rtClient.bottom, PATCOPY); return true; } bool CCCore::PostRender() { // m_hOffScreenDC 이미지를 m_hScreenDC로 복사해라. BitBlt(m_hScreenDC, m_rtClient.left, m_rtClient.top, m_rtClient.right, m_rtClient.bottom, m_hOffScreenDC, 0, 0, SRCCOPY); return true; } bool CCCore::DrawDebug() { RECT rect; if (m_hOffScreenDC != NULL) { GetClientRect(m_hWnd, &rect); SetBkColor(m_hOffScreenDC, RGB(255, 0, 0)); SetTextColor(m_hOffScreenDC, RGB(0, 0, 255)); SetBkMode(m_hOffScreenDC, TRANSPARENT); // 그리기 DrawText(m_hOffScreenDC, m_Timer.m_csBuffer, -1, &rect, DT_LEFT | DT_VCENTER); //SetTextAlign(hdc,TA_LEFT); //TextOut(hdc,100,100,L"KHJ", //wcslen(L"KHJ")); } return true; } bool CCCore::GameRender() { PreRender(); Render(); m_Timer.Render(); m_Input.Render(); DrawDebug(); PostRender(); return true; } bool CCCore::GameRun() { GameFrame(); GameRender(); return true; } void CCCore::MsgEvent(MSG msg) { m_Input.MsgEvent(msg); } CCCore::CCCore() { } CCCore::~CCCore() { } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <Windows.h> #include <tchar.h> #include <iostream> #include <conio.h> #include <WS2tcpip.h> #pragma comment (lib,"ws2_32") #define MAX_BUFFER_SIZE 256 void T_ERR_EXIT(TCHAR* msg) { LPVOID IpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (TCHAR*)&IpMsgBuf, 0, NULL); MessageBox(NULL, (TCHAR*)IpMsgBuf, msg,MB_ICONERROR); LocalFree(IpMsgBuf); } int NonBlockingSocket(SOCKET sock, u_long iMode) { // 넌블로킹 소켓으로 만들고 // controls the I/O mode of a socket. int iResult = ioctlsocket(sock, FIONBIO, &iMode); if (iResult != NIIF_ERROR) { T_ERR_EXIT(_T("ioctlsocket")); } return iResult; } // 접속시간을 timeout만큼 제한한다. bool tConnect(SOCKET sock, int timeout) { TIMEVAL Timeout; Timeout.tv_sec = timeout; Timeout.tv_usec = 0; struct sockaddr_in address; unsigned long iMode = 1; int iResult = ioctlsocket(sock, FIONBIO, &iMode); if (iResult != NO_ERROR) { printf("ioctlsocket failed with error: %ld \n", iResult); } // 넌블로킹 소켓으로 다시 전환한다. iMode = 0; iResult = ioctlsocket(sock, FIONBIO, &iMode); if (iResult != NO_ERROR) { printf("ioctlsocket failed with error: %ld \n", iResult); } fd_set Write, Err; FD_ZERO(&Write); FD_ZERO(&Err); FD_SET(sock, &Write); FD_SET(sock, &Err); // 넌블로킹 소켓으로 TImeout 만큼 대기한다. iResult = select(0, NULL, &Write, &Err, &Timeout); if (iResult == 0) { // timeout return true; } if (FD_ISSET(sock, &Write)) { //Connected! return true; } if (FD_ISSET(sock, &Err)) { //Error } return false; } void main() { WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return; } SOCKET Sock = socket(AF_INET, SOCK_STREAM, 0); if (NonBlockingSocket(Sock, TRUE) == SOCKET_ERROR)return; SOCKADDR_IN sa; ZeroMemory(&sa, sizeof(sa)); sa.sin_addr.s_addr = inet_addr("192,168,0,106"); sa.sin_family = AF_INET; sa.sin_port = htons(10000); int iRet = connect(Sock,(SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { T_ERR_EXIT(_T("connect")); return; } // 접속 시간제한은 WSAEWOULDBLOCK 일경우 세팅한다. if (tConnect(Sock, 3000) == false) { return; } } // 넌블로킹 소켓으로 다시 전환한다. if (NonBlockingSocket(Sock, TRUE) == SOCKET_ERROR)return; char buf[MAX_BUFFER_SIZE] = { 0, }; int iEnd = 0; while (1) { if (_kbhit() == 1) { int iValue = _getch(); if (strlen(buf) == 0 && iValue == '\r')break; if (iValue == '\r') { if (strlen(buf) == 1)break; int iRet = send(Sock, buf, strlen(buf), 0); if (iRet == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { T_ERR_EXIT(_T("send")); closesocket(Sock); break; } } memset(buf, 0, sizeof(char)*MAX_BUFFER_SIZE); iEnd = 0; } else { if (iEnd < MAX_BUFFER_SIZE - 1) { buf[iEnd++] = iValue; } } } else { char bufRecv[MAX_BUFFER_SIZE] = { 0, }; int iRecvByte = recv(Sock, bufRecv, MAX_BUFFER_SIZE - 1, 0); if (iRecvByte == 0)break; if (iRecvByte == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { closesocket(Sock); T_ERR_EXIT(_T("recv")); break; } } bufRecv[iRecvByte] = 0; printf("recv=%s\n", bufRecv); } } closesocket(Sock); WSACleanup(); } <file_sep>#include "Mgr.h" void main() { srand(time(NULL)); int select; while (1) { printf("\n 신규 : 0 출력 :1 이름검색 :2 번호검색 :3 추가 :4 삭제 :5 저장 :6 불러오기 :7 EXIT : (99)"); scanf("%d", &select); if (select == EXIT)break;//만약 EXIT선택시 종료 system("cls");//선택시 삭제 switch (select) { case NewData: { }break; case PrintData: { }break; case FindName: { }break; case FindIndex: { }break; case AddData: { }break; case DeleteData: { }break; case SaveData: { }break; case LoadData: { }break; } } free(pStudentFile); _getch(); return; }<file_sep>#pragma once #include <Windows.h> #include <tchar.h> #include <vector> #include <string> using namespace std; #pragma comment (lib,"winmm.lib") //timeGetTime 함수 사용하기 위한 선언 extern HWND g_hWnd; extern RECT g_rtClient; extern int g_iFPS;//1 초당 프레임 개수 extern float g_fSecPerFrame; //1프레임의 경과 시간 extern float g_fAccumulation; // 실행된 경과 시간 <file_sep>#include "xModelView.h" LRESULT xModelView::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_LBUTTONDOWN) { short iMouseX = LOWORD(lParam); short iMouseY = HIWORD(lParam); m_WorldArcBall.OnBegin(iMouseX, iMouseY); } if (msg == WM_RBUTTONDOWN) { } if (msg == WM_MOUSEMOVE) { short iMouseX = LOWORD(lParam); short iMouseY = HIWORD(lParam); m_WorldArcBall.OnMove(iMouseX, iMouseY); } if (msg == WM_LBUTTONUP) { m_WorldArcBall.OnEnd(); } if (msg == WM_RBUTTONUP) { } return 1; } bool xModelView::Update(D3DXVECTOR4 vValue) { xCamera::Update(vValue); D3DXMATRIX mModelRot, mModelLastRotInv, mInvView; D3DXMatrixInverse(&mInvView, NULL, &m_matView); mInvView._41 = 0.0f; mInvView._42 = 0.0f; mInvView._43 = 0.0f; D3DXMatrixInverse(&mModelLastRotInv,NULL, &m_mModelLastRot); mModelRot = m_WorldArcBall.GetRotationMatrix(); m_mModelRot = m_mModelRot * m_matView * mModelLastRotInv * mModelRot * mInvView; m_mModelLastRot = mModelRot; m_mModelRot._41 = 0; m_mModelRot._42 = 0; m_mModelRot._43 = 0; m_matWorld = m_mModelRot; return true; } xModelView::xModelView() { D3DXMatrixIdentity(&m_mModelRot); D3DXMatrixIdentity(&m_mModelLastRot); } xModelView::~xModelView() { } <file_sep>#pragma once #include "CCWindow.h" #include "CCTimer.h" #include "CCInput.h" class CCCore : public CCWindow { public: CCTimer m_Timer; CCInput m_Input; HDC m_hScreenDC; //전면 버퍼 HBITMAP m_hOldBitmap; //후면 버퍼의 이미지 HDC m_hOffScreenDC; // 후면 버퍼 HBITMAP m_hOffScreenBitmap;// 후면버퍼의 이미지 public: bool GameRun(); bool GameInit(); bool GameFrame(); bool GameRender(); bool GameRelease(); void MsgEvent(MSG msg); bool DrawDebug(); bool PreRender(); bool PostRender(); public: ////////가상 함수들//////// virtual bool Init() { return true; } virtual bool Frame() { return true; } virtual bool Render() { return true; } virtual bool Release() { return true; } public: CCCore(); virtual ~CCCore(); }; <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <iostream> #pragma comment (lib,"ws2_32.lib") // 소켓 생성 // 연결형, TCP 프로토콜(sock_STREAM,IPPROTO_TCP) // 비연결형, UDP 프로토콜(sock_DGRAM,IPPROTO_UDP) int main(int argc, char*argv[]) { unsigned short iPort = 10000; WSADATA wsa; int iRet; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return 1; } SOCKET listenSock = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN sa; ZeroMemory(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(iPort); sa.sin_addr.s_addr = htonl(INADDR_ANY); // 소켓을 대상 ip에 연결해라. iRet = bind(listenSock, (SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR) return -1; iRet = listen(listenSock, SOMAXCONN); if (iRet == SOCKET_ERROR)return -1; SOCKADDR_IN clientaddr; SOCKET client; while (1) { int addlen = sizeof(clientaddr); client = accept(listenSock, (SOCKADDR*)&clientaddr, &addlen); printf("클라이언트 접속 : IP:%s, PORT:%d\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port)); char buf[256] = { 0, }; int iLen = 0; while (1) { int iRecvByte = recv(client, buf, 256, 0); if (iRecvByte == 0 || iRecvByte == SOCKET_ERROR) { printf("클라이언트 접속 종료 :IPL%s,PORT:%d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); break; } buf[iRecvByte] = '\n'; printf("\n%s", buf); int iSendByte = send(client, buf, iRecvByte, 0); } closesocket(client); } closesocket(listenSock); // 윈속 소멸 iRet = WSACleanup(); return iRet; }<file_sep>#include "DIDInput.h" #define KEYDOWN(key) (((m_KeyState[key])&0x80)?true:false) #define KEYUP(key) (((m_KeyState[key])&0x80)?false:true) bool DIDInput::ResetDevice() { Release(); Init(); return true; } bool DIDInput::Render() { return true; } bool DIDInput::Init() { memset(&m_KeyBeforeState, 0, sizeof(BYTE)*KEYSTATECOUNT); memset(&m_MouseBeforeState, 0, sizeof(DIMOUSESTATE)); m_dwElements = 0; return true; } bool DIDInput::Frame() { if (!KeyProcess() || !MouseProcess()) { return false; } return true; } bool DIDInput::IsKeyDown(DWORD dwKey) { if (m_dwlmmediate) { if (KEYDOWN(dwKey))return true; } else { for (DWORD i = 0; i < m_dwElements; i++) { // this will display then scan code of the key // plus a 'D' - meaning the key was pressed // or a 'U' - meaning ther key was released // DOWN if (m_didod[i].dwOfs == dwKey && (m_didod[i].dwData & 0x80)) { return true; } } } return false; } bool DIDInput::IsKeyUP(DWORD dwKey) { if (m_dwlmmediate) { if (m_KeyBeforeState[dwKey] & 0x80) { if (KEYUP(dwKey)) return true; } } else { for (DWORD i = 0; i < m_dwElements; i++) { // this will display then scan code of the key // plus a 'D' - meaning the key was pressed // or a 'U' - meaning the key was released if (m_didod[i].dwOfs == dwKey && !(m_didod[i].dwData & 0x80)) { return true; } } } return false; } void DIDInput::PostProcess() { memcpy(&m_KeyBeforeState, &m_KeyState, sizeof(BYTE)*KEYSTATECOUNT); memcpy(&m_MouseBeforeState, &m_MouseState, sizeof(DIMOUSESTATE)); } DIDInput::DIDInput() { m_pDi = NULL; m_pDidevKey = NULL; m_pDidevMouse = NULL; m_hWnd = NULL; m_dwElements = 0; m_dwlmmediate = TRUE; } DIDInput::~DIDInput() { Release(); } bool DIDInput::InitDirectInput(HINSTANCE hInst, HWND hWnd, bool keyboard, bool mouse) { HRESULT hr; //GetModuleHandle(NULL) m_hWnd = hWnd; if (m_pDidevKey || m_pDidevMouse)return true; if (FAILED(hr = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDi, NULL))) { return false; } if (keyboard) { if (FAILED(m_pDi->CreateDevice(GUID_SysKeyboard, &m_pDidevKey,NULL))) return false; if (FAILED(m_pDidevKey->SetDataFormat(&c_dfDIKeyboard))) return false; if (FAILED(hr = m_pDidevKey->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND | DISCL_NOWINKEY))) { while (m_pDidevKey->Acquire() == DIERR_INPUTLOST); if (FAILED(m_pDidevKey->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_BACKGROUND | DISCL_NOWINKEY))) return false; } if (!m_dwlmmediate) { DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = SAMPLE_BUFFER_SIZE; // Arbitary buffer size if (FAILED(hr = m_pDidevKey->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph))) return false; } while (m_pDidevKey->Acquire() == DIERR_INPUTLOST); } if (mouse) { if (FAILED(m_pDi->CreateDevice(GUID_SysMouse, &m_pDidevMouse, NULL))) return false; if (FAILED(m_pDidevMouse->SetDataFormat(&c_dfDIMouse))) return false; if (FAILED(m_pDidevMouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) { while (m_pDidevMouse->Acquire() == DIERR_INPUTLOST); if (FAILED(m_pDidevMouse->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND))) return false; } while (m_pDidevMouse->Acquire() == DIERR_INPUTLOST); } return true; } bool DIDInput::Release() { if (m_pDi) { if (m_pDidevKey) { m_pDidevKey->Unacquire(); m_pDidevKey->Release(); m_pDidevKey = NULL; } if (m_pDidevMouse) { m_pDidevMouse->Unacquire(); m_pDidevMouse->Release(); m_pDidevMouse=NULL; } m_pDi->Release(); m_pDi = NULL; } return true; } bool DIDInput::KeyProcess() { HRESULT hr; if (m_dwlmmediate) { ZeroMemory(m_KeyState, sizeof(BYTE)*KEYSTATECOUNT); if (!m_pDidevKey)return false; if (FAILED(m_pDidevKey->GetDeviceState(KEYSTATECOUNT, m_KeyState))) { while (m_pDidevKey->Acquire() == DIERR_INPUTLOST) m_pDidevKey->Acquire(); return true; } } else { if (NULL == m_pDidevKey)return false; memset(&m_didod, 0, sizeof(DIDEVICEOBJECTDATA)*SAMPLE_BUFFER_SIZE); m_dwElements = SAMPLE_BUFFER_SIZE; hr = m_pDidevKey->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), m_didod, &m_dwElements, 0); if (hr != DI_OK) { m_dwElements = 0; hr = m_pDidevKey->Acquire(); while (hr == DIERR_INPUTLOST) hr = m_pDidevKey->Acquire(); return true; } } return true; } bool DIDInput::MouseProcess() { ZeroMemory(&m_MouseState, sizeof(DIMOUSESTATE)); if (!m_pDidevMouse)return false; if (FAILED(m_pDidevMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_MouseState))) { while (m_pDidevMouse->Acquire() == DIERR_INPUTLOST) m_pDidevMouse->Acquire(); return true; } return true; } void DIDInput::SetAcquire(bool bActive) { if (bActive)DeviceAcquire(); else DeviceUnacquire(); } void DIDInput::DeviceAcquire() { if (m_pDidevKey) m_pDidevKey->Acquire(); if (m_pDidevMouse) m_pDidevMouse->Acquire(); } void DIDInput::DeviceUnacquire() { if (m_pDidevKey) m_pDidevKey->Unacquire(); if (m_pDidevMouse) m_pDidevMouse->Unacquire(); }<file_sep>#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <Windows.h> #include <tchar.h> #include <vector> #include <list> #include <string> #include <iostream> #include "SProtocol.h" #pragma comment (lib,"ws2_32.lib") using namespace std; typedef basic_string<TCHAR> T_STR; typedef basic_string<wchar_t> W_STG; typedef basic_string<char> C_STR; // struct TUserData{header, name[9],age }; // 사용방법 (1) // 준비 : char buffer[2048] = {0,}; // SPaket data; // data << header; // data << " 김현진 "; // data << age; // 사용방법(2) // data << header << "김현진" << 25; // char buffer[2048] ={0,}; // SPaket data; // data >> header; // data >> " 김현진 " ; // data >> age; // 사용방법 (2) // data >> header >> "김현진" >> 25; class SPacket { public: char* m_pOffset; UPACKET m_uPacket; public: void PutData(const char* pData, int iSize); void GetData(const char* pData, int iSize); public: // 연산자 재정의 SPacket & operator << (int data); SPacket & operator << (short data); SPacket & operator << (long data); SPacket & operator << (float data); // SPacket & operator << (byte data); SPacket & operator << (char* data); SPacket & operator << (DWORD data); SPacket & operator << (string data); SPacket & operator >> (int& data); SPacket & operator >> (short& data); SPacket & operator >> (long& data); SPacket & operator >> (float& data); //SPacket & operator >> (byte& data); SPacket & operator >> (char* data); SPacket & operator >> (DWORD& data); SPacket & operator >> (string& data); public: SPacket(); SPacket(int dwType); virtual ~SPacket(); }; <file_sep>#include <iostream> #include "TBTree.h" // 트리의 구조를 확인하기 위해서 int main(void) { BTreeNode* avlRoot; BTreeNode* clNode; //current left node BTreeNode* crNode; //current right node BSTMakeAndInit(&avlRoot); BSTInsert(&avlRoot, 1); BSTInsert(&avlRoot, 2); BSTInsert(&avlRoot, 3); BSTInsert(&avlRoot, 4); BSTInsert(&avlRoot, 5); BSTInsert(&avlRoot, 6); BSTInsert(&avlRoot, 7); BSTInsert(&avlRoot, 8); BSTInsert(&avlRoot, 9); std::cout << "루트 노드" << "[" << GetData(avlRoot) << "]" << std::endl; clNode = GetLeftSubTree(avlRoot); crNode = GetRightSubTree(avlRoot); std::cout << "왼쪽 1:" << "[" << GetData(clNode) << "]" << "오른쪽 1: " << "[" << GetData(crNode) << "]" << std::endl; clNode = GetLeftSubTree(clNode); crNode = GetRightSubTree(crNode); std::cout << "왼쪽 2:" << "[" << GetData(clNode) << "]" << "오른쪽 2: " << "[" << GetData(crNode) << "]" << std::endl; clNode = GetLeftSubTree(clNode); crNode = GetRightSubTree(crNode); std::cout << "왼쪽 3:" << "[" << GetData(clNode) << "]" << "오른쪽 3: " << "[" << GetData(crNode) << "]" << std::endl; clNode = GetLeftSubTree(clNode); crNode = GetRightSubTree(crNode); std::cout << "왼쪽 4:" << "[" << GetData(clNode) << "]" << "오른쪽 4: " << "[" << GetData(crNode) << "]" << std::endl; return 0; }<file_sep>#pragma once #include "TEmployee.h" class TTemporary : public TEmployee { private: int time; //일한 시간 int pay; //시간당 급여 public: TTemporary(char* _name, int _time, int pay); int GetPay(); }; <file_sep>#pragma once #include "TTemplate.h" #include "TAseObj.h" #include "TTbsObj.h" #include "TSkinObj.h" #include "TBoneObj.h" class TObjMgr : public TTemplateMap< TModel >, public TSingleton<TObjMgr> { private: friend class TSingleton<TObjMgr>; public: int Load( ID3D11Device* pd3dDevice, const TCHAR* strFileName, const TCHAR* strShaderName, bool bThread = false); int Add(TModel* pNode); TModel* GetFileTypeID(const TCHAR* pszFileName); void SetMatrix(D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj); private: TObjMgr(void); virtual ~TObjMgr(void); }; static TAseObj* IsAseObjType(TModel* pModel) { const std::type_info& r1 = typeid(*pModel); const std::type_info& r2 = typeid(TAseObj); TAseObj* pObj = nullptr; if (&r1 == &r2) { pObj = dynamic_cast<TAseObj*>(pModel); } return pObj; } static TTbsObj* IsTbsObjType(TModel* pModel) { const std::type_info& r1 = typeid(*pModel); const std::type_info& r2 = typeid(TTbsObj); TTbsObj* pObj = nullptr; if (&r1 == &r2) { pObj = dynamic_cast<TTbsObj*>(pModel); } return pObj; } #define I_ObjMgr TObjMgr::GetInstance() //template<typename T, typename F> //auto execute(T* value, F func) -> decltype(func(value)) //{ // return func(value); //} template<typename T> auto CreateDefaultSubobject(const TCHAR* szName) { shared_ptr<T> pNode = make_shared<T>(); I_ObjMgr.Add(pNode); pNode->m_szName = szName; return pNode; } <file_sep>#include "S_WorkThread.h" #include "S_IOCP.h" #include "S_SvrUser.h" bool S_WorkThread::Run() { DWORD dwTransfer; ULONG_PTR keyValue; LPOVERLAPPED LPOV; BOOL Return; while (1) { Return = ::GetQueuedCompletionStatus(S_iocp.m_hIOCP, &dwTransfer, &keyValue, &LPOV, INFINITE); S_SvrUser* User = (S_SvrUser*)keyValue; if (Return == TRUE) { if (dwTransfer == 0) { User->DeleteUser(); } if (dwTransfer != 0 && LPOV != 0) { User->Dispatch(dwTransfer, LPOV); } else { if (GetLastError() != ERROR_OPERATION_ABORTED) { if (dwTransfer == 0) { User->DeleteUser(User->m_Socket); } } } } } return true; } void S_WorkThread::Set(HANDLE hIOCP) { m_hIOCP = hIOCP; } S_WorkThread::S_WorkThread() { } S_WorkThread::~S_WorkThread() { } <file_sep>#pragma once #include<iostream> #include<conio.h> using namespace std; class TPoint { public: int x; int y; void SetPosition(int _x, int _y); void Move(int _x, int _y); void Show(void); public: TPoint(); ~TPoint(); }; <file_sep>#include "Sample.h" #include "TChatSvr.h" #include "SServerIOCP.h" #include "SDebugString.h" bool Sample::Init() { I_ServerIOCP.Init(); I_Server.Init(); m_Udp.Init(); return true; } bool Sample::Release() { m_Udp.Release(); I_Server.Release(); return true; } LRESULT Sample::MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch( message ) { case WM_CREATE: { int iWidth = m_rtClient.right - m_rtClient.left; int iHeight = m_rtClient.bottom - m_rtClient.top; I_Debug.m_hList = CreateWindow( L"listbox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 0, 0, iWidth -100, iHeight, hWnd, (HMENU)0, m_hInstance, NULL ); }break; } return 0; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow ) { Sample server; if (!server.SetWindow(hInstance, _T("ChatSvr_1"), 800, 600)) { return 0; } SetCursor(NULL); // 윈도우 프로시져 담당 if( server.Run() == false ) { return 0; } return 1; } Sample::Sample(void) { } Sample::~Sample(void) { } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") void Error(char* msg) { LPVOID lpMsgBuffer; int iError = WSAGetLastError(); FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, iError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuffer, 0, NULL); printf("%s", lpMsgBuffer); LocalFree(lpMsgBuffer); //exit(-1); } void main() { WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { return; } SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) { Error("sock invalid"); } SOCKADDR_IN serveradd; ZeroMemory(&serveradd, sizeof(serveradd)); serveradd.sin_family = AF_INET; serveradd.sin_port = htons(10000); // 멀티케스트 그룹에 가입하려면 반드시 INADDR_ANY를 사용해야 한다. serveradd.sin_addr.s_addr = htonl(INADDR_ANY); int iRet = bind(sock, (SOCKADDR*)&serveradd, sizeof(serveradd)); if (iRet == SOCKET_ERROR) { Error("sock invalid"); } // INCLUDE 대상 포함 // IP_ADD_SOURCE_MEMBERSHIP <->IP_DROP_SOURCE_MEMBERSHIP /*struct ip_mreq_source mreqsrc; mreqsrc.imr_interface.s_addr = htonl(INADDR_ANY); mreqsrc.imr_multiaddr.s_addr = inet_addr("172.16.17.32"); mreqsrc.imr_sourceaddr.s_addr = inet_addr("192.168.0.61"); setsockopt(sock, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *)&mreqsrc, sizeof(mreqsrc)); mreqsrc.imr_sourceaddr.s_addr = inet_addr("192.168.0.60"); setsockopt(sock, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *)&mreqsrc, sizeof(mreqsrc)); */ // EXCLUDE 대상 삭제 // IP_ADD_MEMBERSHIP <-> IP_BLOCK_SOURCE struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = inet_addr("172.16.17.32"); mreq.imr_interface.s_addr = inet_addr("192.168.0.101"); iRet = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq)); if (iRet == SOCKET_ERROR) { Error("sock invalid"); } struct ip_mreq_source mreqsrc; mreqsrc.imr_interface = mreq.imr_interface; mreqsrc.imr_multiaddr = mreq.imr_multiaddr; mreqsrc.imr_sourceaddr.s_addr = inet_addr("192.168.0.33"); setsockopt(sock, IPPROTO_IP, IP_BLOCK_SOURCE, (char *)&mreqsrc, sizeof(mreqsrc)); SOCKADDR_IN clientAddr; char buf[256] = { 0, }; int addlen; while (1) { addlen = sizeof(clientAddr); iRet = recvfrom(sock, buf, 256, 0, (SOCKADDR*)&clientAddr, &addlen); if (iRet == SOCKET_ERROR) { Error("sock invalid"); } buf[iRet] = 0; printf("\n[%s:%d]:%s", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buf); } // 응용프로그램을 종료하거나 소켓을 닫으면 그룹 설정이 지워진다. setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq)); WSACleanup(); }<file_sep>#include<stdio.h> #include<stdlib.h> //동적 할당 //void main() //{ // char count, *ptr, *p; // ptr = (char *)malloc(35 * sizeof(char)); // if (ptr == NULL) // { // puts("Memory allocation eroor."); // exit(1); // } // p = ptr; // for (count = 65; count < 91; count++)//아스키 코드 A~Z // { // *p++ = count; // *p = '\0'; // puts(ptr); // } //} void main() { unsigned char x; for (x = 65; x < 91; x++) { printf("ASCII code %d is Character:%c\n",x, x); } }<file_sep>#pragma once #include "xFrustum.h" class xCamera : public xFrustum { public: D3DXMATRIX m_mModelRot; D3DXMATRIX m_mModelLastRot; public: D3DXMATRIX m_matWorld; D3DXMATRIX m_matView; D3DXMATRIX m_matProj; D3DXVECTOR3 m_vPos; D3DXVECTOR3 m_vTarget; D3DXVECTOR3 m_vDefaultUp; D3DXVECTOR3 m_vLook; D3DXVECTOR3 m_vSide; D3DXVECTOR3 m_vUp; float m_fCameraYawAngle; float m_fCameraPitchAngle; float m_fFov; float m_fAspect; float m_fNear; float m_fFar; float m_fSpeed; public: void SetSpeed(float fValue); void MoveLook(float fValue); void MoveSide(float fValue); bool UpdateVector(); D3DXMATRIX SetViewMatrix( D3DXVECTOR3 vPos = D3DXVECTOR3(0, 0, -10.0f), D3DXVECTOR3 vTarget=D3DXVECTOR3(0,0,1), D3DXVECTOR3 vUp = D3DXVECTOR3(0, 1, 0) ); D3DXMATRIX SetProjMatrix(float fFov, float fAspect, float fNear=1.0f, float fFar=1000.0f); void UpdateProjMatrix(UINT width, UINT height); public: virtual bool Init() {return true;}; virtual bool Frame(); virtual bool Render(){return true;}; virtual bool Release(){ return true;}; virtual bool Update(D3DXVECTOR4 vValue); public: xCamera(); virtual ~xCamera(); }; <file_sep>#pragma once #include "SvrStd.h" #define PACKETBUFFERSIZE 8192 class SSPacket { public: typedef struct { WORD* len; WORD* type; }PACKETHEADER; public: PACKETHEADER m_PacketHeader; char m_strPacketBuffer[PACKETBUFFERSIZE]; char* m_pstrWritePosition; char* m_pstrReadPosition; WORD GetID(); WORD GetSize(); int m_iReceivedSize; int GetDataSize(); void ReadData(void* buffer, int iSize); void WriteData(void* buffer, int iSize); public: SSPacket& SetID(unsigned short ID); // 패킷을 생성할 떄 SSPacket& operator << (int arg); // 패킷에서 데이터를 추출할 떄 SSPacket& operator >> (int& arg); SSPacket& operator << (DWORD arg); SSPacket& operator >> (DWORD& arg); SSPacket& operator << (bool arg); SSPacket& operator >> (bool& arg); SSPacket& operator << (unsigned short arg); SSPacket& operator >> (unsigned short& arg); SSPacket& operator << (float arg); SSPacket& operator >> (float& arg); SSPacket& operator << (char* arg); SSPacket& operator >> (char* arg); SSPacket& operator << (SSPacket& arg); SSPacket& operator >> (SSPacket& arg); char* GetData(); void Clear(); public: SSPacket(void); SSPacket(unsigned short type); virtual ~SSPacket(void); }; <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <iostream> #include <map> #include "SProtocol.h" #pragma comment(lib,"ws2_32.lib") using namespace std; CRITICAL_SECTION g_crit; // 유저모드 HANDLE g_hMutex; // 커널 모드 struct SUser { SOCKET sock; SOCKADDR_IN clientaddr; SUser() {} SUser(const SUser& copy) { sock = copy.sock; clientaddr = copy.clientaddr; } SUser(SOCKET client, SOCKADDR_IN addr) { sock = client; clientaddr = addr; } }; map<SOCKET, SUser> g_allClientSocket; typedef map<SOCKET, SUser>::iterator ITOR; void T_ERROR(bool bPrint) { if (WSAGetLastError() != WSA_IO_PENDING) { char* lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&lpMsgBuf, 0, NULL); if (bPrint) { MessageBoxA(NULL, lpMsgBuf, "ERROR", MB_OK); } else { OutputDebugStringA((char*)lpMsgBuf); printf("\n%s", (char*)lpMsgBuf); } LocalFree(lpMsgBuf); } } int CheckReturn(int iRet) { if (iRet == 0) { printf("\n----> 정상 퇴장"); return 0; } if (iRet <= SOCKET_ERROR) { printf("\n----> 비정상 퇴장"); T_ERROR(false); return -1; } return iRet; } int SendMsg(SOCKET sock, char* msg, WORD type) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sendmsg.ph.len = strlen(msg); sendmsg.ph.type = type; memcpy(sendmsg.msg, msg, strlen(msg)); int sendbytes = 0; int iTotalsize = strlen(msg) + PACKET_HEADER_SIZE; char* pMsg = (char*)&sendmsg; int iSend = 0; do { iSend = send(sock, &pMsg[sendbytes], iTotalsize - sendbytes, 0); if (CheckReturn(iSend) <= 0) { return iSend; } sendbytes += iSend; } while(sendbytes < iTotalsize); return sendbytes; } int SendMsg(SOCKET sock, UPACKET* packet, WORD type) { int sendbytes = 0; int iTotalsize = packet->ph.len + PACKET_HEADER_SIZE; packet->ph.type = type; char* pMsg = (char*)packet; int iSend = 0; do { iSend = send(sock, &pMsg[sendbytes], iTotalsize - sendbytes, 0); if (CheckReturn(iSend) <= 0) { return iSend; } sendbytes += iSend; } while (sendbytes < iTotalsize); return sendbytes; } int Broadcastting(UPACKET* pPacket) { //EnterCriticalSection(&g_crit); int iUserCounter = 0; DWORD dwRet = WaitForSingleObject(g_hMutex, INFINITE); // 대기 함수 if (dwRet != WAIT_TIMEOUT) { for (ITOR itor = g_allClientSocket.begin(); itor != g_allClientSocket.end();) { SUser* pUser = (SUser*)&itor->second; if (pUser != nullptr) { int iSendByte = SendMsg(pUser->sock, (UPACKET*)pPacket, PACKET_CHAT_MSG); if (CheckReturn(iSendByte) <= 0) { printf("\n 퇴장(send) : IP :%s, PORT:%d\n", inet_ntoa(pUser->clientaddr.sin_addr), ntohs(pUser->clientaddr.sin_port)); g_allClientSocket.erase(itor++); } else { iUserCounter++; ++itor; } } } } //LeaveCriticalSection(&g_crit); ReleaseMutex(g_hMutex); return -1; } void DeleteUser(SOCKET sock) { //EnterCriticalSection(&g_crit); DWORD dwRet = WaitForSingleObject(g_hMutex, INFINITE); // 대기 함수 ITOR itor = g_allClientSocket.find(sock); if (itor != g_allClientSocket.end()) { SUser* pUser = (SUser*)&itor->second; if (pUser != nullptr) { printf("\n퇴장(sock) : IP: %s, PORT : %d\n", inet_ntoa(pUser->clientaddr.sin_addr), ntohs(pUser->clientaddr.sin_port)); } g_allClientSocket.erase(itor); } closesocket(sock); //LeaveCriticalSection(&g_crit); ReleaseMutex(g_hMutex); } void GreetMessage(SUser& user) { printf("\n 클라이언트 접속 : IP:%s, PORT:%d\n", inet_ntoa(user.clientaddr.sin_addr), ntohs(user.clientaddr.sin_port)); char message[MAX_PATH] = { 0, }; sprintf_s(message, "[서버] 환영합니다"); SendMsg(user.sock, message, PACKET_CHAT_MSG); DWORD dwRet = WaitForSingleObject(g_hMutex, INFINITE); // 대기 함수 g_allClientSocket.insert(make_pair(user.sock, user)); ReleaseMutex(g_hMutex); } DWORD WINAPI ClientThread(LPVOID arg) { SOCKET sock = (SOCKET)arg; SUser* pUser = &g_allClientSocket[sock]; char buffer[256] = { 0, }; int recvbyte = 0; int iRet = 0; while (1) { iRet = recv(sock, &buffer[recvbyte], PACKET_HEADER_SIZE - recvbyte, 0); if (CheckReturn(iRet) <= 0) { break; } recvbyte += iRet; if (recvbyte == PACKET_HEADER_SIZE) { UPACKET packet; ZeroMemory(&packet, sizeof(packet)); memcpy(&packet.ph, buffer, PACKET_HEADER_SIZE); int rByte = 0; int iRecvByte = 0; do { rByte = recv(sock, (char*)&packet.msg[iRecvByte], packet.ph.len - iRecvByte, 0); if (CheckReturn(iRet) <= 0) { break; } iRecvByte += rByte; } while (packet.ph.len > iRecvByte); if (CheckReturn(iRet) <= 0) { break; } recvbyte = 0; switch (packet.ph.type) { case PACKET_CHAT_MSG: { std::cout << "패킷 완성---->" << packet.msg; Broadcastting(&packet); }break; } } Sleep(1); } DeleteUser(sock); return 0; } // 소켓 생성 // 연결형, TCP프로토콜(SOCK_STREAM,IPPROTO_TCP) // 비연결형 UDP프로토콜 (SOCK_DGRAM,IPPROTO_UDP) int main(int argc, char* argv[]) { HANDLE hExecutMutex = CreateMutex(NULL, FALSE, L"OnceMutex"); if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(hExecutMutex); return 1; } InitializeCriticalSection(&g_crit); //TRUE = 현재의 스레드가 소유자 //FALSE = 소유자가 없다. (신호상태) : 비신호 상태 g_hMutex = CreateMutex(NULL, FALSE, L"CHAT_MUTEX"); unsigned short iPort = 10000; //atoi(argv[1]); // 윈도우 소켓 (윈속) 초기화 WSADATA wsa; int iRet; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return 1; } { SOCKET listenSock = socket(AF_INET, SOCK_STREAM, 0); { SOCKADDR_IN sa; ZeroMemory(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(iPort); sa.sin_addr.s_addr = htonl(INADDR_ANY); // 소켓을 대상 ip에 연결해라. iRet = bind(listenSock, (SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR)return -1; iRet = listen(listenSock, SOMAXCONN); if (iRet == SOCKET_ERROR)return -1; SOCKADDR_IN clientaddr; SOCKET client; while (1) { int addlen = sizeof(clientaddr); client = accept(listenSock, (SOCKADDR*)&clientaddr, &addlen); if (client == INVALID_SOCKET) break; SUser user(client, clientaddr); //EnterCriticalSection(&g_crit); // 신호 상태 일 경우만 진입 WaitForSingleObject(g_hMutex, INFINITE); // 대기 함수 GreetMessage(user); //LeaveCriticalSetion(&g_crit); ReleaseMutex(g_hMutex); // 비신호상태로 전환 DWORD dwRecvThreadID; HANDLE hThread = NULL; hThread = CreateThread(0, 0, ClientThread, (LPVOID)client, 0, &dwRecvThreadID); CloseHandle(hThread); } } closesocket(listenSock); } // 윈도우 소켓 소멸 iRet = WSACleanup(); DeleteCriticalSection(&g_crit); CloseHandle(g_hMutex); CloseHandle(hExecutMutex); return 0; }<file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #include "targetver.h" #include <istdplug.h> #include <iparamb2.h> #include <iparamm2.h> #include <maxtypes.h> #include <utilapi.h> #include <max.h> #include <stdmat.h> #include <decomp.h> #include <CS/bipexp.h> #include <CS/phyexp.h> #include <iskin.h> #include <string> #include <vector> #include <map> using namespace std;<file_sep>#pragma once #include "S_Core.h" #include "S_ChatUdp.h" class S_ChatMain : public S_Core { public: S_ChatUdp m_UDP; public: bool Init(); bool Release(); bool PreRender() { return true; } bool PostRender() { return true; } public: LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: S_ChatMain(); virtual ~S_ChatMain(); }; <file_sep>#pragma once #include "DDefine.h" using namespace std; class DDirectWrite { public: float m_fDPIScaleX; float m_fDPIScaleY; FLOAT m_fdpiX; FLOAT m_fdpiY; HWND m_hWnd; ID2D1RenderTarget* m_pRT; ID2D1Factory* m_pD2DFactory; ID2D1SolidColorBrush* m_pBlackBrush; IDWriteFactory* m_pDWriteFactory; IDWriteTextFormat* m_pTextFormat; IDWriteTextLayout* m_pTextLayout; public: DWRITE_FONT_WEIGHT m_fontWeight; DWRITE_FONT_STYLE m_fontStyle; BOOL m_fontUnderline; wstring m_wszFontFamily; float m_fontSize; wstring m_wszText; UINT32 m_cTextlength; public: // 초기화 bool Set(HWND hWnd, int iWidth, int iHeight, IDXGISurface1* m_pSurface); bool Init(); // 랜더링 bool Begin(); HRESULT DrawText(RECT rc, TCHAR* pText, D2D1::ColorF Color = D2D1::ColorF(1, 0, 0, 1)); HRESULT DrawText(D2D1_POINT_2F origin, D2D1::ColorF Color = D2D1::ColorF(1, 0, 0, 1)); bool End(); // 전체 소멸 bool Release(); // 객체 생성 및 소멸 HRESULT CreateDeviceIndependentResources(); void DiscardDeviceIndependentResources(); HRESULT CreateDeviceResources(IDXGISurface1* m_pSurface); void DiscardDeviceResources(); public: HRESULT SetText(D2D1_POINT_2F pos,const wchar_t *text, D2D1::ColorF Color); HRESULT SetFont(wchar_t *fontFamily); HRESULT SetFontSize(float size); HRESULT SetBold(bool bold); HRESULT Setltalic(bool italic); HRESULT SetUnderline(bool underline); // 화면 사이즈 변경 void OnResize(UINT width, UINT height, IDXGISurface1 *pSurface); public: DDirectWrite(); virtual ~DDirectWrite(); }; <file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++에서 생성한 포함 파일입니다. // UITOOL.rc에서 사용되고 있습니다. // #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDR_POPUP_EDIT 119 #define ID_STATUSBAR_PANE1 120 #define ID_STATUSBAR_PANE2 121 #define IDS_STATUS_PANE1 122 #define IDS_STATUS_PANE2 123 #define IDS_TOOLBAR_STANDARD 124 #define IDS_TOOLBAR_CUSTOMIZE 125 #define ID_VIEW_CUSTOMIZE 126 #define IDR_MAINFRAME 128 #define IDR_MAINFRAME_256 129 #define IDR_UITOOLTYPE 130 #define IDR_THEME_MENU 200 #define ID_SET_STYLE 201 #define ID_VIEW_APPLOOK_WIN_2000 205 #define ID_VIEW_APPLOOK_OFF_XP 206 #define ID_VIEW_APPLOOK_WIN_XP 207 #define ID_VIEW_APPLOOK_OFF_2003 208 #define ID_VIEW_APPLOOK_VS_2005 209 #define ID_VIEW_APPLOOK_VS_2008 210 #define ID_VIEW_APPLOOK_OFF_2007_BLUE 215 #define ID_VIEW_APPLOOK_OFF_2007_BLACK 216 #define ID_VIEW_APPLOOK_OFF_2007_SILVER 217 #define ID_VIEW_APPLOOK_OFF_2007_AQUA 218 #define ID_VIEW_APPLOOK_WINDOWS_7 219 #define IDS_EDIT_MENU 306 #define IDD_INTERFACE 314 #define IDCANCEL 1005 #define IDC_BUTTON1 1006 #define IDC_BUTTON2 1014 #define IDC_BUTTON3 1015 #define IDC_BUTTON4 1016 #define IDC_BUTTON5 1017 #define IDC_CHECK6 1027 #define IDC_CHECK7 1028 #define IDC_CHECK8 1029 #define IDC_CHECK9 1030 #define IDC_CHECK10 1031 #define IDC_BUTTON6 1032 #define IDC_BUTTON7 1033 #define IDC_BUTTON8 1034 #define IDC_BUTTON9 1035 #define IDC_BUTTON10 1036 #define IDC_BUTTON11 1037 #define IDC_BUTTON12 1038 #define IDC_LIST1 1040 #define IDC_SCROLLBAR1 1043 #define IDC_BUTTON13 1045 #define IDC_BUTTON14 1046 #define IDC_BUTTON15 1047 #define IDC_BUTTON16 1048 #define IDC_BUTTON17 1049 #define IDC_BUTTON18 1050 #define IDC_EDIT1 1052 #define ID_INTERFACE 32771 #define ID_SOUND 32772 #define ID_TEXTURE 32773 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 316 #define _APS_NEXT_COMMAND_VALUE 32774 #define _APS_NEXT_CONTROL_VALUE 1053 #define _APS_NEXT_SYMED_VALUE 310 #endif #endif <file_sep>#pragma once #include "S_Thread.h" class S_Acceptor : public S_Thread { public: SOCKET m_ListenSock; public: bool Run(); bool Release(); bool Set(int iPort, const char* strAddress = 0); virtual void AddUser(SOCKET socket, SOCKADDR_IN address); public: S_Acceptor(); virtual ~S_Acceptor(); }; <file_sep>//bridge는 '무엇인가를 연결한다'는 의미이다. bridge 패턴도 두 장소를 연결하는 역할을 한다. //bridge 패턴은 기능의 클래스 계층과 구현의 클래스 계층을 연결하고, //구현부에서 추상 계층을 분리하여 각자 독립적으로 변형할 수 있게 해준다. #include <iostream> #include <string> using namespace std; class BTree { }; class SearchEngineImp { public: virtual bool Search(string s, string idxFn) = 0; virtual bool Search(string s, BTree& bTree) = 0; }; class UnixSearchEngineImp : public SearchEngineImp { public: bool Search(string s, string idxFn) { // -- Unix 환경에 맞추어 idxFn 에서 문자열 검색 return true; } bool Search(string s, BTree& bTree) { // -- Unix 환경에 맞추어 BTree 에서 문자열 검색 return true; } }; class WindowsSearchEnginelmp : public SearchEngineImp { public: bool Search(string s, string idxFn) { //-- MS Windows 환경에 맞추어 idxFn에서 문자열 검색 return true; } bool Search(string s, BTree& bTree) { //-- MS Windows 환경에 맞추어 BTree 에서 문자열 검색 return true; } }; class SearchEngine { public: SearchEngine() { plmp_ = 0; } virtual bool Search(string s) = 0; protected: SearchEngineImp * GetSearchEnginelmp() { if (plmp_ == 0) { #ifdef __WIN32__ plmp_ = new WindowsSearchEnginelmp; #else plmp_ = new UnixSearchEngineImp; #endif } return plmp_; } private: SearchEngineImp * plmp_; }; class WebSearchEngine : public SearchEngine { public: WebSearchEngine(string idxFn) { indexFn_ = idxFn; } bool Search(string s) { return GetSearchEnginelmp()->Search(s, indexFn_); } private: string indexFn_; }; class DBSearchEngine : public SearchEngine { public: bool Search(string s) { return GetSearchEnginelmp()->Search(s, bTree_); } private: BTree bTree_; }; void main() { WebSearchEngine finder("inverted_file4web.idx"); finder.Search("디자인 패턴"); }<file_sep>#include<stdio.h> //다중 배열 포인터 void main() { int c; int arr[9][9]; printf("input num\n"); scanf_s("%d",&c); for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { arr[i - 1][j - 1] = (i)*(j); } } for (int z = 0; z <= 8; z++) printf("\n%d*%d=%d", c, z + 1, *(*(arr + c - 1) + z)); }<file_sep>#pragma once #include <iostream> #include <conio.h> using namespace std; struct Node { Node* m_pNext; int iData; int iCount; Node (int pData) { iData = pData; }; }; class LinkedListSing { public: Node* m_Head; Node* m_Tail; int i_MAX; public: void Add(); void Del(int aData); void print(); void Find(int sData); public: LinkedListSing(); ~LinkedListSing(); }; <file_sep>#pragma once #include "ODBCSTD.h" class DB_CONNECT { public: SQLHENV m_hENV; // 환경핸들 SQLHDBC m_hDBC; // 연결핸들 SQLHSTMT m_hSTMT; // 명령핸들 public: bool DBConnect(); // 접속 및 버전 void DBDisConnect(); // 해제 public: DB_CONNECT(); virtual ~DB_CONNECT(); }; <file_sep>#include<stdio.h> int main(void) { unsigned char fourBitVal1 = 0x05, fourBitVal2 = 0x07; unsigned char eightBitVal; eightBitVal = fourBitVal1 << 4; eightBitVal |= fourBitVal2; printf("%x,%x_>%x\n", fourBitVal1, fourBitVal2, eightBitVal); return 0; }<file_sep>#pragma once #include "S_SvrUser.h" class S_ChatUser : public S_SvrUser { public: int m_iIndex; int m_PositionX; int m_PositionY; int m_iDirection; public: void MoveMent(UPACKET* pPacket); void AddPacket(PACKET& addPacket); void DeleteUser(SOCKET socket); void DeleteUser(); void Dispatch(DWORD dwByteSize, LPOVERLAPPED OV); public: S_ChatUser(); virtual ~S_ChatUser(); }; <file_sep>#pragma once #include "SThread.h" class SWorkThread : public SThread { public: HANDLE m_hIOCP; bool Run(); void Set(HANDLE hIOCP) { m_hIOCP = hIOCP; }; public: SWorkThread(void); virtual ~SWorkThread(void); }; <file_sep>#include "SStudent.h" #include "LinkedList.h" int main() { cout << "========================================\n" << endl; cout << "============성적관리프로그램============\n" << endl; cout << "========================================\n " << endl; int MaxCount = 0; LinkedList FIND; while (1) { cout << "신규(1)" << "출력(2)" << "번호검색(3)" << "저장(4)" << "불러오기(5)" <<"추가(6)"<<"삭제(7)"<< "종료(6)" << endl; scanf("%d", &MaxCount); if (MaxCount == EXIT)break; system("cls"); switch (MaxCount) { case DataNew: { FIND.Insert(); }break; case DataPrint: { FIND.printAll(); }break; case IndexFind: { FIND.Find(); }break; case SaveData: { FIND.save(); }break; case LoadData: { FIND.Load(); }break; case AddData: { }break; case DelData: { }break; } } _getch(); return 0; }<file_sep>#include<stdio.h> void func() { int a = 0; a = a + 1; printf("%d\n", a); } void main() { func(); func(); func(); }<file_sep>#pragma once #include <windows.h> #include "TProtocol.h" #define PACKETBUFFERSIZE 8192 class TPacket { public: typedef struct { WORD* len; WORD* type; }PACKETHEADER; public: PACKETHEADER m_PacketHeader; char m_strPacketBuffer[PACKETBUFFERSIZE]; char* m_pstrWritePosition; char* m_pstrReadPosition; WORD GetID(); WORD GetSize(); int m_iReceivedSize; int GetDataSize(); void ReadData( void* buffer, int iSize ); void WriteData( void* buffer, int iSize ); TPacket& SetID( unsigned short ID ); // 패킷을 생성할 때 TPacket& operator << ( int arg ); // 패킷에서 데이터를 추출할 때 TPacket& operator >> ( int& arg ); TPacket& operator << ( DWORD arg ); TPacket& operator >> ( DWORD& arg ); TPacket& operator << ( bool arg ); TPacket& operator >> ( bool& arg ); TPacket& operator << ( unsigned short arg ); TPacket& operator >> ( unsigned short& arg ); TPacket& operator << ( float arg ); TPacket& operator >> ( float& arg ); TPacket& operator << ( char* arg ); TPacket& operator >> ( char* arg ); TPacket& operator << ( TPacket& arg ); TPacket& operator >> ( TPacket& arg ); char* GetData(); void Clear(); public: TPacket(void); TPacket(unsigned short type); virtual ~TPacket(void); }; <file_sep>#pragma once #include "TWorkThread.h" #include "TUser.h" #define WORKDER_THREAD_COUNT 3 class TServerIOCP : public TSingleton<TServerIOCP>, public TServerObj { private: friend class TSingleton<TServerIOCP>; public: HANDLE m_hIOCP; TWorkThread m_WorkerThread[WORKDER_THREAD_COUNT]; public: bool Init(); bool Release(); void AddHandleToIOCP( HANDLE hClientSocket, ULONG_PTR dwReturnKey); public: TServerIOCP(void); ~TServerIOCP(void); }; #define I_ServerIOCP TServerIOCP::GetInstance() <file_sep>#pragma once #include "DXWindow.h" #include "assert.h" #include "tchar.h" #include "d3dx11.h" #include "d3d11.h" #include "d3dx11.h" #include <dxgi.h> #include <set> #include <list> #include <string> #include <map> #include <vector> #include <algorithm> #include <bitset> #include <limits> #include <functional> using namespace std; #pragma comment (lib,"dxerr.lib") #pragma comment (lib,"dxguid.lib") #pragma comment (lib,"d3d11.lib") #pragma comment (lib,"dxgi.lib") #if defined(DEBUG) || defined(_DEBUG) #pragma comment(lib,"d3dx11d.lib") #else #pragma comment(lib,"d3dx11.lib") #endif #pragma comment(lib,"d3dcompiler.lib") #pragma comment(lib,"winmm.lib") #pragma comment (lib, "comct132.lib") typedef basic_string<TCHAR> T_STR; typedef basic_string<TCHAR>::iterator T_ITOR; typedef vector<basic_string<TCHAR>> T_STR_VECTOR; typedef vector<string> C_STR_VECTOR; typedef list<basic_string<TCHAR>> T_STR_LIST; typedef string CHAR_STRING; typedef vector<DWORD> DWORD_VECTOR; typedef vector< DWORD >::iterator DWORD_VECTOR_ITOR; typedef list<DWORD> DWORD_LIST; typedef list<DWORD>::iterator DWORD_LIST_ITOR; typedef list< HANDLE > HANDLE_LIST; typedef list< HANDLE >::iterator HANDLE_LIST_ITOR; ////////////////////////////////////////////// // DX 매소드 호출에 대한 반환값 처리 매크로 ////////////////////////////////////////////// #ifndef V #define V(x) { hr = (x); } #endif #ifndef V_RETURN #define V_RETURN(x){ hr = (x); if( FAILED(hr) ) { return hr; } } #endif ////////////////////////////////////////////// // 객체 및 배열 할당과 삭제 및 소멸 매크로 ////////////////////////////////////////////// #ifndef SAFE_ZERO #define SAFE_ZERO(A) { A = 0; } #endif #ifndef SAFE_NEW #define SAFE_NEW(A, B) { if (!A) A = new B; } #endif #ifndef SAFE_DEL #define SAFE_DEL(A) { if (A) delete A; (A)=NULL; } #endif #ifndef SAFE_NEW_ARRAY #define SAFE_NEW_ARRAY(A, B, C) { if (!A && C) A = new B[C]; } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(A) { if (A) delete [] A; (A)=NULL; } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(A) { if(A) { (A)->Release(); (A)=NULL; } } #endif #ifndef SAFE_NEW_CLEAR #define SAFE_NEW_CLEAR( A, B ) { if (!A) A = new B; if(A) memset( A, 0, sizeof(B) ); }; #endif #ifndef SAFE_NEW_ARRAY_CLEAR #define NEW_ARRAY_CLEAR( A, B, C ) { if (!A && C) A = new B[C]; if(A) memset( A, 0, sizeof(B)*C ); }; #endif <file_sep>#pragma once #include "DXWindow.h" class Sample : public DXWindow { public: Sample(void); ~Sample(void); };<file_sep>#include "S_KHJGlobal.h" void S_KHJGlobal::Initialize(Interface *i, TSTR name) { m_pMax = i; m_szFileName = name; m_pRootNode = m_pMax->GetRootNode(); m_Interval = m_pMax->GetAnimRange(); m_Scene.iFirstFrame = m_Interval.Start() / GetTicksPerFrame(); m_Scene.iLastFrame = m_Interval.End() / GetTicksPerFrame(); m_Scene.iFrameSpeed = GetFrameRate(); m_Scene.iTickPerFrame = GetTicksPerFrame(); // 전역/ 160 PreProcess(m_pRootNode); } void S_KHJGlobal::AddObject(INode*pNode) { ObjectState os = pNode->EvalWorldState( // 오브젝트 상태 m_Interval.Start()); if (os.obj) { switch (os.obj->SuperClassID()) { case GEOMOBJECT_CLASS_ID: case HELPER_CLASS_ID: //geomobject //helperobject m_ObjectList.push_back(pNode); } } } void S_KHJGlobal::AddMtl(INode*pNode) { Mtl* pMtl = pNode->GetMtl(); if (pMtl != NULL) // NULL 과 같지 않다면 있다 { bool bAdd = true; // flag 값 for (int iCnt = 0; iCnt <m_MtrlList.size(); iCnt++) { if (m_MtrlList[iCnt] == pMtl) { bAdd = false; break; } } if (bAdd) { m_MtrlList.push_back(pMtl); } } } void S_KHJGlobal::PreProcess(INode* pNode) { if (pNode == NULL)return; AddObject(pNode); AddMtl(pNode); int iNumChild = pNode->NumberOfChildren(); for (int iChild = 0; iChild < iNumChild; iChild++) { INode* pChild = pNode->GetChildNode(iChild); PreProcess(pChild); } } S_KHJGlobal::S_KHJGlobal() { } S_KHJGlobal::~S_KHJGlobal() { } <file_sep>#include "Sample.h" bool Sample::Init() { HRESULT hr; if (FAILED(hr = CreateDXGIFactory())) { DXTRACE_MSG(DXGetErrorDescription(hr), hr); return false; } if (FAILED(hr = CreateDevice())) { DXTRACE_MSG(DXGetErrorDescription(hr)); return false; } if (FAILED(hr = CreateSwapChain(m_hWnd, this->m_iWindowWidth, this->m_iWindowHeight))) { DXTRACE_MSG(DXGetErrorDescription(hr), hr); return false; } if (FAILED(hr = SetRenderTargetView())) { DXTRACE_MSG(DXGetErrorDescription(hr), hr); } if (FAILED(hr = SetViewPort())) { DXTRACE_MSG(DXGetErrorDescription(hr), hr); return false; } return true; } bool Sample::Render() { DXGI_SWAP_CHAIN_DESC CurrentSD; m_pSwapChain->GetDesc(&CurrentSD); GetClientRect(m_hWnd, &m_rcWindowClient); float ClearColor[4] = { 0.0f,0.125f,0.3f,1.0f };//red,green,blue,alpha m_plmmediateContext->ClearRenderTargetView(m_pRenderTargetView, ClearColor); m_pSwapChain->Present(0, 0); return true; } bool Sample::Release() { if (!CleanupDevice())return false; return true; } Sample::Sample(void) { } Sample::~Sample(void) { } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { Sample gSample; if (!gSample.InitWindow(hInstance, nCmdShow, L"CreateDevice_1")) { MessageBox(0, _T("Sample 초기화 실패"), _T("Fatal error"), MB_OK); return 0; } ShowCursor(TRUE); gSample.Run(); return 1; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<conio.h> int main(int argc, char*argv[]) { FILE*fp; char c; if (argc == 1)//인자가 없으면 { printf("USAGE: %s filename(1)...filename(n)\n", *argv); return (1); } while (--argc > 0)//인자가 있으면 if ((fp = fopen(*++argv, "r")) == NULL) { printf("Error:Cannot open %s\n", *argv); continue; } printf("\n***%s***\n", argv); while ((c = getc(&fp)) != EOF) putchar(c); fclose(fp); _getch(); }<file_sep>#pragma once #include <iostream> using namespace std; class TFigure { public: void Move(int x, int y); //도형 이동 void Resize(int width, int height); // 도형 크기 virtual void Draw(); protected: int x; //중심의 x좌표 int y; //중심의 y좌표 int width; //가로길이 int height; //세로 길이 public: TFigure(); TFigure(int x, int y, int width , int height); ~TFigure(); }; <file_sep>#pragma once #include "SThread.h" class SAcceptor : public SThread { public: SOCKET m_ListenSock; // 소켓 생성 public: bool Run(); // 돌리는 함수 bool Release(); // 소멸함수 bool Set(int iPort, const char* strAddress = 0); // 포트와 주소를 세팅 하는 함수 virtual void AddUser(SOCKET socket, SOCKADDR_IN address); // 유저 추가하는 함수 public: SAcceptor(void); virtual ~SAcceptor(void); }; <file_sep>#pragma once #include "TFigure.h" class TRectangle:public TFigure { public: void Draw(); //오버라이딩 public: TRectangle(); TRectangle(int x, int y,int width, int height); ~TRectangle(); }; <file_sep>#include "S_SvrObj.h" S_SvrObj::S_SvrObj() { InitializeCriticalSection(&m_Ct); } S_SvrObj::~S_SvrObj() { DeleteCriticalSection(&m_Ct); } <file_sep>#include "Header.h" #include "S_Writer.h" #define KHJEXP_CLASS_ID Class_ID(0x79537139, 0x5c066d4f) class KHJExporter : public SceneExport { public: KHJExporter(); ~KHJExporter(); public: int ExtCount(); const TCHAR* Ext(int n); const TCHAR* LongDesc(); const TCHAR* ShortDesc(); const TCHAR* AuthorName(); const TCHAR* CopyrightMessage(); const TCHAR* OtherMessage1(); const TCHAR* OtherMessage2(); unsigned int Version(); void ShowAbout(HWND hWnd); BOOL SupportsOptions(int ext, DWORD options); int DoExport(const TCHAR* name, ExpInterface* ei, Interface *i, BOOL suppressPrompts = FALSE, DWORD options = 0); }; class KHJExporterClassDesc : public ClassDesc2 { public: virtual int IsPublic() { return TRUE; } virtual void* Create(BOOL) { return new KHJExporter(); } virtual const TCHAR* ClassName() { return _T("KHJExporter100"); } virtual SClass_ID SuperClassID() { return SCENE_EXPORT_CLASS_ID; } virtual Class_ID ClassID() { return KHJEXP_CLASS_ID; } virtual const TCHAR* Category() { return _T("KHJExporter"); } virtual const TCHAR* InternalName() { return _T("KHJExporterClassDesc"); } virtual HINSTANCE Hinstance() { return hInstance; } }; ClassDesc2* GetExportDesc() { static KHJExporterClassDesc KHJExportDesc; return &KHJExportDesc; } KHJExporter::KHJExporter() { } KHJExporter::~KHJExporter() { } int KHJExporter::ExtCount() { return 1; } const TCHAR* KHJExporter::Ext(int n) { return _T("KHJ"); } const TCHAR* KHJExporter::LongDesc() { return _T("KHJ EXPOTER 2.0"); } const TCHAR* KHJExporter::ShortDesc() { return _T("KHJExpoter"); } const TCHAR* KHJExporter::AuthorName() { return _T("PROKVIP"); } const TCHAR* KHJExporter::CopyrightMessage() { return _T(""); } const TCHAR* KHJExporter::OtherMessage1() { return _T(""); } const TCHAR* KHJExporter::OtherMessage2() { return _T(""); } unsigned int KHJExporter::Version() { return 100; } void KHJExporter::ShowAbout(HWND) { } BOOL KHJExporter::SupportsOptions(int, DWORD) { return TRUE; } int KHJExporter::DoExport(const TCHAR* name, ExpInterface* ei, Interface* i, BOOL suppressPrompts, DWORD options) { I_Writer.Initialize(i); I_Writer.KHJExport(); return TRUE; }<file_sep>#pragma once #include <d3d11.h> namespace DX { class xDxState { public: static ID3D11DepthStencilState* g_pDSVStateEnableLessEqual; static ID3D11DepthStencilState* g_pDSVStateEnableGreater; static ID3D11DepthStencilState* g_pDSVStateDetphWriteDisable; static ID3D11RasterizerState* g_pRSWireFrame; static ID3D11RasterizerState* g_pRSSolid; static ID3D11RasterizerState* g_pRSBackCullSolid; static ID3D11RasterizerState* g_pRSFrontCullSolid; static ID3D11RasterizerState* g_pRSNoneCullSolid; static ID3D11RasterizerState* g_pRSBackCullWireFrame; static ID3D11RasterizerState* g_pRSFrontCullWireFrame; static ID3D11RasterizerState* g_pRSNoneCullWireFrame; static ID3D11BlendState* g_pBSNoBlend; static ID3D11BlendState* g_pBSAlphaBlend; static ID3D11SamplerState* g_pSSWrapLinear; static ID3D11SamplerState* g_pSSWrapPoint; static HRESULT SetState(ID3D11Device* pd3dDevice); static bool Release(); public: xDxState(); ~xDxState(); }; static void ApplyDSS(ID3D11DeviceContext* pContext, ID3D11DepthStencilState* pState, UINT iRef=0x01) { pContext->OMSetDepthStencilState(pState,iRef ); } static void ApplyRS(ID3D11DeviceContext* pContext, ID3D11RasterizerState* pState) { pContext->RSSetState(pState); } static void ApplyBS( ID3D11DeviceContext* pContext, ID3D11BlendState* pState, const float fBlendFactor[] = 0, UINT iMask = 0xffffffff) { pContext->OMSetBlendState(pState, fBlendFactor, iMask); } static void ApplySS(ID3D11DeviceContext* pContext, ID3D11SamplerState* pSamplerState, UINT iSlot = 0, UINT iArray = 1) { pContext->PSSetSamplers(iSlot, iArray, &pSamplerState); } } <file_sep>#include "xSkyBox.h" bool xSkyBox::Create(ID3D11Device* pDevice, T_STR szShaderName, T_STR szTextureName) { D3DXMatrixScaling(&m_matWorld, 100.0f, 100.0f, 100.0f); xShape::Create(pDevice, szShaderName, szTextureName); return true; } HRESULT xSkyBox::LoadTexture(T_STR szName) { HRESULT hr = S_OK; const TCHAR* g_szSkyTextures[] = { L"../../Sampleinclude/data/st00_cm_front.bmp", L"../../Sampleinclude/data/st00_cm_back.bmp", L"../../Sampleinclude/data/st00_cm_right.bmp", L"../../Sampleinclude/data/st00_cm_left.bmp", L"../../Sampleinclude/data/st00_cm_up.bmp", L"../../Sampleinclude/data/st00_cm_down.bmp" }; int iNumTexture = sizeof(g_szSkyTextures) / sizeof(g_szSkyTextures[0]); for (int iTex = 0; iTex < iNumTexture; iTex++) { m_pTexSRV[iTex].Attach(DX::CreateShaderResourceView(m_pd3dDevice, g_szSkyTextures[iTex])); } return hr; } bool xSkyBox::Render(ID3D11DeviceContext* pContext) { ApplySS(pContext, xDxState::g_pSSWrapPoint); //ApplyDSS(pContext, xDxState::g_pDSVStateDetphWriteDisable); D3DXMATRIX matView = m_matView; matView._41 = 0; matView._42 = 0; matView._43 = 0; SetMatrix(&m_matWorld, &matView, &m_matProj); pContext->UpdateSubresource(m_dxObj.m_pConstantBuffer.Get(),0, NULL, &m_cbData, 0, 0); pContext->IASetPrimitiveTopology((D3D_PRIMITIVE_TOPOLOGY)m_Primitive); PreRender(pContext); //-------------------------------------------------------------------------------------- // 한장씩 랜더링 하는 방법 //-------------------------------------------------------------------------------------- for (int iTex = 0; iTex < MAX_SKYBOX_TEXTURE; iTex++) { if (m_pTexSRV[iTex] == nullptr) break; pContext->PSSetShaderResources(0, 1, m_pTexSRV[iTex].GetAddressOf()); // 랜더링에 사용할 인덱스 버퍼 갯수, 인덱스 버퍼 시작, 버텍스 버퍼 시작 pContext->DrawIndexed(6, 6 * iTex, 0); } ApplySS(pContext, xDxState::g_pSSWrapLinear); //ApplyDSS(pContext, xDxState::g_pDSVStateEnableLessEqual); return true; } bool xSkyBox::Release() { xShape::Release(); return true; } xSkyBox::xSkyBox() { } xSkyBox::~xSkyBox() { } <file_sep>#include"StudentMgr2.h" void main() { srand(time(NULL)); int select; while (1) { printf("\n 신규:0 출력:1 검색이름 :2 번호검색:3 저장:4 불러오기:5 추가:6 삭제:7 수정:8종료(99)"); scanf_s("%d", &select); if (select == Exit)break; system("cls"); switch(select) { case NewData: { DataNew(); }break; case PrintData: { DataPrint(); }break; case FindNameData: { DataFindName(); }break; case FindIndexData: { DataFindIndex(); }break; case SaveData: { DataSave(); }break; case LoadData: { DataLoad(); }break; case AddData: { DataAdd(); }break; case DeleteData: { DataDelete(); }break; case EditData: { DataEdit(); }break; } } free(pStudentData); printf("\n 아무키나 누르면 종료됩니다"); _getch(); return 0; }<file_sep>#include<stdio.h> #include<conio.h> //다이아몬드 완성 .. 휴 void main() { for (int sum = 0; sum < 4; sum++) { for (int sum1 = 0; sum1 < 4-sum; sum1++) { printf(" "); } for (int sum2 = 0; sum2 <= sum*2; sum2++) { printf("*"); } printf("\n"); } for (int sum = 0; sum < 5; sum++) { for (int sum1 = 0; sum1 < sum; sum1++) { printf(" "); } for (int sum2 = 0; sum2 < 2 * (5 - sum) - 1; sum2++) { printf("*"); } printf("\n"); } _getch(); }<file_sep>#include "S_CharMgr.h" #include "TObjMgr.h" BOOL SCharacterLoader::GetDataFromSkinMeshString(const TCHAR* pString, VOID* pData0, VOID* pData1) { TCHAR szPath_0[MAX_PATH] = TEXT(""); TCHAR szPath_1[MAX_PATH] = TEXT(""); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%s%s"), m_pString, szPath_0, szPath_1); if (!_tcsicmp(m_pString, pString)) { _tcscpy((TCHAR*)pData0, &szPath_0[0]); _tcscpy((TCHAR*)pData1, &szPath_1[0]); return TRUE; } return FALSE; } int S_CharMgr::Create(ID3D11Device* pd3dDevice, ID3D11DeviceContext* plmmediateContext, const TCHAR* strFileName, const TCHAR* strShaderName, int iMatrixIndex) { TCHAR szFileName[256]; TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; if (strFileName) { _tsplitpath_s(strFileName, Drive, Dir, FName, Ext); Ext[4] = 0; _stprintf_s(szFileName, _T("%s%s"), FName, Ext); for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { S_Character *pPoint = (S_Character*)(*itor).second; if (!_tcsicmp(pPoint->m_szName.c_str(), szFileName)) { return (*itor).first; } } } S_Character* pChild = 0; SAFE_NEW(pChild, S_Character); pChild->m_szName = szFileName; pChild->m_pBoneObject = (TBoneObj*)I_ObjMgr.GetPtr(iMatrixIndex); pChild->SetActionFrame(pChild->m_pBoneObject->m_Scene.iFirstFrame, pChild->m_pBoneObject->m_Scene.iLastFrame, iMatrixIndex); { TMap.insert(make_pair(m_iCurIndex++, pChild)); return m_iCurIndex - 1; } return -1; } bool S_CharMgr::Load(ID3D11Device* pd3dDevice, ID3D11DeviceContext* plmmediateContext, const TCHAR* strFileName) { const TCHAR* Sections[] = { _T("*SKIN_UPPER_BODY_COUNT"), _T("*SKIN_UPPER_BODY"), _T("*SKIN_LOWER_BODY_COUNT"), _T("*SKIN_LOWER_BODY"), _T("*SKIN_ARM_COUNT"), _T("*SKIN_ARM"), _T("*SKIN_HAND_COUNT"), _T("*SKIN_HAND"), _T("*SKIN_FOOT_COUNT"), _T("*SKIN_FOOT"), _T("*SKIN_FACE_COUNT"), _T("*SKIN_FACE"), _T("*SKIN_HAIR_COUNT"), _T("*SKIN_HAIR"), _T("*SKIN_WEAPON_COUNT"), _T("*SKIN_WEAPON"), _T("*SKIN_DEFENSE_COUNT"), _T("*SKIN_DEFENSE"), _T("*SKIN_ETCETERA_COUNT"), _T("*SKIN_ETCETERA"), }; int iNumSection = sizeof(Sections) / sizeof(Sections[0]); m_Parser.OpenStream(strFileName); TCHAR strCharacterName[MAX_PATH] = { 0, }; TCHAR strMeshName[MAX_PATH] = { 0, }; TCHAR strShaderName[MAX_PATH] = { 0, }; TCHAR strMatrixName[MAX_PATH] = { 0, }; int iNumCharacter = 0; if (m_Parser.GetDataFromFileLoop(_T("*NUMCHARACTER"), &iNumCharacter, INT_DATA)) { float a, b, c; for (int iNum = 0; iNum < iNumCharacter; iNum++) { m_Parser.GetDataFromFileLoop(_T("*CHARACTERNAME"), strCharacterName, STRING_DATA); m_Parser.GetDataFromFileLoop(_T("*SHADERFILENMAE"), strShaderName, STRING_DATA); m_Parser.GetDataFromFileLoop(_T("*MATRIXFILENAME"), strMatrixName, STRING_DATA); int iNumSkin = 0; S_Character* pChar = 0; int iCharacterIndex = -1; int iMatrixIndex = -1; if (_tcsicmp(strMatrixName, _T("null"))) { iMatrixIndex = I_ObjMgr.Load(pd3dDevice, strMatrixName, _T("MatrixViewer.hlsl")); } iCharacterIndex = Create(pd3dDevice, plmmediateContext, strCharacterName, strShaderName, iMatrixIndex); if (iCharacterIndex < 0) continue; pChar = GetPtr(iCharacterIndex); for (int iMesh = 0; iMesh < iNumSection; iMesh += 2) { m_Parser.GetDataFromFileLoop(Sections[iMesh], &iNumSkin, INT_DATA); for (int iSkin = 0; iSkin < iNumSkin; iSkin++) { m_Parser.GetDataFromSkinMeshString(Sections[iMesh + 1], strMeshName, strMatrixName); int iModelMatrixIndex = -1; if (_tcsicmp(strMatrixName, _T("null"))) { iModelMatrixIndex = I_ObjMgr.Load(pd3dDevice, strMatrixName, _T("MatrixViewer.hlsl")); } if (pChar) { pChar->Add(pd3dDevice, plmmediateContext, strMeshName, strShaderName, iMatrixIndex, iModelMatrixIndex); } } } } } m_Parser.CloseStream(); return true; } S_CharMgr::S_CharMgr() { } S_CharMgr::~S_CharMgr() { } <file_sep>#pragma once #include "SPacketPool.h" #include "SProtocolChat.h" class SChatPacketPool : public SPacketPool { public: void ProcessWork(S_PACKET* pUserData); public: SChatPacketPool(void); virtual ~SChatPacketPool(void); }; <file_sep>#pragma once #include "xShape.h" struct xMapDesc { int iNumCols; int iNumRows; float fDistance; float fScaleHeight; T_STR szTextureFile; T_STR szShaderFile; }; class xMap : public xShape { public: xMapDesc m_xMapDesc; int m_iNumRows; int m_iNumCols; int m_iNumCellRows; int m_iNumCellCols; int m_iNumFace; int m_iNumVertices; float m_fCellDistance; float m_fScaleHeight; vector<float> m_fHeightList; public: virtual HRESULT CreateVertexData() override; virtual HRESULT CreateIndexData() override; D3DXVECTOR2 GetTextureOfVertex(float fU, float fV); D3DXVECTOR3 GetNormalOfVertex(int iIndex); D3DXVECTOR4 GetColorOfVertex(int iIndex); float GetHeightOfVertex(int iIndex); // 기하쉐이더(기본값은 구를 생성) 생략함. HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; bool CreateHeightMap( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, T_STR szName); bool CreateMap(xMapDesc desc); bool Load(ID3D11Device* pDevice,xMapDesc desc); bool Init(); bool Frame(); bool Render(ID3D11DeviceContext* pContext); bool Release(); public: xMap(); virtual ~xMap(); }; <file_sep>#pragma once #include "Std.h" /* 1) 1프레임의 경과 시간=m_fSecPerFrame 2) 1초의 프레임 카운터 3) 게임이 실행된 누적시간 */ class Timer { DWORD m_dwFrameCount; DWORD m_dwFPS; DWORD m_dwBeforeTick; float m_fSecPerFrame; float m_fGameTimer; float m_fTimer; TCHAR m_csBuffer[256]; public: bool Init(); //초기화 bool Frame(); //계산 bool Render(); //드로우 bool Release(); //소멸, 삭제 public: Timer(); virtual ~Timer(); }; <file_sep>#include "TUdpSocket.h" #include "SDebugString.h" bool TUdpSocket::Init() { m_SendSocket = socket( AF_INET, SOCK_DGRAM, 0 ); m_Socket = socket( AF_INET, SOCK_DGRAM, 0 ); int optval = 1; setsockopt( m_SendSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); setsockopt( m_Socket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); m_RecvAddr.sin_family = AF_INET; m_RecvAddr.sin_port = htons(10001); m_RecvAddr.sin_addr.s_addr= htonl(INADDR_ANY); int retval = ::bind( m_Socket, (SOCKADDR*)&m_RecvAddr, sizeof(m_RecvAddr)); if( retval == SOCKET_ERROR ) return false; BOOL bEnable = TRUE; retval = setsockopt( m_SendSocket, SOL_SOCKET, SO_BROADCAST, (char*)&bEnable, sizeof(bEnable)); if( retval == SOCKET_ERROR ) return false; m_SendAddr.sin_family = AF_INET; m_SendAddr.sin_port = htons(9001); m_SendAddr.sin_addr.s_addr= htonl(INADDR_BROADCAST); CreateThread(); return true; } bool TUdpSocket::Run() { int retval, addrlen; SOCKADDR_IN PeerAddr; char buf[2048]= {0,}; while(1) { addrlen = sizeof(PeerAddr); retval = recvfrom(m_Socket, buf, 2048, 0, (SOCKADDR*)&PeerAddr, &addrlen); if( retval == SOCKET_ERROR ) { I_Debug.Print("[%s]", "Error!!!!!"); break; } I_Debug.Print("[RECV]IP=%s, PORT=%d, %s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buf); //I_Debug.Print("%s ¹Þ°í", buf); buf[retval] = 0; retval = sendto(m_SendSocket, buf, strlen(buf), 0, (SOCKADDR*)&m_SendAddr, sizeof(m_SendAddr)); if( retval == SOCKET_ERROR ) { I_Debug.T_ERROR(true); I_Debug.Print("[%s]", "Error!!!!!"); break; } I_Debug.Print("[SEND]IP=%s, PORT=%d, %s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buf); } closesocket(m_Socket); m_Socket = 0; return true; } bool TUdpSocket::Release() { if(m_Socket != 0 ) { closesocket(m_Socket); m_Socket = 0; } return true; } TUdpSocket::TUdpSocket(void) { m_Socket = 0; } TUdpSocket::~TUdpSocket(void) { } <file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #define ID_ASE_AM 0 // ambient #define ID_ASE_DI 1 // diffuse #define ID_ASE_SP 2 // specular #define ID_ASE_SH 3 // shininesNs #define ID_ASE_SS 4 // shininess stregth #define ID_ASE_SI 5 // self-illumination #define ID_ASE_OP 6 // opacity #define ID_ASE_FI 7 // filter color #define ID_ASE_BU 8 // bump #define ID_ASE_RL 9 // reflection #define ID_ASE_RR 10 // refraction #define ID_ASE_DP 11 // displacement #define ID_ASE_GN 12 // Generic #define ID_ASE_EV 13 // EnvMap #include "xStd.h" struct xScene { int iFirstFrame; int iLastFrame; int iFrameSpeed; int iTickPerFrame; }; struct xTextureMap { int iType; T_STR name; }; struct xMtrlerial { vector<xTextureMap> m_mapList; vector<xMtrlerial> m_SubMaterial; }; struct xIndex { int i[3]; int iSubMtrl; }; struct xGeomMesh { int mtrlRef; T_STR name; D3DXMATRIX matWorld; vector<D3DXVECTOR3> vertexList; vector<xIndex> PosFaceList; vector<D3DXVECTOR3> texList; vector<xIndex> texFaceList; vector<D3DXVECTOR3> ColList; vector<xIndex> ColFaceList; vector<D3DXVECTOR3> NorList; }; class x_AseMesh { public: xScene m_Scene; FILE* m_pStream; int m_iTemp; TCHAR m_pBuffer[256]; TCHAR m_pString[256]; TCHAR m_pString2[256]; xMtrlerial xMtrl; xTextureMap tMap; vector<xMtrlerial> m_MaterialList; vector<xGeomMesh> m_ObjectList; public: bool Load(T_STR name); void LoadScene(); void LoadMaterial(); void LoadGeomObject(); void GetData(void* pData); bool FineString(T_STR find); void LoadVertexData(D3DXVECTOR3& v, bool bSwap = true); void LoadIndexData(xIndex& v); public: x_AseMesh(); virtual ~x_AseMesh(); }; <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") void Error(char* msg) { LPVOID lpMsgBuffer; int iError = WSAGetLastError(); FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, iError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuffer, 0, NULL); printf("%s", lpMsgBuffer); LocalFree(lpMsgBuffer); exit(-1); } void main() { WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { return; } SOCKET SendSock = socket(AF_INET, SOCK_DGRAM, 0); if (SendSock == INVALID_SOCKET) { Error("sock invalid"); } int mulTTL = 64;// 기본값 128 setsockopt(SendSock, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&mulTTL, sizeof(mulTTL)); // 전송할 인터페이스 지정 : 기본 라우터 테이블 첫번째 인터페이스가 된다. ULONG localif = inet_addr("192.168.0.101"); setsockopt(SendSock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localif, sizeof(localif)); //전송시는 그룹에 가입하지 않아도 된다. SOCKADDR_IN serveradd; ZeroMemory(&serveradd, sizeof(serveradd)); serveradd.sin_family = AF_INET; serveradd.sin_port = htons(10000); serveradd.sin_addr.s_addr = inet_addr("172.16.17.32"); SOCKADDR_IN clientAddr; char buf[256] = { 0, }; char recvbuf[256] = { 0, }; int addlen; int iCount = 0; while (1) { sprintf(buf, "%s:%d", "kgca", iCount++); int iRet = sendto(SendSock, buf, strlen(buf), 0, (SOCKADDR*)&serveradd, sizeof(serveradd)); if (iRet == SOCKET_ERROR) { Error("sock invalid"); } Sleep(1000); } WSACleanup(); }<file_sep>#pragma once #include "xStd.h" #include "xShape.h" struct xMapDesc { int iNumCols; // 가로 개수 int iNumRows; // 세로 개수 float fDistance; float fScaleHeight; T_STR szTextureFile; T_STR szShaderFile; }; class xMap : public xBoxShape { public: xMapDesc m_xMapDesc; public: int m_iNumRows; int m_iNumCols; int m_iNumCellRows; int m_iNumCellCols; int m_iNumFace; int m_iNumVertices; float m_fColliDistance; public: bool CreateMap(xMapDesc desc); bool Load(ID3D11Device* pDevice, xMapDesc desc); bool CreateHeightMap(ID3D11Device* pDevice,T_STR szName); bool Init(); bool Frame(); bool Release(); bool Render(ID3D11DeviceContext* pContext); public: D3DXVECTOR2 GetTextureOfVertex(float fU, float fV); D3DXVECTOR3 GetNormalOfVertex(int iIndex); D3DXVECTOR4 GetColorOfVertex(int iIndex); float GetHeightOfVertex(int iIndex); virtual HRESULT CreateVertexData() override; virtual HRESULT CreateIndexData() override; public: xMap(); virtual ~xMap(); }; <file_sep>#include<stdio.h> void main() { char lname[81],fname[81]; int count, id_num; puts("Enter last name.first name, ID number"); puts("separated by spaces, then press Enter"); count = scanf_s("%s%s%d", lname, fname, &id_num); printf("%d items entered: %s %s %d", count, fname, lname, id_num); }<file_sep>#include "TUser.h" void TUser::Dispatch( DWORD dwByteSize, LPOVERLAPPED ov) { OVERLAPPEDEX* pOV = (OVERLAPPEDEX*)ov; if( dwByteSize == 0 ) return; if( pOV->iFlags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put( m_szRecvBuffer.buf, // this->m_strBuffer, dwByteSize, this); } if( pOV->iFlags == OVERLAPPEDEX::MODE_SEND) { } WaitForPacketReceive(); }; void TUser::AddPacket(T_PACKET& addPacket ) { { TSynchronize sync(this); m_StreamPacket.m_PacketList.push_back(addPacket); } return; } bool TUser::Create() { ZeroMemory(&m_ov, sizeof(m_ov)); WaitForPacketReceive(); return true; } void TUser::WaitForPacketReceive() { DWORD cbTransferred, flags=0; m_szRecvBuffer.buf = m_strBuffer; m_szRecvBuffer.len = 4096; int iRet = WSARecv( m_Socket, &m_szRecvBuffer,1, &cbTransferred, &flags, (LPOVERLAPPED)&m_ov, NULL); if( iRet == SOCKET_ERROR ) { int dwError = WSAGetLastError(); if( dwError != WSA_IO_PENDING ) { int kkkk= 0; } } } bool TUser::Run() { char szMsgBuffer[2048]= {0,}; int strlen = 0; while(1) { strlen = recv( m_Socket, szMsgBuffer,sizeof(szMsgBuffer), 0 ); if( strlen <= 0) break; szMsgBuffer[strlen] = 0; m_StreamPacket.Put(szMsgBuffer, strlen, this); Sleep(10); } DeleteUser(m_Socket); return true; } void TUser::DeleteUser( SOCKET socket ) { } void TUser::DeleteUser() { } TUser::TUser(void) { m_Socket = 0; } TUser::~TUser(void) { closesocket(m_Socket); } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <sql.h> #include <sqlext.h> #include <tchar.h> //#include <stdio.h> #include <iostream> #define IDD_DIALOGMAIN 101 #define IDC_LISTUSER 1001 #define IDC_BTNADD 1002 #define IDC_BTNDEL 1003 #define IDC_BTNUPDATE 1004 #define IDC_FUserID 1006 #define IDC_FUserPS 1007 #define IDC_FCreateTime 1010 // 핸들 SQLHENV m_hEnv; // 환경핸들 SQLHDBC m_hDbc; // 연결핸들 SQLHSTMT m_hStmt; // 명령핸들 LRESULT CALLBACK MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); BOOL DBConnect(); void DBDisConnect(); BOOL DBExecuteSQL(); HINSTANCE g_hInst; HWND hDlgMain; HWND hList, hUserID, hUserPS, hCreateTime; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdSHow) { g_hInst = hInstance; if (DBConnect() == FALSE) { MessageBox(NULL, _T("데이터 베이스에 연결할 수 없습니다"), _T("에러"), MB_OK); return 0; } DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOGMAIN), HWND_DESKTOP, (DLGPROC)MainDlgProc); DBDisConnect(); return 0; } // 에러 발생시 진단 정보를 출력해 준다. void PrintDiag() { int ii; SQLRETURN Ret; SQLINTEGER NativeError; SQLTCHAR SqlState[6], Msg[255]; SQLSMALLINT MsgLen; TCHAR str[256]; ii = 1; while (Ret = SQLGetDiagRec(SQL_HANDLE_STMT, m_hStmt, ii, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen) != SQL_NO_DATA) { wsprintf(str, _T("SQLSTATE: %s, 진단정보:%s"), (LPCTSTR)SqlState, (LPCTSTR)Msg); ::MessageBox(NULL, str, _T("진단 정보"), 0); ii++; } } BOOL DBConnect() { // 연결 설정을 위한 변수들 TCHAR InCon[255]; SQLTCHAR OutCon[1024]; SQLSMALLINT cbOutCon; TCHAR Dir[MAX_PATH]; SQLRETURN Ret; // 환경 핸들을 할당하고 버전 속성을 설정한다. if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnv) != SQL_SUCCESS) // 핸들을 할당한다 { return FALSE; } if (SQLSetEnvAttr(m_hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER) != SQL_SUCCESS) // 핸들의 버전속성을 정한다 { return FALSE; } // 연결 핸들을 할당하고 연결한다. if (SQLAllocHandle(SQL_HANDLE_DBC, m_hEnv, &m_hDbc) != SQL_SUCCESS) { return FALSE; } // MDB 파일에 연결하기 GetCurrentDirectory(MAX_PATH, Dir); // 주의 --> *.mdb,"한칸뛰어야 한다." *.accdb // <*accdb> 파일 // _stprintf(InCon,_T("DRIVER={Microsoft Access Driver(*.mdb, *.accdb)}; DBQ=%s\\cigarette.accdb;"),Dir); //// <*.mdb> 파일 // _stprintf(InCon, _T(DRIVER={Microsoft Access Driver(*.mdb, *.accdb)}; DBQ=%s\\cigarette.mdb;"),Dir); //// <*.dsn> 파일 // _stprintf((TCHAR*))InCon, _T("FileDsn=%s"),_T("cigaretteaccdb.dsn")); // _stprintf((THCAR*)InCon,_T("Dsn=%s"),_T("SVRKGCA")); // SQLSERVER(client) 접속 _stprintf(InCon, _T("%s"), _T("Driver={SQL Server};Server=shader.kr;Address=192.168.3.11,1433;Network=dbmssocn;Database=KHJDB;Uid=sa;Pwd=<PASSWORD>;")); Ret = SQLDriverConnect(m_hDbc, NULL, (SQLTCHAR*)InCon, _countof(InCon), OutCon, _countof(OutCon), &cbOutCon, SQL_DRIVER_NOPROMPT); Ret = SQLConnect(m_hDbc, (SQLTCHAR*)L"KHJUser", SQL_NTS, // 테이블 이름 (SQLTCHAR*)L"sa", SQL_NTS, (SQLTCHAR*)L"kgca!@34", SQL_NTS); if ((Ret != SQL_SUCCESS) && (Ret != SQL_SUCCESS_WITH_INFO)) { SQLTCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1]; SQLTCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length; // 단순한 에러 SQLError(m_hEnv, m_hDbc, m_hStmt, sqlstate, &sqlcode, buffer, SQL_MAX_MESSAGE_LENGTH + 1, &length); MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); // MB_OK = ok 버튼 하나만 나타낸다 // 모든 에러 나열됨 int iErrorCnt = 1; while (Ret = SQLGetDiagRec(SQL_HANDLE_DBC, m_hDbc, iErrorCnt++, sqlstate, &sqlcode, buffer, sizeof(buffer), &length) != SQL_NO_DATA) { MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); } return FALSE; } if (SQLAllocHandle(SQL_HANDLE_STMT, m_hDbc, &m_hStmt) != SQL_SUCCESS) { return 0; } return TRUE; } void DBDisConnect() { // 소멸,삭제, 뒷정리 등등 지우기,,,, // 삭제는 반대 순서로 해준다 if (m_hStmt)SQLFreeHandle(SQL_HANDLE_STMT, m_hStmt); if (m_hDbc)SQLDisconnect(m_hDbc); if (m_hDbc)SQLFreeHandle(SQL_HANDLE_DBC, m_hDbc); if (m_hEnv)SQLFreeHandle(SQL_HANDLE_ENV, m_hEnv); } BOOL DBExecuteSQL() { // 결과값을 돌려받기 위한 변수들 SQLCHAR iUserID[21]; SQLLEN IUSERID; // 결과를 돌려받기 위해 바인딩 한다. SQLBindCol(m_hStmt, 1, SQL_C_CHAR, iUserID, sizeof(iUserID), &IUSERID); // SQL문을 실행한다. if (SQLExecDirect(m_hStmt, (SQLTCHAR *)_T("select name from KHJUser"), SQL_NTS) != SQL_SUCCESS) { return FALSE; } // 읽어온 데이터 출력 SendMessage(hList, LB_RESETCONTENT, 0, 0); while (SQLFetch(m_hStmt) != SQL_NO_DATA) { SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)iUserID); } if (m_hStmt)SQLCloseCursor(m_hStmt); return TRUE; } // 현재 선택된 레코드를 읽어 에디트에 출력한다. BOOL ReadRecord() { // 결과값을 돌려받기 위한 변수들 SQLTCHAR UserID[21]; int iUserPS; BOOL bCreateID; SQLLEN IUSERID, IUSERPS, ICREATETIME; int idx; TCHAR key[256], szSQL[256]; idx = SendMessage(hList, LB_GETCURSEL, 0, 0); if (idx == -1) return FALSE; SendMessage(hList, LB_GETTEXT, idx, (LPARAM)key); wsprintf(szSQL, _T("select UserId,UserPs,CreateID from KHJUser where UserId='%s'"), key); // 결과를 돌려받기 위해 바인딩한다. SQLBindCol(m_hStmt, 1, SQL_C_CHAR, UserID, sizeof(UserID), &IUSERID); SQLBindCol(m_hStmt, 2, SQL_C_ULONG, &iUserPS, 0, &IUSERPS); SQLBindCol(m_hStmt, 3, SQL_C_ULONG,&bCreateID ,0, &ICREATETIME); // SQL문을 실행한다. if (SQLExecDirect(m_hStmt, (SQLTCHAR*)szSQL, SQL_NTS) != SQL_SUCCESS) { return FALSE; } // 읽어온 데이터 출력 if (SQLFetch(m_hStmt) != SQL_NO_DATA) { SetWindowText(hUserID, (LPCTSTR)UserID); wsprintf(szSQL, _T("%d"), iUserPS); SetWindowText(hUserPS, szSQL); SendMessage(hCreateTime, BM_SETCHECK, (bCreateID ? BST_CHECKED : BST_UNCHECKED), 0); } if (m_hStmt)SQLCloseCursor(m_hStmt); return TRUE; } // 레코드를 추가한다. void AddRecord() { SQLCHAR UserID[21]; int iUserPS; BOOL bCreateID; TCHAR szSQL[256]; // 값읽음 GetWindowText(hUserID, (LPTSTR)UserID, 20); if (lstrlen((LPCTSTR)UserID) == 0) { MessageBox(hDlgMain, _T("추가할 레코드의 이름을 먼저 입력하십시요"), _T("알림"), MB_OK); return; } GetWindowText(hUserPS, szSQL, 256); iUserPS = _ttoi(szSQL); bCreateID = (SendMessage(hCreateTime, BM_GETCHECK, 0, 0) == BST_CHECKED); wsprintf(szSQL, _T("Insert into KHJUser (UserId,UserPs,CreateID) VALUES('%s',%d,%d)"), UserID, iUserPS, bCreateID); if (SQLExecDirect(m_hStmt, (SQLTCHAR*)szSQL, SQL_NTS) != SQL_SUCCESS) { MessageBox(hDlgMain, _T("레코드 추가 에러, 이름이 같은 레코드는 추가할 수 없습니다"), _T("에러"), MB_OK); return; } if (m_hStmt)SQLCloseCursor(m_hStmt); DBExecuteSQL(); } // 선택된 레코드를 삭제한다. void DeleteRecord() { TCHAR Key[256], szSQL[256]; int idx; idx = SendMessage(hList, LB_GETCURSEL, 0, 0); if (idx == -1) { MessageBox(hDlgMain, _T("삭제할 레코드를 먼저 선택하십시요"), _T("알림"),MB_OK); return; } SendMessage(hList, LB_GETTEXT, idx, (LPARAM)Key); wsprintf(szSQL, _T("DELETE form KHJUser where UserId='%s'"), Key); if(SQLExecDirect(m_hStmt,(SQLTCHAR*)szSQL,SQL_NTS)!=SQL_SUCCESS) { return; } if (m_hStmt)SQLCloseCursor(m_hStmt); DBExecuteSQL(); } // 업데이트 한다. void UpdateRecord() { SQLCHAR OldUserID[21], NewUserID[21]; int iUserPS; BOOL bCreateID; TCHAR szSQL[256]; int idx; // 값 읽음 idx = SendMessage(hList, LB_GETCURSEL, 0, 0); if (idx == -1) { return; } SendMessage(hList, LB_GETTEXT, idx, (LPARAM)OldUserID); GetWindowText(hUserID, (LPTSTR)NewUserID, 20); if (lstrlen((LPCTSTR)NewUserID) == 0) { MessageBox(hDlgMain, _T("변경할 레코드의 이름을 먼저 입력하십시요"), _T("알림"), MB_OK); return; } GetWindowText(hUserPS, szSQL, 256); iUserPS = _ttoi(szSQL); bCreateID = (SendMessage(hCreateTime, BM_GETCHECK, 0, 0) == BST_CHECKED); wsprintf(szSQL, _T("Update KHJUser set UserId='%s', UserPs=%d, CreateID=%d where UserId='%s'"), NewUserID, iUserPS, bCreateID, OldUserID); if(SQLExecDirect(m_hStmt,(SQLTCHAR*)szSQL,SQL_NTS)) { return; } if (m_hStmt)SQLCloseCursor(m_hStmt); DBExecuteSQL(); } void CenterWindow(HWND hWnd) { RECT rcTemp1, rcTemp2; LONG iX, iY, iWidth, iHeight; GetWindowRect(GetDesktopWindow(), &rcTemp1); GetWindowRect(hWnd, &rcTemp2); iWidth = rcTemp2.right - rcTemp2.left; iHeight = rcTemp2.bottom - rcTemp2.top; iX = LONG((rcTemp1.right - iWidth) / 2); iY = LONG((rcTemp1.bottom - iHeight) / 2); MoveWindow(hWnd, iX, iY, iWidth, iHeight, TRUE); } LRESULT CALLBACK MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_INITDIALOG: hDlgMain = hDlg; hList = GetDlgItem(hDlgMain, IDC_LISTUSER); hUserID = GetDlgItem(hDlgMain, IDC_FUserID); hUserPS = GetDlgItem(hDlgMain, IDC_FUserPS); hCreateTime = GetDlgItem(hDlgMain, IDC_FCreateTime); CenterWindow(hDlg); DBExecuteSQL(); return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: case IDCANCEL: EndDialog(hDlgMain, IDOK); return TRUE; case IDC_BTNADD: AddRecord(); return TRUE; case IDC_BTNDEL: DeleteRecord(); return TRUE; case IDC_BTNUPDATE: UpdateRecord(); return TRUE; case IDC_LISTUSER: switch (HIWORD(wParam)) { case LBN_SELCHANGE: ReadRecord(); return TRUE; } } return FALSE; } return FALSE; } <file_sep>#include<stdio.h> int main() { int a = 5; int b = 6; int c = 5; int d = 1; int x; x = a < b || a < c && c < d; printf("x is : %d", x); x = (a < b || a < c) && c < d; printf("\n x is : %d", x); }<file_sep>#pragma once #include "TCore.h" #include "TUdpSocket.h" class Sample: public TCore { public: TUdpSocket m_Udp; public: bool Init(); bool Release(); bool PreRender() { return true; } bool PostRender() { return true; } LRESULT MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); public: Sample(void); ~Sample(void); }; <file_sep>#include "DXDevice.h" // -------------------------------------------------------- // ID3D11Device 인터페이스를 생성한다. // -------------------------------------------------------- HRESULT DXDevice::CreateDevice() { HRESULT hr; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_UNKNOWN, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, }; UINT numFeatureLevels = sizeof(featureLevels) / sizeof(featureLevels[0]); //IDXGIAdapter* pAdapter = NULL; //m_pGIFactory->EnumAdapters(0,&pAdapter); for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { m_DriverType = driverTypes[driverTypeIndex]; if (SUCCEEDED(hr = D3D11CreateDevice(NULL, m_DriverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &m_pd3dDevice, &m_FeatureLevel, &m_plmmediateContext))) { if (FAILED(hr) || m_FeatureLevel < D3D_FEATURE_LEVEL_11_0) { if (m_plmmediateContext) m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); continue; } break; } } // if (pAdapter) pAdapter-> Relase(); if (FAILED(hr)) { //DXTRACE_ERR_MSGBOX(DXGetErrorDescription(hr),hr); return false; } DXTRACE_MSG(DXGetErrorDescription(hr)); return S_OK; } // ----------------------------------------------- // DXGIFactory 인터페이스를 생성한다. // ----------------------------------------------- HRESULT DXDevice::CreateGIFactory() { HRESULT hr; if (FAILED(hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&m_pGIFactory)))) { //DXTRACE_ERR_MSGBOX(DXGetErrorDescription(hr),hr); //MessageBox(m_hWnd,DXGetErrorDescription(hr),DXGetErrorString(hr),MB_OK); return false; } return hr; } // -------------------------------------------------------------------- // DXGIFactory 인터페이스로부터 IDXGISwapChain 인터페이스를 생성한다. // -------------------------------------------------------------------- HRESULT DXDevice::CreateSwapChain(HWND hWnd, UINT iWidth, UINT iHeight) { HRESULT hr = S_OK; if (m_pGIFactory == NULL)return S_FALSE; DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = iWidth; sd.BufferDesc.Height = iHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = true; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; if (FAILED(hr = m_pGIFactory->CreateSwapChain(m_pd3dDevice, &sd, &m_pSwapChain))) { return hr; } return hr; } HRESULT DXDevice::SetRenderTargetView() { HRESULT hr = S_OK; //Create a render target view ID3D11Texture2D* pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if (FAILED(hr)) return hr; hr = m_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); if (FAILED(hr)) return hr; m_plmmediateContext->OMSetRenderTargets(1, &m_pRenderTargetView, NULL); return S_OK; } HRESULT DXDevice::SetViewPort() { HRESULT hr = S_OK; DXGI_SWAP_CHAIN_DESC Desc; m_pSwapChain->GetDesc(&Desc); // Setup the viewport m_ViewPort.Width = Desc.BufferDesc.Width; m_ViewPort.Height = Desc.BufferDesc.Height; m_ViewPort.MinDepth = 0.0f; m_ViewPort.MaxDepth = 1.0f; m_ViewPort.TopLeftX = 0; m_ViewPort.TopLeftY = 0; m_plmmediateContext->RSSetViewports(1, &m_ViewPort); return S_OK; } bool DXDevice::CleanupDevice() { if (m_plmmediateContext)m_plmmediateContext->ClearState(); if (m_pRenderTargetView)m_pRenderTargetView->Release(); if (m_pSwapChain)m_pSwapChain->Release(); if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); if (m_pGIFactory)m_pGIFactory->Release(); m_pd3dDevice = NULL; m_pSwapChain = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; m_pGIFactory = NULL; return true; } DXDevice::DXDevice() { m_driverType = D3D_DRIVER_TYPE_NULL; m_FeatureLevel = D3D_FEATURE_LEVEL_11_0; m_pSwapChain = NULL; m_pd3dDevice = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; } DXDevice::~DXDevice() { } <file_sep>#pragma once #include "xCore.h" #include "x_AseMesh.h" #include "x_Mesh.h" class Sample : public xCore { public: x_AseMesh m_Obj; x_Mesh m_xObj; public: int IsEqulVertexList(x_Mesh& pMesh,PNCT_VERTEX& v) { for (int ilist = 0; ilist < pMesh.m_VertexList.size(); ilist++) { if (v == pMesh.m_VertexList[ilist]) { return ilist; } // xMesh.m_VertexList } return -1; } bool Init() { //if(m_Obj.Load(L"../../Sampleinclude/data/multiBox2.ASE")) //if (m_Obj.Load(L"../../Sampleinclude/data/BOX.ASE")) if(m_Obj.Load(L"../../Sampleinclude/data/St02sc00.ASE")) //if(m_Obj.Load(L"../../Sampleinclude/data/multicameras.ASE")) { for (int iObj = 0; iObj < m_Obj.m_ObjectList.size(); iObj++) { x_Mesh xMesh; int iMtrl = m_Obj.m_ObjectList[iObj].mtrlRef; int iSubMtrl = m_Obj.m_MaterialList[iMtrl].m_SubMaterial.size(); if (iSubMtrl > 0) { //sub Material xMesh.m_SubList.resize(iSubMtrl); int iNumFace = m_Obj.m_ObjectList[iObj].PosFaceList.size(); for (int iFace = 0; iFace < iNumFace; iFace++) { int iSubBuffer = m_Obj.m_ObjectList[iObj].PosFaceList[iFace].iSubMtrl; for (int iVer = 0; iVer < 3; iVer++) { PNCT_VERTEX v; int iID = iFace * 3 + iVer; // pos if (m_Obj.m_ObjectList[iObj].vertexList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].PosFaceList[iFace].i[iVer]; v.p = m_Obj.m_ObjectList[iObj].vertexList[iIndex]; } // nor if (m_Obj.m_ObjectList[iObj].NorList.size() > 0) { v.n = m_Obj.m_ObjectList[iObj].NorList[iID]; } //color v.c = D3DXVECTOR4(1, 1, 1, 1); if (m_Obj.m_ObjectList[iObj].ColFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].ColFaceList[iFace].i[iVer]; v.c.x = m_Obj.m_ObjectList[iObj].ColList[iIndex].x; v.c.y = m_Obj.m_ObjectList[iObj].ColList[iIndex].y; v.c.z = m_Obj.m_ObjectList[iObj].ColList[iIndex].z; v.c.w = 1.0f; } //tex if (m_Obj.m_ObjectList[iObj].texFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].texFaceList[iFace].i[iVer]; v.t.x = m_Obj.m_ObjectList[iObj].texList[iIndex].x; v.t.y = m_Obj.m_ObjectList[iObj].texList[iIndex].y; } xMesh.m_SubList[iSubBuffer].m_VertexList.push_back(v); } } for (int iSub = 0; iSub < iSubMtrl; iSub++) { xMesh.m_SubList[iSub].m_iNumVertex = xMesh.m_SubList[iSub].m_VertexList.size(); T_STR texName = m_Obj.m_MaterialList[iMtrl].m_SubMaterial[iSub].m_mapList[0].name; xMesh.m_SubList[iSub].Create(m_pd3dDevice, L"../../Sampleinclude/data/Shader/map.hlsl", texName); } } else { xMesh.m_iNumFaces = m_Obj.m_ObjectList[iObj].PosFaceList.size(); xMesh.m_TempVertexList.resize(xMesh.m_iNumFaces * 3); for (int iFace = 0; iFace < xMesh.m_iNumFaces; iFace++) { for (int iVer = 0; iVer < 3; iVer++) { int iID = iFace * 3 + iVer; // pos if (m_Obj.m_ObjectList[iObj].vertexList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].PosFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].p = m_Obj.m_ObjectList[iObj].vertexList[iIndex]; } // nor if (m_Obj.m_ObjectList[iObj].NorList.size() > 0) { xMesh.m_TempVertexList[iID].n = m_Obj.m_ObjectList[iObj].NorList[iID]; } //color xMesh.m_TempVertexList[iID].c = D3DXVECTOR4(1, 1, 1, 1); if (m_Obj.m_ObjectList[iObj].ColFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].ColFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].c.x = m_Obj.m_ObjectList[iObj].ColList[iIndex].x; xMesh.m_TempVertexList[iID].c.y = m_Obj.m_ObjectList[iObj].ColList[iIndex].y; xMesh.m_TempVertexList[iID].c.z = m_Obj.m_ObjectList[iObj].ColList[iIndex].z; xMesh.m_TempVertexList[iID].c.w = 1.0f; } //tex if (m_Obj.m_ObjectList[iObj].texFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].texFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].t.x = m_Obj.m_ObjectList[iObj].texList[iIndex].x; xMesh.m_TempVertexList[iID].t.y = m_Obj.m_ObjectList[iObj].texList[iIndex].y; } } } // Create ib + vb // xMesh.m_VertexList; // 비용이 많아지는 구간 for (int ivb = 0; ivb < xMesh.m_TempVertexList.size(); ivb++) { PNCT_VERTEX v = xMesh.m_TempVertexList[ivb]; int iPos = IsEqulVertexList(xMesh, v); if (iPos < 0) { xMesh.m_VertexList.push_back(v); iPos = xMesh.m_VertexList.size() - 1; } xMesh.m_IndexList.push_back(iPos); } /////////////////////// xMesh.m_iNumIndex = xMesh.m_IndexList.size(); xMesh.m_iNumVertex = xMesh.m_VertexList.size(); int iRef = m_Obj.m_ObjectList[iObj].mtrlRef; //T_STR FullPassName = L"../../Sampleinclude/data/"; T_STR texName = m_Obj.m_MaterialList[iRef].m_mapList[0].name; //FullPassName += texName; xMesh.Create(m_pd3dDevice, L"../../Sampleinclude/data/Shader/map.hlsl", texName); //xMesh.m_iNumIndex = xMesh.m_iNumVertex; } m_xObj.m_ObjectList.push_back(xMesh); } } return true; } bool Render() { for (auto mesh : m_xObj.m_ObjectList) { if (mesh.m_SubList.size()>0) { for (int iSubObj = 0; iSubObj < mesh.m_SubList.size(); iSubObj++) { mesh.m_SubList[iSubObj].SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); mesh.m_SubList[iSubObj].Render(m_pContext); } } else { mesh.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); mesh.Render(m_pContext); } } return true; } bool Release() { for (auto mesh : m_xObj.m_ObjectList) { mesh.Release(); } return true; } public: Sample() {} ~Sample() {} }; GAME_RUN("SAMPLE_ASE", 800, 600)<file_sep>#include<stdio.h> void main(int argc, char **argv) { printf("count = %d\n", argc); }<file_sep>#pragma once #include "Sstd.h" #include <d2d1.h> #include <DWrite.h> #pragma comment(lib,"d2d1.lib") #pragma comment(lib,"dwrite.lib") struct STextArray { D2D1_MATRIX_3X2_F matWorld; D2D1_RECT_F rf; D3DCOLORVALUE color; T_STR pText; //IDWriteTextFormat* pTextFormat; STextArray() { matWorld = D2D1::IdentityMatrix(); color = D2D1::ColorF(0, 0, 0, 1); rf.left = g_rtClient.left; rf.top = g_rtClient.top; rf.right = g_rtClient.right; rf.bottom = g_rtClient.bottom; } }; class sWrite { public: D2D1::Matrix3x2F m_matWorld; vector<STextArray> m_TextList; public: ID2D1Factory* m_pd2dFactory; IDWriteFactory* m_pWriteFactory; ID2D1RenderTarget* m_pRT; IDWriteTextFormat* m_pTextFormat; ID2D1SolidColorBrush* m_pColorBrush; float m_fdpiX; float m_fdpiY; public: bool Init(); bool Frame(); bool Render(); bool Release(); public: bool Set(HWND hWnd, int iWidth, int iHeight, IDXGISurface* pSurface); HRESULT CreateDeviceIndependentResources(); HRESULT CreateDeviceResources(IDXGISurface* pSurface); void DiscardDeviceResources(); void OnResize(int iWidth, int iHeight, IDXGISurface* pSurface); HRESULT DrawText(RECT rc, const TCHAR* pText, D2D1::ColorF color); public: sWrite(); virtual ~sWrite(); }; <file_sep>#pragma once #include "TServerObj.h" #include "TProtocol.h" #define MAX_RECV_SIZE 10000 class TUser; typedef struct{ UPACKET packet; TUser* pUser; }T_PACKET,*P_TPACKET; class TStreamPacket : public TServerObj { public: std::list<T_PACKET> m_PacketList; typedef std::list<T_PACKET>::iterator m_PackItor; public: UPACKET* m_pPacket; char m_RecvBuffer[MAX_RECV_SIZE]; int m_iStartPos; int m_iWritePos; int m_iReadPos; public: void Put(char* redvBuffer, int iSize, TUser* = NULL); public: TStreamPacket(); virtual ~TStreamPacket(); }; <file_sep>#include <stdio.h> int main(void) { unsigned char eightBitVal = 0x57; unsigned char fourBitVal1, fourBitVal2; fourBitVal1 = eightBitVal >> 4; fourBitVal2 = eightBitVal & 0x0f; printf("%x_>%x,%x\n", eightBitVal, fourBitVal1, fourBitVal2); return 0; }<file_sep>#include "CCWindow.h" CCWindow* g_Window = NULL; RECT g_rtClient; HWND g_hWnd; //운영체제로 부터 메세지를 받는 함수 //메세지는 메세지 큐에 저장되고 //필요시 해당 윈도가 큐에서 꺼내온다. LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_SIZE: { //if(wParam==SIZE_MAXIMIZED) if (wParam != SIZE_MINIMIZED && g_Window != NULL) { UINT width = LOWORD(lParam); UINT height = HIWORD(lParam); GetWindowRect(hWnd, &g_Window->m_rtWindow); GetClientRect(hWnd, &g_Window->m_rtClient); g_rtClient = g_Window->m_rtClient; } }break; // 윈도우를 다시 그려야 할때 발생 case WM_PAINT : //BeginPaint { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); }break; case WM_DESTROY: { //닫기 메세지를 윈도우 //프로 시져에 등록한다. PostQuitMessage(0); }break; } return DefWindowProc(hWnd, msg, wParam, lParam); } void CCWindow::CenterWindow() { int iScreenWidth = GetSystemMetrics(SM_CXFULLSCREEN); int iScreenHeight = GetSystemMetrics(SM_CYFULLSCREEN); int x = (iScreenWidth - (m_rtWindow.right - m_rtWindow.left)) / 2; int y = (iScreenHeight - (m_rtWindow.bottom - m_rtWindow.top)) / 2; MoveWindow(m_hWnd, x, y, m_rtWindow.right, m_rtWindow.bottom, true); } //char 멀티바이트 => CHAR // 유니코드 => WCHAR bool CCWindow::SetWindow(HINSTANCE hInstance, TCHAR* pTitleName, int iWidth, int iHeight) { m_hInstance = hInstance; //1. 윈도우 클래스 객체 등록 (운영체제) WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; // 윈도우 프로시져 wc.lpfnWndProc = WndProc;// WNDPROC IpfnWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hInstance; wc.hIcon = LoadIcon(NULL, IDI_QUESTION); wc.hCursor = LoadCursor(NULL, IDC_IBEAM); wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = L"KHJ"; wc.hIconSm = LoadIcon(NULL, IDI_QUESTION); if (RegisterClassEx(&wc) == false) { return false; } //2, 등록된 클래스 객체를 사용하여 윈도우 생성 #ifdef _DEBUG m_hWnd = CreateWindowEx( WS_EX_APPWINDOW, //DWORD dwExStyle, L"KHJ",//LPCWSTR IpClassName, pTitleName,//LPCWSTR IpWindowName, WS_POPUPWINDOW, 0, 0, iWidth, iHeight, NULL, NULL, m_hInstance, NULL); if (m_hWnd == NULL)return false; g_hWnd = m_hWnd; #else m_hWnd = CreateWindowEx( WS_EX_TOPMOST, ..DWORD dwExStyle, L"KHJ",//LPCWSTR ipClassName, pTitleName,//LPCWSTR IpWindowName, WS_POPUOWINDOW,//DWORD dwStyle, 0, 0, iWidth, iHeight, NULL, NULL, m_hInstance, NULL); if (m_hWnd == NULL)return false; #endif GetClientRect(m_hWnd, &m_rtWindow); CenterWindow(); ShowWindow(m_hWnd, SW_SHOW); return true; }; bool CCWindow::Run() { GameInit(); MSG msg; ZeroMemory(&msg, sizeof(msg)); //메세지 큐에서 메세지 1개를 가져온다. while (true) { //PM_NOREMOVE,PM_REMOVE if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //키 해석해라. TranslateMessage(&msg); //메세지 프로시져에 전달해라. DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } MsgEvent(msg); } else { GameRun(); } } GameRelease(); return true; }; bool CCWindow::Release() { return true; }; CCWindow::CCWindow() { g_Window = this; //자기 자신 } CCWindow::~CCWindow() { } <file_sep>#include "TPacketPool.h" bool TPacketPool::AddPacket(T_PACKET& addPacket) { { TSynchronize sync(this); m_PacketList.push_back(addPacket); } return true; } bool TPacketPool::ProcessPacket() { { TSynchronize sync(this); std::list<T_PACKET>::iterator iter; for( iter= m_PacketList.begin(); iter != m_PacketList.end(); iter++) { T_PACKET* pUserData = (T_PACKET*)&(*iter); ProcessWork(pUserData); } m_PacketList.clear(); } return true; } void TPacketPool::ProcessWork(T_PACKET* pUserData) { } TPacketPool::TPacketPool(void) { } TPacketPool::~TPacketPool(void) { } <file_sep>#include<stdio.h> void main() { int k = 0; int j = 0; for (int i = 0; i <= 100; i++) { if (i % 2 == 0) { k = k + i; } else { j = j + i; } } printf("%d\n", k); printf("%d\n", j); printf("%d",k+j); }<file_sep>#pragma once #include "xStd.h" #include <d2d1.h> #include <dwrite.h> #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "dwrite.lib") struct TTextArray { D2D1_MATRIX_3X2_F matWorld; D2D1_RECT_F rf; D3DCOLORVALUE color; T_STR pText; //IDWriteTextFormat* pTextFormat; TTextArray() { matWorld = D2D1::IdentityMatrix(); color = D2D1::ColorF(0, 0, 0, 1); rf.left = g_rtClient.left; rf.top = g_rtClient.top; rf.right = g_rtClient.right; rf.bottom = g_rtClient.bottom; } }; class xDxWrite { public: D2D1::Matrix3x2F m_matWorld; std::vector<TTextArray> m_TextList; public: ID2D1Factory* m_pd2dFactory; IDWriteFactory* m_pWriteFactory; ID2D1RenderTarget* m_pRT; IDWriteTextFormat* m_pTextFormat; ID2D1SolidColorBrush* m_pColorBrush; float m_fdpiX; float m_fdpiY; public: bool Init(); bool Frame(); bool Render(); bool Release(); public: bool Set(HWND hWnd,int iWidth, int iHeight,IDXGISurface* pSurface); HRESULT CreateDeviceIndependentResources(); HRESULT CreateDeviceResources(IDXGISurface* pSurface); void DiscardDeviceResources(); void OnResize(int iWidth,int iHeight, IDXGISurface* pSurface); HRESULT DrawText(RECT rc, const TCHAR* pText, D2D1::ColorF color); public: xDxWrite(); virtual ~xDxWrite(); }; <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <conio.h> #include <stdlib.h> int main() { int iValue = 50; //변수 2개 float fValue = 3.141592f; FILE* fp = fopen("demo.txt", "w"); //파일 포인터 사용 현재 있는 프로젝트 폴더에"demo.txt"라는 것을 w==쓰기 파일 없는 경우에 파일 만들어서 써라 { fprintf(fp, "%s", "============ KGCA =========="); fprintf(fp, "\n%s", "홍길동"); fprintf(fp, "%d %f", iValue,fValue); fclose(fp); } iValue = 99; fValue = 6.26f; fp = fopen("demo.txt", "a"); { fprintf(fp,"\n%s", "개똥이"); fprintf(fp, "%d %f", iValue, fValue); fclose(fp); } char buffer[256] = { 0, }; int iValueRead; float fValueRead; FILE* fpRead = fopen("demo.txt", "r"); { fgets(buffer, 256,fpRead); fscanf(fpRead, "%s %d %f", buffer, &iValueRead, &fValueRead); printf("\n%s %d %f", buffer, iValueRead, fValueRead); fscanf(fpRead, "%s %d %f", buffer, &iValueRead, &fValueRead); printf("\n%s %d %f", buffer, iValueRead, fValueRead); fclose(fpRead); } _getch(); return 0; }<file_sep>//병합 정렬(Merge Sort) /*병합 정렬은 배열을 작은 단위의 배열로 분할한 후에 분할한 배열을 정렬하고 이들을 다시 정렬하면서 전체 배열을 정렬하는 알고리즘이다*/ #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 int *origin; int on; void MergeSort(int *base, int n); void ViewArr(int *arr, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; origin = arr; on = 10; ViewArr(origin, on); MergeSort(arr, 10); ViewArr(origin, on); _getch(); return 0; } void PrintSpace(int n); void MergeSort(int *base, int n) { int ahalf = n / 2; //배열의 앞쪽 개수 int bhalf = n - ahalf; //배열의 뒤쪽 개수 int ai = 0, bi = ahalf; int i = 0; int *tbase = 0; if (n <= 1)//배열의 크기가 1보다 작거나 같을 때 { return; } MergeSort(base, ahalf);//앞쪽 배열 재귀호출로 정렬 PrintSpace(base - origin); ViewArr(base, ahalf); MergeSort(base + ahalf, bhalf);//뒤쪽 배열 재귀호출로 정렬 PrintSpace(base + ahalf - origin); ViewArr(base + ahalf, bhalf); tbase = (int *)malloc(sizeof(int)*n);//배열 크기의 임시 공간을 할당 memcpy(tbase, base, sizeof(int)*n);//임시 공간에 배열 메모리 복사 while ((ai<ahalf) && (bi<n)) { if (tbase[ai] <= tbase[bi])//뒤쪽이 크거나 같을 때 { base[i] = tbase[ai];//앞쪽 배열의 원소를 대입 ai++; } else { base[i] = tbase[bi];//뒤쪽 배열의 원소를 대입 bi++; } i++; } while (ai<ahalf)//앞쪽 배열의 남은 것들을 대입 { base[i] = tbase[ai]; i++; ai++; } while (bi<n)//뒤쪽 배열의 남은 것들을 대입 { base[i] = tbase[bi]; i++; bi++; } free(tbase);//임시 버퍼에 할당한 메모리 해제 } void PrintSpace(int n) { int i = 0; for (i = 0; i<n; i++) { printf(" "); } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); }<file_sep>#include "TDepartment.h" void TDepartment::AddEmployee(TEmployee* emp) { empList[index++] = emp; } void TDepartment::ShowList()//급여리스트 출력 { for (int i = 0; i < index; i++) { cout << "name: " << empList[i]->GetName() << endl; cout << "salary: " << empList[i]->GetPay() << endl; cout << endl; } } <file_sep>#include<stdio.h> #include<conio.h> #include<stdlib.h> //#define MAX 10 //포인터 연산 //void main() //{ // int arr[MAX] = { 0,1,2,3,4,5,6,7,8,9 }; // int *ptr, count; // ptr = arr; // // for (count = 0; count < MAX; count++) // { // printf("%d\n,*ptr++"); // } // for (count = MAX - 1; count < MAX; count++) // { // printf("%d\n", *--ptr); // } //} void main() { int arr[10] = { 0,1,2,3,4,5,6,7 }; int i, *ptr, *ptr1; ptr = arr; ptr1 = &arr[5]; printf("Difference:%d\n", ptr1 - ptr); printf("Compare:%d\n",ptr>ptr1); for (i = 0; i < 10; i++) { printf("%d\t", *ptr++); } _getch(); }<file_sep>#include "DB_MGR.h" void main() { DB_MGR mgr; while (1) { int iSelect = 0; printf("\n 1: 출력 2: 추가 3: 수정 4: 삭제 5: 검색"); printf("\n 번호를 입력하시요 :"); scanf("%d", &iSelect); mgr.DBConnect(); switch (iSelect) { case 1: mgr.Select(); { system("pause"); break; } case 2: mgr.Add(); { break; } case 3: mgr.Update(); { break; } case 4: mgr.Delete(); { break; } case 5: mgr.FindSelect(); { system("pause"); break; } } system("cls"); } mgr.DBDisConnect(); }<file_sep>#include<stdio.h> #include<conio.h> //forĮ¦¾ī¹® //void main() //{ // int i; // for (i = 1; i <= 100; i++) // printf("%d", i); //} //void main() //{ // int i; // for (i = 1; i <= 100; i++) // { // if (i % 2 == 0)continue; // printf("%d", i); // } //} void main() { int i; for (i = 1; i <= 100; i++) { if (i == 51)break; printf("%d",i); } }<file_sep>#pragma once #include "sObjectStd.h" #include "sDxState.h" class xShape { public: ID3D11Device* m_pd3dDevice; D3D_PRIMITIVE_TOPOLOGY m_Primitive; sDxObj m_dxObj; vector<PNCT_VERTEX> m_VertexList; vector<DWORD> m_IndexList; UINT m_iVertexSize; S_CB_DATA m_cbData; D3DXMATRIX m_matWorld; D3DXMATRIX m_matView; D3DXMATRIX m_matProj; D3DXVECTOR3 m_vPosition; D3DXVECTOR3 m_vLook; D3DXVECTOR3 m_vSide; D3DXVECTOR3 m_vUp; UINT m_iNumIndex; UINT m_iNumVertex; public: void SetColor(D3DXVECTOR4 vColor); public: bool Create(ID3D11Device* pDevice, T_STR szShaderName, T_STR szTextureName); virtual HRESULT CreateVertexData() { return S_OK; }; virtual HRESULT CreateIndexData() { return S_OK; }; virtual HRESULT CreateVertexBuffer(); virtual HRESULT CreateIndexBuffer(); virtual HRESULT CreateConstantBuffer(); virtual HRESULT CreateInputLayout(); virtual HRESULT LoadVertexShader(T_STR szName); virtual HRESULT LoadPixelShader(T_STR szName); virtual HRESULT LoadGeometryShader(T_STR szName); virtual HRESULT LoadTexture(T_STR szName); virtual bool PreRender(ID3D11DeviceContext* pContext); virtual void SetMatrix(D3DXMATRIX* pWorld = NULL, D3DXMATRIX* pView = NULL, D3DXMATRIX* pProj = NULL); virtual bool Render(ID3D11DeviceContext* pContext); virtual bool PostRender(ID3D11DeviceContext* pContext); virtual bool Release(); virtual bool Frame(); virtual bool Init(); public: xShape(); virtual ~xShape(); }; class xBoxShape : public xShape { public: HRESULT CreateVertexData(); HRESULT CreateIndexData(); HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; public: xBoxShape(); virtual ~xBoxShape(); }; class xPlaneShape : public xShape { public: HRESULT CreateVertexData(); HRESULT CreateIndexData(); HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; public: xPlaneShape(); virtual ~xPlaneShape(); }; class xLineShape : public xShape { public: HRESULT CreateVertexData(); HRESULT CreateIndexData(); HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; bool Draw( ID3D11DeviceContext* pContext, D3DXVECTOR3 vStart, D3DXVECTOR3 vEnd, D3DXVECTOR4 vColor = D3DXVECTOR4(1,0,0,1)); HRESULT LoadPixelShader(T_STR szName); public: xLineShape(); virtual ~xLineShape(); }; class xDirLineShape : public xLineShape { public: HRESULT CreateVertexData(); HRESULT CreateIndexData(); HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; bool Render(ID3D11DeviceContext* pContext); public: xDirLineShape(); virtual ~xDirLineShape(); }; class xSphereShape : public xBoxShape { vector<PNCT_VERTEX> m_vList; public: PNCT_VERTEX NormalizeVertex(PNCT_VERTEX Vertex); void TriAppend(PNCT_VERTEX V0, PNCT_VERTEX V1, PNCT_VERTEX V2, vector<PNCT_VERTEX>& TriStream, int iIndex); HRESULT CreateVertexData(); HRESULT CreateIndexData() { return S_OK;}; HRESULT CreateVertexBuffer(); HRESULT CreateIndexBuffer() { return S_OK; } HRESULT LoadVertexShader(T_STR szName); HRESULT LoadGeometryShader(T_STR szName); public: xSphereShape(); virtual ~xSphereShape(); };<file_sep>#include<stdio.h> void main() { int sum = 0; int max = 0; int iCount = 1; do { sum = sum + iCount++; } while (iCount <= 100); printf("1~100±îÁöÀÇ ÇÕ:%d\n", sum); }<file_sep>#include<stdio.h> void main() { int count = 0; printf("Out,count=%d", count); { int count = 99; printf("In,count=%d",count); } printf("Out,count=%d", count); }<file_sep>#pragma once #include "sDxObj.h" struct _DX_MATRIX { union { struct { float _11, _12, _13, _14; float _21, _22, _23,_24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; float m[4][4]; }; }; struct DX_MATRIX : public _DX_MATRIX { void RoationX(float fAngle) { _22 = cosf(fAngle); _23 = sinf(fAngle); _32 = -sinf(fAngle); _33 = cosf(fAngle); } void RoationY(float fAngle) { _11 = cosf(fAngle); _13 = -sinf(fAngle); _31 = sinf(fAngle); _33 = cosf(fAngle); } void RoationZ(float fAngle) { _11 = cosf(fAngle); _12 = sinf(fAngle); _21 = -sinf(fAngle); _22 = cosf(fAngle); } void Indentity(float fAngle) { _11 = 1.0f; _21 = 0.0f; _31 = 0.0f; _41 = 0.0f; _12 = 0.0f; _22 = 1.0f; _32 = 0.0f; _42 = 0.0f; _13 = 0.0f; _23 = 0.0f; _33 = 1.0f; _43 = 0.0f; _14 = 0.0f; _24 = 0.0f; _34 = 0.0f; _44 = 1.0f; } void Transpose() { DX_MATRIX mat = *this; mat._11 = _11; mat._12 = _21; mat._13 = _31; mat._14 = _41; mat._21 = _12; mat._22 = _22; mat._23 = _32; mat._24 = _42; mat._31 = _13; mat._32 = _23; mat._33 = _33; mat._34 = _43; mat._41 = _14; mat._42 = _24; mat._43 = _34; mat._44 = _44; *this = mat; } DX_MATRIX() { _11 = _22 = _33 = _44 = 1.0f; _12 = _13 = _14 = 0.0f; _21 = _23 = _24 = 0.0f; _31 = _32 = _34 = 0.0f; _41 = _42 = _43 = 0.0f; } }; struct SActorCB { DX_MATRIX m_matWorld; DX_MATRIX m_matView; DX_MATRIX m_matProj; }; struct SOffSet { float fScaleX0; float fScaleX1; float fScaleY0; float fScaleY1; float fOffsetU0; float fOffsetV0; float fOffsetU1; float fOffsetV1; }; struct SPoint { float x, y; }; class SActor { public: RECT m_rtInit; SOffSet m_sOffset; PNCT_VERTEX m_VertexList[6]; public: sDxObj m_dxObj; D3DXVECTOR3 m_vCenter; SActorCB m_ActorCB; public: virtual bool Init(); virtual bool Frame(float fGameTimer, float fFps); virtual bool PreRender(ID3D11DeviceContext* pContext, UINT iVertexSize); virtual bool Render(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount); virtual bool PostRender(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount); virtual bool Release(); public: virtual D3DXVECTOR3 Gen(float x, float y); virtual void GenCenter(); virtual void SetVertexData(); virtual bool Setdata(UINT left, UINT top, UINT width, UINT height); public: SActor(); virtual ~SActor(); }; <file_sep>#include "xDevice.h" void xDevice::DeleteDeviceResources(){} HRESULT xDevice::CreateDeviceResources(UINT width, UINT height) { return S_OK; } void xDevice::ResizeDevice(UINT width, UINT height) { if (m_pd3dDevice == NULL) return; m_pContext->OMSetRenderTargets(0, NULL, NULL); DeleteDeviceResources(); m_pRenderTargetView->Release(); HRESULT hr; DXGI_SWAP_CHAIN_DESC sd = m_sd; sd.BufferDesc.Height = height; sd.BufferDesc.Width = width; hr = m_pSwapChain->ResizeBuffers(sd.BufferCount, width, height, sd.BufferDesc.Format, sd.Flags); if (SUCCEEDED(hr)) { m_pSwapChain->GetDesc(&m_sd); } SetRenderTargetView(); SetViewPort(); CreateDeviceResources(width, height); } bool xDevice::Init() { if (FAILED(CreateDevice())) { return false; } if (FAILED(CreateGIFactory())) { return false; } if (FAILED(CreateSwapChain())) { return false; } if (FAILED(SetRenderTargetView())) { return false; } SetViewPort(); CreateDSV(); m_pDXGIFactory->MakeWindowAssociation(g_hWnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); } HRESULT xDevice::CreateDevice() { HRESULT hr = S_OK; //1)디바이스 생성 D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; UINT FeatureLevels = 2; UINT Flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG Flags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE DriverType[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(DriverType) / sizeof(DriverType[0]); for (int iMode = 0; iMode < numDriverTypes; iMode++) { D3D_FEATURE_LEVEL retFL; if (SUCCEEDED(D3D11CreateDevice( NULL, DriverType[iMode], NULL, Flags, pFeatureLevels, FeatureLevels, D3D11_SDK_VERSION, &m_pd3dDevice, &retFL, &m_pContext))) { if (retFL != D3D_FEATURE_LEVEL_11_0) { if (m_pSwapChain)m_pSwapChain->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); if (m_pContext)m_pContext->Release(); continue; } break; } } return hr; } HRESULT xDevice::CreateGIFactory() { if (m_pd3dDevice == NULL) return E_FAIL; HRESULT hr;// = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&m_pGIFactory) ); IDXGIDevice * pDXGIDevice; hr = m_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice); IDXGIAdapter * pDXGIAdapter; hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter); IDXGIFactory * pIDXGIFactory; pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&m_pDXGIFactory); pDXGIDevice->Release(); pDXGIAdapter->Release(); return hr; } HRESULT xDevice::CreateSwapChain() { HRESULT hr = S_OK; ZeroMemory(&m_sd, sizeof(m_sd)); m_sd.BufferDesc.Width = g_rtClient.right; m_sd.BufferDesc.Height = g_rtClient.bottom; m_sd.BufferDesc.RefreshRate.Numerator = 60; m_sd.BufferDesc.RefreshRate.Denominator = 1; m_sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; m_sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; m_sd.BufferCount = 1; m_sd.OutputWindow = g_hWnd; m_sd.Windowed = true; m_sd.SampleDesc.Count = 1; m_sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; if (FAILED(hr = m_pDXGIFactory->CreateSwapChain( m_pd3dDevice, &m_sd, &m_pSwapChain))) { return false; } return hr; } HRESULT xDevice::SetRenderTargetView() { HRESULT hr = S_OK; // 2)랜더타켓 뷰 생성 ID3D11Texture2D* pBackBuffer; m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer); m_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); return hr; } void xDevice::SetViewPort() { HRESULT hr = S_OK; // 3)뷰포트 생성 D3D11_VIEWPORT vp; vp.TopLeftX = 0; vp.TopLeftY = 0; vp.Width = m_sd.BufferDesc.Width; vp.Height = m_sd.BufferDesc.Height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; m_pContext->RSSetViewports(1, &vp); g_rtClient.right = m_sd.BufferDesc.Width; g_rtClient.bottom = m_sd.BufferDesc.Height; } HRESULT xDevice::CreateDSV() { HRESULT hr; ID3D11Texture2D* pTex = nullptr; D3D11_TEXTURE2D_DESC td; td.Width = g_rtClient.right; td.Height = g_rtClient.bottom; td.MipLevels = 1; td.ArraySize = 1; td.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; td.SampleDesc.Count = 1; td.SampleDesc.Quality = 0; td.Usage = D3D11_USAGE_DEFAULT; td.BindFlags = D3D11_BIND_DEPTH_STENCIL; td.CPUAccessFlags = 0; td.MiscFlags = 0; hr = m_pd3dDevice->CreateTexture2D(&td, NULL, &pTex); D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; dsvd.Format = td.Format; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvd.Flags = 0; dsvd.Texture2D.MipSlice = 0; hr = m_pd3dDevice->CreateDepthStencilView( pTex, &dsvd, &m_pDSV); if (pTex) pTex->Release(); return hr; } bool xDevice::Release() { m_pSwapChain->SetFullscreenState(false, NULL); if (m_pDSV)m_pDSV->Release(); if (m_pRenderTargetView)m_pRenderTargetView->Release(); if (m_pSwapChain)m_pSwapChain->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); if (m_pContext)m_pContext->Release(); if (m_pDXGIFactory)m_pDXGIFactory->Release(); m_pRenderTargetView = nullptr; m_pSwapChain = nullptr; m_pd3dDevice = nullptr; m_pContext = nullptr; m_pDXGIFactory = nullptr; return true; } xDevice::xDevice() { } xDevice::~xDevice() { } <file_sep>#include<stdio.h> #include<conio.h> //반대로 피라미드 void main() { for (int sum = 0; sum < 5; sum++) { for (int sum1 = 0; sum1 < sum; sum1++) { printf(" "); } for (int sum2 = 0; sum2 < 2*(4-sum)-1 ; sum2++) { printf("*"); }printf("\n"); }_getch(); }<file_sep>#pragma once #include <windows.h> #include <assert.h> #include <tchar.h> #define GAME_START int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,LPSTR lpCmdLine,int nCmdShow){ #define GAME_END } #define GAME_RUN(s, w, h) GAME_START { Sample win; win.SetWindow(hInst, L#s, w, h); win.Run(); }GAME_END extern HWND g_hWnd;<file_sep>#include "TChatAccept.h" #include "TChatSvr.h" void TChatAccept::AddUser(SOCKET socket, SOCKADDR_IN address ) { I_Server.AddUser( socket, address ); } TChatAccept::TChatAccept(void) { } TChatAccept::~TChatAccept(void) { } <file_sep>#include "xCore.h" LRESULT xCore::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { return m_ModelCamera.MsgProc(hWnd, msg, wParam, lParam); } void xCore::DeleteDeviceResources() { if (m_pDSV)m_pDSV->Release(); m_Font.DiscardDeviceResources(); DeleteResources(); } HRESULT xCore::CreateDeviceResources(UINT width, UINT height) { IDXGISurface* pBackBuffer=nullptr; m_pSwapChain->GetBuffer(0, __uuidof(IDXGISurface), (void**)&pBackBuffer); HRESULT hr = m_Font.CreateDeviceResources(pBackBuffer); pBackBuffer->Release(); CreateDSV(); m_pMainCamera->UpdateProjMatrix(width, height); CreateResources(width, height); return hr; } bool xCore::GamePreInit() { return false; } bool xCore::GameInit() { GamePreInit(); xDevice::Init(); m_Timer.Init(); m_Font.Init(); I_Input.Init(); IDXGISurface* pBackBuffer; m_pSwapChain->GetBuffer(0, __uuidof(IDXGISurface),(void**)&pBackBuffer); m_Font.Set(m_hWnd,m_sd.BufferDesc.Width,m_sd.BufferDesc.Height, pBackBuffer); pBackBuffer->Release(); xDxState::SetState(m_pd3dDevice); m_DefaultCamera.SetViewMatrix(); m_DefaultCamera.SetProjMatrix(D3DX_PI * 0.25f,(float)m_rtClient.right/ (float)m_rtClient.bottom ); m_ModelCamera.SetViewMatrix(); m_ModelCamera.SetProjMatrix(D3DX_PI * 0.25f, (float)m_rtClient.right / (float)m_rtClient.bottom); m_pMainCamera = &m_DefaultCamera; m_SkyBox.Create(m_pd3dDevice, L"../../Sampleinclude/data/shader/sky.hlsl", L"../../Sampleinclude/data/grassenvmap1024.dds"); m_dirAxis.Create(m_pd3dDevice,L"../../Sampleinclude/data/shader/shape.hlsl",L"../../Sampleinclude/data/eye.bmp"); Init(); return true; } void xCore::SwapModelView() { m_pMainCamera = &m_ModelCamera; } void xCore::SwapDefaultView() { m_pMainCamera = &m_DefaultCamera; } bool xCore::GameFrame() { m_Timer.Frame(); I_Input.Frame(); D3DXVECTOR4 vYawPitchRoll(0,0,0,0); // camera control if (g_Input.bButton1) { vYawPitchRoll.y = 0.1f * D3DXToRadian(I_Input.m_MouseState.lX); vYawPitchRoll.x = 0.1f * D3DXToRadian(I_Input.m_MouseState.lY); } float fValue = I_Input.m_MouseState.lZ; vYawPitchRoll.w = fValue *g_fSecPerFrame; if (g_Input.bJump) { m_pMainCamera->SetSpeed(g_fSecPerFrame*3.0f); } if (g_Input.bFront) { m_pMainCamera->MoveLook(g_fSecPerFrame*5.0f); } if (g_Input.bBack) { m_pMainCamera->MoveLook(-g_fSecPerFrame*5.0f); } if (g_Input.bLeft) { m_pMainCamera->MoveSide(-g_fSecPerFrame * 5.0f); } if (g_Input.bRight) { m_pMainCamera->MoveSide(g_fSecPerFrame*5.0f); } m_pMainCamera->Update(vYawPitchRoll); m_pMainCamera->Frame(); m_SkyBox.Frame(); Frame(); m_dirAxis.Frame(); return true; } bool xCore::GamePreRender() { float color[4] = { 0.44f,0.61f,0.83f,1 }; m_pContext->ClearRenderTargetView(m_pRenderTargetView, color); m_pContext->ClearDepthStencilView(m_pDSV, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); m_pContext->OMSetRenderTargets(1,&m_pRenderTargetView, m_pDSV); ApplyDSS(m_pContext, xDxState::g_pDSVStateEnableLessEqual); ApplyBS(m_pContext, xDxState::g_pBSAlphaBlend); //ApplyRS(m_pContext, xDxState::g_pRSBackCullSolid); ApplySS(m_pContext, xDxState::g_pSSWrapLinear); if (I_Input.m_KeyState[DIK_P]) ApplyRS(m_pContext, xDxState::g_pRSWireFrame); else ApplyRS(m_pContext, xDxState::g_pRSNoneCullSolid); m_pContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_SkyBox.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_SkyBox.Render(m_pContext); return true; } bool xCore::GamePostRender() { m_Timer.Render(); RECT rt = g_rtClient; m_Font.Render(); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); m_Font.DrawText(rt, m_Timer.m_csBuffer, D2D1::ColorF(0, 0, 0, cosf(m_Timer.m_fGameTimer)*0.5f + 0.5f)); m_dirAxis.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_dirAxis.Render(m_pContext); m_pSwapChain->Present(0, 0); return true; } bool xCore::GameRender() { GamePreRender(); { PreRender(); Render(); PostRender(); } GamePostRender(); return true; } bool xCore::GameRun() { GameFrame(); GameRender(); return true; } bool xCore::GameRelease() { Release(); m_ModelCamera.Release(); m_DefaultCamera.Release(); m_SkyBox.Release(); m_Timer.Release(); m_Font.Release(); I_Input.Release(); m_dirAxis.Release(); xDxState::Release(); xDevice::Release(); return true; } xCore::xCore() { m_pMainCamera = NULL; } xCore::~xCore() { } <file_sep>#pragma once #include "S_Acceptor.h" class S_ChatAccept : public S_Acceptor { public: void AddUser(SOCKET socket, SOCKADDR_IN address); public: S_ChatAccept(); virtual ~S_ChatAccept(); }; <file_sep>#pragma once #include "S_Server.h" #include "S_Chat_PacketPool.h" #include "S_ChatAccept.h" #include "S_ChatUser.h" class S_Chat_Svr : public S_Server,public Singleton<S_Chat_Svr> { friend class Singleton<S_Chat_Svr>; public: S_Chat_PacketPool m_PacketPool; S_ChatAccept m_Acceptor; list<S_ChatUser*> m_UserList; typedef list<S_ChatUser*>::iterator m_Listitor; int m_iUserCount; public: bool Init(); bool Release(); bool Run(); public: bool AddUser(SOCKET socket, SOCKADDR_IN address); void DeleteUser(SOCKET socket); void DeleteUser(S_ChatUser* pDeleteUser); void Broadcastting(char* msg, WORD code, SOCKET SendSocket = 0); void Broadcastting(PACKET* pUserData); void Broadcastting(UPACKET* pPacket, SOCKET pSendUser = NULL); public: S_Chat_Svr(); virtual ~S_Chat_Svr(); }; #define S_CHAT S_Chat_Svr::GetInstance() <file_sep>#include<stdio.h> #include<conio.h> void main() { int sum = 0; int sum1 = 0; int max = 0; int iCount = 1; scanf_s("%d", &max); do { sum = sum + iCount++; } while (iCount <= max); printf("1~N개 까지의 합:%d\n", sum); _getch(); }<file_sep>// IME = input method editer // 완성워드 . 조합중워드 // input method manger = 국가별로 다존재하는 os // input method editer #include <iostream> #include <Windows.h> #include <vector> #pragma comment(lib,"imm32.lib") <file_sep>#include "xArcBall.h" D3DXMATRIX xArcBall::GetRotationMatrix() { D3DXMATRIX matRot; D3DXMatrixRotationQuaternion(&matRot, &m_qNow); return matRot; } void xArcBall::OnBegin(int x, int y) { m_bDrag = true; m_qDown = m_qNow; m_vDownPt = ScreenToVector(x, y); } // 2D -> 3d D3DXVECTOR3 xArcBall::ScreenToVector(float fX, float fY) { // fx*fx + fy*fy + fz*fz =r*r; float fHalfX = (g_rtClient.right / 2.0f); float fHalfY = (g_rtClient.bottom / 2.0f); float x = -(fX - fHalfX) / fHalfX; float y = (fY - fHalfY) / fHalfY; float z = 0.0f; float fFlag = (x*x + y * y); if (fFlag > 1.0f) { x *= (1.0f/sqrtf(fFlag) ); y *= (1.0f / sqrtf(fFlag)); } else { z = sqrtf(1.0f - fFlag); } return D3DXVECTOR3(x, y, z); } D3DXQUATERNION xArcBall::QuatFromBallPoints( D3DXVECTOR3 m_vDownPt, D3DXVECTOR3 m_vCurrentPt) { float fDot = D3DXVec3Dot(&m_vDownPt, &m_vCurrentPt); D3DXVECTOR3 vPart; D3DXVec3Cross(&vPart, &m_vDownPt, &m_vCurrentPt); D3DXQUATERNION qRet(vPart.x, vPart.y, vPart.z, fDot); return qRet; } void xArcBall::OnMove(int x, int y) { if (m_bDrag) { m_vCurrentPt = ScreenToVector(x, y); m_qNow = m_qDown * QuatFromBallPoints(m_vDownPt, m_vCurrentPt); } } void xArcBall::OnEnd() { m_bDrag = false; } xArcBall::xArcBall() { m_bDrag = false; m_vDownPt = D3DXVECTOR3(0, 0, 0); m_vCurrentPt = D3DXVECTOR3(0, 0, 0); D3DXQuaternionIdentity(&m_qNow); D3DXQuaternionIdentity(&m_qDown); } xArcBall::~xArcBall() { } <file_sep>#pragma once #include "Window.h" #include "Timer.h" class Core : public Window { public: Timer m_Timer; public: bool GameInit(); bool GameRun(); bool GameRelease(); bool GameFrame(); bool GameRender(); public: virtual bool Init() { return true; } virtual bool Frame() { return true; } virtual bool Render() { return true; } virtual bool Release() { return true; } public: Core(); virtual ~Core(); }; <file_sep>#pragma once #include "SAcceptor.h" class SCHATAccept : public SAcceptor { public: void AddUser(SOCKET socket, SOCKADDR_IN address); public: SCHATAccept(void); virtual ~SCHATAccept(void); }; <file_sep>#include <stdio.h> void main(int argc, char**argv) { printf("count =%d\n", argc); printf("string=%s\n", argv[0]); }<file_sep>#include "S_Client.h" #include "S_DebugString.h" unsigned __stdcall sendMessage(void* arg) { S_Debug.Print("%s", "send 스레드 시작"); S_Client* pClient = (S_Client*)arg; while (!pClient->m_bExit) { if (pClient->m_LoginOk && pClient->m_Send) { if (pClient->SendMsg(pClient->m_strBuf, PACKET_CHAT_MSG) <= 0) { break; } pClient->m_Send = false; } if (SwitchToThread() == FALSE) { Sleep(1); } } return 0; } unsigned __stdcall receiveMessage(void* arg) { S_Debug.Print("%s", "receive 스레드 시작"); S_Client* pClient = (S_Client*)arg; int iSocket = pClient->m_iSocket; char strBuffer[2048] = { 0, }; while (!pClient->m_bExit) { int iRet = recv(iSocket, strBuffer, sizeof(strBuffer), 0); if (iRet <= 0) { if (WSAGetLastError() == WSAEWOULDBLOCK) { continue; } pClient->m_bExit = true; closesocket(pClient->m_iSocket); break; } strBuffer[iRet] = 0; pClient->m_StreamPacket.Put(strBuffer, iRet, pClient); if (SwitchToThread() == FALSE) { Sleep(1); } } return 0; } int S_Client::ProcessPacket() { { S_Lock Lock(this); list<PACKET>::iterator iter; for (iter = m_StreamPacket.PacketList.begin(); iter != m_StreamPacket.PacketList.end(); iter++) { UPACKET* pPacket = &(*iter).packet; switch (pPacket->ph.type) { case PACEKT_CHAT_NAME_REQ: { S_Debug.Print("%s", pPacket->msg); }break; case PACKET_CHAT_MSG: { S_Debug.Print("%s", pPacket->msg); }break; } } m_StreamPacket.PacketList.clear(); } return 1; } int S_Client::SendMsg(char* pmsg, WORD code) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sprintf_s(sendmsg.msg, pmsg); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(sendmsg.msg); int iRet = send(m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if (iRet <= 0) { m_Send = false; if (WSAGetLastError() == WSAEWOULDBLOCK) { return 1; } return 0; } m_Send = false; return 1; } int S_Client::SendMsg(char* pmsg, int iSize, WORD code) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); memcpy(sendmsg.msg, pmsg, iSize); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + iSize; int iRet = send(m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if (iRet <= 0) { m_Send = false; if (WSAGetLastError() == WSAEWOULDBLOCK) { return 1; } return 0; } m_Send = false; return 1; } int S_Client::CreateConnectSocket(int iPort) { int Rv; m_iSocket = socket(AF_INET, SOCK_STREAM, 0); if (m_iSocket == INVALID_SOCKET) { return -1; } SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serveraddr.sin_port = htons(iPort); Rv = connect(m_iSocket, (sockaddr*)&serveraddr, sizeof(serveraddr)); if (Rv == SOCKET_ERROR) { return -1; } linger optval; int iLength = sizeof(optval); getsockopt(m_iSocket, SOL_SOCKET, SO_LINGER, (char*)&optval, &iLength); optval.l_onoff = 1; optval.l_linger = 1000; setsockopt(m_iSocket, SOL_SOCKET, SO_LINGER, (char*)&optval, iLength); int socketType1; int typeLen1 = sizeof(socketType1); getsockopt(m_iSocket, SOL_SOCKET, SO_TYPE, (char*)&socketType1, &typeLen1); if (socketType1 == SOCK_STREAM) { S_Debug.Print("%s", "SOCK_STREAM"); } else { S_Debug.Print("%s", "SOCk_DGRAM"); } getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1); S_Debug.Print("%s=%d", "SO_SNDBUF", socketType1); getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1); S_Debug.Print("%s=%d", "SO_RCVBUF", socketType1); return 0; } bool S_Client::Init() { int RV; WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return -1; } if (CreateConnectSocket(10000) == 0) { unsigned sendThread, receiveThread; m_SendThread = _beginthreadex(NULL, 0, sendMessage, (void*)this, 0, &sendThread); m_ReceiveThread = _beginthreadex(NULL, 0, receiveMessage, (void*)this, 0, &receiveThread); int iLevelSend = GetThreadPriority(HANDLE(m_SendThread)); int iLevelRecv = GetThreadPriority(HANDLE(m_ReceiveThread)); if (SetThreadPriority(HANDLE(m_ReceiveThread), THREAD_PRIORITY_ABOVE_NORMAL == TRUE)) { iLevelRecv = GetThreadPriority(HANDLE(m_ReceiveThread)); INT sss = 0; } m_LoginOk = true; } return true; } bool S_Client::Frame() { if (m_bExit) { S_Debug.Print("%s", "서버 종료"); m_bExit = false; } return true; } bool S_Client::Release() { m_bExit = true; closesocket(m_iSocket); WaitForSingleObject((HANDLE)m_SendThread, INFINITE); WaitForSingleObject((HANDLE)m_ReceiveThread, INFINITE); WSACleanup(); CloseHandle(HANDLE(m_ReceiveThread)); CloseHandle(HANDLE(m_SendThread)); m_ReceiveThread = NULL; m_SendThread = NULL; return true; } S_Client::S_Client() { m_Send = false; m_LoginOk = false; m_bExit = false; m_iSocket = 0; m_ReceiveThread = 0; m_SendThread = 0; } S_Client::~S_Client() { } <file_sep>#include "TRegion.h" int main(void) { TRegion::SetNotation(TRegion::POINT_POINT); // 출력 형식 지정 TRegion r1(10, 10, 100, 100); // 영역 r1 선언 TRegion r2(50, 50, 120, 120); // 영역 r2 선언 //////////////////// 상수 객체 반환 //////////////////////// const TRegion* x1 = r1.Get(); const TRegion& x2 = r2.GetRef(); //TRegion* x1 = r1.Get(); // 오류! 비상수 포인터 //TRegion& x2 = r2.GetRef(); // 오류! 비상수 참조 int iX = x1->GetWidth(); // 정상! 비 상수 반환 & 상수 함수 호출 int iT = x1->GetHeight(); // 정상! 상수 반환 & 상수 함수 호출 const int iC = x1->GetWidth(); // 정상! 비 상수 반환 & 상수 함수 호출 const int iD = x1->GetHeight(); // 정상! 상수 반환 & 상수 함수 호출 //int iValue = x1->GetLeft(); // 오류! 비상수 함수 호출 int iXref = x2.GetWidth(); // 정상! 상수 함수 호출 //int iValueref = x2.GetLeft(); // 오류! 비상수 함수 호출 /////////////////// 상수 데이터 반환 /////////////////////// int iY = r1.GetLeft(); // 정상! 비 상수 반환 함수 호출 int iZ = r1.GetTop(); // 정상! 상수 반환 함수 호출 const int iG = r1.GetLeft(); // 정상! 비 상수 반환 함수 호출 const int iJ = r1.GetTop(); // 정상! 상수 반환 함수 호출 //int* iP = r1.GetRight(); // 오류! 상수 반환 함수 호출 const int* iQ = r1.GetRight(); // 정상! 상수 반환 함수 호출 //int& i6 = r1.GetBottom(); // 오류! 상수 반환 함수 호출 const int& i7 = r1.GetBottom(); // 정상! 상수 반환 함수 호출 /////////////////// 영역 관리 함수 /////////////////////// TRegion r3; // r1과 r2의 교집합을 r3에 저장 r3.IntersectRegion(r1, r2); r3.Show(); // r1과 r2의 합집합을 r3에 저장 r3.UnionRegion(r1, r2); r3.Show(); // r3의 위치 이동 r3.Move(100, 100); r3.Show(); // r3의 크기 변경 r3.Resize(200, 200); r3.Show(); TRegion::SetNotation(TRegion::POINT_SIZE); // 출력 형식 변경 r1.Show(); r2.Show(); r3.Show(); return 0; } <file_sep>// kgcaExporter.cpp : DLL 응용 프로그램을 위해 내보낸 함수를 정의 합니다. #include "Header.h" #define KHJExporter_CLASS_ID Class_ID(0x7f1d60c8, 0x6c453ac4) class KHJExporter : public SceneExport { public: KHJExporter(); ~KHJExporter(); public: int ExtCount(); const TCHAR *Ext(int n); const TCHAR *LongDesc(); const TCHAR *ShortDesc(); const TCHAR *AuthorName(); const TCHAR *CopyrightMessage(); const TCHAR *OtherMessage1(); const TCHAR *OtherMessage2(); unsigned int Version(); void ShowAbout(HWND hwnd); public: BOOL SupportsOptions(int ext, DWORD options); int DoExport(const TCHAR *name, ExpInterface *ei, Interface*i, BOOL suppressPrompts = FALSE, DWORD options = 0); }; class KHJExportClassDesc :public ClassDesc2 { public: virtual int IsPublic() { return TRUE; } virtual void* Create(BOOL) { return new KHJExporter(); } virtual const TCHAR* ClassName() { return _T("KHJ_EXPORTER 1"); } virtual SClass_ID SuperClassID() { return SCENE_EXPORT_CLASS_ID; } virtual Class_ID ClassID() { return KHJExporter_CLASS_ID; } virtual const TCHAR* Category() { return _T("KHJ_EXPORTER"); } virtual const TCHAR* InternalName() { return _T("KHJ_EXPORT_ClassDesc"); } virtual HINSTANCE HInstance() { return hInstance; } }; ClassDesc2* GetExportDesc() { static KHJExportClassDesc KHJExportDesc; return &KHJExportDesc; } KHJExporter::KHJExporter() { } KHJExporter::~KHJExporter() { } int KHJExporter::ExtCount() { #pragma message(TODO("Returns the number of file name extensions supported by the plug-in")) return 1; } const TCHAR *KHJExporter::Ext(int) { #pragma message(TODO("Return the 'i-th' file name extension (i.e. \"3DS\").")) return _T("KHJ1"); } const TCHAR* KHJExporter::LongDesc() { #pragma message(TODO("Return long ASCII description (i.e. \"Targa 2.0 Image File\")"))) return _T("KHJ Exporter 1.0"); } const TCHAR* KHJExporter::ShortDesc() { #pragma message(TODO("Return short ASCII description (i.e. \"Targa\")")) return _T("KHJExporter"); } const TCHAR *KHJExporter::AuthorName() { #pragma message(TODO("Return ASCII Author name")) return _T("PROKVIP"); } const TCHAR *KHJExporter::CopyrightMessage() { #pragma message(TODO("Return ASCII Copyright message")) return _T(""); } const TCHAR *KHJExporter::OtherMessage1() { //TODO: Return Other message #1 if any return _T(""); } const TCHAR *KHJExporter::OtherMessage2() { //TODO: Return other message #2 in any return _T(""); } unsigned int KHJExporter::Version() { #pragma message(TODO("Return Version number * 100 (i.e. v3.01 = 301)")) return 100; } void KHJExporter::ShowAbout(HWND /*hWnd*/) { // Optional } BOOL KHJExporter::SupportsOptions(int /*ext*/, DWORD /*options*/) { #pragma message(TODO("Decide which options to support. Simply return true for each option supported by each Extension the exporter supports.")) return TRUE; } int KHJExporter::DoExport(const TCHAR *name, ExpInterface *ei, Interface *i, BOOL suppressPrompts, DWORD options) { return FALSE; } <file_sep>#include <iostream> using namespace std; typedef struct Node { int iDepth; int iOrder; int iData; struct Node* pChildNode[2]; }TNode; int g_iData[10] = { 5,0,4,7,8,3,9,2,6,1 }; int g_iIndex = 0; TNode* g_pRoot = 0; TNode* CreateNode(TNode* pParent) { if (pParent == 0)return 0; if (pParent->iDepth > 3)return 0; pParent->iOrder = g_iIndex++; pParent->pChildNode[0] = new TNode(); pParent->pChildNode[1] = new TNode(); pParent->pChildNode[0]->iDepth = pParent->iDepth + 1; pParent->pChildNode[1]->iDepth = pParent->iDepth + 1; CreateNode(pParent->pChildNode[0]); CreateNode(pParent->pChildNode[1]); } TNode* BinaryNode(TNode* pParent, int iData) { if (pParent == 0)return 0; if (pParent->iData > iData) { if (pParent->pChildNode[0] == 0) { pParent->pChildNode[0] = new TNode(); pParent->pChildNode[0]->iData = iData; pParent->pChildNode[0]->iDepth = pParent->iDepth + 1; } else { BinaryNode(pParent->pChildNode[0], iData); } } else { if (pParent->pChildNode[1] == 0) { pParent->pChildNode[1] = new TNode(); pParent->pChildNode[1]->iData = iData; pParent->pChildNode[1]->iDepth = pParent->iDepth + 1; } else { BinaryNode(pParent->pChildNode[1], iData); } } } TNode* BinarySearch(TNode* pParent, int iData) { if (pParent == 0)return 0; if (pParent->iData == iData) { return pParent; } if (pParent->iData > iData) { BinarySearch(pParent->pChildNode[0], iData); } else { BinarySearch(pParent->pChildNode[1], iData); } } void main() { g_pRoot = new TNode(); g_pRoot->iData = g_iData[g_iIndex++]; for (int i = 1; i < 10; i++) { BinaryNode(g_pRoot, g_iData[i]); } for (int i = 0; i < 10; i++) { TNode* pfind = BinarySearch(g_pRoot, g_iData[i]); cout << "[" << pfind->iData << "]" << endl; } system("pause"); }<file_sep>#include "TAvlTree.h" int TAvlTree::getHeight(Node* node) { if (node == nullptr) return 0; return node->height; } Node* TAvlTree::updateHeight(Node* node) { node->height = 1 + max(getHeight(Node->left), getHeight(Node->right)); return node; } Node* TAvlTree::insert(Node* root, int value) { if (root == nullptr) return new Node(value); if (root->value < value) { root->right = insert(root->right, value); } else if (root->value == value) { cout << "value: " << value << "No duplicate vertex allowed." << endl; return root; } else { root->left = insert(root->left, value); } root = updateHeight(root); int balance_factor = getHeight(root->left) - getHeight(root->right); //LR rotation if (balance_factor > 1 && root->left->value < value) { root->left = leftRotate(root->left); return rightRotate(root); } //RR rotation else if (balance_factor > 1 && root->left->value > value) { return rightRotate(root); } //LL rotation else if (balance_factor < -1 && root->right->value < value) { return leftRotate(root); } //RL rotation else if (balance_factor<-1 && root->right->value>value) { root->right = rightRotate(root->right); return leftRotate(root); } } Node* TAvlTree::leftRotate(Node* root) { Node* x = root->right; Node* t = x->left; root->right = t; x->left = root; //update height x = updateHeight(x); root = updateHeight(root); return x; } Node* TAvlTree::rightRotate(Node* root) { Node* x = root->left; Node* t = x->right; root->left = t; x->right = root; //update height root = updateHeight(root); x = updateHeight(x); return x; } TAvlTree::TAvlTree() { } TAvlTree::~TAvlTree() { } <file_sep>#include "SPacket.h" // 임계영역 , 락 CRITICAL_SECTION g_crit; // 유저모드 HANDLE g_hMutex; // 커널 모드 SOCKET g_allClientSocket[100]; int g_iNumClient = 0; int SendMsg(SOCKET sock, char* msg, WORD type) { SPacket packet(type); packet << msg; int iRet = send(sock, (char*)&packet.m_uPacket, packet.m_uPacket.ph.len + PACKET_HEADER_SIZE, 0); return iRet; } void GreetMessage(SOCKET sock) { char message[MAX_PATH] = { 0, }; sprintf_s(message, "[서버]환영합니다.\n"); SendMsg(sock, message, PACKET_CHAT_MSG); DWORD dwRet = WaitForSingleObject(g_hMutex, INFINITE); // 싱글 대기함수 g_allClientSocket[g_iNumClient] = sock; g_iNumClient++; ReleaseMutex(g_hMutex); // temp = sock } DWORD WINAPI ClientThread(LPVOID arg) // Thread 생성 { SOCKET sock = (SOCKET)arg; SOCKADDR_IN clientaddr; char buffer[256] = { 0, }; int recvbyte = 0; while (1) // 무한반복 { recvbyte += recv(sock, &buffer[recvbyte], sizeof(char)* PACKET_HEADER_SIZE - recvbyte, 0); if (recvbyte == 0) break; if (recvbyte == PACKET_HEADER_SIZE) { UPACKET packet; ZeroMemory(&packet, sizeof(packet)); memcpy(&packet.ph, buffer, sizeof(char)*PACKET_HEADER_SIZE); int rByte = 0; int iRecvByte = 0; do { iRecvByte = recv(sock, (char*)&packet.msg[rByte], sizeof(char)* packet.ph.len - rByte, 0); if (iRecvByte == 0)break; rByte += iRecvByte; } while (packet.ph.len > rByte); if (iRecvByte <= 0)break; recvbyte = 0; switch (packet.ph.type) { case PACKET_CHAT_MSG: { printf("패킷 완성 %s", packet.msg); //EnterCriticalSection(&g_crit); DWORD dwRet = WaitForSingleObject(g_hMutex,INFINITE); // 대기 함수 if (dwRet != WAIT_TIMEOUT) { for (int iClient = 0; iClient < g_iNumClient; iClient++) { int iSendByte = SendMsg(g_allClientSocket[iClient], packet.msg, PACKET_CHAT_MSG); if (iSendByte == SOCKET_ERROR) { printf(" 소켓 오류\n"); break; // 오류면 클라이언트 종료 } } } //LeaveCriticalSection(&g_crit); ReleaseMutex(g_hMutex); }break; } } Sleep(1); } // 클라이언트 종료 처리 // EnterCriticalSection(&g_crit); WaitForSingleObject(g_hMutex, INFINITE); // 대기함수 for (int iClient = 0; iClient < g_iNumClient; iClient++) { if (g_allClientSocket[iClient] == sock) { for (int iUser = iClient; iUser < g_iNumClient; iUser++) { g_allClientSocket[iUser] = g_allClientSocket[iUser + 1]; } break; } } g_iNumClient--; // LeaveCriticalSection(*g_crit); ReleaseMutex(g_hMutex); closesocket(sock); return 0; } // 소켓 생성 // 연결형, TCP프로토콜(SOCK_STREAM, IPPROTO_TCP) // 비연결형m, UDP프로토콜 (SOCK_DGRAM,IPPROTO_UDP) int main(int argc, char* argv[]) { HANDLE hExecuteMutex = CreateMutex(NULL, FALSE, L"OnceMutex"); if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(hExecuteMutex); return 1; } InitializeCriticalSection(&g_crit); // TRUE = 현재의 스레드가 소유자 // FALSE = 소유자가 없다. (신호상태) : 비신호 상태 unsigned short iPort = 10000; //atoi(argv[1]); // 윈도우 소켓 (윈속) 초기화 WSADATA wsa; int iRet; HANDLE hThread; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return 1; } { SOCKET listensock = socket(AF_INET, SOCK_STREAM, 0); { SOCKADDR_IN sa; ZeroMemory(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(iPort); sa.sin_addr.s_addr = htonl(INADDR_ANY); // 소켓을 대상 ip에 연결해라. iRet = bind(listensock, (SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR) return -1; iRet = listen(listensock, SOMAXCONN); if (iRet == SOCKET_ERROR)return -1; SOCKADDR_IN clientaddr; SOCKET client; while (1) { int addlen = sizeof(clientaddr); client = accept(listensock, (SOCKADDR*)&clientaddr, &addlen); printf("클라이언트 접속 : IP:%s,PORT:%d \n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); //EnterCriticalSection(&g_crit); // 신호상태 일 경우만 진입 WaitForSingleObject(g_hMutex, INFINITE); // 대기 함수 GreetMessage(client); //LeaveCriticalSection(&g_crit); ReleaseMutex(g_hMutex); // 비신호상태로 전환 DWORD dwRecvThreadID; hThread = CreateThread(0, 0, ClientThread, (LPVOID)client, 0, &dwRecvThreadID); } } closesocket(listensock); } // 윈도우 소켓 소멸 iRet = WSACleanup(); DeleteCriticalSection(&g_crit); CloseHandle(g_hMutex); CloseHandle(hExecuteMutex); return 0; }<file_sep>#pragma once #include <iostream> // 입출력 헤더 stdio와 같은개념 using namespace std; // std를 입력하지 않고 바로 사용가능 struct Node //구조체 노드 { Node* m_pNext; //노드의 멤버변수 int iData; int iCount; Node(int pData) { iData = pData; }; }; class CLinkedList { public: Node * m_Head; Node* m_Tail; int iMAX; public: void Add(); //더해주는 함수 void Del(int aData); //삭제하는 함수 void Print(); //출력하는 함수 void Find(int sData); //검색하는 함수 public: CLinkedList(); virtual ~CLinkedList(); }; <file_sep>#ifndef SAMPLE_MUTEX #define SAMPLE_MUTEX #include "SProtocol.h" #pragma pack(push, 1 ) typedef struct { int user_idx; BYTE posX; BYTE posY; BYTE direction; //0 ~7 8방향 }TPACKET_USER_POSITION; #define PACKET_USER_POSITION 3000 typedef struct { int user_idx; char uid[21]; char ups[15]; }TPACKET_USER_LOGIN; #define PACKET_USER_LOGIN 2000 // 서버 #define PACKET_CHAT_NAME_REQ 1000 // 대화명 입력해라. // 클라이언트 #define PACKET_CHAT_NAME_ACK 1001 // 대화명 입력 전송. // 보통 채팅 메세지 #define PACKET_CHAT_MSG 1002 // 대화명 입력 전송. #pragma pack(pop) #endif<file_sep>#include <iostream> #include <stddef.h> //hash example #include <stdio.h> #include <functional> #include <string> size_t stringLength(const char* source) { if (source == NULL) { return 0; } size_t length = 0; while (*source != '\0') { length++; source++; } return length; } //hash function static size_t djb_hash(const char* cp) { size_t hash = 5381; while (*cp) hash = 33 * hash ^ (unsigned char)*cp++; return hash; } // hash function static size_t fnv1a_hash(const char* cp) { size_t hash = 0x811c9dc5; while (*cp) { hash ^= (unsigned char)*cp++; hash *= 0x01000193; } return hash; } static size_t getHash(const char* source) { size_t length = stringLength(source); size_t hash = 0; for (size_t i = 0; i < length; i++) { char c=source[i]; int a = c - '0'; hash = (hash * 10) + a; } return hash; } static const char *const testCases[] = { "this", "is", "a", "test", "but", "i", "should", "use", "real", "dictonary" }; #define TABLE_SIZE (16) //unsigned long hash(unsigned char *str) //{ // unsigned long hash = 5381; // int c; // // while (c = *str++) // hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ // // return hash; //} //unsigned long hash(unsigned char *str) //{ // unsigned long hash = 5381; // int c; // // while (c = *str++) // hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ // // return hash; //} int main() { size_t name = getHash("<NAME>"); std::cout << "[" << name << "]" << std::endl; for (size_t i = 0; i < (sizeof(testCases) / sizeof(testCases[0])); i++) { const char* source = testCases[i]; size_t hash = fnv1a_hash(source); printf("%s<==>%zu\n", source, (hash % TABLE_SIZE)); } char nts1[] = "Test"; char nts2[] = "Test"; std::string str1(nts1); std::string str2(nts2); std::hash<char*>ptr_hash; std::hash<std::string>str_hash; std::cout << "same Hashes:\n" << std::boolalpha; std::cout << "nts1 and nts2:" << (ptr_hash(nts1) == ptr_hash(nts2)) << '\n'; std::cout << "str1 and str2:" << (ptr_hash(nts1) == ptr_hash(nts2)) << '\n'; return 0; }<file_sep>#pragma once #include "S_Window.h" #include "S_Input.h" #include "S_Time.h" class S_Core : public S_Window { public: S_Time m_Timer; HDC m_hScreenDC; HBITMAP m_hOldBitmap; HDC m_hOffScreenDC; HBITMAP m_hOffScreenBitmap; HBRUSH m_hbrBack; HBRUSH m_hbrOld; HANDLE m_hPen; HANDLE m_hOldPen; HFONT m_fontDefault; HFONT m_fontDefaultOld; public: bool GameRun(); bool GameInit(); bool GameFrame(); virtual bool GameRender(); bool GameRelease(); bool ResizeClient(UINT iWidth, UINT iHeight); virtual bool DrawDebug(); virtual bool DrawDebug(TCHAR* pString, int iX, int iY); virtual bool PreRender(); virtual bool PostRender(); public: virtual bool Init() { return true; } virtual bool PreFrame() { return true; } virtual bool PostFrame() { return true; } virtual bool Frame() { return true; } virtual bool Render() { return true; } virtual bool Release() { return true; }; public: S_Core(); virtual ~S_Core(); }; <file_sep>#include<stdio.h> #include<conio.h> void HanioTab(int n, char from, char temp, char to) { if (n > 0) { HanioTab(n - 1, from, to, temp); printf("[%d] %c-->%c\n", n, from, to); HanioTab(n - 1, temp, from, to); } } void HanioTower(int n, char from, char temp, char to) { if (n == 1) { printf("[%d] %c-->%c\n", n, from, to); } else { HanioTower(n - 1, from, to, temp); printf("[%d]%c-->%c\n", n, from, to); HanioTower(n - 1, temp, from, to); } } int factorial(int n) { if (n == 1) { return 1; } else { int iRet = factorial(n - 1); return n * iRet; } } void main() { int sum = 1; for (int i = 1; i <= 3; i++) { sum = sum * i; } printf("\n%d", sum); printf("\n%d", factorial(5)); int n; printf("¿ø¹Ý °¹¼ö...?"); scanf_s("%d", &n); HanioTower(n, 'a', 'b', 'c'); _getch(); }<file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #ifndef TSERVER_STD #define TSERVER_STD #include <thread> #include <process.h> #include <ws2tcpip.h> #include "TStd.h" #endif<file_sep>#include <iostream> using namespace std; template<typename D> void Swap(D& Num, D& Count) { D temp = Num; Num = Count; Count = temp; } int main() { int Num = 10, Count = 40; cout << " Num:" << Num << ", Count" << Count << endl; Swap(Num, Count); cout << "swap Num: " << Num << ", Count " << Count << endl; system("pause"); }<file_sep>#include<stdio.h> void main() { int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } printf("1~100±îÁöÀÇ ÇÕ:%d\n",sum); }<file_sep>#pragma once #include "SUser.h" class TChatUser : public SUser { public: int m_iIndex; int m_PositionX; int m_PositionY; int m_iDirection; public: void Movement(UPACKET* pPacket); void AddPacket(S_PACKET& addPacket ); void DeleteUser( SOCKET socket ); void DeleteUser(); void Dispatch( DWORD dwByteSize, LPOVERLAPPED ov); public: TChatUser(void); ~TChatUser(void); }; <file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { system("cls"); char *pArray[6]; for (int iCnt = 0; iCnt < 6; iCnt++) { pArray[iCnt] = (char*)malloc(sizeof(char) * 4); } for (int iCnt = 0; iCnt < 6; iCnt++) { for (int jCnt = 0; jCnt < 3; jCnt++) { pArray[iCnt][jCnt] = 65 + iCnt * 3 + jCnt; } pArray[iCnt][3] = 0; } for (int iCnt = 0; iCnt < 6; iCnt++) { printf("\n"); printf("[%d]=%s", iCnt, pArray[iCnt]); } for (int iCnt = 0; iCnt < 6; iCnt++) { free(pArray[iCnt]); } _getch(); }<file_sep>#include "xMap.h" float xMap::Lerp(float fStart, float fEnd, float fTangent) { return fStart - (fStart*fTangent) + (fEnd*fTangent); } float xMap::GetHeightmap(int row, int col) { return m_VertexList[row * m_iNumRows + col].p.y;// *m_xMapDesc.fScaleHeight; } float xMap::GetHeight(float fPosX, float fPosZ) { // fPosX/fPosZ의 위치에 해당하는 높이맵셀을 찾는다. // m_iNumCols와m_iNumRows은 가로/세로의 실제 크기값임. float fCellX = (float)(m_iNumCellCols*m_fCellDistance / 2.0f + fPosX); float fCellZ = (float)(m_iNumCellRows*m_fCellDistance / 2.0f - fPosZ); // 셀의 크기로 나누어 0~1 단위의 값으로 바꾸어 높이맵 배열에 접근한다. fCellX /= (float)m_fCellDistance; fCellZ /= (float)m_fCellDistance; // fCellX, fCellZ 값보다 작거나 같은 최대 정수( 소수부분을 잘라낸다.) float fVertexCol = ::floorf(fCellX); float fVertexRow = ::floorf(fCellZ); // 높이맵 범위를 벗어나면 강제로 초기화 한다. if (fVertexCol < 0.0f) fVertexCol = 0.0f; if (fVertexRow < 0.0f) fVertexRow = 0.0f; if ((float)(m_iNumCols - 2) < fVertexCol) fVertexCol = (float)(m_iNumCols - 2); if ((float)(m_iNumRows - 2) < fVertexRow) fVertexRow = (float)(m_iNumRows - 2); // 계산된 셀의 플랜을 구성하는 4개 정점의 높이값을 찾는다. // A B // *---* // | / | // *---* // C D float A = GetHeightmap((int)fVertexRow, (int)fVertexCol); float B = GetHeightmap((int)fVertexRow, (int)fVertexCol + 1); float C = GetHeightmap((int)fVertexRow + 1, (int)fVertexCol); float D = GetHeightmap((int)fVertexRow + 1, (int)fVertexCol + 1); // A정점의 위치에서 떨어진 값(변위값)을 계산한다. 0 ~ 1.0f float fDeltaX = fCellX - fVertexCol; float fDeltaZ = fCellZ - fVertexRow; // 보간작업를 위한 기준 페잇스를 찾는다. float fHeight = 0.0f; // 윗페이스를 기준으로 보간한다. // fDeltaZ + fDeltaX < 1.0f if (fDeltaZ < (1.0f - fDeltaX)) //ABC { float uy = B - A; // A->B float vy = C - A; // A->C // 두 정점의 높이값의 차이를 비교하여 델타X의 값에 따라 보간값을 찾는다. fHeight = A + Lerp(0.0f, uy, fDeltaX) + Lerp(0.0f, vy, fDeltaZ); } // 아래페이스를 기준으로 보간한다. else // DCB { float uy = C - D; // D->C float vy = B - D; // D->B // 두 정점의 높이값의 차이를 비교하여 델타Z의 값에 따라 보간값을 찾는다. fHeight = D + Lerp(0.0f, uy, 1.0f - fDeltaX) + Lerp(0.0f, vy, 1.0f - fDeltaZ); } return fHeight; } bool xMap::CreateHeightMap(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, T_STR szName) { HRESULT hr; D3DX11_IMAGE_INFO imageinfo; ID3D11Resource* pLoadTexture = nullptr; D3DX11_IMAGE_LOAD_INFO info; ZeroMemory(&info, sizeof(info)); info.MipLevels = 1; info.Usage = D3D11_USAGE_STAGING; info.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; info.Format = DXGI_FORMAT_R8G8B8A8_UNORM; info.pSrcInfo = &imageinfo; if (FAILED(hr = D3DX11CreateTextureFromFile(pDevice, szName.c_str(), &info, NULL, &pLoadTexture, NULL))) { return false; } ID3D11Texture2D* pTex2D = nullptr; if( FAILED(pLoadTexture->QueryInterface( __uuidof(ID3D11Texture2D), (LPVOID*)&pTex2D))) { return false; } SAFE_RELEASE(pLoadTexture); D3D11_TEXTURE2D_DESC desc; pTex2D->GetDesc(&desc); m_fHeightList.resize(desc.Height*desc.Width); D3D11_MAPPED_SUBRESOURCE map; UINT index = D3D11CalcSubresource(0, 0, 1); if (SUCCEEDED(pContext->Map(pTex2D, index, D3D11_MAP_READ, 0, &map))) { UCHAR* pTexels = (UCHAR*)map.pData; for (UINT iRow = 0; iRow < desc.Height; iRow++) { UINT rowStart = iRow * map.RowPitch; for (UINT iCol= 0; iCol < desc.Width; iCol++) { UINT colStart = iCol * 4; UCHAR uRed = pTexels[rowStart + colStart +0]; m_fHeightList[iRow*desc.Width+ iCol] = uRed; } } pContext->Unmap(pTex2D, index); } m_iNumRows = desc.Height; m_iNumCols = desc.Width; SAFE_RELEASE(pTex2D); return true; } HRESULT xMap::CreateVertexData() { m_iNumVertex = m_iNumVertices; m_VertexList.resize(m_iNumVertices); float fHalfCols = (m_iNumCols-1) / 2.0f; float fHalfRows = (m_iNumRows - 1) / 2.0f; float fOffsetU = 1.0f / (m_iNumCols - 1); float fOffsetV = 1.0f / (m_iNumRows - 1); for (int iRow = 0; iRow < m_iNumRows; iRow++) { for (int iCol = 0; iCol < m_iNumCols; iCol++) { int iIndex = iRow * m_iNumCols + iCol; m_VertexList[iIndex].p.x = (iCol-fHalfCols)*m_fCellDistance; m_VertexList[iIndex].p.y = GetHeightOfVertex(iIndex); m_VertexList[iIndex].p.z = -((iRow - fHalfRows)*m_fCellDistance); m_VertexList[iIndex].n = GetNormalOfVertex(iIndex); m_VertexList[iIndex].c = GetColorOfVertex(iIndex); m_VertexList[iIndex].t = GetTextureOfVertex(fOffsetU*iCol, fOffsetV*iRow); } } return S_OK; } HRESULT xMap::CreateIndexData() { m_iNumIndex = m_iNumFace * 3; m_IndexList.resize(m_iNumIndex); int iIndex = 0; for (int iRow = 0; iRow < m_iNumCellRows; iRow++) { for (int iCol = 0; iCol < m_iNumCellCols; iCol++) { // 0 1 2 // 3 4 5 int iNextRow = iRow + 1; m_IndexList[iIndex + 0] = iRow * m_iNumCols + iCol; m_IndexList[iIndex + 1] = m_IndexList[iIndex + 0]+1; m_IndexList[iIndex + 2] = iNextRow * m_iNumCols + iCol; m_IndexList[iIndex + 3] = m_IndexList[iIndex + 2]; m_IndexList[iIndex + 4] = m_IndexList[iIndex + 1]; m_IndexList[iIndex + 5] = m_IndexList[iIndex + 2]+1; iIndex += 6; } } GenVertexNormal(); return S_OK; } bool xMap::GenVertexNormal() { InitFaceNormals(); GenNormalLookupTable(); CalcPerVertexNormalsFastLookup(); return true; } void xMap::InitFaceNormals() { m_FaceNormalList.resize(m_iNumFace); } void xMap::CalcFaceNormals() { int iFaceIndex = 0; for (int iIndex = 0; iIndex < m_IndexList.size(); iIndex += 3) { DWORD i0 = m_IndexList[iIndex]; DWORD i1 = m_IndexList[iIndex + 1]; DWORD i2 = m_IndexList[iIndex + 2]; m_FaceNormalList[iFaceIndex++] = ComputeFaceNormal(i0, i1, i2); } } D3DXVECTOR3 xMap::ComputeFaceNormal(DWORD i0, DWORD i1, DWORD i2) { D3DXVECTOR3 vNormal; D3DXVECTOR3 v0 = m_VertexList[i1].p - m_VertexList[i0].p; D3DXVECTOR3 v1 = m_VertexList[i2].p - m_VertexList[i0].p; D3DXVec3Cross(&vNormal, &v0, &v1); D3DXVec3Normalize(&vNormal, &vNormal); return vNormal; } void xMap::GenNormalLookupTable() { m_NormalLooupTabel.resize(m_iNumVertex); for (int iFace = 0; iFace < m_iNumFace; iFace++) { for (int iVertex = 0; iVertex < 3; iVertex++) { for (int iTable = 0; iTable < 6; iTable++) { int iIndex = m_IndexList[iFace*3+iVertex]; if (m_NormalLooupTabel[iIndex].faceIndex[iTable] == -1) { m_NormalLooupTabel[iIndex].faceIndex[iTable] = iFace; break; } } } } } void xMap::CalcPerVertexNormalsFastLookup() { CalcFaceNormals(); for (int iVertex = 0; iVertex < m_NormalLooupTabel.size(); iVertex++) { D3DXVECTOR3 avgNormal(0,0,0); int iFace = 0; for (iFace = 0; iFace < 6; iFace++) { if (m_NormalLooupTabel[iVertex].faceIndex[iFace] != -1) { int iFaceIndex = m_NormalLooupTabel[iVertex].faceIndex[iFace]; avgNormal += m_FaceNormalList[iFaceIndex]; } else { break; } } D3DXVec3Normalize(&m_VertexList[iVertex].n, &avgNormal); //// 조명계산 //D3DXVECTOR3 vLight(100, 100, 100); //D3DXVec3Normalize(&vLight, &vLight); //float fDot = D3DXVec3Dot(&m_VertexList[iVertex].n,&vLight); //m_VertexList[iVertex].c.x = fDot; //m_VertexList[iVertex].c.y = fDot; //m_VertexList[iVertex].c.z = fDot; } } D3DXVECTOR2 xMap::GetTextureOfVertex(float fU, float fV) { return D3DXVECTOR2(fU, fV); } D3DXVECTOR3 xMap::GetNormalOfVertex(int iIndex) { return D3DXVECTOR3(0.0f, 1.0f, 0.0f ); } D3DXVECTOR4 xMap::GetColorOfVertex(int iIndex) { return D3DXVECTOR4( randstep(0.0f, 1.0f), randstep(0.0f, 1.0f), randstep(0.0f, 1.0f), 1.0f ); } float xMap::GetHeightOfVertex(int iIndex) { if (m_fHeightList.size() > 0) { return m_fHeightList[iIndex] * m_fScaleHeight; } return 0.0f; } bool xMap::CreateMap(xMapDesc desc) { m_iNumRows = desc.iNumRows; m_iNumCols = desc.iNumCols; m_iNumCellRows = m_iNumRows-1; m_iNumCellCols= m_iNumCols-1; m_iNumVertices = m_iNumRows * m_iNumCols; m_iNumFace = m_iNumCellRows* m_iNumCellCols*2; m_fCellDistance = desc.fDistance; m_fScaleHeight = desc.fScaleHeight; m_xMapDesc = desc; return true; } bool xMap::Load(ID3D11Device* pDevice, xMapDesc desc) { m_pd3dDevice = pDevice; if (!CreateMap(desc)) { return false; } xShape::Create(m_pd3dDevice,desc.szShaderFile,desc.szTextureFile); return true; } bool xMap::Init() { return true; } bool xMap::Frame() { return xShape::Frame(); } bool xMap::Render(ID3D11DeviceContext* pContext) { xShape::Render(pContext); return true; } bool xMap::Release() { xShape::Release(); return true; } xMap::xMap() { m_fScaleHeight = 1; } xMap::~xMap() { } <file_sep>#include "S_SvrUser.h" void S_SvrUser::Dispatch(DWORD dwByteSize, LPOVERLAPPED Ov) { OVERLAPPEDEX* pOv = (OVERLAPPEDEX*)Ov; if (dwByteSize == 0) { return; } if (pOv->i_Flags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put(m_szRecvBuf.buf, dwByteSize, this); } if (pOv->i_Flags == OVERLAPPEDEX::MODE_SEND) { } WaitforPacketReceive(); } void S_SvrUser::AddPacket(PACKET& addPacket) { { S_Lock Lock(this); m_StreamPacket.PacketList.push_back(addPacket); } return; } bool S_SvrUser::Create() { ZeroMemory(&m_OV, sizeof(m_OV)); WaitforPacketReceive(); return true; } void S_SvrUser::WaitforPacketReceive() { DWORD Transferred, flag = 0; m_szRecvBuf.buf = m_strBuffer; m_szRecvBuf.len = 4096; int ret = WSARecv(m_Socket, &m_szRecvBuf, 1, &Transferred, &flag, (LPOVERLAPPED)&m_OV, NULL); if (ret == SOCKET_ERROR) { int Error = WSAGetLastError(); if (Error != WSA_IO_PENDING) { int i = 0; } } } bool S_SvrUser::Run() { char szMsgBuf[2048] = { 0, }; int strlen = 0; while (1) { strlen = recv(m_Socket, szMsgBuf, sizeof(szMsgBuf), 0); if (strlen <= 0)break; szMsgBuf[strlen] = 0; m_StreamPacket.Put(szMsgBuf, strlen, this); Sleep(10); } DeleteUser(m_Socket); return true; } void S_SvrUser::DeleteUser(SOCKET socket) { } void S_SvrUser::DeleteUser() { } S_SvrUser::S_SvrUser() { m_Socket = 0; } S_SvrUser::~S_SvrUser() { closesocket(m_Socket); } <file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<time.h> #include<string.h> #include<conio.h> typedef struct StudentCode { char strName[4]; int Index; int iKor; int iEng; int iMat; int Total; float Average; }Student; Student *pStudentFile = 0; int MAX=0; enum WORK { NewData, PrintData, FindName, FindIndex, AddData, DeleteData, SaveData, LoadData, EXIT = 99, }; void DataNew(); void DataPrint(); void NameFind(); void IndexFind(); void DataAdd(); void DataDelete(); void DataSave(); void DataLoad(); void DataNew() { printf("\n 학생의 수를 입력하시오 :"); scanf("%d", &MAX); if (pStudentFile != NULL) { free(pStudentFile); pStudentFile = 0; } if (pStudentFile == NULL) { pStudentFile = (Student *)malloc(sizeof(Student)*MAX); } for (int i = 0; i < MAX; i++) { pStudentFile[i].strName[0] = 65 + rand() % 26; pStudentFile[i].strName[1] = 65 + rand() % 26; pStudentFile[i].strName[2] = 65 + rand() % 26; pStudentFile[i].strName[3] = '\0'; pStudentFile[i].Index = i; pStudentFile[i].iKor = rand() % 101; pStudentFile[i].iEng = rand() % 101; pStudentFile[i].iMat = rand() % 101; pStudentFile[i].Total = pStudentFile[i].iKor + pStudentFile[i].iEng + pStudentFile[i].iMat; pStudentFile[i].Average = pStudentFile[i].Total / 3.0f; } }<file_sep>#include <winsock2.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") #define MAX_BUF_SIZE 1048 void main() { HANDLE m_hWriteFile = ::CreateFile(L"xxx.bmp", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); BOOL bEnable = TRUE; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&bEnable, sizeof(bEnable)) < 0) { return; } SOCKADDR_IN addr; ZeroMemory(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(9009); addr.sin_addr.s_addr = INADDR_ANY; bind(sock, (SOCKADDR*)&addr, sizeof(addr)); SOCKADDR_IN peeraddr; char buf[MAX_BUF_SIZE + 1] = { 0, }; int addrlen; int iTotalSize = 0; while (1) { addrlen = sizeof(peeraddr); int iRet = recvfrom(sock, buf, MAX_BUF_SIZE + 1, 0, (SOCKADDR*)&peeraddr, &addrlen); if (iRet == SOCKET_ERROR) { break; } if (_stricmp(buf, "end") == 0) { break; } DWORD writeBytes = 0; WriteFile(m_hWriteFile, buf, iRet, &writeBytes, NULL); iTotalSize += writeBytes; printf("\n%d", iTotalSize); } CloseHandle(m_hWriteFile); closesocket(sock); WSACleanup(); } //#include "winsock2.h" //#include <iostream> //#include <conio.h> //using namespace std; //#pragma comment(lib, "ws2_32.lib") //#define MYPORT 9009 // the port users will be connecting to // //int main() //{ // WSADATA wsaData; // WSAStartup(MAKEWORD(2, 2), &wsaData); // SOCKET sock; // sock = socket(AF_INET, SOCK_DGRAM, 0); // char broadcast = '1'; // if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0) // { // closesocket(sock); // return 0; // } // struct sockaddr_in Recv_addr; // struct sockaddr_in Sender_addr; // int len = sizeof(struct sockaddr_in); // char recvbuff[50]; // int recvbufflen = 50; // char sendMSG[] = "Broadcast message from READER"; // Recv_addr.sin_family = AF_INET; // Recv_addr.sin_port = htons(MYPORT); // Recv_addr.sin_addr.s_addr = INADDR_ANY; // if (bind(sock, (sockaddr*)&Recv_addr, sizeof(Recv_addr)) < 0) // { // cout << "Error in BINDING" << WSAGetLastError(); // _getch(); // closesocket(sock); // return 0; // } // recvfrom(sock, recvbuff, recvbufflen, 0, (sockaddr *)&Sender_addr, &len); // cout << "\n\n\tReceived Message is : " << recvbuff; // cout << "\n\n\tPress Any to send message"; // _getch(); // if (sendto(sock, sendMSG, strlen(sendMSG) + 1, 0, (sockaddr *)&Sender_addr, sizeof(Sender_addr)) < 0) // { // cout << "Error in Sending." << WSAGetLastError(); // cout << "\n\n\t\t Press any key to continue...."; // _getch(); // closesocket(sock); // return 0; // } // else // cout << "\n\n\n\tREADER sends the broadcast message Successfully"; // // cout << "\n\n\tpress any key to CONT..."; // _getch(); // closesocket(sock); // WSACleanup(); //}<file_sep>#include "xShape.h" HRESULT xPlaneShape::CreateVertexData() { HRESULT hr = S_OK; // ¾Õ¸é m_VertexList.resize(4); m_VertexList[0] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[1] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[2] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[3] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); m_iNumVertex = m_VertexList.size(); return hr; } HRESULT xPlaneShape::CreateIndexData() { HRESULT hr = S_OK; m_IndexList.resize(6); int iIndex = 0; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 1; m_IndexList[iIndex++] = 2; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 2; m_IndexList[iIndex++] = 3; m_iNumIndex = m_IndexList.size(); return hr; } xPlaneShape::xPlaneShape() { } xPlaneShape::~xPlaneShape() { }<file_sep>#include "TStreamPacket.h" #include "TServer.h" void TStreamPacket::Put(char* recvBuffer, int iRecvSize, TUser* pUser) { { TSynchronize sync(this); // 받는 버퍼의 용량이 부족하면 if (m_iWritePos + iRecvSize >= MAX_RECV_SIZE) { char strTemp[MAX_RECV_SIZE] = { 0, }; memcpy(strTemp, &m_RecvBuffer[m_iStartPos], m_iReadPos); ZeroMemory(&m_RecvBuffer, sizeof(char)* MAX_RECV_SIZE); memcpy(&m_RecvBuffer, &strTemp, m_iReadPos); m_pPacket = (P_UPACKET)m_RecvBuffer; m_iStartPos = 0; m_iWritePos = m_iReadPos; } memcpy(&m_RecvBuffer[m_iWritePos], recvBuffer, iRecvSize); m_iWritePos += iRecvSize; m_iReadPos += iRecvSize; if (m_iReadPos < PACKET_HEADER_SIZE) return; // 패킷의 시작 m_pPacket = (P_UPACKET)&m_RecvBuffer[m_iStartPos]; // 1개의 패킷 사이즈만큼 받았다면 if (m_iReadPos >= m_pPacket->ph.len) { do { T_PACKET add; ZeroMemory(&add, sizeof(add)); memcpy(&add.packet, &m_RecvBuffer[m_iStartPos], m_pPacket->ph.len); add.pUser = pUser; if (pUser != NULL) { pUser->AddPacket(add); } // 1개의 패킷을 처리하고 남은 잔여량 크기 m_iReadPos -= m_pPacket->ph.len; // 패킷의 시작 위치 m_iStartPos += m_pPacket->ph.len; // 잔여량이 패킷 헤더모다 작을 경우 if (m_iReadPos < PACKET_HEADER_SIZE) break; m_pPacket = (P_UPACKET)&m_RecvBuffer[m_iStartPos]; } while (m_iReadPos >= m_pPacket->ph.len); } } }; TStreamPacket::TStreamPacket() { ZeroMemory(m_RecvBuffer, sizeof(char) * MAX_RECV_SIZE); m_iStartPos = 0; m_iWritePos = 0; m_iReadPos = 0; m_pPacket = NULL; } TStreamPacket::~TStreamPacket() { }<file_sep>#include "CLinkedList.h" void main() { CLinkedList Data; Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Add(); Data.Del(5); Data.Find(2); system("pause"); }<file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> //행렬 예제(포인터) void printf_array(int *num, int row, int col); void main() { int row; int col; int datd[100][100]; int i; int j; printf("Enter the row and columm:"); scanf_s("%d%d", &row, &col); if (row > 1000 || col > 1000) { printf("the values should be between 0 and 999\n"); exit(1); } for (i = 0; i < row; i++) { for (j = 0; j < col; j++) *(&data[0][0] + i * col + j) = (int)rand() % 100; } print_array((int*)data, row, col); } void printf_array(int *num, int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { printf("%3d", *(num + i * col + j)); printf("\n"); } } }<file_sep>#pragma once #include "TThread.h" class TWorkThread : public TThread { public: HANDLE m_hIOCP; bool Run(); void Set( HANDLE hIOCP ){ m_hIOCP = hIOCP; }; public: TWorkThread(void); virtual ~TWorkThread(void); }; <file_sep>#include <iostream> int g_iArray[10][10]; unsigned short Hash(void* p) { unsigned short val = reinterpret_cast<unsigned short>(p); return val % 10; } void Set(int iRow, int iValue) { for (int i = 0; i < 10; i++) { if (g_iArray[iRow][i] <= 0) { g_iArray[iRow][i] = iValue; break; } } } int Get(int iRow, int iValue) { for (int i = 0; i < 10; i++) { if (g_iArray[iRow][i] == iValue) { return g_iArray[iRow][i]; } } return -1; } int main() { int iArray[100]; for (int i = 0; i < 10; i++) { iArray[i] = i + 1; unsigned short iHash = Hash(&iArray[i]); std::cout << Get(iHash, iArray[i]) << " " << std::endl; } return 0; }<file_sep>#include <iostream> #include <stdio.h> #include <conio.h> //dynamic_cast는 vtable를 사용하기 떄문에 //반드시 virtual 함수가 있어야 작동한다. struct A { virtual void test() { printf_s("in A\n"); } }; struct B :A { virtual void test() { printf_s("in B\n"); } }; struct C :B { virtual void test() { printf_s("in C\n"); } void test2() { printf_s("test2 in C\n"); } }; void Globaltest(A& a) { try { C &c = dynamic_cast<C&>(a); printf_s("in GlobalTest\n"); } catch (std::bad_cast) { printf_s("Can't cast to C\n"); } } int main() { A *pa = new C; A *pa2 = new B; pa->test(); B *pb = dynamic_cast<B *>(pa); if (pb) pb->test(); C *pc = dynamic_cast<C *>(pa2); if (pc) pc->test2(); C ConStack; Globaltest(ConStack); //B가C를 알고 있지 않기 때문에 실패한다. B BonStack; Globaltest(BonStack); _getch(); }<file_sep>#pragma once #include "S_Thread.h" class S_ChatUdp: public S_Thread { public: SOCKET m_Socket; SOCKET m_SendSocket; SOCKADDR_IN m_RecvAddr; SOCKADDR_IN m_SendAddr; public: bool Init(); bool Run(); bool Release(); public: S_ChatUdp(); virtual ~S_ChatUdp(); }; <file_sep>#include "TRectangle.h" void TRectangle::Draw() { cout << "Draw Rectangle: "; cout << "(" << x << "," << y << "),"; cout << width << "x" << height; cout << endl; } TRectangle::TRectangle() { cout << "TRectangle 持失切" << endl; } TRectangle::TRectangle(int x,int y, int width, int height) :TFigure(x,y,width,height) { cout << "TRectangle 持失切 " << endl; } TRectangle::~TRectangle() { cout << "TRectangle 背薦切" << endl; } <file_sep>#pragma once #include <windows.h> #include <assert.h> #include <tchar.h> class DXWindow { public: //---------------------------- //Global Variables //---------------------------- HINSTANCE m_hInstance; // 인스턴스 핸들 HWND m_hWnd; // 윈도우 핸들 DWORD m_dwWindowStyle; // 윈도우 스타일 RECT m_rcWindowBounds; // 윈도우 영역 RECT m_rcWindowClient; // 클라이언트 영역 UINT m_iWindowWidth; // 클라이언트 영역 가로크기 UINT m_iWindowHeight;// 클라이언트 영역 세로크기 public: // 윈도우 생성 bool InitWindow(HINSTANCE hInstance, int nCmdShow, const wchar_t* strWindowTitle); // 윈도우 위치 화면 중앙으로 이동 void CenterWindow(HWND hwnd); public: virtual bool Init(); virtual bool Frame(); virtual bool Render(); virtual bool Release(); virtual bool Run(); virtual LRESULT WndProc(HWND, UINT, WPARAM, LPARAM); public: DXWindow(void); virtual ~DXWindow(void); }; <file_sep>#pragma once #include "S_CharMgr.h" #define MAX_BONE_MATRICES 255 struct CBConstBoneWorld { D3DXMATRIX g_mConstBoneWorld[MAX_BONE_MATRICES]; }; class S_HeroObj : public TModel { public: int m_iObjectIndex; S_Character* m_pChar; T_STR m_szName; TBoneObj* m_pBoneObject; bool m_bConstantBufferType; int m_iStartFrame; int m_iLastFrame; int m_iCurrentFrame; float m_fFrame; float m_fLerpTime; float m_fSpeed; D3DXMATRIX m_pMatrix[255]; CBConstBoneWorld m_cbBoneData; ComPtr<ID3D11Buffer> m_pCBConstBoneWorld; int m_iMatrixIndex; bool m_bBoneRender; public: void SetBoneMatrices(vector<D3DXMATRIX>* pList); bool Frame(); bool Render(ID3D11DeviceContext* pContext); void SetActionFrame(int iStart, int iEnd, int iCharacterMatrixIndex = -1, int iModelMatrixIndex = -1); HRESULT CreateConstantBuffer(); public: S_HeroObj(); virtual ~S_HeroObj(); }; <file_sep>#pragma once #include "xShape.h" struct xMapDesc { int iNumCols; int iNumRows; int fDistance; float fScaleHeight; T_STR szTextureFile; T_STR szShaderFile; }; class xMap : public xBoxShape { public: xMapDesc m_xMapDesc; int m_iNumRows; int m_iNumCols; int m_iNumCellRows; int m_iNumCellCols; int m_iNumFace; int m_iNumVertices; float m_fCellDistance; public: virtual HRESULT CreateVertexData() override; virtual HRESULT CreateIndexData() override; D3DXVECTOR2 GetTextureOfVertex(float fU, float fV); D3DXVECTOR3 GetNormalOfVertex(int iIndex); D3DXVECTOR4 GetColorOfVertex(int iIndex); float GetHeightOfVertex(int iIndex); public: HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; public: bool CreateMap(xMapDesc desc); bool Load(ID3D11Device* pDevice, xMapDesc desc); bool Init(); bool Frame(); bool Render(ID3D11DeviceContext* pContext); bool Release(); public: xMap(); virtual ~xMap(); }; <file_sep>#pragma once #include "SPacketPool.h" #include "TProtocolChat.h" class TChatPacketPool : public SPacketPool { public: void ProcessWork(S_PACKET* pUserData); public: TChatPacketPool(void); ~TChatPacketPool(void); }; <file_sep>#include "xCore.h" #include "D3Dcompiler.h" //D3DCOMPILE_DEBUG #include <math.h> #define CPU struct P3VERTEX //pnct { float x; float y; float z; float r, g, b, a; float u; float v; }; //콘스턴트 버퍼, 상수버퍼. 셰이더내에서 글로벌 변수와 비슷하게 쓰인다. //float4개 단위로 보내야한다. 안쓰더라도 float 4개단위로 보내야한다. //fTime[0]이거 하나만 쓰더라도 float fTime[4];이렇게 선언해야한다. struct VS_CB { float r, g, b, a; float fTime[4]; }; class Sample : public xCore { public: VS_CB m_constantData; ID3D11Buffer* m_pVertextBuffer; ID3D11Buffer* m_pIndexBuffer; ID3D11Buffer* m_pConstantBuffer; ID3D11VertexShader* m_pVS; ID3D11PixelShader* m_pPS; ID3D11PixelShader* m_pPS2; ID3D11PixelShader* m_pPS3; ID3D11InputLayout* m_pVertexLayout; std::vector<P3VERTEX> m_verList; std::vector<DWORD> m_indexList; ID3D11ShaderResourceView* m_pTexSRV; ID3D11ShaderResourceView* m_pTexSRVAlpha; ID3D11ShaderResourceView* m_pTexSRVNoAlpha; ID3D11SamplerState* m_pSamplerState; ID3D11BlendState* m_pAlphaBlend; ID3D11BlendState* m_pAlphaBlend2; ID3D11BlendState* m_pAlphaBlend3; public: HRESULT CreateVertextBuffer(); HRESULT CreateIndexBuffer(); HRESULT CreateConstantBuffer(); HRESULT LoadShaderAndInputLayout(); HRESULT CreatePixelShader(); HRESULT LoadTextureFile(ID3D11ShaderResourceView** ppTexSRV, const TCHAR* szFileName); HRESULT SetBlendState(); public: bool Init() { xCore::Init(); if (FAILED(SetBlendState())) { return false; } m_constantData.r = cosf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.g = sinf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.b = 0.5f + cosf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.a = 1; m_constantData.fTime[0] = g_fGameTimer; LoadTextureFile(&m_pTexSRV, L"../../data/Particle4.dds"); LoadTextureFile(&m_pTexSRVAlpha, L"../../data/hud.dds"); LoadTextureFile(&m_pTexSRVNoAlpha, L"../../data/Dirt_Diff.dds"); CreateVertextBuffer(); CreateIndexBuffer(); CreateConstantBuffer(); if (FAILED(LoadShaderAndInputLayout())) { return false; } if (FAILED(CreatePixelShader())) { return false; } return true; } bool Frame() { xCore::Frame(); //static float fAngle = 0.0f; //fAngle += g_fSecPerFrame; #ifdef GPU //gpu update m_constantData.r = cosf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.g = sinf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.b = 0.5f + cosf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.a = 1; m_constantData.fTime[0] = cosf(g_fGameTimer) * 0.5f + 0.5f; m_constantData.fTime[1] = 1.0f; m_constantData.fTime[2] = 1.0f; //m_constantData.fTime[3] = fAngle; m_pContext->UpdateSubresource(m_pConstantBuffer, 0, NULL, &m_constantData, 0, 0); #elif defined CPU //cpu update //MAP ->자물쇠 열고 //~~ -->상수버퍼갱신 //UNMAP ->자물쇠 닫고 D3D11_MAPPED_SUBRESOURCE address; HRESULT hr; if (SUCCEEDED(hr = m_pContext->Map(m_pConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &address))) { VS_CB* cb = (VS_CB*)address.pData; cb->r = cosf(g_fGameTimer) * 0.5f + 0.5f; cb->g = sinf(g_fGameTimer) * 0.5f + 0.5f; cb->b = 0.5f + cosf(g_fGameTimer) * 0.5f + 0.5f; cb->a = 1.0f; cb->fTime[0] = cosf(g_fGameTimer) * 0.5f + 0.5f; cb->fTime[1] = 2.0f; cb->fTime[2] = 2.0f; //cb->fTime[3] = fAngle; m_pContext->Unmap(m_pConstantBuffer, 0); } #endif return true; } bool Render() { xCore::Render(); m_pContext->VSSetShader(m_pVS, NULL, 0); m_pContext->HSSetShader(NULL, NULL, 0); m_pContext->DSSetShader(NULL, NULL, 0); m_pContext->GSSetShader(NULL, NULL, 0); m_pContext->PSSetSamplers(0, 1, &m_pSamplerState); m_pContext->OMSetBlendState(m_pAlphaBlend, 0, -1); m_pContext->PSSetShaderResources(0, 1, &m_pTexSRV); m_pContext->PSSetShader(m_pPS, NULL, 0); UINT offset = 0; UINT stride = sizeof(P3VERTEX); m_pContext->IASetVertexBuffers(0, 1, &m_pVertextBuffer, &stride, &offset); m_pContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); //상수버퍼 적용(픽셀셰이더) m_pContext->PSSetConstantBuffers(0, //0 슬롯번호(레지스터 번호) 1, //1 상수버퍼 1개 &m_pConstantBuffer); //상수버퍼 적용(버텍스셰이더) m_pContext->VSSetConstantBuffers(0, 1, &m_pConstantBuffer); m_pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_pContext->IASetInputLayout(m_pVertexLayout); //m_pContext->Draw(6, 0); //multi pass Rendering //m_pContext->DrawIndexed(m_indexList.size(), 0, 0); m_pContext->PSSetShader(m_pPS2, NULL, 0); m_pContext->OMSetBlendState(m_pAlphaBlend2, 0, -1); m_pContext->PSSetShaderResources(0, 1, &m_pTexSRVNoAlpha); m_pContext->DrawIndexed(m_indexList.size(), 0, 0); m_pContext->PSSetShader(m_pPS3, NULL, 0); m_pContext->OMSetBlendState(m_pAlphaBlend3, 0, -1); m_pContext->PSSetShaderResources(0, 1, &m_pTexSRVAlpha); m_pContext->DrawIndexed(m_indexList.size(), 0, 0); return true; } bool Release() { xCore::Release(); if (m_pVertextBuffer != NULL) m_pVertextBuffer->Release(); if (m_pIndexBuffer != NULL) m_pIndexBuffer->Release(); if (m_pConstantBuffer != NULL) m_pConstantBuffer->Release(); if (m_pVS != NULL) m_pVS->Release(); if (m_pPS != NULL) m_pPS->Release(); if (m_pVertexLayout != NULL) m_pVertexLayout->Release(); m_pVertextBuffer = NULL; m_pIndexBuffer = NULL; m_pConstantBuffer = NULL; m_pVS = NULL; m_pPS = NULL; m_pVertexLayout = NULL; return true; } public: Sample() {} ~Sample() {} }; HRESULT Sample::CreateVertextBuffer() { HRESULT hr; P3VERTEX vList[6]; m_verList.resize(4); //정점의 저장순서 : 시계방향 //반시계방향으로 그리면 안나온다. m_verList[0].x = -0.5f; m_verList[0].y = 0.5f; m_verList[0].z = 0.5f; m_verList[0].u = 0.0f; m_verList[0].v = 0.0f; m_verList[0].r = 1.0f; m_verList[0].g = 0.0f; m_verList[0].b = 0.0f; m_verList[1].x = 0.5f; m_verList[1].y = 0.5f; m_verList[1].z = 0.5f; m_verList[1].u = 1.0f; m_verList[1].v = 0.0f; m_verList[1].r = 0.0f; m_verList[1].g = 1.0f; m_verList[1].b = 0.0f; m_verList[2].x = -0.5f; m_verList[2].y = -0.5f; m_verList[2].z = 0.5f; m_verList[2].u = 0.0f; m_verList[2].v = 1.0f; m_verList[2].r = 0.0f; m_verList[2].g = 0.0f; m_verList[2].b = 1.0f; /*vList[3].x = -0.5f; vList[3].y = -0.5f; vList[3].z = 0.5f; vList[4].x = 0.5f; vList[4].y = 0.5f; vList[4].z = 0.5f;*/ m_verList[3].x = 0.5f; m_verList[3].y = -0.5f; m_verList[3].z = 0.5f; m_verList[3].u = 1.0f; m_verList[3].v = 1.0f; m_verList[3].r = 1.0f; m_verList[3].g = 1.0f; m_verList[3].b = 1.0f; //GPU상에 메모리를 할당함. D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.ByteWidth = m_verList.size() * sizeof(P3VERTEX); //36바이트 bd.Usage = D3D11_USAGE_DEFAULT; //GPU에 메모리를 할당해라. 기본이 GPU메모리. GPU는 READ/WRITE 가능.CPU는 접근불가능하다. //D3D11_USAGE_STAGING만이 CPU가 접근가능하다. 단점은 느리다. bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; //정점버퍼 //GPU상에 메모리를 셋팅하고 할당함. //hr = m_pd3dDevice->CreateBuffer(&bd, &InitialData, &m_pVertextBuffer); D3D11_SUBRESOURCE_DATA InitialData; ZeroMemory(&InitialData, sizeof(InitialData)); InitialData.pSysMem = &(m_verList.at(0)); if (FAILED(hr = m_pd3dDevice->CreateBuffer(&bd, &InitialData, &m_pVertextBuffer))) { return hr; } return hr; } HRESULT Sample::CreateIndexBuffer() { HRESULT hr; m_indexList.push_back(0); m_indexList.push_back(1); m_indexList.push_back(2); m_indexList.push_back(2); m_indexList.push_back(1); m_indexList.push_back(3); /*DWORD indices[] = { 0,1,2, 2,1,3, };*/ //GPU상에 메모리를 할당함. int iNumCount = sizeof(m_indexList) / sizeof(m_indexList[0]); D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.ByteWidth = m_indexList.size() * sizeof(DWORD); bd.Usage = D3D11_USAGE_DEFAULT; //GPU에 메모리를 할당해라. 기본이 GPU메모리. GPU는 READ/WRITE 가능.CPU는 접근불가능하다. //D3D11_USAGE_STAGING만이 CPU가 접근가능하다. 단점은 느리다. bd.BindFlags = D3D11_BIND_INDEX_BUFFER; //인덱스버퍼 //GPU상에 메모리를 셋팅하고 할당함. //hr = m_pd3dDevice->CreateBuffer(&bd, &InitialData, &m_pIndexBuffer))) D3D11_SUBRESOURCE_DATA InitialData; ZeroMemory(&InitialData, sizeof(InitialData)); InitialData.pSysMem = &(m_indexList.at(0)); if (FAILED(hr = m_pd3dDevice->CreateBuffer(&bd, &InitialData, &m_pIndexBuffer))) { return hr; } return hr; } HRESULT Sample::CreateConstantBuffer() { HRESULT hr; //GPU상에 메모리를 할당함. D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.ByteWidth = sizeof(VS_CB); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //상수버퍼 //GPU상에 메모리를 셋팅하고 할당함. //Usage //D3D11_USAGE_DEFAULT = 0, // gpu w/r가능. CPU 접근 불가능. //D3D11_USAGE_IMMUTABLE = 1, // gpu r 가능 //D3D11_USAGE_DYNAMIC = 2, // 중간에 변경가능. CPUAccessFlags 값을 셋팅해야한다. //D3D11_USAGE_STAGING = 3 // cpu w/r 가능 #ifdef CPU bd.Usage = D3D11_USAGE_DYNAMIC; //D3D11_USAGE_DYNAMIC : GPU는 READ/WRITE 가능. cpu Read X/ Write 0. bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; //D3D11_USAGE_DYNAMIC이면 CPUAccessFlags 값을 셋팅해야한다. #elif defined GPU bd.Usage = D3D11_USAGE_DEFAULT; #endif D3D11_SUBRESOURCE_DATA InitialData; ZeroMemory(&InitialData, sizeof(InitialData)); InitialData.pSysMem = &(m_constantData); if (FAILED(hr = m_pd3dDevice->CreateBuffer(&bd, &InitialData, &m_pConstantBuffer))) { return hr; } return hr; } HRESULT Sample::LoadShaderAndInputLayout() { HRESULT hr = S_OK; ID3DBlob* pVSBuf = NULL; ID3DBlob* pErrorMsgs = NULL; //L"vertexshader.txt" => 셰이더파일이름, "VS" => VertexShader함수이름(), "vs_5_0"=> 컴파일러 DWORD dwFlags = D3DCOMPILE_DEBUG; if (FAILED(hr = D3DX11CompileFromFile(L"vertextshader.txt", NULL, NULL, "VS", "vs_5_0", dwFlags, NULL, NULL, &pVSBuf, &pErrorMsgs, NULL))) { OutputDebugStringA((char*)pErrorMsgs->GetBufferPointer()); } //셰이더 컴파일된 결과(오브젝트파일, 목적파일) V_RETURN(m_pd3dDevice->CreateVertexShader(pVSBuf->GetBufferPointer(), pVSBuf->GetBufferSize(), NULL, &m_pVS)); //InputLayout. //셰이더 함수의 선언. 전달인자 타입으로 POSITION을 쓰겠다. //float4 VS(in float3 pos : POSITION ) : SV_POSITION D3D11_INPUT_ELEMENT_DESC layout[] = { //5번째 전달인자인 0에서 DXGI_FORMAT_R32G32B32_FLOAT만큼 꺼낸다. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, //5번째 전달인자인 12바이트에서 DXGI_FORMAT_R32G32_FLOAT만큼 꺼낸다. { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, //5번째 전달인자인 28바이트에서 DXGI_FORMAT_R32G32_FLOAT만큼 꺼낸다. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; int iNum = sizeof(layout) / sizeof(layout[0]); //layout.SemanticName = "POSITION"; //함수전달인자 타입. //layout.SemanticIndex = 0; //layout.Format = DXGI_FORMAT_R32G32B32_FLOAT; //POSITION은 float3개이다. //layout.InputSlot = 0; //layout.AlignedByteOffset = 0; //layout.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; //layout.InstanceDataStepRate = 0; m_pd3dDevice->CreateInputLayout(layout, iNum, pVSBuf->GetBufferPointer(), pVSBuf->GetBufferSize(), &m_pVertexLayout); pVSBuf->Release(); return hr; } HRESULT Sample::CreatePixelShader() { HRESULT hr = S_OK; //L"vertexshader.txt" => 셰이더파일이름, "PS" => PixelShader함수이름(), "ps_5_0"=> 컴파일러 ID3DBlob* pPSBuf = NULL; ID3DBlob* pErrorMsgs = NULL; DWORD dwFlags = D3DCOMPILE_DEBUG; if (FAILED(hr = D3DX11CompileFromFile(L"vertextshader.txt", NULL, NULL, "PS", "ps_5_0", dwFlags, NULL, NULL, &pPSBuf, &pErrorMsgs, NULL))) { OutputDebugStringA((char*)pErrorMsgs->GetBufferPointer()); } //셰이더 컴파일된 결과(오브젝트파일, 목적파일) V_RETURN(m_pd3dDevice->CreatePixelShader(pPSBuf->GetBufferPointer(), pPSBuf->GetBufferSize(), NULL, &m_pPS)); pPSBuf->Release(); //2) //ID3DBlob* pPSBuf = NULL; //ID3DBlob* pErrorMsgs = NULL; //DWORD dwFlags = D3DCOMPILE_DEBUG; if (FAILED(hr = D3DX11CompileFromFile(L"vertextshader.txt", NULL, NULL, "PS2", "ps_5_0", dwFlags, NULL, NULL, &pPSBuf, &pErrorMsgs, NULL))) { OutputDebugStringA((char*)pErrorMsgs->GetBufferPointer()); } //셰이더 컴파일된 결과(오브젝트파일, 목적파일) V_RETURN(m_pd3dDevice->CreatePixelShader(pPSBuf->GetBufferPointer(), pPSBuf->GetBufferSize(), NULL, &m_pPS2)); pPSBuf->Release(); //3) //ID3DBlob* pPSBuf = NULL; //ID3DBlob* pErrorMsgs = NULL; //DWORD dwFlags = D3DCOMPILE_DEBUG; if (FAILED(hr = D3DX11CompileFromFile(L"vertextshader.txt", NULL, NULL, "PS3", "ps_5_0", dwFlags, NULL, NULL, &pPSBuf, &pErrorMsgs, NULL))) { OutputDebugStringA((char*)pErrorMsgs->GetBufferPointer()); } //셰이더 컴파일된 결과(오브젝트파일, 목적파일) V_RETURN(m_pd3dDevice->CreatePixelShader(pPSBuf->GetBufferPointer(), pPSBuf->GetBufferSize(), NULL, &m_pPS3)); pPSBuf->Release(); return hr; } HRESULT Sample::LoadTextureFile(ID3D11ShaderResourceView** ppTexSRV, const TCHAR* szFileName) { HRESULT hr = S_OK; //D3DX11_IMAGE_LOAD_INFO pLoadInfo; //D3DX11_IMAGE_INFO pSrcInfo; //ZeroMemory(&pLoadInfo, sizeof(D3DX11_IMAGE_LOAD_INFO)); //pLoadInfo.Format = DXGI_FORMAT_FROM_FILE; //pLoadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE; //pLoadInfo.Width = D3DX11_DEFAULT; //pLoadInfo.Height = D3DX11_DEFAULT; //pLoadInfo.pSrcInfo = &pSrcInfo; //pLoadInfo.MipLevels = 1; if (FAILED(hr = D3DX11CreateShaderResourceViewFromFile(m_pd3dDevice, szFileName, NULL, NULL, ppTexSRV, NULL))) { return hr; } D3D11_SAMPLER_DESC sd; ZeroMemory(&sd, sizeof(D3D11_SAMPLER_DESC)); sd.AddressU = D3D11_TEXTURE_ADDRESS_MIRROR; sd.AddressV = D3D11_TEXTURE_ADDRESS_MIRROR; sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; m_pd3dDevice->CreateSamplerState(&sd, &m_pSamplerState); return hr; } HRESULT Sample::SetBlendState() { HRESULT hr = S_OK; D3D11_BLEND_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.RenderTarget[0].BlendEnable = true; //FinalColor = destColor * DescBlend + srcColor * SrcBlend; bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; //FinalAlpha = destAlpha * DescBlendAlpha + srcAlpha * SrcBlendAlpha; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; m_pd3dDevice->CreateBlendState(&bd, (ID3D11BlendState **)&m_pAlphaBlend); //2) bd.RenderTarget[0].BlendEnable = false; //FinalColor = destColor * DescBlend + srcColor * SrcBlend; bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; //FinalAlpha = destAlpha * DescBlendAlpha + srcAlpha * SrcBlendAlpha; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; m_pd3dDevice->CreateBlendState(&bd, (ID3D11BlendState **)&m_pAlphaBlend2); //3) bd.RenderTarget[0].BlendEnable = true; //FinalAlpha = destAlpha * DescBlendAlpha + srcAlpha * SrcBlendAlpha; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; m_pd3dDevice->CreateBlendState(&bd, (ID3D11BlendState **)&m_pAlphaBlend3); return hr; } GAMERUN("AlphaBlend", 800, 600);<file_sep>#include "xCore.h" class Sample : public xCore { xBoxShape m_ObjBox; xPlaneShape m_ObjPlane; xLineShape m_ObjLine; xSphereShape m_ObjSphere; D3DXMATRIX m_World[100]; public: void DeleteResources() { } HRESULT CreateResources(UINT width, UINT height) { return S_OK; } bool Init() { D3DXMatrixIdentity(&m_World[0]); for (int iObj = 1; iObj < 100; iObj++) { m_World[iObj] = m_World[0]; m_World[iObj]._43 = iObj * 10; } // 모델뷰 카메라 전환 SwapModelView(); m_pMainCamera->SetViewMatrix(D3DXVECTOR3(0.0f, 10.0f, -10.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f)); m_ObjLine.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/Eye.bmp"); m_ObjBox.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/Eye.bmp"); m_ObjPlane.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/Eye.bmp"); m_ObjSphere.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/Eye.bmp"); return true; } bool Frame() { m_ObjLine.Frame(); m_ObjPlane.Frame(); m_ObjSphere.Frame(); return m_ObjBox.Frame(); } bool Render() { // 박스 출력 int iRenderCnt = 0; for (int iObj = 0; iObj < 100; iObj++) { D3DXVECTOR3 vPos; vPos.x = m_World[iObj]._41; vPos.y = m_World[iObj]._42; vPos.z = m_World[iObj]._43; m_World[iObj] = m_pMainCamera->m_matWorld; m_World[iObj]._41 = vPos.x; m_World[iObj]._42 = vPos.y; m_World[iObj]._43 = vPos.z; if (m_pMainCamera->ClassifySphere(vPos, 1.44f)) { m_ObjBox.SetMatrix(&m_World[iObj], &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_ObjBox.Render(m_pContext); iRenderCnt++; } } return true; } bool Release() { m_ObjLine.Release(); m_ObjSphere.Release(); m_ObjPlane.Release(); return m_ObjBox.Release(); } public: Sample() { } ~Sample() {} }; GAME_RUN("SampleModelView", 800, 600) <file_sep>#pragma once #include "CCCore.h" class CCSample : public CCCore { public: bool Init(); bool Frame(); bool Render(); public: CCSample(); virtual ~CCSample(); }; <file_sep>#include "TFigure.h" void TFigure::Move(int x, int y) { this->x = x; this->y = y; } void TFigure::Resize(int width, int height) { this->width = width; this->height = height; } void TFigure::Draw() { cout << "Figure::Draw" << endl; } TFigure::TFigure() { cout << "TFigure 持失切" << endl; } TFigure::TFigure(int x, int y, int width, int height) { Move(x, y); Resize(width, height); cout << "TFigure 持失切" << endl; } TFigure::~TFigure() { cout << "TFigure 背薦切 " << endl; } <file_sep>#pragma once #include "TSynchronize.h" class TThread : public TServerObj { public: unsigned int m_hThread; unsigned int m_iThreadID; bool m_bStarted; public: void CreateThread(); virtual bool Run(); static unsigned int WINAPI HandleRunner(LPVOID parameter); public: TThread(void); virtual ~TThread(void); }; <file_sep>#pragma once #include <iostream> #include <vector> using namespace std; enum Direction{ North, East,South,West }; class MapSite { public: virtual void Enter() = 0; }; class Room : public MapSite { public: Room() {} Room(int RoomNo) { _roomNumber = RoomNo;}; MapSite* GetSide(Direction dir)const { return _sides[dir]; } void SetSide(Direction dir, MapSite* pMapSize) { _sides[dir] = pMapSize; }; virtual void Enter() {}; private: MapSite * _sides[4]; int _roomNumber; }; class Wall : public MapSite { public: Wall() {} virtual void Enter() {} }; class Door : public MapSite { public: Door() {} Door(Room* a, Room* b) { _room1 = a; _room2 = b; } virtual void Enter() {} Room* OtherSideFrom(Room*){} private: Room * _room1; Room* _room2; bool _isOpen; }; class Maze { public: Maze() {} void AddRoom(Room* room) { m_RoomList.push_back(room); } Room* RoomNo(int no)const { return m_RoomList[no]; } vector<Room*>m_RoomList; };<file_sep>#pragma once #include "DIDevice.h" class DIWindow: public DIDevice { public: //////////////////////////////////////////////////////////// // Global Variables //////////////////////////////////////////////////////////// HINSTANCE m_hInstance; // 인스턴스 핸들 HWND m_hWnd; // 윈도우 핸들 DWORD m_dwWindowStyle; // 윈도우 스타일 RECT m_rcWindowBounds; // 윈도우 영역 RECT m_rcWindowClient; // 클라이언트 영역 UINT m_iWindowWidth; // 클라이언트 영역 가로크기 UINT m_iWindowHeight; // 클라이언트 영역 세로크기 bool m_bActive; // 윈도우의 활성화 여부를 판단한다. public: // 윈도우 생성 bool InitWindow(HINSTANCE hInstance, int nCmdShow, TCHAR* strWindowTitle, BOOL IsFullScreen = FALSE); // 윈도우 위치 화면 중앙으로 이동 void CenterWindow(HWND hwnd); public: virtual bool Init(); virtual bool Frame(); virtual bool Render(); virtual bool Release(); virtual bool Run(); virtual LRESULT WndProc(HWND, UINT, WPARAM, LPARAM); public: DIWindow(void); virtual ~DIWindow(void); }; <file_sep>#include <Windows.h> #include <iostream> #include <tchar.h> #include <string> #include <conio.h> using namespace std; #define MAX_WORK_THREAD 4 #define MAX_READ_SZIE 4096 // 중요 class TIocp { public: HANDLE m_hIOCP; HANDLE m_hFileRead; HANDLE m_hFileWrite; OVERLAPPED m_hReadOV; OVERLAPPED m_hWriteOV; HANDLE m_hEventKillThread; HANDLE m_hWorkThread[MAX_WORK_THREAD]; char m_szReadBuffer[MAX_READ_SZIE]; public: void Init(); void Frame(); bool WaitForRead(); bool DispatchRead(DWORD dwTransfer); bool DispatchWrite(DWORD dwTransfer); static DWORD WINAPI WorkerThread(LPVOID parameter); public: ~TIocp() {} void Release() { CloseHandle(m_hFileRead); CloseHandle(m_hFileWrite); CloseHandle(m_hIOCP); CloseHandle(m_hWorkThread[0]); CloseHandle(m_hWorkThread[1]); CloseHandle(m_hWorkThread[2]); CloseHandle(m_hWorkThread[3]); } }; DWORD WINAPI TIocp::WorkerThread(LPVOID parameter) { TIocp* iocp = (TIocp*)parameter; OVERLAPPED ov; DWORD bytesTransfer; ULONG_PTR keyValue; while (1) { if (WAIT_OBJECT_0 == ::WaitForSingleObject(iocp->m_hEventKillThread, 1)); { break; } // IOCP QUEUE // GetQueuedCompletionStatus = QUEUE에 있는 데이터를 빼온다. BOOL bRet=::GetQueuedCompletionStatus(iocp->m_hIOCP, &bytesTransfer,&keyValue, (LPOVERLAPPED*)&ov,1); if (bRet == TRUE) // Read 작업이 완료되면 블랙포인트가 여기에 잡힌다. { if (keyValue == (ULONG_PTR)iocp->m_hFileRead) { iocp->DispatchRead(bytesTransfer); } else { iocp->DispatchWrite(bytesTransfer); } } else { if (GetLastError() == WAIT_TIMEOUT) { continue; } //....... } } return 0; } bool TIocp::DispatchRead(DWORD dwTransfer) { DWORD dwWrite; if(::WriteFile(m_hFileWrite,m_szReadBuffer,dwTransfer,&dwWrite,(LPOVERLAPPED)&m_hWriteOV)==FALSE); { if (GetLastError() != ERROR_IO_PENDING) // 핵심적인 작업 { return false; } } LARGE_INTEGER data; data.QuadPart = dwTransfer; m_hReadOV.Offset += data.LowPart; m_hReadOV.OffsetHigh += data.HighPart; WaitForRead(); return true; } bool TIocp::DispatchWrite(DWORD dwTransfer) { LARGE_INTEGER data; data.QuadPart = dwTransfer; m_hWriteOV.Offset += data.LowPart; m_hWriteOV.OffsetHigh += data.HighPart; return true; } void TIocp::Init() { m_hFileRead = CreateFile( // 읽고 L"aaaa.zip", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); m_hFileWrite = CreateFile( // 쓰기 L"copy.zip", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); DWORD id; for (int i = 0; i < MAX_WORK_THREAD; i++) { m_hWorkThread[i] = ::CreateThread(0, 0, WorkerThread, this, 0, &id); } m_hEventKillThread = ::CreateEvent(0, TRUE, FALSE,L"EventKillThread"); ::ResetEvent(m_hEventKillThread); m_hIOCP=::CreateIoCompletionPort(INVALID_HANDLE_VALUE,0,0,0); // iocp m_gIOCP= 기술자,중계적인 역활 // m_hIOCP 핸들이 관리를 한다. 다른 쓰레드의 작업을 확인할수 있다. ::CreateIoCompletionPort(m_hFileRead,m_hIOCP,(ULONG_PTR)m_hFileRead,0); //key == 완료키 // ULONG_PTR 대신에 DWORD를 넣어도 된다. ::CreateIoCompletionPort(m_hFileWrite,m_hIOCP, (ULONG_PTR)m_hFileWrite,0); } bool TIocp::WaitForRead() { DWORD dwReadBytes = 0; if (::ReadFile(m_hFileRead,m_szReadBuffer, MAX_READ_SZIE, &dwReadBytes,&m_hReadOV)==FALSE) // :: 범위 해결 연산자. // 비동기 작업 { if (GetLastError() == ERROR_IO_PENDING) // 핵심적인 작업 { return true; } return false; } //else // true 읽은거다.. 다 끝났어 // 혹시 모를 ERROR 떄문에 확인한다. // 사실상 없어도 된다. 정상적으로 돌아간다면 .. //{ // if (dwReadBytes == 0 || // GetLastError() == ERROR_HANDLE_EOF) // { // return false; // } //} return true; } void TIocp::Frame() { //WaitForMultipleObjects(MAX_WORK_THREAD,m_hWorkThread,TRUE,1); // 1을 넣으면 타임 아웃이 걸린다. WaitForRead(); while(WaitForMultipleObjects(MAX_WORK_THREAD, m_hWorkThread, TRUE, 1)); Release(); } void Main() { TIocp iocp; iocp.Init(); iocp.Frame(); _getch(); }<file_sep>#pragma once #include "Sstd.h" #include "dinput.h" #pragma comment(lib,"dinput8.lib") #pragma comment(lib,"dxguid.lib") class sInput : public SSingleton<sInput> { private: friend class SSingleton<sInput>; public: LPDIRECTINPUT8 m_pDI; LPDIRECTINPUTDEVICE8 m_pKey; LPDIRECTINPUTDEVICE8 m_pMouse; BYTE m_KeyState[256]; DIMOUSESTATE m_MouseState; public: bool Init(); bool Frame(); bool Release(); protected: sInput(); public: virtual ~sInput(); }; #define I_Input sInput::GetInstance() <file_sep>#pragma once #include "DDefine.h" class DIDevice { public: ID3D11Device * m_pd3dDevice; // 디바이스 객체 IDXGISwapChain* m_pSwapChain; // 스왑체인 객체 ID3D11RenderTargetView* m_pRenderTargetView; // 메인 랜더타켓 뷰 D3D11_VIEWPORT m_ViewPort; // 뷰포트 D3D_DRIVER_TYPE m_driverType; // 디바이스 타입 (디폴트:하드웨어 가속) IDXGIFactory* m_pGIFactory; //DXGI 객체 ID3D11DeviceContext* m_plmmediateContext; // 디바이스 컨텍스트 D3D_FEATURE_LEVEL m_FeatureLevel; // 특성 수준 BOOL m_IsFullScreenMode; // 풀스크린 디바이스 여부 판단 public: BOOL GetFullScreenFlag(); void SetFullScreenFlag(BOOL bFlag); ID3D11Device* GetDevice(); ID3D11DeviceContext* GetContext(); IDXGISwapChain* GetSwapChain(); ID3D11RenderTargetView* GetRenderTargeView(); IDXGIFactory* GetGIFactory(); public: //////////////////////////////////////////// // 디바이스 및 스왑 체인 생성 : InitDevice() //////////////////////////////////////////// HRESULT InitDevice(HWND hWnd, UINT iWidth, UINT iHeight, BOOL IsFullScreen = FALSE); // 0, InitDevice() // 1, CreateGIFactory() // 2, CreateDevice() // 3, CreateSwapChain() // 4, SetRenderTargetView() // 5, SetViewPort() //////////////////////////////////////////////////////////////////////////////// HRESULT CreateDevice(); HRESULT CreateGIFactory(); HRESULT CreateSwapChain(HWND hWnd, UINT iWidth, UINT iHeigh, BOOL IsFUllScreen = FALSE); //////////////////////////////////////////////////////// //////// ////////////////////////////////////////////////////// HRESULT SetRenderTargetView(); HRESULT SetViewPort(); bool CleanupDevice(); /////////////////////////////////////////////////////// // 변경된 클라이언트 영역을 재설정 한다. /////////////////////////////////////////////////////// HRESULT ResizeDevice(UINT iWidth, UINT iHeight); public: DIDevice(void); virtual ~DIDevice(void); }; <file_sep>#include "S_ChatUdp.h" #include "S_DebugString.h" bool S_ChatUdp::Init() { m_SendSocket = socket(AF_INET, SOCK_DGRAM, 0); m_Socket = socket(AF_INET, SOCK_DGRAM,0); int optval = 1; setsockopt(m_SendSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); setsockopt(m_Socket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); m_RecvAddr.sin_family = AF_INET; m_RecvAddr.sin_port = htons(10001); m_RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); int retval = ::bind(m_Socket, (SOCKADDR*)&m_RecvAddr, sizeof(m_RecvAddr)); if (retval == SOCKET_ERROR)return false; m_SendAddr.sin_family = AF_INET; m_SendAddr.sin_port = htons(9001); m_SendAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); CreateThread(); return true; } bool S_ChatUdp::Run() { int retval, addrlen; SOCKADDR_IN PeerAddr; char buffer[2048] = { 0, }; while (1) { addrlen = sizeof(PeerAddr); retval = recvfrom(m_Socket, buffer, 2048, 0, (SOCKADDR*)&PeerAddr, &addrlen); if (retval == SOCKET_ERROR) { S_Debug.Print("%s", "ERROR!!!"); break; } S_Debug.Print("Recv...IP=%s,PORT=%d,%s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buffer); buffer[retval] = 0; retval = sendto(m_SendSocket, buffer, strlen(buffer), 0, (SOCKADDR*)&m_SendAddr, sizeof(m_SendAddr)); if (retval == SOCKET_ERROR) { S_Debug.S_Error(true); S_Debug.Print("%s", "Error!!"); break; } S_Debug.Print("Send...IP=%s,PORT=%d,%s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buffer); } closesocket(m_Socket); m_Socket = 0; return true; } bool S_ChatUdp::Release() { if (m_Socket != 0) { closesocket(m_Socket); m_Socket = 0; } return true; } S_ChatUdp::S_ChatUdp() { m_Socket = 0; } S_ChatUdp::~S_ChatUdp() { } <file_sep>#include "TEmployee.h" TEmployee::TEmployee(char* _name) { strcpy_s(name, _name); } const char* TEmployee::GetName() { return name; } TEmployee::~TEmployee() { } <file_sep>#pragma once #define DIRECTINPUT_VERSION 0x0800 #ifndef UNICODE #error "TBAIS는 유니코드로 컴파일 해야 합니다." #endif #include <Windows.h> #include <tchar.h> #include <time.h> #include <crtdbg.h> #include <cassert> #include <assert.h> #include <d3dx11.h> #include <D3Dcompiler.h> #include <dinput.h> #include <d2d1.h> #include <d2d1helper.h> #include <dwrite.h> // C RunTime Header Files #include <stdlib.h> #include <malloc.h> #include <memory> #include <new> #include <set> #include <list> #include <string> #include <map> #include <vector> #include <algorithm> #include <bitset> #include <limits> #include <functional> using namespace std; #define SAMPLE_BUFFER_SIZE 16 #define KEYSTATECOUNT 256 #pragma comment (lib, "dinput8.lib") #pragma comment (lib, "dxguid.lib") #pragma comment (lib, "d3d11.lib") #pragma comment (lib,"d2d1.lib") #pragma comment (lib,"dwrite.lib") #if defined(DEBUG) || defined(_DEBUG) #pragma comment (lib,"d3dx10d.lib") #pragma comment (lib,"d3dx11d.lib") #pragma comment (lib,"dxgi.lib") #else #pragma comment (lib,"d3dx11.lib") #pragma comment (lib,"d3dx11.lib") #endif #pragma comment (lib,"d3dcompiler.lib") #pragma comment (lib,"winmm.lib") #pragma comment (lib,"comctl32.lib") typedef basic_string<TCHAR> T_STR; typedef basic_string<TCHAR>::iterator T_ITOR; typedef vector<basic_string<TCHAR>> T_STR_VECTOR; typedef vector<string> C_STR_VECTOR; typedef list<basic_string<TCHAR>> T_STR_LIST; typedef string CHAR_STRING; typedef vector<DWORD> DWORD_VECTOR; typedef vector< DWORD >::iterator DWORD_VECTOR_ITOR; typedef list<DWORD> DWORD_LIST; typedef list<DWORD>::iterator DWORD_LIST_ITOR; typedef list< HANDLE > HANDLE_LIST; typedef list< HANDLE >::iterator HANDLE_LIST_ITOR; ///////////////////////////////////////////// // 템플릿 객체 릴리즈 함수 ///////////////////////////////////////////// template<class Interface> inline void SAFE_RELEASE(Interface **ppInterfaceToRelease) { if (*ppInterfaceToRelease != NULL) { (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = NULL; } } //////////////////////////////////////// // Assert //////////////////////////////////////// #ifndef Assert #if defined(_DEBUG) || defined (_DEBUG) #define Assert(b)do {if(!(b)){OutputDebugStringW(L"Assert:"#b L"\n");}} while(0) #else #define Assert(b) #endif //_DEBUG||_DEBUG #endif ////////////////////////////////////// // DX 메소드 호출에 대한 반환값 처리 매크로 ////////////////////////////////////// #ifndef V #define V(x) {hr=(x);} #endif #ifndef V_RETURN #define V_RETURN(x){hr=(x); if(FAILED(hr)){return hr;}} #endif ////////////////////////////////////// // 객체 및 배열 할당과 삭제 및 소멸 매크로 ////////////////////////////////////// #ifndef SAFE_ZERO #define SAFE_ZERO(A){A=0;} #endif #ifndef SAFE_NEW #define SAFE_NEW(A,B) {if(!A)A =new B;} #endif #ifndef SAFE_DEL #define SAFE_DEL(A){if(A)delete A; (A)=NULL;} #endif #ifndef SAFE_NEW_ARRAY #define SAFE_NEW_ARRAY(A,B,C) {if(!A&&C)A=newB[C];} #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(A) {if(A)delete[]A; (A)=NULL;} #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(A){if(A){(A)->Release(); (A)=NULL;}} #endif #ifndef SAFE_NEW_CLEAR #define SAFE_NEW_CLEAR(A,B) {if(!A)A=new B; if(A)memset (A,0,sizeof(B));}; #endif #ifndef SAFE_NEW_ARRAY_CLEAR #define NEW_ARRAY_CLEAR(A,B,C){if(!A && C)A=newB[C]; if(A)memset (A,0,sizeof(B)*C);}; #endif<file_sep>#pragma once #include <Windows.h> #define PACKET_HEADER_SIZE 4 #pragma pack(push,1) typedef struct { WORD len; // 패킷의 전체 길이 WORD type; // 패킷의 타입(종류) // WORD Index; // 패킷의 고유한 인덱스 // WORD time; // 패킷의 전달 시간 }PACKET_HEADER; typedef struct { PACKET_HEADER ph; char msg[2048]; }UPACKET, *P_UPAKCET; // 캐릭터 생성 패킷 typedef struct { byte szName[13]; int iIndex; int iData[50]; }CHARACTER_INFO; // 아이템 생성 패킷 typedef struct { byte szName[13]; int iIndex; int iData[10]; }ITEM_INFO; #pragma pack(pop)// 복원 // [0] ~ [12][13][14] [14][15][16] ////////////// 패킷의 타입들 ///////// #define PACKET_CHAT_MSG 1000 #define PACKET_GAME_START 2000 #define PACKET_GAME_END 3000 #define PACKET_CREATE_CHARACTER 4000 #define PACKET_MOVE_CHARACTER 5000 /* MSG = "안녕하세여!" UPACKET sendPacket; sendPacket.ph.len = strlen(MSG) + PACKET_HEADER_SIZE; sendPacket.ph.type = PACKET_CHAT_MSG; sendPacket.msg = MSG; UPACKET sendPacket; sendPacket.ph.len = strlen(CHARACTER_INFO) + PACKET_HEADER_SIZE; sendPacket.ph.type = PACKET_CREATE_CHARACTER; sendPacket.msg = CHARACTER_INFO; // 4 바이트 패킹 struct TData { int iA; // 4 int iD; // 4 short sB; // 2 덤 2byte short sC; // 2 덤 2byte short sC; // 2 덤 2byte byte bC; // 3 byte byte bC; // 3 byte }; // 200 UPACKET a[10]; for( send(a[i] ) // a[0]a[1]a[2]a[3] == > 스트림(연속적인 물의 흐름 ) char buffer[256]; UPACKET a[10]; while(1) { iRecvByte=recv(buffer, 256) a[0]생성, a[1]= 56 + 144byte;일부분만 받음 200-56 = 144 ~ 256 256-144= 12 a[2] = 144~ 244; a[3] = 244~256=12 } recvbuffer = recv(); if( strlen(recvbuffer) > PACKET_HEADER_SIZE) { // if( strlen(recvbuffer) > packet.len ) { } } */<file_sep>#include "CCSample.h" //// 클래스 멤버 변수 초기화 bool CCSample::Init() { TCHAR str[] = _T("NAME"); TCHAR str2[] = _T("NAME"); _tcscpy(str, str2); return true; } //// 매 프레임에서 계산을 담당한다. bool CCSample::Frame() { if (m_Input.KeyCheck(VK_LEFT) == KEY_PUSH) { MessageBox(g_hWnd, L"VK_LEFT", L"KEY", MB_OK); } if (m_Input.KeyCheck(VK_RIGHT) == KEY_PUSH) { MessageBox(g_hWnd, L"VKRIGHT", L"KEY", MB_OK); } if (m_Input.KeyCheck(VK_UP) == KEY_PUSH) { MessageBox(g_hWnd, L"VK_UP", L"KEY", MB_OK); } if (m_Input.KeyCheck(VK_DOWN) == KEY_PUSH) { MessageBox(g_hWnd, L"VK_DOWN", L"KEY", MB_OK); } if (m_Input.KeyCheck('0') == KEY_PUSH) { MessageBox(g_hWnd, L"0", L"KEY", MB_OK); } if (m_Input.KeyCheck('A') == KEY_PUSH) { MessageBox(g_hWnd, L"A", L"KEY", MB_OK); } if (m_Input.KeyCheck(VK_F1) == KEY_PUSH) { MessageBox(g_hWnd, L"VK_F1", L"Key", MB_OK); } return true; } // 매 프레임에서 드로우를 담당한다. bool CCSample::Render() { RECT rect; if (m_hOffScreenDC != NULL) { SetBkColor(m_hOffScreenDC, RGB(255, 0, 0)); SetTextColor(m_hOffScreenDC, RGB(0, 0, 255)); SetBkMode(m_hOffScreenDC, TRANSPARENT); for (int iCnt = 0; iCnt < m_Input.m_strList.size(); iCnt++) { //SetTextAlign(hdc,TA_LEFT); TextOut(m_hOffScreenDC, 0, 100 + iCnt * 20, m_Input.m_strList[iCnt].c_str(), m_Input.m_strList[iCnt].size()); } } return true; } //// 클래스 멤버 변수 소멸을 담당한다. // bool CCSample :: Release() //{ // return true; //}; CCSample::CCSample() { } CCSample::~CCSample() { } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR IpCmdLine, int nCmdShow) { CCSample sample; // 윈도우를 생성한다. if (sample.SetWindow(hInstance,0, 800, 600)) { // 생성된 윈도우를 가동한다. sample.Run(); } } <file_sep>#include "xCore.h" class Sample : public xCore { public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600) //#include "xCore.h" //#include "xShape.h" // //class Sample : public xCore //{ // xBoxShape m_ObjBox; // xPlaneShape m_ObjPlane; // xLineShape m_ObjLine; // xSphereShape m_ObjSphere; //public: // void DeleteResources() // { // } // HRESULT CreateResources(UINT width, UINT height) // { // return S_OK; // } // bool Init() // { // m_pMainCamera->SetViewMatrix( // D3DXVECTOR3(0.0f, 0.0f, -5.0f), // D3DXVECTOR3(0.0f, 0.0f, 0.0f)); // // m_ObjLine.Create(m_pd3dDevice, // L"../../Include/data/shader/shape.hlsl", // L"../../Include/data/eye.bmp"); // // m_ObjBox.Create(m_pd3dDevice, // L"../../Include/data/shader/shape.hlsl", // L"../../Include/data/eye.bmp"); // // m_ObjPlane.Create(m_pd3dDevice, // L"../../Include/data/shader/shape.hlsl", // L"../../Include/data/eye.bmp"); // // // m_ObjSphere.Create(m_pd3dDevice, // L"../../Include/data/shader/shape.hlsl", // L"../../Include/data/eye.bmp"); // return true; // } // bool Frame() // { // m_ObjLine.Frame(); // m_ObjPlane.Frame(); // m_ObjSphere.Frame(); // return m_ObjBox.Frame(); // } // bool Render() // { // D3DXMATRIX matWorld, matRot; // D3DXMatrixTranslation(&matWorld,3.0f, 0, 0); // D3DXMatrixRotationY(&matRot,m_Timer.m_fGameTimer); // matWorld = matWorld * matRot; // //ApplyRS(m_pContext, xDxState::g_pRSNoneCullSolid); // // 면 출력 // m_ObjPlane.SetMatrix(&matWorld, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); // m_ObjPlane.Render(m_pContext); // //ApplyRS(m_pContext, xDxState::g_pRSBackCullSolid); // // // 면 출력 // //ApplyRS(m_pContext, xDxState::g_pRSWireFrame); // D3DXMatrixTranslation(&matWorld, -3.0f, 0, 0); // m_ObjSphere.SetMatrix(&matWorld, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); // m_ObjSphere.Render(m_pContext); // // // 박스 출력 // m_ObjBox.SetMatrix(NULL,&m_pMainCamera->m_matView,&m_pMainCamera->m_matProj); // m_ObjBox.Render(m_pContext); // // // 박스와 면의 연결선 출력 // m_ObjLine.Draw(m_pContext,m_ObjBox.m_vPosition,m_ObjPlane.m_vPosition,D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f)); // // // 면 방향벡터 출력 // m_ObjLine.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); // D3DXVECTOR3 vDir = m_ObjPlane.m_vLook * 10.0f; // m_ObjLine.Draw(m_pContext, m_ObjPlane.m_vPosition,m_ObjPlane.m_vPosition+ vDir, D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f) ); // vDir = m_ObjPlane.m_vUp * 10.0f; // m_ObjLine.Draw(m_pContext,m_ObjPlane.m_vPosition,m_ObjPlane.m_vPosition + vDir, D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f)); // vDir = m_ObjPlane.m_vSide * 10.0f; // m_ObjLine.Draw(m_pContext,m_ObjPlane.m_vPosition,m_ObjPlane.m_vPosition + vDir, D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f)); // return true; // } // bool Release() // { // m_ObjLine.Release(); // m_ObjSphere.Release(); // m_ObjPlane.Release(); // return m_ObjBox.Release(); // } //public: // Sample() { // } // ~Sample() {} //}; //GAME_RUN("Sample", 800, 600) <file_sep>#include "TPermanent.h" TPermanent::TPermanent(char* _name,int sal):TEmployee(_name) { salary = sal; } int TPermanent::GetPay() { return salary; } TPermanent::~TPermanent() { } <file_sep>#include "TChild.h" int main(void) { TChild aBoy; aBoy.Character(); //Parent에서 상속 받은 함수 호출 aBoy.Appearance(); //Parent에서 상속 받은 함수 호출 aBoy.Wealth(); //Parent에서 상속 받은 함수 호출 aBoy.Humanity(); //child 에서 추가된 함수 호출 return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> //void main() //{ // size_t length; // char buf[80]; // while (1) // { // puts("Enter a line of text"); // puts("blank line terminates."); // gets(buf); // length = strlen(buf); // if (length != 0) // { // printf("%u caracters\n\n", length); // } // else // { // break; // } // } //} void main() { char word[] = "Happy Birth day"; char *great = "hello"; int count = 0; while (word[count] != NULL) { count++; printf("Length =%d\n", count); } count = 0; while (great[count] != NULL) { count++; printf("Length=%d\n", count); } }<file_sep>//iterate는 '반복하다'라는 뜻이고, iterator은 '반복자'라는 뜻이다. #include "xltem.h" #include "xlist.h" #include "xiter.h"<file_sep>#include "DIDevice.h" HRESULT DIDevice::InitDevice(HWND hWnd, UINT iWidth, UINT iHeight, BOOL IsFullScreen) { HRESULT hr = S_OK; if (FAILED(hr = CreateDevice())) { MessageBox(0, _T("CreateDevice 실패"), _T("Fatal error"), MB_OK); return hr; } if (FAILED(hr = CreateSwapChain(hWnd, iWidth, iHeight, IsFullScreen))) { MessageBox(0, _T("CreateSwapChain 실패"), _T("Fatal error"), MB_OK); return hr; } if (FAILED(hr = SetRenderTargetView())) { MessageBox(0, _T("SetRenderTargetView 실패 "), _T("Fatal error"), MB_OK); return hr; } if (FAILED(hr = SetViewPort())) { MessageBox(0, _T("SetViewPort 실패 "), _T("Fatal error"), MB_OK); return hr; } // ALT+ENTER 키를 막는다. if (FAILED(hr = m_pGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER))) { return hr; } return hr; } BOOL DIDevice::GetFullScreenFlag() { return m_IsFullScreenMode; } void DIDevice::SetFullScreenFlag(BOOL bFlag) { m_IsFullScreenMode = bFlag; } ID3D11Device* DIDevice::GetDevice() { assert(m_pd3dDevice); return m_pd3dDevice; } ID3D11DeviceContext* DIDevice::GetContext() { assert(m_plmmediateContext); return m_plmmediateContext; } IDXGISwapChain* DIDevice::GetSwapChain() { assert(m_pSwapChain); return m_pSwapChain; } ID3D11RenderTargetView* DIDevice::GetRenderTargeView() { assert(m_pRenderTargetView); return m_pRenderTargetView; } IDXGIFactory* DIDevice::GetGIFactory() { assert(m_pGIFactory); return m_pGIFactory; } //NEW HRESULT DIDevice::ResizeDevice(UINT iWidth, UINT iHeight) { if (m_pd3dDevice == NULL) return true; HRESULT hr; ///////////////////////////////////////////////////////// // 랜더 타켓과 깊이스텐실 버퍼를 해제한다. m_plmmediateContext->OMSetRenderTargets(0, NULL, NULL); if (m_pRenderTargetView)m_pRenderTargetView->Release(); /////////////////////////////////////////////////////////// // 백버퍼의 크기를 조정한다. /////////////////////////////////////////////////////////// DXGI_SWAP_CHAIN_DESC CurrentSD; m_pSwapChain->GetDesc(&CurrentSD); m_pSwapChain->ResizeBuffers(CurrentSD.BufferCount, iWidth, iHeight, CurrentSD.BufferDesc.Format, CurrentSD.Flags); /*DXGI_MODE_DESC desc; ZeroMemory(&desc, sizeof (desc)); desc.Width = iWidth; desc.Height = iHeight; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.RefreshRate.Denominator = 0; desc.RefreshRate.Numerator = 0; desc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; desc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;*/ // 윈도우 크기 및 해상도( 화면모드 ) 변경 //m_pSwapChain->ResizeTarget(&desc); //랜더타켓뷰 생성 및 적용한다. if (FAILED(hr = SetRenderTargetView())) { return hr; } // 뷰포트를 세팅하고 적용한다. if (FAILED(hr = SetViewPort())) { return hr; } return S_OK; } ///////////////////////////////////////////////////////////////////////// // DXGIFactory 인터페이스로부터 IDXGISwapChain 인터페이스를 생성한다. ///////////////////////////////////////////////////////////////////////// HRESULT DIDevice::CreateSwapChain(HWND hWnd, UINT iWidth, UINT iHeight, BOOL IsFullScreen) { HRESULT hr = S_OK; SetFullScreenFlag(IsFullScreen); if (m_pGIFactory == NULL) return S_FALSE; DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = iWidth; sd.BufferDesc.Height = iHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = !m_IsFullScreenMode; // 추가 sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; if (FAILED(hr = m_pGIFactory->CreateSwapChain(m_pd3dDevice, &sd, &m_pSwapChain))) { return hr; } return hr; } ///////////////////////////////////////////////////////// // ID3D11Device 인터페이스를 생성한다. ///////////////////////////////////////////////////////// HRESULT DIDevice::CreateDevice() { HRESULT hr; UINT createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); D3D_FEATURE_LEVEL featureLevel[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevel); for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { m_driverType = driverTypes[driverTypeIndex]; if (SUCCEEDED(hr = D3D11CreateDevice(NULL, m_driverType, NULL, createDeviceFlags, featureLevel, numFeatureLevels, D3D11_SDK_VERSION, &m_pd3dDevice, &m_FeatureLevel, &m_plmmediateContext))) { if (FAILED(hr) || m_FeatureLevel < D3D_FEATURE_LEVEL_11_0) { if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); continue; } break; } } if (FAILED(hr))return hr; return CreateGIFactory(); } HRESULT DIDevice::CreateGIFactory() { if (m_pd3dDevice == NULL)return E_FAIL; HRESULT hr; //CreateDXGIFactory (__uuidof(IDXGIFactory),(void**)(&m_pGIFactory)); IDXGIDevice* pDXGIDevice; hr = m_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&pDXGIDevice); IDXGIAdapter* pDXGIAdapter; hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&pDXGIAdapter); IDXGIFactory* pIDXGIFactory; pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&m_pGIFactory); pDXGIDevice->Release(); pDXGIAdapter->Release(); return hr; } //--------------------------------------------------------------------- // DXGIFactory 인터페이스로부터 IDXGISwapChain 인터페이스를 생성한다. //--------------------------------------------------------------------- HRESULT DIDevice::SetRenderTargetView() { HRESULT hr = S_OK; // Create a render target view ID3D11Texture2D* pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if (FAILED(hr)) return hr; hr = m_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); if (FAILED(hr)) return hr; m_plmmediateContext->OMSetRenderTargets(1, &m_pRenderTargetView, NULL); return S_OK; } HRESULT DIDevice::SetViewPort() { HRESULT hr = S_OK; DXGI_SWAP_CHAIN_DESC Desc; m_pSwapChain->GetDesc(&Desc); // Setup the viewport m_ViewPort.Width = Desc.BufferDesc.Width; m_ViewPort.Height = Desc.BufferDesc.Height; m_ViewPort.MinDepth = 0.0f; m_ViewPort.MaxDepth = 1.0f; m_ViewPort.TopLeftX = 0; m_ViewPort.TopLeftY = 0; m_plmmediateContext->RSSetViewports(1, &m_ViewPort); return S_OK; } bool DIDevice::CleanupDevice() { // 초기 풀스크린 윈도우에서 응용프로그램이 닫히는 경우에는 윈도우 전환 후에 // 객체들을 소멸해야한다. (메모리 누수를 막을 수 있다.) m_pSwapChain->SetFullscreenState(false, NULL); if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pRenderTargetView)m_pRenderTargetView->Release(); if (m_pSwapChain)m_pSwapChain->Release(); if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); if (m_pGIFactory)m_pGIFactory->Release(); m_pd3dDevice = NULL; m_pSwapChain = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; m_pGIFactory = NULL; return true; } DIDevice::DIDevice(void) { m_driverType = D3D_DRIVER_TYPE_NULL; m_FeatureLevel = D3D_FEATURE_LEVEL_11_0; m_pd3dDevice = NULL; m_pSwapChain = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; m_pGIFactory = NULL; } DIDevice::~DIDevice(void) { } <file_sep>#include <iostream> static const int g_iMaxDepth = 2; int g_iIndex = 0; struct TNode { int iData; int iIndex; int iDepth; TNode* pChild[2]; }; typedef TNode* p_TNode; TNode* g_pRootNode = 0; TNode* g_pRootNodePtr = 0; TNode** g_pArrayNode; TNode** g_pArrayNodePtr; TNode* NewNode() { TNode* pNode = new TNode; pNode->iData = rand() % 100; pNode->iIndex = g_iIndex++; pNode->iDepth = 0; pNode->pChild[0] = NULL; pNode->pChild[1] = NULL; return pNode; } TNode* AddNode(TNode* pNode) { if (pNode == NULL)return NULL; if (pNode->iDepth >= g_iMaxDepth)return NULL; pNode->pChild[0] = g_pArrayNode[pNode->iIndex * 2 + 1]; pNode->pChild[1] = g_pArrayNode[pNode->iIndex * 2 + 1]; pNode->pChild[0]->iDepth = pNode->iDepth + 1; pNode->pChild[1]->iDepth = pNode->iDepth + 1; // 왼쪽 자식노드 인덱스 = pParentNode->iIndex * 2 + 1 // 오른쪽 자식노드 인덱스 = pParentNode->iIndex * 2 + 2 AddNode(pNode->pChild[0]); AddNode(pNode->pChild[1]); } TNode* AddNodePtr(TNode* pNode) { if (pNode == NULL)return NULL; if (pNode->iDepth >= g_iMaxDepth)return NULL; pNode->pChild[0] = NewNode(); pNode->pChild[1] = NewNode(); pNode->pChild[0]-> iDepth = pNode->iDepth + 1; pNode->pChild[1]-> iDepth = pNode->iDepth + 1; int iIndex = pNode->iIndex * 2 + 1; g_pArrayNodePtr[iIndex] = pNode->pChild[0]; g_pArrayNodePtr[iIndex + 1] = pNode->pChild[1]; AddNodePtr(pNode->pChild[0]); AddNodePtr(pNode->pChild[1]); } TNode* PrintAddNodePtr(TNode* pNode) { if (pNode == NULL)return NULL; std::cout << pNode->iIndex << "[" << pNode->iData << "]" << std::endl; PrintAddNodePtr(pNode->pChild[0]); PrintAddNodePtr(pNode->pChild[1]); } void DeleteNode(int iNumCount) { for (int iNode = 0; iNode < iNumCount; iNode++) { if (g_pArrayNode[iNode] != NULL); { delete g_pArrayNode[iNode]; g_pArrayNode[iNode] = 0; } } } void DeleteNodePtr(TNode* pNode) { if (pNode == NULL)return; DeleteNodePtr(pNode->pChild[0]); DeleteNodePtr(pNode->pChild[1]); delete pNode; pNode = 0; } void main() { int iNumCount = pow(2.0f, g_iMaxDepth + 1) - 1; g_pArrayNode = new p_TNode[iNumCount]; g_pArrayNodePtr = new p_TNode[iNumCount]; for (int i = 0; i < iNumCount; i++) { g_pArrayNode[i] = NewNode(); } g_pRootNode = g_pArrayNode[0]; AddNode(g_pRootNode); TNode* pParent = g_pArrayNode[(3 - 1) / 2]; PrintAddNodePtr(g_pRootNode); DeleteNode(iNumCount); g_iIndex = 0; g_pRootNodePtr = NewNode(); g_pArrayNodePtr[0] = g_pRootNodePtr; AddNodePtr(g_pRootNodePtr); DeleteNodePtr(g_pRootNodePtr); delete[] g_pArrayNode; delete[] g_pArrayNodePtr; g_pArrayNode = 0; g_pArrayNodePtr = 0; system("pause"); }<file_sep>#pragma once #include <stdlib.h> #include <iostream> #include <time.h> #define MAX_NUM 100 int g_iStackBuffer[MAX_NUM]; int g_iTopStack = 0; int g_iQueueBuffer[MAX_NUM]; int g_iRearQueue = 0; int g_iFrontQueue = 0; bool g_bFlagQueue = false; void Swap(int *a, int *b) { if (*a > *b) { int t = *a; *a = *b; *b = t; } } ///////////////////////////// //statk ///////////////////////////// void InitStack() { g_iTopStack = 0; } void StackPush(int i) { if (g_iTopStack >= MAX_NUM) { std::cout << "g_iStackBuffer Full" << std::endl; return; } else { g_iStackBuffer[g_iTopStack++] = i; } } int StackPop() { if (g_iTopStack == 0) { return 0; } else return g_iStackBuffer[--g_iTopStack]; } int IsStatkEmpty() { if (g_iTopStack == 0) { return 1; } else return 0; } ////////////////////////////////// //Queue ////////////////////////////////// void InitQueue() { g_iRearQueue = 0; g_iFrontQueue = 0; } //0번째 방은 제일 마지막에 넣는다. void QueuePush(int i) { if (g_bFlagQueue == true) { std::cout << "g_iQueueBuffer Full" << std::endl; return; } g_iRearQueue = (g_iRearQueue + 1) % MAX_NUM; if (g_iFrontQueue == g_iRearQueue) { //이코드가 없으면 계속 다음칸에 복사하여 넣는다. g_bFlagQueue = true; } g_iQueueBuffer[g_iRearQueue] = i; } int QueuePop() { if (g_iFrontQueue == g_iRearQueue && g_bFlagQueue == false) { std::cout << "g_iQueueBuffer Empty" << std::endl; return 0; } g_bFlagQueue = false; g_iFrontQueue = (g_iFrontQueue + 1) % MAX_NUM; return g_iQueueBuffer[g_iFrontQueue]; } int IsQueueEmpty() { if (g_iFrontQueue == g_iRearQueue) { return 1; } else { return 0; } } <file_sep>#pragma once #include "SThread.h" #include <ws2tcpip.h> class sUdpSocket : public SThread { public: SOCKET m_Socket; SOCKET m_SendSocket; SOCKADDR_IN m_RecvAddr; SOCKADDR_IN m_SendAddr; public: bool Init(); bool Run(); bool Release(); public: sUdpSocket(void); virtual ~sUdpSocket(void); }; <file_sep>#include "xCore.h" #include "xMap.h" struct LIGHT_CONSTANT_BUFFER { D3DXMATRIX g_matInvWorld; D3DXVECTOR4 g_vLightDir; D3DXVECTOR4 g_vLightPos; D3DXVECTOR4 g_vEyeDir; D3DXVECTOR4 g_vEyePos; }; class Sample : public xCore { xMap m_map; xLineShape m_ObjLine; ComPtr<ID3D11Buffer> m_pCBLight; LIGHT_CONSTANT_BUFFER m_cbLightData; D3DXVECTOR3 m_vLightPos; public: bool Init() { HRESULT hr = S_OK; DX::CreateConstantBuffer(m_pd3dDevice, 1, sizeof(LIGHT_CONSTANT_BUFFER), m_pCBLight.GetAddressOf(), &m_cbLightData, false); m_pMainCamera->SetViewMatrix( D3DXVECTOR3(0.0f, 300.0f, -300.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f)); m_ObjLine.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/eye.bmp"); xMapDesc desc = { 5, 5, 1.0f, 1.0f, L"../../Include/data/map/Tile40.jpg", L"../../Include/data/shader/mapLight.hlsl", }; m_map.Init(); m_map.CreateHeightMap(m_pd3dDevice, m_pContext, L"../../Include/data/map/heightMap513.bmp"); desc.iNumRows = m_map.m_iNumRows; desc.iNumCols = m_map.m_iNumCols; desc.fScaleHeight = 1.0f; if (m_map.Load(m_pd3dDevice, desc) == false) { return false; } } bool Frame() { D3DXVECTOR3 vLightDir; D3DXMATRIX matRotY; D3DXMatrixRotationY(&matRotY, m_Timer.m_fGameTimer*0.5f); D3DXVec3TransformCoord(&vLightDir,&m_vLightPos,&matRotY); D3DXVec3Normalize(&vLightDir, &-vLightDir); //m_vLightPos = D3DXVECTOR3(100, 100, 100); m_cbLightData.g_vLightDir.x = vLightDir.x; m_cbLightData.g_vLightDir.y = vLightDir.y; m_cbLightData.g_vLightDir.z = vLightDir.z; m_cbLightData.g_vLightDir.w = 10.0f; // intensity(세기,강도); m_cbLightData.g_vLightPos.x = m_vLightPos.x; m_cbLightData.g_vLightPos.y = m_vLightPos.y; m_cbLightData.g_vLightPos.z = m_vLightPos.z; m_cbLightData.g_vLightPos.w = 200.0f; // intensity(세기,강도); m_cbLightData.g_vEyeDir.x = m_pMainCamera->m_vLook.x; m_cbLightData.g_vEyeDir.y = m_pMainCamera->m_vLook.y; m_cbLightData.g_vEyeDir.z = m_pMainCamera->m_vLook.z; m_cbLightData.g_vEyeDir.w = 10.0f; // intensity(세기,강도); m_cbLightData.g_vEyePos.x = m_pMainCamera->m_vPos.x; m_cbLightData.g_vEyePos.y = m_pMainCamera->m_vPos.y; m_cbLightData.g_vEyePos.z = m_pMainCamera->m_vPos.z; m_cbLightData.g_vEyePos.w = 200.0f; // intensity(세기,강도); return true; } bool Render() { m_map.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); D3DXMatrixInverse(&m_cbLightData.g_matInvWorld,NULL,&m_map.m_matWorld); D3DXMatrixTranspose(&m_cbLightData.g_matInvWorld,&m_cbLightData.g_matInvWorld); D3DXMatrixTranspose(&m_cbLightData.g_matInvWorld, &m_cbLightData.g_matInvWorld); m_pContext->UpdateSubresource(m_pCBLight.Get(), 0, NULL, &m_cbLightData, 0, 0); m_pContext->VSSetConstantBuffers(1, 1, m_pCBLight.GetAddressOf()); m_pContext->GSSetConstantBuffers(1, 1, m_pCBLight.GetAddressOf()); m_map.Render(m_pContext); for (int iVertex = 0; iVertex < m_map.m_VertexList.size(); iVertex += 10000) { D3DXVECTOR3 vNormal = m_map.m_VertexList[iVertex].n; m_ObjLine.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_ObjLine.Draw(m_pContext, m_map.m_VertexList[iVertex].p, m_map.m_VertexList[iVertex].p + vNormal * 10.0f); } return true; } bool Release() { return m_map.Release(); } public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600) <file_sep>#include <Windows.h> #include <tchar.h> #pragma comment(lib, "winmm.lib") DWORD m_dwKeyState[255]; int g_iFPS = 0; int g_iTmpCount = 0; float g_fSecPerFrame = 0.0f; float g_fGameTime = 0.0f; TCHAR g_szBuffer[256]; LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) // 운영체제 { switch (msg) { case WM_DESTROY: { PostQuitMessage(0); }break; } return DefWindowProc(hWnd, msg, wParam, lParam); } int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPWSTR IpCmdLine, int nCmdShow) { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.hInstance = hInst; wc.lpfnWndProc = WndProc; wc.lpszClassName = L"MYWINDOW"; if (RegisterClassEx(&wc) == false) { return false; } HWND hWnd = CreateWindowEx(WS_EX_APPWINDOW, L"MYWINDOW", L"WINDOW TEST", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, //위치 위치 , 해상도 해상도 NULL, NULL, hInst, NULL); if (hWnd == NULL) return false; ShowWindow(hWnd, SW_SHOW); HBITMAP hBitmap = (HBITMAP)LoadImage(hInst, L"end04.bmp.bmp", IMAGE_BITMAP, 0,0,LR_DEFAULTSIZE | LR_LOADFROMFILE); HDC hdc = GetDC(hWnd); HDC hMemDC = CreateCompatibleDC(hdc); //세팅 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap); DWORD dwTick = timeGetTime(); MSG msg; while (1) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))//블럭형 함수 { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { //Sleep(1); WORD dwCurrentTick = timeGetTime(); DWORD dwElapseTick = dwCurrentTick - dwTick; g_fSecPerFrame = dwElapseTick / 1000.0f; g_fGameTime += g_fSecPerFrame; static float fTime = 0.0f; fTime += g_fSecPerFrame; if (fTime >= 1.0f) { g_iFPS = g_iTmpCount; fTime -= 1.0f; g_iTmpCount = 0; } dwTick = dwCurrentTick; /*static DWORD dw100Frame = 0; dw100Frame += dwElapseTick; if (dw100Frame < 10) { continue; } dw100Frame = 0;*/ for (int iKey = 0; iKey < 255; iKey++) { SHORT sKey = GetAsyncKeyState(iKey); m_dwKeyState[iKey] = (sKey & 0x8000) ? 1 : 0; } if (m_dwKeyState[VK_LBUTTON]) { MessageBox(NULL, L"VK_LBUTTON", L"MOUSE", MB_OK); } if (m_dwKeyState['W']) { MessageBox(NULL, L"W", L"MOUSE", MB_OK); } if (m_dwKeyState[VK_LCONTROL] && m_dwKeyState[VK_RBUTTON]) { MessageBox(NULL, L"CONBO", L"KEY+MOUSE", MB_OK); } _stprintf_s(g_szBuffer, L"%d : %10.4f : %10.4f :",g_iFPS, g_fGameTime, g_fSecPerFrame); BitBlt( //출력 DC hdc, 0, 0, 800, 600, //소스 (원본,dc) hMemDC, 0, 0, SRCCOPY); TextOut(hdc, 0, 0, g_szBuffer, wcslen(g_szBuffer)); g_iTmpCount++; } } //복원 SelectObject(hMemDC, hBitmap); DeleteObject(hBitmap); ReleaseDC(hWnd, hMemDC); ReleaseDC(hWnd, hdc); return true; } <file_sep>#include "TTriangle.h" void TTriangle::Draw() { cout << "Draw TTriangle: "; cout << "(" << x << "," << y << "),"; cout << width << "x" << height; cout << endl; } TTriangle::TTriangle() { cout << "TTriangle 생성자" << endl; } TTriangle::~TTriangle() { cout << "TTriangle 해제자" << endl; } <file_sep>#pragma once #include "S_Object.h" #define MAX_WEIGHT_BIPED 8 struct SBipedVertex { int m_dwNumWeight; vector<BYTE> m_BipIDList; vector<float> m_fWeightList; }; struct P3NCT3VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; float w[4]; float i[4]; }; struct PNCT5_VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; float w1[4]; float i1[4]; float w2[4]; float i2[4]; }; struct SSkinTri :public STri { PNCT5_VERTEX m_vVertex[3]; }; struct SSkinMesh : public SMesh { vector<SSkinTri> m_SkinTriList; vector<SSkinMesh*> m_pSkinSubMesh; int m_iNumTex; int m_iTexType[13]; TCHAR m_szTexName[13][30]; SSkinMesh() {}; virtual ~SSkinMesh() {}; }; class S_Skin : public SSingleton<S_Skin> { private: friend class SSingleton<S_Skin>; public: SScene m_Scene; typedef vector<SBipedVertex> SBIPED_VERTEX_VECTOR; SBIPED_VERTEX_VECTOR m_BipedList; typedef vector<SSkinMesh*> SSKINMESH_VECTOR; SSKINMESH_VECTOR m_SkinmeshList; public: bool Init(); bool skmExport(); bool Release(); Modifier* FindModifier(INode *nodePtr, Class_ID classID); void SetBipedInfo(INode* node); void ExportPhysiqueData(INode* node, Modifier *phyMod); void ExportSkinData(INode* node, Modifier *skinMod); bool ExportMesh(FILE* fp, SSkinMesh* pMesh); void SetVertexBiped(INode* node, Face* face, int v0, int v1, int v2, SSkinTri* pTri); bool GetNodeInfo(INode* node, TimeValue t); void GenerateGroup(INode* node, Mesh *mesh, SSkinMesh* pSkinMesh); void LoadMaterial(SSkinMesh* pSkinMesh, Mtl* mtl); void SetTriangle(INode* node, Mesh *mesh, SSkinMesh* pSkinMesh, SSkinMesh* pSumMesh = NULL, int iMtrl = 0); int GetMapID(Class_ID cid, int subNo); int IsEqulVertexList(vector<PNCT5_VERTEX>& VertexArray, PNCT5_VERTEX& Vertex); public: public: S_Skin(); virtual ~S_Skin(); }; #define I_SkinExp S_Skin::GetInstance() <file_sep>#pragma once #include "KHJ_Global.h" class KHJ_Object : public KHJ_Global { public: void GetMaterial(); // 매터리얼 리스트에서 정보 얻기 void GetTexture(SMtl* pDestMtl, Mtl* pSrcMtl); // 매터리얼 리스트에서 정보얻기 public: void UpdateObject(); void GetObject(MATRIXINDEX* pPoint); // 오브젝트 리스트에서 정보얻기 // 오브젝트 정보 void GetNodeHeader(INode* node, SMesh* pMesh); void GetNodeTM(INode* node, SMesh* pMesh); // 메쉬 정보 void GetMesh(INode* node, SMesh* pMesh); Point3 GetVertexNormal(Mesh* mesh, int faceNo, RVertex* rv); TriObject* GetTriObjectFromNode(INode* node, TimeValue t, int & deletelt); // 애니메이션 virtual void GetAnimKeys(INode*, SMesh*) {}; public: KHJ_Object(void); virtual ~KHJ_Object(void); }; <file_sep>#include<stdio.h> #define MAX 10 int Iargest(int x[], int y); void main() { int array[MAX], count; for (count = 0; count < MAX; count++) { printf("Enter Number:"); scanf_s("%d", &array[count]); } printf("\n\nLargest value = %d", Iargest(array, MAX)); } int Iargest(int x[], int y) { int count, biggest = x[0]; for (count = 0; count < y; count++) { if (x[count] > biggest) biggest = x[count]; } return biggest; }<file_sep>#pragma once #include "xDxState.h" //namespace DX //{ // class XDX_RT // { // public: // Microsoft::WRL::ComPtr // public: // XDX_RT(); // virtual ~XDX_RT(); // }; // //}<file_sep>#include "SChatPacketPool.h" #include "SChatUser.h" #include "SDebugString.h" #include "SChatSvr.h" void SChatPacketPool::ProcessWork(S_PACKET* pUserData) { UPACKET* pPacket = &(pUserData->packet); SChatUser* pUser = (SChatUser*)pUserData->pUser; switch (pPacket->ph.type) { case PACKET_USER_POSITION: { pUser->Movement(pPacket); I_Server.Broadcastting(pPacket, pUser->m_Socket); }break; case PACKET_CHAR_NAME_ACK: { pUser->m_szName = pPacket->msg; char buffer[256] = { 0, }; sprintf_s(buffer, "[%s]%s", pUser->m_szName.c_str(), "님이 들어오셧습니다."); ZeroMemory(pPacket->msg, 2048); sprintf_s(pPacket->msg, "%s", buffer); pPacket->ph.len = sizeof(PACKET_HEADER) + strlen(buffer); pPacket->ph.type = PACKET_CHAR_MSG; I_Server.Broadcastting(pPacket, pUser->m_Socket); }break; case PACKET_CHAR_MSG: { I_Server.Broadcastting(pPacket, pUser->m_Socket); }break; } } SChatPacketPool::SChatPacketPool(void) { } SChatPacketPool::~SChatPacketPool(void) { } <file_sep>#include <stdio.h> int main() { double a, b, c; a = 55.0; b = 55.0; c = 55.0; printf("%f\t%f\t%f\t", a, b, c); c = a + b; printf("%f\n", c); c = -c; printf("%2.2f\n", c); a = a / b; printf("%2.2f\n", a); }<file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #include "resource.h" #include <istdplug.h> #include <iparamb2.h> #include <iparamm2.h> #include <maxtypes.h> #include <utilapi.h> #include <max.h> #include <stdmat.h> #include <decomp.h> #include <CS/bipexp.h> #include <CS/phyexp.h> #include <iskin.h> #include <string> #include <vector> #include <map> #include <set> #include <list> #include <algorithm> #include <bitset> #include <limits> #include <functional> using namespace std; #ifndef SAFE_ZERO #define SAFE_ZERO(A) { A = 0; } #endif #ifndef SAFE_NEW #define SAFE_NEW(A, B) { if (!A) A = new B; } #endif #ifndef SAFE_DEL #define SAFE_DEL(A) { if (A) delete A; (A)=NULL; } #endif #ifndef SAFE_NEW_ARRAY #define SAFE_NEW_ARRAY(A, B, C) { if (!A && C) A = new B[C]; } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(A) { if (A) delete [] A; (A)=NULL; } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(A) { if(A) { (A)->Release(); (A)=NULL; } } #endif #ifndef SAFE_NEW_CLEAR #define SAFE_NEW_CLEAR( A, B ) { if (!A) A = new B; if(A) memset( A, 0, sizeof(B) ); }; #endif #ifndef SAFE_NEW_ARRAY_CLEAR #define NEW_ARRAY_CLEAR( A, B, C ) { if (!A && C) A = new B[C]; if(A) memset( A, 0, sizeof(B)*C ); }; #endif #define RELEASE(A) { if(A) { (A)->Release(); } } typedef basic_string<TCHAR> T_STR; typedef basic_string<CHAR> CHAR_STRING; typedef vector<basic_string<TCHAR>> T_STR_VECTOR; typedef vector<DWORD> DWORD_VECTOR; <file_sep>#pragma once #include <Windows.h> #include <iostream> #include <math.h> #define TBASIS_EPSILON ((FLOAT) 0.001f) #define TBASIS_PI 3.141592654 #define DtoR(degree) ((degree)*(TBASIS_PI/180.0)) #define RtoD(radian) ((radian)*(180.0/TBASIS_PI)) struct float2 { union { struct { float x, y; }; float v[2]; }; }; struct float3 { union { struct { float x, y, z; }; float v[3]; }; }; struct float4 { union { struct { float x, y, z, w; }; float v[4]; }; }; class Vector2 : public float2 { public: bool operator | (Vector2 const & vO); Vector2 operator ^ (Vector2 const& vO); public: Vector2(); Vector2(const Vector2& vO); // 복사 생성자 Vector2(float fX, float fY); ~Vector2() {} }; class Vector3 : public float3 { public: Vector3(); Vector3(const Vector3& vO); Vector3(float fX, float fY, float fZ); // 연산자 재정의 Vector3 operator + (Vector3 const &vO); Vector3 operator - (Vector3 const &vO); Vector3 operator * (float const &fScala); Vector3 operator + (float const &fScala); Vector3 operator / (float const &fScala); bool operator == (Vector3 const &vO); // 내적 외적 float operator | (Vector3 const& vO); Vector3 operator ^ (Vector3 const& vO); // 제곱 float LengthSquared(); // 원점으로 부터의 거리 float Length(); Vector3 Normalize(); // 정규화 Vector3 Normal(); ~Vector3() {} }; class Vector4 : public float4 { public: Vector4(); Vector4(const Vector4& vO); Vector4(float fX, float fY, float fZ, float fW); ~Vector4() {} };<file_sep>#include "S_Acceptor.h" #include "S_DebugString.h" bool S_Acceptor::Run() { SOCKET m_ClientSocket; SOCKADDR_IN m_ClientAddr; int m_iAddrlen; while (m_bStarted) { m_iAddrlen = sizeof(m_ClientAddr); m_ClientSocket = accept(m_ListenSock, (SOCKADDR*)&m_ClientAddr, &m_iAddrlen); if (m_ClientSocket == INVALID_SOCKET) { continue; } AddUser(m_ClientSocket, m_ClientAddr); Sleep(10); } return true; } bool S_Acceptor::Release() { return true; } bool S_Acceptor::Set(int iPort, const char* strAddress) { int Ret; WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); m_ListenSock = socket(AF_INET, SOCK_STREAM, 0); if (m_ListenSock == INVALID_SOCKET) { return false; } SOCKADDR_IN SvrAddr; ZeroMemory(&SvrAddr, sizeof(SvrAddr)); SvrAddr.sin_family = AF_INET; if (strAddress == NULL) { SvrAddr.sin_addr.s_addr = htonl(INADDR_ANY); } else { SvrAddr.sin_addr.s_addr = inet_addr(strAddress); } SvrAddr.sin_port = htons(iPort); Ret = ::bind(m_ListenSock, (SOCKADDR*)&SvrAddr, sizeof(SvrAddr)); if (Ret == SOCKET_ERROR) { switch (WSAGetLastError()) { case WSAEADDRINUSE: case WSAEACCES: S_Debug.S_Error(); break; } return false; } Ret = listen(m_ListenSock, SOMAXCONN); if (Ret == SOCKET_ERROR) { return false; } char Flag = 1; if (SOCKET_ERROR == setsockopt(m_ListenSock, IPPROTO_TCP, TCP_NODELAY, &Flag, sizeof(char))) { return false; } int optvalexe = 1; Ret = setsockopt(m_ListenSock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&optvalexe, sizeof(optvalexe)); if (Ret == SOCKET_ERROR) { S_Debug.S_Error(); } linger optval2; int Size = sizeof(optval2); optval2.l_linger = 1000; optval2.l_onoff = 1; getsockopt(m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, &Size); setsockopt(m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, Size); int socketType1; int typeLen1 = sizeof(socketType1); getsockopt(m_ListenSock, SOL_SOCKET, SO_TYPE, (char*)&socketType1, &typeLen1); if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) < 0) { S_Debug.S_Error(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1) < 0) { S_Debug.S_Error(); } int SandBufferSize = 10000; int SandBufferSizelen = sizeof(SandBufferSizelen); if (setsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&SandBufferSize, SandBufferSizelen) < 0) { S_Debug.S_Error(); } int rcvBufferSizeLen = sizeof(int); int rcvBufferSize = 10000; if (setsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&rcvBufferSize, rcvBufferSizeLen) < 0) { S_Debug.S_Error(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { S_Debug.S_Error(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { S_Debug.S_Error(); } CreateThread(); return true; } void S_Acceptor::AddUser(SOCKET socket, SOCKADDR_IN address) { char buf[MAX_ARRAY] = { 0, }; InetNtopA(AF_INET, &address.sin_addr, buf, sizeof(char)*MAX_ARRAY); } S_Acceptor::S_Acceptor() { } S_Acceptor::~S_Acceptor() { } <file_sep>#include <iostream> using namespace std; #define MAX 10 int stack[MAX]; int top; void InitStack() { top = -1; } int push(int t) { if (top >= MAX - 1) { cout << "over flow" << endl; return t; } } int pop() { if (top < 0) { cout << "under flow" << endl; return -1; } return stack[top--]; } void PrintStack() { cout << "Stack Contents :Top ---> Bottom" << endl; for (int i = top; i >= 0; i--) { cout << "%-6d" << stack[i] << endl; } } void main() { InitStack(); printf("\nPush 5,4,7,8,2,1"); push(5); push(4); push(7); push(8); push(2); push(1); PrintStack(); printf("\nPop"); int i = pop(); PrintStack(); printf("\n Push 3,2,5,7,2"); push(3); push(2); push(5); push(7); push(2); PrintStack(); printf("\nNow stack is full, push 3"); push(3); PrintStack(); printf("\n Initialize stack"); InitStack(); PrintStack(); printf("\nNow stack is empty, pop"); i = pop(); printf("\n poppint value is %d", i); system("pause"); }<file_sep>#pragma once #include <iostream> using namespace std; struct TNode { int m_iKey; TNode* m_pParent; char m_cColor; TNode* m_pLeft; TNode* m_pRight; }; class RBtree { TNode * m_pRootNode; TNode * q; public: RBtree() { q = NULL; m_pRootNode = NULL; } void insert(int iValue); void insertfix(TNode *); void leftrotate(TNode *); void rightrotate(TNode *); void del(); TNode* successor(TNode *); void delfix(TNode *); void disp(); void display(TNode *); void search(); }; void RBtree::insert(int iValue) { TNode* p, *q; TNode* pNewNode = new TNode; pNewNode->m_iKey = iValue; pNewNode->m_pLeft = NULL; pNewNode->m_pRight = NULL; pNewNode->m_cColor = 'r'; p = m_pRootNode; q = NULL; if (m_pRootNode == NULL) { m_pRootNode = pNewNode; pNewNode->m_pParent = NULL; } else { while (p != NULL) { q = p; if (p->m_iKey < pNewNode->m_iKey) p = p->m_pRight; else p = p->m_pLeft; } pNewNode->m_pParent = q; if (q->m_iKey < pNewNode->m_iKey) q = p->m_pRight; else p = p->m_pLeft=pNewNode; } insertfix(pNewNode); } void RBtree::insertfix(TNode* t) { TNode *u; if (m_pRootNode == t) { t->m_cColor='b'; return; } while (t->m_pParent != NULL && t->m_pParent->m_cColor == 'r') { TNode *g = t->m_pParent->m_pParent; if (g->m_pLeft == t->m_pParent) { if (g->m_pRight != NULL) { u = g->m_pRight; if (u->m_cColor == 'r') { t->m_pParent->m_cColor = 'b'; u->m_cColor = 'b'; g->m_cColor = 'r'; t = g; } } else { if (t->m_pParent->m_pRight == t) { t = t->m_pParent; leftrotate(t); } t->m_pParent->m_cColor = 'b'; g->m_cColor = 'r'; rightrotate(g); } } else { if (g->m_pLeft != NULL) { u = g->m_pLeft; if (u->m_cColor == 'r') { t->m_pParent->m_cColor = 'b'; u->m_cColor = 'b'; g->m_cColor = 'r'; t = g; } } else { if (t->m_pParent->m_pLeft == t) { t = t->m_pParent; rightrotate(t); } t->m_pParent->m_cColor = 'b'; g->m_cColor = 'r'; leftrotate(g); } } m_pRootNode->m_cColor = 'b'; } } void RBtree::del() { if (m_pRootNode == NULL) { cout << "\nEmpty Tree."; return; } int x; cout << "\nENter the m_iKey of the TNode to be deleted: "; cin >> x; TNode *p; p = m_pRootNode; TNode *y = NULL; TNode *q = NULL; int found = 0; while(p != NULL && found == 0) { if (p->m_iKey == x) found = 1; if (found == 0) { if (p->m_iKey < x) p = p->m_pRight; else p = p->m_pLeft; } } if (found == 0) { cout << "\nElement Not Found. "; return; } else { cout << "\nDeleted Element: " << p->m_iKey; cout << "\nColour: "; if (p->m_cColor == 'b') cout << "Black\n"; else cout << "Red\n"; if (p->m_pParent != NULL) cout << "\nParent:" << p->m_pParent->m_iKey; else cout << "\nThere is no m_pParent of the TNode. "; if (p->m_pRight != NULL) cout << "\nRight Child: " << p->m_pRight->m_iKey; else cout << "\nThere is no m_pRight child of the TNode. "; if (p->m_pLeft != NULL) cout << "\nLeft Child: " << p->m_pLeft->m_iKey; else cout << "\nThere is no m_pLeft child of the TNode. "; cout << "\n Node Deleted. "; if (p->m_pLeft == NULL || p->m_pRight == NULL) y = p; else y = successor(p); if (y->m_pLeft != NULL) q = y->m_pLeft; else { if (y->m_pRight != NULL) q = y->m_pRight; else q = NULL; } if (q != NULL) q->m_pParent = y->m_pParent; if (y->m_pParent == NULL) m_pRootNode = q; else { if (y == y->m_pParent->m_pLeft) y->m_pParent->m_pLeft = q; else y->m_pParent->m_pRight = q; } if (y != p) { p->m_cColor = y->m_cColor; p->m_iKey = y->m_iKey; } if (y->m_cColor == 'b') delfix(q); } }<file_sep>#include<stdio.h> void main() { char ch; float f; double d; ch = 'X'; f = 100.123; d = 123.009; printf("ch is %c,", ch); printf("f is %f,", f); printf("d is %f,",d ); }<file_sep>#include <stdio.h> #include <conio.h> void main() { int sum = 0; int sum1 = 0; int iCount = 1; int max = 0; scanf_s("%d", &max); do { sum = sum + iCount; iCount++; } while (iCount<=max); printf("%d", sum); }<file_sep>#pragma once #include "S_Thread.h" class S_UdpSocket : public S_Thread { public: SOCKET m_Socket; SOCKET m_RecvSocket; SOCKADDR_IN m_RecvAddr; SOCKADDR_IN m_SendAddr; vector<string> m_ipList; public: bool Init(); bool Run(); bool Release(); int GetIPList(); public: S_UdpSocket(); virtual ~S_UdpSocket(); }; <file_sep>#include "sCore.h" class Sample : public sCore { public: public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600)<file_sep>#pragma once /////////////////원형 연결 리스트 ////////////////////////// //사용자 정의 함수 사용 //while() //if~else //for() //////////////////////////////////////////////////////////// #define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> int iNodeSize; struct _NODE { char cName; struct _NODE *pNext; }; _NODE *g_pHead = 0; _NODE *CircularLinkedList(char *strList); _NODE *NextNodeDelete(_NODE *p); void JosephProblem(_NODE *p, int n); <file_sep>#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <thread> #include <process.h> #include <WS2tcpip.h> #include <WinSock2.h> #include <windows.h> #include <windowsx.h> #include <time.h> #include <algorithm> #include <functional> #include <tchar.h> #include <iostream> #include <vector> #include <list> #include <string> using namespace std; #pragma comment (lib,"ws2_32.lib") #pragma comment (lib,"winmm.lib") #pragma comment (lib,"Chat_Lib.lib") typedef basic_string<TCHAR> T_STR; typedef basic_string<wchar_t> W_STG; typedef basic_string<char> C_STR; #include "S_header.h"<file_sep>#include<stdio.h> #include<conio.h> #include<stdlib.h> //? void draw(int row, int col); void main() { int row=0; int col=0; printf("행렬의 차원을 입력 합니다.\n"); printf("x="); scanf_s("%d",&row); printf("y="); scanf_s("%d",&col); draw(row, col); } void draw(int row, int col) { int temp = col; for (; row > 0; col--) { printf("X"); col = temp; printf("\n"); } }<file_sep>//포인터(더럽..) // 정적할당(스택메모리):자동삭제 // 동적할당(N개수)(힙메모리):수동삭제 //1차원 배열-> 동적화->포인터 변수(N) //2차원 배열-> 동적화->포인터 변수 배열(N) //포인터 변수 배열[N] *p[N] //포인터 변수 배열 포인터 **p<file_sep>#include "DXEnumeration.h" DEnumOutput::~DEnumOutput() { SAFE_RELEASE(m_pOutput); m_DisplayModeList.clear(); } DEnumDevice::~DEnumDevice() { } void DEnumOutput::Set(UINT iIndex, IDXGIOutput* pOutput) { m_Output = iIndex; m_pOutput = pOutput; pOutput->GetDesc(&m_Desc); } DEnumAdapter::~DEnumAdapter(void) { DEnumDevice* pDeviceInfo; for (int i = 0; i < m_DeviceInfoList.size(); i++) { pDeviceInfo = m_DeviceInfoList[i]; SAFE_DEL(pDeviceInfo); } m_DeviceInfoList.clear(); DEnumOutput* pOutputInfo; for (int i = 0; i < m_OutputInfoList.size(); i++) { pOutputInfo = m_OutputInfoList[i]; SAFE_DEL(pOutputInfo); } m_OutputInfoList.clear(); SAFE_RELEASE(m_pAdapter); } void DEnumAdapter::Set(UINT iIndex, IDXGIAdapter* pAdapter) { m_AdapterOrdinal = iIndex; m_pAdapter = pAdapter; pAdapter->GetDesc(&m_AdapterDesc); } HRESULT DXEnumeration::Enumerate(IDXGIFactory* pFactory) { HRESULT hr; if (pFactory == NULL) return E_FAIL; ClearAdapterInfoList(); for (int index = 0; ; ++index) { IDXGIAdapter* pAdapter = NULL; hr = pFactory->EnumAdapters(index, &pAdapter); if (FAILED(hr))break; DEnumAdapter* pAdapterInfo = 0; SAFE_NEW(pAdapterInfo, DEnumAdapter); if (!pAdapterInfo) { return E_OUTOFMEMORY; } pAdapterInfo->Set(index, pAdapter); hr = EnumerateDevices(pAdapterInfo); if (FAILED(hr)) { delete pAdapterInfo; continue; } hr = EnumerateOutputs(pAdapterInfo); if (FAILED(hr) || pAdapterInfo->m_OutputInfoList.size() <= 0) { delete pAdapterInfo; continue; } m_AdapterInfoList.push_back(pAdapterInfo); } return S_OK; } HRESULT DXEnumeration::EnumerateDevices(DEnumAdapter* pAdapterInfo) { HRESULT hr; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; const D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); const UINT DevTypeArrayCount = sizeof(driverTypes) / sizeof(driverTypes[0]); for (UINT iDeviceType = 0; iDeviceType < DevTypeArrayCount; iDeviceType++) { DEnumDevice* pDeviceInfo = 0; SAFE_NEW(pDeviceInfo, DEnumDevice); if (pDeviceInfo == NULL) return E_OUTOFMEMORY; pDeviceInfo->m_AdapterOrdinal = pAdapterInfo->m_AdapterOrdinal; pDeviceInfo->DeviceType = driverTypes[iDeviceType]; ID3D11Device* pd3dDevice = NULL; ID3D11DeviceContext* plmmediateContext = NULL; IDXGIAdapter* pAdapter = NULL; D3D_DRIVER_TYPE ddt = driverTypes[iDeviceType]; if (driverTypes[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) { pAdapter = pAdapterInfo->m_pAdapter; ddt = D3D_DRIVER_TYPE_UNKNOWN; } D3D_FEATURE_LEVEL getFeatureLevel; hr = D3D11CreateDevice(pAdapter, ddt, (HMODULE)0, NULL, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &pd3dDevice, &getFeatureLevel, &plmmediateContext); if (FAILED(hr)) { delete pDeviceInfo; continue; } D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS ho; pd3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho)); SAFE_RELEASE(pd3dDevice); SAFE_RELEASE(plmmediateContext); pAdapterInfo->m_DeviceInfoList.push_back(pDeviceInfo); } return S_OK; } HRESULT DXEnumeration::EnumerateOutputs(DEnumAdapter* pAdapterInfo) { HRESULT hr; IDXGIOutput* pOutput; for (int iOutput = 0; ; ++iOutput) { pOutput = NULL; hr = pAdapterInfo->m_pAdapter->EnumOutputs(iOutput, &pOutput); if (DXGI_ERROR_NOT_FOUND == hr) { return S_OK; } else if (FAILED(hr)) { return hr; //Something bad happened. } else //Success! { DEnumOutput* pOutputInfo = new DEnumOutput; if (!pOutputInfo) { SAFE_RELEASE(pOutput); return E_OUTOFMEMORY; } pOutputInfo->Set(iOutput, pOutput); EnumerateDisplayModes(pOutputInfo); if (pOutputInfo->m_DisplayModeList.size() <= 0) { // If this output has no valid display mode, do not save it. delete pOutputInfo; continue; } pAdapterInfo->m_OutputInfoList.push_back(pOutputInfo); } } } HRESULT DXEnumeration::EnumerateDisplayModes(DEnumOutput* pOutputInfo) { HRESULT hr = S_OK; DXGI_FORMAT allowedAdapterFormatArray[] = { DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, //This is DXUT's preferred mode DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM }; int allowedAdapterFormatArrayCount = sizeof(allowedAdapterFormatArray) / sizeof(allowedAdapterFormatArray[0]); for (int f = 0; f < allowedAdapterFormatArrayCount; ++f) { UINT NumModes = 512; hr = pOutputInfo->m_pOutput->GetDisplayModeList(allowedAdapterFormatArray[f], DXGI_ENUM_MODES_SCALING, &NumModes, 0); DXGI_MODE_DESC* pDesc = new DXGI_MODE_DESC[NumModes]; assert(pDesc); if (!pDesc) return E_OUTOFMEMORY; hr = pOutputInfo->m_pOutput->GetDisplayModeList(allowedAdapterFormatArray[f], DXGI_ENUM_MODES_SCALING, &NumModes, pDesc); if (DXGI_ERROR_NOT_FOUND == hr) { SAFE_DELETE_ARRAY(pDesc); NumModes = 0; break; } if (SUCCEEDED(hr)) { for (UINT m = 0; m < NumModes; m++) { if (pDesc[m].Width >= 800 && pDesc[m].Height >= 600) { pOutputInfo->m_DisplayModeList.push_back(pDesc[m]); } } } SAFE_DELETE_ARRAY(pDesc); } return hr; } void DXEnumeration::ClearAdapterInfoList() { DEnumAdapter* pAdapterInfo; for (int i = 0; i < m_AdapterInfoList.size(); i++) { pAdapterInfo = m_AdapterInfoList[i]; SAFE_DEL(pAdapterInfo); } m_AdapterInfoList.clear(); } DXEnumeration::DXEnumeration() { } DXEnumeration::~DXEnumeration() { } <file_sep>#include <iostream> using namespace std; //static_cast 의미없는 형변환 방지. typedef unsigned char BYTE; void f() { char ch; int i = 65; float f = 2.5; double dbl; ch = static_cast<char>(i); //int to char dbl = static_cast<double>(f); //float to double i = static_cast<BYTE>(ch); } class B { public: virtual void Test(){} }; class D :public B{};// 상속 void f(B* pb) { D* pd1 = dynamic_cast<D*>(pb); D*pd2 = static_cast<D*>(pb); if (pd1 == NULL) cout << "pd1==NULL" << endl; else cout << "pd1 !=NULL" << endl; if (pd2 == NULL) cout << " pd1 ==NULL" << endl; else cout << "pd1 != NULL" << endl; } void f2(B* pb, D* pd) { D* pd2 = static_cast<D*>(pb); //안전하지 않다. B* pd2 = static_cast<B*>(pd); //안전하다.(safe conversion) } /////////////////////////////////////////////////////////////// class BClass; class AClass { public: int m_iValue; operator BClass(); }; AClass::operator BClass() { //멤버 초기화 BClass fRet = { static_cast<float>(m_iValue) }; return fRet; }; class BClass { public: float m_fValue; }; void main() { f(); B b; f(&b); ////////////////////////////////////////////////////// AClass a; a.m_iValue = 99; BClass c; //static_cast는 형변환 방법을 알면 변환한다. //그러나 방법을 모르면 알려줘야 한다. c = static_cast<BClass>(a); }<file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> #define USE_ARRAY USE_ARRAY int Data[20][20]; void MagicSquare(int iSize) { int iWidth, iHeight; int suja; int iRow = 0; int iCol = (iSize - 1) / 2; Data[0][iCol] = 1; for (suja = 2; suja <= iSize * iSize; suja++) { if (iRow == 0) { iHeight = iSize - 1; } else { iHeight = iRow - 1; } if (iCol == iSize - 1) { iWidth = 0; } else { iWidth = iCol + 1; } if (Data[iHeight][iWidth] == 0) { iRow = iHeight, iCol = iWidth; } else { iRow++; } Data[iRow][iCol] = suja; } } void main() { int iSize; for (;;) { printf("마방진 크기(3~19사이 홀수)....?"); scanf_s("%d", &iSize); if (iSize >= 3 && iSize < 20) { break; } MagicSquare(iSize); for (int iRow = 0; iRow < iSize; iRow++) { for (int jCol = 0; jCol < iSize; jCol++) { printf("%4d",Data[iRow][jCol]); } } printf("\n"); }_getch(); } <file_sep>#pragma once #include <iostream> #include <vector> using namespace std; enum Direction{North, East,South,West}; class MapSite { public: virtual void Enter() = 0; }; class Room: public MapSite { public: Room() {} Room(int RoomNo) { _roomNumber = RoomNo; }; MapSite* SetSide(Direction dir)const { return _sides[dir]; } void SetSide(Direction dir, MapSite* pMapSize) { _sides[dir] = pMapSize; } virtual void Enter() {}; private: MapSite * _sides[4]; int _roomNumber; }; class Wall : public MapSite { public: Wall() {} virtual void Enter() {} virtual Wall* Clone() { return new Wall(*this); }; }; class Door : public MapSite { public: Door(){} Door(Room* a, Room* b) { _room1 = a; _room2 = b; } Door(const Door& other) { _room1 = other._room1; _room2 = other._room2; }; virtual void Initialize(Room* r1, Room* r2) { _room1 = r1; _room2 = r2; }; virtual void Enter() {} Room* OtherSideFrom(Room*) {} virtual Door* Clone() { return new Door(*this); }; public: Room * _room1; Room* _room2; bool _isOpen; }; class Maze { public: Maze() {} void AddRoom(Room* room) { m_RoomList.push_back(room);} Room* RoomNo(int no)const { return m_RoomList[no]; } vector<Room*> m_RoomList; };<file_sep>#pragma once #include "xWindow.h" #include "xTimer.h" #include "xDxWrite.h" #include "xInput.h" #include "xDxState.h" #include "xModelView.h" #include "xSkyBox.h" using namespace DX; class xCore : public xWindow { public: xSkyBox m_SkyBox; xTimer m_Timer; xDxWrite m_Font; xCamera m_DefaultCamera; xModelView m_ModelCamera; xCamera* m_pMainCamera; xDirLineShape m_dirAxis; public: virtual bool GamePreInit(); bool GameInit(); bool GameRun(); bool GameRelease(); bool GameFrame(); bool GameRender(); bool GamePreRender(); bool GamePostRender(); void DeleteDeviceResources(); HRESULT CreateDeviceResources(UINT width, UINT height); virtual void DeleteResources() {}; virtual HRESULT CreateResources(UINT width, UINT height) { return S_OK; } public: virtual bool Init() { return true; } virtual bool Frame() { return true; } virtual bool Render() { return true; } virtual bool PreRender() { return true; } virtual bool PostRender() { return true; } virtual bool Release() { return true; } LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: void SwapDefaultView(); void SwapModelView(); public: xCore(); virtual ~xCore(); }; <file_sep>#pragma once #include "xStd.h" /* 1) 1프레임의 경과 시간=m_fSecPerFrame 2) 1초의 프레임 카운터 3) 게임이 실행된 누적시간 */ class xTimer { public: LARGE_INTEGER m_Frequency; DWORD m_dwFrameCount; DWORD m_dwFPS; LARGE_INTEGER m_dwBeforeTick; LARGE_INTEGER m_Elapse; LARGE_INTEGER m_Start; float m_fSecPerFrame; float m_fGameTimer; float m_fTimer; TCHAR m_csBuffer[256]; bool m_bStarted; float m_fEventTime; public: bool Init(); // 초기화 bool Frame(); // 계산 bool Render(); // 드로우 bool Release(); // 소멸, 삭제 float GetElapsedTime(); public: xTimer(); virtual ~xTimer(); }; class CStopwatch { public: CStopwatch() { QueryPerformanceFrequency(&m_liPerFreq); Start(); } void Start() { QueryPerformanceCounter(&m_liPerfStart); } __int64 Now() { // Start 가 호출된 후 경과한 밀리초를 리턴 LARGE_INTEGER liPerfNow; QueryPerformanceCounter(&liPerfNow); __int64 qwElapsedTime = (((liPerfNow.QuadPart - m_liPerfStart.QuadPart)));// / m_liPerFreq.QuadPart); return qwElapsedTime; } void Output(const TCHAR* pData) { #ifdef _DEBUG TCHAR strMessage[MAX_PATH] = { 0, }; __int64 qwElapsedTime = Now(); //float Second = static_cast<float>(qwElapsedTime) / static_cast<float>(m_liPerFreq.QuadPart); _stprintf_s(strMessage, _T("<=====%s[%lld]====>"), pData, qwElapsedTime); OutputDebugString(strMessage); #endif } private: LARGE_INTEGER m_liPerFreq; // 초당 계수 LARGE_INTEGER m_liPerfStart; // 시작 계수 };<file_sep>#pragma once #include "S_SvrObj.h" class S_Lock { public: S_SvrObj* m_pSvrObj; public: S_Lock(S_SvrObj* pSvrObj); virtual ~S_Lock(); }; <file_sep>#include <stdio.h> int main(void) { int icount; int j = 0; { for (icount = 0; icount <= 100; icount++) j += icount; printf("1~100±îÁöÀÇ ÇÕ:%d\n",j); } }<file_sep>#include "TObjMgr.h" int TObjMgr::Load(ID3D11Device* pd3dDevice, const TCHAR* strFileName, const TCHAR* strShaderName, bool bThread) { TCHAR szFileName[256]; TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; // Á¾º¹ ¹æÁö if (strFileName) { _tsplitpath_s(strFileName, Drive, Dir, FName, Ext); Ext[4] = 0; _stprintf_s(szFileName, _T("%s%s"), FName, Ext); for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { TModel *pPoint = (TModel *)(*itor).second; if (!_tcsicmp(pPoint->m_szName.c_str(), szFileName)) { return (*itor).first; } } } TModel* pNewModel = GetFileTypeID(strFileName); if (pNewModel == nullptr) { return -1; } pNewModel->Init(); pNewModel->m_szName = szFileName; if (pNewModel->Load(pd3dDevice, strFileName, strShaderName, bThread)) { TMap.insert(make_pair(m_iCurIndex++, pNewModel)); return m_iCurIndex - 1; } return -1; }; int TObjMgr::Add(TModel* pNode) { TMap.insert(make_pair(m_iCurIndex++, pNode)); return m_iCurIndex - 1; }; TModel* TObjMgr::GetFileTypeID(const TCHAR* pszFileName) { TCHAR szFileName[256]; TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; _tsplitpath(pszFileName, Drive, Dir, FName, Ext); Ext[4] = 0; _stprintf_s(szFileName, _T("%s%s"), FName, Ext); TModel* pModel = nullptr; if (!_tcsicmp(Ext, _T(".ASE"))) { SAFE_NEW(pModel,TAseObj); pModel->m_ObjType = ASEFILE; return pModel; } if( !_tcsicmp( Ext, _T(".TBS") ) ) { SAFE_NEW(pModel, TTbsObj); pModel->m_ObjType = TBSFILE; return pModel; } if( !_tcsicmp( Ext, _T(".SKM") ) ) { SAFE_NEW(pModel, TSkinObj); pModel->m_ObjType = SKMFILE; return pModel; } if( !_tcsicmp( Ext, _T(".MAT") ) ) { SAFE_NEW(pModel, TBoneObj); pModel->m_ObjType = MATFILE; return pModel; } return nullptr; } void TObjMgr::SetMatrix(D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj) { TTemplateMap< TModel >::TemplateMapItor itor; for (itor = TMap.begin(); itor != TMap.end(); itor++) { TModel *pPoint = (TModel *)(*itor).second; if (pPoint) { pPoint->SetMatrix(pWorld, pView, pProj); } } } TObjMgr::TObjMgr() { } TObjMgr::~TObjMgr() { } <file_sep>#pragma once #include "Header.h" typedef struct _D3DMATRIX_ { union { struct { float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; float m[4][4]; }; } _D3DMATRIX; struct SScene { int iFirstFrame; int iLastFrame; int iFrameSpeed; int iTickPerFrame; int iNumObject; int iNumMtrl; }; struct xTextureMap { int iType; TSTR name; }; struct xMtrlerial { vector<xTextureMap> m_mapList; vector<xMtrlerial> m_SubMaterial; }; struct xIndex { int i[3]; int iSubMtrl; }; struct SVertex { Point3 p; Point3 n; Point3 c; Point3 t; }; struct STri { SVertex v[3]; }; struct xGeomMesh { int mtrlRef; TSTR pParentName; TSTR name; _D3DMATRIX matWorld; // MAX = Matrix3 4x3 vector<Point3> vertexList; vector<xIndex> PosFaceList; vector<Point2> texList; vector<xIndex> texFaceList; vector<Point4> ColList; vector<xIndex> ColFaceList; vector<Point3> NorList; }; class S_KHJGlobal { public: Interface * m_pMax; TSTR m_szFileName; // TSTR NAME; //TSTR max에서 사용하는거 INode* m_pRootNode; Interval m_Interval; SScene m_Scene; vector<INode*> m_ObjectList; vector<Mtl*> m_MtrlList; vector<xMtrlerial> m_xMtrlList; vector<xGeomMesh> m_xObjectList; public: void PreProcess(INode* pNode); void Initialize(Interface *i, TSTR name); void AddObject(INode* pNode); void AddMtl(INode* pNode); public: void DumpMatrix3(Matrix3* m, _D3DMATRIX& mat); public: S_KHJGlobal(); virtual ~S_KHJGlobal(); }; <file_sep>#include "TCore.h" #include "TBitmap.h" struct tPoint { float x, y; }; class Sample : public TCore { TBitmap m_bitmap; tPoint m_pos; public: bool Init() { m_pos.x = 100; m_pos.y = 100; m_bitmap.Load(L"rogo1.bmp.bmp"); return true; } bool Frame() { if (I_Input.Key('W')) { m_pos.y += -1 * g_fSecPerFrame*300.0f; } if (I_Input.Key('S')) { m_pos.y += 1 * g_fSecPerFrame*300.0f; } if (I_Input.Key('A')) { m_pos.x += -1 * g_fSecPerFrame*300.0f; } if (I_Input.Key('D')) { m_pos.x += 1 * g_fSecPerFrame*300.0f; } return true; } bool Render() { BitBlt(m_hOffScreenDC, m_pos.x, m_pos.y, 800, 600, m_bitmap.m_hMemDC, 0, 0, SRCCOPY); return true; } bool Release() { return true; } public: Sample() {} ~Sample() {} }; GAME_RUN("SampleInput", 800, 600)<file_sep>#include "S_Lock.h" S_Lock::S_Lock(S_SvrObj* pSvrObj) : m_pSvrObj(pSvrObj) { if (pSvrObj == NULL) { return; } EnterCriticalSection(&pSvrObj->m_Ct); } S_Lock::~S_Lock() { if (m_pSvrObj == NULL) { return; } LeaveCriticalSection(&m_pSvrObj->m_Ct); } <file_sep>#pragma once #include "DTemplate.h" namespace TBASIS_BASE { class DIDInput : public DSingleton<DIDInput> { private: friend class DSingleton<DIDInput>; public: bool Init(); bool Frame(); bool Render(); bool Release(); bool ResetDevice(); bool ResetResource() { return true; }; public: LPDIRECTINPUT8 m_pDi; LPDIRECTINPUTDEVICE8 m_pDidevKey; LPDIRECTINPUTDEVICE8 m_pDidevMouse; DIDEVICEOBJECTDATA m_didod[SAMPLE_BUFFER_SIZE]; BYTE m_KeyState[KEYSTATECOUNT]; BYTE m_KeyBeforeState[KEYSTATECOUNT]; DIMOUSESTATE m_MouseState; DIMOUSESTATE m_MouseBeforeState; DWORD m_dwElements; HWND m_hWnd; DWORD m_dwlmmediate; public: bool InitDirectInput(HINSTANCE, HWND, bool, bool); bool KeyProcess(); bool MouseProcess(); void DeviceAcquire(); void DeviceUnacquire(); bool IsKeyDown(DWORD dwKey); bool IsKeyUP(DWORD dwKey); void PostProcess(); void SetAcquire(bool bActive); public: DIDInput(void); virtual ~DIDInput(void); }; #define I_Input DIDInput::GetInstance() } using namespace TBASIS_BASE; <file_sep>#pragma once #include "S_Std.h" class S_Input :public Singleton<S_Input> { private: friend class Singleton<S_Input>; public: bool m_bKeydown[MAX_ARRAY]; bool m_bKeyUp[MAX_ARRAY]; public: POINT m_ptMousePos; bool StayKeydown(INT iKey); bool OnceKeydwon(INT iKey); bool OnceKeyUp(INT iKey); public: bool Init(); bool Frame(); bool Render(); bool Release(); public: S_Input(); virtual ~S_Input(); }; #define S_INPUT S_Input::GetInstance() <file_sep>#include<stdio.h> #include<conio.h> void main() { int a = 1; switch (a) { case 1: printf("A=1\n"); case 2: printf("A=2\n"); break; } _getch(); }<file_sep>#include<stdio.h> void main() { int a = 5; int b = 6; if (a < b) { printf("a<b\n"); } else { printf("a>b\n"); } }<file_sep>#pragma once #include "Std.h" class Window { public: HWND m_hWnd; HINSTANCE m_hInstance; RECT m_rtClient; RECT m_rtWindow; private: DWORD m_dwStyle; public: void Set(DWORD dwStyle); void CenterWindow(); bool SetWindow(HINSTANCE hInstance, const TCHAR* pTitleName = L"KGCA Sample", UINT iWidth = 800, UINT iHight = 600); bool Run(); public: virtual LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); virtual bool GameInit(); virtual bool GameRun(); virtual bool GameRelease(); public: Window(); virtual ~Window(); }; <file_sep>#include <stdio.h> int main(void) { int a = 2 != 4 && 5 > 3; int b = !1 || !0; printf("%d\n", a); printf("%d\n", b); }<file_sep>#pragma once #include "S_PacketPool.h" #include "S_Protocol.h" class S_Chat_PacketPool : public S_PacketPool { public: void ProcessWork(PACKET* pUserData); public: S_Chat_PacketPool(); virtual ~S_Chat_PacketPool(); }; <file_sep>#include<stdio.h> #include<conio.h> // 다차원 배열 //void main() //{ // int a[2][3]; // int i; // int j; // // a[0][0] = 0; a[0][1] = 1; a[0][2] = 2; // a[1][0] = 1; a[1][1] = 2; a[1][2] = 3; // // printf("\n[%d][%d]=%d", 0, 0, a[0][0]); // printf("\n[%d][%d]=%d", 1, 0, a[1][0]); // printf("\n[%d][%d]=%d", 0, 1, a[0][1]); // printf("\n[%d][%d]=%d", 1, 1, a[1][1]); // printf("\n[%d][%d]=%d", 0, 2, a[0][2]); // printf("\n[%d][%d]=%d", 1, 2, a[1][2]); // printf("\n[%d][%d]=%d", 0, 0, a[0][0]); //} void main() { int i; int j; static int integer[2][3] = { 1,2,3,4,5 }; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { printf("\n integer[%d][%d]=%d", i, j, integer[i][j]); } } }<file_sep>#pragma once // UI_INTERFACE 대화 상자 class UI_INTERFACE : public CDialog { DECLARE_DYNAMIC(UI_INTERFACE) public: UI_INTERFACE(CWnd* pParent = nullptr); // 표준 생성자입니다. virtual ~UI_INTERFACE(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_INTERFACE }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); }; <file_sep>#include "SLock.h" SLock::SLock(SServerObj* pObj) : m_pSerObj(pObj) { if (pObj == NULL)return; EnterCriticalSection(&pObj->m_cs); } SLock::~SLock(void) { if (m_pSerObj == NULL)return; LeaveCriticalSection(&m_pSerObj->m_cs); } <file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { int *IpPoint[10]; for (int iCnt = 0; iCnt < 10; iCnt++) { IpPoint[iCnt] = (int*)malloc(sizeof(int)); *IpPoint[iCnt] = iCnt * 10; printf("\n0x%08x¹øÁö:%d", IpPoint + iCnt, *IpPoint[iCnt]); } for (int iCnt = 0; iCnt < 10; iCnt++) { free(IpPoint[iCnt]); } }<file_sep>#include "SCHAT_Client.h" #include "SDebugString.h" #include "SLock.h" unsigned __stdcall sendMessage(void * arg) { I_Debug.Print("%s","send 스레드 시작"); SCHAT_Client* pClient = (SCHAT_Client*)arg; while (!pClient->m_bExit) { if (pClient->m_bLoginOK && pClient->m_bSend) { if (pClient->SendMsg(pClient->m_strBuffer, PACKET_CHAT_MSG) <= 0) { break; } pClient->m_bSend = false; } if (SwitchToThread() == FALSE) { Sleep(1); } } return 0; } unsigned __stdcall receiveMessage(void* arg) { I_Debug.Print("%s", "receive 스레드 시작"); SCHAT_Client* pClient = (SCHAT_Client*)arg; int iSocket = pClient->m_iSocket; char strBuffer[2048] = { 0, }; while (!pClient->m_bExit) { int iRet = recv(iSocket, strBuffer, sizeof(strBuffer), 0); if (iRet <= 0) { if (WSAGetLastError() == WSAEWOULDBLOCK) { continue; } pClient->m_bExit = true; closesocket(pClient->m_iSocket); break; } strBuffer[iRet] = 0; pClient->m_StreamPacket.Put(strBuffer, iRet, pClient); if (SwitchToThread() == FALSE) { Sleep(1); } } return 0; } int SCHAT_Client::ProcessPacket() { { SLock lock(this); list<S_PACKET>::iterator itor; for (itor = m_StreamPacket.m_PacketList.begin(); itor != m_StreamPacket.m_PacketList.end(); itor++) { UPACKET* pPacket = &(*itor).packet; switch (pPacket->ph.type) { case PACEKT_CHAT_NAME_REQ: { I_Debug.Print("%s", pPacket->msg); }break; case PACKET_CHAT_MSG: { I_Debug.Print("%s", pPacket->msg); }break; } } m_StreamPacket.m_PacketList.clear(); } return 1; } int SCHAT_Client::SendMsg(char* pMsg, WORD code) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sprintf_s(sendmsg.msg, pMsg); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(sendmsg.msg); int iRet = send(m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if (iRet <= 0) { m_bSend = false; if (WSAGetLastError() == WSAEWOULDBLOCK) { return 1; } return 0; } m_bSend = false; return 1; } int SCHAT_Client::SendMsg(char*pMsg, int iSize, WORD code) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); memcpy(sendmsg.msg, pMsg, iSize); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + iSize; int iRet = send(m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if (iRet <= 0) { m_bSend = false; if (WSAGetLastError() == WSAEWOULDBLOCK) { return 1; } return 0; } m_bSend = false; return 1; } int SCHAT_Client::CreateConnectSocket(int iPort) { int Rv; m_iSocket = socket(AF_INET, SOCK_STREAM, 0); if (m_iSocket == INVALID_SOCKET) { return -1; } SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 루프백 주소 127.0.0.1 serveraddr.sin_port = htons(iPort); Rv = connect(m_iSocket, (sockaddr*)&serveraddr, sizeof(serveraddr)); if (Rv == SOCKET_ERROR) { return -1; } linger optval; int iLength = sizeof(optval); getsockopt(m_iSocket, SOL_SOCKET, SO_LINGER, (char*)&optval, &iLength); optval.l_onoff = 1; optval.l_linger = 1000; setsockopt(m_iSocket, SOL_SOCKET, SO_LINGER, (char*)&optval, iLength); int socketType1; int typeLen1 = sizeof(socketType1); getsockopt(m_iSocket, SOL_SOCKET, SO_TYPE, (char*)&socketType1, &typeLen1); if (socketType1 == SOCK_STREAM) { I_Debug.Print("%s", "SOCK_STREAM."); } else { I_Debug.Print("%s", "SOCK_DGRAM"); } getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1); I_Debug.Print("%s=%d", "SO_SNDBUF", socketType1); getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1); I_Debug.Print("%s=%d", "SO_RCVBUF", socketType1); return 0; } bool SCHAT_Client::Init() { int rv; WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return -1; } if (CreateConnectSocket(10000) == 0) { // send thread unsigned sendThread, receiveThread; m_hSendThread = _beginthreadex(NULL, 0, sendMessage, (void*)this, 0, &sendThread); // recv thread m_hReceiveThread = _beginthreadex(NULL, 0, receiveMessage, (void*)this, 0, &receiveThread); int iLevelSend = GetThreadPriority(HANDLE(m_hSendThread)); int iLeveIRecv = GetThreadPriority(HANDLE(m_hReceiveThread)); if (SetThreadPriority(HANDLE(m_hReceiveThread), THREAD_PRIORITY_ABOVE_NORMAL == TRUE)) { iLeveIRecv = GetThreadPriority(HANDLE(m_hReceiveThread)); INT KKK = 0; }; m_bLoginOK = true; } return true; } bool SCHAT_Client::Frame() { if (m_bExit) { I_Debug.Print("%s", " 서버가 종료 되었습니다."); m_bExit = false; } return true; } bool SCHAT_Client::Release() { m_bExit = true; closesocket(m_iSocket); WaitForSingleObject((HANDLE)m_hSendThread, INFINITE); WaitForSingleObject((HANDLE)m_hReceiveThread, INFINITE); WSACleanup(); CloseHandle(HANDLE(m_hReceiveThread)); CloseHandle(HANDLE(m_hSendThread)); m_hReceiveThread = NULL; m_hSendThread = NULL; return true; } SCHAT_Client::SCHAT_Client(void) { m_bSend = false; m_bLoginOK = false; m_bExit = false; m_iSocket = 0; m_hReceiveThread = 0; m_hSendThread = 0; } SCHAT_Client::~SCHAT_Client(void) { } <file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { system("cls"); int *pPtr; int **ppPtr; int num = 10; pPtr = &num; //포인터의 메모리 주소는 일반포인트에 저장 불가하며 //반드시 이중포인터에 저장해야 한다. ppPtr = &pPtr;//pPtr의 주소 저장 printf("%d\n", **ppPtr);//ppPtr의 메모리 주소에 접근 int **ppPoint = 0; ppPoint = (int**)malloc(sizeof(int) * 10); for (int iCnt = 0; iCnt < 10; iCnt++) { ppPoint[iCnt] = (int*)malloc(sizeof(int) * 10); } for (int iCnt = 0; iCnt < 10; iCnt++) { for (int jCnt = 0; jCnt < 10; jCnt++) { ppPoint[iCnt][jCnt] = iCnt * 10 + jCnt; } } for (int iCnt = 0; iCnt < 10; iCnt++) { printf("\n"); for (int jCnt = 0; jCnt < 10; jCnt++) { printf("[%d,%d]=%d", iCnt, jCnt, ppPoint[iCnt][jCnt]); printf("[%d,%d]=%d", iCnt, jCnt, *(ppPoint[iCnt] + jCnt)); } } for (int iCnt = 0; iCnt < 10; iCnt++) { free(ppPoint[iCnt]); } free(ppPoint); }<file_sep>#include "LinkedListSing.h" void LinkedListSing::Add() { //첫번째 생성 if (m_Head == NULL) { m_Head = new Node(i_MAX++); // Head 동적할당 m_Tail = m_Head; // Tail과 Head 연결 m_Tail->m_pNext = NULL; //Tail의 Next가 NULL return; } //두번째 생성 m_Tail->m_pNext = new Node(i_MAX++); //Tail의 Next 동적할당 m_Tail = m_Tail->m_pNext; m_Tail->m_pNext = NULL; //Tail의 next가 NULL } void LinkedListSing::Del(int aData) { if (m_Head != NULL) { if (m_Head->m_pNext == NULL) { if (m_Head->iData == aData) { delete m_Head; }return; } if (m_Head->m_pNext != NULL) { Node* pTemp; if (m_Head->iData == aData) { pTemp = m_Head->m_pNext; delete m_Head; m_Head = pTemp; } for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { if (pTemp->m_pNext->iData == aData) { break; } } Node* DelNode = pTemp->m_pNext; Node* DelNodeNext = DelNode->m_pNext; delete DelNode; pTemp->m_pNext = DelNodeNext; } } } void LinkedListSing::print() { Node* pTemp; for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { cout << pTemp->iData << endl; } cout << pTemp->iData << endl; } void LinkedListSing::Find(int sData) { Node* pTemp; for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { if (pTemp->m_pNext->iData == sData) { break; } } } LinkedListSing::LinkedListSing() { m_Head = 0; m_Tail = 0; i_MAX = 0; } LinkedListSing::~LinkedListSing() { } <file_sep>#include "S_Chat_PacketPool.h" #include "S_ChatUser.h" #include "S_Chat_Svr.h" #include "S_DebugString.h" void S_Chat_PacketPool::ProcessWork(PACKET* pUserData) { UPACKET* pPacket = &(pUserData->packet); S_ChatUser* pUser = (S_ChatUser*)pUserData->pUser; switch (pPacket->ph.type) { case PACKET_USER_POSITION: { pUser->MoveMent(pPacket); S_CHAT.Broadcastting(pPacket, pUser->m_Socket); }break; case PACKET_CHAT_NAME_ACK: { pUser->m_szname = pPacket->msg; char buffer[256] = { 0, }; sprintf_s(buffer, "[%s]%s", pUser->m_szname.c_str(), "님이 들어오셧습니다"); ZeroMemory(pPacket->msg, 2048); sprintf_s(pPacket->msg, "%s", buffer); pPacket->ph.len = WORD(sizeof(PACKET_HEADER) + strlen(buffer)); pPacket->ph.type = PACKET_CHAT_MSG; S_CHAT.Broadcastting(pPacket, pUser->m_Socket); }break; case PACKET_CHAT_MSG: { S_CHAT.Broadcastting(pPacket, pUser->m_Socket); }break; } } S_Chat_PacketPool::S_Chat_PacketPool() { } S_Chat_PacketPool::~S_Chat_PacketPool() { } <file_sep>#include <iostream> #include <time.h> #define MAX_NUM 100 int g_iStackBuffer[MAX_NUM]; int g_iTopStack = 0; int g_iQueueNuffer[MAX_NUM];<file_sep>#pragma once #include "S_Core.h" #include "S_Client.h" #include "S_UdpSocket.h" class S_Main : public S_Core { public: S_UdpSocket m_UDP; S_Client m_Client; HWND m_hEdit; HWND m_hChatEdit; TCHAR m_strBuf[128]; public: bool Init(); bool Frame(); bool Release(); bool PreRender() { return true; } bool PostRender() { return true; } LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: S_Main(); virtual ~S_Main(); }; <file_sep>#pragma once #include "DXDefine.h" class DEnumOutput { public: ~DEnumOutput(); void Set(UINT iIndex, IDXGIOutput* pAdapter); UINT m_Output; IDXGIOutput* m_pOutput; DXGI_OUTPUT_DESC m_Desc; vector<DXGI_MODE_DESC> m_DisplayModeList; }; class DEnumDevice { public: public: ~DEnumDevice(); UINT m_AdapterOrdinal; vector<DEnumOutput*> m_OutputInfoList; D3D_DRIVER_TYPE DeviceType; }; class DEnumAdapter { public: ~DEnumAdapter(); void Set(UINT iIndex, IDXGIAdapter* pAdapter); UINT m_AdapterOrdinal; DXGI_ADAPTER_DESC m_AdapterDesc; IDXGIAdapter* m_pAdapter; vector<DEnumOutput*> m_OutputInfoList; vector<DEnumOutput*> m_DeviceInfoList; }; class DXEnumeration { public: vector<DEnumAdapter*> m_AdapterInfoList; public: HRESULT Enumerate(IDXGIFactory* pFactory); HRESULT EnumerateDevices(DEnumAdapter* pAdapterInfo); HRESULT EnumerateDisplayModes(DEnumOutput); HRESULT EnumerateOutputs(DEnumAdapter* pAdaperInfo); void ClearAdapterInfoList(); public: DXEnumeration(void); virtual ~DXEnumeration(void); }; <file_sep>#pragma once #include "TParent.h" class TChild:public TParent { public: void Humanity(void); //추가된 멤버함수 void Character(void); //수정된 멤버함수 void Appearance(void); //확장된 멤버함수 public: TChild(); ~TChild(); }; <file_sep>#include "SProtocol.h" #define PACKET_CHAR_NAME_REQ 1000 #define PACKET_CHAR_NAME_ACK 1001 #define PACKET_CHAR_MSG 1002 #pragma pack(push,1) typedef struct { WORD user_idx; WORD PosX; WORD PosY; WORD direction; }SPACKET_USER_POSITION; #define PACKET_USER_POSITION 3000 #pragma pack(pop)<file_sep>#include<stdio.h> #include<conio.h> //Á¦¾î¹® //void main() //{ // int oddTotal = 0; // int evenTotal = 0; // // for (int i = 1; i <= 100; i++) // { // if (i % 2 == 0) // { // evenTotal += i; // } // else // { // oddTotal += i; // } // } // printf("%d%d", evenTotal, oddTotal); //} int get_menu_choice(void); void main() { int choice; choice = get_menu_choice(); printf("You chose Menu Option %d\n", choice); } int get_menu_choice() { int selection = 0; do { printf("1.Add aRecord\n"); printf("2.Change a record\n"); printf("3.Quit\n"); printf("1. Enter Selection:"); scanf_s("%d", &selection); } while (selection < 1 || selection>3); return selection; }<file_sep>#pragma once #include "TPacketPool.h" typedef struct _OVERLAPPEDEX : OVERLAPPED { enum { MODE_RECV=0, MODE_SEND=1 }; int iFlags; _OVERLAPPEDEX(){ iFlags = MODE_RECV; } }OVERLAPPEDEX; class TUser : public TServerObj { public: TStreamPacket m_StreamPacket; SOCKET m_Socket; C_STR m_szName; SOCKADDR_IN m_UserAddress; WSABUF m_szRecvBuffer; WSABUF m_szWsaBuf; char m_strBuffer[4096]; OVERLAPPEDEX m_ov; public: bool Create(); bool Run(); virtual void AddPacket(T_PACKET& addPacket ); virtual void DeleteUser( SOCKET socket ); virtual void DeleteUser(); virtual void WaitForPacketReceive(); virtual void Dispatch( DWORD dwByteSize, LPOVERLAPPED ov); public: TUser(void); ~TUser(void); }; <file_sep>#pragma once #include "xStd.h" /* 1) 1프레임의 경과 시간=m_fSecPerFrame 2) 1초의 프레임 카운터 3) 게임이 실행된 누적시간 */ class xTimer { public: LARGE_INTEGER m_Frequency; DWORD m_dwFrameCount; DWORD m_dwFPS; LARGE_INTEGER m_dwBeforeTick; float m_fSecPerFrame; float m_fGameTimer; float m_fTimer; TCHAR m_csBuffer[256]; public: bool Init(); // 초기화 bool Frame(); // 계산 bool Render(); // 드로우 bool Release(); // 소멸, 삭제 public: xTimer(); virtual ~xTimer(); }; <file_sep>#include "S_Main.h" #include "S_DebugString.h" #include "S_Input.h" LRESULT S_Main::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { m_hEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, 500, 10, 200, 25, hWnd, (HMENU)202, m_hInstance, NULL); CreateWindow(_T("button"), _T("Send"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 700, 10, 50, 25, hWnd, (HMENU)302, m_hInstance, NULL); int iWidth = 800; int iHeight = 600; S_Debug.m_hList = CreateWindow(L"listbox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL, 0, 0, iWidth - 300, iHeight, hWnd, (HMENU)0, m_hInstance, NULL); }return 0; case WM_COMMAND: switch (LOWORD(wParam)) { case 302: { GetWindowText(m_hEdit, m_strBuf, 128); S_Debug.ConvertWideStringToAnsiCch(m_Client.m_strBuf, m_strBuf, 128); InvalidateRect(hWnd, NULL, NULL); if (m_Client.m_LoginOk == false && m_Client.SendMsg(m_Client.m_strBuf, PACKET_CHAT_NAME_ACK)) { m_Client.m_LoginOk = true; } else { m_Client.m_Send = true; } } } break; case WM_CHAR: break; } return -1; } bool S_Main::Init() { m_Client.Init(); m_UDP.Init(); return true; } bool S_Main::Frame() { if (S_INPUT.StayKeydown(VK_LEFT)) { SPACKET_USER_POSITION UserData; UserData.direction = VK_LEFT; UserData.PosX = 100; UserData.PosY = 100; UserData.user_idx = 999; char buffer[256] = { 0, }; int Size = sizeof(UserData); memcpy(buffer, &UserData, Size); m_Client.SendMsg(buffer, Size, PACKET_USER_POSITION); } m_Client.ProcessPacket(); m_Client.Frame(); return true; } bool S_Main::Release() { m_UDP.Release(); m_Client.Release(); return true; } S_Main::S_Main() { } S_Main::~S_Main() { } INT WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPreInst, LPWSTR strCmdLine, INT nShow) { S_Main Client; if (!Client.SetWindow(hInst, _T("S_Chat_Client"), 800, 600)) { return 0; } SetCursor(NULL); if (Client.Run() == false) { return 0; } return 1; }<file_sep>#include "DB_MGR.h" bool DB_MGR::Add() { USERINFO info; char m_cName[20] = { 0, }; char m_cPass[20] = { 0, }; printf("아이디를 입력 하세요:"); scanf("%s", &m_cName); MultiByteToWideChar(CP_ACP, 0, m_cName, -1, info.UserID, sizeof(m_cName)); printf("\n비밀번호를 입력 하세요:"); scanf("%s", &m_cPass); MultiByteToWideChar(CP_ACP, 0, m_cPass, -1, info.UserPS, sizeof(m_cPass)); wsprintf(info.szSQL, _T("Insert into KHJUser(UserId,UserPs) values('%s','%s')"), info.UserID, info.UserPS); SQLRETURN sRet; sRet = SQLExecDirect(m_hSTMT, info.szSQL, SQL_NTS); if (sRet == SQL_SUCCESS) { SQLCloseCursor(m_hSTMT); return true; } SQLCloseCursor(m_hSTMT); return false; } bool DB_MGR::Delete() { USERINFO info; char m_cName[20] = { 0, }; printf("삭제할 아이디를 입력하시요 :"); scanf("%s", &m_cName); MultiByteToWideChar(CP_ACP, 0, m_cName, -1, info.UserID, sizeof(m_cName)); wsprintf(info.szSQL, _T("delete from KHJUser where UserId='%s'"), info.UserID); SQLRETURN sRet; sRet = SQLExecDirect(m_hSTMT, info.szSQL, SQL_NTS); if (sRet == SQL_SUCCESS) { SQLCloseCursor(m_hSTMT); return true; } SQLCloseCursor(m_hSTMT); return false; } bool DB_MGR::Update() { USERINFO info; char OldName[20] = { 0, }; char NewName[20] = { 0, }; printf("수정할 아이디를 입력하세요 :"); scanf("%s", &OldName); MultiByteToWideChar(CP_ACP, 0, OldName, -1, info.OldUserID, sizeof(OldName)); printf("새로운 아이디를 입력하세요 :"); scanf("%s", &NewName); MultiByteToWideChar(CP_ACP, 0, NewName, -1, info.NewUserID, sizeof(NewName)); wsprintf(info.szSQL, _T("update KHJUser set UserId='%s' where UserId='%s'"), info.NewUserID, info.OldUserID); SQLRETURN sRet; sRet = SQLExecDirect(m_hSTMT, info.szSQL, SQL_NTS); if (sRet == SQL_SUCCESS) { SQLCloseCursor(m_hSTMT); return true; } SQLCloseCursor(m_hSTMT); return false; } void DB_MGR::Select() { USERINFO info; SQLLEN LID, LPS; SQLBindCol(m_hSTMT, 1, SQL_C_CHAR, info.UserID, sizeof(info.UserID), &LID); SQLBindCol(m_hSTMT, 2, SQL_C_CHAR, info.UserPS, sizeof(info.UserPS), &LPS); //ret = SQLExecDirect(m_hSTMT, (SQLTCHAR*)_T("select UserId, UserPs from KHJUser"), SQL_NTS); if (SQLExecDirect(m_hSTMT, (SQLTCHAR*)_T("{CALL usp_Select}"), SQL_NTS) != SQL_SUCCESS) { return; } while (SQLFetch(m_hSTMT) != SQL_NO_DATA) { printf("\nID : %s\tPS : %s", info.UserID, info.UserPS); } SQLCloseCursor(m_hSTMT); } SQLRETURN HandleDiagnosticRecord(SQLHANDLE hHandle, SQLSMALLINT hType, RETCODE RetCode) { int ii; SQLINTEGER NativeError; SQLTCHAR SqlState[6], Msg[255]; SQLSMALLINT MsgLen; TCHAR str[256]; ii = 1; while (RetCode = SQLGetDiagRec(hType, hHandle, ii, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen) != SQL_NO_DATA) { wsprintf(str, _T("SQLSTATE:%s, 진단정보:%s"), (LPCTSTR)SqlState, (LPCTSTR)Msg); ::MessageBox(NULL, str, _T("진단 정보"), 0); ii++; } return RetCode; } void DB_MGR::FindSelect() { int sRet=0; USERINFO info; SQLINTEGER cbRetParam; TCHAR FindUserID[10] = { 0, }; SQLLEN lName, lPass; SQLBindCol(m_hSTMT, 1, SQL_C_CHAR, info.UserID, sizeof(info.UserID), &lName); SQLBindCol(m_hSTMT, 2, SQL_C_CHAR, info.UserPS, sizeof(info.UserPS), &lPass); printf(" 검색할 아이디를 입력하세요 : "); scanf_s("%s", FindUserID, 10); SQLBindParameter(m_hSTMT, 1, SQL_PARAM_OUTPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &sRet, 0, 0); SQLBindParameter(m_hSTMT, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 20,0,(SQLTCHAR*)&FindUserID,0,0); sRet = SQLExecDirect(m_hSTMT, (SQLTCHAR*)_T("{?= CALL usp_FIND(?)}"), SQL_NTS); if (sRet != SQL_SUCCESS && sRet != SQL_SUCCESS_WITH_INFO) { SQLTCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1]; SQLTCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length; // 단순한 에러 SQLError(m_hENV, m_hDBC, m_hSTMT, sqlstate, &sqlcode, buffer, SQL_MAX_MESSAGE_LENGTH + 1, &length); MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); // 모든 에러 나열됨. int iErrorCnt = 1; while (sRet = SQLGetDiagRec(SQL_HANDLE_DBC, m_hDBC, iErrorCnt++, sqlstate, &sqlcode, buffer, sizeof(buffer), &length) != SQL_NO_DATA) { MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); } return; } system("cls"); while (SQLFetch(m_hSTMT) != SQL_NO_DATA) { printf("\nID : %s\tPS : %s", info.UserID, info.UserPS); } SQLCloseCursor(m_hSTMT); } DB_MGR::DB_MGR() { } DB_MGR::~DB_MGR() { } <file_sep>#pragma once #include "DDefine.h" namespace TBASIS_BASE { template<class D> class DSingleton { public: static D& GetInstance() { static D theSingleInstance; return theSingleInstance; } static D* GetInstancePtr() { static D theSingleInstance; return &theSingleInstance; } }; }<file_sep>#pragma once #include "SServerObj.h" class SDebugString : public SSingleton<SDebugString>, public SServerObj { private: friend class SSingleton<SDebugString>; public: HWND m_hList; // 윈도우 핸들 public: void Print(const char* fmt, ...); // 출력 함수 public: bool Init(); // 초기화 bool Release(); // 소멸 WCHAR* GetMbToWcs(const char* strMsg); // 멀티바이트를 유니코드로 변환 char* GetWcsToMbs(const WCHAR* strMsg); // 유니코드를 멀티바이트로 변환 HRESULT ConvertWideStringToAnsiCch(char* msg, const WCHAR* strMsg, int iRen); // 유니코드를 멀티바이트로 변환 HRESULT ConvertAnsiStringToWideCch(WCHAR* msg, const char* strMsg, int iRen); // 멀티바이트를 유니코드로 변환 void T_ERROR(bool bPrint = false); public: SDebugString(void); virtual ~SDebugString(void); }; #define I_Debug SDebugString::GetInstance() <file_sep>#pragma once #include <winsock2.h> #include <ws2tcpip.h> //InetNtop(), inet_ntop(); #include <iostream> #include <list> #include <map> #pragma comment(lib, "ws2_32") class pch { public: pch(); virtual ~pch(); }; <file_sep>#include "Sample.h" void qsort(int a[], int n) { int p, t; int i, j; int l, r; InitStack(); l = 0; r = n - 1; StackPush(r); StackPush(l); while (!IsStatkEmpty()) { l = StackPop(); r = StackPop(); if (r - l + 1 > 1) { //종료조건 ::남아 있는 분할의 원소 개수가 1개 이상일 경우 p = a[r]; i = l - 1; j = r; while (1) { while (a[++i] < p); while (a[--j] > p); if (i >= j)break; Swap(&a[i], &a[j]); } //pivot과 i값을 교환 Swap(&a[i], &a[r]); StackPush(r); //오른쪽 분할의 오른쪽 끝 StackPush(i+1); //오른쪽 분할의 왼쪽 끝 StackPush(i-1); //왼쪽 분할의 오른쪽 끝 StackPush(l); // 왼쪽 분할의 왼쪽 끝 } // if }// while } void DataPrint(int item[], int iCount) { for (int iCnt = 0; iCnt < iCount; iCnt++) { std::cout << item[iCnt] << std::endl; } } void SetData(int item[], int iCount) { srand((unsigned int)time(NULL)); for (int iCnt = 0; iCnt < iCount; iCnt++) { item[iCnt] = rand() % iCount; } } void main() { srand((unsigned)time(NULL)); int data[MAX_NUM]; for (int i = 0; i < MAX_NUM; i++) { data[i] = rand() % MAX_NUM; StackPush(data[i]); QueuePush(data[i]); } // 원시 데이터 printf("\n원시 데이터"); DataPrint(data, MAX_NUM); //int Size = sizeof(data)/sizeof(data[0]); printf("\n스택 데이터"); for (int i = 0; i<MAX_NUM; i++) { printf(" %d", StackPop()); } //printf("%c",'\n'); printf("\n큐 데이터"); for (int i = 0; i<MAX_NUM; i++) { printf(" %d", QueuePop()); } printf("%c", '\n'); qsort(data, MAX_NUM); printf("\n퀵 정렬 데이터"); DataPrint(data, MAX_NUM); }<file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <iostream> #include <WinSock2.h> #include <vector> #pragma comment(lib,"ws2_32.lib") std::vector<SOCKET>g_userList; int main() { // WSA는 윈속 없으면 유닉스 // 윈속 초기화 WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) // 0 성공 1실패 { return 1; } //////////////////////////////// SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //SOCK_DGRAM // 3번째 인자는 그냥 무조건 0으로 쓰자 // (IPPROTO_TCP,IPPROTO_UDP) 원래는 맞게끔 넣어줘야함 //SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { return 1; } // 소켓 생성 SOCKADDR_IN addr; ZeroMemory(&addr, sizeof(addr)); addr.sin_family = AF_INET; // 무조건 고정 addr.sin_addr.s_addr = inet_addr("192.168.0.106"); addr.sin_port = htons(10000); // string에서 수치로 변환 int ret = bind(sock, (sockaddr*)&addr, sizeof(addr)); if (ret == SOCKET_ERROR) { return 1; } // 정보를 듣겠다. int ret1 = listen(sock, SOMAXCONN); if (ret1 = SOCKET_ERROR) { return 1; } SOCKET clientSock; SOCKADDR_IN clientInfo; int addlen = sizeof(clientInfo); char buffer[] = "안녕!"; while (1) { clientSock = accept(sock, (sockaddr*)&clientInfo, &addlen); //sock에는 클라이언트의 정보가 들어가 있다 if (clientSock == INVALID_SOCKET) { break; } printf("\n%s,%d", inet_ntoa(clientInfo.sin_addr), // 32비트라는 수치를 string으로 변환 ntohs(clientInfo.sin_port)); g_userList.push_back(clientSock); while (1) { send(clientSock, buffer, sizeof(buffer), 0); char buffer2[256] = { 0 }; ret = recv(clientSock, buffer2, sizeof(buffer2), 0); if (ret == 0) { printf("\n정상 종료%s,%d 나갔습니다.", inet_ntoa(clientInfo.sin_addr), ntohs(clientInfo.sin_port)); break; } if (ret<0) { printf("\n비정상종료 %s,%d 나갔습니다.", inet_ntoa(clientInfo.sin_addr), ntohs(clientInfo.sin_port)); break; } printf("\n정상 종료[%s]%s,%d 받았습니다.", buffer2, inet_ntoa(clientInfo.sin_addr), ntohs(clientInfo.sin_port)); std::cout << buffer2; for (int iUser = 0; iUser < g_userList.size(); iUser++) { send(g_userList[iUser], buffer2, sizeof(buffer2), 0); } } //closesocket(clientSock); } //closesocket(sock); // 윈속 닫기 WSACleanup(); std::cout << "HELLO World!\n"; }<file_sep>#include "SChatSvr.h" #include "SServerIOCP.h" #include "SDebugString.h" #include "SLock.h" #include "TStd.h" #include "SServer.h" bool SChatSvr::AddUser(SOCKET socket, SOCKADDR_IN address) { { SLock Lock(this); SChatUser* pUser = NULL; SAFE_NEW(pUser, SChatUser); pUser->m_Socket = socket; pUser->m_UserAddress = address; I_Debug.Print("IP = %s,PORT =%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port)); if (pUser) { I_Server.SendMsg(pUser->m_Socket, "어서오세요!", PACKET_CHAR_NAME_REQ); m_UserList.push_back(pUser); I_ServerIOCP.AddHandleToIOCP((HANDLE)socket, (ULONG_PTR)pUser); pUser->Create(); } } return true; } void SChatSvr::DeleteUser(SOCKET socket) { { SLock Lock(this); list<SChatUser*>::iterator iter; list<SChatUser*>::iterator DelUser; int iClientUser = I_Server.m_UserList.size(); for (iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++) { SChatUser* pUser = (SChatUser*)*iter; if (pUser->m_Socket == socket) { char buffer[256] = { 0, }; sprintf_s(buffer, "%s%s", pUser->m_szName.c_str(), "님이 종료하셧습니다."); I_Debug.Print("%s%s", pUser->m_szName.c_str(), "님이 종료하셧습니다."); I_Server.Broadcastting(buffer, PACKET_CHAR_MSG, pUser->m_Socket); closesocket(pUser->m_Socket); DelUser = iter; SAFE_DEL(pUser); break; } } I_Server.m_UserList.erase(DelUser); } } void SChatSvr::DeleteUser(SChatUser* pDeleteUser) { { SLock Lock(this); list<SChatUser*>::iterator iter; list<SChatUser*>::iterator DelUser; int iClientUser = (int)I_Server.m_UserList.size(); for (iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++) { SChatUser* pUser = (SChatUser*)*iter; if (pUser == pDeleteUser) { char buffer[256] = { 0, }; sprintf_s(buffer, "%s%s", pUser->m_szName.c_str(), "님이 종료하셧습니다."); I_Debug.Print("%s%s", pUser->m_szName.c_str(), "님이 종료하셧습니다."); I_Server.Broadcastting(buffer, PACKET_CHAR_MSG, pUser->m_Socket); closesocket(pUser->m_Socket); DelUser = iter; SAFE_DEL(pUser); break; } } I_Server.m_UserList.erase(DelUser); } } void SChatSvr::Broadcastting(char * msg, WORD code, SOCKET SendSocket) { { SLock Lock(this); list<SChatUser*>::iterator iter; list<SChatUser*>::iterator DelUser; int iClientUser = (int)I_Server.m_UserList.size(); for (iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++) { SChatUser*pUser = (SChatUser*)*iter; if (0 == SendSocket || pUser->m_Socket != SendSocket) { if (!SendMsg(pUser->m_Socket, msg, code)) { I_Debug.T_ERROR(false); continue; } } I_Debug.Print("%s%s%s", pUser->m_szName.c_str(), msg, "보냈습니다."); } } } void SChatSvr::Broadcastting(UPACKET* pPacket, SOCKET pSendUser) { { SLock Lock(this); list<SChatUser*>::iterator iter; list<SChatUser*>::iterator DelUser; int iClientUser = (int)I_Server.m_UserList.size(); for (iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++) { SChatUser* pUser = (SChatUser*)*iter; int iRet = send(pUser->m_Socket, (char*)pPacket, pPacket->ph.len, 0); if (iRet < 0) { I_Debug.T_ERROR(false); continue; } I_Debug.Print("%s 를 보냈습니다.", pPacket->msg); } } } void SChatSvr::Broadcastting(S_PACKET* pUserData) { { SLock Lock(this); list<SChatUser*>::iterator iter; list<SChatUser*>::iterator DelUser; UPACKET* pPacket = &pUserData->packet; //DWORD dwSendByte; int iClientUser =(int)I_Server.m_UserList.size(); for (iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++) { SChatUser* pUser = (SChatUser*)*iter; if (pUser->m_Socket != pUserData->pUser->m_Socket) { int iRet = send(pUser->m_Socket, (char*)&pUserData->packet, pUserData->packet.ph.len, 0); if (iRet < 0) { I_Debug.T_ERROR(false); continue; } } I_Debug.Print("%s에게 %s를 보냈습니다.", pUser->m_szName.c_str(), pUserData->packet.msg); } } } bool SChatSvr::Init() { I_Debug.Print("%s", "채팅 서버"); SServer::Init(); m_Acceptor.Set(10000, NULL); return true; } bool SChatSvr::Release() { return SServer::Release(); } bool SChatSvr::Run() { while (m_bStarted) { m_PacketPool.ProcessPacket(); Sleep(10); } return true; } SChatSvr::SChatSvr(void) { } SChatSvr::~SChatSvr(void) { } <file_sep>#include<stdio.h> void main() { int sum = 0; int iCount = 1; int max = 0; scanf_s("%d", &max); while (iCount <= max) { sum = sum + iCount; iCount++; } printf("%d", sum); } <file_sep>#include<stdio.h> void main() { int sum = 0; int sum1 = 0; int max = 0; int iCount = 1; scanf_s("%d", &max); do { if (iCount % 2 == 0) { sum = sum + iCount++; } else { sum1 = sum1 + iCount++; } } while (iCount <= max); printf("1~n개까지의 짝수의 합:%d\n", sum); printf("1~n개까지의 홀수의 합:%d\n", sum1); printf("1~n개까지의 짝수 홀수의 합은:%d\n", sum + sum1); }<file_sep>// UI_INTERFACE.cpp: 구현 파일 // #include "stdafx.h" #include "UI_TOOL.h" #include "UI_INTERFACE.h" #include "afxdialogex.h" // UI_INTERFACE 대화 상자 IMPLEMENT_DYNAMIC(UI_INTERFACE, CDialog) UI_INTERFACE::UI_INTERFACE(CWnd* pParent /*=nullptr*/) : CDialog(IDD_INTERFACE, pParent) { } UI_INTERFACE::~UI_INTERFACE() { } void UI_INTERFACE::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(UI_INTERFACE, CDialog) ON_WM_SIZE() //ON_BN_CLICKED(IDC_BUTTON5, &UI_INTERFACE::OnBnClickedButton5) END_MESSAGE_MAP() // UI_INTERFACE 메시지 처리기 void UI_INTERFACE::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); CWnd* pCtl = GetDlgItem(IDD_INTERFACE); // TODO: 여기에 메시지 처리기 코드를 추가합니다. if (!pCtl) { return; } CRect rect; pCtl->GetWindowRect(&rect); ScreenToClient(&rect); pCtl->MoveWindow(rect.left, rect.top, cx - 2 * rect.left, cy - rect.top - rect.left, TRUE); return; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> //Æ÷ÀÎÅÍ //void main() //{ // int var = 1; // int *ptr; // ptr = &var; // // printf("Direct,var=%d\n", var); // printf("Indirect,var=%d\n", *ptr); // printf("The address of var=%d", &var); // printf("The address of var=%d", ptr); //} //void main() //{ // int Var1; // int Var2; // int *pVar = &Var1; // // *pVar = 10; // printf("%d\n", Var1); // // Var2 = *pVar; // printf("%d\n", Var2); // // pVar = &Var2; // *pVar = 5; // printf("%d\n", Var2); //} //void main() //{ // int p=3; // int q=2; // // printf("\n*p==%d, *q==%d\n", p,q); // printf("\n*p==%p, *q==%p\n", p,q); // printf("\n*p==%p, *q==%p\n", &p, &q); //} //void main() //{ // int *p; // int *q; // int a = 1; // int b = 2; // p = &a; // q = &b; // // printf("\n&a==%p, a==%d, &b==%p, b==%d", &a, a, &b, b); // printf("\np==%p,*p==%d,q==%p,*q==%d\n",p,*p,q,*q); // //} void main() { int a = 1; int b = 3; int *p; int *q; p = &a; q = &b; printf("\n*p=%d,*q=%d\n", *p, *q); call_ref(p, q); printf("\n *p=%d,*q=%d", *p, *q); } call_ref(int *x, int *y) { *x = 3; *y = 5; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void swap(int *a, int *b)// 함수 { int j = *a; int k = *b; *a = k; *b = j; } void main() // 메인 함수 { int a = 3; int b = 5; swap(&a,&b); printf("%d,%d", a, b); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <conio.h> void main() { int *pPointArray = (int*)malloc(sizeof(int) * 10); for (int iCnt = 0; iCnt < 10; iCnt++) { pPointArray[iCnt] = iCnt * 10; printf("\n0x%08x¹øÁö: %d", pPointArray[iCnt], *(pPointArray + iCnt)); } free(pPointArray); } <file_sep>#include "SWorkThread.h" #include "SServerIOCP.h" #include "SUser.h" bool SWorkThread::Run() { DWORD dwTransfer; ULONG_PTR keyValue; LPOVERLAPPED overlapped; BOOL rReturn; while (1) { rReturn = ::GetQueuedCompletionStatus( I_ServerIOCP.m_hIOCP, &dwTransfer, &keyValue, &overlapped, INFINITE); SUser* pUser = (SUser*)keyValue; if (rReturn == TRUE) { if (dwTransfer == 0) { // 유저 삭제 처리 pUser->DeleteUser(); } if (dwTransfer != 0 && overlapped != 0) { pUser->Dispatch(dwTransfer, overlapped); } } else { // 한개의 소켓으로 보내고 받고 할 경우에 발생 if (GetLastError() != ERROR_OPERATION_ABORTED) { if (dwTransfer == 0) { // 유저 삭제 처리 pUser->DeleteUser(pUser->m_Socket); } } } } return true; } SWorkThread::SWorkThread(void) { } SWorkThread::~SWorkThread(void) { } <file_sep>#include "TQueue.h" int TQueue::Get() { if (m_iFront == m_iNear) { std::cout << "under flow" << std::endl; } int iValue = m_iQueueArray[m_iFront]; m_iQueueArray[m_iFront]=-1; m_iFront = ++m_iFront % g_iMaxQueue; return iValue; } int TQueue::put(int iData) { if ((m_iNear+1) % g_iMaxQueue==m_iFront) { std::cout << "over flow" << std::endl; return -1; } m_iQueueArray[m_iNear] = iData; m_iNear = ++m_iNear % g_iMaxQueue; } void TQueue::Show() { } TQueue::TQueue() : m_iFront(0),m_iNear(0) { } TQueue::~TQueue() { } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<conio.h> // 파일을 읽어들여 16진수와 문자로 출력한다. void DrawHexAscii(char*file) { unsigned char munja[10]; int i, j, n = 0; FILE * fp; fp = fopen(file, "rb"); if (fp == NULL) { puts("n파일이 존재하지 않습니다."); return; } while (!feof(fp)) { printf("\n%05d : ", ftell(fp)); for (i = 0; i < 10; i++) { munja[i] = fgetc(fp); printf("%02x", munja[i]); if (feof(fp))break; } printf(" "); for (j = 0; j < i; j++) { if (munja[j] == '\t' || munja[j] == '\n' || munja[j] == '\r') { munja[j] = '.'; } putchar(munja[j]); } n++; if (n % 20 == 0) { puts("\n< 아무키나 누르세요>\n"), _getch(); } } } // 파일을 로딩하여 역순으로 출력한다 void DrawInverse(char* file) { FILE *fp; fp = fopen(file, "rb"); if (fp == NULL) { puts("n파일이 존재하지 않습니다."); return; } fseek(fp, 0, SEEK_END); int iSize = ftell(fp); printf("%d, %s\n", iSize, "바이트 입니다."); fseek(fp, 0, SEEK_SET); int n = 0; do { char *munja = 0; munja = (char*)calloc(256, sizeof(char)); int i, j; for (i = 0; i < 256; i++) { if (!feof(fp)) { munja[i] = fgetc(fp); } else { free(munja); return; } //int iCnt =fsek(fp,2,SEEK_SUR); if (munja[i] == '\n' || ftell(fp) <= 0) { break; } } for (j = i; j > 0; j--) { putchar(munja[j]); } n++; free(munja); if (n % 20 == 0) { puts("\n< 아무키나 누르세요>\n"), _getch(); } } while (!feof(fp)); } void main(int argc, char *argv[]) { if (argc != 3) { printf("\n 사용법 : fileof.exe filePath 0(Inverse) or 1(Hex)\n"); return; } int iValue = atoi(argv[2]); if (iValue == 1) { DrawHexAscii(argv[1]); } else { DrawInverse(argv[1]); } _getch(); }<file_sep>#include "S_Time.h" int g_iFPS; float g_fSecPerFrame; float g_fAccumulation; bool S_Time::Init() { m_dwBeforeTick = timeGetTime(); ZeroMemory(m_csBuffer, sizeof(TCHAR)* MAX_PATH); return true; }; bool S_Time::Frame() { //(winmm.lib) ==> timeGetTime을 사용하기 위해서 포함하는 Lib파일 DWORD dwCurrentTick = timeGetTime(); DWORD dwElapseTick = dwCurrentTick - m_dwBeforeTick; g_fSecPerFrame = m_fSecondperFrame = dwElapseTick / 1000.0f; g_fAccumulation = m_fAccumulation += m_fSecondperFrame; m_fFrameTime += m_fSecondperFrame; if (m_fFrameTime > 1.0f) { g_iFPS = m_iFPS = m_dwFrameCnt; m_dwFrameCnt = 0; m_fFrameTime -= 1.0f; } m_dwFrameCnt++; m_dwBeforeTick = dwCurrentTick; return true; }; bool S_Time::Render() { _stprintf_s( m_csBuffer, L"Timer:[%10.4f] FPS:[%d] %10.4f\n", m_fAccumulation, m_iFPS, m_fSecondperFrame); return true; }; bool S_Time::Release() { return true; } S_Time::S_Time() { m_iFPS = 0; m_dwFrameCnt = 0; m_fSecondperFrame = 0.0f; m_fAccumulation = 0.0f; m_fFrameTime = 0.0f; } S_Time::~S_Time() { } <file_sep>#include "S_Chat_Svr.h" #include "S_IOCP.h" #include "S_DebugString.h" bool S_Chat_Svr::AddUser(SOCKET socket, SOCKADDR_IN address) { { S_Lock Lock(this); S_ChatUser* pUser = NULL; SAFE_NEW(pUser, S_ChatUser); pUser->m_Socket = socket; pUser->m_UserAddr = address; S_Debug.Print("IP=%s, PORT=%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port)); if (pUser) { S_CHAT.SendMsg(pUser->m_Socket, "어서오세요! 채팅을 입력해주세요", PACEKT_CHAT_NAME_REQ); m_UserList.push_back(pUser); S_iocp.AddhandleToIOCP((HANDLE)socket, (ULONG_PTR)pUser); pUser->Create(); } } return true; } void S_Chat_Svr::DeleteUser(SOCKET socket) { { S_Lock Lock(this); list<S_ChatUser*>::iterator iter; list<S_ChatUser*>::iterator delUser; int iClientUser = (int)S_CHAT.m_UserList.size(); for (iter = S_CHAT.m_UserList.begin(); iter != S_CHAT.m_UserList.end(); iter++) { S_ChatUser* pUser=(S_ChatUser*)*iter; if (pUser->m_Socket = socket) { char buffer[256] = { 0, }; sprintf_s(buffer, "%s,%s", pUser->m_szname.c_str(), "님이 나가셧습니다."); S_Debug.Print("%s,%s", pUser->m_szname.c_str(), "님이 나가셧습니다."); S_CHAT.Broadcastting(buffer, PACKET_CHAT_MSG, pUser->m_Socket); closesocket(pUser->m_Socket); delUser = iter; SAFE_DELETE(pUser); break; } } S_CHAT.m_UserList.erase(delUser); } } void S_Chat_Svr::DeleteUser(S_ChatUser* pDeleteUser) { S_Lock Lock(this); list<S_ChatUser*>::iterator iter; list<S_ChatUser*>::iterator delUser; int iClientUser = (int)S_CHAT.m_UserList.size(); for (iter = S_CHAT.m_UserList.begin(); iter != S_CHAT.m_UserList.end(); iter++) { S_ChatUser* pUser = (S_ChatUser*)*iter; if (pUser == pDeleteUser) { char buffer[256] = { 0, }; sprintf_s(buffer, "%s,%s", pUser->m_szname.c_str(), "님이 나가셧습니다."); S_Debug.Print("%s,%s", pUser->m_szname.c_str(), "님이 나가셧습니다."); S_CHAT.Broadcastting(buffer, PACKET_CHAT_MSG, pUser->m_Socket); closesocket(pUser->m_Socket); delUser = iter; SAFE_DELETE(pUser); break; } S_CHAT.m_UserList.erase(delUser); } } void S_Chat_Svr::Broadcastting(UPACKET* pPacket, SOCKET pSendUser) { { S_Lock Lock(this); list<S_ChatUser*>::iterator iter; list<S_ChatUser*>::iterator delUser; int iClientUser = (int)S_CHAT.m_UserList.size(); for (iter = S_CHAT.m_UserList.begin(); iter != S_CHAT.m_UserList.end(); iter++) { S_ChatUser* pUser = (S_ChatUser*)*iter; { int iRet = send(pUser->m_Socket, (char*)pPacket, pPacket->ph.len, 0); if (iRet < 0) { S_Debug.S_Error(false); continue; } } S_Debug.Print("%s 에게 %s 보냈습니다.", pUser->m_szname.c_str(), pPacket->msg); } } } void S_Chat_Svr::Broadcastting(PACKET* pUserData) { { S_Lock Lock(this); list<S_ChatUser*>::iterator iter; list<S_ChatUser*>::iterator delUser; UPACKET* pPacket = &pUserData->packet; int iClientUser = (int)S_CHAT.m_UserList.size(); for (iter = S_CHAT.m_UserList.begin(); iter != S_CHAT.m_UserList.end(); iter++) { S_ChatUser* pUser = (S_ChatUser*)*iter; if (pUser->m_Socket != pUserData->pUser->m_Socket) { int iRet = send(pUser->m_Socket, (char*)&pUserData->packet, pUserData->packet.ph.len, 0); if (iRet < 0) { S_Debug.S_Error(false); continue; } } S_Debug.Print("%s 에게 %s 님의 %s 보냈습니다.", pUser->m_szname.c_str(), pUserData->pUser->m_szname.c_str(), pUserData->packet.msg); } } } void S_Chat_Svr::Broadcastting(char* msg, WORD code, SOCKET SendSocket) { { S_Lock Lock(this); list<S_ChatUser*>::iterator iter; list<S_ChatUser*>::iterator delUser; int iClientUser = (int)S_CHAT.m_UserList.size(); for (iter = S_CHAT.m_UserList.begin(); iter != S_CHAT.m_UserList.end(); iter++) { S_ChatUser* pUser = (S_ChatUser*)*iter; if (0 == SendSocket || pUser->m_Socket != SendSocket) { if (!SendMsg(pUser->m_Socket, msg, code)) { S_Debug.S_Error(false); continue; } } S_Debug.Print("%s %s %s", pUser->m_szname.c_str(), msg, "보냈습니다"); } } } bool S_Chat_Svr::Init() { S_Debug.Print("%s", "서버 시작"); S_Server::Init(); m_Acceptor.Set(10000, NULL); return true; } bool S_Chat_Svr::Release() { return S_Server::Release(); } bool S_Chat_Svr::Run() { while (m_bStarted) { m_PacketPool.ProcessPacket(); Sleep(10); } return true; } S_Chat_Svr::S_Chat_Svr() { } S_Chat_Svr::~S_Chat_Svr() { } <file_sep>#include "sWrite.h" bool sWrite::Set(HWND hWnd, int iWidth, int iHeight, IDXGISurface* pSurface) { CreateDeviceIndependentResources(); CreateDeviceResources(pSurface); return true; } HRESULT sWrite::CreateDeviceIndependentResources() { HRESULT hr; if (FAILED(hr = D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pd2dFactory))) { return hr; } if (FAILED(hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown **)&m_pWriteFactory))) { return hr; } if (FAILED(hr = m_pWriteFactory->CreateTextFormat( L"ΈνΑ¶", NULL, DWRITE_FONT_WEIGHT_BOLD, // WEIGHT DWRITE_FONT_STYLE_OBLIQUE, // STYLE DWRITE_FONT_STRETCH_EXTRA_EXPANDED, //STRETCH 20, L"ko-kr",//L"un-us",//L"ko-kr", &m_pTextFormat))) { return hr; } return hr; } HRESULT sWrite::CreateDeviceResources(IDXGISurface* pSurface) { HRESULT hr; D2D1_PIXEL_FORMAT pf; pf.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; pf.format = DXGI_FORMAT_UNKNOWN; m_pd2dFactory->GetDesktopDpi(&m_fdpiX, &m_fdpiY); // 800 * ppi * 96.0f; // 600 * ppi * 96.0f; D2D1_RENDER_TARGET_PROPERTIES rtp; rtp.type = D2D1_RENDER_TARGET_TYPE_DEFAULT; rtp.pixelFormat = pf; rtp.dpiX = m_fdpiX; rtp.dpiY = m_fdpiY; rtp.usage = D2D1_RENDER_TARGET_USAGE_NONE; rtp.minLevel = D2D1_FEATURE_LEVEL_DEFAULT; if (FAILED(hr = m_pd2dFactory->CreateDxgiSurfaceRenderTarget(pSurface, &rtp, &m_pRT))) { return hr; } D2D1::ColorF color(D2D1::ColorF::Yellow); if (FAILED(hr = m_pRT->CreateSolidColorBrush( color, &m_pColorBrush))) { return hr; } return hr; } HRESULT sWrite::DrawText(RECT rt, const TCHAR* pText, D2D1::ColorF color) { m_pRT->BeginDraw(); //D2D1::Matrix3x2F matWorld; //D2D1_POINT_2F center; //center.x = 400; //center.y = 300; //float fScale = (cosf(g_fGameTimer)*0.5f + 0.5f) * 10; //D2D1::Matrix3x2F scale = matWorld.Scale(fScale, fScale, center); //D2D1::Matrix3x2F rot = matWorld.Rotation(g_fGameTimer*100,center); //rot = scale * rot; m_pRT->SetTransform(m_matWorld);// D2D1::IdentityMatrix() ); D2D1_RECT_F rf = D2D1::RectF(rt.left, rt.top, rt.right, rt.bottom); m_pColorBrush->SetColor(color); m_pRT->DrawText(pText, wcslen(pText), m_pTextFormat, rf, m_pColorBrush); m_pRT->EndDraw(); return S_OK; } bool sWrite::Render() { m_pRT->BeginDraw(); for (int iText = 0; iText < m_TextList.size(); iText++) { m_pRT->SetTransform(m_TextList[iText].matWorld);// D2D1::IdentityMatrix()); D2D1_RECT_F rf = m_TextList[iText].rf; rf.top += iText * 30.0f; m_pColorBrush->SetColor(m_TextList[iText].color); m_pRT->DrawText(m_TextList[iText].pText.c_str(), m_TextList[iText].pText.size(), m_pTextFormat, rf, m_pColorBrush); } m_pRT->EndDraw(); return true; } void sWrite::OnResize(int iWidth, int iHeight, IDXGISurface* pSurface) { DiscardDeviceResources(); CreateDeviceResources(pSurface); } void sWrite::DiscardDeviceResources() { if (m_pColorBrush)m_pColorBrush->Release(); if (m_pRT)m_pRT->Release(); m_pRT = nullptr; } bool sWrite::Init() { return true; } bool sWrite::Frame() { return true; } bool sWrite::Release() { DiscardDeviceResources(); if (m_pTextFormat)m_pTextFormat->Release(); if (m_pWriteFactory)m_pWriteFactory->Release(); if (m_pd2dFactory)m_pd2dFactory->Release(); m_pWriteFactory = nullptr; m_pd2dFactory = nullptr; return true; } sWrite::sWrite() { m_matWorld = m_matWorld.Identity(); } sWrite::~sWrite() { } <file_sep>#pragma once #include "S_WorkThread.h" #include "S_SvrUser.h" class S_IOCP : public S_SvrObj,public Singleton<S_IOCP> { private: friend class Singleton<S_IOCP>; public: HANDLE m_hIOCP; S_WorkThread m_WorkThread[3]; public: bool Init(); bool Run(); bool Release(); void AddhandleToIOCP(HANDLE hClientSocket, ULONG_PTR dwReturnkey); public: S_IOCP(); virtual ~S_IOCP(); }; #define S_iocp S_IOCP::GetInstance() <file_sep>#pragma once #include "Header.h" #include "TemplateMap.h" #define CTL_CHARS 31 #define SINGLE_QUOTE 39 #define ALMOST_ZERO 1.0e-3f typedef struct _D3D_MATRIX { union { struct { float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; float m[4][4]; }; }D3D_MATRIX, *LPD3D_MATRIX; typedef class Matrix3 *LPMATRIX3; struct P3NCVERTEX { float Px, Py, Pz; float Nx, Ny, Nz; Point4 c; }; struct PNCT_VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; }; const enum OBJECTCLASSTYPE { CLASS_GEOM = 0, CLASS_BONE, CLASS_DUMMY, CLASS_BIPED, }; struct STri { PNCT_VERTEX v[3]; int iSubIndex; }; struct SScene { int iVersion; // 파일 버전 int iFirstFrame; // 시작 프레임 int iLastFrame; // 마지막 프레임 int iFrameSpeed; // 1초당 프레임 개수(30) int iTickPerFrame; // 1프레임의 틱 값(160) int iNumMesh; // 메쉬 오브젝트 개수 int iMaxweight; // 정점 당 가중치 int iBindPose; // 바인딩 포즈 애니메이션 여부 }; struct STexMap { int iIndex; int iType; // 텍스쳐 타입 인덱스 TSTR StrTextureName; // 텍스쳐 이름 }; struct SMtl { int iIndex; int iNumSubMtl; // 서브 매터리얼 개수 int iNumMap; // 텍스쳐 맵 개수 TSTR strName; // 매터리얼 이름 TSTR strClassName; // 맵클래스 이름 vector<STexMap> TexMaps; // 맵 타이틀 vector<SMtl> SubMaterial; // 서브 매터리얼 저장 벡터 }; struct SAnimTrack { int iType; int iTick; Quat qValue; Point3 vValue; }; struct SMESH_HEADER { OBJECTCLASSTYPE m_ClassType; Box3 m_Box; D3D_MATRIX m_matWorld; int m_iNumVertex; int m_iNumFace; int m_iMtrlRef; int m_iNumTrack[4]; }; struct SMesh : public SMESH_HEADER { TSTR m_strNodeName; TSTR m_strParentName; vector<SAnimTrack> m_PosTrack; vector<SAnimTrack> m_RotTrack; vector<SAnimTrack> m_SclTrack; vector<SAnimTrack> m_VisTrack; vector<STri> m_TriList; vector<SMesh*> m_pSubMesh; SMesh() { m_iMtrlRef = -1; m_iNumFace = 0; m_iNumTrack[0] = 0; m_iNumTrack[1] = 0; m_iNumTrack[2] = 0; m_iNumTrack[3] = 0; m_ClassType = CLASS_GEOM; }; ~SMesh() { m_PosTrack.clear(); m_RotTrack.clear(); m_SclTrack.clear(); m_VisTrack.clear(); m_TriList.clear(); }; }; struct MATRIXINDEX { OBJECTCLASSTYPE m_ClassType; int m_iIndex; // 애니메이션 행렬의 인덱스 T_STR m_szName; // 애니메이션 행렬의 이름 vector<P3NCVERTEX> m_VertexList; // 메쉬 페이스 리스트 Matrix3 m_NodeTM; Matrix3 m_InvNodeTM; INode* m_pINode; Object* m_pObj; Control* m_pControl; SMesh m_sMesh; void Add(int iIndex, T_STR szName) { m_pObj = NULL; m_pControl = NULL; m_iIndex = iIndex; m_szName = szName; } void SetNode(INode* pNode, int iTick, MATRIXINDEX* pParentIndex = 0) { m_pINode = pNode; m_pObj = m_pINode->GetObjectRef(); m_pControl =m_pINode->GetTMController(); m_ClassType = CLASS_GEOM; if (m_pObj && m_pObj->ClassID() == Class_ID(BONE_CLASS_ID, 0)) // 본 오브젝트 { m_ClassType = CLASS_BONE; } if (m_pObj && m_pObj->ClassID() == Class_ID(DUMMY_CLASS_ID,0)) // 더미 오브젝트 { m_ClassType = CLASS_DUMMY; } if (m_pControl->ClassID() == BIPSLAVE_CONTROL_CLASS_ID || // 루트 바이패드 제외한 모든 바이패드들 m_pControl->ClassID() == BIPBODY_CONTROL_CLASS_ID) // 루트 바이패드 1개 { m_ClassType = CLASS_BIPED; } m_NodeTM = pNode->GetNodeTM(iTick); m_InvNodeTM = Inverse(m_NodeTM); } void Release() { for (int iSub = 0; iSub < m_sMesh.m_pSubMesh.size(); iSub++) { SAFE_DEL(m_sMesh.m_pSubMesh[iSub]); } m_sMesh.m_pSubMesh.clear(); }; }; class S_KHJ_Global { public: Interface* m_p3dsMax; // 맥스 인터페이스 INode* m_pRootNode; Interval m_Interval; // 프레임 정보 SScene m_Scene; // 씬 정보 저장 TTemplateMap<MATRIXINDEX> m_MatrixMap; vector<Mtl*> m_pMtlList; // 매터리얼 리스트 vector<SMtl> m_Material; // 출력 할 정보 리스트 TSTR m_CurtFileName; // 맥스 파일 이름 TCHAR m_tmpBuffer[MAX_PATH]; // 임시 버퍼 public: bool CheckFile(Interface* pMax); bool Initialize(Interface* p3dsMax = NULL,TSTR name); void PreProcess(INode* pNode); void AddObject(INode* pNode); void AddMtl(INode* pNode); // 중복되지 않고 매터리얼 추가 int GetMtlref(Mtl* pMtl); // pMtl이 저장된 인덱스를 반환한다. void SetBindPose(bool bBindPose = false) { m_Scene.iBindPose = bBindPose; } int GetIndex(const TCHAR* strNodeName); public: void DumpMatrix3(Matrix3* m, D3D_MATRIX& mat); void DumpPoint3(Point3& pDest, Point3& pSrc); bool TMNegParity(Matrix3 &m); bool EqualPoint2(Point2 p1, Point2 p2); bool EqualPoint3(Point3 p1, Point3 p2); bool EqualPoint4(Point4 p1, Point4 p2); TCHAR* FixupName(MSTR Name); public: S_KHJ_Global(void); virtual ~S_KHJ_Global(void); }; <file_sep>#include "SActor.h" D3DXVECTOR3 SActor::Gen(float x, float y) { D3DXVECTOR3 vRet; vRet.x = x / 800; vRet.y = y / 600; vRet.x = vRet.x*2.0f - 1.0f; vRet.y = (vRet.y * 2 - 1.0f)*-1.0f; return vRet; } void SActor::GenCenter() { m_vCenter.x = 0.0f; m_vCenter.y = 0.0f; for (int iV = 0; iV < 6; iV++) { D3DXVECTOR3 vertex = m_VertexList[iV].p; m_vCenter.x += vertex.x; m_vCenter.y += vertex.y; } m_vCenter.x /= 6.0f; m_vCenter.y /= 6.0f; } bool SActor::Setdata(UINT left, UINT top, UINT width, UINT height) { m_rtInit.left = left; m_rtInit.right = width; m_rtInit.top = top; m_rtInit.bottom = height; SetVertexData(); return true; } void SActor::SetVertexData() { D3DXVECTOR3 pos = Gen(m_rtInit.left, m_rtInit.top); m_VertexList[0].p = D3DXVECTOR3(pos.x, pos.y, 0.0f); m_VertexList[0].t = D3DXVECTOR2(0.0f, 0.0f); m_VertexList[0].c = D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f); pos = Gen(m_rtInit.left + m_rtInit.right, m_rtInit.top); m_VertexList[1].p = D3DXVECTOR3(pos.x, pos.y, 0.0f); m_VertexList[1].t = D3DXVECTOR2(1.0f, 0.0f); m_VertexList[1].c = D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f); pos = Gen(m_rtInit.left, m_rtInit.top + m_rtInit.bottom); m_VertexList[2].p = D3DXVECTOR3(pos.x, pos.y, 0.0f); m_VertexList[2].t = D3DXVECTOR2(0.0f, 1.0f); m_VertexList[2].c = D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f); m_VertexList[3] = m_VertexList[2]; m_VertexList[4] = m_VertexList[1]; pos = Gen(m_rtInit.left + m_rtInit.right, m_rtInit.top + m_rtInit.bottom); m_VertexList[5].p = D3DXVECTOR3(pos.x, pos.y, 0.0f); m_VertexList[5].t = D3DXVECTOR2(1.0f, 1.0f); m_VertexList[5].c = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f); GenCenter(); } bool SActor ::Frame(float fGameTimer,float fFps) { return true; } bool SActor::PreRender(ID3D11DeviceContext* pContext, UINT iVertexSize) { m_dxObj.PreRender(pContext, iVertexSize); return true; } bool SActor::Render(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount) { m_dxObj.Render(pContext, iVertexSize, iCount); return true; } bool SActor::PostRender(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount) { m_dxObj.PostRender(pContext, iVertexSize, iCount); return true; } bool SActor::Init() { return true; } bool SActor::Release() { m_dxObj.Release(); return true; } SActor::SActor() { } SActor::~SActor() { } <file_sep>#pragma once #include "KHJ_Object.h" // include ->C:\Program Files(x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.11.25503\atlmfc\include // lib -> C:\Program Files(x86)\Windows Kits\10\Lib\10.0.15063.0\ucrt\x64 #define MAX_WEIGHT_BIPED 8 // 정점당 1개 씩 할당 필요 struct SBipedVertex { int m_dwNumWeight; vector<BYTE> m_BipIDList; vector<float> m_fWeightList; }; // 쉐이더 사용시 ( 가중치 4개 제한 사용) struct P3NCT3_VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; float w[4]; // w0, fw1, fw2, fNumWeight; float i[4]; // i0, i1, i2, i3 }; // 쉐이더 사용시 (가중치 8개 제한 사용) struct PNCT5_VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; float w1[4]; // w0, fw1, fw2, fw3 float i1[4]; // i0, i1, i2, i3 float w2[4]; // w4, fw5, fw6, fNumWeight; float i2[4]; // i4, i5 ,i6 ,i7 }; struct SSkinTri : public STri { PNCT5_VERTEX m_vVertex[3]; }; struct SSkinMesh :public SMesh { vector<SSkinTri> m_SkinTriList; vector<SSkinMesh*> m_pSkinSubMesh; // 텍스쳐 정보 (텍스쳐 맵 단위) int m_iNumTex; int m_iTexType[13]; TCHAR m_szTexName[13][30]; SSkinMesh() {}; virtual ~SSkinMesh() {}; }; class KHJ_SkinExp : public TSingleton<KHJ_SkinExp> { private: friend class TSingleton<KHJ_SkinExp>; public: SScene m_Scene; // 정점 가중치 리스트 typedef vector<SBipedVertex> TBIPED_VERTEX_VECTOR; TBIPED_VERTEX_VECTOR m_BipedList; // 메쉬 페이스 리스트 typedef vector<SSkinMesh*> SSKINMESH_VECTOR; SSKINMESH_VECTOR m_SkinMeshList; public: bool Init(); bool skmExport(); bool Release(); Modifier* FindModifier(INode* nodePtr, Class_ID classID); void SetBipedInfo(INode* node); void ExportPhysiqueData(INode* node, Modifier *phyMod); void ExportSkinData(INode* node, Modifier * skinMod); bool ExportMesh(FILE* fp, SSkinMesh* pMesh); void SetVertexBiped(INode* node, Face* face, int v0, int v1, int v2, SSkinTri* pTri); bool GetNodeInfo(INode* node, TimeValue t); // 서브메터리얼 사용시를 고려하여 페이스 리스트 생성 void GenerateGroup(INode* node, Mesh* mesh, SSkinMesh* pSkinMesh); void LoadMaterial(SSkinMesh* pSkinMesh, Mtl* mtl); void SetTriangle(INode* node, Mesh* mesh, SSkinMesh* pSkinMesh, SSkinMesh* pSumMesh = NULL, int iMtrl = 0); int GetMapID(Class_ID cid, int subNo); int IsEqulVertexList(vector<PNCT5_VERTEX>& VertexArray, PNCT5_VERTEX& Vertex); public: KHJ_SkinExp(void); virtual ~KHJ_SkinExp(void); }; #define I_SkinExp KHJ_SkinExp::GetInstance() <file_sep>#include "S_Input.h" bool S_Input::StayKeydown(INT iKey) { if (GetAsyncKeyState(iKey) & 0x8000) { return TRUE; } } bool S_Input::OnceKeydwon(INT iKey) { if (GetAsyncKeyState(iKey) & 0x8000) { if (m_bKeydown[iKey] == false) { m_bKeydown[iKey] = true; return TRUE; } } else { m_bKeydown[iKey] = false; } return FALSE; } bool S_Input::OnceKeyUp(INT iKey) { if (GetAsyncKeyState(iKey) & 0x8000) { m_bKeyUp[iKey] = true; } else { if (m_bKeyUp[iKey] == true) { m_bKeyUp[iKey] = false; return TRUE; } } return FALSE; } bool S_Input::Init() { ZeroMemory(m_bKeydown, MAX_ARRAY); ZeroMemory(m_bKeyUp, MAX_ARRAY); return true; } bool S_Input::Frame() { GetCursorPos(&m_ptMousePos); ScreenToClient(g_hWnd, &m_ptMousePos); return true; } bool S_Input::Render() { return true; } bool S_Input::Release() { return true; } S_Input::S_Input() { } S_Input::~S_Input() { } <file_sep>#include "sDxState.h" namespace DX { ID3D11BlendState* sDxState::g_pBSNoBlend = 0; ID3D11BlendState* sDxState::g_pBSAlphaBlend = 0; ID3D11DepthStencilState* sDxState::g_pDSVStateEnableLessEqual = 0; ID3D11DepthStencilState* sDxState::g_pDSVStateEnableGreater = 0; ID3D11DepthStencilState* sDxState::g_pDSVStateDetphWriteDisable = 0; ID3D11RasterizerState* sDxState::g_pRSWireFrame = 0; ID3D11RasterizerState* sDxState::g_pRSSolid = 0; ID3D11RasterizerState* sDxState::g_pRSBackCullSolid = 0; ID3D11RasterizerState* sDxState::g_pRSFrontCullSolid = 0; ID3D11RasterizerState* sDxState::g_pRSNoneCullSolid = 0; ID3D11RasterizerState* sDxState::g_pRSBackCullWireFrame = 0; ID3D11RasterizerState* sDxState::g_pRSFrontCullWireFrame = 0; ID3D11RasterizerState* sDxState::g_pRSNoneCullWireFrame = 0; ID3D11SamplerState* sDxState::g_pSSWrapLinear = NULL; ID3D11SamplerState* sDxState::g_pSSWrapPoint = NULL; HRESULT sDxState::SetState(ID3D11Device* pd3dDevice) { HRESULT hr; ///////////////////////// blend ////////////// D3D11_BLEND_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.RenderTarget[0].BlendEnable = TRUE; bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; pd3dDevice->CreateBlendState(&bd, &g_pBSAlphaBlend); bd.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; bd.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; hr = pd3dDevice->CreateBlendState(&bd, &g_pBSNoBlend); ///////////////////////////// D3D11_DEPTH_STENCIL_DESC dsd; ZeroMemory(&dsd, sizeof(dsd)); dsd.DepthEnable = TRUE; dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateEnableLessEqual); dsd.DepthEnable = TRUE; dsd.DepthFunc = D3D11_COMPARISON_GREATER; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateEnableGreater); dsd.DepthEnable = FALSE; dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateDetphWriteDisable); //////////////////////////////// ////////////////////////////////// D3D11_RASTERIZER_DESC rd; ZeroMemory(&rd, sizeof(rd)); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_BACK; rd.DepthClipEnable = TRUE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSWireFrame); rd.FillMode = D3D11_FILL_SOLID; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSSolid); rd.CullMode = D3D11_CULL_FRONT; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSFrontCullSolid); rd.CullMode = D3D11_CULL_BACK; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSBackCullSolid); rd.CullMode = D3D11_CULL_NONE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSNoneCullSolid); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_FRONT; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSFrontCullWireFrame); rd.CullMode = D3D11_CULL_BACK; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSBackCullWireFrame); rd.CullMode = D3D11_CULL_NONE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSNoneCullWireFrame); ////////////////////////////////// D3D11_SAMPLER_DESC descSamp; descSamp.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.MipLODBias = 0; descSamp.MaxAnisotropy = 16; descSamp.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; descSamp.ComparisonFunc = D3D11_COMPARISON_NEVER; descSamp.BorderColor[0] = 1.0f; descSamp.BorderColor[1] = 0.0f; descSamp.BorderColor[2] = 0.0f; descSamp.BorderColor[3] = 1.0f; descSamp.MinLOD = 0; descSamp.MaxLOD = D3D10_FLOAT32_MAX; pd3dDevice->CreateSamplerState(&descSamp, &g_pSSWrapLinear); descSamp.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; pd3dDevice->CreateSamplerState(&descSamp, &g_pSSWrapPoint); return hr; } bool sDxState::Release() { if (g_pDSVStateEnableLessEqual)g_pDSVStateEnableLessEqual->Release(); if (g_pDSVStateEnableGreater) g_pDSVStateEnableGreater->Release(); if (g_pRSWireFrame) g_pRSWireFrame->Release(); if (g_pRSSolid) g_pRSSolid->Release(); if (g_pRSBackCullSolid) g_pRSBackCullSolid->Release(); if (g_pRSFrontCullSolid) g_pRSFrontCullSolid->Release(); if (g_pRSNoneCullSolid) g_pRSNoneCullSolid->Release(); if (g_pRSBackCullWireFrame) g_pRSBackCullWireFrame->Release(); if (g_pRSFrontCullWireFrame) g_pRSFrontCullWireFrame->Release(); if (g_pRSNoneCullWireFrame) g_pRSNoneCullWireFrame->Release(); if (g_pBSNoBlend) g_pBSNoBlend->Release(); if (g_pBSAlphaBlend) g_pBSAlphaBlend->Release(); if (g_pSSWrapLinear) g_pSSWrapLinear->Release(); if (g_pSSWrapPoint)g_pSSWrapPoint->Release(); if (g_pDSVStateDetphWriteDisable) g_pDSVStateDetphWriteDisable->Release(); return true; } sDxState::sDxState() { } sDxState::~sDxState() { } }<file_sep>#pragma once #include "SServerObj.h" #include "SProtocol.h" #define MAX_RECV_SIZE 10000 class SUser; typedef struct { UPACKET packet; SUser* pUser; }S_PACKET, *P_SPACKET; class SStreamPacket : public SServerObj { public: list<S_PACKET> m_PacketList; typedef list<S_PACKET>::iterator m_PackItor; // 패킷 리스트를 가지고 있는다 public: UPACKET* m_pPacket; char m_RecvBuffer[MAX_RECV_SIZE]; int m_iStartPos; int m_iWritePos; int m_iReadPos; public: void Put(char* recvBuffer, int iSize, SUser* = NULL); public: SStreamPacket(); virtual ~SStreamPacket(); }; <file_sep>#include<stdio.h> #include<conio.h> void main() { int a = 10; if (a == 10) { printf("a=10\n"); } if (a) { printf("A=Ture\n"); } if (!a) { printf("A=False"); } } <file_sep>#include <iostream> class ImageWork {}; class Image {}; class ImageLoad {}; class ImageResult {}; // 핸들링 class FacadeHandler //Facade 역할 { public: void DoWork(ImageWork& image, ImageResult& result) { m_Image = ImageLoad(image.m_szName); //흑백 명암을 변경해라 result = ImageWork.DoWork(m_Image); } private: Image m_Image; }; void main() { ImageWork image("aaa.bmp",blank); ImageResult result; FacadeHandler work; work.DoWork(image,result); }<file_sep>#ifndef ITEM_H #define ITEM_H #include <iostream> #include <string> using namespace std; class Item { public: Item(string str) :data_(str) { } string data_; }; #endif <file_sep>//연산자 오버로딩 #include "Tpoint.h" void(Tpoint:: *fp)(); void Execute(Tpoint* the) { if (fp != NULL) { (the->*fp)(); } } int main(void) { Tpoint p1(0, 0), p2, p3, p4; p2 = ++p1; p1.Show(); p2.Show(); p1->Show(); (*p1).Show(); Tpoint* pData = new Tpoint(); pData->Show(); p3 = p1++; p1.Show(); p3.Show(); p4 = p1 + p2; p4.Show(); Tpoint p5(10, 20), p6, p7, p8; p6 = p5 * 2; p6.Show(); p6 = 2 * p5; p6.Show(); p7 = p5 / 2; p7.Show(); p8 = 2 / p5; p8.Show(); p5 += p4; p5.Show(); p6 -= p5; p6.Show(); p5 *= 2; p5.Show(); p6 /= 2; p6.Show(); p5 *= p4; p5.Show(); p6 /= p4; p6.Show(); if (p5 == p6)cout << "같다."; if (p5 != p6)cout << "다르다."; cout << p6[0] << endl; cout << p6[1] << endl; Tpoint a, b, c; cout << "첫번째 입력: "; cin >> a; cout << "두번쨰 입력:"; cin >> b; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a+b = " << a + b << endl; cout << "a-b = " << a - b << endl; cout << "a*b = " << a * b << endl; cout << "a/b = " << a / b << endl; Tpoint* d = new Tpoint(); d->SetPosition(10, 10); cout << *d; fp = &Tpoint::Show; Execute(d); d->m_fp = &Tpoint::Show; (*d) > &a; d->Execute(); delete d; return 0; }<file_sep>#pragma once #include "sWindow.h" #include "sTimer.h" #include "sInput.h" #include "sDxState.h" #include "sWrite.h" #include "xSkyBox.h" #include "xModelView.h" using namespace DX; class sCore : public sWindow { public: xSkyBox m_SkyBox; sTimer m_Timer; sWrite m_Font; xCamera m_DefaultCamera; xModelView m_ModelCamera; xCamera* m_pMainCamera; xDirLineShape m_dirAxis; public: virtual bool GamePreInit(); bool GameInit(); bool GameRun(); bool GameRelease(); bool GameFrame(); bool GameRender(); bool GamePreRender(); bool GamePostRender(); void DeleteDeviceResources(); HRESULT CreateDeviceResources(UINT width, UINT height); virtual void DeleteResources() {}; virtual HRESULT CreateResources(UINT width, UINT height) { return S_OK; } public: virtual bool Init() { return true; } virtual bool Frame() { return true; } virtual bool Render() { return true; } virtual bool PreRender() { return true; } virtual bool PostRender() { return true; } virtual bool Release() { return true; } LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: void SwapDefaultView(); void SwapModelView(); public: sCore(); virtual ~sCore(); };<file_sep>#pragma once #include "xCore.h" #include "S_HeroObj.h" class S_Viewer : public xCore { public: shared_ptr<xCamera> m_pMainCamera; D3DXMATRIX m_matWorld; vector<shared_ptr<S_HeroObj>> m_HeroObj; public: bool Init(); bool Frame(); bool Render(); bool Release(); HRESULT CreateResource(); HRESULT DeleteResource(); public: S_Viewer(void); virtual ~S_Viewer(void); }; <file_sep>#include "TWorkThread.h" #include "TServerIOCP.h" #include "TUser.h" bool TWorkThread::Run() { DWORD dwTransfer; ULONG_PTR keyValue; LPOVERLAPPED overlapped; BOOL rReturn; while(1) { rReturn = ::GetQueuedCompletionStatus( I_ServerIOCP.m_hIOCP, &dwTransfer, &keyValue, &overlapped, INFINITE ); TUser* pUser = (TUser*)keyValue; if( rReturn == TRUE ) { if( dwTransfer == 0 ) { // 유저 삭제 처리 pUser->DeleteUser(); } if( dwTransfer != 0 && overlapped != 0) { pUser->Dispatch(dwTransfer,overlapped); } }else { // 한개의 소켓으로 보내고 받고 할 경우에 발생 if( GetLastError() != ERROR_OPERATION_ABORTED ) { if( dwTransfer == 0 ) { // 유저 삭제 처리 pUser->DeleteUser(pUser->m_Socket); } } } } return true; } TWorkThread::TWorkThread(void) { } TWorkThread::~TWorkThread(void) { } <file_sep>#pragma once #include "SThread.h" #include "SAcceptor.h" #include "SStreamPacket.h" #include "SUser.h" class SServer : public SThread { public: SAcceptor m_Acceptor; public: bool Init(); bool Release(); bool Run(); virtual bool AddUser(SOCKET socket, SOCKADDR_IN address); bool SendMsg(SOCKET socket, const char* msg, WORD code); public: SServer(void); virtual ~SServer(void); }; <file_sep>#pragma once #include "sDevice.h" class sWindow : public sDevice { public: HWND m_hWnd; HINSTANCE m_hInstance; RECT m_rtClient; RECT m_rtWindow; public: DWORD m_dwStyle; public: void Set(DWORD dwStyle); void CenterWindow(); bool SetWindow(HINSTANCE hInstance, const TCHAR* pTitleName = L"KHJ", UINT iWidth = 800, UINT iHeight = 600); bool Run(); public: virtual LRESULT MainMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); virtual LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); virtual bool GameInit(); virtual bool GameRun(); virtual bool GameRelease(); void MsgEvent(MSG msg); public: sWindow(); virtual ~sWindow(); }; <file_sep>#include "S_Std.h" typedef struct _OVERLAPPEDEX : OVERLAPPED { enum {MODE_RECV = 0 , MODE_SEND = 1}; int i_Flags; _OVERLAPPEDEX() { i_Flags = MODE_RECV; } }OVERLAPPEDEX; template <class S> class Singleton { public: static S& GetInstance() { static S theSingleInstance; return theSingleInstance; } }; #define MAX_ARRAY 256 #define SAFE_NEW(A, B) { if (!A) A = new B; } #define SAFE_DELETE(p) if(p){delete p; p = NULL;} #define PACKETBUFFERSIZE 8192 #define MAX_RECV 10000 extern HWND g_hWnd;<file_sep>#pragma once #include "xDevice.h" class xWindow : public xDevice { public: HWND m_hWnd; HINSTANCE m_hInstance; RECT m_rtClient; RECT m_rtWindow; private: DWORD m_dwStyle; public: void Set(DWORD dwStyle); void CenterWindow(); bool SetWindow(HINSTANCE hInstance, const TCHAR* pTitleName = L"KGCA Sample", UINT iWidth = 800, UINT iHeight = 600); bool Run(); public: virtual LRESULT MainMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); virtual LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); virtual bool GameInit(); virtual bool GameRun(); virtual bool GameRelease(); void MsgEvent(MSG msg); public: xWindow(); virtual ~xWindow(); }; <file_sep>#include "xShape.h" void xShape::SetColor(D3DXVECTOR4 vColor) { m_cbData.vColor = vColor; } void xShape::SetMatrix( D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj) { if (pWorld != NULL) { m_matWorld = *pWorld; } if (pView != NULL) { m_matView = *pView; } if (pProj != NULL) { m_matProj = *pProj; } D3DXMatrixInverse(&m_cbData.matInvWorld, NULL, &m_matWorld); D3DXMatrixTranspose(&m_cbData.matInvWorld,&m_cbData.matInvWorld); m_vPosition.x = m_matWorld._41; m_vPosition.y = m_matWorld._42; m_vPosition.z = m_matWorld._43; m_vLook.x = m_matWorld._11; m_vLook.y = m_matWorld._12; m_vLook.z = m_matWorld._13; m_vSide.x = m_matWorld._21; m_vSide.y = m_matWorld._22; m_vSide.z = m_matWorld._23; m_vUp.x = m_matWorld._31; m_vUp.y = m_matWorld._32; m_vUp.z = m_matWorld._33; D3DXMatrixTranspose(&m_cbData.matWorld,&m_matWorld); D3DXMatrixTranspose(&m_cbData.matView,&m_matView); D3DXMatrixTranspose(&m_cbData.matProj,&m_matProj); D3DXMatrixTranspose(&m_cbData.matInvWorld, &m_cbData.matInvWorld); } bool xShape::Create( ID3D11Device* pDevice, T_STR szShaderName, T_STR szTextureName) { m_pd3dDevice = pDevice; CreateVertexData(); CreateIndexData(); CreateVertexBuffer(); CreateIndexBuffer(); CreateConstantBuffer(); LoadVertexShader(szShaderName); LoadPixelShader(szShaderName); LoadGeometryShader(szShaderName); CreateInputLayout(); LoadTexture(szTextureName); return true; } HRESULT xShape::CreateVertexBuffer() { HRESULT hr = S_OK; if (m_iNumVertex <= 0)return hr; m_iVertexSize = sizeof(PNCT_VERTEX); DX::CreateVertexBuffer(m_pd3dDevice, m_iNumVertex, sizeof(PNCT_VERTEX), &m_VertexList.at(0), m_dxObj.m_pVertexBuffer.GetAddressOf()); return hr; } HRESULT xShape::CreateIndexBuffer() { HRESULT hr = S_OK; if (m_iNumIndex <= 0)return hr; DX::CreateIndexBuffer(m_pd3dDevice, m_iNumIndex, sizeof(DWORD), &m_IndexList.at(0), m_dxObj.m_pIndexBuffer.GetAddressOf()); return hr; } HRESULT xShape::CreateConstantBuffer() { HRESULT hr = S_OK; DX::CreateConstantBuffer(m_pd3dDevice, 1, sizeof(T_CB_DATA), m_dxObj.m_pConstantBuffer.GetAddressOf(), &m_cbData, false); return hr; } HRESULT xShape::CreateInputLayout() { HRESULT hr = S_OK; D3D11_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = sizeof(layout) / sizeof(layout[0]); DX::CreateInputLayout(m_pd3dDevice, m_dxObj.m_pVSBlob->GetBufferSize(), m_dxObj.m_pVSBlob->GetBufferPointer(), layout, numElements, m_dxObj.m_pInputLayout.GetAddressOf()); return hr; } HRESULT xShape::LoadVertexShader(T_STR szName) { HRESULT hr = S_OK; m_dxObj.m_pVertexShader.Attach( DX::LoadVertexShaderFile(m_pd3dDevice, szName.c_str(), m_dxObj.m_pVSBlob.GetAddressOf())); return hr; } HRESULT xShape::LoadPixelShader(T_STR szName) { HRESULT hr = S_OK; m_dxObj.m_pPixelShader.Attach( DX::LoadPixelShaderFile(m_pd3dDevice, szName.c_str())); return hr; } HRESULT xShape::LoadGeometryShader(T_STR szName) { HRESULT hr = S_OK; m_dxObj.m_pGeometryShader.Attach( DX::LoadGeometryShaderFile(m_pd3dDevice, szName.c_str())); return hr; } HRESULT xShape::LoadTexture(T_STR szName) { HRESULT hr = S_OK; if (szName.empty()) return E_FAIL; D3DX11_IMAGE_LOAD_INFO loadinfo; ZeroMemory(&loadinfo, sizeof(loadinfo)); loadinfo.BindFlags = D3D11_BIND_SHADER_RESOURCE; loadinfo.Format = DXGI_FORMAT_FROM_FILE; ID3D11ShaderResourceView* pTex = NULL; hr=D3DX11CreateShaderResourceViewFromFile( m_pd3dDevice, szName.c_str(), &loadinfo, NULL, m_dxObj.m_pTextureRV.GetAddressOf(), NULL); return hr; } bool xShape::PreRender( ID3D11DeviceContext* pContext) { m_dxObj.PreRender(pContext, m_iVertexSize); return true; } bool xShape::Render(ID3D11DeviceContext* pContext) { pContext->UpdateSubresource( m_dxObj.m_pConstantBuffer.Get(), 0, NULL, &m_cbData, 0, 0); pContext->IASetPrimitiveTopology( (D3D_PRIMITIVE_TOPOLOGY)m_Primitive); m_dxObj.PreRender(pContext, m_iVertexSize); if (m_iNumIndex > 0) m_dxObj.PostRender(pContext, m_iVertexSize, m_iNumIndex); else m_dxObj.PostRender(pContext, m_iVertexSize, m_iNumVertex); return true; } bool xShape::PostRender(ID3D11DeviceContext* pContext ) { m_dxObj.PostRender(pContext, m_iVertexSize, m_iNumIndex); return true; } bool xShape::Release() { return true; } bool xShape::Frame() { return true; } bool xShape::Init() { return true; } xShape::xShape() { m_iNumIndex=0; m_iNumVertex=0; D3DXMatrixIdentity(&m_matWorld); m_vPosition.x = m_matWorld._41; m_vPosition.y = m_matWorld._42; m_vPosition.z = m_matWorld._43; m_vLook.x = m_matWorld._11; m_vLook.y = m_matWorld._12; m_vLook.z = m_matWorld._13; m_vSide.x = m_matWorld._21; m_vSide.y = m_matWorld._22; m_vSide.z = m_matWorld._23; m_vUp.x = m_matWorld._31; m_vUp.y = m_matWorld._32; m_vUp.z = m_matWorld._33; D3DXMatrixIdentity(&m_matView); D3DXMatrixIdentity(&m_matProj); m_Primitive = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; } xShape::~xShape() { } //////////////// TBoxSahpe ////////////////// HRESULT xBoxShape::CreateVertexData() { HRESULT hr = S_OK; // ¾Õ¸é m_VertexList.resize(24); m_VertexList[0] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[1] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[2] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[3] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); // µÞ¸é m_VertexList[4] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR3(0.0f, 0.0f, 1.0f), D3DXVECTOR4(0.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[5] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR3(0.0f, 0.0f, 1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[6] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR3(0.0f, 0.0f, 1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[7] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR3(0.0f, 0.0f, 1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); // ¿À¸¥ÂÊ m_VertexList[8] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR3(1.0f, 0.0f, 0.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[9] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR3(1.0f, 0.0f, 0.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[10] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR3(1.0f, 0.0f, 0.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[11] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR3(1.0f, 0.0f, 0.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); // ¿ÞÂÊ m_VertexList[12] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR3(-1.0f, 0.0f, 0.0f), D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[13] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR3(-1.0f, 0.0f, 0.0f), D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[14] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR3(-1.0f, 0.0f, 0.0f), D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[15] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR3(-1.0f, 0.0f, 0.0f), D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); // À­¸é m_VertexList[16] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR4(1.0f, 0.5f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[17] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR4(1.0f, 0.5f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[18] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR4(1.0f, 0.5f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[19] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR4(1.0f, 0.5f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); // ¾Æ·§¸é m_VertexList[20] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR3(0.0f, -1.0f, 0.0f), D3DXVECTOR4(0.0f, 1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[21] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR3(0.0f, -1.0f, 0.0f), D3DXVECTOR4(0.0f, 1.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[22] = PNCT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR3(0.0f, -1.0f, 0.0f), D3DXVECTOR4(0.0f, 1.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 1.0f)); m_VertexList[23] = PNCT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR3(0.0f, -1.0f, 0.0f), D3DXVECTOR4(0.0f, 1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 1.0f)); m_iNumVertex = m_VertexList.size(); return hr; } HRESULT xBoxShape::CreateIndexData() { HRESULT hr = S_OK; m_IndexList.resize(36); int iIndex = 0; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 1; m_IndexList[iIndex++] = 2; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 2; m_IndexList[iIndex++] = 3; m_IndexList[iIndex++] = 4; m_IndexList[iIndex++] = 5; m_IndexList[iIndex++] = 6; m_IndexList[iIndex++] = 4; m_IndexList[iIndex++] = 6; m_IndexList[iIndex++] = 7; m_IndexList[iIndex++] = 8; m_IndexList[iIndex++] = 9; m_IndexList[iIndex++] = 10; m_IndexList[iIndex++] = 8; m_IndexList[iIndex++] = 10; m_IndexList[iIndex++] = 11; m_IndexList[iIndex++] = 12; m_IndexList[iIndex++] = 13; m_IndexList[iIndex++] = 14; m_IndexList[iIndex++] = 12; m_IndexList[iIndex++] = 14; m_IndexList[iIndex++] = 15; m_IndexList[iIndex++] = 16; m_IndexList[iIndex++] = 17; m_IndexList[iIndex++] = 18; m_IndexList[iIndex++] = 16; m_IndexList[iIndex++] = 18; m_IndexList[iIndex++] = 19; m_IndexList[iIndex++] = 20; m_IndexList[iIndex++] = 21; m_IndexList[iIndex++] = 22; m_IndexList[iIndex++] = 20; m_IndexList[iIndex++] = 22; m_IndexList[iIndex++] = 23; m_iNumIndex = m_IndexList.size(); return hr; } xBoxShape::xBoxShape() { } xBoxShape::~xBoxShape() { }<file_sep>#pragma once #include "SvrStd.h" #include <process.h> #include "TProtocolChat.h" #include "SUser.h" class TClient : public SUser { public: int m_iSocket; unsigned long m_hSendThread; unsigned long m_hReceiveThread; bool m_bExit; public: char m_strBuffer[128]; bool m_bSend; bool m_bLoginOK; bool Init(); bool Frame(); bool Release(); int CreateConnectSocket( int iPort); int SendMsg( char* pMsg, WORD code ); int SendMsg( char* pMsg, int iSize, WORD code ); int ProcessPacket(); public: TClient(void); ~TClient(void); }; <file_sep>#pragma once #include "DUtils.h" class DXDevice { public: // ---------------------------------------------------- // Global Variables // ---------------------------------------------------- ID3D11Device* m_pd3dDevice; // 디바이스 객체 IDXGISwapChain* m_pSwapChain; // 스왑체인 객체 ID3D11RenderTargetView* m_pRenderTargetView; // 메인 랜더타켓 뷰 D3D11_VIEWPORT m_ViewPort; // 뷰 포트 D3D_DRIVER_TYPE m_driverType; // 디바이스 타입(디폴트 : 하드웨어 가속) IDXGIFactory* m_pGIFactory; // DXGI 객체 ID3D11DeviceContext* m_plmmediateContext; // 디바이스 컨텍스트 D3D_DRIVER_TYPE m_DriverType; // 디바이스 타입 D3D_FEATURE_LEVEL m_FeatureLevel; // Directx의 기능 수준 public: //------------------------------------------------- // 디바이스 및 스왑체인 생성 : // 1, CreateDevice() // 2, CreateGIFactory() // 3, CreateSwapChain() // 4, SetRenderTargetView() // 5, SetViewPort() //-------------------------------------------------- HRESULT CreateDevice(); HRESULT CreateGIFactory(); HRESULT CreateSwapChain(HWND hWnd, UINT iWidth, UINT iHeigh); // ------------------------------------------------- // // ------------------------------------------------- HRESULT SetRenderTargetView(); HRESULT SetViewPort(); bool CleanupDevice(); public: DXDevice(); virtual ~DXDevice(); }; <file_sep>#include "Sample.h" bool Sample::Init() { DXDevice::CreateGIFactory(); // =--------------------------------------------= // // =--------------------------------------------= FILE *fp; fp = _tfopen(_T("DeviceInfo.txt"), _T("wt")); if (!fp) { MessageBox(NULL, _T("파일을 생성하지 못했습니다."), _T("파일 생성 에러"), MB_ICONERROR); return FALSE; } DEnumAdapter* pAdapterInfo; _ftprintf(fp, L"Num Adapter: %d\n", m_Enumeration) }<file_sep>#pragma once #include "S_Lock.h" class S_Thread : public S_SvrObj { public: unsigned int m_hThread; unsigned int m_iThreadID; bool m_bStarted; public: void CreateThread(); virtual bool Run(); static unsigned int WINAPI HandleRunner(LPVOID parameter); public: S_Thread(); virtual ~S_Thread(); }; <file_sep>#include<stdio.h> void main() { int sum = 0; int max = 0; int iCount = 1; scanf_s("%d", &max); while (iCount <= max) { sum = sum + iCount++; } printf("1~100±îÁöÀÇ ÇÕ:%d\n", sum); }<file_sep>//STL //#include <iostream> 앞으로 많이 쓸 헤더.. //#include <string> //#include <vector> //#include <list> //#include <map> //#include <set> //#include <algorithm> //#include <functional> 함수 객체. //#include <iterator> //set = 같은 종류 갯수 카운팅 , 갯수 상관없이 종류별 카운팅. 용이. //set = 중복된 데이터 입력불가 //set 특성상 많은 함수가 지원 안함 //cbegin() c=const //multiset = 중복데이터 입력가능, 기본정렬이 되서 입력된다. //for_each(mesetList.begin(),mesetList.end(),fucn()); // 함수까지 같이 포함하여 for문으로 돌릴수 있음 //mem-fun =클래스 안의 멤버함수를 주소를 넘겨서 호출. //bind2nd = 기본적으론 인자값을 한개,구조체 사용시 여러개 //generate() //std::map<int, string> =사전식 자료관리. 반드시 인덱스가 있어야한다 (차례가 있어야한다) //PAIR=값+키 //키=인덱스//키와 값이 같이다니는게 MAP// 유일성=키 //insert(make.pair(0,"홍길동")); //first =키 //값=second // 트리형식 - 검색을 빠르게 하려고. //map 검색 // iter= mapList.find(100); //힙 정렬 = 트리 //가장 우선순위가 높은걸 제일 앞으로 .. //우선순위큐 // 깊이 우선 탐색은 스택 // 넓이 우선 탐색은 큐 // 로직은 항상 똑같아야 한다. //크루스칼 //프림 //사이클은 피해라 //최소 비용 신장 트리 //최단 거리 계산 할때 //하지만 동적일때는 매우 불--편 //이거보다 좋은건 다이스타 알고리즘 //shared_ptr 스마트 포인터 //unique_ptr //API // 콘솔응 void, int main() // API는 int WINAPI WinMain // 인스턴스 - 메모리 실체 //윈도우 프로시저에는 함수 주소값를 넘겨주어야한다 . //1프레임의 경과 시간 //1초의 프레임 카운터 //게임이 실행된 누적시간 //API // bool init() // bool Frame() // bool Render() // bool Release() // 항상 있어야 하는 함수 <file_sep>#include <iostream> #define SAFE_NEW(p,N) {if(!p) p=new N;} //#define SAFE_NEW_ARRAY(p,N,C) {if(!p) p=new N[C]; if(p) memset(p,0,sizeof(N)*C);} #define SAFE_NEW_VALUE(p,N,v) {if(!p) p=new N(v);} #define SAFE_DEL(p) {if(p)delete p; (p) = NULL; } #define SAFE_ZERO(p) {p=0;}; struct TNode { int m_iValue; int m_iDepth; TNode* m_pLeft; TNode* m_pRight; TNode(int idata) : m_iValue(idata), m_pLeft(0), m_pRight(0), m_iDepth(0) {}; }; TNode* g_pRoot = NULL; int g_iIndex = 0; void BinaryNode(TNode* pParentNode, int idata) { if (pParentNode == 0)return; // iData > parent --> 오른쪽 노드 추가 // 왼쪽노드 추가 (반대경우) if (pParentNode->m_iValue > idata) { if (pParentNode->m_pLeft == 0) { pParentNode->m_pLeft = new TNode(idata); } else { BinaryNode(pParentNode->m_pLeft, idata); } } else { if (pParentNode->m_pRight == 0) { pParentNode->m_pRight = new TNode(idata); } else { BinaryNode(pParentNode->m_pRight, idata); } } } //void Build(TNode* pParentNode) //{ // std::cout << pParentNode->m_iValue << std::endl; // // if (ADD(pParentNode)) // { // // Build(pParentNode->m_pLeft); // Build(pParentNode->m_pRight); // } //} void PRINT(TNode* pParentNode) { if (pParentNode != NULL) { std::cout << pParentNode->m_iValue << std::endl; //전위 preorder Build(pParentNode->m_pLeft); //std::cout << pParentNode->m_iValue << std::endl; //중위 inorder Build(pParentNode->m_pRight); //std::cout << pParentNode->m_iValue << std::endl; //후위 postorder } } void DELALL(TNode* pParentNode) { if (pParentNode == NULL)return; DELALL(pParentNode->m_pLeft); DELALL(pParentNode->m_pRight); SAFE_DEL(pParentNode); } int g_iData[10] = { 5,0,4,7,8,3,9,2,6,1 }; void main() { g_pRoot = new TNode(0); TNode* pNode = g_pRoot; SAFE_NEW_VALUE(g_pRoot, TNode, g_iData[g_iIndex++]); for (int i = 1; i < 10; i++) { BinaryNode(g_pRoot, g_iData[i]); } //Build(g_pRoot); PRINT(g_pRoot); DELALL(g_pRoot); SAFE_ZERO(g_pRoot) getchar(); }<file_sep>#include "TServerIOCP.h" bool TServerIOCP::Init() { m_hIOCP = ::CreateIoCompletionPort( INVALID_HANDLE_VALUE, 0, 0, WORKDER_THREAD_COUNT ); for( int iThread=0; iThread < WORKDER_THREAD_COUNT; iThread++) { m_WorkerThread[iThread].CreateThread(); } return true; } bool TServerIOCP::Release(){ return true; } void TServerIOCP::AddHandleToIOCP( HANDLE hClientSocket, ULONG_PTR dwReturnKey ) { ::CreateIoCompletionPort(hClientSocket, m_hIOCP,dwReturnKey, 0); return; } TServerIOCP::TServerIOCP(void) { } TServerIOCP::~TServerIOCP(void) { } <file_sep>#pragma once #include "SAcceptor.h" class TChatAccept : public SAcceptor { public: void AddUser(SOCKET socket, SOCKADDR_IN address ); public: TChatAccept(void); ~TChatAccept(void); }; <file_sep>#include "S_Packet.h" WORD S_Packet::getID() { return *m_ptrPacket.type; } WORD S_Packet::getSize() { return *m_ptrPacket.len; } char* S_Packet::getData() { return m_strPacketbuf; } int S_Packet::getDataSize() { return m_iReceivedsize; } void S_Packet::ReadData(void* buf, int iSize) { ::CopyMemory(buf, m_pStrReadPos, iSize); m_pStrReadPos += iSize; } void S_Packet::WriteData(void* buf, int iSize) { if (m_iReceivedsize >= PACKETBUFFERSIZE - 4) { } *m_ptrPacket.len += iSize; CopyMemory(m_pStrWritePos, buf, iSize); m_pStrWritePos += iSize; m_iReceivedsize += iSize; } S_Packet& S_Packet::SetId(unsigned short id) { *m_ptrPacket.type = id; return *this; } void S_Packet::Clear() { ZeroMemory(m_strPacketbuf, PACKETBUFFERSIZE); m_ptrPacket.len = (WORD*)m_strPacketbuf + 0; m_ptrPacket.type = (WORD*)m_strPacketbuf + 2; m_pStrWritePos = &m_strPacketbuf[4]; m_pStrReadPos = &m_strPacketbuf[4]; m_iReceivedsize = 0; *m_ptrPacket.len = 4; } S_Packet& S_Packet::operator << (int arg) { WriteData(&arg, sizeof(int)); return *this; } S_Packet& S_Packet::operator >> (int& arg) { ReadData(&arg, sizeof(int)); return *this; } S_Packet& S_Packet::operator << (DWORD arg) { WriteData(&arg, sizeof(DWORD)); return *this; } S_Packet& S_Packet::operator >> (DWORD& arg) { ReadData(&arg, sizeof(DWORD)); return *this; } S_Packet& S_Packet::operator << (bool arg) { WriteData(&arg, sizeof(bool)); return *this; } S_Packet& S_Packet::operator >> (bool& arg) { ReadData(&arg, sizeof(bool)); return *this; } S_Packet& S_Packet::operator << (unsigned short arg) { WriteData(&arg, sizeof(unsigned short)); return *this; } S_Packet& S_Packet::operator >> (unsigned short& arg) { ReadData(&arg, sizeof(unsigned short)); return *this; } S_Packet& S_Packet::operator << (float arg) { WriteData(&arg, sizeof(float)); return *this; } S_Packet& S_Packet::operator >> (float& arg) { ReadData(&arg, sizeof(float)); return *this; } S_Packet& S_Packet::operator << (char* arg) { int iLen = sizeof(char)*strlen(arg); WriteData(&arg, iLen); return *this; } S_Packet& S_Packet::operator >> (char* arg) { int iLen = sizeof(char)*strlen(this->m_pStrReadPos); ReadData(&arg, sizeof(char)*iLen); return *this; } S_Packet& S_Packet::operator << (S_Packet& arg) { unsigned short type = arg.getID(); unsigned short size = arg.getSize(); WriteData(&type, sizeof(unsigned short)); WriteData(&size, sizeof(unsigned short)); WriteData(&arg.m_pStrWritePos, size - 4); return *this; } S_Packet& S_Packet::operator >> (S_Packet& arg) { int type, size; char buffer[4096] = { 0, }; ReadData(&type, sizeof(unsigned short)); ReadData(&size, sizeof(unsigned short)); ReadData(&buffer, size - 4); arg.SetId(type); arg.WriteData(buffer, size - 4); return *this; } S_Packet::S_Packet() { Clear(); SetId(0); } S_Packet::S_Packet(unsigned short type) { Clear(); SetId(type); } S_Packet::~S_Packet() { } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <WinSock2.h> #include "TProtocol.h" #pragma comment(lib,"ws2_32.lib") int SendMsg(SOCKET sock, char* msg, WORD type) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sendmsg.ph.len = strlen(msg); sendmsg.ph.type = type; memcpy(sendmsg.msg, msg, strlen(msg)); int sendbytes = 0; int iTotalsize = strlen(msg) + PACKET_HEADER_SIZE; char* pMsg = (char*)&sendmsg; do { sendbytes += send(sock, &pMsg[sendbytes], iTotalsize - sendbytes, 0); } while (sendbytes < iTotalsize); return iTotalsize; } int main() { // WSA는 윈속 없으면 유닉스 // 윈속 초기화 WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) // 0 성공 1이 실패 { return 1; } //////////////////////////////// SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //SOCK_DGRAM // 3번째 인자는 그냥 무조건 0으로 쓰자 // (IPPROTO_TCP,IPPROTO_UDP) 원래는 맞게끔 넣어줘야함 //SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { return 1; } // 소켓 생성 SOCKADDR_IN addr; ZeroMemory(&addr, sizeof(addr)); addr.sin_family = AF_INET; // 무조건 고정 addr.sin_addr.s_addr = inet_addr("192.168.0.101"); // 127.0.0.1 loofback 주소 addr.sin_port = htons(10000); // 접속(전화를 걸었다) int ret = connect(sock, (sockaddr*)&addr, sizeof(addr)); // 서버의 정보가 들어가 있다 if (ret == SOCKET_ERROR) { return 1; } // SOCKET_ERROR 가 아니면 연결이 된것 //while (1) //{ //} //while (1)99 //{ /*char buffer3[256] = { 0, }; recv(sock, buffer3, sizeof(buffer3), 0); std::cout << buffer3;*/ while (1) { char buffer2[] = { 0, }; scanf("%s", buffer2); send(sock, buffer2, sizeof(buffer2), 0); } //} char buffer[256] = { 0, }; recv(sock, buffer, sizeof(buffer), 0); std::cout << buffer; closesocket(sock); // 윈속 닫기 WSACleanup(); std::cout << "HELLO World!\n"; }<file_sep>#pragma once #include "TServerObj.h" class TSynchronize { public: TServerObj* m_pSerObj; public: TSynchronize( TServerObj* pObj ); virtual ~TSynchronize(void); }; <file_sep>#include "DB_CONNECT.h" bool DB_CONNECT::DBConnect() { TCHAR InCon[255]; SQLTCHAR OutCon[1024]; SQLSMALLINT cbOutCon; TCHAR Dir[MAX_PATH]; SQLRETURN Ret; if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hENV) != SQL_SUCCESS) { return FALSE; } if (SQLSetEnvAttr(m_hENV, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER) != SQL_SUCCESS) { return FALSE; } if (SQLAllocHandle(SQL_HANDLE_DBC, m_hENV, &m_hDBC) != SQL_SUCCESS) { return FALSE; } GetCurrentDirectory(MAX_PATH, Dir); _stprintf(InCon, _T("%s"), _T("Driver={SQL Server};Server=shader.kr;Address=192.168.0.28,1433;Network=dbmssocn;Database=KHJUser;Uid=sa;Pwd=<PASSWORD>;")); Ret = SQLDriverConnect(m_hDBC, NULL, (SQLTCHAR*)InCon, _countof(InCon), OutCon, _countof(OutCon), &cbOutCon, SQL_DRIVER_NOPROMPT); if ((Ret != SQL_SUCCESS) && (Ret != SQL_SUCCESS_WITH_INFO)) { SQLTCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1]; SQLTCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length; SQLError(m_hENV, m_hDBC, m_hSTMT, sqlstate, &sqlcode, buffer, SQL_MAX_MESSAGE_LENGTH + 1, &length); MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); int iErrorCnt = 1; while (Ret = SQLGetDiagRec(SQL_HANDLE_DBC, m_hDBC, iErrorCnt++, sqlstate, &sqlcode, buffer, sizeof(buffer), &length) != SQL_NO_DATA) { MessageBox(NULL, (LPTSTR)buffer, (LPTSTR)sqlstate, MB_OK); } return FALSE; } if (SQLAllocHandle(SQL_HANDLE_STMT, m_hDBC, &m_hSTMT) != SQL_SUCCESS) { return 0; } return TRUE; } void DB_CONNECT::DBDisConnect() { // 삭제는 반대순서로 해야한다. SQLFreeHandle(SQL_HANDLE_STMT, m_hSTMT); SQLDisconnect(m_hDBC); SQLFreeHandle(SQL_HANDLE_DBC, m_hDBC); SQLFreeHandle(SQL_HANDLE_ENV, m_hENV); } DB_CONNECT::DB_CONNECT() { } DB_CONNECT::~DB_CONNECT() { } <file_sep>#include "pch.h" #define MAX_WORK_THREAD 4 #define RECV 1000 #define SEND 2000 struct OVERLAPPED_EX : OVERLAPPED { DWORD flag; }; struct TUser { SOCKET sock; WSABUF buffer; char buf[2048]; OVERLAPPED_EX ov; }; TUser user; HANDLE m_hIOCP; HANDLE m_hWorkThread[MAX_WORK_THREAD]; bool BeginWinSock() { WSADATA wsa; int iRet = WSAStartup(MAKEWORD(2, 2), &wsa); if (iRet != 0) return false; return true; } bool EndWinSock() { int iRet = WSACleanup(); if (iRet != 0) return false; return true; } DWORD WINAPI WorkerThread(LPVOID param); int main() { if (BeginWinSock() == false) { return -1; } // listen socket SOCKET listenSock; listenSock = socket(AF_INET, SOCK_STREAM, 0); // ip + port -> bind -> 운영 체제 보고. // port를 사용하고 있는 프로세스(실행파일을 구분하는 용도로 한다.)에게 알려준다. SOCKADDR_IN sa; ZeroMemory(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(10000); //sa.sin_addr.s_addr = inet_addr("192.168.0.27"); //ip가 여러개인 경우에(랜선, 무선랜) 여러개중 아무거로 다 받는다는 뜻. sa.sin_addr.s_addr = htonl(INADDR_ANY); bind(listenSock, (sockaddr*)&sa, sizeof(sa)); // listen -> 듣다. listen(listenSock, SOMAXCONN); //->개통 //스레드4개를 고용. DWORD id; for (int i = 0; i < MAX_WORK_THREAD; i++) { m_hWorkThread[i] = ::CreateThread(0, 0, WorkerThread, 0, 0, &id); } //기술자를 고용. m_hIOCP = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); SOCKADDR_IN addr; int addrlen = sizeof(addr); while (1) { SOCKET sock = accept(listenSock, (SOCKADDR*)&addr, &addrlen); user.sock = sock; //기술자에게 Read파일에대한 읽는 결과가 완료되면, 그 결과를 완료키key( ex)1111 )의 내용으로 알려줘라. ::CreateIoCompletionPort((HANDLE)sock, m_hIOCP, (ULONG_PTR)&user, 0); DWORD trans,flag=0; user.buffer.buf = user.buf; user.buffer.len = 2048; user.ov.flag = RECV; int iRet = WSARecv(sock, &user.buffer, 1, &trans,&flag, (LPOVERLAPPED)&user.ov, NULL); if (iRet == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { return false; } } } EndWinSock(); } DWORD WINAPI WorkerThread(LPVOID param) { LPOVERLAPPED ov; DWORD bytesTransfer; ULONG_PTR keyValue; while (1) { //비동기 입출력의 작업결과를 확인하는 함수. //::범위 지정함수. //::사용자 정의 함수와 헷갈리지 말라고 이함수는 여기 클래스가 아니라 상위에 있다고 알려주는 함수. //IOCP QUEUE bool bRet = ::GetQueuedCompletionStatus(m_hIOCP, &bytesTransfer, &keyValue, &ov, INFINITE); TUser* pUser = (TUser*)keyValue; OVERLAPPED_EX* ovex = (OVERLAPPED_EX*)ov; if (bRet == TRUE) { if (ovex->flag == RECV) { pUser->buffer.buf = pUser->buf; pUser->buffer.len = 2048; DWORD trans = bytesTransfer; pUser->ov.flag = SEND; int iRet = WSASend(pUser->sock, &(pUser->buffer), 1, &trans, 0, (LPOVERLAPPED)&(pUser->ov), NULL); } else { /*if (iRet == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { return false; } }*/ } } // if (bytesTransfer == 0) // { // ::SetEvent(iocp->m_hEventKillThread); // return true; // } // if (keyValue == (ULONG_PTR)iocp->m_hFileRead) // { // iocp->DispatchRead(bytesTransfer); // } // else // { // iocp->DispatchWrite(bytesTransfer); // } //} //else //{ // /*if (ERROR_HANDLE_EOF == GetLastError()) // { // iocp->m_bEndRead = true; // return true; // } // if (GetLastError() == WAIT_TIMEOUT) // { // continue; // } //...... //} } return 0; }<file_sep>#include "Maze.h" // 상위 클래스에서는 인스턴스를 만드는 방법만 결정하고, 구체적인 클래스 이름은 뒤로 미룬다. // 어떤 클래스의 인스턴스를 생성할 지에 대한 결정은 서브 클래스가 결정한다. //1) 어떤 클래스가 자신이 생성해야 하는 객체의 클래스를 예측할 수 없을 때 //2)생성할 객체를 기술하는 책임을 자신의 서브클래스가 지정했으면 할 떄 //3)객체 생성의 책임을 몇 개의 보조 서브클래스 가운데 하나에게 위임하고 // 어떤 서브클래스가 위임자인지에 대한 정보를 국소화 시키고 싶을 떄 class Spell { public: Spell() {}; }; class EnchantedRoom :public Room { public: EnchantedRoom(int n, Spell*) :Room(n) { } }; class BombedWall : public Wall { public: BombedWall(){} }; class BombedWithRoom : public Room { public: BombedWithRoom(int n): Room(n){} }; class DoorNeedingSpell :public Door { public: DoorNeedingSpell(Room* r1, Room* r2) :Door(r1, r2) { } }; class MazeGame { public: Maze * CreateMaze() { Maze* aMaze = MakeMaze(); Room* r1 = MakeRoom(1); Room* r2 = MakeRoom(2); Door* theDoor = MakeDoor(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); r1->SetSide(North, MakeWall()); r1->SetSide(East, theDoor); r1->SetSide(South, MakeWall()); r1->SetSide(West, MakeWall()); r2->SetSide(North, MakeWall()); r2->SetSide(East, MakeWall()); r2->SetSide(South, MakeWall()); r2->SetSide(West, theDoor); return aMaze; } // Factory Method virtual Maze* MakeMaze() { return new Maze; } virtual Room* MakeRoom(int n) { return new Room(n); } virtual Wall* MakeWall() { return new Wall; } virtual Door* MakeDoor(Room* r1, Room* r2) { return new Door(r1, r2); } }; class BombedMazeGame :public MazeGame { public: virtual Wall* MakeWall() { return new BombedWall; } virtual Room* MakeRoom(int n) { return new BombedWithRoom(n); } }; class EnchantedMazeGame : public MazeGame { public: virtual Door* MakeDoor(Room* r1, Room* r2) { return new DoorNeedingSpell(r1, r2); } virtual Room* MakeRoom(int n) { return new EnchantedRoom(n, CastSpell()); } protected: Spell * CastSpell() { return 0; }; }; void main() { MazeGame mg; Maze* pMaze1 = mg.CreateMaze(); BombedMazeGame bombedGame; Maze* pMaze2 = bombedGame.CreateMaze(); EnchantedMazeGame EnchantedGame; Maze* pMaze3 = EnchantedGame.CreateMaze(); }<file_sep>#include<stdio.h> #include<conio.h> //Æ÷ÀÎÅÍ void swap(int *a, int *b) { int i = *a; int j = *b; *a = j; *b = i; } void main() { int a = 3; int b = 5; swap(&a,&b); printf("a=%d, b=%d", a, b); } <file_sep>#include "Sample.h" typedef basic_string<TCHAR> T_STR; bool Sample::Init() { if (FAILED(InitDevice(m_hWnd, this->m_iWindowWidth, this->m_iWindowHeight))) { MessageBox(0, _T("CreateDevice 실패"), _T("Fatal error"), MB_OK); return false; } if (!m_Timer.Init())return false; m_Timer.Start(); IDXGISurface1* pBackBuffer = NULL; HRESULT hr = GetSwapChain()->GetBuffer(0, __uuidof(IDXGISurface), (LPVOID*)pBackBuffer); m_Font.Set(m_hWnd, m_iWindowWidth, m_iWindowHeight, pBackBuffer); if (pBackBuffer)pBackBuffer->Release(); /*if(!m_Font.Init()) { return false; } if(!m_Font.Set(m_pd3dDevice,m_plmmediateContext)) { return false; } DirectX Input 생성*/ if (!I_Input.InitDirectInput(m_hInstance, m_hWnd, true, true)) { return false; } //DirectX Input 초기화 if (!I_Input.Init()) { return false; } return true; } bool Sample::Release() { m_Timer.Stop(); if (!CleanupDevice()) return false; if (!m_Timer.Release())return false; if (!m_Font.Release())return false; if (!I_Input.Release())return false; return true; } bool Sample::Frame() { if (!m_Timer.Frame())return false; static float fTimer = 0.0f; fTimer += m_Timer.GetSPF(); // if(!I_Input.m_dwlmmediate& fTumer>0.2f) { //m_strBuffer.clear(); if (!I_Input.Frame())return false; fTimer = 0.0f; } return true; } bool Sample::Render() { float ClearColor[4] = { 0.0f,0.125f,0.3f,1.0f }; //red,green.blue,alpha m_plmmediateContext->ClearRenderTargetView(m_pRenderTargetView, ClearColor); TCHAR pBuffer[256]; memset(pBuffer, 0, sizeof(TCHAR) * 256); // 인풋 정보 출력 int iCount = 0; if (I_Input.m_dwlmmediate) { for (int iKey = 0; iKey < KEYSTATECOUNT; iKey++) { if (I_Input.m_KeyState[iKey] & 0x80) { // DirectInput keyboard scan Codes _stprintf_s(pBuffer, _T("Key State:0x%02x: %d"), iKey, I_Input.m_KeyState[iKey]); UINT iStartX = m_iWindowWidth / 2; UINT iStartY = m_iWindowHeight / 2 + (20 * iCount); m_Font.Begin(); m_Font.m_pRT->SetTransform(D2D1::Matrix3x2F::Identity()); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); RECT rc1 = { iStartX,iStartY,m_iWindowWidth,m_iWindowHeight }; m_Font.DrawTextW(rc1, pBuffer, D2D1::ColorF(1, 1, 1, 0.5)); m_Font.End(); /* m_Font.Begin(); m_Font.DrawTextLine(pBuffer,iStartX,iStartY); m_Font.End();*/ iCount++; } } } else { //2 int iCount = I_Input.m_dwElements; if (iCount >= 1)m_strBuffer.clear(); for (DWORD i = 0; i < iCount; i++) { _stprintf_s(pBuffer, _T("key[%d] State: 0x%02x %s \n"), i, I_Input.m_didod[i].dwOfs, (I_Input.m_didod[i].dwData & 0x80) ? TEXT("Down") : TEXT("UP")); m_strBuffer += pBuffer; } UINT iStartX = 0; UINT iStartY = 0; m_Font.Begin(); m_Font.m_pRT->SetTransform(D2D1::Matrix3x2F::Identity()); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); RECT rc1 = { iStartX,iStartY,m_iWindowWidth,m_iWindowHeight }; const TCHAR* strData = m_strBuffer.c_str(); m_Font.DrawTextW(rc1, const_cast<TCHAR*>(strData), D2D1::ColorF(1, 1, 1, 0.5)); m_Font.End(); /* m_Font.Begin(); m_Font.DrawTextLine(strBuffer.c_str,iStartX,iStartY); m_Font.End();*/ for (int iKey = 0; iKey < 4; iKey++) { if (I_Input.m_MouseState.rgbButtons[iKey] & 0x80) { _stprintf_s(pBuffer, _T("Mouse Button State; %02d"), iKey); UINT iStartX = m_iWindowHeight / 2; UINT iStartY = m_iWindowHeight / 2 + (20 * iCount); m_Font.Begin(); m_Font.m_pRT->SetTransform(D2D1::Matrix3x2F::Identity()); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); RECT rc1 = { iStartX,iStartY,m_iWindowWidth,m_iWindowHeight }; m_Font.DrawTextW(rc1, pBuffer, D2D1::ColorF(1, 1, 1, 0.5)); m_Font.End(); /*m_Font.Begin(); m_Font.DrawTextLine( pBuffer, iStartX, iStartY); m_Font.End();*/ iCount++; } } } static LONG MousePosX = I_Input.m_MouseState.lX; static LONG MousePosY = I_Input.m_MouseState.lY; static LONG MousePosZ = I_Input.m_MouseState.lZ; MousePosX += I_Input.m_MouseState.lX; MousePosY += I_Input.m_MouseState.lY; MousePosZ += I_Input.m_MouseState.lZ; _stprintf_s(pBuffer, _T("Mouse X:%ld,Y:%ld,Z:%ld"), MousePosX, MousePosY, MousePosZ); UINT iStartX = m_iWindowWidth / 2; UINT iStartY = m_iWindowHeight / 2 + (20 * iCount); m_Font.Begin(); D2D1_POINT_2F center; center.x = 0; center.y = 0; m_fScale = 1.0f + cosf(m_Timer.GetElapseTime())*0.5f + 0.5f; D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(m_fScale, m_fScale); D2D1::Matrix3x2F rot = D2D1::Matrix3x2F::Rotation(m_Timer.GetElapseTime()*100.0f, center); D2D1::Matrix3x2F trans = D2D1::Matrix3x2F::Translation(iStartX, iStartY); m_matWorld = scale * rot * trans; m_Font.m_pRT->SetTransform(m_matWorld); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); RECT rc1 = { 0,0, m_iWindowWidth, m_iWindowHeight }; m_Font.DrawText(rc1, pBuffer, D2D1::ColorF(1, 1, 1, 0.5)); m_Font.End(); /*m_Font.Begin(); m_Font.DrawTextLine( pBuffer, iStartX, iStartY); m_Font.End();*/ // 타이머 정보 출력 memset(pBuffer, 0, sizeof(TCHAR) * 256); _stprintf_s(pBuffer, _T("FPS:%d SecPerFrame:%10.5f Elapsed : %10.2f"), m_Timer.GetFPS(), m_Timer.GetSPF(), m_Timer.GetElapseTime()); iStartX = m_iWindowWidth; iStartY = 0; m_Font.Begin(); m_Font.m_pRT->SetTransform(D2D1::Matrix3x2F::Identity()); m_Font.m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_Font.m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); RECT rc2 = { iStartX,iStartY, m_iWindowWidth, m_iWindowHeight }; m_Font.DrawText(rc2, pBuffer, D2D1::ColorF(1, 1, 1, 0.5)); m_Font.End(); //m_Font.Begin(); // m_Font.DrawTextLine( pBuffer, iStartX, iStartY); //m_Font.End(); m_pSwapChain->Present(0, 0); I_Input.PostProcess(); return true; } Sample::Sample(void) { m_matWorld = D2D1::IdentityMatrix(); m_fScale = 1.0f; } Sample::~Sample(void) { } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { Sample gSample; if (!gSample.InitWindow(hInstance, nCmdShow, NULL)) { MessageBox(0, _T("Sample 초기화 실패"), _T("Fatal error"), MB_OK); return 0; } ShowCursor(TRUE); gSample.Run(); return 1; } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <iostream> #include <WS2tcpip.h> // InetNtop(), inet_ntop() #include <map> #include "Protocol.h" #pragma comment(lib, "ws2_32") bool BeginWinSock(); bool EndWinSock(); DWORD WINAPI ClientThread(LPVOID arg) { SOCKET sock = (SOCKET)arg; char buf[256] = { 0, }; while (true) { int iRecvByte = recv(sock, buf, sizeof(buf), 0); if (iRecvByte == 0) { break; } int iSendByte = send(sock, buf, iRecvByte, 0); if (iSendByte == 0 || iSendByte == SOCKET_ERROR) { break; } Sleep(1); } closesocket(sock); return 1; } struct User { SOCKET sock; SOCKADDR_IN Addr; }; int main(void) { const u_short port = 10000; if (BeginWinSock() == false) { return -1; } SOCKET Listensock = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); int iRet = bind(Listensock, (sockaddr*)&addr, sizeof(addr)); if (iRet != 0) { return -1; } iRet = listen(Listensock, SOMAXCONN); if (iRet != 0) { return -1; } //u_long on = TRUE; //ioctlsocket(Listensock, FIONBIO, &on); char buffer[] = { "qqqq" }; char ip[INET_ADDRSTRLEN] = { 0, }; std::map<int, User> g_userList; int g_iNumUser = 0; while (1) { SOCKET client; SOCKADDR_IN clientaddr; int AddrLen = sizeof(clientaddr); client = accept(Listensock, (sockaddr*)&clientaddr, &AddrLen); if (client != SOCKET_ERROR) { printf("%s, %d\n", inet_ntop(AF_INET, &clientaddr.sin_addr, ip, sizeof(ip)), ntohs(clientaddr.sin_port)); DWORD threadID; HANDLE hThread = CreateThread(0, 0, ClientThread, (LPVOID)&client, 0, &threadID); } } closesocket(Listensock); if (EndWinSock() == false) { return -1; } return 0; } bool BeginWinSock() { WSADATA wsaData; int iRet = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iRet != 0) return false; return true; } bool EndWinSock() { int iRet = WSACleanup(); if (iRet != 0) return false; return true; }<file_sep>#pragma once #include <Windows.h> #define PACKET_HEADER_SIZE 4 #pragma pack (push, 1) typedef struct { WORD len; // 패킷의 전체 길이 WORD type; // 패킷의 타입(종류) // WORD Index; // 패킷의 고유한 인덱스 // WORD time; // 패킷의 전달 시간 }PACKET_HEADER; typedef struct { PACKET_HEADER ph; char msg[2048]; }UPACKET, *P_UPACKET; // 캐릭터 생성 패킷 typedef struct { byte szName[13]; int iIndex; int iData[10]; }ITEM_INFO; #pragma pack (pop)// 복원 // [0]~ [12][13][14] [14][15][16] ///////////// 패킷의 타입들 ///// #define PACKET_CHAT_MSG 1000 #define PACKET_GAME_START 2000 #define PACKET_GAME_END 3000 #define PACKET_CREATE_CHARACTER 4000 #define PACKET_MOVE_CHARACTER 5000 // //MSG = "안녕하세요!" // //UPACKET sendPacket; //sendPacket.ph.len = strlen(MSG) + PACKET_HEADER_SIZE; //sendPacket.ph.type = PACKET_CHAR_MSG; //sendPacket.msg = MSG; // //UPACKET sendPacket; //sendPacket.ph.len = strlen(CHARACTER_INFO) + PACKET_HEADER_SIZE; //sendPacket.ph.type = PACKET_CREATE_CHARACTER; //sendPacket.msg = CHARACTER_INFO; // // 4 바이트 패킹 // //struct TDATA //{ // int iA; // 4 // int iD; // 4 // short sB; // 2덤 2byte // short sC; // 2덤 2byte // short sC; // 2덤 2byte // byte bC; // 3byte // byte bC; // 3byte //}; // //// 200 //UPACKET a[10]; for (send(a[i])) //a[0]a[1]a[2]a[3] == > 스트림(연속적인 물의 흐름) //char buffer[256]; //UPACKET a[10]; //while (1) //{ // iRecvByte = recv(buffer, 256) // a[0]생성, a[1] = 56 + 144 byte; 일부분만 받음 // 200 - 56 = 144 ~256 256 - 144 = 12 // a[2] = 144~244; // a[3] = 244~256 = 12 //} //recvbuffer = recv(); //if (str; em(recvbuffer) > PACKET_HEADER_SIZE) //{ // if (strlen(recvbuffer) > packet.len) // { // // } //}<file_sep>#include "xDxState.h" namespace DX { ID3D11BlendState* xDxState::g_pBSNoBlend=0; ID3D11BlendState* xDxState::g_pBSAlphaBlend=0; ID3D11DepthStencilState* xDxState::g_pDSVStateEnableLessEqual =0; ID3D11DepthStencilState* xDxState::g_pDSVStateEnableGreater =0; ID3D11DepthStencilState* xDxState::g_pDSVStateDetphWriteDisable=0; ID3D11RasterizerState* xDxState::g_pRSWireFrame=0; ID3D11RasterizerState* xDxState::g_pRSSolid = 0; ID3D11RasterizerState* xDxState::g_pRSBackCullSolid = 0; ID3D11RasterizerState* xDxState::g_pRSFrontCullSolid = 0; ID3D11RasterizerState* xDxState::g_pRSNoneCullSolid = 0; ID3D11RasterizerState* xDxState::g_pRSBackCullWireFrame = 0; ID3D11RasterizerState* xDxState::g_pRSFrontCullWireFrame = 0; ID3D11RasterizerState* xDxState::g_pRSNoneCullWireFrame = 0; ID3D11SamplerState* xDxState::g_pSSWrapLinear=NULL; ID3D11SamplerState* xDxState::g_pSSWrapPoint = NULL; HRESULT xDxState::SetState(ID3D11Device* pd3dDevice) { HRESULT hr; ///////////////////////// blend ////////////// D3D11_BLEND_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.RenderTarget[0].BlendEnable = TRUE; bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; pd3dDevice->CreateBlendState(&bd, &g_pBSAlphaBlend); bd.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; bd.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; hr = pd3dDevice->CreateBlendState(&bd, &g_pBSNoBlend); ///////////////////////////// D3D11_DEPTH_STENCIL_DESC dsd; ZeroMemory(&dsd, sizeof(dsd)); dsd.DepthEnable = TRUE; dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateEnableLessEqual); dsd.DepthEnable = TRUE; dsd.DepthFunc = D3D11_COMPARISON_GREATER; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateEnableGreater); dsd.DepthEnable = FALSE; dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; hr = pd3dDevice->CreateDepthStencilState( &dsd, &g_pDSVStateDetphWriteDisable); //////////////////////////////// ////////////////////////////////// D3D11_RASTERIZER_DESC rd; ZeroMemory(&rd, sizeof(rd)); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_BACK; rd.DepthClipEnable = TRUE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSWireFrame); rd.FillMode = D3D11_FILL_SOLID; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSSolid); rd.CullMode = D3D11_CULL_FRONT; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSFrontCullSolid); rd.CullMode = D3D11_CULL_BACK; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSBackCullSolid); rd.CullMode = D3D11_CULL_NONE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSNoneCullSolid); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_FRONT; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSFrontCullWireFrame); rd.CullMode = D3D11_CULL_BACK; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSBackCullWireFrame); rd.CullMode = D3D11_CULL_NONE; hr = pd3dDevice->CreateRasterizerState(&rd, &g_pRSNoneCullWireFrame); ////////////////////////////////// D3D11_SAMPLER_DESC descSamp; descSamp.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; descSamp.MipLODBias = 0; descSamp.MaxAnisotropy = 16; descSamp.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; descSamp.ComparisonFunc = D3D11_COMPARISON_NEVER; descSamp.BorderColor[0] = 1.0f; descSamp.BorderColor[1] = 0.0f; descSamp.BorderColor[2] = 0.0f; descSamp.BorderColor[3] = 1.0f; descSamp.MinLOD = 0; descSamp.MaxLOD = D3D10_FLOAT32_MAX; pd3dDevice->CreateSamplerState(&descSamp, &g_pSSWrapLinear); descSamp.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; pd3dDevice->CreateSamplerState(&descSamp, &g_pSSWrapPoint); return hr; } bool xDxState::Release() { if(g_pDSVStateEnableLessEqual)g_pDSVStateEnableLessEqual->Release(); if(g_pDSVStateEnableGreater) g_pDSVStateEnableGreater->Release(); if(g_pRSWireFrame) g_pRSWireFrame->Release(); if(g_pRSSolid) g_pRSSolid->Release(); if(g_pRSBackCullSolid) g_pRSBackCullSolid->Release(); if(g_pRSFrontCullSolid) g_pRSFrontCullSolid->Release(); if(g_pRSNoneCullSolid) g_pRSNoneCullSolid->Release(); if(g_pRSBackCullWireFrame) g_pRSBackCullWireFrame->Release(); if(g_pRSFrontCullWireFrame) g_pRSFrontCullWireFrame->Release(); if(g_pRSNoneCullWireFrame) g_pRSNoneCullWireFrame->Release(); if (g_pBSNoBlend) g_pBSNoBlend->Release(); if (g_pBSAlphaBlend) g_pBSAlphaBlend->Release(); if(g_pSSWrapLinear) g_pSSWrapLinear->Release(); if (g_pSSWrapPoint)g_pSSWrapPoint->Release(); if (g_pDSVStateDetphWriteDisable) g_pDSVStateDetphWriteDisable->Release(); return true; } xDxState::xDxState() { } xDxState::~xDxState() { } } <file_sep>//#pragma once //#include "xStd.h" //namespace KHJ_DX //{ // template< class T > void Swap(T* a, T* b) // { // T Temp; // Temp = *a; // *a = *b; // *b = Temp; // } // template<typename TContainer> // void stl_wipe(TContainer& container) // { // typename TContainer::iterator iter; // for (iter = container.begin(); iter != container.end(); ++iter) // { // delete *iter; // } // container.clear(); // } // // template<typename T> // void stl_wipe_vector(vector<T>& rVector) // { // vector<T> emptyData; // rVector.swap(emptyData); // } // // //////////////////////////////////////////////////////// // // 해당 객체를 sdl::map으로 관리한다 // //////////////////////////////////////////////////////// // template< class Child > class TTemplateMap // { // public: // typedef unordered_map <int, Child*> TemplateMap; // typedef typename TemplateMap::iterator TemplateMapItor; // TemplateMapItor TItor; // TemplateMap TMap; // int m_iCurIndex; // public: // // 초기화 한다. // virtual bool Init(); // // 인덱스를 통하여 객체를 리턴받는다. // virtual Child* const GetPtr(int index); // // 객체이름으로 객체를 리턴받는다. // virtual Child* const GetPtr(const TCHAR* szName); // // 객체 포인터로 저장된 인덱스를 리턴받는다. // virtual int GetID(Child*); // // 객체이름으로 저장된 인덱스를 리턴받는다. // virtual int GetID(const TCHAR* szName); // // 전체 저장된 갯수를 얻는다. // virtual int Count(); // // 전체 저장된 객체를 삭제한다. // virtual bool Release(); // // 인덱스에 해당하는 객체를 삭제한다. // virtual bool Delete(int iIndex); // // pPoint에 해당하는 객체를 삭제한다. // virtual bool Delete(Child *pPoint); // virtual bool Frame(); // virtual bool Render(ID3D11DeviceContext* pContext); // // public: // TTemplateMap(); // virtual ~TTemplateMap(); // }; // // template < class Child > // int TTemplateMap< Child >::GetID(Child* pChild) // { // int iIndex = -1; // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (pChild == pPoint) // { // iIndex = (*itor).first; // break; // } // } // return iIndex; // } // template < class Child > // int TTemplateMap< Child >::GetID(const TCHAR* szName) // { // int iIndex = -1; // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (!_tcsicmp(pPoint->m_szName.c_str(), szName)) // { // iIndex = (*itor).first; // break; // } // } // return iIndex; // } // // template < class Child > // bool TTemplateMap< Child >::Init() // { // m_iCurIndex = 0; // TMap.clear(); // return true; // } // template < class Child > // int TTemplateMap< Child >::Count() // { // return (int)TMap.size(); // } // // template < class Child > // bool TTemplateMap< Child >::Frame() // { // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (pPoint) // pPoint->Frame(); // } // return true; // } // template < class Child > // bool TTemplateMap< Child >::Render(ID3D11DeviceContext* pContext) // { // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (pPoint) // pPoint->Render(pContext); // } // return true; // } // template < class Child > // bool TTemplateMap< Child >::Release() // { // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (pPoint) // pPoint->Release(); // else // return false; // delete pPoint; // } // TMap.clear(); // m_iCurIndex = 0; // return true; // } // template < class Child > // Child* const TTemplateMap< Child >::GetPtr(int iIndex) // { // TemplateMapItor itor = TMap.find(iIndex); // if (itor == TMap.end()) return NULL; // Child *pPoint = (*itor).second; // return pPoint; // } // template < class Child > // Child* const TTemplateMap< Child >::GetPtr(const TCHAR* szName) // { // for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) // { // Child *pPoint = (Child *)(*itor).second; // if (!_tcsicmp(pPoint->m_szName.c_str(), szName)) // { // return pPoint; // } // } // return NULL; // } // template < class Child > // bool TTemplateMap< Child >::Delete(int iIndex) // { // Child* const pPoint = GetPtr(iIndex); // if (pPoint) // { // pPoint->Release(); // TMap.erase(iIndex); // } // return true; // } // template < class Child > // bool TTemplateMap< Child >::Delete(Child *pPoint) // { // if (pPoint) // { // pPoint->Release(); // TMap.erase(GetID(pPoint)); // } // return true; // } // template < class Child > // TTemplateMap< Child >::TTemplateMap() // { // m_iCurIndex = 0; // TMap.clear(); // } // // template < class Child > // TTemplateMap< Child >::~TTemplateMap() // { // Release(); // } //}<file_sep>#include "S_DebugString.h" #include "S_Lock.h" void S_DebugString::Print(const char* fmt, ...) { if (m_hList == NULL) { return; } { S_Lock Lock(this); va_list arg; va_start(arg, fmt); char buf[MAX_ARRAY] = { 0, }; vsprintf_s(buf, fmt, arg); SendMessage(m_hList, LB_ADDSTRING, 0, (LPARAM)S_Debug.GetMbToWcs(buf)); int iIndex = SendMessage(m_hList, LB_GETCOUNT, 0, 0); if (iIndex > 30) { SendMessage(m_hList, LB_RESETCONTENT, 0, 0); } va_end(arg); } } WCHAR* S_DebugString::GetMbToWcs(const char* strMsg) { TCHAR Msg[4096] = { 0, }; { S_Lock Lock(this); int iRen = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, 0, 0); ConvertAnsiStringToWideCch(Msg, strMsg, iRen); } return Msg; } char* S_DebugString::GetWcsToMbs(const WCHAR* strMsg) { char Msg[4096] = { 0, }; { S_Lock Lock(this); int iRen = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, 0, 0, NULL, NULL); ConvertWideStringToAnsiCch(Msg, strMsg, iRen); } return Msg; } HRESULT S_DebugString::ConvertWideStringToAnsiCch(char* msg, const WCHAR* strMsg, int iRen) { { S_Lock Lock(this); if (msg == NULL || strMsg == NULL || iRen < 1) { return E_INVALIDARG; } int i_Ret = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, msg, iRen, NULL, NULL); if (i_Ret == 0) { return E_FAIL; } return S_OK; } } HRESULT S_DebugString::ConvertAnsiStringToWideCch(WCHAR* msg, const char* strMsg, int iRen) { { S_Lock Lock(this); if (msg == NULL || strMsg == NULL || iRen < 1) { return E_INVALIDARG; } int i_Ret = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, msg, iRen); if (iRen == 0) { return E_FAIL; } msg[iRen - 1] = 0; } return S_OK; } void S_DebugString::S_Error(bool bPrint) { { S_Lock Lock(this); if (WSAGetLastError() != WSA_IO_PENDING) { char* lpMsgbuf; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&lpMsgbuf, 0, NULL); if (bPrint) { MessageBoxA(NULL, lpMsgbuf, "ERROR", MB_OK); } else { OutputDebugStringA((char*)lpMsgbuf); } LocalFree(lpMsgbuf); } } } bool S_DebugString::Init() { m_hList = NULL; return true; } bool S_DebugString::Release() { return true; } S_DebugString::S_DebugString() { } S_DebugString::~S_DebugString() { } <file_sep>#include <iostream> using namespace std; template<class T> class Bag { T*elem; int size; int max_size; public: Bag() :elem(0), size(0), max_size(1) {} void add(T t) { T* tmp; if (size + 1 >= max_size) { max_size *= 2; tmp = new T[max_size]; for (int i = 0; i < size; i++) tmp[i] = elem[i]; tmp[size++] = t; delete[]elem; elem = tmp; } else elem[size++] = t; } void print() { for (int i = 0; i < size; i++) cout << elem[i] << " "; cout << endl; } }; //포인터 유형에 대한 템플릿 부분 특수화. //NULL을 검사하도록 컬렉션이 수정 및 저장소 유형 template<class T> class Bag<T*> { T* elem; int size; int max_size; public: Bag() : elem(0), size(0), max_size(1) {} void add(T* t) { T* tmp; if (t == NULL) { //Check for NULL cout << " Null pointer!" << endl; return; } if (size + 1 >= max_size) { max_size *= 2; tmp = new T[max_size]; for (int i = 0; i < size; i++) tmp[i] = elem[i]; tmp[size++] = *t; //Dereference delete[]elem; elem = tmp; } else elem[size++] = *t; //Dereference } void print() { for (int i = 0; i < size; i++) cout << elem[i] << " "; cout << endl; } }; int main() { Bag<int> xi; Bag<char> xc; Bag<int*> xp;//Uses partial specialization for pointer types. xi.add(10); xi.add(9); xi.add(8); xi.print(); xc.add('a'); xc.add('b'); xc.add('c'); xc.print(); int i = 3, j = 87, *p = new int[2]; *p = 8; *(p + 1) = 100; xp.add(&i); xp.add(&j); xp.add(p); xp.add(p + 1); p = NULL; xp.add(p); xp.print(); } <file_sep>////순차 정렬(Sequential Sort) ///*순차 정렬은 맨 앞에서 부터 제일 작은 원소를 배치하게 만들어 나가는 알고리즘이다*/ //#include <stdio.h> //#include<conio.h> // //#define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 // // //void SequenceSort(int *base, int n); //int main(void) //{ // int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; // SequenceSort(arr, 10); // _getch(); // return 0; //} //void ViewArr(int *arr, int n); //void SequenceSort(int *base, int n) //{ // int i, j; // ViewArr(base, n);//현재 상태 출력 // for (i = 0; i<n; i++) // { // for (j = i; j<n; j++) // { // if (base[i]>base[j])//앞쪽 원소가 더 크면 // { // SWAP(base[i], base[j]);//교환 // ViewArr(base, n);//상태 출력 // } // } // } //} // //void ViewArr(int *arr, int n) //{ // int i = 0; // for (i = 0; i<n; i++) // { // printf("%2d ", arr[i]); // } // printf("\n"); //} // <file_sep>#pragma once #include "Window.h" #include "Timer.h" class Core : public Window { Timer m_Timer; public: bool GameInit(); bool GameRun(); bool GameRelease(); public: Core(); virtual ~Core(); }; <file_sep>#include <iostream> #include <typeinfo.h> #include <vector> #include <queue> // 큐는 재정의 해서 쓰느게 좋다 // RTTI RUN TIME TYPE INFORMATION #define STRING(S) #S // # 스트링화 연산자 #define LINK(i,j) i##j // ## 연결 연산자 #define DECLARE_CLASSNAME static char IpszClassName[] // 스태틱 함수 #define IMPLEMENT_CLASSNAME(S) char S##::IpszClassName[] = (#S); // 스태틱 초기화 #define RUNTIME_CLASS(S) &S::class##S; // 어떤놈의 주소를 연결할꺼다. #define DECLARE_DYNAMIC(S) static CRuntimeClass class##S; #define DECLARE_DYN_CREATE(S) static CObject* CreateObject(); #define IMPLEMENT_DYN_CREATE(S) static CObject* CreateObject() {return new S;}; #define IMPLEMENT_DYNMIC(S) CRuntimeClass S::class##S = {#S,sizeof(S),S::CreateObject }; // &(CMyClass::classCMyClass); class CObject; // 전방선언 struct CRuntimeClass { char m_ipszClassName[21]; int m_iObjectSize; CObject* (*pfnCreateObject)(); // 함수 포인터 CObject* CreateObject() { return (*pfnCreateObject)(); // CMyClass를 호출하고 있네 } }; // 동적 클래스 생성 // MFC 기반 class CObject { public: static CRuntimeClass classCObject; // CRuntimeClass를 들고 있는거다 DECLARE_CLASSNAME; // CObject에 대한 CMyclass 이다 virtual char* GetClassName() const { return NULL; } virtual ~CObject() {} static CObject* CreateObject(); protected: // 생성자를 막은건 파생해서만 사용가능 CObject() {} }; IMPLEMENT_CLASSNAME(CObject); CObject* CObject::CreateObject() { return NULL; } IMPLEMENT_DYNMIC(CObject); //CRuntimeClass CObject::classCObject = { "CObject" ,sizeof(CObject),NULL }; // 외부에서 초기화 32번줄 class TsessionMgr // 라이브러리 안에 있는거다 { public: std::queue<CObject*>m_StaticQueue; std::vector<CObject*>m_userlist; void Create(CRuntimeClass* pRTC) { for (int iQueue = 0; iQueue < 1000; iQueue++) // 1000개의 CMyClass가 들어가 있는거다 // 정적화 { CObject* pObj = pRTC->CreateObject(); m_StaticQueue.push(pObj); } } CObject* CreateNewSession() { CObject* newSession = (CObject*)m_StaticQueue.front(); m_userlist.push_back(newSession); return newSession; } CObject* RemoveSession(CObject* pSession) { //m_userlist.push_back(newSession); itor 사용해라 m_StaticQueue.push(pSession); } }; TsessionMgr g_SessionMgr; // --------------------------벽-------------------------------- 이 있다 // 매크로로 사용하면 정말 편하다. class CMyClass : public CObject { public: DECLARE_CLASSNAME; DECLARE_DYNAMIC(CMyClass); //static CRuntimeClass classCMyClass; DECLARE_DYN_CREATE(CMyClass); //static CObject* CreateObject(); // 함수 포인터 /*virtual char* GetClassName() const { return IpszClassName; }*/ }; IMPLEMENT_CLASSNAME(CMyClass); IMPLEMENT_DYN_CREATE(CMyClass); //IMPLEMENT_CLASSNAME(CMyClass); IMPLEMENT_DYNMIC(CMyClass); //CObject* CMyClass::CreateObject() { return new CMyClass; }; //CRuntimeClass CMyClass::classCMyClass = { "CMyClass" ,sizeof(CMyClass),CMyClass::CreateObject }; void main() { //g_SessionMgr.Create(RUNTIME_CLASS(CMyClass)); CRuntimeClass* pRTCMyClass = RUNTIME_CLASS(CMyClass); g_SessionMgr.Create(pRTCMyClass); /*CObject* p = pRTCMyClass->CreateObject(); CMyClass* pChild = (CMyClass*)p; std::cout << pChild->IpszClassName << std::endl; delete p;*/ #pragma region LINK&STRING std::cout << STRING(kgca) << std::endl; char m_szValue[] = "kgcagame"; std::cout << LINK(m_sz, Value) << std::endl; // 잘 이용하면 조건을 잘걸어서 변수를 사용할 수 있다 std::cout << m_szValue << std::endl; int LINK(m_i, Data) = 0; // int m_iData = 0; #pragma endregion LINK&STRING //#pragma region aaa // CBase parent; // CChild child; // // const type_info& tBase = typeid(parent); // const type_info& tChild = typeid(child); // // std::cout << tBase.name() << "{ }" << std::endl; // std::cout << typeid(parent).name() << std::endl; // // std::cout << tChild.name() << std::endl; // std::cout << typeid(child).name() << std::endl; // // std::cout << tBase.before(tChild) << std::endl; // std::cout << tChild.before(tBase) << std::endl; // std::cout << (tChild == tBase) << std::endl; //#pragma endregion aaa } // //#include <iostream> //#include <typeinfo.h> ////#include <list> //#include <queue> // //#define DECLARE_CLASSNAME static char lpszClassName[] //#define IMPLEMENT_CLASSNAME(s) char s##::lpszClassName[] = (#s); // //#define DECLARE_DYNCREATE static CObject* CreateObject(); //#define IMPLEMENT_DYNCREATE(s) CObject* s::CreateObject() {return new s;} // //#define DECLARE_DYNAMIC(s) static CRuntimeClass class##s; //#define IMPLEMENT_DYNAMIC(s) CRuntimeClass s::class##s={ #s, sizeof(s), s::CreateObject } // //#define DECLARE_DYNCLASS_CREATE CRuntimeClass* GetRuntimeClass() const; //#define IMPLEMENT_DYNCLASS_CREATE(s) CRuntimeClass* s::GetRuntimeClass() const{return &class##s;} // //#define RUNTIME_CLASS(s) &s::class##s; // // //class CObject; ////핵심!!! //class CRuntimeClass //{ //public: // char m_lpszClassName[21]; // int m_iObjectSize; // CObject* (*pfnCreateObject)(); // CObject* CreateObject() // { // return (*pfnCreateObject)(); // } //}; // //class CObject //{ //public: // static CRuntimeClass classCObject; //DECLARE_DYNAMIC(CObject); // static char lpszClassName[]; //DECLARE_CLASSNAME; // virtual CRuntimeClass* GetRuntimeClass() const // { // return NULL; // } // virtual ~CObject() {} //protected: // CObject() {} //}; // //char CObject::lpszClassName[] = "CObject"; // IMPLEMENT_CLASSNAME(CObject); //CRuntimeClass CObject::classCObject = { "CObject", sizeof(CObject), NULL }; // //class Mgr //{ //public: // // std::queue<CObject*> m_StaticQueue; // std::queue<CObject*> m_UserQueue; // // void Create(CRuntimeClass* pRTC) // { // for (int iQueue = 0; iQueue < 1000; iQueue++) { // CObject* pObj = pRTC->CreateObject(); // m_StaticQueue.push(pObj); // } // } // // CObject* CreateUser() // { // CObject* User = (CObject*)m_StaticQueue.front(); // m_UserQueue.push(User); // return User; // } //}; // //Mgr g_mgr; // ////이 위는 라이브러리에 있는 클래스 ////----------------------------------------------------------------------------------// ////이 아래는 프로그램 코드 // // //class CUser : public CObject //{ //public: // DECLARE_CLASSNAME; /*static char lpszClassName[]; */ // DECLARE_DYNCREATE; /*static CObject* CreateObject(); */ // DECLARE_DYNCLASS_CREATE; /*CRuntimeClass* GetRuntimeClass() const; */ // DECLARE_DYNAMIC(CUser); /*static CRuntimeClass classCUser; */ //protected: // CUser() {} //}; // //IMPLEMENT_CLASSNAME(CUser); /*char CUser::lpszClassName[] = ("CUser"); */ //IMPLEMENT_DYNCREATE(CUser); /*CObject* CUser::CreateObject() { return new CUser; } */ //IMPLEMENT_DYNCLASS_CREATE(CUser); /*CRuntimeClass* CUser::GetRuntimeClass() const { return &classCUser; } */ //IMPLEMENT_DYNAMIC(CUser); /*CRuntimeClass CUser::classCUser = { "CUser", sizeof(CUser), CUser::CreateObject }; */ // //class test : public CObject //{ //public: // DECLARE_CLASSNAME; /*static char lpszClassName[]; */ // DECLARE_DYNCREATE; /*static CObject* CreateObject(); */ // DECLARE_DYNCLASS_CREATE; /*CRuntimeClass* GetRuntimeClass() const; */ // DECLARE_DYNAMIC(test); /*static CRuntimeClass classCUser; */ //protected: // test() {} //}; // //IMPLEMENT_CLASSNAME(test); /*char CUser::lpszClassName[] = ("CUser"); */ //IMPLEMENT_DYNCREATE(test); /*CObject* CUser::CreateObject() { return new CUser; } */ //IMPLEMENT_DYNCLASS_CREATE(test); /*CRuntimeClass* CUser::GetRuntimeClass() const { return &classCUser; } */ //IMPLEMENT_DYNAMIC(test); /*CRuntimeClass CUser::classCUser = { "CUser", sizeof(CUser), CUser::CreateObject }; */ // // //int main() //{ // CRuntimeClass* pRTCMyClass = RUNTIME_CLASS(CUser); // g_mgr.Create(pRTCMyClass); // // //CRuntimeClass* pRTCMyClass = &CUser::classCUser; //RUNTIME_CLASS(CUser); // //CObject* p = pRTCMyClass->CreateObject(); // // g_mgr.CreateUser(); // g_mgr.CreateUser(); // g_mgr.CreateUser(); // // test* pPoint; // CUser* pCUser; // // for (int i = 0; i < 2; i++) { // pPoint = (test*)(g_mgr.m_UserQueue.front()); // std::cout << pPoint->lpszClassName << std::endl; // g_mgr.m_UserQueue.pop(); // //delete (CUser*)(CUser*)(g_mgr.m_UserQueue.front()); // } // // pCUser = (CUser*)(g_mgr.m_UserQueue.front()); // std::cout << pCUser->lpszClassName << std::endl; // g_mgr.m_UserQueue.pop(); // //}<file_sep>#include "TTemporary.h" TTemporary::TTemporary(char* _name, int time, int pay) :TEmployee(_name) { time = _time; pay = _pay; } TTemporary::GetPay() { return time * pay; } <file_sep>#include "TRegion.h" int TRegion::notation = TRegion::POINT_POINT; TRegion::TRegion(void) { SetRect(0, 0, 0, 0); //영역을 0으로 초기화 } TRegion::TRegion(int I, int t, int r,int b) { SetRect(I, t, r, b); //영역을 주어진 값으로 초기화 } void TRegion::SetRect(int I, int t, int r, int b) { m_iLeft = I; //시작점의 x좌표 설정 m_iTop = t; //시작점의 y좌표 설정 m_iRight = r; //끝점의 x좌표 설정 m_iBottom = b; //끝점의 y좌표 설정 } int TRegion::GetWidth()const { return m_iRight - m_iLeft; } const int TRegion::GetHeight() const { return m_iBottom - m_iTop; } void TRegion::GetStartPoint(int &x, int &y)const { x = m_iLeft; // 시작점의 x좌표 얻기 y = m_iTop; //시작점의 y좌표 얻기 } void TRegion::GetEndPoint(int &x, int &y)const { x = m_iRight; //끝점의 x좌표 얻기 y = m_iBottom; //끝점의 y좌표 얻기 } void TRegion::GetCenterPoint(int &x, int &y)const { x = (m_iLeft + m_iRight) / 2; //중심점의 x좌표얻기 y = (m_iTop + m_iBottom) / 2; //중심점의 y좌표 얻기 } bool TRegion::IsPointInRegion(int x, int y)const { return(x >= m_iLeft && x <= m_iRight && y >= m_iTop && y <= m_iBottom); } void TRegion::Move(int x, int y) { m_iLeft += x; //시작점의 x좌표 이동 m_iRight += x; //끝점의 x좌표 이동 m_iTop += y; //시작점의 y좌표 이동 m_iBottom += y; //끝점의 y좌표 이동 } void TRegion::Resize(int width, int height) { int x, y; GetCenterPoint(x, y);// 중심점 좌표 얻기 m_iLeft = x - width / 2; //중심으로부터 가로길이 절반만큼 이동 m_iTop = y - height / 2; //중심으로부터 세로길이 절반만큼 이동 m_iRight = m_iLeft + width; //가로길이가 width가 되도록 조절 m_iBottom = m_iTop + height; //세로길이가 height가 되도록 조절 } void TRegion::UnionRegion(const TRegion &r1, const TRegion &r2) { m_iLeft = r1.m_iLeft < r2.m_iLeft ? r1.m_iLeft : r2.m_iLeft; m_iRight = r1.m_iRight > r2.m_iRight ? r1.m_iRight : r2.m_iRight; m_iTop = r1.m_iTop < r2.m_iTop ? r1.m_iTop : r2.m_iTop; m_iBottom = r1.m_iBottom > r2.m_iBottom ? r1.m_iBottom : r2.m_iBottom; } bool TRegion::IntersectRegion(const TRegion &r1, const TRegion &r2) { m_iLeft = r1.m_iLeft > r2.m_iLeft ? r1.m_iLeft : r2.m_iLeft; m_iRight = r1.m_iRight < r2.m_iRight ? r1.m_iRight : r2.m_iRight; m_iTop = r1.m_iTop > r2.m_iTop ? r1.m_iTop : r2.m_iTop; m_iBottom = r1.m_iBottom < r2.m_iBottom ? r1.m_iBottom : r2.m_iBottom; // 한점 또는 라인이 중첩되었을 때 교차로 판정하지 않았다. // 교집합이 존재하지 않는 경우 if (m_iLeft >= m_iRight || m_iTop >= m_iBottom) { m_iLeft = m_iTop = m_iRight = m_iBottom = 0; return false; } return true; } void TRegion::SetNotation(int n) { notation = n; } void TRegion::Show(void) { if (notation == POINT_POINT) // 시작점/끝점 형식 { printf("(%d, %d), (%d, %d)\n", m_iLeft, m_iTop, m_iRight, m_iBottom); } else // 시작점/가로, 세로/길이 형식 { printf("(%d, %d), [%d x %d]\n", m_iLeft, m_iTop, GetWidth(), GetHeight()); } } <file_sep>#include<stdio.h> #include<conio.h> //입력 받은 개수로 다이아 몬드 만들기 void main() { int line = 0; scanf_s("%d", &line); for (int sum = 0; sum < line-1; sum++) { for (int sum1 = 0; sum1 < line-sum-1; sum1++) { printf(" "); } for (int sum2 = 0; sum2 <= sum*2; sum2++) { printf("*"); } printf("\n"); } for (int sum = 0; sum < line; sum++) { for (int sum1 = 0; sum1 < sum; sum1++) { printf(" "); } for (int sum2 = 0; sum2 < 2*(line-sum)-1; sum2++) { printf("*"); } printf("\n"); } _getch(); }<file_sep>#pragma once #include<iostream> using std::endl; using std::cout; class TEmployee { protected: char name[20]; public: const char* GetName(); virtual int GetPay() = 0; public: TEmployee(char* _name); ~TEmployee(); }; <file_sep>//선택 정렬(Selection Sort) /*제일 큰 값을 찾아 맨 뒤의 요소와 교체하는 방법을 반복하여 전체를 정렬하는 알고리즘이다. 반대로도 제일 작은 값을 찾아 맨 앞의 요소와 교체하는 방법을 반복할 수도 있다.*/ #include <stdio.h> #include <conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 void SelectionSort(int *base, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; SelectionSort(arr, 10); _getch(); return 0; } void ViewArr(int *arr, int n); void SelectionSort(int *base, int n) { int i, j; int maxi; ViewArr(base, n);//현재 상태 출력 for (i = n; i>1; i--)//정렬할 범위를 축소해 나갑니다. { maxi = 0; for (j = 1; j<i; j++) { if (base[maxi]<base[j])//더 큰 원소를 만나면 { maxi = j; } } SWAP(base[maxi], base[i - 1]);//교환 ViewArr(base, n);//상태 출력 } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#pragma once #include "SServer.h" #include "SCHATAccept.h" #include "SChatUser.h" #include "SChatPacketPool.h" class SChatSvr : public SSingleton<SChatSvr>, public SServer { private: friend class SSingleton<SChatSvr>; public: SChatPacketPool m_PacketPool; SCHATAccept m_Acceptor; list<SChatUser*> m_UserList; typedef list<SChatUser*>::iterator m_ListItor; int m_iUserCount; public: bool Init(); bool Release(); bool Run(); LRESULT MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void Print(char*fmt, ...); bool AddUser(SOCKET socket, SOCKADDR_IN address); void DeleteUser(SOCKET socket); void DeleteUser(SChatUser* pUser); void Broadcastting(char* msg, WORD code, SOCKET SendSocket = 0); void Broadcastting(S_PACKET* pUserData); void Broadcastting(UPACKET* pPacket,SOCKET pSendUser=NULL); public: SChatSvr(void); virtual ~SChatSvr(void); }; #define I_Server SChatSvr::GetInstance() <file_sep>#include<stdio.h> void main(int argc, char*argv[]) { for(int i = 0; i < argc; i++) { printf("string=%s\n", argv[i]); } }<file_sep>#include "TPacket.h" void TPacket::PutData(const char* pData,int iSize) { m_uPacket.ph.len += iSize; memcpy(m_pOffset, pData, iSize); m_pOffset += iSize; } TPacket& TPacket::operator<< (const char* data) { int iSize = strlen(data)+1; PutData(data, iSize); return *this; } TPacket& TPacket::operator<< (int data) { PutData((char*)&data, sizeof(int)); return *this; } TPacket& TPacket::operator<< (string data) { PutData(data.c_str(), data.size()); return *this; } void TPacket::GetData(const char* pData, int iSize) { memcpy(const_cast<char*>(pData),m_pOffset,iSize); m_pOffset += iSize; } TPacket& TPacket::operator>> (string& data) { int iSize = strlen(m_pOffset) + 1; char buffer[256] = { 0, }; GetData(buffer, iSize); data = buffer; return *this; } TPacket& TPacket::operator>> (const char* data) { int iSize = strlen(m_pOffset) + 1; GetData(data, iSize); return *this; } TPacket& TPacket::operator>> (int& data) { GetData((char*)&data, sizeof(int)); return *this; } TPacket::TPacket(WORD type) { ZeroMemory(&m_uPacket, sizeof(UPACKET)); m_uPacket.ph.type = type; m_pOffset = m_uPacket.msg; } TPacket::TPacket() { ZeroMemory(&m_uPacket, sizeof(UPACKET)); m_pOffset = m_uPacket.msg; } TPacket::~TPacket() { } <file_sep>#pragma once #include "xShape.h" struct xMapDesc { int iNumCols; int iNumRows; float fDistance; float fScaleHeight; T_STR szTextureFile; T_STR szShaderFile; }; struct TIndexTable { int faceIndex[6]; TIndexTable() { faceIndex[0] = -1; faceIndex[1] = -1; faceIndex[2] = -1; faceIndex[3] = -1; faceIndex[4] = -1; faceIndex[5] = -1; } }; class xMap : public xShape { public: xMapDesc m_xMapDesc; int m_iNumRows; int m_iNumCols; int m_iNumCellRows; int m_iNumCellCols; int m_iNumFace; int m_iNumVertices; float m_fCellDistance; float m_fScaleHeight; vector<float> m_fHeightList; vector<D3DXVECTOR3> m_FaceNormalList; vector<TIndexTable> m_NormalLooupTabel; public: float Lerp(float fStart, float fEnd, float fTangent); virtual HRESULT CreateVertexData() override; virtual HRESULT CreateIndexData() override; D3DXVECTOR2 GetTextureOfVertex(float fU, float fV); D3DXVECTOR3 GetNormalOfVertex(int iIndex); D3DXVECTOR4 GetColorOfVertex(int iIndex); float GetHeightOfVertex(int iIndex); // 기하쉐이더(기본값은 구를 생성) 생략함. HRESULT LoadGeometryShader(T_STR szName) { return S_OK; }; bool GenVertexNormal(); bool CreateHeightMap( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, T_STR szName); bool CreateMap(xMapDesc desc); bool Load(ID3D11Device* pDevice,xMapDesc desc); bool Init(); bool Frame(); bool Render(ID3D11DeviceContext* pContext); bool Release(); public: float GetHeightmap(int row, int col); float GetHeight(float fPosX, float fPosY); void InitFaceNormals(); void CalcFaceNormals(); void GenNormalLookupTable(); void CalcPerVertexNormalsFastLookup(); D3DXVECTOR3 ComputeFaceNormal(DWORD i0, DWORD i1, DWORD i2); public: xMap(); virtual ~xMap(); }; <file_sep>#pragma once #include "S_Std.h" #include "S_Protocol.h" class S_StreamPacket { public: list<PACKET> PacketList; typedef list<PACKET>::iterator itor; public: UPACKET* m_pPacket; int m_iStartPos; int m_iWritePos; int m_iReadPos; char RecvBuffer[MAX_RECV]; public: void Put(char* recvBuffer, int Size, S_SvrUser* = NULL); public: S_StreamPacket(); virtual ~S_StreamPacket(); }; <file_sep>#pragma once #include "TObjStd.h" #include <tchar.h> enum T_VERTEX_USAGE { T_USAGE_POSITION = 0, T_USAGE_BLENDWEIGHT = 1, T_USAGE_BLENDINDICES = 2, T_USAGE_NORMAL = 3, T_USAGE_TEXCOORD = 5, T_USAGE_TANGENT = 6, T_USAGE_BINORMAL = 7, T_USAGE_COLOR = 10, }; enum T_DECL_TYPE { T_TYPE_FLOAT1 = 0, // 1D float expanded to (value, 0., 0., 1.) T_TYPE_FLOAT2 = 1, // 2D float expanded to (value, value, 0., 1.) T_TYPE_FLOAT3 = 2, // 3D float expanded to (value, value, value, 1.) T_TYPE_FLOAT4 = 3, // 4D float T_TYPE_D3DCOLOR = 4, // 4D packed unsigned bytes mapped to 0. to 1. range // Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A) T_TYPE_UBYTE4 = 5, // 4D unsigned byte T_TYPE_UBYTE4N = 8, // Each of 4 bytes is normalized by dividing to 255.0 T_TYPE_SHORT4N = 10, // 4D signed short normalized (v[0]/32767.0,v[1]/32767.0,v[2]/32767.0,v[3]/32767.0) // Note: There is no equivalent to D3DDECLTYPE_DEC3N (14) as a DXGI_FORMAT T_TYPE_FLOAT16_2 = 15, // Two 16-bit floating point values, expanded to (value, value, 0, 1) T_TYPE_FLOAT16_4 = 16, // Four 16-bit floating point values T_TYPE_UNUSED = 17, // When the type field in a decl is unused. // These are extensions for DXGI-based versions of Direct3D T_TYPE_DXGI_R10G10B10A2_UNORM = 32 + DXGI_FORMAT_R10G10B10A2_UNORM, T_TYPE_DXGI_R11G11B10_FLOAT = 32 + DXGI_FORMAT_R11G11B10_FLOAT, T_TYPE_DXGI_R8G8B8A8_SNORM = 32 + DXGI_FORMAT_R8G8B8A8_SNORM, T_TYPE_XBOX_R10G10B10_SNORM_A2_UNORM = 32 + 189, }; #pragma pack(push,4) struct T_VERTEX_ELEMENT { WORD Stream; // Stream index WORD Offset; // Offset in the stream in bytes BYTE Type; // Data type BYTE Method; // Processing method BYTE Usage; // Semantics BYTE UsageIndex; // Semantic index }; #pragma pack(pop) struct TVertexFormat { public: TVertexFormat() : m_bPosition(true), m_bNormal(true), m_bSkinData(false), m_bTangent(false), m_bBinormal(false), m_bVertexColor(true), m_uUVSetCount(1), m_uUVSetSize(2) { } bool m_bPosition; bool m_bNormal; bool m_bTangent; bool m_bBinormal; bool m_bSkinData; bool m_bVertexColor; UINT m_uUVSetCount; UINT m_uUVSetSize; }; struct ExportMeshVertex { public: ExportMeshVertex() { Initialize(); } void Initialize() { ZeroMemory(this, sizeof(ExportMeshVertex)); BoneWeights.x = 1.0f; } UINT DCCVertexIndex; D3DXVECTOR3 Position; D3DXVECTOR3 Normal; D3DXVECTOR3 SmoothNormal; D3DXVECTOR3 Tangent; D3DXVECTOR3 Binormal; D3DXVECTOR4 BoneIndices; D3DXVECTOR4 BoneWeights; D3DXVECTOR4 TexCoords[8]; D3DXVECTOR4 Color; ExportMeshVertex* pNextDuplicateVertex; bool Equals(const ExportMeshVertex* pOtherVertex) const; }; typedef std::vector< ExportMeshVertex* > ExportMeshVertexArray; class ExportVB { public: ExportVB() : m_uVertexCount(0), m_uVertexSizeBytes(0) { } ~ExportVB() { } void SetVertexSize(DWORD uByteCount) { m_uVertexSizeBytes = uByteCount; } DWORD GetVertexSize() const { return m_uVertexSizeBytes; } void SetVertexCount(size_t uVertexCount) { m_uVertexCount = uVertexCount; } size_t GetVertexCount() const { return m_uVertexCount; } void Allocate(); uint8_t* GetVertex(size_t uIndex); const uint8_t* GetVertex(size_t uIndex) const; uint8_t* GetVertexData() { return m_pVertexData.get(); } const uint8_t* GetVertexData() const { return m_pVertexData.get(); } size_t GetVertexDataSize() const { return m_uVertexSizeBytes * m_uVertexCount; } void ByteSwap(const T_VERTEX_ELEMENT* pVertexElements, const size_t dwVertexElementCount); protected: DWORD m_uVertexSizeBytes; size_t m_uVertexCount; std::unique_ptr<uint8_t[]> m_pVertexData; }; class ExportIB { public: ExportIB() : m_uIndexCount(0), m_dwIndexSize(2) { } ~ExportIB() { } void SetIndexSize(DWORD dwIndexSize) { assert(dwIndexSize == 2 || dwIndexSize == 4); m_dwIndexSize = dwIndexSize; } DWORD GetIndexSize() const { return m_dwIndexSize; } void SetIndexCount(size_t uIndexCount) { m_uIndexCount = uIndexCount; } size_t GetIndexCount() const { return m_uIndexCount; } void Allocate(); DWORD GetIndex(size_t uIndex) const { if (m_dwIndexSize == 2) { auto pIndexData16 = reinterpret_cast<const WORD*>(m_pIndexData.get()); return pIndexData16[uIndex]; } else { auto pIndexData32 = reinterpret_cast<const DWORD*>(m_pIndexData.get()); return pIndexData32[uIndex]; } } void SetIndex(size_t uIndex, DWORD dwData) { if (m_dwIndexSize == 2) { auto pIndexData16 = reinterpret_cast<WORD*>(m_pIndexData.get()); pIndexData16[uIndex] = static_cast<WORD>(dwData); } else { auto pIndexData32 = reinterpret_cast<DWORD*>(m_pIndexData.get()); pIndexData32[uIndex] = dwData; } } uint8_t* GetIndexData() { return m_pIndexData.get(); } const uint8_t* GetIndexData() const { return m_pIndexData.get(); } size_t GetIndexDataSize() const { return m_uIndexCount * m_dwIndexSize; } void ByteSwap(); protected: DWORD m_dwIndexSize; size_t m_uIndexCount; std::unique_ptr<uint8_t[]> m_pIndexData; }; class TExpMesh { public: enum OptimizationFlags { COMPRESS_VERTEX_DATA = 1, FLIP_TRIANGLES = 2, FORCE_SUBD_CONVERSION = 4, CLEAN_MESHES = 8, VCACHE_OPT = 16, }; bool m_x2Bias; std::vector< T_VERTEX_ELEMENT > m_VertexElements; std::vector< D3D11_INPUT_ELEMENT_DESC > m_InputLayout; std::unique_ptr<ExportVB> m_pVB; std::unique_ptr<ExportIB> m_pIB; std::unique_ptr<D3DXVECTOR3[]> m_pVBPositions; std::unique_ptr<D3DXVECTOR3[]> m_pVBNormals; std::unique_ptr<D3DXVECTOR2[]> m_pVBTexCoords; public: // 2018 std::vector< T_STR > m_InfluenceNames; std::unordered_map<T_STR, D3DXMATRIX> m_matBindPoseMap; TVertexFormat m_VertexFormat; void AddInfluence(T_STR InfluenceName, D3DXMATRIX& mat) { m_InfluenceNames.push_back(InfluenceName); m_matBindPoseMap[InfluenceName] = mat; m_VertexFormat.m_bSkinData = true; } void SetVertexUVCount(UINT uCount) { m_VertexFormat.m_uUVSetCount = uCount; } void SetVertexUVDimension(UINT uDimension) { m_VertexFormat.m_uUVSetSize = uDimension; } void SetVertexNormalCount(UINT uCount); void SetVertexColorCount(UINT uCount) { m_VertexFormat.m_bVertexColor = (uCount > 0); } size_t GetVertexDeclElementCount() const { return m_VertexElements.size(); } const T_VERTEX_ELEMENT& GetVertexDeclElement(size_t uIndex) const { return m_VertexElements[uIndex]; } void BuildVertexBuffer(ExportMeshVertexArray& VertexArray, DWORD dwFlags); void TransformPosition(D3DXVECTOR3* pDestPosition, const D3DXVECTOR3* pSrcPosition) const; void TransformAndWriteVector(BYTE* pDest, D3DXVECTOR3* normal, const D3DXVECTOR3& Src, DWORD dwDestFormat); void WriteColor(BYTE* pDest, const D3DXVECTOR4& Src, DWORD dwDestFormat); void TransformDirection(D3DXVECTOR3* pDestDirection, const D3DXVECTOR3* pSrcDirection) const; void TransformMatrix(D3DXMATRIX* pDestMatrix, const D3DXMATRIX* pSrcMatrix) const; float TransformLength(float fInputLength) const; public: // Sets unit scale for exporting all geometry - works with characters too. void SetUnitScale(const float fScale) { m_fUnitScale = fScale; } void SetZFlip(const bool bFlip) { m_bFlipZ = bFlip; } protected: float m_fUnitScale; bool m_bMaxConversion; bool m_bFlipZ; public: TExpMesh(); virtual ~TExpMesh(); }; <file_sep>#pragma once #include "DG_Shape.h" class ViewCube :public DG_Shape { public: bool CreateVertexData(); bool CreateIndexData(); HRESULT CreateResource(); public: ViewCube(); virtual ~ViewCube(); }; <file_sep>#include "S_Thread.h" unsigned int WINAPI S_Thread::HandleRunner(LPVOID parameter) { S_Thread* pThread = (S_Thread*)parameter; if (pThread) { pThread->Run(); } return 0; } void S_Thread::CreateThread() { if (m_bStarted) { return; } m_hThread = _beginthreadex(NULL, 0, HandleRunner, (LPVOID)this, 0, &m_iThreadID); m_bStarted = true; } bool S_Thread::Run() { return true; } S_Thread::S_Thread() { m_bStarted = false; } S_Thread::~S_Thread() { CloseHandle((HANDLE)m_hThread); } <file_sep>#pragma once #include "Header.h" #include "S_KHJWriter.h" #define KHJExport_CLASS_ID Class_ID(0x6fb548fb, 0x2a057187) // MAXSDK/help/gencid.exe 새로 발급받아야하는 플러그인 class S_KHJExporter : public SceneExport { public: S_KHJWriter g_Writer; public: //Constructor/Destructor S_KHJExporter(); ~S_KHJExporter(); int ExtCount(); // Number of extensions supported const TCHAR * Ext(int n); // Extension #n (i.e. "3DS") const TCHAR * LongDesc(); // Long ASCII description (i.e. "Autodesk 3D Studio File") const TCHAR * ShortDesc(); // Short ASCII description (i.e. "3D Studio") const TCHAR * AuthorName(); // ASCII Author name const TCHAR * CopyrightMessage(); // ASCII Copyright message const TCHAR * OtherMessage1(); // Other message #1 const TCHAR * OtherMessage2(); // Other message #2 unsigned int Version(); // Version number * 100 (i.e. v3.01 = 301) void ShowAbout(HWND hWnd); // Show DLL's "About..." box BOOL SupportsOptions(int ext, DWORD options); int DoExport(const TCHAR *name, ExpInterface *ei, Interface *i, BOOL suppressPrompts = FALSE, DWORD options = 0); }; class S_KHJClassDesc :public ClassDesc2 { public: virtual int IsPublic() { return TRUE; } virtual void* Create(BOOL /*loading = FALSE*/) { return new S_KHJExporter(); } virtual const TCHAR * ClassName() { return _T("KHJExporter100"); } virtual SClass_ID SuperClassID() { return SCENE_EXPORT_CLASS_ID; } virtual Class_ID ClassID() { return KHJExport_CLASS_ID; } virtual const TCHAR* Category() { return _T("KHJExporter"); } virtual const TCHAR* InternalName() { return _T("S_KHJClassDesc"); } // returns fixed parsable name (scripter-visible name) virtual HINSTANCE HInstance() { return hInstance; } // returns owning module handle }; ClassDesc2* GetExportDesc() { static S_KHJClassDesc theDesc; return &theDesc; } S_KHJExporter::S_KHJExporter() { } S_KHJExporter::~S_KHJExporter() { } int S_KHJExporter::ExtCount() { #pragma message(TODO("Returns the number of file name extensions supported by the plug-in.")) return 1; } const TCHAR *S_KHJExporter::Ext(int /*i*/) { #pragma message(TODO("Return the 'i-th' file name extension (i.e. \"3DS\").")) return _T("KHJ"); } const TCHAR *S_KHJExporter::LongDesc() { #pragma message(TODO("Return long ASCII description (i.e. \"Targa 2.0 Image File\")")) return _T("KHJExporter 2.0"); } const TCHAR *S_KHJExporter::ShortDesc() { #pragma message(TODO("Return short ASCII description (i.e. \"Targa\")")) return _T("KHJExporter"); } const TCHAR *S_KHJExporter::AuthorName() { #pragma message(TODO("Return ASCII Author name")) return _T("PROKVIP"); } const TCHAR *S_KHJExporter::CopyrightMessage() { #pragma message(TODO("Return ASCII Copyright message")) return _T(""); } const TCHAR *S_KHJExporter::OtherMessage1() { //TODO: Return Other message #1 if any return _T(""); } const TCHAR *S_KHJExporter::OtherMessage2() { //TODO: Return other message #2 in any return _T(""); } unsigned int S_KHJExporter::Version() { #pragma message(TODO("Return Version number * 100 (i.e. v3.01 = 301)")) return 100; } void S_KHJExporter::ShowAbout(HWND /*hWnd*/) { // Optional } BOOL S_KHJExporter::SupportsOptions(int /*ext*/, DWORD /*options*/) { #pragma message(TODO("Decide which options to support. Simply return true for each option supported by each Extension the exporter supports.")) return TRUE; } int S_KHJExporter::DoExport(const TCHAR *name, ExpInterface *ei, Interface *i, // Interface *i 막강한 인터페이스이다. BOOL suppressPrompts, DWORD options) { g_Writer.Initialize(i,name); g_Writer.Run(); g_Writer.Release(); return TRUE; }<file_sep>#include "LinkedList.h" #include "SStudent.h" void LinkedList::Insert()//»ðÀÔ { if (Head == NULL) { SStudent mData; mData.inputData(++MAX); Node* aData = new Node(mData); Head = aData; Tail = Head; Tail->pNext = NULL; return; } SStudent qData; qData.inputData(++MAX); Node* aData = new Node(qData); Tail->pNext = aData; Tail = Tail->pNext; Tail->pNext = NULL; } void LinkedList::Delete() { if (Head == NULL) return; else if (Head->pNext == NULL) delete Head; int select = 0; cin >> select; Node* tamp = Head; while (tamp->pNext != NULL) { if (tamp->iData.GetData().iindex == select) { break; } } Node* delNode = tamp->pNext; Node* nextNode = delNode->pNext; delete delNode; tamp->pNext = nextNode; } void LinkedList::Delete(Node* _preNode) { if (Head == NULL) { return; } else if (_preNode == NULL || _preNode->pNext == NULL) { return; } Node* pDelNode = _preNode->pNext; Node* pNextNode = pDelNode->pNext; delete pDelNode; MAX--; _preNode->pNext = pNextNode; } void LinkedList::Find() { if (Head == NULL) return; int select = 0; cin >> select; Node* tamp = Head; while (tamp->pNext != NULL) { if (tamp->iData.GetData().iindex == select) { break; } tamp = tamp->pNext; } tamp->iData.Print(); } void LinkedList::printAll() { if (Head == NULL) return; Node* tamp = Head; for (int i = 0; i < MAX; i++) { tamp->iData.Print(); tamp = tamp->pNext; } } void LinkedList::save() { FILE* fp = NULL; fp = fopen("DEMO.txt", "wt"); cur = Head; fprintf(fp, "%d", MAX); for (int i = 0; i < MAX; i++) { fprintf (fp, "\n%3d %8s %7d %7d %7d %7d %10.4f", cur->iData.GetData().iindex, cur->iData.GetData().strName, cur->iData.GetData().iKor, cur->iData.GetData().iEng, cur->iData.GetData().iMat, cur->iData.GetData().iTotal, cur->iData.GetData().Average ); cur = cur->pNext; } fclose(fp); } void LinkedList::Load() { FILE* fp; fp = fopen("DEMO.txt", "rt"); if (fp == NULL) { return ; } if (Head != NULL) { while (Head->pNext != NULL) { delete(Head); } Tail = Head; delete Head; } //fscanf(fp, "%d", &MAX); if (Head == NULL) { SStudent cStuTemp; char szTempName[255] = { 0, }; int iTemp[6] = { 0, }; float fTemp = 0.0f; fscanf(fp, "%d", &MAX); for (int i = 0; i < MAX; i++) { fscanf(fp, "%d %s %d %d %d %d %f", &iTemp[0], szTempName, &iTemp[1], &iTemp[2], &iTemp[3], &iTemp[4], &fTemp); cStuTemp.SetData(szTempName,iTemp[0],iTemp[1],iTemp[2],iTemp[3],iTemp[4],fTemp); Node* pTempNode = new Node(cStuTemp); Insert(pTempNode); } } fclose(fp); } void LinkedList::Insert(Node* _newNode) { if (Head == NULL) { Node* pFirstNode = new Node(_newNode->iData); Head = pFirstNode; Tail = Head; Tail->pNext = NULL; return; } Node* pNewNode = new Node(_newNode->iData); Tail->pNext = _newNode; Tail = Tail->pNext; Tail->pNext = NULL; } LinkedList::LinkedList() { Head = NULL; Tail = NULL; MAX = 0; cur = NULL; } LinkedList::~LinkedList() { } <file_sep>#include "S_KHJ_Object.h" void S_KHJ_Object::GetMaterial() { for (int iMtl = 0; iMtl < m_pMtlList.size(); iMtl++) { Mtl* pSrcMtl = m_pMtlList[iMtl]; SMtl AddMtl; TSTR className; pSrcMtl->GetClassName(className); AddMtl.strName = FixupName(pSrcMtl->GetName()); AddMtl.strClassName = FixupName(className); AddMtl.iNumSubMtl = pSrcMtl->NumSubMtls(); AddMtl.iIndex = iMtl; if (pSrcMtl->NumSubMtls() > 0) { for (int iSubMtrl = 0; iSubMtrl < pSrcMtl->NumSubMtls(); iSubMtrl++) { Mtl* subMtl = pSrcMtl->GetSubMtl(iSubMtrl); SMtl AddSubMtl; AddSubMtl.iIndex = iSubMtrl; AddSubMtl.iNumSubMtl = subMtl->NumSubMtls(); AddSubMtl.strName = FixupName(subMtl->GetName()); TSTR className; subMtl->GetClassName(className); AddSubMtl.strClassName = FixupName(className); if (subMtl->NumSubMtls() > 0) { MessageBox(0, _T("다중 서브 매터리얼"), _T("Fatal error"), MB_OK); } if (subMtl) { GetTexture(&AddSubMtl, subMtl); } AddMtl.SubMaterial.push_back(AddSubMtl); } } else { GetTexture(&AddMtl, pSrcMtl); } m_Material.push_back(AddMtl); } } void S_KHJ_Object::GetTexture(SMtl* DestMtrl, Mtl* pSrcMtl) { for (int iSubMap = 0; iSubMap < pSrcMtl->NumSubTexmaps(); iSubMap++) { Texmap* tex = pSrcMtl->GetSubTexmap(iSubMap); if (tex) { if (pSrcMtl->ClassID() == Class_ID(DMTL_CLASS_ID, 0)) { StdMat* std = (StdMat*)pSrcMtl; if (!std->MapEnabled(iSubMap)) continue; } STexMap TexMap; TexMap.iType = iSubMap; if (tex->ClassID() == Class_ID(BMTEX_CLASS_ID, 0x00)) { TSTR mapName = ((BitmapTex*)tex)->GetMapName(); TSTR strFullName; SplitPathFile(mapName, &strFullName, &mapName); TexMap.StrTextureName = FixupName(mapName); } DestMtrl->TexMaps.push_back(TexMap); DestMtrl->iNumMap = DestMtrl->TexMaps.size(); } } } void S_KHJ_Object::UpdateObject() { for (int iObj=0; iObj < m_MatrixMap.Count(); iObj++) { MATRIXINDEX* pPoint = (MATRIXINDEX*)m_MatrixMap.TMap[iObj]; GetObject(pPoint); } } void S_KHJ_Object::GetObject(MATRIXINDEX* pPoint) { SMesh* pMesh = &pPoint->m_sMesh; pMesh->m_ClassType = pPoint->m_ClassType; GetNodeHeader(pPoint->m_pINode, pMesh); // 노드의 이름을 얻는다. GetNodeTM(pPoint->m_pINode, pMesh); // 노드의 행렬을 얻는다. GetMesh(pPoint->m_pINode, pMesh); // 기하 정보를 얻는다. GetAnimKeys(pPoint->m_pINode, pMesh); // 애니메이션 정보를 얻는다. } void S_KHJ_Object::GetNodeHeader(INode* node, SMesh* Smesh) { Smesh->m_strNodeName = FixupName(node->GetName()); INode* parent = node->GetParentNode(); if (parent && (!parent->IsRootNode())) { Smesh->m_strParentName = FixupName(parent->GetName()); } } void S_KHJ_Object::GetNodeTM(INode* node, SMesh* Smesh) { Matrix3 g_matWorld = node->GetNodeTM(m_Interval.Start()); DumpMatrix3(&g_matWorld, Smesh->m_matWorld); } void S_KHJ_Object::GetMesh(INode* node, SMesh* Smesh) { Matrix3 tm = node->GetObjTMAfterWSM(m_Interval.Start()); // 작업중 및 작업완료된 파이프 라인의 결과에 액세스 함으로써 현재 노드의 결과를 돌려준다. ObjectState os = node->EvalWorldState(m_Interval.Start()); if (!os.obj || os.obj->SuperClassID() != GEOMOBJECT_CLASS_ID) { return; } BOOL needDel; TriObject* tri = GetTriObjectFromNode(node, m_Interval.Start(), needDel); if (!tri) { return; } Mesh* mesh = &tri->GetMesh(); // 바운딩 박스 mesh->buildBoundingBox(); Box3 box = mesh->getBoundingBox(&tm); DumpPoint3(Smesh->m_Box.pmax, box.pmax); DumpPoint3(Smesh->m_Box.pmin, box.pmin); Smesh->m_iNumFace = mesh->getNumFaces(); BOOL negScale = TMNegParity(tm); int v0, v1, v2; if (negScale) { v0 = 2; v1 = 1; v2 = 0; } else { v0 = 0; v1 = 1; v2 = 2; } Smesh->m_TriList.resize(Smesh->m_iNumFace); for (int iFace = 0; iFace < Smesh->m_iNumFace;iFace++) { Matrix3 pInverse = Inverse(node->GetNodeTM(m_Interval.Start())); Point3 v; if (mesh->getNumVerts() > 0) { v = mesh->verts[mesh -> faces[iFace].v[v0]] * tm*pInverse; DumpPoint3(Smesh->m_TriList[iFace].v[0].p, v); v = mesh->verts[mesh -> faces[iFace].v[v2]] * tm*pInverse; DumpPoint3(Smesh->m_TriList[iFace].v[1].p, v); v = mesh->verts[mesh->faces[iFace].v[v1]] * tm*pInverse; DumpPoint3(Smesh->m_TriList[iFace].v[2].p, v); } if (mesh->getNumTVerts() > 0) { Smesh->m_TriList[iFace].v[0].t.x = mesh->tVerts[mesh->tvFace[iFace].t[v0]].x; Smesh->m_TriList[iFace].v[0].t.y = 1.0f - mesh->tVerts[mesh->tvFace[iFace].t[v0]].y; Smesh->m_TriList[iFace].v[1].t.x = mesh->tVerts[mesh->tvFace[iFace].t[v2]].x; Smesh->m_TriList[iFace].v[1].t.y = 1.0f - mesh->tVerts[mesh->tvFace[iFace].t[v2]].y; Smesh->m_TriList[iFace].v[2].t.x = mesh->tVerts[mesh->tvFace[iFace].t[v1]].x; Smesh->m_TriList[iFace].v[2].t.y = 1.0f - mesh->tVerts[mesh->tvFace[iFace].t[v1]].y; } Smesh->m_TriList[iFace].v[0].c = Point4(1, 1, 1, 1); Smesh->m_TriList[iFace].v[1].c = Point4(1, 1, 1, 1); Smesh->m_TriList[iFace].v[2].c = Point4(1, 1, 1, 1); if (mesh->getNumVertCol() > 0) { Smesh->m_TriList[iFace].v[0].c.x = mesh->vertCol[mesh->vcFace[iFace].t[v0]].x; Smesh->m_TriList[iFace].v[0].c.y = mesh->vertCol[mesh->vcFace[iFace].t[v0]].y; Smesh->m_TriList[iFace].v[0].c.z = mesh->vertCol[mesh->vcFace[iFace].t[v0]].z; Smesh->m_TriList[iFace].v[0].c.w = 1.0f; Smesh->m_TriList[iFace].v[0].c.x = mesh->vertCol[mesh->vcFace[iFace].t[v2]].x; Smesh->m_TriList[iFace].v[0].c.y = mesh->vertCol[mesh->vcFace[iFace].t[v2]].y; Smesh->m_TriList[iFace].v[0].c.z = mesh->vertCol[mesh->vcFace[iFace].t[v2]].z; Smesh->m_TriList[iFace].v[0].c.w = 1.0f; Smesh->m_TriList[iFace].v[0].c.x = mesh->vertCol[mesh->vcFace[iFace].t[v1]].x; Smesh->m_TriList[iFace].v[0].c.y = mesh->vertCol[mesh->vcFace[iFace].t[v1]].y; Smesh->m_TriList[iFace].v[0].c.z = mesh->vertCol[mesh->vcFace[iFace].t[v1]].z; Smesh->m_TriList[iFace].v[0].c.w = 1.0f; } // 정점 노말 얻기 mesh->buildNormals(); int vert = mesh->faces[iFace].getVert(v0); Point3 vn = GetVertexNormal(mesh, iFace, mesh->getRVertPtr(vert)); DumpPoint3(Smesh->m_TriList[iFace].v[0].n, vn); vert = mesh->faces[iFace].getVert(v2); vn = GetVertexNormal(mesh, iFace, mesh->getRVertPtr(vert)); DumpPoint3(Smesh->m_TriList[iFace].v[1].n, vn); vert = mesh->faces[iFace].getVert(v1); vn = GetVertexNormal(mesh, iFace, mesh->getRVertPtr(vert)); DumpPoint3(Smesh->m_TriList[iFace].v[2].n, vn); // 서브 매터리얼 인덱스 Smesh->m_TriList[iFace].iSubIndex = mesh->faces[iFace].getMatID(); } if (needDel) { delete tri; } Smesh->m_iMtrlRef = GetMtlref(node->GetMtl()); } Point3 S_KHJ_Object::GetVertexNormal(Mesh* mesh, int faceNo, RVertex* rv) { Face* f = &mesh->faces[faceNo]; DWORD smGroup = f->smGroup; int numNormals = rv->rFlags & NORCT_MASK; Point3 vertexNormal; if (rv->rFlags & SPECIFIED_NORMAL) { vertexNormal = rv->rn.getNormal(); } else if (numNormals && smGroup) { if (numNormals == 1) { vertexNormal = rv->rn.getNormal(); } else { for (int i = 0; i < numNormals; i++) { if (rv->ern[i].getSmGroup() & smGroup) { vertexNormal = rv->ern[i].getNormal(); } } } } else { vertexNormal = mesh->getFaceNormal(faceNo); } return vertexNormal; } TriObject* S_KHJ_Object::GetTriObjectFromNode(INode* node, TimeValue t, int &deletelt) { deletelt = FALSE; Object* obj = node->EvalWorldState(t).obj; if (obj->CanConvertToType(Class_ID(TRIOBJ_CLASS_ID, 0))) { TriObject* tri = (TriObject*)obj->ConvertToType(t, Class_ID(TRIOBJ_CLASS_ID, 0)); if (obj != tri)deletelt = TRUE; return tri; } else { return NULL; } } S_KHJ_Object::S_KHJ_Object(void) { } S_KHJ_Object::~S_KHJ_Object(void) { } <file_sep>#pragma once #include "DIWindow.h" #include "DTimer.h" #include "DDirectWrite.h" #include "DIDInput.h" class Sample : public DIWindow { public: DTimer m_Timer; DDirectWrite m_Font; T_STR m_strBuffer; D2D1_MATRIX_3X2_F m_matWorld; float m_fScale; public: bool Init(); bool Frame(); bool Render(); bool Release(); public: Sample(void); ~Sample(void); };<file_sep>//기존에 구현되어 있는 클래스(둥근 모양의 빵) 에 그때 그떄 필요한 기능(초콜릿, 치즈, 생크림)을 //추가(장식,포장)해나가는 설계 패턴을 decorator패턴이라고 한다. //이것은 기능 확장이 필요할 때 상속의 대안으로 사용한다. #include <iostream> using namespace std; ////아래의 코드는 기본코드 //class Airplane //{ //public: // void Additem(item* pltem) // { // direction_ += pltem->GetDirection(); // } // void Attack() // { // if (direction_ &SIDE_DIRECTION) // { // //--측방 공격 수행 // cout << "측방 공격" << endl; // } // if(direction_&REAR_DIRECTION) // { // //-- 후방 공격 수행 // cout << "후방 공격" << endl; // } // // -- 전방 공격 수행 // cout << "전방 공격" << endl; // } //private: // int direction_; //}; class Airplane { public: virtual void Attack() = 0; }; class FrontAttackAirplane : public Airplane { public: void Attack() { // --전방 공격 수행 cout << "전방 공격" << endl; } }; class Decorator : public Airplane { public: Decorator(Airplane* pObj) { pComponent_ = pObj; } virtual ~Decorator() = 0; virtual void Attack() { if (pComponent_ != 0) pComponent_->Attack(); } private: Airplane * pComponent_; }; Decorator::~Decorator() {} class SideAttackAirplane : public Decorator { public: SideAttackAirplane(Airplane* pObj) : Decorator(pObj) {} void Attack() { Decorator::Attack(); //--측방 공격 수행 cout << "측방 공격" << endl; } }; class RearAttackAirplane : public Decorator { public: RearAttackAirplane(Airplane* pObj) : Decorator(pObj) {} void Attack() { Decorator::Attack(); //--후방 공격 수행 cout << "후방 공격" << endl; } }; void main() { Airplane* pFrontAttackAirplane = new FrontAttackAirplane; Airplane* pSideAttackAirplane = new SideAttackAirplane(pFrontAttackAirplane); Airplane* pRearAttackAirplane = new RearAttackAirplane(pSideAttackAirplane); pRearAttackAirplane->Attack(); delete pRearAttackAirplane; pSideAttackAirplane->Attack(); }<file_sep>#pragma once #include "SServerObj.h" class SLock // SLock == Synchronize { public: SServerObj* m_pSerObj; public: SLock(SServerObj* pObj); virtual ~SLock(void); };<file_sep>#include "SCHATAccept.h" #include "SChatSvr.h" void SCHATAccept::AddUser(SOCKET socket, SOCKADDR_IN address) { I_Server.AddUser(socket, address); } SCHATAccept::SCHATAccept(void) { } SCHATAccept::~SCHATAccept(void) { } <file_sep>#pragma once #include "S_Global.h" class S_Object : public S_Global { public: void GetMaterial(); void GetTexture(SMtl* pDestMtl, Mtl* pSrcMtl); public: void UpdateObject(); void GetObject(MATRIXINDEX* pPoint); void GetNodeHeader(INode* node, SMesh* pMesh); void GetNodeTM(INode* node, SMesh* pMesh); void GetMesh(INode* node, SMesh* pMesh); Point3 GetVertexNormal(Mesh* mesh, int faceNo, RVertex* rv); TriObject* GetTriObjectFromNode(INode* node, TimeValue t, int &deletelt); virtual void GetAnimKeys(INode*, SMesh*) {}; public: S_Object(void); virtual ~S_Object(void); }; <file_sep>#include "xCore.h" #include "xMap.h" class Sample : public xCore { xMap m_map; public: bool Init() { m_pMainCamera->SetViewMatrix( D3DXVECTOR3(0.0f, 300.0f, -300.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f)); xMapDesc desc = { 5, 5, 1.0f, 1.0f, L"../../Include/data/map/Tile40.jpg", L"../../Include/data/shader/map.hlsl", }; m_map.Init(); m_map.CreateHeightMap(m_pd3dDevice, m_pContext, L"../../Include/data/map/heightMap513.bmp"); desc.iNumRows = m_map.m_iNumRows; desc.iNumCols = m_map.m_iNumCols; desc.fScaleHeight = 0.5f; if (m_map.Load(m_pd3dDevice,desc)==false) { return false; } } bool Render() { m_map.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_map.Render(m_pContext); return true; } bool Release() { return m_map.Release(); } public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600) <file_sep>#include "SProtocol.h" #define PACKET_CHAR_NAME_REQ 1000 #define PACKET_CHAR_NAME_ACK 1001 #define PACKET_CHAR_MSG 1002 #pragma pack( push, 1 ) /// 필요한 프로토콜 정의 typedef struct { WORD user_idx; // 케릭터의 고유한 인덱스 WORD posX; // 좌표 WORD posY; WORD direction; // 방향 ( 0~7 ) 8방향 }TPACKET_USER_POSITION; #define PACKET_USER_POSITION 3000 #pragma pack(pop)<file_sep>#include "TAvlTree.h" int main() { TAvlTree avl; Node* root = nullptr; // 리프노드 높이가 =1 이면 , 루트가 가장 크다. root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); root = avl.insert(root, 1); avl.printAll(root); return 0; }<file_sep>#include "TParent.h" TParent::TParent(void) { money = 100000000; cout << "Parent 생성자" << endl; } TParent::TParent(int money) { this->money = money; cout << "Parent 생성자" << endl; } TParent::~TParent(void) { cout << "Parent 소멸자" << endl; } void TParent::Character(void) { cout << "차분한 성품" << endl; } void TParent::Appearance(void) { cout << "잘생긴 외모" << endl; } void TParent::Wealth(void) { cout << "재산:" << money << "원" << endl; } <file_sep>#include "DXVector.h" D3DXVECTOR3::D3DXVECTOR3() { x = y = z = 0.0f; } D3DXVECTOR3::D3DXVECTOR3(const D3DXVECTOR3& vO) { x = vO.x; y = vO.y; z = vO.z; } D3DXVECTOR3::D3DXVECTOR3(float fX, float fY, float fZ) { x = fX; y = fY; z = fZ; } // 연산자 재정의 D3DXVECTOR3 D3DXVECTOR3::operator + (D3DXVECTOR3 const &vO) { return D3DXVECTOR3( vO.x + x, vO.y + y, vO.z + z); } D3DXVECTOR3 D3DXVECTOR3::operator - (D3DXVECTOR3 const &vO) { return D3DXVECTOR3( x - vO.x, y - vO.y, z - vO.z); } D3DXVECTOR3 D3DXVECTOR3::operator + (float const &fScala) { return D3DXVECTOR3( fScala + x, fScala + y, fScala + z); } D3DXVECTOR3 D3DXVECTOR3::operator * (float const &fScala) { return D3DXVECTOR3( fScala*x, fScala*y, fScala*z); } D3DXVECTOR3 D3DXVECTOR3::operator / (float const &fScala) { float fInvert = 1.0f / fScala; return D3DXVECTOR3( x*fInvert, y*fInvert, z*fInvert); } bool D3DXVECTOR3::operator == (D3DXVECTOR3 const &vO) //fabs == 절대값 { if (fabs(x - vO.x) < TBASIS_EPSILON) { if (fabs(y - vO.y) < TBASIS_EPSILON) { if (fabs(z - vO.z) < TBASIS_EPSILON) { return true; } } } return false; } // 제곱 float D3DXVECTOR3::LengthSquared() { return (x*x + y * y + z * z); } // 원점으로 부터의 거리 float D3DXVECTOR3::Length() { return (float)sqrt(LengthSquared()); } D3DXVECTOR3 D3DXVECTOR3::Normalize() // 정규화 { float invertLength = 1.0f / Length(); return D3DXVECTOR3( x*invertLength, y*invertLength, z*invertLength); } D3DXVECTOR3 D3DXVECTOR3::Normal() { if (Length() - 0.0f, 0.001f) { return *this; } float invertLength = 1.0f / Length(); x *= invertLength; y *= invertLength; z *= invertLength; return *this; } // 3D 내적 외적 float D3DXVECTOR3 :: operator | (D3DXVECTOR3 const & vO) { return x * vO.x + y * vO.y + z * vO.z; } D3DXVECTOR3 D3DXVECTOR3::operator ^(D3DXVECTOR3 const& vO) { return D3DXVECTOR3((y*vO.z - z * vO.y), (z*vO.x - x * vO.z), (x*vO.y - y * vO.x)); } // Vector2 Vector2::Vector2() { x = y = 0.0f; } Vector2::Vector2(const Vector2& vO) { x = vO.x; y = vO.y; } Vector2::Vector2(float fX, float fY) { x = fX; y = fY; } // 2D 내적 외적 bool Vector2::operator | (Vector2 const & vO) { return x * vO.x + y * vO.y; } Vector2 Vector2::operator ^ (Vector2 const& vO) { return Vector2(0, (x*vO.y - y * vO.x)); } // Vector4 Vector4::Vector4() { x = y = z = w = 0.0f; } Vector4::Vector4(const Vector4& vO) { x = vO.x; y = vO.y; z = vO.z; w = vO.w; } Vector4::Vector4(float fX, float fY, float fZ, float fW) { x = fX; y = fY; z = fZ; w = fW; } void main() { }<file_sep>#include <Windows.h> LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { MessageBox(NULL, L"윈도우가 떳다",L"윈도우가 떳다", MB_OK); } case WM_LBUTTONDOWN: { DestroyWindow(hWnd); }break; case WM_DESTROY: { PostQuitMessage(0); //WM_Quit-->>Push //DestroyWindow(hWnd); //WM_DESTROY--->Push }return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } void GameRun() { //지형, 오브젝트,이펙트,UI } void GameInit() { //지형, 오브젝트,이펙트,UI } void GameRelease() { //지형, 오브젝트,이펙트,UI } int WINAPI WindMain(HINSTANCE hInst, HINSTANCE hPrevinst, LPSTR IpCmdLine, int nCmadSHow) { //Window class 등록 WNDCLASSEX wc; //Window CLASS 변수 선언 ZeroMemory(&wc, sizeof(WNDCLASSEX)); // 0으로 초기화 wc.cbSize = sizeof(WNDCLASSEX); // 사이즈 재정의 wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.hInstance = hInst; wc.lpszClassName = L"MY Window"; // 윈도우창 이름 wc.hIcon = LoadIcon(hInst, IDI_QUESTION); // 아이콘 그림 wc.hCursor = LoadCursor(NULL,IDC_IBEAM); // 마우스 아이콘 wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH); // window 색상 wc.lpszMenuName = NULL; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wc.cbClsExtra = 0; //클래스의 여분 메모리 wc.cbWndExtra = 0;// 윈도우위 여분 메모리 if (RegisterClassEx(&wc) == FALSE) { return 1; } //윈도우 생성 (등록된 클래스를 사용해서 윈도우생성) //기본 HWND hWnd = CreateWindowEx(WS_EX_APPWINDOW, L"Windeow", L"KHJ SAMPLE", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, NULL, NULL, hInst, NULL); if (hWnd == NULL) { return 1; } ShowWindow(hWnd, SW_SHOW); GameInit(); MSG msg; ZeroMemory(&msg, sizeof(MSG)); while (1) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { //화면에 무언가를 뿌린다.(DRAW); GameRun(); } } GameRelease(); return 0; }<file_sep>#include <iostream> template <typename T> void swap(T &a,T &b) { T temp; temp = a; a = b; b = temp; } int main(void) { int a = 1, b = 2; swap(a, b); std::cout << a << "," << b << std::endl; double c = 0.1, d = 0.2; swap(c, d); std::cout << c << "," << d << std::endl; return 0; }<file_sep>#include "S_Server.h" bool S_Server::Init() { CreateThread(); return true; } bool S_Server::Release() { return true; } bool S_Server::Run() { return true; } bool S_Server::AddUser(SOCKET socket, SOCKADDR_IN address) { return true; } bool S_Server::SendMsg(SOCKET socket,const char* msg, WORD code) { UPACKET Sendmsg; ZeroMemory(&Sendmsg, sizeof(Sendmsg)); sprintf_s(Sendmsg.msg, "%s", msg); Sendmsg.ph.type = code; Sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(Sendmsg.msg); int ret = send(socket, (char*)&Sendmsg, Sendmsg.ph.len, 0); if (ret <= 0) { return false; } return true; } S_Server::S_Server() { } S_Server::~S_Server() { } <file_sep>#include <iostream> #include "TBTree.h" //LL회전 BTreeNode* RotateLL(BTreeNode* bst) { BTreeNode* pNode; BTreeNode* cNode; pNode = bst; cNode = GetLeftSubTree(pNode); ChangeLeftSubTree(pNode, GetRightSubTree(cNode)); ChangeRightSubTree(cNode, pNode); return cNode; } //RR 회전 BTreeNode* RotateRR(BTreeNode* bst) { BTreeNode* pNode; BTreeNode* cNode; pNode = bst; cNode = GetRightSubTree(pNode); ChangeRightSubTree(pNode, GetLeftSubTree(cNode)); ChangeLeftSubTree(cNode, pNode); return cNode; } //RL회전 BTreeNode* RotateRL(BTreeNode* bst) { BTreeNode* pNode; BTreeNode* cNode; pNode = bst; cNode = GetRightSubTree(pNode); ChangeRightSubTree(pNode, RotateLL(cNode)); //부분적 LL회전 return RotateRR(pNode); //RR회전 } //LR회전 BTreeNode* RotateLR(BTreeNode* bst) { BTreeNode* pNode; BTreeNode* cNode; pNode = bst; cNode = GetLeftSubTree(pNode); ChangeLeftSubTree(pNode, RotateRR(cNode)); // 부분적 RR회전 return RotateLL(pNode); //LL회전 } // 트리의 높이를 계산하여 반환 int GetHeight(BTreeNode* bst) { int leftH; //left Height int rightH; //right Height if (bst == NULL) return 0; //왼쪽 서브 트리 높이 계산 leftH = GetHeight(GetLeftSubTree(bst)); //오른쪽 서브 트리 높이 계산 rightH = GetHeight(GetRightSubTree(bst)); //큰 값의 높이를 반환한다. if (leftH > rightH) return leftH + 1; else return rightH + 1; } //두 서브 트리의 높이의 차를 반환 int GetHeightDiff(BTreeNode* bst) { int lsh; //left sub tree height int rsh; // right sub tree height if (bst == NULL) return 0; lsh = GetHeight(GetLeftSubTree(bst)); rsh = GetHeight(GetRightSubTree(bst)); return lsh - rsh; } //트리의 균형을 잡는다 BTreeNode* Rebalance(BTreeNode** pRoot) { int hDiff = GetHeightDiff(*pRoot); if (hDiff > 1) //왼쪽 서브 트리 방향으로 높이가 2 이상 크다면 { if (GetHeightDiff(GetLeftSubTree(*pRoot)) > 0) *pRoot = RotateLL(*pRoot); else *pRoot = RotateLR(*pRoot); } if (hDiff < -1)// 오른쪽 서브 트리 방향으로 2이상 크다면 { if (GetHeightDiff(GetRightSubTree(*pRoot)) < 0) *pRoot = RotateRR(*pRoot); else *pRoot = RotateRL(*pRoot); } return *pRoot; }<file_sep>#include<stdio.h> void func() { int a=5; } int a; void main() { printf("%d\n", a); func(); a = 10; printf("%d\n", a); }<file_sep>#pragma once #include "TCore.h" #include "sUdpSocket.h" class ServerMain: public TCore { public: sUdpSocket m_Udp; public: bool Init(); bool Release(); bool PreRender() { return true;} bool PostRender() { return true; } public: LRESULT MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); public: ServerMain(void); virtual ~ServerMain(void); }; <file_sep>#pragma once #include "TPermanent.h" #include "TTemporary.h" class TDepartment { private: TEmployee * empList[10]; int index; public: TDepartment() :index(0) { }; void AddEmployee(TEmployee*emp); void ShowList();//급여 리스트 출력 }; <file_sep>#pragma once #include "S_Protocol.h" class S_Packet { public: PTR_HEADER_PACKET m_ptrPacket; char m_strPacketbuf[PACKETBUFFERSIZE]; char* m_pStrWritePos; char* m_pStrReadPos; int m_iReceivedsize; public: WORD getID(); WORD getSize(); char* getData(); int getDataSize(); public: void ReadData(void* buf, int iSize); void WriteData(void* buf, int iSize); void Clear(); public: S_Packet& SetId(unsigned short id); public: S_Packet& operator << (int arg); S_Packet& operator << (DWORD arg); S_Packet& operator << (bool arg); S_Packet& operator << (unsigned short arg); S_Packet& operator << (float arg); S_Packet& operator << (char* arg); S_Packet& operator << (S_Packet& arg); public: S_Packet& operator >> (int& arg); S_Packet& operator >> (DWORD& arg); S_Packet& operator >> (bool& arg); S_Packet& operator >> (unsigned short& arg); S_Packet& operator >> (float& arg); S_Packet& operator >> (char* arg); S_Packet& operator >> (S_Packet& arg); public: S_Packet(); S_Packet(unsigned short type); virtual ~S_Packet(); }; <file_sep>#include "DTimer.h" bool DTimer::Init() { QueryPerformanceCounter(&m_Frame); // 고해상도 타이머 // 고해상도 타이머 지원여부 판단 if (m_Frame.QuadPart == 0) { return false; } m_FPS = m_Frame; m_iFramePerSecond = 0; m_iFPSElapse = 0; m_fSecPerFrame = 0.0f; Start(); return true; } bool DTimer::Frame() { // 1프레임의 시간 체크 // 현재 시간을 찾느다 QueryPerformanceCounter(&m_Current); m_fSecPerFrame = static_cast<float> (m_Current.QuadPart - m_Frame.QuadPart) / static_cast<float>(m_Frequency.QuadPart); // 1초당 프레임 체크 if (((m_Current.LowPart - m_FPS.LowPart) / m_Frequency.LowPart) > 1) { m_iFramePerSecond = m_iFPSElapse; m_iFPSElapse = 0; m_FPS = m_Current; } m_iFPSElapse++; m_Frame = m_Current; return true; } int DTimer::GetFPS() { return m_iFramePerSecond; } float DTimer::GetSPF() { return m_fSecPerFrame; } bool DTimer::Render() { return true; } bool DTimer::Release() { return true; } void DTimer::Reset() { m_bStarted = false; m_fEventTime = 0.0f; memset(&m_Start, 0, sizeof(LARGE_INTEGER)); memset(&m_Elapse, 0, sizeof(LARGE_INTEGER)); } void DTimer::Start() { m_bStarted = true; m_fEventTime = 0.0f; QueryPerformanceCounter((LARGE_INTEGER*)&m_Start); } void DTimer::Stop() { GetElapseTime(); m_bStarted = false; } bool DTimer::IsStarted()const { return m_bStarted; } float DTimer::GetElapseTime() { if (m_bStarted) { QueryPerformanceCounter((LARGE_INTEGER*)&m_Elapse); m_fEventTime = static_cast<float>(m_Elapse.LowPart - m_Start.LowPart) / static_cast<float>(m_Frequency.LowPart); } return m_fEventTime; } DTimer::DTimer() { m_bStarted = false; m_iFramePerSecond = 0; m_iFPSElapse = 0; m_fSecPerFrame = 0.0f; m_fEventTime = 0.0f; // 시스템의 주파수 변동폭을 얻어 온다 . 이는 시간의 표준을 잡기 위해서 사용한다. QueryPerformanceFrequency((LARGE_INTEGER*)&m_Frequency); } DTimer::~DTimer() { } <file_sep>#include<stdio.h> #include<string.h> #include<stdlib.h> #include<conio.h> void main() //void strcpy(const char* source, const char* destination) //{ // int i; // i = 0; // // while ((const char *source[i] = destination[i]) != '\0')i++; //} //void strcpy(char* s, char* t) //{ // while ((*s = *t) != '\0') // { // s++; // t++; // } //} //void strcpy(char* s, char* t) // { // while ((*s++ = *t++ != '\0')); // } <file_sep>#pragma once #include "xArcBall.h" class xModelView : public xCamera { xArcBall m_WorldArcBall; public: LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); bool Update(D3DXVECTOR4 vValue); public: xModelView(); virtual ~xModelView(); }; <file_sep>#include "CCInput.h" //KeyCheck(VK_LEFT) //KeyCheck('0') //keyCheck('A') DWORD CCInput::KeyCheck(DWORD dwKey) { //GetKeyState() //동기적 //GetAsyncKeyState() //비동기적 SHORT sKey = GetAsyncKeyState(dwKey); //0x8000= 10000000 00000000 if (sKey & 0x8000) { if (m_dwKeyState[dwKey] == KEY_FREE) m_dwKeyState[dwKey] = KEY_PUSH; else m_dwKeyState[dwKey] = KEY_HOLD; } else { if (m_dwKeyState[dwKey] == KEY_PUSH || m_dwKeyState[dwKey] == KEY_HOLD) m_dwKeyState[dwKey] = KEY_UP; else m_dwKeyState[dwKey] = KEY_FREE; } return m_dwKeyState[dwKey]; } //클래스 멤버 변수 초기화 bool CCInput::Init() { ZeroMemory(m_dwKeyState, sizeof(DWORD) * 256); ZeroMemory(m_dwMouseState, sizeof(DWORD) * 3); return true; } //매 프레임에서 계산을 담당한다. bool CCInput::Frame() { return true; } // 매 프레임에서 드로우를 담당한다 bool CCInput::Render() { ZeroMemory(m_csBuffer, sizeof(TCHAR)*MAX_PATH); m_strList.clear(); //for (int ikey = 0; ikey < 256; ikey++) //{ // if (m_dwKeyState == KEY_FREE) // strData += L""; //} std::wstring strData0; if (m_dwMouseState[0] == TRUE) { strData0 = L"m_dwMouseState[0]"; m_strList.push_back(strData0); } std::wstring strData1; if (m_dwMouseState[1] == TRUE) { strData1 = L"m_dwMouseState[1]"; m_strList.push_back(strData1); } std::wstring strData2; if (m_dwMouseState[2] == TRUE) { strData2 = L"m_dwMousestate[2]"; m_strList.push_back(strData2); } //_stprintf_s(m_csBuffer,L"%s\n",strData.c_str()); return true; } //클래스 멤버 변수 소멸을 담당한다. bool CCInput::Release() { return true; } void CCInput::MsgEvent(MSG msg) { switch (msg.message) { case WM_LBUTTONDOWN: { m_dwMouseState[0] = TRUE; }break; case WM_LBUTTONUP: { m_dwMouseState[0] = FALSE; }break; case WM_RBUTTONDOWN: { m_dwMouseState[1] = TRUE; }break; case WM_RBUTTONUP: { m_dwMouseState[1] = FALSE; }break; case WM_MBUTTONDOWN: { m_dwMouseState[2] = TRUE; }break; case WM_MBUTTONUP: { m_dwMouseState[2] = FALSE; }break; } } CCInput::CCInput() { } CCInput::~CCInput() { } <file_sep>#pragma once #include "SThread.h" #include <ws2tcpip.h> class TUdpSocket : public SThread { public: SOCKET m_Socket; SOCKET m_SendSocket; SOCKADDR_IN m_RecvAddr; SOCKADDR_IN m_SendAddr; public: bool Init(); bool Run(); bool Release(); public: TUdpSocket(void); ~TUdpSocket(void); }; <file_sep>#pragma once #include "xDxObj.h" struct _PC_VERTEX { D3DXVECTOR3 p; D3DXVECTOR4 c; }; struct _PNCT_VERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; D3DXVECTOR4 c; D3DXVECTOR2 t; bool operator == (const _PNCT_VERTEX & Vertex) { if (p == Vertex.p && n == Vertex.n && c == Vertex.c && t == Vertex.t) { return true; } return false; } _PNCT_VERTEX() {} _PNCT_VERTEX(D3DXVECTOR3 vp, D3DXVECTOR3 vn, D3DXVECTOR4 vc, D3DXVECTOR2 vt) { p = vp, n = vn, c = vc, t = vt; } }; struct PT_VERTEX { D3DXVECTOR3 p; D3DXVECTOR2 t; }; struct T_CB_DATA { D3DXMATRIX matWorld; D3DXMATRIX matView; D3DXMATRIX matProj; float fTime; float fActiveVP; float z, w; D3DXVECTOR4 vColor; };<file_sep>#include<stdio.h> #include<conio.h> //Call by reference //void func(int data[]) //{ // data[0] = 10; //} //void main() //{ // int i; // int var[10] = { 1,2,3,4,5,6,7,8,9,0 }; // // func(var); // for (i = 0; i < 10; i++) // { // printf("%d\n", var); // } //} //func함수를 호출할 때 var이란 변수를 인수로 //func함수에서는 data라는 인수로 배열을 전달 //Call by value void func(int data) { data = 10; } void main() { int var = 1; func(var); printf("%d\n", var); } //main 함수에는 var이란 변수가 //그 변수에 초기값으로 1을 준 다음 func를 호출했는데 //인수로 var이란 변수를 주었음<file_sep>#pragma once #include "xStd.h" #include "dinput.h" #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") #define KEYSTATECOUNT 256 enum Key_State { KEY_FREE = 0, KEY_UP = 1, KEY_PUSH = 2, KEY_HOLD = 3, }; class xInput : public SSingleton < xInput > { private: friend class SSingleton<xInput>; public: LPDIRECTINPUT8 m_pDI; LPDIRECTINPUTDEVICE8 m_pKey; LPDIRECTINPUTDEVICE8 m_pMouse; HWND m_hWnd; BYTE m_KeyState[256]; DIMOUSESTATE m_MouseState; public: bool Init(); bool Frame(); bool Release(); protected: xInput(); public: virtual ~xInput(); }; #define I_Input xInput::GetInstance() <file_sep>#pragma once #include "S_Std.h" class S_SvrObj { public: CRITICAL_SECTION m_Ct; public: S_SvrObj(); virtual ~S_SvrObj(); }; <file_sep>//#include <Windows.h> //#include <iostream> //#include <tchar.h> //#include <string> //using namespace std; // // //char * GetW2M(WCHAR* data) // 유니코드를 멀티바이트로 바꾸는 함수 //{ // char cData[3333] = { 0, }; // // int iLength = WideCharToMultiByte( // CP_ACP, 0, data, -1, 0, 0, NULL, NULL); // // int iRet = WideCharToMultiByte( // CP_ACP, 0, data, -1, cData, iLength, NULL, NULL); // // return cData; //} //WCHAR * GetM2W(char* data) // 멀티바이트를 유니코드로 바꾸는 함수 //{ // WCHAR cData[3333] = { 0, }; // int iLength = MultiByteToWideChar( // CP_ACP, 0, data, -1, 0, 0); // // int iRet = MultiByteToWideChar( // CP_ACP, 0, data, -1, cData, iLength); // // return cData; //} //string w2m(wstring data) // 유니코드를 string으로 변경 //{ // string ret = string(data.begin(),data.end()); // return ret; //} //wstring m2w(string data) // 유니코드를 string으로 변경 //{ // wstring ret = wstring(data.begin(), data.end()); // return ret; //} // // // //void main() //{ // HANDLE hWritefile = CreateFile( // L"test.txt", // GENERIC_WRITE, 0, NULL, // CREATE_ALWAYS, // FILE_ATTRIBUTE_NORMAL, NULL); // 쓰기전용 txt 무조건 생성 // if (hWritefile != NULL) // { // TCHAR buf[] = L"asasasasasas"; // DWORD dwLength = sizeof(buf); // DWORD dwWritten; // bool iRet=WriteFile(hWritefile,buf,dwLength, // &dwWritten,NULL); // if (iRet == TRUE) // { // printf("출력완료"); // } // } // CloseHandle(hWritefile); // 파일을 닫는다 // // // // HANDLE hReadfile = CreateFile( // L"test.txt", // GENERIC_READ, 0, NULL, // OPEN_EXISTING, // FILE_ATTRIBUTE_NORMAL, NULL); // 파일을 연다 // if (hReadfile != NULL) // { // TCHAR buf[1024] = { 0, }; // DWORD dwLength = sizeof(buf); // DWORD dwRead; // bool iRet = ReadFile(hReadfile, buf, dwLength, // &dwRead, NULL); // if (iRet == TRUE) // { // wstring strWData = buf; // string strCData= w2m(strWData); // // printf("\n%s", strCData.c_str()); // _tcprintf(L"\n%s", m2w(strCData.c_str())); // // printf("\n%s", strCData.c_str()); // // char* pData = GetW2M(buf); // printf("\n%s", pData); // // char dddd[] = "aaaaa"; // wprintf(L"\n%s", GetM2W(pData)); // // //_tcprintf(L"\n%s", buf); // } // } // CloseHandle(hReadfile); // 파일을 닫는다. //}<file_sep>#include<stdio.h> #include<conio.h> //1Â÷¿ø ¹è¿­ //int index, arr[10]; // //void main() //{ // for (index = 0; index < 10; index++) // { // scanf_s("%d", &arr[index]); // } // for (index = 0; index < 10; index++) // { // printf("%d:%d\n", index, arr[index]); // } //} //void main() //{ // int i, integer[2]; // char ch[2]; // integer[0] = 1; // integer[1] = 2; // ch[0] = 'a'; ch[1] = 'b'; // // for (i = 0; i < 2; i++) // { // printf("\n%d", integer[i]); // } // for (i = 0; i < 2; i++) // printf("\n%c", ch[i]); // _getch(); //} #include<stdio.h> void main() { int i; static int integer[5]; static char ch[5]; static float f[5]; for (i = 0; i < 5; i++) { printf("%3d", integer[i]); printf("\n"); } for (i = 0; i < 5; i++) { printf("%3c",ch[i]); printf("\n"); } for (i = 0; i < 5; i++) { printf("%5.3f", f[i]); } _getch(); }<file_sep>#include <string> #include <iostream> #include <tchar.h> void printer(const char* pData) { std::cout << pData; } void main() { TCHAR data[] = _T("kgca"); TCHAR dataA[] = _T("game"); //UNICODE<->MULTIBYTE //std::wstring copyA = data; std::string copyData; if (dataA == copyData) { } copyData = data; copyData += dataA; std::cout << copyData; printer(copyData.c_str()); /*char copyData[256] = { 0, }; strcpy(copyData, data); strcat(copyData, "game"); memcpy(copyData, data, sizeof(char)*strlen(data)); if (strcmp(data, copyData) == 0)*/ }<file_sep>#pragma once #include "STD.h" enum KeyState { KEY_FREE = 0, KEY_PUSH, KEY_UP, KEY_HOLD, }; class CCInput { public: std::vector<wstring> m_strList; TCHAR m_csBuffer[MAX_PATH]; DWORD m_dwKeyState[256]; DWORD m_dwMouseState[3]; RECT m_MovePt; public: DWORD KeyCheck(DWORD dwKey); //클래스 멤버 변수 초기화 bool Init(); //매 프레임에서 계산을 담당한다. bool Frame(); //매 프레임에서 드로우를 담당한다. bool Render(); //클래스 멤버 변수 소멸을 담당한다. bool Release(); void MsgEvent(MSG msg); public: CCInput(); virtual ~CCInput(); }; <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <WS2tcpip.h> // InetNtop() . inet_ntop() #include <iostream> #include <map> #include "TProtocol.h" #pragma comment (lib,"ws2_32") using namespace std; bool BeginWinSock(); bool EndWinSock(); int SendMsg(SOCKET sock, char* msg, WORD type) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sendmsg.ph.len = strlen(msg); sendmsg.ph.type = type; memcpy(sendmsg.msg, msg, strlen(msg)); int sendbytes = 0; int iTotalsize = strlen(msg) + PACKET_HEADER_SIZE; char* pMsg = (char*)&sendmsg; do { send(sock, &pMsg[sendbytes], iTotalsize-sendbytes, 0); } while (sendbytes<iTotalsize); return sendmsg.ph.len + PACKET_HEADER_SIZE; } int SendMsg(SOCKET sock, PACKET_HEADER ph, char* msg) { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); sendmsg.ph = ph; memcpy(sendmsg.msg, msg, strlen(msg)); int sendbytes = 0; int iTotalsize = strlen(msg) + PACKET_HEADER_SIZE; char* pMsg = (char*)&sendmsg; do { send(sock, &pMsg[sendbytes], iTotalsize - sendbytes, 0); } while (sendbytes<iTotalsize); return sendmsg.ph.len + PACKET_HEADER_SIZE; } int SendMsg(SOCKET sock, UPACKET* uPacket) { int sendbytes = 0; int iTotalsize = strlen(msg) + PACKET_HEADER_SIZE; char* pMsg = (char*)&sendmsg; do { send(sock, &pMsg[sendbytes], iTotalsize - sendbytes, 0); } while (sendbytes<iTotalsize); return sendmsg.ph.len + PACKET_HEADER_SIZE; } DWORD WINAPI clientThread(LPVOID arg) { SOCKET sock = (SOCKET)arg; char buf[256] = { 0, }; while (1) { char buffer[256] = { 0, }; int recvbyte = 0; while (1) { recvbyte += recv(sock, (char*)&buffer[recvbyte], sizeof(char) * PACKET_HEADER_SIZE - recvbyte, 0); if (recvbyte == PACKET_HEADER_SIZE) { UPACKET packet; ZeroMemory(&packet, sizeof(packet)); memcpy(packet.ph, buffer, sizeof(char)*PACKET_HEADER_SIZE); int rByte == 0; do { rByte += recv(sock, (char*)&packet.msg[rByte], sizeof(char)*packet.ph.len - rByte, 0); } while (packet.ph.len > rByte) recvbyte = 0; switch (packet.ph.type) { case PACKET_CHAT_MSG: { printf("패킷 완성%s", packet.msg); SendMsg() }break; } } }Sleep(1); closesocket(sock); return 1; } void main() { if (BeginWinSock() == false) { return; } SOCKET listenSock; listenSock = socket(AF_INET, SOCK_STREAM, 0); // listen socket // ip + port -> bind -> 운영체제 보고,통지,알림,신고,적용,세팅 // port를 사용하고 있는 프로세스(인덱스에 불가 하다)(실행파일)(실행파일을 구분하는 용도로 사용한다)에게 알려 준다 SOCKADDR_IN sa; sa.sin_family = AF_INET; sa.sin_port = htons(10000); sa.sin_addr.s_addr = inet_addr("192,168,0,106"); //sa.sin_addr.s_addr = htonl(INADDR_ANY); bind(listenSock, (sockaddr*)&sa, sizeof(sa)); listen(listenSock, SOMAXCONN); // -> 개통 u_long on = TRUE; ioctlsocket(listenSock, FIONBIO, &on); //FIONBIO 블럭형 X int g_iNumUser = 0; while (g_iNumUser < 10) { SOCKADDR_IN clientaddr; int addlen = sizeof(clientaddr); SOCKET client = accept(listenSock, (sockaddr*)&clientaddr, &addlen); // 누군가 -> 접속시도 if (client == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) //WSAEWOULDBLOCK와 같지 않으면 오류 { exit(1); } // Use inet_ntop() or lnetNtop() printf("\nip=%s,port=%d", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); if (client != SOCKET_ERROR) { HANDLE hThread = CreateThread(0, 0, clientThread, clientaddr, 0, &threadID); } //char ip[INET_ADDRSTRLEN] = { 0, }; //char ip[256] = { 0, }; //printf("\nip=%s,port=%d", inet_ntop(AF_INET, &clientAddr.sin_addr, ip, INET6_ADDRSTRLEN), // ntohs(clientAddr.sin_port)); } } closesocket(listenSock); // listen -> 듣다. // client socket 준비 // while(1) // client socket = accept // 누군가 -> 접속시도.연결시도 -> 수용,허가 EndWinSock(); } bool BeginWinSock() // 윈속 초기화 { WSADATA wsa; int iRet = WSAStartup(MAKEWORD(2, 2), &wsa); if (iRet != 0)return false; return true; } bool EndWinSock() // 윈속 소멸 { WSACleanup(); return true; }<file_sep>#pragma once #include "TServerStd.h" class TServerObj { public: CRITICAL_SECTION m_cs; public: TServerObj(void); virtual ~TServerObj(void); }; <file_sep>#include "S_HeroObj.h" inline void DXUT_SetDebugName(ID3D11DeviceChild* pObj, const CHAR* pstrName) { if (pObj) pObj->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName); } HRESULT S_HeroObj::CreateConstantBuffer() { HRESULT hr = S_OK; D3D11_BUFFER_DESC Desc; Desc.Usage = D3D11_USAGE_DYNAMIC; Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; Desc.MiscFlags = 0; Desc.ByteWidth = sizeof(CBConstBoneWorld); V_RETURN(g_pd3dDevice->CreateBuffer(&Desc, NULL, m_pCBConstBoneWorld.GetAddressOf())); DXUT_SetDebugName(m_pCBConstBoneWorld.Get(), "CBConstBoneWorld"); return hr; } void S_HeroObj::SetActionFrame(int iStart, int iEnd, int iCharacterMatrixIndex, int iModelMatrixIndex) { m_iStartFrame = iStart; m_iLastFrame = iEnd; m_iCurrentFrame = (float)iStart; m_fFrame = m_iStartFrame; if (iCharacterMatrixIndex >= 0) { m_iMatrixIndex = iCharacterMatrixIndex; } } void S_HeroObj::SetBoneMatrices(vector<D3DXMATRIX>* pList) { for (UINT i = 0; i < pList->size(); i++) { D3DXMatrixTranspose(&m_cbBoneData.g_mConstBoneWorld[i], &((*pList)[i] * m_pMatrix[i])); } } bool S_HeroObj::Frame() { m_fFrame += (g_fSecPerFrame* m_fSpeed* m_pBoneObject->m_Scene.iFrameSpeed); m_iCurrentFrame = (int)m_fFrame; m_fLerpTime = m_fFrame - m_iCurrentFrame; #ifdef _DEBUG TCHAR strMessage[MAX_PATH] = { 0, }; _stprintf_s(strMessage, _T("<===== %d [%10.4f] %d====>\n "), m_iCurrentFrame, m_fLerpTime, m_iCurrentFrame + 1); OutputDebugString(strMessage); #endif if (m_pBoneObject->AniFrame(m_fFrame, m_fLerpTime, m_iStartFrame, m_iLastFrame, m_pMatrix)) { m_iCurrentFrame = m_iStartFrame; m_fFrame = (float)m_iStartFrame + m_fLerpTime; } return true; } bool S_HeroObj::Render(ID3D11DeviceContext* pContext) { for (int iObj = 0; iObj < m_pChar->m_pModelList.size(); iObj++) { TSkinObj* pModel = (TSkinObj*)m_pChar->m_pModelList[iObj]->m_pModel; _ASSERT(pModel); pModel->SetMatrix(&m_matWorld, &m_matView, &m_matProj); if (m_bConstantBufferType) { SetBoneMatrices(pModel->GetMatrix()); D3D11_MAPPED_SUBRESOURCE Mappedresource; pContext->Map(m_pCBConstBoneWorld.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &Mappedresource); memcpy(Mappedresource.pData, &m_cbBoneData, sizeof(CBConstBoneWorld)); pContext->Unmap(m_pCBConstBoneWorld.Get(), 0); pContext->VSSetConstantBuffers(1, 1, m_pCBConstBoneWorld.GetAddressOf()); } else { m_pBoneObject->SetBoneMatrices(pContext, m_pMatrix, pModel->GetMatrix()); ID3D11ShaderResourceView* aRViews[1] = { m_pBoneObject->m_pBoneBufferRV }; pContext->VSSetShaderResources(1, 1, aRViews); } pModel->Render(pContext); } if (m_bBoneRender) { memcpy(m_pBoneObject->m_pMatrix, m_pMatrix, m_pBoneObject->m_Scene.iNumMesh * sizeof(D3DXMATRIX)); m_pBoneObject->SetMatrix(&m_matWorld, &m_matView, &m_matProj); m_pBoneObject->Render(pContext); } return true; } S_HeroObj::S_HeroObj() { m_fSpeed = 1.0f; m_fFrame = 0.0f; m_fLerpTime = 0.0f; m_iStartFrame = 0; m_iLastFrame = 0; m_bConstantBufferType = false; m_bBoneRender = false; } S_HeroObj::~S_HeroObj() { } <file_sep>#include "SSample.h" #include "SDebugString.h" #include "TInput.h" LRESULT SSample::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { m_hEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, 500, 10, 200, 25, hWnd, (HMENU)202, g_hInstance, NULL); CreateWindow(_T("button"), _T("Send"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 700, 10, 50, 25, hWnd, (HMENU)302, g_hInstance, NULL); int iWidth = this->m_rtClient.right - m_rtClient.left; int iHeight = this->m_rtClient.bottom - m_rtClient.top; I_Debug.m_hList = CreateWindow(L"listbox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 0, 0, iWidth-400, iHeight, hWnd, (HMENU)0, m_hInstance, NULL); }return 0; case WM_COMMAND: switch (LOWORD(wParam)) { case 302: { GetWindowText(m_hEdit, m_strBuffer, 128); I_Debug.ConvertWideStringToAnsiCch(m_Client.m_strBuffer, m_strBuffer, 128); InvalidateRect(hWnd, NULL, NULL); if (m_Client.m_bLoginOK == false && m_Client.SendMsg(m_Client.m_strBuffer, PACKET_CHAT_NAME_ACK)) { m_Client.m_bLoginOK = true; } else { m_Client.m_bSend = true; } } } break; case WM_CHAR: break; } return -1; } bool SSample::Init() { m_Client.Init(); m_Udp.Init(); return true; } bool SSample::Frame() { if (I_Input.KeyCheck(VK_LEFT) == KEY_PUSH) { SPACKET_USER_POSITON UserData; UserData.bDirection = VK_LEFT; UserData.POS_X = 100; UserData.POS_Y = 100; UserData.User_iIndex = 999; char buffer[256] = { 0, }; int iSize = sizeof(UserData); memcpy(buffer, &UserData, iSize); m_Client.SendMsg(buffer, iSize, PACKET_USER_POSITON); } m_Client.ProcessPacket(); m_Client.Frame(); return true; } bool SSample::Release() { m_Udp.Release(); m_Client.Release(); return true; } SSample::SSample(void) { } SSample::~SSample(void) { } INT WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPreInst, LPWSTR strCmdLine, INT nShow) { SSample server; if (!server.SetWindow(hInst, _T("Client_Chat"), 800, 600)) { return 0; } SetCursor(NULL); if (server.Run() == false) { return 0; } return 1; }<file_sep>#pragma once #include "xStd.h" class xDevice { public: ID3D11Device* m_pd3dDevice; ID3D11DeviceContext* m_pContext; IDXGISwapChain* m_pSwapChain; ID3D11RenderTargetView* m_pRenderTargetView; IDXGIFactory* m_pDXGIFactory; DXGI_SWAP_CHAIN_DESC m_sd; ID3D11DepthStencilView* m_pDSV; public: bool Init(); bool Release(); HRESULT CreateDevice(); HRESULT CreateGIFactory(); HRESULT CreateSwapChain(); HRESULT SetRenderTargetView(); HRESULT CreateDSV(); void SetViewPort(); void ResizeDevice(UINT width, UINT height); virtual void DeleteDeviceResources(); virtual HRESULT CreateDeviceResources(UINT width, UINT height); public: xDevice(); virtual ~xDevice(); }; <file_sep>#include <iostream> using std::endl; using std::cout; using std::cin; //exception const char* account = "1234-5678"; //계좌번호 int sid = 1122; //비밀번호 int balance = 1000; //잔액 class AccountExpt { char acc[10]; int sid; public: AccountExpt(char* str, int id) { strcpy_s(acc, str); sid = id; } void What() { cout << "계좌번호: " << acc << endl; cout << "비밀번호: " << sid << endl; } }; int main(void) { char acc[10]; int id; int money; try { cout << "계좌번호 입력 : "; cin >> acc; cout << "비밀번호 4자리 입력 :"; cin >> id; if (strcmp(account, acc) || sid != id) throw AccountExpt(acc, id); cout << "출금액 입력 : "; cin >> money; if (balance < money) throw money; balance -= money; cout << "잔액 : " << balance << endl; } catch (int money) { cout << "부족 금액: " << money - balance << endl; } catch (std::exception& expt) { cout << "다음 입력을 다시 한번 확인 하세요" << endl; expt.what(); } catch (AccountExpt& expt) { cout << "다음 입력을 다시 한번 확인 하세요" << endl; expt.What(); } return 0; }<file_sep>#include "TPacket.h" // TPacket packet; // int id, ps, money; // char email[30], address[30]; // packet.SetID(1002) << id << ps; // packet.SetID(1002) << id << ps << email << addree << money; // packet.SetID(1002) >> id >> ps >> email >> addree >> money; // TPacket packet(1002); // packet << id << ps; // packet >> id >> ps; WORD TPacket::GetID() { return *m_PacketHeader.type; } WORD TPacket::GetSize() { return *m_PacketHeader.len; } char* TPacket::GetData() { return m_strPacketBuffer; } int TPacket::GetDataSize() { return m_iReceivedSize; } void TPacket::ReadData( void* buffer, int iSize ) { ::CopyMemory( buffer, m_pstrReadPosition, iSize ); m_pstrReadPosition+=iSize; }; void TPacket::WriteData( void* buffer, int iSize ) { if( m_iReceivedSize >= PACKETBUFFERSIZE-4) { // 오류 } *m_PacketHeader.len += iSize; CopyMemory(m_pstrWritePosition, buffer, iSize ); // 1차원 배열의 주소가 이동 m_pstrWritePosition+=iSize; // 실제 데이터의 바이트 용량 m_iReceivedSize += iSize; }; TPacket& TPacket::SetID( unsigned short ID ) { *m_PacketHeader.type = ID; return *this; }; // 패킷을 생성할 때 sum = a.v + b.v + c.v + d.v + e.v; TPacket& TPacket::operator << ( int arg ) { WriteData(&arg, sizeof(int)); return *this; }; // 패킷에서 데이터를 추출할 때 TPacket& TPacket::operator >> ( int& arg ) { ReadData(&arg, sizeof(int)); return *this; }; TPacket& TPacket::operator << ( DWORD arg ){ WriteData(&arg, sizeof(DWORD)); return *this; }; TPacket& TPacket::operator >> ( DWORD& arg ){ ReadData(&arg, sizeof(DWORD)); return *this; }; TPacket& TPacket::operator << ( bool arg ){ WriteData(&arg, sizeof(bool)); return *this; }; TPacket& TPacket::operator >> ( bool& arg ){ ReadData(&arg, sizeof(bool)); return *this; }; TPacket& TPacket::operator << ( unsigned short arg ){ WriteData(&arg, sizeof(unsigned short)); return *this; }; TPacket& TPacket::operator >> ( unsigned short& arg ){ ReadData(&arg, sizeof(unsigned short)); return *this; }; TPacket& TPacket::operator << ( float arg ){ WriteData(&arg, sizeof(float)); return *this; }; TPacket& TPacket::operator >> ( float& arg ){ ReadData(&arg, sizeof(float)); return *this; }; TPacket& TPacket::operator << ( char* arg ) { int iLen = sizeof(char)*strlen(arg); WriteData(&arg, iLen ); return *this; }; TPacket& TPacket::operator >> ( char* arg ) { int iLen = sizeof(char)*strlen(this->m_pstrReadPosition); ReadData(&arg, sizeof(char)*iLen); return *this; }; TPacket& TPacket::operator << ( TPacket& arg ) { unsigned short type = arg.GetID(); unsigned short size = arg.GetSize(); WriteData(&type, sizeof(unsigned short)); WriteData(&size, sizeof(unsigned short)); WriteData(&arg.m_pstrWritePosition, size-4); return *this; }; TPacket& TPacket::operator >> ( TPacket& arg ) { int type, size; char buffer[4096]={0,}; ReadData(&type, sizeof(unsigned short)); ReadData(&size, sizeof(unsigned short)); ReadData(&buffer, size-4 ); arg.SetID( type ); arg.WriteData( buffer, size-4 ); return *this; }; void TPacket::Clear() { ZeroMemory( m_strPacketBuffer, PACKETBUFFERSIZE ); m_PacketHeader.len = (WORD*)m_strPacketBuffer + 0; m_PacketHeader.type = (WORD*)m_strPacketBuffer + 2; m_pstrWritePosition = &m_strPacketBuffer[4]; m_pstrReadPosition = &m_strPacketBuffer[4]; m_iReceivedSize = 0; *m_PacketHeader.len = 4; } TPacket::TPacket(void) { Clear(); SetID( 0 ); }; TPacket::TPacket(unsigned short type) { Clear(); SetID( type ); }; TPacket::~TPacket(void) { } <file_sep>//컴파일러를 개발해라! //제품별(sun , hp) //TAttack,TDenfense,GENERATOR,OPTIMIZER //클래스 구조, sun? hp= 동일한 작업이 진행 #include <iostream> #include <memory> int g_iType = 0; #define WARRIOR 0 #define MAGICIAN 1 class TAttack {}; class TDenfense {}; class TSword :public TAttack {}; class TShield :public TDenfense {}; class TMagicainTAttack :public TAttack {}; class TMagicainTDenfense :public TDenfense {}; class TCharacter { public: virtual TAttack* CreateTAttack() = 0; virtual TDenfense* CreateTDenfense() = 0; TAttack* attack; TDenfense denfense; }; class TWarrior : public TCharacter { public: TAttack * CreateTAttack() { return new TSword; }; TDenfense* CreateTDenfense() { return new TShield; }; }; class TMagicain :public TCharacter { public: TAttack * CreateTAttack() { return new TMagicainTAttack; }; TDenfense* CreateTDenfense() { return new TMagicainTDenfense; }; }; void mian() { g_iType = MAGICIAN; //TCharacter* g_pFactory; std::shared_ptr<TCharacter> g_pFactory; if (g_iType == WARRIOR) { g_pFactory = std::make_shared<TWarrior>(); } else { g_pFactory = std::make_shared<TMagicain>(); } std::shared_ptr<TAttack> (g_pFactory->CreateTAttack()); std::shared_ptr<TDenfense> a(new TDenfense); std::shared_ptr<TDenfense> b(g_pFactory->CreateTDenfense); //pScanner = std ::move(a); a.swap(b); auto temp = g_pFactory->CreateTDenfense(); std::shared_ptr<TDenfense> pDenfense; pDenfense .reset(g_pFactory->CreateTDenfense()); //print(pDenfense.get()); //auto }<file_sep>#pragma once #include "STD.h" class CCWindow { public: HWND m_hWnd; // window 핸들 HINSTANCE m_hInstance; //실행객체 핸들 RECT m_rtWindow; RECT m_rtClient; public: void CenterWindow(); bool SetWindow(HINSTANCE hInstance, TCHAR* pTitleName, int iWidth = 800, int iHeight = 600); bool Run(); bool Release(); virtual bool GameRun() { return true; }; virtual void MsgEvent(MSG msg) {}; virtual bool GameInit() { return true; }; virtual bool GameRelease() { return true; }; public: CCWindow(); virtual ~CCWindow(); }; <file_sep>#include "xShape.h" HRESULT xLineShape::CreateVertexData() { HRESULT hr = S_OK; // ¾Õ¸é m_VertexList.resize(2); m_VertexList[0] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[1] = PNCT_VERTEX(D3DXVECTOR3(1.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_iNumVertex = m_VertexList.size(); return hr; } HRESULT xLineShape::CreateIndexData() { HRESULT hr = S_OK; m_IndexList.resize(2); int iIndex = 0; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 1; m_iNumIndex = m_IndexList.size(); return hr; } bool xLineShape::Draw( ID3D11DeviceContext* pContext, D3DXVECTOR3 vStart, D3DXVECTOR3 vEnd, D3DXVECTOR4 vColor) { PNCT_VERTEX vertexList[2]; vertexList[0] = m_VertexList[0]; vertexList[1] = m_VertexList[1]; vertexList[0].p = vStart; vertexList[0].c = vColor; vertexList[1].p = vEnd; vertexList[1].c = vColor; pContext->UpdateSubresource( m_dxObj.m_pVertexBuffer.Get(), 0, NULL, &vertexList, 0, 0); Render(pContext); pContext->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return true; } HRESULT xLineShape::LoadPixelShader(T_STR szName) { HRESULT hr = S_OK; m_dxObj.m_pPixelShader.Attach( DX::LoadPixelShaderFile(m_pd3dDevice, szName.c_str(),NULL,"PSLine")); return hr; } xLineShape::xLineShape() { m_Primitive = D3D_PRIMITIVE_TOPOLOGY_LINELIST; } xLineShape::~xLineShape() { } HRESULT xDirLineShape::CreateVertexData() { HRESULT hr = S_OK; // ¾Õ¸é m_VertexList.resize(6); m_VertexList[0] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[1] = PNCT_VERTEX(D3DXVECTOR3(10000.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[2] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[3] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 10000.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_VertexList[4] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(0.0f, 0.0f)); m_VertexList[5] = PNCT_VERTEX(D3DXVECTOR3(0.0f, 0.0f, 10000.0f), D3DXVECTOR3(0.0f, 0.0f, -1.0f), D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f), D3DXVECTOR2(1.0f, 0.0f)); m_iNumVertex = m_VertexList.size(); return hr; } HRESULT xDirLineShape::CreateIndexData() { HRESULT hr = S_OK; m_IndexList.resize(6); int iIndex = 0; m_IndexList[iIndex++] = 0; m_IndexList[iIndex++] = 1; m_IndexList[iIndex++] = 2; m_IndexList[iIndex++] = 3; m_IndexList[iIndex++] = 4; m_IndexList[iIndex++] = 5; m_iNumIndex = m_IndexList.size(); return hr; } bool xDirLineShape::Render(ID3D11DeviceContext* pContext) { xLineShape::Render(pContext); pContext->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return true; } xDirLineShape::xDirLineShape() { m_Primitive = D3D_PRIMITIVE_TOPOLOGY_LINELIST; } xDirLineShape::~xDirLineShape() { } <file_sep>#include<stdio.h> #include<conio.h> void main() { int a = 2; if (a == 1) { printf("A=1\n"); } else if (a == 2) { printf("A=2\n"); } else if (a == 3) { printf("A=3\n"); } else { printf("Error!\n"); } _getch(); }<file_sep>#include<iostream> #include<conio.h> using namespace std; class CCTest { public: void setNumber(int); void printNumber()const; const int* GetConst(); private: int number; }; void CCTest::setNumber(int num) { number = num; } //멤버 함수const가 붙으면 클래스 자체가 상수화된다. void CCTest::printNumber()const { cout << "\nBefore: " << number; const_cast<CCTest *>(this)->number--; cout << "\nAfter: " << number; } const int* CCTest::GetConst() { return&number; } int main() { CCTest X; X.setNumber(8); //1 const int* iValue = X.GetConst(); //*iValue=20; //상수에러 //2 int* iValue2 = const_cast<int*>(X.GetConst()); *iValue2 = 20; X.printNumber(); _getch(); }<file_sep>#include "Header.h" extern ClassDesc2* GetExportDesc(); HINSTANCE hInstance; int controlsInit = FALSE; BOOL WINAPI DllMain(HINSTANCE hinstDLL, ULONG fdwReason, LPVOID /*lpvReserved*/) { if (fdwReason == DLL_PROCESS_ATTACH) { hInstance = hinstDLL; DisableThreadLibraryCalls(hInstance); } return(TRUE); } __declspec(dllexport) const TCHAR* LibDescription() { return _T("KHJExporter 100"); } __declspec(dllexport) int LibNumberClasses() { return 1; } __declspec(dllexport) ClassDesc* LibClassDesc(int i) { switch (i) { case 0: return GetExportDesc(); default: return 0; } } __declspec(dllexport) ULONG LibVersion() { return VERSION_3DSMAX; } __declspec(dllexport) int LibInitialize(void) { #pragma message(TODO("Perform initialization here.")) return TRUE; } __declspec(dllexport) int LibShutdown(void) { #pragma message(TODO("Perform un-initialization here.")) return TRUE; } TCHAR *GetString(int id) { static TCHAR buf[256]; if (hInstance) return LoadString(hInstance, id, buf, _countof(buf)) ? buf : NULL; return NULL; } <file_sep>#include<stdio.h> //삼각형 반대로 만들기 void main() { int line = 0; scanf_s("%d", &line); //삼각형 for (int i = 0; i <= line; i++) { for (int j = 0; j <= i; j++) { printf("*"); }printf("\n"); } //밑으로 삼각형 for (int i = 0; i <= line; i++) { for (int j = 0; j <= line-i; j++) { printf("*"); } printf("\n"); } }<file_sep>#include "SDebugString.h" #include "SLock.h" // == Synchronize bool SDebugString::Init() // 초기화 { m_hList = NULL; return true; } bool SDebugString::Release() // 소멸 { return true; } void SDebugString::Print(const char* fmt, ...) // 출력 { if (m_hList == NULL)return; // 리스트가 NULL일경우 return { SLock Lock(this); va_list arg; va_start(arg, fmt); char buf[256] = { 0, }; vsprintf_s(buf, fmt, arg); SendMessage(m_hList,LB_ADDSTRING,0, // LB_ADDSTRING == 문자열 항목을 추가하여 그 인덱스를 리턴한다. -> LPARAM(포인터사용) (LPARAM)I_Debug.GetMbToWcs(buf)); // LPARAM == LONG_PTR int index = SendMessage(m_hList, LB_GETCOUNT, 0, 0); // LB_GETCOUNT == 총 항목 개수를 조사한다. if (index > 30) { SendMessage(m_hList, LB_RESETCONTENT,0,0); } va_end(arg); } } void SDebugString::T_ERROR(bool bPrint) { SLock Lock(this); if (WSAGetLastError() != WSA_IO_PENDING) { char * IpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&IpMsgBuf, 0, NULL); if (bPrint) { MessageBoxA(NULL, IpMsgBuf, "ERROR", MB_OK); } else { OutputDebugStringA((char*)IpMsgBuf); } LocalFree(IpMsgBuf); } } WCHAR* SDebugString::GetMbToWcs(const char* strMsg) { TCHAR msg[4096] = { 0, }; { SLock lock(this); int nRen = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, 0, 0); ConvertAnsiStringToWideCch(msg, strMsg, nRen); } return msg; } HRESULT SDebugString::ConvertAnsiStringToWideCch(WCHAR* msg, const char* strMsg, int nRen) { { SLock lock(this); if (msg == NULL || strMsg == NULL || nRen < 1) { return E_INVALIDARG; } int nRetrun = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, msg, nRen); if (nRen == 0)return E_FAIL; msg[nRen - 1] = 0; } return S_OK; } char* SDebugString::GetWcsToMbs(const WCHAR* strMsg) { char msg[4096] = { 0, }; { SLock lock(this); int iRen = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, 0, 0, NULL, NULL); ConvertWideStringToAnsiCch(msg, strMsg, iRen); } return msg; } HRESULT SDebugString::ConvertWideStringToAnsiCch(char* msg, const WCHAR* strMsg, int iRen) { { SLock lock(this); if (msg == NULL || strMsg == NULL || iRen < 1) { return E_INVALIDARG; } int iReturn = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, msg, iRen, NULL, NULL); if (iReturn == 0)return E_FAIL; } return S_OK; } SDebugString::SDebugString(void) { } SDebugString::~SDebugString(void) { } <file_sep>#pragma once #include "xCore.h" #include "x_AseMesh.h" #include "x_Mesh.h" class Sample : public xCore { public: x_AseMesh m_Obj; x_Mesh m_xObj; public: int IsEqulVertexList(x_Mesh& pMesh,PNCT_VERTEX& v) { for (int ilist = 0; ilist < pMesh.m_VertexList.size(); ilist++) { if (v == pMesh.m_VertexList[ilist]) { return ilist; } return -1; // xMesh.m_VertexList } } bool Init() { if (m_Obj.Load(L"box.ase")) { for (int iObj = 0; iObj < m_Obj.m_ObjectList.size(); iObj++) { x_Mesh xMesh; xMesh.m_iNumFaces = m_Obj.m_ObjectList[iObj].PosFaceList.size(); xMesh.m_TempVertexList.resize(xMesh.m_iNumFaces*3); for (int iFace = 0; iFace < xMesh.m_iNumFaces; iFace++) { for (int iVer = 0; iVer < 3; iVer++) { int iID = iFace * 3 + iVer; // pos if (m_Obj.m_ObjectList[iObj].vertexList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].PosFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].p = m_Obj.m_ObjectList[iObj].vertexList[iIndex]; } // nor if (m_Obj.m_ObjectList[iObj].NorList.size() > 0) { xMesh.m_TempVertexList[iID].n = m_Obj.m_ObjectList[iObj].NorList[iID]; } //color xMesh.m_TempVertexList[iID].c = D3DXVECTOR4(1, 1, 1, 1); if (m_Obj.m_ObjectList[iObj].ColFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].ColFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].c.x = m_Obj.m_ObjectList[iObj].ColList[iIndex].x; xMesh.m_TempVertexList[iID].c.y = m_Obj.m_ObjectList[iObj].ColList[iIndex].y; xMesh.m_TempVertexList[iID].c.z = m_Obj.m_ObjectList[iObj].ColList[iIndex].z; xMesh.m_TempVertexList[iID].c.w = 1.0f; } //tex if (m_Obj.m_ObjectList[iObj].texFaceList.size() > 0) { int iIndex = m_Obj.m_ObjectList[iObj].texFaceList[iFace].i[iVer]; xMesh.m_TempVertexList[iID].t.x = m_Obj.m_ObjectList[iObj].texList[iIndex].x; xMesh.m_TempVertexList[iID].t.y = m_Obj.m_ObjectList[iObj].texList[iIndex].y; } } } // Create ib + vb // xMesh.m_VertexList; for (int ivb = 0; ivb < xMesh.m_TempVertexList.size(); ivb++) { PNCT_VERTEX v = xMesh.m_TempVertexList[ivb]; int iPos = IsEqulVertexList(xMesh, v); if (iPos < 0) { xMesh.m_VertexList.push_back(v); iPos = xMesh.m_VertexList.size() - 1; } xMesh.m_IndexList.push_back(iPos); } xMesh.m_iNumIndex = xMesh.m_IndexList.size(); xMesh.m_iNumVertex = xMesh.m_VertexList.size(); int iRef = m_Obj.m_ObjectList[iObj].mtrlRef; T_STR texName = m_Obj.m_MaterialList[iRef].m_mapList[0].name; xMesh.Create(m_pd3dDevice, L"../../Include/data/Shader/map.hlsl", texName); //xMesh.m_iNumIndex = xMesh.m_iNumVertex; m_xObj.m_ObjectList.push_back(xMesh); } } return true; } bool Render() { for (auto mesh : m_xObj.m_ObjectList) { mesh.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); mesh.Render(m_pContext); } return true; } bool Release() { for (auto mesh : m_xObj.m_ObjectList) { mesh.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); mesh.Release(); } return true; } public: Sample() {} ~Sample() {} }; GAME_RUN("SAMPLE_ASE", 800, 600)<file_sep>#pragma once #include "xShape.h" class x_Mesh: public xShape { public: vector<x_Mesh> m_ObjectList; vector<x_Mesh> m_SubList; vector<PNCT_VERTEX> m_TempVertexList; int m_iNumFaces; //int m_iTexIndex; public: virtual HRESULT LoadGeometryShader(T_STR szName) { return S_OK; } /*virtual HRESULT CreateVertexData() override; virtual HRESULT CreateIndexData() override;*/ public: x_Mesh(); virtual ~x_Mesh(); }; <file_sep>#pragma once #include "SvrStd.h" class SServerObj { public: CRITICAL_SECTION m_cs; // ÀÓ°è ¿µ¿ª, public: SServerObj(void); virtual ~SServerObj(void); }; <file_sep>#include<stdio.h> void func(void); void main() { int count; for (count = 0; count < 10; count++) { printf("Atiteration %d:", count); func(); } } void func(void) { static int x = 0; int y = 0; printf("x=%d,y=%d\n", x++, y++); }<file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void main(int argc, char*argv[]) { if (argc != 3) { printf("쓰는법이 틀렸습니다."); exit; }_getch(); }<file_sep>//객체를 구성하는 부분을 먼저 생성하고 //이를 조합하여 객체를 완성한다. #include <iostream> class Product {}; class TAttack : public Product{}; class TDenfense : public Product{}; //class Door : public Product{}; class TCharacter { Product product[2]; }; class TBuilder { TCharacter* m_pMaze; virtual void BuildAttack(); virtual void BuildDefense(); public: virtual TCharacter* GetMaze() = 0; }; class TWarrior : public TBuilder { std::vector<TAttack> a; std::vector<TDenfense> b; TCharacter* GetMaze() { return NULL; } }; class TMagicain : public TBuilder { Product a; }; class TDirector //매니저 역활 //중개 역활(외주) { public: TCharacter * CreateMaze(TBuilder& pBuilder) { int iWork = 0; while (iWork>=2) { iWork+= pBuilder.BuildAttack(); iWork+= pBuilder.BuildDefense(); } return pBuilder->GetMaze(); }; }; void main() { TDirector director; TWarrior build; director.CreateMaze(build); TCharacter* maze = director.GetTCharacter(); }<file_sep>#pragma once #include "xCamera.h" class xArcBall { public: bool m_bDrag; D3DXVECTOR3 m_vDownPt; D3DXVECTOR3 m_vCurrentPt; D3DXQUATERNION m_qNow; D3DXQUATERNION m_qDown; public: D3DXMATRIX GetRotationMatrix(); D3DXQUATERNION QuatFromBallPoints( D3DXVECTOR3 m_vDownPt, D3DXVECTOR3 m_vCurrentPt); D3DXVECTOR3 ScreenToVector(float fX, float fY); void OnBegin(int x, int y); void OnMove(int x, int y); void OnEnd(); public: xArcBall(); virtual ~xArcBall(); }; <file_sep>#pragma once #include "TObject.h" #pragma warning(disable:4005) class S_Character :public TObject { public: T_STR m_szName; TBoneObj* m_pBoneObject; int m_iStarFrame; int m_iLastFrame; int m_iCurrentFrame; float m_fFrame; float m_fLerpTime; D3DXMATRIX m_pMatrix[255]; int m_iMatrixIndex; ID3D11Buffer* m_pBoneBuffer; ID3D11ShaderResourceView* m_pBoneBufferRV; public: bool Init(); bool Frame(); bool Render(ID3D11DeviceContext* pContext); bool Release(); bool Add(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pImmediateContext, const TCHAR* strSkinFileName, const TCHAR* strSkinShaderName, int iMatrixIndex = -1, int iModelMatrixIndex = -1); void SetModelMaterixID(int iMatrixIndex); void SetMatrix(D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj); void SetActionFrame(int iStart, int iEnd, int iCharacterMatrixIndex = -1, int iModelMatrixIndex = -1); public: S_Character(void); virtual ~S_Character(void); }; <file_sep>#include "TEllipse.h" void TEllipse::Draw() { cout << "Draw Ellipse: "; cout << "(" << x << "," << y << "),"; cout << width << "x" << height; cout << endl; } TEllipse::TEllipse() { cout << "TEllipse 持失切" << endl; } TEllipse::TEllipse(int x, int y, int width,int height) :TFigure(x, y, width, height) { cout << "TEllipse 持失切" << endl; } TEllipse::~TEllipse() { cout << "Tellipse 背薦切" << endl; } <file_sep>#include "DX_Device.h" #include "DX_State.h" #include "DX_Extern.h" //DX11에대한 정보인거 같으니 번역해서 한번 볼것 //http://seanmiddleditch.com/direct3d-11-debug-api-tricks/ HRESULT CDXDevice::CreateDevice() { HRESULT hr = S_OK; UINT CreateDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG //디버그시 포함 플레그 CreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif //TYPE들이 전부 배열로 되있는 이유 //버전체크를 위해서 제일 위의 목록부터 //지원가능한것을 체크해 나간다 //UNKOWN ==> 그래픽 카드 하드웨어가 어떤것인지 모를때 주로 사용하는 장치를 자동 지정 //HARDWARE ==> 지금 지정되어있는 장치를 사용 //WARP ==> 고성능 소프트웨어 레스터라이저 그냥 CPU가 GPU대신 고속 연산한다고 생각하면됨 //REFERENCE ==> CPU사용 D3D_DRIVER_TYPE DriverTypes[] = { D3D_DRIVER_TYPE_UNKNOWN, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE }; UINT NumDriverTypes = sizeof(DriverTypes) / sizeof(DriverTypes[0]); //그래픽장치 하드웨어의 버전을 물어보는것 //배열의 순서대로 물어본다 D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0 }; UINT NumFeatureTypes = sizeof(pFeatureLevels) / sizeof(pFeatureLevels[0]); //IDXGIAdapter ==> 그래픽 카드 장치를 의미 IDXGIAdapter* pAdapter; m_pGIFactory->EnumAdapters(0, &pAdapter); //위의 그래픽 카드 지원의 값 반환을 알아보기 위한 자료형 D3D_FEATURE_LEVEL retFeatureLevel; for (unsigned int i = 0; i < NumDriverTypes; i++) { m_DriverType = DriverTypes[i]; if (SUCCEEDED(hr = D3D11CreateDevice( pAdapter, m_DriverType, NULL, CreateDeviceFlags, pFeatureLevels, NumFeatureTypes, D3D11_SDK_VERSION, &m_pD3DDevice, &retFeatureLevel, &m_pImmediateContext))) { if (retFeatureLevel < D3D_FEATURE_LEVEL_11_0) { if (m_pImmediateContext) m_pImmediateContext->Release(); if (m_pD3DDevice) m_pD3DDevice->Release(); continue; } break; } } hr = m_pD3DDevice->QueryInterface(IID_PPV_ARGS(&m_pDebug)); return hr; } HRESULT CDXDevice::CreateGIFactory() { HRESULT hr; hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&m_pGIFactory)); return hr; } HRESULT CDXDevice::CreateSwapChain() { HRESULT hr = S_OK; //_ASSERT == 안정성 검사를 위한 매크로함수 _ASSERT(m_pD3DDevice != NULL); _ASSERT(m_pGIFactory != NULL); DXGI_SWAP_CHAIN_DESC SwapChainDesc; ZeroMemory(&SwapChainDesc, sizeof(SwapChainDesc)); SwapChainDesc.BufferCount = 1; //DX에서 출력할 창을 윈도우 메인 핸들을 통해 받아오는 작업 SwapChainDesc.OutputWindow = m_hWnd; //윈도우의 변형을 허가해 줄것인지 아닌지 SwapChainDesc.Windowed = TRUE; //윈도우의 가로 세로 값 SwapChainDesc.BufferDesc.Width = WINCX; SwapChainDesc.BufferDesc.Height = WINCY; //화면 주사율 설정(ex.60hz) //Numerator ==> 화면 주사율의 분자 //만약 114hz 화면 지원 모니터라면 바꿔주면 된다 SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; //Denominator ==> 화면 주사율의 분모 SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; //컬러값들을 RGBA를 8비트씩 사용하겠다 그냥 우리가 쓰던 컬러값을 사용하겠다 //UNORM은 그냥 마이너스 값이 필요없으니까 정규화 안된 unsinged값을 사용하겠다 //왜냐하면 컬러값이 0~255까지만 있으니까 SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //오프스크린 버퍼의 사용 용도 //선택의 여지가 없다 DXGI_USAGE_RENDER_TARGET_OUTPUT외의 것은 다른곳에서 사용 SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //멀티 샘플링의 숫자를 말한다 //여러번 뿌려주는것 ==> 계단현상방지 SwapChainDesc.SampleDesc.Count = 1; //윈도우 모드에서 전체화면 모드로 전환하면 창의 크기에 맞게 화면 해상도가 변경된다 SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; hr = m_pGIFactory->CreateSwapChain(m_pD3DDevice, &SwapChainDesc, &m_pSwapChain); //윈도우 전체화면 true false //전체화면 hr = m_pSwapChain->SetFullscreenState(false, NULL); return hr; } HRESULT CDXDevice::SetRenderTargetView() { HRESULT hr = S_OK; //생성된 스왑체인의 정보를 조회 hr = m_pSwapChain->GetDesc(&m_SwapChainDesc); //렌더타겟 생성 //__uuidof매크로 ==> DirectX112D에서 클래스네임 충돌이 안나게끔 //하기 위해 유일한 값으로 인스턴트생성을 하겠다라는 뜻 ID3D11Texture2D* pResource; m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pResource); hr = m_pD3DDevice->CreateRenderTargetView(pResource, NULL, &m_pRTV); pResource->Release(); if (SUCCEEDED(hr)) { //OM의 뜻 Output-Merger Stage 나중에 렌더링 파이프 라인 도표를 보면 될것 m_pImmediateContext->OMSetRenderTargets(1, &m_pRTV, m_pDSV); } return hr; } HRESULT CDXDevice::SetViewPort() { HRESULT hr = S_OK; //뷰포트 설정 m_ViewPort.TopLeftX = 0; m_ViewPort.TopLeftY = 0; m_ViewPort.Width = float(m_SwapChainDesc.BufferDesc.Width); m_ViewPort.Height = float(m_SwapChainDesc.BufferDesc.Height); //화면의 깊이값 m_ViewPort.MinDepth = 0; m_ViewPort.MaxDepth = 1; m_pImmediateContext->RSSetViewports(1, &m_ViewPort); return hr; } bool CDXDevice::Reset(UINT iWidth, UINT iHeight) { if (m_pD3DDevice == NULL) return true; HRESULT hr = S_OK; m_pImmediateContext->OMSetRenderTargets(0, NULL, NULL); if (m_pDSV != NULL) m_pDSV->Release(); if (m_pRTV != NULL) m_pRTV->Release(); if (FAILED(hr = m_pSwapChain->ResizeBuffers(m_SwapChainDesc.BufferCount, iWidth, iHeight, m_SwapChainDesc.BufferDesc.Format, m_SwapChainDesc.Flags))) { return false; } CreateDepthStencilState(); if (FAILED(hr = SetRenderTargetView())) return false; if (FAILED(hr = SetViewPort())) return false; CMyWindow::ResizeClient(iWidth, iHeight); return true; } HRESULT CDXDevice::CreateDepthStencilState() { HRESULT hr = S_OK; //생성된 스왑체인의 정보를 조회 hr = m_pSwapChain->GetDesc(&m_SwapChainDesc); ID3D11Texture2D* pTex; D3D11_TEXTURE2D_DESC texDesc; ZeroMemory(&texDesc, sizeof(D3D11_TEXTURE2D_DESC)); texDesc.Width = m_SwapChainDesc.BufferDesc.Width; texDesc.Height = m_SwapChainDesc.BufferDesc.Height; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_DEFAULT; texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; texDesc.CPUAccessFlags = 0; texDesc.MiscFlags = 0; if (FAILED(hr = GetDevice()->CreateTexture2D(&texDesc, NULL, &pTex))) { return hr; } D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; ZeroMemory(&dsvd, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC)); dsvd.Format = texDesc.Format; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; if (FAILED(hr = GetDevice()->CreateDepthStencilView(pTex, &dsvd, &m_pDSV))) { return hr; } SAFE_RELEASE(pTex); return hr; } bool CDXDevice::Init() { HRESULT hr; if (FAILED(CreateGIFactory())) { return false; } if (FAILED(CreateDevice())) { return false; } if (FAILED(CreateSwapChain())) { return false; } if (FAILED(CreateDepthStencilState())) { return false; } if (FAILED(SetRenderTargetView())) { return false; } if (FAILED(SetViewPort())) { return false; } //반드시 디바이스 생성시 어뎁터를 명시해야함 if (FAILED(hr = m_pGIFactory->MakeWindowAssociation(m_hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER))) { return hr; } return true; } bool CDXDevice::PreRender() { float fRed = 0.0f; fRed = (cosf(g_fAccumulation) * 0.5f + 0.5f); float fGreen = 0.0f; fGreen = (sinf(g_fAccumulation) * 0.5f + 0.5f); float clearColor[4] = { 0.f, 0.f, 1.f, 1 }; m_pImmediateContext->ClearRenderTargetView(m_pRTV, clearColor); m_pImmediateContext->ClearDepthStencilView(m_pDSV, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, (UINT8)0.0f); return true; } bool CDXDevice::PostRender() { //첫번째 인자값은 0일경우 즉시 시연되고 동기화된다(주사율을 지연안시키고 시연한다) //나머지 0이 아닌 1234값일 경우 지연되었다가 시연된다 //두번째 인자값은 사용하지 않는다 다른 플레그 값은 게임이 아닌 그래픽 작업등에서 사용한다 m_pSwapChain->Present(0, 0); return true; } bool CDXDevice::Release() { if (m_pDSV != NULL) m_pDSV->Release(); if (m_pRTV != NULL) m_pDSV->Release(); if (m_pImmediateContext != NULL) m_pImmediateContext->Release(); if (m_pD3DDevice != NULL) m_pD3DDevice->Release(); //잘모르겠으니 선생님 수업 잘들을것 //m_pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL); if (m_pDebug != NULL) m_pDebug->Release(); return true; } CDXDevice::CDXDevice() { m_pRTV = NULL; m_pSwapChain = NULL; m_pImmediateContext = NULL; m_pD3DDevice = NULL; } CDXDevice::~CDXDevice() { }<file_sep>#include <stdio.h> #define PI 3.14159 int main(void) { int number = 5; float ouzo = 13.5; int cost = 31000; printf("The %d women drank %f glasses of ouzo.\n", number, ouzo); printf("The value of pi is %f.\n", PI); printf("히히 안녕하세요.\n"); printf("%c%d\n", '$', cost); printf("If you want to printf percent...put character%%.\n"); number = 1 + 3; printf("number=%d", number); }<file_sep>#include "S_KHJ_AnimObj.h" void S_KHJ_AnimObj::GetAnimKeys(INode* pNode, SMesh* pMesh) { BOOL bPosAnim; BOOL bRotAnim; BOOL bScaleAnim; m_iDeltaTick = m_Scene.iTickPerFrame; if (CheckForAnimation(pNode, bPosAnim, bRotAnim, bScaleAnim)) { if (bPosAnim) { DumpPosSample(pNode, pMesh); } if (bRotAnim) { DumpRotSample(pNode, pMesh); } if (bScaleAnim) { DumpScaleSample(pNode, pMesh); } } // Export the visibility track Control* visCont = pNode->GetVisController(); if (visCont) { DumpFloatKeys(visCont, pMesh); } } bool S_KHJ_AnimObj::GetDecompAffine(TimeValue t, INode* pNode, AffineParts* ap, Point3* rotAxis, float* rotAngle) { Matrix3 tm = pNode->GetNodeTM(t) * Inverse(pNode->GetParentTM(t)); decomp_affine(tm, ap); Point3 vRotAxis; float fRotAngle; if (rotAngle != NULL && rotAngle != NULL) { AngAxisFromQ(ap->q, rotAngle, *rotAxis); } return true; } BOOL S_KHJ_AnimObj::CheckForAnimation(INode* pNode, BOOL& bPos, BOOL& bRot, BOOL& bScale) { AffineParts ap; Point3 firstPos, firstRotAxis, firstScaleFactor; float firstRotAngle; GetDecompAffine(m_Interval.Start(), pNode, &ap, &firstRotAxis, &firstRotAngle); firstPos = ap.t; firstScaleFactor = ap.k; TimeValue start = m_Interval.Start() + GetTicksPerFrame(); TimeValue end = m_Interval.End(); bPos = bRot = bScale = FALSE; float rotAngle; Point3 rotAxis; for (TimeValue t=start; t <= end; t += m_iDeltaTick) { GetDecompAffine(t, pNode, &ap, &rotAxis, &rotAngle); if (!bPos) { if (!EqualPoint3(ap.t, firstPos)) { bPos = TRUE; } } if (!bRot) { if (fabs(rotAngle - firstRotAngle) > ALMOST_ZERO) { bRot = TRUE; } else if (!EqualPoint3(rotAxis, firstRotAxis)) { bRot = TRUE; } } if (!bScale) { if (!EqualPoint3(ap.k, firstScaleFactor)) { bScale = TRUE; } } if (bPos && bRot && bScale)break; } return bPos || bRot || bScale; } void S_KHJ_AnimObj::DumpPosSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltaTick) { GetDecompAffine(t, pNode, &ap); SAnimTrack pAnim; pAnim.iTick = t; pAnim.vValue.x = ap.t.x; pAnim.vValue.y = ap.t.z; pAnim.vValue.z = ap.t.y; pMesh->m_PosTrack.push_back(pAnim); } } void S_KHJ_AnimObj::DumpRotSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltaTick) { GetDecompAffine(t, pNode, &ap); SAnimTrack pAnim; pAnim.iTick = t; pAnim.qValue.x = ap.q.x; pAnim.qValue.y = ap.q.z; pAnim.qValue.z = ap.q.y; pAnim.qValue.w = ap.q.w; pMesh->m_RotTrack.push_back(pAnim); } } void S_KHJ_AnimObj::DumpScaleSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltaTick) { GetDecompAffine(t, pNode, &ap); SAnimTrack Anim; Anim.iTick = t; Anim.vValue.x = ap.k.x; Anim.vValue.y = ap.k.z; Anim.vValue.y = ap.k.y; Anim.qValue.x = ap.u.x; Anim.qValue.y = ap.u.z; Anim.qValue.z = ap.u.y; Anim.qValue.w = ap.u.w; pMesh->m_SclTrack.push_back(Anim); } } void S_KHJ_AnimObj::DumpFloatKeys(Control* cont, SMesh* pMesh) { if (!cont) return; int i; IKeyControl *ikc = NULL; ikc = GetKeyControlInterface(cont); SAnimTrack Anim; // TCB float if (ikc && cont->ClassID() == Class_ID(TCBINTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { ITCBFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } // Bezier float else if (ikc && cont->ClassID() == Class_ID(HYBRIDINTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { IBezFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } else if (ikc && cont->ClassID() == Class_ID(LININTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { ILinFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } else { TSTR name; cont->GetClassName(name); // If it is animated at all if (cont->IsAnimated()) { // Get the range of the controller animation Interval range; // Get range of full animation Interval animRange = m_p3dsMax->GetAnimRange(); TimeValue t = cont->GetTimeRange(TIMERANGE_ALL).Start(); float value; // while we are inside the animation... while (animRange.InInterval(t)) { // Sample the controller range = FOREVER; cont->GetValue(t, &value, range); // Set time to start of controller validity interval t = range.Start(); Anim.iTick = t; Anim.vValue.x = value; pMesh->m_VisTrack.push_back(Anim); if (range.End() > cont->GetTimeRange(TIMERANGE_ALL).End()) { break; } else { // t = (range.End()/GetTicksPerFrame()+GetKeyFramestep()) * GetTicksPerFrame(); t = (range.End() / GetTicksPerFrame())*GetTicksPerFrame(); } } } } } S_KHJ_AnimObj::S_KHJ_AnimObj(void) { m_iDeltaTick = 160; } S_KHJ_AnimObj::~S_KHJ_AnimObj(void) { } //BOOL TbsAnimObj::IsKnownController(Control* cont) //{ // ulong partA, partB; // // if (!cont) // return FALSE; // ////Listed below are the first ULONG of the 8 byte ID. ////The second ULONG is 0 for all built-in classes (unless noted otherwise). ////For example a Class_ID for a TriObject would read: ////Class_ID(TRIOBJ_CLASS_ID, 0); ////Note that only built-in classes should have the second ULONG equal to 0. ////All plug-in developers should use both ULONGs. // // // // ClassID는 두개의 ULONG변수로 구성되며 내장된 클래스들은 모두 두번째 // // 변수는 0의 값을 갖고 있다. // // 단, 개발자의 플로그인은 두번째 값을 갖게 된다. // partA = cont->ClassID().PartA(); // partB = cont->ClassID().PartB(); // // if (partB != 0x00) // return FALSE; // // switch (partA) { // case TCBINTERP_POSITION_CLASS_ID: // case TCBINTERP_ROTATION_CLASS_ID: // case TCBINTERP_SCALE_CLASS_ID: // case HYBRIDINTERP_POSITION_CLASS_ID: // case HYBRIDINTERP_ROTATION_CLASS_ID: // case HYBRIDINTERP_SCALE_CLASS_ID: // case LININTERP_POSITION_CLASS_ID: // case LININTERP_ROTATION_CLASS_ID: // case LININTERP_SCALE_CLASS_ID: // return TRUE; // } // // return FALSE; //} // //void TbsAnimObj::DumpPosKeys(Control* cont, TMesh* pMesh) //{ // if (!cont) // return; // // int i; // IKeyControl *ikc = GetKeyControlInterface(cont); // // // TCB position // if (ikc && cont->ClassID() == Class_ID(TCBINTERP_POSITION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ITCBPoint3Key key; // ikc->GetKey(i, &key); // // TAnimTrack Anim; // Anim.m_dwType = T_TCBINTERP_POSITION_CLASS_ID; // Anim.iTick = key.time; // Anim.vValue.x = key.val.x; // Anim.vValue.y = key.val.z; // Anim.vValue.z = key.val.y; // Anim.tens = key.tens; // Anim.cont = key.cont; // Anim.bias = key.bias; // Anim.easeIn = key.easeIn; // Anim.easeOut = key.easeOut; // pMesh->m_PosTrack.push_back(Anim); // } // } // } //// // Key flags ////#define KEY_SELECTED IKEY_SELECTED ////#define KEY_XSEL IKEY_XSEL ////#define KEY_YSEL IKEY_YSEL ////#define KEY_ZSEL IKEY_ZSEL ////#define KEY_WSEL IKEY_WSEL ////#define KEY_ALLSEL IKEY_ALLSEL ////#define KEY_FLAGGED IKEY_FLAGGED ////#define KEY_TIME_LOCK IKEY_TIME_LOCK // // Bezier position // else if (ikc && cont->ClassID() == Class_ID(HYBRIDINTERP_POSITION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if(numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // IBezPoint3Key key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_HYBRIDINTERP_POSITION_CLASS_ID; // Anim.iTick = key.time; // Anim.vValue.x = key.val.x; // Anim.vValue.y = key.val.z; // Anim.vValue.z = key.val.y; // Anim.m_vIntan.x = key.intan.x; // Anim.m_vIntan.y = key.intan.z; // Anim.m_vIntan.z = key.intan.y; // Anim.m_vOuttan.x = key.outtan.x; // Anim.m_vOuttan.y = key.outtan.z; // Anim.m_vOuttan.z = key.outtan.y; // Anim.m_inLength.x = key.inLength.x; // Anim.m_inLength.y = key.inLength.z; // Anim.m_inLength.z = key.inLength.y; // Anim.m_outLength.x = key.outLength.x; // Anim.m_outLength.y = key.outLength.z; // Anim.m_outLength.z = key.outLength.y; // Anim.flags = key.flags; // pMesh->m_PosTrack.push_back(Anim); // } // } // } // // Linear position // else if (ikc && cont->ClassID() == Class_ID(LININTERP_POSITION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if(numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ILinPoint3Key key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_LININTERP_POSITION_CLASS_ID; // Anim.iTick = key.time; // Anim.vValue.x = key.val.x; // Anim.vValue.y = key.val.z; // Anim.vValue.z = key.val.y; // pMesh->m_PosTrack.push_back(Anim); // } // } // } //} // //void TbsAnimObj::DumpRotKeys(Control* cont, TMesh* pMesh) //{ // if (!cont) return; // // int i; // IKeyControl *ikc = GetKeyControlInterface(cont); // // if (ikc && cont->ClassID() == Class_ID(TCBINTERP_ROTATION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ITCBRotKey key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_TCBINTERP_ROTATION_CLASS_ID; // Anim.iTick = key.time; // Quat qR = QFromAngAxis( key.val.angle, key.val.axis ); // Anim.qValue.x = qR.x; // Anim.qValue.y = qR.z; // Anim.qValue.z = qR.y; // Anim.qValue.w = qR.w; // Anim.tens = key.tens; // Anim.cont = key.cont; // Anim.bias = key.bias; // Anim.easeIn = key.easeIn; // Anim.easeOut = key.easeOut; // pMesh->m_PosTrack.push_back(Anim); // } // } // } // else if (ikc && cont->ClassID() == Class_ID(HYBRIDINTERP_ROTATION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // IBezQuatKey key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_HYBRIDINTERP_ROTATION_CLASS_ID; // Anim.iTick = key.time; // Anim.qValue.x = key.val.x; // Anim.qValue.y = key.val.z; // Anim.qValue.z = key.val.y; // Anim.qValue.w = key.val.w; // pMesh->m_PosTrack.push_back(Anim); // } // } // } // else if (ikc && cont->ClassID() == Class_ID(LININTERP_ROTATION_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ILinRotKey key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_LININTERP_ROTATION_CLASS_ID; // Anim.iTick = key.time; // Anim.qValue.x = key.val.x; // Anim.qValue.y = key.val.z; // Anim.qValue.z = key.val.y; // Anim.qValue.w = key.val.w; // pMesh->m_PosTrack.push_back(Anim); // } // } // } //} // //void TbsAnimObj::DumpScaleKeys(Control* cont, TMesh* pMesh) //{ // if (!cont) // return; // // int i; // IKeyControl *ikc = GetKeyControlInterface(cont); // // if (ikc && cont->ClassID() == Class_ID(TCBINTERP_SCALE_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ITCBScaleKey key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_TCBINTERP_SCALE_CLASS_ID; // Anim.iTick = key.time; // // Anim.vValue.x = key.val.s.x; // Anim.vValue.y = key.val.s.z; // Anim.vValue.z = key.val.s.y; // // Anim.qValue.x = key.val.q.x; // Anim.qValue.y = key.val.q.z; // Anim.qValue.z = key.val.q.y; // Anim.qValue.w = key.val.q.w; // // Anim.tens = key.tens; // Anim.cont = key.cont; // Anim.bias = key.bias; // Anim.easeIn = key.easeIn; // Anim.easeOut = key.easeOut; // pMesh->m_PosTrack.push_back(Anim); // } // } // } // else if (ikc && cont->ClassID() == Class_ID(HYBRIDINTERP_SCALE_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // IBezScaleKey key; // ikc->GetKey(i, &key); // // TAnimTrack Anim; // Anim.m_dwType = T_HYBRIDINTERP_SCALE_CLASS_ID; // Anim.iTick = key.time; // // Anim.vValue.x = key.val.s.x; // Anim.vValue.y = key.val.s.z; // Anim.vValue.z = key.val.s.y; // // Anim.qValue.x = key.val.q.x; // Anim.qValue.y = key.val.q.z; // Anim.qValue.z = key.val.q.y; // Anim.qValue.w = key.val.q.w; // // Anim.m_vIntan.x = key.intan.x; // Anim.m_vIntan.y = key.intan.z; // Anim.m_vIntan.z = key.intan.y; // Anim.m_vOuttan.x = key.outtan.x; // Anim.m_vOuttan.y = key.outtan.z; // Anim.m_vOuttan.z = key.outtan.y; // Anim.flags = key.flags; // pMesh->m_PosTrack.push_back(Anim); // } // } // } // else if (ikc && cont->ClassID() == Class_ID(LININTERP_SCALE_CLASS_ID, 0)) // { // int numKeys = ikc->GetNumKeys(); // if (numKeys != 0) // { // for (i=0; i<numKeys; i++) // { // ILinScaleKey key; // ikc->GetKey(i, &key); // TAnimTrack Anim; // Anim.m_dwType = T_LININTERP_SCALE_CLASS_ID; // Anim.iTick = key.time; // // Anim.vValue.x = key.val.s.x; // Anim.vValue.y = key.val.s.z; // Anim.vValue.z = key.val.s.y; // // Anim.qValue.x = key.val.q.x; // Anim.qValue.y = key.val.q.z; // Anim.qValue.z = key.val.q.y; // Anim.qValue.w = key.val.q.w; // pMesh->m_PosTrack.push_back(Anim); // } // } // } //}<file_sep>#pragma once #include <iostream> struct SNode { int m_iData; SNode* m_pNextNode; SNode() {} SNode(int _iData) { m_iData = _iData; m_pNextNode = NULL; } };<file_sep>#pragma once #include "SCHAT_Client.h" #include "SUdpSocket.h" #include "TCore.h" class SSample : public TCore { public: SUdpSocket m_Udp; SCHAT_Client m_Client; HWND m_hEdit; HWND m_hChatEdit; TCHAR m_strBuffer[128]; public: bool Init(); bool Frame(); bool Release(); bool PreRender() { return true; } bool PostRender() { return true; } LRESULT MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); public: SSample(void); virtual ~SSample(void); }; <file_sep>#include "TPoint.h" void TPoint::SetPosition(int _x, int _y) { x = _x; y = _y; } void TPoint::Move(int _x, int _y) { x += _x; y += _y; } void TPoint::Show(void) { cout << "(" << x << "," << y << ")" << endl; } TPoint::TPoint() { cout << "Constuctor" << endl; } TPoint::~TPoint() { cout << "Distructor" << endl; } <file_sep>#pragma once #include "xCamera.h" class SArcBall { public: bool m_bDrag; D3DXVECTOR3 m_vDownPT; D3DXVECTOR3 m_vCurrentPT; D3DXQUATERNION m_qNow; D3DXQUATERNION m_qDown; public: D3DXMATRIX GetRotationMatrix(); D3DXVECTOR3 ScreenToVector(float fX,float fY); D3DXQUATERNION QuatFromBallPoints(D3DXVECTOR3 m_vDownPt, D3DXVECTOR3 m_vCurrentPt); void OnBegin(int x, int y); void OnMove(int x, int y); void OnEnd(); public: SArcBall(); virtual ~SArcBall(); }; <file_sep>#pragma once #include "DXWindow.h" #include "DXDevice.h" class Sample : public DXWindow { public: bool Init(); bool Render(); bool Release(); public: Sample(void); ~Sample(void); };<file_sep>#pragma once #include "TCore.h" #include "TClient.h" #include "TUdpSocket.h" class Sample: public TCore { public: TUdpSocket m_Udp; TClient m_Client; HWND m_hEdit; HWND m_hChatEdit; TCHAR m_strBuffer[128]; public: bool Init(); bool Frame(); bool Release(); bool PreRender(){ return true; } bool PostRender() { return true; } LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: Sample(void); ~Sample(void); }; <file_sep>#include <iostream> using namespace std; class TClass { private: int m_iValue; public: TClass(int iValue) :m_iValue(iValue) { } TClass(TClass& copy) : m_iValue(copy.m_iValue) { } ~TClass(){} }; class TClassExplicit { private: int m_iValue; public: //explicit는 생성자 앞에 붙여서 묵시적인 호출을 방지한다. //이는 명시적인 호출만 가능토록 한다. explicit TClassExplicit(int iValue) :m_iValue(iValue) { } //explicit을 복사 생성자에서 사용하면 // 대입 연산자를 통하여 객체의 생성 및 초기화를 할 수 없다. explicit TClassExplicit(TClassExplicit& copy); ~TClassExplicit() {} }; TClassExplicit::TClassExplicit(TClassExplicit& copy) : m_iValue(copy.m_iValue) { //m_iValue=copy.m_ivalue; } class TClassMutable { private: int m_iValue; //mutable 은 const 함수에서 변경가능해 진다. //이는 constdml 예외를 두는 결과가 된다. mutable int m_iData; public: // 함수가 const 이지만 mutable는 값의 변경을 예외적으로 허용한다. int Get(int iValue)const { m_iData = iValue; return m_iData; } explicit TClassMutable(int iVlaue) : m_iValue(iValue) { } explicit TClassMutable(TClassMutable& copy) :m_iValue(copy.m_iValue) {} TClassMutable(){} }; void main() { TClass tA(3); TClass tB = 3; TClass tC = tA; TClassExplicit tD(3); // 묵시적 변환이 발생하지 못한다. //TClassExplicit tE=3;//Error // 대입 연산자를 통하여 객체의 생성 및 초기화를 할 수 없다. //TClassExplicit tF=tD//Error TClassExplicit pColp(tD);//oK TClassMutable tG(3); cout << tG.Get(5); }<file_sep>#include "Sample.h" #include "SDebugString.h" #include "TInput.h" #include "TStd.h" LRESULT Sample::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch( msg ) { case WM_CREATE: { m_hEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, 500, 10, 200, 25, hWnd, (HMENU)202, g_hInstance, NULL ); CreateWindow(_T("button"), _T("Send"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON , 700, 10, 50, 25, hWnd, (HMENU)302, g_hInstance, NULL ); int iWidth = this->m_rtClient.right - m_rtClient.left; int iHeight = this->m_rtClient.bottom - m_rtClient.top; I_Debug.m_hList = CreateWindow( L"listbox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 0, 0, iWidth -300, iHeight, hWnd, (HMENU)0, m_hInstance, NULL ); }return 0; case WM_COMMAND: switch( LOWORD(wParam)) { case 302: { GetWindowText( m_hEdit, m_strBuffer, 128 ); I_Debug.ConvertWideStringToAnsiCch( m_Client.m_strBuffer, m_strBuffer, 128 ); InvalidateRect( hWnd, NULL, NULL ); if( m_Client.m_bLoginOK==false && m_Client.SendMsg( m_Client.m_strBuffer,PACKET_CHAT_NAME_ACK) ) { m_Client.m_bLoginOK = true; } else { m_Client.m_bSend = true; } } } break; case WM_CHAR: break; } return -1; } bool Sample::Init() { m_Client.Init(); m_Udp.Init(); return true; } bool Sample::Frame() { // 유저 키 입력 및 전송 if( I_Input.KeyCheck(VK_LEFT) == KEY_PUSH ) { TPACKET_USER_POSITION userdata; userdata.direction = VK_LEFT; userdata.posX = 100; userdata.posY = 100; userdata.user_idx = 999; char buffer[256]= {0,}; int iSize = sizeof( userdata ); memcpy( buffer, &userdata, iSize ); m_Client.SendMsg( buffer, iSize, PACKET_USER_POSITION ); } m_Client.ProcessPacket(); m_Client.Frame(); return true; } bool Sample::Release() { m_Udp.Release(); m_Client.Release(); return true; } Sample::Sample(void) { } Sample::~Sample(void) { } INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE hPreInst, LPWSTR strCmdLine, INT nShow ) { Sample server; if (!server.SetWindow(hInst, _T("ChatClient_1"), 800, 600)) { return 0; } SetCursor(NULL); // 윈도우 프로시져 담당 if( server.Run() == false ) { return 0; } return 1; }<file_sep>#pragma once #include "S_SvrObj.h" class S_DebugString : public S_SvrObj,public Singleton<S_DebugString> { private: friend class Singleton<S_DebugString>; public: HWND m_hList; public: void Print(const char* fmt, ...); bool Init(); bool Release(); WCHAR* GetMbToWcs(const char* strMsg); char* GetWcsToMbs(const WCHAR* strMsg); HRESULT ConvertWideStringToAnsiCch(char* msg, const WCHAR* strMsg, int iRen); HRESULT ConvertAnsiStringToWideCch(WCHAR* msg, const char* strMsg, int iRen); void S_Error(bool bprint = false); public: S_DebugString(); virtual ~S_DebugString(); }; #define S_Debug S_DebugString::GetInstance() <file_sep>#include "S_Global.h" int S_Global::GetIndex(const TCHAR* strNodeName) { return m_MatrixMap.GetID(strNodeName); } bool S_Global::CheckFile(Interface* pMax) { TSTR curtFileName = FixupName(pMax->GetCurFileName()); if (curtFileName.isNull() == false && m_CurtFileName == curtFileName) { return false; } m_MatrixMap.Release(); m_pMtlList.clear(); m_CurtFileName = curtFileName; return true; } bool S_Global::Initialize(Interface* pMax) { m_p3dsMax = pMax; m_pRootNode = pMax->GetRootNode(); if (pMax == NULL && m_pRootNode == NULL) { return false; } if (CheckFile(pMax) == false)return true; // scene 정보 얻기 m_Interval = m_p3dsMax->GetAnimRange(); memset(&m_Scene, 0, sizeof(m_Scene)); m_Scene.iVersion = 20190121; m_Scene.iFirstFrame = m_Interval.Start() / GetTicksPerFrame(); m_Scene.iLastFrame = m_Interval.End() / GetTicksPerFrame(); m_Scene.iFrameSpeed = GetFrameRate(); m_Scene.iTickPerFrame = GetTicksPerFrame(); // 최 상위 INode 얻기 PreProcess(m_p3dsMax->GetRootNode()); m_Scene.iNumMesh = m_MatrixMap.Count(); m_Scene.iMaxWeight = 1; return true; } void S_Global::PreProcess(INode* pNode) { if (pNode == NULL)return; AddObject(pNode); AddMtl(pNode); // 재귀 호출 int iNumChildren = pNode->NumberOfChildren(); // pNode의 자식 노드 개수를 반환함. for (int iCnt = 0; iCnt < iNumChildren; iCnt++) { INode* pChild = pNode->GetChildNode(iCnt); // iCnt 번째의 자식 노드를 반환함. PreProcess(pChild); } } void S_Global::AddObject(INode* pNode) { // 오브젝트 추가 ObjectState os = pNode->EvalWorldState(m_Interval.Start()); // 타켓 클래스인 오브젝트는 불필요한 오브젝트이다. if (os.obj) { // 타켓 클래스인 오브젝트는 불필요한 오브젝트이다. if (os.obj->ClassID() == Class_ID(TARGET_CLASS_ID, 0)) { return; } switch (os.obj->SuperClassID()) { case GEOMOBJECT_CLASS_ID: case HELPER_CLASS_ID: { int iIndex = m_MatrixMap.Add(pNode->GetName()); TSTR parentname = pNode->GetParentNode()->GetName(); m_MatrixMap.GetPtr(iIndex)->SetNode(pNode, m_Interval.Start(), m_MatrixMap.GetPtr(parentname)); } break; } } } void S_Global::AddMtl(INode* pNode) { // 매터리얼 추가(중복 제거) Mtl* pMtl = pNode->GetMtl(); if (pMtl != NULL) { bool bAdd = true; for (int iCnt = 0; iCnt < m_pMtlList.size(); iCnt++) { if (m_pMtlList[iCnt] == pMtl) { bAdd = false; break; } } if(bAdd) { m_pMtlList.push_back(pMtl); } } } int S_Global::GetMtlRef(Mtl* pMtl) { for (int iMtl = 0; iMtl < m_pMtlList.size(); iMtl++) { if (m_pMtlList[iMtl] == pMtl) { return iMtl; } } return -1; } TCHAR* S_Global::FixupName(MSTR name) { memset(m_tmpBuffer, 0, sizeof(TCHAR)*MAX_PATH); TCHAR* cPtr; _tcscpy(m_tmpBuffer, name); cPtr = m_tmpBuffer; while (*cPtr) { if (*cPtr == '"') *cPtr = SINGLE_QUOTE; else if (*cPtr == ' ' || *cPtr <= CTL_CHARS) *cPtr = _T('_'); cPtr++; } return m_tmpBuffer; } void S_Global::DumpMatrix3(Matrix3* m, D3D_MATRIX& mat) { Point3 row; row = m->GetRow(0); mat._11 = row.x; mat._13 = row.y; mat._12 = row.z; row = m->GetRow(2); mat._21 = row.x; mat._23 = row.y; mat._22 = row.z; row = m->GetRow(1); mat._31 = row.x; mat._33 = row.y; mat._32 = row.z; row = m->GetRow(3); mat._41 = row.x; mat._43 = row.y; mat._42 = row.z; mat._14 = mat._24 = mat._34 = 0.0f; mat._44 = 1.0f; } void S_Global::DumpPoint3(Point3& pDest, Point3& pSrc) { pDest.x = pSrc.x; pDest.y = pSrc.z; pDest.z = pSrc.y; } bool S_Global::TMNegParity(Matrix3 &m) { return (DotProd(CrossProd(m.GetRow(0), m.GetRow(1)), m.GetRow(2)) < 0.0) ? 1 : 0; } bool S_Global::EqualPoint2(Point2 p1, Point2 p2) { if (fabs(p1.x - p2.x) > ALMOST_ZERO) return false; if (fabs(p1.y - p2.y) > ALMOST_ZERO) return false; return true; } bool S_Global::EqualPoint3(Point3 p1, Point3 p2) { if (fabs(p1.x - p2.x) > ALMOST_ZERO) return false; if (fabs(p1.y - p2.y) > ALMOST_ZERO) return false; if (fabs(p1.z - p2.z) > ALMOST_ZERO) return false; return true; } bool S_Global::EqualPoint4(Point4 p1, Point4 p2) { if (fabs(p1.x - p2.x) > ALMOST_ZERO) return false; if (fabs(p1.y - p2.y) > ALMOST_ZERO) return false; if (fabs(p1.z - p2.z) > ALMOST_ZERO) return false; if (fabs(p1.w - p2.w) > ALMOST_ZERO) return false; return true; } S_Global::S_Global(void) { m_p3dsMax = NULL; m_pRootNode = NULL; } S_Global::~S_Global(void) { m_MatrixMap.Release(); } <file_sep>#include<stdio.h> extern int a; void func() { a = 5; } int a; void main() { printf("%d\n", a); func(); a = 10; printf("%d\n", a); }<file_sep>// DLL 응용 프로그램을 위해 내보낸 함수를 정의합니다 #define KHJ_EXPORT_CLASS_ID Class_ID(0x36765dca, 0xa95244d) #include "Header.h" #include "S_KHJ_Writer.h" #include "S_KHJ_SkinExp.h" class KHJMaxExporter { public: S_KHJ_Writer g_Writer; public: //HWND hPanel; //IUtil *iu; //Interface *ip; KHJMaxExporter(); virtual ~KHJMaxExporter(); int ExtCount(); const TCHAR* Ext(int n); const TCHAR* LongDesc(); const TCHAR* ShortDesc(); const TCHAR* AuthorName(); const TCHAR* CopyrightMessage(); const TCHAR* OtherMessage1(); const TCHAR* OtherMessage2(); unsigned int Version(); void ShowAbout(HWND hWnd); public: BOOL SupportsOptions(int ext, DWORD options); int DoExport(const TCHAR*name, ExpInterface*ei, Interface* i, BOOL suppressPrompts = FALSE, DWORD options = 0); // virtual void DeleteThis() {} // // virtual void BeginEditParams(Interface *ip, IUtil *iu); // virtual void EndEditParams(Interface *ip, IUtil *iu); // // virtual void Init(HWND hWnd); // virtual void Destroy(HWND hWnd); // // void SelectionSetChanged(Interface *ip, IUtil *iu); // // // static KHJMaxExporter* GetInstance() // { // static KHJMaxExporter theKHJUtilExp; // return &theKHJUtilExp; // } // //private: // // static INT_PTR CALLBACK DlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); }; class KHJUtilExpClassDesc : public ClassDesc2 { public: virtual int IsPublic() { return TRUE; } virtual void* Create(BOOL) { return new KHJMaxExporter(); } virtual const TCHAR* ClassName() { return _T("KHJUtilExpClassDesc"); } virtual SClass_ID SuperClassID(){ return UTILITY_CLASS_ID; } virtual Class_ID ClassID() { return KHJ_EXPORT_CLASS_ID; } virtual const TCHAR* Category() { return _T("KHJMaxExporter"); } virtual const TCHAR* InternalName() { return _T("KHJUtilExpClassDesc"); } virtual HINSTANCE HInstance() { return hInstance; } }; ClassDesc2* GetExportDesc() { static KHJUtilExpClassDesc KHJUtilExpDesc; return &KHJUtilExpDesc; } KHJMaxExporter::KHJMaxExporter() /*: hPanel(nullptr) , iu(nullptr)*/ { } KHJMaxExporter::~KHJMaxExporter() { } int KHJMaxExporter::ExtCount() { return 1; } const TCHAR* KHJMaxExporter::Ext(int) { return _T("KHJ"); } const TCHAR* KHJMaxExporter::LongDesc() { return _T("KHJExporter 2.0"); } const TCHAR* KHJMaxExporter::ShortDesc() { return _T("KHJExporter"); } const TCHAR* KHJMaxExporter::AuthorName() { return _T("PROKVIP"); } const TCHAR* KHJMaxExporter::CopyrightMessage() { return _T(""); } const TCHAR* KHJMaxExporter::OtherMessage1() { return _T(""); } const TCHAR* KHJMaxExporter::OtherMessage2() { return _T(""); } unsigned int KHJMaxExporter::Version() { return 100; } void KHJMaxExporter::ShowAbout(HWND) { } BOOL KHJMaxExporter::SupportsOptions(int, DWORD) { return TRUE; } int KHJMaxExporter::DoExport(const TCHAR*name, ExpInterface*ei, Interface* i, BOOL suppressPrompts, DWORD options) { g_Writer.Initialize(i,name); g_Writer.Release(); } //void KHJMaxExporter::BeginEditParams(Interface* ip, IUtil* iu) //{ // this->iu = iu; // this->ip = ip; // hPanel = ip->AddRollupPage(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), DlgProc, _T("Parameters"), 0); //} // //void KHJMaxExporter::EndEditParams(Interface* ip, IUtil*) //{ // this->iu = NULL; // this->ip = NULL; // this->iu = nullptr; // // ip->DeleteRollupPage(hPanel); // hPanel = nullptr; //} // //void KHJMaxExporter::Init(HWND hWnd) //{ // /*if (I_SkinExp.Init() == false)return; // if (I_Writer.Initialize(ip) == false)return; // // if (I_Writer.m_MatrixMap.Count() > 0) // { // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_SKINEXP), true); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_MATRIXEXP), true); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_OBJEXPORT), true); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_UPDATE), false); // } // else // { // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_SKINEXP), false); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_MATRIXEXP), false); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_OBJEXPORT), false); // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_UPDATE), true); // }*/ // //SendMessage(theKHJUtilExp::GetInstance()->hPanel, BM_SETCHECK, BST_CHECKED, 0); // //CheckDlgButton(KHJMaxExporter.hPanel, IDC_BINDPOSE, TRUE ); // //EnableWindow(GetDlgItem(theKHJUtilExp::GetInstance()->hPanel, IDC_BINDPOSE), false); //} // //void KHJMaxExporter::Destroy(HWND hWnd) //{ // /*I_SkinExp.Release(); // I_Writer.Release();*/ //} // //void KHJMaxExporter::SelectionSetChanged(Interface* ip, IUtil* iu) //{ // if(ip->GetSelNodeCount()<=0) // { // return; // } // for (int iSelectobj = 0; iSelectobj < ip->GetSelNodeCount(); iSelectobj++) // { // // } // //if (ip->GetSelNodeCount() <= 0) // //{ // // return; // //} // //if (I_Writer.Initialize(ip) == false) // //{ // // return; // //} // //I_SkinExp.Release(); // // //for (int iSelectObj = 0; iSelectObj < ip->GetSelNodeCount(); iSelectObj++) // //{ // // I_SkinExp.GetNodeInfo(ip->GetSelNode(iSelectObj), ip->GetTime()); // //} // //if (I_Writer.m_MatrixMap.Count() > 0) // //{ // // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_MATRIXEXP), true); // // if (ip->GetSelNodeCount() > 0) // // { // // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_SKINEXP), true); // // } // // else // // { // // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_SKINEXP), false); // // } // //} // //else // //{ // // EnableWindow(GetDlgItem(KHJMaxExporter::GetInstance()->hPanel, IDC_MATRIXEXP), false); // //} //} // //INT_PTR CALLBACK KHJMaxExporter::DlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) //{ // /*switch (msg) // { // case WM_INITDIALOG: // KHJMaxExporter::GetInstance()->Init(hWnd); // break; // case WM_DESTROY: // KHJMaxExporter::GetInstance()->Destroy(hWnd); // break; // case WM_COMMAND: // switch (LOWORD(wParam)) // { // case IDC_OBJEXPORT: // { // I_Writer.Initialize(KHJMaxExporter::GetInstance()->ip); // I_Writer.KHJExport(); // }break; // case IDC_SKINEXP: // { // I_Writer.SetBindPose(true); // I_Writer.Initialize(KHJMaxExporter::GetInstance()->ip); // I_SkinExp.m_Scene = I_Writer.m_Scene; // I_SkinExp.skmExport(); // }break; // case IDC_MATRIXEXP: // { // I_Writer.Initialize(KHJMaxExporter::GetInstance()->ip); // I_Writer.SetBindPose(true); // I_Writer.matExport(); // }break; // }break; // // case WM_LBUTTONDOWN: // case WM_LBUTTONUP: // case WM_MOUSEMOVE: // GetCOREInterface()->RollupMouseMessage(hWnd, msg, wParam, lParam); // break; // default: // return 0; // } // return 1;*/ // switch (msg) // { // case WM_INITDIALOG: // KHJMaxExporter::GetInstance()->Init(hWnd); // break; // case WM_DESTROY: // KHJMaxExporter::GetInstance()->Destroy(hWnd); // break; // case WM_COMMAND: // switch (LOWORD(wParam)) // { // // }break; // case WM_LBUTTONDOWN: // case WM_LBUTTONUP: // case WM_MOUSEMOVE: // GetCOREInterface()->RollupMouseMessage(hWnd, msg, wParam, lParam); // break; // default: // return 0; // } // return 1; //}<file_sep>#pragma once #include "xShape.h" #define MAX_SKYBOX_TEXTURE 6 class xSkyBox : public xBoxShape { ComPtr<ID3D11ShaderResourceView> m_pTexSRV[MAX_SKYBOX_TEXTURE]; public: bool Create(ID3D11Device* pDevice, T_STR szShaderName, T_STR szTextureName); bool Render(ID3D11DeviceContext* pContext); bool Release(); HRESULT LoadTexture(T_STR szName); public: xSkyBox(); virtual ~xSkyBox(); }; <file_sep>#include<stdio.h>//printf문과 scanf문 사용하기 위한 헤더 #include<conio.h>//_getch()문 사용을 위한 헤더 #define SWAP(a,b) {int t; t=a; a=b; b=t;}//a와b를 교환 void SequenoeSort(int *base, int n); int main(void)//메인 { int arr[10] = { 9,4,3,10,5,8,7,6,2,1, }; // 배열 임의 초기화 SequenoeSort(arr, 10);//함수 호출 _getch(); return 0; } void ViewArr(int *arr, int n); void SequenoeSort(int *base, int n) { int i; int j; ViewArr(base, n); //현재 상태 출력 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (base[i] > base[j])//앞쪽 원소가 더 크면 { SWAP(base[i], base[j]);//교환 ViewArr(base, n);//상태 출력 } } } } void ViewArr(int *arr, int n)// 현재 상태 배열 출력 { int i = 0; for (i = 0; i < n; i++) { printf("%2d\t", arr[i]); } printf("\n"); }<file_sep>//정렬 //배열의 자료를 원하는 순으로 배치하는것. /*순차 정렬 (Sequential Sort) 순차 정렬은 맨 앞에서 부터 제일 작은 원소를 배치하게 만들어 나가는 알고리즘이다*/ /*버블정렬(Bubble Sort) 앞에서 부터 이웃하는 원소의 값을 비교하여 위치를 교환하는 것을 반복하며 끝까지 반복하면 제일 큰 값이 맨뒤에 위치한다 그리고 정렬할 개수를 1 줄인후 다시 반복하며 정렬할 원소의 개수가 1이면 모든 반복이 완료*/ /*선택정렬(Selection Sort) 제일 큰 값을 찾아 맨 뒤의 요소와 교체하는 방법을 반복하여 전체를 정렬하는 알고리즘이다. 반대로도 제일 작은 값을 찾아 맨 앞의 요소와 교체하는 방법을 반복할 수도 있다.*/ /*삽입 정렬(Insertion Sort) 삽입 정렬 알고리즘은 점진적으로 정렬 범위를 넓혀 나가는 방식으로 정렬하는 알고리즘이다. 이를 위해 새로운 범위에 포함하는 마지막 원소를 앞으로 이동하면서 자신보다 작은 요소를 찾을 떄까지 이동하면서 자리를 교환한다*/ /*쉘 정렬(Shell Sort) 쉘 정렬은 삽입 정렬 알고리즘을 이용하는 정렬 방식이다 같은 간격에 있는 원소들을 삽입 정렬 원리로 정렬하는 것을 반복 간격의 초기값은 배열의 크기 /2 이며 간격이 1일떄까지 1/2로 줄이면서 반복한다*/ /*퀵 정렬Quick Sort) 퀵 정렬은 재귀적인 방법으로 문제를 해결하는 알고리즘 피벗 값을 선택하여 피벗 값보다 작은 값들은 왼쪽으로 보내고 큰 값들은 오른쪽으로 보낸 후에 이들 사이에 피벗을 위치시키는 원리를 이용 이후 피벗보다 작은 값들을 재귀 호출로 정렬하고 피벗보다 큰 값들도 재구호출로 정렬 하는 방식이다 주의 할 점으로는 퀵 정렬은 어떠한 요소를 피벗으로 선택하냐에 따라 성능에 차이가 생긴다 만약 전체 요소의 중간 순위의 요소를 선택 하면 재귀 호출에서 반씩나누어 정렬을 하게되어 좋은 성능을 발휘한다 반대로 가장 작은 값이나 가장 큰값을 피벗으로 선택하면 최악의 성능을 발휘한다*/ /*병합 정렬(Merge Sort) 병합 정렬은 배열을 작은 단위의 배열로 분할한 후에 분할한 배열을 정렬하고 이들을 다시 정렬하면서 전체 배열을 정렬하는 알고리즘이다*/ /*힙 정렬(Heap Sort) 힙 정렬은 힙 트리를 이용하는 알고리즘이다 최대 힙을 사용하면 크기 순으로 정렬하고 최소 합을 사용하면 크기 역순으로 정렬한다 힙 정렬은 먼저 힙트리를 구성하고 루트의 값고 맨 마지막 값을 교환한 후에 정렬 범위를 1 줄인다 반복하여 정렬 범위가 1일 때까지 반복한다 최대 힙 트리에서 루트는 최대 값을 갖는다 마지막 값과 교환 하면 제일 큰값이 맨 뒤로 배치할수 있다 그 뒤에 정렬 범위를 줄여 나가면 최종적으로 정렬 상태가 완성*/<file_sep>#pragma once #include "TStreamPacket.h" #include "TThread.h" #include "TAcceptor.h" #include "TUser.h" class TServer : public TThread { public: TAcceptor m_Acceptor; public: bool Init(); bool Release(); bool Run(); virtual bool AddUser(SOCKET socket,SOCKADDR_IN address); bool SendMsg( SOCKET socket, char* msg, WORD code ); public: TServer(void); virtual ~TServer(void); }; <file_sep>#pragma once #include "DUtils.h" #include "DXWindow.h" class Sample : public DXWindow { private: //-------------------------------------- // GlobalVariables //-------------------------------------- ID3D11Device* m_pd3dDevice; // 디바이스 객체 ID3D11DeviceContext* m_plmmediateContext; // 디바이스 컨텍스트 객체 IDXGISwapChain* m_pSwapChain; // 스왑체인 객체 ID3D11RenderTargetView* m_pRenderTargetView; // 메인 랜더타켓 뷰 객체 D3D_DRIVER_TYPE m_DriverType; // 디바이스 타입 속성값 D3D_FEATURE_LEVEL m_FeatureLevel; // Direct3D 특성레벨 속성값 DXGI_SWAP_CHAIN_DESC m_SwapChainDesc; // 스왑체인 속성값 D3D11_VIEWPORT m_ViewPort; // 뷰 포트 속성값 public: bool Init(); bool Render(); bool Release(); public: Sample(void); ~Sample(void); }; <file_sep>#include "xTimer.h" float g_fSecPerFrame = 0.0f; float g_fGameTimer = 0.0f; bool xTimer::Init() { QueryPerformanceCounter(&m_dwBeforeTick); return true; } bool xTimer::Frame() { LARGE_INTEGER dwCurrentTick; QueryPerformanceCounter(&dwCurrentTick); LONGLONG dwElapseTick = (dwCurrentTick.QuadPart - m_dwBeforeTick.QuadPart); m_fSecPerFrame = (float)dwElapseTick / m_Frequency.QuadPart; g_fSecPerFrame = m_fSecPerFrame; m_fGameTimer += m_fSecPerFrame; g_fSecPerFrame = m_fSecPerFrame; g_fGameTimer = m_fGameTimer; m_fTimer += m_fSecPerFrame; if (m_fTimer >= 1.0f) { m_dwFPS = m_dwFrameCount; m_dwFrameCount = 0; m_fTimer -= 1.0f; _stprintf_s(m_csBuffer, L"FPS:%d TIME:%10.4f SPF:%10.4f", m_dwFPS, m_fGameTimer, m_fSecPerFrame); //OutputDebugString(m_csBuffer); } m_dwFrameCount++; m_dwBeforeTick = dwCurrentTick; return true; } bool xTimer::Render() { return true; } bool xTimer::Release() { return true; } xTimer::xTimer() { m_fGameTimer = 0.0f; m_dwFrameCount = 0; m_dwFPS = 0; m_fSecPerFrame = 0.0f; m_fGameTimer = 0.0f; m_fTimer = 0.0f; QueryPerformanceFrequency(&m_Frequency); } xTimer::~xTimer() { } <file_sep>#include <stdio.h> int main(void) { printf("*********************************\n"); printf("Let's study C/C++ programming!!!\n"); printf("*********************************\n"); return 0; }<file_sep>#pragma once #include "S_Thread.h" class S_WorkThread : public S_Thread { public: HANDLE m_hIOCP; public: bool Run(); void Set(HANDLE hIOCP); public: S_WorkThread(); virtual ~S_WorkThread(); }; <file_sep>#pragma once #include "SThread.h" #include <WS2tcpip.h> class SUdpSocket : public SThread { public: SOCKET m_Socket; SOCKET m_RecvSocket; SOCKADDR_IN m_RecvAddr; SOCKADDR_IN m_SendAddr; vector<string>m_ipList; public: bool Init(); bool Run(); bool Release(); int GetIPList(); public: SUdpSocket(void); virtual ~SUdpSocket(void); }; <file_sep>#pragma once #pragma once #include "Header.h" template< class Child > class TTemplateMap { public: typedef map <int, Child*> TemplateMap; typedef typename TemplateMap::iterator TemplateMapItor; TemplateMapItor TItor; TemplateMap TMap; int m_iCurIndex; public: // 초기화 한다. bool Init(); // 할당된 포인터를 사용하여 저장한다. int Add(Child*); // 객체이름으로 Child 객체를 할당하여 저장한다. int Add(const TCHAR *pFileName); // 인덱스를 통하여 객체를 리턴받는다. Child* GetPtr(DWORD index); // 객체이름으로 객체를 리턴받는다. Child* GetPtr(const TCHAR* szName); // 객체 포인터로 저장된 인덱스를 리턴받는다. int GetID(Child*); // 객체이름으로 저장된 인덱스를 리턴받는다. int GetID(const TCHAR* szName); // 전체 저장된 갯수를 얻는다. int Count(); // 전체 저장된 객체를 삭제한다. bool Release(); public: TTemplateMap(); ~TTemplateMap(); }; template < class Child > int TTemplateMap< Child >::GetID(Child* pChild) { int iIndex = -1; for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (pChild == pPoint) { iIndex = (*itor).first; break; } } return dwIndex; } template < class Child > int TTemplateMap< Child >::GetID(const TCHAR* szName) { int iIndex = -1; for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (!_tcsicmp(pPoint->m_szName.c_str(), szName)) { iIndex = (*itor).first; break; } } return iIndex; } template < class Child > bool TTemplateMap< Child >::Init() { m_iCurIndex = 0; TMap.clear(); return true; } template < class Child > int TTemplateMap< Child >::Count() { return (int)TMap.size(); } template < class Child > bool TTemplateMap< Child >::Release() { for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (pPoint) pPoint->Release(); else return false; delete pPoint; } TMap.clear(); m_iCurIndex = 0; return true; } template < class Child > int TTemplateMap< Child >::Add(Child* pChild) { if (pChild == NULL) { return 0; } for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (pPoint == pChild) { return 0; } } TMap.insert(make_pair(m_iCurIndex++, pChild)); return m_iCurIndex - 1; } template < class Child > int TTemplateMap< Child >::Add(const TCHAR *pFileName) { // 종복 방지 if (pFileName) { TCHAR szFileName[256]; TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; _tsplitpath_s(pFileName, Drive, Dir, FName, Ext); Ext[4] = 0; _stprintf_s(szFileName, _T("%s%s"), FName, Ext); for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (!_tcsicmp(pPoint->m_szName.c_str(), szFileName)) { return (*itor).first; } } } Child *pPoint = NULL; SAFE_NEW(pPoint, Child); pPoint->Add(m_iCurIndex, pFileName); TMap.insert(make_pair(m_iCurIndex++, pPoint)); return m_iCurIndex - 1; } template < class Child > Child *TTemplateMap< Child >::GetPtr(DWORD dwIndex) { TemplateMapItor itor = TMap.find(dwIndex); if (itor == TMap.end()) return NULL; Child *pPoint = (*itor).second; return pPoint; } template < class Child > Child* TTemplateMap< Child >::GetPtr(const TCHAR* szName) { for (TemplateMapItor itor = TMap.begin(); itor != TMap.end(); itor++) { Child *pPoint = (Child *)(*itor).second; if (!_tcsicmp(pPoint->m_szName.c_str(), szName)) { return pPoint; } } return NULL; } template < class Child > TTemplateMap< Child >::TTemplateMap() { m_iCurIndex = 0; TMap.clear(); } template < class Child > TTemplateMap< Child >::~TTemplateMap() { Release(); } template<class T> class TSingleton { public: static T& GetInstance() { static T theSingleInstance; return theSingleInstance; } static T* GetInstancePtr() { static T theSingleInstance; return &theSingleInstance; } };<file_sep>#pragma once #include "TFigure.h" class TEllipse: public TFigure { public: void Draw(); // 오버라이딩 public: TEllipse(); TEllipse(int x,int y,int width,int height); ~TEllipse(); }; <file_sep>#pragma once #include "TTemplate.h" #include "S_Character.h" #include "TParser.h" class SCharacterLoader : public TParser { public: BOOL GetDataFromSkinMeshString(const TCHAR* pString, VOID* pData0, VOID* pData1); public: SCharacterLoader() {}; ~SCharacterLoader() {}; }; class S_CharMgr : public TTemplateMap<S_Character>, public TSingleton<S_CharMgr> { private: friend class TSingleton<S_CharMgr>; public: SCharacterLoader m_Parser; public: int Create(ID3D11Device* pd3dDevice, ID3D11DeviceContext* plmmediateContext, const TCHAR* strFileName, const TCHAR* strShaderName, int iMatrixIndex = -1); bool Load(ID3D11Device* pd3dDevice, ID3D11DeviceContext* plmmediateContext, const TCHAR* strFileName); public: S_CharMgr(); virtual ~S_CharMgr(); }; #define I_CharMgr S_CharMgr::GetInstance() <file_sep>#include "sUdpSocket.h" #include "SDebugString.h" bool sUdpSocket::Init() { m_SendSocket = socket(AF_INET, SOCK_DGRAM, 0); m_Socket = socket(AF_INET, SOCK_DGRAM, 0); int optval = 1; setsockopt(m_SendSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); setsockopt(m_Socket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); m_RecvAddr.sin_family = AF_INET; m_RecvAddr.sin_port = htons(10001); m_RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); int retval = ::bind(m_Socket, (SOCKADDR*)&m_RecvAddr, sizeof(m_RecvAddr)); if (retval == SOCKET_ERROR)return false; m_SendAddr.sin_family = AF_INET; m_SendAddr.sin_port = htons(9001); m_SendAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); CreateThread(); return true; } bool sUdpSocket::Run() { int retval, addrlen; SOCKADDR_IN PeerAddr; char buf[2048] = { 0, }; while (1) { addrlen = sizeof(PeerAddr); retval = recvfrom(m_Socket, buf, 2048, 0, (SOCKADDR*)&PeerAddr, &addrlen); if (retval == SOCKET_ERROR) { I_Debug.Print("[%s]", "Error!!!!"); break; } I_Debug.Print("[RECV]IP=%s,PROT=%d,%s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buf); buf[retval] = 0; retval = sendto(m_SendSocket, buf, strlen(buf), 0, (SOCKADDR*)&m_SendAddr, sizeof(m_SendAddr)); if (retval == SOCKET_ERROR) { I_Debug.T_ERROR(true); I_Debug.Print("[%s]", "Error!!!"); break; } I_Debug.Print("[SEND]IP=%s,PORT=%d,%s", inet_ntoa(PeerAddr.sin_addr), ntohs(PeerAddr.sin_port), buf); } closesocket(m_Socket); m_Socket = 0; return true; } bool sUdpSocket::Release() { if (m_Socket != 0) { closesocket(m_Socket); m_Socket = 0; } return true; } sUdpSocket::sUdpSocket(void) { m_Socket = 0; } sUdpSocket::~sUdpSocket(void) { } <file_sep>#include "S_KHJExporter.h"<file_sep>//버블 정렬(Bubble Sort) /*앞에서 부터 이웃하는 원소의 값을 비교하여 위치를 교환하는 것을 반복하며 끝까지 반복하면 제일 큰 값이 맨뒤에 위치한다.그리고 정렬할 개수를 1 줄인후 다시 반복하며 정렬할 원소의 개수가 1이면 모든 반복이 완료*/ #include <stdio.h> #include<conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 void BubbleSort(int *base, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; BubbleSort(arr, 10); _getch(); return 0; } void ViewArr(int *arr, int n); void BubbleSort(int *base, int n) { int i, j; ViewArr(base, n);//현재 상태 출력 for (i = n; i>1; i--)//정렬할 범위를 축소해 나갑니다. { for (j = 1; j<i; j++) { if (base[j - 1]>base[j])//앞쪽 원소가 더 크면 { SWAP(base[j - 1], base[j]);//교환 ViewArr(base, n);//상태 출력 } } } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#pragma once #include <Windows.h> #pragma pack(push,1) typedef struct { WORD len; WORD type; }PACKET_HEADER; typedef struct { PACKET_HEADER ph; char msg[256]; }UPACKET,*P_UPACKET; typedef struct { byte szName[13]; int iIndex; int iData[20]; }CHARACTER_INFO; #pragma pack(pop) #define PACKET_HEADER_SIZE 4 // TYPE #define PACKET_CHAT_MSG 1000 #define PACKET_CREATE_CHARACTER 2000 // SEND //char buffer[] = "KGCA"; //UPACKET packet; //ZeroMemory(&packet, sizeof(packet)); //packet.ph.len = strlen(buffer); //packet.ph.type = PACKET_CHAT_MSG; //memcpy(packet.msg,buffer,strlen(buffer)); //send(sock, (char*)&packet, packet.ph.len,0); //UPACKET packet; //ZeroMemory(&packet, sizeof(packet)); //CHARACTER_INFO cInfo; // cInfo.szName = ; // cInfo.iIndex = ; // cInfo.iData = ; //packet.ph.len = strlen(cInfo); //packet.ph.type = PACKET_CHAT_MSG; //memcpy(packet.msg,(char*)cInfo,strlen(cInfo)); //send(sock, (char*)&packet, packet.ph.len,0); // RECV // char buffer[256]={0,}; //int recvbyte = 0; //while (1) //{ // recvbyte += recv(sock, buffer[recvbyte], // sizeof(char) * PACKET_HEADER_SIZE-recvbyte, 0); // if (recvbyte == PACKET_HEADER_SIZE) // { // UPACKET packet; // ZeroMemory(&packet, sizeof(packet)); // memcpy(packet.ph, buffer,sizeof(char)*PACKET_HEADER_SIZE); // int rByte == 0; // do // { // rByte += recv(sock, // packet.msg[rByte], // sizeof(char)*packet.ph.len-rByte, 0); // // } while (packet.ph.len > rByte) // recvbyte = 0; // switch (packet.ph.type) // { // case PACKET_CHAT_MSG: // { // printf("ÆÐŶ ¿Ï¼º%s",packet.msg); // }break; // case PACKET_CREATE_CHARACTER: // { // CHARACTER_INFO cInfo; // memcpy(cInfo, packet.msg, sizeof(CHARACTER_INFO)); // }break; // // // } // // } //}<file_sep>#include <stdio.h> int main(void) { int a = 10; int b = 5; int c; c = b > a ? b : a; printf("%d\n",c); printf("%d\n", b > a ? b : a); }<file_sep>#include <stdio.h> void main() { int a; { int b; a = 5; b = 10; printf("%d %d", a,b); } a = 10; int b=0; printf("%d %d", a,b); }<file_sep>#include "TChatUser.h" #include "TChatSvr.h" //typedef struct { // WORD user_idx; // 케릭터의 고유한 인덱스 // WORD posX; // 좌표 // WORD posY; // WORD direction; // 방향 ( 0~7 ) 8방향 //}TPACKET_USER_POSITION; void TChatUser::Movement(UPACKET* pPacket) { TPACKET_USER_POSITION user; memcpy( &user, pPacket->msg, sizeof(char)* pPacket->ph.len-4 ); m_iIndex = user.user_idx; m_PositionX = user.posX; m_PositionY = user.posY; m_iDirection = user.direction; }; void TChatUser::AddPacket(S_PACKET& addPacket ) { I_Server.m_PacketPool.AddPacket(addPacket); } void TChatUser::DeleteUser( SOCKET socket ) { I_Server.DeleteUser( socket ); }; void TChatUser::DeleteUser() { I_Server.DeleteUser( this ); } void TChatUser::Dispatch( DWORD dwByteSize, LPOVERLAPPED ov) { OVERLAPPEDEX* pOV = (OVERLAPPEDEX*)ov; if( dwByteSize == 0 ) return; if( pOV->iFlags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put( m_szRecvBuffer.buf, // this->m_strBuffer, dwByteSize, this); } if( pOV->iFlags == OVERLAPPEDEX::MODE_SEND) { } WaitForPacketReceive(); }; TChatUser::TChatUser(void) { } TChatUser::~TChatUser(void) { } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <WS2tcpip.h> // InetNtop() . inet_ntop() #include <iostream> #include <map> #include <time.h> #pragma comment (lib,"ws2_32") using namespace std; // //FD_SET rSet; //FD_SET wSet; // //int main(void) //{ // // // while (1) // { // FD_ZERO(&rSet); // FD_ZERO(&wSet); // // // // // // 장점 : // // 블로킹 소켓 - > 블록킹함수 문제 해결. // // 취소 : 넌 블록킹 소켓 -> WSAEWOULDBLOCK 해결. // timeval time; // time.tv_sec = 1; // time.tv_usec = 0; // int iRet = Select(0, &rSet, &wSet, NULL, &time); // if (iRet == SOCKET_ERROR) break; // if (iRet == 0) {} // timeout // else // { } // } // //}<file_sep>#include "xMap.h" HRESULT xMap::CreateVertexData() { m_iNumVertex = m_iNumVertices; m_VertexList.resize(m_iNumVertices); float fHalfCols = (m_iNumCols - 1) / 2.0f; float fHalfRows = (m_iNumRows - 1) / 2.0f; float fOffsetU = 1.0f / (m_iNumCols - 1); float fOffsetV = 1.0f / (m_iNumRows - 1); for (int iRow = 0; iRow < m_iNumRows; iRow++) { for (int iCol = 0; iCol < m_iNumCols; iCol++) { int iIndex = iRow * m_iNumCols + iCol; m_VertexList[iIndex].p.x = (iCol - fHalfCols)*m_fCellDistance; m_VertexList[iIndex].p.y = GetHeightOfVertex(iIndex); m_VertexList[iIndex].p.z = -((iRow - fHalfRows)*m_fCellDistance); m_VertexList[iIndex].n = GetNormalOfVertex(iIndex); m_VertexList[iIndex].c = GetColorOfVertex(iIndex); m_VertexList[iIndex].t = GetTextureOfVertex(fOffsetU*iCol, fOffsetV*iRow); } } return S_OK; } HRESULT xMap::CreateIndexData() { m_iNumIndex = m_iNumFace * 3; m_IndexList.resize(m_iNumIndex); int iIndex = 0; for (int iRow = 0; iRow < m_iNumCellRows; iRow++) { for (int iCol = 0; iCol < m_iNumCellCols; iCol++) { // 0 1 2 // 3 4 5 int iNextRow = iRow + 1; m_IndexList[iIndex + 0] = iRow * m_iNumCols + iCol; m_IndexList[iIndex + 1] = m_IndexList[iIndex + 0] + 1; m_IndexList[iIndex + 2] = iNextRow * m_iNumCols + iCol; m_IndexList[iIndex + 3] = m_IndexList[iIndex + 2]; m_IndexList[iIndex + 4] = m_IndexList[iIndex + 1]; m_IndexList[iIndex + 5] = m_IndexList[iIndex + 2] + 1; iIndex += 6; } } return S_OK; } D3DXVECTOR2 xMap::GetTextureOfVertex(float fU, float fV) { return D3DXVECTOR2(fU, fV); } D3DXVECTOR3 xMap::GetNormalOfVertex(int iIndex) { return D3DXVECTOR3(0.0f, 1.0f, 0.0f); } D3DXVECTOR4 xMap::GetColorOfVertex(int iIndex) { return D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f); } float xMap::GetHeightOfVertex(int iIndex) { return 0.0f; } bool xMap::CreateMap(xMapDesc desc) { m_iNumRows = desc.iNumRows; m_iNumCols = desc.iNumCols; m_iNumCellRows = m_iNumRows - 1; m_iNumCellCols = m_iNumCols - 1; m_iNumVertices = m_iNumRows * m_iNumCols; m_iNumFace = m_iNumCellRows * m_iNumCellCols * 2; m_fCellDistance = desc.fDistance; return true; } bool xMap::Load(ID3D11Device* pDevice, xMapDesc desc) { m_pd3dDevice = pDevice; if (!CreateMap(desc)) { return false; } xShape::Create(m_pd3dDevice, desc.szShaderFile, desc.szTextureFile); return true; } bool xMap::Init() { return true; } bool xMap::Frame() { return xShape::Frame(); } bool xMap::Render(ID3D11DeviceContext* pContext) { xShape::Render(pContext); return true; } bool xMap::Release() { xShape::Release(); return true; } xMap::xMap() { } xMap::~xMap() { } <file_sep>#include "ServerMain.h" #include "SChatSvr.h" #include "SServerIOCP.h" #include "SDebugString.h" bool ServerMain::Init() { I_ServerIOCP.Init(); I_Server.Init(); m_Udp.Init(); return true; } bool ServerMain::Release() { m_Udp.Release(); I_Server.Release(); return true; } LRESULT ServerMain::MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: { int iWidth = m_rtClient.right - m_rtClient.left; int iHeight = m_rtClient.bottom - m_rtClient.top; I_Debug.m_hList = CreateWindow(L"listbox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 0, 0, iWidth - 100, iHeight, hWnd,(HMENU)0, m_hInstance, NULL); }break; } return 0; } ServerMain::ServerMain(void) { } ServerMain::~ServerMain(void) { } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow) { ServerMain server; if (!server.SetWindow(hInstance, _T("ChatServer"), 800, 600)) { return 0; } SetCursor(NULL); if (server.Run() == false) { return 0; } return 1; }<file_sep>#include <stdio.h> int x = 1; int y = 2; void demo(void); main() { printf("Before:x=%d,y=%d\n", x, y); demo(); printf("After:x=%d,y=%d\n",x,y); } void demo(void) { int x = 88; int y = 99; printf("In demo():x=%d,y=%d\n", x, y); }<file_sep>#pragma once #pragma comment (lib,"ODBCLIB.lib") #define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <sql.h> #include <sqlext.h> #include <tchar.h> #include <stdio.h> #include <iostream> #include <string> using namespace std; extern HINSTANCE g_hInst;<file_sep>#include "S_IOCP.h" bool S_IOCP::Init() { m_hIOCP = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 3); for (int Thread = 0; Thread < 3; Thread++) { m_WorkThread[Thread].CreateThread(); } return true; } bool S_IOCP::Run() { return true; } bool S_IOCP::Release() { return true; } void S_IOCP::AddhandleToIOCP(HANDLE hClientSocket, ULONG_PTR dwReturnkey) { ::CreateIoCompletionPort(hClientSocket, m_hIOCP, dwReturnkey, 0); return; } S_IOCP::S_IOCP() { } S_IOCP::~S_IOCP() { } <file_sep>#pragma once #ifndef SPROTOCAL_HEADER #define SPROTOCAL_HEADER #include "S_Std.h" #define PACKET_HEADER_SIZE 4 #pragma pack(push,1) typedef struct { WORD len; WORD type; }PACKET_HEADER; typedef struct { PACKET_HEADER ph; char msg[2048]; }UPACKET, *P_UPACKET; typedef struct { int User_iIndex; BYTE POS_X; BYTE POS_Y; BYTE bDirection; }SPACKET_USER_POSITON; #define PACKET_USER_POSITON 3000 class S_SvrUser; typedef struct { UPACKET packet; S_SvrUser* pUser; }PACKET, *PTR_PACKET; typedef struct { WORD* len; WORD* type; }PTR_HEADER_PACKET; typedef struct { int UserIndex; char User_ID[21]; char User_PS[15]; }SPACKET_USER_LOGIN; #define PACKET_USER_LOGIN 2000 #define PACEKT_CHAT_NAME_REQ 1000 // 대화명 입력 #define PACKET_CHAT_NAME_ACK 1001 // 대화명 입력 전송 #define PACKET_CHAT_MSG 1002 // 대화명 입력 전송 typedef struct { WORD user_idx; WORD PosX; WORD PosY; WORD direction; }SPACKET_USER_POSITION; #define PACKET_USER_POSITION 3000 #pragma pack(pop) #endif<file_sep>#include "Maze.h" class BombedWall :public Wall { public: BombedWall() {}; BombedWall(const BombedWall& other) :Wall(other) { _bomb = other._bomb; } private: bool _bomb; }; class MazeFactory { public: virtual Maze* MakeMaze() const { return new Maze; } virtual Wall* MakeWall() const { return new Wall; } virtual Room* MakeRoom(int n)const { return new Room(n); } virtual Door* MakeDoor(Room* r1, Room* r2)const { return new Door(r1, r2); } MazeFactory() {} }; class MazePrototypeFactory : public MazeFactory { public: MazePrototypeFactory(Maze* maze, Wall* wall, Room* room, Door* door) { _prototypeMaze = maze; _prototypeRoom = room; _prototypeWall = wall; _prototypeDoor = door; } virtual Wall* MakeWall() { return _prototypeWall->Clone(); }; virtual Door* MakeDoor(Room* r1, Room* r2) { Door* door = _prototypeDoor->Clone(); door->Initialize(r1, r2); return door; }; private: Maze * _prototypeMaze; Room* _prototypeRoom; Wall* _prototypeWall; Door* _prototypeDoor; }; class MazeGame { public: static MazeGame* InStance(); //AbstractFactory Maze* CreateMaze(MazePrototypeFactory* factory) { Maze* aMaze = factory->MakeMaze(); Room* r1 = factory->MakeRoom(1); Room* r2 = factory->MakeRoom(2); Door* theDoor = factory->MakeDoor(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); r1->SetSide(North, factory->MakeWall()); r1->SetSide(East, theDoor); r1->SetSide(South, factory->MakeWall()); r1->SetSide(West, factory->MakeWall()); r2->SetSide(North, factory->MakeWall()); r2->SetSide(East, factory->MakeWall()); r2->SetSide(South, factory->MakeWall()); r2->SetSide(West, theDoor); return aMaze; } protected: MazeGame() {} private: static MazeGame* _instance; }; MazeGame* MazeGame::_instance = 0; MazeGame* MazeGame::InStance() { if (_instance == 0) { _instance = new MazeGame; } return _instance; } void main() { MazeGame* game = MazeGame::InStance(); MazePrototypeFactory simpleMazeFactory(new Maze, new Wall, new Room, new Door); Maze* maze = game->CreateMaze(&simpleMazeFactory); }<file_sep>#include "DDirectWrite.h" #include <math.h> #pragma comment (lib,"winmm.lib") template <class D> inline void SafeRelease(D **ppD) { if (*ppD) { (*ppD)->Release(); *ppD = NULL; } } bool DDirectWrite::Set(HWND hWnd, int iWidth, int iHeight, IDXGISurface1* pSurface) { HRESULT hr; if (!Init()) { return false; } m_hWnd = hWnd; V(CreateDeviceIndependentResources()); V(CreateDeviceResources(pSurface)); SetText(D2D1::Point2F(iWidth, iHeight), L"DBasisSample!", D2D1::ColorF(1, 1, 1, 1)); return true; } bool DDirectWrite::Release() { m_wszText.clear(); m_wszFontFamily.clear(); DiscardDeviceIndependentResources(); DiscardDeviceResources(); return true; } bool DDirectWrite::Init() { const wchar_t defaultText[] = L"Gabriola"; m_wszFontFamily = defaultText; return true; } DDirectWrite::DDirectWrite() { } DDirectWrite::~DDirectWrite() { } <file_sep>#pragma once #include "S_KHJ_Object.h" class S_KHJ_AnimObj : public S_KHJ_Object { public: int m_iDeltaTick; // 샘플링 void GetAnimKeys(INode* pNode, SMesh* pMesh); void DumpScaleSample(INode* node, SMesh* Mesh); void DumpRotSample(INode* node, SMesh* Mesh); void DumpPosSample(INode* node, SMesh* Mesh); BOOL CheckForAnimation(INode* node, BOOL& bPos, BOOL& bRot, BOOL& bScale); bool GetDecompAffine(TimeValue t, INode* pNode, AffineParts* ap, Point3* rotAxis = NULL, float* rotAngle = NULL); void DumpFloatKeys(Control* cont, SMesh* pMesh); public: // 키프레임 //void DumpPosKeys(Control* cont, TMesh* pMesh); //void DumpRotKeys(Control* cont, TMesh* pMesh); //void DumpScaleKeys(Control* cont, TMesh* pMesh) ; //BOOL IsKnownController(Control* cont); public: S_KHJ_AnimObj(void); virtual ~S_KHJ_AnimObj(void); }; //struct TTCBKey //{ // DWORD flags; // float tens; // Tension // float cont; // Continuity // float bias; // Bias // float easeIn; // float easeOut; //}; //struct TAnimTrack : public TTCBKey //{ // DWORD m_dwType; // int m_iTick; // Quat qValue; // Point3 m_vValue; // // Point3 m_vIntan; //Inconming Tangent Vector // Point3 m_vOuttan; //Outgoing Tanglent Vector // Point3 m_inLength; //The in length of the horizontal handle // Point3 m_outLength; //The out length of the horizontal handle // // TAnimTrack* m_pNext; // TAnimTrack* m_pPrev; // TAnimTrack() : m_pNext(0), m_pPrev(0) {} //}; <file_sep>#include <iostream> #define SAFE_NEW(p,N) {if(!p) p=new N;if(p) memset(p,0,sizeof(N)*C);} //#define SAFE_NEW_ARRAY(p,N,C) {if(!p) p=new N[C]; if(p) memset(p,0,sizeof(N)*C);} #define SAFE_NEW_VALUE(p,N,v) {if(!p) p=new N(v);} #define SAFE_DEL(p) {if(p)delete p; (p) = NULL; } #define SAFE_ZERO(p) {p=0;}; struct TNode { int m_iValue; int m_iDepth; TNode* m_pLeft; TNode* m_pRight; TNode(int idata) : m_iValue(idata), m_pLeft(0), m_pRight(0), m_iDepth(0) {}; }; TNode* g_pRoot = NULL; int g_iIndex = 0; bool ADD(TNode* pParentNode) { if (pParentNode->m_iDepth > 2) { return false; } TNode* pLeft = 0; SAFE_NEW_VALUE(pLeft, TNode, ++g_iIndex); pLeft->m_iDepth = pParentNode->m_iDepth + 1; pParentNode->m_pLeft = pLeft; TNode* pRight = new TNode(++g_iIndex); pRight->m_iDepth = pParentNode->m_iDepth + 1; pParentNode->m_pRight = pRight; return true; } void Build(TNode* pParentNode) { std::cout << pParentNode->m_iValue << std::endl; if (ADD(pParentNode)) { Build(pParentNode->m_pLeft); Build(pParentNode->m_pRight); } } void PRINT(TNode* pParentNode) { if (pParentNode != NULL) { std::cout << pParentNode->m_iValue << std::endl; //전위 preorder Build(pParentNode->m_pLeft); //std::cout << pParentNode->m_iValue << std::endl; //중위 inorder Build(pParentNode->m_pRight); //std::cout << pParentNode->m_iValue << std::endl; //후위 postorder } } void DELALL(TNode* pParentNode) { if (pParentNode == NULL)return; DELALL(pParentNode->m_pLeft); DELALL(pParentNode->m_pRight); SAFE_DEL(pParentNode); } void main() { g_pRoot = new TNode(0); TNode* pNode = g_pRoot; SAFE_NEW_VALUE(g_pRoot, TNode, 0); Build(g_pRoot); PRINT(g_pRoot); DELALL(g_pRoot); SAFE_ZERO(g_pRoot) getchar(); }<file_sep>#include <Windows.h> #include <iostream> #include <tchar.h> #include <string> using namespace std; // 비동기 작업 // 로딩 화면에서 쓰면 될듯?! OVERLAPPED OV; // 구조체 LARGE_INTEGER g_size; char* buf = NULL; char * GetW2M(WCHAR* data) // 유니코드를 멀티바이트로 바꾸는 함수 { char cData[3333] = { 0, }; int iLength = WideCharToMultiByte( CP_ACP, 0, data, -1, 0, 0, NULL, NULL); int iRet = WideCharToMultiByte( CP_ACP, 0, data, -1, cData, iLength, NULL, NULL); return cData; } WCHAR * GetM2W(char* data) // 멀티바이트를 유니코드로 바꾸는 함수 { WCHAR cData[3333] = { 0, }; int iLength = MultiByteToWideChar( CP_ACP, 0, data, -1, 0, 0); int iRet = MultiByteToWideChar( CP_ACP, 0, data, -1, cData, iLength); return cData; } string w2m(wstring data) // 유니코드를 string으로 변경 { string ret = string(data.begin(), data.end()); return ret; } wstring m2w(string data) // 유니코드를 string으로 변경 { wstring ret = wstring(data.begin(), data.end()); return ret; } void FileRead(HANDLE hReadfile, DWORD offset) { DWORD dwLength = 4096 * 1024; // filesize.QuadPart; g_size.QuadPart += offset; OV.Offset = g_size.LowPart; OV.OffsetHigh = g_size.HighPart; char* pTemp = &buf[g_size.QuadPart]; DWORD dwRead; BOOL iRet = ReadFile(hReadfile, buf, dwLength, &dwRead, &OV); if (iRet == FALSE) // 이것이 아니라면 오류다 { if (GetLastError() == ERROR_IO_PENDING) // 읽고있으니 에러처리 하지마라 { printf("\n%s", "Read ...."); // 이게 출력되느냐 안되느냐에 따라 비동기인지를 확인 할수 있다. } } } void main() { //ZeroMemory(&OV, sizeof(OVERLAPPED)); LARGE_INTEGER filesize; // LARGE_INTEGER : 24억 바이트 DWORD dwLength = filesize.QuadPart; DWORD trans; HANDLE hReadfile = CreateFileA( "Bigfile.iso", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); // 파일을 연다 if (hReadfile != INVALID_HANDLE_VALUE) { GetFileSizeEx(hReadfile, &filesize); // 파일사이즈의 크기 확인할수 있는 함수 buf = new char[filesize.QuadPart]; if (buf == NULL) { return; } FileRead(hReadfile, 0); OVERLAPPED OV; // 구조체 ZeroMemory(&OV, sizeof(OVERLAPPED)); } CloseHandle(hReadfile); // 파일을 닫는다. OVERLAPPED wOV; ZeroMemory(&wOV, sizeof(OVERLAPPED)); HANDLE hWritefile = CreateFileA( "copy.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); // 쓰기전용 txt 무조건 생성 if (hWritefile != NULL) { DWORD trans = 0; DWORD dwWritten; bool iRet = WriteFile(hWritefile, buf, filesize.QuadPart, &dwWritten, &wOV); if (iRet == FALSE) { if (GetLastError() == ERROR_IO_PENDING) // 읽고있으니 에러처리 하지마라 { printf("\n%s", "\nWrite ...."); // 이게 출력되느냐 안되느냐에 따라 비동기인지를 확인 할수 있다. } } while (1) { BOOL ret = GetOverlappedResult( // 결과만을 확인하는 함수이다. hReadfile, &wOV, &trans, TRUE); if (ret == TRUE) { if (filesize.QuadPart <= g_size.QuadPart) { break; } //FileRead(hReadfile, trans); printf("\n%s", "\nfinish ...."); break; } else { printf("\n%s", "\nREAD......"); } } printf("파일 출력 완료 !"); delete[] buf; CloseHandle(hWritefile); // 파일을 닫는다 } }<file_sep>#pragma once #include "xModelView.h" #include "xCore.h" #include <memory> const UINT g_iTextureRTSize = 1024; class Sample : public xCore { public: shared_ptr<xModelView> m_pMainCamera; shared_ptr<xPlaneShape> m_pPlane; shared_ptr<xBoxShape> m_pBox; shared_ptr<xPlaneShape> m_pMinimap; shared_ptr<xPlaneShape> m_pScreen; D3D11_VIEWPORT m_MinimapViewPort; public: };<file_sep>//composite 패턴은 사용자가 단일 객체와 복합 객체 모두 동일하게 다루도록 한 것이다 #include <iostream> #include <list> #include <iterator> #include <map> using namespace std; class Graphic { public: virtual void Draw() = 0; virtual void Add(Graphic* pObj){} virtual void Remove(Graphic* pObj) {} virtual Graphic* GetChild(int nth) { return 0; } }; class Line :public Graphic { public: void Draw() { //-- 라인 그리기 } }; class Triangle : public Graphic { public: void Draw() { //--삼각형 그리기 } }; class Rectangle :public Graphic { public: void Draw() { //--사각형 그리기 } }; class ComposedGraphic : public Graphic { public: void Draw() { list<Graphic*>::iterator iter1; for (iter1 = components_.begin(); iter1 != components_.end(); iter1++) (*iter1)->Draw(); } void Add(Graphic *pObj) { components_.push_front(pObj); } void remove(Graphic *pObj) { list<Graphic*> ::iterator iter1; for (iter1 = components_.begin(); iter1 != components_.end(); iter1++) { if (*iter1 == pObj) components_.erase(iter1); } } Graphic* GetChild(int nth) { int i; list<Graphic*>::iterator iter1; for (i = 0, iter1 = components_.begin(); iter1 != components_.end(); iter1++, i++) { if (i == nth)return *iter1; } return 0; } private: list<Graphic*>components_; }; class Palette { public: Palette() { Graphic* pGraphic = new Triangle; items_[1] = pGraphic; pGraphic = new Rectangle; items_[2] = pGraphic; //--필요한 만큼 기본 도형 등록 } void RegisterNewGraphic(Graphic* pGraphic) { items_[items_.size() + 1] = pGraphic; } private: map<int, Graphic*>items_; }; void main() { Triangle aTriangle; Rectangle aRectangle; ComposedGraphic aComposedGraphic2; aComposedGraphic2.Add(&aTriangle); aComposedGraphic2.Add(&aRectangle); Line aLine; Rectangle aRectangle2; ComposedGraphic aComposedGraphic; aComposedGraphic.Add(&aComposedGraphic2); aComposedGraphic.Add(&aLine); aComposedGraphic.Add(&aRectangle2); }<file_sep>#pragma once #ifndef __BINARY_TREE3_H__ #define __BINARY_TREE3_H__ typedef int BTData; typedef struct _bTreeNode { BTData data; struct _bTreeNode* left; struct _bTreeNode* right; }BTreeNode; BTreeNode* MakeBTreeNode(void); BTData GetData(BTreeNode* bt); void SetData(BTreeNode* bt, BTData data); BTreeNode* GetLeftSubTree(BTreeNode* bt); BTreeNode* GetRightSubTree(BTreeNode* bt); void MakeLeftSubTree(BTreeNode* main, BTreeNode* sub); void MakeRightSubTree(BTreeNode* main, BTreeNode* sub); typedef void VisitFuncPtr(BTData data); void PreorderTraverse(BTreeNode* bt, VisitFuncPtr action); void InorderTraverse(BTreeNode* bt, VisitFuncPtr action); void PostorderTraverse(BTreeNode* bt, VisitFuncPtr action); //왼쪽 자식 노드 제거, 제거된 노드의 주소 값이 반환된다. BTreeNode* RemoveLeftSubTree(BTreeNode* bt); //오른쪽 자식 노드 제거, 제거된 노드의 주소 값이 반환된다 BTreeNode* RemoveRightSubTree(BTreeNode* bt); //메모리 소멸을 수반하지 않고 main의 왼쪽 자식 노드를 변경한다. void ChangeLeftSubTree(BTreeNode* main, BTreeNode* sub); //메모리 소멸을 수반하지 않고 main의 오른쪽 자식 노드를 변경한다. void ChangeRightSubTree(BTreeNode* main, BTreeNode* sub); typedef BTData BSTData; //이진 탐색 트리의 생성 및 초기화 void BSTMakeAndInit(BTreeNode** pRoot); //노드에 저장된 데이터 반환 BSTData BStGetNodeData(BTreeNode* bst); //이진 탐색 트리를 대상으로 데이터 저장(노드의 생성과정 포함) void BSTInsert(BTreeNode**pRoot, BSTData data); //이진 탐색 트리를 대상으로 데이터 탐색 BTreeNode* BSTSearch(BTreeNode* bst, BSTData target); //트리에서 노드를 제거하고 제거된 노드의 주소값을 반환한다. BTreeNode* BSTRemove(BTreeNode**pRoot, BSTData Target); //이진 탐색트리에 저장된 모든 노드의 데이터를 출력한다. void BSTSHowAll(BTreeNode* bst); #endif <file_sep>#include "xlist.h" #include <iostream> #include "xiter.h" using namespace std; int AbstractList::Count() { return totaICnt_; } Iterator * LinkedList::CreateIterator() { return new ListIterator(this); } void LinkedList::AddNext(Item *pNewItem, Item *pItem) { if (pFirst_ == 0) pFirst_=new LinkedItem(pNewItem); else if (pItem == 0 || pItem == pFirst_->pData_) { LinkedItem* pTmp = pFirst_->pNext_; pFirst_->pNext_ = new LinkedItem(pNewItem, pTmp); } else { LinkedItem* pPrev = 0; LinkedItem* pTmp = pFirst_; while (pTmp != 0 && pTmp->pData_ != pItem) { pPrev = pTmp; pTmp = pTmp->pNext_; } if (pTmp != 0) { LinkedItem* pTmp2 = pTmp->pNext_; pTmp->pNext_ = new LinkedItem(pNewItem, pTmp2); } else pPrev->pNext_ = new LinkedItem(pNewItem, 0); } totaICnt_++; } void LinkedList::AddChild(Item* pNewItem, Item* pItem) { AddNext(pNewItem, pItem); } void LinkedList::Remove(Item* pItem) { if (pItem == 0)return; LinkedItem* pPrev = 0; LinkedItem* pTmp = pFirst_; while (pTmp != 0 && pTmp->pData_ != pItem) { pPrev = pTmp; pTmp = pTmp->pNext_; } if (pTmp != 0) { if (pTmp == pFirst_) { delete pTmp; pFirst_ = 0; } else { pPrev->pNext_ = pTmp->pNext_; delete pTmp; } totaICnt_--; } } Item* LinkedList::GetItem(int pos) { int cnt = 0; LinkedItem* pTmp = pFirst_; while (pTmp != 0 && cnt != pos) { pTmp = pTmp->pNext_; cnt++; } if (pTmp != 0)return pTmp->pData_; else return 0; } Iterator * TreeList::CreateIterator() { return new TreeIterator(this); }<file_sep>#include "TExpMesh.h" void NormalizeBoneWeights(BYTE* pWeights) { DWORD dwSum = static_cast<DWORD>(pWeights[0]) + static_cast<DWORD>(pWeights[1]) + static_cast<DWORD>(pWeights[2]) + static_cast<DWORD>(pWeights[3]); if (dwSum == 255) return; INT iDifference = 255 - static_cast<INT>(dwSum); for (DWORD i = 0; i < 4; ++i) { if (pWeights[i] == 0) continue; INT iValue = static_cast<INT>(pWeights[i]); if (iValue + iDifference > 255) { iDifference -= (255 - iValue); iValue = 255; } else { iValue += iDifference; iDifference = 0; } pWeights[i] = static_cast<BYTE>(iValue); } dwSum = static_cast<DWORD>(pWeights[0]) + static_cast<DWORD>(pWeights[1]) + static_cast<DWORD>(pWeights[2]) + static_cast<DWORD>(pWeights[3]); assert(dwSum == 255); } inline INT GetElementSizeFromDeclType(DWORD Type) { switch (Type) { case T_TYPE_FLOAT1: case T_TYPE_D3DCOLOR: case T_TYPE_UBYTE4: case T_TYPE_UBYTE4N: case T_TYPE_FLOAT16_2: /*case T_TYPE_DXGI_R10G10B10A2_UNORM: case T_TYPE_DXGI_R11G11B10_FLOAT: case T_TYPE_DXGI_R8G8B8A8_SNORM: case T_TYPE_XBOX_R10G10B10_SNORM_A2_UNORM:*/ return 4; case T_TYPE_FLOAT2: case T_TYPE_SHORT4N: case T_TYPE_FLOAT16_4: return 8; case T_TYPE_FLOAT3: return 12; case T_TYPE_FLOAT4: return 16; case T_TYPE_UNUSED: return 0; default: assert(false); return 0; } } void ExportVB::Allocate() { size_t uSize = GetVertexDataSize(); m_pVertexData.reset(new uint8_t[uSize]); ZeroMemory(m_pVertexData.get(), uSize); } uint8_t* ExportVB::GetVertex(size_t uIndex) { if (!m_pVertexData) return nullptr; if (uIndex >= m_uVertexCount) return nullptr; return m_pVertexData.get() + (uIndex * m_uVertexSizeBytes); } const uint8_t* ExportVB::GetVertex(size_t uIndex) const { if (!m_pVertexData) return nullptr; if (uIndex >= m_uVertexCount) return nullptr; return m_pVertexData.get() + (uIndex * m_uVertexSizeBytes); } void ExportVB::ByteSwap(const T_VERTEX_ELEMENT* pVertexElements, const size_t dwVertexElementCount) { for (size_t dwVertexIndex = 0; dwVertexIndex < m_uVertexCount; dwVertexIndex++) { auto pVB = GetVertex(dwVertexIndex); for (size_t i = 0; i < dwVertexElementCount; i++) { auto pElement = reinterpret_cast<DWORD*>(pVB + pVertexElements[i].Offset); switch (pVertexElements[i].Type) { case T_TYPE_FLOAT4: *pElement = _byteswap_ulong(*pElement); pElement++; case T_TYPE_FLOAT3: *pElement = _byteswap_ulong(*pElement); pElement++; case T_TYPE_FLOAT2: *pElement = _byteswap_ulong(*pElement); pElement++; case T_TYPE_FLOAT1: case T_TYPE_D3DCOLOR: case T_TYPE_UBYTE4: case T_TYPE_UBYTE4N: /*case T_TYPE_DXGI_R10G10B10A2_UNORM: case T_TYPE_DXGI_R11G11B10_FLOAT: case T_TYPE_DXGI_R8G8B8A8_SNORM: case T_TYPE_XBOX_R10G10B10_SNORM_A2_UNORM:*/ *pElement = _byteswap_ulong(*pElement); break; case T_TYPE_SHORT4N: case T_TYPE_FLOAT16_4: { auto pWord = reinterpret_cast<WORD*>(pElement); *pWord = _byteswap_ushort(*pWord); pWord++; *pWord = _byteswap_ushort(*pWord); pElement++; } case T_TYPE_FLOAT16_2: { auto pWord = reinterpret_cast<WORD*>(pElement); *pWord = _byteswap_ushort(*pWord); pWord++; *pWord = _byteswap_ushort(*pWord); pElement++; break; } } } } } void ExportIB::ByteSwap() { if (m_dwIndexSize == 2) { auto pIndexData16 = reinterpret_cast<WORD*>(m_pIndexData.get()); for (size_t i = 0; i < m_uIndexCount; i++) { WORD wIndex = _byteswap_ushort(pIndexData16[i]); pIndexData16[i] = wIndex; } } else { auto pIndexData32 = reinterpret_cast<DWORD*>(m_pIndexData.get()); for (size_t i = 0; i < m_uIndexCount; i++) { DWORD dwIndex = _byteswap_ulong(pIndexData32[i]); pIndexData32[i] = dwIndex; } } } void ExportIB::Allocate() { if (m_dwIndexSize == 2) { m_pIndexData.reset(reinterpret_cast<uint8_t*>(new WORD[m_uIndexCount])); ZeroMemory(m_pIndexData.get(), m_uIndexCount * sizeof(WORD)); } else { m_pIndexData.reset(reinterpret_cast<uint8_t*>(new DWORD[m_uIndexCount])); ZeroMemory(m_pIndexData.get(), m_uIndexCount * sizeof(DWORD)); } } bool ExportMeshVertex::Equals(const ExportMeshVertex* pOtherVertex) const { if (!pOtherVertex) return false; if (pOtherVertex == this) return true; D3DXVECTOR3 v0 = Position; D3DXVECTOR3 v1 = pOtherVertex->Position; if (v0 != v1) return false; v0 = Normal; v1 = pOtherVertex->Normal; if (v0 != v1) return false; D3DXVECTOR4 v2, v3; for (size_t i = 0; i < 8; i++) { v2 = TexCoords[i]; v3 = pOtherVertex->TexCoords[i]; if (v2 != v3) return false; } v2 = Color; v3 = pOtherVertex->Color; if (v2 != v1) return false; return true; } void TExpMesh::BuildVertexBuffer(ExportMeshVertexArray& VertexArray, DWORD dwFlags) { UINT uVertexSize = 0; INT iCurrentVertexOffset = 0; INT iPositionOffset = -1; INT iNormalOffset = -1; INT iTangentOffset = -1; INT iBinormalOffset = -1; INT iSkinDataOffset = -1; INT iColorOffset = -1; INT iUVOffset = -1; // create a vertex element struct and set default values T_VERTEX_ELEMENT VertexElement; ZeroMemory(&VertexElement, sizeof(T_VERTEX_ELEMENT)); D3D11_INPUT_ELEMENT_DESC InputElement; ZeroMemory(&InputElement, sizeof(D3D11_INPUT_ELEMENT_DESC)); bool bCompressVertexData = (dwFlags & COMPRESS_VERTEX_DATA); DWORD dwColorType = T_TYPE_FLOAT4; DXGI_FORMAT dwColorTypeDXGI = DXGI_FORMAT_B8G8R8A8_UNORM; switch (dwColorType) { case T_TYPE_FLOAT4: dwColorTypeDXGI = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case T_TYPE_D3DCOLOR: break; case T_TYPE_UBYTE4N: dwColorTypeDXGI = DXGI_FORMAT_R8G8B8A8_UNORM; break; case T_TYPE_FLOAT16_4: dwColorTypeDXGI = DXGI_FORMAT_R16G16B16A16_FLOAT; break; /*case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: dwColorTypeDXGI = DXGI_FORMAT_R10G10B10A2_UNORM; break; case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: dwColorTypeDXGI = DXGI_FORMAT_R11G11B10_FLOAT; break;*/ default: assert(false); break; } DWORD dwNormalType = T_TYPE_FLOAT3; DXGI_FORMAT dwNormalTypeDXGI = DXGI_FORMAT_R32G32B32_FLOAT; m_x2Bias = false; if (bCompressVertexData) { dwNormalType = DXGI_FORMAT_R8G8B8A8_UNORM; switch (dwNormalType) { case T_TYPE_UBYTE4N: dwNormalTypeDXGI = DXGI_FORMAT_R8G8B8A8_UNORM; m_x2Bias = true; break; case T_TYPE_SHORT4N: dwNormalTypeDXGI = DXGI_FORMAT_R16G16B16A16_SNORM; break; case T_TYPE_FLOAT16_4: dwNormalTypeDXGI = DXGI_FORMAT_R16G16B16A16_FLOAT; break; /*case T_TYPE_DXGI_R10G10B10A2_UNORM: dwNormalTypeDXGI = DXGI_FORMAT_R10G10B10A2_UNORM; m_x2Bias = true; break; case T_TYPE_DXGI_R11G11B10_FLOAT: dwNormalTypeDXGI = DXGI_FORMAT_R11G11B10_FLOAT; m_x2Bias = true; break; case T_TYPE_DXGI_R8G8B8A8_SNORM: dwNormalTypeDXGI = DXGI_FORMAT_R8G8B8A8_SNORM; break; case T_TYPE_XBOX_R10G10B10_SNORM_A2_UNORM: dwNormalTypeDXGI = DXGI_FORMAT(189); break;*/ default: assert(false); break; } } m_VertexElements.clear(); m_InputLayout.clear(); // check each vertex format option, and create a corresponding decl element if (m_VertexFormat.m_bPosition) { iPositionOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_POSITION; VertexElement.Type = T_TYPE_FLOAT3; m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "SV_Position"; InputElement.Format = DXGI_FORMAT_R32G32B32_FLOAT; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } if (m_VertexFormat.m_bSkinData) { iSkinDataOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_BLENDWEIGHT; VertexElement.Type = T_TYPE_UBYTE4N; m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "BLENDWEIGHT"; InputElement.Format = DXGI_FORMAT_R8G8B8A8_UNORM; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_BLENDINDICES; VertexElement.Type = T_TYPE_UBYTE4; m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "BLENDINDICES"; InputElement.Format = DXGI_FORMAT_R8G8B8A8_UINT; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } if (m_VertexFormat.m_bNormal) { iNormalOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_NORMAL; VertexElement.Type = static_cast<BYTE>(dwNormalType); m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "NORMAL"; InputElement.Format = dwNormalTypeDXGI; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } if (m_VertexFormat.m_bVertexColor) { iColorOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_COLOR; VertexElement.Type = static_cast<BYTE>(dwColorType); m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "COLOR"; InputElement.Format = dwColorTypeDXGI; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } if (m_VertexFormat.m_uUVSetCount > 0) { iUVOffset = iCurrentVertexOffset; for (UINT t = 0; t < m_VertexFormat.m_uUVSetCount; t++) { VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_TEXCOORD; InputElement.SemanticName = "TEXCOORD"; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); switch (m_VertexFormat.m_uUVSetSize) { case 1: VertexElement.Type = T_TYPE_FLOAT1; InputElement.Format = DXGI_FORMAT_R32_FLOAT; break; case 2: if (bCompressVertexData) { VertexElement.Type = T_TYPE_FLOAT16_2; InputElement.Format = DXGI_FORMAT_R16G16_FLOAT; } else { VertexElement.Type = T_TYPE_FLOAT2; InputElement.Format = DXGI_FORMAT_R32G32_FLOAT; } break; case 3: if (bCompressVertexData) { VertexElement.Type = T_TYPE_FLOAT16_4; InputElement.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; } else { VertexElement.Type = T_TYPE_FLOAT3; InputElement.Format = DXGI_FORMAT_R32G32B32_FLOAT; } break; case 4: if (bCompressVertexData) { VertexElement.Type = T_TYPE_FLOAT16_4; InputElement.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; } else { VertexElement.Type = T_TYPE_FLOAT4; InputElement.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; } break; default: continue; } VertexElement.UsageIndex = static_cast<BYTE>(t); m_VertexElements.push_back(VertexElement); InputElement.SemanticIndex = t; m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } VertexElement.UsageIndex = 0; InputElement.SemanticIndex = 0; } if (m_VertexFormat.m_bTangent) { iTangentOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_TANGENT; VertexElement.Type = static_cast<BYTE>(dwNormalType); m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "TANGENT"; InputElement.Format = dwNormalTypeDXGI; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } if (m_VertexFormat.m_bBinormal) { iBinormalOffset = iCurrentVertexOffset; VertexElement.Offset = static_cast<WORD>(iCurrentVertexOffset); VertexElement.Usage = T_USAGE_BINORMAL; VertexElement.Type = static_cast<BYTE>(dwNormalType); m_VertexElements.push_back(VertexElement); InputElement.SemanticName = "BINORMAL"; InputElement.Format = dwNormalTypeDXGI; InputElement.AlignedByteOffset = static_cast<UINT>(iCurrentVertexOffset); m_InputLayout.push_back(InputElement); iCurrentVertexOffset += GetElementSizeFromDeclType(VertexElement.Type); } assert(m_VertexElements.size() == m_InputLayout.size()); // save vertex size uVertexSize = iCurrentVertexOffset; if (uVertexSize == 0) return; // create vertex buffer and allocate storage size_t nVerts = VertexArray.size(); m_pVB = std::make_unique<ExportVB>(); m_pVB->SetVertexCount(nVerts); m_pVB->SetVertexSize(uVertexSize); m_pVB->Allocate(); if (iPositionOffset != -1) { m_pVBPositions.reset(new D3DXVECTOR3[nVerts]); memset(m_pVBPositions.get(), 0, sizeof(D3DXVECTOR3) * nVerts); } if (iNormalOffset != -1) { m_pVBNormals.reset(new D3DXVECTOR3[nVerts]); memset(m_pVBNormals.get(), 0, sizeof(D3DXVECTOR3) * nVerts); } if (iUVOffset != -1) { m_pVBTexCoords.reset(new D3DXVECTOR2[nVerts]); memset(m_pVBTexCoords.get(), 0, sizeof(D3DXVECTOR2) * nVerts); } // copy raw vertex data into the packed vertex buffer for (size_t i = 0; i < nVerts; i++) { auto pDestVertex = m_pVB->GetVertex(i); ExportMeshVertex* pSrcVertex = VertexArray[i]; if (!pSrcVertex) { continue; } if (iPositionOffset != -1) { auto pDest = reinterpret_cast<D3DXVECTOR3*>(pDestVertex + iPositionOffset); TransformPosition(pDest, &pSrcVertex->Position); memcpy(&m_pVBPositions[i], pDest, sizeof(D3DXVECTOR2)); } if (iNormalOffset != -1) { TransformAndWriteVector(pDestVertex + iNormalOffset, &m_pVBNormals[i], pSrcVertex->Normal, dwNormalType); } if (iSkinDataOffset != -1) { BYTE* pDest = pDestVertex + iSkinDataOffset; BYTE* pBoneWeights = pDest; *pDest++ = static_cast<BYTE>(pSrcVertex->BoneWeights.x * 255.0f); *pDest++ = static_cast<BYTE>(pSrcVertex->BoneWeights.y * 255.0f); *pDest++ = static_cast<BYTE>(pSrcVertex->BoneWeights.z * 255.0f); *pDest++ = static_cast<BYTE>(pSrcVertex->BoneWeights.w * 255.0f); NormalizeBoneWeights(pBoneWeights); *pDest++ = (BYTE)pSrcVertex->BoneIndices.x; *pDest++ = (BYTE)pSrcVertex->BoneIndices.y; *pDest++ = (BYTE)pSrcVertex->BoneIndices.z; *pDest++ = (BYTE)pSrcVertex->BoneIndices.w; } if (iTangentOffset != -1) { TransformAndWriteVector(pDestVertex + iTangentOffset, nullptr, pSrcVertex->Tangent, dwNormalType); } if (iBinormalOffset != -1) { TransformAndWriteVector(pDestVertex + iBinormalOffset, nullptr, pSrcVertex->Binormal, dwNormalType); } if (iColorOffset != -1) { WriteColor(pDestVertex + iColorOffset, pSrcVertex->Color, dwColorType); } if (iUVOffset != -1) { UINT iTangentSpaceIndex = 0; if (m_VertexFormat.m_uUVSetCount > iTangentSpaceIndex) { if (m_VertexFormat.m_uUVSetSize > 1) { memcpy(&m_pVBTexCoords[i], &pSrcVertex->TexCoords[iTangentSpaceIndex], sizeof(D3DXVECTOR2)); } } /*if (bCompressVertexData) { auto pDest = reinterpret_cast<DWORD*>(pDestVertex + iUVOffset); for (size_t t = 0; t < m_VertexFormat.m_uUVSetCount; t++) { switch (m_VertexFormat.m_uUVSetSize) { case 1: { memcpy(pDest, &pSrcVertex->TexCoords[t], sizeof(float)); pDest++; break; } case 2: { auto pFloat16 = reinterpret_cast<HALF*>(pDest); XMConvertFloatToHalfStream(pFloat16, sizeof(HALF), reinterpret_cast<const float*>(&pSrcVertex->TexCoords[t]), sizeof(float), 2); pDest++; break; } case 3: { pDest[1] = 0; auto pFloat16 = reinterpret_cast<HALF*>(pDest); XMConvertFloatToHalfStream(pFloat16, sizeof(HALF), reinterpret_cast<const float*>(&pSrcVertex->TexCoords[t]), sizeof(float), 3); pDest += 2; break; } case 4: { auto pFloat16 = reinterpret_cast<HALF*>(pDest); XMConvertFloatToHalfStream(pFloat16, sizeof(HALF), reinterpret_cast<const float*>(&pSrcVertex->TexCoords[t]), sizeof(float), 4); pDest += 2; break; } default: assert(false); break; } } } else*/ { size_t uStride = m_VertexFormat.m_uUVSetSize * sizeof(float); BYTE* pDest = pDestVertex + iUVOffset; for (UINT t = 0; t < m_VertexFormat.m_uUVSetCount; t++) { memcpy(pDest, &pSrcVertex->TexCoords[t], uStride); pDest += uStride; } } } } } void TExpMesh::WriteColor(BYTE* pDest, const D3DXVECTOR4& Src, DWORD dwDestFormat) { /*static const XMVECTORF32 s_8BitBias = { 0.5f / 255.f, 0.5f / 255.f, 0.5f / 255.f, 0.5f / 255.f }; switch (dwDestFormat) { case D3DDECLTYPE_D3DCOLOR: { XMVECTOR clr = XMLoadFloat4(&Src); clr = XMVectorAdd(clr, s_8BitBias); XMStoreColor(reinterpret_cast<XMCOLOR*>(pDest), clr); break; } case D3DDECLTYPE_UBYTE4N: { XMVECTOR clr = XMLoadFloat4(&Src); clr = XMVectorAdd(clr, s_8BitBias); XMStoreUByteN4(reinterpret_cast<XMUBYTEN4*>(pDest), clr); break; } case D3DDECLTYPE_FLOAT4: *reinterpret_cast<D3DXVECTOR4*>(pDest) = Src; break; case D3DDECLTYPE_FLOAT16_4: *reinterpret_cast<D3DXVECTOR4*>(pDest) = D3DXVECTOR4(Src.x, Src.y, Src.z, Src.z); break; case D3DDECLTYPE_DXGI_R10G10B10A2_UNORM: { XMVECTOR clr = XMLoadFloat4(&Src); XMStoreUDecN4(reinterpret_cast<XMUDECN4*>(pDest), clr); break; } case D3DDECLTYPE_DXGI_R11G11B10_FLOAT: { XMVECTOR clr = XMLoadFloat4(&Src); XMStoreFloat3PK(reinterpret_cast<XMFLOAT3PK*>(pDest), clr); break; } default: assert(false); break; }*/ } void TExpMesh::TransformAndWriteVector(BYTE* pDest, D3DXVECTOR3* normal, const D3DXVECTOR3& Src, DWORD dwDestFormat) { D3DXVECTOR3 SrcTransformed; TransformDirection(&SrcTransformed, &Src); if (normal) { memcpy(normal, &SrcTransformed, sizeof(D3DXVECTOR3)); } switch (dwDestFormat) { case T_TYPE_FLOAT3: { *reinterpret_cast<D3DXVECTOR3*>(pDest) = SrcTransformed; break; } //case T_TYPE_UBYTE4N: // Biased to get normals [-1,1] into range //{ // D3DXVECTOR3 v = SrcTransformed; // v = v * g_XMOneHalf; // v += g_XMOneHalf; // v = XMVectorSelect(g_XMOne, v, g_XMSelect1110); // XMStoreUByteN4(reinterpret_cast<XMUBYTEN4*>(pDest), v); // break; //} //case T_TYPE_SHORT4N: //{ // *reinterpret_cast<XMSHORTN4*>(pDest) = XMSHORTN4(SrcTransformed.x, SrcTransformed.y, SrcTransformed.z, 1); // break; //} //case T_TYPE_FLOAT16_4: //{ // *reinterpret_cast<XMHALF4*>(pDest) = XMHALF4(SrcTransformed.x, SrcTransformed.y, SrcTransformed.z, 1); // break; //} //case T_TYPE_DXGI_R10G10B10A2_UNORM: // Biased to get normals [-1,1] into range //{ // XMVECTOR v = XMLoadFloat3(&SrcTransformed); // v = v * g_XMOneHalf; // v += g_XMOneHalf; // XMStoreUDecN4(reinterpret_cast<XMUDECN4*>(pDest), v); // break; //} //case T_TYPE_DXGI_R11G11B10_FLOAT: // Biased to get normals [-1,1] into range //{ // XMVECTOR v = XMLoadFloat3(&SrcTransformed); // v = v * g_XMOneHalf; // v += g_XMOneHalf; // XMStoreFloat3PK(reinterpret_cast<XMFLOAT3PK*>(pDest), v); // break; //} //case T_TYPE_DXGI_R8G8B8A8_SNORM: //{ // *reinterpret_cast<XMBYTEN4*>(pDest) = XMBYTEN4(SrcTransformed.x, SrcTransformed.y, SrcTransformed.z, 1); // break; //} //case D3DDECLTYPE_XBOX_R10G10B10_SNORM_A2_UNORM: //{ // // Xbox One specific format // *reinterpret_cast<XMXDECN4*>(pDest) = XMXDECN4(SrcTransformed.x, SrcTransformed.y, SrcTransformed.z, 1); // break; //} default: assert(false); break; } } void TExpMesh::TransformPosition(D3DXVECTOR3* pDestPosition, const D3DXVECTOR3* pSrcPosition) const { D3DXVECTOR3 SrcVector; if (pSrcPosition == pDestPosition) { SrcVector = *pSrcPosition; pSrcPosition = &SrcVector; } if (m_bMaxConversion) { pDestPosition->x = pSrcPosition->x * m_fUnitScale; pDestPosition->y = pSrcPosition->z * m_fUnitScale; pDestPosition->z = pSrcPosition->y * m_fUnitScale; } else { const float flipZ = m_bFlipZ ? -1.0f : 1.0f; pDestPosition->x = pSrcPosition->x * m_fUnitScale; pDestPosition->y = pSrcPosition->y * m_fUnitScale; pDestPosition->z = pSrcPosition->z * m_fUnitScale * flipZ; } } void TExpMesh::TransformDirection(D3DXVECTOR3* pDestDirection, const D3DXVECTOR3* pSrcDirection) const { D3DXVECTOR3 SrcVector; if (pSrcDirection == pDestDirection) { SrcVector = *pSrcDirection; pSrcDirection = &SrcVector; } if (m_bMaxConversion) { pDestDirection->x = pSrcDirection->x; pDestDirection->y = pSrcDirection->z; pDestDirection->z = pSrcDirection->y; } else { const float flipZ = m_bFlipZ ? -1.0f : 1.0f; pDestDirection->x = pSrcDirection->x; pDestDirection->y = pSrcDirection->y; pDestDirection->z = pSrcDirection->z * flipZ; } } void TExpMesh::TransformMatrix(D3DXMATRIX* pDestMatrix, const D3DXMATRIX* pSrcMatrix) const { D3DXMATRIX SrcMatrix; if (pSrcMatrix == pDestMatrix) { memcpy(&SrcMatrix, pSrcMatrix, sizeof(D3DXMATRIX)); pSrcMatrix = &SrcMatrix; } memcpy(pDestMatrix, pSrcMatrix, sizeof(D3DXMATRIX)); // What we're doing here is premultiplying by a left hand -> right hand matrix, // and then postmultiplying by a right hand -> left hand matrix. // The end result of those multiplications is that the third row and the third // column are negated (so element _33 is left alone). So instead of actually // carrying out the multiplication, we just negate the 6 matrix elements. if (m_bFlipZ) { pDestMatrix->_13 = -pSrcMatrix->_13; pDestMatrix->_23 = -pSrcMatrix->_23; pDestMatrix->_43 = -pSrcMatrix->_43; pDestMatrix->_31 = -pSrcMatrix->_31; pDestMatrix->_32 = -pSrcMatrix->_32; pDestMatrix->_34 = -pSrcMatrix->_34; } // Apply the global unit scale to the translation components of the matrix. pDestMatrix->_41 *= m_fUnitScale; pDestMatrix->_42 *= m_fUnitScale; pDestMatrix->_43 *= m_fUnitScale; } float TExpMesh::TransformLength(float fInputLength) const { return fInputLength * m_fUnitScale; } TExpMesh::TExpMesh() : m_fUnitScale(1.0f), m_bFlipZ(true), m_bMaxConversion(false) { } TExpMesh::~TExpMesh() { m_InfluenceNames.clear(); } <file_sep>#include <stdio.h> int main(void) { printf("정수나눗셈:5/4 %d이다.\n", 5 / 4); printf("정수나눗셈:6/3 %d이다.\n", 6 / 3); printf("정수나눗셈:7/4 %d이다.\n", 7 / 4); printf("부동소수점나눗셈:7.0/4.0는 %2.2f이다.\n", 7.0 / 4.0); printf("혼합나눗셈:7.0/4는 %2.2f이다\n", 7.0 / 4); }<file_sep>#pragma once #include<iostream> const int g_iMaxQueue = 5; class TQueue { public: int m_iQueueArray[g_iMaxQueue]; int m_iFront; int m_iNear; public: int Get(); int put(int iData); void Show(); public: TQueue(); virtual ~TQueue(); }; <file_sep>#include "Problem.h" /////////////////////////////////////////////////// //원형 링크드 리스트를 작성한다. /////////////////////////////////////////////////// _NODE * CircularLinkedList(char *strList) { _NODE *pNode = 0; pNode = (_NODE*)malloc(iNodeSize); pNode->cName = strList[0]; g_pHead = pNode; int iMaxCount = strlen(strList); for (int iCount = 1; iCount < iMaxCount; iCount++) { pNode->pNext = (_NODE*)malloc(iNodeSize); pNode = pNode->pNext; pNode->cName = strList[iCount]; } pNode->pNext = g_pHead; return g_pHead; } ///////////////////////////////////////////////////////////// //노드를 삭제한다 //////////////////////////////////////////////////////////// _NODE*NextNodeDelete(_NODE*pNode) { _NODE *pDelNode = pNode->pNext; pNode->pNext = pDelNode->pNext; free(pDelNode); return pNode->pNext; } //////////////////////////////////////////////////////////// //요셉의 문제를 계산한다 //////////////////////////////////////////////////////////// void JosephProblem(_NODE* pNode, int n) { _NODE *pPreNode = 0; while (pNode != pNode->pNext) { for (int i = 0; i < n - 1; i++) { pPreNode = pNode; pNode = pNode->pNext; } printf("%c", pNode->cName); pNode = NextNodeDelete(pPreNode); } printf("\n\n탈출할 장병: %c\n", pNode->cName); free(pNode); } /////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////// void main() { char strList[100]; int iCount; printf("장병 문자열...?"); scanf("%s", &strList); //fflush(stdin); char c; while ((c = getchar()) != '\n'&&c != EOF); printf("몇명 간격...?"); scanf("%d", &iCount); iNodeSize = sizeof(_NODE); _NODE* pLeafNode = CircularLinkedList(strList); JosephProblem(pLeafNode, iCount); }<file_sep>#include<stdio.h> #include<conio.h> void main() { int a = 4; if (a == 1) { printf("A=1\n"); } else if (a == 2) { printf("A=2\n"); } else if (a == 3) { printf("A=3\n"); } else { printf("Error\n"); } }<file_sep>#include "TQueue.h" #include <queue> #include <deque> void main() { std::deque<int> queueList; queueList.push_back(0); queueList.push_back(1); queueList.push_back(2); int iA =queueList.front(); int iB = queueList.back(); queueList.pop_front(); queueList.push_back(); TQueue queue; queue.put(0); queue.put(1); queue.put(2); queue.put(3); queue.put(4); queue.put(5); queue.Get(); queue.put(6); // 0 queue.put(7); queue.Get(); queue.Get(); queue.Get(); queue.put(8); queue.put(9); queue.Get(); queue.Get(); queue.put(10); }<file_sep>#include "SServer.h" bool SServer::SendMsg(SOCKET socket, const char* msg, WORD code) // 보내기 { UPACKET sendmsg; ZeroMemory(&sendmsg, sizeof(sendmsg)); // sprintf (sendmsg.msg, "%s",msg); sprintf_s(sendmsg.msg, "%s", msg); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(sendmsg.msg); int iRet = send(socket, (char*)&sendmsg, sendmsg.ph.len, 0); if (iRet <= 0) { return false; } return true; } bool SServer::AddUser(SOCKET socket, SOCKADDR_IN address) { return true; } bool SServer::Init() { // 쓰레드 생성 CreateThread(); return true; } bool SServer::Run() { return true; } bool SServer::Release() { return true; } SServer::SServer(void) { } SServer::~SServer(void) { } <file_sep>#pragma once #include "SActor.h" class SButton : public SActor { public: vector<PNCT_VERTEX> m_tVertexList; SActor m_Actor[9]; SPoint m_cpPoint[16]; public: D3DXVECTOR3 Gen(float x, float y); void MoveX(float fDis); void MoveY(float fDis); void SetVertexData(); public: bool SetData(RECT rt, float fScaleX0 = 1.0f,float fScaleX1=1.0f, float fScaleY0 = 1.0f, float fScaleY1 = 1.0f, float fOffsetU0 = 1.0f, float fOffsetU1 = 1.0f, float fOffsetV0 = 1.0f, float fOffsetV1 = 1.0f); bool Create(ID3D11Device* pd3dDevice, const TCHAR* pVsFile, const TCHAR* pPsFile, const TCHAR* pTexFile); bool Render(ID3D11DeviceContext* pContext,UINT iVertexSize); bool PostRender(ID3D11DeviceContext* pContext); bool Init(); bool Frame(float fGameTimer, float fFps); bool Release(); public: SButton(); virtual ~SButton(); }; <file_sep>#include <stdio.h> #include <conio.h> #include <stdlib.h> void main() { char*pCharPoint = 0; int iCount = 0; pCharPoint = (char*)malloc(sizeof(char) * 100); do { pCharPoint[iCount++] = _getche(); } while (pCharPoint[iCount - 1] != '\r'); //\n,\r pCharPoint[iCount + 1] = 0; printf("\n0x%08x¹øÁö:%s", pCharPoint, pCharPoint); for (int iCnt = 0; iCnt < iCount; iCnt++) { printf("\n0x%08x¹øÁö:%c", pCharPoint + iCnt, *(pCharPoint + iCnt)); } free(pCharPoint); }<file_sep>#include "sInput.h" SGameInput g_Input; bool sInput::Frame() { HRESULT hr; if (FAILED(hr = m_pKey->GetDeviceState(256, &m_KeyState))) { while (m_pKey->Acquire() == DIERR_INPUTLOST); } if (FAILED(hr = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_MouseState))) { while (m_pMouse->Acquire() == DIERR_INPUTLOST); } g_Input.bFront = m_KeyState[DIK_W]; g_Input.bBack = m_KeyState[DIK_S]; g_Input.bLeft = m_KeyState[DIK_A]; g_Input.bRight = m_KeyState[DIK_D]; g_Input.bSpace = m_KeyState[DIK_SPACE]; g_Input.bButton0 = m_MouseState.rgbButtons[0]; g_Input.bButton1 = m_MouseState.rgbButtons[1]; g_Input.bButton2 = m_MouseState.rgbButtons[2]; return true; } bool sInput::Release() { m_pKey->Unacquire(); m_pMouse->Unacquire(); m_pKey->Release(); m_pMouse->Release(); m_pDI->Release(); return true; } bool sInput::Init() { memset(&m_KeyState, 0, sizeof(BYTE) * 256); memset(&m_MouseState, 0, sizeof(DIMOUSESTATE)); HRESULT hr; if (FAILED(hr = DirectInput8Create(g_hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDI, NULL))) { return false; } // keyboard if (FAILED(hr = m_pDI->CreateDevice(GUID_SysKeyboard, &m_pKey, NULL))) { return false; } if (FAILED(hr = m_pKey->SetDataFormat(&c_dfDIKeyboard))) { return false; } if (FAILED(hr = m_pKey->SetCooperativeLevel( g_hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND | DISCL_NOWINKEY))) { return false; } while (m_pKey->Acquire() == DIERR_INPUTLOST); // mouse if (FAILED(hr = m_pDI->CreateDevice(GUID_SysMouse, &m_pMouse, NULL))) { return false; } if (FAILED(hr = m_pMouse->SetDataFormat(&c_dfDIMouse))) { return false; } if (FAILED(hr = m_pMouse->SetCooperativeLevel(g_hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND | DISCL_NOWINKEY))) { return false; } while (m_pMouse->Acquire() == DIERR_INPUTLOST); return true; } sInput::sInput() { } sInput::~sInput() { } <file_sep>#include "xMap.h" bool xMap::CreateHeightMap(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, T_STR szName) { HRESULT hr; D3DX11_IMAGE_INFO imageinfo; ID3D11Resource* pLoadTexture = nullptr; D3DX11_IMAGE_LOAD_INFO info; ZeroMemory(&info, sizeof(info)); info.MipLevels = 1; info.Usage = D3D11_USAGE_STAGING; info.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; info.Format = DXGI_FORMAT_FROM_FILE; info.pSrcInfo = &imageinfo; if (FAILED(hr = D3DX11CreateTextureFromFile(pDevice, szName.c_str(), &info, NULL, &pLoadTexture, NULL))) { return false; } ID3D11Texture2D* pTex2D = nullptr; if( FAILED(pLoadTexture->QueryInterface( __uuidof(ID3D11Texture2D), (LPVOID*)&pTex2D))) { return false; } SAFE_RELEASE(pLoadTexture); D3D11_TEXTURE2D_DESC desc; pTex2D->GetDesc(&desc); m_fHeightList.resize(desc.Height*desc.Width); D3D11_MAPPED_SUBRESOURCE map; UINT index = D3D11CalcSubresource(0, 0, 1); if (SUCCEEDED(pContext->Map(pTex2D, index, D3D11_MAP_READ, 0, &map))) { UCHAR* pTexels = (UCHAR*)map.pData; for (UINT iRow = 0; iRow < desc.Height; iRow++) { UINT rowStart = iRow * map.RowPitch; for (UINT iCol= 0; iCol < desc.Width; iCol++) { UINT colStart = iCol * 4; UCHAR uRed = pTexels[rowStart + colStart +0]; m_fHeightList[iRow*desc.Width+ iCol] = uRed; } } pContext->Unmap(pTex2D, index); } m_iNumRows = desc.Height; m_iNumCols = desc.Width; return true; } HRESULT xMap::CreateVertexData() { m_iNumVertex = m_iNumVertices; m_VertexList.resize(m_iNumVertices); float fHalfCols = (m_iNumCols-1) / 2.0f; float fHalfRows = (m_iNumRows - 1) / 2.0f; float fOffsetU = 1.0f / (m_iNumCols - 1); float fOffsetV = 1.0f / (m_iNumRows - 1); for (int iRow = 0; iRow < m_iNumRows; iRow++) { for (int iCol = 0; iCol < m_iNumCols; iCol++) { int iIndex = iRow * m_iNumCols + iCol; m_VertexList[iIndex].p.x = (iCol-fHalfCols)*m_fCellDistance; m_VertexList[iIndex].p.y = GetHeightOfVertex(iIndex); m_VertexList[iIndex].p.z = -((iRow - fHalfRows)*m_fCellDistance); m_VertexList[iIndex].n = GetNormalOfVertex(iIndex); m_VertexList[iIndex].c = GetColorOfVertex(iIndex); m_VertexList[iIndex].t = GetTextureOfVertex(fOffsetU*iCol, fOffsetV*iRow); } } return S_OK; } HRESULT xMap::CreateIndexData() { m_iNumIndex = m_iNumFace * 3; m_IndexList.resize(m_iNumIndex); int iIndex = 0; for (int iRow = 0; iRow < m_iNumCellRows; iRow++) { for (int iCol = 0; iCol < m_iNumCellCols; iCol++) { // 0 1 2 // 3 4 5 int iNextRow = iRow + 1; m_IndexList[iIndex + 0] = iRow * m_iNumCols + iCol; m_IndexList[iIndex + 1] = m_IndexList[iIndex + 0]+1; m_IndexList[iIndex + 2] = iNextRow * m_iNumCols + iCol; m_IndexList[iIndex + 3] = m_IndexList[iIndex + 2]; m_IndexList[iIndex + 4] = m_IndexList[iIndex + 1]; m_IndexList[iIndex + 5] = m_IndexList[iIndex + 2]+1; iIndex += 6; } } return S_OK; } D3DXVECTOR2 xMap::GetTextureOfVertex(float fU, float fV) { return D3DXVECTOR2(fU*50, fV*50); } D3DXVECTOR3 xMap::GetNormalOfVertex(int iIndex) { return D3DXVECTOR3(0.0f, 1.0f, 0.0f ); } D3DXVECTOR4 xMap::GetColorOfVertex(int iIndex) { return D3DXVECTOR4( randstep(0.0f, 1.0f), randstep(0.0f, 1.0f), randstep(0.0f, 1.0f), 1.0f ); } float xMap::GetHeightOfVertex(int iIndex) { return m_fHeightList[iIndex]* m_fScaleHeight; } bool xMap::CreateMap(xMapDesc desc) { m_iNumRows = desc.iNumRows; m_iNumCols = desc.iNumCols; m_iNumCellRows = m_iNumRows-1; m_iNumCellCols= m_iNumCols-1; m_iNumVertices = m_iNumRows * m_iNumCols; m_iNumFace = m_iNumCellRows* m_iNumCellCols*2; m_fCellDistance = desc.fDistance; m_fScaleHeight = desc.fScaleHeight; return true; } bool xMap::Load(ID3D11Device* pDevice, xMapDesc desc) { m_pd3dDevice = pDevice; if (!CreateMap(desc)) { return false; } xShape::Create(m_pd3dDevice,desc.szShaderFile,desc.szTextureFile); return true; } bool xMap::Init() { return true; } bool xMap::Frame() { return xShape::Frame(); } bool xMap::Render(ID3D11DeviceContext* pContext) { xShape::Render(pContext); return true; } bool xMap::Release() { xShape::Release(); return true; } xMap::xMap() { m_fScaleHeight = 1; } xMap::~xMap() { } <file_sep>#include <iostream> #define MAX 10 using namespace std; int queue[MAX]; int front, rear; void InitQueue() { front = rear = 0; } void ClearQueue() { front = rear; } int put(int t) { if ((rear + 1) % MAX == front) { cout << "over flow" << endl; return -1; } queue[rear] = t; rear = ++rear % MAX; return t; } int get() { if (front == rear) { cout << " under flow" << endl; return -1; } int i = queue[front]; front = ++front % MAX; return i; } void PrintQueue() { cout << " Queue Contents : Top ---> Bottom" << endl; for (int i = front; i != rear; i = ++i%MAX) { cout << "%-6d" << queue[i] << endl; } } void main() { InitQueue(); printf("\nPush 5,4,7,8,2,1"); put(5); put(4); put(7); put(8); put(2); put(1); PrintQueue(); printf("\nGet"); int i = get(); PrintQueue(); printf("\n Put 3,2,5,7"); put(3); put(2); put(5); put(7); PrintQueue(); printf("\nNow queue is full, push 3"); put(3); PrintQueue(); printf("\n Initialize queue"); ClearQueue(); PrintQueue(); printf("\nNow queue is empty, pop"); i = get(); printf("\n poppint value is %d", i); system("pause"); }<file_sep>#pragma once #include "MyWindow.h" class CDXDevice : public CMyWindow { private: //그래픽 카드 장치 인터페이스(리소스생성) ID3D11Device* m_pD3DDevice; //명령 제어, 전달 및 실행 인터페이스 ID3D11DeviceContext* m_pImmediateContext; public: ID3D11Debug* m_pDebug; IDXGIFactory* m_pGIFactory; //오프스크린 (더블버퍼링 담당)인터페이스 IDXGISwapChain* m_pSwapChain; //오프스크린 대상 버퍼 ID3D11RenderTargetView* m_pRTV; DXGI_SWAP_CHAIN_DESC m_SwapChainDesc; D3D11_VIEWPORT m_ViewPort; D3D_DRIVER_TYPE m_DriverType; //스텐실 버퍼 ID3D11DepthStencilView* m_pDSV; public: ID3D11Device* GetDevice() { return m_pD3DDevice; }; ID3D11DeviceContext* GetContext() { return m_pImmediateContext; }; public: bool Init(); bool PreRender(); bool PostRender(); bool Release(); public: bool Reset(UINT iWidth, UINT iHeight); HRESULT CreateGIFactory(); HRESULT CreateDevice(); HRESULT CreateSwapChain(); HRESULT CreateDepthStencilState(); HRESULT SetRenderTargetView(); HRESULT SetViewPort(); public: CDXDevice(); virtual ~CDXDevice(); };<file_sep>#include "CLinkedList.h" void CLinkedList::Add() { //첫번째 생성 if (m_Head == NULL) { m_Head = new Node(iMAX++); // HEAD 동적할당 m_Tail = m_Head; //Tail과 Head 연결 m_Tail->m_pNext = NULL; //Tail의 Next가 NULL return; } // 두번쨰 생성 m_Tail->m_pNext = new Node(iMAX++); //Tail의 next 동적할당 m_Tail = m_Tail->m_pNext; //Tail을 next에 연결 m_Tail->m_pNext = NULL; //Tail의 next가 NULL } void CLinkedList::Del(int aData) { if (m_Head != NULL) // Head가 NULL이 아닐경우 { if (m_Head->m_pNext == NULL) //Head의 next가 NULL일 경우 { if (m_Head->iData == aData) //head의 iData가 aData와 같을 경우 { delete m_Head; //Head를 삭제 }return; } if (m_Head->m_pNext != NULL) //Head의 next가 NULL이 아닌경우 { Node* pTemp; //빈 노드 if (m_Head->iData == aData)//head의 iData가 aData와 같을 경우 { pTemp = m_Head->m_pNext; //temp에 Head의 next를 저장 delete m_Head; //헤더를 삭제 m_Head = pTemp; //Head에 다시 저장 } for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { if (pTemp->m_pNext->iData == aData) { break; } } Node* DelNode = pTemp->m_pNext; // 지울 노드의 next를 저장 Node* DelNodeNext = DelNode->m_pNext; delete DelNode; pTemp->m_pNext = DelNodeNext; } } } void CLinkedList::Print() { Node* pTemp; for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { cout << pTemp->iData << endl; } cout << pTemp->iData << endl; } void CLinkedList::Find(int sData) { Node* pTemp; for (pTemp = m_Head; pTemp->m_pNext != NULL; pTemp = pTemp->m_pNext) { if (pTemp->m_pNext->iData == sData) { break; } } } CLinkedList::CLinkedList() { m_Head = 0; m_Tail = 0; iMAX = 0; } CLinkedList::~CLinkedList() { } <file_sep>#include <iostream> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; bool swap(int* a, int* b) { if (*a > *b) { int t = *a; *a = *b; *b = t; return true; } return false; } void SelectionSort(int item[], int count) { for (int a=0; a<count; a++) { for (int b = a + 1; b < count; b++) { swap(&item[a], &item[b]); } } } void BubbleSort(int item[], int count) { for (int a = 0; a < count - 1; a++) { bool bFlag = false; for (int b = 0; b < count - a - 1; b++) { if (swap(&item[a], &item[b])) { bFlag = true; } } if (bFlag == false) break; } } void InsertionSort(int item[], int count, int iStart = 1, int iStep = 1) { for (int a = iStart; a < count; a += iStep) { int temp = item[a]; int b = a - iStep; while (b >=0 && item[b] > temp) { item[b + iStep] = item[b]; b -= iStep; } item[b + iStep] = temp; } } void shellsort(int item[], int n) { int k = 4; while (k>1) { k = k / 2; for (int s = 0; s < k; s++) { InsertionSort(item, n, s, k); } } } void DataPrint(int item[], int iCount) { //return; for (int t = 0; t < iCount; t++) { if (t % 20 == 0) { cout << " "; } cout << item[t]<<" "; } } void Merge(int item[], int iStart, int iEnd, int iMiddle) { vector<int>itemList; int i = iStart; int j = iMiddle + 1; while (i <= iMiddle && j <= iEnd) { if (item[i] < item[j]) { itemList.push_back(item[i++]); } else { itemList.push_back(item[j++]); } } while (i <= iMiddle)itemList.push_back(item[i++]); while (j <= iEnd)itemList.push_back(item[j++]); int copy = 0; for (int k = iStart; k <= iEnd; k++) { item[k] = itemList[copy++]; } } void MergeSort(int item[], int iStart, int iEnd) { if (iStart < iEnd) { int iMiddle = (iStart + iEnd) / 2; MergeSort(item, iStart, iMiddle); MergeSort(item, iMiddle + 1, iEnd); Merge(item,iStart, iEnd, iMiddle); } } void QuickSort(int item[], int iStart, int iEnd) { int iPivot = item[iStart]; int iBeginStart = iStart; int iBeginEnd = iEnd; while (iStart < iEnd) { while (iPivot <= item[iEnd] && iStart < iEnd) { iEnd--; } if (iStart > iEnd)break; while (iPivot >= item[iStart] && iStart < iEnd) { iStart++; } if (iStart > iEnd)break; swap(&item[iStart], &item[iEnd]); } swap(&item[iBeginStart], &item[iStart]); if (iBeginStart < iStart) QuickSort(item, iBeginStart, iStart - 1); if (iBeginEnd > iEnd) QuickSort(item, iStart + 1, iBeginEnd); } void SetData(int item[], int iCount) { srand((unsigned int)time(NULL)); for (int a = 0; a < iCount; a++) { item[a] = rand() % iCount; } DataPrint(item, iCount); } void main() { int item[10000]; int count = 10000; clock_t sTime, eTime; cout << " How many numbers(MAX=10000?"; scanf_s("%d", &count); getchar(); printf("\nSelect Sort "); SetData(item, count); sTime = clock(); SelectionSort(item, count); eTime = clock() - sTime; printf("\n\ttime => [%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); printf("\nBubble Sort "); SetData(item, count); sTime = clock(); BubbleSort(item, count); eTime = clock() - sTime; printf("\n\ttime => [%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); printf("\nInsert Sort "); SetData(item, count); sTime = clock(); InsertionSort(item, count); eTime = clock() - sTime; printf("\n\ttime =>[%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); printf("\nshell Sort "); SetData(item, count); sTime = clock(); shellsort(item, count); eTime = clock() - sTime; printf("\n\ttime =>[%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); printf("\nMerge Sort "); SetData(item, count); //item[0] = 6; //item[1] = 5; //item[2] = 3; //item[3] = 1; //item[4] = 8; //item[5] = 7; //item[6] = 2; //item[7] = 4; //count = 8; sTime = clock(); MergeSort(item, 0, count - 1); eTime = clock() - sTime; printf("\n\ttime =>[%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); printf("\nQuick Sort "); SetData(item, count); sTime = clock(); QuickSort(item, 0, count - 1); eTime = clock() - sTime; printf("\n\ttime =>[%ld,%8.3f] => ", eTime, eTime / (double)CLK_TCK); DataPrint(item, count); getchar(); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> #include<conio.h> void main() { int i; int j; char str[30]; scanf("%s", str); j = strlen(str); for (i = j - 1; i >= 0; i--) { printf("%c", str[i]); } _getch(); }<file_sep>#include "SingleLinkedList.h" #include "Node.h" void SingleLinkedList::AddNode() { if (m_HeadNode == NULL) { return; } SNode* pNewNode = new SNode(++m_iCount); m_TailNode->m_pNextNode = pNewNode; m_TailNode = m_TailNode->m_pNextNode; m_TailNode->m_pNextNode = NULL; } void SingleLinkedList::AddNode(SNode* _pNewNode) { if (m_HeadNode) { return; } _pNewNode->m_iData = ++m_iCount; m_TailNode->m_pNextNode = _pNewNode; m_TailNode = m_TailNode->m_pNextNode; m_TailNode->m_pNextNode = NULL; } void SingleLinkedList:: DelNode(SNode* _pPreNode) { if (m_HeadNode == NULL) { return; } else if (_pPreNode == NULL || _pPreNode->m_pNextNode == NULL) { return; } SNode* pDelNode = _pPreNode->m_pNextNode; SNode* pNextNode = pDelNode->m_pNextNode; delete pDelNode; _pPreNode->m_pNextNode = pNextNode; m_iCount--; } void SingleLinkedList::DelNode(int _iData) { if (m_HeadNode == NULL) { return; } SNode* pSearchPreNode = m_HeadNode; while (pSearchPreNode->m_pNextNode != NULL) { if (pSearchPreNode->m_pNextNode->m_iData == _iData) { DelNode(pSearchPreNode); return; } pSearchPreNode = pSearchPreNode->m_pNextNode; } } void SingleLinkedList::ShowAllData() { for (SNode* pTemp = m_HeadNode; pTemp->m_pNextNode != NULL; pTemp = pTemp->m_pNextNode) { std::cout << pTemp->m_iData << std::endl; } } SingleLinkedList::SingleLinkedList() { m_iCount = 0; SNode* FirstNode = new SNode(m_iCount); m_HeadNode = FirstNode; m_TailNode = m_HeadNode; m_TailNode->m_pNextNode = NULL; } SingleLinkedList::~SingleLinkedList() { delete m_HeadNode; } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <WS2tcpip.h> // InetNtop() . inet_ntop() #include <iostream> #include <map> #pragma comment (lib,"ws2_32") using namespace std; bool BeginWinSock(); bool EndWinSock(); struct TUser { SOCKET sock; SOCKADDR_IN clientAddr; }; void main() { if (BeginWinSock() == false) { return; } SOCKET listenSock; listenSock = socket(AF_INET,SOCK_STREAM,0); // listen socket // ip + port -> bind -> 운영체제 보고,통지,알림,신고,적용,세팅 // port를 사용하고 있는 프로세스(인덱스에 불가 하다)(실행파일)(실행파일을 구분하는 용도로 사용한다)에게 알려 준다 SOCKADDR_IN sa; sa.sin_family = AF_INET; sa.sin_port = htons(10000); sa.sin_addr.s_addr = inet_addr("192,168,0,106"); //sa.sin_addr.s_addr = htonl(INADDR_ANY); bind(listenSock, (sockaddr*)&sa, sizeof(sa)); listen(listenSock, SOMAXCONN); // -> 개통 u_long on = TRUE; ioctlsocket(listenSock,FIONBIO,&on); //FIONBIO 블럭형 X std::map<int, TUser>g_userList; int g_iNumUser = 0; while (g_iNumUser<10) { TUser tUser; int iSize = sizeof(tUser.clientAddr); tUser.sock = accept(listenSock, (sockaddr*)&tUser.clientAddr, &iSize); // 누군가 -> 접속시도 if (tUser.sock == SOCKET_ERROR) { if (WSAGetLastError()!=WSAEWOULDBLOCK) //WSAEWOULDBLOCK와 같지 않으면 오류 { exit(1); } } else { g_userList.insert(make_pair(g_iNumUser++, tUser)); // Use inet_ntop() or lnetNtop() printf("\nip=%s,port=%d", inet_ntoa(tUser.clientAddr.sin_addr), ntohs(tUser.clientAddr.sin_port)); } //char ip[INET_ADDRSTRLEN] = { 0, }; //char ip[256] = { 0, }; //printf("\nip=%s,port=%d", inet_ntop(AF_INET, &clientAddr.sin_addr, ip, INET6_ADDRSTRLEN), // ntohs(clientAddr.sin_port)); } while (1) { char recvmsg[256] = { 0, }; int iRecvByte = sizeof(recvmsg); TUser* pUser for (int iUser = 0; iUser < g_userList.size(); iUser++) { int iByte = recv(g_userList[iUser].sock, recvmsg, iRecvByte, 0); printf("\nip=%s,port=%d", inet_ntoa(g_userList[iUser].clientAddr.sin_addr), //ntohs(g_userList[iUser].clientAddr.sin_addr,recvmsg); send(g_userList[iUser].sock, recvmsg, iRecvByte, 0); } } char msg[] = "게임종료합니다. !!!"; int iSebdByte = sizeof(msg); for (int iUser = 0; iUser < g_userList.size();) { send(g_userList[iUser].sock, msg, iSebdByte,0); } for (int iUser = 0; iUser < g_userList.size();) { closesocket(g_userList[iUser].sock); } closesocket(listenSock); // listen -> 듣다. // client socket 준비 // while(1) // client socket = accept // 누군가 -> 접속시도.연결시도 -> 수용,허가 EndWinSock(); } bool BeginWinSock() // 윈속 초기화 { WSADATA wsa; int iRet = WSAStartup(MAKEWORD(2, 2), &wsa); if (iRet != 0)return false; return true; } bool EndWinSock() // 윈속 소멸 { WSACleanup(); return true; }<file_sep>//쉘 정렬(Shell Sort) /*쉘 정렬은 삽입 정렬 알고리즘을 이용하는 정렬 방식이다. 같은 간격에 있는 원소들을 삽입 정렬 원리로 정렬하는 것을 반복간격의 초기값은 배열의 크기 /2 이며 간격이 1일떄까지 1/2로 줄이면서 반복한다*/ #include <stdio.h> #include <conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 int *origin; int on; void ShellSort(int *base, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; origin = arr; on = 10; ShellSort(arr, 10); _getch(); return 0; } void InsertionSort2(int *base, int size, int step); void ViewArr(int *arr, int n); void ShellSort(int *base, int size) { int i, step; for (step = size / 2; step>0; step /= 2)//step의 폭을 1/2로 줄여간다. { printf("step:%d\n", step); for (i = 0; i<step; i++) //step 간격에 있는 요소들을 삽입정렬 { InsertionSort2(base + i, size - i, step); } } } void InsertionSort2(int *base, int size, int step) { int i, j; for (i = step; i<size; i += step)//정렬 대상 원소는 step 간격으로 이동 { for (j = i; j>0; j -= step)//step 간격으로 앞으로 이동 { if (base[j - step]>base[j])//앞쪽이 더 클 때 { SWAP(base[j - step], base[j]);//교환 ViewArr(origin, on); } else { break; } } } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#include "stdafx.h" #include "Sample.h" Sample::Sample() { } Sample::~Sample() { } <file_sep>#include"TPoint.h" int main(void) { TPoint p1, p2; //점의 좌표를 저장할 변수 선언 p1.SetPosition(10, 20); //p1의 좌표 설정 p2.SetPosition(50, 60); //p2의 좌표설정 p1.Move(5, 0); //p1의 좌표 이동 p2.Move(0, 5); //p2의 좌표 이동 p1.Show(); //p1의 좌표를 출력 p2.Show(); //p2의 좌표를 출력 _getch(); return 0; }<file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <winsock2.h> #include <windows.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") #define MAX_BUF_SIZE 1048 void Error(char* msg) { LPVOID lpMsgBuffer; int iError = WSAGetLastError(); FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, iError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuffer, 0, NULL); printf("%s", lpMsgBuffer); LocalFree(lpMsgBuffer); exit(-1); } void main() { HANDLE m_hReadFile = ::CreateFile(L"../../data/bitmap1.bmp", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { return; } SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) { Error("sock invalid"); } BOOL bEnable = TRUE; setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&bEnable, sizeof(bEnable)); SOCKADDR_IN serveradd; ZeroMemory(&serveradd, sizeof(serveradd)); serveradd.sin_family = AF_INET; serveradd.sin_port = htons(9009); serveradd.sin_addr.s_addr = INADDR_BROADCAST; char buf[MAX_BUF_SIZE] = { 0, }; char recvbuf[MAX_BUF_SIZE] = { 0, }; char endbuffer[] = "end"; int addlen = sizeof(serveradd);; int iCount = 0; int iTotalSize = 0; while (1) { DWORD byteRead = 0; DWORD ret = ReadFile(m_hReadFile, buf, MAX_BUF_SIZE, &byteRead, NULL); if (byteRead == 0 || ret == FALSE) { //if (ERROR_HANDLE_EOF == ::GetLastError()) { sendto(sock, buf, strlen(endbuffer), 0, (SOCKADDR*)&serveradd, addlen); break; } } int iRet = sendto(sock, buf, byteRead, 0, (SOCKADDR*)&serveradd, addlen); if (iRet == 0) break; iTotalSize += iRet; printf("\n%d[%d]", iTotalSize, iCount++); Sleep(1000); } CloseHandle(m_hReadFile); WSACleanup(); } // //#include <winsock2.h> //#include<iostream> //#include<conio.h> //using namespace std; //#pragma comment(lib, "ws2_32.lib") //#define MYPORT 9009 // the port users will be connecting to // //int main() //{ // WSADATA wsaData; // WSAStartup(MAKEWORD(2, 2), &wsaData); // // SOCKET sock; // sock = socket(AF_INET, SOCK_DGRAM, 0); // char broadcast = '1'; // if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0) // { // cout << "Error in setting Broadcast option"; // closesocket(sock); // return 0; // } // struct sockaddr_in Recv_addr; // struct sockaddr_in Sender_addr; // int len = sizeof(struct sockaddr_in); // char sendMSG[] = "Broadcast message from KGCA GAME ACADEMY"; // char recvbuff[50] = ""; // int recvbufflen = 50; // // Recv_addr.sin_family = AF_INET; // Recv_addr.sin_port = htons(MYPORT); // Recv_addr.sin_addr.s_addr = INADDR_BROADCAST; // // sendto(sock, sendMSG, strlen(sendMSG) + 1, 0, (sockaddr *)&Recv_addr, sizeof(Recv_addr)); // recvfrom(sock, recvbuff, recvbufflen, 0, (sockaddr *)&Recv_addr, &len); // cout << "\n\n\tReceived message from Reader is => " << recvbuff; // cout << "\n\n\tpress any key to CONT..."; // _getch(); // closesocket(sock); // WSACleanup(); //}<file_sep>//하나의 추상 클래스에 execute() 메서드를 하나 만들고 각 명령이 들어오면 // 그에 맞는 서브 클래스(copy_command)가 선택되어 실행하는 것이 효율적이다. // 이는 함수 오버로딩(overloading)과 같은 추상화 개념을 사용한 것이다. #include <iostream> #include <string> #include <map> using namespace std; static const int NA_POS = -1; #define CMD_NAME "cmd" #define LOGIN_VAL "login" #define BBSLIST_VAL "bbslist" #define BBSREAD_VAL "bbsread" class Request { public: string GetValue(string name) { return nvList_[name]; } void SetNameValue(string name, string value) { nvList_[name] = value; } private: map<string, string>nvList_; }; class RequestParser { public: bool GetRequest(string input, Request& req) { string key, value, str; int start = 0, pos = 0; while (pos != NA_POS) { pos = input.find("=", start); if (pos == NA_POS) continue; key = input.substr(start, pos - start); start = pos + 1; pos = input.find("&", start); if (pos == NA_POS) value = input.substr(start, input.length() - start); else value = input.substr(start, pos - start); start = pos + 1; if (!key.empty()) { req.SetNameValue(DecodeString(key), DecodeString(value)); key = " "; } } return true; } protected: string DecodeString(string s) { string output; int len = s.length(); for (int i = 0; i < len; i++) { if (s[i] == '+') output += ' '; else if (s[i] == '%') { const char *pStr = s.data() + i + 1; char ch = Hex2Digit(pStr); output += ch; i += 2; } else output += s[i]; } return output; } unsigned int Hex2Digit(const char* hex) { register char digit; digit = (hex[0] >= 'A' ? ((hex[0] & 0x4F) - 'A') + 10 : (hex[0] - '0')); digit <<= 4; digit += (hex[1] >= 'A' ? ((hex[1] & 0x4F) - 'A') + 10 : (hex[1] - '0')); return digit; } private: }; class UserManager { public: bool CheckPasswd(Request& req) { cout << "Passwd ok" << endl; return true; } }; //Bulletin Board System class BBS { public: void DisplayList(Request& req) { cout << "Display BBS List" << endl; } void DisplayItem(Request& req) { cout << "Display BBS Item" << endl; } }; class Command { public: virtual void Execute(Request& req) = 0; }; class LoginCommand : public Command { public: LoginCommand(UserManager * pUserMan) { pUserMan_ = pUserMan; } void Execute(Request& req) { pUserMan_->CheckPasswd(req); } private: UserManager * pUserMan_; }; class ListCommand : public Command { public: ListCommand(BBS *pBbs) { pBbs_ = pBbs; } void Execute(Request& req) { pBbs_->DisplayList(req); } private: BBS * pBbs_; }; class ReadCommand : public Command { public: ReadCommand(BBS *pBbs) { pBbs_ = pBbs; } void Execute(Request& req) { pBbs_->DisplayItem(req); } private: BBS * pBbs_; }; BBS _bbs; UserManager _userMan; map<string, Command *> _req2cmd; void RegisterCommand() { _req2cmd[LOGIN_VAL] = new LoginCommand(&_userMan); _req2cmd[BBSLIST_VAL] = new ListCommand(&_bbs); _req2cmd[BBSREAD_VAL] = new ReadCommand(&_bbs); } void main() { string input; RequestParser parser; RegisterCommand(); while (1) { cin >> input; cout<< "Command 패턴 " << endl; Request req; parser.GetRequest(input, req); string cmd = req.GetValue(CMD_NAME); Command *pCmd = _req2cmd[cmd]; if (pCmd != NULL) pCmd->Execute(req); else cout << "Not Available Command : " << cmd << endl; } }<file_sep>#pragma once #include "S_Std.h" #include "S_Protocol.h" #include "S_SvrUser.h" class S_Client : public S_SvrUser { public: int m_iSocket; unsigned long m_SendThread; unsigned long m_ReceiveThread; bool m_bExit; public: char m_strBuf[128]; bool m_Send; bool m_LoginOk; public: bool Init(); bool Frame(); bool Release(); public: int CreateConnectSocket(int iPort); int SendMsg(char* pmsg, WORD code); int SendMsg(char* pmsg, int iSize, WORD code); int ProcessPacket(); public: S_Client(); ~S_Client(); }; <file_sep>#pragma warning (disable : 4996) #include <windows.h> // ODBC 위에 windows.h #include <stdlib.h> #include <iostream> #include <sql.h> #include <sqlext.h> #include <tchar.h> //SQLServer의 프로시저를 사용해서 바꾸는 작업을 한 프로젝트 SQLHENV g_hEnv; // 핸들 SQLHDBC g_hDbc; // 핸들 SQLHSTMT g_hStmt; // 핸들 bool Add(); void Select(); bool Delete(); bool Update(); SQLRETURN HandleDiagnosticRecord(SQLHANDLE hHandle, SQLSMALLINT hType, RETCODE RetCode) { int ii; SQLINTEGER NativeError; SQLTCHAR SqlState[6], Msg[255]; SQLSMALLINT MsgLen; TCHAR str[256]; ii = 1; while (RetCode = SQLGetDiagRec(hType, hHandle, ii, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen) != SQL_NO_DATA) { wsprintf(str, _T("SQLSTATE:%s, 진단정보:%s"), (LPCTSTR)SqlState, (LPCTSTR)Msg); ::MessageBox(NULL, str, _T("진단 정보"), 0); ii++; } return RetCode; } //Insert into tblcigar (name,prive,korean)values('aaa',3000,1) //_T("Insert into tblcigar (name,price,korean)values('bbb',3000,1)"); bool Add() { TCHAR szSQL[256] = { 0, }; SQLTCHAR ID[20] = L"aaa"; SQLTCHAR PS[20] = L"WWW"; wsprintf(szSQL, _T("Insert into UserList (userid, userpass)values('%s','%s')"), ID, PS); if (SQLExecDirect(g_hStmt, szSQL, SQL_NTS) // SQL 명령어를 실행 == SQL_SUCCESS) { SQLCloseCursor(g_hStmt); Select(); return true; } SQLCloseCursor(g_hStmt); return false; } // select ,, from table // select ,, from table where ?=? void Select() { // 명령핸들 SQLAllocHandle(SQL_HANDLE_STMT, g_hDbc, &g_hStmt); SQLCHAR ID[20] = { 0, }; SQLCHAR PS[20] = { 0, }; SQLLEN LID, LPS; SQLBindCol(g_hStmt, 1, SQL_C_CHAR, ID, sizeof(ID), &LID); // 리턴 받는걸 Name으로 받는다 SQLBindCol(g_hStmt, 2, SQL_C_CHAR, PS, sizeof(PS), &LPS); // 작업구간 // 조회 // 시가라는 테이블로부터 이름으로 되어있는것 전부다 리턴 // "select name,price,korean from tblCigar" SQL 명령어 //if (SQLExecDirect(g_Stmt, (SQLTCHAR*)_T("select name,price,korean from tblCigar where name = 'this'"), SQL_NTS) != SQL_SUCCESS) SWORD sReturn; SQLINTEGER cbRetParam; SQLBindParameter(g_hStmt, 1, SQL_PARAM_OUTPUT, SQL_C_SHORT, SQL_INTEGER, 0, 0, &sReturn, 0, &cbRetParam); SQLBindParameter(g_hStmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_INTEGER, 0, 0, &sReturn, 0, NULL); SQLRETURN ret=0; if (SQLExecDirect(g_hStmt, (SQLTCHAR*)_T("{?=CALL usp_Test(?)}"), SQL_NTS) // 저장프로시저 이름으로 불러올수 있드아 != SQL_SUCCESS) { HandleDiagnosticRecord(g_hStmt,SQL_HANDLE_STMT,ret); return; } while (SQLFetch(g_hStmt) != SQL_NO_DATA) { printf("\nID : %s\tPS : %s", ID, PS); } // 커서를 해제시켜준다 (맨위로 올려준다) // 이유 커서가 있는곳으로 부터 검색을 하기때문에 맨위로 올려준다고 생각하면된다. SQLCloseCursor(g_hStmt); } bool Delete() { TCHAR szSQL[256] = { 0, }; wsprintf(szSQL, _T("Delete from UserList where userid='aaa'")); if (SQLExecDirect(g_hStmt, szSQL, SQL_NTS) // SQL 명령어를 실행 == SQL_SUCCESS) { SQLCloseCursor(g_hStmt); Select(); return true; } SQLCloseCursor(g_hStmt); return false; } bool Update() { TCHAR szSQL[256] = { 0, }; wsprintf(szSQL, _T("Update UserList set userid='ccc' where userid='aaa'")); if (SQLExecDirect(g_hStmt, szSQL, SQL_NTS) // SQL 명령어를 실행 == SQL_SUCCESS) { SQLCloseCursor(g_hStmt); Select(); return true; } SQLCloseCursor(g_hStmt); return false; } // 오픈 데이타 베이스 void main() { // 분산을 잘해야한다. // 기본 포맷은 32비트 // 환경-> 연결 // 환경핸들은 부모가 NULL // 환경핸들 if (SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &g_hEnv) != SQL_SUCCESS) // 할당하고자하는 함수 { return; } if (SQLSetEnvAttr( g_hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, // 버전 SQL_IS_INTEGER) != SQL_SUCCESS) // 할당 받았으니 값을 넣어준다 세팅해준다. { return; } // 연결핸들 SQLAllocHandle(SQL_HANDLE_DBC, g_hEnv, &g_hDbc); SQLRETURN ret = SQLConnect(g_hDbc, (SQLTCHAR*)L"172.16.31.10", SQL_NTS, (SQLTCHAR*)L"sa", SQL_NTS, (SQLTCHAR*)L"kgca!@34", SQL_NTS); if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) { return; } while (1) { int iSelect; printf("\n0 : 출력 1: 추가 2: 삭제 3: 수정 \n"); scanf_s("%d", &iSelect); switch (iSelect) { case 0: Select(); break; case 1: Add(); break; case 2: Delete(); break; case 3: Update(); break; } } // 삭제 반대순서로 SQLFreeHandle(SQL_HANDLE_STMT, g_hStmt); SQLDisconnect(g_hDbc); // 연결을 끊어줘야한다. SQLFreeHandle(SQL_HANDLE_DBC, g_hDbc); SQLFreeHandle(SQL_HANDLE_ENV, g_hEnv); }<file_sep>#pragma once #include<iostream> //const char*p=0; // 비상수 포인터 , 상수 데이터 //char* const p =0; //상수 포인터, 비상수 데이터 //const char* const p=0; //상수 포인터, 상수 데이터 //void a() const {} // 함수에서 멤버 변수 값 변경 불가능 //const 함수에서는 const 함수만 호출가능. class TRegion { public: enum{POINT_POINT, POINT_SIZE};//시작점과 끝점, 시작점과 길이 int m_iWidth; int m_iHeight; private: //사각형 영역을 저장하기 위한 멤버변수들 int m_iLeft; //시작점의 x좌표 int m_iTop; //시작점의 y좌표 int m_iRight; //끝점의 x좌표 int m_iBottom; //끝점의 y좌표 //출력방식을 지정하기 위한 멤버변수 static int notation; //POINT_POINT또는 POINT_SIZE public: const TRegion* Get() const { return this; } const Tregion& GetRef() const { return *this; }//this ==자기를 칭하는 함수 //사각형 영역에 대한 정보를 얻는 함수들 const int GetLeft() { return m_iLeft; } const int GetTop() { return m_iTop; } const int* GetRight() { return &m_iRight; } const int& GetBottom() { return m_iBottom; } int GetWidth() const; //가로길이 얻기 const int GetHeight() const; //세로길이 얻기 void GetStartPoint(int &x, int &y)const; //시작점 얻기 void GetEndPoint(int &x, int &y)const; //끝점 얻기 void GetCenterPoint(int &x, int &y)const; //중심점 얻기 bool IsPointInRegion(int x, int y)const; //점이 영역 안에 있는지 // 사각형 영역을 설정하고 처리하는 함수들 void SetRect(int I, int t, int r, int b, ); //영역 설정 void Move(int x, int y); //위치 이동 void Resize(int width, int height); //크기 변경 void UnionRegion(const TRegion &r1, const TRegion &r2); // 합집합 bool IntersectRegion(const TRegion &r1, const TRegion &r2); // 교집합 // 사각형 영역을 표시하기 위한 함수들 void Show(void); //영역 출력 static void SetNotation(int notation); //출력 방식 public: TRegion(void); //생성자 TRegion(int I, int t, int r, int b); //생성자 }; <file_sep>#ifndef SPROTOCAL_HEADER #define SPROTOCAL_HEADER #include "SvrStd.h" #define PACKET_HEADER_SIZE 4 #pragma pack(push,1) typedef struct { WORD len; WORD type; }PACKET_HEADER; typedef struct { PACKET_HEADER ph; char msg[2048]; }UPACKET, *P_UPACKET; #pragma pack(pop) #endif<file_sep>#pragma once #include "SWorkThread.h" #include "SUser.h" #include "SSingleton.h" #define WORKDER_THREAD_COUNT 3 class SServerIOCP : public SSingleton<SServerIOCP>, public SServerObj { private: friend class SSingleton<SServerIOCP>; public: HANDLE m_hIOCP; SWorkThread m_WorkerThread[WORKDER_THREAD_COUNT]; public: bool Init(); bool Release(); void AddHandleToIOCP(HANDLE hClientSocket, ULONG_PTR dwReturnKey); public: SServerIOCP(void); virtual ~SServerIOCP(void); }; #define I_ServerIOCP SServerIOCP::GetInstance() <file_sep>#include "xiter.h" xiter::xiter() { } xiter::~xiter() { } <file_sep>#include "TEllipse.h" #include "TTriangle.h" #include "TRectangle.h" int main(void) { //TEllipse ellipse (30,20,50,20); //TTriangle triangle(10,10,20,30); //Trectangle rectangle(20,30,10,20); //ellipse.Draw(); //타원 그리기 //triangle.Draw(); //삼각형 그리기 //rectangle.Draw(); //사각형 그리기 const int FIGURES = 3; TFigure *figures[FIGURES] = { new TTriangle(10,10,20,30), new TTriangle(20,30,10,20), new TEllipse(30,20,50,20), }; for (int i = 0; i < FIGURES; i++) figures[i]->Draw(); //저장된 모든 도형 그리기 for (int i = 0; i < FIGURES; i++) delete figures[i]; return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <conio.h> void main() { int *pPoint = (int*)malloc(sizeof(int)); *pPoint = 100; printf("%0x¹øÁö:%d\n", pPoint + 0, *(pPoint + 0)); free(pPoint = 100); }<file_sep>#include "CCTimer.h" int g_iFPS;// 1초당 프레임 개수 float g_fSecPerFrame; //1프레임의 경과시간 float g_fAccumulation; // 실행된 경과 시간 // 클래스 멤버 변수 초기화 bool CCTimer::Init() { m_dwBeforeTick = timeGetTime(); ZeroMemory(m_csBuffer, sizeof(TCHAR)*MAX_PATH); return true; }; // 매 프레임에서 계산을 담당한다. bool CCTimer::Frame() { //1000==1초 (winmm.lib) DWORD dwCurrentTick = timeGetTime(); DWORD dwElapseTick = dwCurrentTick - m_dwBeforeTick; g_fSecPerFrame = m_fSecondPerFrame = dwElapseTick / 1000.0f; g_fAccumulation = m_fAccumulation += m_fSecondPerFrame; m_fFrameTime += m_fSecondPerFrame; if (m_fFrameTime > 1.0f) { g_iFPS = m_iFPS = m_dwFrameCnt; m_dwFrameCnt = 0; m_fFrameTime -= 1.0f; // _CRT_SECURE_NO_WARNINGS //_stprintf_s(m_csBuffer,L"Timer:[%10.4f]FPS:[%d] %f\n", // m_fAccumulation,m_iFPS,m_fSecondPerFrame); //OutputDebugString(m_csBuffer); } m_dwFrameCnt++; m_dwBeforeTick = dwCurrentTick; return true; } // 매 프레임에서 드로우를 담당한다. bool CCTimer::Render() { _stprintf_s(m_csBuffer, L"Timer:[%10.4f] FPS:[%d] %10.4f\n", m_fAccumulation, m_iFPS, m_fSecondPerFrame); //OutputDebugString return true; } bool CCTimer::Release() { return true; } CCTimer::CCTimer() { m_iFPS = 0;//1초당 프레임 개수 m_dwFrameCnt = 0; m_fSecondPerFrame = 0.0f; // 1프레임의 경과 시간 m_fAccumulation = 0.0f; // 실행된 경과 시간 m_fFrameTime = 0.0f; } CCTimer::~CCTimer() { } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <WinSock2.h> #include <Windows.h> #include <iostream> #pragma comment(lib,"ws2_32.lib") void Error(const char* msg) { LPVOID lpMsgBuffer; int iError = WSAGetLastError(); FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, iError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuffer, 0, NULL); printf("%s", lpMsgBuffer); LocalFree(lpMsgBuffer); exit(-1); } void main() { WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { return; } SOCKET sock = socket((AF_INET), SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) { Error("sock invalid"); } SOCKADDR_IN serveradd; ZeroMemory(&serveradd, sizeof(serveradd)); serveradd.sin_family = AF_INET; serveradd.sin_port = htons(9000); serveradd.sin_addr.s_addr = inet_addr("127.0.0.1"); //bind(sock,(SOCKADDR*)&serveradd,sizeof(serveradd)); SOCKADDR_IN clientAddr; char buf[256] = { 0, }; char recvbuf[256] = { 0, }; int addlen; int iCount = 0; while (1) { sprintf(buf, "%s:%d", "kgca", iCount++); int iRet = sendto(sock, buf, strlen(buf), 0,(SOCKADDR*)&serveradd, sizeof(serveradd)); if (iRet == SOCKET_ERROR) { Error("sock invalid"); } addlen = sizeof(clientAddr); iRet = recvfrom(sock, recvbuf, 256, 0, (SOCKADDR*)&clientAddr, &addlen); if (iRet = SOCKET_ERROR) { Error("sock invalid"); } recvbuf[iRet] = 0; printf("\n[%s:%d]:%s%s", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), recvbuf, recvbuf); // Sleep(1000); } WSACleanup(); }<file_sep>#include "TChatPacketPool.h" #include "TChatUser.h" #include "SDebugString.h" #include "TChatSvr.h" #include "TChatUser.h" void TChatPacketPool::ProcessWork(S_PACKET* pUserData) { UPACKET* pPacket = &(pUserData->packet); TChatUser* pUser = (TChatUser*)pUserData->pUser; switch(pPacket->ph.type) { case PACKET_USER_POSITION: { pUser->Movement(pPacket); I_Server.Broadcastting(pPacket, pUser->m_Socket ); }break; case PACKET_CHAR_NAME_ACK: { pUser->m_szName=pPacket->msg; char buffer[256] = {0,}; sprintf_s( buffer, "[%s]%s", pUser->m_szName.c_str(),"님이 입장하였습니다."); ZeroMemory(pPacket->msg, 2048); sprintf_s( pPacket->msg,"%s", buffer ); pPacket->ph.len = sizeof( PACKET_HEADER) + strlen(buffer); pPacket->ph.type = PACKET_CHAR_MSG; I_Server.Broadcastting(pPacket, pUser->m_Socket ); }break; case PACKET_CHAR_MSG: { I_Server.Broadcastting(pPacket,pUser->m_Socket); }break; } } TChatPacketPool::TChatPacketPool(void) { } TChatPacketPool::~TChatPacketPool(void) { } <file_sep>#include "xCore.h" #include "xMap.h" class Sample : public xCore { xMap m_map; xLineShape m_ObjLine; public: bool Init() { m_pMainCamera->SetViewMatrix( D3DXVECTOR3(0.0f, 300.0f, -300.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f)); m_ObjLine.Create(m_pd3dDevice, L"../../Include/data/shader/shape.hlsl", L"../../Include/data/eye.bmp"); xMapDesc desc = { 5, 5, 1.0f, 1.0f, L"../../Include/data/map/Tile40.jpg", L"../../Include/data/shader/map.hlsl", }; m_map.Init(); m_map.CreateHeightMap(m_pd3dDevice, m_pContext, L"../../Include/data/map/heightMap513.bmp"); desc.iNumRows = m_map.m_iNumRows; desc.iNumCols = m_map.m_iNumCols; desc.fScaleHeight = 1.0f; if (m_map.Load(m_pd3dDevice,desc)==false) { return false; } } bool Render() { m_map.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_map.Render(m_pContext); for (int iVertex = 0; iVertex < m_map.m_VertexList.size(); iVertex+=10000) { D3DXVECTOR3 vNormal = m_map.m_VertexList[iVertex].n; m_ObjLine.SetMatrix(NULL,&m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_ObjLine.Draw(m_pContext, m_map.m_VertexList[iVertex].p, m_map.m_VertexList[iVertex].p+vNormal*10.0f); } return true; } bool Release() { return m_map.Release(); } public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600) <file_sep>#pragma once #include "SUser.h" class SChatUser : public SUser { public: int m_iIndex; int m_PositionX; int m_PositionY; int m_iDirection; public: void Movement(UPACKET* pPacket); void AddPacket(S_PACKET& addPacket); void DeleteUser(SOCKET socket); void DeleteUser(); void Dispatch(DWORD dwByteSize, LPOVERLAPPED ov); public: SChatUser(void); virtual ~SChatUser(void); }; <file_sep>#include "x_Mesh.h" //HRESULT x_Mesh::CreateVertexData() //{ // return S_OK; //} //HRESULT x_Mesh::CreateIndexData() //{ // return S_OK; //} x_Mesh::x_Mesh() { } x_Mesh::~x_Mesh() { } <file_sep>#include "S_PacketPool.h" bool S_PacketPool::AddPacket(PACKET& addPacket) { { S_Lock Lock(this); m_PacketList.push_back(addPacket); } return true; } bool S_PacketPool::ProcessPacket() { { S_Lock Lock(this); list<PACKET>::iterator itor; for (itor = m_PacketList.begin(); itor != m_PacketList.end(); itor++) { PACKET* UserData = (PACKET*)&(*itor); ProcessWork(UserData); } m_PacketList.clear(); } return true; } void S_PacketPool::ProcessWork(PACKET* UserData) { } S_PacketPool::S_PacketPool() { } S_PacketPool::~S_PacketPool() { } <file_sep>#pragma once #include "DB_CONNECT.h" struct USERINFO { SQLTCHAR szSQL[256] = { 0, }; SQLTCHAR UserID[20] = { 0, }; SQLTCHAR UserPS[20] = { 0, }; SQLTCHAR NewUserID[20] = { 0, }; SQLTCHAR OldUserID[20] = { 0, }; }; class DB_MGR: public DB_CONNECT { public: HWND m_hList; public: bool Add(); bool Delete(); bool Update(); void Select(); void FindSelect(); //SQLRETURN HandleDiagnosticRecord(SQLHANDLE hHandle, SQLSMALLINT hType, RETCODE RetCode); public: DB_MGR(); virtual ~DB_MGR(); }; <file_sep>#pragma once #include "TThread.h" #include "TStreamPacket.h" class TPacketPool : public TServerObj { public: std::list<T_PACKET> m_PacketList; typedef std::list<T_PACKET>::iterator m_PackItor; public: virtual bool AddPacket(T_PACKET& addPacket); virtual bool ProcessPacket(); virtual void ProcessWork(T_PACKET* pUserData); public: TPacketPool(void); virtual ~TPacketPool(void); }; <file_sep>#include "SThread.h" unsigned int WINAPI SThread::HandleRunner(LPVOID parameter) { SThread* pThread = (SThread*)parameter; if (pThread) pThread->Run(); return 0; } bool SThread::Run() { return true; } void SThread::CreateThread() { if (m_bStarted == true)return; m_hThread = _beginthreadex( // 루틴을 시작하는 함수를 만든다. NULL, 0, HandleRunner, // 시작함수 (LPVOID)this, // 인자값 0, &m_iThreadID); // _beginthreadex 인자값 /*_In_opt_ void* _Security, _In_ unsigned _StackSize, _In_ _beginthreadex_proc_type _StartAddress, _In_opt_ void* _ArgList, _In_ unsigned _InitFlag, _Out_opt_ unsigned* _ThrdAddr*/ } SThread::SThread() { m_bStarted = false; // 기본을 false로 준다 } SThread::~SThread() { CloseHandle((HANDLE)m_hThread); // 쓰레드를 닫는다. } <file_sep>#include<stdio.h> #include<conio.h> //¹ØÀ¸·Î »ï°¢Çü void main() { for (int i = 0; i <= 5; i++) { for (int j = 0; j <= 5-i; j++) { printf("*"); } printf("\n"); }_getch(); }<file_sep>#include "TServer.h" bool TServer::SendMsg( SOCKET socket, char* msg, WORD code ) { UPACKET sendmsg; ZeroMemory( &sendmsg, sizeof(sendmsg)); //sprintf( sendmsg.msg, "%s", msg ); sprintf_s( sendmsg.msg, "%s", msg ); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(sendmsg.msg ); int iRet = send( socket, (char*)&sendmsg,sendmsg.ph.len, 0 ); if( iRet <= 0 ) { return false; } return true; } bool TServer::AddUser(SOCKET socket, SOCKADDR_IN address) { return true; } bool TServer::Init() { // 쓰레드 생성 CreateThread(); return true; } bool TServer::Run() { return true; } bool TServer::Release() { return true; } TServer::TServer(void) { } TServer::~TServer(void) { } <file_sep>#include <stdio.h> #include <conio.h> #include <stdlib.h> void main() { int arr[5], x; float farr[5]; double darr[5]; printf("\t\t Integer\t\tFloat\t\t Double"); for (x = 0; x < 5; x++) { printf("\nElement %d:\t%d\t\t%d\t\t%d", x, &arr[x], &farr[x], &darr[x]); } }<file_sep>#include "SServerIOCP.h" bool SServerIOCP::Init() { m_hIOCP = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, WORKDER_THREAD_COUNT); for (int iThread = 0; iThread < WORKDER_THREAD_COUNT; iThread++) { m_WorkerThread[iThread].CreateThread(); } return true; } bool SServerIOCP::Release() { return true; } void SServerIOCP::AddHandleToIOCP(HANDLE hClientSocket, ULONG_PTR dwReturnKey) { ::CreateIoCompletionPort(hClientSocket, m_hIOCP, dwReturnKey, 0); return; } SServerIOCP::SServerIOCP(void) { } SServerIOCP::~SServerIOCP(void) { } <file_sep>#include <stdio.h> void main() { char ch; ch = getchar(); putchar(ch); putchar('S'); putchar('\n'); putchar('\007'); putchar(getchar()); }<file_sep>#include<stdio.h> #include<stdlib.h> void main() { int item[100]; int count, a; printf("How many numbers?"); scanf_s("%d", &count); for (a = 0; a < count; a++) { scanf_s("%d", &item[a]); printf("%5.5f", mean(item, count)); } } //double mean(int item[], int n) //{ // int total = 0; // for (int i = 0; i < n; i++) // // total += item[i]; // // return double (total/n); //}<file_sep>#include "S_Viewer.h" #include "TObjMgr.h" bool S_Viewer::Init() { I_CharMgr.Init(); if(!I_CharMgr.Load(g_pd3dDevice, m_pContext,_T("CharacterTable.cit"))) { return false; } shared_ptr<S_HeroObj> pObjA = make_shared<S_HeroObj>(); pObjA->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR0"); pObjA->m_pBoneObject = pObjA->m_pChar->m_pBoneObject; pObjA->SetActionFrame(pObjA->m_pBoneObject->m_Scene.iFirstFrame, pObjA->m_pBoneObject->m_Scene.iLastFrame); m_HeroObj.push_back(pObjA); shared_ptr<S_HeroObj> pObjB = make_shared<S_HeroObj>(); pObjB->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR1"); if (pObjB->m_pChar) { pObjB->m_pBoneObject = pObjB->m_pChar->m_pBoneObject; pObjB->SetActionFrame(pObjB->m_pBoneObject->m_Scene.iFirstFrame, 60); m_HeroObj.push_back(pObjB); } shared_ptr<S_HeroObj> pObjC = make_shared<S_HeroObj>(); pObjC->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR1"); if (pObjC->m_pChar) { pObjC->m_pBoneObject = m_HeroObj[1]->m_pChar->m_pBoneObject; pObjC->SetActionFrame(61, 91); m_HeroObj.push_back(pObjC); } shared_ptr<S_HeroObj> pObjD = make_shared<S_HeroObj>(); pObjD->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR1"); if (pObjD->m_pChar) { pObjD->m_pBoneObject = m_HeroObj[1]->m_pChar->m_pBoneObject; pObjD->SetActionFrame(92, 116); m_HeroObj.push_back(pObjD); } shared_ptr<S_HeroObj> pObjE = make_shared<S_HeroObj>(); pObjE->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR2"); if (pObjE->m_pChar) { pObjE->m_pBoneObject = pObjE->m_pChar->m_pBoneObject; pObjE->SetActionFrame(pObjE->m_pBoneObject->m_Scene.iFirstFrame, pObjE->m_pBoneObject->m_Scene.iLastFrame); m_HeroObj.push_back(pObjE); } shared_ptr<S_HeroObj> pObjF = make_shared<S_HeroObj>(); pObjF->m_pChar = I_CharMgr.GetPtr(L"TEST_CHAR3"); if (pObjF->m_pChar) { pObjF->m_pBoneObject = pObjF->m_pChar->m_pBoneObject; pObjF->SetActionFrame(pObjF->m_pBoneObject->m_Scene.iFirstFrame, pObjF->m_pBoneObject->m_Scene.iLastFrame); m_HeroObj.push_back(pObjF); } //-------------------------------------------------------------------------------------- // 카메라 행렬 //-------------------------------------------------------------------------------------- m_pMainCamera = make_shared<xCamera>(); m_pMainCamera->SetViewMatrix(D3DXVECTOR3(-100.0f, 30.0f, -100.0f), D3DXVECTOR3(100.0f, 30.0f, 100.0f)); float fAspectRatio = 800 / (FLOAT)600; m_pMainCamera->SetProjMatrix(D3DX_PI / 4, fAspectRatio, 0.1f, 1000.0f); //m_pMainCamera->SetWindow(800, 600); return true; } bool S_Viewer::Render() { for (int iChar = 0; iChar < m_HeroObj.size(); iChar++) { m_matWorld._41 = -50.0f + iChar * 25.0f; m_HeroObj[iChar]->SetMatrix(&m_matWorld,&m_pMainCamera->m_matView,&m_pMainCamera->m_matProj); m_HeroObj[iChar]->Render(m_pContext); } return true; } bool S_Viewer::Release() { I_CharMgr.Release(); return true; } bool S_Viewer::Frame() { float t = m_Timer.GetElapsedTime() * D3DX_PI; //m_pMainCamera->Update(g_fSecPerFrame); m_pMainCamera->Frame(); m_matWorld = m_pMainCamera->m_matWorld; m_matWorld._41 = 0.0f; m_matWorld._42 = 0.0f; m_matWorld._43 = 0.0f; for (int iChar = 0; iChar < m_HeroObj.size(); iChar++) { if (I_Input.m_KeyState[DIK_ADD]) { m_HeroObj[iChar]->m_fSpeed += g_fSecPerFrame; } if (I_Input.m_KeyState[DIK_SUBTRACT]) { m_HeroObj[iChar]->m_fSpeed -= g_fSecPerFrame; if (m_HeroObj[iChar]->m_fSpeed < 0.0f) m_HeroObj[iChar]->m_fSpeed = 0.01f; } m_HeroObj[iChar]->Frame(); } if (I_Input.m_KeyState[DIK_F3] == KEY_UP && m_HeroObj.size() > 1) { m_HeroObj[1]->SetActionFrame(120, 205);//jump } if (I_Input.m_KeyState[DIK_F4] == KEY_UP && m_HeroObj.size() > 1) { m_HeroObj[1]->SetActionFrame(205, 289);//attack } if (I_Input.m_KeyState[DIK_F5] == KEY_UP) { for (int iChar = 0; iChar < m_HeroObj.size(); iChar++) { m_HeroObj[iChar]->m_bBoneRender = !m_HeroObj[iChar]->m_bBoneRender; } } return true; } HRESULT S_Viewer::CreateResource() { HRESULT hr; if (m_pMainCamera) { float fAspectRatio = m_sd.BufferDesc.Width / (float)m_sd.BufferDesc.Height; m_pMainCamera->SetProjMatrix(D3DX_PI / 4, fAspectRatio, 0.1f, 500.0f); } return S_OK; } HRESULT S_Viewer::DeleteResource() { HRESULT hr = S_OK; if (m_pContext)m_pContext->ClearState(); return S_OK; } S_Viewer::S_Viewer(void) { } S_Viewer::~S_Viewer(void) { } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow) { S_Viewer vie; vie.SetWindow(hInst, L"Viewer", 800, 600); vie.Run(); }<file_sep>#include<stdio.h> #include<conio.h> //while¹® //void main() //{ // int a = 1; // int total = 0; // // while (a < 100) // { // total += a; // a++; // } // printf("%d\n", total); //} //do~while¹® //void main() //{ // int yn; // do // { // print("Continue(Y/N)?"); // yn = getche(); // putchar('\n'); // } while (yn != 'Y'&&yn != 'N'); //}<file_sep>#include <stdio.h> #include <conio.h> //ÇǶó¹Ìµå void main() { for (int sum = 0; sum < 5; sum++) { for (int sum1 = 0; sum1 < 5-sum-1; sum1++) { printf(" "); } for (int sum2 = 0; sum2 <= sum*2; sum2++) { printf("*"); } printf("\n"); } _getch(); }<file_sep>#include "Core.h" class Sample : public Core { public: bool Init() { return true; } bool Frame() { if (I_Input.Key(VK_LBUTTON) == KEY_PUSH) { MessageBox(NULL, L"0", L"VK_LBUTTON", MB_OK); } SHORT sKey = GetAsyncKeyState(VK_LBUTTON); if (sKey & 0x8001) { MessageBox(NULL, L"1", L"m_dwMouseState", MB_OK); } DWORD dwState = I_Input.m_dwMouseState[0]; if (dwState == KEY_PUSH) { MessageBox(NULL, L"2", L"m_dwMouseState", MB_OK); } if (I_Input.m_dwMouseState[1] == KEY_PUSH) { //MessageBox(NULL, L"1", L"m_dwMouseState", MB_OK); } if (I_Input.m_dwMouseState[2] == KEY_PUSH) { //MessageBox(NULL, L"2", L"m_dwMouseState", MB_OK); } if (I_Input.Key(VK_END) == KEY_PUSH) { //MessageBox(NULL, L"KEY_PUSH", L"KEY", MB_OK); } if (I_Input.Key(VK_END) == KEY_HOLD) { //MessageBox(NULL, L"KEY_HOLD", L"KEY", MB_OK); } if (I_Input.Key(VK_END) == KEY_UP) { //MessageBox(NULL, L"KEY_UP", L"KEY", MB_OK); } bool bComboKey = I_Input.Key(VK_LCONTROL) == KEY_HOLD && I_Input.Key('p') == KEY_PUSH; if (bComboKey) { MessageBox(NULL, L"bComboKey+p", L"Mouse+Key", MB_OK); } return true; } bool Render() { return true; } bool Release() { return true; } public: Sample() {} ~Sample() {} }; GAME_RUN("SampleInput", 800, 600)<file_sep>#include "Window.h" GAME_RUN("WindowClass",800,600) //GAME_START //TWindow win; //win.Set(WS_POPUPWINDOW); //if (win.SetWindow(hInst)) //{ // win.Run(); //} //GAME_END<file_sep>#pragma once typedef basic_string<TCHAR> T_STR; typedef basic_string<CHAR> C_STR; template <class S> class SSingleton { public: static S& GetInstance() { static S theSingleInstance; return theSingleInstance; } };<file_sep>#include "sample.h" // 테스트 Sample::Sample(void) { } Sample::~Sample(void) { } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdshow) { Sample gSample; if (!gSample.InitWindow(hInstance, nCmdshow, L"CreateWindow")) { MessageBox(0, _T("CreateWindow 초기화 실패"), _T("Fatal error"), MB_OK); return 0; } ShowCursor(TRUE); gSample.Run(); return 1; }<file_sep>//퀵 정렬(Quick Sort) /*퀵 정렬은 재귀적인 방법으로 문제를 해결하는 알고리즘 피벗 값을 선택하여 피벗 값보다 작은 값들은 왼쪽으로 보내고 큰 값들은 오른쪽으로 보낸 후에 이들 사이에 피벗을 위치시키는 원리를 이용이후 피벗보다 작은 값들을 재귀 호출로 정렬하고 피벗보다 큰 값들도 재구호출로 정렬 하는 방식이다 주의 할 점으로는 퀵 정렬은 어떠한 요소를 피벗으로 선택하냐에 따라 성능에 차이가 생긴다. 만약 전체 요소의 중간 순위의 요소를 선택 하면재귀 호출에서 반씩나누어 정렬을 하게되어 좋은 성능을 발휘한다 반대로 가장 작은 값이나 가장 큰값을 피벗으로선택하면 최악의 성능을 발휘한다*/ #include <stdio.h> #include<conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 int *origin; int on; void QuickSort(int *base, int n); void ViewArr(int *arr, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; origin = arr; on = 10; ViewArr(arr, 10); QuickSort(arr, 10); ViewArr(arr, 10); _getch(); return 0; } void PrintSpace(int n); void QuickSort(int *base, int n) { int pivot = 0; // 피벗의 위치 기억하는 변수 int left = 0, right = 0; // 피벗보다 큰 값과 작은 값의 위치를 찾기위한 변수 if (n <= 1) { return; } left = 0; right = n; //퀵 소트는 피벗보다 작은 값들은 앞쪽으로 이동시키고 피벗보다 큰 값들은 뒤쪽으로 이동시켜서 //작은 값들과 큰 값들 사이에 피벗을 보내는 것이 기본 동작입니다. //그리고 난 후에 작은 값들이 있는 배열을 재귀적으로 다시 정렬하고 //큰 값들이 있는 배열을 재귀적으로 다시 정렬하는 알고리즘입니다. while (1) { //앞쪽에 피벗(인덱스 0에 있는 원소)보다 큰 값을 만날 때까지 left를 이동합니다. //for문 맨 앞의 left를 1 증가하면서 출발하는 이유는 이전에 끝난 다음 위치부터 시작하기 위해서입니다. for (left++; (left<n) && (base[0] >= base[left]); left++); //뒤쪽에 피벗(인덱스 0에 있는 원소)보다 작은 값을 만날 때까지 right를 이동합니다. for (right--; (right>0) && (base[0]<base[right]); right--); //만약 left가 right보다 작다면 피벗과 비교했을 때 작은 값이 큰 값보다 뒤에 있으니 교환합니다. if (left<right) { SWAP(base[left], base[right]); PrintSpace(base - origin); ViewArr(base, n); } //그렇지 않다면 피벗을 중심으로 작은 값들과 큰 값들이 분리 작업이 끝난 것입니다. else { break; } } //이제 피벗을 작은 값들과 큰 값들 사이로 보냅니다. SWAP(base[0], base[right]); PrintSpace(base - origin); ViewArr(base, n); //피벗보다 작은 값들이 있는 앞쪽을 재귀 호출로 정렬합니다. QuickSort(base, right); //피벗보다 큰 값들이 있는 뒤쪽을 재귀 호출로 정렬합니다. QuickSort(base + left, n - left); } void PrintSpace(int n) { int i = 0; for (i = 0; i<n; i++) { printf(" "); } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#include <stdio.h> void main() { int i; int j=0; int k; { scanf_s("%d", &k); for (i = 0; i <= k; i++) j += i; printf("%d", j); } }<file_sep>#pragma once #include "SServer.h" #include "TChatPacketPool.h" #include "TChatAccept.h" #include "TChatUser.h" class TChatSvr : public SSingleton<TChatSvr>, public SServer { private: friend class SSingleton<TChatSvr>; public: TChatPacketPool m_PacketPool; TChatAccept m_Acceptor; ////////////// 유저 리스트 /////////////////// std::list<TChatUser*> m_UserList; typedef std::list<TChatUser*>::iterator m_ListItor; int m_iUserCount; public: bool Init(); bool Release(); bool Run(); LRESULT MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void Print( char* fmt, ... ); bool AddUser(SOCKET socket, SOCKADDR_IN address); void DeleteUser( SOCKET socket ); void DeleteUser( TChatUser* pUser ); void Broadcastting( char* msg, WORD code, SOCKET SendSocket=0 ); void Broadcastting( S_PACKET* pUserData ); void Broadcastting( UPACKET* pPacket, SOCKET pSendUser=NULL ); public: TChatSvr(void); ~TChatSvr(void); }; #define I_Server TChatSvr::GetInstance() <file_sep>#include "Core.h" class Sample : public Core { public: Sample() {} ~Sample() {} }; GAME_RUN("SampleTimer", 800,600)<file_sep>#pragma once #include "SStudent.h" class LinkedList { public: void Insert(); void Delete(); void Delete(Node*_preNode); void Find(); void Insert(Node* _newNode); Node* Head; Node* Tail; int MAX; void printAll(); void save(); void Load(); Node* cur; public: LinkedList(); ~LinkedList(); }; <file_sep>#include "TClient.h" #include "SLock.h" #include "SDebugString.h" unsigned __stdcall sendMessage( void * arg ) { I_Debug.Print("%s", "send 스레드 시작" ); TClient* pClient = (TClient*)arg; while(!pClient->m_bExit) { if( pClient->m_bLoginOK && pClient->m_bSend ) { if( pClient->SendMsg(pClient->m_strBuffer,PACKET_CHAT_MSG ) <= 0 ) { break; } pClient->m_bSend = false; } if( SwitchToThread() == FALSE ) { Sleep(1); // Sleep(0)은 동일한 우선순위 스레드 스위칭 되지만 // Sleep(1)은 서로 다른 우선순위 스레드에서도 스위칭이 된다. } } return 0; } unsigned __stdcall receiveMessage( void * arg ) { I_Debug.Print("%s", "receive 스레드 시작" ); TClient* pClient = (TClient*)arg; int iSocket = pClient->m_iSocket; char strBuffer[2048]= {0,}; while(!pClient->m_bExit) { int iRet = recv( iSocket, strBuffer, sizeof(strBuffer), 0); if( iRet <= 0 ) { //비동기 소켓 if( WSAGetLastError() == WSAEWOULDBLOCK ) { continue; } pClient->m_bExit = true; closesocket(pClient->m_iSocket); break; } strBuffer[iRet] = 0; pClient->m_StreamPacket.Put( strBuffer, iRet, pClient); // Sleep(1) 또는 SwitchToThread()를 사용하면 // 우선순위가 낮은 스레드에도 스위칭이 가능하다. if( SwitchToThread() == FALSE ) { Sleep(1); } } return 0; } // 완성된 패킷에 대한 처리 int TClient::ProcessPacket() { { SLock sync(this); std::list<S_PACKET>::iterator iter; for (iter = m_StreamPacket.m_PacketList.begin(); iter != m_StreamPacket.m_PacketList.end(); iter++) { UPACKET* pPacket = &(*iter).packet; switch (pPacket->ph.type) { case PACKET_USER_POSITION: { TPACKET_USER_POSITION user; memcpy(&user, pPacket->msg, sizeof(char)* pPacket->ph.len - 4); if (user.direction == VK_DOWN) { // user.x += 10 * g_fSecPerfame; int kkkk = 0; } if (user.direction == VK_LEFT) { // user.x += 10 * g_fSecPerfame; int kkkk = 0; } if (user.direction == VK_RIGHT) { // user.x += 10 * g_fSecPerfame; int kkkk = 0; } if (user.direction == VK_UP) { // user.x += 10 * g_fSecPerfame; int kkkk = 0; } }break; case PACKET_CHAT_NAME_REQ: { I_Debug.Print("%s", pPacket->msg); }break; case PACKET_CHAT_MSG: { I_Debug.Print("%s", pPacket->msg); }break; } } m_StreamPacket.m_PacketList.clear(); } return 1; } int TClient::SendMsg( char* pMsg, WORD code ) { UPACKET sendmsg; ZeroMemory( &sendmsg, sizeof(sendmsg) ); sprintf_s(sendmsg.msg, pMsg); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + strlen(sendmsg.msg); int iRet = send( m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if( iRet <= 0 ) { m_bSend = false; //비동기 소켓 if( WSAGetLastError() == WSAEWOULDBLOCK ) { return 1; } return 0; } m_bSend = false; return 1; } int TClient::SendMsg( char* pMsg, int iSize, WORD code ) { UPACKET sendmsg; ZeroMemory( &sendmsg, sizeof(sendmsg) ); //sprintf(sendmsg.msg, pMsg); memcpy( sendmsg.msg, pMsg, iSize ); sendmsg.ph.type = code; sendmsg.ph.len = sizeof(PACKET_HEADER) + iSize; int iRet = send( m_iSocket, (char*)&sendmsg, sendmsg.ph.len, 0); if( iRet <= 0 ) { m_bSend = false; //비동기 소켓 if( WSAGetLastError() == WSAEWOULDBLOCK ) { return 1; } return 0; } m_bSend = false; return 1; } int TClient::CreateConnectSocket( int iPort) { int rv; m_iSocket = socket( AF_INET, SOCK_STREAM, 0 ); if( m_iSocket == INVALID_SOCKET ) { return -1; } SOCKADDR_IN serveraddr; ZeroMemory( &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr= inet_addr("172.16.17.32"); serveraddr.sin_port = htons(iPort); rv = connect(m_iSocket,(sockaddr*)&serveraddr, sizeof(serveraddr)); if( rv == SOCKET_ERROR ) { return -1; } //struct linger //{ // int l_onoff; //linger 옵션 사용여부 // int l_linger; //linger time //} linger optval; int iLength = sizeof(optval); getsockopt(m_iSocket, SOL_SOCKET, SO_LINGER,(char*)&optval, &iLength ); optval.l_onoff = 1; optval.l_linger = 1000; setsockopt(m_iSocket, SOL_SOCKET,SO_LINGER,(char*)&optval, iLength ); int socketType1; int typeLen1=sizeof(socketType1); getsockopt(m_iSocket, SOL_SOCKET, SO_TYPE, (char*)&socketType1,&typeLen1); if(socketType1==SOCK_STREAM) I_Debug.Print("%s", "SOCK_STREAM." ); else I_Debug.Print("%s", "SOCK_DGRAM" ); getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1,&typeLen1); I_Debug.Print("%s=%d","SO_SNDBUF",socketType1 ); getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1,&typeLen1); I_Debug.Print("%s=%d", "SO_RCVBUF",socketType1 ); //////////////////////////////////////// 주의 ///////////////////////////////// //비동기 소켓의 경우에 스레드의 루틴이 무한 반복될 수 있기 때문에 //테스트를 하기 위해서 다수의 클라이언트 프로그램을 뛰우면 성능이 심각하게 저하된다. // If iMode = 0, blocking is enabled; // If iMode != 0, non-blocking mode is enabled. //int iMode = 1; //ioctlsocket(m_iSocket, FIONBIO, (u_long FAR*) &iMode); return 0; } bool TClient::Init() { int rv; WSADATA wsa; if( WSAStartup( MAKEWORD(2,2), &wsa ) != 0 ) { return -1; } if( CreateConnectSocket( 10000 ) == 0 ) { // send thread unsigned sendThread, receiveThread; m_hSendThread = _beginthreadex( NULL, 0, sendMessage,(void*)this, 0, &sendThread); // recv thread m_hReceiveThread = _beginthreadex( NULL, 0, receiveMessage, (void*)this, 0, &receiveThread); int iLevelSend = GetThreadPriority(HANDLE(m_hSendThread)); int iLevelRecv = GetThreadPriority(HANDLE(m_hReceiveThread)); if(SetThreadPriority( HANDLE(m_hReceiveThread), THREAD_PRIORITY_ABOVE_NORMAL == TRUE)) { iLevelRecv = GetThreadPriority(HANDLE(m_hReceiveThread)); INT KKKK = 0; }; m_bLoginOK = true; } return true; } bool TClient::Frame() { if( m_bExit ) { I_Debug.Print("%s", "서버가 종료되었습니다." ); m_bExit = false; } return true; } bool TClient::Release() { m_bExit = true; closesocket( m_iSocket ); // send exit wait WaitForSingleObject((HANDLE)m_hSendThread, INFINITE ); // rect exit wait WaitForSingleObject((HANDLE)m_hReceiveThread, INFINITE ); //TerminateThread( (HANDLE)m_hReceiveThread, 0); WSACleanup(); CloseHandle( HANDLE(m_hReceiveThread) ); CloseHandle( HANDLE(m_hSendThread) ); m_hReceiveThread = NULL; m_hSendThread = NULL; return true; } TClient::TClient(void) { m_bSend = false; m_bLoginOK = false; m_bExit = false; m_iSocket = 0; m_hReceiveThread=0; m_hSendThread=0; } TClient::~TClient(void) { } <file_sep>#include "SStreamPacket.h" #include "SServer.h" #include "SLock.h" void SStreamPacket::Put(char* recvBuffer, int iRecvSize, SUser* pUser) { { SLock lock(this); // 받는 버퍼의 용량이 부족하면 if (m_iWritePos + iRecvSize >= MAX_RECV_SIZE) { char strTemp[MAX_RECV_SIZE] = { 0, }; memcpy(strTemp, &m_RecvBuffer[m_iStartPos], m_iReadPos); ZeroMemory(&m_RecvBuffer, sizeof(char)* MAX_RECV_SIZE); memcpy(&m_RecvBuffer, &strTemp, m_iReadPos); m_pPacket = (P_UPACKET)m_RecvBuffer; m_iStartPos = 0; m_iWritePos = m_iReadPos; } memcpy(&m_RecvBuffer[m_iWritePos], recvBuffer, iRecvSize); m_iWritePos += iRecvSize; m_iReadPos += iRecvSize; if (m_iReadPos < PACKET_HEADER_SIZE)return; // 패킷의 시작 m_pPacket = (P_UPACKET)&m_RecvBuffer[m_iStartPos]; // 1개의 패킷 사이즈만큼 받았다면 if (m_iReadPos >= m_pPacket->ph.len) { do { S_PACKET add; ZeroMemory(&add, sizeof(add)); memcpy(&add.packet, &m_RecvBuffer[m_iStartPos], m_pPacket->ph.len); add.pUser = pUser; if (pUser != NULL) { pUser->AddPacket(add); } // 1개의 패킷을 처리하고 남은 잔여량 크기 m_iReadPos -= m_pPacket->ph.len; // 패킷의 시작 위치 m_iStartPos += m_pPacket->ph.len; // 잔여량이 패킷 헤더보다 작을 경우 if (m_iReadPos < PACKET_HEADER_SIZE)break; m_pPacket = (P_UPACKET)&m_RecvBuffer[m_iStartPos]; } while (m_iReadPos >= m_pPacket->ph.len); } } }; SStreamPacket::SStreamPacket() { ZeroMemory(m_RecvBuffer, sizeof(char)*MAX_RECV_SIZE); m_iStartPos = 0; m_iWritePos = 0; m_iReadPos = 0; m_pPacket = NULL; } SStreamPacket::~SStreamPacket() { } <file_sep>#include<stdio.h> #include<conio.h> void swap(int *a,int *b) { int i = *a; int j = *b; *a = j; *b = i; } void main() { int a = 3; int b = 5; swap(&a, &b); printf("%d %d", &a, &b); }<file_sep>#pragma once #define _DISABLE_EXTENDED_ALIGNED_STORAGE //#include <d3d11_1.h> #include <d3dx11.h> #ifdef NO_TOOL_LIBRARY #include <dxgi1_2.h> #endif #include <dxgi.h> #include <D3Dcompiler.h> #include <d2d1.h> #include <d2d1helper.h> #include <dwrite.h> #include <d3dx10math.h> #include <DirectXMath.h> #include "TMath.h" #pragma comment( lib, "dxguid.lib" ) #pragma comment( lib, "dxgi.lib" ) #pragma comment( lib, "d3d11.lib" ) #if defined(DEBUG) || defined(_DEBUG) #pragma comment( lib, "d3dx10d.lib" ) #pragma comment( lib, "d3dx11d.lib" ) #else #pragma comment( lib, "d3dx10.lib" ) #pragma comment( lib, "d3dx11.lib" ) #endif #pragma comment( lib, "d3dcompiler.lib" ) #pragma comment( lib, "d2d1.lib" ) #pragma comment( lib, "dwrite.lib" ) //namespace TBASIS //{ extern ID3D11Device* g_pd3dDevice; extern ID3D11DeviceContext* g_pImmediateContext; //} #if defined(DEBUG) | defined(_DEBUG) #ifndef H_RETURN #define H_RETURN(x){ if (FAILED(x)){\ LPWSTR output;\ WCHAR buffer[256]={0,};\ FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS |FORMAT_MESSAGE_ALLOCATE_BUFFER,\ NULL,x,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR)&output,0,NULL);\ wsprintf(buffer,L"File=%s\nLine=%s", xstr(__FILE__),xstr(__LINE__));\ MessageBox(NULL, buffer,output,MB_OK); return hr;}\ } #endif #ifndef H #define H(x){ if (FAILED(x)){\ LPWSTR output;\ WCHAR buffer[256]={0,};\ FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS |FORMAT_MESSAGE_ALLOCATE_BUFFER,\ NULL,x,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR)&output,0,NULL);\ wsprintf(buffer,L"File=%s\nLine=%s", xstr(__FILE__),xstr(__LINE__));\ MessageBox(NULL, buffer,output,MB_OK);}\ } #endif #else #ifndef H_RETURN #define H_RETURN(x) (x) #endif #ifndef H #define H(x) (x) #endif #endif #ifndef V #define V(x) { hr = (x); } #endif #ifndef V_RETURN #define V_RETURN(x){ hr = (x); if( FAILED(hr) ) { return hr; } } #endif<file_sep>#include "S_Writer.h" struct DescendingDateSort { bool operator()(STri& rpStart, STri& rpEnd) { return rpStart.iSubIndex < rpEnd.iSubIndex; } }; static int g_iSearchIndex = 0; struct IsSameInt { bool operator()(STri& value) { return value.iSubIndex == g_iSearchIndex; } }; void S_Writer::matExport() { m_strFileName = I_Writer.SaveFileDlg(_T("mat"), _T("SMatrixExport")); FILE *fp; fp = _tfopen(m_strFileName, _T("wb")); if (!fp) { MessageBox(NULL, m_strFileName, _T("출력파일을 생성하지 못했습니다.Faild"), MB_OK); return; } struct tm *newtime; time_t aclock; time(&aclock); newtime = localtime(&aclock); fwrite(newtime, sizeof(tm), 1, fp); SScene scene = m_Scene; scene.iNumMesh = m_MatrixMap.Count(); fwrite(&scene, sizeof(SScene), 1, fp); for (DWORD iBiped = 0; iBiped < m_MatrixMap.Count(); iBiped++) { MATRIXINDEX *pPoint = (MATRIXINDEX*)m_MatrixMap.TMap[iBiped]; INode* pNode = pPoint->m_pINode; Matrix3 m_pAnimTm; D3D_MATRIX m_pAnimation; for (int iFrame = m_Scene.iFirstFrame; iFrame < m_Scene.iLastFrame; iFrame++) { TimeValue iTime = iFrame * m_Scene.iTickPerFrame; Matrix3 m_pAnimTm = pNode->GetNodeTM(iTime); DumpMatrix3(&m_pAnimTm, m_pAnimation); fwrite(&m_pAnimation, sizeof(D3D_MATRIX), 1, fp); } } for (DWORD iBiped = 0; iBiped < m_MatrixMap.Count(); iBiped++) { MATRIXINDEX *pPoint = (MATRIXINDEX*)m_MatrixMap.GetPtr(iBiped); INode* pNode = pPoint->m_pINode; TimeValue t = this->m_Interval.Start(); if (pPoint->m_ClassType == CLASS_BIPED || pPoint->m_ClassType == CLASS_GEOM) { BOOL needDel; TriObject *tri = GetTriObjectFromNode(pPoint->m_pINode, t, needDel); if (tri != NULL) { Matrix3 tm = pPoint->m_pINode->GetObjTMAfterWSM(t); Mesh *mesh = &tri->GetMesh(); mesh->buildNormals(); pPoint->m_VertexList.resize(mesh->getNumFaces() * 3); for (int iFace = 0; iFace < mesh->getNumFaces(); iFace++) { for (int iVertex = 0; iVertex < 3; iVertex++) { P3NCVERTEX vVertex; Point3 v; if (iVertex == 0) v = tm * mesh->verts[mesh->faces[iFace].v[0]]; else if (iVertex == 1) v = tm * mesh->verts[mesh->faces[iFace].v[2]]; else v = tm * mesh->verts[mesh->faces[iFace].v[1]]; vVertex.Px = v.x; vVertex.Py = v.z; vVertex.pz = v.y; pPoint->m_VertexList[iFace * 3 + iVertex] = vVertex; } } } } else if (pPoint->m_ClassType == CLASS_BONE || pPoint->m_ClassType == CLASS_DUMMY) { Object* helperObj = pPoint->m_pObj; Matrix3 oTM = pPoint->m_pINode->GetObjectTM(t); Box3 bbox; helperObj->GetDeformBBox(t, bbox, &oTM); bbox.pmax = bbox.pmax * Inverse(pPoint->m_pINode->GetNodeTM(m_Interval.Start())); bbox.pmin = bbox.pmin * Inverse(pPoint->m_pINode->GetNodeTM(m_Interval.Start())); P3NCVERTEX vVertex[2]; memset(vVertex, 0, sizeof(P3NCVERTEX) * 2); vVertex[0].Px = bbox.pmax.x; vVertex[0].Py = bbox.pmax.z; vVertex[0].pz = bbox.pmax.y; vVertex[1].Px = bbox.pmax.x; vVertex[1].Py = bbox.pmax.z; vVertex[1].pz = bbox.pmax.y; vVertex[0].c = Point4(1.0f, 1.0f, 0.0f, 0.0f); vVertex[1].c = Point4(1.0f, 1.0f, 0.0f, 0.0f); pPoint->m_VertexList.push_back(vVertex[0]); pPoint->m_VertexList.push_back(vVertex[1]); } int iLen = pPoint->m_szName.size(); fwrite(&pPoint->m_ClassType, sizeof(int), 1, fp); fwrite(&iLen, sizeof(int), 1, fp); fwrite(pPoint->m_szName.c_str(), sizeof(TCHAR) * iLen, 1, fp); D3D_MATRIX matWorld; DumpMatrix3(&pPoint->m_pINode->GetNodeTM(t), matWorld); fwrite(&matWorld, sizeof(D3D_MATRIX), 1, fp); int iCount = pPoint->m_VertexList.size(); fwrite(&iCount, sizeof(int), 1, fp); for (int iVertex = 0; iVertex < pPoint->m_VertexList.size(); iVertex++) { fwrite(&pPoint->m_VertexList[iVertex], sizeof(P3NCVERTEX), 1, fp); } } fclose(fp); MessageBox(NULL, m_strFileName, _T("Succeed!!"), MB_OK); return; } bool S_Writer::Init(TSTR strFileName, Interface* pMax) { m_strFileName = strFileName; return Initialize(pMax); } TCHAR* S_Writer::SaveFileDlg(TCHAR* szExt, TCHAR* szTitle) { OPENFILENAME ofn; TCHAR szFile[256], szFileTitle[256]; static TCHAR * szFilter; ZeroMemory(&ofn, sizeof(OPENFILENAME)); _tcscpy_s(szFile, _T("*.")); _tcscat_s(szFile, szExt); _tcscat_s(szFile, _T("\0")); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = GetActiveWindow(); ofn.lpstrFilter = szFilter; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0L; ofn.nFilterIndex = 1; ofn.lpstrFile = szFile; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = sizeof(szFileTitle); ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = szTitle; ofn.Flags = 0L; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = szExt; if (!GetSaveFileName(&ofn)) { return NULL; } return szFile; } bool S_Writer::KHJExport() { GetMaterial(); UpdateObject(); TCHAR szFile[256] = { 0, }; _tcscpy(szFile, I_Writer.SaveFileDlg(_T("KHJ"), _T("KHJExpoter"))); m_pStream = _tfopen(szFile, _T("wt")); if (!m_pStream) { return 0; } ExpScene(); ExpMaterial(); ExpObject(); fclose(m_pStream); MessageBox(GetActiveWindow(), szFile, _T("Succeed!!"), MB_OK); return true; } bool S_Writer::Release() { m_pMtlList.clear(); m_MatrixMap.Release(); return true; } void S_Writer::ExpScene() { struct tm* newtime; time_t aclock; time(&aclock); newtime = localtime(&aclock); TSTR today = _tasctime(newtime); today.remove(today.length() - 1); _ftprintf(m_pStream, _T("%s %s\n"), _T("#TBF_FILE_EXPORT"), FixupName(today)); _ftprintf(m_pStream, _T("%s\n"), _T("#SCENE")); _ftprintf(m_pStream, _T("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d"), m_Scene.iVersion, m_Scene.iFirstFrame, m_Scene.iLastFrame, m_Scene.iFrameSpeed, m_Scene.iTickPerFrame, m_Scene.iNumMesh, m_Scene.iMaxWeight, m_Scene.iBindPose); } void S_Writer::ExpMaterial() { _ftprintf(m_pStream, _T("\n%s\t%d"), _T("#ROOT_MATERIAL"), m_Material.size()); for (int IRootMtl = 0; IRootMtl < m_Material.size(); IRootMtl++) { _ftprintf(m_pStream, _T("\n%s %d\n"), _T("#MATERIAL"), m_Material[IRootMtl].iIndex); if (!m_Material[IRootMtl].strName.isNull()) _ftprintf(m_pStream, _T("\t%s"), m_Material[IRootMtl].strName); else _ftprintf(m_pStream, _T("\t%s"), _T("NULL")); if (!m_Material[IRootMtl].strClassname.isNull()) _ftprintf(m_pStream, _T("\t%s"), m_Material[IRootMtl].strClassname); else _ftprintf(m_pStream, _T("\t%s"), _T("NULL")); _ftprintf(m_pStream, _T("\t%d"), m_Material[IRootMtl].iNumSubMtl); if (m_Material[IRootMtl].iNumSubMtl > 0) { _ftprintf(m_pStream, _T("\t%d"), m_Material[IRootMtl].TexMaps.size()); for (int iSubMtl = 0; iSubMtl < m_Material[IRootMtl].iNumSubMtl; iSubMtl++) { _ftprintf(m_pStream, _T("\n\t%s %d"), _T("#SUBMATERIAL"), m_Material[IRootMtl].SubMaterial[iSubMtl].iIndex); if (!m_Material[IRootMtl].SubMaterial[iSubMtl].strName.isNull()) _ftprintf(m_pStream, _T("\n\t\t%s"), m_Material[IRootMtl].SubMaterial[iSubMtl].strName); else _ftprintf(m_pStream, _T("\t%s"), _T("NULL")); if (!m_Material[IRootMtl].SubMaterial[iSubMtl].strClassname.isNull()) _ftprintf(m_pStream, _T("\t%s"), m_Material[IRootMtl].SubMaterial[iSubMtl].strClassname); else _ftprintf(m_pStream, _T("\t%s"), _T("NULL")); _ftprintf(m_pStream, _T("\t%d"), m_Material[IRootMtl].SubMaterial[iSubMtl].iNumSubMtl); ExpTexture(m_Material[IRootMtl].SubMaterial[iSubMtl].TexMaps); } } else { ExpTexture(m_Material[IRootMtl].TexMaps); } } } void S_Writer::ExpTexture(vector<STexMap>& TexMap) { _ftprintf(m_pStream, _T("\t%d"), TexMap.size()); for (int iTexMap = 0; iTexMap < TexMap.size(); iTexMap++) { if (!TexMap[iTexMap].strTextureName.isNull()) { _ftprintf(m_pStream, _T("\n\t\t%d\t%s"), TexMap[iTexMap].iType, TexMap[iTexMap].strTextureName); } else { _ftprintf(m_pStream, _T("\t\t%d\t%s"), TexMap[iTexMap].iType, _T("NULL")); } } } int S_Writer::IsEqulVertexList(vector<PNCT_VERTEX>& VertexArray, PNCT_VERTEX& Vertex) { for (int iVertex = 0; iVertex < VertexArray.size(); iVertex++) { if (EqualPoint3(VertexArray[iVertex].p, Vertex.p) && EqualPoint3(VertexArray[iVertex].n, Vertex.n) && EqualPoint4(VertexArray[iVertex].c, Vertex.c) && EqualPoint2(VertexArray[iVertex].t, Vertex.t)) { return iVertex; } } return -1; } int S_Writer::SetUniqueBuffer(SMesh* pMesh, int iMtrl, int iStartTri, vector <PNCT_VERTEX>& VertexArray, vector<int>& IndexArray) { int iNumFaces = pMesh->m_TriList.size(); if (iMtrl >= 0) { g_iSearchIndex = iMtrl; iNumFaces = count_if(pMesh->m_TriList.begin(), pMesh->m_TriList.end(), IsSameInt()); } int iPosPushCnt = 0; for (int iFace = 0; iFace < iNumFaces; iFace++) { for (int iCnt = 0; iCnt < 3; iCnt++) { int iPosReturn = IsEqulVertexList(VertexArray, pMesh->m_TriList[iStartTri + iFace].v[iCnt]); if (iPosReturn < 0) { VertexArray.push_back(pMesh->m_TriList[iStartTri + iFace].v[iCnt]); iPosReturn = iPosPushCnt++; } IndexArray.push_back(iPosReturn); } } return iNumFaces; } void S_Writer::ExpObject() { for (int iMesh = 0; iMesh < m_MatrixMap.Count(); iMesh++) { MATRIXINDEX *pPoint = (MATRIXINDEX *)m_MatrixMap.TMap[iMesh]; SMesh* pMesh = &pPoint->m_tMesh; _ftprintf(m_pStream, _T("\n%s %d"), _T("#OBJECTS"), iMesh); _ftprintf(m_pStream, _T("\n%s %s"), pMesh->m_strNodeName, pMesh->m_strParentName); _ftprintf(m_pStream, _T("\n%d\t%d\t%d\t%d\t%d\t%d\t%d\n"), pMesh->m_ClassType, pMesh->m_iNumFace, pMesh->m_PosTrack.size(), pMesh->m_RotTrack.size(), pMesh->m_SclTrack.size(), pMesh->m_VisTrack.size(), pMesh->m_iMtrlRef); _ftprintf(m_pStream, _T("\t%f %f %f\t%f %f %f\n"), pMesh->m_Box.pmax.x, pMesh->m_Box.pmax.y, pMesh->m_Box.pmax.z, pMesh->m_Box.pmin.x, pMesh->m_Box.pmin.y, pMesh->m_Box.pmin.z); _ftprintf(m_pStream, _T("\t%s\n"), _T("#WORLD_MATRIX")); _ftprintf(m_pStream, _T("\t%10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_matWorld._11, pMesh->m_matWorld._12, pMesh->m_matWorld._13, pMesh->m_matWorld._14); _ftprintf(m_pStream, _T("\t%10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_matWorld._21, pMesh->m_matWorld._22, pMesh->m_matWorld._23, pMesh->m_matWorld._24); _ftprintf(m_pStream, _T("\t%10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_matWorld._31, pMesh->m_matWorld._32, pMesh->m_matWorld._33, pMesh->m_matWorld._34); _ftprintf(m_pStream, _T("\t%10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_matWorld._41, pMesh->m_matWorld._42, pMesh->m_matWorld._43, pMesh->m_matWorld._44); _ftprintf(m_pStream, _T("\t%s\n"), _T("#TRAINGLES")); std::sort(pMesh->m_TriList.begin(), pMesh->m_TriList.end(), DescendingDateSort()); int iAddCount = 0; // 서브매터리얼을 사용할 경우 if (pMesh->m_iMtrlRef >= 0 && m_Material[pMesh->m_iMtrlRef].iNumSubMtl > 0) { for (int iMtrl = 0; iMtrl < m_Material[pMesh->m_iMtrlRef].iNumSubMtl; iMtrl++) { iAddCount += ExpMesh(m_pStream, pMesh, iMtrl, iAddCount); } } else { ExpMesh(m_pStream, pMesh, -1, 0); } // 에니메이션 정보 출력 ExpAnimation(pMesh); } } int S_Writer::ExpMesh(FILE* fp, SMesh* pMesh, int iMtrl, int iAddCount) { vector <PNCT_VERTEX> VertexArray; vector <int> IndexArray; int iNumFaces = SetUniqueBuffer(pMesh, iMtrl, iAddCount, VertexArray, IndexArray); _ftprintf(fp, _T("\t%d \t%d %d\n"), iMtrl, iNumFaces, VertexArray.size()); for (int iCnt = 0; iCnt < VertexArray.size(); iCnt++) { _ftprintf(fp, _T("\t%10.4f %10.4f %10.4f\t%10.4f %10.4f %10.4f \t %10.4f %10.4f %10.4f %10.4f \t%10.4f %10.4f\n"), VertexArray[iCnt].p.x, VertexArray[iCnt].p.y, VertexArray[iCnt].p.z, VertexArray[iCnt].n.x, VertexArray[iCnt].n.y, VertexArray[iCnt].n.z, VertexArray[iCnt].c.x, VertexArray[iCnt].c.y, VertexArray[iCnt].c.z, VertexArray[iCnt].c.w, VertexArray[iCnt].t.x, VertexArray[iCnt].t.y); } for (int iIndex = 0; iIndex < IndexArray.size(); iIndex += 3) { _ftprintf(fp, _T("\t%d %d %d\n"), IndexArray[iIndex + 0], IndexArray[iIndex + 1], IndexArray[iIndex + 2]); } return iNumFaces; } void S_Writer::ExpAnimation(SMesh* pMesh) { if (pMesh->m_PosTrack.size() > 0) { _ftprintf(m_pStream, _T("\t%s\n"), _T("#POSITION_TRACK")); for (DWORD dwPosTrack = 0; dwPosTrack < pMesh->m_PosTrack.size(); dwPosTrack++) { _ftprintf(m_pStream, _T("\t%d %10.4f %10.4f %10.4f\n"), pMesh->m_PosTrack[dwPosTrack].iTick, pMesh->m_PosTrack[dwPosTrack].vValue.x, pMesh->m_PosTrack[dwPosTrack].vValue.y, pMesh->m_PosTrack[dwPosTrack].vValue.z); } } if (pMesh->m_RotTrack.size() > 0) { _ftprintf(m_pStream, _T("\t%s\n"), _T("#ROTATION_TRACK")); for (DWORD dwRotTrack = 0; dwRotTrack < pMesh->m_RotTrack.size(); dwRotTrack++) { _ftprintf(m_pStream, _T("\t%d %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_RotTrack[dwRotTrack].iTick, pMesh->m_RotTrack[dwRotTrack].vValue.x, pMesh->m_RotTrack[dwRotTrack].vValue.y, pMesh->m_RotTrack[dwRotTrack].vValue.z, pMesh->m_RotTrack[dwRotTrack].qValue.x, pMesh->m_RotTrack[dwRotTrack].qValue.y, pMesh->m_RotTrack[dwRotTrack].qValue.z, pMesh->m_RotTrack[dwRotTrack].qValue.w); } } if (pMesh->m_SclTrack.size() > 0) { _ftprintf(m_pStream, _T("\t%s\n"), _T("#SCALE_TRACK")); for (DWORD dwSclTrack = 0; dwSclTrack < pMesh->m_SclTrack.size(); dwSclTrack++) { _ftprintf(m_pStream, _T("\t%d %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\n"), pMesh->m_SclTrack[dwSclTrack].iTick, pMesh->m_SclTrack[dwSclTrack].vValue.x, pMesh->m_SclTrack[dwSclTrack].vValue.y, pMesh->m_SclTrack[dwSclTrack].vValue.z, pMesh->m_SclTrack[dwSclTrack].qValue.x, pMesh->m_SclTrack[dwSclTrack].qValue.y, pMesh->m_SclTrack[dwSclTrack].qValue.z, pMesh->m_SclTrack[dwSclTrack].qValue.w); } } if (pMesh->m_VisTrack.size() > 0) { _ftprintf(m_pStream, _T("\t%s\n"), _T("#VISIVILITY_TRACK")); for (DWORD dwVisTrack = 0; dwVisTrack < pMesh->m_VisTrack.size(); dwVisTrack++) { _ftprintf(m_pStream, _T("\t%d %10.4f\n"), pMesh->m_VisTrack[dwVisTrack].iTick, pMesh->m_VisTrack[dwVisTrack].vValue.x); } } } S_Writer::S_Writer(void) { } S_Writer::~S_Writer(void) { } <file_sep>#include "TThread.h" unsigned int WINAPI TThread::HandleRunner(LPVOID parameter) { TThread* pThread = (TThread*)parameter; if( pThread ) pThread->Run(); return 0; } bool TThread::Run() { return true; } void TThread::CreateThread() { if( m_bStarted==true ) return; m_hThread = _beginthreadex( NULL, 0, HandleRunner, // 시작함수 (LPVOID)this, // 인자값 0, &m_iThreadID); m_bStarted = true; } TThread::TThread(void) { m_bStarted = false; } TThread::~TThread(void) { CloseHandle( (HANDLE)m_hThread ); } <file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <WinSock2.h> #include <Windows.h> #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"winmm.lib") DWORD WINAPI SendThread(LPVOID param) { SOCKET sock = (SOCKET)param; while (1) { char buffer[256] = { 0, }; fgets(buffer, 256, stdin); if (strlen(buffer) <=1) { break; } send(sock,buffer,strlen(buffer),0); } return true; } int main() { // WSA는 윈속 없으면 유닉스 // 윈속 초기화 WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) // 0 성공 1이 실패 { return 1; } //////////////////////////////// SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //SOCK_DGRAM // 3번째 인자는 그냥 무조건 0으로 쓰자 // (IPPROTO_TCP,IPPROTO_UDP) 원래는 맞게끔 넣어줘야함 //SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { return 1; } // 소켓 생성 SOCKADDR_IN addr; ZeroMemory(&addr, sizeof(addr)); addr.sin_family = AF_INET; // 무조건 고정 addr.sin_addr.s_addr = inet_addr("192.168.0.27"); // 127.0.0.1 loofback 주소 addr.sin_port = htons(10000); // 접속(전화를 걸었다) int ret = connect(sock, (sockaddr*)&addr, sizeof(addr)); // 서버의 정보가 들어가 있다 if (ret == SOCKET_ERROR) { return 1; } // SOCKET_ERROR 가 아니면 연결이 된것 //while (1) //{ //} //while (1)99 //{ DWORD id; HANDLE hThread = CreateThread(NULL, 0,SendThread,(LPVOID)sock,0,&id); while (1) { char buffer3[256] = { 0, }; int iRet=recv(sock, buffer3, sizeof(buffer3), 0); if (iRet == 0)break; if (iRet == SOCKET_ERROR)break; std::cout << buffer3; } char buffer2[] = { 0, }; scanf("%s", buffer2); send(sock, buffer2, sizeof(buffer2), 0); //} /*char buffer[256] = { 0, }; recv(sock, buffer, sizeof(buffer), 0); std::cout << buffer;*/ closesocket(sock); // 윈속 닫기 WSACleanup(); std::cout << "HELLO World!\n"; }<file_sep>#include "xDxObj.h" namespace DX { ID3D11ShaderResourceView* CreateShaderResourceView( ID3D11Device* pd3dDevice, const TCHAR* szFileName) { HRESULT hr = S_OK; ID3D11ShaderResourceView* pSRV = nullptr; D3DX11_IMAGE_LOAD_INFO loadinfo; ZeroMemory(&loadinfo, sizeof(loadinfo)); loadinfo.BindFlags = D3D11_BIND_SHADER_RESOURCE; loadinfo.Format = DXGI_FORMAT_FROM_FILE; ID3D11ShaderResourceView* pTex = NULL; hr = D3DX11CreateShaderResourceViewFromFile( pd3dDevice, szFileName, &loadinfo, NULL, &pSRV, NULL); if (FAILED(hr)) { return nullptr; } return pSRV; } ID3D11Buffer* CreateVertexBuffer( ID3D11Device* pd3dDevice, UINT iNumCount, UINT iSize, VOID* data, ID3D11Buffer** ppBuffer) { HRESULT hr; ID3D11Buffer* pBuffer = nullptr; D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA sd; ZeroMemory(&bd, sizeof(bd)); ZeroMemory(&sd, sizeof(sd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.CPUAccessFlags = 0; bd.ByteWidth = iNumCount * iSize; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; sd.pSysMem = data; if (FAILED(hr = pd3dDevice->CreateBuffer(&bd, &sd, &pBuffer))) { return nullptr; } *ppBuffer = pBuffer; return pBuffer; } ID3D11Buffer* CreateIndexBuffer( ID3D11Device* pd3dDevice, UINT iNumCount, UINT iSize, VOID* data, ID3D11Buffer** ppBuffer) { HRESULT hr; ID3D11Buffer* pBuffer = nullptr; D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA sd; ZeroMemory(&bd, sizeof(bd)); ZeroMemory(&sd, sizeof(sd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.CPUAccessFlags = 0; bd.ByteWidth = iNumCount * iSize; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; sd.pSysMem = data; if (FAILED(hr = pd3dDevice->CreateBuffer(&bd, &sd, &pBuffer))) { return nullptr; } *ppBuffer = pBuffer; return pBuffer; } ID3D11Buffer* CreateConstantBuffer( ID3D11Device* pd3dDevice, UINT iNumCount, UINT iSize, ID3D11Buffer** ppBuffer, VOID* data, bool bDynamic) { HRESULT hr; ID3D11Buffer* pBuffer = nullptr; D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA sd; ZeroMemory(&bd, sizeof(bd)); ZeroMemory(&sd, sizeof(sd)); if (bDynamic) { bd.Usage = D3D11_USAGE_DYNAMIC; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } else { bd.Usage = D3D11_USAGE_DEFAULT; bd.CPUAccessFlags = 0; } bd.ByteWidth = iNumCount * iSize; bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; if (data != NULL) { sd.pSysMem = data; if (FAILED(hr = pd3dDevice->CreateBuffer(&bd, &sd, &pBuffer))) { return nullptr; } } else { sd.pSysMem = data; if (FAILED(hr = pd3dDevice->CreateBuffer(&bd, NULL, &pBuffer))) { return nullptr; } } *ppBuffer = pBuffer; return pBuffer; } ID3D11InputLayout* CreateInputLayout( ID3D11Device* pd3dDevice, DWORD dwSize, LPCVOID lpData, D3D11_INPUT_ELEMENT_DESC* layout, UINT numElements, ID3D11InputLayout** ppInputLayout) { HRESULT hr; ID3D11InputLayout* pInputLayout; if (FAILED(hr = pd3dDevice->CreateInputLayout(layout, numElements, lpData, dwSize, &pInputLayout))) { return nullptr; } *ppInputLayout = pInputLayout; return pInputLayout; } HRESULT CompileShaderFromFile(const WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3DCOMPILE_DEBUG; #endif ID3DBlob* pErrorBlob; hr = D3DX11CompileFromFile(szFileName, NULL, NULL, szEntryPoint, szShaderModel, dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL); if (FAILED(hr)) { if (pErrorBlob != NULL) OutputDebugStringA((char*)pErrorBlob->GetBufferPointer()); if (pErrorBlob) pErrorBlob->Release(); return hr; } if (pErrorBlob) pErrorBlob->Release(); return S_OK; } ID3D11VertexShader* LoadVertexShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut, const char* pFuntionName) { HRESULT hr; ID3D11VertexShader* pVertexShader; ID3DBlob* pBlob; if (FAILED(hr = CompileShaderFromFile( (TCHAR*)pShaderFile, pFuntionName, "vs_5_0", &pBlob))) { return nullptr; } if (FAILED(hr = pd3dDevice->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pVertexShader))) { if (pBlob)pBlob->Release(); return nullptr; } if (ppBlobOut == nullptr) { if (pBlob)pBlob->Release(); } else { *ppBlobOut = pBlob; } return pVertexShader; } ID3D11PixelShader* LoadPixelShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut, const char* pFuntionName) { HRESULT hr; ID3D11PixelShader* pPixelShader; ID3DBlob* pBlob; if (FAILED(hr = CompileShaderFromFile( (TCHAR*)pShaderFile, pFuntionName, "ps_5_0", &pBlob))) { return nullptr; } if (FAILED(hr = pd3dDevice->CreatePixelShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pPixelShader))) { if (pBlob)pBlob->Release(); return nullptr; } if (ppBlobOut == nullptr) { if (pBlob)pBlob->Release(); } else { *ppBlobOut = pBlob; } return pPixelShader; } ID3D11GeometryShader* LoadGeometryShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut, const char* pFuntionName) { HRESULT hr; ID3D11GeometryShader* pGShader; ID3DBlob* pBlob; if (FAILED(hr = CompileShaderFromFile( (TCHAR*)pShaderFile, pFuntionName, "gs_5_0", &pBlob))) { return nullptr; } if (FAILED(hr = pd3dDevice->CreateGeometryShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pGShader))) { if (pBlob)pBlob->Release(); return nullptr; } if (ppBlobOut == nullptr) { if (pBlob)pBlob->Release(); } else { *ppBlobOut = pBlob; } return pGShader; } bool xDxObj::PreRender( ID3D11DeviceContext* pContext, UINT iVertexSize) { pContext->IASetInputLayout( m_pInputLayout.Get()); UINT stride = iVertexSize; UINT offset = 0; pContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); pContext->IASetIndexBuffer( m_pIndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0); pContext->VSSetConstantBuffers(0,1, m_pConstantBuffer.GetAddressOf()); pContext->GSSetConstantBuffers(0, 1, m_pConstantBuffer.GetAddressOf()); pContext->VSSetShader( m_pVertexShader.Get(), NULL, 0); pContext->PSSetShader( m_pPixelShader.Get(), NULL, 0); pContext->GSSetShader( m_pGeometryShader.Get(), NULL, 0); pContext->PSSetShaderResources( 0,1, m_pTextureRV.GetAddressOf()); return true; } bool xDxObj::Render( ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount) { PreRender(pContext, iVertexSize); PostRender(pContext, iVertexSize, iCount); return true; } bool xDxObj::PostRender( ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount) { if (m_pIndexBuffer != nullptr) pContext->DrawIndexed(iCount, 0, 0); else pContext->Draw(iCount, 0); return true; } bool xDxObj::Release() { return true; } xDxObj::xDxObj() { } xDxObj::~xDxObj() { Release(); } }<file_sep>#include<stdio.h> int main(void) { int val1 = 15; int val2 = 28; int logicAnd; int bitAnd; logicAnd = val1 && val2; bitAnd = val1 & val2; printf("%d\n",val1&val2); }<file_sep>#include<stdio.h> #include<conio.h> // 다이아몬드 void main() { int Start = 6; int Count = 1; for (int i = 1; i <= 5; i++) { for (int space = 1; space <= 11; space++) { if (space == Start) { for (int j = 1; j <= Count * 2; j++) printf("*"); } else { printf(" "); } } printf("\n"); Start--; Count++; } Count--; Start++; for (int i = 1; i <= 4; i++) { Start++; Count--; for (int spaceb = 1; spaceb <= 11; spaceb++) { if (spaceb == Start) for (int j = 1; j <= Count * 2; j++) { printf("*"); } else { printf(" "); } }printf("\n"); } _getch(); }<file_sep>#pragma once #include "Sstd.h" namespace DX { ID3D11Buffer* CreateVertexBuffer( ID3D11Device* pd3dDevice, UINT iNumVertex, UINT iVertexSize, VOID* data, ID3D11Buffer** ppBuffer); ID3D11Buffer* CreateIndexBuffer( ID3D11Device* pd3dDevice, UINT iNumVertex, UINT iVertexSize, VOID* data, ID3D11Buffer** ppBuffer); ID3D11Buffer* CreateConstantBuffer( ID3D11Device* pd3dDevice, UINT iNumVertex, UINT iVertexSize, ID3D11Buffer** ppBuffer, VOID* data = NULL, bool bDynamic = false); // ID3D11InputLayout* CreateInputLayout( ID3D11Device* pd3dDevice, DWORD dwSize, LPCVOID lpData, D3D11_INPUT_ELEMENT_DESC* layout, UINT numElements, ID3D11InputLayout** ppInputLayout); ID3D11VertexShader* LoadVertexShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut = nullptr, const char* pFuntionName = "VS"); ID3D11PixelShader* LoadPixelShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut = nullptr, const char* pFuntionName = "PS"); ID3D11GeometryShader* LoadGeometryShaderFile( ID3D11Device* pd3dDevice, const void* pShaderFile, ID3DBlob** ppBlobOut = nullptr, const char* pFuntionName = "GS"); HRESULT CompileShaderFromFile(const WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut); ID3D11ShaderResourceView* CreateShaderResourceView(ID3D11Device* pd3dDevice, const TCHAR* szFileName); class sDxObj { public: ComPtr<ID3D11Buffer> m_pVertexBuffer; ComPtr<ID3D11Buffer> m_pIndexBuffer; ComPtr<ID3D11Buffer> m_pConstantBuffer; ComPtr<ID3D11InputLayout> m_pInputLayout; ComPtr<ID3D11VertexShader> m_pVertexShader; ComPtr<ID3D11PixelShader> m_pPixelShader; ComPtr<ID3D11GeometryShader> m_pGeometryShader; ComPtr<ID3DBlob> m_pVSBlob; ComPtr<ID3D11ShaderResourceView> m_pTextureRV; public: bool PreRender(ID3D11DeviceContext* pContext, UINT iVertexSize); bool Render(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount); bool PostRender(ID3D11DeviceContext* pContext, UINT iVertexSize, UINT iCount); bool Release(); public: sDxObj(); virtual ~sDxObj(); }; } using namespace DX;<file_sep>#pragma once #include <windows.h> #include <assert.h> #define GAME_START int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR IpCmdLine, int nCmdShow){ #define GAME_END } #define GAME_RUN(s,w,h) GAME_START{Window win;win.SetWindow(hInst,L#s); win.Run();}GAME_END<file_sep>#include "value.h" value::value(TCHAR* pData) { int iLength = _tcslen(pData) + 1; int iSize = sizeof(TCHAR)*iLength; this->m_szValue = new TCHAR[iSize]; _tcscpy_s(m_szValue, iSize, pData); m_pNext = NULL; } value::~value() { delete m_szValue; } <file_sep>#pragma once #include "DIWindow.h" class DTimer { private: LARGE_INTEGER m_Frequency; // 초당 주파수 LARGE_INTEGER m_Current; // 현재 시간 LARGE_INTEGER m_Frame; // 이전 프레임의 시간 체크 float m_fSecPerFrame; // 프레임 경과 시간 LARGE_INTEGER m_FPS; // FPS 체크 타이머 int m_iFramePerSecond; // 초당 프레임 int m_iFPSElapse; // 초당 경과된 프레임 LARGE_INTEGER m_Start; // 이벤트 타이머 시작 시간 LARGE_INTEGER m_Elapse; // 이벤트 타이머 경과 시간 bool m_bStarted; // 이벤트 타이머 작동 여부 float m_fEventTime; public: // 엔진코어에서 사용하는 지원함수 bool Init(); bool Frame(); bool Render(); bool Release(); // 경과한 시간에 대한 지원 함수들 void Reset(); void Start(); void Stop(); bool IsStarted() const; float GetElapseTime(); // FPS int GetFPS(); float GetSPF(); public: DTimer(); virtual ~DTimer(); }; <file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <time.h> #include <cstdlib> #include <cstring> #include <conio.h> using namespace std; struct StudentData { char strName[4]; int iindex; int iKor; int iEng; int iMat; int iTotal; float Average; }; class SStudent { public: void inputData(int Cnt); StudentData GetData(); void SetData(char strName[], int iindex, int iKor, int iEng, int iMat, int iTotal, float Average); void Print(); private: StudentData sData; public: SStudent(); ~SStudent(); }; struct Node { SStudent iData; Node* pNext; Node(SStudent temp) { memcpy(&iData, &temp,sizeof(SStudent)); }; }; enum Work { DataNew = 1, DataPrint, IndexFind, SaveData, LoadData, AddData, DelData, EXIT, }; <file_sep>#include "S_AnimObj.h" void S_AnimObj::GetAnimKeys(INode* pNode, SMesh* pMesh) { BOOL bPosAnim; BOOL bRotAnim; BOOL bScaleAnim; m_iDeltatick = m_Scene.iTickPerFrame; if (CheckForAnimation(pNode, bPosAnim, bRotAnim, bScaleAnim)) { if (bPosAnim) { DumpPosSample(pNode, pMesh); } if (bRotAnim) { DumpRotSample(pNode, pMesh); } if (bScaleAnim) { DumpScaleSample(pNode, pMesh); } } Control* visCont = pNode->GetVisController(); if (visCont) { DumpFloatKeys(visCont, pMesh); } } bool S_AnimObj::GetDecompAffine(TimeValue t, INode* pNode, AffineParts* ap, Point3* rotAxis, float* rotAngle) { Matrix3 tm = pNode->GetNodeTM(t)*Inverse(pNode->GetParentTM(t)); decomp_affine(tm, ap); Point3 vRotAxis; float fRotAngle; if (rotAngle != NULL && rotAngle != NULL) { AngAxisFromQ(ap->q, rotAngle, *rotAxis); } return true; } BOOL S_AnimObj::CheckForAnimation(INode* pNode, BOOL& bPos, BOOL& bRot, BOOL& bScale) { AffineParts ap; Point3 firstPos, firstRotAxis, firstScaleFactor; float firstRotAngle; GetDecompAffine(m_Interval.Start(), pNode, &ap, &firstRotAxis, &firstRotAngle); firstPos = ap.t; firstScaleFactor = ap.k; TimeValue start = m_Interval.Start() + GetTicksPerFrame(); TimeValue end = m_Interval.End(); bPos = bRot = bScale = FALSE; float rotAngle; Point3 rotAxis; for (TimeValue t = start; t <= end; t += m_iDeltatick) { GetDecompAffine(t, pNode, &ap, &rotAxis, &rotAngle); if (!bPos) { if (!EqualPoint3(ap.t, firstPos)) { bPos = TRUE; } } if (!bRot) { if (fabs(rotAngle - firstRotAngle) > ALMOST_ZERO) { bRot = TRUE; } else if (!EqualPoint3(rotAxis, firstRotAxis)) { bRot = TRUE; } } if (!bScale) { if (!EqualPoint3(ap.k, firstScaleFactor)) { bScale = TRUE; } } if (bPos && bRot && bScale)break; } return bPos || bRot || bScale; } void S_AnimObj::DumpPosSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltatick) { GetDecompAffine(t, pNode, &ap); SAnimTrack pAnim; pAnim.iTick = t; pAnim.vValue.x = ap.t.x; pAnim.vValue.y = ap.t.z; pAnim.vValue.z = ap.t.y; pMesh->m_PosTrack.push_back(pAnim); } } void S_AnimObj::DumpRotSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltatick) { GetDecompAffine(t, pNode, &ap); SAnimTrack pAnim; pAnim.iTick = t; pAnim.qValue.x = ap.q.x; pAnim.qValue.y = ap.q.z; pAnim.qValue.z = ap.q.y; pAnim.qValue.w = ap.q.w; pMesh->m_RotTrack.push_back(pAnim); } } void S_AnimObj::DumpScaleSample(INode* pNode, SMesh* pMesh) { TimeValue start = m_Interval.Start(); TimeValue end = m_Interval.End(); AffineParts ap; for (TimeValue t = start; t <= end; t += m_iDeltatick) { GetDecompAffine(t, pNode, &ap); SAnimTrack Anim; Anim.iTick = t; Anim.vValue.x = ap.k.x; Anim.vValue.y = ap.k.z; Anim.vValue.z = ap.k.y; Anim.qValue.x = ap.u.x; Anim.qValue.y = ap.u.z; Anim.qValue.z = ap.u.y; Anim.qValue.w = ap.u.w; pMesh->m_SclTrack.push_back(Anim); } } void S_AnimObj::DumpFloatKeys(Control* cont, SMesh* pMesh) { if (!cont) return; int i; IKeyControl *ikc = NULL; ikc = GetKeyControlInterface(cont); SAnimTrack Anim; if (ikc && cont->ClassID() == Class_ID(TCBINTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { ITCBFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } else if (ikc && cont->ClassID() == Class_ID(HYBRIDINTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { IBezFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } else if (ikc && cont->ClassID() == Class_ID(LININTERP_FLOAT_CLASS_ID, 0)) { for (i = 0; i < ikc->GetNumKeys(); i++) { ILinFloatKey key; ikc->GetKey(i, &key); Anim.iTick = key.time; Anim.vValue.x = key.val; pMesh->m_VisTrack.push_back(Anim); } } else { TSTR name; cont->GetClassName(name); if (cont->IsAnimated()) { Interval range; Interval animRange = m_p3dsMax->GetAnimRange(); TimeValue t = cont->GetTimeRange(TIMERANGE_ALL).Start(); float value; while (animRange.InInterval(t)) { range = FOREVER; cont->GetValue(t, &value, range); t = range.Start(); Anim.iTick = t; Anim.vValue.x = value; pMesh->m_VisTrack.push_back(Anim); if (range.End() > cont->GetTimeRange(TIMERANGE_ALL).End()) { break; } else { t = (range.End() / GetTicksPerFrame()) * GetTicksPerFrame(); } } } } } S_AnimObj::S_AnimObj() { } S_AnimObj::~S_AnimObj() { } <file_sep>#include "S_ChatMain.h" #include "S_Chat_Svr.h" #include "S_IOCP.h" #include "S_DebugString.h" bool S_ChatMain::Init() { S_iocp.Init(); S_CHAT.Init(); m_UDP.Init(); return true; } bool S_ChatMain::Release() { m_UDP.Release(); S_CHAT.Release(); return true; } LRESULT S_ChatMain::MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: { int iWidth = 800; int iHeight = 600; S_Debug.m_hList = CreateWindow(L"ListBox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 0, 0, iWidth, iHeight, hWnd, (HMENU)0, m_hInstance, NULL); }break; } return 0; } S_ChatMain::S_ChatMain() { } S_ChatMain::~S_ChatMain() { } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow) { S_ChatMain Main; if (!Main.SetWindow(hInstance, _T("chat_Svr"), 800, 600)) { return 0; } SetCursor(NULL); if (Main.Run() == false) { return 0; } return 1; }<file_sep>#pragma once #include "value.h" class Token { public: value * m_pToken; int m_iSize; public: void Show(); Token(TCHAR* pData); ~Token(); }; <file_sep>#pragma once #include "Header.h" #include "TemplateMap.h" #define CTL_CHARS 31 #define SINGLE_QUOTE 39 #define ALMOST_ZERO 1.0e-3f typedef struct _D3D_MATRIX { union { struct { float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; float m[4][4]; }; }D3D_MATRIX, *LPD3D_MATRIX; typedef class Matrix3 *LPMATRIX3; struct P3NCVERTEX { float Px, Py, pz; float Nx, Ny, Nz; Point4 c; }; struct PNCT_VERTEX { Point3 p; Point3 n; Point4 c; Point2 t; }; const enum OBJECTCLASSTYPE { CLASS_GEOM = 0, CLASS_BONE, CLASS_DUMMY, CLASS_BIPED, }; struct STri { PNCT_VERTEX v[3]; int iSubIndex; }; struct SScene { int iVersion; // 파일 버전 int iFirstFrame; // 시작 프레임 int iLastFrame; // 마지막 프레임 int iFrameSpeed; // 1초당 프레임 개수 (30) int iTickPerFrame; // 1프레임의 틱 값(160) int iNumMesh; // 메쉬 오브젝트 개수 int iMaxWeight; // 정점 당 가중치 int iBindPose; // 바인딩 포즈 애니메이션 여부 }; struct STexMap { int iIndex; int iType; // 텍스쳐 타입 인덱스 TSTR strTextureName; // 텍스쳐 이름. }; struct SMtl { int iIndex; int iNumSubMtl; // 서브 메터리얼 개수 int iNumMap; // 텍스쳐 맵 갯수 TSTR strName; // 매터리얼 이름 TSTR strClassname; // 맵클래스 이름 vector<STexMap> TexMaps; // 맵 타이틀 vector<SMtl> SubMaterial;// 서브 매터리얼 저장 벡터 }; struct SAnimTrack { int iType; int iTick; Quat qValue; Point3 vValue; }; struct SMESH_HEADER { OBJECTCLASSTYPE m_ClassType; Box3 m_Box; D3D_MATRIX m_matWorld; int m_iNumVertex; int m_iNumFace; int m_iMtrlRef; int m_iNumTrack[4]; }; struct SMesh:public SMESH_HEADER { TSTR m_strNodeName; TSTR m_strParentName; vector <SAnimTrack> m_PosTrack; vector <SAnimTrack> m_RotTrack; vector <SAnimTrack> m_SclTrack; vector <SAnimTrack> m_VisTrack; vector <STri> m_TriList; vector <SMesh*> m_pSubMesh; SMesh() { m_iMtrlRef = 1; m_iNumFace = 0; m_iNumTrack[0] = 0; m_iNumTrack[1] = 0; m_iNumTrack[2] = 0; m_iNumTrack[3] = 0; m_ClassType = CLASS_GEOM; }; ~SMesh() { m_PosTrack.clear(); m_RotTrack.clear(); m_SclTrack.clear(); m_VisTrack.clear(); m_TriList.clear(); }; }; struct MATRIXINDEX { OBJECTCLASSTYPE m_ClassType; int m_iIndex; T_STR m_szName; vector<P3NCVERTEX> m_VertexList; Matrix3 m_NodeTM; Matrix3 m_InvNodeTM; INode* m_pINode; Object* m_pObj; Control* m_pControl; SMesh m_tMesh; void Add(int iIndex, TSTR szName) { m_pObj = NULL; m_pControl = NULL; m_iIndex = iIndex; m_szName = szName; } void SetNode(INode* pNode, int iTick, MATRIXINDEX* pParentIndex = 0) { m_pINode = pNode; m_pObj = m_pINode->GetObjectRef(); m_pControl = m_pINode->GetTMController(); m_ClassType = CLASS_GEOM; if (m_pObj&&m_pObj->ClassID() == Class_ID(BONE_CLASS_ID, 0)) { m_ClassType = CLASS_BONE; } if (m_pObj&&m_pObj->ClassID() == Class_ID(DUMMY_CLASS_ID, 0)) { m_ClassType = CLASS_DUMMY; } if (m_pControl->ClassID() == BIPSLAVE_CONTROL_CLASS_ID || m_pControl->ClassID() == BIPBODY_CONTROL_CLASS_ID) { m_ClassType = CLASS_BIPED; } m_NodeTM = pNode->GetNodeTM(iTick); m_InvNodeTM = Inverse(m_NodeTM); } void Release() { for (int iSub = 0; iSub < m_tMesh.m_pSubMesh.size(); iSub++) { SAFE_DEL(m_tMesh.m_pSubMesh[iSub]); } m_tMesh.m_pSubMesh.clear(); }; }; class S_Global { public: Interface* m_p3dsMax; // 맥스 인터페이스 INode* m_pRootNode; Interval m_Interval; //프레임 정보 SScene m_Scene; // 씬정보 저장 STemplateMap<MATRIXINDEX> m_MatrixMap; vector<Mtl*> m_pMtlList; // 매터리얼 리스트 vector<SMtl> m_Material; // 출력 할 정보 리스트 TSTR m_CurtFileName; // 맥스 파일 이름 TCHAR m_tmpBuffer[MAX_PATH]; // 임시 버퍼 public: bool CheckFile(Interface* pMax); bool Initialize(Interface* p3dsMax = NULL); void PreProcess(INode* pNode); void AddObject(INode* pNode); void AddMtl(INode* pNode); // 중복되지 않고 매터리얼 추가 int GetMtlRef(Mtl* pMtl);// pMtl 이 저장된 인덱스를 반환한다. void SetBindPose(bool bBindPose = false) { m_Scene.iBindPose = bBindPose; } int GetIndex(const TCHAR* strNodeName); public: void DumpMatrix3(Matrix3* m, D3D_MATRIX& mat); void DumpPoint3(Point3& pDest, Point3& pSrc); bool TMNegParity(Matrix3 &m); bool EqualPoint2(Point2 p1, Point2 p2); bool EqualPoint3(Point3 p1, Point3 p2); bool EqualPoint4(Point4 p1, Point4 p2); TCHAR* FixupName(MSTR name); public: S_Global(void); virtual ~S_Global(void); }; <file_sep>#include<stdio.h> void main(int argc, char*argv[]) { printf("count=%d\n", argc); printf("string1=%s\n", argv[0]); printf("string2=%s\n", argv[1]); }<file_sep>#pragma once #include <iostream> using namespace std; //const char& operator []() const {} //char& operator []() 두 함수는 별개의 함수가 된다. // 연산자 재정의 불가 //1)선택 연산자: . //2)포인터 선택 연산자: .* //3)영역 연산자: :: //4)조건 연산자: ? : //5)크기 연산자: sizeof class Tpoint { public: int x, y; void SetPosition(int _x, int _y); void Move(int _x, int _y); void Show(void); public: Tpoint * operator->() { return this; } Tpoint& operator*() { return *this; } Tpoint operator++(void);//++p1 Tpoint operator++(int);//p1-- //이항연산자 p3=p1+p2; Tpoint operator+(const Tpoint &pt)const; Tpoint operator-(const Tpoint &pt)const; Tpoint operator*(const Tpoint &c); Tpoint operator/(const Tpoint &c); Tpoint operator*(int mag)const; //p2=p1*2; Tpoint operator/(int div)const; //p2=p1/2; friend Tpoint operator*(int mag, const Tpoint &pt);// p2=2*p1 friend Tpoint operator/(int div, const Tpoint &pt);//p2=2/p1 Tpoint &operator=(const Tpoint &pt); Tpoint &operator+=(const Tpoint &pt); Tpoint &operator-=(const Tpoint &pt); Tpoint &operator*=(const Tpoint &pt); Tpoint &operator/=(const Tpoint &pt); Tpoint &operator*= (int mag); Tpoint &operator/=(int div); bool operator ==(const Tpoint &pt)const; bool operator !=(const Tpoint &pt)const; int &operator[](int index); void *operator new(size_t size); void operator delete(void *p); //std::cout<<*pFindA<<*pFindB; friend ostream &operator <<(ostream &os, const Tpoint &pt); friend istream &operator >>(istream& is, Tpoint &pt); void (Tpoint::*m_fp)(); void Execute() { if (m_fp != NULL) { (this->*m_fp)(); } } void operator >(Tpoint* the) { if (m_fp != NULL) { (the->*m_fp)(); } } public: Tpoint(); Tpoint(int x, int y); ~Tpoint(); }; <file_sep>#pragma once #include "S_KHJ_AnimObj.h" class S_KHJ_Writer : public S_KHJ_AnimObj, public TSingleton<S_KHJ_Writer> { private: friend class TSingleton<S_KHJ_Writer>; public: FILE* m_pStream; // 출력 파일 포인터 TSTR m_strFileName; // 출력 할 파일명 public: bool Init(TSTR strFileName, Interface* pMax); // 초기화 bool KHJExport(); // 파일 출력 bool Release(); // 메모리 소멸 및 해제 // 출력 파일 지정 대화상자 TCHAR* SaveFileDlg(TCHAR* szExt, TCHAR* szTitle = _T("KHJExporter")); void ExpScene(); void ExpMaterial(); void ExpObject(); int ExpMesh(FILE* fp, SMesh* pMesh, int iMtrl = -1, int iAddCount = 0); void ExpAnimation(SMesh* pMesh); void ExpTexture(vector<STexMap>& TexMap); int IsEqulVertexList(vector<PNCT_VERTEX>& VertexArray, PNCT_VERTEX& Vertex); int SetUniqueBuffer(SMesh* pMesh, int iMtrl, int iStartTir, vector<PNCT_VERTEX>& VertexArray, vector<int>& IndexArray); void matExport(); public: S_KHJ_Writer(); virtual ~S_KHJ_Writer(); }; #define I_Writer S_KHJ_Writer::GetInstance() <file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #define DIRECTINPUT_VERSION 0x800 #include <windows.h> #include <assert.h> #include <tchar.h> #include <iostream> #include <map> #include <string> #include <list> #include <vector> #include "d3dx11.h" //#include "dxgi.h" #include "d3dcompiler.h" #include <d3dx10math.h> #include <wrl.h> #pragma comment(lib,"d3dx10d.lib") #pragma comment(lib,"winmm.lib") #pragma comment(lib,"d3d11.lib") #pragma comment(lib,"d3dx11.lib") //#pragma comment(lib,"dxgi.lib") #pragma comment(lib,"3D_lib.lib") using namespace std; using namespace Microsoft::WRL; typedef std::basic_string<char> C_STR; typedef std::basic_string<wchar_t> W_STR; typedef std::basic_string<TCHAR> T_STR; typedef std::basic_string<char>::iterator C_ITOR; typedef std::basic_string<wchar_t>::iterator W_ITOR; typedef std::basic_string<TCHAR>::iterator T_ITOR; #define GAME_START int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,LPSTR lpCmdLine,int nCmdShow){ #define GAME_END } #define GAME_RUN(s,w,h) GAME_START{ Sample win;win.SetWindow(hInst, L#s,w,h);win.Run();}GAME_END extern HWND g_hWnd; extern HINSTANCE g_hInstance; extern RECT g_rtClient; extern bool g_bActiveApp; extern float g_fGameTimer; extern float g_fSecPerFrame; struct TGameInput { BOOL bFront; BOOL bBack; BOOL bLeft; BOOL bRight; BOOL bAttack; BOOL bJump; BOOL bButton0; BOOL bButton1; BOOL bButton2; }; extern TGameInput g_Input; template<class T> class SSingleton { public: static T& GetInstance() { static T theSingleInstance; return theSingleInstance; } }; ///////////////////// 매크로 ////////////////////// #define randf(x) (x*rand()/(float)RAND_MAX) #define randf2(x,off) (off+(x*rand())/(float)RAND_MAX) #define randstep(fMin,fMax) (fMin+((float)fMax-(float)fMin)*rand()/(float)RAND_MAX) #define clamp(x, minX, maxX) if(x>maxX) x= maxX;else if(x< minX) x= minX; #ifndef V #define V(x) { hr = (x);} #endif #ifndef V_RETURN #define V_RETURN(x) { hr = (x); if( FAILED(hr)){return hr;}} #endif ////////////////////////////////////////////// // 객체 및 배열 할당과 삭제 및 소멸 매크로 ////////////////////////////////////////////// #ifndef SAFE_ZERO #define SAFE_ZERO(A) { A = 0; } #endif #ifndef SAFE_NEW #define SAFE_NEW(A, B) { if (!A) A = new B; } #endif #ifndef SAFE_DEL #define SAFE_DEL(A) { if (A) delete A; (A)=NULL; } #endif #ifndef SAFE_NEW_ARRAY #define SAFE_NEW_ARRAY(A, B, C) { if (!A && C) A = new B[C]; } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(A) { if (A) delete [] A; (A)=NULL; } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(A) { if(A) { (A)->Release(); (A)=NULL; } } #endif #ifndef SAFE_NEW_CLEAR #define SAFE_NEW_CLEAR( A, B ) s { if (!A) A = new B; if(A) memset( A, 0, sizeof(B) ); }; #endif #ifndef SAFE_NEW_ARRAY_CLEAR #define NEW_ARRAY_CLEAR( A, B, C ) { if (!A && C) A = new B[C]; if(A) memset( A, 0, sizeof(B)*C ); }; #endif ////////////////////////////////////////////// // Assert ////////////////////////////////////////////// #ifndef Assert #if defined( _DEBUG ) || defined( _DEBUG ) #define Assert(b) do {if (!(b)) {OutputDebugStringW(L"Assert: " #b L"\n");}} while(0) #else #define Assert(b) #endif //_DEBUG || _DEBUG #endif /////////////////////////////////////////////////////////////////////////////////////////////////// // 디버그 메세지( 오류가 예상되는 곳에서 사용함 ) : 파일명과 라인 및 문자열이 출력되며 강제 종료됨. /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG #define DEBUGMSG(lpText)\ {\ TCHAR szBuffer[256];\ _stprintf_s(szBuffer, _T("[File: %s][Line: %d]\n[Note : %s]"), _CRT_WIDE(__FILE__), __LINE__, lpText); \ MessageBox(NULL, szBuffer, _T("ERROR"), MB_ICONERROR);\ _ASSERT(1);} #else #define DEBUGMSG(lpText) #endif<file_sep>// 프로그램을 작성하다 보면 기존에 만들어 놓은 클래스와 유사한 경우가 있다. // 하지만 그 클래스를 재사용하고 싶어도 조금이라도 수정하지 않고 사용하기란 어려울 것이다 //adapter 패턴은 기존 클래스를 재사용할 수 있도록 중간에서 맞춰주는 역할을 한다. //즉 호환성이 없는 기존 클래스의 인터페이스를 변환해 재사용할 수 있도록 해준다. //adapter 패턴은 다음 두 가지 형태로 사용된다.1) 클래스아답터 2)오브젝트 아답터 #include <iostream> using namespace std; //#define CLASS_ADAPTER #define OBJECT_ADAPTER class Rectangle { public: Rectangle(int x1, int y1, int x2, int y2) { x1_ = x1; y1_ = y1; x2_ = x2; y2_ = y2; } void Draw() {} private: int x1_, y1_, x2_, y2_; }; class TextView { public: Rectangle GetExtent() { return Rectangle(x1_, y1_, x1_ + width_, y1_ + height_); } private: int x1_, y1_; int width_, height_; }; class Shape { public: virtual Rectangle BoundingBox() = 0; }; class LineShape : public Shape { public: Rectangle BoundingBox() { return Rectangle(x1_, y1_, x2_, y2_); } private: int x1_, y1_, x2_, y2_; }; #if defined(CLASS_ADAPTER) class Textshape : public Shape, private TextView { public: Rectangle BoundingBox() { return GetExtent(); } }; void DisplayBoundingBox(Shape* pSelectedShape) { (pSelectedShape->BoundingBox()).Draw(); } #elif defined(OBJECT_ADAPTER) class LineShape :public Shape { public: Rectangle BoundingBox() { return Rectangle(x1_, y1_, x2_, y2_); } private: int x1_, y1_, x2_, y2_; }; class TextShape : public Shape { public: TextShape() { pText_ = new TextView; } Rectangle BoundingBox() { return pText_->GetExtent(); } private: TextView * pText_; }; void DisplayBoundingBox(Shape* pSelectedShape) { (pSelectedShape->BoundingBox()).Draw(); } #else void DisplayBoundingBox(Shape* pSelectedShape, TextView* pSelectedText) { if (pSelectedText != 0) { (pSelectedText->GetExtent()).Draw(); } else if (pSelectedShape != 0) { (pSelectedShape->BoundingBox()).Draw(); } else { } } #endif void main() { #if defined(CLASS_ADPTER)||defined(OBJECT_ADAPTER) TextShape text; DisplayBoundingBox(&text); #else TextView text; DisplayBoundingBox(0, &text); #endif }<file_sep>#include<stdio.h> int a; void func(void) { a = 5; } void main() { func(); printf("%d\n", a); a = 10; printf("%d\n", a); }<file_sep>#include "SPacketPool.h" #include "SLock.h" // 패킷 풀에 패킷을 저장해준다 bool SPacketPool::AddPacket(S_PACKET& addPacket) { { SLock lock(this); m_PacketList.push_back(addPacket); } return true; } bool SPacketPool::ProcessPacket() { { SLock lock(this); list<S_PACKET>::iterator iter; for (iter = m_PacketList.begin(); iter != m_PacketList.end(); iter++) { S_PACKET* pUserData = (S_PACKET*)&(*iter); ProcessWork(pUserData); } return true; } } void SPacketPool::ProcessWork(S_PACKET* pUserData) { } SPacketPool::SPacketPool() { } SPacketPool::~SPacketPool() { } <file_sep>#include "TSynchronize.h" TSynchronize::TSynchronize( TServerObj* pObj): m_pSerObj(pObj) { if( pObj == NULL ) return; EnterCriticalSection(&pObj->m_cs); } TSynchronize::~TSynchronize(void) { if( m_pSerObj == NULL ) return; LeaveCriticalSection(&m_pSerObj->m_cs); } <file_sep>#pragma once #include "S_Thread.h" #include "S_StreamPacket.h" class S_PacketPool : public S_SvrObj { public: list<PACKET> m_PacketList; typedef list<PACKET>::iterator m_Piter; public: virtual bool AddPacket(PACKET& addPacket); virtual bool ProcessPacket(); virtual void ProcessWork(PACKET* _pUserData); public: S_PacketPool(); virtual ~S_PacketPool(); }; <file_sep>#pragma once #include <iostream> #include <string> #include <WinSock2.h> // 윈도우 위에 있어야 한다. #pragma comment(lib,"ws2_32") #include "TProtocol.h" using namespace std; class TPacket { public: //PACKET_HEADER ph; 구조체를 사용해도 상관은 없다. //char* m_pData; //WORD m_iSize; //WORD m_iType; UPACKET m_uPacket; char* m_pOffset; public: void PutData(const char* pData,int iSize); TPacket& operator << (const char* data); TPacket& operator << (int data); //TPacket& operator << (float data); //TPacket& operator << (DWORD data); TPacket& operator << (string data); public: void GetData(const char* pData, int iSize); TPacket& operator >> (const char* data); TPacket& operator >> (int& data); TPacket& operator >> (string& data); public: TPacket(); TPacket(WORD type); virtual ~TPacket(); }; <file_sep>#include "S_KHJ_SkinExp.h" #include "S_KHJ_Writer.h" bool S_KHJ_SkinExp::Init() { return true; } void S_KHJ_SkinExp::ExportPhysiqueData(INode* node, Modifier *phyMod) { IPhysiqueExport * phyExport = (IPhysiqueExport*)phyMod->GetInterface(I_PHYEXPORT); IPhyContextExport * mcExport = (IPhyContextExport *)phyExport->GetContextInterface(node); // 블랜딩 및 논블랜딩 타입을 변환 mcExport->ConvertToRigid(true); mcExport->AllowBlending(true); // 블랜딩 타입일 경우 변환 // class UPhyBlendedRigidVertex : public IPhyVertexExport IPhyBlendedRigidVertex *rb_vtx = NULL; // 논블랜딩 타입일 경우 변환 // class IPhyRigidVertex : public IPhyVertexExport IPhyRigidVertex *r_vtx = NULL; int numverts = mcExport->GetNumberVertices(); // 피직크에 적용이 된 모든 정점들에 대한 정보를 얻는다. for (int i = 0; i < numverts; i++) { float totalWeight = 0.0f, weight = 0.0f; TSTR nodeName; // 독립된 정점(IPhyVertexExport) 을 얻는다. IPhyVertexExport *vi = mcExport->GetVertexInterface(i); if (vi) { // 정점에 적용된 타입을 파악해야 한다. int type = vi->GetVertexType(); switch (type) { case RIGID_BLENDED_TYPE: { rb_vtx = (IPhyBlendedRigidVertex*)vi; // 현 정점에 영향을 미치는 노드의 갯수 int iNode = rb_vtx->GetNumberNodes(); SBipedVertex BipVertex; BipVertex.m_dwNumWeight = iNode; // Point3 BlendP(0.0f,0.0f,0.0f); for (int x = 0; x < iNode; x++) { INode* pNode = rb_vtx->GetNode(x); nodeName = pNode->GetName(); // 전체 노드를 저장하고 있는 SMatrixExport 에서 해당 인덱스를 리턴 받는다. BYTE Index = (BYTE)I_Writer.GetIndex(nodeName); BipVertex.m_BipIDList.push_back(Index); float fWeight = rb_vtx->GetWeight(x); BipVertex.m_fWeightList.push_back(fWeight); // Point3 Offset=rb_vtx->GetOffsetVector(x); // BlendP +=(pNode->GetNodeTM(I_Writer.m_p3dsMax->GetTime())*offset)*fWeight; if (Index < 0) { MessageBox(GetActiveWindow(), _T("No Biped ID."), _T("ERROR !!"), MB_OK | MB_ICONSTOP); break; } } // 최대 가중치 갯수를 저장 if (m_Scene.iMaxweight < iNode) { m_Scene.iMaxweight = iNode; if (m_Scene.iMaxweight > 8) { MessageBox(GetActiveWindow(), _T("바이패드+ 본 + 더미가 정점 당 8 개 이상 적용되었습니다."), _T("최대 적용 에러"), MB_OK | MB_ICONSTOP); } } m_BipedList.push_back(BipVertex); } break; case RIGID_NON_BLENDED_TYPE: { r_vtx = (IPhyRigidVertex*)vi; // 정점에 적용이 된 노드의 이름을 얻는다. INode* pNode = r_vtx->GetNode(); nodeName = pNode->GetName(); SBipedVertex BipVertex; BipVertex.m_dwNumWeight = 1; // 매트릭스 익스포터에서 저장된 모든 노드를 참조해서 // 현 nodeName과 같은 노드를 찾아서 그 인덱스를 리턴한다. BYTE Index = (BYTE)I_Writer.GetIndex(nodeName); BipVertex.m_BipIDList.push_back(Index); BipVertex.m_fWeightList.push_back(1.0f); // 최대 가중치 갯수를 저장 if (m_Scene.iMaxweight < 1) { m_Scene.iMaxweight = 1; } m_BipedList.push_back(BipVertex); if (Index < 0) { MessageBox(GetActiveWindow(), _T("No Biped ID."), _T("Errror !!"), MB_OK | MB_ICONSTOP); break; } } break; default: MessageBox(GetActiveWindow(), _T("Nothing !! Rigid Vertex Type"), _T("Error !!"), MB_OK | MB_ICONSTOP); break; } mcExport->ReleaseVertexInterface(vi); } } phyExport->ReleaseContextInterface(mcExport); phyMod->ReleaseInterface(I_PHYINTERFACE, phyExport); } void S_KHJ_SkinExp::ExportSkinData(INode* node, Modifier *skinMod) { if (node == NULL || skinMod == NULL)return; // get the skin interface ISkin * skin = (ISkin*)skinMod->GetInterface(I_SKIN); ISkinContextData* skinData = skin->GetContextInterface(node); if (skin && skinData) { int numberOFPoints; // 스킨 버텍스의 갯수 numberOFPoints = skinData->GetNumPoints(); for (int i = 0; i < numberOFPoints; i++) { // 연결된 본의 갯수 int numOFWeights = skinData->GetNumAssignedBones(i); SBipedVertex BipVertex; BipVertex.m_dwNumWeight = numOFWeights; for (int j = 0; j < numOFWeights; j++) { int boneIndex = skinData->GetAssignedBone(i, j); INode* pBone = skin->GetBone(boneIndex); if (pBone == NULL)break; const TCHAR* nodeName = nodeName = pBone->GetName(); //skin - >GetBoneName(boneIndex); float boneWeight = skinData->GetBoneWeight(i, j); BYTE Index = (BYTE)I_Writer.GetIndex(nodeName); BipVertex.m_BipIDList.push_back(Index); BipVertex.m_fWeightList.push_back(boneWeight); if (Index < 0) { MessageBox(GetActiveWindow(), _T("No Biped ID"), _T("Error!!"), MB_OK | MB_ICONSTOP); break; } } m_BipedList.push_back(BipVertex); // 최대 가중치 갯수를 저장 if (m_Scene.iMaxweight < numOFWeights) { m_Scene.iMaxweight = numOFWeights; if (m_Scene.iMaxweight > 8) { MessageBox(GetActiveWindow(), _T(" 바이패드 + 본 + 더미가 정점 당 8개 이상 적용되었습니다."), _T("최대 적용 에러 !"), MB_OK | MB_ICONSTOP); } } } } } void S_KHJ_SkinExp::SetBipedInfo(INode* node) { Modifier *phyMod = FindModifier(node, Class_ID(PHYSIQUE_CLASS_ID_A, PHYSIQUE_CLASS_ID_B)); Modifier *skinMod = FindModifier(node, SKIN_CLASSID); if (phyMod) { ExportPhysiqueData(node, phyMod); } else if (skinMod) { ExportSkinData(node, skinMod); } } // 노드에 대한 정보 획득 bool S_KHJ_SkinExp::GetNodeInfo(INode* node, TimeValue t) { // 랜더가능한 데이터 정보 버퍼 저장. BOOL needDel; TriObject *tri = I_Writer.GetTriObjectFromNode(node, t, needDel); if (tri == NULL)return false; Mesh * mesh = &tri->GetMesh(); mesh->buildNormals(); if (!mesh->faces || !tri || !mesh || !mesh->getNumFaces() || !mesh->getNumVerts() || !mesh->getNumTVerts()) { return false; } SetBipedInfo(node); SSkinMesh* SkinMesh = NULL; SAFE_NEW(SkinMesh, SSkinMesh); // 메쉬를 저장한다. (서브메터리얼 여부를 판단하여 저장) GenerateGroup(node, mesh, SkinMesh); if (needDel) { delete tri; } return true; } void S_KHJ_SkinExp::SetVertexBiped(INode* node, Face* face, int v0, int v1, int v2, SSkinTri* pTri) { int iNumWeight = 1; if (m_BipedList.size()) { iNumWeight = m_BipedList[face->v[v0]].m_BipIDList.size(); for (int iBip = 0; iBip < iNumWeight; iBip++) { if (iBip < 4) { pTri->m_vVertex[0].i1[iBip] = m_BipedList[face->v[v0]].m_BipIDList[iBip]; pTri->m_vVertex[0].w1[iBip] = m_BipedList[face->v[v0]].m_fWeightList[iBip]; } else { pTri->m_vVertex[0].i2[iBip - 4] = m_BipedList[face->v[v0]].m_BipIDList[iBip]; pTri->m_vVertex[0].w2[iBip - 4] = m_BipedList[face->v[v0]].m_fWeightList[iBip]; } } iNumWeight = m_BipedList[face->v[v2]].m_BipIDList.size(); for (int iBip = 0; iBip < iNumWeight; iBip++) { if (iBip < 4) { pTri->m_vVertex[1].i1[iBip] = m_BipedList[face->v[v2]].m_BipIDList[iBip]; pTri->m_vVertex[1].w1[iBip] = m_BipedList[face->v[v2]].m_fWeightList[iBip]; } else { pTri->m_vVertex[1].i2[iBip - 4] = m_BipedList[face->v[2]].m_BipIDList[iBip]; pTri->m_vVertex[1].w2[iBip - 4] = m_BipedList[face->v[2]].m_fWeightList[iBip]; } } iNumWeight = m_BipedList[face->v[v1]].m_BipIDList.size(); for (int iBip = 0; iBip < iNumWeight; iBip++) { if (iBip < 4) { pTri->m_vVertex[2].i1[iBip] = m_BipedList[face->v[v1]].m_BipIDList[iBip]; pTri->m_vVertex[2].w1[iBip] = m_BipedList[face->v[v1]].m_fWeightList[iBip]; } else { pTri->m_vVertex[2].i2[iBip - 4] = m_BipedList[face->v[v1]].m_BipIDList[iBip]; pTri->m_vVertex[2].w2[iBip - 4] = m_BipedList[face->v[v1]].m_fWeightList[iBip]; } } // 정점 당 가중치 적용 갯수 pTri->m_vVertex[0].w2[3] = m_BipedList[face->v[v0]].m_dwNumWeight; pTri->m_vVertex[1].w2[3] = m_BipedList[face->v[v2]].m_dwNumWeight; pTri->m_vVertex[2].w2[3] = m_BipedList[face->v[v1]].m_dwNumWeight; } else { // 정점에 적용된 바이패드가 없다는 것은 자체 애니메이션을 가진 오브젝트가 된다. // 이때는 가중치를 얻을 수 없기 떄문에 직접 1개의 가중치 값을 세팅해 주어야 한다. int iBipIndex = I_Writer.GetIndex(node->GetName()); pTri->m_vVertex[0].i1[0] = iBipIndex; pTri->m_vVertex[0].w1[0] = 1.0f; pTri->m_vVertex[1].i1[0] = iBipIndex; pTri->m_vVertex[1].w1[0] = 1.0f; pTri->m_vVertex[2].i1[0] = iBipIndex; pTri->m_vVertex[2].w1[0] = 1.0f; // 가중치 적용 갯수 pTri->m_vVertex[0].w2[3] = 1.0f; pTri->m_vVertex[1].w2[3] = 1.0f; pTri->m_vVertex[2].w2[3] = 1.0f; } } void S_KHJ_SkinExp::SetTriangle(INode* node, Mesh* mesh, SSkinMesh* pSkinMesh, SSkinMesh*pSubMesh, int iMtrl) { SSkinMesh* pMesh = NULL; if (pSubMesh == NULL) { pMesh = pSkinMesh; } else { pMesh = pSubMesh; } // 원하는 시점 (I_Writer.m_p3dsMax->GetTime() 에서 월드 행렬을 얻는다. Matrix3 tm = node->GetObjTMAfterWSM(I_Writer.m_Interval.Start()); // .m_p3dsMax->GetTime(); Matrix3 nodetm = node->GetNodeTM(I_Writer.m_Interval.Start()); I_Writer.DumpMatrix3(&nodetm, pSkinMesh->m_matWorld); int v0, v1, v2; v0 = 0, v1 = 1, v2 = 2; if (I_Writer.TMNegParity(tm)) { v0 = 2, v1 = 1, v2 = 0; } Matrix3 invTM = Inverse(nodetm); for (int i = 0; i < mesh->getNumFaces(); i++) { // 서브매터리얼 사용시는 그룹화 해야하기 때문에 해당 매터리얼이 아닐시 반복시킴 if (pMesh->m_iMtrlRef > 0 && mesh->faces[i].getMatID() != iMtrl) { continue; } SSkinTri Triangle; // 페이스 리스트 초기화 memset(&Triangle, 0, sizeof(STri)); // 서브 매터리얼 인덱스 Triangle.iSubIndex = mesh->faces[i].getMatID(); // 정점 위치 저장 if(mesh->getNumVerts()>0) { SetVertexBiped(node, &mesh->faces[i], v0, v1, v2, &Triangle); for (int iVertex = 0; iVertex < 3; iVertex++) { Point3 v; if (iVertex == 0) v = tm * mesh->verts[mesh->faces[i].v[v0]]; else if (iVertex == 1) v = tm * mesh->verts[mesh->faces[i].v[v2]]; else v = tm * mesh->verts[mesh->faces[i].v[v1]]; //v = invTM * v; Triangle.m_vVertex[iVertex].p.x = v.x; Triangle.m_vVertex[iVertex].p.y = v.z; Triangle.m_vVertex[iVertex].p.z = v.y; } } // 정점 텍스쳐좌표 저장 if (mesh->getNumTVerts() > 0) { Triangle.m_vVertex[0].t.x = mesh->tVerts[mesh->tvFace[i].t[v0]].x; Triangle.m_vVertex[0].t.y = 1.0f - mesh->tVerts[mesh->tvFace[i].t[v0]].y; Triangle.m_vVertex[1].t.x = mesh->tVerts[mesh->tvFace[i].t[v2]].x; Triangle.m_vVertex[1].t.y = 1.0f - mesh->tVerts[mesh->tvFace[i].t[v2]].y; Triangle.m_vVertex[2].t.x = mesh->tVerts[mesh->tvFace[i].t[v1]].x; Triangle.m_vVertex[2].t.y = 1.0f - mesh->tVerts[mesh->tvFace[i].t[v1]].y; } // 정점 컬러 저장 Triangle.m_vVertex[0].c = Point4(1.0f, 1.0f, 1.0f, 1.0f); Triangle.m_vVertex[1].c = Point4(1.0f, 1.0f, 1.0f, 1.0f); Triangle.m_vVertex[2].c = Point4(1.0f, 1.0f, 1.0f, 1.0f); if (mesh->getNumVertCol() > 0) { Triangle.m_vVertex[0].c.w = 0xff; Triangle.m_vVertex[0].c.x = mesh->vertCol[mesh->vcFace[i].t[v0]].x; Triangle.m_vVertex[0].c.y = mesh->vertCol[mesh->vcFace[i].t[v0]].y; Triangle.m_vVertex[0].c.z = mesh->vertCol[mesh->vcFace[i].t[v0]].z; Triangle.m_vVertex[1].c.w = 0xff; Triangle.m_vVertex[1].c.x = mesh->vertCol[mesh->vcFace[i].t[v2]].x; Triangle.m_vVertex[1].c.y = mesh->vertCol[mesh->vcFace[i].t[v2]].y; Triangle.m_vVertex[1].c.z = mesh->vertCol[mesh->vcFace[i].t[v2]].z; Triangle.m_vVertex[2].c.w = 0xff; Triangle.m_vVertex[2].c.x = mesh->vertCol[mesh->vcFace[i].t[v1]].x; Triangle.m_vVertex[2].c.y = mesh->vertCol[mesh->vcFace[i].t[v1]].y; Triangle.m_vVertex[2].c.z = mesh->vertCol[mesh->vcFace[i].t[v1]].z; } // 정점 노말 및 페이스 노말 저장 Point3 vn, fn; // Vertex normal, Face normal int vert; Face* f; f = &mesh->faces[i]; vert = f->getVert(v0); vn = I_Writer.GetVertexNormal(mesh, i, mesh->getRVertPtr(vert)); Triangle.m_vVertex[0].n.x = vn.x; Triangle.m_vVertex[0].n.y = vn.z; Triangle.m_vVertex[0].n.z = vn.y; vert = f->getVert(v2); vn = I_Writer.GetVertexNormal(mesh, i, mesh->getRVertPtr(vert)); Triangle.m_vVertex[1].n.x = vn.x; Triangle.m_vVertex[1].n.y = vn.z; Triangle.m_vVertex[1].n.z = vn.y; vert = f->getVert(v1); vn = I_Writer.GetVertexNormal(mesh, i, mesh->getRVertPtr(vert)); Triangle.m_vVertex[2].n.x = vn.x; Triangle.m_vVertex[2].n.y = vn.z; Triangle.m_vVertex[2].n.z = vn.y; pMesh->m_SkinTriList.push_back(Triangle); } pMesh->m_iNumFace = pMesh->m_SkinTriList.size(); } void S_KHJ_SkinExp::GenerateGroup(INode* node, Mesh *mesh, SSkinMesh* pSkinMesh) { Mtl* mtl = node->GetMtl(); pSkinMesh->m_strNodeName = node->GetName(); if (mtl) { pSkinMesh->m_iMtrlRef = mtl->NumSubMtls(); } if (pSkinMesh->m_iMtrlRef > 0) { for (int imtl = 0; imtl < pSkinMesh->m_iMtrlRef; imtl++) { SSkinMesh* pSubSkinMesh = NULL; SAFE_NEW(pSubSkinMesh, SSkinMesh); // 맥스 서브메터리얼 정보 저장 Mtl* subMtl = mtl->GetSubMtl(imtl); LoadMaterial(pSubSkinMesh, subMtl); // 매쉬를 이루는 페이스리스트를 만든다. SetTriangle(node, mesh, pSkinMesh, pSubSkinMesh, imtl); pSkinMesh->m_pSubMesh.push_back(pSubSkinMesh); } } else { LoadMaterial(pSkinMesh, mtl); // 매쉬를 이루는 페이스리스트를 만든다. SetTriangle(node, mesh, pSkinMesh); } } void S_KHJ_SkinExp::LoadMaterial(SSkinMesh* pMesh, Mtl* mtl) { if (mtl) { pMesh->m_iNumTex = 0; memset(pMesh->m_szTexName, 0, sizeof(TCHAR) * 13 * 30); for (int i = 0; i < mtl->NumSubTexmaps(); i++) { Texmap* subTex = mtl->GetSubTexmap(i); float amt = 1.0f; if (subTex) { if (mtl->ClassID() == Class_ID(DMTL_CLASS_ID, 0)) { if (!((StdMat*)mtl)->MapEnabled(i)) continue; } if (subTex->ClassID() == Class_ID(BMTEX_CLASS_ID, 0x00)) { pMesh->m_iTexType[pMesh->m_iNumTex] = GetMapID(mtl->ClassID(), i); TSTR mapName = ((BitmapTex *)subTex)->GetMapName(); TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; _tsplitpath_s(I_Writer.FixupName(mapName), Drive, Dir, FName, Ext); Ext[4] = 0; _stprintf_s(pMesh->m_szTexName[pMesh->m_iNumTex], _T("%s%s"), FName, Ext); pMesh->m_iNumTex++; } } } } } // 피직크 검색 Modifier* S_KHJ_SkinExp::FindModifier(INode *nodePtr, Class_ID classID) { Object *ObjectPtr = nodePtr->GetObjectRef(); if (!ObjectPtr) { return NULL; } while (ObjectPtr->SuperClassID() == GEN_DERIVOB_CLASS_ID && ObjectPtr) { IDerivedObject *DerivedObjectPtr = (IDerivedObject *)(ObjectPtr); int ModStackIndex = 0; while (ModStackIndex < DerivedObjectPtr->NumModifiers()) { Modifier* ModifierPtr = DerivedObjectPtr->GetModifier(ModStackIndex); if (ModifierPtr->ClassID() == classID) { return ModifierPtr; } ModStackIndex++; } ObjectPtr = DerivedObjectPtr->GetObjRef(); } return NULL; } int S_KHJ_SkinExp::GetMapID(Class_ID cid, int subNo) { int iResultIndex = 1; if (cid == Class_ID(0, 0)) { iResultIndex = 30; } else if (cid == Class_ID(DMTL_CLASS_ID, 0)) { switch (subNo) { case ID_AM: iResultIndex = 0; break; case ID_DI: iResultIndex = 1; break; case ID_SP: iResultIndex = 2; break; case ID_SH: iResultIndex = 3; break; case ID_SS: iResultIndex = 4; break; case ID_SI: iResultIndex = 5; break; case ID_OP: iResultIndex = 6; break; case ID_FI: iResultIndex = 7; break; case ID_BU: iResultIndex = 8; break; case ID_RL: iResultIndex = 9; break; case ID_RR: iResultIndex = 10; break; } } else { iResultIndex = 31; } return iResultIndex; } int S_KHJ_SkinExp::IsEqulVertexList(vector<PNCT5_VERTEX>& VertexArray, PNCT5_VERTEX& Vertex) { for (int iVertex = 0; iVertex < VertexArray.size(); iVertex++) { if (I_Writer.EqualPoint3(VertexArray[iVertex].p, Vertex.p) && I_Writer.EqualPoint3(VertexArray[iVertex].n, Vertex.n) && I_Writer.EqualPoint4(VertexArray[iVertex].c, Vertex.c) && I_Writer.EqualPoint2(VertexArray[iVertex].t, Vertex.t)) { return iVertex; } } return -1; } bool S_KHJ_SkinExp::skmExport() { int iSkinMeshCount = m_SkinMeshList.size(); if (iSkinMeshCount <= 0) { MessageBox(NULL, _T("출력할 정보가 없습니다."), _T("파일생성에러"), MB_ICONERROR); return FALSE; } TCHAR szFile[256] = { 0, }; _tcscpy(szFile, I_Writer.SaveFileDlg(_T("skm"), _T("TSkinExport"))); FILE *fp; fp = _tfopen(szFile, _T("wb")); if (!fp) { MessageBox(NULL, _T("파일을 생성하지 못했습니다."), _T("파일생성에러"), MB_ICONERROR); return FALSE; } struct tm *newtime; time_t aclock; time(&aclock); newtime = localtime(&aclock); fwrite(newtime, sizeof(tm), 1, fp); m_Scene.iNumMesh = m_SkinMeshList.size(); fwrite(&m_Scene, sizeof(SScene), 1, fp); for (SSKINMESH_VECTOR::iterator iter = m_SkinMeshList.begin(); iter != m_SkinMeshList.end(); iter++) { SSkinMesh* pMesh = (*iter); TCHAR szName[256] = { 0, }; TCHAR szParentName[256] = { 0, }; // 노드 이름 int iLen = pMesh->m_strNodeName.Length(); fwrite(&iLen, sizeof(int), 1, fp); if (iLen > 0) { _tcscpy(szName, pMesh->m_strNodeName); fwrite(szName, sizeof(TCHAR)*iLen, 1, fp); } // 노드 부모 이름 iLen = pMesh->m_strParentName.Length(); _tcscpy(szParentName, pMesh->m_strParentName); fwrite(&iLen, sizeof(int), 1, fp); if (iLen > 0) { fwrite(szParentName, sizeof(TCHAR)*iLen, 1, fp); } // 월드 행렬 fwrite(&pMesh->m_matWorld, sizeof(D3D_MATRIX), 1, fp); // 서브매터리얼 개수 int iRealSubMtrlConter = pMesh->m_pSubMesh.size(); fwrite(&iRealSubMtrlConter, sizeof(int), 1, fp); if (iRealSubMtrlConter <= 0) { ExportMesh(fp, pMesh); } else { for (int iMesh = 0; iMesh < pMesh->m_pSubMesh.size(); iMesh++) { SSkinMesh* pSubMesh = pMesh->m_pSkinSubMesh[iMesh]; ExportMesh(fp, pSubMesh); } } } // 드레스 포즈의 각 바이패드 행렬 출력 MATRIXINDEX* matIndex; D3D_MATRIX d3dMat; int iNumMatrix = I_Writer.m_MatrixMap.TMap.size(); fwrite(&iNumMatrix, sizeof(int), 1, fp); for (int iMat = 0; iMat < iNumMatrix; iMat++) { matIndex = I_Writer.m_MatrixMap.GetPtr(iMat); I_Writer.DumpMatrix3(&matIndex->m_InvNodeTM, d3dMat); fwrite(&d3dMat, sizeof(D3D_MATRIX), 1, fp); } fclose(fp); Release(); MessageBox(GetActiveWindow(), szFile, _T("Succeed!!"), MB_OK); return true; } bool S_KHJ_SkinExp::ExportMesh(FILE* fp, SSkinMesh* pMesh) { vector <PNCT5_VERTEX> VertexArray; vector < unsigned int> IndexArray; VertexArray.reserve(pMesh->m_iNumFace * 3); IndexArray.reserve(pMesh->m_iNumFace * 3); int iPosPushCnt = 0; for (int iFace = 0; iFace < pMesh->m_iNumFace; iFace++) { for (int iCnt = 0; iCnt < 3; iCnt++) { int iPosReturn = IsEqulVertexList(VertexArray, pMesh->m_SkinTriList[iFace].m_vVertex[iCnt]); if (iPosReturn < 0) { // 서브매터리얼 인덱스 => 정점 알파성분에 대입 //pMesh->m_SkinTriList[iFace].m_vVertex[iCnt].c.w = pMesh->m_SkinTriList[iFace].iSubIndex; VertexArray.push_back(pMesh->m_SkinTriList[iFace].m_vVertex[iCnt]); iPosReturn = iPosPushCnt++; } IndexArray.push_back(iPosReturn); } } pMesh->m_iNumVertex = VertexArray.size(); fwrite(&pMesh->m_iNumVertex, sizeof(int), 1, fp); fwrite(&pMesh->m_iNumFace, sizeof(int), 1, fp); fwrite(&pMesh->m_iNumTex, sizeof(int), 1, fp); fwrite(&VertexArray.at(0), sizeof(PNCT5_VERTEX) * VertexArray.size(), 1, fp); fwrite(&IndexArray.at(0), sizeof(unsigned int) * IndexArray.size(), 1, fp); for (int itex = 0; itex < pMesh->m_iNumTex; itex++) { int iLen = _tcslen(pMesh->m_szTexName[itex]); fwrite(&iLen, sizeof(int), 1, fp); fwrite(&pMesh->m_iTexType[itex], sizeof(int), 1, fp); fwrite(pMesh->m_szTexName[itex], sizeof(TCHAR) * iLen, 1, fp); } return true; } bool S_KHJ_SkinExp::Release() { m_BipedList.clear(); for (SSKINMESH_VECTOR::iterator iter = m_SkinMeshList.begin(); iter != m_SkinMeshList.end(); iter++) { SSkinMesh* pMesh = (*iter); if (pMesh->m_iMtrlRef > 0) { pMesh->m_pSkinSubMesh.clear(); for (int imtl = 0; imtl < pMesh->m_iMtrlRef; imtl++) { //SAFE_DEL( pMesh->m_pSkinSubMesh[imtl] ); } } SAFE_DEL(pMesh); } m_SkinMeshList.clear(); return true; } S_KHJ_SkinExp::S_KHJ_SkinExp(void) { Init(); } S_KHJ_SkinExp::~S_KHJ_SkinExp(void) { Release(); } <file_sep>#ifndef __AVL_REBALANCE_H__ #define __AVL_BEBALANCE_H__ #include "TBTree.h" BTreeNode* Rebalance(BTreeNode** pRoot); #endif<file_sep>//#pragma once //#include "xStd.h" //#include "XTemplate.h" //class xTexture //{ //public: // T_STR m_szName; // T_STR m_szPath; //public: // ID3D11ShaderResourceView* m_pTextureRV; // ID3D11SamplerState* m_pSamplerState; // D3D11_SAMPLER_DESC m_SampleDesc; //public: // HRESULT Load(ID3D11Device* pDevice, const TCHAR* strFilePath); // bool Apply(ID3D11DeviceContext* plmmediateContext); // bool Release(); // void SetPath(const TCHAR* pPath); //public: // xTexture(void); // virtual ~xTexture(void); //}; // //class XTextureMgr : public TSingleton<XTextureMgr> //{ //private: // friend class TSingleton<XTextureMgr>; // ID3D11Device* m_pd3dDevice; // ID3D11DeviceContext* m_plmmediateContext; //public: // typedef unordered_map <INT, xTexture*> TemplateMap; // typedef TemplateMap::iterator TemplateMapItor; // TemplateMapItor TItor; // TemplateMap TMap; // INT m_iCurIndex; //public: // INT Add(ID3D11Device* pDevice, const TCHAR* pFileName); // INT Add(ID3D11Device* pDevice, const TCHAR* pFileName, const TCHAR* szPath); // xTexture* const Getptr(INT iIndex); // xTexture* const Getptr(T_STR strFindName); // bool Release(); //public: // XTextureMgr(); // virtual ~XTextureMgr(); //}; //#define I_Texture XTextureMgr::GetInstance() <file_sep>#include "Sample.h" // 디바이스 생성-1- bool Sample::Init() { HRESULT hr; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = m_iWindowWidth; sd.BufferDesc.Height = m_iWindowHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = m_hWnd; sd.SampleDesc.Count = 1; sd.Windowed = TRUE; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { m_DriverType = driverTypes[driverTypeIndex]; if (SUCCEEDED(hr = D3D11CreateDeviceAndSwapChain( NULL, m_DriverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &m_pSwapChain, &m_pd3dDevice, &m_FeatureLevel, &m_plmmediateContext))) { if (FAILED(hr) || m_FeatureLevel < D3D_FEATURE_LEVEL_11_0) { if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); continue; } break; } } if (FAILED(hr)) { return true; } ///////////////////////// // Create a Render target view ID3D11Texture2D* pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if (FAILED(hr)) return false; hr = m_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); if (FAILED(hr))return false; m_plmmediateContext->OMSetRenderTargets(1, &m_pRenderTargetView, NULL); ////////////////////////////// DXGI_SWAP_CHAIN_DESC Desc; m_pSwapChain->GetDesc(&Desc); // Setup the viewport m_ViewPort.Width = (FLOAT)Desc.BufferDesc.Width; m_ViewPort.Height = (FLOAT)Desc.BufferDesc.Height; m_ViewPort.MaxDepth = 0.0f; m_ViewPort.MinDepth = 1.0; m_ViewPort.TopLeftX = 0; m_ViewPort.TopLeftY = 0; m_plmmediateContext->RSSetViewports(1, &m_ViewPort); return true; } bool Sample::Render() { // 백버퍼를 지운다. float clearColor[4] = { 0.0f,0.125f,0.3f,1.0f }; //red,green,blue,alpha m_plmmediateContext->ClearRenderTargetView(m_pRenderTargetView, clearColor); m_pSwapChain->Present(0, 0); return true; } bool Sample::Release() { if (m_plmmediateContext)m_plmmediateContext->ClearState(); if (m_plmmediateContext)m_pRenderTargetView->Release(); if (m_pSwapChain)m_pSwapChain->Release(); if (m_plmmediateContext)m_plmmediateContext->Release(); if (m_pd3dDevice)m_pd3dDevice->Release(); m_pd3dDevice = NULL; m_pSwapChain = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; return true; } Sample::Sample(void) { m_pd3dDevice = NULL; m_pSwapChain = NULL; m_pRenderTargetView = NULL; m_plmmediateContext = NULL; } Sample::~Sample(void) { } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { Sample gSample; if (!gSample.InitWindow(hInstance, nCmdShow, L"CreateDevice_0")) { MessageBox(0, _T("Sample 초기화 실패"), _T("Fatal error"), MB_OK); return 0; } ShowCursor(TRUE); gSample.Run(); return 1; }<file_sep>#include "xShape.h" HRESULT xSphereShape::CreateVertexBuffer() { HRESULT hr = S_OK; m_iVertexSize = sizeof(PNCT_VERTEX); DX::CreateVertexBuffer(m_pd3dDevice, m_iNumVertex, sizeof(PNCT_VERTEX), &m_vList.at(0), m_dxObj.m_pVertexBuffer.GetAddressOf()); return hr; } // 로칼 정점의 크기를 정규화하여 1로 만든다. PNCT_VERTEX xSphereShape::NormalizeVertex( PNCT_VERTEX Vertex) { PNCT_VERTEX newvertex;// = (PNCT_VERTEX)0; D3DXVec3Normalize(&newvertex.p, &Vertex.p); // 정점이 원점을 중심으로 하는 노말 벡터가 된다. newvertex.n = newvertex.p; newvertex.c = Vertex.c; newvertex.t = Vertex.t; return newvertex; } void xSphereShape::TriAppend( PNCT_VERTEX V0, PNCT_VERTEX V1, PNCT_VERTEX V2, vector<PNCT_VERTEX>& TriStream, int iIndex) { TriStream[iIndex + 0] = NormalizeVertex(V0); TriStream[iIndex + 1] = NormalizeVertex(V1); TriStream[iIndex + 2] = NormalizeVertex(V2); } HRESULT xSphereShape::CreateVertexData() { xBoxShape::CreateVertexData(); xBoxShape::CreateIndexData(); vector<PNCT_VERTEX> vList; vList.resize(m_IndexList.size()); m_vList.resize((m_IndexList.size() / 3) * 12); for (int iFace = 0; iFace < 12; iFace++) { int iCount = iFace * 3; vList[iCount+ 0] = m_VertexList[m_IndexList[iCount + 0]]; vList[iCount + 1] = m_VertexList[m_IndexList[iCount + 1]]; vList[iCount + 2] = m_VertexList[m_IndexList[iCount + 2]]; } int iIndex = 0; for (int iFace = 0; iFace < 12; iFace++) { PNCT_VERTEX input[3]; input[0] = vList[iFace * 3 + 0]; input[1] = vList[iFace * 3 + 1]; input[2] = vList[iFace * 3 + 2]; PNCT_VERTEX Center0, Center1, Center2; Center0.p = D3DXVECTOR3((input[0].p + input[1].p) / 2.0); Center0.n = (input[0].n + input[1].n) / 2.0; Center0.c = (input[0].c + input[1].c) / 2.0; Center0.t = (input[0].t + input[1].t) / 2.0; Center1.p = D3DXVECTOR3((input[1].p + input[2].p) / 2.0); Center1.n = (input[1].n + input[2].n) / 2.0; Center1.c = (input[1].c + input[2].c) / 2.0; Center1.t = (input[1].t + input[2].t) / 2.0; Center2.p = D3DXVECTOR3((input[0].p + input[2].p) / 2.0); Center2.n = (input[0].n + input[2].n) / 2.0; Center2.c = (input[0].c + input[2].c) / 2.0; Center2.t = (input[0].t + input[2].t) / 2.0; TriAppend(input[0], Center0, Center2, m_vList, iIndex); iIndex += 3; TriAppend(Center0, input[1], Center1, m_vList, iIndex); iIndex += 3; TriAppend(input[2], Center2, Center1, m_vList, iIndex); iIndex += 3; TriAppend(Center0, Center1, Center2, m_vList, iIndex); iIndex += 3; } m_iNumVertex = m_vList.size(); m_iNumIndex = m_vList.size(); return S_OK; }; HRESULT xSphereShape::LoadVertexShader(T_STR szName) { HRESULT hr = S_OK; m_dxObj.m_pVertexShader.Attach( DX::LoadVertexShaderFile(m_pd3dDevice, szName.c_str(), m_dxObj.m_pVSBlob.GetAddressOf(), "VS_NoMatrix")); return hr; } HRESULT xSphereShape::LoadGeometryShader(T_STR szName) { return xShape::LoadGeometryShader(szName); } xSphereShape::xSphereShape() { } xSphereShape::~xSphereShape() { }<file_sep>#pragma once #include "TEmployee.h" class TPermanent : public TEmployee { private: int salary; // ±âº»±Þ¿© public: int GetPay(); public: TPermanent(char* _name,int sal); ~TPermanent(); }; <file_sep>#include "SStudent.h" void SStudent::Print() { cout << "번호 : " << sData.iindex << endl; cout << "이름 : " << sData.strName << endl; cout << "국어 : " << sData.iKor << endl; cout << "영어 : " << sData.iEng << endl; cout << "수학 : " << sData.iMat << endl; cout << "총합 : " << sData.iTotal << endl; cout << "평균 : " << sData.Average << endl << endl; system("pause"); } void SStudent::inputData(int Cnt) { sData.strName[0] = 65 + rand() % 26; sData.strName[1] = 65 + rand() % 26; sData.strName[2] = 65 + rand() % 26; sData.strName[3] = '\0'; sData.iindex = Cnt; sData.iKor = rand() % 101; sData.iEng = rand() % 101; sData.iMat = rand() % 101; sData.iTotal = sData.iKor + sData.iEng + sData.iMat; sData.Average = sData.iTotal / 3.0f; } void SStudent::SetData(char strName[],int iindex,int iKor,int iEng,int iMat,int iTotal,float Average) { sData.iindex = iindex; sData.iKor = iKor; sData.iEng = iEng; sData.iMat = iMat; sData.iTotal = iTotal; sData.Average = Average; strcpy(sData.strName, strName); } StudentData SStudent::GetData() { return sData; } SStudent::SStudent() { } SStudent::~SStudent() { } <file_sep>#include<stdio.h> //get () 함수를 이용한 문자열 //void main() //{ // char input[81], *ptr; // puts("Enter a line, then press Enter"); // puts("Enter a blank line when done."); // while (*(ptr = gets(input)) != NULL) // { // printf("You enterd %s\n", input); // } //} void main() { char letters[5]; int i; for (i = 0; i < 5; i++) { letters[i] = getchar(); } for (i = 4; i >= 0; i++) { putchar(letters[i]); } }<file_sep>#pragma once #include "SvrStd.h" #include <process.h> #include "sProtocolClient.h" #include "SUser.h" class SCHAT_Client : public SUser { public: int m_iSocket; unsigned long m_hSendThread; unsigned long m_hReceiveThread; bool m_bExit; public: char m_strBuffer[128]; bool m_bSend; bool m_bLoginOK; public: bool Init(); bool Frame(); bool Release(); public: int CreateConnectSocket(int iPort); int SendMsg(char* pMsg, WORD code); int SendMsg(char* pMsg, int iSize, WORD code); int ProcessPacket(); public: SCHAT_Client(void); virtual ~SCHAT_Client(void); }; <file_sep>#ifndef MUTEX_SAMPLE #define MUTEX_SAMPLE #include "SProtocol.h" #pragma pack(push,1) typedef struct { int User_iIndex; BYTE POS_X; BYTE POS_Y; BYTE bDirection; }SPACKET_USER_POSITON; #define PACKET_USER_POSITON 3000 typedef struct { int UserIndex; char User_ID[21]; char User_PS[15]; }SPACKET_USER_LOGIN; #define PACKET_USER_LOGIN 2000 #define PACEKT_CHAT_NAME_REQ 1000 // 대화명 입력 #define PACKET_CHAT_NAME_ACK 1001 // 대화명 입력 전송 #define PACKET_CHAT_MSG 1002 // 대화명 입력 전송 #pragma pack(pop) #endif<file_sep>#include "FWindow.h" FWindow::FWindow() { } FWindow::~FWindow() { } <file_sep>#include "SChatUser.h" #include "SChatSvr.h" void SChatUser::Movement(UPACKET* pPacket) { SPACKET_USER_POSITION user; memcpy(&user, pPacket->msg, sizeof(char)*pPacket->ph.len - 4); m_iIndex = user.user_idx; m_PositionX = user.PosX; m_PositionY = user.PosY; m_iDirection = user.direction; } void SChatUser::AddPacket(S_PACKET& addPacket) { I_Server.m_PacketPool.AddPacket(addPacket); } void SChatUser::DeleteUser(SOCKET socket) { I_Server.DeleteUser(socket); } void SChatUser::DeleteUser() { I_Server.DeleteUser(this); } void SChatUser::Dispatch(DWORD dwByteSize, LPOVERLAPPED ov) { OVERLAPPEDEX* pOV = (OVERLAPPEDEX*)ov; if (dwByteSize == 0)return; if (pOV->iFlags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put(m_szRecvBuffer.buf, dwByteSize, this); } if (pOV->iFlags == OVERLAPPEDEX::MODE_SEND) { } WaitForPacketReceive(); } SChatUser::SChatUser(void) { } SChatUser::~SChatUser(void) { } <file_sep>#include "TAcceptor.h" #include "TUser.h" #include "TServer.h" #include "stdio.h" #include "TServerIOCP.h" #include "TDebugString.h" bool TAcceptor::Release() { return true; } bool TAcceptor::Run() { SOCKET clientSocket; SOCKADDR_IN clientaddr; int addrlen; while(m_bStarted) { addrlen = sizeof( clientaddr ); clientSocket = accept( m_ListenSock, (SOCKADDR*)&clientaddr, &addrlen ); if( clientSocket == INVALID_SOCKET ) { continue; } AddUser(clientSocket,clientaddr); Sleep(10); } return true; } void TAcceptor::AddUser(SOCKET socket, SOCKADDR_IN address ) { char buf[255] = { 0, }; InetNtopA(AF_INET, &address.sin_addr, buf, sizeof(char) * 255); } bool TAcceptor::Set( int iPort, const char* strAddress) { int iRet; WSADATA wd; WSAStartup( MAKEWORD(2,2), &wd); ///////////////////////////////// // ///////////////////////////////// m_ListenSock = socket( AF_INET, SOCK_STREAM, 0 ); if( m_ListenSock == INVALID_SOCKET ) { return false; } SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; if( strAddress == NULL ) { serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); }else { serveraddr.sin_addr.s_addr = inet_addr(strAddress); } serveraddr.sin_port = htons(iPort); iRet = ::bind(m_ListenSock, (SOCKADDR*)&serveraddr, sizeof(SOCKADDR)); if (iRet == SOCKET_ERROR) { switch (WSAGetLastError()) { case WSAEADDRINUSE : case WSAEACCES: I_Debug.T_ERROR(); break; } return false; } iRet = listen( m_ListenSock, SOMAXCONN ); if( iRet == SOCKET_ERROR ) return false; char cFlag = 1; if (SOCKET_ERROR == setsockopt(m_ListenSock, IPPROTO_TCP, TCP_NODELAY, &cFlag, sizeof(char))) { return FALSE; } // SO_REUSEADDR & SO_EXCLUSIVEADDRUSE 둘 중에 하나만 사용한다. // 윈도우 -> SO_EXCLUSIVEADDRUSE // 리눅스 -> SO_REUSEADDR 이 적당하다. /*int optval = 1; iRet = setsockopt( m_ListenSock, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); if (iRet == SOCKET_ERROR) { I_Debug.T_ERROR(); }*/ int optvalexe = 1; iRet = setsockopt(m_ListenSock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&optvalexe, sizeof(optvalexe)); if (iRet == SOCKET_ERROR) { I_Debug.T_ERROR(); } linger optval2; int iSize = sizeof(optval2); optval2.l_linger = 1000; optval2.l_onoff = 1; getsockopt( m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, &iSize); setsockopt( m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, iSize); int socketType1; int typeLen1 = sizeof(socketType1); getsockopt( m_ListenSock, SOL_SOCKET, SO_TYPE, (char*)&socketType1, &typeLen1); //if( socketType1 == SOCK_STREAM ) if (getsockopt( m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1)< 0) { I_Debug.T_ERROR(); } if (getsockopt( m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1)< 0) { I_Debug.T_ERROR(); } int sdnBufferSize = 10000; int sndBufferSizeLen = sizeof(sndBufferSizeLen); if (setsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&sdnBufferSize, sndBufferSizeLen) < 0 ) { I_Debug.T_ERROR(); } int rcvBufferSizeLen = sizeof(int); int rcvBufferSize = 10000; if (setsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&rcvBufferSize, rcvBufferSizeLen)< 0) { I_Debug.T_ERROR(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { I_Debug.T_ERROR(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { I_Debug.T_ERROR(); } // 쓰레드 생성 CreateThread(); return true; } TAcceptor::TAcceptor(void) { } TAcceptor::~TAcceptor(void) { } <file_sep>#include "SServerObj.h" SServerObj::SServerObj(void) { InitializeCriticalSection(&m_cs); // 임계영역 초기화 함수 } SServerObj::~SServerObj(void) { DeleteCriticalSection(&m_cs); // 임계 영역 소멸 함수 } <file_sep>#include <iostream> #include <time.h> void DataPrint(int list[], int iNum) { //return; for (int i = 0; i < iNum; i++) { std::cout << list[i] << " "; } std::cout << std::endl<<std::endl; } void SetData(int list[], int iNum) { srand(time(NULL)); for (int i = 0; i < iNum; i++) { list[i] = rand() % 100; } DataPrint(list, iNum); } bool swap(int& a, int& b) { if (a > b) { int temp = a; a = b; b = temp; return true; } return false; } void change(int& a, int& b) { if (a > b) { int temp = a; a = b; b = temp; } } void SelectionSort(int list[], int iNum) { for (int i = 0; i < iNum; i++) { for (int j = i + 1; j < iNum; j++) { swap(list[i], list[j]); } } } void insertionSort(int list[], int iNum, int s = 1, int step = 1) { for (int i = s; i < iNum; i += step) { int temp = list[i]; int j = i - step; for (; j >= 0; j -= step) { int temp = list[i]; if (list[j] > temp) { list[j + step] = list[j]; continue; } swap(list[i], list[j]); break; } list[j + step] = temp; } } void bubbleSort(int list[], int iNum) { for (int i = 0; i < iNum - 1; i++) { bool bflag = false; for (int j = i + 1; j < iNum - i - 1; j++) { if(bflag = swap(list[j], list[i + 1])); { bflag = true; } } if (bflag == false) { break; } } } void ShellSort(int list[], int iNum) { //n=3*x+1; //x=(n-1) / 3; //1,4,13,40,121,364,1093...........; int g; for (g = 1; g < iNum; g = 3 * g + 1); for (g /= 3; g > 0; g /= 3); int k = g; // 그룹의 개수 while (k > 1) { k = k / 2; for (int s = 0; s < k; s++) { //시작,간격 insertionSort(list, iNum, s, k); } } } void QuickSort(int list[], int iStart, int iEnd) { int iPivot = list[iStart]; int iBeginStart = iStart; int iBeginEnd = iEnd; while (iStart < iEnd) { while (iPivot <= list[iEnd] && iStart < iEnd) { iEnd--; } while (iPivot >= list[iStart] && iStart < iEnd) { iStart++; } if (iStart > iEnd) break; swap(list[iStart], list[iEnd]); } swap(list[iBeginStart], list[iStart]); if (iBeginStart < iStart) QuickSort(list, iBeginStart, iStart-1); if (iBeginEnd > iEnd) QuickSort(list,iStart+1,iBeginEnd); } void BuildHeap(int list[], int n) { for(int i = 1; i < n; i++) { int iChild = i; do { int iRoot = (iChild = -1) / 2; if (list[iRoot] < list[iChild]) { change(list[iRoot], list[iChild]); } iChild = iRoot; } while (iChild != 0); } } void RebuildHeap(int list[], int n) { for (int iLast = n-1; iLast >= 0; iLast--) { change(list[0], list[iLast]); int iRoot = 0; int iChild; do { iChild = 2 * iRoot + 1; int iRoot = (iChild = -1) / 2; if (iChild<iLast-1 && list[iChild] < list[iChild+1]) { iChild++; } if (iChild<iLast &&list[iRoot] < list[iChild]) { change(list[iRoot], list[iChild]); } iRoot = iChild; } while (iChild != iLast); } } void HeapSort(int list[], int n) { BuildHeap(list, n); RebuildHeap(list, n); } const int g_iMaxCnt = 10; void main() { int item[g_iMaxCnt];//_countof int* pitem = new int[20]; SetData(item, _countof(item)); clock_t sTime, eTime; sTime = clock(); //1000: 1초 SelectionSort(item, g_iMaxCnt); eTime = clock() - sTime; std::cout << "SelectionSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); SetData(item, _countof(item)); sTime = clock(); //1000: 1초 bubbleSort(item, g_iMaxCnt); eTime = clock() - sTime; std::cout << "bubbleSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); SetData(item, _countof(item)); sTime = clock(); //1000: 1초 insertionSort(item, g_iMaxCnt); eTime = clock() - sTime; std::cout << "insertionSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); SetData(item, _countof(item)); sTime = clock(); //1000: 1초 ShellSort(item, g_iMaxCnt); eTime = clock() - sTime; std::cout << "ShellSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); SetData(item, _countof(item)); sTime = clock(); //1000: 1초 QuickSort(item, 0,g_iMaxCnt-1); eTime = clock() - sTime; std::cout << "QuickSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); SetData(item, _countof(item)); sTime = clock(); //1000: 1초 HeapSort(item, g_iMaxCnt); eTime = clock() - sTime; std::cout << "HeapSort-->" << eTime / (double)CLK_TCK << std::endl; DataPrint(item, g_iMaxCnt); system("pause"); }<file_sep>#pragma once #include "xCore.h" class Sample : public xCore { public: Sample(); ~Sample(); }; <file_sep>#include<stdio.h> int main(void) { int value = 0; int sum1; int j = 0; { scanf_s("%d", &value); for (sum1 = 0; sum1 <= value; sum1++) j = j + sum1; printf("1~n±îÁö ÀÇ ÇÕ:%d",j); } }<file_sep>#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <iostream> #pragma comment (lib,"ws2_32.lib") int main(int argc, char* argv[]) { if (argc != 3) { printf("\n [사용방법] xxx.exe[port][ip]"); printf("\n [사용예시] xxx.exe 10000 192.168.0.100"); return 1; } unsigned short iPort = atoi(argv[1]); char * ip = argv[2]; WSADATA wsa; int iRet; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return 1; } SOCKET sock; sock = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN sa; //sockaddr name; ZeroMemory(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(iPort); // host byte 정렬 to network byte 정렬 short sa.sin_addr.s_addr = inet_addr(ip); iRet = connect(sock, (SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR) { return 1; } char buf[256] = { 0, }; int iLen = 0; while (1) { ZeroMemory(buf, sizeof(char) * 256); printf("\n 보낼 데이터 입력하시오?"); fgets(buf, 256, stdin); if (buf[0] == '\n')break; // 엔터는 종료 ! iLen = strlen(buf) - 1; int iSendByte = send(sock, buf, iLen, 0); printf("%d 바이트를 전송하였습니다.", iSendByte); memset(buf, 0, sizeof(char) * 256); int iRecvByte = recv(sock, buf, 26, 0); if (iRecvByte == 0 || iRecvByte == SOCKET_ERROR) { printf(" 서버 종료"); } buf[iRecvByte] = '\n'; printf("\n%s", buf); } closesocket(sock); // 윈속 소멸 iRet = WSACleanup(); return iRet; }<file_sep>#pragma once #include <iostream> #include <math.h> using namespace std; #ifndef max #define max(a,b) ((a)>(b)?(a):(b)) #endif class Node { public: Node * left; Node* right; int value; int height; Node(int value) { this->value = value; left = right = nullptr; height = 1; } }; class TAvlTree { public: int getHeight(Node* node); Node* updateHeight(Node* node); Node* insert(Node* root, int value); Node* leftRotate(Node* root); Node* rightRotate(Node* root); void printAll(Node* root); public: TAvlTree(); ~TAvlTree(); }; <file_sep>#pragma once #include "S_KHJGlobal.h" // 입출력 클래스 class S_KHJWriter : public S_KHJGlobal { public: FILE* m_pStream; public: void Run(); void Release(); void Exeporter(); void GetTexture(Mtl* pSubmtl, xMtrlerial& xMtrl); void GetMesh(INode* pNode, xGeomMesh& xMesh); void GetTriObjectFromNode(); public: S_KHJWriter(); virtual ~S_KHJWriter(); }; <file_sep>#include "xCore.h" #include "xMap.h" class Sample : public xCore { xMap m_map; public: bool Init() { m_pMainCamera->SetViewMatrix(D3DXVECTOR3(0.0f, 50.0f, -30.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f)); xMapDesc desc = { 257, 257, 1.0f, 1.0f, L"../../Include/data/Eye.bmp", L"../../Include/data/shader/shape.hlsl" }; m_map.Init(); if (m_map.Load(m_pd3dDevice, desc) == false) { return false; } } bool Render() { m_map.SetMatrix(NULL, &m_pMainCamera->m_matView, &m_pMainCamera->m_matProj); m_map.Render(m_pContext); return true; } bool Release() { return m_map.Release(); } public: Sample() {} ~Sample() {} }; GAME_RUN("Sample", 800, 600) <file_sep>#pragma once #include "Sstd.h" class sTimer { public: LARGE_INTEGER m_Frequency; DWORD m_dwFrameCount; DWORD m_dwFPS; LARGE_INTEGER m_dwBeforeTick; float m_fSecPerFrame; float m_fGameTimer; float m_fTimer; TCHAR m_csBuffer[256]; public: bool Init(); // 초기화 bool Frame(); // 계산 bool Render(); // 드로우 bool Release(); // 소멸, 삭제 public: sTimer(); virtual ~sTimer(); }; <file_sep>#include "x_AseMesh.h" void x_AseMesh::LoadScene() { //*SCENE_FILENAME "Box.max" _fgetts(m_pBuffer, 256, m_pStream); //*SCENE_FIRSTFRAME 0 _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &m_Scene.iFirstFrame); //*SCENE_LASTFRAME 100 _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &m_Scene.iLastFrame); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &m_Scene.iFrameSpeed); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &m_Scene.iTickPerFrame); } void x_AseMesh::LoadMaterial() { //*MATERIAL_COUNT 1 int iCount = 0; _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iCount); for (int iCnt = 0; iCnt < iCount; iCnt++) { // multi/sub-object int iSubMtrl=0; if (FineString(_T("*MATERIAL_CLASS")) == false) return; TCHAR szClass[256] = { 0, }; _stscanf(m_pBuffer, _T("%s%s"), m_pString, &szClass); if (!_tcsicmp(szClass, _T("\"Multi/Sub-Object\""))) { if (FineString(_T("*NUMSUBMTLS")) == false) return; _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iSubMtrl); } if (iSubMtrl > 0) { for (int iSub = 0; iSub < iSubMtrl; iSub++) { xMtrlerial xSubMat; xTextureMap tSubMap; if (FineString(_T("*MAP_SUBNO")) == false) return; _stscanf(m_pBuffer, _T("%s%d"), m_pString, &tSubMap.iType); _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%s"), m_pString, m_pString2); TCHAR drive[256] = { 0, }; TCHAR dir[256] = { 0, }; TCHAR fname[256] = { 0, }; TCHAR ext[256] = { 0, }; _tsplitpath(m_pString2, drive, dir, fname, ext); tSubMap.name = fname; ext[4] = 0; tSubMap.name += ext; xSubMat.m_mapList.push_back(tSubMap); xMtrl.m_SubMaterial.push_back(xSubMat); } } else { if (FineString(_T("*MAP_SUBNO")) == false) return; _stscanf(m_pBuffer, _T("%s%d"), m_pString, &tMap.iType); _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%s"), m_pString, m_pString2); TCHAR drive[256] = { 0, }; TCHAR dir[256] = { 0, }; TCHAR fname[256] = { 0, }; TCHAR ext[256] = { 0, }; _tsplitpath(m_pString2, drive, dir, fname, ext); tMap.name = fname; ext[4] = 0; tMap.name += ext; xMtrl.m_mapList.push_back(tMap); } m_MaterialList.push_back(xMtrl); } } bool x_AseMesh::Load(T_STR name) { m_pStream = NULL; m_pStream = _tfopen(name.c_str(), _T("rt")); if (m_pStream == NULL) return false; if (FineString(_T("*SCENE")) == false) return false; LoadScene(); if (FineString(_T("*MATERIAL_LIST")) == false) return false; LoadMaterial(); if (FineString(_T("*GEOMOBJECT")) == false) return false; LoadGeomObject(); fclose(m_pStream); return true; } void x_AseMesh::GetData(void* pData) { _stscanf(m_pBuffer, _T("%s%f%f%f"), m_pString, &((D3DXVECTOR3*)pData)->x, &((D3DXVECTOR3*)pData)->z, &((D3DXVECTOR3*)pData)->y); } bool x_AseMesh::FineString(T_STR find) { while (!feof(m_pStream)) { _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s"), m_pString); if (!_tcsicmp(m_pString, find.c_str())) { return true; } } return false; } void x_AseMesh::LoadVertexData(D3DXVECTOR3& v, bool bSwap) { _fgetts(m_pBuffer, 256, m_pStream); if (bSwap) { _stscanf(m_pBuffer, _T("%s%d%f%f%f"), m_pString, &m_iTemp, &v.x, &v.z, &v.y); } else { _stscanf(m_pBuffer, _T("%s%d%f%f%f"), m_pString, &m_iTemp, &v.x, &v.y, &v.z); } } void x_AseMesh::LoadIndexData(xIndex& v) { _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d%d%d%d"), m_pString, &m_iTemp, &v.i[0], &v.i[2], &v.i[1]); } void x_AseMesh::LoadGeomObject() { while (!feof(m_pStream)) { int iNumFaces = 0; int iNumVertex = 0; xGeomMesh geomObject; _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%s"), m_pString, m_pString2); geomObject.name = m_pString2; D3DXMatrixIdentity(&geomObject.matWorld); if (FineString(_T("*TM_ROW0")) == false) return; GetData(&geomObject.matWorld.m[0]); _fgetts(m_pBuffer, 256, m_pStream); GetData(&geomObject.matWorld.m[2]); _fgetts(m_pBuffer, 256, m_pStream); GetData(&geomObject.matWorld.m[1]); _fgetts(m_pBuffer, 256, m_pStream); GetData(&geomObject.matWorld.m[3]); if (FineString(_T("*MESH")) == false) return; _fgetts(m_pBuffer, 256, m_pStream); //*MESH_NUMVERTEX 8 _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumVertex); if (iNumVertex > 0) { //*MESH_NUMFACES 12 _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumFaces); _fgetts(m_pBuffer, 256, m_pStream); geomObject.vertexList.resize(iNumVertex); for (int iVertex = 0; iVertex < iNumVertex; iVertex++) { LoadVertexData(geomObject.vertexList[iVertex]); } _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); geomObject.PosFaceList.resize(iNumFaces); for (int iFace = 0; iFace < iNumFaces; iFace++) { //*MESH_FACE 0: A: 0 B: 2 C: 3 //AB: 1 BC: 1 CA: 0 //*MESH_SMOOTHING 2 *MESH_MTLID 1 _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%s %s%d %s%d %s%d %s%d %s%d %s %d %s%d %s%d"), m_pString, m_pString, m_pString, &geomObject.PosFaceList[iFace].i[0], m_pString, &geomObject.PosFaceList[iFace].i[2], m_pString, &geomObject.PosFaceList[iFace].i[1], m_pString, &m_iTemp, m_pString, &m_iTemp, m_pString, &m_iTemp, m_pString, &m_iTemp, m_pString, &geomObject.PosFaceList[iFace].iSubMtrl); } } // Texture Coord _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumVertex); if (iNumVertex > 0) { _fgetts(m_pBuffer, 256, m_pStream); geomObject.texList.resize(iNumVertex); for (int iVertex = 0; iVertex < iNumVertex; iVertex++) { LoadVertexData(geomObject.texList[iVertex], false); geomObject.texList[iVertex].y = 1.0f - geomObject.texList[iVertex].y; } //*MESH_NUMTVFACES 12 _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumFaces); _fgetts(m_pBuffer, 256, m_pStream); geomObject.texFaceList.resize(iNumFaces); for (int iFace = 0; iFace < iNumFaces; iFace++) { LoadIndexData(geomObject.texFaceList[iFace]); } } //*MESH_NUMCVERTEX 0 _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumVertex); geomObject.ColList.resize(iNumVertex); if (iNumVertex > 0) { _fgetts(m_pBuffer, 256, m_pStream); for (int iVertex = 0; iVertex < iNumVertex; iVertex++) { LoadVertexData(geomObject.ColList[iVertex], false); } //*MESH_CFACELIST 0 _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); _stscanf(m_pBuffer, _T("%s%d"), m_pString, &iNumFaces); _fgetts(m_pBuffer, 256, m_pStream); geomObject.ColFaceList.resize(iNumFaces); for (int iFace = 0; iFace < iNumFaces; iFace++) { LoadIndexData(geomObject.ColFaceList[iFace]); } } //*MESH_NORMALS{ geomObject.NorList.resize(iNumFaces * 3); _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); for (int iFace = 0; iFace < iNumFaces; iFace++) { _fgetts(m_pBuffer, 256, m_pStream); LoadVertexData(geomObject.NorList[iFace * 3 + 0]); LoadVertexData(geomObject.NorList[iFace * 3 + 2]); LoadVertexData(geomObject.NorList[iFace * 3 + 1]); } //*MATERIAL_REF 0 if (FineString(_T("*MATERIAL_REF")) == false) return; _stscanf(m_pBuffer, _T("%s%d"), m_pString, &geomObject.mtrlRef); _fgetts(m_pBuffer, 256, m_pStream); _fgetts(m_pBuffer, 256, m_pStream); m_ObjectList.push_back(geomObject); } } x_AseMesh::x_AseMesh() { } x_AseMesh::~x_AseMesh() { } <file_sep>#pragma once #include "S_Object.h" class S_AnimObj :public S_Object { public: int m_iDeltatick; public: void GetAnimKeys(INode* pNode, SMesh* pMesh); void DumpScaleSample(INode* pNode, SMesh* pMesh); void DumpRotSample(INode* pNode, SMesh* pMesh); void DumpPosSample(INode* pNode, SMesh* pMesh); BOOL CheckForAnimation(INode* pNode, BOOL& bPos, BOOL& bRot, BOOL& bScale); bool GetDecompAffine(TimeValue t, INode* pNode, AffineParts* ap, Point3* rotAxis = NULL, float* rotAngle = NULL); public: void DumpFloatKeys(Control* cont, SMesh* pMesh); public: S_AnimObj(void); virtual ~S_AnimObj(void); }; <file_sep>#pragma once #include "Sstd.h" #include "xShape.h" struct xPlane { float a, b, c, d; void CreatePlane(D3DXVECTOR3 v0, D3DXVECTOR3 v1, D3DXVECTOR3 v2) { D3DXVECTOR3 vEdge0 = v1 - v0; D3DXVECTOR3 vEdge1 = v2 - v0; D3DXVECTOR3 vNormal; D3DXVec3Cross(&vNormal, &vEdge0, &vEdge1); D3DXVec3Normalize(&vNormal, &vNormal); a = vNormal.x; b = vNormal.y; c = vNormal.z; d = -(v0.x*a + v0.y*b + v0.z*c); } void CreatePlane(D3DXVECTOR3 v0, D3DXVECTOR3 vNormal) { D3DXVec3Normalize(&vNormal, &vNormal); a = vNormal.x; b = vNormal.y; c = vNormal.z; d = -(v0.x*a + v0.y*b + v0.z*c); } xPlane() { a = b = c = d = 0.0f; } }; class xFrustum { private: D3DXMATRIX m_mWorld; D3DXMATRIX m_mView; D3DXMATRIX m_mProj; public: xPlane m_Plane[6]; D3DXVECTOR3 m_vFrustum[8]; public: void SetMatrix( D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj); bool CreateFrustum(); bool ClassifyPoint(D3DXVECTOR3 v0); bool ClassifySphere(D3DXVECTOR3 v, float fRadius); public: xFrustum(); virtual ~xFrustum(); }; <file_sep>//interpreter는 '통역자'란 뜻이다. //대부분의 프로그래밍 언어가 컴파일러(compiler)를 사용해 기계어로 변역하는 //반면 일부는 인터프리터(interpreter)방식으로 번역한다. //인터프리터 방식은 코드를 한 줄씩 해석하여 해당 작업을 바로 수행하는 방식으로 전체 코드를 해석하고 수행해간다. #include <iostream> #include <fstream> #include <string> #include <strstream> using namespace std; static const int NA_POS = -1; class RegularExp { public: virtual bool Match(string context) = 0; }; class LiteralExp :public RegularExp { public: LiteralExp(const char * pStr) :literal_(pStr) { } LiteralExp(const string str) : literal_(str) { } bool Match(string context) { string str; ifstream ifs(context.data()); while (!ifs.eof()) { ifs >> str; if (literal_ == str) return true; } return false; } private: string literal_; }; class OrExp : public RegularExp { public: OrExp(RegularExp *pExp1,RegularExp *pExp2) :pOrExp1_(pExp1),pOrExp2_(pExp2){ } bool Match(string context) { if (pOrExp1_->Match(context)) return true; else { return pOrExp2_->Match(context); } } private: RegularExp * pOrExp1_; RegularExp* pOrExp2_; }; class AndExp : public RegularExp { public: AndExp(RegularExp *pExp1, RegularExp *pExp2) : pAndExp1_(pExp1),pAndExp2_(pExp2){ } bool Match(string context) { return pAndExp1_->Match(context) && pAndExp2_->Match(context); } private: RegularExp * pAndExp1_; RegularExp* pAndExp2_; }; RegularExp* CreateRegularExp(string searchStr) { int len = searchStr.length(); if (len == 0)return NULL; else cout << "===>" << searchStr << endl; int pos = searchStr.find_first_of("(&|"); if (searchStr[pos] == '(') { int endParenPos = 0; int parenCnt = 1; for (int i = pos + 1; i < len; i++) { if (searchStr[i] == '(')parenCnt++; else if (searchStr[i] == ')')parenCnt--; else {} if (parenCnt == 0) { int nextOpPos = searchStr.find_first_of("&|", i + 1); if (nextOpPos != NA_POS) { if (searchStr[nextOpPos] == '&') return new AndExp(CreateRegularExp(searchStr.substr(pos + 1, i - pos - 1)), CreateRegularExp(searchStr.substr(nextOpPos + 1, len - nextOpPos - 1))); else return new OrExp(CreateRegularExp(searchStr.substr(pos + 1, i - pos - 1)), CreateRegularExp(searchStr.substr(nextOpPos + 1, len - nextOpPos - 1))); } else return CreateRegularExp(searchStr.substr(pos + 1, i - pos - 1)); } } //--searchStr 수식이 잘못된 것임 return NULL; } else if (searchStr[pos] == '|') { if (pos >= len - 1)return NULL; return new OrExp(CreateRegularExp(searchStr.substr(0, pos)), CreateRegularExp(searchStr.substr(pos + 1, len - pos - 1))); } else { //--앞뒤 White-space 제거 string literal; strstream strm; strm << searchStr; strm >> literal; if (literal.empty()) return NULL; return new LiteralExp(literal); } } void main() { string str; getline(cin, str); RegularExp*pRegExp = CreateRegularExp(str); if (pRegExp == NULL) { cout << "Search Pattern Error" << endl; exit(0); } if (pRegExp->Match("data.txt")) cout << "Found the search string" << endl; else cout << "Not Exist the search string" << endl; }<file_sep>#include "xFrustum.h" void xFrustum::SetMatrix(D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj) { if (pWorld != NULL) { m_mWorld = *pWorld; } if (pView != NULL) { m_mView = *pView; } if (pProj!= NULL) { m_mProj = *pProj; } } bool xFrustum::CreateFrustum() { D3DXMATRIX matInvViewProj;// = m_mView * m_mProj; D3DXMatrixMultiply(&matInvViewProj, &m_mView, &m_mProj); D3DXMatrixInverse(&matInvViewProj, NULL, &matInvViewProj); // 뒤면 // 5 6 // 4 7 // 앞변 // 1 2 // 0 3 m_vFrustum[0] = D3DXVECTOR3(-1.0f, -1.0f, 0.0f); m_vFrustum[1] = D3DXVECTOR3(-1.0f, 1.0f, 0.0f); m_vFrustum[2] = D3DXVECTOR3( 1.0f, 1.0f, 0.0f); m_vFrustum[3] = D3DXVECTOR3( 1.0f, -1.0f, 0.0f); m_vFrustum[4] = D3DXVECTOR3(-1.0f, -1.0f, 1.0f); m_vFrustum[5] = D3DXVECTOR3(-1.0f, 1.0f, 1.0f); m_vFrustum[6] = D3DXVECTOR3( 1.0f, 1.0f, 1.0f); m_vFrustum[7] = D3DXVECTOR3( 1.0f, -1.0f, 1.0f); for (int iVertex = 0; iVertex < 8; iVertex++) { D3DXVec3TransformCoord(&m_vFrustum[iVertex], &m_vFrustum[iVertex], &matInvViewProj); } // 뒤면 // 5 6 // 4 7 // 앞변 // 1 2 // 0 3 m_Plane[0].CreatePlane(m_vFrustum[0],m_vFrustum[1], m_vFrustum[2] );// -z m_Plane[1].CreatePlane(m_vFrustum[6],m_vFrustum[5], m_vFrustum[4]);// +z m_Plane[2].CreatePlane(m_vFrustum[2],m_vFrustum[6], m_vFrustum[7]);// +x m_Plane[3].CreatePlane(m_vFrustum[5],m_vFrustum[1], m_vFrustum[0]);// -x m_Plane[4].CreatePlane(m_vFrustum[1], m_vFrustum[5], m_vFrustum[6]);// -z m_Plane[5].CreatePlane(m_vFrustum[0], m_vFrustum[3], m_vFrustum[7]);// +z return true; } bool xFrustum::ClassifyPoint(D3DXVECTOR3 v) { for (int iPlane = 0; iPlane < 6; iPlane++) { float fDistance = m_Plane[iPlane].a * v.x + m_Plane[iPlane].b * v.y + m_Plane[iPlane].c * v.z + m_Plane[iPlane].d; if (fDistance > 0.0f) { return false; } } return true; } bool xFrustum::ClassifySphere(D3DXVECTOR3 v, float fRadius) { for (int iPlane = 0; iPlane < 6; iPlane++) { float fDistance = m_Plane[iPlane].a * v.x + m_Plane[iPlane].b * v.y + m_Plane[iPlane].c * v.z + m_Plane[iPlane].d; if (fDistance > fRadius) { return false; } } return true; } xFrustum::xFrustum() { D3DXMatrixIdentity(&m_mWorld); D3DXMatrixIdentity(&m_mView); D3DXMatrixIdentity(&m_mProj); } xFrustum::~xFrustum() { } <file_sep>#include "DXWindow.h" DXWindow* g_pWindow = NULL; // ---------------------------------------------- // 메인 윈도우 프로시져 // ---------------------------------------------- LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { assert(g_pWindow); return g_pWindow->WndProc(hWnd, message, wParam, lParam); } // --------------------------------------------- // 윈도우 프로시져 // --------------------------------------------- LRESULT DXWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc(hWnd, message, wParam, lParam); } void DXWindow::CenterWindow(HWND hwnd) { // 화면 스크린의 해상도 (넓이와 높이)을 얻는다. int iScreenWidth = GetSystemMetrics(SM_CXFULLSCREEN); int iScreenHeight = GetSystemMetrics(SM_CYFULLSCREEN); // 윈도우 클라이언트 중앙과 화면 스크린 중앙을 맞춘다. int iDestX = (iScreenWidth - (m_rcWindowBounds.right - m_rcWindowBounds.left)) / 2; int iDestY = (iScreenHeight - (m_rcWindowBounds.bottom - m_rcWindowBounds.top)) / 2; //d 윈도우를 화면 중앙으로 이동시킨다. MoveWindow(hwnd, iDestX, iDestY, m_rcWindowBounds.right - m_rcWindowBounds.left, m_rcWindowBounds.bottom - m_rcWindowBounds.top, true); } bool DXWindow::InitWindow(HINSTANCE hInstance, int nCmdShow, const wchar_t* strWindowTitle) { //Register class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = &StaticWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"TBASIS3D11_Sample"; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); if (!RegisterClassEx(&wcex)) return false; //Create window m_hInstance = hInstance; RECT rc = { 0,0,800,600 }; // 작업 영역(타이틀 바/경계선/메뉴/스크롤 바 등의 영역을 제외한 영역), 윈도우 스타일 ,메뉴 여부 AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); m_hWnd = CreateWindowEx(WS_EX_TOOLWINDOW,//ws_EX_TOPMOST,//|WS_EX_TOOLWINDOW, L"TBASIS3D11_Sample", strWindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL); if (!m_hWnd) return false; // 윈도우 스타일을 저장하고 스크린 영역과 클리이언트 영역을 얻는다. m_dwWindowStyle = GetWindowLong(m_hWnd, GWL_STYLE); GetWindowRect(m_hWnd, &m_rcWindowBounds); GetClientRect(m_hWnd, &m_rcWindowClient); CenterWindow(m_hWnd); UpdateWindow(m_hWnd); // 윈도우 클라이언트 넓이와 높이를 얻는다. m_iWindowWidth = m_rcWindowClient.right - m_rcWindowClient.left; m_iWindowHeight = m_rcWindowClient.bottom - m_rcWindowClient.top; ShowWindow(m_hWnd, nCmdShow); return true; } bool DXWindow::Init() { return true; } bool DXWindow::Frame() { return true; } bool DXWindow::Render() { return true; } bool DXWindow::Release() { return true; } bool DXWindow::Run() { if (!Init())return false; // Main message loop MSG msg={ 0 }; while (WM_QUIT != msg.message) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { if (!Frame() || !Render()) { break; } } } if (!Release())return false; return true; } DXWindow::DXWindow(void) { m_hInstance = NULL; m_hWnd = NULL; g_pWindow = this; } DXWindow::~DXWindow(void) { } <file_sep>#include "TChatSvr.h" #include "SServer.h" #include "SServerIOCP.h" #include "SDebugString.h" #include "SLock.h" #include "TStd.h" bool TChatSvr::AddUser(SOCKET socket, SOCKADDR_IN address) { { SLock sync(this); TChatUser* pUser = NULL; SAFE_NEW( pUser, TChatUser ); // 유저 정보 체움. pUser->m_Socket = socket; pUser->m_UserAddress = address; I_Debug.Print("IP=%s, PORT=%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port)); if( pUser ) { I_Server.SendMsg(pUser->m_Socket, "환영! 대화명 입력하시오", PACKET_CHAR_NAME_REQ); m_UserList.push_back( pUser ); I_ServerIOCP.AddHandleToIOCP((HANDLE)socket, (ULONG_PTR)pUser); pUser->Create(); } } return true; } void TChatSvr::DeleteUser( SOCKET socket ) { { SLock sync(this); std::list<TChatUser*>::iterator iter; std::list<TChatUser*>::iterator delUser; int iClientUser = I_Server.m_UserList.size(); for( iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++ ) { TChatUser* pUser = (TChatUser*)*iter; if( pUser->m_Socket == socket ) { char buffer[256] = {0,}; sprintf_s( buffer, "%s%s", pUser->m_szName.c_str(),"님이 나가셨습니다." ); I_Debug.Print("%s%s", pUser->m_szName.c_str(),"님이 나가셨습니다."); I_Server.Broadcastting( buffer, PACKET_CHAR_MSG, pUser->m_Socket); closesocket( pUser->m_Socket ); delUser = iter; SAFE_DEL( pUser ); break; } } I_Server.m_UserList.erase(delUser); } }; //TChatUser* pUser void TChatSvr::DeleteUser( TChatUser* pDeleteUser) { { SLock sync(this); std::list<TChatUser*>::iterator iter; std::list<TChatUser*>::iterator delUser; int iClientUser = I_Server.m_UserList.size(); for( iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++ ) { TChatUser* pUser = (TChatUser*)*iter; if( pUser == pDeleteUser ) { char buffer[256] = {0,}; sprintf_s( buffer, "%s%s", pUser->m_szName.c_str(),"님이 나가셨습니다." ); I_Debug.Print("%s%s", pUser->m_szName.c_str(),"님이 나가셨습니다."); I_Server.Broadcastting( buffer, PACKET_CHAR_MSG, pUser->m_Socket); closesocket( pUser->m_Socket ); delUser = iter; SAFE_DEL( pUser ); break; } } I_Server.m_UserList.erase(delUser); } }; void TChatSvr::Broadcastting( UPACKET* pPacket, SOCKET SendSocket ) { { SLock sync(this); std::list<TChatUser*>::iterator iter; std::list<TChatUser*>::iterator delUser; int iClientUser = I_Server.m_UserList.size(); for( iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++ ) { TChatUser* pUser = (TChatUser*)*iter; //if( 0==SendSocket /*|| pUser->m_Socket != SendSocket*/ ) { int iRet = send( pUser->m_Socket, (char*)pPacket, pPacket->ph.len, 0 ); if( iRet < 0 ) { I_Debug.T_ERROR(false); continue; } } I_Debug.Print("%s에게 %s 보냈습니다.", pUser->m_szName.c_str(), pPacket->msg); } } } void TChatSvr::Broadcastting( S_PACKET* pUserData) { { SLock sync(this); std::list<TChatUser*>::iterator iter; std::list<TChatUser*>::iterator delUser; UPACKET* pPacket = &pUserData->packet; DWORD dwSendByte; int iClientUser = I_Server.m_UserList.size(); for( iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++ ) { TChatUser* pUser = (TChatUser*)*iter; if( pUser->m_Socket != pUserData->pUser->m_Socket ) { /*pUser->m_szWsaBuf.buf = (CHAR *)pPacket; pUser->m_szWsaBuf.len = pPacket.ph.len; pUser->m_ov.iFlag = OVERLAPPEDEX::MODE_SEND; T_PACKET* P = (T_PACKET*)pUser->m_szWsaBuf.buf; int iRet = WSASend(pUser->m_Socket, &(pUser->m_szWsaBuf), 1, &dwSendByte, 0, (LPOVERLAPPED)&pUser->m_ov, NULL);*/ int iRet = send( pUser->m_Socket, (char*)&pUserData->packet, pUserData->packet.ph.len, 0 ); if( iRet < 0 ) { I_Debug.T_ERROR(false); continue; } } I_Debug.Print("%s에게 %s님의 %s 보냈습니다.", pUser->m_szName.c_str(), pUserData->pUser->m_szName.c_str(), pUserData->packet.msg); } } }; void TChatSvr::Broadcastting( char* msg, WORD code, SOCKET SendSocket ) { { SLock sync(this); std::list<TChatUser*>::iterator iter; std::list<TChatUser*>::iterator delUser; int iClientUser = I_Server.m_UserList.size(); for( iter = I_Server.m_UserList.begin(); iter != I_Server.m_UserList.end(); iter++ ) { TChatUser* pUser = (TChatUser*)*iter; if( 0==SendSocket || pUser->m_Socket != SendSocket ) { if( !SendMsg( pUser->m_Socket, msg, code ) ) { I_Debug.T_ERROR(false); continue; } } I_Debug.Print("%s%s%s", pUser->m_szName.c_str(), msg, "보냈습니다."); } } }; bool TChatSvr::Init() { I_Debug.Print("%s", "서버 시작합니다."); SServer::Init(); m_Acceptor.Set( 10000, NULL ); return true; } bool TChatSvr::Release() { return SServer::Release(); } bool TChatSvr::Run() { while(m_bStarted) { m_PacketPool.ProcessPacket(); Sleep(10); } return true; } TChatSvr::TChatSvr(void) { } TChatSvr::~TChatSvr(void) { } <file_sep>#include "S_ChatUser.h" #include "S_Chat_Svr.h" void S_ChatUser::MoveMent(UPACKET* pPacket) { SPACKET_USER_POSITION User; memcpy(&User, pPacket->msg, sizeof(char)*pPacket->ph.len - 4); m_iIndex = User.user_idx; m_PositionX = User.PosX; m_PositionY = User.PosY; m_iDirection = User.direction; } void S_ChatUser::AddPacket(PACKET& addPacket) { S_CHAT.m_PacketPool.AddPacket(addPacket); } void S_ChatUser::DeleteUser(SOCKET socket) { S_CHAT.DeleteUser(socket); } void S_ChatUser::DeleteUser() { S_CHAT.DeleteUser(this); } void S_ChatUser::Dispatch(DWORD dwByteSize, LPOVERLAPPED OV) { OVERLAPPEDEX* pOV = (OVERLAPPEDEX*)OV; if (dwByteSize == 0)return; if (pOV->i_Flags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put(m_szRecvBuf.buf, dwByteSize, this); } if (pOV->i_Flags == OVERLAPPEDEX::MODE_SEND) { } WaitforPacketReceive(); } S_ChatUser::S_ChatUser() { } S_ChatUser::~S_ChatUser() { } <file_sep>#include<stdio.h> #include<conio.h> void main() { int sum = 0; int sum1 = 0; for (int i = 0; i <= 100; i++) { if (i % 2 == 0) { sum = sum + i; } else { sum1 = sum1 + i; } } printf("1~100까지의 짝수의 합:%d\n", sum); printf("1~100까지의 홀수의 합:%d\n", sum1); printf("1~100까지의 짝수와 홀수의 합:%d\n", sum + sum1); _getch(); }<file_sep>#include "SPacket.h" void SPacket::PutData(const char* pData, int iSize) { m_uPacket.ph.len += iSize; memcpy(m_pOffset, pData, iSize); m_pOffset += iSize; } void SPacket::GetData(const char* pData, int iSize) { memcpy(const_cast<char*>(pData), m_pOffset, iSize); m_pOffset += iSize; } SPacket & SPacket::operator << (int data) { PutData((char*)&data, sizeof(int)); return *this; } SPacket & SPacket::operator << (short data) { PutData((char*)&data, sizeof(short)); return *this; } SPacket & SPacket::operator << (long data) { PutData((char*)&data, sizeof(long)); return *this; } SPacket & SPacket::operator << (DWORD data) { PutData((char*)&data, sizeof(DWORD)); return *this; } SPacket & SPacket::operator << (float data) { PutData((char*)&data, sizeof(float)); return *this; } SPacket & SPacket::operator << (char* data) { int iSize = strlen(data) + 1; PutData(data, iSize); return *this; } SPacket & SPacket::operator << (string data) { PutData(data.c_str(), data.size()); return *this; } ///////////////////////////////// SPacket & SPacket::operator >> (int& data) { GetData((char*)&data, sizeof(int)); return *this; } SPacket & SPacket::operator >> (short& data) { GetData((char*)&data, sizeof(short)); return *this; } SPacket & SPacket::operator >> (long& data) { GetData((char*)&data, sizeof(long)); return *this; } SPacket & SPacket::operator >> (DWORD& data) { GetData((char*)&data, sizeof(DWORD)); return *this; } SPacket & SPacket::operator >> (float& data) { GetData((char*)&data, sizeof(float)); return *this; } SPacket & SPacket::operator >> (char* data) { int iSize = strlen(m_pOffset) + 1; GetData(data, iSize); return *this; } SPacket & SPacket::operator >> (string& data) { int ilen = strlen(m_pOffset) + 1; char buffer[256] = { 0, }; GetData(buffer, ilen); data = buffer; return *this; } SPacket::SPacket() { ZeroMemory(&m_uPacket, sizeof(UPACKET)); m_pOffset = m_uPacket.msg; } SPacket::SPacket(int dwType) { ZeroMemory(&m_uPacket, sizeof(UPACKET)); m_uPacket.ph.len = 0; m_uPacket.ph.type = dwType; m_pOffset = m_uPacket.msg; } SPacket::~SPacket() { } <file_sep>//#pragma once //#include <d3d11_1.h> //#include <d3dx11.h> //#if !defined(__d3d11_h__) && !defined(__d3d11_x_h__) && !defined(__d3d12_h__) && !defined(__d3d12_x_h__) //#error include d3d11.h or d3d12.h before including TMath.h //#endif // //#if !defined(_XBOX_ONE) || !defined(_TITLE) ////#include <dxgi1_2.h> //#endif // //#include <functional> //#include <assert.h> //#include <memory.h> // //#include <DirectXMath.h> //#include <DirectXPackedVector.h> //#include <DirectXCollision.h> // //#ifndef XM_CONSTEXPR //#define XM_CONSTEXPR //#endif //using namespace DirectX; //namespace TBASIS_EX //{ // struct TVector2; // struct TVector3; // struct TVector4; // struct TDxMatrix; // struct TQuaternion; // struct TPlane; // // //------------------------------------------------------------------------------ // // 2D rectangle // struct TRectangle // { // long x; // long y; // long width; // long height; // // // Creators // TRectangle() noexcept : x(0), y(0), width(0), height(0) {} // XM_CONSTEXPR TRectangle(long ix, long iy, long iw, long ih) : x(ix), y(iy), width(iw), height(ih) {} // explicit TRectangle(const RECT& rct) : x(rct.left), y(rct.top), width(rct.right - rct.left), height(rct.bottom - rct.top) {} // // TRectangle(const TRectangle&) = default; // TRectangle& operator=(const TRectangle&) = default; // // TRectangle(TRectangle&&) = default; // TRectangle& operator=(TRectangle&&) = default; // // operator RECT() { RECT rct; rct.left = x; rct.top = y; rct.right = (x + width); rct.bottom = (y + height); return rct; } //#ifdef __cplusplus_winrt // operator Windows::Foundation::Rect() { return Windows::Foundation::Rect(float(x), float(y), float(width), float(height)); } //#endif // // // Comparison operators // bool operator == (const TRectangle& r) const { return (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height); } // bool operator == (const RECT& rct) const { return (x == rct.left) && (y == rct.top) && (width == (rct.right - rct.left)) && (height == (rct.bottom - rct.top)); } // // bool operator != (const TRectangle& r) const { return (x != r.x) || (y != r.y) || (width != r.width) || (height != r.height); } // bool operator != (const RECT& rct) const { return (x != rct.left) || (y != rct.top) || (width != (rct.right - rct.left)) || (height != (rct.bottom - rct.top)); } // // // Assignment operators // TRectangle& operator=(_In_ const RECT& rct) { x = rct.left; y = rct.top; width = (rct.right - rct.left); height = (rct.bottom - rct.top); return *this; } // // // TRectangle operations // TVector2 Location() const; // TVector2 Center() const; // // bool IsEmpty() const { return (width == 0 && height == 0 && x == 0 && y == 0); } // // bool Contains(long ix, long iy) const { return (x <= ix) && (ix < (x + width)) && (y <= iy) && (iy < (y + height)); } // bool Contains(const TVector2& point) const; // bool Contains(const TRectangle& r) const { return (x <= r.x) && ((r.x + r.width) <= (x + width)) && (y <= r.y) && ((r.y + r.height) <= (y + height)); } // bool Contains(const RECT& rct) const { return (x <= rct.left) && (rct.right <= (x + width)) && (y <= rct.top) && (rct.bottom <= (y + height)); } // // void Inflate(long horizAmount, long vertAmount); // // bool Intersects(const TRectangle& r) const { return (r.x < (x + width)) && (x < (r.x + r.width)) && (r.y < (y + height)) && (y < (r.y + r.height)); } // bool Intersects(const RECT& rct) const { return (rct.left < (x + width)) && (x < rct.right) && (rct.top < (y + height)) && (y < rct.bottom); } // // void Offset(long ox, long oy) { x += ox; y += oy; } // // // Static functions // static TRectangle Intersect(const TRectangle& ra, const TRectangle& rb); // static RECT Intersect(const RECT& rcta, const RECT& rctb); // // static TRectangle Union(const TRectangle& ra, const TRectangle& rb); // static RECT Union(const RECT& rcta, const RECT& rctb); // }; // // //------------------------------------------------------------------------------ // // 2D vector // struct TVector2 : DirectX::XMFLOAT2 // { // TVector2() noexcept : XMFLOAT2(0.f, 0.f) {} // XM_CONSTEXPR explicit TVector2(float x) : XMFLOAT2(x, x) {} // XM_CONSTEXPR TVector2(float _x, float _y) : XMFLOAT2(_x, _y) {} // explicit TVector2(_In_reads_(2) const float *pArray) : XMFLOAT2(pArray) {} // TVector2(XMFLOAT2 V) { x = V.x; y = V.y; } // TVector2(const XMFLOAT2& V) { this->x = V.x; this->y = V.y; } // explicit TVector2(const DirectX::XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; } // // TVector2(const TVector2&) = default; // TVector2& operator=(const TVector2&) = default; // // TVector2(TVector2&&) = default; // TVector2& operator=(TVector2&&) = default; // // operator DirectX::XMVECTOR() const { return XMLoadFloat2(this); } // // // Comparison operators // bool operator == (const TVector2& V) const; // bool operator != (const TVector2& V) const; // // // Assignment operators // TVector2& operator= (const DirectX::XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; return *this; } // TVector2& operator+= (const TVector2& V); // TVector2& operator-= (const TVector2& V); // TVector2& operator*= (const TVector2& V); // TVector2& operator*= (float S); // TVector2& operator/= (float S); // // // Unary operators // TVector2 operator+ () const { return *this; } // TVector2 operator- () const { return TVector2(-x, -y); } // // // Vector operations // bool InBounds(const TVector2& Bounds) const; // // float Length() const; // float LengthSquared() const; // // float Dot(const TVector2& V) const; // void Cross(const TVector2& V, TVector2& result) const; // TVector2 Cross(const TVector2& V) const; // // void Normalize(); // void Normalize(TVector2& result) const; // // void Clamp(const TVector2& vmin, const TVector2& vmax); // void Clamp(const TVector2& vmin, const TVector2& vmax, TVector2& result) const; // // // Static functions // static float Distance(const TVector2& v1, const TVector2& v2); // static float DistanceSquared(const TVector2& v1, const TVector2& v2); // // static void Min(const TVector2& v1, const TVector2& v2, TVector2& result); // static TVector2 Min(const TVector2& v1, const TVector2& v2); // // static void Max(const TVector2& v1, const TVector2& v2, TVector2& result); // static TVector2 Max(const TVector2& v1, const TVector2& v2); // // static void Lerp(const TVector2& v1, const TVector2& v2, float t, TVector2& result); // static TVector2 Lerp(const TVector2& v1, const TVector2& v2, float t); // // static void SmoothStep(const TVector2& v1, const TVector2& v2, float t, TVector2& result); // static TVector2 SmoothStep(const TVector2& v1, const TVector2& v2, float t); // // static void Barycentric(const TVector2& v1, const TVector2& v2, const TVector2& v3, float f, float g, TVector2& result); // static TVector2 Barycentric(const TVector2& v1, const TVector2& v2, const TVector2& v3, float f, float g); // // static void CatmullRom(const TVector2& v1, const TVector2& v2, const TVector2& v3, const TVector2& v4, float t, TVector2& result); // static TVector2 CatmullRom(const TVector2& v1, const TVector2& v2, const TVector2& v3, const TVector2& v4, float t); // // static void Hermite(const TVector2& v1, const TVector2& t1, const TVector2& v2, const TVector2& t2, float t, TVector2& result); // static TVector2 Hermite(const TVector2& v1, const TVector2& t1, const TVector2& v2, const TVector2& t2, float t); // // static void Reflect(const TVector2& ivec, const TVector2& nvec, TVector2& result); // static TVector2 Reflect(const TVector2& ivec, const TVector2& nvec); // // static void Refract(const TVector2& ivec, const TVector2& nvec, float refractionIndex, TVector2& result); // static TVector2 Refract(const TVector2& ivec, const TVector2& nvec, float refractionIndex); // // static void Transform(const TVector2& v, const TQuaternion& quat, TVector2& result); // static TVector2 Transform(const TVector2& v, const TQuaternion& quat); // // static void Transform(const TVector2& v, const TDxMatrix& m, TVector2& result); // static TVector2 Transform(const TVector2& v, const TDxMatrix& m); // static void Transform(_In_reads_(count) const TVector2* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector2* resultArray); // // static void Transform(const TVector2& v, const TDxMatrix& m, TVector4& result); // static void Transform(_In_reads_(count) const TVector2* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector4* resultArray); // // static void TransformNormal(const TVector2& v, const TDxMatrix& m, TVector2& result); // static TVector2 TransformNormal(const TVector2& v, const TDxMatrix& m); // static void TransformNormal(_In_reads_(count) const TVector2* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector2* resultArray); // // // Constants // static const TVector2 Zero; // static const TVector2 One; // static const TVector2 UnitX; // static const TVector2 UnitY; // }; // // // Binary operators // TVector2 operator+ (const TVector2& V1, const TVector2& V2); // TVector2 operator- (const TVector2& V1, const TVector2& V2); // TVector2 operator* (const TVector2& V1, const TVector2& V2); // TVector2 operator* (const TVector2& V, float S); // TVector2 operator/ (const TVector2& V1, const TVector2& V2); // TVector2 operator* (float S, const TVector2& V); // // //------------------------------------------------------------------------------ // // 3D vector // struct TVector3 : DirectX::XMFLOAT3 // { // TVector3() noexcept : DirectX::XMFLOAT3(0.f, 0.f, 0.f) {} // XM_CONSTEXPR explicit TVector3(float x) : DirectX::XMFLOAT3(x, x, x) {} // XM_CONSTEXPR TVector3(float _x, float _y, float _z) : DirectX::XMFLOAT3(_x, _y, _z) {} // TVector3(const float *pArray) : DirectX::XMFLOAT3(pArray) {} // TVector3(DirectX::XMFLOAT3 V) { x = V.x; y = V.y; z = V.z; } // TVector3(const DirectX::XMFLOAT3& V) { this->x = V.x; this->y = V.y; this->z = V.z; } // explicit TVector3(const DirectX::XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; } // // TVector3(const TVector3&) = default; // TVector3& operator=(const TVector3&) = default; // // TVector3(TVector3&&) = default; // TVector3& operator=(TVector3&&) = default; // // operator DirectX::XMVECTOR() const { return XMLoadFloat3(this); } // // float operator [](int i) // { // if (i == 0) return x; // if (i == 1) return y; // if (i == 2) return z; // return 0.0f; // } // // // Comparison operators // bool operator == (const TVector3& V) const; // bool operator != (const TVector3& V) const; // // // Assignment operators // TVector3& operator= (const DirectX::XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; return *this; } // TVector3& operator+= (const TVector3& V); // TVector3& operator-= (const TVector3& V); // TVector3& operator*= (const TVector3& V); // TVector3& operator*= (float S); // TVector3& operator/= (float S); // // // Unary operators // TVector3 operator+ () const { return *this; } // TVector3 operator- () const; // // // Vector operations // bool InBounds(const TVector3& Bounds) const; // // float Length() const; // float LengthSquared() const; // // float Dot(const TVector3& V) const; // void Cross(const TVector3& V, TVector3& result) const; // TVector3 Cross(const TVector3& V) const; // // void Normalize(); // void Normalize(TVector3& result) const; // // void Clamp(const TVector3& vmin, const TVector3& vmax); // void Clamp(const TVector3& vmin, const TVector3& vmax, TVector3& result) const; // // // Static functions // static float Distance(const TVector3& v1, const TVector3& v2); // static float DistanceSquared(const TVector3& v1, const TVector3& v2); // // static void Min(const TVector3& v1, const TVector3& v2, TVector3& result); // static TVector3 Min(const TVector3& v1, const TVector3& v2); // // static void Max(const TVector3& v1, const TVector3& v2, TVector3& result); // static TVector3 Max(const TVector3& v1, const TVector3& v2); // // static void Lerp(const TVector3& v1, const TVector3& v2, float t, TVector3& result); // static TVector3 Lerp(const TVector3& v1, const TVector3& v2, float t); // // static void SmoothStep(const TVector3& v1, const TVector3& v2, float t, TVector3& result); // static TVector3 SmoothStep(const TVector3& v1, const TVector3& v2, float t); // // static void Barycentric(const TVector3& v1, const TVector3& v2, const TVector3& v3, float f, float g, TVector3& result); // static TVector3 Barycentric(const TVector3& v1, const TVector3& v2, const TVector3& v3, float f, float g); // // static void CatmullRom(const TVector3& v1, const TVector3& v2, const TVector3& v3, const TVector3& v4, float t, TVector3& result); // static TVector3 CatmullRom(const TVector3& v1, const TVector3& v2, const TVector3& v3, const TVector3& v4, float t); // // static void Hermite(const TVector3& v1, const TVector3& t1, const TVector3& v2, const TVector3& t2, float t, TVector3& result); // static TVector3 Hermite(const TVector3& v1, const TVector3& t1, const TVector3& v2, const TVector3& t2, float t); // // static void Reflect(const TVector3& ivec, const TVector3& nvec, TVector3& result); // static TVector3 Reflect(const TVector3& ivec, const TVector3& nvec); // // static void Refract(const TVector3& ivec, const TVector3& nvec, float refractionIndex, TVector3& result); // static TVector3 Refract(const TVector3& ivec, const TVector3& nvec, float refractionIndex); // // static void Transform(const TVector3& v, const TQuaternion& quat, TVector3& result); // static TVector3 Transform(const TVector3& v, const TQuaternion& quat); // // static void Transform(const TVector3& v, const TDxMatrix& m, TVector3& result); // static TVector3 Transform(const TVector3& v, const TDxMatrix& m); // static void Transform(_In_reads_(count) const TVector3* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector3* resultArray); // // static void Transform(const TVector3& v, const TDxMatrix& m, TVector4& result); // static void Transform(_In_reads_(count) const TVector3* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector4* resultArray); // // static void TransformNormal(const TVector3& v, const TDxMatrix& m, TVector3& result); // static TVector3 TransformNormal(const TVector3& v, const TDxMatrix& m); // static void TransformNormal(_In_reads_(count) const TVector3* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector3* resultArray); // // // Constants // static const TVector3 Zero; // static const TVector3 One; // static const TVector3 UnitX; // static const TVector3 UnitY; // static const TVector3 UnitZ; // static const TVector3 Up; // static const TVector3 Down; // static const TVector3 Right; // static const TVector3 Left; // static const TVector3 Forward; // static const TVector3 Backward; // }; // // // Binary operators // TVector3 operator+ (const TVector3& V1, const TVector3& V2); // TVector3 operator- (const TVector3& V1, const TVector3& V2); // TVector3 operator* (const TVector3& V1, const TVector3& V2); // TVector3 operator* (const TVector3& V, float S); // TVector3 operator/ (const TVector3& V1, const TVector3& V2); // TVector3 operator* (float S, const TVector3& V); // // //------------------------------------------------------------------------------ // // 4D vector // struct TVector4 : public XMFLOAT4 // { // TVector4() noexcept : XMFLOAT4(0.f, 0.f, 0.f, 0.f) {} // XM_CONSTEXPR explicit TVector4(float x) : XMFLOAT4(x, x, x, x) {} // XM_CONSTEXPR TVector4(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} // explicit TVector4(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} // TVector4(XMFLOAT4 V) { x = V.x; y = V.y; z = V.z; w = V.w; } // TVector4(const XMFLOAT4& V) { this->x = V.x; this->y = V.y; this->z = V.z; this->w = V.w; } // explicit TVector4(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } // // TVector4(const TVector4&) = default; // TVector4& operator=(const TVector4&) = default; // // TVector4(TVector4&&) = default; // TVector4& operator=(TVector4&&) = default; // // operator XMVECTOR() const { return XMLoadFloat4(this); } // // // Comparison operators // bool operator == (const TVector4& V) const; // bool operator != (const TVector4& V) const; // // // Assignment operators // TVector4& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } // TVector4& operator+= (const TVector4& V); // TVector4& operator-= (const TVector4& V); // TVector4& operator*= (const TVector4& V); // TVector4& operator*= (float S); // TVector4& operator/= (float S); // // // Unary operators // TVector4 operator+ () const { return *this; } // TVector4 operator- () const; // // // Vector operations // bool InBounds(const TVector4& Bounds) const; // // float Length() const; // float LengthSquared() const; // // float Dot(const TVector4& V) const; // void Cross(const TVector4& v1, const TVector4& v2, TVector4& result) const; // TVector4 Cross(const TVector4& v1, const TVector4& v2) const; // // void Normalize(); // void Normalize(TVector4& result) const; // // void Clamp(const TVector4& vmin, const TVector4& vmax); // void Clamp(const TVector4& vmin, const TVector4& vmax, TVector4& result) const; // // // Static functions // static float Distance(const TVector4& v1, const TVector4& v2); // static float DistanceSquared(const TVector4& v1, const TVector4& v2); // // static void Min(const TVector4& v1, const TVector4& v2, TVector4& result); // static TVector4 Min(const TVector4& v1, const TVector4& v2); // // static void Max(const TVector4& v1, const TVector4& v2, TVector4& result); // static TVector4 Max(const TVector4& v1, const TVector4& v2); // // static void Lerp(const TVector4& v1, const TVector4& v2, float t, TVector4& result); // static TVector4 Lerp(const TVector4& v1, const TVector4& v2, float t); // // static void SmoothStep(const TVector4& v1, const TVector4& v2, float t, TVector4& result); // static TVector4 SmoothStep(const TVector4& v1, const TVector4& v2, float t); // // static void Barycentric(const TVector4& v1, const TVector4& v2, const TVector4& v3, float f, float g, TVector4& result); // static TVector4 Barycentric(const TVector4& v1, const TVector4& v2, const TVector4& v3, float f, float g); // // static void CatmullRom(const TVector4& v1, const TVector4& v2, const TVector4& v3, const TVector4& v4, float t, TVector4& result); // static TVector4 CatmullRom(const TVector4& v1, const TVector4& v2, const TVector4& v3, const TVector4& v4, float t); // // static void Hermite(const TVector4& v1, const TVector4& t1, const TVector4& v2, const TVector4& t2, float t, TVector4& result); // static TVector4 Hermite(const TVector4& v1, const TVector4& t1, const TVector4& v2, const TVector4& t2, float t); // // static void Reflect(const TVector4& ivec, const TVector4& nvec, TVector4& result); // static TVector4 Reflect(const TVector4& ivec, const TVector4& nvec); // // static void Refract(const TVector4& ivec, const TVector4& nvec, float refractionIndex, TVector4& result); // static TVector4 Refract(const TVector4& ivec, const TVector4& nvec, float refractionIndex); // // static void Transform(const TVector2& v, const TQuaternion& quat, TVector4& result); // static TVector4 Transform(const TVector2& v, const TQuaternion& quat); // // static void Transform(const TVector3& v, const TQuaternion& quat, TVector4& result); // static TVector4 Transform(const TVector3& v, const TQuaternion& quat); // // static void Transform(const TVector4& v, const TQuaternion& quat, TVector4& result); // static TVector4 Transform(const TVector4& v, const TQuaternion& quat); // // static void Transform(const TVector4& v, const TDxMatrix& m, TVector4& result); // static TVector4 Transform(const TVector4& v, const TDxMatrix& m); // static void Transform(_In_reads_(count) const TVector4* varray, size_t count, const TDxMatrix& m, _Out_writes_(count) TVector4* resultArray); // // // Constants // static const TVector4 Zero; // static const TVector4 One; // static const TVector4 UnitX; // static const TVector4 UnitY; // static const TVector4 UnitZ; // static const TVector4 UnitW; // }; // // // Binary operators // TVector4 operator+ (const TVector4& V1, const TVector4& V2); // TVector4 operator- (const TVector4& V1, const TVector4& V2); // TVector4 operator* (const TVector4& V1, const TVector4& V2); // TVector4 operator* (const TVector4& V, float S); // TVector4 operator/ (const TVector4& V1, const TVector4& V2); // TVector4 operator* (float S, const TVector4& V); // // //------------------------------------------------------------------------------ // // 4x4 TDxMatrix (assumes right-handed cooordinates) // struct TDxMatrix : public XMFLOAT4X4 // { // TDxMatrix() noexcept // : XMFLOAT4X4(1.f, 0, 0, 0, // 0, 1.f, 0, 0, // 0, 0, 1.f, 0, // 0, 0, 0, 1.f) {} // XM_CONSTEXPR TDxMatrix(float m00, float m01, float m02, float m03, // float m10, float m11, float m12, float m13, // float m20, float m21, float m22, float m23, // float m30, float m31, float m32, float m33) // : XMFLOAT4X4(m00, m01, m02, m03, // m10, m11, m12, m13, // m20, m21, m22, m23, // m30, m31, m32, m33) {} // explicit TDxMatrix(const TVector3& r0, const TVector3& r1, const TVector3& r2) // : XMFLOAT4X4(r0.x, r0.y, r0.z, 0, // r1.x, r1.y, r1.z, 0, // r2.x, r2.y, r2.z, 0, // 0, 0, 0, 1.f) {} // explicit TDxMatrix(const TVector4& r0, const TVector4& r1, const TVector4& r2, const TVector4& r3) // : XMFLOAT4X4(r0.x, r0.y, r0.z, r0.w, // r1.x, r1.y, r1.z, r1.w, // r2.x, r2.y, r2.z, r2.w, // r3.x, r3.y, r3.z, r3.w) {} // TDxMatrix(const XMFLOAT4X4& M) { memcpy_s(this, sizeof(float) * 16, &M, sizeof(XMFLOAT4X4)); } // TDxMatrix(const XMFLOAT3X3& M); // TDxMatrix(const XMFLOAT4X3& M); // // explicit TDxMatrix(_In_reads_(16) const float *pArray) : XMFLOAT4X4(pArray) {} // TDxMatrix(CXMMATRIX M) { XMStoreFloat4x4(this, M); } // // TDxMatrix(const TDxMatrix&) = default; // TDxMatrix& operator=(const TDxMatrix&) = default; // // TDxMatrix(TDxMatrix&&) = default; // TDxMatrix& operator=(TDxMatrix&&) = default; // // operator XMFLOAT4X4() const { return *this; } // // // Comparison operators // bool operator == (const TDxMatrix& M) const; // bool operator != (const TDxMatrix& M) const; // // // Assignment operators // TDxMatrix& operator= (const XMFLOAT3X3& M); // TDxMatrix& operator= (const XMFLOAT4X3& M); // TDxMatrix& operator+= (const TDxMatrix& M); // TDxMatrix& operator-= (const TDxMatrix& M); // TDxMatrix& operator*= (const TDxMatrix& M); // TDxMatrix& operator*= (float S); // TDxMatrix& operator/= (float S); // // TDxMatrix& operator/= (const TDxMatrix& M); // // Element-wise divide // // // Unary operators // TDxMatrix operator+ () const { return *this; } // TDxMatrix operator- () const; // // // Properties // TVector3 Up() const { return TVector3(_21, _22, _23); } // void Up(const TVector3& v) { _21 = v.x; _22 = v.y; _23 = v.z; } // // TVector3 Down() const { return TVector3(-_21, -_22, -_23); } // void Down(const TVector3& v) { _21 = -v.x; _22 = -v.y; _23 = -v.z; } // // TVector3 Right() const { return TVector3(_11, _12, _13); } // void Right(const TVector3& v) { _11 = v.x; _12 = v.y; _13 = v.z; } // // TVector3 Left() const { return TVector3(-_11, -_12, -_13); } // void Left(const TVector3& v) { _11 = -v.x; _12 = -v.y; _13 = -v.z; } // // TVector3 Forward() const { return TVector3(-_31, -_32, -_33); } // void Forward(const TVector3& v) { _31 = -v.x; _32 = -v.y; _33 = -v.z; } // // TVector3 Backward() const { return TVector3(_31, _32, _33); } // void Backward(const TVector3& v) { _31 = v.x; _32 = v.y; _33 = v.z; } // // TVector3 Translation() const { return TVector3(_41, _42, _43); } // void Translation(const TVector3& v) { _41 = v.x; _42 = v.y; _43 = v.z; } // // // TDxMatrix operations // bool Decompose(TVector3& scale, TQuaternion& rotation, TVector3& translation); // // TDxMatrix Transpose() const; // void Transpose(TDxMatrix& result) const; // // TDxMatrix Invert() const; // void Invert(TDxMatrix& result) const; // // float Determinant() const; // // // Static functions // static TDxMatrix CreateBillboard(const TVector3& object, const TVector3& cameraPosition, const TVector3& cameraUp, _In_opt_ const TVector3* cameraForward = nullptr); // // static TDxMatrix CreateConstrainedBillboard(const TVector3& object, const TVector3& cameraPosition, const TVector3& rotateAxis, // _In_opt_ const TVector3* cameraForward = nullptr, _In_opt_ const TVector3* objectForward = nullptr); // // static TDxMatrix CreateTranslation(const TVector3& position); // static TDxMatrix CreateTranslation(float x, float y, float z); // // static TDxMatrix CreateScale(const TVector3& scales); // static TDxMatrix CreateScale(float xs, float ys, float zs); // static TDxMatrix CreateScale(float scale); // // static TDxMatrix CreateRotationX(float radians); // static TDxMatrix CreateRotationY(float radians); // static TDxMatrix CreateRotationZ(float radians); // // static TDxMatrix CreateFromAxisAngle(const TVector3& axis, float angle); // // static TDxMatrix CreatePerspectiveFieldOfView(float fov, float aspectRatio, float nearPlane, float farPlane); // static TDxMatrix CreatePerspective(float width, float height, float nearPlane, float farPlane); // static TDxMatrix CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlane, float farPlane); // static TDxMatrix CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane); // static TDxMatrix CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane); // // static TDxMatrix CreateLookAt(const TVector3& position, const TVector3& target, const TVector3& up); // static TDxMatrix CreateWorld(const TVector3& position, const TVector3& forward, const TVector3& up); // // static TDxMatrix CreateFromQuaternion(const TQuaternion& quat); // // static TDxMatrix CreateFromYawPitchRoll(float yaw, float pitch, float roll); // // static TDxMatrix CreateShadow(const TVector3& lightDir, const TPlane& plane); // // static TDxMatrix CreateReflection(const TPlane& plane); // // static void Lerp(const TDxMatrix& M1, const TDxMatrix& M2, float t, TDxMatrix& result); // static TDxMatrix Lerp(const TDxMatrix& M1, const TDxMatrix& M2, float t); // // static void Transform(const TDxMatrix& M, const TQuaternion& rotation, TDxMatrix& result); // static TDxMatrix Transform(const TDxMatrix& M, const TQuaternion& rotation); // // // Constants // static const TDxMatrix Identity; // }; // // // Binary operators // TDxMatrix operator+ (const TDxMatrix& M1, const TDxMatrix& M2); // TDxMatrix operator- (const TDxMatrix& M1, const TDxMatrix& M2); // TDxMatrix operator* (const TDxMatrix& M1, const TDxMatrix& M2); // TDxMatrix operator* (const TDxMatrix& M, float S); // TDxMatrix operator/ (const TDxMatrix& M, float S); // TDxMatrix operator/ (const TDxMatrix& M1, const TDxMatrix& M2); // // Element-wise divide // TDxMatrix operator* (float S, const TDxMatrix& M); // // // //----------------------------------------------------------------------------- // // TPlane // struct TPlane : public XMFLOAT4 // { // TPlane() noexcept : XMFLOAT4(0.f, 1.f, 0.f, 0.f) {} // XM_CONSTEXPR TPlane(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} // TPlane(const TVector3& normal, float d) : XMFLOAT4(normal.x, normal.y, normal.z, d) {} // TPlane(const TVector3& point1, const TVector3& point2, const TVector3& point3); // TPlane(const TVector3& point, const TVector3& normal); // explicit TPlane(const TVector4& v) : XMFLOAT4(v.x, v.y, v.z, v.w) {} // explicit TPlane(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} // TPlane(XMFLOAT4 V) { x = V.x; y = V.y; z = V.z; w = V.w; } // TPlane(const XMFLOAT4& p) { this->x = p.x; this->y = p.y; this->z = p.z; this->w = p.w; } // explicit TPlane(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } // // TPlane(const TPlane&) = default; // TPlane& operator=(const TPlane&) = default; // // TPlane(TPlane&&) = default; // TPlane& operator=(TPlane&&) = default; // // operator XMVECTOR() const { return XMLoadFloat4(this); } // // // Comparison operators // bool operator == (const TPlane& p) const; // bool operator != (const TPlane& p) const; // // // Assignment operators // TPlane& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } // // // Properties // TVector3 Normal() const { return TVector3(x, y, z); } // void Normal(const TVector3& normal) { x = normal.x; y = normal.y; z = normal.z; } // // float D() const { return w; } // void D(float d) { w = d; } // // // TPlane operations // void Normalize(); // void Normalize(TPlane& result) const; // // float Dot(const TVector4& v) const; // float DotCoordinate(const TVector3& position) const; // float DotNormal(const TVector3& normal) const; // // // Static functions // static void Transform(const TPlane& plane, const TDxMatrix& M, TPlane& result); // static TPlane Transform(const TPlane& plane, const TDxMatrix& M); // // static void Transform(const TPlane& plane, const TQuaternion& rotation, TPlane& result); // static TPlane Transform(const TPlane& plane, const TQuaternion& rotation); // // Input quaternion must be the inverse transpose of the transformation // }; // // //------------------------------------------------------------------------------ // // TQuaternion // struct TQuaternion : public XMFLOAT4 // { // TQuaternion() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} // XM_CONSTEXPR TQuaternion(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} // TQuaternion(const TVector3& v, float scalar) : XMFLOAT4(v.x, v.y, v.z, scalar) {} // explicit TQuaternion(const TVector4& v) : XMFLOAT4(v.x, v.y, v.z, v.w) {} // explicit TQuaternion(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} // TQuaternion(XMFLOAT4 V) { x = V.x; y = V.y; z = V.z; w = V.w; } // TQuaternion(const XMFLOAT4& q) { this->x = q.x; this->y = q.y; this->z = q.z; this->w = q.w; } // explicit TQuaternion(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } // // TQuaternion(const TQuaternion&) = default; // TQuaternion& operator=(const TQuaternion&) = default; // // TQuaternion(TQuaternion&&) = default; // TQuaternion& operator=(TQuaternion&&) = default; // // operator XMVECTOR() const { return XMLoadFloat4(this); } // // // Comparison operators // bool operator == (const TQuaternion& q) const; // bool operator != (const TQuaternion& q) const; // // // Assignment operators // TQuaternion& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } // TQuaternion& operator+= (const TQuaternion& q); // TQuaternion& operator-= (const TQuaternion& q); // TQuaternion& operator*= (const TQuaternion& q); // TQuaternion& operator*= (float S); // TQuaternion& operator/= (const TQuaternion& q); // // // Unary operators // TQuaternion operator+ () const { return *this; } // TQuaternion operator- () const; // // // TQuaternion operations // float Length() const; // float LengthSquared() const; // // void Normalize(); // void Normalize(TQuaternion& result) const; // // void Conjugate(); // void Conjugate(TQuaternion& result) const; // // void Inverse(TQuaternion& result) const; // // float Dot(const TQuaternion& Q) const; // // // Static functions // static TQuaternion CreateFromAxisAngle(const TVector3& axis, float angle); // static TQuaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll); // static TQuaternion CreateFromRotationMatrix(const TDxMatrix& M); // // static void Lerp(const TQuaternion& q1, const TQuaternion& q2, float t, TQuaternion& result); // static TQuaternion Lerp(const TQuaternion& q1, const TQuaternion& q2, float t); // // static void Slerp(const TQuaternion& q1, const TQuaternion& q2, float t, TQuaternion& result); // static TQuaternion Slerp(const TQuaternion& q1, const TQuaternion& q2, float t); // // static void Concatenate(const TQuaternion& q1, const TQuaternion& q2, TQuaternion& result); // static TQuaternion Concatenate(const TQuaternion& q1, const TQuaternion& q2); // // // Constants // static const TQuaternion Identity; // }; // // // Binary operators // TQuaternion operator+ (const TQuaternion& Q1, const TQuaternion& Q2); // TQuaternion operator- (const TQuaternion& Q1, const TQuaternion& Q2); // TQuaternion operator* (const TQuaternion& Q1, const TQuaternion& Q2); // TQuaternion operator* (const TQuaternion& Q, float S); // TQuaternion operator/ (const TQuaternion& Q1, const TQuaternion& Q2); // TQuaternion operator* (float S, const TQuaternion& Q); // // //------------------------------------------------------------------------------ // // TColor // struct TColor : public XMFLOAT4 // { // TColor() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} // XM_CONSTEXPR TColor(float _r, float _g, float _b) : XMFLOAT4(_r, _g, _b, 1.f) {} // XM_CONSTEXPR TColor(float _r, float _g, float _b, float _a) : XMFLOAT4(_r, _g, _b, _a) {} // explicit TColor(const TVector3& clr) : XMFLOAT4(clr.x, clr.y, clr.z, 1.f) {} // explicit TColor(const TVector4& clr) : XMFLOAT4(clr.x, clr.y, clr.z, clr.w) {} // explicit TColor(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} // TColor(XMFLOAT3 V) { x = V.x; y = V.y; z = V.z; } // TColor(const XMFLOAT4& c) { this->x = c.x; this->y = c.y; this->z = c.z; this->w = c.w; } // explicit TColor(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } // // explicit TColor(const DirectX::PackedVector::XMCOLOR& Packed); // // BGRA Direct3D 9 D3DCOLOR packed color // // explicit TColor(const DirectX::PackedVector::XMUBYTEN4& Packed); // // RGBA XNA Game Studio packed color // // TColor(const TColor&) = default; // TColor& operator=(const TColor&) = default; // // TColor(TColor&&) = default; // TColor& operator=(TColor&&) = default; // // operator XMVECTOR() const { return XMLoadFloat4(this); } // operator const float*() const { return reinterpret_cast<const float*>(this); } // // // Comparison operators // bool operator == (const TColor& c) const; // bool operator != (const TColor& c) const; // // // Assignment operators // TColor& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } // TColor& operator= (const DirectX::PackedVector::XMCOLOR& Packed); // TColor& operator= (const DirectX::PackedVector::XMUBYTEN4& Packed); // TColor& operator+= (const TColor& c); // TColor& operator-= (const TColor& c); // TColor& operator*= (const TColor& c); // TColor& operator*= (float S); // TColor& operator/= (const TColor& c); // // // Unary operators // TColor operator+ () const { return *this; } // TColor operator- () const; // // // Properties // float R() const { return x; } // void R(float r) { x = r; } // // float G() const { return y; } // void G(float g) { y = g; } // // float B() const { return z; } // void B(float b) { z = b; } // // float A() const { return w; } // void A(float a) { w = a; } // // // TColor operations // DirectX::PackedVector::XMCOLOR BGRA() const; // DirectX::PackedVector::XMUBYTEN4 RGBA() const; // // TVector3 ToVector3() const; // TVector4 ToVector4() const; // // void Negate(); // void Negate(TColor& result) const; // // void Saturate(); // void Saturate(TColor& result) const; // // void Premultiply(); // void Premultiply(TColor& result) const; // // void AdjustSaturation(float sat); // void AdjustSaturation(float sat, TColor& result) const; // // void AdjustContrast(float contrast); // void AdjustContrast(float contrast, TColor& result) const; // // // Static functions // static void Modulate(const TColor& c1, const TColor& c2, TColor& result); // static TColor Modulate(const TColor& c1, const TColor& c2); // // static void Lerp(const TColor& c1, const TColor& c2, float t, TColor& result); // static TColor Lerp(const TColor& c1, const TColor& c2, float t); // }; // // // Binary operators // TColor operator+ (const TColor& C1, const TColor& C2); // TColor operator- (const TColor& C1, const TColor& C2); // TColor operator* (const TColor& C1, const TColor& C2); // TColor operator* (const TColor& C, float S); // TColor operator/ (const TColor& C1, const TColor& C2); // TColor operator* (float S, const TColor& C); // // //------------------------------------------------------------------------------ // // TRay // class TRay // { // public: // TVector3 position; // TVector3 direction; // // TRay() noexcept : position(0, 0, 0), direction(0, 0, 1) {} // TRay(const TVector3& pos, const TVector3& dir) : position(pos), direction(dir) {} // // TRay(const TRay&) = default; // TRay& operator=(const TRay&) = default; // // TRay(TRay&&) = default; // TRay& operator=(TRay&&) = default; // // // Comparison operators // bool operator == (const TRay& r) const; // bool operator != (const TRay& r) const; // // // TRay operations // bool Intersects(const BoundingSphere& sphere, _Out_ float& Dist) const; // bool Intersects(const BoundingBox& box, _Out_ float& Dist) const; // bool Intersects(const TVector3& tri0, const TVector3& tri1, const TVector3& tri2, _Out_ float& Dist) const; // bool Intersects(const TPlane& plane, _Out_ float& Dist) const; // }; // // //------------------------------------------------------------------------------ // // TViewport // class TViewport // { // public: // float x; // float y; // float width; // float height; // float minDepth; // float maxDepth; // // TViewport() noexcept : // x(0.f), y(0.f), width(0.f), height(0.f), minDepth(0.f), maxDepth(1.f) {} // XM_CONSTEXPR TViewport(float ix, float iy, float iw, float ih, float iminz = 0.f, float imaxz = 1.f) : // x(ix), y(iy), width(iw), height(ih), minDepth(iminz), maxDepth(imaxz) {} // explicit TViewport(const RECT& rct) : // x(float(rct.left)), y(float(rct.top)), // width(float(rct.right - rct.left)), // height(float(rct.bottom - rct.top)), // minDepth(0.f), maxDepth(1.f) {} // //#if defined(__d3d11_h__) || defined(__d3d11_x_h__) // // Direct3D 11 interop // explicit TViewport(const D3D11_VIEWPORT& vp) : // x(vp.TopLeftX), y(vp.TopLeftY), // width(vp.Width), height(vp.Height), // minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) {} // // operator D3D11_VIEWPORT() { return *reinterpret_cast<const D3D11_VIEWPORT*>(this); } // const D3D11_VIEWPORT* Get11() const { return reinterpret_cast<const D3D11_VIEWPORT*>(this); } // TViewport& operator= (const D3D11_VIEWPORT& vp); //#endif // //#if defined(__d3d12_h__) || defined(__d3d12_x_h__) // // Direct3D 12 interop // explicit TViewport(const D3D12_VIEWPORT& vp) : // x(vp.TopLeftX), y(vp.TopLeftY), // width(vp.Width), height(vp.Height), // minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) {} // // operator D3D12_VIEWPORT() { return *reinterpret_cast<const D3D12_VIEWPORT*>(this); } // const D3D12_VIEWPORT* Get12() const { return reinterpret_cast<const D3D12_VIEWPORT*>(this); } // TViewport& operator= (const D3D12_VIEWPORT& vp); //#endif // // TViewport(const TViewport&) = default; // TViewport& operator=(const TViewport&) = default; // // TViewport(TViewport&&) = default; // TViewport& operator=(TViewport&&) = default; // // // Comparison operators // bool operator == (const TViewport& vp) const; // bool operator != (const TViewport& vp) const; // // // Assignment operators // TViewport& operator= (const RECT& rct); // // // TViewport operations // float AspectRatio() const; // // TVector3 Project(const TVector3& p, const TDxMatrix& proj, const TDxMatrix& view, const TDxMatrix& world) const; // void Project(const TVector3& p, const TDxMatrix& proj, const TDxMatrix& view, const TDxMatrix& world, TVector3& result) const; // // TVector3 Unproject(const TVector3& p, const TDxMatrix& proj, const TDxMatrix& view, const TDxMatrix& world) const; // void Unproject(const TVector3& p, const TDxMatrix& proj, const TDxMatrix& view, const TDxMatrix& world, TVector3& result) const; // // // Static methods // static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight); // static RECT __cdecl ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight); // }; // // // ///////////////////////////////////////// static /////////////////////////////////////////// // //-------------------------- // // 2D Vector // //-------------------------- // // static float D3DXVec2Length(CONST TVector2 *pV) // { // return pV->Length(); // } // // static float D3DXVec2LengthSq(CONST TVector2 *pV) // { // return 0.0f; // } // // static float D3DXVec2Dot(CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return 0.0f; // } // // // Z component of ((x1,y1,0) cross (x2,y2,0)) // static float D3DXVec2CCW(CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return 0.0f; // } // // static TVector2* D3DXVec2Add(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return pOut; // } // // static TVector2* D3DXVec2Subtract(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return pOut; // } // // // Minimize each component. x = min(x1, x2), y = min(y1, y2) // static TVector2* D3DXVec2Minimize(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return pOut; // } // // // Maximize each component. x = max(x1, x2), y = max(y1, y2) // static TVector2* D3DXVec2Maximize(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2) // { // return pOut; // } // // static TVector2* D3DXVec2Scale(TVector2 *pOut, CONST TVector2 *pV, float s) // { // return pOut; // } // // // Linear interpolation. V1 + s(V2-V1) // static TVector2* D3DXVec2Lerp(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2, // float s) // { // return pOut; // } // static TVector2* D3DXVec2Normalize(TVector2 *pOut, CONST TVector2 *pV) // { // return pOut; // } // // // Hermite interpolation between position V1, tangent T1 (when s == 0) // // and position V2, tangent T2 (when s == 1). // static TVector2* D3DXVec2Hermite(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pT1, // CONST TVector2 *pV2, CONST TVector2 *pT2, float s) // { // return pOut; // } // // // CatmullRom interpolation between V1 (when s == 0) and V2 (when s == 1) // static TVector2* D3DXVec2CatmullRom(TVector2 *pOut, CONST TVector2 *pV0, CONST TVector2 *pV1, // CONST TVector2 *pV2, CONST TVector2 *pV3, float s) // { // return pOut; // } // // // Barycentric coordinates. V1 + f(V2-V1) + g(V3-V1) // static TVector2* D3DXVec2BaryCentric(TVector2 *pOut, CONST TVector2 *pV1, CONST TVector2 *pV2, // CONST TVector2 *pV3, float f, float g) // { // return pOut; // } // // // Transform (x, y, 0, 1) by matrix. // static TVector4* D3DXVec2Transform(TVector4 *pOut, CONST TVector2 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // Transform (x, y, 0, 1) by matrix, project result back into w=1. // static TVector2* D3DXVec2TransformCoord(TVector2 *pOut, CONST TVector2 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // Transform (x, y, 0, 0) by matrix. // static TVector2* D3DXVec2TransformNormal(TVector2 *pOut, CONST TVector2 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // Transform Array (x, y, 0, 1) by matrix. // static TVector4* D3DXVec2TransformArray(TVector4 *pOut, UINT OutStride, CONST TVector2 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // Transform Array (x, y, 0, 1) by matrix, project result back into w=1. // static TVector2* D3DXVec2TransformCoordArray(TVector2 *pOut, UINT OutStride, CONST TVector2 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // Transform Array (x, y, 0, 0) by matrix. // static TVector2* D3DXVec2TransformNormalArray(TVector2 *pOut, UINT OutStride, CONST TVector2 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // //-------------------------- // // 3D Vector // //-------------------------- // // static float D3DXVec3Dot(CONST TVector3 *pV1, CONST TVector3 *pV2) // { // return pV1->Dot(*pV2); // } // static TVector3* D3DXVec3Cross(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2) // { // *pOut = pV1->Cross(*pV2); // return pOut; // } // static TVector3* D3DXVec3Normalize(TVector3 *pOut, CONST TVector3 *pV) // { // pV->Normalize(*pOut); // return pOut; // } // static TVector3* D3DXVec3TransformCoord(TVector3 *pOut, CONST TVector3 *pV, CONST TDxMatrix *pM) // { // *pOut = TVector3::Transform(*pV, *pM); // return pOut; // } // static float D3DXVec3Length(CONST TVector3 *pV) // { // return pV->Length(); // } // // // // static float D3DXVec3LengthSq(CONST TVector3 *pV) // { // return 0.0f; // } // // // static TVector3* D3DXVec3Add(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2) // { // return pOut; // } // // static TVector3* D3DXVec3Subtract(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2) // { // return pOut; // } // // // Minimize each component. x = min(x1, x2), y = min(y1, y2), ... // static TVector3* D3DXVec3Minimize(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2) { // } // // // Maximize each component. x = max(x1, x2), y = max(y1, y2), ... // static TVector3* D3DXVec3Maximize(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2) // { // return pOut; // } // // static TVector3* D3DXVec3Scale(TVector3 *pOut, CONST TVector3 *pV, float s) // { // return pOut; // } // // // Linear interpolation. V1 + s(V2-V1) // static TVector3* D3DXVec3Lerp(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2, float s) // { // return pOut; // } // // // // Hermite interpolation between position V1, tangent T1 (when s == 0) // // and position V2, tangent T2 (when s == 1). // static TVector3* D3DXVec3Hermite(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pT1, // CONST TVector3 *pV2, CONST TVector3 *pT2, float s) // { // } // // // CatmullRom interpolation between V1 (when s == 0) and V2 (when s == 1) // static TVector3* D3DXVec3CatmullRom(TVector3 *pOut, CONST TVector3 *pV0, CONST TVector3 *pV1, // CONST TVector3 *pV2, CONST TVector3 *pV3, float s) // { // return pOut; // } // // // Barycentric coordinates. V1 + f(V2-V1) + g(V3-V1) // static TVector3* D3DXVec3BaryCentric(TVector3 *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2, // CONST TVector3 *pV3, float f, float g) // { // return pOut; // } // // // Transform (x, y, z, 1) by matrix. // static TVector4* D3DXVec3Transform(TVector4 *pOut, CONST TVector3 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // Transform (x, y, z, 0) by matrix. If you transforming a normal by a // // non-affine matrix, the matrix you pass to this function should be the // // transpose of the inverse of the matrix you would use to transform a coord. // static TVector3* D3DXVec3TransformNormal(TVector3 *pOut, CONST TVector3 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // // Transform Array (x, y, z, 1) by matrix. // static TVector4* D3DXVec3TransformArray(TVector4 *pOut, UINT OutStride, CONST TVector3 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // Transform Array (x, y, z, 1) by matrix, project result back into w=1. // static TVector3* D3DXVec3TransformCoordArray(TVector3 *pOut, UINT OutStride, CONST TVector3 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // Transform (x, y, z, 0) by matrix. If you transforming a normal by a // // non-affine matrix, the matrix you pass to this function should be the // // transpose of the inverse of the matrix you would use to transform a coord. // static TVector3* D3DXVec3TransformNormalArray(TVector3 *pOut, UINT OutStride, CONST TVector3 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // Project vector from object space into screen space // static TVector3* D3DXVec3Project(TVector3 *pOut, CONST TVector3 *pV, CONST D3D10_VIEWPORT *pViewport, // CONST TDxMatrix *pProjection, CONST TDxMatrix *pView, CONST TDxMatrix *pWorld) // { // return pOut; // } // // // Project vector from screen space into object space // static TVector3* D3DXVec3Unproject(TVector3 *pOut, CONST TVector3 *pV, CONST D3D10_VIEWPORT *pViewport, // CONST TDxMatrix *pProjection, CONST TDxMatrix *pView, CONST TDxMatrix *pWorld) // { // return pOut; // } // // // Project vector Array from object space into screen space // static TVector3* D3DXVec3ProjectArray(TVector3 *pOut, UINT OutStride, CONST TVector3 *pV, UINT VStride, CONST D3D10_VIEWPORT *pViewport, // CONST TDxMatrix *pProjection, CONST TDxMatrix *pView, CONST TDxMatrix *pWorld, UINT n) // { // return pOut; // } // // // Project vector Array from screen space into object space // static TVector3* D3DXVec3UnprojectArray(TVector3 *pOut, UINT OutStride, CONST TVector3 *pV, UINT VStride, CONST D3D10_VIEWPORT *pViewport, // CONST TDxMatrix *pProjection, CONST TDxMatrix *pView, CONST TDxMatrix *pWorld, UINT n) // { // return pOut; // } // // //-------------------------- // // 4D Vector // //-------------------------- // // static float D3DXVec4Length(CONST TVector4 *pV) // { // return pV->Length(); // } // // // static float D3DXVec4LengthSq(CONST TVector4 *pV) // { // return 0.0f; // } // // static float D3DXVec4Dot(CONST TVector4 *pV1, CONST TVector4 *pV2) // { // return 0.0f; // } // static TVector4* D3DXVec4Add(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2) // { // return pOut; // } // // static TVector4* D3DXVec4Subtract(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2) // { // return pOut; // } // // // Minimize each component. x = min(x1, x2), y = min(y1, y2), ... // static TVector4* D3DXVec4Minimize(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2) // { // return pOut; // } // // // Maximize each component. x = max(x1, x2), y = max(y1, y2), ... // static TVector4* D3DXVec4Maximize(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2) // { // return pOut; // } // static TVector4* D3DXVec4Scale(TVector4 *pOut, CONST TVector4 *pV, float s) { // return pOut; // } // // // Linear interpolation. V1 + s(V2-V1) // static TVector4* D3DXVec4Lerp(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2, float s) // { // return pOut; // } // // // Cross-product in 4 dimensions. // static TVector4* D3DXVec4Cross(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2, // CONST TVector4 *pV3) // { // return pOut; // } // // static TVector4* D3DXVec4Normalize(TVector4 *pOut, CONST TVector4 *pV) // { // return pOut; // } // // // Hermite interpolation between position V1, tangent T1 (when s == 0) // // and position V2, tangent T2 (when s == 1). // static TVector4* D3DXVec4Hermite(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pT1, // CONST TVector4 *pV2, CONST TVector4 *pT2, float s) // { // return pOut; // } // // // CatmullRom interpolation between V1 (when s == 0) and V2 (when s == 1) // static TVector4* D3DXVec4CatmullRom(TVector4 *pOut, CONST TVector4 *pV0, CONST TVector4 *pV1, // CONST TVector4 *pV2, CONST TVector4 *pV3, float s) // { // return pOut; // } // // // Barycentric coordinates. V1 + f(V2-V1) + g(V3-V1) // static TVector4* D3DXVec4BaryCentric(TVector4 *pOut, CONST TVector4 *pV1, CONST TVector4 *pV2, // CONST TVector4 *pV3, float f, float g) // { // return pOut; // } // // // Transform vector by matrix. // static TVector4* D3DXVec4Transform(TVector4 *pOut, CONST TVector4 *pV, CONST TDxMatrix *pM) // { // return pOut; // } // // // Transform vector array by matrix. // static TVector4* D3DXVec4TransformArray(TVector4 *pOut, UINT OutStride, CONST TVector4 *pV, UINT VStride, CONST TDxMatrix *pM, UINT n) // { // return pOut; // } // // // static TDxMatrix* D3DXMatrixIdentity(TDxMatrix *pOut) // { // pOut->Identity(4, 4); // return pOut; // } // static TDxMatrix* D3DXMatrixRotationQuaternion(TDxMatrix *pOut, CONST TQuaternion *pQ) // { // *pOut = TDxMatrix::CreateFromQuaternion(*pQ); // return pOut; // } // static TQuaternion* D3DXQuaternionRotationMatrix(TQuaternion *pOut, CONST TDxMatrix *pM) // { // *pOut = TQuaternion::CreateFromRotationMatrix(*pM); // return pOut; // } // // static float D3DXMatrixDeterminant(CONST TDxMatrix *pM) { // return pM->Determinant(); // } // // static HRESULT D3DXMatrixDecompose(TVector3 *pOutScale, TQuaternion *pOutRotation, // TVector3 *pOutTranslation, TDxMatrix *pM) // { // if (pM->Decompose(*pOutScale, *pOutRotation, *pOutTranslation) == false) // { // return S_FALSE; // } // return S_OK; // } // // static TDxMatrix* D3DXMatrixTranspose(TDxMatrix *pOut, CONST TDxMatrix *pM) { // // return pOut; // } // // // Matrix multiplication. The result represents the transformation M2 // // followed by the transformation M1. (Out = M1 * M2) // static TDxMatrix* D3DXMatrixMultiply(TDxMatrix *pOut, CONST TDxMatrix *pM1, CONST TDxMatrix *pM2) { // *pOut = (*pM1) * (*pM2); // return pOut; // } // // // Matrix multiplication, followed by a transpose. (Out = T(M1 * M2)) // static TDxMatrix* D3DXMatrixMultiplyTranspose(TDxMatrix *pOut, CONST TDxMatrix *pM1, CONST TDxMatrix *pM2) { // // *pOut = (*pM1) * (*pM2); // pOut->Transpose(); // return pOut; // } // // // Calculate inverse of matrix. Inversion my fail, in which case NULL will // // be returned. The determinant of pM is also returned it pfDeterminant // // is non-NULL. // static TDxMatrix* D3DXMatrixInverse(TDxMatrix *pOut, float *pDeterminant, CONST TDxMatrix *pM) { // pM->Invert(*pOut); // *pDeterminant = pM->Determinant(); // return pOut; // } // // // Build a matrix which scales by (sx, sy, sz) // static TDxMatrix* D3DXMatrixScaling(TDxMatrix *pOut, float sx, float sy, float sz) { // *pOut = TDxMatrix::CreateScale(sx, sy, sz); // return pOut; // } // // // Build a matrix which translates by (x, y, z) // static TDxMatrix* D3DXMatrixTranslation(TDxMatrix *pOut, float x, float y, float z) { // *pOut = TDxMatrix::CreateTranslation(x, y, z); // return pOut; // } // // // Build a matrix which rotates around the X axis // static TDxMatrix* D3DXMatrixRotationX(TDxMatrix *pOut, float Angle) { // *pOut = TDxMatrix::CreateRotationX(Angle); // return pOut; // } // // // Build a matrix which rotates around the Y axis // static TDxMatrix* D3DXMatrixRotationY(TDxMatrix *pOut, float Angle) { // *pOut = TDxMatrix::CreateRotationY(Angle); // return pOut; // } // // // Build a matrix which rotates around the Z axis // static TDxMatrix* D3DXMatrixRotationZ(TDxMatrix *pOut, float Angle) { // *pOut = TDxMatrix::CreateRotationZ(Angle); // return pOut; // } // // // Build a matrix which rotates around an arbitrary axis // static TDxMatrix* D3DXMatrixRotationAxis(TDxMatrix *pOut, CONST TVector3 *pV, float Angle) { // *pOut = TDxMatrix::CreateFromAxisAngle(*pV, Angle); // return pOut; // } // // // Yaw around the Y axis, a pitch around the X axis, // // and a roll around the Z axis. // static TDxMatrix* D3DXMatrixRotationYawPitchRoll(TDxMatrix *pOut, float Yaw, float Pitch, float Roll) { // *pOut = TDxMatrix::CreateFromYawPitchRoll(Yaw, Pitch, Roll); // return pOut; // } // // // Build transformation matrix. NULL arguments are treated as identity. // // Mout = Msc-1 * Msr-1 * Ms * Msr * Msc * Mrc-1 * Mr * Mrc * Mt // static TDxMatrix* D3DXMatrixTransformation(TDxMatrix *pOut, CONST TVector3 *pScalingCenter, // CONST TQuaternion *pScalingRotation, CONST TVector3 *pScaling, // CONST TVector3 *pRotationCenter, CONST TQuaternion *pRotation, // CONST TVector3 *pTranslation) // { // return pOut; // } // // // Build 2D transformation matrix in XY plane. NULL arguments are treated as identity. // // Mout = Msc-1 * Msr-1 * Ms * Msr * Msc * Mrc-1 * Mr * Mrc * Mt // static TDxMatrix* D3DXMatrixTransformation2D(TDxMatrix *pOut, CONST TVector2* pScalingCenter, // float ScalingRotation, CONST TVector2* pScaling, // CONST TVector2* pRotationCenter, float Rotation, // CONST TVector2* pTranslation) { // return pOut; // } // // // Build affine transformation matrix. NULL arguments are treated as identity. // // Mout = Ms * Mrc-1 * Mr * Mrc * Mt // static TDxMatrix* D3DXMatrixAffineTransformation(TDxMatrix *pOut, float Scaling, CONST TVector3 *pRotationCenter, // CONST TQuaternion *pRotation, CONST TVector3 *pTranslation) { // return pOut; // } // // // Build 2D affine transformation matrix in XY plane. NULL arguments are treated as identity. // // Mout = Ms * Mrc-1 * Mr * Mrc * Mt // static TDxMatrix* D3DXMatrixAffineTransformation2D(TDxMatrix *pOut, float Scaling, CONST TVector2* pRotationCenter, // float Rotation, CONST TVector2* pTranslation) { // return pOut; // } // // // Build a lookat matrix. (right-handed) // static TDxMatrix* D3DXMatrixLookAtRH(TDxMatrix *pOut, CONST TVector3 *pEye, CONST TVector3 *pAt, CONST TVector3 *pUp) { // return pOut; // } // // // Build a lookat matrix. (left-handed) // static TDxMatrix* D3DXMatrixLookAtLH(TDxMatrix *pOut, CONST TVector3 *pEye, CONST TVector3 *pAt, CONST TVector3 *pUp) { // *pOut = TDxMatrix::CreateLookAt(*pEye, *pAt, *pUp); // return pOut; // } // // // Build a perspective projection matrix. (right-handed) // static TDxMatrix* D3DXMatrixPerspectiveRH(TDxMatrix *pOut, float w, float h, float zn, float zf) { // return pOut; // } // // // Build a perspective projection matrix. (left-handed) // static TDxMatrix* D3DXMatrixPerspectiveLH(TDxMatrix *pOut, float w, float h, float zn, float zf) { // *pOut = TDxMatrix::CreatePerspective(w, h, zn, zf); // return pOut; // } // // // Build a perspective projection matrix. (right-handed) // static TDxMatrix* D3DXMatrixPerspectiveFovRH(TDxMatrix *pOut, float fovy, float Aspect, float zn, float zf) { // return pOut; // } // // // Build a perspective projection matrix. (left-handed) // static TDxMatrix* D3DXMatrixPerspectiveFovLH(TDxMatrix *pOut, float fovy, float Aspect, float zn, float zf) { // *pOut = TDxMatrix::CreatePerspectiveFieldOfView(fovy, Aspect, zn, zf); // return pOut; // } // // // Build a perspective projection matrix. (right-handed) // static TDxMatrix* D3DXMatrixPerspectiveOffCenterRH(TDxMatrix *pOut, float l, float r, float b, float t, float zn, float zf) { // return pOut; // } // // // Build a perspective projection matrix. (left-handed) // static TDxMatrix* D3DXMatrixPerspectiveOffCenterLH(TDxMatrix *pOut, float l, float r, float b, float t, float zn, float zf) { // *pOut = TDxMatrix::CreatePerspectiveOffCenter(l, r, b, t, zn, zf); // return pOut; // } // // // Build an ortho projection matrix. (right-handed) // static TDxMatrix* D3DXMatrixOrthoRH(TDxMatrix *pOut, float w, float h, float zn, float zf) { // return pOut; // } // // // Build an ortho projection matrix. (left-handed) // static TDxMatrix* D3DXMatrixOrthoLH(TDxMatrix *pOut, float w, float h, float zn, float zf) { // *pOut = TDxMatrix::CreateOrthographic(w, h, zn, zf); // return pOut; // } // // // Build an ortho projection matrix. (right-handed) // static TDxMatrix* D3DXMatrixOrthoOffCenterRH(TDxMatrix *pOut, float l, float r, float b, float t, float zn, float zf) { // return pOut; // } // // // Build an ortho projection matrix. (left-handed) // static TDxMatrix* D3DXMatrixOrthoOffCenterLH(TDxMatrix *pOut, float l, float r, float b, float t, float zn, float zf) { // *pOut = TDxMatrix::CreateOrthographicOffCenter(l, r, b, t, zn, zf); // return pOut; // } // // // Build a matrix which flattens geometry into a plane, as if casting // // a shadow from a light. // static TDxMatrix* D3DXMatrixShadow(TDxMatrix *pOut, CONST TVector4 *pLight, CONST TPlane *pPlane) { // //*pOut = TDxMatrix::CreateShadow( *pLight, *pPlane); // return pOut; // } // // // Build a matrix which reflects the coordinate system about a plane // static TDxMatrix* D3DXMatrixReflect(TDxMatrix *pOut, CONST TPlane *pPlane) { // *pOut = TDxMatrix::CreateReflection(*pPlane); // return pOut; // } // // //-------------------------- // // Quaternion // //-------------------------- // // // inline // // static float D3DXQuaternionLength(CONST TQuaternion *pQ) // { // return 0.0f; // }; // // // Length squared, or "norm" // static float D3DXQuaternionLengthSq(CONST TQuaternion *pQ) { // return 0.0f; // }; // // static float D3DXQuaternionDot // (CONST TQuaternion *pQ1, CONST TQuaternion *pQ2) { // return 0.0f; // }; // // // (0, 0, 0, 1) // static TQuaternion* D3DXQuaternionIdentity(TQuaternion *pOut) { // return pOut; // }; // // static BOOL D3DXQuaternionIsIdentity(CONST TQuaternion *pQ) { // return TRUE; // }; // // // (-x, -y, -z, w) // static TQuaternion* D3DXQuaternionConjugate(TQuaternion *pOut, CONST TQuaternion *pQ) { // return pOut; // }; // // // // Compute a quaternin's axis and angle of rotation. Expects unit quaternions. // static void D3DXQuaternionToAxisAngle(CONST TQuaternion *pQ, TVector3 *pAxis, float *pAngle) { // }; // // static TQuaternion* D3DXQuaternionRotationAxis(TQuaternion *pOut, CONST TVector3 *pV, FLOAT Angle) // { // *pOut = TQuaternion::CreateFromAxisAngle(*pV, Angle); // return pOut; // } // // // Yaw around the Y axis, a pitch around the X axis, // // and a roll around the Z axis. // static TQuaternion* D3DXQuaternionRotationYawPitchRoll(TQuaternion *pOut, float Yaw, float Pitch, float Roll) { // return pOut; // }; // // // Quaternion multiplication. The result represents the rotation Q2 // // followed by the rotation Q1. (Out = Q2 * Q1) // static TQuaternion* D3DXQuaternionMultiply(TQuaternion *pOut, CONST TQuaternion *pQ1, // CONST TQuaternion *pQ2) { // return pOut; // }; // // static TQuaternion* D3DXQuaternionNormalize(TQuaternion *pOut, CONST TQuaternion *pQ) { // return pOut; // }; // // // Conjugate and re-norm // static TQuaternion* D3DXQuaternionInverse(TQuaternion *pOut, CONST TQuaternion *pQ) { // return pOut; // }; // // // Expects unit quaternions. // // if q = (cos(theta), sin(theta) * v); ln(q) = (0, theta * v) // static TQuaternion* D3DXQuaternionLn(TQuaternion *pOut, CONST TQuaternion *pQ) { // return pOut; // }; // // // Expects pure quaternions. (w == 0) w is ignored in calculation. // // if q = (0, theta * v); exp(q) = (cos(theta), sin(theta) * v) // static TQuaternion* D3DXQuaternionExp(TQuaternion *pOut, CONST TQuaternion *pQ) { // return pOut; // }; // // // Spherical linear interpolation between Q1 (t == 0) and Q2 (t == 1). // // Expects unit quaternions. // static TQuaternion* D3DXQuaternionSlerp(TQuaternion *pOut, CONST TQuaternion *pQ1, // CONST TQuaternion *pQ2, float t) { // return pOut; // }; // // // Spherical quadrangle interpolation. // // Slerp(Slerp(Q1, C, t), Slerp(A, B, t), 2t(1-t)) // static TQuaternion* D3DXQuaternionSquad(TQuaternion *pOut, CONST TQuaternion *pQ1, // CONST TQuaternion *pA, CONST TQuaternion *pB, // CONST TQuaternion *pC, float t) { // return pOut; // }; // // // Setup control points for spherical quadrangle interpolation // // from Q1 to Q2. The control points are chosen in such a way // // to ensure the continuity of tangents with adjacent segments. // static void D3DXQuaternionSquadSetup(TQuaternion *pAOut, TQuaternion *pBOut, TQuaternion *pCOut, // CONST TQuaternion *pQ0, CONST TQuaternion *pQ1, // CONST TQuaternion *pQ2, CONST TQuaternion *pQ3) { // }; // // // Barycentric interpolation. // // Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g)) // static TQuaternion* D3DXQuaternionBaryCentric(TQuaternion *pOut, CONST TQuaternion *pQ1, // CONST TQuaternion *pQ2, CONST TQuaternion *pQ3, // float f, float g) { // return pOut; // }; // // // //-------------------------- // // Plane // //-------------------------- // // // inline // // // ax + by + cz + dw // static float D3DXPlaneDot(CONST TPlane *pP, CONST TVector4 *pV) { // return 0.0f; // }; // // ax + by + cz + d // static float D3DXPlaneDotCoord(CONST TPlane *pP, CONST TVector3 *pV) { // return 0.0f; // }; // // ax + by + cz // static float D3DXPlaneDotNormal(CONST TPlane *pP, CONST TVector3 *pV) { // return 0.0f; // }; // static TPlane* D3DXPlaneScale(TPlane *pOut, CONST TPlane *pP, float s) { // return pOut; // }; // // // // Normalize plane (so that |a,b,c| == 1) // static TPlane* D3DXPlaneNormalize(TPlane *pOut, CONST TPlane *pP) { // return pOut; // }; // // // Find the intersection between a plane and a line. If the line is // // parallel to the plane, NULL is returned. // static TVector3* D3DXPlaneIntersectLine(TVector3 *pOut, CONST TPlane *pP, CONST TVector3 *pV1, // CONST TVector3 *pV2) { // return pOut; // }; // // // Construct a plane from a point and a normal // static TPlane* D3DXPlaneFromPointNormal(TPlane *pOut, CONST TVector3 *pPoint, CONST TVector3 *pNormal) { // return pOut; // }; // // // Construct a plane from 3 points // static TPlane* D3DXPlaneFromPoints(TPlane *pOut, CONST TVector3 *pV1, CONST TVector3 *pV2, // CONST TVector3 *pV3) { // return pOut; // }; // // // Transform a plane by a matrix. The vector (a,b,c) must be normal. // // M should be the inverse transpose of the transformation desired. // static TPlane* D3DXPlaneTransform(TPlane *pOut, CONST TPlane *pP, CONST TDxMatrix *pM) { // return pOut; // }; // // Transform an array of planes by a matrix. The vectors (a,b,c) must be normal. //// M should be the inverse transpose of the transformation desired. // static TPlane* D3DXPlaneTransformArray(TPlane *pOut, UINT OutStride, CONST TPlane *pP, UINT PStride, CONST TDxMatrix *pM, UINT n) { // return pOut; // }; // // // // //-------------------------- // // Color // //-------------------------- // // // inline // // // (1-r, 1-g, 1-b, a) // static TColor* D3DXColorNegative(TColor *pOut, CONST TColor *pC) { // return pOut; // }; // // static TColor* D3DXColorAdd(TColor *pOut, CONST TColor *pC1, CONST TColor *pC2) { // return pOut; // }; // // static TColor* D3DXColorSubtract(TColor *pOut, CONST TColor *pC1, CONST TColor *pC2) { // return pOut; // }; // // static TColor* D3DXColorScale(TColor *pOut, CONST TColor *pC, float s) { // return pOut; // }; // // // (r1*r2, g1*g2, b1*b2, a1*a2) // static TColor* D3DXColorModulate(TColor *pOut, CONST TColor *pC1, CONST TColor *pC2) { // return pOut; // }; // // // Linear interpolation of r,g,b, and a. C1 + s(C2-C1) // static TColor* D3DXColorLerp(TColor *pOut, CONST TColor *pC1, CONST TColor *pC2, float s) { // return pOut; // }; // // // // Interpolate r,g,b between desaturated color and color. // // DesaturatedColor + s(Color - DesaturatedColor) // static TColor* D3DXColorAdjustSaturation(TColor *pOut, CONST TColor *pC, float s) { // return pOut; // }; // // Interpolate r,g,b between 50% grey and color. Grey + s(Color - Grey) // static TColor* D3DXColorAdjustContrast(TColor *pOut, CONST TColor *pC, float c) { // return pOut; // }; // // // // // // //-------------------------- // // Misc // //-------------------------- // // Calculate Fresnel term given the cosine of theta (likely obtained by // // taking the dot of two normals), and the refraction index of the material. // static float D3DXFresnelTerm(float CosTheta, float RefractionIndex) // { // return 0.0f; // }; //} // //// ------------------------------------------------------------------------------ //// Support for TMath and Standard C++ Library containers //namespace std //{ // template<> struct less<TBASIS_EX::TRectangle> // { // bool operator()(const TBASIS_EX::TRectangle& r1, const TBASIS_EX::TRectangle& r2) const // { // return ((r1.x < r2.x) // || ((r1.x == r2.x) && (r1.y < r2.y)) // || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width < r2.width)) // || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height < r2.height))); // } // }; // // template<> struct less<TBASIS_EX::TVector2> // { // bool operator()(const TBASIS_EX::TVector2& V1, const TBASIS_EX::TVector2& V2) const // { // return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y))); // } // }; // // template<> struct less<TBASIS_EX::TVector3> // { // bool operator()(const TBASIS_EX::TVector3& V1, const TBASIS_EX::TVector3& V2) const // { // return ((V1.x < V2.x) // || ((V1.x == V2.x) && (V1.y < V2.y)) // || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z))); // } // }; // // template<> struct less<TBASIS_EX::TVector4> // { // bool operator()(const TBASIS_EX::TVector4& V1, const TBASIS_EX::TVector4& V2) const // { // return ((V1.x < V2.x) // || ((V1.x == V2.x) && (V1.y < V2.y)) // || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z)) // || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z == V2.z) && (V1.w < V2.w))); // } // }; // // template<> struct less<TBASIS_EX::TDxMatrix> // { // bool operator()(const TBASIS_EX::TDxMatrix& M1, const TBASIS_EX::TDxMatrix& M2) const // { // if (M1._11 != M2._11) return M1._11 < M2._11; // if (M1._12 != M2._12) return M1._12 < M2._12; // if (M1._13 != M2._13) return M1._13 < M2._13; // if (M1._14 != M2._14) return M1._14 < M2._14; // if (M1._21 != M2._21) return M1._21 < M2._21; // if (M1._22 != M2._22) return M1._22 < M2._22; // if (M1._23 != M2._23) return M1._23 < M2._23; // if (M1._24 != M2._24) return M1._24 < M2._24; // if (M1._31 != M2._31) return M1._31 < M2._31; // if (M1._32 != M2._32) return M1._32 < M2._32; // if (M1._33 != M2._33) return M1._33 < M2._33; // if (M1._34 != M2._34) return M1._34 < M2._34; // if (M1._41 != M2._41) return M1._41 < M2._41; // if (M1._42 != M2._42) return M1._42 < M2._42; // if (M1._43 != M2._43) return M1._43 < M2._43; // if (M1._44 != M2._44) return M1._44 < M2._44; // // return false; // } // }; // // template<> struct less<TBASIS_EX::TPlane> // { // bool operator()(const TBASIS_EX::TPlane& P1, const TBASIS_EX::TPlane& P2) const // { // return ((P1.x < P2.x) // || ((P1.x == P2.x) && (P1.y < P2.y)) // || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z < P2.z)) // || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z == P2.z) && (P1.w < P2.w))); // } // }; // // template<> struct less<TBASIS_EX::TQuaternion> // { // bool operator()(const TBASIS_EX::TQuaternion& Q1, const TBASIS_EX::TQuaternion& Q2) const // { // return ((Q1.x < Q2.x) // || ((Q1.x == Q2.x) && (Q1.y < Q2.y)) // || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z < Q2.z)) // || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z == Q2.z) && (Q1.w < Q2.w))); // } // }; // // template<> struct less<TBASIS_EX::TColor> // { // bool operator()(const TBASIS_EX::TColor& C1, const TBASIS_EX::TColor& C2) const // { // return ((C1.x < C2.x) // || ((C1.x == C2.x) && (C1.y < C2.y)) // || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z < C2.z)) // || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z == C2.z) && (C1.w < C2.w))); // } // }; // // template<> struct less<TBASIS_EX::TRay> // { // bool operator()(const TBASIS_EX::TRay& R1, const TBASIS_EX::TRay& R2) const // { // if (R1.position.x != R2.position.x) return R1.position.x < R2.position.x; // if (R1.position.y != R2.position.y) return R1.position.y < R2.position.y; // if (R1.position.z != R2.position.z) return R1.position.z < R2.position.z; // // if (R1.direction.x != R2.direction.x) return R1.direction.x < R2.direction.x; // if (R1.direction.y != R2.direction.y) return R1.direction.y < R2.direction.y; // if (R1.direction.z != R2.direction.z) return R1.direction.z < R2.direction.z; // // return false; // } // }; // // template<> struct less<TBASIS_EX::TViewport> // { // bool operator()(const TBASIS_EX::TViewport& vp1, const TBASIS_EX::TViewport& vp2) const // { // if (vp1.x != vp2.x) return (vp1.x < vp2.x); // if (vp1.y != vp2.y) return (vp1.y < vp2.y); // // if (vp1.width != vp2.width) return (vp1.width < vp2.width); // if (vp1.height != vp2.height) return (vp1.height < vp2.height); // // if (vp1.minDepth != vp2.minDepth) return (vp1.minDepth < vp2.minDepth); // if (vp1.maxDepth != vp2.maxDepth) return (vp1.maxDepth < vp2.maxDepth); // // return false; // } // }; // // //}; // <file_sep>#include "SSPacket.h" // SSPacket packet; // int id , ps , money; // char email[30], address[30]; // packet.SetID(1002) << id << ps; // packet.SetID(1002) << id << ps << email << addree << money; // packet.SetID(1002) >> id >> ps >> email >> addree >> money; // SSPacket packet(1002); // packet << id << ps; // packet >> id >> ps; WORD SSPacket::GetID() { return *m_PacketHeader.type; } WORD SSPacket::GetSize() { return *m_PacketHeader.len; } char* SSPacket::GetData() { return m_strPacketBuffer; } int SSPacket::GetDataSize() { return m_iReceivedSize; } void SSPacket::ReadData(void* buffer, int iSize) { ::CopyMemory(buffer, m_pstrReadPosition, iSize); m_pstrReadPosition += iSize; }; void SSPacket::WriteData(void* buffer, int iSize) { if (m_iReceivedSize >= PACKETBUFFERSIZE - 4) { // 오류 } *m_PacketHeader.len += iSize; CopyMemory(m_pstrWritePosition, buffer, iSize); // 1차원 배열의 주소가 이동 m_pstrWritePosition += iSize; // 실제 데이터의 바이트 용량 m_iReceivedSize += iSize; }; SSPacket& SSPacket::SetID(unsigned short ID) { *m_PacketHeader.type = ID; return *this; }; // 패킷을 생성할 떄 sum - a.v + b.v + c.v + d.v + e.v; SSPacket& SSPacket::operator << (int arg) { WriteData(&arg, sizeof(int)); return *this; }; SSPacket& SSPacket::operator >> (int& arg) { WriteData(&arg, sizeof(int)); return *this; }; SSPacket& SSPacket::operator << (DWORD arg) { WriteData(&arg, sizeof(DWORD)); return *this; }; SSPacket& SSPacket::operator >> (DWORD& arg) { ReadData(&arg, sizeof(DWORD)); return *this; }; SSPacket& SSPacket::operator << (bool arg) { WriteData(&arg, sizeof(bool)); return *this; }; SSPacket& SSPacket::operator >> (bool& arg) { ReadData(&arg, sizeof(bool)); return *this; }; SSPacket& SSPacket::operator << (unsigned short arg) { WriteData(&arg, sizeof(unsigned short)); return *this; }; SSPacket& SSPacket::operator >> (unsigned short& arg) { ReadData(&arg, sizeof(unsigned short)); return *this; } SSPacket& SSPacket::operator << (float arg) { WriteData(&arg, sizeof(float)); return *this; }; SSPacket& SSPacket::operator >> (float& arg) { ReadData(&arg, sizeof(float)); return *this; }; SSPacket& SSPacket::operator << (char* arg) { int iLen = sizeof(char)*strlen(arg); WriteData(&arg, iLen); return *this; }; SSPacket& SSPacket::operator >> (char* arg) { int iLen = sizeof(char)*strlen(this->m_pstrReadPosition); ReadData(&arg, sizeof(char)*iLen); return *this; }; SSPacket& SSPacket::operator << (SSPacket& arg) { unsigned short type = arg.GetID(); unsigned short size = arg.GetSize(); WriteData(&type, sizeof(unsigned short)); WriteData(&size, sizeof(unsigned short)); WriteData(&arg.m_pstrWritePosition, size - 4); return *this; }; SSPacket& SSPacket::operator >> (SSPacket& arg) { int type, size; char buffer[4069] = { 0, }; ReadData(&type, sizeof(unsigned short)); ReadData(&size, sizeof(unsigned short)); ReadData(&buffer, size - 4); arg.SetID(type); arg.WriteData(buffer, size - 4); return *this; }; void SSPacket::Clear() { ZeroMemory(m_strPacketBuffer, PACKETBUFFERSIZE); m_PacketHeader.len = (WORD*)m_strPacketBuffer + 0; m_PacketHeader.type = (WORD*)m_strPacketBuffer + 2; m_pstrWritePosition = &m_strPacketBuffer[4]; m_pstrReadPosition = &m_strPacketBuffer[4]; m_iReceivedSize = 0; *m_PacketHeader.len = 4; } SSPacket::SSPacket(void) { Clear(); SetID(0); } SSPacket::SSPacket(unsigned short type) { Clear(); SetID(type); } SSPacket::~SSPacket(void) { } <file_sep>#pragma once #include "xStd.h" #include "dinput.h" #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") class xInput : public TSingleton < xInput > { private: friend class TSingleton<xInput>; public: LPDIRECTINPUT8 m_pDI; LPDIRECTINPUTDEVICE8 m_pKey; LPDIRECTINPUTDEVICE8 m_pMouse; BYTE m_KeyState[256]; DIMOUSESTATE m_MouseState; public: bool Init(); bool Frame(); bool Release(); protected: xInput(); public: virtual ~xInput(); }; #define I_Input xInput::GetInstance() <file_sep>#include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { int iValue[3][2] = { {10,20},{30,40},{50,60} }; for (int iCnt = 0; iCnt < 3; iCnt++) { printf("\n*(iValue+%d):%p", iCnt, *(iValue + iCnt)); printf("\t\tiValue[%d]:%p", iCnt, iValue[iCnt]); } printf("\n"); for (int iCnt = 0; iCnt < 3; iCnt++) { for (int jCnt = 0; jCnt < 2; jCnt++) { printf("\n*(*iValue+%d)+%d):%d", iCnt, jCnt, *(*(iValue + iCnt) + jCnt)); printf("\t\t *(iValue[%d]+%d):%d", iCnt, jCnt, *(iValue[iCnt] + jCnt)); } } _getch(); }<file_sep>#pragma once #include "S_Std.h" class S_Window { public: HWND m_hWnd; HINSTANCE m_hInstance; RECT m_rtWindow; RECT m_rtClient; public: void CenterWindow(); bool SetWindow(HINSTANCE hInstance, const TCHAR* pTitleName = L"Chat_KHJ", int iWidth = 800, int iHeight = 600, DWORD dwStyle = WS_OVERLAPPEDWINDOW); bool Run(); bool Release(); virtual bool ResizeClient(UINT iWidth, UINT iHeight); virtual bool GameRun() { return true; }; virtual void MsgEvent(MSG msg) {}; virtual bool GameInit() { return true; }; virtual bool GameRelease() { return true; }; virtual LRESULT MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); public: S_Window(); virtual ~S_Window(); }; <file_sep>#pragma once #include "SPacketPool.h" typedef struct _OVERLAPPEDEX : OVERLAPPED // 비동기 구조체 { enum { MODE_RECV = 0, MODE_SEND=1 }; // 반환 이넘값 어떤일이 떨어졌는지 알수 있다 int iFlags; _OVERLAPPEDEX() { iFlags = MODE_RECV; // 기본 값을 recv로 계속 받을수 있게한다? } }OVERLAPPEDEX; class SUser : public SServerObj { public: SStreamPacket m_StreamPacket; SOCKET m_Socket; C_STR m_szName; SOCKADDR_IN m_UserAddress; WSABUF m_szRecvBuffer; WSABUF m_szWsaBuf; char m_strBuffer[4096]; OVERLAPPEDEX m_ov; // 비동기 구조체 변수 public: bool Create(); bool Run(); virtual void AddPacket(S_PACKET& addPacket); virtual void DeleteUser(SOCKET socket); virtual void DeleteUser(); virtual void WaitForPacketReceive(); virtual void Dispatch(DWORD dwByteSize, LPOVERLAPPED ov); public: SUser(void); virtual ~SUser(void); }; <file_sep>#ifndef LINKED_TREE_LIST_H #define LINKED_TREE_LIST_H #include "xltem.h" class Iterator; class AbstractList { public: virtual Iterator* CreateIterator() = 0; int Count(); virtual void AddNext(Item*pNewItem, Item *pItem = 0) = 0; virtual void AddChild(Item*pNewItem,Item *pItem = 0) = 0; virtual void Remove(Item* pItem) = 0; virtual Item* GetItem(int pos) = 0; protected: AbstractList():totaICnt_(0){} int totaICnt_; }; class LinkedList : public AbstractList { public: LinkedList():pFirst_(0){} struct LinkedItem { LinkedItem(Item *pItem = 0, LinkedItem *pNext = 0) : pData_(pItem), pNext_(pNext) {} Item* pData_; LinkedItem* pNext_; }; Iterator *CreateIterator(); void AddNext(Item *pNewItem, Item *pItem = 0); void AddChild(Item*pNewItem, Item*pItem = 0); void Remove(Item *pItem); Item* GetItem(int pos); private: LinkedItem * pFirst_; }; class TreeList : public AbstractList { public: TreeList() :pRoot_(0){} struct TreeItem { TreeItem(Item* pItem = 0, TreeItem* pParent = 0, TreeItem *pFirstChild=0, TreeItem* pSibling=0) : pData_(pItem),pParent_(pParent), pFirstChild_(pFirstChild),pSibling_(pSibling) {} Item* pData_; TreeItem* pParent_; TreeItem* pFirstChild_; TreeItem* pSibling_; }; Iterator * CreateIterator(); void AddNext(Item *pNewItem, Item* pItem = 0); void AddChild(Item *pNewItem, Item* pItem = 0); void Remove(Item *pItem); Item* GetItem(int pos); protected: TreeItem * GetNext(const TreeItem* pStart); private: TreeItem * pRoot_; }; #endif<file_sep>#include "stdafx.h" #include "TAccept.h" #include "SSynchronize.h" // SLOCKÀ¸·Î À̸§ ¤¡ void main() { TAccept svr; svr.Set(10000); svr.CreateThread(); while (1); }<file_sep>#include "Node.h" #include "SingleLinkedList.h" #include <windows.h> void main() { SingleLinkedList List; SNode* pTestNode = new SNode(List.m_iCount); List.AddNode(); List.AddNode(); List.AddNode(); List.AddNode(); List.AddNode(pTestNode); List.ShowAllData(); std::cout << std::endl; List.DelNode(1); List.ShowAllData(); std::cout << std::endl; List.DelNode(3); List.ShowAllData(); std::cout << std::endl; List.DelNode(4); List.ShowAllData(); }<file_sep>#pragma once //{{NO_DEPENDENCIES}} // Microsoft Visual C++에서 생성한 포함 파일입니다. // tbsMaxExporter.rc에서 사용되고 있습니다. // #define IDD_DIALOG1 101 #define IDC_OBJEXPORT 1001 #define IDC_SKINEXP 1002 #define IDC_UPDATE 1003 #define IDC_BINDPOSE 1004 #define IDC_MATRIXEXP 1005 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 103 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>#include "SAcceptor.h" #include "SDebugString.h" bool SAcceptor:: Release() { return true; } bool SAcceptor::Run() { SOCKET clientSocket; SOCKADDR_IN clientaddr; int addrlen; while (m_bStarted) { addrlen = sizeof(clientaddr); clientSocket = accept(m_ListenSock, // 접속 (SOCKADDR*)&clientaddr, &addrlen); if (clientSocket == INVALID_SOCKET) { continue; } AddUser(clientSocket, clientaddr); Sleep(10); } return true; } void SAcceptor::AddUser(SOCKET socket, SOCKADDR_IN address) { char buf[255] = { 0, }; InetNtopA(AF_INET, &address.sin_addr,buf, sizeof(char) * 255); // ip주소를 받아온다. } bool SAcceptor::Set(int iPort, const char* strAddress) { // 윈속 초기화 int iRet; WSADATA wd; WSAStartup(MAKEWORD(2, 2),&wd); /////////////////////////// ////////// /////////////////////////// m_ListenSock = socket(AF_INET, SOCK_STREAM, 0); // TCP 서버 if (m_ListenSock == INVALID_SOCKET) // INVALID_SOCKET 실패 { // 성공 : 새로운 소켓 return false; } SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); // 주소를 비운다 serveraddr.sin_family = AF_INET; if (strAddress == NULL) // { serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); } else { serveraddr.sin_addr.s_addr = inet_addr(strAddress); } serveraddr.sin_port = htons(iPort); iRet = ::bind(m_ListenSock, (SOCKADDR*)&serveraddr, sizeof(SOCKADDR)); if (iRet == SOCKET_ERROR) { switch (WSAGetLastError()) { case WSAEADDRINUSE: case WSAEACCES: I_Debug.T_ERROR(); break; } return false; } iRet = listen(m_ListenSock, SOMAXCONN); if (iRet == SOCKET_ERROR) return false; char cFlag = 1; if (SOCKET_ERROR == setsockopt(m_ListenSock, IPPROTO_TCP, TCP_NODELAY, &cFlag, sizeof(char))) { return FALSE; } // SO_REUSEADDDR & SO_EXCLUSIVEADDRUSE 둘 중에 하나만 사용한다. // 윈도우 - > SO_EXCLUSIVEADDRUSE // 리눅스 - > SO_REUSEADDR 이 적당하다. // int optval = 1; // iRet = setsockopt(m_ListenSock, SOL_SOCKET, // SO_REUSEADDR, (char*)&optval, // sizeof(optval)); // (iRet == SOCKET_ERROR) // { // I_Debug.T_ERROR(); // } int optvalexe = 1; iRet = setsockopt(m_ListenSock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&optvalexe, sizeof(optvalexe)); if (iRet == SOCKET_ERROR) { I_Debug.T_ERROR(); } linger optval2; int iSize = sizeof(optval2); optval2.l_linger = 1000; optval2.l_onoff = 1; getsockopt(m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, &iSize); setsockopt(m_ListenSock, SOL_SOCKET, SO_LINGER, (char*)&optval2, iSize); int socketType1; int typeLen1 = sizeof(socketType1); getsockopt(m_ListenSock, SOL_SOCKET, SO_TYPE, (char*)&socketType1, &typeLen1); // if(socketType1 == SOCK_STREAM) if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) < 0) { I_Debug.T_ERROR(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&socketType1, &typeLen1) < 0) { I_Debug.T_ERROR(); } int rcvBufferSizeLen = sizeof(int); int rcvBufferSize = 10000; if (setsockopt(m_ListenSock, SOL_SOCKET, SO_RCVBUF, (char*)&rcvBufferSize, rcvBufferSizeLen) < 0) { I_Debug.T_ERROR(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { I_Debug.T_ERROR(); } if (getsockopt(m_ListenSock, SOL_SOCKET, SO_SNDBUF, (char*)&socketType1, &typeLen1) == SOCKET_ERROR) { I_Debug.T_ERROR(); } // 쓰레드 생성 CreateThread(); return true; } SAcceptor::SAcceptor(void) { } SAcceptor::~SAcceptor(void) { } <file_sep>#include<stdio.h> unsigned int f,x; unsigned int fact(unsigned int a); main() { printf("Enter number(1-8):"); scanf_s("%d", &x); printf("%d factprial equals %d", x, fact(x)); } unsigned int fact(unsigned int a) { if (a == 1) { return 1; } else { a *= fact(a - 1); return a; } }<file_sep>#include "Tpoint.h" Tpoint Tpoint::operator++(void)//전위형 { ++x, ++y; return *this; } Tpoint Tpoint::operator++(int) //후위형 { Tpoint temp = *this; ++x, ++y; return temp; } Tpoint Tpoint::operator+(const Tpoint &pt)const { return Tpoint(x + pt.x, y + pt.y); } Tpoint Tpoint::operator-(const Tpoint &pt)const { return Tpoint(x - pt.x, y - pt.y); } Tpoint Tpoint::operator*(int mag)const { return Tpoint(x*mag, y*mag); } Tpoint Tpoint::operator/(int div)const { return Tpoint(x / div, y / div); } Tpoint operator*(int mag, const Tpoint &pt) { return Tpoint(pt.x*mag, pt.y*mag); } Tpoint operator/(int div, const Tpoint &pt) { return Tpoint(pt.x / div, pt.y / div); } Tpoint &Tpoint::operator=(const Tpoint &pt) { x = pt.x; y = pt.y; return *this; } Tpoint &Tpoint::operator+=(const Tpoint &pt) { x += pt.x; y += pt.y; return *this; } Tpoint &Tpoint::operator-=(const Tpoint &pt) { x -= pt.x; y -= pt.y; return *this; } Tpoint &Tpoint::operator*=(const Tpoint &pt) { x *= pt.x; y *= pt.y; return *this; } Tpoint &Tpoint::operator/=(const Tpoint &pt) { x /= pt.x; y /= pt.y; return *this; } Tpoint &Tpoint::operator*=(int mag) { x *= mag; y *= mag; return *this; } Tpoint &Tpoint::operator/=(int div) { x /= div; y /= div; return *this; } bool Tpoint::operator==(const Tpoint &pt)const { return(x == pt.x &&y == pt.y); //x,y가 모두 같으면 ture } bool Tpoint::operator !=(const Tpoint &pt)const { return (x != pt.x || y != pt.y); //x,y 중 하나라도 다르면 ture } int &Tpoint::operator[](int index) { if (index == 0) return x; return y; } void *Tpoint::operator new(size_t size) { return malloc(size); } void Tpoint::operator delete(void *p) { free(p); } ostream &operator<<(ostream &os, const Tpoint &pt) { os << "(" << pt.x << "," << pt.y << ")"; return os; } istream &operator>>(istream &is, Tpoint &pt) { is >> pt.x; is >> pt.y; return is; } Tpoint Tpoint::operator*(const Tpoint &c) { Tpoint temp; temp.x = x * c.x; temp.y = y * c.y; return temp; } Tpoint Tpoint::operator/(const Tpoint &c) { Tpoint temp; temp.x = x / c.x; temp.y = y / c.y; return temp; } void Tpoint::SetPosition(int _x, int _y) { x = _x; y = _y; } void Tpoint::Move(int _x, int _y) { x += _x; y += _y; } void Tpoint::Show(void) { cout << "(" << x << "," << y << ")" << endl; } Tpoint::Tpoint() { cout << "Constuctor" << endl; } Tpoint::Tpoint(int x, int y) { this->x = x; this->y = y; cout << "Constuctor" << endl; } Tpoint::~Tpoint() { cout << "Distructor" << endl; } <file_sep>#include "S_ChatAccept.h" #include "S_Chat_Svr.h" void S_ChatAccept::AddUser(SOCKET socket, SOCKADDR_IN address) { S_CHAT.AddUser(socket, address); } S_ChatAccept::S_ChatAccept() { } S_ChatAccept::~S_ChatAccept() { } <file_sep>#include "Token.h" void main() { TCHAR buffer[] = L"kgca game academy"; Token token(buffer); token.Show(); }<file_sep>#include "TPacket.h" int SendMsg(SOCKET sock,const char* msg, WORD type) { string address="서울 특별시"; TPacket sendPacket(type); sendPacket << msg; sendPacket << 1000; sendPacket << address; int iRet=send(sock, (char*)&sendPacket.m_uPacket, sendPacket.m_uPacket.ph.len + PACKET_HEADER_SIZE,0); char name[5] = { 0, }; int iValue=0; string add; TPacket recvPacket; recvPacket.m_uPacket.ph= sendPacket.m_uPacket.ph; memcpy(recvPacket.m_uPacket.msg, sendPacket.m_uPacket.msg, sizeof(char) * 256); recvPacket >> name; recvPacket >> iValue; recvPacket >> add; return iRet; } void main() { SOCKET sock=0; SendMsg(sock, "game", PACKET_CHAT_MSG); }<file_sep>#pragma once #include "S_Thread.h" #include "S_Acceptor.h" #include "S_SvrUser.h" class S_Server:public S_Thread { public: S_Acceptor m_Acceptor; public: bool Init(); bool Release(); bool Run(); virtual bool AddUser(SOCKET socket, SOCKADDR_IN address); bool SendMsg(SOCKET socket, const char* msg, WORD code); public: S_Server(); virtual ~S_Server(); }; <file_sep>#include "LinkedListSing.h" void main() { LinkedListSing ADATA; ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Add(); ADATA.Del(5); ADATA.Find(8); system("pause"); }<file_sep>#pragma once struct SNode; class SingleLinkedList { public: SNode* m_HeadNode; SNode* m_TailNode; int m_iCount; public: void AddNode(); void AddNode(SNode* _pNewNode); void DelNode(int _iData); void DelNode(SNode* _DelNode); void ShowAllData(); public: SingleLinkedList(); virtual ~SingleLinkedList(); }; <file_sep>#include "xCamera.h" void xCamera::SetSpeed(float fValue) { m_fSpeed += fValue; } void xCamera::MoveLook(float fValue) { m_vPos += m_vLook * fValue*m_fSpeed; } void xCamera::MoveSide(float fValue) { m_vPos += m_vSide * fValue*m_fSpeed; } bool xCamera::Frame() { m_fSpeed -= g_fSecPerFrame; if (m_fSpeed < 0.5f) m_fSpeed = 0.5f; return true; } bool xCamera::UpdateVector() { m_vLook.x = m_matView._13; m_vLook.y = m_matView._23; m_vLook.z = m_matView._33; m_vUp.x = m_matView._12; m_vUp.y = m_matView._22; m_vUp.z = m_matView._32; m_vSide.x = m_matView._11; m_vSide.y = m_matView._21; m_vSide.z = m_matView._31; D3DXVec3Normalize(&m_vLook, &m_vLook); D3DXVec3Normalize(&m_vUp, &m_vUp); D3DXVec3Normalize(&m_vSide, &m_vSide); xFrustum::SetMatrix(NULL, &m_matView, &m_matProj); xFrustum::CreateFrustum(); return true; } bool xCamera::Update(D3DXVECTOR4 vValue) { // yaw, pitch,roll, radius D3DXMATRIX matRotation; D3DXQUATERNION qRotation; D3DXQuaternionRotationYawPitchRoll(&qRotation, m_fCameraYawAngle+=vValue.y, m_fCameraPitchAngle+=vValue.x, vValue.z); m_vPos += m_vLook * vValue.w*m_fSpeed; D3DXMatrixAffineTransformation(&matRotation, 1.0f, NULL, &qRotation,&m_vPos); D3DXMatrixInverse(&m_matView, NULL, &matRotation); UpdateVector(); return true; } D3DXMATRIX xCamera::SetViewMatrix( D3DXVECTOR3 vPos, D3DXVECTOR3 vTarget, D3DXVECTOR3 vUp) { m_vPos = vPos; m_vTarget = vTarget; m_vDefaultUp = vUp; D3DXMatrixLookAtLH(&m_matView,&vPos,&vTarget,&vUp); UpdateVector(); // 뷰 행렬 생성 할 때 1번만 호출되도록 한다. // 이유는 카메라가 뒤집어 질 경우에는 문제가 생긴다. D3DXMATRIX mInvView; D3DXMatrixInverse(&mInvView, NULL, &m_matView); D3DXVECTOR3* pZBasis = (D3DXVECTOR3*)&mInvView._31; m_fCameraYawAngle = atan2f(pZBasis->x, pZBasis->z); float fLen = sqrtf(pZBasis->z * pZBasis->z + pZBasis->x * pZBasis->x); m_fCameraPitchAngle = -atan2f(pZBasis->y, fLen); return m_matView; } D3DXMATRIX xCamera::SetProjMatrix(float fFov,float fAspect,float fNear,float fFar) { m_fFov= fFov; m_fAspect= fAspect; m_fNear= fNear; m_fFar= fFar; D3DXMatrixPerspectiveFovLH(&m_matProj,fFov,fAspect,fNear, fFar); return m_matProj; } void xCamera::UpdateProjMatrix(UINT width, UINT height) { m_fAspect = (float)width / (float)height; SetProjMatrix(m_fFov,m_fAspect, m_fNear, m_fFar); } xCamera::xCamera() { m_fSpeed = 1.0f; m_fCameraYawAngle = 0.0f; m_fCameraPitchAngle = 0.0f; D3DXMatrixIdentity(&m_matWorld); } xCamera::~xCamera() { } <file_sep>#pragma once #include "S_Std.h" class S_Time { public: TCHAR m_csBuffer[256]; int m_iFPS; float m_fSecondperFrame; float m_fAccumulation; public: DWORD m_dwBeforeTick; float m_fFrameTime; DWORD m_dwFrameCnt; public: bool Init(); bool Frame(); bool Render(); bool Release(); public: S_Time(); virtual ~S_Time(); }; <file_sep>#include "S_Character.h" #include "xTimer.h" #include "TObjMgr.h" void S_Character::SetActionFrame(int iStart, int iEnd, int iCharacterMatrixIndex, int iModelMatrixIndex) { m_iStartFrame = iStart; m_iLastFrame = iEnd; m_iCurrentFrame = (float)iStart; m_fFrame = m_iStartFrame; if (iCharacterMatrixIndex >= 0) { m_iMatrixIndex = iCharacterMatrixIndex; } if (iModelMatrixIndex >= 0) { SetModelMaterixID(iModelMatrixIndex); } } void S_Character::SetModelMaterixID(int iMatrixIndex) { for (int iObj = 0; iObj < m_pModelList.size(); iObj++) { m_pSubObjList[iObj]->SetMatrixIndex(iMatrixIndex); } } bool S_Character::Add(ID3D11Device* pd3dDevice, ID3D11DeviceContext* plmmediateContext, const TCHAR* strSkinFileName, const TCHAR* strSkinShaderName, int iMatrixIndex, int iModelMatrixIndex) { if (!_tcsicmp(strSkinFileName, _T("null"))) { return false; } if (!Load(pd3dDevice, strSkinFileName, strSkinShaderName)) { return false; } m_pBoneObject = (TBoneObj*)I_ObjMgr.GetPtr(iMatrixIndex); SetActionFrame(m_pBoneObject->m_Scene.iFirstFrame, m_pBoneObject->m_Scene.iLastFrame, iMatrixIndex, iModelMatrixIndex); return true; } bool S_Character::Init() { TObject::Init(); return true; } bool S_Character::Render(ID3D11DeviceContext* pContext) { m_pBoneObject->m_pMatrix = m_pMatrix; TObject::Render(pContext); m_pBoneObject->Render(pContext); return true; } void S_Character::SetMatrix(D3DXMATRIX* pWorld, D3DXMATRIX* pView, D3DXMATRIX* pProj) { TObject::SetMatrix(pWorld, pView, pProj); m_pBoneObject->SetMatrix(pWorld, pView, pProj); } bool S_Character::Release() { TObject::Release(); return true; } bool S_Character::Frame() { _ASSERT(m_pBoneObject); m_fFrame += (g_fSecPerFrame* m_pBoneObject->m_Scene.iFrameSpeed); m_iCurrentFrame = (int)m_fFrame; m_fLerpTime = m_fFrame - m_iCurrentFrame; if (m_pBoneObject->AniFrame(m_iCurrentFrame, m_fLerpTime, m_iStartFrame, m_iLastFrame, m_pMatrix)) { m_iCurrentFrame = m_iStartFrame; m_fFrame = (float)m_iStartFrame; } TObject::Frame(); return true; } S_Character::S_Character() { m_iMatrixIndex = -1; } S_Character::~S_Character() { } <file_sep>//삽입 정렬(Insertion Sort) /*삽입 정렬 알고리즘은 점진적으로 정렬 범위를 넓혀 나가는 방식으로 정렬하는 알고리즘이다. 이를 위해 새로운 범위에 포함하는 마지막 원소를 앞으로 이동하면서 자신보다 작은 요소를 찾을 떄까지 이동하면서 자리를 교환한다*/ #include <stdio.h> #include<conio.h> #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 void InsertionSort(int *base, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; InsertionSort(arr, 10); _getch(); return 0; } void ViewArr(int *arr, int n); void InsertionSort(int *base, int n) { int i, j; ViewArr(base, n);//현재 상태 출력 for (i = 1; i < n; i++)//정렬할 범위를 확대해 나갑니다. { for (j = i; j > 0; j--) { if (base[j - 1] > base[j])//앞쪽 원소가 더 크면 { SWAP(base[j - 1], base[j]);//교환 ViewArr(base, n);//상태 출력 } else { break; } } } } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i < n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#pragma once #include "SThread.h" #include "SStreamPacket.h" class SPacketPool : public SServerObj { public: list<S_PACKET> m_PacketList; typedef list<S_PACKET>::iterator m_PackItor; public: virtual bool AddPacket(S_PACKET& addPacket); virtual bool ProcessPacket(); virtual void ProcessWork(S_PACKET* pUserData); public: SPacketPool(void); virtual ~SPacketPool(void); }; <file_sep>//chain of responsibility는 책임들이 연결되어 있어 내가 책임을 못 질 것 같으면 // 다음 책임자에게 자동으로 넘어가는 구조를 말한다.(전화 중계) #include <iostream> #include <string> using namespace std; class HelpHandler { public: HelpHandler(HelpHandler* pObj = 0, string helpMsg = "") { pSuccessor_ = pObj; helpMsg_ = helpMsg; } virtual void SetHandler(HelpHandler* pObj, string helpMsg) { pSuccessor_ = pObj; helpMsg_ = helpMsg; } virtual bool HasHelp() { return !helpMsg_.empty(); } virtual void HandleHelp() { if (pSuccessor_) pSuccessor_->HandleHelp(); } virtual void ShowHelpMsg() { //--helpMsg_를 보여준다. cout << helpMsg_ << endl; } protected: string helpMsg_; private: HelpHandler * pSuccessor_; }; class Widget : public HelpHandler { protected: Widget(Widget* pObj, string helpMsg = "") :HelpHandler(pObj, helpMsg) { pParent_ = pObj; } private: Widget * pParent_; }; class Button : public Widget { public: Button(Widget* pObj, string helpMsg = "") :Widget(pObj, helpMsg) {} virtual void HandleHelp() { if (HasHelp())ShowHelpMsg(); else HelpHandler::HandleHelp(); } virtual void ShowHelpMsg() { // --helpMsg_ 내용을 Button 도움말 양식에 맞추어 보여준다. cout << helpMsg_ << endl; } }; class Dialog :public Widget { public: Dialog(HelpHandler * pObj, string helpMsg = "") :Widget(0) { SetHandler(pObj, helpMsg); } virtual void HandleHelp() { if (HasHelp())ShowHelpMsg(); else HelpHandler::HandleHelp(); } virtual void ShowHelpMsg() { //--helpMsg_ 내용을 Dialog 도움말 양식에 맞추어 보여준다. cout << helpMsg_ << endl; } }; class Application : public HelpHandler { public: Application(string helpMsg): HelpHandler(0,helpMsg){} virtual void HandleHelp() { ShowHelpMsg(); } virtual void ShowHelpMsg() { //--helpMsg_ 내용을 보여준다. cout << helpMsg_ << endl; } }; void main() { Application *pApp = new Application("A[[lication Help"); Dialog* pDialog = new Dialog(pApp, "Dialog Help"); Button* pButton = new Button(pDialog); pButton->HandleHelp(); }<file_sep>#include "SUser.h" #include "SLock.h" void SUser::Dispatch(DWORD dwByteSize, LPOVERLAPPED ov) { OVERLAPPEDEX* pOV = (OVERLAPPEDEX*)ov; if (dwByteSize == 0)return; if (pOV->iFlags == OVERLAPPEDEX::MODE_RECV) { m_StreamPacket.Put(m_szRecvBuffer.buf, // this-> m_strBuffer, dwByteSize, this); } if(pOV->iFlags == OVERLAPPEDEX::MODE_SEND) { } WaitForPacketReceive(); }; void SUser::AddPacket(S_PACKET& addPacket) { { SLock lock(this); m_StreamPacket.m_PacketList.push_back(addPacket); } return; } bool SUser::Create() { ZeroMemory(&m_ov, sizeof(m_ov)); WaitForPacketReceive(); return true; } void SUser::WaitForPacketReceive() { DWORD cbTransferred, flags = 0; m_szRecvBuffer.buf = m_strBuffer; m_szRecvBuffer.len = 4096; int iRet = WSARecv(m_Socket, &m_szRecvBuffer, 1, &cbTransferred, &flags, (LPOVERLAPPED)&m_ov, NULL); if (iRet == SOCKET_ERROR) { int dwError = WSAGetLastError(); if (dwError != WSA_IO_PENDING) { int kkkk = 0; } } } bool SUser:: Run() { char szMsgBuffer[2048] = { 0, }; int strlen = 0; while (1) { strlen = recv(m_Socket, szMsgBuffer, sizeof(szMsgBuffer), 0); if (strlen <= 0)break; szMsgBuffer[strlen] = 0; m_StreamPacket.Put(szMsgBuffer, strlen, this); Sleep(10); } DeleteUser(m_Socket); return true; } void SUser::DeleteUser(SOCKET socket) { } void SUser::DeleteUser() { } SUser::SUser() { m_Socket = 0; } SUser::~SUser() { closesocket(m_Socket); } <file_sep>#include <iostream> #include <list> #include <map> using namespace std; template<class T> class Tsingleton { public: static T& GetInstance()// 참조 중요 ..지역변수에 참조로 넘긴다 { static T inst; return inst; } }; class TPosition { public: TPosition() {} TPosition(int ix, int iy) { m_ix = ix; m_iy = iy; } int m_ix; int m_iy; }; class TGraphic { public: virtual TGraphic* Clone() = 0; virtual void Draw(TPosition pos) = 0; }; class TTriangle : public TGraphic { public: TGraphic * Clone() { return new TTriangle(*this); }; void Draw(TPosition pos) { std::cout << pos.m_ix << pos.m_iy; }; }; class TRectangle : public TGraphic { public: TGraphic * Clone() { return new TRectangle(*this); }; void Draw(TPosition pos) { std::cout << pos.m_ix << pos.m_iy; }; }; class TGraphicComposite : public TGraphic { public: void Draw(TPosition pos) { std::cout << pos.m_ix << pos.m_iy; }; // Composite pattern std::list<TGraphic*>m_components; TGraphic * Clone() { TGraphicComposite* pGC = new TGraphicComposite(*this); //데이터는 같지만 메모리는 다르다 std::list<TGraphic*>::iterator iterSrc; for (iterSrc = m_components.begin(); iterSrc != m_components.end(); iterSrc++) { TGraphic* pNewGraphic = (*iterSrc)->Clone(); pGC->m_components.push_back(pNewGraphic); } return pGC; }; }; class TMouse { public: TPosition m_pos; bool m_bLeftButton[3]; public: bool IsLeftButtonPushed() { return m_bLeftButton[0]; } TPosition GetPosition() { return m_pos; } }; TMouse g_Mouse; class TDocument { public: list<TGraphic*>m_docList; public: void Add(TGraphic* pobj) { m_docList.push_back(pobj); } }; class TGraphicEditor { public: TDocument m_doc; public: void AddNewGraphic(TGraphic* pSelected) { TGraphic* pobj = pSelected->Clone(); while (g_Mouse.IsLeftButtonPushed()) { pobj->Draw(g_Mouse.GetPosition()); } m_doc.Add(pobj); } private: }; class TPalette : public Tsingleton<TPalette> { private: friend class Tsingleton<TPalette>; std::map<int, TGraphic*> m_items; public: void Draw() {} /*static TPalette* g_pPlette; static TPalette* GetInstance() { if (g_pPlette == NULL) { g_pPlette = new TPalette; } return g_pPlette; }*/ //원시 모델 추가등록 void RegisterNewGraphic(TGraphic* pGraphic) { m_items[m_items.size() + 1] = pGraphic; } TGraphic* GetSelectedobj() { return m_items[GetItemOrder()]; } int GetItemOrder() { int iItem = -1; //g_Mouse.GetPosition(); return iItem; } protected: TPalette() { //원시 모델 TGraphic* pGraphicA = new TTriangle; m_items[0] = pGraphicA; TGraphic* pGraphicB = new TRectangle; m_items[1] = pGraphicB; } }; #define I_Palette TPalette::GetInstance() void main() { TPalette palette= I_Palette; TPalette paletteA=TPalette::GetInstance(); I_Palette.Draw(); TGraphicEditor editer; editer.AddNewGraphic(I_Palette.GetSelectedobj()); TGraphicComposite etc; list<TGraphic*>::iterator iter; for (iter = editer.m_doc.m_docList.begin(); iter != editer.m_doc.m_docList.end(); iter++) { TGraphic* pData = (*iter); etc.m_components.push_back(pData); } I_Palette.RegisterNewGraphic(&etc); //components 패턴 /* TTriangle tri; TRectangle rec; TGraphicComposite etc; etc.m_components.push_back(&tri); etc.m_components.push_back(&rec); palette.RegisterNewGraphic(&etc); TRectangle rec1; TRectangle rec2; TGraphicComposite etc; etc.m_components.push_back(&rec1); etc.m_components.push_back(&rec2); palette.RegisterNewGraphic(&etc); TGraphicComposite etc3; TGraphicComposite etc4; etc.m_components.push_back(&etc3); etc.m_components.push_back(&etc4); palette.RegisterNewGraphic(&etc);*/ //siggle Pattern 유일성mgr 종류들 }<file_sep>//힙 정렬(Heap Sort) /*힙 정렬은 힙 트리를 이용하는 알고리즘이다. 최대 힙을 사용하면 크기 순으로 정렬하고 최소 합을 사용하면 크기 역순으로 정렬한다. 힙 정렬은 먼저 힙트리를 구성하고 루트의 값과 맨 마지막 값을 교환한 후에 정렬 범위를 1 줄인다 반복하여 정렬 범위가 1일 때까지 반복한다.최대 힙 트리에서 루트는 최대 값을 갖는다 마지막 값과 교환 하면 제일 큰값이 맨 뒤로 배치할수 있다. 그 뒤에 정렬 범위를 줄여 나가면 최종적으로 정렬 상태가 완성*/ #include <stdio.h> #include<conio.h> #define LEFT_CHILD(x) (2*x + 1) #define RIGHT_CHILD(x) (2*x + 2) #define PARENT(x) ((x-1)/2) #define SWAP(a,b) {int t; t = a; a=b; b=t;}//a와 b를 교환 void HeapSort(int *base, int n); void ViewArr(int *arr, int n); int main(void) { int arr[10] = { 9,4,3,10,5,8,7,6,2,1 }; ViewArr(arr, 10); HeapSort(arr, 10); ViewArr(arr, 10); _getch(); return 0; } void InitHeap(int *base, int n); void MakeHeap(int *base, int n); void HeapSort(int *base, int n) { int on = n; printf("초기 힙 생성 과정\n"); InitHeap(base, n); n--; SWAP(base[0], base[n]); printf("정렬 과정\n"); while (n>1) { MakeHeap(base, n); ViewArr(base, n + 1); n--; SWAP(base[0], base[n]); } ViewArr(base, n + 1); } void InitHeap(int *base, int n) { int pa = 0; int now; int i; for (i = 1; i<n; i++)//순차적으로 힙에 구성 { now = i; while (now>0)//now의 인덱스가 0이 아니면(힙의 루트가 아니면) { pa = PARENT(now);//부모 인덱스 구함 if (base[now]>base[pa])//부모보다 더 크면 { SWAP(base[now], base[pa]);//부모와 교환 now = pa;//인덱스를 부모로 설정 } else//아니면 자리를 찾은 것임 { break; } } ViewArr(base, i + 1); } } int FindMaxIndex(int *base, int n, int now); void MakeHeap(int *base, int n) { int now = 0; int mp = 0; //루트에 있는 요소를 힙 트리에 맞게 자리를 찾는 과정 while (LEFT_CHILD(now) < n)//왼쪽 자식이 있다면 { int mp = FindMaxIndex(base, n, now);//now와 왼쪽, 오른쪽 자식 중에 큰 값의 위치 찾음 if (mp == now)//mp와 now가 같으면 { break;//자리를 찾은 것임 } SWAP(base[mp], base[now]);//now와 큰 값의 자리 교환 now = mp;//큰 값의 위치를 now로 설정 } } int FindMaxIndex(int *base, int n, int now) { int lc = LEFT_CHILD(now);//왼쪽 자식 int rc = RIGHT_CHILD(now);//오른쪽 자식 if (rc >= n)//오른쪽 자식이 없을 때 { if (base[now]<base[lc]) { return lc; } return now; } if (base[lc]<base[rc]) { return rc; } return lc; } void ViewArr(int *arr, int n) { int i = 0; for (i = 0; i<n; i++) { printf("%2d ", arr[i]); } printf("\n"); } <file_sep>#include <stdio.h> int main(void) { int icount = 1; int sum1 = 0; while (icount <= 100) { sum1 = sum1 + icount; icount++; } printf("1~100±îÁöÀÇ ÇÕ:%d", sum1); return 0; }<file_sep>#include "S_StreamPacket.h" #include "S_Server.h" void S_StreamPacket::Put(char* recvBuffer, int Size, S_SvrUser* pUser) { if (m_iWritePos + Size >= MAX_RECV) { char cTemp[MAX_RECV] = { 0, }; memcpy(cTemp, &RecvBuffer[m_iStartPos], m_iReadPos); ZeroMemory(&RecvBuffer, sizeof(char)*MAX_RECV); memcpy(&RecvBuffer, &cTemp, m_iReadPos); m_pPacket = (P_UPACKET)RecvBuffer; m_iStartPos = 0; m_iWritePos = m_iReadPos; } memcpy(&RecvBuffer[m_iWritePos], recvBuffer, Size); m_iWritePos += Size; m_iReadPos += Size; if (m_iReadPos < PACKET_HEADER_SIZE) { return; } m_pPacket = (P_UPACKET)&RecvBuffer[m_iStartPos]; if (m_iReadPos >= m_pPacket->ph.len) { do { PACKET Add; ZeroMemory(&Add, sizeof(Add)); memcpy(&Add.packet, &RecvBuffer[m_iStartPos], m_pPacket->ph.len); Add.pUser = pUser; if (pUser != NULL) { pUser->AddPacket(Add); } m_iReadPos -= m_pPacket->ph.len; m_iStartPos += m_pPacket->ph.len; if (m_iReadPos < MAX_RECV) { break; } m_pPacket = (P_UPACKET)&RecvBuffer[m_iStartPos]; } while (m_iReadPos >= m_pPacket->ph.len); } } S_StreamPacket::S_StreamPacket() { ZeroMemory(RecvBuffer, sizeof(char)*MAX_RECV); m_iStartPos = 0; m_iWritePos = 0; m_iReadPos = 0; m_pPacket = NULL; } S_StreamPacket::~S_StreamPacket() { } <file_sep>#include "SButton.h" D3DXVECTOR3 SButton::Gen(float x, float y) { D3DXVECTOR3 vRet = SActor::Gen(x, y); //vRet.x = vRet.x * (800 * 0.5f); //vRet.y = vRet.y * (600 * 0.5f); return vRet; } void SButton::SetVertexData() { m_cpPoint[0] = { m_rtInit.left*1.0f,m_rtInit.top*1.0f }; m_cpPoint[1] = { m_rtInit.left + m_rtInit.right*m_sOffset.fScaleX0,m_rtInit.top*1.0f }; m_cpPoint[2] = { m_rtInit.left + m_rtInit.right*(1.0f - m_sOffset.fScaleX1),m_rtInit.top*1.0f }; m_cpPoint[3] = { m_rtInit.left + m_rtInit.right*1.0f,m_rtInit.left*1.0f }; m_cpPoint[4] = { m_cpPoint[0].x,m_rtInit.top + m_rtInit.bottom*m_sOffset.fScaleY0 }; m_cpPoint[5] = { m_cpPoint[1].x,m_rtInit.top + m_rtInit.bottom*m_sOffset.fScaleY0 }; m_cpPoint[6] = { m_cpPoint[2].x,m_rtInit.top + m_rtInit.bottom*m_sOffset.fScaleY0 }; m_cpPoint[7] = { m_cpPoint[3].x,m_rtInit.top + m_rtInit.bottom*m_sOffset.fScaleY0 }; m_cpPoint[8] = { m_cpPoint[0].x,m_rtInit.top + m_rtInit.bottom * (1.0f - m_sOffset.fScaleY1) }; m_cpPoint[9] = { m_cpPoint[1].x,m_rtInit.top + m_rtInit.bottom*(1.0f - m_sOffset.fScaleY1) }; m_cpPoint[10] = { m_cpPoint[2].x,m_rtInit.top + m_rtInit.bottom * (1.0f - m_sOffset.fScaleY1) }; m_cpPoint[11] = { m_cpPoint[3].x,m_rtInit.top + m_rtInit.bottom*(1.0f - m_sOffset.fScaleY1) }; m_cpPoint[12] = { m_cpPoint[0].x,m_rtInit.top + m_rtInit.bottom*1.0f }; m_cpPoint[13] = { m_cpPoint[1].x,m_rtInit.top + m_rtInit.bottom*1.0f }; m_cpPoint[14] = { m_cpPoint[2].x,m_rtInit.top + m_rtInit.bottom*1.0f }; m_cpPoint[15] = { m_cpPoint[3].x,m_rtInit.top + m_rtInit.bottom*1.0f }; m_Actor[0].Setdata(m_cpPoint[0].x, m_cpPoint[0].y, m_cpPoint[1].x - m_cpPoint[0].x, m_cpPoint[4].y - m_cpPoint[0].y); m_Actor[0].m_VertexList[1].t.x = m_sOffset.fOffsetU0; m_Actor[0].m_VertexList[1].t.y = 0.0f; m_Actor[0].m_VertexList[2].t.x = 0.0f; m_Actor[0].m_VertexList[2].t.y = m_sOffset.fOffsetV0; m_Actor[0].m_VertexList[3] = m_Actor[0].m_VertexList[2]; m_Actor[0].m_VertexList[4] = m_Actor[0].m_VertexList[1]; m_Actor[0].m_VertexList[5].t.x = m_sOffset.fOffsetU0; m_Actor[0].m_VertexList[5].t.y = m_sOffset.fOffsetV0; m_Actor[1].Setdata(m_cpPoint[1].x, m_cpPoint[1].y, m_cpPoint[2].x - m_cpPoint[1].x, m_cpPoint[6].y - m_cpPoint[2].y); m_Actor[1].m_VertexList[0].t.x = m_sOffset.fOffsetU0; m_Actor[1].m_VertexList[0].t.y = 0.0f; m_Actor[1].m_VertexList[1].t.x = 1.0f - m_sOffset.fOffsetU0; m_Actor[1].m_VertexList[1].t.y = 0.0f; m_Actor[1].m_VertexList[2].t.x = m_Actor[1].m_VertexList[0].t.x; m_Actor[1].m_VertexList[2].t.y = m_sOffset.fOffsetV0; m_Actor[1].m_VertexList[3] = m_Actor[1].m_VertexList[2]; m_Actor[1].m_VertexList[4] = m_Actor[1].m_VertexList[1]; m_Actor[1].m_VertexList[5].t.x = m_Actor[1].m_VertexList[1].t.x; m_Actor[1].m_VertexList[5].t.y = m_Actor[1].m_VertexList[2].t.y; m_Actor[2].Setdata(m_cpPoint[2].x, m_cpPoint[2].y, m_cpPoint[3].x - m_cpPoint[2].x, m_cpPoint[6].y - m_cpPoint[2].y); m_Actor[2].m_VertexList[0].t.x = 1.0f - m_sOffset.fOffsetU0; m_Actor[2].m_VertexList[0].t.y = 0.0f; m_Actor[2].m_VertexList[1].t.x = 1.0f; m_Actor[2].m_VertexList[1].t.y = 0.0f; m_Actor[2].m_VertexList[2].t.x = m_Actor[2].m_VertexList[0].t.x; m_Actor[2].m_VertexList[2].t.y = m_sOffset.fOffsetV0; m_Actor[2].m_VertexList[3] = m_Actor[2].m_VertexList[2]; m_Actor[2].m_VertexList[4] = m_Actor[2].m_VertexList[1]; m_Actor[2].m_VertexList[5].t.x = m_Actor[2].m_VertexList[1].t.x; m_Actor[2].m_VertexList[5].t.y = m_Actor[2].m_VertexList[2].t.y; #pragma endregion //////// #pragma region 3~5 m_Actor[3].Setdata(m_cpPoint[4].x, m_cpPoint[4].y, m_cpPoint[1].x - m_cpPoint[0].x, m_cpPoint[8].y - m_cpPoint[4].y); m_Actor[3].m_VertexList[0].t = m_Actor[0].m_VertexList[2].t; m_Actor[3].m_VertexList[1].t = m_Actor[0].m_VertexList[5].t; m_Actor[3].m_VertexList[2].t.x = 0.0f; m_Actor[3].m_VertexList[2].t.y = 1.0f - (m_sOffset.fOffsetV0 - m_sOffset.fOffsetV1); m_Actor[3].m_VertexList[3] = m_Actor[3].m_VertexList[2]; m_Actor[3].m_VertexList[4] = m_Actor[3].m_VertexList[1]; m_Actor[3].m_VertexList[5].t.x = m_Actor[3].m_VertexList[1].t.x; m_Actor[3].m_VertexList[5].t.y = m_Actor[3].m_VertexList[2].t.y; m_Actor[4].Setdata(m_cpPoint[5].x, m_cpPoint[5].y, m_cpPoint[2].x - m_cpPoint[1].x, m_cpPoint[8].y - m_cpPoint[4].y); m_Actor[4].m_VertexList[0].t = m_Actor[3].m_VertexList[1].t; m_Actor[4].m_VertexList[1].t.x = m_Actor[1].m_VertexList[1].t.x; m_Actor[4].m_VertexList[1].t.y = m_sOffset.fOffsetV0; m_Actor[4].m_VertexList[2].t.x = m_sOffset.fOffsetU0; m_Actor[4].m_VertexList[2].t.y = 1.0f - (m_sOffset.fOffsetV0 - m_sOffset.fOffsetV1); m_Actor[4].m_VertexList[3] = m_Actor[4].m_VertexList[2]; m_Actor[4].m_VertexList[4] = m_Actor[4].m_VertexList[1]; m_Actor[4].m_VertexList[5].t.x = m_Actor[4].m_VertexList[1].t.x; m_Actor[4].m_VertexList[5].t.y = m_Actor[4].m_VertexList[2].t.y; m_Actor[5].Setdata(m_cpPoint[6].x, m_cpPoint[6].y, m_cpPoint[3].x - m_cpPoint[2].x, m_cpPoint[8].y - m_cpPoint[4].y); m_Actor[5].m_VertexList[0].t = m_Actor[4].m_VertexList[1].t; m_Actor[5].m_VertexList[1].t.x = 1.0f; m_Actor[5].m_VertexList[1].t.y = m_sOffset.fOffsetV0; m_Actor[5].m_VertexList[2].t = m_Actor[4].m_VertexList[5].t; m_Actor[5].m_VertexList[3] = m_Actor[5].m_VertexList[2]; m_Actor[5].m_VertexList[4] = m_Actor[5].m_VertexList[1]; m_Actor[5].m_VertexList[5].t.x = m_Actor[5].m_VertexList[1].t.x; m_Actor[5].m_VertexList[5].t.y = m_Actor[5].m_VertexList[2].t.y; #pragma endregion 3~5 #pragma region 6~9 m_Actor[6].Setdata(m_cpPoint[8].x, m_cpPoint[8].y, m_cpPoint[1].x - m_cpPoint[0].y, m_cpPoint[12].y - m_cpPoint[8].y); m_Actor[6].m_VertexList[0].t = m_Actor[3].m_VertexList[2].t; m_Actor[6].m_VertexList[1].t = m_Actor[3].m_VertexList[5].t; m_Actor[6].m_VertexList[2].t.x = 0.0f; m_Actor[6].m_VertexList[2].t.y = 1.0f; m_Actor[6].m_VertexList[3] = m_Actor[6].m_VertexList[2]; m_Actor[6].m_VertexList[4] = m_Actor[6].m_VertexList[1]; m_Actor[6].m_VertexList[5].t.x = m_Actor[6].m_VertexList[1].t.x; m_Actor[6].m_VertexList[5].t.y = m_Actor[6].m_VertexList[2].t.y; m_Actor[7].Setdata(m_cpPoint[9].x, m_cpPoint[9].y, m_cpPoint[2].x - m_cpPoint[1].x, m_cpPoint[12].y - m_cpPoint[8].y); m_Actor[7].m_VertexList[0].t = m_Actor[4].m_VertexList[3].t; m_Actor[7].m_VertexList[1].t = m_Actor[4].m_VertexList[5].t; m_Actor[7].m_VertexList[2].t.x = m_sOffset.fOffsetU0; m_Actor[7].m_VertexList[2].t.y = 1.0f; m_Actor[7].m_VertexList[3] = m_Actor[7].m_VertexList[2]; m_Actor[7].m_VertexList[4] = m_Actor[7].m_VertexList[1]; m_Actor[7].m_VertexList[5].t.x = m_Actor[7].m_VertexList[1].t.x; m_Actor[7].m_VertexList[5].t.y = m_Actor[7].m_VertexList[2].t.y; m_Actor[8].Setdata(m_cpPoint[10].x, m_cpPoint[10].y, m_cpPoint[3].x - m_cpPoint[2].x, m_cpPoint[12].y - m_cpPoint[8].y); m_Actor[8].m_VertexList[0].t = m_Actor[5].m_VertexList[3].t; m_Actor[8].m_VertexList[1].t = m_Actor[5].m_VertexList[5].t; m_Actor[8].m_VertexList[2].t = m_Actor[7].m_VertexList[5].t; m_Actor[8].m_VertexList[3] = m_Actor[8].m_VertexList[2]; m_Actor[8].m_VertexList[4] = m_Actor[8].m_VertexList[1]; m_Actor[8].m_VertexList[5].t.x = m_Actor[8].m_VertexList[1].t.x; m_Actor[8].m_VertexList[5].t.y = m_Actor[8].m_VertexList[2].t.y; ////////////////////// #pragma endregion 3~5 for (int iRect = 0; iRect < 9; iRect++) { for (int iV = 0; iV < 6; iV++) { m_tVertexList.push_back(m_Actor[iRect].m_VertexList[iV]); } } } void SButton::MoveX(float fDis) { for (int iV = 0; iV < 6; iV++) { m_VertexList[iV].p.x += fDis; } GenCenter(); } void SButton::MoveY(float fDis) { for (int iV = 0; iV < 6; iV++) { m_VertexList[iV].p.y += fDis; } GenCenter(); } bool SButton::SetData(RECT rt,float fScaleX0, float fScaleX1, float fScaleY0, float fScaleY1, float fOffsetU0, float fOffsetU1, float fOffsetV0, float fOffsetV1) { m_rtInit = rt; m_sOffset.fScaleX0 = fScaleX0; m_sOffset.fScaleX1 = fScaleX1; m_sOffset.fScaleY0 = fScaleY0; m_sOffset.fScaleY1 = fScaleY1; m_sOffset.fOffsetU0 = fOffsetU0; m_sOffset.fOffsetU1 = fOffsetU1; m_sOffset.fOffsetV0 = fOffsetV1; m_sOffset.fOffsetV0 = fOffsetV1; SetVertexData(); return true; } bool SButton::Create(ID3D11Device* pd3dDevice, const TCHAR* pVsFile, const TCHAR* pPsFile, const TCHAR* pTexFile) { LoadVertexShaderFile(pd3dDevice,pVsFile); LoadPixelShaderFile(pd3dDevice,pPsFile); CreateInputLayout(pd3dDevice); CreateVertexBuffer(pd3dDevice, &m_tVertexList.at(0), m_tVertexList.size()); CreateConstantBuffer(pd3dDevice, &m_ActorCB, sizeof(SActorCB)); CreateLayout(pd3dDevice, m_dxObj.m_pVSBlob); LoadTexture(pd3dDevice, pTexFile); return true; } bool SButton::Init() { return true; } bool SButton::Frame(float fGameTimer, float fFps) { m_ActorCB.m_matWorld.RoationZ(fGameTimer); D3DXVECTOR3 vEye = D3DXVECTOR3(0.0f, 0.0f, -50.f); D3DXMatrixLookAtLH((D3DXMATRIX*)&m_ActorCB.m_matView, &vEye, &D3DXVECTOR3(0.0f, 0.0f, 0.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); D3DXMatrixOrthoLH((D3DXMATRIX*)&m_ActorCB.m_matProj, 2, 2, 0.0f, 100.0f); m_ActorCB.m_matWorld.Transpose(); m_ActorCB.m_matView.Transpose(); m_ActorCB.m_matProj.Transpose(); return true; } bool SButton::Render(ID3D11DeviceContext* pContext, UINT iVertexSize) { pContext->UpdateSubresource(m_dxObj.m_pConstantBuffer.Get(), 0, NULL, &m_ActorCB, 0, 0); m_dxObj.PreRender(pContext,iVertexSize); PostRender(pContext); return true; } bool SButton::PostRender(ID3D11DeviceContext* pContext) { pContext->Draw(m_tVertexList.size(), 0); return true; } bool SButton::Release() { SActor::Release(); for (int iRect = 0; iRect < 9; iRect++) { m_Actor[iRect].Release(); } return true; } SButton::SButton() { } SButton::~SButton() { } <file_sep>#pragma once #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <sstream> #include <cstdlib> #include <string> #include <string.h> #include <tchar.h> #include <vector> #define SPA _T(" ") using namespace::std; class Token; class value { public: TCHAR * m_szValue; value* m_pNext; friend class Token; public: value(TCHAR*); public: ~value(); }; <file_sep>#pragma once #include "TServerObj.h" class TDebugString : public TSingleton<TDebugString>, public TServerObj { private: friend class TSingleton<TDebugString>; public: HWND m_hList; public: void Print( char* fmt, ... ); public: bool Init(); bool Release(); WCHAR* GetMbToWcs(const char* strMsg); char* GetWcsToMbs(const WCHAR* strMsg); HRESULT ConvertWideStringToAnsiCch( char* msg, const WCHAR* strMsg, int iRen ); HRESULT ConverAnsiStringToWideCch( WCHAR* msg, const char* strMsg, int nRen ); void T_ERROR(bool bPrint=false); public: TDebugString(void); virtual ~TDebugString(void); }; #define I_Debug TDebugString::GetInstance()<file_sep>#pragma once class FWindow { public: FWindow(); virtual ~FWindow(); }; <file_sep>#include <Windows.h> LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM iParam) { switch (msg) { case WM_CREATE: { MessageBox(NULL, L"윈도우가 떳다", L"원도우가 떳다", MB_OK); } case WM_LBUTTONDOWN: { DestroyWindow(hWnd); }break; case WM_DESTROY: { PostQuitMessage(0); }return 0; } return DefWindowProc(hWnd, msg, wParam, iParam); } void GameRun() { //지형 , 오브젝트 ,이펙트,UI } void GameInit() { //지형 , 오브젝트 ,이펙트,UI } void GameRelease() { //지형 , 오브젝트 ,이펙트,UI } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevinst, LPSTR IpCmdLine, int nCmdShow) { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.hInstance = hInst; wc.lpszClassName = L"MY WINDOW"; wc.hIcon = LoadIcon(hInst, IDI_QUESTION); wc.hCursor = LoadCursor(NULL, IDC_IBEAM); wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH); wc.lpszMenuName = NULL; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wc.cbClsExtra = 0; wc.cbWndExtra = 0; if (RegisterClassEx(&wc) == FALSE) { return 1; } HWND hWnd = CreateWindowEx(WS_EX_APPWINDOW, L"MY Windeow", L"KGCA SAMPLES", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, NULL, NULL, hInst, NULL); if (hWnd == NULL) { return 1; } ShowWindow(hWnd, SW_SHOW); GameInit(); MSG msg; ZeroMemory(&msg, sizeof(MSG)); while (1) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { //화면에 무언가를 뿌린다.(DRAW); GameRun(); } } GameRelease(); return 0; }<file_sep>#include "TDebugString.h" #include "TSynchronize.h" bool TDebugString::Init() { m_hList = NULL; return true; } bool TDebugString::Release() { return true; } void TDebugString::Print( char* fmt, ... ) { if (m_hList == NULL) return; { TSynchronize Sync(this); va_list arg; va_start(arg, fmt ); char buf[256] = {0,}; vsprintf_s( buf, fmt, arg ); SendMessage( m_hList, LB_ADDSTRING, 0, (LPARAM)I_Debug.GetMbToWcs(buf) ); int index = SendMessage (m_hList , LB_GETCOUNT , 0 , 0) ; if(index > 30) { SendMessage( m_hList, LB_RESETCONTENT, 0,0 ); } va_end(arg); } } void TDebugString::T_ERROR(bool bPrint) { { TSynchronize Sync(this); if(WSAGetLastError() != WSA_IO_PENDING ) { char* lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&lpMsgBuf, 0, NULL ); if( bPrint ) { MessageBoxA(NULL, lpMsgBuf, "ERROR", MB_OK ); } else { OutputDebugStringA((char*)lpMsgBuf); } LocalFree( lpMsgBuf ); } } } WCHAR* TDebugString::GetMbToWcs(const char* strMsg) { TCHAR msg[4096] = {0, }; { TSynchronize Sync(this); int nRen = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, 0, 0 ); ConverAnsiStringToWideCch( msg, strMsg, nRen ); } return msg; } HRESULT TDebugString::ConverAnsiStringToWideCch( WCHAR* msg, const char* strMsg, int nRen ) { { TSynchronize Sync(this); if( msg == NULL || strMsg == NULL || nRen < 1) { return E_INVALIDARG; } int nRetrun = MultiByteToWideChar(CP_ACP, 0, strMsg, -1, msg, nRen ); if(nRen == 0) return E_FAIL; msg[nRen-1]=0; } return S_OK; }; char* TDebugString::GetWcsToMbs(const WCHAR* strMsg) { char msg[4096] = {0, }; { TSynchronize Sync(this); int iRen = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, 0, 0, NULL, NULL); ConvertWideStringToAnsiCch( msg, strMsg, iRen ); } return msg; } HRESULT TDebugString::ConvertWideStringToAnsiCch( char* msg, const WCHAR* strMsg, int iRen ) { { TSynchronize Sync(this); if( msg == NULL || strMsg == NULL || iRen < 1 ) { return E_INVALIDARG; } int iReturn = WideCharToMultiByte(CP_ACP, 0, strMsg, -1, msg, iRen, NULL, NULL); if( iReturn == 0 ) return E_FAIL; } return S_OK; }; TDebugString::TDebugString(void) { } TDebugString::~TDebugString(void) { } <file_sep>#include "Token.h" void Token::Show() { value* pData = m_pToken; for (int i = 0; i < m_iSize; i++) { std::wcout << pData->m_szValue << endl; pData = pData->m_pNext; } } Token::Token(TCHAR* pData) { m_iSize = 0; TCHAR* temp; TCHAR* pszNextToken = 0; temp = _tcstok_s(pData, SPA, &pszNextToken); if (temp != NULL) { m_pToken = new value(temp); value* pLink = m_pToken; for (m_iSize = 1; temp = _tcstok_s(0, SPA, &pszNextToken); m_iSize++) { pLink->m_pNext = new value(temp); pLink = pLink->m_pNext; } } } Token::~Token() { value* pDel; value* pLink = m_pToken; while (pLink != 0) { pDel = pLink; pLink = pLink->m_pNext; delete pDel; } } <file_sep>#include<stdio.h> #include<conio.h> void func() { static int a = 0; a = a + 1; printf("%d\n", a); } void main() { func(); func(); func(); _getch(); }<file_sep>#pragma once #include "S_PacketPool.h" class S_SvrUser : public S_SvrObj { public: S_StreamPacket m_StreamPacket; SOCKET m_Socket; C_STR m_szname; SOCKADDR_IN m_UserAddr; WSABUF m_szRecvBuf; WSABUF m_szWSABuf; char m_strBuffer[4096]; OVERLAPPEDEX m_OV; public: bool Create(); bool Run(); virtual void AddPacket(PACKET& addPacket); virtual void DeleteUser(SOCKET socket); virtual void DeleteUser(); virtual void WaitforPacketReceive(); virtual void Dispatch(DWORD dwByteSize, LPOVERLAPPED Ov); public: S_SvrUser(); virtual ~S_SvrUser(); }; <file_sep>#pragma once #include <iostream> using namespace std; class TParent { public: TParent(void); //생성자 ~TParent(void); //소멸자 TParent(int money); void Character(void); //성품 출력 void Appearance(void); //외모 출력 void Wealth(void); // 재산 출력 private: int money; // 돈 저장 }; <file_sep>#include "TDepartment.h" int main() { //직원을 관리하는 CONTROL 클래스 TDepartment department; //직원 등록 department.AddEmployee(new TPermanent("KIM", 1000)); department.AddEmployee(new TPermanent("LEE", 1500)); department.AddEmployee(new TTemporary("HAN", 10, 200)); department.AddEmployee(new TTemporary("JANG", 12, 300)); //최종적으로 이번달에 지불해야할 급여는? department.ShowList(); return 0; }<file_sep>#pragma once #include "S_AnimObj.h" class S_Writer : public S_AnimObj, public SSingleton<S_Writer> { private: friend class SSingleton<S_Writer>; public: FILE* m_pStream; TSTR m_strFileName; public: bool Init(TSTR strFileName, Interface* pMax); bool KHJExport(); bool Release(); public: TCHAR* SaveFileDlg(TCHAR* szExt, TCHAR* szTitle = _T("KHJExporter")); void ExpScene(); void ExpMaterial(); void ExpObject(); int ExpMesh(FILE* fp, SMesh* pMesh, int iMtrl = -1, int iAddCount = 0); void ExpAnimation(SMesh* pMesh); void ExpTexture(vector<STexMap>&TexMap); int IsEqulVertexList(vector<PNCT_VERTEX>& VertexArray, PNCT_VERTEX& Vertex); int SetUniqueBuffer(SMesh* pMesh, int iMtrl, int iStartTri, vector<PNCT_VERTEX>& VertexArray, vector<int>& IndexArray); void matExport(); public: S_Writer(); virtual ~S_Writer(); }; #define I_Writer S_Writer::GetInstance() <file_sep>#include <Windows.h> #include <tchar.h> #pragma comment (lib, "winmm.lib") LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_DESTROY: { PostQuitMessage(0); }break; } return DefWindowProc(hWnd, msg, wParam, lParam); } int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPWSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.hInstance = hInst; wc.lpfnWndProc = WndProc; wc.lpszClassName = L"MYWINDOW"; if (RegisterClassEx(&wc) == false) { return false; } HWND hWnd = CreateWindowEx(WS_EX_APPWINDOW, L"MYWINDOW",L"SAMPLEWINDOW", WS_OVERLAPPEDWINDOW, 0,0,800,600, NULL,NULL,hInst,NULL); if (hWnd == NULL) return false; ShowWindow(hWnd, SW_SHOW); HBITMAP hBitmap = (HBITMAP)LoadImage(hInst, L"end04.bmp.bmp", IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE | LR_LOADFROMFILE); HDC hdc = GetDC(hWnd); HDC hMemDC = CreateCompatibleDC(hdc); HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap); MSG msg; while (1) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { } } }<file_sep>#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <ws2tcpip.h> #include <Windows.h> #include <windowsx.h> #include <process.h> #include <thread> #include <iostream> #include <tchar.h> #include <string> #include <algorithm> #include <io.h> #include <vector> #include <list> #include <map> #pragma comment (lib,"SSvrLIB.lib") #pragma comment (lib,"ws2_32.lib") #pragma comment (lib,"winmm.lib") using namespace std; #include "SSingleton.h" extern HWND g_hWnd; extern HINSTANCE g_hInstance; extern RECT g_rtClient; extern int g_iFPS;// 1초당 프레임 개수 extern float g_fSecPerFrame; // 1프레임의 경과시간 extern float g_fAccumulation;// 실행된 경과 시간 extern HDC g_hScreenDC; extern HDC g_hOffScreenDC; <file_sep>#pragma once #include "SServerObj.h" class SThread : public SServerObj { public: unsigned int m_hThread; // 쓰레드 변수 unsigned int m_iThreadID; // 쓰레드 ID 변수 bool m_bStarted; // 쓰레드의 시작지점 변수 public: void CreateThread(); // 쓰레드 생성 함수 virtual bool Run(); // 돌리는 함수 static unsigned int WINAPI HandleRunner(LPVOID parameter); // 쓰레드를 돌리는 함수 public: SThread(void); virtual ~SThread(void); }; <file_sep>#include "S_KHJWriter.h" void S_KHJWriter::Run() { Exeporter(); } void S_KHJWriter::GetTexture(Mtl* pmtl, xMtrlerial& xMtrl) { for (int iSubMap=0;iSubMap< pmtl->NumSubTexmaps(); iSubMap++) { xTextureMap xTexMap; Texmap* tex = pmtl->GetSubTexmap(iSubMap); if (tex) // tex가 NULL이 아니여야한다. { // 실제 적용여부 판단 if (pmtl->ClassID() == Class_ID(DMTL_CLASS_ID,0)) { StdMat* std = (StdMat*)pmtl; if(std->MapEnabled(iSubMap)) continue; } // 실제 정보 얻기 if (tex->ClassID() == Class_ID(BMTEX_CLASS_ID, 0)) // bitmap이다 { TSTR mapname = ((BitmapTex*)tex)->GetMapName(); TSTR szFullName; TSTR szMapName; SplitPathFile(mapname, &szFullName, &szMapName); // max api // szMapName 이걸원한다! xTexMap.iType = iSubMap ; xTexMap.name = szMapName; xMtrl.m_mapList.push_back(xTexMap); } } } } void S_KHJWriter::DumpMatrix3(Matrix3* m, _D3DMATRIX& mat) { } void S_KHJWriter::Exeporter() { m_Scene.iNumObject = m_ObjectList.size(); m_Scene.iNumMtrl = m_MtrlList.size(); m_pStream = _tfopen(this->m_szFileName,_T("wt")); // 파일 생성 _ftprintf(m_pStream, _T("%s"), _T("#SCENE")); _ftprintf(m_pStream, _T("\n%d %d %d %d %d %d"), m_Scene.iFirstFrame, m_Scene.iLastFrame, m_Scene.iFrameSpeed, m_Scene.iTickPerFrame, m_Scene.iNumObject, m_Scene.iNumMtrl); for (int iMtl = 0; iMtl < m_MtrlList.size(); iMtl++) { xMtrlerial xMtl; TSTR calssname; m_MtrlList[iMtl]->GetClassName(calssname); TSTR name = m_MtrlList[iMtl]->GetName(); xMtl.m_SubMaterial.resize(m_MtrlList[iMtl]->NumSubMtls()); if(xMtl.m_SubMaterial.size()>0) { for (int iSub=0; iSub< xMtl.m_SubMaterial.size();iSub++) { Mtl* pSubMtl = m_MtrlList[iMtl]->GetSubMtl(iSub); GetTexture(pSubMtl,xMtl.m_SubMaterial[iSub]); //sub } } else { GetTexture(m_MtrlList[iMtl], xMtl); //root } m_xMtrlList.push_back(xMtl); } for (int iObj = 0; iObj < m_ObjectList.size(); iObj++) //helper geom { xGeomMesh xmesh; INode* pNode = m_ObjectList[iObj]; INode* pParent = pNode->GetParentNode; xmesh.name = pNode->GetName(); xmesh.pParentName = _T("none"); if (!pParent->IsRootNode())// 가상의 노드 { xmesh.pParentName = pParent->GetName(); //false 가 되야 진짜 } // nodetm Matrix3 matWorld=pNode->GetNodeTM(m_Interval.Start()); DumpMatrix3(matWorld, xmesh.matWorld); GetMesh(pNode) // mtrl_ref Mtl* pMtl = m_ObjectList[iObj]->GetMtl(); int iMtlRef = -1; for (int iMtl = 0; iMtl < m_MtrlList.size(); iMtl++) { if (pMtl == m_MtrlList[iMtl]) { iMtlRef = iMtl; // mtlRef 여기에 있다 } } xmesh.mtrlRef = iMtlRef; m_xObjectList.push_back(xmesh); } _ftprintf(m_pStream, _T("\n%s"), _T("#MATERIALE")); /* for (int iMtl = 0; iMtl < m_xMtrlList.size(); iMtl++) { if (m_xMtrlList[iMtl].m_SubMaterial.size() > 0) { for (iSub = 0; iSub<) for (int iSub = 0; iSub < m_xMtrlList[iMtl].m_mapList.size(); iSub++) { _ftprintf(m_pStream, _T("\n%d %s"), m_xMtrlList[iMtl].m_mapList[iSub].iType, m_xMtrlList[iMtl].m_mapList[iSub].name); } } }*/ /* _ftprintf(m_pStream, _T("%s"), _T("#OBJECT")); _ftprintf(m_pStream, _T("\n%d %d %d %d %d %d"),*/ fclose(m_pStream); } void S_KHJWriter::GetMesh(INode* pNode, xGeomMesh& xMesh) { ObjectState os = pNode->EvalWorldState(m_Interval.Start()); if (!os.obj || os.obj->SuperClassID() != GEOMOBJECT_CLASS_ID)return; BOOL needDel; TriObject* tri = GetTriObjectFromNode(pNode,m_Interval.Start(), needDel); if (tri == NULL)return; Mesh* mesh = &tri->GetMesh(); int v0, v1, v2; BOOL negScale = TMNegParity(tm); if (negScale) { v0 = 2; v1 = 1; v2 = 0; } else { v0 = 0; v1 = 1; v2 = 2; } int iNumFace = mesh->getNumFaces(); for (int iFace = 0; iFace < iNumFace; iFace++) { Point3 v; int iNumVertex = mesh->getNumVerts(); if(iNumVertex > 0) { v = mesh->verts[mesh->faces[iFace].v[0]]; v = mesh->verts[mesh->faces[iFace].v[2]]; v = mesh->verts[mesh->faces[iFace].v[1]]; } int iNumVertex = mesh->getNumTVerts(); if (iNumVertex > 0) { } int iNumVertex = mesh->getNumVertCol(); if (iNumVertex > 0) { } mesh->buildNormals; } if (needDel)delete tri; } void S_KHJWriter::Release() { } S_KHJWriter::S_KHJWriter() { } S_KHJWriter::~S_KHJWriter() { } <file_sep>#pragma once #include "TThread.h" #include "TPacket.h" class TAcceptor : public TThread { public: SOCKET m_ListenSock; public: bool Run(); bool Release(); bool Set( int iPort, const char* strAddress = 0); virtual void AddUser(SOCKET socket, SOCKADDR_IN address ); public: TAcceptor(void); virtual ~TAcceptor(void); }; <file_sep>#include "TChild.h" void TChild::Humanity(void) { cout << "넘치는 인간미" << endl; } void TChild::Character(void) { cout << "불 같은 성품 " << endl; } void TChild::Appearance(void) { TParent::Appearance(); //기반 클래스에서 정의한 기능 cout << "훤칠한 키" << endl; //파생 클래스에서 확장된 기능 } //TChild::TChild() //{ // cout << "Child 생성자" << endl; //} TChild::TChild(void) : TParent(1000) { cout << "Child 생성자" << endl; } TChild::~TChild() { cout << "Child 소멸자" << endl; }
5aa4d76fef6247d93b6500f73512cdc98143b25d
[ "C", "C++" ]
570
C++
leader1118/KHJ-Project
0eb0144bbd2b4d40156402a5994c8f782b558f6c
a854bc392991e24774ab0feca0bb49eb8593ef15
refs/heads/master
<repo_name>AlexisFigueroaDev/JS-Node-React<file_sep>/Fundamentos/flecha.js function sumar(a, b = 10) { return a + b; } console.log(sumar(5)); function resta(a, b) { return a - b; } console.log(resta(5, 2)); const sumar2 = (a, b) => { return a + b; }; console.log(sumar2(5, 3)); const sumar3 = (a, b) => a + b; console.log(sumar3(5, 4)); const saludar = (nombre) => `Hola ${nombre}`; console.log(saludar('Alexis')); //pusheado <file_sep>/Practicas/practica/index.js const express = require('express'); // const routes = require('./routes'); const bodyParser = require('body-parser'); const db = require('./db/db'); const env = require('node-env-file'); env('Environment.env'); const app = express(); // habilitar bodyparser app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // app.use('/', routes()); app.listen(process.env.PORT); console.log(`Escuchando el puerto ${process.env.PORT}`); //Middleware const token = (req, res, next) => { auth = req.header('auth'); console.log(auth); if (auth !== '<PASSWORD>') { res.status(401).json({ message: 'No tiene acceso', }); } next(); }; //controllers const buscoParticipante = (req, res) => { nombre = req.body; const user = Object.values(db.participantes).find( (e) => e.nombre === nombre.nombre ); if (user !== undefined) { res.json({ message: user, }); } else { res.json({ message: 'No existe el usuario', }); } }; //ROUTES app.get('/busco', [token], buscoParticipante); <file_sep>/Practicas/Atributos_extendidos.js /* * * Atributos extendidos * */ let myName = { firstname: 'Alexis', middlename: 'Gabriel', }; let lastname = 'Figueroa'; //los 3 puntos agregan un objeto dentro de uno nuevo trayendo la informacion del objeto let myLife = { ...myName, lastname, }; // console.log(myLife); //Arreglo let heroes = ['Batman', 'Superman']; let villanos = ['villano1', 'villano2']; console.log(heroes); console.log(villanos); let personajes = [...heroes, ...villanos]; console.log(personajes); <file_sep>/Fundamentos/callback-hell.js const empleados = [ { id: 1, nombre: 'Alexis', }, { id: 2, nombre: 'Linda', }, { id: 3, nombre: 'Karen', }, ]; const salarios = [ { id: 1, salario: 5000, }, { id: 2, salario: 1500, }, ]; const getEmpleado = (id, callback) => { const empleado = empleados.find((e) => e.id === id); if (empleado) { callback(null, empleado); } else { callback(`Empleado con id ${id} no existe`); } }; const getSalario = (id, callback) => { const salario = salarios.find((e) => e.id === id)?.salario; if (salario) { callback(null, salario); } else { callback(`El salario con id ${id} no existe`); } }; getEmpleado(3, (err, empleado) => { if (err) { return console.log(err); } console.log(empleado.nombre); }); getSalario(10, (err, salario) => { if (err) { return console.log(err); } console.log(salario); }); <file_sep>/README.md # Curso NodeJS - React - Fundamentos de jS <file_sep>/Practicas/practica/db/db.js const participantes = { participante1: { nombre: 'Alexis', edad: 28, }, participante2: { nombre: 'manuela', edad: 38, }, participante4: { nombre: 'lucas', edad: 27, }, participante5: { nombre: 'hernan', edad: 31, }, }; module.exports = { participantes, }; <file_sep>/Fundamentos/template-string.js const nombre = 'Alexis'; const real = 'Gabriel'; const normal = nombre + ' ' + real; const template = `nombre completo: ${normal} Figueroa`; console.log(normal); console.log(template); const html = ` <h1>Hola</h1> <p>Mundo</p> `; console.log(html);
0632bb245036ad2062d2cc86bb8e70b1d31a7400
[ "JavaScript", "Markdown" ]
7
JavaScript
AlexisFigueroaDev/JS-Node-React
6cc3acc33f8d7e583568c74a04a86deb37a01e50
8621e992ee461410353b9715492796e5fb7728b7
refs/heads/master
<repo_name>mual3154/HW1<file_sep>/test.cpp nclude <iostream> #include <string> #include <fstream> #include <sstream> #include <math.h> #include <string> #include <vector> using namespace std; //int check(string ind); //int *dubs(int array[], int size, int number); struct wordItem//structure for the words { string word; int count; }; void getStopwords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords); void printTopN(wordItem *&wordItemList, int topN); bool isCommonWord(string word, vector<string>& _vecIgnoreWords); const int STOPWORD_LIST_SIZE = 50; int main(int argc, char *argv[]) { int size = 100;//initialize array/size wordItem *library = new wordItem[size];//use later for doubling vector<string> vecIgnoreWords(STOPWORD_LIST_SIZE); int t = atoi(argv[1]);//This changes the command line argument to an integer getStopwords(argv[3], vecIgnoreWords); string ind; int totwrds = 0;//total words in document int unqwrds = 0;//total "unique" words int v=0;// int aindex=0; int dbscnt=0; ifstream file; file.open(argv[2]); while(file >> ind) { totwrds = totwrds + 1; if(file.is_open()) { bool a = isCommonWord(ind, vecIgnoreWords); if (a == false)//only continues if the word is unique { unqwrds++; for(int i = 0; i<=aindex; i++)//if the word is already in library the counter goes up { if(ind == library[i].word) { library[i].count++; v=1;//resets while loop } } if(v==0)//adds word if not in library { library[aindex].word = ind; library[aindex].count = 1; aindex++; } for(int z=0;z<size;z++)//ensures that the library is in descending order { if (library[z+1].count > library[z].count) { int temp = 0; string tem; temp = library[z].count; library[z].count = library[z+1].count; library[z+1].count = temp; tem = library[z].word; library[z].word = library[z+1].word; library[z+1].word = tem; } } if (size <= aindex)//here we double { dbscnt++; wordItem *newArray = new wordItem[2*size]; for (int i=0; i<size; i++) { newArray[i].count = library[i].count; newArray[i].word = library[i].word; } size*=2; delete[] library; library = newArray; } } } v=0; } printTopN(library, t); cout<<"#"<<endl; cout<<"Array doubled: "<<dbscnt<<endl; //cout<<size<<endl; //cout<<totwrds<<endl; cout<<"#"<<endl; cout<<"Unique non-common words: "<<aindex<<endl; cout<<"#"<<endl; cout<<"Total non-common words: "<<unqwrds<<endl; file.close(); delete[] library; } /*int check(string ind) { if (ind == "the") return 1; if (ind == "be") return 1; if (ind == "to") return 1; if (ind == "of") return 1; if (ind == "and") return 1; if (ind == "a") return 1; if (ind == "in") return 1; if (ind == "that") return 1; if (ind == "have") return 1; if (ind == "i") return 1; if (ind == "it") return 1; if (ind == "for") return 1; if (ind == "not") return 1; if (ind == "on") return 1; if (ind == "with") return 1; if (ind == "he") return 1; if (ind == "as") return 1; if (ind == "you") return 1; if (ind == "do") return 1; if (ind == "at") return 1; if (ind == "this") return 1; if (ind == "but") return 1; if (ind == "his") return 1; if (ind == "by") return 1; if (ind == "from") return 1; if (ind == "they") return 1; if (ind == "we") return 1; if (ind == "say") return 1; if (ind == "her") return 1; if (ind == "she") return 1; if (ind == "or") return 1; if (ind == "an") return 1; if (ind == "will") return 1; if (ind == "my") return 1; if (ind == "one") return 1; if (ind == "all") return 1; if (ind == "would") return 1; if (ind == "there") return 1; if (ind == "their") return 1; if (ind == "what") return 1; if (ind == "so") return 1; if (ind == "up") return 1; if (ind == "out") return 1; if (ind == "if") return 1; if (ind == "about") return 1; if (ind == "who") return 1; if (ind == "get") return 1; if (ind == "which") return 1; if (ind == "go") return 1; if (ind == "me") return 1; return 0;}*/ void getStopwords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords) { int i = 0; string igword; ifstream ignore; ignore.open(ignoreWordFileName); while(ignore >> igword) { if(ignore.is_open()) { _vecIgnoreWords[i] = igword; i++; } } ignore.close(); } bool isCommonWord(string word, vector<string>& _vecIgnoreWords) { for(int i = 0; i<STOPWORD_LIST_SIZE; i++) { if(word == _vecIgnoreWords[i]) { return true; } } return false; } void printTopN(wordItem *&wordItemList, int topN) { for (int i = 0; i < topN; ++i) { cout<<wordItemList[i].count<<"-"<<wordItemList[i].word<<endl; } } <file_sep>/HW1.cpp #include<iostream> #include<fstream> #include<sstream> #include<string> #include<cstdlib> #include<vector> using namespace std; struct wordItem{ string word; int count; }; void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords); bool isCommonWord(string word, vector<string>& _vecIgnoreWords); void printTopN(wordItem wordItemList[], int topN); const int STOPWORD_LIST_SIZE = 50; int main(int argc, char* argv[]) { if (argc != 4) { cout << "Usage: "; cout << argv[0] << " <number of words> <filename.txt> <ignorefilename.txt>"; cout << endl; return 0; } //end of parameter check -------------------------------------------------------------------- int size = 100; wordItem *library = new wordItem [size]; int range = stoi(argv[1]); string mainFile = argv[2]; //string ignoreFile = argv[3]; vector<string> vecIgnoreWords(STOPWORD_LIST_SIZE); getStopWords(argv[3], vecIgnoreWords); string ind; int totwrds = 0; int unqwrds = 0; int v = 0; int aindex = 0; int dbscnt = 0; ifstream file; file.open(mainFile); while(file >> ind) { totwrds++; if(file.is_open()) { bool a = isCommonWord(ind , vecIgnoreWords); if(a == false) { unqwrds++; for(int i = 0; i<=aindex; i++) { if(ind == library[i].word) { library[i].count++; v=1;//resets while loop } } if(v==0)//adds word if not in library { library[aindex].word = ind; library[aindex].count = 1; aindex++; } for(int z=0;z<size;z++)//ensures that the library is in descending order { if (library[z+1].count > library[z].count) { int temp = 0; string tem; temp = library[z].count; library[z].count = library[z+1].count; library[z+1].count = temp; tem = library[z].word; library[z].word = library[z+1].word; library[z+1].word = tem; } } if (size <= aindex)//here we double { dbscnt++; wordItem *newArray = new wordItem[2*size]; for (int i=0; i<size; i++) { newArray[i].count = library[i].count; newArray[i].word = library[i].word; } size*=2; delete[] library; library = newArray; } } } v = 0; } printTopN(library, range); cout<<"#"<<endl; cout<<"Array doubled: "<<dbscnt<<endl; cout<<"#"<<endl; cout<<"Unique non-common words: "<<aindex<<endl; cout<<"#"<<endl; cout<<"Total non-common words: "<<unqwrds<<endl; file.close(); delete[] library; return 0; } void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords) { int i = 0; string igword; ifstream ignore; ignore.open(ignoreWordFileName); while(ignore >> igword) { if(ignore.is_open()) { _vecIgnoreWords[i] = igword; i++; } } ignore.close(); } bool isCommonWord(string word, vector<string>& _vecIgnoreWords) { for(int i = 0; i<STOPWORD_LIST_SIZE; i++) { if(word == _vecIgnoreWords[i]) { return true; } } return false; } void printTopN(wordItem wordItemList[], int topN) { for(int x = 0 ; x<topN ; x++) { cout << wordItemList[x].word << " - " << wordItemList[x].count << endl; } return; }
9a6be9091fb03ed645787dc0b98f8cdb2c014abb
[ "C++" ]
2
C++
mual3154/HW1
fb22c997706cd44dd8c852fce148c84236527ffa
792753cbd49e0944ab549ea098f51a556f15cdfd
refs/heads/master
<file_sep> Resize DSLR image magic convert BackPack.png -filter Lanczos -define filter:lobes=4 -define filter:blur=0.88451002338585141 -resize 1200x1200 Lanczos_4.png http://www.imagemagick.org/discourse-server/viewtopic.php?t=20992&p=85257#p85257 http://www.imagemagick.org/Usage/resize/#cyl_interpolated <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.eliaharm</groupId> <artifactId>photoflow</artifactId> <version>1.0-SNAPSHOT</version> <name>PhotoFlow</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <mainClass>com.eliaharm.photoflow.MainApp</mainClass> </properties> <organization> <!-- Used as the 'Vendor' for JNLP generation --> <name><NAME></name> </organization> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>unpack-dependencies</id> <phase>package</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <excludeScope>system</excludeScope> <excludeGroupIds>junit,org.mockito,org.hamcrest</excludeGroupIds> <outputDirectory>${project.build.directory}/classes</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <id>unpack-dependencies</id> <phase>package</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>${java.home}/../bin/javapackager</executable> <arguments> <argument>-createjar</argument> <argument>-nocss2bin</argument> <argument>-appclass</argument> <argument>${mainClass}</argument> <argument>-srcdir</argument> <argument>${project.build.directory}/classes</argument> <argument>-outdir</argument> <argument>${project.build.directory}</argument> <argument>-outfile</argument> <argument>${project.build.finalName}.jar</argument> </arguments> </configuration> </execution> <execution> <id>default-cli</id> <goals> <goal>exec</goal> </goals> <configuration> <executable>${java.home}/bin/java</executable> <commandlineArgs>${runfx.args}</commandlineArgs> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArguments> <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib/jfxrt.jar</bootclasspath> </compilerArguments> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> <configuration> <additionalClasspathElements> <additionalClasspathElement>${java.home}/lib/jfxrt.jar</additionalClasspathElement> </additionalClasspathElements> </configuration> </plugin> <!-- elia added --> <plugin> <groupId>io.repaint.maven</groupId> <artifactId>tiles-maven-plugin</artifactId> <version>2.11</version> <extensions>true</extensions> <configuration> <tiles> <tile>org.avaje.tile:java-compile:1.1</tile> <tile>io.ebean.tile:enhancement:5.5</tile> </tiles> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <mainClass>com.eliaharm.photoflow.MainApp</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <!-- this is used for inheritance merges --> <phase>package</phase> <!-- bind to the packaging phase --> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.jmtp</groupId> <artifactId>jmtp</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jmtp.jar</systemPath> </dependency> <!-- encryption --> <dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId> <version>1.9.2</version> <classifier>lite</classifier> <scope>compile</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.197</version> <!--<scope>test</scope> --> </dependency> <!-- for ebean --> <!-- https://mvnrepository.com/artifact/io.ebean/ebean --> <dependency> <groupId>io.ebean</groupId> <artifactId>ebean</artifactId> <version>11.15.4</version> </dependency> <!-- support for query beans --> <dependency> <groupId>io.ebean</groupId> <artifactId>ebean-querybean</artifactId> <version>11.2.1</version> </dependency> <!-- java annotation processor to generate query beans --> <dependency> <groupId>io.ebean</groupId> <artifactId>querybean-generator</artifactId> <version>11.1.2</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/io.ebean.tile/enhancement --> <!-- <dependency> <groupId>io.ebean.tile</groupId> <artifactId>enhancement</artifactId> <version>5.5</version> </dependency> --> <!-- Optional but Ebean will read these annotations like @size to determine column lengths etc --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <!-- still under test --> <dependency> <groupId>org.controlsfx</groupId> <artifactId>controlsfx</artifactId> <version>8.40.14</version> </dependency> <!-- material design <dependency> <groupId>com.jfoenix</groupId> <artifactId>jfoenix</artifactId> <version>8.0.3</version> </dependency> --> <!-- Java ffmpeg command-line wrapper --> <dependency> <groupId>com.github.kokorin.jaffree</groupId> <artifactId>jaffree</artifactId> <version>0.5.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.mjeanroy/exiftool-lib --> <dependency> <groupId>com.github.mjeanroy</groupId> <artifactId>exiftool-lib</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>net.bramp.ffmpeg</groupId> <artifactId>ffmpeg</artifactId> <version>0.6.2</version> </dependency> <!-- encryption --> <dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId> <version>1.9.2</version> <classifier>lite</classifier> <scope>compile</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> </dependencies> </project> <file_sep>package com.eliaharm.photoflow.mtp; public class MTPDeviceInfo { private final String model; private final String serialNumber; public MTPDeviceInfo(final String model, final String serialNumber) { this.model = model; this.serialNumber = serialNumber; } @Override public String toString() { return model + " - " + serialNumber; } }
1589cff6a25121b9700598222ee1d65ea56dd7c0
[ "Java", "Text", "Maven POM" ]
3
Text
eliaharm/photoflow
56496be92b08c0732b365169692c05065ba00e7c
98ff73adaeb4a6363c7b7f6bfdb1fed9f95310a5
refs/heads/master
<file_sep>package com.otus.hw_07.library; import com.otus.hw_07.domain.Author; import com.otus.hw_07.domain.Book; import com.otus.hw_07.domain.Genre; import com.otus.hw_07.repositories.AuthorRepository; import com.otus.hw_07.repositories.BookRepository; import com.otus.hw_07.repositories.GenreRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; @Service @RequiredArgsConstructor public class LibraryService { private final AuthorRepository authorRepository; private final GenreRepository genreRepository; private final BookRepository bookRepository; public List<Book> findAllBooks() { return bookRepository.findAll(); } public List<Book> findBooksByTitle(final String title) { return bookRepository.findByTitleContainingIgnoreCase(title); } public List<Author> findAllAuthors() { return authorRepository.findAll(); } public List<Author> findAuthorsByFirstName(final String firstName) { return authorRepository.findAuthorByFirstNameContainingIgnoreCase(firstName); } public List<Genre> findAllGenres() { return genreRepository.findAll(); } public List<Genre> findGenresByName(final String genreName) { return genreRepository.findGenresByName(genreName); } } <file_sep>package com.otus.hw_07.changelog; import com.github.cloudyrock.mongock.ChangeLog; import com.github.cloudyrock.mongock.ChangeSet; import com.google.gson.Gson; import com.mongodb.MongoClient; import com.otus.hw_07.domain.Author; import com.otus.hw_07.domain.Book; import com.otus.hw_07.domain.Genre; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.types.ObjectId; import org.springframework.data.mongodb.core.MongoTemplate; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Objects.requireNonNull; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; @Slf4j @ChangeLog public class LibraryChangeLog { private static final String DATABASE = "library"; private static final String AUTHORS = "authors"; private static final String GENRES = "genres"; private static final String BOOKS = "books"; private static final String AUTHORS_JSON_RESOURCE = "json/authors.json"; private static final String GENRES_JSON_RESOURCE = "json/genres.json"; private static final String BOOKS_JSON_RESOURCE = "json/books.json"; private static CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build())); @ChangeSet(author = "user", id = "dropDb", order = "001", runAlways = true) public void dropDb(final MongoTemplate template) { template.getDb().drop(); log.info("Dropped database {}", DATABASE); } @ChangeSet(author = "user", id = "createGenres", order = "020") public void createGenres(final MongoTemplate template) { val collection = template.getDb().getCollection(GENRES); final List<String> jsonFileContent = getFileContents(GENRES_JSON_RESOURCE); final String jsonFromFile = readFileToString(jsonFileContent); final Genre[] genres = new Gson().fromJson(jsonFromFile, Genre[].class); for (Genre g : genres) { collection.insertOne(new Document() .append("_id", new ObjectId(g.getId())) .append("genreName", g.getGenreName()) ); } log.info("Created collection {}", GENRES); } @ChangeSet(author = "user", id = "createAuthors", order = "010") public void createAuthors(final MongoTemplate template) { val collection = template.getDb().getCollection(AUTHORS); final List<String> jsonFileContent = getFileContents(AUTHORS_JSON_RESOURCE); final String jsonFromFile = readFileToString(jsonFileContent); final Author[] authors = new Gson().fromJson(jsonFromFile, Author[].class); for (Author a : authors) { collection.insertOne(new Document() .append("_id", new ObjectId(a.getId())) .append("firstName", a.getFirstName()) .append("lastName", a.getLastName()) ); } log.info("Created collection {}", AUTHORS); } @ChangeSet(author = "user", id = "createBooks", order = "030") public void createBooks(final MongoTemplate template) { val collection = template.getDb().withCodecRegistry(codecRegistry).getCollection(BOOKS); final List<String> jsonFileContent = getFileContents(BOOKS_JSON_RESOURCE); final String jsonFromFile = readFileToString(jsonFileContent); final Book[] books = new Gson().fromJson(jsonFromFile, Book[].class); for (Book b : books) { collection.insertOne(new Document() .append("_id", new ObjectId(b.getId())) .append("authors", b.getAuthors()) .append("comments", b.getComments()) .append("genres", b.getGenres()) .append("title", b.getTitle()) .append("year", b.getYear()) ); } log.info("Created collection {}", BOOKS); } public String readFileToString(final List<String> list) { String result; try (Stream<String> lines = list.stream()) { result = lines .map(String::trim) .collect(Collectors.joining()); } return result; } private List<String> getFileContents(final String resource) { final List<String> list = new ArrayList<>(); String str; try (final InputStream is = getClass().getClassLoader().getResourceAsStream(resource); final BufferedReader br = new BufferedReader(new InputStreamReader(requireNonNull(is)))) { while ((str = br.readLine()) != null) { list.add(str); } } catch (IOException e) { log.error("Exception in LibraryChangeLog class: {}", e); } return list; } } <file_sep># Spring Framework Developer Course - <NAME> - 2018-11 ## HW 7. Library app with Spring Data MongoDB - Create console library application - Use MongoDB and Spring Data for backend - Implement tests with embedded Mongo database ### Useful commands ```shell docker-compose exec mongo /bin/bash ``` ### Useful links [Spring Data MongoDB](https://spring.io/projects/spring-data-mongodb) [MongoDB Documentation](https://docs.mongodb.com/manual/) [MongoDB Java Driver](http://mongodb.github.io/mongo-java-driver/) <file_sep>plugins { id 'java' id 'groovy' id 'jacoco' id 'application' id 'com.adarshr.test-logger' version '1.6.0' id "org.springframework.boot" version "2.1.2.RELEASE" } apply plugin: 'io.spring.dependency-management' group = 'com.otus.hw_07' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' repositories { mavenCentral() maven { url 'https://repo.spring.io/milestone' } } ext { gsonVersion = '2.8.5' spockVersion = '1.2-groovy-2.5' groovyVersion = '2.5.6' springShellVersion = '2.0.1.RELEASE' junitJupiterVersion = '5.3.2' junitVintageVersion = '5.3.2' javaAssistVersion = '3.18.2-GA' mongockVersion = '2.0.0' } dependencies { implementation( "com.google.code.gson:gson:${gsonVersion}", 'org.springframework.boot:spring-boot-starter-data-mongodb', "org.springframework.shell:spring-shell-starter:${springShellVersion}", "org.javassist:javassist:${javaAssistVersion}", "com.github.cloudyrock.mongock:mongock-core:${mongockVersion}", "com.github.cloudyrock.mongock:mongock-spring:${mongockVersion}", "com.github.cloudyrock.mongock:mongock-jongo:${mongockVersion}" ) runtimeOnly 'org.springframework.boot:spring-boot-devtools' compileOnly 'org.projectlombok:lombok' testCompileOnly('org.projectlombok:lombok') annotationProcessor('org.projectlombok:lombok') testAnnotationProcessor('org.projectlombok:lombok') testImplementation( 'de.flapdoodle.embed:de.flapdoodle.embed.mongo', 'org.springframework.boot:spring-boot-starter-test', "org.spockframework:spock-core:${spockVersion}", "org.spockframework:spock-spring:${spockVersion}", "org.codehaus.groovy:groovy-all:${groovyVersion}", "org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}" ) testRuntimeOnly( "org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}", "org.junit.vintage:junit-vintage-engine:${junitVintageVersion}" ) } application { mainClassName = "com.otus.hw_07.App" } wrapper { gradleVersion = '5.2.1' } testlogger { theme 'standard-parallel' showStandardStreams = true } test { useJUnitPlatform() testLogging { exceptionFormat = 'full' showStandardStreams = true } } clean.doFirst { delete "out" } <file_sep>pluginManagement { repositories { gradlePluginPortal() } } rootProject.name = 'otus-spring-hw-07-spring-mongo' <file_sep>package com.otus.hw_07.library; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; @ShellComponent public class LibraryShell { private final LibraryService service; @Autowired public LibraryShell(final LibraryService service) { this.service = service; } @ShellMethod(value = "Find all books in the library.") public void findAllBooks() { service.findAllBooks().forEach(System.out::println); } @ShellMethod(value = "Find books by title.") public void findBookByTitle(final String title) { service.findBooksByTitle(title).forEach(System.out::println); } @ShellMethod(value = "Find all authors.") public void findAllAuthors() { service.findAllAuthors().forEach(System.out::println); } @ShellMethod(value = "Find authors by first name.") public void findAuthorsByFirstName(final String firstName) { service.findAuthorsByFirstName(firstName).forEach(System.out::println); } @ShellMethod(value = "Find all genres.") public void findAllGenres() { service.findAllGenres().forEach(System.out::println); } @ShellMethod(value = "Find genres by genre name.") public void findGenresByName(final String genreName) { service.findGenresByName(genreName).forEach(System.out::println); } }
451d0436df194bfbbcd39d02ec4479e47bcb4a06
[ "Markdown", "Java", "Gradle" ]
6
Java
gitpushforcemain/otus-spring-hw-07-spring-mongo
f5ccfff922d31f885ac3161db06792f9f9ff54bc
be7f167b6fc7a5855d7cd93b59985638ac031df8
refs/heads/master
<repo_name>anderson-optimization/gams-parser<file_sep>/Makefile IMAGE="andersonopt/task-gams-parser" NOSETEST=$(shell which nosetests) all: echo "Test" init: pip install -r requirements.txt build: docker build -t ${IMAGE} . deploy: docker push ${IMAGE} inspect: docker run -it --rm ${IMAGE} /bin/bash test: test_parse test_inject test_transform test_gams_parser test_inject test_writer ## Test categories test_parse: python ${NOSETEST} -v ${FLAGS} test/parse/*.py test_inject: python ${NOSETEST} -v ${FLAGS} test/inject/inject*.py test_transform: python ${NOSETEST} -v ${FLAGS} test/transform/*.py test_gams_parser: python ${NOSETEST} -v ${FLAGS} test/gams_parser/*.py test_writer: python ${NOSETEST} -v ${FLAGS} test/writer/*.py ## Individuals test_real: python ${NOSETEST} -v ${FLAGS} test/parse/real.py test_equation: python ${NOSETEST} -v ${FLAGS} test/transform/transform_equation.py test_to_json: python ${NOSETEST} -v ${FLAGS} test/transform/transform_dict.py test_set: python ${NOSETEST} -v ${FLAGS} test/parse/set.py test_verbose: make FLAGS="--nocapture" test .PHONY: init test<file_sep>/gams_parser/gams_parser.py from lark import Lark import os from .tree_injector import TreeInjector from .tree_to_model import TreeToModel import logging logger = logging.getLogger('gams_parser') dirname = os.path.dirname(__file__) grammar_gams = os.path.join(dirname, 'grammar/gams.lark') grammar_ao_inject = os.path.join(dirname, 'grammar/ao_inject.lark') with open(grammar_gams,'r') as in_file: text=in_file.read() lark_gams = Lark(text,propagate_positions=True) with open(grammar_ao_inject,'r') as in_file: text=in_file.read() lark_ao_inject = Lark(text) def scrub_meta(obj, bad=["_meta","meta"]): if isinstance(obj, dict): for k in obj.keys(): if k in bad: del obj[k] else: scrub_meta(obj[k], bad) elif isinstance(obj, list): for i in reversed(range(len(obj))): if obj[i] in bad: del obj[i] else: scrub_meta(obj[i], bad) else: # neither a dict nor a list, do nothing pass class GamsParser(): def __init__(self,file): if isinstance(file,str): self.file = open(file,'r') else: self.file = file self.text=self.file.read() def inject(self,context=None,run=None,data=None): logger.debug("GamsParser : Inject : 1. Parse") self.text+="\n" pt= lark_ao_inject.parse(self.text) #print("Parse Tree") #print(pt.pretty()) logger.debug("GamsParser : Inject : 2. Transform") TI=TreeInjector(context,data=data) new_model,inject_map=TI.transform(pt) return new_model,inject_map def parse(self): return lark_gams.parse(self.text) def transform(self): parse_tree=lark_gams.parse(self.text) model=TreeToModel().transform(parse_tree) model.cross_reference() model.reference_lines(self.text) return model <file_sep>/test/transform/transform_equation.py from gams_parser import GamsParser import logging logging.basicConfig(level=logging.DEBUG) logging.debug("TEst") def test_transform_equation_def(): with open('./test/gams/equation-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) <file_sep>/test/transform/transform_real.py from gams_parser import GamsParser import logging logging.basicConfig(level=logging.DEBUG) logging.debug("TEst") def test_transform_real_shopmodel(): with open('./test/gams/real-shopmodel.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_real_eminit(): with open('./test/gams/real-eminit.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_real_siteanalysis(): with open('./test/gams/real-siteanalysis.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) <file_sep>/test/gams/inject-datademand.inc * Data sets , probably a csv table demand(time,site) $offlisting SiteA_Parcel **ao json2data group=demand "t{_index} {row.AverageLoad(kW)}" $onlisting ; <file_sep>/gdxpds/Makefile IMAGE="andersonopt/gdxpandas" all: echo "Test" build: gams.exe docker build -t ${IMAGE} . gams.exe: curl -o gams.exe https://d37drm4t2jghv5.cloudfront.net/distributions/27.1.0/linux/linux_x64_64_sfx.exe deploy: docker push ${IMAGE} inspect: docker run -it --rm ${IMAGE} /bin/bash clean: rm gams.exe<file_sep>/test/gams_parser/gp_class.py from gams_parser import GamsParser def test_open_file(): gp = GamsParser('./test/gams/set-ranged.gms') parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/README.md # GAMS Parser This python library uses [lark](https://github.com/lark-parser/lark) to parse the algebraic modeling language [GAMS](https://www.gams.com/). ## Package Overview ### Goals 1. Gather rich data on structure of model in a gams file. 2. Inject custom defintions and data into gams files based upon a DSL. 3. Format and write datasets into common GAMS formats 4. [Future direction] Gather defined data from model using python api. - This is probably outside the scope of this library as it requires `GAMS` as a dependency. ### Contents - [Parser](#Parser) - [Injector](#Injector) - [Writer](#Writer) ## Parser GAMS to AST Model This accomplishes goal 1. Create structure model from GAMS code. SHORT PARAGRAPH ON THIS FUNCTIONALITY HOW TO USE HERE ### Examples EXAMPLES HERE ## Injector AO GAMS DSL This accomplishes goal 2. Inject GAMS code into gams file using AO context item. SHORT PARAGRAPH ON THIS FUNCTIONALITY HOW TO USE HERE ### Examples #### List and map items Template file ``` * Project set project / **ao list project /; set asset / **ao list asset new_solar new_battery /; set gen(asset) / **ao list asset "type startswith asset:gen" **ao list asset "type startswith asset:battery" new_solar new_battery /; set project2asset(project,asset) / **ao map project asset /; set project2data(project,data) / **ao map project data /; ``` Output ``` * Project set project / SiteAProject /; * Asset set asset / SiteA_Parcel, ArcelormittalClevelandInc_GENC new_solar new_battery /; set gen(asset) / ArcelormittalClevelandInc_GENC new_solar new_battery /; set project2asset(project,asset) / SiteAProject.SiteA_Parcel SiteAProject.ArcelormittalClevelandInc_GENC SiteAProject.new_battery SiteAProject.new_solar /; set project2data(project,data) / SiteAProject.SiteALoad SiteAProject.SiteA_TOURates /; ``` #### Params Template ``` parameter param_financial(project,financial_field) / **ao param project 'step.financial.parameter.simplefinance' /; parameter param_solar(project,solar_field) / **ao param project 'step.solar.parameter.solar' /; ** SOC min/max???? parameter param_battery(project,battery_field) / **ao param project 'step.battery.parameter.batterycapitalcost' **ao param project 'step.battery.parameter.batterycharacter' **ao param project 'step.battery.parameter.batterysize' /; ``` Output ``` parameter param_financial(project,financial_field) / SiteAProject.stateTaxRate 0.05 SiteAProject.inflationRate 0.03 SiteAProject.period 25 SiteAProject.federalTaxRate 0.25 SiteAProject.omEscalationRate 0.02 SiteAProject.discountRate 0.08 /; parameter param_solar(project,solar_field) / SiteAProject.degradationRate 2 SiteAProject.capacityCost 1500 SiteAProject.omCost 2 SiteAProject.capacityPower 5 /; ** SOC min/max???? parameter param_battery(project,battery_field) / SiteAProject.energyCosts 1500 SiteAProject.capacityCosts 1500 SiteAProject.dischargeEfficiency 0.95 SiteAProject.chargeEfficiency 0.95 SiteAProject.duration 2 /; ``` #### Tariff Structure Template ``` set product /energy,demand/; set period /period1*period10/; set tier /tier1*tier10/; parameter product_rate(supply,product,period,tier) "Rate of energy/demand cost ($/kWh and $/kW)"; parameter product_adj(supply,product,period,tier) "Rate of adjustment ($/kWh and $/kW)"; set weekday_schedule(supply,product,month,hour,period); set weekend_schedule(supply,product,month,hour,period); ** Tariff definition parameter product_rate(supply,product,period,tier) / **ao tariff product_rate /; parameter product_adj(supply,product,period,tier) / **ao tariff product_adj /; set weekend_schedule(supply,product,month,hour,period) / **ao tariff weekend_schedule /; set weekday_schedule(supply,product,month,hour,period) / **ao tariff weekend_schedule /; ``` Output ``` set product /energy,demand/; set period /period1*period10/; set tier /tier1*tier10/; parameter product_rate(supply,product,period,tier) "Rate of energy/demand cost ($/kWh and $/kW)"; parameter product_adj(supply,product,period,tier) "Rate of adjustment ($/kWh and $/kW)"; set weekday_schedule(supply,product,month,hour,period); set weekend_schedule(supply,product,month,hour,period); ** Tariff definition parameter product_rate(supply,product,period,tier) / supply1.demand.period1.tier1 0 supply1.demand.period2.tier1 19.8 supply1.demand.period3.tier1 17 supply1.energy.period1.tier1 0.0584 supply1.energy.period2.tier1 0.0321 supply1.energy.period3.tier1 0.04 supply1.energy.period4.tier1 0.032 /; parameter product_adj(supply,product,period,tier) / supply1.demand.period1.tier1 0 supply1.demand.period2.tier1 0 supply1.demand.period3.tier1 0 supply1.energy.period1.tier1 0 supply1.energy.period2.tier1 0 supply1.energy.period3.tier1 0 supply1.energy.period4.tier1 0 /; set weekend_schedule(supply,product,month,hour,period) / supply1.demand.m1.h1.period1 supply1.demand.m1.h2.period1 supply1.demand.m1.h3.period1 supply1.demand.m1.h4.period1 supply1.demand.m1.h5.period1 supply1.demand.m1.h6.period1 supply1.demand.m1.h7.period1 supply1.demand.m1.h8.period1 supply1.demand.m1.h9.period1 supply1.demand.m1.h10.period1 supply1.demand.m1.h11.period1 supply1.demand.m1.h12.period1 supply1.demand.m1.h13.period1 supply1.demand.m1.h14.period1 supply1.demand.m1.h15.period1 supply1.demand.m1.h16.period1 supply1.demand.m1.h17.period1 * etc... /; ``` ## Writer Dataframe to CSV This writes pandas dataframes to csv in ways that GAMS can easily digest. SHORT PARAGRAPH ON THIS FUNCTIONALITY HOW TO USE HERE #### EXAMPLES ## Grammar - The current grammar is focused on capturing all `GAMS` syntax as long as it is valid and less concerned about catching invalid syntax. - The current grammar is built to gather data related to symbol definitions. As such, other parts of the grammar may be not accurate. ### Difficulties - Gams operates on two passes through the input files. Compiler statements are done before execution and are used to directly include gams code into a parent file or add/remove specific statements. - Lark parses the gams file in one pass and is a somewhat hybrid of compiler/execution syntax. This leads to set values possibly containing only include statements, whereas `GAMS` would check to ensure these are actual set values at execution time as well. ### Gams Syntax [https://www.gams.com/latest/docs/UG_SetDefinition.html](https://www.gams.com/latest/docs/UG_SetDefinition.html) ### ISSUES The expression grammar doesn't obey order of operations for math. use this calculater as reference for parsing structure. [https://github.com/lark-parser/lark/blob/master/examples/calc.py](https://github.com/lark-parser/lark/blob/master/examples/calc.py) ## Tests The `test/gams` folder contains sample gams syntax that can be used to test a grammar file to ensure it captures `GAMS` fairly complex syntax. ``` make test make test FLAGS="--nocapture --nologcapture" ``` <file_sep>/test/transform/transform_add.py from gams_parser import GamsParser import logging logging.basicConfig(level=logging.DEBUG) logging.debug("TEst") def test_transform_real_shopmodel(): with open('./test/gams/inject-datagen.inc','r') as gen_file, \ open('./test/gams/inject-datademand.inc','r') as demand_file, \ open('./test/gams/inject-siteanalysis.gms','r') as main_file: gp_main = GamsParser(main_file) gp_gen = GamsParser(gen_file) gp_demand = GamsParser(demand_file) model_main = gp_main.transform() model_gen = gp_gen.transform() model_demand = gp_gen.transform() model = model_main + model_gen + model_demand print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s)<file_sep>/test/parse/parameter.py from gams_parser import GamsParser def test_parameter_basic(): with open('./test/gams/parameter-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_parameter_tuple(): with open('./test/gams/parameter-tuple.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/test/inject/inject-tariff.py from gams_parser import GamsParser import json import logging logging.basicConfig(level=logging.DEBUG) def test_inject_tariff(): gp = GamsParser('./test/gams/inject-tariff.gms') with open('./test/ao/scenario-context.json') as in_file, \ open('./test/ao/tariff.json') as tariff_file: data=json.load(in_file) tariff=json.load(tariff_file) print(tariff.keys()) print("Inject data") d_map={ "-LXKLG1sepBvV6cTX0EN":tariff } new_model,inject_map=gp.inject(context=data,data=d_map) print("Output") print(new_model) <file_sep>/test/parse/table.py from gams_parser import GamsParser def test_table_basic(): with open('./test/gams/table-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/test/parse/misc.py from gams_parser import GamsParser def test_misc_comments(): with open('./test/gams/misc-comments.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_misc_include(): with open('./test/gams/misc-include.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_misc_conditional(): with open('./test/gams/misc-conditional.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty())<file_sep>/gams_parser/util.py def get_path(obj,path): keys = path.split('.') for k in keys: try: obj = obj[k] except KeyError: return None return obj def set_path(obj,path,value): keys = path.split('.') for k in keys[:-1]: if k not in obj.keys(): obj[k] = {} obj = obj[k] obj[keys[-1]] = value<file_sep>/gams_parser/gams_writer.py import os import logging import csv logger = logging.getLogger('gams_writer') class GamsWriter(): def __init__(self,dump_folder): if not dump_folder: raise ValueError('Need a dump folder for GamsWriter') self.dump_folder=dump_folder def dump_set(self,name,df): path="{}/{}.csv".format(self.dump_folder,name) folder=os.path.dirname(path) if not os.path.exists(folder): os.makedirs(folder) try: df.to_csv(path,columns=[],header=False) logger.debug('DumpSet:{}, items:{}'.format(name,len(df))) return except AttributeError as e: logger.debug('Not a dataframe, try list') with open(path,'w') as out_file: out_writer = csv.writer(out_file, delimiter=' ', quotechar='"', quoting=csv.QUOTE_MINIMAL) for item in df: out_writer.writerow([item]) def dump_param(self,name,df,sep=",",ignore_zero=False,round_decimals=None,key=None,header=False): if key: try: df = df[key] except KeyError as e: logger.warning('Error dumping dataset {}, no key {}'.format(name,e)) df = pd.DataFrame() if round_decimals: df=df.round(round_decimals) path="{}/{}.csv".format(self.dump_folder,name) folder=os.path.dirname(path) if not os.path.exists(folder): os.makedirs(folder) if ignore_zero: logger.debug('Ignore zeros') df=df[df.notna()] df.to_csv(path,header=header,sep=sep) logger.debug('DumpParam:{}, items:{}'.format(name,len(df))) def dump_param_t(self,name,df,sep=",",ignore_zero=False,round_decimals=None,key=None): if key: try: df = df[key] except KeyError as e: logger.warning('Error dumping dataset {}, no key {}'.format(name,e)) df = pd.DataFrame() if round_decimals: df=df.round(round_decimals) path="{}/{}.csv".format(self.dump_folder,name) folder=os.path.dirname(path) if not os.path.exists(folder): os.makedirs(folder) if ignore_zero: logger.debug('Ignore zeros') df=df[df.notna()] df.to_csv(path,sep=sep) logger.debug('DumpParam:{}, items:{}'.format(name,len(df)))<file_sep>/test/parse/set.py from gams_parser import GamsParser def test_set_basic(): with open('./test/gams/set-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_alias(): with open('./test/gams/set-alias.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_indexed(): with open('./test/gams/set-indexed.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_ranged(): with open('./test/gams/set-ranged.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_multi(): with open('./test/gams/set-multi.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_include(): with open('./test/gams/set-include.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_set_tuple(): with open('./test/gams/set-tuple.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty())<file_sep>/test/parse/scalar.py from gams_parser import GamsParser def test_scalar_basic(): with open('./test/gams/scalar-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/gams_parser/tree_injector.py from lark import Transformer, Tree from .util import get_path import logging import re import json class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self logger = logging.getLogger('gams_parser.injector') logger.setLevel('DEBUG') def get_id(item): ao_item=None item_name=None item_id=None if isinstance(item,str): logger.debug('Getting id from string') item_name=item item_id=item elif item and 'id' in item: logger.debug('Getting id from item') ao_item = item elif item and 'item' in item and 'id' in item['item']: logger.debug('Getting id from nested item ref') ao_item=item['item'] else: raise Exception("Unknown id format") if ao_item: item_id=ao_item['id'] # Try to get name name=get_path(ao_item,'parameter.name.name') # Attempt project name if not name: name=get_path(ao_item,'step.start.parameter.name.name') if name: item_name=name else: item_name=item_id item_name=item_name.replace(" ",'').replace("-","_") # Hopefully this removes everything but a-zA-Z_ item_name = re.sub( r"[^\w]", "", item_name ) # print("item_name",item_id,item_name) return item_id,item_name class TreeInjector(Transformer): def __init__(self,context,data=None): self._context=context self._data=data self._map=[] self._mapped=set() def _add_to_map(self,item_id=None,item_name=None,item=None): if not item_id: raise Exception("Need item id") if not item_name: raise Exception("Need item name") if item_id not in self._mapped: self._map.append({ "item_id": item_id, "item_name": item_name, "item": item }) self._mapped.add(item_id) def start(self,args): logger.debug("Start") return "".join(args),self._map def statement(self,args): #logger.debug('Statement') return "".join(args) def white_space(self,args): logger.debug("White space") return args[0].value def newline(self,args): return args[0].value def filter(self,args): logger.debug("Filter") def filter_fn(item): if args[1].data=='op_eq': return item[args[0]]==args[2] elif args[1].data=='op_sw': return item[args[0]].startswith(args[2]) else: raise Exception("Unknown operator") return filter_fn def project(self,args): logger.debug("Project") items=[self._context['project']] return items def data(self,args): logger.debug("Data") items=self._context['data'] return items def asset(self,args): logger.debug("Asset") items=self._context['asset'] if len(args)>0: items=[i for i in items if args[0](i)] return items def item_exp(self,args): logger.debug("Item Expr") items=args[0] # If Children, filter if len(args)>1: filter_fn=args[1] items=[i for i in items if filter_fn(i)] return items def cmd_jsondata(self,args): logger.debug("cmd JsonData") data_selector=args[0] out_items=[] data_item=None data_by_col=None if data_selector.data=='data_by_key': key="".join(data_selector.children) data = self._data[key] elif data_selector.data=='data_by_group': group="".join(data_selector.children) data_items=[d for d in self._context['data'] if d['groupKey']==group] if len(data_items)>1: raise Exception("Only support single data selectors for now") data_item=data_items[0] data_id,data_name=get_id(data_item) data=self._data[data_id] out_items.append('\t{}'.format(data_name)) else: raise Exception("Data selector not supported") columns=[] for a in args[1:]: for c in a.children: columns.append(c) for r in range(len(data)): row_template="".join(columns) row_data=AttrDict(data[r]) if data_item: data_by_col = [data[r][c['prop']] for c in data_item['item']['columns']] row_str=row_template.format(_index=r,_index_p1=r+1,row=row_data,col=data_by_col) out_items.append(row_str) return "\n".join(out_items) def cmd_param(self,args): logger.debug("cmd Param") items=args[0] ## ASSUME SELECTORS selector=args[1] if len(selector.children)>1: raise Exception("Only one selector allowed") selector=selector.children[0].strip("'") out_items=[] for item in items: item_id,item_name=get_id(item) self._add_to_map(item_id=item_id,item_name=item_name,item=item) logger.debug("Item") logger.debug("Selector {}".format(selector)) if 'item' in item: value=get_path(item['item'],selector) else: value=get_path(item,selector) logger.debug("Value {}".format(value)) if not value: continue if isinstance(value,float) or isinstance(value,int): out_items.append(item_name+" "+str(value)) elif isinstance(value,dict): logger.debug("Value is a dictionary, nest values") for key in value: val=value[key] if isinstance(val,float) or isinstance(val,int): logger.debug("Adding {key}={val}".format(key=key,val=val)) out_items.append(item_name+'.'+key+" "+str(val)) elif isinstance(val,str): try: val=float(val) out_items.append(item_name+'.'+key+" "+str(val)) except ValueError as verr: logger.debug("Ignoring string {key}={val}".format(key=key,val=val)) else: logger.debug("Unknown {key}={val}".format(key=key,val=val)) if isinstance(value,str): raise Exception("Parameters can not be strings") logger.debug("Out items {}".format(len(out_items))) return "{command}{args}".format(command="\n".join(out_items),args="".join(args[2:])) def cmd_map(self,args): logger.debug("cmd Map") project=args[0] ## ASSSUME ONLY 1 PROJECT project_id,project_name=get_id(project[0]) self._add_to_map(item_id=project_id,item_name=project_name,item=project[0]) items=args[1] out_items=[] if isinstance(items,Tree) and items.data=='selector': out_items.append(project_name+"."+"".join(items.children)) else: for item in items: item_id,item_name=get_id(item) self._add_to_map(item_id=item_id,item_name=item_name,item=item) out_items.append(project_name+'.'+item_name) logger.debug("Out items {}".format(len(out_items))) if len(out_items)>0: return "{command}{args}".format(command="\n".join(out_items),args="".join(args[2:])) else: return "" def cmd_list(self,args): logger.debug("cmd List") items=args[0] out_items=[] for item in items: item_id,item_name=get_id(item) self._add_to_map(item_id=item_id,item_name=item_name,item=item) out_items.append(item_name) if len(out_items)>0: return "{command}{args}".format(command=", ".join(out_items),args="".join(args[1:])) else: return "" def cmd_tariff(self,args): logger.debug('cmd Tariff') tariff_type=args[0].data out_items=[] # print("context",self._context['data']) supply_data=[d for d in self._context['data'] if d['groupKey']=='tourate'] for supply in supply_data: supply_id,supply_name=get_id(supply) supply_data=self._data[supply_id] self._add_to_map(item_id=supply_id,item_name=supply_name,item=supply) if tariff_type.startswith("tariff_sched"): if tariff_type=='tariff_sched_weekend': schedule_type_key="Weekend" # print('there') elif tariff_type=='tariff_sched_weekday': schedule_type_key='Weekday' else: raise Exception("Dont understand tariff sched param") logger.debug("Generating Tariff Sched") for product in ['demand','energy']: schedule_key="{product}{type}Sched".format(product=product,type=schedule_type_key) schedule=supply_data[schedule_key] for month in range(len(schedule)): month_key="m{}".format(month+1) for hour in range(len(schedule[month])): hour_key="h{}".format(hour+1) period_key="period{}".format(schedule[month][hour]+1) map_item=".".join([supply_name,product,month_key,hour_key,period_key]) out_items.append(map_item) elif tariff_type.startswith("tariff_rate"): if tariff_type=='tariff_rate': value_key='rate' elif tariff_type=='tariff_rate_adj': value_key='adj' else: raise Exception("Dont understand tariff rate param") logger.debug("Generating Tariff Rate") for product in ['demand','energy']: data=supply_data[product+'RateStrux'] for period in range(len(data)): period_key='period{}'.format(str(period+1)) tier_name='{}RateTiers'.format(product) for tier in range(len(data[period][tier_name])): tier_key='tier{}'.format(str(tier+1)) key=".".join([supply_name,product,period_key,tier_key]) if value_key in data[period][tier_name][tier]: value=data[period][tier_name][tier][value_key] out_items.append("{} {}".format(key,value)) else: raise Exception("Only know about 2 tariff types") return "\n".join(out_items) def ao_macro(self,args): logger.debug("AO Macro - Inject Info") args = [a for a in args if a != ''] if len(args)==1 and args[0].type=="NL": # Empty macro logger.debug("Empty macro") return "" else: return "".join(args) #return "<-- AO {} - {} -->".format(command,", ".join(out_items)) <file_sep>/test/parse/real.py from gams_parser import GamsParser def test_real_shopmodel(): with open('./test/gams/real-shopmodel.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_real_eminit(): with open('./test/gams/real-eminit.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_real_siteanalysis(): with open('./test/gams/real-siteanalysis.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/gams_parser/tree_to_model.py from lark import Transformer, Tree, Token, v_args from lark.tree import Meta import json import logging logger = logging.getLogger('gams_parser.model') @v_args(meta=True) class TreeToModel(Transformer): def string(self,args,meta): return "".join(args) def value(self,args,meta): return float(args[0]) def symbol_name(self,children,meta): if len(children)>1: raise Exception("Only a single identifier allowed for name") logger.debug('Create symbol name={}'.format(children[0])) return SymbolName('symbol_name',children,meta=meta) def definition(self,children,meta): return Definition(children,meta) def model_definition(self,children,meta): return ModelDefinition('model_definition',children,meta) def solve_definition(self,children,meta): return SolveDefinition('solve_definition',children,meta) def assignment_definition(self,children,meta): return AssignmentDefinition('assignment_definition',children,meta) def index_list(self,chilren,meta): logger.debug("IndexList {}".format(chilren)) return IndexList('index_list',chilren,meta) def set_list(self,args,meta): for set_def in args: set_def.symbol_type='set' return args def parameter_list(self,args,meta): for set_def in args: set_def.symbol_type='parameter' return args def variable_list(self,args,meta): for set_def in args: set_def.symbol_type='variable' return args def scalar_list(self,args,meta): for set_def in args: set_def.symbol_type='scalar' return args def equation_list(self,args,meta): for set_def in args: set_def.symbol_type='equation' return args def table_list(self,args,meta): for set_def in args: set_def.symbol_type='table' return args def variable_list(self,args,meta): for set_def in args: set_def.symbol_type='variable' return args def start(self,children,meta): model = Model() logger.debug("Process Statements") for statement in children: try: logger.debug("Processing new statement.") if isinstance(statement,Tree) and statement.data=='equation_definition': logger.debug('Have equation defintion') model.add_equation(statement) elif isinstance(statement,Tree) and statement.data=='model_definition': logger.debug('Have model definition') model.add_model(statement) elif isinstance(statement,Tree) and statement.data=='solve_definition': logger.debug('Have solve statement') model.add_solve(statement) elif isinstance(statement,Tree) and statement.data=='assignment_definition': logger.debug('Have assignment statement') model.add_assignment(statement) elif isinstance(statement,list): logger.debug('Have symbol list') for symbol_def in statement: model.add_symbol(symbol_def) else: logger.debug('Unknown statement') logger.debug("Statement data",statement.data) raise Exception("Statement type not handled") logger.debug("Finished statement.") except Exception as e: logger.error("Statement not processed, error: {}".format(e)) return model class Description(): pass class EquationDefinition(): pass class ModelDefinition(Tree): def __init__(self,data,children,meta=None): self.name=children[0] self.equations=children[1:] Tree.__init__(self,data,children,meta=meta) def __repr__(self): return "<model={} eqn={}>".format(self.name,",".join([str(e) for e in self.equations])) class SolveDefinition(Tree): def __init__(self,data,children,meta=None): self.name=children[0] for c in children: if isinstance(c,Tree) and c.data == 'sense_min': self.sense='min' elif isinstance(c,Tree) and c.data == 'sense_max': self.sense='max' elif isinstance(c,SymbolName): self.obj=c else: logger.warning("Solve definition, dont recognize child") Tree.__init__(self,data,children,meta=meta) def __repr__(self): return "-> solve model={name} {sense} {obj}".format(name=self.name,sense=self.sense,obj=self.obj) class AssignmentDefinition(Tree): def __init__(self,data,children,meta=None): self.symbol_refs=[] refs=set() for s in children: if isinstance(s,SymbolName): refs.add(s.name) elif isinstance(s,Tree): for s in s.find_data('symbol_name'): refs.add(s.name) self.symbol_refs=list(refs) Tree.__init__(self,data,children,meta=meta) def __repr__(self): return "<assignment n_symbols={num}>".format(num=len(self.symbol_refs)) class SymbolName(Tree): def __init__(self,data,children,meta=None): self.name=children[0] Tree.__init__(self,data,children,meta=meta) def __str__(self): return self.name def __repr__(self): return "__{name}__".format(name=self.name) class IndexList(Tree): def items(self): return [s.name for s in self.children] def __repr__(self): return "({items})".format(items=",".join([str(c) for c in self.children])) class Model(object): symbols={} def __init__(self): self.symbols={ "set": [], "parameter": [], "variable": [], "equation": [], "scalar": [], "table": [] } self.equation_defs=[] self.assignments=[] self.model_defs=[] self.solve=[] def __add__(self,other): model = Model() for s in self.symbols: model.symbols[s]=self.symbols[s]+other.symbols[s] model.equation_defs=self.equation_defs+other.equation_defs model.assignments=self.assignments+other.assignments model.model_defs=self.model_defs+other.model_defs model.solve=self.solve+other.solve return model def add_equation(self,e): eqn_def=EquationDefinition() eqn_def.symbol=Symbol(e.children[0]) eqn_def.meta=e.meta eqn_def.symbol_ref=[] for s in e.find_data('symbol_name'): logger.debug('Found symbol ref: {}'.format(s)) eqn_def.symbol_ref.append(s) self.equation_defs.append(eqn_def) def add_assignment(self,a): self.assignments.append(a) def add_model(self,m): self.model_defs.append(m) def add_solve(self,s): self.solve.append(s) def add_symbol(self,e): if not e.symbol_type: raise Exception('Symbol does not have a type!') elif e.symbol_type not in self.symbols: raise Exception('Symbol type not found') self.symbols[e.symbol_type].append(e) logger.info("Symbol[{type}]={name} added to model".format(name=e.symbol.name,type=e.symbol_type)) def set(self): return self.symbols['set'] def parameter(self): return self.symbols['parameter'] def equation(self): return self.symbols['equation'] def variable(self): return self.symbols['variable'] def scalar(self): return self.symbols['scalar'] def symbol(self): for i in self.symbols: for j in self.symbols[i]: yield j def cross_reference(self): logger.debug("CrossREFERENCEing") for i in self.symbols['equation']: for j in self.equation_defs: if i.symbol==j.symbol: logger.debug('CR Match') i.equation=j i.symbol_ref=j.symbol_ref def reference_lines(self,text): lines=text.splitlines() for s in self.symbol(): logger.debug("Reference line for symbol {}".format(s)) line=s.meta.line-1 end_line=s.meta.end_line text=["\n".join(lines[line:end_line])] if s.equation: text.insert(0,"*** Symbol Definition ***\n\n") text.append("\n\n*** Equation Definition ***\n\n") line=s.equation.meta.line-1 end_line=s.equation.meta.end_line text.append("\n".join(lines[line:end_line])) s.text="".join(text) for a in self.assignments: logger.debug("Reference line for assignment {}".format(a)) line=a.meta.line-1 end_line=a.meta.end_line text=["\n".join(lines[line:end_line])] a.text="".join(text) def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) def toDict(self): return json.loads(self.toJSON()) def __repr__(self): output=["** model **","\nsymbols:"] for i in self.symbols: if len(self.symbols[i])>0: output.append("n_{name}={num}".format(name=i,num=len(self.symbols[i]))) if len(self.assignments)>0: output.append("\nn_assignments={num}".format(num=len(self.assignments))) for m in self.model_defs: output.append("\n{}".format(m)) for s in self.solve: output.append("\n{}".format(s)) output.append("\n** end model **") return " ".join(output) class Data(): def __init__(self,args): logger.debug("BUILD Data {}".format(args)) self.data=args def __repr__(self): return "<data block len={length}>".format(length=len(self.data)) class Definition(): symbol_type=None symbol=None description=None data=None equation=None symbol_ref=[] def __init__(self,args,meta): #logger.debug("Build Definition: {}".format(args)) self._meta=meta for a in args: if isinstance(a,Tree) and a.data=='symbol': self.symbol=Symbol(a) self.meta.line=a.meta.line self.meta.end_line=a.meta.end_line self.meta.empty=False elif isinstance(a,Tree) and a.data=="description": self.description="".join(a.children).strip("'") self.meta.end_line=a.end_line elif isinstance(a,Tree) and a.data=="data": self.data=a self.meta.end_line=a.end_line @property def meta(self): if self._meta is None: self._meta = Meta() return self._meta def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) def __repr__(self): output=[] if self.symbol_type: output.append('[{}]'.format(self.symbol_type)) output.append('{}'.format(self.symbol)) if self.description: output.append('"{}"'.format(self.description)) if self.data: output.append('{}'.format(self.data)) return " ".join(output) ## This should have index list class Symbol(): symbol_name=None index_list=None def __init__(self,tree): if tree.data != 'symbol': raise Exception("Not a symbol def") info=tree.children self.name=info[0].name logger.debug("Creating Symbol: {}".format(self.name)) if len(info)>1: self.index_list=info[1].items() def __eq__(self,other): return self.name == other.name def __repr__(self): if self.index_list: return '__{symbol_name}{index_list}__'.format(symbol_name=self.name,index_list=self.index_list) else: return '__{symbol_name}__'.format(symbol_name=self.name) class SymbolId(): def __init__(self,sid): logger.debug("Creating Symbol ID {}".format(sid)) self.sid=str(sid) def __str__(self): return self.sid def __repr__(self): return '*{sid}*'.format(sid=self.sid) <file_sep>/test/inject/inject-data.py from gams_parser import GamsParser import json import pprint import logging logging.basicConfig(level=logging.DEBUG) def test_inject_data_gen(): gp = GamsParser('./test/gams/inject-datagen.inc') with open('./test/ao/scenario-context.json') as in_file, \ open('./test/ao/demand.json') as demand_file, \ open('./test/ao/nrel-sam-gen.json') as gen_file: data=json.load(in_file) demand=json.load(demand_file) gen=json.load(gen_file) print("Inject data") d_map={ "nrel-sam-gen": gen, "-LXKR3vVaHl1b3lDunJL": demand } new_model,inject_map=gp.inject(context=data,data=d_map) print("Output") #print(new_model) inject_simple=[{ "id": item['item_id'], "name": item['item_name'], "type": item['item']['type'], "rn": item['item']['rn'] } for item in inject_map] pprint.pprint(inject_simple) with open('tmp/output-gen.gms','w') as out_file: out_file.write(new_model) def test_inject_data_demand(): gp = GamsParser('./test/gams/inject-datademand.inc') with open('./test/ao/scenario-context.json') as in_file, \ open('./test/ao/demand.json') as demand_file, \ open('./test/ao/nrel-sam-gen.json') as gen_file: data=json.load(in_file) demand=json.load(demand_file) gen=json.load(gen_file) print("Inject data") d_map={ "nrel-sam-gen": gen, "-LXKR3vVaHl1b3lDunJL": demand } new_model,inject_map=gp.inject(context=data,data=d_map) print("Output") #print(new_model) inject_simple=[{ "id": item['item_id'], "name": item['item_name'], "type": item['item']['type'], "rn": item['item']['rn'] } for item in inject_map] pprint.pprint(inject_simple) with open('tmp/output-demand.gms','w') as out_file: out_file.write(new_model)<file_sep>/test/parse/assignment.py from gams_parser import GamsParser def test_assignment_basic(): with open('./test/gams/assignment-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_assignment_expansion(): with open('./test/gams/assignment-expansion.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_assignment_conditional(): with open('./test/gams/assignment-conditional.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_assignment_suffix(): with open('./test/gams/assignment-suffix.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/gams_parser/__init__.py from .gams_parser import * from .gams_writer import *<file_sep>/gdxpds/Dockerfile FROM andersonopt/ao-python ENV TASKPATH /var/task WORKDIR $TASKPATH # Copy dependencies COPY gams.exe /tmp/gams.exe # Install GAMS ENV GAMSFOLDER gams27.1_linux_x64_64_sfx ENV GAMSPATH ${TASKPATH}/${GAMSFOLDER} RUN chmod +x /tmp/gams.exe && /tmp/gams.exe && rm /tmp/gams.exe RUN ln -s $GAMSPATH gams # Setup python bindings RUN apt-get update && apt-get install -y python-dev WORKDIR ${GAMSPATH}/apifiles/Python/api_36 RUN python3 setup.py install ENV LD_LIBRARY_PATH ${GAMSPATH} WORKDIR $TASKPATH #Install gdxpds # Encoding error on install https://github.com/attilaolah/diffbot.py/issues/13 ENV LC_CTYPE C.UTF-8 RUN \ pip3 install gdxpds -t .pypath/ COPY gdx_to_csv.py /bin/gdx_to_csv.py COPY format.json $TASKPATH/format.json RUN chmod +x /bin/gdx_to_csv.py WORKDIR /root CMD ['gdx_to_csv.py'] <file_sep>/test/inject/inject-real.py from gams_parser import GamsParser import json import pprint import logging logging.basicConfig(level=logging.DEBUG) def test_inject_tariff(): gp = GamsParser('./test/gams/inject-siteanalysis.gms') with open('./test/ao/scenario-context.json') as in_file, \ open('./test/ao/demand.json') as demand_file, \ open('./test/ao/nrel-sam-gen.json') as gen_file, \ open('./test/ao/tariff.json') as tariff_file: data=json.load(in_file) demand=json.load(demand_file) gen=json.load(gen_file) tariff=json.load(tariff_file) print(tariff.keys()) print("Inject data") d_map={ "nrel-sam-gen": gen, "-LXKR3vVaHl1b3lDunJL": demand, "-LXKLG1sepBvV6cTX0EN":tariff } new_model,inject_map=gp.inject(context=data,data=d_map) print("Output") #print(new_model) inject_simple=[{ "id": item['item_id'], "name": item['item_name'], "type": item['item']['type'], "rn": item['item']['rn'] } for item in inject_map] pprint.pprint(inject_simple) with open('tmp/output-siteanalysis.gms','w') as out_file: out_file.write(new_model)<file_sep>/gdxpds/README.md # [GDX Pandas](https://github.com/NREL/gdx-pandas) Create docker image to use gdx to csv functionality Example usage ```bash docker run -w /root -v $(pwd):/root -u $(id -u):$(id -g) andersonopt/gdxpandas gdx_to_csv.py -i output.gdx -o output ``` ## References Great examples of sandboxing functionality in docker [https://github.com/jessfraz/dockerfiles](https://github.com/jessfraz/dockerfiles)<file_sep>/test/transform/transform_basic.py from gams_parser import GamsParser import logging logging.basicConfig(level=logging.DEBUG) logging.debug("TEst") def test_transform_multi_sets(): with open('./test/gams/set-multi.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_tuple_set(): with open('./test/gams/set-tuple.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_indexed_set(): with open('./test/gams/set-indexed.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_parameter(): with open('./test/gams/parameter-tuple.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_variable(): with open('./test/gams/variable-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) def test_transform_equation(): with open('./test/gams/equation-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) <file_sep>/test/parse/equation.py from gams_parser import GamsParser def test_equation_basic(): with open('./test/gams/equation-basic.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_equation_indexoperator(): with open('./test/gams/equation-indexoperator.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) def test_equation_elementindex(): with open('./test/gams/equation-elementindex.gms','r') as in_file: gp = GamsParser(in_file) parse_tree=gp.parse() print(parse_tree.pretty()) <file_sep>/test/inject/inject.py from gams_parser import GamsParser import json import logging logging.basicConfig(level=logging.DEBUG) def test_inject_list(): gp = GamsParser('./test/gams/inject-basic.gms') with open('./test/ao/scenario-context.json') as in_file: data=json.load(in_file) #print(data) print("Inject data") new_model,inject_map=gp.inject(context=data) print("Output") print(new_model) def test_inject_filtered(): gp = GamsParser('./test/gams/inject-filtered.gms') with open('./test/ao/scenario-context.json') as in_file: data=json.load(in_file) #print(data) print("Inject data") new_model,inject_map=gp.inject(context=data) print("Output") print(new_model) def test_inject_map(): gp = GamsParser('./test/gams/inject-map.gms') with open('./test/ao/scenario-context.json') as in_file: data=json.load(in_file) #print(data) print("Inject data") new_model,inject_map=gp.inject(context=data) print("Output") print(new_model) def test_inject_param(): gp = GamsParser('./test/gams/inject-param.gms') with open('./test/ao/scenario-context.json') as in_file: data=json.load(in_file) #print(data) print("Inject data") new_model,inject_map=gp.inject(context=data) print("Output") print(new_model) <file_sep>/test/transform/transform_dict.py from gams_parser import GamsParser, scrub_meta import json import pprint import logging logging.basicConfig(level=logging.DEBUG) def test_transform_def_dict(): with open('./test/gams/real-shopmodel.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) #print(s.toJSON()) def test_transform_model_json(): with open('./test/gams/real-shopmodel2.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) dm=model.toJSON() #print("\nmodel.toJSON\n") #print(dm) print("\nmodel.toDict Hack\n") m=model.toDict() scrub_meta(m) pprint.pprint(m['assignments']) def test_transform_model_siteanalysis(): with open('./test/gams/real-siteanalysis.gms','r') as in_file: gp = GamsParser(in_file) model=gp.transform() print("\nModel\n") print(model) print("\nSymbols:\n") for s in model.symbol(): print(s) dm=model.toJSON() #print("\nmodel.toJSON\n") #print(dm) print("\nmodel.toDict Hack\n") m=model.toDict() scrub_meta(m) pprint.pprint(m) <file_sep>/Dockerfile FROM andersonopt/task-ao WORKDIR /var/task COPY requirements.txt /var/task/requirements.txt RUN \ pip install -r requirements.txt -t .pypath/ ADD gams_parser /var/task/.pypath/gams_parser
b52732e4f54c9f04d10378b05e8cb4575a7c1122
[ "Markdown", "Makefile", "Python", "PHP", "Dockerfile" ]
31
Makefile
anderson-optimization/gams-parser
3786206a34d6a6ae08d9525965ddc21df0beefe1
759344ded12d45ec10115d3517f564855f506007
refs/heads/develop
<file_sep># Sinatra APP class MyApp < Sinatra::Base use Rack::PostBodyContentTypeParser register Sinatra::Namespace set :raise_errors, false register do def auth (type) condition do halt 401 unless send("is_#{type}?") end end end helpers do def is_admin? # Verify if the request content is an authenticable Admin false end def is_client? # Verify if the request content is an authenticable Client true end end error do json error: env['sinatra.error'].class, error_message: env['sinatra.error'].message end namespace '/v1' do include Controllers::V1::Root namespace '/admin', auth: :admin do include Controllers::V1::Admin end namespace '/client', auth: :client do include Controllers::V1::Client end end end <file_sep>ENV['RACK_ENV'] ||= 'development' require 'bundler' Bundler.require(:default, ENV['RACK_ENV']) require 'sinatra/base' require 'sinatra/namespace' require 'sinatra/json' require 'active_support/concern' require 'active_support/core_ext/time' require 'active_support/core_ext/string' Dotenv.load Dir['app/{**, **/**}/*.rb'].sort.each {|file| require File.expand_path(file) } Dir['config/initializers/{**, **/**}/*.rb'].sort.each {|file| require File.expand_path(file) } require './app' <file_sep>ENV['RACK_ENV'] = 'test' require 'simplecov' SimpleCov.start require File.expand_path '../../boot.rb', __FILE__ module RSpecMixin def app() MyApp end end Airborne.configure do |config| config.rack_app = MyApp end RSpec.configure do |config| config.include RSpecMixin config.order = :random end <file_sep>require File.expand_path '../../spec_helper.rb', __FILE__ describe 'MyApp' do it 'allow access to the root URL' do get '/v1/' expect(response.status).to eq 200 expect_json(message: 'API v1!') end end <file_sep>require File.join(File.expand_path(File.dirname(__FILE__)), 'boot.rb') run MyApp.new <file_sep># Sinatra Template ## Running the project You can run the project using `rackup` for better perfomance or `shotgun` to reload application in every request: ``` $ rackup config.ru -p 9292 $ shotgun config.ru -p 9292 ``` ## Interactive Console In the app `current` folder do: ``` RACK_ENV=production /home/gustavosobral/.rvm/bin/rvm 2.7.0 do bundle exec irb -I. -r boot.rb ``` <file_sep>module Controllers module V1 module Admin extend ActiveSupport::Concern included do get '/' do json message: 'Admin API v1!' end end end end end <file_sep>module Controllers module V1 module Root extend ActiveSupport::Concern included do get '/' do json message: 'API v1!' end end end end end <file_sep>Dir.glob('lib/tasks/*.rake').each { |r| load r} task :environment do require File.join(File.expand_path(File.dirname(__FILE__)), 'boot.rb') end <file_sep>source 'https://rubygems.org' ruby '2.7.0' gem 'activesupport' gem 'dotenv' gem 'puma' gem 'rack-contrib' gem 'rake' gem 'sinatra' gem 'sinatra-contrib' group :development, :test do gem 'pry' gem 'pry-byebug' end group :development do gem 'shotgun' end group :test do gem 'airborne' gem 'rspec' gem 'simplecov', require: false end
1b2aa07ea868e3627c24cd25a47c7009be03c27e
[ "Markdown", "Ruby" ]
10
Ruby
gustavosobral/sinatra_template
a20f826ea1e8a7fa1a48ef192616ae6b827dbf0d
8d7e15660e2a48936ce5f2c2b3e042c071565e9d
refs/heads/master
<file_sep>import React from 'react' import PropTypes from 'prop-types' import { hot } from 'react-hot-loader' import { connect } from 'redux-bundler-react' import { Main } from '@components/main/styled' import NYTimesLogo from '@components/nyt-logo' import PreviewArticleDrawer from '@components/preview-article-drawer' import 'antd/dist/antd.css' const AppRoot = ({ route }) => { const Page = route return ( <> <NYTimesLogo /> <Main> <Page /> </Main> <PreviewArticleDrawer /> </> ) } AppRoot.propTypes = { route: PropTypes.func.isRequired, } export default hot(module)( connect( 'selectRoute', AppRoot, ), ) <file_sep>import React from 'react' import PropTypes from 'prop-types' import { connect } from 'redux-bundler-react' import navHelper from 'internal-nav-helper' import { Search, Wrapper } from './styled' const SearchField = ({ doFetchNews, doUpdateUrl }) => { function handleSubmit(val) { doFetchNews(val, () => { navHelper(doUpdateUrl('/news')) }) } return ( <Wrapper> <Search placeholder="input search text" enterButton="Search" size="large" onSearch={(val) => handleSubmit(val)} /> </Wrapper> ) } SearchField.propTypes = { doFetchNews: PropTypes.func.isRequired, doUpdateUrl: PropTypes.func.isRequired, } export default connect( 'doFetchNews', 'doUpdateUrl', SearchField, ) <file_sep>import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { initialData } from '@tests/initial-data' import NewsItem from '@components/news-item' storiesOf('NewsItem', module) .add('with text', () => ( <div style={{ padding: '20px' }}> <div className="ant-list-vertical ant-list-lg ant-list-split ant-list-something-after-last-item"> <NewsItem item={ initialData.news.data[0] } /> </div> </div> )) <file_sep>import React from 'react' import styled from 'styled-components' import SearchField from '@components/search-field' const Heading = styled.h2` font-family: 'Noto Serif KR', sans-serif; color: #000; text-align: center; width: 100%; ` export default () => ( <> <Heading>What news are you looking for ?</Heading> <SearchField /> </> ) <file_sep>import { composeBundles, createCacheBundle } from 'redux-bundler' import routes from '@bundles/routes' import news from '@bundles/news' import redirects from '@bundles/redirects' import cache from '@common/utils/cache' import extraArgs from '@bundles/extra-args' export default composeBundles( routes, news, redirects, createCacheBundle(cache.set), extraArgs, ) <file_sep>export const initialData = { news: { article: { _id: "5ba46d04068401528a2dc251", snippet: "In the hit movie “Crazy Rich Asians,” the country looks luxe. But it’s easy to have a great time (and eat memorably well) without spending much.", multimedia: [ { subtype: "jumbo", url: "images/2018/09/23/travel/23singapore1/merlin_142944708_9276e9dd-b36e-40f3-90f6-34e79e64552e-jumbo.jpg" } ], pub_date: "2018-09-21T04:01:06+0000", source: "The New York Times", web_url: "https://www.nytimes.com/2018/09/21/travel/singapore-travel-budget.html", headline: { main: "Singapore, for Those Who Aren’t Crazy Rich", print_headline: "Singapore, if You’re Not Crazy Rich" } }, data: [ { _id: "5ba46d04068401528a2dc251", snippet: "In the hit movie “Crazy Rich Asians,” the country looks luxe. But it’s easy to have a great time (and eat memorably well) without spending much.", multimedia: [ { subtype: "tumbnail", url: "images/2018/09/23/travel/23singapore1/merlin_142944708_9276e9dd-b36e-40f3-90f6-34e79e64552e-articleLarge.jpg" }, ], pub_date: "2018-09-21T04:01:06+0000", source: "The New York Times", web_url: "https://www.nytimes.com/2018/09/21/travel/singapore-travel-budget.html", headline: { main: "Singapore, for Those Who Aren’t Crazy Rich", print_headline: "Singapore, if You’re Not Crazy Rich" }, }, ], drawer: false, lastError: null, lastFetch: null, loading: false, meta: { hits: 36208, offset: 0, time: 23 }, query: 'singapore', } } <file_sep>import React from 'react' import { render } from 'react-testing-library' import { Provider } from 'redux-bundler-react' import getStore from '@bundles' import { initialData } from '@tests/initial-data' const customRender = (node, ...options) => { const [{ context } = {}] = options return render( <Provider store={getStore(context || initialData)}> {node} </Provider>, ...options, ) } // re-export everything export * from 'react-testing-library' // override render method export {customRender as render} <file_sep>export function sel(id) { return `[aria-label="${id}"]` } <file_sep>import React from 'react' import PropTypes from 'prop-types' import { connect } from 'redux-bundler-react' import Moment from 'moment' import { Drawer, Row, Col, Divider } from 'antd' import { Headline, ArticleMedia, Snippet, Source, Date } from './styled' const PreviewArticleDrawer = ({ previewArticleContent, drawer, doCloseDrawer, }) => { let headline, media, snippet, source, date if (previewArticleContent) { headline = previewArticleContent.headline.main || null media = previewArticleContent.multimedia.length > 0 && previewArticleContent.multimedia.find( (media) => media.subtype === 'jumbo', ) !== undefined ? `https://graphics8.nytimes.com/${ previewArticleContent.multimedia.find( (media) => media.subtype === 'jumbo', ).url }` : null snippet = previewArticleContent.snippet || null source = previewArticleContent.source || null date = previewArticleContent.pub_date || null } return ( <Drawer width={window.innerWidth < 400 ? '100%' : '50%'} placement="right" closable={true} onClose={() => doCloseDrawer()} visible={drawer} extra={"data-testid='drawer'"} > {previewArticleContent ? <> <Headline>{headline}</Headline> <Divider /> <Source>{source}</Source> <Date>{Moment(date).format('ll')}</Date> {media && <ArticleMedia src={media} />} <Row> <Col span={24}> <Snippet>{snippet}</Snippet> </Col> </Row> </> : null} </Drawer> ) } PreviewArticleDrawer.propTypes = { previewArticleContent: PropTypes.object, drawer: PropTypes.bool, doCloseDrawer: PropTypes.func.isRequired, } export default connect( 'selectPreviewArticleContent', 'selectDrawer', 'doCloseDrawer', PreviewArticleDrawer, ) <file_sep>import { createRouteBundle } from 'redux-bundler' import HomePage from '@screens/home' import NewsPage from '@screens/news' export default createRouteBundle({ '/': HomePage, '/news': NewsPage, }) <file_sep>import React from 'react' import PropTypes from 'prop-types' import Moment from 'moment' import { Item, Meta, Avatar, Date, Source, Title } from './styled' const NewsItem = ({ item: { _id, snippet, multimedia, pub_date, source, web_url, headline, }, doPreviewArticle, }) => { const thumb = multimedia.length > 0 && multimedia.find((item) => item.subtype === 'thumbnail') !== undefined ? `https://graphics8.nytimes.com/${ multimedia.find((item) => item.subtype === 'thumbnail').url }` : 'https://www.randjsc.com/wp-content/uploads/2015/05/NYT-logo-square-150x150.jpg' return ( <Item key={_id} extra={<img width={75} alt="logo" src={thumb} />}> <Source>{source}</Source> <Meta avatar={<Avatar src={thumb} />} title={ <Title href={web_url} onClick={(e) => doPreviewArticle(e, _id)}> {headline.main} </Title> } description={snippet} /> <Date>{Moment(pub_date).fromNow()}</Date> </Item> ) } NewsItem.propTypes = { item: PropTypes.object.isRequired, doPreviewArticle: PropTypes.func, } export default NewsItem <file_sep>// import { mount, shallow, render } from 'enzyme' import 'react-testing-library/cleanup-after-each' import 'jest-dom/extend-expect' import 'jest-styled-components' // global.shallow = shallow // global.render = render // global.mount = mount const localStorageMock = { getItem: jest.fn(), setItem: jest.fn(), clear: jest.fn(), } global.localStorage = localStorageMock <file_sep>const path = require('path') module.exports = (baseConfig, env, defaultConfig) => { baseConfig.devtool = 'sourcemap' defaultConfig.resolve.alias['@components'] = path.resolve(__dirname, '../src/components') defaultConfig.resolve.alias['@bundles'] = path.resolve(__dirname, '../src/bundles') defaultConfig.resolve.alias['@common'] = path.resolve(__dirname, '../src/common') defaultConfig.resolve.alias['@screens'] = path.resolve(__dirname, '../src/screens') defaultConfig.resolve.alias['@tests'] = path.resolve(__dirname, '../src/tests') return defaultConfig } <file_sep>import styled from 'styled-components' import { Input as AntInput } from 'antd' const Search = styled(AntInput.Search)` display: block; ` const Wrapper = styled.div` margin: 0 auto; width: 50%; @media (max-width: 600px) { width: 100%; } ` export { Search, Wrapper } <file_sep>import getStore from '@bundles' import { initialData } from './initial-data' export const store = getStore(initialData) <file_sep>import { createSelector } from 'redux-bundler' export default { name: 'news', getReducer: () => { const initialState = { loading: false, drawer: false, lastError: null, lastFetch: null, query: null, meta: null, data: null, article: null, } return (state = initialState, { type, payload }) => { if (type === 'FETCH_NEWS_START') { return Object.assign({}, state, { loading: true, query: payload, }) } if (type === 'FETCH_NEWS_ERROR') { return Object.assign({}, state, { lastError: Date.now(), loading: false, }) } if (type === 'FETCH_NEWS_SUCCESS') { return Object.assign({}, state, { lastFetch: Date.now(), loading: false, lastError: null, data: payload.response.docs, meta: payload.response.meta, }) } if (type === 'OPEN_PREVIEW_ARTICLE_DRAWER') { return Object.assign({}, state, { drawer: true, article: payload, }) } if (type === 'CLOSE_PREVIEW_ARTICLE_DRAWER') { return Object.assign({}, state, { drawer: false, }) } return state } }, doFetchNews: (query, callback, page = 0) => ({ dispatch, apiNYT }) => { dispatch({ type: 'FETCH_NEWS_START', payload: query }) apiNYT('/', query, page) .then((payload) => { dispatch({ type: 'FETCH_NEWS_SUCCESS', payload, }) callback && callback() }) .catch((err) => { dispatch({ type: 'FETCH_NEWS_ERROR', err }) }) }, doPreviewArticle: (e, id) => ({ dispatch, getState }) => { e.preventDefault() dispatch({ type: 'OPEN_PREVIEW_ARTICLE_DRAWER', payload: getState().news.data.find((article) => article._id === id), }) }, doCloseDrawer: () => ({ dispatch }) => { dispatch({ type: 'CLOSE_PREVIEW_ARTICLE_DRAWER' }) }, // selector for the whole contents of the reducer // including metadata about fetches selectNewsRaw: (state) => state.news, // selector for just the actual data if we have it selectNews: (state) => state.news.data, selectMeta: (state) => state.news.meta, selectQuery: (state) => state.news.query, selectLoading: (state) => state.news.loading, selectDrawer: (state) => state.news.drawer, selectPreviewArticleContent: (state) => state.news.article, // we'll extract a status string here, for display, just to show // the type of information available about the data selectNewsFetchStatus: createSelector('selectNewsRaw', (news) => { const { data, lastError, lastFetch, loading } = news let result = '' if (data) { result += 'Has data' } else { result += 'Does not have data' } if (loading) { return result + ' and is fetching currently' } if (lastError) { return ( result + ` but had an error at ${lastError} and will retry after ~30 seconds` ) } if (lastFetch) { return ( result + ` that was fetched at ${lastFetch} but will be updated a minute later` ) } }), reactShouldFetchNews: createSelector( // this is the selector we defined above, note that we can // just reference it by it's string name, but we could have // also assigned the function to a variable and passed that // function directly here instead. 'selectNewsRaw', // this is one of the selectors that is made available by // one of the included bundles called 'appTime' this bundle // timestamps all actions and we also run an "app idle" // dispatch every 30 seconds if there have been no actions // dispatched and using requestAnimationFrame, this will // only happen if the tab is visible. // All this to say, we have a self-updating timestamp in our // redux state that we can use to see how long it's been. 'selectAppTime', (news, appTime) => { // never trigger another fetch if we're already fetching if (news.loading) { return null } // for readability in this example I'm going to break out // and comment on the various conditions here. In reality // you'd likely want to write an abstraction that lets you describe // all this at a higher level. One such, abstraction is // included in the "/bundles" dir of the redux-bundler repo let shouldFetch = false // if we don't have data at all we definitely want to fetch if (!news.data) { shouldFetch = true } // was there an error last time we tried to fetch? // if it's been 15 seconds, give it another go... else if (news.lastError) { const timePassed = appTime - news.lastError if (timePassed > 15000) { shouldFetch = true } } // maybe our data is just stale? // I've made this arbitrarily short at just 1 minute // so you can see it working. // Note that we don't wipe out existing data if we have // it. else if (news.lastFetch) { const timePassed = appTime - news.lastfetch if (timePassed > 60000) { shouldFetch = true } } // here we can either return an actual action object to dispatch // by using `{type: 'SOME_ACTION'}` or we can just specify the // name of the action creator function we want to run, and optionally // any args we want to pass to it. if (shouldFetch) { return { actionCreator: 'doFetchNews' } } }, ), persistActions: ['FETCH_NEWS_SUCCESS'], } <file_sep>const HtmlWebPackPlugin = require('html-webpack-plugin'); const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin'); const WebpackPwaManifest = require('webpack-pwa-manifest'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const webpack = require('webpack'); const path = require('path'); module.exports = { entry: { main: ['@babel/polyfill', path.resolve(__dirname, 'src/index.js')], }, output: { filename: '[name].[hash].js', path: path.resolve(__dirname, 'dist'), }, devServer: { open: true, historyApiFallback: true, port: 5050, watchOptions: { aggregateTimeout: 300, poll: 1000 }, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS', 'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization', }, }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\.html$/, use: [ { loader: 'html-loader', options: { minimize: true }, }, ], }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ], }, resolve: { alias: { '@bundles': path.resolve(__dirname, 'src/bundles'), '@components': path.resolve(__dirname, 'src/components'), '@containers': path.resolve(__dirname, 'src/containers'), '@common': path.resolve(__dirname, 'src/common'), '@screens': path.resolve(__dirname, 'src/screens'), }, }, optimization: { nodeEnv: JSON.stringify(process.env.NODE_ENV), minimize: JSON.stringify(process.env.NODE_ENV) === 'production', concatenateModules: JSON.stringify(process.env.NODE_ENV) === 'production', runtimeChunk: JSON.stringify(process.env.NODE_ENV) === 'production', minimizer: [ new UglifyJsPlugin({ uglifyOptions: { ecma: 8, compress: { warnings: false, // Disabled because of an issue with Uglify breaking seemingly valid code: // https://github.com/facebook/create-react-app/issues/2376 // Pending further investigation: // https://github.com/mishoo/UglifyJS2/issues/2011 comparisons: false, }, mangle: { safari10: true, reserved: ['BigInteger', 'ECPair', 'Point'], }, output: { comments: false, // Turned on because emoji and regex are not minified properly using default // https://github.com/facebook/create-react-app/issues/2488 ascii_only: true, }, }, parallel: true, cache: true, sourceMap: true, }), ], splitChunks: { chunks: 'all', minSize: 0, maxAsyncRequests: Infinity, maxInitialRequests: Infinity, name: false, cacheGroups: { vendors: { name: 'vendors', enforce: true, test: /[\\/]node_modules[\\/]/, priority: -10, reuseExistingChunk: true, }, commons: { name: 'commons', chunks: 'initial', minChunks: 2, test: /[\\/]src[\\/]/, priority: -5, reuseExistingChunk: true, }, }, }, }, plugins: [ new WebpackPwaManifest({ name: 'Blockstack React + Redux Bundler Starter', short_name: 'Blockstack Starter', description: 'A starter repo for building Blockstack apps with React and Redux Bundler.', background_color: '#ffffff', filename: '[name][ext]', start_url: 'http://react-blockstack.now.sh/', fingerprints: false, inject: false, publicPath: 'http://react-blockstack.now.sh/', icons: [ { src: path.resolve('src/assets/app-icon.png'), sizes: [96, 128, 192, 256, 384, 512], }, ], }), new HtmlWebPackPlugin({ template: path.resolve(__dirname, 'public', 'index.html'), filename: path.resolve(__dirname, 'dist', 'index.html'), inlineSource: 'runtime~.+\\.js', }), new HtmlWebpackInlineSourcePlugin(), ], }; <file_sep>import styled from 'styled-components' import { List, Avatar as AntAvatar } from 'antd' const Item = styled(List.Item)` display: block; ` const Avatar = styled(AntAvatar)` display: block; ` const Meta = styled(List.Item.Meta)` display: block; ` const Date = styled.time` font-family: 'Helvetica', sans-serif; color: #ccc; font-weight: 100; font-size: 12px; ` const Source = styled.p` font-family: 'Libre Franklin', sans-serif; text-transform: uppercase; font-size: 10px; font-weight: 700; color: rgb(18, 18, 18); display: block; ` const Title = styled.a` font-family: 'Noto Serif KR', sans-serif; font-size: 16px; font-weight: bold; ` export { Item, Avatar, Meta, Date, Source, Title } <file_sep>import styled from 'styled-components' const Headline = styled.h2` font-family: 'Noto Serif KR', sans-serif; font-size: 28px; color: #000; @media (max-width: 600px) { font-size: 23px; } ` const ArticleMedia = styled.img` display: inline-block; background-color: #ececec; width: 100%; ` const Snippet = styled.p` font-size: 16px; color: #000; margin-top: 20px; ` const Source = styled.span` text-transform: uppercase; font-size: 12px; color: #ddd; display: inline-block; ` const Date = styled.time` font-family: 'Helvetica', sans-serif; font-weight: 500; font-size: 14px; display: inline-block; float: right; ` export { Headline, ArticleMedia, Snippet, Source, Date } <file_sep>import React from 'react' import { render } from '@tests/utils/render-with-app-context' import NYTimesLogo from '@components/nyt-logo' describe('<NYTimesLogo />', () => { const { container } = render(<NYTimesLogo />) test('should match snapshot', () => { expect(container).toMatchSnapshot() }) })
0ef755a06066732f68895488906c5e5bc7391648
[ "JavaScript" ]
20
JavaScript
gipsy/nyt-demo
0d5f013e0127ebdd97ea6f42af37a7d9e7d45e7f
8beecc8a3d162563e7306525b4dc66102d5f7dba
refs/heads/main
<repo_name>HyonheeYoo/eval-tool<file_sep>/public/preload.js const fs = require("fs/promises"); const path = require("path"); const util = require("util"); const exec = util.promisify(require("child_process").exec); const { contextBridge, ipcRenderer, shell } = require("electron"); const { v4: uuidv4 } = require("uuid"); const ffmpegUtils = require("./utils/ffmpeg"); const createCsvWriter = require("csv-writer").createObjectCsvWriter; const { parsePrediction, filterPrediction } = require("./utils/parser"); const { extract } = require("./utils/ffmpeg-helper"); const getWindowId = async () => { const windowId = await ipcRenderer.invoke("get-window-id", "app"); return windowId; }; const getPath = async (dirname) => { const pathname = await ipcRenderer.invoke("getPath", dirname); return pathname; }; const getWorkDir = async () => { const appDataPath = await ipcRenderer.invoke("getPath", "appData"); const appName = await ipcRenderer.invoke("getName"); const workDir = path.join(appDataPath, appName, "storage", uuidv4()); try { await fs.access(workDir); } catch { await fs.mkdir(workDir, { recursive: true }); } return workDir; }; const extractFrames = async (workDir, videoPath) => { const framesDir = path.join(workDir, "frames"); try { await fs.access(framesDir); } catch { await fs.mkdir(framesDir, { recursive: true }); } const copiedVideoPath = path.join(workDir, path.basename(videoPath)); try { await fs.access(copiedVideoPath); } catch (error) { await fs.copyFile(videoPath, copiedVideoPath); } await ffmpegUtils.extractFrames(videoPath, framesDir); }; const writeCsv = async (workDir, withModel, prediction) => { const csvPath = path.join(workDir, `${withModel}.csv`); const csvWriter = createCsvWriter({ path: csvPath, header: [ { id: "", title: "" }, { id: "predict", title: "predict" }, ], }); const records = prediction.map((predict, i) => ({ "": i, predict })); await csvWriter.writeRecords(records); return csvPath; }; const predict = async (workDir, videoName, withModel) => { const command = `docker run --rm -i -v ${path.join(__dirname, "oob")}:/OOB_RECOG -v ${path.dirname(workDir.replace(" ", ""))}:/OOB_RECOG/mount evaltool python test.py ${path.basename(workDir)} ${withModel}`; console.log(command); const { stdout } = await exec(command); if (stdout) { let prediction; try { prediction = JSON.parse(stdout); } catch (error) { prediction = JSON.parse(stdout.trim().split("\n").pop()); } finally { console.log(prediction); } const parsedPrediction = parsePrediction(prediction); const inBody = filterPrediction(parsedPrediction, true); const outOfBody = filterPrediction(parsedPrediction, false); const videoPath = path.join(workDir, videoName); const extractPromises = []; if (inBody.length > 0) { const inBodyVideoPath = path.resolve(videoPath, videoPath.replace(".mp4", `_in_body_${withModel}.mp4`)); extractPromises.push(extract(inBody, videoPath, inBodyVideoPath)); } if (outOfBody.length > 0) { const outOfBodyVideoPath = path.resolve(videoPath, videoPath.replace(".mp4", `_out_of_body_${withModel}.mp4`)); extractPromises.push(extract(outOfBody, videoPath, outOfBodyVideoPath)); } const extractResults = await Promise.allSettled(extractPromises); extractResults.forEach((result) => { if (result.status === "rejected") { console.log(result); } }); const csvPath = await writeCsv(workDir, withModel, prediction); return csvPath; } }; const evalPrediction = async (csvPath, gtPath) => { const copiedGtPath = path.join(path.dirname(csvPath), path.basename(gtPath)); try { await fs.access(copiedGtPath); } catch (error) { await fs.copyFile(gtPath, copiedGtPath); } const command = `docker run --rm -i -v ${path.join(__dirname, "oob")}:/OOB_RECOG -v ${path.dirname(csvPath.replace(" ", ""))}:/OOB_RECOG/mount evaltool python eval.py --model_output_csv_path ./mount/${path.basename(csvPath)} --gt_json_path ./mount/${path.basename(gtPath)} --save_dir_path ${path.dirname(csvPath).replace(" ", "")} --inference_step 5`; console.log(command); const { stdout } = await exec(command); if (stdout) { console.log(stdout); } }; const openPath = (path) => { shell.openPath(path); }; contextBridge.exposeInMainWorld("api", { getPath, getWorkDir, extractFrames, predict, evalPrediction, openPath, }); <file_sep>/public/utils/parser.js const parsePrediction = (prediction) => { const initialState = null; let state = initialState; let closed = false; const result = prediction.reduce((acc, curr, i) => { const isInBody = curr === 0; // code 0 means in body if (state === initialState) { state = { start: i, end: i, isInBody }; return acc; } if (state.isInBody === isInBody) { state = { ...state, end: i }; closed = false; return acc; } acc.push(state); state = { start: i, end: i, isInBody }; closed = true; return acc; }, []); if (!closed) { result.push({ ...state, end: prediction.length - 1 }); } return result; }; const filterPrediction = (parsedPrediction, isInBody) => { return parsedPrediction.filter( (el) => el.isInBody === isInBody && el.start !== el.end, ); }; module.exports = { parsePrediction, filterPrediction, }; <file_sep>/public/oob/test_dataset.py import os import glob import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms from PIL import Image from natsort import natsorted data_transforms = { 'test': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } IB_CLASS, OOB_CLASS = (0,1) class OOB_DB_Dataset(Dataset): def __init__(self, DB_path): self.img_list = glob.glob(os.path.join('./mount', DB_path, 'frames', '*.jpg')) # ALL img into DB path self.img_list = natsorted(self.img_list) # sorting self.aug = data_transforms['test'] def __len__(self): return len(self.img_list) def __getitem__(self, index): img_path = self.img_list[index] img = Image.open(img_path) img = self.aug(img) return {'img': img} # aug 형태의 img (tensor) # IT'S NOT UNIFORM SAMPLER # test => [0,5,10,15...] step size # gradcam => [0, 9, 11, 13 ...] # https://stackoverflow.com/questions/66065272/customizing-the-batch-with-specific-elements # Dataloader(OOB_DB_Dataset, batch_sampler=[[0,1,2], [3,4,5], [6,7], [8,9]]) class IDX_Sampler(): def __init__(self, idx_list, batch_size): self.idx_list = idx_list self.batch_size = batch_size def __iter__(self): batches = [] start_pos = 0 end_pos = len(self.idx_list) for _ in range(start_pos, end_pos + self.batch_size, self.batch_size): batch_idx = self.idx_list[start_pos : start_pos + self.batch_size] if batch_idx != []: batches.append(batch_idx) start_pos = start_pos + self.batch_size return iter(batches)<file_sep>/public/oob/test_model.py import torch import torchvision.models as models import pytorch_lightning as pl from efficientnet_pytorch import EfficientNet # Add Support Model [EfficientNet Family] - https://github.com/lukemelas/EfficientNet-PyTorch from torchsummary import summary class CAMIO(pl.LightningModule): """ Define backbone model. """ def __init__(self, config:dict): super(CAMIO, self).__init__() self.hparams.update(config) # self.hparams=config has been removed from later versions and is no longer supported. self.save_hyperparameters() # save with hparams # hyper param setting self.init_lr = self.hparams.optimizer_lr # config['optimizer_lr'] self.backbone = self.hparams.backbone_model # config['backborn_model'] # print(config) # print(self.init_lr) # print(self.backbone) # model setting if self.backbone.find('mobilenet') != -1 : if self.backbone == 'mobilenet_v3_large' : self.model = models.mobilenet_v3_large(pretrained=True) self.num_ftrs = self.model.classifier[-1].in_features self.model.classifier = torch.nn.Sequential( torch.nn.Linear(960, self.num_ftrs), #lastconv_output_channels, last_channel torch.nn.Hardswish(inplace=True), torch.nn.Dropout(p=0.2, inplace=True), torch.nn.Linear(self.num_ftrs, 2) #last_channel, num_classes ) else : assert(False, '=== Not supported MobileNet model ===') elif self.backbone.find('efficientnet') != -1 : if self.backbone == 'efficientnet_b3' : self.model = EfficientNet.from_pretrained('efficientnet-b3', advprop=False, num_classes=2) # Normailize from ImageNet else : assert(False, '=== Not supported EfficientNet model ===') else : assert(False, '=== Not supported Model === ') def forward(self, x): return self.model(x) <file_sep>/public/oob/pp.py import numpy as np import pandas as pd from itertools import groupby import copy from skimage.morphology import binary_erosion, binary_dilation, opening, closing, erosion, dilation class FilterBank: def __init__(self, seq_list:list, seq_fps=1): self.EXCEPTION_NUM = -100 self.seq_list = seq_list # seq_list should be 1D list, list should be composite in 0 or 1. example:[1,0,1,1,0,0,1,1,0...] self.seq_fps = seq_fps # default fps(vihub's 1.2 inference fps) = 1 def list_to_numpy(self, list): return np.array(list, dtype=np.int32) def numpy_to_list(self, npy): return npy.tolist() def apply_filter(self, seq_list, filter_type:str, kernel_size:int) : """ appling post processing from support filter [median, opening, closing] Args: seq_list: 1D input list, [1,0,0,0,1,1,0,1 ...] filter_type: str, ['median', 'opening', 'closing'] kernel_size: int, filter's kernel size Returns: results: seq_list after applying pp filter. example [1,0,0,1,1,..] results error : -100 (EXCEPTION_NUM) """ assert filter_type in ['median', 'opening', 'closing'], "NOT SUPPORT FILTER" seq_numpy = self.list_to_numpy(seq_list) # converting list to numpy print('\n\n\t\t ===== APPLYING FILTER | type : {} | kernel_size = {} =====\n\n'.format(filter_type, kernel_size)) results = self.EXCEPTION_NUM # init error value if filter_type == 'median' : assert kernel_size in [1,3,5,7,9,11], "NOT SUPPORT FILTER SIZE" results=self.medfilter(seq_numpy, kernel_size) # 1D numpy elif filter_type == 'opening' : results = self.openingfilter(seq_numpy, kernel_size) # 1D numpy elif filter_type == 'closing' : results = self.closingfilter(seq_numpy, kernel_size) # 1D numpy results = results.astype(seq_numpy.dtype) # convert to original dtype results = self.numpy_to_list(results) # convert to numpy to list return results # numpy # not yet used def encode_list(self, s_list): # run-length encoding from list return [[len(list(group)), key] for key, group in groupby(s_list)] # [[length, value], [length, value]...] # not yet used def decode_list(self, run_length): # run_length -> [0,1,1,1,1,0 ...] decode_list = [] for length, group in run_length : decode_list += [group] * length return decode_list def time_to_filtersize(self, filter_sec, fps): """ calculate filter kernel size from applying filter second Args: filter_time:float or int, applying filter time you want to convert fps: float or int, seq_list's fps, if predict seq's fps is 1fps, you set param fps=1 Returns: filter_size: converted filter kernel size results error : -100 (EXCEPTION_NUM) example: time_to_filtersize(1, 1) => 1 time_to_filtersize(1, 6) => 6 time_to_filtersize(3, 30) => 90 """ filter_size = self.EXCEPTION_NUM filter_size = filter_sec * fps return int(filter_size) def medfilter (self, x, k): """ Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints. Args: x:1D numpy k:kernel_size Returns: 1D numpy """ assert k % 2 == 1, "Median filter length must be odd." assert x.ndim == 1, "Input must be one-dimensional." k2 = (k - 1) // 2 y = np.zeros ((len (x), k), dtype=x.dtype) ''' print('==> prepare') print(y) ''' y[:,k2] = x ''' print('\n==> arrange') print(y) ''' for i in range (k2): j = k2 - i y[j:,i] = x[:-j] y[:j,i] = x[0] y[:-j,-(i+1)] = x[j:] y[-j:,-(i+1)] = x[-1] ''' print('\n==> margin padding') print(y) ''' return np.median (y, axis=1) def openingfilter(self, x, iter_count): """ Applying opening mophology calc from 1D sequence Args: x:1D numpy iter_count: iteration count of opening mophology calculation Returns: 1D numpy """ out = np.copy(x) # opening for i in range(iter_count): out = erosion(out) for j in range(iter_count): out = dilation(out) return out def closingfilter(self, x, iter_count): """ Applying closing mophology calc from 1D sequence Args: x:1D numpy iter_count: iteration count of closing mophology calculation Returns: 1D numpy """ out = np.copy(x) # closing for i in range(iter_count): out = dilation(out) for j in range(iter_count): out = erosion(out) return out def apply_best_filter(self): """ Applying apply best pp filter from self.seq_list Returns: best_pp_results """ pp_results = self.EXCEPTION_NUM # apply filter sequence pp_results = self.apply_filter(self.seq_list, "opening", self.time_to_filtersize(1, self.seq_fps)) pp_results = self.apply_filter(pp_results, "closing", self.time_to_filtersize(1, self.seq_fps)) return pp_results if __name__ == '__main__': # example data seq_list = [1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1] # predict sequence seq_fps = 1 # sequence's fps ##### example 1. when you want to apply best pp filter fb = FilterBank(seq_list, seq_fps) best_pp_seq_list = fb.apply_best_filter() print(seq_list) print(best_pp_seq_list) # pp results ##### example 2. when you want to apply custimizing sequence of pp filter # fb2 = FilterBank(seq_list, seq_fps) # seq_fps custimize_pp_seq_list = fb.apply_filter(seq_list, "median", kernel_size=3) custimize_pp_seq_list = fb.apply_filter(custimize_pp_seq_list, "opening", kernel_size=1) print(seq_list) print(custimize_pp_seq_list) # pp results<file_sep>/src/components/RecordsTable/style.js import { styled } from "@stitches/react"; export const ClickableTd = styled("td", { cursor: "pointer", color: "blue", textDecoration: "underline", }); <file_sep>/public/oob/eval.py import os import csv import pandas as pd import numpy as np import json import argparse import pp parser = argparse.ArgumentParser() parser.add_argument('--model_output_csv_path', type=str, default='/OOB_RECOG/shared_OOB_Inference_Module/assets/Inference/Inference-ROBOT-01_G_01_R_100_ch1_01.csv', help='model predict output file path') parser.add_argument('--gt_json_path', type=str, default='/OOB_RECOG/shared_OOB_Inference_Module/assets/Annotation(V2)/01_G_01_R_100_ch1_01_OOB_27.json', help='ground-truth (annotation) file path') parser.add_argument('--save_dir_path', type=str) parser.add_argument('--inference_step', type=int, default=5, help='inference frame step') args, _ = parser.parse_known_args() class Inference_eval: def __init__(self, model_output_csv_path:str, gt_json_path:str, save_dir_path:str, inference_step:int): self.model_output_csv_path = model_output_csv_path self.gt_json_path = gt_json_path self.save_dir_path = save_dir_path self.inference_step = inference_step self.video_name = '_'.join(self.gt_json_path.split('/')[-1].split('.')[0].split('_')[:7]) def create_directory(self, dir): try: if not os.path.exists(dir): os.makedirs(dir) except OSError: print("ERROR: Failed to created the directory") def list_length_parity_check(self, model_output_list:list, gt_list:list): """ Check the the number of model_output_list match the number of gt_list. Args: model_output_list: `list`, model predict output list. gt_list: `list`, gt_list. Returns: True or False (Boolean) """ return len(model_output_list) != len(gt_list) def file_format_parity_check(self): return ('csv' in self.model_output_csv_path) and ('json' in self.gt_json_path) def convert_gt_json(self): """ Read groud-truth(gt) json file, covert gt json to binary list. Returns: `list` of groud-truth. Example: >>> convert_gt_json() [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, ... , 0] """ self.gt_idx_list=[] self.gt_return_list=[] # open annotation json file with open(self.gt_json_path) as self.json_file : self.json_data = json.load(self.json_file) self.totalframe = self.json_data['totalFrame'] # totalframe = 51540 # annotation frame for self.anno_data in self.json_data['annotations'] : self.start = self.anno_data['start'] # start frame number self.end = self.anno_data['end'] # end frame number self.gt_idx_list.append([self.start, self.end]) # gt_idx_list = [[start, end], [start, end]..] self.gt_list=[0]*self.totalframe # gt_list = [0, 0, 0, 0, 0, 0, ... , 0] for self.gt_idx in self.gt_idx_list: ## if last annotation frame number exceeds the total number of frames, ## cut the last annotation frame to the total number of frames. if self.gt_idx[1] >= self.totalframe : self.gt_idx[1] = self.totalframe-1 # indicate OOB (1) for self.i in range(self.gt_idx[0], self.gt_idx[1]+1) : self.gt_list[self.i]=1 # convert gt_list to inference step. for i, gt in enumerate(self.gt_list) : if i % self.inference_step==0 : self.gt_return_list.append(gt) return self.gt_return_list # gt_return_list = [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, ... , 0] def calc_OR_CR(self): """ Calculate Over_Estimation_Ratio(OR) and Confidence_Ratio(CR). Save results (OR, CR) to json file `results-OR_CR.json`. It overwrite duplicate videos. output json file : results-OR_CR.json { "01_G_01_R_100_ch1_03": { "over_estimation_ratio": 0.01046610685164902, "confidence_ratio": 0.9785809906291834 }, "01_G_01_R_100_ch1_01": { "over_estimation_ratio": 0.18985270049099837, "confidence_ratio": 0.6202945990180033 }, "01_G_01_R_100_ch1_05": { "over_estimation_ratio": 0.0, "confidence_ratio": 0.9303075063784074 } } Returns: `list`, of Over_Estimation_Ratio and Confidence_Ratio. [self.over_estimation_ratio, self.confidence_ratio] Example: >>> calc_OR_CR() [0.15, 0.8466666] """ ## 1. parity check - file format if not self.file_format_parity_check(): raise Exception('ERROR: file format is not csv or json') # read model_output_list as pandas. self.model_output_result=pd.read_csv(self.model_output_csv_path) # convert pandas to list format. self.model_output_list=list(np.array(self.model_output_result['predict'].tolist())) ####### Post Processing ####### ##### example 1. when you want to apply best pp filter (default sequence fps = 1) fb = pp.FilterBank(self.model_output_list, seq_fps=1) self.model_output_list = fb.apply_best_filter() # modify after pp ####### Post Processing ####### # read gt_list from annotation json file. self.gt_list=self.convert_gt_json() ## 2. parity check - list length ## if len(model_output_list) != len(gt_list) -> raise ERROR, exit(1) if self.list_length_parity_check(self.model_output_list, self.gt_list): raise Exception('ERROR: the number of model_output_list does not match the number of gt_list.') # calculate TP, TN, FP, FN self.TP, self.TN, self.FP, self.FN = 0, 0, 0, 0 for self.predict, self.gt in zip(self.model_output_list, self.gt_list) : if self.predict == self.gt : if self.predict == 0 : self.TN += 1 elif self.predict == 1 : self.TP += 1 elif self.predict != self.gt : if self.predict == 0 : self.FN += 1 elif self.predict == 1 : self.FP += 1 # caculate over_estimation_ratio(OR), confidence_ratio(CR) try: self.over_estimation_ratio=self.FP/(self.FP+self.TP+self.FN) self.confidence_ratio=(self.TP-self.FP)/(self.FP+self.TP+self.FN) ## if (FP+TP+FN)==0, set over_estimation_ratio, confidence_ratio as 1 except: self.over_estimation_ratio=-1 self.confidence_ratio=-1 # save result file. # self.save_dir_path = './results_pp' # 저장 위치 받아와서 할당 self.create_directory(self.save_dir_path) self.save_file_path = os.path.join(self.save_dir_path, 'results_OR_CR.json') # if the file exists. if os.path.isfile(self.save_file_path): # read old file. with open(self.save_file_path, 'r') as self.json_file: self.json_data=json.load(self.json_file) self.json_data[self.video_name] = {'over_estimation_ratio':self.over_estimation_ratio, 'confidence_ratio':self.confidence_ratio} # overwrite new file. with open(self.save_file_path, 'w') as self.json_file: json.dump(self.json_data, self.json_file, indent=2) # if the file not exits. else: self.calc_OR_CR_dict = {} self.calc_OR_CR_dict[self.video_name] = {'over_estimation_ratio':self.over_estimation_ratio, 'confidence_ratio':self.confidence_ratio} with open(self.save_file_path, 'w') as fh: json.dump(self.calc_OR_CR_dict, fh, indent=2) return [self.over_estimation_ratio, self.confidence_ratio] def calc_mOR_mCR(self, OR_CR_list:list) : # OR_CR_list = [[OR, CR], [OR, CR], [OR, CR]] """ Calculate mean_Over_Estimation_Ratio(mOR) and mean_Confidence_Ratio(mCR). Args: CR_OR_list: `list`, pair of the [[OR_1, CR_1], [OR_2, CR_2], [OR_3, CR_3], ... , [OR_9, CR_9]] Returns: `list`, of mean_Over_Estimation_Ratio and mean_Confidence_Ratio. Example: >>> calc_mOR_mCR([[0.1, 0.9], [0.2, 0.8], [0.15, 0.84]]) [0.15, 0.8466666] """ self.OR_CR_list = OR_CR_list self.OR_sum, self.CR_sum = 0, 0 for self.OR_CR in self.OR_CR_list : self.OR_sum += self.OR_CR[0] self.CR_sum += self.OR_CR[1] self.mOR = self.OR_sum/len(self.OR_CR_list) self.mCR = self.CR_sum/len(self.OR_CR_list) return [self.mOR, self.mCR] if __name__ == '__main__': test = Inference_eval(model_output_csv_path=args.model_output_csv_path, gt_json_path=args.gt_json_path, save_dir_path=args.save_dir_path, inference_step=args.inference_step) test.calc_OR_CR() <file_sep>/src/components/FileLoader/style.js import { styled } from "@stitches/react"; export const Label = styled("label", { display: "block", }); <file_sep>/public/utils/ffmpeg-helper.js const fs = require("fs/promises"); const path = require("path"); const { v4: uuidv4 } = require("uuid"); const ffmpegUtils = require("./ffmpeg"); const extract = async (guide, srcPath, dstPath) => { const tmpDir = path.join(path.dirname(dstPath), uuidv4()); await fs.mkdir(tmpDir); const sliced = []; const sliceTasks = guide.map( (curr, i) => { const { start, end } = curr; const filePath = path.join(tmpDir, `${i}.mp4`); sliced.push(filePath); return ffmpegUtils.slice(srcPath, start, end - start, filePath); }, [], ); try { await Promise.all(sliceTasks); await ffmpegUtils.concat(sliced, dstPath, tmpDir); } catch (error) { console.error(error); } await fs.rmdir(tmpDir, { recursive: true, force: true }); }; module.exports = { extract, }; <file_sep>/requirements.txt absl-py==0.12.0 aiohttp==3.7.4.post0 art==5.2 async-timeout==3.0.1 attrs==21.2.0 brotlipy==0.7.0 cachetools==4.2.2 certifi==2020.12.5 conda==4.9.2 conda-build==3.21.4 cycler==0.10.0 dataclasses==0.6 decord==0.5.2 dnspython==2.1.0 efficientnet-pytorch==0.7.1 fsspec==2021.4.0 future==0.18.2 google-auth==1.30.0 google-auth-oauthlib==0.4.4 grad-cam==1.2.9 grpcio==1.37.1 jedi==0.17.0 joblib==1.0.1 kiwisolver==1.3.1 Markdown==3.3.4 MarkupSafe==1.1.1 matplotlib==3.4.2 mkl-fft==1.3.0 mkl-random==1.1.1 mkl-service==2.3.0 multidict==5.1.0 natsort==7.1.1 oauthlib==3.1.0 olefile==0.46 opencv-python==4.5.2.52 packaging==20.9 pandas==1.2.4 parso==0.7.0 pkginfo==1.7.0 protobuf==3.16.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycm==3.1 pycosat==0.6.3 pyDeprecate==0.3.0 pyparsing==2.4.7 python-dateutil==2.8.1 python-etcd==0.4.5 pytorch-lightning==1.3.0 PyYAML==5.3.1 requests-oauthlib==1.3.0 rsa==4.7.2 ruamel-yaml==0.15.87 scikit-learn==0.24.2 scipy==1.6.3 sklearn==0.0 tensorboard==2.4.1 tensorboard-plugin-wit==1.8.0 threadpoolctl==2.1.0 torch==1.8.0 torch-summary==1.4.4 torchelastic==0.2.1 torchmetrics==0.3.2 torchtext==0.9.0 torchvision==0.9.0 ttach==0.0.3 Werkzeug==1.0.1 yarl==1.6.3 torch_summary==1.4.4 efficientnet_pytorch==0.7.1 tqdm==4.51.0 pytorch_lightning==1.3.0 numpy==1.21.0 Pillow==8.2.0 torchsummary==1.5.1 scikit-image <file_sep>/src/components/RecordsTable/index.jsx import PropTypes from "prop-types"; import { memo } from "react"; import * as S from "./style"; function RecordsTable({ records, openWorkDir }) { return ( <table> <thead> <tr> <th>날짜</th> <th>비디오</th> <th>디렉토리</th> </tr> </thead> <tbody> { records.map((record) => ( <tr key={record.date}> <td>{(new Date(record.date)).toString()}</td> <td>{record.videoName}</td> <S.ClickableTd onClick={openWorkDir} data-work-dir={record.workDir}>{record.workDir}</S.ClickableTd> </tr> )) } </tbody> </table> ); } function areEqual(prevProps, nextProps) { return JSON.stringify(prevProps.records) === JSON.stringify(nextProps.records); } export default memo(RecordsTable, areEqual); RecordsTable.propTypes = { records: PropTypes.arrayOf(PropTypes.shape({ data: PropTypes.string.isRequired, videoName: PropTypes.string.isRequired, workDir: PropTypes.string.isRequired, })).isRequired, openWorkDir: PropTypes.func.isRequired, }; <file_sep>/Dockerfile FROM pytorch/pytorch:1.8.0-cuda11.1-cudnn8-runtime WORKDIR /OOB_RECOG CMD [ "mkdir", "mount" ] ADD requirements.txt . RUN pip install -r requirements.txt<file_sep>/public/oob/test.py from __future__ import print_function, division import os import sys import argparse import torch # from tqdm import tqdm import platform from test_model import CAMIO from torch.utils.data import Dataset, DataLoader from test_dataset import OOB_DB_Dataset, IDX_Sampler image_datasets_dir = sys.argv[1] model_path = './models/mobile.ckpt' if sys.argv[2] == 'mobile' else './models/efficient.ckpt' def inference_by_frame_list(image_datasets_dir, model_path) : """ Inference using frame img. BATCH_SIZE = 64 Args: image_datasets_dir: target datasets directory for infernece -> str: model: trainer model. we only support .ckpt extention. -> str: Return: BATCH_PREDICT (predict list) -> List[int]: """ predict_list = [] # predict if 'mobile' in model_path : test_hparams = { 'optimizer_lr' : 0, # dummy (this option use only for training) 'backbone_model' : 'mobilenet_v3_large' # (for train, test) } elif 'efficient' in model_path : test_hparams = { 'optimizer_lr' : 0, # dummy (this option use only for training) 'backbone_model' : 'efficientnet_b3' # (for train, test) } model = CAMIO.load_from_checkpoint(model_path, config=test_hparams) # model.cuda() BATCH_SIZE = 64 test_dataset = OOB_DB_Dataset(image_datasets_dir) # target idx TARGET_IDX_LIST = list(range(0, len(test_dataset))) # Set index for batch s = IDX_Sampler(TARGET_IDX_LIST, batch_size=BATCH_SIZE) #[[0, 100], [200, 300], ... , [136800,136900]] # set dataloader with custom batch sampler dl = DataLoader(test_dataset, batch_sampler=list(s)) with torch.no_grad() : model.eval() # inferencing model for sample in dl: # BATCH_INPUT = sample['img'].cuda() BATCH_INPUT = sample['img'] BATCH_OUTPUT = model(BATCH_INPUT) # predict BATCH_PREDICT = torch.argmax(BATCH_OUTPUT.cpu(), 1) BATCH_PREDICT = BATCH_PREDICT.tolist() # save results predict_list+= list(BATCH_PREDICT) # print('\n ==================================== \n') # print('len(predict_list) : ', len(predict_list)) # print('\n ==================================== \n\n') # print('predict_list ====> \n', predict_list) # print('\n ==================================== \n') return predict_list if __name__ == "__main__": ### base setting for model testing ### ### os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' list = inference_by_frame_list(image_datasets_dir, model_path) print(list) <file_sep>/src/pages/App/index.js import { useState, useCallback, useEffect } from "react"; import FileLoader from "../../components/FileLoader"; import RecordsTable from "../../components/RecordsTable"; import { ScrollableSection } from "../../components/ScrollableSection/style"; import { db, subscribe } from "../../services/idb"; function App() { const [videoInput, setVideoInput] = useState(); const [gtInput, setGtInput] = useState(); const [onProcessing, setOnProcessing] = useState(false); const [messages, setMessages] = useState([]); const [records, setRecords] = useState([]); const onChange = useCallback(async (e) => { if (onProcessing) return; const file = e.target.files[0]; if (!file) return; switch (e.target.id) { case "gt": setGtInput(file); break; case "video": setVideoInput(file); break; } }, [onProcessing]); const printMessage = useCallback((scope, status, action) => { setMessages((messages) => messages.concat(`[${scope}] ${status}: ${action}`)); }, []); const openWorkDir = useCallback((e) => { window.api.openPath(e.target.dataset.workDir); }, []); useEffect(async () => { await subscribe("records", setRecords); }, []); useEffect(() => { if (gtInput && videoInput) { setOnProcessing(true); } }, [gtInput, videoInput]); useEffect(async () => { if (!gtInput || !videoInput || !onProcessing) return; printMessage(videoInput.name, "start", "extracting frames"); const workDir = await window.api.getWorkDir(); await window.api.extractFrames(workDir, videoInput.path); printMessage(videoInput.name, "done", "extracting frames"); printMessage(videoInput.name, "start", "prediction"); // TODO: 도커 컨테이너에 [workDir]/frames 전달 -> prediction 수행 -> 결과 .csv로 저장 (workDir에) => 결과 파일 저장 경로 반환 // TODO: .csv 파일 경로 받고 -> eval -> 결과 .json으로 저장 (컨테이너가 직접 저장) => 결과 파일 저장 경로 반환 const promises = ["mobile", "efficient"].map((withModel) => ( window.api.predict(workDir, videoInput.name, withModel) .then((csvPath) => window.api.evalPrediction(csvPath, gtInput.path)) )); const results = await Promise.allSettled(promises); results.forEach((result) => { if (result.status === "rejected") { console.log(result); } }); printMessage(videoInput.name, "done", "prediction"); db.records.add({ date: Date.now(), videoName: videoInput.name, workDir, }); setGtInput(); setVideoInput(); setOnProcessing(false); }, [gtInput, videoInput, onProcessing]); return ( <> <h1>Eval Tool</h1> <section> <FileLoader id="gt" label="JSON 형식의 gt 파일을 선택 해 주세요." accept="application/JSON" onChange={onChange} /> <FileLoader id="video" label="비디오를 선택 해 주세요." accept="video/mp4" onChange={onChange} /> </section> <ScrollableSection messages={messages} /> <section> <RecordsTable records={records} openWorkDir={openWorkDir} /> </section> </> ); } export default App;
7ac7a098f5297b6d43333e6b46b7629f67bf5505
[ "JavaScript", "Python", "Text", "Dockerfile" ]
14
JavaScript
HyonheeYoo/eval-tool
e247ac0d543c1ca526cec57a3b1aee2519a30d50
00d7b4a51fa496e93e03934d5b85b964051aeccc
refs/heads/master
<repo_name>antoyohan/android_downloadmanager<file_sep>/README.md # android_downloadmanager Sample android project for downloading http stream into local memory <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/interfaces/IDownloadManager.java package com.media.downloadmanager.interfaces; import com.media.downloadmanager.model.DownloadRequest; public interface IDownloadManager { int add(DownloadRequest request); int pause(String id); void pauseAll(); int resume(String id); int cancel(String id); void release(); } <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/utils/MediaHeaderRequest.java package com.media.downloadmanager.utils; import android.os.AsyncTask; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Class to fetch the http header values * */ public class MediaHeaderRequest extends AsyncTask<String, Void, String> { private OnDownloadCompleteListener mListener; private String TAG = MediaHeaderRequest.class.getName(); public MediaHeaderRequest(OnDownloadCompleteListener listener) { mListener = listener; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { URL url = null; try { url = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String contentLength = conn.getHeaderField("Content-Length"); conn.disconnect(); return contentLength; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String contentlength) { super.onPostExecute(contentlength); if (mListener != null) { mListener.onDownloadComplete(contentlength); } } public interface OnDownloadCompleteListener { void onDownloadComplete(String result); } } <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/application/ApplicationClass.java package com.media.downloadmanager.application; import android.content.Context; public class ApplicationClass { private static Context sContext ; public static void setContext(Context sContext) { ApplicationClass.sContext = sContext; } public static Context getContext() { return sContext; } } <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/DownloadService.java package com.media.downloadmanager; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class DownloadService extends Service { protected static final String TAG = "DownloadService"; private static boolean isRunning; @Override public void onCreate() { super.onCreate(); } private void init() { Log.d(TAG, "Starting Download service..."); DownloadManager downloadManager = DownloadManager.getInstance(this); if (downloadManager.isDownloadableItemsPresent()) { //repopulate the queue and start download DownloadManager.getInstance(this).reloadQueue(); downloadManager.startDownloading(); } } public void stop() { DownloadManager.getInstance(getApplicationContext()).release(); stopSelf(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { isRunning = true; Log.e(TAG, "onStartCommand"); init(); return START_STICKY; } public static boolean isRunning() { return isRunning; } @Override public void onTaskRemoved(Intent rootIntent) { Log.d(TAG, "onTaskRemoved"); DownloadManager.getInstance(this).placeEverythingInQueue(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); isRunning = false; DownloadManager.getInstance(this).placeEverythingInQueue(); DownloadManager.getInstance(this).release(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/DownloadDispatcher.java package com.media.downloadmanager; import android.net.Uri; import android.os.Process; import android.text.TextUtils; import android.util.Log; import com.media.downloadmanager.interfaces.DownloadError; import com.media.downloadmanager.interfaces.DownloadStatusListener; import com.media.downloadmanager.interfaces.IDownloadState; import com.media.downloadmanager.model.DownloadRequest; import org.apache.http.conn.ConnectTimeoutException; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.BlockingQueue; import io.realm.Realm; import io.realm.RealmObject; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_MOVED_PERM; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.HttpURLConnection.HTTP_PARTIAL; import static java.net.HttpURLConnection.HTTP_SEE_OTHER; import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; public class DownloadDispatcher extends Thread { /** * The queue of download requests to service. */ private final BlockingQueue<DownloadRequest> mQueue; private final ArrayList<DownloadRequest> mDownloadList; /** * Used to tell the dispatcher to die. */ private volatile boolean mQuit = false; /** * Current Download request that this dispatcher is working */ private DownloadRequest mRequest; /** * The buffer size used to stream the data */ public final int BUFFER_SIZE = 4096; /** * How many times redirects happened during a download request. */ private int mRedirectionCount = 0; /** * Listener for updating the download status to ui */ private DownloadStatusListener mDownloadStatusListener; /** * The maximum number of redirects. */ public final int MAX_REDIRECTS = 0; private final int HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; private final int HTTP_TEMP_REDIRECT = 307; private long mContentLength; private long mCurrentBytes; boolean shouldAllowRedirects = true; /** * Tag used for debugging/logging */ public static final String TAG = "DownloadDispatcher"; private String mCurrentDownloadId = ""; private String mPauseId = ""; private DownloadRequest mDbInstance; private Realm mRealmInstance; private boolean mShouldRetry = false; private String mQueueId = ""; private String mCancelId = ""; /** * Constructor take the dependency (DownloadRequest queue) that all the Dispatcher needs */ public DownloadDispatcher(BlockingQueue<DownloadRequest> queue, ArrayList<DownloadRequest> queueList) { mQueue = queue; mDownloadList = queueList; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { try { Log.d(TAG, "Waiting for object"); clearVariables(); mRequest = mQueue.take(); mCurrentDownloadId = mRequest.getArticleId(); mDownloadList.remove(mRequest); Log.d(TAG, "Download initiated for " + mCurrentDownloadId); getDbObject(); updateDownloadInProgress(); executeDownload(mRequest.getUrl()); mRealmInstance.close(); } catch (InterruptedException e) { Log.d(TAG, "Thread Interrupted"); if (mCurrentDownloadId != null && !mCurrentDownloadId.isEmpty()) { updateDownloadQueued(); } } } } private void clearVariables() { mCurrentDownloadId = ""; mQueueId = ""; mQuit = false; mContentLength = 0l; mPauseId = ""; mCancelId = ""; mCurrentBytes = 0l; mRedirectionCount = 0; mShouldRetry = false; shouldAllowRedirects = true; } public void quit() { mQuit = true; interrupt(); } private boolean shoudResumeDownload() { return isDestinationFilePresent() && mDbInstance.getDownloadedBytes() > 0; } private boolean isDestinationFilePresent() { File destinationFile = new File(mRequest.getDestinationPath()); Log.d(TAG, "is File present " + destinationFile.exists() + mRequest.getDestinationPath()); return destinationFile.exists(); } private void executeDownload(String downloadUrl) { URL url; if (shoudResumeDownload()) { mCurrentBytes = mRequest.getDownloadedBytes(); mContentLength = mRequest.getTotalBytes(); resumeDownload(downloadUrl); return; } cleanupDestination(); try { url = new URL(downloadUrl); } catch (MalformedURLException e) { updateDownloadFailed(DownloadError.MALFORMED_URL, "MalformedURLException: URI passed is malformed."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); /*conn.setConnectTimeout(mRequest.getRetryPolicy().getCurrentTimeout()); conn.setReadTimeout(mRequest.getRetryPolicy().getCurrentTimeout());*/ HashMap<String, String> customHeaders = new HashMap<>(); if (customHeaders != null) { for (String headerName : customHeaders.keySet()) { conn.addRequestProperty(headerName, customHeaders.get(headerName)); } } // Status Connecting is set here before // urlConnection is trying to connect to destination. //updateDownloadState(DownloadManager.STATUS_CONNECTING); final int responseCode = conn.getResponseCode(); Log.v(TAG, "Response code obtained for downloaded Id " + mRequest.getArticleId() + " : httpResponse Code " + responseCode); switch (responseCode) { case HTTP_PARTIAL: case HTTP_OK: shouldAllowRedirects = false; if (readResponseHeaders(conn) == 1) { mRequest.setTotalBytes(mContentLength); transferData(conn); } else { updateDownloadFailed(DownloadError.UNKNOWN_SIZE, "Transfer-Encoding not found as well as can't know size of download, giving up"); } return; case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: // Take redirect url and call executeDownload recursively until // MAX_REDIRECT is reached. attemptRetryOnHTTPException(); break; case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: updateDownloadFailed(HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, conn.getResponseMessage()); break; case HTTP_UNAVAILABLE: updateDownloadFailed(HTTP_UNAVAILABLE, conn.getResponseMessage()); break; case HTTP_INTERNAL_ERROR: updateDownloadFailed(HTTP_INTERNAL_ERROR, conn.getResponseMessage()); break; default: updateDownloadFailed(DownloadError.HTTP_ERROR, "Unhandled HTTP response:" + responseCode + " message:" + conn.getResponseMessage()); break; } } catch (SocketTimeoutException e) { e.printStackTrace(); // Retry. attemptRetryOnHTTPException(); } catch (ConnectTimeoutException e) { e.printStackTrace(); attemptRetryOnHTTPException(); } catch (IOException e) { e.printStackTrace(); attemptRetryOnHTTPException(); } finally { if (mShouldRetry) { executeDownload(downloadUrl); } else { if (conn != null) { conn.disconnect(); } } } } private void resumeDownload(String downloadUrl) { Log.e(TAG, "resume Download.."); URL url; try { url = new URL(downloadUrl); } catch (MalformedURLException e) { updateDownloadFailed(DownloadError.MALFORMED_URL,"MalformedURLException: URI passed is malformed."); return; } HttpURLConnection conn = null; try { if (url.getProtocol().toLowerCase().equals("https")) { //trustAllHosts(); } conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); // conn.setConnectTimeout(mRequest.getRetryPolicy().getCurrentTimeout()); // conn.setReadTimeout(mRequest.getRetryPolicy().getCurrentTimeout()); HashMap<String, String> customHeaders = new HashMap<String, String>(); ; if (customHeaders != null && !customHeaders.keySet().isEmpty()) { for (String headerName : customHeaders.keySet()) { if (headerName.equals("Range")) { String rangeEnd = customHeaders.get(headerName); if (!TextUtils.isEmpty(rangeEnd)) { int index = rangeEnd.indexOf("-"); if (index > 0) { String end = ""; try { end = rangeEnd.substring(index + 1); } catch (IndexOutOfBoundsException e) { //ignore } if (!TextUtils.isEmpty(end)) { conn.addRequestProperty(headerName, "bytes=" + mRequest.getDownloadedBytes() + "-" + end); } else { conn.addRequestProperty(headerName, "bytes=" + mRequest.getDownloadedBytes() + "-"); } } else { conn.addRequestProperty(headerName, "bytes=" + mRequest.getDownloadedBytes() + "-"); } } } else { conn.addRequestProperty(headerName, customHeaders.get(headerName)); } } } else { conn.addRequestProperty("Range", "bytes=" + mRequest.getDownloadedBytes() + "-"); } // Status Connecting is set here before // urlConnection is trying to connect to destination. //updateDownloadState(DownloadManager.STATUS_CONNECTING); final int responseCode = conn.getResponseCode(); Log.v(TAG, "Response code obtained for downloaded Id " + mRequest.getArticleId() + " : httpResponse Code " + responseCode); switch (responseCode) { case HTTP_PARTIAL: case HTTP_OK: shouldAllowRedirects = false; if (isResponseContentPresent(conn) == 1) { // readResponseHeaders(conn); transferData(conn); } else { updateDownloadFailed(DownloadError.UNKNOWN_SIZE, "Transfer-Encoding not found as well as can't know size of download, giving up"); } return; case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: // Take redirect url and call executeDownload recursively until // MAX_REDIRECT is reached. attemptRetryOnHTTPException(); break; case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: updateDownloadFailed(HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, conn.getResponseMessage()); break; case HTTP_UNAVAILABLE: updateDownloadFailed(HTTP_UNAVAILABLE, conn.getResponseMessage()); break; case HTTP_INTERNAL_ERROR: updateDownloadFailed(HTTP_INTERNAL_ERROR, conn.getResponseMessage()); break; default: updateDownloadFailed(DownloadError.HTTP_ERROR, "Unhandled HTTP response:" + responseCode + " message:" + conn.getResponseMessage()); break; } } catch (SocketTimeoutException e) { e.printStackTrace(); // Retry. attemptRetryOnHTTPException(); } catch (ConnectTimeoutException e) { e.printStackTrace(); attemptRetryOnHTTPException(); } catch (IOException e) { e.printStackTrace(); attemptRetryOnHTTPException(); } finally { if (mShouldRetry) { executeDownload(downloadUrl); } else { if (conn != null) { conn.disconnect(); } } } } private int isResponseContentPresent(HttpURLConnection conn) { final String transferEncoding = conn.getHeaderField("Transfer-Encoding"); long contentLength = -1; if (transferEncoding == null) { contentLength = getHeaderFieldLong(conn, "Content-Length", -1); } else { Log.v(TAG, "Ignoring Content-Length since Transfer-Encoding is also defined for Downloaded Id " + mRequest.getArticleId()); } if (contentLength != -1) { return 1; } else if (transferEncoding == null || !transferEncoding.equalsIgnoreCase("chunked")) { return -1; } else { return 1; } } private void transferData(HttpURLConnection conn) { InputStream in = null; OutputStream out = null; FileDescriptor outFd = null; try { try { in = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); } Uri desturi = Uri.parse(mRequest.getDestinationPath()); File destinationFile = new File(desturi.getPath()); // Create destination file if it doesn't exists boolean errorCreatingDestinationFile = createFile(destinationFile); // If Destination file couldn't be created. Abort the data transfer. if (!errorCreatingDestinationFile) { try { out = new FileOutputStream(destinationFile, true); outFd = ((FileOutputStream) out).getFD(); } catch (IOException e) { e.printStackTrace(); } if (in == null) { updateDownloadFailed(DownloadError.FILE_ERROR, "Error in creating input stream"); } else if (out == null) { updateDownloadFailed(DownloadError.FILE_ERROR, "Error in writing download contents to the destination file"); } else { // Start streaming data transferData(in, out); } } } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (out != null) { out.flush(); } if (outFd != null) { outFd.sync(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void transferData(InputStream in, OutputStream out) { final byte data[] = new byte[BUFFER_SIZE]; Log.d(TAG, "Content Length: " + mContentLength + " for Download Id " + mRequest.getArticleId()); for (; ; ) { if (mPauseId.equals(mCurrentDownloadId)) { //Stop the download and make the item in paused state Log.d(TAG, "Content PAUSED ------"); updateDownloadPaused(); return; } if (mQueueId.equals(mCurrentDownloadId)) { //Stop the download and make the item in queued state Log.d(TAG, "Content QUEUED ------"); updateDownloadQueued(); return; } if (mCancelId.equals(mCurrentDownloadId)) { //Stop the download after this, content will be deleted so don't update db. Log.d(TAG, "Content Cancelled ------"); updateDownloadCancelled(); return; } int bytesRead = readFromResponse(data, in); if (mContentLength != -1 && mContentLength > 0) { int progress = (int) ((mCurrentBytes * 100) / mContentLength); updateDownloadProgress(progress, mCurrentBytes); } if (bytesRead == -1) { // success, end of stream already reached updateDownloadComplete(); return; } else if (bytesRead == Integer.MIN_VALUE) { return; } if (writeDataToDestination(data, bytesRead, out)) { Log.d(TAG, "data written " + mCurrentBytes); mCurrentBytes += bytesRead; updateDownloadDatabaseStatus(mCurrentBytes); } else { finish(); return; } } } private void finish() { if (mDownloadList.isEmpty()) { //this.quit(); } } private int readFromResponse(byte[] data, InputStream entityStream) { try { return entityStream.read(data); } catch (IOException ex) { if ("unexpected end of stream".equals(ex.getMessage())) { return -1; } // return Integer.MIN_VALUE; } return Integer.MIN_VALUE; } private boolean writeDataToDestination(byte[] data, int bytesRead, OutputStream out) { boolean successInWritingToDestination = true; try { out.write(data, 0, bytesRead); } catch (IOException ex) { successInWritingToDestination = false; } catch (Exception e) { successInWritingToDestination = false; } return successInWritingToDestination; } private int readResponseHeaders(HttpURLConnection conn) { final String transferEncoding = conn.getHeaderField("Transfer-Encoding"); mContentLength = -1; if (transferEncoding == null) { mContentLength = getHeaderFieldLong(conn, "Content-Length", -1); } else { Log.v(TAG, "Ignoring Content-Length since Transfer-Encoding is also defined for Downloaded Id " + mRequest.getArticleId()); } if (mContentLength != -1) { return 1; } else if (transferEncoding == null || !transferEncoding.equalsIgnoreCase("chunked")) { return -1; } else { return 1; } } private long getHeaderFieldLong(URLConnection conn, String field, long defaultValue) { try { return Long.parseLong(conn.getHeaderField(field)); } catch (NumberFormatException e) { return defaultValue; } } private void attemptRetryOnHTTPException() { //Code to retry the Download if (mRedirectionCount < MAX_REDIRECTS && shouldAllowRedirects) { mShouldRetry = true; mRedirectionCount++; } else { mShouldRetry = false; updateDownloadFailed(DownloadError.ERROR_TOO_MANY_REDIRECTS, "too many redirects"); } } /** * Called just before the thread finishes, regardless of status, to take any necessary action on * the downloaded file. */ private void cleanupDestination() { Log.d(TAG, "cleanupDestination() deleting " + mRequest.getDestinationPath()); File destinationFile = new File(mRequest.getDestinationPath()); if (destinationFile.exists()) { destinationFile.delete(); } } private void updateDownloadComplete() { Log.d(TAG, "updateDownlaodComplete"); if (mDownloadStatusListener != null) { mDownloadStatusListener.onDownloadComplete(mCurrentDownloadId); } updateDownloadState(IDownloadState.COMPLETE); } private void updateDownloadFailed(int errorCode, String errorMsg) { Log.d(TAG, "updateDownlaodFailed " + errorCode + " " + errorMsg); if (mDownloadStatusListener != null) { mDownloadStatusListener.onDownloadFailed(mCurrentDownloadId, errorCode, errorMsg); } //updateDownloadState(IDownloadState.FAILED); updateDownloadState(IDownloadState.IN_QUEUE);//Moved into queue state to retry if reloaded } private void updateDownloadInProgress() { updateDownloadState(IDownloadState.IN_PROGRESS); } private void updateDownloadState(int state) { mRequest.setDownloadState(state); update(mRequest); } private void updateDownloadQueued() { updateDownloadState(IDownloadState.IN_QUEUE); } private void updateDownloadPaused() { updateDownloadState(IDownloadState.PAUSED); } private void updateDownloadCancelled() { cleanupDestination(); deleteFromDb(); } private void updateDownloadProgress(int progress, long downloadedBytes) { Log.d(TAG, " id " + mCurrentDownloadId + " progress " + progress + " bytes " + downloadedBytes); if (mDownloadStatusListener != null) { mDownloadStatusListener.onProgress(mCurrentDownloadId, downloadedBytes, progress); } } private void updateDownloadDatabaseStatus(long downloadedBytes) { mRequest.setDownloadedBytes(downloadedBytes); mRequest.setDownloadState(IDownloadState.IN_PROGRESS); update(mRequest); } private void getDbObject() { if (mRealmInstance == null) { mRealmInstance = Realm.getDefaultInstance(); } DownloadRequest downloadRequest = mRealmInstance.where(DownloadRequest.class). equalTo(DownloadRequest.ARTICLE_ID, mCurrentDownloadId).findFirst(); if (downloadRequest != null) { mDbInstance = mRealmInstance.copyFromRealm(downloadRequest); } } private void update(final RealmObject obj) { mRealmInstance.beginTransaction(); mRealmInstance.copyToRealmOrUpdate(obj); mRealmInstance.commitTransaction(); } String getCurrentDownloadId() { return mCurrentDownloadId; } void setDownloadStatusListener(DownloadStatusListener listener) { mDownloadStatusListener = listener; } private boolean createFile(File file) { if (!file.exists()) { file.getParentFile().mkdirs(); try { Log.d(TAG, "creating file " + file.getPath()); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return true; } } return false; } void setPauseId(String pauseId) { mPauseId = pauseId; } void setQueueId(String downloadId) { mQueueId = downloadId; } void setCancelId(String cancelId) { mCancelId = cancelId; } private void deleteFromDb() { Realm realm = Realm.getDefaultInstance(); DownloadRequest downloadRequest = realm.where(DownloadRequest.class). equalTo(DownloadRequest.ARTICLE_ID, mCurrentDownloadId).findFirst(); if (downloadRequest != null) { realm.beginTransaction(); downloadRequest.deleteFromRealm(); realm.commitTransaction(); } realm.close(); } } <file_sep>/downloadmanager/src/main/java/com/media/downloadmanager/interfaces/IDownloadState.java package com.media.downloadmanager.interfaces; public interface IDownloadState { int IN_QUEUE = 1; int IN_PROGRESS = 2; int PAUSED = 3; int FAILED = 4; int COMPLETE = 5; }
f9ae7124e711834255f800476d0d86c502d99065
[ "Markdown", "Java" ]
7
Markdown
antoyohan/android_downloadmanager
aa1f64ebe2eedce08f63fffca89bbc66f1bb34bc
9539712d714f9d19dca44d453015ada9d2b290c8
refs/heads/master
<repo_name>macntouch/CMS_recordingsviewer<file_sep>/scripts/js/videoplayer.js function initReqObject(reqObject) { reqObject = new XMLHttpRequest(); } function playVideo(vidSelection) { var xmlHttp = new XMLHttpRequest(); // initReqObject(xmlHttp); m_url = "./vidList.php"; m_params = "f=s&s=" + vidSelection; // alert(m_url+'?'+m_params); xmlHttp.open("GET", m_url+'?'+m_params, true); xmlHttp.onreadystatechange = function() { document.getElementById("videoPlayer").innerHTML = document.getElementById("videoPlayer").innerHTML + "<br>Starting"; if(xmlHttp.readyState == 4) { m_selection = "readyState is now: 4, status: " + xmlHttp.status + "<br>"; if(xmlHttp.status == 200) { // var m_selection = JSON.parse(xmlHttp.responseText); m_selection = xmlHttp.responseText; // alert(xmlHttp.responseText); // alert("Ready State: " + xmlHttp.readyState + "<br>Status: " + xmlHttp.status); document.getElementById("videoPlayer").innerHTML = document.getElementById("videoPlayer").innerHTML + "<br>Got here #1<br>"; processVideoMeta(m_selection.trim()); document.getElementById("videoPlayer").innerHTML = document.getElementById("videoPlayer").innerHTML + "<br>Got here #2<br>"; } } else { // alert("Ready State: " + xmlHttp.readyState + "<br>Status: " + xmlHttp.status); } } xmlHttp.send(null); // document.getElementById("videoPlayer").innerHTML = document.getElementById("videoPlayer").innerHTML + xmlHttp.responseText; } function processVideoMeta(m_selection) { // document.getElementById("videoPlayer").innerHTML = document.getElementById("videoPlayer").innerHTML + m_selection; document.getElementById("videoPlayer").innerHTML = "<video controls autoplay><source src=\"" + m_selection + "\" type=\"video/mp4\"></video>"; } <file_sep>/recordingview/vidList.php <?php function getVideosCreateArray() { $col_count = 0; $my_dir = './recordings/spaces/'; $my_spaces = new DirectoryIterator($my_dir); $meta_pattern = '/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/'; $vidArray = array(); foreach($my_spaces as $theDir) { if(strlen($theDir->getfilename()) > 2){ $my_dir2 = $my_dir . $theDir; $tmp_theDir = $theDir->getfilename(); $my_files = new DirectoryIterator($my_dir2); foreach($my_files as $file) { if(strlen($file) > 2) { if (preg_match_all($meta_pattern, $file, $matches)) { $m_index = $matches[0][0]; $vidArray["$m_index"] = array("vidYear" => $matches[1][0], "vidMonth" => $matches[2][0], "vidDay" => $matches[3][0], "vidFile" => $matches[0][0] . "-0400.mp4", "vidDir" => $tmp_theDir, "vidParentDir" => $my_dir2); } } } } } return ($vidArray); } function displayVideos() { header("Content-Type:text/html"); print("<html><head><title>Video Review Portal</title></head><body>"); $col_count = 0; $my_dir = './recordings/spaces/'; $my_spaces = new DirectoryIterator($my_dir); $meta_pattern = '/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/'; print("<table border=\"1\"><tr><th></th><th></th></tr>" . PHP_EOL); foreach($my_spaces as $theDir) { if(strlen($theDir->getfilename()) > 2){ print("<tr><td colspan=\"2\" style=\"background-color: blue; color: white; height: 20px; font-size: 18pt;\">" . $theDir . "</td></tr>" . PHP_EOL); $my_dir2 = $my_dir . $theDir; $my_files = new DirectoryIterator($my_dir2); foreach($my_files as $file) { if(strlen($file) > 2) { print("<td>" . PHP_EOL); if($col_count >= 0 && $col_count <= 4) { print("<td>" . PHP_EOL); } else { print("<tr><td>" . PHP_EOL); } print("<video width=\"320\" height=\"280\" controls>" . PHP_EOL); print("<source src=\"" . $my_dir2 . "/" . $file . "\" " . "type=\"video/mp4\">" . PHP_EOL); print("</video>" . PHP_EOL); // print("<br>" . $file); if (preg_match_all($meta_pattern, $file, $matches)) { print("<table><tr><td align=\"RIGHT\">YEAR:</td><td>" . $matches[1][0] . "</td><td><button type=\"button\" name=\"btn_profile\" id=\"btn_profile\">PROFILE</button></td></tr><tr><td align=\"RIGHT\">MONTH:</td><td>" . $matches[2][0] . "</td></tr><tr><td align=\"RIGHT\">DAY:</td><td>" . $matches[3][0] . "</td></tr><tr><td align=\"RIGHT\">HOUR:</td><td>" . $matches[4][0] . "</td></tr><tr><td align=\"RIGHT\">MINUTE:</td><td>" . $matches[5][0] . "</td></tr><tr><td align=\"RIGHT\">SECOND:</td><td>" . $matches[6][0] . "</td></tr></table>"); } else { print("<br>A matching error occurred"); } if($col_count++ >= 0 && $col_count < 4) { print("</td>" . PHP_EOL); } else { print("</td></tr>" . PHP_EOL); $col_count = 0; } } } $col_count = 0; print("</tr>" . PHP_EOL); } } print("</table>" . PHP_EOL); print("</body></html>"); } function displayVideosXML() { $xml_version = "1.0"; $xml_encoding = "UTF-8"; $video_count = 0; $video_xmldescrip = ""; /*// print("<?xml version='" . $xml_version . "' encoding='" . $xml_encoding . "'?>"); */ header("Content-Type: text/xml"); $my_dir = './recordings/spaces/'; $my_spaces = new DirectoryIterator($my_dir); $meta_pattern = '/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/'; foreach($my_spaces as $theDir) { if(strlen($theDir->getfilename()) > 2) { $my_dir2 = $my_dir . $theDir; $my_files = new DirectoryIterator($my_dir2); foreach($my_files as $theVideo) { if(strlen($theVideo) > 2) { if(preg_match_all($meta_pattern, $theVideo, $matches)) { $vid_year = $matches[1][0]; $vid_day = $matches[3][0]; $vid_month = $matches[2][0]; $vid_hour = $matches[4][0]; $vid_minute = $matches[5][0]; $vid_second = $matches[6][0]; } $video_xmldescrip = $video_xmldescrip . "<video><id>" . $theDir . "-" . $matches[0][0] . "</id><filename>" . $theVideo . "</filename><year>" . $vid_year . "</year><month>" . $vid_month . "</month><day>" . $vid_day . "</day><hour>" . $vid_hour . "</hour><minute>" . $vid_minute . "</minute><second>" . $vid_second . "</second></video>"; ++$video_count; } } } } print("<videos total=\"" . $video_count . "\">"); print($video_xmldescrip); print("</videos>"); } function displayVideosJSON() { $xml_version = "1.0"; $xml_encoding = "UTF-8"; $video_count = 0; $video_jsondescrip = ""; /*// print("<?xml version='" . $xml_version . "' encoding='" . $xml_encoding . "'?>"); */ header("Content-Type: application/json"); $my_dir = './recordings/spaces/'; $my_spaces = new DirectoryIterator($my_dir); $meta_pattern = '/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/'; foreach($my_spaces as $theDir) { if(strlen($theDir->getfilename()) > 2) { $my_dir2 = $my_dir . $theDir; $my_files = new DirectoryIterator($my_dir2); foreach($my_files as $theVideo) { if(strlen($theVideo) > 2) { if(preg_match_all($meta_pattern, $theVideo, $matches)) { $vid_year = $matches[1][0]; $vid_day = $matches[3][0]; $vid_month = $matches[2][0]; $vid_hour = $matches[4][0]; $vid_minute = $matches[5][0]; $vid_second = $matches[6][0]; } $video_jsondescrip = $video_jsondescrip . "{\"id\" : \"" . $theDir . "-" . $matches[0][0] . "\",\"filename\" : \"" . $theVideo . "\", \"year\" : \"" . $vid_year . "\", \"month\" : \"" . $vid_month . "\", \"day\" : \"" . $vid_day . "\",\"hour\" : \"" . $vid_hour . "\",\"minute\" : \"" . $vid_minute . "\",\"second\" : \"" . $vid_second . "\"},"; ++$video_count; } } } } print("{"); print($video_jsondescrip); print("}"); } function displayVideosTABLE() { $video_count = 0; $video_table = ""; /*// print("<?xml version='" . $xml_version . "' encoding='" . $xml_encoding . "'?>"); */ header("Content-Type: text/html"); $my_videos = getVideosCreateArray(); rsort($my_videos); foreach($my_videos as $vidKey => $vidValue) { $video_table = $video_table . "<tr><td>" . $vidValue['vidDir'] . "-" . $vidValue['vidYear'] . $vidValue["vidMonth"] . $vidValue["vidDay"] . "</td><td>" . $vidValue['vidFile'] . "</td><td>" . $vidValue['vidMonth'] . "-" . $vidValue['vidDay'] . "-" . $vidValue['vidYear'] . "</td><td><button type=\"button\"onclick=\"parent.parent.playVideo('" . $vidValue['vidParentDir'] . "/" . $vidValue['vidFile'] . "'); return false;\">PLAY</button></td></tr>"; ++$video_count; } print("<html><head><title>Video Catalog</title></head><body>" . PHP_EOL); print("<table border=\"0\" cellpadding=\"2\" class=\"vidPlayer\">" . PHP_EOL); // print("<tr><th>ID</th><th>FILENAME</th><th>DATE</th><th>ACTION</th></tr>" . PHP_EOL); print($video_table); print("</body></html>" . PHP_EOL); } function selectDisplayVideo($m_selection) { // header("Content-Type: text/xml"); echo($m_selection); } ?> <?php if(empty($f)) { $f = $_GET["f"]; } switch ($f) { case "x": displayVideosXML(); break; case "j": displayVideosJSON(); break; case "t": displayVideosTABLE(); break; case "s": selectDisplayVideo($_GET["s"]); break; case "p": default: displayVideos(); } ?> <file_sep>/recordingview/vidSelection.php <?php header("Cache-Control: no-cache; must revalidate"); $v_selection = $_GET["s"]; echo("<videos count=\"1\"><video id=\"$v_selection\">$v_selection</video></videos>"); ?> <file_sep>/recordingview/vidPlayer.php <html> <head> <link rel="stylesheet" type="text/css" href="/css/videoplayer.css"> <script language="javascript" src="/scripts/js/videoplayer.js"> </script> <title>Acano Recordings Player Portal</title> </head> <body class="vidPlayer"> <center><div id="videoPlayer" name="videoPlayer" class="videoPlayer">VIDEO PLAYER WINDOW</div></center> <center><div id="videoListHeader" name="videoListHeader" class="videoListHeader"><table><th><td width="370">ID</td><td width="215">FILENAME</td><td width="75">DATE</td><td width="70">ACTION</td></th></table></div></center> <center><div id="videolList" name="videoList" class="videoList" style="background-color: grey; width: 800px; height: 280px; overflow: auto;"><?php $f=t; include 'vidList.php'; ?></div></center> </body> </html>
c9393ccb4f59eb5adc5b45f316f849ce5ab7cc9f
[ "JavaScript", "PHP" ]
4
JavaScript
macntouch/CMS_recordingsviewer
ef8fa5a08e4284a2ebab12d5ebc5eed2bc6ff8df
ee092399d17eacf01c76a70c5ce864f5c59df248
refs/heads/master
<file_sep># fdcontrols.rb # Controls on pallets # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'vr/vrmgdlayout' require 'fdvr/m17n' require 'fdvr/fdmodules' require 'fdvr/fdresources' require 'yaml' class Hash def << (h) self.update h end def + (h) r = self.clone; r.update h end end module FDControls include FDBmps include FDItems include FDFakeClass include FDModules include VRMarginedFrameUseable attr_reader(:prBevel) FDStruct=Struct.new :klass,:inst,:dflt_w,:dflt_h,:style,:required,:included, :createMethod,:info,:attrs,:events,:mthds,:mods,:popups,:items,:bmp, :default_style FDPallet = Struct.new(:title,:items) # Description of attribute metohd definition def controls_init # @prStyle = lambda{|c|"0x"+sprintf("%8X",c.style)} @prStyle = 'lambda{|c| st = (c.style|c.owndraw)-c._default_style st == 0 ? "default" : sprintf("%#x",st)}' @prExStyle = 'lambda{|c| c.exstyle.to_x}' @prFont = 'lambda{|c| getFontName(c)}' @prTab = 'lambda{|c| c.tab_order}' @prArray = 'lambda{|c| "click ->"}' @prMenuItem = 'lambda{|c| "click ->"}' @prModule = 'lambda{|c| "click ->"}' @prAccel = 'lambda{|c| if c.getaccel then "true" else "false" end}' @prCCS = 'lambda{|c| FDWStyle::CCSStr[c.style & 0x2f]}' @prOwnerDraw = 'lambda{|c| c.owndraw_used?}' @prLayout = 'lambda{|c| "click ->"}' @prBevel = 'lambda{|c| { VRMgdTwoPaneFrame::BevelNone=>"None", VRMgdTwoPaneFrame::BevelGroove1=>"Groove1", VRMgdTwoPaneFrame::BevelGroove2=>"Groove2", VRMgdTwoPaneFrame::BevelRaise1=>"Raise1", VRMgdTwoPaneFrame::BevelRaise2=>"Raise2", VRMgdTwoPaneFrame::BevelSunken1=>"Sunken1", VRMgdTwoPaneFrame::BevelSunken2=>"Sunken2"}[c.substance.bevel]}' std_attr = ["name","caption","x","y","w","h",["font",@prFont,:_btFont], ["style",@prStyle,:_btStyle],["exstyle",@prExStyle,:_btExStyle], ["modules",@prModule,:_btModule], ["tabOrder", @prTab,:_btTab], ["owndraw",@prOwnerDraw,:_cbOwnDraw]] =begin a = [ FDPallet["Standard",[ #klass,inst,dflt_w,dflt_h,style,required,included,createMethod,info,container FDStruct["VRButton","button",80,24,0,"vrcontrol",nil,:newFDCtrl,"Button", std_attr, #attrs ["clicked","dblclicked"], #events [ ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpButton,0x50000000 ], FDStruct["VREdit","edit",120,20,0,"vrcontrol",nil,:newFDCtrl,"Edit", std_attr, #attrs ["changed"], #events [ "text", "text=(str)","getSel","setSel(st,en,noscroll=0)","setCaret(r)", "replaceSel(newstr)","readonly=(b)","limit","modified","modified=(f)", "cut","copy","paste","clear","undo" ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpEdit,0x50000080 ], FDStruct["VRText","text",120,100,0,"vrcontrol",nil,:newFDCtrl,"Text", std_attr, #attrs ["changed"], #events [ "text", "text=(str)","getSel","setSel(st,en,noscroll=0)","setCaret(r)", "replaceSel(newstr)","readonly=(b)","limit","modified","modified=(f)", "cut","copy","paste","clear","undo" ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpText,0x50000044 ], FDStruct["VRCheckbox","checkBox",96,24,0,"vrcontrol",nil,:newFDCtrl,"CheckBox", std_attr, #attrs ["clicked","dblclicked"], #events ["checked?", "check(v)"],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpCheckbox,0x50000003 ], FDStruct["VRRadiobutton","radioBtn",96,24,0,"vrcontrol",nil,:newFDCtrl,"RadioButton", std_attr, #attrs ["clicked","dblclicked"], #events ["checked?", "check(v)"],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpRadiobutton,0x50000009 ], FDStruct["VRStatic","static",96,24,0,"vrcontrol",nil,:newFDCtrl,"StaticText", std_attr, #attrs [], #events [],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpStatic,0x50000000 ], FDStruct["VRListbox","listBox",120,120,0,"vrcontrol",nil,:newFDCtrl,"ListBox", std_attr, #attrs ["selchanged"], #events ["addString(idx,str)","deleteString(idx)","countStrings","clearStrings", "eachString{|i|}","setListStrings(strarray)","selectedString","select(idx)", "getTextOf(idx)","setDir(fname,opt=0)","findString(findstr,start=0)","getDataOf(idx)", "setDataOf(idx,data)"],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpListbox,0x50800001 ], FDStruct["VRCombobox","comboBox",120,80,0,"vrcontrol",nil,:newFDCombo,"ComboBox", std_attr[0..5]+["drop_h"]+std_attr[6..-1], #attrs ["selchanged"], #events ["addString(idx,str)","deleteString(idx)","countStrings","clearStrings", "eachString{|i|}","setListStrings(strarray)","selectedString","select(idx)", "getTextOf(idx)","setDir(fname,opt=0)","findString(findstr,start=0)","getDataOf(idx)", "setDataOf(idx,data)"],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpCombobox,0x50000203 ], FDStruct["VREditCombobox","edCmbBox",120,80,0,"vrcontrol",nil,:newFDCombo, "EditComboBox", std_attr[0..5]+["drop_h"]+std_attr[6..-1], #attrs ["selchanged"], #events ["addString(idx,str)","deleteString(idx)","countStrings","clearStrings", "eachString{|i|}","setListStrings(strarray)","selectedString","select(idx)", "getTextOf(idx)","setDir(fname,opt=0)","findString(findstr,start=0)","getDataOf(idx)", "setDataOf(idx,data)"],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpEdCombo,0x50000243 ], FDStruct["VRGroupbox","groupBox",120,120,0,"vrcontrol",nil,:newFDCtrl,"GroupBox", std_attr, #attrs [], #events [],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpGroupbox,0x50000007 ], FDStruct["VRPanel","panel",120,120,0,"vrcontrol",nil,:newFDCtrl,"Panel", std_attr[0..-3], #attrs [], #events [],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpPanel,0x50000000 ], FDStruct["VRCanvasPanel","canvaspanel",120,120,0,"vrcontrol",nil,:newFDCtrl,"CanvasPanel", std_attr[0..-3], #attrs [], #events ["createCanvas(w,h,color=0xffffff)","canvas"],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpCanvasPanel,0x50000000 ], FDStruct["VRBitmapPanel","bmppanel",120,120,0,"vrcontrol",nil,:newFDCtrl,"BmpPanel", std_attr[0..-3], #attrs [], #events ["loadFile(filename)", "createBitmap(info,bmp)" ,"bmp"],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpBitmapPanel,0x50000000 ] ]], FDPallet["Additonal",[ FDStruct["VRRichedit","richEdit",150,150,0,"vrrichedit",nil, :newFDCtrl,"RichEdit", std_attr[0..-2],#attrs ["changed"], [ "text", "text=(str)", "getSel", "setSel(st,en,noscroll=0)", "setCaret(r)", "replaceSel(newstr)", "readonly=(b)", "limit", "modified", "modified=(f)", "cut", "copy", "paste", "clear", "undo", "char2line(ptr)", "setTextFont(fontface,height=280,area=SCF_SELECTION)", "getTextFont(selarea=true)", "setTextColor(col,area=SCF_SELECTION)", "getTextColor(selarea=true)", "setBold(flag=true,area=SCF_SELECTION)", "setItalic(flag=true,area=SCF_SELECTION)", "setUnderlined(flag=true,area=SCF_SELECTION)", "setStriked(flag=true,area=SCF_SELECTION)", "bold?(selarea=true)", "italic?(selarea=true)", "underlined?(selarea=true)", "striked?(selarea=true)", "setAlignment(align)", "bkcolor=(color)", "selformat(area=SCF_SELECTION)", "selformat=(format)" ],#mthds StdModules,#mods [["font","setfont"]],#popups nil,#items BmpRichedit,0x50000004 ], FDStruct["VRToolbar","toolBar",150,26,0,"vrcomctl","VRToolbarUseable",:newFDToolbar,"Toolbar", std_attr[0..-3]+[["ccstyles",@prCCS,nil],["buttons",@prArray,:_btArray]], #attrs nil, #events [ "insertButton(i,name,style=TBSTYLE_BUTTON)", "addButton(style)", "deleteButton(i)", "clearButtons", "countButtons", "setImagelist(imglist)", "setParent(hwnd)", "autoSize", "indeterminateOf(i,bool=true)", "commandToIndex(id)", "enableButton(i,bool=true)", "getButtonStateOf(id)", "setButtonStateOf(i,state)", "setButtons(buttons)", "enumButtons" ],#mthds StdModules,#mods [["font","setfont"]],#popups FDItems::FDToolbarTemplate,#items BmpToolbar,0x50000001 ], FDStruct["VRRebar","rebar",150,32,0,"vrcomctl",nil,:newFDRebar,"Rebar", std_attr[0..-3]+[["buttons",@prArray,:_btArray]], #attrs ["layoutchanged"], #events [ "insertband(cntl,txt,minx=30,miny=cnt.h+2,band=-1)", "bkColor=(c)", "bkColor", "textColor=(c)", "textColor", "relayout(x=self.x, y=self.y, w=self.w, h=self.h)" ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpRebar,0x50000001 ], FDStruct["VRListview","listView",120,120,0,"vrcomctl",nil,:newFDCtrl,"Listview", std_attr+[["lvexstyle",'lambda{|c|c.lvexstyle.to_x}',:_btStyle]],#attrs ["itemchanged(idx,state)","itemchanging(idx,state)","columnclick(subitem)", "begindrag","beginrdrag"], #events [ "setViewMode(mode)", "getViewMode", "iconview", "reportview", "smalliconview", "listview", "setBkColor(color)", "bkcolor=(color)", "lvexstyle", "lvexstyle=(style)", "setListviewExStyle(style,mask=0xffffffff)", "insertColumn(column,text,width=50,format=0,textsize=title.size)", "deleteColumn(column)", "clearColumns", "countColumns", "addColumn(text,width=50,format=0,textsize=title.size)", "setImagelist(imagelist,itype=0)", "setItemIconOf(hitem,img)", "getItemIconOf(hitem)", "getColumnWidthOf(column)", "setColumnWidthOf(column,width)", "getColumnTextOf(column)", "setColumnTextOf(column,text)", "getColumnFormatOf(column)", "setColumnFormatOf(column,format)", "insertItem(index,texts,lparam=0,textsize=128)", "addItem(texts,lparam=0,textsize=128)", "insertMultiItems(index,multitexts)", "deleteItem(idx)", "clearItems" , "countItems", "hittest(x,y)", "hittest2(x,y)", "getItemRect(idx)", "getItemStateOf(idx)", "setItemStateOf(idx,state)", "selectItem(idx,flag) ", "getNextItem(start,flags)", "focusedItem", "getItemTextOf(idx,subitem=0,textsize=128)", "setItemTextOf(idx,subitem,text,textsize=text.size)", "getItemLParamOf(idx)", "setItemLParamOf(idx,lparam)", "selected?(idx)", "focused?(idx)", "eachSelectedItems", "countSelectedItems()", "ensureVisible(i,partial=true)", ],#mthds StdModules,#mods [["font","setfont"]],#popups nil,#items BmpListview,0x50000001 ], FDStruct["VRTreeview","treeView",120,120,0,"vrcomctl",nil,:newFDCtrl,"Treeview", std_attr[0..-2],#attrs [ "selchanged(hitem,lparam)", "itemexpanded(hitem,state,lparam)", "deleteitem(hitem,lparam)", "begindrag(hitem,state,lparam)", "beginrdrag(hitem,state,lparam)" ],#events [ "insertItem(hparent,hafter,text,lparam=0,textsize=text.size)", "insertMultiItems(hparent,hafter,items)", "addItem(hparent,text,lparam=0,textsize=text.size)", "addMultiItems(hparent,items)", "deleteItem(hitem)", "clearItems", "countItems", "selectItem(hitem)", "indent", "indent=", "hittest(x,y)", "hittest2(x,y)", "getNextItem(hitem,code)", "topItem", "root", "last", "selectedItem()", "getParentOf(hitem)", "getChildOf(hitem)", "getNextSiblingOf(hitem)", "setImagelist(imagelist)", "setItemIconOf(hitem,img,simg)", "getItemIconOf(hitem)", "setItemLParamOf(hitem,lparam)", "getItemLParamOf(hitem)", "setItemTextOf(hitem,text)", "getItemTextOf(hitem,textsize=128)", "setItemStateOf(hitem,state)", "getItemStateOf(hitem)" ],#mthds StdModules,#mods [["font","setfont"]],#popups nil,#items BmpTreeview,0x5000000f ], FDStruct["VRProgressbar","prgrssBar",120,20,0,"vrcomctl",nil,:newFDCtrl,"Progressbar", std_attr[0..-3], #attrs [], #events [ "setRange(minr,maxr)","position","position=(pos)","stepwidth=(st)","step","advance(n=1)" ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpProgressbar,0x50000000 ], FDStruct["VRTrackbar","trackBar",120,25,0,"vrcomctl",nil,:newFDCtrl,"Trackbar", std_attr[0..-2], #attrs [], #events [ "position", "position=(pos)", "linesize", "linesize=(s)", "pagesize", "pagesize=(p)", "rangeMin", "rangeMin=(m)", "rangeMax", "rangeMax=(m)", "selStart", "selStart=(m)", "selEnd", "selEnd=(m)", "clearSel", ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpTrackbar,0x50000000 ], FDStruct["VRUpdown","updown",25,16,0,"vrcomctl",nil,:newFDCtrl,"Updown", std_attr[0..-3], #attrs ["changed(pos)"], #events [ "setRange(minr,maxr)", "getRange", "position", "position=", "base", "base=(b)", ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpUpdown,0x50000000 ], FDStruct["VRStatusbar","statusbar",120,25,0,"vrcomctl",nil,:newFDCtrl,"Statusbar", std_attr[0..-3], #attrs [], #events [ "setparts(p,width=[-1])", "parts", "getTextOf(idx)", "setTextOf(idx,text,style=0)", "getRectOf(idx)", "minheight=(minh)" ],#mthds StdModules,#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpStatusbar,0x50000000 ], FDStruct["VRTabControl","tabControl",140,45,0,"vrcomctl",nil,:newFDCtrl,"TabControl", std_attr[0..-3]+[["owndraw",@prOwnerDraw,:_cbOwnDraw]], #attrs ["selchanged"], #events [ "insertTab(index,text,textmax=text.size,lparam=0)", "clearTabs", "deleteTab(idx)", "countTabs", "selectedTab", "selectTab(idx)", "setImagelist(imagelist)", "setTabSize(width,height)", "getTabRect(i)", "adjustRect(x,y,w,h,flag=false)", "getTabTextOf(idx)", "setTabTextOf(idx,text)", "getTabImageOf(idx)", "setTabImageOf(idx,image)", "getTabLParamOf(idx)", "setTabLParamOf(idx,lparam)" ],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups nil,#items BmpTabControl,0x54000000 ], FDStruct["VRTabbedPanel","tabPanel",140,140,0,"vrcomctl",nil,:newFDTabbedPanel,"TabbedPanel", std_attr[0..-3] + [["pages",@prArray,:_btArray], ["owndraw",@prOwnerDraw,:_cbOwnDraw]], #attrs ["selchanged"], #events [ "setupPanels(title-1,title-2,title-3,....)", "send_parent2(idx,controlname,eventname)", "panels", "insertTab(index,text,textmax=text.size,lparam=0)", "clearTabs", "deleteTab(idx)", "countTabs", "selectedTab", "selectTab(idx)", "setImagelist(imagelist)", "setTabSize(width,height)", "getTabRect(i)", "adjustRect(x,y,w,h,flag=false)", "getTabTextOf(idx)", "setTabTextOf(idx,text)", "getTabImageOf(idx)", "setTabImageOf(idx,image)", "getTabLParamOf(idx)", "setTabLParamOf(idx,lparam)" ],#mthds StdModules.merge(ParentModules),#mods [["font","setfont"],["color","setcolor"]],#popups ['tab1','tab2'],#items BmpTabbedPanel,0x54000000 ], FDStruct["VRMediaView","mmedia",200,26,0,"vrmmedia","VRMediaViewModeNotifier", :newFDCoverd,"MediaView,", std_attr[0..-3], #attrs [ "onerror()", "modechanged(newmode)", "sizechanged()", "mediachanged(str)", ], #events [ "mediaopen(filename,flag=0)", "mediaclose", "mode", "modestring(n)", "errorstring", "play", "pause", "stop", "eject", "step(n=1)", "seek(pos)", "seekHome", "seekEnd", "playable?", "ejectable?", "window?", "length", "position", "volume", "volume=(vl)", "speed", "speed=", "zoom", "zoom=" ],#mthds StdModules,#mods [],#popups nil,#items BmpMmedia,0x50005d80 ] ]], FDPallet["System" ,[ FDStruct["VRMenu","mainmenu",24,24,0,"vrcontrol","VRMenuUseable",:newFDMenu,"Menu", ["name","caption","x","y",["accel",@prAccel,:_cbTF],["menus",@prMenuItem,:_btArray]], nil, ["append(caption,state)", "insert(ptr,caption,state)", "delete(id)", "count", "set(sarr)" ],#mthds nil,#mods [["addItem","addItem"]], FDItems::FDMenuTemplate,#items BmpMenu ], FDStruct["FDPopup","popupmenu",24,24,0,"vrcontrol","VRMenuUseable",:newFDPopup,"PopupMenu", ["name","caption","x","y",["menus",@prMenuItem,:_btArray]], nil, ["showPopup(menu)", "append(caption,state)", "insert(ptr,caption,state)", "delete(id)", "count", "set(sarr)" ],#mthds nil,#mods [["addItem","addItem"]], FDItems::FDPopupMenuTemplate,#items #FDItems::FDMenuTemplate,#items BmpPopupMenu ], FDStruct["FDOpenDlg","openDlg",24,24,0,nil,nil,:newFDOpenSaveDlg,"OpenDlg", ["name","caption","x","y", ["filters",@prArray,:_btArray],["flags",@prArray,:_btArray], "title","defaultExt"], #attrs [], #events ["openFilenameDialog(*arg)"],#mthds nil,#mods [],#popups nil,#items BmpOpenDlg ], FDStruct["FDSaveDlg","saveDlg",24,24,0,nil,nil,:newFDOpenSaveDlg,"SaveDlg", ["name","caption","x","y", ["filters",@prArray,:_btArray],["flags",@prArray,:_btArray],"title","defaultExt"], #attrs [], #events ["saveFilenameDialog(*arg)"],#mthds nil,#mods [],#popups nil,#items BmpSaveDlg ], FDStruct["FDSelectDir","selectDirectory",24,24,0,nil,nil,:newFDSelectDir,"SelectDirectory", ["name","caption","x","y","title","initialdir",["flags",@prArray,:_btArray]], #attrs [], #events ["selectDirectory(*arg)"],#mthds nil,#mods [],#popups nil,#items BmpFolder ], FDStruct["FDFontDlg","fontDlg",24,24,0,nil,nil,:newFDModule,"FontDlg", ["name","caption","x","y"], #attrs [], #events ["chooseFontDialog(*arg)"],#mthds nil,#mods [],#popups nil,#items BmpFontDlg ], FDStruct["FDColorDlg","colorDlg",24,24,0,nil,nil,:newFDModule,"ColorDlg", ["name","caption","x","y"], #attrs [], #events ["chooseColorDialog(*arg)"],#mthds nil,#mods [],#popups nil,#items BmpColorDlg ] ]], FDPallet["Layout",[ FDStruct["VRMgdHorizTwoPaneFrame","horiz2Pane",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFD2Pane, "Horiz2Pane",["name","caption","x","y",["register",@prLayout,:_btLayout], ["ratio",'lambda{|c|c.substance.ratio}',"self.ratio"], ["position",'lambda{|c|c.substance.position}',"self.position"], ["gap",'lambda{|c|c.substance.gap}',"num"], ["bevel",@prBevel,:_cbBevel], ["lLimit",'lambda{|c|c.substance.lLimit}',"num"], ["rLimit",'lambda{|c|c.substance.rLimit}',"num"] ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpHoriz2Pane ], FDStruct["VRMgdVertTwoPaneFrame","vert2Pane",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFD2Pane, "Vert2Pane",["name","caption","x","y",["register",@prLayout,:_btLayout], ["ratio",'lambda{|c|c.substance.ratio}',"self.ratio"], ["position",'lambda{|c|c.substance.position}',"self.position"], ["gap",'lambda{|c|c.substance.gap}',"num"], ["bevel",@prBevel,:_cbBevel], ["uLimit",'lambda{|c|c.substance.uLimit}',"num"], ["lLimit",'lambda{|c|c.substance.lLimit}',"num"] ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpVert2Pane ], FDStruct["VRMgdFullsizeLayoutFrame","fullsize",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFDLayout, "FullsizeFrame",["name","caption","x","y",["register",@prLayout,:_btLayout], ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpFullsize ], FDStruct["VRMgdHorizLayoutFrame","horizFrame",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFDLayout, "HorizFrame",["name","caption","x","y",["register",@prLayout,:_btLayout], ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpHorizFrame ], FDStruct["VRMgdVertLayoutFrame","vertFrame",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFDLayout, "VertFrame", ["name","caption","x","y",["register",@prLayout,:_btLayout], ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpVertFrame ], FDStruct["VRMgdGridLayoutFrame","gridFrame",24,24,0,'vrmgdlayout', "VRMarginedFrameUseable",:newFDLayout, "GridFrame",["name","caption","x","y",["register",@prLayout,:_btLayout], ["xsize",'lambda{|c|c.substance.instance_eval "@_vr_xsize"}',"@_vr_xsize"], ["ysize",'lambda{|c|c.substance.instance_eval "@_vr_ysize"}',"@_vr_ysize"] ], #attrs [], #events [],#mthds nil,#mods [],#popups nil,#items BmpGridFrame ], ]]] =end if defined? ExerbRuntime a = YAML.load(ExerbRuntime.open('fddefault.yml')) else a = YAML.load_file($program_dir + '/fddefault.yml') end a.each{|i| i.items.each{|j| j.klass = eval(j.klass) j.attrs = j.attrs.map{|i| if i.is_a? Array; [i[0], i[1].is_a?(Proc) ? i[1] : eval(i[1]) ,i[2]] else i end } j.bmp = Zlib::Inflate.inflate(j.bmp.unpack('m')[0]) } } a end end <file_sep># fdwstyle.rb # The wondow styles of controls # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> module FDWStyle WStyles ={ "WS_BORDER" => 0x800000, # "WS_CAPTION" => 0xc00000, # "WS_CHILD" => 0x40000000, # "WS_CHILDWINDOW" => 0x40000000, # "WS_CLIPCHILDREN" => 0x2000000, # "WS_CLIPSIBLINGS" => 0x4000000, "WS_DISABLED" => 0x8000000, # "WS_DLGFRAME" => 0x400000, "WS_GROUP" => 0x20000, "WS_HSCROLL" => 0x100000, # "WS_ICONIC" => 0x20000000, # "WS_MAXIMIZE" => 0x1000000, # "WS_MAXIMIZEBOX" => 0x10000, # "WS_MINIMIZE" => 0x20000000, # "WS_MINIMIZEBOX" => 0x20000, # "WS_OVERLAPPED" => 0, # "WS_OVERLAPPEDWINDOW" => 0xcf0000, # "WS_POPUP" => 0x80000000, # "WS_POPUPWINDOW" => 0x80880000, # "WS_SIZEBOX" => 0x40000, # "WS_SYSMENU" => 0x80000, # "WS_TABSTOP" => 0x10000, "WS_THICKFRAME" => 0x40000, # "WS_TILED" => 0, # "WS_TILEDWINDOW" => 0xcf0000, # "WS_VISIBLE" => 0x10000000, "WS_VSCROLL" => 0x200000} CtlStyles = { VRButton => { :style=>{ "BS_DEFPUSHBUTTON" => 0x01, # "BS_OWNERDRAW" => 0x0b, "BS_BITMAP" => 128, "BS_BOTTOM" => 0x800, "BS_CENTER" => 0x300, "BS_LEFT" => 256, "BS_RIGHT" => 512, "BS_TOP" => 0x400, "BS_VCENTER" => 0xc00, "BS_FLAT" => 0x8000, "BS_MULTILINE" => 0x2000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VREdit => { :style=>{ "ES_AUTOHSCROLL" => 128, "ES_AUTOVSCROLL" => 64, "ES_CENTER" => 1, "ES_LOWERCASE" => 16, # "ES_MULTILINE" => 4, "ES_NOHIDESEL" => 256, "ES_NUMBER" => 0x2000, "ES_OEMCONVERT" => 0x400, "ES_PASSWORD" => 32, "ES_READONLY" => 0x800, "ES_RIGHT" => 2, "ES_UPPERCASE" => 8, "ES_WANTRETURN" => 4096, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VRText => { :style=>{ "ES_AUTOHSCROLL" => 128, "ES_AUTOVSCROLL" => 64, # "ES_CENTER" => 1, "ES_LOWERCASE" => 16, # "ES_MULTILINE" => 4, "ES_NOHIDESEL" => 256, "ES_NUMBER" => 0x2000, "ES_OEMCONVERT" => 0x400, "ES_PASSWORD" => 32, "ES_READONLY" => 0x800, # "ES_RIGHT" => 2, "ES_UPPERCASE" => 8, "ES_WANTRETURN" => 4096, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VRCheckbox => { :style=>{ "BS_RIGHTBUTTON" => 32, "WS_BORDER" => 0x800000, "WS_DISABLED" => 0x8000000, "WS_GROUP" => 0x20000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VRRadiobutton => { :style=>{ "BS_RIGHTBUTTON" => 32, "WS_BORDER" => 0x800000, "WS_DISABLED" => 0x8000000, "WS_GROUP" => 0x20000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VRStatic => { :style=>{ "SS_NOPREFIX" => 128, "SS_NOTIFY" => 256, "SS_CENTERIMAGE" => 512, "SS_RIGHTJUST" => 0x400, "SS_REALSIZEIMAGE" => 0x800, "SS_SUNKEN" => 4096, "WS_BORDER" => 0x800000, "WS_THICKFRAME" => 0x40000, }, :option =>{ "SS_LEFT" => 0, "SS_CENTER" => 1, "SS_RIGHT" => 2, "SS_ICON" => 3, "SS_BLACKRECT" => 4, "SS_GRAYRECT" => 5, "SS_WHITERECT" => 6, "SS_BLACKFRAME" => 7, "SS_GRAYFRAME" => 8, "SS_WHITEFRAME" => 9, "SS_USERITEM" => 10, "SS_SIMPLE" => 11, "SS_LEFTNOWORDWRAP" => 12, "SS_OWNERDRAW" => 13, "SS_BITMAP" => 14, "SS_ENHMETAFILE" => 15, "SS_ETCHEDHORZ" => 16, "SS_ETCHEDVERT" => 17, "SS_ETCHEDFRAME" => 18, } }, VRListbox => { :style=>{ # "LBS_NOTIFY" => 1, "LBS_SORT" => 2, "LBS_NOREDRAW" => 4, "LBS_MULTIPLESEL" => 8, # "LBS_OWNERDRAWFIXED" => 0x10, # "LBS_OWNERDRAWVARIABLE" => 0x20, "LBS_HASSTRINGS" => 0x40, "LBS_USETABSTOPS" => 0x80, "LBS_NOINTEGRALHEIGHT" => 0x100, "LBS_MULTICOLUMN" => 0x200, "LBS_WANTKEYBOARDINPUT" => 0x400, "LBS_EXTENDEDSEL" => 0x800, "LBS_DISABLENOSCROLL" => 0x1000, "LBS_NODATA" => 0x2000, "LBS_NOSEL" => 0x4000, # "LBS_STANDARD" => 0xa00003, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VRCombobox => { :style=>{ # "CBS_SIMPLE" => 1, # "CBS_DROPDOWN" => 2, # "CBS_DROPDOWNLIST" => 3, # "CBS_OWNERDRAWFIXED" => 0x10, # "CBS_OWNERDRAWVARIABLE" => 0x20, "CBS_AUTOHSCROLL" => 0x40, "CBS_OEMCONVERT" => 0x80, "CBS_SORT" => 0x100, "CBS_HASSTRINGS" => 0x200, "CBS_NOINTEGRALHEIGHT" => 0x400, "CBS_DISABLENOSCROLL" => 0x800, "CBS_UPPERCASE" => 0x2000, "CBS_LOWERCASE" => 0x4000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VREditCombobox => { :style=>{ # "CBS_SIMPLE" => 1, # "CBS_DROPDOWN" => 2, # "CBS_DROPDOWNLIST" => 3, # "CBS_OWNERDRAWFIXED" => 0x10, # "CBS_OWNERDRAWVARIABLE" => 0x20, "CBS_AUTOHSCROLL" => 0x40, "CBS_OEMCONVERT" => 0x80, "CBS_SORT" => 0x100, "CBS_HASSTRINGS" => 0x200, "CBS_NOINTEGRALHEIGHT" => 0x400, "CBS_DISABLENOSCROLL" => 0x800, "CBS_UPPERCASE" => 0x2000, "CBS_LOWERCASE" => 0x4000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VRGroupbox => { :style=>{ "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000, }, :option =>{} }, VRRichedit => { :style => { "ES_DISABLENOSCROLL" => 8192, "ES_EX_NOCALLOLEINIT" =>16777216, "ES_NOIME" =>524288, "ES_SAVESEL" =>32768, "ES_SELFIME" =>262144, "ES_SUNKEN" =>16384, "ES_VERTICAL" =>4194304, "ES_SELECTIONBAR" =>16777216, "ES_AUTOHSCROLL" => 128, "ES_AUTOVSCROLL" => 64, "ES_CENTER" => 1, "ES_MULTILINE" => 4, "ES_NOHIDESEL" => 256, "ES_READONLY" => 0x800, "ES_RIGHT" => 2, "ES_WANTRETURN" => 4096, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option => {} }, VRToolbar => { :style=>{ "TBSTYLE_TOOLTIPS" => 256, "TBSTYLE_WRAPABLE" => 512, "TBSTYLE_ALTDRAG" => 1024, "TBSTYLE_FLAT" => 2048, }, :option =>{ "CCS_TOP" => 1, "CCS_NOMOVEY" => 2, "CCS_BOTTOM" => 3, "CCS_NORESIZE" => 4, "CCS_NOPARENTALIGN" => 8, "CCS_ADJUSTABLE" => 32, "CCS_NODIVIDER" => 64 } }, VRRebar => { :style=>{ "RBS_TOOLTIPS" => 256, "RBS_VARHEIGHT" => 512, "RBS_BANDBORDERS" => 1024, "RBS_FIXEDORDER" => 2048, }, :option =>{ "CCS_TOP" => 1, "CCS_NOMOVEY" => 2, "CCS_BOTTOM" => 3, "CCS_NORESIZE" => 4, "CCS_NOPARENTALIGN" => 8, "CCS_ADJUSTABLE" => 32, "CCS_NODIVIDER" => 64 } }, VRListview => { :style=>{ #"LVS_TYPEMASK" => 3, "LVS_SINGLESEL" => 4, "LVS_SHOWSELALWAYS" => 8, "LVS_SORTASCENDING" => 0x10, "LVS_SORTDESCENDING" => 0x20, "LVS_SHAREIMAGELISTS" => 0x40, "LVS_NOLABELWRAP" => 0x80, "LVS_AUTOARRANGE" => 0x100, "LVS_EDITLABELS" => 0x200, "LVS_NOSCROLL" => 0x2000, "LVS_TYPESTYLEMASK" => 0xfc00, #"LVS_ALIGNTOP" => 0, "LVS_ALIGNLEFT" => 0x800, "LVS_ALIGNMASK" => 0xc00, #"LVS_OWNERDRAWFIXED" => 0x400, "LVS_NOCOLUMNHEADER" => 0x4000, "LVS_NOSORTHEADER" => 0x8000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{ "LVS_ICON" => 0, "LVS_REPORT" => 1, "LVS_SMALLICON" => 2, "LVS_LIST" => 3 } }, VRTreeview => { :style => { "TVS_HASLINES" => 2, "TVS_LINESATROOT" => 4, "TVS_EDITLABELS" => 8, "TVS_DISABLEDRAGDROP" => 16, "TVS_SHOWSELALWAYS" => 32, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VRProgressbar => { :style=>{ "WS_BORDER" => 0x800000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VRTrackbar => { :style=>{ "TBS_VERT" => 2, # "TBS_HORZ" => 0, "TBS_TOP" => 4, # "TBS_BOTTOM" => 0, "TBS_LEFT" => 4, # "TBS_RIGHT" => 0, "TBS_BOTH" => 8, "TBS_NOTICKS" => 16, "TBS_ENABLESELRANGE" => 32, "TBS_FIXEDLENGTH" => 64, "TBS_NOTHUMB" => 128, "WS_BORDER" => 0x800000, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :toggle => ["TBS_VERT", "TBS_TOP", "TBS_LEFT"], :option =>{} }, VRUpdown => { :style=>{ "UDS_WRAP" => 1, "UDS_SETBUDDYINT" => 2, "UDS_ALIGNRIGHT" => 4, "UDS_ALIGNLEFT" => 8, "UDS_AUTOBUDDY" => 16, "UDS_ARROWKEYS" => 32, "UDS_HORZ" => 64, "UDS_NOTHOUSANDS" => 128, "WS_DISABLED" => 0x8000000, "WS_THICKFRAME" => 0x40000 }, :option =>{} }, VRStatusbar => { :style=>{ "SBARS_SIZEGRIP" => 256 }, :option =>{ "CCS_TOP" => 1, "CCS_NOMOVEY" => 2, "CCS_BOTTOM" => 3, "CCS_NORESIZE" => 4, "CCS_NOPARENTALIGN" => 8, "CCS_ADJUSTABLE" => 32, "CCS_NODIVIDER" => 64, "WS_DISABLED" => 0x8000000, } }, VRTabControl => { :style=>{ "TCS_FORCEICONLEFT" => 16, "TCS_FORCELABELLEFT" => 32, # "TCS_TABS" => 0, "TCS_BUTTONS" => 256, # "TCS_SINGLELINE" => 0, "TCS_MULTILINE" => 512, # "TCS_RIGHTJUSTIFY" => 0, "TCS_FIXEDWIDTH" => 1024, "TCS_RAGGEDRIGHT" => 2048, "TCS_FOCUSONBUTTONDOWN" => 0x1000, #"TCS_OWNERDRAWFIXED" => 0x2000, "TCS_TOOLTIPS" => 0x4000, "TCS_FOCUSNEVER" => 0x8000, "TCS_BOTTOM" => 2, "TCS_RIGHT" => 2, "TCS_VERTICAL" => 128, "TCS_HOTTRACK" => 0x0040, "WS_DISABLED" => 0x8000000, }, :toggle => ["TCS_VERTICAL", "TCS_BOTTOM", "TCS_RIGHT"], :option =>{} }, VRTabbedPanel => { :style=>{ "TCS_FORCEICONLEFT" => 16, "TCS_FORCELABELLEFT" => 32, # "TCS_TABS" => 0, #"TCS_BUTTONS" => 256, # "TCS_SINGLELINE" => 0, "TCS_MULTILINE" => 512, # "TCS_RIGHTJUSTIFY" => 0, "TCS_FIXEDWIDTH" => 1024, "TCS_RAGGEDRIGHT" => 2048, "TCS_FOCUSONBUTTONDOWN" => 0x1000, #"TCS_OWNERDRAWFIXED" => 0x2000, "TCS_TOOLTIPS" => 0x4000, "TCS_FOCUSNEVER" => 0x8000, "TCS_BOTTOM" => 2, "TCS_RIGHT" => 2, "TCS_VERTICAL" => 128, "TCS_HOTTRACK" => 0x0040, "WS_DISABLED" => 0x8000000, }, :toggle => ["TCS_VERTICAL", "TCS_BOTTOM", "TCS_RIGHT"], :option =>{} } } LVMStr = { 0 => "LVS_ICON", 1 => "LVS_REPORT", 2 => "LVS_SMALLICON", 3 => "LVS_LIST" } LVMConst = { "LVS_ICON" => 0, "LVS_REPORT" => 1, "LVS_SMALLICON" => 2, "LVS_LIST" => 3 } CCSStr = { 1 => "CCS_TOP", 2 => "CCS_NOMOVEY", 3 => "CCS_BOTTOM", 4 => "CCS_NORESIZE", 8 => "CCS_NOPARENTALIGN", 0x20 => "CCS_ADJUSTABLE", 0x40 => "CCS_NODIVIDER" } CCSConst= { "CCS_TOP" => 1, "CCS_NOMOVEY" => 2, "CCS_BOTTOM" => 3, "CCS_NORESIZE" => 4, "CCS_NOPARENTALIGN" => 8, "CCS_ADJUSTABLE" => 0x20, "CCS_NODIVIDER" => 0x40 } end module FDExStyle ExStyles = { 'WS_EX_ACCEPTFILES' => 16, 'WS_EX_APPWINDOW' => 0x40000, 'WS_EX_CLIENTEDGE' => 512, 'WS_EX_COMPOSITED' => 0x2000000, # XP 'WS_EX_CONTEXTHELP' => 0x400, 'WS_EX_CONTROLPARENT' => 0x10000, 'WS_EX_DLGMODALFRAME' => 1, 'WS_EX_LAYERED' => 0x80000, # w2k 'WS_EX_LAYOUTRTL' => 0x400000, # w98, w2k 'WS_EX_LEFT' => 0, 'WS_EX_LEFTSCROLLBAR' => 0x4000, 'WS_EX_LTRREADING' => 0, 'WS_EX_MDICHILD' => 64, 'WS_EX_NOACTIVATE' => 0x8000000, # w2k 'WS_EX_NOINHERITLAYOUT' => 0x100000, # w2k 'WS_EX_NOPARENTNOTIFY' => 4, 'WS_EX_OVERLAPPEDWINDOW' => 0x300, 'WS_EX_PALETTEWINDOW' => 0x188, 'WS_EX_RIGHT' => 0x1000, 'WS_EX_RIGHTSCROLLBAR' => 0, 'WS_EX_RTLREADING' => 0x2000, 'WS_EX_STATICEDGE' => 0x20000, 'WS_EX_TOOLWINDOW' => 128, 'WS_EX_TOPMOST' => 8, 'WS_EX_TRANSPARENT' => 32, 'WS_EX_WINDOWEDGE' => 256 } CtlExStyles = { VRListview => { 'LVS_EX_CHECKBOXES' => 4, 'LVS_EX_FULLROWSELECT' => 32, 'LVS_EX_GRIDLINES' => 1, 'LVS_EX_HEADERDRAGDROP' => 16, 'LVS_EX_ONECLICKACTIVATE' => 64, 'LVS_EX_SUBITEMIMAGES' => 2, 'LVS_EX_TRACKSELECT' => 8, 'LVS_EX_TWOCLICKACTIVATE' => 128, # 'LVSICF_NOINVALIDATEALL' => 0x00000001, # 'LVSICF_NOSCROLL' => 0x00000002, #if( _WIN32_IE >= 0x0400 ) 'LVS_EX_FLATSB' => 0x00000100, 'LVS_EX_REGIONAL' => 0x00000200, 'LVS_EX_INFOTIP' => 0x00000400, 'LVS_EX_UNDERLINEHOT' => 0x00000800, 'LVS_EX_UNDERLINECOLD' => 0x00001000, 'LVS_EX_MULTIWORKAREAS' => 0x00002000, #endif /* _WIN32_IE >=0x0400 */ #if( _WIN32_IE >= 0x0500 ) 'LVS_EX_LABELTIP' => 0x00004000, 'LVS_EX_BORDERSELECT' => 0x00008000, }, VRToolbar => { }, VRTabControl => { } } end module FDOwnerDraw ODConst={ VRButton=>{'use'=>0x0b}, VRListbox=>{'fixed'=>0x10,'variable'=>0x20}, VRCombobox=>{'fixed'=>0x10,'variable'=>0x20}, VREditCombobox=>{'fixed'=>0x10,'variable'=>0x20}, VRListview=>{'fixed'=>0x400}, VRTabControl=>{'fixed'=>0x2000}, VRTabbedPanel=>{'fixed'=>0x2000} } end <file_sep># fdmodules.rb # Modules for which add to controls # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> module FDModules FDMod = Struct.new(:events,:methods,:requires) FormModules = { :VRDestroySensitive => FDMod[['self_destroy'],[],'vrhandler'], :VRClosingSensitive => FDMod[['self_close'],[],'vrhandler'], :VRClipboardObserver => FDMod[['self_drawclipboard'],[],'vrclipboard'] } ParentModules = { :VRMessageParentRelayer => FDMod[[],[],''] } StdModules = { :VRDrawable => FDMod[['self_paint'],[]], # :VRMessageHandler => FDMod[[],['acceptEvents(ev_array)', # 'addHandler(msg,handlername,argtype,argparsestr)']], :VRResizeSensitive => FDMod[['self_resize(w,h)'],[]], :VRMouseFeasible => FDMod[[ 'self_lbuttonup(shift,x,y)', 'self_lbuttondown(shift,x,y)', 'self_rbuttonup(shift,x,y)', 'self_rbuttondown(shift,x,y)', 'self_mousemove(shift,x,y)', ],[],'vrhandler'], :VRFocusSensitive => FDMod[[ 'self_gotfocus()', 'self_lostfocus()' ],[],'vrhandler'], :VRKeyFeasible => FDMod[[ 'self_char(keycode,keydata)', 'self_deadchar(keycode,keydata)', 'self_syschar(keycode,keydata)', 'self_sysdeadchar(keycode,keydata)' ],[],'vrhandler'], :VROwnerDrawControlContainer => FDMod[[],[],'vrowndraw'], :VRDropFileTarget => FDMod[['self_dropfiles(files)'],[],'vrddrop'], :VRDragFileSource => FDMod[['dragStart(files)'],[],'vrddrop'] } MMModules = { :VRMediaViewModeNotifier => FDMod[[],[],''] } end <file_sep># m17n.rb # Multilingualization Module # # Programmed by <EMAIL> # Copyright 2001-2004 <NAME> require 'vr/vrcontrol' require 'vr/vrcomctl' module EN HTML_Help=$program_dir.gsub(/\//,'\\')+'\doc\vrswin-en.chm' module FDItems FDMenuTemplate= [ ["&File", [ ["&New\tCtrl+N","new"], ["&Open","open"], ["&Save","save"], ["Save&As","saveas"], VRMenu::SEPARATOR, ["E&xit","exit"]]], ["&Edit", [ ["&Delete","doDelete"], ["Cu&t","cut"], ["&Copy","copy"], ["&Paste","paste"]]], ["&Help", [ ["Versio&n","version"]]] ] FDPopupMenuTemplate=[["&Delete\tDelete","doDelete"],VRMenu::SEPARATOR, ["&Copy\tCtrl+C","doCopy"],["&Paste\tCtrl+V","doPaste"]] FDToolbarTemplate = [['toolButton1'], ['toolButton2',WConst::TBSTYLE_SEP], ['toolButton3',WConst::TBSTYLE_CHECKGROUP], ['toolButton4',WConst::TBSTYLE_CHECKGROUP], ['toolButton5',WConst::TBSTYLE_CHECKGROUP]] FDDlgFilterTemplate=[["all(*.*)","*.*"]] end module FDMenuItems FDMainmenu=[ ["&File", [ ["&NewForm\tCtrl+N", [ ["Form","new_form"], ["ModelessForm","new_modeless_form"], ["ModelessDialog","new_modeless_dlg"]]], ["&Open\tCtrl+O","open"], ["OpenWith&RDE\tCtrl+R","open_rde"], ["ChangeMainformType", [ ["Form","change_to_mainform"], ["ModelessForm","change_to_modeless_mainform"], ["ModelessDialog","change_to_modeless_maindlg"]]], ["&Save\tCtrl+S","save"], ["Save&As", [ ["FormsOnly","saveas_form"], ["ProjectWithSeparated Forms","saveas_proj_part"], ["ProjectWithBuiltForms","saveas_proj_mono"]]], VRMenu::SEPARATOR, ["&EditProject\tCtrl+E","run_editor"], ["Update&Project","update_proj"], VRMenu::SEPARATOR, ["E&xit\tAlt+F4","exit"]]], ["&Insert", [ ["Form","insert_form"], ["Mode&lessForm","insert_modelessform"], ["&ModalForm","insert_modalform"], ["ChangeFormType", [ ["Form","change_to_form"], ["ModelessForm","change_to_modeless_form"], ["ModalForm","change_to_modal_form"]]], VRMenu::SEPARATOR, ["ReadFromFile","insert_form_from_file"], ["SaveThisForm","save_this_form"], VRMenu::SEPARATOR, ["&DeleteThisForm","delete_this_form"]]], ["&Edit", [ ["&Delete\tDelete","doDelete"], VRMenu::SEPARATOR, ["Cu&t\tCtrl+X","doCut"], ["&Copy\tCtrl+C","doCopy"], ["&Paste\tCtrl+V","doPaste"], VRMenu::SEPARATOR, ["&BackToParent\tHome","back_to_parent"]]], ["&Window", [ VRMenu::SEPARATOR, ["&Inspect","inspectShow",VRMenuItem::CHECKED]]], ["&Run", [ ["E&xecute\tF5","execute"], ["Examine","examine"]]], ["&Option", [ ["&Preferences","prefer"], VRMenu::SEPARATOR, ["Grid","gridState",VRMenuItem::CHECKED]]], ["&Tool", [ ["Bmp2Str","bmp2str"]]], ["&Help", [ ["&Show topic\tF1","show_topic"], ["&Show SDKtopic\tF2","show_SDK_topic"], ["Versio&n","version"]]] ] FDPopupmenu=[ ["&Delete\tDelete","doDeletepop"], VRMenu::SEPARATOR, ["Cu&t\tCtrl+X","doCutpop"], ["&Copy\tCtrl+C","doCopypop"], ["&Paste\tCtrl+V","doPastepop"], VRMenu::SEPARATOR, ["&BackToParent\tHome","back_to_parentpop"]] end module FDMsgItems Sorry="Sorry just moment" NoChosen = "Nothing is chosen." NoFileError=["#{ARGV[0]} is not exist","No file error",16] OptionError=["too many arguments","Option error" ,16] DoYouSave="Do you save this file?" OpenPreare="Open file" FileNotExist=[" is not exist","File not exist",16] FileWasModified=["This working file was modifyed by other apprication."+ "\r\nDo you read new file?","Working file was modifyed" ,0x0003] SaveBeforeEdit=["Please save befor editing","This is new project",0x30] SaveFromEditor=["Have you saved Project from Editor?", "Updating Project ",0x31] ThisIsMain=["This is Main Form.", "Cannot Change",16] OerationCannotUndo=["This operation cannot UNDO.\r\n\r\nDo you delete anyway?", "Delete this form",0x34] GridMustBe=["Grid span must be in 2 to 100" ,"Warning!!",16] Base64Finish="Base64 string was copied into clipboard" SaveBrforeExit=["Do you save this file?","Exit FormDesigner",0x1023] InDDEmode=["Here is in DDE mode. Do you exit realy?","Exit FormDesigner",0x1034] Modified="Modified" Saved=" was saved." Noform=["There is none to raed or old file","Read form from file",16] NoPaste=["Cannot paste to this parent","Invalid parent",16] DialogRunning=[" dialog is running. ","Running dialog",0x30] end module FDPrfItems Preferences="Preferences" CROnly="CR Only" CgwinLS="Cygwin's line separator" Gridsize="Glid Size" DockInspect='Dock inspect window' Editor="Editor" UseJp='Use Japanese' Font="Font" NextStart='(Enable next starting)' Verbose='Output comments of caution' OK="O K" Cancel="Cancel" end module FDNewProjectItem NewProject=" is new project" Prompt="Please select type which you'd like" end module FDProjectTypes Apart="project with separated forms" Form="forms only" Mono="project with built forms" end end module JA HTML_Help=$program_dir.gsub(/\//,'\\')+'\doc\vrswin-ja.chm' module FDItems FDMenuTemplate= [ ["ファイル(&F)", [ ["新規作成(&N)\tCtrl+N","new"], ["開く(&O)","open"], ["保存(&S)","save"], ["名前を付けて保存(&A)","saveas"], VRMenu::SEPARATOR, ["終了(&X)","exit"]]], ["編集(&E)", [ ["削除(&D)","doDelete"], ["カット(&T)","cut"], ["コピー(&C)","copy"], ["貼り付け(&P)","paste"]]], ["ヘルプ(&H)", [ ["バージョン情報","version"]]] ] FDPopupMenuTemplate=[["削除(&D)\tDelete","doDelete"],VRMenu::SEPARATOR, ["コピー(&C)\tCtrl+C","doCopy"],["貼り付け(&P)\tCtrl+V","doPaste"]] FDToolbarTemplate = [['toolButton1'], ['toolButton2',WConst::TBSTYLE_SEP], ['toolButton3',WConst::TBSTYLE_CHECKGROUP], ['toolButton4',WConst::TBSTYLE_CHECKGROUP], ['toolButton5',WConst::TBSTYLE_CHECKGROUP]] FDDlgFilterTemplate=[["全て(*.*)","*.*"]] end module FDMenuItems FDMainmenu=[ ["ファイル(&F)",[ ["新規フォーム", [ ["フォーム","new_form"], ["モードレスフォーム","new_modeless_form"], ["モードレスダイアログ","new_modeless_dlg"]]], ["開く(&O)\tCtrl+O","open"], ["RDEで開く(&R)\tCtrl+R","open_rde"], ["メインフォーム種別を変更", [ ["フォーム","change_to_mainform"], ["モードレスフォーム","change_to_modeless_mainform"], ["モードレスダイアログ","change_to_modeless_maindlg"]]], ["上書き保存(&S)\tCtrl+S","save"], ["名前を付けて保存(&A)", [ ["フォームだけ","saveas_form"], ["フォーム分離型プロジェクト","saveas_proj_part"], ["フォーム内蔵型プロジェクト","saveas_proj_mono"]]], VRMenu::SEPARATOR, ["(&E)プロジェクトを編集\tCtrl+E","run_editor"], ["(&U)プロジェクトをアップデート\tCtrl+U","update_proj"], VRMenu::SEPARATOR, ["終了(&X)\tAlt+F4","exit"]]], ["挿入(&I)", [ ["フォーム","insert_form"], ["モードレスフォーム","insert_modelessform"], ["モーダルフォーム","insert_modalform"], ["フォーム種別を変更", [ ["フォーム","change_to_form"], ["モードレスフォーム","change_to_modeless_form"], ["モーダルフォーム","change_to_modal_form"]]], VRMenu::SEPARATOR, ["ファイルから","insert_form_from_file"], ["このフォームを保存","save_this_form"], VRMenu::SEPARATOR, ["このフォームを削除","delete_this_form"], ]], ["編集(&E)", [ ["削除(&D)\tDelete","doDelete"], VRMenu::SEPARATOR, ["カット(&T)\tCtrl+X","doCut"], ["コピー(&C)\tCtrl+C","doCopy"], ["貼り付け(&P)\tCtrl+V","doPaste"], VRMenu::SEPARATOR, ["親ウインドウへ移動(&B)\tHome","back_to_parent"]]], ["ウインドウ(&W)", [ VRMenu::SEPARATOR, ["&Inspect","inspectShow",VRMenuItem::CHECKED]]], ["実行(&R)", [ ["実行(&X)\tF5","execute"], ["コード表示","examine"]]], ["オプション(&O)", [ ["設定(&P)","prefer"], VRMenu::SEPARATOR, ["グリッド","gridState",VRMenuItem::CHECKED]]], ["ツール(&T)", [ ["Bmp2Str","bmp2str"]]], ["ヘルプ(&H)", [ ["トピックの表示\tF1","show_topic"], ["SDKトピックの表示\tF2","show_SDK_topic"], ["バージョン情報(&N)","version"]]]] FDPopupmenu=[ ["削除(&D)\tDelete","doDeletepop"], VRMenu::SEPARATOR, ["カット(&X)\tCtrl+X","doCutpop"], ["コピー(&C)\tCtrl+C","doCopypop"], ["貼り付け(&P)\tCtrl+V","doPastepop"], VRMenu::SEPARATOR, ["親ウインドウへ移動(&B)\tHome","back_to_parentpop"]] end module FDMsgItems Sorry="ちょっと待ってね" NoChosen = "無選択" NoFileError=["#{ARGV[0]} は存在しません","ファイルがありません",16] OptionError=["引数が多すぎます","オプションエラー" ,16] DoYouSave="このファイルを保存しますか?" OpenPreare="ファイルを開く" FileNotExist=[" が存在しません","ファイルが存在しません",16] FileWasModified=["この作業ファイルは他のアプリケーションによって書き換えられました。"+ "\r\n新しいファイルを読み込みますか?","作業ファイルが変更されました" ,0x0003] SaveBeforeEdit=["編集の前にプロジェクトを保存してください","新規プロジェクト",0x30] SaveFromEditor=["エディタからプロジェクトを保存しましたか?", "プロジェクトをアップデート",0x31] ThisIsMain=["メインフォームは削除できません.", "削除不可",16] OerationCannotUndo=["アンドゥできませんが、本当に削除しますか?", "このフォームを削除",0x34] GridMustBe=["グリッドは 2 から 100までの整数でなければなりません" ,"警告!!",16] Base64Finish="Base64 文字列がクリップボードに保存されました" SaveBrforeExit=["ファイルを保存しますか?","FormDesignerの終了",0x1023] InDDEmode=["DDEモードです。本当に終了しますか?","FormDesignerの終了",0x1034] Modified="変更あり" Saved=" を保存済み" Noform=["読めるフォームが無いか、古いファイルです","ファイルから挿入",16] NoPaste=["この親ウインドウに貼り付けることは出来ません","無効な親ウインドウ",16] DialogRunning=[" ダイアログを実行中です","ダイアログ実行中",0x30] end module FDPrfItems Preferences="設定" CROnly="CR のみ" CgwinLS="Cygwinでの改行記号" Gridsize="グリッド幅" DockInspect='インスペクトウインドウをドック' Editor="エディタ" UseJp='日本語を使用' Font="フォント" NextStart='(次回の起動で有効)' Verbose='警告コメントを出力' OK="O K" Cancel="キャンセル" end module FDNewProjectItem NewProject=" は新規プロジェクトです" Prompt="いずれかのタイプを選択してください" end module FDProjectTypes Apart="フォーム分離型プロジェクト" Form="フォームだけ" Mono="フォーム内蔵型プロジェクト" end end if $Lang=="JA" include JA else include EN end <file_sep>#! ruby -Ks # # FormDesigner.rb # Programmed by <EMAIL> # Copyright 2001-2007 <NAME> $KCODE = 's' require 'win32ole' $RDE = WIN32OLE.new 'RDE.Main' require 'fdvr/fdmain' require 'fdvr/fdcontroldesign' require 'fdvr/fdinspect' require 'fdvr/fddialogs' VRLocalScreen.start FDControlSelection <file_sep># inner.rb # Analizing methods which parser use # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'strscan' module Inner def initialize(frm,old_data=nil) # @yydebug =true if old_data then extend Inner_old else extend Inner_new end _init(frm) end end module Inner_old def _init(frm) @form=frm @var={} @x=@y=0 @cntctrls={} @nodes = { "name" => "self", "childs" => [], "addings" => [], "fonts"=>{},"pendings" => [] ,"modules"=>[]} @item_pendings = {} @inFrm=@inCnt=false end def do_end if @inFrm then @inFrm , @inDef = false,false elsif @inCntn then @inCntn , @inDef =false,false else yyaccept end end def do_primary(val) if val =~ /Cntn_\w+/ || val =~ /Extn_\w+/ || @var[val] then val else @form.instance_eval(val) end end def do_arr_prim(val) eval(val) end def do_assign(receiver,vname, val ) if val.is_a? String then r = @form.instance_eval(receiver.join(".")+"."+vname+"= '"+val+"'") elsif val == @_newPopupMenu c = @form.send("newFDPopup",@form,@form.instance_eval("FDPopup"),vname.sub(/@/,''), vname.sub(/@/,''),0,@y+=24,24,24,0,val) c.send("extend",FDCommonMethod) @form.instance_eval "@names << '#{vname.sub(/@/,'')}'" else @var[vname]=val end end def do_send(val) [val] end def do_send2(rcvr,val) rcvr.push val end def serch_ext(ext) r={} @nodes[ext].each{|i| if i[ext] then r = i else r = serch_ext(i) end } r end def serch_node(c,name) #r={} if c["name"] == name then r = c else c["childs"].each{ |i| if r = serch_node(i,name) then r ; break end } end r end def serch_nodes(a,name) r=nil a.each{|i| if r = serch_node(i,name) then r break end } r end def serch_node2(c,name) if r = serch_node(c,name) then r else r = serch_nodes(c["pendings"],name) end end def make_node(c,parent,child) r=r1=nil if r=serch_node(c,parent) then c["pendings"].reject!{|i| if i["name"] == child then r1=i;true else false end } if r1 then r["childs"] << { "name" => child, "childs" => [*(r1["childs"])], "addings" => [*(r1["addings"])],"fonts"=>r1["fonts"], "modules"=>r1["modules"] } else r["childs"] << { "name" => child, "childs" => [*(r1["childs"])], "addings" => [],"fonts"=>{},"modules"=>[] } end elsif r = serch_nodes(c["pendings"],parent) then c["pendings"].reject!{|i| if i["name"] == child then r1 =i;true else false end } if r1 then r["childs"] << { "name" => child, "childs" => [*(r1["childs"])], "addings" => [*(r1["addings"])],"fonts"=>r1["fonts"], "modules"=>r1["modules"] } else r["childs"] << { "name" => child, "childs" => [], "addings" => [],"fonts"=>{},"modules"=>[]} end else if child then c["pendings"].reject!{ |i| if i["name"] == child then r1=i;true else false end } c["pendings"] << { "name" => parent, "childs" => [{ "name" => child, "childs" => [*(r1["childs"])],"addings" => [*(r1["addings"])], "fonts"=>r1["fonts"]}], "addings" => [] ,"modules"=>[]} else c["pendings"] << {"name" => parent, "childs" => [] ,"addings" => [], "fonts" =>{},"modules"=>[]} end end c end def find_item(node,name) unless node["addings"] == [] then r = node["addings"].select{|j| j[1] == name}[0] r else nil end # unless (pn = nodes["pendings"]) == [] then # pn.each{|i|r = find_item(i,name) # return(r) if r # } # end r end def do_call(receiver,method, args ) receiver = @form if receiver == ["self"] @_newPopupMenu = nil a="" a=args.join(",") case method when 'extend' if @inFrm then @nodes = make_node(@nodes,"self",args[0]) elsif @inCntn @nodes = make_node(@nodes,@cntname,args[0]) end when '_cntn_init' if @inFrm then #do nothing elsif @inCntn #do nothing end when 'addControl' #p @cntname+"_#{args[1]}" if @inFrm then @nodes["addings"] << (args << @item_pendings[args[1]]) elsif @inCntn then serch_node2(@nodes,@cntname)["addings"] << (args << @item_pendings[@cntname+"_#{args[1]}"]) end when 'setMenu' args[0].scan(/@(.+)/) c = @form.send("newFDMenu",@form,@form.instance_eval("VRMenu"),$1, $1,0,@y+=24,24,24,0,@var[args[0]]) c.send("extend",FDCommonMethod) @form.instance_eval "@names << '#{$1}'" c.send("accel",args[1]) when 'set' if receiver[0]=='newPopupMenu' then @_newPopupMenu = args[0] end args[0] when 'setFont' if @inFrm then @nodes["fonts"][*receiver] = *args elsif @inCntn then (serch_node2(@nodes,@cntname)["fonts"])[*receiver] = *args else end when 'newfont' f=FontStruct.new2(args) f when 'insertband' p0=@cntname.sub(/_(\w+)$/,'') if p0 == "Cntn" then if itm=find_item(@nodes,$1) then itm.last << [args[0],args[1],args[2],args[3]] else unless @item_pendings[$1] @item_pendings[$1] = [[args[0],args[1],args[2],args[3]]] else @item_pendings[$1] << [args[0],args[1],args[2],args[3]] end end else if itm=find_item(serch_node2(@nodes,p0),$1) then itm.last << [args[0],args[1],args[2],args[3]] else unless @item_pendings[@cntname] @item_pendings[@cntname] = [[args[0],args[1],args[2],args[3]]] else @item_pendings[@cntname] << [args[0],args[1],args[2],args[3]] end end end when /set\w+/ if @inFrm then find_item(@nodes,receiver[0].sub(/@/,''))[8] = args[0] elsif @inCntn find_item(serch_node2(@nodes,@cntname),receiver[0].sub(/@/,''))[8] = args[0] else end else receiver.send( method,*args) end end def do_array(var, args ) if var =~/\$_.+_fonts/ then args[0] end end def parse( str ) @str = str yyparse self, :scan [@st1,@nodes,@var] end def scan @inFrm = @inCntn = @inDef = requires = false str = @str str.strip! @st1 = @modname = "" until str.empty? do case str when /\A\s*\$_\w+_fonts\s*=\s*/ sfon=str[$~.end(0)..sidx=str.index("]",$~.end(0))] @form.instance_eval("@temp_fonts=#{sfon}") @form.instance_eval("@temp_fonts.each{|i|@afont[i.hfont]=i}") str=str[sidx+2..str.size-1] when /\Avr_DIR\=\"vr\/\" unless vr_DIR\W.*[\r\n]?/ str = $' ;requires = true when /\Arequire vr_DIR\+('.+')\W.*[\r\n]?/ @st1 += $& unless requires str = $' when /\Amodule (Cntn_\w+).*$/, /\Amodule (Extn_\w+).*$/ @inCntn = includes = true ; @cntname = $1 make_node(@nodes,@cntname,nil) str = $' @st1 += $& +"\n" when /\Amodule Frm_(\w+).*$/ @inFrm = includes = true ; @modname=$1 @form.instance_eval("self.name='#{@modname}'") str = $' @st1 += $& +"\n" when /\Ainclude (\w+).*$/ @st1 += $& unless includes str = $' s1=$1 if @inFrm @nodes["modules"] << s1 elsif @inCntn nod=serch_node2(@nodes,@cntname) nod["modules"] << s1 else end when /\Adef +_cntn_init.*$/ @inDef = true ; str = $' ; when /\Adef +_#{@modname}_init.*/ @inDef = true ; str = $' when /\A#\$_/ #this is fd_prefix #reject fd_prefix str = $' when /\A\*/ #reject multi assign operator str = $' when /\A#.*[\r\n]?/ if includes && @inFrm then includes = false elsif includes && @inCntn then includes = false elsif requires then requires = false else @st1+=$& unless @inDef end str = $' when /\A\s+/ @st1 += $& unless @inDef || includes str = $' when /\Aend/ if @inDef then yield 'end' ,$& @inDef = false else @st1+=$& end str = $' when /\A[+-]?\d+/ if @inDef then yield :NMBR ,$& else @st1+=$& end str = $' when /\A"(?:[^"\\]+|\\.)*"/,/\A'(?:[^'\\]+|\\.)*'/ #" if @inDef yield :STRG, $& else @st1+=$& end str = $' when /\A[@$]?\w+/ if @inDef yield :IDNT, $& else @st1+=$& end str = $' else c = str[0,1] if @inDef then yield c, c else @st1 += c end str = str[1..-1] end end yield false, '$' end def next_token @q.shift end end #module module Inner_new def _init(frm) @form=frm # @var={} @x=@y=0 @cntctrls={} @nodes = Node.new(@form.name) @current = @nodes @inDef=false end class Node < Hash attr_accessor :parent, :klass, :items, :var, :methods, :default_font def initialize(name) self["name"]=name self["childs"]=[] self["addings"]=[] self["fonts"]={} self["modules"]=[] self["margins"]={} @klass=nil @items=nil @parent=nil @var={} @default_font=nil @methods=[] end def add(name,klass=nil) c=Node.new(name) c.parent=self c.klass=klass self["childs"] << c c end def find_class(key) r = self["childs"].find{|i| i["name"] == key} [r.klass,r.items] if r end end def do_end if @inDef then @inDef =false else @current=@current.parent # yyaccept unless @current end end def do_primary(val) return val return nil unless val if val =~ /\A[A-Z]\w+/ || @var[val] then val else @form.instance_eval(val) end end def do_arr_prim(val) if val.is_a?(String) && (val =~ /^['"].*['"]$/) then @form.instance_eval(val) else val end end def do_assign(receiver, vname, val) return if val == nil receiver = [''] unless receiver if val.is_a? String then @current.methods << [receiver.join('.'), vname+'=', val] elsif val && val == @__newMenu r = @current["addings"].find{|i| i[1] == vname.sub(/@/,'')} r[7] = 0; r[8] = val elsif val && val == @__newPopupMenu r = @current["addings"].find{|i| i[1] == vname.sub(/@/,'')} r[7] = 0; r[8] = val elsif val && val == @__set_mgd_frame_args r = @current["addings"].find{|i| i[1] == vname.sub(/@/,'')} r[7] = 0; r[8] = val[1..val.size-1]; r[9]= true elsif val && val == @__new_mgd_frame_args r = @current["addings"].find{|i| i[1] == vname.sub(/@/,'')} r[7] = 0; r[8] = val else @current.methods << [receiver.join('.'), vname+'=', val] end end def do_send(val) [val] end def do_send2(rcvr,val) rcvr.push val end def find_item(node,name) unless node["addings"] == [] then r = node["addings"].select{|j| j[1] == name}[0] r else nil end r end def do_call(receiver,method, args ) # receiver = @form if receiver == ["self"] @_newPopupMenu = nil a="" a=args.join(",") case method when 'extend' #do nothing when 'vrinit' #do nothing when 'addControl' cname,itm= @current.find_class(args[0]) if cname then args[0]=@form.instance_eval(cname) args[8]=itm if itm else args[0]=@form.instance_eval(args[0]) end args[1..2] = args[1..2].map{|i| eval(i)} @current["addings"] << args nil when 'setMenu' # args[0].scan(/@(.+)/) # c = @form.send("newFDMenu",@form,@form.instance_eval("VRMenu"),$1, # $1,0,@y+=24,24,24,0,@current.var[args[0]]) # c.send("extend",FDCommonMethod) # @form.instance_eval "@names << '#{$1}'" # c.send("accel",args[1]) @current.methods << [args[0],'accel', args[1]] when 'set' if receiver[0]=='newPopupMenu' then @__newPopupMenu = args[0] else @__newMenu = args[0] end args[0] when 'setFont' args[0].match(/[A-Z][a-zA-Z0-9_]+_fonts\[(\d)\]\Z/) @current["fonts"][*receiver] = $1.to_i when 'newfont' f=FontStruct.new2(args) f when 'setMarginedFrame' @__set_mgd_frame_args = args args when 'new' @__new_mgd_frame_args = args when 'setup' # thrugh receiver receiver when 'setMargin' @current.methods << [receiver.join('.'), method, args] when 'insertband' @current.methods << ['self', 'setbandattr', args] #do nothing when 'setupPanels' @current.items=args[0].map{|i| [i[0],nil,i[2]]} when 'autoresize_panels' #do nothing when 'register' @current.methods << [receiver.join('.'), method, args] when /set\w+/ find_item(@current,receiver[0].sub(/@/,''))[8] = args[0] else @form.instance_eval(receiver.join('.')).send( method,*args) end end def do_array(var, args) if var =~/[A-Z][a-zA-Z0-9_]+_fonts\Z/ then args[0] end end def parse( str ) @str = str yyparse self, :scan [@st1,@nodes,@var] end def scan @inDef = requires = false s = StringScanner.new(@str) @st1 = ""; @modname = "" until s.eos? do case when s.scan(/\A\s*[A-Z][a-zA-Z0-9_]+?_fonts\=\s*(\[.*?\])/m) @form.instance_eval("@temp_fonts=#{s[1].strip}") @form.instance_eval("@temp_fonts.each{|i|@_hsh_font[i.hfont]=i}") when s.scan(/\A\s*DEFAULT_FONT\s*=[\s*A-Z][a-zA-Z0-9_]+_fonts\[(\d)\]\s*$/) @current.default_font = s[1].to_i when s.scan(/\Amodule (\w+).*$/) includes = true ; @current = @current.add(s[1]) @st1 += s[0] +"\n" when s.scan(/\Aclass (\w+)\s*<\s*(\w+).*$/) includes = true ; @current = @current.add(s[1],s[2]) @st1 += s[0] +"\n" when s.scan(/\Ainclude (\w+).*$/) @st1 += s[0] unless includes @current["modules"] << s[1] when s.scan(/\Adef +vrinit.*$/) @inDef = true when s.scan(/\Adef construct.*$/) @inDef = true when s.scan(/\A#\$_/) #this is fd_prefix #reject fd_prefix when s.scan(/\A\*/) #reject multi assign operator when s.scan(/\A#.*[\r\n]?/) @st1+=s[0] unless @inDef when s.scan(/\A\s+/) @st1 += s[0] unless @inDef || includes when s.scan(/\Aend/) yield 'end' ,s[0] when s.scan(/\Atrue/), s.scan(/\Afalse/), s.scan(/\Anil/) if @inDef then yield :CNST ,eval(s[0]) else @st1+=s[0] end when s.scan(/\A0x[0-9a-fA-F]+/),s.scan(/\A\d+\.\d+/),s.scan(/\A[+-]?\d+/) if @inDef then yield :NMBR ,eval(s[0]) else @st1+=s[0] end when s.scan(/\A"(?:[^"\\]+|\\.)*"/),s.scan(/\A'(?:[^'\\]+|\\.)*'/) if @inDef yield :STRG, s[0] else @st1+=s[0] end when s.scan(/\A([\@\$]?[a-z_][a-zA-Z0-9_]+)/) if @inDef yield :IDNT, s[0] else @st1+=s[0] end when s.scan(/\A[A-Z][a-zA-z0-9_]*(::[A-Z][a-zA-z0-9_]*)?/) if @inDef yield :IDNT, s[0] else p s[0] @st1+=s[0] end else c = s.getch if @inDef then yield c, c else @st1 += c end end end yield false, '$' end def next_token @q.shift end end #module <file_sep># fduser.rb # user defined pallets and controls # # This prototype was programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'fdvr/fdcontrols' module CreateCtrl include FDControls def user_createinit #add user pallet $conf << FDPallet["User",[ ]] end end <file_sep># FormDesigner FormDesigner for project VisualuRuby ## 修正内容 - Exerb でEXE化可能な様に修正 - 出力するコントロールの追加内容をソートする(毎回同じになる)ように修正 ## オリジナルファイルについて - FormDesigner for Project VisualuRuby Ver 060501 - https://ja.osdn.net/projects/fdvr/ - Subversion リポジトリ r71(r65以降)の/formdesigner/trunk を使用 - https://ja.osdn.net/projects/fdvr/svn/view/formdesigner/trunk/?root=fdvr - 開発者:雪見酒 - ライセンス:Ruby Licence ### Exerb - http://exerb.osdn.jp/man/README.ja.html - 開発者:加藤勇也 - ライセンス:LGPL <file_sep>### FormDesigner for VisualuRuby project 040417 ### ### ### mailto:<EMAIL> http://homepage3.nifty.com/Yukimi_Sake/ 口上: 光陰矢の如しとは良く言ったもので2年以上の月日が経ってしまいました。 その後VisualuRubyもApolloも順調に発展していますが、FormDesignerは 停滞したままでした。このままじゃいかん!というわけでアップデイトを 敢行いたしました。但し、この版は暫定版です。まだいくらか作業が残って いますし、バグも取りきっていません。使用なさる方は心しておいてくださ い。開発経緯についてはreadme.old.txt を添付してありますのでそちらを お読みください。さて、能書きはこれくらいにしておいて、本題に入ります。 大前提: この版はのvruby031014以降でのみ動作します。(ただし最新のを極力使用し てください。)にゃすさんのホームページからダウンロードしてインストール してください。 http://www.osk.3web.ne.jp/~nyasu/software/vrproject.html また、旧版で編集したファイルは多くの場合、読み込むことができません。 というのは、FormDesignerで編集したForm固有のファイルはアプリケーショ ン本体と分離したからです。旧版ではかなりの確率で手作業編集をしたファ イルが開けなくなりましたが、この版ではそういうことがなくなるはずです。 もし開けなければそれはFormDesignerのバグですから、私にご連絡いただけ れば、できる限り対応します。 分離の方法は以下のようになっています。 FormDesignerで編集したファイルは、"_frm_hoge.rb"のように"_frm_"という プリフィクスがつきます。FormDesignerはこのプリフィクスのついたファイ ルを自分が作ったファイルだと識別して開きます。これ以外のファイルは開 きません。一方あなたが編集するべきファイルは"プロジェクト"と呼びます。 FormDesignerはこのプロジェクトのモジュール定義やrequire定義などを自動 的に作成して雛型ファイルを出力します。こちらは名前の制限がありませんが、 同名で、前述のプリフィクスのついたファイルも同時に出力します。 つまり、あなたのプロジェクト本体はエディタで、Formファイルの編集は FormDesignerでと作業分担がはっきり分かれました。 以上ご承知おきください。 できること: フォームを作る フォームにコントロールを乗せる パネルやグループボックスのようなコンテナにコントロールを乗せる コントロールの移動、サイズ変更(ドラッグ&ドロップ、Inspectウインド ウでの値変更)、削除(右クリック) コントロールの一部の属性の変更(caption,name) コントロールのフォント変更(Inspectウインウからボタンで) コントロールのスタイルの変更(Inspectウインウからボタンで) テンプレートになったメニューを乗せる(現在テンプレートは1種類のみ) メニューを編集する(Inspectウインウからボタンで) ポップアップメニューを編集する(Inspectウインウからボタンで) ToolbarやTabbedPanelなどアイテムを持つコントロールのアイテム編集(同) 現状のスクリプトの確認、実行(ユーザーコードは動きません) コントロールに一部のモジュールを追加する。 moduleになっている、コモンダイアログのメソッド引数の編集 以上をruby ソースファイルとして読み書きする エディタを起動して編集する(エディタはPreferenceで好きなのを選択可能) コントロール固有のイベントをクリップボードに書き出す。 メソッドもクリップボードに書き出す。 上記二つはFormDesignerからエディタを起動している場合はダブルクリック でエディタに制御が移る ユーザーコード別置型にしたので、ユーザーコードの雛型を出力 ユーザーコード編集中にモジュールをジュールを必要とするコントロールを 追加した場合、ユーザーコードに反映させることができる ビットマップリソース作成用のツールが一つ と、まあ以前よりは機能が増えたし、多少使いやすくなっています。 まだできてないこと: ImageListの実装、Tooltipの実装、レイアウトマネージャ、copy/pasteの 実装、マニュアル、、コントロール追加モジュールの拾い出しなどなど まだまだ多数。 必要なバージョン: Ruby 1.8.0 以降でcygwin,mingw,mswin の各版のいずれか swin (WindowsAPI からフォームやコントロールを作るDLL)040314以降 で各版に適合したバイナリ vruby (Rubyスクリプトで書かれたVisualuRubyの本体)上述のように 0040306以降。 作成したアプリケーションでToolbarを使用している場合はcheckoutバージョ ンより前のvrubyで動作させる場合、tooltipが使えないなど、若干の注意が 必要になる場合があります。(実装してないから大丈夫か...) インストール: Ruby は1.8.0以降がインストールしてあるのが前提の話。 mswin版ではActiveScriptRuby1.8.1.1以降がおすすめ。 http://www.geocities.co.jp/SiliconValley-PaloAlto/9251/ruby 注意:ネスケでダウンロードしちゃだめよ! 適当なディレクトリでアーカイブを解凍します。(cvsをチェックアウトし た場合はそのままディレクトリになっている) vruby031014lzhを解凍してインストールします。解凍するとディレクトリ 内のトップにvrinstall.rbがありますので、それを実行してください。 ActiveScriptRubyをインストールしている場合は、このファイルのダブル クリックでインストールが始まります。そうでない場合はコマンドライン から解凍したディレクトリ内でruby vrinstall.rb とします。 もしくは私のホームページに最新版のswinとvrubyがインストーラつきで 用意してありますから、それをインストールしても良いでしょう。 うごかしてみる: Ruby/binディレクトリにパスが通っていれば、コンソールからFormDesigner を解凍したディレクトリで "ruby FormDesigner.rb" [ENTER] で三つのウィンドウを持った画面が現れます。ActiveScriptRubyならエク スプローラからこのファイルをダブルクリックするだけです。あとは適宜 ツールバーのボタンやら、Inspectウインドウやら、メニューやらをいじく りまわして、遊んで下さい。VBやDelphiをお使いの方はすぐに分かると思 います。あ、2つだけ。 今回の配布は一応ベータ扱いとしますです。ただし、バグは機能が増えた 分増加していると思います。 あと何かを選択しても何の反応もないのはバグではありません(^^;。単に その処理を実装してないだけです。(一部"sorry"メッセージボックスの出る のもありますが)そういうのは実装間近なのだなと善意に解釈して下さい。 (^^;; そのあとは: 初めての方はまず、にゃすさんのHPを訪れて下さい。そこのサンプルやら リファレンスやらをDLしたり、ブックマークしたりして、いろいろ試しなが ら覚えましょう。また、vr(Ruby スクリプト)のソースにもRD形式のリファ レンスが入ってます。(まさに「ソースを読め!」ですな) あっと、ご質問、ご意見、バグレポートなどなど: 冒頭のアドレスにメールをいただければ何らかのリアクションがあります。 たいていは私のHPの日記に引用した上で回答、お返事をすることになりま す。但し、必要に応じて直接ご返信することもありえます。 また、ruby listは購読しておりますので、そちらに上げていただければ、そ ちらでお返事いたします。 soureceforge のForumでも結構ですが、ちょっと巡回頻度が低いです。 URL: http://sourceforge.net/projects/vruby/ nifty:FGALTSはさらに巡回頻度が低いです。 さらに、ああっと、ライセンスなど: 当然 Ruby ライセンスに従います。"Ruby ライセンス"ってなに?という方 は本家へ行って原文を読んでください。私の説明では誤解を招く恐れがあり ますので。 本家のURL:http://www.ruby-lang.org/ja/ ありがとう: Rubyの生みの親、まつもとゆきひろさん、Windowsへのポーティングをして くださった皆さん、Raccのあおきさん、ActiveScriptRubyのartonさん、 そして、VisualuRuby計画のにゃすさん、そしてそしてRubyの普及に日夜尽 力しておられる皆さん、ありがとうございます。 では、いろいろ試して楽しんでください。(^-^)/~~ なお、変更履歴はhistory.txtに記載してあります。 2004/4/17 雪見酒 <file_sep># fddialogs.rb # Dialogs for formdesigner # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'vr/vruby' require 'vr/vrdialog' require 'vr/vrcomctl' require 'vr/vrhandler' require 'vr/vrowndraw' require 'fdvr/fdwin32' require 'fdvr/fdresources' require 'vr/contrib/vrctlcolor' include SWin include User32 include GDI32 module DrawFrameConst DFC_CAPTION = 1 DFC_MENU = 2 DFC_SCROLL = 3 DFC_BUTTON = 4 DFCS_CAPTIONCLOSE = 0 DFCS_CAPTIONMIN = 1 DFCS_CAPTIONMAX = 2 DFCS_CAPTIONRESTORE = 3 DFCS_CAPTIONHELP = 4 DFCS_MENUARROW = 0 DFCS_MENUCHECK = 1 DFCS_MENUBULLET = 2 DFCS_MENUARROWRIGHT = 4 DFCS_SCROLLUP = 0 DFCS_SCROLLDOWN = 1 DFCS_SCROLLLEFT = 2 DFCS_SCROLLRIGHT = 3 DFCS_SCROLLCOMBOBOX = 5 DFCS_SCROLLSIZEGRIP = 8 DFCS_SCROLLSIZEGRIPRIGHT = 16 DFCS_BUTTONCHECK = 0 DFCS_BUTTONRADIOIMAGE = 1 DFCS_BUTTONRADIOMASK = 2 DFCS_BUTTONRADIO = 4 DFCS_BUTTON3STATE = 8 DFCS_BUTTONPUSH = 16 DFCS_INACTIVE = 256 DFCS_PUSHED = 512 DFCS_CHECKED = 1024 DFCS_ADJUSTRECT = 0x2000 DFCS_FLAT = 0x4000 DFCS_MONO = 0x8000 end module EditMsgConst EM_CANUNDO = 198 EM_CHARFROMPOS = 215 EM_EMPTYUNDOBUFFER = 205 EM_FMTLINES = 200 EM_GETFIRSTVISIBLELINE = 206 EM_GETHANDLE = 189 EM_GETLIMITTEXT = 213 EM_GETLINE = 196 EM_GETLINECOUNT = 186 EM_GETMARGINS = 212 EM_GETMODIFY = 184 EM_GETPASSWORDCHAR = 210 EM_GETRECT = 178 EM_GETSEL = 176 EM_GETTHUMB = 190 EM_GETWORDBREAKPROC = 209 EM_LIMITTEXT = 197 EM_LINEFROMCHAR = 201 EM_LINEINDEX = 187 EM_LINELENGTH = 193 EM_LINESCROLL = 182 EM_POSFROMCHAR = 214 EM_REPLACESEL = 194 EM_SCROLL = 181 EM_SCROLLCARET = 183 EM_SETHANDLE = 188 EM_SETLIMITTEXT = 197 EM_SETMARGINS = 211 EM_SETMODIFY = 185 EM_SETPASSWORDCHAR = 204 EM_SETREADONLY = 207 EM_SETRECT = 179 EM_SETRECTNP = 180 EM_SETSEL = 177 EM_SETTABSTOPS = 203 EM_SETWORDBREAKPROC = 208 EM_UNDO = 199 EN_CHANGE = 768 EN_ERRSPACE = 1280 EN_HSCROLL = 1537 EN_KILLFOCUS = 512 EN_MAXTEXT = 1281 EN_SETFOCUS = 256 EN_UPDATE = 1024 EN_VSCROLL = 1538 end module ListBoxDlgMessage def bt_checked?(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::BM_GETCHECK,0,0) end def bt_setcheck(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::BM_SETCHECK,0,0) end def lb_addString(id,str) SendDlgItemMessage2.call(self.hWnd,id,WMsg::LB_ADDSTRING,0,str) end def lb_insertString(id,nStart,nEnd) SendDlgItemMessage2.call(self.hWnd,id,WMsg::LB_INSERTSTRING,nStart,nEnd) end def lb_getcount(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::LB_GETCOUNT,0,0) end def lb_getsel(id,index) SendDlgItemMessage.call(self.hWnd,id,WMsg::LB_GETSEL,index,0) end def lb_findsel(id) lb_getcount(id) r = nil for i in 0..lb_getcount(id)-1 unless lb_getsel(id,i) == 0 then r = i ; break end end r end def lb_gettext(id,idx) str=" " * SendDlgItemMessage.call(self.hWnd,id,WMsg::LB_GETTEXTLEN,idx.to_i,0) SendDlgItemMessage2.call(self.hWnd,id,WMsg::LB_GETTEXT,idx.to_i,str) str end def lb_getitemdata(id,index) SendDlgItemMessage.call(self.hWnd,id,WMsg::LB_GETITEMDATA,index,0) end def lb_setitemdata(id,index,data) SendDlgItemMessage.call(self.hWnd,id,WMsg::LB_SETITEMDATA,index,data) end def lb_replacesel(id,str) SendDlgItemMessage2.call(self.hWnd,id,WMsg::EM_REPLACESEL,0,str) end def lb_setlistStrings(id,a) a.each{|i| lb_addString(id,i) } end def lb_getlistStrings(id) n=lb_getcount(id) ; r = [] for i in 0 .. n-1 r << lb_gettext(id,i) end r end def cb_addString(id,str) SendDlgItemMessage2.call(self.hWnd,id,WMsg::CB_ADDSTRING,0,str) end def cb_insertString(id,nStart,nEnd) SendDlgItemMessage2.call(self.hWnd,id,WMsg::CB_INSERTSTRING,nStart,nEnd) end def cb_getcount(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_GETCOUNT,0,0) end def cb_getsel(id,index) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_GETSEL,index,0) end def cb_getitemdata(id,index) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_GETITEMDATA,index,0) end def cb_setitemdata(id,index,data) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_SETITEMDATA,index,data) end def cb_selectedString(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_GETCURSEL,0,0) end def cb_select(id,idx) SendDlgItemMessage.call(self.hWnd,id,WMsg::CB_SETCURSEL,idx,0) end end class OwnerDrawModalDlg < VRModalDialog WM_DRAWITEM = 0x002B def OwnerDrawModalDlg.new(screen,template) r=screen.factory.newdialog(template.to_template,self) r.parentinit(screen) r.options={} r.addEvent WMsg::WM_INITDIALOG r.addEvent WMsg::WM_COMMAND r.addEvent WM_DRAWITEM return r end end class ListBoxDlg < OwnerDrawModalDlg #style Dialog include ListBoxDlgMessage include DrawFrameConst def msghandler(msg) case msg.msg when WMsg::WM_INITDIALOG setListTextData(@options["target"],@options["default"]) if @options["target"] setCBTextData(@options["target2"],@options["default2"]) if @options["target2"] when WMsg::WM_COMMAND if msg.wParam == @options["okbutton"] then close self.getListTextData(@options["target"],@options["target2"]) elsif msg.wParam==@options["cancelbutton"] then close false elsif msg.wParam==@options["helpbutton"] @parent.parent.class::SDKDocument.DisplayTopicFromURL( FDSDK::DE_Prefix + FDSDK::WND_STYLE_DOC) elsif HIWORD(msg.wParam) == WMsg::LBN_SELCHANGE && LOWORD(msg.wParam) == @options["target"] then lb_selchange(LOWORD(msg.wParam)) elsif HIWORD(msg.wParam) == WMsg::CBN_SELCHANGE && LOWORD(msg.wParam) == @options["target2"] then cb_selchange(LOWORD(msg.wParam)) end when WM_DRAWITEM drawitem(SWin::Application.cstruct2array(msg.lParam,'UUUUUUUUUUUU')) end end def setListTextData(id,a) n = 0 a.each{|i| lb_addString(id,i[0]) lb_setitemdata(id,n,i[1]) n += 1 } end def setCBTextData(id,a) n = 0 sel = a.shift a.each{|i| cb_addString(id,i[0]) cb_setitemdata(id,n,i[1]) n += 1 } cb_select(id,sel) end def getListTextData(id1,id2) r = [] r << cb_getitemdata(id2,cb_selectedString(id2)) if @options["target2"] for i in 0..lb_getcount(id1)-1 r << [lb_gettext(id1,i),lb_getitemdata(id1,i)] end r end def lb_selchange(id) sel=lb_findsel(id) unless lb_getitemdata(id,sel) == 1 then lb_setitemdata(id,sel,1) else lb_setitemdata(id,sel,0) end self.refresh end def drawitem(args) hdc=args[6];l=args[7];t=args[8];i=args[2];id=args[1] SetBkMode.call(hdc,1) a = [2,t+1,16,t+15].pack("LLLL") if lb_getitemdata(id,i) == 1 then DrawFrameControl.call(hdc,a,DFC_BUTTON,DFCS_BUTTONCHECK | DFCS_CHECKED ) else DrawFrameControl.call(hdc,a,DFC_BUTTON,DFCS_BUTTONCHECK) end s = lb_gettext(id,i) TextOut.call(args[6],l+20,t+0,s,s.size) end def cb_selchange(id) #p "cb_selchage" end end class StyleDlg < VRModalDialog @@args = nil def self.args=(args) @@args = args end include VRContainersSet DEFAULT_FONT=VRLocalScreen.factory.newfont('Terminal',-13,0,4,0,0,0,1,128) def construct self.caption = 'Styles' self.move(140,124,194,400) addControl(VRButton,'btOHelp',"?",128,328,56,20) addControl(ListBox1,'listBox1',"listBox1",0,24,184,305,0x50) addControl(VRCombobox,'comboBox1',"",0,0,186,80) addControl(VRButton,'btOK',"O K",0,352,72,20) addControl(VRButton,'btCancel',"Cancel",112,352,72,20) addControl(VRButton,'btCHelp',"?",52,328,72,20) addControl(VRButton,'btWHelp',"WStyle?",0,328,48,20) end def self_created setButtonAs(@btOK,IDOK) setButtonAs(@btCancel,IDCANCEL) @klass,aitems, aoptions, @toggle = *@@args @@args = nil if FDSDK::CTL_STYLE_DOC[@klass] @btCHelp.caption = @klass.name.sub(/^VR/,'') + '?' else @btCHelp.hide end aitems.each_with_index{|i, j| @listBox1.addString i[0] @listBox1.setDataOf j, i[1] } if aoptions && aoptions.size > 1 pos = aoptions.shift aoptions.each_with_index{|i, j| @comboBox1.addString i[0] @comboBox1.setDataOf j, i[1] } @comboBox1.select pos else @comboBox1.hide @btOHelp.hide @listBox1.move 0,0,184,330 end toggle_string0(*@toggle) if @toggle end def listBox1_selchanged if @listBox1.getDataOf(@listBox1.selectedString) == 0 @listBox1.setDataOf(@listBox1.selectedString, 1) else @listBox1.setDataOf(@listBox1.selectedString, 0) end toggle_string(*@toggle) if @toggle && @listBox1.getTextOf(@listBox1.selectedString) == @toggle[0] @listBox1.refresh end def toggle_string0(key,normal,alt) n = @listBox1.findString(key) if @listBox1.getDataOf(n) == 0 pos = @listBox1.findString(alt) @listBox1.deleteString(pos) else pos = @listBox1.findString(normal) @listBox1.deleteString(pos) end end def toggle_string(key,normal,alt) n = @listBox1.findString(key,0) if @listBox1.getDataOf(n) == 0 pos = @listBox1.findString(alt,0) @listBox1.deleteString(pos) @listBox1.addString(pos,normal) else pos = @listBox1.findString(normal,0) @listBox1.deleteString(pos) @listBox1.addString(pos,alt) end end def btOK_clicked r = [] r << @comboBox1.getDataOf(@comboBox1.selectedString) 0.upto(@listBox1.countStrings-1){|i| r << [@listBox1.getTextOf(i),@listBox1.getDataOf(i)] } close r end def btCancel_clicked close nil end def btWHelp_clicked @parent.parent.class::SDKDocument.DisplayTopicFromURL( FDSDK::DE_Prefix + FDSDK::WND_STYLE_DOC) end def btCHelp_clicked @parent.parent.class::SDKDocument.DisplayTopicFromURL( FDSDK::DE_Prefix + FDSDK::CTL_STYLE_DOC[@klass]) end class ListBox1 < VRListbox include GDI32 include User32 include DrawFrameConst def ownerdraw(iid,action,state,hwnd,hdc,left,top,right,bottom,data) SetBkMode.call(hdc,1) a = [2,top+2,14,top+14].pack("LLLL") if self.getDataOf(iid) == 1 then DrawFrameControl.call(hdc,a,DFC_BUTTON,DFCS_BUTTONCHECK | DFCS_CHECKED ) else DrawFrameControl.call(hdc,a,DFC_BUTTON,DFCS_BUTTONCHECK) end s = self.getTextOf(iid) TextOut.call(hdc,left+20,top+0,s,s.size) end end end class PrDlg < VRModalDialog # for preferences Dialog include VRCommonDialog def msghandler(msg) if msg.msg == WMsg::WM_INITDIALOG then self.setItemTextOf(@options["target"],@options["default"].to_s) self.setItemTextOf(@options["target2"],@options["default2"].to_s) self.bt_check(@options["checkbox"],@options["check"]) end if msg.msg == WMsg::WM_COMMAND then if msg.wParam==@options["okbutton"] then close [ self.getItemTextOf(@options["target"]), self.getItemTextOf(@options["target2"]) , self.bt_checked?(@options["checkbox"]) ] elsif msg.wParam==@options["cancelbutton"] then close false elsif msg.wParam==@options["browsebutton"] then if @editpath=openFilenameDialog([["Editor","*.exe"]]) then self.setItemTextOf(@options["target2"],@editpath.to_s) end end end end def bt_checked?(id) SendDlgItemMessage.call(self.hWnd,id,WMsg::BM_GETCHECK,0,0) == 1 ? true : false end def bt_check(id,v) SendDlgItemMessage.call(self.hWnd,id,WMsg::BM_SETCHECK,((v) ? 1 : 0),0) end end module EditDlgMsg include EditMsgConst def ed_getSel r = SendDlgItemMessage.call self.hWnd,@id,EM_GETSEL,0,0 return LOWORD(r),HIWORD(r) end def ed_setSel(st,en,noscroll=0) SendDlgItemMessage.call self.hWnd,@id,EM_SETSEL,st,en end def ed_setCaret(r) ed_setSel(r,r) end def ed_replaceSel(newstr) SendDlgItemMessage2.call self.hWnd,@id,EM_REPLACESEL,0,newstr.to_s end def ed_text r = "" SendDlgItemMessage2.call self.hWnd,@id,WMsg::WM_GETTEXT,2,r r end end =begin class ArrayEditDialog < VRModalDialog #for menu editor and toolbar editor include EditMsgConst include EditDlgMsg def initialize super end def msghandler(msg) case msg.msg when WMsg::WM_INITDIALOG setItemTextOf(@options["target"],@options["default"]) @buff = @options["default"] @buff0 = @buff.dup when WMsg::WM_COMMAND if msg.wParam == @options["okbutton"] then close self.getItemTextOf(@options["target"]) elsif msg.wParam==@options["cancelbutton"] then close false elsif HIWORD(msg.wParam) == EN_CHANGE && LOWORD(msg.wParam) == @options["target"] then @id = @options["target"] ed_changed unless @supplaceMsg @supplaceMsg = nil end else end end def ed_changed @buff = self.getItemTextOf(@id) if @buff.size-@buff0.size == 1 then @supplaceMsg = true n=ed_getSel[0] case @buff[n-1] when '"'[0] ed_replaceSel('"') when "'"[0] ed_replaceSel("\'") when '['[0] ed_replaceSel(']') end ed_setCaret n elsif @buff.size-@buff0.size == 2 @supplaceMsg = true n=ed_getSel[0] case @buff[n-1] when 10 astr =get_prev_line(n) @indent = 0 @indent = astr[/^ */].size if astr s = " " * @indent if @buff[n-2] == 13 && @buff[n-3] == '['[0] && @buff[n] == ']'[0] then ed_replaceSel "#{s} \r\n#{s}" n += 2 + @indent else ed_replaceSel(s); n += @indent end end ed_setCaret n end @buff0 = self.getItemTextOf(@id) end def get_prev_line(n) return if n == 0 i0 = -1 (n-3).downto(0){|i| if @buff[i] == 10 then i0 = i; break; end} if i0 < n-3 then @buff[i0+1..n-3] else nil end end end =end class ExamineModalDlg < VRModalDialog include VRStdControlContainer def vrinit super target = @options["target"] end def msghandler(msg) if msg.msg == WMsg::WM_INITDIALOG then self.setItemTextOf(@options["target"],@options["default"].to_s) end if msg.msg == WMsg::WM_COMMAND then if msg.wParam==@options["okbutton"] then close true elsif msg.wParam==@options["cancelbutton"] then close false end end end end class EDListview < VRListview class InplaceEdit < VREdit include VRKeyFeasible include VRFocusSensitive def self_char(ch,data) case ch when 13 @parent.update end end def self_lostfocus @parent.update end end include VRParent include VRStdControlContainer include VRMouseFeasible attr :ed,1 attr :fixfirstcolumn,1 def construct @font= @screen.factory.newfont("ms gothic",14) self.setFont(@font) self.reportview addControl(InplaceEdit,'ed','') @ed.setFont(@font) @ed.hide end def hittest3(x,y) idx = hittest2(x,y)[3] w=0;left=0;cw=0 subitem = 0.upto(countColumns-1){|i| left=w cw=getColumnWidthOf(i) break(i) if (w+=cw) > x } l1,top,right,bottom = getItemRect(idx) [idx,subitem,left,top,cw,bottom-top] end def self_lbuttondown(shift,x,y) @ed.hide @idx,@subitem,left,top,width,height = *hittest3(x,y) selectItem(@idx,false) return if @fixfirstcolumn && @subitem==0 @ed.move(left-1,top-1,width+2,height+2) @ed.text=getItemTextOf(@idx,@subitem) @ed.show @ed.focus refresh end def update setItemTextOf(@idx,@subitem,@ed.text) end end class ItemEditDlg < VRModalDialog include VRComCtlContainer include VROwnerDrawControlContainer attr :position,1 POS=[] ADDREMOVE=[] #enable add&remove FIXCOLUMN=[] TITLES=[] ITEMS=[] ADDINGNAME=[] UPDOWN=[] STYLES=[] LISTWIDTH=[392] DEFAULTSTR = [''] def _itemEdit_init font = @screen.factory.newfont "Terminal",-13,0,0,0,0,0,1,128,100,0 self.caption = 'ItemEditor' self.move(POS[0][0],POS[0][1],POS[0][2],POS[0][3]) addControl(EDListview,'listView1','listView1',0,0,LISTWIDTH[0],240,12) addControl(VRButton,'btOk','O K',226,246,80,24) addControl(VRButton,'btCan','Cancel',312,246,80,24) addControl(VRButton,'btAdd','Add',0,246,80,24) if ADDREMOVE[0] addControl(VRButton,'btRemove','Remove',86,246,80,24) if ADDREMOVE[0] addControl(Bt_UP,'btUP','',170,246,24,24) addControl(Bt_DN,'btDN','',198,246,24,24) addArrayedControl(0,VRRadiobutton,'radioBtn',STYLES[0][0],260,32,160,24).setFont(font) if STYLES[0]&&STYLES[0][0] addArrayedControl(1,VRRadiobutton,'radioBtn',STYLES[0][1],260,56,160,24).setFont(font) if STYLES[0]&&STYLES[0][1] addArrayedControl(2,VRRadiobutton,'radioBtn',STYLES[0][2],260,80,160,24).setFont(font) if STYLES[0]&&STYLES[0][2] addArrayedControl(3,VRRadiobutton,'radioBtn',STYLES[0][3],260,104,160,24).setFont(font) if STYLES[0]&&STYLES[0][3] addArrayedControl(4,VRRadiobutton,'radioBtn',STYLES[0][4],260,128,160,24).setFont(font)if STYLES[0]&&STYLES[0][4] addArrayedControl(5,VRRadiobutton,'radioBtn',STYLES[0][5],260,128,160,24).setFont(font)if STYLES[0]&&STYLES[0][5] @current_pos = 0 end def construct _itemEdit_init @listView1.lvexstyle=ADDREMOVE[0]? 33 : 1 @listView1.reportview TITLES[0].each{|i| @listView1.addColumn(i[0],i[1]) } 0.upto(ITEMS[0].size-1){|i| @listView1.addItem(ITEMS[0][i]) } @listView1.fixfirstcolumn=FIXCOLUMN[0] @btUP.visible = UPDOWN[0] @btDN.visible = UPDOWN[0] end def btOk_clicked a=[] 0.upto(@listView1.countItems-1){|i| a1=[] 0.upto(@listView1.countColumns-1){|j| a1 << @listView1.getItemTextOf(i,j) } a << a1 } @parent._return_val = a close 0 end def btCan_clicked close 1 end def btAdd_clicked if ADDINGNAME[0] == 'tab' then s = ADDINGNAME[0] + (@listView1.countItems+1).to_s else s = @parent.get_serial_name(ADDINGNAME[0]+'1') end @listView1.selectItem(@listView1.focusedItem,false) @listView1.addItem([DEFAULTSTR[0],s]) @listView1.setItemStateOf(@listView1.countItems-1,1) @listView1.selectItem(@listView1.countItems-1,true) end def btRemove_clicked @listView1.deleteItem(@listView1.focusedItem) @listView1.setItemStateOf(@listView1.focusedItem, WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) end def listView1_itemchanged(idx,state) @current_pos=@listView1.countItems-1-idx n = STYLES[0].index(@listView1.getItemTextOf(idx,0)) if STYLES[0] @radioBtn.each{|i| i.check false} if @radioBtn @radioBtn[n].check true if n end def btUP_clicked s = [] @listView1.ed.hide nf = @listView1.focusedItem return if nf == 0 0.upto(@listView1.countColumns-1){|i| s << @listView1.getItemTextOf(nf-1,i)} @listView1.insertItem(nf+1,s) @listView1.deleteItem(nf-1) end def btDN_clicked s = [] @listView1.ed.hide nf = @listView1.focusedItem return if nf == @listView1.countItems-1 @listView1.selectItem(nf,false) 0.upto(@listView1.countColumns-1){|i| s << @listView1.getItemTextOf(nf,i)} @listView1.insertItem(nf+2,s) @listView1.deleteItem(nf) @listView1.setItemStateOf(nf+1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) end def radioBtn_clicked(n) @listView1.setItemTextOf(@listView1.focusedItem,0,@radioBtn[n].caption) if @listView1.focusedItem > -1 end end class MenuAnalizer attr :colCount def maxCol(n) @colCount = n if n > colCount end def __analize(ar) ar.each{|i| if i[1].is_a? Array then a = [[""]*@n,i[0].gsub(/\t/,'\t')].flatten @ar << a @colCount = a.size if a.size > @colCount @n += 1 __analize(i[1]) else a = [[""]*@n,i].flatten.select{|i| i .is_a? String}.collect{|i| i.gsub /\t/,'\t'} @colCount = a.size if a.size > @colCount @ar << a end } @n -= 1 end def analize(ar) @ar=[] @n = 0 @colCount=0 __analize(ar) @ar end def __unanalize(s,level=0) r = [] i = 0 while(i < s.size) do l0 = 0 data=[] flag0=nil s[i].each{|j| if j=="" then unless flag0 then l0 += 1 else break end else data << j.sub(/\\t/,"\t") if j flag0 = true end } case l0 <=> level when -1 return r,i-1 when 0 if data == ["sep","_vrmenusep"] then r << ["sep","_vrmenusep",2048] else r << data end when 1 a = __unanalize(s[i,s.size-i],l0) r.last << a[0] i += a[1] end i += 1 end #while [r,i] end def unanalize(ar) __unanalize(ar,0)[0] end end class Bt_UP < VROwnerDrawButton def drawpushed(left,top,right,bottom,state) rect=[left,top,right,bottom].pack("iiii") DrawFrameControl.call(hdc,rect,4,0x210) drawBitmap(OwnerDrawBtnBmp::BmpUP,5,5) end def drawreleased(left,top,right,bottom,state) rect=[left,top,right,bottom].pack("iiii") DrawFrameControl.call(hdc,rect,4,0x10) drawBitmap(OwnerDrawBtnBmp::BmpUP,4,4) end end class Bt_DN < VROwnerDrawButton def drawpushed(left,top,right,bottom,state) rect=[left,top,right,bottom].pack("iiii") DrawFrameControl.call(hdc,rect,4,0x210) drawBitmap(OwnerDrawBtnBmp::BmpDN,5,5) end def drawreleased(left,top,right,bottom,state) rect=[left,top,right,bottom].pack("iiii") DrawFrameControl.call(hdc,rect,4,0x10) drawBitmap(OwnerDrawBtnBmp::BmpDN,4,4) end end class MnEDListview < EDListview attr :level attr :items attr :ed def getItemsAttr(idx) items = [] level = 0 flag0 = nil 0.upto(countColumns-1){|i| if s=getItemTextOf(idx,i) == "" then break if flag0 level += 1 else items << getItemTextOf(idx,i) flag0 = true end } [items,level] end def updateTitle(idx) @items,@level=getItemsAttr(idx) if @items.size > 1 then 0.upto(countColumns-1){|i| if i == @level then s = 'Item Caption' elsif i == @level+1 s = 'Item Event' else s = '' end setColumnTextOf(i,s) } else 0.upto(countColumns-1){|i| if i == @level then s = 'Menu Caption' else s = '' end setColumnTextOf(i,s) } end end def self_lbuttondown(shift,x,y) @items = [] @level=0 flag0 = nil @ed.hide @idx,@subitem,left,top,width,height = *hittest3(x,y) updateTitle(@idx) return if @subitem < @level or @subitem >= @level + @items.size selectItem(@idx,false) return if @fixfirstcolumn && @subitem==0 @ed.move(left-1,top-1,width+2,height+2) @ed.text=getItemTextOf(@idx,@subitem) @ed.show @ed.focus refresh end end class MenuEditDlg < VRModalDialog include VRComCtlContainer include VROwnerDrawControlContainer attr :position,1 POS=[[100,100,464,250]] FIXCOLUMN=[] TITLES=[] ITEMS=[] ADDINGNAME=[] UPDOWN=[] STYLES=[] LISTWIDTH=[460] def _itemEdit_init font = @screen.factory.newfont "Terminal",-13,0,0,0,0,0,1,128,100,0 self.caption = 'ItemEditor' self.move(POS[0][0],POS[0][1],POS[0][2],POS[0][3]) addControl(MnEDListview,'listView1','listView1',0,0,LISTWIDTH[0],240,12) addControl(VRButton,'btAddMnu','AddMnu',0,246,64,24) addControl(VRButton,'btAddItm','AddItm',68,246,64,24) addControl(VRButton,'btAddSep','AddSep',136,246,64,24) addControl(VRButton,'btRemove','Remove',204,246,64,24) addControl(Bt_UP,'btUP','',272,246,24,24) addControl(Bt_DN,'btDN','',298,246,24,24) addControl(VRButton,'btOk','O K',326,246,64,24) addControl(VRButton,'btCan','Cancel',394,246,64,24) end def construct _itemEdit_init @listView1.lvexstyle=33 @listView1.reportview TITLES[0].each{|i| @listView1.addColumn(i[0],i[1]) } 0.upto(ITEMS[0].size-1){|i| @listView1.addItem(ITEMS[0][i]) } @listView1.fixfirstcolumn=FIXCOLUMN[0] end def btOk_clicked a=[] 0.upto(@listView1.countItems-1){|i| a1=[] 0.upto(@listView1.countColumns-1){|j| a1 << @listView1.getItemTextOf(i,j) } a << a1 } @parent._return_val = a close 0 end def btCan_clicked close 1 end def find_next(pos) pos1 = pos2 = nil l1 = i1 = nil pos.upto(@listView1.countItems-1){|i| itm,lvl=@listView1.getItemsAttr(i) if @listView1.level > lvl then return pos,nil elsif @listView1.level == lvl pos1 = i if itm.size > 1 then pos2 = i break else (i+1).upto(@listView1.countItems-1){|j| i2,l2=@listView1.getItemsAttr(j) return pos1,j-1 if @listView1.level > l2 if @listView1.level == l2 then pos2 = j-1 break end } pos2 = @listView1.countItems-1 unless pos2 break end else #<EMAIL> < lvl (i+1).upto(@listView1.countItems-1){|j| i1,l1=@listView1.getItemsAttr(j) return j,nil if @listView1.level > l1 if @listView1.level == l1 then pos1 = j break end } return @listView1.countItems,nil unless pos1 if i1.size > 1 then pos2 = pos1 else (pos1+1).upto(@listView1.countItems-1){|j| i2,l2=@listView1.getItemsAttr(j) if @listView1.level == l2 then pos2 = j-1 break end } pos2 = @listView1.countItems-1 unless pos2 break end end } pos1 = @listView1.countItems unless pos1 [pos1,pos2] end def find_prev(pos) pos.downto(0){|i| itm,lvl=@listView1.getItemsAttr(i) if @listView1.level == lvl return i elsif @listView1.level > lvl return i+1 end } 0 end def btAddMnu_clicked @listView1.ed.hide if @listView1.countItems == 0 n1 = 0 0.upto(2-@listView1.countColumns){ |i|@listView1.insertColumn(0,'',112)}if @listView1.countColumns < 3 @listView1.insertItem(n1,['Menu']) else return unless @listView1.items @listView1.selectItem(@listView1.focusedItem,false) n1,n2=find_next(@listView1.focusedItem+1) @listView1.insertItem(n1,['']*(@listView1.level)+['Menu']) if n1 end @listView1.setItemStateOf(n1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) @listView1.updateTitle(@listView1.focusedItem) end def btAddItm_clicked @listView1.ed.hide if @listView1.countItems == 0 0.upto(1-@listView1.countColumns){ |i|@listView1.insertColumn(0,'',112)}if @listView1.countColumns < 2 @listView1.insertItem(0,['item','event']) n1 = -1 else return unless @listView1.items n1 = @listView1.focusedItem @listView1.selectItem(n1,false) if @listView1.items.size == 1 if @listView1.countColumns < @listView1.level+@listView1.items.size+2 @listView1.insertColumn(@listView1.countColumns,'',112) end @listView1.insertItem(n1+1,['']*(@listView1.level+1)+['item','event']) else @listView1.insertItem(n1+1,['']*(@listView1.level)+['item','event']) end end @listView1.setItemStateOf(n1+1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) @listView1.updateTitle(@listView1.focusedItem) end def btAddSep_clicked @listView1.ed.hide return if @listView1.countItems==0 return unless @listView1.items n1 = @listView1.focusedItem @listView1.selectItem(n1,false) if @listView1.items.size == 1 then if @listView1.countColumns < @listView1.level+@listView1.items.size+2 then @listView1.insertColumn(@listView1.countColumns,'',112) end @listView1.insertItem(n1+1,['']*(@listView1.level+1)+['sep','_vrmenusep']) else @listView1.insertItem(n1+1,['']*(@listView1.level)+['sep','_vrmenusep']) end @listView1.setItemStateOf(n1+1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) @listView1.updateTitle(@listView1.focusedItem) end def btRemove_clicked @listView1.ed.hide return unless @listView1.items nf=@listView1.focusedItem @listView1.selectItem(nf,false) if @listView1.items.size == 1 then n1,n2=find_next(nf+1) nf.upto(n1-1){|i| @listView1.deleteItem(nf) } if n1 else @listView1.deleteItem(nf) end nf = nf < 0 || nf >= @listView1.countItems ? 0 : nf @listView1.setItemStateOf(nf,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) @listView1.updateTitle(@listView1.focusedItem) end def btUP_clicked @listView1.ed.hide return unless @listView1.items nf=@listView1.focusedItem return if nf == 0 n0=find_prev(nf-1) return if nf == n0 n1,n2 = find_next(n0+1) return unless n2 (n1-1).downto(n0){|i| a = [] 0.upto(@listView1.countColumns-1){|j| a << @listView1.getItemTextOf(i,j)} @listView1.insertItem(n2+1,a) } (n1-1).downto(n0){|i| @listView1.deleteItem(n0) } end def btDN_clicked @listView1.ed.hide return unless @listView1.items nf=@listView1.focusedItem n1,n2=find_next(nf+1) return unless n2 @listView1.selectItem(nf,false) (n1-1).downto(nf){|i| a = [] 0.upto(@listView1.countColumns-1){|j| a << @listView1.getItemTextOf(i,j)} @listView1.insertItem(n2+1,a) } (n1-1).downto(nf){|i| @listView1.deleteItem(nf) } nf = nf + n2 - n1 + 1 @listView1.setItemStateOf(nf,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) @listView1.updateTitle(@listView1.focusedItem) end end class PreferDlg < VRModalDialog include VRCommonDialog PreferDlg_fonts=[ VRLocalScreen.factory.newfont("Terminal",-13,0,0,0,0,0,1,128,100,0), VRLocalScreen.factory.newfont("MS UI Gothic",-15,0,0,0,0,0,50,128,110,0) ] DEFAULT_FONT=PreferDlg_fonts[0] @@args=nil def self.arg= (arg); @@arg=arg end def construct self.caption = FDPrfItems::Preferences self.move(139,124,320,240) addControl(VRCheckbox,'cbCygwin',FDPrfItems::CROnly,200,116,64,24) addControl(VRStatic,'static4', FDPrfItems::CgwinLS,8,120,192,24) addControl(VRStatic,'static1',FDPrfItems::Gridsize,8,12,64,20) addControl(VRStatic,'static2',FDPrfItems::Editor,8,44,48,24) addControl(VREdit,'edGrid','',72,8,48,20) addControl(VRCheckbox,'cbLang',FDPrfItems::UseJp,188,8,100,20,0x20) addControl(VRButton,'btBrowseFon','...',288,72,24,20) addControl(VREdit,'edEditor','notepad',56,40,232,20) addControl(VREdit,'edFont','System',56,72,232,20) addControl(VRStatic,'static3',FDPrfItems::Font,8,76,48,24) addControl(VRStatic,'static5',FDPrfItems::NextStart, 8,96,200,20) addControl(VRCheckbox,'cbDock', FDPrfItems::DockInspect,8,140,264,24) addControl(VRCheckbox,'cbVerbose', FDPrfItems::Verbose,8,160,264,24) addControl(VRButton,'btBrowseEd','...',288,40,24,20) addControl(VRButton,'btOK',FDPrfItems::OK,136,188,80,24).setFont( PreferDlg_fonts[1]) addControl(VRButton,'btCan',FDPrfItems::Cancel,224,188,80,24).setFont( PreferDlg_fonts[1]) end def self_created @arg = @@arg setButtonAs(@btOK,IDOK) setButtonAs(@btCan,IDCANCEL) @btOK.focus @edEditor.text = @arg[:editor] @edGrid.text = @arg[:grid].to_s @cbCygwin.check(@arg[:cygwin]) @edFont.text= @arg[:font] @cbDock.check(@arg[:dock]) @cbVerbose.check(@arg[:verbose]) @cbLang.check($Lang=='JA') end def btBrowseEd_clicked if editpath=openFilenameDialog([["Editor","*.exe"]]) then @edEditor.text=editpath.to_s end end def btBrowseFon_clicked fon=@arg[:font].split(',') if @default_font=SWin::CommonDialog.chooseFont(self,[[fon[0],(fon[1].to_f)*4/3, 0,300,135,0,0,2,128],120,0]) @edFont.text="#{@default_font[0][0]},#{@default_font[1] / 10}" end end def btOK_clicked $Lang=@cbLang.checked? ? 'JA' : 'EN' close [@edGrid.text,@edEditor.text,@cbCygwin.checked?,@edFont.text, @cbDock.checked?,@cbVerbose.checked?] end def btCan_clicked close nil end end class TabOrderDlg < VRModalDialog include VRComCtlContainer include VROwnerDrawControlContainer DEFAULT_FONT=VRLocalScreen.factory.newfont('MS UI Gothic',-13,0,4,0,0,0,50,128) @@args=nil def TabOrderDlg.args= (args); @@args=args end def initialize; super ; @args = @@args end def _tabDlg_init self.caption = 'TAB order' self.move(@args[:x],@args[:y]+124,140,400) addControl(VRButton,'btTab',"Use TAB",52,316,80,24,1342177280) addControl(VRListview,'listView1',"listView1",0,0,132,308,1342177285) addControl(VRButton,'btOK',"OK",0,348,64,24,1342177280) addControl(VRButton,'btCan',"Cancel",68,348,64,24,1342177280) addControl(Bt_UP,'btUP',"",0,316,24,24) addControl(Bt_DN,'btDN',"",24,316,24,24) setButtonAs(@btOK,IDOK) setButtonAs(@btCan,IDCANCEL) @btOK.focus end def construct @ctlList=[] _tabDlg_init @listView1.lvexstyle=0x21 @listView1.addColumn('ord',30) @listView1.addColumn('control name',98) @args[:c].tabOrders.each_with_index{|itm,idx| @ctlList << [idx.to_s,@args[:c].controls[itm].name,itm] unless itm.is_a?(FDCoverPanel) || itm.is_a?(FDContainer) } @args[:c].controls.each{|k,itm| @ctlList << ["",itm.name,k] unless @args[:c].tabOrders.index(k) unless itm.is_a?(FDCoverPanel) || itm.is_a?(FDContainer) } @ctlList.each{|i|@listView1.addItem(i[0,2])} @tabCount=@args[:c].tabOrders.size end def btUP_clicked nf=@listView1.focusedItem if nf > 0 then s=@listView1.getItemTextOf(nf-1,1) @listView1.setItemTextOf(nf-1,1,@listView1.getItemTextOf(nf,1)) @listView1.setItemTextOf(nf,1,s) @listView1.setItemStateOf(nf-1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) a1=@ctlList[nf-1][1,2] @ctlList[nf-1][1,2]=@ctlList[nf][1,2] @ctlList[nf][1,2]=a1 end @listView1.focus end def btDN_clicked nf=@listView1.focusedItem if nf < @listView1.countItems-1 then s=@listView1.getItemTextOf(nf+1,1) @listView1.setItemTextOf(nf+1,1,@listView1.getItemTextOf(nf,1)) @listView1.setItemTextOf(nf,1,s) @listView1.setItemStateOf(nf+1,WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) a1=@ctlList[nf+1][1,2] @ctlList[nf+1][1,2]=@ctlList[nf][1,2] @ctlList[nf][1,2]=a1 end @listView1.focus end def btTab_clicked if @ctlList[@listView1.focusedItem][0] == "" then @ctlList[@listView1.focusedItem][0]="#{@tabCount+=1}" else @ctlList[@list<EMAIL>Item][0]="" @tabCount-=1 end @ctlList.sort!{|a,b| a1 = a[0] == '' ? 0x100000000 : a[0].to_i b1 = b[0] == '' ? 0x100000000 : b[0].to_i a1 <=> b1} @ctlList.each_with_index{|itm,idx| itm[0] = idx if itm[0] != '' } @listView1.clearItems @ctlList.each{|i|@listView1.addItem(i)} @listView1.focus end def btOK_clicked @args[:c].tabOrders = @ctlList.collect{|i| if i[0]!="" then i[2] end }.select{|i| i} close true end def btCan_clicked close nil end def listView1_itemchanged(idx,state) return if state != 0 if @listView1.getItemTextOf(idx,0)== "" then @btTab.caption="Use TAB" else @btTab.caption="Unuse TAB" end c0 = @args[:c].controls.select{|k,v| v.name == @listView1.getItemTextOf(idx,1)}[0][1] @args[:frm].setFocusRgn(c0) end end class NewProjectDlg < VRModalDialog @@args=nil def NewProjectDlg.args=(arg) @@args=arg end def construct arg=@@args; @@args=nil self.caption = arg + FDNewProjectItem::NewProject self.move(163,149,400,185) addControl(VRRadiobutton,'rbMono',FDProjectTypes::Mono,48,80,280,24) addControl(VRButton,'btOK',"O K",160,120,80,24,0x50000000) addControl(VRStatic,'static1',FDNewProjectItem::Prompt,48,16,280,24) addControl(VRRadiobutton,'rbApart',FDProjectTypes::Apart,48,48,280,24) @rbApart.check true setButtonAs(@btOK,IDOK) end def btOK_clicked close @rbApart.checked? end end class LayoutDlg < VRModalDialog include VRComCtlContainer include VROwnerDrawControlContainer DEFAULT_FONT=VRLocalScreen.factory.newfont('MS UI Gothic',-13,0,4,0,0,0,50,128) @@args=nil def LayoutDlg.args= (args); @@args=args end def initialize; super ; @args = @@args end class TabPane < VRTabControl include VRComCtlContainer include VRMessageParentRelayer attr :listView1,1 def construct insertTab(0,"") addControl(VRListview,'listView1',"listView1",*adjustRect(x,y,w-4,h)) @listView1.lvexstyle=0x21 @listView1.addColumn('*',18) @listView1.addColumn('control name',@listView1.w-22) end end def _registerDlg_init self.caption = 'Register' self.move(@args[:x],@args[:y]+124,140,400) addControl(TabPane,'tabPane','',0,0,self.w-8,self.h-84,WStyle::TCS_BOTTOM) addControl(VRButton,'btRegister',"Register",48,320,84,24) addControl(VRButton,'btOK',"OK",0,348,64,24) addControl(VRButton,'btCan',"Cancel",68,348,64,24) addControl(Bt_UP,'btUP',"",0,320,24,24) addControl(Bt_DN,'btDN',"",24,320,24,24) setButtonAs(@btOK,IDOK) setButtonAs(@btCan,IDCANCEL) @btOK.focus end def construct _registerDlg_init if @args[:focused].substance.is_a? VRHorizTwoPaneFrame @tabPane.setTabTextOf(0,"left") @tabPane.insertTab(1,"right") elsif @args[:focused].substance.is_a? VRVertTwoPaneFrame @tabPane.setTabTextOf(0,"upper") @tabPane.insertTab(1,"lower") else @tabPane.setTabTextOf(0,"layout") end @ctlList=[[],[]] @registerd = [[],[]] @current_tab = 0 @args[:c].controls.each{|k,itm| if itm.is_a?(FDContainer) sb = itm.substance next unless sb.is_a?(VRLayoutFrame)|| itm.substance.is_a?(VRTwoPaneFrame) next if (@args[:c].instance_eval("@__regsterd_vr_margined_frame")==sb) if @args[:focused] == itm next elsif itm.registerd_to.empty? @ctlList[0] << ["",itm.name] @ctlList[1] << ["",itm.name] elsif itm.registerd_to[0] == @args[:focused] @ctlList[itm.registerd_to[1]] << ["*",itm.name] @registerd[itm.registerd_to[1]] << itm else end elsif !(itm.is_a?(FDCoverPanel)) # p [itm.name,itm.registerd_to] if @args[:focused] == itm next elsif itm.registerd_to.empty? @ctlList[0] << ["",itm.name] @ctlList[1] << ["",itm.name] elsif itm.registerd_to[0] == @args[:focused] @ctlList[itm.registerd_to[1]] << ["*",itm.name] @registerd[itm.registerd_to[1]] << itm else end else end } @ctlList[0].each{|i|@tabPane.listView1.addItem(i)} @current_tab = @tabPane.selectedTab end def tabPane_listView1_itemchanged(idx,state) return if state != 0 if @tabPane.listView1.getItemTextOf(idx,0) == "" then @btRegister.caption="Register" else @btRegister.caption="UnRegister" end c0 = @args[:c].controls.select{|k,v| v.name == @tabPane.listView1.getItemTextOf(idx,1)}[0][1] @args[:frm].setFocusRgn(c0) end def tabPane_selchanged @ctlList[@current_tab].clear 0.upto(@tabPane.listView1.countItems-1){|i| @ctlList[@current_tab] << [@tabPane.listView1.getItemTextOf(i,0), @tabPane.listView1.getItemTextOf(i,1)]} @tabPane.listView1.clearItems @ctlList[@tabPane.selectedTab].each{|i|@tabPane.listView1.addItem(i)} @current_tab = @tabPane.selectedTab end def tabPane_listView1_columnclick(subitem) btRegister_clicked if subitem == 0 end def btRegister_clicked return if @tabPane.listView1.countItems == 0 n = @current_tab==0 ? 1 : 0 s = @tabPane.listView1.getItemTextOf(@tabPane.listView1.focusedItem,1) if @tabPane.listView1.getItemTextOf(@tabPane.listView1.focusedItem,0) == "" @tabPane.listView1.setItemTextOf(@tabPane.listView1.focusedItem,0,"*") @registerd[@current_tab] << @args[:c].controls.find{|k,i| i.name == s}[1] @ctlList[n].reject!{|i| i[1] == s} if @tabPane.countTabs > 1 else @tabPane.listView1.setItemTextOf(@tabPane.listView1.focusedItem,0,"") @registerd[@current_tab].reject!{|i| i.name == s} @ctlList[n] << ["",s] if @tabPane.countTabs > 1 end @tabPane.listView1.focus end def btUP_clicked nf=@tabPane.listView1.focusedItem if nf > 0 then s=@tabPane.listView1.getItemTextOf(nf-1,0) @tabPane.listView1.setItemTextOf(nf-1,0, @tabPane.listView1.getItemTextOf(nf,0)) @tabPane.listView1.setItemTextOf(nf,0,s) s=@tabPane.listView1.getItemTextOf(nf-1,1) @tabPane.listView1.setItemTextOf(nf-1,1, @tabPane.listView1.getItemTextOf(nf,1)) @tabPane.listView1.setItemTextOf(nf,1,s) @tabPane.listView1.setItemStateOf(nf,0) @tabPane.listView1.setItemStateOf(nf-1, WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) end @tabPane.listView1.focus end def btDN_clicked nf=@tabPane.listView1.focusedItem if nf < @tabPane.listView1.countItems-1 then s=@tabPane.listView1.getItemTextOf(nf+1,0) @tabPane.listView1.setItemTextOf(nf+1,0, @tabPane.listView1.getItemTextOf(nf,0)) @tabPane.listView1.setItemTextOf(nf,0,s) s=@tabPane.listView1.getItemTextOf(nf+1,1) @tabPane.listView1.setItemTextOf(nf+1,1, @tabPane.listView1.getItemTextOf(nf,1)) @tabPane.listView1.setItemTextOf(nf,1,s) @tabPane.listView1.setItemStateOf(nf,0) @tabPane.listView1.setItemStateOf(nf+1, WConst::LVIS_SELECTED|WConst::LVIS_FOCUSED) end @tabPane.listView1.focus end def btOK_clicked r = [] @tabPane.selectTab(0) tabPane_selchanged n = @tabPane.listView1.countItems 0.upto(n-1) do |i| if @tabPane.listView1.getItemTextOf(i,0) == '*' then r << @args[:c].controls.find{|k,itm| itm.name == @tabPane.listView1.getItemTextOf(i,1) }[1] end end if @tabPane.countTabs > 1 then r = [r,[]] 0.upto(@ctlList[1].size-1) do |i| if @ctlList[1][i][0] == '*' then r[1] << @args[:c].controls.find{|k,itm| itm.name == @ctlList[1][i][1] }[1] end end end close r end def btCan_clicked close nil end end class VersionDlg < VRModalDialog VersionDlg_fonts=[ VRLocalScreen.factory.newfont('Times New Roman',-16,1,7,0,0,0,18,0), VRLocalScreen.factory.newfont('Times New Roman',-21,1,7,0,0,0,18,0), VRLocalScreen.factory.newfont('Times New Roman',-13,0,4,0,0,0,18,0), VRLocalScreen.factory.newfont('Times New Roman',-13,2,4,0,0,0,18,0), VRLocalScreen.factory.newfont('Times New Roman',-16,0,7,0,0,0,18,0) ] ShellExecute = Win32API.new('shell32','ShellExecute','LPPPPL','L') include VRCtlColor include VRDrawable include VRMouseFeasible include VRContainersSet def self.args=(arg) @@args = arg ;end def construct self.caption = 'Version information of FormDesigner' self.move(168,196,496,246) addControl(VRStatic,'static9',"000000",384,40,56,16,0x2) @static9.setFont(VersionDlg_fonts[0]) addControl(VRStatic,'static1',"The FormDesigner for Project VisualuRuby",56,8,384,24) @static1.setFont(VersionDlg_fonts[1]) addControl(VRStatic,'static2',"Written by:",16,80,96,16,0xb) @static2.setFont(VersionDlg_fonts[2]) addControl(VRStatic,'static7',"https://sourceforge.jp/projects/fdvr",160,128,192,16) @static7.setFont(VersionDlg_fonts[3]) addControl(VRStatic,'static3',"<EMAIL>",160,80,176,16) @static3.setFont(VersionDlg_fonts[2]) addControl(VRStatic,'static8',"Version:",328,40,56,16) @static8.setFont(VersionDlg_fonts[0]) addControl(VRStatic,'static5',"<EMAIL>",160,104,176,16) @static5.setFont(VersionDlg_fonts[2]) addControl(VRButton,'button1',"O K",192,184,104,24) @button1.setFont(VersionDlg_fonts[4]) addControl(VRStatic,'static10',"VisualuRuby Home Page:",16,152,136,16) @static10.setFont(VersionDlg_fonts[2]) addControl(VRStatic,'static6',"Project Home Page:",16,128,112,16) @static6.setFont(VersionDlg_fonts[2]) addControl(VRStatic,'static4',"Basic designed by:",16,104,112,16) @static4.setFont(VersionDlg_fonts[2]) addControl(VRStatic,'static11',"",160,152,320,16) if $Lang == 'EN' @static11.caption = "http://www.osk.3web.ne.jp/~nyasu/vruby/vrproject-e.html" else @static11.caption = "http://www.osk.3web.ne.jp/~nyasu/software/vrproject.html" end @static11.setFont(VersionDlg_fonts[3]) setButtonAs(@button1,IDOK) @button1.focus end def hittest(x,y) if @static7.x <= x && x <= @static7.x+@static7.w && @static7.y <= y && y <= @static7.y+@static7.h @static7 elsif @static11.x <= x && x <= @static11.x+@static11.w && @static11.y <= y && y <= @static11.y+@static11.h @static11 else nil end end def self_mousemove(shift,x,y) if ctl = hittest(x,y) @ctl = ctl ctl.setCtlTextColor(0xff0000) ctl.refresh elsif @ctl @ctl.setCtlTextColor(0x0) @ctl.refresh end end def self_lbuttonup(shift,x,y) if c = hittest(x,y) s = c.caption ShellExecute.call(0, nil, s, nil, nil, 0) close nil end end def self_created arg = @@args @static9.caption = arg.to_s centering(nil) setButtonAs(@button1,IDOK) @controls.each{|i,c| addCtlColor(c) unless c.is_a? VRButton} @ctl = nil @bmp = SWin::Bitmap.newBitmap(1,64) 0.upto(63){|i|@bmp[0,i]=[0xff,0xff,0xff]} end def self_paint stretchBitmap 0,0,self.w,self.h,@bmp end def button1_clicked self.close nil end end <file_sep># fdresources.rb # Bitmaps of pallets # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'vr/vrcontrol' require 'vr/vrcomctl' module FDBmps BmpNoselect=" BAV1OhFTV2luOjpCaXRtYXACigFCTYoBAAAAAAAAdgAAACgAAAAXAAAAFwAA AAEABAAAAAAAFAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACAAAAAgIAA gAAAAIAAgACAgAAAgICAAMDAwAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD/ //8AZmZmZmZmZmZmZmZgZmZmZmZmZmZmZmZgZmZmZmZmZmZmZmZgZmZmZmZm ZmZgZmZgZmZmZmZmZmYPBmZgZmZmZmZmZmD/8GZgZmZmZmZmZg//BmZgZmZm ZmZmYP/wZmZgZmZmZgZmD/8GZmZgZmZmZgBg//BmZmZgZmZmYP8P/wZmZmZg ZmZmYP//8GZmZmZgZmZmD///BmZmZmZgZmZmD///8GZmZmZgZmZg////8AZm ZmZgZmZg///wBmZmZmZgZmYP//AGZmZmZmZgZmYP8AZmZmZmZmZgZmDwBmZm ZmZmZmZgZmAGZmZmZmZmZmZgZmZmZmZmZmZmZmZgZmZmZmZmZmZmZmZgZmZm ZmZmZmZmZmZg " =begin BmpBitmapPanel = " eJx9kEtPwzAQhO/+KxwGsCrFx62TyD2gNlZVpUckyymPCg6g8PPZ9SMpF9ay 4288GT/Ulk4P+0t/PD2+f+9fP+3z6L/OI9mXqbfH88eWSoWJBysDjTL0M5Ei 6qg6ep7/X7Z0omnHP6csnkwsTknkxaeWZtEPTe7UAnMLkdL<KEY> " BmpButton = " <KEY> " BmpCanvasPanel = " <KEY> " BmpCheckbox = " <KEY> " BmpColorDlg = " <KEY> " BmpCombobox = " <KEY> " BmpEdCombo = " <KEY> " BmpEdit = " <KEY> " BmpFolder = " <KEY> <KEY> " BmpFontDlg = " <KEY> " BmpFullsize = " <KEY> Z/BraHFgUcMDBla0hQ== " BmpGridFrame = " <KEY> " BmpGroupbox = " <KEY> " BmpHoriz2Pane = " <KEY> " BmpHorizFrame = " <KEY> " BmpListbox = " <KEY> " BmpListview = " <KEY> <KEY> " BmpMenu = " <KEY> " BmpMmedia = " <KEY> " BmpOpenDlg = " <KEY> " BmpPanel = " <KEY> " BmpPopupMenu = " <KEY> " BmpPrinter = " <KEY> " BmpProgressbar = " <KEY> " BmpRadiobutton = " <KEY> " BmpRebar = " <KEY> " BmpRichedit = " <KEY> " BmpSaveDlg = " e<KEY>/<KEY> " BmpStatic = " <KEY> " BmpStatusbar = " <KEY> " BmpTabControl = " <KEY> " BmpTabbedPanel = " <KEY> " BmpText = " <KEY> " BmpToolbar = " <KEY> " BmpTooltip = " <KEY> " BmpTrackbar = " <KEY> " BmpTreeview = " <KEY> " BmpUpdown = " <KEY> " BmpVert2Pane = " <KEY> " BmpVertFrame = " <KEY> " =end end module FDFakeClass class FDPopup end class FDOpenDlg attr :filters,1 attr :flags,1 attr :title,1 attr :defaultExt,1 end class FDSaveDlg attr :filters,1 attr :flags,1 attr :title,1 attr :defaultExt,1 end class FDFontDlg end class FDColorDlg end class FDSelectDir attr :flags,1 attr :title,1 attr :initialdir,1 end class FDLayout attr :register,1 attr :position,1 end end module FDComDlgItems OpenFileFlag = { "OFN_ALLOWMULTISELECT" => 512, "OFN_CREATEPROMPT" => 0x2000, # "OFN_ENABLEHOOK" => 32, # "OFN_ENABLETEMPLATE" => 64, # "OFN_ENABLETEMPLATEHANDLE" => 128, "OFN_EXPLORER" => 0x80000, "OFN_EXTENSIONDIFFERENT" => 0x400, "OFN_FILEMUSTEXIST" => 0x1000, "OFN_HIDEREADONLY" => 4, "OFN_LONGNAMES" => 0x200000, "OFN_NOCHANGEDIR" => 8, "OFN_NODEREFERENCELINKS" => 0x100000, "OFN_NOLONGNAMES" => 0x40000, "OFN_NONETWORKBUTTON" => 0x20000, # "OFN_NOREADONLYRETURN" => 0x8000, # "OFN_NOTESTFILECREATE" => 0x10000, # "OFN_NOVALIDATE" => 256, # "OFN_OVERWRITEPROMPT" => 2, "OFN_PATHMUSTEXIST" => 0x800, "OFN_READONLY" => 1, # "OFN_SHAREAWARE" => 0x4000, "OFN_SHOWHELP" => 16, # "OFN_SHAREFALLTHROUGH" => 2, # "OFN_SHARENOWARN" => 1, # "OFN_SHAREWARN" => 0, # "OFN_NODEREFERENCELINKS" => 0x100000 } SaveFileFlag = { # "OFN_ALLOWMULTISELECT" => 512, "OFN_CREATEPROMPT" => 0x2000, # "OFN_ENABLEHOOK" => 32, # "OFN_ENABLETEMPLATE" => 64, # "OFN_ENABLETEMPLATEHANDLE" => 128, "OFN_EXPLORER" => 0x80000, "OFN_EXTENSIONDIFFERENT" => 0x400, # "OFN_FILEMUSTEXIST" => 0x1000, "OFN_HIDEREADONLY" => 4, "OFN_LONGNAMES" => 0x200000, "OFN_NOCHANGEDIR" => 8, "OFN_NODEREFERENCELINKS" => 0x100000, "OFN_NOLONGNAMES" => 0x40000, "OFN_NONETWORKBUTTON" => 0x20000, "OFN_NOREADONLYRETURN" => 0x8000, "OFN_NOTESTFILECREATE" => 0x10000, "OFN_NOVALIDATE" => 256, "OFN_OVERWRITEPROMPT" => 2, "OFN_PATHMUSTEXIST" => 0x800, "OFN_READONLY" => 1, # "OFN_SHAREAWARE" => 0x4000, "OFN_SHOWHELP" => 16, # "OFN_SHAREFALLTHROUGH" => 2, # "OFN_SHARENOWARN" => 1, # "OFN_SHAREWARN" => 0, # "OFN_NODEREFERENCELINKS" => 0x100000 } BrowseFolderFlag = { "BIF_RETURNONLYFSDIRS"=>1, "BIF_DONTGOBELOWDOMAIN"=>2, "BIF_STATUSTEXT"=>4, "BIF_RETURNFSANCESTORS"=>8, "BIF_EDITBOX"=>16, "BIF_VALIDATE"=>32, "BIF_NEWDIALOGSTYLE"=>64, "BIF_BROWSEINCLUDEURLS"=>128, "BIF_USENEWUI"=>80, "BIF_BROWSEFORCOMPUTER"=>0x1000, "BIF_BROWSEFORPRINTER"=>0x2000, "BIF_BROWSEINCLUDEFILES"=>0x4000, "BIF_SHAREABLE"=>0x8000 } end module OwnerDrawBtnBmp BmpDN = SWin::Bitmap.loadString( ' BAh1OhFTV2luOjpCaXRtYXAB7kJN7gAAAAAAAAB2AAAAKAAAAA8AAAAPAAAA AQAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIAAAACAgACA AAAAgACAAICAAADOzs4AgICAAAAA/wAA/wAAAP//AP8AAAD/AP8A//8AAP// /wB3d3d3d3d3cHd3d3d3d3dwd3d3d3d3d3B3d3dwd3d3cHd3dwAHd3dwd3dw AAB3d3B3dwAAAAd3cHdwAAAAAHdwdwAAAAAAB3BwAAAAAAAAcAAAAAAAAAAA d3d3d3d3d3B3d3d3d3d3cHd3d3d3d3dwd3d3d3d3d3A= ') BmpUP = SWin::Bitmap.loadString( ' BAh1OhFTV2luOjpCaXRtYXAB7kJN7gAAAAAAAAB2AAAAKAAAAA8AAAAPAAAA AQAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIAAAACAgACA AAAAgACAAICAAADOzs4AgICAAAAA/wAA/wAAAP//AP8AAAD/AP8A//8AAP// /wB3d3d3d3d3cHd3d3d3d3dwd3d3d3d3d3B3d3d3d3d3cAAAAAAAAAAAcAAA AAAAAHB3AAAAAAAHcHdwAAAAAHdwd3cAAAAHd3B3d3AAAHd3cHd3dwAHd3dw d3d3cHd3d3B3d3d3d3d3cHd3d3d3d3dwd3d3d3d3d3A= ') end module FDHelp HH_hash={"VRForm"=>0x1000, "VRLayoutManager"=>0x1001, "VRVertLayoutManager"=>0x1002, "VRHorizLayoutManager"=>0x1003, "VRGridLayoutManager"=>0x1004, "VRDropFileTarget"=>0x1005, "VRVertTwoPane"=>0x1006, "VRHorizTwoPane"=>0x1007, "VRDrawable"=>0x1008, "VRMenuUseable"=>0x1009, "VRCommonDialog"=>0x100a, "VRMediaViewModeNotifier"=>0x100b, "VRButton"=>0x100c, "VRCheckbox"=>0x100d, "VRRadiobutton"=>0x100e, "VRGroupbox"=>0x100f, "VRStatic"=>0x1010, "VREdit"=>0x1011, "VRText"=>0x1012, "VRListbox"=>0x1013, "VRCombobox"=>0x1014, "VREditCombobox"=>0x1015, "VRRichedit"=>0x1016, "VRListview"=>0x1017, "VRTreeview"=>0x1018, "VRProgressbar"=>0x1019, "VRTrackbar"=>0x101a, "VRUpdown"=>0x101b, "VRStatusbar"=>0x101c, "VRTabControl"=>0x101d, "VRTabbedPanel"=>0x101e, "VRRebar"=>0x101f, "VRToolbar"=>0x1020, "VRPanel"=>0x1021, "VRBitmapPanel"=>0x1022, "VRCanvasPanel"=>0x1023, "VRMediaView"=>0x1024, "VRMenu"=>0x1025, "VRMenuItem"=>0x1026, "VRWinComponent"=>0x1027, "VRMessageHandler"=>0x1028, "VRParent"=>0x1029, "VRStdControlContainer"=>0x102a, "VRComCtlContainer"=>0x102b, "VRScreen"=>0x102c} end module FDSources BeginOfFD="##__BEGIN_OF_FORMDESIGNER__\n" Caution="## CAUTION!! ## This code was automagically ;-) created by "<< "FormDesigner.\n## NEVER modify manualy -- otherwise, you'll have a "<< "terrible experience.\n\n" EndOfFD="##__END_OF_FORMDESIGNER__\n" TagOfFD="##__BY_FDVR" Follows=<<EEOOSS ## Now,you can describe freely in subsequent lines. ## But be carefully to change the line tagged "#{TagOfFD}". EEOOSS StartOfForm="VRLocalScreen.start " StartOfModeless="VRLocalScreen.modelessform(nil,WStyle::WS_OVERLAPPEDWINDOW," StartOfMdlsDlg="VRLocalScreen.modelessform(nil,nil," StartOfModeless2=").show\nVRLocalScreen.messageloop" end module FDMsg end <file_sep># fdcontroldesign.rb # The form to controls designing # # Programmed by <EMAIL> # Copyright 2001-2004 <NAME> require 'vr/vruby' require 'vr/sysmod' require 'vr/vrcontrol' require 'vr/vrcomctl' require 'vr/vrhandler' require 'vr/winconst' require 'vr/rscutil' require 'vr/vrrichedit' require 'vr/vrtooltip' require 'vr/contrib/inifile' require 'vr/vrtimer' require 'vr/vrddrop' require 'vr/vrclipboard' require 'vr/vrddrop' require 'vr/vrmmedia' require 'vr/vrmargin' require 'vr/vrmgdlayout' require 'fdvr/fdwin32' require 'fdvr/fdparser' require 'fdvr/fdwstyle' require 'fdvr/fdmodules' require 'fdvr/fdresources' require 'fdvr/fdcfg' module FDMouseControl R2_COPYPEN = 13 R2_NOTXORPEN = 10 def step(v) if @enableGrid then v-v%@span else v end end end class FDContainer < VRBitmapPanel include FDDraggable attr_accessor :substance, :items undef :addControl def self_destroy #unhookwndproc self.terminate if defined? self.terminate end end class ModStruct attr_reader :name, :oldname attr_accessor :childs, :parent, :tline, :sline, :eline def initialize(oldname,name,parent,childs=[]) @oldname = oldname @name = name @parent = parent @childs = childs @tline = nil @sline = nil @eline = nil end def find(str) self.childs.find{|i| i.oldname == str} end end module FDControlDesign # for DesignForm include VRFocusSensitive include VRMenuUseable include VRToolbarUseable include VRDrawable include VRResizeable include VRClosingSensitive include VRCommonDialog include VRParent include VRMarginedFrameUseable include VRDropFileTarget include FDMouseControl include VRTimerFeasible include CreateCtrl #from 'fdcfg' include FDCommonMethod include WConst include FDParent include FDFakeClass attr_reader :controls, :modules, :names attr_accessor :form, :type_of_form, :creation, :span, :enableGrid, :name attr_accessor :oldname, :sender, :focused, :focusExists, :buff1, :linscan2 attr_accessor :cntnmodules, :_return_val, :tabOrders, :_default_font def vrinit super @app=@screen.application @curs=@app::SysCursors end def construct begin SWin::Application.setAccel(self,@parent) ;rescue ;end lpRect = ' ' * 16 @span=$ini.read('settings','span',8).to_i addHandler WMsg::WM_LBUTTONDOWN,'lbuttondown',MSGTYPE::ARGLINTINT,nil addHandler WMsg::WM_MOUSEMOVE, 'mousemove',MSGTYPE::ARGINTINTINT,nil addHandler WMsg::WM_LBUTTONUP, 'lbuttonup', MSGTYPE::ARGLINTINT,nil addHandler WMsg::WM_RBUTTONUP, 'rbuttonup', MSGTYPE::ARGINTSINTSINT,nil addHandler WMsg::WM_RBUTTONDOWN,'rbuttondown',MSGTYPE::ARGINTSINTSINT,nil addHandler WMsg::WM_MOVE, 'move', MSGTYPE::ARGLINTINT,0 acceptEvents [WMsg::WM_LBUTTONUP,WMsg::WM_RBUTTONUP, WMsg::WM_LBUTTONDOWN,WMsg::WM_RBUTTONDOWN, WMsg::WM_MOUSEMOVE,WMsg::WM_MOVE] @dc=GetDC.Call(self.hWnd) x,y,w,h = self.clientrect @hrgn=CreateRectRgn.Call(x,y,w,h) SelectClipRgn.Call(@dc,@hrgn) @hBrush=CreateBrush.call(0) @oldBrush=SelectObject.Call(@dc,@hBrush) @hPen = CreatePen.Call(0,2,0x00404040) @oldhPen=SelectObject.Call(@dc,@hPen) @selected_point=Struct.new(:x,:y)[0,0] @paste_to=nil @copy_buff=[] init_designfrm end def init_designfrm @form=self @type_of_form=VRForm @names=[] # @controls={} @focus=[0,0,0,0] @moving=false; @resizing=false @x1=@x2=@y1=@y2=0 @enableGrid=true @required=["vruby"] @included=[] @modules=[] @tabOrders=[] @_hsh_font={} @temp_fonts=[] @_font_array=[] @font_hash={} @name="form1" @oldname="form1" @buff="" @frm_sizebox = 'true' @frm_maximizebox = 'true' # arrydlgcreate moddlgcreate createinit fd_parent_init refreshCntName refreshInspect(nil) end def addControl(*args) r = super if @_default_font then r.setFont(@_default_font) end r end =begin def arrydlgcreate tpl = VRDialogTemplate.new tpl.style = WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_SETFONT tpl.fontname = "MS Gothic" tpl.fontsize = 11 tpl.caption="Array Editor" btok = tpl.addDlgControl(VRButton,"O K",5,187,40,12,0x00010000) btcan = tpl.addDlgControl(VRButton,"Cancel",50,187,40,12,0x00010000) ed1 = tpl.addDlgControl(VREdit,"",2,2,200,180,0x00b01064) @arrydlg=ArrayEditDialog.new(@screen,tpl) @arrydlg.options ={"target"=>ed1,"okbutton"=>btok, "cancelbutton"=>btcan,"default" => [["",""]]} end =end def moddlgcreate tpl = VRDialogTemplate.new tpl.style = WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_SETFONT tpl.fontname = "Terminal" tpl.fontsize = 10 tpl.caption="Modules" btok = tpl.addDlgControl(VRButton,"O K",5,182,40,12) btcan = tpl.addDlgControl(VRButton,"Cancel",50,182,40,12) lb1 = tpl.addDlgControl(VRListbox,"",2,2,100,164,0x0060) @moddlg=ListBoxDlg.new(@screen,tpl) @moddlg.options ={"target"=>lb1,"okbutton"=>btok, "cancelbutton"=>btcan,"default" => [["",0]]} end def setPenMode(mode) SetROP2.Call(@dc,mode) end def rect(x1,y1,x2,y2) MoveTo.Call(@dc,x1,y1,0) LineTo.Call(@dc,x2,y1); LineTo.Call(@dc,x2,y2); LineTo.Call(@dc,x1,y2); LineTo.Call(@dc,x1,y1) end def get_serial_name(s) s1 = s.dup if @names.index(s1) then s1.sub! /(\d+)$/ , "" s1 << "#{$1.to_i+1}" get_serial_name(s1) else @names << s1 s1 end end def delete_serial_name(s) @names.delete(s) end def self_paint if @enableGrid then a=clientrect SetROP2.Call(hdc,8) nh=(a[2]/@span).to_i;nv=(a[3]/@span).to_i setBrush(0) dc=self.hdc i=0 #draw grids for i in 0.. nh grMoveTo(i*@span,0) grLineTo(i*@span,nv*@span) end for i in 0.. nv grMoveTo(0,i*@span) grLineTo(nh*@span,i*@span) end SetROP2.Call(hdc,13) end if @focusExists then addTimer(50) end end def self_timer paintFocusRect deleteTimer end def paintFocusRect dopaint do Rectangle.Call(@dc,@x1-5,@y1-5,@x1,@y1) Rectangle.Call(@dc,@x2+5,@y2+5,@x2,@y2) Rectangle.Call(@dc,@x1-5,@y2+5,@x1,@y2) Rectangle.Call(@dc,@x2+5,@y1-5,@x2,@y1) Rectangle.Call(@dc,@x1-5,(@y1+@y2)/2-3,@x1,(@y1+@y2)/2+2) Rectangle.Call(@dc,@x2+5,(@y1+@y2)/2-3,@x2,(@y1+@y2)/2+2) Rectangle.Call(@dc,(@x1+@x2)/2-3,@y1-5,(@x1+@x2)/2+2,@y1) Rectangle.Call(@dc,(@x1+@x2)/2-3,@y2+5,(@x1+@x2)/2+2,@y2) end if @focusExists end def setFocusRgn(c) unless c then @x1=@x2=@y1=@y2=nil @focusExists = false else if c.parent.is_a?(VRForm) then @x1=c.x;@y1=c.y;@x2=c.x+c.w;@y2=c.y+c.h else a=getFormPos(c) @x1=a[0];@y1=a[1];@x2=a[0]+c.w;@y2=a[1]+c.h end end end def getFormPos(c) r=[0,0] if c then if c.parent.is_a?VRForm then r[0]=c.x;r[1]=c.y else a=getFormPos(c.parent) r[0]=c.x+a[0];r[1]=c.y+a[1] end end r end def resizecursor(l,r,t,b) # from visualu.rb if l if t @curs.SizeNWSE elsif b @curs.SizeNESW else @curs.SizeWE end elsif r if t @curs.SizeNESW elsif b @curs.SizeNWSE else @curs.SizeWE end elsif t or b @curs.SizeNS else @curs.Arrow end end def controlstate(l,r,t,b) @moving = @resizeALL = @resizeLR = @resizeUD = false if l @ox1=@x2 if t @oy1=@y2;@resizeALL=true elsif b @oy1=@y1;@resizeALL=true else @oy1=@y1;@resizeLR=true end elsif r @ox1=@x1 if t @oy1=@y2;@resizeALL=true elsif b @oy1=@y1;@resizeALL=true else @oy1=@y1;@resizeLR=true end elsif t @ox1=@x1;@oy1=@y2;@resizeUD=true elsif b @ox1=@x1;@oy1=@y1;@resizeUD=true else @ox1=@x1;@oy1=@y1;@ox2=@x2;@oy2=@y2 @moving=true end end def set_selected_point(sx,sy) @selected_point.x = sx @selected_point.y = sy end def self_lbuttonup(x,y) num=1 ; @dragging = false sx=step(x < 0xefff ? x : x-0x10000) sy=step(y < 0xefff ? y : y-0x10000) ox=oy=0;a=[0,0] set_selected_point(sx,sy) if @containerCnt != self || @focused && @focused.parent != self then if @containerCnt != self then a = getFormPos(@containerCnt) ox = a[0]; oy = a[1] end end if @creation then nam = get_serial_name(@creation.inst + "1") @creating=instance_eval("#{@creation.createMethod}(@containerCnt,@creation, nam,nam,@ox1-ox,@oy1-oy,@creation.dflt_w, @creation.dflt_h)") return unless @creating if @creating && sx - @ox1 >0 && sy - @oy1 >0 then @creating.move @ox1-ox,@oy1-oy,sx-@ox1,sy-@oy1 end moveC(@creating) @focused=@creating @creating.parent.child_created(@creating) if @creating.parent.respond_to? :child_created setFocusRgn(@focused) @focusExists = true if @focused refreshCntName @parent.inc_modified elsif @resizeALL then # p 'resizeALL' if @ox1 < sx then x1=@ox1 ; w=sx-@ox1 if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_w = #{w}") unless @focused.mgRight end else x1=sx ; w=@ox1-sx if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_x = @__org_x + @__org_w - #{w}; @__org_w = #{w}") unless @focused.mgLeft end end if @oy1 < sy then y1=@oy1 ; h=sy-@oy1 if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_h = #{h}") unless @focused.mgBottom end else y1=sy ; h=@oy1-sy if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_y = @__org_y + @__org_h - #{h}; @__org_h = #{h}") unless @focused.mgTop end end @focused.move(x1-ox,y1-oy,w,h) unless @focused.respond_to?(:initMargin) moveC(@focused) setFocusRgn(@focused) @focusExists = true @parent.inc_modified elsif @resizeLR then # p 'resizeLR' if @ox1 < sx then # p 'right' x1=@ox1 ; w=sx-@ox1 if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_w = #{w}") unless @focused.mgRight end else # p 'left' x1=sx ; w=@ox1-sx if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_x = @__org_x + @__org_w - #{w}; @__org_w = #{w}") unless @focused.mgLeft end end @focused.move(x1-ox,@focused.y,w,@focused.h) unless @focused.respond_to?(:initMargin) moveC(@focused) setFocusRgn(@focused) @focusExists = true @parent.inc_modified elsif @resizeUD then # p 'resizeUD' if @oy1 < sy then # p 'bottom' y1=@oy1 ; h=sy-@oy1 if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_h = #{h}") unless @focused.mgBottom end else # p 'top' y1=sy ; h=@oy1-sy if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_y = @__org_y + @__org_h - #{h}; @__org_h = #{h}") unless @focused.mgTop end end @focused.move(@focused.x,y1-oy,@focused.w,h) unless @focused.respond_to?(:initMargin) moveC(@focused) setFocusRgn(@focused) @focusExists = true @parent.inc_modified elsif @moving then if @focused.respond_to?(:_fd_dragging) && @focused._fd_dragging return end if @focused.respond_to? :initMargin then if !@focused.mgTop && !@focused.mgBottom && !@focused.mgLeft && !@focused.mgRight @focused.instance_eval("@__org_y =#{sy-@yu-oy};@__org_x=#{sx-@xl-ox}") elsif !@focused.mgLeft && !@focused.mgRight @focused.instance_eval("@__org_x=#{sx-@xl-ox}") elsif !@focused.mgTop && !@focused.mgBottom @focused.instance_eval("@__org_y =#{sy-@yu-oy}") else end moveC(@focused) else @focused.move sx-@xl-ox,sy-@yu-oy,@xr+@xl,@yu+@yd end if @prevfocuse && @prevfocuse.parent.is_a?(VRRebar) && sx==@px1 && sy==@py1 @focused = @prevfocuse @prevfocuse = nil end setFocusRgn(@focused) @focusExists = true @parent.inc_modified end if @focused && (@focused.visible? == false) then @focused.visible=true end setPenMode(R2_COPYPEN) self.refresh @moving=@resizeALL=@resizeLR=@resizeUD= false releaseCapture self.parent.tab.noselectAll self.focus refreshInspect(@focused) @creating = nil @containerCnt = self end def self_lbuttondown(x,y) sx=step(x);sy=step(y) c0 = checkfocus(x,y) c1 = c0 ? c0 : self @paste_to=c0 xf, yf = getFormPos(@focused) if @focused if @focused && (@focused.parent == c1) && ((xf-4 < x && x < xf + @focused.w+4) && (yf-4 < y && y < yf + @focused.h+4)) # reamin focus else setFocusRgn(@focused = c0) end if @creation if @focused && (@creation.klass <= SWin::Window) if @focused.respond_to?(:addControl) @containerCnt = @focused else @containerCnt = @focused.parent end elsif @focused && ((@creation.createMethod == :newFD2Pane) || (@creation.createMethod == :newFDLayout)) if (@focused.is_a?(VRPanel) && !@focused.is_a?(FDContainer)) @containerCnt = @focused else @containerCnt = @focused.parent end else @containerCnt = self end @ox1=sx; @oy1=sy @px1 = @ox1 ; @py1 = @oy1 setPenMode(R2_NOTXORPEN) setCapture elsif @focused @containerCnt=@focused.parent controlstate((x-@x1).abs < 4 && @y2+4 > y && y > @y1-4, (x-@x2).abs < 4 && @y2+4 > y && y > @y1-4, (y-@y1).abs < 4 && @x2+4 > x && x > @x1-4, (y-@y2).abs < 4 && @x2+4 > x && x > @x1-4 ) @px1 = @ox1 ; @py1 = @oy1 if @moving if @focused.parent.is_a?(VRTabbedPanel)||(@focused.parent.is_a? VRRebar) @prevfocuse = @focused @focused = @focused.parent setFocusRgn(@focused) @containerCnt=@focused.parent @ox1=@x1;@oy1=@y1;@ox2=@x2;@oy2=@y2 end @px1 = sx ; @py1 = sy @xl=@px1-@x1;@yu=@py1-@y1 @xr=@x2-@px1;@yd=@y2-@py1 @focusExists = true end setPenMode(R2_NOTXORPEN) setCapture else @focused = nil @focusExists = false @containerCnt = self end refresh @dragging = true end def self_rbuttondown(shift,x,y) sx=step(x < 0xefff ? x : x-0x10000) sy=step(y < 0xefff ? y : y-0x10000) if @focused = checkfocus(x,y) then @paste_to=@focused @focused = @focused.parent if @focused.parent.class==VRTabbedPanel setFocusRgn(@focused) @focusExists = true else @paste_to=nil @focusExists = false end set_selected_point(sx,sy) refreshInspect(@focused) refresh @parent.popupMenu @parent.amenu.menu,self.x+x,self.y+y end def self_mousemove(shift,x,y) SWin::Application.doevents sx=step(x < 0xefff ? x : x-0x10000) sy=step(y < 0xefff ? y : y-0x10000) if @creation then @cur=@curs.Cross @app.setCursor @cur if (shift&1) == 1 && @dragging then #shift1: left button down # erase previous lines rect(@ox1,@oy1,@px1,@py1) # draw new lines rect(@ox1,@oy1,sx,sy) @px1 = sx ; @py1 = sy end elsif @moving then return if @focused.respond_to?(:_fd_dragging) && @focused._fd_dragging if (shift&1) == 1 && @dragging then #shift1: left button down rect(@px1-@xl,@py1-@yu,@px1+@xr,@py1+@yd) rect(sx-@xl,sy-@yu,sx+@xr,sy+@yd) @px1 = sx ; @py1 = sy end elsif @resizeALL then if (shift&1) == 1 && @dragging then #shift1: left button down rect(@ox1,@oy1,@px1,@py1) rect(@ox1,@oy1,sx,sy) @px1 = sx ; @py1 = sy end elsif @resizeLR then if (shift&1) == 1 && @dragging then #shift1: left button down rect(@ox1,@oy1,@px1,@y2) rect(@ox1,@oy1,sx,@y2) @px1 = sx ; @py1 = sy end elsif @resizeUD then if (shift&1) == 1 && @dragging then #shift1: left button down rect(@ox1,@oy1,@x2,@py1) rect(@ox1,@oy1,@x2,sy) @px1 = sx ; @py1 = sy end elsif @focusExists if @x1 && @x2 && @y1 && @y2 then @app.setCursor( resizecursor( (x-@x1).abs < 4 && @y2+4 > y && y > @y1-4, (x-@x2).abs < 4 && @y2+4 > y && y > @y1-4, (y-@y1).abs < 4 && @x2+4 > x && x > @x1-4, (y-@y2).abs < 4 && @x2+4 > x && x > @x1-4 )) end else @app.setCursor @curs.Arrow end end def getFontName(c) if c.respond_to? :addControl hf = c._default_font ? c._default_font.hfont : 0 f = @_hsh_font[hf] else hf=c.sendMessage(WMsg::WM_GETFONT,0,0) hf=hf+0x100000000 if hf < 0 f = @_hsh_font[hf] f = nil if c.parent._default_font && c.parent._default_font == f end if f f.fontname + ',' +f.params[1].abs.to_s else r = "default" end end def refreshInspect(c) return if c.class == FDCoverPanel c = self unless c r = nil el = [] c.modules.each{|i| if j = FDModules::StdModules["#{i}".intern] el = el + j.events elsif j = FDModules::FormModules["#{i}".intern] el = el + j.events end } unless c.modules.empty? el << 'ownerdraw(iid,action,state,hwnd,hdc,left,top,right,bottom,data)' if c != self && c.owndraw && (c.owndraw > 0) if c != self then r = findPalletItem(c) attrs = [] r.attrs.each{|i| next if i.is_a?(Array)&&c.parent.is_a?(VRTabbedPanel)&& (i[0]=="style" || i[0]=="font") attrs << if i.is_a?(Array) then [i[0],i[1].call(c),i[2]] elsif c.is_a? FDContainer case i when 'name','caption','x','y' [i,c.instance_eval(i).to_s] else [i,c.substance.instance_eval(i).to_s] end else [i,c.instance_eval(i).to_s] end } if c.respond_to?(:margined) && c.margined then attrs = attrs + [ ["mgLeft","#{c.mgLeft}","numnil"], ["mgTop","#{c.mgTop}","numnil"], ["mgRight","#{c.mgRight}","numnil"], ["mgBottom","#{c.mgBottom}","numnil"]] elsif c.is_a?(FDContainer) && c.substance.respond_to?(:initMargin) attrs = attrs + [ ["mgLeft","#{c.substance.mgLeft}","num"], ["mgTop","#{c.substance.mgTop}","num"], ["mgRight","#{c.substance.mgRight}","num"], ["mgBottom","#{c.substance.mgBottom}","num"]] end if r then if r.events @parent.inspectfrm.skip_ctrl_name = false el = r.events + el @parent.inspectfrm.evtList.setListStrings(el) else #e.g. menu,toolbar @parent.inspectfrm.skip_ctrl_name = true @parent.inspectfrm.evtList.setListStrings(c.eventList) end end @parent.inspectfrm.mthdList.setListStrings(r.mthds) if r elsif self.type_of_form <= VRDialogComponent c = self a = c.windowrect attrs = [["name",c.name],["caption",c.caption],["x",a[0].to_s], ["y",a[1].to_s],["w",a[2].to_s],["h",a[3].to_s], ["FONT",eval(@prFont).call(c),:_btFont], ["style",'',:nil], ["modules",eval(@prModule).call(c),:_btModule]] @parent.inspectfrm.evtList.setListStrings(el) if !@parent.forms[0] || @parent.forms[0]==self @parent.inspectfrm.mthdList.setListStrings([ "modelessform","setButtonAs(button,dlgbuttonid)","centering"]) elsif self.type_of_form==VRModalDialog @parent.inspectfrm.mthdList.setListStrings([ "openModalDialog","setButtonAs(button,dlgbuttonid)","centering"]) else @parent.inspectfrm.mthdList.setListStrings([ "openModelessDialog","setButtonAs(button,dlgbuttonid)","centering"]) end else c = self a = c.windowrect attrs = [["name",c.name],["caption",c.caption],["x",a[0].to_s], ["y",a[1].to_s],["w",a[2].to_s],["h",a[3].to_s], ['sizebox',@frm_sizebox.to_s,:_cbTF], ['maximizebox',@frm_maximizebox.to_s,:_cbTF], ["FONT",eval(@prFont).call(c),:_btFont], ["style",'',:nil], ["modules",eval(@prModule).call(c),:_btModule]] @parent.inspectfrm.evtList.setListStrings(el) if !@parent.forms[0] || @parent.forms[0]==self @parent.inspectfrm.mthdList.setListStrings(["start"]) else @parent.inspectfrm.mthdList.setListStrings(["showForm"]) end end if c == self then s = "#{c.name}:#{c.type_of_form}" parent.form_edit_menu else s = "#{c.name}:#{c.class}" if c.is_a?(FDContainer) &&(c.substance.is_a?(VRTwoPaneFrame)|| c.substance.is_a?(VRLayoutFrame)||c.substance.is_a?(VRMenu)) parent.inhibit_paste_menu else parent.enable_paste_menu end end i= @parent.inspectfrm.cbControl.findString(s) @parent.inspectfrm.cbControl.select(i) @parent.inspectfrm.setItems(attrs) @parent.inspectfrm.stb2.caption = "" end def setControlsList(c) c.each do |id,item| next if item.is_a? FDCoverPanel if item.respond_to?(:controls) then setControlsList(item.controls) end unless item.parent.is_a?(VRTabbedPanel) && item.is_a?(VRPanel) s="#{item.name}:#{item.class}" @parent.inspectfrm.cbControl.addString(s) end end end def refreshCntName @parent.inspectfrm.cbControl.clearStrings s="#{self.name}:#{self.type_of_form}" @parent.inspectfrm.cbControl.addString(s) setControlsList(@controls) # @parent.inspectfrm.cbControl.select( # @parent.inspectfrm.cbControl.findString(s)) end def moveC(c) if c.kind_of?(SWin::Window) then x,y,w,h=c.windowrect x = c.x y = c.y if c.respond_to? :initMargin then x = x - (c.mgLeft ? c.mgLeft : 0) y = y - (c.mgTop ? c.mgTop : 0) w = w + (c.mgLeft ? c.mgLeft : 0) + (c.mgRight ? c.mgRight : 0) h = h + (c.mgTop ? c.mgTop : 0) + (c.mgBottom ? c.mgBottom : 0) end c.move(x, y, w, h) end end def check_container(c,n = 1) c.name + "+" + n.to_s c.parent.parent.instance_eval("@#{c.name}") c.parent.parent.controls if c.parent.parent.kind_of? VRGroupbox if c.parent.parent then if c.parent.parent.instance_eval("@#{c.name}") then r = true ; return(true) else r = check_container(c.parent,n+1) end end r end def update_target(name,caption,x,y,w,h,*arg) if @focused then unless @focused.name == name then oldname=@focused.name.dup @focused.name=name @focused.parent.instance_eval("@#{name} = @#{oldname}") @focused.parent.instance_eval("@#{oldname} = nil") @names.delete(oldname) @names << name @focused.parent.update_items(oldname,name) if @focused.parent.respond_to? :update_items if @focused.respond_to?(:addControl) then @buff.gsub!(/\_#{oldname}/,"_#{name}") if @buff end end if @focused.respond_to?(:initMargin) lf=@focused.mgLeft; tp=@focused.mgTop; ri=@focused.mgRight; bt=@focused.mgBottom end arg.each do |i| v = ((v = eval(i[1])) == "") ? nil : v if @focused.is_a? FDContainer unless @focused.substance.instance_eval("#{i[0]}")==v then @focused.substance.instance_eval("#{i[0]} = #{i[1]}") break end else unless @focused.instance_eval("#{i[0]}")==v then @focused.instance_eval("#{i[0]} = #{i[1]}") break end end end pr = @focused ? @focused.parent : self @focused.caption=caption @focused.move(x,y,w,h) if @focused.respond_to?(:initMargin) @focused.instance_eval("@__org_x = @__org_x + @__org_w - #{w}; @__org_w = #{w}") unless lf || @focused.mgLeft @focused.instance_eval("@__org_y = @__org_y + @__org_h - #{h}; @__org_h = #{h}") unless tp || @focused.mgTop @focused.instance_eval("@__org_w = #{w}") unless ri || @focused.mgRight @focused.instance_eval("@__org_h = #{h}") unless bt || @focused.mgBottom if !@focused.mgTop && !tp && !@focused.mgBottom && !bt || !@focused.mgLeft && !lf && !@focused.mgRight && !ri @focused.instance_eval("@__org_y=#{y};@__org_x=#{x}") elsif !@focused.mgLeft && !lf && !@focused.mgRight && !ri @focused.instance_eval("@__org_x=#{x}") elsif !@focused.mgTop && !tp && !@focused.mgBottom && !bt @focused.instance_eval("@__org_y =#{y}") end end pr.sendMessage(WMsg::WM_SIZE,0,MAKELPARAM(pr.w,pr.h)) setFocusRgn(@focused) else #if form oldname=self.name @buff.gsub!(/\_#{oldname}/,"_#{name}") if @buff self.name=name self.caption=caption move(x,y,w,h) @parent.update_menu(self) end @parent.inc_modified refreshCntName refreshInspect(@focused) end def save_window(cnt) x0,y0,w0,h0 = cnt.windowrect it = nil if cnt.items if cnt.is_a?(VRRebar) && cnt.items.size==1 && cnt.items[0][0]=="@__#{cnt.name}" cnt.instance_eval("deleteControl @__#{cnt.name}") it = nil else it = cnt.items.dup end end hf0 = cnt.sendMessage(WMsg::WM_GETFONT,0,0) hf0 = hf0 + 0x100000000 if hf0 < 0 hf = !(_hsh_font[hf0])||(cnt.parent._prev_dflt_hfont == hf0) ? 0 : hf0 r = { :type => cnt.class, :name => cnt.name, :oldname => cnt.oldname, :caption => cnt.caption, :style => cnt.style, :x => cnt.x, :y => cnt.y, :w => w0, :h => h0, :id => cnt.etc, :form => cnt.form, :hfont => hf, :items => it, :mods => cnt.modules && cnt.modules.dup, :owndraw => cnt.owndraw, :registerd_to => (cnt.registerd_to.empty? ? [] : [cnt.registerd_to[0].name, cnt.registerd_to[1]]), :controls => [] } r[:substance] = cnt.substance if cnt.is_a? FDContainer unless cnt.registerd_to.empty? unless cnt.is_a? FDContainer r[:x] = cnt.__org_x r[:y] = cnt.__org_y r[:w] = cnt.__org_w r[:h] = cnt.__org_h r[:left] = cnt.mgLeft r[:top] = cnt.mgTop r[:right] = cnt.mgRight r[:bottom] = cnt.mgBottom end if (r0=cnt.registerd_to[0].substance).is_a? VRTwoPaneFrame if cnt.registerd_to[1] == 0 if cnt.is_a? FDContainer r[:regist_index] = r0.pane1.index(cnt.substance) else r[:regist_index] = r0.pane1.index(cnt) end else if cnt.is_a? FDContainer r[:regist_index] = r0.pane2.index(cnt.substance) else r[:regist_index] = r0.pane2.index(cnt) end end elsif r0.is_a? VRGridLayoutFrame if cnt.is_a? FDContainer r[:regist_index] = r0._vr_layoutclients.each_with_index{|c,i| break i if c[0] == cnt.substance} else r[:regist_index] = r0._vr_layoutclients.each_with_index{|c,i| break i if c[0] == cnt} end else if cnt.is_a? FDContainer r[:regist_index] = r0._vr_layoutclients.index(cnt.substance) else r[:regist_index] = r0._vr_layoutclients.index(cnt) end end end if cnt.respond_to?(:addControl) then r[:_default_font] = cnt._default_font controls=cnt.controls.dup save_layouts = lambda do |frame| r[:controls] << save_window(controls.delete(frame.container.etc)) if frame.is_a? VRTwoPaneFrame frame.pane1.each{|i| if i.is_a? SWin::Window r[:controls] << save_window(controls.delete(i.etc)) else save_layouts.call(i) if i end }if frame.pane1 frame.pane2.each{|i| if i.is_a? SWin::Window r[:controls] << save_window(controls.delete(i.etc)) else save_layouts.call(i) if i end } if frame.pane2 elsif frame.is_a? VRGridLayoutFrame frame._vr_layoutclients.each{|i| if i[0].is_a? SWin::Window r[:controls] << save_window(controls.delete(i[0].etc)) else save_layouts.call(i[0]) if i[0] end } else frame._vr_layoutclients.each{|i| if i.is_a? SWin::Window r[:controls] << save_window(controls.delete(i.etc)) else save_layouts.call(i) if i end } end end if cnt.__regsterd_vr_margined_frame r[:registerd_frame] = cnt.__regsterd_vr_margined_frame save_layouts.call(cnt.__regsterd_vr_margined_frame) end controls.each{|i,c| r[:controls] << save_window(c) unless c.is_a? FDCoverPanel } unless controls.empty? end r end def saveandclosewindow(cnt) return unless cnt r = save_window(cnt) cnt.terminate if cnt.respond_to?(:terminate) cnt.parent.deleteControl(cnt) cnt.parent.child_deleted(cnt) if cnt.parent.respond_to? :child_deleted r end def recreate1(c_parent, a, offset=[0,0], paste_mode=nil, addstyle=nil) if a[:type] <= FDContainer item = findPalletItem(a[:substance].class) else item = findPalletItem(a[:type]) end if paste_mode then newname = get_serial_name(a[:name]) else newname=a[:name] end addstyle = a[:style]|a[:owndraw] unless addstyle x0=a[:x]+offset[0] y0=a[:y]+offset[1] c=c_parent.instance_eval("#{item.createMethod} c_parent,#{item.klass},"+ "'#{newname}','#{a[:caption]}',#{x0},#{y0},#{a[:w]},#{a[:h]},"+ "#{addstyle},a[:items]") c_parent.child_created(c) if c_parent.respond_to? :child_created c.sendMessage(WMsg::WM_SETFONT,a[:hfont],0) unless a[:hfont] == 0 c.modules = a[:mods] c.form = a[:form] if newname == a[:name] c.oldname = a[:oldname] else c.oldname = a[:name] end c.registerd_to = a[:registerd_to].empty? ? [] : [c.parent.controls.find{|k,i|i.oldname == a[:registerd_to][0]}[1], a[:registerd_to][1]] unless a[:registerd_to].empty? if (r0=c.registerd_to[0].substance).is_a? VRTwoPaneFrame if c.registerd_to[1] == 0 if c.is_a? FDContainer r0.pane1[a[:regist_index],0]=c.substance else r0.pane1[a[:regist_index],0]=c end else if c.is_a? FDContainer r0.pane2[a[:regist_index],0]=c.substance else r0.pane2[a[:regist_index],0]=c end end elsif r0.is_a? VRGridLayoutFrame if c.is_a? FDContainer r0._vr_layoutclients[a[:regist_index],0]=c.substance else r0._vr_layoutclients[a[:regist_index],0]=[[c,c.x,c.y,c.w,c.h]] end else if c.is_a? FDContainer r0._vr_layoutclients[a[:regist_index],0]=c.substance else r0._vr_layoutclients[a[:regist_index],0]=c end end unless c.is_a? FDContainer c.extend(VRMargin).initMargin(a[:left],a[:top],a[:right],a[:bottom]) c.margined = true end end if c.is_a?(FDContainer) && (cs=c.substance).is_a?(VRTwoPaneFrame) as = a[:substance] cs.ratio = as.ratio cs.position = as.position cs.gap = as.gap cs.bevel = as.bevel cs.lLimit = as.lLimit cs.setMargin(as.mgLeft,as.mgTop,as.mgRight,as.mgBottom) if cs.is_a?(VRHorizTwoPaneFrame) cs.rLimit = as.rLimit else cs.uLimit = as.uLimit end elsif cs && cs.is_a?(VRGridLayoutFrame) as = a[:substance] cs.instance_eval("@_vr_xsize = #{as.instance_eval("@_vr_xsize")}") cs.instance_eval("@_vr_ysize = #{as.instance_eval("@_vr_ysize")}") cs.setMargin(as.mgLeft,as.mgTop,as.mgRight,as.mgBottom) elsif cs && cs.is_a?(VRLayoutFrame) as = a[:substance] cs.setMargin(as.mgLeft,as.mgTop,as.mgRight,as.mgBottom) elsif cs as = a[:substance] if paste_mode cs=as.dup else cs=as end elsif c.is_a? VRTabbedPanel c._default_font = a[:_default_font] c.panels.each_index{|i| # c.panels[i].extend(FDCommonMethod) # c.panels[i].extend(FDParent).fd_parent_init # c.panels[i].extend CreateCtrl c.panels[i]._default_font = c._default_font a[:controls].find{|j| j[:name] == "panel#{i}"}[:controls].each{|j| recreate1(c.panels[i],j,[0,0],paste_mode)} } elsif c.is_a? VRRebar c.items.each{|i| recreate1(c,a[:controls].select{|j| j[:name]==i[0].sub(/^@/,'')}[0],[0,0],paste_mode)} if a[:items] elsif c.respond_to?(:addControl) then c._default_font = a[:_default_font] c.extend(FDCommonMethod) c.extend(FDParent).fd_parent_init c.extend CreateCtrl a[:controls].each{|i|recreate1(c,i,[0,0],paste_mode)} if paste_mode then c.controls.each{|k,i| i.oldname = i.name} c.oldname = c.name end c.sendMessage(WMsg::WM_SIZE,0,MAKELPARAM(c.w,c.h)) end c end def recreateControl(cnt,parent = nil, style = nil) parent = cnt.parent unless parent idx = @tabOrders.index(cnt.etc) @tabOrders.delete_at(idx) if idx a = saveandclosewindow(cnt) @focused = recreate1(parent, a,[0,0], nil, style) @tabOrders[idx, 0] = @focused.etc if idx @focused.parent.sendMessage(WMsg::WM_SIZE,0, MAKELPARAM(@focused.parent.w,@focused.parent.h)) refreshInspect(@focused) end def deleteCont if @focused then if @focused.respond_to? :addControl then @focused.delete_child_controls end par = @focused.parent par.tabOrders.delete(@focused.etc) @focused.terminate if @focused.respond_to? :terminate @focused.parent.deleteControl(@focused) par.child_deleted(@focused) if par.respond_to? :child_deleted delete_serial_name(@focused.name) @focused = nil @focusExists = false refresh refreshCntName refreshInspect(nil) @parent.inc_modified end end def cutCont @copy_buff=[] @cut_mode=true @copy_buff << saveandclosewindow(@focused) @focused = nil @focusExists = nil refreshInspect(nil) refresh end def copyCont if @focused then @copy_buff=[] @copy_buff << save_window(@focused) end end def pasteCont unless @copy_buff.empty? then a=[] _ox=0; _oy=0 _ox,_oy=getFormPos(@paste_to) if @paste_to @copy_buff[0][:x]=0;@copy_buff[0][:y]=0 offset=[@selected_point.x-_ox,@selected_point.y-_oy] if @paste_to && @paste_to.respond_to?(:addControl) then @copy_buff.each{|c| a << recreate1(@paste_to,c,offset,!@cut_mode)} elsif @paste_to then @copy_buff.each{|c| a << recreate1(@paste_to.parent,c,offset,!@cut_mode)} else @copy_buff.each_with_index{|c,i| a << recreate1(self,c,offset,!@cut_mode)} end @cut_mode=nil @focused=a[0] refreshCntName refreshInspect(@focused) setFocusRgn(@focused) @focusExists=true refresh end end def backToParent return unless @focused if @focused.parent.parent.is_a? VRTabbedPanel @focused=@focused.parent.parent elsif @focused.parent != self @focused=@focused.parent else @focused = nil @focusExists=nil end c=@focused ? @focused : self setFocusRgn(@focused) refreshCntName refreshInspect(@focused) c.controls.each{|k,i| if i.is_a? FDContainer i.focus SetWindowPos.call(i.hWnd,1,0,0,24,24,3) end } c.refresh end def setWinStyle if @focused StyleDlg.args = [ @focused.class, setWSArray(@focused.style,FDWStyle::CtlStyles), setWSOption(@focused.style,FDWStyle::CtlStyles), (FDWStyle::CtlStyles[@focused.class] ? FDWStyle::CtlStyles[@focused.class][:toggle] : nil) ] @parent.dialog_running = 'Window Style' r = @screen.openModalDialog self, nil, StyleDlg @parent.dialog_running = nil if r then ropt = r.shift rint = wsArray2int(r, FDWStyle::CtlStyles) st = ropt >= 0 ? rint | ropt : rint @focused.style = st # p [1235,@focused.style.to_x] recreateControl(@focused, nil, st) # p [1237,st.to_x,@focused.style.to_x] @parent.inc_modified end end end def _add_style(s2,style,hash) a=[] s2.each{|i| i1 = i.dup s = style & hash[@focused.class][:style][i1] a << [i1.to_s , (hash[@focused.class][:style][i1] != s ? 0 : 1)] } a end def setWSOption(style,hash) r = [0] ; a = [] ; n = 0 if hash[@focused.class] && hash[@focused.class][:option] != {} a1 = hash[@focused.class][:option].dup.to_a.sort a1.each{|i| s = [i[0].dup,i[1]] ns = (s0=style & 0x3f) < 4 ? s0 : s0 & 0x3e r[0] = n if ns == s[1] a << s n += 1 } r += a end r end def setWSArray(style,hash) a=[] if hash[@focused.class] then s2 = hash[@focused.class][:style].keys.dup a = a + _add_style(s2,style,hash) else s1 = FDWStyle::WStyles.keys.dup s1.each{|i| s = i.dup a << [s.to_s,((FDWStyle::WStyles[i] & style) == 0 ? 0 : 1)] } end a.sort end def wsArray2int(a,hash) r =0 a.each{|i| if w = FDWStyle::WStyles[i[0]] then r |= w * i[1] else c = hash[@focused.class][:style][i[0]] r |= c * i[1] end } r |= @focused.owndraw unless @focused.is_a? VRButton r end def setExStyle end def setModules if @focused then c=@focused else c=self end @moddlg.options["default"] = getModArray(c) @moddlg.move 0,0,104,195 @parent.dialog_running = 'Modules' r = @moddlg.open(self) @parent.dialog_running = nil if r then c.modules.clear r.each{|i| c.set_modules(eval(i[0])) if i[1] == 1 } @parent.inc_modified end refreshInspect(c) end def getModArray(c) r = [] if c == self then FDModules::StdModules.each{|key,val| n = c.modules.include?(eval(key.to_s)) ? 1 : 0 r << [key.to_s,n] } FDModules::FormModules.each{|key,val| n = c.modules.include?(eval(key.to_s)) ? 1 : 0 r << [key.to_s,n] } else a = findPalletItem(c) a.mods.each{|key,val| n = c.modules.include?(eval(key.to_s)) ? 1 : 0 r << [key.to_s,n] } if a end r end def showModDlg(a,w,h) @moddlg.options["default"]= a @moddlg.move 0,0,w,h @parent.dialog_running = 'Modules' r=@moddlg.open(self) @parent.dialog_running = nil if r then @parent.inc_modified end r end def ctrl_Tab_orders x0,y0,w0,h0=parent.windowrect TabOrderDlg.args={:x=>x0,:y=>y0,:c=>@focused.parent,:frm=>self} @parent.dialog_running = 'Tab order' @screen.modalform(self,0x02,TabOrderDlg) @parent.dialog_running = nil refreshInspect(@focused) @parent.inc_modified end def changeFocuse(s) c = findCtrl(s) if c then @focused = c setFocusRgn(c) @focusExists=true else @focused = nil @focusExists=false end refreshInspect(c) refresh end def ctrl_setFont(to_default = nil) def check_default(c,d) hf=c.sendMessage(WMsg::WM_GETFONT,0,0) hf=hf+0x100000000 if hf < 0 c.is_a?(FDContainer) || !@_hsh_font[hf] || (d && hf == d.hfont) end if @focused then c = @focused else c = self end if c.respond_to? :addControl hf = c._default_font ? c._default_font.hfont : 0 else hf=c.sendMessage(WMsg::WM_GETFONT,0,0) hf=hf+0x100000000 if hf < 0 end if to_default return unless @_hsh_font[hf] newfont = c.parent._default_font if c.parent.respond_to? :_default_font dflt = nil else af = @_hsh_font[hf] ? [@_hsh_font[hf].params,0,0] : [["System",19,0,300,135,0,0,2,128],135,0] af[0][1]=(af[0][1]).abs.to_i if af @parent.dialog_running = 'Choose font' f = SWin::CommonDialog.chooseFont self, af @parent.dialog_running = nil if f then newfont=@_hsh_font[setFontHash(f)] dflt = newfont @parent.inc_modified else return end end c.setFont(newfont) unless c == self if c.respond_to? :addControl if c.is_a? VRTabbedPanel c.sendMessage(WMsg::WM_SIZE,0,MAKELPARAM(c.w,c.h)) c.panels.each do |i| i.controls.each{|k,j| j.setFont(dflt) if check_default(i,c._default_font)} i._default_font=dflt end else c.controls.each do |id,j| j.setFont(dflt) if check_default(j,c._default_font) end end c._default_font=dflt else x0,y0,w0,h0=c.windowrect @focused.move(c.x,c.y,w0,h0) setFocusRgn(@focused) end refreshInspect(@focused) end def setValue(klass,val) klass = val end def setFontHash(f) unless r=@_hsh_font.select{|k,v| f[0][0]==v.params[0] && f[0][1]==v.params[1] && f[0][2]==v.params[2] && f[0][3]==v.params[3] && f[0][4]==v.params[4] && f[0][5]==v.params[5] && f[0][6]==v.params[6] && f[0][7]==v.params[7] && f[0][8]==v.params[8] }[0] then f[0][3] = f[0][3]/100.to_i #weight ffont=@screen.factory.newfont *f[0] @_hsh_font[ffont.hfont]=ffont ffont.handle else r[0] end end def getFontHash(font_handle) @_hsh_font[font_handle] end def get_font_number(font_handle) return nil unless @_hsh_font[font_handle] unless (n=@_font_array.index(font_handle)) then @_font_array << font_handle @_font_array.size-1 else n end end =begin def showArrayEditDlg(a,w,h) @arrydlg.move 0,0,w,h #204,200 @arrydlg.options["default"] = a.gsub(/\n/,"\r\n").gsub(/\t/,'\t') if r=@arrydlg.open(self) then r.gsub(/\\t/,"\t").gsub(/\r\n/,"\n").to_s end end =end def setTrueFalse(str,svalue) if @focused then @focused.instance_eval("#{str}(#{svalue})") else #this form self.instance_eval "@frm_#{str}=svalue" end end def registerLayout x0,y0,w0,h0=parent.windowrect LayoutDlg.args={:x=>x0,:y=>y0,:c=>@focused ? @focused.parent : self, :frm=>self,:focused=>@focused} @parent.dialog_running = 'Register' r = @screen.openModalDialog(self,0x02,LayoutDlg) @parent.dialog_running = nil if r then if (s=@focused.substance).is_a? VRTwoPaneFrame r[0].each_with_index do |v,i| unless f = s.pane1.find{|j| if j.is_a? SWin::Window then j == v else j.container == v end } f = v unless f.is_a? FDContainer f.extend(VRMargin).initMargin(0,0,0,0) f.margined = true end end unless f.is_a? SWin::Window then f.container.registerd_to = [@focused,0] else f.registerd_to = [@focused,0] end f = f.substance if f.is_a? FDContainer s.pane1.delete(f) s.pane1[i,0] = f end (s.pane1.size-1).downto(r[0].size){|j| c = s.pane1.delete_at(j) if c.is_a? SWin::Window c.registerd_to.clear c.setMargin(nil,nil,nil,nil) c.margined = nil else c.container.registerd_to.clear end } if r[0].size < s.pane1.size r[1].each_with_index do |v,i| unless f = s.pane2.find{|j| if j.is_a? SWin::Window then j == v else j.container == v end } f = v unless f.is_a? FDContainer f.extend(VRMargin).initMargin(0,0,0,0) f.margined = true end end unless f.is_a? SWin::Window then f.container.registerd_to = [@focused,1] else f.registerd_to = [@focused,1] end f = f.substance if f.is_a? FDContainer s.pane2.delete(f) s.pane2[i,0] = f end (s.pane2.size-1).downto(r[1].size){|j| c = s.pane2.delete_at(j) if c.is_a? SWin::Window c.registerd_to.clear c.setMargin(nil,nil,nil,nil) c.margined = nil else c.container.registerd_to.clear end } if (r[1].size < s.pane2.size) elsif s.is_a? VRGridLayoutFrame r.each_with_index do |v,i| unless f = s._vr_layoutclients.find{|j| if j[0].is_a? SWin::Window then j[0] == v else j[0].container == v end } if v.is_a? FDContainer f = [v.substance,0,0,v.parent.w,v.parent.h] else f = [v,v.x,v.y,v.w,v.h] end if f[0].is_a? SWin::Window f[0].extend(VRMargin).initMargin(0,0,0,0) f[0].margined = true end end unless f[0].is_a? SWin::Window then f[0].container.registerd_to = [@focused,0] else f[0].registerd_to = [@focused,0] end f[0] = f[0].substance if f[0].is_a? FDContainer s._vr_layoutclients.delete(f) s._vr_layoutclients[i,0] = [f] end (s._vr_layoutclients.size-1).downto(r.size){|j| c = s._vr_layoutclients.delete_at(j) if c[0].is_a? SWin::Window c[0].registerd_to.clear c[0].setMargin(nil,nil,nil,nil) c[0].margined = nil else c[0].container.registerd_to.clear end } if r.size < s._vr_layoutclients.size else r.each_with_index do |v,i| unless f = s._vr_layoutclients.find{|j| if j.is_a? SWin::Window then j == v else j.container == v end } f = v unless f.is_a? FDContainer f.extend(VRMargin).initMargin(0,0,0,0) f.margined = true end end unless f.is_a? SWin::Window then f.container.registerd_to = [@focused,0] else f.registerd_to = [@focused,0] end f = f.substance if f.is_a? FDContainer s._vr_layoutclients.delete(f) s._vr_layoutclients[i,0] = f end (s._vr_layoutclients.size-1).downto(r.size){|j| c = s._vr_layoutclients.delete_at(j) if c.is_a? SWin::Window c.registerd_to.clear c.setMargin(nil,nil,nil,nil) c.margined = nil else c.container.registerd_to.clear end } if r.size < s._vr_layoutclients.size end @focused.parent.sendMessage(WMsg::WM_SIZE,0, MAKELPARAM(@focused.parent.w,@focused.parent.h)) end setFocusRgn(@focused) refreshInspect(@focused) refresh end def make_fonts_str(a) return nil if a.empty? r = "[\n" a.each{|i| f=@_hsh_font[i].params.to_a f[0]="\'#{f[0]}\'" f[3]=f[3]/100 r+=" VRLocalScreen.factory.newfont(#{f.join(',')}),\n"} r[r.size-2,1]="" r+=" ]\n" r end def get_require @modules.each{|m| if rq = FDModules::FormModules["#{m}".intern ] then (@required << rq.requires).uniq! elsif rq = FDModules::StdModules["#{m}".intern ] then (@required << rq.requires).uniq! end } @required.reject!{|i| !i} @required end def ex_include r = "" @included.uniq! @modules.uniq! @included.each{|s| r += " include #{s} if defined? #{s}\n" if s} unless @included.empty? @modules.each{|s| r += " include #{s}\n" if s} unless @modules.empty? r end def examine a=[] @cntnmodules=[] rf = [] rc = [] ctls = @controls.dup x0,y0,w0,h0=self.windowrect str = "\n def construct\n" n = str.size str += " self.sizebox=#{@frm_sizebox}\n" if @frm_sizebox == 'false' str += " self.maximizebox=#{@frm_maximizebox}\n" if @frm_maximizebox == 'false' str += " self.caption = '#{self.caption}'\n" str += " self.move(#{x0},#{y0},#{w0},#{h0})\n" analize_frame = lambda do |frame| if frame.is_a? VRTwoPaneFrame frame.pane1.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << c.createSourceStr end end frame.pane2.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << c.createSourceStr end end elsif frame.is_a? VRGridLayoutFrame frame._vr_layoutclients.each do |i| unless i[0].is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i[0].container.etc) rf << c.createSourceStr end end else frame._vr_layoutclients.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << c.createSourceStr end end end end if @__regsterd_vr_margined_frame analize_frame.call(@__regsterd_vr_margined_frame) c = ctls.delete(@__regsterd_vr_margined_frame.container.etc) rf << c.createSourceStr end ctls.each do |k,i| if i.is_a? FDContainer c = ctls.delete(i.etc) if i.substance.is_a? VRMenu str += c.createSourceStr else rc << c.createSourceStr end end end @tabOrders.each do |id| item = ctls.delete(id) item.style = item.style | WStyle::WS_TABSTOP (@required << 'vrowndraw').uniq! if item.respond_to?(:owndraw) && item.owndraw > 0 target=item str += target.createSourceStr item.style = item.style-WStyle::WS_TABSTOP end ctls.each do |id,item| (@required << 'vrowndraw').uniq! if item.respond_to?(:owndraw) && item.owndraw > 0 str += item.createSourceStr if item.respond_to? :createSourceStr end str += rf.to_s str += rc.to_s str += " end \n\n" str end def linscan(a,ptn) n = 0 ; r = nil while a.size-1 >= n do if a[n] =~ ptn then r = n+1 ; break end n += 1 end r end def linscan2(a,ptn1,ptn2 = nil, n = 0) r = nil while a.size-1 >= n do if a[n] =~ ptn2 then break elsif a[n] =~ ptn1 then r = n+1 ; break end n += 1 end r end def make_executive @_font_array.clear s = examine s[0,0] = @cntnmodules.join("") if @cntnmodules s[0,0] = " include VRContainersSet\n" if @type_of_form<=VRDialogComponent s[0,0] = ex_include s[0,0] = getDEFAULTFONT(" ") if @_default_font s[0,0] =" #{self.name.capitalize1}_fonts="+ "#{make_fonts_str(@_font_array)}" unless @_font_array.empty? s[0,0] = "\nclass #{self.name.capitalize1} < #{@type_of_form}\n" s += "end\n" s end def check_rejectable_modules(j) j==VRToolbarUseable || j==VRStdControlContainer || j==VRComCtlContainer || j==VRMarginedFrameUseable || j==VRContainersSet || j==VROwnerDrawControlContainer end def readfile(str) # str = "" parser = FDParser.new(self,true) # if f then r = true # begin # open(f){|ff| # $tstamp=ff.stat.mtime.to_i # ff.each do |lin| # str+=lin # end # } @buff,@nodes,@variables = parser.parse str @modules = @nodes["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } set_controls(self,@nodes) set_variables(@variables) # refreshCntName # rescue # messageBox "\nIf you are not going to open the file of an old version\n" + # "or you edited manually,then please contact me.\n\n#{$!}", # "File Reading Error - #{f}",16 # r = false # end # end # refreshInspect(nil) r end def parse_str(s) parser = FDParser.new(self) @buff,@nodes,@variables = parser.parse s @modules = @nodes["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } set_controls2(self,@nodes) # set_variables(@variables) end def set_controls(c_parent,nodes) if c_parent.is_a? VRTabbedPanel c_parent.panels.each{|i| no=nodes["childs"].select{|j| j["name"] =~ /#{i.name}$/}[0] set_controls(i,no) } end r=nil nodes["addings"].each{ |i| mtd=findPalletItem(i[0]).createMethod ctrl=instance_eval("#{mtd}(c_parent,*i)") @names << ctrl.name unless (f1 = nodes["fonts"]) == {} then if f2 = f1["@"+i[1]] then if f2.is_a? Integer then ctrl.setFont(@_hsh_font[@temp_fonts[f2].hfont]) else #for old form file f = f2 # ffont=@screen.factory.newfont(f.fontface,f.height,f.style, # (f.weight / 100),f.width, f.escapement, f.orientation, # f.pitch_family,f.charset,f.point,f.color) ffont=setFontHash(f) ctrl.setFont(@_hsh_font[ffont]) ctrl._default_font = @_hsh_font[ffont] if ctrl.respond_to? :_default_font end end end if ctrl.respond_to?(:addControl) && ctrl.class != FDContainer then ctrl.extend FDCommonMethod ctrl.extend(FDParent).fd_parent_init ctrl.extend CreateCtrl # r = nodes["childs"].select{|n| n["name"]=="Cntn_#{ctrl.name}"}[0] r = nodes["childs"].select{|n| n["name"]=~/Cntn\w*_#{ctrl.name}$/}[0] ctrl.modules = r["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } if r set_controls(ctrl,r) else r = nodes["childs"].select{|n| n["name"]=~/Extn\w*_#{ctrl.name}/}[0] ctrl.modules = r["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } if r end ctrl.parent.child_created(ctrl) if ctrl.parent.respond_to? :child_created } end def set_controls2(c_parent,nodes) str2inst = lambda do |_ctls| if _ctls.is_a?(String) [c_parent.instance_eval(_ctls)] elsif _ctls.is_a?(Array) _ctls.map do |i| if i.is_a? Array str2inst.call(i) elsif i.is_a?(String) c_parent.instance_eval(i) else i end end else [_ctls] end end if c_parent.is_a? VRTabbedPanel c_parent.panels.each{|i| no=nodes["childs"].select{|j| j["name"] == i.name.capitalize1 }[0] set_controls2(i,no) } end c_parent.setFont(@temp_fonts[nodes["fonts"]["self"]]) if nodes["fonts"]["self"] c_parent._default_font=@temp_fonts[nodes.default_font] if nodes.default_font r=nil nodes["addings"].each{|i| mtd=findPalletItem(i[0]).createMethod i[7] = 0 unless i[7] if (i[7] & 0x10000) == 0x10000 i[7] &= ~0x10000 ctrl=instance_eval("#{mtd}(c_parent,*i)"); c_parent.tabOrders << ctrl.etc else ctrl=instance_eval("#{mtd}(c_parent,*i)"); end @names << ctrl.name if (f1 = nodes["fonts"]) != {} && (f2 = f1["@"+i[1]]) ctrl.setFont(@_hsh_font[@temp_fonts[f2].hfont]) if f2.is_a? Integer end if ctrl.respond_to?(:addControl) && ctrl.class != FDContainer then ctrl.extend FDCommonMethod ctrl.extend(FDParent).fd_parent_init ctrl.extend CreateCtrl r = nodes["childs"].select{|n| n["name"]=~/#{ctrl.name.capitalize1}$/}[0] ctrl.modules = r["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } if r ctrl.modules.uniq! set_controls2(ctrl,r) else r = nodes["childs"].select{|n| n["name"]==ctrl.name.capitalize1}[0] ctrl.modules = r["modules"].collect!{|i| eval(i)}.delete_if{|j| check_rejectable_modules(j) } if r ctrl.modules.uniq! end ctrl.parent.child_created(ctrl) if ctrl.parent.respond_to? :child_created } nodes.methods.each{|i| case i[1] when 'sizebox=','maximizebox=' instance_eval "@frm_#{i[1]}'#{i[2]}'" when /^ctn_([a-z][a-zA-Z0-9_]*)=/ instance_eval("@#{$1}").set_attrs(i[2]) else if (c=c_parent.instance_eval(i[0])).is_a? FDContainer if c.substance.is_a? VRMenu c.send(i[1],*str2inst.call(i[2])) else c.substance.send(i[1],*str2inst.call(i[2])) end else c.send(i[1],*str2inst.call(i[2])) end end } end def makeModStruct(cnt,parent=nil) ms=ModStruct.new(cnt.oldname.capitalize1,cnt.name.capitalize1,parent) cnt.controls.each{|k,i| next if i.is_a?(FDCoverPanel) if i.respond_to?(:addControl) ms.childs << makeModStruct(i,ms) elsif !i.modules.empty? || (i.owndraw > 0) ms.childs << ModStruct.new(i.name.capitalize1,i.oldname.capitalize1,ms) end } ms end def set_variables(variables) variables.each{|var,val| case var when 'sizebox','maximizebox' instance_eval "@frm_#{var}='#{val}'" when /^ctn_(\w+)/ instance_eval "@#{$1}.move #{val[0]},#{val[1]},24,24" instance_eval "@#{$1}.set_attrs val[2,val.size-2]" else end } end def self_dropfiles(files) parent.open_by_drop(files[0]) end def self_gotfocus parent.designfrm=self parent.window_menu_set_check(self.etc) refreshCntName refreshInspect(@focused) end def self_resize(x,y) x,y,w,h = self.clientrect DeleteObject.Call(@hrgn) @hrgn=CreateRectRgn.Call(x,y,w,h) SelectClipRgn.Call(@dc,@hrgn) a=windowrect $ini.write "designform","top",a[0] $ini.write "designform","left",a[1] $ini.write "designform","width",a[2] $ini.write "designform","height",a[3] refreshInspect(nil) end def self_move(x0,y0) refreshInspect(self) unless @focused parent.inc_modified end def self_close SKIP_DEFAULTHANDLER end end <file_sep># fdcfg.rb # Configuration File of FormDesigner for Visualu Ruby # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'fdvr/fdcontrols' require 'fdvr/fddialogs' class VRControl def setFont(font,redraw=true) if self.dopaint then super font end if font.is_a?(SWin::Font) then self.properties["font"]=font sendMessage WMsg::WM_SETFONT,font.hfont, ( (redraw)? 1 : 0 ) elsif !font sendMessage WMsg::WM_SETFONT,0,1 self.properties["font"]=nil else raise "#{font} is not a font." end end end class VRLayoutFrame def reset_registerd @_vr_layoutclients.each do|i| if i.is_a? SWin::Window i.setMargin(nil,nil,nil,nil) elsif i i.reset_registerd end i.registerd_to.clear end end end class VRTwoPaneFrame module VRTwoPaneFrameUsable def self_vrsepl2buttondown(s,x,y) @_vr_twopaneframes.each do |f| if f.hittest(x,y) f.setDragCur f.dragstart @_vr_current_tpframe=f @_fd_dragging=true end end end def self_vrsepl2buttonup(s,x,y) @_vr_current_tpframe=nil @_vr_twopaneframes.each do |f| f.dragend @_fd_dragging=false end refresh end end def reset_registerd if @pane1.is_a? Array @pane1.each do|i| if i.is_a? SWin::Window i.setMargin(nil,nil,nil,nil) i.registerd_to.clear else i.reset_registerd i.container.registerd_to.clear end end elsif @pane1 if @pane1.is_a? SWin::Window @pane1.setMargin(nilnilnilnil) @pane1.registerd_to.clear else @pane1.reset_registerd @pane1.container.registerd_to.clear end end if @pane2.is_a? Array @pane2.each do|i| if i.is_a? SWin::Window i.setMargin(nil,nil,nil,nil) i.registerd_to.clear else i.reset_registerd i.container.registerd_to.clear end end elsif @pane2 if @pane2.is_a? SWin::Window @pane2.setMargin(nilnilnilnil) @pane2.registerd_to.clear else @pane2.reset_registerd @pane2.container.registerd_to.clear end end end end module VRMarginedFrameUseable module VRMgdLayoutFrame def register(*ctls) @_vr_layoutclients.concat(ctls.flatten.map{|i| unless $subwnd i.registerd_to = [self.container,0] unless i.is_a?(FDContainer) i.margined = true i.extend(VRMargin).initMargin(0,0,0,0) i else i.substance end else i.extend(VRMargin).initMargin(0,0,0,0) unless i.is_a?(FDContainer) end }) _vr_relayout end end class VRMgdGridLayoutFrame def register(*ctls) if ctls[0].is_a? Array ctls.each do|i| unless $subwnd i[0].margined = true i[0].registerd_to = [self.container,0] end i[0].extend(VRMargin).initMargin(0,0,0,0) unless i[0].is_a?(FDContainer) super(*i) end else unless $subwnd ctls[0].margined = true ctls[0].registerd_to = [self.container,0] end ctls[0].extend(VRMargin).initMargin(0,0,0,0) unless ctls[0].is_a?(FDContainer) super end end end class VRMgdVertTwoPaneFrame alias :_vr_draw_bevel_org :_vr_draw_bevel def _vr_draw_bevel(win) _vr_draw_bevel_org(win) if $subwnd || !@container.registerd_to.empty? || (window_parent.__regsterd_vr_margined_frame == self) end end class VRMgdHorizTwoPaneFrame alias :_vr_draw_bevel_org :_vr_draw_bevel def _vr_draw_bevel(win) _vr_draw_bevel_org(win) if $subwnd || !@container.registerd_to.empty? || (window_parent.__regsterd_vr_margined_frame == self) end end end module ExecuteDesignfrm include VRDestroySensitive # include VRMouseFeasible def vrinit super $subwnd = self end def self_destroy $main.exitExec if $main.alive? $subwnd = nil end end class Array def format r = "[\n" self.each{|i| if i == self.last r += " " + i.inspect + "\n" else r += " " + i.inspect + ",\n" end } r += "]\n" end end class Integer def to_x sprintf "%#x" ,self end end class String def esc self.gsub /\"/,'\"' end end class MenuStrMaker def _analize(ar,mn=nil) @ar += " "*@n + "[\"#{mn}\",[\n" if mn ar.each{|i| if i[1].is_a? Array then @n += 1 _analize(i[1],i[0]) @ar[@<EMAIL>-1,0]=',' else @ar += " "*(@n+1) + i.inspect + ",\n" end } @ar[@<EMAIL>-2,1]="]" @ar += " "*@n + "]\n" @n -= 1 end def makeStr(ar) @ar="[\n" @n = 0 _analize(ar) @ar[@ar.<EMAIL>-4,1]='' @ar end end module FDCommonMethod attr :controls def vrinit super @controls={} end def setcontrols(contorls) @controls = contorls end def checkfocus(x,y) p=[0,0,0x100000000,0x100000000] r = nil @controls.each { |i,c| unless c.is_a?(VRToolbar::VRToolbarButton) || c.is_a?(FDCoverPanel) || !c.visible? if (c.x < x) && (c.x+c.w > x) && (c.y < y ) && (c.y+c.h > y) then if p[0]<c.x || p[1]<c.y || p[2] >c.w || p[3]>c.h then p=[c.x,c.y,c.w,c.h] r=c if c && c.respond_to?(:addControl) && c.visible? then r1 = c.checkfocus(x-c.x,y-c.y) r=r1 if r1 end end end end } r end def findCtrl(s) c=nil @controls.each { |id,item| if item.respond_to?(:addControl) then return c if c = item.findCtrl( s ) end return item if item.name == s } c end end module WMsg RB_IDTOINDEX = WM_USER + 16 end module FDDraggable include VRMessageHandler def draggable_init if self.is_a? VRPanel addHandler WMsg::WM_PAINT, "vrsepl2paint", MSGTYPE::ARGNONE,nil acceptEvents [WMsg::WM_PAINT] else hookwndproc unless hookedwndproc? end addHandler WMsg::WM_LBUTTONDOWN,"lbuttondown",MSGTYPE::ARGLINTINT,nil addHandler WMsg::WM_MOUSEMOVE, "mousemove",MSGTYPE::ARGINTINTINT,nil addHandler WMsg::WM_LBUTTONUP, "lbuttonup", MSGTYPE::ARGLINTINT,nil addHandler WMsg::WM_RBUTTONUP, "rbuttonup", MSGTYPE::ARGINTSINTSINT,nil addHandler WMsg::WM_RBUTTONDOWN,"rbuttondown",MSGTYPE::ARGINTSINTSINT,nil addHandler WMsg::WM_SIZE, "resize",MSGTYPE::ARGLINTINT,nil acceptEvents [WMsg::WM_LBUTTONUP,WMsg::WM_RBUTTONUP, WMsg::WM_LBUTTONDOWN,WMsg::WM_RBUTTONDOWN, WMsg::WM_MOUSEMOVE,WMsg::WM_SIZE] end def self_lbuttondown(x,y) self.substance.move(self.x,self.y,w,h) if self.is_a? FDCoverPanel @parent.send "self_lbuttondown", (x < 0xefff ? x+self.x : x+self.x-0x10000), (y < 0xefff ? y+self.y : y+self.y-0x10000) SKIP_DEFAULTHANDLER unless self.is_a? VRTabControl end def self_mousemove(shift,x,y) @parent.send :self_mousemove,shift, (x < 0xefff ? x+self.x : x+self.x-0x10000), (y < 0xefff ? y+self.y : y+self.y-0x10000) end def self_lbuttonup(x,y) x0,y0,w0,h0=self.windowrect x0=self.x y0=self.y if respond_to? :initMargin then x0 = x0 - (mgLeft ? mgLeft : 0) y0 = y0 - (mgTop ? mgTop : 0) w0 = w0 + (mgLeft ? mgLeft : 0) + (mgRight ? mgRight : 0) h0 = h0 + (mgTop ? mgTop : 0) + (mgBottom ? mgBottom : 0) end self.move(x0,y0,w0,h0) @parent.send "self_lbuttonup", (x < 0xefff ? x+self.x : x+self.x-0x10000), (y < 0xefff ? y+self.y : y+self.y-0x10000) SKIP_DEFAULTHANDLER unless self.is_a? VRTabControl end def self_rbuttondown(shift,x,y) @parent.send "self_rbuttondown",shift, (x < 0xefff ? x+self.x : x+self.x-0x10000), (y < 0xefff ? y+self.y : y+self.y-0x10000) SKIP_DEFAULTHANDLER end def self_resize(w,h) if self.is_a? VRTabbedPanel x,y,w,h = adjustRect(0,0,self.w,self.h,false) @panels.each{|i| i.move x,y,w-x,h-y } else end end def self_vrsepl2paint nil end end module CreateCtrl require 'fdvr/fduser' #user defined configuration include FDControls attr_reader :cmodules, :cinfo, :_vr_menu, :_hsh_font, :required, :modules Stylehash = { "TBSTYLE_BUTTON" => 0, "TBSTYLE_SEP" => 1, "TBSTYLE_CHECK" => 2, "TBSTYLE_GROUP" => 4, "TBSTYLE_CHECKGROUP" => 6 } Indent_Str = ' ' module FDControlExt attr_reader :__org_x,:__org_y,:__org_w,:__org_h attr_accessor :form , :oldname, :items , :modules, :owndraw, :registerd_to, :margined, :_default_style def _ext_init() @modules = []; @owndraw = 0; @taborder = -1; @form = @parent.form; @oldname = @name ;@registerd_to = [] ;@margined = nil @_default_style = 0 end def set_modules(m); (@modules << m).uniq!; end def get_parents_str(c) return "" if c.is_a? VRForm s = "_#{c.name}" s[0,0] = get_parents_str(c.parent) unless c.parent.is_a? VRForm s end def getLevel(c) if c.is_a?(VRForm) || c.is_a?(VRDialogComponent) then "" else getLevel(c.parent) + Indent_Str end end def owndraw_used? FDOwnerDraw::ODConst[self.class].each{|key,value| return key if value == @owndraw } if @owndraw != 0 'not used' end def tab_order if (self.style & WStyle::WS_TABSTOP) == 0 then "" else @taborder.to_s end end def set_owndraw(state) unless @owndraw=FDOwnerDraw::ODConst[self.class][state] @owndraw=0 end end def mk_addstr(cnt,name,caption,x,y,w,h,sty) st = ','+sprintf("%#x",sty) unless sty == 0 "addControl(#{cnt},'#{name}',\"#{caption}\",#{x},#{y},#{w},#{h}#{st})\n" end end module FDParent include FDCommonMethod, CreateCtrl, VRContainersSet attr_reader :included, :names, :cntnmodules, :_fd_dragging, :_vr_twopaneframes attr_accessor :tabOrders, :__regsterd_vr_margined_frame, :_default_font, :_prev_dflt_hfont def fd_parent_init() vrinit; @included = []; @tabOrders=[]; @cntnmodules=[] end def addControl(*args) r = super if @_default_font then r.setFont(@_default_font) end r end def delete_child_controls @controls.each{|k,v| deleteControl(v) @form.delete_serial_name(v.name) delete_child_controls if v.respond_to? :addControl } end def getDEFAULTFONT(lv) return "" unless @_default_font hf=@_default_font.hfont n = @form.get_font_number(hf) "#{lv} DEFAULT_FONT=#{@form.name.capitalize1}_fonts[#{n}]\n" end def getFontStrParent(lv) return "" if !@_default_font || self.parent.is_a?(VRTabbedPanel) hf = @_default_font.hfont if (n = @form.get_font_number(hf)) lv + " self.setFont(#{@form.name.capitalize1}_fonts[#{n}])\n" else "" end end def get_childs_source(novrinit=nil) ctls = @controls.dup @cntnmodules=[] r=[] rf=[] lv=getLevel(self) s="\n"+lv+"class #{self.name.capitalize1} < #{self.class}\n"; sattr="" incld1 = [] @modules.uniq! analize_frame = lambda do |frame| if frame.is_a? VRTwoPaneFrame frame.pane1.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << yield(c) end end frame.pane2.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << yield(c) end end elsif frame.is_a? VRGridLayoutFrame frame._vr_layoutclients.each do |i| unless i[0].is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i[0].container.etc) rf << yield(c) end end else frame._vr_layoutclients.each do |i| unless i.is_a? SWin::Window analize_frame.call(i) c = ctls.delete(i.container.etc) rf << yield(c) end end end end if @__regsterd_vr_margined_frame analize_frame.call(@__regsterd_vr_margined_frame) c = ctls.delete( @__regsterd_vr_margined_frame.container.etc) rf << yield(c) end @tabOrders.each{|id| item = ctls.delete(id) next if item.class == FDCoverPanel if item.is_a? VRNotifyControl then (incld1 << "VRComCtlContainer").uniq! else (incld1 << "VRStdControlContainer").uniq! end (@modules << "VROwnerDrawControlContainer").uniq! if item.owndraw > 0 sattr += lv+" attr_reader :#{item.name}\n" item.style = item.style+WStyle::WS_TABSTOP r << yield(item) } ctls.each{|id,item| next if @tabOrders.index(id) next if item.class == FDCoverPanel if item.is_a? VRNotifyControl then (incld1 << "VRComCtlContainer").uniq! else (incld1 << "VRStdControlContainer").uniq! end (@modules << "VROwnerDrawControlContainer").uniq! if item.owndraw > 0 sattr += lv+" attr_reader :#{item.name}\n" r << yield(item) } unless @modules.empty? then incld1 = incld1 + @modules @modules.each{|m| if rq = FDModules::StdModules["#{m}".intern ] then (@form.required << rq.requires).uniq! @form.required.reject!{|i| !i} #delete nil end } end s1 = [] incld1.each{|i| s1 << lv+" include #{i}"} @included.each{|m| s1 << lv+" include #{m} if defined? #{m}" if m} s += s1.join("\n") + "\n" s += getDEFAULTFONT(lv) if @_default_font s += sattr s += @cntnmodules.join("") if @cntnmodules s += "\n#{lv} def construct\n" # s += getFontStrParent(lv) s += r.to_s s += rf.to_s s += lv+" end\n" s += lv+"end\n" s end def set_include(i) @included << i @included.uniq! end end module STDSourceMaker def getFontStr(lv) hf=sendMessage(WMsg::WM_GETFONT,0,0) hf=hf+0x100000000 if hf < 0 if (n = @form.get_font_number(hf)) && (!@parent._default_font || @parent._default_font.hfont != hf) lv + " @#{name}.setFont(#{@form.name.capitalize1}_fonts[#{n}])\n" else "" end end def addRequire unless @modules.empty? then @modules.each{|m| if rq = FDModules::StdModules["#{m}".intern ] then (@form.required << rq.requires).uniq! @form.required.reject!{|i| !i} end } end end def addModules sp=get_parents_str(self.parent) lv=getLevel(self) ms = lv+"class #{name.capitalize1} < #{self.class}\n" @modules.each{|m| ms += lv+" include #{m}\n"; (@form.required << FDModules::StdModules["#{m}".intern ].requires).uniq! @form.required.reject!{|i| !i} } ms += lv+"end\n\n" @parent.cntnmodules << ms end def createStdSourceStr if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y end str = "" sty = (self.style|@owndraw)-@_default_style sp = get_parents_str(self.parent) lv = getLevel(self) cnt = self.class.to_s if respond_to?(:addControl) then str += lv + " " + mk_addstr(name.capitalize1,name,caption.esc,x0,y0,w0,h0,sty) @parent.cntnmodules << get_childs_source{|i| i.createSourceStr} addRequire elsif !@modules.empty? || @owndraw > 0 then str += lv + " " + mk_addstr(name.capitalize1,name,caption.esc,x0,y0,w0,h0,sty) addModules else str += lv+" "+ mk_addstr(cnt,name,caption.esc,x0,y0,w0,h0,sty) end str+= getFontStr(lv) str end def createSourceStr createStdSourceStr end end def set_modules(m) (@modules << m) ; @modules.uniq! end def findPalletItem(cnt) r = nil if cnt.is_a? FDStruct then return cnt else if cnt.respond_to?(:substance) then c = cnt.substance else c = cnt end $conf.each{|pallet| r = pallet.items.find{|i| (c == i.klass) || (c.class == i.klass)} return(r) if r } end r end def set_cnt_attr(a,cnt) @required = [] unless @required @required << cnt.required @required.uniq! @cmodules={} unless @cmodules @cinfo={} unless @cinfo @cmodules[a.etc]=a.inspect.sub(/#<(.+):.*>/,'\1') @cinfo[a.etc]=cnt.klass a.extend(FDDraggable).draggable_init a.extend(FDControlExt)._ext_init a._default_style = cnt.default_style end def check_owndraw(c,addstyle) if ods = FDOwnerDraw::ODConst[c.klass] then ods.each{|key,value| return value if addstyle & value != 0 } end 0 end #definiton of creating methods on FormDesigner def newFDCtrl(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) c = findPalletItem(cnt) od = check_owndraw(c,addstyle) addstyle -= od if c.klass <= VRButton a = prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle ) prnt.set_include(c.included) a.extend STDSourceMaker set_cnt_attr(a,c) a.owndraw = od a.extend(FDParent).fd_parent_init if a.respond_to?(:addControl) a end module FDComboExt attr :drop_h,1 include STDSourceMaker end def newFDCombo(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) c = findPalletItem(cnt) addstyle |= 1 if c.klass == VREditCombobox od = check_owndraw(c,addstyle) addstyle -= od a=prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle ) a.extend FDComboExt prnt.set_include(c.included) def a.createSourceStr if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y end str = "" sty = style+@owndraw-@_default_style sty &= 0xfffffffe if self.class == VREditCombobox sp = get_parents_str(self.parent) lv = getLevel(self) cnt=self.to_s.sub(/\#\<([A-Za-z]+).*/,'\1') if !@modules.empty? || @owndraw > 0 then cnt = name.capitalize1 addModules end str += lv+" "+ mk_addstr(cnt,name,caption.esc,x0,y0,w0,@_drop_h,sty) str += getFontStr(lv) str end def a.drop_h; @_drop_h=h unless @_drop_h; @_drop_h end def a.set_drop_h(h0) @_drop_h=h0 ;end # def a.terminate # @parent.deleteControl @_coverPanel # end set_cnt_attr(a,c) a.owndraw = od a.set_drop_h(h) x0,y0,w0,h0=a.windowrect a.move(a.x,a.y,a.w,h0) a end module FDCoverExt attr :_coverPanel,1 include STDSourceMaker def move(x,y,w,h) super @_coverPanel.move(x,y,w,h) if @_coverPanel end end def newFDCoverd(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) c = findPalletItem(cnt) od = check_owndraw(c,addstyle) addstyle -= od cv=prnt.addControl(FDCoverPanel,'_'+name,'',x,y,w,h) a=prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle ) a.extend FDCoverExt prnt.set_include(c.included) def a.createSourceStr if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y end str = "" sty = self.style+@owndraw-@_default_style sp=get_parents_str(self.parent) lv=getLevel(self) cnt=self.to_s.sub(/\#\<([A-Za-z]+).*/,'\1') str += lv+" "+ mk_addstr(cnt,name,caption.esc,x0,y0,w0,h0,sty) hf=sendMessage(WMsg::WM_GETFONT,0,0) hf=hf+0x100000000 if hf < 0 if n = @form.get_font_number(hf) then str += lv+" @#{name}.setFont($_#{@form.name}_fonts[#{n}])\n" else nil end if @owndraw > 0 then str += lv+" @#{name}.extend(#{name.capitalize1}).vrinit\n" addModules end str end def a.terminate @parent.deleteControl @_coverPanel end set_cnt_attr(a,c) a.owndraw = od a._coverPanel = cv cv.substance = a a end def newFDToolbar(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) addstyle |= 4 if prnt.is_a? VRRebar c = findPalletItem(cnt) a=prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle ) a.class.module_eval "attr :_vr_toolbar_buttons,1" prnt.extend VRToolbarUseable prnt.set_include(c.included) def a.getItemsStr(option=nil) lv=getLevel(self) s = lv+" [" 0.upto(countButtons-1){|i| b = getButton(i) st = option ? b[3].to_s : Stylehash.invert[b[3]].to_s s << "\n#{lv} [\"#{@parent._vr_toolbar_buttons[b[1]].name}\",#{st}]," } if s[s.size-1] == ','[0] then s[s.size-1,1] = "\n#{lv} ]" else s << "]" end s end def a.getItems2 s = [] 0.upto(countButtons-1){|i| b = getButton(i) st = Stylehash.invert[b[3]].to_s s << [st,@parent._vr_toolbar_buttons[b[1]].name] } s end def a.refreshItems(ar) begin ar.collect!{|i| [i[1],Stylehash[i[0]]]} self.terminate setButtons(ar) self.items = ar rescue Exception messageBox $!,'Illegal setting of items',16 end end def a.terminate (countButtons-1).downto(0){|i| b = getButton(i) @parent._vr_toolbar_buttons.delete(b[1]) deleteButton(i) } end def a.createSourceStr if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y end str = "" sty = self.style-@_default_style cnt=self.class.to_s lv=getLevel(self) str += lv+" "+ mk_addstr(cnt,name,caption.esc,x0,y0,w0,h0,sty) if countButtons > 0 then str += lv+" "+"@#{name}.setButtons(\n#{getItemsStr(true)})\n" else str += "\n" end end def a.eventList as = [] 0.upto(countButtons-1){|i| b = getButton(i) as << @parent._vr_toolbar_buttons[b[1]].name + "_clicked" unless b[3] == 1 } as end def a.buttons @form._return_val=nil ItemEditDlg::POS[0] = [100,100,400,300] ItemEditDlg::LISTWIDTH[0] = 254 ItemEditDlg::ADDINGNAME[0] = 'toolButton' ItemEditDlg::ADDREMOVE[0] = true ItemEditDlg::TITLES[0]=[['button style',140],['button name',110]] ItemEditDlg::ITEMS[0] = getItems2 ItemEditDlg::FIXCOLUMN[0] = true ItemEditDlg::UPDOWN[0] = true ItemEditDlg::STYLES[0]=['TBSTYLE_BUTTON','TBSTYLE_SEP','TBSTYLE_CHECK', 'TBSTYLE_GROUP','TBSTYLE_CHECKGROUP'] ItemEditDlg::DEFAULTSTR[0]='TBSTYLE_BUTTON' VRLocalScreen.modalform @form ,nil,ItemEditDlg r = @form._return_val refreshItems(r) if r @form.refreshInspect(self) end set_cnt_attr(a,c) if c_items then a.setButtons(c_items) a.items = c_items elsif a.items a.setButtons(a.items) else items2=c.items.dup.collect!{|i| [get_serial_name(i[0]),i[1]] } a.setButtons(items2) a.items = items2 end a end def newFDRebar(prnt,cnt,name,caption,x,y,w,h,addstyle=0, c_items=nil) if prnt.is_a? VRRebar then messageBox 'cannot arrange VRRebar on VRRebar','Illegal arrangement',16 return end c = findPalletItem(cnt) a=prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle) prnt.set_include(c.included) a.extend STDSourceMaker def a.get_childs_source(novrinit=nil) @cntnmodules = [] lv=getLevel(self) r=[] s="" incld1 = [] @modules.uniq! @items.each{|i| ct = instance_eval("#{i[0]}") break if ct.is_a?(VRStatic) && i[0] == "@__"+ct.parent.name break if ct.class == FDCoverPanel if ct.kind_of? VRNotifyControl then (incld1 << "VRComCtlContainer").uniq! else (incld1 << "VRStdControlContainer").uniq! end r << yield(ct,i[1],i[2],i[3]) } unless @modules.empty? then incld1 = incld1 + @modules @modules.each{|m| if rq = FDModules::StdModules["#{m}".intern ] then (@form.required << rq.requires).uniq! @form.required.reject!{|i| !i} #delete nil end } end s += "\n#{lv} def construct\n" # s += getFontStrParent(lv) s += r.to_s s1 = [] incld1.each{|i| s1 << "#{lv} include #{i}"} @included.each{|m| s1<<"#{lv} include #{m} if defined? #{m}" if m} unless @included.empty? sp=get_parents_str(self.parent) s = s1.join("\n")+ "\n" + s s[0,0] = getDEFAULTFONT(lv) if @_default_font s[0,0] = "\n#{lv}class #{name.capitalize1} < #{self.class}\n" s += "#{lv} end\n" s += "#{lv}end\n" s end def a.createSourceStr if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y end str = "" sty = self.style-@_default_style sp=get_parents_str(self.parent) lv=getLevel(self) cnt=self.class.to_s if respond_to?(:addControl) then str += lv+" "+ mk_addstr(name.capitalize1,name,caption.esc, x0,y0,w0,h0,sty) @parent.cntnmodules << get_childs_source{|c,t,w,h| s=c.createSourceStr s.sub! /^ +/,lv+" @#{c.name}=" s << lv+" insertband(@#{c.name},'#{t}',#{w},#{h})\n" s } addRequire elsif !@modules.empty? then str += lv+" "+ mk_addstr(name.capitalize1,name,caption.esc,x,y,w,h,sty) addModules else str += lv+" "+ mk_addstr(cnt,name,caption.esc,x,y,w,h,sty) end str+= getFontStr(lv) str end def a.refreshItems(ar) @items.each_index{|i| i0 =ar.select{|j| @items[i][0] == j[0]}[0] @items[i][1] = i0[1] @items[i][2] = i0[2].to_i @items[i][3] = i0[3].to_i setbandattr(i,i0[1],i0[2].to_i,i0[3].to_i) } end def a.bands @form._return_val=nil ItemEditDlg::LISTWIDTH[0] = 392 ItemEditDlg::STYLES[0]=nil ItemEditDlg::POS[0] = [100,100,400,300] ItemEditDlg::ADDREMOVE[0] = false ItemEditDlg::UPDOWN[0] = false ItemEditDlg::TITLES[0]=[['control',100],['text',100], ['min w',92],['min h',92]] ItemEditDlg::ITEMS[0] = @items ItemEditDlg::FIXCOLUMN[0] = true VRLocalScreen.modalform @form ,nil,ItemEditDlg r = @form._return_val refreshItems(r) if r end def a.setbandattr(idx,txt="",minx=30,miny=30) unless idx.is_a? Integer n = @items.index(items.find{|i| i[0] == "@#{idx.name}" }) idx = n end mask= WConst::RBBIM_TEXT | WConst::RBBIM_STYLE | WConst::RBBIM_CHILD | WConst::RBBIM_CHILDSIZE | WConst::RBBIM_SIZE t= "" tis = [56,mask,0,0,0,t,0,0,0,0,0,0,0,0,0].pack("LLLLLP#{t.length}LLLLLLLL") sendMessage WMsg::RB_GETBANDINFO,idx,tis a = tis.unpack("LLLLLPLLLLLLLL") a[5]= txt; a[9]=minx; a[10]=miny rbbi=a.pack("LLLLLP#{txt.length}LLLLLLLL") sendMessage(WMsg::RB_INSERTBAND+5,idx,rbbi) end def a.deleteband(idx) sendMessage WMsg::RB_DELETEBAND,idx,0 end def a.update_items(oldname,newname) @items.find{|i|i[0]=='@'+oldname}[0] = '@' + newname end =begin def a.terminate @items.reject!{|i| unless i[0] == "@__#{self.name}" deleteControl(instance_eval("#{i[0]}")) child_deleted(instance_eval("#{i[0]}")) end true } end =end def a.child_created(c) if c0=@items.find{|i| i[0] == "@__#{self.name}"} then deleteControl(instance_eval("#{c0[0]}")) @items.delete_at(0) deleteband(0) end @parent.instance_eval("@#{c.name}=nil") @parent.instance_eval "@controls.delete(c.etc)" @controls[c.etc] = c unless itm=@items.find{|i| i[0] == '@'+c.name} then @items << itm=['@'+c.name,c.name,30,c.h+2] end instance_eval "@#{c.name}=c" insertband(c,itm[1],itm[2],itm[3]) relayout end def a.child_deleted(c) idx = @items.index(@items.find{|i| i[0] == '@'+c.name }) @items.delete_at(idx) deleteband(idx) if @items.empty? then cv=addControl(VRStatic,"__#{name}",'',0,0,25,25) @parent.instance_eval("@#{cv.name}=nil") @parent.instance_eval "@controls.delete(cv.etc)" @controls[cv.etc] = cv instance_eval("@#{cv.name}=cv") insertband(cv,"",0,30) @items = [['@'+cv.name,""]] c1 = findPalletItem(cv) @form.set_cnt_attr(cv,c1) end end set_cnt_attr(a,c) a.extend(FDParent).fd_parent_init unless c_items then cv=a.addControl(VRStatic,"__#{name}",'',0,0,25,25) a.parent.instance_eval("@#{cv.name}=nil") a.parent.instance_eval "@controls.delete(cv.etc)" a.controls[cv.etc] = cv a.instance_eval("@#{cv.name}=cv") a.insertband(cv,"",0,30) a.items = [['@'+cv.name,""]] c1 = findPalletItem(cv) set_cnt_attr(cv,c1) else a.items = c_items end a end def newFDTabbedPanel(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) if prnt.is_a? VRTabControl then messageBox 'cannot arrange VRTabbedPanel on VRTabControl','Illegal arrangement',16 return end c = findPalletItem(cnt) # addstyle = 0 unless addstyle od = check_owndraw(c,addstyle) addstyle -= od a=prnt.addControl(c.klass,name,caption,x,y,w,h,addstyle ) a.extend STDSourceMaker prnt.set_include(c.included) def a.getItemsStr(option=nil) lv=getLevel(self) s = "[\n" 0.upto(countTabs-1){ |i| s += "#{lv} ['#{getTabTextOf(i)}'," + "#{@panels[i].name.capitalize1},'#{@panels[i].name}'],\n"} s[s.size-2,2] = "\n#{lv} ]" s end def a.getItems2 s = [] 0.upto(countTabs-1){ |i| s << [@panels[i].name,getTabTextOf(i)]} s end def a.refreshItems(a0) @items = a0.collect{|i| i[1]} a1 = a0.select{|i| i[0]!=""}.collect{|i| instance_eval('@'+i[0])} @panels.each_with_index{|itm,idx| unless a1.find{|j| j == itm } then @panels[idx].delete_child_controls deleteControl(@panels[idx]) @panels.delete_at(idx) end } @panels.each{|i| instance_eval "@#{i.name}=nil" i.name = "___"+i.name } clearTabs 0.upto(a0.size-1){|i| insertTab(i,a0[i][1]) if (n=a0[i][0]) != '' then m = 0.upto(@panels.size-1){|j| break j if @panels[j].name == "___#{n}" } @panels[i,0] = @panels.delete_at(m) instance_eval "@#{@panels[i].name.sub(/^___/,'')}=nil" @panels[i].name = "panel#{i}" instance_eval "@#{@panels[i].name}=@panels[i]" else @panels[i,0] = nil x,y,w,h = adjustRect(0,0,self.w,self.h,false) @panels[i] = addControl(VRPanel,"panel#{i}","panel#{i}",x,y,w-x,h-y) @panels[i].extend VRContainersSet @panels[i].containers_init @panels[i].show 0 c1 = @form.findPalletItem(@panels[i]) @form.set_cnt_attr(@panels[i],c1) @panels[i].extend STDSourceMaker @panels[i].extend(FDParent).fd_parent_init @panels[i].extend CreateCtrl end @panels[i]._default_font = self._default_font } #selectTab 0 end def a.terminate end def a.createSourceStr lv = getLevel(self) if respond_to? :initMargin x0=@__org_x; y0=@__org_y; w0=@__org_w; h0=@__org_h sr = lv + " auto_panelresize(true)\n" else x0,y0,w0,h0 = self.windowrect; x0=self.x; y0=self.y sr = "" end str = "" sty = self.style+@owndraw-@_default_style cnt=self.class.to_s str += lv+" "+mk_addstr(name.capitalize1,name,caption.esc,x0,y0,w0,h0,sty) s2 = "" sattr="" @panels.each{|i| i.modules = self.modules sattr += lv+" attr_reader :#{i.name}\n" s2 << i.get_childs_source(true){|j| j.createSourceStr} } s2 += "\n" + lv + " def construct\n" s2 += getFontStrParent(lv) s2 += lv + " setupPanels(*#{getItemsStr(true)})\n" if @panels.size > 0 s2 += lv + " end\n" @parent.cntnmodules<<"\n#{lv}class #{name.capitalize1} < #{self.class}\n" @modules.each{|m| @parent.cntnmodules << lv+" include #{m}\n"; (@form.required << FDModules::StdModules["#{m}".intern ].requires).uniq! @form.required.reject!{|i| !i} } @parent.cntnmodules << "#{sattr}" @parent.cntnmodules << getDEFAULTFONT(lv) if @_default_font @parent.cntnmodules << sr @parent.cntnmodules << s2 + "#{lv}end\n" str += getFontStr(lv) str end def a.pages @form._return_val=nil ItemEditDlg::LISTWIDTH[0] = 392 ItemEditDlg::STYLES[0]=nil ItemEditDlg::POS[0] = [100,100,400,300] ItemEditDlg::ADDINGNAME[0] = 'tab' ItemEditDlg::ADDREMOVE[0] = true ItemEditDlg::UPDOWN[0] = false ItemEditDlg::TITLES[0]=[['panel',120],['title',100]] ItemEditDlg::ITEMS[0] = getItems2 ItemEditDlg::FIXCOLUMN[0] = true VRLocalScreen.modalform @form ,nil,ItemEditDlg r = @form._return_val refreshItems(r) if r @form.refreshCntName @form.refreshInspect(self) end set_cnt_attr(a,c) a.owndraw = od a.extend(FDParent).fd_parent_init if c_items then a.setupPanels(*c_items) a.items = c_items elsif a.items a.setupPanels(*a.items) else a.setupPanels(*c.items) a.items = c.items end a.panels.each{|i| c1 = findPalletItem(i) set_cnt_attr(i,c1) i.extend STDSourceMaker i.extend(FDParent).fd_parent_init } a end def newFDMenu(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) c = findPalletItem(cnt) prnt.class.module_eval "attr :_vr_menus,1 " a=addControl(FDContainer,name,caption,x,y,w,h,addstyle ) prnt.set_include(c.included) def a.createMthodStr(t) s= "@#{self.name}.#{t}" s end def a.getItemsStr mn=MenuStrMaker.new mn.makeStr(@items) end def a.refreshItems(a) begin self.items = a @parent._vr_menus.clear self.terminate self.substance = @parent.newMenu.set(self.items) @parent.setMenu self.substance,false rescue Exception messageBox $!,'Illegal setting of items',16 end end def a.terminate @parent.setMenu @parent.newMenu,false if parent.visible? end def a.set_attrs(a) #do nothing end def a.createSourceStr r = " \#$_addControl(VRMenu,'#{name}',\"\",#{x},#{y},24,24)\n" r += " @#{self.name} = newMenu.set(\n" r += self.getItemsStr.gsub(/^/," "*6) r += " )\n" @_kb_accel=false unless @_kb_accel r += " setMenu(@#{self.name},#{@_kb_accel})\n" # r += " \#$_ctn_#{self.name}=[#{self.x},#{self.y}]\n" r end def a.eventList s_ary = [] @parent._vr_menus.each{|i,c| s_ary << c.name + "_clicked" unless c.name == '_vrmenusep' } s_ary end def a.menus a = [] @form._return_val=nil analizer = MenuAnalizer.new MenuEditDlg::ITEMS[0] = analizer.analize(@items) MenuEditDlg::POS[0] = [@form.x+50,@form.y+50,468,300] 0.upto(analizer.colCount-1){|i| a << ["#{i+1}",112]} MenuEditDlg::TITLES[0]=a VRLocalScreen.modalform @form ,nil,MenuEditDlg r = analizer.unanalize(@form._return_val) if @form._return_val refreshItems(r) if r @form.refreshInspect(self) end def a.accel(a = true) @_kb_accel = a end def a.getaccel() @_kb_accel end set_cnt_attr(a,c) a.bmp=SWin::Bitmap.loadString(c.bmp) if c_items then a.items=c_items elsif c.items a.items=c.items else a.items=FDMenuTemplate end a.accel(true) a.substance = newMenu.set a.items self.setMenu a.substance,false a end def newFDPopup(prnt,cnt,name,caption,x,y,w,h,addstyle=0,c_items=nil) c = findPalletItem(cnt) a=addControl(FDContainer,name,caption,x,y,w,h,addstyle ) prnt.set_include(c.included) def a.createMthodStr(t) case t when /^showPopup/ s=t.sub /(\(.+\))/,"(@#{self.name})" else s= "@#{self.name}.#{t}" end s end def a.getItemsStr mn=MenuStrMaker.new mn.makeStr(@items) end def a.set_attrs(a) #do nothing end def a.createSourceStr r = " \#$_addControl(FDPopup,'#{name}',\"\",#{x},#{y},24,24)\n" r += " @#{self.name} = newPopupMenu.set(\n" r += self.getItemsStr.gsub(/^/," "*6) r += " )\n" r end def a.menus a = [] @form._return_val=nil analizer = MenuAnalizer.new MenuEditDlg::ITEMS[0] = analizer.analize(@items) MenuEditDlg::POS[0] = [@form.x+50,@form.y+50,468,300] 0.upto(analizer.colCount-1){|i| a << ["#{i+1}",112]} MenuEditDlg::TITLES[0]=a VRLocalScreen.modalform @form ,nil,MenuEditDlg @items = analizer.unanalize(@form._return_val) if @form._return_val @form.refreshInspect(self) end def a.eventList ar = [] an = MenuAnalizer.new ana = an.analize(@items) ana.each{|i| level = 0 flag0 = nil a = [] i.each{|j| if j == "" then break if flag0 level += 1 else a << j flag0 = true end } ar << a[1]+'_clicked' if a.size > 1 && a[1] != "_vrmenusep" } ar end set_cnt_attr(a,c) if c_items then a.items=c_items elsif c.items a.items=c.items else a.items=FDItems::FDPopupMenuTemplate end a.bmp=SWin::Bitmap.loadString(c.bmp) a.substance = c.klass.new a end def newFDOpenSaveDlg(prnt,cnt,name,caption,x,y,w,h,addstyle=0,info=nil,ext=nil) c = findPalletItem(cnt) a=addControl(FDContainer,name,caption,x,y,w,h,addstyle ) def a.init @substance.filters = FDItems::FDDlgFilterTemplate if @substance.class == FDOpenDlg aryFlags = FDComDlgItems::OpenFileFlag @substance.flags = aryFlags['OFN_FILEMUSTEXIST'] else aryFlags = FDComDlgItems::SaveFileFlag @substance.flags = aryFlags['OFN_OVERWRITEPROMPT'] end @substance.title = nil @substance.defaultExt = nil end def a.createSourceStr cnt=self.substance.class.name.sub /^.*::/,'' sb = self.substance sty = sprintf("%#x",style) r = " \#$_addControl(#{cnt},'#{name}',\"\",#{x},#{y},24,24)\n" r += " \#$_ctn_#{self.name}=[#{sb.filters.inspect},#{sb.flags.to_x},"+ "#{sb.title.inspect},#{sb.defaultExt.inspect}]\n" r end def a.createMthodStr(s) sb = self.substance str = s.sub /\(.*$/ , '' fs = sb.flags ? sb.flags.to_x : 'nil' "#{str}(#{sb.filters.inspect},#{fs},#{sb.title.inspect},"+ "#{sb.defaultExt.inspect})" end def a.set_attrs(a) @substance.filters = a[0] @substance.flags = a[1] @substance.title = a[2] @substance.defaultExt = a[3] end def a.filters @substance.filters = [["all(*.*)","*.*"]] unless @substance.filters @form._return_val=nil ItemEditDlg::LISTWIDTH[0] = 392 ItemEditDlg::STYLES[0]=nil ItemEditDlg::POS[0] = [100,100,400,300] ItemEditDlg::ADDINGNAME[0] = '*.*' ItemEditDlg::ADDREMOVE[0] = true ItemEditDlg::UPDOWN[0] = true ItemEditDlg::TITLES[0]=[['title',200],['filter',100]] ItemEditDlg::ITEMS[0] = @substance.filters ItemEditDlg::FIXCOLUMN[0] = false VRLocalScreen.modalform @form ,nil,ItemEditDlg r = @form._return_val @substance.filters=r if r @form.refreshInspect(self) end def a.flags if @substance.class == FDOpenDlg aryFlags = FDComDlgItems::OpenFileFlag @substance.flags = aryFlags['OFN_FILEMUSTEXIST'] unless @substance.flags else aryFlags = FDComDlgItems::SaveFileFlag @substance.flags = aryFlags['OFN_OVERWRITEPROMPT'] unless @substance.flags end a = [] aryFlags.each{|k,v| n = ((@substance.flags & v) == 0 ) ? 0 : 1 a << [k.dup,n] } if s = @form.showModDlg(a,104,195) then n = 0 s.each{|i| n |= aryFlags[i[0]] if i[1] !=0} @substance.flags=n end @form.refreshInspect(self) end def a.title() @substance.title end def a.defaultExt() @substance.defaultExt end a.substance = c.klass.new set_cnt_attr(a,c) a.bmp=SWin::Bitmap.loadString(c.bmp) a.init a end def newFDSelectDir(prnt,cnt,name,caption,x,y,w,h,addstyle=0,info=nil,ext=nil) c = findPalletItem(cnt) a=addControl(FDContainer,name,caption,x,y,w,h,addstyle ) def a.init @substance.flags=FDComDlgItems::BrowseFolderFlag["BIF_RETURNONLYFSDIRS"] end def a.flags a = [] FDComDlgItems::BrowseFolderFlag.each{|k,v| n = ((@substance.flags & v) == 0 ) ? 0 : 1 a << [k.dup,n] } if s = @form.showModDlg(a,104,195) then n = 0 s.each{|i| n |= FDComDlgItems::BrowseFolderFlag[i[0]] if i[1] !=0} @substance.flags = n end end def a.set_attrs(a) #do nothing end def a.title() @substance.title end def a.initialdir() @substance.initialdir end def a.terminate end def a.createSourceStr cnt=self.substance.class.name.sub /^.*::/,'' sty = sprintf("%#x",style) r = " \#$_addControl(#{cnt},'#{name}',\"\",#{x},#{y},24,24)\n" r += " \#$_ctn_#{self.name}=[#{self.x},#{self.y},"+ "#{@substance.title.inspect},#{@substance.initialdir.inspect},"+ "#{@substance.flags.to_x}]\n" r end def a.createMthodStr(s) sb = self.substance str = s.sub /\(.*$/ , '' fs = sb.flags ? sb.flags.to_x : 'nil' "#{str}(#{sb.title.inspect},#{sb.initialdir.inspect},#{fs})" end a.substance = c.klass.new set_cnt_attr(a,c) a.bmp=SWin::Bitmap.loadString(c.bmp) a.init a end def newFD2Pane(prnt,cnt,name,caption,x,y,w,h,addstyle=0,items=nil,first=nil) c = findPalletItem(cnt) a=prnt.addControl(FDContainer,name,"",x,y,w,h,addstyle ) prnt.set_include(c.included) def a.getItemsStr(option=nil) "" end def a.set_attrs(a) #do nothing end def a.refreshItems(ar) end def a.terminate if parent.__regsterd_vr_margined_frame == self.substance parent.__regsterd_vr_margined_frame=nil;GC.start end @substance.bevel=VRMgdTwoPaneFrame::BevelNone @substance.gap=0 @substance.pane1.each{|i| if i.is_a? SWin::Window then i.setMargin(nil,nil,nil,nil) i.registerd_to = [] i.margined = nil end } if @substance.pane1 @substance.pane2.each{|i| if i.is_a? SWin::Window then i.setMargin(nil,nil,nil,nil) i.registerd_to = [] i.margined = nil end } if @substance.pane2 end def a.createSourceStr def self.create_setmargin(lv,name,o) "#{lv} @#{name}.setMargin("+o.mgLeft.inspect+','+o.mgTop.inspect+ ','+o.mgRight.inspect+','+o.mgBottom.inspect+")\n" end make_panes = lambda do |p| s=p.map{|i| '@'+(i.is_a?(SWin::Window) ? i.name : i.container.name)+','}.to_s s[0,s.size-1] end lv = getLevel(self) sb = self.substance cnt=sb.class.name.sub /^.*::/,'' sty = sprintf("%#x",style) r = "#{lv} \#$_addControl(#{cnt},'#{name}',\"\",#{x},#{y},24,24)\n" if parent.__regsterd_vr_margined_frame == self.substance r += "#{lv} @#{self.name}=setMarginedFrame(#{cnt}," + "[#{make_panes.call(sb.pane1)}],[#{make_panes.call(sb.pane2)}])\n" r += create_setmargin(lv,self.name,sb) else r += "#{lv} @#{self.name}=#{cnt}.new([#{make_panes.call(sb.pane1)}]," + "[#{make_panes.call(sb.pane2)}]).setup(self)\n" end r += "#{lv} @#{self.name}.ratio=#{sb.ratio}\n" if sb.ratio r += "#{lv} @#{self.name}.position=#{sb.position}\n" if sb.position r += "#{lv} @#{self.name}.gap=#{sb.gap}\n" r += "#{lv} @#{self.name}.bevel=" + "VRMgdTwoPaneFrame::Bevel#{eval(@form.prBevel).call(self)}\n" r += "#{lv} @#{self.name}.lLimit=#{sb.lLimit}\n" if sb.lLimit > 0 if sb.is_a? VRHorizTwoPaneFrame r += "#{lv} @#{self.name}.rLimit=#{sb.rLimit}\n" if sb.rLimit > 0 else r += "#{lv} @#{self.name}.uLimit=#{sb.uLimit}\n" if sb.uLimit > 0 end sb.pane1.each do |i| if i.is_a? SWin::Window r += create_setmargin(lv,i.name,i) else r += create_setmargin(lv,i.container.name,i) end end sb.pane2.each do |i| if i.is_a? SWin::Window r += create_setmargin(lv,i.name,i) else r += create_setmargin(lv,i.container.name,i) end end r end def a.createMthodStr(s) str = s.sub /\(.*$/ , '' "#{str}" end c.klass.module_eval("attr :pane1,1;attr :pane2,1") c.klass.module_eval("attr :container,1") if first or (!items && !prnt.__regsterd_vr_margined_frame) if items a.substance = prnt.setMarginedFrame(c.klass, items[0].map{|i| (j= prnt.instance_eval(i)).is_a?(FDContainer)? j.substance : j}, items[1].map{|i| (j= prnt.instance_eval(i)).is_a?(FDContainer)? j.substance : j}) a.substance.pane1.each do |i| if i.is_a?(SWin::Window) i.registerd_to=[a,0] i.margined = true else i.container.registerd_to=[a,0] end end a.substance.pane2.each do |i| if i.is_a?(SWin::Window) i.registerd_to=[a,1] i.margined = true else i.container.registerd_to=[a,1] end end else a.substance = prnt.setMarginedFrame(c.klass,[],[]) end a.bmp=SWin::Bitmap.loadString(c.bmp) else if items a.substance = c.klass.new( items[0].map{|i| (j= prnt.instance_eval(i)).is_a?(FDContainer)? j.substance : j}, items[1].map{|i| (j= prnt.instance_eval(i)).is_a?(FDContainer)? j.substance : j}) a.substance.pane1.each do |i| if i.is_a?(SWin::Window) i.registerd_to=[a,0] else i.container.registerd_to=[a,0] end end a.substance.pane2.each do |i| if i.is_a?(SWin::Window) i.registerd_to=[a,1] else i.container.registerd_to=[a,1] end end else a.substance = c.klass.new([],[]).initMargin(0,0,0,0) end a.substance.setup(prnt) bm=SWin::Bitmap.loadString(c.bmp) bm1 = SWin::Bitmap.newBitmap(23,23) 0.upto(bm.width-1) do |i| 0.upto(bm.height-1) do |j| clr = bm[i,j] bm1[i,j] = [clr[1],clr[2],clr[0]] end end a.bmp=bm1 end a.substance.container = a a.substance.bevel = VRMgdTwoPaneFrame::BevelGroove1 _x,_y,_w,_h= prnt.clientrect prnt.sendMessage(WMsg::WM_SIZE,0,MAKELPARAM(_w,_h)) set_cnt_attr(a,c) a end def newFDLayout(prnt,cnt,name,caption,x,y,w,h,addstyle=0,items=nil,first=nil) c = findPalletItem(cnt) a=prnt.addControl(FDContainer,name,"",x,y,w,h,addstyle ) prnt.set_include(c.included) def a.getItemsStr(option=nil) "" end def a.set_attrs(a) #do nothing end def a.refreshItems(ar) end def a.terminate if parent.__regsterd_vr_margined_frame == self.substance parent.__regsterd_vr_margined_frame=nil end @substance._vr_layoutclients.each{|i| if i.is_a? SWin::Window then i.setMargin(nil,nil,nil,nil) i.registerd_to = nil i.margined = nil end } end def a.createSourceStr def self.create_setmargin(lv,name,o) "#{lv} @#{name}.setMargin("+o.mgLeft.inspect+','+o.mgTop.inspect+ ','+o.mgRight.inspect+','+o.mgBottom.inspect+")\n" end make_panes=lambda do |p| unless self.substance.is_a? VRGridLayoutFrame s=p.map{|i| '@'+ if i.is_a?(SWin::Window) i.name elsif i.is_a? Array if i[0].is_a? SWin::Window i[0].name else i[0].container.name end else i.container.name end +',' }.to_s else s=p.map{|i| '[@'+ if i.is_a?(SWin::Window) i.name+",#{i.x},#{i.y},#{i.w},#{i.h}" elsif i.is_a? Array if i[0].is_a? SWin::Window i[0].name+",#{i[0].x},#{i[0].y},#{i[0].w},#{i[0].h}" else i[0].container.name + ",#{i[0].parent.x},#{i[0].parent.y}"+ ",#{i[0].parent.w},#{i[0].parent.h}" end else i.container.name+",#{i.parent.x},#{i.parent.y}"+ ",#{i.parent.w},#{i.parent.h}" end +'],' }.to_s end s[0,s.size-1] end lv = getLevel(self) sb = self.substance cnt=sb.class.name.sub /^.*::/,'' sty = sprintf("%#x",style) r = "#{lv} \#$_addControl(#{cnt},'#{name}',\"\",#{x},#{y},24,24)\n" if parent.__regsterd_vr_margined_frame == sb unless sb.is_a? VRGridLayoutFrame r += "#{lv} @#{self.name}=setMarginedFrame(#{cnt})\n" else r += "#{lv} @#{self.name}=setMarginedFrame(#{cnt},"+ "#{sb.instance_eval('@_vr_xsize')},"+ "#{sb.instance_eval('@_vr_ysize')})\n" end unless sb._vr_layoutclients.empty? r += "#{lv} @#{self.name}.register(" + "#{make_panes.call(sb._vr_layoutclients)})\n" r += create_setmargin(lv,self.name,sb) end else r += "#{lv} @#{self.name}=#{cnt}.new\n" end sb._vr_layoutclients.each do |i| if i.is_a? SWin::Window r += create_setmargin(lv,i.name,i) elsif i.is_a? Array if i[0].is_a? SWin::Window r += create_setmargin(lv,i[0].name,i[0]) else r += create_setmargin(lv,i[0].container.name,i[0]) end else r += create_setmargin(lv,i.container.name,i) end end r end def a.createMthodStr(s) str = s.sub /\(.*$/ , '' "#{str}" end c.klass.module_eval("attr :_vr_layoutclients,1") c.klass.module_eval("attr :container,1") if first or (!items && !prnt.__regsterd_vr_margined_frame) if items if c.klass == VRMgdGridLayoutFrame a.substance = prnt.setMarginedFrame(c.klass,prnt.w,prnt.h) else a.substance = prnt.setMarginedFrame(c.klass, items.map{|i| (j= prnt.instance_eval(i)).is_a?(FDContainer)? j.substance : j}) end else if c.klass == VRMgdGridLayoutFrame a.substance = prnt.setMarginedFrame(c.klass,prnt.w,prnt.h) else a.substance = prnt.setMarginedFrame(c.klass) end end a.bmp=SWin::Bitmap.loadString(c.bmp) else if items if c.klass <= VRGridLayoutFrame a.substance = c.klass.new(prnt.w,prnt.h).initMargin(0,0,0,0) else a.substance = c.klass.new.initMargin(0,0,0,0) end else if c.klass <= VRGridLayoutFrame a.substance = c.klass.new(prnt.w,prnt.h).initMargin(0,0,0,0) else a.substance = c.klass.new.initMargin(0,0,0,0) end end bm=SWin::Bitmap.loadString(c.bmp) bm1 = SWin::Bitmap.newBitmap(23,23) 0.upto(bm.width-1) do |i| 0.upto(bm.height-1) do |j| clr = bm[i,j] bm1[i,j] = [clr[1],clr[2],clr[0]] end end a.bmp=bm1 end a.substance.container = a _x,_y,_w,_h= prnt.clientrect prnt.sendMessage(WMsg::WM_SIZE,0,MAKELPARAM(_w,_h)) set_cnt_attr(a,c) a end def newFDModule(prnt,cnt,name,caption,x,y,w,h,addstyle=0,info=nil,ext=nil) c = findPalletItem(cnt) a=addControl(FDContainer,name,caption,x,y,w,h,addstyle ) def a.getItemsStr(option=nil) "" end def a.set_attrs(a) #do nothing end def a.refreshItems(ar) end def a.terminate end def a.createSourceStr cnt=self.substance.class.name.sub /^.*::/,'' sty = sprintf("%#x",style) r = " \#$_addControl(#{cnt},'#{name}',\"\",#{x},#{y},24,24)\n" r end def a.createMthodStr(s) str = s.sub /\(.*$/ , '' "#{str}" end a.substance = c.klass.new set_cnt_attr(a,c) a.bmp=SWin::Bitmap.loadString(c.bmp) a end def createinit() $conf = controls_init user_createinit end end class FDCoverPanel < VRPanel include FDDraggable undef :addControl attr :substance,1 def vrinit super draggable_init end end class FDDummyPanel < VRPanel undef :addControl def vrinit super draggable_init end end <file_sep># fdinspect.rb # Inspect Window of FormDesigner # # Programmed by <EMAIL> # Copyright 2001-2003 <NAME> require 'vr/vruby' require 'vr/sysmod' require 'vr/vrcontrol' require 'vr/vrcomctl' require 'vr/vrhandler' require 'vr/clipboard' require 'vr/vrmgdlayout' require 'fdvr/fddialogs' class PnEvt < VRPanel include VRResizeable def construct messageBox self.to_s addControl VRListbox,"evtList","" @evtList.move 0,0,100,100 end def self_resize(w,h) messageBox w.to_s r=cleientrect @evtList.move 0,0,w,h end end class PnMtd < VRPanel include VRResizeable attr :inspectView def construct addControl VRButton,"bt1","bt1",0,0,100,25 addControl VRListview ,"inspectView", "",0,0,100,100 @inspectView.reportview @inspectView.addColumn("name") @inspectView.addColumn("value") @inspectView.setColumnWidthOf(1,78) @inspectView.visible=true end def self_resize(w,h) @inspectView.move(0,0,w,h) end end class EditableListview < EDListview include VRParent include VRStdControlContainer include VRMarginedFrameUseable attr_accessor :ed, :btArray BevelConst = ['None','Groove1','Groove2','Raise1','Raise2','Sunken1','Sunken2'] def construct self.lvexstyle=1 addControl InplaceEdit,"ed","ed",0,0,10,10,0x80 #create inplace editor addControl VRButton,"btStyle","...",0,0,10,10 addControl VRButton,"btExStyle","...",0,0,10,10 addControl VRCombobox,"btFont","...",0,0,10,10 addControl VRButton,"btModule","...",0,0,10,10 addControl VRButton,"btArray","...",0,0,10,10 addControl VRButton,"btTab","...",0,0,10,10 addControl VRCombobox,"cbTF",'true',0,0,10,40 addControl VRCombobox,"cbOwnDraw",'true',0,0,10,50 addControl VRCombobox,"cbBevel",'None',0,0,10,50 addControl VRButton,"btLayout","...",0,0,10,10 @ed.setFont $SysFont @btStyle.setFont $SysFont @btExStyle.setFont $SysFont @btFont.setFont $SysFont @btModule.setFont $SysFont @btArray.setFont $SysFont @btTab.setFont $SysFont @cbTF.setFont $SysFont @cbOwnDraw.setFont $SysFont @cbBevel.setFont $SysFont @btLayout.setFont $SysFont @ed.visible=false @btStyle.visible=false @btExStyle.visible=false @btFont.visible=false @btFont.setListStrings ['new','default'] @btModule.visible=false @btArray.visible=false @btTab.visible=false @cbTF.setListStrings ['true','false'] @cbTF.visible=false @cbOwnDraw.visible=false @cbBevel.setListStrings BevelConst @cbBevel.visible=false @btLayout.visible=false end def setFont(font) super @ed.setFont(font) end def hideAllContorls @controls.each{|i,j| j.visible=false} end def self_lbuttondown(shift,x,y) hideAllContorls @idx,@subitem,left,top,width,height = *hittest3(x,y) selectItem(@idx,false) if @subitem!=1 then width = getColumnWidthOf(1) left = getColumnWidthOf(0) @subitem = 1 end case getItemTextOf(@idx,2) when "nil" # do nothing when "_btStyle" @btStyle.move(left+width-height,top,height,height) @btStyle.show when "_btExStyle" @btExStyle.move(left+width-height,top,height,height) @btExStyle.show when "_btFont" s=getItemTextOf(@idx,1) @btFont.move(left,top-4,width,height+40) @btFont.select s=='default' ? 1 : 0 @btFont.show when "_btModule" @btModule.move(left+width-height,top,height,height) @btModule.show when "_btArray" @btArray.move(left+width-height,top,height,height) @btArray.show when "_btTab" @btTab.move(left+width-height,top,height,height) @btTab.show when "_cbTF" s=getItemTextOf(@idx,1) @cbTF.move(left,top-4,width,height+40) @cbTF.select s=='true' ? 0 : 1 @cbTF.show when "_cbOwnDraw" owndrwConst=FDOwnerDraw::ODConst[@parent.parent.designfrm.focused.class] if owndrwConst && fowndrw=owndrwConst.keys then @cbOwnDraw.clearStrings @cbOwnDraw.setListStrings(a = ['not used'] + fowndrw) s=getItemTextOf(@idx,1) @cbOwnDraw.move(left,top-4,width,height+64) @cbOwnDraw.select a.index(s) @cbOwnDraw.show end when "_cbBevel" s=getItemTextOf(@idx,1) @cbBevel.move(left,top-4,width,height+96) @cbBevel.select BevelConst.index(s) @cbBevel.show when "_btLayout" @btLayout.move(left+width-height,top,height,height) @btLayout.show else s=getItemTextOf(@idx,1) @ed.move(left-1,top-1,width+2,height+2) @ed.text=getItemTextOf(@idx,@subitem) @ed.show @ed.focus end end def update return if getItemTextOf(@idx,1) == @ed.text if @idx == 0 && @parent.parent.designfrm.names.index(@ed.text) then messageBox "already used name : '#{@ed.text}'",'name definition eror',16 return end setItemTextOf(@idx,1,@ed.text) @parent.updateCont end def btStyle_clicked @parent.parent.designfrm.setWinStyle end def btExStyle_clicked @parent.parent.designfrm.setExStyle end def btFont_selchanged svalue = @btFont.getTextOf(@btFont.selectedString) @parent.parent.designfrm.ctrl_setFont(svalue == 'default') end def btModule_clicked @parent.parent.designfrm.setModules end def btArray_clicked @parent.parent.designfrm.focused.instance_eval("#{getItemTextOf(@idx,0)}") end def btTab_clicked @parent.parent.designfrm.ctrl_Tab_orders end def cbTF_selchanged str = getItemTextOf(@idx,0) #"sizebox" or "maximizebox" svalue = @cbTF.getTextOf(@cbTF.selectedString) #"true" or "false" @parent.parent.designfrm.setTrueFalse(str,svalue) setItemTextOf(@idx,1,svalue) end def cbOwnDraw_selchanged #str = getItemTextOf(@idx,0) #always "owndraw" svalue = @cbOwnDraw.getTextOf(@cbOwnDraw.selectedString) @parent.parent.designfrm.focused.set_owndraw(svalue) setItemTextOf(@idx,1,svalue) @parent.parent.designfrm.refreshInspect(@parent.parent.designfrm.focused) end def cbBevel_selchanged svalue = @cbBevel.getTextOf(@cbBevel.selectedString) @parent.parent.designfrm.focused.substance.bevel = { 'None'=>VRMgdTwoPaneFrame::BevelNone, 'Groove1'=>VRMgdTwoPaneFrame::BevelGroove1, 'Groove2'=>VRMgdTwoPaneFrame::BevelGroove2, 'Raise1'=>VRMgdTwoPaneFrame::BevelRaise1, 'Raise2'=>VRMgdTwoPaneFrame::BevelRaise2, 'Sunken1'=>VRMgdTwoPaneFrame::BevelSunken1, 'Sunken2'=>VRMgdTwoPaneFrame::BevelSunken2}[svalue] setItemTextOf(@idx,1,svalue) @parent.parent.designfrm.focused.parent.refresh @parent.parent.designfrm.refreshInspect(@parent.parent.designfrm.focused) end def btLayout_clicked @parent.parent.designfrm.registerLayout end end class FDListboxExt < VRListbox def vrinit super addCommandHandler(WMsg::LBN_DBLCLK, "dblclicked",MSGTYPE::ARGNONE,nil) end end module FDInspect include VRMessageHandler include VRResizeable include VRDestroySensitive include VRStatusbarDockable include VRClosingSensitive attr_reader :inspectView attr_accessor :cbControl, :evtList, :mthdList, :stb2, :skip_ctrl_name def vrinit super addHandler(WMsg::WM_ACTIVATE,"activate", MSGTYPE::ARGINTINT,0) addHandler(WMsg::WM_MOVE,"move", MSGTYPE::ARGLINTINT,0) acceptEvents([WMsg::WM_ACTIVATE,WMsg::WM_MOVE]) end def construct begin SWin::Application.setAccel(self,@parent) ;rescue ;end addControl VRTabControl,"tab1","tab1" @tab1.setFont $SysFont @tab1.insertTab(0,"Attr") @tab1.insertTab(1,"Event") @tab1.insertTab(2,"Mthd") @stb2 = addStatusbar addControl FDListboxExt,"evtList","" addControl FDListboxExt,"mthdList","" @evtList.setFont $SysFont @mthdList.setFont $SysFont addControl VRCombobox,"cbControl","ComboBox1" @cbControl.setFont($SysFont) @cbControl.setListStrings(["1","2","4","8","16"]) @cbControl.select(0) @evtList.setListStrings([]) @evtList.visible=false @mthdList.visible=false addControl EditableListview ,"inspectView", "" @inspectView.reportview @inspectView.setFont($SysFont) @inspectView.addColumn("name") @inspectView.addColumn("value") @inspectView.addColumn("option") @inspectView.setColumnWidthOf(1,78) @inspectView.setColumnWidthOf(2,0) @inspectView.enabled=true end def self_created end def updateCont n = @inspectView.countItems s = "" if @parent.designfrm.focused.class == FDContainer then arg = [@inspectView.getItemTextOf(0,1),@inspectView.getItemTextOf(1,1)] arg << @inspectView.getItemTextOf(2,1).to_i arg << @inspectView.getItemTextOf(3,1).to_i arg = arg + [24,24] 4.upto(n-1){|i| s0 = @inspectView.getItemTextOf(i,0) s1 = @inspectView.getItemTextOf(i,1) s2 = @inspectView.getItemTextOf(i,2) if s2 == "numnil" s = (s1 =~ /^\d+$/) ? s1 : "nil" arg << ["self."+s0,s] elsif s2 == "" s = (s1 =~ /^\d+$/) ? s1 : s1.inspect arg << [ "@" + s0,s] elsif s2 == "num" s = (s1 =~ /^\d+$/) ? s1 : "0" arg << ["self."+s0,s] elsif !(s2 == "nil") && !(s2 =~ /^_.*/) s = (s1 =~ /^[+-]?\d+\.?\d*$/) ? s1 : s1.inspect arg << [s2,s] else end } if n > 4 else arg = [@inspectView.getItemTextOf(0,1),@inspectView.getItemTextOf(1,1)] 2.upto(5){|i| arg << @inspectView.getItemTextOf(i,1).to_i } 6.upto(n-1){|i| s0 = @inspectView.getItemTextOf(i,0) s1 = @inspectView.getItemTextOf(i,1) s2 = @inspectView.getItemTextOf(i,2) if s2 == "numnil" s = (s1 =~ /^\d+$/) ? s1 : "nil" arg << ["self."+s0,s] elsif s2 == "" s = (s1 =~ /^\d+$/) ? s1 : s1.inspect arg << [ "@_" + s0,s] elsif s2 == "num" s = (s1 =~ /^\d+$/) ? s1 : "0" arg << ["self."+s0,s] elsif !(s2 == "nil") && !(s2 =~ /^_.*/) s = (s1 =~ /^[+-]?\d+\.?\d*$/) ? s1 : s1.inspect arg << [s2,s] else end } if n > 6 end @parent.designfrm.update_target(*arg) end def self_activate(wParam,hwnd) @inspectView.hideAllContorls if LOWORD(wParam) == 0 end def self_resize(w,h) a=windowrect @tab1.move(0,20,w,20) @cbControl.move(0,0,w,200) @evtList.move(0,40,w,h-60) @mthdList.move(0,40,w,h-60) @inspectView.move(0,40,w,h-60) $ini.write "inspect","top",a[1] $ini.write "inspect","left",a[0] $ini.write "inspect","width",a[2] $ini.write "inspect","height",a[3] end def tab1_selchanged case @tab1.selectedTab when 0 @evtList.visible=false @mthdList.visible=false @inspectView.visible=true when 1 @evtList.visible=true @mthdList.visible=false @inspectView.visible=false when 2 @mthdList.visible=true @evtList.visible=false @inspectView.visible=false end @stb2.caption = "" end def self_destroy a=windowrect $ini.write "inspect","x",a[0] $ini.write "inspect","y",a[1] $ini.write "inspect","w",a[2] $ini.write "inspect","h",a[3] $ini.write "inspect","viewCol_0",@inspectView.getColumnWidthOf(0) $ini.write "inspect","viewCol_1",@inspectView.getColumnWidthOf(1) parent.inspectShow.checked = false @controls.each{|i,c| deleteControl(c) } $ini.flash end def self_close SKIP_DEFAULTHANDLER end def setItems(a) @inspectView.clearItems a.each do |item| @inspectView.addItem(item) end end def evtList_selchanged if tt=@evtList.getTextOf(@evtList.selectedString) unless (tt=~/^self_\w+/) || (@skip_ctrl_name) || (tt=~/^ownerdraw.+/) ctl = @parent.designfrm.focused nm = "" if !ctl nm = "self_" elsif (prnt=ctl.parent).modules.index(VRMessageParentRelayer) nm = prnt.name + '_' + ctl.name + '_' while (prnt=prnt.parent).modules.index(VRMessageParentRelayer) nm[0,0] = prnt.name + '_' end else nm = ctl.name + '_' end end tt=" def #{nm}#{tt}\n \n end\n\n" @stb2.caption = "Copied to ClipBoard" clb1=Clipboard.open(self.hWnd) clb1.setText(tt) clb1.close end end def evtList_dblclicked parent.show_editor end def mthdList_selchanged if t=@mthdList.getTextOf(@mthdList.selectedString) then if @parent.designfrm.focused.class == FDContainer then tt = @parent.designfrm.focused.createMthodStr(t) elsif !@parent.designfrm.focused n=@parent.designfrm.name.capitalize1 case t when 'modelessform' if @parent.designfrm.type_of_form == VRModelessDialog tt=FDSources::StartOfMdlsDlg else tt=FDSources::StartOfModeless end tt += n + FDSources::StartOfModeless2 when 'start' tt = FDSources::StartOfForm + n when 'openModalDialog','openModelessDialog' tt = "@screen.#{t}(self,nil,#{n})" else tt = t end else n = @parent.designfrm.focused.name case t when /(\A[a-z_]\w*)\s*=\s*(.+)/ t1 = $1; t2 = "=" when /(\A[a-z_]\w*)\s*(\(.*\))/ t1 = $1; t2 = $2 #"(#{$2.gsub(/[^,]/,"")})" which do you like? when /(\A[a-z_]\w*)/ t1 = $1 ; t2 = "" end tt="@#{n}.#{t1}#{t2}" end @stb2.caption = "Copied to ClipBoard" clb1=Clipboard.open(self.hWnd) clb1.setText(tt) clb1.close end end def mthdList_dblclicked parent.show_editor end def cbControl_selchanged @inspectView.hideAllContorls s=@cbControl.getTextOf(@cbControl.selectedString).sub(/(.+):.+/,'\1') @parent.designfrm.changeFocuse(s) end def self_move(x,y) if $ini.read("settings","dock",'true')=='true' then sx,sy,sw,sh=self.windowrect px,py,pw,ph=parent.windowrect self.move(px,py+ph,sw,sh) end end end <file_sep># fdmain.rb # The main window of FormDesiner # # Programmed by <EMAIL> # Copyright 2001-2004 <NAME> require 'vr/contrib/inifile' #Dir.chdir $program_dir $ini=Inifile.new("FormDesigner.ini") $Lang=$ini.read("settings","language","EN") $Ver='060501' require 'set' require 'zlib' require 'swin' require 'win32ole' require 'vr/vruby' require 'vr/vrcontrol' require 'vr/vrcomctl' require 'vr/vrhandler' require 'vr/vrtooltip' require 'vr/vrtimer' require 'vr/contrib/msgboxconst' require 'vr/vrmgdlayout' require 'vr/vrdde' require 'fdvr/fdwin32' require 'fdvr/fdresources' require 'fdvr/SDKTopic' module WConst WS_CAPTION=0x00c00000 WS_SYSMENU=0x00080000 DS_SETFONT=0x40 DS_MODALFRAME=0x80 LBS_NODATA = 0x2000 LBS_NOTIFY = 0x0001 LBS_OWNERDRAWFIXED = 0x0010 end class String def capitalize1(); self[0,1].upcase + self[1,self.size-1] ; end end class ArrayedToolbar < VRToolbar def insertArrayedbutton(num,name,tbStyle=TBSTYLE_BUTTON) r = insertButton(num,name+"#{num}",tbStyle) @parent.registerControlAsArrayed(num,r,name,r.etc) end def addArrayedbutton(num,name,tbStyle=TBSTYLE_BUTTON) r = addButton(name+"#{num}",tbStyle) @parent.registerControlAsArrayed(num,r,name,r.etc) end end module FDPanelExt include VRToolbarUseable attr :items def setToolbar(items) @items = items addControl ArrayedToolbar,'tb','tb',0,0,100,40,2048 @tb.addButton "btnoselect",WConst::TBSTYLE_BUTTON @tb.insertButton 1,"btsep",WConst::TBSTYLE_SEP items.each_index{|i| @tb.addArrayedbutton(i, "bt",WConst::TBSTYLE_CHECKGROUP) } iml=imagelistCreate(items) @tb.setImagelist(imagelistCreate(items)) @tb.autoSize 2.upto(@tb.countButtons-1){|i| $tooltip.addTool @_vr_toolbar_buttons[@tb.getButton(i)[1]],items[i-2].info } self.refresh end def imagelistCreate(a) r=@screen.factory.newimagelist(23,23,1) bmp=SWin::Bitmap.loadString FDBmps::BmpNoselect r.addmasked(bmp,0x00808000) if a then a.each do |item| bmp=SWin::Bitmap.loadString item.bmp r.addmasked(bmp,0x00808000) end end r end def noselection for i in 0..@tb.countButtons - 1 @tb.setButtonStateOf(@tb.indexToCommand(i),4) parent.parent.setcontrol nil end end def bt_clicked(i) parent.parent.setcontrol @items[i] end def btnoselect_clicked noselection end end class FDTabbedPanel < VRTabControl #setup Pallets include VRParent attr :panels def vrinit super @panels = [] @pallets = [] end def addPanel(pallet) i = countTabs insertTab i, pallet.title x1,y1,w1,h1 = adjustRect(0,0,self.w,self.h,false) @pallets << pallet @panels << addControl(VRPanel,"panel#{i}","panel#{i}",x1,y1,w1-x1,h1-y1) @panels.last.extend VRContainersSet @panels.last.extend(FDPanelExt).setToolbar(pallet.items) @panels.last.containers_init @panels.last.show 0 @_vr_prevpanel=0 selectTab 0 end def selectTab(i) super selchanged end def selchanged @panels[@_vr_prevpanel].show(0) if @_vr_prevpanel t=selectedTab @panels[t].show @_vr_prevpanel=t @panels[t].refresh @panels[t].noselection end def noselectAll @panels.each {|i| i.noselection} end end module Toolbarhandler def imagelistCreate(a) @iml=@screen.factory.newimagelist(23,23,1) bmp=SWin::Bitmap.loadString $noselectbmp @iml.addmasked(bmp,0x00808000) if a then a.each { |item| bmp=SWin::Bitmap.loadString item.bmp @iml.addmasked(bmp,0x00808000) } end end end $newclass = VRLocalScreen.factory.registerWinClass("designfrm",nil,nil,nil,0) class DesignForm < VRForm def DesignForm.winclass $newclass end end class FDControlSelection < VRForm # As Main Form attr :inspectfrm attr :designfrm,1 attr :forms attr :tab attr :formShow attr :inspectShow attr :mainmenu attr :amenu attr :afont,1 attr :dialog_running,1 include VRStatusbarDockable include VRMenuUseable include VRToolbarUseable include VRClosingSensitive include VRDestroySensitive include VRCommonDialog include VRResizeable include VRTimerFeasible include User32 include Shell32 include Hhctrl include WConst include Base64dumper if defined?(VRDdeRequestServer) then include VRDdeExecuteServer include VRDdePokeServer include VRDdeRequestServer end HH_INITIALIZE = 0x001C # Initializes the help system. HH_UNINITIALIZE = 0x001D HH_DISPLAY_TOC = 0x1 HH_DISPLAY_INDEX = 0x2 HH_DISPLAY_SEARCH = 0x3 HH_HELP_CONTEXT = 0xF Start_Of_FrmID = 0x1000 begin SDKDocument = WIN32OLE.new 'DExplore.AppObj' rescue SDKDocument = nil end SDKDocument.SetCollection FDSDK::DE_Prefix,'' if SDKDocument def self_wmcommand(msg) if (frmID=LOWORD(msg.wParam))>=Start_Of_FrmID then select_form(frmID) else super end end ### initialize def vrinit super addHandler(WMsg::WM_ACTIVATEAPP,"activateapp", MSGTYPE::ARGINTINT,0) addHandler(WMsg::WM_MOVE,"move", MSGTYPE::ARGLINTINT,0) acceptEvents([WMsg::WM_ACTIVATEAPP,WMsg::WM_MOVE]) @fd_cookie=nil @forms=[] @project_type=nil @dialog_running=nil end def preferdlgcreate tpl=VRDialogTemplate.new tpl.style = WS_CAPTION | DS_MODALFRAME | WS_SYSMENU | DS_SETFONT tpl.fontname = "MS Gothic" tpl.fontsize = 11 tpl.caption=FDPrfItems::Preferences stt=tpl.addDlgControl(VRStatic,FDPrfItems::GridSize,7,4,40,12) stt2=tpl.addDlgControl(VRStatic,FDPrfItems::Editor,7,18,30,12) btok=tpl.addDlgControl(VRButton,FDPrfItems::OK,5,50,40,12) btcan=tpl.addDlgControl(VRButton,FDPrfItems::CANCEL,50,50,40,12) btbrowse=tpl.addDlgControl(VRButton,"...",142,16,14,12) ed1=tpl.addDlgControl(VREdit,"8",50,2,20,12,0x0880000) ed2=tpl.addDlgControl(VREdit,"",40,16,100,12,0x0880000) st1=tpl.addDlgControl(VRStatic,"cygwin's line separator:",7,32,100,12) chb1=tpl.addDlgControl(VRCheckbox,"LF Only",110,30,50,12) @prdlg=PrDlg.new(VRLocalScreen,tpl) @prdlg.options ={"target"=>ed1,"target2"=>ed2,"okbutton"=>btok, "cancelbutton"=>btcan,"browsebutton"=>btbrowse,"checkbox"=>chb1, "default"=>"8","default2"=>"notepad.exe","check"=>false} end def examindlgcreate tpl = VRDialogTemplate.new tpl.style = WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_SETFONT tpl.fontname = "MS Gothic" tpl.fontsize = 10 tpl.caption="Examine" btok = tpl.addDlgControl(VRButton,"O K",140,204,40,12,0x00010000) ed1 = tpl.addDlgControl(VRText,"",6,4,320,200,0x00200840) @examinedlg=ExamineModalDlg.new(@screen,tpl) @examinedlg.options ={"target"=>ed1,"okbutton"=>btok,"default" => [["",0]]} end def construct HtmlHelp.call(0,nil,HH_INITIALIZE,@fd_cookie) addDDEAppTopic("FormDesigner","Edit") if defined?(addDDEAppTopic) self.sizebox=false self.maximizebox=false clear_modified $main=self require 'fdvr/m17n' fon=$ini.read("settings","font","MS UI Gothic,12").split(',') $SysFont=@screen.factory.newfont(fon[0],fon[1].to_f) top=$ini.read("mainform","top",0).to_i left=$ini.read("mainform","left",0).to_i self.move left,top,640,124 $editor=$ini.read("settings","editor","notepad.exe") if RUBY_PLATFORM =~ /^\w+-cygwin/ && $ini.read("settings",'LFOnly','false')=='false' then $n="\r\n" else $n="\n" end if $ini.read("settings","dock",'true')=='true' then @inspect_x=left @inspect_y=top+124 else @inspect_x=$ini.read("inspect","x",left).to_i @inspect_y=$ini.read("inspect","y",top+124).to_i end @inspect_w=$ini.read("inspect","w",140).to_i @inspect_h=$ini.read("inspect","h",400).to_i examindlgcreate @inspectfrm=@screen.newform(self) @inspectfrm.extend FDInspect @inspectfrm.move @inspect_x,@inspect_y,@inspect_w,@inspect_h @inspectfrm.caption="Inspect" @inspectfrm.create.show @inspectfrm.inspectView.setColumnWidthOf(0, $ini.read("inspect","viewCol_0",50)) @inspectfrm.inspectView.setColumnWidthOf(1, $ini.read("inspect","viewCol_1",78)) @amenu=newMenu(true).set(FDMenuItems::FDPopupmenu) # Set Menu setMenu @mainmenu=newMenu.set(FDMenuItems::FDMainmenu) ,true new_designfrm $tooltip = createTooltip # Create Pallets addControl FDTabbedPanel,"tab","tab",0,0,self.clientrect[2],58 @tab.setFont $SysFont $conf.each{|i| @tab.addPanel(i)} SWin::Application.setAccel(@designfrm,self) SWin::Application.setAccel(@inspectfrm,self) @sb1=addStatusbar @running = false @hwndEd = 0 @buffer1 = @buffer2 = "" @sb1.setparts(3,[100,480,-1]) @_dde_line_no = 0 @_new_project = nil end def create_form(_x,_y,_w,_h,s) frm = @screen.newform(self,nil,DesignForm) frm.extend FDControlDesign frm.createinit frm.move(_x,_y,_w,_h) frm.caption=s frm.create.show check_form_menu(true) frm end def new_designfrm a=self.windowrect remove_instance_variable(:@designfrm) if defined?(@designfrm) @forms<<create_form(a[0]+@inspectfrm.windowrect[2],a[1]+124,500,400,'form1') @forms[0].etc=Start_Of_FrmID @mainmenu.menu.insert "form1",Start_Of_FrmID,@inspectShow.etc-1 @designfrm=@forms[0] window_menu_set_check(@designfrm.etc) self.caption = "FormDesigner" @hwndEd = 0 @workingfile = nil clear_modified @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each{|i| @class_struct1.childs << i.makeModStruct(i,@class_struct1)} end def setcontrol(ctrl) if @designfrm.creation=ctrl then @sb1.setTextOf(0,"#{ctrl.info}") if @sb1 else @sb1.setTextOf(0,FDMsgItems::NoChosen) if @sb1 end end def self_created s = ARGV.shift if s == nil # default elsif s != '' if FileTest.exist? s open1 s else messageBox *FDMsgItems::NoFileError end else messageBox *FDMsgItems::OptionError end end ### DDE ### def self_ddeexecute(command,shwnd,appname,topic) case command when /initiate\s*,\s*(\d*)/ @hwndEd = $1.to_i @new_form.state=1 @new_modeless_form.state=1 @new_modeless_dlg.state=1 @open.state=1 @save.state=1 @saveas_form.state=1 @saveas_proj_part.state=1 @saveas_proj_mono.state=1 @run_editor.state=1 @update_proj.state=1 @exit.state=1 inc_modified @_dde_mode=true when "show" self.focus else end end def self_dderequest(item,shwnd,app,topic) clear_modified @_dde_result end def self_ddepoke(item,data,cfmt,shwnd,app,topic) @_dde_result = "" begin if @modified==0 then @_dde_result=""; return; end @_dde_ed_line_no = item.to_i @_dde_line_no = @_dde_ed_line_no if @project_type == :mono then data.scan(/^#{FDSources::BeginOfFD}.*^#{FDSources::EndOfFD}/m)[0] @buffer1=$` ? $` : "" @buffer2=$' ? $' : "" form_lin_count = $& ? $&.count("\n") : 0 line_count1 = @buffer1.count("\n") line_count2 = @buffer2.count("\n") if @_dde_line_no <= line_count1 state=-1 @_dde_line_no = 0 elsif (n=@_dde_line_no-form_lin_count-line_count1)>=0 state=1 @_dde_line_no = n else state=0 @_dde_line_no = 0 end @_a_buffer2=$'.to_a @_a_buffer2=[''] if @_a_buffer2.empty? @buffer2=update if @_new_project then @_dde_result="#{@_dde_line_no}\n#! ruby -Ks\n"+ @buffer1+make_fdvr_source unless $ini.read("settings","verbose","true")=="false" @_dde_result += FDSources::Follows else @_dde_result += "\n" end @_dde_result += @buffer2+ "#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" @_new_project = nil else s=make_fdvr_source if state < 0 n=line_count1 elsif state == 0 n=line_count1+s.count("\n") else n=line_count1+s.count("\n")+@_dde_line_no end @_dde_result="#{n}\n"+@buffer1+s+@buffer2 end else @buffer1="" @buffer2="" @_a_buffer2=data.to_a @_a_buffer2=[''] if @_a_buffer2.empty? @buffer2=update save if @_new_project then @_dde_result="#{@_dde_line_no}\n"+ "require '#{File.basename(@workingfile)}'\n\n"+ @buffer2+"#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" @_new_project = nil else @_dde_result="#{@_dde_line_no}\n"+@buffer2 end end rescue messageBox($!.to_s + "\r\n" + $@.join("\r\n")) end end def self_ddeterminate(hwnd) self.close end ### File ### def close_all_forms @forms.each{|i| @mainmenu.delete(i.etc) i.close } @forms=[] @hinstance=nil @designform=nil @hwndEd = 0 @workingfile = nil @project_type=nil clear_modified self.caption = "FormDesigner" end def new_form(ctype) unless @designfrm.alive? then new_designfrm #@formShow.checked = true end if @modified > 0 then if save_prepare_close("New file") then close_all_forms new_designfrm end else close_all_forms new_designfrm end @designfrm.type_of_form = ctype #@hinstance = nil end def check_form_menu(b) @change_to_mainform.checked = b @change_to_modeless_mainform.checked = !b end def new_form_clicked new_form(VRForm) @designfrm.refreshCntName @designfrm.refreshInspect(nil) check_form_menu(true) end def new_modeless_form_clicked new_form(VRDialogComponent) @designfrm.refreshCntName @designfrm.refreshInspect(nil) check_form_menu(false) end def new_modeless_dlg_clicked new_form(VRModelessDialog) @designfrm.refreshCntName @designfrm.refreshInspect(nil) check_form_menu(false) end def change_to_mainform_clicked @forms[0].type_of_form = VRForm @designfrm.refreshInspect(@designfrm.focused) if designfrm == @forms[0] check_form_menu(true) inc_modified end def change_to_modeless_mainform_clicked @forms[0].type_of_form = VRDialogComponent @designfrm.refreshInspect(@designfrm.focused) if designfrm == @forms[0] check_form_menu(false) inc_modified end def change_to_modeless_maindlg_clicked @forms[0].type_of_form = VRModelessDialog @designfrm.refreshInspect(@designfrm.focused) if designfrm == @forms[0] check_form_menu(false) inc_modified end def save_prepare_close(s) r = messageBox(FDMsgItems::DoYouSave,s, WConst::MB_ICONQUESTION|WConst::MB_YESNOCANCEL|WConst::MB_SYSTEMMODAL) case r when 6 if save_clicked then r = true end when 7 r = true else r = nil end r end def scan_project(str) case str when /^\s*module\s+[A-Z][a-zA-Z0-9_]*/, /^\s*class\s+[A-Z][a-zA-Z0-9_]*.*$/ yield 1,$1 when /^\s*end/ yield -1,nil end end def parse_project(str) while true str = scan_project(str){|n,s| } break if str == "" end end def open_clicked if @modified == 0 || save_prepare_close(FDMsgItems::OpenPreare) then wf=openFilenameDialog( [["ruby scripts","*.rb"],["ruby forms","_frm_*.rb"]]) if wf open1(wf) clear_modified end end end def open_by_drop(fn) return if @_dde_mode return unless File.extname(fn) =~ /\.[rR][bB]/ if @modified == 0 || save_prepare_close(FDMsgItems::OpenPreare) then wf= fn if wf open1(wf) clear_modified end end end def read_form(s,idx=0) def check_selial_name(nm) if @forms.find{|i| i.name == nm} then check_selial_name(nm.sub(/([0-9]+)$/,'')+($1.to_i+1).to_s) else nm end end if s0=s.scan(/^#{FDSources::BeginOfFD}.*^#{FDSources::EndOfFD}/m)[0] @buffer1=$` @buffer2=$' close_all_forms if idx==0 s0.scan(/^class.*?^end/m){|s| @forms[idx,0] = create_form(0,0,0,0,"") @designfrm = @forms[idx] s.match(/^class +([A-Z][a-zA-Z0-9_]*)\s*<\s([A-Z][a-zA-Z0-9_]*).*$/) if idx > 0 then @designfrm.name=check_selial_name($1[0,1].downcase+$1[1..$1.size-1]) else @designfrm.name=$1[0,1].downcase+$1[1..$1.size-1] end @designfrm.type_of_form=eval($2) check_form_menu(@designfrm.type_of_form <= VRForm) @designfrm.oldname=@designfrm.name.dup @designfrm.parse_str($') } @forms[idx..@forms.size-1].each_with_index{|c,i| @mainmenu.menu.insert(c.name,Start_Of_FrmID+i+idx,@inspectShow.etc-1) c.etc=Start_Of_FrmID+i+idx } true else nil end end def set_project_type(typ) case typ when :mono @sb1.setTextOf(2,FDProjectTypes::Mono) when :apart @sb1.setTextOf(2,FDProjectTypes::Apart) else @sb1.setTextOf(2,FDProjectTypes::Form) end @project_type=typ end def open1(wf) str='' tstamp=0 fobj=nil #begin open(wf){|f| wf=File.expand_path(wf);tstamp=f.stat.mtime.to_i; str=f.read } wf0 = File.basename(wf).sub(/^_frm_(.+)/,'\1') unless read_form(str) wf1 = File.dirname(wf)+'/_frm_'+ wf0 if File.exist?(wf1) then open(wf1){|f| tstamp=f.stat.mtime.to_i; str=f.read} else # new project NewProjectDlg.args = wf if @screen.openModalDialog(self,nil,NewProjectDlg) then set_project_type :apart @workingfile=wf1 else set_project_type :mono @workingfile=wf end self.caption=self.caption+" - #{@workingfile.gsub!(/\//,'\\')}" @_new_project = true return end unless read_form(str) #old version close_all_forms @forms<<create_form(0,0,0,0,"") @designfrm=@forms.last @designfrm.readfile(str) end set_project_type :apart @workingfile = wf1 else if File.basename(wf) =~ /^_frm_/ then set_project_type nil else set_project_type :mono end @workingfile = wf end #rescue # messageBox FDMsgItems::Noform # return #end $tstamp = tstamp @designfrm=@forms[0] @designfrm.focus window_menu_set_check(@forms[0].etc) @designfrm.refreshCntName @designfrm.refreshInspect(nil) self.caption = "FormDesigner - #{@workingfile.gsub!(/\//,'\\')}" @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each do|i| x,y,w,h = i.windowrect @class_struct1.childs << i.makeModStruct(i,@class_struct1) end if $RDE s = (File.dirname(wf)+"/#{wf0}").tr('/','\\') @rde_project = $RDE.newCodeWindow(s) end end def save_clicked if @project_type == :mono then update_proj_clicked return end if @workingfile then save else saveas_form_clicked end end def saveas_form_clicked if r = saveFilenameDialog(["ruby forms","_frm_*.rb"]) then case r when /(.+)\\(.+)\.rb$/ d = $1;e = $2 when /(.+)\\(.+)$/ d = $1;e = $2 end e.sub!(/^_frm_/,'') @workingfile= d + '\\_frm_' + e + '.rb' save @project_type = nil @sb1.setTextOf(2,FDProjectTypes::Form) end r end def saveas_proj_part_clicked if r = saveFilenameDialog(["ruby scripts","*.rb"]) then case r when /(.+)\\(.+)\.rb$/ d = $1;e = $2 when /(.+)\\(.+)$/ d = $1;e = $2 end e.sub!(/^_frm_/,'') @workingfile= d + '\\_frm_' + e + '.rb' save saveProject(d + '\\' + e + '.rb') @project_type = :apart @sb1.setTextOf(2,FDProjectTypes::Apart) end end def saveas_proj_mono_clicked if r = saveFilenameDialog(["ruby scripts","*.rb"]) then save1(r,true) self.caption = "FormDesigner - #{@workingfile=r}" @project_type = :mono @sb1.setTextOf(2,FDProjectTypes::Mono) end end def self_activateapp(wParam,hwnd) return if @_dde_mode if LOWORD(wParam) == 1 then if @workingfile && File.exist?(@workingfile) then r = checkTstamp($tstamp) end if r then rr=messageBox *FDMsgItems::FileWasModified case rr when 6 clear_modified wf = @workingfile ; ed = @hwndEd ctype = @designfrm.type_of_form close_all_forms @designfrm.type_of_form = ctype @workingfile = wf ; @hwndEd =ed open1(@workingfile) self.caption = "FormDesigner - #{@workingfile}" else $tstamp=File.stat(@workingfile).mtime.to_i end end else if @editorStarting then @hwndEd = 0 @hwndEd = GetForegroundWindow.call until @hwndEd > 0 end @editorStarting = false end end def checkTstamp(time) File.stat(@workingfile).mtime.to_i > $tstamp end def make_fdvr_source a = [] s0 = FDSources::BeginOfFD unless $ini.read("settings","verbose","true")=="false" s0 += FDSources::Caution else s0 += "\n" end s1 = "" @forms.reverse_each{|i| s1 += i.make_executive a << 'vrdialog' if i.type_of_form <= VRDialogComponent a = a + i.get_require } a.uniq.each{|i| s0+="require 'vr/#{i}'\n"} s = s0 + s1 s += "\n" + FDSources::EndOfFD s end def save1(fname,proj=nil) s = make_fdvr_source if proj then unless $ini.read("settings","verbose","true")=="false" s += FDSources::Follows else s += "\n" end @forms.reverse_each{|i| s += modStruct_to_s(i.makeModStruct(i)) } if @forms[0].type_of_form == VRDialogComponent then s += FDSources::StartOfModeless+@forms[0].name.capitalize1 + FDSources::StartOfModeless2 elsif @forms[0].type_of_form == VRModelessDialog then s += FDSources::StartOfMdlsDlg+@forms[0].name.capitalize1 + FDSources::StartOfModeless2 else s += "\n#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" end unless (@bufffer1 == "") && (@buffer2 == "") @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each{|i| @class_struct1.childs << i.makeModStruct(i,@class_struct1)} end #########出力結果をソートする############# s_out = "" add_control_buf = [] atter_reader_buf = [] s.each do |s_line| add_control_flag = false atter_reader_falg = false if s_line =~ /^ +addControl\(/ add_control_flag = true add_control_buf.push s_line next end if s_line =~ /^ +attr_reader :/ atter_reader_falg = true atter_reader_buf.push s_line next end if add_control_buf.size > 0 add_control_buf.sort! s_out += add_control_buf.join add_control_buf = [] end if atter_reader_buf.size > 0 atter_reader_buf.sort! s_out += atter_reader_buf.join atter_reader_buf = [] end s_out += s_line end if add_control_buf.size == 0 && atter_reader_buf.size == 0 s = s_out end ############################################# open(fname,"w") {|f| f.write s $tstamp=f.stat.mtime.to_i clear_modified} end def save r=save1(@workingfile) @sb1.setTextOf(1,@workingfile + FDMsgItems::Saved) self.caption = "FormDesigner - #{@workingfile}" @designfrm.focused = nil @designfrm.refreshInspect(nil) @designfrm.setFocusRgn(nil) r end def modStruct_to_s(st,level=0) lv = " "*level s0=lv + "class #{st.name}" s = s0 + ' '*(s0.size<68 ? 68-s0.size : 1) + FDSources::TagOfFD + "\n\n" st.childs.each{|i| s += modStruct_to_s(i,level+1)} s += " def self_created\n\n end\n" if level == 0 s0 = lv + "end" s += s0 + ' '*(s0.size<68 ? 68-s0.size : 1) + FDSources::TagOfFD + "\n\n" end def project_prefix(filepath) s = "#! ruby -Ks\n" s += "require \'vr/vruby\'\n" s += "require '_frm_#{File.basename(filepath,'.rb')}'\n" unless @project_type == :mono s end def saveProject(filepath) ss = project_prefix(filepath) @forms.reverse_each{|i| ss += modStruct_to_s(i.makeModStruct(i))} ss += "\n#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" update_name @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each{|i| @class_struct1.childs << i.makeModStruct(i,@class_struct1)} open(filepath,"w") {|f| f.write ss} end def run_editor_clicked unless @workingfile then messageBox *FDMsgItems::SaveBeforeEdit return end if @modified > 0 save1(@workingfile) unless @project_type == :mono update_proj_clicked end ed = IsWindow.call(@hwndEd) if @hwndEd if ! ed || ed == 0 then fpath = @workingfile.sub(/_frm_(.+\.rb)/,'\1') @hinstance = ShellExecute.call(0,"open",$editor, "\"#{fpath}\"", nil,1) @editorStarting = true else SetForegroundWindow.call(@hwndEd) end end def show_editor ed = IsWindow.call(@hwndEd) if @hwndEd SetForegroundWindow.call(@hwndEd) if ed && (ed != 0) end def getModulesSet(cnt) #obsolete st = Set[] unless cnt.is_a? VRForm ps = get_parents_str(cnt) st << "Cntn#{ps}" st << "Extn#{ps}_#{cnt.name}" unless cnt.respond_to?(:addControl) || cnt.modules.empty? end cnt.controls.each{|i,c| if c.respond_to? :addControl then st = st + getModulesSet(c) end st << "Extn#{ps}_#{c.name}" unless c.is_a?(FDCoverPanel)||c.respond_to?(:addControl) || (c.modules.empty? && (c.owndraw==0)) } st end def update_proj_clicked n=messageBox FDMsgItems::SaveFromEditor[0], FDMsgItems::SaveFromEditor[0] + "#{@workingfile}",0x31 return if n > 1 if @project_type == :mono update_proj_mono else update_proj end end def update_name def up1(cnt) cnt.oldname = cnt.name if cnt.respond_to? :addControl cnt.controls.each{|i,v| up1(v)} end end @forms.each{|i| up1(i)} end def update clin = 0 compare_struct = lambda do |c1,c2,lv| a = []; s=""; lin=0 c1.childs.each{|i| if (j=c2.find(i.oldname)) && j.sline then @_a_buffer2[j.sline,1][0].sub!(/#{j.oldname}.*$/, i.name+" "*((62-lv*2-i.name.size)>0 ? (62-lv*2-i.name.size) : 2)+ FDSources::TagOfFD) compare_struct.call(i,j,lv+1) else a << i end } a.each{|i| s << modStruct_to_s(i,lv) } lin = c2.tline ? c2.tline : c2.eline lin = 0 unless lin clin += s.count("\n") if @_dde_line_no > lin @_a_buffer2[lin,1][0][0,0] = s end class_struct2 = ModStruct.new(nil,nil,nil) @forms.each{|i| class_struct2.childs << i.makeModStruct(i,class_struct2)} current=@class_struct1 in_rd=nil not_find=nil @_a_buffer2.each_with_index{|lin,idx| if in_rd && !(lin =~ /^=end/) then next else in_rd=false end case lin when /^=begin/ in_rd=true;next when /^\s*class\s+([A-Z][a-zA-z0-9_]*)\s+#{FDSources::TagOfFD}$/ current.tline = idx-@_a_buffer2.size unless current.tline unless c = current.find($1) then c = ModStruct.new($1,$1,current) current.childs << c end current = c current.sline = idx-@_a_buffer2.size when /^\s*end\s+#{FDSources::TagOfFD}$/ current.eline = idx-@_a_buffer2.size current = current.parent else end } compare_struct.call(class_struct2,@class_struct1,0) update_name @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each{|i| @class_struct1.childs << i.makeModStruct(i,@class_struct1)} r = @_a_buffer2.to_s @_dde_line_no += clin r end def update_proj_mono s="" unless @workingfile then saveas_proj_mono_clicked return end begin open(@workingfile,'r'){|f| s = f.read} rescue end s.scan(/^#{FDSources::BeginOfFD}.*^#{FDSources::EndOfFD}/m)[0] @buffer1=$` ? $` : "" @buffer2=$' ? $' : "" @_a_buffer2=@buffer2.empty? ? [""] : $'.to_a @buffer2=update s = @buffer1+make_fdvr_source+@buffer2 open(@workingfile,'w'){|f| f.write(s) $tstamp=f.stat.mtime.to_i clear_modified} end def update_proj unless @workingfile then unless saveas_proj_part_clicked then return end else save1(@workingfile) if @modified > 0 end fpath = @workingfile.sub(/_frm_(.+\.rb)/,'\1')#+$1 if File.exist?(fpath) then open(fpath,'r'){|f| @buffer2=f.read} @_a_buffer2=@buffer2.to_a @buffer2=update open(fpath,'w'){|f| f.write @buffer2 } show_editor else saveProject(fpath) show_editor end end def exit_clicked self_close end ### Insert ### def get_serial_name(s0) s=s0.sub(/\d*$/,'') n=1 while true break if @forms.select{|i| i.name == (s + n.to_s) }.empty? n += 1 end s + n.to_s end def insert_form(fname,klass) s=get_serial_name(fname) @forms<<create_form(@forms.last.x+20,@forms.last.y,500,400,s) @forms.last.name=s @forms.last.oldname=s @mainmenu.menu.insert(s,Start_Of_FrmID+@forms.size-1,@inspectShow.etc-1) @forms.last.etc=Start_Of_FrmID+@forms.size-1 window_menu_set_check(@forms.last.etc) @designfrm=@forms.last @designfrm.type_of_form = klass @designfrm.refreshInspect(nil) @designfrm.refreshCntName inc_modified end def insert_form_clicked insert_form("form",VRForm) @designfrm.refreshCntName @designfrm.refreshInspect(nil) end def insert_modelessform_clicked insert_form("mdlessdlg",VRModelessDialog) @designfrm.refreshCntName @designfrm.refreshInspect(nil) end def insert_modalform_clicked insert_form("modaldlg",VRModalDialog) @designfrm.refreshCntName @designfrm.refreshInspect(nil) end def change_to_form_clicked unless @designfrm == @forms[0] @designfrm.type_of_form = VRForm @designfrm.refreshCntName @designfrm.refreshInspect(@designfrm.focused) else messageBox *FDMsgItems::ThisIsMain end end def change_to_modeless_form_clicked unless @designfrm == @forms[0] @designfrm.type_of_form = VRModelessDialog @designfrm.refreshCntName @designfrm.refreshInspect(@designfrm.focused) else messageBox *FDMsgItems::ThisIsMain end end def change_to_modal_form_clicked unless @designfrm == @forms[0] @designfrm.type_of_form = VRModalDialog @designfrm.refreshCntName @designfrm.refreshInspect(@designfrm.focused) else messageBox *FDMsgItems::ThisIsMain end end def delete_this_form_clicked if @designfrm.etc==Start_Of_FrmID then messageBox *FDMsgItems::ThisIsMain return nil end r = messageBox(*FDMsgItems::OerationCannotUndo) if r==6 then @mainmenu.delete(@designfrm.etc) @forms.delete(@designfrm) @designfrm.close @forms[0].focus inc_modified end end def insert_form_from_file_clicked return unless fname = openFilenameDialog(["ruby scripts","*.rb"]) open(fname){|f| s=f.read messageBox *FDMsgItems::Noform unless read_form(s,@forms.size) } end def save_this_form_clicked return unless r = saveFilenameDialog(["ruby scripts","*.rb"]) s0 = FDSources::BeginOfFD + FDSources::Caution s = @designfrm.make_executive a=@designfrm.get_require a << 'vrdialog' if @designfrm.type_of_form <= VRDialogComponent a.uniq.each{|i| s0+="require 'vr/#{i}'\n"} open(r,"w"){|f| f.write(s0 + s + "\n" + FDSources::EndOfFD)} end ### Edit ### def doDelete_clicked @designfrm.deleteCont end def doCut_clicked @designfrm.cutCont end def doCopy_clicked @designfrm.copyCont end def doPaste_clicked @designfrm.pasteCont end def back_to_parent_clicked @designfrm.backToParent end def setFont_clicked @designfrm.ctrl_setFont end def setWinStyle_clicked @designfrm.setWinStyle end def setWSArray(style) a=[] ;s1 =$Style[:win].keys.dup s1.each{|i| s = i.dup ; a << [s.to_s,((($Style[:win])[i] & style) == 0 ? 0 : 1)] } a.sort end def wsArrat2int(a) r =0 a.each{|i| r = r | $Style[:win][i[0]]*i[1] } r end def examine_clicked @examinedlg.options["default"] = @designfrm.make_executive.gsub(/\n/,"\r\n") @examinedlg.move 20,20,328,220 @examinedlg.open(@designfrm) end def execute_clicked unless @running then @running=true @designfrm.visible = false @inspectfrm.visible = false s = nil s = @designfrm.make_executive s.sub!(/(^class +)(\w+)\s*<\s*\w+/,'\1TMP_\2 < VRForm;include ExecuteDesignfrm;') s1 = $2 s << "\nVRLocalScreen.showForm TMP_#{s1}" eval s self.class.module_eval "remove_const :TMP_#{s1}" end end def exitExec @running=false @designfrm.visible = true if @designfrm.alive? @inspectfrm.visible = true if @inspectfrm.alive? end def formShow_clicked unless @designfrm.alive? then new_designfrm @formShow.checked = true ; return end if @designfrm.visible? then @formShow.checked = @designfrm.visible = false else @formShow.checked = @designfrm.visible = true end end ## window ## def window_menu_set_check(id) @forms.each{|i| @mainmenu.menu.setChecked(i.etc,i.etc == id) } end def select_form(id) @forms.select{|i| i.etc==id}[0].focus end def inspectShow_clicked unless @inspectfrm.alive? then t=$ini.read("inspect","top",0).to_i l=$ini.read("inspect","left",0).to_i h=$ini.read("inspect","height",400).to_i w=$ini.read("inspect","width",140).to_i @inspectfrm.move(l,t,w,h) @inspectfrm.create.show @designfrm.refreshInspect(@designfrm.focused) @designfrm.refreshCntName @inspectShow.checked = true ; return end if @inspectfrm.visible? then @inspectShow.checked = @inspectfrm.visible = false else @inspectShow.checked = @inspectfrm.visible = true end end def prefer_clicked PreferDlg.arg={:editor=>$ini.read("settings","editor","notepad.exe"), :grid=>$ini.read("settings","span",8), :cygwin=>$ini.read("settings","LFOnly",'false')=='false' ? false : true, :font=>$ini.read("settings","font","MS UI Gothic,12"), :dock=>$ini.read("settings","dock",'true')=='true' ? true : false , :verbose=>$ini.read("settings","verbose",'true')=='true' ? true : false} if a1=@screen.modalform(self,0x02,PreferDlg) then grid, editor, cygwin, font, dock, verbose = *a1 g=grid.to_i if 1 < g && g < 100 then $ini.write("settings","span",@designfrm.span=g) @designfrm.refresh else messageBox *FDMsgItems::GridMustBe end $editor = editor $ini.write("settings","editor",$editor) $ini.write("settings","font","#{font}") $ini.write("settings","dock","#{dock}") $n = RUBY_PLATFORM =~ /\w+-cygwin/ && !cygwin ? "\r\n" : "\n" $ini.write("settings","LFOnly",cygwin) $ini.write("settings","verbose","#{verbose}") sx,sy,sw,sh=self.windowrect self_move(sx,sy) end end def show_reference_clicked HtmlHelp.call(hWnd,HTML_Help,HH_DISPLAY_TOC,0) end def show_topic_clicked s = "" if @designfrm.creation s = @designfrm.creation.klass.name elsif @designfrm.focused s = @designfrm.focused.class.name else s = "VRForm" end HtmlHelp.call(hWnd,HTML_Help,HH_HELP_CONTEXT,FDHelp::HH_hash[s]) end def show_SDK_topic_clicked return unless SDKDocument if (d=FDSDK::DE_Hash[@designfrm.focused.class.name]) SDKDocument.DisplayTopicFromURL FDSDK::DE_Prefix + d else SDKDocument.DisplayTopicFromURL( 'ms-help://MS.PSDK.1033/shellcc/platform/commctls/wincontrols.htm') end end def version_clicked VersionDlg.args = $Ver @screen.modalform(self,0x02,VersionDlg) end def gridState_clicked if @designfrm.enableGrid then @gridState.checked = @designfrm.enableGrid = false else @gridState.checked = @designfrm.enableGrid = true end @designfrm.refresh end def self_resize(w,h) @tab.move 0,0,w,58 if @tab end ### Tool ### def bmp2str_clicked str="" fi=[] if fi=openFilenameDialog([["bitmaps","*.bmp"]]) then fi.each do |f| bmp = SWin::Bitmap.loadFile(fi) str = bmp.dumpString end clb1=Clipboard.open(self.hWnd) clb1.setText(str) clb1.close @designfrm.messageBox FDMsgItems::Base64Finish end end def bmp2strz_clicked str="" fi=[] if fi=openFilenameDialog([["bitmaps","*.bmp"]]) then fi.each do |f| bmp = SWin::Bitmap.loadFile(fi) str = [Zlib::Deflate.deflate(Marshal.dump(bmp))].pack("m") end clb1=Clipboard.open(self.hWnd) clb1.setText(str) clb1.close @designfrm.messageBox FDMsgItems::Base64Finish end end ### event handler def self_move(x0,y0) if @inspectfrm && $ini.read("settings","dock",'true')=='true'then sx,sy,sw,sh = self.windowrect ix,iy,iw,ih=@inspectfrm.windowrect @inspectfrm.move(sx,sy+sh,iw,ih) end end def self_close if @dialog_running then messageBox @dialog_running + FDMsgItems::DialogRunning[0], FDMsgItems::DialogRunning[1],FDMsgItems::DialogRunning[2] return SKIP_DEFAULTHANDLER end if @_dde_mode then r = messageBox(*FDMsgItems::InDDEmode) if r == 6 then close else return SKIP_DEFAULTHANDLER end end if @modified > 0 then n = messageBox(*FDMsgItems::SaveBrforeExit) case n when 6 unless save_clicked then SKIP_DEFAULTHANDLER else close end when 2 SKIP_DEFAULTHANDLER when 7 close end else close end end def self_destroy SDKDocument.Close if SDKDocument HtmlHelp.call(0,nil,HH_UNINITIALIZE,@fd_cookie) $subwnd.close if $subwnd && $subwnd.alive? a=windowrect $ini.write "settings","language",$Lang $ini.write "mainform","left",a[0] $ini.write "mainform","top",a[1] $ini.write "mainform","width",a[2] $ini.write "mainform","height",a[3] @controls.clear $ini.flash end #popup menu def doDeletepop_clicked() doDelete_clicked() end def doCopypop_clicked() doCopy_clicked end def doPastepop_clicked() doPaste_clicked end def doCutpop_clicked() doCut_clicked end def back_to_parentpop_clicked() back_to_parent_clicked end ### Other methods def inhibit_paste_menu @doDelete.state = 0 @doCopy.state = 1 @doPaste.state = 1 @doCut.state = 1 @back_to_parent.state = 0 @doDeletepop.state = 0 @doCopypop.state = 1 @doPastepop.state = 1 @doCutpop.state = 1 @back_to_parentpop.state = 0 end def enable_paste_menu @doDelete.state = 0 @doCopy.state = 0 @doPaste.state = 0 @doCut.state = 0 @back_to_parent.state = 0 @doDeletepop.state = 0 @doCopypop.state = 0 @doPastepop.state = 0 @doCutpop.state = 0 @back_to_parentpop.state = 0 end def form_edit_menu @doDelete.state = 1 @doCopy.state = 1 @doPaste.state = 0 @doCut.state = 1 @back_to_parent.state = 1 @doDeletepop.state = 1 @doCopypop.state = 1 @doPastepop.state = 0 @doCutpop.state = 1 @back_to_parentpop.state = 1 end def update_menu(frm) @mainmenu.menu.modify(frm.etc,frm.name) end def inc_modified @modified += 1 if $RDE @sb1.setTextOf(1,"RDE Mode") if @sb1 modify_RDE_text else @sb1.setTextOf(1,FDMsgItems::Modified) if @sb1 end end def clear_modified @modified = 0 return if $RDE @sb1.setTextOf(1,"") if @sb1 end def modify_RDE_text return unless @rde_project cw = @rde_project lno = cw.row cno = cw.col data = cw.text data, ln = modify_project_buffer(data,lno) cw.text = data cw.row = ln cw.col = cno end def modify_project_buffer(data, org_line_no) line_no = org_line_no if @project_type == :mono data.scan(/^#{FDSources::BeginOfFD}.*^#{FDSources::EndOfFD}/m)[0] buffer1=$` ? $` : "" buffer2=$' ? $' : "" form_lin_count = $& ? $&.count("\n") : 0 line_count1 = buffer1.count("\n") line_count2 = buffer2.count("\n") if line_no <= line_count1 state = -1 line_no = 0 elsif (n = line_no-form_lin_count-line_count1) >= 0 state=1 line_no = n else state=0 line_no = 0 end a_buffer = $'.to_a a_buffer = [''] if a_buffer2.empty? buffer2 = update_project_buffer(a_buff,line_no) if @_new_project then result = "#! ruby -Ks\n" + buffer1 + make_fdvr_source unless $ini.read("settings","verbose","true")=="false" result += FDSources::Follows else result += "\n" end result += buffer2+ "#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" @_new_project = nil else s = make_fdvr_source if state < 0 n = line_count1 elsif state == 0 n = line_count1 + s.count("\n") else n = line_count1 + s.count("\n") + line_no end result = buffer1 + s + buffer2 line_no = n end else result ="" buffer2 = "" a_buffer = data.to_a a_buffer = [''] if a_buffer.empty? buffer2, line_no = update_project_buffer(a_buffer,line_no) save1(@workingfile) if @_new_project result = "require '#{File.basename(@workingfile)}'\n\n"+ buffer2 + "#{FDSources::StartOfForm}#{@forms[0].name.capitalize1}\n" @_new_project = nil else result = buffer2.to_s end end [result, line_no] end def update_project_buffer(a_buffer,line_no) clin = 0 compare_struct = lambda do |c1,c2,lv| a = []; s=""; lin=0 c1.childs.each{|i| if (j=c2.find(i.oldname)) && j.sline then a_buffer[j.sline,1][0].sub!(/#{j.oldname}.*$/, i.name+" "*((62-lv*2-i.name.size)>0 ? (62-lv*2-i.name.size) : 2)+ FDSources::TagOfFD) compare_struct.call(i,j,lv+1) else a << i end } a.each{|i| s << modStruct_to_s(i,lv) } lin = c2.tline ? c2.tline : c2.eline lin = 0 unless lin clin += s.count("\n") if line_no > lin a_buffer[lin,1][0][0,0] = s end class_struct2 = ModStruct.new(nil,nil,nil) @forms.each{|i| class_struct2.childs << i.makeModStruct(i,class_struct2)} current=@class_struct1 in_rd=nil not_find=nil a_buffer.each_with_index{|lin,idx| if in_rd && !(lin =~ /^=end/) then next else in_rd=false end case lin when /^=begin/ in_rd=true;next when /^\s*class\s+([A-Z][a-zA-z0-9_]*)\s+#{FDSources::TagOfFD}/ current.tline = idx-a_buffer.size unless current.tline unless c = current.find($1) then c = ModStruct.new($1,$1,current) current.childs << c end current = c current.sline = idx-a_buffer.size when /^\s*end\s+#{FDSources::TagOfFD}/ current.eline = idx-a_buffer.size current = current.parent else end } compare_struct.call(class_struct2,@class_struct1,0) update_name @class_struct1 = ModStruct.new(nil,nil,nil) @forms.reverse_each{|i| @class_struct1.childs << i.makeModStruct(i,@class_struct1)} r = a_buffer.to_s [r,clin + line_no] end def sorry messageBox FDMsgItems::SORRY end end <file_sep>#require 'vr/vrcontrol' #require 'vr/vrcomctl' require 'vr/vrrichedit' require 'vr/vrmmedia' require 'vr/vrtooltip' module FDSDK DE_Prefix = 'ms-help://MS.PSDK.1033/' DE_Hash={ 'VRButton' => 'shellcc/platform/commctls/buttons/buttons.htm', 'VRCheckbox' => 'shellcc/platform/commctls/buttons/buttontypesandstyles.htm#check_boxes', 'VRCombobox' => 'shellcc/platform/commctls/comboboxes/comboboxes.htm', 'VRCommonDialog' => 'winui/winui/windowsuserinterface/userinput/commondialogboxlibrary.htm', 'VREdit' => 'shellcc/platform/commctls/editcontrols/editcontrols.htm', 'VREditCombobox' => 'shellcc/platform/commctls/comboboxes/comboboxes.htm', 'VRGroupbox' => 'shellcc/platform/commctls/buttons/buttontypesandstyles.htm#group_boxes', 'VRListbox' => 'shellcc/platform/commctls/listboxes/listboxes.htm', 'VRListview' => 'shellcc/platform/commctls/listview/reflist.htm', 'VRMediaView' => 'multimed/vfwstart_8ld1.htm', 'VRMenu' => 'winui/winui/windowsuserinterface/resources/menus.htm', 'VRProgressbar' => 'shellcc/platform/commctls/progbar/reflist.htm', 'VRRadiobutton' => 'shellcc/platform/commctls/buttons/buttontypesandstyles.htm#radio_buttons', 'VRRebar' => 'shellcc/platform/commctls/rebar/reflist.htm', 'VRRichedit' => 'shellcc/platform/commctls/richedit/richeditcontrols.htm', 'VRScrollbar' => 'shellcc/platform/commctls/scrollbars/scrollbars.htm', 'VRStatic' => 'shellcc/platform/commctls/staticcontrols/staticcontrols.htm', 'VRStatusbar' => 'shellcc/platform/commctls/status/reflist.htm', 'VRTabbedPanel' => 'shellcc/platform/commctls/tab/reflist.htm', 'VRTabControl' => 'shellcc/platform/commctls/tab/reflist.htm', 'VRText' => 'shellcc/platform/commctls/editcontrols/editcontrols.htm', 'VRToolbar' => 'shellcc/platform/commctls/toolbar/reflist.htm', 'VRTooltip' => 'shellcc/platform/commctls/tooltip/reflist.htm', 'VRTrackbar' => 'shellcc/platform/commctls/trackbar/reflist.htm', 'VRTreeview' => 'shellcc/platform/commctls/treeview/reflist.htm', 'VRUpdown' => 'shellcc/platform/commctls/updown/reflist.htm' } CTL_STYLE_DOC = { 'VRButton' => 'shellcc/platform/commctls/buttons/buttonreference/buttonstyles.htm', 'VRCheckbox' => 'shellcc/platform/commctls/buttons/buttonreference/buttonstyles.htm', 'VRCombobox' => 'shellcc/platform/commctls/comboboxes/comboboxreference/comboboxstyles.htm', 'VREdit' => 'shellcc/platform/commctls/editcontrols/editcontrolreference/editcontrolstyles.htm', 'VREditCombobox' => 'shellcc/platform/commctls/editcontrols/editcontrolreference/editcontrolstyles.htm', 'VRGroupbox' => 'shellcc/platform/commctls/buttons/buttonreference/buttonstyles.htm', 'VRListbox' => 'shellcc/platform/commctls/listboxes/listboxreference/listboxstyles.htm', 'VRListview' => 'shellcc/platform/commctls/listview/styles.htm', #VRMediaView=>'', 'VRProgressbar' => 'shellcc/platform/commctls/progbar/styles.htm', 'VRRadiobutton' => 'shellcc/platform/commctls/buttons/buttonreference/buttonstyles.htm', 'VRRebar' => 'shellcc/platform/commctls/rebar/styles.htm', 'VRRichedit' => 'shellcc/platform/commctls/richedit/richeditcontrols/richeditcontrolreference/richeditconstants/richeditcontrolstyles.htm', 'VRScrollbar' => 'shellcc/platform/commctls/scrollbars/scrollbarreference/scrollbarcontrolstyles.htm', 'VRStatic' => 'ms-help://MS.PSDK.1033/shellcc/platform/commctls/staticcontrols/staticcontrolreference/staticcontrolstyles.htm', 'VRStatusbar' => 'shellcc/platform/commctls/status/styles.htm', 'VRTabbedPanel' => '', 'VRTabControl' => 'shellcc/platform/commctls/tab/styles.htm', 'VRText' => '/shellcc/platform/commctls/editcontrols/editcontrolreference/editcontrolstyles.htm', 'VRToolbar' => 'shellcc/platform/commctls/toolbar/styles.htm', 'VRTooltip' => 'shellcc/platform/commctls/tooltip/styles.htm', 'VRTrackbar' => 'shellcc/platform/commctls/trackbar/styles.htm', 'VRTreeview' => 'shellcc/platform/commctls/treeview/styles.htm', 'VRUpdown' => 'shellcc/platform/commctls/updown/styles.htm' } WND_STYLE_DOC = 'winui/winui/windowsuserinterface/windowing/windows/windowreference/WindowStyles.htm' WND_EXSTYLE_DOC = 'winui/winui/windowsuserinterface/windowing/windows/windowreference/windowfunctions/createwindowex.htm' CTL_EX_STYLE_DOC = { 'VRListview' => 'shellcc/platform/commctls/listview/ex_styles.htm', 'VRToolbar' => 'shellcc/platform/commctls/toolbar/ex_styles.htm', 'VRTabControl' => 'shellcc/platform/commctls/tab/ex_styles.htm', 'VRTabbedPanel' => 'shellcc/platform/commctls/tab/ex_styles.htm' } end <file_sep>#! ruby -Ks # # FormDesigner.rb # Programmed by <EMAIL> # Copyright 2001-2004 <NAME> $KCODE = 's' $program_dir = File.dirname(File.expand_path($0)) $:.unshift($program_dir) require 'fdvr/fdmain' require 'fdvr/fdcontroldesign' require 'fdvr/fdinspect' require 'fdvr/fddialogs' VRLocalScreen.start FDControlSelection <file_sep>#Win32API require 'Win32API' module User32 GetDC = Win32API.new('User32', 'GetDC', 'L', 'L') IsWindow = Win32API.new('user32','IsWindow','L','L') GetForegroundWindow = Win32API.new('user32','GetForegroundWindow','V','L') SetForegroundWindow = Win32API.new('user32','SetForegroundWindow','L','L') SetActiveWindow = Win32API.new('user32','SetActiveWindow','L','L') DestroyWindow = Win32API.new('user32','DestroyWindow','L','L') SendDlgItemMessage=Win32API.new('user32','SendDlgItemMessage','LLLLL','L') SendDlgItemMessage2=Win32API.new('user32','SendDlgItemMessage','LLLLP','L') DrawFrameControl=Win32API.new('user32','DrawFrameControl','LPII','I') SetWindowPos = Win32API.new('user32','SetWindowPos','LLLLLLL','L') end module GDI32 GetTextFace=Win32API.new('GDI32','GetTextFace','LLP','L') CreateRectRgn = Win32API.new('GDI32','CreateRectRgn','LLLL','L') SelectClipRgn = Win32API.new('GDI32','SelectClipRgn','LL','L') CreatePen = Win32API.new('GDI32', 'CreatePen', 'LLL', 'L') CreateBrush = Win32API.new('GDI32', 'CreateSolidBrush', 'L', 'L') SelectObject = Win32API.new('GDI32', 'SelectObject', 'LL', 'L') DeleteObject = Win32API.new('GDI32', 'DeleteObject', 'L', 'L') SetROP2 = Win32API.new('GDI32','SetROP2','LL','L') MoveTo = Win32API.new('GDI32', 'MoveToEx', 'LLLP', 'V') LineTo = Win32API.new('GDI32', 'LineTo', 'LLL', 'V') Rectangle = Win32API.new('GDI32', 'Rectangle', 'LLLLL', 'V') SetBkMode = Win32API.new("GDI32", "SetBkMode", ['L']*2, 'L') TextOut = Win32API.new("GDI32","TextOut",['L','L','L','P','L'],'L') end module Kernel32 end module Shell32 ShellExecute = Win32API.new('shell32','ShellExecute','LPPPPI','L') end module Hhctrl HtmlHelp=Win32API.new('hhctrl.ocx',"HtmlHelpA","LPLP","L") end
5a529a4346eea03307bea9b901235efe5556414d
[ "Markdown", "Text", "Ruby" ]
18
Ruby
rynan4818/formdesigner
cfb6257948f0f4c2b29d0bb520378cb3c2da7eac
992269b084ea898569a81c7041bf626183d7e72e
refs/heads/master
<repo_name>JRikken/youbot_markers<file_sep>/src/send_markers.cpp #include <vector> #include <string> #include <sstream> #include <fstream> #include <ros/ros.h> #include <tf/tf.h> #include <move_base_msgs/MoveBaseAction.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Quaternion.h> #include <actionlib/client/simple_action_client.h> typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient; int main(int argc, char** argv) { ros::init(argc, argv, "goal_queue"); if (argc < 2 || argc > 2) { printf("Usage: send_markers file_name\n"); return -1; } std::string file_name = std::string(argv[1]); ROS_INFO("Goal Queue Started."); int goal_itr = 0; bool ac_online = false; ros::NodeHandle n; MoveBaseClient ac("/move_base", true); if(ac.waitForServer(ros::Duration(10.0))) { ROS_INFO("Contacted move_base action server"); ac_online = true; } else ROS_INFO("Unable to contact move_base action server."); ros::Rate r(1); std::vector<std::string> targets; std::string line; std::ifstream myfile (file_name.c_str()); if (myfile.is_open()) { while ( getline (myfile,line) ) { //cout << line << '\n'; targets.push_back(line); } myfile.close(); } else { std::cout << "Unable to open file" << std::endl;; return -1; } /*double x, y, z, qx, qy, qz, qw; for (unsigned int i=0; i < targets.size(); i++) { std::string tmp = targets.at(i); std::stringstream ss(tmp); std::string str_x, str_y, str_z, str_qx, str_qy, str_qz, str_qw; ss >> str_x >> str_y >> str_z >> str_qx >> str_qy >> str_qz >> str_qw; x = atof(str_x.c_str()); y = atof(str_y.c_str()); z = atof(str_z.c_str()); qx = atof(str_qx.c_str()); qy = atof(str_qy.c_str()); qz = atof(str_qz.c_str()); qw = atof(str_qw.c_str()); std::cout << x << " " << y << " " << z << " " << qx << " " << qy << " " << qz << " " << qw << std::endl; }*/ while(ros::ok() && ac_online && goal_itr < targets.size()) { double x, y, z, qx, qy, qz, qw; std::string tmp = targets.at(goal_itr); std::stringstream ss(tmp); std::string str_x, str_y, str_z, str_qx, str_qy, str_qz, str_qw; ss >> str_x >> str_y >> str_z >> str_qx >> str_qy >> str_qz >> str_qw; x = atof(str_x.c_str()); y = atof(str_y.c_str()); z = atof(str_z.c_str()); qx = atof(str_qx.c_str()); qy = atof(str_qy.c_str()); qz = atof(str_qz.c_str()); qw = atof(str_qw.c_str()); move_base_msgs::MoveBaseGoal goal; //geometry_msgs::Pose pose(geometry_msgs::Point(x, y, z), geometry_msgs::Quaternion(qx, qy, qz, qw)); //geometry_msgs::Pose pose; /*geometry_msgs::Vector3 point;// = tf::Vector3(x, y, z); geometry_msgs::Quaternion q;// = tf::Quaternion(qx, qy, qz, qw); pose.position = point; pose.orientation = q;*/ geometry_msgs::PoseStamped pose; pose.header.stamp = ros::Time::now(); pose.header.frame_id = "/map"; pose.pose.position.x = x; pose.pose.position.y = y; pose.pose.position.z = z; pose.pose.orientation.x = qx; pose.pose.orientation.y = qy; pose.pose.orientation.z = qz; pose.pose.orientation.w = qw; goal.target_pose = pose; goal.target_pose.header.stamp = ros::Time::now(); ROS_INFO("Sending Goal nr: %d / %lu", goal_itr + 1, targets.size()); std::cout << "Goal data: " << std::endl; std::cout << x << " " << y << " " << z << " " << qx << " " << qy << " " << qz << " " << qw << std::endl; ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("Goal reached succesfully."); else ROS_INFO("Reaching the goal has failed."); ros::Duration(5).sleep(); if(goal_itr++ == targets.size()){ goal_itr = 0; break; } ROS_INFO("Moving to goal nr: %d / %lu", goal_itr + 1, targets.size()); ros::spinOnce(); r.sleep(); } ROS_INFO("Stop sending targets..."); return 0; } <file_sep>/src/teach_markers.cpp #include <cstdio> #include <tf/transform_listener.h> #include <ros/ros.h> #include <iostream> #include <fstream> #define _USE_MATH_DEFINES class echoListener { public: tf::TransformListener tf; //constructor with name echoListener() { }; ~echoListener() { }; private: }; int main(int argc, char ** argv) { //Initialize ROS ros::init(argc, argv, "tf_echo", ros::init_options::AnonymousName); // Allow 1 if (argc < 3 || argc > 3) { printf("Usage: teach_markers base_name file_name\n"); return -1; } ros::NodeHandle nh; //Instantiate a local listener echoListener echoListener; std::string base_name = std::string(argv[1]); std::string file_name = std::string(argv[2]); std::string output; unsigned int iter = 0; double x, y, r; // Wait for up to one second for the first transforms to become avaiable. echoListener.tf.waitForTransform("/map", "/base_footprint", ros::Time(), ros::Duration(1.0)); //Nothing needs to be done except wait for a quit //The callbacks withing the listener class //will take care of everything while(nh.ok()) { std::stringstream s; s << iter; std::string converted(s.str()); std::string target = base_name + converted; try { tf::StampedTransform echo_transform; echoListener.tf.lookupTransform("/map", target, ros::Time(), echo_transform); std::cout.precision(3); std::cout.setf(std::ios::fixed,std::ios::floatfield); double yaw, pitch, roll; echo_transform.getBasis().getRPY(roll, pitch, yaw); tf::Quaternion q = echo_transform.getRotation(); tf::Vector3 v = echo_transform.getOrigin(); std::cout << "From: " << "/map to: " << target << std::endl; std::cout << "Raw data:" << std::endl; std::cout << "- Translation: [" << v.getX() << ", " << v.getY() << ", " << v.getZ() << "]" << std::endl; std::cout << "- Rotation: in Quaternion [" << q.getX() << ", " << q.getY() << ", " << q.getZ() << ", " << q.getW() << "]" << std::endl << " in RPY (radian) [" << roll << ", " << pitch << ", " << yaw << "]" << std::endl << " in RPY (degree) [" << roll*180.0/M_PI << ", " << pitch*180.0/M_PI << ", " << yaw*180.0/M_PI << "]" << std::endl << std::endl; std::cout << "Normalized data:" << std::endl; tf::Quaternion q_norm; q_norm.setRPY(0.0, 0.0, yaw); std::cout << "- Translation: [" << v.getX() << ", " << v.getY() << ", " << 0.0 << "]" << std::endl; std::cout << "- Rotation: in Quaternion [" << q_norm.getX() << ", " << q_norm.getY() << ", " << q_norm.getZ() << ", " << q_norm.getW() << "]" << std::endl; x = v.getX(); y = v.getY(); r = yaw; } catch(tf::TransformException& ex) { std::cout << "Failure at "<< ros::Time::now() << std::endl; std::cout << "Exception thrown:" << ex.what()<< std::endl; } std::cout << "NESW for orientation to store, Q to quit anything else to skip" << std::endl; char c; std::cin.get(c); if(c == 'n'){ std::cout << "NORTH" << std::endl; tf::Quaternion q; q.setRPY(0.0, 0.0, r); std::stringstream s; s << " " << x << " " << y << " " << 0 << " " << q.getX() << " " << q.getY() << " " << q.getZ() << " " << q.getW() << std::endl; std::string converted(s.str()); std::string target = base_name + converted; output += converted; iter++; } else if(c == 'e'){ std::cout << "EAST" << std::endl; tf::Quaternion q; q.setRPY(0.0, 0.0, r - (M_PI/2.0)); std::stringstream s; s << " " << x << " " << y << " " << 0 << " " << q.getX() << " " << q.getY() << " " << q.getZ() << " " << q.getW() << std::endl; std::string converted(s.str()); std::string target = base_name + converted; output += converted; iter++; } else if(c == 's'){ std::cout << "SOUTH" << std::endl; tf::Quaternion q; q.setRPY(0.0, 0.0, r + M_PI); std::stringstream s; s << " " << x << " " << y << " " << 0 << " " << q.getX() << " " << q.getY() << " " << q.getZ() << " " << q.getW() << std::endl; std::string converted(s.str()); std::string target = base_name + converted; output += converted; iter++; } else if(c == 'w'){ std::cout << "WEST" << std::endl; tf::Quaternion q; q.setRPY(0.0, 0.0, r + (M_PI/2.0)); std::stringstream s; s << " " << x << " " << y << " " << 0 << " " << q.getX() << " " << q.getY() << " " << q.getZ() << " " << q.getW() << std::endl; std::string converted(s.str()); std::string target = base_name + converted; output += converted; iter++; } else if(c == 'q'){ std::cout << "QUIT" << std::endl; std::ofstream myfile (file_name.c_str()); if (myfile.is_open()) { myfile << output; myfile.close(); } else std::cout << "Unable to open file"; break; } else{ std::cout << "SKIP" << std::endl; } } return 0; }; <file_sep>/README.md # youbot_markers Code for the 2016 navigation assignment (Fontys minor AR)
86ca205812fc7f13686ea0b3ac8187892e3c2245
[ "Markdown", "C++" ]
3
C++
JRikken/youbot_markers
5b529fed4f96fceaff45993084469ba4121e233c
ead0d449bba1c95ff2325404789fbbf2fc6826a6
refs/heads/master
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 25 10:42:24 2018 @author: ktai12 """ import numpy as np import keras BEFORE_NUMBER = 10 BATCH_SIZE = 512 STEPS = 100000 LOG_STEP = 1000 start_point = np.random.uniform(100, 1000, (BATCH_SIZE,)) difference = np.random.uniform(1, 100, (BATCH_SIZE,)) samples_x = np.array([start_point + difference * i for i in range(BEFORE_NUMBER)]).transpose([1, 0]) samples_y = [start_point + BEFORE_NUMBER * difference] from keras.layers import Dense,LeakyReLU model=keras.Sequential() model.add(Dense(1000,input_shape=[BEFORE_NUMBER,])) model.add(LeakyReLU()) model.add(Dense(1000)) model.add(LeakyReLU()) model.add(Dense(1)) model.compile(optimizer='rmsprop',loss='mse') hist=model.fit(samples_x,samples_y,epochs=STEPS,validation_split=0.2) diff=np.array([150,200,300]) s_point=np.array([100000,200000,300000]) test_x=np.array([s_point + diff * i for i in range(BEFORE_NUMBER)]).transpose([1, 0]) test_y=[s_point + BEFORE_NUMBER * diff] model.load_weights('weights') model.predict(test_x) <file_sep>""" Multilayer Perceptron. A Multilayer Perceptron (Neural Network) implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/). Links: [MNIST Dataset](http://yann.lecun.com/exdb/mnist/). Author: <NAME> Project: https://github.com/aymericdamien/TensorFlow-Examples/ """ # ------------------------------------------------------------------ # # THIS EXAMPLE HAS BEEN RENAMED 'neural_network.py', FOR SIMPLICITY. # # ------------------------------------------------------------------ #this is to check branch from __future__ import print_function # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) import tensorflow as tf sess=tf.InteractiveSession() # Parameters learning_rate = 0.01 training_epochs = 15 batch_size = 100 display_step = 1 # Network Parameters n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2_1 = 128 # 2nd layer number of neurons n_hidden_2_2 = 128 # 2nd layer number of neurons n_hidden_3_1 = 128 # 2nd layer number of neurons n_hidden_3_2 = 128 n_hidden_3 = 256 n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input X = tf.placeholder("float", [None, n_input]) Y = tf.placeholder("float", [None, n_classes]) # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2_1': tf.Variable(tf.random_normal([128, n_hidden_2_1])), 'h2_2': tf.Variable(tf.random_normal([128, n_hidden_2_2])), 'h3_1': tf.Variable(tf.random_normal([128, 128])), 'h3_2': tf.Variable(tf.random_normal([128,128])), 'out': tf.Variable(tf.random_normal([256, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2_1': tf.Variable(tf.random_normal([n_hidden_2_1])), 'b2_2': tf.Variable(tf.random_normal([n_hidden_2_2])), 'b3': tf.Variable(tf.random_normal([n_hidden_3])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Create model def multilayer_perceptron(x): # Hidden fully connected layer with 256 neurons layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['b1'])) # Hidden fully connected layer with 256 neurons tmp1=layer_1[:,:128] tmp2=layer_1[:,128:] layer_2_1 = tf.nn.relu(tf.add(tf.matmul(tmp1, weights['h2_1']), biases['b2_1'])) layer_2_2 = tf.nn.relu(tf.add(tf.matmul(tmp2, weights['h2_2']), biases['b2_2'])) layer_3_1 = tf.nn.relu(tf.matmul(layer_2_1, weights['h3_1'])) layer_3_2 = tf.nn.relu(tf.matmul(layer_2_2, weights['h3_2'])) merge=tf.concat([layer_3_1,layer_3_2],-1)+biases['b3'] # Output fully connected layer with a neuron for each class out_layer = tf.matmul(merge, weights['out']) + biases['out'] return out_layer # Construct model logits = multilayer_perceptron(X) # Define loss and optimizer loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2( logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # Initializing the variables init = tf.global_variables_initializer() #with tf.Session() as sess: sess.run(init) pred = tf.nn.softmax(logits) # Apply softmax to logits correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c ,acc= sess.run([train_op, loss_op,accuracy], feed_dict={X: batch_x, Y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost),"acc={0}".format(acc)) print("Optimization Finished!") # Test model # Calculate accuracy print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels})) <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 22 17:18:19 2018 @author: ktai12 """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt sess=tf.InteractiveSession() from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) #convolution 압축을 확인하자! #압축률이 다른 5장의 사진 img=mnist.train.images[0].reshape(28,28) #original-28*28 plt.imshow(img) plt.title('original') W=tf.Variable(tf.random_normal([3,3,1,1],stddev=0.01)) img=img.reshape(-1,28,28,1) conv2d=tf.nn.conv2d(img,W,strides=[1,1,1,1],padding="VALID") sess.run(tf.global_variables_initializer()) conv2d_img1=conv2d.eval() conv2d_img1.shape #convolution once - 26*26 img1=conv2d_img1.reshape(26,26) plt.imshow(img1) plt.title('once') #convolution twice conv2d=tf.nn.conv2d(conv2d_img1,W,strides=[1,1,1,1],padding="VALID") conv2d_img2=conv2d.eval() conv2d_img2.shape img2=conv2d_img2.reshape(24,24) plt.imshow(img2) plt.title('once') tmp=img for i in range(10): a=tmp.shape[0] tmp=tmp.reshape(-1,a,a,1) conv2d=tf.nn.conv2d(tmp,W,strides=[1,1,1,1],padding="VALID") conv2d_img=conv2d.eval() k=conv2d_img.shape[1] tmp=conv2d_img.reshape(k,k) plt.imshow(tmp) plt.title("{0}*{0} size".format(k)) plt.show()<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 22 16:08:22 2018 @author: ktai12 """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) img=mnist.train.images[0].reshape(28,28) plt.imshow(img,cmap="gray") sess=tf.InteractiveSession() img=img.reshape(-1,28,28,1) #몇 장 가져오는지 모를때 W1=tf.Variable(tf.random_normal([3,3,1,5],stddev=0.01)) conv2d=tf.nn.conv2d(img,W1,strides=[1,1,1,1],padding="SAME") print(conv2d) sess.run(tf.global_variables_initializer()) conv2d_img=conv2d.eval() print("Before size : ",conv2d_img.shape) conv2d_img=np.swapaxes(conv2d_img,0,3) print("After size : ",conv2d_img.shape) for i,one_img in enumerate(conv2d_img): print("one_img shape= : ", one_img.shape) plt.subplot(2,3,i+1),plt.imshow(one_img.reshape(28,28),cmap='gray')<file_sep># KT-AI-academy <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 22 14:21:43 2018 @author: ktai12 """ #%matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt sess=tf.InteractiveSession() image=np.array([[[[4],[3]],[[2],[1]]]], dtype=np.float32) pool=tf.nn.max_pool(image,ksize=[1,2,2,1], strides=[1,1,1,1],padding="VALID") #print("image.shape= :",image.shape) print("pool.shape= : ",pool.shape) print(pool.eval()) #plt.imshow(image.reshape(3,3),cmap='Greys') #weight=tf.constant([[[[1.,-10.,-1.]],[[1.,-10.,-1.]]], # [[[1.,-10.,-1.]],[[1.,-10.,-1.]]]]) # #print("weight.shape",weight.shape) # ##VALID-> 0패딩 안씀. 이미지가 줄어드는 한이 있어도 유효하게 가져가겠다. #SAME도 있음 # #conv2d=tf.nn.conv2d(image,weight,strides=[1,1,1,1],padding="SAME") # #conv2d_img=conv2d.eval() #print("conv2d_img.shape",conv2d_img.shape) # #conv2d_img=np.swapaxes(conv2d_img,0,3) # #for i,one_img in enumerate(conv2d_img): # print(one_img.reshape(3,3)) # plt.subplot(1,3,i+1) # plt.imshow(one_img.reshape(3,3),cmap='gray')
780fa3fed7e5890f26f9c952f10cefbacfa6e09a
[ "Markdown", "Python" ]
6
Python
jsrimr/code_during_KTaiacadmey
ab98b1613d9cb8ca77cd2462e0a42664b71bd758
d508303417fe0916f98f7cd65c6521adb0a933fa
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TeamProjKateEgor { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Context _context; Manager manager; public MainWindow() { InitializeComponent(); _context = new Context(); Company company = new Company {Name = "RGD", Country = "Italy"}; _context.Trips.Add(new Trip { DepartureTime = new DateTime(2014, 07, 23), ArrivalTime = new DateTime(2014, 07, 24), ArrivalStation = "Moscow", Company = company }); _context.SaveChanges(); manager = new Manager(); addButton.IsEnabled = false; deleteButton.IsEnabled = false; queryButton.IsEnabled = false; } private int SortByTripTitle(Trip t1, Trip t2) { return t1.Title.CompareTo(t2.Title); } private int SortByCompanyName(Trip t1, Trip t2) { return t1.Company.Name.CompareTo(t2.Company.Name); } private int SortByDepartureTime(Trip t1, Trip t2) { return t1.DepartureTime.CompareTo(t2.DepartureTime); } private void menuExit_Click(object sender, RoutedEventArgs e) { Close(); } private void menuSort_Click(object sender, RoutedEventArgs e) { if (showButton.IsEnabled == false) { if (sender == menuTripTitle) manager.SortByField(SortByTripTitle); if (sender == menuCompanyName) manager.SortByField(SortByCompanyName); if (sender == menuDepartureTime) manager.SortByField(SortByDepartureTime); this.DataContext = null; this.DataContext = manager.Trips; } else MessageBox.Show("Warning!", "Error", MessageBoxButton.OK, MessageBoxImage.Asterisk); } private void showButton_Click(object sender, RoutedEventArgs e) { this.DataContext = null; this.DataContext = manager.Trips; showButton.IsEnabled = false; addButton.IsEnabled = true; deleteButton.IsEnabled = true; queryButton.IsEnabled = true; } private void queryButton_Click(object sender, RoutedEventArgs e) { if ((dateLower.SelectedDate == null || dateUpper.SelectedDate == null) || dateUpper.SelectedDate < dateLower.SelectedDate) MessageBox.Show("Select dates by wright way!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); else { this.DataContext = manager.DbQuery(dateLower.SelectedDate.Value, dateUpper.SelectedDate.Value); showButton.IsEnabled = true; } } private void addButton_Click(object sender, RoutedEventArgs e) { AddWindow addingWindow = new AddWindow(); addingWindow.ShowDialog(); if (addingWindow.DialogResult.HasValue && addingWindow.DialogResult.Value) manager.AddNewItem(addingWindow.Trip, addingWindow.selection.SelectedIndex); this.DataContext = null; this.DataContext = manager.Trips; } private void deleteButton_Click(object sender, RoutedEventArgs e) { if (mainTable.SelectedIndex == -1) MessageBox.Show("Choose trip for deleting!", "Warning", MessageBoxButton.OK, MessageBoxImage.Asterisk); else { manager.RemoveSelectedItem(mainTable.SelectedIndex); this.DataContext = null; this.DataContext = manager.Trips; } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamProjKateEgor { public class Context : DbContext { public DbSet<Trip> Trips { get; set; } public DbSet<Company> Companies { get; set; } public Context() : base("RailwayDB") { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamProjKateEgor { public class Company { public int Id { get; set; } public string Name { get; set; } public string Country { get; set; } public Company() { } public Company(int id, string name, string country) { Id = id; Name = name; Country = country; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace TeamProjKateEgor { /// <summary> /// Interaction logic for AddWindow.xaml /// </summary> public partial class AddWindow : Window { private Trip _trip; public AddWindow() { InitializeComponent(); _trip = new Trip(); } private void AddButton_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrWhiteSpace(textBoxTripTitle.Text) || String.IsNullOrWhiteSpace(textBoxArrStation.Text) || datePickDeparture.SelectedDate == null || datePickArrival.SelectedDate == null || selection.SelectedIndex == -1) MessageBox.Show("Please, fill all fields.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); else { _trip.Title = textBoxTripTitle.Text; _trip.DepartureTime = datePickDeparture.SelectedDate.Value; _trip.ArrivalTime = datePickArrival.SelectedDate.Value; _trip.ArrivalStation = textBoxArrStation.Text; _trip.Company = null; DialogResult = true; } } public Trip Trip { get { return _trip; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamProjKateEgor { public class Manager { Context context; List<Trip> _trips; List<Company> _companies; public Manager() { context = new Context(); _trips = context.Trips.ToList(); _companies = context.Companies.ToList(); } public IEnumerable<Trip> DbQuery(DateTime d1, DateTime d2) { var query = from t in _trips where t.DepartureTime >= d1 && t.DepartureTime <= d2 select t; return query; } public void SortByField(Comparison<Trip> sorting) { _trips.Sort(sorting); context.SaveChanges(); } public void AddNewItem(Trip trip, int id) { trip.Company = _companies[id]; _trips.Add(trip); context.Trips.Add(trip); context.SaveChanges(); } public void RemoveSelectedItem(int index) { context.Trips.Remove(_trips[index]); _trips.RemoveAt(index); context.SaveChanges(); } public List<Trip> Trips { get { return _trips; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamProjKateEgor { public class Trip { public int Id { get; set; } public string Title { get; set; } public DateTime DepartureTime { get; set; } public DateTime ArrivalTime { get; set; } public string ArrivalStation { get; set; } public Company Company { get; set; } public Trip() { } public Trip(int id, string title, DateTime departureTime, DateTime arrivalTime, string arrivalStation, Company company) { Id = id; Title = title; DepartureTime = departureTime; ArrivalTime = arrivalTime; ArrivalStation = arrivalStation; Company = company; } } }
d0d360be9409791637ec2f906af2d7366be9ce4b
[ "C#" ]
6
C#
TeamProjectHSE/karnauh-plusheva
74ec8b8c91fb9b8dfd4449be647f44b1ba9ddce8
8a6819fc86d2c510cee5ffc45242a43b10baa6b4
refs/heads/master
<repo_name>bonuelc/AdHawkSmartTipMockup<file_sep>/SmartTips/JSONHandler.swift // // JSONManager.swift // SmartTips // // Created by <NAME> on 8/1/16. // Copyright © 2016 <NAME>. All rights reserved. // import Alamofire import SwiftyJSON class SmartTipJSONManager { static let getInstance = SmartTipJSONManager() var smartTips = [SmartTip]() private init() {} func loadArrayFromJSONurl(url: URLStringConvertible, completionHandler: () -> ()) { Alamofire.request(.GET, url).responseJSON { response in switch response.result { case .Success(let value): self.parseJSON(JSON(value)) case .Failure(let error): print(error) } completionHandler() } } func parseJSON(json: JSON) { smartTips = json[dataPath].arrayValue.flatMap { SmartTip(smartTip: $0) } smartTips.sortInPlace() } }<file_sep>/SmartTips/SmartTipColor.swift // // SmartTipColor.swift // SmartTips // // Created by <NAME> on 7/29/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class SmartTipColor { private init() {} class func greenColor() -> UIColor { return UIColor.init(red: 46.0/255.0, green: 224.0/255.0, blue: 136.0/255.0, alpha: 1.0) } class func redColor() -> UIColor { return UIColor.init(red: 237.0/255.0, green: 29.0/255.0, blue: 35.0/255.0, alpha: 1.0) } class func grayColor() -> UIColor { return UIColor.init(red: 144.0/255.0, green: 144.0/255.0, blue: 146.0/255.0, alpha: 1.0) } }<file_sep>/SmartTips/SmartTip.swift // // SmartTip.swift // SmartTips // // Created by <NAME> on 8/1/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import SwiftyJSON struct SmartTip { let provider: String let title: String let description: String var status: Status let creationDate: NSDate var expired: Bool = false init?(smartTip: JSON) { guard let p = smartTip[providerPath].string else { return nil } guard let t = smartTip[titlePath].string else { return nil } guard let d = smartTip[descriptionPath].string else { return nil } guard let statusInt = smartTip[statusPath].int, s = Status(rawValue: statusInt) else { return nil } let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" if let dateString = smartTip[createdAtDatePath].string, cDate = formatter.dateFromString(dateString) { creationDate = cDate } else { creationDate = NSDate() } // commented out b/c all sample data are expired // if let dateString = smartTip[expiresAtDatePath].string, expirationDate = formatter.dateFromString(dateString) { // if expirationDate < NSDate() { return nil } // } provider = p title = t description = d status = s } mutating func reject() { status = Status.Rejected } mutating func accept() { status = Status.Accepted } mutating func read() { status = Status.Read } } extension SmartTip: Equatable, Comparable { } func ==(lhs: SmartTip, rhs: SmartTip) -> Bool { return lhs.creationDate == rhs.creationDate } func <(lhs: SmartTip, rhs: SmartTip) -> Bool { return lhs.creationDate < rhs.creationDate } extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending }<file_sep>/SmartTips/JSONPaths.swift // // JSONPaths.swift // SmartTips // // Created by <NAME> on 7/29/16. // Copyright © 2016 <NAME>. All rights reserved. // import SwiftyJSON let dataPath: [JSONSubscriptType] = ["data"] let providerPath: [JSONSubscriptType] = ["relationships", "identity", "data", "provider"] let titlePath: [JSONSubscriptType] = ["attributes", "title"] let descriptionPath: [JSONSubscriptType] = ["attributes", "description"] let statusPath: [JSONSubscriptType] = ["attributes", "status"] let expiresAtDatePath: [JSONSubscriptType] = ["attributes", "expires_at"] let createdAtDatePath: [JSONSubscriptType] = ["attributes", "created_at"]<file_sep>/SmartTips/SmartTipViewController.swift // // SmartTipViewController.swift // SmartTips // // Created by <NAME> on 7/28/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import SwiftyJSON protocol SmartTipDelegate { func tipStatusSelectionDidFinish(controller: SmartTipViewController) } class SmartTipViewController: UIViewController { @IBOutlet weak var providerLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var rejectButton: UIButton! @IBOutlet weak var acceptButton: UIButton! @IBOutlet weak var okButton: UIButton! @IBOutlet weak var cancelButton: UIButton! var smartTip: SmartTip! var delegate: SmartTipDelegate! override func viewDidLoad() { super.viewDidLoad() configureLabels() } @IBAction func rejectButtonTapped() { smartTip.reject() configureButtons() } @IBAction func acceptButtonTapped() { smartTip.accept() configureButtons() } @IBAction func cancelButtonTapped() { smartTip.read() configureButtons() } @IBAction func okButtonTapped() { delegate.tipStatusSelectionDidFinish(self) } func configureLabels() { providerLabel.text = smartTip.provider titleLabel.text = smartTip.title descriptionLabel.text = smartTip.description } func configureButtons() { switch smartTip.status { case .Accepted, .Rejected: rejectButton.hidden = true acceptButton.hidden = true okButton.hidden = false cancelButton.hidden = false default: rejectButton.hidden = false acceptButton.hidden = false okButton.hidden = true cancelButton.hidden = true } } }<file_sep>/SmartTips/Status.swift // // Status.swift // SmartTips // // Created by <NAME> on 7/29/16. // Copyright © 2016 <NAME>. All rights reserved. // enum Status: Int { case Unread = 0, Read, Accepted, Rejected, Cancelled, Pending }<file_sep>/SmartTips/SmartTipTableViewCell.swift // // SmartTipTableViewCell.swift // SmartTips // // Created by <NAME> on 7/28/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class SmartTipTableViewCell: UITableViewCell { @IBOutlet weak var providerLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! } <file_sep>/SmartTips/File.swift // // File.swift // SmartTips // // Created by <NAME> on 7/28/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation <file_sep>/SmartTips/SmartTipsListViewController.swift // // SmartTipsListViewControllerswift // SmartTips // // Created by <NAME> on 7/26/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class SmartTipsListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let cellIdentfier = "smartTipCell" let jsonURL: URLStringConvertible = "https://demo7998593.mockable.io/smarttips.json" var smartTips: [SmartTip] = [] { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() let smartTipManager = SmartTipJSONManager.getInstance smartTipManager.loadArrayFromJSONurl(jsonURL) { self.smartTips = smartTipManager.smartTips } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showSmartTipDetailView" { if let tipVC = segue.destinationViewController as? SmartTipViewController, index = tableView.indexPathForSelectedRow?.row { tipVC.smartTip = smartTips[index] tipVC.delegate = self } } } } extension SmartTipsListViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return smartTips.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell: SmartTipTableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentfier) as? SmartTipTableViewCell else { return UITableViewCell() } let smartTip = smartTips[indexPath.row] // configure labels cell.providerLabel.text = smartTip.provider cell.titleLabel.text = smartTip.title cell.descriptionLabel.text = smartTip.description // set background color switch smartTip.status { case .Accepted: cell.backgroundColor = SmartTipColor.greenColor() case .Rejected: cell.backgroundColor = SmartTipColor.redColor() default: cell.backgroundColor = UIColor.whiteColor() } return cell } } extension SmartTipsListViewController: UITableViewDelegate { func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let reject = UITableViewRowAction(style: .Destructive, title: "Reject") { (action, indexPath) in self.smartTips[indexPath.row].reject() } let accept = UITableViewRowAction(style: .Normal, title: "Accept") { (action, indexPath) in self.smartTips[indexPath.row].accept() } reject.backgroundColor = SmartTipColor.redColor() accept.backgroundColor = SmartTipColor.greenColor() return [reject, accept] } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { guard let cell: SmartTipTableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentfier) as? SmartTipTableViewCell else { return UITableViewCell().bounds.size.height } return cell.bounds.size.height } } extension SmartTipsListViewController: SmartTipDelegate { func tipStatusSelectionDidFinish(controller: SmartTipViewController) { controller.dismissViewControllerAnimated(true) { () in if let index = self.tableView.indexPathForSelectedRow?.row { self.smartTips[index] = controller.smartTip } } } }
f8b5d887425d0e0968957feef20016232f217b56
[ "Swift" ]
9
Swift
bonuelc/AdHawkSmartTipMockup
76a01e219e23d5892896edd2855a1afc0da50b60
a285f9e9b473b2d101361fcda71b629f9927c705
refs/heads/master
<file_sep><?php use Faker\Generator as Faker; $factory->define(App\Services\Products\Product::class, function (Faker $faker) { return [ 'slug'=>str_slug('Velg Yokomaha 12inch', '-'), 'name'=>'<NAME>', 'price'=> '2000000', 'thumbnail'=> 'src/photos/yokohama12inch.jpg', 'size'=> 12, 'status'=> 'Baru', 'detail'=> 'Lorem ipsum dolor sit amet', ]; }); <file_sep><?php namespace App\Services\Orders; use Illuminate\Database\Eloquent\Model; class OrderItems extends Model { protected $table = 'order_items'; protected $fillable = [ 'order_id','product_id', 'quantity', 'price' ]; public function items() { return $this->belongsTo(App\Services\Products\Product::class, 'product_id','id'); } public function orders() { return $this->belongsTo(Order::class, 'order_id','id'); } } <file_sep><?php $factory->define(App\Services\Orders\Order::class, function (Faker\Generator $faker) { return [ 'customer_email' => $faker->email, 'status' => 'Menunggu Pembayaran', ]; }); <file_sep><?php $factory->define(App\Services\Products\ProductPhotos::class, function (Faker\Generator $faker) { return [ 'src' => $faker->imageUrl, ]; }); <file_sep><?php namespace App\Services\Products; use Illuminate\Database\Eloquent\Model; class ProductPhotos extends Model { protected $table = 'product_photos'; protected $fillable = [ 'product_id','src' ]; public function products() { return $this->belongsTo(Product::class, 'product_id'); } } <file_sep><?php namespace App\Services\Products; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $fillable = [ 'slug','name', 'price', 'thumbnail', 'size', 'status', 'detail' ]; public function photos() { return $this->hasMany(ProductPhotos::class, 'product_id', 'id'); } } <file_sep><?php $factory->define(App\Services\Orders\OrderItems::class, function (Faker\Generator $faker) { return [ 'product_id' => rand(1,5), 'price' => rand(150000,5000000), 'quantity'=> rand(1,4) ]; }); <file_sep><?php use Illuminate\Database\Seeder; class ProductTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(App\Services\Products\Product::class)->create()->each(function($product_photos) { $product_photos->photos()->save(factory(App\Services\Products\ProductPhotos::class)->make()); }); } } <file_sep><?php namespace App\Services\Orders; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $fillable = [ 'customer_email','status' ]; public function orderItems() { return $this->hasMany(OrderItems::class, 'order_id','id'); } }
94bdd949a6d5d54a2fc3b0c92d7addc3520c69ea
[ "PHP" ]
9
PHP
agilukm/auto-shop
36ccac3d9e9da96c649d49360bddb10f46d1322b
6b525c723bf40e0855430a8861253bd5996142f1
refs/heads/master
<file_sep>var port = process.env.PORT || 3000; var itemData = require('./itemData.json') var express = require('express') var app = express() var exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({ defaultLayout: 'main' })) app.set('view engine', 'handlebars') app.use(express.static('public')) if (itemData){ console.log("itemData imported successfully"), console.log(itemData["meats"]) } // return the main page app.get('/', function (req, res) { if(itemData) {res.status(200).render('homePage', { meatsItems: itemData["meats"], veggiesItems: itemData["veggies"], drinksItems: itemData["drinks"] } ) } else {next()} }) app.get('/category', function (req, res, next){ res.status(200).render('catMainPage') } ) // return the main page, using parameters and itemData.json array app.get('/category/:key', function (req, res, next){ var key = req.params.key if(itemData[key]) res.status(200).render('catPage', { items: itemData[key] } ) else {next()} } ) app.get('/checkout', function (req, res, next){ console.log("Checkout page requested") res.status(200).render('checkoutPage', //{ // serve the selected items data object here, somehow //} ) next() } ) app.get('*', function (req, res, next) { res.status(404).render('404') }) app.listen(port, function () { console.log("== Server is listening on port", port) } );
554737e6df413df879dd8d99cc81ec1b69df6eba
[ "JavaScript" ]
1
JavaScript
alsalmaf/final-project-group-12
4243000446748497724433ea2fb0ca099114ab9a
e391fda7c947291890a203ee59a7689393f7883a
refs/heads/master
<repo_name>geekzw/blogProMac<file_sep>/source/tags/index.md --- title: 标签 date: 2016-11-01 15:28:43 type: "tags" comments: false --- <file_sep>/source/_posts/android-常用小知识.md --- title: android 常用小知识 date: 2016-12-06 11:13:28 categories: android tags: android description: "android 常用知识" --- ## 阿里freeline 加快编译速度,并打造动态热部署:[freeline][1] [1]: https://github.com/alibaba/freeline<file_sep>/updateBolg.sh git add * git commit -m "update" git push origin master hexo g -d
35f5f8b843e77335677431a08133c467d62e7393
[ "Markdown", "Shell" ]
3
Markdown
geekzw/blogProMac
2bb2902c642f8c5cb91ea3eb52c887221edeba29
8ca6d1574da4a1c94aa573a2e6f801be776c0f34
refs/heads/master
<file_sep>Worker Module ================ This node module will allow specific jobs to be scheduled at user controlled intervals The job will be made up of the following. { name : "<NAME> the job", pattern : "cron pattern to trigger job", start : "the function to call when the job is triggered" } ##How to install Until this module has been published to NPM repo add the following to your package.json file in the dependencies element. "worker-module": "git+https://github.com/gbd77rc/worker-module.git" Then run npm update worker-module It should then install the latest version. ##Dependencies The following Node packages are also installed. * q * node-schedule (It has been fixed for CRON intervals so the code is in the lib folder and not as a package dependency) ##How to use In the app.js/server.js or whichever Node JavaScript file you wish to initialise this module in do the following. The job can be added using this method var worker = require('worker-module'); worker.add({ name :"queue-job", pattern:"0 0 4 * *", // Start at 4am every morning start: function(jobStatus){ var def = q.defer(); setInterval(function(){ console.log("Its 4am time to get up!"); status.processed++; def.resolve("Successful"); },500); return def.promise; } }); ###Job Start Function The job start method MUST implement a promise. The system is designed to work with a promise being returned and the method either resolving or rejecting depending on the outcome of the start method. ####Start Method If the job is already running then this method is ignore. It will just return straight away. To start the heartbeat in fire/forget mode then just use the command worker.start() ####Stop Method If the job is already stopped then this method is ignore. It will just return straight away. To stop the worker in fire/forget mode then just use the command worker.stop(); ####Restart Method To restart all jobs then use without the jobName parameter. worker.stop(jobName); ####Get Status Method To get the current status of the jobs then just use the command worker.getStatus(); It will return the following object. It will contain a job status per job added. [ { name:"queue-job", status:"waiting", nextRunTime:"", lastRunTime:"", timesRan:"", processed:0, // The only property of the jobStatus that is not automatically updated by the worker system. pattern:"", schedule:null, start:{} } ] ####Events Triggered The following events are available. worker.on('worker-job-success',function(result){ // Do something as the job has completed successfully }); worker.on('worker-job-error',function(result){ // Do something as the job has completed with an error }); worker.on('worker-job-waiting',function(result){ // Do something as the job has been scheduled }); worker.on('worker-job-stopped',function(result){ // Do something as the job has been stopped }); The `result` object will contain the following information { name:"", status:"", results:"" } <file_sep>var scheduler = require('./schedule'); var events = require('events'); exports = module.exports = new events.EventEmitter(); var jobs = []; var validate = function(job){ if ( job == undefined ){ throw "Job is missing"; } if ( job.name === undefined || job.name === ""){ throw "Name of job is missing"; } if ( job.pattern === undefined || job.pattern === ""){ throw "Job interval pattern is missing"; } if ( job.start=== undefined || typeof job.start !== "function"){ throw "Job start method is missing"; } if ( findIndex(job.name) > -1){ throw "Job with this name (" + job.name +") already exists!"; } }; var findIndex = function(jobName){ var idx = -1; for( var i = 0; i < jobs.length; i++ ){ var job = jobs[i]; if ( job.name == jobName ){ idx = i; break; } } return idx; }; // Status // not-started // waiting // success // error var createJob = function(job){ return { name:job.name, status:"not-started", nextRunTime:"", lastRunTime:"", timesRan:"", processed:0, pattern:job.pattern, schedule:null, start: job.start, lastError:"" }; }; var findJob = function(jobName){ for(var i = 0; i < jobs.length; i++){ var job = jobs[i]; if ( job.name === jobName ){ return job; } } return null; }; exports.clear = function(){ exports.stop(); jobs = []; }; exports.add = function(job){ validate(job); // If got here then we must be ok. jobs.push(createJob(job)); }; exports.getStatus = function(){ return jobs; }; exports.runJob = function(jobName){ try { var job = jobs[findIndex(jobName)]; if ( job === undefined ){ throw "Job not found!"; } if( job.schedule != null ){ var currentTime = new Date(); // Check if manually triggered or not job.lastRunTime = (currentTime < job.nextRunTime) ? currentTime : job.nextRunTime; job.nextRunTime = job.schedule.nextInvocation(); } job.status = "running"; job.start(job).then(function(results){ job.status = "success"; job.timesRan++; if ( results == "skipped"){ job.status = "skipped"; } exports.emit("worker-job-success", { name : job.name, status : job.status, results : results }); }, function(err){ job.status = "error"; job.lastError = err; exports.emit("worker-job-error", { name : job.name, status : job.status, results : err }); }).finally(function(){ var msg = "next schedule run is " + job.nextRunTime; exports.emit('worker-job-waiting',{ name : job.name, status : job.status, results : msg }); }).done(); } catch(e){ throw "Problem running job - " + e; } }; exports.start = function(){ // Schedule for(var i =0; i < jobs.length; i++ ){ var job = jobs[i]; startJob(job); } }; var startJob = function(job){ if ( job.status === "not-started") { job.schedule = scheduler.scheduleJob(job.pattern, function () { exports.runJob(job.name); }); job.nextRunTime = job.schedule.nextInvocation(); var msg = "schedule to run at " + job.nextRunTime; exports.emit('worker-job-waiting',{ name : job.name, status : job.status, results : msg }); } }; exports.stop = function(){ // Schedule for(var i =0; i < jobs.length; i++ ){ var job = jobs[i]; stopJob(job); } }; var stopJob = function(job){ if ( job.schedule != null ){ job.schedule.cancel(); } job.status = "not-started"; var msg = "has been stopped."; exports.emit('worker-job-stopped',{ name : job.name, status : job.status, results : msg }); }; exports.restart = function(jobName){ if ( jobName == undefined || jobName === "") { exports.stop(); exports.start(); } else { var job = findJob(jobName); stopJob(job); startJob(job); } };<file_sep>var should = require('should'); var assert = require('assert'); var worker = require('../lib/'); var q = require('q'); describe("Use Background Worker", function(){ describe("Pass an invalid job should raise exception", function() { it("No job specified", function () { try { worker.add(); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Job is missing"); } }); it("No name property specified", function () { try { worker.add({ name2: "testing" }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Name of job is missing"); } }); it("No name value specified", function () { try { worker.add({ name: "" }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Name of job is missing"); } }); it("No pattern property specified", function () { try { worker.add({ name: "<NAME>" }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Job interval pattern is missing"); } }); it("No pattern value specified", function () { try { worker.add({ name: "<NAME>", pattern : "" }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Job interval pattern is missing"); } }); it("No start property specified", function () { try { worker.add({ name: "<NAME>", pattern: "0 4 * * *" }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Job start method is missing"); } }); it("No start value specified", function () { try { worker.add({ name: "<NAME>", pattern: "0 4 * * *", start:null }); assert.fail("Should not reach here!"); } catch (e) { e.should.be.equal("Job start method is missing"); } }); }); describe("Run a missing job", function(){ it("Should raise an exception", function(){ try { worker.runJob("Test3"); assert.fail("Should not be here!"); } catch(e){ e.should.be.equal("Problem running job - Job not found!") } }); }); describe("Worker is successful",function(){ beforeEach(function(done){ worker.removeAllListeners(['worker-job-success', 'worker-job-error']); worker.clear(); done(); }); it("Job will display hello", function(){ worker.on("worker-job-success", function(result){ should.exists(result); result.status.should.equal("success"); result.name.should.equal("Test1"); result.results.should.equal("Success"); }); worker.add({ name :"Test1", pattern:" 0/2 * * * *", start:function(status){ var def = q.defer(); setInterval(function() { var msg = "Hello - " + status.status; msg.should.be.equal("Hello - running"); def.resolve("Success"); }, 500); return def.promise; } }); var status = worker.getStatus(); status.length.should.be.equal(1); status[0].status.should.be.equal("not-started"); status[0].name.should.be.equal('Test1'); worker.runJob("Test1"); }); it("Start schedule and stop it", function(){ worker.on("worker-job-success", function(result){ should.exists(result); result.status.should.equal("success"); result.name.should.equal("Test2"); result.results.should.equal("Success"); }); worker.add({ name :"Test2", pattern:" 0/1 * * * *", start:function(status){ var def = q.defer(); setInterval(function() { var msg = "Hello - " + status.status; msg.should.be.equal("Hello - running"); def.resolve("Success"); }, 500); return def.promise; } }); worker.start(); }) }); });
245c545c27c0b1c21913d86e8cac43d7554bcde0
[ "Markdown", "JavaScript" ]
3
Markdown
gbd77rc/worker-module
cb06c6a1b818b0fe5782c22c7c8fe0205020e6d7
91b26c7b92c3da939f136379de2ed42be6590a2b
refs/heads/master
<file_sep># FaceNet-Pytorch https://arxiv.org/pdf/1503.03832.pdf - Pytorch <file_sep>import os import random from glob import glob from PIL import Image from torch.utils.data import Dataset class TripletImageDataset(Dataset): """ Creates anchor, positive, negative triples from diretory of Image folders """ def __init__(self, root, transform=None): self.name_to_id = dict((name, i) for i, name in enumerate(sorted(os.listdir(root)))) self.id_to_name = dict((i, name) for name, i in self.name_to_id.items()) self.images = glob(os.path.join(root, "*", "*")) self.class_dirs = glob(os.path.join(root, "*")) self.transform = transform def create_triplets(self): class_1, class_2 = random.sample(self.class_paths, 2) images_1 = os.listdir(class_1) image_2 = os.listdir(class_2) return class_1, class_2, images_1, image_2 def __getitem__(self, idx): anchor_path = random.choice(self.images) anchor_class_dir, _ = os.path.split(anchor_path) positive_image_paths = glob(os.path.join(anchor_class_dir, '*')) positive_path = random.choice(positive_image_paths) while True: negative_class_dir = random.choice(self.class_dirs) if negative_class_dir != anchor_class_dir: break negative_image_paths = glob(os.path.join(negative_class_dir, '*')) negative_path = random.choice(negative_image_paths) anchor = Image.open(anchor_path).convert('RGB') positive = Image.open(positive_path).convert('RGB') negative = Image.open(negative_path).convert('RGB') if self.transform: anchor = self.transform(anchor) positive = self.transform(positive) negative = self.transform(negative) return anchor, positive, negative def __len__(self): return len(self.images) <file_sep>import random import torch from torch.autograd import Variable from torchvision import transforms def to_var(tensor): """Converts tensor to variable.""" if torch.cuda.is_available(): tensor = tensor.cuda() return Variable(tensor) def to_tensor(variable): """Converts variable to tensor.""" if torch.cuda.is_available(): variable = variable.cpu() return variable.data def to_image(tensor): """Converts tensor to pil Image.""" return transforms.ToPILImage()(tensor.clamp(0, 1)) def summary(net): num_params = 0 print("NAME | SIZE | NUM PARAMETERS") for name, param in net.named_parameters(): print("{} | {} | {} ".format(name, tuple(param.size()), param.numel())) num_params += param.numel() print('Total number of parameters: %d' % num_params) class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def save_checkpoint(model_state, optimizer_state, filename): state = dict(model_state=model_state, optimizer_state=optimizer_state) torch.save(state, filename)
14c9e0e89641c8fa9989a8b023e95e1f22165bad
[ "Markdown", "Python" ]
3
Markdown
A-Jacobson/FaceNet-Pytorch
fb38a42afc4e9bfedd9d73d700adbb836db6dbab
b4cc8592233a0dbcd5ebc244376e3b505c6c008e
refs/heads/master
<file_sep>package tim.wat.darts.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import tim.wat.darts.objects.ContestObject; import tim.wat.darts.objects.PlayerObject; import tim.wat.darts.repositories.ContestRepository; import tim.wat.darts.repositories.PlayerRepository; import tim.wat.darts.source.Contest; import tim.wat.darts.source.Player; import java.util.ArrayList; import java.util.List; @RestController public class ContestController { @Autowired ContestRepository contestRepository; @Autowired PlayerRepository playerRepository; @RequestMapping(value = "/setContest", method = RequestMethod.POST) @ResponseBody public ContestObject setContest(@RequestParam(value = "contest_name", defaultValue = "") String contest_name, @RequestParam(value = "contest_pass", defaultValue = "") String contest_pass, @RequestParam(value = "login", defaultValue = "") String login ) { Contest contest = new Contest(contest_name, contest_pass); contest.getPlayers().add(playerRepository.findByLogin(login)); contestRepository.save(contest); return new ContestObject(contest.getId(), contest.getContestName()); } @RequestMapping(value = "/joinContest", method = RequestMethod.POST) @ResponseBody public ContestObject joinMatch(@RequestParam(value = "contest_name", defaultValue = "") String contest_name, @RequestParam(value = "contest_pass", defaultValue = "") String contest_pass, @RequestParam(value = "login", defaultValue = "") String login ) { Contest contest = contestRepository.findByContestNameAndContestPass(contest_name,contest_pass); contest.getPlayers().add(playerRepository.findByLogin(login)); contestRepository.save(contest); return new ContestObject(contest.getId(), contest.getContestName()); } @RequestMapping(value = "/getPlayerContests", method = RequestMethod.POST) @ResponseBody public ArrayList<ContestObject> getContest( @RequestParam(value = "login", defaultValue = "") String login ) { Player player=playerRepository.findByLogin(login); ArrayList<ContestObject> playerContest = contestRepository.findAllByPlayers(player); System.out.println("logged"); return playerContest; } @RequestMapping(value = "/getContestPlayers", method = RequestMethod.POST) @ResponseBody public ArrayList<PlayerObject> getPlayers( @RequestParam(value = "contest", defaultValue = "") String contest ) { ArrayList<Player> player=playerRepository.findAllByContests(contestRepository.findByContestName(contest)); ArrayList<PlayerObject> playerObjects = new ArrayList<>(); for (int i =0;i< player.size();i++){ playerObjects.add(new PlayerObject(player.get(i).getId(),player.get(i).getName(),player.get(i).getSurname(),player.get(i).getLogin(),null)); } return playerObjects; } } <file_sep>package tim.wat.darts.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import tim.wat.darts.objects.PlayerObject; import tim.wat.darts.repositories.PlayerRepository; import tim.wat.darts.source.Player; import java.util.Collections; import java.util.List; import java.util.Map; import static tim.wat.darts.source.Player.PlayerRole.ROLE_USER; @RestController("/api") public class PlayerController { @Autowired PlayerRepository playerRepository; @Autowired PasswordEncoder passwordEncoder; @RequestMapping(value = "/setPlayer", method = RequestMethod.POST) @ResponseBody public PlayerObject setPlayer(@RequestParam(value = "name", defaultValue = "") String name, @RequestParam(value = "surname", defaultValue = "") String surname, @RequestParam(value = "login", defaultValue = "") String login, @RequestParam(value = "password", defaultValue = "") String password, @RequestParam(value = "avatarPath", defaultValue = "") String avatarPath) { String encodedPassword = passwordEncoder.encode(password); Player player = new Player(name, surname, login, encodedPassword, avatarPath); player.setRoles(ROLE_USER); playerRepository.save(player); return new PlayerObject(player.getId(), player.getName(),player.getSurname(),player.getLogin(),player.getAvatarPath()); } @RequestMapping(value = "/setAvatarImage", method = RequestMethod.POST) @ResponseBody public PlayerObject setVatharImage(@RequestParam(value = "name", defaultValue = "") String name, @RequestParam(value = "surname", defaultValue = "") String surname, @RequestParam(value = "login", defaultValue = "") String login, @RequestParam(value = "password", defaultValue = "") String password, @RequestParam(value = "avatarPath", defaultValue = "") String avatarPath) { String encodedPassword = passwordEncoder.encode(password); Player player = new Player(name, surname, login, encodedPassword, avatarPath); playerRepository.save(player); return new PlayerObject(player.getId(), player.getName(),player.getSurname(),player.getLogin(),player.getAvatarPath()); } @RequestMapping(value = "/whoAmI", method = RequestMethod.GET) @ResponseBody public Map<String, String> whoAmI() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!authentication.getName().equals("anonymousUser")) { return Collections.singletonMap("login", authentication.getName()); } return null; } } <file_sep> insert into player values (1,null,false,'admin','','$2a$07$qT0PeJq4lcxDfexyhylYyOYLXWyKuABuVq0xy2dvMQUYIWhzhboUy',''); insert into player values (2,null,false,'user','','$2a$07$qT0PeJq4lcxDfexyhylYyOYLXWyKuABuVq0xy2dvMQUYIWhzhboUy',''); insert into players_role VALUES (1,'ROLE_ADMIN'); insert into players_role VALUES (1,'ROLE_USER'); insert into players_role VALUES (2,'ROLE_USER'); insert into contest values (1,'test1','test',null); insert into contest values (2,'test221','test',null); insert into contest_player values (1,1); insert into contest_player values (2,1); insert into contest_player values (2,2); insert into round values (1,30,30,null,1,2); insert into round values (2,30,60,null,1,1); insert into round values (3,30,90,null,1,1); select setval('hibernate_sequence', 100, true);<file_sep>package tim.wat.darts.source; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity public class Contest { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(unique = true) private String contestName; private String contestPass; @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinTable(name = "contest_player", joinColumns = { @JoinColumn(name = "contest_id") }, inverseJoinColumns = { @JoinColumn(name = "player_id") }) private Set< Player> players = new HashSet<>(); public Player getWinner() { return winner; } public void setWinner(Player winner) { this.winner = winner; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="winner_id") private Player winner; public Contest(String contestName, String contestPass) { this.contestName = contestName; this.contestPass = contestPass; } protected Contest() { } public Long getId() { return id; } public Set<Player> getPlayers() { return players; } public void setPlayers(Set<Player> players) { this.players = players; } public String getContestName() { return contestName; } public void setContestName(String contestName) { this.contestName = contestName; } public String getContestPass() { return contestPass; } public void setContestPass(String contestPass) { this.contestPass = contestPass; } } <file_sep>package tim.wat.darts.source; import javax.persistence.*; @Entity public class Round { public void setId(Long id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private int amount; private int fullAmount; private String photoPath; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="contest_id") private Contest contest; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="player_id") private Player player; public Round(int amount, String photoPath) { this.amount = amount; this.photoPath = photoPath; } public Long getId() { return id; } public Contest getContest() { return contest; } public void setContest(Contest contest) { this.contest = contest; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public int getFullAmount() { return fullAmount; } public void setFullAmount(int fullAmount) { this.fullAmount = fullAmount; } public String getPhotoPath() { return photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } protected Round(){ } } <file_sep>spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=<PASSWORD> spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect spring.jpa.hibernate.ddl-auto=create-drop spring.datasource.initialization-mode=always server.servlet.path=/api<file_sep>package tim.wat.darts.objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; public class RoundObject { private Long id; private int amount; private int fullAmount; private String photoPath; private String login; public RoundObject(Long id, int amount, int fullAmount, String photoPath,String login) { this.id = id; this.amount = amount; this.fullAmount = fullAmount; this.photoPath = photoPath; this.login=login; } public RoundObject() { } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public int getFullAmount() { return fullAmount; } public void setFullAmount(int fullAmount) { this.fullAmount = fullAmount; } public String getPhotoPath() { return photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } }
6a5f7bcd7b1b083211f0b5185120712e2638c86d
[ "Java", "SQL", "INI" ]
7
Java
dudap1/Darts-1
817e5af681ac0d47d8174ebd437a234c07d63596
03d767d9598d53d990534e925fa9b481f0780ccc
refs/heads/master
<repo_name>Piero-Onorati/js-faq-accordion-card<file_sep>/js/script.js document.querySelectorAll('.accordion-question').forEach(item =>{ item.addEventListener('click', event =>{ console.log('click'); if (!item.classList.contains('open')) { // add collapsing at accordion answer item.nextElementSibling.classList ='.accordion-answer collapsing'; // after an amount of time, remove collapsing and add opened setTimeout(()=>{ item.nextElementSibling.classList ='.accordion-answer opened'; },300) } else { // remove class opened and add collapsing item.nextElementSibling.classList ='.accordion-answer collapsing'; // after an amount of time, remove collapsing and add collapse setTimeout(()=>{ item.nextElementSibling.classList ='accordion-answer collapse'; },100) } item.classList.toggle('open'); }); }); // const app = new Vue( // { // el: '#app', // data : { // indexCheck:'', // active:false, // boldQuestion: 'boldQuestion', // accordions: [ // { // question:'How many team members can I invite?', // answer: 'You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.' // }, // { // question:'What is the maximum file upload size?', // answer: 'No more than 2GB. All files in your account must fit your allotted storage space.', // }, // { // question:'How do I reset my password?', // answer: 'Click “Forgot password” from the login page or “Change password” from your profile page. A reset link will be emailed to you.' // }, // { // question:'Can I cancel my subscription?', // answer: 'Yes! Send us a message and we’ll process your request no questions asked.' // }, // { // question:'Do you provide additional support?', // answer: 'Chat and email support is available 24/7. Phone lines are open during normal business hours.' // } // ] // }, // methods :{ // openAccordion: function(index){ // this.indexCheck = index // this.active = !this.active; // } // } // } // );
bc125e59a863c8617e2e5f6826f3c959c522cd57
[ "JavaScript" ]
1
JavaScript
Piero-Onorati/js-faq-accordion-card
83260a04b86a7d839c876c1b18787eeb177d6844
81da15514e0e40d091e3a9525b2dd5b3a9041ada
refs/heads/master
<file_sep>/*! @file SimpleSvm.cpp @brief All C code. @author <NAME> @copyright Copyright (c) 2017-2020, <NAME>. All rights reserved. */ #define POOL_NX_OPTIN 1 #include "SimpleSvm.hpp" #include <intrin.h> #include <ntifs.h> #include <stdarg.h> EXTERN_C DRIVER_INITIALIZE DriverEntry; static DRIVER_UNLOAD SvDriverUnload; static CALLBACK_FUNCTION SvPowerCallbackRoutine; EXTERN_C VOID _sgdt ( _Out_ PVOID Descriptor ); _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ DECLSPEC_NORETURN EXTERN_C VOID NTAPI SvLaunchVm ( _In_ PVOID HostRsp ); // // x86-64 defined structures. // // // See "2-Mbyte PML4E-Long Mode" and "2-Mbyte PDPE-Long Mode". // typedef struct _PML4_ENTRY_2MB { union { UINT64 AsUInt64; struct { UINT64 Valid : 1; // [0] UINT64 Write : 1; // [1] UINT64 User : 1; // [2] UINT64 WriteThrough : 1; // [3] UINT64 CacheDisable : 1; // [4] UINT64 Accessed : 1; // [5] UINT64 Reserved1 : 3; // [6:8] UINT64 Avl : 3; // [9:11] UINT64 PageFrameNumber : 40; // [12:51] UINT64 Reserved2 : 11; // [52:62] UINT64 NoExecute : 1; // [63] } Fields; }; } PML4_ENTRY_2MB, *PPML4_ENTRY_2MB, PDP_ENTRY_2MB, *PPDP_ENTRY_2MB; static_assert(sizeof(PML4_ENTRY_2MB) == 8, "PML4_ENTRY_1GB Size Mismatch"); // // See "2-Mbyte PDE-Long Mode". // typedef struct _PD_ENTRY_2MB { union { UINT64 AsUInt64; struct { UINT64 Valid : 1; // [0] UINT64 Write : 1; // [1] UINT64 User : 1; // [2] UINT64 WriteThrough : 1; // [3] UINT64 CacheDisable : 1; // [4] UINT64 Accessed : 1; // [5] UINT64 Dirty : 1; // [6] UINT64 LargePage : 1; // [7] UINT64 Global : 1; // [8] UINT64 Avl : 3; // [9:11] UINT64 Pat : 1; // [12] UINT64 Reserved1 : 8; // [13:20] UINT64 PageFrameNumber : 31; // [21:51] UINT64 Reserved2 : 11; // [52:62] UINT64 NoExecute : 1; // [63] } Fields; }; } PD_ENTRY_2MB, *PPD_ENTRY_2MB; static_assert(sizeof(PD_ENTRY_2MB) == 8, "PDE_ENTRY_2MB Size Mismatch"); // // See "GDTR and IDTR Format-Long Mode" // #include <pshpack1.h> typedef struct _DESCRIPTOR_TABLE_REGISTER { UINT16 Limit; ULONG_PTR Base; } DESCRIPTOR_TABLE_REGISTER, *PDESCRIPTOR_TABLE_REGISTER; static_assert(sizeof(DESCRIPTOR_TABLE_REGISTER) == 10, "DESCRIPTOR_TABLE_REGISTER Size Mismatch"); #include <poppack.h> // // See "Long-Mode Segment Descriptors" and some of definitions // (eg, "Code-Segment Descriptor-Long Mode") // typedef struct _SEGMENT_DESCRIPTOR { union { UINT64 AsUInt64; struct { UINT16 LimitLow; // [0:15] UINT16 BaseLow; // [16:31] UINT32 BaseMiddle : 8; // [32:39] UINT32 Type : 4; // [40:43] UINT32 System : 1; // [44] UINT32 Dpl : 2; // [45:46] UINT32 Present : 1; // [47] UINT32 LimitHigh : 4; // [48:51] UINT32 Avl : 1; // [52] UINT32 LongMode : 1; // [53] UINT32 DefaultBit : 1; // [54] UINT32 Granularity : 1; // [55] UINT32 BaseHigh : 8; // [56:63] } Fields; }; } SEGMENT_DESCRIPTOR, *PSEGMENT_DESCRIPTOR; static_assert(sizeof(SEGMENT_DESCRIPTOR) == 8, "SEGMENT_DESCRIPTOR Size Mismatch"); typedef struct _SEGMENT_ATTRIBUTE { union { UINT16 AsUInt16; struct { UINT16 Type : 4; // [0:3] UINT16 System : 1; // [4] UINT16 Dpl : 2; // [5:6] UINT16 Present : 1; // [7] UINT16 Avl : 1; // [8] UINT16 LongMode : 1; // [9] UINT16 DefaultBit : 1; // [10] UINT16 Granularity : 1; // [11] UINT16 Reserved1 : 4; // [12:15] } Fields; }; } SEGMENT_ATTRIBUTE, *PSEGMENT_ATTRIBUTE; static_assert(sizeof(SEGMENT_ATTRIBUTE) == 2, "SEGMENT_ATTRIBUTE Size Mismatch"); // // SimpleSVM specific structures. // typedef struct _SHARED_VIRTUAL_PROCESSOR_DATA { PVOID MsrPermissionsMap; DECLSPEC_ALIGN(PAGE_SIZE) PML4_ENTRY_2MB Pml4Entries[1]; // Just for 512 GB DECLSPEC_ALIGN(PAGE_SIZE) PDP_ENTRY_2MB PdpEntries[512]; DECLSPEC_ALIGN(PAGE_SIZE) PD_ENTRY_2MB PdeEntries[512][512]; } SHARED_VIRTUAL_PROCESSOR_DATA, *PSHARED_VIRTUAL_PROCESSOR_DATA; typedef struct _VIRTUAL_PROCESSOR_DATA { union { // // Low HostStackLimit[0] StackLimit // ^ ... // ^ HostStackLimit[KERNEL_STACK_SIZE - 2] StackBase // High HostStackLimit[KERNEL_STACK_SIZE - 1] StackBase // DECLSPEC_ALIGN(PAGE_SIZE) UINT8 HostStackLimit[KERNEL_STACK_SIZE]; struct { UINT8 StackContents[KERNEL_STACK_SIZE - (sizeof(PVOID) * 6) - sizeof(KTRAP_FRAME)]; KTRAP_FRAME TrapFrame; UINT64 GuestVmcbPa; // HostRsp UINT64 HostVmcbPa; struct _VIRTUAL_PROCESSOR_DATA* Self; PSHARED_VIRTUAL_PROCESSOR_DATA SharedVpData; UINT64 Padding1; // To keep HostRsp 16 bytes aligned UINT64 Reserved1; } HostStackLayout; }; DECLSPEC_ALIGN(PAGE_SIZE) VMCB GuestVmcb; DECLSPEC_ALIGN(PAGE_SIZE) VMCB HostVmcb; DECLSPEC_ALIGN(PAGE_SIZE) UINT8 HostStateArea[PAGE_SIZE]; } VIRTUAL_PROCESSOR_DATA, *PVIRTUAL_PROCESSOR_DATA; static_assert(sizeof(VIRTUAL_PROCESSOR_DATA) == KERNEL_STACK_SIZE + PAGE_SIZE * 3, "VIRTUAL_PROCESSOR_DATA Size Mismatch"); typedef struct _GUEST_REGISTERS { UINT64 R15; UINT64 R14; UINT64 R13; UINT64 R12; UINT64 R11; UINT64 R10; UINT64 R9; UINT64 R8; UINT64 Rdi; UINT64 Rsi; UINT64 Rbp; UINT64 Rsp; UINT64 Rbx; UINT64 Rdx; UINT64 Rcx; UINT64 Rax; } GUEST_REGISTERS, *PGUEST_REGISTERS; typedef struct _GUEST_CONTEXT { PGUEST_REGISTERS VpRegs; BOOLEAN ExitVm; } GUEST_CONTEXT, *PGUEST_CONTEXT; // // x86-64 defined constants. // #define IA32_MSR_PAT 0x00000277 #define IA32_MSR_EFER 0xc0000080 #define EFER_SVME (1UL << 12) #define RPL_MASK 3 #define DPL_SYSTEM 0 #define CPUID_FN8000_0001_ECX_SVM (1UL << 2) #define CPUID_FN0000_0001_ECX_HYPERVISOR_PRESENT (1UL << 31) #define CPUID_FN8000_000A_EDX_NP (1UL << 0) #define CPUID_MAX_STANDARD_FN_NUMBER_AND_VENDOR_STRING 0x00000000 #define CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS 0x00000001 #define CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS_EX 0x80000001 #define CPUID_SVM_FEATURES 0x8000000a // // The Microsoft Hypervisor interface defined constants. // #define CPUID_HV_VENDOR_AND_MAX_FUNCTIONS 0x40000000 #define CPUID_HV_INTERFACE 0x40000001 // // SimpleSVM specific constants. // #define CPUID_UNLOAD_SIMPLE_SVM 0x41414141 #define CPUID_HV_MAX CPUID_HV_INTERFACE /*! @brief Breaks into a kernel debugger when it is present. @details This macro is emits software breakpoint that only hits when a kernel debugger is present. This macro is useful because it does not change the current frame unlike the DbgBreakPoint function, and breakpoint by this macro can be overwritten with NOP without impacting other breakpoints. */ #define SV_DEBUG_BREAK() \ if (KD_DEBUGGER_NOT_PRESENT) \ { \ NOTHING; \ } \ else \ { \ __debugbreak(); \ } \ reinterpret_cast<void*>(0) // // A power state callback handle. // static PVOID g_PowerCallbackRegistration; /*! @brief Sends a message to the kernel debugger. @param[in] Format - The format string to print. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ static VOID SvDebugPrint ( _In_z_ _Printf_format_string_ PCSTR Format, ... ) { va_list argList; va_start(argList, Format); vDbgPrintExWithPrefix("[SimpleSvm] ", DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, Format, argList); va_end(argList); } /*! @brief Allocates page aligned, zero filled physical memory. @details This function allocates page aligned nonpaged pool. The allocated memory is zero filled and must be freed with SvFreePageAlingedPhysicalMemory. On Windows 8 and later versions of Windows, the allocated memory is non executable. @param[in] NumberOfBytes - A size of memory to allocate in byte. This must be equal or greater than PAGE_SIZE. @result A pointer to the allocated memory filled with zero; or NULL when there is insufficient memory to allocate requested size. */ __drv_allocatesMem(Mem) _Post_writable_byte_size_(NumberOfBytes) _Post_maybenull_ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ _Must_inspect_result_ static PVOID SvAllocatePageAlingedPhysicalMemory ( _In_ SIZE_T NumberOfBytes ) { PVOID memory; // // The size must be equal or greater than PAGE_SIZE in order to allocate // page aligned memory. // NT_ASSERT(NumberOfBytes >= PAGE_SIZE); #pragma prefast(disable : 28118 __WARNING_ERROR, "FP due to POOL_NX_OPTIN.") memory = ExAllocatePoolWithTag(NonPagedPool, NumberOfBytes, 'MVSS'); if (memory != nullptr) { NT_ASSERT(PAGE_ALIGN(memory) == memory); RtlZeroMemory(memory, NumberOfBytes); } return memory; } /*! @brief Frees memory allocated by SvAllocatePageAlingedPhysicalMemory. @param[in] BaseAddress - The address returned by SvAllocatePageAlingedPhysicalMemory. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ static VOID SvFreePageAlingedPhysicalMemory ( _Pre_notnull_ __drv_freesMem(Mem) PVOID BaseAddress ) { ExFreePoolWithTag(BaseAddress, 'MVSS'); } /*! @brief Allocates page aligned, zero filled contiguous physical memory. @details This function allocates page aligned nonpaged pool where backed by contiguous physical pages. The allocated memory is zero filled and must be freed with SvFreeContiguousMemory. The allocated memory is executable. @param[in] NumberOfBytes - A size of memory to allocate in byte. @result A pointer to the allocated memory filled with zero; or NULL when there is insufficient memory to allocate requested size. */ _Post_writable_byte_size_(NumberOfBytes) _Post_maybenull_ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ _Must_inspect_result_ static PVOID SvAllocateContiguousMemory ( _In_ SIZE_T NumberOfBytes ) { PVOID memory; PHYSICAL_ADDRESS boundary, lowest, highest; boundary.QuadPart = lowest.QuadPart = 0; highest.QuadPart = -1; #pragma prefast(disable : 30030, "No alternative API on Windows 7.") memory = MmAllocateContiguousMemorySpecifyCacheNode(NumberOfBytes, lowest, highest, boundary, MmCached, MM_ANY_NODE_OK); if (memory != nullptr) { RtlZeroMemory(memory, NumberOfBytes); } return memory; } /*! @brief Frees memory allocated by SvAllocateContiguousMemory. @param[in] BaseAddress - The address returned by SvAllocateContiguousMemory. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ static VOID SvFreeContiguousMemory ( _In_ PVOID BaseAddress ) { MmFreeContiguousMemory(BaseAddress); } /*! @brief Injects #GP with 0 of error code. @param[in,out] VpData - Per processor data. */ _IRQL_requires_same_ static VOID SvInjectGeneralProtectionException ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData ) { EVENTINJ event; // // Inject #GP(vector = 13, type = 3 = exception) with a valid error code. // An error code are always zero. See "#GP-General-Protection Exception // (Vector 13)" for details about the error code. // event.AsUInt64 = 0; event.Fields.Vector = 13; event.Fields.Type = 3; event.Fields.ErrorCodeValid = 1; event.Fields.Valid = 1; VpData->GuestVmcb.ControlArea.EventInj = event.AsUInt64; } /*! @brief Handles #VMEXIT due to execution of the CPUID instructions. @details This function returns unmodified results of the CPUID instruction, except for few cases to indicate presence of the hypervisor, and to process an unload request. CPUID leaf 0x40000000 and 0x40000001 return modified values to conform to the hypervisor interface to some extent. See "Requirements for implementing the Microsoft Hypervisor interface" https://msdn.microsoft.com/en-us/library/windows/hardware/Dn613994(v=vs.85).aspx for details of the interface. @param[in,out] VpData - Per processor data. @param[in,out] GuestContext - Guest's GPRs. */ _IRQL_requires_same_ static VOID SvHandleCpuid ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData, _Inout_ PGUEST_CONTEXT GuestContext ) { int registers[4]; // EAX, EBX, ECX, and EDX int leaf, subLeaf; SEGMENT_ATTRIBUTE attribute; // // Execute CPUID as requested. // leaf = static_cast<int>(GuestContext->VpRegs->Rax); subLeaf = static_cast<int>(GuestContext->VpRegs->Rcx); __cpuidex(registers, leaf, subLeaf); switch (leaf) { case CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS: // // Indicate presence of a hypervisor by setting the bit that are // reserved for use by hypervisor to indicate guest status. See "CPUID // Fn0000_0001_ECX Feature Identifiers". // registers[2] |= CPUID_FN0000_0001_ECX_HYPERVISOR_PRESENT; break; case CPUID_HV_VENDOR_AND_MAX_FUNCTIONS: // // Return a maximum supported hypervisor CPUID leaf range and a vendor // ID signature as required by the spec. // registers[0] = CPUID_HV_MAX; registers[1] = 'pmiS'; // "SimpleSvm " registers[2] = 'vSel'; registers[3] = ' m'; break; case CPUID_HV_INTERFACE: // // Return non Hv#1 value. This indicate that the SimpleSvm does NOT // conform to the Microsoft hypervisor interface. // registers[0] = '0#vH'; // Hv#0 registers[1] = registers[2] = registers[3] = 0; break; case CPUID_UNLOAD_SIMPLE_SVM: if (subLeaf == CPUID_UNLOAD_SIMPLE_SVM) { // // Unload itself if the request is from the kernel mode. // attribute.AsUInt16 = VpData->GuestVmcb.StateSaveArea.SsAttrib; if (attribute.Fields.Dpl == DPL_SYSTEM) { GuestContext->ExitVm = TRUE; } } break; default: break; } // // Update guest's GPRs with results. // GuestContext->VpRegs->Rax = registers[0]; GuestContext->VpRegs->Rbx = registers[1]; GuestContext->VpRegs->Rcx = registers[2]; GuestContext->VpRegs->Rdx = registers[3]; // // Debug prints results. Very important to note that any use of API from // the host context is unsafe and absolutely avoided, unless the API is // documented to be accessible on IRQL IPI_LEVEL+. This is because // interrupts are disabled when host code is running, and IPI is not going // to be delivered when it is issued. // // This code is not exception and violating this rule. The reasons for this // code are to demonstrate a bad example, and simply show that the SimpleSvm // is functioning for a test purpose. // if (KeGetCurrentIrql() <= DISPATCH_LEVEL) { SvDebugPrint("CPUID: %08x-%08x : %08x %08x %08x %08x\n", leaf, subLeaf, registers[0], registers[1], registers[2], registers[3]); } // // Then, advance RIP to "complete" the instruction. // VpData->GuestVmcb.StateSaveArea.Rip = VpData->GuestVmcb.ControlArea.NRip; } /*! @brief Handles #VMEXIT due to execution of the WRMSR and RDMSR instructions. @details This protects EFER.SVME from being cleared by the guest by injecting #GP when it is about to be cleared. For other MSR access, it passes-through. @param[in,out] VpData - Per processor data. @param[in,out] GuestContext - Guest's GPRs. */ _IRQL_requires_same_ static VOID SvHandleMsrAccess ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData, _Inout_ PGUEST_CONTEXT GuestContext ) { ULARGE_INTEGER value; UINT32 msr; BOOLEAN writeAccess; msr = GuestContext->VpRegs->Rcx & MAXUINT32; writeAccess = (VpData->GuestVmcb.ControlArea.ExitInfo1 != 0); // // If IA32_MSR_EFER is accessed for write, we must protect the EFER_SVME bit // from being cleared. // if (msr == IA32_MSR_EFER) { // // #VMEXIT on IA32_MSR_EFER access should only occur on write access. // NT_ASSERT(writeAccess != FALSE); value.LowPart = GuestContext->VpRegs->Rax & MAXUINT32; value.HighPart = GuestContext->VpRegs->Rdx & MAXUINT32; if ((value.QuadPart & EFER_SVME) == 0) { // // Inject #GP if the guest attempts to clear the SVME bit. Protection of // this bit is required because clearing the bit while guest is running // leads to undefined behavior. // SvInjectGeneralProtectionException(VpData); } // // Otherwise, update the MSR as requested. Important to note that the value // should be checked not to allow any illegal values, and inject #GP as // needed. Otherwise, the hypervisor attempts to resume the guest with an // illegal EFER and immediately receives #VMEXIT due to VMEXIT_INVALID, // which in our case, results in a bug check. See "Extended Feature Enable // Register (EFER)" for what values are allowed. // // This code does not implement the check intentionally, for simplicity. // VpData->GuestVmcb.StateSaveArea.Efer = value.QuadPart; } else { // // If the MSR being accessed is not IA32_MSR_EFER, assert that #VMEXIT // can only occur on access to MSR outside the ranges controlled with // the MSR permissions map. This is true because the map is configured // not to intercept any MSR access but IA32_MSR_EFER. See // "MSR Ranges Covered by MSRPM" in "MSR Intercepts" for the MSR ranges // controlled by the map. // // Note that VMware Workstation has a bug that access to unimplemented // MSRs unconditionally causes #VMEXIT ignoring bits in the MSR // permissions map. This can be tested by reading MSR zero, for example. // NT_ASSERT(((msr > 0x00001fff) && (msr < 0xc0000000)) || ((msr > 0xc0001fff) && (msr < 0xc0010000)) || (msr > 0xc0011fff)); // // Execute WRMSR or RDMSR on behalf of the guest. Important that this // can cause bug check when the guest tries to access unimplemented MSR // *even within the SEH block* because the below WRMSR or RDMSR raises // #GP and are not protected by the SEH block (or cannot be protected // either as this code run outside the thread stack region Windows // requires to proceed SEH). Hypervisors typically handle this by noop-ing // WRMSR and returning zero for RDMSR with non-architecturally defined // MSRs. Alternatively, one can probe which MSRs should cause #GP prior // to installation of a hypervisor and the hypervisor can emulate the // results. // if (writeAccess != FALSE) { value.LowPart = GuestContext->VpRegs->Rax & MAXUINT32; value.HighPart = GuestContext->VpRegs->Rdx & MAXUINT32; __writemsr(msr, value.QuadPart); } else { value.QuadPart = __readmsr(msr); GuestContext->VpRegs->Rax = value.LowPart; GuestContext->VpRegs->Rdx = value.HighPart; } } // // Then, advance RIP to "complete" the instruction. // VpData->GuestVmcb.StateSaveArea.Rip = VpData->GuestVmcb.ControlArea.NRip; } /*! @brief Handles #VMEXIT due to execution of the VMRUN instruction. @details This function always injects #GP to the guest. @param[in,out] VpData - Per processor data. @param[in,out] GuestContext - Guest's GPRs. */ _IRQL_requires_same_ static VOID SvHandleVmrun ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData, _Inout_ PGUEST_CONTEXT GuestContext ) { UNREFERENCED_PARAMETER(GuestContext); SvInjectGeneralProtectionException(VpData); } /*! @brief C-level entry point of the host code called from SvLaunchVm. @details This function loads save host state first, and then, handles #VMEXIT which may or may not change guest's state via VpData or GuestRegisters. Interrupts are disabled when this function is called due to the cleared GIF. Not all host state are loaded yet, so do it with the VMLOAD instruction. If the #VMEXIT handler detects a request to unload the hypervisor, this function loads guest state, disables SVM and returns to execution flow where the #VMEXIT triggered. @param[in,out] VpData - Per processor data. @param[in,out] GuestRegisters - Guest's GPRs. @result TRUE when virtualization is terminated; otherwise FALSE. */ _IRQL_requires_same_ EXTERN_C BOOLEAN NTAPI SvHandleVmExit ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData, _Inout_ PGUEST_REGISTERS GuestRegisters ) { GUEST_CONTEXT guestContext; KIRQL oldIrql; guestContext.VpRegs = GuestRegisters; guestContext.ExitVm = FALSE; // // Load some host state that are not loaded on #VMEXIT. // __svm_vmload(VpData->HostStackLayout.HostVmcbPa); NT_ASSERT(VpData->HostStackLayout.Reserved1 == MAXUINT64); // // Raise the IRQL to the DISPATCH_LEVEL level. This has no actual effect since // interrupts are disabled at #VMEXI but warrants bug check when some of // kernel API that are not usable on this context is called with Driver // Verifier. This protects developers from accidentally writing such #VMEXIT // handling code. This should actually raise IRQL to HIGH_LEVEL to represent // this running context better, but our Logger code is not designed to run at // that level unfortunately. Finally, note that this API is a thin wrapper // of mov-to-CR8 on x64 and safe to call on this context. // oldIrql = KeGetCurrentIrql(); if (oldIrql < DISPATCH_LEVEL) { KeRaiseIrqlToDpcLevel(); } // // Guest's RAX is overwritten by the host's value on #VMEXIT and saved in // the VMCB instead. Reflect the guest RAX to the context. // GuestRegisters->Rax = VpData->GuestVmcb.StateSaveArea.Rax; // // Update the _KTRAP_FRAME structure values in hypervisor stack, so that // Windbg can reconstruct call stack of the guest during debug session. // This is optional but very useful thing to do for debugging. // VpData->HostStackLayout.TrapFrame.Rsp = VpData->GuestVmcb.StateSaveArea.Rsp; VpData->HostStackLayout.TrapFrame.Rip = VpData->GuestVmcb.ControlArea.NRip; // // Handle #VMEXIT according with its reason. // switch (VpData->GuestVmcb.ControlArea.ExitCode) { case VMEXIT_CPUID: SvHandleCpuid(VpData, &guestContext); break; case VMEXIT_MSR: SvHandleMsrAccess(VpData, &guestContext); break; case VMEXIT_VMRUN: SvHandleVmrun(VpData, &guestContext); break; default: SV_DEBUG_BREAK(); #pragma prefast(disable : __WARNING_USE_OTHER_FUNCTION, "Unrecoverble path.") KeBugCheck(MANUALLY_INITIATED_CRASH); } // // Again, no effect to change IRQL but restoring it here since a #VMEXIT // handler where the developers most likely call the kernel API inadvertently // is already executed. // if (oldIrql < DISPATCH_LEVEL) { KeLowerIrql(oldIrql); } // // Terminate the SimpleSvm hypervisor if requested. // if (guestContext.ExitVm != FALSE) { NT_ASSERT(VpData->GuestVmcb.ControlArea.ExitCode == VMEXIT_CPUID); // // Set return values of CPUID instruction as follows: // RBX = An address to return // RCX = A stack pointer to restore // EDX:EAX = An address of per processor data to be freed by the caller // guestContext.VpRegs->Rax = reinterpret_cast<UINT64>(VpData) & MAXUINT32; guestContext.VpRegs->Rbx = VpData->GuestVmcb.ControlArea.NRip; guestContext.VpRegs->Rcx = VpData->GuestVmcb.StateSaveArea.Rsp; guestContext.VpRegs->Rdx = reinterpret_cast<UINT64>(VpData) >> 32; // // Load guest state (currently host state is loaded). // __svm_vmload(MmGetPhysicalAddress(&VpData->GuestVmcb).QuadPart); // // Set the global interrupt flag (GIF) but still disable interrupts by // clearing IF. GIF must be set to return to the normal execution, but // interruptions are not desirable until SVM is disabled as it would // execute random kernel-code in the host context. // _disable(); __svm_stgi(); // // Disable SVM, and restore the guest RFLAGS. This may enable interrupts. // Some of arithmetic flags are destroyed by the subsequent code. // __writemsr(IA32_MSR_EFER, __readmsr(IA32_MSR_EFER) & ~EFER_SVME); __writeeflags(VpData->GuestVmcb.StateSaveArea.Rflags); goto Exit; } // // Reflect potentially updated guest's RAX to VMCB. Again, unlike other GPRs, // RAX is loaded from VMCB on VMRUN. // VpData->GuestVmcb.StateSaveArea.Rax = guestContext.VpRegs->Rax; Exit: NT_ASSERT(VpData->HostStackLayout.Reserved1 == MAXUINT64); return guestContext.ExitVm; } /*! @brief Returns attributes of a segment specified by the segment selector. @details This function locates a segment descriptor from the segment selector and the GDT base, extracts attributes of the segment, and returns it. The returned value is the same as what the "dg" command of Windbg shows as "Flags". Here is an example output with 0x18 of the selector: ---- 0: kd> dg 18 P Si Gr Pr Lo Sel Base Limit Type l ze an es ng Flags ---- ----------------- ----------------- ---------- - -- -- -- -- -------- 0018 00000000`00000000 00000000`00000000 Data RW Ac 0 Bg By P Nl 00000493 ---- @param[in] SegmentSelector - A segment selector to get attributes of a corresponding descriptor. @param[in] GdtBase - A base address of GDT. @result Attributes of the segment. */ _IRQL_requires_same_ _Check_return_ static UINT16 SvGetSegmentAccessRight ( _In_ UINT16 SegmentSelector, _In_ ULONG_PTR GdtBase ) { PSEGMENT_DESCRIPTOR descriptor; SEGMENT_ATTRIBUTE attribute; // // Get a segment descriptor corresponds to the specified segment selector. // descriptor = reinterpret_cast<PSEGMENT_DESCRIPTOR>( GdtBase + (SegmentSelector & ~RPL_MASK)); // // Extract all attribute fields in the segment descriptor to a structure // that describes only attributes (as opposed to the segment descriptor // consists of multiple other fields). // attribute.Fields.Type = descriptor->Fields.Type; attribute.Fields.System = descriptor->Fields.System; attribute.Fields.Dpl = descriptor->Fields.Dpl; attribute.Fields.Present = descriptor->Fields.Present; attribute.Fields.Avl = descriptor->Fields.Avl; attribute.Fields.LongMode = descriptor->Fields.LongMode; attribute.Fields.DefaultBit = descriptor->Fields.DefaultBit; attribute.Fields.Granularity = descriptor->Fields.Granularity; attribute.Fields.Reserved1 = 0; return attribute.AsUInt16; } /*! @brief Tests whether the SimpleSvm hypervisor is installed. @details This function checks a result of CPUID leaf 40000000h, which should return a vendor name of the hypervisor if any of those who implement the Microsoft Hypervisor interface is installed. If the SimpleSvm hypervisor is installed, this should return "SimpleSvm", and if no hypervisor is installed, it the result of CPUID is undefined. For more details of the interface, see "Requirements for implementing the Microsoft Hypervisor interface" https://msdn.microsoft.com/en-us/library/windows/hardware/Dn613994(v=vs.85).aspx @result TRUE when the SimpleSvm is installed; otherwise, FALSE. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ _Check_return_ static BOOLEAN SvIsSimpleSvmHypervisorInstalled ( VOID ) { int registers[4]; // EAX, EBX, ECX, and EDX char vendorId[13]; // // When the SimpleSvm hypervisor is installed, CPUID leaf 40000000h will // return "SimpleSvm " as the vendor name. // __cpuid(registers, CPUID_HV_VENDOR_AND_MAX_FUNCTIONS); RtlCopyMemory(vendorId + 0, &registers[1], sizeof(registers[1])); RtlCopyMemory(vendorId + 4, &registers[2], sizeof(registers[2])); RtlCopyMemory(vendorId + 8, &registers[3], sizeof(registers[3])); vendorId[12] = ANSI_NULL; return (strcmp(vendorId, "SimpleSvm ") == 0); } /*! @brief Virtualize the current processor. @details This function enables SVM, initialize VMCB with the current processor state, and enters the guest mode on the current processor. @param[in,out] VpData - The address of per processor data. @param[in] SharedVpData - The address of share data. @param[in] ContextRecord - The address of CONETEXT to use as an initial context of the processor after it is virtualized. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ static VOID SvPrepareForVirtualization ( _Inout_ PVIRTUAL_PROCESSOR_DATA VpData, _In_ PSHARED_VIRTUAL_PROCESSOR_DATA SharedVpData, _In_ const CONTEXT* ContextRecord ) { DESCRIPTOR_TABLE_REGISTER gdtr, idtr; PHYSICAL_ADDRESS guestVmcbPa, hostVmcbPa, hostStateAreaPa, pml4BasePa, msrpmPa; // // Capture the current GDTR and IDTR to use as initial values of the guest // mode. // _sgdt(&gdtr); __sidt(&idtr); guestVmcbPa = MmGetPhysicalAddress(&VpData->GuestVmcb); hostVmcbPa = MmGetPhysicalAddress(&VpData->HostVmcb); hostStateAreaPa = MmGetPhysicalAddress(&VpData->HostStateArea); pml4BasePa = MmGetPhysicalAddress(&SharedVpData->Pml4Entries); msrpmPa = MmGetPhysicalAddress(SharedVpData->MsrPermissionsMap); // // Configure to trigger #VMEXIT with CPUID and VMRUN instructions. CPUID is // intercepted to present existence of the SimpleSvm hypervisor and provide // an interface to ask it to unload itself. // // VMRUN is intercepted because it is required by the processor to enter the // guest mode; otherwise, #VMEXIT occurs due to VMEXIT_INVALID when a // processor attempts to enter the guest mode. See "Canonicalization and // Consistency Checks" on "VMRUN Instruction". // VpData->GuestVmcb.ControlArea.InterceptMisc1 |= SVM_INTERCEPT_MISC1_CPUID; VpData->GuestVmcb.ControlArea.InterceptMisc2 |= SVM_INTERCEPT_MISC2_VMRUN; // // Also, configure to trigger #VMEXIT on MSR access as configured by the // MSRPM. In our case, write to IA32_MSR_EFER is intercepted. // VpData->GuestVmcb.ControlArea.InterceptMisc1 |= SVM_INTERCEPT_MISC1_MSR_PROT; VpData->GuestVmcb.ControlArea.MsrpmBasePa = msrpmPa.QuadPart; // // Specify guest's address space ID (ASID). TLB is maintained by the ID for // guests. Use the same value for all processors since all of them run a // single guest in our case. Use 1 as the most likely supported ASID by the // processor. The actual the supported number of ASID can be obtained with // CPUID. See "CPUID Fn8000_000A_EBX SVM Revision and Feature // Identification". Zero of ASID is reserved and illegal. // VpData->GuestVmcb.ControlArea.GuestAsid = 1; // // Enable Nested Page Tables. By enabling this, the processor performs the // nested page walk, that involves with an additional page walk to translate // a guest physical address to a system physical address. An address of // nested page tables is specified by the NCr3 field of VMCB. // // We have already build the nested page tables with SvBuildNestedPageTables. // // Note that our hypervisor does not trigger any additional #VMEXIT due to // the use of Nested Page Tables since all physical addresses from 0-512 GB // are configured to be accessible from the guest. // VpData->GuestVmcb.ControlArea.NpEnable |= SVM_NP_ENABLE_NP_ENABLE; VpData->GuestVmcb.ControlArea.NCr3 = pml4BasePa.QuadPart; // // Set up the initial guest state based on the current system state. Those // values are loaded into the processor as guest state when the VMRUN // instruction is executed. // VpData->GuestVmcb.StateSaveArea.GdtrBase = gdtr.Base; VpData->GuestVmcb.StateSaveArea.GdtrLimit = gdtr.Limit; VpData->GuestVmcb.StateSaveArea.IdtrBase = idtr.Base; VpData->GuestVmcb.StateSaveArea.IdtrLimit = idtr.Limit; VpData->GuestVmcb.StateSaveArea.CsLimit = GetSegmentLimit(ContextRecord->SegCs); VpData->GuestVmcb.StateSaveArea.DsLimit = GetSegmentLimit(ContextRecord->SegDs); VpData->GuestVmcb.StateSaveArea.EsLimit = GetSegmentLimit(ContextRecord->SegEs); VpData->GuestVmcb.StateSaveArea.SsLimit = GetSegmentLimit(ContextRecord->SegSs); VpData->GuestVmcb.StateSaveArea.CsSelector = ContextRecord->SegCs; VpData->GuestVmcb.StateSaveArea.DsSelector = ContextRecord->SegDs; VpData->GuestVmcb.StateSaveArea.EsSelector = ContextRecord->SegEs; VpData->GuestVmcb.StateSaveArea.SsSelector = ContextRecord->SegSs; VpData->GuestVmcb.StateSaveArea.CsAttrib = SvGetSegmentAccessRight(ContextRecord->SegCs, gdtr.Base); VpData->GuestVmcb.StateSaveArea.DsAttrib = SvGetSegmentAccessRight(ContextRecord->SegDs, gdtr.Base); VpData->GuestVmcb.StateSaveArea.EsAttrib = SvGetSegmentAccessRight(ContextRecord->SegEs, gdtr.Base); VpData->GuestVmcb.StateSaveArea.SsAttrib = SvGetSegmentAccessRight(ContextRecord->SegSs, gdtr.Base); VpData->GuestVmcb.StateSaveArea.Efer = __readmsr(IA32_MSR_EFER); VpData->GuestVmcb.StateSaveArea.Cr0 = __readcr0(); VpData->GuestVmcb.StateSaveArea.Cr2 = __readcr2(); VpData->GuestVmcb.StateSaveArea.Cr3 = __readcr3(); VpData->GuestVmcb.StateSaveArea.Cr4 = __readcr4(); VpData->GuestVmcb.StateSaveArea.Rflags = ContextRecord->EFlags; VpData->GuestVmcb.StateSaveArea.Rsp = ContextRecord->Rsp; VpData->GuestVmcb.StateSaveArea.Rip = ContextRecord->Rip; VpData->GuestVmcb.StateSaveArea.GPat = __readmsr(IA32_MSR_PAT); // // Save some of the current state on VMCB. Some of those states are: // - FS, GS, TR, LDTR (including all hidden state) // - KernelGsBase // - STAR, LSTAR, CSTAR, SFMASK // - SYSENTER_CS, SYSENTER_ESP, SYSENTER_EIP // See "VMSAVE and VMLOAD Instructions" for mode details. // // Those are restored to the processor right before #VMEXIT with the VMLOAD // instruction so that the guest can start its execution with saved state, // and also, re-saved to the VMCS with right after #VMEXIT with the VMSAVE // instruction so that the host (hypervisor) do not destroy guest's state. // __svm_vmsave(guestVmcbPa.QuadPart); // // Store data to stack so that the host (hypervisor) can use those values. // VpData->HostStackLayout.Reserved1 = MAXUINT64; VpData->HostStackLayout.SharedVpData = SharedVpData; VpData->HostStackLayout.Self = VpData; VpData->HostStackLayout.HostVmcbPa = hostVmcbPa.QuadPart; VpData->HostStackLayout.GuestVmcbPa = guestVmcbPa.QuadPart; // // Set an address of the host state area to VM_HSAVE_PA MSR. The processor // saves some of the current state on VMRUN and loads them on #VMEXIT. See // "VM_HSAVE_PA MSR (C001_0117h)". // __writemsr(SVM_MSR_VM_HSAVE_PA, hostStateAreaPa.QuadPart); // // Also, save some of the current state to VMCB for the host. This is loaded // after #VMEXIT to reproduce the current state for the host (hypervisor). // __svm_vmsave(hostVmcbPa.QuadPart); } /*! @brief Virtualize the current processor. @details This function enables SVM, initialize VMCB with the current processor state, and enters the guest mode on the current processor. @param[in] Context - A pointer of share data. @result STATUS_SUCCESS on success; otherwise, an appropriate error code. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ _Check_return_ static NTSTATUS SvVirtualizeProcessor ( _In_opt_ PVOID Context ) { NTSTATUS status; PSHARED_VIRTUAL_PROCESSOR_DATA sharedVpData; PVIRTUAL_PROCESSOR_DATA vpData; PCONTEXT contextRecord; SV_DEBUG_BREAK(); vpData = nullptr; NT_ASSERT(ARGUMENT_PRESENT(Context)); _Analysis_assume_(ARGUMENT_PRESENT(Context)); contextRecord = static_cast<PCONTEXT>(ExAllocatePoolWithTag( NonPagedPool, sizeof(*contextRecord), 'MVSS')); if (contextRecord == nullptr) { SvDebugPrint("Insufficient memory.\n"); status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } // // Allocate per processor data. // #pragma prefast(push) #pragma prefast(disable : __WARNING_MEMORY_LEAK, "Ownership is taken on success.") vpData = static_cast<PVIRTUAL_PROCESSOR_DATA>( SvAllocatePageAlingedPhysicalMemory(sizeof(VIRTUAL_PROCESSOR_DATA))); #pragma prefast(pop) if (vpData == nullptr) { SvDebugPrint("Insufficient memory.\n"); status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } // // Capture the current RIP, RSP, RFLAGS, and segment selectors. This // captured state is used as an initial state of the guest mode; therefore // when virtualization starts by the later call of SvLaunchVm, a processor // resume its execution at this location and state. // RtlCaptureContext(contextRecord); // // First time of this execution, the SimpleSvm hypervisor is not installed // yet. Therefore, the branch is taken, and virtualization is attempted. // // At the second execution of here, after SvLaunchVm virtualized the // processor, SvIsSimpleSvmHypervisorInstalled returns TRUE, and this // function exits with STATUS_SUCCESS. // if (SvIsSimpleSvmHypervisorInstalled() == FALSE) { SvDebugPrint("Attempting to virtualize the processor.\n"); sharedVpData = static_cast<PSHARED_VIRTUAL_PROCESSOR_DATA>(Context); // // Enable SVM by setting EFER.SVME. It has already been verified that this // bit was writable with SvIsSvmSupported. // __writemsr(IA32_MSR_EFER, __readmsr(IA32_MSR_EFER) | EFER_SVME); // // Set up VMCB, the structure describes the guest state and what events // within the guest should be intercepted, ie, triggers #VMEXIT. // SvPrepareForVirtualization(vpData, sharedVpData, contextRecord); // // Switch to the host RSP to run as the host (hypervisor), and then // enters loop that executes code as a guest until #VMEXIT happens and // handles #VMEXIT as the host. // // This function should never return to here. // SvLaunchVm(&vpData->HostStackLayout.GuestVmcbPa); SV_DEBUG_BREAK(); KeBugCheck(MANUALLY_INITIATED_CRASH); } SvDebugPrint("The processor has been virtualized.\n"); status = STATUS_SUCCESS; Exit: if (contextRecord != nullptr) { ExFreePoolWithTag(contextRecord, 'MVSS'); } if ((!NT_SUCCESS(status)) && (vpData != nullptr)) { // // Frees per processor data if allocated and this function is // unsuccessful. // SvFreePageAlingedPhysicalMemory(vpData); } return status; } /*! @brief Execute a callback on all processors one-by-one. @details This function execute Callback with Context as a parameter for each processor on the current IRQL. If the callback returned non-STATUS_SUCCESS value or any error occurred, this function stops execution of the callback and returns the error code. When NumOfProcessorCompleted is not NULL, this function always set a number of processors that successfully executed the callback. @param[in] Callback - A function to execute on all processors. @param[in] Context - A parameter to pass to the callback. @param[out] NumOfProcessorCompleted - A pointer to receive a number of processors executed the callback successfully. @result STATUS_SUCCESS when Callback executed and returned STATUS_SUCCESS on all processors; otherwise, an appropriate error code. */ _IRQL_requires_max_(APC_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ _Check_return_ static NTSTATUS SvExecuteOnEachProcessor ( _In_ NTSTATUS (*Callback)(PVOID), _In_opt_ PVOID Context, _Out_opt_ PULONG NumOfProcessorCompleted ) { NTSTATUS status; ULONG i, numOfProcessors; PROCESSOR_NUMBER processorNumber; GROUP_AFFINITY affinity, oldAffinity; status = STATUS_SUCCESS; // // Get a number of processors on this system. // numOfProcessors = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); for (i = 0; i < numOfProcessors; i++) { // // Convert from an index to a processor number. // status = KeGetProcessorNumberFromIndex(i, &processorNumber); if (!NT_SUCCESS(status)) { goto Exit; } // // Switch execution of this code to a processor #i. // affinity.Group = processorNumber.Group; affinity.Mask = 1ULL << processorNumber.Number; affinity.Reserved[0] = affinity.Reserved[1] = affinity.Reserved[2] = 0; KeSetSystemGroupAffinityThread(&affinity, &oldAffinity); // // Execute the callback. // status = Callback(Context); // // Revert the previously executed processor. // KeRevertToUserGroupAffinityThread(&oldAffinity); // // Exit if the callback returned error. // if (!NT_SUCCESS(status)) { goto Exit; } } Exit: // // i must be the same as the number of processors on the system when this // function returns STATUS_SUCCESS; // NT_ASSERT(!NT_SUCCESS(status) || (i == numOfProcessors)); // // Set a number of processors that successfully executed callback if the // out parameter is present. // if (ARGUMENT_PRESENT(NumOfProcessorCompleted)) { *NumOfProcessorCompleted = i; } return status; } /*! @brief De-virtualize the current processor if virtualized. @details This function asks SimpleSVM hypervisor to deactivate itself through CPUID with a back-door function id and frees per processor data if it is returned. If the SimpleSvm is not installed, this function does nothing. @param[in] Context - An out pointer to receive an address of shared data. @result Always STATUS_SUCCESS. */ _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ _Check_return_ static NTSTATUS SvDevirtualizeProcessor ( _In_opt_ PVOID Context ) { int registers[4]; // EAX, EBX, ECX, and EDX UINT64 high, low; PVIRTUAL_PROCESSOR_DATA vpData; PSHARED_VIRTUAL_PROCESSOR_DATA* sharedVpDataPtr; if (!ARGUMENT_PRESENT(Context)) { goto Exit; } // // Ask SimpleSVM hypervisor to deactivate itself. If the hypervisor is // installed, this ECX is set to 'SSVM', and EDX:EAX indicates an address // of per processor data to be freed. // __cpuidex(registers, CPUID_UNLOAD_SIMPLE_SVM, CPUID_UNLOAD_SIMPLE_SVM); if (registers[2] != 'SSVM') { goto Exit; } SvDebugPrint("The processor has been de-virtualized.\n"); // // Get an address of per processor data indicated by EDX:EAX. // high = registers[3]; low = registers[0] & MAXUINT32; vpData = reinterpret_cast<PVIRTUAL_PROCESSOR_DATA>(high << 32 | low); NT_ASSERT(vpData->HostStackLayout.Reserved1 == MAXUINT64); // // Save an address of shared data, then free per processor data. // sharedVpDataPtr = static_cast<PSHARED_VIRTUAL_PROCESSOR_DATA*>(Context); *sharedVpDataPtr = vpData->HostStackLayout.SharedVpData; SvFreePageAlingedPhysicalMemory(vpData); Exit: return STATUS_SUCCESS; } /*! @brief De-virtualize all virtualized processors. @details This function execute a callback to de-virtualize a processor on all processors, and frees shared data when the callback returned its pointer from a hypervisor. */ _IRQL_requires_max_(APC_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ static VOID SvDevirtualizeAllProcessors ( VOID ) { PSHARED_VIRTUAL_PROCESSOR_DATA sharedVpData; sharedVpData = nullptr; // // De-virtualize all processors and free shared data when returned. // NT_VERIFY(NT_SUCCESS(SvExecuteOnEachProcessor(SvDevirtualizeProcessor, &sharedVpData, nullptr))); if (sharedVpData != nullptr) { SvFreeContiguousMemory(sharedVpData->MsrPermissionsMap); SvFreePageAlingedPhysicalMemory(sharedVpData); } } /*! @brief Build the MSR permissions map (MSRPM). @details This function sets up MSRPM to intercept to IA32_MSR_EFER, as suggested in "Extended Feature Enable Register (EFER)" ---- Secure Virtual Machine Enable (SVME) Bit Bit 12, read/write. Enables the SVM extensions. (...) The effect of turning off EFER.SVME while a guest is running is undefined; therefore, the VMM should always prevent guests from writing EFER. ---- Each MSR is controlled by two bits in the MSRPM. The LSB of the two bits controls read access to the MSR and the MSB controls write access. A value of 1 indicates that the operation is intercepted. This function locates an offset for IA32_MSR_EFER and sets the MSB bit. For details of logic, see "MSR Intercepts". @param[in,out] MsrPermissionsMap - The MSRPM to set up. */ _IRQL_requires_same_ static VOID SvBuildMsrPermissionsMap ( _Inout_ PVOID MsrPermissionsMap ) { static const UINT32 BITS_PER_MSR = 2; static const UINT32 SECOND_MSR_RANGE_BASE = 0xc0000000; static const UINT32 SECOND_MSRPM_OFFSET = 0x800 * CHAR_BIT; RTL_BITMAP bitmapHeader; ULONG offsetFrom2ndBase, offset; // // Setup and clear all bits, indicating no MSR access should be intercepted. // RtlInitializeBitMap(&bitmapHeader, static_cast<PULONG>(MsrPermissionsMap), SVM_MSR_PERMISSIONS_MAP_SIZE * CHAR_BIT ); RtlClearAllBits(&bitmapHeader); // // Compute an offset from the second MSR permissions map offset (0x800) for // IA32_MSR_EFER in bits. Then, add an offset until the second MSR // permissions map. // offsetFrom2ndBase = (IA32_MSR_EFER - SECOND_MSR_RANGE_BASE) * BITS_PER_MSR; offset = SECOND_MSRPM_OFFSET + offsetFrom2ndBase; // // Set the MSB bit indicating write accesses to the MSR should be intercepted. // RtlSetBits(&bitmapHeader, offset + 1, 1); } /*! @brief Build pass-through style page tables used in nested paging. @details This function build page tables used in Nested Page Tables. The page tables are used to translate from a guest physical address to a system physical address and pointed by the NCr3 field of VMCB, like the traditional page tables are pointed by CR3. The nested page tables built in this function are set to translate a guest physical address to the same system physical address. For example, guest physical address 0x1000 is translated into system physical address 0x1000. In order to save memory to build nested page tables, 2MB large pages are used (as opposed to the standard pages that describe translation only for 4K granularity. Also, only up to 512 GB of translation is built. 1GB huge pages are not used due to VMware not supporting this feature. @param[out] SharedVpData - Out buffer to build nested page tables. */ _IRQL_requires_same_ static VOID SvBuildNestedPageTables ( _Out_ PSHARED_VIRTUAL_PROCESSOR_DATA SharedVpData ) { ULONG64 pdpBasePa, pdeBasePa, translationPa; // // Build only one PML4 entry. This entry has subtables that control up to // 512GB physical memory. PFN points to a base physical address of the page // directory pointer table. // pdpBasePa = MmGetPhysicalAddress(&SharedVpData->PdpEntries).QuadPart; SharedVpData->Pml4Entries[0].Fields.PageFrameNumber = pdpBasePa >> PAGE_SHIFT; // // The US (User) bit of all nested page table entries to be translated // without #VMEXIT, as all guest accesses are treated as user accesses at // the nested level. Also, the RW (Write) bit of nested page table entries // that corresponds to guest page tables must be 1 since all guest page // table accesses are threated as write access. See "Nested versus Guest // Page Faults, Fault Ordering" for more details. // // Nested page tables built here set 1 to those bits for all entries, so // that all translation can complete without triggering #VMEXIT. This does // not lower security since security checks are done twice independently: // based on guest page tables, and nested page tables. See "Nested versus // Guest Page Faults, Fault Ordering" for more details. // SharedVpData->Pml4Entries[0].Fields.Valid = 1; SharedVpData->Pml4Entries[0].Fields.Write = 1; SharedVpData->Pml4Entries[0].Fields.User = 1; // // One PML4 entry controls 512 page directory pointer entires. // for (ULONG64 i = 0; i < 512; i++) { // // PFN points to a base physical address of the page directory table. // pdeBasePa = MmGetPhysicalAddress(&SharedVpData->PdeEntries[i][0]).QuadPart; SharedVpData->PdpEntries[i].Fields.PageFrameNumber = pdeBasePa >> PAGE_SHIFT; SharedVpData->PdpEntries[i].Fields.Valid = 1; SharedVpData->PdpEntries[i].Fields.Write = 1; SharedVpData->PdpEntries[i].Fields.User = 1; // // One page directory entry controls 512 page directory entries. // // We do not explicitly configure PAT in the NPT entry. The consequences // of this are: 1) pages whose PAT (Page Attribute Table) type is the // Write-Combining (WC) memory type could be treated as the // Write-Combining Plus (WC+) while it should be WC when the MTRR type is // either Write Protect (WP), Writethrough (WT) or Writeback (WB), and // 2) pages whose PAT type is Uncacheable Minus (UC-) could be treated // as Cache Disabled (CD) while it should be WC, when MTRR type is WC. // // While those are not desirable, this is acceptable given that 1) only // introduces additional cache snooping and associated performance // penalty, which would not be significant since WC+ still lets // processors combine multiple writes into one and avoid large // performance penalty due to frequent writes to memory without caching. // 2) might be worse but I have not seen MTRR ranges configured as WC // on testing, hence the unintentional UC- will just results in the same // effective memory type as what would be with UC. // // See "Memory Types" (7.4), for details of memory types, // "PAT-Register PA-Field Indexing", "Combining Guest and Host PAT Types", // and "Combining PAT and MTRR Types" for how the effective memory type // is determined based on Guest PAT type, Host PAT type, and the MTRR // type. // // The correct approach may be to look up the guest PTE and copy the // caching related bits (PAT, PCD, and PWT) when constructing NTP // entries for non RAM regions, so the combined PAT will always be the // same as the guest PAT type. This may be done when any issue manifests // with the current implementation. // for (ULONG64 j = 0; j < 512; j++) { // // PFN points to a base physical address of system physical address // to be translated from a guest physical address. Set the PS // (LargePage) bit to indicate that this is a large page and no // subtable exists. // translationPa = (i * 512) + j; SharedVpData->PdeEntries[i][j].Fields.PageFrameNumber = translationPa; SharedVpData->PdeEntries[i][j].Fields.Valid = 1; SharedVpData->PdeEntries[i][j].Fields.Write = 1; SharedVpData->PdeEntries[i][j].Fields.User = 1; SharedVpData->PdeEntries[i][j].Fields.LargePage = 1; } } } /*! @brief Test whether the current processor support the SVM feature. @details This function tests whether the current processor has enough features to run SimpleSvm, especially about SVM features. @result TRUE if the processor supports the SVM feature; otherwise, FALSE. */ _IRQL_requires_same_ _Check_return_ static BOOLEAN SvIsSvmSupported ( VOID ) { BOOLEAN svmSupported; int registers[4]; // EAX, EBX, ECX, and EDX ULONG64 vmcr; svmSupported = FALSE; // // Test if the current processor is AMD one. An AMD processor should return // "AuthenticAMD" from CPUID function 0. See "Function 0h-Maximum Standard // Function Number and Vendor String". // __cpuid(registers, CPUID_MAX_STANDARD_FN_NUMBER_AND_VENDOR_STRING); if ((registers[1] != 'htuA') || (registers[3] != 'itne') || (registers[2] != 'DMAc')) { goto Exit; } // // Test if the SVM feature is supported by the current processor. See // "Enabling SVM" and "CPUID Fn8000_0001_ECX Feature Identifiers". // __cpuid(registers, CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS_EX); if ((registers[2] & CPUID_FN8000_0001_ECX_SVM) == 0) { goto Exit; } // // Test if the Nested Page Tables feature is supported by the current // processor. See "Enabling Nested Paging" and "CPUID Fn8000_000A_EDX SVM // Feature Identification". // __cpuid(registers, CPUID_SVM_FEATURES); if ((registers[3] & CPUID_FN8000_000A_EDX_NP) == 0) { goto Exit; } // // Test if the SVM feature can be enabled. When VM_CR.SVMDIS is set, // EFER.SVME cannot be 1; therefore, SVM cannot be enabled. When // VM_CR.SVMDIS is clear, EFER.SVME can be written normally and SVM can be // enabled. See "Enabling SVM". // vmcr = __readmsr(SVM_MSR_VM_CR); if ((vmcr & SVM_VM_CR_SVMDIS) != 0) { goto Exit; } svmSupported = TRUE; Exit: return svmSupported; } /*! @brief Virtualizes all processors on the system. @details This function attempts to virtualize all processors on the system, and returns STATUS_SUCCESS if all processors are successfully virtualized. If any processor is not virtualized, this function de-virtualizes all processors and returns an error code. @result STATUS_SUCCESS on success; otherwise, an appropriate error code. */ _IRQL_requires_max_(APC_LEVEL) _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_same_ _Check_return_ static NTSTATUS SvVirtualizeAllProcessors ( VOID ) { NTSTATUS status; PSHARED_VIRTUAL_PROCESSOR_DATA sharedVpData; ULONG numOfProcessorsCompleted; sharedVpData = nullptr; numOfProcessorsCompleted = 0; // // Test whether the current processor supports all required SVM features. If // not, exit as error. // if (SvIsSvmSupported() == FALSE) { SvDebugPrint("SVM is not fully supported on this processor.\n"); status = STATUS_HV_FEATURE_UNAVAILABLE; goto Exit; } // // Allocate a data structure shared across all processors. This data is // page tables used for Nested Page Tables. // #pragma prefast(push) #pragma prefast(disable : __WARNING_MEMORY_LEAK, "Ownership is taken on success.") sharedVpData = static_cast<PSHARED_VIRTUAL_PROCESSOR_DATA>( SvAllocatePageAlingedPhysicalMemory(sizeof(SHARED_VIRTUAL_PROCESSOR_DATA))); #pragma prefast(pop) if (sharedVpData == nullptr) { SvDebugPrint("Insufficient memory.\n"); status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } // // Allocate MSR permissions map (MSRPM) onto contiguous physical memory. // sharedVpData->MsrPermissionsMap = SvAllocateContiguousMemory( SVM_MSR_PERMISSIONS_MAP_SIZE); if (sharedVpData->MsrPermissionsMap == nullptr) { SvDebugPrint("Insufficient memory.\n"); status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } // // Build nested page table and MSRPM. // SvBuildNestedPageTables(sharedVpData); SvBuildMsrPermissionsMap(sharedVpData->MsrPermissionsMap); // // Execute SvVirtualizeProcessor on and virtualize each processor one-by-one. // How many processors were successfully virtualized is stored in the third // parameter. // // STATUS_SUCCESS is returned if all processor are successfully virtualized. // When any error occurs while virtualizing processors, this function does // not attempt to virtualize the rest of processor. Therefore, only part of // processors on the system may have been virtualized on error. In this case, // it is a caller's responsibility to clean-up (de-virtualize) such // processors. // status = SvExecuteOnEachProcessor(SvVirtualizeProcessor, sharedVpData, &numOfProcessorsCompleted); Exit: if (!NT_SUCCESS(status)) { // // On failure, after successful allocation of shared data. // if (numOfProcessorsCompleted != 0) { // // If one or more processors have already been virtualized, // de-virtualize any of those processors, and free shared data. // NT_ASSERT(sharedVpData != nullptr); SvDevirtualizeAllProcessors(); } else { // // If none of processors has not been virtualized, simply free // shared data. // if (sharedVpData != nullptr) { if (sharedVpData->MsrPermissionsMap != nullptr) { SvFreeContiguousMemory(sharedVpData->MsrPermissionsMap); } SvFreePageAlingedPhysicalMemory(sharedVpData); } } } return status; } /*! @brief An entry point of this driver. @param[in] DriverObject - A driver object. @param[in] RegistryPath - Unused. @result STATUS_SUCCESS on success; otherwise, an appropriate error code. */ _Use_decl_annotations_ EXTERN_C NTSTATUS DriverEntry ( PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath ) { NTSTATUS status; UNICODE_STRING objectName; OBJECT_ATTRIBUTES objectAttributes; PCALLBACK_OBJECT callbackObject; PVOID callbackRegistration; UNREFERENCED_PARAMETER(RegistryPath); SV_DEBUG_BREAK(); callbackRegistration = nullptr; DriverObject->DriverUnload = SvDriverUnload; // // Opts-in no-execute (NX) nonpaged pool when available for security. By // defining POOL_NX_OPTIN as 1 and calling this function, nonpaged pool // allocation by the ExAllocatePool family with the NonPagedPool flag // automatically allocates NX nonpaged pool on Windows 8 and later versions // of Windows, while on Windows 7 where NX nonpaged pool is unsupported, // executable nonpaged pool is returned as usual. // ExInitializeDriverRuntime(DrvRtPoolNxOptIn); // // Registers a power state callback (SvPowerCallbackRoutine) to handle // system sleep and resume to manage virtualization state. // // First, opens the \Callback\PowerState callback object provides // notification regarding power state changes. This is a system defined // callback object that was already created by Windows. To open a system // defined callback object, the Create parameter of ExCreateCallback must be // FALSE (and AllowMultipleCallbacks is ignore when the Create parameter is // FALSE). // objectName = RTL_CONSTANT_STRING(L"\\Callback\\PowerState"); objectAttributes = RTL_CONSTANT_OBJECT_ATTRIBUTES(&objectName, OBJ_CASE_INSENSITIVE); status = ExCreateCallback(&callbackObject, &objectAttributes, FALSE, TRUE); if (!NT_SUCCESS(status)) { SvDebugPrint("Failed to open the power state callback object.\n"); goto Exit; } // // Then, registers our callback. The open callback object must be // dereferenced. // callbackRegistration = ExRegisterCallback(callbackObject, SvPowerCallbackRoutine, nullptr); ObDereferenceObject(callbackObject); if (callbackRegistration == nullptr) { SvDebugPrint("Failed to register a power state callback.\n"); status = STATUS_UNSUCCESSFUL; goto Exit; } // // Virtualize all processors on the system. // status = SvVirtualizeAllProcessors(); Exit: if (NT_SUCCESS(status)) { // // On success, save the registration handle for un-registration. // NT_ASSERT(callbackRegistration); g_PowerCallbackRegistration = callbackRegistration; } else { // // On any failure, clean up stuff as needed. // if (callbackRegistration != nullptr) { ExUnregisterCallback(callbackRegistration); } } return status; } /*! @brief Driver unload callback. @details This function de-virtualize all processors on the system. @param[in] DriverObject - Unused. */ _Use_decl_annotations_ static VOID SvDriverUnload ( PDRIVER_OBJECT DriverObject ) { UNREFERENCED_PARAMETER(DriverObject); SV_DEBUG_BREAK(); // // Unregister the power state callback. // NT_ASSERT(g_PowerCallbackRegistration); ExUnregisterCallback(g_PowerCallbackRegistration); // // De-virtualize all processors on the system. // SvDevirtualizeAllProcessors(); } /*! @brief PowerState callback routine. @details This function de-virtualize all processors when the system is exiting system power state S0 (ie, the system is about to sleep etc), and virtualize all processors when the system has just reentered S0 (ie, the system has resume from sleep etc). Those operations are required because virtualization is cleared during sleep. For the meanings of parameters, see ExRegisterCallback in MSDN. @param[in] CallbackContext - Unused. @param[in] Argument1 - A PO_CB_XXX constant value. @param[in] Argument2 - A value of TRUE or FALSE. */ _Use_decl_annotations_ static VOID SvPowerCallbackRoutine ( PVOID CallbackContext, PVOID Argument1, PVOID Argument2 ) { UNREFERENCED_PARAMETER(CallbackContext); // // PO_CB_SYSTEM_STATE_LOCK of Argument1 indicates that a system power state // change is imminent. // if (Argument1 != reinterpret_cast<PVOID>(PO_CB_SYSTEM_STATE_LOCK)) { goto Exit; } if (Argument2 != FALSE) { // // The system has just reentered S0. Re-virtualize all processors. // NT_VERIFY(NT_SUCCESS(SvVirtualizeAllProcessors())); } else { // // The system is about to exit system power state S0. De-virtualize all // processors. // SvDevirtualizeAllProcessors(); } Exit: return; } <file_sep>SimpleSvm ========== Introduction ------------- SimpleSvm is a minimalistic educational hypervisor for Windows on AMD processors. It aims to provide small and explanational code to use Secure Virtual Machine (SVM), the AMD version of Intel VT-x, with Nested Page Tables (NPT) from a windows driver. SimpleSvm is inspired by SimpleVisor, an Intel x64/EM64T VT-x specific hypervisor for Windows, written by <NAME> (@aionescu). Supported Platforms ---------------------- - Windows 10 x64 and Windows 7 x64 - AMD Processors with SVM and NPT support Resources ------------------- - AMD64 Architecture Programmer’s Manual Volume 2 and 3 - http://developer.amd.com/resources/developer-guides-manuals/ - SimpleVisor - http://ionescu007.github.io/SimpleVisor/ - HelloAmdHvPkg - https://github.com/tandasat/HelloAmdHvPkg
43b88e82781f8ed65be44c7ba20a5443bd7b1c38
[ "Markdown", "C++" ]
2
C++
fengjixuchui/SimpleSvm
7fc3da46938c25e4d76d77abe63e5c1a16342f91
8741236c7e4a67c79b25ddb32680fc994e9d454a
refs/heads/master
<file_sep>import { Text, TextStyle } from 'pixi.js'; import Scene from '../libs/scene'; export default class OverScene extends Scene { init() { super.init(); console.log('Over init'); this._angle = 0; } preload() { console.log('Over preload'); } pause() { super.pause(); console.log('Over pause'); } create() { const style = new TextStyle({ align: 'right', dropShadow: true, dropShadowAlpha: 0.2, dropShadowAngle: 0.6, dropShadowColor: '#676565', dropShadowDistance: 2, fill: '#822742', fontSize: 50, lineHeight: 45, stroke: '#666', }); this.text = new Text('游戏结束...', style); this.text.x = this.state.width / 2 - this.text.width / 2; this.text.y = this.state.height / 2 - this.text.height / 2; this.addChild(this.text); } update() { //this.text.y += Math.cos(this._angle); //this._angle += 0.2; } onResize({ width, height }) { this.state.width = width; this.state.height = height; this.text.x = width / 2 - this.text.width / 2; this.text.y = height / 2 - this.text.height / 2; } } <file_sep>import LoadingScene from './loading'; import PlayingScene from './playing'; import OverScene from './over'; export default { loading: LoadingScene, playing: PlayingScene, over: OverScene, }; <file_sep>export function extend(Graphics) { Graphics.prototype.drawDashLine = function(toX, toY, dash = 16, gap = 8) { const lastPosition = this.currentPath.shape.points; const currentPosition = { x: lastPosition[lastPosition.length - 2] || 0, y: lastPosition[lastPosition.length - 1] || 0, }; const absValues = { toX: Math.abs(toX), toY: Math.abs(toY), }; for (; Math.abs(currentPosition.x) < absValues.toX || Math.abs(currentPosition.y) < absValues.toY; ) { currentPosition.x = Math.abs(currentPosition.x + dash) < absValues.toX ? currentPosition.x + dash : toX; currentPosition.y = Math.abs(currentPosition.y + dash) < absValues.toY ? currentPosition.y + dash : toY; this.lineTo(currentPosition.x, currentPosition.y); currentPosition.x = Math.abs(currentPosition.x + gap) < absValues.toX ? currentPosition.x + gap : toX; currentPosition.y = Math.abs(currentPosition.y + gap) < absValues.toY ? currentPosition.y + gap : toY; this.moveTo(currentPosition.x, currentPosition.y); } }; Graphics.prototype.drawDashedRect = function(x, y, w, h, rotation, dash, gap, offsetPercentage) { let polygons = [ { x: 0, y: 0 }, { x: w, y: 0 }, { x: w, y: h }, { x: 0, y: h }, ]; this.drawDashedPolygon(polygons, x, y, rotation, dash, gap, offsetPercentage); }; Graphics.prototype.drawDashedPolygon = function(polygons, x, y, rotation, dash, gap, offsetPercentage) { var i; var p1; var p2; var dashLeft = 0; var gapLeft = 0; if (offsetPercentage > 0) { var progressOffset = (dash + gap) * offsetPercentage; if (progressOffset < dash) dashLeft = dash - progressOffset; else gapLeft = gap - (progressOffset - dash); } var rotatedPolygons = []; for (i = 0; i < polygons.length; i++) { var p = { x: polygons[i].x, y: polygons[i].y }; var cosAngle = Math.cos(rotation); var sinAngle = Math.sin(rotation); var dx = p.x; var dy = p.y; p.x = dx * cosAngle - dy * sinAngle; p.y = dx * sinAngle + dy * cosAngle; rotatedPolygons.push(p); } for (i = 0; i < rotatedPolygons.length; i++) { p1 = rotatedPolygons[i]; if (i == rotatedPolygons.length - 1) p2 = rotatedPolygons[0]; else p2 = rotatedPolygons[i + 1]; var dx = p2.x - p1.x; var dy = p2.y - p1.y; var len = Math.sqrt(dx * dx + dy * dy); var normal = { x: dx / len, y: dy / len }; var progressOnLine = 0; this.moveTo(x + p1.x + gapLeft * normal.x, y + p1.y + gapLeft * normal.y); while (progressOnLine <= len) { progressOnLine += gapLeft; if (dashLeft > 0) progressOnLine += dashLeft; else progressOnLine += dash; if (progressOnLine > len) { dashLeft = progressOnLine - len; progressOnLine = len; } else { dashLeft = 0; } this.lineTo(x + p1.x + progressOnLine * normal.x, y + p1.y + progressOnLine * normal.y); progressOnLine += gap; if (progressOnLine > len && dashLeft == 0) { gapLeft = progressOnLine - len; } else { gapLeft = 0; this.moveTo(x + p1.x + progressOnLine * normal.x, y + p1.y + progressOnLine * normal.y); } } } }; } <file_sep>import StateMachine from 'javascript-state-machine'; import SceneManager from './scene-manager'; import PubSub from 'pubsub-js'; import { Container } from 'pixi.js'; import { View } from './view'; export default class Game extends PIXI.Application { constructor(options) { super(options); this.ssm = new SceneManager(this); //simple scene manager this.fsm = new StateMachine(this.createState()); //有限状态机 finite state machines this.initRootStage(options); this.init(); this.preload(); //游戏主循环 this.ticker.add(this.update.bind(this)); } initRootStage(options) { this.rootStage = new Container(); this.rootStage.width = options.width; this.rootStage.height = options.height; this.stage.addChild(this.rootStage); this.detectOrient(options); } renderScene(scene) { this.rootStage.addChildAt(scene, 0); } getAdapterMode() { return View.FIXED_HEIGHT; } /** * 横竖屏处理 */ detectOrient(options) { let sizeOptions = View.setViewMode( this.renderer, this.rootStage, options.screenWidth, options.screenHeight, options.designWidth, options.designHeight, this.getAdapterMode(), options => { this.onResize(options); //console.log('Game -> detectOrient -> options', options); } ); this.state = sizeOptions; ///console.log('Game -> detectOrient -> sizeOptions', sizeOptions); } createState() { return { transitions: [], }; } /** * 添加场景 * @param {*} name 场景名称 * @param {*} scene 场景 */ addScene(name, scene) { this.ssm.add(name, scene); return this; } /** * 批量添加场景 * @param {*} scenes 场景信息 { sceneName1:sceneObj1,sceneName2:sceneObj2 } */ addScenes(scenes) { Object.keys(scenes).forEach(sceneName => { this.addScene(sceneName, scenes[sceneName]); }); } /** * 开始某个场景 * @param {String} name 场景的名称 * @param {*} args 场景init的参数 */ startScene(name, args) { this.ssm.start(name, args); } /** * 初始化方法 */ init() { this.stage.addChild(this.rootStage); } /** * 预加载资源需要重新这个方法 */ preload() {} /** * 资源加载进度 */ progress(loader, resources) {} /** * 资源加载完成后,开始游戏状态 * @param {*} loaders 记载器 * @param {*} resources 资源信息 */ create(loader, resources) {} /** * 主事件循环中 */ update(delta) { //调用场景的刷新 this.ssm.update(delta); } onResize(options) { this.ssm.onResize(options); } //--------------------- // 发布/订阅模式的简单封装 //--------------------- subscribe(...args) { PubSub.subscribe(...args); } publish(...args) { PubSub.publish(...args); } } <file_sep>export default { EVENTS: { PING: 1, START_GAME: 2, END_GAME: 3, }, //这是一个示例, }; <file_sep>import PubSub from 'pubsub-js'; export default class Component extends PIXI.Container { constructor(options) { super(); this.state = options; this.init(); this.create(); } init() {} create() {} //--------------------- // 发布/订阅模式的简单封装 //--------------------- subscribe(...args) { PubSub.subscribe(...args); } publish(...args) { PubSub.publish(...args); } update() {} } <file_sep>import { Text, TextStyle } from 'pixi.js'; import Scene from '../libs/scene'; import constants from '../constants'; export default class PlayingScene extends Scene { init() { super.init(); console.log('Playing init'); this._angle = 0; } preload() { console.log('Playing preload'); } pause() { super.pause(); console.log('Playing pause'); } create() { const style = new TextStyle({ align: 'right', dropShadow: true, dropShadowAlpha: 0.2, dropShadowAngle: 0.6, dropShadowColor: '#676565', dropShadowDistance: 2, fill: '#27825a', fontSize: 50, lineHeight: 45, stroke: '#666', }); this.text = new Text('Playing...', style); this.text.x = this.state.width / 2 - this.text.width / 2; this.text.y = this.state.height / 2 - this.text.height / 2; this.text.interactive = true; this.text.buttonMode = true; this.text.on('pointerdown', () => { super.publish(constants.EVENTS.END_GAME); //发布事件 }); this.addChild(this.text); } update() { this.text.y += Math.cos(this._angle); this._angle += 0.2; } onResize({ width, height }) { this.state.width = width; this.state.height = height; this.text.x = width / 2 - this.text.width / 2; this.text.y = height / 2 - this.text.height / 2; } } <file_sep>import Game from './libs/game'; import scenes from './scenes'; import config from './config'; import constants from './constants'; class App extends Game { constructor(options) { super(options); this.options = Object.assign({}, options); } /** * 重写创建游戏状态 */ createState() { let state = { methods: { onTransition: this.onTransition.bind(this), }, }; let newState = Object.assign(super.createState(), config.state, state); console.log(newState); return newState; } //------------------------ // 默认的事件处理 //----------------------- init() { Object.keys(scenes).forEach(sceneName => { this.addScene(sceneName, scenes[sceneName]); }); // 事件订阅 this.subscribe(constants.EVENTS.START_GAME, this.onStartGame.bind(this)); this.subscribe(constants.EVENTS.END_GAME, this.onEndGame.bind(this)); } preload() { console.log(this.fsm.state); } //------------------------ // 状态机的事件 //----------------------- onTransition(lifecycle) { console.log(lifecycle.transition); console.log(lifecycle.from); console.log(lifecycle.to); this.startScene(lifecycle.to); } //------------------------ // 发布订阅的事件 //----------------------- onPing() { console.log('on ping event fired'); } onStartGame() { console.log('on start game event fired'); this.fsm.play(); } onEndGame() { console.log('on start game event fired'); this.fsm.lose(); } } export default App; <file_sep>const { AnimatedSprite, Texture } = PIXI; export class StatesAnimatedSprite extends AnimatedSprite { constructor(frameBaseName, states, initState) { let arrName = frameBaseName.split('.'); let extName = arrName.pop(); let preName = arrName.join('.'); let animatedStates = {}; let stateKeys = Object.keys(states); if (!initState || !states[initState]) { initState = stateKeys[0]; } Object.keys(states).forEach(key => { let range = states[key]; let textures = []; if (range.length == 1) { textures.push(Texture.from(`${preName}${range[0]}.${extName}`)); } else { for (let i = range[0], l = range[1]; i <= l; i++) { textures.push(Texture.from(`${preName}${i}.${extName}`)); } } animatedStates[key] = textures; }); super(animatedStates[initState]); this.animatedStates = animatedStates; } playState(stateName) { if (this.animatedStates[stateName] && this.animatedStates[stateName].length > 0) { this.stop(); this.textures = this.animatedStates[stateName]; this.gotoAndPlay(0); } else { console.log(this.animatedStates); console.warn('stateName=' + stateName + ' is notfound'); } } } <file_sep>export default { state: { init: 'loading', transitions: [ { name: 'play', from: 'loading', to: 'playing' }, { name: 'lose', from: 'playing', to: 'over' }, ], methods: {}, }, }; <file_sep># Pitaya- 使用 Pixi 开发小游戏的脚手架 --- ## how to use 请看代码中的 app.js <file_sep>import Game from './game'; import Component from './component'; import Scene from './scene'; import SceneManager from './scene-manager'; import { StatesAnimatedSprite } from './states-animated-sprite'; import { View } from './view'; export { Game, Component, Scene, SceneManager, StatesAnimatedSprite, View };
d20baace2521b3bea0eeb1cd6fb631c61e121faa
[ "JavaScript", "Markdown" ]
12
JavaScript
xuanye/pitaya
605c4a5a515bb4099b83f12100807bfa44195297
302172b4af581507fab0205febc3d01aaa1670e9
refs/heads/master
<file_sep>#include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/epoll.h> #include <arpa/inet.h> #include <fcntl.h> #include <errno.h> #include <iostream> #define local_port 12345 #define local_ip "0.0.0.0" #define MAX_EVENTS 100 #define MAX_BUFFER 1024 int main(int argc, char *argv[]) { int listenFd, clientFd = 0; int epfd = 0; int ret, cLen, rlen, wlen = 0; char rbuf[MAX_BUFFER] = {0}; char wbuf[MAX_BUFFER] = {0}; struct sockaddr_in local_addr, client_addr; struct epoll_event myevents[MAX_EVENTS] = {0}; memset(&client_addr, 0, sizeof(client_addr)); listenFd = socket(AF_INET, SOCK_STREAM, 0); if(listenFd == -1) { perror("can't create stream socket!\n"); return -1; } int addrval = 1; if(setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, (const void*)&addrval, sizeof(addrval)) == -1) { perror("setsockopt SO_REUSEADDR socket fail!\n"); return -1; } int flags = fcntl(listenFd, F_GETFL, 0); if(fcntl(listenFd, F_SETFL, flags|O_NONBLOCK) == -1) { perror("set socket noblock fail!\n"); return -1; } local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = INADDR_ANY; //inet_addr(local_ip); local_addr.sin_port = htons(local_port); if(bind(listenFd, (struct sockaddr*)&local_addr, sizeof(local_addr)) == -1) { perror("bind socket fail!\n"); return -1; } if(listen(listenFd, 5) == -1) { perror("listen socket fail!\n"); return -1; } epfd = epoll_create(5); struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = listenFd; if(epoll_ctl(epfd, EPOLL_CTL_ADD, listenFd, &ev) == -1) { perror("epoll_ctl:: add socket fail!\n"); return -1; } while(true) { int evnum = epoll_wait(epfd, myevents, MAX_EVENTS, -1); for(int i= 0; i<evnum; i++) { if(myevents[i].data.fd == listenFd) { clientFd = accept(listenFd, (struct sockaddr*)&client_addr,(socklen_t *)&cLen); if(clientFd == -1) { if((errno == EAGAIN) || (errno == EINTR)) { continue; } else { perror("accept failed. Error"); epoll_ctl(epfd, EPOLL_CTL_DEL, listenFd, NULL); close(clientFd); return -1; } } else { struct epoll_event nev; nev.events = EPOLLIN; nev.data.fd = clientFd; if(epoll_ctl(epfd, EPOLL_CTL_ADD, clientFd, &nev) == -1) { perror("epoll_ctl:: add socket fail!\n"); close(clientFd); return -1; } } } if(myevents[i].events == EPOLLIN) { memset(rbuf, 0, sizeof(rbuf)); int rfd = myevents[i].data.fd; int rnum = read(rfd, (void*)rbuf, (size_t)rlen); if(rnum == -1) { if(errno == EAGAIN || errno == EINTR) continue; else { perror("epoll_ctl:: read fail!\n"); epoll_ctl(epfd, EPOLL_CTL_DEL, rfd, NULL); close(rfd); } } else { printf("Server read->%s,len = %d", rbuf, rnum); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLOUT; ev.data.fd = rfd; if(epoll_ctl(epfd, EPOLL_CTL_MOD, rfd,&ev) == -1) { perror("epoll_ctl:: mod socket fail!\n"); return -1; } } } if(myevents[i].events == EPOLLOUT ) { int wfd = myevents[i].data.fd; int wnum = write(wfd, (void*)rbuf, sizeof(rbuf)); if(wnum == -1) { if(errno == EAGAIN || errno == EINTR) continue; else { perror("epoll_ctl:: write fail!\n"); epoll_ctl(epfd, EPOLL_CTL_DEL, wfd, NULL); close(wfd); } } else { printf("Server write->%s,len = %d", rbuf,wnum); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = wfd; if(epoll_ctl(epfd, EPOLL_CTL_MOD, wfd,&ev) == -1) { perror("epoll_ctl:: mod socket fail!\n"); return -1; } } }// end if myevnets[i] }//end for int i = 0 }//end while true close(epfd); return 0; } <file_sep>#include <netinet/in.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int MySocket, optval,realSend, ret = 0; struct sockaddr_in addr_in; char SendBuf[1024*4+1] = ""; int Real_send = 0; MySocket = socket(AF_INET, SOCK_STREAM, 0); if(MySocket == -1) { printf("Create Mysock fail!n"); return -1; } optval = 1; setsockopt(MySocket, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, sizeof(optval) ); memset(&addr_in, 0, sizeof(sockaddr_in)); addr_in.sin_family = AF_INET; addr_in.sin_addr.s_addr = inet_addr(argv[1]); addr_in.sin_port = htons(atoi(argv[2])); //循环连接server while(true) { ret = connect(MySocket, (const struct sockaddr *)&addr_in, sizeof(addr_in)); if(ret == 0) { break; } else { if(errno == EINTR) { continue; } else if(errno == EINTR) { //usleep(1000); continue; } else { perror("connect fail,error:"); close(MySocket); printf("connect server address->%s:%s fail!\n", argv[1], argv[2]); return -1; } } } int flags = fcntl(MySocket, F_GETFL, 0); if(flags == -1) { printf( "get socket flag fail, error: %s\n", strerror(errno)); return -1; } fcntl(MySocket, F_SETFL, flags | O_NONBLOCK); //读写数据 while(true) { cout<<"please input you want message"<<endl; cin>>SendBuf; if(strcmp(SendBuf,"q") ==0) { printf("client quit\n"); close(MySocket); return 1; } Real_send = send(MySocket, SendBuf, strlen(SendBuf), 0); if(Real_send == -1) { /* errno为EAGAINE或 EWOULDBLOCK,表示当前缓冲区写满,可以继续写 */ if(errno == EAGAIN) { usleep(1000); continue; } /* errno为EINTR表示被中断,可以继续写 */ else if(errno == EINTR) { continue; } /* 即errno不为EAGAINE或EWOULDBLOCK或EINTR,则发送出错,此时应该close(sockfd) */ else { printf( "send failed: %s\n", strerror(errno)); close(MySocket); return -1; } } else { printf("send dada:%s successful!\n"); continue; } } return 0; } <file_sep>ARCHIVE := $(shell uname -m) BIT32 := i686 BIT64 := x86_64 FPIC= ifeq ($(ARCHIVE),$(BIT64)) FPIC=-fPIC endif ifndef BUILD_DIR BUILD_DIR := ./bin endif NULL := $(shell mkdir -pv $(BUILD_DIR)) CC = g++ CFLAGS = -Wall -O -g -I/usr/local/include/ LDFLAGS = -static -L. -lstdc++ SERV := $(BUILD_DIR)/Serv CLI := $(BUILD_DIR)/Cli SERVER_DIR = ./server CLIENT_DIR = ./client CLIENT_SRC=$(wildcard $(CLIENT_DIR)/*.c $(CLIENT_DIR)/*.cpp) CLIENT_OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o, $(wildcard $(CLIENT_SRC)))) SERVER_SRC=$(wildcard $(SERVER_DIR)/*.c $(SERVER_DIR)/*.cpp) SERVER_OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o, $(wildcard $(SERVER_SRC)))) all: $(SERV) $(CLI) $(SERV):$(SERVER_OBJS) g++ -o $@ $^ $(LDFLAGS) $(CLI):$(CLIENT_OBJS) g++ -o $@ $^ $(LDFLAGS) %.o: %.c g++ $(CFLAGiS) -c $< -o $@ $(INCLUDES) .PHONY: clean clean: rm -rf $(SERVER_DIR)/*.o $(CLIENt_DIR)/*.o $(BUILD_DIR) <file_sep> #include <stdio.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <fcntl.h> #include <errno.h> #define INADDR_ANY ((in_addr_t) 0x00000000) #define HOST_PORT 8888 int main(int argc, char*argv[]) { char RecvBuf[1024*4+1] = ""; char ipAddr[255]=""; int hSocket,connfd,optval, peerLen, hostLen, flags = 0; socklen_t C_addr_len = 0; size_t Recv_len = 1024 * 4; size_t RetSend,RetRecv = 0; hSocket = socket(AF_INET, SOCK_STREAM, 0); if(hSocket == -1) { perror("can't create stream socket!\n"); return 1; } flags = fcntl(hSocket, F_GETFL, 0); if(flags == -1) { printf( "get socket flag fail, error: %s\n", strerror(errno)); return -1; } fcntl(hSocket, F_SETFL, flags | O_NONBLOCK); optval = 1; setsockopt(hSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, sizeof(optval) ); /* When a socket is created with socket(2), it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified to by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. */ struct sockaddr_in addr_in, client_addr, peerAddr, hostAddr; memset(&addr_in, 0, sizeof(sockaddr_in)); memset(&peerAddr, 0, sizeof(sockaddr_in)); addr_in.sin_family = AF_INET; addr_in.sin_addr.s_addr = INADDR_ANY; //inet_addr("192.168.127.12"); addr_in.sin_port = htons(HOST_PORT); int ret = bind(hSocket, (struct sockaddr*)&addr_in, sizeof(addr_in)); if(ret == -1) { perror("bind failed. Error"); return 1; } ret = listen(hSocket, 5); if(ret == -1) { perror("listen failed. Error"); return 1; } getsockname(hSocket, (struct sockaddr *)&hostAddr, (socklen_t*)&hostLen);//获取server本机的ip地址 printf("server address = %s:%d\n", inet_ntoa(hostAddr.sin_addr), ntohs(hostAddr.sin_port)); //接受客户端的连接请求 memset(&client_addr, 0, sizeof(client_addr)); while(true) { connfd = accept(hSocket, (struct sockaddr*)&client_addr, (socklen_t *)&C_addr_len); if(connfd == -1) { if((errno == EAGAIN) || (errno == EINTR)) { usleep(1000); continue; } else { perror("accept failed. Error"); return -1; } } else { printf("connect establish!, client ip = %s, port=%d\n", inet_ntoa(client_addr.sin_addr), ntohl(client_addr.sin_port)); break; } } //读取客户端发送的信息,并直接返回给客户端 /* ssize_t recv(int sockfd, void *buf, size_t len, int flags); These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown. */ while(true) { memset(RecvBuf, 0, sizeof(RecvBuf)); RetRecv = recv(connfd, (void*)RecvBuf, Recv_len, 0); /* 表示对端已经关闭了这个链接 */ if(RetRecv == 0) { printf("client close socket,exit!\n"); close(connfd); break; } /* 分情况判断返回错误 */ else if(RetRecv == -1) { /* errno为EAGAINE或EWOULDBLOCK, 表示暂时无数据可读,可以继续读 原因:可能是多进程读同一个sockfd,可能一个进程读到数据,其他进程就读取不到数据 */ if(errno == EAGAIN) { usleep(1000); continue; } /* errno为 EINTR, 表示被中断了,可以继续读 */ else if(errno == EINTR) { continue; } else { printf( "recv failed: %s\n", strerror(errno)); close(connfd); break; } } //接收正常 else { RetSend = send(connfd, RecvBuf, RetRecv, 0); if(RetSend == -1) { /* errno为EAGAINE或 EWOULDBLOCK,表示当前缓冲区写满,可以继续写 */ if(errno == EAGAIN) { usleep(1000); continue; } /* errno为EINTR表示被中断,可以继续写 */ else if(errno == EINTR) { continue; } /* 即errno不为EAGAINE或EWOULDBLOCK或EINTR,则发送出错,此时应该close(sockfd) */ else { printf( "send failed: %s\n", strerror(errno)); close(connfd); } } else { /* >=0且不等于要求发送的长度,应该继续send,如果等于要求发送的长度,发送完毕,后续补充 */ getpeername(connfd, (struct sockaddr *)&peerAddr, (socklen_t*)&peerLen); printf("recv msg:%s from address = %s:%d\n", RecvBuf, inet_ntop(AF_INET, &peerAddr.sin_addr, ipAddr, sizeof(ipAddr)), ntohs(peerAddr.sin_port)); } } } close(hSocket); return 0; }
3f37261eda53cc9df804d033bb0dced71694e9f4
[ "C", "Makefile" ]
4
C
caihm837/NetWork
9dd4c569142271fbdf6d739c74608538d74218be
7080e6172b847b162d2ff9641780d803973a6d73
refs/heads/master
<file_sep>## Additional prompt: Have an org Anyone can join any org. Backend to setup that extra permission. printing the org that the member is a part of making the public or private is for the org. Limit to an hour -------------------------- ## To do: x Add a field in the user model for a organization. x Add a dropdown for them to choose and org at sign up that assigns them to a new org. x Add a field on the message model for an org. x When making public messages, assign the org to the message. x When doing public messages, only query for the public messages with the org name associated. -------------------------- ## Improve for the future: - Admin signs up a company - User can sign up for a company automatically by recognizing co. email address. <file_sep>'use strict'; const db = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/omni_lab_interview_app' module.exports = { db: { production: db, development: db, test: db, }, mailer: { auth: { user: '<EMAIL>', pass: '<PASSWORD>', }, defaultFromAddress: 'First Last <<EMAIL>>' } }; // Started referencing this tutorial for password reset via email http://www.scotchmedia.com/tutorials/express/authentication/3/02 <file_sep>const express = require('express'), router = express.Router(), bcrypt = require('bcrypt'), User = require('../models/users.js'); // RENDER NEW USER PAGE router.get('/register', (req, res) => { res.render('users/new.ejs'); }); // REGISTER A NEW USER router.post('/register', (req, res) => { // hash the password console.log("hitting the post route for sessions/register"); console.log(req.body); const hashedPassword = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)); //The new user const newUser = {}; newUser.username = req.body.username; newUser.password = <PASSWORD>; newUser.organization = req.body.organization; User.create(newUser, (err, createdUser) => { req.session.currentuser = createdUser; req.session.logged = true; res.redirect('/welcome'); }); }); //LOGIN router.get('/new', (req, res) => { res.render('sessions/new.ejs'); }); //SIGN IN - CREATE A NEW SESSION router.post('/', (req, res) => { console.log(req.body); User.findOne({ username: req.body.username }, (err, foundUser) => { console.log("foundUser:", foundUser); if(foundUser){ if(bcrypt.compare(req.body.password, foundUser.password)){ req.session.currentuser = foundUser; req.session.logged = true; res.redirect('/welcome'); } else { res.send('password is incorrect'); } } else { res.send('username is incorrect'); } }); }); //GET PASSWORD RESET PAGE router.get('/password-reset', (req, res) => { console.log(req.session); console.log("..............", req.session.currentuser.username); res.render('users/reset.ejs', { currentUserName: req.session.currentuser.username }); }); // RESET PASSWORD router.post ('/password-reset', function(req, res){ let foundUser = User.findOne({username: req.body.username}); const newPassword = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)); if(foundUser){ User.updateOne( {username: req.body.username}, {$set: {password : <PASSWORD>} },(err, updatedDoc) => { if (err) { console.log(err) } else { res.redirect('/welcome'); } }) } else { res.redirect('/'); } }) // LOGOUT OF SESSION router.get('/logout', function(req, res){ req.session.destroy((err) => { if(err){ console.log(err); } else { res.redirect('/'); } }); }); module.exports = router;
6398897b7c95bb235f2dfae8c2ac11f1f2e8b5bf
[ "Markdown", "JavaScript" ]
3
Markdown
kristynrb/Users-message-app
ddd183343181e8dd9325b78072d1e14dc1567c3b
cfcd7ce678b32aab0a421d019940e15cb4902d22
refs/heads/master
<file_sep>#include "stdafx.h" #include "model.h" class Decoder { public: Decoder(vector<vector<int> > *cur_line_ptr,Model *model); ~Decoder(); bool decode_for_train(vector<int> &taglist_output, vector<int> &taglist_gold); vector<int> decode(); vector<vector<int> > extract_features(const vector<int> &taglist,size_t feature_extract_pos); private: vector<Cand> expand(const Cand &cand); void add_to_new(const vector<Cand> &candlist); bool check_is_history_same(const Cand &cand0, const Cand &cand1); private: Model *m_model; vector<vector<int> > *m_token_matrix_ptr; const static size_t BEAM_SIZE = 16; const static size_t NGRAM = 3; vector<Cand> candlist_old; vector<Cand> candlist_new; vector<int> m_gold_taglist; size_t cur_pos; }; <file_sep>#include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <map> #include <unordered_map> #include <boost/functional/hash.hpp> #include <set> #include <algorithm> #include <math.h> #include <stdlib.h> #include <pthread.h> //#include <zlib.h> using namespace std; using namespace boost; <file_sep>pcpt: g++ *.cpp -o pcpt -O2 -std=c++11 <file_sep>#include "model.h" Model::Model(const string &mode, const string &model_file, size_t line, size_t round) { MODE = mode; LINE = line; ROUND = round; m_model_file = model_file; bigram_feature_flag = false; trigram_feature_flag = false; load_validtagset(); parse_template(); if (MODE == "test") { load_bin_model(m_model_file); } } void Model::load_validtagset() { ifstream fin; fin.open("tagset_for_token"); if (!fin.is_open()) { cerr<<"fail to open tagset_for_token file\n"; return; } string line; while(getline(fin,line)) { TrimLine(line); vector<string> toks; Split(toks,line); set<int> validtagset; for (size_t i=1;i<toks.size();i++) { validtagset.insert(stoi(toks.at(i))); } tagset_for_token[stoi(toks.at(0))] = validtagset; } fin.close(); fin.open("tagset_for_last_tag"); if (!fin.is_open()) { cerr<<"fail to open tagset_for_last_tag file\n"; return; } while(getline(fin,line)) { TrimLine(line); vector<string> toks; Split(toks,line); set<int> validtagset; for (size_t i=1;i<toks.size();i++) { validtagset.insert(stoi(toks.at(i))); } tagset_for_last_tag[stoi(toks.at(0))] = validtagset; } fin.close(); } void Model::parse_template() { ifstream fin; fin.open("template"); if (!fin.is_open()) { cerr<<"fail to open template file\n"; return; } string sep("%"); string line; while(getline(fin,line)) { TrimLine(line); if (line.size() == 0) continue; if (line[0] == '#') continue; if (line == "B") { bigram_feature_flag = true; continue; } if (line == "T") { trigram_feature_flag = true; continue; } vector<pair<int,int> > feature_template; vector<string> toks; Split(toks,line,sep); for (size_t i=1;i<toks.size();i++) { string &tok = toks.at(i); tok = tok.substr(2,tok.size()-3); size_t p = tok.find(','); int row = stoi(tok.substr(0,p)); int col = stoi(tok.substr(p+1)); feature_template.push_back(make_pair(row,col)); } feature_templates.push_back(feature_template); } fin.close(); } void Model::save_model() { ofstream fout; fout.open("model"); if (!fout.is_open()) { cerr<<"fail to open model file to write\n"; return; } for (const auto &fwp : train_para_dict) { if (fwp.second.acc_weight > -1e10 && fwp.second.acc_weight< 1e-10) continue; for (const auto &v : fwp.first) { fout<<v<<'\t'; } fout<<fwp.second.acc_weight/LINE*ROUND<<endl; } cout<<"save model over\n"; } void Model::save_bin_model(size_t round) { ofstream fout(m_model_file+"."+to_string(round),ios::binary); if (!fout.is_open()) { cerr<<"fail to open binary model file to write!\n"; return; } size_t feature_num = 0; for (const auto &fwp : train_para_dict) { if (fwp.second.acc_weight > -1e-10 && fwp.second.acc_weight < 1e-10) continue; feature_num++; } fout.write((char*)&feature_num,sizeof(size_t)); for (const auto &fwp : train_para_dict) { if (fwp.second.acc_weight > -1e-10 && fwp.second.acc_weight < 1e-10) continue; size_t len = fwp.first.size(); fout.write((char*)&len,sizeof(size_t)); fout.write((char*)&(fwp.first.at(0)),sizeof(int)*fwp.first.size()); double weight = fwp.second.acc_weight/(LINE*ROUND); fout.write((char*)&(weight),sizeof(double)); } //cout<<"save binary model over\n"; } void Model::load_model() { ifstream fin; fin.open("model"); if (!fin.is_open()) { cerr<<"fail to open model file\n"; return; } string line; while(getline(fin,line)) { TrimLine(line); vector<string> toks; Split(toks,line); vector<int> feature; for (size_t i=0;i<toks.size()-1;i++) { feature.push_back(stoi(toks.at(i))); } test_para_dict[feature] = stod(toks.at(toks.size()-1)); } cout<<"load model over\n"; } void Model::load_bin_model(const string &model_file) { ifstream fin; fin.open(model_file.c_str(),ios::binary); if (!fin.is_open()) { cerr<<"fail to open binary model file\n"; return; } size_t feature_num; fin.read((char*)&feature_num, sizeof(size_t)); size_t len; for (size_t i = 0; i < feature_num; i++) { fin.read((char*)&len, sizeof(size_t)); vector<int> feature; feature.resize(len); fin.read((char*)&(feature.at(0)),sizeof(int)*len); double weight; fin.read((char*)&weight, sizeof(double)); test_para_dict[feature] = weight; } cout<<"load binary model over\n"; } void Model::update_paras(const vector<vector<int> > &local_features, const vector<vector<int> > &local_gold_features, const size_t round, const size_t line) { for (const auto &e_feature : local_features) { auto it = train_para_dict.find(e_feature); if (it == train_para_dict.end()) { WeightInfo tmp = {-1,-1,line,round}; train_para_dict.insert(make_pair(e_feature,tmp)); } else { it->second.acc_weight += it->second.weight*((round - it->second.lastround)*LINE + line - it->second.lastline) - 1; it->second.weight += -1; it->second.lastline = line; it->second.lastround = round; } } for (const auto &e_feature : local_gold_features) { auto it = train_para_dict.find(e_feature); if (it == train_para_dict.end()) { WeightInfo tmp = {1,1,line,round}; train_para_dict.insert(make_pair(e_feature,tmp)); } else { it->second.acc_weight += it->second.weight*((round-it->second.lastround)*LINE+line-it->second.lastline)+1; it->second.weight += 1; it->second.lastline = line; it->second.lastround = round; } } } void Model::update_paras_for_lastline(const size_t round, const size_t line) { for (auto &fwp : train_para_dict) { fwp.second.acc_weight += fwp.second.weight*((round - fwp.second.lastround)*LINE + line - fwp.second.lastline); fwp.second.lastline = line; fwp.second.lastround = round; } } vector<int> Model::get_validtagset(int cur_tok_id, int last_tag) { vector<int> validtagset; set<int> validtagset1; auto it = tagset_for_token.find(cur_tok_id); if (it != tagset_for_token.end()) { validtagset1 = it->second; } else { validtagset1 = tagset_for_token[-1]; } set<int> validtagset2; it = tagset_for_last_tag.find(last_tag); if (it != tagset_for_last_tag.end()) { validtagset2 = it->second; } else { validtagset2 = tagset_for_last_tag[-1]; } set_intersection(validtagset1.begin(),validtagset1.end(),validtagset2.begin(),validtagset2.end(),back_inserter(validtagset)); return validtagset; } double Model::cal_local_score(const vector<vector<int> > &features) { double local_score = 0; for (const auto &e_feature : features) { if (MODE == "train") { local_score += train_para_dict[e_feature].weight; } else { local_score += test_para_dict[e_feature]; } } return local_score; } <file_sep>#include "myutils.h" void Split(vector <string> &vs, string &s) { vs.clear(); stringstream ss; string e; ss << s; while(ss >> e) vs.push_back(e); } void Split(vector <string> &vs, string &s, string &sep) { int cur = 0,next; next = s.find(sep); while(next != string::npos) { if(s.substr(cur,next-cur) !="") vs.push_back(s.substr(cur,next-cur)); cur = next+sep.size(); next = s.find(sep,cur); } vs.push_back(s.substr(cur)); } void TrimLine(string &line) { line.erase(0,line.find_first_not_of(" \t\r\n")); line.erase(line.find_last_not_of(" \t\r\n")+1); } int s2i(string &s) { int i; stringstream ss; ss<<s; ss>>i; return i; } double s2d(string &s) { double d; stringstream ss; ss<<s; ss>>d; return d; } string i2s(int i) { stringstream ss; ss<<i; return ss.str(); } size_t fnv1_hash(const vector<int> &ivec) { size_t hash = 2166136261; for (auto &i : ivec) { hash *= 16777619; hash ^= i; } return hash; } size_t djb2_hash(const vector<int> &ivec) { size_t hash = 5381; for (auto &i : ivec) { hash = ((hash << 5) + hash) + i; /* hash * 33 + c */ } return hash; } size_t bkdr_hash(const vector<int> &ivec) { //size_t seed = 131; // 31 131 1313 13131 131313 etc.. size_t hash = 0; for (auto &i : ivec) { hash = hash * 131 + i; } return (hash & 0x7FFFFFFF); } <file_sep>#include "stdafx.h" #include "myutils.h" class Data { public: Data(const string &mode, const string &data_file); void shuffle(){random_shuffle(m_token_matrix_list.begin(),m_token_matrix_list.end());}; size_t get_size() {return m_token_matrix_list.size();}; vector<vector<int> >* get_token_matrix_ptr(size_t m_line) {return &m_token_matrix_list.at(m_line);}; string get_tag(int id){return id2tag[id];}; public: vector<vector<vector<int> > > m_token_matrix_list; vector<vector<string> > m_data_matrix; private: void load_data(const string &data_file); bool load_train_block(ifstream &fin); bool load_test_block(ifstream &fin); void save_dict(); void load_dict(); private: string MODE; const size_t TAGSET_CONSTRAINT = 1; const size_t THRESHOLD_FOR_RARE = 10; size_t m_field_size; vector<int> ids; vector<unordered_map<string,int> > dict; unordered_map<int,set<int> > token2tagset; unordered_map<int,int> token2freq; unordered_map<int,set<int> > lasttag2tagset; set<int> tagset; unordered_map<int,string> id2tag; }; <file_sep>#include "stdafx.h" #include "datastruct.h" class Model { public: Model(const string &mode, const string &model_file, size_t line, size_t round); void load_validtagset(); void parse_template(); void load_model(); void load_bin_model(const string &model_file); void save_model(); void save_bin_model(size_t round); vector<int> get_validtagset(int cur_tok_id, int last_tag); double cal_local_score(const vector<vector<int> > &features); void update_paras_for_lastline(const size_t round, const size_t line); void update_paras(const vector<vector<int> > &local_features, const vector<vector<int> > &local_gold_features, const size_t round, const size_t line); public: vector<vector<pair<int,int> > > feature_templates; bool bigram_feature_flag; bool trigram_feature_flag; private: string MODE; size_t LINE; size_t ROUND; string m_model_file; unordered_map<vector<int>, WeightInfo, vechash> train_para_dict; unordered_map<vector<int>, double, vechash> test_para_dict; unordered_map<int, set<int> > tagset_for_token; unordered_map<int, set<int> > tagset_for_last_tag; }; <file_sep>#include "data.h" Data::Data(const string &mode, const string &data_file) { MODE = mode; load_data(data_file); } void Data::save_dict() { ofstream fout; fout.open("dict"); if (!fout.is_open()) { cerr<<"fail to open dict file to write\n"; return; } for (const auto &d : dict) { fout<<"###dict###"<<endl; for (const auto &kvp : d) { fout<<kvp.first<<'\t'<<kvp.second<<endl; } } fout.close(); fout.open("tagset_for_token"); if (!fout.is_open()) { cerr<<"fail to open tagset_for_token file to write\n"; return; } fout<<"-1"; for (const auto &e : tagset) { fout<<' '<<e; } if (TAGSET_CONSTRAINT == 0 || TAGSET_CONSTRAINT == 2) { fout<<endl; for (const auto &kvp : token2tagset) { if (token2freq[kvp.first] < THRESHOLD_FOR_RARE) { continue; } fout<<kvp.first; for (const auto &e : kvp.second) { fout<<' '<<e; } fout<<endl; } } fout.close(); fout.open("tagset_for_last_tag"); if (!fout.is_open()) { cerr<<"fail to open tagset_for_last_tag file to write\n"; return; } fout<<"-1"; for (const auto &e : tagset) { fout<<' '<<e; } if (TAGSET_CONSTRAINT == 1 || TAGSET_CONSTRAINT == 2) { fout<<endl; for (const auto &kvp : lasttag2tagset) { fout<<kvp.first; for (const auto &e : kvp.second) { fout<<' '<<e; } fout<<endl; } } fout.close(); } void Data::load_dict() { dict.resize(m_field_size+1); ifstream fin; fin.open("dict"); if (!fin.is_open()) { cerr<<"fail to open dict file to load\n"; return; } int dict_id = -1; string line; while(getline(fin,line)) { TrimLine(line); if (line == "###dict###") { dict_id += 1; } else { vector<string> kv; Split(kv,line); dict.at(dict_id).insert(make_pair(kv.at(0),stoi(kv.at(1)))); } } fin.close(); for(const auto &kv : dict.at(dict_id)) { id2tag.insert(make_pair(kv.second,kv.first)); } } void Data::load_data(const string &data_file) { ifstream fin; fin.open(data_file.c_str()); if (!fin.is_open()) { cerr<<"fail to open data file!\n"; return; } string line; getline(fin,line); vector<string> fields; Split(fields,line); m_field_size = fields.size(); fin.seekg(0,fin.beg); if (MODE == "train") { ids.resize(m_field_size,1); dict.resize(m_field_size); while(load_train_block(fin)); save_dict(); } else { load_dict(); while(load_test_block(fin)); } cout<<"load data over\n"; } bool Data::load_test_block(ifstream &fin) { vector<vector<int> > token_matrix; vector<string> line_list(2,"<s>"); string line; vector<int> default_token_vec(m_field_size,0); token_matrix.push_back(default_token_vec); token_matrix.push_back(default_token_vec); while(getline(fin,line)) { //for the case that the first token in the line is blank if (line[0]==' ') { line[0] = '^'; } TrimLine(line); if (line.size() == 0) { token_matrix.push_back(default_token_vec); token_matrix.push_back(default_token_vec); m_token_matrix_list.push_back(token_matrix); m_data_matrix.push_back(line_list); return true; } vector<string> fields; Split(fields,line); vector<int> token_vec; for (size_t i=0;i<m_field_size;i++) { string &field = fields.at(i); auto it=dict.at(i).find(field); if (it != dict.at(i).end()) { token_vec.push_back(it->second); } else { token_vec.push_back(-1); } } token_matrix.push_back(token_vec); line_list.push_back(line); } return false; } bool Data::load_train_block(ifstream &fin) { vector<vector<int> > token_matrix; string line; vector<int> default_token_vec(m_field_size,0); token_matrix.push_back(default_token_vec); token_matrix.push_back(default_token_vec); size_t lasttag_id = 0; while(getline(fin,line)) { TrimLine(line); if (line.size() == 0) { token_matrix.push_back(default_token_vec); token_matrix.push_back(default_token_vec); m_token_matrix_list.push_back(token_matrix); return true; } vector<string> fields; Split(fields,line); vector<int> token_vec; for (size_t i=0;i<m_field_size;i++) { string &field = fields.at(i); auto it=dict.at(i).find(field); if (it != dict.at(i).end()) { token_vec.push_back(it->second); } else { dict.at(i).insert(make_pair(field,ids.at(i))); token_vec.push_back(ids.at(i)); ids.at(i) += 1; } } token2tagset[token_vec.at(0)].insert(token_vec.at(m_field_size-1)); token2freq[token_vec.at(0)] += 1; lasttag2tagset[lasttag_id].insert(token_vec.at(m_field_size-1)); tagset.insert(token_vec.at(m_field_size-1)); lasttag_id = token_vec.at(m_field_size-1); /* for (auto &e_field : fields) { token_vec.push_back(stoi(e_field)); } */ token_matrix.push_back(token_vec); } return false; } <file_sep>#include "decoder.h" Decoder::Decoder(vector<vector<int> > *cur_line_ptr,Model *model) { m_model = model; m_token_matrix_ptr = cur_line_ptr; candlist_old.clear(); candlist_new.clear(); Cand init_cand; init_cand.taglist.push_back(0); init_cand.taglist.push_back(0); init_cand.acc_score = 0; candlist_old.push_back(init_cand); m_gold_taglist.clear(); m_gold_taglist.push_back(0); m_gold_taglist.push_back(0); } Decoder::~Decoder() { m_model = NULL; m_token_matrix_ptr = NULL; candlist_old.resize(0); candlist_new.resize(0); m_gold_taglist.resize(0); } bool Decoder::decode_for_train(vector<int> &taglist_output, vector<int> &taglist_gold) { for (cur_pos=2;cur_pos<m_token_matrix_ptr->size()-2;cur_pos++) { size_t len = m_token_matrix_ptr->at(cur_pos).size(); m_gold_taglist.push_back(m_token_matrix_ptr->at(cur_pos).at(len-1)); for (const auto &e_cand : candlist_old) { vector<Cand> candvec = expand(e_cand); add_to_new(candvec); } sort(candlist_new.begin(),candlist_new.end(),greater<Cand>()); candlist_old.swap(candlist_new); if (candlist_old.size() > BEAM_SIZE) { candlist_old.resize(BEAM_SIZE); } candlist_new.resize(0); bool lose_track = true; for (const auto &e_cand : candlist_old) { if (e_cand.taglist == m_gold_taglist) { lose_track = false; break; } } if (lose_track == true) { taglist_output = candlist_old.at(0).taglist; taglist_gold = m_gold_taglist; return false; } //cout<<"decoding at pos "<<cur_pos-2<<endl; } if (candlist_old.at(0).taglist == m_gold_taglist) return true; taglist_output = candlist_old.at(0).taglist; taglist_gold = m_gold_taglist; return false; } vector<int> Decoder::decode() { //cout<<"current sentence size: "<<m_token_matrix_ptr->size()-2<<endl; for (cur_pos=2;cur_pos<m_token_matrix_ptr->size()-2;cur_pos++) { for (const auto &e_cand : candlist_old) { vector<Cand> candvec = expand(e_cand); add_to_new(candvec); } sort(candlist_new.begin(),candlist_new.end(),greater<Cand>()); candlist_old.swap(candlist_new); if (candlist_old.size() > BEAM_SIZE) { candlist_old.resize(BEAM_SIZE); } candlist_new.resize(0); //cout<<"decoding at pos "<<cur_pos-2<<endl; } return candlist_old.at(0).taglist; } vector<Cand> Decoder::expand(const Cand &cand) { vector<Cand> candvec; int cur_tok_id = m_token_matrix_ptr->at(cur_pos).at(0); int last_tag = cand.taglist.at(cand.taglist.size()-1); vector<int> validtagset = m_model->get_validtagset(cur_tok_id,last_tag); for (const auto &e_tag : validtagset) { Cand cand_new; cand_new.taglist = cand.taglist; cand_new.taglist.push_back(e_tag); vector<vector<int> > local_features = extract_features(cand_new.taglist,cand_new.taglist.size()-1); double local_score = m_model->cal_local_score(local_features); cand_new.acc_score = cand.acc_score+local_score; candvec.push_back(cand_new); } return candvec; } bool Decoder::check_is_history_same(const Cand &cand0, const Cand &cand1) { for (size_t k=0;k<NGRAM;k++) { if (cand0.taglist.at(cur_pos-k) != cand1.taglist.at(cur_pos-k)) { return false; } } return true; } void Decoder::add_to_new(const vector<Cand> &candvec) { for (const auto &e_cand : candvec) { bool is_history_same = false; /* */ for (auto &e_ori_cand : candlist_new) { is_history_same = check_is_history_same(e_cand,e_ori_cand); if (is_history_same == true) { if (e_cand.acc_score > e_ori_cand.acc_score) { e_ori_cand.taglist = e_cand.taglist; e_ori_cand.acc_score = e_cand.acc_score; } break; } } if (is_history_same == false) { candlist_new.push_back(e_cand); } } } vector<vector<int> > Decoder::extract_features(const vector<int> &taglist, size_t feature_extract_pos) { vector<vector<int> > features; features.clear(); vector<int> feature; int id = -1; for (const auto &ft : m_model->feature_templates) { id ++; feature.clear(); feature.push_back(id); for(const auto &rcp : ft) { feature.push_back(m_token_matrix_ptr->at(feature_extract_pos+rcp.first).at(rcp.second)); } feature.push_back(taglist.at(feature_extract_pos)); features.push_back(feature); } if (m_model->bigram_feature_flag == true) { feature.clear(); feature.push_back(++id); feature.push_back(taglist.at(feature_extract_pos-1)); feature.push_back(taglist.at(feature_extract_pos)); features.push_back(feature); } if (m_model->trigram_feature_flag == true) { feature.clear(); feature.push_back(++id); feature.push_back(taglist.at(feature_extract_pos-2)); feature.push_back(taglist.at(feature_extract_pos-1)); feature.push_back(taglist.at(feature_extract_pos)); features.push_back(feature); } return features; } /* vector<vector<int> > Model::extract_features(vector<vector<int> > &features, const vector<int> &taglist, size_t feature_extract_pos) { vector<vector<int> > features; features.clear(); if (taglist.at(feature_extract_pos) == 0) { auto pw_begin_it = find(taglist.rend()-feature_extract_pos,taglist.rend(),0); size_t pw_begin = taglist.rend() - 1 - pw_begin_it; size_t pw_end = feature_extract_pos - 1; size_t ppw_begin = taglist.rend() -1 - find(pw_begin_it+1,taglist.rend(),0); size_t ppw_end = pw_begin-1; vector<int> feature; feature.push_back(1); for (size_t pos=pw_begin;pos<=pw_end;pos++) { feature.push_back(m_token_matrix_ptr->at(pos).at(0)); } features.push_back(feature); size_t pw_len = pw_end - pw_begin + 1; if (pw_len == 1) { feature.at(0) = 2; features.push_back(feature); } feature.at(0) = 3; feature.push_back(m_token_matrix_ptr->at(feature_extract_pos).at(0)); features.push_back(feature); feature.at(0) = 4; feature.at(feature.size()-1) = m_token_matrix_ptr->at(ppw_end).at(0); features.push_back(feature); size_t ppw_len = ppw_end - ppw_begin + 1; feature.at(0) = 5; feature.at(feature.size()-1) = ppw_len; features.push_back(feature); feature.at(0) = 6; feature.at(feature.size()-1) = 0; for (size_t pos=ppw_begin;pos<=ppw_end;pos++) { feature.push_back(m_token_matrix_ptr->at(pos).at(0)); } features.push_back(feature); feature.clear(); feature.push_back(7); feature.push_back(m_token_matrix_ptr->at(pw_begin).at(0)); feature.push_back(pw_len); features.push_back(feature); feature.at(0) = 8; feature.at(1) = m_token_matrix_ptr->at(pw_end).at(0); features.push_back(feature); feature.at(0) = 9; feature.at(2) = m_token_matrix_ptr->at(feature_extract_pos).at(0); features.push_back(feature); feature.at(0) = 10; feature.at(1) = m_token_matrix_ptr->at(pw_begin).at(0); feature.at(2) = m_token_matrix_ptr->at(pw_end).at(0); features.push_back(feature); feature.at(0) = 11; feature.at(2) = m_token_matrix_ptr->at(feature_extract_pos).at(0); features.push_back(feature); feature.at(0) = 12; feature.at(1) = m_token_matrix_ptr->at(ppw_end).at(0); feature.at(2) = m_token_matrix_ptr->at(pw_end).at(0); features.push_back(feature); feature.clear(); feature.push_back(13); for (size_t pos=ppw_begin;pos<=ppw_end;pos++) { feature.push_back(m_token_matrix_ptr->at(pos).at(0)); } feature.push_back(pw_len); features.push_back(feature); } else { vector<int> feature; feature.push_back(14); feature.push_back(m_token_matrix_ptr->at(feature_extract_pos-1).at(0)); feature.push_back(m_token_matrix_ptr->at(feature_extract_pos).at(0)); features.push_back(feature); } return features; } */ <file_sep>#include "stdafx.h" #include "myutils.h" struct Cand { vector <int> taglist; double acc_score; bool operator> (const Cand &cand_rhs) const { return (acc_score > cand_rhs.acc_score); } }; struct WeightInfo { double weight; double acc_weight; size_t lastline; size_t lastround; }; struct vechash { size_t operator()(const vector<int>& v) const { //return hash_range(v.begin(),v.end()); return fnv1_hash(v); //return djb2_hash(v); //return bkdr_hash(v); } }; <file_sep>#include "perceptron.h" Perceptron::Perceptron(Data *data,Model *model,size_t line,size_t round) { ROUND = round; LINE = line; m_line = 0; m_round = 0; m_data = data; m_model = model; } void Perceptron::train(string &train_file) { LINE = m_data->get_size(); size_t sect_size = LINE/20; for (m_round=0;m_round<ROUND;m_round++) { m_data->shuffle(); for (m_line=0;m_line<LINE;m_line++) { vector<vector<int> > *cur_line_ptr = m_data->get_token_matrix_ptr(m_line); Decoder m_decoder(cur_line_ptr,m_model); vector<int> taglist_output; vector<int> taglist_gold; if(m_decoder.decode_for_train(taglist_output,taglist_gold) == false) { size_t end_pos = taglist_output.size(); for (size_t i=2;i<end_pos;i++) { vector<vector<int> > local_features = m_decoder.extract_features(taglist_output,i); vector<vector<int> > local_gold_features = m_decoder.extract_features(taglist_gold,i); m_model->update_paras(local_features,local_gold_features,m_round,m_line); } } if (m_line == LINE - 1) { m_model->update_paras_for_lastline(m_round,m_line); } if (m_line%sect_size == 0) { cout<<'.'; cout.flush(); } } cout<<"\t iter"<<m_round<<endl; m_model->save_bin_model(m_round); } //m_model->save_bin_model(m_round); } void Perceptron::test(string &test_file) { LINE = m_data->get_size(); ofstream fout; fout.open("output"); if (!fout.is_open()) { cerr<<"fail to open output file\n"; return; } vector<vector<int> > outputs; outputs.resize(LINE); //#pragma omp parallel for num_threads(4) for(size_t m_line=0;m_line<LINE;m_line++) { vector<vector<int> > *cur_line_ptr = m_data->get_token_matrix_ptr(m_line); Decoder m_decoder(cur_line_ptr,m_model); outputs.at(m_line) = m_decoder.decode(); } for(size_t m_line=0;m_line<LINE;m_line++) { for (size_t i=2;i<outputs.at(m_line).size();i++) { fout<<m_data->m_data_matrix.at(m_line).at(i)<<'\t'<<m_data->get_tag(outputs.at(m_line).at(i))<<endl; } fout<<endl; } } int main(int argc, char *argv[]) { clock_t a,b; a = clock(); if (argc == 1) { cout<<"usage:\n./pcpt -t training_file -m model_file -i iter_num\n./pcpt -d testing_file -m model_file\n"; return 0; } if (argv[1][1] == 't') { string train_file(argv[2]); string model_file(argv[4]); size_t round(stoi(argv[6])); string mode("train"); Data my_data(mode,train_file); size_t line = my_data.get_size(); Model my_model(mode,model_file,line,round); Perceptron my_pcpt(&my_data,&my_model,line,round); my_pcpt.train(train_file); } else if (argv[1][1] == 'd') { string test_file(argv[2]); string model_file(argv[4]); string mode("test"); Data my_data(mode,test_file); size_t line = my_data.get_size(); Model my_model(mode,model_file,line,0); Perceptron my_pcpt(&my_data,&my_model,line,0); my_pcpt.test(test_file); } b = clock(); cout<<"time cost: "<<double(b-a)/CLOCKS_PER_SEC<<endl; return 0; } <file_sep>#include "stdafx.h" void TrimLine(string &line); int s2i(string &s); double s2d(string &s); string i2s(int i); void Split(vector<string> &vs, string &s); void Split(vector<string> &vs, string &s, string &sep); size_t fnv1_hash(const vector<int> &ivec); size_t djb2_hash(const vector<int> &ivec); size_t bkdr_hash(const vector<int> &ivec); <file_sep>#include "stdafx.h" #include "data.h" #include "decoder.h" class Perceptron { public: Perceptron(Data *data,Model *model,size_t line,size_t round); void train(string &train_file); void test(string &test_file); private: size_t ROUND; size_t LINE; size_t m_line; size_t m_round; Model *m_model; Data *m_data; };
ab7669e28c14548b0fc326954b6d70f0b8599bb9
[ "C", "Makefile", "C++" ]
13
C++
lixiaoqing/perceptron
c266f07ce9473871d45bab194f6540507d8aa505
0c1be5fa7b310705a12a6ada6129250dd169bfe9
refs/heads/master
<file_sep><!-- Please update value in the {} --> <h1 align="center">App Motorcyclists</h1> <div align="center"> <h3> <a href="https://motorcyclists.netlify.app/"> Demo </a> <span> | </span> <a href="https://github.com/sedian27/App-Motorcyclists"> Solution </a> </h3> </div> <!-- TABLE OF CONTENTS --> ## Table of Contents - [Table of Contents](#table-of-contents) - [Overview](#overview) - [Built With](#built-with) - [Features](#features) - [Requirements](#requirements) - [Use cases](#use-cases) - [Contact](#contact) <!-- OVERVIEW --> ## Overview ![screenshot](./01.png) ### Built With <!-- This section should list any major frameworks that you built your project using. Here are a few examples.--> - HTML5 - Bootstrap - JavaScript - Firebase ## Features <!-- List the features of your application or follow the template. Don't share the figma file here :) --> Mi primera aplicacion con firebase, esta aplicación cumple con los casos de uso y requisitos pedidos. #### Requirements - Lista que contenga tramos horarios en intervalos de 30 minutos - Que inicie a las 8 am y termine a las 8 pm. - La empresa tiene una disponibilidad de 8 motociclistas cada 30 minutos. - Si otros usuarios han tomado todos los recursos la fila debe ser de color rojo. #### Use cases - El usuario podra adquirir un recurso si este se encuentra disponible. - El usuario solo podrá agarrar 1 recursos de cada horario. - El usuario podrá liberar el recurso. ## Contact - GitHub [@sedian27](https://github.com/sedian27) - Web [sergiodiestra.com](https://sergiodiestra.com) - LinkedIn [<NAME>](https://www.linkedin.com/in/segio-diestra-andrade-596276174/) <file_sep>import Storage from "./localstorage.js"; import Firebase from "./firebase.js"; document.addEventListener("DOMContentLoaded", () => { const db = new Firebase(); const storage = new Storage(); const table = document.getElementById("table"); document.addEventListener("click", select); window.addEventListener("DOMContentLoaded", async () => { db.onGetData((querySnapshot) => { table.innerHTML = ""; querySnapshot.forEach((doc) => { insertDt(doc.id, doc.data()); }); storage.loadStorage(); }); }); function insertDt(id, arr) { const row = table.insertRow(); row.setAttribute("id", id); let status = "No Disponible"; if (arr.amount > 0) { status = "Disponible"; } else { row.className += "bg-danger"; } row.innerHTML = ` <td>${arr.hour}</td> <td>${arr.amount}</td> <td>${status}</td> `; } const validation = (id) => { db.updateData(id, { amount: 8 }); return 8; }; async function select(e) { const id = e.target.parentElement.getAttribute("id"); let selectedRow = document.getElementById(id); const isSelected = selectedRow.className == "bg-success"; const doc = await db.getData(id); let amount = doc.data().amount > 8 ? validation(id) : doc.data().amount; if (!isSelected && amount > 0) { db.updateData(id, { amount: --amount }); selectedRow.className = "bg-success"; storage.addSelected(id); } else if (isSelected && amount < 8) { db.updateData(id, { amount: ++amount }); selectedRow.className = ""; storage.removeSelected(id); } } });
cf557ff1fc4b35e70d4db6b483cb4d89e5ee8d20
[ "Markdown", "JavaScript" ]
2
Markdown
sedian27/App-Motorcyclists
f0b3af22a1697791aaa5674f311cd4977b6c0b7a
ded46191f0676e6f86d536ff11ce7a7ee0c1bb5c
refs/heads/master
<file_sep>import warnings from asl_data import SinglesData def recognize(models: dict, test_set: SinglesData): """ Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...} :param test_set: SinglesData object :return: (list, list) as probabilities, guesses both lists are ordered by the test set word_id probabilities is a list of dictionaries where each key a word and value is Log Liklihood [{SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... }, {SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... }, ] guesses is a list of the best guess words ordered by the test set word_id ['WORDGUESS0', 'WORDGUESS1', 'WORDGUESS2',...] """ warnings.filterwarnings("ignore", category=DeprecationWarning) probabilities = [] guesses = [] # Implement the recognizer # Iterate through the test_set unknown words for word_id in range(len(test_set.get_all_sequences())): # Create a dictionary for this test word with keys = known words and values = score from model applied to test word prob_dict = dict() test_X,test_lengths = test_set.get_all_Xlengths()[word_id] for known_word,model in models.items(): try: prob_dict[known_word] = model.score(test_X,test_lengths) except: prob_dict[known_word] = float('-inf') # Add this dictionary to probabilities probabilities.append(prob_dict) # Add the known_word with highest prob to guesses. best_word = max(prob_dict, key=prob_dict.get) guesses.append(best_word) # return probabilities, guesses return probabilities, guesses
dc5dccb7f0bbe961e33d215e1fcaa6ec213e0646
[ "Python" ]
1
Python
awtotty/asl_recognizer
557911937ba2484009842652cb2b089364ac1179
939eaab463a38b40e475fe430585f2df02afbc56
refs/heads/master
<file_sep>package channelService import ( "errors" "github.com/kudoochui/kudos/log" "github.com/kudoochui/kudos/rpc" "github.com/kudoochui/kudos/service/codecService" "github.com/kudoochui/kudos/service/rpcClientService" "github.com/kudoochui/kudos/utils/array" "sync" ) type Channel struct { name string group map[int64]*rpc.Session //uid => session nodeMap map[string][]int64 //address => [sessionId] lock sync.RWMutex } func NewChannel(name string) *Channel { return &Channel{ name: name, group: map[int64]*rpc.Session{}, nodeMap: map[string][]int64{}, } } // Add user to channel. func (c *Channel) Add(s *rpc.Session) error { c.lock.Lock() defer c.lock.Unlock() if _,ok := c.group[s.GetUserId()]; ok { return errors.New("already in channel") } c.group[s.GetUserId()] = s.Clone() a := c.nodeMap[s.NodeId] if a != nil { c.nodeMap[s.NodeId] = append(a, s.GetSessionId()) } else { a = make([]int64,0) c.nodeMap[s.NodeId] = append(a, s.GetSessionId()) } return nil } // Remove user from channel. func (c *Channel) Leave(uid int64) { c.lock.Lock() defer c.lock.Unlock() s := c.group[uid] if s == nil { return } if a, ok := c.nodeMap[s.NodeId]; ok { c.nodeMap[s.NodeId] = array.PullInt64(a, s.GetSessionId()) } delete(c.group, uid) } // Get userId array func (c *Channel) GetMembers() []int64 { c.lock.RLock() defer c.lock.RUnlock() array := make([]int64, 0) for k,_ := range c.group { array = append(array, k) } return array } func (c *Channel) GetSessions() map[int64]*rpc.Session { c.lock.RLock() defer c.lock.RUnlock() m := make(map[int64]*rpc.Session, 0) for k,v := range c.group { m[k] = v } return m } // Push message to all the members in the channel, exclude uid in the excludeUid. func (c *Channel) PushMessage(route string, msg interface{}, excludeUid []int64) { data, err := codecService.GetCodecService().Marshal(msg) if err != nil { log.Error("marshal error: %v", err) } c.lock.RLock() nodeMap := make(map[string][]int64, 0) for k,v := range c.nodeMap { w := make([]int64, len(v)) copy(w, v) nodeMap[k] = w } if len(excludeUid) > 0 { for _,uid := range excludeUid { if s,ok := c.group[uid]; ok { if a, ok := nodeMap[s.NodeId]; ok { nodeMap[s.NodeId] = array.PullInt64(a, s.GetSessionId()) } } } } c.lock.RUnlock() for nodeId, sids := range nodeMap { args := &rpc.ArgsGroup{ Sids: sids, Route: route, Payload: data, } reply := &rpc.ReplyGroup{} rpcClientService.GetRpcClientService().Go(nodeId+"@ChannelRemote","PushMessageByGroup", args, reply, nil) } } <file_sep>package connector import ( "context" "github.com/kudoochui/kudos/rpc" msgService "github.com/kudoochui/kudos/service/msgService" ) type ChannelRemote struct { connector Connector } func NewChannelRemote(conn Connector) *ChannelRemote { return &ChannelRemote{connector:conn} } // Push message to client by uids. func (c *ChannelRemote) PushMessageByGroup(ctx context.Context, args *rpc.ArgsGroup, reply *rpc.ReplyGroup) error { //log.Debug(">>>> %s push: %s, %+v, %s", c.connector.opts.WSAddr, args.Route, args.Sids, string(args.Payload)) for _, sid := range args.Sids { if a, err := c.connector.GetSessionMap().GetAgent(sid); err == nil { routeId := msgService.GetMsgService().GetRouteId(args.Route) a.PushMessage(routeId, args.Payload) } } return nil } // Broadcast to all the client connectd with current frontend server. func (c *ChannelRemote) Broadcast(ctx context.Context, args *rpc.ArgsGroup, reply *rpc.ReplyGroup) error { //log.Debug(">>>> %s broadcast: %s, %s", c.connector.opts.WSAddr, args.Route, string(args.Payload)) c.connector.GetSessionMap().Range(func(key, value interface{}) bool { routeId := msgService.GetMsgService().GetRouteId(args.Route) value.(Agent).PushMessage(routeId, args.Payload) return true }) return nil }<file_sep>module github.com/kudoochui/kudos go 1.15 require ( github.com/OwnLocal/goes v1.0.0 github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542 github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 github.com/gogo/protobuf v1.3.1 github.com/golang/protobuf v1.4.3 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/json-iterator/go v1.1.10 github.com/kudoochui/rpcx v0.0.0-20210323121129-7ba90168bdfa github.com/mitchellh/mapstructure v1.3.3 github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 github.com/smallnest/libkv-etcdv3-store v1.1.9 // indirect github.com/wendal/errors v0.0.0-20181209125328-7f31f4b264ec // indirect github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 // indirect google.golang.org/grpc/examples v0.0.0-20210322221411-d26af8e39165 // indirect gotest.tools v2.2.0+incompatible ) <file_sep>package rpc import ( "github.com/kudoochui/kudos/service/idService" "github.com/kudoochui/kudos/service/rpcClientService" "sync" ) type Session struct { NodeId string SessionId int64 UserId int64 userIdLock sync.RWMutex Settings map[string]string } func NewSession(nodeId string) *Session { return &Session{ NodeId: nodeId, SessionId: idService.GenerateID().Int64(), Settings: map[string]string{}, } } func (s *Session) GetSessionId() int64 { return s.SessionId } func (s *Session) GetUserId() int64 { s.userIdLock.RLock() defer s.userIdLock.RUnlock() return s.UserId } func (s *Session) SetUserId(userId int64) { s.userIdLock.Lock() defer s.userIdLock.Unlock() s.UserId = userId } func (s *Session) SyncSettings(settings map[string]interface{}) { _settings := make(map[string]string) for k,v := range settings { _settings[k] = v.(string) } s.Settings = _settings } func (s *Session) Bind(userId int64) { s.UserId = userId args := &Args{ Session: *s, MsgReq: userId, } reply := &Reply{} rpcClientService.GetRpcClientService().Call(s.NodeId+"@SessionRemote","Bind", args, reply) } func (s *Session) UnBind() { s.UserId = 0 args := &Args{ Session: *s, } reply := &Reply{} rpcClientService.GetRpcClientService().Call(s.NodeId+"@SessionRemote","UnBind", args, reply) } func (s *Session) Get(key string) string { return s.Settings[key] } func (s *Session) Set(key, value string) { if s.Settings == nil { s.Settings = make(map[string]string) } s.Settings[key] = value } func (s *Session) Remove(key string) { delete(s.Settings, key) } func (s *Session) Clone() *Session { session := &Session{ NodeId: s.NodeId, SessionId: s.SessionId, UserId: s.UserId, Settings: map[string]string{}, } for k,v := range s.Settings { session.Settings[k] = v } return session } // synchronize setting with frontend session func (s *Session) Push(){ args := &Args{ Session: *s, MsgReq: s.Settings, } reply := &Reply{} rpcClientService.GetRpcClientService().Call(s.NodeId+"@SessionRemote","Push", args, reply) } func (s *Session) Close(reason string) { args := &Args{ Session: *s, MsgReq: reason, } reply := &Reply{} rpcClientService.GetRpcClientService().Call(s.NodeId+"@SessionRemote","KickBySid", args, reply) }<file_sep>package channelService import ( "github.com/kudoochui/kudos/log" "github.com/kudoochui/kudos/rpc" "github.com/kudoochui/kudos/service/codecService" "github.com/kudoochui/kudos/service/rpcClientService" "sync" ) var _channelService *ChannelService var once sync.Once type ChannelService struct { channels sync.Map } func GetChannelService() *ChannelService { once.Do(func() { _channelService = &ChannelService{ } }) return _channelService } func (c *ChannelService) CreateChannel(name string) *Channel { channel := NewChannel(name) c.channels.Store(name, channel) return channel } func (c *ChannelService) DestroyChannel(name string) { c.channels.Delete(name) } func (c *ChannelService) GetChannel(name string) *Channel { channel, ok := c.channels.Load(name) if ok { return channel.(*Channel) } return nil } func (c *ChannelService) PushMessageBySid(nodeId string, route string, msg interface{}, sids []int64) { data, err := codecService.GetCodecService().Marshal(msg) if err != nil { log.Error("marshal error: %v", err) } args := &rpc.ArgsGroup{ Sids: sids, Route: route, Payload: data, } reply := &rpc.ReplyGroup{} rpcClientService.GetRpcClientService().Call(nodeId+"@ChannelRemote","PushMessageByGroup", args, reply) } func (c *ChannelService) AsyncPushMessageBySid(nodeId string, route string, msg interface{}, sids []int64) { data, err := codecService.GetCodecService().Marshal(msg) if err != nil { log.Error("marshal error: %v", err) } args := &rpc.ArgsGroup{ Sids: sids, Route: route, Payload: data, } reply := &rpc.ReplyGroup{} rpcClientService.GetRpcClientService().Go(nodeId+"@ChannelRemote","PushMessageByGroup", args, reply, nil) } func (c *ChannelService) Broadcast(nodeId string, route string, msg interface{}) { data, err := codecService.GetCodecService().Marshal(msg) if err != nil { log.Error("marshal error: %v", err) } args := &rpc.ArgsGroup{ Sids: []int64{}, Route: route, Payload: data, } reply := &rpc.ReplyGroup{} rpcClientService.GetRpcClientService().Go(nodeId+"@ChannelRemote","Broadcast", args, reply, nil) }
ee2e70595f7bc7d2ffcf320c8c637227b8690146
[ "Go Module", "Go" ]
5
Go
loveyfore/kudos
26a360c1689f6cfe8e31c09a67f9f0e133d3372c
f37bb49e198e33eafa0481b9e8dae3554a2310b3
refs/heads/master
<repo_name>vanbungkring/Basic-CRUD_Typescript<file_sep>/src/core/models/book.model.ts import mongoose from "mongoose"; import { Model } from "./model.interface"; export interface IBook{ _id: any; title: string; author: string; year: number; } export type BookDocument = mongoose.Document & { _id: any; title: string; author: string; year: number; } export default MBook;<file_sep>/src/core/service/book/book.worker.ts import QueryProxy from '@core/util/storage/queryProxy' import MBook from '@core/models/book.model'; class BookWorker { qp: QueryProxy constructor() { this.qp = new QueryProxy(MBook) } } export default BookWorker<file_sep>/src/core/models/model.interface.ts export enum Model{ Book = 'Book' }<file_sep>/src/app.ts import express from "express"; const app = express(); const port = process.env.PORT || 3000; app.get('/',function(req,res) { res.sendFile(__dirname + '/index.html'); }); app.listen(port, function () { console.log('Updated : Server listening at port %d', port); }); <file_sep>/src/core/util/storage/queryproxy.ts import mongoose from "mongoose"; import { IRepository } from "@core/util/storage/repository"; import { logger } from "@core/util/logger/logger"; class QueryProxy implements IRepository { public model: mongoose.Model<mongoose.Document>; constructor(modelName: mongoose.Model<mongoose.Document>) { this.model = modelName; } public async create(data: any): Promise<any> { const p = new Promise((resolve, reject) => { const q = new this.model(data); q.save((err, result) => { if (err) { reject(err); } else { logger.info(result) resolve(result); } }); }); return p; } public async find(err:any, data:any): Promise<any> { // tslint:disable-next-line: no-shadowed-variable const p = new Promise((resolve, reject) => { const q = new this.model(data); q.save((err, result) => { if (err) { reject(err); } else { logger.info(result) resolve(result); } }); }); return p; } public async findById(id: string): Promise<any> { const p = new Promise((resolve, reject) => { const q = this.model.findById(id); q.exec((err, result) => { if (err) { logger.info(err) reject(err); } else { logger.info(result) resolve(result); } }); }); return p; } public async findByIdAndUpdate(id: string, params: any): Promise<any> { const p = new Promise((resolve, reject) => { const q = this.model.findByIdAndUpdate(id, params) q.exec((err, result) => { if (err) { logger.info(err) reject(err); } else { logger.info(result) resolve(result); } }); }); return p; } public async deleteOne(data: any): Promise<any> { const p = new Promise((resolve, reject) => { const q = this.model.remove(data); q.exec((err, result) => { if (err) { logger.info(err) reject(err); } else { logger.info(result) resolve(result); } }); }); return p; } } export default QueryProxy;<file_sep>/src/core/service/book/book.service.ts // import {Request, Response, request} from "express"; // import Book from './../book'; // import BookWorker from "./book.worker"; // class BookService { // worker: any; // initRouter() { // throw new Error("Method not implemented."); // } // constructor() { // this.initRouter(); // this.worker = new BookWorker(); // } // } // // GET = returns all books // export let allBooks = (req:Request, res: Response)=>{ // let books = Book.find((err: any, book: any) => { // if(err){ // res.send(err); // }else{ // res.send(books); // } // }) // } // // GET = returns book by id // export let getBooks = (req:Request, res: Response)=>{ // Book.findById(req.params.id, (err:any, book:any)=>{ // if(err){ // res.send(err); // }else{ // res.send(book); // } // }) // } // // PUT = adding new book // export let addBook = (req:Request, res:Response)=>{ // let book = new Book(req.body); // book.save((err:any)=> // { // if(err){ // res.send(err); // }else{ // res.send(book); // } // }) // } // // DELETE = delete book // export let deleteBook = (req:Request, res:Response)=>{ // Book.deleteOne({_id: req.params.id}, (err:any)=> // { // if(err){ // res.send(err); // }else{ // res.send("Successfully deteled the book"); // } // }) // } // // UPDATE = update book // export let updateBook = (req:Request, res:Response)=>{ // Book.findByIdandUpdate(req.params.id, req.body, (err: any, book:any)=>{ // if(err){ // res.send(err); // }else{ // res.send("Successfully updated the book"); // } // }) // } <file_sep>/src/core/util/storage/repository.ts import mongoose from 'mongoose'; export interface IRepository { model: mongoose.Model<mongoose.Document>; deleteOne(data:any): Promise<any>; // findAll(data: any, params?: any, skip?: number, limit?: number): Promise<any>; find(err:any, data:any): Promise<any>; findById(id:string): Promise<any>; findByIdAndUpdate(id: string, params: any): Promise<any>; create(data: [any]): Promise<any>; // createMany(data: any): Promise<any>; // updateMany(err:any, data:any): Promise<any>; // update(err:any, data:any): Promise<any>; // aggregate(data:any): Promise<any>; }
ede00a53584905e6922e4e644809f0add1dc4009
[ "TypeScript" ]
7
TypeScript
vanbungkring/Basic-CRUD_Typescript
d33cc3204a57be107521c2b999fd43c3a811511f
b1fa27b66fbacda27424298fc760b7344acfb1e7
refs/heads/master
<file_sep>from server import RequestHandler, run_forever def test_do_GET(): run_forever() assert do_GET() <file_sep>from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs from cowpy import cow import requests import json class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): """ Method to create routes on '/' and '/cow' and create cow instances and drawings based on whether there is a query string and what the contents of that query string are. """ parsed_path = urlparse(self.path) parsed_qs = parse_qs(parsed_path.query) link = '<a href="/cow">Click Here for Fun Stuffs</a>' if parsed_path.path == '/': self.send_response(200) self.send_header('content-type', 'text/html') self.end_headers() animal = cow.Stegosaurus() msg = animal.milk(link) self.wfile.write(f'<!DOCTYPE html><html><head><title>Click Me</title></head><body><header></header><main style="font-family:monospace; font-weight:bold; color:green;"><pre>{msg}</pre></main></body></html>'.encode()) return elif parsed_path.path == '/cow': if parsed_qs: try: message = parsed_qs['msg'][0] animal = cow.Turkey() msg = animal.milk(message) except KeyError: self.send_response(400) self.end_headers() self.wfile.write(f'<!DOCTYPE html><html><head><title>Sample</title></head><body><header><header><main font-family=monospace><pre>{msg}</pre></br></br><h2>Instructions:</h2><p>In the url, after "/cow" type "?msg=" and your message. Instead of spaces, use the "+" sign, and please avoid using special characters!</p></main></body></html>'.encode()) return else: message = "Isn't this fun!? Wanna try?" animal = cow.Tux() msg = animal.milk(message) self.send_response(200) self.end_headers() self.wfile.write(f'<!DOCTYPE html><html><head><title>{message}</title></head><body><header><header><main font-family=monospace><pre>{msg}</pre></br></br><h2>Instructions:</h2><p>In the url, after "/cow" type "?msg=" and your message. Instead of spaces, use the "+" sign, and please avoid using special characters!</p></main></body></html>'.encode()) else: self.send_response_only(404) self.end_headers() def do_POST(self): """ Method to create POST route on any path that returns a JSON object with the client's query string as the value of key 'msg'. """ content_length = int(self.headers.get('Content-Length')) post_body = self.rfile.read(content_length).decode() parsed_json = json.loads(post_body) message = parsed_json['msg'] animal = cow.Squirrel() msg = animal.milk(message) self.send_response(200) self.send_header('content-type', 'text/html') self.end_headers() def run_forever(): """ Method to start up the server. """ port = 5000 server_address = ('localhost', port) server = HTTPServer(server_address, RequestHandler) try: print(f'Starting server on PORT {port}') server.serve_forever() except KeyboardInterrupt: server.server_close() server.shutdown() if __name__ == "__main__": run_forever() <file_sep># http-server **Author**: <NAME> & <NAME> **Version**: 1.0.0 ## Overview This is a simple HTTP server with get routes on '/' and '/cow'. The functionality of the server allows a client to append a query string to the '/cow' path to produce a string that will populate the word bubble of a cowsay drawing. The server will also return a JSON object with a key of 'msg' and a value of a string of a new cowpie drawing with a user's params from a POST request. ## Getting Started To run the application, you will want to create a virtual environment with `pipenv shell` and run `pipenv install` to install the dependencies. From there, you can fire up the server by running `python server.py`. To start, a user can navigate to the index page. For our purposes, we used localhost and port 5000. On that index page, we have a cowsay drawing with a link to take them to the '/cow' route. Once there, they have a set of instructions showing them how to append a query string to the end of the url. When they submit the updated url, the get route will take their query string and convert it to a string that gets passed in to a new cow instance and will return the cowsay drawing with their query string as the text in the word bubble. ## Architecture We are using Python version 3.7 for this application and utilizing the cowpy, httpie, urllib, json and requests libraries. Please refer to the Pipfile for a list of dependencies. ## API cowpy requests httpie
ca084b19996d374a45439aa58af946fb31531f89
[ "Markdown", "Python" ]
3
Python
chrisba11/http-server
b2b1b3c4ffa442d2fbba5cb3a31967745e300f0d
a6dc93d31314def4ff625fa6400345310592eaa7
refs/heads/master
<file_sep>package com.wenxianm.service.user; import com.wenxianm.exception.SerException; import com.wenxianm.model.bo.user.Client; /** * 在线用户管理 * * @Author: [caiwenxian] * @Date: [2018-03-08 15:48] * @Description: [ ] * @Version: [1.0.0] */ public interface IClientService { /** * 获取当前用户 * * @param * @return class * @version v1 */ Client getCurrentUser() throws SerException; /** * 添加在线用户 * * @param * @return class * @version v1 */ void addCurrentUser(Client client) throws SerException; } <file_sep>package com.wenxianm.model.enums; public enum C { EQ, NE, LIKE, DA, IXAO, IN; public static String getSqlWhere(C c) { switch (c) { case EQ: return "="; case NE: return "<>"; case LIKE: return "like"; case DA: return ">"; case IXAO: return "<"; case IN: return "in"; default: return "="; } } } <file_sep>package exception; public class ErrorCode { static public int GENERAL = 303; } <file_sep>package model.po.music; import model.po.common.BasePO; /** * 歌单 * * @Author: [caiwenxian] * @Date: [2018-02-08 10:35] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class SongListPO extends BasePO { /** * 歌单id */ private String songListId; /** * 歌单名称 */ private String name; /** * 图片url */ private String picUrl; /** * 播放量 */ private Integer playCount; /** * 来源 */ private String origin; /** * 更新时间 */ private String trackUpdateTime; public SongListPO() { } public SongListPO(String songListId, String name, String picUrl, Integer playCount, String origin, String trackUpdateTime) { this.songListId = songListId; this.name = name; this.picUrl = picUrl; this.playCount = playCount; this.origin = origin; this.trackUpdateTime = trackUpdateTime; } public String getSongListId() { return songListId; } public void setSongListId(String songListId) { this.songListId = songListId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public Integer getPlayCount() { return playCount; } public void setPlayCount(Integer playCount) { this.playCount = playCount; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getTrackUpdateTime() { return trackUpdateTime; } public void setTrackUpdateTime(String trackUpdateTime) { this.trackUpdateTime = trackUpdateTime; } } <file_sep>package com.wenxianm.service.common.impl; import org.apache.log4j.Logger; import com.wenxianm.service.common.IBaseService; public class BaseServiceImpl implements IBaseService { protected Logger logger = Logger.getLogger(getClass()); } <file_sep>package model.dto.music; import model.dto.common.BaseDTO; import model.enums.music.TopListType; /** * @Author: [caiwenxian] * @Date: [2018-01-18 17:53] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class TopListDTO extends BaseDTO { /** * 排行榜类型 */ private TopListType topListType; public TopListType getTopListType() { return topListType; } public void setTopListType(TopListType topListType) { this.topListType = topListType; } public TopListDTO() { } public TopListDTO(TopListType topListType) { this.topListType = topListType; } @Override public String toString() { return "TopListDTO{" + "topListType=" + topListType + '}'; } } <file_sep>package com.wenxianm.service.music.reptile.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.wenxianm.exception.SerException; import com.wenxianm.model.constant.NetseaseUrl; import com.wenxianm.model.dto.music.ArtistHotSongDTO; import com.wenxianm.model.dto.music.MusicDTO; import com.wenxianm.model.dto.music.SongListDTO; import com.wenxianm.model.dto.music.TopListDTO; import com.wenxianm.model.enums.music.Origin; import com.wenxianm.model.enums.music.TopListType; import com.wenxianm.model.po.music.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wenxianm.service.common.impl.BaseServiceImpl; import com.wenxianm.model.po.mq.MessagePO; import com.wenxianm.service.mq.rabbitmq.RabbitProducer; import com.wenxianm.service.music.IArtistHotSongService; import com.wenxianm.service.music.IArtistService; import com.wenxianm.service.music.ISongService; import com.wenxianm.service.music.ITopListService; import com.wenxianm.service.music.reptile.IReptileSongService; import com.wenxianm.utils.HttpClientHelper; import java.net.URLEncoder; import java.util.Calendar; import java.util.Iterator; /** * @Author: [caiwenxian] * @Date: [2018-01-30 09:38] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Service public class ReptileSongServiceImpl extends BaseServiceImpl implements IReptileSongService { @Autowired ISongService songService; @Autowired IArtistService artistService; @Autowired ITopListService topListService; @Autowired IArtistHotSongService artistHotSongService; @Autowired private RabbitProducer rabbiProducer; public void reptileTopSongs(TopListDTO dto) throws SerException { try { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/playlist/detail?id="); String url2 = TopListType.getId(dto.getTopListType().getCode()); url.append(url2); url.append("&limit=" + dto.getLimit()); url.append("&order=new"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONObject object = (JSONObject) jsonObject.get("result"); JSONArray songs = object.getJSONArray("tracks"); //保存排行榜 String topListId = object.getString("id"); String topListName = object.getString("name"); String trackUpdateTime = object.getString("trackUpdateTime"); TopListPO old = topListService.getByTopListId(topListId); if (old != null && trackUpdateTime.equals(old.getTrackUpdateTime())) { logger.info("官方排行榜暂未更新"); return; // throw new SerException("官方排行榜暂未更新"); } if (old != null && !trackUpdateTime.equals(old.getTrackUpdateTime())) { logger.info("官方排行榜已更新"); //删除旧排行榜歌曲 topListService.deleteTopListDetails(old.getTopListId()); } topListService.addTopList(new TopListPO(topListName, topListId, Origin.WANG_YI.name(), trackUpdateTime)); Iterator<Object> it = songs.iterator(); int num = 1; while (it.hasNext()) { JSONObject song = (JSONObject) it.next(); JSONArray artist = song.getJSONArray("artists"); //保存歌手 ArtistPO artistPO = new ArtistPO(); artistPO.setArtistId(artist.getJSONObject(0).getString("id")); artistPO.setName(artist.getJSONObject(0).getString("name")); artistPO.setOrigin(Origin.WANG_YI.getName()); artistService.addArtist(artistPO); //保存歌曲 SongInfoPO po = new SongInfoPO(); String songId = song.getString("id"); po.setSongId(songId); po.setName(song.getString("name")); po.setArtistId(artistPO.getArtistId()); po.setOrigin(Origin.WANG_YI.getName()); songService.addSong(po); //爬取歌曲url // songService.reptileMp3Url(po.getSongId()); //排行榜-歌曲关联 topListService.addTopListDetails(new TopListDetailsPO(topListId, songId, num)); num++; } logger.info("爬取排行榜列表完成" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } public void reptileAllTopSongs() throws SerException { try { for (TopListType topListType : TopListType.values()) { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/playlist/detail?id="); String url2 = TopListType.getId(topListType.getCode()); url.append(url2); url.append("&limit=100"); url.append("&order=new"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONObject object = (JSONObject) jsonObject.get("result"); JSONArray songs = object.getJSONArray("tracks"); //保存排行榜 String topListId = object.getString("id"); String topListName = object.getString("name"); String trackUpdateTime = object.getString("trackUpdateTime"); TopListPO old = topListService.getByTopListId(topListId); if (old != null && trackUpdateTime.equals(old.getTrackUpdateTime())) { logger.info(topListType.getName() + ":官方排行榜暂未更新"); continue; } if (old != null && !trackUpdateTime.equals(old.getTrackUpdateTime())) { logger.info(topListType.getName() + ":官方排行榜已更新"); //删除旧排行榜歌曲 topListService.deleteTopListDetails(old.getTopListId()); } topListService.addTopList(new TopListPO(topListName, topListId, Origin.WANG_YI.name(), trackUpdateTime)); Iterator<Object> it = songs.iterator(); int num = 1; while (it.hasNext()) { JSONObject song = (JSONObject) it.next(); JSONArray artist = song.getJSONArray("artists"); //保存歌手 ArtistPO artistPO = new ArtistPO(); artistPO.setArtistId(artist.getJSONObject(0).getString("id")); artistPO.setName(artist.getJSONObject(0).getString("name")); artistPO.setOrigin(Origin.WANG_YI.getName()); artistService.addArtist(artistPO); //保存歌曲 SongInfoPO po = new SongInfoPO(); String songId = song.getString("id"); po.setSongId(songId); po.setName(song.getString("name")); po.setArtistId(artistPO.getArtistId()); po.setOrigin(Origin.WANG_YI.getName()); songService.addSong(po); //排行榜-歌曲关联 topListService.addTopListDetails(new TopListDetailsPO(topListId, songId, num)); num++; } //睡眠1s Thread.sleep(1000); } logger.info("爬取排行榜列表完成" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } @Override public void reptileMp3Url(String songId) throws SerException { /*Thread thread = new Thread(new ReptilepMp3(songId)); thread.start();*/ //放到消息队列 try { MessagePO messagePO = new MessagePO(); messagePO.setData(songId); messagePO.setType("2"); //发送到消息队列 rabbiProducer.sendMessageQueue2(messagePO); } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } @Override public void reptileMp3UrlV2(String songId) throws SerException { try { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/song/enhance/player/url/"); url.append("?id=" + songId); url.append("&ids=[" + songId + "]"); url.append("&br=3200000"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONArray songs = jsonObject.getJSONArray("data"); JSONObject song = songs.getJSONObject(0); String map3Url = song.getString("url"); String size = song.getString("size"); String type = song.getString("type"); logger.info("爬取mp3url完成"); //添加歌曲mp3url songService.addMp3Url(songId, map3Url); } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } @Override public void reptileHotSongs(ArtistHotSongDTO dto) throws SerException { try { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/search/pc/"); url.append("?s=" + URLEncoder.encode(dto.getName())); url.append("&limit=1"); url.append("&type=100"); url.append("&offset=0"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONObject object = (JSONObject) jsonObject.get("result"); JSONArray artists = object.getJSONArray("artists"); if (artists == null || artists.size() < 1) { throw new SerException("未爬取到相关信息"); } JSONObject artist = (JSONObject) artists.get(0); ArtistPO artistPO = new ArtistPO(); artistPO.setArtistId(artist.getString("id")); artistPO.setName(artist.getString("name")); artistPO.setOrigin(Origin.WANG_YI.getName()); artistService.addArtist(artistPO); logger.info("爬取歌手完成"); //爬取歌曲 StringBuffer url2 = new StringBuffer(); url2.append("http://music.163.com/api/artist/"); url2.append(artistPO.getArtistId()); url2.append("?limit=" + dto.getLimit()); url2.append("&offset=0"); String result2 = HttpClientHelper.sendGet(url2.toString(), null, "UTF8"); JSONObject jsonObject2 = JSONObject.parseObject(result2); String code = jsonObject2.getString("code"); JSONArray songs = jsonObject2.getJSONArray("hotSongs"); //热门歌曲 //保存歌曲 int num = 1; for (Object song1 : songs) { JSONObject song = (JSONObject) song1; SongInfoPO po = new SongInfoPO(); String songId = song.getString("id"); po.setSongId(songId); po.setName(song.getString("name")); po.setArtistId(artistPO.getArtistId()); po.setOrigin(Origin.WANG_YI.getName()); songService.addSong(po); //爬取歌曲url // songService.reptileMp3Url(po.getSongId()); //歌手-热门歌曲关联 ArtistHotSongPO artistHotSongPO = new ArtistHotSongPO(songId, artistPO.getArtistId(), num); artistHotSongService.addArtistHotSong(artistHotSongPO); num++; } num = 1; } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } @Override public void reptileSongs(String name) throws SerException { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/search/pc/"); url.append("?s=" + name); url.append("&limit=10"); url.append("&type=1"); url.append("&offset=0"); String result = HttpClientHelper.sendPost(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONObject object = (JSONObject) jsonObject.get("result"); JSONArray songs = object.getJSONArray("songs"); int num = 1; for (Object song1 : songs) { JSONObject song = (JSONObject) song1; SongInfoPO songInfoPO = new SongInfoPO(); songInfoPO.setSongId(song.getString("id")); songInfoPO.setName(song.getString("name")); songInfoPO.setNum(num); songInfoPO.setOrigin(Origin.WANG_YI.getName()); songService.addSong(songInfoPO); num++; } logger.info("爬取歌曲完成"); } @Override public void asynReptile(int type, Object[] params) throws SerException { Thread thread = new Thread(new Reptilep(type, params)); thread.start(); } @Override public void reptileRecommendSongList(Integer offset, Integer limit) throws SerException { try { offset = offset == null ? 0 : offset; limit = limit == 0 ? 10 : limit; StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/personalized/playlist"); url.append("?offset=" + offset); url.append("&limit=" + limit); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); if (!"200".equals(jsonObject.getString("code"))) { return; } JSONArray object = jsonObject.getJSONArray("result"); int num = 1; for (Object song1 : object) { JSONObject song = (JSONObject) song1; String id = song.getString("id"); String name = song.getString("name"); String picUrl = song.getString("picUrl"); Integer playCount = song.getInteger("playCount"); SongListPO po = new SongListPO(id, name, picUrl, playCount, Origin.WANG_YI.name(), null); //新增歌单信息 songService.addSongList(po); //新增推荐歌单 songService.addRecommendSongList(new RecommendSongListPO(id, num, String.valueOf(Calendar.getInstance().getTimeInMillis()))); num++; //爬取歌单详细信息 reptileSongListDetails(po.getSongListId()); } logger.info("爬取推荐歌单完成:" + Calendar.getInstance().getTime()); } catch (SerException e) { e.printStackTrace(); throw new SerException(); } } /** * 爬取歌单详情 * * @param songListId */ private void reptileSongListDetails(String songListId) throws SerException { if (StringUtils.isBlank(songListId)) { return; } try { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/playlist/detail?id=" + songListId); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); if (!"200".equals(jsonObject.getString("code"))) { return; } JSONObject object = (JSONObject) jsonObject.get("result"); String trackUpdateTime = object.getString("trackUpdateTime"); //更新歌单trackUpdateTime songService.updateSongList(songListId, trackUpdateTime); //保存歌曲 JSONArray songs = object.getJSONArray("tracks"); int num = 1; for (Object ob : songs) { JSONObject song = (JSONObject) ob; song.put("num", num); song.put("songListId", songListId); MessagePO messagePO = new MessagePO(); messagePO.setData(song.toString()); messagePO.setType("1"); //发送到消息队列 rabbiProducer.sendMessage(messagePO); num++; /*JSONObject song = (JSONObject) song1; //保存歌手 JSONObject artist = (JSONObject) song.getJSONArray("artists").get(0); //歌手信息 ArtistPO artistPO = new ArtistPO(); String artistId = artist.getString("id"); artistPO.setArtistId(artistId); artistPO.setName(artist.getString("name")); artistPO.setOrigin(Origin.WANG_YI.getName()); artistService.addArtist(artistPO); String songId = song.getString("id"); String name = song.getString("name"); SongInfoPO songInfoPO = new SongInfoPO(songId, name, artistId, null, null, Origin.WANG_YI.name(), num); songService.addSong(songInfoPO); //保存歌单-歌曲关联 songService.addSongListDetails(new SongListDetailsPO(songListId, songId, num)); num++;*/ } } catch (Exception e) { logger.error("爬取歌单详情出错", e); } } public void saveSongWithSongList(JSONObject song) throws SerException { try { //保存歌手 JSONObject artist = (JSONObject) song.getJSONArray("artists").get(0); //歌手信息 ArtistPO artistPO = new ArtistPO(); String artistId = artist.getString("id"); artistPO.setArtistId(artistId); artistPO.setName(artist.getString("name")); artistPO.setOrigin(Origin.WANG_YI.getName()); artistService.addArtist(artistPO); //保存歌曲 String songId = song.getString("id"); String name = song.getString("name"); int num = Integer.valueOf(song.getString("num")); String songListId = song.getString("songListId"); SongInfoPO songInfoPO = new SongInfoPO(songId, name, artistId, null, null, Origin.WANG_YI.name(), num); songService.addSong(songInfoPO); //保存歌单-歌曲关联 songService.addSongListDetails(new SongListDetailsPO(songListId, songId, num)); } catch (SerException e) { logger.error(e.getMessage(), e); } } @Override public void reptileSongList(MusicDTO dto) throws SerException { int offset = (dto.getPage() - 1) * dto.getLimit(); StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/search/pc/"); url.append("?s=" + dto.getKeyword()); url.append("&limit=" + dto.getLimit()); url.append("&type=1000"); String result = HttpClientHelper.sendPost(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); if (!"200".equals(jsonObject.getString("code"))) { return; } JSONObject object = (JSONObject) jsonObject.get("result"); JSONArray songs = object.getJSONArray("playlists"); int num = 1; for (Object song1 : songs) { JSONObject song = (JSONObject) song1; String id = song.getString("id"); String name = song.getString("name"); String picUrl = song.getString("coverImgUrl"); Integer playCount = song.getInteger("playCount"); SongListPO po = new SongListPO(id, name, picUrl, playCount, Origin.WANG_YI.name(), null); songService.addSongList(po); songService.addRecommendSongList(new RecommendSongListPO(id, num, String.valueOf(Calendar.getInstance().getTimeInMillis()))); num++; reptileSongListDetails(po.getSongListId()); } logger.info("爬取推荐歌单完成:" + Calendar.getInstance().getTime()); } @Override public void reptileSongListByType(SongListDTO dto) throws SerException { try { // http://music.163.com/api/playlist/list/?limit=10&order=new&cat=华语&offset=0&total=true int offset = (dto.getPage() - 1) * dto.getLimit(); String order = dto.getOrder() == null ? "hot" : dto.getOrder(); String cat = dto.getSongListType() == null ? "全部" : dto.getSongListType().getName(); StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/playlist/list/"); url.append("?limit=" + dto.getLimit()); url.append("&order=" + order); url.append("&cat=" + URLEncoder.encode(cat)); url.append("&offset=" + offset); url.append("&total=true"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); if (!"200".equals(jsonObject.getString("code"))) { return; } // JSONObject object = (JSONObject)jsonObject.get("result"); JSONArray songs = jsonObject.getJSONArray("playlists"); int num = 1; for (Object song1 : songs) { JSONObject song = (JSONObject) song1; String id = song.getString("id"); String name = song.getString("name"); String picUrl = song.getString("coverImgUrl"); Integer playCount = song.getInteger("playCount"); String trackUpdateTime = song.getString("trackUpdateTime"); SongListPO po = new SongListPO(id, name, picUrl, playCount, Origin.WANG_YI.name(), trackUpdateTime); songService.addSongList(po); songService.addRecommendSongList(new RecommendSongListPO(id, num, String.valueOf(Calendar.getInstance().getTimeInMillis()))); num++; // reptileSongListDetails(po.getSongListId()); //开启多线程处理 new Thread(new Reptilep(3, new Object[]{po.getSongListId()})).start(); } logger.info("爬取歌单(按列别)完成:" + Calendar.getInstance().getTime()); } catch (Exception e) { e.printStackTrace(); throw new SerException(); } } /** * 异步爬取 * * @version v1 */ class Reptilep implements Runnable { private Integer type; private Object params[]; public Reptilep(Integer type, Object[] params) { this.type = type; this.params = params; } public void run() { try { switch (type) { case 1: //歌曲搜索 reptileSongs(String.valueOf(params[0])); break; case 2: //歌手热门歌曲 reptileHotSongs((ArtistHotSongDTO) params[0]); break; case 3: //歌单详情 reptileSongListDetails(String.valueOf(params[0])); break; default: break; } } catch (SerException e) { e.printStackTrace(); } } } void reptileMp3() { } /** * 异步爬取mp3url */ class ReptilepMp3 implements Runnable { private String songId; public ReptilepMp3(String songId) { this.songId = songId; } public void run() { StringBuffer url = new StringBuffer(); url.append(NetseaseUrl.API); url.append("/api/song/enhance/player/url/"); url.append("?id=" + this.songId); url.append("&ids=[" + this.songId + "]"); url.append("&br=3200000"); String result = HttpClientHelper.sendGet(url.toString(), null, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(result); JSONArray songs = jsonObject.getJSONArray("data"); JSONObject song = songs.getJSONObject(0); String map3Url = song.getString("url"); String size = song.getString("size"); String type = song.getString("type"); logger.info("爬取mp3url完成"); try { //添加歌曲mp3url songService.addMp3Url(this.songId, map3Url); } catch (SerException e) { e.printStackTrace(); } } } } <file_sep>package model.enums.knowledge; /** * @Author: [caiwenxian] * @Date: [2018-03-14 14:10] * @Description: [ ] * @Version: [1.0.0] */ public enum ArticleType { /** * 技术类别 */ TECHNOLOGY(1, "技术"), /** * 生活类别 */ LIFE(2, "生活"); private Integer code; private String name; public static String getName(Integer code) { for (ArticleType type : ArticleType.values()) { if (type.getCode().equals(code)) { return type.getName(); } } return null; } ArticleType(Integer code) { this.code = code; } ArticleType(Integer code, String name) { this.code = code; this.name = name; } public static ArticleType articleType(Integer code) { for (ArticleType top : ArticleType.values()) { if (top.getCode().equals(code)) { return top; } } return null; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>package com.wenxianm.model.vo.music; import com.wenxianm.model.po.music.SongInfoPO; import java.util.List; /** * 排行榜 * * @Author: [caiwenxian] * @Date: [2018-02-07 14:46] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class TopListVO { /** * 名称 */ private String name; /** * id */ private String toplistId; /** * 歌曲对象 */ private List<SongInfoPO> songInfoPO; public TopListVO() { } public TopListVO(String name, String toplistId, List<SongInfoPO> songInfoPO) { this.name = name; this.toplistId = toplistId; this.songInfoPO = songInfoPO; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getToplistId() { return toplistId; } public void setToplistId(String toplistId) { this.toplistId = toplistId; } public List<SongInfoPO> getSongInfoPO() { return songInfoPO; } public void setSongInfoPO(List<SongInfoPO> songInfoPO) { this.songInfoPO = songInfoPO; } } <file_sep>package service.task.impl; import exception.SerException; import model.dto.music.TopListDTO; import model.enums.music.TopListType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.common.impl.BaseServiceImpl; import service.music.reptile.IReptileSongService; import service.task.IReptileMusicTaskService; /** * 定时任务-爬取音乐 * * @Author: [caiwenxian] * @Date: [2018-02-11 10:48] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Service public class ReptileMusicTaskServiceImpl extends BaseServiceImpl implements IReptileMusicTaskService { @Autowired IReptileSongService reptileSongService; public void reptileAllTopList() { try { for (TopListType t : TopListType.values()) { TopListDTO dto = new TopListDTO(t); reptileSongService.reptileTopSongs(dto); } } catch (SerException e) { logger.info("更新排行榜出错:" + e.getMessage()); } } } <file_sep>package com.wenxianm.service.knowledge; import com.wenxianm.exception.SerException; import com.wenxianm.model.dto.knowledge.ArticleDTO; import com.wenxianm.model.po.common.PagePO; import com.wenxianm.model.po.knowledge.ArticlePO; import com.wenxianm.model.po.music.ArtistPO; import com.wenxianm.model.to.ArticleTO; import com.wenxianm.model.vo.knowledge.ArticleVO; /** * @Author: [caiwenxian] * @Date: [2018-03-13 15:41] * @Description: [ ] * @Version: [1.0.0] */ public interface IKnowledgeService { /** * 获取文章列表 * * @param * @return class * @version v1 */ PagePO<ArticlePO> ListArticle(ArticleDTO dto) throws Exception; /** * 获取单个文章 * * @param * @return class * @version v1 */ ArticleVO getArticle(String id) throws SerException, Exception; /** * 添加文章 * * @param * @return class * @version v1 */ void addArticle(ArticleTO to) throws SerException, Exception; /** * 更新文章观阅数 * * @param * @return class * @version v1 */ void updateArticleBrowseAmount(String article) throws SerException; /** * 更新文章评论数 * * @param * @return class * @version v1 */ void updateArticleCommentAmount(String article) throws SerException; } <file_sep>package service.knowledge; import exception.SerException; import model.dto.knowledge.ArticleCommentDTO; import model.po.common.PagePO; import model.po.knowledge.ArticleCommentPO; import model.vo.knowledge.ArticleCommentVO; import java.lang.reflect.InvocationTargetException; /** * @Author: [caiwenxian] * @Date: [2018-03-22 16:23] * @Description: [ ] * @Version: [1.0.0] */ public interface IArticleCommentService { /** * 添加评论 * * @param * @return class * @version v1 */ void addComment(ArticleCommentPO po) throws SerException; /** * 获取评论列表 * * @param * @return class * @version v1 */ PagePO<ArticleCommentVO> listArticleComment(ArticleCommentDTO dto) throws SerException, InvocationTargetException, IllegalAccessException; } <file_sep>package com.wenxianm.controller.music; import com.wenxianm.controller.common.BaseController; import com.wenxianm.exception.ErrorCode; import com.wenxianm.exception.SerException; import com.wenxianm.model.po.music.ArtistPO; import com.wenxianm.model.po.music.SongInfoPO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.wenxianm.service.common.Result; import com.wenxianm.service.common.impl.ActResult; import com.wenxianm.service.music.IArtistHotSongService; import com.wenxianm.service.music.IArtistService; import java.util.List; /** * 歌手业务 * * @Author: [caiwenxian] * @Date: [2018-01-29 17:17] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Controller @RequestMapping("/artist") public class ArtistController extends BaseController { @Autowired IArtistService artistService; @Autowired IArtistHotSongService artistHotSongService; /** * 歌手模糊搜索 * * @param * @return class * @version v1 */ @GetMapping("/search/{name}") @ResponseBody public Result search(@PathVariable String name) { try { List<ArtistPO> list = artistService.listArtistByName(name); return ActResult.data(list); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } /** * 歌手热门歌曲 * * @param * @return class * @version v1 */ @GetMapping("/hot-song/{artistId}") @ResponseBody public Result listHotSong(@PathVariable String artistId) { try { List<SongInfoPO> list = artistHotSongService.listHotSongByArtistId(artistId); return ActResult.data(list); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } } <file_sep>package com.mq; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.TextMessage; @Service public class QueueListenerV2 { @Resource private JmsTemplate jmsTemplate; public TextMessage receive(Destination destination) { TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination); try { System.out.println("从队列" + destination.toString() + "收到的消息:" + textMessage); } catch (Exception e) { } return textMessage; } } <file_sep>package dao.java.music; import exception.QueryException; import model.po.music.ArtistPO; import model.po.music.HotArtistPO; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * 歌手业务操作 * * @Author: [caiwenxian] * @Date: [2018-01-19 09:20] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Repository public interface IArtistDao { /** * 保存歌手 * * @param * @return class * @version v1 */ void addArtist(ArtistPO po) throws QueryException; /** * 根据歌手id获取歌手信息 * * @param * @return class * @version v1 */ ArtistPO getArtistByArtistId(String id) throws QueryException; /** * 添加热门歌手 * * @param * @return class * @version v1 */ void addHotArtist(List<HotArtistPO> list) throws QueryException; /** * 根据姓名获取歌手列表 * * @param name * @return class * @version v1 */ List<ArtistPO> listArtistByName(@Param("name") String name) throws QueryException; } <file_sep>package com.wenxianm.service.common; import org.apache.log4j.Logger; public interface IBaseService { } <file_sep>package service.music; import exception.SerException; import model.dto.common.BaseDTO; import model.dto.music.MusicDTO; import model.po.common.PagePO; import model.po.common.PaginationPO; import model.po.music.RecommendSongListPO; import model.po.music.SongInfoPO; import model.po.music.SongListDetailsPO; import model.po.music.SongListPO; import model.vo.music.TopListVO; import java.util.List; /** * 歌曲基础业务 * * @Author: [caiwenxian] * @Date: [2018-01-19 09:43] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public interface ISongService { /** * 添加歌曲信息 * * @param * @return class * @version v1 */ void addSong(SongInfoPO po) throws SerException; /** * 根据songId获取歌曲信息 * * @param * @return class * @version v1 */ SongInfoPO getBySongId(String songId) throws SerException; /** * 更新 * * @param * @return class * @version v1 */ void update(SongInfoPO po) throws SerException; /** * 添加mp3url * * @param * @return class * @version v1 */ void addMp3Url(String songId, String mp3Url) throws SerException; /** * 根据歌名搜索歌曲列表 * * @param * @return class * @version v1 */ List<SongInfoPO> listSongByName(String name) throws SerException; /** * 根据歌名搜索歌曲列表 * * @param * @return class * @version v1 */ PagePO<SongInfoPO> listSongByNameByPage(String name, int page, int limit) throws SerException; /** * 获取所有排行榜歌曲 * * @param * @return class * @version v1 */ List<SongInfoPO> listAllTopList() throws SerException; /** * 根据排行榜id获取排行榜歌曲 * * @param * @return class * @version v1 */ TopListVO listTopListByTopListId(String topListId) throws SerException; /** * 获取热门歌曲 * * @param * @return class * @version v1 */ PagePO listHotSong(BaseDTO dto) throws SerException; /** * 添加歌单 * * @param * @return class * @version v1 */ void addSongList(SongListPO po) throws SerException; /** * 更新歌单信息 * * @param * @return class * @version v1 */ void updateSongList(String songListId, String trackUpdateTime) throws SerException; /** * 添加推荐歌单 * * @param * @return class * @version v1 */ void addRecommendSongList(RecommendSongListPO po) throws SerException; /** * 添加歌单详情 * * @param * @return class * @version v1 */ void addSongListDetails(SongListDetailsPO po) throws SerException; } <file_sep>package service.mq.rabbitmq; import com.alibaba.fastjson.JSONObject; import com.rabbitmq.client.Channel; import dao.java.mq.IRabbitMessageDao; import model.constant.MessageType; import model.po.mq.MessagePO; import model.vo.ins.PictureVo; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener; import org.springframework.beans.factory.annotation.Autowired; import service.common.impl.BaseServiceImpl; import service.ins.InsService; import service.music.reptile.IReptileSongService; import utils.SerializeUtil; import java.time.LocalDateTime; /** * 消费者 * @author caiwx * @date 2019年02月25日 11:11 * */ public class QueueListener extends BaseServiceImpl implements ChannelAwareMessageListener { @Autowired IReptileSongService reptileSongService; @Autowired IRabbitMessageDao rabbitMessageDao; @Autowired InsService insService; @Override public void onMessage(Message message, Channel channel) throws Exception { Thread.sleep(3000); byte[] body = message.getBody(); long deliveryTag = message.getMessageProperties().getDeliveryTag(); Boolean redelivered = message.getMessageProperties().getRedelivered(); // logger.info("receive message:" + new String(body)); /* long deliveryTag = message.getMessageProperties().getDeliveryTag(); Boolean redelivered = message.getMessageProperties().getRedelivered(); logger.info("deliveryTag:" + deliveryTag + ", redelivered:" + redelivered);*/ /* try { logger.info("message.getMessageProperties().getDeliveryTag():" + message.getMessageProperties().getDeliveryTag()); logger.info("thread:" + Thread.currentThread().getName()); // if (message.getMessageProperties().getDeliveryTag()%10 == 0) { if ("messageContainer-2".equals(Thread.currentThread().getName())) { throw new Exception(); } channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (Exception e) { // logger.info("进入catch"); // channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); }*/ // 代表投递的标识符,唯一标识了当前信道上的投递,通过 deliveryTag ,消费者就可以告诉 RabbitMQ 确认收到了当前消息,见下面的方法 // long deliveryTag = message.getMessageProperties().getDeliveryTag(); // 如果是重复投递的消息,redelivered 为 true // Boolean redelivered = message.getMessageProperties().getRedelivered(); // logger.info("deliveryTag:" + deliveryTag + ", redelivered:" + redelivered); // 代表消费者确认收到当前消息,第二个参数表示一次是否 ack 多条消息 // channel.basicAck(deliveryTag, false); // 代表消费者拒绝一条或者多条消息,第二个参数表示一次是否拒绝多条消息,第三个参数表示是否把当前消息重新入队 // channel.basicNack(deliveryTag, false, false); // 代表消费者拒绝当前消息,第二个参数表示是否把当前消息重新入队 // channel.basicReject(deliveryTag,false); MessagePO messagePO = new MessagePO(); try { Object object = SerializeUtil.deSerialize(body); messagePO = (MessagePO) object; messagePO.setConsumeTime(LocalDateTime.now()); logger.info("消息id:" + messagePO.getId()); //保存歌单歌曲 if ("1".equals(messagePO.getType())) { reptileSongService.saveSongWithSongList(JSONObject.parseObject(messagePO.getData())); } //文本 if ("MSG".equals(messagePO.getType())) { logger.info("文本消息"); } //爬取歌曲的URL if ("2".equals(messagePO.getType())) { logger.info("消费者:爬取歌曲的URL"); reptileSongService.reptileMp3UrlV2(messagePO.getData()); } //下载图片 if (MessageType.DOWNLOAD_PICTURE.equals(messagePO.getType())) { logger.info("消费者:下载图片"); insService.downPicture(JSONObject.parseObject(messagePO.getData(), PictureVo.class)); } channel.basicAck(deliveryTag, false); //更新消息状态 messagePO.setStatus(1); rabbitMessageDao.updateMessageStatus(messagePO); } catch(Exception e) { logger.error("消费消息失败", e); //拒绝消息,并将消息重新加入队列 if (!redelivered) { channel.basicReject(deliveryTag,true); } else { // 如果是重复投递的消息,拒绝消息并且不重新放入队列 channel.basicReject(deliveryTag,false); //更新消息状态 // messagePO = messagePO == null ? new MessagePO() : messagePO; messagePO.setStatus(-1); messagePO.setConsumeTime(LocalDateTime.now()); messagePO.setReturnMsg("消费消息失败:" + e.getMessage()); rabbitMessageDao.updateMessageStatus(messagePO); } } } } <file_sep>package com.wenxianm.model.po.music; import com.wenxianm.model.po.common.BasePO; /** * 推荐的歌单 * * @Author: [caiwenxian] * @Date: [2018-02-08 11:01] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class RecommendSongListPO extends BasePO { /** * 歌单id */ private String songListId; /** * 序号 */ private int num; /** * 更新时间 */ private String trackUpdateTime; public RecommendSongListPO() { } public RecommendSongListPO(String songListId, int num, String trackUpdateTime) { this.songListId = songListId; this.num = num; this.trackUpdateTime = trackUpdateTime; } @Override public String toString() { return "recommendSongListPO{" + "songListId='" + songListId + '\'' + ", num=" + num + ", trackUpdateTime='" + trackUpdateTime + '\'' + '}'; } public String getSongListId() { return songListId; } public void setSongListId(String songListId) { this.songListId = songListId; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getTrackUpdateTime() { return trackUpdateTime; } public void setTrackUpdateTime(String trackUpdateTime) { this.trackUpdateTime = trackUpdateTime; } } <file_sep>package model.po.common; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-02-07 10:25] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class PaginationPO implements Page { int startRow = 0; int endRow = 0; int totalSize = 0; public PaginationPO() { } public PaginationPO(Page page) { System.out.println("page:" + page.init()); } public PaginationPO(int limit, int pageIndex) { } @Override public int init() { return 0; } @Override public List initData(int pageIndex, int pageSize) { System.out.println(pageIndex + " " + pageSize); return null; } public int getStartRow() { return startRow; } public void setStartRow(int startRow) { this.startRow = startRow; } public int getEndRow() { return endRow; } public void setEndRow(int endRow) { this.endRow = endRow; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } } <file_sep>package com.wenxianm; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 启动器 * @author caiwx * @date 2021/4/29 - 16:45 **/ @SpringBootApplication public class BlogApplication { public static void main(String[] args) { SpringApplication.run(BlogApplication.class, args); } } <file_sep>package service.common.impl; import org.apache.log4j.Logger; import service.common.IBaseService; public class BaseServiceImpl implements IBaseService { protected Logger logger = Logger.getLogger(getClass()); } <file_sep>package model.po.base; /** * 基础类 * * @author caiwenxian * @date 18-3-5 下午3:41 */ public class Po { } <file_sep>package com.sort; import org.junit.Test; /** * 冒泡排序 * @author caiwx * @date 2019年03月19日 15:56 * */ public class BubbleSort { public int[] BubbleSort(int[] target) { int len = target.length; for (int i = 0; i < len; i ++) { boolean stop = false; for (int j = i; j < len; j ++) { if (target[i] > target[j]) { int temp = target[i]; target[i] = target[j]; target[j] = temp; stop = true; } } if (!stop) { break; } } return target; } @Test public void test1() { int[] str = {1, 3, 4, 2, 6, 2, 9, 6, 4, 10, 9}; str = BubbleSort(str); for (int i : str) { System.out.print(i); } } } <file_sep>package com.wenxianm.model.po.user; import com.wenxianm.model.po.common.BasePO; import javax.validation.constraints.NotNull; /** * @Author: [caiwenxian] * @Date: [2018-02-26 17:17] * @Description: [ ] * @Version: [1.0.0] */ public class LoginPO extends BasePO { @NotNull(message = "帐号不能为空") private String name; private String password; private boolean rememberMe; private String verifyCode; private String refUrl; public LoginPO() { } public LoginPO(String name, String password) { this.name = name; this.password = <PASSWORD>; } public LoginPO(String name, String password, boolean rememberMe) { this.name = name; this.password = <PASSWORD>; this.rememberMe = rememberMe; } public String getName() { return name; } public String getPassword() { return password; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = <PASSWORD>; } public boolean isRememberMe() { return rememberMe; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } public String getVerifyCode() { return verifyCode; } public void setVerifyCode(String verifyCode) { this.verifyCode = verifyCode; } public String getRefUrl() { return refUrl; } public void setRefUrl(String refUrl) { this.refUrl = refUrl; } } <file_sep>package com.wenxianm.model.po.music; import com.wenxianm.model.po.common.BasePO; /** * 歌手热门歌曲 * * @Author: [caiwenxian] * @Date: [2018-01-29 16:52] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class ArtistHotSongPO extends BasePO { /** * 歌曲id */ private String songId; /** * 歌手id */ private String artistId; /** * 序号 */ private Integer num; public ArtistHotSongPO() { } public ArtistHotSongPO(String songId, String artistId, Integer num) { this.songId = songId; this.artistId = artistId; this.num = num; } @Override public String toString() { return "ArtistHotSongPO{" + "songId='" + songId + '\'' + ", artistId='" + artistId + '\'' + ", num='" + num + '\'' + '}'; } public String getSongId() { return songId; } public void setSongId(String songId) { this.songId = songId; } public String getArtistId() { return artistId; } public void setArtistId(String artistId) { this.artistId = artistId; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } } <file_sep>package com.wenxianm.model.to.ins; import com.wenxianm.model.po.common.BasePO; import java.util.List; /** * @description:图片 * @author: caiwx * @createDate : 2020年08月05日 17:09:00 */ public class PictureTo extends BasePO { /** * 展示图片url */ private String displayUrl; private List<String> displayResourceUrl; /** * 用户名 */ private String userName; public String getDisplayUrl() { return displayUrl; } public void setDisplayUrl(String displayUrl) { this.displayUrl = displayUrl; } public List<String> getDisplayResourceUrl() { return displayResourceUrl; } public void setDisplayResourceUrl(List<String> displayResourceUrl) { this.displayResourceUrl = displayResourceUrl; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }<file_sep>package com.wenxianm.service.user; import com.wenxianm.exception.SerException; import com.wenxianm.model.po.user.LoginPO; /** * @Author: [caiwenxian] * @Date: [2018-02-26 17:16] * @Description: [ ] * @Version: [1.0.0] */ public interface ILoginService { void login(LoginPO po) throws SerException; } <file_sep>package model.po.knowledge; import model.po.base.annotation.TableName; import model.po.common.BasePO; /** * 文章评论 * * @Author: [caiwenxian] * @Date: [2018-03-22 16:14] * @Description: [ ] * @Version: [1.0.0] */ @TableName(name = "t_article_comment") public class ArticleCommentPO extends BasePO { /** * 用户id */ private String userId; /** * 文章id */ private String articleId; /** * 被回复的评论id */ private String parentId; /** * 评论内容 */ private String comment; /** * 赞 */ private int approve; public ArticleCommentPO() { } public ArticleCommentPO(String userId, String articleId, String parentId, String comment) { this.userId = userId; this.articleId = articleId; this.parentId = parentId; this.comment = comment; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getArticleId() { return articleId; } public void setArticleId(String articleId) { this.articleId = articleId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public int getApprove() { return approve; } public void setApprove(int approve) { this.approve = approve; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>blog</artifactId> <groupId>com.wenxianm</groupId> <version>1.0.0</version> </parent> <artifactId>blog-main</artifactId> <version>${blog.main.version}</version> <name>blog-main</name> <packaging>jar</packaging> <properties> <!-- <java.version>8</java.version>--> <!-- <spring-cloud.version>Hoxton.SR7</spring-cloud.version>--> </properties> <dependencies> <!--<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>--> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <!--可以把依赖的包都打包到生成的Jar包中--> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <!-- 针对资源文件,要指定编码字符集,可以解决部分中文乱码造成编译不能通过 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skipTests>true</skipTests> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>package com.wenxianm.model.dto.common; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-01-18 17:44] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class BaseDTO implements Serializable { private static final long serialVersionUID = -3558525794931360478L; /** * 每显示数量 */ protected Integer limit = 10; /** * 当前页 */ protected Integer page = 1; private int startRow; private int endRow; public BaseDTO() { this.startRow = (this.page - 1) * this.limit; this.endRow = this.page * this.limit; } public BaseDTO(Integer limit, Integer page) { this.limit = limit; this.page = page; } public static long getSerialVersionUID() { return serialVersionUID; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; this.startRow = (this.page - 1) * this.limit; this.endRow = this.page * this.limit; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; this.startRow = (this.page - 1) * this.limit; this.endRow = this.page * this.limit; } public int getStartRow() { return startRow; } public void setStartRow(int startRow) { this.startRow = startRow; } public int getEndRow() { return endRow; } public void setEndRow(int endRow) { this.endRow = endRow; } } <file_sep>package com.wenxianm.model.enums.user; /** * @Author: [caiwenxian] * @Date: [2018-02-27 16:31] * @Description: [ ] * @Version: [1.0.0] */ public enum CacheType { USER_INFO("用户缓存"); private String name; CacheType(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>package service.common; /** * @Author: [caiwenxian] * @Date: [2018-01-26 11:45] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public interface Result { public static final String MSG_NOT_LOGIN_OPERATE = "用户未登录,不可操作"; public static final String MSG_NOT_LOGIN = "用户未登录"; public static final String MSG_PARAMS_MISS = "参数缺失"; public static final int CODE_NOT_LOGIN = 401; public static final int CODE_SERVE_ERROR = 500; /** * 消息码 */ int getCode(); /** * 错误消息 */ String getMsg(); /** * 返回数据 */ Object getData(); } <file_sep>package dao.java.music; import exception.QueryException; import model.po.music.ArtistHotSongPO; import model.po.music.SongInfoPO; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import javax.xml.ws.soap.Addressing; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-01-29 16:55] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Repository public interface IArtistHotSongDao { /** * 添加歌手热门歌曲 * * @param * @return class * @version v1 */ void addArtistHotSong(ArtistHotSongPO po) throws QueryException; /** * 获取单个实体 * * @param * @return class * @version v1 */ ArtistHotSongPO getBySongIdAndArtistId(@Param("songId") String songId, @Param("artistId") String artistId) throws QueryException; /** * 根据歌手id获取热门歌曲 * * @param * @return class * @version v1 */ List<SongInfoPO> listHotSongByArtistId(@Param("artistId") String artistId) throws QueryException; } <file_sep>package controller.music; import controller.common.BaseController; import dao.java.music.IArtistHotSongDao; import exception.ErrorCode; import exception.SerException; import model.dto.music.ArtistHotSongDTO; import model.po.music.ArtistPO; import model.po.music.SongInfoPO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import service.common.Result; import service.common.impl.ActResult; import service.music.IArtistHotSongService; import service.music.IArtistService; import service.music.reptile.IReptileSongService; import java.util.List; /** * 歌手业务 * * @Author: [caiwenxian] * @Date: [2018-01-29 17:17] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Controller @RequestMapping("/artist") public class ArtistController extends BaseController { @Autowired IArtistService artistService; @Autowired IArtistHotSongService artistHotSongService; /** * 歌手模糊搜索 * * @param * @return class * @version v1 */ @GetMapping("/search/{name}") @ResponseBody public Result search(@PathVariable String name) { try { List<ArtistPO> list = artistService.listArtistByName(name); return ActResult.data(list); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } /** * 歌手热门歌曲 * * @param * @return class * @version v1 */ @GetMapping("/hot-song/{artistId}") @ResponseBody public Result listHotSong(@PathVariable String artistId) { try { List<SongInfoPO> list = artistHotSongService.listHotSongByArtistId(artistId); return ActResult.data(list); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } } <file_sep>package com.wenxianm.controller.life; import com.wenxianm.controller.common.BaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * @Author: [caiwenxian] * @Date: [2018-03-19 10:47] * @Description: [ ] * @Version: [1.0.0] */ @Controller @RequestMapping("/life") public class LifeController extends BaseController { @GetMapping @ResponseBody public ModelAndView lifePage() { return new ModelAndView("life/life"); } } <file_sep>package service.knowledge.impl; import dao.java.knowledge.IArticleCommentDao; import dao.java.knowledge.impl.ArticleCommentDaoImpl; import exception.SerException; import model.dto.knowledge.ArticleCommentDTO; import model.po.common.PagePO; import model.po.knowledge.ArticleCommentPO; import model.po.knowledge.ArticlePO; import model.vo.knowledge.ArticleCommentVO; import org.apache.commons.beanutils.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.common.impl.BaseServiceImpl; import service.knowledge.IArticleCommentService; import service.knowledge.IKnowledgeService; import service.music.IArtistService; import service.user.IClientService; import utils.RandomUtil; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; /** * 文章评论业务实现 * * @Author: [caiwenxian] * @Date: [2018-03-22 16:23] * @Description: [ ] * @Version: [1.0.0] */ @Service public class ArticleCommentServiceImpl extends BaseServiceImpl implements IArticleCommentService { @Autowired ArticleCommentDaoImpl articleCommentDao; @Autowired IKnowledgeService knowledgeService; @Autowired IClientService clientService; @Override public void addComment(ArticleCommentPO po) throws SerException { try { po.setUserId(clientService.getCurrentUser().getUserId()); po.setId(RandomUtil.getUid()); articleCommentDao.add(po, true); Callable callable = new CommentCallable(po.getArticleId()); FutureTask futureTask = new FutureTask(callable); Thread thread = new Thread(futureTask); thread.start(); } catch (SerException e) { e.printStackTrace(); // throw new SerException(e.getCode(), e.getMessage()); } } @Override public PagePO<ArticleCommentVO> listArticleComment(ArticleCommentDTO dto) throws SerException, InvocationTargetException, IllegalAccessException { int count = articleCommentDao.countArticleComment(dto); if (count < 1) { return new PagePO(0, null); } List<ArticleCommentVO> pos = articleCommentDao.listArticleComment(dto); List<ArticleCommentVO> vos = convertComment(pos); return new PagePO<ArticleCommentVO>(count, vos); } private List<ArticleCommentVO> convertComment(List<ArticleCommentVO> pos) throws InvocationTargetException, IllegalAccessException { List<ArticleCommentVO> vos = new ArrayList<ArticleCommentVO>(); int len = pos.size(); for (int i = 0; i < len; i++) { if (pos.get(i).getParentId() != null) { continue; } List<ArticleCommentVO> childs = new ArrayList<ArticleCommentVO>(); for (int j = 0; j < len; j++) { if (pos.get(i).getId().equals(pos.get(j).getParentId())) { childs.add(pos.get(j)); pos.remove(pos.get(j)); len--; j--; } } pos.get(i).setChilds(childs.size() > 0 ? childs : null); vos.add(pos.get(i)); } return vos; } public class CommentCallable implements Callable { private String articleId; public CommentCallable(String articleId) { this.articleId = articleId; } @Override public Object call() throws Exception { knowledgeService.updateArticleCommentAmount(articleId); return null; } } } <file_sep>package com.wenxianm.model.constant; /** * 通用常量 * * @Author: [caiwenxian] * @Date: [2018-02-07 11:44] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class Common { /** * 线程睡眠时间 */ public final static int threadSleepTime = 3000; /** * 分页limit */ public final static int PAGE_LIMIT = 20; } <file_sep>1. Dao可实现基础业务操作 普通dao可以继承Dao实现基础的“增删查改” <file_sep>package dao.java.knowledge; import model.dto.knowledge.ArticleCommentDTO; import model.po.knowledge.ArticleCommentPO; import model.vo.knowledge.ArticleCommentVO; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-03-22 16:20] * @Description: [ ] * @Version: [1.0.0] */ public interface IArticleCommentDao { /** * 获取文章评论总条数 * * @param * @return class * @version v1 */ int countArticleComment(ArticleCommentDTO dto); /** * 获取文章评论列表 * * @param * @return class * @version v1 */ List<ArticleCommentVO> listArticleComment(ArticleCommentDTO dto); } <file_sep>package com.wenxianm.model.po.mq; import com.wenxianm.model.po.base.annotation.TableName; import com.wenxianm.model.po.common.BasePO; import java.io.Serializable; import java.time.LocalDateTime; /** * Description: rabbit消息实体 * @author: caiwx * @date: 2019/10/29 14:55 * @param: * @return: */ @TableName(name = "t_rabbit_message") public class MessagePO extends BasePO implements Serializable { private static final long serialVersionUID = -9018118238271043366L; /** 消息类型 * 0: 测试消息 * 1:爬取并存储歌曲详情() * */ private String type; /** 消息状态:0:初始状态、1:消费成功、-1、消费失败*/ private int status; /** 消息主体,json串*/ private String data; /** rabbit产生的消息id */ private String correlationDataId; /** 发送时间 */ private LocalDateTime sendTime; /** 消费时间 */ private LocalDateTime consumeTime; /** 消费后返回消息 */ private String returnMsg; public MessagePO() {} public MessagePO(String type, int status, String data) { this.type = type; this.status = status; this.data = data; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getData() { return data; } public void setData(String data) { this.data = data; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getCorrelationDataId() { return correlationDataId; } public void setCorrelationDataId(String correlationDataId) { this.correlationDataId = correlationDataId; } public LocalDateTime getSendTime() { return sendTime; } public void setSendTime(LocalDateTime sendTime) { this.sendTime = sendTime; } public LocalDateTime getConsumeTime() { return consumeTime; } public void setConsumeTime(LocalDateTime consumeTime) { this.consumeTime = consumeTime; } public String getReturnMsg() { return returnMsg; } public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } } <file_sep>package service.mq.rabbitmq; import exception.SerException; import model.dto.mq.MessageDTO; import model.po.common.PagePO; import model.po.mq.MessagePO; import model.vo.mq.MessageVO; /** * Description: rabbit消息业务 * @author: caiwx * @date: 2019/11/4 9:55 * @param: * @return: */ public interface IRabbitMessageService { /** * Description: 获取rabbit消息列表 * @author: caiwx * @date: 2019/11/4 9:59 * @param: * @return: */ PagePO<MessageVO> listRabbitService(MessageDTO messageDTO) throws SerException; /** * 重新发送消息 * @author caiwx * @date 2019/12/19 17:56 * @return */ void reSendRabbitMessage(MessageDTO messageDTO) throws SerException; } <file_sep>package model.po.music; import model.po.common.BasePO; /** * 热门歌手 * * @Author: [caiwenxian] * @Date: [2018-01-31 16:47] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class HotArtistPO extends BasePO { /** * 歌手id */ private String artistId; /** * 序号 */ private Integer num; public HotArtistPO() { } public HotArtistPO(String artistId, Integer num) { this.artistId = artistId; this.num = num; } @Override public String toString() { return "HotArtistPO{" + "artistId='" + artistId + '\'' + ", num=" + num + '}'; } public String getArtistId() { return artistId; } public void setArtistId(String artistId) { this.artistId = artistId; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } } <file_sep>package com.wenxianm.model.po.music; import com.wenxianm.model.po.common.BasePO; import java.time.LocalDateTime; /** * 排行榜 * * @Author: [caiwenxian] * @Date: [2018-01-27 10:12] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public class TopListPO extends BasePO { /** * 排行榜名称 */ private String name; /** * 排行榜id */ private String topListId; /** * 来源 */ private String origin; /** * 官方排行榜更新时间(时间戳) */ private String trackUpdateTime; public TopListPO() { } public TopListPO(String name, String topListId, String origin, String trackUpdateTime) { this.name = name; this.topListId = topListId; this.origin = origin; this.trackUpdateTime = trackUpdateTime; } @Override public String toString() { return "TopListPO{" + "name='" + name + '\'' + ", topListId='" + topListId + '\'' + ", origin='" + origin + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTopListId() { return topListId; } public void setTopListId(String topListId) { this.topListId = topListId; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getTrackUpdateTime() { return trackUpdateTime; } public void setTrackUpdateTime(String trackUpdateTime) { this.trackUpdateTime = trackUpdateTime; } } <file_sep>package com.wenxianm.model.enums.knowledge; import javax.print.DocFlavor; /** * 文章状态 * * @Author: [caiwenxian] * @Date: [2018-03-14 14:06] * @Description: [ ] * @Version: [1.0.0] */ public enum ArticleStatus { /** * 发布状态 */ PUBLISH(1), /** * 草稿状态 */ DRAFT(2), /** * 删除状态 */ DELETED(3); private Integer code; ArticleStatus(Integer code) { this.code = code; } public static ArticleStatus articleStatus(Integer code) { for (ArticleStatus top : ArticleStatus.values()) { if (top.getCode().equals(code)) { return top; } } return null; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } <file_sep>package dao.java.knowledge.impl; import dao.java.impl.DaoImpl; import dao.java.knowledge.IKnowledgeDao; import model.dto.knowledge.ArticleDTO; import model.po.knowledge.ArticlePO; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-03-13 15:38] * @Description: [ ] * @Version: [1.0.0] */ @Repository public class KnowledgeDaoImpl extends DaoImpl<ArticlePO, String> implements IKnowledgeDao { @Resource(name = "sqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplateASS; public int countArticle(ArticleDTO dto) { return sqlSessionTemplateASS.selectOne("countArticle", dto); } public List<ArticlePO> listArticle(ArticleDTO dto) { List list = sqlSessionTemplateASS.selectList("listArticleByPage", dto); return list; } @Override public void addArticle(ArticlePO po) { sqlSessionTemplateASS.insert("addArticle", po); } @Override public ArticlePO getArticle(String id) { return sqlSessionTemplateASS.selectOne("getArticle", id); } } <file_sep>package com.mq; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import service.mq.rabbitmq.other.MyProducer; @RunWith(value = SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:spring-rabbitmq.xml", "classpath:spring-mvc.xml"}) public class TestARabbit { @Autowired MyProducer myProducer; private static final String QUEUE_KEY = "test_queue"; @Test public void send() { String message = "hello rabbitMQ!"; // Map<String,Object> msg = new HashMap<String,Object>(); // msg.put("data","hello,rabbmitmq!"); myProducer.sendDataToQueue(QUEUE_KEY,message); } }<file_sep>package service.music.impl; import dao.java.music.IArtistHotSongDao; import exception.SerException; import model.dto.music.ArtistHotSongDTO; import model.po.music.ArtistHotSongPO; import model.po.music.SongInfoPO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.common.impl.BaseServiceImpl; import service.music.IArtistHotSongService; import service.music.reptile.IReptileArtistService; import service.music.reptile.IReptileSongService; import utils.RandomUtil; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-01-29 15:55] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Service public class ArtistHotSongServiceImpl extends BaseServiceImpl implements IArtistHotSongService { // @Autowired // ISongService songService; // @Autowired // IArtistService artistService; @Autowired IArtistHotSongDao artistHotSongDao; @Autowired IReptileArtistService reptileArtistService; @Autowired IReptileSongService reptileSongService; @Override public void addArtistHotSong(ArtistHotSongPO po) { ArtistHotSongPO old = artistHotSongDao.getBySongIdAndArtistId(po.getSongId(), po.getArtistId()); if (old != null) { return; } po.setId(RandomUtil.getUid()); artistHotSongDao.addArtistHotSong(po); } @Override public List<SongInfoPO> listHotSongByArtistId(String artistId) throws SerException { List<SongInfoPO> list = artistHotSongDao.listHotSongByArtistId(artistId); if (list.size() == 0) { //本地无数据,爬取官网 String ids[] = new String[]{artistId}; reptileSongService.asynReptile(2, new Object[]{new ArtistHotSongDTO(ids)}); try { Thread.currentThread().sleep(3000); list = artistHotSongDao.listHotSongByArtistId(artistId); } catch (InterruptedException e) { e.printStackTrace(); } } return list; } } <file_sep>package controller.security.realm; import controller.security.token.UserToken; import exception.SerException; import model.po.user.UserPO; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import service.user.IUserService; /** * author: wenxian.cai * date: 2017/9/25 11:12 */ public class UserRealm extends AuthorizingRealm { public void setCacheManager(CacheManager cacheManager) { super.setCacheManager(cacheManager); } // @Autowired // CustomerUserService userService; @Autowired IUserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // LoginUser user = ClientManager.getClient().getUser(); /* TAdminRole role = adminService.getAdminRole(user.getRoleId()); if (role != null) { Set<String> roles = new HashSet<>(); roles.add(role.getName()); info.setRoles(roles); Set<String> pers = adminService.getCurrentAdminPermissionSet(role.getId()); Iterator<String> it = pers.iterator(); while (it.hasNext()) { String str = it.next(); logger.info("str:" + str); } // pers.removeAll(pers); info.setStringPermissions(pers); //TAdminPermission permission = adminService.getAdminPermission(role.getPermissionId()); *//*Set<String> permissionSet = new HashSet<>(); String[] pe = permission.getMenu().split(","); for (String p : pe) { permissionSet.add(p); }*//* //info.setStringPermissions(permissionSet); //info.setObjectPermissions(); }*/ return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UserToken userToken = (UserToken) authenticationToken; String userName = userToken.getUsername(); UserPO user = null; try { user = userService.getUserByName(userName); } catch (SerException e) { e.printStackTrace(); } if (user == null) { throw new UnknownAccountException("该账号不存在"); } return new SimpleAuthenticationInfo(userName, user.getPassword(), getName()); // return new SimpleAuthenticationInfo("mueju", "000000", getName()); } /** * 为权限标签扩展or、and、not功能 * * @param principals * @param permission * @return */ @Override public boolean isPermitted(PrincipalCollection principals, String permission) { if (permission.contains("or") && permission.contains(" ")) { String[] permissions = permission.split("or"); for (String orPermission : permissions) { if (isPermittedWithNotOperator(principals, orPermission)) { return true; } } return false; } else if (permission.contains("and") && permission.contains(" ")) { String[] permissions = permission.split("and"); for (String orPermission : permissions) { if (!isPermittedWithNotOperator(principals, orPermission)) { return false; } } return true; } else { return isPermittedWithNotOperator(principals, permission); } } private boolean isPermittedWithNotOperator(PrincipalCollection principals, String permission) { if (permission.startsWith("not")) { return !super.isPermitted(principals, permission.substring(3)); } else { return super.isPermitted(principals, permission); } } @Override public void clearCachedAuthorizationInfo(PrincipalCollection principals) { super.clearCachedAuthorizationInfo(principals); } @Override public void clearCachedAuthenticationInfo(PrincipalCollection principals) { super.clearCachedAuthenticationInfo(principals); } @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); } public void clearAllCachedAuthorizationInfo() { getAuthorizationCache().clear(); } public void clearAllCachedAuthenticationInfo() { getAuthenticationCache().clear(); } public void clearAllCache() { clearAllCachedAuthenticationInfo(); clearAllCachedAuthorizationInfo(); } } <file_sep>package com.wenxianm.controller.security.token; import org.apache.shiro.authc.UsernamePasswordToken; /** * author: wenxian.cai * date: 2017/9/25 11:13 */ public class UserToken extends UsernamePasswordToken { private String validCode; public UserToken(String username, String password, boolean rememberMe, String validCode, String host) { super.setUsername(username); super.setPassword(<PASSWORD>()); super.setRememberMe(rememberMe); this.validCode = validCode; super.setHost(host); } public String getValidCode() { return validCode; } public void setValidCode(String validCode) { this.validCode = validCode; } } <file_sep>package controller.music; import controller.common.BaseController; import exception.ErrorCode; import exception.SerException; import model.dto.common.BaseDTO; import model.enums.music.TopListType; import model.po.common.PagePO; import model.po.music.ArtistPO; import model.po.music.SongInfoPO; import model.vo.music.TopListVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import service.common.Result; import service.common.impl.ActResult; import service.music.ISongService; import java.util.List; import static model.constant.Common.PAGE_LIMIT; /** * 歌曲业务 * * @Author: [caiwenxian] * @Date: [2018-02-05 17:52] * @Description: [ 歌曲业务 ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Controller @RequestMapping("/song") public class SongController extends BaseController { @Autowired ISongService songService; /** * 歌曲模糊搜索 * * @param * @return class * @version v1 */ @GetMapping("/search/{name}/{page}") @ResponseBody public Result search(@PathVariable String name, @PathVariable Integer page) { try { // List<SongInfoPO> list = songService.listSongByName(name); page = page == null ? 1 : page; PagePO<SongInfoPO> pagePO = songService.listSongByNameByPage(name, page, PAGE_LIMIT); return ActResult.data(pagePO); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } /** * 根据排行榜id获取排行榜歌曲 * * @param * @return class * @version v1 */ @GetMapping("/toplist/{id}") @ResponseBody public Result getTopList(@PathVariable String id) { try { TopListVO vo = songService.listTopListByTopListId(id); return ActResult.data(vo); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } /** * 获取热门歌曲 * * @param * @return class * @version v1 */ @GetMapping("/hotsong/{page}") @ResponseBody public Result listHotSong(@PathVariable Integer page) { try { BaseDTO dto = new BaseDTO(); dto.setPage(page); dto.setLimit(20); PagePO vo = songService.listHotSong(dto); return ActResult.data(vo); } catch (SerException e) { return ActResult.error(ErrorCode.GENERAL, e.getMessage()); } } } <file_sep>package com; import controller.security.token.UserToken; import exception.ActException; import exception.SerException; import model.po.music.SongInfoPO; import model.po.user.LoginPO; import model.po.user.UserPO; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import service.common.Result; import service.common.impl.ActResult; import service.music.ISongService; import service.user.IUserService; import service.user.ILoginService; import utils.CacheManage; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; import java.util.logging.Logger; /** * @Author: [caiwenxian] * @Date: [2018-01-16 11:11] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Controller @RequestMapping("/test") public class TestController { final Logger logger = Logger.getLogger(TestController.class.getName()); @Autowired IUserService userService; @Autowired ISongService songService; @GetMapping("/v1/test") @ResponseBody public String test() { CacheManage cacheManage = new CacheManage(); try { Collection collection = cacheManage.AllSession(); } catch (Exception e) { e.printStackTrace(); } return "hello"; } @GetMapping("/v1/user") @ResponseBody public Result user() { try { userService.addUser(new UserPO("zhangsan", "000000", 1)); return ActResult.success("success"); } catch (SerException e) { return ActResult.error(303, e.getMessage()); } } @GetMapping("/v1/home") public ModelAndView home() { return new ModelAndView("home/home"); } @GetMapping("v1/transaction") public String test1() { try { songService.update(new SongInfoPO("28196001", null, null, null, "212", null, null)); return "success"; } catch (SerException e) { e.printStackTrace(); return "error"; } } @Autowired EhCacheManager cacheManager; @Autowired ILoginService loginService; @GetMapping("v1/login") @ResponseBody public String login(HttpServletRequest request, HttpServletResponse response) throws ActException { UserToken token = new UserToken("zhangsan", "<PASSWORD>", true, null, null); Subject subject = SecurityUtils.getSubject(); try { loginService.login(new LoginPO("zhangsan", "000000")); // Object object = subject.getSession().getAttribute(subject.getSession().getId()); String refUrl = request.getParameter("refUrl"); if (StringUtils.isNotBlank(refUrl)) { response.sendRedirect(refUrl); } return "success"; } catch (SerException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { return "success"; } } @GetMapping("/v1/header") @ResponseBody public ModelAndView header() { return new ModelAndView("common/header"); } } <file_sep>package com.wenxianm.service.user; import com.wenxianm.exception.SerException; import com.wenxianm.model.po.user.UserPO; /** * @Author: [caiwenxian] * @Date: [2018-01-25 16:12] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public interface IUserService { /** * 添加用户 * * @param po * @return class * @version v1 */ void addUser(UserPO po) throws SerException; /** * 根据姓名获取用户 * * @param * @return class * @version v1 */ UserPO getUserByName(String name) throws SerException; /** * 根据姓名获取基本信息 * * @param * @return class * @version v1 */ UserPO getUserInfoByName(String name) throws SerException; } <file_sep>package service.music.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import dao.java.music.IArtistDao; import exception.SerException; import model.constant.NetseaseUrl; import model.po.music.ArtistPO; import model.po.music.HotArtistPO; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.jdbc.Null; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.common.impl.BaseServiceImpl; import service.music.IArtistService; import service.music.reptile.IReptileArtistService; import utils.HttpClientHelper; import utils.RandomUtil; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-01-19 09:34] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ @Service public class ArtistServiceImpl extends BaseServiceImpl implements IArtistService { @Autowired IArtistDao artistDao; @Autowired IReptileArtistService reptileArtistService; public void addArtist(ArtistPO po) throws SerException { synchronized (ArtistServiceImpl.class) { if (StringUtils.isBlank(po.getArtistId())) { throw new SerException("歌手artistId为空"); } ArtistPO old = artistDao.getArtistByArtistId(po.getArtistId()); if (old != null) { logger.info("歌手已存在"); return; } po.setId(RandomUtil.getUid()); artistDao.addArtist(po); } } @Override public void addHotArtist(List<HotArtistPO> pos) throws SerException { if (pos == null || pos.size() == 0) { return; } for (HotArtistPO po : pos) { po.setId(RandomUtil.getUid()); } artistDao.addHotArtist(pos); } @Override public List<ArtistPO> listArtistByName(String name) throws SerException { List<ArtistPO> list = artistDao.listArtistByName(name); if (list.size() == 0) { //若本地数据库找不到,则进行爬取 reptileArtistService.asynReptile(1, new String[]{name}); try { Thread.currentThread().sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } list = artistDao.listArtistByName(name); } return list; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>blog</groupId> <artifactId>blog</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <springframework.version>4.3.5.RELEASE</springframework.version> <jackson.version>2.7.5</jackson.version> <!--<mybatis.version>1.0</mybatis.version>--> <java-version>1.7</java-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springframework.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <!-- <dependency> <groupId>com.alipay</groupId> <artifactId>sdk-java</artifactId> <version>20170324180803</version> </dependency>--> <!--本地生成--> <!--<dependency> <groupId>com.jedis</groupId> <artifactId>sdk-java</artifactId> <version>2.9.0</version> </dependency>--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.28</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax/javaee-api --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/aspectj/aspectjrt --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.12.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.4</version> </dependency> <!--<dependency>--> <!--<groupId>org.junit.jupiter</groupId>--> <!--<artifactId>junit-jupiter-api</artifactId>--> <!--<version>RELEASE</version>--> <!--</dependency>--> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-typehandlers-jsr310</artifactId> <version>1.0.1</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.15.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.15.0</version> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>1.6.0.RELEASE</version> </dependency> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.8.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.8.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.8.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.3.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warName>${project.artifactId}</warName> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>(1)添加事务方法: @Transactional(propagation = Propagation.REQUIRED, rollbackFor = SerException.class)<file_sep>package com.wenxianm.controller.about; import com.wenxianm.controller.common.BaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * @Author: [caiwenxian] * @Date: [2018-03-19 10:47] * @Description: [ ] * @Version: [1.0.0] */ @Controller @RequestMapping("/about") public class AboutController extends BaseController { @GetMapping("/about-author") @ResponseBody public ModelAndView aboutAuthorPage() { return new ModelAndView("about/about-author"); } @GetMapping("/about-blog") @ResponseBody public ModelAndView aboutBlogPage() { return new ModelAndView("about/about-blog"); } @GetMapping("/guest-message") @ResponseBody public ModelAndView guestMessagePage() { return new ModelAndView("about/guest-message"); } } <file_sep>package service.mq.activemq; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jms.*; /** * 发送消息服务 * * @author caiwx * @date 2019年01月18日 9:38 * */ @Service public class MessageService { @Resource(name = "jmsTemplate") private JmsTemplate jmsTemplate; @Resource(name = "queueDestination") private Destination queueDestination; @Resource(name = "topicDestination") private Destination topicDestination; /** * 发送队列文本消息 * * @author caiwx * @date 2019年01月18日 9:35 * */ public void sendQueueMessage(final String messageContent) { jmsTemplate.send(queueDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(messageContent); return message; } }); } /** * 发送主题文本消息 * * @author caiwx * @date 2019年01月18日 9:36 * */ public void sendTopicMessage(final String messageContent) { jmsTemplate.send(topicDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage(messageContent); return textMessage; } }); } } <file_sep>package model.po.base.validate; /** * @Author: [caiwenxian] * @Date: [2018-03-06 10:19] * @Description: [ ] * @Version: [1.0.0] */ public interface UPDATE { } <file_sep>package model.po.base.validate; /** * @Author: [caiwenxian] * @Date: [2018-03-06 10:20] * @Description: [ ] * @Version: [1.0.0] */ public interface SELECT { } <file_sep>package com; public class Singleton1 { private static Singleton1 singleton = new Singleton1(); public Singleton1() { } public static Singleton1 getSingleton() { return singleton; } } <file_sep>package com.wenxianm.service.music; import com.wenxianm.exception.SerException; import com.wenxianm.model.dto.music.TopListDTO; import com.wenxianm.model.po.music.SongInfoPO; import com.wenxianm.model.po.music.TopListDetailsPO; import com.wenxianm.model.po.music.TopListPO; import java.util.List; /** * @Author: [caiwenxian] * @Date: [2018-01-17 17:42] * @Description: [ ] * @Version: [1.0.0] * @Copy: [com.bjike] */ public interface ITopListService { // void addSong(SongInfoPO po); /** * 添加排行榜 * * @param * @return class * @version v1 */ void addTopList(TopListPO po) throws SerException; /** * 添加排行榜-歌曲关联 * * @param * @return class * @version v1 */ void addTopListDetails(TopListDetailsPO po) throws SerException; /** * 根据排行榜id获取排行榜 * * @param * @return class * @version v1 */ TopListPO getByTopListId(String topListId) throws SerException; /** * 删除排行榜-歌曲关联 * * @param * @return class * @version v1 */ void deleteTopListDetails(String topListId) throws SerException; } <file_sep>package com.wenxianm.controller.music; import com.wenxianm.controller.common.BaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * @Author: [caiwenxian] * @Date: [2018-03-19 10:57] * @Description: [ ] * @Version: [1.0.0] */ @Controller @RequestMapping("/music") public class MusicController extends BaseController { @GetMapping @ResponseBody public ModelAndView musicPage() { return new ModelAndView("music/music"); } } <file_sep>package com.wenxianm.model.po.knowledge; import com.wenxianm.model.enums.knowledge.ArticleStatus; import com.wenxianm.model.enums.knowledge.ArticleType; import com.wenxianm.model.po.base.annotation.TableName; import com.wenxianm.model.po.common.BasePO; import com.wenxianm.model.po.user.UserPO; /** * 文章 * * @Author: [caiwenxian] * @Date: [2018-03-13 15:28] * @Description: [ ] * @Version: [1.0.0] */ @TableName(name = "t_article") public class ArticlePO extends BasePO { private byte[] content; private Integer status; private Integer type; private String title; private String contentText; private String userId; private String userName; private Integer browseAmount; private Integer commentAmount; public ArticlePO() { } public ArticlePO(byte[] content) { this.content = content; } public ArticlePO(byte[] content, Integer status, Integer type) { this.content = content; this.status = status; this.type = type; } public ArticlePO(byte[] content, Integer status, Integer type, String title) { this.content = content; this.status = status; this.type = type; this.title = title; } public ArticlePO(byte[] content, Integer status, Integer type, String title, String contentText) { this.content = content; this.status = status; this.type = type; this.title = title; this.contentText = contentText; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContentText() { return contentText; } public void setContentText(String contentText) { this.contentText = contentText; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getBrowseAmount() { return browseAmount; } public void setBrowseAmount(Integer browseAmount) { this.browseAmount = browseAmount; } public Integer getCommentAmount() { return commentAmount; } public void setCommentAmount(Integer commentAmount) { this.commentAmount = commentAmount; } } <file_sep>package com.wenxianm.exception; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Author: [caiwenxian] * @Date: [2018-03-20 09:16] * @Description: [ ] * @Version: [1.0.0] */ public class ExceptionResolver implements HandlerExceptionResolver { //该方法的的参数会自动获取 请求(request),响应(response),异常(exception),handler(异常参数的处理器 Controller) public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mav = new ModelAndView(); /*if (ex instanceof SerException) { }*/ //系统异常 try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e) { e.printStackTrace(); } mav.addObject("message", "系统出现异常,请稍后访问"); mav.setViewName("common/500"); return mav; } }
d0a34993629b8a89a062c284d3f7e50d499aafc5
[ "Markdown", "Java", "Maven POM" ]
65
Java
caiwenxian/bolg-java
2263dfff57572ceca79916903ef2a0ee17c24546
bea90b3bcd1dc6a944ea413e78c0a3731a564654
refs/heads/master
<file_sep>from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter): def __init__(self, url_map, *items): super(RegexConverter, self).__init__(url_map) self.regex = items[0] PAPER_ID_REGEX = r"[a-zA-Z0-9:\./]+" class PaperIdConverter(RegexConverter): def __init__(self, url_map): super(PaperIdConverter, self).__init__(url_map, PAPER_ID_REGEX) <file_sep>$(document).ready(function() { var currentVisibleNodes = {}; var entryTextArea = $('#entry'); var userText = $('#user'); var passwordText = $('#<PASSWORD>'); var referenceButton = $('#reference'); var referenceMessageText = $("#referenceMessage"); var paper1Text = $('#paper1'); var paper2Text = $('#paper2'); var addEntryButton = $('#addEntry'); function setAuth(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(userText.val() + ":" + passwordText.val())); } referenceButton.click(function(e) { var referee = paper1Text.val(); var referenced = paper2Text.val(); var message = referenceMessageText.val(); var url = "/api/references/" + referee + "/" + referenced; $.ajax({ url: url, type: "POST", beforeSend: setAuth, data: JSON.stringify({message:message}), contentType: "application/json", success: function(result) { alert("Success!"); }, error: function(result) { if(result.status == 409) { alert("Relationship already exists!"); } else { alert(result.status + " " + result.statusText); } } }); }); addEntryButton.click(function(e) { var entry = entryTextArea.val(); $.ajax({ url: "/api/papers", type: "POST", beforeSend: setAuth, data: entry, contentType: "text/plain", success: function(data) { alert("Inserted!"); }, error: function(result) { if(result.status == 409) { alert("That entry already exists!"); } else { alert(result.status + " " + result.statusText); } } }) }); }); <file_sep>from flask import Flask from flask_graphql import GraphQLView from mybib.graphql import schemas from mybib.web.api.papers import papers_api from mybib.web.api.references import references_api from mybib.web.api.root import root_api from mybib.web.front import frontend from mybib.web.routing.regex_converters import PaperIdConverter app = Flask(__name__, template_folder="front/templates", static_folder="front/static") app.url_map.converters["paper_id"] = PaperIdConverter app.register_blueprint(frontend) app.register_blueprint(root_api) app.register_blueprint(papers_api) app.register_blueprint(references_api) app.add_url_rule( "/graphql", view_func=GraphQLView.as_view("graphql", schema=schemas.schema, graphiql=True), ) <file_sep>import bibtexparser from bibtexparser.customization import type as bibtextparser_type from mybib.bibtext.utils import _split_by def _get_keywords(record): """ Split keyword field into a list. :param record: the record. :type record: dict :type record: string, optional :returns: dict -- the modified record. """ keyword = record.get("keyword") keywords = record.get("keywords") if keyword: del record["keywords"] record["keywords"] = _split_by(keyword) elif keywords: del record["keywords"] record["keywords"] = _split_by(keywords) else: record["keywords"] = [] return record def _get_authors(record): """ Split author field into a list of "Name, Surname". :param record: the record. :type record: dict :returns: dict -- the modified record. """ author = record.get("author") authors = record.get("authors") if authors: del record["authors"] record["authors"] = bibtexparser.customization.getnames( [i.strip() for i in authors.replace("\n", " ").split(" and ")] ) elif author: del record["author"] record["authors"] = bibtexparser.customization.getnames( [i.strip() for i in author.replace("\n", " ").split(" and ")] ) else: record["authors"] = [] return record def _customize(record): record = bibtextparser_type(record) record = _get_authors(record) record = bibtexparser.customization.editor(record) record = _get_keywords(record) record = bibtexparser.customization.page_double_hyphen(record) return record <file_sep>from flask import Blueprint, jsonify, request root_api = Blueprint("root_api", __name__) @root_api.route("/api/recent") def get_recent_nodes(): # nodes, references = recent_papers_and_references() return jsonify({"nodes": None, "references": None}) <file_sep>from mybib.bibtext.reader import load_from_string def test_load_from_string_dblp_format(bibtex_dblp_format, json_dblp_format): actual = load_from_string(bibtex_dblp_format) assert actual == json_dblp_format def test_load_from_string_multiple_authors(bibtex_json_multiple_authors): bibtex_multiple_authors, json_multiple_authors = bibtex_json_multiple_authors actual = load_from_string(bibtex_multiple_authors) assert actual == json_multiple_authors def test_load_from_string_single_author(bibtex_json_single_author): bibtex_single_author, json_single_author = bibtex_json_single_author actual = load_from_string(bibtex_single_author) assert actual == json_single_author def test_load_from_string_no_keywords(bibtex_json_no_keywords): bibtex_no_keywords, json_no_keywords = bibtex_json_no_keywords actual = load_from_string(bibtex_no_keywords) assert actual == json_no_keywords <file_sep># MyBib Keep track of your bibliography using Neo4j. With a simple user interface add research papers from their BibTex citations, query them and link them together. ## Deploy to Heroku: Simply follow the [steps outlined here](https://devcenter.heroku.com/articles/getting-started-with-python#deploy-the-app), but instead of cloning their source code, clone this repository instead (`https://github.com/fferegrino/mybib.git`). You'll also need a running instance of Neo4j, I used [GrapheneDB](https://elements.heroku.com/addons/graphenedb), which is free and easy to install into your recently created Heroku app. After deployment, there are two configurations that you must set in order to interact with your app: `MYBIB_USER` and `MYBIB_PASS`, these values will be used for authentication. <file_sep>import base64 from unittest.mock import patch import pytest from mybib.web.app import app @pytest.fixture(scope="session", autouse=True) def patch_neo4j(request): def unpatch(): pass request.addfinalizer(unpatch) @pytest.fixture def auth_header(): valid_credentials = base64.b64encode(b"testuser:testpassword").decode("utf-8") return {"Authorization": "Basic " + valid_credentials} @pytest.fixture def client(): return app.test_client() @pytest.fixture def authenticated_post(client, auth_header): def post(*args, **kwargs): kwargs["headers"] = auth_header return client.post(*args, **kwargs) with patch("mybib.web.authentication.check_auth") as check_auth: check_auth.return_value = True yield post <file_sep>from flask import Blueprint, render_template, request from werkzeug.utils import redirect from mybib.neo4j.models import Keyword, Paper, Project frontend = Blueprint("frontend", __name__) @frontend.route("/admin", methods=["GET"]) def get_index(): return render_template("admin.html") @frontend.route("/", methods=["GET"]) def get_graph(): return render_template("graph.html") @frontend.route("/papers/<paper_id:identifier>", methods=["GET"]) def get_paper(identifier): paper = Paper(ID=identifier).fetch() keywords = ",".join([kw["value"] for kw in paper.fetch_keywords()]) projects = ",".join([pr["name"] for pr in paper.fetch_projects()]) paper = paper.asdict() title = paper.pop("title") time = paper.pop("_time") ID = paper.pop("ID") bibtex = paper.pop("_bibtex") return render_template( "paper.html", ID=ID, keywords=keywords, projects=projects, title=title, paper=paper, ) @frontend.route("/papers/<paper_id:identifier>", methods=["POST"]) def post_paper(identifier): updated_paper = request.form.to_dict() new_keywords = set(updated_paper.pop("keywords").split(",")) new_projects = set(updated_paper.pop("projects").split(",")) ID = updated_paper.pop("ID") paper_to_update = Paper(ID=ID).fetch() existing_keywords = { keyword["value"] for keyword in paper_to_update.fetch_keywords() } existing_projects = { project["name"] for project in paper_to_update.fetch_projects() } keep_keywords = existing_keywords.intersection(new_keywords) to_remove_keywords = existing_keywords - keep_keywords to_add_keywords = new_keywords - keep_keywords keep_projects = existing_projects.intersection(new_projects) to_remove_projects = existing_projects - keep_projects to_add_projects = new_projects - keep_projects for kw in to_add_keywords: keyword = Keyword(value=kw) fetched_keyword = keyword.fetch() if fetched_keyword: paper_to_update.keywords.add(fetched_keyword) else: keyword.save() paper_to_update.keywords.add(keyword) for kw in to_remove_keywords: keyword = Keyword(value=kw) fetched_keyword = keyword.fetch() paper_to_update.keywords.remove(fetched_keyword) for pj in to_add_projects: project = Project(name=pj) fetched_project = project.fetch() if fetched_project: paper_to_update.projects.add(fetched_project) else: project.save() paper_to_update.projects.add(project) for pj in to_remove_projects: project = Project(name=pj) fetched_project = project.fetch() paper_to_update.projects.remove(fetched_project) paper_to_update.save() return redirect("/papers/" + identifier) <file_sep>from py2neo import NodeMatcher from mybib.neo4j.models import ( REFERENCES_RELATIONSHIP, Author, Keyword, Paper, Project, get_graph, ) class EntityAlreadyExistsError(Exception): pass def get_create_keyword(keyword): kw = Keyword(keyword) kw_ = kw.fetch() if kw_ is None: kw.save() return kw return kw_ def get_create_author(author): auth = Author(name=author) auth_ = auth.fetch() if auth_ is None: auth.save() return auth return auth_ def get_paper(identifier): paper = Paper(ID=identifier).fetch() return paper.asdict() def insert_paper(paper_dict): keywords = paper_dict.pop("keywords") authors = paper_dict.pop("authors") paper_to_insert = Paper(**paper_dict) existing_paper = paper_to_insert.fetch() if existing_paper is not None: raise EntityAlreadyExistsError() paper_to_insert.save() for kw in keywords: paper_to_insert.keywords.add(get_create_keyword(kw)) for author in authors: paper_to_insert.authors.add(get_create_author(author)) paper_to_insert.save() return paper_to_insert def are_related(referee_id, referenced_id): referee = Paper(ID=referee_id).fetch() referenced = Paper(ID=referenced_id).fetch() assert referee is not None assert referenced is not None graph = get_graph() matches = list( graph.match( (referee.__ogm__.node, referenced.__ogm__.node), r_type=REFERENCES_RELATIONSHIP, ) ) return len(matches) > 0 def insert_reference(referee, referenced, attr_dict): relationship_exists = are_related(referee, referenced) if relationship_exists: raise EntityAlreadyExistsError() referee_paper = Paper(ID=referee).fetch() referenced_paper = Paper(ID=referenced).fetch() referee_paper.references.add(referenced_paper, attr_dict) referee_paper.save() def return_keywords(query): graph = get_graph() matcher = NodeMatcher(graph) kws = matcher.match("Keyword", value__contains=query) return [dict(kw) for kw in kws] def return_papers_by_keyword(query): graph = get_graph() matcher = NodeMatcher(graph) kws = matcher.match("Keyword", value__contains=query) retrieved_papers = set() papers = [] for keyword in [Keyword(**dict(kw)).fetch() for kw in kws]: for paper in keyword.fetch_papers(): if paper["ID"] in retrieved_papers: continue papers.append(paper) retrieved_papers.add(paper["ID"]) return papers def return_papers_by_author(query): graph = get_graph() matcher = NodeMatcher(graph) kws = matcher.match("Author", name__contains=query) retrieved_papers = set() papers = [] for keyword in [Author(**dict(kw)).fetch() for kw in kws]: for paper in keyword.fetch_papers(): if paper["ID"] in retrieved_papers: continue papers.append(paper) retrieved_papers.add(paper["ID"]) return papers def return_papers_by_project(query): graph = get_graph() matcher = NodeMatcher(graph) kws = matcher.match("Project", name__contains=query) retrieved_papers = set() papers = [] for keyword in [Project(**dict(kw)).fetch() for kw in kws]: for paper in keyword.fetch_papers(): if paper["ID"] in retrieved_papers: continue papers.append(paper) retrieved_papers.add(paper["ID"]) return papers def return_papers_by_title(query): graph = get_graph() matcher = NodeMatcher(graph) nodes = matcher.match("Paper", title__contains=query) return [Paper(**dict(p)) for p in nodes] <file_sep>import re def _split_by(text, separator=",|;"): return [i.strip() for i in re.split(separator, text.replace("\n", ""))] <file_sep>import pytest @pytest.fixture def bibtex_dblp_format(): return """@article{DBLP:journals/corr/NohASH16, author = {<NAME> and <NAME> and <NAME> and <NAME>}, title = {Image Retrieval with Deep Local Features and Attention-based Keypoints}, journal = {CoRR}, volume = {abs/1612.06321}, year = {2016}, url = {http://arxiv.org/abs/1612.06321}, archivePrefix = {arXiv}, eprint = {1612.06321}, timestamp = {Mon, 13 Aug 2018 16:48:55 +0200}, biburl = {https://dblp.org/rec/bib/journals/corr/NohASH16}, bibsource = {dblp computer science bibliography, https://dblp.org} }""" @pytest.fixture def json_dblp_format(): return [ { "journal": "CoRR", "volume": "abs/1612.06321", "year": "2016", "url": "http://arxiv.org/abs/1612.06321", "archiveprefix": "arXiv", "eprint": "1612.06321", "keywords": [], "timestamp": "Mon, 13 Aug 2018 16:48:55 +0200", "biburl": "https://dblp.org/rec/bib/journals/corr/NohASH16", "bibsource": "dblp computer science bibliography, https://dblp.org", "title": "Image Retrieval with Deep Local Features and Attention-based Keypoints", "authors": ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], "ENTRYTYPE": "article", "ID": "DBLP:journals/corr/NohASH16", } ] @pytest.fixture def bibtex_json_multiple_authors(): return ( """@inproceedings{Petrovski:2017:EAP:3106426.3106449, author = {Petrovski, Petar and Bizer, Christian}, title = {Extracting Attribute-value Pairs from Product Specifications on the Web}, booktitle = {Proceedings of the International Conference on Web Intelligence}, series = {WI '17}, year = {2017}, isbn = {978-1-4503-4951-2}, location = {Leipzig, Germany}, pages = {558--565}, numpages = {8}, url = {http://doi.acm.org/10.1145/3106426.3106449}, doi = {10.1145/3106426.3106449}, acmid = {3106449}, publisher = {ACM}, address = {New York, NY, USA}, keywords = {feature extraction, product data, schema matching, web tables}, }""", [ { "keywords": [ "feature extraction", "product data", "schema matching", "web tables", ], "address": "New York, NY, USA", "publisher": "ACM", "acmid": "3106449", "doi": "10.1145/3106426.3106449", "url": "http://doi.acm.org/10.1145/3106426.3106449", "numpages": "8", "pages": "558--565", "location": "Leipzig, Germany", "isbn": "978-1-4503-4951-2", "year": "2017", "series": "WI '17", "booktitle": "Proceedings of the International Conference on Web Intelligence", "title": "Extracting Attribute-value Pairs from Product Specifications on the Web", "authors": ["<NAME>", "<NAME>"], "ENTRYTYPE": "inproceedings", "ID": "Petrovski:2017:EAP:3106426.3106449", } ], ) @pytest.fixture def single_json_multiple_authors(bibtex_json_multiple_authors): return bibtex_json_multiple_authors[1][0] @pytest.fixture def bibtex_json_single_author(): return ( """@inproceedings{Petrovski:2017:EAP:3106426.3106449, author = {<NAME>}, title = {Extracting Attribute-value Pairs from Product Specifications on the Web}, booktitle = {Proceedings of the International Conference on Web Intelligence}, series = {WI '17}, year = {2017}, isbn = {978-1-4503-4951-2}, location = {Leipzig, Germany}, pages = {558--565}, numpages = {8}, url = {http://doi.acm.org/10.1145/3106426.3106449}, doi = {10.1145/3106426.3106449}, acmid = {3106449}, publisher = {ACM}, address = {New York, NY, USA}, keywords = {feature extraction, product data, schema matching, web tables}, }""", [ { "keywords": [ "feature extraction", "product data", "schema matching", "web tables", ], "address": "New York, NY, USA", "publisher": "ACM", "acmid": "3106449", "doi": "10.1145/3106426.3106449", "url": "http://doi.acm.org/10.1145/3106426.3106449", "numpages": "8", "pages": "558--565", "location": "Leipzig, Germany", "isbn": "978-1-4503-4951-2", "year": "2017", "series": "WI '17", "booktitle": "Proceedings of the International Conference on Web Intelligence", "title": "Extracting Attribute-value Pairs from Product Specifications on the Web", "authors": ["<NAME>"], "ENTRYTYPE": "inproceedings", "ID": "Petrovski:2017:EAP:3106426.3106449", } ], ) @pytest.fixture def bibtex_json_no_keywords(): return ( """@inproceedings{Petrovski:2017:EAP:3106426.3106449, author = {<NAME>}, title = {Extracting Attribute-value Pairs from Product Specifications on the Web}, booktitle = {Proceedings of the International Conference on Web Intelligence}, series = {WI '17}, year = {2017}, isbn = {978-1-4503-4951-2}, location = {Leipzig, Germany}, pages = {558--565}, numpages = {8}, url = {http://doi.acm.org/10.1145/3106426.3106449}, doi = {10.1145/3106426.3106449}, acmid = {3106449}, publisher = {ACM}, address = {New York, NY, USA}, }""", [ { "keywords": [], "address": "New York, NY, USA", "publisher": "ACM", "acmid": "3106449", "doi": "10.1145/3106426.3106449", "url": "http://doi.acm.org/10.1145/3106426.3106449", "numpages": "8", "pages": "558--565", "location": "Leipzig, Germany", "isbn": "978-1-4503-4951-2", "year": "2017", "series": "WI '17", "booktitle": "Proceedings of the International Conference on Web Intelligence", "title": "Extracting Attribute-value Pairs from Product Specifications on the Web", "authors": ["<NAME>"], "ENTRYTYPE": "inproceedings", "ID": "Petrovski:2017:EAP:3106426.3106449", } ], ) <file_sep>FROM python:3.6-alpine ENV PATH ${PATH}:/root/.local/bin WORKDIR /code COPY Pipfile Pipfile.lock ./ COPY mybib ./mybib RUN pip install --user pipenv && \ pipenv install --system --deploy CMD ["gunicorn", "--chdir", "mybib/web", "--reload", "app:app", "-b :8000"] <file_sep>import json from unittest.mock import MagicMock, patch import pytest from mybib.graphql.access_layer import EntityAlreadyExistsError @patch("mybib.web.api.references.insert_reference") def test_post_inserts(insert_reference_mock, authenticated_post): id1 = "id1" id2 = "id2" expected = {"a": "reference"} response = authenticated_post( f"/api/references/{id1}/{id2}", data=json.dumps(expected), content_type="application/json", ) insert_reference_mock.assert_called_once_with(id1, id2, expected) assert response.status_code == 201 @patch( "mybib.web.api.references.insert_reference", side_effect=EntityAlreadyExistsError() ) def test_post_inserts_fails_already_exists(insert_reference_mock, authenticated_post): id1 = "id1" id2 = "id2" expected = {"a": "reference"} response = authenticated_post( f"/api/references/{id1}/{id2}", data=json.dumps(expected), content_type="application/json", ) insert_reference_mock.assert_called_once_with(id1, id2, expected) assert response.status_code == 409 @patch("mybib.web.api.references.insert_reference", side_effect=AssertionError()) def test_post_inserts_fails_reference_does_not_exist( insert_reference_mock, authenticated_post ): id1 = "id1" id2 = "id2" expected = {"a": "reference"} response = authenticated_post( f"/api/references/{id1}/{id2}", data=json.dumps(expected), content_type="application/json", ) insert_reference_mock.assert_called_once_with(id1, id2, expected) assert response.status_code == 400 <file_sep>import graphene import mybib.graphql.access_layer from mybib.neo4j import models class MyBibSchema(graphene.ObjectType): _time = graphene.Float() class AuthorSchema(MyBibSchema): name = graphene.String() class KeywordSchema(MyBibSchema): value = graphene.String() class ProjectSchema(MyBibSchema): name = graphene.String() class PaperSchema(MyBibSchema): ID = graphene.String() title = graphene.String() address = graphene.String() acmid = graphene.String() year = graphene.String() isbn = graphene.String() link = graphene.String() _bibtex = graphene.String() numpages = graphene.String() url = graphene.String() pages = graphene.String() series = graphene.String() ENTRYTYPE = graphene.String() publisher = graphene.String() location = graphene.String() booktitle = graphene.String() doi = graphene.String() authors = graphene.List(AuthorSchema) keywords = graphene.List(KeywordSchema) projects = graphene.List(ProjectSchema) references = graphene.List(lambda: PaperSchema) def resolve_authors(self, info): return [ AuthorSchema(**author) for author in models.Paper(ID=self.ID).fetch().fetch_authors() ] def resolve_keywords(self, info): return [ KeywordSchema(**keyword) for keyword in models.Paper(ID=self.ID).fetch().fetch_keywords() ] def resolve_projects(self, info): return [ ProjectSchema(**project) for project in models.Paper(ID=self.ID).fetch().fetch_projects() ] def resolve_references(self, info): return [ PaperSchema(**paper) for paper in models.Paper(ID=self.ID).fetch().fetch_references() ] class Query(graphene.ObjectType): paper = graphene.Field(lambda: PaperSchema, ID=graphene.String()) keywords = graphene.List(lambda: KeywordSchema, keyword=graphene.String()) by_id = graphene.List(lambda: PaperSchema, parameter=graphene.String()) by_keywords = graphene.List(lambda: PaperSchema, parameter=graphene.String()) by_author = graphene.List(lambda: PaperSchema, parameter=graphene.String()) by_title = graphene.List(lambda: PaperSchema, parameter=graphene.String()) by_project = graphene.List(lambda: PaperSchema, parameter=graphene.String()) papers = graphene.List(lambda: PaperSchema) def resolve_paper(self, info, ID): customer = models.Paper(ID=ID).fetch() return PaperSchema(**customer.asdict()) def resolve_papers(self, info): return [PaperSchema(**paper.asdict()) for paper in models.Paper().all()] def resolve_keywords(self, info, keyword): return [ KeywordSchema(**kw) for kw in mybib.graphql.access_layer.return_keywords(keyword) ] def resolve_by_id(self, info, parameter): customer = models.Paper(ID=parameter).fetch() return [PaperSchema(**customer.asdict())] def resolve_by_keywords(self, info, parameter): return [ PaperSchema(**paper) for paper in mybib.graphql.access_layer.return_papers_by_keyword(parameter) ] def resolve_by_author(self, info, parameter): return [ PaperSchema(**paper) for paper in mybib.graphql.access_layer.return_papers_by_author(parameter) ] def resolve_by_project(self, info, parameter): return [ PaperSchema(**paper) for paper in mybib.graphql.access_layer.return_papers_by_project(parameter) ] def resolve_by_title(self, info, parameter): return [ PaperSchema(**paper.asdict()) for paper in mybib.graphql.access_layer.return_papers_by_title(parameter) ] schema = graphene.Schema(query=Query, auto_camelcase=False) <file_sep>version: '3' services: web: build: context: ../ dockerfile: docker/Dockerfile ports: - "8000:8000" environment: - NEO4J_URL=neo4j - NEO4J_USER=neo4j - NEO4J_PASS=<PASSWORD> - NEO4J_PORT=7687 - MYBIB_USER=fferegrino - MYBIB_PASSWORD=<PASSWORD> neo4j: image: "neo4j:3.5.7" ports: - "7474:7474" - "7687:7687" environment: - NEO4J_AUTH=neo4j/neo4j_generic <file_sep>import os from py2neo import Graph from py2neo.ogm import GraphObject, Property, RelatedFrom, RelatedTo GRAPH: Graph = None REFERENCES_RELATIONSHIP = "REFERENCES" WROTE_RELATIONSHIP = "WROTE" HAS_KEYWORD_RELATIONSHIP = "HAS_KEYWORD" PART_OF_RELATIONSHIP = "PART_OF" def get_graph(): global GRAPH if not GRAPH: host = os.getenv("NEO4J_URL") user = os.getenv("NEO4J_USER") password = <PASSWORD>("NEO4J_PASS") port = int(os.getenv("NEO4J_PORT")) GRAPH = Graph(host=host, user=user, password=<PASSWORD>, port=port, secure=True) return GRAPH class BaseModel(GraphObject): __other_properties_dict = dict() _time = Property() def __init__(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) else: self.__other_properties_dict[key] = value def all(self): graph = get_graph() return self.match(graph) def save(self): graph = get_graph() graph.push(self) class Paper(BaseModel): __primarykey__ = "ID" ID = Property() title = Property() address = Property() acmid = Property() year = Property() isbn = Property() link = Property() _bibtex = Property() numpages = Property() url = Property() pages = Property() series = Property() ENTRYTYPE = Property() publisher = Property() location = Property() booktitle = Property() doi = Property() authors = RelatedFrom("Author", WROTE_RELATIONSHIP) keywords = RelatedTo("Keyword", HAS_KEYWORD_RELATIONSHIP) projects = RelatedFrom("Project", PART_OF_RELATIONSHIP) references = RelatedTo("Paper", REFERENCES_RELATIONSHIP) referenced_by = RelatedFrom("Paper", REFERENCES_RELATIONSHIP) def asdict(self): return { "ID": self.ID, "title": self.title, "address": self.address, "acmid": self.acmid, "year": self.year, "isbn": self.isbn, "link": self.link, "_bibtex": self._bibtex, "_time": self._time, "numpages": self.numpages, "url": self.url, "pages": self.pages, "series": self.series, "ENTRYTYPE": self.ENTRYTYPE, "publisher": self.publisher, "location": self.location, "booktitle": self.booktitle, "doi": self.doi, } def fetch(self): graph = get_graph() return Paper.match(graph, self.ID).first() def fetch_authors(self): return [ {**author[0].asdict(), **author[1]} for author in self.authors._related_objects ] def fetch_keywords(self): return [{**kw[0].asdict(), **kw[1]} for kw in self.keywords._related_objects] def fetch_projects(self): return [ {**proj[0].asdict(), **proj[1]} for proj in self.projects._related_objects ] def fetch_references(self): return [{**proj[0].asdict()} for proj in self.references._related_objects] class Author(BaseModel): __primarykey__ = "name" name = Property() papers = RelatedTo("Paper", WROTE_RELATIONSHIP) def fetch(self): graph = get_graph() return Author.match(graph, self.name).first() def fetch_papers(self): return [{**paper[0].asdict()} for paper in self.papers._related_objects] def asdict(self): return {"name": self.name} class Keyword(BaseModel): __primarykey__ = "value" value = Property() papers = RelatedFrom("Paper", HAS_KEYWORD_RELATIONSHIP) def fetch(self): graph = get_graph() return Keyword.match(graph, self.value).first() def fetch_papers(self): return [{**paper[0].asdict()} for paper in self.papers._related_objects] def asdict(self): return {"value": self.value} class Project(BaseModel): __primarykey__ = "name" name = Property() papers = RelatedTo("Paper", PART_OF_RELATIONSHIP) def fetch(self): graph = get_graph() return Project.match(graph, self.name).first() def fetch_papers(self): return [{**paper[0].asdict()} for paper in self.papers._related_objects] def asdict(self): return {"name": self.name} <file_sep>import json from copy import deepcopy from unittest.mock import MagicMock, patch import pytest from mybib.graphql.access_layer import ( EntityAlreadyExistsError, insert_paper, insert_reference, ) from mybib.neo4j.models import Paper @patch("mybib.graphql.access_layer.Paper", autospec=True) @patch("mybib.graphql.access_layer.get_create_keyword", return_value=MagicMock()) @patch("mybib.graphql.access_layer.get_create_author", return_value=MagicMock()) def test_insert_paper( get_create_author_mock, get_create_keyword_mock, paper_mock, single_json_multiple_authors, ): fake_paper = MagicMock() fake_paper.fetch.return_value = None paper_mock.return_value = fake_paper expected_insertion = deepcopy(single_json_multiple_authors) keywords = expected_insertion.pop("keywords") authors = expected_insertion.pop("authors") insert_paper(single_json_multiple_authors) assert len(get_create_keyword_mock.mock_calls) == len(keywords) assert len(get_create_author_mock.mock_calls) == len(authors) assert expected_insertion == single_json_multiple_authors paper_mock.assert_called_once_with(**expected_insertion) fake_paper.save.assert_called() @patch("mybib.graphql.access_layer.Paper", autospec=True) @patch("mybib.graphql.access_layer.get_create_keyword", return_value=MagicMock()) @patch("mybib.graphql.access_layer.get_create_author", return_value=MagicMock()) def test_insert_paper_fails( get_create_author_mock, get_create_keyword_mock, paper_mock, single_json_multiple_authors, ): fake_paper = MagicMock() fake_paper.fetch.return_value = Paper(ID="ID1") paper_mock.return_value = fake_paper expected_insertion = deepcopy(single_json_multiple_authors) expected_insertion.pop("keywords") expected_insertion.pop("authors") with pytest.raises(EntityAlreadyExistsError): insert_paper(single_json_multiple_authors) get_create_author_mock.assert_not_called() get_create_keyword_mock.assert_not_called() paper_mock.assert_called_once_with(**expected_insertion) fake_paper.save.assert_not_called() @patch("mybib.graphql.access_layer.Paper.fetch") @patch("mybib.graphql.access_layer.are_related", return_value=False) def test_insert_reference_succeeds(are_related_mock, fetch_mock): referee_mock = MagicMock() referenced_mock = MagicMock() fetch_mock.side_effect = [referee_mock, referenced_mock] id1 = "id1" id2 = "id2" expected = {"a": "reference"} insert_reference(id1, id2, expected) are_related_mock.assert_called_once_with(id1, id2) referee_mock.references.add.assert_called_once_with(referenced_mock, expected) @patch("mybib.graphql.access_layer.Paper.fetch") @patch("mybib.graphql.access_layer.are_related", return_value=True) def test_insert_reference_fails_already_exists(are_related_mock, fetch_mock): referee_mock = MagicMock() referenced_mock = MagicMock() fetch_mock.side_effect = [referee_mock, referenced_mock] id1 = "id1" id2 = "id2" expected = {"a": "reference"} with pytest.raises(EntityAlreadyExistsError): insert_reference(id1, id2, expected) are_related_mock.assert_called_once_with(id1, id2) referee_mock.references.add.assert_not_called() @patch("mybib.graphql.access_layer.Paper.fetch") @patch("mybib.graphql.access_layer.are_related", side_effect=AssertionError()) def test_insert_reference_fails_reference_does_not_exist(are_related_mock, fetch_mock): referee_mock = MagicMock() referenced_mock = MagicMock() fetch_mock.side_effect = [referee_mock, referenced_mock] id1 = "id1" id2 = "id2" expected = {"a": "reference"} with pytest.raises(AssertionError): insert_reference(id1, id2, expected) are_related_mock.assert_called_once_with(id1, id2) referee_mock.references.add.assert_not_called() <file_sep>from copy import deepcopy from unittest.mock import patch from mybib.graphql.access_layer import EntityAlreadyExistsError @patch("mybib.web.api.papers.insert_paper", autospec=True) def test_post_inserts( insert_paper_mock, authenticated_post, bibtex_json_multiple_authors ): bibtex_multiple_authors, json_multiple_authors = bibtex_json_multiple_authors insert_paper_mock.return_value = json_multiple_authors entries = deepcopy(json_multiple_authors) inserted_paper = entries[0] inserted_paper["_bibtex"] = bibtex_multiple_authors response = authenticated_post("/api/papers", data=bibtex_multiple_authors) insert_paper_mock.assert_called_once_with(inserted_paper) assert response.status_code == 201 @patch("mybib.web.api.papers.insert_paper", autospec=True) def test_post_inserts_already_exist( insert_paper_mock, authenticated_post, bibtex_json_multiple_authors ): bibtex_multiple_authors, json_multiple_authors = bibtex_json_multiple_authors insert_paper_mock.side_effect = EntityAlreadyExistsError() entries = deepcopy(json_multiple_authors) inserted_paper = entries[0] inserted_paper["_bibtex"] = bibtex_multiple_authors response = authenticated_post("/api/papers", data=bibtex_multiple_authors) insert_paper_mock.assert_called_once_with(inserted_paper) assert response.status_code == 409 <file_sep>import bibtexparser from mybib.bibtext.record_customization import _customize def get_parser(): parser = bibtexparser.bparser.BibTexParser() parser.customization = _customize return parser def load_from_string(bibtex_text): return bibtexparser.loads(bibtex_text, parser=get_parser()).entries <file_sep>PIPENV := pipenv run BLACK_TARGETS := $(shell find . -name "*.py" -not -path "*/.venv/*" -not -path "*/.tox/*") MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) CURRENT_DIR := $(notdir $(patsubst %/,%,$(dir $(MAKEFILE_PATH)))) .EXPORT_ALL_VARIABLES: PIPENV_VENV_IN_PROJECT = 1 experiment: $(PIPENV) jupyter .PHONY: experiment create_env: pipenv install --dev .PHONY: create_env run_tests: PYTHONPATH=. $(PIPENV) pytest --cov=mybib --cov-report html:htmlcov test/ .PHONY: run_tests format: $(PIPENV) isort --apply $(PIPENV) black $(BLACK_TARGETS) .PHONY: format lint: $(PIPENV) black --check $(BLACK_TARGETS) .PHONY: lint <file_sep>from flask import Blueprint, jsonify, request from mybib.bibtext.reader import load_from_string from mybib.graphql.access_layer import EntityAlreadyExistsError from mybib.graphql.access_layer import get_paper as get_paper_da from mybib.graphql.access_layer import insert_paper from mybib.web.authentication import requires_auth papers_api = Blueprint("papers_api", __name__) @papers_api.route("/api/papers/<paper_id:identifier>", methods=["GET"]) def get_paper(identifier): return jsonify(get_paper_da(identifier)) @papers_api.route("/api/papers", methods=["POST"]) @requires_auth def post_paper(): bibtex_text = request.data.decode("utf-8") [paper_dict] = load_from_string(bibtex_text) paper_dict["_bibtex"] = bibtex_text response = jsonify() try: insert_paper(paper_dict) response.status_code = 201 response.autocorrect_location_header = False except EntityAlreadyExistsError: response.status_code = 409 response.headers["location"] = f"/api/papers/{paper_dict['ID']}" return response @papers_api.route("/api/papers/search", methods=["GET"]) def search_papers(): title = request.args["title"] res = None return jsonify(res) <file_sep>from flask import Blueprint, jsonify, request from mybib.graphql.access_layer import EntityAlreadyExistsError, insert_reference from mybib.web.authentication import requires_auth references_api = Blueprint("references_api", __name__) @references_api.route( "/api/references/<paper_id:referee>/<paper_id:referenced>", methods=["POST"] ) @requires_auth def post_reference(referee, referenced): attr_dict = request.get_json() response = jsonify() try: insert_reference(referee, referenced, attr_dict) response.status_code = 201 response.headers["location"] = f"/api/references/{referee}/{referenced}" response.autocorrect_location_header = False except AssertionError: response.status_code = 400 except EntityAlreadyExistsError as ae: response.status_code = 409 response.headers["location"] = f"/api/references/{referee}/{referenced}" return response <file_sep>[[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] "py2neo" = "*" bibtexparser = "*" flask = "*" flask-graphql = "*" graphene = "*" gunicorn = "*" [dev-packages] black = "==19.3b0" docker-compose = "*" isort = "*" pytest = "*" pytest-cov = "*" [requires] python_version = "3.6"
a0525892ca3ae091f8199139b181b5b73b10b1d7
[ "YAML", "JavaScript", "Markdown", "TOML", "Makefile", "Python", "Dockerfile" ]
24
Python
fferegrino/mybib
7f2530b45b462464cded9f33904de5eb4cb4213a
e5e181456c24b6c8e5b0bf0981c6499d5491c58f
refs/heads/master
<file_sep>var React = require('react'); var Backbone = require('backbone'); var $ = require('jquery'); var User = require('../models/user').User; var Student = require('../models/students').Student; var StudentCollection = require('../models/students').StudentCollection; // Second Parent form On-Off toggle var isDefined = function(val) { return val != null; } var ToggleDisplay = React.createClass({ propTypes: { hide: React.PropTypes.bool, show: React.PropTypes.bool }, shouldHide: function() { var shouldHide; if(isDefined(this.props.show)) { shouldHide = !this.props.show; } else if(isDefined(this.props.hide)) { shouldHide = this.props.hide; } else { shouldHide = false; } return shouldHide; }, render: function() { var style = {}; if(this.shouldHide()) { style.display = 'none'; } return ( <span style={style} {...this.props} /> ); } }); // Student selection and Primary Parent form var Signup = React.createClass({ getInitialState: function(){ return { show: true, student: '', school: '', grade: '', gender: '', username: '', password: '', firstname1: '', lastname1: '', street1: '', city1: '', state1: '', zip1: '', phone1: '', email1: '', firstname2: '', lastname2: '', street2: '', city2: '', state2: '', zip2: '', phone2: '', email2: '', // studentList: new StudentCollection, }; }, componentWillMount: function(){ var self = this; // this.state.studentList.fetch().done(function(){ // self.forceUpdate(); // }); }, handleSignupSubmit: function(e){ e.preventDefault(); var self = this; var student = $('#new-student').val(); var school = $('#new-school').val(); var grade = $('#new-grade').val(); var gender = $('#new-gender').val(); var username = $('#new-username').val(); var password = $('#new-password').val(); var firstname1 = $('#new-firstname1').val(); var lastname1 = $('#new-lastname1').val(); var street1 = $('#new-street1').val(); var city1 = $('#new-city1').val(); var state1 = $('#new-state1').val(); var zip1 = $('#new-zip1').val(); var phone1 = $('#new-phone1').val(); var email1 = $('#new-email1').val(); var firstname2 = $('#new-firstname2').val(); var lastname2 = $('#new-lastname2').val(); var street2 = $('#new-street2').val(); var city2 = $('#new-city2').val(); var state2 = $('#new-state2').val(); var zip2 = $('#new-zip2').val(); var phone2 = $('#new-phone2').val(); var email2 = $('#new-email2').val(); var user = new User(); user.set({'student': student, 'school': school, 'grade': grade, 'gender': gender, 'username': username, 'password': <PASSWORD>, 'firstname1': firstname1, 'lastname1': lastname1, 'street1': street1, 'city1': city1, 'state1': state1, 'zip1': zip1, 'phone1': phone1, 'email1': email1, 'firstname2': firstname2, 'lastname2': lastname2, 'street2': street2, 'city2': city2, 'state2': state2, 'zip2': zip2, 'phone2': phone2, 'email2': email2}); user.save().done(function(){ self.props.router.navigate('login/', {trigger: true}) }).fail(function(){ alert('Inproper Sign Up. Check your email address and/or password.') }); }, handleClick: function() { this.setState({ show: !this.state.show }); }, render: function(){ return ( <div> <div className="col-xs-offset-1 col-xs-10 col-md-offset-2 col-md-8"> <div className="icon-third"><a href="#login/"><img src="images/PoolParty_purplelog.png"></img></a></div> <div> <h1 id="page-title">Register to join Pool Party</h1> </div> <div className="sect-sep"> <p>This is copy that instructs on how to register as a new user in Pool Party. You must know your child’s current school. Registration will require name, address, phone, and confirmation via email link provided.</p> </div> </div> <form onSubmit={this.handleSignupSubmit}> <div className="col-xs-offset-1 col-xs-10 col-md-offset-2 col-md-8"> <div> <h2><img src="./images/security.png" className="panel-art" />First, create your user name & password</h2> </div> <div className="row form-group"> <div className="col-sm-4"> <input type="username" className="form-control" id="new-username" placeholder="User Name" /> </div> <div className="col-sm-4"> <input type="<PASSWORD>" className="form-control" id="new-password" placeholder="<PASSWORD>" /> </div> </div> <div className="sect-sep"></div> <div> <h2><img src="./images/schoolhands.png" className="panel-art" />..then provide your child’s information</h2> </div> <div className="row form-group"> <div className="col-sm-4"> <input type="student" className="form-control" id="new-student" placeholder="Child’s full name..." /> </div> <div className="col-sm-4"> <select type="school" className="form-control" id="new-school"> <option value=''>School</option> <option value="" disabled>–– Elementary Schools ––</option> <option>Bell’s Crossing Elementary School</option> <option>Bethel Elementary School</option> <option>Bryson Elementary School</option> <option>Mauldin Elementary School</option> <option>Oakview Elementary School</option> <option>Rudolf Gordon Elementary School</option> <option value="" disabled>–– Middle Schools ––</option> <option>Beck Academy School</option> <option>Bryson Academy School</option> <option>Hillcrest Middle School</option> <option>League Academy School</option> <option>Mauldin Middle School</option> <option>Northwood Middle School</option> <option>Ralph Chandler Middle School</option> <option value="" disabled>–– High Schools ––</option> <option>Berea High School</option> <option>Eastside High School</option> <option>Greenville High School</option> <option>Hillcrest High School</option> <option>J.L. Mann High School</option> <option>Mauldin High School</option> <option>Riverside High School</option> <option>Travelers Rest High School</option> <option>Wade Hampton High School</option> </select> </div> <div className="col-sm-2"> <select type="grade" className="form-control" id="new-grade"> <option>Grade</option> <option>12</option> <option>11</option> <option>10</option> <option>9</option> <option>8</option> <option>7</option> <option>6</option> <option>5</option> <option>4</option> <option>3</option> <option>2</option> <option>1</option> </select> </div> <div className="col-sm-2"> <select type="gender" className="form-control" id="new-gender"> <option>Gender</option> <option>F</option> <option>M</option> </select> </div> </div> <div className="sect-sep"></div> <div className="row"> <h2><img src="./images/parents.png" className="panel-art" />Primary Parent’s Information:</h2> <div className="col-md-10"> <div className="form-group col-xs-6 col-md-6"> <label htmlFor="new-firstname1" className="control-label">First Name</label> <input type="text" className="form-control" id="new-firstname1" placeholder="First name..." /> </div> <div className="form-group col-xs-6 col-md-6"> <label htmlFor="new-lastname1" className="control-label">Last Name</label> <input type="text" className="form-control" id="new-lastname1" placeholder="Last name..." /> </div> <div className="form-group col-xs-12"> <label htmlFor="new-street1" className="control-label">Street Address</label> <input type="text" className="form-control" id="new-street1" placeholder="Street address (no P.O. Box)" /> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-city1" className="control-label">City</label> <input type="text" className="form-control" id="new-city1" placeholder="City..." /> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-state1" className="control-label">State</label> <select type="text" className="form-control" id="new-state1"> <option>Select...</option> <option value="AK">Alaska</option> <option value="AL">Alabama</option> <option value="AR">Arkansas</option> <option value="AZ">Arizona</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DC">District of Columbia</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="IA">Iowa</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="MA">Massachusetts</option> <option value="MD">Maryland</option> <option value="ME">Maine</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MO">Missouri</option> <option value="MS">Mississippi</option> <option value="MT">Montana</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="NE">Nebraska</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NV">Nevada</option> <option value="NY">New York</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="PR">Puerto Rico</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VA">Virginia</option> <option value="VT">Vermont</option> <option value="WA">Washington</option> <option value="WI">Wisconsin</option> <option value="WV">West Virginia</option> <option value="WY">Wyoming</option> </select> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-zip1" className="control-label">Zip Code</label> <input type="text" className="form-control" id="new-zip1" placeholder="00000" /> </div> <div className="form-group col-xs-6"> <label htmlFor="new-phone1" className="control-label">Primary Phone</label> <input type="text" className="form-control" id="new-phone1" placeholder="000-000-0000" /> </div> <div className="form-group col-xs-6"> <label htmlFor="new-email1" className="control-label">Email</label> <input type="email" className="form-control" id="new-email1" placeholder="<EMAIL>" /> </div> <button type="button" className="btn btn-info btn-sm pull-right" onClick={ this.handleClick }>Add Secondary Parent <span className="glyphicon glyphicon-plus-sign" /></button> </div> </div> <div className="row"> <ToggleDisplay show={this.state.show}></ToggleDisplay> <ToggleDisplay hide={this.state.show}> <h2><img src="./images/parents2.png" className="panel-art" />Secondary Parent’s Information:</h2> <div className="col-md-10"> <div className="form-group col-xs-6 col-md-6"> <label htmlFor="new-firstname2" className="control-label">First Name</label> <input type="text" className="form-control" id="new-firstname2" placeholder="First name..." /> </div> <div className="form-group col-xs-6 col-md-6"> <label htmlFor="new-lastname2" className="control-label">Last Name</label> <input type="text" className="form-control" id="new-lastname2" placeholder="Last name..." /> </div> <div className="form-group col-xs-12"> <label htmlFor="new-street2" className="control-label">Street Address</label> <input type="text" className="form-control" id="new-street2" placeholder="Street address (no P.O.)..." /> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-city2" className="control-label">City</label> <input type="text" className="form-control" id="new-city2" placeholder="City..." /> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-state2" className="control-label">State</label> <select type="text" className="form-control" id="new-state2"> <option>Select...</option> <option value="AK">Alaska</option> <option value="AL">Alabama</option> <option value="AR">Arkansas</option> <option value="AZ">Arizona</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DC">District of Columbia</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="IA">Iowa</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="MA">Massachusetts</option> <option value="MD">Maryland</option> <option value="ME">Maine</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MO">Missouri</option> <option value="MS">Mississippi</option> <option value="MT">Montana</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="NE">Nebraska</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NV">Nevada</option> <option value="NY">New York</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="PR">Puerto Rico</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VA">Virginia</option> <option value="VT">Vermont</option> <option value="WA">Washington</option> <option value="WI">Wisconsin</option> <option value="WV">West Virginia</option> <option value="WY">Wyoming</option> </select> </div> <div className="form-group col-xs-4 col-md-4"> <label htmlFor="new-zip2" className="control-label">Zip Code</label> <input type="text" className="form-control" id="new-zip2" placeholder="00000" /> </div> <div className="form-group col-xs-6"> <label htmlFor="new-phone2" className="control-label">Primary Phone</label> <input type="text" className="form-control" id="new-phone2" placeholder="000-000-0000" /> </div> <div className="form-group col-xs-6"> <label htmlFor="new-email2" className="control-label">Email</label> <input type="email" className="form-control" id="new-email2" placeholder="<EMAIL>" /> </div> </div> </ToggleDisplay> </div> <div className="row col-md-8"> <button type="submit" className="btn btn-success">Register</button> </div> </div> </form> </div> ) } }); module.exports = Signup; <file_sep>## D9 Final Project My Final Project is the development of Pool Party, a do-it-yourself car pool signup application. Designed for parents of school students in the area, it allows you to have an online location to create or join groups of other parents who have kids that are friends and/or in the same school as your children, and wish to participate in a car pool together. The application will allow you to sign up, then sign in to initially create your group. This group provides the name of students, their parents, and their address so you can decide whose convenient to your location, for example. Then your login page will be a central spot for seeing the members of your group with their contact information, as well as an area showing the weekly driving schedule. There's also a convenient comment area to discuss with other parents topics like switching days or weeks, or perhaps whose child is sick and should not be picked up. The Pool Party app is developed in React with various components that include a sign up form, login authentication and logout, student list selection for creating a group, and the displaying of group information of individual records ("student members"). The app is responsive and can be further modified to accurately display as a mobile app later. Future development will include the online modifying of the schedule, the editing of Groups (to remove members no longer wishing to be in it), the automation of email confirmation to activate the Group and notify its members, and eventually in the mobile version, the ability to GPS track pick up & drop off routes for parents as well as automated text messages when your child has arrived at school. ## Steps: 1. At Welcome page, click on "Click here" link in either intro copy or under login form for new signups. 2. At Sign Up page, fill out form completely (2nd parent is optionanl) and submit. 3. Upon return to Welcome page, insert your Username and Password on the login form. (FYI, parse server is slow and sometimes takes time to register new user...give it 5 minutes to be sure.) 4. Initial login will take you to Group setup page. Select names of 4 students you'd like to be in your group and hit Create Group. 5. Upon creating group, you'll be directed to Schedules page which lists your group and its members, shows weekly schedule, and has discussion area to post comments. <file_sep>var React = require('react'); var Backbone = require('backbone'); var $ = require('jquery'); var User = require('../models/user').User; var Welcome = React.createClass({ getInitialState: function(){ return { }; }, componentWillMount: function(){ var self = this; }, handleLoginSubmit: function(e){ e.preventDefault(); var self = this; var username = $('#username').val(); var password = $('#<PASSWORD>').val(); User.login(username, password, { success: function(response){ self.props.router.navigate('schedules/', {trigger: true}); }, fail: function(response){ alert('Login failed. Please check user name or password.'); } }); localStorage.setItem('username', username) }, render: function(){ return ( <div> <div className="welc-area col-md-offset-1 col-md-10"> <div className="welc-box-b"> <div className="welc-logo"> <div className="icon-lrg"> <img src="images/PoolParty_purplelogtag.png"></img> </div> <div className="log-copy"> <p>Welcome to the app that makes it easy to create and join a school car pool for your little students! Here’s <a href="#B">how it works...</a></p> <p><a href="#signup/">Click here</a> if you’re wanting to join!</p> </div> </div> </div> <div className="welc-box-a"> <div className="welc-login"> <div> <h3 id="form-title">Log In...</h3> </div> <form onSubmit={this.handleLoginSubmit}> <label htmlFor="username">User Name</label> <input type="username" className="form-control log-entry" id="username" placeholder="Enter your user name"></input> <label htmlFor="<PASSWORD>">Password</label> <input type="<PASSWORD>" className="form-control log-entry" id="password" placeholder="Enter <PASSWORD>"></input> <input type="submit" className="btn btn-success btn-sm" value="Login"></input> </form> <div className="open-links">Not signed up yet? <a href="#signup/">Click here</a> </div> </div> </div> <div className="welc-box-a"> <div className="welc-info"> <a name="B" /><p>One of the hardest aspects of your children attending school is getting them there and back! Often, there is no easy way for you personally to transport them, and even harder to find other parents who might have interest in a car pool to lessen the daily commitment.</p> <p>That’s where Pool Party comes in.</p> <p>With Pool Party, you just sign up by telling us some brief information about you & your child, their school, and then we send you an invitation to register and get started.</p> <p>Within no time, you can create your own car pool group, have a schedule set up, and be provided with directions on where each Group member lives…and all based on the school your child attends and convenience to where you live.</p> <p>So sign up today and we’ll provide you with information on how to quickly become a member of your own car pool!</p> <p>Let’s get this Pool Party started!</p> </div> </div> <div className="welc-box-b"> <div className="welc-art"> <img className="img-responsive" src="./images/welcome.png" /> </div> </div> </div> </div> ) } }); module.exports = Welcome; <file_sep>var React = require('react'); var ReactDOM = require('react-dom'); var $ = require('jquery'); var StudentCollection = require('../models/students').StudentCollection; var Group = require('../models/groups').Group; var GroupSetup = React.createClass({ getInitialState: function(){ return { studentList: new StudentCollection(), kidsGroup: new Group(), }; }, componentWillMount: function(){ var self = this; this.state.studentList.fetch().done(function(){ self.forceUpdate(); }); }, onRowSelect: function(row, isSelected){ console.log(row); console.log("selected: " + isSelected) }, onSelectAll: function(isSelected){ console.log("is select all: " + isSelected); }, onSubmit: function(e){ e.preventDefault(); var router = this.props.router; var kidsGroup = this.state.kidsGroup; var selectGroup = []; var user = JSON.parse(localStorage.getItem('user')); $("#groupTable input:checkbox:checked").map(function(){ var row = $(this).closest('tr'); var studentItem = $(row).find('.thisStudent').html(); var schoolItem = $(row).find('.thisSchool').html(); var firstName1Item = $(row).find('.thisFirstName1').html(); var lastName1Item = $(row).find('.thisLastName1').html(); var street1Item = $(row).find('.thisStreet1').html(); var city1Item = $(row).find('.thisCity1').html(); var state1Item = $(row).find('.thisState1').html(); var zip1Item = $(row).find('.thisZip1').html(); var email1Item = $(row).find('.thisEmail1').html(); var phone1Item = $(row).find('.thisPhone1').html(); selectGroup.push([studentItem, schoolItem, firstName1Item, lastName1Item, street1Item, city1Item, state1Item, zip1Item, email1Item, phone1Item]); }); console.log(selectGroup); kidsGroup.set('myGroup', selectGroup); kidsGroup.setPointer('user', user, '_User'); kidsGroup.save().done(function(){ router.navigate('schedules/', {trigger: true}); }); }, render: function(){ var user = JSON.parse(localStorage.getItem('user')); var chooseStudent = this.state.studentList; var eachStudent = chooseStudent.map(function(student, index){ return ( <tr key={index}> <td align="center"> <input type="checkbox" className="case" name="case" value={index} /> </td> <td className="thisStudent">{student.get('student')}</td> <td className="thisSchool">{student.get('school')}</td> <td>{student.get('grade')}</td> <td>{student.get('gender')}</td> <td className="thisFirstName1">{student.get('firstname1')}</td> <td className="thisLastName1">{student.get('lastname1')}</td> <td className="thisPhone1">{student.get('phone1')}</td> <td className="thisEmail1">{student.get('email1')}</td> <td className="thisStreet1">{student.get('street1')}</td> <td className="thisCity1">{student.get('city1')}</td> <td className="thisState1">{student.get('state1')}</td> <td className="thisZip1">{student.get('zip1')}</td> </tr> ) }) return ( <div> <div className="col-xs-offset-1 col-xs-10 col-md-offset-2 col-md-8"> < NavTitle /> <div><h1 id="page-title">Welcome, {user.firstname1}!</h1></div> <div className="sect-sep"> <p>Now that you’re a Pool Party member, let’s start with creating a Group. The Students you’ll see listed below live within a 2-mile radius of your home. This makes it convenient for both them and you to join together.</p> </div> <div className="row"> <div> <div className="subtitle"><h2><img src="./images/group.png" className="panel-art"/>Create A Group!</h2></div> <div className="panel-body"> <p>Select from the eligible students shown to form your potential car pool group. Do not select more than 4 potential students; Groups cannot consist of more than 5 members. Students with the name crossed through have already joined a group.</p> <p>Once you’ve selected your group, name the group below. Then click the Create button. An email will be sent to each student’s parent(s) informing them of your wish to have them join your car pool. You will be notified once they have confirmed their participation.</p> </div> <div className="well tableScroll table-responsive"> <table border="1" className="table table-striped" id="groupTable"> <thead> <tr> <th>Select</th> <th>Student</th> <th>School</th> <th>Grade Level</th> <th>Gender</th> <th>Parent Name</th> <th>Parent Last</th> <th>Phone</th> <th>Email</th> <th>Street</th> <th>City</th> <th>State</th> <th>Zip Code</th> </tr> </thead> <tbody>{eachStudent}</tbody> </table> </div> </div> <div> <button id="submitButton" type="submit" className="btn btn-success btn-sm" onClick={this.onSubmit}>Create Group</button> </div> </div> </div> </div> ) } }); var NavTitle = React.createClass({ handleSignOut: function(){ localStorage.clear(); }, render: function(){ var user = JSON.parse(localStorage.getItem('user')); return ( <div className="row"> <div className="col-xs-12"> <div className="pull-right"> <div className="row active-user"> <span className="glyphicon glyphicon-user" aria-hidden="true"></span> <h5>{user.username}</h5> <div className="active-btn btn btn-sm btn-link" onClick={this.handleSignOut}> <a href="#" className="sign-out">Sign Out</a> </div> </div> </div> <div> <div className="icon-third"><a href="#"><img src="images/PoolParty_purplelog.png"></img></a></div> </div> </div> </div> ) } }); module.exports = { 'GroupSetup': GroupSetup, }; // var GroupPop = React.createClass({ // groupShare: function() { // window.open('', 'sharer', 'toolbar=0,status=0,width=640,height=480'); // }, // render: function(){ // return ( // <div> // <button id="submitButton" type="submit" className="btn btn-success btn-sm pull-right" onClick={this.groupShare}>Create Group</button> // </div> // ); // } // }); // // var onRowSelect; // var onSelectAll; // var selectRowProp = { // mode: "checkbox", // clickToSelect: true, // bgColor: "#FFC469", // onSelect: onRowSelect, // onSelectAll: onSelectAll // }; // // var GroupSelect = React.createClass({ // getInitialState: function(){ // return { // router // }; // }, // componentWillMount: function(){ // var self = this; // }, // render: function(){ // return ( // <div> // <h2>Here’s you Group!</h2> // <div> // <p>Now that you’ve set up your Group, be sure to confirm the students you selected and give your Group a name. If you wish to change your selection, click on the Edit button below.</p> // </div> // </div> // ) // } // }); // <div> // <BootstrapTable className="table" id="table" data={data} height="280" selectRow={selectRowProp} striped={true} hover={true} condensed={true}> // <TableHeaderColumn dataField="studentName" isKey={true} dataSort={true} className="td-header-group">Students Eligible</TableHeaderColumn> // <TableHeaderColumn dataField="studentSchool" dataAlign="center" className="td-header-group">School</TableHeaderColumn> // <TableHeaderColumn dataField="studentGrade" dataAlign="center" className="td-header-group">Grade Level</TableHeaderColumn> // <TableHeaderColumn dataField="studentGender" dataAlign="center" className="td-header-group">Gender</TableHeaderColumn> // </BootstrapTable> // </div> <file_sep>var React = require('react'); var ReactDOM = require('react-dom'); var Backbone = require('backbone'); var Welcome = require('./components/welcome.jsx'); var Login = require('./components/login.jsx'); var Signup = require('./components/signup.jsx'); var GroupSetup = require('./components/group-setup.jsx').GroupSetup; var MapSchedule = require('./components/map.jsx').MapSchedule; var User = require('./models/user').User; var CommentBox = require('./components/comments.jsx').CommentBox; var Router = Backbone.Router.extend({ routes: { '': 'welcomeController', 'index': 'welcomeController', 'login/': 'loginController', 'signup/': 'signupController', 'groups/': 'groupCreate', 'schedules/': 'scheduleController', }, initialize: function(){ if (User.isAuthenticated()) { var currentParent = User.restore(); } }, welcomeController: function(){ var self = this; ReactDOM.render( React.createElement(Welcome, {router: self}), document.getElementById('container') ) }, loginController: function(){ var self = this; ReactDOM.render( React.createElement(Login, {router: self}), document.getElementById('container') ) }, signupController: function(){ var self = this; ReactDOM.render( React.createElement(Signup, {router: self}), document.getElementById('container') ); }, groupCreate: function(){ var self = this; ReactDOM.render( React.createElement(GroupSetup, {router: self}), document.getElementById('container') ); }, scheduleController: function(){ var self = this; ReactDOM.render( React.createElement(MapSchedule, {router: self}), document.getElementById('container') ); }, CommentBox: function(){ var self = this; ReactDOM.render( React.createElement(CommentBox, {router: self}), document.getElementById('container') ); }, }); var router = new Router(); module.exports = router; <file_sep>var Backbone = require('backbone'); var PointerFieldModel = Backbone.Model.extend({ setPointer: function(field, obj, className){ this.set(field, {'__type': 'Pointer', 'className': className, 'objectId': obj.objectId}); } }); var Group = PointerFieldModel.extend({ defaults: { myGroup: [] }, idAttribute: "objectId", urlRoot: "https://d9-dev-server.herokuapp.com/classes/D9groups" }); var GroupCollection = Backbone.Collection.extend({ model: Group, url: "https://d9-dev-server.herokuapp.com/classes/D9groups", parse: function(serverResponse){ return serverResponse.results; } }); module.exports = { 'Group': Group, 'GroupCollection': GroupCollection } <file_sep>var Backbone = require('backbone'); var Student = Backbone.Model.extend({ idAttribute: 'objectId', urlRoot: "https://d9-dev-server.herokuapp.com/classes/_User", }); var StudentCollection = Backbone.Collection.extend({ model: Student, url: "https://d9-dev-server.herokuapp.com/classes/_User", parse: function(serverResponse){ return serverResponse.results; } }); module.exports = { 'Student': Student, 'StudentCollection': StudentCollection };
f028db4166642525f36bc2b448ec5a7f578cbbe1
[ "JavaScript", "Markdown" ]
7
JavaScript
pairof9s/TIY_Final_Project_Live
ca8632f521334f8ac4cb6b30504143184b5df86a
e661c1329240bd8402a4f266d00ba871ac05df84
refs/heads/master
<file_sep>require File.dirname(__FILE__) + '/spec_helper' describe Palindrome do it "finds the reverse of 12" do 12.reverse.should == 21 end it "finds the reverse of 123456789" do 123456789.reverse.should == 987654321 end it "determines if a number is palindromic" do 121.should be_palindromic end it "determines if a number is NOT palindromic" do 123.should_not be_palindromic end it "finds the palindrome of 47" do 47.palindrome.should == 121 end it "finds the palindrome of 349" do 349.palindrome.should == 7337 end it "does NOT find the palindrome of 196" do 196.palindrome.should be_nil end it "determines if a number is lychrel" do 196.should be_lychrel end it "determines if a number is NOT lychrel" do 121.should_not be_lychrel end end<file_sep>require 'rubygems' require 'spec' require File.join( File.dirname(__FILE__), *%w[ .. lib palindrome ] )<file_sep>Palindrome ---------- A number that never forms a palindrome through the reverse and add process is called a Lychrel number. **How many Lychrel numbers are there below ten-thousand?** $ ruby run.rb 246<file_sep>module Palindrome def lychrel? !self.palindrome end def palindrome max_tries = 50 result = self tries = 0 until result.palindromic? return nil if tries >= max_tries result += result.reverse tries += 1 end result end def palindromic? self == self.reverse end def reverse self.to_s.reverse.to_i end end class Integer include Palindrome end<file_sep>require File.dirname(__FILE__) + '/lib/palindrome' puts (1..10000).inject(0) { |sum, i| i.lychrel? ? sum += 1 : sum }
1ec60be6f48aa233c02dbac05503819df0a7d9a7
[ "Markdown", "Ruby" ]
5
Ruby
mattpuchlerz/palindrome
c569cde804b254fe72fe2f24c7e33d2a30bbc514
9efb2dd2754ecca06ed202a5074530e420d7c8cb
refs/heads/master
<repo_name>FlorianLeChat/darkrp_scripts<file_sep>/README.md # darkrp_scripts Github version of all my workshop addons : https://steamcommunity.com/id/florian4016/myworkshopfiles/?appid=4000 <file_sep>/ooc_disabler/lua/autorun/ooc_disabler.lua -- [[ SETTINGS ]] -- -- What the name of this command ? (Default : "ooccontrol") local command_name = "ooccontrol" -- What is the delay for DarkRP anti-spam command ? (Default : 1.5) local command_delay = 1.5 -- Admins can always use ooc when is disabled ? (Default : true) local admin_can_always_use_ooc = true -- [[ CODE WORK ]] -- function OOC_Disabler_GamemodeCheck() if _G.DarkRP then if SERVER then -- OOC CONTROL COMMAND local function OOC_CONTROL(ply) local pname = ply:Nick() if ply:IsAdmin() then if GAMEMODE.Config.ooc then GAMEMODE.Config.ooc = false DarkRP.notifyAll(0, 5, "OOC was disabled by " .. pname .. " !") else GAMEMODE.Config.ooc = true DarkRP.notifyAll(0, 5, "OOC was enabled by " .. pname .. " !") end else DarkRP.notify("You're not authorized to execute this command.") end return "" end DarkRP.defineChatCommand(command_name, OOC_CONTROL) -- OOC COMMAND MODIFICATION if admin_can_always_use_ooc then local function OOC(ply, args) if not GAMEMODE.Config.ooc and not ply:IsAdmin() then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("disabled", DarkRP.getPhrase("ooc"), "")) return "" end local DoSay = function(text) if text == "" then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", "")) return "" end local col = team.GetColor(ply:Team()) local col2 = Color(255, 255, 255, 255) if not ply:Alive() then col2 = Color(255, 200, 200, 255) col = col2 end local phrase = DarkRP.getPhrase("ooc") local name = ply:Nick() for _, v in ipairs(player.GetAll()) do DarkRP.talkToPerson(v, col, "(" .. phrase .. ") " .. name, col2, text, ply) end end return args, DoSay end DarkRP.defineChatCommand("/", OOC, true, 1.5) DarkRP.defineChatCommand("a", OOC, true, 1.5) DarkRP.defineChatCommand("ooc", OOC, true, 1.5) end end DarkRP.declareChatCommand{ command = command_name, description = "Enable or disable OOC.", delay = command_delay } else timer.Create("OOC_Disabler.GamemodeInitError", 30, 0, function() for _, v in ipairs(player.GetAll()) do if IsValid(v) then v:ChatPrint("'OOC Disabler' not loaded because he only work with DarkRP or derived !") end end end) end end hook.Add("OnGamemodeLoaded", "OOC_Disabler_GamemodeCheck", OOC_Disabler_GamemodeCheck) concommand.Add("oocdisaber_check", function(ply) ply:ChatPrint("This server use 'OOC Disabler' script ! ( https://steamcommunity.com/sharedfiles/filedetails/?id=1314167955 )") end) -- Made by "The Cat" alias "Florian #" ( http://steamcommunity.com/profiles/76561198053479101 ) -- I'm french baguette.. sorry <3
112ff6dcb2e7459b2a51be317adb74a08ac9609c
[ "Markdown", "Lua" ]
2
Markdown
FlorianLeChat/darkrp_scripts
e23c9248fe81b2129a9f327ee05ac5cce24e5115
3115b2e9b49493a7c0b55ce2f99a438ce4692619
refs/heads/master
<file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\OptionsResolver\OptionsResolver; /** * Description of Client * * @author marwa */ class UserFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('firstname', TextType::class) ->add('lastname', TextType::class) ->add('email', TextType::class) ->add('username', TextType::class) ->add('password', TextType::class) ->add('phoneNumber', TextType::class) ->add('fidilityCard', TextType::class, array('mapped' => false)); } /** * Sets options as model for current form type. * * @param OptionsResolverInterface $resolver The resolver instance. * * @return void */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'csrf_protection' => false, )); } public function getName() { return ""; } } <file_sep><?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="promotion") */ class Promotion { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="datetime") */ private $beginDate; /** * @ORM\Column(type="datetime") */ private $endDate; /** * @ORM\Column(type="float") */ private $newPrice; /** * @ORM\ManyToOne(targetEntity="Product", inversedBy="promotions") * @ORM\JoinColumn(name="product_id", referencedColumnName="id") */ private $product; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set beginDate * * @param \DateTime $beginDate * * @return Promotion */ public function setBeginDate($beginDate) { $this->beginDate = $beginDate; return $this; } /** * Get beginDate * * @return \DateTime */ public function getBeginDate() { return $this->beginDate; } /** * Set endDate * * @param \DateTime $endDate * * @return Promotion */ public function setEndDate($endDate) { $this->endDate = $endDate; return $this; } /** * Get endDate * * @return \DateTime */ public function getEndDate() { return $this->endDate; } /** * Set newPrice * * @param float $newPrice * * @return Promotion */ public function setNewPrice($newPrice) { $this->newPrice = $newPrice; return $this; } /** * Get newPrice * * @return float */ public function getNewPrice() { return $this->newPrice; } /** * Set product * * @param \AppBundle\Entity\Product $product * * @return Promotion */ public function setProduct(\AppBundle\Entity\Product $product = null) { $this->product = $product; return $this; } /** * Get product * * @return \AppBundle\Entity\Product */ public function getProduct() { return $this->product; } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\View\View; use AppBundle\Entity\User; use AppBundle\Entity\Carte; use Symfony\Component\HttpKernel\Exception\HttpException; use AppBundle\Form\Type\UserFormType; use Symfony\Component\HttpFoundation\Request; /** * Description of ClientController * * @author imen */ class UserController extends FOSRestController { /** * Returns all users values. * * @return View * */ public function getUsersAction() { $data = $this->getDoctrine()->getManager()->getRepository(User::class)->findAll(); $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function getUserAction($id) { $data = $this->getDoctrine()->getManager()->getRepository(User::class)->findOneById($id); if (!$data) { throw new HttpException(404, "user with the id $id not found"); } $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function postUserAction(Request $request) { $user = new User(); $view = View::create(); $form = $this->createForm(UserFormType::class, $user, array('method' => 'POST')); try { $form->setData($user); if ('POST' === $request->getMethod()) { $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $encoder = $this->container->get('security.password_encoder'); $passwordEncoded = $encoder->encodePassword($user, $user->getPassword()); $user->setPassword($passwordEncoded); $fidilityCard = $request->get('fidilityCard'); $cart = new Carte(); $cart->setNumber($fidilityCard); $cart->setPoint(0); $cart->setDescription('bienvenue'); $user->setCarte($cart); $this->getDoctrine()->getManager()->persist($cart); $this->getDoctrine()->getManager()->persist($user); $this->getDoctrine()->getManager()->flush(); $view->setStatusCode(204); } else { $view->setStatusCode(400); $view->setData(array($form)); } } else { $view->setStatusCode(400); $view->setData(array($form)); } } catch (\Exception $ex) { throw new HttpException(500, $ex->getMessage()); } return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function putUserAction(Request $request, $id) { $user = $this->getDoctrine()->getManager()->getRepository(User::class)->findOneById($id); if (!$user) { throw new HttpException(404, "user with the id $id not found"); } $view = View::create(); $form = $this->createForm(UserFormType::class, $user, array('method' => 'PUT')); try { $form->setData($user); if ('PUT' === $request->getMethod()) { $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $encoder = $this->container->get('security.password_encoder'); $passwordEncoded = $encoder->encodePassword($user, $user->getPassword()); $user->setPassword($passwordEncoded); $this->getDoctrine()->getManager()->persist($user); $this->getDoctrine()->getManager()->flush(); $view->setStatusCode(204); } else { $view->setStatusCode(400); $view->setData(array($form)); } } else { $view->setStatusCode(400); $view->setData(array($form)); } } catch (\Exception $ex) { throw new HttpException(500, $ex->getMessage()); } return $this->get('fos_rest.view_handler')->handle($view); } public function likeUserCategoryAction($userId, $categoryId) { $user = $this->getDoctrine()->getManager()->getRepository(User::class)->findOneById($userId); if (!$user) { throw new HttpException(404, "user with the id $userId not found"); } $categorie = $this->getDoctrine()->getManager()->getRepository(\AppBundle\Entity\Categorie::class)->findOneById($categoryId); if (!$categorie) { throw new HttpException(404, "categorie with the id $categoryId not found"); } $user->addCategory($categorie); $this->getDoctrine()->getManager()->persist($user); $this->getDoctrine()->getManager()->flush(); $view = View::create(); $view->setStatusCode(204); return $this->get('fos_rest.view_handler')->handle($view); } } <file_sep><?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="product") */ class Product { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string") */ private $label; /** * @ORM\Column(type="float") */ private $price; /** * @ORM\Column(type="string") */ private $description; /** * @ORM\Column(type="string", unique=true) */ private $barCode; /** * @ORM\Column(type="string") */ private $picture; /** * @ORM\Column(type="integer") */ private $guarantee; /** * @ORM\OneToMany(targetEntity="Promotion", mappedBy="product") */ private $promotions; /** * @ORM\ManyToOne(targetEntity="Categorie", inversedBy="produits") * @ORM\JoinColumn(name="categorie_id", referencedColumnName="id") */ private $categorie; /** * Constructor */ /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Recipe", mappedBy="products") */ private $recipes; public function __construct() { $this->promotions = new \Doctrine\Common\Collections\ArrayCollection(); $this->recipes = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set label * * @param string $label * * @return Product */ public function setLabel($label) { $this->label = $label; return $this; } /** * Get label * * @return string */ public function getLabel() { return $this->label; } /** * Set price * * @param float $price * * @return Product */ public function setPrice($price) { $this->price = $price; return $this; } /** * Get price * * @return float */ public function getPrice() { return $this->price; } /** * Set description * * @param string $description * * @return Product */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set barCode * * @param string $barCode * * @return Product */ public function setBarCode($barCode) { $this->barCode = $barCode; return $this; } /** * Get barCode * * @return string */ public function getBarCode() { return $this->barCode; } /** * Set picture * * @param string $picture * * @return Product */ public function setPicture($picture) { $this->picture = $picture; return $this; } /** * Get picture * * @return string */ public function getPicture() { return $this->picture; } /** * Add promotion * * @param \AppBundle\Entity\Promotion $promotion * * @return Product */ public function addPromotion(\AppBundle\Entity\Promotion $promotion) { $this->promotions[] = $promotion; return $this; } /** * Remove promotion * * @param \AppBundle\Entity\Promotion $promotion */ public function removePromotion(\AppBundle\Entity\Promotion $promotion) { $this->promotions->removeElement($promotion); } /** * Get promotions * * @return \Doctrine\Common\Collections\Collection */ public function getPromotions() { return $this->promotions; } /** * Set categorie * * @param \AppBundle\Entity\Categorie $categorie * * @return Product */ public function setCategorie(\AppBundle\Entity\Categorie $categorie = null) { $this->categorie = $categorie; return $this; } /** * Get categorie * * @return \AppBundle\Entity\Categorie */ public function getCategorie() { return $this->categorie; } /** * Set guarantee * * @param integer $guarantee * * @return Product */ public function setGuarantee($guarantee) { $this->guarantee = $guarantee; return $this; } /** * Get guarantee * * @return integer */ public function getGuarantee() { return $this->guarantee; } /** * Add recipe * * @param \App\Entity\Recipe $recipe * * @return Product */ public function addRecipe(\AppBundle\Entity\Recipe $recipe) { $this->recipes[] = $recipe; return $this; } /** * Remove recipe * * @param \App\Entity\Recipe $recipe */ public function removeRecipe(\AppBundle\Entity\Recipe $recipe) { $this->recipes->removeElement($recipe); } /** * Get recipes * * @return \Doctrine\Common\Collections\Collection */ public function getRecipes() { return $this->recipes; } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\View\View; use AppBundle\Entity\Carte; use Symfony\Component\HttpKernel\Exception\HttpException; /** * Description of carteController * * @author imen */ class CarteController extends FOSRestController { /** * Returns all enumeration values. * * @return View * */ public function getCarteAction($number) { $data = $this->getDoctrine()->getManager()->getRepository(Carte::class)->findOneByNumber($number); if (!$data) { throw new HttpException(404, "carte with the id $number not found"); } $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="carte") */ class Carte { /** * @ORM\Id * @ORM\Column(type="integer") */ private $number; /** * @ORM\Column(type="string") */ private $description; /** * @ORM\Column(type="integer") */ private $point; /** * Set number * * @param integer $number * * @return Carte */ public function setNumber($number) { $this->number = $number; return $this; } /** * Get number * * @return integer */ public function getNumber() { return $this->number; } /** * Set description * * @param string $description * * @return Carte */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set point * * @param integer $point * * @return Carte */ public function setPoint($point) { $this->point = $point; return $this; } /** * Get point * * @return integer */ public function getPoint() { return $this->point; } } <file_sep><?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="recipe") */ class Recipe { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string") */ private $name; /** * @ORM\Column(type="string") */ private $difficult ; /** * @ORM\Column(type="string") */ private $time; /** * @ORM\Column(type="string") */ private $picture; /** * @ORM\Column(type="string") */ private $description; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Product", inversedBy="recipes", cascade={"persist"}) * @ORM\JoinTable(name="recipe_product") */ private $products; /** * Constructor */ public function __construct() { $this->products = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Recipe */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set difficult * * @param string $difficult * * @return Recipe */ public function setDifficult($difficult) { $this->difficult = $difficult; return $this; } /** * Get difficult * * @return string */ public function getDifficult() { return $this->difficult; } /** * Set time * * @param string $time * * @return Recipe */ public function setTime($time) { $this->time = $time; return $this; } /** * Get time * * @return string */ public function getTime() { return $this->time; } /** * Set picture * * @param string $picture * * @return Recipe */ public function setPicture($picture) { $this->picture = $picture; return $this; } /** * Get picture * * @return string */ public function getPicture() { return $this->picture; } /** * Set description * * @param string $description * * @return Recipe */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Add product * * @param \App\Entity\Product $product * * @return Recipe */ public function addProduct(\App\Entity\Product $product) { $this->products[] = $product; return $this; } /** * Remove product * * @param \App\Entity\Product $product */ public function removeProduct(\App\Entity\Product $product) { $this->products->removeElement($product); } /** * Get products * * @return \Doctrine\Common\Collections\Collection */ public function getProducts() { return $this->products; } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\View\View; use AppBundle\Entity\Product; use Symfony\Component\HttpKernel\Exception\HttpException; /** * Description of ClientController * * @author imen */ class ProductController extends FOSRestController { /** * Returns all users values. * * @return View * */ public function getProductsAction() { $data = $this->getDoctrine()->getManager()->getRepository(Product::class)->findAll(); $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all users values. * * @return View * */ public function getProductsWithValidPromotionAction() { $repository = $this->getDoctrine()->getManager()->getRepository(Product::class); $date = date("Y-m-d H:i:s"); $data = $repository->createQueryBuilder('p') ->join('p.promotions', 'pr') ->where(':date BETWEEN pr.beginDate AND pr.endDate') ->setParameter('date', $date) ->getQuery() ->getResult(); $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function getProductAction($id) { $data = $this->getDoctrine()->getManager()->getRepository(Product::class)->findOneById($id); if (!$data) { throw new HttpException(404, "product with the id $id not found"); } $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="categorie") */ class Categorie { //put your code here /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string") */ private $description; /** * @ORM\OneToMany(targetEntity="Product", mappedBy="categorie") */ private $produits; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User", mappedBy="categories") */ private $users; /** * Constructor */ public function __construct() { $this->produits = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set description * * @param string $description * * @return Categorie */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set picture * * @param string $picture * * @return Categorie */ /** * Add produit * * @param \AppBundle\Entity\Product $produit * * @return Categorie */ public function addProduit(\AppBundle\Entity\Product $produit) { $this->produits[] = $produit; return $this; } /** * Remove produit * * @param \AppBundle\Entity\Product $produit */ public function removeProduit(\AppBundle\Entity\Product $produit) { $this->produits->removeElement($produit); } /** * Get produits * * @return \Doctrine\Common\Collections\Collection */ public function getProduits() { return $this->produits; } /** * Add user * * @param \AppBundle\Entity\User $user * * @return Categorie */ public function addUser(\AppBundle\Entity\User $user) { $this->users[] = $user; return $this; } /** * Remove user * * @param \AppBundle\Entity\User $user */ public function removeUser(\AppBundle\Entity\User $user) { $this->users->removeElement($user); } /** * Get users * * @return \Doctrine\Common\Collections\Collection */ public function getUsers() { return $this->users; } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\View\View; use AppBundle\Entity\Recipe; use Symfony\Component\HttpKernel\Exception\HttpException; /** * Description of ClientController * * @author imen */ class RecipeController extends FOSRestController { /** * Returns all users values. * * @return View * */ public function getRecipesAction() { $data = $this->getDoctrine()->getManager()->getRepository(Recipe::class)->findAll(); $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function getRecipeAction($id) { $data = $this->getDoctrine()->getManager()->getRepository(Recipe::class)->findOneById($id); if (!$data) { throw new HttpException(404, "product with the id $id not found"); } $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\View\View; use AppBundle\Entity\Promotion; use Symfony\Component\HttpKernel\Exception\HttpException; use FOS\RestBundle\Controller\Annotations\QueryParam; use FOS\RestBundle\Request\ParamFetcher; /** * Description of PromotionController * * @author imen */ class PromotionController extends FOSRestController { /** * Returns all users values. * * @return View * */ public function getPromotionsAction() { $data = $this->getDoctrine()->getManager()->getRepository(Promotion::class)->findAll(); $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } /** * @QueryParam(name="date", description="date") */ public function getPromotionsDateAction(ParamFetcher $paramFetcher) { $repository = $this->getDoctrine()->getRepository(Promotion::class); $date = date("Y-m-d H:i:s", $paramFetcher->get('date')); $query = $repository->createQueryBuilder('p') ->select("count(p.id)") ->where(':date BETWEEN p.beginDate AND p.endDate') ->setParameter('date', $date) ->getQuery(); $productCount = $query->getSingleScalarResult(); $isDisponible = false; if($productCount > 0){ $isDisponible = true; } $view = View::create() ->setStatusCode(200) ->setData(array("isDisponible" => $isDisponible)); return $this->get('fos_rest.view_handler')->handle($view); } /** * Returns all enumeration values. * * @return View * */ public function getPromotionAction($id) { $data = $this->getDoctrine()->getManager()->getRepository(Promotion::class)->findOneById($id); if (!$data) { throw new HttpException(404, "promotion with the id $id not found"); } $view = View::create() ->setStatusCode(200) ->setData($data); return $this->get('fos_rest.view_handler')->handle($view); } } <file_sep><?php namespace AppBundle\Entity; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="user") */ class User implements UserInterface { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", nullable=true) */ private $identityCarteNumber; /** * @ORM\Column(type="string") */ private $firstname; /** * @ORM\Column(type="string") */ private $lastname; /** * @ORM\Column(type="string", nullable=true) */ private $email; /** * @ORM\Column(type="integer") */ private $phoneNumber; /** * @ORM\Column(type="string", unique=true) */ private $username; /** * @ORM\Column(type="string") */ private $password; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Categorie", inversedBy="users", cascade={"persist"}) * @ORM\JoinTable(name="user_categorie") */ private $categories; /** * One user has One carte. * @ORM\OneToOne(targetEntity="Carte") * @ORM\JoinColumn(name="carte_id", referencedColumnName="number") */ private $carte; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set username * * @param string $username * @return User */ public function setUsername($username) { $this->username = $username; return $this; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } /** * Set password * * @param string $password * * @return User */ public function setPassword($password) { $this->password = $password; return $this; } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * Set firstname * * @param string $firstname * * @return User */ public function setFirstname($firstname) { $this->firstname = $firstname; return $this; } /** * Get firstname * * @return string */ public function getFirstname() { return $this->firstname; } /** * Set lastname * * @param string $lastname * * @return User */ public function setLastname($lastname) { $this->lastname = $lastname; return $this; } /** * Get lastname * * @return string */ public function getLastname() { return $this->lastname; } /** * Set email * * @param string $email * * @return User */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set phoneNumber * * @param integer $phoneNumber * * @return User */ public function setPhoneNumber($phoneNumber) { $this->phoneNumber = $phoneNumber; return $this; } /** * Get phoneNumber * * @return integer */ public function getPhoneNumber() { return $this->phoneNumber; } /** * Get roles * * @return array */ public function getRoles() { return array(); } public function getSalt() { } public function eraseCredentials() { } /** * Constructor */ public function __construct() { $this->categories = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add category * * @param \AppBundle\Entity\Categorie $category * * @return User */ public function addCategory(\AppBundle\Entity\Categorie $category) { $this->categories[] = $category; return $this; } /** * Remove category * * @param \AppBundle\Entity\Categorie $category */ public function removeCategory(\AppBundle\Entity\Categorie $category) { $this->categories->removeElement($category); } /** * Get categories * * @return \Doctrine\Common\Collections\Collection */ public function getCategories() { return $this->categories; } /** * Set identityCarteNumber * * @param string $identityCarteNumber * * @return User */ public function setIdentityCarteNumber($identityCarteNumber) { $this->identityCarteNumber = $identityCarteNumber; return $this; } /** * Get identityCarteNumber * * @return string */ public function getIdentityCarteNumber() { return $this->identityCarteNumber; } /** * Set carte * * @param \AppBundle\Entity\Carte $carte * * @return User */ public function setCarte(\AppBundle\Entity\Carte $carte = null) { $this->carte = $carte; return $this; } /** * Get carte * * @return \AppBundle\Entity\Carte */ public function getCarte() { return $this->carte; } } <file_sep><?php namespace AppBundle\Serializer; use JMS\Serializer\EventDispatcher\EventSubscriberInterface; use JMS\Serializer\EventDispatcher\ObjectEvent; class RecipePictureSeralizer implements EventSubscriberInterface { private $routePicturePathRecipe; public function __construct($routePicturePathRecipe) { $this->routePicturePathRecipe = $routePicturePathRecipe; } public static function getSubscribedEvents() { return array( array( 'event' => 'serializer.post_serialize', 'method' => 'onPostSerialize', 'class' => 'AppBundle\Entity\Recipe', 'format' => 'json', 'priority' => 0, ), ); } public function onPostSerialize(ObjectEvent $event) { $path = $this->routePicturePathRecipe . $event->getObject()->getPicture(); $file = fopen($path, "rb"); $contents = fread($file, filesize($path)); $encoded_image = base64_encode($contents); $event->getVisitor()->addData('picture_binaire', $encoded_image); } }
d3d33ffcb5e18942b199eacd9c0ffb15098bd715
[ "PHP" ]
13
PHP
chaymaISETCH/mgWeb
a27613908f5aea068c4ca314be7884327a69d283
264601580c56b469b97941948beace334df0ea58
refs/heads/master
<repo_name>mpfranco10/parcial2-20201<file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import * as serviceWorker from './serviceWorker'; import localeEsMessages from "./locales/es"; import localeEnMessages from "./locales/en"; import {IntlProvider} from 'react-intl'; import Movies from "./Movies"; const messages = { 'es': localeEsMessages, 'en': localeEnMessages }; const language = navigator.language.split(/[-_]/)[0]; // language without region code ReactDOM.render( <IntlProvider locale={language} messages={messages[language]}> <Movies locale={language}/> </IntlProvider>, document.getElementById("root") ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.register();<file_sep>/src/Detail.js import React, { Component } from "react"; class Detail extends Component { state = this.props.movie; render() { return ( <div className="card"> <img src={this.state.poster} className="card-img-top" alt="..."></img> <div className="card-body"> <h5 className="card-title">{this.state.name}</h5> <p className="card-text">{this.state.description}</p> </div> <ul className="list-group list-group-flush"> <li className="list-group-item"><strong>{this.state.cast}</strong></li> </ul> </div> ); } } export default Detail;<file_sep>/src/Movie.js import React, { Component } from "react"; import { FormattedDate } from 'react-intl'; import { FormattedPlural } from 'react-intl'; import { FormattedNumber } from 'react-intl'; import { FormattedMessage } from 'react-intl'; class Movie extends Component { state = { movie : this.props.movie }; renderLikes() { return this.state.likes === 0 ? "Give us a like" : this.state.likes; } handleIncrement = () => { this.setState({ likes: this.state.likes + 1 }); }; render() { return ( <tr onClick={() => this.props.onDelete(this.props.movie)} > <th>{this.state.movie.id}</th> <td>{this.state.movie.name}</td> <td>{this.state.movie.directedBy}</td> <td>{this.state.movie.country}</td> <td> {this.state.movie.budget} <FormattedPlural value={this.state.movie.budget} one= {<FormattedMessage id="Million" />} other={<FormattedMessage id="Millions" />} /> </td> <td> <FormattedDate value={new Date(this.state.movie.releaseDate)} year='numeric' month='long' day='numeric' weekday='long' /> </td> <td><FormattedNumber value={this.state.movie.views} /></td> </tr> ); } } export default Movie;
5cd04aea28e109d6e556403ca780512210c59262
[ "JavaScript" ]
3
JavaScript
mpfranco10/parcial2-20201
1c0251b7a3fed02a72367588eb6cca64a949f16d
7ad3e5d3d98b27380577fdca78e251e10382dc9b
refs/heads/master
<repo_name>marras/FCS-analyzer<file_sep>/src/analyzer.cpp #include <QVBoxLayout> #include "analyzer.h" #include "program.h" #include <qwt_plot.h> #include <qwt_symbol.h> #include <stdio.h> using std::cout; using std::cerr; void IndexedPushButton :: emit_i () { emit clicked(i, SM::SWITCH); } // -------- Oblicza srednia funkcje korelacji Z ZAZNACZONYCH ------------- // bool Analyzer :: CalculateAverageCorrelation () { if (info == NULL) { cout << "No data loaded!\n"; return false;} if (listFunctions->count() < 1) { cout << "***ERROR in code: No data loaded & NULL not detected!!!***\n"; return false;} //should not happen! Info::Func srednia; //NOTE we no longer assume all the correlations nor countrates have the same size Info::Func srednia_countrate; //NOTE instead, let's take the shortest one for the sake of averaging uint size = info->correlation[0].size(); uint count_size = info->countrate[0].size(); //#points in one correlation for (uint f = 0; f < info->correlation.size(); f++) { //info->correlation.size - #correlations; if (info->correlation[f].size() < size) size = info->correlation[f].size(); //size = teraz minimalny (rowny najkrotszej f-cji korelacji) if (info->countrate[f].size() < count_size ) count_size = info->countrate[f].size(); //size = teraz minimalny (rowny najkrotszej f-cji korelacji) } srednia.resize(size); srednia_countrate.resize(count_size); uint checked = 0; for (uint f = 0; f < info->correlation.size(); f++) { //info->correlation.size - #correlations; if (!listFunctions->item(f)->isSelected()) continue; //usredniamy tylko funkcje wybrane z listy! // if (info->correlation[f].size() != size) {cout << "Error: correlation arrays have different sizes!"; return false;} for (uint a = 0; a < size; a ++) srednia[a].y += info->correlation[f][a].y; //a - wspolrzedna X // if (info->countrate[f].size() != count_size) {cout << "Error: countrate trajectories have different sizes!"; return false;} for (uint a = 0; a < count_size; a ++) srednia_countrate[a].y += info->countrate[f][a].y; //a - wspolrzedna X checked ++; } if (checked == 0) {cerr << "No function selected.\n"; return false;} //nie zaznaczylismy zadnej funkcji for (uint a = 0; a < size; a++) { srednia[a].x = info->correlation[0][a].x; srednia[a].y /= checked;//info->correlation.size(); nie wszystkie sa zaznaczone } for (uint a = 0; a < count_size; a ++) { srednia_countrate[a].x = a; srednia_countrate[a].y /= checked; } qwtPlotCF->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu DrawFunction (srednia, "Average", qwtPlotCF); //i namaluj tylko srednia qwtPlotResiduals->detachItems (QwtPlotItem::Rtti_PlotCurve); //wyczysc okno i namaluj sredni przebieg intensywnosci DrawFunction (srednia_countrate, "Average countrate", qwtPlotResiduals); return true; //return true if anything is drawn } void DrawFunction (const Info::Func & f, QString text, QwtPlot * plot) { //display countrate in the top graph for the first experiment int ar_size = f.size(); //array size double * x = new double [ar_size]; //copy the values from FCS_Info->vector into a simple array double * y = new double [ar_size]; for (int i=0; i<ar_size; ++i) { x[i] = f[i].x; y[i] = f[i].y; } QwtPlotCurve * curve = new QwtPlotCurve (text); curve->setSamples (x,y,ar_size); curve->attach (plot); plot->replot(); delete [] x; delete [] y; } // --------- Otworz plik z danymi, namaluj je na wykresie i dodaj do okienka funkcji ---------- // void Analyzer :: OpenFCSFile (QString fname) { if (info != NULL) delete info; info = new Info::FCS_Info; if (!info->LoadFCSFile(fname)) {QMessageBox::warning( NULL, "Error", tr("Failed to load file %1.").arg(fname)); return;} info->Print (std::cout); /////DEBUG listFunctions->clear(); //wyczysc okienko z lista funckji qwtPlotCF->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu qwtPlotResiduals->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu for (int i=0;i<info->num_repeats();i++) { //dodaj funkcje korelacji do okienka QListWidgetItem * item = new QListWidgetItem; item->setText(tr("Function %1: %2").arg(i+1).arg(info->AvgIntensity(i))); listFunctions->addItem (item); DrawFunction (info->countrate[i], tr("Intensity #%1").arg(i), qwtPlotResiduals); //namaluj funkcje na wykresie DrawFunction (info->correlation[i], tr("Correlation #%1").arg(i), qwtPlotCF); } fitFrom->setText (QString::number(0)); fitTo->setText (QString::number(info->correlation[0].size())); if (fname.length() > 25) filename = QString ("...") + fname.right(25); else filename = fname; listFunctions->setCurrentRow(0); //Ustaw tytul, zeby bylo widac nazwe pliku /*MainWindow->*///setWindowTitle (QString("FCS analyzer: ")+name); /* QTabWidget * p = (QTabWidget *) parent(); p->setTabText (p->currentIndex(), name);*/ } // ------------------- Otwórz plik wysymulowany - format ASCII, z pominieciem I linijki ------------ // void Analyzer :: OpenSimulated (QString fname) { if (info != NULL) delete info; info = new Info::FCS_Info; info->correlation.resize(1); info->repeats = 1; info->countrate.resize(1); info->countrate[0].resize(1); //wlasciwie po nic, ale niech bedzie,zeby nie segfaulcil HACK QFile fp (fname); if (!fp.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning( NULL, "Error", "Could not open file."); return; } QString line; line = fp.readLine().trimmed(); //skip 1st line while ((line = fp.readLine().trimmed())!=NULL) { QStringList words = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); Info :: XYData xydata; xydata.x = words[0].toDouble(); xydata.y = words[1].toDouble(); info->correlation[0].push_back(xydata); } fp.close(); info->Print (std::cout); /////DEBUG listFunctions->clear(); //wyczysc okienko z lista funckji qwtPlotCF->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu qwtPlotResiduals->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu QListWidgetItem * item = new QListWidgetItem; item->setText(tr("%1").arg(fname)); listFunctions->addItem (item); //DrawFunction (info->countrate[0], tr("Intensity #%1").arg(i), qwtPlotResiduals); //namaluj funkcje na wykresie DrawFunction (info->correlation[0], tr("Simulated Correlation"), qwtPlotCF); fitFrom->setText (QString::number(0)); fitTo->setText (QString::number(info->correlation[0].size())); listFunctions->setCurrentRow(0); inputBaseLine->setText("0"); if (fname.length() > 25) filename = QString ("...") + fname.right(25); else filename = fname; //Ustaw tytul, zeby bylo widac nazwe pliku TODO setWindowTitle (QString("FCS analyzer: Simulated data")); } // ------------------- Otwórz plik z danymi w formacie ASCII ------------ // void Analyzer :: OpenASCII () { printf ("Opening ASCII file..."); QStringList name_list = QFileDialog :: getOpenFileNames (NULL,tr("Open ASCII data file"),"~",tr("ASCII Data files (*.dat);;All files (*)")); if (name_list.size() == 0) {QMessageBox::information( NULL, "Information", "No file selected.");return;} if (info != NULL) delete info; info = new Info::FCS_Info; // if (!info->LoadFCSFile(name)) // {QMessageBox::warning( NULL, "Error", tr("Failed to load file %1.").arg(name)); return;} info->correlation.resize(name_list.size()); info->countrate.resize(name_list.size()); //wlasciwie po nic, ale niech bedzie,zeby nie segfaulcil HACK info->repeats = name_list.size(); for (int c = 0; c < name_list.size(); ++c) { //c - #funkcji korelacji QFile fp (name_list.at(c)); if (!fp.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning( NULL, "Error", "Could not open file."); return; } QString line; while ((line = fp.readLine().trimmed())!=NULL) { QStringList words = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); Info :: XYData xydata; xydata.x = words[0].toDouble(); xydata.y = words[1].toDouble(); info->correlation[c].push_back(xydata); } fp.close(); info->countrate[c].resize(1); } info->Print (std::cout); /////DEBUG listFunctions->clear(); //wyczysc okienko z lista funckji qwtPlotCF->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu qwtPlotResiduals->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu for (int i=0;i<info->num_repeats();i++) { //dodaj funkcje korelacji do okienka QListWidgetItem * item = new QListWidgetItem; item->setText(tr("%1").arg(name_list[i])); listFunctions->addItem (item); DrawFunction (info->countrate[i], tr("Intensity #%1").arg(i), qwtPlotResiduals); //namaluj funkcje na wykresie DrawFunction (info->correlation[i], tr("Correlation #%1").arg(i), qwtPlotCF); } fitFrom->setText (QString::number(0)); fitTo->setText (QString::number(info->correlation[0].size())); listFunctions->setCurrentRow(0); //Ustaw tytul, zeby bylo widac nazwe pliku TODO setWindowTitle (QString("FCS analyzer: ASCII data")); } void Analyzer :: DrawCorrelationFromParams () { const uint N = qwtPlotCF->transform(QwtPlot::xBottom,qwtPlotCF->axisScaleDiv(QwtPlot::xBottom)->upperBound()); double x[N],y[N]; double par [NUM_PARAMS]; for (uint i = 0; i < NUM_PARAMS; i++) par[i] = tableParameters->item(i,0)->text().toDouble(); for (uint i = 0; i < N; i++) { x[i] = qwtPlotCF->invTransform(QwtPlot::xBottom,i); y[i] = G_val (x[i],par); // std::cout << x[i] << ", " << y[i] <<"\n"; } QwtPlotCurve * curve = new QwtPlotCurve ("G(tau) - fitted"); QPen kolor (Qt::red); curve->setSamples (x,y,N); curve->setPen (kolor); curve->attach (qwtPlotCF); // qwtPlotCF->setAxisAutoScale (xBottom); qwtPlotCF->setAxisScaleDiv (QwtPlot::xBottom, *qwtPlotCF->axisScaleDiv(QwtPlot::xBottom));//HACK wylacza autoscaling :) qwtPlotCF->replot(); // ------------ Draw residuals in the upper plot ---------------// if (info == NULL) return; //do not draw residuals if there is no correlation loaded qwtPlotResiduals->detachItems (QwtPlotItem::Rtti_PlotCurve); //clean up the upper plot // Oblicz srednia (jak w CalculateAverageCorrelation) Info::Func funkcja; //NOTE assume all the correlations have the same size uint size = fitTo->text().toUInt() - fitFrom->text().toUInt() + 1; //#points in one correlation funkcja.resize(size); uint checked = 0; for (uint f = 0; f < info->correlation.size(); f++) { //info->correlation.size - #correlations; if (!listFunctions->item(f)->isSelected()) continue; //usredniamy tylko funkcje wybrane z listy! for (uint a = 0; a < size; a ++) funkcja[a].y += info->correlation[f][a + fitFrom->text().toUInt()].y; //a - wspolrzedna X checked ++; } for (uint a = 0; a < size; a++) { funkcja[a].x = info->correlation[0][a + fitFrom->text().toUInt()].x; funkcja[a].y /= checked; //dzielimy sume przez liczbe funkcji (nie wszystkie sa zaznaczone) -> dostajemy srednia z wynikow funkcja[a].y = funkcja[a].y - G_val (funkcja[a].x,par); //odejmujemy od niej wartosc dopasowana } QwtScaleEngine * log_engine = new QwtLog10ScaleEngine; qwtPlotResiduals->setAxisScaleEngine (QwtPlot::xBottom, log_engine); //ustaw skale na logarytmiczna qwtPlotResiduals->setAxisScaleDiv (QwtPlot::xBottom, *qwtPlotCF->axisScaleDiv(QwtPlot::xBottom));//HACK manual scale - z dolnego grafu:) DrawFunction (funkcja, "Average", qwtPlotResiduals); //i namaluj tylko srednia // qwtPlotResiduals->replot(); } void Analyzer :: setFitLimits(int button, double x, double) { //double y- niewykorzystane if (button == Qt::MidButton) { //set left point uint i; for (i = 0; i < info->correlation[0].size(); ++i) { if (info->correlation[0][i].x > x) break; } if (i >= fitTo->text().toUInt()) i = fitTo->text().toUInt() - 1; fitFrom->setText (QString::number(i)); labelFrom->setText (QString("(")+QString::number(info->correlation[0][i].x)+") to "); QList<QwtPlotItem*> lista = qwtPlotCF->itemList(); QwtPlotCurve * krzywa = (QwtPlotCurve *) lista[0]; m1.setValue (krzywa->sample(i).x(), krzywa->sample(i).y()); m1.attach (qwtPlotCF); } else if (button == Qt::RightButton) { //set right point uint i; for (i = 0; i < info->correlation[0].size(); ++i) { if (info->correlation[0][i].x > x) break; } if (i == info->correlation[0].size()) //jezeli przelecielismy cala petle i nadal x jest za maly i = info->correlation[0].size() - 1; //ustaw marker na ostatnim punkcie krzywej if (i <= fitFrom->text().toUInt()) i = fitFrom->text().toUInt() + 1; fitTo->setText (QString::number(i)); labelTo->setText (QString("(")+QString::number(info->correlation[0][i].x)+") seconds"); QList<QwtPlotItem*> lista = qwtPlotCF->itemList(); QwtPlotCurve * krzywa = (QwtPlotCurve *) lista[0]; m2.setValue (krzywa->sample(i).x(), krzywa->sample(i).y()); m2.attach (qwtPlotCF); cout << "Marker set at "<<m2.xValue() << ", "<<m2.yValue()<<"\n"; cout.flush(); } qwtPlotCF->replot(); } void Analyzer :: setFitModel (int model) { if (model == 1) { //1-component tableParameters->lockCell (0,SM::ON); //odblokuj tylko G(0) tableParameters->lockCell (4,SM::ON); //i t_D1 tableParameters->lockCell (5,SM::OFF); tableParameters->lockCell (6,SM::OFF); tableParameters->lockCell (7,SM::OFF); tableParameters->lockCell (8,SM::OFF); tableParameters->setValue(1.0, 5,0); //A1 = 1 tableParameters->setValue(0.0, 7,0); //A2 =~ 0 } if (model == 2) { //2-component // for (int i=0;i<NUM_PARAMS;i++) tableParameters->lockCell (i,SM::OFF); tableParameters->lockCell (0,SM::ON); //odblokuj tylko G(0), tableParameters->lockCell (4,SM::ON); //t_D1 tableParameters->lockCell (5,SM::ON); //A1 tableParameters->lockCell (8,SM::ON); //i t_D3 tableParameters->lockCell (6,SM::OFF); tableParameters->lockCell (7,SM::OFF); tableParameters->setValue(0.5, 5,0); //A1 = 1 //wystarczy, ze to sie zmieni: A3 = 1-A1-A2 = 1-A1-0 = 1-A1 = 0.5 na starcie tableParameters->setValue(0.0, 7,0); //A2 =~ 0 } if (model == 3) { //3-component // for (int i=0;i<NUM_PARAMS;i++) tableParameters->lockCell (i,SM::OFF); tableParameters->lockCell (0,SM::ON); //odblokuj G(0), tableParameters->lockCell (4,SM::ON); //t_D1 tableParameters->lockCell (5,SM::ON); //A1 tableParameters->lockCell (6,SM::ON); //t_D2 tableParameters->lockCell (7,SM::ON); //A2 tableParameters->lockCell (8,SM::ON); //t_D3 tableParameters->setValue(0.33, 5,0); //A1 = 0.33 tableParameters->setValue(0.33, 7,0); //A2 = 0.33 } } void Analyzer :: setTripletModel (int s) { if (s == Qt::Checked) { tableParameters->setValue(0.2, 2,0); //T = 0.2 tableParameters->setValue(1, 3,0); //t_T = 10 tableParameters->lockCell (2,SM::ON); //odblokuj T tableParameters->lockCell (3,SM::ON); //odblokuj t_T } else { tableParameters->setValue(0.0, 2,0); //T =~ 0 tableParameters->lockCell (2,SM::OFF); //zablokuj T tableParameters->lockCell (3,SM::OFF); //zablokuj t_T } } void Analyzer :: setBleachModel (int s) { if (s == Qt::Checked) { tableParameters->setValue(0.2, 10,0); //BT = 0.2 tableParameters->setValue(50, 9,0); //t_bl = 10000 tableParameters->lockCell (10,SM::ON); //odblokuj B tableParameters->lockCell (9,SM::ON); //odblokuj t_bl } else { tableParameters->setValue(0.0, 10,0); //B =~ 0 tableParameters->lockCell (10,SM::OFF); //zablokuj B tableParameters->lockCell (9,SM::OFF); //zablokuj t_bl } } void Analyzer :: SaveParams () { if (info == NULL) { cout << "No data loaded!\n"; return;} QString name = QFileDialog :: getSaveFileName (this,tr("Select file to append results to"),tr("~"),tr("Parameter files (*.par);;All files (*)"), NULL, QFileDialog::DontConfirmOverwrite); if (name == NULL) {QMessageBox::information( NULL, "Information", "Output file not selected.");return;} FILE * fp = fopen (name.toAscii(), "at"); fprintf (fp, "name\t\t\tG0\t\tSP\t\tT\t\tt_T\t\tt_D1\t\tA1\t\tt_D2\t\tA2\t\tt_D3\t\tt_bl\t\tB\t\tChi^2\n"); fprintf (fp, "%s\t",filename.toAscii().data()); for (uint i = 0; i < NUM_PARAMS; i++) { if (tableParameters->item(i,0)->background() != Qt::gray) fprintf (fp, "%le\t", tableParameters->item(i,0)->text().toDouble()); else fprintf (fp, "(%le)\t", tableParameters->item(i,0)->text().toDouble()); } fprintf (fp, "%le\t",lblChiSqr->text().toDouble()); fprintf (fp, "\n"); fclose(fp); QMessageBox::information( NULL, "Finished", QString("Fit parameters appended to: ")+name); } Analyzer :: Analyzer (QWidget * par) { setParent (par); info = NULL; setupUi (this); QwtSymbol * s1 = new QwtSymbol(QwtSymbol::Diamond, QBrush(QColor(Qt::red)), QPen (QColor(Qt::black)), QSize (10,10)); QwtSymbol * s2 = new QwtSymbol(QwtSymbol::Diamond, QBrush(QColor(Qt::green)), QPen (QColor(Qt::black)), QSize (10,10)); m1.setSymbol (s1); m2.setSymbol (s2); QwtScaleEngine * log_engine = new QwtLog10ScaleEngine; qwtPlotCF->setAxisScaleEngine (QwtPlot::xBottom, log_engine); sliderN->SetExpParams (labN_min->text().toDouble(), labN_max->text().toDouble(),0,0); sliderT->SetExpParams (labT_min->text().toDouble(), labT_max->text().toDouble(),2,0); sliderTau1->SetExpParams (labTau1_min->text().toDouble(), labTau1_max->text().toDouble(),4,0); connect (sliderN, SIGNAL(sendExp(double,int,int)), tableParameters, SLOT(setValue(double,int,int))); connect (sliderT, SIGNAL(sendExp(double,int,int)), tableParameters, SLOT(setValue(double,int,int))); connect (sliderTau1, SIGNAL(sendExp(double,int,int)), tableParameters, SLOT(setValue(double,int,int))); connect (tableParameters, SIGNAL (cellValueSet(double,int,int)), sliderN, SLOT(updateSlider(double,int,int))); connect (tableParameters, SIGNAL (cellValueSet(double,int,int)), sliderT, SLOT(updateSlider(double,int,int))); connect (tableParameters, SIGNAL (cellValueSet(double,int,int)), sliderTau1, SLOT(updateSlider(double,int,int))); connect (butSelectAll, SIGNAL (clicked()), listFunctions, SLOT (selectAll())); connect (butSelectNone, SIGNAL (clicked()), listFunctions, SLOT (clearSelection())); // connect (butAverage, SIGNAL (clicked()), this, SLOT (CalculateAverageCorrelation())); connect (butSaveASCII, SIGNAL (clicked()), this, SLOT (SaveASCII())); connect (butSaveAvg, SIGNAL (clicked()), this, SLOT (SaveAvg())); connect (butSaveParameters, SIGNAL (clicked()), this, SLOT (SaveParams())); connect (butShowInfo, SIGNAL (clicked()), this, SLOT (ShowInfo())); connect (listFunctions,SIGNAL (itemSelectionChanged()), this, SLOT(CalculateAverageCorrelation())); connect (butFit, SIGNAL (clicked()), this, SLOT(Fit())); connect (butDraw, SIGNAL(clicked()), this, SLOT(DrawCorrelationFromParams())); connect (qwtPlotCF, SIGNAL (clicked (int , double, double)), this, SLOT(setFitLimits(int , double, double))); connect (comboModel, SIGNAL (currentIndexChanged (int)), this, SLOT (setFitModel (int))); connect (chkTriplet, SIGNAL (stateChanged (int)), this, SLOT (setTripletModel (int))); connect (chkPhotobleaching, SIGNAL (stateChanged (int)), this, SLOT (setBleachModel (int))); for (int i=0;i<NUM_PARAMS;i++) tableParameters->lockCell (i,SM::OFF); //lock all cells QVBoxLayout * layoutLockButtons = new QVBoxLayout; //tworzymy recznie layout,bo pod linuxem inaczej nie styka :/ IndexedPushButton * lockbutton[NUM_PARAMS]; for (int i=0; i<NUM_PARAMS; i++) { lockbutton[i] = new IndexedPushButton ("Lock", i); layoutLockButtons->addWidget (lockbutton[i]); connect (lockbutton[i], SIGNAL (clicked(int, SM::SwitchModes)), tableParameters, SLOT(lockCell(int,SM::SwitchModes))); } frameLock->setLayout(layoutLockButtons); } void Analyzer :: ShowInfo () { if (info == NULL) {QMessageBox::warning( NULL, "Error", "No file loaded."); return;} QString text = info->GetMeasurementInfo(); QMessageBox::information( NULL, "Measurement info", text); return; } void Analyzer :: SaveASCII () { if (info == NULL) { cout << "No data loaded!\n"; return;} QString name = QFileDialog :: getExistingDirectory (this,tr("Select output directory"),"~",QFileDialog::ShowDirsOnly); if (name == NULL) {QMessageBox::information( NULL, "Information", "Output directory not selected.");return;} for (uint f = 0; f < info->correlation.size(); f++) { //info->correlation.size - #correlations; if (!listFunctions->item(f)->isSelected()) continue; //wypisujemy //NIE// tylko funkcje wybrane z listy! QString filename = name + "/" + QString::number(f+1) + ".dat"; FILE * fp = fopen (filename.toLatin1(), "wt"); for (uint a = 0; a < info->correlation[f].size(); a ++) fprintf (fp, "%lf\t%lf\n", info->correlation[f][a].x, info->correlation[f][a].y); fclose(fp); } QMessageBox::information( NULL, "Finished", QString("Files saved in: ")+name); } void Analyzer :: SaveAvg () { if (info == NULL) { cout << "No data loaded!\n"; return;} QString name = QFileDialog :: getSaveFileName (this,tr("Select output file"),"~"); if (name == NULL) {QMessageBox::information( NULL, "Information", "Output file not selected.");return;} if (!CalculateAverageCorrelation()) //leave only one (average) function & check if there's anything to fit to :) { printf ("Average correlation could not be calculated.\n"); return;} QList<QwtPlotItem*> lista = qwtPlotCF->itemList(); if (lista.size()!=1) {printf ("Warning: more than one curve on the plot!!\n");} QwtPlotCurve* krzywa = (QwtPlotCurve*) lista[0]; //dopasowujemy do I krzywej z wykresu // const uint start = fitFrom->text().toUInt(); // const uint n = fitTo->text().toUInt() - fitFrom->text().toUInt();//krzywa->dataSize(); //n-dlugosc traj TODO FILE * fp = fopen (name.toAscii(), "wt"); for (uint i = 0; i < info->correlation[0].size(); i++) { fprintf (fp, "%lf\t%lf\n", krzywa->sample(i).x(), krzywa->sample(i).y()); } fclose(fp); QMessageBox::information( NULL, "Finished", QString("Average correlation saved in: ")+name); } Analyzer :: ~Analyzer () { if (info != NULL) delete info; } <file_sep>/src/correlatorSimple.cpp #include "correlator.h" // #include "log.h" /**************************************************************************************** * Constructor, to be used if the fluorescence trajectory is given directly as int[]. * * Parameters: * * . int* traj - fluorescence trajectory (array of photon counts), * * . const double step_size - trajectory resolution in [ps], * * . const int num_steps: length of the trajectory in step_size units, * * . const int _steps_per_bin: binning resolution for correlation function calculation. * ****************************************************************************************/ CorrelatorSimple :: CorrelatorSimple (int * traj, const double step_size, const int num_steps, const int _steps_per_bin) : Correlator (step_size, num_steps, _steps_per_bin) { photons = new int [num_steps/_steps_per_bin]; for (int i=0;i<B;i++) { photons[i]=0; for (int j=0;j<_steps_per_bin;j++) { photons[i]+=traj[i*_steps_per_bin+j]; K+=traj[i*_steps_per_bin+j]; } } avg_intensity = (double)K/(double)B; LOG ("K= %d, B= %d, AVG_INT = %f\n",K,B,avg_intensity); } // /******************************************************************************* // * Constructor, to be used if the fluorescence trajectory is stored in a file. * // * Arguments as above. * // *******************************************************************************/ // CorrelatorSimple:: CorrelatorSimple (const char * fluor_file, const double step_size, const int num_steps, const int _steps_per_bin) : Correlator (step_size, num_steps, _steps_per_bin) // { // LOG ("Creating correlatorSIMPLE object with step_size = %f [ps], num_steps = %d, steps_per_bin = %d.\n",step_size,num_steps,_steps_per_bin); // // assert (B == num_steps/_steps_per_bin); //DEBUG // printf ("Using %d frames.\n",B*_steps_per_bin); // photons = new int [B]; //allocate memory for numbers of photon counts in each bin // FILE * fp; // assert ((fp = fopen64 (fluor_file, "rt")) != NULL); //NOTE use large file support // // for (int i=0; i<B; i++) { // photons[i]=0; // clear the array // for (int j=0;j<_steps_per_bin;j++) { // int phot; // fscanf (fp, "%d\n",&phot); // assert (phot>=0); // //DEBUG // photons[i]+=phot; // assert (photons[i]>=0); // //DEBUG // K+=phot; // } // } // fclose(fp); // avg_intensity = (double)K/(double)B; // LOG ("K= %d, B= %d, AVG_INT = %f\n",K,B,avg_intensity); // } CorrelatorSimple :: ~CorrelatorSimple () { delete [] photons; } double CorrelatorSimple :: Calculate_correlation (double time) { int k = int (time / bin_size); //k - delay (bin size units) double sum = 0; assert (k>=0); for (int i=0;i<B-k;i++) { if (photons[i]<0 || photons[i+k]<0) { //DEBUG printf ("ERROR! ph[%d]= %d, ph[%d] = %d!\n",i,photons[i],i+k,photons[i+k]); } assert (photons[i]>=0); assert (photons[i+k]>=0); sum += photons[i]*photons[i+k]; } double correlation = sum/((B - k)*(avg_intensity*avg_intensity)) - 1; //calculate the value of the correlation return correlation; } /******************** * EXAMPLE OF USAGE * ********************/ /* const int NUM_STEPS = 1500; //liczba krokow trajektorii fluorescencji (jedn. dT) const double LAMBDA = 0.1; //f(t) = lambda * e^( -lambda*t ) const int dT = 1; //dlugosc kroku do obliczania F(t) (step size) const int DT = 2; //szerokosc kanalu do zliczania G(tau) (bin size) const double TAU = 6; //odstep czasowy, dla jakiego obliczamy funkcje korelacji void Gen_random_times (const int num_steps, const double step_size, int * & dist) { dist = new int [num_steps]; memset (dist,0,num_steps); double t = 0.0f; int i=0; FILE * fp = fopen ("times.txt","wt"); while (i<num_steps) { //printf ("i=%d, t= %f, dist[%d]=%d\n",i,t,i,dist[i]); ////// if (t>step_size) { i++; t-=step_size; continue; } double rnd = rng.rand(); t+= (-log(1-rnd))/LAMBDA; //t += 10 + rnd/5; //f. okresowa! fprintf (fp,"%f\n",t); //t += rnd; //jednostajna? dist[i]++; } fclose (fp); } int main () { srand (RAND_SEED); int * intensity=NULL; //trajektoria intensywnosci fluorescencji Gen_random_times (NUM_STEPS, dT, intensity); //zapisana z rozdzielczoscia dT for (int i=0;i<NUM_STEPS;i++) printf ("F(%d) = %d \n",i,intensity[i]); //////// CorrelatorSimple corr (intensity, dT, NUM_STEPS, DT/dT); //create a correlator object FILE * fp = fopen ("correlation.txt","wt"); // fprintf (fp,"%d %f\n",0, corr.Calculate_correlation (0)); for (int k=0; k<NUM_STEPS*dT/DT*3/4; k++) { //// * 3/4 - nie bierzemy calej traj. bo pod koniec sa szumy fprintf (fp,"%d %f\n",k, corr.Calculate_correlation (k)); } fclose (fp); return 0; } */ <file_sep>/src/tableparams.cpp #include "tableparams.h" #include <iostream> TableParams :: TableParams (QWidget * parent) : QTableWidget (parent) { horizontalHeader()->setResizeMode (QHeaderView::Fixed);//ResizeToContents); horizontalHeader()->setDefaultSectionSize (95); std::cout << "size:"<< horizontalHeader()->sectionSize(0); // QMessageBox::information( NULL, "Tytul",tr("Section 0: %1").arg(x)); connect (this, SIGNAL (cellChanged (int, int)), this, SLOT (emit_cellValueSet (int, int))); } void TableParams :: emit_cellValueSet (int r, int c) { emit cellValueSet (item(r,c)->text().toDouble(), r,c); } void TableParams :: setValue (double v, int row, int column) { item(row,column)->setText (QString::number(v,'g',5)); } void TableParams :: lockCell (int r, SM::SwitchModes mode) { if (mode == SM::SWITCH) { if (item(r,0)->background() == Qt::gray) item(r,0)->setBackground(Qt::white); else item(r,0)->setBackground(Qt::gray); } else if (mode == SM::OFF) item(r,0)->setBackground(Qt::gray); else if (mode == SM::ON) item(r,0)->setBackground(Qt::white); //TODO: spr. ENABLED? HACK Nie trzeba - przeciez mozemy chciec miec mozliwosc zmieniania //wszystkich parametrow, one maja byc "stale" tylko na czas fitowania! } <file_sep>/src/fit.cpp #include "analyzer.h" #include <float.h> #include <fstream> #include <stdlib.h> #include <stdio.h> //#include <QString> /*** Directives for the Grace library ***/ //#include <unistd.h> // #include <grace_np.h> #include <math.h> /*** Levenberg-Marquardt algorithm, LEVMAR ***/ #include "lm.h" #define MAGIC_TANH 2.0 //value to divide tanh by, in order to let it reach values of 0.0 and 1.0 exactly (should be around 2.0). // void my_error_function(const char *msg) { fprintf(stderr, "[GRACE library]: \"%s\"\n", msg); } double p [NUM_PARAMS]; //tablica aktualnych wartosci wszystkich parametrow (czesc nie bedzie sie zmieniac) int permut [NUM_PARAMS]; //tablica permutacyjna: permut[i] - ktory element z wektora p znajduje sie na i-tej pozycji w param.Grace int reverse_permut [NUM_PARAMS];//odwrotne tablica permutacyjna: permut[a] - ktory numer w tablicy permut ma a-ty parametr z programu glownego double baseline = 1; double *x_data; //x_data - zmienna niezalezna (czas) double *y_data; //y_data - G(t) EKSPERYMENTALNE! double Par (int i) { //calculate the actual value of a parameter switch (i) { case 2: case 5: case 7: case 10: //T, A1, A2, B e (0,1) return tanh(p[i])/MAGIC_TANH + 0.5;break; /* case 3: //t_T max = 10 000 us ub[i] = 1e4; break; case 9: ub[i] = 1e7; break; //t_bl max = 10s*/ default: return p[i]*p[i];break; //zwracamy kwadrat --> Par(i) >= 0 :-) } } void G_function (double *lmp, double *hy, int m, int n, void *adata) { //hy - G(t) DOPASOWANE! lmp- wart parametrow wg L-M //przepisz nowe wartosci parametrow do wektora p wg tablicy permutacyjnej for (int i=0; i<m; i++) p[permut[i]] = lmp[i]; for (int i=0; i<n; i++) hy[i] = G_val (x_data[i],NULL) - y_data[i]; } //Oblicza wartosc funkcji dla zadanego opoznienia t i aktualnych parametrow double G_val (double t, const double new_params [NUM_PARAMS] = NULL) { if (new_params == NULL) return Par(0) * (1 + Par(2)*exp(-t/Par(3)) - Par(2)) / (1 - Par(2)) //triplet * (1 + Par(10)*exp(-t/Par(9)) - Par(10)) //bleaching * ( Par(5) / (1+t/Par(4)) / sqrt(1 + t/(Par(1)*Par(1)*Par(4))) //1st diffusion + Par(7) / (1+t/Par(6)) / sqrt(1 + t/(Par(1)*Par(1)*Par(6))) //2nd diffusion + (1-Par(5)-Par(7)) / (1+t/Par(8)) / sqrt(1 + t/(Par(1)*Par(1)*Par(8))) //3rd diffusion ) + baseline; // +1, bo nieznormalizowana g(2) else return new_params[0] * (1 + new_params[2]*exp(-t/new_params[3]) - new_params[2]) / (1 - new_params[2]) //triplet * (1 + new_params[10]*exp(-t/new_params[9]) - new_params[10]) //bleaching * (new_params[5] / (1+t/new_params[4]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[4])) //1st diffusion + new_params[7] / (1+t/new_params[6]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[6])) //2nd diffusion + (1-new_params[5]-new_params[7]) / (1+t/new_params[8]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[8])) //3rd diffusion ) + baseline; // +1, bo nieznormalizowana g(2) } // static double Pochodna (int a, double t) { // //TODO przepisac rownania z maximy :) // // //zm. pomocnicze dla przyspieszenia obliczen // double Gv = G_val (t); // double nawias_T = (1 + p[2]*exp(-t/p[3]) - p[2]); // double nawias_B = (1 + p[9]*exp(-t/p[9]) - p[9]); // double nawias_1 = p[5] / (1+t/p[4]) / sqrt(1 + t/(p[1]*p[1]*p[4])); // double nawias_2 = p[7] / (1+t/p[6]) / sqrt(1 + t/(p[1]*p[1]*p[6])); // double nawias_3 = (1-p[5]-p[7]) / (1+t/p[8]) / sqrt(1 + t/(p[1]*p[1]*p[8])); // double nawiasy_123 = nawias_1 + nawias_2 + nawias_3; // // if (a==0) return Gv/p[0]; //dN // else if (a==1) return nawias_T * nawias_B * p[0] * ( //dSP // ((-p[7]-p[5]+1)*t) / (p[1]*p[1]*p[1]*p[8]*(t/p[8]+1)*(t/(p[1]*p[1]*p[8])+1)*sqrt(t/(p[1]*p[1]*p[8])+1)) + // (p[7]*t) / (p[1]*p[1]*p[1]*p[6]*(t/p[6]+1)*(t/(p[1]*p[1]*p[6])+1)*sqrt(t/(p[1]*p[1]*p[6])+1)) + // (p[5]*t) / (p[1]*p[1]*p[1]*p[4]*(t/p[4]+1)*(t/(p[1]*p[1]*p[4])+1)*sqrt(t/(p[1]*p[1]*p[4])+1)) ); // else if (a==2) return p[0]*nawiasy_123*nawias_B * //dT // (exp(-t/p[3]) - 1); // else if (a==3) return p[0]*p[2]*t*nawiasy_123*nawias_B*exp(-t/p[3])/p[3]/p[3]; //dt_T // else if (a==4) return p[0]*nawias_T*nawias_B * //dt_D1 //CHECK! TODO nie wiem czy dziala jak nalezy :/ // (nawias_1*t/p[4]/p[4]/(1+t/p[4]) + // nawias_1*t/p[4]/p[4]/2/(1+t/p[4]/p[1]/p[1])/p[1]/p[1]) ; // else if (a==5) return p[0]*nawias_T*nawias_B * //dA1 // (nawias_1/p[5]-nawias_3/(1-p[5]-p[7])) ; // else if (a==6) return p[0]*nawias_T*nawias_B * //dt_D2 // (nawias_2*t/p[6]/p[6]/(1+t/p[6]) + // nawias_2*t/p[6]/p[6]/2/(1+t/p[6]/p[1]/p[1])/p[1]/p[1]) ; // else if (a==7) return p[0]*nawias_T*nawias_B * //dA2 // (nawias_2/p[7]*-nawias_3/(1-p[5]-p[7])) ; // else if (a==8) return p[0]*nawias_T*nawias_B * //dt_D3 // (nawias_3*t/p[8]/p[8]/(1+t/p[8]) + // nawias_3*t/p[8]/p[8]/2/(1+t/p[8]/p[1]/p[1])/p[1]/p[1]) ; // else if (a==9) return p[0]*p[10]*t*nawiasy_123*nawias_T*exp(-t/p[9])/p[9]/p[9]; //dt_bl // else if (a==10) return p[0]*nawias_T*nawiasy_123*(exp(-t/p[9])-1) ; //dB // else {std::cerr << "Invalid parameter number!"; exit (2);} // } // // // Wypelnij tablice z Jakobianem na poczet algorytmu L-M // void Jacobian (double *lmp, double *jac, int m, int n, void *adata) { // for (int i=0; i<m; i++) p[permut[i]] = lmp[i]; //update real parameters list, just in case // // int i,j,k; // // for(i=j=0; i<n; ++i){ //i - kolejne punkty, j - indeks w tabeli jakobianu (1-wymiarowa :/ ) // for (k=0; k<m; k++) { //k - kolejne parametry // jac[j++]=Pochodna(permut[k], x_data[i]); // } // } // } // /*********************************************** * Przerobiony na wykorzystanie pakietu levmar * ***********************************************/ bool Analyzer :: Fit () { printf ("atanh(0.999->) = %lf, %lf, %lf",atanh(0.999),atanh(0.9999), atanh(0.999999)); printf ("atanh(0.001->) = %lf, %lf, %lf",atanh((0.001-0.5)*MAGIC_TANH),atanh((0.00001-0.5)*MAGIC_TANH), atanh((0.0000001-0.5)*MAGIC_TANH)); baseline = inputBaseLine->text().toDouble(); if (!CalculateAverageCorrelation()) //leave only one (average) function & check if there's anything to fit to :) { printf ("Average correlation could not be calculated.\n"); return false;} /******************************************************************************** * p[i] - i-ty parametr (w tabeli zwyklej - z formularza) * * permut[i] - co oznacza i-ty parametr sposrod modyfikowalnych * * reverse_permut[i] - ktory nr w tabeli permutacyjnej ma normalny parametr i * ********************************************************************************/ int num_par = 0; //number of fitted parameters for (int i = 0; i < NUM_PARAMS; i++) { p[i] = tableParameters->item(i,0)->text().toDouble(); if (tableParameters->item(i,0)->background() != Qt::gray) { //jezeli mamy dopasowywac dany parametr permut[num_par] = i; //to wpisujemy go do tablicy permutacyjnej reverse_permut[i] = num_par; num_par++; } else reverse_permut[i] = -1; } for (int i=0; i<num_par; i++) printf ("permut [%d] = %d --> %lf\n",i,permut[i],p[permut[i]]); //box constraints - na nowa modle (funkcje tanh, x^2) for (int i=0; i<NUM_PARAMS; i++) { //odwrocon parametry (pierwiastki, atanh itp.) do tablicy p switch (i) { case 2: case 5: case 7: case 10: //T, A1, A2, B e (0,1) printf ("Converting p[%i]... %lf -->",i,p[i]); p[i] = atanh ((p[i]-0.5)*MAGIC_TANH); break; default: p[i] = sqrt(p[i]);break; //reszta >= 0 } } for (int i=0; i<NUM_PARAMS; i++) printf ("Converted param %i: %lf\n",i,p[i]); if (num_par == 0) {fprintf (stderr, "Error: no free parameters for fit.\n"); return false;} //Load curve data into the arrays QList<QwtPlotItem*> lista = qwtPlotCF->itemList(); if (lista.size()!=1) {printf ("Warning: more than one curve on the plot!!\n");} QwtPlotCurve* krzywa = (QwtPlotCurve*) lista[0]; //dopasowujemy do I krzywej z wykresu const uint start = fitFrom->text().toUInt(); const uint n = fitTo->text().toUInt() - fitFrom->text().toUInt();//krzywa->dataSize(); //n-dlugosc traj TODO printf ("\nnum_par = %d, n = %d (od %d do %d)\n",num_par,n,start,fitTo->text().toUInt()); //debug if (n < num_par) {printf ("Too few data points (n<p), cannot fit!\n"); return false;} //przepiszmy punkty ekperymentalne z wykresu do tablic globalnych x[] i y[] x_data = new double [n]; y_data = new double [n]; for (uint i = 0; i < n; i++) { x_data[i] = krzywa->sample(start+i).x(); y_data[i] = krzywa->sample(start+i).y();} //LEVMAR: m - liczba parametrow, n - liczba punktow // double *work, *covar; // work=(double*)malloc((LM_DIF_WORKSZ(num_par, n)+num_par*num_par)*sizeof(double)); // if(!work){ // fprintf(stderr, "memory allocation request failed in main()\n"); // exit(1); // } // covar=work+LM_DIF_WORKSZ(num_par, n); // ret=dlevmar_dif(G_function, p, y, m, n, 1000, opts, info, work, covar, NULL); // no Jacobian, caller allocates work memory, covariance estimated double p_robocze [num_par]; for (int i=0; i<num_par; i++) p_robocze[i] = p[permut[i]]; //na tych parametrach algorytm LM bedzie operowal int ret; double opts[LM_OPTS_SZ], info[LM_INFO_SZ]; //opts musi byc wypelnione!! //domyslnie: //opts[0] = 1e-3; opts[1] = opts[2] = 1e-17; opts[3] = 1e-17; opts[4] = 1e-6 //4 -tylko dla "_dif" opts[0] = 1e-2; opts[1] = opts[2] = 1e-50; opts[3] = 1e-17; opts[4] = 1e-6; //4 -tylko dla "_dif" // tu musimy przekazac p_robocze, a nie p !! zeby nie zmienial nam bezposrednio w nszej tabelce, a jedynie po uwzglednieniu permutacji! ret = dlevmar_dif(G_function, p_robocze, NULL, num_par, n, 100, NULL, info, NULL, NULL, NULL); // ret = dlevmar_bc_der(G_function, Jacobian, p_robocze, y_data, num_par, n, lb, ub, 100, NULL, info, NULL, NULL, NULL); // ret = dlevmar_der(G_function, Jacobian, p_robocze, y_data, num_par, n, 1000, NULL, info, NULL, NULL, NULL); // no Jacobian, caller allocates work memory, covariance estimated printf("Levenberg-Marquardt returned in %g iter, reason %g, sumsq %g [%g]\n", info[5], info[6], info[1], info[0]); printf("Best fit parameters:\n"); for (int i=0;i<num_par;i++) printf ("%d: %7.7g\n",i,p[permut[i]]); printf("Best fit parameters:\n"); for (int i=0;i<NUM_PARAMS;i++) printf ("p[%d]: %7.7g\n",i,p[i]); //wypiszmy wszystkie parametry (takze te zafixowane) // double err[n]; // dlevmar_chkjac(G_function, Jacobian, p_robocze, num_par, n, NULL,err); // for (int i=0;i<n;i++) printf ("err[%d] = %lf\n",i,err[i]); //output the errors between numer and analytical Jacobians // printf("Covariance of the fit:\n"); // for(i=0; i<num_par; ++i){ // for(j=0; j<num_par; ++j) // printf("%g ", covar[i*m+j]); // printf("\n"); // } // printf("\n"); // free(work); delete [] x_data; delete [] y_data; //display results back in tableParameters for (uint i = 0; i < NUM_PARAMS; i++) tableParameters->item(i,0)->setText(QString::number(Par(i))); for (int i=0; i<num_par; i++) printf ("permut [%d] = %d --> %lf\n",i,permut[i],p[permut[i]]); DrawCorrelationFromParams(); /*** Ocena jakości fitu: [chi2 = suma{(yi-yi_fit)^2} x (N^2) / n] ***/ double G0 = tableParameters->item(0,0)->text().toDouble(); double chi2n = info[1]/G0/G0/n; lblChiSqr->setText (QString::number(chi2n,'e')); return true; } /* static double pochodna_numer (int a, double t) { //FIXME nie dziala? TODO const double wartosc = p[a]; const double h = 0.1*wartosc; //krok p[a] = wartosc + h; const double G_1 = G_val (t); p[a] = wartosc - h; const double G_2 = G_val (t); p[a] = wartosc; //przywracamy stara wartosc a-tego parametru return (G_1-G_2)/2/h; //3-pktowa } //Wartosc pochodnej po parametrze a w punkcie t static int G_f (const gsl_vector * par_fit, void *data, gsl_vector * f) { std::cout << "G_F! "; uint n = ((struct data*) data)->n; double *y = ((struct data *)data)->y; double *x = ((struct data*) data)->x; double *sigma = ((struct data *) data)->sigma; //uaktualniamy nowe dopasowane wartosci for (uint i = 0; i < num_par; i++) p[permut[i]] = gsl_vector_get (par_fit,i); for (uint i = 0; i < n; i++) { double t = x[i]; double Yi = G_val (t); gsl_vector_set (f, i, (Yi - y[i])/sigma[i]); } return GSL_SUCCESS; } //*/ // QString Analyzer :: Par (int i) { // if (tableParameters->item(i,0)->background() == Qt::gray) return tableParameters->item(i,0)->text(); //jezeli param jest zablokowany, to wpisujemy do rownania jego wartosc // // //jezeli dopasowujemy parametr - trezba go wpisac jako A0 / A1 /... itp. // QString str = "A"; // str += QString::number (reverse_permut[i]); // return str; // } /////////////// /* GraceRegisterErrorFunction(my_error_function); // Start Grace with a buffer size of 2048 and open the pipe if (GraceOpen(2048) == -1) { fprintf(stderr, "Can't run Grace. \n"); exit(EXIT_FAILURE); } GracePrintf("s0 on"); GracePrintf("title \"FCS fit\""); GracePrintf("s0 symbol 1"); GracePrintf("s0 symbol size 0.2"); GracePrintf("s0 symbol fill pattern 1"); // Send plot data to Grace for (uint i = 0; i < n && GraceIsOpen(); i++) GracePrintf("g0.s0 point %lf, %lf", krzywa->x(start+i), krzywa->y(start+i)); // std::cout << x[i] << ", " << y[i] <<"\n"; if (GraceIsOpen()) { GracePrintf("xaxes scale logarithmic \n autoscale \n saveall \"sample.agr\""); QString s = "fit formula \"y = "; //here comes our formula: triplet, bleaching, 1st, 2nd, 3rd diffusion, +1 to normalize g(2) s += ""+Par(0)+" * (1+"+Par(2)+"*exp(-x/"+Par(3)+")-"+Par(2)+")/(1-"+Par(2)+")\ * (1+"+Par(10)+"*exp(-x/"+Par(9)+")-"+Par(10)+")\ * ("+Par(5)+"/(1+x/"+Par(4)+")/sqrt(1+x/("+Par(1)+"*"+Par(1)+"*"+Par(4)+"))\ + "+Par(7)+"/(1+x/"+Par(6)+")/sqrt(1+x/("+Par(1)+"*"+Par(1)+"*"+Par(6)+"))\ + (1-"+Par(5)+"-"+Par(7)+")/(1+x/"+Par(8)+")/sqrt(1+x/("+Par(1)+"*"+Par(1)+"*"+Par(8)+"))\ ) + 1"; s += "\" \n"; GracePrintf(s.toAscii()); printf (s.toAscii()); s = "fit with "; s += QString::number(num_par); s += " parameters\n fit prec 0.05 \n"; // \n needed? // std::cout << s.toStdString(); GracePrintf(s.toAscii()); //write out initial parameters to Grace for (uint i = 0; i < num_par; i++) { s = ""; //Special cases: constraints! Ograniczenia dla czasow: 0-100000000us, ogr. dla ulamkow: 0-1 if (permut[i]==0 || permut[i]==1 || permut[i]==3 || permut[i]==4 || permut[i]==6 || permut[i]==8 || permut[i]==9) s += "A" + QString::number(i) + " = " + QString::number(p[permut[i]]) + "\n A" + QString::number(i)+" constraints on\n A"+QString::number(i)+"min = 0 \n A"+QString::number(i)+"max = 1e8\n"; else s += "A" + QString::number(i) + " = " + QString::number(p[permut[i]]) + "\n A" + QString::number(i)+" constraints on\n A"+QString::number(i)+"min = 0 \n A"+QString::number(i)+"max = 1\n"; // printf (s.toAscii()); GracePrintf(s.toAscii()); } //Perform fit s = ""; s += "nonlfit (s0, "+QString::number(n)+")\n"; GracePrintf (s.toAscii()); //Store fit parameters in a new dataset s = "s1 on \n s1 length "; s += QString::number (num_par); for (uint i = 0; i < num_par; i++) s += "\ns1.x["+QString::number(i)+"] = " + QString::number(i) + "\ns1.y["+QString::number(i)+"] = A"+QString::number(i); GracePrintf (s.toAscii()); //save the dataset with parameters to a file GracePrintf ("WRITE s1 FILE \"par.fit\""); GraceClose(); //add info which param is which FILE * fpar = fopen ("par.fit","a"); for (uint i=0;i<num_par;i++) { fprintf (fpar, "%d %s\n", i, tableParameters->verticalHeaderItem(permut[i])->text().data()); } fclose(fpar); } else exit(EXIT_FAILURE); //back to our program: read params file & update our variables std::ifstream fpar ("par.fit"); for (uint i = 0; i < num_par; i++) { fpar >> p[permut[i]]; fpar >> p[permut[i]];} //HACK pierwsza liczba jest niewazna (numer parametru), wiec ja nadpiszemy */ <file_sep>/src/program.h #ifndef _MW_PROGRAM_H_ #define _MW_PROGRAM_H_ #include "ui_Main_analyzer.h" #include "analyzer.h" #include <QTabWidget> #include <QMessageBox> #include <QFileDialog> #include <QWidget> //#include <qwt_plot.h> // #include <qwt_plot_curve.h> // #include <qwt_scale_engine.h> // #include <qwt_plot_marker.h> // #include "tableparams.h" #include "fcs_loader.h" class Program : public QMainWindow, public Ui::MainWindow { //could be Ui_MainWindow as well Q_OBJECT private: private slots: void OpenFCSFile (); void OpenASCII (); void OpenRAWFile (); void RemoveTab (int index); void on_actionSaveAll_triggered (); void on_actionFitAll_triggered (); void on_butLoadSimul_clicked (); protected: void keyPressEvent (QKeyEvent * e); public: Program (); // public slots: }; #endif //_MW_PROGRAM_H_ <file_sep>/src/tableparams.h #ifndef _MY_TABLE_ #define _MY_TABLE_ #include <QMessageBox> #include <QTableWidget> #include <QHeaderView> #include <math.h> namespace SM { enum SwitchModes { OFF = 0, ON, SWITCH }; }; class TableParams : public QTableWidget { Q_OBJECT private: public: TableParams (QWidget * parent); public slots: void lockCell (int r, SM::SwitchModes mode); void setValue (double v, int r, int c); private slots: // void on_cellChanged (int r,int c); void emit_cellValueSet (int r,int c); signals: void cellValueSet (double v, int r, int c); }; #endif //_MY_TABLE_ <file_sep>/src/program.cpp #include "program.h" #include <stdio.h> Program :: Program () { setupUi (this); tabWidget->clear(); connect (butLoadFCSData, SIGNAL (clicked()), this, SLOT (OpenFCSFile())); //DONE Ha-ha! :) connect (butLoadASCIIData, SIGNAL (clicked()), this, SLOT (OpenASCII())); //DONE Ha-ha! :) connect (butLoadRAW, SIGNAL (clicked()), this, SLOT (OpenRAWFile())); connect (tabWidget, SIGNAL (tabCloseRequested (int)), this, SLOT (RemoveTab (int))); } void Program :: keyPressEvent (QKeyEvent * e) { int k = e->key(); int m = e->modifiers(); int i = tabWidget->currentIndex(); if (k == Qt::Key_W && m == Qt::ControlModifier) tabWidget->removeTab(i); //close tab else if (k == Qt::Key_PageDown && m == Qt::ControlModifier) { //next tab if (tabWidget->currentIndex() == tabWidget->count()-1) tabWidget->setCurrentIndex (0); else tabWidget->setCurrentIndex (tabWidget->currentIndex() + 1); } else if (k == Qt::Key_PageUp && m == Qt::ControlModifier) { //previous tab if (tabWidget->currentIndex() == 0) tabWidget->setCurrentIndex (tabWidget->count () - 1); else tabWidget->setCurrentIndex (tabWidget->currentIndex() - 1); } } void Program :: RemoveTab (int index) { tabWidget->removeTab (index); } void Program :: OpenFCSFile () { QStringList name_list = QFileDialog :: getOpenFileNames (NULL,tr("Open FCS data file"),"~",tr("Correlation function files (*.fcs);;All files (*.*)")); if (name_list.size() == 0) {QMessageBox::information( NULL, "Information", "No file selected.");return;} QStringList::Iterator it = name_list.begin(); while(it != name_list.end()) { Analyzer * nowy_tab = new Analyzer (this); nowy_tab->OpenFCSFile(*it); tabWidget->addTab (nowy_tab, nowy_tab->filename); tabWidget->setCurrentWidget (nowy_tab); ++it; } } void Program :: OpenASCII () { Analyzer * nowy_tab = new Analyzer (this); nowy_tab->OpenASCII(); tabWidget->addTab (nowy_tab, "ASCII"); tabWidget->setCurrentWidget (nowy_tab); } void Program :: OpenRAWFile () { Analyzer * nowy_tab = new Analyzer (this); nowy_tab->OpenRAWFile(); tabWidget->addTab (nowy_tab, "RAW"); tabWidget->setCurrentWidget (nowy_tab); } void Program :: on_butLoadSimul_clicked () { QStringList name_list = QFileDialog :: getOpenFileNames (NULL,tr("Open simulated correlation file"),"~",tr("ASCII Data files (*.dat);;All files (*)")); if (name_list.size() == 0) {QMessageBox::information( NULL, "Information", "No file selected.");return;} QStringList::Iterator it = name_list.begin(); while(it != name_list.end()) { Analyzer * nowy_tab = new Analyzer (this); nowy_tab->OpenSimulated(*it); tabWidget->addTab (nowy_tab, nowy_tab->filename); tabWidget->setCurrentWidget (nowy_tab); ++it; } } void Program :: on_actionSaveAll_triggered () { //autoconnect actually works!! QString name = QFileDialog :: getSaveFileName (this,tr("Select a new output file"),tr("~"),tr("Parameter files (*.par);;All files (*.*)")); if (name == NULL) {QMessageBox::information( NULL, "Information", "Output file not selected.");return;} FILE * fp = fopen (name.toAscii(), "wt"); fprintf (fp, "name\t\t\tG0\t\tSP\t\tT\t\tt_T\t\tt_D1\t\tA1\t\tt_D2\t\tA2\t\tt_D3\t\tt_bl\t\tB\t\tChi^2\n"); for (int i = 0; i < tabWidget->count(); i++) { Analyzer * anal = (Analyzer *) tabWidget->widget(i); fprintf (fp, "%s\t",tabWidget->tabText(i).toAscii().data()); for (uint j = 0; j < NUM_PARAMS; j++) { if (anal->tableParameters->item(j,0)->background() != Qt::gray) fprintf (fp, "%le\t", anal->tableParameters->item(j,0)->text().toDouble()); else fprintf (fp, "(%le)\t", anal->tableParameters->item(j,0)->text().toDouble()); } fprintf (fp, "%le\t",anal->lblChiSqr->text().toDouble()); fprintf (fp, "\n"); } fclose(fp); QMessageBox::information( NULL, "Finished", QString("All fit parameters saved to: ")+name); } void Program :: on_actionFitAll_triggered () { Analyzer * curr = (Analyzer *) tabWidget->widget(tabWidget->currentIndex ()); stBar->showMessage ("Fitting..."); //timeout=20s for (int i = 0; i < tabWidget->count(); i++) { Analyzer * anal = (Analyzer *) tabWidget->widget(i); for (uint p = 0; p < NUM_PARAMS; p++) { anal->tableParameters->item(p,0)->setBackground (curr->tableParameters->item(p,0)->background()); anal->tableParameters->item(p,0)->setText(QString::number(curr->tableParameters->item(p,0)->text().toDouble())); } anal->inputBaseLine->setText (curr->inputBaseLine->text()); //baseline anal->comboModel->setCurrentIndex (curr->comboModel->currentIndex()); if (!actionKeepSeparateFitLimits->isChecked()) { //if we uncheck the "Keep separate ..." menu item, force all limits to the same values anal->fitFrom->setText (curr->fitFrom->text()); //granice anal->fitTo->setText (curr->fitTo->text()); } anal->Fit(); } stBar->showMessage ("Fitting all functions complete!", 10000); //timeout=20s } <file_sep>/src/main.cpp #include "program.h" #include <iostream> #ifdef __WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif //__WIN32 #include <stdio.h> #include <malloc.h> int main(int argc, char *argv[]) { #ifdef __WIN32 // Create the application's console if ( AllocConsole() == 0 ) { ::MessageBox( 0, L"Can't allocate console!\n", L"** FCS_analyzer **", MB_OK | MB_ICONSTOP ); return false; } //(?) add better error handling code later... freopen( "CON", "w", stderr); freopen( "CON", "w", stdout); // std::ios::sync_with_stdio(); // This is often nifty to know... char* cwd = new char[ MAX_PATH + 1 ]; GetCurrentDirectoryA( MAX_PATH, cwd ); std::cout << "CWD = " << cwd << std::endl; delete [] cwd; #endif //__WIN32 //QApplication a(argc, argv); QApplication app(argc, argv); Program * okno = new Program; okno->show(); app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) ); int app_rv = app.exec(); return app_rv; } <file_sep>/src/fcs_loader.cpp #include "fcs_loader.h" using namespace Info; using std::cout; QString FCS_Info :: ReadLine(QFile* fp) { QString line = fp->readLine(); return line.trimmed(); } void FCS_Info :: Print (std::ostream & out) { out << "Method\t\t" << method.Name.toAscii().data() << " ("<<method.Comment.toAscii().data()<<") from "<<method.Date.toAscii().data() <<"\n"; out << "Measure date\t" << method.MeasureDate.toAscii().data() << "\n"; out << "Number of experiments (repeats): "<< repeats<<"\n"; for (uint c=0;c<correlation.size();c++) { out << "Correlation #" <<c<<":\n"; for (int i=0;i<5;i++) {out << correlation[c][i].x << "\t" <<correlation[c][i].y << "\n";} } for (uint c=0;c<countrate.size();c++) { out << "Countrate #" <<c<<":\n"; for (int i=0;i<5;i++) {out << countrate[c][i].x << "\t" <<countrate[c][i].y << "\n";} } } void FCS_Info :: ReadLasers(QFile* fp) { } double FCS_Info :: AvgIntensity (int i) { double total = 0; for (uint a = 0; a < countrate[i].size(); a++) total += countrate [i][a].y; return (total / countrate[i].size()); } void FCS_Info :: ReadMeasureParams (QFile * fp) { QString line; int begins = 1; while ((line = ReadLine (fp))!=NULL) { QStringList words = line.split(QString(" = "),QString::SkipEmptyParts); // for (int i=0;i<words.size();i++) {cout << i << ": " <<words[i].toAscii().data() << "|\n";} if (words[0] == "MethodName") method.Name = words[1]; if (words[0] == "MethodComment") method.Comment = words[1]; if (words[0] == "MethodDate") method.Date = words[1]; if (words[0] == "MeasureDate") method.MeasureDate = words[1]; words = line.split (" ",QString::SkipEmptyParts); //podzielmy na poszczegolne slowa if (words[0] == "BEGIN") { begins ++; cout << line.toAscii().data() <<"\n"; cout << begins << " "; if (line == "BEGIN Lasers 10000") ReadLasers (fp); // if (line == "BEGIN Correlations 10000") ReadCorrelationsInfo (fp); //is it needed? } else if (words[0] == "END") { begins --; if (begins <= 0) {cout << "END reached, params reading finished.\n"; return;} } } } //TODO? histogram zliczen, parametry fitu void FCS_Info :: ReadCountrate(QFile* fp) { QString line; int begins = 1; std::cout << "Reading countrates...";//////////////////////// while ((line = ReadLine (fp))!=NULL) { QStringList words = line.split(QString(" = "),QString::SkipEmptyParts); if (words[0] == "CountRateArrayUsage") { int num_channels = words[1].toInt(); countrate[countrates_loaded].resize(num_channels); ReadLine (fp); //skip "CountRateArray = num_channels 2" line for (int i=0;i<num_channels;++i) { line = ReadLine (fp); words = line.split(QString(" "),QString::SkipEmptyParts); countrate[countrates_loaded][i].x = words[0].toDouble(); countrate[countrates_loaded][i].y = words[1].toDouble(); } } //TODO maybe: read histogram? if (words[0] == "BEGIN") {begins ++; cout << line.toAscii().data() <<"\n"; cout << begins << " ";} else if (words[0] == "END") {begins --;if (begins <= 0) {cout << "END reached, countrate reading finished.\n"; countrates_loaded ++; return;}} } } void FCS_Info :: ReadCorrelation(QFile* fp) { QString line; int begins = 1; std::cout << "Reading correlations...";//////////////////////// while ((line = ReadLine (fp))!=NULL) { QStringList words = line.split(QString(" = "),QString::SkipEmptyParts); if (words[0] == "CorrelationArrayUasge") { int num_channels = words[1].toInt(); correlation[corrs_loaded].resize(num_channels); ReadLine (fp); //skip "CorrelationArray = num_channels 2" line for (int i=0;i<num_channels;++i) { line = ReadLine (fp); words = line.split(QString(" "),QString::SkipEmptyParts); correlation[corrs_loaded][i].x = words[0].toDouble()*10; //NOTE w "oryginalnych" plikach .fcs jednostka jest 10 us!! correlation[corrs_loaded][i].y = words[1].toDouble(); } } if (words[0] == "BEGIN") {begins ++; cout << line.toAscii().data() <<"\n"; cout << begins << " ";} else if (words[0] == "END") {begins --;if (begins <= 0) {cout << "END reached, correlation reading finished.\n"; corrs_loaded ++; return;}} } } /* ------------- Glowna funkcja ladujaca plik FCS --------------- */ bool FCS_Info :: LoadFCSFile (QString filename) { //check if file's ok QFile fp (filename); if (!fp.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning( NULL, "Error", "Could not open file."); return false; } //Read header QString line = ReadLine (&fp); if (line != "<NAME>foCor2 - measurement data file Version 2.1") { QMessageBox::warning( NULL, "Error", QObject::tr("Incorrect file version: %1.").arg(line)); return false; } while ((line = ReadLine (&fp)) != NULL) { QStringList words = line.split(QString(" = "),QString::SkipEmptyParts); if (words[0] == "RepeatCount") {repeats = words[1].toInt();} if (words[0] == "NumberPositions") {repeats = repeats * words[1].toInt(); correlation.resize(repeats); countrate.resize(repeats);} //total #correlations = repeats * NumberPositions if (line == "BEGIN MeasureParameters 10001") ReadMeasureParams (&fp); if (line == "BEGIN Channel0 10001") ReadCountrate (&fp); if (line == "BEGIN Correlation0 10001") ReadCorrelation (&fp); } if (corrs_loaded != repeats) {std::cerr << "ERROR: only "<<corrs_loaded<<" out of "<<repeats<<" correlations loaded."; return false;} if (countrates_loaded != repeats) {std::cerr << "ERROR: only "<<countrates_loaded<<" out of "<<repeats<<" count rates loaded."; return false;} return true; } QString FCS_Info :: GetMeasurementInfo () { QString a; a += method.Name +'\n'+ method.Comment +'\n'+ method.Date +'\n'+ method.MeasureDate +'\n'+ method.User; return a; } /* //-----Beam Path-----// bp.Name = Trim(pLista->Values["BeamPathName "]); bp.Pinhole_Adjustment = Trim(pLista->Values["PinholeAdjustment "]); int CountDetectors = StrToInt(pLista->Strings[pLista->IndexOf("BEGIN Detectors 10000")+1].SubString(9,pLista->Strings[pLista->IndexOf("BEGIN Detectors 10000")+1].Length()-8)); wiersz = pLista->IndexOf("BEGIN Detectors 10000")+3; for(int i=1; i<=CountDetectors;i++) { Beam1.Channel_Name +="CH"+IntToStr(i)+": "+pLista->Strings[wiersz].SubString(16,pLista->Strings[wiersz].Length()-15)+" "; Beam1.Pinhole_Diameter +="CH"+IntToStr(i)+": "+pLista->Strings[wiersz+2].SubString(27,pLista->Strings[wiersz+2].Length()-26)+" "; Beam1.Emission_Filter +="CH"+IntToStr(i)+": "+pLista->Strings[wiersz+7].SubString(22,pLista->Strings[wiersz+7].Length()-21)+" "; Beam1.Pinhole_Position +=" CH"+IntToStr(i)+": "; for(int j=1;j<=3;j++) { Beam1.Pinhole_Position +=pLista->Strings[wiersz+2+j].SubString(28,pLista->Strings[wiersz+2+j].Length()-27)+"/"; } wiersz =(pLista->IndexOf("BEGIN Detectors 10000")+3)+i*10; } int CountBeamsplitters = StrToInt(pLista->Strings[pLista->IndexOf("BEGIN BeamSplitters 10000")+1].SubString(9,pLista->Strings[pLista->IndexOf("BEGIN BeamSplitters 10000")+1].Length()-8)); wiersz = pLista->IndexOf("BEGIN BeamSplitters 10000")+4; for(int i=1; i<=CountBeamsplitters;i++) { Beam1.Splitters +=pLista->Strings[wiersz].SubString(26,pLista->Strings[wiersz].Length()-25)+", "; wiersz = (pLista->IndexOf("BEGIN BeamSplitters 10000")+4)+i*4; } int CountCollimators = StrToInt(pLista->Strings[pLista->IndexOf("BEGIN Collimators 10000")+1].SubString(9,pLista->Strings[pLista->IndexOf("BEGIN Collimators 10000")+1].Length()-8)); wiersz = pLista->IndexOf("BEGIN Collimators 10000")+4; for(int i=1; i<=CountCollimators;i++) { Beam1.Collimator +=pLista->Strings[wiersz].SubString(22,pLista->Strings[wiersz].Length()-21)+", "; wiersz =(pLista->IndexOf("BEGIN Collimators 10000")+4)+i*4; } //---------Lasers----------// int CountLasers = StrToInt(pLista->Strings[pLista->IndexOf("BEGIN Lasers 10000")+1].SubString(9,pLista->Strings[pLista->IndexOf("BEGIN Lasers 10000")+1].Length()-8)); wiersz = pLista->IndexOf("BEGIN Lasers 10000")+3; float Procent; for(int i=1; i<=CountLasers;i++) { Laser1.Name +=IntToStr(i)+") "+pLista->Strings[wiersz].SubString(13,pLista->Strings[wiersz].Length()-12)+", "; Buffer = Trim(pLista->Strings[wiersz+2].SubString(22,pLista->Strings[wiersz+2].Length()-21)); if(DecimalSeparator == ',') { Buffer.Insert(',',Buffer.Pos('.')); Buffer.Delete(Buffer.Pos('.'),1); } Procent = StrToFloat(Buffer)*100; Buffer = FloatToStr(Procent)+"%"; Laser1.Power +=IntToStr(i)+") "+Buffer+" of " +pLista->Strings[wiersz+1].SubString(14,pLista->Strings[wiersz+1].Length()-13)+", "; wiersz = (pLista->IndexOf("BEGIN Lasers 10000")+3)+i*6; } int CountAttenuators = StrToInt(pLista->Strings[pLista->IndexOf("BEGIN Attenuators 10000")+1].SubString(9,pLista->Strings[pLista->IndexOf("BEGIN Attenuators 10000")+1].Length()-8)); wiersz = pLista->IndexOf("BEGIN Attenuators 10000")+3; for (int i=1;i<=CountAttenuators;i++) { Buffer = Trim(pLista->Strings[wiersz+1].SubString(27,pLista->Strings[wiersz+1].Length()-26)); if(DecimalSeparator == ',') { Buffer.Insert(',',Buffer.Pos('.')); Buffer.Delete(Buffer.Pos('.'),1); } Procent = StrToFloat(Buffer)*100; Buffer = FloatToStr(Procent)+"%"; Laser1.Transmission += IntToStr(i)+") "+pLista->Strings[wiersz].SubString(24,pLista->Strings[wiersz].Length()-23)+" : "+ Buffer+" , "; wiersz = (pLista->IndexOf("BEGIN Attenuators 10000")+3)+i*5; } //----------Times-----------// Time1.Bleach = Trim(pLista->Values["BleachTime "]); Time1.Measure = Trim(pLista->Values["MeasureTime "]); //------RepeatCount i Kinetics------// Repeat_Count = StrToInt(Trim(pLista->Values["RepeatCount "])); Kinetics = Trim(pLista->Values["Kinetics "]); //-----Measure Date--------------// MeasureDate = Trim(pLista->Values["MeasureDate "]); */ <file_sep>/src/fit_gsl.cpp #include "analyzer.h" #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlin.h> //#define N 40 #define MAX_ITERS 50 uint num_par = 0; //number of fitted parameters double p [NUM_PARAMS]; //tablica aktualnych wartosci wszystkich parametrow (czesc nie bedzie sie zmieniac) double par_init [NUM_PARAMS]; //poczatkowe guessy - tylko fitowane (po permutacji) int permut [NUM_PARAMS]; //tablica permutacyjna: permut[i] - ktory element z wektora p znajduje sie na i-tej pozycji w par_init struct data { uint n; double * x; double * y; double * sigma; }; static void print_state (size_t iter, gsl_multifit_fdfsolver * s) { printf ("iter: %3u x = % 15.8f " "|f(x)| = %g\n", iter, gsl_vector_get (s->x, 0), gsl_blas_dnrm2 (s->f)); /////DEBUG, TODO poprawic } //Oblicza wartosc funkcji dla zadanego opoznienia t i aktualnych parametrow double G_val (double t, const double new_params [NUM_PARAMS] = NULL) { if (new_params == NULL) return p[0] * (1 + p[2]*exp(-t/p[3]) - p[2]) / (1 - p[2]) //triplet * (1 + p[10]*exp(-t/p[9]) - p[10]) //bleaching * ( p[5] / (1+t/p[4]) / sqrt(1 + t/(p[1]*p[1]*p[4])) //1st diffusion + p[7] / (1+t/p[6]) / sqrt(1 + t/(p[1]*p[1]*p[6])) //2nd diffusion + (1-p[5]-p[7]) / (1+t/p[8]) / sqrt(1 + t/(p[1]*p[1]*p[8])) //3rd diffusion ) + 1; // +1, bo nieznormalizowana g(2) else return new_params[0] * (1 + new_params[2]*exp(-t/new_params[3]) - new_params[2]) / (1 - new_params[2]) //triplet * (1 + new_params[10]*exp(-t/new_params[9]) - new_params[10]) //bleaching * (new_params[5] / (1+t/new_params[4]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[4])) //1st diffusion + new_params[7] / (1+t/new_params[6]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[6])) //2nd diffusion + (1-new_params[5]-new_params[7]) / (1+t/new_params[8]) / sqrt(1 + t/(new_params[1]*new_params[1]*new_params[8])) //3rd diffusion ) + 1; // +1, bo nieznormalizowana g(2) // double G0 = gsl_vector_get (par,0); // double SP = gsl_vector_get (par,1); // double T = gsl_vector_get (par,2); // double t_T = gsl_vector_get (par,3); // double t_D1 = gsl_vector_get (par,4); // double A1 = gsl_vector_get (par,5); // double t_D2 = gsl_vector_get (par,6); // double A2 = gsl_vector_get (par,7); // double t_D3 = gsl_vector_get (par,8); // double t_bl = gsl_vector_get (par,9); // double B = gsl_vector_get (par,10); } static double pochodna_numer (int a, double t) { //FIXME nie dziala? TODO const double wartosc = p[a]; const double h = 0.1*wartosc; //krok p[a] = wartosc + h; const double G_1 = G_val (t); p[a] = wartosc - h; const double G_2 = G_val (t); p[a] = wartosc; //przywracamy stara wartosc a-tego parametru return (G_1-G_2)/2/h; //3-pktowa } //Wartosc pochodnej po parametrze a w punkcie t static double pochodna_par (int a, double t) { //TODO przepisac rownania z maximy :) //zm. pomocnicze dla przyspieszenia obliczen double Gv = G_val (t); double nawias_T = (1 + p[2]*exp(-t/p[3]) - p[2]); double nawias_B = (1 + p[9]*exp(-t/p[9]) - p[9]); double nawias_1 = p[5] / (1+t/p[4]) / sqrt(1 + t/(p[1]*p[1]*p[4])); double nawias_2 = p[7] / (1+t/p[6]) / sqrt(1 + t/(p[1]*p[1]*p[6])); double nawias_3 = (1-p[5]-p[7]) / (1+t/p[8]) / sqrt(1 + t/(p[1]*p[1]*p[8])); double nawiasy_123 = nawias_1 + nawias_2 + nawias_3; if (a==0) return Gv/p[0]; //dN else if (a==1) return nawias_T * nawias_B * p[0] * ( //dSP ((-p[7]-p[5]+1)*t)/(p[1]*p[1]*p[1]*p[8]*(t/p[8]+1)*(t/(p[1]*p[1]*p[8])+1)*sqrt(t/(p[1]*p[1]*p[8])+1)) + (p[7]*t)/(p[1]*p[1]*p[1]*p[6]*(t/p[6]+1)*(t/(p[1]*p[1]*p[6])+1)*sqrt(t/(p[1]*p[1]*p[6])+1)) + (p[5]*t)/(p[1]*p[1]*p[1]*p[4]*(t/p[4]+1)*(t/(p[1]*p[1]*p[4])+1)*sqrt(t/(p[1]*p[1]*p[4])+1)) ); else if (a==2) return p[0]*nawiasy_123*nawias_B * //dT (exp(-t/p[3]) - 1); else if (a==3) return p[0]*p[2]*t*nawiasy_123*nawias_B*exp(-t/p[3])/p[3]/p[3]; //dt_T else if (a==4) return p[0]*nawias_T*nawias_B * //dt_D1 //CHECK! TODO nie wiem czy dziala jak nalezy :/ (nawias_1*t/p[4]/p[4]/(1+t/p[4]) + nawias_1*t/p[4]/p[4]/2/(1+t/p[4]/p[1]/p[1])/p[1]/p[1]) ; else if (a==5) return p[0]*nawias_T*nawias_B * //dA1 (nawias_1/p[5]-nawias_3/(1-p[5]-p[7])) ; else if (a==6) return p[0]*nawias_T*nawias_B * //dt_D2 (nawias_2*t/p[6]/p[6]/(1+t/p[6]) + nawias_2*t/p[6]/p[6]/2/(1+t/p[6]/p[1]/p[1])/p[1]/p[1]) ; else if (a==7) return p[0]*nawias_T*nawias_B * //dA2 (nawias_2/p[7]*-nawias_3/(1-p[5]-p[7])) ; else if (a==8) return p[0]*nawias_T*nawias_B * //dt_D3 (nawias_3*t/p[8]/p[8]/(1+t/p[8]) + nawias_3*t/p[8]/p[8]/2/(1+t/p[8]/p[1]/p[1])/p[1]/p[1]) ; else if (a==9) return p[0]*p[10]*t*nawiasy_123*nawias_T*exp(-t/p[9])/p[9]/p[9]; //dt_bl else if (a==10) return p[0]*nawias_T*nawiasy_123*(exp(-t/p[9])-1) ; //dB else {std::cerr << "Invalid parameter number!"; exit (2);} } //Funkcja ustawiajaca macierz J wedlug zadanego rownania //par - wektor parametrow, data - dane, J - jakobian - macierz pochodnych // czastkowych funkcji po kolejnych parametrach dopasowywanych dla calej dziedziny funkcji static int G_df (const gsl_vector * par, void *data, gsl_matrix * J) { std::cout << "g_dF! "; uint n = ((struct data *)data)->n; double *sigma = ((struct data *) data)->sigma; //skroty do danych double *x = ((struct data *) data)->x; for (uint j = 0; j < num_par; j++) printf ("Pochodna (x=0)[%d]: %lf, numerycznie: %lf\n",j,pochodna_par (permut[j],x[0]), pochodna_numer (permut[j],x[0])); for (uint i = 0; i < n; i++) //jedziemy po wszystkich danych { /* Jacobian matrix J(i,j) = dfi / dpj, */ /* where fi = (Yi - yi)/sigma[i], */ /* Yi = wartosc funkcji obliczona */ /* and the pj are the parameters (N,tau_D, etc.) */ for (uint j = 0; j < num_par; j++) { gsl_matrix_set (J, i, j, pochodna_par (permut[j],x[i]) / sigma[i]); } } return GSL_SUCCESS; } static int G_f (const gsl_vector * par_fit, void *data, gsl_vector * f) { std::cout << "G_F! "; uint n = ((struct data*) data)->n; double *y = ((struct data *)data)->y; double *x = ((struct data*) data)->x; double *sigma = ((struct data *) data)->sigma; //uaktualniamy nowe dopasowane wartosci for (uint i = 0; i < num_par; i++) p[permut[i]] = gsl_vector_get (par_fit,i); for (uint i = 0; i < n; i++) { double t = x[i]; double Yi = G_val (t); gsl_vector_set (f, i, (Yi - y[i])/sigma[i]); } return GSL_SUCCESS; } //zbiorcza funkcja int G_fdf (const gsl_vector * par_fit, void *data, gsl_vector * f, gsl_matrix * J) { std::cout << "FDF! "; G_f (par_fit, data, f); G_df (par_fit, data, J); return GSL_SUCCESS; } bool Analyzer :: Fit () { if (!CalculateAverageCorrelation()) //leave only one (average) function & check if there's anything to fit to :) { printf ("Average correlation could not be calculated.\n"); return false;} //Fill in the permutation table num_par = 0; for (int i = 0; i < NUM_PARAMS; i++) { p[i] = tableParameters->item(i,0)->text().toDouble(); if (tableParameters->item(i,0)->background() != Qt::gray) { //jezeli mamy dopasowywac dany parametr par_init[num_par] = p[i]; permut[num_par] = i; //to wpisujemy go do tablicy permutacyjnej std::cout << "used: "<<i<<" ("<<num_par<<") ("<<p[permut[num_par]]<<"="<<p[i]<<") "; num_par++; } } if (num_par == 0) {fprintf (stderr, "Error: no free parameters for fit.\n"); return false;} //Load curve data into the arrays QList<QwtPlotItem*> lista = qwtPlotCF->itemList(); if (lista.size()!=1) {printf ("Warning: more than one curve on the plot!!\n");} QwtPlotCurve* krzywa = (QwtPlotCurve*) lista[0]; //dopasowujemy do I krzywej z wykresu const uint start = fitFrom->text().toUInt(); const uint n = fitTo->text().toUInt() - fitFrom->text().toUInt();//krzywa->dataSize(); //n-dlugosc traj TODO printf ("\nnum_par = %d, n = %d (od %d do %d)\n",num_par,n,start,fitTo->text().toUInt()); //debug if (n < num_par) {printf ("Too few data points (n<p), cannot fit!\n"); return false;} double x[n], y[n], sigma[n]; struct data d = { n, x, y, sigma}; //d - "skrot" do danych for (uint i = 0; i < n; ++i) { x[i] = krzywa->x(start+i); y[i] = krzywa->y(start+i); // std::cout << x[i] << ", " << y[i] <<"\n"; sigma[i] = y[i]; } gsl_vector_view par = gsl_vector_view_array (par_init, num_par); //Chcemy stworzyc gsl_vector z double[] array'a (a nie ma tu konstruktora) gsl_multifit_function_fdf f; //f - struct. opisujaca dopasowywana funkcje f.f = &G_f; f.df = &G_df; f.fdf = &G_fdf; f.n = n; f.p = num_par; f.params = &d; //ustawiamy rodzaj solvera (chyba jedyny dostepny to Levenberg-Marquard ;) ) const gsl_multifit_fdfsolver_type * T = gsl_multifit_fdfsolver_lmsder; gsl_multifit_fdfsolver * s = gsl_multifit_fdfsolver_alloc (T, n, num_par); // s - nasz solver gsl_multifit_fdfsolver_set (s, &f, &par.vector); unsigned int iter = 0; int status; print_state (iter, s); //debug do { iter++; status = gsl_multifit_fdfsolver_iterate (s); //iteracja dopasowywania printf ("status = %s\n", gsl_strerror (status)); print_state (iter, s); if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-5, 1e-5); //testujemy, czy jestesmy w granicach (epsilon) } while (status == GSL_CONTINUE && iter < MAX_ITERS); gsl_matrix *covar = gsl_matrix_alloc (num_par, num_par); //covar - macierz kowariancji (do obliczenia bledow) gsl_multifit_covar (s->J, 0.0, covar); #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) double chi = gsl_blas_dnrm2(s->f); double dof = n - num_par; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); printf ("chisq/dof = %g\n", chi*chi / dof); for (uint i = 0; i < num_par; i++) printf ("p[%d]\t = %.5f +/- %.5f\n", permut[i], FIT(i), c*ERR(i)); printf ("status = %s\n", gsl_strerror (status)); //uaktualniamy nowe dopasowane wartosci (Not sure if necessary) for (uint i = 0; i < num_par; i++) p[permut[i]] = gsl_vector_get (s->x,i); //display results back in tableParameters for (uint i = 0; i < NUM_PARAMS; i++) tableParameters->item(i,0)->setText(QString::number(p[i])); gsl_multifit_fdfsolver_free (s); gsl_matrix_free (covar); DrawCorrelationFromParams(); return true; } <file_sep>/src/correlatorPAT.cpp #include "correlator.h" // #include "log.h" #define MAX_M 30 //max delay = 2^31 // NOTE observe the size of int!! CorrelatorPAT :: CorrelatorPAT (const vector<int>& channel/*, const double step_size, const int num_steps, const int _steps_per_bin*/) { //PAT = photon arrival times (dl. wektora = liczba fotonow w traj.) delay.clear(); corr.resize(MAX_M); for (vector<int>::const_iterator i = channel.begin(); i != channel.end(); i++) { static int iter = 0; for (uint d=0;d<delay.size();d++) { delay[d] += *i; //co ja chce miec w tym delay??!! // printf ("d=%d, delay[d]=%d\n",d,delay[d]); for (int m = 0; m < MAX_M; m++) { if ((1 << m) >= delay[d]) {corr[m] ++; break;} //TODO optimize! } } delay.push_back(0); if (iter%100 == 0) printf ("iter:=%d\n",iter); iter++; } double avg_intensity = (double)channel.size()/(double)delay[0]; for (int i=0;i<corr.size();i++) printf ("%d %lf \n",i,(double)corr[i]/avg_intensity); } CorrelatorPAT :: ~CorrelatorPAT () { } // double CorrelatorPAT :: Calculate_correlation (double time) { // // int k = int (time / bin_size); //k - delay (bin size units) // double sum = 0; // // assert (k>=0); // // for (int i=0;i<B-k;i++) { // if (photons[i]<0 || photons[i+k]<0) { //DEBUG // printf ("ERROR! ph[%d]= %d, ph[%d] = %d!\n",i,photons[i],i+k,photons[i+k]); // } // // assert (photons[i]>=0); // assert (photons[i+k]>=0); // sum += photons[i]*photons[i+k]; // } // double correlation = sum/((B - k)*(avg_intensity*avg_intensity)) - 1; //calculate the value of the correlation // return correlation; // } <file_sep>/src/logslider.h #ifndef _MY_LOG_SLIDER_ #define _MY_LOG_SLIDER_ #include <QMessageBox> #include <QSlider> #include <math.h> #ifndef ASSERT #ifdef assert #define ASSERT assert #else inline void ASSERT (bool warunek) {if (!warunek) {QMessageBox::critical( NULL, "Error:", "Assertion failed!"); abort();}} #endif //assert #endif //ASSERT class LogSlider : public QSlider { Q_OBJECT private: double k; double A; int r,c; //row & column of the table in which the slider value is shown (optional) public: LogSlider (QWidget * parent); void SetExpParams (double min, double max, int r, int c); //given the return-value limits, set Base, A and table positions. private slots: void calcExpValue (); void updateSlider (double v,int r,int c); //move the slider to the correct position when a value in the table is manually changed signals: void sendExp(double,int,int); }; #endif //_MY_LOG_SLIDER_ <file_sep>/Main_analyzer.h /**************************************************************************** ** Form interface generated from reading ui file 'Main_analyzer.ui' ** ** Created: Wed Mar 17 13:06:21 2010 ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ <file_sep>/README.md FCS-analyzer ============ GUI for fitting fluorescence correlation functions obtained from <NAME> Confocor 2 microscope. ###Install required libraries: - libqwt 5.2.2 - QT4 - C++ - qmake - levmar 2.4 by <NAME> and its dependencies: - f2c - libblas - liblapack Tested with Ubuntu 14.04. ``` sudo apt-get install libqwt-dev liblapack-dev libblas-dev f2c cd levmar-2.4; make ``` ###How to compile: - qmake - (make clean) - first time - make - ./FCS_analyzer ## Docs for the plotting library (qwt) http://qwt.sourceforge.net/class_qwt_plot_marker.html#af44231c2b63bb277706e4f515297c7b1 <file_sep>/src/zoomplot.cpp #include "zoomplot.h" #include <QMessageBox> #include <qwt_scale_widget.h> #include <qwt_scale_div.h> #include <QSize> #include <QMoveEvent> //overriden virtual protected function from QWidget :) void ZoomPlot :: mousePressEvent ( QMouseEvent * event ) { if (event->button() == Qt::LeftButton) { //LMB - zooming zoom_start_x = event->x();// - axisWidget(yLeft)->sizeHint().width(); zoom_start_y = event->y(); // - axis->sizeHint().width(); //na gorze nie ma skali, wiec nie trzeba :) kwadrat = new KwadratWidget(this); kwadrat->x1 = zoom_start_x; kwadrat->y1 = zoom_start_y; kwadrat->x2 = zoom_start_x; kwadrat->y2 = zoom_start_y; // std::cout << "Setting up a new KwadratWidget at "<<event->x()<<","<<event->y(); drawing = true; } /* else if (event->button() == Qt::MidButton) { } //ustaw lewy kraniec else if (event->button() == Qt::RightButton) { emit clicked(Qt::RightButton, invTransform (xBottom, event->x()-axisWidget(yLeft)->sizeHint().width()), invTransform (yLeft, event->y())); } //ustaw prawy kraniec*/ } void ZoomPlot :: mouseMoveEvent (QMouseEvent * event) { if (drawing) { kwadrat->x2 = event->x(); kwadrat->y2 = event->y(); kwadrat->repaint(); } } void ZoomPlot :: wheelEvent (QWheelEvent * event) { // std::cout << "Wheel: "<<event->delta()<<"\n"; //delta == -120 - w dol if (event->delta() < 0) { ZoomOut(); } } void ZoomPlot :: mouseReleaseEvent ( QMouseEvent * event ) { int mx = event->x() - axisWidget(yLeft)->sizeHint().width(); //current mouse coordinates int my = event->y(); //in reference to plot origin (w/o scale) if (event->button() == Qt::LeftButton) { //LMB - zooming drawing = false; delete kwadrat; zoom_start_x -= axisWidget(yLeft)->sizeHint().width(); if (mx == zoom_start_x || my == zoom_start_y) {std::cout << "Cannot zoom!\n"; return;} double to_x = invTransform (xBottom, mx), to_y = invTransform (yLeft, my); double from_x = invTransform (xBottom, zoom_start_x), from_y = invTransform (yLeft, zoom_start_y); ZoomIn (from_x,from_y,to_x,to_y); } else if (event->button() == Qt::MidButton) { emit clicked(Qt::MidButton, invTransform (xBottom, event->x()-axisWidget(yLeft)->sizeHint().width()), invTransform (yLeft, event->y()));} //ustaw lewy kraniec? else if (event->button() == Qt::RightButton) { emit clicked(Qt::RightButton, invTransform (xBottom, event->x()-axisWidget(yLeft)->sizeHint().width()), invTransform (yLeft, event->y()));} //ustaw prawy kraniec? } ZoomPlot :: ZoomPlot (QWidget * parent) : QwtPlot (parent) {drawing = false;} ZoomPlot :: ~ZoomPlot () {} void swap (double & a, double & b) { double c = a; a = b; b = c; } void ZoomPlot :: ZoomIn (double from_x, double from_y, double to_x, double to_y) { std::cout << "Zooming from "<<from_x<<","<<from_y<<" to "<<to_x<<","<<to_y<<std::endl; if (from_x > to_x) swap (from_x, to_x); if (from_y > to_y) swap (from_y, to_y); setAxisScale (xBottom, from_x, to_x); setAxisScale (yLeft, from_y, to_y); replot(); } // void ZoomPlot :: SaveScaleParams (double x1, double x2, double y1, double y2) { // //xmin = x1; xmax = x2; ymin = y1; ymax = y2; // } void ZoomPlot :: ZoomOut () { /* setAxisScale (xBottom, xmin, xmax); setAxisScale (yLeft, ymin, ymax);*/ setAxisAutoScale (xBottom);setAxisAutoScale (yLeft); replot(); } <file_sep>/src/correlator.h #ifndef _CORRELATOR_H_ #define _CORRELATOR_H_ #include <stdlib.h> #include <math.h> #include <stdio.h> #include <time.h> #include <vector> #include <assert.h> #define LOG printf using namespace std; /********************************** * Photon Arrival Times structure * **********************************/ class PAT { public: PAT () {b=k=0;} ~PAT () {} int b; //the index of the bin in which photon counts have been observed int k; //number of photon count in this bin void Zero () {b=k=0;} }; /************************* * Correlator base class * *************************/ class Correlator { protected: int steps_in_a_bin; //binning resolution for the calculation of the correlation function (how many frames fit in one bin?) int B; //total number of bins int K; //total number of photon counts double bin_size; //bin size in time units [ps] double avg_intensity; //average number of photons per bin public: Correlator (const double step_size, const int num_steps, const int _steps_per_bin) { if (num_steps%_steps_per_bin!=0) LOG ("*The number of steps (%d) is not an integer multiple of bin size (%d).\n",num_steps,_steps_per_bin); this->steps_in_a_bin = _steps_per_bin; B = num_steps / steps_in_a_bin; //save the total number of bins bin_size = steps_in_a_bin * step_size; K=0; } virtual ~Correlator () {} /*********************************************************** * Returns the value of the correlation function. * * Arguments: double time - correlation delay time in [ps] * ***********************************************************/ virtual double Calculate_correlation (double time)=0; }; /******************************************************** * Correlator implementation using the direct algorithm * ********************************************************/ class CorrelatorSimple : public Correlator { private: int * photons; //the array of photon counts in each bin public: CorrelatorSimple (int * distr, const double step_size, const int num_steps, const int _steps_per_bin); // CorrelatorSimple (const char* fluor_file, const double step_size, const int num_steps, const int _steps_per_bin); ~CorrelatorSimple (); double Calculate_correlation (double time); }; class CorrelatorPAT { private: vector<int> delay; //o ile atualny foton jest opozniony w stosunku do i-tego fot. vector<int> corr; //kolejne pkty na wykresie G(t), x_n = 2*x_{n-1} public: CorrelatorPAT (const vector<int> & channel); ~CorrelatorPAT (); // double Calculate_correlation (double time); }; #endif //_CORRELATOR_H_ <file_sep>/src/raw_loader.cpp #include "raw_loader.h" #include "fcs_loader.h" #include "correlator.h" /* --- Fragment odpalajacy okno dialogowe do ladowania funkcji z RAW ----*/ void Analyzer :: OpenRAWFile () { //First, clean up listFunctions->clear(); //wyczysc okienko z lista funckji if (info != NULL) delete info; // *** NEW *** // RawLoader * raw_loader = new RawLoader; raw_loader->exec(); //NOTE: if successful, this dialog will also allocate mem for FCS_Info structure (and load it) //jesli kliknelismy FINISH, zamykamy dialog i pakujemy funkcje korelacji do glownego okienka if (raw_loader->result() == QDialog::Accepted) info = raw_loader->Wynik(); if (info == NULL) {QMessageBox::information( NULL, "Information", "No file loaded.");return;} delete raw_loader; for (int i=0;i<info->num_repeats();i++) { //dodaj funkcje korelacji do okienka QListWidgetItem * item = new QListWidgetItem; item->setText(tr("Function %1: %2").arg(i+1).arg(info->AvgIntensity(i))); listFunctions->addItem (item); // DrawFunction (info->countrate[i], tr("Intensity #%1").arg(i), qwtPlotIntensity); //namaluj funkcje na wykresie // DrawFunction (info->correlation[i], tr("Correlation #%1").arg(i), qwtPlotCF_2); } // if (name.length() > 25) filename = QString ("...") + name.right(25); // else filename = name; fitFrom->setText (QString::number(0)); fitTo->setText (QString::number(info->correlation[0].size()));//*/ } RawLoader :: RawLoader () : info (NULL) { setupUi (this); connect (butLoadRAW, SIGNAL (clicked()), this, SLOT (OpenRAWFile())); connect (butCalculateIntensity, SIGNAL (clicked()), this, SLOT (CalculateIntensity())); connect (butCalculateCorrelation, SIGNAL (clicked()), this, SLOT (CalculateRAWCorrelation())); connect (butFinish, SIGNAL (clicked()), this, SLOT (accept())); connect (butCalcCorrRightAway, SIGNAL (clicked()), this, SLOT (CalcCorrRightAway())); sliderDT->SetExpParams (labDT_min->text().toDouble(), labDT_max->text().toDouble(),0,0); /////// testing connect (sliderDT, SIGNAL(sendExp(double,int,int)), inputDT, SLOT(setValue(double,int,int))); /////// testing connect (inputDT, SIGNAL(cellValueSet(double,int,int)), sliderDT, SLOT (updateSlider(double,int,int)));/////// testing QwtScaleEngine * log_engine = new QwtLog10ScaleEngine; qwtPlotCF_2->setAxisScaleEngine (QwtPlot::xBottom, log_engine); }; /* ------ Glowna funkcja ladujaca plik RAW --------- */ void RawLoader :: OpenRAWFile() { QString name = QFileDialog :: getOpenFileName (NULL,tr("Open RAW data file"),"~",tr("RAW intensity trajectory files (*.raw);;All files (*.*)")); if (name == NULL) {/*QMessageBox::information( NULL, "Information", "No file selected.");*/return;} qwtPlotCF_2->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu CF_2 (w II tabie) //check if file's ok QFile fp (name); if (!fp.open(QIODevice::ReadOnly)) { QMessageBox::warning( NULL, "Error", "Could not open file."); return; } QByteArray qba = fp.readAll(); const char * data = qba.constData(); //wskaznik do kolejnych bajtow wczytanych z pliku // if (qba.size() % 2) QMessageBox::warning( NULL, "Error", "Incorrect RAW file length (odd number of bytes)!"); ch1.clear(); ch2.clear(); //wyczyscmy dane z obu kanalow int ch1_cycles = 1, ch2_cycles = 1; //ile czasu minelo od ostatniego zliczenia :) (czyli "odstep"+1 kanal) for (int i=0; i<qba.size()/2; i++) { //2 bytes = sizeof(short) short word = ((short*)data)[i]; uchar time_elapsed = (uchar) (word & 255); //low byte uchar pulses_code = (uchar) ((word >> 8) & 255); //high byte // printf ("Time elapsed: %d\n",(int)time_elapsed); ch1_cycles += time_elapsed; ch2_cycles += time_elapsed; if (pulses_code == 0) { ch1_cycles += 4; ch2_cycles += 4; continue; //brak zliczen - jedziemy dalej } // printf ("ch1_cycles: %d\n",ch1_cycles); for (int bt=0; bt<4; bt++) { char kod = pulses_code & 3; if (kod != 0) { if (kod & 1) {ch1.push_back (ch1_cycles); ch1_cycles = 0;} if (kod & 2) {ch2.push_back (ch2_cycles); ch2_cycles = 0;} } ch1_cycles ++; ch2_cycles ++; pulses_code >>= 2; } } LOG("Channel1: %d photons, channel 2: %d photons.",ch1.size(),ch2.size()); setWindowTitle (QString("RAW analyzer: ")+name); //Ustaw tytul, zeby bylo widac nazwe pliku inputRAWFileName->setText(name); //Ustaw nazwe pliku w polu edycji butCalculateIntensity->setEnabled(true); } using namespace Info; using std::cout; /* ------ Oblicz funkcje korelacji bez kanalizowania w traj. int. (oszcz. pamieci)--------- */ void RawLoader :: CalcCorrRightAway () { if (info!= NULL) { info->correlation.clear(); info->correlation.resize(1); //clean up first } else { info = new FCS_Info; } //obliczamy korelacje info->repeats = 1; const double dT = inputDT->text().toInt(); const int STEPS_PER_BIN = inputDT_2->text().toInt(); vector<int> & channel = radioCh1->isChecked() ? ch1 : ch2; ///z main.cpp (fluor4)---------------------- int counter = 0; //counter=1; double time = STEPS_PER_BIN*dT; //chcialoby sie dac "0", ale to brzydko wyglada double TIME_STEP = STEPS_PER_BIN; double TAU_MAX;// = ((double)info->countrate[0].size())*dT*0.1; ////////// CorrelatorPAT * corr1 = new CorrelatorPAT (channel);//, dT, info->countrate[0].size(), STEPS_PER_BIN); printf ("Calculating LOG correlation (DIRECTLY from RAW) for BIN_SIZE = %d; dT = %lf, TAU_MAX = %lf.\n",STEPS_PER_BIN, dT, TAU_MAX); while (time <= TAU_MAX) { double result;// = corr1->Calculate_correlation (time); NOTE odblokowac printf ("g(%5.9le)=%lf\n", time*50e-9, result); XYData xy_data; xy_data.x = time*50e-9; xy_data.y = result; info->correlation[0].push_back(xy_data); counter++; if (counter >= 4) {counter=0; TIME_STEP*=2;} //every 4 iterations, the correlation time increase is doubled time += TIME_STEP*dT; } ///--------------------- DrawFunction (info->correlation[0], "RAW-based direct correlation", qwtPlotCF_2); butFinish->setEnabled(true); delete corr1; } /* ------ Pogrupuj zliczenia w kanaly i oblicz intensywnosc --------- */ void RawLoader :: CalculateIntensity () { qwtPlotCF_2->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu CF_2 (w II tabie) qwtPlotIntensity->detachItems (QwtPlotItem::Rtti_PlotCurve); //skasuj wszystkie krzywe z wykresu Intensywnosci //mamy juz czasy odstepu w ch1 i ch2 - teraz nalezy przerobic na intensywnosc wg zadanego kanalu. vector<int> & channel = radioCh1->isChecked() ? ch1 : ch2; uint B = inputDT->text().toUInt();//szerokosc kanalu [FIXME na razie w cyklach] labelBinSize->setText(QString("= ")+QString::number(B*0.05)+QString(" [us].")); uint counts = 0, gap = 0; //gap - odstep miedzy zliczeniami info = new Info::FCS_Info; info->countrate.clear(); info->countrate.resize (1); //just one intensity trajectory for (uint a=0; a < channel.size(); a++) { gap += channel[a]; counts += 1; while (gap > B) { gap -= B; // printf ("Next bin! remaining gap = %d, counts = %d.\n",gap,counts); Info::XYData xy_data; xy_data.x = info->countrate[0].size(); //TODO //Clock rate: 20 MHz = 50 ns xy_data.y = counts; info->countrate[0].push_back(xy_data); counts = 0; } } DrawFunction (info->countrate[0], "RAW intensity", qwtPlotIntensity); butCalculateCorrelation->setEnabled(true); } // TODO FIXME PROBLEM: Trajektoria intensywnosci dla malego kanalu nie miesci sie w pamieci!!!!!! // Moze zrobic korelacje jednak na podstawie channeli???? JAK? TODO znalezc publikacje o HW correlatorach void RawLoader :: CalculateRAWCorrelation () { info->correlation.clear(); info->correlation.resize(1); //clean up first //obliczamy korelacje int * traj = new int [info->countrate[0].size()]; for (uint i=0; i<info->countrate[0].size(); i++) traj[i] = info->countrate[0][i].y; info->repeats = 1; const double dT = inputDT->text().toInt(); const int STEPS_PER_BIN = inputDT_2->text().toInt(); Correlator * corr1 = new CorrelatorSimple (traj, dT, info->countrate[0].size(), STEPS_PER_BIN); //z main.cpp (fluor4) int counter = 0; //counter=1; double time = STEPS_PER_BIN*dT; //chcialoby sie dac "0", ale to brzydko wyglada double TIME_STEP = STEPS_PER_BIN; double TAU_MAX = ((double)info->countrate[0].size())*dT*0.1; printf ("Calculating LOG correlation for BIN_SIZE = %d; dT = %lf, TAU_MAX = %lf.\n",STEPS_PER_BIN, dT, TAU_MAX); // fp = fopen ("correlationLOG.dat","wt"); while (time <= TAU_MAX) { double result = corr1->Calculate_correlation (time); printf ("g(%5.9le)=%lf\n", time*50e-9, result); XYData xy_data; xy_data.x = time*50e-9; xy_data.y = result; info->correlation[0].push_back(xy_data); counter++; if (counter >= 4) {counter=0; TIME_STEP*=2;} //every 4 iterations, the correlation time increase is doubled time += TIME_STEP*dT; } // info->Print (std::cout); /////DEBUG DrawFunction (info->correlation[0], "RAW-based correlation", qwtPlotCF_2); butFinish->setEnabled(true); delete [] traj; delete corr1; } <file_sep>/src/logslider.cpp #include "logslider.h" LogSlider :: LogSlider (QWidget * parent) : QSlider (parent) { // QMessageBox::information( NULL, "Tytul","LogSlider created :)"); k = 10.0; A = 1.0; connect (this, SIGNAL(valueChanged(int)), this, SLOT(calcExpValue())); } void LogSlider :: calcExpValue () { double a = A * exp(k*value()); if (isSliderDown()) emit sendExp(a,r,c); } //zamiast valueChanged(int) void LogSlider :: SetExpParams (double min, double max, int row, int col) { r=row; c=col; ASSERT (minimum() == 0); A = min; //assuming minimum = 0 ticks k = log(max/A) / maximum(); // QMessageBox::information( NULL, "LogParams:", tr("%1, %2").arg(A).arg(k)); ///////// } void LogSlider :: updateSlider (double v, int row, int col) { if (r!=row || c!=col) return; int pos = (int) (log(v/A)/k); //no need to check boundaries, setSliderPosition() will do it setSliderPosition (pos); //this way, with tracking off, valueChanged() signal is not emitted :) HACK? } <file_sep>/Makefile ############################################################################# # Makefile for building: FCS_analyzer # Generated by qmake (2.01a) (Qt 4.8.1) on: Tue May 6 23:28:17 2014 # Project: FCS_analyzer.pro # Template: app # Command: /usr/bin/qmake -o Makefile FCS_analyzer.pro ############################################################################# ####### Compiler, tools and options CC = gcc CXX = g++ DEFINES = -DQT_WEBKIT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED CFLAGS = -m64 -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES) CXXFLAGS = -m64 -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES) INCPATH = -I/usr/share/qt4/mkspecs/linux-g++-64 -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. -I/usr/include/qt4 -I/usr/include/qwt -Isrc -I. -I. LINK = g++ LFLAGS = -m64 -Wl,-O1 LIBS = $(SUBLIBS) -L./levmar-2.4 -L/usr/lib/x86_64-linux-gnu -lqwt -llevmar -llapack -lblas -lQtGui -lQtCore -lpthread AR = ar cqs RANLIB = QMAKE = /usr/bin/qmake TAR = tar -cf COMPRESS = gzip -9f COPY = cp -f SED = sed COPY_FILE = $(COPY) COPY_DIR = $(COPY) -r STRIP = strip INSTALL_FILE = install -m 644 -p INSTALL_DIR = $(COPY_DIR) INSTALL_PROGRAM = install -m 755 -p DEL_FILE = rm -f SYMLINK = ln -f -s DEL_DIR = rmdir MOVE = mv -f CHK_DIR_EXISTS= test -d MKDIR = mkdir -p ####### Output directory OBJECTS_DIR = ./ ####### Files SOURCES = src/analyzer.cpp \ src/logslider.cpp \ src/main.cpp \ src/tableparams.cpp \ src/fcs_loader.cpp \ src/zoomplot.cpp \ src/fit.cpp \ src/raw_loader.cpp \ src/correlatorSimple.cpp \ src/program.cpp \ src/correlatorPAT.cpp moc_analyzer.cpp \ moc_logslider.cpp \ moc_tableparams.cpp \ moc_zoomplot.cpp \ moc_loglineedit.cpp \ moc_raw_loader.cpp \ moc_program.cpp OBJECTS = analyzer.o \ logslider.o \ main.o \ tableparams.o \ fcs_loader.o \ zoomplot.o \ fit.o \ raw_loader.o \ correlatorSimple.o \ program.o \ correlatorPAT.o \ moc_analyzer.o \ moc_logslider.o \ moc_tableparams.o \ moc_zoomplot.o \ moc_loglineedit.o \ moc_raw_loader.o \ moc_program.o DIST = /usr/share/qt4/mkspecs/common/unix.conf \ /usr/share/qt4/mkspecs/common/linux.conf \ /usr/share/qt4/mkspecs/common/gcc-base.conf \ /usr/share/qt4/mkspecs/common/gcc-base-unix.conf \ /usr/share/qt4/mkspecs/common/g++-base.conf \ /usr/share/qt4/mkspecs/common/g++-unix.conf \ /usr/share/qt4/mkspecs/qconfig.pri \ /usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \ /usr/share/qt4/mkspecs/features/qt_functions.prf \ /usr/share/qt4/mkspecs/features/qt_config.prf \ /usr/share/qt4/mkspecs/features/exclusive_builds.prf \ /usr/share/qt4/mkspecs/features/default_pre.prf \ /usr/share/qt4/mkspecs/features/release.prf \ /usr/share/qt4/mkspecs/features/default_post.prf \ /usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \ /usr/share/qt4/mkspecs/features/warn_on.prf \ /usr/share/qt4/mkspecs/features/qt.prf \ /usr/share/qt4/mkspecs/features/unix/thread.prf \ /usr/share/qt4/mkspecs/features/moc.prf \ /usr/share/qt4/mkspecs/features/resources.prf \ /usr/share/qt4/mkspecs/features/uic.prf \ /usr/share/qt4/mkspecs/features/yacc.prf \ /usr/share/qt4/mkspecs/features/lex.prf \ /usr/share/qt4/mkspecs/features/include_source_dir.prf \ FCS_analyzer.pro QMAKE_TARGET = FCS_analyzer DESTDIR = TARGET = FCS_analyzer first: all ####### Implicit rules .SUFFIXES: .o .c .cpp .cc .cxx .C .cpp.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cc.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cxx.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .C.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .c.o: $(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<" ####### Build rules all: Makefile $(TARGET) $(TARGET): ui_Main_analyzer.h ui_Raw_loader.h ui_Tab.h $(OBJECTS) $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) Makefile: FCS_analyzer.pro /usr/share/qt4/mkspecs/linux-g++-64/qmake.conf /usr/share/qt4/mkspecs/common/unix.conf \ /usr/share/qt4/mkspecs/common/linux.conf \ /usr/share/qt4/mkspecs/common/gcc-base.conf \ /usr/share/qt4/mkspecs/common/gcc-base-unix.conf \ /usr/share/qt4/mkspecs/common/g++-base.conf \ /usr/share/qt4/mkspecs/common/g++-unix.conf \ /usr/share/qt4/mkspecs/qconfig.pri \ /usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \ /usr/share/qt4/mkspecs/features/qt_functions.prf \ /usr/share/qt4/mkspecs/features/qt_config.prf \ /usr/share/qt4/mkspecs/features/exclusive_builds.prf \ /usr/share/qt4/mkspecs/features/default_pre.prf \ /usr/share/qt4/mkspecs/features/release.prf \ /usr/share/qt4/mkspecs/features/default_post.prf \ /usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \ /usr/share/qt4/mkspecs/features/warn_on.prf \ /usr/share/qt4/mkspecs/features/qt.prf \ /usr/share/qt4/mkspecs/features/unix/thread.prf \ /usr/share/qt4/mkspecs/features/moc.prf \ /usr/share/qt4/mkspecs/features/resources.prf \ /usr/share/qt4/mkspecs/features/uic.prf \ /usr/share/qt4/mkspecs/features/yacc.prf \ /usr/share/qt4/mkspecs/features/lex.prf \ /usr/share/qt4/mkspecs/features/include_source_dir.prf \ /usr/lib/x86_64-linux-gnu/libQtGui.prl \ /usr/lib/x86_64-linux-gnu/libQtCore.prl $(QMAKE) -o Makefile FCS_analyzer.pro /usr/share/qt4/mkspecs/common/unix.conf: /usr/share/qt4/mkspecs/common/linux.conf: /usr/share/qt4/mkspecs/common/gcc-base.conf: /usr/share/qt4/mkspecs/common/gcc-base-unix.conf: /usr/share/qt4/mkspecs/common/g++-base.conf: /usr/share/qt4/mkspecs/common/g++-unix.conf: /usr/share/qt4/mkspecs/qconfig.pri: /usr/share/qt4/mkspecs/modules/qt_webkit_version.pri: /usr/share/qt4/mkspecs/features/qt_functions.prf: /usr/share/qt4/mkspecs/features/qt_config.prf: /usr/share/qt4/mkspecs/features/exclusive_builds.prf: /usr/share/qt4/mkspecs/features/default_pre.prf: /usr/share/qt4/mkspecs/features/release.prf: /usr/share/qt4/mkspecs/features/default_post.prf: /usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf: /usr/share/qt4/mkspecs/features/warn_on.prf: /usr/share/qt4/mkspecs/features/qt.prf: /usr/share/qt4/mkspecs/features/unix/thread.prf: /usr/share/qt4/mkspecs/features/moc.prf: /usr/share/qt4/mkspecs/features/resources.prf: /usr/share/qt4/mkspecs/features/uic.prf: /usr/share/qt4/mkspecs/features/yacc.prf: /usr/share/qt4/mkspecs/features/lex.prf: /usr/share/qt4/mkspecs/features/include_source_dir.prf: /usr/lib/x86_64-linux-gnu/libQtGui.prl: /usr/lib/x86_64-linux-gnu/libQtCore.prl: qmake: FORCE @$(QMAKE) -o Makefile FCS_analyzer.pro dist: @$(CHK_DIR_EXISTS) .tmp/FCS_analyzer1.0.0 || $(MKDIR) .tmp/FCS_analyzer1.0.0 $(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/FCS_analyzer1.0.0/ && $(COPY_FILE) --parents src/analyzer.h src/logslider.h src/tableparams.h src/fcs_loader.h src/zoomplot.h src/loglineedit.h src/correlator.h src/lm.h src/raw_loader.h src/program.h .tmp/FCS_analyzer1.0.0/ && $(COPY_FILE) --parents src/analyzer.cpp src/logslider.cpp src/main.cpp src/tableparams.cpp src/fcs_loader.cpp src/zoomplot.cpp src/fit.cpp src/raw_loader.cpp src/correlatorSimple.cpp src/program.cpp src/correlatorPAT.cpp .tmp/FCS_analyzer1.0.0/ && $(COPY_FILE) --parents Main_analyzer.ui Raw_loader.ui Tab.ui .tmp/FCS_analyzer1.0.0/ && (cd `dirname .tmp/FCS_analyzer1.0.0` && $(TAR) FCS_analyzer1.0.0.tar FCS_analyzer1.0.0 && $(COMPRESS) FCS_analyzer1.0.0.tar) && $(MOVE) `dirname .tmp/FCS_analyzer1.0.0`/FCS_analyzer1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/FCS_analyzer1.0.0 clean:compiler_clean -$(DEL_FILE) $(OBJECTS) -$(DEL_FILE) *~ core *.core ####### Sub-libraries distclean: clean -$(DEL_FILE) $(TARGET) -$(DEL_FILE) Makefile check: first mocclean: compiler_moc_header_clean compiler_moc_source_clean mocables: compiler_moc_header_make_all compiler_moc_source_make_all compiler_moc_header_make_all: moc_analyzer.cpp moc_logslider.cpp moc_tableparams.cpp moc_zoomplot.cpp moc_loglineedit.cpp moc_raw_loader.cpp moc_program.cpp compiler_moc_header_clean: -$(DEL_FILE) moc_analyzer.cpp moc_logslider.cpp moc_tableparams.cpp moc_zoomplot.cpp moc_loglineedit.cpp moc_raw_loader.cpp moc_program.cpp moc_analyzer.cpp: ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/analyzer.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/analyzer.h -o moc_analyzer.cpp moc_logslider.cpp: src/logslider.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/logslider.h -o moc_logslider.cpp moc_tableparams.cpp: src/tableparams.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/tableparams.h -o moc_tableparams.cpp moc_zoomplot.cpp: src/zoomplot.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/zoomplot.h -o moc_zoomplot.cpp moc_loglineedit.cpp: src/loglineedit.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/loglineedit.h -o moc_loglineedit.cpp moc_raw_loader.cpp: ui_Raw_loader.h \ src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/raw_loader.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/raw_loader.h -o moc_raw_loader.cpp moc_program.cpp: ui_Main_analyzer.h \ src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/program.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) src/program.h -o moc_program.cpp compiler_rcc_make_all: compiler_rcc_clean: compiler_image_collection_make_all: qmake_image_collection.cpp compiler_image_collection_clean: -$(DEL_FILE) qmake_image_collection.cpp compiler_moc_source_make_all: compiler_moc_source_clean: compiler_uic_make_all: ui_Main_analyzer.h ui_Raw_loader.h ui_Tab.h compiler_uic_clean: -$(DEL_FILE) ui_Main_analyzer.h ui_Raw_loader.h ui_Tab.h ui_Main_analyzer.h: Main_analyzer.ui /usr/bin/uic-qt4 Main_analyzer.ui -o ui_Main_analyzer.h ui_Raw_loader.h: Raw_loader.ui /usr/bin/uic-qt4 Raw_loader.ui -o ui_Raw_loader.h ui_Tab.h: Tab.ui /usr/bin/uic-qt4 Tab.ui -o ui_Tab.h compiler_yacc_decl_make_all: compiler_yacc_decl_clean: compiler_yacc_impl_make_all: compiler_yacc_impl_clean: compiler_lex_make_all: compiler_lex_clean: compiler_clean: compiler_moc_header_clean compiler_uic_clean ####### Compile analyzer.o: src/analyzer.cpp src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/program.h \ ui_Main_analyzer.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o analyzer.o src/analyzer.cpp logslider.o: src/logslider.cpp src/logslider.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o logslider.o src/logslider.cpp main.o: src/main.cpp src/program.h \ ui_Main_analyzer.h \ src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o src/main.cpp tableparams.o: src/tableparams.cpp src/tableparams.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o tableparams.o src/tableparams.cpp fcs_loader.o: src/fcs_loader.cpp src/fcs_loader.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o fcs_loader.o src/fcs_loader.cpp zoomplot.o: src/zoomplot.cpp src/zoomplot.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o zoomplot.o src/zoomplot.cpp fit.o: src/fit.cpp src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/lm.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o fit.o src/fit.cpp raw_loader.o: src/raw_loader.cpp src/raw_loader.h \ ui_Raw_loader.h \ src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h \ src/correlator.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o raw_loader.o src/raw_loader.cpp correlatorSimple.o: src/correlatorSimple.cpp src/correlator.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o correlatorSimple.o src/correlatorSimple.cpp program.o: src/program.cpp src/program.h \ ui_Main_analyzer.h \ src/analyzer.h \ ui_Tab.h \ src/tableparams.h \ src/fcs_loader.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o program.o src/program.cpp correlatorPAT.o: src/correlatorPAT.cpp src/correlator.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o correlatorPAT.o src/correlatorPAT.cpp moc_analyzer.o: moc_analyzer.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_analyzer.o moc_analyzer.cpp moc_logslider.o: moc_logslider.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_logslider.o moc_logslider.cpp moc_tableparams.o: moc_tableparams.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_tableparams.o moc_tableparams.cpp moc_zoomplot.o: moc_zoomplot.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_zoomplot.o moc_zoomplot.cpp moc_loglineedit.o: moc_loglineedit.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_loglineedit.o moc_loglineedit.cpp moc_raw_loader.o: moc_raw_loader.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_raw_loader.o moc_raw_loader.cpp moc_program.o: moc_program.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_program.o moc_program.cpp ####### Install install: FORCE uninstall: FORCE FORCE: <file_sep>/src/loglineedit.h #ifndef _MY_LOG_EDIT_ #define _MY_LOG_EDIT_ #include <QLineEdit> #include <QMessageBox> //#include <math.h> class LogLineEdit: public QLineEdit { Q_OBJECT public slots: void setValue (double v, int , int ) { setText (QString::number((int)(v+0.5))); } //+0.5 zeby lepiej zaokraglic :) , int,int - zeby sie zgadzala sygnatura z logsliderem void emit_cellValueSet (const QString &) {emit cellValueSet (text().toDouble(), 0,0);} signals: void cellValueSet (double v, int r, int c); public: LogLineEdit (QWidget * parent) : QLineEdit (parent) { connect (this, SIGNAL (textChanged(const QString &)), this, SLOT (emit_cellValueSet (const QString &))); } }; #endif //_MY_LOG_EDIT_ <file_sep>/src/analyzer.h #ifndef _MW_ANALYZER_H_ #define _MW_ANALYZER_H_ #include "ui_Tab.h" #include <QMessageBox> #include <QFileDialog> //#include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_scale_engine.h> #include <qwt_plot_marker.h> #include "tableparams.h" #include "fcs_loader.h" #define NUM_PARAMS 11 double G_val (double tau, const double par [NUM_PARAMS]); class Analyzer : public QWidget, public Ui::Tab { Q_OBJECT private: Info::FCS_Info * info; QwtPlotMarker m1, m2; private slots: bool CalculateAverageCorrelation (); void DrawCorrelationFromParams (); void setFitLimits(int button, double x, double y); void setFitModel (int model); void setBleachModel (int s); void setTripletModel (int s); void SaveASCII (); void SaveAvg (); void SaveParams (); void ShowInfo (); public: Analyzer (QWidget * parent); ~Analyzer (); QString filename; void OpenFCSFile (QString fname); void OpenASCII (); void OpenRAWFile (); void OpenSimulated (QString fname); public slots: bool Fit (); }; void DrawFunction (const Info::Func & f, QString text, QwtPlot * plot); //now global class IndexedPushButton : public QPushButton { Q_OBJECT private: int i; private slots: void emit_i (); public: IndexedPushButton (QString name, int _i) : QPushButton (name) {i = _i; connect (this,SIGNAL(clicked()),this,SLOT(emit_i()));} signals: void clicked (int, SM::SwitchModes); }; #endif //_MW_ANALYZER_H_ <file_sep>/src/zoomplot.h #ifndef _ZOOMPLOT_H_ #define _ZOOMPLOT_H_ #include <qwt_plot.h> #include <QMouseEvent> #include <QPainter> #include <QWidget> #include <iostream> class KwadratWidget : public QWidget { protected: /* void moveEvent (QMoveEvent * me) { std::cout << "Widget moved to "<<pos().x()<<","<<pos().y()<<".\n"; }*/ virtual void paintEvent (QPaintEvent *) { QPainter painter (this); painter.setPen (QColor(255,0,0)); painter.setBrush (QColor(255,20,0,120)); painter.drawRect (x1,y1,x2-x1,y2-y1); // std::cout << "Drawing (x,y,w,h): "<< x1<<" "<< y1<<" "<<x2<<" "<< y2; } public: int x1,y1,x2,y2; KwadratWidget (QWidget * parent): QWidget (parent) { x1=y1=x2=y2=0; setFixedSize(800,800);show(); } }; class ZoomPlot : public QwtPlot { Q_OBJECT protected: //variables int zoom_start_x, zoom_start_y; KwadratWidget * kwadrat; bool drawing; double xmin,ymin, xmax,ymax; //my functions void ZoomIn (double from_x, double from_y, double to_x, double to_y); void ZoomOut (); //overriden from QWidget void mousePressEvent ( QMouseEvent * event ); void mouseReleaseEvent ( QMouseEvent * event ); void mouseMoveEvent ( QMouseEvent * event ); void wheelEvent (QWheelEvent * event); // void paintEvent ( QPaintEvent * event); public: ZoomPlot (QWidget * parent); ~ZoomPlot (); signals: void clicked (int button, double x, double y); }; #endif //_ZOOMPLOT_H_ <file_sep>/src/raw_loader.h #ifndef _MW_RAW_LOADER_ #define _MW_RAW_LOADER_ #include "ui_Raw_loader.h" #include "analyzer.h" #include <QDialog> #include <QFileDialog> #include <QMessageBox> //#include <qwt_plot.h> // #include <qwt_plot_curve.h> #include <qwt_scale_engine.h> #include <qwt_plot_marker.h> // #include "tableparams.h" #include "fcs_loader.h" using namespace Info; class RawLoader : public QDialog, public Ui::DialogLoadRAW { Q_OBJECT private: Info::FCS_Info * info; QwtPlotMarker m1, m2; vector<int> ch1, ch2; //wektory czasow odstepu pomiedzy kolejnymi zliczeniami dla obu kanalow (dla wczytywania traj. RAW) private slots: // void DrawFunction (const Info::Func & f, QString text, QwtPlot * plot); void CalculateIntensity (); void CalculateRAWCorrelation (); void CalcCorrRightAway (); void OpenRAWFile (); public: FCS_Info * Wynik () {return info;} RawLoader (); // public slots: }; #endif //_MW_RAW_LOADER_
080b43648f27f0e65c4ffc4d38f1200c4a0c16a6
[ "Markdown", "C", "Makefile", "C++" ]
23
C++
marras/FCS-analyzer
41056d3772cf2e57f3b6aa8412052279ec1e0775
ca0000fb4d36e46d7b31a3836729fbe89e0605e5
refs/heads/master
<repo_name>ctywzy/JavaBase<file_sep>/day20/i10.java package day20; import java.io.File; import java.io.IOException; import java.io.Reader; public class i10 { public static void main(String[] args) { File f = new File("demo.txt"); Reader r = new Reader(f) { @Override public int read(char[] cbuf, int off, int len) throws IOException { return 0; } @Override public void close() throws IOException { } }; } } <file_sep>/day18/g10.java package day18; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class g10 { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("demo.txt"); BufferedReader bufr = new BufferedReader(fr); String Line = null; while((Line = bufr.readLine())!=null){ System.out.println(Line); } } } <file_sep>/day22/k2.java package day22; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /* Properties集合读取硬盘中的键值对信息 */ public class k2 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("a.txt"); Properties prop = new Properties(); prop.load(fis); prop.list(System.out); } } <file_sep>/day24/m4.java package day24; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class m4 { private static final int BUFFER_SIZE = 1024; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket ds = new DatagramSocket(); String line = null; while((line = br.readLine()) != null){ DatagramPacket dp = new DatagramPacket(line.getBytes(),line.length(), InetAddress.getByName("127.0.0.1"),9999); ds.send(dp); if("over".equals(line)){ break; } } ds.close(); } } <file_sep>/day20/i6.java package day20; /* 匿名内部类 */ public class i6 { int k = 1; public void show(){ System.out.println("111"); } public static void main(String[] args) { i6 ii = new i6(){ int k = 2; public void show(){ System.out.println("222"); } }; ii.show(); System.out.println(ii.k); /* 222 1 */ } } <file_sep>/day22/k6.java package day22; /* 文件切割 */ import java.io.*; public class k6 { private static final int BUFFER_SIZE = 1024; public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("a.txt"); byte[] buf = new byte[BUFFER_SIZE];//单个文件大小; int len = 0; int count = 1; FileOutputStream fos = null; File dir = new File("");//目录 if(dir.exists()){ dir.createNewFile(); } while((fis.read(buf)) != -1){ fos = new FileOutputStream(new File(dir,count++ + ".path")); fos.write(buf,0,len); } fis.close(); fos.close(); } } <file_sep>/day20/i7.java package day20; public class i7 { public static void main(String[] args) { } } <file_sep>/day15/d3.java package day15; class TreeNode{ TreeNode lchild; TreeNode rchild; int date; TreeNode(){} TreeNode(int date){ this.date = date; } } public class d3 { public static void main(String[] args) { TreeNode root = new TreeNode(); int[] pre = {1,2,4,7,3,5,6,8}; int[] in = {4,7,2,1,5,3,8,6}; int[] out = new int[pre.length]; root = rebuild(pre,0,pre.length-1,in,0,in.length-1); pppre(root); } public static void pppre(TreeNode root){ if(root == null) return; System.out.println(root.date); pppre(root.lchild); pppre(root.rchild); } public static TreeNode rebuild(int[] pre, int s1, int e1, int[] in, int s2, int e2){ if(e1<s1||e2<s2){ return null; } TreeNode root = new TreeNode(); int i = s2; for(;i <=e2 ;i++){ if(in[i]==pre[s1]){ break; } } int k1 = i - s2; int k2 = e2 - i; root.date = pre[s1]; root.lchild = rebuild(pre,s1+1 , s1+k1 ,in ,s2 ,s2+k1-1); root.rchild = rebuild(pre,e1-k2+1, e1,in ,e2-k2+1, e2); return root; } } <file_sep>/day27/o5.java package day27; import java.util.TreeSet; /* 正则表达式练习 1.把字符串改成我要学编程 2.对给定的ip地址进行排序 3.邮箱地址校验 */ public class o5 { public static void main(String[] args){ //f1(); //f2(); f3("<EMAIL>_1@2adf_.com.com.cssssssssso"); } public static void f1(){ String str = "我我..我我..我.我.我要.....要.要.要.要....要要要学学学学....学学学编编....编....编程程程..程"; String regex = ""; str = str.replaceAll("\\.+",""); System.out.println(str); str = str.replaceAll("(.)\\1+","$1"); System.out.println(str); } public static void f2(){ String s1 = "172.16.17.32 13.13.13 3.3.3.2"; s1 = s1.replaceAll("(\\d+)","00$1");//连续出现的数字前补0; s1 = s1.replaceAll("\\d*(\\d{3})","$1");//所有数字都用后三位代替 //获取 //s1 = s1.replaceAll("0*(\\d{3})","$1"); //s1 = s1.replaceAll("0*(\\d+)","$1"); String ips[] = s1.split(" +"); System.out.println(ips.length); TreeSet<String> ts = new TreeSet<String>(); for(String ip:ips){ ts.add(ip); //System.out.println(ip); } for(String ip : ts){ System.out.println(ip.replaceAll("0*(\\d+)","$1")); } } public static void f3(String str){ String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-zA-Z]{1,3}){1,3}"; System.out.println(str.matches(regex)); } } <file_sep>/day24/m8.java package day24; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /* TCP服务端 */ public class m8 { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(8888); Socket socket = ss.accept(); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); String str = new String(buf,0,len); String ip = socket.getInetAddress().getHostAddress(); System.out.println(ip + ":" +str); out.write("你也好".getBytes("utf-8")); socket.close(); ss.close(); } } <file_sep>/day19/h1.java package day19; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class h1 { public static void main(String[] args) { int[] a = new int[2]; try{ System.out.println(a[2]); ReadWriteLock rwl = new ReentrantReadWriteLock(); rwl.readLock().lock(); //Lock lock = new Ree }catch(Exception e){ System.out.println("0000"); } } } <file_sep>/day20/i1.java package day20; import java.util.ArrayList; import java.util.List; public class i1 { public static void i1(){ System.out.println(11); } public static void main(String args[]) { StringBuffer s1 = new StringBuffer(10); } } <file_sep>/day28/p7.java package day28; class pp7{ public String name; public void f1(){ System.out.println("1"); } } public class p7 extends pp7{ public String name; public void f1(){ System.out.println("2"); } public void f3(){ System.out.println("3"); } public static void main(String[] args) { pp7 k = new p7(); k.f1(); pp7 kk = (pp7) k; kk.f1(); new p7(){ public void f1(){ System.out.println("4"); } }.f1(); } } <file_sep>/day24/m5.java package day24; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class m5 { private static final int BUFFER_SIZE = 1024; public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(9999); byte[] buf = new byte[BUFFER_SIZE]; DatagramPacket dp = new DatagramPacket(buf,buf.length); while(true){ ds.receive(dp); String text = new String(dp.getData(),0,dp.getLength()); if("over".equals(text)){ break; } String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); System.out.println(ip+ " : " +port + " : " + text); } ds.close(); } } <file_sep>/day21/j3.java package day21; import java.io.File; public class j3 { public static void main(String[] args) { File f = new File("C:\\Program Files"); String[] name = f.list(); for(String n:name){ System.out.println(n); } } } <file_sep>/day26/Test.java package day26; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class Test { private int a; public String b; public void f1(){ System.out.println("f1"); }; private void f2(){ System.out.println("f2"); } public void f3(int k){ System.out.println(k); } public static void main(String[] args) throws IOException { File file = new File("config.properties"); FileOutputStream fos = new FileOutputStream(file); Properties prop = new Properties(); prop.setProperty("c1","day26.wangka"); prop.setProperty("c2","day26.shengka"); prop.store(fos,null); fos.close(); } } <file_sep>/day24/m13.java package day24; import java.io.*; import java.net.Socket; public class m13 { public static void main(String[] args) throws IOException { Socket s = new Socket("127.0.0.1",9999); OutputStream os = s.getOutputStream(); FileInputStream fis = new FileInputStream("E:\\picture.jpg"); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf))!=-1){ os.write(buf,0,len); } s.shutdownOutput(); //利用转换流把字节转换成字符,可以输出中文 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = br.readLine(); System.out.println(str); s.close(); fis.close(); } } <file_sep>/day18/g7.java package day18; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class g7 { public static void main(String[] args) { FileReader fr = null; try{ fr = new FileReader("demo.txt"); int c; while((c = fr.read())!=-1){ System.out.println((char)c); } } catch (Exception e) { e.printStackTrace(); }finally { if(fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } } <file_sep>/day26/n2.java package day26; class nn2{ } class nnn2 extends nn2{ public void run(){ System.out.println("run"); } } public class n2 { public static void main(String[] args) { nn2 k = new nnn2(); } } <file_sep>/day24/m7.java package day24; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /* TCP客户端 */ public class m7 { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1",8888); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); byte[] buf = new byte[1024]; int len =0; out.write("你好".getBytes("utf-8")); len = in.read(buf); String str = new String(buf,0,len); System.out.println("收到回信息"+str); socket.close(); } } <file_sep>/day27/o6.java package day27; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* 网页爬虫 获取邮箱 */ public class o6 { public static void main(String[] args) throws IOException { //前提是这个路径能够正常访问, URL url = new URL("https://mail.qq.com/cgi-bin/frame_html?sid=Uz0MruVElI-TM1MO&r=179c675082e559d2897d9aae67d3fa90"); BufferedReader bfin = new BufferedReader(new InputStreamReader(url.openStream())); String regex = "\\w+@\\w+(\\.\\w+)+"; List<String> lists = new ArrayList<String>(); Pattern p = Pattern.compile(regex); String line = null; while((line = bfin.readLine())!=null){ System.out.println(line); // Matcher m =p.matcher(line); // while (m.find()){ // lists.add(m.group()); // } } for(String mail : lists){ System.out.println(mail); } } } <file_sep>/day18/g3.java package day18; public class g3 { public static void main(String[] args) { // double a = Math.floor(-12.5); // System.out.println(a); for(int i=0;i<10;i++){ double d = Math.random()*100+100; System.out.println(Math.floor(d)); } } } <file_sep>/day27/o2.java package day27; /* 正则切割 */ public class o2 { public static void main(String[] args) { String names = "abc\\bcd\\ddd\\kfc"; String[] name = names.split("\\\\"); System.out.println(name.length); } } <file_sep>/day15/d1.java package day15; public class d1 { public static void main(String[] args) { Integer a = 1; Integer b = 1; System.out.println(a==b); } } <file_sep>/day22/k7.java package day22; import java.io.*; import java.util.*; /* 文件合并 */ public class k7 { public static void main(String[] args) throws IOException { ArrayList<FileInputStream> array = new ArrayList<FileInputStream>(); FileInputStream fis = null; for(int i=0;i < 10 ;i++){//搜索一下获取共有几个文件 fis = new FileInputStream(i+".part"); array.add(fis); } Enumeration<FileInputStream> en = Collections.enumeration(array); SequenceInputStream sis = new SequenceInputStream(en); FileOutputStream fos = new FileOutputStream("a.txt"); byte[] buf = new byte[1024]; int len = 0; File dir = new File("c:\\a"); if(dir.exists() == false){ dir.createNewFile(); } while((len = sis.read(buf)) != -1){ fos.write(buf,0,len); } sis.close(); fos.close(); fis.close(); } } <file_sep>/day26/n1.java package day26; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; class nn1{ public nn1(int k){ } public nn1(){ } public nn1(String s1,int k){ } public void run(){ System.out.println("run"); } } public class n1 { public static void main(String[] args) throws Exception{ Class clazs = Class.forName("day26.nn1"); System.out.println(clazs.getName()); int k = 1; day26.nn1 kk = new day26.nn1(); Constructor constructor = clazs.getConstructor(int.class); nn1 obj = (nn1)constructor.newInstance(k); obj.run(); } } <file_sep>/day26/n3.java package day26; import java.lang.reflect.Field; import java.lang.reflect.Method; public class n3 { public static void main(String[] args) throws Exception { //getvariable(); getMethod(); } public static void getvariable() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException { Class clazs = Class.forName("day26.Test"); Field field = clazs.getDeclaredField("a"); field.setAccessible(true); System.out.println(field); Object o1 = clazs.newInstance(); Object obj = field.get(o1); System.out.println(o1); } public static void getMethod() throws Exception{ Class claze = Class.forName("day26.Test"); Method method = claze.getDeclaredMethod("f2"); method.setAccessible(true); Object obj = claze.newInstance(); method.invoke(obj); } } <file_sep>/day24/m2.java package day24; import java.io.IOException; import java.net.*; public class m2 { public static void main(String[] args) throws IOException { System.out.println("发送udp数据包"); /* 建立udp socket服务 */ DatagramSocket ds = new DatagramSocket(); System.out.println(ds.getLocalPort()); String str = "udp socket通讯"; byte[] buf = str.getBytes(); /* 封装udp包 */ DatagramPacket dp = new DatagramPacket(buf,buf.length, InetAddress.getByName("10.60.46.207"),9999); /* 发送包 */ ds.send(dp); /* 关闭服务 */ ds.close(); } } <file_sep>/day24/m12.java package day24; import com.sun.source.tree.Scope; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.Buffer; /* 服务器接收一个文件,并写到特定的目的地 */ public class m12 { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(8888); Socket s = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedWriter bw = new BufferedWriter(new FileWriter("demo1.txt")); String line = null; /* 等到客户端流关闭了,循环才退出 */ while((line = br.readLine())!=null){ bw.write(line); bw.newLine(); System.out.println(line); bw.flush(); } PrintWriter out = new PrintWriter(s.getOutputStream(),true); System.out.println("文件接收成功"); out.println("文件上传成功"); s.close(); ss.close(); br.close(); bw.close(); } } <file_sep>/day26/IIInvoke.java package day26; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; class BeInvoke{ BeInvoke(){ } BeInvoke(int a,int b){ } } public class IIInvoke { public static void main(String[] args) throws Exception { Class clazs = Class.forName("day26.BeInvoke"); Object obj1 = clazs.getNestHost(); Constructor con1 = clazs.getConstructor(); Object obj2 = con1.newInstance(); Constructor con2 = clazs.getConstructor(int.class,int.class); Object obj3 = con2.newInstance(1,2); } } <file_sep>/day24/m11.java package day24; import java.io.*; import java.net.Socket; /* 文本文件操作 传输一个文件到服务器 */ public class m11 { public static void main(String[] args) throws IOException { Socket s = new Socket("127.0.0.1",8888); BufferedReader br = new BufferedReader(new FileReader("demo.txt")); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; while((line = br.readLine())!=null){ System.out.println(line); out.println(line); } s.shutdownOutput(); //out.println("over");/*去掉这句话可以看到堵塞效果*/ BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = brin.readLine();/*阻塞式的,结束,在s之前,会导致两边等待数据的堵塞,*/ System.out.println(str); s.close(); br.close(); } } <file_sep>/day14/c2.java package day14; public class c2 { public static void main(String[] args) { String s1 = "abc"; String s2 = s1.intern(); System.out.println(s2+s1); System.out.println(s1==s2); String s3 = new String("abc"); String s4 = s3.intern(); System.out.println(s3==s4); } } <file_sep>/day15/d2.java package day15; import java.util.ArrayList; public class d2 { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(); ArrayList<Integer> rs = new ArrayList<>(); arr.add(67); arr.add(0); arr.add(24); arr.add(58); for(int i = arr.size() - 1; i >= 0 ;i--){ } } } <file_sep>/day20/i9.java package day20; import java.io.IOException; import java.io.InputStream; public class i9 { public static void main(String[] args) throws IOException { readkey(); readkey2(); } private static void readkey2() throws IOException { InputStream in = System.in; } private static void readkey() throws IOException { InputStream in = System.in; int ch1,ch2,ch3; ch1 = in.read(); ch2 = in.read(); ch3 = in.read(); System.out.println(ch1+" "+ch2+" "+ch3); } } <file_sep>/day23/l1.java package day23; import java.io.*; /* 文件序列化存储读出; */ class person implements Serializable { String name; String age; person(String name,String age){ this.name = name; this.age = age; } @Override public String toString() { return "person{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } public class l1 { public static void main(String[] args) throws IOException, ClassNotFoundException { /* 存null对象 2.直接读出整个数组 3.利用文件的available */ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("aa.txt",true)); oos.writeObject(new person("mjn","xka")); oos.writeObject(new person("mjxn","xkxa")); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aa.txt")); person p = null; while((p = (person)ois.readObject())!=null){ System.out.println(p); } ois.close(); } } <file_sep>/day18/g9.java package day18; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.SQLOutput; public class g9 { private static final int BUFFER_SIZE = 1024; public static void main(String[] args) { FileReader fr = null; try { fr = new FileReader("demo.txt"); char[] buf = new char[BUFFER_SIZE]; int len = 0; while((len = fr.read(buf))!=-1){ System.out.println(new String(buf,0,len)); } } catch (Exception e) { e.printStackTrace(); }finally { if(fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } } <file_sep>/day17/f2.java package day17; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; class pp{ String name; public pp(String name){ this.name = name; } @Override public String toString() { return "pp{" + "name='" + name + '\'' + '}'; } } class p1 extends pp{ public p1(String name) { super(name); } @Override public String toString() { return "p1{" + "name='" + name + '\'' + '}'; } } class p2 extends pp{ public p2(String name) { super(name); } @Override public String toString() { return "p2{" + "name='" + name + '\'' + '}'; } } interface Inter<T>{ public void show(T t); } class implement implements Inter<String>{ @Override public void show(String s) { System.out.println("show:" + s); } } class implement1<T> implements Inter<T>{ @Override public void show(T t) { System.out.println("show"+t); } } public class f2 { public static void main(String[] args) { implement imp = new implement(); imp.show("abc"); ArrayList<p1> pp1 = new ArrayList<p1>(); pp1.add(new p1("abc")); pp1.add(new p1("abc")); print(pp1); ArrayList<p2> pp2 = new ArrayList<p2>(); pp2.add(new p2("def")); pp2.add(new p2("def")); print(pp2); } public static void print(Collection<? extends pp> a1){ Iterator<? extends pp> it = a1.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } <file_sep>/day18/g2.java package day18; import java.io.IOException; /* 利用runtime类打开本地程序 */ public class g2 { public static void main(String[] args) { Runtime r = Runtime.getRuntime(); try { Process p = r.exec("notepad.exe"); Thread.sleep(1000); p.destroy(); System.out.println(Math.PI); } catch (Exception e) { e.printStackTrace(); } } }
1ccd8f834c6e5cfd609dd84fa23826bd6426e5c5
[ "Java" ]
38
Java
ctywzy/JavaBase
9c60ec4d0657022be694bfaefb96b4779054c67e
413d7982544baffc7669c654cba31778de690dc8
refs/heads/master
<repo_name>TatsutoYamamoto/test<file_sep>/udemy.rb def meth puts "s" end meth a = [1,2,3] puts a[0] h = {"a" => 123, "b" =>456, "c" => 789} puts h["a"] puts h["b"]
f1fbaa94ef85f509962b9462d2a42a25ca6608e0
[ "Ruby" ]
1
Ruby
TatsutoYamamoto/test
5c488d7dde5c8b8e48d115e5d3fec76c3d4127a3
d307854e0aa582e170ecf051278c2a88a01b0e76
refs/heads/master
<file_sep>using Corale.Colore.Razer.Keyboard; using System; namespace Matrix { static class KeyDefinitions { public const int Rows = 5; private static readonly Key[] Row1 = new Key[] { Key.Escape, Key.F1, Key.F2, Key.F3, Key.F4, Key.F5, Key.F6, Key.F7, Key.F8, Key.F9, Key.F10, Key.F11, Key.F12, Key.Insert, Key.Delete }; private static readonly Key[] Row2 = new Key[] { Key.OemTilde, Key.D1, Key.D2, Key.D3, Key.D4, Key.D5, Key.D6, Key.D7, Key.D8, Key.D9, Key.D0, Key.OemMinus, Key.OemEquals, Key.Backspace }; private static readonly Key[] Row3 = new Key[] { Key.Tab, Key.Q, Key.W, Key.E, Key.R, Key.T, Key.Y, Key.U, Key.I, Key.O, Key.P, Key.OemLeftBracket, Key.OemRightBracket, Key.OemBackslash }; private static readonly Key[] Row4 = new Key[] { Key.CapsLock, Key.A, Key.S, Key.D, Key.F, Key.G, Key.H, Key.J, Key.K, Key.L, Key.OemSemicolon, Key.OemApostrophe, Key.Enter }; private static readonly Key[] Row5 = new Key[] { Key.LeftShift, Key.Z, Key.X, Key.C, Key.V, Key.B, Key.N, Key.M, Key.OemComma, Key.OemPeriod, Key.OemSlash, Key.RightShift }; public static Key[] GetKeyDefinition(int rowNumber) { switch (rowNumber) { case 1: return Row1; case 2: return Row2; case 3: return Row3; case 4: return Row4; case 5: return Row5; default: throw new IndexOutOfRangeException(); } } } } <file_sep>using System; using System.Windows.Forms; namespace Matrix { static class Program { [STAThread] static void Main() { var animator = new Animator(); animator.Start(); Application.Run(); } } } <file_sep>using Corale.Colore.Core; namespace Matrix { class Gradation { public static Gradation Green => new Gradation(Color.Green, 1.0f); public static Gradation White => new Gradation(Color.White, 1.0f); public static Gradation Empty => new Gradation(); public Color Color => new Color( (byte) (BaseColor.R * Opacity), (byte) (BaseColor.G * Opacity), (byte) (BaseColor.B * Opacity)); public bool IsClear => BaseColor == Color.Black; public Color BaseColor { get; private set; } public float Opacity { get; private set; } public Gradation() { BaseColor = Color.Black; Opacity = 0.0f; } public Gradation(Color baseColor, float opacity) { BaseColor = baseColor; Opacity = opacity; } public Gradation Clone() { return new Gradation(BaseColor, Opacity); } public void FadeOut() { Opacity -= 0.3f; if (Opacity < 0.0f) { Opacity = 0.0f; } } } } <file_sep>using Corale.Colore.Core; using Corale.Colore.Razer.Keyboard; using System; using System.Linq; using System.Threading.Tasks; namespace Matrix { class Animator { private const int Delay = 200; private Random random = new Random(); private IKeyboard instance = Keyboard.Instance; public async void Start() { var gradations = Enumerable .Range(1, KeyDefinitions.Rows) .Select(it => { var keys = KeyDefinitions.GetKeyDefinition(it); return Enumerable .Range(0, keys.Length) .Select(_ => Gradation.Empty) .ToArray(); }) .ToArray(); while (true) { for (var i = 0; i < KeyDefinitions.Rows; i++) { var keys = KeyDefinitions.GetKeyDefinition(i + 1); var gradation = gradations[i]; Draw(keys, gradation); gradations[i] = Next(gradation); } await Task.Delay(Delay); } } private void Draw(Key[] keys, Gradation[] grads) { for (int i = 0; i < keys.Length; i++) { var key = keys[i]; var grad = grads[i]; instance.SetKey(key, grad.Color); } } private Gradation[] Next(Gradation[] arr) { var newArr = new Gradation[arr.Length]; Array.Copy(arr, 0, newArr, 1, arr.Length - 1); newArr[0] = GetNextColor(arr); return newArr; } private Gradation GetNextColor(Gradation[] grads) { var first = grads[0].Clone(); if (first.BaseColor == Color.White) { if (first.Opacity <= 0.4f) { return Gradation.Green; } first.FadeOut(); return first; } if (first.BaseColor == Color.Green) { if (first.Opacity <= 0.0f) { return Gradation.Empty; } if (first.Opacity < 1.0f || random.Next(3) == 0) { first.FadeOut(); } return first; } if (first.IsClear && grads[1].IsClear && grads[2].IsClear) { return random.Next(4) == 0 ? Gradation.Empty : Gradation.White; } return Gradation.Empty; } } }
4d3840c9d4133b377f03e708713b4a7144aa382f
[ "C#" ]
4
C#
CORDEA/Matrix
12a0ff74529baa482305d324fbafdea9e322f073
e8ff02a1201f538d71ae6aa5ee45b2c141d8238a
refs/heads/master
<repo_name>averywei/PowerTrend<file_sep>/PowerTrend/PowerTrend/__init__.py """ Package for PowerTrend. """
74aafd667eaf24e0b393499b2772df630255c4f4
[ "Python" ]
1
Python
averywei/PowerTrend
15f26cf2eb58b4df6246444a717b8a6e587568b4
1f1583373a11ce767018e750651dbecd786f1ea9
refs/heads/master
<file_sep>class Comment < ApplicationRecord belongs_to :article # sets up an ActiveRecord association end <file_sep>class ArticlesController < ApplicationController # inherits from ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new @article = Article.new end def edit @article = Article.find(params[:id]) end def create @article = Article.new(article_params) # instantiating Article if @article.save # saving new Article instance to DB. # returns boolean whether the article was saved or not redirect_to @article else render 'new' end end # used when you want to update a record that already exists # accepts a hash containing the attributes you want to update def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path end # strong parameter: private # private method ensures it can't be called outside its intended context def article_params params.require(:article).permit(:title, :text) end end <file_sep># Rails Blog Tutorial Just working through this tutorial for learning purposes. Specifically learning about ActiveRecord and ActionController. Maybe I'll even refactor Autodidact using Rails. <file_sep># Migrations are Ruby classes that are designed to make it simple to # create and modify database tables. Rails uses rake commands to run # migrations, and it's possible to undo a migration after it's been # applied to your database. # This migration creates a method named 'change' which will be called # when you run this migration. # When you run this migration it will create an 'articles' table with # one string column and a text column. It also creates a timestamp # field to allow Rails to track article creation and update times. class CreateArticles < ActiveRecord::Migration[5.0] def change create_table :articles do |t| t.string :title t.text :text t.timestamps end end end
16feb88c199f87f04c8ca20fed8aa1e51e3a7c99
[ "Markdown", "Ruby" ]
4
Ruby
ashleyabrooks/rails-blog-tutorial
e5b075ff6a5f6306901e956642173fe6be267600
1539ed893cb300bfd261267e614aa05967d06b7a
refs/heads/master
<repo_name>nzaouesgi/doodlejump_ia<file_sep>/maze5AL1-arcade-ann.py import arcade import numpy as np from sklearn.neural_network import MLPRegressor MAZE = """ ##.######## # # # # # # # # # # ########*## """ UP, DOWN, LEFT, RIGHT = 'U', 'D', 'L', 'R' ACTIONS = [UP, DOWN, LEFT, RIGHT] REWARD_IMPOSSIBLE = -60 REWARD_STUCK = -6 REWARD_DEFAULT = -1 REWARD_GOAL = 60 DEFAULT_LEARNING_RATE = 1 DEFAULT_DISCOUNT_FACTOR = 0.5 SPRITE_SIZE = 64 class Environment: def __init__(self, text): self.states = {} lines = text.strip().split('\n') self.height = len(lines) self.width = len(lines[0]) for row in range(self.height): for col in range(len(lines[row])): self.states[(row, col)] = lines[row][col] if lines[row][col] == '.': self.starting_point = (row, col) elif lines[row][col] == '*': self.goal = (row, col) def apply(self, state, action): if action == UP: new_state = (state[0] - 1, state[1]) elif action == DOWN: new_state = (state[0] + 1, state[1]) elif action == LEFT: new_state = (state[0], state[1] - 1) elif action == RIGHT: new_state = (state[0], state[1] + 1) if new_state in self.states: #calculer la récompense if self.states[new_state] in ['#', '.']: reward = REWARD_STUCK elif self.states[new_state] in ['*']: #Sortie du labyrinthe : grosse récompense reward = REWARD_GOAL else: reward = REWARD_DEFAULT else: #Etat impossible: grosse pénalité new_state = state reward = REWARD_IMPOSSIBLE return new_state, reward class Agent: def __init__(self, environment): self.environment = environment self.policy = Policy(ACTIONS, environment.width, environment.height) self.reset() def reset(self): self.state = environment.starting_point self.previous_state = self.state self.score = 0 def best_action(self): return self.policy.best_action(self.state) def do(self, action): self.previous_state = self.state self.state, self.reward = self.environment.apply(self.state, action) self.score += self.reward self.last_action = action def update_policy(self): self.policy.update(agent.previous_state, agent.state, self.last_action, self.reward) class Policy: #ANN def __init__(self, actions, width, height, learning_rate = DEFAULT_LEARNING_RATE, discount_factor = DEFAULT_DISCOUNT_FACTOR): self.learning_rate = learning_rate self.discount_factor = discount_factor self.actions = actions self.maxX = width self.maxY = height self.mlp = MLPRegressor(hidden_layer_sizes = (8,), activation = 'tanh', solver = 'sgd', learning_rate_init = self.learning_rate, max_iter = 1, warm_start = True) self.mlp.fit([[0, 0]], [[0, 0, 0, 0]]) self.q_vector = None def __repr__(self): return self.q_vector def state_to_dataset(self, state): return np.array([[state[0] / self.maxX, state[1] / self.maxY]]) def best_action(self, state): self.q_vector = self.mlp.predict(self.state_to_dataset(state))[0] #Vérifier que state soit au bon format action = self.actions[np.argmax(self.q_vector)] return action def update(self, previous_state, state, last_action, reward): #Q(st, at) = Q(st, at) + learning_rate * (reward + discount_factor * max(Q(state)) - Q(st, at)) maxQ = np.amax(self.q_vector) last_action = ACTIONS.index(last_action) print(self.q_vector, maxQ, self.q_vector[last_action]) self.q_vector[last_action] += reward + self.discount_factor * maxQ inputs = self.state_to_dataset(previous_state) outputs = np.array([self.q_vector]) self.mlp.fit(inputs, outputs) class MazeWindow(arcade.Window): def __init__(self, agent): super().__init__(agent.environment.width * SPRITE_SIZE, agent.environment.height * SPRITE_SIZE, "Escape from ESGI") self.agent = agent def setup(self): self.walls = arcade.SpriteList() for state in agent.environment.states: if agent.environment.states[state] == '#': sprite = arcade.Sprite(":resources:images/tiles/grassCenter.png", 0.5) sprite.center_x = sprite.width * (state[1] + 0.5) sprite.center_y = sprite.height * (agent.environment.height - state[0] - 0.5) self.walls.append(sprite) self.goal = arcade.Sprite(":resources:images/items/flagGreen1.png", 0.5) self.goal.center_x = self.goal.width * (self.agent.environment.goal[1] + 0.5) self.goal.center_y = self.goal.height * (agent.environment.height - self.agent.environment.goal[0] - 0.5) self.player = arcade.Sprite(":resources:images/animated_characters/robot/robot_idle.png", 0.5) self.update_player_xy() def update_player_xy(self): self.player.center_x = self.player.height * (self.agent.state[1] + 0.5) self.player.center_y = self.player.height * (agent.environment.height - self.agent.state[0] - 0.5) def on_update(self, delta_time): if agent.state != environment.goal: action = self.agent.best_action() self.agent.do(action) self.agent.update_policy() self.update_player_xy() def on_key_press(self, key, modifiers): if key == arcade.key.R: self.agent.reset() def on_draw(self): arcade.start_render() self.walls.draw() self.goal.draw() self.player.draw() arcade.draw_text(f"Score: {self.agent.score}", 10, 10, arcade.csscolor.WHITE, 20) if __name__ == "__main__": #Initialiser l'environment environment = Environment(MAZE) #Initialiser l'agent agent = Agent(environment) #Lancer le jeu window = MazeWindow(agent) window.setup() arcade.run() <file_sep>/doodle.py import random import time import arcade import numpy as np from sklearn.neural_network import MLPRegressor X = 0 Y = 1 GAME_WIDTH = 600 GAME_HEIGHT = 30000 VIEWPORT_WIDTH = 800 VIEWPORT_HEIGHT = 1000 PLATFORM_WIDTH = 50 MOVE_X = 10 MOVE_Y = 20 MAX_JUMP_HEIGHT = 250 GRAVITY = 0.60 ACTION_NOTHING = 0 ACTION_GOING_LEFT = 1 ACTION_GOING_RIGHT = 2 ACTIONS = [ ACTION_NOTHING, ACTION_GOING_LEFT, ACTION_GOING_RIGHT ] LEARNING_RATE = 1 DISCOUNT_FACTOR = 0.5 DECISION_TIMEOUT = 0.1 DEFAULT_REWARD = -10 NEXT_PLATFORM_REWARD = 50 DEAD_REWARD = -50 def load_texture_pair(filename): return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ] class Game(arcade.Window): def __init__(self, agent, environment): super().__init__(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, "Doodle Jump") self.environment = environment self.agent = agent self.decision_timeout = 0 self.current_action = ACTION_NOTHING self.dead = False self.new_platform = False self.background = arcade.load_texture("resources/bck.png") def setup(self): self.environment.reset() self.dead = False self.current_platform_index = 0 self.last_height = self.environment.current_height self.physics_engine = arcade.PhysicsEnginePlatformer(self.environment.player, arcade.SpriteList( use_spatial_hash=True), GRAVITY) self.physics_engine.disable_multi_jump() arcade.set_viewport( 0, VIEWPORT_WIDTH, 0, VIEWPORT_HEIGHT ) def on_draw(self): # Clear the screen to the background color arcade.start_render() (left, _right, bottom, _top) = arcade.get_viewport() arcade.draw_lrwh_rectangle_textured(left, bottom, VIEWPORT_WIDTH, VIEWPORT_HEIGHT, self.background) # Draw our sprites self.environment.platforms.draw() self.environment.player.draw() def set_effective_platforms(self): effective_platforms = arcade.SpriteList(use_spatial_hash=True) for platform in self.environment.platforms: if platform.top <= self.environment.player.bottom: effective_platforms.append(platform) self.physics_engine.platforms = effective_platforms def move_left(self): self.environment.player.change_x = -MOVE_X self.environment.player.set_texture(0) def move_right(self): self.environment.player.change_x = MOVE_X self.environment.player.set_texture(1) def scroll_viewport(self): (_left, _right, bottom, top) = arcade.get_viewport() new_bottom = bottom new_top = top must_scroll = False if bottom < self.environment.current_height: new_bottom = bottom + 10 must_scroll = True if new_top < VIEWPORT_HEIGHT + self.environment.current_height: new_top = top + 10 must_scroll = True if must_scroll: arcade.set_viewport( 0, VIEWPORT_WIDTH, new_bottom, new_top ) def update_game (self): self.set_effective_platforms() if self.current_action == ACTION_GOING_LEFT: self.move_left() elif self.current_action == ACTION_GOING_RIGHT: self.move_right() else: self.environment.player.change_x = 0 if self.environment.player.change_y <= 0.0: if self.physics_engine.can_jump(): for i, platform in enumerate(self.environment.platforms): if platform.top < self.environment.player.bottom and i >= self.current_platform_index : if self.current_platform_index != i: self.current_platform_index = i self.environment.current_height = self.environment.platforms[self.current_platform_index].bottom self.new_platform = True self.physics_engine.jump(MOVE_Y) self.physics_engine.update() if self.environment.player.top <= self.environment.current_height: self.dead = True self.setup() if self.environment.player.right < 0: self.environment.player.left = VIEWPORT_WIDTH elif self.environment.player.left > VIEWPORT_WIDTH: self.environment.player.right = 0 self.scroll_viewport() def get_reward (self): if self.dead: return DEAD_REWARD elif self.new_platform: return NEXT_PLATFORM_REWARD print(self.current_platform_index) state = self.environment.get_state(self.environment.platforms[self.current_platform_index + 1]) player_x = state[0] next_platform_x = state[1] distance = player_x - next_platform_x if player_x >= next_platform_x else next_platform_x - player_x percentage = -(abs((distance / VIEWPORT_WIDTH) * 100) // 2) return percentage def on_update(self, delta_time): self.decision_timeout += delta_time decide = False if self.decision_timeout >= DECISION_TIMEOUT: self.decision_timeout = 0 decide = True self.current_action = self.agent.best_action() self.update_game() if decide: reward = self.get_reward() self.agent.learn( self.current_action, self.environment.get_state(self.environment.platforms[self.current_platform_index]), reward) self.dead = False self.new_platform = False class Agent: def __init__(self, environment): self.environment = environment self.policy = Policy() self.reset() def reset(self): self.state = self.environment.get_state(self.environment.platforms[0]) self.score = 0 def best_action (self): return self.policy.best_action(self.state) def learn(self, action, new_state, reward): previous_state = self.state self.policy.update(previous_state, new_state, action, reward) self.state = new_state self.score += reward class Policy: #ANN def __init__(self): self.learning_rate = LEARNING_RATE self.discount_factor = DISCOUNT_FACTOR self.actions = ACTIONS self.maxX = VIEWPORT_WIDTH self.maxY = VIEWPORT_HEIGHT self.mlp = MLPRegressor(hidden_layer_sizes = (2,), activation = 'tanh', solver = 'adam', learning_rate_init = self.learning_rate, max_iter = 1, warm_start = True) self.mlp.fit([[0, 0]], [[0, 0, 0]]) self.q_vector = [ 0, 0, 0 ] def __repr__(self): return self.q_vector def state_to_dataset(self, state): return np.array([ [ #state[0][0] / self.maxX, state[0][1] / self.maxY, #state[1][0] / self.maxX, state[1][1] / self.maxY state[0] / self.maxX, state[1] / self.maxX ] ]) def best_action(self, state): dataset = self.state_to_dataset(state) self.q_vector = self.mlp.predict(dataset)[0] #Vérifier que state soit au bon format action = self.actions[np.argmax(self.q_vector)] return action def update(self, previous_state, state, last_action, reward): #Q(st, at) = Q(st, at) + learning_rate * (reward + discount_factor * max(Q(state)) - Q(st, at)) maxQ = np.amax(self.q_vector) self.q_vector[last_action] += reward + self.discount_factor * maxQ #self.q_vector[last_action] = reward inputs = self.state_to_dataset(previous_state) outputs = np.array([self.q_vector]) self.mlp.fit(inputs, outputs) class Environment: def __init__(self): self.level_platforms_coordinates = self.generate_platforms_coordinates() self.reset() def reset (self): self.setup_platforms() self.setup_player() self.current_height = 0 def get_state(self, next_platform): return [ #(self.player.center_x, self.player.center_y), #self.get_next_platform_coordinates() self.player.center_x, next_platform.center_x ] def setup_platforms(self): self.platforms = arcade.SpriteList(use_spatial_hash=True) for coordinates in self.level_platforms_coordinates: sprite = arcade.Sprite("resources/platform.png", 1) sprite.center_x = coordinates[X] sprite.center_y = coordinates[Y] self.platforms.append(sprite) def setup_player(self): first_platform = self.platforms[0] filename = "resources/doodle_left.png" self.player = arcade.Sprite(scale=0.5) for t in load_texture_pair(filename): self.player.append_texture(t) self.player.set_texture(0) self.player.center_x = first_platform.center_x self.player.bottom = first_platform.bottom + first_platform.height def generate_platforms_coordinates(self): current_height = 50 coordinates = [ ((GAME_WIDTH / 2), current_height) ] min_decay = 30 max_decay = 60 while current_height <= GAME_HEIGHT: x = random.randint( 0, GAME_WIDTH - PLATFORM_WIDTH ) y = random.randint( current_height + min_decay, current_height + MAX_JUMP_HEIGHT ) if random.choice([ True, False ]): if min_decay < max_decay: min_decay += 1 current_height = y c = (x, y) coordinates.append(c) return coordinates if __name__ == "__main__": environment = Environment() agent = Agent(environment) window = Game(agent, environment) window.setup() arcade.run()
7db452c3051f9a0bdd0d6fe3c07e840e3e71ea10
[ "Python" ]
2
Python
nzaouesgi/doodlejump_ia
f583c92065e11856f787cd3fd178821a420c37ec
fd446fa25e5f13b257e28698a0c4b8e06675aab2
refs/heads/master
<file_sep>import requests from lxml import html import os import time __author__ = 'dh_liu' # 用log函数把所有输出写入到文件 def log(*args, **kwargs): t = '%Y/%m/%d %H:%M:%S' value = time.localtime(int(time.time())) dt = time.strftime(t, value) # 中文windows平台默认打开的文件编码是gbk所以需要指定一下 with open('log.gua.txt', 'a', encoding='utf-8') as f: # 通过file参数可以把输出写入到文件f中 print(dt, *args, file=f, **kwargs) class Model(object): def __repr__(self): class_name = self.__class__.__name__ properties = ('{} = ({})'.format(k, v) for k, v in self.__dict__.items()) r = '\n<{}:\n {}\n>'.format(class_name, '\n '.join(properties)) return r # 定义电影类 class Movie(Model): def __init__(self): self.name = '' self.score = 0 self.quote = '' self.cover_url = '' self.rank = 0 # 下载爬取网页的页面数据, 并保存为 html 格式 def cached_url(url): filename = url.split('=')[-1] + '.html' path = os.path.join('cache', filename) # 避免重复下载 if os.path.exists(path): with open(path, 'rb') as f: return f.read() else: r = requests.get(url) with open(path, 'wb') as f: f.write(r.content) return r.content # 下载电影封面 def download_img(url, name): filename = name path = os.path.join('image', filename) # 避免重复下载 if not os.path.exists(path): r = requests.get(url) with open(path, 'wb') as f: f.write(r.content) # save 数据 def save(movies): for m in movies: download_img(m.cover_url, m.name + 'jpg') # 获取电影大div中的要爬取的元素 def movie_from_div(div): movie = Movie() movie.name = div.xpath('.//span[@class="title"]')[0].text movie.score = div.xpath('.//span[@class="rating_num"]')[0].text try: movie.quote = div.xpath('.//span[@class="inq"]')[0].text except IndexError as e: movie.quote = '消失的爱人竟然没有引用' img_url = div.xpath('//div[@class="pic"]/a/img/@src')[0] movie.cover_url = img_url movie.rank = div.xpath('.//div[@class="pic"]/em')[0].text return movie # 解析单个电影的所有数据(在一个 div 标签中) def movies_from_url(url): # 下载页面 page = cached_url(url) # 下载页面是一个 html 文件, 用函数解析一下, 方便之后进行查找 root = html.fromstring(page) movie_divs = root.xpath('//div[@class="item"]') movies = [] for div in movie_divs: movie = movie_from_div(div) movies.append(movie) return movies def main(): for i in range(0, 250, 25): url = 'https://movie.douban.com/top250?start={}'.format(i) movies = movies_from_url(url) log(movies) save(movies) if __name__ == '__main__': main() <file_sep># douban_pachong 简单豆瓣爬虫练习
cf4eec85314f5c0845a9bcb65143e78298457b5d
[ "Markdown", "Python" ]
2
Python
lldhliu/douban_pachong
12e73e218d704281c8283f5745366bd18989ceee
99ac03772b987eb933579f8d9a344862febd807a
refs/heads/main
<file_sep><?php $config['serveur']='localhost'; $config['login']='login8024'; $config['mdp']='TxNNSBufHmQvQtJ'; $config['bd']='dblogin8024'; ?><file_sep><?php require_once 'controleur.php'; ?><file_sep><?php function getPage(){ $lesPages['accueil'] = "accueilControleur"; $lesPages['contact'] = "contactControleur"; $lesPages['mention'] = "mentionControleur"; $lesPages['apropos'] = "aproposControleur"; $lesPages['catalogue'] = "catalogueControleur"; $lesPages['connexion'] = "connexionControleur"; $lesPages['inscription'] = "inscriptionControleur"; $lesPages['4chetteprime'] = "fourchetteprimeControleur"; if (isset($_GET['page'])){ $page = $_GET['page']; } else{ $page = 'accueil'; } if (isset($lesPages[$page])){ $contenu = $lesPages[$page]; } else{ $contenu = $lesPages['accueil']; } return $contenu; } ?><file_sep><?php function accueilControleur($twig){ echo $twig->render('accueil.html.twig',array()); } function contactControleur($twig){ echo $twig->render('contact.html.twig',array()); } function mentionControleur($twig){ echo $twig->render('mention.html.twig',array()); } function aproposControleur($twig){ echo $twig->render('apropos.html.twig',array()); } function catalogueControleur($twig){ echo $twig->render('catalogue.html.twig',array()); } function connexionControleur($twig){ echo $twig->render('connexion.html.twig',array()); } function inscriptionControleur($twig){ $form = array(); if (isset($_POST['btInscrire'])){ $inputEmail = $_POST['inputEmail']; $inputPassword = $_POST['inputPassword']; $inputPassword2 = $_POST['<PASSWORD>']; $role = $_POST['role']; $form['valide'] = true; if ($inputPassword!=$inputPassword2){ $form['valide'] = false; $form['message'] = 'Les mots de passe sont différents'; } $form['email'] = $inputEmail; $form['role'] = $role; } echo $twig->render('inscription.html.twig',array('form'=>$form)); } function fourchetteprimeControleur($twig){ echo $twig->render('4chetteprime.html.twig',array()); } ?>
7b6613f65295794b05dabddb220990b54ff8d49a
[ "PHP" ]
4
PHP
Aryshia/phpecole
971af304d32c5c9add62387058267dc5c6c6334e
0466cc8d0c751869fc2d1d0854502f4afa669866
refs/heads/master
<file_sep><?php ob_start(); session_start(); if(file_exists('admin/_conf.php')) { include('admin/_conf.php'); } elseif(file_exists('../admin/_conf.php')) { include('../admin/_conf.php'); } elseif(file_exists('../../admin/_conf.php')) { include('../../admin/_conf.php'); } elseif(file_exists('../../../admin/_conf.php')) { include('../../../admin/_conf.php'); } else { include('../../../admin/_conf.php'); } ?> <?php if(file_exists('admin/_inc/functions.php')) { include('admin/_inc/functions.php'); } elseif(file_exists('../admin/_inc/functions.php')) { include('../admin/_inc/functions.php'); } elseif(file_exists('../../admin/_inc/functions.php')) { include('../../admin/_inc/functions.php'); } elseif(file_exists('../../../admin/_inc/functions.php')) { include('../../../admin/_inc/functions.php'); } else { include('../../../admin/_inc/functions.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <title><?php get_options('building_info', 'val_1', true); ?></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--/ css link /--> <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="main.css"> <!--/ javascript src /--> <script src="js/jquery.js"></script> <script src="js/validation.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/main.js"></script> </head> <body> <?php include 'admin/admin_menu.php'; ?> <?php include 'admin/account_menu.php'; ?> <header> <div class="navbar navbar-default navbar-top m-none"> <div class="container"> <div class="row"> <div class="col-md-8 collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="index.php">Ana Sayfa</a></li> <?php index_navigation(); ?> <li><a href="contact.php">İletişim</a></li> </ul> </div><!--/ .collapse /--> <div class="col-md-4 navbar-right"> <ul class="nav navbar-nav"> <li><a href="<?php get_options('facebook', 'val_1', true); ?>"><i class="fa fa-facebook"></i></a></li> <li><a href="<?php get_options('twitter', 'val_1', true); ?>"><i class="fa fa-twitter"></i></a></li> <li><a href="<?php get_options('instagram', 'val_1', true); ?>"><i class="fa fa-instagram"></i></a></li> <li><a href="<?php get_options('google_plus', 'val_1', true); ?>"><i class="fa fa-google-plus"></i></a></li> </ul> </div><!--/ .navbar-nav /--> </div><!--/ .row /--> </div><!--/ .container /--> </div><!--/ .navbar-top /--> <div class="header-body"> <div class="container"> <div class="row"> <div class="header-body-item"> <div class="col-md-6"> <a class="navbar-brand" href="index.php"><span><img src="image/logo.png" class="img-responsive logo" alt="RulmanSoft.com"></span><span class="logo-text">RulmanSoft</span></a> </div><!--/ .col-md-6 /--> <div class="col-md-6 pull-right m-none"> <div class="phone"><i class="fa fa-mobile"></i> Tel : <?php get_options('phone', 'val_1', true); ?></div> <div class="emails"><i class="fa fa-envelope"></i> <?php get_options('email', 'val_1', true); ?></div> </div> </div><!--/ .header-bodu-item /--> </div><!--/ .row /--> </div><!--/ .header-body/--> </div><!--/ .header-body /--> </header> <div class="container BW main-container"> <div class="row"> <nav class="navbar navbar-default navbar-header"> <div class="col-md-2 col-xs-12 pull-right"> <button type="button" class="pull-left ml10 navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="search"> <i class="fa fa-search"></i> <div class="search-box"> <form method="get" action="search.php"> <div class="row no-space"> <div class="col-md-9 col-xs-9"> <input type="text" name="search" class="form-control" placeholder="<NAME>"> </div><!--/ .col-md-9 /--> <div class="col-md-3 col-xs-3"> <input type="submit" value="Ara"> </div><!--/ .col-md-3 /--> </div><!--/ .row /--> </form> </div><!--/ .search-box /--> </div><!--/ .search /--> </div><!--/ .col-md-2s /--> <div class="collapse navbar-collapse col-md-10" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="index.php">Ana Sayfa</a></li> <?php index_navigation(); ?> <?php if(!is_login()): ?> <li><a href="login.php">Girişi Yap</a></li> <li><a href="register.php">Üye ol</a></li> <?php endif; ?> <li class="pull-right"><a href="contact.php">İletişim</a></li> </ul> </div><!--/ .collpase /--> </nav> </div><!--/ .row /--> <file_sep><?php /* Rulman Soft Hazır Codlar ve Tanımları */ /*---------------------------- Pages.php Sayfası için ----------------------------*/ $page = get_page($_GET['id']); // get_pages fonksiyonu ile pages tablosundaki verileri alabiliyoruz $page->$id; // id'si $page->$status; // statusü $page->$date; // tarihini $page->$upload_date; // son güncellenme tarihini $page->$title; // bağlığını $page->$content; // içeriğini /*---------------------------- news.php Sayfası için ----------------------------*/ $news = get_news($_GET['id']); // get_news fonksiyonu ile news tablosundaki verileri alabiliyoruz $news->$id; // id'si $news->$status; // statusü $news->$date; // tarihini $news->$upload_date; // son güncellenme tarihini $news->$title; // bağlığını $news->$list_img; // haberler listesindeki öne çıkarılmış resim $news->$content; // içeriğini /*----------------------------/ Firma Genel Bilgileri /----------------------------*/ /* Firma adı */ get_options('building_info', 'val_1', true); /* Firma Telefon */ get_options('phone', 'val_1', true); /* Yetkili Kişi Telefon */ get_options('mobile_phone', 'val_1', true); /* E-Mail */ get_options('email', 'val_1', true); /* Fax */ get_options('fax', 'val_1', true); /* İl - İlçe */ get_options('province', 'val_1', true); /* Ülke */ get_options('country', 'val_1', true); /* Adres Bilgileri */ get_options('address', 'val_1', true); /* Firma hakıımızda bilgileri */ get_options('information', 'val_1', true); /*----------------------------/ <NAME> /-----------------------------------*/ /* Facebook */ get_options('facebook', 'val_1', true); /* Twitter */ get_options('twitter', 'val_1', true); /* İnstagram */ get_options('instagram', 'val_1', true); /* Google+ */ get_options('google_plus', 'val_1', true); /*----------------------------/ Api Hizmetleri /-----------------------------------*/ /* Google Analytics */ get_options("google_analytics", 'val_1', true); /* Google Remarketing */ get_options("google_remarketing", 'val_1', true); /* Google Haritalar */ get_options("google_map", 'val_1', true); /* Facebook Pixel */ get_options("facebook_pixel", 'val_1', true); /* Facebook Remarketing */ get_options("facebook_remarketing", 'val_1', true); /* Yandex */ get_options("yandex_analytics", 'val_1', true); ?> <file_sep><?php $corporate['company_name'] = ''; $corporate['name'] = ''; $corporate['surname'] = ''; $corporate['email'] = ''; $corporate['gsm'] = ''; $corporate['password'] = ''; $corporate['district'] = ''; $corporate['city'] = ''; $corporate['district'] = ''; $corporate['city'] = ''; $corporate['country'] = ''; $corporate['address'] = ''; if(isset($_POST['submit'])) { $corporate['company_name'] = mb_ucwords(form_input_control($_POST['company_name'])); $corporate['name'] = mb_ucwords(form_input_control($_POST['name'])); $corporate['surname'] = mb_ucwords(form_input_control($_POST['surname'])); $corporate['email'] = strtolower(form_input_control($_POST['email'])); $corporate['gsm'] = convert_gsm(form_input_control($_POST['gsm'])); $corporate['password'] = form_input_control($_POST['password']); $corporate['city'] = form_input_control($_POST['city']); $corporate['district'] = form_input_control($_POST['district']); $corporate['country'] = form_input_control($_POST['country']); $corporate['address'] = form_input_control($_POST['address']); // form string kontrolleri form_string_control($corporate['company_name'], 'Firma adı', array('min'=>3, 'max'=>50)); form_string_control($corporate['name'], 'Ad', array('min'=>3, 'max'=>50)); form_string_control($corporate['surname'], 'Soyad', array('min'=>3, 'max'=>50)); form_string_control($corporate['email'], 'E-posta', array('required'=>true, 'is_mail'=>true)); form_string_control($corporate['gsm'], 'Cep telefonu', array('required'=>true, 'is_gsm'=>true)); form_string_control($corporate['password'], 'Şifre', array('required'=>true, 'min'=>6, 'max'=>32)); form_string_control($corporate['city'], 'Şehir', array('required'=>true, 'min'=>3)); form_string_control($corporate['country'], 'Ülke', array('required'=>true, 'min'=>3)); form_string_control($corporate['address'], 'Adres', array('required'=>true, 'min'=>10)); if(!is_form_error()) { $corporate['status'] = '1'; $corporate['date'] = date('Y-m-d H:i:s'); $corporate['user_type'] = 'corporate'; if(is_user("gsm='".$corporate['gsm']."'") > 0) { array_push($err_msg, '<strong>'.$corporate['gsm'].'</strong> telefon numarasına ait üyelik bulunmakta. Üyelik ile ilgili problem yaşıyorsanız <a href="'.site_url('iletisim').'" target="_blank">iletişim</a> sayfasından bizimle iletişime geçebilirsiniz.'); } elseif(is_user("email='".$corporate['email']."'") > 0) { array_push($err_msg, '<strong>'.$corporate['email'].'</strong> e-posta numarasına ait üyelik bulunmakta. Üyelik ile ilgili problem yaşıyorsanız <a href="'.site_url('iletisim').'" target="_blank">iletişim</a> sayfasından bizimle iletişime geçebilirsiniz.'); } else { // her sey duzgun ise veritabani ekleyelim $corporate_id = add_user($corporate); if($corporate_id > 0) { $corporate = get_user($corporate_id); $_SESSION['login_id'] = $corporate['id']; header("Location: ".account_url('')); } } } } ?> <?php if(is_form_error()): ?><div class="row"><div class="col-md-3"></div><div class="col-md-6"> <?php print_alert($err_msg, 'danger', 'false'); ?> </div> <!-- /.col-md-3 --><div class="col-md-3"></div></div> <!-- /.row --> <?php endif; ?> <div class="row"> <div class="col-md-3"></div><!--/ .col-md-3 /--> <div class="col-md-6"> <form action="" method="post" class="login-register validate"> <h3>Üye Kayıt Formu</h3> <div class="form-group"> <input type="text" name="company_name" value="" placeholder="Firma Adı" class="form-control"> </div><!--/ .form-group /--> <div class="row"> <div class="col-md-6"> <input type="text" minlength="3" name="name" value="" placeholder="Ad" class="form-control required"> </div><!--/ .col-md-6 /--> <div class="col-md-6"> <input type="text" minlength="3" name="surname" value="" placeholder="Soyad" class="form-control required"> </div><!--/ .col-md-6 /--> </div><!--/ .row /--> <div class="form-group mt20"> <input type="email" minlength="3" name="email" value="" placeholder="E-Posta Adresiniz" class="form-control required"> </div><!--/ .form-group /--> <div class="form-group"> <input type="password" minlength="8" maxlength="16" name="password" value="" placeholder="<PASSWORD>" class="form-control required"> </div><!--/ .form-group /--> <div class="form-group"> <input type="number" minlength="10" maxlength="11" name="gsm" value="" placeholder="Telefon Numarası" class="form-control required digits"> </div><!--/ .form-group /--> <div class="row"> <div class="col-md-6"> <input type="text" name="city" value="" maxlength="20" placeholder="İl" class="form-control required"> </div><!--/ .col-md-6 /--> <div class="col-md-6"> <input type="text" name="district" value="" maxlength="20" placeholder="İlçe" class="form-control required"> </div><!--/ .col-md-6 /--> </div><!--/ .form-group /--> <div class="form-group mt20"> <input type="text" class="form-control" name="country" maxlength="20" value="" placeholder="Ülke"> </div><!--/ .form-group /--> <div class="form-group"> <textarea name="address" rows="4" cols="40" class="form-control" placeholder=""></textarea> </div><!--/ .form-group /--> <div class="form-group"> <input type="submit" name="submit" value="Gönder" class="btn btn-success required"> <span style="margin-top: 25px;" class="pull-right m-none"> Sitemize üyeliğiniz var mı? <a href="<?php echo account_url('login.php'); ?>">Üye giriş paneli</a>.</span> </div><!--/ .form-group /--> </form> </div><!--/ .col-md-6 /--> <div class="col-md-3"></div><!--/ .col-md-3 /--> </div><!--/ .row /--> <file_sep><?php include '_inc/header.php'; //Get Header ?> <?php if(isset($_GET['id'])): $news = get_news($_GET['id']); if($news): if($news->status == 1):?> <div class="paragraf p30"> <div class="title"> <h3 class="CG"><?php echo $news->title; ?></h3> </div> </div><!--/ .paragraf /--> <div class="content mtb20 p20"> <?php echo $news->content; ?> </div><!--/ .content /--> </div><!--/ .row /--> <?php else: ?> <?php get_alert('Aradığınız Haber Daha Önce Silinmiş!', '', 'danger mtb40', 'false'); ?> <?php endif; ?> <?php else: ?> <?php include '_inc/404.php' ?> <?php endif; ?> <?php else: ?> <div class="row"> <div class="col-md-1"></div> <div class="col-md-10"> <?php $results = get_list_news(); if($results): ?> <?php while($lists = $results->fetch_object()): if($lists->status == 1): ?> <div class="news"> <div class="title cnb"><h3><a class="CNB" href="?id=<?php echo $lists->id; ?>"><?php echo $lists->title; ?></a></h3></div> <div class="content"> <div class="row"> <div class="col-md-4"> <a href="?id=<?php echo $lists->id; ?>"><img src="admin/upload/news/<?php if($lists->list_img){ echo $lists->list_img; }else{ echo 'image/img-none.png'; } ?>" class="img-responsive" alt="" /></a> </div> <div class="col-md-8"> <p class="mtb10"><?php echo strip_tags(substr($lists->content, 0, 500).'...'); ?></p> <a href="?id=<?php echo $lists->id; ?>" class="btn btn-nb pull-right">Devamı...</a> </div> </div> </div> </div> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> </div> <div class="col-md-1"></div> </div> <?php endif; ?> <?php include '_inc/footer.php'; //Get Footer ?> <file_sep><?php include '_conf.php'; ?> <?php include '_inc/functions.php'; ?> <link rel="stylesheet" href="css/bootstrap.min.css" media="screen" title="no title" charset="utf-8"> <?php if(isset($_GET['print_address'])): $order = orders_detail($_GET['print_address']); ?> <div class="row"> <div class="col-md-6"> <h3>Gönderen Adres</h3> <table class="table table-bordered table-hover table-condensed"> <tr> <td class="col-md-4"><b>Firma Adı: </b></td> <td><?php get_options('building_info', 'val_1', true); ?></td> </tr> <tr> <td><b>Yekili Telefon</b></td> <td><?php get_options('mobile_phone', 'val_1', true); ?></td> </tr> <tr> <td><b>Firma Telefon</b></td> <td><?php get_options('phone', 'val_1', true); ?></td> </tr> <tr> <td><b>İl - İlçe</b></td> <td><?php get_options('province', 'val_1', true); ?></td> </tr> <tr> <td><b>Adress</b></td> <td><?php get_options('address', 'val_1', true); ?></td> </tr> </table> </div><!--/ .col-md-6 /--> <div class="col-md-6"> <h3>Alıcı Adres</h3> <table class="table table-bordered table-hover table-condensed"> <tr> <td class="col-md-4"><b>Firma Adı: </td> <td><?php echo $order->company_name; ?></td> </tr> <tr> <td><b>Adı - Soyadı</td> <td><?php echo $order->name; ?> - <?php echo $order->surname; ?></td> </tr> <tr> <td><b>Yekili Telefon</td> <td><?php echo $order->phone; ?></td> </tr> <tr> <td><b>Son Sipariş</td> <td><?php echo time_late($order->date); ?></td> </tr> <tr> <td><b>İl - İlçe</td> <td><?php echo $order->city; ?> <?php echo $order->district; ?></td> </tr> <tr> <td><b>Adress</td> <td><?php echo $order->address; ?></td> </tr> </table> </div><!--/ .col-md-6 /--> </div><!--/ .row /--> <?php elseif(isset($_GET['print_orders'])): $order = orders_detail($_GET['print_orders']); ?> <h3>Sipariş Formu</h3> <table class="table table-bordered table-hover table-condensed"> <thead> <tr> <td><b>Ürün Markası: </b></td> <td><?php echo $order->product_brand; ?></td> </tr> <tr> <td><b>Ürün Kodu: </b></td> <td><?php echo $order->product_code; ?> <?php echo $order->code_type; ?></td> </tr> <tr> <td><b>Sipariş Adedi: </b></td> <td><?php echo $order->amount; ?></td> </tr> <tr> <td><b>Son İşlem Tarihi</b></td> <td><?php echo substr($order->date_update, '0', '10'); ?> - <?php echo substr($order->date_update, '10', '6'); ?></td> </tr> <tr> <td><b>Satış Fiyatı</b></td> <td> <?php echo $order->sale_price; ?> <?php if($order->currency == '0'): ?> ₺ <?php elseif($order->currency == '1'): ?> $ <?php elseif($order->currency == '2'): ?> € <?php endif; ?> </td> </tr> </thead> </table> <?php endif; ?> <script> window.print(); $(document).keydown(function(e) { // ESCAPE key pressed if (e.keyCode == 27) { window.close(); } }); </script> <file_sep><div class="h50 hidden-xs hidden-sm"></div> </div> <!-- /.container [header.php]--> <footer> <div class="footer-bottom"> <div class="container"> <div class="pull-left">© <?php get_options('building_info', 'val_1', true); ?>, 2016 tüm hakları saklıdır.</div> <div class="pull-right">© Alt yapı <a href="http://rulmansoft.com" title="RulmanSoft" target="_blank" style="text-decoration:underline;">RulmanSoft.com</a> ekibi tarafından yazılmıştır.</div> </div> <!-- /.container --> </div> <!-- /.footer-bottom --> </footer> </body> </html> <file_sep><div class="row"> <div class="col-md-1"></div> <div class="col-md-10 col-xs-12" itemscope itemtype="http://schema.org/Product"> <?php $list_id = form_input_control($_GET['list_id']); ?> <?php $list = get_single_list($list_id); ?> <?php $corporate = get_user($list['user_id']); ?> <ol class="breadcrumb hidden-xs hidden-sm"> <li><a href="<?php echo $theme_url; ?>">Anasayfa</a></li> <li><a href="<?php echo site_url(''); ?>"><?php echo $corporate['company_name']; ?></a></li> <li class="active"><?php echo brand($list['brand_id'],'name'); ?> <?php echo $list['code']; ?> <?php echo $list['code_type']; ?></li> </ol> <h3 class="text-danger" itemprop="name"><span itemprop="brand"><?php echo brand($list['brand_id']); ?></span> <?php echo $list['code']; ?> <?php echo $list['code_type']; ?></h3> <?php $result = mysqli()->query("SELECT * FROM product WHERE brand_id='".$list['brand_id']."' AND code='".$list['code']."' AND code_type='".$list['code_type']."'"); ?> <?php if($result->num_rows > 0): ?> <?php $product = $result->fetch_assoc(); ?> <div class="bg-muted padding5"> <table class="table table-condensed fs-11" style="margin-bottom:0px;"> <thead> <tr> <th>İç (d)</th> <th>Dış (D)</th> <th>En (B)</th> <th>Ağırlık</th> <th>Referans Hızı</th> <th>Devir Hızı</th> </tr> </thead> <tbody> <tr> <td><?php echo $product['d0']; ?> <span class="text-muted">mm</span></td> <td><?php echo $product['D']; ?> <span class="text-muted">mm</span></td> <td><?php echo $product['B']; ?> <span class="text-muted">mm</span></td> <td><?php echo $product['mass']; ?> <span class="text-muted">kg</span></td> <td><?php echo $product['reference_speed']; ?> <span class="text-muted">/dakika</span></td> <td><?php echo $product['limiting_speed']; ?> <span class="text-muted">/dakika</span></td> </tr> </tbody> </table> </div> <!-- /.bg-muted --> <div class="h20"></div> <?php endif; ?> <div class="row"> <div class="col-md-5" itemprop="offers" itemscope itemtype="http://schema.org/Offer"> <table class="table table-condensed fs-13"> <tr> <th width="80">Fiyat</th> <td width="10">:</td> <td> <?php if($list['price'] == 0): ?> <link itemprop="availability" href="http://schema.org/PreOrder"/> <meta itemprop="priceCurrency" content="TRY" /> <span itemprop="price">0.00</span> <span class="text-danger fs-12">Teklif alınız.</span> <?php else: ?> <?php if($list['currency'] == '0'): ?> <meta itemprop="priceCurrency" content="TRY" /> <?php elseif($list['currency'] == '1'): ?> <meta itemprop="priceCurrency" content="USD" /> <?php elseif($list['currency'] == '1'): ?> <meta itemprop="priceCurrency" content="EUR" /> <?php endif; ?> <span itemprop="price"><?php echo number_format($list['price'],2); ?> <?php echo currency_to_text($list['currency']); ?></span> <link itemprop="availability" href="http://schema.org/InStock"/> <?php endif; ?> </td> </tr> <tr> <th>Firma</th> <td>:</td> <td><span itemprop="seller"><?php echo $corporate['company_name']; ?></span></td> </tr> <tr> <th>Yetkili Adı</th> <td>:</td> <td><?php echo $corporate['name']; ?></td> </tr> <tr> <th>Gsm</th> <td>:</td> <td><?php echo $corporate['gsm']; ?></td> </tr> <tr> <th>E-posta</th> <td>:</td> <td><?php echo $corporate['email']; ?></td> </tr> <tfoot> <tr> </tr> <th></th> <th></th> <th></th> </tfoot> </table> <?php if($list['price'] == 0): ?> <?php else: ?> <div class="row"> <div class="col-md-6"> <a href="#" class="btn btn-success btn-lg" data-toggle="modal" data-target="#order_now">Hemen Al</a> </div><!--/ .col-md-6 /--> </div><!--/ .row /--> <?php endif; // if($list['price'] == 0): ?> </div> <!-- /.col-md-5 --> <?php if(is_login()): $current_id = $_SESSION['login_id']; $current_user = get_user($current_id); if($current_user['user_type'] == 'user'):?> <?php if(isset($_POST['order_now'])) { $amount = form_input_control($_POST['amount']); $order['status'] = 1; $order['date'] = Date('Y-m-d H:i:s'); $order['date_update'] = Date('Y-m-d H:i:s'); $order['microtime'] = $_POST['microtime']; $order['company_id'] = $current_user['id']; $order['company_name'] = $current_user['company_name']; $order['name'] = $current_user['name']; $order['surname'] = $current_user['surname']; $order['phone'] = $current_user['gsm']; $order['address'] = $current_user['address']; $order['district'] = $current_user['district']; $order['city'] = $current_user['city']; $order['country'] = $current_user['country']; $order['product_brand'] = brand($list['brand_id']); $order['product_code'] = $list['code']; $order['product_id'] = $list['id']; $order['code_type'] = $list['code_type']; $order['amount'] = $amount; $order['sale_price'] = $list['price']; $order['currency'] = $list['currency']; if(add_orders($order)) { $code = brand($list['brand_id']).' '.$list['code'].' '.$list['code_type']; echo '<div class="col-md-7">'; get_alert('Siperişinizin Tüm Detaylarını Yönetim Panelinden Görebilirsiniz.', ' '. $amount. ' Adet '. $code .'', 'success'); echo '</div>'; } else { echo '<div class="col-md-7">'; get_alert("Veritabanı Hatası"); echo '</div>'; } } ?> <div id="order_now" class="modal fade" tabindex="-1" role="dialog"> <form action="" method="post" class="validate"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="text-danger modal-title"><?php echo brand($list['brand_id']); ?></span> <?php echo $list['code']; ?> <?php echo $list['code_type']; ?></h3> </div><!--/ .modal-header /--> <div class="modal-body"> <div class="row"> <div class="col-md-6"> <table class="table table-bordered table-condensed fs-13"> <tr> <th>Firma</th> <td>:</td> <td><span itemprop="seller"><?php echo $corporate['company_name']; ?></span></td> </tr> <tr> <th>Yetkili Adı</th> <td>:</td> <td><?php echo $corporate['name']; ?> <?php echo $corporate['surname']; ?></td> </tr> <tr> <th>Gsm</th> <td>:</td> <td><?php echo $corporate['gsm']; ?></td> </tr> <tr> <th>E-posta</th> <td>:</td> <td><?php echo $corporate['email']; ?></td> </tr> </table> </div><!--/ .col-md-6 /--> <div class="col-md-6"> <h4> <?php if($list['currency'] == '0'): ?> <meta itemprop="priceCurrency" content="TRY" /> <?php elseif($list['currency'] == '1'): ?> <meta itemprop="priceCurrency" content="USD" /> <?php elseif($list['currency'] == '1'): ?> <meta itemprop="priceCurrency" content="EUR" /> <?php endif; ?> <span itemprop="price"><?php echo number_format($list['price'],2); ?> <?php echo currency_to_text($list['currency']); ?></span> <link itemprop="availability" href="http://schema.org/InStock"/> </h4> <div class="form-group mt30"> <label for="amount">Adet Giriniz</label> <input type="number" name="amount" id="amount" placeholder="Adet" class="form-control required"> </div><!--/ .form-group /--> </div><!--/ .col-md-6 /--> </div><!--/ .row /--> </div><!--/ .modal-body /--> <div class="modal-footer"> <?php html_microtime(); ?> <input type="submit" name="order_now" value="Şiparişi Onayla" class="btn btn-success"> </div><!--/ .modal-footer /--> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </form> </div><!-- /.modal --> <div class="col-md-7"> <?php if(isset($_POST['microtime']) and isset($_POST['send_message'])) { $message['name_surname'] = mb_ucwords(form_input_control($_POST['name_surname'])); $message['phone'] = form_input_control($_POST['phone']); $message['email'] = strtolower(form_input_control($_POST['email'])); $message['description'] = form_input_control($_POST['description']); if($message['description'] == '') { get_alert('Mesaj Bölümü en az 10 karakter olmalıdır!'); }else { if(is_login()){ $message['out_user_id'] = active_user('id'); } else { $message['out_user_id'] = ''; } if(add_message($message['out_user_id'], $list['user_id'], $message['description'], '', $message)) { get_alert('Mesajınız ilgili firmaya başarı ile ulaşmıştır.', '', 'success', false); } else { get_alert('Tüm Bölümleri Dorğru girdiğinizden emin olduktan sonra tekrar deneyiniz.', '', 'danger', false); } } } ?> <?php if($list['price'] == 0){ $message = 'Merhaba, '.brand($list['brand_id']).' '.$list['code'].' '.$list['code_type'].' ürününüz ile ilgili fiyat teklifi alabilir miyim?'; } else { $message = ''; } ?> <div class="bg-warning p10 radius3"> <form name="form_message" id="form_message" action="" method="POST" class="validate_2"> <legend><i class="fa fa-envelope-o"></i> Satıcı firmaya mesaj gönderin</legend> <div class="form-group"> <input type="text" name="name_surname" id="name_surname" class="form-control input-sm required" minlength="3" maxlength="30" placeholder="<NAME>" value="<?php echo $current_user['name']; ?> <?php echo $current_user['surname']; ?>"> </div> <!-- /.form-group --> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" name="phone" id="phone" class="form-control input-sm required validatePhone digitsOnly" minlength="10" maxlength="11" placeholder="Cep Telefonu" value="<?php echo $current_user['gsm']; ?>"> </div> <!-- /.form-group --> </div> <!-- /.col-md-6 --> <div class="col-md-6"> <div class="form-group"> <input type="text" name="email" id="email" class="form-control input-sm required email" maxlength="100" placeholder="E-posta" value="<?php echo $current_user['email']; ?>"> </div> <!-- /.form-group --> </div> <!-- /.col-md-6 --> </div> <!-- /.row --> <div class="form-group"> <textarea name="description" id="description" required class="form-control input-sm required" style="height:100px;" minlength="10" maxlength="255" placeholder="Bir mesaj yazın"><?php echo $message; ?></textarea> </div> <!-- /.form-group --> <div class="text-right"> <?php html_microtime(); ?> <input type="hidden" name="send_message"> <button class="btn btn-default btn-sm">Mesaj Gönder</button> </div> <!-- /.text-right --> </form> </div> <!-- /.bg-muted --> </div> <!-- /.col-md-7 --> <?php endif; // if($current_user['user_type'] == 'user'): ?> <?php else: // if(is_login()): ?> <div class="col-md-7"> <div class="bg-warning p10 radius3"> Satıcı Firmaya Mesaj Döndermek İçin <strong><a href="<?php echo $theme_url; ?>/register.php">Üye</a> </strong>Olmanız Gerekmekte. </div> <!-- /.bg-warning --> </div><!--/ .col-md-7 /--> <?php endif; // if(is_login()): ?> </div> <!-- /.row --> </div> <!-- /.col-md-10 --> <div class="col-md-1"></div><!-- /.col-md-1 --> </div> <!-- /.row --> <file_sep><?php $mysqli = mysqli_connect('localhost', 'root', '', 'rulmansoft'); mysqli_set_charset($mysqli, "utf8"); // fonksiyonlarda mysqli_query kullanmak icin connect() adında bir fonksiyon olusturuyoruz. function mysqli() { global $mysqli; return $mysqli; } // default $site_url = 'http://localhost/RulmanSoft/admin'; $theme_url = 'http://localhost/RulmanSoft'; $account_url = 'http://localhost/RulmanSoft/accounts'; ?> <file_sep><?php include('_inc/header.php'); ?> <?php session_unset(); ?> <?php header("Location: ".account_url('')); ?> <?php include('_inc/footer.php'); ?> <file_sep><?php include '_inc/header.php'; //GET Header ?> <div class="row"> <div class="col-md-3"> <?php include '_inc/sidebar.php'; ?> </div><!--/ .col-md-3 /--> <div class="col-md-9"> <?php if(isset($_GET['status'])): ?> <?php $orders = get_orders($_GET['status'], $_SESSION['login_id']); ?> <?php ?> <?php if($orders->num_rows): ?> <h3 class="text-center"><?php if($_GET['status'] == 1){ echo 'Yeni Siparişlerim'; }elseif($_GET['status'] == 2){ echo 'Hazırlanan Siparişlerim'; }else{ echo 'Kapatılan Siparişlerim'; } ?></h3> <div class="h30"></div> <table class="table table-bordered"> <thead> <tr> <th>Ürün Adı</th> <th>Adet</th> <th>Onaylandı</th> <th class="hidden-xs">Yapılan Son işlem Tarihi</th> <th>Satış Fiyatı</th> </tr> </thead> <tbody> <?php while($list = $orders->fetch_object()): ?> <tr> <td><?php echo $list->product_brand.' '.$list->product_code.' '.$list->code_type; ?></td> <td><?php echo $list->amount; ?></td> <td><?php echo time_late($list->date_update); ?></td> <td class="hidden-xs"><?php echo substr($list->date_update, '0', '10'); ?> - <?php echo substr($list->date_update, '10', '6'); ?></td> <td> <?php if($list->currency == '0'): ?> <meta itemprop="priceCurrency" content="TRY" /> <?php elseif($list->currency == '1'): ?> <meta itemprop="priceCurrency" content="USD" /> <?php elseif($list->currency == '1'): ?> <meta itemprop="priceCurrency" content="EUR" /> <?php endif; ?> <span itemprop="price"><?php echo $list->sale_price; ?> <?php echo currency_to_text($list->currency); ?></span> <link itemprop="availability" href="http://schema.org/InStock"/> </td> </tr> <?php endwhile; ?> </tbody> </table> </div><!--/ .row /--> <?php else: ?> <div class="alert-danger padding5"> <h4 class="text-center">Gösterilecek veri bulunamadı.</h4> </div><!--/ .alert-danger /--> <div class="h60"></div> <?php endif; ?> <?php endif; ?> </div><!--/ .col-md-9 /--> </div><!--/ .row /--> <?php include '_inc/footer.php'; //GET Footer ?> <file_sep><?php include '_inc/header.php'; //Get Header ?> <div class="paragraf p30"> <div class="title"> <h2 class="CG inline">İletişim</h2> <span class="ml30 m-none">İletişim ve Adres Bilgileri Aşağıda Yer Almakta</span> </div> </div><!--/ .paragraf /--> <div class="row no-space pr10"> <div class="col-md-8"> <img src="image/map.png" class="p20 img-responsive" alt="" /> </div><!--/ .col-md-8 /--> <div class="col-md-4 CLG"> <div class="title mt20"> <h4><b>Hakkımızda</b></h4> <hr class="mtb10"> <p class="f12"><?php get_options('information', 'val_1', true); ?></p> </div> <div class="title mt20"> <h4><b>İletişim Bilgileri</b></h4> <hr class="mtb10"> <p class="f12"> <span><?php get_options('building_info', 'val_1', true); ?></span><br> <span><?php get_options('address', 'val_1', true); ?></span><br> <span><?php get_options('city', 'val_1', true); ?> <?php get_options('country', 'val_1', true); ?></span><br> <span>Call : <?php get_options('phone', 'val_1', true); ?> </span><br> <span>Email : <?php get_options('email', 'val_1', true); ?></span><br> </p> </div> <div class="title mt20"> <h4><b>Sosyal medya</b></h4> <hr class="mtb10"> <p class="f12">Facebook: <a href="<?php get_options('facebook', 'val_1', true); ?>"><?php get_options('facebook', 'val_1', true); ?></p> <p class="f12">Twitter: <a href="<?php get_options('facebook', 'val_1', true); ?>"><?php get_options('twitter', 'val_1', true); ?></a></p> </div> </div><!--/ .col-md-4 /--> </div><!--/ .row /--> <div class="row"> <div class="col-md-8"> <?php $corporate_id = get_options('corporate_id', 'val_1', false); $user = get_user($corporate_id); if(isset($_POST['contact_message']) and isset($_POST['microtime'])) { $message['name_surname'] = form_input_control($_POST['name_surname']); $message['email'] = form_input_control($_POST['email']); $message['phone'] = form_input_control($_POST['phone']); $message['description'] = form_input_control($_POST['description']); $message['microtime'] = $_POST['microtime']; $message['in_user_id'] = $user['id']; $message['date'] = date('Y-m-d H:i:s'); if(add_fast_message($message)) { echo get_alert('Mesajınız ilgili Firmaya başarılı bir şekilde gönderildi.','Mesajınız Gönderildi.', 'success'); } else { echo get_alert('Tüm alanları eksiksiz doldurunuz.', 'Mesaj Gönderilemedi', 'danger'); } } ?> <form class="form-contact mtb40 validate_2" action="" method="post"> <div class="col-md-7"> <span>Ad - Soyad*</span><br> <input type="text" name="name_surname" value="" class="required"> </div> <div class="col-md-7"> <span>E-Posta*</span><br> <input type="email" name="email" value="" class="required"> </div> <div class="col-md-7"> <span>Telefon*</span><br> <input type="text" name="phone" value="" minlength="10" class="required"> </div> <div class="col-md-12"> <span>Mesaj*</span><br> <textarea name="description" rows="8" cols="40" minlength="10" class="required"></textarea> </div> <div class="col-md-12"> <?php html_microtime(); ?> <input type="hidden" name="contact_message"> <input type="submit" class="mtb20 btn btn-nb" value="Gönder"> </div> </form> </div><!--/ .col-md-8 /--> <div class="col-md-6"> <?php get_options("google_map", 'val_1', true); ?> </div> </div> <div class="col-md-4"></div> <?php include '_inc/footer.php'; //Get Footer ?> <file_sep><?php include '_inc/header.php'; //Get Header ?> <?php if(isset($_GET['id'])): $page = get_page($_GET['id']); if($page): if($page->status == 1):?> <div class="paragraf p30"> <div class="title"> <h3 class="CG"><?php echo $page->title; ?></h3> </div> </div><!--/ .paragraf /--> <div class="content mtb20 p20"> <?php echo $page->content; ?> </div><!--/ .content /--> </div><!--/ .row /--> <?php else: ?> <?php get_alert('Aradığınız Sayfa Daha Önce Silinmiş!', '', 'danger mtb40', 'false'); ?> <?php endif; ?> <?php else: ?> <?php include '_inc/404.php' ?> <?php endif; ?> <?php endif; ?> <?php include '_inc/footer.php'; //Get Footer ?> <file_sep><?php include '_inc/header.php'; // Get Header ?> <div class="row"> <div class="col-md-3"> <?php include '_inc/sidebar.php'; ?> </div> <div class="col-md-9"> <?php if(isset($_GET['order_id'])): $order = orders_detail($_GET['order_id']); ?> <ol class="breadcrumb"> <li><a href="<?php echo site_url(''); ?>">Anasayfa</a></li> <li><a href="<?php echo site_url('index.php'); ?>">Yönetim Paneli</a></li> <li class="active">Sipariş Detayı</li> </ol> <div class="row"> <div class="col-md-7"> <h4>Müşteri Hakkında</h4> <table class="table table-bordered table-hover table-condensed"> <tr> <th class="col-md-4">Firma Adı: </th> <td><?php echo $order->company_name; ?></td> </tr> <tr> <th>Adı - Soyadı</th> <td><?php echo $order->name; ?> - <?php echo $order->surname; ?></td> </tr> <tr> <th>Yekili Telefon</th> <td><?php echo $order->phone; ?></td> </tr> <tr> <th>Son Sipariş</th> <td><?php echo time_late($order->date); ?></td> </tr> <tr> <th>İl - İlçe</th> <td><?php echo $order->city; ?> <?php echo $order->district; ?></td> </tr> <tr> <th>Adress</th> <td><?php echo $order->address; ?></td> </tr> </table> <div class="h30"></div> </div><!--/ .col-md-7 /--> <?php if(isset($_GET['case'])) { $case = $_GET['case']; if($case == 'confirm') { if(orders_case($order->id, 2)) { header("Location:".site_url('orders.php?status=2&case=success')); } } elseif($case == 'delete') { if(orders_case($order->id, 0)) { header("Location:".site_url('orders.php?status=0'.'&case=delete')); } } elseif($case == 'close') { if(orders_case($order->id, 3)) { header("Location:".site_url('orders.php?status=3&case=success')); } } } ?> <div class="col-md-5"> <div class="h40"></div> <?php if($_GET['type'] == 1): ?> <div class="btn-group pull-right"> <a href="<?php echo site_url('orders_detail.php?order_id=').$order->id.'&case=confirm';?>" class="btn btn-success"><i class="fa fa-check"></i> Siparişi Onayla</a> <a href="<?php echo site_url('orders_detail.php?order_id=').$order->id.'&case=delete';?>" class="btn btn-danger"><i class="fa fa-trash"></i> Siparişi Sil</a> </div><!--/ .btn-group /--> <?php elseif($_GET['type'] == 2): ?> <div class="btn-group pull-right"> <a href="<?php echo site_url('orders_detail.php?order_id=').$order->id.'&case=close';?>" class="btn btn-warning"><i class="fa fa-check"></i> Siparişi Kapat</a> <a href="<?php echo site_url('orders_detail.php?order_id=').$order->id.'&case=delete';?>" class="btn btn-danger"><i class="fa fa-trash"></i> Siparişi Sil</a> </div><!--/ .btn-group /--> <?php endif; ?> <div class="h60"></div> <div class="pull-right"> <a href="<?php echo site_url('print_orders.php?print_address=').$order->id; ?>" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-print"></i> Adres Etkiketi Yazdır</a> <div class="h10"></div> <a href="<?php echo site_url('print_orders.php?print_orders=').$order->id; ?>" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-print"></i> Sipariş Formu Yazdır</a> </div><!--/ .pull-right /--> </div><!--/ .col-md-5 /--> </div><!--/ .row /--> <h4>Sipariş Hakkında</h4> <table class="table table-bordered table-hover table-condensed"> <thead> <tr> <th>Ürün Markası: </th> <th>Ürün Kodu: </th> <th>Sipariş Adedi: </th> <th>Son İşlem Tarihi</th> <th>Satış Fiyatı</th> </tr> </thead> <tbody> <tr> <td><?php echo $order->product_brand; ?></td> <td><?php echo $order->product_code; ?> <?php echo $order->code_type; ?></td> <td><?php echo $order->amount; ?></td> <td><?php echo substr($order->date_update, '0', '10'); ?> - <?php echo substr($order->date_update, '10', '6'); ?></td> <td> <?php if($order->currency == '0'): ?> <meta itemprop="priceCurrency" content="TRY" /> <?php elseif($order->currency == '1'): ?> <meta itemprop="priceCurrency" content="USD" /> <?php elseif($order->currency == '1'): ?> <meta itemprop="priceCurrency" content="EUR" /> <?php endif; ?> <span itemprop="price"><?php echo $order->sale_price; ?> <?php echo currency_to_text($order->currency); ?></span> <link itemprop="availability" href="http://schema.org/InStock"/> </td> </tr> </tbody> </table> <?php endif; ?> </div><!--/ .col-md-9 /--> </div><!--/ .row /--> <?php include '_inc/footer.php' ?> <file_sep><?php include('_inc/header.php'); ?> <?php page_access('user'); ?> <?php if(!is_login()) { header("Location: ".account_url('login.php')); exit; } ?> <div class="row"> <div class="col-md-3"> <?php include('_inc/sidebar.php'); ?> </div> <!-- /.col-md-3 --> <div class="col-md-9"> <ol class="breadcrumb"> <li><a href="<?php echo account_url(''); ?>">Anasayfa</a></li> <li class="active">Yönetim Paneli</li> </ol> <style> .dashboard_box { display: block; background-color: #f5f5f5; padding: 10px; text-align:center; color:#000; border:1px solid #ccc; height: 100px; position: relative; } .dashboard_box i { display: block; font-size: 36px; margin-bottom: 5px; } .dashboard_box i.fa2 { font-size:18px; position: absolute; right: 10px; top: 5px; color:#1b926c; } .dashboard_box span { color:#7D7D7D; } </style> <h4>Sipariş Takibi & Mesajlaşma</h4> <div class="row"> <div class="col-md-2"> <a href="<?php echo account_url('message_inbox.php'); ?>" class="dashboard_box z-depth-1"> <i class="fa fa-envelope-o"></i> <span>Mesaj Kutusu</span> </a> </div> <!-- /.col-md-2 --> <div class="col-md-2"> <a href="<?php echo account_url('orders.php?status=1'); ?>" class="dashboard_box z-depth-1"> <i class="fa fa-shopping-basket"></i> <i class="fa fa-clock-o fa2"></i> <span>Yeni Sipariş</span> </a> </div> <!-- /.col-md-2 --> <div class="col-md-2"> <a href="<?php echo account_url('orders.php?status=2'); ?>" class="dashboard_box z-depth-1"> <i class="fa fa-shopping-basket"></i> <i class="fa fa-cubes fa2"></i> <span>Hazırlanan Sipariş</span> </a> </div> <!-- /.col-md-2 --> <div class="col-md-2"> <a href="<?php echo account_url('orders.php?status=3'); ?>" class="dashboard_box z-depth-1"> <i class="fa fa-shopping-basket"></i> <i class="fa fa-check fa2"></i> <span>Kapatılan Sipariş</span> </a> </div> <!-- /.col-md-2 --> </div> <!-- /.row --> </div> <!-- /.row --> </div> <!-- /.col-md-9 --> </div> <!-- /.row --> <?php include('_inc/footer.php'); ?> <file_sep><?php include '_inc/header.php'; //Get Header ?> <?php $results = get_list_news(6); if($results): ?> <div class="h20"></div> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Wrapper for slides --> <div class="carousel-inner" style="height: 400px;" role="listbox"> <?php while($news_img = $results->fetch_object()): if($news_img->status == 1): ?> <a href="<?php echo theme_url('news.php?id=').$news_img->id; ?>" class="item"> <img src="<?php echo site_url('upload/news/').$news_img->list_img; ?>" alt="..." class="img-responsive"> <div class="carousel-caption"> <?php echo $news_img->title; ?> </div> </a> <?php endif; endwhile; ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <?php endif; ?> <div class="main-content"> <div class="title"><h3 class="CNB"><NAME></h3><hr></div><!--/ .title /--> <?php $news = get_list_news(3); if($results): ?> <div class="row"> <?php while($news_text = $news->fetch_object()): if($news_text->status == 1): ?> <div class="col-md-4"> <div class="content-info"> <div class="content-info-header"><a href="<?php echo theme_url('news.php?id=').$news_text->id; ?>"><?php echo $news_text->title; ?></a></div> <div class="content-info-body"> <p><?php echo substr($news_text->content, 0, 150); ?> ..</p> </div><!--/ .content-info-body /--> </div><!--/ .content-info /--> </div><!--/ .col-md-4 /--> <?php endif; endwhile; ?> </div><!--/ .row /--> <?php endif; ?> <blockquote class="gray-blockquote mt20"> <div class="row"> <div class="col-md-10"> <div class="title"> <h1>Biz Kimiz?</h1> </div> <p class="f15"> <?php strip_tags(substr(get_options('information', 'val_1', true), 0, 20)); ?> </p> </div><!--/ .col-md-10 /--> <div class="col-md-2"> <div class="ptb20"> <a href="<?php echo theme_url('about.php'); ?>" class="pull-right btn btn-nb">Devamını oku!</a> </div> </div><!--/ .col-md-2 /--> </div><!--/ .row /--> </blockquote> <?php /* <div class="row"> <div class="col-md-6"> <h3 class="CNB">Rulman</h3> <hr> <img src="http://www.demirsektoru.com/uploads/logo/ringspann-bilya-hirdavat-rulman-tic-ltd-sti.jpg" class="img-responsive" alt="" /> </div><!--/ .col-md-6 /--> <div class="col-md-6"> <h3 class="CNB">Rulmanlar hakkında Bilgi</h3> <hr> <ul class="text-list"> <li><div><i class="fa fa-plus"></i><span>Venenatis Justo Ullamcorper Ridiculus</span></div> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Sed posuere consectetur est at lobortis.</p> </li> <li><div><i class="fa fa-plus"></i><span>Venenatis Justo Ullamcorper Ridiculus</span></div> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Sed posuere consectetur est at lobortis.</p> </li> <li><div><i class="fa fa-plus"></i><span>Venenatis Justo Ullamcorper Ridiculus</span></div> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Sed posuere consectetur est at lobortis.</p> </li> <li><div><i class="fa fa-plus"></i><span>Venenatis Justo Ullamcorper Ridiculus</span></div> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Sed posuere consectetur est at lobortis.</p> </li> </ul> </div><!--/ .col-md-6 /--> </div><!--/ .row /--> */ ?> <div class="row"> <div class="h60"></div> <div class="col-md-4"> <div class="title"><h2 class="CNB">Hakkımızda</h2></div> <div class="paragraf mt10"> <p><?php get_options('information', 'val_1', true); ?></p> </div> </div> <div class="col-md-4"> <div class="title"><h2 class="CNB">Bizden haberler</h2></div> <img id="last_news_img" src="" class="ptb10 img-responsive" style="height: 140px;" alt="" /> <div class="paragraf Bnone p0"> <p id="last_news_content"></p> </div> </div> <div class="col-md-4"> <div class="title"><h2 class="CNB">İletişim</h2></div> <div class="p10"> <p><i class="fa fa-phone"></i> <?php get_options('phone', 'val_1', true); ?></p> <p><i class="fa fa-envelope"></i> <?php get_options('email', 'val_1', true); ?></p> <p class="f12"><?php get_options('address', 'val_1', true); ?></p> <a href="<?php echo theme_url('contact.php'); ?>" class="btn btn-nb">İletişim Formu</a> </div> </div> <div class="h60"></div> </div><!--/ /--> </div> <?php include '_inc/footer.php'; //Get Footer ?> <file_sep><?php include('_inc/header.php'); ?> <?php include('admin/search.php'); ?> <?php include('_inc/footer.php'); ?> <file_sep><div class="sidebar hidden-xs"> <?php if(is_login()): ?> <div class="h20"></div> <h3 class="module-title"><i class="fa fa-shopping-basket"></i> Sipariş İstatistik</h3> <p><b>Bugün: </b><span class="text-primary"><?php echo orders_reporting(array( 'start_date'=>date('Y-m-d', strtotime('0 day',strtotime(date('Y-m-d')))).' 00:00:00', 'end_date'=>date('Y-m-d', strtotime('0 day',strtotime(date('Y-m-d')))).' 99:99:99' ), active_user('id')); ?> Sipariş</span></p> <p><b>Dün: </b><span class="text-primary"><?php echo orders_reporting(array( 'start_date'=>date('Y-m-d', strtotime('-1 day',strtotime(date('Y-m-d')))).' 00:00:00', 'end_date'=>date('Y-m-d', strtotime('-1 day',strtotime(date('Y-m-d')))).' 99:99:99' ), active_user('id')); ?> Sipariş</span></p> <p><b>Bu Hafta: </b><span class="text-primary"><?php echo orders_reporting(array( 'start_date'=>date('Y-m-d', strtotime('-7 day',strtotime(date('Y-m-d')))).' 00:00:00', 'end_date'=>date('Y-m-d', strtotime('0 day',strtotime(date('Y-m-d')))).' 99:99:99' ), active_user('id')); ?> Sipariş</span></p> <p><b>Bu Ay (<?php echo date_translate(date('F')); ?>): </b><span class="text-primary"><?php echo orders_reporting(array( 'start_date'=>date('Y-m-d', strtotime('-30 day',strtotime(date('Y-m-d')))).' 00:00:00', 'end_date'=>date('Y-m-d', strtotime('0 day',strtotime(date('Y-m-d')))).' 99:99:99' ), active_user('id')); ?> Sipariş</span></p> <?php endif; ?> <script>$(".sidebar").height($('.container.container-content').height());</script> </div> <!-- /.sidebar --> <file_sep><?php include('../_inc/header.php'); ?> <script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script> <div class="row"> <div class="col-md-3"> <?php include('../_inc/sidebar.php'); ?> </div><!--/ .col-md-3 /--> <div class="col-md-9"> <ol class="breadcrumb"> <li><a href="<?php echo site_url(''); ?>">Anasayfa</a></li> <li><a href="<?php echo site_url('index.php'); ?>">Yönetim Paneli</a></li> <li class="active">Yeni Sayfa</li> </ol> <?php if(isset($_GET['id'])): $id = $_GET['id']; $page = get_page($id); ?> <?php if($_POST){ $title = $_POST['title']; $content = $_POST['content']; $m_short = $_POST['m_short']; $m_title = $_POST['m_title']; if(!$title || !$content){ echo get_alert('Tüm Alanları eksiksiz şekilde Doldurunuz'); } elseif(strlen($content) < 10) { echo get_alert('İçerik alanı en az 10 karakter olmalı.'); } else{ if(edit_pages($id, $title, $content, $m_short, $m_title, $theme_url."/pages.php?id=".$id)) { $page = get_page($id); echo get_alert("Sayfa Başarılı Bir Şekilde Güncellendi", "Sayfa Güncellendi", "success"); header("Refresh:2;".site_url("pages/page_list.php")); } } } ?> <form class="" action="" method="post"> <div class="form-group"> <input type="text" name="title" class="form-control" value="<?php echo $page->title; ?>" placeholder="Sayfa Başlığını Giriniz"> </div><!--/ .form-group /--> <div class="form-group"> <textarea name="content" style="outline: none;" class="form-control" rows="8" cols="40"><?php echo $page->content; ?></textarea> </div><!--/ .form-group /--> <div class="row"> <div class="col-md-2"></div> <div class="col-md-4"> <div style="height:5px;"></div> <label class="text-muted" style="cursor:pointer;"> <input type="checkbox" name="is_menu" id="is_menu" value="1" <?php if($page->m_short > 0){echo'checked';}else{} ?>> <small>Site menüsünde gösterilsin mi?</small></label> </div> <!-- /.col-md-4 --> <div class="col-md-4"> <div class="form-group m_items"><input type="text" name="m_title" id="m_title" class="form-control input-sm" value="<?php echo $page->m_title; ?>" placeholder="Menü Adı"/></div> </div> <!-- /.col-md-4 --> <div class="col-md-2"> <div class="form-group m_items"><input type="text" name="m_short" id="m_short" class="form-control input-sm" value="<?php if($page->m_short == '0'){echo'';}else{echo $page->m_short;} ?>" placeholder="Sıralama (0,1,2,7,8...)" /></div> </div> <!-- /.col-md-4 --> </div> <!-- /.form-group --> <script> $(document).ready(function() { $('#is_menu').change(function() { if($(this).is(':checked')) { $('.m_items').show('slide'); } else { $('.m_items').hide('slide'); } }); <?php if($page->m_short == 0){echo " $('.m_items').hide();";}else{} ?> }); </script> <div class="form-group text-right"> <input type="submit" name="submit" class="btn btn-success" value="Kaydet"> </div><!--/ .row /--> </form> <?php else: ?> <?php get_alert("Aradığınız Sayfa Bulunamadı!"); ?> <?php endif; ?> </div><!--/ .col-md-9 /--> </div><!--/ .row /--> <?php include('../_inc/footer.php'); ?> <file_sep><?php include('_inc/header.php'); ?> <?php include('admin/list_detail.php'); ?> <?php include('_inc/footer.php'); ?> <file_sep><?php include '_inc/header.php'; // GET header ?> <div class="row"> <div class="col-md-3"> <?php include '_inc/sidebar.php'; ?> </div><!--/ .col-md-3 /--> <div class="col-md-9"> <div class="h20"></div> <?php if(isset($_GET['status'], $_GET['id'])) { $status = $_GET['status']; $id = $_GET['id']; if(status_user($id, $status)) { if($status == 1) { get_alert('', 'Kullanıcı Onaylandı !', 'success text-center'); }else { get_alert('', 'Kullanıcı Engllendi !', 'danger text-center'); } } } ?> <div class="h30"></div> <table class="table table-bordered table-hover table-condensed"> <thead> <th></th> <th>Firma Adı</th> <th>Adı - Soyadı</th> <th>E-Potası</th> <th>Telefon</th> <th>İl - İlçe</th> </thead> <tbody> <?php $user = get_list_user(); while($list = $user->fetch_object()): if($list->user_type == 'user'): ?> <tr style="<?php if($list->status == 0): echo 'background-color: #efefef;'; else: echo 'background-color: #fff;'; endif; ?>"> <td> <?php if($list->status == 0): ?> <a href="<?php echo site_url('users.php?status=1&id=').$list->id; ?>" data-toggle="tooltip" data-placement="top" title="Onayla" class="btn btn-success btn-xs"><i class="fa fa-check"></i></a> <?php elseif($list->status == 1): ?> <a href="<?php echo site_url('users.php?status=0&id=').$list->id; ?>" data-toggle="tooltip" data-placement="top" title="Engelle" class="btn btn-danger btn-xs"><i class="fa fa-times"></i></a> <?php endif; ?> </td> <td><?php echo $list->company_name; ?></td> <td><?php echo $list->name; ?> <?php echo $list->surname; ?></td> <td><?php echo $list->email; ?></td> <td><?php echo $list->gsm; ?></td> <td><?php echo $list->city; ?> <?php echo $list->district; ?></td> </tr> <?php endif; ?> <?php endwhile; ?> </tbody> </table> </div><!--/ .col-md-7 /--> </div><!--/ .row /--> <?php include '_inc/footer.php'; // GET footer ?> <file_sep><?php include '_inc/header.php'; // GET Header ?> <?php include 'admin/register.php';?> <?php include '_inc/footer.php'; // GET Footer ?> <file_sep><?php include '_inc/header.php'; //GET Header ?> <?php if(isset($_GET['status'])): ?> <ol class="breadcrumb"> <li><a href="<?php echo site_url(''); ?>">Anasayfa</a></li> <li><a href="<?php echo site_url('index.php'); ?>">Yönetim Paneli</a></li> <li class="active">Yeni Siparişler</li> </ol> <?php $orders = get_orders($_GET['status'], $_SESSION['login_id']); ?> <?php if(isset($_GET['case'])) { if($_GET['case'] == 'success') { echo get_alert('', 'İşlem Tamamlandı', 'success text-center'); } elseif($_GET['case'] == 'delete') { echo get_alert('', 'Sipariş Silindi!', 'danger text-center'); } } ?> <?php if($orders->num_rows): ?> <h3 class="text-center"><?php if($_GET['status'] == 1){ echo 'Yeni Siparişler'; }elseif($_GET['status'] == 2){ echo 'Hazırlanan Siparişler'; }elseif($_GET['status'] == 3){ echo 'Kapatılan Siparişler'; }else{ echo 'Silinen Siparişler'; } ?></h3> <div class="h30"></div> <table class="table table-bordered table-hover table-condensed"> <thead> <tr> <?php if($_GET['status'] == 0): else: ?> <th>Onayla</th> <?php endif; ?> <th class="hidden-xs">Firma Adı</th> <th>Ad - Soyad</th> <th class="hidden-xs">Telefon</th> <th class="hidden-xs">İl - İlçe</th> <th>Ürün Adı</th> <th>Adet</th> <th class="hidden-xs">Son İşlem Tarihi</th> <th class="hidden-xs">Satış Fiyatı</th> </tr> </thead> <tbody> <?php while($list = $orders->fetch_object()): ?> <tr> <?php if($_GET['status'] == 1): ?> <td><a href="<?php echo site_url('orders_detail.php/?order_id=').$list->id.'&type=1'; ?>" class="btn btn-default btn-xs">Detaylar</a> <a href="<?php echo site_url('orders_detail.php?order_id=').$list->id.'&type=1&case=confirm';?>" data-toggle="tooltip" data-placement="top" title="" class="btn btn-success edit_btn btn-xs hidden-xs" data-original-title="Onayla"><i class="fa fa-check"></i></a></td> <?php elseif($_GET['status'] == 2): ?> <td><a href="<?php echo site_url('orders_detail.php/?order_id=').$list->id.'&type=2'; ?>" class="btn btn-default btn-xs">Detaylar</a> <a href="<?php echo site_url('orders_detail.php?order_id=').$list->id.'&case=close';?>" data-toggle="tooltip" data-placement="top" title="Kapat" class="btn btn-xs btn-warning hidden-xs"><i class="fa fa-power-off"></i></a></td> <?php elseif($_GET['status'] == 3):?> <td><a href="<?php echo site_url('orders_detail.php?order_id=').$list->id.'&case=delete';?>" class="btn btn-warning btn-xs z-depth-1" style="width: 100%;"><i class="fa fa-trash"></i> Sil</a></td> <?php else: ?> <?php endif; ?> <td class="hidden-xs"><?php echo $list->company_name; ?></td> <td><?php echo $list->name; ?> <?php echo $list->surname; ?></td> <td class="hidden-xs"><?php echo $list->phone; ?></td> <td class="hidden-xs"><?php echo $list->district; ?> <?php echo $list->city; ?></td> <td><?php echo $list->product_brand.' '.$list->product_code.' '.$list->code_type; ?></td> <td><?php echo $list->amount; ?></td> <td class="hidden-xs"><?php echo substr($list->date_update, '0', '10'); ?> - <?php echo substr($list->date_update, '10', '6'); ?></td> <td class="hidden-xs"> <?php if($list->currency == '0'): ?> <meta itemprop="priceCurrency" content="TRY" /> <?php elseif($list->currency == '1'): ?> <meta itemprop="priceCurrency" content="USD" /> <?php elseif($list->currency == '1'): ?> <meta itemprop="priceCurrency" content="EUR" /> <?php endif; ?> <span itemprop="price"><?php echo $list->sale_price; ?> <?php echo currency_to_text($list->currency); ?></span> <link itemprop="availability" href="http://schema.org/InStock"/> </td> </tr> <?php endwhile; ?> </tbody> </table> </div><!--/ .row /--> <?php else: ?> <div class="alert-danger padding5"> <h4 class="text-center">Gösterilecek veri bulunamadı.</h4> </div><!--/ .alert-danger /--> <div class="h60"></div> <?php endif; ?> <?php endif; ?> <?php include '_inc/footer.php'; //GET Footer ?> <file_sep> </div><!--/ .main-cotnainer /--> <div class="container p0"> <footer class="m-none"> <div class="row"> <div class="col-md-4"> <div class="title"><h3><NAME></h3></div> <hr> <ul class="socail-comment"> <li><a href="<?php get_options('facebook', 'val_1', true); ?>"><i class="fa fa-facebook"></i> Facebook</a></li> <li><a href="<?php get_options('twitter', 'val_1', true); ?>"><i class="fa fa-twitter"></i> Twitter</a></li> <li><a href="<?php get_options('instagram', 'val_1', true); ?>"><i class="fa fa-instagram"></i> İnstagram</a></li> <li><a href="<?php get_options('google_plus', 'val_1', true); ?>"><i class="fa fa-google-plus"></i> Google</a></li> </ul> </div><!--/ .col-md-4 /--> <div class="col-md-4"> <div class="title"><h3><NAME></h3></div> <hr> <?php $result = get_list_news(3); while($news = $result->fetch_object()): if($news->status == 1): ?> <div class="row mt20"> <div class="col-md-3"><a href="<?php echo theme_url('news.php?id=').$news->id; ?>"><img src="<?php echo site_url('upload/news/').$news->list_img; ?>" class="img-responsive" alt="" /></a></div> <div class="col-md-9"><a href="<?php echo theme_url('news.php?id=').$news->id; ?>" class="f16"><?php echo $news->title; ?></a><p class="f12 mt10"><?php echo substr($news->content, 0, 40); ?></p></div> </div><!--/ .row /--> <?php endif; endwhile; ?> </div><!--/ .col-md-4 /--> <div class="col-md-4"> <div class="title"><h3>İletişim</h3></div> <hr> <?php $corporate_id = get_options('corporate_id', 'val_1', false); $user = get_user($corporate_id); if(isset($_POST['footer_message']) and isset($_POST['microtime'])) { $message['name_surname'] = form_input_control($_POST['name_surname']); $message['email'] = form_input_control($_POST['email']); $message['phone'] = form_input_control($_POST['phone']); $message['description'] = form_input_control($_POST['description']); $message['microtime'] = $_POST['microtime']; $message['in_user_id'] = $user['id']; $message['date'] = date('Y-m-d H:i:s'); if(add_fast_message($message)) { echo get_alert('Mesajınız ilgili Firmaya başarılı bir şekilde gönderildi.','Mesajınız Gönderildi.', 'success'); } else { echo get_alert('Tüm alanları eksiksiz doldurunuz.', 'Mesaj Gönderilemedi', 'danger'); } } ?> <form name="form_message" id="form_message" action="" method="POST" class="validate_4"> <div class="form-group"> <input type="text" name="name_surname" class="form-control required" id="name_surname" placeholder="Ad - Soyad"> </div><!--/ .form-group /--> <div class="form-group"> <input type="email" name="email" class="form-control required" id="email" placeholder="E-Posta"> </div><!--/ .form-group /--> <div class="form-group"> <input type="number" name="phone" class="form-control required" minlength="10" id="phone" placeholder="Telefon"> </div><!--/ .form-group /--> <div class="form-group"> <label for="exampleInputFile">Mesaj*</label> <textarea class="form-control required" minlength="10" name="description" rows="2" cols="40"></textarea> </div><!--/ .form-group /--> <?php html_microtime(); ?> <input type="hidden" name="footer_message"> <button type="submit" class="btn btn-gray">Submit</button> </form> </div><!--/ col-md-4 /--> </div><!--/ .row /--> <div class="CLG"> <hr> <span class="pull-left"><?php get_options('building_info', 'val_1', true); ?></span> <span class="pull-right">© Alt yapı <a href="http://rulmansoft.com">RulmanSoft</a> ekibi tarafından yazılmıştır.</span> </div><!--/ .text-center /--> </footer> </div><!--/ .containe /--> </body> </html> <?php analytics(); ?>
b826fc0c0ae26f39cbe5a0457d8b6aeba6fc01f6
[ "PHP" ]
23
PHP
IMinan/RulmanSoft
d3df11b30945e7569332eb25285fd87ab5f7125d
8ace276ca7cc7ef54e8fe06c81962c506f40a539
refs/heads/master
<repo_name>lza93/Asn_1_cmpt471<file_sep>/tunnel.c #include <netinet/in.h> #include <time.h> #include <strings.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <stdlib.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #define MAXLINE 4096 /* max text line length */ #define LISTENQ 1024 /* 2nd argument to listen() */ #define DAYTIME_PORT 3333 #define DEBUG 0 int isValidIpAddress(char*); int hostname_to_ip(int, char*,char*,char*,char*); int ip_to_hostname(int, char*,char*,char*,char*); int main(int argc, char **argv) { int listenfd, connfd, forwardfd = 0; struct sockaddr_in tunneladdr, clientaddr; socklen_t addr_size; //pid_t pid; char buff1[MAXLINE] ; char buff2[MAXLINE] ; char recvline[MAXLINE + 1]; char ip[MAXLINE]; char name[MAXLINE]; if(argc != 2) { printf("Usage:%s<portNumber>", argv[0]); return -1; } char *port_num = argv[1]; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&tunneladdr, sizeof(tunneladdr)); tunneladdr.sin_family = AF_INET; tunneladdr.sin_addr.s_addr = htonl(INADDR_ANY); tunneladdr.sin_port = htons(atoi(port_num)); /* daytime server */ bind(listenfd, (struct sockaddr *) &tunneladdr, sizeof(tunneladdr)); listen(listenfd, LISTENQ); for ( ; ; ) { addr_size = sizeof(clientaddr); connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &addr_size); printf("Reading server name\n"); if(read (connfd, buff1, strlen(buff1))==0) { printf("server name: %s\n", buff1); } printf("Reading port number\n"); read (connfd,buff2,strlen(buff2)); printf("server port: %s\n", buff2); /*if((pid=fork())<0) { printf("Fork Failed\n"); exit(1); } if(pid==0) /*Child* { printf("child id: %d\n", getpid());*/ /*host name input case*/ if(!isValidIpAddress(buff1)) { hostname_to_ip(forwardfd, buff1, buff2, ip, recvline); printf("Via Tunnel:%s\nIP Address:%s\nPort Number:%s\n",buff1,ip, buff2); if (fputs(recvline, stdout) == EOF) { printf("fputs error\n"); } write(connfd, recvline, strlen(recvline)+1); } else { ip_to_hostname(forwardfd, buff1, buff2, name, recvline); } close(forwardfd); close(connfd); } exit(0); } /****************************************************************************************** * check if the input is an ip address or not * *******************************************************************************************/ int isValidIpAddress(char *server_name) { struct sockaddr_in servaddr; int result = inet_pton(AF_INET,server_name,&(servaddr.sin_addr)); printf("%d\n", result); return result !=0; } /****************************************************************************************** * convert host name into ip address * *******************************************************************************************/ int hostname_to_ip(int connfd, char *server_name, char *port_num, char *ip, char *recvline) { int sockfd, n; struct sockaddr_in *servaddr; struct addrinfo hints, *res, *p; bzero(&servaddr, sizeof(servaddr)); //if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){ memset(&hints,0,sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //convert hostname into IP getaddrinfo(server_name,port_num, &hints, &res); //if (inet_pton(AF_INET,argv[1], &servaddr.sin_addr) <= 0) { for(p= res;p!=NULL;p=p->ai_next) { servaddr = (struct sockaddr_in *)p->ai_addr; strcpy(ip, inet_ntoa(servaddr->sin_addr)); } if( (sockfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol)) < 0) { printf("socket error\n"); exit(1); } connfd=connect(sockfd, res->ai_addr, res->ai_addrlen); if(connfd<0) { printf("connect error\n"); exit(1); } while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null terminate */ } if (n < 0) { printf("read error\n"); exit(1); } freeaddrinfo(res); return 0; } /******************************************************************************************************** *convert ip address into host name * ********************************************************************************************************/ int ip_to_hostname(int connfd, char *server_name, char *port_num, char *name, char *recvline) { int sockfd, n; struct hostent *he; struct sockaddr_in servaddr; socklen_t len; len = sizeof(servaddr); /*convert Ip address to hostname*/ inet_pton(AF_INET,server_name,&servaddr.sin_addr); he = gethostbyaddr(&servaddr.sin_addr, len, AF_INET); strcpy(name, he->h_name); #if DEBUG int r; r=getnameinfo((struct sockaddr *)&servaddr,len, name, sizeof name, port_num,sizeof port_num, 0); printf("%s\n",name); if (r) { printf("%s\n", gai_strerror(r)); exit(1); } #endif bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(port_num)); if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){ printf("socket error\n"); exit(1); } connfd=connect(sockfd, (struct sockaddr *)&servaddr,len); if(connfd<0) { printf("connect error\n"); exit(1); } while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null terminate */ } if (n < 0) { printf("read error\n"); exit(1); } return 0; }<file_sep>/server.c #include <netinet/in.h> #include <time.h> #include <strings.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <stdlib.h> #include <netdb.h> #include <arpa/inet.h> #define MAXLINE 4096 /* max text line length */ #define LISTENQ 1024 /* 2nd argument to listen() */ int main(int argc, char **argv) { int listenfd, connfd; struct sockaddr_in servaddr, clientaddr; socklen_t addr_size; char buff[MAXLINE]; time_t ticks; char *port_num; if(argc != 2) { printf("Usage:%s<portNumber>", argv[0]); return -1; } port_num = argv[1]; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(atoi(port_num)); /* daytime server */ bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); for ( ; ; ) { addr_size = sizeof(clientaddr); connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &addr_size); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); write(connfd, buff, strlen(buff)); printf("request address: %s\n", inet_ntoa(clientaddr.sin_addr)); printf("Sending response: %s", buff); close(connfd); } } <file_sep>/client.c #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include <strings.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <netdb.h> #define MAXLINE 4096 /* max text line length */ #define DEBUG 0 int isValidIpAddress(char*); void hostname_to_ip(int, char*,char*,char*,char*); void ip_to_hostname(int, char*,char*,char*,char*); int main(int argc, char **argv) { int connfd = 0; char recvline[MAXLINE + 1]; char ip[MAXLINE]; char name[MAXLINE]; if (argc != 3 && argc != 5) { printf("usage: %s <IPaddress and port>", argv[0]); exit(1); } /******************************************************************************************* *No tunnel using case ********************************************************************************************/ if (argc==3){ char *server_name = argv[1]; char *port_num = argv[2]; /* hostname input case*/ if(!isValidIpAddress(server_name)){ hostname_to_ip(connfd, server_name, port_num, ip, recvline); printf("hostname:%s\nIpaddress:%s\n",server_name, ip); if (fputs(recvline, stdout) == EOF) { printf("fputs error\n"); exit(1); } } /* ip input case*/ else { ip_to_hostname(connfd, server_name, port_num, name,recvline); printf("hostname:%s\nIpaddress:%s\n",name,server_name); if (fputs(recvline, stdout) == EOF) { printf("fputs error\n"); exit(1); } } } /*********************************************************************************************** * Tunnel Using Case * ************************************************************************************************/ else{ char *server_name = argv[3]; char *port_num = argv[4]; char *tunnel_name = argv[1]; char *tunnel_port = argv[2]; char stat[MAXLINE]; /*host name input case*/ if(!isValidIpAddress(tunnel_name)) { hostname_to_ip(connfd, tunnel_name, tunnel_port, ip, recvline); printf("writing server name: %s\n",server_name); write(connfd, server_name, strlen(server_name)+1); printf("writing server port: %s\n",port_num); write(connfd, port_num, strlen(port_num)+1); printf("Reading response from server\n"); read(connfd,stat,strlen(stat)+1); printf("time: %s\n", stat); printf("Via Tunnel:%s\nIP Address:%s\nPort Number:%s\n",tunnel_name,ip, tunnel_port); if (fputs(recvline, stdout) == EOF) { printf("fputs error\n"); } } /* ip input case*/ else { ip_to_hostname(connfd, tunnel_name, tunnel_port, name, recvline); printf("writing server name: %s\n",server_name); write(connfd, server_name, strlen(server_name)); printf("writing server port: %s\n",port_num); write(connfd, port_num, strlen(port_num)); printf("Reading response from server\n"); char stat[1]; read(connfd,stat,1); printf("Via Tunnel:%s\nIP Address:%s\nPort Number:%s\n",name,tunnel_name, tunnel_port); if (fputs(recvline, stdout) == EOF) { printf("fputs error\n"); exit(1); } } } close(connfd); exit(0); } /****************************************************************************************** * check if the input is an ip address or not * *******************************************************************************************/ int isValidIpAddress(char *server_name) { struct sockaddr_in servaddr; int result = inet_pton(AF_INET,server_name,&(servaddr.sin_addr)); return result !=0; } /****************************************************************************************** * convert host name into ip address * *******************************************************************************************/ void hostname_to_ip(int connfd, char *server_name, char *port_num, char *ip, char *recvline) { int sockfd, n; struct sockaddr_in *servaddr; struct addrinfo hints, *res, *p; bzero(&servaddr, sizeof(servaddr)); //if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){ memset(&hints,0,sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //convert hostname into IP getaddrinfo(server_name,port_num, &hints, &res); //if (inet_pton(AF_INET,argv[1], &servaddr.sin_addr) <= 0) { for(p= res;p!=NULL;p=p->ai_next) { servaddr = (struct sockaddr_in *)p->ai_addr; strcpy(ip, inet_ntoa(servaddr->sin_addr)); } if( (sockfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol)) < 0) { printf("socket error\n"); exit(1); } connfd=connect(sockfd, res->ai_addr, res->ai_addrlen); if(connfd<0) { printf("connect error\n"); exit(1); } while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null terminate */ } if (n < 0) { printf("read error\n"); exit(1); } freeaddrinfo(res); } /******************************************************************************************************** *convert ip address into host name * ********************************************************************************************************/ void ip_to_hostname(int connfd, char *server_name, char *port_num, char *name, char *recvline) { int sockfd, n; struct hostent *he; struct sockaddr_in servaddr; socklen_t len; len = sizeof(servaddr); /*convert Ip address to hostname*/ inet_pton(AF_INET,server_name,&servaddr.sin_addr); he = gethostbyaddr(&servaddr.sin_addr, len, AF_INET); strcpy(name, he->h_name); #if DEBUG int r; r=getnameinfo((struct sockaddr *)&servaddr,len, name, sizeof name, port_num,sizeof port_num, 0); printf("%s\n",name); if (r) { printf("%s\n", gai_strerror(r)); exit(1); } #endif bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(port_num)); if ( (sockfd = socket(AF_INET,SOCK_STREAM,0))<0){ printf("socket error\n"); exit(1); } connfd=connect(sockfd, (struct sockaddr *)&servaddr,len); if(connfd<0) { printf("connect error\n"); exit(1); } while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null terminate */ } if (n < 0) { printf("read error\n"); exit(1); } }
60b580e7eaf22cc94d63c899eef381e768a5655b
[ "C" ]
3
C
lza93/Asn_1_cmpt471
39339774469aba7ae653d93c8cec492ae27cd59c
67795e7c2399782ae5158ed9280de3d2b13397dc